input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
common.assert_isclose(koila.run(a), c),
[
[LazyTensor(arr).min(), arr.min()],
[LazyTensor(arr).min(1)[0], arr.min(1)[0]],
[LazyTensor(arr).min(1)[1], arr.min(1)[1]],
],
)
def test_min_function() -> None:
arr = torch.randn(6, 7, 8)
brr = torch.randn(1, 7, 8)
la = typing.cast(Tensor, LazyTensor(arr))
lb = typing.cast(Tensor, LazyTensor(brr))
common.call(
lambda a, c: common.assert_isclose(koila.run(a), c),
[
[torch.min(la), torch.min(arr)],
[torch.min(la, 2)[0], torch.min(arr, 2)[0]],
[
torch.min(la, 1, keepdim=True).indices,
torch.min(arr, 1, keepdim=True).indices,
],
[torch.min(la, lb), torch.min(arr, brr)],
],
)
def test_max_method() -> None:
arr = torch.randn(6, 7, 8)
common.call(
lambda a, c: common.assert_isclose(koila.run(a), c),
[
[LazyTensor(arr).max(), arr.max()],
[LazyTensor(arr).max(1)[0], arr.max(1)[0]],
[LazyTensor(arr).max(1)[1], arr.max(1)[1]],
],
)
def test_max_function() -> None:
arr = torch.randn(6, 7, 8)
brr = torch.randn(1, 7, 8)
la = typing.cast(Tensor, LazyTensor(arr))
lb = typing.cast(Tensor, LazyTensor(brr))
common.call(
lambda a, c: common.assert_isclose(koila.run(a), c),
[
[torch.max(la), torch.max(arr)],
[torch.max(la, 2)[0], torch.max(arr, 2)[0]],
[
torch.max(la, 1, keepdim=True).indices,
torch.max(arr, 1, keepdim=True).indices,
],
[torch.max(la, lb), torch.max(arr, brr)],
],
)
def test_size_shape_method() -> None:
arr = torch.randn(11, 13)
la = LazyTensor(arr)
assert la.size() == la.shape == (11, 13)
assert la.size(0) == 11
assert la.size(1) == 13
def test_t_method() -> None:
arr = torch.randn(11, 13)
la = LazyTensor(arr)
assert la.T.size() == la.t().size() == (13, 11)
def test_t_function() -> None:
arr = torch.randn(11, 13)
la = typing.cast(Tensor, LazyTensor(arr))
assert torch.t(la).shape == (13, 11)
def test_dim_method() -> None:
arr = torch.randn(11, 13)
assert arr.ndim == arr.dim() == 2
arr = torch.randn(1, 2, 3, 4, 5)
assert arr.dim() == 5
def test_permute_method() -> None:
arr = torch.randn(2, 3, 4, 5, 6)
la = LazyTensor(arr)
assert la.permute(3, 4, 1, 2, 0).shape == (5, 6, 3, 4, 2)
assert la.permute(0, 1, 4, 3, 2).shape == (2, 3, 6, 5, 4)
def test_permute_function() -> None:
arr = torch.randn(2, 3, 4, 5, 6)
la = typing.cast(Tensor, LazyTensor(arr))
assert torch.permute(la, (3, 4, 1, 2, 0)).shape == (5, 6, 3, 4, 2)
assert torch.permute(la, (0, 1, 4, 3, 2)).shape == (2, 3, 6, 5, 4)
def test_transpose_method() -> None:
arr = torch.randn(2, 3, 4, 5, 6)
la = LazyTensor(arr)
assert la.transpose(3, 4).shape == (2, 3, 4, 6, 5)
assert la.transpose(0, 1).shape == (3, 2, 4, 5, 6)
assert la.transpose(0, 3).shape == (5, 3, 4, 2, 6)
def test_select_method() -> None:
arr = torch.randn(3, 4, 5)
sel = arr.select(1, 2)
assert isinstance(sel, Tensor)
assert not isinstance(sel, LazyTensor)
la = LazyTensor(arr)
lsel = la.select(1, 2)
assert not isinstance(lsel, Tensor)
assert isinstance(lsel, LazyTensor)
assert sel.size() == lsel.size() == (3, 5)
common.assert_isclose(lsel.run(), sel)
def test_select_function() -> None:
arr = torch.randn(3, 4, 5)
sel = torch.select(arr, 1, 2)
assert isinstance(sel, Tensor)
assert not isinstance(sel, LazyTensor)
la = typing.cast(Tensor, LazyTensor(arr))
lsel = torch.select(la, 1, 2)
assert not isinstance(lsel, Tensor)
assert isinstance(lsel, LazyTensor)
assert sel.size() == lsel.size() == (3, 5)
common.assert_isclose(lsel.run(), sel)
def test_index_select_method() -> None:
arr = torch.randn(3, 4, 5)
idx = torch.tensor([1, 2, 3])
sel = arr.index_select(1, idx)
assert isinstance(sel, Tensor)
assert not isinstance(sel, LazyTensor)
la = LazyTensor(arr)
lsel = la.index_select(1, idx)
assert not isinstance(lsel, Tensor)
assert isinstance(lsel, LazyTensor)
assert sel.size() == lsel.size() == (3, 3, 5)
common.assert_isclose(lsel.run(), sel)
def test_index_select_function() -> None:
arr = torch.randn(3, 4, 5)
idx = torch.tensor([1, 2, 3])
sel = torch.index_select(arr, 1, idx)
assert isinstance(sel, Tensor)
assert not isinstance(sel, LazyTensor)
la = typing.cast(Tensor, LazyTensor(arr))
lsel = torch.index_select(la, 1, idx)
assert not isinstance(lsel, Tensor)
assert isinstance(lsel, LazyTensor)
assert sel.size() == lsel.size() == (3, 3, 5)
common.assert_isclose(lsel.run(), sel)
def test_numel_method() -> None:
arr = torch.randn(2, 3, 4, 5, 6)
la = typing.cast(Tensor, LazyTensor(arr))
assert la.numel() == 2 * 3 * 4 * 5 * 6
arr = torch.randn(15, 19)
la = typing.cast(Tensor, LazyTensor(arr))
assert la.numel() == 15 * 19
def test_numel_function() -> None:
arr = torch.randn(2, 3, 4, 5, 6)
la = typing.cast(Tensor, LazyTensor(arr))
assert torch.numel(la) == 2 * 3 * 4 * 5 * 6
arr = torch.randn(15, 19)
la = typing.cast(Tensor, LazyTensor(arr))
assert torch.numel(la) == 15 * 19
def test_sigmoid_method() -> None:
arr = torch.randn(4, 5, 6)
common.call(
lambda a, c: common.assert_isclose(koila.run(a), c),
[[LazyTensor(arr).sigmoid(), torch.sigmoid(arr)]],
)
def test_sigmoid_function() -> None:
arr = torch.randn(4, 5, 6)
la = typing.cast(Tensor, arr)
common.call(
lambda a, c: common.assert_isclose(koila.run(a), c),
[[torch.sigmoid(la), torch.sigmoid(arr)]],
)
def test_sin_method() -> None:
common.call(
lambda a, c: common.assert_isclose(a.sin().item(), c),
[
[LazyTensor(torch.tensor(0)), 0],
[LazyTensor(torch.tensor(math.pi)), 0],
[LazyTensor(torch.tensor(math.pi / 2)), 1],
[LazyTensor(torch.tensor(3 * math.pi / 2)), -1],
[LazyTensor(torch.tensor(42.0)), math.sin(42)],
[LazyTensor(torch.tensor(-75.0)), math.sin(-75)],
],
)
def test_sin_function() -> None:
common.call(
lambda a, c: common.assert_isclose(torch.sin(a).item(), c),
[
[LazyTensor(torch.tensor(0)), 0],
[LazyTensor(torch.tensor(math.pi)), 0],
[LazyTensor(torch.tensor(math.pi / 2)), 1],
[LazyTensor(torch.tensor(3 * math.pi / 2)), -1],
[LazyTensor(torch.tensor(42.0)), math.sin(42)],
[LazyTensor(torch.tensor(-75.0)), math.sin(-75)],
],
)
def test_cos_method() -> None:
common.call(
lambda a, c: common.assert_isclose(a.cos().item(), c),
[
[LazyTensor(torch.tensor(0)), 1],
[LazyTensor(torch.tensor(math.pi)), -1],
[LazyTensor(torch.tensor(math.pi / 2)), 0],
[LazyTensor(torch.tensor(3 * math.pi / 2)), 0],
[LazyTensor(torch.tensor(27.0)), math.cos(27)],
[LazyTensor(torch.tensor(-14.0)), math.cos(-14)],
],
)
def test_cos_function() -> None:
common.call(
lambda a, c: common.assert_isclose(torch.cos(a).item(), c),
[
[LazyTensor(torch.tensor(0)), 1],
[LazyTensor(torch.tensor(math.pi)), -1],
[LazyTensor(torch.tensor(math.pi / 2)), 0],
[LazyTensor(torch.tensor(3 * math.pi / 2)), 0],
[LazyTensor(torch.tensor(27.0)), math.cos(27)],
[LazyTensor(torch.tensor(-14.0)), math.cos(-14)],
],
)
def test_tan_method() -> None:
common.call(
lambda a, c: common.assert_isclose(a.tan().item(), c),
[
[LazyTensor(torch.tensor(0)), 0],
[LazyTensor(torch.tensor(math.pi)), 0],
[LazyTensor(torch.tensor(99.0)), math.tan(99)],
[LazyTensor(torch.tensor(-4.0)), math.tan(-4)],
],
)
def test_tan_function() -> None:
common.call(
lambda a, c: common.assert_isclose(torch.tan(a).item(), c),
[
[LazyTensor(torch.tensor(0)), 0],
[LazyTensor(torch.tensor(math.pi)), 0],
[LazyTensor(torch.tensor(99.0)), math.tan(99)],
[LazyTensor(torch.tensor(-4.0)), math.tan(-4)],
],
)
def test_asin_method() -> None:
common.call(
lambda a, c: common.assert_isclose(a.asin().item(), c),
[
[LazyTensor(torch.tensor(n)), math.asin(n)]
for n in np.linspace(-1, 1).tolist()
],
)
def test_asin_function() -> None:
common.call(
lambda a, c: common.assert_isclose(torch.asin(a).item(), c),
[
[LazyTensor(torch.tensor(n)), math.asin(n)]
for n in np.linspace(-1, 1).tolist()
],
)
def test_acos_method() -> None:
common.call(
lambda a, c: common.assert_isclose(a.acos().item(), c),
[
[LazyTensor(torch.tensor(n)), math.acos(n)]
for n in np.linspace(-1, 1).tolist()
],
)
def test_acos_function() -> None:
common.call(
lambda a, c: common.assert_isclose(torch.acos(a).item(), c),
[
[LazyTensor(torch.tensor(n)), math.acos(n)]
for n in np.linspace(-1, 1).tolist()
],
)
def test_atan_method() -> None:
common.call(
lambda a, c: common.assert_isclose(a.atan().item(), c),
[
[LazyTensor(torch.tensor(99.0)), math.atan(99)],
[LazyTensor(torch.tensor(-4.0)), math.atan(-4)],
[LazyTensor(torch.tensor(-6.0)), math.atan(-6)],
[LazyTensor(torch.tensor(242.0)), math.atan(242)],
],
)
def test_atan_function() -> None:
common.call(
lambda a, c: common.assert_isclose(torch.atan(a).item(), c),
[
[LazyTensor(torch.tensor(99.0)), math.atan(99)],
[LazyTensor(torch.tensor(-4.0)), math.atan(-4)],
[LazyTensor(torch.tensor(-6.0)), math.atan(-6)],
[LazyTensor(torch.tensor(242.0)), math.atan(242)],
],
)
def test_sinh_method() -> None:
common.call(
lambda a, c: common.assert_isclose(a.sinh().item(), c),
[
[LazyTensor(torch.tensor(n)), math.sinh(n)]
for n in np.linspace(-1, 1).tolist()
],
)
def test_sinh_function() -> None:
common.call(
lambda a, c: common.assert_isclose(torch.sinh(a).item(), c),
[
[LazyTensor(torch.tensor(n)), math.sinh(n)]
for n in np.linspace(-1, 1).tolist()
],
)
def test_cosh_method() -> None:
common.call(
lambda a, c: common.assert_isclose(a.cosh().item(), c),
[
[LazyTensor(torch.tensor(n)), math.cosh(n)]
for n in np.linspace(-1, 1).tolist()
],
)
def test_cosh_function() -> None:
common.call(
lambda a, c: common.assert_isclose(torch.cosh(a).item(), c),
[
[LazyTensor(torch.tensor(n)), math.cosh(n)]
for n in np.linspace(-1, 1).tolist()
],
)
def test_tanh_method() -> None:
common.call(
lambda a, c: common.assert_isclose(a.tanh().item(), c),
[[LazyTensor(torch.tensor(n)), math.tanh(n)] for n in np.linspace(-10, 10)],
)
def test_tanh_function() -> None:
common.call(
lambda a, c: common.assert_isclose(torch.tanh(a).item(), c),
[[LazyTensor(torch.tensor(n)), math.tanh(n)] for n in np.linspace(-10, 10)],
)
def test_asinh_method() -> None:
common.call(
lambda a, c: common.assert_isclose(a.asinh().item(), c),
[
[LazyTensor(torch.tensor(199.0)), math.asinh(199)],
[LazyTensor(torch.tensor(-241.0)), math.asinh(-241)],
[LazyTensor(torch.tensor(-9.0)), math.asinh(-9)],
[LazyTensor(torch.tensor(0.0)), math.asinh(0)],
],
)
def test_asinh_function() -> None:
common.call(
lambda a, c: common.assert_isclose(torch.asinh(a).item(), c),
[
[LazyTensor(torch.tensor(199.0)), math.asinh(199)],
[LazyTensor(torch.tensor(-241.0)), math.asinh(-241)],
[LazyTensor(torch.tensor(-9.0)), math.asinh(-9)],
[LazyTensor(torch.tensor(0.0)), math.asinh(0)],
],
)
def test_acosh_method() -> None:
common.call(
lambda a, c: common.assert_isclose(a.acosh().item(), c),
[
[LazyTensor(torch.tensor(14.0)), math.acosh(14)],
[LazyTensor(torch.tensor(2.0)), math.acosh(2)],
[LazyTensor(torch.tensor(1.0)), math.acosh(1)],
[LazyTensor(torch.tensor(65.0)), math.acosh(65)],
],
)
def test_acosh_function() -> None:
common.call(
lambda a, c: common.assert_isclose(torch.acosh(a).item(), c),
[
[LazyTensor(torch.tensor(14.0)), math.acosh(14)],
[LazyTensor(torch.tensor(2.0)), math.acosh(2)],
[LazyTensor(torch.tensor(1.0)), math.acosh(1)],
[LazyTensor(torch.tensor(65.0)), math.acosh(65)],
],
)
def test_atanh_method() -> None:
common.call(
lambda a, c: common.assert_isclose(a.atanh().item(), c),
[
[LazyTensor(torch.tensor(n)), math.atanh(n)]
for n in np.linspace(-0.99, 0.99, endpoint=False).tolist()
],
)
def test_atanh_function() -> None:
common.call(
lambda a, c: common.assert_isclose(torch.atanh(a).item(), c),
[
[LazyTensor(torch.tensor(n)), math.atanh(n)]
for n in np.linspace(-0.99, 0.99, endpoint=False).tolist()
],
)
def test_run_method() -> None:
random = torch.randn(3, 4, 5, 6)
common.call(
lambda a, b: common.assert_isclose(a.run(), b), [[LazyTensor(random), random]]
)
def test_torch_method() -> None:
random = torch.randn(3, 4, 5, 6)
common.call(
lambda a, b: common.assert_isclose(a.torch(), b), [[LazyTensor(random), random]]
)
def test_numpy_method() -> None:
random = torch.randn(3, 4, 5, 6)
common.call(
lambda a, b: common.assert_isclose(a.numpy(), b.numpy()),
[[LazyTensor(random), random]],
)
def test_pad_function() -> None:
tensor = torch.randn(3, 4, 5, 6)
padded = F.pad(tensor, (2, 3, 0, 1), mode="reflect")
assert isinstance(padded, Tensor)
assert not isinstance(padded, LazyTensor)
la = typing.cast(Tensor, LazyTensor(tensor))
lazy_padded = F.pad(la, (2, 3, 0, 1), mode="reflect")
assert not isinstance(lazy_padded, Tensor)
assert isinstance(lazy_padded, LazyTensor)
assert padded.shape == lazy_padded.shape
common.assert_isclose(lazy_padded.run(), padded)
def test_buffer_sizes() -> None:
a = torch.randn(4, 5, 6)
la = LazyTensor(a)
assert a.numel() == la.numel() == la.buffer_numel()[1]
b = torch.randn(4, 5, 1)
lb = LazyTensor(b)
assert b.numel() == lb.numel() == lb.buffer_numel()[1]
lc = typing.cast(LazyTensor, la + lb)
assert | |
+ random() * 2) * choice([1, -1])
ball = vector(0, 0)
aim = vector(value(), value())
state = {1: 0, 2: 0}
def move(player, change):
"Move player position by change."
state[player] += change
def rectangle(x, y, width, height):
"Draw rectangle at (x, y) with given width and height."
up()
goto(x, y)
down()
begin_fill()
for count in range(2):
forward(width)
left(90)
forward(height)
left(90)
end_fill()
def draw():
"Draw game and move pong ball."
clear()
rectangle(-200, state[1], 10, 50)
rectangle(190, state[2], 10, 50)
ball.move(aim)
x = ball.x
y = ball.y
up()
goto(x, y)
dot(10)
update()
if y < -200 or y > 200:
aim.y = -aim.y
if x < -185:
low = state[1]
high = state[1] + 50
if low <= y <= high:
aim.x = -aim.x
else:
return
if x > 185:
low = state[2]
high = state[2] + 50
if low <= y <= high:
aim.x = -aim.x
else:
return
ontimer(draw, 50)
setup(420, 420, 370, 0)
hideturtle()
tracer(False)
listen()
onkey(lambda: move(1, 40), 'w')
onkey(lambda: move(1, -40), 's')
onkey(lambda: move(2, 40), 'Up')
onkey(lambda: move(2, -40), 'Down')
draw()
done()
elif command == "spinner":
from turtle import *
state = {'turn': 0}
val = float(input("Enter speed (in number): "))
def spinner():
clear()
angle = state['turn']/10
right(angle)
forward(100)
dot(120, 'red')
back(100)
right(120)
forward(100)
dot(120, 'purple')
back(100)
right(120)
forward(100)
dot(120, 'blue')
back(100)
right(120)
update()
def animate():
if state['turn']>0:
state['turn']-=1
spinner()
ontimer(animate, 20)
def flick():
state['turn']+=val
setup(420, 420, 370, 0)
hideturtle()
tracer(False)
width(20)
onkey(flick, 'Right')
onkey(flick, 'Left')
onkey(flick, 'Up')
onkey(flick, 'Down')
onkey(flick, 'space')
onkey(flick, 'w')
onkey(flick, 'a')
onkey(flick, 's')
onkey(flick, 'd')
listen()
animate()
done()
elif command == "version":
print("PY-DOS version-8")
elif command == "randomnumber":
print("Generates a random number from 0 to 9")
import random
print(random.randint(0,9))
elif command == "browser":
# importing required libraries
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtWebEngineWidgets import *
from PyQt5.QtPrintSupport import *
import os
import sys
# creating main window class
class MainWindow(QMainWindow):
# constructor
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
# creating a QWebEngineView
self.browser = QWebEngineView()
# setting default browser url as google
self.browser.setUrl(QUrl("file:///C://My Websites/browser.html"))
# adding action when url get changed
self.browser.urlChanged.connect(self.update_urlbar)
# adding action when loading is finished
self.browser.loadFinished.connect(self.update_title)
# set this browser as central widget or main window
self.setCentralWidget(self.browser)
# creating a status bar object
self.status = QStatusBar()
# adding status bar to the main window
self.setStatusBar(self.status)
# creating QToolBar for navigation
navtb = QToolBar("Navigation")
# adding this tool bar tot he main window
self.addToolBar(navtb)
# adding actions to the tool bar
# creating a action for back
back_btn = QAction("Back", self)
# setting status tip
back_btn.setStatusTip("Back to previous page")
# adding action to the back button
# making browser go back
back_btn.triggered.connect(self.browser.back)
# adding this action to tool bar
navtb.addAction(back_btn)
# similarly for forward action
next_btn = QAction("Forward", self)
next_btn.setStatusTip("Forward to next page")
# adding action to the next button
# making browser go forward
next_btn.triggered.connect(self.browser.forward)
navtb.addAction(next_btn)
# similarly for reload action
reload_btn = QAction("Reload", self)
reload_btn.setStatusTip("Reload page")
# adding action to the reload button
# making browser to reload
reload_btn.triggered.connect(self.browser.reload)
navtb.addAction(reload_btn)
# similarly for home action
home_btn = QAction("Home", self)
home_btn.setStatusTip("Go home")
home_btn.triggered.connect(self.navigate_home)
navtb.addAction(home_btn)
# adding a separator in the tool bar
navtb.addSeparator()
# creating a line edit for the url
self.urlbar = QLineEdit()
# adding action when return key is pressed
self.urlbar.returnPressed.connect(self.navigate_to_url)
# adding this to the tool bar
navtb.addWidget(self.urlbar)
# adding stop action to the tool bar
stop_btn = QAction("Stop", self)
stop_btn.setStatusTip("Stop loading current page")
# adding action to the stop button
# making browser to stop
stop_btn.triggered.connect(self.browser.stop)
navtb.addAction(stop_btn)
# showing all the components
self.show()
# method for updating the title of the window
def update_title(self):
title = self.browser.page().title()
self.setWindowTitle("% s - PY Browser" % title)
# method called by the home action
def navigate_home(self):
# open the google
self.browser.setUrl(QUrl("msn.com"))
# method called by the line edit when return key is pressed
def navigate_to_url(self):
# getting url and converting it to QUrl objetc
q = QUrl(self.urlbar.text())
# if url is scheme is blank
if q.scheme() == "":
# set url scheme to html
q.setScheme("http")
# set the url to the browser
self.browser.setUrl(q)
# method for updating url
# this method is called by the QWebEngineView object
def update_urlbar(self, q):
# setting text to the url bar
self.urlbar.setText(q.toString())
# setting cursor position of the url bar
self.urlbar.setCursorPosition(0)
# creating a pyQt5 application
app = QApplication(sys.argv)
# setting name to the application
app.setApplicationName("PY Browser")
# creating a main window object
window = MainWindow()
# loop
app.exec_()
exit_browser = input("Press enter to exit")
elif command == "age calc":
import datetime
print("This program is written in Python for PY-DOS!!!")
birth_year = int(input("Enter your year of birth: "))
birth_month = int(input("Enter your month of birth: "))
birth_day = int(input("Enter your day of birth: "))
current_year = datetime.date.today().year
current_month = datetime.date.today().month
current_day = datetime.date.today().day
age_year = abs(current_year - birth_year)
age_month = abs(current_month - birth_month)
age_day = abs(current_day - birth_day)
print("Your age is " , age_year , " Years," , age_month , " Months and" , age_day , " Days")
elif command == "programver":
print(" Calculator Suite: 2.5 Unicorn ")
print(" Calc+ 1.00")
print(" Calc- 1.00")
print(" Calc* 1.00")
print(" Calc/ 2.5 Unicorn")
print(" CalcSQRT 1.00")
print(" RandomNumber 1.00")
print(" Chat 3.01")
print(" PY Browser 1.00")
print(" Table 1.00")
print(" Calendar 1.00")
print(" Date and Time Manager 1.00")
print(" NeoCommand 8.00")
elif command == "py-dos":
print(" PY-DOS Version Version History")
print(" PY-DOS 1")
print(" PY-DOS 2")
print(" PY-DOS 2.5")
print(" PY-DOS 3")
print(" PY-DOS 3.1")
print(" PY-DOS 4")
print(" PY-DOS 5")
print(" PY-DOS 6")
print(" PY-DOS 8 ---> Current version")
elif command == "microsoft":
print("Microsoft Corporation is an American multinational technology company with headquarters in Redmond, Washington. It develops, manufactures, licenses, supports, and sells computer software, consumer electronics, personal computers, and related services. Its best known software products are the Microsoft Windows line of operating systems, the Microsoft Office suite, and the Internet Explorer and Edge web browsers. Its flagship hardware products are the Xbox video game consoles and the Microsoft Surface lineup of touchscreen personal computers. Microsoft ranked No. 21 in the 2020 Fortune 500 rankings of the largest United States corporations by total revenue; it was the world's largest software maker by revenue as of 2016. It is considered one of the Big Five companies in the U.S. information technology industry, along with Google, Apple, Amazon, and Facebook.")
elif command == "google":
print("Google LLC is an American multinational technology company that specializes in Internet-related services and products, which include online advertising technologies, a search engine, cloud computing, software, and hardware. It is considered one of the big four Internet stocks along with Amazon, Facebook, and Apple.")
elif command == "apple":
print("Apple Inc. is an American multinational technology company headquartered in Cupertino, California, that designs, develops, and sells consumer electronics, computer software, and online services. It is considered one of the Big Five companies in the U.S. information technology industry, along with Amazon, Google, Microsoft, and Facebook. It is one of the most popular smartphone and tablet companies in the world.")
elif command == "facebook":
print("Facebook is a for-profit corporation and online social networking service based in Menlo Park, California, United States. The Facebook website was launched on February 4, 2004, by <NAME>, along with fellow Harvard College students and roommates, <NAME>, <NAME>, <NAME>, and <NAME>.")
elif command == "amazon":
print("Amazon.com, Inc. is an American multinational technology company which focuses on e-commerce, cloud computing, digital streaming, and artificial intelligence. It is one of the Big Five companies in the U.S. information technology industry, along with Google, Apple, Microsoft, and Facebook. The company has been referred to as one of the most influential economic and cultural forces in the world, as well as the world's most valuable brand.")
elif command == "newupdates":
print(" Expected changes to come in next version of PY-DOS")
print(" An updated new calculator in PY-DOS 8 --> Under Developent")
print(" New Easter-Egg command --> May Come")
elif command == "table":
print("This program is written in Python!!!")
num = int(input("Enter the number : "))
i = 1
print("Here you go!!!")
while i<=10:
num = num * 1
print(num,'x',i,'=',num*i)
i += 1
elif command == "who made you":
print("<NAME>!!!")
elif command == "who made you?":
print("<NAME>!!!")
elif command == "do you know gautham":
print("Oh, yeah, he created me!!")
elif command == "do you know gautham?":
print("Oh, yeah, he created me!!")
elif command == "do you know gautham nair":
print("Oh, yeah, he created me!!")
elif command == "do you know gautham nair?":
print("Oh, yeah, he created me!!")
elif command == "do you know zanvok corporation":
print("Sure, I do!!...A great company...!!!")
elif command == "do you know zanvok corporation?":
print("Sure, I do!!...A great company...!!!")
elif command == "do you know zanvok":
print("Sure!! Zanvok Corporation is awesome!!")
elif command == "do you know zanvok?":
print("Sure!! Zanvok Corporation is awesome!!")
elif command == "neofetch":
print("---------------------------------------------")
print("---------------------------------------------")
print("---------------------------------------------")
print("---------------------------------------------")
print("********** **********")
print(" ********** **********")
print(" ********** **********")
print(" ********** **********")
print("********** **********")
print(" 8")
print("---------------------------------------------")
print("---------------------------------------------")
print("---------------------------------------------")
print("---------------------------------------------")
print("PY-DOS ")
print("-----------------")
print("Version 8")
print("Mutated Monkey")
print("------------------------------------")
print("Written in Python")
print("---------------------------------------")
print("Zanvok Corporation")
elif command == "help":
print("Commands for using PY-DOS")
print(" calc+ - addition calculator")
print(" calc- - subtraction calculator")
print(" calc/ - division calculator")
print(" calc* - multiplication calculator")
print(" calcsqrt - square root calculator")
print(" age calc - age calculator")
print(" table - display table")
print(" py-dos - PY-DOS Version History")
print(" browser - starts PY Browser, a PyQt-Chromium based browser")
print(" about - about PY-DOS")
print(" status - PY-DOS Update and Base Version Details")
print(" credits - display credits")
print(" user - display user information")
print(" change username - changes your username")
print(" date - displays date")
print(" time - display time")
print(" date and time - display date and time")
print(" chat - start a chat with PY-DOS")
print(" clock - displays clock, inaccessible sometimes")
print(" calendar | |
u('\u5e7f\u4e1c\u7701\u6cb3\u6e90\u5e02')},
'861581929':{'en': 'Zhaoqing, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u8087\u5e86\u5e02')},
'86158193':{'en': 'Zhongshan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e2d\u5c71\u5e02')},
'861581930':{'en': 'Zhaoqing, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u8087\u5e86\u5e02')},
'861581931':{'en': 'Zhaoqing, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u8087\u5e86\u5e02')},
'861581932':{'en': 'Zhaoqing, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u8087\u5e86\u5e02')},
'86158194':{'en': 'Zhuhai, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u73e0\u6d77\u5e02')},
'86158195':{'en': 'Jieyang, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u63ed\u9633\u5e02')},
'861581950':{'en': 'Yunfu, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e91\u6d6e\u5e02')},
'861581951':{'en': 'Yunfu, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e91\u6d6e\u5e02')},
'861581952':{'en': 'Yunfu, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e91\u6d6e\u5e02')},
'861581953':{'en': 'Yunfu, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e91\u6d6e\u5e02')},
'86158196':{'en': 'Jieyang, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u63ed\u9633\u5e02')},
'86158197':{'en': 'Jiangmen, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6c5f\u95e8\u5e02')},
'861581980':{'en': 'Zhuhai, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u73e0\u6d77\u5e02')},
'861581981':{'en': 'Zhuhai, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u73e0\u6d77\u5e02')},
'861581982':{'en': 'Zhuhai, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u73e0\u6d77\u5e02')},
'861581983':{'en': 'Zhuhai, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u73e0\u6d77\u5e02')},
'861581984':{'en': 'Zhuhai, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u73e0\u6d77\u5e02')},
'861581985':{'en': 'Huizhou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u60e0\u5dde\u5e02')},
'861581986':{'en': 'Huizhou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u60e0\u5dde\u5e02')},
'861581987':{'en': 'Huizhou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u60e0\u5dde\u5e02')},
'861581988':{'en': 'Huizhou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u60e0\u5dde\u5e02')},
'861581989':{'en': 'Huizhou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u60e0\u5dde\u5e02')},
'861581990':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6c5f\u95e8\u5e02')},
'861581991':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6c5f\u95e8\u5e02')},
'861581992':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6c5f\u95e8\u5e02')},
'861581993':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6c5f\u95e8\u5e02')},
'861581994':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6c5f\u95e8\u5e02')},
'861581995':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u4e2d\u5c71\u5e02')},
'861581996':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u4e2d\u5c71\u5e02')},
'861581997':{'en': 'Zhongshan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e2d\u5c71\u5e02')},
'861581998':{'en': 'Zhongshan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e2d\u5c71\u5e02')},
'861581999':{'en': 'Zhongshan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e2d\u5c71\u5e02')},
'861582000':{'en': 'Jinan, Shandong', 'zh': u('\u5c71\u4e1c\u7701\u6d4e\u5357\u5e02')},
'861582001':{'en': '<NAME>', 'zh': u('\u5c71\u4e1c\u7701\u6d4e\u5357\u5e02')},
'861582002':{'en': 'Qingdao, Shandong', 'zh': u('\u5c71\u4e1c\u7701\u9752\u5c9b\u5e02')},
'861582003':{'en': 'Qingdao, Shandong', 'zh': u('\u5c71\u4e1c\u7701\u9752\u5c9b\u5e02')},
'861582004':{'en': 'Liaocheng, Shandong', 'zh': u('\u5c71\u4e1c\u7701\u804a\u57ce\u5e02')},
'861582005':{'en': 'Yantai, Shandong', 'zh': u('\u5c71\u4e1c\u7701\u70df\u53f0\u5e02')},
'861582006':{'en': 'Dezhou, Shandong', 'zh': u('\u5c71\u4e1c\u7701\u5fb7\u5dde\u5e02')},
'861582007':{'en': '<NAME>', 'zh': u('\u5c71\u4e1c\u7701\u6d4e\u5b81\u5e02')},
'861582008':{'en': '<NAME>', 'zh': u('\u5c71\u4e1c\u7701\u9752\u5c9b\u5e02')},
'861582009':{'en': '<NAME>', 'zh': u('\u5c71\u4e1c\u7701\u6d4e\u5357\u5e02')},
'861582010':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u97f6\u5173\u5e02')},
'861582011':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u97f6\u5173\u5e02')},
'861582012':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u97f6\u5173\u5e02')},
'861582013':{'en': 'Chaozhou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6f6e\u5dde\u5e02')},
'861582014':{'en': 'Chaozhou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6f6e\u5dde\u5e02')},
'861582015':{'en': 'Chaozhou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6f6e\u5dde\u5e02')},
'861582016':{'en': 'Heyuan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6cb3\u6e90\u5e02')},
'861582017':{'en': 'Maoming, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u8302\u540d\u5e02')},
'861582018':{'en': 'Maoming, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u8302\u540d\u5e02')},
'861582019':{'en': 'Maoming, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u8302\u540d\u5e02')},
'86158202':{'en': 'Guangzhou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u5e7f\u5dde\u5e02')},
'861582030':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6c55\u5c3e\u5e02')},
'861582031':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6c55\u5c3e\u5e02')},
'861582032':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6e05\u8fdc\u5e02')},
'861582033':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6e05\u8fdc\u5e02')},
'861582034':{'en': 'Yangjiang, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u9633\u6c5f\u5e02')},
'861582035':{'en': 'Meizhou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6885\u5dde\u5e02')},
'861582036':{'en': 'Yangjiang, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u9633\u6c5f\u5e02')},
'861582037':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u8087\u5e86\u5e02')},
'861582038':{'en': 'Zhaoqing, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u8087\u5e86\u5e02')},
'861582039':{'en': 'Meizhou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6885\u5dde\u5e02')},
'86158204':{'en': 'Shenzhen, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6df1\u5733\u5e02')},
'861582050':{'en': 'Zhongshan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e2d\u5c71\u5e02')},
'861582051':{'en': 'Zhongshan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e2d\u5c71\u5e02')},
'861582052':{'en': 'Zhongshan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e2d\u5c71\u5e02')},
'861582053':{'en': 'Zhongshan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e2d\u5c71\u5e02')},
'861582054':{'en': 'Zh<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u4e2d\u5c71\u5e02')},
'861582055':{'en': 'Zhuhai, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u73e0\u6d77\u5e02')},
'861582056':{'en': 'Zhuhai, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u73e0\u6d77\u5e02')},
'861582057':{'en': 'Zhuhai, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u73e0\u6d77\u5e02')},
'861582058':{'en': 'Zhuhai, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u73e0\u6d77\u5e02')},
'861582059':{'en': 'Zhuhai, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u73e0\u6d77\u5e02')},
'86158206':{'en': 'Foshan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4f5b\u5c71\u5e02')},
'861582070':{'en': 'Huizhou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u60e0\u5dde\u5e02')},
'861582071':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u60e0\u5dde\u5e02')},
'861582072':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u60e0\u5dde\u5e02')},
'861582073':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u60e0\u5dde\u5e02')},
'861582074':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u60e0\u5dde\u5e02')},
'861582075':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6df1\u5733\u5e02')},
'861582076':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6df1\u5733\u5e02')},
'861582077':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6df1\u5733\u5e02')},
'861582078':{'en': 'Shenzhen, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6df1\u5733\u5e02')},
'861582079':{'en': 'Shenzhen, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6df1\u5733\u5e02')},
'86158208':{'en': 'Dongguan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e1c\u839e\u5e02')},
'86158209':{'en': 'Dongguan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e1c\u839e\u5e02')},
'8615821':{'en': 'Shanghai', 'zh': u('\u4e0a\u6d77\u5e02')},
'8615822':{'en': 'Tianjin', 'zh': u('\u5929\u6d25\u5e02')},
'8615823':{'en': 'Chongqing', 'zh': u('\u91cd\u5e86\u5e02')},
'86158240':{'en': 'Taizhou, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u53f0\u5dde\u5e02')},
'86158241':{'en': 'Hangzhou, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u676d\u5dde\u5e02')},
'86158242':{'en': 'Ningbo, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u5b81\u6ce2\u5e02')},
'86158243':{'en': 'Jiaxing, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u5609\u5174\u5e02')},
'86158244':{'en': 'Hangzhou, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u676d\u5dde\u5e02')},
'86158245':{'en': 'Ningbo, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u5b81\u6ce2\u5e02')},
'86158246':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u5b89\u9633\u5e02')},
'86158247':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u5546\u4e18\u5e02')},
'86158248':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u90d1\u5dde\u5e02')},
'86158249':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u6d1b\u9633\u5e02')},
'86158250':{'en': '<NAME>', 'zh': u('\u4e91\u5357\u7701\u66f2\u9756\u5e02')},
'861582500':{'en': 'Lincang, Yunnan', 'zh': u('\u4e91\u5357\u7701\u4e34\u6ca7\u5e02')},
'861582501':{'en': 'L<NAME>', 'zh': u('\u4e91\u5357\u7701\u4e34\u6ca7\u5e02')},
'861582510':{'en': '<NAME>', 'zh': u('\u4e91\u5357\u7701\u66f2\u9756\u5e02')},
'861582511':{'en': '<NAME>', 'zh': u('\u4e91\u5357\u7701\u66f2\u9756\u5e02')},
'861582512':{'en': '<NAME>', 'zh': u('\u4e91\u5357\u7701\u7389\u6eaa\u5e02')},
'861582513':{'en': '<NAME>', 'zh': u('\u4e91\u5357\u7701\u7389\u6eaa\u5e02')},
'861582514':{'en': '<NAME>', 'zh': u('\u4e91\u5357\u7701\u7389\u6eaa\u5e02')},
'861582515':{'en': '<NAME>', 'zh': u('\u4e91\u5357\u7701\u7389\u6eaa\u5e02')},
'861582516':{'en': '<NAME>', 'zh': u('\u4e91\u5357\u7701\u695a\u96c4\u5f5d\u65cf\u81ea\u6cbb\u5dde')},
'861582517':{'en': '<NAME>', 'zh': u('\u4e91\u5357\u7701\u5927\u7406\u767d\u65cf\u81ea\u6cbb\u5dde')},
'861582518':{'en': '<NAME>', 'zh': u('\u4e91\u5357\u7701\u7ea2\u6cb3\u54c8\u5c3c\u65cf\u5f5d\u65cf\u81ea\u6cbb\u5dde')},
'861582519':{'en': '<NAME>', 'zh': u('\u4e91\u5357\u7701\u7ea2\u6cb3\u54c8\u5c3c\u65cf\u5f5d\u65cf\u81ea\u6cbb\u5dde')},
'861582520':{'en': '<NAME>', 'zh': u('\u4e91\u5357\u7701\u7ea2\u6cb3\u54c8\u5c3c\u65cf\u5f5d\u65cf\u81ea\u6cbb\u5dde')},
'861582521':{'en': '<NAME>', 'zh': u('\u4e91\u5357\u7701\u7ea2\u6cb3\u54c8\u5c3c\u65cf\u5f5d\u65cf\u81ea\u6cbb\u5dde')},
'861582522':{'en': 'H<NAME>', 'zh': u('\u4e91\u5357\u7701\u7ea2\u6cb3\u54c8\u5c3c\u65cf\u5f5d\u65cf\u81ea\u6cbb\u5dde')},
'861582523':{'en': 'H<NAME>', 'zh': u('\u4e91\u5357\u7701\u7ea2\u6cb3\u54c8\u5c3c\u65cf\u5f5d\u65cf\u81ea\u6cbb\u5dde')},
'861582524':{'en': '<NAME>', 'zh': u('\u4e91\u5357\u7701\u7ea2\u6cb3\u54c8\u5c3c\u65cf\u5f5d\u65cf\u81ea\u6cbb\u5dde')},
'861582525':{'en': '<NAME>', 'zh': u('\u4e91\u5357\u7701\u6606\u660e\u5e02')},
'861582526':{'en': '<NAME>', 'zh': u('\u4e91\u5357\u7701\u6606\u660e\u5e02')},
'861582527':{'en': '<NAME>', 'zh': u('\u4e91\u5357\u7701\u6606\u660e\u5e02')},
'861582528':{'en': '<NAME>', 'zh': u('\u4e91\u5357\u7701\u6606\u660e\u5e02')},
'861582529':{'en': '<NAME>', 'zh': u('\u4e91\u5357\u7701\u6606\u660e\u5e02')},
'861582530':{'en': '<NAME>', 'zh': u('\u5b81\u590f\u94f6\u5ddd\u5e02')},
'861582531':{'en': '<NAME>', 'zh': u('\u5b81\u590f\u94f6\u5ddd\u5e02')},
'861582532':{'en': '<NAME>', 'zh': u('\u5b81\u590f\u77f3\u5634\u5c71\u5e02')},
'861582533':{'en': 'Wuzhong, Ningxia', 'zh': u('\u5b81\u590f\u5434\u5fe0\u5e02')},
'861582534':{'en': '<NAME>', 'zh': u('\u5b81\u590f\u56fa\u539f\u5e02')},
'861582535':{'en': 'Zhongwei, Ningxia', 'zh': u('\u5b81\u590f\u4e2d\u536b\u5e02')},
'861582536':{'en': 'Shizuishan, Ningxia', 'zh': u('\u5b81\u590f\u77f3\u5634\u5c71\u5e02')},
'861582537':{'en': 'Yinchuan, Ningxia', 'zh': u('\u5b81\u590f\u94f6\u5ddd\u5e02')},
'861582538':{'en': 'Yinchuan, Ningxia', 'zh': u('\u5b81\u590f\u94f6\u5ddd\u5e02')},
'861582539':{'en': 'Guyuan, Ningxia', 'zh': u('\u5b81\u590f\u56fa\u539f\u5e02')},
'861582540':{'en': 'Wenzhou, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u6e29\u5dde\u5e02')},
'861582541':{'en': 'Wenzhou, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u6e29\u5dde\u5e02')},
'861582542':{'en': 'Wenzhou, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u6e29\u5dde\u5e02')},
'861582543':{'en': 'Wenzhou, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u6e29\u5dde\u5e02')},
'861582544':{'en': 'Wenzhou, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u6e29\u5dde\u5e02')},
'861582545':{'en': 'Taizhou, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u53f0\u5dde\u5e02')},
'861582546':{'en': 'Taizhou, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u53f0\u5dde\u5e02')},
'861582547':{'en': 'Taizhou, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u53f0\u5dde\u5e02')},
'861582548':{'en': 'Taizhou, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u53f0\u5dde\u5e02')},
'861582549':{'en': 'Taizhou, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u53f0\u5dde\u5e02')},
'861582550':{'en': 'Hangzhou, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u676d\u5dde\u5e02')},
'861582551':{'en': 'Hangzhou, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u676d\u5dde\u5e02')},
'861582552':{'en': 'Hangzhou, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u676d\u5dde\u5e02')},
'861582553':{'en': 'Hangzhou, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u676d\u5dde\u5e02')},
'861582554':{'en': 'Hangzhou, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u676d\u5dde\u5e02')},
'861582555':{'en': 'Ningbo, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u5b81\u6ce2\u5e02')},
'861582556':{'en': 'Ningbo, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u5b81\u6ce2\u5e02')},
'861582557':{'en': 'Ningbo, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u5b81\u6ce2\u5e02')},
'861582558':{'en': 'Ningbo, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u5b81\u6ce2\u5e02')},
'861582559':{'en': 'Ningbo, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u5b81\u6ce2\u5e02')},
'86158256':{'en': 'Wenzhou, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u6e29\u5dde\u5e02')},
'861582570':{'en': 'Jiaxing, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u5609\u5174\u5e02')},
'861582571':{'en': 'Jiaxing, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u5609\u5174\u5e02')},
'861582572':{'en': 'Jiaxing, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u5609\u5174\u5e02')},
'861582573':{'en': 'Jiaxing, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u5609\u5174\u5e02')},
'861582574':{'en': 'Jiaxing, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u5609\u5174\u5e02')},
'861582575':{'en': 'Jinhua, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u91d1\u534e\u5e02')},
'861582576':{'en': '<NAME>hejiang', 'zh': u('\u6d59\u6c5f\u7701\u91d1\u534e\u5e02')},
'861582577':{'en': 'Jinhua, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u91d1\u534e\u5e02')},
'861582578':{'en': 'Jinhua, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u91d1\u534e\u5e02')},
'861582579':{'en': 'Jinhua, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u91d1\u534e\u5e02')},
'861582580':{'en': '<NAME>', 'zh': u('\u7518\u8083\u7701\u5929\u6c34\u5e02')},
'861582581':{'en': '<NAME>', 'zh': u('\u7518\u8083\u7701\u5b9a\u897f\u5e02')},
'861582582':{'en': '<NAME>', 'zh': u('\u7518\u8083\u7701\u5b9a\u897f\u5e02')},
'861582583':{'en': '<NAME>', 'zh': u('\u7518\u8083\u7701\u5e73\u51c9\u5e02')},
'861582584':{'en': '<NAME>', 'zh': u('\u7518\u8083\u7701\u5e73\u51c9\u5e02')},
'861582585':{'en': '<NAME>', 'zh': u('\u7518\u8083\u7701\u5e73\u51c9\u5e02')},
'861582586':{'en': '<NAME>', 'zh': u('\u7518\u8083\u7701\u5e86\u9633\u5e02')},
'861582587':{'en': '<NAME>', 'zh': u('\u7518\u8083\u7701\u9647\u5357\u5e02')},
'861582588':{'en': '<NAME>', 'zh': u('\u7518\u8083\u7701\u9647\u5357\u5e02')},
'861582589':{'en': '<NAME>', 'zh': u('\u7518\u8083\u7701\u9647\u5357\u5e02')},
'86158259':{'en': 'Chongqing', 'zh': u('\u91cd\u5e86\u5e02')},
'86158260':{'en': 'Chongqing', 'zh': u('\u91cd\u5e86\u5e02')},
'86158261':{'en': 'Chongqing', 'zh': u('\u91cd\u5e86\u5e02')},
'86158262':{'en': 'Chongqing', 'zh': u('\u91cd\u5e86\u5e02')},
'86158263':{'en': 'Chongqing', 'zh': u('\u91cd\u5e86\u5e02')},
'86158264':{'en': 'Chongqing', 'zh': u('\u91cd\u5e86\u5e02')},
'86158265':{'en': 'Jingzhou, Hubei', 'zh': u('\u6e56\u5317\u7701\u8346\u5dde\u5e02')},
'86158266':{'en': 'Jingzhou, Hubei', 'zh': u('\u6e56\u5317\u7701\u8346\u5dde\u5e02')},
'861582666':{'en': 'Enshi, Hubei', 'zh': u('\u6e56\u5317\u7701\u6069\u65bd\u571f\u5bb6\u65cf\u82d7\u65cf\u81ea\u6cbb\u5dde')},
'861582667':{'en': 'Enshi, Hubei', 'zh': u('\u6e56\u5317\u7701\u6069\u65bd\u571f\u5bb6\u65cf\u82d7\u65cf\u81ea\u6cbb\u5dde')},
'861582668':{'en': 'Enshi, Hubei', 'zh': u('\u6e56\u5317\u7701\u6069\u65bd\u571f\u5bb6\u65cf\u82d7\u65cf\u81ea\u6cbb\u5dde')},
'861582669':{'en': 'Enshi, Hubei', 'zh': u('\u6e56\u5317\u7701\u6069\u65bd\u571f\u5bb6\u65cf\u82d7\u65cf\u81ea\u6cbb\u5dde')},
'86158267':{'en': 'Suizhou, Hubei', 'zh': u('\u6e56\u5317\u7701\u968f\u5dde\u5e02')},
'861582670':{'en': 'Enshi, Hubei', 'zh': u('\u6e56\u5317\u7701\u6069\u65bd\u571f\u5bb6\u65cf\u82d7\u65cf\u81ea\u6cbb\u5dde')},
'861582679':{'en': 'Xiaogan, Hubei', 'zh': u('\u6e56\u5317\u7701\u5b5d\u611f\u5e02')},
'86158268':{'en': 'Xiaogan, Hubei', 'zh': u('\u6e56\u5317\u7701\u5b5d\u611f\u5e02')},
'861582688':{'en': 'Wuhan, Hubei', 'zh': u('\u6e56\u5317\u7701\u6b66\u6c49\u5e02')},
'861582689':{'en': 'Wuhan, Hubei', 'zh': u('\u6e56\u5317\u7701\u6b66\u6c49\u5e02')},
'861582690':{'en': 'Wuhan, Hubei', 'zh': u('\u6e56\u5317\u7701\u6b66\u6c49\u5e02')},
'861582691':{'en': 'Wuhan, Hubei', 'zh': u('\u6e56\u5317\u7701\u6b66\u6c49\u5e02')},
'861582692':{'en': 'Wuhan, Hubei', 'zh': u('\u6e56\u5317\u7701\u6b66\u6c49\u5e02')},
'861582693':{'en': 'Wuhan, Hubei', 'zh': u('\u6e56\u5317\u7701\u6b66\u6c49\u5e02')},
'861582694':{'en': 'Huangshi, Hubei', 'zh': u('\u6e56\u5317\u7701\u9ec4\u77f3\u5e02')},
'861582695':{'en': 'Huangshi, Hubei', 'zh': u('\u6e56\u5317\u7701\u9ec4\u77f3\u5e02')},
'861582696':{'en': 'Huangshi, Hubei', 'zh': u('\u6e56\u5317\u7701\u9ec4\u77f3\u5e02')},
'861582697':{'en': 'Huangshi, Hubei', 'zh': u('\u6e56\u5317\u7701\u9ec4\u77f3\u5e02')},
'861582698':{'en': 'Huangshi, Hubei', 'zh': u('\u6e56\u5317\u7701\u9ec4\u77f3\u5e02')},
'861582699':{'en': 'Ezhou, Hubei', 'zh': u('\u6e56\u5317\u7701\u9102\u5dde\u5e02')},
'8615827':{'en': 'Wuhan, Hubei', 'zh': u('\u6e56\u5317\u7701\u6b66\u6c49\u5e02')},
'86158277':{'en': 'Jingzhou, Hubei', 'zh': u('\u6e56\u5317\u7701\u8346\u5dde\u5e02')},
'86158278':{'en': 'Jingmen, Hubei', 'zh': u('\u6e56\u5317\u7701\u8346\u95e8\u5e02')},
'861582780':{'en': 'Ezhou, Hubei', 'zh': u('\u6e56\u5317\u7701\u9102\u5dde\u5e02')},
'861582781':{'en': 'Ezhou, Hubei', 'zh': u('\u6e56\u5317\u7701\u9102\u5dde\u5e02')},
'861582790':{'en': '<NAME>', 'zh': u('\u6e56\u5317\u7701\u54b8\u5b81\u5e02')},
'861582791':{'en': '<NAME>', 'zh': u('\u6e56\u5317\u7701\u54b8\u5b81\u5e02')},
'861582792':{'en': '<NAME>', 'zh': u('\u6e56\u5317\u7701\u54b8\u5b81\u5e02')},
'8615828':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u6210\u90fd\u5e02')},
'861582870':{'en': '<NAME>uan', 'zh': u('\u56db\u5ddd\u7701\u5185\u6c5f\u5e02')},
'861582871':{'en': '<NAME>uan', 'zh': u('\u56db\u5ddd\u7701\u5185\u6c5f\u5e02')},
'861582872':{'en': '<NAME>uan', 'zh': u('\u56db\u5ddd\u7701\u5185\u6c5f\u5e02')},
'861582873':{'en': '<NAME>uan', 'zh': u('\u56db\u5ddd\u7701\u5185\u6c5f\u5e02')},
'861582874':{'en': 'Neijiang, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u5185\u6c5f\u5e02')},
'861582875':{'en': 'Liangshan, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u51c9\u5c71\u5f5d\u65cf\u81ea\u6cbb\u5dde')},
'861582876':{'en': 'Liangshan, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u51c9\u5c71\u5f5d\u65cf\u81ea\u6cbb\u5dde')},
'861582877':{'en': 'Liangshan, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u51c9\u5c71\u5f5d\u65cf\u81ea\u6cbb\u5dde')},
'861582878':{'en': 'Liangshan, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u51c9\u5c71\u5f5d\u65cf\u81ea\u6cbb\u5dde')},
'861582879':{'en': 'Liangshan, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u51c9\u5c71\u5f5d\u65cf\u81ea\u6cbb\u5dde')},
'861582880':{'en': 'Neijiang, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u5185\u6c5f\u5e02')},
'861582881':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u5185\u6c5f\u5e02')},
'861582882':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u5185\u6c5f\u5e02')},
'861582883':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u5185\u6c5f\u5e02')},
'861582884':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u5185\u6c5f\u5e02')},
'861582885':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u9042\u5b81\u5e02')},
'861582886':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u9042\u5b81\u5e02')},
'861582887':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u9042\u5b81\u5e02')},
'861582888':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u9042\u5b81\u5e02')},
'861582889':{'en': 'Suining, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u9042\u5b81\u5e02')},
'861582890':{'en': 'Bazhong, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u5df4\u4e2d\u5e02')},
'861582891':{'en': 'Bazhong, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u5df4\u4e2d\u5e02')},
'861582892':{'en': 'Bazhong, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u5df4\u4e2d\u5e02')},
'861582893':{'en': 'Bazhong, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u5df4\u4e2d\u5e02')},
'861582894':{'en': 'Bazhong, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u5df4\u4e2d\u5e02')},
'861582895':{'en': 'Suining, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u9042\u5b81\u5e02')},
'861582896':{'en': 'Suining, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u9042\u5b81\u5e02')},
'861582897':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u9042\u5b81\u5e02')},
'861582898':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u9042\u5b81\u5e02')},
'861582899':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u9042\u5b81\u5e02')},
'86158290':{'en': '<NAME>', 'zh': u('\u9655\u897f\u7701\u897f\u5b89\u5e02')},
'861582910':{'en': '<NAME>', 'zh': u('\u9655\u897f\u7701\u897f\u5b89\u5e02')},
'861582911':{'en': '<NAME>', 'zh': u('\u9655\u897f\u7701\u5ef6\u5b89\u5e02')},
'861582912':{'en': '<NAME>', 'zh': u('\u9655\u897f\u7701\u6986\u6797\u5e02')},
'861582913':{'en': '<NAME>', 'zh': u('\u9655\u897f\u7701\u5546\u6d1b\u5e02')},
'861582914':{'en': 'Xianyang, Shaanxi', 'zh': u('\u9655\u897f\u7701\u54b8\u9633\u5e02')},
'861582915':{'en': 'Weinan, Shaanxi', 'zh': u('\u9655\u897f\u7701\u6e2d\u5357\u5e02')},
'861582916':{'en': 'Shangluo, Shaanxi', 'zh': u('\u9655\u897f\u7701\u5546\u6d1b\u5e02')},
'861582917':{'en': 'Shangluo, Shaanxi', 'zh': u('\u9655\u897f\u7701\u5546\u6d1b\u5e02')},
'861582918':{'en': '<NAME>', 'zh': u('\u9655\u897f\u7701\u54b8\u9633\u5e02')},
'861582919':{'en': '<NAME>', 'zh': u('\u9655\u897f\u7701\u6e2d\u5357\u5e02')},
'86158292':{'en': 'XiAn, Shaanxi', 'zh': u('\u9655\u897f\u7701\u897f\u5b89\u5e02')},
'86158293':{'en': 'XiAn, Shaanxi', 'zh': u('\u9655\u897f\u7701\u897f\u5b89\u5e02')},
'861582940':{'en': 'Baoji, Shaanxi', 'zh': u('\u9655\u897f\u7701\u5b9d\u9e21\u5e02')},
'861582941':{'en': 'YanAn, Shaanxi', 'zh': u('\u9655\u897f\u7701\u5ef6\u5b89\u5e02')},
'861582942':{'en': 'Weinan, Shaanxi', 'zh': u('\u9655\u897f\u7701\u6e2d\u5357\u5e02')},
'861582943':{'en': 'Weinan, Shaanxi', 'zh': u('\u9655\u897f\u7701\u6e2d\u5357\u5e02')},
'861582944':{'en': '<NAME>', 'zh': u('\u9655\u897f\u7701\u54b8\u9633\u5e02')},
'861582945':{'en': 'Ankang, Shaanxi', 'zh': u('\u9655\u897f\u7701\u5b89\u5eb7\u5e02')},
'861582946':{'en': 'XiAn, Shaanxi', 'zh': u('\u9655\u897f\u7701\u897f\u5b89\u5e02')},
'861582947':{'en': 'XiAn, Shaanxi', 'zh': u('\u9655\u897f\u7701\u897f\u5b89\u5e02')},
'861582948':{'en': '<NAME>', 'zh': u('\u9655\u897f\u7701\u54b8\u9633\u5e02')},
'861582949':{'en': '<NAME>', 'zh': u('\u9655\u897f\u7701\u5b9d\u9e21\u5e02')},
'861582950':{'en': 'Baoji, Shaanxi', 'zh': u('\u9655\u897f\u7701\u5b9d\u9e21\u5e02')},
'861582951':{'en': 'Xianyang, Shaanxi', 'zh': u('\u9655\u897f\u7701\u54b8\u9633\u5e02')},
'861582952':{'en': '<NAME>', 'zh': u('\u9655\u897f\u7701\u54b8\u9633\u5e02')},
'861582953':{'en': '<NAME>', 'zh': u('\u9655\u897f\u7701\u897f\u5b89\u5e02')},
'861582954':{'en': 'XiAn, Shaanxi', 'zh': u('\u9655\u897f\u7701\u897f\u5b89\u5e02')},
'861582955':{'en': '<NAME>', 'zh': u('\u9655\u897f\u7701\u897f\u5b89\u5e02')},
'861582956':{'en': 'Shangluo, Shaanxi', 'zh': u('\u9655\u897f\u7701\u5546\u6d1b\u5e02')},
'861582957':{'en': 'Shangluo, Shaanxi', 'zh': u('\u9655\u897f\u7701\u5546\u6d1b\u5e02')},
'861582958':{'en': 'XiAn, Shaanxi', 'zh': u('\u9655\u897f\u7701\u897f\u5b89\u5e02')},
'861582959':{'en': 'YanAn, Shaanxi', 'zh': u('\u9655\u897f\u7701\u5ef6\u5b89\u5e02')},
'86158296':{'en': 'XiAn, Shaanxi', 'zh': u('\u9655\u897f\u7701\u897f\u5b89\u5e02')},
'86158297':{'en': 'XiAn, Shaanxi', 'zh': u('\u9655\u897f\u7701\u897f\u5b89\u5e02')},
'861582980':{'en': 'Xianyang, Shaanxi', | |
"""Base class for the tidal database models."""
# 1. Standard python modules
from abc import ABCMeta, abstractmethod
from datetime import datetime
import math
# 2. Third party modules
import numpy
import pandas as pd
from pytides.astro import astro
# 3. Aquaveo modules
# 4. Local modules
from .resource import ResourceManager
NCNST = 37
# Dictionary of NOAA constituent speed constants (deg/hr)
# Source: https://tidesandcurrents.noaa.gov
# The speed is the rate change in the phase of a constituent, and is equal to 360 degrees divided by the
# constituent period expressed in hours
# name: (speed, amplitude, frequency, ETRF)
NOAA_SPEEDS = {
'OO1': (16.139101, 0.0, 0.00007824457305, 0.069),
'2Q1': (12.854286, 0.0, 0.000062319338107, 0.069),
'2MK3': (42.92714, 0.0, 0.000208116646659, 0.069),
'2N2': (27.895355, 0.0, 0.000135240496464, 0.069),
'2SM2': (31.015896, 0.0, 0.000150369306157, 0.069),
'K1': (15.041069, 0.141565, 0.000072921158358, 0.736),
'K2': (30.082138, 0.030704, 0.000145842317201, 0.693),
'J1': (15.5854435, 0.0, 0.00007556036138, 0.069),
'L2': (29.528479, 0.0, 0.000143158105531, 0.069),
'LAM2': (29.455626, 0.0, 0.000142804901311, 0.069),
'M1': (14.496694, 0.0, 0.000070281955336, 0.069),
'M2': (28.984104, 0.242334, 0.000140518902509, 0.693),
'M3': (43.47616, 0.0, 0.000210778353763, 0.069),
'M4': (57.96821, 0.0, 0.000281037805017, 0.069),
'M6': (86.95232, 0.0, 0.000421556708011, 0.069),
'M8': (115.93642, 0.0, 0.000562075610519, 0.069),
'MF': (1.0980331, 0.0, 0.000005323414692, 0.069),
'MK3': (44.025173, 0.0, 0.000213440061351, 0.069),
'MM': (0.5443747, 0.0, 0.000002639203022, 0.069),
'MN4': (57.423832, 0.0, 0.000278398601995, 0.069),
'MS4': (58.984104, 0.0, 0.000285963006842, 0.069),
'MSF': (1.0158958, 0.0, 0.000004925201824, 0.069),
'MU2': (27.968208, 0.0, 0.000135593700684, 0.069),
'N2': (28.43973, 0.046398, 0.000137879699487, 0.693),
'NU2': (28.512583, 0.0, 0.000138232903707, 0.069),
'O1': (13.943035, 0.100514, 0.000067597744151, 0.695),
'P1': (14.958931, 0.046834, 0.000072522945975, 0.706),
'Q1': (13.398661, 0.019256, 0.000064958541129, 0.695),
'R2': (30.041067, 0.0, 0.000145643201313, 0.069),
'RHO': (13.471515, 0.0, 0.000065311745349, 0.069),
'S1': (15.0, 0.0, 0.000072722052166, 0.069),
'S2': (30.0, 0.112841, 0.000145444104333, 0.693),
'S4': (60.0, 0.0, 0.000290888208666, 0.069),
'S6': (90.0, 0.0, 0.000436332312999, 0.069),
'SA': (0.0410686, 0.0, 0.000000199106191, 0.069),
'SSA': (0.0821373, 0.0, 0.000000398212868, 0.069),
'T2': (29.958933, 0.0, 0.000145245007353, 0.069),
}
def get_complex_components(amps, phases):
"""Get the real and imaginary components of amplitudes and phases.
Args:
amps (:obj:`list` of :obj:`float`): List of constituent amplitudes
phases (:obj:`list` of :obj:`float`): List of constituent phases in radians
Returns:
:obj:`list` of :obj:`tuple` of :obj:`float`: The list of the complex components,
e.g. [[real1, imag1], [real2, imag2]]
"""
components = [[0.0, 0.0] for _ in range(len(amps))]
for idx, (amp, phase) in enumerate(zip(amps, phases)):
components[idx][0] = amp * math.cos(phase)
components[idx][1] = amp * math.sin(phase)
return components
def convert_coords(coords, zero_to_360=False):
"""Convert latitude coordinates to [-180, 180] or [0, 360].
Args:
coords (:obj:`list` of :obj:`tuple` of :obj:`float`): latitude [-90, 90] and longitude [-180 180] or [0 360]
of the requested point.
zero_to_360 (:obj:`bool`, optional) If True, coordinates will be converted to the [0, 360] range. If False,
coordinates will be converted to the [-180, 180] range.
Returns:
:obj:`list` of :obj:`tuple` of :obj:`float`: The list of converted coordinates. None if a coordinate out of
range was encountered
"""
# Make sure point locations are valid lat/lon
for idx, pt in enumerate(coords):
y_lat = pt[0]
x_lon = pt[1]
if x_lon < 0.0:
x_lon += 360.0
if not zero_to_360 and x_lon > 180.0:
x_lon -= 360.0
bad_lat = y_lat > 90.0 or y_lat < -90.0 # Invalid latitude
bad_lon = not zero_to_360 and (x_lon > 180.0 or x_lon < -180.0) # Invalid [-180, 180]
bad_lon = bad_lon or (zero_to_360 and (x_lon > 360.0 or x_lon < 0.0)) # Invalid [0, 360]
if bad_lat or bad_lon:
# ERROR: Not in latitude/longitude
return None
else:
coords[idx] = (y_lat, x_lon)
return coords
class OrbitVariables(object):
"""Container for variables used in astronomical equations.
Attributes:
astro (:obj:`pytides.astro.astro`): Orbit variables obtained from pytides.
grterm (:obj:`dict` of :obj:`float`): Dictionary of equilibrium arguments where the key is constituent name
nodfac (:obj:`dict` of :obj:`float`): Dictionary of nodal factors where the key is constituent name
"""
def __init__(self):
"""Construct the container."""
self.astro = {}
self.grterm = {con: 0.0 for con in NOAA_SPEEDS}
self.nodfac = {con: 0.0 for con in NOAA_SPEEDS}
class TidalDB(object):
"""The base class for extracting tidal data from a database.
Attributes:
orbit (:obj:`OrbitVariables`): The orbit variables.
data (:obj:`list` of :obj:`pandas.DataFrame`): List of the constituent component DataFrames with one
per point location requested from get_components(). Intended return value of get_components().
resources (:obj:`harmonica.resource.ResourceManager`): Manages fetching of tidal data
"""
"""(:obj:`list` of :obj:`float`): The starting days of the months (non-leap year)."""
day_t = [0.0, 31.0, 59.0, 90.0, 120.0, 151.0, 181.0, 212.0, 243.0, 273.0, 304.0, 334.0]
def __init__(self, model):
"""Base class constructor for the tidal extractors.
Args:
model (str): The name of the model. See resource.py for supported models.
"""
self.orbit = OrbitVariables()
# constituent information dataframe:
# amplitude (meters)
# phase (degrees)
# speed (degrees/hour, UTC/GMT)
self.data = []
self.model = model
self.resources = ResourceManager(self.model)
__metaclass__ = ABCMeta
@abstractmethod
def get_components(self, locs, cons, positive_ph):
"""Abstract method to get amplitude, phase, and speed of specified constituents at specified point locations.
Args:
locs (:obj:`list` of :obj:`tuple` of :obj:`float`): latitude [-90, 90] and longitude [-180 180] or [0 360]
of the requested points.
cons (:obj:`list` of :obj:`str`, optional): List of the constituent names to get amplitude and phase for. If
not supplied, all valid constituents will be extracted.
positive_ph (bool, optional): Indicate if the returned phase should be all positive [0 360] (True) or
[-180 180] (False, the default).
Returns:
:obj:`list` of :obj:`pandas.DataFrame`: Implementations should return a list of dataframes of constituent
information including amplitude (meters), phase (degrees) and speed (degrees/hour, UTC/GMT). The list is
parallel with locs, where each element in the return list is the constituent data for the corresponding
element in locs. Empty list on error. Note that function uses fluent interface pattern.
"""
pass
def have_constituent(self, name):
"""Determine if a constituent is valid for this tidal extractor.
Args:
name (str): The name of the constituent.
Returns:
bool: True if the constituent is valid, False otherwise
"""
return name.upper() in self.resources.available_constituents()
def get_nodal_factor(self, names, timestamp, timestamp_middle):
"""Get the nodal factor for specified constituents at a specified time.
Args:
names (:obj:`list` of :obj:`str`): Names of the constituents to get nodal factors for
timestamp (:obj:`datetime.datetime`): Start date and time to extract constituent arguments at
timestamp_middle (:obj:`datetime.datetime`): Date and time to consider as the middle of the series.
Returns:
:obj:`pandas.DataFrame`: Constituent data frames. Each row contains frequency, earth tidal reduction factor,
amplitude, nodal factor, and equilibrium argument for one of the specified constituents. Rows labeled by
constituent name.
"""
con_data = pd.DataFrame(columns=['amplitude', 'frequency', 'speed', 'earth_tide_reduction_factor',
'equilibrium_argument', 'nodal_factor'])
if not timestamp_middle:
float_hours = timestamp.hour / 2.0
hour = int(float_hours)
float_minutes = (float_hours - hour) * 60.0
minute = int(float_minutes)
second = int((float_minutes - minute) * 60.0)
timestamp_middle = datetime(timestamp.year, timestamp.month, timestamp.day, hour, minute, second)
self.get_eq_args(timestamp, timestamp_middle)
for name in names:
name = name.upper()
if name not in NOAA_SPEEDS:
con_data.loc[name] = [numpy.nan, numpy.nan, numpy.nan, numpy.nan, numpy.nan, numpy.nan]
else:
equilibrium_arg = 0.0
nodal_factor = self.orbit.nodfac[name]
if nodal_factor != 0.0:
equilibrium_arg = self.orbit.grterm[name]
con_data.loc[name] = [
NOAA_SPEEDS[name][1], NOAA_SPEEDS[name][2], NOAA_SPEEDS[name][0], NOAA_SPEEDS[name][3],
equilibrium_arg, nodal_factor
]
return con_data
def get_eq_args(self, timestamp, timestamp_middle):
"""Get equilibrium arguments at a starting time.
Args:
timestamp (:obj:`datetime.datetime`): Date and time to extract constituent arguments at
timestamp_middle (:obj:`datetime.datetime`): Date and time to consider as the middle of the series
"""
self.nfacs(timestamp_middle)
self.gterms(timestamp, timestamp_middle)
@staticmethod
def angle(a_number):
"""Converts the angle to be within 0-360.
Args:
a_number (float): The angle to convert.
Returns:
The angle converted to be within 0-360.
"""
ret_val = a_number
while ret_val < 0.0:
ret_val += 360.0
while ret_val > 360.0:
ret_val -= 360.0
return ret_val
def set_orbit(self, timestamp):
"""Determination of primary and secondary orbital functions.
Args:
timestamp (:obj:`datetime.datetime`): Date and time to extract constituent arguments at.
"""
self.orbit.astro = astro(timestamp)
def nfacs(self, timestamp):
"""Calculates node factors for constituent tidal signal.
Args:
timestamp (:obj:`datetime.datetime`): Date and time to extract constituent arguments at
Returns:
The same values as found in table 14 of Schureman.
"""
self.set_orbit(timestamp)
fi = math.radians(self.orbit.astro['i'].value)
nu = math.radians(self.orbit.astro['nu'].value)
sini = math.sin(fi)
sini2 = math.sin(fi / 2.0)
sin2i = math.sin(2.0 * fi)
cosi2 = math.cos(fi / 2.0)
# EQUATION 197, SCHUREMAN
# qainv = math.sqrt(2.310+1.435*math.cos(2.0*pc))
# EQUATION 213, SCHUREMAN
# rainv = math.sqrt(1.0-12.0*math.pow(tani2, 2)*math.cos(2.0*pc)+36.0*math.pow(tani2, 4))
# VARIABLE NAMES REFER TO EQUATION NUMBERS IN SCHUREMAN
eq73 = (2.0 / 3.0 - math.pow(sini, 2)) / 0.5021
| |
import logging
from nes.instructions import INSTRUCTION_SET, PyNamedInstruction, AddressModes
#from nes import LOG_CPU
class MOS6502:
"""
Software emulator for MOS Technologies 6502 CPU
References:
[1] https://www.masswerk.at/6502/6502_instruction_set.html
[2] http://www.obelisk.me.uk/6502/addressing.html
[3] https://www.csh.rit.edu/~moffitt/docs/6502.html
[4] V-flag: http://www.6502.org/tutorials/vflag.html
[5] Decimal mode: http://www.6502.org/tutorials/decimal_mode.html
[6] PC: http://6502.org/tutorials/6502opcodes.html#PC
[7] http://forum.6502.org/viewtopic.php?t=1708
[8] Assembler online: https://www.masswerk.at/6502/assembler.html
[9] CPU startup sequence: https://www.pagetable.com/?p=410
[10] B-flag: http://wiki.nesdev.com/w/index.php/Status_flags#The_B_flag
[11] V-flag: http://www.righto.com/2012/12/the-6502-overflow-flag-explained.html
[12] JMP indirect 'bug': http://forum.6502.org/viewtopic.php?f=2&t=6170
[13] Undocumented opcodes: http://nesdev.com/undocumented_opcodes.txt
[14] Undocumented opcodes: http://www.ffd2.com/fridge/docs/6502-NMOS.extra.opcodes
[15] Amazing timing data: http://www.6502.org/users/andre/petindex/local/64doc.txt
[16] Undocumented opcodes: http://hitmen.c02.at/files/docs/c64/NoMoreSecrets-NMOS6510UnintendedOpcodes-20162412.pdf
"""
# Masks for the bits in the status register
SR_N_MASK = 0b10000000 # negative
SR_V_MASK = 0b01000000 # overflow
SR_X_MASK = 0b00100000 # unused, but should be set to 1
SR_B_MASK = 0b00010000 # the "break" flag (indicates BRK was executed, only set on the stack copy)
SR_D_MASK = 0b00001000 # decimal
SR_I_MASK = 0b00000100 # interrupt disable
SR_Z_MASK = 0b00000010 # zero
SR_C_MASK = 0b00000001 # carry
# some useful memory locations
STACK_PAGE = 0x0100 # stack is held on page 1, from 0x0100 to 0x01FF
IRQ_BRK_VECTOR_ADDR = 0xFFFE # start of 16 bit location containing the address of the IRQ/BRK interrupt handler
RESET_VECTOR_ADDR = 0xFFFC # start of 16 bit location containing the address of the RESET handler
NMI_VECTOR_ADDR = 0xFFFA # start of 16 bit location of address of the NMI (non maskable interrupt) handler
# 6502 is little endian (least significant byte first in 16bit words)
LO_BYTE = 0
HI_BYTE = 1
# cycles taken to do the NMI or IRQ interrupt - (this is a guess, based on BRK, couldn't find a ref for this!)
INTERRUPT_REQUEST_CYCLES = 7
OAM_DMA_CPU_CYCLES = 513
def __init__(self, memory, support_BCD=False, undocumented_support_level=1, aax_sets_flags=False, stack_underflow_causes_exception=True):
# memory is user-supplied object with read and write methods, allowing for memory mappers, bank switching, etc.
self.memory = memory
# create a map from bytecodes to functions for the instruction set
self.instructions = self._make_bytecode_dict()
# User-accessible registers
self.A = None # accumulator
self.X = None # X register
self.Y = None # Y register
# Indirectly accessible registers
self.PC = None # program counter (not valid until a reset() has occurred)
self.SP = None # stack pointer (8-bit, but the stack is in page 1 of mem, starting at 0x01FF and counting backwards to 0x0100)
# Flags
# (stored as an 8-bit register in the CPU)
# (use _status_[to/from]_byte to convert to 8-bit byte for storage on stack)
self.N = None
self.V = None
self.D = None
self.I = None
self.Z = None
self.C = None
# CPU cycles since the processor was started or reset
self.cycles_since_reset = None
self.started = False
# debug
self._previous_PC = 0
# control behaviour of the cpu
self.support_BCD = support_BCD
self.aax_sets_flags = aax_sets_flags
self.undocumented_support_level = undocumented_support_level
self.stack_underflow_causes_exception = stack_underflow_causes_exception
def reset(self):
"""
Resets the CPU
"""
# read the program counter from the RESET_VECTOR_ADDR
self.PC = self._read_word(self.RESET_VECTOR_ADDR)
# clear the registers
self.A = 0 # accumulator
self.X = 0 # X register
self.Y = 0 # Y register
# stack pointer (8-bit, but the stack is in page 1 of mem, starting at 0x01FF and counting backwards to 0x0100)
# reset does three stack pops, so this is set to 0xFD after reset [9]
self.SP = 0xFD
# Flags
# (use _status_[to/from]_byte to convert to 8-bit byte for storage on stack)
self.N = False
self.V = False
self.D = False
self.I = True # CPU should "come up with interrupt disable bit set" [7]
self.Z = False
self.C = False
# CPU cycles since the processor was started or reset
# reset takes 7 cycles [9]
self.cycles_since_reset = 7
def _make_bytecode_dict(self):
"""
Translates the instruction sets into a bytecode->instr dictionary and links the instruction opcodes
to the functions in this object that execute them (this is done by instruction name).
"""
instructions = [None] * 256
for _, instr_set in INSTRUCTION_SET.items():
for mode, instr in instr_set.modes.items():
if type(instr.bytecode) == list:
# some of the undocumented opcodes have multiple aliases, so in that case a list of
# opcodes is supplied
for bytecode in instr.bytecode:
instructions[bytecode] = PyNamedInstruction(name=instr_set.name,
bytecode=bytecode,
mode=mode,
size_bytes=instr.size_bytes,
cycles=instr.cycles,
function=getattr(self, "_{}".format(instr_set.name)),
)
else:
instructions[instr.bytecode] = PyNamedInstruction(name=instr_set.name,
bytecode=instr.bytecode,
mode=mode,
size_bytes=instr.size_bytes,
cycles=instr.cycles,
function=getattr(self, "_{}".format(instr_set.name)),
)
return instructions
def print_status(self):
"""
Prints a human-readable summary of the CPU status
"""
print("A: ${0:02x} X: ${0:02x} Y: ${0:02x}".format(self.A, self.X, self.Y))
print("SP: ${:x}".format(self.SP))
print("STACK: (head) ${0:02x}".format(self.memory.read(self.STACK_PAGE + self.SP)))
if 0xFF - self.SP > 0:
print(" ${:x}".format(self.memory.read(self.STACK_PAGE + self.SP + 1)))
if 0xFF - self.SP > 1:
print(" ${:x}".format(self.memory.read(self.STACK_PAGE + self.SP + 2)))
print("Flags: NV-BDIZC as byte: ${:x}".format(self._status_to_byte()))
print(" {0:08b}".format(self._status_to_byte()))
print()
cur_bytecode = self.memory.read(self._previous_PC)
cur_instr = self.instructions[cur_bytecode]
cur_data = self.memory.read_block(self._previous_PC + 1, bytes=cur_instr.size_bytes - 1)
print("last PC: ${:x} Instr @ last PC: ${:x} - ".format(self._previous_PC, cur_bytecode), end="")
print(self.format_instruction(cur_instr, cur_data))
bytecode = self.memory.read(self.PC)
instr = self.instructions[bytecode]
data = self.memory.read_block(self.PC + 1, bytes=instr.size_bytes - 1)
print("next PC: ${:x} Instr @ next PC: ${:x} - ".format(self.PC, bytecode), end="")
print(self.format_instruction(instr, data))
print("cycles: {}".format(self.cycles_since_reset))
def format_instruction(self, instr, data, caps=True):
line = ""
name = instr.name if not caps else instr.name.upper()
line += '{} '.format(name)
if instr.mode == AddressModes.IMMEDIATE:
line += '#${0:02X}'.format(data[0])
elif instr.mode == AddressModes.ZEROPAGE:
line += '${0:02X}'.format(data[0])
elif instr.mode == AddressModes.ZEROPAGE_X:
line += '${0:02X},X'.format(data[0])
elif instr.mode == AddressModes.ZEROPAGE_Y:
line += '${0:02X},Y'.format(data[0])
elif instr.mode == AddressModes.ABSOLUTE:
line += '${0:04X}'.format(self._from_le(data))
elif instr.mode == AddressModes.ABSOLUTE_X:
line += '${0:04X},X'.format(self._from_le(data))
elif instr.mode == AddressModes.ABSOLUTE_Y:
line += '${0:04X},Y'.format(self._from_le(data))
elif instr.mode == AddressModes.INDIRECT_X:
line += '(${:02X},X) @ {:02X} = {:04X}'.format(data[0], data[0], self._read_word((data[0] + self.X) & 0xFF, wrap_at_page=True))
elif instr.mode == AddressModes.INDIRECT_Y:
line += '(${:02X}),Y = {:04X} @ {:04X}'.format(data[0], self._read_word(data[0], wrap_at_page=True), (self._read_word(data[0], wrap_at_page=True) + self.Y) & 0xFFFF)
elif instr.mode == AddressModes.INDIRECT:
line += '(${0:04X})'.format(self._from_le(data))
elif instr.mode == AddressModes.IMPLIED:
line += ''
elif instr.mode == AddressModes.ACCUMULATOR:
line += 'A'
elif instr.mode == AddressModes.RELATIVE:
line += '${0:02X} (-> ${1:04X})'.format(self._from_2sc(data[0]), self.PC + 2 + self._from_2sc(data[0]))
return line
def log_line(self):
"""
Generates a log line in the format of nestest
"""
str = "{0:04X} ".format(self.PC)
bytecode = self.memory.read(self.PC)
instr = self.instructions[bytecode]
data = self.memory.read_block(self.PC + 1, bytes=instr.size_bytes - 1)
str += "{0:02X} ".format(bytecode)
str += "{0:02X} ".format(data[0]) if len(data) > 0 else " "
str += "{0:02X} ".format(data[1]) if len(data) > 1 else " "
str += self.format_instruction(instr, data)
while len(str) < 48:
str += " "
str += "A:{:02X} X:{:02X} Y:{:02X} P:{:02X} SP:{:02X} PPU:---,--- CYC:{:d}".format(self.A,
self.X,
self.Y,
self._status_to_byte(),
self.SP,
self.cycles_since_reset
)
return str
def oam_dma_pause(self):
cycles = self.OAM_DMA_CPU_CYCLES + self.cycles_since_reset % 2
self.cycles_since_reset += cycles
return cycles
def set_reset_vector(self, reset_vector):
"""
Sets the reset vector (at fixed mem address), which tells the program counter where to start on a reset
:param reset_vector: 16-bit address to which PC will be set after a reset
"""
self.memory.write(self.RESET_VECTOR_ADDR, reset_vector & 0x00FF) # low byte
self.memory.write(self.RESET_VECTOR_ADDR + 1, (reset_vector & 0xFF00) >> 8) # high byte
@staticmethod
def _from_le(data):
"""
Create an integer from a little-endian two byte array
:param data: two-byte little endian array
:return: an integer in the range 0-65535
"""
return (data[MOS6502.HI_BYTE] << 8) + data[MOS6502.LO_BYTE]
def _read_word(self, addr, wrap_at_page=False):
"""
Read a word at an address and return it as an integer
If wrap_at_page is True then if the address is 0xppFF, then the word will be read from 0xppFF and 0xpp00
"""
if wrap_at_page and (addr & 0xFF) == 0xFF:
# will wrap at page boundary
byte_lo = self.memory.read(addr)
byte_hi = self.memory.read(addr & 0xFF00) # read the second (hi) byte from the start of the page
else:
byte_lo = self.memory.read(addr)
byte_hi = self.memory.read(addr + 1)
return byte_lo + (byte_hi << 8)
def trigger_nmi(self):
"""
Trigger a non maskable interrupt (NMI)
"""
self._interrupt(self.NMI_VECTOR_ADDR)
self.cycles_since_reset += self.INTERRUPT_REQUEST_CYCLES
return self.INTERRUPT_REQUEST_CYCLES
def trigger_irq(self):
"""
Trigger a maskable hardware interrupt (IRQ); if interrupt disable bit (self.I) is set, ignore
"""
if not self.I:
self._interrupt(self.IRQ_BRK_VECTOR_ADDR)
self.cycles_since_reset += self.INTERRUPT_REQUEST_CYCLES
return self.INTERRUPT_REQUEST_CYCLES
else:
return 0 # ignored!
def run_next_instr(self):
"""
Decode and run the next instruction at the program counter, updating | |
<filename>lib/model/fpn/resnext_IN.py<gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 27 19:14:38 2019
@author: Administrator
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
sys.path.append("../..")
from model.utils.config import cfg
from model.fpn.fpn import _FPN
import pickle as cPickle
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import math
import torch.utils.model_zoo as model_zoo
import pdb
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152', 'resnext50_32x4d', 'resnext101_32x8d']
activate_function = [nn.ReLU,nn.LeakyReLU,nn.PReLU,nn.ELU]
activate = activate_function[1](0.2)
# courtesy: https://github.com/darkstar112358/fast-neural-style/blob/master/neural_style/transformer_net.py
class InstanceNormalization(torch.nn.Module):
"""InstanceNormalization
Improves convergence of neural-style.
ref: https://arxiv.org/pdf/1607.08022.pdf
"""
def __init__(self, dim, eps=1e-9):
super(InstanceNormalization, self).__init__()
self.scale = nn.Parameter(torch.FloatTensor(dim))
self.shift = nn.Parameter(torch.FloatTensor(dim))
self.eps = eps
self._reset_parameters()
def _reset_parameters(self):
self.scale.data.uniform_()
self.shift.data.zero_()
def forward(self, x):
n = x.size(2) * x.size(3)
t = x.view(x.size(0), x.size(1), n)
mean = torch.mean(t, 2).unsqueeze(2).unsqueeze(3).expand_as(x)
# Calculate the biased var. torch.var returns unbiased var
var = torch.var(t, 2).unsqueeze(2).unsqueeze(3).expand_as(x) * ((n - 1) / float(n))
scale_broadcast = self.scale.unsqueeze(1).unsqueeze(1).unsqueeze(0)
scale_broadcast = scale_broadcast.expand_as(x)
shift_broadcast = self.shift.unsqueeze(1).unsqueeze(1).unsqueeze(0)
shift_broadcast = shift_broadcast.expand_as(x)
out = (x - mean) / torch.sqrt(var + self.eps)
out = out * scale_broadcast + shift_broadcast
return out
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=dilation, groups=groups, bias=False, dilation=dilation)
def conv1x1(in_planes, out_planes, stride=1):
"""1x1 convolution"""
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
def downsampling(in_planes, out_planes, step, last):
layer = []
for i in range(step):
layer.append(nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=2, padding=1, bias=False))
layer.append(nn.BatchNorm2d(out_planes))
if i == 0:
in_planes = out_planes
if last == 1:
layer.append(nn.ReLU(inplace=True))
return nn.Sequential(*layer)
def upsampling(in_planes, out_planes, step):
layer = []
layer.append(nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=1, bias=False))
layer.append(nn.BatchNorm2d(out_planes))
layer.append(nn.Upsample(scale_factor=pow(2,step), mode='nearest'))
return nn.Sequential(*layer)
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
base_width=64, dilation=1, norm_layer=None):
super(BasicBlock, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
if groups != 1 or base_width != 64:
raise ValueError('BasicBlock only supports groups=1 and base_width=64')
if dilation > 1:
raise NotImplementedError("Dilation > 1 not supported in BasicBlock")
# Both self.conv1 and self.downsample layers downsample the input when stride != 1
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = norm_layer(planes)
self.relu = activate
self.conv2 = conv3x3(planes, planes)
self.bn2 = norm_layer(planes)
self.downsample = downsample
self.stride = stride
def forward(self, x):
identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
out = self.relu(out)
return out
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
base_width=64, dilation=1, norm_layer=None):
super(Bottleneck, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
width = int(planes * (base_width / 64.)) * groups
# Both self.conv2 and self.downsample layers downsample the input when stride != 1
self.conv1 = conv1x1(inplanes, width)
self.bn1 = norm_layer(width)
self.conv2 = conv3x3(width, width, stride, groups, dilation)
self.bn2 = norm_layer(width)
self.conv3 = conv1x1(width, planes * self.expansion)
self.bn3 = norm_layer(planes * self.expansion)
self.relu = activate
self.downsample = downsample
self.stride = stride
def forward(self, x):
identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
out = self.relu(out)
return out
class ExchangeResidualUnit(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, norm_layer=None):
super(ExchangeResidualUnit, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
stride = 1
# Both self.conv1 and self.downsample layers downsample the input when stride != 1
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
self.bn1 = norm_layer(planes)
self.relu = activate
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
self.bn2 = norm_layer(planes)
self.stride = stride
def forward(self, x):
identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
# if self.downsample is not None:
# identity = self.downsample(x)
# out += identity
out = self.relu(out)
return out
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000, zero_init_residual=False,
groups=1, width_per_group=64, replace_stride_with_dilation=None,
norm_layer=None):
super(ResNet, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
self._norm_layer = norm_layer
self.inplanes = 16
self.dilation = 1
if replace_stride_with_dilation is None:
# each element in the tuple indicates if we should replace
# the 2x2 stride with a dilated convolution instead
# replace_stride_with_dilation = [False, False, False]
replace_stride_with_dilation = [True, True, False]
if len(replace_stride_with_dilation) != 3:
raise ValueError("replace_stride_with_dilation should be None "
"or a 3-element tuple, got {}".format(replace_stride_with_dilation))
self.groups = groups
self.base_width = width_per_group
self.conv1 = nn.Conv2d(3, 6, kernel_size=3, stride=1, padding=1,
bias=False)
self.conv2 = nn.Conv2d(6, 16, kernel_size=3, stride=1, padding=1,
bias=False)
self.conv3 = nn.Conv2d(16, 16, kernel_size=3, stride=1, padding=1,
bias=False)
self.bn1 = norm_layer(self.inplanes)
self.relu = activate
# self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=0, ceil_mode=True) # change
self.layer1 = self._make_layer(block, 16, layers[0])
self.layer2 = self._make_layer(block, 32, layers[1], stride=2,
dilate=replace_stride_with_dilation[0])
self.layer3 = self._make_layer(block, 64, layers[2], stride=2,
dilate=replace_stride_with_dilation[1])
self.layer4 = self._make_layer(block, 128, layers[3], stride=1,
dilate=replace_stride_with_dilation[2])
# self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.avgpool = nn.AdaptiveAvgPool2d(7)
self.fc = nn.Linear(128 * block.expansion, num_classes)
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
# Zero-initialize the last BN in each residual branch,
# so that the residual branch starts with zeros, and each residual block behaves like an identity.
# This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
if zero_init_residual:
for m in self.modules():
if isinstance(m, Bottleneck):
nn.init.constant_(m.bn3.weight, 0)
elif isinstance(m, BasicBlock):
nn.init.constant_(m.bn2.weight, 0)
def _make_layer(self, block, planes, blocks, stride=1, dilate=False):
norm_layer = self._norm_layer
downsample = None
previous_dilation = self.dilation
if dilate:
self.dilation *= stride
stride = 1
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
conv1x1(self.inplanes, planes * block.expansion, stride),
norm_layer(planes * block.expansion),
)
layers = []
layers.append(block(self.inplanes, planes, stride, downsample, self.groups,
self.base_width, previous_dilation, norm_layer))
self.inplanes = planes * block.expansion
for _ in range(1, blocks):
layers.append(block(self.inplanes, planes, groups=self.groups,
base_width=self.base_width, dilation=self.dilation,
norm_layer=norm_layer))
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
def resnet18(pretrained=False, **kwargs):
"""Constructs a ResNet-18 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)
return model
def resnet34(pretrained=False, **kwargs):
"""Constructs a ResNet-34 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)
return model
def resnet50(pretrained=False, **kwargs):
"""Constructs a ResNet-50 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
return model
def resnext50_32x4d(pretrained=False, **kwargs):
# model = ResNet(Bottleneck, [3, 4, 6, 3], groups=32, width_per_group=4, **kwargs)
model = ResNet(Bottleneck, [1, 1, 1, 1], groups=32, width_per_group=4, **kwargs)
# if pretrained:
# model.load_state_dict(model_zoo.load_url(model_urls['resnext50_32x4d']))
return model
### add in 2019.6.8 L1 and L2 regularization
class Regularization(torch.nn.Module):
def __init__(self, model, weight_decay):
'''
:param model 模型
:param weight_decay:正则化参数
:param p: 范数计算中的幂指数值,默认求2范数,
当p=0为L2正则化,p=1为L1正则化
'''
super(Regularization, self).__init__()
if weight_decay <= 0:
print("param weight_decay can not <=0")
exit(0)
self.model = model
self.weight_decay = weight_decay
self.weight_list = self.get_weight(model)
def to(self, device):
'''
指定运行模式
:param device: cude or cpu
:return:
'''
self.device = device
super().to(device)
return self
def forward(self, model):
self.weight_list = self.get_weight(model) # 获得最新的权重
reg_loss = self.regularization_loss(self.weight_list, self.weight_decay)
return reg_loss
def get_weight(self, model):
'''
获得模型的权重列表
:param model:
:return:
'''
weight_list = []
for name, param in model.named_parameters():
if 'weight' in name:
weight = (name, param)
weight_list.append(weight)
return weight_list
def regularization_loss(self, weight_list, weight_decay):
'''
计算张量范数
:param weight_list:
:param p: 范数计算中的幂指数值,默认求2范数
:param weight_decay:
:return:
'''
reg_loss = 0
for name, w in weight_list:
l1_reg = torch.norm(w,p=1)
l2_reg = torch.norm(w,p=2)
reg_loss = reg_loss + l2_reg + l1_reg
reg_loss = weight_decay * reg_loss
return reg_loss
class resnet(_FPN):
def __init__(self, classes, num_layers=101, pretrained=False, class_agnostic=False):
self.model_path = '/home/lab30202/lq/ai_future/galaxy_star_detect/fpn_galaxy_star/data/pretrained_model/best_galaxy_star_IN.pth'
self.dout_base_model = 64 ## 256 -> 24
self.pretrained = pretrained
self.class_agnostic = class_agnostic
_FPN.__init__(self, classes, class_agnostic)
def _init_modules(self):
resnet = resnext50_32x4d()
print("pretrained:",self.pretrained)
if self.pretrained == True:
print("Loading pretrained weights from %s" %(self.model_path))
state_dict = torch.load(self.model_path)
num_ftrs = resnet.fc.in_features
resnet.fc = nn.Linear(num_ftrs * 49, 3)
resnet.load_state_dict({k:v for k,v in state_dict.items() if k in resnet.state_dict()})
self.RCNN_layer0 = nn.Sequential(resnet.conv1,resnet.conv2,resnet.conv3, resnet.bn1, resnet.relu, resnet.maxpool)
self.RCNN_layer1 = nn.Sequential(resnet.layer1)
| |
"""Detect all Python scripts in HTML pages in current folder and subfolders.
Generate brython_modules.js, a bundle with all the modules and packages used
by an application.
Generate a Python package ready for installation and upload on PyPI.
"""
import os
import shutil
import html.parser
import json
import traceback
import sys
import time
import io
import tokenize
import token
# Template for application setup.py script
setup = """from setuptools import setup, find_packages
import os
if os.path.exists('README.rst'):
with open('README.rst', encoding='utf-8') as fobj:
LONG_DESCRIPTION = fobj.read()
setup(
name='{app_name}',
version='{version}',
# The project's main homepage.
url='{url}',
# Author details
author='{author}',
author_email='{author_email}',
# License
license='{license}',
packages=['data'],
py_modules=["{app_name}"],
package_data={{'data':[{files}]}}
)
"""
# Template for the application script
app = """import os
import shutil
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--install',
help='Install {app_name} in an empty directory',
action="store_true")
args = parser.parse_args()
files = ({files})
if args.install:
print('Installing {app_name} in an empty directory')
src_path = os.path.join(os.path.dirname(__file__), 'data')
if os.listdir(os.getcwd()):
print('{app_name} can only be installed in an empty folder')
import sys
sys.exit()
for path in files:
dst = os.path.join(os.getcwd(), path)
head, tail = os.path.split(dst)
if not os.path.exists(head):
os.mkdir(head)
shutil.copyfile(os.path.join(src_path, path), dst)
"""
class FromImport:
def __init__(self):
self.source = ''
self.type = "from"
self.level = 0
self.expect = "source"
self.names = []
def __str__(self):
return '<import ' + str(self.names) + ' from ' + str(self.source) +'>'
class Import:
def __init__(self):
self.type = "import"
self.expect = "module"
self.modules = []
def __str__(self):
return '<import ' + str(self.modules) + '>'
class ImportsFinder:
def __init__(self, *args, **kw):
self.package = kw.pop("package") or ""
def find(self, src):
"""Find imports in source code src. Uses the tokenize module instead
of ast in previous Brython version, so that this script can be run
with CPython versions older than the one implemented in Brython."""
imports = set()
importing = None
f = io.BytesIO(src.encode("utf-8"))
for tok_type, tok_string, *_ in tokenize.tokenize(f.readline):
tok_type = token.tok_name[tok_type]
if importing is None:
if tok_type == "NAME" and tok_string in ["import", "from"]:
context = Import() if tok_string == "import" \
else FromImport()
importing = True
else:
if tok_type == "NEWLINE":
imports.add(context)
importing = None
else:
self.transition(context, tok_type, tok_string)
if importing:
imports.add(context)
# Transform raw import objects into a list of qualified module names
self.imports = set()
for imp in imports:
if isinstance(imp, Import):
for mod in imp.modules:
parts = mod.split('.')
while parts:
self.imports.add('.'.join(parts))
parts.pop()
elif isinstance(imp, FromImport):
source = imp.source
if imp.level > 0:
if imp.level == 1:
imp.source = self.package
else:
parts = self.package.split(".")
imp.source = '.'.join(parts[:1 - imp.level])
if source:
imp.source += '.' + source
parts = imp.source.split('.')
while parts:
self.imports.add('.'.join(parts))
parts.pop()
self.imports.add(imp.source)
for name in imp.names:
parts = name.split('.')
while parts:
self.imports.add(imp.source + '.' + '.'.join(parts))
parts.pop()
def transition(self, context, token, value):
if context.type == "from":
if token == "NAME":
if context.expect == "source":
if value == "import" and context.level:
# syntax "from . import name"
context.expect = "names"
else:
context.source += value
context.expect = "."
elif context.expect == "." and value == "import":
context.expect = "names"
elif context.expect == "names":
context.names.append(value)
context.expect = ","
elif token == "OP":
if value == "," and context.expect == ",":
context.expect = "names"
elif value == "." and context.expect == ".":
context.source += '.'
context.expect = "source"
elif value == "." and context.expect == "source":
context.level += 1
elif context.type == "import":
if token == "NAME":
if context.expect == "module":
if context.modules and context.modules[-1].endswith("."):
context.modules[-1] += value
else:
context.modules.append(value)
context.expect = '.'
elif token == "OP":
if context.expect == ".":
if value == ".":
context.modules[-1] += '.'
context.expect = "module"
class ModulesFinder:
def __init__(self, directory=os.getcwd()):
self.directory = directory
self.modules = set()
def get_imports(self, src, package=None):
"""Get all imports in source code src."""
finder = ImportsFinder(package=package)
finder.find(src)
for module in finder.imports:
if module in self.modules:
continue
found = False
for module_dict in [stdlib, user_modules]:
if module in module_dict:
found = True
self.modules.add(module)
if module_dict[module][0] == '.py':
is_package = len(module_dict[module]) == 4
if is_package:
package = module
elif "." in module:
package = module[:module.rfind(".")]
else:
package = ""
imports = self.get_imports(module_dict[module][1],
package)
return finder.imports
def norm_indent(self, script):
"""Scripts in Brython page may start with an indent, remove it before
building the AST.
"""
indent = None
lines = []
for line in script.split('\n'):
if line.strip() and indent is None:
indent = len(line) - len(line.lstrip())
line = line[indent:]
elif indent is not None:
line = line[indent:]
lines.append(line)
return '\n'.join(lines)
def inspect(self):
"""Walk the directory to find all pages with Brython scripts, parse
them to get the list of modules needed to make them run.
"""
site_packages = 'Lib{0}site-packages{0}'.format(os.sep)
imports = set()
for dirname, dirnames, filenames in os.walk(self.directory):
for name in dirnames:
if name.endswith('__dist__'):
# don't inspect files in the subfolder __dist__
dirnames.remove(name)
break
for filename in filenames:
path = os.path.join(dirname, filename)
if path == __file__:
continue
ext = os.path.splitext(filename)[1]
if ext.lower() == '.html':
print("script in html", filename)
# detect charset
charset_detector = CharsetDetector()
with open(path, encoding="iso-8859-1") as fobj:
charset_detector.feed(fobj.read())
# get text/python scripts
parser = BrythonScriptsExtractor(dirname)
with open(path, encoding=charset_detector.encoding) as fobj:
parser.feed(fobj.read())
for script in parser.scripts:
script = self.norm_indent(script)
try:
imports |= self.get_imports(script)
except SyntaxError:
print('syntax error', path)
traceback.print_exc(file=sys.stderr)
elif ext.lower() == '.py':
print("python", filename)
if filename == "list_modules.py":
continue
if dirname != self.directory and not is_package(dirname):
continue
# get package name
package = dirname[len(self.directory) + 1:] or None
if package is not None and \
package.startswith(site_packages):
package = package[len('Lib/site-packages/'):]
with open(path, encoding="utf-8") as fobj:
try:
imports |= self.get_imports(fobj.read(), package)
except SyntaxError:
print('syntax error', path)
traceback.print_exc(file=sys.stderr)
self.imports = sorted(list(imports))
def make_brython_modules(self):
"""Build brython_modules.js from the list of modules needed by the
application.
"""
print("modules", self.modules, "http" in self.modules)
vfs = {"$timestamp": int(1000 * time.time())}
for module in self.modules:
dico = stdlib if module in stdlib else user_modules
vfs[module] = dico[module]
elts = module.split('.')
for i in range(1, len(elts)):
pkg = '.'.join(elts[:i])
if not pkg in vfs:
vfs[pkg] = dico[pkg]
# save in brython_modules.js
path = os.path.join(stdlib_dir, "brython_modules.js")
with open(path, "w", encoding="utf-8") as out:
# Add VFS_timestamp ; used to test if the indexedDB must be
# refreshed
out.write("__BRYTHON__.VFS_timestamp = {}\n".format(
int(1000 * time.time())))
out.write("__BRYTHON__.use_VFS = true\nvar scripts = ")
json.dump(vfs, out)
out.write("\n__BRYTHON__.update_VFS(scripts)")
def _dest(self, base_dir, dirname, filename):
"""Build the destination path for a file."""
elts = dirname[len(os.getcwd()) + 1:].split(os.sep)
dest_dir = base_dir
for elt in elts:
dest_dir = os.path.join(dest_dir, elt)
if not os.path.exists(dest_dir):
os.mkdir(dest_dir)
return os.path.join(dest_dir, filename)
def make_setup(self):
"""Make the setup script (setup.py) and the entry point script
for the application."""
# Create a temporary directory
temp_dir = '__dist__'
if os.path.exists(temp_dir):
shutil.rmtree(temp_dir)
os.mkdir(temp_dir)
# Create a package "data" in this directory
data_dir = os.path.join(temp_dir, 'data')
os.mkdir(data_dir)
with open(os.path.join(data_dir, "__init__.py"), "w") as out:
out.write('')
# If there is a brython_setup.json file, use it to get information
if os.path.exists("brython_setup.json"):
with open("brython_setup.json", encoding="utf-8") as fobj:
info = json.load(fobj)
else:
# Otherwise, ask setup information
while True:
app_name = input("Application name: ")
if app_name:
break
while True:
version = input("Version: ")
if version:
break
author = input("Author: ")
author_email = input("Author email: ")
license = input("License: ")
url = input("Project url: ")
info = {
"app_name": app_name,
"version": version,
"author": author,
"author_email": author_email,
"license": license,
"url": url
}
# Store information in brython_setup.json
with open("brython_setup.json", "w", encoding="utf-8") as out:
json.dump(info, out, indent=4)
# Store all application files in the temporary directory. In HTML
# pages, replace "brython_stdlib.js" by "brython_modules.js"
files = []
for dirname, dirnames, filenames in os.walk(self.directory):
if dirname == "__dist__":
continue
if "__dist__" in dirnames:
dirnames.remove("__dist__")
for filename in filenames:
path = os.path.join(dirname, filename)
parts = path[len(os.getcwd()) + 1:].split(os.sep)
files.append("os.path.join(" +
", ".join(repr(part) for part in parts) +")")
if os.path.splitext(filename)[1] == '.html':
# detect charset
charset_detector = CharsetDetector()
with open(path, encoding="iso-8859-1") as fobj:
charset_detector.feed(fobj.read())
encoding = charset_detector.encoding
# get text/python scripts
parser = VFSReplacementParser(dirname)
with open(path, encoding=encoding) as fobj:
parser.feed(fobj.read())
if not parser.has_vfs:
# save file
dest = self._dest(data_dir, dirname, filename)
shutil.copyfile(path, dest)
continue
with open(path, encoding=encoding) as fobj:
lines = fobj.readlines()
start_line, start_pos = parser.start
end_line, end_pos = parser.end
res = ''.join(lines[:start_line - 1])
for num in range(start_line - 1, end_line):
res += lines[num].replace("brython_stdlib.js",
"brython_modules.js")
res += ''.join(lines[end_line:])
dest = self._dest(data_dir, dirname, filename)
with | |
<filename>code/src/formatting_functions/formatter.py
import glob
import os
import re
import h5py
import logging
from copy import deepcopy
from joblib import Parallel, delayed
import numpy as np
import scipy.io
import scipy.signal
import mne
from ..preprocessing import filtering
class Formatter:
'''
Base class for dataset formatter.
What this class does:
- Import training/testing EEG data from npz/gdf/vhdr/mat format files.
- Extract labels around each stimulus given parameters.
- Save dataset in a compressed .npz format.
Outputs:
- X: EEG channels data | X.shape = (n_channels, n_samples)
- y: Labels for each timestep | y.shape = (n_samples,)
Parameters:
- root: Folder containing the data
- labels_idx: Stimulus encoding in the input data.
- ch_list: List of channels names to pick (uses MNE -> only for gdf/vhdr).
- remove_ch: Remove given channel names (uses MNE -> only for gdf/vhdr).
- fs: Sampling frequency of the input data.
- pre/post: Region of interest around each stimulus in seconds.
- save: Save the returned dataset.
- mode: Dataset folder to consider ('train'/'test').
- save_path: Path where to save data.
- save_folder: Name of save folder.
- unknown_idx: Index corresponding to unknown event (used during labelling of test data)
'''
def __init__(self, root, save_path, labels_idx, ch_list, remove_ch, pre, post, mode, save, save_folder, resample=False, preprocess=False, unknown_idx=4, fs=250, save_as_trial=False):
self.root = root
self.labels_idx = labels_idx
self.ch_list = ch_list
self.remove_ch = remove_ch
self.fs = fs
self.pre = pre
self.post = post
self.save = save
self.mode = mode
self.save_path = save_path
self.save_folder = save_folder
self.unknown_idx = unknown_idx
self.resample = resample
self.preprocess = preprocess
self.save_as_trial = save_as_trial
def extracting(self, raw):
# Resampling
if self.resample:
print('Resampling from {} Hz to 250 Hz'.format(raw.info['sfreq']))
raw.resample(250, npad="auto")
# Extract labels array
events = mne.events_from_annotations(raw)[0]
print('Detected labels: ', np.unique(events[:, -1]))
# Extract sample frequency
self.fs = raw.info['sfreq']
print('Sampling frequency: ', self.fs)
# Extract mapping
mapping = mne.events_from_annotations(raw)[1]
for key, val in mapping.items():
print(key, val)
# Extract channels
if self.remove_ch:
print('Removing the following channels: ', self.remove_ch)
raw.drop_channels(self.remove_ch)
if self.ch_list:
print('Extracting the following channels: ', self.ch_list)
raw.pick_channels(self.ch_list)
# Preprocessing
print('Numerical stability & filtering...')
raw = mne_apply(lambda a: a * 1e6, raw)
if self.preprocess:
raw = mne_apply(lambda a: filtering(a, f_low=0.5,
f_high=100,
fs=raw.info["sfreq"],
f_order=5), raw)
# Convert to numpy array
eeg = raw.get_data(verbose=False)
logging.info('Signal shape: ', eeg.shape)
# Reshape from (n_samples, n_channels) to (n_channels, n_samples)
return eeg, events, mapping
def labelling(self, events, signal_len, file_idx):
print("Counting labels before labelling")
for label in np.unique(events[:, -1]):
print("\t {}: {:.2f}".format(label, len(
np.where(events[:, -1] == label)[0])))
# Extract labels
if self.mode == "train":
labels = self.labelling_train(events, signal_len)
elif self.mode == "test":
data = scipy.io.loadmat(
self.root + 'test/labels/{}.mat'.format(file_idx))
true_labels = np.array(
data['classlabel']) + min(self.labels_idx) - 1
print('True labels set: ', np.unique(true_labels))
labels = self.labelling_test(events, signal_len,
true_labels, self.unknown_idx)
# Sanity check
print("Counting labels after labelling")
for label in self.labels_idx:
print("\t {}: {:.2f}".format(label, len(
np.where(labels == label)[0]) / (self.fs*(self.pre + self.post))))
return labels
def labelling_train(self, events, signal_len):
labels = np.zeros(signal_len, dtype=np.int16)
# Convert window boundaries from s to nbr of time samples
thresh_pre = int(self.pre*self.fs)
thresh_post = int(self.post*self.fs)
# Extract [pre,post] time window around each event
for t, _, label in events:
if label in self.labels_idx:
labels[t-thresh_pre:t+thresh_post] = label
print("Finished labelling...")
return labels
def labelling_test(self, events, signal_len, true_labels, event_id):
labels = np.zeros(signal_len, dtype=np.int16)
cnt = 0
# Convert window boundaries from s to nbr of time samples
thresh_pre = int(self.pre*self.fs)
thresh_post = int(self.post*self.fs)
# Extract [pre,post] time window around each event
for t, _, label in events:
if label == event_id:
labels[t-thresh_pre:t+thresh_post] = true_labels[cnt]
cnt += 1
print("Finished labelling...")
return labels
def cutting(self, eeg, labels_in):
n_channels, n_samples_in = eeg.shape
trials = []
labels = []
trial = np.empty((n_channels, 0))
for label in self.labels_idx:
print("Processing trials of class {}...".format(label))
idxs = np.where(labels_in == label)[0]
trial = np.empty((n_channels, 0))
# Go through each corresponding index, append eeg[idxs[i]] to current trial until idxs[i+1]-idx[i] > thresh
for i in range(len(idxs)):
if (idxs[i] - idxs[i-1]) > self.fs/20: # Detect new trial
trials.append(trial)
labels.append(label)
trial = np.empty((n_channels, 0))
sample = np.reshape(eeg[:, idxs[i]], (n_channels, 1))
trial = np.append(trial, sample, axis=1)
if i == len(idxs)-1: # Detect end of last trial
trials.append(trial)
labels.append(label)
trials = np.reshape(trials, (-1, n_channels, trial.shape[-1]))
labels = np.reshape(labels, (-1,))
print("Cutting successful ! Shape: {}".format(trials.shape))
return trials, labels
def saving(self, X, y=None, file_name='data1'):
if self.save_folder not in os.listdir(self.save_path):
os.mkdir(path=self.save_path + self.save_folder)
if self.mode not in os.listdir(self.save_path + self.save_folder):
os.mkdir(path=self.save_path + self.save_folder +
'/{}'.format(self.mode))
# Remap labels
y = y - np.min(y)
# Reorder indexing
idx = np.argsort(y)
X, y = X[idx], y[idx]
if self.save_as_trial:
for trial_idx in range(X.shape[0]):
np.savez_compressed(self.save_path + '{}/{}/{}'.format(
self.save_folder, self.mode, trial_idx), X=X[trial_idx], y=y[trial_idx])
else:
print("Saving data of shape: ", X.shape)
np.savez_compressed(
self.save_path + '{}/{}/{}'.format(self.save_folder, self.mode, file_name), X=X, y=y)
print('Saved successfully ! \n')
class FormatterNPZ(Formatter):
def __init__(self, root, save_path, labels_idx, ch_list, remove_ch, pre, post, fs, mode, save, save_folder):
super().__init__(root, save_path, labels_idx, ch_list,
remove_ch, pre, post, mode, save, save_folder, fs=fs)
self.unknown_idx = 783
def run(self):
# Get all filepaths for each pilot data
if self.mode == "train":
filepaths = glob.glob(self.root + "train/*T.npz")
else:
filepaths = glob.glob(self.root + "test/*E.npz")
for pilot_idx, filepath in enumerate(filepaths):
print("Start formatting " + filepath + "...")
# Extract EEG signal
raw = np.load(filepath)
# Extract events & reshape EEG signal from (n_samples, n_channels) to (n_channels, n_samples)
eeg = raw['s']
events = np.stack(
[raw['epos'].reshape(-1), raw['edur'].reshape(-1), raw['etyp'].reshape(-1)], axis=1)
eeg = np.swapaxes(eeg, 0, 1)
# Labelling
to_find = r'A\d+T|B\d+T' if self.mode == 'train' else r'A\d+E|B\d+E'
file_idx = re.findall(to_find, filepath)[0]
print(file_idx)
labels = self.labelling(events, eeg.shape[-1], file_idx)
# Cutting
eeg, labels = self.cutting(eeg, labels)
# Save as .npy file
if self.save:
self.saving(eeg, labels, '{}{}'.format(self.mode, pilot_idx+1))
print("")
return print("Successfully converted all {} ".format(len(filepaths)) + self.mode + "ing data !")
class FormatterGDF(Formatter):
def __init__(self, root, save_path, labels_idx, ch_list, remove_ch, pre, post, mode, save, save_folder, resample=False, preprocess=False, unknown_idx=4, fs=None, save_as_trial=False, multisession=False, multithread=False):
super().__init__(root, save_path, labels_idx, ch_list, remove_ch, pre, post,
mode, save, save_folder, resample, preprocess, unknown_idx, fs, save_as_trial)
self.labels_idx_saved = labels_idx
self.multisession = multisession
self.multithread = multithread
def run(self):
# Get all filepaths for each pilot data
if self.mode == "train":
filepaths_all = glob.glob(self.root + "train/*T.gdf")
elif self.mode == "test":
filepaths_all = glob.glob(self.root + "test/*E.gdf")
else:
print("Please choose among these two modes {train, test}.")
return
# Clustering common pilot data
if self.multisession:
filepaths_pilots = [[]]
pilot_idx = 0
to_find = r'B\d+T' if self.mode == 'train' else r'B\d+E'
# In case of dataset IV 2b, there are multiple training sessions per subject
for filepath in filepaths_all:
if int(re.findall(to_find, filepath)[0][2]) == pilot_idx:
pass
else:
pilot_idx += 1
filepaths_pilots.append([])
filepaths_pilots[pilot_idx].append(filepath)
filepaths_pilots.pop(0) # Remove []
print(filepaths_pilots)
else:
filepaths_pilots = [[path] for path in filepaths_all]
# Multi-threading allows for faster processing (only after debugging complete)
if self.multithread:
num_cores = -1 # Use all processors but one
results = Parallel(n_jobs=num_cores, verbose=100)(delayed(self.sub_run)(
pilot, filepaths_pilot) for pilot, filepaths_pilot in enumerate(filepaths_pilots))
else:
for pilot, filepaths_pilot in enumerate(filepaths_pilots):
print('Pilot ', pilot+1)
self.sub_run(pilot, filepaths_pilot)
return print("Successfully converted all {} ".format(len(filepaths_pilots)) + self.mode + "ing data !")
def sub_run(self, pilot_idx, filepaths_pilot):
pilot_eeg = np.array([])
pilot_labels = np.array([])
to_find = r'A\d+T|B\d+T' if self.mode == 'train' else r'A\d+E|B\d+E'
for session_idx in range(len(filepaths_pilot)):
print("Start formatting " + filepaths_pilot[session_idx] + "...")
print('Session {}'.format(session_idx+1))
# Quick fix for session 3 of dataset BCIC IV 2b
if session_idx == 2:
self.labels_idx_saved = self.labels_idx
self.labels_idx = [4, 5]
else:
self.labels_idx = self.labels_idx_saved
file_idx = re.findall(to_find, filepaths_pilot[session_idx])[0]
# Import raw EEG signal (should be a .gdf file)
raw = mne.io.read_raw_gdf(
filepaths_pilot[session_idx], preload=True)
# Extract eeg, events and map encodings
eeg, events, mapping = self.extracting(raw)
# Labelling
labels = self.labelling(events, eeg.shape[-1], file_idx)
# Cutting trials
eeg, labels = self.cutting(eeg, labels)
# Remap labels
labels = labels - np.min(labels)
print('Output labels', np.unique(labels))
# Stack trials
if len(pilot_eeg) == 0:
pilot_eeg = eeg
pilot_labels = labels
else:
pilot_eeg = np.vstack([pilot_eeg, eeg])
pilot_labels = np.concatenate([pilot_labels, labels])
# Save as .npy file
if self.save:
self.saving(pilot_eeg, pilot_labels,
'{}{}'.format(self.mode, pilot_idx+1))
print("")
class FormatterVHDR(Formatter):
def __init__(self, root, save_path, pilot_idx, session_idx, labels_idx, ch_list, remove_ch, pre, post, mode, save, save_folder, resample=False, preprocess=False, unknown_idx=4, control=False, save_as_trial=False):
super().__init__(root, save_path, labels_idx, ch_list, remove_ch, pre, post, mode, save,
save_folder, resample, | |
from msg import ReqMsg
from cmds import Cmd
class Window(Cmd):
def __init__(self, session):
self._session = session
# Function: window_get_buffer
# Parameters Window: window
# Returns Buffer
# Recieves channel id False
# Can fail True
def get_buffer(self, window):
return self.send_sync(ReqMsg('window_get_buffer', *[window]))
# Function: window_get_cursor
# Parameters Window: window
# Returns ArrayOf(Integer, 2)
# Recieves channel id False
# Can fail True
def get_cursor(self, window):
return self.send_sync(ReqMsg('window_get_cursor', *[window]))
# Function: window_set_cursor
# Parameters Window: window, ArrayOf(Integer, 2): pos
# Returns void
# Recieves channel id False
# Can fail True
def set_cursor(self, window, pos):
return self.send_sync(ReqMsg('window_set_cursor', *[window, pos]))
# Function: window_get_height
# Parameters Window: window
# Returns Integer
# Recieves channel id False
# Can fail True
def get_height(self, window):
return self.send_sync(ReqMsg('window_get_height', *[window]))
# Function: window_set_height
# Parameters Window: window, Integer: height
# Returns void
# Recieves channel id False
# Can fail True
def set_height(self, window, height):
return self.send_sync(ReqMsg('window_set_height', *[window, height]))
# Function: window_get_width
# Parameters Window: window
# Returns Integer
# Recieves channel id False
# Can fail True
def get_width(self, window):
return self.send_sync(ReqMsg('window_get_width', *[window]))
# Function: window_set_width
# Parameters Window: window, Integer: width
# Returns void
# Recieves channel id False
# Can fail True
def set_width(self, window, width):
return self.send_sync(ReqMsg('window_set_width', *[window, width]))
# Function: window_get_var
# Parameters Window: window, String: name
# Returns Object
# Recieves channel id False
# Can fail True
def get_var(self, window, name):
return self.send_sync(ReqMsg('window_get_var', *[window, name]))
# Function: window_set_var
# Parameters Window: window, String: name, Object: value
# Returns Object
# Recieves channel id False
# Can fail True
def set_var(self, window, name, value):
return self.send_sync(ReqMsg('window_set_var', *[window, name, value]))
# Function: window_get_option
# Parameters Window: window, String: name
# Returns Object
# Recieves channel id False
# Can fail True
def get_option(self, window, name):
return self.send_sync(ReqMsg('window_get_option', *[window, name]))
# Function: window_set_option
# Parameters Window: window, String: name, Object: value
# Returns void
# Recieves channel id False
# Can fail True
def set_option(self, window, name, value):
return self.send_sync(ReqMsg('window_set_option', *[window, name, value]))
# Function: window_get_position
# Parameters Window: window
# Returns ArrayOf(Integer, 2)
# Recieves channel id False
# Can fail True
def get_position(self, window):
return self.send_sync(ReqMsg('window_get_position', *[window]))
# Function: window_get_tabpage
# Parameters Window: window
# Returns Tabpage
# Recieves channel id False
# Can fail True
def get_tabpage(self, window):
return self.send_sync(ReqMsg('window_get_tabpage', *[window]))
# Function: window_is_valid
# Parameters Window: window
# Returns Boolean
# Recieves channel id False
# Can fail False
def is_valid(self, window):
return self.send_sync(ReqMsg('window_is_valid', *[window]))
class Buffer(Cmd):
def __init__(self, session):
self._session = session
# Function: buffer_line_count
# Parameters Buffer: buffer
# Returns Integer
# Recieves channel id False
# Can fail True
def line_count(self, buffer):
return self.send_sync(ReqMsg('buffer_line_count', *[buffer]))
# Function: buffer_get_line
# Parameters Buffer: buffer, Integer: index
# Returns String
# Recieves channel id False
# Can fail True
def get_line(self, buffer, index):
return self.send_sync(ReqMsg('buffer_get_line', *[buffer, index]))
# Function: buffer_set_line
# Parameters Buffer: buffer, Integer: index, String: line
# Returns void
# Recieves channel id False
# Can fail True
def set_line(self, buffer, index, line):
return self.send_sync(ReqMsg('buffer_set_line', *[buffer, index, line]))
# Function: buffer_del_line
# Parameters Buffer: buffer, Integer: index
# Returns void
# Recieves channel id False
# Can fail True
def del_line(self, buffer, index):
return self.send_sync(ReqMsg('buffer_del_line', *[buffer, index]))
# Function: buffer_get_line_slice
# Parameters Buffer: buffer, Integer: start, Integer: end, Boolean: include_start, Boolean: include_end
# Returns ArrayOf(String)
# Recieves channel id False
# Can fail True
def get_line_slice(self, buffer, start, end, include_start, include_end):
return self.send_sync(ReqMsg('buffer_get_line_slice', *[buffer, start, end, include_start, include_end]))
# Function: buffer_set_line_slice
# Parameters Buffer: buffer, Integer: start, Integer: end, Boolean: include_start, Boolean: include_end, ArrayOf(String): replacement
# Returns void
# Recieves channel id False
# Can fail True
def set_line_slice(self, buffer, start, end, include_start, include_end, replacement):
return self.send_sync(ReqMsg('buffer_set_line_slice', *[buffer, start, end, include_start, include_end, replacement]))
# Function: buffer_get_var
# Parameters Buffer: buffer, String: name
# Returns Object
# Recieves channel id False
# Can fail True
def get_var(self, buffer, name):
return self.send_sync(ReqMsg('buffer_get_var', *[buffer, name]))
# Function: buffer_set_var
# Parameters Buffer: buffer, String: name, Object: value
# Returns Object
# Recieves channel id False
# Can fail True
def set_var(self, buffer, name, value):
return self.send_sync(ReqMsg('buffer_set_var', *[buffer, name, value]))
# Function: buffer_get_option
# Parameters Buffer: buffer, String: name
# Returns Object
# Recieves channel id False
# Can fail True
def get_option(self, buffer, name):
return self.send_sync(ReqMsg('buffer_get_option', *[buffer, name]))
# Function: buffer_set_option
# Parameters Buffer: buffer, String: name, Object: value
# Returns void
# Recieves channel id False
# Can fail True
def set_option(self, buffer, name, value):
return self.send_sync(ReqMsg('buffer_set_option', *[buffer, name, value]))
# Function: buffer_get_number
# Parameters Buffer: buffer
# Returns Integer
# Recieves channel id False
# Can fail True
def get_number(self, buffer):
return self.send_sync(ReqMsg('buffer_get_number', *[buffer]))
# Function: buffer_get_name
# Parameters Buffer: buffer
# Returns String
# Recieves channel id False
# Can fail True
def get_name(self, buffer):
return self.send_sync(ReqMsg('buffer_get_name', *[buffer]))
# Function: buffer_set_name
# Parameters Buffer: buffer, String: name
# Returns void
# Recieves channel id False
# Can fail True
def set_name(self, buffer, name):
return self.send_sync(ReqMsg('buffer_set_name', *[buffer, name]))
# Function: buffer_is_valid
# Parameters Buffer: buffer
# Returns Boolean
# Recieves channel id False
# Can fail False
def is_valid(self, buffer):
return self.send_sync(ReqMsg('buffer_is_valid', *[buffer]))
# Function: buffer_insert
# Parameters Buffer: buffer, Integer: lnum, ArrayOf(String): lines
# Returns void
# Recieves channel id False
# Can fail True
def insert(self, buffer, lnum, lines):
return self.send_sync(ReqMsg('buffer_insert', *[buffer, lnum, lines]))
# Function: buffer_get_mark
# Parameters Buffer: buffer, String: name
# Returns ArrayOf(Integer, 2)
# Recieves channel id False
# Can fail True
def get_mark(self, buffer, name):
return self.send_sync(ReqMsg('buffer_get_mark', *[buffer, name]))
class Tabpage(Cmd):
def __init__(self, session):
self._session = session
# Function: tabpage_get_windows
# Parameters Tabpage: tabpage
# Returns ArrayOf(Window)
# Recieves channel id False
# Can fail True
def get_windows(self, tabpage):
return self.send_sync(ReqMsg('tabpage_get_windows', *[tabpage]))
# Function: tabpage_get_var
# Parameters Tabpage: tabpage, String: name
# Returns Object
# Recieves channel id False
# Can fail True
def get_var(self, tabpage, name):
return self.send_sync(ReqMsg('tabpage_get_var', *[tabpage, name]))
# Function: tabpage_set_var
# Parameters Tabpage: tabpage, String: name, Object: value
# Returns Object
# Recieves channel id False
# Can fail True
def set_var(self, tabpage, name, value):
return self.send_sync(ReqMsg('tabpage_set_var', *[tabpage, name, value]))
# Function: tabpage_get_window
# Parameters Tabpage: tabpage
# Returns Window
# Recieves channel id False
# Can fail True
def get_window(self, tabpage):
return self.send_sync(ReqMsg('tabpage_get_window', *[tabpage]))
# Function: tabpage_is_valid
# Parameters Tabpage: tabpage
# Returns Boolean
# Recieves channel id False
# Can fail False
def is_valid(self, tabpage):
return self.send_sync(ReqMsg('tabpage_is_valid', *[tabpage]))
class Vim(Cmd):
def __init__(self, session):
self._session = session
# Function: vim_push_keys
# Parameters String: str
# Returns void
# Recieves channel id False
# Can fail False
def push_keys(self, v_str):
return self.send_sync(ReqMsg('vim_push_keys', *[v_str]))
# Function: vim_command
# Parameters String: str
# Returns void
# Recieves channel id False
# Can fail True
def command(self, v_str):
return self.send_sync(ReqMsg('vim_command', *[v_str]))
# Function: vim_feedkeys
# Parameters String: keys, String: mode
# Returns void
# Recieves channel id False
# Can fail False
def feedkeys(self, keys, mode):
return self.send_sync(ReqMsg('vim_feedkeys', *[keys, mode]))
# Function: vim_replace_termcodes
# Parameters String: str, Boolean: from_part, Boolean: do_lt, Boolean: special
# Returns String
# Recieves channel id False
# Can fail False
def replace_termcodes(self, v_str, from_part, do_lt, special):
return self.send_sync(ReqMsg('vim_replace_termcodes', *[v_str, from_part, do_lt, special]))
# Function: vim_eval
# Parameters String: str
# Returns Object
# Recieves channel id False
# Can fail True
def eval(self, v_str):
return self.send_sync(ReqMsg('vim_eval', *[v_str]))
# Function: vim_strwidth
# Parameters String: str
# Returns Integer
# Recieves channel id False
# Can fail True
def strwidth(self, v_str):
return self.send_sync(ReqMsg('vim_strwidth', *[v_str]))
# Function: vim_list_runtime_paths
# Parameters
# Returns ArrayOf(String)
# Recieves channel id False
# Can fail False
def list_runtime_paths(self, ):
return self.send_sync(ReqMsg('vim_list_runtime_paths', *[]))
# Function: vim_change_directory
# Parameters String: dir
# Returns void
# Recieves channel id False
# Can fail True
def change_directory(self, v_dir):
return self.send_sync(ReqMsg('vim_change_directory', *[v_dir]))
# Function: vim_get_current_line
# Parameters
# Returns String
# Recieves | |
the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values.
:type op_ConfigLocked: String
| ``api version min:`` None
| ``api version max:`` None
| ``required:`` False
| ``default:`` None
:param val_f_ConfigLocked: If op_ConfigLocked is specified, the field named in this input will be compared to the value in ConfigLocked using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_ConfigLocked must be specified if op_ConfigLocked is specified.
:type val_f_ConfigLocked: String
| ``api version min:`` None
| ``api version max:`` None
| ``required:`` False
| ``default:`` None
:param val_c_ConfigLocked: If op_ConfigLocked is specified, this value will be compared to the value in ConfigLocked using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_ConfigLocked must be specified if op_ConfigLocked is specified.
:type val_c_ConfigLocked: String
| ``api version min:`` None
| ``api version max:`` None
| ``required:`` False
| ``default:`` None
:param op_ConfigPolling: The operator to apply to the field ConfigPolling. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. ConfigPolling: 1 if NetMRI configuration collection is enabled for the device group members; 0 otherwise. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values.
:type op_ConfigPolling: String
| ``api version min:`` None
| ``api version max:`` None
| ``required:`` False
| ``default:`` None
:param val_f_ConfigPolling: If op_ConfigPolling is specified, the field named in this input will be compared to the value in ConfigPolling using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_ConfigPolling must be specified if op_ConfigPolling is specified.
:type val_f_ConfigPolling: String
| ``api version min:`` None
| ``api version max:`` None
| ``required:`` False
| ``default:`` None
:param val_c_ConfigPolling: If op_ConfigPolling is specified, this value will be compared to the value in ConfigPolling using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_ConfigPolling must be specified if op_ConfigPolling is specified.
:type val_c_ConfigPolling: String
| ``api version min:`` None
| ``api version max:`` None
| ``required:`` False
| ``default:`` None
:param op_CredentialGroupID: The operator to apply to the field CredentialGroupID. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. CredentialGroupID: The unique identifier of the credential group. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values.
:type op_CredentialGroupID: String
| ``api version min:`` None
| ``api version max:`` None
| ``required:`` False
| ``default:`` None
:param val_f_CredentialGroupID: If op_CredentialGroupID is specified, the field named in this input will be compared to the value in CredentialGroupID using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_CredentialGroupID must be specified if op_CredentialGroupID is specified.
:type val_f_CredentialGroupID: String
| ``api version min:`` None
| ``api version max:`` None
| ``required:`` False
| ``default:`` None
:param val_c_CredentialGroupID: If op_CredentialGroupID is specified, this value will be compared to the value in CredentialGroupID using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_CredentialGroupID must be specified if op_CredentialGroupID is specified.
:type val_c_CredentialGroupID: String
| ``api version min:`` None
| ``api version max:`` None
| ``required:`` False
| ``default:`` None
:param op_Criteria: The operator to apply to the field Criteria. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. Criteria: The criteria used to define membership within this device group. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values.
:type op_Criteria: String
| ``api version min:`` None
| ``api version max:`` None
| ``required:`` False
| ``default:`` None
:param val_f_Criteria: If op_Criteria is specified, the field named in this input will be compared to the value in Criteria using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_Criteria must be specified if op_Criteria is specified.
:type val_f_Criteria: String
| ``api version min:`` None
| ``api version max:`` None
| ``required:`` False
| ``default:`` None
:param val_c_Criteria: If op_Criteria is specified, this value will be compared to the value in Criteria using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_Criteria must be specified if op_Criteria is specified.
:type val_c_Criteria: String
| ``api version min:`` None
| ``api version max:`` None
| ``required:`` False
| ``default:`` None
:param op_DataSourceID: The operator to apply to the field DataSourceID. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. DataSourceID: The internal NetMRI identifier for the collector NetMRI that collected this data record. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values.
:type op_DataSourceID: String
| ``api version min:`` None
| ``api version max:`` None
| ``required:`` False
| ``default:`` None
:param val_f_DataSourceID: If op_DataSourceID is specified, the field named in this input will be compared to the value in DataSourceID using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_DataSourceID must be specified if op_DataSourceID is specified.
:type val_f_DataSourceID: String
| ``api version min:`` None
| ``api version max:`` None
| ``required:`` False
| ``default:`` None
:param val_c_DataSourceID: If op_DataSourceID is specified, this value will be compared to the value in DataSourceID using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_DataSourceID must be specified if op_DataSourceID is specified.
:type val_c_DataSourceID: String
| ``api version min:`` None
| ``api version max:`` None
| ``required:`` False
| ``default:`` None
:param op_DeviceGroupChangedCols: The operator to apply to the field DeviceGroupChangedCols. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. DeviceGroupChangedCols: The fields that changed between this revision of the record and the previous revision. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values.
:type op_DeviceGroupChangedCols: String
| ``api version min:`` None
| ``api version max:`` None
| ``required:`` False
| ``default:`` None
:param val_f_DeviceGroupChangedCols: If op_DeviceGroupChangedCols is specified, the field named in this input will be compared to the value in DeviceGroupChangedCols using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_DeviceGroupChangedCols must be specified if op_DeviceGroupChangedCols is specified.
:type val_f_DeviceGroupChangedCols: String
| ``api version min:`` None
| ``api version max:`` None
| ``required:`` False
| ``default:`` None
:param val_c_DeviceGroupChangedCols: If op_DeviceGroupChangedCols is specified, this value will be compared to the value in DeviceGroupChangedCols using the specified operator. The value in | |
*(dict) --*
Information about a Session Manager connection to an instance.
- **SessionId** *(string) --*
The ID of the session.
- **Target** *(string) --*
The instance that the Session Manager session connected to.
- **Status** *(string) --*
The status of the session. For example, "Connected" or "Terminated".
- **StartDate** *(datetime) --*
The date and time, in ISO-8601 Extended format, when the session began.
- **EndDate** *(datetime) --*
The date and time, in ISO-8601 Extended format, when the session was terminated.
- **DocumentName** *(string) --*
The name of the Session Manager SSM document used to define the parameters and plugin settings for the session. For example, ``SSM-SessionManagerRunShell`` .
- **Owner** *(string) --*
The ID of the AWS user account that started the session.
- **Details** *(string) --*
Reserved for future use.
- **OutputUrl** *(dict) --*
Reserved for future use.
- **S3OutputUrl** *(string) --*
Reserved for future use.
- **CloudWatchOutputUrl** *(string) --*
Reserved for future use.
:type State: string
:param State: **[REQUIRED]**
The session status to retrieve a list of sessions for. For example, \"Active\".
:type Filters: list
:param Filters:
One or more filters to limit the type of sessions returned by the request.
- *(dict) --*
Describes a filter for Session Manager information.
- **key** *(string) --* **[REQUIRED]**
The name of the filter.
- **value** *(string) --* **[REQUIRED]**
The filter value. Valid values for each filter key are as follows:
* InvokedAfter: Specify a timestamp to limit your results. For example, specify 2018-08-29T00:00:00Z to see sessions that started August 29, 2018, and later.
* InvokedBefore: Specify a timestamp to limit your results. For example, specify 2018-08-29T00:00:00Z to see sessions that started before August 29, 2018.
* Target: Specify an instance to which session connections have been made.
* Owner: Specify an AWS user account to see a list of sessions started by that user.
* Status: Specify a valid session status to see a list of all sessions with that status. Status values you can specify include:
* Connected
* Connecting
* Disconnected
* Terminated
* Terminating
* Failed
:type PaginationConfig: dict
:param PaginationConfig:
A dictionary that provides parameters to control pagination.
- **MaxItems** *(integer) --*
The total number of items to return. If the total number of items available is more than the value specified in max-items then a ``NextToken`` will be provided in the output that you can use to resume pagination.
- **PageSize** *(integer) --*
The size of each page.
- **StartingToken** *(string) --*
A token to specify where to start paginating. This is the ``NextToken`` from a previous response.
:rtype: dict
:returns:
"""
pass
class GetInventory(Paginator):
def paginate(self, Filters: List = None, Aggregators: List = None, ResultAttributes: List = None, PaginationConfig: Dict = None) -> Dict:
"""
Creates an iterator that will paginate through responses from :py:meth:`SSM.Client.get_inventory`.
See also: `AWS API Documentation <https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/GetInventory>`_
**Request Syntax**
::
response_iterator = paginator.paginate(
Filters=[
{
'Key': 'string',
'Values': [
'string',
],
'Type': 'Equal'|'NotEqual'|'BeginWith'|'LessThan'|'GreaterThan'|'Exists'
},
],
Aggregators=[
{
'Expression': 'string',
'Aggregators': {'... recursive ...'},
'Groups': [
{
'Name': 'string',
'Filters': [
{
'Key': 'string',
'Values': [
'string',
],
'Type': 'Equal'|'NotEqual'|'BeginWith'|'LessThan'|'GreaterThan'|'Exists'
},
]
},
]
},
],
ResultAttributes=[
{
'TypeName': 'string'
},
],
PaginationConfig={
'MaxItems': 123,
'PageSize': 123,
'StartingToken': 'string'
}
)
**Response Syntax**
::
{
'Entities': [
{
'Id': 'string',
'Data': {
'string': {
'TypeName': 'string',
'SchemaVersion': 'string',
'CaptureTime': 'string',
'ContentHash': 'string',
'Content': [
{
'string': 'string'
},
]
}
}
},
],
}
**Response Structure**
- *(dict) --*
- **Entities** *(list) --*
Collection of inventory entities such as a collection of instance inventory.
- *(dict) --*
Inventory query results.
- **Id** *(string) --*
ID of the inventory result entity. For example, for managed instance inventory the result will be the managed instance ID. For EC2 instance inventory, the result will be the instance ID.
- **Data** *(dict) --*
The data section in the inventory result entity JSON.
- *(string) --*
- *(dict) --*
The inventory result item.
- **TypeName** *(string) --*
The name of the inventory result item type.
- **SchemaVersion** *(string) --*
The schema version for the inventory result item/
- **CaptureTime** *(string) --*
The time inventory item data was captured.
- **ContentHash** *(string) --*
MD5 hash of the inventory item type contents. The content hash is used to determine whether to update inventory information. The PutInventory API does not update the inventory item type contents if the MD5 hash has not changed since last update.
- **Content** *(list) --*
Contains all the inventory data of the item type. Results include attribute names and values.
- *(dict) --*
- *(string) --*
- *(string) --*
:type Filters: list
:param Filters:
One or more filters. Use a filter to return a more specific list of results.
- *(dict) --*
One or more filters. Use a filter to return a more specific list of results.
- **Key** *(string) --* **[REQUIRED]**
The name of the filter key.
- **Values** *(list) --* **[REQUIRED]**
Inventory filter values. Example: inventory filter where instance IDs are specified as values Key=AWS:InstanceInformation.InstanceId,Values= i-a12b3c4d5e6g, i-1a2b3c4d5e6,Type=Equal
- *(string) --*
- **Type** *(string) --*
The type of filter. Valid values include the following: \"Equal\"|\"NotEqual\"|\"BeginWith\"|\"LessThan\"|\"GreaterThan\"
:type Aggregators: list
:param Aggregators:
Returns counts of inventory types based on one or more expressions. For example, if you aggregate by using an expression that uses the ``AWS:InstanceInformation.PlatformType`` type, you can see a count of how many Windows and Linux instances exist in your inventoried fleet.
- *(dict) --*
Specifies the inventory type and attribute for the aggregation execution.
- **Expression** *(string) --*
The inventory type and attribute name for aggregation.
- **Aggregators** *(list) --*
Nested aggregators to further refine aggregation for an inventory type.
- **Groups** *(list) --*
A user-defined set of one or more filters on which to aggregate inventory data. Groups return a count of resources that match and don\'t match the specified criteria.
- *(dict) --*
A user-defined set of one or more filters on which to aggregate inventory data. Groups return a count of resources that match and don\'t match the specified criteria.
- **Name** *(string) --* **[REQUIRED]**
The name of the group.
- **Filters** *(list) --* **[REQUIRED]**
Filters define the criteria for the group. The ``matchingCount`` field displays the number of resources that match the criteria. The ``notMatchingCount`` field displays the number of resources that don\'t match the criteria.
- *(dict) --*
One or more filters. Use a filter to return a more specific list of results.
- **Key** *(string) --* **[REQUIRED]**
The name of the filter key.
- **Values** *(list) --* **[REQUIRED]**
Inventory filter values. Example: inventory filter where instance IDs are specified as values Key=AWS:InstanceInformation.InstanceId,Values= i-a12b3c4d5e6g, i-1a2b3c4d5e6,Type=Equal
- *(string) --*
- **Type** *(string) --*
The type of filter. Valid values include the following: \"Equal\"|\"NotEqual\"|\"BeginWith\"|\"LessThan\"|\"GreaterThan\"
:type ResultAttributes: list
:param ResultAttributes:
The list of inventory item types to return.
- *(dict) --*
The inventory item result attribute.
- **TypeName** *(string) --* **[REQUIRED]**
Name of the inventory item type. Valid value: AWS:InstanceInformation. Default Value: AWS:InstanceInformation.
:type PaginationConfig: dict
:param PaginationConfig:
A dictionary that provides parameters to control pagination.
- **MaxItems** *(integer) --*
The total number of items to return. If the total number of items available is more than the value specified in max-items then a ``NextToken`` will be provided in the output that you can use to resume pagination.
- **PageSize** *(integer) --*
The size of each page.
- **StartingToken** *(string) --*
A token to specify where to start paginating. This is the ``NextToken`` from a previous response.
:rtype: dict
:returns:
"""
pass
class GetInventorySchema(Paginator):
def paginate(self, TypeName: str = None, Aggregator: bool = None, SubType: bool = None, PaginationConfig: | |
formatted using
d3-format's syntax %{variable:d3-format}, for example
"Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api-
reference/blob/master/Formatting.md#d3_format for
details on the formatting syntax. Dates are formatted
using d3-time-format's syntax %{variable|d3-time-
format}, for example "Day: %{2019-01-01|%A}".
https://github.com/d3/d3-time-format#locale_format for
details on the date formatting syntax. Every attributes
that can be specified per-point (the ones that are
`arrayOk: true`) are available. variables `initial`,
`delta`, `final` and `label`.
texttemplatesrc
Sets the source reference on Chart Studio Cloud for
texttemplate .
totals
:class:`plotly.graph_objects.waterfall.Totals` instance
or dict with compatible properties
uid
Assign an id to this trace, Use this to provide object
constancy between traces during animations and
transitions.
uirevision
Controls persistence of some user-driven changes to the
trace: `constraintrange` in `parcoords` traces, as well
as some `editable: true` modifications such as `name`
and `colorbar.title`. Defaults to `layout.uirevision`.
Note that other user-driven trace attribute changes are
controlled by `layout` attributes: `trace.visible` is
controlled by `layout.legend.uirevision`,
`selectedpoints` is controlled by
`layout.selectionrevision`, and `colorbar.(x|y)`
(accessible with `config: {editable: true}`) is
controlled by `layout.editrevision`. Trace changes are
tracked by `uid`, which only falls back on trace index
if no `uid` is provided. So if your app can add/remove
traces before the end of the `data` array, such that
the same trace has a different index, you can still
preserve user-driven changes if you give each trace a
`uid` that stays with it as it moves.
visible
Determines whether or not this trace is visible. If
"legendonly", the trace is not drawn, but can appear as
a legend item (provided that the legend itself is
visible).
width
Sets the bar width (in position axis units).
widthsrc
Sets the source reference on Chart Studio Cloud for
width .
x
Sets the x coordinates.
x0
Alternate to `x`. Builds a linear space of x
coordinates. Use with `dx` where `x0` is the starting
coordinate and `dx` the step.
xaxis
Sets a reference between this trace's x coordinates and
a 2D cartesian x axis. If "x" (the default value), the
x coordinates refer to `layout.xaxis`. If "x2", the x
coordinates refer to `layout.xaxis2`, and so on.
xperiod
Only relevant when the axis `type` is "date". Sets the
period positioning in milliseconds or "M<n>" on the x
axis. Special values in the form of "M<n>" could be
used to declare the number of months. In this case `n`
must be a positive integer.
xperiod0
Only relevant when the axis `type` is "date". Sets the
base for period positioning in milliseconds or date
string on the x0 axis. When `x0period` is round number
of weeks, the `x0period0` by default would be on a
Sunday i.e. 2000-01-02, otherwise it would be at
2000-01-01.
xperiodalignment
Only relevant when the axis `type` is "date". Sets the
alignment of data points on the x axis.
xsrc
Sets the source reference on Chart Studio Cloud for x
.
y
Sets the y coordinates.
y0
Alternate to `y`. Builds a linear space of y
coordinates. Use with `dy` where `y0` is the starting
coordinate and `dy` the step.
yaxis
Sets a reference between this trace's y coordinates and
a 2D cartesian y axis. If "y" (the default value), the
y coordinates refer to `layout.yaxis`. If "y2", the y
coordinates refer to `layout.yaxis2`, and so on.
yperiod
Only relevant when the axis `type` is "date". Sets the
period positioning in milliseconds or "M<n>" on the y
axis. Special values in the form of "M<n>" could be
used to declare the number of months. In this case `n`
must be a positive integer.
yperiod0
Only relevant when the axis `type` is "date". Sets the
base for period positioning in milliseconds or date
string on the y0 axis. When `y0period` is round number
of weeks, the `y0period0` by default would be on a
Sunday i.e. 2000-01-02, otherwise it would be at
2000-01-01.
yperiodalignment
Only relevant when the axis `type` is "date". Sets the
alignment of data points on the y axis.
ysrc
Sets the source reference on Chart Studio Cloud for y
.
row : 'all', int or None (default)
Subplot row index (starting from 1) for the trace to be
added. Only valid if figure was created using
`plotly.tools.make_subplots`.If 'all', addresses all
rows in the specified column(s).
col : 'all', int or None (default)
Subplot col index (starting from 1) for the trace to be
added. Only valid if figure was created using
`plotly.tools.make_subplots`.If 'all', addresses all
columns in the specified row(s).
secondary_y: boolean or None (default None)
If True, associate this trace with the secondary y-axis of the
subplot at the specified row and col. Only valid if all of the
following conditions are satisfied:
* The figure was created using `plotly.subplots.make_subplots`.
* The row and col arguments are not None
* The subplot at the specified row and col has type xy
(which is the default) and secondary_y True. These
properties are specified in the specs argument to
make_subplots. See the make_subplots docstring for more info.
Returns
-------
Figure
"""
from plotly.graph_objs import Waterfall
new_trace = Waterfall(
alignmentgroup=alignmentgroup,
base=base,
cliponaxis=cliponaxis,
connector=connector,
constraintext=constraintext,
customdata=customdata,
customdatasrc=customdatasrc,
decreasing=decreasing,
dx=dx,
dy=dy,
hoverinfo=hoverinfo,
hoverinfosrc=hoverinfosrc,
hoverlabel=hoverlabel,
hovertemplate=hovertemplate,
hovertemplatesrc=hovertemplatesrc,
hovertext=hovertext,
hovertextsrc=hovertextsrc,
ids=ids,
idssrc=idssrc,
increasing=increasing,
insidetextanchor=insidetextanchor,
insidetextfont=insidetextfont,
legendgroup=legendgroup,
measure=measure,
measuresrc=measuresrc,
meta=meta,
metasrc=metasrc,
name=name,
offset=offset,
offsetgroup=offsetgroup,
offsetsrc=offsetsrc,
opacity=opacity,
orientation=orientation,
outsidetextfont=outsidetextfont,
selectedpoints=selectedpoints,
showlegend=showlegend,
stream=stream,
text=text,
textangle=textangle,
textfont=textfont,
textinfo=textinfo,
textposition=textposition,
textpositionsrc=textpositionsrc,
textsrc=textsrc,
texttemplate=texttemplate,
texttemplatesrc=texttemplatesrc,
totals=totals,
uid=uid,
uirevision=uirevision,
visible=visible,
width=width,
widthsrc=widthsrc,
x=x,
x0=x0,
xaxis=xaxis,
xperiod=xperiod,
xperiod0=xperiod0,
xperiodalignment=xperiodalignment,
xsrc=xsrc,
y=y,
y0=y0,
yaxis=yaxis,
yperiod=yperiod,
yperiod0=yperiod0,
yperiodalignment=yperiodalignment,
ysrc=ysrc,
**kwargs
)
return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y)
def select_coloraxes(self, selector=None, row=None, col=None):
"""
Select coloraxis subplot objects from a particular subplot cell
and/or coloraxis subplot objects that satisfy custom selection
criteria.
Parameters
----------
selector: dict, function, or None (default None)
Dict to use as selection criteria.
coloraxis objects will be selected if they contain
properties corresponding to all of the dictionary's keys, with
values that exactly match the supplied values. If None
(the default), all coloraxis objects are selected. If a
function, it must be a function accepting a single argument and
returning a boolean. The function will be called on each
coloraxis and those for which the function returned True will
be in the selection.
row, col: int or None (default None)
Subplot row and column index of coloraxis objects to select.
To select coloraxis objects by row and column, the Figure
must have been created using plotly.subplots.make_subplots.
If None (the default), all coloraxis objects are selected.
Returns
-------
generator
Generator that iterates through all of the coloraxis
objects that satisfy all of the specified selection criteria
"""
return self._select_layout_subplots_by_prefix("coloraxis", selector, row, col)
def for_each_coloraxis(self, fn, selector=None, row=None, col=None):
"""
Apply a function to all coloraxis objects that satisfy the
specified selection criteria
Parameters
----------
fn:
Function that inputs a single coloraxis object.
selector: dict, function, or None (default None)
Dict to use as selection criteria.
coloraxis objects will be selected if they contain
properties corresponding to all of the dictionary's keys, with
values that exactly match the supplied values. If None
(the default), all coloraxis objects are selected. If a
function, it must be a function accepting a single argument and
returning a boolean. The function will be called on each
coloraxis and those for which the function returned True will
be in the selection.
row, col: int or None (default None)
Subplot row and column index of coloraxis objects to select.
To select coloraxis objects by row and column, the Figure
must have been created using plotly.subplots.make_subplots.
If None (the default), all coloraxis objects are selected.
Returns
-------
self
Returns the Figure object that the method was called on
"""
for obj in self.select_coloraxes(selector=selector, row=row, col=col):
fn(obj)
return self
def update_coloraxes(
self, patch=None, selector=None, overwrite=False, row=None, col=None, **kwargs
):
"""
Perform a property update operation on all coloraxis objects
that satisfy the specified selection criteria
Parameters
----------
patch: dict
| |
# coding: utf-8
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class DataAsset(object):
"""
Represents a data source in the Data Integration service.
"""
#: A constant which can be used with the model_type property of a DataAsset.
#: This constant has a value of "ORACLE_DATA_ASSET"
MODEL_TYPE_ORACLE_DATA_ASSET = "ORACLE_DATA_ASSET"
#: A constant which can be used with the model_type property of a DataAsset.
#: This constant has a value of "ORACLE_OBJECT_STORAGE_DATA_ASSET"
MODEL_TYPE_ORACLE_OBJECT_STORAGE_DATA_ASSET = "ORACLE_OBJECT_STORAGE_DATA_ASSET"
#: A constant which can be used with the model_type property of a DataAsset.
#: This constant has a value of "ORACLE_ATP_DATA_ASSET"
MODEL_TYPE_ORACLE_ATP_DATA_ASSET = "ORACLE_ATP_DATA_ASSET"
#: A constant which can be used with the model_type property of a DataAsset.
#: This constant has a value of "ORACLE_ADWC_DATA_ASSET"
MODEL_TYPE_ORACLE_ADWC_DATA_ASSET = "ORACLE_ADWC_DATA_ASSET"
#: A constant which can be used with the model_type property of a DataAsset.
#: This constant has a value of "MYSQL_DATA_ASSET"
MODEL_TYPE_MYSQL_DATA_ASSET = "MYSQL_DATA_ASSET"
#: A constant which can be used with the model_type property of a DataAsset.
#: This constant has a value of "GENERIC_JDBC_DATA_ASSET"
MODEL_TYPE_GENERIC_JDBC_DATA_ASSET = "GENERIC_JDBC_DATA_ASSET"
#: A constant which can be used with the model_type property of a DataAsset.
#: This constant has a value of "FUSION_APP_DATA_ASSET"
MODEL_TYPE_FUSION_APP_DATA_ASSET = "FUSION_APP_DATA_ASSET"
#: A constant which can be used with the model_type property of a DataAsset.
#: This constant has a value of "AMAZON_S3_DATA_ASSET"
MODEL_TYPE_AMAZON_S3_DATA_ASSET = "AMAZON_S3_DATA_ASSET"
def __init__(self, **kwargs):
"""
Initializes a new DataAsset object with values from keyword arguments. This class has the following subclasses and if you are using this class as input
to a service operations then you should favor using a subclass over the base class:
* :class:`~oci.data_integration.models.DataAssetFromJdbc`
* :class:`~oci.data_integration.models.DataAssetFromOracleDetails`
* :class:`~oci.data_integration.models.DataAssetFromAdwcDetails`
* :class:`~oci.data_integration.models.DataAssetFromAmazonS3`
* :class:`~oci.data_integration.models.DataAssetFromObjectStorageDetails`
* :class:`~oci.data_integration.models.DataAssetFromFusionApp`
* :class:`~oci.data_integration.models.DataAssetFromAtpDetails`
* :class:`~oci.data_integration.models.DataAssetFromMySQL`
The following keyword arguments are supported (corresponding to the getters/setters of this class):
:param model_type:
The value to assign to the model_type property of this DataAsset.
Allowed values for this property are: "ORACLE_DATA_ASSET", "ORACLE_OBJECT_STORAGE_DATA_ASSET", "ORACLE_ATP_DATA_ASSET", "ORACLE_ADWC_DATA_ASSET", "MYSQL_DATA_ASSET", "GENERIC_JDBC_DATA_ASSET", "FUSION_APP_DATA_ASSET", "AMAZON_S3_DATA_ASSET", 'UNKNOWN_ENUM_VALUE'.
Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'.
:type model_type: str
:param key:
The value to assign to the key property of this DataAsset.
:type key: str
:param model_version:
The value to assign to the model_version property of this DataAsset.
:type model_version: str
:param name:
The value to assign to the name property of this DataAsset.
:type name: str
:param description:
The value to assign to the description property of this DataAsset.
:type description: str
:param object_status:
The value to assign to the object_status property of this DataAsset.
:type object_status: int
:param identifier:
The value to assign to the identifier property of this DataAsset.
:type identifier: str
:param external_key:
The value to assign to the external_key property of this DataAsset.
:type external_key: str
:param asset_properties:
The value to assign to the asset_properties property of this DataAsset.
:type asset_properties: dict(str, str)
:param native_type_system:
The value to assign to the native_type_system property of this DataAsset.
:type native_type_system: oci.data_integration.models.TypeSystem
:param object_version:
The value to assign to the object_version property of this DataAsset.
:type object_version: int
:param parent_ref:
The value to assign to the parent_ref property of this DataAsset.
:type parent_ref: oci.data_integration.models.ParentReference
:param metadata:
The value to assign to the metadata property of this DataAsset.
:type metadata: oci.data_integration.models.ObjectMetadata
:param key_map:
The value to assign to the key_map property of this DataAsset.
:type key_map: dict(str, str)
"""
self.swagger_types = {
'model_type': 'str',
'key': 'str',
'model_version': 'str',
'name': 'str',
'description': 'str',
'object_status': 'int',
'identifier': 'str',
'external_key': 'str',
'asset_properties': 'dict(str, str)',
'native_type_system': 'TypeSystem',
'object_version': 'int',
'parent_ref': 'ParentReference',
'metadata': 'ObjectMetadata',
'key_map': 'dict(str, str)'
}
self.attribute_map = {
'model_type': 'modelType',
'key': 'key',
'model_version': 'modelVersion',
'name': 'name',
'description': 'description',
'object_status': 'objectStatus',
'identifier': 'identifier',
'external_key': 'externalKey',
'asset_properties': 'assetProperties',
'native_type_system': 'nativeTypeSystem',
'object_version': 'objectVersion',
'parent_ref': 'parentRef',
'metadata': 'metadata',
'key_map': 'keyMap'
}
self._model_type = None
self._key = None
self._model_version = None
self._name = None
self._description = None
self._object_status = None
self._identifier = None
self._external_key = None
self._asset_properties = None
self._native_type_system = None
self._object_version = None
self._parent_ref = None
self._metadata = None
self._key_map = None
@staticmethod
def get_subtype(object_dictionary):
"""
Given the hash representation of a subtype of this class,
use the info in the hash to return the class of the subtype.
"""
type = object_dictionary['modelType']
if type == 'GENERIC_JDBC_DATA_ASSET':
return 'DataAssetFromJdbc'
if type == 'ORACLE_DATA_ASSET':
return 'DataAssetFromOracleDetails'
if type == 'ORACLE_ADWC_DATA_ASSET':
return 'DataAssetFromAdwcDetails'
if type == 'AMAZON_S3_DATA_ASSET':
return 'DataAssetFromAmazonS3'
if type == 'ORACLE_OBJECT_STORAGE_DATA_ASSET':
return 'DataAssetFromObjectStorageDetails'
if type == 'FUSION_APP_DATA_ASSET':
return 'DataAssetFromFusionApp'
if type == 'ORACLE_ATP_DATA_ASSET':
return 'DataAssetFromAtpDetails'
if type == 'MYSQL_DATA_ASSET':
return 'DataAssetFromMySQL'
else:
return 'DataAsset'
@property
def model_type(self):
"""
Gets the model_type of this DataAsset.
The type of the data asset.
Allowed values for this property are: "ORACLE_DATA_ASSET", "ORACLE_OBJECT_STORAGE_DATA_ASSET", "ORACLE_ATP_DATA_ASSET", "ORACLE_ADWC_DATA_ASSET", "MYSQL_DATA_ASSET", "GENERIC_JDBC_DATA_ASSET", "FUSION_APP_DATA_ASSET", "AMAZON_S3_DATA_ASSET", 'UNKNOWN_ENUM_VALUE'.
Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'.
:return: The model_type of this DataAsset.
:rtype: str
"""
return self._model_type
@model_type.setter
def model_type(self, model_type):
"""
Sets the model_type of this DataAsset.
The type of the data asset.
:param model_type: The model_type of this DataAsset.
:type: str
"""
allowed_values = ["ORACLE_DATA_ASSET", "ORACLE_OBJECT_STORAGE_DATA_ASSET", "ORACLE_ATP_DATA_ASSET", "ORACLE_ADWC_DATA_ASSET", "MYSQL_DATA_ASSET", "GENERIC_JDBC_DATA_ASSET", "FUSION_APP_DATA_ASSET", "AMAZON_S3_DATA_ASSET"]
if not value_allowed_none_or_none_sentinel(model_type, allowed_values):
model_type = 'UNKNOWN_ENUM_VALUE'
self._model_type = model_type
@property
def key(self):
"""
Gets the key of this DataAsset.
Generated key that can be used in API calls to identify data asset.
:return: The key of this DataAsset.
:rtype: str
"""
return self._key
@key.setter
def key(self, key):
"""
Sets the key of this DataAsset.
Generated key that can be used in API calls to identify data asset.
:param key: The key of this DataAsset.
:type: str
"""
self._key = key
@property
def model_version(self):
"""
Gets the model_version of this DataAsset.
The model version of an object.
:return: The model_version of this DataAsset.
:rtype: str
"""
return self._model_version
@model_version.setter
def model_version(self, model_version):
"""
Sets the model_version of this DataAsset.
The model version of an object.
:param model_version: The model_version of this DataAsset.
:type: str
"""
self._model_version = model_version
@property
def name(self):
"""
Gets the name of this DataAsset.
Free form text without any restriction on permitted characters. Name can have letters, numbers, and special characters. The value is editable and is restricted to 1000 characters.
:return: The name of this DataAsset.
:rtype: str
"""
return self._name
@name.setter
def name(self, name):
"""
Sets the name of this DataAsset.
Free form text without any restriction on permitted characters. Name can have letters, numbers, and special characters. The value is editable and is restricted to 1000 characters.
:param name: The name of this DataAsset.
:type: str
"""
self._name = name
@property
def description(self):
"""
Gets the description of this DataAsset.
User-defined description of the data asset.
:return: The description of this DataAsset.
:rtype: str
"""
return self._description
@description.setter
def description(self, description):
"""
Sets the description of this DataAsset.
User-defined description of the data asset.
:param description: The description of this DataAsset.
:type: str
"""
self._description = description
@property
def object_status(self):
"""
Gets the object_status of this DataAsset.
The status of an object that can be set to value 1 for shallow references across objects, other values reserved.
:return: The object_status of this DataAsset.
:rtype: int
"""
return self._object_status
@object_status.setter
def object_status(self, object_status):
"""
Sets the object_status of this DataAsset.
The status of an object that can be set to value 1 for shallow references across objects, other values reserved.
:param object_status: The object_status of this DataAsset.
:type: int
"""
self._object_status = object_status
@property
def identifier(self):
"""
Gets the identifier of this DataAsset.
Value can only contain upper case letters, underscore, and numbers. It should begin with upper case | |
= int(len(working_objects[no_of_fractions])/2)
tick_tock = False
else:
lower_idx = int(len(working_objects[no_of_fractions])/2) - 1
upper_idx = -1
tick_tock = True
#print(no_of_fractions, int(ceil(len(working_objects[no_of_fractions])/2)))
obj_start, obj_stop = copy.deepcopy(working_objects[no_of_fractions][lower_idx]),\
copy.deepcopy(working_objects[no_of_fractions][upper_idx])
fat_obj_start, fat_obj_stop = copy.deepcopy(working_fatigue[no_of_fractions][lower_idx]), \
copy.deepcopy(working_fatigue[no_of_fractions][upper_idx])
lat_start, lat_stop = working_lateral[no_of_fractions][lower_idx], \
working_lateral[no_of_fractions][upper_idx]
fat_press_start, fat_press_stop = working_fatigue_press[no_of_fractions][lower_idx], \
working_fatigue_press[no_of_fractions][upper_idx]
slam_start, slam_stop = working_slamming[no_of_fractions][lower_idx], \
working_slamming[no_of_fractions][upper_idx]
# if no_of_fractions == 11:
# print('Tick/tock', tick_tock, 'lower/opper idx', lower_idx, upper_idx)
for work, work_input in zip([working_objects[no_of_fractions], working_lateral[no_of_fractions],
working_fatigue[no_of_fractions],
working_fatigue_press[no_of_fractions],
working_slamming[no_of_fractions]],
[(obj_start, obj_stop), (lat_start, lat_stop),
(fat_obj_start, fat_obj_stop), (fat_press_start, fat_press_stop),
(slam_start, slam_stop)]):
# First iteration tick_tock true, second tick_tock false
if not tick_tock:
lower_idx = lower_idx
upper_idx = upper_idx + 1
else:
lower_idx = lower_idx + 1
upper_idx = -1
work.insert(lower_idx, work_input[0])
work.insert(upper_idx, work_input[1])
similar_count += 2
# if no_of_fractions == 11:
# [print(item.get_structure_type()) for item in working_objects[no_of_fractions]]
# print('')
for no_of_fractions, struc_objects in working_objects.items():
for struc_obj in struc_objects:
struc_obj.set_span(tot_len/no_of_fractions)
solution_found, iterations = False, 0
while not solution_found:
iterations += 1
if iterations != 1:
min_var[0:6] += deltas/2
max_var[0:6] -= deltas/2
if algorithm == 'pso':
opt_objects = particle_search_geometric(min_var=min_var,max_var=max_var,deltas=deltas,
initial_structure_obj=working_objects[no_of_fractions],
lateral_pressure=working_lateral[no_of_fractions],
init_filter = init_filter,side=side,const_chk=const_chk,
pso_options=pso_options, fat_obj = fat_obj,
fat_press = fat_press)
elif algorithm == 'anysmart':
if load_pre:
import pickle
with open('geo_opt_2.pickle', 'rb') as file:
opt_objects = pickle.load(file)[no_of_fractions][1]
else:
opt_objects = any_smart_loop_geometric(min_var=min_var,max_var=max_var,deltas=deltas,
initial_structure_obj=working_objects[no_of_fractions],
lateral_pressure=working_lateral[no_of_fractions],
init_filter = init_filter,side=side,const_chk=const_chk,
fat_obj = working_fatigue[no_of_fractions],
slamming_press = working_slamming[no_of_fractions],
fat_press=working_fatigue_press[no_of_fractions],
predefiened_stiffener_iter = predefiened_stiffener_iter,
ml_algo=ml_algo)
# TODO fatigue and slamming implemetation
# Finding weight of this solution.
tot_weight, frame_spacings, valid, width, weight_details = 0, [None for dummy in range(len(opt_objects))], \
True, 10, {'frames': list(), 'objects': list(),
'scales': list()}
#print('Weight for', no_of_fractions)
for count, opt in enumerate(opt_objects):
obj = opt[0]
if opt[3]:
weigth_to_add = calc_weight((obj.get_s(),obj.get_pl_thk(),obj.get_web_h(),obj.get_web_thk(),
obj.get_fl_w(),obj.get_fl_thk(),obj.get_span(),width), prt=False)
tot_weight += weigth_to_add
weight_details['objects'].append(weigth_to_add)
if frame_spacings[count // 2] is None:
frame_spacings[count // 2] = obj.get_s()
#print('added normal weight', weigth_to_add)
else:
# In this case there are no applicable solutions found in the specified dimension ranges.
tot_weight += float('inf')
valid = False
if valid:
#print(frame_distance)
for frame in range(no_of_fractions-1):
frame_height = 2.5 if frame_distance is None else frame_distance['start_dist'] + \
(frame_distance['stop_dist']-
frame_distance['start_dist']) * \
((frame+1)/no_of_fractions)
#pl_area, stf_area = 0.018 * width, 0.25 * 0.015 * (width//frame_spacings[frame])
this_x = (frame_spacings[frame], opt_girder_prop[0], opt_girder_prop[1], opt_girder_prop[2],
opt_girder_prop[3], opt_girder_prop[4], None, width)
this_weight = sum(get_field_tot_area(this_x))* frame_height * 7850
scale_max, scale_min = opt_girder_prop[5], opt_girder_prop[6]
this_scale = scale_min + (scale_max-scale_min) * (abs((max_frame_count-(count+1)/2))/
(max_frame_count-min_frame_count))
#print('Number of fractions', no_of_fractions, 'Scale', this_scale)
tot_weight += this_weight * this_scale
solution_found = True
#print('added frame weight', this_weight * this_scale)
weight_details['frames'].append(this_weight * this_scale)
weight_details['scales'].append(this_scale)
elif iterations == 2:
solution_found = True # Only iterate once.
if predefiened_stiffener_iter is not None or not reiterate:
solution_found = True # Noe solution may be found, but in this case no more iteations.
results[no_of_fractions] = tot_weight, opt_objects, weight_details
return results
def any_find_min_weight_var(var):
'''
Find the minimum weight of the inpu
:param min:
:param max:
:return:
'''
return min(map(calc_weight))
def any_constraints_all(x,obj,lat_press,init_weight,side='p',chk=(True,True,True,True, True, True, True, False,
False, False),
fat_dict = None, fat_press = None, slamming_press = 0, PULSrun: calc.PULSpanel = None,
print_result = False, fdwn = 1, fup = 0.5, ml_results = None):
'''
Checking all constraints defined.
iter_var = ((item,init_stuc_obj,lat_press,init_filter_weight,side,chk,fat_dict,fat_press,slamming_press, PULSrun)
for item in iterable_all)
:param x:
:return:
'''
all_checks = [0,0,0,0,0,0,0,0,0,0,0]
print_result = False
calc_object = create_new_calc_obj(obj, x, fat_dict, fdwn = fdwn, fup = fup)
# PULS buckling check
if chk[7] and PULSrun is not None:
x_id = x_to_string(x)
if calc_object[0].get_puls_method() == 'buckling':
puls_uf = PULSrun.get_puls_line_results(x_id)["Buckling strength"]["Actual usage Factor"][0]
elif calc_object[0].get_puls_method() == 'ultimate':
puls_uf = PULSrun.get_puls_line_results(x_id)["Ultimate capacity"]["Actual usage Factor"][0]
if type(puls_uf) == str:
return False, 'PULS', x, all_checks
all_checks[8] = puls_uf/PULSrun.puls_acceptance
if puls_uf/PULSrun.puls_acceptance >= 1:
if print_result:
print('PULS', calc_object[0].get_one_line_string(), False)
return False, 'PULS', x, all_checks
# Buckling ml-cl
if chk[8]:
if any([calc_object[0].get_puls_method() == 'buckling' and ml_results[0] != 9,
calc_object[0].get_puls_method() == 'ultimate' and ml_results[1] != 9]):
if print_result:
print('Buckling ML-CL', calc_object[0].get_one_line_string(), False)
return False, 'Buckling ML-CL', x, all_checks
# Buckling ml-reg
if chk[9]:
pass
this_weight = calc_weight(x)
if this_weight > init_weight:
weigt_frac = this_weight / init_weight
if print_result:
pass
# print('Weights', calc_weight(x), ' > ', init_weight,
# calc_object[0].get_one_line_string(), init_weight, False)
all_checks[0] = weigt_frac
return False, 'Weight filter', x, all_checks
# Section modulus
if chk[0]:
section_modulus = min(calc_object[0].get_section_modulus())
min_section_modulus = calc_object[0].get_dnv_min_section_modulus(lat_press)
section_frac = section_modulus / min_section_modulus # TODO is this correct
all_checks[1] = section_frac
if not section_modulus > min_section_modulus :
if print_result:
print('Section modulus',calc_object[0].get_one_line_string(), False)
return False, 'Section modulus', x, all_checks
# Local stiffener buckling
if chk[6]:
buckling_local = calc_object[0].buckling_local_stiffener()
all_checks[2] = buckling_local[1]
if not buckling_local[0]:
if print_result:
print('Local stiffener buckling',calc_object[0].get_one_line_string(), False)
return False, 'Local stiffener buckling', x, all_checks
# Buckling
if chk[3]:
buckling_results = calc_object[0].calculate_buckling_all(design_lat_press=lat_press, checked_side=side)[0:5]
all_checks[3] = max(buckling_results)
if not all([uf<=1 for uf in buckling_results]):
if print_result:
print('Buckling',calc_object[0].get_one_line_string(), False)
return False, 'Buckling', x, all_checks
# Minimum plate thickness
if chk[1]:
act_pl_thk = calc_object[0].get_plate_thk()
min_pl_thk = calc_object[0].get_dnv_min_thickness(lat_press)/1000
plate_frac = min_pl_thk / act_pl_thk
all_checks[4] = plate_frac
if not act_pl_thk > min_pl_thk:
if print_result:
print('Minimum plate thickeness',calc_object[0].get_one_line_string(), False)
return False, 'Minimum plate thickness', x, all_checks
# Shear area
if chk[2]:
calc_shear_area = calc_object[0].get_shear_area()
min_shear_area = calc_object[0].get_minimum_shear_area(lat_press)
shear_frac = min_shear_area / calc_shear_area
all_checks[5] = shear_frac
if not calc_shear_area > min_shear_area:
if print_result:
print('Shear area',calc_object[0].get_one_line_string(), False)
return False, 'Shear area', x, all_checks
# Fatigue
if chk[4] and fat_dict is not None and fat_press is not None:
fatigue_uf = calc_object[1].get_total_damage(ext_press=fat_press[0],
int_press=fat_press[1])*calc_object[1].get_dff()
all_checks[6] = fatigue_uf
if fatigue_uf > 1:
if print_result:
print('Fatigue',calc_object[0].get_one_line_string(), False)
return False, 'Fatigue', x, all_checks
# Slamming
if chk[5] and slamming_press != 0:
slam_check = calc_object[0].check_all_slamming(slamming_press)
all_checks[7] = slam_check[1]
if slam_check[0] is False:
if print_result:
print('Slamming',calc_object[0].get_one_line_string(), False)
return False, 'Slamming', x, all_checks
if print_result:
print('OK Section', calc_object[0].get_one_line_string(), True)
return True, 'Check OK', x, all_checks
def any_constraints_all_number(x,*args):
'''
Checking all constraints defined.
:param x:
:return:
'''
# if calc_weight_pso(x) > init_weight:
# return -1
obj, lat_press, init_weight, side, chk = args[0:5]
fat_dict, fat_press = args[7], args[8]
calc_object = create_new_calc_obj(obj, x, fat_dict)
slamming_press = args[9]
# Section modulus
if chk[0]:
if not min(calc_object[0].get_section_modulus()) > calc_object[0].get_dnv_min_section_modulus(lat_press) :
return -1
# Local stiffener buckling
if not calc_object[0].buckling_local_stiffener():
return -1
# Buckling
if chk[3]:
if not all([uf<=1 for uf in calc_object[0].calculate_buckling_all(design_lat_press=lat_press,
checked_side=side)[0:5]]):
return -1
#Minimum plate thickeness
if chk[1]:
if not calc_object[0].get_plate_thk()>calc_object[0].get_dnv_min_thickness(lat_press)/1000:
return -1
# Shear area
if chk[2]:
if not calc_object[0].get_shear_area()>calc_object[0].get_minimum_shear_area(lat_press):
return -1
# Fatigue
try:
if chk[4] and fat_dict is not None:
if calc_object[1].get_total_damage(ext_press=fat_press[0], int_press=fat_press[1]) * \
calc_object[1].get_dff() > 1:
return -1
except IndexError:
pass
# Slamming
if chk[5] and slamming_press != 0:
if not calc_object[0].check_all_slamming(slamming_press):
return -1
#print('OK')
return 0
def constraint_geometric(fractions, *args):
return sum(fractions) == 1
def pso_constraint_geometric(x,*args):
''' The sum of the fractions must be 1.'''
return 1-sum(x)
def create_new_calc_obj(init_obj,x, fat_dict=None, fdwn = 1, fup = 0.5):
'''
Returns a new calculation object to be used in optimization
:param init_obj:
:return:
'''
x_old = [init_obj.get_s(), init_obj.get_plate_thk(), init_obj.get_web_h() , init_obj.get_web_thk(),
init_obj.get_fl_w(),init_obj.get_fl_thk(), init_obj.get_span(), init_obj.get_lg()]
sigma_y1_new = stress_scaling(init_obj.get_sigma_y1(), init_obj.get_plate_thk(), x[1], fdwn = fdwn, fup = fup)
sigma_y2_new = stress_scaling(init_obj.get_sigma_y2(), init_obj.get_plate_thk(), x[1], fdwn = fdwn, fup = fup)
tau_xy_new = stress_scaling(init_obj.get_tau_xy(), init_obj.get_plate_thk(), x[1], fdwn = fdwn, fup = fup)
sigma_x_new = stress_scaling_area(init_obj.get_sigma_x(),
sum(get_field_tot_area(x_old)),
sum(get_field_tot_area(x)), fdwn = fdwn, fup = fup)
try:
stf_type = x[8]
except IndexError:
stf_type = init_obj.get_stiffener_type()
main_dict = {'mat_yield': [init_obj.get_fy(), 'Pa'],'mat_factor': [init_obj.get_mat_factor(), 'Pa'],
'span': [init_obj.get_span(), 'm'],
'spacing': [x[0], 'm'],'plate_thk': [x[1], 'm'],'stf_web_height':[ x[2], 'm'],
'stf_web_thk': [x[3], 'm'],'stf_flange_width': [x[4], 'm'],
'stf_flange_thk': [x[5], 'm'],'structure_type': [init_obj.get_structure_type(), ''],
'stf_type': [stf_type, ''],'sigma_y1': [sigma_y1_new, 'MPa'],
'sigma_y2': [sigma_y2_new, 'MPa'],'sigma_x': [sigma_x_new, 'MPa'],
'tau_xy': [tau_xy_new, 'MPa'],'plate_kpp': [init_obj.get_kpp(), ''],
'stf_kps': [init_obj.get_kps(), ''],'stf_km1': [init_obj.get_km1(), ''],
'stf_km2': [init_obj.get_km2(), ''],'stf_km3': [init_obj.get_km3(), ''],
'structure_types':[init_obj.get_structure_types(), ''],
'zstar_optimization': [init_obj.get_z_opt(), ''],
'puls buckling method':[init_obj.get_puls_method(),''],
'puls boundary':[init_obj.get_puls_boundary(),''],
'puls stiffener end':[init_obj.get_puls_stf_end(),''],
'puls sp or up':[init_obj.get_puls_sp_or_up(),''],
'puls up boundary':[init_obj.get_puls_up_boundary(),'']}
if fat_dict == None:
return calc.CalcScantlings(main_dict), None
else:
return calc.CalcScantlings(main_dict), calc.CalcFatigue(main_dict, fat_dict)
def create_new_structure_obj(init_obj, x, fat_dict=None, fdwn = 1, fup = 0.5):
'''
Returns a new calculation object to be used in optimization
:param init_obj:
:return:
'''
x_old = [init_obj.get_s(), init_obj.get_plate_thk(), init_obj.get_web_h() , init_obj.get_web_thk(),
init_obj.get_fl_w() ,init_obj.get_fl_thk(), init_obj.get_span(), init_obj.get_lg()]
sigma_y1_new = stress_scaling(init_obj.get_sigma_y1(), init_obj.get_plate_thk(), x[1], fdwn = fdwn, fup = fup)
sigma_y2_new = stress_scaling(init_obj.get_sigma_y2(), init_obj.get_plate_thk(), x[1], fdwn = fdwn, fup = fup)
tau_xy_new = stress_scaling(init_obj.get_tau_xy(), init_obj.get_plate_thk(), x[1],fdwn = fdwn, fup = fup)
| |
"""
University of Minnesota
Aerospace Engineering and Mechanics - UAV Lab
Copyright 2019 Regents of the University of Minnesota
See: LICENSE.md for complete license details
Author: <NAME>
Analysis for Thor RTSM
"""
#%%
# Import Libraries
import numpy as np
import matplotlib.pyplot as plt
# Hack to allow loading the Core package
if __name__ == "__main__" and __package__ is None:
from sys import path, argv
from os.path import dirname, abspath, join
path.insert(0, abspath(join(dirname(argv[0]), "..")))
path.insert(0, abspath(join(dirname(argv[0]), "..", 'Core')))
del path, argv, dirname, abspath, join
from Core import Loader
from Core import OpenData
plt.rcParams.update({
"text.usetex": True,
"font.family": "serif",
"font.serif": ["Palatino"],
"font.size": 10
})
# Constants
hz2rps = 2 * np.pi
rps2hz = 1 / hz2rps
#%% File Lists
import os.path as path
pathBase = path.join('/home', 'rega0051', 'FlightArchive', 'Thor')
#pathBase = path.join('G:', 'Shared drives', 'UAVLab', 'Flight Data', 'Thor')
fileList = {}
flt = 'FLT126'
fileList[flt] = {}
fileList[flt]['log'] = path.join(pathBase, 'Thor' + flt, 'Thor' + flt + '.h5')
fileList[flt]['config'] = path.join(pathBase, 'Thor' + flt, 'thor.json')
fileList[flt]['def'] = path.join(pathBase, 'Thor' + flt, 'thor_def.json')
flt = 'FLT127'
fileList[flt] = {}
fileList[flt]['log'] = path.join(pathBase, 'Thor' + flt, 'Thor' + flt + '.h5')
fileList[flt]['config'] = path.join(pathBase, 'Thor' + flt, 'thor.json')
fileList[flt]['def'] = path.join(pathBase, 'Thor' + flt, 'thor_def.json')
flt = 'FLT128'
fileList[flt] = {}
fileList[flt]['log'] = path.join(pathBase, 'Thor' + flt, 'Thor' + flt + '.h5')
fileList[flt]['config'] = path.join(pathBase, 'Thor' + flt, 'thor.json')
fileList[flt]['def'] = path.join(pathBase, 'Thor' + flt, 'thor_def.json')
#%%
from Core import FreqTrans
rtsmSegList = [
# {'flt': 'FLT126', 'seg': ('time_us', [875171956 , 887171956], 'FLT126 - RTSM - Nominal Gain, 4 deg amp'), 'color': 'k'},
# {'flt': 'FLT126', 'seg': ('time_us', [829130591 , 841130591], 'FLT126 - RTSM Route - Nominal Gain, 4 deg amp'), 'color': 'k'},
# {'flt': 'FLT127', 'seg': ('time_us', [641655909 , 653655909], 'FLT127 - RTSM Route - Nominal Gain, 4 deg amp'), 'color': 'k'}, # Yaw controller in-op??
# {'flt': 'FLT128', 'seg': ('time_us', [700263746 , 712263746 ], 'FLT128 - RTSM Route - Nominal Gain, 4 deg amp'), 'color': 'k'}, # Interesting Roll Margin vs. Uncertainty
# {'flt': 'FLT128', 'seg': ('time_us', [831753831 , 843753831 ], 'FLT128 - RTSM Route - Nominal Gain, 4 deg amp'), 'color': 'k'},
# {'flt': 'FLT128', 'seg': ('time_us', [ 959859721 , 971859721 ], 'FLT128 - RTSM Route - Nominal Gain, 4 deg amp'), 'color': 'k'}, # Not good
# {'flt': 'FLT126', 'seg': ('time_us', [928833763 , 940833763], 'FLT126 - RTSM Large - Nominal Gain, 8 deg amp'), 'color': 'r'},
# {'flt': 'FLT127', 'seg': ('time_us', [698755386 , 707255278], 'FLT127 - RTSM Large Route - Nominal Gain, 8 deg amp'), 'color': 'r'}, # Yaw controller in-op??
# {'flt': 'FLT128', 'seg': ('time_us', [779830919 , 791830919 ], 'FLT128 - RTSM Large Route - Nominal Gain, 8 deg amp'), 'color': 'r'},
# {'flt': 'FLT128', 'seg': ('time_us', [900237086 , 912237086 ], 'FLT128 - RTSM Large Route - Nominal Gain, 8 deg amp'), 'color': 'r'},
# {'flt': 'FLT126', 'seg': ('time_us', [902952886 , 924952886], 'FLT126 - RTSM Long - Nominal Gain, 4 deg amp'), 'color': 'b'},
# {'flt': 'FLT127', 'seg': ('time_us', [657015836 , 689015836], 'FLT127 - RTSM Long Route - Nominal Gain, 4 deg amp'), 'color': 'b'}, # Yaw controller in-op??
{'flt': 'FLT128', 'seg': ('time_us', [714385469 , 746385469 ], 'FLT128 - RTSM Long Route - Nominal Gain, 4 deg amp'), 'color': 'b'},
{'flt': 'FLT128', 'seg': ('time_us', [847254621 , 879254621 ], 'FLT128 - RTSM Long Route - Nominal Gain, 4 deg amp'), 'color': 'g'}, # Best
# {'flt': 'FLT127', 'seg': ('time_us', [1209355236 , 1221535868], 'FLT127 - RTSM LongLarge Route - Nominal Gain, 8 deg amp'), 'color': 'm'}, # Yaw controller in-op??
{'flt': 'FLT128', 'seg': ('time_us', [794251787 , 826251787 ], 'FLT128 - RTSM LongLarge Route - Nominal Gain, 8 deg amp'), 'color': 'r'},
{'flt': 'FLT128', 'seg': ('time_us', [921438015 , 953438015 ], 'FLT128 - RTSM LongLarge Route - Nominal Gain, 8 deg amp'), 'color': 'm'},
# {'flt': 'FLT126', 'seg': ('time_us', [981115495 , 993115495], 'FLT126 - RTSM - High Gain, 4 deg amp')},
# {'flt': 'FLT126', 'seg': ('time_us', [689907125 , 711907125], 'FLT126 - RTSM Long - High Gain, 4 deg amp')},
# {'flt': 'FLT126', 'seg': ('time_us', [728048050 , 740048050], 'FLT126 - RTSM Large - High Gain, 8 deg amp')},
]
oDataSegs = []
for rtsmSeg in rtsmSegList:
fltNum = rtsmSeg['flt']
fileLog = fileList[fltNum]['log']
fileConfig = fileList[fltNum]['config']
# Load
h5Data = Loader.Load_h5(fileLog) # RAPTRS log data as hdf5
sysConfig = Loader.JsonRead(fileConfig)
oData = Loader.OpenData_RAPTRS(h5Data, sysConfig)
oData['cmdRoll_FF'] = h5Data['Control']['cmdRoll_pidFF']
oData['cmdRoll_FB'] = h5Data['Control']['cmdRoll_pidFB']
oData['cmdPitch_FF'] = h5Data['Control']['cmdPitch_pidFF']
oData['cmdPitch_FB'] = h5Data['Control']['cmdPitch_pidFB']
oData['cmdYaw_FF'] = h5Data['Control']['refPsi_rad']
oData['cmdYaw_FB'] = h5Data['Control']['cmdYaw_damp_rps']
# Segments
rtsmSeg['seg'][1][0] += 1e6
rtsmSeg['seg'][1][1] += -1e6 + 50e3
oDataSegs.append(OpenData.Segment(oData, rtsmSeg['seg']))
#%%
sigExcList = ['cmdRoll_rps', 'cmdPitch_rps', 'cmdYaw_rps']
sigFbList = ['cmdRoll_FB', 'cmdPitch_FB', 'cmdYaw_FB']
sigFfList = ['cmdRoll_FF', 'cmdPitch_FF', 'cmdYaw_FF']
#sigSensList = ['wB_I_rps', 'cmdPitch_FF', 'cmdYaw_FF']
freqExc_rps = []
freqExc_rps.append( np.array(sysConfig['Excitation']['OMS_RTSM_1']['Frequency']))
freqExc_rps.append( np.array(sysConfig['Excitation']['OMS_RTSM_2']['Frequency']))
freqExc_rps.append( np.array(sysConfig['Excitation']['OMS_RTSM_3']['Frequency']))
vCmdList = []
vExcList = []
vFbList = []
vFfList = []
ySensList = []
for iSeg, seg in enumerate(oDataSegs):
vCmd = np.zeros((len(sigExcList), len(seg['time_s'])))
vExc = np.zeros((len(sigExcList), len(seg['time_s'])))
vFb = np.zeros((len(sigExcList), len(seg['time_s'])))
vFf = np.zeros((len(sigExcList), len(seg['time_s'])))
ySens = np.zeros((len(sigExcList), len(seg['time_s'])))
for iSig, sigExc in enumerate(sigExcList):
sigFb = sigFbList[iSig]
sigFf = sigFfList[iSig]
vCmd[iSig] = seg['Control'][sigExc]
vExc[iSig] = seg['Excitation'][sigExc]
vFb[iSig] = -seg[sigFb]
# vFb[iSig][1:-1] = -seg[sigFb][0:-2] # Shift the time of the output into next frame
vFf[iSig] = seg[sigFf]
ySens[iSig] = seg['wB_I_rps'][iSig]
vCmdList.append(vCmd)
vExcList.append(vExc)
vFbList.append(vFb)
vFfList.append(vFf)
ySensList.append(ySens)
plt.plot(oDataSegs[iSeg]['time_s'], oDataSegs[iSeg]['vIas_mps'])
plt.plot(oDataSegs[iSeg]['time_s'], vExcList[iSeg][0])
plt.plot(oDataSegs[iSeg]['time_s'], vExcList[iSeg][1])
plt.plot(oDataSegs[iSeg]['time_s'], vExcList[iSeg][2])
plt.plot(oDataSegs[iSeg]['time_s'], vFbList[iSeg][0])
plt.plot(oDataSegs[iSeg]['time_s'], vFbList[iSeg][1])
plt.plot(oDataSegs[iSeg]['time_s'], vFbList[iSeg][2])
#%% Estimate the frequency response function
# Define the excitation frequencies
freqRate_hz = 50
freqRate_rps = freqRate_hz * hz2rps
optSpec = FreqTrans.OptSpect(dftType = 'czt', freqRate_rps = freqRate_rps, smooth = ('box', 5), winType = 'bartlett', detrendType = 'linear')
# Excited Frequencies per input channel
optSpec.freq_rps = np.asarray(freqExc_rps)
optSpec.freqInterp = np.sort(optSpec.freq_rps.flatten())
# Null Frequencies
freqNull_rps = optSpec.freqInterp[0:-1] + 0.5 * np.diff(optSpec.freqInterp)
optSpec.freqNull = freqNull_rps
optSpec.freqNullInterp = True
# FRF Estimate
TaEstNomList = []
TaEstUncList = []
TaEstCohList = []
SaEstNomList = []
SaEstUncList = []
SaEstCohList = []
LaEstNomList = []
LaEstUncList = []
LaEstCohList = []
for iSeg, seg in enumerate(oDataSegs):
freq_rps, Txy, Cxy, Sxx, Syy, Sxy, TxyUnc, SxxNull, Snn = FreqTrans.FreqRespFuncEstNoise(vExcList[iSeg], vFbList[iSeg], optSpec)
freq_hz = freq_rps * rps2hz
TaEstNom = -Txy # Sa = I - Ta
TaEstUnc = TxyUnc # TxuUnc = np.abs(Sxu / Sxx)
TaEstCoh = Cxy # Cxy = np.abs(Sxu)**2 / (Sxx * Suu)
SaEstNom, SaEstUnc, SaEstCoh = FreqTrans.TtoS(TaEstNom, TaEstUnc, TaEstCoh)
LaEstNom, LaEstUnc, LaEstCoh = FreqTrans.StoL(SaEstNom, SaEstUnc, SaEstCoh)
TaEstNomList.append( TaEstNom )
TaEstUncList.append( TaEstUnc )
TaEstCohList.append( TaEstCoh )
SaEstNomList.append( SaEstNom )
SaEstUncList.append( SaEstUnc )
SaEstCohList.append( SaEstCoh )
LaEstNomList.append( LaEstNom )
LaEstUncList.append( LaEstUnc )
LaEstCohList.append( LaEstCoh )
print(np.sum(SxxNull, axis = -1) / np.sum(Sxx, axis = -1))
T_InputNames = sigExcList
T_OutputNames = sigFbList
# Compute Gain, Phase, Crit Distance
#%% Sigma Plot
svLaEstNomList = []
svLaEstUncList = []
for iSeg in range(0, len(oDataSegs)):
# I3 = np.repeat([np.eye(3)], SaEstNomList.shape[-1], axis=0).T
# svLaEstNom_mag = FreqTrans.Sigma( I3 + LaEstNomList[iSeg] ) # Singular Value Decomp
svLaEstNom_mag = 1 / FreqTrans.Sigma(SaEstNomList[iSeg]) # sv(I + La) = 1 / sv(Sa)
svLaEstUnc_mag = FreqTrans.Sigma( LaEstUncList[iSeg] ) # Singular Value Decomp
svLaEstNomList.append(svLaEstNom_mag)
svLaEstUncList.append(svLaEstUnc_mag)
if True:
fig = None
for iSeg in range(0, len(oDataSegs)):
cohLaEst = LaEstCohList[iSeg]
# cohLaEstMin = np.min(cohLaEst, axis = (0,1))
cohLaEstMin = np.mean(cohLaEst, axis = (0,1))
svNom = svLaEstNomList[iSeg]
svNomMin = np.min(svNom, axis=0)
svUnc = svLaEstUncList[iSeg]
svUncMax = np.max(svUnc, axis=0)
svUncLower = svNomMin - svUncMax
svUncLower[svUncLower < 0] = svNomMin[svUncLower < 0]
fig = FreqTrans.PlotSigma(freq_hz[0], svNomMin, svUnc_mag = svUncLower, coher_nd = cohLaEstMin, fig = fig, color = rtsmSegList[iSeg]['color'], linestyle = '-', label = oDataSegs[iSeg]['Desc'])
fig = FreqTrans.PlotSigma(freq_hz[0], 0.4 * np.ones_like(freq_hz[0]), color = 'r', linestyle = '--', fig = fig)
ax = fig.get_axes()
ax[0].set_xlim(0, 10)
ax[0].set_ylim(0, 1.5)
#%% Vector Margin Plots
inPlot = ['$p_{ex}$', '$q_{ex}$', '$r_{ex}$'] # Elements of sigExcList
outPlot = ['$p_{fb}$', '$q_{fb}$', '$r_{fb}$'] # Elements of sigFbList
vmLaEstNomList_mag = []
vmLaEstUncList_mag = []
for iSeg in range(0, len(oDataSegs)):
vm_mag, vmUnc_mag, vmMin_mag = FreqTrans.VectorMargin(LaEstNomList[iSeg], LaEstUncList[iSeg], typeUnc = 'circle')
vmLaEstNomList_mag.append(vm_mag)
vmLaEstUncList_mag.append(vmUnc_mag)
# vm_mag.append(vmMin_mag)
numOut = len(outPlot); numIn = len(inPlot)
ioArray = np.array(np.meshgrid(np.arange(numOut), np.arange(numIn))).T.reshape(-1, 2)
if False:
for iPlot, [iOut, iIn] in enumerate(ioArray):
fig = 10 + iPlot
for iSeg in range(0, len(oDataSegs)):
vm_mag = vmLaEstNomList_mag[iSeg][iOut, iIn]
vmUnc_mag = vmLaEstUncList_mag[iSeg][iOut, iIn]
fig = FreqTrans.PlotVectorMargin(freq_hz[iIn], vm_mag, vmUnc_mag = vmUnc_mag, coher_nd = LaEstCohList[iSeg][iOut, iIn], fig = fig, color = rtsmSegList[iSeg]['color'], label = oDataSegs[iSeg]['Desc'])
fig = FreqTrans.PlotVectorMargin(freq_hz[iIn], 0.4 * np.ones_like(freq_hz[iIn]), fig = fig, color = 'r', linestyle = '--', label = 'Critical')
fig.suptitle('$L_a$ - ' + inPlot[iIn] + ' to ' + outPlot[iOut])
ax = fig.get_axes()
ax[0].set_ylim(0, 2)
#%% Nyquist Plots
if False:
for iPlot, [iOut, iIn] in enumerate(ioArray):
fig | |
<reponame>andycasey/gap_tellurics
# coding: utf-8
""" Basic functionality to treat spectra as mutable objects. """
from __future__ import division, print_function
__author__ = "<NAME> <<EMAIL>>"
# Standard library
import json
import logging
import os
from shutil import copyfile
# Third-party
import numpy as np
import pyfits
from scipy import interpolate, ndimage, polyfit, poly1d
from scipy.optimize import fmin, leastsq
__all__ = ['Spectrum', 'Spectrum1D']
class Spectrum(object):
"""A class to represent multi-dimensional spectral objects. """
def __init__(self, disp, flux, uncertainty=None, headers={}):
"""Initializes a `Spectrum` object with the given (multi-dimensional)
dispersion and flux arrays.
Inputs
------
disp : `np.ndarray`
Dispersion of the spectra.
flux : `np.ndarray`
Flux values for each dispersion point.
uncertainty : `np.ndarray`
Uncertainty values for each dispersion point.
headers : `dict`
Headers.
"""
self.disp = disp
self.flux = flux
self.uncertainty = uncertainty
self.headers = headers
self.num_orders = self.flux.shape[1] if len(self.flux.shape) > 1 else len(self.flux)
return None
def remove_invalid_orders(self, band=None):
"""Discards any invalid orders where no finite flux values greater than
zero exist.
Inputs
------
band : `int`
Dimensional index to search for invalid orders on.
"""
if band > self.flux.shape[0]:
raise ValueError
remove_indices = []
for i in xrange(self.flux.shape[1]):
flux_values = self.flux[band, i, :]
if not np.any(np.isfinite(flux_values) * flux_values > 0):
remove_indices.append(i)
if len(remove_indices) > 0:
logging.warn("Invalid orders ({indices}) identified and discarded!".format(indices=remove_indices))
cleaned_flux = np.delete(self.flux, remove_indices, axis=1)
cleaned_disp = np.delete(self.disp, remove_indices, axis=0)
return Spectrum1D(disp=cleaned_disp, flux=cleaned_flux, headers=self.headers)
return self
@classmethod
def load_multispec(cls, filename):
"""Reads in a multispec FITS file into a `Spectrum` object.
Inputs
----
filename : `str`
Multi-spec FITS filename to load.
"""
if not os.path.exists(filename):
raise IOError("filename '{filename}'' does not exist".format(filename=filename))
with pyfits.open(filename) as image:
headers = image[0].header
flux = image[0].data
headers_dict = {}
for k, v in headers.iteritems():
try:
str(v)
json.dumps(v)
except TypeError:
continue
if headers_dict.has_key(k):
headers_dict[k] += v
else:
headers_dict[k] = v
# Determine number of orders
num_pixels = flux.shape[-1]
num_orders = 1 if len(flux.shape) == 1 else flux.shape[-2]
# Try linear dispersion
try:
crval = headers['crval1']
crpix = headers['crpix1']
cd = headers['cd1_1']
ctype = headers['ctype1']
if ctype.strip() == 'LINEAR':
dispersion = np.zeros((num_orders, num_pixels), dtype=np.float)
dispersion_base = (np.arange(num_pixels) + 1 - crpix) * cd + crval
for i in xrange(num_orders):
dispersion[i, :] = dispersion_base
dcflag = headers['dc-flag']
if dcflag == 1:
dispersion = 10.0 ** dispersion
elif dcflag != 0:
raise ValueError("dispersion is not linear or logarithmic (DC-FLAG = {dcflag})".format(dcfloag=dcflag))
if num_orders == 1:
dispersion.shape = (num_pixels, )
flux = np.squeeze(flux)
return cls(dispersion, flux, headers=headers_dict)
except KeyError:
pass
# Get multi-spec headers
try:
wat = headers['wat2_*']
num_wat_headers = len(wat)
except KeyError:
raise ValueError("cannot decipher header: need either WAT2_* or CRVAL keywords")
# Concatenate headers
wat_str = ''
for i in xrange(num_wat_headers):
# Apparently this is a hack to fix a problem in
# older PyFits versions (< 3.1) where trailing blanks are stripped
value = wat[i]
if hasattr(value, 'value'): value = value.value
value = value + (" " * (68 - len(value)))
wat_str += value
# Find all the spec#="..." strings
spec_str = [''] * num_orders
for i in xrange(num_orders):
name = 'spec%i' % (i + 1, )
p0 = wat_str.find(name)
p1 = wat_str.find('"', p0)
p2 = wat_str.find('"', p1 + 1)
if p0 < 0 or p2 < 0 or p2 < 0:
raise ValueError("cannot find '{name}' in WAT2_* keyword".format(name=name))
spec_str[i] = wat_str[p1 + 1:p2]
# Get wavelength calibration information
z_params = np.zeros(num_orders)
w_params = np.zeros((num_orders, 9))
w = np.zeros(9)
for i in xrange(num_orders):
w = np.asarray(spec_str[i].split(), dtype=np.float)
w_params[i, :] = w
if w[2] == -1:
raise ValueError("spectrum aperture {index} has no wavelength calibration (type = {index_type})".format(index=i+1, index_type=w[2]))
elif w[6] != 0:
z_params[i] = w[6]
dispersion = np.zeros((num_orders, num_pixels), dtype=np.float)
disp_fields = [None] * num_orders
for i in xrange(num_orders):
if w_params[i, 2] in (0, 1):
# Simple linear or logarithmic spacing
dispersion[i, :] = np.arange(num_pixels) * w_params[i, 4] + w_params[i, 3]
if w_params[i, 2] == 1:
dispersion[i, :] = 10. ** dispersion[i, :]
else:
dispersion[:, i], disp_fields[i] = compute_non_linear_disp(num_pixels, spec_str[i])
# Apply z-correction for this order
dispersion[i, :] *= (1 - z_params[i])
if num_orders == 1:
flux = np.squeeze(flux)
dispersion.shape = (num_pixels, )
# Check blue to red orders
if np.min(dispersion[0]) > np.min(dispersion[-1]):
dispersion = dispersion[::-1]
if len(flux.shape) > 2:
flux = flux[:, ::-1]
else: flux = flux[::-1]
return cls(disp=dispersion, flux=flux, headers=headers_dict)
class Spectrum1D(object):
"""A mutable class to represent a one dimensional spectrum."""
def __init__(self, disp, flux, uncertainty=None, headers={}):
"""Initializes a `Spectrum1D` object with the given dispersion and flux
arrays.
Inputs
------
disp : `np.array`
Dispersion of the spectrum (i.e. the wavelength points).
flux : `np.array`
Flux points for each `disp` point.
uncertainty : `np.array`
Uncertainty in flux points for each dispersion point.
"""
self.disp = disp
self.flux = flux
self.uncertainty = uncertainty
self.headers = headers
return None
@classmethod
def load(cls, filename, **kwargs):
"""Load a `Spectrum1D` object from a given filename.
Inputs
----
filename : `str`
Filename to load. This can be a single dimensional FITS file or an
ASCII format.
Notes
-----
If you are loading from an non-standard ASCII file, you can pass
kwargs to `np.loadtxt` through this function.
"""
if not os.path.exists(filename):
raise IOError("filename '{fileame}' does not exist".format(filename=filename))
uncertainty = None
if filename.endswith('.fits'):
image = pyfits.open(filename, **kwargs)
header = image[0].header
# Check for a tabular data structure
if len(image) > 1 and image[0].data is None:
names = [name.lower() for name in image[1].data.names]
dispersion_key = 'wave' if 'wave' in names else 'disp'
disp, flux = image[1].data[dispersion_key], image[1].data['flux']
if 'error' in names or 'uncertainty' in names:
uncertainty_key = 'error' if 'error' in names else 'uncertainty'
uncertainty = image[1].data[uncertainty_key]
else:
# According to http://iraf.net/irafdocs/specwcs.php ....
#li = a.headers['LTM1_1'] * np.arange(a.headers['NAXIS1']) + a.headers['LTV1']
#a.headers['CRVAL1'] + a.headers['CD1_1'] * (li - a.headers['CRPIX1'])
if np.all([header.has_key(key) for key in ('CDELT1', 'NAXIS1', 'CRVAL1')]):
disp = header['CRVAL1'] + np.arange(header['NAXIS1']) * header['CDELT1']
if header.has_key('LTV1'):
disp -= header['LTV1'] * header['CDELT1']
#disp -= header['LTV1'] if header.has_key('LTV1') else 0
flux = image[0].data
# Add the headers in
headers = {}
for row in header.items():
key, value = row
# Check the value is valid
try:
str(value)
json.dumps(value)
except TypeError:
continue
if len(key) == 0 or len(str(value)) == 0: continue
if headers.has_key(key):
if not isinstance(headers[key], list):
headers[key] = [headers[key]]
headers[key].append(value)
else:
headers[key] = value
for key, value in headers.iteritems():
if isinstance(value, list):
headers[key] = "\n".join(map(str, value))
else:
headers = {}
disp, flux = np.loadtxt(filename, unpack=True, **kwargs)
return cls(disp, flux, uncertainty=uncertainty, headers=headers)
def save(self, filename, clobber=True):
"""Saves the `Spectrum1D` object to the specified filename.
Inputs
------
filename : `str`
The filename to save the `Spectrum1D` object to.
clobber : `bool`, optional
Whether to overwite the `filename` if it already exists.
Raises
------
IOError
If the filename exists and we are not asked to clobber it.
ValueError
If the ``Spectrum1D`` object does not have a linear dispersion map.
"""
if os.path.exists(filename) and not clobber:
raise IOError("filename '{filename}' already exists and we have been asked not to clobber it".format(filename=filename))
if not filename.endswith('fits'):
# ASCII
data = np.hstack([self.disp.reshape(len(self.disp), 1), self.flux.reshape(len(self.disp), 1)])
assert len(data.shape) == 2
assert data.shape[1] == 2
np.savetxt(filename, data)
else:
# FITS
crpix1, crval1 = 1, self.disp.min()
cdelt1 = np.mean(np.diff(self.disp))
test_disp = (crval1 + np.arange(len(self.disp), dtype=self.disp.dtype) * cdelt1).astype(self.disp.dtype)
if np.max(self.disp - test_disp) > 10e-2 or self.uncertainty is not None:
# Non-linear dispersion map, or we have uncertainty information too
# Create a tabular FITS format.
col_disp = pyfits.Column(name='disp', format='1D', array=self.disp)
col_flux = pyfits.Column(name='flux', format='1D', array=self.flux)
if self.uncertainty is not None:
col_uncertainty = pyfits.Column(name='uncertainty', format='1D', array=self.uncertainty)
table_hdu = pyfits.new_table([col_disp, col_flux, col_uncertainty])
else:
table_hdu = pyfits.new_table([col_disp, col_flux])
# Create Primary HDU
hdu = pyfits.PrimaryHDU()
# Update primary HDU with headers
for key, value in self.headers.iteritems():
if len(key) > 8:
# To deal with ESO compatibility
hdu.header.update('HIERARCH %s' % (key, ), value)
try:
hdu.header.update(key, value)
except ValueError:
logging.warn("Could not save header key/value combination: %s = %s" % (key, | |
bytes_transferred, dst_uri)
def _PerformDownloadToStream(self, src_key, src_uri, str_fp, headers):
(cb, num_cb, res_download_handler) = self._GetTransferHandlers(
src_uri, src_key.size, False)
start_time = time.time()
src_key.get_contents_to_file(str_fp, headers, cb=cb, num_cb=num_cb)
end_time = time.time()
bytes_transferred = src_key.size
end_time = time.time()
return (end_time - start_time, bytes_transferred)
def _CopyFileToFile(self, src_key, src_uri, dst_uri, headers):
"""Copies a local file to a local file.
Args:
src_key: Source StorageUri. Must be a file URI.
src_uri: Source StorageUri.
dst_uri: Destination StorageUri.
headers: The headers dictionary.
Returns:
(elapsed_time, bytes_transferred, dst_uri), excluding
overhead like initial HEAD.
Raises:
CommandException: if errors encountered.
"""
self._LogCopyOperation(src_uri, dst_uri, headers)
dst_key = dst_uri.new_key(False, headers)
start_time = time.time()
dst_key.set_contents_from_file(src_key.fp, headers)
end_time = time.time()
return (end_time - start_time, os.path.getsize(src_key.fp.name), dst_uri)
def _CopyObjToObjDaisyChainMode(self, src_key, src_uri, dst_uri, headers):
"""Copies from src_uri to dst_uri in "daisy chain" mode.
See -D OPTION documentation about what daisy chain mode is.
Args:
src_key: Source Key.
src_uri: Source StorageUri.
dst_uri: Destination StorageUri.
headers: A copy of the headers dictionary.
Returns:
(elapsed_time, bytes_transferred, version-specific dst_uri) excluding
overhead like initial HEAD.
Raises:
CommandException: if errors encountered.
"""
self._SetContentTypeHeader(src_uri, headers)
self._LogCopyOperation(src_uri, dst_uri, headers)
canned_acl = None
if self.sub_opts:
for o, a in self.sub_opts:
if o == '-a':
canned_acls = dst_uri.canned_acls()
if a not in canned_acls:
raise CommandException('Invalid canned ACL "%s".' % a)
canned_acl = a
elif o == '-p':
# We don't attempt to preserve ACLs across providers because
# GCS and S3 support different ACLs and disjoint principals.
raise NotImplementedError('Cross-provider cp -p not supported')
return self._PerformResumableUploadIfApplies(KeyFile(src_key), dst_uri,
canned_acl, headers)
def _PerformCopy(self, src_uri, dst_uri):
"""Performs copy from src_uri to dst_uri, handling various special cases.
Args:
src_uri: Source StorageUri.
dst_uri: Destination StorageUri.
Returns:
(elapsed_time, bytes_transferred, version-specific dst_uri) excluding
overhead like initial HEAD.
Raises:
CommandException: if errors encountered.
"""
# Make a copy of the input headers each time so we can set a different
# content type for each object.
if self.headers:
headers = self.headers.copy()
else:
headers = {}
src_key = src_uri.get_key(False, headers)
if not src_key:
raise CommandException('"%s" does not exist.' % src_uri)
# On Windows, stdin is opened as text mode instead of binary which causes
# problems when piping a binary file, so this switches it to binary mode.
if IS_WINDOWS and src_uri.is_file_uri() and src_key.is_stream():
import msvcrt
msvcrt.setmode(src_key.fp.fileno(), os.O_BINARY)
if self.no_clobber:
# There are two checks to prevent clobbering:
# 1) The first check is to see if the item
# already exists at the destination and prevent the upload/download
# from happening. This is done by the exists() call.
# 2) The second check is only relevant if we are writing to gs. We can
# enforce that the server only writes the object if it doesn't exist
# by specifying the header below. This check only happens at the
# server after the complete file has been uploaded. We specify this
# header to prevent a race condition where a destination file may
# be created after the first check and before the file is fully
# uploaded.
# In order to save on unnecessary uploads/downloads we perform both
# checks. However, this may come at the cost of additional HTTP calls.
if dst_uri.exists(headers):
if not self.quiet:
self.THREADED_LOGGER.info('Skipping existing item: %s' %
dst_uri.uri)
return (0, 0, None)
if dst_uri.is_cloud_uri() and dst_uri.scheme == 'gs':
headers['x-goog-if-generation-match'] = '0'
if src_uri.is_cloud_uri() and dst_uri.is_cloud_uri():
if src_uri.scheme == dst_uri.scheme and not self.daisy_chain:
return self._CopyObjToObjInTheCloud(src_key, src_uri, dst_uri, headers)
else:
return self._CopyObjToObjDaisyChainMode(src_key, src_uri, dst_uri,
headers)
elif src_uri.is_file_uri() and dst_uri.is_cloud_uri():
return self._UploadFileToObject(src_key, src_uri, dst_uri, headers)
elif src_uri.is_cloud_uri() and dst_uri.is_file_uri():
return self._DownloadObjectToFile(src_key, src_uri, dst_uri, headers)
elif src_uri.is_file_uri() and dst_uri.is_file_uri():
return self._CopyFileToFile(src_key, src_uri, dst_uri, headers)
else:
raise CommandException('Unexpected src/dest case')
def _ExpandDstUri(self, dst_uri_str):
"""
Expands wildcard if present in dst_uri_str.
Args:
dst_uri_str: String representation of requested dst_uri.
Returns:
(exp_dst_uri, have_existing_dst_container)
where have_existing_dst_container is a bool indicating whether
exp_dst_uri names an existing directory, bucket, or bucket subdirectory.
Raises:
CommandException: if dst_uri_str matched more than 1 URI.
"""
dst_uri = self.suri_builder.StorageUri(dst_uri_str)
# Handle wildcarded dst_uri case.
if ContainsWildcard(dst_uri):
blr_expansion = list(self.WildcardIterator(dst_uri))
if len(blr_expansion) != 1:
raise CommandException('Destination (%s) must match exactly 1 URI' %
dst_uri_str)
blr = blr_expansion[0]
uri = blr.GetUri()
if uri.is_cloud_uri():
return (uri, uri.names_bucket() or blr.HasPrefix()
or blr.GetKey().endswith('/'))
else:
return (uri, uri.names_directory())
# Handle non-wildcarded dst_uri:
if dst_uri.is_file_uri():
return (dst_uri, dst_uri.names_directory())
if dst_uri.names_bucket():
return (dst_uri, True)
# For object URIs check 3 cases: (a) if the name ends with '/' treat as a
# subdir; else, perform a wildcard expansion with dst_uri + "*" and then
# find if (b) there's a Prefix matching dst_uri, or (c) name is of form
# dir_$folder$ (and in both these cases also treat dir as a subdir).
if dst_uri.is_cloud_uri() and dst_uri_str.endswith('/'):
return (dst_uri, True)
blr_expansion = list(self.WildcardIterator(
'%s*' % dst_uri_str.rstrip(dst_uri.delim)))
for blr in blr_expansion:
if blr.GetRStrippedUriString().endswith('_$folder$'):
return (dst_uri, True)
if blr.GetRStrippedUriString() == dst_uri_str.rstrip(dst_uri.delim):
return (dst_uri, blr.HasPrefix())
return (dst_uri, False)
def _ConstructDstUri(self, src_uri, exp_src_uri,
src_uri_names_container, src_uri_expands_to_multi,
have_multiple_srcs, exp_dst_uri,
have_existing_dest_subdir):
"""
Constructs the destination URI for a given exp_src_uri/exp_dst_uri pair,
using context-dependent naming rules that mimic Linux cp and mv behavior.
Args:
src_uri: src_uri to be copied.
exp_src_uri: Single StorageUri from wildcard expansion of src_uri.
src_uri_names_container: True if src_uri names a container (including the
case of a wildcard-named bucket subdir (like gs://bucket/abc,
where gs://bucket/abc/* matched some objects). Note that this is
additional semantics tha src_uri.names_container() doesn't understand
because the latter only understands StorageUris, not wildcards.
src_uri_expands_to_multi: True if src_uri expanded to multiple URIs.
have_multiple_srcs: True if this is a multi-source request. This can be
true if src_uri wildcard-expanded to multiple URIs or if there were
multiple source URIs in the request.
exp_dst_uri: the expanded StorageUri requested for the cp destination.
Final written path is constructed from this plus a context-dependent
variant of src_uri.
have_existing_dest_subdir: bool indicator whether dest is an existing
subdirectory.
Returns:
StorageUri to use for copy.
Raises:
CommandException if destination object name not specified for
source and source is a stream.
"""
if self._ShouldTreatDstUriAsSingleton(
have_multiple_srcs, have_existing_dest_subdir, exp_dst_uri):
# We're copying one file or object to one file or object.
return exp_dst_uri
if exp_src_uri.is_stream():
if exp_dst_uri.names_container():
raise CommandException('Destination object name needed when '
'source is a stream')
return exp_dst_uri
if not self.recursion_requested and not have_multiple_srcs:
# We're copying one file or object to a subdirectory. Append final comp
# of exp_src_uri to exp_dst_uri.
src_final_comp = exp_src_uri.object_name.rpartition(src_uri.delim)[-1]
return self.suri_builder.StorageUri('%s%s%s' % (
exp_dst_uri.uri.rstrip(exp_dst_uri.delim), exp_dst_uri.delim,
src_final_comp))
# Else we're copying multiple sources to a directory, bucket, or a bucket
# "sub-directory".
# Ensure exp_dst_uri ends in delim char if we're doing a multi-src copy or
# a copy to a directory. (The check for copying to a directory needs
# special-case handling so that the command:
# gsutil cp gs://bucket/obj dir
# will turn into file://dir/ instead of file://dir -- the latter would cause
# the file "dirobj" to be created.)
# Note: need to check have_multiple_srcs or src_uri.names_container()
# because src_uri could be a bucket containing a single object, named
# as gs://bucket.
if ((have_multiple_srcs or src_uri.names_container()
or os.path.isdir(exp_dst_uri.object_name))
and not exp_dst_uri.uri.endswith(exp_dst_uri.delim)):
exp_dst_uri = exp_dst_uri.clone_replace_name(
'%s%s' % (exp_dst_uri.object_name, exp_dst_uri.delim)
)
# Making naming behavior match how things work with local Linux cp and mv
# operations depends on many factors, including whether the destination is a
# container, the plurality of the source(s), and whether the mv command is
# being used:
# 1. For the "mv" command that specifies a non-existent destination subdir,
# renaming should occur at the level of the src subdir, vs appending that
# subdir beneath the dst subdir like is done for copying. For example:
# gsutil rm -R gs://bucket
# gsutil cp -R dir1 gs://bucket
# gsutil cp -R dir2 gs://bucket/subdir1
# gsutil mv gs://bucket/subdir1 gs://bucket/subdir2
# would (if using cp naming behavior) end up with paths like:
# gs://bucket/subdir2/subdir1/dir2/.svn/all-wcprops
# whereas mv naming behavior should result in:
# gs://bucket/subdir2/dir2/.svn/all-wcprops
# 2. Copying from directories, buckets, or bucket subdirs should result in
# objects/files mirroring the source directory hierarchy. For | |
= fmr.TwistToScrew(self.screw_list[:, i])
#Convert TwistToScrew
self.joint_poses_home[0:3, i] = joint_pose_temp; # For plotting purposes
self.end_effector_home = new_end_effector_home
self.original_end_effector_home = self.end_effector_home.copy()
if len(self.link_home_positions) != 1:
new_link_mass_transforms = [None] * len(self.link_home_positions)
new_link_mass_transforms[0] = self.link_home_positions[0];
for i in range(1, 6):
new_link_mass_transforms[i] = (
self.link_home_positions[i-1].inv() @ self.link_home_positions[i])
new_link_mass_transforms[len(self.link_home_positions) -1] = (
self.link_home_positions[5].inv() @ self.end_effector_home)
self.link_mass_transforms = new_link_mass_transforms
self.box_spatial_links = 0
for i in range(0, self.num_dof):
self.screw_list_body[:, i] = (
fmr.Adjoint(self.end_effector_home.inv().gTM()) @ self.screw_list[:, i])
#print(new_theta)
self.FK(new_theta)
"""
__ __ _ _ _____ _ _
| \/ | | | (_) | __ \| | (_)
| \ / | ___ | |_ _ ___ _ __ | |__) | | __ _ _ __ _ __ _ _ __ __ _
| |\/| |/ _ \| __| |/ _ \| '_ \ | ___/| |/ _` | '_ \| '_ \| | '_ \ / _` |
| | | | (_) | |_| | (_) | | | | | | | | (_| | | | | | | | | | | | (_| |
|_| |_|\___/ \__|_|\___/|_| |_| |_| |_|\__,_|_| |_|_| |_|_|_| |_|\__, |
__/ |
|___/
"""
def lineTrajectory(self, target, initial = 0, execute = True,
tol = np.array([.05, .05, .05, .05, .05, .05]), delt = .01):
"""
Move the arm end effector in a straight line towards the target
Args:
target: Target pose to reach
intial: Starting pose. If set to 0, as is default, uses current position
execute: Execute the desired motion after calculation
tol: tolerances on motion
delt: delta in meters to be calculated for each step
Returns:
theta_list list of theta configurations
"""
if initial == 0:
initial = self.end_effector_pos_global.copy()
satisfied = False
init_theta = np.copy(self._theta)
theta_list = []
count = 0
while not satisfied and count < 2500:
count+=1
error = fsr.poseError(target, initial).gTAA().flatten()
satisfied = True
for i in range(6):
if abs(error[i]) > tol[i]:
satisfied = False
initial = fsr.closeLinearGap(initial, target, delt)
theta_list.append(np.copy(self._theta))
self.IK(initial, self._theta)
self.IK(target, self._theta)
theta_list.append(self._theta)
if (execute == False):
self.FK(init_theta)
return theta_list
def visualServoToTarget(self, target, tol = 2, ax = 0, plt = 0, fig = 0):
"""
Use a virtual camera to perform visual servoing to target
Args:
target: Object to move to
tol: piexel tolerance
ax: matplotlib object to draw to
plt: matplotlib plot
fig: whether or not to draw
Returns: Thetalist for arm, figure object
Returns:
theta: thetas at goal
fig: figure
"""
if (len(self.cameras) == 0):
print('NO CAMERA CONNECTED')
return
at_target = False
done = False
start_pos = self.FK(self._theta)
theta = 0
j = 0
plt.ion()
images = []
while not (at_target and done):
for i in range(len(self.cameras)):
pose_adjust = tm()
at_target = True
done = True
img, q, suc = self.cameras[i][0].getPhoto(target)
if not suc:
print('Failed to locate Target')
return self._theta
if img[0] < self.cameras[i][2][0] - tol:
pose_adjust[0] = -.01
at_target = False
if img[0] > self.cameras[i][2][0] + tol:
pose_adjust[0] = .01
at_target = False
if img[1] < self.cameras[i][2][1] - tol:
pose_adjust[1] = -.01
at_target = False
if img[1] > self.cameras[i][2][1] + tol:
pose_adjust[1] = .01
at_target = False
if at_target:
d = fsr.distance(self.end_effector_pos_global, target)
print(d)
if d < .985:
done = False
pose_adjust[2] = -.01
if d > 1.015:
done = False
pose_adjust[2] = .01
start_pos =start_pos @ pose_adjust
theta = self.IK(start_pos, self._theta)
self.updateCams()
if fig != 0:
ax = plt.axes(projection = '3d')
ax.set_xlim3d(-7, 7)
ax.set_ylim3d(-7, 7)
ax.set_zlim3d(0, 8)
DrawArm(self, ax)
DrawRectangle(target, [.2, .2, .2], ax)
print('Animating')
plt.show()
plt.savefig('VideoTemp' + '/file%03d.png' % j)
ax.clear()
j = j + 1
return theta, fig
def PDControlToGoalEE(self, theta, goal_position, Kp, Kd, prevtheta, max_theta_dot):
"""
Uses PD Control to Maneuver to an end effector goal
Args:
theta: start theta
goal_position: goal position
Kp: P parameter
Kd: D parameter
prevtheta: prev_theta parameter
max_theta_dot: maximum joint velocities
Returns:
scaled_theta_dot: scaled velocities
"""
current_end_effector_pos = self.FK(theta)
previous_end_effector_pos = self.FK(prevtheta)
error_ee_to_goal = fsr.Norm(current_end_effector_pos[0:3, 3]-goal_position[0:3, 3])
delt_distance_to_goal = (error_ee_to_goal-
fsr.Norm(previous_end_effector_pos[0:3, 3]-goal_position[0:3, 3]))
scale = Kp @ error_ee_to_goal + Kd @ min(0, delt_distance_to_goal)
twist = self.TwistSpaceToGoalEE(theta, goal_position)
twist_norm = fsr.NormalizeTwist(twist)
normalized_twist = twist/twist_norm
theta_dot = self.ThetadotSpace(theta, normalized_twist)
scaled_theta_dot = max_theta_dot/max(abs(theta_dot)) @ theta_dot @ scale
return scaled_theta_dot
"""
_____ _ _ _ _____ _ _
/ ____| | | | | /\ | | / ____| | | | |
| | __ ___| |_| |_ ___ _ __ ___ / \ _ __ __| | | (___ ___| |_| |_ ___ _ __ ___
| | |_ |/ _ \ __| __/ _ \ '__/ __| / /\ \ | '_ \ / _` | \___ \ / _ \ __| __/ _ \ '__/ __|
| |__| | __/ |_| || __/ | \__ \ / ____ \| | | | (_| | ____) | __/ |_| || __/ | \__ \
\_____|\___|\__|\__\___|_| |___/ /_/ \_\_| |_|\__,_| |_____/ \___|\__|\__\___|_| |___/
"""
def setDynamicsProperties(self, link_mass_transforms = None,
link_home_positions = None, box_spatial_links = None, link_dimensions = None):
"""
Set dynamics properties of the arm
At mimimum dimensions are a required parameter for drawing of the arm.
Args:
link_mass_transforms: The mass matrices of links
link_home_positions: List of Home Positions
box_spatial_links: Mass Matrices (Inertia)
link_dimensions: Dimensions of links
"""
self.link_mass_transforms = link_mass_transforms
self.link_home_positions = link_home_positions
self.box_spatial_links = box_spatial_links
self.link_dimensions = link_dimensions
def setMasses(self, mass):
"""
set Masses
Args:
mass: mass
"""
self.masses = mass
def testArmValues(self):
"""
prints a bunch of arm values
"""
np.set_printoptions(precision=4)
np.set_printoptions(suppress=True)
print('S')
print(self.screw_list, title = 'screw_list')
print('screw_list_body')
print(self.screw_list_body, title = 'screw_list_body')
print('Q')
print(self.joint_poses_home, title = 'joint_poses_home list')
print('end_effector_home')
print(self.end_effector_home, title = 'end_effector_home')
print('original_end_effector_home')
print(self.original_end_effector_home, title = 'original_end_effector_home')
print('_Mlinks')
print(self.link_mass_transforms, title = 'Link Masses')
print('_Mhome')
print(self.link_home_positions, title = '_Mhome')
print('_Glinks')
print(self.box_spatial_links, title = '_Glinks')
print('_dimensions')
print(self.link_dimensions, title = 'Dimensions')
def getJointTransforms(self):
"""
returns tmobjects for each link in a serial arm
Returns:
tmlist
"""
dimensions = np.copy(self.link_dimensions).conj().T
joint_pose_list = [None] * dimensions.shape[0]
end_effector_home = self.base_pos_global
end_effector_transform = tm(fmr.FKinSpace(end_effector_home.gTM(),
self.screw_list[0:6, 0:0], self._theta[0:0]))
#print(end_effector_transform, 'EEPOS')
joint_pose_list[0] = end_effector_transform
for i in range((self.num_dof)):
if self.link_home_positions == None:
temp_tm = tm()
temp_tm[0:3, 0] = self.original_joint_poses_home[0:3, i]
end_effector_home = self.base_pos_global @ temp_tm
else:
end_effector_home = self.link_home_positions[i]
#print(end_effector_home, 'end_effector_home' + str(i + 1))
#print(self._theta[0:i+1])
end_effector_transform = tm(fmr.FKinSpace(end_effector_home.gTM(),
self.screw_list[0:6, 0:i], self._theta[0:i]))
#print(end_effector_transform, 'EEPOS')
joint_pose_list[i] = end_effector_transform
if dimensions.shape[0] > self.num_dof:
#Fix handling of dims
#print(fsr.TAAtoTM(np.array([0.0, 0.0, self.link_dimensions[-1, 2], 0.0 , 0.0, 0.0])))
joint_pose_list[len(joint_pose_list) - 1] = self.FK(self._theta)
#if self.eef_transform is not None:
# joint_pose_list.append(joint_pose_list[-1] @ self.eef_transform)
return joint_pose_list
def setArbitraryHome(self, theta,T):
"""
# Given a pose and some T in the space frame, find out where
# that T is in the EE frame, then find the home pose for
# that arbitrary pose
Args:
theta: theta configuration
T: new transform
"""
end_effector_temp = self.FK(theta)
ee_to_new = np.cross(np.inv(end_effector_temp),T)
self.end_effector_home = np.cross(self.end_effector_home, ee_to_new)
#Converted to Python - Joshua
def restoreOriginalEE(self):
"""
Retstore the original End effector of the Arm
"""
self.end_effector_home = self.original_end_effector_home
def getEEPos(self):
"""
Gets End Effector Position
"""
#if self.eef_transform is not None:
# return self.end_effector_pos_global.copy() @ self.eef_transform
return self.end_effector_pos_global.copy()
def getScrewList(self):
"""
Returns screw list in space
Return:
screw list
"""
return self.screw_list.copy()
def getLinkDimensions(self):
"""
Returns link dimensions
Return:
link dimensions
"""
return self.link_dimensions.copy()
"""
______ _ _____ _
| ____| | | | __ \ (_)
| |__ ___ _ __ ___ ___ ___ __ _ _ __ __| | | | | |_ _ _ __ __ _ _ __ ___ _ ___ ___
| __/ _ \| '__/ __/ _ \/ __| / _` | '_ \ / _` | | | | | | | | '_ \ / _` | '_ ` _ \| |/ __/ __|
| | | (_) | | | (_| __/\__ \ | (_| | | | | (_| | | |__| | |_| | | | | (_| | | | | | | | (__\__ \
|_| \___/|_| \___\___||___/ \__,_|_| |_|\__,_| |_____/ \__, |_| |_|\__,_|_| |_| |_|_|\___|___/
__/ | |
in self.all_text_fields:
attr_input = getattr(batch, name)
embeddings = inv_freq_pool(embed[name](attr_input))
attr_embeddings[name].append(embeddings.data.data)
# Compute the first principal component of weighted sequence embeddings for each
# attribute.
pc = {}
for name in self.all_text_fields:
concatenated = torch.cat(attr_embeddings[name])
svd = TruncatedSVD(n_components=1, n_iter=7)
svd.fit(concatenated.numpy())
pc[name] = svd.components_[0]
self.metadata["pc"] = pc
def finalize_metadata(self):
r"""Perform final touches to dataset metadata.
This allows performing modifications to metadata that cannot be serialized into
the cache.
"""
self.orig_metadata = copy.deepcopy(self.metadata)
for name in self.all_text_fields:
self.metadata["word_probs"][name] = defaultdict(
lambda: 1 / self.metadata["totals"][name],
self.metadata["word_probs"][name],
)
def get_raw_table(self):
r"""Create a raw pandas table containing all examples (tuple pairs) in the dataset.
To resurrect tokenized attributes, this method currently naively joins the tokens
using the whitespace delimiter.
"""
rows = []
columns = [name for name, field in six.iteritems(self.fields) if field]
for ex in self.examples:
row = []
for attr in columns:
if self.fields[attr]:
val = getattr(ex, attr)
if self.fields[attr].sequential:
val = " ".join(val)
row.append(val)
rows.append(row)
return pd.DataFrame(rows, columns=columns)
def sort_key(self, ex):
r"""Sort key for dataset examples.
A key to use for sorting dataset examples for batching together examples with
similar lengths to minimize padding.
"""
return interleave_keys(
[len(getattr(ex, attr)) for attr in self.all_text_fields]
)
@staticmethod
def save_cache(datasets, fields, datafiles, cachefile, column_naming, state_args):
r"""Save datasets and corresponding metadata to cache.
This method also saves as many data loading arguments as possible to help ensure
that the cache contents are still relevant for future data loading calls. Refer
to :meth:`~data.Dataset.load_cache` for more details.
Arguments:
datasets (list): List of datasets to cache.
fields (dict): Mapping from attribute names (e.g. "left_address") to
corresponding :class:`~data.MatchingField` objects that specify how to
process the field.
datafiles (list): A list of the data files.
cachefile (str): The cache file path.
column_naming (dict): A `dict` containing column naming conventions. See
`__init__` for details.
state_args (dict): A `dict` containing other information about the state under
which the cache was created.
"""
examples = [dataset.examples for dataset in datasets]
train_metadata = datasets[0].metadata
datafiles_modified = [os.path.getmtime(datafile) for datafile in datafiles]
vocabs = {}
field_args = {}
reverse_fields = {}
for name, field in six.iteritems(fields):
reverse_fields[field] = name
for field, name in six.iteritems(reverse_fields):
if field is not None and hasattr(field, "vocab"):
vocabs[name] = field.vocab
for name, field in six.iteritems(fields):
field_args[name] = None
if field is not None:
field_args[name] = field.preprocess_args()
data = {
"examples": examples,
"train_metadata": train_metadata,
"vocabs": vocabs,
"datafiles": datafiles,
"datafiles_modified": datafiles_modified,
"field_args": field_args,
"state_args": state_args,
"column_naming": column_naming,
}
torch.save(data, cachefile)
@staticmethod
def load_cache(fields, datafiles, cachefile, column_naming, state_args):
r"""Load datasets and corresponding metadata from cache.
This method also checks whether any of the data loading arguments have changes
that make the cache contents invalid. The following kinds of changes are currently
detected automatically:
* Data filename changes (e.g. different train filename)
* Data file modifications (e.g. train data modified)
* Column changes (e.g. using a different subset of columns in CSV file)
* Column specification changes (e.g. changing lowercasing behavior)
* Column naming convention changes (e.g. different labeled data column)
Arguments:
fields (dict): Mapping from attribute names (e.g. "left_address") to
corresponding :class:`~data.MatchingField` objects that specify how to
process the field.
datafiles (list): A list of the data files.
cachefile (str): The cache file path.
column_naming (dict): A `dict` containing column naming conventions. See
`__init__` for details.
state_args (dict): A `dict` containing other information about the state under
which the cache was created.
Returns:
Tuple containing unprocessed cache data dict and a list of cache staleness
causes, if any.
.. warning::
Note that if a column specification, i.e., arguments to
:class:`~data.MatchingField` include callable arguments (e.g. lambdas or
functions) these arguments cannot be serialized and hence will not be checked
for modifications.
"""
cached_data = torch.load(cachefile)
cache_stale_cause = set()
if datafiles != cached_data["datafiles"]:
cache_stale_cause.add("Data file list has changed.")
datafiles_modified = [os.path.getmtime(datafile) for datafile in datafiles]
if datafiles_modified != cached_data["datafiles_modified"]:
cache_stale_cause.add("One or more data files have been modified.")
if set(fields.keys()) != set(cached_data["field_args"].keys()):
cache_stale_cause.add("Fields have changed.")
for name, field in six.iteritems(fields):
none_mismatch = (field is None) != (cached_data["field_args"][name] is None)
args_mismatch = False
if field is not None and cached_data["field_args"][name] is not None:
args_mismatch = (
field.preprocess_args() != cached_data["field_args"][name]
)
if none_mismatch or args_mismatch:
cache_stale_cause.add("Field arguments have changed.")
if field is not None and not isinstance(field, MatchingField):
cache_stale_cause.add("Cache update required.")
if column_naming != cached_data["column_naming"]:
cache_stale_cause.add("Other arguments have changed.")
cache_stale_cause.update(
MatchingDataset.state_args_compatibility(
state_args, cached_data["state_args"]
)
)
return cached_data, cache_stale_cause
@staticmethod
def state_args_compatibility(cur_state, old_state):
errors = []
if not old_state["train_pca"] and cur_state["train_pca"]:
errors.append("PCA computation necessary.")
return errors
@staticmethod
def restore_data(fields, cached_data):
r"""Recreate datasets and related data from cache.
This restores all datasets, metadata and attribute information (including the
vocabulary and word embeddings for all tokens in each attribute).
"""
datasets = []
for d in range(len(cached_data["datafiles"])):
metadata = None
if d == 0:
metadata = cached_data["train_metadata"]
dataset = MatchingDataset(
path=cached_data["datafiles"][d],
fields=fields,
examples=cached_data["examples"][d],
metadata=metadata,
column_naming=cached_data["column_naming"],
)
datasets.append(dataset)
for name, field in fields:
if name in cached_data["vocabs"]:
field.vocab = cached_data["vocabs"][name]
return datasets
@classmethod
def splits(
cls,
path,
train=None,
validation=None,
test=None,
fields=None,
embeddings=None,
embeddings_cache=None,
column_naming=None,
cache=None,
check_cached_data=True,
auto_rebuild_cache=False,
train_pca=False,
**kwargs
):
"""Create Dataset objects for multiple splits of a dataset.
Args:
path (str): Common prefix of the splits' file paths.
train (str): Suffix to add to path for the train set.
validation (str): Suffix to add to path for the validation set, or None
for no validation set. Default is None.
test (str): Suffix to add to path for the test set, or None for no test
set. Default is None.
fields (list(tuple(str, MatchingField))): A list of tuples containing column
name (e.g. "left_address") and corresponding :class:`~data.MatchingField`
pairs, in the same order that the columns occur in the CSV file. Tuples of
(name, None) represent columns that will be ignored.
embeddings (str or list): Same as `embeddings` parameter of
:func:`~data.process`.
embeddings_cache (str): Directory to store dowloaded word vector data.
column_naming (dict): Same as `column_naming` paramter of `__init__`.
cache (str): Suffix to add to path for cache file. If `None` disables caching.
check_cached_data (bool): Verify that data files haven't changes since the
cache was constructed and that relevant field options haven't changed.
auto_rebuild_cache (bool): Automatically rebuild the cache if the data files
are modified or if the field options change. Defaults to False.
train_pca (bool): Whether to compute PCA for each attribute as part of
dataset metadata compuatation. Defaults to False.
filter_pred (callable or None): Use only examples for which
filter_pred(example) is True, or use all examples if None.
Default is None. This is a keyword-only parameter.
Returns:
Tuple[MatchingDataset]: Datasets for (train, validation, and test) splits in
that order, if provided.
"""
fields_dict = dict(fields)
state_args = {"train_pca": train_pca}
datasets = None
if cache:
datafiles = [f for f in (train, validation, test) if f is not None]
datafiles = [os.path.expanduser(os.path.join(path, d)) for d in datafiles]
cachefile = os.path.expanduser(os.path.join(path, cache))
try:
cached_data, cache_stale_cause = MatchingDataset.load_cache(
fields_dict, datafiles, cachefile, column_naming, state_args
)
if check_cached_data and cache_stale_cause:
if not auto_rebuild_cache:
raise MatchingDataset.CacheStaleException(cache_stale_cause)
else:
logger.warning(
"Rebuilding data cache because: %s", list(cache_stale_cause)
)
if not check_cached_data or not cache_stale_cause:
datasets = MatchingDataset.restore_data(fields, cached_data)
except IOError:
pass
if not datasets:
begin = timer()
dataset_args = {"fields": fields, "column_naming": column_naming, **kwargs}
train_data = (
None
if train is None
else cls(path=os.path.join(path, train), **dataset_args)
)
val_data = (
None
if validation is None
else cls(path=os.path.join(path, validation), **dataset_args)
)
test_data = (
None
if test is None
else cls(path=os.path.join(path, test), **dataset_args)
)
datasets = tuple(
d for d in (train_data, val_data, test_data) if d is not None
)
after_load = timer()
logger.info("Data load took: {}s".format(after_load - begin))
fields_set = set(fields_dict.values())
for field in fields_set:
if field is not None and field.use_vocab:
field.build_vocab(
*datasets, vectors=embeddings, cache=embeddings_cache
)
after_vocab = timer()
logger.info("Vocab construction time: {}s".format(after_vocab - after_load))
if train:
datasets[0].compute_metadata(train_pca)
after_metadata = timer()
logger.info(
"Metadata computation time: {}s".format(after_metadata - after_vocab)
)
if cache:
MatchingDataset.save_cache(
datasets,
fields_dict,
datafiles,
cachefile,
column_naming,
state_args,
)
after_cache = timer()
logger.info("Cache save time: | |
<reponame>dmort27/kairos-yaml
"""Converts CMU YAML into KAIROS SDF JSON-LD."""
import argparse
from collections import Counter, defaultdict
import itertools
import json
import logging
from pathlib import Path
import random
import typing
from typing import Any, List, Mapping, MutableMapping, Optional, Sequence, Tuple, Union
from pydantic import parse_obj_as
import requests
from typing_extensions import TypedDict
import yaml
from yaml_schema import Before, Container, Overlaps, Schema, Slot, Step
ONTOLOGY: Optional[Mapping[str, Any]] = None
def get_ontology() -> Mapping[str, Any]:
"""Loads the ontology from the JSON file.
Returns:
Ontology.
"""
global ONTOLOGY # pylint: disable=global-statement
if ONTOLOGY is None:
with Path("ontology.json").open() as file:
ONTOLOGY = json.load(file)
return ONTOLOGY
def get_step_type(step: Step) -> str:
"""Gets type of step.
Args:
step: Step data.
Returns:
Step type.
"""
# Add missing "Unspecified"s
primitive_segments = step.primitive.split(".")
if len(primitive_segments) < 3:
primitive_segments.extend(["Unspecified"] * (3 - len(primitive_segments)))
primitive = ".".join(primitive_segments)
if primitive not in get_ontology()['events']:
logging.warning(f"Primitive '{step.primitive}' in step '{step.id}' not in ontology")
return f"kairos:Primitives/Events/{primitive}"
def get_slot_role(slot: Slot, step_type: str) -> str:
"""Gets slot role.
Args:
slot: Slot data.
step_type: Type of step.
Returns:
Slot role.
"""
event_type = get_ontology()['events'].get(step_type.split("/")[-1], None)
if event_type is not None and slot.role not in event_type['args']:
logging.warning(f"Role '{slot.role}' is not valid for event '{event_type['type']}'")
return f"{step_type}/Slots/{slot.role}"
def get_slot_name(slot: Slot, slot_shared: bool) -> str:
"""Gets slot name.
Args:
slot: Slot data.
slot_shared: Whether slot is shared.
Returns:
Slot name.
"""
name = "".join([' ' + x if x.isupper() else x for x in slot.role]).lstrip()
name = name.split()[0].lower()
if slot_shared and slot.refvar is not None:
name += "-" + slot.refvar
return name
def get_slot_id(slot: Slot, schema_slot_counter: typing.Counter[str],
schema_id: str, slot_shared: bool) -> str:
"""Gets slot ID.
Args:
slot: Slot data.
schema_slot_counter: Slot counter.
schema_id: Schema ID.
slot_shared: Whether slot is shared.
Returns:
Slot ID.
"""
slot_name = get_slot_name(slot, slot_shared)
slot_id = chr(schema_slot_counter[slot_name] + 97)
schema_slot_counter[slot_name] += 1
return f"{schema_id}/Slots/{slot_name}-{slot_id}"
def get_slot_constraints(constraints: Sequence[str]) -> Sequence[str]:
"""Gets slot constraints.
Args:
constraints: Constraints.
Returns:
Slot constraints.
"""
for entity in constraints:
if entity not in get_ontology()['entities']:
logging.warning(f"Entity '{entity}' not in ontology")
return [f"kairos:Primitives/Entities/{entity}" for entity in constraints]
def create_slot(slot: Slot, schema_slot_counter: typing.Counter[str], schema_id: str, step_type: str,
slot_shared: bool, entity_map: MutableMapping[str, Any]) -> MutableMapping[str, Any]:
"""Gets slot.
Args:
slot: Slot data.
schema_slot_counter: Slot counter.
schema_id: Schema ID.
step_type: Type of step.
slot_shared: Whether slot is shared.
entity_map: Mapping from mentions to entities.
Returns:
Slot.
"""
cur_slot: MutableMapping[str, Any] = {
"name": get_slot_name(slot, slot_shared),
"@id": get_slot_id(slot, schema_slot_counter, schema_id, slot_shared),
"role": get_slot_role(slot, step_type),
}
constraints = get_slot_constraints(slot.constraints if slot.constraints is not None else [])
if constraints:
cur_slot["entityTypes"] = constraints
if slot.reference is not None:
cur_slot["reference"] = slot.reference
# Get entity ID for relations
if slot.refvar is not None:
entity_map[cur_slot["@id"]] = slot.refvar
cur_slot["refvar"] = slot.refvar
else:
logging.warning(f"{slot} misses refvar")
entity_map[cur_slot["@id"]] = str(random.random())
if slot.comment is not None:
cur_slot["comment"] = slot.comment
return cur_slot
def get_step_id(step: Step, schema_id: str) -> str:
"""Gets step ID.
Args:
step: Step data.
schema_id: Schema ID.
Returns:
Step ID.
"""
return f"{schema_id}/Steps/{step.id}"
def convert_yaml_to_sdf(yaml_data: Schema) -> Mapping[str, Any]:
"""Converts YAML to SDF.
Args:
yaml_data: Data from YAML file.
Returns:
Schema in SDF format.
"""
# assigned_info["schema_name"] = ''.join([' ' + x if x.isupper() else x for x
# in assigned_info["schema_id"][len("cmu:"):]]).lstrip()
# assigned_info["schema_name"] = assigned_info["schema_name"][0] + \
# assigned_info["schema_name"][1:].lower()
schema: MutableMapping[str, Any] = {
"@id": yaml_data.schema_id,
"comment": '',
"super": "kairos:Event",
"name": yaml_data.schema_name,
"description": yaml_data.schema_dscpt,
"version": yaml_data.schema_version,
"steps": [],
"order": [],
"entityRelations": []
}
# Get comments
comments = [x.id.replace("-", " ") for x in yaml_data.steps]
comments = ["Steps:"] + [f"{idx + 1}. {text}" for idx, text in enumerate(comments)]
schema["comment"] = comments
# Get steps
steps = []
# For sameAs relation
entity_map: MutableMapping[str, Any] = {}
# For order
class StepMapItem(TypedDict):
id: str
step_idx: int
step_map: MutableMapping[str, StepMapItem] = {}
# For naming slot ID
schema_slot_counter: typing.Counter[str] = Counter()
for idx, step in enumerate(yaml_data.steps):
cur_step: MutableMapping[str, Any] = {
"@id": get_step_id(step, schema["@id"]),
"name": step.id,
"@type": get_step_type(step),
"comment": comments[idx + 1],
}
if step.comment is not None:
cur_step["comment"] += "\n" + step.comment
# if "provenance" in step:
# cur_step["provenance"] = step["provenance"]
step_map[step.id] = {"id": cur_step["@id"], "step_idx": idx + 1}
slots = []
for slot in step.slots:
slot_shared = sum([slot.role == sl.role for sl in step.slots]) > 1
slots.append(
create_slot(slot, schema_slot_counter, schema["@id"], cur_step["@type"], slot_shared, entity_map))
cur_step["participants"] = slots
steps.append(cur_step)
slots = []
for slot in yaml_data.slots:
slot_shared = sum([slot.role == sl.role for sl in yaml_data.slots]) > 1
parsed_slot = create_slot(slot, schema_slot_counter, schema["@id"], schema["@id"], slot_shared, entity_map)
parsed_slot["roleName"] = parsed_slot["role"]
del parsed_slot["role"]
slots.append(parsed_slot)
schema["slots"] = slots
# Cleaning "-a" suffix for slots with counter == 1.
for cur_step in steps:
for cur_slot in cur_step["participants"]:
if schema_slot_counter[cur_slot["name"]] == 1:
temp = entity_map[cur_slot["@id"]]
del entity_map[cur_slot["@id"]]
cur_slot["@id"] = cur_slot["@id"].strip("-a")
entity_map[cur_slot["@id"]] = temp
schema["steps"] = steps
step_ids = set(step.id for step in yaml_data.steps)
order_tuples: List[Tuple[str, ...]] = []
for order in yaml_data.order:
if isinstance(order, Before):
order_tuples.append((order.before, order.after))
elif isinstance(order, Container):
order_tuples.append((order.container, order.contained))
elif isinstance(order, Overlaps):
order_tuples.append(tuple(order.overlaps))
else:
raise NotImplementedError
order_ids = set(itertools.chain.from_iterable(order_tuples))
missing_order_ids = order_ids - step_ids
if missing_order_ids:
for missing_id in missing_order_ids:
logging.error(f"The ID '{missing_id}' in `order` is not in `steps`")
exit(1)
base_order_id = f'{schema["@id"]}/Order/'
orders = []
for order in yaml_data.order:
if isinstance(order, Before):
before_idx = step_map[order.before]['step_idx']
before_id = step_map[order.before]['id']
after_idx = step_map[order.after]['step_idx']
after_id = step_map[order.after]['id']
if not before_id and not before_idx:
logging.warning(f"before: {order.before} does not appear in the steps")
if not after_id and not after_idx:
logging.warning(f"after: {order.after} does not appear in the steps")
cur_order: Mapping[str, Union[str, Sequence[str]]] = {
"@id": f"{base_order_id}precede-{before_idx}-{after_idx}",
"comment": f"{before_idx} precedes {after_idx}",
"before": before_id,
"after": after_id
}
elif isinstance(order, Container):
container_idx = step_map[order.container]['step_idx']
container_id = step_map[order.container]['id']
contained_idx = step_map[order.contained]['step_idx']
contained_id = step_map[order.contained]['id']
if not container_id and not container_idx:
logging.warning(f"container: {order.container} does not appear in the steps")
if not contained_id and not contained_idx:
logging.warning(f"contained: {order.contained} does not appear in the steps")
cur_order = {
"@id": f"{base_order_id}contain-{container_idx}-{contained_idx}",
"comment": f"{container_idx} contains {contained_idx}",
"container": container_id,
"contained": contained_id
}
elif isinstance(order, Overlaps):
overlaps_idx = []
overlaps_id = []
for overlap in order.overlaps:
overlap_idx = step_map[overlap]['step_idx']
overlap_id = step_map[overlap]['id']
if not overlap_id and not overlap_idx:
logging.warning(f"overlaps: {overlap_id} does not appear in the steps")
overlaps_idx.append(overlap_idx)
overlaps_id.append(overlap_id)
cur_order = {
"@id": f"{base_order_id}overlap-{'-'.join(str(i) for i in overlaps_idx)}",
"comment": f"{', '.join(str(i) for i in overlaps_idx)} overlaps",
"overlaps": overlaps_id,
}
else:
raise NotImplementedError
orders.append(cur_order)
schema["order"] = orders
# Get entity relations
entity_map = {x: y for x, y in entity_map.items() if y is not None}
# Get same as relation
reverse_entity_map = defaultdict(list)
for k, v in entity_map.items():
reverse_entity_map[v].append(k)
entity_relations: Sequence[Any] = []
# for v in reverse_entity_map.values():
# cur_entity_relation = {
# "relationSubject": v[0],
# "relations": [{
# "relationPredicate": "kairos:Relations/sameAs",
# "relationObject": x
# } for x in v[1:]]
# }
# if cur_entity_relation["relations"]:
# entity_relations.append(cur_entity_relation)
schema["entityRelations"] = entity_relations
return schema
def merge_schemas(schema_list: Sequence[Mapping[str, Any]], library_id: str) -> Mapping[str, Any]:
"""Merge multiple schemas.
Args:
schema_list: List of SDF schemas.
library_id: ID of schema collection.
Returns:
Data in JSON output format.
"""
sdf = {
"@context": ["https://kairos-sdf.s3.amazonaws.com/context/kairos-v0.9.jsonld"],
"sdfVersion": "0.9",
"@id": library_id,
"schemas": schema_list,
}
return sdf
def validate_schemas(json_data: Mapping[str, Any]) -> None:
"""Validates generated schema against the program validator.
The program validator is not always avoilable, so the request will time out if no response is
received within 10 seconds.
Args:
json_data: Data in JSON output format.
"""
try:
req = requests.post("http://validation.kairos.nextcentury.com/json-ld/ksf/validate",
json=json_data,
headers={
"Accept": "application/json",
"Content-Type": "application/ld+json"
},
timeout=10)
except requests.exceptions.Timeout:
logging.warning("Program validator is unavailable, so schema might not validate")
else:
response = req.json()
validator_messages = response['errorsList'] + response['warningsList']
if validator_messages:
print('Messages from program validator:')
for message in validator_messages:
print(f'\t{message}')
def convert_all_yaml_to_sdf(yaml_schemas: Sequence[Mapping[str, Any]], library_id: str) -> Mapping[str, Any]:
"""Convert YAML schema library into SDF schema library.
Args:
yaml_schemas: YAML schemas.
library_id: ID of schema collection.
Returns:
Data in JSON output format.
"""
sdf_schemas = []
parsed_yaml = parse_obj_as(List[Schema], yaml_schemas)
if [p.dict(exclude_none=True) for p in parsed_yaml] != yaml_schemas:
raise RuntimeError(
"The parsed and raw schemas do not match. The schema might have misordered fields, or there is a bug in this script.")
for yaml_schema in parsed_yaml:
out_json = convert_yaml_to_sdf(yaml_schema)
sdf_schemas.append(out_json)
json_data = merge_schemas(sdf_schemas, library_id)
validate_schemas(json_data)
return json_data
def convert_files(yaml_files: Sequence[Path], json_file: Path) -> None:
"""Converts YAML files into | |
from django import forms
from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from django.core.cache import cache
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.db.models import Avg, Max, Min, Count, Sum, F
from django.template import RequestContext, Context, Template, loader
from django.views.decorators.cache import cache_page
from server.twitinfo.models import Event,Tweet,Keyword,WordFrequency
from datetime import datetime,timedelta
from operator import itemgetter
import itertools
import json
import nltk
import re
import random
import sys
import settings
sys.path.append(settings.SSQL_PATH)
from ssql.builtin_functions import MeanOutliers
NUM_TWEETS = 20 # total tweets to display
NUM_LINKS = 3 # total top links to display
URL_REGEX = re.compile("http\:\/\/\S+")
CACHE_SECONDS = 864000
def twitinfo(request):
featured = Event.objects.filter(featured = True)
return render_to_response('twitinfo/twitinfo.html', {"featured":featured})
def search_results(request):
search = Event.normalize_name(request.GET['query'])
events = Event.objects.filter(name = search)
events_from_keywords = Event.objects.filter(keywords__key_word=search)
total_events=itertools.chain(events,events_from_keywords)
total_events=list(total_events)
if len(total_events)==0:
return render_to_response('twitinfo/results.html', {'error':'Sorry, the keyword you searched for does not exist.'},
context_instance=RequestContext(request))
else:
return render_to_response('twitinfo/results.html', {'events':total_events},
context_instance=RequestContext(request))
def event_details(request,event_id):
try:
keys=[]
event = Event.objects.get(pk=event_id)
keywords = Keyword.objects.filter(event=event_id).values_list('key_word', flat=True)
keys=", ".join(keywords)
except Event.DoesNotExist:
return render_to_response('twitinfo/details.html', {'error':'Event does not exit!'},
context_instance=RequestContext(request))
return render_to_response('twitinfo/details.html', {'event':event,'keywords':keys},
context_instance=RequestContext(request))
class TweetDateForm(forms.Form):
start_date = forms.DateTimeField(input_formats=["%Y-%m-%d %H:%M"],required=False)
end_date = forms.DateTimeField(input_formats=["%Y-%m-%d %H:%M"],required=False)
words = forms.CharField(required=False)
def display_tweets(request,event_id):
key = request.get_full_path()
print "fp: %s" % key
resp_string = cache.get(key)
if resp_string == None:
print "no cache"
resp_string = display_tweets_impl(request, event_id)
cache.set(key, resp_string, CACHE_SECONDS)
print "after getting data"
return HttpResponse(resp_string)
def display_tweets_impl(request,event_id):
try:
print "before"
event = Event.objects.get(pk=event_id)
print "uh"
except Event.DoesNotExist:
return render_to_response('twitinfo/display_tweets.html', {'error':'Event does not exit!'},
context_instance=RequestContext(request))
tweets = Tweet.objects.filter(keyword__event=event_id)
print "generated tweets query"
form = TweetDateForm(request.REQUEST)
if form.is_valid():
print "getting date data"
start_date = form.cleaned_data['start_date']
end_date = form.cleaned_data['end_date']
start_date = start_date if start_date != None else event.start_date
end_date = end_date if end_date != None else event.end_date
if start_date != None:
tweets = tweets.filter(created_at__gte = start_date)
if end_date != None:
tweets = tweets.filter(created_at__lte = end_date)
tweets = tweets.order_by("created_at")#+
words = form.cleaned_data['words']
if len(words) == 0:
print "no words"
tweets = tweets[:NUM_TWEETS]
else:
print "splitting tweets"
words = words.split(",")
matched_tweets = []
already_tweets = set()
for tweet in tweets[:500]:
count = 0
text = tweet.tweet.lower()
if "rt" in text:
count -= 2
text = URL_REGEX.sub("WEBSITE", text)
if text not in already_tweets:
for word in words:
if word in text:
count += 1
matched_tweets.append((tweet, count))
already_tweets.add(text)
matched_tweets.sort(cmp=lambda a,b: cmp(b[1],a[1]))
tweets = [t[0] for t in matched_tweets[:min(NUM_TWEETS,len(matched_tweets))]]
t = loader.get_template('twitinfo/display_tweets.html')
print len(tweets)
resp_string = t.render(Context({'tweets': tweets,'event':event}))
return resp_string
def display_links(request,event_id):
key = request.get_full_path()
resp_string = cache.get(key)
if resp_string == None:
resp_string = display_links_impl(request, event_id)
cache.set(key, resp_string, CACHE_SECONDS)
return HttpResponse(resp_string)
def display_links_impl(request,event_id):
try:
event = Event.objects.get(pk=event_id)
except Event.DoesNotExist:
return 'Event does not exit!'
tweets = Tweet.objects.filter(keyword__event=event_id)
form = TweetDateForm(request.REQUEST)
if form.is_valid():
start_date = form.cleaned_data['start_date']
end_date = form.cleaned_data['end_date']
start_date = start_date if start_date != None else event.start_date
end_date = end_date if end_date != None else event.end_date
if start_date != None:
tweets = tweets.filter(created_at__gte = start_date)
if end_date != None:
tweets = tweets.filter(created_at__lte = end_date)
tweets = tweets.order_by("created_at")#+
links = {}
for tweet in tweets[:500]:
text = tweet.tweet
incr = 1
if "RT" in text:
incr = .5
for match in URL_REGEX.findall(text):
count = links.get(match, 0.0)
count += incr
links[match] = count
linkcounts = links.items()
linkcounts.sort(key = itemgetter(1), reverse = True)
displaylinks = []
for i in range(0, min(len(linkcounts), NUM_LINKS)):
if linkcounts[i][1] > 2.5:
displaylinks.append((linkcounts[i][0], int(linkcounts[i][1])))
t = loader.get_template('twitinfo/display_links.html')
resp_string = t.render(Context({'links': displaylinks}))
return resp_string
class EventForm(forms.Form):
title=forms.CharField(max_length=100)
key_words = forms.CharField()
start_date = forms.DateTimeField(input_formats=["%Y-%m-%d %H:%M"],required=False)
end_date = forms.DateTimeField(input_formats=["%Y-%m-%d %H:%M"],required=False)
parent_id = forms.IntegerField(widget=forms.HiddenInput,required=False)
def create_event(request):
if request.method == 'POST': # If the form has been submitted...
form = EventForm(request.POST) # A form bound to the POST data
if form.is_valid():
name = form.cleaned_data['title']
name = Event.normalize_name(name)
key_words = form.cleaned_data['key_words']
list_keywords = Keyword.normalize_keywords(key_words)
keyobjs=[]
for key in list_keywords:
try:
fkeyword = Keyword.objects.get(key_word = key)
except Keyword.DoesNotExist:
fkeyword = Keyword(key_word = key)
fkeyword.save()
keyobjs.append(fkeyword)
e = Event(name = name,start_date = None,end_date = None)
try:
e.start_date = form.cleaned_data['start_date']
except:
pass
try:
e.end_date = form.cleaned_data['end_date']
except:
pass
e.save()
e.keywords = keyobjs
try:
parent = form.cleaned_data['parent_id']
parent_event = Event.objects.get(id=parent)
parent_event.children.add(e)
cache.delete("graph" + str(parent)) # clear parent view to include child
except Event.DoesNotExist:
pass
return HttpResponseRedirect('detail/%d' % (e.id)) # Redirect after POST
else:
# initialize the form with a set of values that are passed in as data. If there are no initial values,initialize an empty form.
try:
parent_id=request.GET["parent_id"]
keywords=request.GET["keywords"]
sd=request.GET["start_date"]
ed=request.GET["end_date"]
data={'start_date':sd,'end_date':ed,'key_words':keywords,'parent_id':parent_id,'title':" "}
form = EventForm(data)
except:
form = EventForm()
return render_to_response('twitinfo/create_event.html', {'form': form}, context_instance=RequestContext(request))
def find_end_dates(tweets,list_peaks):
i=0
k=0
if len(list_peaks) > 0:
while(i<len(list_peaks) and i+1<len(list_peaks)):
for j in range(len(tweets)):
if(list_peaks[i]["start_date"]==tweets[j]['date']):
k=j+1
break
while(k<len(tweets)):
if(list_peaks[i+1]['start_date']==tweets[k]['date'] or tweets[k]['num_tweets']<=list_peaks[i]["start_freq"] or k==len(tweets)-1):
end_date=tweets[k]['date']
list_peaks[i]["end_date"]=end_date
break
k+=1
i+=1
for l in range(len(tweets)):
if(list_peaks[len(list_peaks)-1]["start_date"]==tweets[l]['date']):
k=l+1
break
while(k<len(tweets)):
if( tweets[k]['num_tweets']<=list_peaks[len(list_peaks)-1]["start_freq"] or k==(len(tweets)-1)):
end_date=tweets[k]['date']
list_peaks[len(list_peaks)-1]["end_date"]=end_date
k+=1
return list_peaks
def words_by_tfidf(dic, keywords):
freq_words = WordFrequency.objects.filter(word__in = dic.iterkeys()).values_list('word', 'idf')
# multiply by -1*idf if it exists in the idf list. record the largest
# idf witnessed
maxidf = 0
for word, idf in freq_words:
if word in dic:
dic[word] *= -1 * idf
if idf > maxidf:
maxidf = idf
# for all idfs which existed, make the tfidf positive again.
# for all already-positive idfs (which didn't have an idf for this
# word), multiply by 10 more than the largest idf in the list.
maxidf += 10
for word, idf in dic.items():
if idf < 0:
dic[word] *= -1
else:
dic[word] *= maxidf
words = dic.keys()
words.sort(cmp=lambda a,b: cmp(dic[b],dic[a]))
return words
def find_max_terms(tweets, keywords):
total_freq=0
words_dict={}
stopwords = set(nltk.corpus.stopwords.words('english'))
stopwords.add("rt")
for tweet in tweets:
text = tweet.tweet
tweet_text=text.lower().replace("'","").split()
for word in tweet_text:
if word in stopwords:
continue
if words_dict.has_key(word):
words_dict[word]+=1
else:
words_dict[word]=1
return words_by_tfidf(words_dict, keywords)
def annotate_peaks(peaks,tweets,event_id,keywords):
list_keywords = ", ".join(keywords)
for peak in peaks:
sdt = convert_date(peak['start_date'])
edt = convert_date(peak['end_date'])
t=Tweet.objects.filter(keyword__event=event_id).filter(created_at__gte=sdt).filter(created_at__lte=edt)
sorted_list=find_max_terms(t, keywords)
for tweet in tweets:
if peak['peak_date']==tweet['date']:
tweet['title']="'" +", ".join(sorted_list[:5])+"'"
tweet['data']={'event':event_id,'keywords':list_keywords,'start_date':sdt.strftime("%Y-%m-%d %H:%M"),'end_date':edt.strftime("%Y-%m-%d %H:%M")}
return tweets
def convert_date(date):
d=date.split(',')
d=map(int , d)
dt=datetime(*d)
return dt
def create_graph(request,event_id):
key = "graph" + event_id
resp_string = cache.get(key)
if resp_string == None:
resp_string = create_graph_impl(request, event_id)
cache.set(key, resp_string, CACHE_SECONDS)
resp_string = request.GET["jsoncallback"] + resp_string
return HttpResponse(resp_string)
def create_graph_impl(request, event_id):
e = Event.objects.get(id=event_id)
sdate = e.start_date
edate = e.end_date
tweets = Tweet.objects.filter(keyword__event = event_id)
if sdate == None:
sdate=tweets.order_by('created_at')[0].created_at
if edate == None:
edate=tweets.order_by('-created_at')[0].created_at
tdelta=(edate-sdate)
total_sec=tdelta.seconds + tdelta.days * 24 *3600
total_min=total_sec / 60.0
total_hours=total_min / 60.0
if total_min <= 1440:
td=timedelta(minutes=1)
sec_divisor = 60
stf = {"date": ('%Y,%m,%d,%H,%M'),"d": 'new Date(%Y,%m-1,%d,%H,%M)'}
if settings.DATABASES['default']['ENGINE'] == 'postgresql_psycopg2':
select_data = {"d": "to_char(created_at, 'ne\"w\" \"D\"ate(YYYY,MM-1,DD, HH24,MI)')" , "date":"to_char(created_at, 'YYYY,MM,DD,HH24,MI')"}
else:
select_data = {"d": "strftime('new Date(%%Y,%%m-1,%%d,%%H,%%M)', created_at)" , "date":"strftime(('%%Y,%%m,%%d,%%H,%%M') , created_at)"}
elif total_hours <= 2016: # 24 hours x 28 days x 3 = about 3 months
td=timedelta(hours=1)
sec_divisor = 3600
stf = {"date": ('%Y,%m,%d,%H'),"d": 'new Date(%Y,%m-1,%d,%H)'}
if settings.DATABASES['default']['ENGINE'] == 'postgresql_psycopg2':
select_data = {"d": "to_char(created_at, 'ne\"w\" \"D\"ate(YYYY,MM-1,DD,HH24)')" , "date":"to_char(created_at, 'YYYY,MM,DD,HH24')"}
else:
select_data = {"d": "strftime('new Date(%%Y,%%m-1,%%d,%%H)', created_at)" , "date":"strftime(('%%Y,%%m,%%d,%%H') , created_at)"}
else:
td=timedelta(days=1)
sec_divisor = 86400
stf = {"date": ('%Y,%m,%d'),"d": 'new Date(%Y,%m-1,%d)'}
if settings.DATABASES['default']['ENGINE'] == 'postgresql_psycopg2':
select_data = {"d": "to_char(created_at, 'ne\"w\" \"D\"ate(YYYY,MM-1,DD)')" , "date":"to_char(created_at, 'YYYY,MM,DD')"}
else:
select_data = {"d": "strftime('new Date(%%Y,%%m-1,%%d)', created_at)" , "date":"strftime(('%%Y,%%m,%%d') , created_at)"}
tweets = tweets.filter(created_at__gte = sdate).filter(created_at__lte = edate).extra(select = select_data).values('d','date').annotate(num_tweets = Count('tweet')).order_by('date')
tweets=list(tweets)
i = 1
detector = MeanOutliers.factory()
list_peaks = []
# loop through the tweets and detect a peak based on mean deviation function provided. save the start date
# and the date of the peak in a dictionary. save each peak in list_peaks.
while i < len(tweets):
tweets[0]['title'] = 'null'
tweets[0]['data'] = 'null'
# sd_p=tweets[i-1]['date'].split(',')
# sd_p=map(int , sd_p)
# sdt_p=datetime(*sd_p)
sdt_p=convert_date(tweets[i-1]['date'])
sd_n=tweets[i]['date'].split(',')
sd_n=map(int , sd_n)
sdt_n=datetime(*sd_n)
delta_d=(sdt_n-sdt_p)
delta_d = (delta_d.seconds + delta_d.days * 24 *3600)/sec_divisor
count=0
if delta_d != 1:
j=0
while(j<delta_d-1):
insert_tweet={'title':'null','num_tweets':0,'data':'null','children':'null'}
sdt_p = sdt_p+td
insert_tweet['date']=sdt_p.strftime(stf['date'])
insert_tweet['d']=sdt_p.strftime(stf['d'])
tweets.insert(i+j,insert_tweet)
j+=1
current_val = tweets[i]['num_tweets']
previous_val = tweets[i-1]['num_tweets']
mdiv = detector(None,tweets[i]['num_tweets'], 1)
if mdiv > 2.0 and current_val > previous_val and current_val > 10:
start_freq = previous_val
start_date = tweets[i-1]['date']
# once a peak is detected, keep climbing up the peak until the maximum is reached. store | |
'''
(c) 2014 <NAME> and <NAME>
Fast block jackknives.
Everything in this module deals with 2D numpy arrays. 1D data are represented as arrays
with dimension (N, 1) or (1, N), to avoid bugs arising from numpy treating (N, ) as
a fundamentally different shape from (N, 1). The convention in this module is for the
first dimension to represent # of data points (or # of blocks in a block jackknife, since
a block is like a datapoint), and for the second dimension to represent the dimensionality
of the data.
'''
import numpy as np
from scipy.optimize import nnls
np.seterr(divide='raise', invalid='raise')
from tqdm import tqdm
from sklearn.linear_model import Lasso
import logging
import warnings
warnings.filterwarnings('ignore', message='Coordinate descent with alpha=0 may lead to unexpected results and is discouraged.')
warnings.filterwarnings('ignore', message='Objective did not converge. You might want to increase the number of iterations. Fitting data with very small alpha may cause precision problems.')
from sklearn.metrics import r2_score
def _check_shape(x, y):
'''Check that x and y have the correct shapes (for regression jackknives).'''
if len(x.shape) != 2 or len(y.shape) != 2:
raise ValueError('x and y must be 2D arrays.')
if x.shape[0] != y.shape[0]:
raise ValueError(
'Number of datapoints in x != number of datapoints in y.')
if y.shape[1] != 1:
raise ValueError('y must have shape (n_snp, 1)')
n, p = x.shape
if p > n:
raise ValueError('More dimensions than datapoints.')
return (n, p)
def _check_shape_block(xty_block_values, xtx_block_values):
'''Check that xty_block_values and xtx_block_values have correct shapes.'''
if xtx_block_values.shape[0:2] != xty_block_values.shape:
raise ValueError(
'Shape of xty_block_values must equal shape of first two dimensions of xty_block_values.')
if len(xtx_block_values.shape) < 3:
raise ValueError('xtx_block_values must be a 3D array.')
if xtx_block_values.shape[1] != xtx_block_values.shape[2]:
raise ValueError(
'Last two axes of xtx_block_values must have same dimension.')
return xtx_block_values.shape[0:2]
class Jackknife(object):
'''
Base class for jackknife objects. Input involves x,y, so this base class is tailored
for statistics computed from independent and dependent variables (e.g., regressions).
The __delete_vals_to_pseudovalues__ and __jknife__ methods will still be useful for other
sorts of statistics, but the __init__ method will need to be overriden.
Parameters
----------
x : np.matrix with shape (n, p)
Independent variable.
y : np.matrix with shape (n, 1)
Dependent variable.
n_blocks : int
Number of jackknife blocks
*args, **kwargs :
Arguments for inheriting jackknives.
Attributes
----------
n_blocks : int
Number of jackknife blocks
p : int
Dimensionality of the independent varianble
N : int
Number of datapoints (equal to x.shape[0])
Methods
-------
jknife(pseudovalues):
Computes jackknife estimate and variance from the jackknife pseudovalues.
delete_vals_to_pseudovalues(delete_vals, est):
Converts delete values and the whole-data estimate to pseudovalues.
get_separators():
Returns (approximately) evenly-spaced jackknife block boundaries.
'''
def __init__(self, x, y, n_blocks=None, separators=None):
self.N, self.p = _check_shape(x, y)
if separators is not None:
if max(separators) != self.N:
raise ValueError(
'Max(separators) must be equal to number of data points.')
if min(separators) != 0:
raise ValueError('Max(separators) must be equal to 0.')
self.separators = sorted(separators)
self.n_blocks = len(separators) - 1
elif n_blocks is not None:
self.n_blocks = n_blocks
self.separators = self.get_separators(self.N, self.n_blocks)
else:
raise ValueError('Must specify either n_blocks are separators.')
if self.n_blocks > self.N:
raise ValueError('More blocks than data points.')
@classmethod
def jknife(cls, pseudovalues):
'''
Converts pseudovalues to jackknife estimate and variance.
Parameters
----------
pseudovalues : np.matrix pf floats with shape (n_blocks, p)
Returns
-------
jknife_est : np.matrix with shape (1, p)
Jackknifed estimate.
jknife_var : np.matrix with shape (1, p)
Variance of jackknifed estimate.
jknife_se : np.matrix with shape (1, p)
Standard error of jackknifed estimate, equal to sqrt(jknife_var).
jknife_cov : np.matrix with shape (p, p)
Covariance matrix of jackknifed estimate.
'''
n_blocks = pseudovalues.shape[0]
jknife_cov = np.atleast_2d(np.cov(pseudovalues.T, ddof=1) / n_blocks)
jknife_var = np.atleast_2d(np.diag(jknife_cov))
jknife_se = np.atleast_2d(np.sqrt(jknife_var))
jknife_est = np.atleast_2d(np.mean(pseudovalues, axis=0))
return (jknife_est, jknife_var, jknife_se, jknife_cov)
@classmethod
def delete_values_to_pseudovalues(cls, delete_values, est):
'''
Converts whole-data estimate and delete values to pseudovalues.
Parameters
----------
delete_values : np.matrix with shape (n_blocks, p)
Delete values.
est : np.matrix with shape (1, p):
Whole-data estimate.
Returns
-------
pseudovalues : np.matrix with shape (n_blocks, p)
Psuedovalues.
Raises
------
ValueError :
If est.shape != (1, delete_values.shape[1])
'''
n_blocks, p = delete_values.shape
if est.shape != (1, p):
raise ValueError(
'Different number of parameters in delete_values than in est.')
return n_blocks * est - (n_blocks - 1) * delete_values
@classmethod
def get_separators(cls, N, n_blocks):
'''Define evenly-spaced block boundaries.'''
return np.floor(np.linspace(0, N, n_blocks + 1)).astype(int)
class LstsqJackknifeSlow(Jackknife):
'''
Slow linear-regression block jackknife. This class computes delete values directly,
rather than forming delete values from block values. Useful for testing and for
non-negative least squares (which as far as I am aware does not admit a fast block
jackknife algorithm).
Inherits from Jackknife class.
Parameters
----------
x : np.matrix with shape (n, p)
Independent variable.
y : np.matrix with shape (n, 1)
Dependent variable.
n_blocks : int
Number of jackknife blocks
nn: bool
Non-negative least-squares?
Attributes
----------
est : np.matrix with shape (1, p)
FWLS estimate.
jknife_est : np.matrix with shape (1, p)
Jackknifed estimate.
jknife_var : np.matrix with shape (1, p)
Variance of jackknifed estimate.
jknife_se : np.matrix with shape (1, p)
Standard error of jackknifed estimate, equal to sqrt(jknife_var).
jknife_cov : np.matrix with shape (p, p)
Covariance matrix of jackknifed estimate.
delete_vals : np.matrix with shape (n_blocks, p)
Jackknife delete values.
'''
@classmethod
def delete_values(cls, x, y, func, s):
'''
Compute delete values by deleting one block at a time.
Parameters
----------
x : np.matrix with shape (n, p)
Independent variable.
y : np.matrix with shape (n, 1)
Dependent variable.
func : function (n, p) , (n, 1) --> (1, p)
Function of x and y to be jackknived.
s : list of ints
Block separators.
Returns
-------
delete_values : np.matrix with shape (n_blocks, p)
Delete block values (with n_blocks blocks defined by parameter s).
Raises
------
ValueError :
If x.shape[0] does not equal y.shape[0] or x and y are not 2D.
'''
_check_shape(x, y)
d = []
logging.info('Starting non-negative jackknife...')
for i in tqdm(range(len(s) - 1)):
jk_est = func(np.vstack([x[0:s[i], ...], x[s[i + 1]:, ...]]), np.vstack([y[0:s[i], ...], y[s[i + 1]:, ...]]))
d.append(jk_est)
return np.concatenate(d, axis=0)
def __init__(self, x, y, is_large_chi2, n_blocks=None, nn=False, separators=None, chr_num=None, evenodd_split=False, nnls_exact=False):
Jackknife.__init__(self, x, y, n_blocks, separators)
#estimate taus
if nn: # non-negative least squares
if nnls_exact:
self.est = np.atleast_2d(nnls(x, np.array(y).T[0])[0])
else:
xtx = x.T.dot(x)
lasso = Lasso(alpha=1e-100, fit_intercept=False, normalize=False, precompute=xtx, positive=True, max_iter=10000, random_state=0)
self.est = lasso.fit(x,y[:,0]).coef_.reshape((1, x.shape[1]))
else:
self.est = np.atleast_2d(np.linalg.lstsq(x, np.array(y).T[0])[0])
#move large_chi2 SNPs to the end of x and y (don't include them in the separator definition, so that they'll never get removed during jackknife)
if np.any(is_large_chi2):
x_large = x[is_large_chi2]
y_large = y[is_large_chi2]
x = x[~is_large_chi2]
y = y[~is_large_chi2]
Jackknife.__init__(self, x, y, n_blocks, separators)
x = np.concatenate((x,x_large), axis=0)
y = np.concatenate((y,y_large), axis=0)
#jackknife
if nn:
d = []
s = self.separators
for i in tqdm(range(len(s) - 1), disable=False):
x_noblock = np.delete(x, slice(s[i], s[i+1]), axis=0)
y_noblock = np.delete(y, slice(s[i], s[i+1]), axis=0)
if nnls_exact:
jk_est = np.atleast_2d(nnls(x_noblock, y_noblock[:,0])[0])
else:
x_block = x[s[i] : s[i+1]]
xtx_noblock = xtx - x_block.T.dot(x_block)
lasso_noblock = Lasso(alpha=1e-100, fit_intercept=False, normalize=False, precompute=xtx_noblock, positive=True, max_iter=10000, random_state=0)
jk_est = lasso_noblock.fit(x_noblock, y_noblock[:,0]).coef_.reshape((1, x.shape[1]))
###z = nnls(x_noblock, y_noblock[:,0])[0]
###assert np.allclose(z, jk_est[0])
d.append(jk_est)
self.delete_values = np.concatenate(d, axis=0)
else:
self.delete_values = self.delete_values(x, y, func, self.separators)
self.pseudovalues = self.delete_values_to_pseudovalues(
self.delete_values, self.est)
(self.jknife_est, self.jknife_var, self.jknife_se, self.jknife_cov) =\
self.jknife(self.pseudovalues)
if evenodd_split:
assert y.shape[1]==1
assert chr_num is not None
assert len(np.unique(chr_num)) > 1
self.chr_list = np.sort(np.unique(chr_num))
self.est_loco = np.empty((len(self.chr_list), x.shape[1]), dtype=np.float32)
for chr_i, left_out_chr in enumerate(tqdm(self.chr_list)):
is_loco = ((chr_num%2)==(left_out_chr%2)) & (chr_num != left_out_chr)
x_loco = x[is_loco]
y_loco = y[is_loco]
self.est_loco[chr_i, :] = nnls(x_loco, y_loco[:,0])[0]
class LstsqJackknifeFast(Jackknife):
def __init__(self, x, y, is_large_chi2, n_blocks=None, separators=None, chr_num=None, evenodd_split=False):
#compute jackknife estimates using all SNPs
Jackknife.__init__(self, x, y, n_blocks, separators)
xty, xtx = self.block_values(x, y, self.separators)
self.est = self.block_values_to_est(xty, xtx)
#compute xtx_tot and xty_tot
xty_tot = np.sum(xty, axis=0)
xtx_tot = np.sum(xtx, axis=0)
#exclude large-chi2 SNPs from xtx and xty for the jackknife
if np.any(is_large_chi2):
x = | |
# Copyright (c) 2016 by <NAME> and the other collaborators on GitHub at
# https://github.com/rmjarvis/Piff All rights reserved.
#
# Piff is free software: Redistribution and use in source and binary forms
# with or without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the disclaimer given in the accompanying LICENSE
# file.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the disclaimer given in the documentation
# and/or other materials provided with the distribution.
"""
.. module:: pixelmodel
"""
import numpy as np
import galsim
import scipy.linalg
import warnings
from galsim import Lanczos
from .model import Model
from .star import Star, StarData, StarFit
class PixelGrid(Model):
"""A PSF modeled as interpolation between a grid of points.
The parameters of the model are the values at the grid points, although the sum of the
values is constrained to be 1/scale**2, to give it unit total flux. The grid is in uv
space, with the scale and size specified on construction. Interpolation will always
assume values of zero outside of grid.
PixelGrid also needs to specify an interpolant to define how to values between grid points
are determined from the pixelated model. Any galsim.Interpolant type is allowed.
The default interpolant is galsim.Lanczos(3)
:param scale: Pixel scale of the PSF model (in arcsec)
:param size: Number of pixels on each side of square grid.
:param interp: An Interpolant to be used [default: Lanczos(3)]
:param centered: If True, PSF model centroid is forced to be (0,0), and the
PSF fitting will marginalize over stellar position. If False, stellar
position is fixed at input value and the fitted PSF may be off-center.
[default: True]
:param logger: A logger object for logging debug info. [default: None]
"""
_method = 'no_pixel'
_model_can_be_offset = True # Indicate that in reflux, the centroid should also move by the
# current centroid of the model. This way on later iterations,
# the model will be close to centered.
def __init__(self, scale, size, interp=None, centered=True, logger=None,
degenerate=None, start_sigma=None):
# Note: Parameters degenerate and start_sigma are not used.
# They are present only for backwards compatibility when reading old Piff
# output files that specify these parameters.
logger = galsim.config.LoggerWrapper(logger)
logger.debug("Building Pixel model with the following parameters:")
logger.debug("scale = %s",scale)
logger.debug("size = %s",size)
logger.debug("interp = %s",interp)
logger.debug("centered = %s",centered)
self.scale = scale
self.size = size
self.pixel_area = self.scale*self.scale
if interp is None: interp = Lanczos(3)
elif isinstance(interp, str): interp = eval(interp)
self.interp = interp
self._centered = centered
# We will limit the calculations to |u|, |v| <= maxuv
self.maxuv = (self.size+1)/2. * self.scale
# The origin of the model in image coordinates
# (Same for both u and v directions.)
self._origin = self.size//2
# These are the kwargs that can be serialized easily.
self.kwargs = {
'scale' : scale,
'size' : size,
'centered' : centered,
'interp' : repr(self.interp),
}
if size <= 0:
raise ValueError("Non-positive PixelGrid size {:d}".format(size))
self._nparams = size*size
logger.debug("nparams = %d",self._nparams)
def initialize(self, star, logger=None):
"""Initialize a star to work with the current model.
:param star: A Star instance with the raw data.
:param logger: A logger object for logging debug info. [default: None]
:returns: a star instance with the appropriate initial fit values
"""
data, weight, u, v = star.data.getDataVector()
# Start with the sum of pixels as initial estimate of flux.
# (Skip w=0 pixels here.)
mask = weight!=0
flux = np.sum(data[mask])
if self._centered:
# Initial center is the centroid of the data.
Ix = np.sum(data[mask] * u[mask]) / flux
Iy = np.sum(data[mask] * v[mask]) / flux
center = (Ix,Iy)
else:
# In this case, center is fixed.
center = star.fit.center
# Calculate the second moment to initialize an initial Gaussian profile.
# hsm returns: flux, x, y, sigma, g1, g2, flag
sigma = star.hsm[3]
# Create an initial parameter array using a Gaussian profile.
u = np.arange( -self._origin, self.size-self._origin) * self.scale
v = np.arange( -self._origin, self.size-self._origin) * self.scale
rsq = (u*u)[:,np.newaxis] + (v*v)[np.newaxis,:]
gauss = np.exp(-rsq / (2.* sigma**2))
params = gauss.ravel()
# Normalize to get unity flux
params /= np.sum(params)
starfit = StarFit(params, flux, center)
return Star(star.data, starfit)
def fit(self, star, logger=None, convert_func=None):
"""Fit the Model to the star's data to yield iterative improvement on its PSF parameters
and uncertainties.
:param star: A Star instance
:param logger: A logger object for logging debug info. [default: None]
:param convert_func: An optional function to apply to the profile being fit before
drawing it onto the image. This is used by composite PSFs to
isolate the effect of just this model component. [default: None]
:returns: a new Star instance with updated fit information
"""
logger = galsim.config.LoggerWrapper(logger)
# Get chisq Taylor expansion for linearized model
star1 = self.chisq(star, logger=logger, convert_func=convert_func)
# The chisq function calculates A and b where
#
# chisq = chisq_0 + 2 bT A dp + dpT AT A dp
#
# is the linearized variation in chisq with respect to changes in the parameter values.
# The minimum of this linearized functional form is
#
# dp = (AT A)^-1 AT b
#
# This is just the least squares solution of
#
# A dp = b
#
# Even if the solution is degenerate, gelsy works fine using QRP decomposition.
# And it's much faster than SVD.
dparam = scipy.linalg.lstsq(star1.fit.A, star1.fit.b,
check_finite=False, cond=1.e-6,
lapack_driver='gelsy')[0]
logger.debug('dparam = %s',dparam)
# Create new StarFit, update the chisq value. Note no beta is returned as
# the quadratic Taylor expansion was about the old parameters, not these.
Adp = star1.fit.A.dot(dparam)
new_chisq = star1.fit.chisq + Adp.dot(Adp) - 2 * Adp.dot(star1.fit.b)
logger.debug('chisq = %s',new_chisq)
# covariance of dp is C = (AT A)^-1
# params_var = diag(C)
try:
params_var = np.diagonal(scipy.linalg.inv(star1.fit.A.T.dot(star1.fit.A)))
except np.linalg.LinAlgError as e:
# If we get an error, set the variance to "infinity".
logger.info("Caught error %s making params_var. Setting all to 1.e100",e)
params_var = np.ones_like(dparam) * 1.e100
starfit2 = StarFit(star1.fit.params + dparam,
flux = star1.fit.flux,
center = star1.fit.center,
params_var = params_var,
A = star1.fit.A,
chisq = new_chisq)
star = Star(star1.data, starfit2)
self.normalize(star)
return star
def chisq(self, star, logger=None, convert_func=None):
"""Calculate dependence of chi^2 = -2 log L(D|p) on PSF parameters for single star.
as a quadratic form chi^2 = dp^T AT A dp - 2 bT A dp + chisq,
where dp is the *shift* from current parameter values. Returned Star
instance has the resultant (A, b, chisq) attributes, but params vector has not have
been updated yet (could be degenerate).
:param star: A Star instance
:param logger: A logger object for logging debug info. [default: None]
:param convert_func: An optional function to apply to the profile being fit before
drawing it onto the image. This is used by composite PSFs to
isolate the effect of just this model component. [default: None]
:returns: a new Star instance with updated fit parameters. (esp. A,b)
"""
logger = galsim.config.LoggerWrapper(logger)
logger.debug('Start chisq function')
logger.debug('initial params = %s',star.fit.params)
data, weight, u, v = star.data.getDataVector()
prof = self.getProfile(star.fit.params)._shift(*star.fit.center)
logger.debug('prof.flux = %s',prof.flux)
# My idea for doing composite functions is that at this point in the calculation, we
# could apply a function to prof to convert it to the full effective PSF profile.
# This function could be passed as an optional extra argument to the fit and chisq
# functions. (The default would just be `lambda prof:prof`.)
# E.g. in a Sum context, this function could be
# convert_func = `lambda prof: galsim.Sum(prof, *other_profiles)`
# Then at this point in the chisq function (and comparable places for other profiles),
# we would call:
# prof = convert_func(prof)
# The draw function below would then draw the full composite profile, not just the
# PixelGrid profile.
if convert_func is not None:
prof = convert_func(prof)
# Adjust the image now so | |
<reponame>mcoirad-gmmb/civis-python
from functools import lru_cache
import logging
import warnings
import civis
from civis.resources import generate_classes_maybe_cached
from civis._utils import get_api_key
from civis._deprecation import deprecate_param
log = logging.getLogger(__name__)
RETRY_CODES = [429, 502, 503, 504]
RETRY_VERBS = ['HEAD', 'TRACE', 'GET', 'PUT', 'OPTIONS', 'DELETE']
POST_RETRY_CODES = [429, 503]
def find(object_list, filter_func=None, **kwargs):
"""Filter :class:`civis.response.Response` objects.
Parameters
----------
object_list : iterable
An iterable of arbitrary objects, particularly those with attributes
that can be targeted by the filters in `kwargs`. A major use case is
an iterable of :class:`civis.response.Response` objects.
filter_func : callable, optional
A one-argument function. If specified, `kwargs` are ignored.
An `object` from the input iterable is kept in the returned list
if and only if ``bool(filter_func(object))`` is ``True``.
**kwargs
Key-value pairs for more fine-grained filtering; they cannot be used
in conjunction with `filter_func`. All keys must be strings.
For an `object` from the input iterable to be included in the
returned list, all the `key`s must be attributes of `object`, plus
any one of the following conditions for a given `key`:
- `value` is a one-argument function and
``bool(value(getattr(object, key)))`` is ``True``
- `value` is ``True``
- ``getattr(object, key)`` is equal to ``value``
Returns
-------
list
Examples
--------
>>> import civis
>>> client = civis.APIClient()
>>> # creds is a list of civis.response.Response objects
>>> creds = client.credentials.list()
>>> # target_creds contains civis.response.Response objects
>>> # with the attribute 'name' == 'username'
>>> target_creds = find(creds, name='username')
See Also
--------
civis.find_one
"""
_func = filter_func
if not filter_func:
def default_filter(o):
for k, v in kwargs.items():
if not hasattr(o, k):
return False
elif callable(v):
if not v(getattr(o, k, None)):
return False
elif isinstance(v, bool):
if hasattr(o, k) != v:
return False
elif v != getattr(o, k, None):
return False
return True
_func = default_filter
return [o for o in object_list if _func(o)]
def find_one(object_list, filter_func=None, **kwargs):
"""Return one satisfying :class:`civis.response.Response` object.
The arguments are the same as those for :func:`civis.find`.
If more than one object satisfies the filtering criteria,
the first one is returned.
If no satisfying objects are found, ``None`` is returned.
Returns
-------
object or None
See Also
--------
civis.find
"""
results = find(object_list, filter_func, **kwargs)
return results[0] if results else None
class MetaMixin():
@lru_cache(maxsize=128)
def get_database_id(self, database):
"""Return the database ID for a given database name.
Parameters
----------
database : str or int
If an integer ID is given, passes through. If a str is given
the database ID corresponding to that database name is returned.
Returns
-------
database_id : int
The ID of the database.
Raises
------
ValueError
If the database can't be found.
"""
if isinstance(database, int):
return database
db = find_one(self.databases.list(), name=database)
if not db:
raise ValueError("Database {} not found.".format(database))
return db["id"]
@lru_cache(maxsize=128)
def get_database_credential_id(self, username, database_name):
"""Return the credential ID for a given username in a given database.
Parameters
----------
username : str or int
If an integer ID is given, this passes through directly. If a
str is given, return the ID corresponding to the database
credential with that username.
database_name : str or int
Return the ID of the database credential with username
`username` for this database name or ID.
Returns
-------
database_credential_id : int
The ID of the database credentials.
Raises
------
ValueError
If the credential can't be found.
Examples
--------
>>> import civis
>>> client = civis.APIClient()
>>> client.get_database_credential_id('jsmith', 'redshift-general')
1234
>>> client.get_database_credential_id(1111, 'redshift-general')
1111
"""
if isinstance(username, int):
return username
else:
creds = self.credentials.list(type="Database")
filter_kwargs = {'username': username}
if isinstance(database_name, int):
filter_kwargs['remote_host_id'] = database_name
else:
filter_kwargs['remote_host_name'] = database_name
my_creds = find_one(creds, **filter_kwargs)
if my_creds is None:
raise ValueError("Credential ID for {} on {} not "
"found.".format(username, database_name))
return my_creds["id"]
@lru_cache(maxsize=128)
def get_aws_credential_id(self, cred_name, owner=None):
"""Find an AWS credential ID.
Parameters
----------
cred_name : str or int
If an integer ID is given, this passes through directly. If a
str is given, return the ID corresponding to the AWS credential
with that name.
owner : str, optional
Return the credential with this owner. If not provided, search
for credentials under your username to disambiguate multiple
credentials with the same name. Note that this function cannot
return credentials which are not associated with an owner.
Returns
-------
aws_credential_id : int
The ID number of the AWS credentials.
Raises
------
ValueError
If the AWS credential can't be found.
Examples
--------
>>> import civis
>>> client = civis.APIClient()
>>> client.get_aws_credential_id('jsmith')
1234
>>> client.get_aws_credential_id(1111)
1111
>>> client.get_aws_credential_id('shared-cred',
... owner='research-group')
99
"""
if isinstance(cred_name, int):
return cred_name
else:
creds = self.credentials.list(type="Amazon Web Services S3")
my_creds = find(creds, name=cred_name)
if owner is not None:
my_creds = find(my_creds, owner=owner)
if not my_creds:
own_str = "" if owner is None else " owned by {}".format(owner)
msg = "AWS credential ID for {}{} cannot be found"
raise ValueError(msg.format(cred_name, own_str))
elif len(my_creds) > 1:
if owner is None:
# If the user didn't specify an owner, see if we can
# narrow down to just credentials owned by this user.
owner = self.username
my_creds = find(my_creds, owner=owner)
if len(my_creds) > 1:
log.warning("Found %d AWS credentials with name %s and "
"owner %s. Returning the first.",
len(my_creds), cred_name, owner)
my_creds = my_creds[0]
return my_creds["id"]
@lru_cache(maxsize=128)
def get_table_id(self, table, database):
"""Return the table ID for a given database and table name.
Parameters
----------
table : str
The name of the table in format schema.tablename.
Either schema or tablename, or both, can be double-quoted to
correctly parse special characters (such as '.').
database : str or int
The name or ID of the database.
Returns
-------
table_id : int
The ID of the table.
Raises
------
ValueError
If a table match can't be found.
Examples
--------
>>> import civis
>>> client = civis.APIClient()
>>> client.get_table_id('foo.bar', 'redshift-general')
123
>>> client.get_table_id('"schema.has.periods".bar', 'redshift-general')
456
"""
database_id = self.get_database_id(database)
schema, name = civis.io.split_schema_tablename(table)
tables = self.tables.list(database_id=database_id, schema=schema,
name=name)
if not tables:
msg = "No tables found for {} in database {}"
raise ValueError(msg.format(table, database))
return tables[0].id
@lru_cache(maxsize=128)
def get_storage_host_id(self, storage_host):
"""Return the storage host ID for a given storage host name.
Parameters
----------
storage_host : str or int
If an integer ID is given, passes through. If a str is given
the storage host ID corresponding to that storage host is returned.
Returns
-------
storage_host_id : int
The ID of the storage host.
Raises
------
ValueError
If the storage host can't be found.
Examples
--------
>>> import civis
>>> client = civis.APIClient()
>>> client.get_storage_host_id('test host')
1234
>>> client.get_storage_host_id(1111)
1111
"""
if isinstance(storage_host, int):
return storage_host
sh = find_one(self.storage_hosts.list(), name=storage_host)
if not sh:
raise ValueError("Storage Host {} not found.".format(storage_host))
return sh["id"]
@property
@lru_cache(maxsize=128)
def default_credential(self):
"""The current user's default credential."""
# NOTE: this should be optional to endpoints...so this could go away
creds = self.credentials.list(default=True)
return creds[0]['id'] if len(creds) > 0 else None
@property
@lru_cache(maxsize=128)
def username(self):
"""The current user's username."""
return self.users.list_me().username
class APIClient(MetaMixin):
"""The Civis API client.
Parameters
----------
api_key : str, optional
Your API key obtained from the Civis Platform. If not given, the
client will use the :envvar:`CIVIS_API_KEY` environment variable.
return_type : str, optional
The following types are implemented:
- ``'raw'`` Returns the raw :class:`requests:requests.Response` object.
- ``'snake'`` Returns a :class:`civis.response.Response` object for the
json-encoded content of a response. This maps the top-level json
keys to snake_case.
- ``'pandas'`` Returns a :class:`pandas:pandas.DataFrame` for
list-like responses and a :class:`pandas:pandas.Series` for single a
json response.
retry_total : int, optional
A number indicating the maximum number of retries for 429, 502, 503, or
504 errors.
api_version : string, optional
The version of endpoints to call. May instantiate multiple client
objects with different versions. Currently only "1.0" is supported.
resources : string, optional
When set to "base", only the default endpoints will be exposed in the
client object. Set to "all" to include all endpoints available for
a given user, including those that may be in development and subject
to breaking changes at a later date. This will be removed in a future
version of the | |
from sqlalchemy.sql import and_, func, text
from sqlalchemy.sql.expression import select
from sqlalchemy.orm import aliased, backref, deferred, mapper, relationship, reconstructor
from sqlalchemy.orm.collections import attribute_mapped_collection
from sqlalchemy.ext.hybrid import hybrid_method
try: from rdkit.Chem import Mol, MolFromSmarts
except ImportError: pass
from credoscript import Base, schema
from credoscript import adaptors as credoadaptor
from credoscript.support import requires
# SHOULD BE WRAPPED IN TRY/EXCEPT
Base.metadata.reflect(schema='chembl')
### CHEMBL DEFAULT TABLES ###
class Activity(Base):
'''
'''
__tablename__ = 'chembl.activities'
Assay = relationship("Assay",
primaryjoin="Assay.assay_id==Activity.assay_id",
foreign_keys="[Assay.assay_id]",
uselist=False, innerjoin=True,
backref=backref('Activities', uselist=True))
Doc = relationship("Doc",
primaryjoin="Doc.doc_id==Activity.doc_id",
foreign_keys="[Doc.doc_id]",
uselist=False, innerjoin=True,
backref=backref('Activities', uselist=True))
Record = relationship("CompoundRecord",
primaryjoin="CompoundRecord.record_id==Activity.record_id",
foreign_keys="[CompoundRecord.record_id]",
uselist=False, innerjoin=True,
backref=backref('Activities', uselist=True))
def __repr__(self):
'''
'''
return '<Activity({self.activity_id})>'.format(self=self)
class Assay(Base):
'''
'''
__tablename__ = 'chembl.assays'
AssayType = relationship("AssayType",
primaryjoin="AssayType.assay_type==Assay.assay_type",
foreign_keys="[AssayType.assay_type]",
uselist=False, innerjoin=True)
Assay2Targets = relationship("Assay2Target",
primaryjoin="Assay2Target.assay_id==Assay.assay_id",
foreign_keys="[Assay2Target.assay_id]", uselist=True, innerjoin=True,
backref='Assay')
Source = relationship("Source",
primaryjoin="Source.src_id==Assay.src_id",
foreign_keys="[Source.src_id]",
uselist=False, innerjoin=True)
Targets = relationship("Target",
secondary=Base.metadata.tables['chembl.assay2target'],
primaryjoin="Assay.assay_id==Assay2Target.assay_id",
secondaryjoin="Target.tid==Assay2Target.tid",
foreign_keys="[Assay2Target.assay_id,Assay2Target.tid]",
uselist=True, innerjoin=True, backref='Assays')
Doc = relationship("Doc",
primaryjoin="Doc.doc_id==Assay.doc_id",
foreign_keys="[Doc.doc_id]",
uselist=False, innerjoin=True, backref='Assays')
def __repr__(self):
'''
'''
return '<Assay({self.assay_id})>'.format(self=self)
@property
def Structures(self):
'''
'''
return credoadaptor.StructureAdaptor().fetch_all_by_pubmed_id(self.Doc.pubmed_id)
class Assay2Target(Base):
'''
'''
__tablename__ = 'chembl.assay2target'
Target = relationship("Target",
primaryjoin="Target.tid==Assay2Target.tid",
foreign_keys="[Target.tid]",
uselist=False, innerjoin=True,
backref='Assay2Targets')
Curator = relationship("Curator",
primaryjoin="Curator.curated_by==Assay2Target.curated_by",
foreign_keys="[Curator.curated_by]",
uselist=False, innerjoin=True)
ConfidenceScore = relationship("ConfidenceScore",
primaryjoin="ConfidenceScore.confidence_score==Assay2Target.confidence_score",
foreign_keys="[ConfidenceScore.confidence_score]",
uselist=False, innerjoin=True)
RelationshipType = relationship("RelationshipType",
primaryjoin="RelationshipType.relationship_type==Assay2Target.relationship_type",
foreign_keys="[RelationshipType.relationship_type]",
uselist=False, innerjoin=True)
def __repr__(self):
'''
'''
return '<Assay2Target({self.assay_id}, {self.tid})>'.format(self=self)
class AssayType(Base):
'''
'''
__tablename__ = 'chembl.assay_type'
def __repr__(self):
'''
'''
return '<AssayType({self.asay_type})>'.format(self=self)
class ATCClassification(Base):
'''
'''
__tablename__ = 'chembl.atc_classification'
DefinedDailyDose = relationship("DefinedDailyDose",
primaryjoin="DefinedDailyDose.atc_code==ATCClassification.level5",
foreign_keys="[DefinedDailyDose.atc_code]",
uselist=False, innerjoin=True)
class ChEMBLID(Base):
'''
'''
__tablename__ = 'chembl.chembl_id_lookup'
class CompoundProperty(Base):
'''
'''
__tablename__ = 'chembl.compound_properties'
Structures = relationship("CompoundStructure",
primaryjoin="CompoundStructure.molregno==CompoundProperty.molregno",
foreign_keys="[CompoundStructure.molregno]",
uselist=True, innerjoin=True,
backref='CompoundProperty')
Records = relationship("CompoundRecord",
primaryjoin="CompoundRecord.molregno==CompoundProperty.molregno",
foreign_keys="[CompoundRecord.molregno]",
uselist=True, innerjoin=True,
backref='CompoundProperty'),
def __repr__(self):
'''
'''
return '<CompoundProperty({self.molregno})>'.format(self=self)
class CompoundRecord(Base):
'''
'''
__tablename__ = 'chembl.compound_records'
Source = relationship("Source",
primaryjoin="Source.src_id==CompoundRecord.src_id",
foreign_keys="[Source.src_id]",
uselist=False, innerjoin=True)
def __repr__(self):
'''
'''
return '<CompoundRecord({self.record_id})>'.format(self=self)
class CompoundStructure(Base):
'''
'''
__tablename__ = 'chembl.compound_structures'
def __repr__(self):
'''
'''
return '<CompoundStructure({self.molregno})>'.format(self=self)
class ConfidenceScore(Base):
__tablename__ = 'chembl.confidence_score_lookup'
class Curator(Base):
__tablename__ = 'chembl.curation_lookup'
class DefinedDailyDose(Base):
__tablename__ = 'chembl.defined_daily_dose'
class Doc(Base):
'''
'''
__tablename__ = 'chembl.docs'
def __repr__(self):
'''
'''
return '<Doc({self.doc_id})>'.format(self=self)
@property
def Structures(self):
'''
'''
return credoadaptor.StructureAdaptor().fetch_all_by_pubmed_id(self.pubmed_id)
class Formulation(Base):
'''
'''
__tablename__ = 'chembl.formulations'
Product = relationship("Product",
primaryjoin="Product.product_id==Formulation.product_id",
foreign_keys="[Product.product_id]",
uselist=False, innerjoin=True,
backref=backref('Formulations', uselist=True))
def __repr__(self):
'''
'''
return '<Formulation({self.product_id}, {self.ingredient})>'.format(self=self)
class Molecule(Base):
'''
'''
__tablename__ = 'chembl.molecule_dictionary'
Property = relationship("CompoundProperty",
primaryjoin="CompoundProperty.molregno==Molecule.molregno",
foreign_keys="[CompoundProperty.molregno]",
uselist=False, backref='Molecule')
Records = relationship("CompoundRecord",
primaryjoin="CompoundRecord.molregno==Molecule.molregno",
foreign_keys="[CompoundRecord.molregno]",
uselist=True, backref='Molecule')
Activities = relationship("Activity",
collection_class=attribute_mapped_collection("assay_id"),
primaryjoin="Activity.molregno==Molecule.molregno",
foreign_keys="[Activity.molregno]",
uselist=True, backref='Molecule')
Structure = relationship("CompoundStructure",
primaryjoin="CompoundStructure.molregno==Molecule.molregno",
foreign_keys="[CompoundStructure.molregno]",
uselist=False, backref='Molecule')
Formulations = relationship("Formulation",
primaryjoin="Formulation.molregno==Molecule.molregno",
foreign_keys="[Formulation.molregno]",
uselist=True, backref='Molecule')
Synonyms = relationship("MoleculeSynonym",
collection_class=attribute_mapped_collection("syn_type"),
primaryjoin="MoleculeSynonym.molregno==Molecule.molregno",
foreign_keys="[MoleculeSynonym.molregno]",
uselist=True, backref='Molecule')
Hierarchy = relationship("MoleculeHierarchy",
primaryjoin="MoleculeHierarchy.molregno==Molecule.molregno",
foreign_keys="[MoleculeHierarchy.molregno]",
uselist=False, backref='Molecule')
Assays = relationship("Assay",
secondary=Base.metadata.tables['chembl.compound_records'],
primaryjoin="Molecule.molregno==CompoundRecord.molregno",
secondaryjoin="CompoundRecord.doc_id==Assay.doc_id",
foreign_keys="[CompoundRecord.molregno,CompoundRecord.doc_id]",
uselist=True, innerjoin=True, backref='Molecules')
def __repr__(self):
'''
'''
return '<Molecule({self.molregno})>'.format(self=self)
@property
def DosedComponent(self):
'''
'''
return MoleculeAdaptor().fetch_dosed_component_by_molregno(self.molregno)
@property
def Targets(self):
'''
'''
return TargetAdaptor().fetch_all_by_molregno(self.molregno)
@property
def Ligands(self):
'''
'''
return credoadaptor.LigandAdaptor().fetch_all_by_chembl_id(self.chembl_id)
def get_activities(self, *expressions):
'''
'''
return ActivityAdaptor().fetch_all_by_molregno(self.molregno,*expressions)
def get_activity_cliffs(self, *expressions):
'''
'''
return ActivityCliffAdaptor().fetch_all_by_molregno(self.molregno, *expressions)
class MoleculeHierarchy(Base):
'''
'''
__tablename__ = 'chembl.molecule_hierarchy'
@property
def Active(self):
'''
'''
return MoleculeAdaptor().fetch_by_molregno(self.active_molregno)
class MoleculeSynonym(Base):
'''
'''
__tablename__ = 'chembl.molecule_synonyms'
def __repr__(self):
'''
'''
return '<MoleculeSynonym({self.molregno}, {self.synonyms}, {self.syn_type})>'.format(self=self)
class OrganismClass(Base):
__tablename__ = 'chembl.organism_class'
class Product(Base):
'''
'''
__tablename__ = 'chembl.products'
def __repr__(self):
'''
'''
return '<Product({self.product_id}, {self.trade_name})>'.format(self=self)
class ProteinTherapeutic(Base):
'''
'''
__tablename__ = 'chembl.protein_therapeutics'
Molecule = relationship("Molecule",
primaryjoin="Molecule.molregno==ProteinTherapeutic.molregno",
foreign_keys="[Molecule.molregno]",
uselist=False, innerjoin=True),
def __repr__(self):
'''
'''
return '<ProteinTherapeutic({self.molregno})>'.format(self=self)
@property
def Chains(self):
'''
'''
md5 = func.md5(self.protein_sequence.upper())
return credoadaptor.ChainAdaptor().fetch_all_by_seq_md5(md5)
class RelationshipType(Base):
__tablename__ = 'chembl.relationship_type'
class ResearchCode(Base):
__tablename__ = 'chembl.research_codes'
class Source(Base):
'''
'''
__tablename__ = 'chembl.source'
def __repr__(self):
'''
'''
return '<Source({self.src_id})>'.format(self=self)
class Target(Base):
'''
'''
__tablename__ = 'chembl.target_dictionary'
Classes = relationship("TargetClass",
primaryjoin="TargetClass.tid==Target.tid",
foreign_keys="[TargetClass.tid]",
uselist=True, innerjoin=True, backref='Target')
Type = relationship("TargetType",
primaryjoin="TargetType.target_type==Target.target_type",
foreign_keys="[TargetType.target_type]",
uselist=False, innerjoin=True),
def __repr__(self):
'''
'''
return '<Target({self.tid})>'.format(self=self)
@property
def Chains(self):
'''
'''
return credoadaptor.ChainAdaptor().fetch_all_by_uniprot(self.protein_accession)
class TargetClass(Base):
__tablename__ = 'chembl.target_class'
class TargetType(Base):
__tablename__ = 'chembl.target_type'
class Version(Base):
__tablename__ = 'chembl.version'
### LOCAL TABLES ###
class ActivityCliff(object):
'''
'''
def __repr__(self):
'''
'''
return '<ActivityCliff({self.assay_id}, {self.activity_bgn_id}, {self.activity_end_id})>'.format(self=self)
class CompoundSmiles(Base):
'''
Table used to store the isomeric SMILES strings produced with OEChem.
'''
__tablename__ = 'chembl.compound_smiles'
@hybrid_method
def like(self, smiles):
'''
Returns an SQL function expression that uses the PostgreSQL trigram index
to compare the SMILES strings.
'''
warn("Trigram functions at the instance level are not implemented.", UserWarning)
@like.expression
def like(self, smiles):
'''
Returns an SQL function expression that uses the PostgreSQL trigram index
to compare the SMILES strings.
'''
return self.ism.op('%%')(smiles)
class CompoundRDMol(Base):
'''
'''
__tablename__ = 'chembl.compound_rdmols'
@reconstructor
def init_on_load(self):
'''
Turns the rdmol column that is returned as a SMILES string back into an
RDMol Base.
'''
self.rdmol = Mol(str(self.rdmol))
@hybrid_method
def contains(self, smiles):
'''
Returns true if the given SMILES string is a substructure of this RDMol.
Uses a client-side RDKit installation.
Returns
-------
contains : boolean
True if the rdmol molecule attribute contains the specified substructure
in SMILES format.
'''
return self.rdmol.HasSubstructMatch(MolFromSmiles(str(smiles)))
@contains.expression
def contains(self, smiles):
'''
Returns a RDKit cartridge substructure query in form of an SQLAlchemy binary
expression.
Returns
-------
expression : sqlalchemy.sql.expression._BinaryExpression
SQL expression that can be used to query ChemCompRDMol for substructure
hits.
'''
return self.rdmol.op('OPERATOR(rdkit.@>)')(smiles)
@hybrid_method
@requires.rdkit
def contained_in(self, smiles):
'''
Returns true if the given SMILES string is a superstructure of this RDMol.
Uses a client-side RDKit installation.
Returns
-------
contains : boolean
True if the rdmol molecule attribute is contained in the specified
substructure in SMILES format.
'''
return MolFromSmiles(smiles).HasSubstructMatch(self.rdmol)
@contained_in.expression
def contained_in(self, smiles):
'''
Returns a RDKit cartridge superstructure query in form of an SQLAlchemy binary
expression.
Returns
-------
expression : sqlalchemy.sql.expression._BinaryExpression
SQL expression that can be used to query ChemCompRDMol for superstructure
hits.
'''
return self.rdmol.op('OPERATOR(rdkit.<@)')(smiles)
@hybrid_method
@requires.rdkit
def matches(self, smarts):
'''
Returns true if the RDMol matches the given SMARTS query. Uses a client-side
RDKit installation.
Returns
-------
matches : boolean
True if the rdmol molecule attribute matches the given SMARTS query.
'''
return self.rdmol.HasSubstructMatch(MolFromSmarts(smarts))
@matches.expression
def matches(self, smarts):
'''
Returns a SMARTS match query in form of an SQLAlchemy binary expression.
Returns
-------
expression : sqlalchemy.sql.expression._BinaryExpression
SQL expression that can be used to query ChemCompRDMol for SMARTS matches.
'''
return self.rdmol.op('OPERATOR(rdkit.@>)')(func.rdkit.qmol_in(smarts))
class CompoundRDFP(Base):
'''
'''
__tablename__ = 'chembl.compound_rdfps'
# CUSTOM SELECT FOR ACTIVITY CLIFFS THAT WILL BE MAPPED AGAINST A CLASS
A1, A2 = metadata.tables['chembl.activities'].alias(), metadata.tables['chembl.activities'].alias()
FP1, FP2 = metadata.tables['chembl.compound_rdfps'].alias(), metadata.tables['chembl.compound_rdfps'].alias()
join = A1.join(A2, A2.c.assay_id==A1.c.assay_id).join(FP1, FP1.c.molregno==A1.c.molregno).join(FP2, FP2.c.molregno==A2.c.molregno)
delta_tanimoto = 1 - func.rdkit.tanimoto_sml(FP1.c.circular_fp, FP2.c.circular_fp)
delta_activity = func.abs(func.log(A1.c.standard_value) - func.log(A2.c.standard_value)).label('delta_activity')
sali = (delta_activity / delta_tanimoto).label('sali')
whereclause = and_(A1.c.activity_id != A2.c.activity_id,
A1.c.molregno < A2.c.molregno,
A1.c.standard_type == A2.c.standard_type,
A1.c.standard_value > 0, A2.c.standard_value > 0,
A1.c.standard_flag > 0, A2.c.standard_flag > 0,
A1.c.standard_units == 'nM', A2.c.standard_units == 'nM',
A1.c.relation == '=', A1.c.relation == '=',
sali >= 1.5)
activity_cliffs = select([A1.c.assay_id,
A1.c.activity_id.label('activity_bgn_id'), A2.c.activity_id.label('activity_end_id'),
A1.c.molregno.label('molregno_bgn'), A2.c.molregno.label('molregno_end'),
delta_tanimoto.label('delta_tanimoto'), delta_activity, sali],
from_obj=[join], whereclause=whereclause).order_by("sali DESC").alias(name='activity_cliffs')
mapper(ActivityCliff, activity_cliffs, properties={
'Assay': relationship(Assay,
primaryjoin=Assay.assay_id==activity_cliffs.c.assay_id,
foreign_keys=[Assay.assay_id], uselist=False, innerjoin=True,
backref=backref('ActivityCliffs',uselist=True, innerjoin=True)),
'ActivityBgn': relationship(Activity,
primaryjoin=Activity.activity_id==activity_cliffs.c.activity_bgn_id,
foreign_keys=[Activity.activity_id], uselist=False, innerjoin=True),
'ActivityEnd': relationship(Activity,
primaryjoin=Activity.activity_id==activity_cliffs.c.activity_end_id,
foreign_keys=[Activity.activity_id], uselist=False, innerjoin=True),
'MoleculeBgn': relationship(Molecule,
primaryjoin=Molecule.molregno==activity_cliffs.c.molregno_bgn,
foreign_keys=[Molecule.molregno], uselist=False, innerjoin=True),
'MoleculeEnd': relationship(Molecule,
primaryjoin=Molecule.molregno==activity_cliffs.c.molregno_end,
foreign_keys=[Molecule.molregno], uselist=False, innerjoin=True,)
})
### ADAPTORS ###
class ActivityAdaptor(object):
'''
'''
def __init__(self):
'''
'''
self.query = session.query(Activity)
def fetch_by_activity_id(self, activity_id):
'''
'''
return self.query.get(activity_id)
def fetch_all_by_molregno(self, molregno, *expressions):
'''
'''
return self.query.filter(and_(Activity.molregno==molregno, *expressions)).all()
class ActivityCliffAdaptor(object):
'''
'''
def __init__(self):
'''
'''
self.query = session.query(ActivityCliff)
def fetch_all_by_molregno(self, molregno, *expressions):
'''
'''
bgn = self.query.filter(and_(ActivityCliff.molregno_bgn==molregno, *expressions))
end = self.query.filter(and_(ActivityCliff.molregno_end==molregno, *expressions))
return bgn.union(end).order_by(ActivityCliff.sali.desc()).limit(1000).all()
class AssayAdaptor(object):
'''
'''
def __init__(self):
'''
'''
self.query = session.query(Assay)
def fetch_by_assay_id(self, assay_id):
'''
'''
return self.query.get(assay_id)
def fetch_by_chembl_id(self, chembl_id):
'''
'''
return self.query.filter(Assay.chembl_id==chembl_id).first()
def fetch_all_by_pubmed_id(self, pubmed_id):
'''
'''
return self.query.join('Doc').filter(Doc.pubmed_id==pubmed_id).all()
class DocAdaptor(object):
'''
'''
def __init__(self):
'''
'''
self.query = session.query(Doc)
def fetch_by_doc_id(self, doc_id):
'''
'''
return self.query.get(doc_id)
def fetch_by_chembl_id(self, chembl_id):
'''
'''
return self.query.filter(Doc.chembl_id==chembl_id).first()
def fetch_all_by_pubmed_id(self, pubmed_id):
'''
'''
return self.query.filter(Doc.pubmed_id==pubmed_id).all()
class MoleculeAdaptor(object):
'''
'''
def __init__(self):
'''
'''
self.query = session.query(Molecule)
def fetch_by_molregno(self, molregno):
'''
'''
return self.query.get(molregno)
def fetch_by_chembl_id(self, chembl_id):
'''
'''
return self.query.filter(Molecule.chembl_id==chembl_id).first()
def fetch_all_by_synonym(self, synonym):
'''
'''
return self.query.join('Synonyms').filter(func.lower(MoleculeSynonym.synonyms)==synonym.lower()).all()
def fetch_active_by_molregno(self, molregno):
'''
'''
query = self.query.join(MoleculeHierarchy, MoleculeHierarchy.molregno==Molecule.molregno)
query = query.filter(MoleculeHierarchy.active_molregno==molregno)
return query.first()
def fetch_parent_by_molregno(self, molregno):
'''
'''
query = self.query.join(MoleculeHierarchy, MoleculeHierarchy.molregno==Molecule.molregno)
query = query.filter(MoleculeHierarchy.parent_molregno==molregno)
return query.first()
def fetch_dosed_component_by_molregno(self, molregno):
'''
'''
query = self.query.join('Formulations')
molecule = session.query(MoleculeHierarchy.molregno.label('molregno')).filter(MoleculeHierarchy.molregno==molregno)
parent = session.query(MoleculeHierarchy.molregno.label('molregno')).filter(MoleculeHierarchy.parent_molregno==molregno)
active = session.query(MoleculeHierarchy.molregno.label('molregno')).filter(MoleculeHierarchy.active_molregno==molregno)
subquery = molecule.union(parent,active).subquery()
query = query.join(subquery, subquery.c.molregno==Molecule.molregno)
return query.first()
def fetch_by_inchi_key(self, inchi_key):
'''
'''
query = self.query.join('Structure')
query = query.filter(CompoundStructure.standard_inchi_key==inchi_key)
return query.first()
@requires.rdkit_catridge
def fetch_all_by_substruct(self, smi, *expressions, **kwargs):
'''
Returns all molecules in ChEMBL that have the given SMILES
substructure.
Parameters
----------
smi : str
SMILES string of the substructure to be used for substructure
searching.
*expressions : BinaryExpressions, optional
SQLAlchemy BinaryExpressions that will be used to filter the query.
Queried Entities
----------------
Molecule, CompoundRDMol
Returns
-------
molecules : list
List of molecules that have the given substructure.
Examples
--------
Requires
--------
.. important:: `RDKit <http://www.rdkit.org>`_ PostgreSQL cartridge.
'''
limit = kwargs.get('limit', 100)
query = self.query.join(CompoundRDMol, CompoundRDMol.molregno==Molecule.molregno)
query = query.filter(and_(CompoundRDMol.contains(smi), *expressions))
return query.limit(limit).all()
@requires.rdkit_catridge
def fetch_all_by_superstruct(self, smiles, *expressions, **kwargs):
'''
Returns all molecules in ChEMBL that have the given SMILES superstructure.
Parameters
----------
smiles : string
SMILES string of the superstructure to be used for superstructure
searching.
*expressions : BinaryExpressions, optional
SQLAlchemy BinaryExpressions that will be used to filter the query.
Queried Entities
----------------
Molecule, CompoundRDMol
Returns
-------
molecules : list
List of molecules that have the given superstructure.
Examples
--------
Requires
--------
.. important:: `RDKit <http://www.rdkit.org>`_ PostgreSQL cartridge.
'''
limit = kwargs.get('limit', 100)
query = self.query.join(CompoundRDMol, CompoundRDMol.molregno==Molecule.molregno)
query = query.filter(and_(CompoundRDMol.contained_in(smiles), *expressions))
return query.limit(limit).all()
@requires.rdkit_catridge
def fetch_all_by_sim(self, smi, threshold=0.5, fp='circular', *expressions, **kwargs):
'''
Returns all molecules that match the given SMILES string with at
least the given similarity threshold using chemical fingerprints.
Parameters
----------
smi : str
The query rdmol in SMILES format.
threshold : float, default=0.5
The similarity threshold that will be used for searching.
fp : {'circular','atompair','torsion'}
RDKit fingerprint type to be used for similarity searching.
*expressions : BinaryExpressions, optional
SQLAlchemy BinaryExpressions that will be used to filter the query.
Queried Entities
----------------
Molecule, CompoundRDFP
Returns
-------
hits : list
List of tuples in the form (Molecule, similarity)
Examples
--------
Requires
--------
.. important:: `RDKit <http://www.rdkit.org>`_ | |
that all the (required) outputs were actually created and are newer than all input files specified so
far.
If successful, this marks all the outputs as up-to-date so that steps that depend on them will immediately
proceed.
"""
self._become_current()
missing_outputs = False
assert self.step is not None
did_sleep = False
for pattern in sorted(self.step.output): # pylint: disable=too-many-nested-blocks
formatted_pattern = fmt_capture(self.kwargs, pattern)
if is_phony(pattern):
Invocation.up_to_date[formatted_pattern] = UpToDate(self.name, self.newest_input_mtime_ns + 1)
continue
try:
paths = glob_paths(formatted_pattern)
if not paths:
Logger.debug(f"Did not make the optional output(s): {pattern}")
else:
for path in paths:
self.built_outputs.append(path)
global touch_success_outputs # pylint: disable=invalid-name
if touch_success_outputs.value:
if not did_sleep:
await self.done(asyncio.sleep(1.0))
did_sleep = True
Logger.file(f"Touch the output: {path}")
Stat.touch(path)
mtime_ns = Stat.stat(path).st_mtime_ns
Invocation.up_to_date[path] = UpToDate(self.name, mtime_ns)
if Logger.isEnabledFor(logging.DEBUG):
if path == formatted_pattern:
Logger.debug(f"Has the output: {path} " f"time: {_datetime_from_nanoseconds(mtime_ns)}")
else:
Logger.debug(
f"Has the output: {pattern} -> {path} "
f"time: {_datetime_from_nanoseconds(mtime_ns)}"
)
except NonOptionalException:
self._become_current()
Logger.error(f"Missing the output(s): {pattern}")
missing_outputs = True
break
if missing_outputs:
self.abort("Missing some output(s)")
def remove_stale_outputs(self) -> None:
"""
Delete stale outputs before running a action.
This is only done before running the first action of a step.
"""
for path in sorted(self.initial_outputs):
if self.should_remove_stale_outputs and not is_precious(path):
Logger.file(f"Remove the stale output: {path}")
Invocation.remove_output(path)
else:
Stat.forget(path)
self.should_remove_stale_outputs = False
@staticmethod
def remove_output(path: str) -> None:
"""
Remove an output file, and possibly the directories that became empty as a result.
"""
try:
Stat.remove(path)
global remove_empty_directories # pylint: disable=invalid-name
while remove_empty_directories.value:
path = os.path.dirname(path)
Stat.rmdir(path)
Logger.file(f"Remove the empty directory: {path}")
except OSError:
pass
def poison_all_outputs(self) -> None:
"""
Mark all outputs as poisoned for a failed step.
Typically also removes them.
"""
assert self.step is not None
for pattern in sorted(self.step.output):
formatted_pattern = fmt_capture(self.kwargs, optional(pattern))
if is_phony(formatted_pattern):
Invocation.poisoned.add(formatted_pattern)
continue
for path in glob_paths(optional(formatted_pattern)):
Invocation.poisoned.add(path)
global remove_failed_outputs # pylint: disable=invalid-name
if remove_failed_outputs.value and not is_precious(path):
Logger.file(f"Remove the failed output: {path}")
Invocation.remove_output(path)
def should_run_action(self) -> bool: # pylint: disable=too-many-return-statements
"""
Test whether all (required) outputs already exist, and are newer than all input files specified so far.
"""
if self.must_run_action:
return True
if self.phony_outputs:
# Either no output files (pure action) or missing output files.
Logger.why(f"Must run actions to satisfy the phony output: {self.phony_outputs[0]}")
return True
if self.missing_output is not None:
Logger.why(f"Must run actions to create the missing output(s): {self.missing_output}")
return True
if self.abandoned_output is not None:
Logger.why(f"Must run actions " f"because changed to abandon the output: {self.abandoned_output}")
return True
if self.new_persistent_actions:
# Compare with last successful build action.
index = len(self.new_persistent_actions) - 1
if index >= len(self.old_persistent_actions):
Logger.why("Must run actions because changed to add action(s)")
return True
new_action = self.new_persistent_actions[index]
old_action = self.old_persistent_actions[index]
if Invocation.different_actions(old_action, new_action):
return True
# All output files exist:
if self.newest_input_path is None:
# No input files (pure computation).
Logger.debug("Can skip actions " "because all the outputs exist and there are no newer inputs")
return False
# There are input files:
if self.oldest_output_path is not None and self.oldest_output_mtime_ns <= self.newest_input_mtime_ns:
# Some output file is not newer than some input file.
Logger.why(
f"Must run actions because the output: {self.oldest_output_path} "
f"is not newer than the input: {self.newest_input_path}"
)
return True
# All output files are newer than all input files.
Logger.debug("Can skip actions " "because all the outputs exist and are newer than all the inputs")
return False
@staticmethod
def different_actions(old_action: PersistentAction, new_action: PersistentAction) -> bool:
"""
Check whether the new action is different from the last build action.
"""
if Invocation.different_required(old_action.required, new_action.required):
return True
if old_action.command != new_action.command:
if old_action.command is None:
old_action_kind = "a phony command"
else:
old_action_kind = "the command: " + " ".join(old_action.command)
if new_action.command is None:
new_action_kind = "a phony command"
else:
new_action_kind = "the command: " + " ".join(new_action.command)
Logger.why(f"Must run actions because changed {old_action_kind} " f"into {new_action_kind}")
return True
return False
@staticmethod
def different_required(old_required: Dict[str, UpToDate], new_required: Dict[str, UpToDate]) -> bool:
"""
Check whether the required inputs of the new action are different from the required inputs of the last build
action.
"""
for new_path in sorted(new_required.keys()):
if new_path not in old_required:
Logger.why(f"Must run actions because changed to require: {new_path}")
return True
for old_path in sorted(old_required.keys()):
if old_path not in new_required:
Logger.why(f"Must run actions because changed to not require: {old_path}")
return True
for path in sorted(new_required.keys()):
old_up_to_date = old_required[path]
new_up_to_date = new_required[path]
if old_up_to_date.producer != new_up_to_date.producer:
Logger.why(
f"Must run actions because the producer of the required: {path} "
f'has changed from: {old_up_to_date.producer or "source file"} '
f'into: {new_up_to_date.producer or "source file"}'
)
return True
if not is_exists(path) and old_up_to_date.mtime_ns != new_up_to_date.mtime_ns:
Logger.why(
f"Must run actions "
f"because the modification time of the required: {path} "
f"has changed from: "
f"{_datetime_from_nanoseconds(old_up_to_date.mtime_ns)} "
f"into: "
f"{_datetime_from_nanoseconds(new_up_to_date.mtime_ns)}"
)
return True
return False
async def run_action( # pylint: disable=too-many-branches,too-many-statements,too-many-locals
self,
kind: str,
runner: Callable[[List[str]], Awaitable],
*command: Strings,
**resources: int,
) -> None:
"""
Spawn a action to actually create some files.
"""
self._become_current()
self.abort_due_to_other()
await self.done(self.sync())
run_parts = []
persistent_parts = []
log_parts = []
is_silent = None
for part in each_string(*command):
if is_silent is None:
if part.startswith("@"):
is_silent = True
if part == "@":
continue
part = part[1:]
else:
is_silent = False
run_parts.append(part)
if not is_phony(part):
persistent_parts.append(part)
if kind != "shell":
part = copy_annotations(part, shlex.quote(part))
log_parts.append(part)
log_command = " ".join(log_parts)
if self.exception is not None:
Logger.debug(f"Can't run: {log_command}")
no_additional_complaints()
raise self.exception
if self.new_persistent_actions:
self.new_persistent_actions[-1].run_action(persistent_parts)
if not self.should_run_action():
global log_skipped_actions # pylint: disable=invalid-name
if not log_skipped_actions.value:
level = logging.DEBUG
elif is_silent:
level = Logger.FILE
else:
level = logging.INFO
Logger.log(level, f"Skip: {log_command}")
self.did_skip_actions = True
if self.new_persistent_actions:
self.new_persistent_actions.append(PersistentAction(self.new_persistent_actions[-1])) #
Invocation.skipped_count += 1
return
if self.did_skip_actions:
self.must_run_action = True
Logger.debug("Must restart step to run skipped action(s)")
raise RestartException("To run skipped action(s)")
self.must_run_action = True
self.did_run_actions = True
Invocation.actions_count += 1
resources = Resources.effective(resources)
if resources:
await self.done(self._use_resources(resources))
try:
self.remove_stale_outputs()
self.oldest_output_path = None
global no_actions # pylint: disable=invalid-name
async with locks():
if is_silent:
Logger.file(f"Run: {log_command}")
else:
Logger.info(f"Run: {log_command}")
if no_actions.value:
raise DryRunException()
if no_actions.value:
exit_status = 0
else:
sub_process = await self.done(runner(run_parts))
read_stdout = self._read_pipe(sub_process.stdout, Logger.STDOUT)
read_stderr = self._read_pipe(sub_process.stderr, Logger.STDERR)
await self.done(asyncio.gather(read_stdout, read_stderr))
exit_status = await self.done(sub_process.wait())
if self.new_persistent_actions:
persistent_action = self.new_persistent_actions[-1]
persistent_action.done_action()
self.new_persistent_actions.append(PersistentAction(persistent_action))
if exit_status != 0:
self.log_and_abort(f"Failure: {log_command}")
return
if not no_actions.value:
Logger.trace(f"Success: {log_command}")
finally:
self._become_current()
if resources:
if Logger.isEnabledFor(logging.DEBUG):
Logger.debug("Free resources: " + _dict_to_str(resources))
Resources.free(resources)
if Logger.isEnabledFor(logging.DEBUG):
Logger.debug("Available resources: " + _dict_to_str(Resources.available))
await self.done(Resources.condition.acquire())
Resources.condition.notify_all()
Resources.condition.release()
async def _read_pipe(self, pipe: asyncio.StreamReader, level: int) -> None:
while True:
line = await self.done(pipe.readline())
if not line:
return
message = line.decode("utf-8").rstrip("\n")
message = Invocation.current.log + " - " + message
Logger._logger.log(level, message) # pylint: disable=protected-access
async def _use_resources(self, amounts: Dict[str, int]) -> None:
self._become_current()
while True:
if Resources.have(amounts):
if Logger.isEnabledFor(logging.DEBUG):
Logger.debug("Grab resources: " + _dict_to_str(amounts))
Resources.grab(amounts)
if Logger.isEnabledFor(logging.DEBUG):
Logger.debug("Available resources: " + _dict_to_str(Resources.available))
return
if Logger.isEnabledFor(logging.DEBUG):
Logger.debug("Available resources: " + _dict_to_str(Resources.available))
Logger.debug("Paused by waiting for resources: " + _dict_to_str(amounts))
await self.done(Resources.condition.acquire())
await self.done(Resources.condition.wait())
Resources.condition.release()
async def sync(self) -> Optional[BaseException]: # pylint: disable=too-many-branches,too-many-statements
"""
Wait until all the async actions queued so far are complete.
This is implicitly called before running a action.
"""
self._become_current()
self.abort_due_to_other()
if self.async_actions:
Logger.debug("Sync")
results: List[Optional[StepException]] = await self.done(asyncio.gather(*self.async_actions))
if self.exception is None:
for exception in results:
if exception is not None:
self.exception = exception
break
self.async_actions = []
Logger.debug("Synced")
failed_inputs = False
global no_actions # pylint: disable=invalid-name
for path in sorted(self.required):
if path in Invocation.poisoned or (not is_optional(path) and path not in Invocation.up_to_date):
if self.exception is None and not isinstance(self.exception, DryRunException):
level = logging.ERROR
else:
level = logging.DEBUG
if no_actions.value:
Logger.log(level, f"Did not run actions for the required: {path}")
else:
Logger.log(level, f"The required: {path} has failed to build")
Invocation.poisoned.add(path)
failed_inputs = True
continue
if path not in Invocation.up_to_date:
assert is_optional(path)
continue
Logger.debug(f"Has the required: {path}")
if is_exists(path):
continue
if path in Invocation.phony:
mtime_ns = Invocation.up_to_date[path].mtime_ns
else:
mtime_ns = Stat.stat(path).st_mtime_ns
if self.newest_input_path is None or self.newest_input_mtime_ns < mtime_ns:
self.newest_input_path = path
self.newest_input_mtime_ns = mtime_ns
if failed_inputs:
if no_actions.value:
raise DryRunException()
| |
<reponame>thunderhoser/GeneralExam<filename>generalexam/evaluation/object_based_evaluation_test.py
"""Unit tests for object_based_evaluation.py."""
import copy
import unittest
import numpy
import pandas
from gewittergefahr.gg_utils import nwp_model_utils
from generalexam.evaluation import object_based_evaluation as object_based_eval
from generalexam.ge_utils import front_utils
from generalexam.ge_utils import a_star_search
from generalexam.machine_learning import machine_learning_utils as ml_utils
TOLERANCE = 1e-6
ARRAY_COLUMN_NAMES = [
object_based_eval.ROW_INDICES_COLUMN,
object_based_eval.COLUMN_INDICES_COLUMN,
object_based_eval.X_COORDS_COLUMN, object_based_eval.Y_COORDS_COLUMN
]
# The following constants are used to test _one_region_to_binary_image and
# _one_binary_image_to_region.
BINARY_IMAGE_MATRIX_ONE_REGION = numpy.array(
[[1, 1, 0, 0, 0, 1, 0, 0],
[0, 1, 0, 0, 0, 1, 1, 0],
[0, 1, 1, 0, 0, 1, 1, 0],
[0, 1, 1, 0, 0, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0, 0]], dtype=int)
ROW_INDICES_ONE_REGION = numpy.array(
[0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int)
COLUMN_INDICES_ONE_REGION = numpy.array(
[0, 1, 5, 1, 5, 6, 1, 2, 5, 6, 1, 2, 5, 2, 3, 4], dtype=int)
# The following constants are used to test _find_endpoints_of_skeleton.
BINARY_SKELETON_MATRIX = numpy.array([[1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 0, 0, 1, 0],
[0, 0, 1, 1, 0, 0, 1, 0],
[0, 0, 0, 1, 1, 0, 1, 0],
[0, 0, 0, 0, 1, 1, 0, 0]], dtype=int)
BINARY_ENDPOINT_MATRIX = numpy.array([[1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 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]], dtype=int)
# The following constants are used to test _get_skeleton_line_endpoint_length,
# _get_skeleton_line_arc_length, and _get_skeleton_line_quality.
THIS_GRID_SEARCH_OBJECT = a_star_search.GridSearch(
binary_region_matrix=BINARY_IMAGE_MATRIX_ONE_REGION)
(ROW_INDICES_ONE_SKELETON, COLUMN_INDICES_ONE_SKELETON
) = a_star_search.run_a_star(
grid_search_object=THIS_GRID_SEARCH_OBJECT, start_row=0, start_column=0,
end_row=1, end_column=6)
(X_GRID_SPACING_METRES, Y_GRID_SPACING_METRES
) = nwp_model_utils.get_xy_grid_spacing(
model_name=nwp_model_utils.NARR_MODEL_NAME)
ENDPOINT_LENGTH_METRES = numpy.sqrt(37.) * X_GRID_SPACING_METRES
MIN_ENDPOINT_LENGTH_SMALL_METRES = ENDPOINT_LENGTH_METRES - 1.
MIN_ENDPOINT_LENGTH_LARGE_METRES = ENDPOINT_LENGTH_METRES + 1.
ARC_LENGTH_METRES = (3 + 5 * numpy.sqrt(2.)) * X_GRID_SPACING_METRES
SKELETON_LINE_QUALITY_POSITIVE = ENDPOINT_LENGTH_METRES ** 2 / ARC_LENGTH_METRES
SKELETON_LINE_QUALITY_NEGATIVE = (
object_based_eval.NEGATIVE_SKELETON_LINE_QUALITY + 0.
)
# The following constants are used to test _get_distance_between_fronts.
THESE_FIRST_X_METRES = numpy.array([1, 1, 2, 2, 2, 2, 2], dtype=float)
THESE_FIRST_Y_METRES = numpy.array([6, 5, 5, 4, 3, 2, 1], dtype=float)
THESE_SECOND_X_METRES = numpy.array([1, 2, 2, 3, 4, 5, 6, 7, 7, 8], dtype=float)
THESE_SECOND_Y_METRES = numpy.array([5, 5, 4, 4, 4, 4, 4, 4, 5, 5], dtype=float)
THESE_SHORTEST_DISTANCES_METRES = numpy.array(
[1, 0, 1, 0, 3, 3, 3], dtype=float)
INTERFRONT_DISTANCE_METRES = numpy.median(THESE_SHORTEST_DISTANCES_METRES)
# The following constants are used to test determinize_probabilities.
THIS_MATRIX_CLASS0 = numpy.array(
[[0.7, 0.1, 0.4, 0.9, 0.6, 0.2, 0.5, 0.6],
[0.7, 0.6, 0.6, 1.0, 0.7, 0.6, 0.3, 0.8],
[0.5, 0.9, 0.6, 0.9, 0.6, 0.2, 0.4, 0.9],
[0.8, 0.8, 0.2, 0.4, 1.0, 0.5, 0.9, 0.9],
[0.2, 0.9, 0.9, 0.2, 0.2, 0.5, 0.1, 0.1]])
THIS_MATRIX_CLASS1 = numpy.array(
[[0.2, 0.7, 0.3, 0.1, 0.1, 0.2, 0.2, 0.1],
[0.3, 0.2, 0.3, 0.0, 0.1, 0.1, 0.3, 0.0],
[0.4, 0.0, 0.3, 0.0, 0.1, 0.3, 0.2, 0.0],
[0.1, 0.0, 0.6, 0.2, 0.0, 0.2, 0.1, 0.1],
[0.5, 0.9, 0.1, 0.5, 0.3, 0.0, 0.4, 0.3]])
THIS_MATRIX_CLASS2 = numpy.array(
[[0.1, 0.2, 0.3, 0.0, 0.3, 0.6, 0.3, 0.3],
[0.0, 0.2, 0.1, 0.0, 0.2, 0.3, 0.4, 0.2],
[0.1, 0.1, 0.1, 0.1, 0.3, 0.5, 0.4, 0.1],
[0.1, 0.2, 0.2, 0.4, 0.0, 0.3, 0.0, 0.0],
[0.3, 0.1, 0.0, 0.3, 0.5, 0.5, 0.5, 0.6]])
PROBABILITY_MATRIX = numpy.stack(
(THIS_MATRIX_CLASS0, THIS_MATRIX_CLASS1, THIS_MATRIX_CLASS2), axis=-1)
PROBABILITY_MATRIX = numpy.expand_dims(PROBABILITY_MATRIX, axis=0)
BINARIZATION_THRESHOLD = 0.75
PREDICTED_LABEL_MATRIX = numpy.array(
[[1, 1, 1, 0, 2, 2, 2, 2],
[1, 1, 1, 0, 2, 2, 2, 0],
[1, 0, 1, 0, 2, 2, 2, 0],
[0, 0, 1, 2, 0, 2, 0, 0],
[1, 0, 0, 1, 2, 2, 2, 2]], dtype=int)
PREDICTED_LABEL_MATRIX = numpy.expand_dims(PREDICTED_LABEL_MATRIX, axis=0)
# The following constants are used to test images_to_regions and
# regions_to_images.
IMAGE_TIMES_UNIX_SEC = numpy.array([0], dtype=int)
REGION_TIMES_UNIX_SEC = numpy.array([0, 0, 0], dtype=int)
FRONT_TYPE_STRINGS = [
front_utils.WARM_FRONT_STRING_ID, front_utils.COLD_FRONT_STRING_ID,
front_utils.WARM_FRONT_STRING_ID
]
ROW_INDICES_LARGE_WF_REGION = numpy.array(
[0, 0, 0, 1, 1, 1, 2, 2, 3, 4], dtype=int)
COLUMN_INDICES_LARGE_WF_REGION = numpy.array(
[0, 1, 2, 0, 1, 2, 0, 2, 2, 3], dtype=int)
ROW_INDICES_SMALL_WF_REGION = numpy.array([4], dtype=int)
COLUMN_INDICES_SMALL_WF_REGION = numpy.array([0], dtype=int)
ROW_INDICES_CF_REGION = numpy.array(
[0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 4], dtype=int)
COLUMN_INDICES_CF_REGION = numpy.array(
[4, 5, 6, 7, 4, 5, 6, 4, 5, 6, 3, 5, 4, 5, 6, 7], dtype=int)
ROW_INDICES_BY_REGION = [
ROW_INDICES_LARGE_WF_REGION, ROW_INDICES_CF_REGION,
ROW_INDICES_SMALL_WF_REGION
]
COLUMN_INDICES_BY_REGION = [
COLUMN_INDICES_LARGE_WF_REGION, COLUMN_INDICES_CF_REGION,
COLUMN_INDICES_SMALL_WF_REGION
]
THIS_DICT = {
front_utils.TIME_COLUMN: REGION_TIMES_UNIX_SEC,
front_utils.FRONT_TYPE_COLUMN: FRONT_TYPE_STRINGS,
object_based_eval.ROW_INDICES_COLUMN: ROW_INDICES_BY_REGION,
object_based_eval.COLUMN_INDICES_COLUMN: COLUMN_INDICES_BY_REGION
}
PREDICTED_REGION_TABLE = pandas.DataFrame.from_dict(THIS_DICT)
# The following constants are used to test discard_regions_with_small_area.
MIN_REGION_AREA_METRES2 = 1.2e10 # 12 000 km^2 (~11 grid cells)
PREDICTED_REGION_TABLE_SANS_SMALL_AREA = PREDICTED_REGION_TABLE.drop(
PREDICTED_REGION_TABLE.index[[0, 2]], axis=0, inplace=False)
# The following constants are used to test skeletonize_frontal_regions.
# SKELETON_MATRIX = numpy.array([[0, 0, 0, 0, 0, 0, 2, 2],
# [0, 1, 0, 0, 0, 2, 0, 0],
# [1, 0, 1, 0, 2, 0, 0, 0],
# [0, 0, 1, 2, 0, 2, 0, 0],
# [1, 0, 0, 1, 2, 2, 2, 2]], dtype=int)
THESE_ROW_INDICES_LARGE_WF = numpy.array([1, 2, 2, 3, 4], dtype=int)
THESE_COLUMN_INDICES_LARGE_WF = numpy.array([1, 0, 2, 2, 3], dtype=int)
THESE_ROW_INDICES_SMALL_WF = numpy.array([4], dtype=int)
THESE_COLUMN_INDICES_SMALL_WF = numpy.array([0], dtype=int)
THESE_ROW_INDICES_COLD_FRONT = numpy.array(
[0, 0, 1, 2, 3, 3, 4, 4, 4, 4], dtype=int)
THESE_COLUMN_INDICES_COLD_FRONT = numpy.array(
[6, 7, 5, 4, 3, 5, 4, 5, 6, 7], dtype=int)
ROW_INDICES_BY_SKELETON = [
THESE_ROW_INDICES_LARGE_WF, THESE_ROW_INDICES_COLD_FRONT,
THESE_ROW_INDICES_SMALL_WF
]
COLUMN_INDICES_BY_SKELETON = [
THESE_COLUMN_INDICES_LARGE_WF, THESE_COLUMN_INDICES_COLD_FRONT,
THESE_COLUMN_INDICES_SMALL_WF
]
PREDICTED_SKELETON_DICT = {
front_utils.TIME_COLUMN: REGION_TIMES_UNIX_SEC,
front_utils.FRONT_TYPE_COLUMN: FRONT_TYPE_STRINGS,
object_based_eval.ROW_INDICES_COLUMN: ROW_INDICES_BY_SKELETON,
object_based_eval.COLUMN_INDICES_COLUMN: COLUMN_INDICES_BY_SKELETON
}
PREDICTED_SKELETON_TABLE = pandas.DataFrame.from_dict(PREDICTED_SKELETON_DICT)
# The following constants are used to test find_main_skeletons.
# MAIN_SKELETON_MATRIX = numpy.array([[0, 0, 0, 0, 0, 0, 2, 2],
# [0, 1, 0, 0, 0, 2, 0, 0],
# [1, 0, 1, 0, 2, 0, 0, 0],
# [0, 0, 1, 0, 0, 2, 0, 0],
# [1, 0, 0, 1, 0, 0, 2, 2]], dtype=int)
THESE_ROW_INDICES_LARGE_WF = numpy.array([2, 1, 2, 3, 4], dtype=int)
THESE_COLUMN_INDICES_LARGE_WF = numpy.array([0, 1, 2, 2, 3], dtype=int)
THESE_ROW_INDICES_COLD_FRONT = numpy.array([0, 0, 1, 2, 3, 4, 4], dtype=int)
THESE_COLUMN_INDICES_COLD_FRONT = numpy.array([7, 6, 5, 4, 5, 6, 7], dtype=int)
THESE_INDICES = numpy.array([0, 1], dtype=int)
PREDICTED_MAIN_SKELETON_DICT = {
front_utils.TIME_COLUMN: REGION_TIMES_UNIX_SEC[THESE_INDICES],
front_utils.FRONT_TYPE_COLUMN:
[FRONT_TYPE_STRINGS[k] for k in THESE_INDICES],
object_based_eval.ROW_INDICES_COLUMN:
[THESE_ROW_INDICES_LARGE_WF, THESE_ROW_INDICES_COLD_FRONT],
object_based_eval.COLUMN_INDICES_COLUMN:
[THESE_COLUMN_INDICES_LARGE_WF, THESE_COLUMN_INDICES_COLD_FRONT]
}
PREDICTED_MAIN_SKELETON_TABLE = pandas.DataFrame.from_dict(
PREDICTED_MAIN_SKELETON_DICT)
# The following constants are used to test convert_regions_rowcol_to_narr_xy.
X_COORDS_LARGE_WF_REGION_METRES = (
COLUMN_INDICES_LARGE_WF_REGION * X_GRID_SPACING_METRES
)
Y_COORDS_LARGE_WF_REGION_METRES = (
ROW_INDICES_LARGE_WF_REGION * Y_GRID_SPACING_METRES
)
X_COORDS_SMALL_WF_REGION_METRES = (
COLUMN_INDICES_SMALL_WF_REGION * X_GRID_SPACING_METRES
)
Y_COORDS_SMALL_WF_REGION_METRES = (
ROW_INDICES_SMALL_WF_REGION * Y_GRID_SPACING_METRES
)
X_COORDS_CF_REGION_METRES = COLUMN_INDICES_CF_REGION * X_GRID_SPACING_METRES
Y_COORDS_CF_REGION_METRES = ROW_INDICES_CF_REGION * Y_GRID_SPACING_METRES
X_COORDS_BY_REGION_METRES = [
X_COORDS_LARGE_WF_REGION_METRES, X_COORDS_CF_REGION_METRES,
X_COORDS_SMALL_WF_REGION_METRES
]
Y_COORDS_BY_REGION_METRES = [
Y_COORDS_LARGE_WF_REGION_METRES, Y_COORDS_CF_REGION_METRES,
Y_COORDS_SMALL_WF_REGION_METRES
]
THIS_DICT = {
object_based_eval.X_COORDS_COLUMN: X_COORDS_BY_REGION_METRES,
object_based_eval.Y_COORDS_COLUMN: Y_COORDS_BY_REGION_METRES
}
PREDICTED_REGION_TABLE_WITH_XY_COORDS = PREDICTED_REGION_TABLE.assign(
**THIS_DICT)
# The following constants are used to test get_binary_contingency_table.
THESE_X_COORDS_BY_FRONT_METRES = [
numpy.array([1.]), numpy.array([2.]), numpy.array([3.]), numpy.array([4.]),
numpy.array([1.]), numpy.array([2.]), numpy.array([3.])
]
THESE_Y_COORDS_BY_FRONT_METRES = [
numpy.array([1.]), numpy.array([2.]), numpy.array([3.]), numpy.array([4.]),
numpy.array([1.]), numpy.array([2.]), numpy.array([3.])
]
THESE_TIMES_UNIX_SEC = numpy.array([0, 0, 0, 0, 1, 1, 1], dtype=int)
THESE_FRONT_TYPE_STRINGS = [
front_utils.COLD_FRONT_STRING_ID, front_utils.WARM_FRONT_STRING_ID,
front_utils.COLD_FRONT_STRING_ID, front_utils.WARM_FRONT_STRING_ID,
front_utils.COLD_FRONT_STRING_ID, front_utils.WARM_FRONT_STRING_ID,
front_utils.COLD_FRONT_STRING_ID
]
THIS_DICT = {
front_utils.TIME_COLUMN: THESE_TIMES_UNIX_SEC,
front_utils.FRONT_TYPE_COLUMN: THESE_FRONT_TYPE_STRINGS,
object_based_eval.X_COORDS_COLUMN: THESE_X_COORDS_BY_FRONT_METRES,
object_based_eval.Y_COORDS_COLUMN: THESE_Y_COORDS_BY_FRONT_METRES
}
ACTUAL_POLYLINE_TABLE = pandas.DataFrame.from_dict(THIS_DICT)
THESE_X_COORDS_BY_FRONT_METRES = [
numpy.array([1.]), numpy.array([2.]), numpy.array([50.]),
numpy.array([4.]), numpy.array([3.])
]
THESE_Y_COORDS_BY_FRONT_METRES = [
numpy.array([0.]), numpy.array([2.]), numpy.array([-100.]),
numpy.array([5.5]), numpy.array([3.])
]
THESE_TIMES_UNIX_SEC = numpy.array([0, 0, 0, 1, 1], dtype=int)
THESE_FRONT_TYPE_STRINGS = [
front_utils.COLD_FRONT_STRING_ID, front_utils.COLD_FRONT_STRING_ID,
front_utils.COLD_FRONT_STRING_ID, front_utils.WARM_FRONT_STRING_ID,
front_utils.COLD_FRONT_STRING_ID
]
THIS_DICT = {
front_utils.TIME_COLUMN: THESE_TIMES_UNIX_SEC,
front_utils.FRONT_TYPE_COLUMN: THESE_FRONT_TYPE_STRINGS,
object_based_eval.X_COORDS_COLUMN: THESE_X_COORDS_BY_FRONT_METRES,
object_based_eval.Y_COORDS_COLUMN: THESE_Y_COORDS_BY_FRONT_METRES
}
PREDICTED_REGION_TABLE_FOR_CT = pandas.DataFrame.from_dict(THIS_DICT)
NEIGH_DISTANCE_METRES = 2.
BINARY_CONTINGENCY_TABLE_AS_DICT = {
object_based_eval.NUM_ACTUAL_FRONTS_PREDICTED_KEY: 5,
object_based_eval.NUM_FALSE_NEGATIVES_KEY: 2,
object_based_eval.NUM_PREDICTED_FRONTS_VERIFIED_KEY: 3,
object_based_eval.NUM_FALSE_POSITIVES_KEY: 2
}
ROW_NORMALIZED_CT_AS_MATRIX = numpy.array([[1., 0., 0.],
[0.25, 0.25, 0.5]])
COLUMN_NORMALIZED_CT_AS_MATRIX = numpy.array([[1. / 3, 0.25],
[0., 0.],
[2. / 3, 0.75]])
# The following constants are used to test performance metrics.
FAKE_BINARY_CT_AS_DICT = {
object_based_eval.NUM_ACTUAL_FRONTS_PREDICTED_KEY: 100,
object_based_eval.NUM_PREDICTED_FRONTS_VERIFIED_KEY: 50,
object_based_eval.NUM_FALSE_POSITIVES_KEY: 200,
object_based_eval.NUM_FALSE_NEGATIVES_KEY: 10
}
BINARY_POD = 100. / 110
BINARY_FOM = 10. / 110
BINARY_SUCCESS_RATIO = 50. / 250
BINARY_FAR = 200. / 250
BINARY_CSI = (110. / 100 + 250. / 50 - 1.) ** -1
BINARY_FREQUENCY_BIAS = (100. / 110) * (250. / 50)
def _compare_tables(first_table, second_table):
"""Compares two pandas DataFrames.
:param first_table: pandas DataFrame.
:param second_table: pandas DataFrame.
:return: are_tables_equal: Boolean flag.
"""
these_column_names = list(first_table)
expected_column_names = list(second_table)
if set(these_column_names) != set(expected_column_names):
return False
this_num_regions = len(first_table.index)
expected_num_regions = len(second_table.index)
if this_num_regions != expected_num_regions:
return False
for i in range(this_num_regions):
for this_column_name in these_column_names:
if this_column_name in ARRAY_COLUMN_NAMES:
if not numpy.allclose(first_table[this_column_name].values[i],
second_table[this_column_name].values[i],
atol=TOLERANCE):
return False
else:
if not (first_table[this_column_name].values[i] ==
second_table[this_column_name].values[i]):
return False
return True
class ObjectBasedEvaluationTests(unittest.TestCase):
"""Each method is a unit test for object_based_evaluation.py."""
def test_one_region_to_binary_image(self):
"""Ensures correct output from _one_region_to_binary_image."""
this_binary_image_matrix = (
object_based_eval._one_region_to_binary_image(
row_indices_in_region=ROW_INDICES_ONE_REGION,
column_indices_in_region=COLUMN_INDICES_ONE_REGION,
num_grid_rows=BINARY_IMAGE_MATRIX_ONE_REGION.shape[0],
num_grid_columns=BINARY_IMAGE_MATRIX_ONE_REGION.shape[1])
)
self.assertTrue(numpy.array_equal(
this_binary_image_matrix, BINARY_IMAGE_MATRIX_ONE_REGION))
def test_one_binary_image_to_region(self):
"""Ensures correct output from _one_binary_image_to_region."""
(these_row_indices, these_column_indices
) = object_based_eval._one_binary_image_to_region(
BINARY_IMAGE_MATRIX_ONE_REGION)
self.assertTrue(numpy.array_equal(
these_row_indices, ROW_INDICES_ONE_REGION))
self.assertTrue(numpy.array_equal(
these_column_indices, COLUMN_INDICES_ONE_REGION))
def test_find_endpoints_of_skeleton(self):
"""Ensures correct output from _find_endpoints_of_skeleton."""
this_binary_endpoint_matrix = (
object_based_eval._find_endpoints_of_skeleton(
BINARY_SKELETON_MATRIX)
)
self.assertTrue(numpy.array_equal(
this_binary_endpoint_matrix, BINARY_ENDPOINT_MATRIX))
def test_get_skeleton_line_endpoint_length(self):
"""Ensures correct output from _get_skeleton_line_endpoint_length."""
this_length_metres = (
object_based_eval._get_skeleton_line_endpoint_length(
row_indices=ROW_INDICES_ONE_SKELETON,
column_indices=COLUMN_INDICES_ONE_SKELETON,
x_grid_spacing_metres=X_GRID_SPACING_METRES,
y_grid_spacing_metres=Y_GRID_SPACING_METRES)
)
self.assertTrue(numpy.isclose(
this_length_metres, | |
'status': 'Active',
'valueLengthMax': '20',
'valueLengthMin': '1'}]
>>> r = client.discover_and_add_accounts(100000, **{
'Banking Userid': 'direct',
'Banking Password': '<PASSWORD>',
})
>>> r
<AggCatResponse 201>
>>> r.content
<Accountlist object [<Creditaccount object @ 0x10d12d790>,<Loanaccount object @ 0x10d12d810> ...] @ 0x10d12d710>
If a *challenge response is required* we get a different result::
>>> r = client.discover_and_add_accounts(100000, **{
'Banking Userid': 'direct',
'Banking Password': '<PASSWORD>',
})
>>> r
<AggCatResponse 401>
>>> r.content
<Challenges object [<Challenge object @ 0x10d12d5d0>,<Challenge object @ 0x10d12d110> ...] @ 0x10d0ffc50>
Notice that ``r.content`` is now a :class:`Challenges` object. Listing the challenges will give
to the questions that must be asked to the user::
>>> for c in r.content:
print c.text
Enter your first pet's name:
Enter your high school's name:
You might convert this into an html form
.. code-block:: html
<form action="/login/confirm-challenge" method="POST>
<div>Enter your first pet's name: <input type="text" name="response_1" /></div>
<div>Enter your high school's name: <input type="text" name="response_2" /></div>
</form>
<input type="submit" value="Confirm Challenges" />
"""
# validate the credentials passed
self._validate_credentials(institution_id, **credentials)
login_xml = self._generate_login_xml(**credentials)
return self._make_request(
'institutions/%s/logins' % institution_id,
'POST',
login_xml
)
def confirm_challenge(self, institution_id, challenge_session_id, challenge_node_id, responses):
"""Post challenge responses and add accounts
:param integer institution_id: The institution's id. See :ref:`search_for_institution`.
:param string challenge_session_id: The session id received from `AggcatResponse.headers` in :meth:`discover_and_add_accounts`
:param string challenge_node_id: The session id received from `AggcatResponse.headers` in :meth:`discover_and_add_accounts`
:param list responses: A list of responses, ex. ['Cats Name', 'First High School']
:returns: An :class:`AggcatReponse` with attribute ``content`` being an :class:`AccountList`
When using :meth:`discover_and_add_accounts` you might get a challenge response::
>>> r = client.discover_and_add_accounts(100000, **{
'Banking Userid': 'direct',
'Banking Password': '<PASSWORD>',
})
>>> r
<AggCatResponse 401>
>>> r.content
<Challenges object [<Challenge object @ 0x10d12d5d0>,<Challenge object @ 0x10d12d110> ...] @ 0x10d0ffc50>
>>> r.headers
{'challengenodeid': '10.136.17.82',
'challengesessionid': 'c31c8a55-754e-4252-8212-b8143270f84f',
'connection': 'close',
'content-length': '275',
'content-type': 'application/xml',
'date': 'Mon, 12 Aug 2013 03:15:42 GMT',
'intuit_tid': 'e41418d4-7b77-401e-a158-12514b0d84e3',
'server': 'Apache/2.2.22 (Unix)',
'status': '401',
'via': '1.1 ipp-gateway-ap02'}
* The ``challenge_session_id`` parameter comes from ``r.headers['challengesessionid']``
* The ``challenge_node_id`` parameter comes from ``r.headers['challengenodeid']``
Now confirm the challenge::
>>> challenge_session_id = r.headers['challengesessionid']
>>> challenge_node_id = r.headers['challengenodeid']
>>> responses = ['Black Cat', 'Meow High School']
>>> accounts = r.confirm_challenge(
1000000,
challenge_session_id,
challenge_node_id,
responses
)
>>> accounts
<AggCatResponse 201>
>>> accounts.content
<Accountlist object [<Creditaccount object @ 0x10d12d790>,<Loanaccount object @ 0x10d12d810> ...] @ 0x10d12d710>
"""
xml = self._generate_challenge_response(responses)
headers = {
'challengeNodeId': challenge_node_id,
'challengeSessionId': challenge_session_id
}
return self._make_request(
'institutions/%s/logins' % institution_id,
'POST',
xml,
headers=headers
)
def get_customer_accounts(self):
"""Get a list of all current customer accounts
:returns: :class:`AggcatResponse`
This endpoint assumes that the customer accounts we are getting
are for the one set in :ref:`initializing_client`::
>>> r = ac.get_customer_accounts()
>>> r.content
<Accountlist object [<Investmentaccount object @ 0x1104779d0>,<Creditaccount object @ 0x110477d50> ...] @ 0x110477b10>
>>> for account in r.content:
print account.account_nickname, account. account_number
My Retirement 0000000001
My Visa 4100007777
My Mortgage 1000000001
My Brokerage 0000000000
My Roth IRA 2000004444
My Savings 1000002222
My Line of Credit 8000006666
My CD 2000005555
My Auto Loan 8000008888
My Checking 1000001111
.. note::
Attributes on accounts very depending on account type. See `account reference
in the Intuit documentation <https://developer.intuit.com/docs/0020_customeraccountdata/customer_account_data_api/0020_api_documentation/0035_getaccount>`_.
Also note that when the XML gets objectified XML attributes like ``accountId`` get converted
to ``account_id``
"""
return self._make_request('accounts')
def get_login_accounts(self, login_id):
"""Get a list of account belonging to a login
:param integer login_id: Login id of the instiution. This can be retrieved from an account.
:returns: :class:`AggcatResponse`
You may have multiple logins. For example, a Fidelity Account and a Bank of America. This
will allow you to get onlt the accounts for a specified login::
>>> client.get_login_accounts(83850162)
<AggCatResponse 200>
>>> r.content
<Accountlist object [<Investmentaccount object @ 0x1090c9bd0>,<Loanaccount object @ 0x1090c9890> ...] @ 0x1090c9b10>
>>> len(r.content)
10
>>> r.content[0]
<Investmentaccount object @ 0x1090c9bd0>
.. note::
Attributes on accounts very depending on account type. See `account reference
in the Intuit documentation <https://developer.intuit.com/docs/0020_customeraccountdata/customer_account_data_api/0020_api_documentation/0035_getaccount>`_.
Also note that when the XML gets objectified XML attributes like ``accountId`` get converted
to ``account_id``
"""
return self._make_request('logins/%s/accounts' % login_id)
def get_account(self, account_id):
"""Get the details of an account
:param integer account_id: the id of an account retrieved from :meth:`get_login_accounts`
or :meth:`get_customer_accounts`.
:returns: :class:`AggcatResponse`
::
>>> r = client.get_account(400004540560)
<AggCatResponse 200>
>>> r.content
<Investmentaccount object @ 0x1091cfc10>
>>> r.content.account_id
'400004540560'
.. note::
Attributes on accounts very depending on type. See `account reference
in the Intuit documentation <https://developer.intuit.com/docs/0020_customeraccountdata/customer_account_data_api/0020_api_documentation/0035_getaccount>`_.
Also note that when the XML gets objectified XML attributes like ``accountId`` get converted
to ``account_id``
"""
return self._make_request('accounts/%s' % account_id)
def get_account_transactions(self, account_id, start_date, end_date=None):
"""Get specific account transactions from a date range
:param integer account_id: the id of an account retrieved from :meth:`get_login_accounts`
or :meth:`get_customer_accounts`.
:param string start_date: the date you want the transactions to start in the format YYYY-MM-DD
:param string end_date: (optional) the date you want the transactions to end in the format YYYY-MM-DD
:returns: :class:`AggcatResponse`
::
>>> r = ac.get_account_transactions(400004540560, '2013-08-10', '2013-08-12')
>>> r
<AggCatResponse 200>
>>> r.content
<Transactionlist object [<Investmenttransaction object @ 0x10a380710>,<Investmenttransaction object @ 0x10a380750> ...] @ 0x109ce8a50>
>>> len(r.content)
3
>>> for t in r.content:
print t.id, t.description, t.total_amount, t.currency_type
400189790351 IRA debit 222 -8.1 USD
400190413930 IRA debit 224 -8.12 USD
400190413931 IRA credit 223 8.11 USD
.. note::
Attributes on transactions very depending on transaction type. See `transaction reference
in the Intuit documentation <https://developer.intuit.com/docs/0020_customeraccountdata/customer_account_data_api/0020_api_documentation/0030_getaccounttransactions>`_.
When the XML gets objectified XML attributes like ``totalAmount`` get converted
to ``total_amount``. This endpoint is not ordered by the date of transaction.
**Pending** transactions are unstable, the transaction id will change once the it has
posted so it is difficult to correlate a once pending transaction with its posted one.
"""
query = {
'txnStartDate': start_date,
}
# add the end date if provided
if end_date:
query.update({
'txnEndDate': end_date
})
return self._make_request(
'accounts/%s/transactions' % account_id,
query=query
)
def get_investment_positions(self, account_id):
"""Get the investment positions of an account
:param integer account_id: the id of an account retrieved from :meth:`get_login_accounts`
or :meth:`get_customer_accounts`.
:returns: :class:`AggcatResponse`
::
>>> r = client.get_investment_positions(400004540560)
<AggCatResponse 200>
>>> r.content
<Investmentpositions object @ 0x10a25ebd0>
.. note::
This endpoint has needs to be tested with an account that
actually returns data here
"""
return self._make_request('accounts/%s/positions' % account_id)
def update_account_type(self, account_id, account_name, account_type):
"""Update an account's type
:param integer account_id: the id of an account retrieved from :meth:`get_login_accounts`
or :meth:`get_customer_accounts`.
:param string account_name: See possible values for account names and types below
:param string account_type: See possible values for account names and types below
:returns: ``None``
::
>>> client.update_account_type(400004540560, 'investment', '403b')
**Possible values for account names and types**
+------------+---------------------------------------------------------------------------------------------+
| Name | Types |
+============+=============================================================================================+
| banking | checking, savings, moneymrkt, cd, cashmanagement, overdraft |
+------------+---------------------------------------------------------------------------------------------+
| credit | creditcard, lineofcredit, other |
+------------+---------------------------------------------------------------------------------------------+
| loan | loan, auto, commercial, constr, consumer, homeequity, military, mortgage, smb, student |
+------------+---------------------------------------------------------------------------------------------+
| investment | taxable, 401k, brokerage, ira, 403b, keogh, trust, tda, simple, normal, sarsep, ugma, other |
+------------+---------------------------------------------------------------------------------------------+
"""
body = AccountType(account_name, account_type).to_xml()
return self._make_request(
'accounts/%s' % account_id,
'PUT',
body
)
def update_institution_login(self, institution_id, login_id, refresh=True, **credentials):
"""Update an instiutions login information
:param integer institution_id: The institution's id. See :ref:`search_for_institution`.
:param string login_id: Login id of the instiution. This can be retrieved from an account.
:param boolean refresh: (optional) Setting this to ``False`` will only update the credentials
in intuit and will not query against the instituion. This might cause issues because some
institutions require you to re-answer the challenge questions. Default: ``True``
:param dict credentials: New credentials. See :ref:`getting_credential_fields`.
:returns: :class:`None` if update is valid or :class:`AggcatResponse` if challenge occurs.
If a challenge response does not occur::
>>> r = ac.update_institution_login(100000, 83850162, **{
'Banking Userid': 'direct',
'Banking Password': '<PASSWORD>'
})
>>> type(r)
NoneType
If a challenge response occurs::
>>> r = ac.update_institution_login(100000, 83850162, **{
'Banking Userid': 'tfa_choice',
'Banking Password': '<PASSWORD>'
})
>>> r
<AggCatResponse 401>
>>> r.content
<Challenges object [<Challenge object @ 0x10d12d5d0>,<Challenge object @ 0x10d12d110> ...] @ 0x10d0ffc50>
Notice that ``r.content`` is now a :class:`Challenges` object. Listing the challenges will | |
<reponame>Rademacher/ONIX
from .functions import *
import ast
import re
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import os
import onix.data as d
#import pylab
def read_nuclide_reac_rank(nuclide, step, path):
file = open(path, 'r')
lines = file.readlines()
zamid = name_to_zamid(nuclide)
search = 'nuclide'
for i in range(0,len(lines)):
l = lines[i]
if l == ' ==={}({}) ===\n'.format(nuclide, zamid):
search = 'step'
elif l == 'STEP {}\n'.format(step) and search == 'step':
data = lines[i+2]
break
data = ast.literal_eval(data)
destruction = {}
dest_total = 0
for tuples in data:
if '-' not in tuples[0]:
if tuples[1] == 0.0:
continue
dest_total += tuples[1]
for tuples in data:
if '-' not in tuples[0]:
if tuples[1] == 0.0:
continue
destruction[tuples[0]] = [tuples[1], tuples[1]/dest_total] # val and percent
production = {}
prod_total = 0
for tuples in data:
if '-' in tuples[0]:
reaction_val = tuples[1]
if reaction_val == 0.0:
continue
prod_total += reaction_val
for tuples in data:
if '-' in tuples[0]:
parent = tuples[0].split()[0]
reaction = tuples[0].split()[1]
reaction_val = tuples[1]
if reaction_val == 0.0:
continue
production[parent] = [reaction, reaction_val, reaction_val/prod_total]
return [destruction, production]
def plot_bucell_nuclide_network(nuclide, step, path, cell, threshold):
path_to_rank = path +'/output_summary/cell_{}_reacs_rank'.format(cell)
file = open(path_to_rank, 'r')
lines = file.readlines()
zamid = name_to_zamid(nuclide)
search = 'nuclide'
for i in range(0,len(lines)):
l = lines[i]
if l == ' ==={}({}) ===\n'.format(nuclide, zamid):
search = 'step'
elif l == 'STEP {}\n'.format(step) and search == 'step':
data = lines[i+2]
break
data = ast.literal_eval(data)
destruction = {}
dest_total = 0
for tuples in data:
if '-' not in tuples[0]:
# if tuples[1] == 0.0:
# continue
if tuples[1] < threshold:
continue
dest_total += tuples[1]
for tuples in data:
if '-' not in tuples[0]:
# if tuples[1] == 0.0:
# continue
if tuples[1] < threshold:
continue
destruction[tuples[0]] = [tuples[1], tuples[1]/dest_total] # val and percent
production = {}
prod_total = 0
for tuples in data:
if '-' in tuples[0]:
reaction_val = tuples[1]
# if reaction_val == 0.0:
# continue
if reaction_val < threshold:
continue
prod_total += reaction_val
for tuples in data:
if '-' in tuples[0]:
parent = tuples[0].split()[0]
reaction = tuples[0].split()[1]
reaction_val = tuples[1]
# if reaction_val == 0.0:
# continue
if reaction_val < threshold:
continue
production[parent] = [reaction, reaction_val, reaction_val/prod_total]
G = nx.MultiDiGraph()
for parent in production:
label = '{}\n{:.2E}[{:.2%}]'.format(production[parent][0], production[parent][1], production[parent][2])
G.add_edge(parent, nuclide, label = label, length = 10)
for edge in destruction:
G.add_edge(nuclide, edge, label = '{:.2E}[{:.2%}]'.format(destruction[edge][0],destruction[edge][1] ), length = 10)
# Get target nuclide index
index = 0
for node in G.nodes():
if node == nuclide:
break
index += 1
edges = G.edges()
edge_labels = []
edge_labels=dict([((u,v,),d['label'])
for u,v,d in G.edges(data=True)])
node_color = []
for node in G.nodes():
if node == nuclide:
node_color.append('mediumaquamarine')
if node in production:
node_color.append('lightskyblue')
if node in destruction:
node_color.append('darksalmon')
edges = G.edges()
# edge_weights = [G[u][v]['weight'] for u,v in edges]
# red_edges = [('C','D'),('D','A')]
# edge_colors = ['black' if not edge in red_edges else 'red' for edge in G.edges()]
pos=nx.circular_layout(G, scale = 2)
pos[nuclide] = np.array([0, 0])
nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels)
nx.draw_networkx_labels(G,pos)
nx.draw_networkx_edges(G,pos, edges = edges)
nx.draw(G,pos, node_size=4000, node_color = node_color, fontsize = 6)
plt.show()
def plot_nuclide_dens_from_passport(bucell, nuclide):
sequence = bucell.sequence
time_seq = sequence.time_seq.copy()
dens_seq = nuclide.dens_seq
time_seq = [i/(24*3600) for i in time_seq]# time_seq is in seconds
plt.figure(1)
plt.plot(time_seq, dens_seq, color = 'orange', marker = 'o')
plt.xlabel('Time [day]')
plt.ylabel('Density [atm/cm3]')
plt.grid()
plt.title('{} {} density evolution'.format(bucell.name, nuclide.name))
plt.show()
def plot_nuclide_dens(bucell, nuclide):
path = os.getcwd() +'/{}_dens'.format(bucell)
time_seq = read_time_seq(path)
dens_seq = read_dens(nuclide, path)
plt.figure(1)
plt.plot(time_seq, dens_seq, color = 'orange', marker = 'o')
plt.xlabel('Time [day]')
plt.ylabel('Density [atm/cm3]')
plt.grid()
plt.title('{} {} density evolution'.format(bucell, nuclide))
plt.show()
def plot_nuclide_dens_from_path(bucell, nuclide, path_to_simulation):
path = path_to_simulation + '/output_summary/{}_dens'.format(bucell)
time_seq = read_time_seq(path)
dens_seq = read_dens(nuclide, path)
plt.figure(1)
plt.plot(time_seq, dens_seq, color = 'orange', marker = 'o')
plt.xlabel('Time [day]')
plt.ylabel('Density [atm/cm3]')
plt.grid()
plt.title('{} {} density evolution'.format(bucell, nuclide))
plt.show()
def plot_xs_time_evolution(bucell, nuclide, xs_name):
path = os.getcwd() +'/{}_xs_lib'.format(bucell)
time_seq = read_time_seq(path)
xs_seq = read_xs(nuclide, xs_name, path)
marker_list = ['x', '+', 'o', '*', '^', 's']
color_list = ['r', 'b', 'g', 'k', 'brown', 'orange']
plt.figure(1)
plt.plot(time_seq, xs_seq, color = 'teal', marker = 'o')
plt.xlabel('Time in Days')
plt.ylabel('Eff. XS in barn')
plt.legend()
plt.grid()
plt.title('{} {} effective cross sections evolution'.format(bucell, nuclide))
plt.show()
def plot_xs_bu_evolution(bucell_list, nuclide, xs_name):
index = 0
for bucell in bucell_list:
path = os.getcwd() +'/{}_xs_lib'.format(bucell)
xs_seq = read_xs_seq(nuclide, xs_name, path)
marker_list = ['x', '+', 'o', '*', '^', 's']
color_list = ['r', 'b', 'g', 'k', 'brown', 'orange']
plt.figure(1)
plt.plot(bu_seq, xs_seq, color = color_list[index], marker = marker_list[index], label = bucell)
index += 1
bu_seq = read_bu_seq(path)
plt.xlabel('BU in MWd/kg')
plt.ylabel('Eff. XS in barn')
plt.legend()
plt.grid()
plt.title('{} {} effective cross sections evolution'.format(nuclide, xs_name))
plt.show()
def plot_xs_time_evolution_from_path(bucell, nuclide, xs_name, path):
time_seq = read_time_seq()
xs_seq = read_xs_seq(nuclide, xs_name, path)
marker_list = ['x', '+', 'o', '*', '^', 's']
color_list = ['r', 'b', 'g', 'k', 'brown', 'orange']
plt.figure(1)
plt.plot(time_seq, xs_seq, color = 'teal', marker = 'o')
plt.xlabel('Time in days')
plt.ylabel('Eff. XS in barn')
plt.legend()
plt.grid()
plt.title('{} {} effective cross sections evolution'.format(bucell, nuclide))
plt.show()
def plot_xs_bu_evolution_from_path(bucell_list, nuclide, xs_name, path):
index = 0
for bucell in bucell_list:
path_xs = path +'/output_summary/{}_xs_lib'.format(bucell)
xs_seq = read_xs_seq(nuclide, xs_name, path, bucell)
marker_list = ['x', '+', 'o', '*', '^', 's']
color_list = ['r', 'b', 'g', 'k', 'brown', 'orange']
plt.figure(1)
bu_seq = read_bu_seq(path_xs)
plt.plot(bu_seq, xs_seq, color = color_list[index], marker = marker_list[index], label = bucell)
index += 1
plt.xlabel('BU in MWd/kg')
plt.ylabel('Eff. XS in barn')
plt.legend()
plt.grid()
plt.title('{} {} effective cross sections evolution'.format(nuclide, xs_name))
plt.show()
# Compare xs evolution for the same nuclide, for various xs for different runs
def compare_xs_bu_evolution_from_path(bucell, nuclide, xs_name_list, path_list, name_list):
bu_seq_list = []
xs_seq_list = []
for path in path_list:
bu_seq_list.append(read_bu_seq(path))
xs_seq_list.append([])
for xs in xs_name_list:
xs_seq_list[-1].append(read_xs_seq(nuclide, xs, path))
marker_list = ['x', '+', 'o', '*', '^', 's']
color_list = ['r', 'b', 'g', 'k', 'brown', 'orange']
# plt.figure(1)
# for i in range(len(path_list)):
# for j in range(len(xs_name_list)):
# plt.plot(bu_seq_list[i], xs_seq_list[i][j], label = '{} {}'.format(name_list[i], xs_name_list[j]))
# Three subplots sharing both x/y axes
f, ax_tuple = plt.subplots(len(xs_name_list), sharex=True)
ax_tuple[0].set_title('{} {} {} effective cross sections evolution'.format(bucell, nuclide, xs_name_list))
for i in range(len(xs_name_list)):
for j in range(len(path_list)):
ax_tuple[i].plot(bu_seq_list[j], xs_seq_list[j][i], label = name_list[j])
ax_tuple[i].set_ylabel('{} Eff. XS [barn]'.format(xs_name_list[i]))
ax_tuple[i].grid()
ax_tuple[i].set_xlabel('BU [MWd/kg]')
# Fine-tune figure; make subplots close to each other and hide x ticks for
# all but bottom plot.
f.subplots_adjust(hspace=0)
plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False)
plt.legend()
plt.show()
def plot_kinf_from_path(path_to_simulation):
path = path_to_simulation + '/output_summary/kinf'
time_seq = read_time_seq(path)
kinf_seq = read_kinf_seq(path)
plt.figure(1)
plt.plot(time_seq, kinf_seq)
plt.xlabel('Time [day]')
plt.ylabel('kinf')
plt.grid()
plt.title('kinf evolution')
plt.show()
def plot_flux(bucell):
path = os.getcwd() +'/{}_xs_lib'.format(bucell)
time_seq = read_time_seq(path)
flux_seq = read_flux(path)
plt.figure(1)
plt.step(time_seq, flux_seq, where = 'pre', color = 'blue')
plt.xlabel('Time [day]')
plt.ylabel('Flux [neutron/cm3.s-1]')
plt.grid()
plt.title('{} neutron flux evolution'.format(bucell))
plt.show()
def plot_flux_from_path(bucell, path_to_simulation):
path = path_to_simulation + '/output_summary/{}_dens'.format(bucell)
time_seq = read_time_seq(path)
flux_seq = read_flux(path)
plt.figure(1)
plt.step(time_seq, flux_seq, where = 'pre', color = 'blue')
plt.xlabel('Time [day]')
plt.ylabel('Flux [neutron/cm3.s-1]')
plt.grid()
plt.title('{} neutron flux evolution'.format(bucell))
plt.show()
def plot_flux_spectrum_bu_evolution_from_path(bucell_list, steps_list, path):
bucell_index = 0
for bucell in bucell_list:
path_flux_spectrum = path +'/{}_flux_spectrum'.format(bucell)
flux_spectrum_list = read_flux_spectrum(path_flux_spectrum, steps_list)
energy_mid_points = read_energy_mid_points(path_flux_spectrum)
marker_list = ['x', '+', 'o', '*', '^', 's']
color_list = ['r', 'b', 'g', 'k', 'brown', 'orange']
plt.figure(bucell_index)
index = 0
for flux_spectrum in flux_spectrum_list:
plt.plot(energy_mid_points, flux_spectrum, color = color_list[index], marker = marker_list[index], label=steps_list[index])
index += 1
plt.xlabel('eV')
plt.ylabel('Neutron spectrum')
plt.legend()
plt.grid()
plt.title('neutron spectrum in cell {} for steps {} '.format(bucell, steps_list))
plt.show()
def plot_lethargy_spectrum_bu_evolution_from_path(bucell_list, steps_list, path):
bucell_index = 0
for bucell in bucell_list:
path_flux_spectrum = path +'/output_summary/{}_flux_spectrum'.format(bucell)
flux_spectrum_list = read_flux_spectrum(path_flux_spectrum, steps_list)
energy_mid_points = read_energy_mid_points(path_flux_spectrum)
energy_bin_length = read_energy_bin_length(path_flux_spectrum)
marker_list = ['x', '+', 'o', '*', '^', 's']
color_list = ['r', 'b', 'g', 'k', 'brown', 'orange']
plt.figure(bucell_index)
index = 0
for flux_spectrum in flux_spectrum_list:
lethargy_spectrum = [x*y/z for x,y,z in zip(flux_spectrum, energy_mid_points, energy_bin_length)]
plt.plot(energy_mid_points, lethargy_spectrum, color = color_list[index], marker = marker_list[index], label=steps_list[index])
index += 1
plt.xlabel('BU in MWd/kg')
plt.ylabel('Eff. XS in barn')
plt.legend()
plt.xscale('log')
plt.yscale('log')
plt.grid()
plt.title('neutron spectrum in cell {} for steps {} '.format(bucell, steps_list))
bucell_index += 1
plt.show()
def plot_xs_dens_flux(bucell, xs_nuclide, xs_name, dens_nuclide, xs_path, dens_path):
time_subseq = read_time_seq(dens_path)
time_seq = read_time_seq(xs_path)
xs_seq = read_xs_seq(xs_nuclide, xs_name, xs_path)
dens_subseq = read_dens(dens_nuclide, dens_path)
flux_subseq = read_flux(dens_path)
# Three subplots sharing both x/y axes
f, (ax1, ax2, ax3) = plt.subplots(3, sharex=True)
ax1.plot(time_seq, xs_seq, color = 'teal', marker = 'o')
ax1.set_ylabel('{}\n{} Eff. XS [barn]'.format(xs_nuclide, xs_name))
ax1.set_title('{} cell'.format(bucell))
ax1.grid()
ax2.plot(time_subseq, dens_subseq, color = 'orange', marker = 'o')
ax2.set_ylabel('{}\nDensity [atm/barn-cm]'.format(dens_nuclide))
ax2.grid()
ax3.step(time_subseq, flux_subseq, color = 'blue')
ax3.set_ylabel('Neutron flux [neutron/cm2-s]')
ax3.set_xlabel('Time [day]')
ax3.grid()
# Fine-tune figure; make subplots close to each other and hide x ticks for
# all but bottom plot.
f.subplots_adjust(hspace=0)
plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False)
plt.show()
def read_time_seq(path):
time_file = open(path, 'r')
lines = time_file.readlines()
# Find and store time
for line in lines:
if line != '\n':
if line.split()[0] == 'TIME':
time_seq = [float(x) for x in line.split()[1:]]
break
return time_seq
def get_step_time_length_seq(path):
time_seq = read_time_seq(path)
if time_seq[0] == 0:
step_time_length = [x-y for x,y in zip(time_seq[1:], time_seq[:-1])]
else:
step_time_length = [time_seq[0]] + [x-y for x,y in zip(time_seq[1:], time_seq[:-1])]
return step_time_length
def read_bu_seq(path):
bu_file = open(path, 'r')
lines = bu_file.readlines()
# Find and store time
for line in lines:
if line != '\n':
if line.split()[0] == 'SYSTEM-BU':
bu_seq = [float(x) for x in line.split()[1:]]
break
return bu_seq
def read_kinf_seq(path):
kinf_file = open(path, 'r')
lines = kinf_file.readlines()
for line in lines:
if line != '\n':
if line.split()[0] == 'K-INF':
kinf_seq = [float(x) for x in line.split()[1:]]
break
return kinf_seq
def read_flux(path):
flux_file = open(path, 'r')
lines = flux_file.readlines()
for line in lines:
if line != '\n':
if line.split()[0] == 'FLUX':
flux_seq = [float(x) for x in line.split()[1:]]
break
# Add an initial 0 for the flux to have same len for flux_seq and time_seq
flux_seq = [0] + flux_seq
return flux_seq
def read_flux_subseq(path):
flux_file = open(path, 'r')
lines = flux_file.readlines()
for line in lines:
if line != '\n':
if line.split()[0] == 'FLUX':
flux_seq = [float(x) for x in line.split()[1:]]
break
return flux_seq
def get_fluence_seq(path, cell):
dens_file = path +'/output_summary/{}_dens'.format(cell)
flux_seq = read_flux(dens_file)
time_seq = read_time_seq(dens_file)
#Reminder: flux starts with 0
fluence_seq = [0]
pre_time = 0
for i in range(1, len(time_seq)):
time = time_seq[i]
flux = flux_seq[i]
time_int = (time-pre_time)*24*3600
fluence_seq.append(time_int*flux + fluence_seq[i-1])
pre_time = time
return fluence_seq
def get_fluence_subseq(path, cell):
subdens_file = path +'/{}_subdens'.format(cell)
flux_subseq = read_flux(subdens_file)
time_subseq = read_time_seq(subdens_file)
#Reminder: flux starts with 0
fluence_subseq = [0]
pre_time = 0
for i in range(1, len(time_subseq)):
time = time_subseq[i]
flux = flux_subseq[i]
time_int = (time-pre_time)*24*3600
fluence_subseq.append(time_int*flux + fluence_subseq[i-1])
pre_time = time
return fluence_subseq
# This method build the fluence sequence until a final time
# Warning this function is only valid for non-fissile material as the flux
# is the same within each step
def get_fluence_seq_until_time(path, cell, final_time):
final_step = find_step_from_time(path, cell, final_time)
extra_fluence = get_extra_fluence_from_time(path, cell, final_time)
fluence_seq = get_fluence_seq(path, cell)
fluence_seq_until_time | |
import itertools
import os
import sys
import threading
import getopt
import time
from threading import Timer
from subprocess import Popen, PIPE
class Setting:
'''
General setting class
rootpath is the directory where the .pv and .pvl files put
'''
rootpath = os.getcwd() + "/"
reg_set_type_row = 4 #indicate which row to insert "let atype = xxx"
reg_insert_row = 23 #indicate which row to insert malicious entities
auth_set_type_row = 7
auth_insert_row = 32
regpath = rootpath + "reg.pv"
authpath = rootpath + "auth.pv"
if not os.path.exists(rootpath + "LOG/"):
os.makedirs(rootpath + "LOG/")
logpath1 = rootpath + "LOG/" + "reg.log"
logpath2 = rootpath + "LOG/" + "auth_1b_em.log"
logpath3 = rootpath + "LOG/" + "auth_1b_st.log"
logpath4 = rootpath + "LOG/" + "auth_1r_em.log"
logpath5 = rootpath + "LOG/" + "auth_1r_st.log"
logpath6 = rootpath + "LOG/" + "auth_2b.log"
logpath7 = rootpath + "LOG/" + "auth_2r.log"
libpath = rootpath + "UAF.pvl"
resultpath = rootpath + "result/"
analyze_flag = "full" #full to analze all scenarios, simple to analyze without fields leakage.
@classmethod
def initiate(cls): # judge if the setting is ready for running
if not os.path.exists(cls.libpath):
print("FIDO.pvl does not exist")
sys.exit(1)
if not os.path.exists(cls.regpath):
print("reg.pv does not exist")
sys.exit(1)
if not os.path.exists(cls.authpath):
print("auth.pv does not exist")
sys.exit(1)
class Type: #indicate the type of the authenticator
def __init__(self,name,write):
self.name = name #for example "autr_1b“
self.write = write # indicate how to write the type in .pv file, for example "let atype = autr_1b"
class Query: # indicate a specific query
def __init__(self,name,write):
self.name = name #for example, the confidentiality of ak: S-ak
self.write = write # indicate how to write the query in .pv file
class Fields: # indicate a specific combination of compromised fields
def __init__(self, fields): # initiate by a list
self.nums = len(fields) # number of the malicious fields
self.write = "" # how to write those fields in .pv file
self.name = "fields-" + str(self.nums) # give it a name to generate the output files
for item in fields:
self.write += item
self.fields = fields
class Entities: # indicate a specific combination of malicious entities
def __init__(self, entities, row_numbers): # initiate by a list and which rows in the list to add
self.nums = len(entities) # how many entities
self.write = "" # how to write the malicious entities in .pv file
if self.nums == 0:
self.name = "mali-" + str(self.nums)
else:
self.name = "mali-" + str(self.nums) + " "
for i in row_numbers:
self.name += "," + str(i)
for item in entities:
self.write += item
self.entities = entities
self.row_numbers = row_numbers
class All_types:
'''
a parant class for all possible authenticator types
use the specific subclass when analyzing
'''
def __init__(self):
self.all_types = []
def size(self):
return len(self.all_types)
def get(self,i):
return self.all_types[i]
class Reg_types(All_types): # Reg types
def __init__(self):
All_types.__init__(self)
self.all_types.append(Type("autr_1b", "let atype = autr_1b in\n"))
self.all_types.append(Type("autr_1r", "let atype = autr_1r in\n"))
self.all_types.append(Type("autr_2b", "let atype = autr_2b in\nlet ltype = stepup in \n"))
self.all_types.append(Type("autr_2r", "let atype = autr_2r in\nlet ltype = stepup in \n"))
class Auth_1b_em_types(All_types): # types of 1b login phase
def __init__(self):
All_types.__init__(self)
self.all_types.append(Type("autr_1b_em","let atype = autr_1b in\nlet ltype = empty in \n"))
class Auth_1b_st_types(All_types):# types of 1b step-up phase
def __init__(self):
All_types.__init__(self)
self.all_types.append(Type("autr_1b_st","let atype = autr_1b in\nlet ltype = stepup in \n"))
class Auth_1r_em_types(All_types): # types of 1r login phase
def __init__(self):
All_types.__init__(self)
self.all_types.append(Type("autr_1r_em","let atype = autr_1r in\nlet ltype = empty in \n"))
class Auth_1r_st_types(All_types): # types of 1r step-up phase
def __init__(self):
All_types.__init__(self)
self.all_types.append(Type("autr_1r_st","let atype = autr_1r in\nlet ltype = stepup in \n"))
class Auth_2b_types(All_types): # types of 2b step-up phase
def __init__(self):
All_types.__init__(self)
self.all_types.append(Type("autr_2b", "let atype = autr_2b in\nlet ltype = stepup in \n"))
class Auth_2r_types(All_types): # types of 2r step-up phase
def __init__(self):
All_types.__init__(self)
self.all_types.append(Type("autr_2r", "let atype = autr_2r in\nlet ltype = stepup in \n"))
class All_queries:
'''
a parant class for all queries
this class indicate the queries for all types of authenticator and all phases(reg/auth)
use the specific subclass when analyzing
you can add queries as you wish
'''
def __init__(self):
self.all_queries = []
self.all_queries.append(Query("S-ak", "query secret testak.\n"))
self.all_queries.append(Query("S-cntr","query secret testcntr.\n"))
self.all_queries.append(Query("S-skau", "query secret testskAU.\n"))
self.all_queries.append(Query("S-kid", "query secret testkid.\n"))
def size(self):
return len(self.all_queries)
def get(self,i):
return self.all_queries[i]
class Reg_queries(All_queries): # reg queries
def __init__(self):
All_queries.__init__(self)
self.all_queries.append(Query("S-skat", "query secret skAT.\n"))
self.all_queries.append(Query("Rauth","query u:Uname,a:Appid,aa:AAID,kid:KeyID; inj-event(RP_success_reg(u,a,aa,kid)) ==> (inj-event(Autr_verify_reg(u,a,aa,kid))==> inj-event(UA_init_reg(u,a))).\n"))
class Auth_stepup_queries(All_queries): # query of step-up phase
def __init__(self):
All_queries.__init__(self)
self.all_queries.append(Query("S-tr","query secret testtr.\n"))
self.all_queries.append(Query("Aauth-tr", "query tr:Tr; inj-event(RP_success_tr(tr)) ==> (inj-event(Autr_verify_tr(tr)) ==> inj-event(UA_launch_auth_tr(tr))).\n"))
class Auth_1b_em_queries(All_queries): # query of 1b login phase
def __init__(self):
All_queries.__init__(self)
self.all_queries.append(Query("Aauth-1br", "query u:Uname,a:Appid,aa:AAID,kid:KeyID; inj-event(RP_success_auth(u,a,aa,kid)) ==> (inj-event(Autr_verify_auth_1br(u,a,aa,kid)) ==> inj-event(UA_launch_auth(u,a))).\n"))
class Auth_1b_st_queries(Auth_stepup_queries): # query of 1b step-up phase
def __init__(self):
Auth_stepup_queries.__init__(self)
self.all_queries.append(Query("Aauth-1br", "query u:Uname,a:Appid,aa:AAID,kid:KeyID; inj-event(RP_success_auth(u,a,aa,kid)) ==> (inj-event(Autr_verify_auth_1br(u,a,aa,kid)) ==> inj-event(UA_launch_auth(u,a))).\n"))
class Auth_2b_queries(Auth_stepup_queries): # query of 2b step-up phase
def __init__(self):
Auth_stepup_queries.__init__(self)
self.all_queries.append(Query("Aauth-2br", "query u:Uname,a:Appid,aa:AAID,kid:KeyID; inj-event(RP_success_auth(u,a,aa,kid)) ==> (inj-event(Autr_verify_auth_2br(a,aa,kid)) ==> inj-event(UA_launch_auth(u,a))).\n"))
class Auth_1r_em_queries(All_queries): # query of 1r login phase
def __init__(self):
All_queries.__init__(self)
self.all_queries.append(Query("Aauth-1br", "query u:Uname,a:Appid,aa:AAID,kid:KeyID; inj-event(RP_success_auth(u,a,aa,kid)) ==> (inj-event(Autr_verify_auth_1br(u,a,aa,kid)) ==> inj-event(UA_launch_auth(u,a))).\n"))
class Auth_1r_st_queries(Auth_stepup_queries): # query of 1r step-up phase
def __init__(self):
Auth_stepup_queries.__init__(self)
self.all_queries.append(Query("Aauth-1br", "query u:Uname,a:Appid,aa:AAID,kid:KeyID; inj-event(RP_success_auth(u,a,aa,kid)) ==> (inj-event(Autr_verify_auth_1br(u,a,aa,kid)) ==> inj-event(UA_launch_auth(u,a))).\n"))
class Auth_2r_queries(Auth_stepup_queries): # query of 2r step-up phase
def __init__(self):
Auth_stepup_queries.__init__(self)
self.all_queries.append(Query("Aauth-2br", "query u:Uname,a:Appid,aa:AAID,kid:KeyID; inj-event(RP_success_auth(u,a,aa,kid)) ==> (inj-event(Autr_verify_auth_2br(a,aa,kid)) ==> inj-event(UA_launch_auth(u,a))).\n"))
class All_entities:
'''
a parant class for all possible combinations of malicous entities
you can just write all the possible malicous in subclass for each phase(reg/auth)
this parant class will generate all the combinations.
version2 is a reduce plan
'''
def __init__(self):
self.all_entities = []
def get_all_scenes(self): # a scheme to get all combinations of the entities
self.entities = []
for delnum in range(len(self.all_entities) + 1):
for row_numbers in itertools.combinations(range(len(self.all_entities)), delnum):
temp = []
for i in row_numbers:
temp.append(self.all_entities[i])
self.entities.append(Entities(temp,row_numbers))
def get_all_scenes_version2(self): # another scheme to get less combinations of the entities
# the rule is to continually add entities which require more ability of the attacker
# we assume if there is a malicious UC, then there is must a malicious UA.
self.entities = []
for i in range(len(self.all_entities) + 1):
temp_combination = []
row_numbers = []
for j in range(i):
temp_combination.append(self.all_entities[j])
self.entities.append(Entities(temp_combination))
def size(self):
return len(self.entities)
def get(self,i):
return self.entities[i]
class Reg_entities(All_entities):
'''
a class record all possible malicious entities
use this class, we generate all possible combinations
'''
def __init__(self):
All_entities.__init__(self)
self.all_entities = []
self.all_entities.append("RegUA(https, c, uname,appid,password)|\n")
self.all_entities.append("RegUC(c, MC, fakefacetid)|\n")
self.all_entities.append("RegUC(CU, c, facetid)|\n")
self.all_entities.append("RegUC(c, c, fakefacetid)|\n")
self.all_entities.append("RegASM(c, AM, token, fakecallerid, atype)|\n")
self.all_entities.append("RegASM(MC, c, token, callerid, atype)|\n")
self.all_entities.append("RegASM(c, c, token, fakecallerid, atype)|\n")
self.all_entities.append("RegAutr(c, aaid, skAT, wrapkey, atype)|\n")
self.get_all_scenes()
class Reg_entities_version2(All_entities):
'''
another way to insert malicious entities
in this way, we only consider malicious scenario but not consider who to communicate in this way.
for example, RegUA | RegASM means there is a malicious UC.
'''
def __init__(self):
All_entities.__init__(self)
self.all_entities = []
self.all_entities.append("RegUC(c, MC, fakefacetid)| (*malicious-UA*)\n")
self.all_entities.append("RegUA(https, c, uname,appid,password)| RegASM(c, AM, token, fakecallerid, atype)| (*malicious-UC*)\n")
self.all_entities.append("RegUC(CU, c, facetid)| RegAutr(c, aaid, skAT, wrapkey, atype)| (*malicious-ASM*)\n")
self.all_entities.append("RegASM(MC, c, token, callerid, atype)| (*-malicious-Autr*)\n")
self.get_all_scenes()
class Auth_entities(All_entities):
def __init__(self):
All_entities.__init__(self)
self.all_entities = []
self.all_entities.append("AuthUA(https, c, uname, ltype)|\n")
self.all_entities.append("AuthUC(c, MC, fakefacetid, ltype)|\n")
self.all_entities.append("AuthUC(CU, c, facetid, ltype)|\n")
self.all_entities.append("AuthUC(c, c, fakefacetid, ltype)|\n")
self.all_entities.append("AuthASM(c,AM,token,fakecallerid,atype,ltype)|\n")
self.all_entities.append("AuthASM(MC,c,token,callerid,atype,ltype)|\n")
self.all_entities.append("AuthASM(c,c,token,fakecallerid,atype,ltype)|\n")
self.all_entities.append("AuthAutr(c,aaid,wrapkey,cntr,tr,atype,ltype)| \n")
self.get_all_scenes()
class Auth_entities_version2(All_entities):
def __init__(self):
All_entities.__init__(self)
self.all_entities = []
self.all_entities.append("AuthUC(c, MC, fakefacetid, ltype)| (*malicious-UA*)\n")
self.all_entities.append("AuthUA(https, c, uname, ltype)| AuthASM(c,AM,token,fakecallerid,atype,ltype)| (*malicious-UC*)\n")
self.all_entities.append("AuthUC(CU, c, facetid, ltype)| AuthAutr(c,aaid,wrapkey,cntr,tr,atype,ltype)| (*malicious-ASM*)\n")
self.all_entities.append("AuthASM(MC,c,token,callerid,atype,ltype)| (*malicious-Autr*)\n")
self.get_all_scenes()
class All_fields:
'''
A parent class for all possible combinations of the compromised fields
based on the command line parameter, it will choose the "full" version
to analyze all compromise scenarios of the fields, or the "simple" version
which do not consider the compromise of the fields.
'''
def __init__(self):
self.all_fields = []
self.all_fields.append("out(c,token);\n")
self.all_fields.append("out(c,wrapkey);\n")
def get_all_scenes(self):
if Setting.analyze_flag == "simple":
print("analyzing the scenarios where no fields are comprimised.")
self.fields = [Fields(["(* no fields being compromised *)\n"])]
else:
print("analyzing the full scenarios.")
self.fields = []
for delnum in range(len(self.all_fields)+ 1) :
for pre in itertools.combinations(self.all_fields, delnum):
self.fields.append(Fields(pre))
def size(self):
return len(self.fields)
def get(self,i):
return self.fields[i]
class Reg_fields(All_fields): # particular case in Reg
def __init__(self):
All_fields.__init__(self)
self.all_fields.append("out(c,skAT);\n")
self.get_all_scenes()
class Auth_fields(All_fields): # paricular case in Auth
def __init__(self):
All_fields.__init__(self)
self.all_fields.append("out(c,skAU);\n")
self.all_fields.append("out(c,cntr);\n")
self.all_fields.append("out(c,kid);\n")
self.get_all_scenes()
class Case:
'''
| |
#!/usr/bin/env python
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License
# Version 1.1 (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.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
# License for the specific language governing rights and limitations
# under the License.
#
# The Original Code is Komodo code.
#
# The Initial Developer of the Original Code is ActiveState Software Inc.
# Portions created by ActiveState Software Inc are Copyright (C) 2000-2007
# ActiveState Software Inc. All Rights Reserved.
#
# Contributor(s):
# ActiveState Software Inc
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
"""Completion evaluation code for Python"""
from os.path import basename, dirname, join, exists, isdir
import operator
from codeintel2.common import *
from codeintel2.tree import TreeEvaluator
base_exception_class_completions = [
("class", "BaseException"),
("class", "Exception"),
("class", "StandardError"),
("class", "ArithmeticError"),
("class", "LookupError"),
("class", "EnvironmentError"),
("class", "AssertionError"),
("class", "AttributeError"),
("class", "EOFError"),
("class", "FloatingPointError"),
("class", "GeneratorExit"),
("class", "IOError"),
("class", "ImportError"),
("class", "IndexError"),
("class", "KeyError"),
("class", "KeyboardInterrupt"),
("class", "MemoryError"),
("class", "NameError"),
("class", "NotImplementedError"),
("class", "OSError"),
("class", "OverflowError"),
("class", "ReferenceError"),
("class", "RuntimeError"),
("class", "StopIteration"),
("class", "SyntaxError"),
("class", "SystemError"),
("class", "SystemExit"),
("class", "TypeError"),
("class", "UnboundLocalError"),
("class", "UnicodeError"),
("class", "UnicodeEncodeError"),
("class", "UnicodeDecodeError"),
("class", "UnicodeTranslateError"),
("class", "ValueError"),
("class", "VMSError"),
("class", "WindowsError"),
("class", "ZeroDivisionError"),
# Warning category exceptions.
("class", "Warning"),
("class", "UserWarning"),
("class", "DeprecationWarning"),
("class", "PendingDeprecationWarning"),
("class", "SyntaxWarning"),
("class", "RuntimeWarning"),
("class", "FutureWarning"),
("class", "ImportWarning"),
("class", "UnicodeWarning"),
]
class PythonImportLibGenerator(object):
"""A lazily loading lib generator.
To be used for Komodo's import lookup handling. This generator will return
libraries as needed, then when the given set of libraries runs out (i.e.
when there were no matches in the given libraries), to then try and find
other possible directories (libraries) that could offer a match."""
def __init__(self, mgr, lang, bufpath, imp_prefix, libs):
self.mgr = mgr
self.lang = lang
self.imp_prefix = imp_prefix
self.bufpath = bufpath
self.libs = libs
self.index = 0
def __iter__(self):
self.index = 0
return self
def __next__(self):
if self.index < len(self.libs):
# Return the regular libs.
try:
return self.libs[self.index]
finally:
self.index += 1
elif self.index == len(self.libs):
# Try to find a matching parent directory to use.
# print "Lazily loading the parent import libs: %r" %
# (self.imp_prefix, )
self.index += 1
lookuppath = dirname(self.bufpath)
parent_dirs_left = 5
import_name = self.imp_prefix[0]
if "." in import_name:
import_name = import_name.split(".", 1)[0]
while lookuppath and parent_dirs_left > 0:
# print ' exists: %r - %r' % (exists(join(lookuppath,
# import_name, "__init__.py")), join(lookuppath, import_name,
# "__init__.py"))
parent_dirs_left -= 1
if exists(join(lookuppath, import_name, "__init__.py")):
# Matching directory - return that as a library.
# print " adding parent dir lib: %r" % (lookuppath)
return self.mgr.db.get_lang_lib(self.lang, "parentdirlib",
[lookuppath])
lookuppath = dirname(lookuppath)
# No match found - we're done.
raise StopIteration
else:
raise StopIteration
class PythonTreeEvaluator(TreeEvaluator):
# Own copy of libs (that shadows the real self.buf.libs) - this is required
# in order to properly adjust the "reldirlib" libraries as they hit imports
# from different directories - i.e. to correctly deal with relative
# imports.
_libs = None
@property
def libs(self):
if self._libs is None:
self._libs = self.buf.libs
return self._libs
@libs.setter
def libs(self, value):
self._libs = value
def eval_cplns(self):
self.log_start()
if self.trg.type == 'available-exceptions':
# TODO: Should perform a lookup to determine all available exception
# classes.
return base_exception_class_completions
start_scoperef = self.get_start_scoperef()
self.info("start scope is %r", start_scoperef)
if self.trg.type == 'local-symbols':
return self._available_symbols(start_scoperef, self.expr)
# if self.trg.type == 'available-classes':
# return self._available_classes(start_scoperef,
# self.trg.extra["consumed"])
hit = self._hit_from_citdl(self.expr, start_scoperef)
return list(self._members_from_hit(hit))
def eval_calltips(self):
self.log_start()
start_scoperef = self.get_start_scoperef()
self.info("start scope is %r", start_scoperef)
hit = self._hit_from_citdl(self.expr, start_scoperef)
return [self._calltip_from_hit(hit)]
def eval_defns(self):
self.log_start()
start_scoperef = self.get_start_scoperef()
self.info("start scope is %r", start_scoperef)
hit = self._hit_from_citdl(self.expr, start_scoperef, defn_only=True)
return [self._defn_from_hit(hit)]
def _defn_from_hit(self, hit):
defn = TreeEvaluator._defn_from_hit(self, hit)
if not defn.path:
# Locate the module in the users own Python stdlib,
# bug 65296.
langintel = self.buf.langintel
info = langintel.python_info_from_env(self.buf.env)
ver, prefix, libdir, sitelibdir, sys_path = info
if libdir:
elem, (blob, lpath) = hit
path = join(libdir, blob.get("name"))
if exists(path + ".py"):
defn.path = path + ".py"
elif isdir(path) and exists(join(path, "__init__.py")):
defn.path = join(path, "__init__.py")
return defn
# def _available_classes(self, scoperef, consumed):
# matches = set()
# blob = scoperef[0] # XXX??
# for elem in blob:
# if elem.tag == 'scope' and elem.get('ilk') == 'class':
# matches.add(elem.get('name'))
# matches.difference_update(set(consumed))
# matches_list = sorted(list(matches))
# return [('class', m) for m in matches_list]
def _available_symbols(self, scoperef, expr):
cplns = []
found_names = set()
while scoperef:
elem = self._elem_from_scoperef(scoperef)
if not elem:
break
for child in elem:
if child.tag == "import":
name = child.get("alias") or child.get(
"symbol") or child.get("module")
# TODO: Deal with "*" imports.
else:
name = child.get("name", "")
if name.startswith(expr):
if name not in found_names:
found_names.add(name)
ilk = child.get("ilk") or child.tag
if ilk == "import":
ilk = "module"
cplns.append((ilk, name))
scoperef = self.parent_scoperef_from_scoperef(scoperef)
# Add keywords, being smart about where they are allowed.
preceeding_text = self.trg.extra.get("preceeding_text", "")
for keyword in self.buf.langintel.keywords:
if len(keyword) < 3 or not keyword.startswith(expr):
continue
# Always add None and lambda, otherwise only at the start of lines.
if not preceeding_text or keyword in ("None", "lambda"):
cplns.append(("keyword", keyword))
return sorted(cplns, key=operator.itemgetter(1))
def _tokenize_citdl_expr(self, citdl):
for token in citdl.split('.'):
if token.endswith('()'):
yield token[:-2]
yield '()'
else:
yield token
def _join_citdl_expr(self, tokens):
return '.'.join(tokens)
def _calltip_from_func(self, elem, scoperef, class_name=None):
# See "Determining a Function CallTip" in the spec for a
# discussion of this algorithm.
signature = elem.get("signature")
ctlines = []
if not signature:
name = class_name or elem.get("name")
ctlines = [name + "(...)"]
else:
ctlines = signature.splitlines(0)
doc = elem.get("doc")
if doc:
ctlines += doc.splitlines(0)
return '\n'.join(ctlines)
def _calltip_from_class(self, elem, scoperef):
# If the class has a defined signature then use that.
signature = elem.get("signature")
if signature:
doc = elem.get("doc")
ctlines = signature.splitlines(0)
if doc:
ctlines += doc.splitlines(0)
return '\n'.join(ctlines)
else:
ctor_hit = self._ctor_hit_from_class(elem, scoperef)
if ctor_hit and (ctor_hit[0].get("doc")
or ctor_hit[0].get("signature")):
self.log("ctor is %r on %r", *ctor_hit)
return self._calltip_from_func(ctor_hit[0], ctor_hit[1],
class_name=elem.get("name"))
else:
doc = elem.get("doc")
if doc:
ctlines = [ln for ln in doc.splitlines(0) if ln]
else:
ctlines = [elem.get("name") + "()"]
return '\n'.join(ctlines)
def _ctor_hit_from_class(self, elem, scoperef):
"""Return the Python ctor for the given class element, or None."""
if "__init__" in elem.names:
class_scoperef = (scoperef[0], scoperef[1]+[elem.get("name")])
return elem.names["__init__"], class_scoperef
else:
for classref in elem.get("classrefs", "").split():
try:
basehit = self._hit_from_type_inference(classref, scoperef)
except CodeIntelError as ex:
self.warn(str(ex))
else:
ctor_hit = self._ctor_hit_from_class(*basehit)
if ctor_hit:
return ctor_hit
return None
def _calltip_from_hit(self, hit):
# TODO: compare with CitadelEvaluator._getSymbolCallTips()
elem, scoperef = hit
if elem.tag == "variable":
XXX
elif elem.tag == "scope":
ilk = elem.get("ilk")
if ilk == "function":
calltip = self._calltip_from_func(elem, scoperef)
elif ilk == "class":
calltip = self._calltip_from_class(elem, scoperef)
else:
raise NotImplementedError("unexpected scope ilk for "
"calltip hit: %r" % elem)
else:
raise NotImplementedError("unexpected elem for calltip "
"hit: %r" % elem)
return calltip
def _members_from_elem(self, elem):
"""Return the appropriate set of autocomplete completions for
the given | |
default running in one or more connection multiplexer subprocesses spawned
off the top-level Ansible process.
"""
def on_strategy_start(self):
"""
Called prior to strategy start in the top-level process. Responsible
for preparing any worker/connection multiplexer state.
"""
raise NotImplementedError()
def on_strategy_complete(self):
"""
Called after strategy completion in the top-level process. Must place
Ansible back in a "compatible" state where any other strategy plug-in
may execute.
"""
raise NotImplementedError()
def get_binding(self, inventory_name):
"""
Return a :class:`Binding` to access Mitogen services for
`inventory_name`. Usually called from worker processes, but may also be
called from top-level process to handle "meta: reset_connection".
"""
raise NotImplementedError()
class ClassicBinding(Binding):
"""
Only one connection may be active at a time in a classic worker, so its
binding just provides forwarders back to :class:`ClassicWorkerModel`.
"""
def __init__(self, model):
self.model = model
def get_service_context(self):
"""
See Binding.get_service_context().
"""
return self.model.parent
def get_child_service_context(self):
"""
See Binding.get_child_service_context().
"""
return self.model.parent
def close(self):
"""
See Binding.close().
"""
self.model.on_binding_close()
class ClassicWorkerModel(WorkerModel):
#: In the top-level process, this references one end of a socketpair(),
#: whose other end child MuxProcesses block reading from to determine when
#: the master process dies. When the top-level exits abnormally, or
#: normally but where :func:`_on_process_exit` has been called, this socket
#: will be closed, causing all the children to wake.
parent_sock = None
#: In the mux process, this is the other end of :attr:`cls_parent_sock`.
#: The main thread blocks on a read from it until :attr:`cls_parent_sock`
#: is closed.
child_sock = None
#: mitogen.master.Router for this worker.
router = None
#: mitogen.master.Broker for this worker.
broker = None
#: Name of multiplexer process socket we are currently connected to.
listener_path = None
#: mitogen.parent.Context representing the parent Context, which is the
#: connection multiplexer process when running in classic mode, or the
#: top-level process when running a new-style mode.
parent = None
def __init__(self, _init_logging=True):
"""
Arrange for classic model multiplexers to be started. The parent choses
UNIX socket paths each child will use prior to fork, creates a
socketpair used essentially as a semaphore, then blocks waiting for the
child to indicate the UNIX socket is ready for use.
:param bool _init_logging:
For testing, if :data:`False`, don't initialize logging.
"""
# #573: The process ID that installed the :mod:`atexit` handler. If
# some unknown Ansible plug-in forks the Ansible top-level process and
# later performs a graceful Python exit, it may try to wait for child
# PIDs it never owned, causing a crash. We want to avoid that.
self._pid = os.getpid()
common_setup(_init_logging=_init_logging)
self.parent_sock, self.child_sock = socket.socketpair()
mitogen.core.set_cloexec(self.parent_sock.fileno())
mitogen.core.set_cloexec(self.child_sock.fileno())
self._muxes = [
MuxProcess(self, index) for index in range(get_cpu_count(default=1))
]
for mux in self._muxes:
mux.start()
atexit.register(self._on_process_exit)
self.child_sock.close()
self.child_sock = None
def _listener_for_name(self, name):
"""
Given an inventory hostname, return the UNIX listener that should
communicate with it. This is a simple hash of the inventory name.
"""
mux = self._muxes[abs(hash(name)) % len(self._muxes)]
LOG.debug(
'will use multiplexer %d (%s) to connect to "%s"', mux.index, mux.path, name
)
return mux.path
def _reconnect(self, path):
if self.router is not None:
# Router can just be overwritten, but the previous parent
# connection must explicitly be removed from the broker first.
self.router.disconnect(self.parent)
self.parent = None
self.router = None
try:
self.router, self.parent = mitogen.unix.connect(
path=path,
broker=self.broker,
)
except mitogen.unix.ConnectError as e:
# This is not AnsibleConnectionFailure since we want to break
# with_items loops.
raise ansible.errors.AnsibleError(shutting_down_msg % (e,))
self.router.max_message_size = MAX_MESSAGE_SIZE
self.listener_path = path
def _on_process_exit(self):
"""
This is an :mod:`atexit` handler installed in the top-level process.
Shut the write end of `sock`, causing the receive side of the socket in
every :class:`MuxProcess` to return 0-byte reads, and causing their
main threads to wake and initiate shutdown. After shutting the socket
down, wait on each child to finish exiting.
This is done using :mod:`atexit` since Ansible lacks any better hook to
run code during exit, and unless some synchronization exists with
MuxProcess, debug logs may appear on the user's terminal *after* the
prompt has been printed.
"""
if self._pid != os.getpid():
return
try:
self.parent_sock.shutdown(socket.SHUT_WR)
except socket.error:
# Already closed. This is possible when tests are running.
LOG.debug("_on_process_exit: ignoring duplicate call")
return
mitogen.core.io_op(self.parent_sock.recv, 1)
self.parent_sock.close()
for mux in self._muxes:
_, status = os.waitpid(mux.pid, 0)
status = mitogen.fork._convert_exit_status(status)
LOG.debug(
"multiplexer %d PID %d %s",
mux.index,
mux.pid,
mitogen.parent.returncode_to_str(status),
)
def _test_reset(self):
"""
Used to clean up in unit tests.
"""
self.on_binding_close()
self._on_process_exit()
set_worker_model(None)
global _classic_worker_model
_classic_worker_model = None
def on_strategy_start(self):
"""
See WorkerModel.on_strategy_start().
"""
def on_strategy_complete(self):
"""
See WorkerModel.on_strategy_complete().
"""
def get_binding(self, inventory_name):
"""
See WorkerModel.get_binding().
"""
if self.broker is None:
self.broker = Broker()
path = self._listener_for_name(inventory_name)
if path != self.listener_path:
self._reconnect(path)
return ClassicBinding(self)
def on_binding_close(self):
if not self.broker:
return
self.broker.shutdown()
self.broker.join()
self.router = None
self.broker = None
self.parent = None
self.listener_path = None
# #420: Ansible executes "meta" actions in the top-level process,
# meaning "reset_connection" will cause :class:`mitogen.core.Latch` FDs
# to be cached and erroneously shared by children on subsequent
# WorkerProcess forks. To handle that, call on_fork() to ensure any
# shared state is discarded.
# #490: only attempt to clean up when it's known that some resources
# exist to cleanup, otherwise later __del__ double-call to close() due
# to GC at random moment may obliterate an unrelated Connection's
# related resources.
mitogen.fork.on_fork()
class MuxProcess(object):
"""
Implement a subprocess forked from the Ansible top-level, as a safe place
to contain the Mitogen IO multiplexer thread, keeping its use of the
logging package (and the logging package's heavy use of locks) far away
from os.fork(), which is used continuously by the multiprocessing package
in the top-level process.
The problem with running the multiplexer in that process is that should the
multiplexer thread be in the process of emitting a log entry (and holding
its lock) at the point of fork, in the child, the first attempt to log any
log entry using the same handler will deadlock the child, as in the memory
image the child received, the lock will always be marked held.
See https://bugs.python.org/issue6721 for a thorough description of the
class of problems this worker is intended to avoid.
"""
#: A copy of :data:`os.environ` at the time the multiplexer process was
#: started. It's used by mitogen_local.py to find changes made to the
#: top-level environment (e.g. vars plugins -- issue #297) that must be
#: applied to locally executed commands and modules.
cls_original_env = None
def __init__(self, model, index):
#: :class:`ClassicWorkerModel` instance we were created by.
self.model = model
#: MuxProcess CPU index.
self.index = index
#: Individual path of this process.
self.path = mitogen.unix.make_socket_path()
def start(self):
self.pid = os.fork()
if self.pid:
# Wait for child to boot before continuing.
mitogen.core.io_op(self.model.parent_sock.recv, 1)
return
ansible_mitogen.logging.set_process_name("mux:" + str(self.index))
if setproctitle:
setproctitle.setproctitle(
"mitogen mux:%s (%s)"
% (
self.index,
os.path.basename(self.path),
)
)
self.model.parent_sock.close()
self.model.parent_sock = None
try:
try:
self.worker_main()
except Exception:
LOG.exception("worker_main() crashed")
finally:
sys.exit()
def worker_main(self):
"""
The main function of the mux process: setup the Mitogen broker thread
and ansible_mitogen services, then sleep waiting for the socket
connected to the parent to be closed (indicating the parent has died).
"""
save_pid("mux")
# #623: MuxProcess ignores SIGINT because it wants to live until every
# Ansible worker process has been cleaned up by
# TaskQueueManager.cleanup(), otherwise harmles yet scary warnings
# about being unable connect to MuxProess could be printed.
signal.signal(signal.SIGINT, signal.SIG_IGN)
ansible_mitogen.logging.set_process_name("mux")
ansible_mitogen.affinity.policy.assign_muxprocess(self.index)
self._setup_master()
self._setup_services()
try:
# Let the parent know our listening socket is ready.
mitogen.core.io_op(self.model.child_sock.send, b("1"))
# Block until the socket is closed, which happens on parent exit.
mitogen.core.io_op(self.model.child_sock.recv, 1)
finally:
self.broker.shutdown()
self.broker.join()
# Test frameworks living somewhere higher on the stack of the
# original parent process may try to catch sys.exit(), so do a C
# level exit instead.
os._exit(0)
def _enable_router_debug(self):
if "MITOGEN_ROUTER_DEBUG" in os.environ:
self.router.enable_debug()
def _enable_stack_dumps(self):
secs = getenv_int("MITOGEN_DUMP_THREAD_STACKS", default=0)
if secs:
mitogen.debug.dump_to_logger(secs=secs)
def _setup_master(self):
"""
| |
u('\u6c5f\u82cf\u7701\u6cf0\u5dde\u5e02')},
'861811411':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u65e0\u9521\u5e02')},
'861811410':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u65e0\u9521\u5e02')},
'861811419':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u626c\u5dde\u5e02')},
'861811418':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u5e38\u5dde\u5e02')},
'861808949':{'en': '<NAME>', 'zh': u('\u7518\u8083\u7701\u6b66\u5a01\u5e02')},
'861808948':{'en': '<NAME>', 'zh': u('\u7518\u8083\u7701\u5f20\u6396\u5e02')},
'861806604':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u5357\u4eac\u5e02')},
'861808946':{'en': '<NAME>', 'zh': u('\u7518\u8083\u7701\u5f20\u6396\u5e02')},
'861808945':{'en': '<NAME>', 'zh': u('\u7518\u8083\u7701\u5929\u6c34\u5e02')},
'861808944':{'en': '<NAME>', 'zh': u('\u7518\u8083\u7701\u5929\u6c34\u5e02')},
'861770390':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u5e73\u9876\u5c71\u5e02')},
'861808942':{'en': '<NAME>', 'zh': u('\u7518\u8083\u7701\u767d\u94f6\u5e02')},
'861808941':{'en': '<NAME>', 'zh': u('\u7518\u8083\u7701\u7518\u5357\u85cf\u65cf\u81ea\u6cbb\u5dde')},
'861808940':{'en': '<NAME>', 'zh': u('\u7518\u8083\u7701\u7518\u5357\u85cf\u65cf\u81ea\u6cbb\u5dde')},
'861805946':{'en': '<NAME>', 'zh': u('\u798f\u5efa\u7701\u4e09\u660e\u5e02')},
'861810605':{'en': '<NAME>', 'zh': u('\u798f\u5efa\u7701\u798f\u5dde\u5e02')},
'861806605':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u5357\u4eac\u5e02')},
'861810604':{'en': 'Fuzhou, Fujian', 'zh': u('\u798f\u5efa\u7701\u798f\u5dde\u5e02')},
'861770391':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u7126\u4f5c\u5e02')},
'861810606':{'en': '<NAME>', 'zh': u('\u798f\u5efa\u7701\u798f\u5dde\u5e02')},
'861812162':{'en': '<NAME>su', 'zh': u('\u6c5f\u82cf\u7701\u8fde\u4e91\u6e2f\u5e02')},
'861810601':{'en': 'Fuzhou, Fujian', 'zh': u('\u798f\u5efa\u7701\u798f\u5dde\u5e02')},
'861810600':{'en': 'Fuzhou, Fujian', 'zh': u('\u798f\u5efa\u7701\u798f\u5dde\u5e02')},
'861810603':{'en': 'Fuzhou, Fujian', 'zh': u('\u798f\u5efa\u7701\u798f\u5dde\u5e02')},
'861810602':{'en': 'Fuzhou, Fujian', 'zh': u('\u798f\u5efa\u7701\u798f\u5dde\u5e02')},
'861812163':{'en': 'Lianyungang, Jiangsu', 'zh': u('\u6c5f\u82cf\u7701\u8fde\u4e91\u6e2f\u5e02')},
'861810549':{'en': '<NAME>', 'zh': u('\u5c71\u4e1c\u7701\u4e34\u6c82\u5e02')},
'861775007':{'en': 'Quanzhou, Fujian', 'zh': u('\u798f\u5efa\u7701\u6cc9\u5dde\u5e02')},
'861775006':{'en': 'Quanzhou, Fujian', 'zh': u('\u798f\u5efa\u7701\u6cc9\u5dde\u5e02')},
'861775005':{'en': 'Quanzhou, Fujian', 'zh': u('\u798f\u5efa\u7701\u6cc9\u5dde\u5e02')},
'861775004':{'en': 'Quanzhou, Fujian', 'zh': u('\u798f\u5efa\u7701\u6cc9\u5dde\u5e02')},
'861775003':{'en': 'Quanzhou, Fujian', 'zh': u('\u798f\u5efa\u7701\u6cc9\u5dde\u5e02')},
'861775002':{'en': 'Quanzhou, Fujian', 'zh': u('\u798f\u5efa\u7701\u6cc9\u5dde\u5e02')},
'861775001':{'en': '<NAME>', 'zh': u('\u798f\u5efa\u7701\u53a6\u95e8\u5e02')},
'861775000':{'en': '<NAME>', 'zh': u('\u798f\u5efa\u7701\u53a6\u95e8\u5e02')},
'861810790':{'en': '<NAME>', 'zh': u('\u6c5f\u897f\u7701\u65b0\u4f59\u5e02')},
'861775009':{'en': 'Quanzhou, Fujian', 'zh': u('\u798f\u5efa\u7701\u6cc9\u5dde\u5e02')},
'861775008':{'en': 'Quanzhou, Fujian', 'zh': u('\u798f\u5efa\u7701\u6cc9\u5dde\u5e02')},
'861770394':{'en': 'Zhoukou, Henan', 'zh': u('\u6cb3\u5357\u7701\u5468\u53e3\u5e02')},
'86180710':{'en': 'Wuhan, Hubei', 'zh': u('\u6e56\u5317\u7701\u6b66\u6c49\u5e02')},
'861811679':{'en': 'Dazhou, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u8fbe\u5dde\u5e02')},
'861811678':{'en': 'Guangyuan, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u5e7f\u5143\u5e02')},
'861811673':{'en': 'Suining, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u9042\u5b81\u5e02')},
'861811672':{'en': 'Bazhong, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u5df4\u4e2d\u5e02')},
'861811671':{'en': 'Bazhong, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u5df4\u4e2d\u5e02')},
'861811670':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u6210\u90fd\u5e02')},
'861811677':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u5e7f\u5143\u5e02')},
'861811676':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u9042\u5b81\u5e02')},
'861811675':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u9042\u5b81\u5e02')},
'861811674':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u9042\u5b81\u5e02')},
'861769879':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u6f2f\u6cb3\u5e02')},
'861769878':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u9a7b\u9a6c\u5e97\u5e02')},
'861769877':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u9a7b\u9a6c\u5e97\u5e02')},
'861769876':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u9a7b\u9a6c\u5e97\u5e02')},
'861769875':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u4fe1\u9633\u5e02')},
'861769874':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u4fe1\u9633\u5e02')},
'861769873':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u4fe1\u9633\u5e02')},
'861769872':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u7126\u4f5c\u5e02')},
'861769871':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u7126\u4f5c\u5e02')},
'861769870':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u7126\u4f5c\u5e02')},
'861770396':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u9a7b\u9a6c\u5e97\u5e02')},
'861810795':{'en': '<NAME>', 'zh': u('\u6c5f\u897f\u7701\u5b9c\u6625\u5e02')},
'861770397':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u9a7b\u9a6c\u5e97\u5e02')},
'861800558':{'en': '<NAME>', 'zh': u('\u5b89\u5fbd\u7701\u961c\u9633\u5e02')},
'861800559':{'en': '<NAME>', 'zh': u('\u5b89\u5fbd\u7701\u9ec4\u5c71\u5e02')},
'861800554':{'en': '<NAME>', 'zh': u('\u5b89\u5fbd\u7701\u6dee\u5357\u5e02')},
'861800555':{'en': '<NAME>', 'zh': u('\u5b89\u5fbd\u7701\u9a6c\u978d\u5c71\u5e02')},
'861800556':{'en': 'An<NAME>', 'zh': u('\u5b89\u5fbd\u7701\u5b89\u5e86\u5e02')},
'861800557':{'en': 'Suzhou, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u5bbf\u5dde\u5e02')},
'861800550':{'en': 'Chuzhou, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u6ec1\u5dde\u5e02')},
'861800551':{'en': 'Hefei, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u5408\u80a5\u5e02')},
'861800552':{'en': 'Bengbu, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u868c\u57e0\u5e02')},
'861800553':{'en': 'Wuhu, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u829c\u6e56\u5e02')},
'86180976':{'en': 'Urumchi, Xinjiang', 'zh': u('\u65b0\u7586\u4e4c\u9c81\u6728\u9f50\u5e02')},
'861804077':{'en': 'Urumchi, Xinjiang', 'zh': u('\u65b0\u7586\u4e4c\u9c81\u6728\u9f50\u5e02')},
'861804076':{'en': 'Urumchi, Xinjiang', 'zh': u('\u65b0\u7586\u4e4c\u9c81\u6728\u9f50\u5e02')},
'861804075':{'en': 'Urumchi, Xinjiang', 'zh': u('\u65b0\u7586\u4e4c\u9c81\u6728\u9f50\u5e02')},
'861804074':{'en': 'Kashi, Xinjiang', 'zh': u('\u65b0\u7586\u5580\u4ec0\u5730\u533a')},
'861804073':{'en': 'Altay, Xinjiang', 'zh': u('\u65b0\u7586\u963f\u52d2\u6cf0\u5730\u533a')},
'861804072':{'en': 'Ili, Xinjiang', 'zh': u('\u65b0\u7586\u4f0a\u7281\u54c8\u8428\u514b\u81ea\u6cbb\u5dde')},
'861804071':{'en': 'Hotan, Xinjiang', 'zh': u('\u65b0\u7586\u548c\u7530\u5730\u533a')},
'861804070':{'en': 'Aksu, Xinjiang', 'zh': u('\u65b0\u7586\u963f\u514b\u82cf\u5730\u533a')},
'861804079':{'en': 'Urumchi, Xinjiang', 'zh': u('\u65b0\u7586\u4e4c\u9c81\u6728\u9f50\u5e02')},
'861804078':{'en': '<NAME>', 'zh': u('\u65b0\u7586\u4e4c\u9c81\u6728\u9f50\u5e02')},
'861808903':{'en': '<NAME>', 'zh': u('\u897f\u85cf\u5c71\u5357\u5730\u533a')},
'861810492':{'en': '<NAME>', 'zh': u('\u8fbd\u5b81\u7701\u978d\u5c71\u5e02')},
'861808902':{'en': '<NAME>', 'zh': u('\u897f\u85cf\u65e5\u5580\u5219\u5730\u533a')},
'861808901':{'en': '<NAME>', 'zh': u('\u897f\u85cf\u62c9\u8428\u5e02')},
'861808900':{'en': '<NAME>', 'zh': u('\u897f\u85cf\u62c9\u8428\u5e02')},
'861808907':{'en': '<NAME>', 'zh': u('\u897f\u85cf\u963f\u91cc\u5730\u533a')},
'861811823':{'en': 'Yangzhou, Jiangsu', 'zh': u('\u6c5f\u82cf\u7701\u626c\u5dde\u5e02')},
'861808906':{'en': 'Nagqu, Tibet', 'zh': u('\u897f\u85cf\u90a3\u66f2\u5730\u533a')},
'861808905':{'en': 'Qamdo, Tibet', 'zh': u('\u897f\u85cf\u660c\u90fd\u5730\u533a')},
'861808904':{'en': 'Nyingchi, Tibet', 'zh': u('\u897f\u85cf\u6797\u829d\u5730\u533a')},
'861804911':{'en': '<NAME>', 'zh': u('\u9655\u897f\u7701\u5ef6\u5b89\u5e02')},
'861804095':{'en': 'Bayingolin, Xinjiang', 'zh': u('\u65b0\u7586\u5df4\u97f3\u90ed\u695e\u8499\u53e4\u81ea\u6cbb\u5dde')},
'861804546':{'en': '<NAME>', 'zh': u('\u9ed1\u9f99\u6c5f\u7701\u4f73\u6728\u65af\u5e02')},
'861804917':{'en': 'Baoji, Shaanxi', 'zh': u('\u9655\u897f\u7701\u5b9d\u9e21\u5e02')},
'861804545':{'en': 'Jiamusi, Heilongjiang', 'zh': u('\u9ed1\u9f99\u6c5f\u7701\u4f73\u6728\u65af\u5e02')},
'861804096':{'en': '<NAME>', 'zh': u('\u65b0\u7586\u4f0a\u7281\u54c8\u8428\u514b\u81ea\u6cbb\u5dde')},
'861804543':{'en': 'Jiamusi, Heilongjiang', 'zh': u('\u9ed1\u9f99\u6c5f\u7701\u4f73\u6728\u65af\u5e02')},
'861804090':{'en': 'Urumchi, Xinjiang', 'zh': u('\u65b0\u7586\u4e4c\u9c81\u6728\u9f50\u5e02')},
'861805658':{'en': 'Wuhu, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u829c\u6e56\u5e02')},
'861805659':{'en': 'Wuhu, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u829c\u6e56\u5e02')},
'861804541':{'en': 'Jiamusi, Heilongjiang', 'zh': u('\u9ed1\u9f99\u6c5f\u7701\u4f73\u6728\u65af\u5e02')},
'861805650':{'en': 'Wuhu, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u829c\u6e56\u5e02')},
'861805651':{'en': 'Hefei, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u5408\u80a5\u5e02')},
'861805652':{'en': 'Wuhu, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u829c\u6e56\u5e02')},
'861805653':{'en': 'Wuhu, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u829c\u6e56\u5e02')},
'861805654':{'en': 'Hefei, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u5408\u80a5\u5e02')},
'861805655':{'en': 'MaAnshan, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u9a6c\u978d\u5c71\u5e02')},
'861805656':{'en': 'MaAnshan, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u9a6c\u978d\u5c71\u5e02')},
'861805657':{'en': 'Hefei, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u5408\u80a5\u5e02')},
'861812500':{'en': 'Maoming, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u8302\u540d\u5e02')},
'861812501':{'en': 'Maoming, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u8302\u540d\u5e02')},
'861812502':{'en': 'Maoming, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u8302\u540d\u5e02')},
'861812503':{'en': 'Maoming, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u8302\u540d\u5e02')},
'861809719':{'en': 'Haixi, Qinghai', 'zh': u('\u9752\u6d77\u7701\u6d77\u897f\u8499\u53e4\u65cf\u85cf\u65cf\u81ea\u6cbb\u5dde')},
'861809718':{'en': 'Xining, Qinghai', 'zh': u('\u9752\u6d77\u7701\u897f\u5b81\u5e02')},
'861812506':{'en': 'Zhuhai, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u73e0\u6d77\u5e02')},
'861812507':{'en': 'Zhuhai, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u73e0\u6d77\u5e02')},
'861809715':{'en': 'Golog, Qinghai', 'zh': u('\u9752\u6d77\u7701\u679c\u6d1b\u85cf\u65cf\u81ea\u6cbb\u5dde')},
'861809714':{'en': 'Hainan, Qinghai', 'zh': u('\u9752\u6d77\u7701\u6d77\u5357\u85cf\u65cf\u81ea\u6cbb\u5dde')},
'861809717':{'en': 'Haixi, Qinghai', 'zh': u('\u9752\u6d77\u7701\u6d77\u897f\u8499\u53e4\u65cf\u85cf\u65cf\u81ea\u6cbb\u5dde')},
'861809716':{'en': 'Yushu, Qinghai', 'zh': u('\u9752\u6d77\u7701\u7389\u6811\u85cf\u65cf\u81ea\u6cbb\u5dde')},
'861807660':{'en': 'Nanning, Guangxi', 'zh': u('\u5e7f\u897f\u5357\u5b81\u5e02')},
'861809710':{'en': 'Haibei, Qinghai', 'zh': u('\u9752\u6d77\u7701\u6d77\u5317\u85cf\u65cf\u81ea\u6cbb\u5dde')},
'861809713':{'en': 'Huangnan, Qinghai', 'zh': u('\u9752\u6d77\u7701\u9ec4\u5357\u85cf\u65cf\u81ea\u6cbb\u5dde')},
'861809712':{'en': 'Haidong, Qinghai', 'zh': u('\u9752\u6d77\u7701\u6d77\u4e1c\u5730\u533a')},
'861803766':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u5468\u53e3\u5e02')},
'861803767':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u90d1\u5dde\u5e02')},
'861803764':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u5546\u4e18\u5e02')},
'861803765':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u5468\u53e3\u5e02')},
'861803762':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u6d1b\u9633\u5e02')},
'861803763':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u5468\u53e3\u5e02')},
'861803760':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u4fe1\u9633\u5e02')},
'861803761':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u4fe1\u9633\u5e02')},
'861775788':{'en': 'Lishui, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u4e3d\u6c34\u5e02')},
'861775789':{'en': 'Zhoushan, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u821f\u5c71\u5e02')},
'861804386':{'en': '<NAME>', 'zh': u('\u5409\u6797\u7701\u677e\u539f\u5e02')},
'861804381':{'en': '<NAME>', 'zh': u('\u5409\u6797\u7701\u957f\u6625\u5e02')},
'861804380':{'en': '<NAME>', 'zh': u('\u5409\u6797\u7701\u677e\u539f\u5e02')},
'861803768':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u90d1\u5dde\u5e02')},
'861803769':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u90d1\u5dde\u5e02')},
'861805038':{'en': '<NAME>', 'zh': u('\u798f\u5efa\u7701\u5357\u5e73\u5e02')},
'861805039':{'en': '<NAME>', 'zh': u('\u798f\u5efa\u7701\u5357\u5e73\u5e02')},
'861813955':{'en': '<NAME>', 'zh': u('\u65b0\u7586\u5580\u4ec0\u5730\u533a')},
'861805034':{'en': '<NAME>', 'zh': u('\u798f\u5efa\u7701\u798f\u5dde\u5e02')},
'861805035':{'en': '<NAME>', 'zh': u('\u798f\u5efa\u7701\u5b81\u5fb7\u5e02')},
'861805036':{'en': '<NAME>', 'zh': u('\u798f\u5efa\u7701\u5b81\u5fb7\u5e02')},
'861805037':{'en': 'Nanping, Fujian', 'zh': u('\u798f\u5efa\u7701\u5357\u5e73\u5e02')},
'861805030':{'en': 'Fuzhou, Fujian', 'zh': u('\u798f\u5efa\u7701\u798f\u5dde\u5e02')},
'861805031':{'en': 'Fuzhou, Fujian', 'zh': u('\u798f\u5efa\u7701\u798f\u5dde\u5e02')},
'861805032':{'en': 'Fuzhou, Fujian', 'zh': u('\u798f\u5efa\u7701\u798f\u5dde\u5e02')},
'861805033':{'en': 'Fuzhou, Fujian', 'zh': u('\u798f\u5efa\u7701\u798f\u5dde\u5e02')},
'861809056':{'en': 'Nanchong, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u5357\u5145\u5e02')},
'861809057':{'en': 'Nanchong, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u5357\u5145\u5e02')},
'861809054':{'en': 'Nanchong, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u5357\u5145\u5e02')},
'861809055':{'en': 'Nanchong, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u5357\u5145\u5e02')},
'861809052':{'en': 'GuangAn, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u5e7f\u5b89\u5e02')},
'861809053':{'en': '<NAME>uan', 'zh': u('\u56db\u5ddd\u7701\u5e7f\u5b89\u5e02')},
'861809050':{'en': 'GuangAn, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u5e7f\u5b89\u5e02')},
'861809051':{'en': 'GuangAn, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u5e7f\u5b89\u5e02')},
'861809989':{'en': 'Ili, Xinjiang', 'zh': u('\u65b0\u7586\u4f0a\u7281\u54c8\u8428\u514b\u81ea\u6cbb\u5dde')},
'86180945':{'en': 'Ningbo, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u5b81\u6ce2\u5e02')},
'861811084':{'en': '<NAME>', 'zh': u('\u5b89\u5fbd\u7701\u5ba3\u57ce\u5e02')},
'861811085':{'en': '<NAME>', 'zh': u('\u5b89\u5fbd\u7701\u5ba3\u57ce\u5e02')},
'861811086':{'en': '<NAME>', 'zh': u('\u5b89\u5fbd\u7701\u5ba3\u57ce\u5e02')},
'861811087':{'en': 'Wuhu, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u829c\u6e56\u5e02')},
'861811080':{'en': 'Xu<NAME>', 'zh': u('\u5b89\u5fbd\u7701\u5ba3\u57ce\u5e02')},
'861811081':{'en': 'Xuancheng, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u5ba3\u57ce\u5e02')},
'861811082':{'en': 'Xuancheng, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u5ba3\u57ce\u5e02')},
'861811083':{'en': '<NAME>', 'zh': u('\u5b89\u5fbd\u7701\u5ba3\u57ce\u5e02')},
'861810285':{'en': 'Shanwei, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6c55\u5c3e\u5e02')},
'861811088':{'en': 'Wuhu, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u829c\u6e56\u5e02')},
'861811089':{'en': 'Bozhou, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u4eb3\u5dde\u5e02')},
'861810284':{'en': 'Guangzhou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u5e7f\u5dde\u5e02')},
'861810287':{'en': 'Shanwei, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6c55\u5c3e\u5e02')},
'861809983':{'en': 'Ili, Xinjiang', 'zh': u('\u65b0\u7586\u4f0a\u7281\u54c8\u8428\u514b\u81ea\u6cbb\u5dde')},
'861809985':{'en': 'Kashi, Xinjiang', 'zh': u('\u65b0\u7586\u5580\u4ec0\u5730\u533a')},
'861811888':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u65e0\u9521\u5e02')},
'861811889':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u65e0\u9521\u5e02')},
'861802569':{'en': 'Zhongshan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e2d\u5c71\u5e02')},
'861802568':{'en': 'Zhongshan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e2d\u5c71\u5e02')},
'861802567':{'en': 'Zhongshan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e2d\u5c71\u5e02')},
'861802566':{'en': 'Zhongshan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e2d\u5c71\u5e02')},
'861802565':{'en': 'Zhongshan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e2d\u5c71\u5e02')},
'861802564':{'en': 'Shantou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6c55\u5934\u5e02')},
'861802563':{'en': 'Shantou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6c55\u5934\u5e02')},
'861802562':{'en': 'Shantou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6c55\u5934\u5e02')},
'861802561':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6c55\u5934\u5e02')},
'861802560':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6c55\u5934\u5e02')},
'86180369':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u5bbf\u8fc1\u5e02')},
'861805233':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u8fde\u4e91\u6e2f\u5e02')},
'861808310':{'en': '<NAME>', 'zh': u('\u8d35\u5dde\u7701\u9ed4\u5357\u5e03\u4f9d\u65cf\u82d7\u65cf\u81ea\u6cbb\u5dde')},
'86180366':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u8fde\u4e91\u6e2f\u5e02')},
'861808311':{'en': '<NAME>', 'zh': u('\u8d35\u5dde\u7701\u9ed4\u5357\u5e03\u4f9d\u65cf\u82d7\u65cf\u81ea\u6cbb\u5dde')},
'861808316':{'en': '<NAME>', 'zh': u('\u8d35\u5dde\u7701\u5b89\u987a\u5e02')},
'861808317':{'en': '<NAME>', 'zh': u('\u8d35\u5dde\u7701\u9ed4\u4e1c\u5357\u82d7\u65cf\u4f97\u65cf\u81ea\u6cbb\u5dde')},
'861808314':{'en': '<NAME>', 'zh': u('\u8d35\u5dde\u7701\u5b89\u987a\u5e02')},
'861805235':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u6dee\u5b89\u5e02')},
'861804322':{'en': '<NAME>', 'zh': u('\u5409\u6797\u7701\u5409\u6797\u5e02')},
'861804897':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u5fb7\u9633\u5e02')},
'86180579':{'en': '<NAME>', 'zh': u('\u6d59\u6c5f\u7701\u91d1\u534e\u5e02')},
'861804896':{'en': 'Nanchong, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u5357\u5145\u5e02')},
'86180578':{'en': 'Lishui, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u4e3d\u6c34\u5e02')},
'861804890':{'en': 'Mianyang, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u7ef5\u9633\u5e02')},
'861804893':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u4e50\u5c71\u5e02')},
'861761448':{'en': '<NAME>', 'zh': u('\u5409\u6797\u7701\u677e\u539f\u5e02')},
'861761449':{'en': '<NAME>', 'zh': u('\u5409\u6797\u7701\u767d\u5c71\u5e02')},
'861761446':{'en': '<NAME>', 'zh': u('\u5409\u6797\u7701\u767d\u57ce\u5e02')},
'861761447':{'en': '<NAME>', 'zh': u('\u5409\u6797\u7701\u8fbd\u6e90\u5e02')},
'861761444':{'en': 'Siping, Jilin', 'zh': u('\u5409\u6797\u7701\u56db\u5e73\u5e02')},
'861761445':{'en': 'Tonghua, Jilin', 'zh': u('\u5409\u6797\u7701\u901a\u5316\u5e02')},
'861761442':{'en': 'Jilin, Jilin', 'zh': u('\u5409\u6797\u7701\u5409\u6797\u5e02')},
'861761443':{'en': '<NAME>', 'zh': u('\u5409\u6797\u7701\u5ef6\u8fb9\u671d\u9c9c\u65cf\u81ea\u6cbb\u5dde')},
'861761440':{'en': 'Changchun, Jilin', 'zh': u('\u5409\u6797\u7701\u957f\u6625\u5e02')},
'861761441':{'en': '<NAME>', 'zh': u('\u5409\u6797\u7701\u957f\u6625\u5e02')},
'861803160':{'en': 'Langfang, Hebei', 'zh': u('\u6cb3\u5317\u7701\u5eca\u574a\u5e02')},
'861803161':{'en': 'Langfang, Hebei', 'zh': u('\u6cb3\u5317\u7701\u5eca\u574a\u5e02')},
'861803162':{'en': '<NAME>', 'zh': u('\u6cb3\u5317\u7701\u5eca\u574a\u5e02')},
'861803163':{'en': '<NAME>', 'zh': u('\u6cb3\u5317\u7701\u5eca\u574a\u5e02')},
'861803164':{'en': '<NAME>', 'zh': u('\u6cb3\u5317\u7701\u5510\u5c71\u5e02')},
'861803165':{'en': 'Qinhuangdao, Hebei', 'zh': u('\u6cb3\u5317\u7701\u79e6\u7687\u5c9b\u5e02')},
'861803166':{'en': 'Qinhuangdao, Hebei', 'zh': u('\u6cb3\u5317\u7701\u79e6\u7687\u5c9b\u5e02')},
'861803167':{'en': '<NAME>', 'zh': u('\u6cb3\u5317\u7701\u5eca\u574a\u5e02')},
'861803168':{'en': '<NAME>', 'zh': u('\u6cb3\u5317\u7701\u5eca\u574a\u5e02')},
'861803169':{'en': '<NAME>', 'zh': u('\u6cb3\u5317\u7701\u5eca\u574a\u5e02')},
'86180571':{'en': 'Hangzhou, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u676d\u5dde\u5e02')},
'861801437':{'en': 'Nantong, Jiangsu', 'zh': u('\u6c5f\u82cf\u7701\u5357\u901a\u5e02')},
'86180570':{'en': 'Quzhou, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u8862\u5dde\u5e02')},
'861768809':{'en': 'Heyuan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6cb3\u6e90\u5e02')},
'861768808':{'en': 'Zhanjiang, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6e5b\u6c5f\u5e02')},
'861768805':{'en': 'Chaozhou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6f6e\u5dde\u5e02')},
'861768804':{'en': 'Dongguan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e1c\u839e\u5e02')},
'861768807':{'en': 'Shanwei, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6c55\u5c3e\u5e02')},
'861768806':{'en': 'Jieyang, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u63ed\u9633\u5e02')},
'861768801':{'en': 'Shantou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6c55\u5934\u5e02')},
'861768800':{'en': 'Shantou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6c55\u5934\u5e02')},
'861768803':{'en': 'Dongguan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e1c\u839e\u5e02')},
'861768802':{'en': 'Dongguan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e1c\u839e\u5e02')},
'861812979':{'en': 'Heyuan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6cb3\u6e90\u5e02')},
'861812978':{'en': 'Yunfu, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e91\u6d6e\u5e02')},
'861812971':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u60e0\u5dde\u5e02')},
'861812970':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u60e0\u5dde\u5e02')},
'861812973':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u60e0\u5dde\u5e02')},
'861812972':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u60e0\u5dde\u5e02')},
'861812975':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u60e0\u5dde\u5e02')},
'861812974':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u60e0\u5dde\u5e02')},
'861812977':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u60e0\u5dde\u5e02')},
'861812976':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u60e0\u5dde\u5e02')},
'861775043':{'en': 'Xiamen, Fujian', 'zh': u('\u798f\u5efa\u7701\u53a6\u95e8\u5e02')},
'861775042':{'en': 'Fuzhou, Fujian', 'zh': u('\u798f\u5efa\u7701\u798f\u5dde\u5e02')},
'861775041':{'en': 'Fuzhou, Fujian', 'zh': u('\u798f\u5efa\u7701\u798f\u5dde\u5e02')},
'861775040':{'en': 'Fuzhou, Fujian', 'zh': u('\u798f\u5efa\u7701\u798f\u5dde\u5e02')},
'861775047':{'en': '<NAME>ian', 'zh': u('\u798f\u5efa\u7701\u5357\u5e73\u5e02')},
'861775046':{'en': 'Sanming, Fujian', 'zh': u('\u798f\u5efa\u7701\u4e09\u660e\u5e02')},
'861813729':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u5b89\u9633\u5e02')},
'861775045':{'en': '<NAME>', 'zh': u('\u798f\u5efa\u7701\u9f99\u5ca9\u5e02')},
'861775044':{'en': '<NAME>', 'zh': u('\u798f\u5efa\u7701\u8386\u7530\u5e02')},
'861811141':{'en': 'Li<NAME>', 'zh': u('\u56db\u5ddd\u7701\u51c9\u5c71\u5f5d\u65cf\u81ea\u6cbb\u5dde')},
'861811140':{'en': 'Liangshan, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u51c9\u5c71\u5f5d\u65cf\u81ea\u6cbb\u5dde')},
'861775049':{'en': '<NAME>', 'zh': u('\u798f\u5efa\u7701\u6cc9\u5dde\u5e02')},
'861775048':{'en': '<NAME>', 'zh': u('\u798f\u5efa\u7701\u6cc9\u5dde\u5e02')},
'861813666':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u5357\u4eac\u5e02')},
'861809526':{'en': 'Guyuan, Ningxia', 'zh': u('\u5b81\u590f\u56fa\u539f\u5e02')},
'861809527':{'en': 'Yinchuan, Ningxia', 'zh': u('\u5b81\u590f\u94f6\u5ddd\u5e02')},
'861809524':{'en': 'Shizuishan, Ningxia', 'zh': u('\u5b81\u590f\u77f3\u5634\u5c71\u5e02')},
'861809525':{'en': 'Shizuishan, Ningxia', 'zh': u('\u5b81\u590f\u77f3\u5634\u5c71\u5e02')},
'861809522':{'en': 'Shizuishan, Ningxia', 'zh': u('\u5b81\u590f\u77f3\u5634\u5c71\u5e02')},
'861809523':{'en': 'Shizuishan, Ningxia', 'zh': u('\u5b81\u590f\u77f3\u5634\u5c71\u5e02')},
'861809520':{'en': 'Shizuishan, Ningxia', 'zh': u('\u5b81\u590f\u77f3\u5634\u5c71\u5e02')},
'861809521':{'en': 'Shizuishan, Ningxia', 'zh': u('\u5b81\u590f\u77f3\u5634\u5c71\u5e02')},
'861814036':{'en': 'Mianyang, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u7ef5\u9633\u5e02')},
'861809528':{'en': 'Shizuishan, Ningxia', 'zh': u('\u5b81\u590f\u77f3\u5634\u5c71\u5e02')},
'861809529':{'en': '<NAME>', 'zh': u('\u5b81\u590f\u77f3\u5634\u5c71\u5e02')},
'861813667':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u5357\u4eac\u5e02')},
'861811930':{'en': '<NAME>', 'zh': u('\u7518\u8083\u7701\u5170\u5dde\u5e02')},
'861806185':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u5357\u4eac\u5e02')},
'861769120':{'en': '<NAME>', 'zh': u('\u9655\u897f\u7701\u897f\u5b89\u5e02')},
'861806187':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u5e38\u5dde\u5e02')},
'861806186':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u76d0\u57ce\u5e02')},
'861806181':{'en': '<NAME>', 'zh': | |
# Copyright (C) 2010 Apple Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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.
import unittest
from StringIO import StringIO
import messages
_messages_file_contents = """# Copyright (C) 2010 Apple Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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.
#include "config.h"
#if ENABLE(WEBKIT2)
messages -> WebPage {
LoadURL(WTF::String url)
#if ENABLE(TOUCH_EVENTS)
TouchEvent(WebKit::WebTouchEvent event)
#endif
DidReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, uint32_t policyAction)
Close()
PreferencesDidChange(WebKit::WebPreferencesStore store)
SendDoubleAndFloat(double d, float f)
SendInts(Vector<uint64_t> ints, Vector<Vector<uint64_t> > intVectors)
CreatePlugin(uint64_t pluginInstanceID, WebKit::Plugin::Parameters parameters) -> (bool result)
RunJavaScriptAlert(uint64_t frameID, WTF::String message) -> ()
GetPlugins(bool refresh) -> (Vector<WebCore::PluginInfo> plugins) DispatchOnConnectionQueue
GetPluginProcessConnection(WTF::String pluginPath) -> (CoreIPC::Connection::Handle connectionHandle) Delayed
TestMultipleAttributes() -> () DispatchOnConnectionQueue Delayed
TestConnectionQueue(uint64_t pluginID) DispatchOnConnectionQueue
#if PLATFORM(MAC)
DidCreateWebProcessConnection(CoreIPC::MachPort connectionIdentifier)
#endif
#if PLATFORM(MAC)
# Keyboard support
InterpretKeyEvent(uint32_t type) -> (Vector<WebCore::KeypressCommand> commandName)
#endif
}
#endif
"""
_expected_results = {
'name': 'WebPage',
'condition': 'ENABLE(WEBKIT2)',
'messages': (
{
'name': 'LoadURL',
'parameters': (
('WTF::String', 'url'),
),
'condition': None,
},
{
'name': 'TouchEvent',
'parameters': (
('WebKit::WebTouchEvent', 'event'),
),
'condition': 'ENABLE(TOUCH_EVENTS)',
},
{
'name': 'DidReceivePolicyDecision',
'parameters': (
('uint64_t', 'frameID'),
('uint64_t', 'listenerID'),
('uint32_t', 'policyAction'),
),
'condition': None,
},
{
'name': 'Close',
'parameters': (),
'condition': None,
},
{
'name': 'PreferencesDidChange',
'parameters': (
('WebKit::WebPreferencesStore', 'store'),
),
'condition': None,
},
{
'name': 'SendDoubleAndFloat',
'parameters': (
('double', 'd'),
('float', 'f'),
),
'condition': None,
},
{
'name': 'SendInts',
'parameters': (
('Vector<uint64_t>', 'ints'),
('Vector<Vector<uint64_t> >', 'intVectors')
),
'condition': None,
},
{
'name': 'CreatePlugin',
'parameters': (
('uint64_t', 'pluginInstanceID'),
('WebKit::Plugin::Parameters', 'parameters')
),
'reply_parameters': (
('bool', 'result'),
),
'condition': None,
},
{
'name': 'RunJavaScriptAlert',
'parameters': (
('uint64_t', 'frameID'),
('WTF::String', 'message')
),
'reply_parameters': (),
'condition': None,
},
{
'name': 'GetPlugins',
'parameters': (
('bool', 'refresh'),
),
'reply_parameters': (
('Vector<WebCore::PluginInfo>', 'plugins'),
),
'condition': None,
},
{
'name': 'GetPluginProcessConnection',
'parameters': (
('WTF::String', 'pluginPath'),
),
'reply_parameters': (
('CoreIPC::Connection::Handle', 'connectionHandle'),
),
'condition': None,
},
{
'name': 'TestMultipleAttributes',
'parameters': (
),
'reply_parameters': (
),
'condition': None,
},
{
'name': 'TestConnectionQueue',
'parameters': (
('uint64_t', 'pluginID'),
),
'condition': None,
},
{
'name': 'DidCreateWebProcessConnection',
'parameters': (
('CoreIPC::MachPort', 'connectionIdentifier'),
),
'condition': 'PLATFORM(MAC)',
},
{
'name': 'InterpretKeyEvent',
'parameters': (
('uint32_t', 'type'),
),
'reply_parameters': (
('Vector<WebCore::KeypressCommand>', 'commandName'),
),
'condition': 'PLATFORM(MAC)',
},
),
}
class MessagesTest(unittest.TestCase):
def setUp(self):
self.receiver = messages.MessageReceiver.parse(StringIO(_messages_file_contents))
class ParsingTest(MessagesTest):
def check_message(self, message, expected_message):
self.assertEquals(message.name, expected_message['name'])
self.assertEquals(len(message.parameters), len(expected_message['parameters']))
for index, parameter in enumerate(message.parameters):
self.assertEquals(parameter.type, expected_message['parameters'][index][0])
self.assertEquals(parameter.name, expected_message['parameters'][index][1])
if message.reply_parameters != None:
for index, parameter in enumerate(message.reply_parameters):
self.assertEquals(parameter.type, expected_message['reply_parameters'][index][0])
self.assertEquals(parameter.name, expected_message['reply_parameters'][index][1])
else:
self.assertFalse('reply_parameters' in expected_message)
self.assertEquals(message.condition, expected_message['condition'])
def test_receiver(self):
"""Receiver should be parsed as expected"""
self.assertEquals(self.receiver.name, _expected_results['name'])
self.assertEquals(self.receiver.condition, _expected_results['condition'])
self.assertEquals(len(self.receiver.messages), len(_expected_results['messages']))
for index, message in enumerate(self.receiver.messages):
self.check_message(message, _expected_results['messages'][index])
_expected_header = """/*
* Copyright (C) 2010 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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.
*/
#ifndef WebPageMessages_h
#define WebPageMessages_h
#if ENABLE(WEBKIT2)
#include "Arguments.h"
#include "Connection.h"
#include "MessageID.h"
#include "Plugin.h"
#include <WebCore/KeyboardEvent.h>
#include <WebCore/PluginData.h>
#include <wtf/ThreadSafeRefCounted.h>
#include <wtf/Vector.h>
namespace CoreIPC {
class ArgumentEncoder;
class Connection;
class MachPort;
}
namespace WTF {
class String;
}
namespace WebKit {
struct WebPreferencesStore;
class WebTouchEvent;
}
namespace Messages {
namespace WebPage {
enum Kind {
LoadURLID,
#if ENABLE(TOUCH_EVENTS)
TouchEventID,
#endif
DidReceivePolicyDecisionID,
CloseID,
PreferencesDidChangeID,
SendDoubleAndFloatID,
SendIntsID,
CreatePluginID,
RunJavaScriptAlertID,
GetPluginsID,
GetPluginProcessConnectionID,
TestMultipleAttributesID,
TestConnectionQueueID,
#if PLATFORM(MAC)
DidCreateWebProcessConnectionID,
#endif
#if PLATFORM(MAC)
InterpretKeyEventID,
#endif
};
struct LoadURL : CoreIPC::Arguments1<const WTF::String&> {
static const Kind messageID = LoadURLID;
typedef CoreIPC::Arguments1<const WTF::String&> DecodeType;
explicit LoadURL(const WTF::String& url)
: CoreIPC::Arguments1<const WTF::String&>(url)
{
}
};
#if ENABLE(TOUCH_EVENTS)
struct TouchEvent : CoreIPC::Arguments1<const WebKit::WebTouchEvent&> {
static const Kind messageID = TouchEventID;
typedef CoreIPC::Arguments1<const WebKit::WebTouchEvent&> DecodeType;
explicit TouchEvent(const WebKit::WebTouchEvent& event)
: CoreIPC::Arguments1<const WebKit::WebTouchEvent&>(event)
{
}
};
#endif
struct DidReceivePolicyDecision : CoreIPC::Arguments3<uint64_t, uint64_t, uint32_t> {
static const Kind messageID = DidReceivePolicyDecisionID;
typedef CoreIPC::Arguments3<uint64_t, uint64_t, uint32_t> DecodeType;
DidReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, uint32_t policyAction)
: CoreIPC::Arguments3<uint64_t, uint64_t, uint32_t>(frameID, listenerID, policyAction)
{
}
};
struct Close : CoreIPC::Arguments0 {
static const Kind messageID = CloseID;
typedef CoreIPC::Arguments0 DecodeType;
};
struct PreferencesDidChange : CoreIPC::Arguments1<const WebKit::WebPreferencesStore&> {
static const Kind messageID = PreferencesDidChangeID;
typedef CoreIPC::Arguments1<const WebKit::WebPreferencesStore&> DecodeType;
explicit PreferencesDidChange(const WebKit::WebPreferencesStore& store)
: CoreIPC::Arguments1<const WebKit::WebPreferencesStore&>(store)
{
}
};
struct SendDoubleAndFloat : CoreIPC::Arguments2<double, float> {
static const Kind messageID = SendDoubleAndFloatID;
typedef CoreIPC::Arguments2<double, float> DecodeType;
SendDoubleAndFloat(double d, float f)
: CoreIPC::Arguments2<double, float>(d, f)
{
}
};
struct SendInts : CoreIPC::Arguments2<const Vector<uint64_t>&, const Vector<Vector<uint64_t> >&> {
static const Kind messageID = SendIntsID;
typedef CoreIPC::Arguments2<const Vector<uint64_t>&, const Vector<Vector<uint64_t> >&> DecodeType;
SendInts(const Vector<uint64_t>& ints, const Vector<Vector<uint64_t> >& intVectors)
: CoreIPC::Arguments2<const Vector<uint64_t>&, const Vector<Vector<uint64_t> >&>(ints, intVectors)
{
}
};
struct CreatePlugin : CoreIPC::Arguments2<uint64_t, const WebKit::Plugin::Parameters&> {
static const Kind messageID = CreatePluginID;
typedef CoreIPC::Arguments1<bool&> Reply;
typedef CoreIPC::Arguments2<uint64_t, const WebKit::Plugin::Parameters&> DecodeType;
CreatePlugin(uint64_t pluginInstanceID, const WebKit::Plugin::Parameters& parameters)
: CoreIPC::Arguments2<uint64_t, const WebKit::Plugin::Parameters&>(pluginInstanceID, parameters)
{
}
};
struct RunJavaScriptAlert : CoreIPC::Arguments2<uint64_t, const WTF::String&> {
static const Kind messageID = RunJavaScriptAlertID;
typedef CoreIPC::Arguments0 Reply;
typedef CoreIPC::Arguments2<uint64_t, const WTF::String&> DecodeType;
RunJavaScriptAlert(uint64_t frameID, const WTF::String& message)
: CoreIPC::Arguments2<uint64_t, const WTF::String&>(frameID, message)
{
}
};
struct GetPlugins : CoreIPC::Arguments1<bool> {
static const Kind messageID = GetPluginsID;
typedef CoreIPC::Arguments1<Vector<WebCore::PluginInfo>&> Reply;
typedef CoreIPC::Arguments1<bool> DecodeType;
explicit GetPlugins(bool refresh)
: CoreIPC::Arguments1<bool>(refresh)
{
}
};
struct GetPluginProcessConnection : CoreIPC::Arguments1<const WTF::String&> {
static | |
class NativeTypeIndex(object):
def __init__(self):
self.Object:int = 0
self.AnnotationManager:int = 1
self.AssetDatabaseV1:int = 2
self.AssetMetaData:int = 3
self.BuiltAssetBundleInfoSet:int = 4
self.EditorBuildSettings:int = 5
self.EditorExtension:int = 6
self.Component:int = 7
self.Behaviour:int = 8
self.Animation:int = 9
self.Animator:int = 10
self.AudioBehaviour:int = 11
self.AudioListener:int = 12
self.AudioSource:int = 13
self.AudioFilter:int = 14
self.AudioChorusFilter:int = 15
self.AudioDistortionFilter:int = 16
self.AudioEchoFilter:int = 17
self.AudioHighPassFilter:int = 18
self.AudioLowPassFilter:int = 19
self.AudioReverbFilter:int = 20
self.AudioReverbZone:int = 21
self.Camera:int = 22
self.Canvas:int = 23
self.CanvasGroup:int = 24
self.Cloth:int = 25
self.Collider2D:int = 26
self.BoxCollider2D:int = 27
self.CapsuleCollider2D:int = 28
self.CircleCollider2D:int = 29
self.CompositeCollider2D:int = 30
self.EdgeCollider2D:int = 31
self.PolygonCollider2D:int = 32
self.TilemapCollider2D:int = 33
self.ConstantForce:int = 34
self.Effector2D:int = 35
self.AreaEffector2D:int = 36
self.BuoyancyEffector2D:int = 37
self.PlatformEffector2D:int = 38
self.PointEffector2D:int = 39
self.SurfaceEffector2D:int = 40
self.FlareLayer:int = 41
self.GUIElement:int = 42
self.GUIText:int = 43
self.GUITexture:int = 44
self.GUILayer:int = 45
self.GridLayout:int = 46
self.Grid:int = 47
self.Tilemap:int = 48
self.Halo:int = 49
self.HaloLayer:int = 50
self.Joint2D:int = 51
self.AnchoredJoint2D:int = 52
self.DistanceJoint2D:int = 53
self.FixedJoint2D:int = 54
self.FrictionJoint2D:int = 55
self.HingeJoint2D:int = 56
self.SliderJoint2D:int = 57
self.SpringJoint2D:int = 58
self.WheelJoint2D:int = 59
self.RelativeJoint2D:int = 60
self.TargetJoint2D:int = 61
self.LensFlare:int = 62
self.Light:int = 63
self.LightProbeGroup:int = 64
self.LightProbeProxyVolume:int = 65
self.MonoBehaviour:int = 66
self.NavMeshAgent:int = 67
self.NavMeshObstacle:int = 68
self.NetworkView:int = 69
self.OffMeshLink:int = 70
self.PhysicsUpdateBehaviour2D:int = 71
self.ConstantForce2D:int = 72
self.PlayableDirector:int = 73
self.Projector:int = 74
self.ReflectionProbe:int = 75
self.Skybox:int = 76
self.SortingGroup:int = 77
self.Terrain:int = 78
self.VideoPlayer:int = 79
self.WindZone:int = 80
self.CanvasRenderer:int = 81
self.Collider:int = 82
self.BoxCollider:int = 83
self.CapsuleCollider:int = 84
self.CharacterController:int = 85
self.MeshCollider:int = 86
self.SphereCollider:int = 87
self.TerrainCollider:int = 88
self.WheelCollider:int = 89
self.Joint:int = 90
self.CharacterJoint:int = 91
self.ConfigurableJoint:int = 92
self.FixedJoint:int = 93
self.HingeJoint:int = 94
self.SpringJoint:int = 95
self.LODGroup:int = 96
self.MeshFilter:int = 97
self.OcclusionArea:int = 98
self.OcclusionPortal:int = 99
self.ParticleAnimator:int = 100
self.ParticleEmitter:int = 101
self.EllipsoidParticleEmitter:int = 102
self.MeshParticleEmitter:int = 103
self.ParticleSystem:int = 104
self.Renderer:int = 105
self.BillboardRenderer:int = 106
self.LineRenderer:int = 107
self.MeshRenderer:int = 108
self.ParticleRenderer:int = 109
self.ParticleSystemRenderer:int = 110
self.SkinnedMeshRenderer:int = 111
self.SpriteMask:int = 112
self.SpriteRenderer:int = 113
self.TilemapRenderer:int = 114
self.TrailRenderer:int = 115
self.Rigidbody:int = 116
self.Rigidbody2D:int = 117
self.TextMesh:int = 118
self.Transform:int = 119
self.RectTransform:int = 120
self.Tree:int = 121
self.WorldAnchor:int = 122
self.WorldParticleCollider:int = 123
self.GameObject:int = 124
self.NamedObject:int = 125
self.AnimatorState:int = 126
self.AnimatorStateMachine:int = 127
self.AnimatorTransitionBase:int = 128
self.AnimatorStateTransition:int = 129
self.AnimatorTransition:int = 130
self.AssetBundle:int = 131
self.AssetBundleManifest:int = 132
self.AssetImporter:int = 133
self.AssemblyDefinitionImporter:int = 134
self.AudioImporter:int = 135
self.ComputeShaderImporter:int = 136
self.DefaultImporter:int = 137
self.IHVImageFormatImporter:int = 138
self.LibraryAssetImporter:int = 139
self.ModelImporter:int = 140
self.FBXImporter:int = 141
self.Mesh3DSImporter:int = 142
self.SketchUpImporter:int = 143
self.MonoImporter:int = 144
self.MovieImporter:int = 145
self.NativeFormatImporter:int = 146
self.PluginImporter:int = 147
self.ScriptedImporter:int = 148
self.ShaderImporter:int = 149
self.SpeedTreeImporter:int = 150
self.SubstanceImporter:int = 151
self.TextScriptImporter:int = 152
self.TextureImporter:int = 153
self.TrueTypeFontImporter:int = 154
self.VideoClipImporter:int = 155
self.AudioMixer:int = 156
self.AudioMixerController:int = 157
self.AudioMixerEffectController:int = 158
self.AudioMixerGroup:int = 159
self.AudioMixerGroupController:int = 160
self.AudioMixerSnapshot:int = 161
self.AudioMixerSnapshotController:int = 162
self.Avatar:int = 163
self.AvatarMask:int = 164
self.BaseAnimationTrack:int = 165
self.NewAnimationTrack:int = 166
self.BillboardAsset:int = 167
self.BuildReport:int = 168
self.CachedSpriteAtlas:int = 169
self.CachedSpriteAtlasRuntimeData:int = 170
self.ComputeShader:int = 171
self.DefaultAsset:int = 172
self.SceneAsset:int = 173
self.Flare:int = 174
self.Font:int = 175
self.GameObjectRecorder:int = 176
self.HumanTemplate:int = 177
self.LightProbes:int = 178
self.LightingDataAsset:int = 179
self.LightingDataAssetParent:int = 180
self.LightmapParameters:int = 181
self.Material:int = 182
self.ProceduralMaterial:int = 183
self.Mesh:int = 184
self.Motion:int = 185
self.AnimationClip:int = 186
self.PreviewAnimationClip:int = 187
self.BlendTree:int = 188
self.NavMeshData:int = 189
self.OcclusionCullingData:int = 190
self.PhysicMaterial:int = 191
self.PhysicsMaterial2D:int = 192
self.PreloadData:int = 193
self.RuntimeAnimatorController:int = 194
self.AnimatorController:int = 195
self.AnimatorOverrideController:int = 196
self.SampleClip:int = 197
self.AudioClip:int = 198
self.Shader:int = 199
self.ShaderVariantCollection:int = 200
self.SpeedTreeWindAsset:int = 201
self.Sprite:int = 202
self.SpriteAtlas:int = 203
self.SubstanceArchive:int = 204
self.TerrainData:int = 205
self.TextAsset:int = 206
self.AssemblyDefinitionAsset:int = 207
self.CGProgram:int = 208
self.MonoScript:int = 209
self.Texture:int = 210
self.BaseVideoTexture:int = 211
self.MovieTexture:int = 212
self.WebCamTexture:int = 213
self.CubemapArray:int = 214
self.LowerResBlitTexture:int = 215
self.ProceduralTexture:int = 216
self.RenderTexture:int = 217
self.CustomRenderTexture:int = 218
self.SparseTexture:int = 219
self.Texture2D:int = 220
self.Cubemap:int = 221
self.Texture2DArray:int = 222
self.Texture3D:int = 223
self.VideoClip:int = 224
self.EditorExtensionImpl:int = 225
self.EditorSettings:int = 226
self.EditorUserBuildSettings:int = 227
self.EditorUserSettings:int = 228
self.GameManager:int = 229
self.GlobalGameManager:int = 230
self.AudioManager:int = 231
self.BuildSettings:int = 232
self.CloudWebServicesManager:int = 233
self.ClusterInputManager:int = 234
self.CrashReportManager:int = 235
self.DelayedCallManager:int = 236
self.GraphicsSettings:int = 237
self.InputManager:int = 238
self.MasterServerInterface:int = 239
self.MonoManager:int = 240
self.NavMeshProjectSettings:int = 241
self.NetworkManager:int = 242
self.PerformanceReportingManager:int = 243
self.Physics2DSettings:int = 244
self.PhysicsManager:int = 245
self.PlayerSettings:int = 246
self.QualitySettings:int = 247
self.ResourceManager:int = 248
self.RuntimeInitializeOnLoadManager:int = 249
self.ScriptMapper:int = 250
self.TagManager:int = 251
self.TimeManager:int = 252
self.UnityAnalyticsManager:int = 253
self.UnityConnectSettings:int = 254
self.LevelGameManager:int = 255
self.LightmapSettings:int = 256
self.NavMeshSettings:int = 257
self.OcclusionCullingSettings:int = 258
self.RenderSettings:int = 259
self.HierarchyState:int = 260
self.InspectorExpandedState:int = 261
self.PackedAssets:int = 262
self.Prefab:int = 263
self.RenderPassAttachment:int = 264
self.SpriteAtlasDatabase:int = 265
self.TilemapEditorUserSettings:int = 266
self.Vector3f:int = 267
self.AudioMixerLiveUpdateBool:int = 268
self.bool:int = 269
self.void:int = 270
self.RootMotionData:int = 271
self.AudioMixerLiveUpdateFloat:int = 272
self.MonoObject:int = 273
self.Collision2D:int = 274
self.Polygon2D:int = 275
self.Collision:int = 276
self.float:int = 277
self.int:int = 278
class ManagedTypeIndex(object):
def __init__(self):
self.system_Boolean:int = 5
self.system_String:int = 6
self.system_Int32:int = 7
self.system_Char:int = 8
self.system_Version:int = 31
self.system_Object:int = 32
self.system_UInt32:int = 47
self.system_Int64:int = 55
self.system_Byte:int = 71
self.system_UInt16:int = 76
self.system_Guid:int = 98
self.system_Int16:int = 99
self.system_AttributeTargets:int = 188
self.system_UInt64:int = 290
self.system_Uri:int = 438
self.system_UriParser:int = 440
self.system_Single:int = 442
self.system_Double:int = 443
self.system_Exception:int = 486
self.system_Type:int = 505
self.system_RuntimeTypeHandle:int = 506
self.system_IntPtr:int = 507
self.system_Tuple:int = 551
self.system_StringBuilderExt:int = 555
self.unityeditor_PurchasingImporter:int = 681
self.system_Decimal:int = 702
self.unityengine_ILogger:int = 712
self.system_Action:int = 714
self.unityengine_GUIContent:int = 730
self.unityengine_Texture:int = 731
self.unityeditor_AnalyticsImporter:int = 751
self.unityeditor_SerializedProperty:int = 753
self.unityeditor_SerializedObject:int = 754
self.unityeditor_GUISlideGroup:int = 768
self.unityengine_GUIStyle:int = 775
self.unityengine_GUIStyleState:int = 776
self.unityengine_Texture2D:int = 777
self.unityengine_RectOffset:int = 779
self.unityengine_Font:int = 780
self.unityengine_Rect:int = 787
self.unityeditor_GenericMenu:int = 788
self.unityengine_Object:int = 807
self.unityengine_GameObject:int = 815
self.unityeditor_AdsImporter:int = 818
self.system_UIntPtr:int = 926
self.system_MulticastDelegate:int = 930
self.system_EventHandler:int = 941
self.system_AsyncCallback:int = 970
self.system_IDisposable:int = 1286
self.system_DateTime:int = 1415
self.system_TimeSpan:int = 1416
self.system_DateTimeKind:int = 1417
self.system_IFormatProvider:int = 1427
self.system_Random:int = 1688
self.unityeditor_iOSDeviceRequirement:int = 1761
self.unityeditor_BuildTarget:int = 1778
self.unityeditor_BuildTargetGroup:int = 1779
self.unityeditor_ScriptingImplementation:int = 1780
self.unityeditor_iOSBuildType:int = 1781
self.unityeditor_iOSTargetDevice:int = 1782
self.unityengine_Color:int = 1797
self.unityeditor_iOSBackgroundMode:int = 1802
self.unityeditor_RuntimeClassRegistry:int = 1835
self.unityeditor_UnityType:int = 1836
self.unityeditor_UnityTypeFlags:int = 1837
self.unityeditor_AndroidPluginImporterExtension:int = 2018
self.unityeditor_AndroidArchitecture:int = 2046
self.unityeditor_AndroidManifest:int = 2052
self.unityeditor_AndroidXmlDocument:int = 2079
self.unityeditor_ProgressTaskManager:int = 2156
self.unityeditor_ProgressHandler:int = 2157
self.unityengine_Animator:int = 2212
self.unityengine_AnimatorTransitionInfo:int = 2240
self.unityengine_Motion:int = 2247
self.unityengine_ObjectGUIState:int = 2252
self.unityengine_GUILayoutGroup:int = 2254
self.unityengine_Matrix4x4:int = 2261
self.unityengine_RenderTexture:int = 2265
self.unityengine_Vector3:int = 2266
self.unityengine_Quaternion:int = 2267
self.system_WeakReference:int = 2271
self.unityengine_IStylePainter:int = 2298
self.unityengine_Vector2:int = 2303
self.unityeditor_SplitterState:int = 2305
self.unityeditor_RenameOverlay:int = 2308
self.unityengine_EventType:int = 2309
self.unityeditor_GUIView:int = 2310
self.unityengine_EventInterests:int = 2312
self.unityeditor_DelayedCallback:int = 2314
self.unityengine_AvatarMask:int = 2325
self.unityengine_AnimatorControllerParameter:int = 2329
self.unityengine_AnimatorControllerParameterType:int = 2330
self.unityeditor_MonoScript:int = 2340
self.unityeditor_TransitionPreview:int = 2345
self.unityeditor_AvatarPreview:int = 2346
self.unityeditor_TimeControl:int = 2348
self.unityengine_Material:int = 2350
self.unityeditor_PreviewRenderUtility:int = 2351
self.unityeditor_PreviewScene:int = 2352
self.unityengine_Camera:int = 2356
self.unityeditor_SavedRenderTargetState:int = 2358
self.unityengine_Light:int = 2360
self.unityengine_Mesh:int = 2361
self.unityeditor_TimelineControl:int = 2365
self.unityeditor_TimeArea:int = 2366
self.unityeditor_TickHandler:int = 2367
self.unityeditor_Editor:int = 2379
self.unityeditor_PropertyHandlerCache:int = 2380
self.unityeditor_IPreviewable:int = 2383
self.unityeditor_OptimizedGUIBlock:int = 2384
self.unityeditor_InspectorMode:int = 2385
self.unityeditor_EditorWindow:int = 2392
self.unityeditor_HostView:int = 2394
self.unityeditor_PrefColor:int = 2395
self.unityengine_Pose:int = 2465
self.unityengine_Bounds:int = 2474
self.unityengine_MeshFilter:int = 2477
self.unityengine_MeshCollider:int = 2480
self.unityengine_MeshRenderer:int = 2483
self.unityengine_PhysicMaterial:int = 2485
self.unityengine_Transform:int = 2521
self.unityengine_PropertyName:int = 2528
self.unityengine_LayerMask:int = 2529
self.unityeditor_NetworkAnimatorEditor:int = 2539
self.unityeditor_NetworkBehaviourInspector:int = 2548
self.unityeditor_NetworkDiscoveryEditor:int = 2549
self.unityeditor_NetworkIdentityEditor:int = 2554
self.unityeditor_NetworkLobbyManagerEditor:int = 2575
self.unityeditor_NetworkManagerEditor:int = 2576
self.unityengine_AsyncOperation:int = 2600
self.unityeditor_NetworkManagerHUDEditor:int = 2601
self.unityeditor_NetworkMigrationManagerEditor:int = 2604
self.unityeditor_NetworkScenePostProcess:int = 2605
self.unityeditor_NetworkTransformChildEditor:int = 2606
self.unityengine_Rigidbody:int = 2614
self.unityengine_Rigidbody2D:int = 2615
self.unityengine_CharacterController:int = 2616
self.unityeditor_NetworkTransformEditor:int = 2617
self.unityeditor_NetworkTransformVisualizerEditor:int = 2619
self.unityengine_AnimationCurve:int = 2735
self.unityengine_Vector4:int = 2749
self.unityeditor_CurveEditor:int = 2777
self.unityeditor_ICurveEditorState:int = 2779
self.unityeditor_CurveEditorSettings:int = 2780
self.unityeditor_TickStyle:int = 2781
self.unityeditor_CurveMenuManager:int | |
components : List[str]
the degree of freedoms to constrain (e.g., '1', '123')
enforced : List[float]
the constrained value for the given node (typically 0.0)
comment : str; default=''
a comment for the card
Notes
-----
len(nodes) == len(components) == len(enforced)
.. warning:: Non-zero enforced deflection requires an SPC/SPC1 as well.
Yes, you really want to constrain the deflection to 0.0
with an SPC1 card and then reset the deflection using an
SPCD card.
"""
spc = SPCD(sid, nodes, components, enforced, comment=comment)
self._add_load_object(spc)
return spc
def add_spcadd(self, conid, sets, comment='') -> SPCADD:
"""Creates a SPCADD card"""
spcadd = SPCADD(conid, sets, comment=comment)
self._add_constraint_spcadd_object(spcadd)
return spcadd
def add_spcax(self, conid, ringax, hid, component, enforced, comment='') -> SPCAX:
"""Creates an SPCAX card"""
spcax = SPCAX(conid, ringax, hid, component, enforced, comment=comment)
self._add_constraint_spc_object(spcax)
return spcax
def add_gmspc(self, conid, component, entity, entity_id, comment='') -> GMSPC:
"""Creates a GMSPC card"""
spc = GMSPC(conid, component, entity, entity_id, comment=comment)
self._add_constraint_spc_object(spc)
return spc
def add_mpc(self, conid: int, nodes: List[int], components: List[str], coefficients: List[float],
comment: str='') -> MPC:
"""
Creates an MPC card
Parameters
----------
conid : int
Case Control MPC id
nodes : List[int]
GRID/SPOINT ids
components : List[str]
the degree of freedoms to constrain (e.g., '1', '123')
coefficients : List[float]
the scaling coefficients
"""
mpc = MPC(conid, nodes, components, coefficients, comment=comment)
self._add_constraint_mpc_object(mpc)
return mpc
def add_mpcadd(self, conid, sets, comment='') -> MPCADD:
"""Creates an MPCADD card"""
mpcadd = MPCADD(conid, sets, comment=comment)
self._add_constraint_mpcadd_object(mpcadd)
return mpcadd
def add_suport(self, nodes, Cs, comment='') -> SUPORT:
"""
Creates a SUPORT card, which defines free-body reaction points.
This is always active.
Parameters
----------
nodes : List[int]
the nodes to release
Cs : List[str]
compoents to support at each node
comment : str; default=''
a comment for the card
"""
suport = SUPORT(nodes, Cs, comment=comment)
self._add_suport_object(suport)
return suport
def add_suport1(self, conid, nodes, Cs, comment='') -> SUPORT1:
"""
Creates a SUPORT card, which defines free-body reaction points.
Parameters
----------
conid : int
Case Control SUPORT id
nodes : List[int]
the nodes to release
Cs : List[str]
compoents to support at each node
comment : str; default=''
a comment for the card
"""
suport1 = SUPORT1(conid, nodes, Cs, comment=comment)
self._add_suport1_object(suport1)
return suport1
def add_aeros(self, cref, bref, sref, acsid=0, rcsid=0, sym_xz=0, sym_xy=0,
comment='') -> AEROS:
"""
Creates an AEROS card
Parameters
----------
cref : float
the aerodynamic chord
bref : float
the wing span
sref : float
the wing area
acsid : int; default=0
aerodyanmic coordinate system
rcsid : int; default=0
coordinate system for rigid body motions
sym_xz : int; default=0
xz symmetry flag (+1=symmetry; -1=antisymmetric)
sym_xy : int; default=0
xy symmetry flag (+1=symmetry; -1=antisymmetric)
comment : str; default=''
a comment for the card
"""
aeros = AEROS(cref, bref, sref, acsid=acsid, rcsid=rcsid,
sym_xz=sym_xz, sym_xy=sym_xy, comment=comment)
self._add_aeros_object(aeros)
return aeros
def add_aero(self, velocity: float, cref: float, rho_ref: float,
acsid: int=0, sym_xz: int=0, sym_xy: int=0,
comment: str='') -> AERO:
"""
Creates an AERO card
Parameters
----------
velocity : float
the airspeed
cref : float
the aerodynamic chord
rho_ref : float
FLFACT density scaling factor
acsid : int; default=0
aerodyanmic coordinate system
sym_xz : int; default=0
xz symmetry flag (+1=symmetry; -1=antisymmetric)
sym_xy : int; default=0
xy symmetry flag (+1=symmetry; -1=antisymmetric)
comment : str; default=''
a comment for the card
"""
aero = AERO(velocity, cref, rho_ref, acsid=acsid, sym_xz=sym_xz, sym_xy=sym_xy,
comment=comment)
self._add_aero_object(aero)
return aero
def add_caero1(self, eid: int, pid: int, igroup: int,
p1: NDArray3float, x12: float,
p4: NDArray3float, x43: float,
cp: int=0,
nspan: int=0, lspan: int=0,
nchord: int=0, lchord: int=0, comment: str='') -> CAERO1:
"""
Defines a CAERO1 card, which defines a simplified lifting surface
(e.g., wing/tail).
Parameters
----------
eid : int
element id
pid : int
int : PAERO1 ID
igroup : int
Group number
p1 : (1, 3) ndarray float
xyz location of point 1 (leading edge; inboard)
p4 : (1, 3) ndarray float
xyz location of point 4 (leading edge; outboard)
x12 : float
distance along the flow direction from node 1 to node 2; (typically x, root chord)
x43 : float
distance along the flow direction from node 4 to node 3; (typically x, tip chord)
cp : int; default=0
int : coordinate system
nspan : int; default=0
int > 0 : N spanwise boxes distributed evenly
int = 0 : use lchord
nchord : int; default=0
int > 0 : N chordwise boxes distributed evenly
int = 0 : use lchord
lspan : int, AEFACT; default=0
int > 0 : AEFACT reference for non-uniform nspan
int = 0 : use nspan
lchord : int, AEFACT; default=0
int > 0 : AEFACT reference for non-uniform nchord
int = 0 : use nchord
comment : str; default=''
a comment for the card
"""
caero = CAERO1(eid, pid, igroup, p1, x12, p4, x43, cp=cp,
nspan=nspan, lspan=lspan, nchord=nchord, lchord=lchord,
comment=comment)
self._add_caero_object(caero)
return caero
def add_caero2(self, eid: int, pid: int, igroup: int,
p1: List[float], x12: float,
cp: int=0,
nsb: int=0, nint: int=0,
lsb: int=0, lint: int=0, comment: str='') -> CAERO2:
"""
Defines a CAERO2 card, which defines a slender body
(e.g., fuselage/wingtip tank).
Parameters
----------
eid : int
element id
pid : int, PAERO2
int : PAERO2 ID
igroup : int
Group number
p1 : (1, 3) ndarray float
xyz location of point 1 (forward position)
x12 : float
length of the CAERO2
cp : int; default=0
int : coordinate system
nsb : int; default=0
Number of slender body elements
lsb : int; default=0
AEFACT id for defining the location of the slender body elements
nint : int; default=0
Number of interference elements
lint : int; default=0
AEFACT id for defining the location of interference elements
comment : str; default=''
a comment for the card
"""
caero = CAERO2(eid, pid, igroup, p1, x12, cp=cp, nsb=nsb, nint=nint, lsb=lsb,
lint=lint, comment=comment)
self._add_caero_object(caero)
return caero
def add_caero3(self, eid, pid, list_w, p1, x12, p4, x43,
cp=0, list_c1=None, list_c2=None, comment='') -> CAERO3:
"""Creates a CAERO3 card"""
caero = CAERO3(eid, pid, list_w, p1, x12, p4, x43,
cp=cp, list_c1=list_c1, list_c2=list_c2, comment=comment)
self._add_caero_object(caero)
return caero
def add_caero4(self, eid, pid, p1, x12, p4, x43,
cp=0, nspan=0, lspan=0, comment='') -> CAERO4:
"""
Defines a CAERO4 card, which defines a strip theory surface.
Parameters
----------
eid : int
element id
pid : int
int : PAERO4 ID
p1 : (1, 3) ndarray float
xyz location of point 1 (leading edge; inboard)
p4 : (1, 3) ndarray float
xyz location of point 4 (leading edge; outboard)
x12 : float
distance along the flow direction from node 1 to node 2
(typically x, root chord)
x43 : float
distance along the flow direction from node 4 to node 3
(typically x, tip chord)
cp : int; default=0
int : coordinate system
nspan : int; default=0
int > 0 : N spanwise boxes distributed evenly
int = 0 : use lchord
lspan : int; default=0
int > 0 : AEFACT reference for non-uniform nspan
int = 0 : use nspan
comment : str; default=''
a comment for the card
"""
caero = CAERO4(eid, pid, p1, x12, p4, x43,
cp=cp, nspan=nspan, lspan=lspan, comment=comment)
self._add_caero_object(caero)
return caero
def add_caero5(self, eid: int, pid: int,
p1: List[float], x12: float,
p4: List[float], x43: float,
cp: int=0,
nspan: int=0, lspan: int=0,
ntheory: int=0,
nthick: int=0, comment: str='') -> CAERO5:
"""Creates a CAERO5 card"""
caero = CAERO5(eid, pid, p1, x12, p4, x43, cp=cp, nspan=nspan, lspan=lspan,
ntheory=ntheory, nthick=nthick, comment=comment)
self._add_caero_object(caero)
return caero
def add_caero7(self, eid: int, label: str,
p1: np.ndarray, x12: float,
p4: np.ndarray, x43: float,
cp: int=0, nspan: int=0,
nchord: int=0, lspan: int=0,
p_airfoil: Any=None, ztaic: Any=None, comment: str='') -> CAERO7:
caero = CAERO7(eid, label, p1, x12, p4, x43,
cp=cp, nspan=nspan,
nchord=nchord, lspan=lspan,
p_airfoil=p_airfoil, ztaic=ztaic, comment='')
self._add_caero_object(caero)
return caero
def add_paero1(self, pid, caero_body_ids=None, comment='') -> PAERO1:
"""
Creates a PAERO1 card, which defines associated bodies for the
panels in the Doublet-Lattice method.
Parameters
----------
pid : int
PAERO1 id
caero_body_ids : List[int]; default=None
CAERO2 ids that are within the | |
<filename>Keysight_M8195_AWG/Keysight_M8195_AWG.py
#!/usr/bin/env python
import InstrumentDriver
from VISA_Driver import VISA_Driver
import numpy as np
class Driver(VISA_Driver):
"""This class implements the Keysight M8195
The driver currently only implements operations on extended memory.
"""
# define channels and markers used in various configurations
CHANNEL_MARKER = {'Single channel (1)': ([1], []),
'Single channel (1) + markers (3,4)': ([1], [3, 4]),
'Dual channel (1,4)': ([1, 4], []),
'Dual channel duplicate (1-3,2-4)': ([1, 2], []),
'Dual channel (1,2) + markers (3,4)': ([1, 2], [3, 4]),
'Four channel': ([1, 2, 3, 4], [])}
def performOpen(self, options={}):
"""Perform the operation of opening the instrument connection"""
# start by calling the generic VISA open to make sure we have a connection
VISA_Driver.performOpen(self, options)
# configure AWG settings
self.configure_awg()
def initSetConfig(self):
"""This function is run before setting values in Set Config"""
# re-configure AWG before setting values
self.configure_awg()
def configure_awg(self):
"""Clear waveform and configure AWG to work with Labber"""
# init vectors with old values
self.n_ch = 4
self.wave_updated = False
self.n_prev_seq = -1
self.is_running = False
self.data = [np.array([], dtype=np.int8) for n1 in range(self.n_ch)]
# turn off run mode and delete all old data
self.writeAndLog(':ABOR')
self.writeAndLog(':TRAC:DEL:ALL')
# make all channels use external memory
self.writeAndLog(':TRACE1:MMOD EXT')
self.writeAndLog(':TRACE2:MMOD EXT')
self.writeAndLog(':TRACE3:MMOD EXT')
self.writeAndLog(':TRACE4:MMOD EXT')
# turn off waveform scaling
self.writeAndLog(':TRACE1:IMP:SCAL 0')
self.writeAndLog(':TRACE2:IMP:SCAL 0')
self.writeAndLog(':TRACE3:IMP:SCAL 0')
self.writeAndLog(':TRACE4:IMP:SCAL 0')
# use arbitrary mode, and automatically advance after waveform ends
self.writeAndLog(':FUNC:MODE ARB')
def performSetValue(self, quant, value, sweepRate=0.0, options={}):
"""Perform the Set Value instrument operation. This function should
return the actual value set by the instrument"""
# keep track of if waveform is updated, to avoid sending it many times
if self.isFirstCall(options):
self.wave_updated = False
# # if sequence mode, make sure the buffer contains enough waveforms
# if self.isHardwareLoop(options):
# (seq_no, n_seq) = self.getHardwareLoopIndex(options)
# # if first call, clear sequence and create buffer
# if seq_no==0:
# # variable for keepin track of sequence updating
# self.writeAndLog(':AWGC:STOP;')
# self.bSeqUpdate = False
# # if different sequence length, re-create buffer
# if seq_no==0 and n_seq != len(self.lOldU16):
# self.lOldU16 = [[np.array([], dtype=np.uint16) \
# for n1 in range(self.n_ch)] for n2 in range(n_seq)]
# elif self.isHardwareTrig(options):
# # if hardware triggered, always stop outputting before setting
# self.writeAndLog(':AWGC:STOP;')
# check what type of quantity to set
if quant.name == 'Run mode':
# run mode is handled by two commands
indx = quant.getValueIndex(value)
self.writeAndLog(':INIT:CONT ' + ('1' if indx == 0 else '0'))
self.writeAndLog(':INIT:GATE ' + ('1' if indx == 2 else '0'))
elif quant.name == 'Channel mode':
# stop AWG
self.stop_awg()
# before changing, make sure sample rate divider is compatible
self.writeAndLog(':INST:DACM SING')
n_ch = len(self.CHANNEL_MARKER[value][0])
if n_ch >= 4:
# four channels, force divider to be 4
self.writeAndLog(':INST:MEM:EXT:RDIV DIV4')
elif n_ch >= 2:
# two channels, force divider to be 2
self.writeAndLog(':INST:MEM:EXT:RDIV DIV2')
self.writeAndLog(':TRACE1:MMOD EXT')
self.writeAndLog(':TRACE2:MMOD EXT')
self.writeAndLog(':TRACE3:MMOD EXT')
self.writeAndLog(':TRACE4:MMOD EXT')
# run standard VISA case for setting channel mode
value = VISA_Driver.performSetValue(self, quant, value, sweepRate,
options=options)
# after setting, update memory mode for all channels
self.writeAndLog(':TRACE1:MMOD EXT')
self.writeAndLog(':TRACE2:MMOD EXT')
self.writeAndLog(':TRACE3:MMOD EXT')
self.writeAndLog(':TRACE4:MMOD EXT')
elif quant.name.startswith('Sample rate divider'):
# stop AWG before changing
self.stop_awg()
value = VISA_Driver.performSetValue(self, quant, value, sweepRate,
options=options)
elif quant.name in ('Ch 1', 'Ch 2', 'Ch 3', 'Ch 4'):
# convert and store new waveform, then mark as need of update
ch = int(quant.name.split('Ch ')[1])
v_pp = self.getValue('Ch%d - Range' % ch)
self.data[ch - 1] = self.scaleWaveformToI8(value['y'], v_pp, ch)
self.wave_updated = True
elif quant.name in ('Run'):
self.start_awg(wait_for_start=False)
else:
# for all other cases, call VISA driver
value = VISA_Driver.performSetValue(self, quant, value, sweepRate,
options=options)
# if final call and wave is updated, send it to AWG
if self.isFinalCall(options) and self.wave_updated:
# send waveforms, check if hardware loop
if self.isHardwareLoop(options):
(seq, n_seq) = self.getHardwareLoopIndex(options)
self.reportStatus('Sending waveform (%d/%d)' % (seq+1, n_seq))
self.send_waveforms(seq=seq, n_seq=n_seq)
else:
self.send_waveforms()
# start if not triggered
if not self.isHardwareTrig(options):
self.start_awg()
return value
def performGetValue(self, quant, options={}):
"""Perform the Get Value instrument operation"""
# check type of quantity
if quant.name in ('Ch 1', 'Ch 2', 'Ch 3', 'Ch 4'):
# do nothing here
value = quant.getValue()
if quant.name == 'Run mode':
# run mode is handled by two commands
cont = int(self.askAndLog(':INIT:CONT?'))
gate = int(self.askAndLog(':INIT:GATE?'))
if cont:
value = 'Continuous'
elif gate:
value = 'Gated'
else:
value = 'Triggered'
else:
# for all other cases, call VISA driver
value = VISA_Driver.performGetValue(self, quant, options)
return value
def performClose(self, bError=False, options={}):
"""Perform the close instrument connection operation"""
try:
# try to stop awg before closing communication
for n in range(self.n_ch):
self.writeAndLog(':OUTP%d 0' % (n + 1))
self.stop_awg()
except:
pass
# close VISA connection
VISA_Driver.performClose(self, bError, options)
def stop_awg(self):
"""Stop AWG and mark as stopped"""
if self.is_running:
self.writeAndLog(':ABOR')
self.is_running = False
def start_awg(self, wait_for_start=True):
"""Start AWG and make sure instrument is running"""
if wait_for_start:
# send command to turn on run mode to AWG
self.writeAndLog('*CLS')
self.writeAndLog('INIT:IMM')
# wait for output to be turned on again
iRunState = int(self.askAndLog(':STAT:OPER:COND?'))
nTry = 20
while nTry>0 and iRunState==0 and not self.isStopped():
# sleep for while to save resources, then try again
self.wait(0.1)
# try again
iRunState = int(self.askAndLog(':STAT:OPER:COND?'))
nTry -= 1
# check if timeout occurred
if nTry <= 0:
# timeout
raise InstrumentDriver.Error('Cannot turn on Run mode')
else:
# don't wait for run, just start
self.writeAndLog('INIT:IMM')
# mark as running
self.is_running = True
def send_waveforms(self, seq=None, n_seq=1):
"""Rescale and send waveform data to the AWG"""
# check channels in use
channels = self.CHANNEL_MARKER[self.getValue('Channel mode')][0]
# get number of elements
n_elements = [len(self.data[ch - 1]) for ch in channels]
self.n_elem = max(n_elements)
# check if sequence mode or normal run mode
if seq is None:
# stop AWG, delete all segments, create empty waveforms
self.stop_awg()
self.writeAndLog(':TRAC:DEL:ALL')
# go through and send waveform on all channels in use
for ch in channels:
self.sendWaveformToAWG(ch)
# set up segment
self.writeAndLog(':TRAC:ADV AUTO')
self.writeAndLog(':TRAC:SEL 1')
self.writeAndLog(':TRAC:COUN 1')
else:
# sequence mode, set up sequences
pass
def sendWaveformToAWG(self, ch, seq=None):
"""Send waveform to AWG"""
# check if sequence
if seq is None:
seq = 1
# get data and markers
vI8 = self.data[ch - 1]
markers = self.CHANNEL_MARKER[self.getValue('Channel mode')][1]
if ch == 1 and len(markers) > 0:
# markers are always ch 3 and ch 4
m1 = self.data[2]
m2 = self.data[3]
if len(vI8) == 0:
# no data, but output zeros to match markers
vI8 = np.zeros((self.n_elem,), dtype=np.int8)
else:
m1 = []
m2 = []
# seems like a zero waveform need to be sent to remove old data
if len(vI8) == 0:
vI8 = np.zeros((self.n_elem,), dtype=np.int8)
# self.writeAndLog(':TRAC%d:DEF 1,%d,0' % (ch, self.n_elem))
# return
# make sure length of all data and markeres are the same
if (len(m1) > 0 and len(vI8) != len(m1)) or \
(len(m2) > 0 and len(vI8) != len(m2)) or \
(self.n_elem > 0 and len(vI8) != self.n_elem):
raise InstrumentDriver.Error(\
'All channels need to have the same number of elements')
# proceed depending on marker or no marker
if ch == 1 and len(markers) > 0:
# create marker vector
mI8 = np.zeros((self.n_elem,), dtype=np.int8)
for m, marker in enumerate([m1, m2]):
# only add if marker has data
if len(marker) == len(vI8):
# get marker trace, with bit shifts
mI8 += (2 ** m) * np.array(marker != 0, dtype=np.int8)
# combine data and marker to one vector
vI8 = np.reshape(np.c_[vI8, mI8], [2 * self.n_elem,])
# define trace
self.writeAndLog(':TRAC%d:DEF 1,%d' % (ch, self.n_elem))
# create binary data as bytes with header
start, length = 0, len(vI8)
sLen = b'%d' % length
sHead = b'#%d%s' % (len(sLen), sLen)
# send to AWG
sCmd = b':TRAC%d:DATA %d,%d,' % (ch, seq, start)
self.write_raw(sCmd + sHead + vI8[start:start+length].tobytes())
def scaleWaveformToI8(self, vData, v_pp, ch):
"""Scales the waveform and returns data in a string of U16"""
Vamp = v_pp / 2.0
# make sure waveform data is within the voltage range
truncate = self.getValue('Truncate waveform if out of range')
if (not truncate) and (np.sum(vData > Vamp) or np.sum(vData | |
<gh_stars>0
# script for generate analysis for datasets
import os
import json
from typing import Tuple
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from functools import partial
from utils.data import Dataset
from utils.data import create_adult_dataset, create_bank_dataset
from utils.data import create_communities_dataset, create_compas_dataset
from utils.data import create_german_dataset, create_titanic_dataset
from utils.generator import gen_complete_random
from utils.completer import complete_by_mean_col, complete_by_mean_col_v2
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.metrics import confusion_matrix, accuracy_score
from imblearn.over_sampling import SMOTE
PLOT_DROP = False
PLOT_IMPUTE = False
PLOT_SCATTER = False
PLOT_DROP_SINGLE = False
PLOT_DROP_EXCLUDE = False
PLOT_ADULT = True
PLOT_COMPAS = True
PLOT_TITANIC = True
PLOT_GERMAN = True
PLOT_COMMUNITIES = True
PLOT_BANK = True
def newBias(data, A=1, B=1):
# Pr(AA is labeled as low risk when he is actually high risk) = Pr(Caucasian is labeled as low risk when actually high risk)
# Pr(AA is labeled as high risk when he is low risk) = Pr(Caucasian is labeled as high risk when actually low risk)
# bias = |LHS - RHS|
# A*|LHS - RHS of first type| + B*|LHS - RHS of second type|
# A*|FPR_A - FPR_B| + B*|FNR_A - FNR_C|
FPR_A = data[1] / (data[1] + data[0])
FNR_A = data[2] / (data[2] + data[3])
FPR_B = data[5] / (data[5] + data[4])
FNR_B = data[6] / (data[6] + data[7])
bias = A*abs(FPR_A - FPR_B) + B*abs(FNR_A - FNR_B)
return bias
def cross_val(data_original: Dataset, data_config, clf_config, complete_function=None, selected_cols=[]):
bias = []
acc = []
smote = SMOTE()
scaler = StandardScaler()
for i in range(10):
if complete_function: data = gen_complete_random(data_original, random_ratio=0.4, selected_cols=selected_cols)
else: data = data_original
print("Running Cross Validation {}".format(i))
bias_cv = []
acc_cv = []
for train_idx, test_idx in StratifiedShuffleSplit(n_splits=20).split(data.X, data.y):
X_train, X_test = data.X.iloc[train_idx].copy(), data.X.iloc[test_idx].copy()
Y_train, Y_test = data.y[train_idx], data.y[test_idx]
X_train.reset_index(drop=True, inplace=True)
X_test.reset_index(drop=True, inplace=True)
if complete_function:
data_incomplete = Dataset("tmp", X_train, Y_train, types=data.types,
protected_features=data.protected_features, categorical_features=data.categorical_features,
encoders=[data.X_encoders, data.y_encoder])
try:
data_complete = complete_function(data_incomplete)
except Exception as e:
print("Error: {}. Skipped".format(e))
continue
if data_complete.X.isnull().sum().sum() > 0:
print("Complete function error, skipped")
continue
X_train = data_complete.X.copy()
Y_train = data_complete.y.copy()
X_train.drop(columns=data.protected_features, inplace=True)
if complete_function:
data_incomplete = Dataset("tmp", X_test, Y_test, types=data.types,
protected_features=data.protected_features, categorical_features=data.categorical_features,
encoders=[data.X_encoders, data.y_encoder])
try:
data_complete = complete_function(data_incomplete)
except Exception as e:
print("Error: {}. Skipped".format(e))
continue
if data_complete.X.isnull().sum().sum() > 0:
print("Complete function error, skipped")
continue
X_test = data_complete.X.copy()
Y_test = data_complete.y.copy()
X_train_res, Y_train_res = smote.fit_resample(X_train, Y_train)
X_scaled = scaler.fit_transform(X_train_res)
clf = LogisticRegression(max_iter=clf_config["max_iter"], C=clf_config["C"], tol=clf_config["tol"])
clf.fit(X_scaled, Y_train_res)
X_test_scaled = pd.DataFrame(scaler.transform(X_test.drop(columns=data.protected_features)), columns=X_test.drop(columns=data.protected_features).columns)
X_test_scaled = pd.concat([X_test_scaled, X_test[data.protected_features]], axis=1)
X_test_A = X_test_scaled[X_test_scaled[data_config["target"]] == data_config["A"]].drop(columns=data.protected_features).to_numpy()
X_test_B = X_test_scaled[X_test_scaled[data_config["target"]] == data_config["B"]].drop(columns=data.protected_features).to_numpy()
Y_test_A = Y_test[X_test_scaled[X_test_scaled[data_config["target"]] == data_config["A"]].index.tolist()]
Y_test_B = Y_test[X_test_scaled[X_test_scaled[data_config["target"]] == data_config["B"]].index.tolist()]
matrix_A = confusion_matrix(Y_test_A, clf.predict(X_test_A)).ravel().tolist()
matrix_B = confusion_matrix(Y_test_B, clf.predict(X_test_B)).ravel().tolist()
try:
bias_cv.append(newBias(matrix_A+matrix_B))
except Exception as e:
print("\tError: {}, skipped".format(e))
acc_cv.append(accuracy_score(clf.predict(X_test_scaled.drop(columns=data.protected_features).to_numpy()), Y_test))
bias.append(np.mean(bias_cv))
acc.append(np.mean(acc_cv))
return (np.mean(bias), np.mean(acc))
def drop_na(data: Dataset) -> Dataset:
data = data.copy()
tmp_concat = pd.concat([data.X, pd.DataFrame(data.y, columns=["_TARGET_"])], axis=1)
tmp_concat.dropna(inplace=True)
tmp_concat.reset_index(drop=True, inplace=True)
data.X = tmp_concat.drop(columns=["_TARGET_"]).copy()
data.y = tmp_concat["_TARGET_"].copy().to_numpy().ravel()
return data
def convert_protected(data: Dataset) -> Tuple[Dataset, LabelEncoder]:
data = data.copy()
encoder = LabelEncoder()
for feature in data.protected_features:
data.X[feature] = encoder.fit_transform(data.X[feature])
return data, encoder
def concat(data: Dataset) -> pd.DataFrame:
data = data.copy()
return pd.concat([data.X, pd.DataFrame(data.y, columns=["_TARGET_"])], axis=1)
def analysis_drop_correlated_features(data_fn, folder, filename):
if not os.path.exists(folder):
os.makedirs(folder)
with open("params_datasets.json", "r") as inFile:
dataConfig = json.load(inFile)
with open("params_acc.json", "r") as inFile:
clfConfig = json.load(inFile)
data: Dataset = drop_na(data_fn())
cdata, encoder = convert_protected(data)
ccdata = concat(cdata)
print("Dataset: {}".format(data.name))
dataConfig = dataConfig[data.name]
clfConfig = clfConfig[data.name]["LogReg"]
correlation = ccdata.corr()[data.protected_features[0]]
correlation = correlation[correlation.abs().sort_values(ascending=False).head(15).index]
if "_TARGET_" in correlation.keys():
del correlation["_TARGET_"]
del correlation[data.protected_features[0]]
print("Correlation with protected attribute:")
for key, val in correlation.items():
print("\tFeature: {:<30} Corr: {:.4f}".format(key, val))
print("Computing accuracy and bias by drop")
correlated_features = np.array(correlation.keys())
plot_bias = []
plot_acc = []
for i in range(len(correlated_features)):
print("Drop {:<2} most correlated features".format(i))
data_tmp = data.copy()
data_tmp.X.drop(columns=correlated_features[range(i)], inplace=True)
# print(data_tmp.X.columns)
bias, acc = cross_val(data_tmp, dataConfig, clfConfig)
plot_bias.append(bias)
plot_acc.append(acc)
print("Generating plots")
fig, axes = plt.subplots(3, 1, figsize=(5, 16))
plot_pos = np.arange(len(correlated_features))
axes[0].barh(plot_pos, correlation.abs(), align='center', height=0.5, tick_label=correlated_features)
axes[0].set_xlabel("Absolute Correlation with Protected Attribute")
axes[1].bar(plot_pos, plot_bias, tick_label=[str(i) for i in range(len(correlated_features))], width=0.8, align="center")
axes[1].set_xlabel("Features Dropped")
axes[1].set_ylabel("Bias")
axes[1].set_ylim([0.0, 1.0])
for i, val in enumerate(plot_bias):
axes[1].text(i, val+0.05, "{:.2f}".format(val), horizontalalignment='center')
axes[2].bar(plot_pos, plot_acc, tick_label=[str(i) for i in range(len(correlated_features))], width=0.8, align="center")
axes[2].set_xlabel("Features Dropped")
axes[2].set_ylabel("Accuracy")
axes[2].set_ylim([0.0, 1.2])
for i, val in enumerate(plot_acc):
axes[2].text(i, val+0.05, "{:.2f}".format(val), horizontalalignment='center')
fig.suptitle("Most Correlated Feature Drop Experiment ({})".format(data.name))
plt.subplots_adjust(top=0.94)
fig.savefig(os.path.join(folder, filename), transparent=False, bbox_inches='tight', pad_inches=0.1)
plt.show(block=False)
plt.pause(2)
plt.close()
print("Done")
def analysis_impute_correlated_features(data_fn, folder, filename):
if not os.path.exists(folder):
os.makedirs(folder)
with open("params_datasets.json", "r") as inFile:
dataConfig = json.load(inFile)
with open("params_acc.json", "r") as inFile:
clfConfig = json.load(inFile)
data: Dataset = drop_na(data_fn())
cdata, encoder = convert_protected(data)
ccdata = concat(cdata)
print("Dataset: {}".format(data.name))
dataConfig = dataConfig[data.name]
clfConfig = clfConfig[data.name]["LogReg"]
correlation = ccdata.corr()[data.protected_features[0]]
correlation = correlation[correlation.abs().sort_values(ascending=False).head(15).index]
if "_TARGET_" in correlation.keys():
del correlation["_TARGET_"]
del correlation[data.protected_features[0]]
print("Correlation with protected attribute:")
for key, val in correlation.items():
print("\tFeature: {:<30} Corr: {:.4f}".format(key, val))
print("Computing accuracy and bias by MCAR and Mean Imputation")
correlated_features = np.array(correlation.keys())
plot_bias = []
plot_acc = []
for i in range(len(correlated_features)):
print("Impute on {:<2} most correlated features".format(i))
data_tmp = data.copy()
# data_tmp.X.drop(columns=correlated_features[range(i)], inplace=True)
# data_tmp = gen_complete_random(data_tmp, random_ratio=0.2, selected_cols=correlated_features[range(i)])
bias, acc = cross_val(data_tmp, dataConfig, clfConfig, complete_by_mean_col, correlated_features[range(i)])
plot_bias.append(bias)
plot_acc.append(acc)
print("Generating plots")
fig, axes = plt.subplots(3, 1, figsize=(5, 16))
plot_pos = np.arange(len(correlated_features))
axes[0].barh(plot_pos, correlation.abs(), align='center', height=0.5, tick_label=correlated_features)
axes[0].set_xlabel("Absolute Correlation with Protected Attribute")
axes[1].bar(plot_pos, plot_bias, tick_label=[str(i) for i in range(len(correlated_features))], width=0.8, align="center")
axes[1].set_xlabel("Features Imputed")
axes[1].set_ylabel("Bias")
axes[1].set_ylim([0.0, 1.0])
for i, val in enumerate(plot_bias):
axes[1].text(i, val+0.05, "{:.2f}".format(val), horizontalalignment='center')
axes[2].bar(plot_pos, plot_acc, tick_label=[str(i) for i in range(len(correlated_features))], width=0.8, align="center")
axes[2].set_xlabel("Features Imputed")
axes[2].set_ylabel("Accuracy")
axes[2].set_ylim([0.0, 1.2])
for i, val in enumerate(plot_acc):
axes[2].text(i, val+0.05, "{:.2f}".format(val), horizontalalignment='center')
fig.suptitle("Most Correlated Feature Impute Experiment ({})".format(data.name))
plt.subplots_adjust(top=0.94)
fig.savefig(os.path.join(folder, filename), transparent=False, bbox_inches='tight', pad_inches=0.1)
plt.show(block=False)
plt.pause(2)
plt.close()
print("Done")
def analysis_scatter_correlated_features(data_fn, folder, filename):
if not os.path.exists(folder):
os.makedirs(folder)
data: Dataset = drop_na(data_fn())
cdata, encoder = convert_protected(data)
ccdata = concat(cdata)
print("Dataset: {}".format(data.name))
print("Plotting correlation of features with target & protected")
correlation_protected = ccdata.corr()[data.protected_features[0]]
del correlation_protected["_TARGET_"]
del correlation_protected[data.protected_features[0]]
correlation_target = ccdata.corr()["_TARGET_"]
del correlation_target["_TARGET_"]
del correlation_target[data.protected_features[0]]
plotX = []
plotY = []
for key in correlation_protected.keys():
plotX.append(correlation_protected[key])
plotY.append(correlation_target[key])
plotX = np.abs(np.array(plotX))
plotY = np.abs(np.array(plotY))
plt.figure(figsize=(10, 10))
plt.scatter(plotX, plotY, s=200, alpha=0.8)
for i, val in enumerate(correlation_protected.keys()):
plt.text(plotX[i], plotY[i], "{}".format(i+1), horizontalalignment='center', verticalalignment='center')
plt.xlabel("Protected Feature Correlation")
plt.ylabel("Target Correlation")
plt.xlim([-0.1, 1.1])
plt.ylim([-0.1, 1.1])
plt.title("Correlation Plot ({})".format(data.name))
plt.savefig(os.path.join(folder, filename), transparent=False, bbox_inches='tight', pad_inches=0.1)
plt.show(block=False)
plt.pause(2)
plt.close()
with open(os.path.join(folder, "{}.txt".format(filename)), "w") as outFile:
for i, val in enumerate(correlation_protected.keys()):
print("{:<2}: {}".format(i+1, val), file=outFile)
print("Done")
def analysis_drop_correlated_features_single(data_fn, folder, filename, draw_original=True, draw_impute_v1=True, draw_impute_v2=True):
if not os.path.exists(folder):
os.makedirs(folder)
with open("params_datasets.json", "r") as inFile:
dataConfig = json.load(inFile)
with open("params_acc.json", "r") as inFile:
clfConfig = json.load(inFile)
data: Dataset = drop_na(data_fn())
cdata, encoder = convert_protected(data)
ccdata = concat(cdata)
print("Dataset: {}".format(data.name))
dataConfig = dataConfig[data.name]
clfConfig = clfConfig[data.name]["LogReg"]
print("Computing bias & accuracy for each single feature (20 most correlated with protected)")
correlation = ccdata.corr()[data.protected_features[0]]
del correlation["_TARGET_"]
del correlation[data.protected_features[0]]
correlation = correlation[correlation.abs().sort_values(ascending=False).head(20).index]
if draw_original:
plotX = [] # bias
plotY = [] # accuracy
for key in correlation.keys():
print("Compute on single feature {}".format(key))
data_tmp = data.copy()
data_tmp.X.drop(columns=[f for f in correlation.keys() if f != key], inplace=True)
bias, acc = cross_val(data_tmp, dataConfig, clfConfig)
plotX.append(acc)
plotY.append(bias)
plotY_compare, plotX_compare = cross_val(data.copy(), dataConfig, clfConfig)
plotX = np.abs(np.array(plotX))
plotY = np.abs(np.array(plotY))
plt.figure(figsize=(10, 10))
# plt.scatter(plotX, plotY, s=200, alpha=0.8)
plt.ylim([0.0, 1.2])
plt.xlim([0.4, 1.0])
sns.regplot(x=plotX, y=plotY, scatter_kws={"s": 200, "alpha": 0.8}, fit_reg=True, truncate=False)
plt.scatter([plotX_compare], [plotY_compare], s=200, alpha=1.0, c="orange")
for i, _ in enumerate(correlation.keys()):
plt.text(plotX[i], plotY[i], "{}".format(i+1), horizontalalignment='center', verticalalignment='center')
plt.ylabel("Bias")
plt.xlabel("Accuracy")
plt.title("Most Correlated Single Feature Experiment ({})".format(data.name))
plt.savefig(os.path.join(folder, filename+".png"), transparent=False, bbox_inches='tight', pad_inches=0.1)
plt.show(block=False)
plt.pause(2)
plt.close()
if draw_impute_v1:
plotX = [] # bias
plotY = [] # accuracy
for key in correlation.keys():
print("Compute on single feature {} (Impute V1)".format(key))
data_tmp = data.copy()
# data_tmp = gen_complete_random(data_tmp, random_ratio=0.4, selected_cols=[f for f in correlation.keys() if f != key])
# data_tmp.X.drop(columns=[f for f in correlation.keys() if f != key], inplace=True)
bias, acc = cross_val(data_tmp, dataConfig, clfConfig, complete_by_mean_col, [f for f in correlation.keys() if f != key])
plotX.append(acc)
plotY.append(bias)
plotY_compare, plotX_compare = cross_val(data.copy(), dataConfig, clfConfig)
plotX = np.abs(np.array(plotX))
plotY = np.abs(np.array(plotY))
plt.figure(figsize=(10, 10))
# plt.scatter(plotX, plotY, s=200, alpha=0.8)
plt.ylim([0.0, 1.2])
plt.xlim([0.4, 1.0])
sns.regplot(x=plotX, y=plotY, scatter_kws={"s": 200, "alpha": 0.8}, fit_reg=True, truncate=False)
plt.scatter([plotX_compare], [plotY_compare], s=200, alpha=1.0, c="orange")
for i, _ in enumerate(correlation.keys()):
plt.text(plotX[i], plotY[i], "{}".format(i+1), horizontalalignment='center', verticalalignment='center')
plt.ylabel("Bias")
plt.xlabel("Accuracy")
plt.title("Most Correlated Single Feature Experiment | |
first two assumptions are checked. The third is not checked
and could cause indexing failures if it is not true.
"""
# check for channels:
if channels is not None:
err = 0
for item in channels:
if item not in dct:
err = 1
print(f"Channel {item} not found in `dct`.")
if err:
raise ValueError(
"`dct` does not contain all requested channels. See above."
)
parms = channels
else:
parms = list(dct.keys())
# get time step:
t, d, isarr = _get_timedata(dct[parms[0]])
dt = (t[-1] - t[0]) / (len(t) - 1)
if mode == "truncate":
# loop to determine maximum overlap:
tmin = t[0]
tmax = t[-1]
for key in parms:
t, d, isarr = _get_timedata(dct[key])
if t[0] > tmax or t[-1] < tmin:
raise ValueError("not all inputs overlap in time.")
if not np.allclose(np.diff(t), dt):
raise ValueError(f"not all time steps in {key} match {dt}")
tmin = max(tmin, t[0])
tmax = min(tmax, t[-1])
n = int(np.ceil((tmax - tmin) / dt))
if (dt * n + tmin) < (tmax + dt / 2):
n += 1
pv = np.arange(n)
dctout = {}
dctout["t"] = pv * dt + tmin
start = tmin + dt / 2 # so index finds closest point
for key in parms:
t, d, isarr = _get_timedata(dct[key])
i = _get_prev_index(t, start)
dctout[key] = d[i + pv]
else:
# loop to determine maximum range:
tmin = t[0]
tmax = t[-1]
for key in parms:
t, d, isarr = _get_timedata(dct[key])
if not np.allclose(np.diff(t), dt):
raise ValueError(f"not all time steps in {key} match {dt}")
tmin = min(tmin, t[0])
tmax = max(tmax, t[-1])
n = int(np.ceil((tmax - tmin) / dt))
if (dt * n + tmin) < (tmax + dt / 2):
n += 1
dctout = {}
t = dctout["t"] = np.arange(n) * dt + tmin
for key in parms:
old_t, old_d, isarr = _get_timedata(dct[key])
i = _get_prev_index(t, old_t[0] + dt / 2)
new_d = np.empty(n)
new_d[:] = value
old_n = len(old_t)
if i + old_n > n:
old_n = n - i
new_d[i : i + old_n] = old_d[:old_n]
dctout[key] = new_d
return dctout
def _vector_to_axis(v, ndim, axis):
"""
Reshape 1d `v` to nd where the only non-unity dimension is `axis`.
Useful for broadcasting when, for example, multiplying a vector
along a certain axis of an nd array.
_vector_to_axis(np.arange(5), 3, 1).shape --> (1, 5, 1)
"""
dims = np.ones(ndim, int)
dims[axis] = -1
return v.reshape(*dims)
def windowends(sig, portion=0.01, ends="front", axis=-1):
"""
Apply parts of a cosine window to the ends of a signal.
This is also called the "Tukey" window. The window values are
computed from: ``(1 - cos)/2``.
Parameters
----------
sig : 1d or 2d ndarray
Vector or matrix; input time signal(s).
portion : scalar, optional
If > 1, specifies the number of points to window at each end.
If in (0, 1], specifies the fraction of signal to window at
each end: ``npts = int(portion * np.size(sig, axis))``.
ends : string, optional
Specify which ends of signal to operate on:
======= ====================================
`ends` Action
======= ====================================
'none' no windowing (no change to `signal`)
'front' window front end only
'back' window back end only
'both' window both ends
======= ====================================
axis : int, optional
Axis along which to operate.
Returns
-------
Returns the windowed signal(s); same size as the input.
Notes
-----
The minimum number of points that can be windowed is 3.
Therefore, `portion` is internally adjusted to 3 if the input
value is (or the computed value turns out to be) less than 3.
Examples
--------
>>> from pyyeti import dsp
>>> import numpy as np
>>> np.set_printoptions(precision=2, suppress=True)
>>> dsp.windowends(np.ones(8), 4)
array([ 0. , 0.25, 0.75, 1. , 1. , 1. , 1. , 1. ])
>>> dsp.windowends(np.ones(8), .7, ends='back')
array([ 1. , 1. , 1. , 1. , 0.85, 0.5 , 0.15, 0. ])
>>> dsp.windowends(np.ones(8), .5, ends='both')
array([ 0. , 0.25, 0.75, 1. , 1. , 0.75, 0.25, 0. ])
.. plot::
:context: close-figs
>>> import matplotlib.pyplot as plt
>>> _ = plt.figure('Example', figsize=[8, 3])
>>> plt.clf()
>>> sig = np.ones(100)
>>> wesig = dsp.windowends(sig, 5, ends='both')
>>> _ = plt.plot(sig, label='Original')
>>> _ = plt.plot(wesig, label='windowends (ends="both")')
>>> _ = plt.ylim(0, 1.2)
"""
if ends == "none":
return sig
sig = np.asarray(sig)
ln = sig.shape[axis]
if portion <= 1:
n = int(portion * ln)
else:
n = int(portion)
if n < 3:
n = 3
v = np.ones(ln, float)
w = 0.5 - 0.5 * np.cos(2 * np.pi * np.arange(n) / (2 * n - 2))
if ends == "front" or ends == "both":
v[:n] = w
if ends == "back" or ends == "both":
v[-n:] = w[::-1]
v = _vector_to_axis(v, sig.ndim, axis)
return sig * v
def _proc_timeslice(timeslice, sr, n):
# work with integers for slicing:
if isinstance(timeslice, str):
ntimeslice = int(timeslice)
timeslice = ntimeslice / sr
else:
ntimeslice = int(round(sr * timeslice))
if ntimeslice > n:
ntimeslice = n
timeslice = ntimeslice / sr
return ntimeslice, timeslice
def waterfall(
sig,
sr,
timeslice,
tsoverlap,
func,
which,
freq,
t0=0.0,
args=None,
kwargs=None,
slicefunc=None,
sliceargs=None,
slicekwargs=None,
):
"""
Compute a 'waterfall' map over time and frequency (typically) using
a user-supplied function.
Parameters
----------
sig : 1d array_like
Time series of measurement values.
sr : scalar
Sample rate.
timeslice : scalar or string-integer
If scalar, it is the length in seconds for each slice. If
string, it contains the integer number of points for each
slice. For example, if `sr` is 1000 samples/second,
``timeslice=0.75`` is equivalent to ``timeslice="750"``.
tsoverlap : scalar in [0, 1) or string-integer
If scalar, is the fraction of each time-slice to overlap. If
string, it contains the integer number of points to
overlap. For example, if `sr` is 1000 samples/second,
``tsoverlap=0.5`` and ``tsoverlap="500"`` each specify 50%
overlap.
func : function
This function is called for each time slice (denoted as
"sig_slice" here) and is expected to return amplitude values
across the frequency range. It can return just the amplitudes,
or it can have multiple outputs (see also `which` and
`freq`). The call is: ``func(sig_slice, *args,
**kwargs)``. Note that the "sig_slice" input is first passed
through `slicefunc` if one is provided (see below).
which : None or integer
Set to None if `func` only returns the amplitudes. Otherwise,
if `func` returns multiple outputs, set `which` to the index
of the output corresponding to the amplitudes. For example, if
`func` returns ``(frequencies, amplitudes)``, `which` would be
1 (and `freq` would be 0).
.. note::
Setting `which` to None is not the same as setting it to
0. Using None means that the function only returns
amplitudes, while a 0 indicates that the output of `func`
must be indexed by 0 to get the amplitudes. For example: if
the function has ``return amps``, use ``which=None``; if
the function has ``return (amps,)``, use ``which=0``.
freq : integer or vector
If integer, it is the index of the output of `func`
corresponding to the frequency vector and cannot be equal to
`which`. Otherwise, if `freq` is a vector, it is the frequency
vector directly.
t0 : scalar; optional
Start time of signal; defaults to 0.0.
args : tuple or list; optional
If provided, these are passed to `func`.
kwargs : dict; optional
If provided, these are passed to `func`.
slicefunc : function or None; optional
If a function, it is called for each time-slice before `func`
is called. This could be for windowing or detrending, for
example. The call is:
``sig_slice = slicefunc(sig[pv], *sliceargs, **slicekwargs)``.
sliceargs : tuple or list; optional
If provided, these are passed to `slicefunc`. Must be None or
`()` if `slicefunc` is None.
slicekwargs : dict; optional
If provided, these are passed to `slicefunc`. Must be None or
`{}` if `slicefunc` is None.
Returns
-------
mp : 2d ndarray
The waterfall map; columns span time, rows span frequency. So,
| |
all_data = {'AK': {'Aleutians East': {'population': 3141, 'tracts': 1},
'Aleutians West': {'population': 5561, 'tracts': 2},
'Anchorage': {'population': 291826, 'tracts': 55},
'Bethel': {'population': 17013, 'tracts': 3},
'Bristol Bay': {'population': 997, 'tracts': 1},
'Denali': {'population': 1826, 'tracts': 1},
'Dillingham': {'population': 4847, 'tracts': 2},
'Fairbanks North Star': {'population': 97581, 'tracts': 19},
'Haines': {'population': 2508, 'tracts': 1},
'Hoonah-Angoon': {'population': 2150, 'tracts': 2},
'Juneau': {'population': 31275, 'tracts': 6},
'Kenai Peninsula': {'population': 55400, 'tracts': 13},
'Ketchikan Gateway': {'population': 13477, 'tracts': 4},
'Kodiak Island': {'population': 13592, 'tracts': 5},
'Lake and Peninsula': {'population': 1631, 'tracts': 1},
'Matanuska-Susitna': {'population': 88995, 'tracts': 24},
'Nome': {'population': 9492, 'tracts': 2},
'North Slope': {'population': 9430, 'tracts': 3},
'Northwest Arctic': {'population': 7523, 'tracts': 2},
'Petersburg': {'population': 3815, 'tracts': 1},
'Prince of Wales-Hyder': {'population': 5559, 'tracts': 4},
'Sitka': {'population': 8881, 'tracts': 2},
'Skagway': {'population': 968, 'tracts': 1},
'Southeast Fairbanks': {'population': 7029, 'tracts': 2},
'Valdez-Cordova': {'population': 9636, 'tracts': 3},
'<NAME>': {'population': 7459, 'tracts': 1},
'Wrangell': {'population': 2369, 'tracts': 1},
'Yakutat': {'population': 662, 'tracts': 1},
'Yukon-Koyukuk': {'population': 5588, 'tracts': 4}},
'AL': {'Autauga': {'population': 54571, 'tracts': 12},
'Baldwin': {'population': 182265, 'tracts': 31},
'Barbour': {'population': 27457, 'tracts': 9},
'Bibb': {'population': 22915, 'tracts': 4},
'Blount': {'population': 57322, 'tracts': 9},
'Bullock': {'population': 10914, 'tracts': 3},
'Butler': {'population': 20947, 'tracts': 9},
'Calhoun': {'population': 118572, 'tracts': 31},
'Chambers': {'population': 34215, 'tracts': 9},
'Cherokee': {'population': 25989, 'tracts': 6},
'Chilton': {'population': 43643, 'tracts': 9},
'Choctaw': {'population': 13859, 'tracts': 4},
'Clarke': {'population': 25833, 'tracts': 9},
'Clay': {'population': 13932, 'tracts': 4},
'Cleburne': {'population': 14972, 'tracts': 4},
'Coffee': {'population': 49948, 'tracts': 14},
'Colbert': {'population': 54428, 'tracts': 14},
'Conecuh': {'population': 13228, 'tracts': 5},
'Coosa': {'population': 11539, 'tracts': 3},
'Covington': {'population': 37765, 'tracts': 14},
'Crenshaw': {'population': 13906, 'tracts': 6},
'Cullman': {'population': 80406, 'tracts': 18},
'Dale': {'population': 50251, 'tracts': 14},
'Dallas': {'population': 43820, 'tracts': 15},
'DeKalb': {'population': 71109, 'tracts': 14},
'Elmore': {'population': 79303, 'tracts': 15},
'Escambia': {'population': 38319, 'tracts': 9},
'Etowah': {'population': 104430, 'tracts': 30},
'Fayette': {'population': 17241, 'tracts': 5},
'Franklin': {'population': 31704, 'tracts': 9},
'Geneva': {'population': 26790, 'tracts': 6},
'Greene': {'population': 9045, 'tracts': 3},
'Hale': {'population': 15760, 'tracts': 6},
'Henry': {'population': 17302, 'tracts': 6},
'Houston': {'population': 101547, 'tracts': 22},
'Jackson': {'population': 53227, 'tracts': 11},
'Jefferson': {'population': 658466, 'tracts': 163},
'Lamar': {'population': 14564, 'tracts': 3},
'Lauderdale': {'population': 92709, 'tracts': 22},
'Lawrence': {'population': 34339, 'tracts': 9},
'Lee': {'population': 140247, 'tracts': 27},
'Limestone': {'population': 82782, 'tracts': 16},
'Lowndes': {'population': 11299, 'tracts': 4},
'Macon': {'population': 21452, 'tracts': 12},
'Madison': {'population': 334811, 'tracts': 73},
'Marengo': {'population': 21027, 'tracts': 6},
'Marion': {'population': 30776, 'tracts': 8},
'Marshall': {'population': 93019, 'tracts': 18},
'Mobile': {'population': 412992, 'tracts': 114},
'Monroe': {'population': 23068, 'tracts': 7},
'Montgomery': {'population': 229363, 'tracts': 65},
'Morgan': {'population': 119490, 'tracts': 27},
'Perry': {'population': 10591, 'tracts': 3},
'Pickens': {'population': 19746, 'tracts': 5},
'Pike': {'population': 32899, 'tracts': 8},
'Randolph': {'population': 22913, 'tracts': 6},
'Russell': {'population': 52947, 'tracts': 13},
'Shelby': {'population': 195085, 'tracts': 48},
'<NAME>': {'population': 83593, 'tracts': 13},
'Sumter': {'population': 13763, 'tracts': 4},
'Talladega': {'population': 82291, 'tracts': 22},
'Tallapoosa': {'population': 41616, 'tracts': 10},
'Tuscaloosa': {'population': 194656, 'tracts': 47},
'Walker': {'population': 67023, 'tracts': 18},
'Washington': {'population': 17581, 'tracts': 5},
'Wilcox': {'population': 11670, 'tracts': 4},
'Winston': {'population': 24484, 'tracts': 7}},
'AR': {'Arkansas': {'population': 19019, 'tracts': 8},
'Ashley': {'population': 21853, 'tracts': 7},
'Baxter': {'population': 41513, 'tracts': 9},
'Benton': {'population': 221339, 'tracts': 49},
'Boone': {'population': 36903, 'tracts': 7},
'Bradley': {'population': 11508, 'tracts': 5},
'Calhoun': {'population': 5368, 'tracts': 2},
'Carroll': {'population': 27446, 'tracts': 5},
'Chicot': {'population': 11800, 'tracts': 4},
'Clark': {'population': 22995, 'tracts': 5},
'Clay': {'population': 16083, 'tracts': 6},
'Cleburne': {'population': 25970, 'tracts': 7},
'Cleveland': {'population': 8689, 'tracts': 2},
'Columbia': {'population': 24552, 'tracts': 5},
'Conway': {'population': 21273, 'tracts': 6},
'Craighead': {'population': 96443, 'tracts': 17},
'Crawford': {'population': 61948, 'tracts': 11},
'Crittenden': {'population': 50902, 'tracts': 20},
'Cross': {'population': 17870, 'tracts': 6},
'Dallas': {'population': 8116, 'tracts': 3},
'Desha': {'population': 13008, 'tracts': 5},
'Drew': {'population': 18509, 'tracts': 5},
'Faulkner': {'population': 113237, 'tracts': 25},
'Franklin': {'population': 18125, 'tracts': 3},
'Fulton': {'population': 12245, 'tracts': 2},
'Garland': {'population': 96024, 'tracts': 20},
'Grant': {'population': 17853, 'tracts': 4},
'Greene': {'population': 42090, 'tracts': 9},
'Hempstead': {'population': 22609, 'tracts': 5},
'<NAME>': {'population': 32923, 'tracts': 7},
'Howard': {'population': 13789, 'tracts': 3},
'Independence': {'population': 36647, 'tracts': 8},
'Izard': {'population': 13696, 'tracts': 4},
'Jackson': {'population': 17997, 'tracts': 5},
'Jefferson': {'population': 77435, 'tracts': 24},
'Johnson': {'population': 25540, 'tracts': 6},
'Lafayette': {'population': 7645, 'tracts': 2},
'Lawrence': {'population': 17415, 'tracts': 6},
'Lee': {'population': 10424, 'tracts': 4},
'Lincoln': {'population': 14134, 'tracts': 4},
'<NAME>': {'population': 13171, 'tracts': 4},
'Logan': {'population': 22353, 'tracts': 6},
'Lonoke': {'population': 68356, 'tracts': 16},
'Madison': {'population': 15717, 'tracts': 4},
'Marion': {'population': 16653, 'tracts': 4},
'Miller': {'population': 43462, 'tracts': 12},
'Mississippi': {'population': 46480, 'tracts': 12},
'Monroe': {'population': 8149, 'tracts': 3},
'Montgomery': {'population': 9487, 'tracts': 3},
'Nevada': {'population': 8997, 'tracts': 3},
'Newton': {'population': 8330, 'tracts': 2},
'Ouachita': {'population': 26120, 'tracts': 6},
'Perry': {'population': 10445, 'tracts': 3},
'Phillips': {'population': 21757, 'tracts': 6},
'Pike': {'population': 11291, 'tracts': 3},
'Poinsett': {'population': 24583, 'tracts': 7},
'Polk': {'population': 20662, 'tracts': 6},
'Pope': {'population': 61754, 'tracts': 11},
'Prairie': {'population': 8715, 'tracts': 3},
'Pulaski': {'population': 382748, 'tracts': 95},
'Randolph': {'population': 17969, 'tracts': 4},
'Saline': {'population': 107118, 'tracts': 21},
'Scott': {'population': 11233, 'tracts': 3},
'Searcy': {'population': 8195, 'tracts': 3},
'Sebastian': {'population': 125744, 'tracts': 26},
'Sevier': {'population': 17058, 'tracts': 4},
'Sharp': {'population': 17264, 'tracts': 4},
'<NAME>': {'population': 28258, 'tracts': 6},
'Stone': {'population': 12394, 'tracts': 3},
'Union': {'population': 41639, 'tracts': 10},
'<NAME>': {'population': 17295, 'tracts': 5},
'Washington': {'population': 203065, 'tracts': 32},
'White': {'population': 77076, 'tracts': 13},
'Woodruff': {'population': 7260, 'tracts': 2},
'Yell': {'population': 22185, 'tracts': 6}},
'AZ': {'Apache': {'population': 71518, 'tracts': 16},
'Cochise': {'population': 131346, 'tracts': 32},
'Coconino': {'population': 134421, 'tracts': 28},
'Gila': {'population': 53597, 'tracts': 16},
'Graham': {'population': 37220, 'tracts': 9},
'Greenlee': {'population': 8437, 'tracts': 3},
'La Paz': {'population': 20489, 'tracts': 9},
'Maricopa': {'population': 3817117, 'tracts': 916},
'Mohave': {'population': 200186, 'tracts': 43},
'Navajo': {'population': 107449, 'tracts': 31},
'Pima': {'population': 980263, 'tracts': 241},
'Pinal': {'population': 375770, 'tracts': 75},
'Santa Cruz': {'population': 47420, 'tracts': 10},
'Yavapai': {'population': 211033, 'tracts': 42},
'Yuma': {'population': 195751, 'tracts': 55}},
'CA': {'Alameda': {'population': 1510271, 'tracts': 360},
'Alpine': {'population': 1175, 'tracts': 1},
'Amador': {'population': 38091, 'tracts': 9},
'Butte': {'population': 220000, 'tracts': 51},
'Calaveras': {'population': 45578, 'tracts': 10},
'Colusa': {'population': 21419, 'tracts': 5},
'Contra Costa': {'population': 1049025, 'tracts': 208},
'Del Norte': {'population': 28610, 'tracts': 7},
'El Dorado': {'population': 181058, 'tracts': 43},
'Fresno': {'population': 930450, 'tracts': 199},
'Glenn': {'population': 28122, 'tracts': 6},
'Humboldt': {'population': 134623, 'tracts': 30},
'Imperial': {'population': 174528, 'tracts': 31},
'Inyo': {'population': 18546, 'tracts': 6},
'Kern': {'population': 839631, 'tracts': 151},
'Kings': {'population': 152982, 'tracts': 27},
'Lake': {'population': 64665, 'tracts': 15},
'Lassen': {'population': 34895, 'tracts': 9},
'Los Angeles': {'population': 9818605, 'tracts': 2343},
'Madera': {'population': 150865, 'tracts': 23},
'Marin': {'population': 252409, 'tracts': 55},
'Mariposa': {'population': 18251, 'tracts': 6},
'Mendocino': {'population': 87841, 'tracts': 20},
'Merced': {'population': 255793, 'tracts': 49},
'Modoc': {'population': 9686, 'tracts': 4},
'Mono': {'population': 14202, 'tracts': 3},
'Monterey': {'population': 415057, 'tracts': 93},
'Napa': {'population': 136484, 'tracts': 40},
'Nevada': {'population': 98764, 'tracts': 20},
'Orange': {'population': 3010232, 'tracts': 583},
'Placer': {'population': 348432, 'tracts': 85},
'Plumas': {'population': 20007, 'tracts': 7},
'Riverside': {'population': 2189641, 'tracts': 453},
'Sacramento': {'population': 1418788, 'tracts': 317},
'San Benito': {'population': 55269, 'tracts': 11},
'San Bernardino': {'population': 2035210, 'tracts': 369},
'San Diego': {'population': 3095313, 'tracts': 628},
'San Francisco': {'population': 805235, 'tracts': 196},
'San Joaquin': {'population': 685306, 'tracts': 139},
'San Luis Obispo': {'population': 269637, 'tracts': 53},
'San Mateo': {'population': 718451, 'tracts': 158},
'Santa Barbara': {'population': 423895, 'tracts': 90},
'Santa Clara': {'population': 1781642, 'tracts': 372},
'Santa Cruz': {'population': 262382, 'tracts': 52},
'Shasta': {'population': 177223, 'tracts': 48},
'Sierra': {'population': 3240, 'tracts': 1},
'Siskiyou': {'population': 44900, 'tracts': 14},
'Solano': {'population': 413344, 'tracts': 96},
'Sonoma': {'population': 483878, 'tracts': 99},
'Stanislaus': {'population': 514453, 'tracts': 94},
'Sutter': {'population': 94737, 'tracts': 21},
'Tehama': {'population': 63463, 'tracts': 11},
'Trinity': {'population': 13786, 'tracts': 5},
'Tulare': {'population': 442179, 'tracts': 78},
'Tuolumne': {'population': 55365, 'tracts': 11},
'Ventura': {'population': 823318, 'tracts': 174},
'Yolo': {'population': 200849, 'tracts': 41},
'Yuba': {'population': 72155, 'tracts': 14}},
'CO': {'Adams': {'population': 441603, 'tracts': 97},
'Alamosa': {'population': 15445, 'tracts': 4},
'Arapahoe': {'population': 572003, 'tracts': 147},
'Archuleta': {'population': 12084, 'tracts': 4},
| |
import numpy as np
inc = [87,7,82,21,47,88,12,71,24,35,10,90,4,97,30,55,36,74,19,50,23,46,13,44,69,27,2,0,37,33,99,49,77,15,89,98,31,51,22,96,73,94,95,18,52,78,32,83,85,54,75,84,59,25,76,45,20,48,9,28,39,70,63,56,5,68,61,26,58,92,67,53,43,62,17,81,80,66,91,93,41,64,14,8,57,38,34,16,42,11,86,72,40,65,79,6,3,29,60,1]
tables = [[ 3, 55, 15, 54, 81,
56, 77, 20, 99, 25,
90, 57, 67, 0, 97,
28, 45, 69, 84, 14,
91, 94, 39, 36, 85],
[52, 60, 30, 7, 36,
71, 97, 77, 19, 46,
6, 3, 75, 82, 24,
4, 57, 2, 11, 91,
56, 84, 23, 43, 48],
[69, 60, 78, 87, 11,
79, 30, 93, 39, 63,
32, 31, 23, 90, 17,
57, 98, 13, 46, 9,
65, 94, 26, 77, 19],
[87, 68, 81, 63, 95,
91, 43, 98, 49, 70,
67, 46, 12, 10, 3,
65, 93, 39, 29, 34,
45, 35, 78, 40, 59],
[95, 11, 27, 19, 78,
8, 47, 87, 44, 10,
48, 83, 93, 52, 23,
16, 13, 21, 1, 4,
69, 12, 40, 39, 81],
[50, 73, 63, 93, 86,
55, 76, 33, 22, 75,
61, 23, 82, 37, 99,
26, 29, 85, 74, 2,
19, 78, 30, 40, 6],
[58, 2, 95, 92, 78,
25, 56, 26, 9, 38,
43, 83, 4, 87, 8,
79, 61, 18, 69, 49,
24, 29, 5, 41, 89],
[56, 8, 72, 92, 9,
34, 26, 28, 66, 22,
51, 42, 89, 87, 90,
98, 48, 40, 18, 19,
13, 80, 71, 79, 52],
[87, 77, 82, 38, 48,
92, 36, 85, 66, 71,
97, 29, 94, 9, 1,
70, 50, 19, 45, 84,
43, 6, 72, 54, 89],
[ 9, 60, 6, 17, 14,
97, 2, 10, 84, 0,
7, 98, 51, 8, 93,
54, 77, 37, 36, 1,
72, 29, 26, 47, 19],
[92, 22, 25, 19, 36,
80, 14, 24, 59, 78,
29, 45, 88, 54, 4,
37, 85, 77, 46, 6,
42, 52, 43, 26, 72],
[41, 84, 36, 95, 49,
22, 17, 83, 47, 99,
25, 77, 12, 71, 39,
76, 73, 60, 79, 85,
63, 94, 11, 54, 51],
[88, 29, 7, 26, 45,
25, 11, 9, 82, 28,
43, 5, 41, 70, 39,
20, 69, 14, 79, 37,
78, 59, 98, 93, 6],
[99, 24, 81, 51, 57,
56, 47, 7, 50, 66,
84, 85, 71, 86, 31,
17, 74, 90, 26, 73,
15, 11, 12, 61, 45],
[61, 27, 84, 49, 21,
76, 15, 5, 0, 2,
35, 7, 79, 77, 20,
40, 91, 72, 57, 89,
11, 33, 18, 42, 78],
[21, 38, 46, 53, 50,
49, 10, 9, 59, 67,
3, 51, 96, 44, 63,
93, 45, 82, 27, 47,
69, 92, 41, 85, 95],
[14, 70, 5, 4, 34,
59, 98, 53, 45, 7,
97, 29, 58, 1, 84,
19, 69, 37, 93, 57,
86, 68, 35, 30, 73],
[38, 21, 7, 1, 43,
41, 9, 54, 0, 11,
51, 94, 99, 75, 72,
89, 78, 79, 2, 73,
18, 90, 85, 84, 10],
[33, 68, 5, 26, 8,
51, 85, 20, 49, 58,
27, 24, 88, 11, 21,
9, 65, 62, 72, 31,
95, 53, 12, 14, 83],
[ 1, 22, 76, 11, 56,
97, 95, 79, 55, 14,
20, 53, 27, 77, 23,
37, 49, 30, 72, 84,
91, 68, 8, 18, 5],
[45, 68, 6, 49, 92,
43, 90, 20, 1, 78,
77, 89, 5, 10, 56,
84, 28, 73, 62, 72,
21, 47, 51, 36, 14],
[30, 71, 52, 21, 13,
20, 8, 73, 38, 92,
17, 50, 59, 3, 14,
19, 76, 41, 4, 90,
57, 25, 94, 82, 62],
[52, 76, 18, 60, 9,
29, 38, 5, 96, 63,
58, 70, 28, 82, 1,
40, 49, 43, 25, 19,
92, 56, 80, 66, 69],
[58, 60, 90, 33, 92,
13, 74, 0, 80, 84,
77, 97, 51, 70, 56,
15, 87, 68, 98, 55,
1, 64, 35, 3, 83],
[77, 43, 69, 58, 34,
42, 12, 75, 27, 28,
74, 54, 30, 2, 15,
63, 21, 81, 90, 9,
6, 22, 29, 65, 19],
[60, 89, 43, 26, 86,
47, 52, 12, 17, 90,
56, 54, 96, 37, 75,
3, 80, 0, 19, 85,
39, 61, 13, 59, 73],
[94, 59, 82, 21, 68,
87, 19, 69, 79, 31,
64, 57, 72, 43, 25,
49, 5, 81, 67, 76,
95, 16, 58, 52, 51],
[33, 36, 1, 61, 85,
11, 74, 37, 89, 30,
24, 59, 31, 76, 62,
4, 50, 81, 69, 78,
66, 57, 9, 94, 7],
[ 6, 20, 26, 2, 9,
52, 34, 63, 89, 13,
16, 65, 30, 29, 27,
97, 18, 47, 53, 19,
79, 7, 38, 33, 39],
[90, 20, 79, 95, 44,
0, 96, 98, 74, 60,
80, 65, 36, 93, 67,
54, 25, 81, 84, 10,
21, 56, 83, 14, 66],
[99, 1, 17, 41, 95,
66, 29, 47, 74, 43,
63, 68, 72, 97, 96,
92, 79, 13, 93, 4,
25, 42, 44, 78, 23],
[17, 19, 98, 55, 14,
2, 35, 42, 22, 64,
52, 32, 69, 27, 82,
85, 16, 89, 41, 81,
10, 70, 95, 56, 84],
[64, 4, 94, 51, 35,
25, 60, 33, 24, 80,
59, 40, 14, 47, 93,
32, 74, 42, 46, 26,
49, 75, 7, 95, 79],
[39, 98, 43, 56, 73,
92, 63, 13, 61, 36,
4, 34, 35, 10, 11,
30, 19, 75, 26, 41,
54, 37, 65, 15, 58],
[89, 64, 83, 43, 42,
71, 32, 25, 63, 34,
80, 93, 99, 86, 16,
31, 33, 94, 27, 91,
8, 17, 81, 41, 85],
[16, 89, 41, 87, 53,
27, 29, 64, 30, 81,
20, 47, 18, 1, 50,
56, 82, 93, 4, 45,
71, 21, 63, 25, 15],
[61, 12, 97, 41, 32,
51, 85, 64, 16, 99,
68, 2, 43, 10, 86,
69, 5, 38, 94, 11,
92, 74, 20, 83, 90],
[98, 96, 44, 95, 36,
63, 42, 56, 24, 21,
40, 7, 65, 48, 59,
18, 11, 2, 58, 13,
86, 41, 0, 53, 20],
[ 0, 74, 23, 35, 48,
21, 34, 97, 10, 2,
17, 25, 80, 89, 60,
15, 27, 94, 68, 7,
72, 75, 69, 32, 85],
[29, 72, 40, 13, 9,
48, 41, 21, 66, 94,
20, 23, 42, 53, 84,
93, 14, 7, 57, 77,
67, 36, 10, 81, 0],
[85, 92, 45, 94, 75,
58, 79, 9, 98, 5,
14, 39, 40, 48, 88,
96, 61, 36, 62, 7,
32, 81, 77, 8, 27],
[78, 80, 98, 62, 87,
90, 53, 91, 81, 23,
46, 15, 4, 63, 74,
30, 6, 47, 64, 44,
12, 45, 95, 68, 99],
[88, 4, 53, 84, 25,
71, 36, 20, 46, 74,
48, 70, 5, 63, 94,
15, 65, 78, 33, 67,
99, 64, 76, 97, 26],
[64, 96, 69, 13, 60,
31, 26, 86, 38, 46,
35, 90, 45, 97, 40,
98, 87, 21, 61, 1,
27, 67, 77, 29, 66],
[74, 97, 72, 66, 1,
34, 50, 2, 57, 33,
29, 71, 52, 88, 73,
16, 7, 39, 40, 24,
15, 38, 80, 54, 17],
[22, 99, 67, 95, 97,
60, 68, 38, 18, 96,
89, 46, 57, 8, 11,
7, 12, 61, 83, 35,
17, 74, 42, 52, 58],
[10, 19, 44, 12, 41,
82, 71, 1, 26, 55,
52, 88, 6, 97, 48,
16, 66, 36, 50, 29,
67, 2, 65, 0, 45],
[68, 16, 99, 57, 12,
36, 50, 32, 19, 91,
43, 21, 52, 31, 69,
41, 82, 37, 49, 75,
20, 74, 87, 76, 63],
[81, 10, 7, 80, 78,
29, 86, 6, 13, 67,
19, 12, 23, 54, 68,
64, 85, 40, 43, 87,
16, 5, 59, 3, 34],
[79, 37, 13, 17, 31,
56, 22, 24, 7, 58,
65, 76, 38, 39, 85,
45, 36, 90, 3, 66,
25, 52, 28, 61, 71],
[18, 20, 21, 74, 33,
77, 30, 29, 56, 26,
86, 49, 44, 75, 62,
11, 47, 10, 90, 97,
64, 94, 6, 43, 67],
[77, 59, 44, 58, 41,
85, 30, 22, 56, 19,
62, 16, 35, 32, 88,
91, 94, 34, 51, 9,
31, 33, 13, 60, 90],
[94, 56, 72, 12, 59,
64, 78, 2, 80, 96,
41, 99, 69, 21, 79,
17, 88, 36, 37, 85,
89, 7, 66, 15, 84],
[61, 80, 26, 83, 11,
62, 42, 51, 79, 31,
86, 98, 64, 28, 58,
2, 19, 71, 35, 52,
14, 34, 0, 32, 44],
[ 1, 50, 76, 15, 12,
96, 55, 73, 61, 19,
74, 0, 79, 5, 8,
3, 36, 53, 67, 52,
60, 49, 93, 43, 85],
[71, 75, 35, 44, 1,
82, 96, 22, 68, 81,
19, 25, 52, 62, 97,
28, 64, 73, 99, 92,
38, 60, 42, 70, 20],
[38, 15, 77, 19, 74,
5, 89, 17, 10, 16,
96, 48, 40, 42, 57,
21, 18, 51, 56, 29,
86, 63, 25, 45, 93],
[98, 36, 26, 69, 2,
70, 75, 18, 89, 81,
33, 24, 10, 76, 47,
28, 59, 54, 49, 58,
62, 19, 53, 73, 16],
[96, 84, 52, 86, 47,
70, 14, 26, 46, 81,
90, 53, 66, 16, 87,
34, 9, 91, 83, 41,
61, 29, 13, 49, 77],
[78, 49, 94, 33, 18,
91, 83, 55, 73, 44,
19, 4, 14, 6, 3,
45, 28, 57, 12, 9,
41, 1, 82, 79, 95],
[74, 38, 35, 88, 6,
80, 21, 32, 3, 71,
1, 34, 17, 8, 2,
94, 24, 84, 26, 91,
64, 27, 83, 60, 23],
[93, 18, 27, 52, 28,
83, 90, 40, 8, 87,
21, 3, 4, 99, 26,
14, 13, 71, 41, 91,
20, 63, 69, 38, 30],
[49, 20, 31, 70, 5,
37, 7, 94, 85, | |
<filename>scripts/ini_editor.py
#!/usr/bin/python
#
# Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
A script to modify dsp.ini config files.
A dsp.ini config file is represented by an Ini object.
An Ini object contains one or more Sections.
Each Section has a name, a list of Ports, and a list of NonPorts.
"""
import argparse
import logging
import os
import re
import StringIO
import sys
from collections import namedtuple
Parameter = namedtuple('Parameter', ['value', 'comment'])
class Port(object):
"""Class for port definition in ini file.
Properties:
io: "input" or "output".
index: an integer for port index.
definition: a string for the content after "=" in port definition line.
parameter: a Parameter namedtuple which is parsed from definition.
"""
@staticmethod
def ParsePortLine(line):
"""Parses a port definition line in ini file and init a Port object.
Args:
line: A string possibly containing port definition line like
"input_0=1; something".
Returns:
A Port object if input is a valid port definition line. Returns
None if input is not a valid port definition line.
"""
result = re.match(r'(input|output)_(\d+)=(.*)', line)
if result:
parse_values = result.groups()
io = parse_values[0]
index = int(parse_values[1])
definition = parse_values[2]
return Port(io, index, definition)
else:
return None
def __init__(self, io, index, definition):
"""Initializes a port.
Initializes a port with io, index and definition. The definition will be
further parsed to Parameter(value, comment) if the format matches
"<some value> ; <some comment>".
Args:
io: "input" or "output".
index: an integer for port index.
definition: a string for the content after "=" in port definition line.
"""
self.io = io
self.index = index
self.definition = definition
result = re.match(r'(\S+)\s+; (.+)', definition)
if result:
self.parameter = Parameter._make(result.groups())
else:
self.parameter = None
def FormatLine(self):
"""Returns a port definition line which is used in ini file."""
line = '%s_%d=' % (self.io, self.index)
if self.parameter:
line +="{:<8}; {:}".format(self.parameter.value, self.parameter.comment)
else:
line += self.definition
return line
def _UpdateIndex(self, index):
"""Updates index of this port.
Args:
index: The new index.
"""
self.index = index
class NonPort(object):
"""Class for non-port definition in ini file.
Properties:
name: A string representing the non-port name.
definition: A string representing the non-port definition.
"""
@staticmethod
def ParseNonPortLine(line):
"""Parses a non-port definition line in ini file and init a NonPort object.
Args:
line: A string possibly containing non-port definition line like
"library=builtin".
Returns:
A NonPort object if input is a valid non-port definition line. Returns
None if input is not a valid non-port definition line.
"""
result = re.match(r'(\w+)=(.*)', line)
if result:
parse_values = result.groups()
name = parse_values[0]
definition = parse_values[1]
return NonPort(name, definition)
else:
return None
def __init__(self, name, definition):
"""Initializes a NonPort <name>=<definition>.
Args:
name: A string representing the non-port name.
definition: A string representing the non-port definition.
"""
self.name = name
self.definition = definition
def FormatLine(self):
"""Formats a string representation of a NonPort.
Returns:
A string "<name>=<definition>".
"""
line = '%s=%s' % (self.name, self.definition)
return line
class SectionException(Exception):
pass
class Section(object):
"""Class for section definition in ini file.
Properties:
name: Section name.
non_ports: A list containing NonPorts of this section.
ports: A list containing Ports of this section.
"""
@staticmethod
def ParseSectionName(line):
"""Parses a section name.
Args:
line: A string possibly containing a section name like [drc].
Returns:
Returns parsed section name without '[' and ']' if input matches
the syntax [<section name>]. Returns None if not.
"""
result = re.match(r'\[(\w+)\]', line)
return result.groups()[0] if result else None
@staticmethod
def ParseLine(line):
"""Parses a line that belongs to a section.
Returns:
A Port or NonPort object if input line matches the format. Returns None
if input line does not match the format of Port nor NonPort.
"""
if not line:
return
parse_port = Port.ParsePortLine(line)
if parse_port:
return parse_port
parse_non_port = NonPort.ParseNonPortLine(line)
if parse_non_port:
return parse_non_port
def __init__(self, name):
"""Initializes a Section with given name."""
self.name = name
self.non_ports= []
self.ports = []
def AddLine(self, line):
"""Adds a line to this Section.
Args:
line: A line to be added to this section. If it matches port or non-port
format, a Port or NonPort will be added to this section. Otherwise,
this line is ignored.
"""
to_add = Section.ParseLine(line)
if not to_add:
return
if isinstance(to_add, Port):
self.AppendPort(to_add)
return
if isinstance(to_add, NonPort):
self.AppendNonPort(to_add)
return
def AppendNonPort(self, non_port):
"""Appends a NonPort to non_ports.
Args:
non_port: A NonPort object to be appended.
"""
self.non_ports.append(non_port)
def AppendPort(self, port):
"""Appends a Port to ports.
Args:
port: A Port object to be appended. The port should be appended
in the order of index, so the index of port should equal to the current
size of ports list.
Raises:
SectionException if the index of port is not the current size of ports
list.
"""
if not port.index == len(self.ports):
raise SectionException(
'The port with index %r can not be appended to the end of ports'
' of size' % (port.index, len(self.ports)))
else:
self.ports.append(port)
def InsertLine(self, line):
"""Inserts a line to this section.
Inserts a line containing port or non-port definition to this section.
If input line matches Port or NonPort format, the corresponding insert
method InsertNonPort or InsertPort will be called. If input line does not
match the format, SectionException will be raised.
Args:
line: A line to be inserted. The line should
Raises:
SectionException if input line does not match the format of Port or
NonPort.
"""
to_insert = Section.ParseLine(line)
if not to_insert:
raise SectionException(
'The line %s does not match Port or NonPort syntax' % line)
if isinstance(to_insert, Port):
self.InsertPort(to_insert)
return
if isinstance(to_insert, NonPort):
self.InsertNonPort(to_insert)
return
def InsertNonPort(self, non_port):
"""Inserts a NonPort to non_ports list.
Currently there is no ordering for non-port definition. This method just
appends non_port to non_ports list.
Args:
non_port: A NonPort object.
"""
self.non_ports.append(non_port)
def InsertPort(self, port):
"""Inserts a Port to ports list.
The index of port should not be greater than the current size of ports.
After insertion, the index of each port in ports should be updated to the
new index of that port in the ports list.
E.g. Before insertion:
self.ports=[Port("input", 0, "foo0"),
Port("input", 1, "foo1"),
Port("output", 2, "foo2")]
Now we insert a Port with index 1 by invoking
InsertPort(Port("output, 1, "bar")),
Then,
self.ports=[Port("input", 0, "foo0"),
Port("output, 1, "bar"),
Port("input", 2, "foo1"),
Port("output", 3, "foo2")].
Note that the indices of foo1 and foo2 had been shifted by one because a
new port was inserted at index 1.
Args:
port: A Port object.
Raises:
SectionException: If the port to be inserted does not have a valid index.
"""
if port.index > len(self.ports):
raise SectionException('Inserting port index %d but'
' currently there are only %d ports' % (port.index,
len(self.ports)))
self.ports.insert(port.index, port)
self._UpdatePorts()
def _UpdatePorts(self):
"""Updates the index property of each Port in ports.
Updates the index property of each Port in ports so the new index property
is the index of that Port in ports list.
"""
for index, port in enumerate(self.ports):
port._UpdateIndex(index)
def Print(self, output):
"""Prints the section definition to output.
The format is:
[section_name]
non_port_name_0=non_port_definition_0
non_port_name_1=non_port_definition_1
...
port_name_0=port_definition_0
port_name_1=port_definition_1
...
Args:
output: A StringIO.StringIO object.
"""
output.write('[%s]\n' % self.name)
for non_port in self.non_ports:
output.write('%s\n' % non_port.FormatLine())
for port in self.ports:
output.write('%s\n' % port.FormatLine())
class Ini(object):
"""Class for an ini config file.
Properties:
sections: A dict containing mapping from section name to Section.
section_names: A list of section names.
file_path: The path of this ini config file.
"""
def __init__(self, input_file):
"""Initializes an Ini object from input config file.
Args:
input_file: The path to an ini config file.
"""
self.sections = {}
self.section_names = []
self.file_path = input_file
self._ParseFromFile(input_file)
def _ParseFromFile(self, input_file):
"""Parses sections in the input config file.
Reads in the content of the input config file and parses each sections.
The parsed sections are stored in sections dict.
The names of each section is stored in section_names list.
Args:
input_file: The path to an ini config file.
"""
content = open(input_file, 'r').read()
content_lines = content.splitlines()
self.sections | |
"""
Inspired by:
1. RLKit: https://github.com/rail-berkeley/rlkit
2. StabelBaselines: https://github.com/hill-a/stable-baselines
3. SpinningUp OpenAI: https://github.com/openai/spinningup
4. CleanRL: https://github.com/vwxyzjn/cleanrl
"""
import os, subprocess, sys
import argparse
import importlib
import datetime
import random
import time
import wandb
import numpy as np
import torch as T
import torch.nn.functional as F
from rl.algorithms.mfrl.mfrl import MFRL
from rl.control.policy import StochasticPolicy
from rl.value_functions.q_function import SoftQFunction
class ActorCritic: # Done
"""
Actor-Critic
An entity contains both the actor (policy) that acts on the environment,
and a critic (Q-function) that evaluate that state-action given a policy.
"""
def __init__(self,
obs_dim, act_dim,
act_up_lim, act_low_lim,
configs, seed, device
) -> None:
# print('Initialize AC!')
self.obs_dim, self.act_dim = obs_dim, act_dim
self.act_up_lim, self.act_low_lim = act_up_lim, act_low_lim
self.configs, self.seed = configs, seed
self._device_ = device
self.actor, self.critic, self.critic_target = None, None, None
self._build()
def _build(self):
self.actor = self._set_actor()
self.critic, self.critic_target = self._set_critic(), self._set_critic()
# parameters will be updated using a weighted average
for p in self.critic_target.parameters():
p.requires_grad = False
def _set_actor(self):
net_configs = self.configs['actor']['network']
return StochasticPolicy(
self.obs_dim, self.act_dim,
self.act_up_lim, self.act_low_lim,
net_configs, self._device_, self.seed)
def _set_critic(self):
net_configs = self.configs['critic']['network']
return SoftQFunction(
self.obs_dim, self.act_dim,
net_configs, self._device_, self.seed)
def get_q(self, o, a):
return self.critic(o, a)
def get_q_target(self, o, a):
return self.critic_target(o, a)
def get_pi(self, o, a=None, reparameterize=True, deterministic=False, return_log_pi=False):
pi, log_pi, entropy = self.actor(o, a, reparameterize, deterministic, return_log_pi)
return pi, log_pi
def get_action(self, o, a=None, reparameterize=False, deterministic=False, return_log_pi=False):
o = T.Tensor(o)
if a: a = T.Tensor(a)
with T.no_grad(): a, _, _ = self.actor(o, a, reparameterize, deterministic, return_log_pi)
return a.cpu()
def get_action_np(self, o, a=None, reparameterize=False, deterministic=False, return_log_pi=False):
return self.get_action(o, a, reparameterize, deterministic, return_log_pi).numpy()
def get_pi_and_q(self, o, a=None):
pi, log_pi, entropy = self.actor(o, a)
return pi, log_pi, self.critic(o)
class SAC(MFRL):
"""
Algorithm: Soft Actor-Critic (Off-policy, Model-free)
01. Input: θ1, θ2, φ > Initial parameters
02. ¯θ1 ← θ1, ¯θ2 ← θ2 > Initialize target network weights
03. D ← ∅ > Initialize an empty replay pool
04. for each iteration do
05. for each environment step do
06. at ∼ πφ(at|st) > Sample action from the policy
07. st+1 ∼ p(st+1|st, at) > Sample transition from the environment
08. D ← D ∪ {(st, at, r(st, at), st+1)} > Store the transition in the replay pool
09. end for
10. for each gradient step do
11. θi ← θi − λ_Q ˆ∇θi J_Q(θi) for i ∈ {1, 2} > Update the Q-function parameters
12. φ ← φ − λ_π ˆ∇φ J_π(φ) > Update policy weights
13. α ← α − λ ˆ∇α J(α) > Adjust temperature
14. ¯θi ← τ θi + (1 − τ) + ¯θi for i ∈ {1, 2} > Update target network weights
15. end for
16. end for
17. Output: θ1, θ2, φ > Optimized parameters
"""
def __init__(self, exp_prefix, configs, seed, device, wb) -> None:
super(SAC, self).__init__(exp_prefix, configs, seed, device)
# print('init SAC Algorithm!')
self.configs = configs
self.seed = seed
self._device_ = device
self.WandB = wb
self._build()
def _build(self):
super(SAC, self)._build()
self._build_sac()
def _build_sac(self):
self._set_actor_critic()
self._set_alpha()
def _set_actor_critic(self):
self.actor_critic = ActorCritic(
self.obs_dim, self.act_dim,
self.act_up_lim, self.act_low_lim,
self.configs, self.seed, self._device_)
def _set_alpha(self):
if self.configs['actor']['automatic_entropy']:
# Learned Temprature
device = self._device_
optimizer = 'T.optim.' + self.configs['actor']['network']['optimizer']
lr = self.configs['actor']['network']['lr']
target_entropy = self.configs['actor']['target_entropy']
if target_entropy == 'auto':
self.target_entropy = (
- 1.0 * T.prod(
T.Tensor(self.learn_env.action_space.shape).to(device)
).item())
self.log_alpha = T.zeros(1, requires_grad=True, device=device)
self.alpha = self.log_alpha.exp().item()
self.alpha_optimizer = eval(optimizer)([self.log_alpha], lr)
else:
# Fixed Temprature
self.alpha = self.configs['actor']['alpha']
def learn(self):
N = self.configs['algorithm']['learning']['epochs']
NT = self.configs['algorithm']['learning']['epoch_steps']
Ni = self.configs['algorithm']['learning']['init_epochs']
Nx = self.configs['algorithm']['learning']['expl_epochs']
E = self.configs['algorithm']['learning']['env_steps']
G = self.configs['algorithm']['learning']['grad_AC_steps']
batch_size = self.configs['data']['batch_size']
o, Z, el, t = self.learn_env.reset(), 0, 0, 0
# o, Z, el, t = self.initialize_learning(NT, Ni)
oldJs = [0, 0, 0]
JQList, JAlphaList, JPiList = [0]*Ni, [0]*Ni, [0]*Ni
AlphaList = [self.alpha]*Ni
logs = dict()
lastEZ, lastES = 0, -2
start_time_real = time.time()
for n in range(1, N+1):
if self.configs['experiment']['print_logs']:
print('=' * 80)
if n > Nx:
print(f'\n[ Epoch {n} Learning ]')
elif n > Ni:
print(f'\n[ Epoch {n} Exploration + Learning ]')
else:
print(f'\n[ Epoch {n} Inintial Exploration ]')
# print(f'[ Replay Buffer ] Size: {self.buffer.size}, pointer: {self.buffer.ptr}')
nt = 0
learn_start_real = time.time()
while nt < NT:
# Interaction steps
for e in range(1, E+1):
o, Z, el, t = self.internact(n, o, Z, el, t)
# Taking gradient steps after exploration
if n > Ni:
for g in range(1, G+1):
batch = self.buffer.sample_batch(batch_size, device=self._device_)
Jq, Jalpha, Jpi = self.trainAC(g, batch, oldJs)
oldJs = [Jq, Jalpha, Jpi]
JQList.append(Jq.item())
JPiList.append(Jpi.item())
if self.configs['actor']['automatic_entropy']:
JAlphaList.append(Jalpha.item())
AlphaList.append(self.alpha)
nt += E
logs['time/training '] = time.time() - learn_start_real
logs['training/sac/Jq '] = np.mean(JQList)
logs['training/sac/Jpi '] = np.mean(JPiList)
if self.configs['actor']['automatic_entropy']:
logs['training/sac/Jalpha '] = np.mean(JAlphaList)
logs['training/sac/alpha '] = np.mean(AlphaList)
eval_start_real = time.time()
EZ, ES, EL = self.evaluate()
logs['time/evaluation '] = time.time() - eval_start_real
if self.configs['environment']['type'] == 'mujoco-pddm-shadowhand':
logs['evaluation/episodic_score_mean '] = np.mean(ES)
logs['evaluation/episodic_score_std '] = np.std(ES)
else:
logs['evaluation/episodic_return_mean'] = np.mean(EZ)
logs['evaluation/episodic_return_std '] = np.std(EZ)
logs['evaluation/episodic_length_mean'] = np.mean(EL)
logs['time/total '] = time.time() - start_time_real
if n > (N - 50):
if self.configs['environment']['type'] == 'mujoco-pddm-shadowhand':
if np.mean(ES) > lastES:
print(f'[ Epoch {n} Agent Saving ] ')
env_name = self.configs['environment']['name']
alg_name = self.configs['algorithm']['name']
T.save(self.actor_critic.actor,
f'./saved_agents/{env_name}-{alg_name}-seed:{self.seed}-epoch:{n}.pth.tar')
lastES = np.mean(ES)
else:
if np.mean(EZ) > lastEZ:
print(f'[ Epoch {n} Agent Saving ] ')
env_name = self.configs['environment']['name']
alg_name = self.configs['algorithm']['name']
T.save(self.actor_critic.actor,
f'./saved_agents/{env_name}-{alg_name}-seed:{self.seed}-epoch:{n}.pth.tar')
lastEZ = np.mean(EZ)
# Printing logs
if self.configs['experiment']['print_logs']:
for k, v in logs.items():
print(f'{k} {round(v, 2)}'+(' '*10))
# WandB
if self.WandB:
wandb.log(logs)
self.learn_env.close()
self.eval_env.close()
def trainAC(self, g, batch, oldJs):
AUI = self.configs['algorithm']['learning']['alpha_update_interval']
PUI = self.configs['algorithm']['learning']['policy_update_interval']
TUI = self.configs['algorithm']['learning']['target_update_interval']
Jq = self.updateQ(batch)
Jalpha = self.updateAlpha(batch)# if (g % AUI == 0) else oldJs[1]
Jpi = self.updatePi(batch)# if (g % PUI == 0) else oldJs[2]
if g % TUI == 0:
self.updateTarget()
return Jq, Jalpha, Jpi
def updateQ(self, batch):
""""
JQ(θ) = E(st,at)∼D[ 0.5 ( Qθ(st, at)
− r(st, at)
+ γ Est+1∼D[ Eat+1~πφ(at+1|st+1)[ Qθ¯(st+1, at+1)
− α log(πφ(at+1|st+1)) ] ] ]
"""
gamma = self.configs['critic']['gamma']
O = batch['observations']
A = batch['actions']
R = batch['rewards']
O_next = batch['observations_next']
D = batch['terminals']
# Calculate two Q-functions
# Qs = self.actor_critic.critic(O, A)
Qs = self.actor_critic.get_q(O, A)
# # Bellman backup for Qs
with T.no_grad():
# pi_next, log_pi_next = self.actor_critic.actor(O_next, reparameterize=True, return_log_pi=True)
pi_next, log_pi_next = self.actor_critic.get_pi(O_next, reparameterize=True, return_log_pi=True)
A_next = pi_next
# Qs_targ = T.cat(self.actor_critic.critic_target(O_next, A_next), dim=1)
Qs_targ = T.cat(self.actor_critic.get_q_target(O_next, A_next), dim=1)
min_Q_targ, _ = T.min(Qs_targ, dim=1, keepdim=True)
Qs_backup = R + gamma * (1 - D) * (min_Q_targ - self.alpha * log_pi_next)
# # MSE loss
Jq = 0.5 * sum([F.mse_loss(Q, Qs_backup) for Q in Qs])
# Gradient Descent
self.actor_critic.critic.optimizer.zero_grad()
Jq.backward()
self.actor_critic.critic.optimizer.step()
return Jq
def updateAlpha(self, batch):
"""
αt* = arg min_αt Eat∼πt∗[ −αt log( πt*(at|st; αt) ) − αt H¯
"""
if self.configs['actor']['automatic_entropy']:
# Learned Temprature
O = batch['observations']
with T.no_grad():
# _, log_pi = self.actor_critic.actor(O, return_log_pi=True)
_, log_pi = self.actor_critic.get_pi(O, return_log_pi=True)
Jalpha = - ( self.log_alpha * (log_pi + self.target_entropy) ).mean()
# Gradient Descent
self.alpha_optimizer.zero_grad()
Jalpha.backward()
self.alpha_optimizer.step()
self.alpha = self.log_alpha.exp().item()
return Jalpha
else:
# Fixed Temprature
return 0.0
def updatePi(self, batch):
"""
Jπ(φ) = Est∼D[ Eat∼πφ[α log (πφ(at|st)) − Qθ(st, at)] ]
"""
O = batch['observations']
# Policy Evaluation
# pi, log_pi = self.actor_critic.actor(O, return_log_pi=True)
# Qs_pi = T.cat(self.actor_critic.critic(O, pi), dim=1)
pi, log_pi = self.actor_critic.get_pi(O, reparameterize=True, return_log_pi=True)
Qs_pi = T.cat(self.actor_critic.get_q(O, pi), dim=1)
min_Q_pi, _ = T.min(Qs_pi, dim=1, keepdim=True)
# Policy Improvement
Jpi = (self.alpha * log_pi - min_Q_pi).mean()
# Gradient Ascent
self.actor_critic.actor.optimizer.zero_grad()
Jpi.backward()
self.actor_critic.actor.optimizer.step()
return Jpi
def updateTarget(self):
# print('updateTarget')
tau = self.configs['critic']['tau']
with T.no_grad():
for p, p_targ in zip(self.actor_critic.critic.parameters(),
self.actor_critic.critic_target.parameters()):
p_targ.data.copy_(tau * p.data + (1 - tau) * p_targ.data)
def main(exp_prefix, config, seed, device, wb):
print('Start an SAC experiment...')
print('\n')
configs = config.configurations
if seed:
random.seed(seed), np.random.seed(seed), T.manual_seed(seed)
alg_name = configs['algorithm']['name']
env_name = configs['environment']['name']
env_type = configs['environment']['type']
group_name = f"{env_name}-{alg_name}"
exp_prefix = f"seed:{seed}"
if wb:
# print('WandB')
wandb.init(
name=exp_prefix,
group=group_name,
# project='test',
project='AMMI-RL-2022',
config=configs
)
agent = SAC(exp_prefix, configs, seed, device, wb)
agent.learn()
print('\n')
print('... End the SAC experiment')
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-exp_prefix', type=str)
parser.add_argument('-cfg', type=str)
parser.add_argument('-seed', type=str)
parser.add_argument('-device', type=str)
parser.add_argument('-wb', type=str)
args = parser.parse_args()
exp_prefix = args.exp_prefix
| |
__license__ = """
Copyright (c) 2012 mpldatacursor developers
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.
"""
import numpy as np
import matplotlib.transforms as mtransforms
from mpl_toolkits import mplot3d
#-- Artist-specific pick info functions --------------------------------------
def _coords2index(im, x, y, inverted=False):
"""
Converts data coordinates to index coordinates of the array.
Parameters
-----------
im : An AxesImage instance
The image artist to operation on
x : number
The x-coordinate in data coordinates.
y : number
The y-coordinate in data coordinates.
inverted : bool, optional
If True, convert index to data coordinates instead of data coordinates
to index.
Returns
--------
i, j : Index coordinates of the array associated with the image.
"""
xmin, xmax, ymin, ymax = im.get_extent()
if im.origin == 'upper':
ymin, ymax = ymax, ymin
data_extent = mtransforms.Bbox([[ymin, xmin], [ymax, xmax]])
array_extent = mtransforms.Bbox([[0, 0], im.get_array().shape[:2]])
trans = mtransforms.BboxTransformFrom(data_extent) +\
mtransforms.BboxTransformTo(array_extent)
if inverted:
trans = trans.inverted()
return trans.transform_point([y,x]).astype(int)
def image_props(event):
"""
Get information for a pick event on an ``AxesImage`` artist. Returns a dict
of "i" & "j" index values of the image for the point clicked, and "z": the
(uninterpolated) value of the image at i,j.
Parameters
-----------
event : PickEvent
The pick event to process
Returns
--------
props : dict
A dict with keys: z, i, j
"""
x, y = event.mouseevent.xdata, event.mouseevent.ydata
i, j = _coords2index(event.artist, x, y)
z = event.artist.get_array()[i,j]
if z.size > 1:
# Override default numpy formatting for this specific case. Bad idea?
z = ', '.join('{:0.3g}'.format(item) for item in z)
return dict(z=z, i=i, j=j)
def line_props(event):
"""
Get information for a pick event on a Line2D artist (as created with
``plot``.)
This will yield x and y values that are interpolated between vertices
(instead of just being the position of the mouse) or snapped to the nearest
vertex if only the vertices are drawn.
Parameters
-----------
event : PickEvent
The pick event to process
Returns
--------
props : dict
A dict with keys: x & y
"""
xclick, yclick = event.mouseevent.xdata, event.mouseevent.ydata
i = event.ind[0]
xorig, yorig = event.artist.get_xydata().T
# For points-only lines, snap to the nearest point.
linestyle = event.artist.get_linestyle()
if linestyle in ['none', ' ', '', None, 'None']:
return dict(x=xorig[i], y=yorig[i])
# ax.step is actually implemented as a Line2D with a different drawstyle...
xs_data = xorig[max(i - 1, 0) : i + 2]
ys_data = yorig[max(i - 1, 0) : i + 2]
drawstyle = event.artist.drawStyles[event.artist.get_drawstyle()]
if drawstyle == "_draw_lines":
pass
elif drawstyle == "_draw_steps_pre":
xs_data = _interleave(xs_data, xs_data[:-1])
ys_data = _interleave(ys_data, ys_data[1:])
elif drawstyle == "_draw_steps_post":
xs_data = _interleave(xs_data, xs_data[1:])
ys_data = _interleave(ys_data, ys_data[:-1])
elif drawstyle == "_draw_steps_mid":
mid_xs = (xs_data[:-1] + xs_data[1:]) / 2
xs_data = _interleave(xs_data, np.column_stack([mid_xs, mid_xs]))
ys_data = _interleave(
ys_data, np.column_stack([ys_data[:-1], ys_data[1:]]))
else:
raise ValueError(
"Unknown drawstyle: {}".format(event.artist.get_drawstyle()))
# The artist transform may be different from the axes transform (e.g.,
# axvline/axhline)
artist_transform = event.artist.get_transform()
axes_transform = event.artist.axes.transData
xs_screen, ys_screen = (
artist_transform.transform(
np.column_stack([xs_data, ys_data]))).T
xclick_screen, yclick_screen = (
axes_transform.transform([xclick, yclick]))
x_screen, y_screen = _interpolate_line(xs_screen, ys_screen,
xclick_screen, yclick_screen)
x, y = axes_transform.inverted().transform([x_screen, y_screen])
return dict(x=x, y=y)
def _interleave(a, b):
"""Interleave arrays a and b; b may have multiple columns and must be
shorter by 1.
"""
b = np.column_stack([b]) # Turn b into a column array.
nx, ny = b.shape
c = np.zeros((nx + 1, ny + 1))
c[:, 0] = a
c[:-1, 1:] = b
return c.ravel()[:-(c.shape[1] - 1)]
def _interpolate_line(xorig, yorig, xclick, yclick):
"""Find the nearest point on a polyline segment to the point *xclick*
*yclick*."""
candidates = []
# The closest point may be a vertex.
for x, y in zip(xorig, yorig):
candidates.append((np.hypot(xclick - x, yclick - y), (x, y)))
# Or it may be a projection on a segment.
for (x0, x1), (y0, y1) in zip(zip(xorig, xorig[1:]), zip(yorig, yorig[1:])):
vec1 = np.array([x1 - x0, y1 - y0])
vec1 /= np.linalg.norm(vec1)
vec2 = np.array([xclick - x0, yclick - y0])
dist_along = vec1.dot(vec2)
x, y = np.array([x0, y0]) + dist_along * vec1
# Drop if out of the segment.
if (x - x0) * (x - x1) > 0 or (y - y0) * (y - y1) > 0:
continue
candidates.append((np.hypot(xclick - x, yclick - y), (x, y)))
_, (x, y) = min(candidates)
return x, y
def collection_props(event):
"""
Get information for a pick event on an artist collection (e.g.
LineCollection, PathCollection, PatchCollection, etc). This will"""
ind = event.ind[0]
arr = event.artist.get_array()
# If a constant color/c/z was specified, don't return it
if arr is None or len(arr) == 1:
z = None
else:
z = arr[ind]
return dict(z=z, c=z)
def scatter_props(event):
"""
Get information for a pick event on a PathCollection artist (usually
created with ``scatter``).
Parameters
-----------
event : PickEvent
The pick event to process
Returns
--------
A dict with keys:
`c`: The value of the color array at the point clicked.
`s`: The value of the size array at the point clicked.
`z`: Identical to `c`. Specified for convenience.
Notes
-----
If constant values were specified to ``c`` or ``s`` when calling
``scatter``, `c` and/or `z` will be ``None``.
"""
# Use only the first item, if multiple items were selected
ind = event.ind[0]
try:
sizes = event.artist.get_sizes()
except AttributeError:
sizes = None
# If a constant size/s was specified, don't return it
if sizes is None or len(sizes) == 1:
s = None
else:
s = sizes[ind]
try:
# Snap to the x, y of the point... (assuming it's created by scatter)
xorig, yorig = event.artist.get_offsets().T
x, y = xorig[ind], yorig[ind]
return dict(x=x, y=y, s=s)
except IndexError:
# Not created by scatter...
return dict(s=s)
def errorbar_props(event):
if hasattr(event.artist, '_mpldatacursor_parent'):
container = event.artist._mpldatacursor_parent
else:
return {}
if hasattr(event, 'ind') and event.ind is not None:
i = event.ind[0]
else:
return {}
xerr = yerr = [None] * i
if container.has_yerr and container.has_xerr:
xerr = _extract_xerr(container[2][0])
yerr = _extract_yerr(container[2][1])
elif container.has_yerr:
xerr = _extract_xerr(container[2][0])
elif container.has_xerr:
yerr = _extract_xerr(container[2][0])
x, y = container[0].get_xydata().T
return {'xerror':xerr[i], 'yerror':yerr[i], 'x':x[i], 'y':y[i]}
def _extract_yerr(errbar_artist):
segments = errbar_artist.get_segments()
return [abs(np.diff(seg[:,1])[0]) for seg in segments]
def _extract_xerr(errbar_artist):
segments = errbar_artist.get_segments()
return [abs(np.diff(seg[:,0])[0]) for seg in segments]
def three_dim_props(event):
"""
Get information for a pick event on a 3D artist.
Parameters
-----------
event : PickEvent
The pick event to process
Returns
--------
A dict with keys:
`x`: The estimated x-value of the click on the artist
`y`: The estimated y-value of the click on the artist
`z`: The estimated z-value of the click on the artist
Notes
-----
Based on mpl_toolkits.axes3d.Axes3D.format_coord
Many thanks to <NAME> for pointing this out!
"""
ax = event.artist.axes
if ax.M is None:
return {}
xd, yd = event.mouseevent.xdata, event.mouseevent.ydata
p = (xd, yd)
edges = ax.tunit_edges()
ldists = [(mplot3d.proj3d.line2d_seg_dist(p0, p1, p), i) for \
i, (p0, p1) in enumerate(edges)]
ldists.sort()
# nearest edge
edgei = ldists[0][1]
p0, p1 = edges[edgei]
# scale the z value to match
x0, y0, z0 = p0
x1, y1, z1 = p1
d0 = np.hypot(x0-xd, y0-yd)
d1 = np.hypot(x1-xd, y1-yd)
dt = d0+d1
z = d1/dt * z0 + d0/dt * z1
x, y, z = | |
stations = { 'acheng': 'ACB',
'aershan': 'ART',
'aershanbei': 'ARX',
'aihe': 'AHP',
'aijiacun': 'AJJ',
'ajin': 'AJD',
'akesu': 'ASR',
'aketao': 'AER',
'alashankou': 'AKR',
'alihe': 'AHX',
'alongshan': 'ASX',
'amuer': 'JTX',
'ananzhuang': 'AZM',
'anda': 'ADX',
'ande': 'ARW',
'anding': 'ADP',
'angangxi': 'AAX',
'anguang': 'AGT',
'anhua': 'PKQ',
'anjia': 'AJB',
'ankang': 'AKY',
'ankouyao': 'AYY',
'anlong': 'AUZ',
'anlu': 'ALN',
'anping': 'APT',
'anqing': 'AQH',
'anqingxi': 'APH',
'anren': 'ARG',
'anshan': 'AST',
'anshanxi': 'AXT',
'anshun': 'ASW',
'anshunxi': 'ASE',
'antang': 'ATV',
'antingbei': 'ASH',
'antu': 'ATL',
'antuxi': 'AXL',
'anxi': 'AXS',
'anyang': 'AYF',
'anyangdong': 'ADF',
'aojiang': 'ARH',
'aolibugao': 'ALD',
'atushi': 'ATR',
'babu': 'BBE',
'bachu': 'BCR',
'badaling': 'ILP',
'badong': 'BNN',
'baibiguan': 'BGV',
'baicheng': 'BCT',
'baigou': 'FEP',
'baiguo': 'BGM',
'baihe': 'BEL',
'baihedong': 'BIY',
'baihexian': 'BEY',
'baijian': 'BAP',
'baijigou': 'BJJ',
'baijipo': 'BBM',
'baikuipu': 'BKB',
'bailang': 'BRZ',
'bailixia': 'AAP',
'baimajing': 'BFQ',
'baiqi': 'BQP',
'baiquan': 'BQL',
'baise': 'BIZ',
'baisha': 'BSW',
'baishanshi': 'HJL',
'baishapo': 'BPM',
'baishishan': 'BAL',
'baishuijiang': 'BSY',
'baishuixian': 'BGY',
'baishuizhen': 'BUM',
'baiyangdian': 'FWP',
'baiyi': 'FHW',
'baiyinchagan': 'BYC',
'baiyinhuanan': 'FNC',
'baiyinhushuo': 'BCD',
'baiyinshi': 'BNJ',
'baiyintala': 'BID',
'baiyinxi': 'BXJ',
'baiyunebo': 'BEC',
'bajiaotai': 'BTD',
'balin': 'BLX',
'bamiancheng': 'BMD',
'bamiantong': 'BMB',
'bancheng': 'BUP',
'banmaoqing': 'BNM',
'bantian': 'BTQ',
'baodi': 'BPP',
'baoding': 'BDP',
'baodingdong': 'BMP',
'baohuashan': 'BWH',
'baoji': 'BJY',
'baojinan': 'BBY',
'baokang': 'BKD',
'baolage': 'BQC',
'baolin': 'BNB',
'baolongshan': 'BND',
'baoqing': 'BUB',
'baoquanling': 'BQB',
'baotou': 'BTC',
'baotoudong': 'BDC',
'bashan': 'BAY',
'baxiantong': 'VXD',
'bayangaole': 'BAC',
'bayuquan': 'BYT',
'bazhong': 'IEW',
'bazhongdong': 'BDE',
'bazhou': 'RMP',
'bazhouxi': 'FOP',
'beian': 'BAB',
'beibei': 'BPW',
'beidaihe': 'BEP',
'beihai': 'BHZ',
'beijiao': 'IBQ',
'beijing': 'BJP',
'beijingbei': 'VAP',
'beijingdong': 'BOP',
'beijingnan': 'VNP',
'beijingxi': 'BXP',
'beijingzi': 'BRT',
'beiliu': 'BOZ',
'beimaquanzi': 'BRP',
'beipiaonan': 'RPD',
'beitai': 'BTT',
'beitun': 'BYP',
'beitunshi': 'BXR',
'beiying': 'BIV',
'beiyinhe': 'BYB',
'beizhai': 'BVP',
'bencha': 'FWH',
'bengbu': 'BBH',
'bengbunan': 'BMH',
'benhong': 'BVC',
'benxi': 'BXT',
'benxihu': 'BHT',
'benxixincheng': 'BVT',
'bijiang': 'BLQ',
'bijiashan': 'BSB',
'bijiguan': 'BJM',
'binhai': 'FHP',
'binhaibei': 'FCP',
'binjiang': 'BJB',
'binxian': 'BXY',
'binyang': 'UKZ',
'binzhou': 'BIK',
'bishan': 'FZW',
'boao': 'BWQ',
'bobai': 'BBZ',
'boketu': 'BKX',
'bole': 'BOR',
'boli': 'BLB',
'botou': 'BZP',
'boxing': 'BXK',
'bozhou': 'BZH',
'buhai': 'BUT',
'buliekai': 'BLR',
'caijiagou': 'CJT',
'caijiapo': 'CJY',
'caishan': 'CON',
'cangnan': 'CEH',
'cangshi': 'CST',
'cangxi': 'CXE',
'cangzhou': 'COP',
'cangzhouxi': 'CBP',
'caohai': 'WBW',
'caohekou': 'CKT',
'caoshi': 'CSL',
'caoxian': 'CXK',
'caozili': 'CFP',
'ceheng': 'CHZ',
'cenxi': 'CNZ',
'chabuga': 'CBC',
'chaigang': 'CGT',
'chaigoupu': 'CGV',
'chaihe': 'CHB',
'chajiang': 'CAM',
'chaka': 'CVO',
'chaling': 'CDG',
'chalingnan': 'CNG',
'changcheng': 'CEJ',
'changchong': 'CCM',
'changchun': 'CCT',
'changchunnan': 'CET',
'changchunxi': 'CRT',
'changde': 'VGQ',
'changdian': 'CDT',
'changge': 'CEF',
'changle': 'CLK',
'changli': 'CLP',
'changlingzi': 'CLT',
'changlinhe': 'FVH',
'changnong': 'CNJ',
'changping': 'DAQ',
'changpingbei': 'VBP',
'changpingdong': 'FQQ',
'changpoling': 'CPM',
'changqingqiao': 'CQJ',
'changsha': 'CSQ',
'changshanan': 'CWQ',
'changshantun': 'CVT',
'changshou': 'EFW',
'changshoubei': 'COW',
'changshouhu': 'CSE',
'changting': 'CES',
'changtingnan': 'CNS',
'changtingzhen': 'CDB',
'changtu': 'CTT',
'changtuxi': 'CPT',
'changwu': 'CWY',
'changxing': 'CBH',
'changxingnan': 'CFH',
'changyang': 'CYN',
'changyuan': 'CYF',
'changzheng': 'CZJ',
'changzhi': 'CZF',
'changzhibei': 'CBF',
'changzhou': 'CZH',
'changzhoubei': 'ESH',
'changzhuang': 'CVK',
'chaohu': 'CIH',
'chaohudong': 'GUH',
'chaolianggou': 'CYP',
'chaoshan': 'CBQ',
'chaoyang': 'CYD',
'chaoyangchuan': 'CYL',
'chaoyangdi': 'CDD',
'chaoyangzhen': 'CZL',
'chaozhou': 'CKQ',
'chasuqi': 'CSC',
'chengcheng': 'CUY',
'chengde': 'CDP',
'chengdedong': 'CCP',
'chengdu': 'CDW',
'chengdudong': 'ICW',
'chengdunan': 'CNW',
'chenggaozi': 'CZB',
'chenggu': 'CGY',
'chengjisihan': 'CJX',
'chenguanying': 'CAJ',
'chengyang': 'CEK',
'chengzitan': 'CWT',
'chenming': 'CMB',
'chenqing': 'CQB',
'chenxi': 'CXQ',
'chenxiangtun': 'CXT',
'chenzhou': 'CZQ',
'chenzhouxi': 'ICQ',
'chezhuanwan': 'CWM',
'chibi': 'CBN',
'chibibei': 'CIN',
'chifeng': 'CFD',
'chifengxi': 'CID',
'chizhou': 'IYH',
'chongqing': 'CQW',
'chongqingbei': 'CUW',
'chongqingnan': 'CRW',
'chongren': 'CRG',
'chongzuo': 'CZZ',
'chuangyecun': 'CEX',
'chunwan': 'CQQ',
'chunyang': 'CAL',
'chushan': 'CSB',
'chuxiong': 'COM',
'chuzhou': 'CXH',
'chuzhoubei': 'CUH',
'cili': 'CUQ',
'cishan': 'CSP',
'cixi': 'CRP',
'cixian': 'CIP',
'ciyao': 'CYK',
'congjiang': 'KNW',
'cuihuangkou': 'CHP',
'cuogang': 'CAX',
'daan': 'RAT',
'daanbei': 'RNT',
'daba': 'DBJ',
'daban': 'DBC',
'dachaigou': 'DGJ',
'dacheng': 'DCT',
'dadenggou': 'DKJ',
'dafangnan': 'DNE',
'daguan': 'RGW',
'daguantun': 'DTT',
'dagushan': 'RMT',
'dahongqi': 'DQD',
'dahuichang': 'DHP',
'dahushan': 'DHD',
'dailing': 'DLB',
'daixian': 'DKV',
'daiyue': 'RYV',
'dajiagou': 'DJT',
'dajian': 'DFP',
'daju': 'DIM',
'dakoutun': 'DKP',
'dalateqi': 'DIC',
'dalatexi': 'DNC',
'dali': 'DKM',
'dalian': 'DLT',
'dalianbei': 'DFT',
'dalin': 'DLD',
'daluhao': 'DLC',
'dandong': 'DUT',
'dandongxi': 'RWT',
'danfeng': 'DGY',
'dangshan': 'DKH',
'dangshannan': 'PRH',
'dangtudong': 'OWH',
'dangyang': 'DYN',
'dani': 'DNZ',
'dantu': 'RUH',
'danxiashan': 'IRQ',
'danyang': 'DYH',
'danyangbei': 'EXH',
'daobao': 'RBT',
'daoerdeng': 'DRD',
'daoqing': 'DML',
'daozhou': 'DFZ',
'dapanshi': 'RPP',
'dapingfang': 'DPD',
'dapu': 'DPI',
'daqilaha': 'DQX',
'daqing': 'DZX',
'daqingdong': 'LFX',
'daqinggou': 'DSD',
'daqingxi': 'RHX',
'dashiqiao': 'DQT',
'dashitou': 'DSL',
'dashitounan': 'DAL',
'dashizhai': 'RZT',
'datianbian': 'DBM',
'datong': 'DTV',
'datongxi': 'DTO',
'datun': 'DNT',
'dawang': 'WWQ',
'dawangtan': 'DZZ',
'dawanzi': 'DFM',
'dawukou': 'DFJ',
'daxing': 'DXX',
'daxinggou': 'DXL',
'dayan': 'DYX',
'dayangshu': 'DUX',
'dayebei': 'DBN',
'daying': 'DYV',
'dayingdong': 'IAW',
'dayingzhen': 'DJP',
'dayingzi': 'DZD',
'dayu': 'DYG',
'dayuan': 'DYZ',
'dazhanchang': 'DTJ',
'dazhangzi': 'DAP',
'dazhou': 'RXW',
'dazhuyuan': 'DZY',
'dazunan': 'FQW',
'dean': 'DAG',
'debao': 'RBZ',
'debosi': 'RDT',
'dechang': 'DVW',
'deerbuer': 'DRX',
'dehui': 'DHT',
'dehuixi': 'DXT',
'delingha': 'DHO',
'dengshahe': 'DWT',
'dengta': 'DGT',
'dengzhou': 'DOF',
'deqing': 'DRH',
'deqingxi': 'MOH',
'dexing': 'DWG',
'deyang': 'DYW',
'dezhou': 'DZP',
'dezhoudong': 'DIP',
'dianjiang': 'DJE',
'dianxin': 'DXM',
'didao': 'DDB',
'dingbian': 'DYJ',
'dinghudong': 'UWQ',
'dinghushan': 'NVQ',
'dingnan': 'DNG',
'dingtao': 'DQK',
'dingxi': 'DSJ',
'dingxiang': 'DXV',
'dingyuan': 'EWH',
'dingzhou': 'DXP',
'dingzhoudong': 'DOP',
'diwopu': 'DWJ',
'dizhuang': 'DVQ',
'dongandong': 'DCZ',
'dongbianjing': 'DBB',
'dongdaihe': 'RDD',
'dongerdaohe': 'DRB',
'dongfang': 'UFQ',
'dongfanghong': 'DFB',
'dongfeng': 'DIL',
'donggangbei': 'RGT',
'dongguan': 'RTQ',
'dongguandong': 'DMQ',
'dongguang': 'DGP',
'donghai': 'DHB',
'donghaixian': 'DQH',
'dongjin': 'DKB',
'dongjingcheng': 'DJB',
'donglai': 'RVD',
'dongmiaohe': 'DEP',
'dongmingcun': 'DMD',
'dongmingxian': 'DNF',
'dongsheng': 'DOC',
'dongshengxi': 'DYC',
'dongtai': 'DBH',
'dongtonghua': 'DTL',
'dongwan': 'DRJ',
'dongxiang': 'DXG',
'dongxinzhuang': 'DXD',
'dongxu': 'RXP',
'dongying': 'DPK',
'dongyingnan': 'DOK',
'dongyudi': 'DBV',
'dongzhen': 'DNV',
'dongzhi': 'DCH',
'dongzhuang': 'DZV',
'douluo': 'DLV',
'douzhangzhuang': 'RZP',
'douzhuang': 'ROP',
'duanzhou': 'WZQ',
'duge': 'DMM',
'duiqingshan': 'DQB',
'duizhen': 'DWV',
'dujia': 'DJL',
'dujiangyan': 'DDW',
'dulitun': 'DTX',
'dunhua': 'DHL',
'dunhuang': 'DHJ',
'dushan': 'RWW',
'dushupu': 'DPM',
'duyun': 'RYW',
'duyundong': 'KJW',
'ebian': 'EBW',
'eerduosi': 'EEC',
'ejina': 'EJC',
'emei': 'EMW',
'emeishan': 'IXW',
'enshi': 'ESN',
'erdaogoumen': 'RDP',
'erdaowan': 'RDX',
'erlian': 'RLC',
'erlong': 'RLD',
'erlongshantun': 'ELA',
'ermihe': 'RML',
'erying': 'RYJ',
'ezhou': 'ECN',
'ezhoudong': 'EFN',
'faer': 'FEM',
'fanchangxi': 'PUH',
'fangchenggangbei': 'FBZ',
'fanjiatun': 'FTT',
'fanshi': 'FSV',
'fanzhen': 'VZK',
'faqi': 'FQE',
'feidong': 'FIH',
'feixian': 'FXK',
'fengcheng': 'FCG',
'fengchengdong': 'FDT',
'fengchengnan': 'FNG',
'fengdu': 'FUW',
'fenghua': 'FHH',
'fenghuangcheng': 'FHT',
'fenghuangjichang': 'FJQ',
'fenglezhen': 'FZB',
'fenglingdu': 'FLV',
'fengshuicun': 'FSJ',
'fengshun': 'FUQ',
'fengtun': 'FTX',
'fengxian': 'FXY',
'fengyang': 'FUH',
'fengzhen': 'FZC',
'fengzhou': 'FZY',
'fenhe': 'FEV',
'fenyang': 'FAV',
'fenyi': 'FYG',
'foshan': 'FSQ',
'fuan': 'FAS',
'fuchuan': 'FDZ',
'fuding': 'FES',
'fuhai': 'FHR',
'fujin': 'FIB',
'fulaerji': 'FRX',
'fuling': 'FLW',
'fulingbei': 'FEW',
'fuliqu': 'FLJ',
'fulitun': 'FTB',
'funan': 'FNH',
'funing': 'FNP',
'fuqing': 'FQS',
'fuquan': 'VMW',
'fushankou': 'FKP',
'fushanzhen': 'FZQ',
'fushun': 'FST',
'fushunbei': 'FET',
'fusong': 'FSL',
'fusui': 'FSZ',
'futian': 'NZQ',
'futuyu': 'FYP',
'fuxian': 'FEY',
'fuxiandong': 'FDY',
'fuxin': 'FXD',
'fuyang': 'FYH',
'fuyu': 'FYX',
'fuyuan': 'FYM',
'fuyubei': 'FBT',
'fuzhou': 'FZG',
'fuzhoubei': 'FBG',
'fuzhoudong': 'FDG',
'fuzhounan': 'FYS',
'gaizhou': 'GXT',
'gaizhouxi': 'GAT',
'gancaodian': 'GDJ',
'gangou': 'GGL',
'gangu': 'GGJ',
'ganhe': 'GAX',
'ganluo': 'VOW',
'ganqika': 'GQD',
'ganquan': 'GQY',
'ganquanbei': 'GEY',
'ganshui': 'GSW',
'gantang': 'GNJ',
'ganzhou': 'GZG',
'gaoan': 'GCG',
'gaobeidian': 'GBP',
'gaobeidiandong': 'GMP',
'gaocheng': 'GEP',
'gaocun': 'GCV',
'gaogezhuang': 'GGP',
'gaolan': 'GEJ',
'gaoloufang': 'GFM',
'gaomi': 'GMK',
'gaoping': 'GPF',
'gaoqiaozhen': 'GZD',
'gaoshanzi': 'GSD',
'gaotai': 'GTJ',
'gaotainan': 'GAJ',
'gaotan': 'GAY',
'gaoyi': 'GIP',
'gaoyixi': 'GNP',
'gaozhou': 'GSQ',
'gashidianzi': 'GXD',
'gediannan': 'GNN',
'geermu': 'GRO',
'gegenmiao': 'GGT',
'geju': 'GEM',
'genhe': 'GEX',
'gezhenpu': 'GZT',
'gongcheng': 'GCZ',
'gongmiaozi': 'GMC',
'gongnonghu': 'GRT',
'gongpengzi': 'GPT',
'gongqingcheng': 'GAG',
'gongyi': 'GXF',
'gongyinan': 'GYF',
'gongyingzi': 'GYD',
'gongzhuling': 'GLT',
'gongzhulingnan': 'GBT',
'goubangzi': 'GBD',
'guan': 'GFP',
'guangan': 'VJW',
'guangannan': 'VUW',
'guangao': 'GVP',
'guangde': 'GRH',
'guanghan': 'GHW',
'guanghanbei': 'GVW',
'guangmingcheng': 'IMQ',
'guangnanwei': 'GNM',
'guangning': 'FBQ',
'guangningsi': 'GQT',
'guangningsinan': 'GNT',
'guangshan': 'GUN',
'guangshui': 'GSN',
'guangtongbei': 'GPM',
'guangyuan': 'GYW',
'guangyuannan': 'GAW',
'guangze': 'GZS',
'guangzhou': 'GZQ',
'guangzhoubei': 'GBQ',
'guangzhoudong': 'GGQ',
'guangzhounan': 'IZQ',
'guangzhouxi': 'GXQ',
'guanlin': 'GLF',
'guanling': 'GLE',
'guanshui': 'GST',
'guanting': 'GTP',
'guantingxi': 'KEP',
'guanzhaishan': 'GSS',
'guanzijing': 'GOT',
'guazhou': 'GZJ',
'gucheng': 'GCN',
'guchengzhen': 'GZB',
'gudong': 'GDV',
'guian': 'GAE',
'guiding': 'GTW',
'guidingbei': 'FMW',
'guidingnan': 'IDW',
'guidingxian': 'KIW',
'guigang': 'GGZ',
'guilin': 'GLZ',
'guilinbei': 'GBZ',
'guilinxi': 'GEZ',
'guiliuhe': 'GHT',
'guiping': 'GAZ',
'guixi': 'GXG',
'guiyang': 'GIW',
'guiyangbei': 'KQW',
'gujiao': 'GJV',
'gujiazi': 'GKT',
'gulang': 'GLJ',
'gulian': 'GRX',
'guojiadian': 'GDT',
'guoleizhuang': 'GLP',
'guosong': 'GSL',
'guoyang': 'GYH',
'guozhen': 'GZY',
'gushankou': 'GSP',
'gushi': 'GXN',
'gutian': 'GTS',
'gutianbei': 'GBS',
'gutianhuizhi': 'STS',
'guyuan': 'GUJ',
'guzhen': 'GEH',
'haerbin': 'HBB',
'haerbinbei': 'HTB',
'haerbindong': 'VBB',
'haerbinxi': 'VAB',
'haianxian': 'HIH',
'haibei': 'HEB',
'haicheng': 'HCT',
'haichengxi': 'HXT',
'haidongxi': 'HDO',
'haikou': 'VUQ',
'haikoudong': 'HMQ',
'hailaer': 'HRX',
'hailin': 'HRB',
'hailong': 'HIL',
'hailun': 'HLB',
'haining': | |
# coding=utf-8
from __future__ import unicode_literals
import io
from copy import deepcopy
from mock import patch
from snips_nlu_utils import hash_str
from snips_nlu.constants import (
DATA, ENTITY, RES_ENTITY, RES_INTENT, RES_INTENT_NAME,
RES_PROBA, RES_SLOTS, RES_VALUE, SLOT_NAME, TEXT, STOP_WORDS)
from snips_nlu.dataset import Dataset
from snips_nlu.entity_parser import BuiltinEntityParser
from snips_nlu.exceptions import IntentNotFoundError, NotTrained
from snips_nlu.intent_parser import LookupIntentParser
from snips_nlu.intent_parser.lookup_intent_parser import _get_entity_scopes
from snips_nlu.pipeline.configs import LookupIntentParserConfig
from snips_nlu.result import (
empty_result, extraction_result, intent_classification_result,
unresolved_slot, parsing_result)
from snips_nlu.tests.utils import FixtureTest, TEST_PATH, EntityParserMock
class TestLookupIntentParser(FixtureTest):
def setUp(self):
super(TestLookupIntentParser, self).setUp()
slots_dataset_stream = io.StringIO(
"""
---
type: intent
name: dummy_intent_1
slots:
- name: dummy_slot_name
entity: dummy_entity_1
- name: dummy_slot_name2
entity: dummy_entity_2
- name: startTime
entity: snips/datetime
utterances:
- >
This is a [dummy_slot_name](dummy_1) query with another
[dummy_slot_name2](dummy_2) [startTime](at 10p.m.) or
[startTime](tomorrow)
- "This is a [dummy_slot_name](dummy_1) "
- "[startTime](tomorrow evening) there is a [dummy_slot_name](dummy_1)"
---
type: entity
name: dummy_entity_1
automatically_extensible: no
values:
- [dummy_a, dummy 2a, dummy a, 2 dummy a]
- [dummy_b, dummy b, dummy_bb, dummy_b]
- dummy d
---
type: entity
name: dummy_entity_2
automatically_extensible: no
values:
- [dummy_c, 3p.m., dummy_cc, dummy c]""")
self.slots_dataset = Dataset.from_yaml_files(
"en", [slots_dataset_stream]).json
def test_should_parse_intent(self):
# Given
dataset_stream = io.StringIO(
"""
---
type: intent
name: intent1
utterances:
- foo bar baz
---
type: intent
name: intent2
utterances:
- foo bar ban""")
dataset = Dataset.from_yaml_files("en", [dataset_stream]).json
parser = LookupIntentParser().fit(dataset)
text = "foo bar ban"
# When
parsing = parser.parse(text)
# Then
probability = 1.0
expected_intent = intent_classification_result(
intent_name="intent2", probability=probability)
self.assertEqual(expected_intent, parsing[RES_INTENT])
def test_should_parse_intent_with_filter(self):
# Given
dataset_stream = io.StringIO(
"""
---
type: intent
name: intent1
utterances:
- foo bar baz
---
type: intent
name: intent2
utterances:
- foo bar ban""")
dataset = Dataset.from_yaml_files("en", [dataset_stream]).json
parser = LookupIntentParser().fit(dataset)
text = "foo bar ban"
# When
parsing = parser.parse(text, intents=["intent1"])
# Then
self.assertEqual(empty_result(text, 1.0), parsing)
def test_should_parse_top_intents(self):
# Given
dataset_stream = io.StringIO("""
---
type: intent
name: intent1
utterances:
- meeting [time:snips/datetime](today)
---
type: intent
name: intent2
utterances:
- meeting tomorrow
---
type: intent
name: intent3
utterances:
- "[event_type](call) [time:snips/datetime](at 9pm)"
---
type: entity
name: event_type
values:
- meeting
- feedback session""")
dataset = Dataset.from_yaml_files("en", [dataset_stream]).json
parser = LookupIntentParser().fit(dataset)
text = "meeting tomorrow"
# When
results = parser.parse(text, top_n=3)
# Then
time_slot = {
"entity": "snips/datetime",
"range": {"end": 16, "start": 8},
"slotName": "time",
"value": "tomorrow"
}
event_slot = {
"entity": "event_type",
"range": {"end": 7, "start": 0},
"slotName": "event_type",
"value": "meeting"
}
weight_intent_1 = 1. / 2.
weight_intent_2 = 1.
weight_intent_3 = 1. / 3.
total_weight = weight_intent_1 + weight_intent_2 + weight_intent_3
proba_intent2 = weight_intent_2 / total_weight
proba_intent1 = weight_intent_1 / total_weight
proba_intent3 = weight_intent_3 / total_weight
expected_results = [
extraction_result(
intent_classification_result(
intent_name="intent2", probability=proba_intent2),
slots=[]),
extraction_result(
intent_classification_result(
intent_name="intent1", probability=proba_intent1),
slots=[time_slot]),
extraction_result(
intent_classification_result(
intent_name="intent3", probability=proba_intent3),
slots=[event_slot, time_slot])
]
self.assertEqual(expected_results, results)
@patch("snips_nlu.intent_parser.lookup_intent_parser" ".get_stop_words")
def test_should_parse_intent_with_stop_words(self, mock_get_stop_words):
# Given
mock_get_stop_words.return_value = {"a", "hey"}
dataset = self.slots_dataset
config = LookupIntentParserConfig(ignore_stop_words=True)
parser = LookupIntentParser(config).fit(dataset)
text = "Hey this is dummy_a query with another dummy_c at 10p.m. " \
"or at 12p.m."
# When
parsing = parser.parse(text)
# Then
probability = 1.0
expected_intent = intent_classification_result(
intent_name="dummy_intent_1", probability=probability)
self.assertEqual(expected_intent, parsing[RES_INTENT])
def test_should_parse_intent_with_duplicated_slot_names(self):
# Given
slots_dataset_stream = io.StringIO("""
---
type: intent
name: math_operation
slots:
- name: number
entity: snips/number
utterances:
- what is [number](one) plus [number](one)""")
dataset = Dataset.from_yaml_files("en", [slots_dataset_stream]).json
parser = LookupIntentParser().fit(dataset)
text = "what is one plus one"
# When
parsing = parser.parse(text)
# Then
probability = 1.0
expected_intent = intent_classification_result(
intent_name="math_operation", probability=probability)
expected_slots = [
{
"entity": "snips/number",
"range": {"end": 11, "start": 8},
"slotName": "number",
"value": "one"
},
{
"entity": "snips/number",
"range": {"end": 20, "start": 17},
"slotName": "number",
"value": "one"
}
]
self.assertDictEqual(expected_intent, parsing[RES_INTENT])
self.assertListEqual(expected_slots, parsing[RES_SLOTS])
def test_should_parse_intent_with_ambivalent_words(self):
# Given
slots_dataset_stream = io.StringIO("""
---
type: intent
name: give_flower
utterances:
- give a rose to [name](emily)
- give a daisy to [name](tom)
- give a tulip to [name](daisy)
""")
dataset = Dataset.from_yaml_files("en",
[slots_dataset_stream]).json
parser = LookupIntentParser().fit(dataset)
text = "give a daisy to emily"
# When
parsing = parser.parse(text)
# Then
expected_intent = intent_classification_result(
intent_name="give_flower", probability=1.0)
expected_slots = [
{
"entity": "name",
"range": {"end": 21, "start": 16},
"slotName": "name",
"value": "emily"
}
]
self.assertDictEqual(expected_intent, parsing[RES_INTENT])
self.assertListEqual(expected_slots, parsing[RES_SLOTS])
def test_should_ignore_completely_ambiguous_utterances(self):
# Given
dataset_stream = io.StringIO(
"""
---
type: intent
name: dummy_intent_1
utterances:
- Hello world
---
type: intent
name: dummy_intent_2
utterances:
- Hello world""")
dataset = Dataset.from_yaml_files("en", [dataset_stream]).json
parser = LookupIntentParser().fit(dataset)
text = "Hello world"
# When
res = parser.parse(text)
# Then
self.assertEqual(empty_result(text, 1.0), res)
def test_should_ignore_very_ambiguous_utterances(self):
# Given
dataset_stream = io.StringIO("""
---
type: intent
name: intent_1
utterances:
- "[event_type](meeting) tomorrow"
---
type: intent
name: intent_2
utterances:
- call [time:snips/datetime](today)
---
type: entity
name: event_type
values:
- call
- diner""")
dataset = Dataset.from_yaml_files("en", [dataset_stream]).json
parser = LookupIntentParser().fit(dataset)
text = "call tomorrow"
# When
res = parser.parse(text)
# Then
self.assertEqual(empty_result(text, 1.0), res)
def test_should_parse_slightly_ambiguous_utterances(self):
# Given
dataset_stream = io.StringIO("""
---
type: intent
name: intent_1
utterances:
- call tomorrow
---
type: intent
name: intent_2
utterances:
- call [time:snips/datetime](today)""")
dataset = Dataset.from_yaml_files("en", [dataset_stream]).json
parser = LookupIntentParser().fit(dataset)
text = "call tomorrow"
# When
res = parser.parse(text)
# Then
expected_intent = intent_classification_result(
intent_name="intent_1", probability=2. / 3.)
expected_result = parsing_result(text, expected_intent, [])
self.assertEqual(expected_result, res)
def test_should_not_parse_when_not_fitted(self):
# Given
parser = LookupIntentParser()
# When / Then
self.assertFalse(parser.fitted)
with self.assertRaises(NotTrained):
parser.parse("foobar")
def test_should_parse_intent_after_deserialization(self):
# Given
dataset = self.slots_dataset
shared = self.get_shared_data(dataset)
parser = LookupIntentParser(**shared).fit(dataset)
parser.persist(self.tmp_file_path)
deserialized_parser = LookupIntentParser.from_path(
self.tmp_file_path, **shared)
text = "this is a dummy_a query with another dummy_c at 10p.m. or " \
"at 12p.m."
# When
parsing = deserialized_parser.parse(text)
# Then
probability = 1.0
expected_intent = intent_classification_result(
intent_name="dummy_intent_1", probability=probability)
self.assertEqual(expected_intent, parsing[RES_INTENT])
def test_should_parse_slots(self):
# Given
dataset = self.slots_dataset
parser = LookupIntentParser().fit(dataset)
texts = [
(
"this is a dummy a query with another dummy_c at 10p.m. or at"
" 12p.m.",
[
unresolved_slot(
match_range=(10, 17),
value="dummy a",
entity="dummy_entity_1",
slot_name="dummy_slot_name",
),
unresolved_slot(
match_range=(37, 44),
value="dummy_c",
entity="dummy_entity_2",
slot_name="dummy_slot_name2",
),
unresolved_slot(
match_range=(45, 54),
value="at 10p.m.",
entity="snips/datetime",
slot_name="startTime",
),
unresolved_slot(
match_range=(58, 67),
value="at 12p.m.",
entity="snips/datetime",
slot_name="startTime",
),
],
),
(
"this, is,, a, dummy a query with another dummy_c at 10pm or "
"at 12p.m.",
[
unresolved_slot(
match_range=(14, 21),
value="dummy a",
entity="dummy_entity_1",
slot_name="dummy_slot_name",
),
unresolved_slot(
match_range=(41, 48),
value="dummy_c",
entity="dummy_entity_2",
slot_name="dummy_slot_name2",
),
unresolved_slot(
match_range=(49, 56),
value="at 10pm",
entity="snips/datetime",
slot_name="startTime",
),
unresolved_slot(
match_range=(60, 69),
value="at 12p.m.",
entity="snips/datetime",
slot_name="startTime",
),
],
),
(
"this is a dummy b",
[
unresolved_slot(
match_range=(10, 17),
value="dummy b",
entity="dummy_entity_1",
slot_name="dummy_slot_name",
)
],
),
(
" this is a dummy b ",
[
unresolved_slot(
match_range=(11, 18),
value="dummy b",
entity="dummy_entity_1",
slot_name="dummy_slot_name",
)
],
),
(
" at 8am ’ there is a dummy a",
[
unresolved_slot(
match_range=(1, 7),
value="at 8am",
entity="snips/datetime",
slot_name="startTime",
),
unresolved_slot(
match_range=(21, 29),
value="dummy a",
entity="dummy_entity_1",
slot_name="dummy_slot_name",
),
],
),
]
for text, expected_slots in texts:
# When
parsing = parser.parse(text)
# Then
self.assertListEqual(expected_slots, parsing[RES_SLOTS])
def test_should_parse_stop_words_slots(self):
# Given
dataset_stream = io.StringIO("""
---
type: intent
name: search
utterances:
- search
- search [search_object](this)
- search [search_object](a cat)
---
type: entity
name: search_object
values:
- [this thing, that]
""")
resources = deepcopy(self.get_resources("en"))
resources[STOP_WORDS] = {"a", "this", "that"}
dataset = Dataset.from_yaml_files("en", [dataset_stream]).json
parser_config = LookupIntentParserConfig(ignore_stop_words=True)
parser = LookupIntentParser(config=parser_config, resources=resources)
parser.fit(dataset)
# When
res_1 = parser.parse("search this")
res_2 = parser.parse("search that")
# Then
expected_intent = intent_classification_result(
intent_name="search", probability=1.0)
expected_slots_1 = [
unresolved_slot(match_range=(7, 11), value="this",
entity="search_object",
slot_name="search_object")
]
expected_slots_2 = [
unresolved_slot(match_range=(7, 11), value="that",
entity="search_object",
slot_name="search_object")
]
self.assertEqual(expected_intent, res_1[RES_INTENT])
self.assertEqual(expected_intent, res_2[RES_INTENT])
self.assertListEqual(expected_slots_1, res_1[RES_SLOTS])
self.assertListEqual(expected_slots_2, res_2[RES_SLOTS])
def test_should_get_intents(self):
# Given
dataset_stream = io.StringIO(
"""
---
type: intent
name: greeting1
utterances:
- Hello John
---
type: intent
name: greeting2
utterances:
- Hello [name](John)
---
type: intent
name: greeting3
utterances:
- "[greeting](Hello) [name](John)"
""")
dataset = Dataset.from_yaml_files("en", [dataset_stream]).json
parser = LookupIntentParser().fit(dataset)
# When
top_intents = parser.get_intents("Hello John")
# Then
expected_intents = [
{
RES_INTENT_NAME: "greeting1",
RES_PROBA: 1. / (1. + 1. / 2. + 1. / 3.)
},
{
RES_INTENT_NAME: "greeting2",
RES_PROBA: (1. / 2.) / (1. + 1. / 2. + 1. / 3.)
},
{
RES_INTENT_NAME: "greeting3",
RES_PROBA: (1. / 3.) / (1. + 1. / 2. + 1. / 3.)
},
{
RES_INTENT_NAME: None,
RES_PROBA: 0.0
},
]
self.assertListEqual(expected_intents, top_intents)
def test_should_get_slots(self):
# Given
slots_dataset_stream = io.StringIO(
"""
---
type: intent
name: greeting1
utterances:
- Hello [name1](John)
---
type: intent
name: greeting2
utterances:
- Hello [name2](Thomas)
---
type: intent
name: goodbye
utterances:
- Goodbye [name](Eric)""")
dataset = Dataset.from_yaml_files("en", [slots_dataset_stream]).json
parser = LookupIntentParser().fit(dataset)
# When
slots_greeting1 = parser.get_slots("Hello John", "greeting1")
slots_greeting2 = parser.get_slots("Hello Thomas", "greeting2")
slots_goodbye = parser.get_slots("Goodbye Eric", "greeting1")
# Then
self.assertEqual(1, len(slots_greeting1))
self.assertEqual(1, len(slots_greeting2))
self.assertEqual(0, len(slots_goodbye))
self.assertEqual("John", slots_greeting1[0][RES_VALUE])
self.assertEqual("name1", slots_greeting1[0][RES_ENTITY])
self.assertEqual("Thomas", slots_greeting2[0][RES_VALUE])
self.assertEqual("name2", slots_greeting2[0][RES_ENTITY])
def test_should_get_no_slots_with_none_intent(self):
# Given
slots_dataset_stream = io.StringIO(
"""
---
type: intent
name: greeting
utterances:
- Hello [name](John)""")
dataset = Dataset.from_yaml_files("en", [slots_dataset_stream]).json
parser = LookupIntentParser().fit(dataset)
# When
slots = parser.get_slots("Hello John", None)
# Then
self.assertListEqual([], slots)
def test_get_slots_should_raise_with_unknown_intent(self):
# Given
slots_dataset_stream = io.StringIO(
"""
---
type: intent
name: greeting1
utterances:
- Hello [name1](John)
---
type: intent
name: goodbye
utterances:
- Goodbye | |
%(fail)s
}
break;
case 2: // backprop wrt. inputs
// output is bottom: (batchsize, num_channels, height, width, depth)
// height, width and depth: bottom = (top - 1) * sample + (weights-1)*dil + 1 - 2*pad
out_dim[0] = PyGpuArray_DIMS(top)[0];
out_dim[1] = PyGpuArray_DIMS(weights)[1] * numgroups;
out_dim[2] = (%(height)s != -1) ? %(height)s : (PyGpuArray_DIMS(top)[2] - 1) * dH + (PyGpuArray_DIMS(weights)[2]-1)*dilH + 1 - 2*padH;
out_dim[3] = (%(width)s != -1) ? %(width)s : (PyGpuArray_DIMS(top)[3] - 1) * dW + (PyGpuArray_DIMS(weights)[3]-1)*dilW + 1 - 2*padW;
out_dim[4] = (%(depth)s != -1) ? %(depth)s : (PyGpuArray_DIMS(top)[4] - 1) * dD + (PyGpuArray_DIMS(weights)[4]-1)*dilD + 1 - 2*padD;
out_typecode = top->ga.typecode;
out_context = top->context;
if (out_dim[0] < 0 || out_dim[1] < 0 || out_dim[2] <= 0 || out_dim[3] <= 0 || out_dim[4] <= 0)
{
PyErr_Format(PyExc_ValueError,
"GpuCorr3dMM backprop wrt. inputs: impossible output shape\\n"
" bottom shape: %%ld x %%ld x %%ld x %%ld x %%ld\\n"
" weights shape: %%ld x %%ld x %%ld x %%ld x %%ld\\n"
" top shape: %%ld x %%ld x %%ld x %%ld x %%ld\\n",
out_dim[0], out_dim[1], out_dim[2], out_dim[3], out_dim[4],
PyGpuArray_DIMS(weights)[0], PyGpuArray_DIMS(weights)[1],
PyGpuArray_DIMS(weights)[2], PyGpuArray_DIMS(weights)[3],
PyGpuArray_DIMS(weights)[4],
PyGpuArray_DIMS(top)[0], PyGpuArray_DIMS(top)[1],
PyGpuArray_DIMS(top)[2], PyGpuArray_DIMS(top)[3],
PyGpuArray_DIMS(top)[4]);
%(fail)s
}
break;
default:
PyErr_SetString(PyExc_ValueError, "BaseGpuCorr3dMM: direction must be 0, 1, or 2\\n");
%(fail)s
}
out_dim_size[0] = (size_t)out_dim[0];
out_dim_size[1] = (size_t)out_dim[1];
out_dim_size[2] = (size_t)out_dim[2];
out_dim_size[3] = (size_t)out_dim[3];
out_dim_size[4] = (size_t)out_dim[4];
// Prepare output array
if (aesara_prep_output(&%(out)s, 5, out_dim_size, out_typecode, GA_C_ORDER, out_context) != 0)
{
PyErr_Format(PyExc_RuntimeError,
"BaseGpuCorrMM: Failed to allocate output of %%lld x %%lld x %%lld x %%lld x %%lld",
out_dim[0], out_dim[1], out_dim[2], out_dim[3], out_dim[4]);
%(fail)s
}
if (!GpuArray_IS_C_CONTIGUOUS(&%(out)s->ga)) {
PyErr_SetString(PyExc_ValueError, "Only contiguous outputs are supported.");
%(fail)s
}
// Call GPU code
out2 = corr3dMM(%(bottom)s, %(weights)s, %(top)s, direction,
dH, dW, dD, dilH, dilW, dilD, padH, padW, padD, numgroups);
if (out2==NULL){
%(fail)s
}
assert (out2 == %(out)s);
"""
% sub
)
class GpuCorr3dMM(BaseGpuCorr3dMM):
"""
GPU correlation implementation using Matrix Multiplication.
Parameters
----------
border_mode
The width of a border of implicit zeros to pad the
input with. Must be a tuple with 3 elements giving the width of
the padding on each side, or a single integer to pad the same
on all sides, or a string shortcut setting the padding at runtime:
``'valid'`` for ``(0, 0, 0)`` (valid convolution, no padding), ``'full'``
for ``(kernel_rows - 1, kernel_columns - 1, kernel_depth - 1)``
(full convolution), ``'half'`` for ``(kernel_rows // 2,
kernel_columns // 2, kernel_depth // 2)`` (same convolution for
odd-sized kernels). Note that the three widths are each
applied twice, once per side (left and right, top and bottom, front
and back).
subsample
The subsample operation applied to each output image. Should be a tuple
with 3 elements. `(sv, sh, sl)` is equivalent to
`GpuCorrMM(...)(...)[:,:,::sv, ::sh, ::sl]`, but faster.
Set to `(1, 1, 1)` to disable subsampling.
filter_dilation
The filter dilation operation applied to each input image.
Should be a tuple with 3 elements.
Set to `(1, 1, 1)` to disable filter dilation.
num_groups
The number of distinct groups the image and kernel must be
divided into.
should be an int
set to 1 to disable grouped convolution
Notes
-----
Currently, the Op requires the inputs, filters and outputs to be
C-contiguous. Use :func:`gpu_contiguous
<aesara.gpuarray.basic_ops.gpu_contiguous>` on these arguments
if needed.
You can either enable the Aesara flag `optimizer_including=conv_gemm`
to automatically replace all convolution operations with `GpuCorr3dMM`
or one of its gradients, or you can use it as a replacement for
:func:`conv2d <aesara.tensor.nnet.conv.conv2d>`, called as
`GpuCorr3dMM(subsample=...)(image, filters)`. The latter is currently
faster, but note that it computes a correlation -- if you need to
compute a convolution, flip the filters as `filters[:,:,::-1,::-1,::-1]`.
"""
def __init__(
self,
border_mode="valid",
subsample=(1, 1, 1),
filter_dilation=(1, 1, 1),
num_groups=1,
):
super().__init__(border_mode, subsample, filter_dilation, num_groups)
def make_node(self, img, kern):
ctx_name = infer_context_name(img, kern)
img = as_gpuarray_variable(img, ctx_name)
kern = as_gpuarray_variable(kern, ctx_name)
if img.type.ndim != 5:
raise TypeError("img must be 5D tensor")
if kern.type.ndim != 5:
raise TypeError("kern must be 5D tensor")
broadcastable = [
img.type.broadcastable[0],
kern.type.broadcastable[0],
False,
False,
False,
]
return Apply(
self,
[img, kern],
[
GpuArrayType(
dtype=img.dtype, context_name=ctx_name, broadcastable=broadcastable
)()
],
)
def c_code(self, node, nodename, inp, out_, sub):
bottom, weights = inp
(top,) = out_
direction = "forward"
return super().c_code_helper(bottom, weights, top, direction, sub)
def grad(self, inp, grads):
bottom, weights = inp
(top,) = grads
top = gpu_contiguous(top)
d_bottom = GpuCorr3dMM_gradInputs(
self.border_mode, self.subsample, self.filter_dilation, self.num_groups
)(weights, top, bottom.shape[-3:])
d_weights = GpuCorr3dMM_gradWeights(
self.border_mode, self.subsample, self.filter_dilation, self.num_groups
)(bottom, top, weights.shape[-3:])
return d_bottom, d_weights
class GpuCorr3dMM_gradWeights(BaseGpuCorr3dMM):
"""
Gradient wrt. filters for `GpuCorr3dMM`.
Notes
-----
You will not want to use this directly, but rely on Aesara's automatic
differentiation or graph optimization to use it as needed.
"""
def __init__(
self,
border_mode="valid",
subsample=(1, 1, 1),
filter_dilation=(1, 1, 1),
num_groups=1,
):
super().__init__(border_mode, subsample, filter_dilation, num_groups)
def make_node(self, img, topgrad, shape=None):
ctx_name = infer_context_name(img, topgrad)
img = as_gpuarray_variable(img, ctx_name)
topgrad = as_gpuarray_variable(topgrad, ctx_name)
if img.type.ndim != 5:
raise TypeError("img must be 5D tensor")
if topgrad.type.ndim != 5:
raise TypeError("topgrad must be 5D tensor")
if shape is None:
if self.subsample != (1, 1, 1) or self.border_mode == "half":
raise ValueError(
"shape must be given if subsample != (1, 1, 1)"
' or border_mode == "half"'
)
height_width_depth = []
else:
height_width_depth = [shape[0], shape[1], shape[2]]
assert shape[0].ndim == 0
assert shape[1].ndim == 0
assert shape[2].ndim == 0
broadcastable = [
topgrad.type.broadcastable[1],
img.type.broadcastable[1],
False,
False,
False,
]
return Apply(
self,
[img, topgrad] + height_width_depth,
[
GpuArrayType(
dtype=img.dtype, context_name=ctx_name, broadcastable=broadcastable
)()
],
)
def c_code(self, node, nodename, inp, out_, sub):
bottom, top = inp[:2]
height, width, depth = inp[2:] or (None, None, None)
(weights,) = out_
direction = "backprop weights"
return super().c_code_helper(
bottom, weights, top, direction, sub, height, width, depth
)
def grad(self, inp, grads):
bottom, top = inp[:2]
(weights,) = grads
weights = gpu_contiguous(weights)
d_bottom = GpuCorr3dMM_gradInputs(
self.border_mode, self.subsample, self.filter_dilation, self.num_groups
)(weights, top, bottom.shape[-3:])
d_top = GpuCorr3dMM(
self.border_mode, self.subsample, self.filter_dilation, self.num_groups
)(bottom, weights)
d_height_width_depth = (
(aesara.gradient.DisconnectedType()(),) * 3 if len(inp) == 5 else ()
)
return (d_bottom, d_top) + d_height_width_depth
def connection_pattern(self, node):
if node.nin == 2:
return [[1], [1]]
else:
return [[1], [1], [0], [0], [0]] # no connection to height, width, depth
class GpuCorr3dMM_gradInputs(BaseGpuCorr3dMM):
"""
Gradient wrt. inputs for `GpuCorr3dMM`.
Notes
-----
You will not want to use this directly, but rely on Aesara's automatic
differentiation or graph optimization to use it as needed.
"""
def __init__(
self,
border_mode="valid",
subsample=(1, 1, 1),
filter_dilation=(1, 1, 1),
num_groups=1,
):
super().__init__(border_mode, subsample, filter_dilation, num_groups)
def make_node(self, kern, topgrad, shape=None):
ctx_name = infer_context_name(kern, topgrad)
kern = as_gpuarray_variable(kern, ctx_name)
topgrad = as_gpuarray_variable(topgrad, ctx_name)
if kern.type.ndim != 5:
raise TypeError("kern must be 5D tensor")
if topgrad.type.ndim != 5:
raise TypeError("topgrad must be 5D tensor")
if shape is None:
if self.subsample != (1, 1, 1):
raise ValueError("shape must be given if subsample != (1, 1, 1)")
height_width_depth = []
else:
height_width_depth = [shape[0], shape[1], shape[2]]
assert shape[0].ndim == 0
assert shape[1].ndim == 0
assert shape[2].ndim == 0
if self.num_groups > 1:
broadcastable = [topgrad.type.broadcastable[0], False, False, False, False]
else:
broadcastable = [
topgrad.type.broadcastable[0],
kern.type.broadcastable[-4],
False,
False,
False,
]
return Apply(
self,
[kern, topgrad] + height_width_depth,
[
GpuArrayType(
dtype=topgrad.dtype,
context_name=ctx_name,
broadcastable=broadcastable,
)()
],
)
def c_code(self, node, nodename, inp, out_, sub):
weights, top = inp[:2]
height, width, depth = inp[2:] or (None, None, None)
(bottom,) = out_
direction = "backprop inputs"
return super().c_code_helper(
bottom, weights, top, direction, sub, height, width, depth
)
def grad(self, inp, grads):
weights, top = inp[:2]
(bottom,) = grads
bottom = gpu_contiguous(bottom)
d_weights = GpuCorr3dMM_gradWeights(
self.border_mode, self.subsample, self.filter_dilation, self.num_groups
)(bottom, top, weights.shape[-3:])
d_top = GpuCorr3dMM(
self.border_mode, self.subsample, self.filter_dilation, self.num_groups
)(bottom, weights)
d_height_width_depth = (
(aesara.gradient.DisconnectedType()(),) * 3 if len(inp) == 5 else ()
)
return (d_weights, d_top) + d_height_width_depth
def connection_pattern(self, node):
if node.nin == 2:
return [[1], [1]]
else:
return [[1], [1], [0], [0], [0]] # no connection to height, width, depth
@inplace_allocempty(GpuGemv, 0)
def local_inplace_gpuagemv(node, inputs):
return [gpugemv_inplace(*inputs)]
@inplace_allocempty(GpuGemm, 0)
def local_inplace_gpuagemm(node, inputs):
return [gpugemm_inplace(*inputs)]
@inplace_allocempty(GpuGer, | |
of the Jacobian matrix.
If `as_linear_operator` is True returns a LinearOperator
with shape (m, n). Otherwise it returns a dense array or sparse
matrix depending on how `sparsity` is defined. If `sparsity`
is None then a ndarray with shape (m, n) is returned. If
`sparsity` is not None returns a csr_matrix with shape (m, n).
For sparse matrices and linear operators it is always returned as
a 2-D structure, for ndarrays, if m=1 it is returned
as a 1-D gradient array with shape (n,).
See Also
--------
check_derivative : Check correctness of a function computing derivatives.
Notes
-----
If `rel_step` is not provided, it assigned to ``EPS**(1/s)``, where EPS is
machine epsilon for float64 numbers, s=2 for '2-point' method and s=3 for
'3-point' method. Such relative step approximately minimizes a sum of
truncation and round-off errors, see [1]_.
A finite difference scheme for '3-point' method is selected automatically.
The well-known central difference scheme is used for points sufficiently
far from the boundary, and 3-point forward or backward scheme is used for
points near the boundary. Both schemes have the second-order accuracy in
terms of Taylor expansion. Refer to [2]_ for the formulas of 3-point
forward and backward difference schemes.
For dense differencing when m=1 Jacobian is returned with a shape (n,),
on the other hand when n=1 Jacobian is returned with a shape (m, 1).
Our motivation is the following: a) It handles a case of gradient
computation (m=1) in a conventional way. b) It clearly separates these two
different cases. b) In all cases np.atleast_2d can be called to get 2-D
Jacobian with correct dimensions.
References
----------
.. [1] W. H. Press et. al. "Numerical Recipes. The Art of Scientific
Computing. 3rd edition", sec. 5.7.
.. [2] <NAME>, <NAME>, and <NAME>, "On the estimation of
sparse Jacobian matrices", Journal of the Institute of Mathematics
and its Applications, 13 (1974), pp. 117-120.
.. [3] <NAME>, "Generation of Finite Difference Formulas on
Arbitrarily Spaced Grids", Mathematics of Computation 51, 1988.
Examples
--------
>>> import numpy as np
>>> from scipy.optimize import approx_derivative
>>>
>>> def f(x, c1, c2):
... return np.array([x[0] * np.sin(c1 * x[1]),
... x[0] * np.cos(c2 * x[1])])
...
>>> x0 = np.array([1.0, 0.5 * np.pi])
>>> approx_derivative(f, x0, args=(1, 2))
array([[ 1., 0.],
[-1., 0.]])
Bounds can be used to limit the region of function evaluation.
In the example below we compute left and right derivative at point 1.0.
>>> def g(x):
... return x**2 if x >= 1 else x
...
>>> x0 = 1.0
>>> approx_derivative(g, x0, bounds=(-np.inf, 1.0))
array([ 1.])
>>> approx_derivative(g, x0, bounds=(1.0, np.inf))
array([ 2.])
"""
if method not in ['2-point', '3-point', 'cs']:
raise ValueError("Unknown method '%s'. " % method)
x0 = np.atleast_1d(x0)
if x0.ndim > 1:
raise ValueError("`x0` must have at most 1 dimension.")
lb, ub = _prepare_bounds(bounds, x0)
if lb.shape != x0.shape or ub.shape != x0.shape:
raise ValueError("Inconsistent shapes between bounds and `x0`.")
if as_linear_operator and not (np.all(np.isinf(lb))
and np.all(np.isinf(ub))):
raise ValueError("Bounds not supported when "
"`as_linear_operator` is True.")
def fun_wrapped(x):
f = np.atleast_1d(fun(x, *args, **kwargs))
if f.ndim > 1:
raise RuntimeError("`fun` return value has "
"more than 1 dimension.")
return f
if f0 is None:
f0 = fun_wrapped(x0)
else:
f0 = np.atleast_1d(f0)
if f0.ndim > 1:
raise ValueError("`f0` passed has more than 1 dimension.")
if np.any((x0 < lb) | (x0 > ub)):
raise ValueError("`x0` violates bound constraints.")
if as_linear_operator:
if rel_step is None:
rel_step = relative_step[method]
return _linear_operator_difference(fun_wrapped, x0,
f0, rel_step, method)
else:
h = _compute_absolute_step(rel_step, x0, method)
if method == '2-point':
h, use_one_sided = _adjust_scheme_to_bounds(
x0, h, 1, '1-sided', lb, ub)
elif method == '3-point':
h, use_one_sided = _adjust_scheme_to_bounds(
x0, h, 1, '2-sided', lb, ub)
elif method == 'cs':
use_one_sided = False
if sparsity is None:
return _dense_difference(fun_wrapped, x0, f0, h,
use_one_sided, method)
else:
if not issparse(sparsity) and len(sparsity) == 2:
structure, groups = sparsity
else:
structure = sparsity
groups = group_columns(sparsity)
if issparse(structure):
structure = csc_matrix(structure)
else:
structure = np.atleast_2d(structure)
groups = np.atleast_1d(groups)
return _sparse_difference(fun_wrapped, x0, f0, h,
use_one_sided, structure,
groups, method)
def _linear_operator_difference(fun, x0, f0, h, method):
m = f0.size
n = x0.size
if method == '2-point':
def matvec(p):
if np.array_equal(p, np.zeros_like(p)):
return np.zeros(m)
dx = h / norm(p)
x = x0 + dx*p
df = fun(x) - f0
return df / dx
elif method == '3-point':
def matvec(p):
if np.array_equal(p, np.zeros_like(p)):
return np.zeros(m)
dx = 2*h / norm(p)
x1 = x0 - (dx/2)*p
x2 = x0 + (dx/2)*p
f1 = fun(x1)
f2 = fun(x2)
df = f2 - f1
return df / dx
elif method == 'cs':
def matvec(p):
if np.array_equal(p, np.zeros_like(p)):
return np.zeros(m)
dx = h / norm(p)
x = x0 + dx*p*1.j
f1 = fun(x)
df = f1.imag
return df / dx
else:
raise RuntimeError("Never be here.")
return LinearOperator((m, n), matvec)
def _dense_difference(fun, x0, f0, h, use_one_sided, method):
m = f0.size
n = x0.size
J_transposed = np.empty((n, m))
h_vecs = np.diag(h)
for i in range(h.size):
if method == '2-point':
x = x0 + h_vecs[i]
dx = x[i] - x0[i] # Recompute dx as exactly representable number.
df = fun(x) - f0
elif method == '3-point' and use_one_sided[i]:
x1 = x0 + h_vecs[i]
x2 = x0 + 2 * h_vecs[i]
dx = x2[i] - x0[i]
f1 = fun(x1)
f2 = fun(x2)
df = -3.0 * f0 + 4 * f1 - f2
elif method == '3-point' and not use_one_sided[i]:
x1 = x0 - h_vecs[i]
x2 = x0 + h_vecs[i]
dx = x2[i] - x1[i]
f1 = fun(x1)
f2 = fun(x2)
df = f2 - f1
elif method == 'cs':
f1 = fun(x0 + h_vecs[i]*1.j)
df = f1.imag
dx = h_vecs[i, i]
else:
raise RuntimeError("Never be here.")
J_transposed[i] = df / dx
if m == 1:
J_transposed = np.ravel(J_transposed)
return J_transposed.T
def _sparse_difference(fun, x0, f0, h, use_one_sided,
structure, groups, method):
m = f0.size
n = x0.size
row_indices = []
col_indices = []
fractions = []
n_groups = np.max(groups) + 1
for group in range(n_groups):
# Perturb variables which are in the same group simultaneously.
e = np.equal(group, groups)
h_vec = h * e
if method == '2-point':
x = x0 + h_vec
dx = x - x0
df = fun(x) - f0
# The result is written to columns which correspond to perturbed
# variables.
cols, = np.nonzero(e)
# Find all non-zero elements in selected columns of Jacobian.
i, j, _ = find(structure[:, cols])
# Restore column indices in the full array.
j = cols[j]
elif method == '3-point':
# Here we do conceptually the same but separate one-sided
# and two-sided schemes.
x1 = x0.copy()
x2 = x0.copy()
mask_1 = use_one_sided & e
x1[mask_1] += h_vec[mask_1]
x2[mask_1] += 2 * h_vec[mask_1]
mask_2 = ~use_one_sided & e
x1[mask_2] -= h_vec[mask_2]
x2[mask_2] += h_vec[mask_2]
dx = np.zeros(n)
dx[mask_1] = x2[mask_1] - x0[mask_1]
dx[mask_2] = x2[mask_2] - x1[mask_2]
f1 = fun(x1)
f2 = fun(x2)
cols, = np.nonzero(e)
i, j, _ = find(structure[:, cols])
j = cols[j]
mask = use_one_sided[j]
df = np.empty(m)
rows = i[mask]
df[rows] = -3 * f0[rows] + 4 * f1[rows] - f2[rows]
rows = i[~mask]
df[rows] = f2[rows] - f1[rows]
elif method == 'cs':
f1 = fun(x0 + h_vec*1.j)
df = f1.imag
dx = h_vec
cols, = np.nonzero(e)
i, j, _ = find(structure[:, cols])
j = cols[j]
else:
raise ValueError("Never be here.")
# All that's left is to compute the fraction. We store i, j and
# fractions as separate arrays and later construct coo_matrix.
row_indices.append(i)
col_indices.append(j)
fractions.append(df[i] / dx[j])
row_indices = np.hstack(row_indices)
col_indices = np.hstack(col_indices)
fractions = np.hstack(fractions)
J = coo_matrix((fractions, (row_indices, col_indices)), shape=(m, n))
return csr_matrix(J)
def check_derivative(fun, jac, x0, bounds=(-np.inf, np.inf), args=(),
kwargs={}):
"""Check correctness of a function computing derivatives (Jacobian or
gradient) by comparison with a finite difference approximation.
Parameters
----------
fun : callable
Function of which to estimate the derivatives. The argument | |
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
import requests
import json
import traceback
from datetime import datetime, timedelta
import time
# Disable insecure warnings
requests.packages.urllib3.disable_warnings() # pylint: disable=no-member
# flake8: noqa
''' CONSTANTS '''
DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ' # ISO8601 format with UTC, default in XSOAR
VALID_VARIANTS = ["HTTP","HTTPS"]
verify_certificate = not demisto.params().get('insecure', False)
def test_module() -> str:
"""Tests API connectivity and authentication'
Returning 'ok' indicates that the integration works like it is supposed to.
Connection to the service is successful.
Raises exceptions if something goes wrong.
:type client: ``Client``
:param Client: client to use
:return: 'ok' if test passed, anything else will fail the test.
:rtype: ``str``
"""
message: str = ''
try:
picus_server = str(demisto.params().get("picus_server"))
picus_server = picus_server[:-1] if picus_server.endswith("/") else picus_server
picus_apikey = demisto.params().get("picus_apikey")
picus_headers = {"X-Refresh-Token": "", "Content-Type": "application/json"}
picus_headers["X-Refresh-Token"] = "Bearer " + str(picus_apikey)
picus_auth_endpoint = "/authenticator/v1/access-tokens/generate"
picus_req_url = str(picus_server) + picus_auth_endpoint
picus_session = requests.Session()
if not demisto.params().get('proxy', False):
picus_session.trust_env = False
picus_auth_response = picus_session.post(picus_req_url, headers=picus_headers, verify=verify_certificate)
picus_auth_response.raise_for_status()
picus_accessToken = json.loads(picus_auth_response.text)["data"]["access_token"]
message = 'ok'
except Exception as e:
if 'Forbidden' in str(e) or 'Authorization' in str(e) or 'NewConnectionError' in str(e) or 'Unauthorized' in str(e) or picus_accessToken is None:
message = 'Authorization Error: make sure API Key or Picus URL is correctly set'
else:
raise e
return message
def getAccessToken():
picus_server = str(demisto.params().get("picus_server"))
picus_server = picus_server[:-1] if picus_server.endswith("/") else picus_server
picus_apikey = demisto.params().get("picus_apikey")
picus_headers = {"X-Refresh-Token": "", "Content-Type": "application/json"}
picus_headers["X-Refresh-Token"] = "Bearer " + str(picus_apikey)
picus_auth_endpoint = "/authenticator/v1/access-tokens/generate"
picus_req_url = str(picus_server) + picus_auth_endpoint
picus_session = requests.Session()
if not demisto.params().get('proxy', False):
picus_session.trust_env = False
picus_auth_response = picus_session.post(picus_req_url, headers=picus_headers, verify=verify_certificate)
if picus_auth_response.status_code!=200:
return_error(picus_auth_response.text)
picus_accessToken = json.loads(picus_auth_response.text)["data"]["access_token"]
return picus_accessToken
def getVectorList():
picus_endpoint = "/user-api/v1/vectors/list"
picus_req_url, picus_headers = generateEndpointURL(getAccessToken(),picus_endpoint)
add_user_details = demisto.args().get('add_user_details')
add_user_details = bool(add_user_details) if add_user_details is not None else add_user_details
page = arg_to_number(demisto.args().get('page'))
size = arg_to_number(demisto.args().get('size'))
picus_post_data = {"add_user_details":add_user_details,"size":size,"page":page}
picus_post_data = assign_params(**picus_post_data)
picus_endpoint_response = requests.post(picus_req_url,headers=picus_headers,data=json.dumps(picus_post_data),verify=verify_certificate)
picus_vectors = json.loads(picus_endpoint_response.text)["data"]["vectors"]
table_name = "Picus Vector List"
table_headers = ['name','description','trusted','untrusted','is_disabled','type']
md_table = tableToMarkdown(table_name,picus_vectors,headers=table_headers,removeNull=True,headerTransform=string_to_table_header)
results = CommandResults(readable_output=md_table,outputs=picus_vectors,outputs_prefix="Picus.vectorlist")
return results
def getPeerList():
picus_endpoint = "/user-api/v1/peers/list"
picus_req_url, picus_headers = generateEndpointURL(getAccessToken(),picus_endpoint)
picus_endpoint_response = requests.post(picus_req_url,headers=picus_headers,verify=verify_certificate)
picus_peers = json.loads(picus_endpoint_response.text)["data"]["peers"]
table_name = "Picus Peer List"
table_headers = ['name','registered_ip','type','is_alive']
md_table = tableToMarkdown(table_name,picus_peers,headers=table_headers,removeNull=True,headerTransform=string_to_table_header)
results = CommandResults(readable_output=md_table,outputs=picus_peers,outputs_prefix="Picus.peerlist")
return results
def getAttackResults():
picus_endpoint = "/user-api/v1/attack-results/list"
picus_req_url, picus_headers = generateEndpointURL(getAccessToken(), picus_endpoint)
picus_attack_results : List[Any] = []
picus_attack_raw_results: Dict[str,Any] = {"results":[]}
tmp_secure_list: List[Any] = []
tmp_insecure_list: List[Any] = []
tmp_results: List[Any] = []
threat_ids = ""
attacker_peer = demisto.args().get('attacker_peer')
victim_peer = demisto.args().get('victim_peer')
days = int(demisto.args().get('days'))
attack_result = demisto.args().get('result').lower()
attack_result = attack_result[0].upper() + attack_result[1:]
valid_attack_results = ["Insecure","Secure","All"]
check_valid = any(result for result in valid_attack_results if(result==attack_result))
if not check_valid:
msg = "Wrong result parameter. The result parameter can only be secure,insecure and all"
return msg
end_date = datetime.now().strftime("%Y-%m-%d")
begin_date = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
picus_post_data_secure = {"attack_result":"secure","begin_date":begin_date,"end_date":end_date,"vectors":[{"trusted":victim_peer,"untrusted":attacker_peer}]}
picus_post_data_insecure = {"attack_result":"insecure","begin_date":begin_date,"end_date":end_date,"vectors":[{"trusted":victim_peer,"untrusted":attacker_peer}]}
picus_endpoint_response_secure = requests.post(picus_req_url,headers=picus_headers,data=json.dumps(picus_post_data_secure),verify=verify_certificate)
picus_endpoint_response_insecure = requests.post(picus_req_url,headers=picus_headers,data=json.dumps(picus_post_data_insecure),verify=verify_certificate)
picus_attack_results_secure = json.loads(picus_endpoint_response_secure.text)["data"]["results"]
picus_attack_results_insecure = json.loads(picus_endpoint_response_insecure.text)["data"]["results"]
if picus_attack_results_secure is not None:
picus_attack_results_secure.sort(key=returnListTimeKey,reverse=True)
for i in range(len(picus_attack_results_secure)):
exists = 0
list_len = len(tmp_secure_list)
for j in range(list_len):
if picus_attack_results_secure[i]["threat_id"] == tmp_secure_list[j]["threat_id"]:
exists = 1
if exists == 0:
tmp_secure_list.append(picus_attack_results_secure[i])
if picus_attack_results_insecure is not None:
picus_attack_results_insecure.sort(key=returnListTimeKey, reverse=True)
for i in range(len(picus_attack_results_insecure)):
exists = 0
list_len = len(tmp_insecure_list)
for j in range(list_len):
if picus_attack_results_insecure[i]["threat_id"] == tmp_insecure_list[j]["threat_id"]:
exists = 1
if exists == 0:
tmp_insecure_list.append(picus_attack_results_insecure[i])
tmp_results = tmp_secure_list + tmp_insecure_list
if len(tmp_results)!=0:
tmp_results.sort(key=returnListTimeKey, reverse=True)
else:
message = "No Results Data."
results = CommandResults(readable_output=message)
return results
for i in range(len(tmp_results)):
exists = 0
list_len = len(picus_attack_results)
for j in range(list_len):
if tmp_results[i]["threat_id"] == picus_attack_results[j]["threat_id"]:
exists = 1
if exists == 0:
picus_attack_results.append(tmp_results[i])
tmp_results = []
for i in range(len(picus_attack_results)):
if attack_result == "All":
tmp_results.append(picus_attack_results[i])
elif picus_attack_results[i]["string"] == attack_result:
tmp_results.append(picus_attack_results[i])
picus_attack_results = tmp_results
for i in range(len(picus_attack_results)):
threat_ids += str(picus_attack_results[i]["threat_id"]) + ","
threat_ids = threat_ids[:-1]
picus_attack_raw_results["results"].append({"threat_ids":threat_ids})
picus_attack_raw_results["results"].append(picus_attack_results)
table_name = attack_result + " Attack List"
table_headers = ['begin_time','end_time','string','threat_id','threat_name']
md_table = tableToMarkdown(table_name,picus_attack_results,headers=table_headers,removeNull=True,headerTransform=string_to_table_header)
results = CommandResults(readable_output=md_table,outputs_prefix="Picus.attackresults",outputs=picus_attack_raw_results,outputs_key_field="results.threat_id")
return results
def runAttacks():
picus_endpoint = "/user-api/v1/schedule/attack/single"
picus_req_url, picus_headers = generateEndpointURL(getAccessToken(), picus_endpoint)
picus_attack_results : Dict[str,Any] = {"results": []}
picus_attack_raw_results = ""
threat_ids = demisto.args().get('threat_ids')
attacker_peer = demisto.args().get('attacker_peer')
victim_peer = demisto.args().get('victim_peer')
variant = demisto.args().get('variant')
if variant not in VALID_VARIANTS:
return_error("Unknown variant type - "+variant)
threat_ids = list(threat_ids.split(","))
t_count = 0
for threat_id in threat_ids:
try:
threat_id = int(threat_id)
picus_attack_data = {"trusted": victim_peer,"untrusted": attacker_peer,"threat_id": threat_id,"variant": variant}
picus_attack_response = requests.post(picus_req_url,headers=picus_headers,data=json.dumps(picus_attack_data),verify=verify_certificate)
attack_result_response = json.loads(picus_attack_response.text)["data"]["result"]
picus_attack_result = {"threat_id":threat_id,"result":attack_result_response}
picus_attack_results["results"].append(picus_attack_result)
if attack_result_response == "success":
picus_attack_raw_results += str(threat_id)+","
if t_count == 3:
time.sleep(1)
t_count = 0
else:
t_count+=1
except Exception as e:
picus_attack_result = {"threat_id":threat_id,"result":"unknown error"}
picus_attack_results["results"].append(picus_attack_result)
continue
if len(picus_attack_raw_results)!=0:
picus_attack_raw_results = picus_attack_raw_results[:-1]
picus_attack_results = picus_attack_results["results"]
table_name = "Picus Attack Results"
table_headers = ['threat_id','result']
md_table = tableToMarkdown(table_name, picus_attack_results, headers=table_headers, removeNull=True,headerTransform=string_to_table_header)
results = CommandResults(readable_output=md_table,outputs_prefix="Picus.runattacks",outputs=picus_attack_raw_results)
return results
def getThreatResults():
picus_endpoint = "/user-api/v1/attack-results/threat-specific-latest"
picus_req_url, picus_headers = generateEndpointURL(getAccessToken(), picus_endpoint)
picus_threat_results : Dict[str,Any] = {"results":[]}
picus_threat_raw_results = ""
threat_raw_output: Dict[str,Any] = {"results":[]}
threat_ids = demisto.args().get('threat_ids')
attacker_peer = demisto.args().get('attacker_peer')
victim_peer = demisto.args().get('victim_peer')
variant = demisto.args().get('variant')
if variant not in VALID_VARIANTS:
return_error("Unknown variant type - "+variant)
threat_ids = list(threat_ids.split(","))
for threat_id in threat_ids:
try:
threat_id = int(threat_id)
picus_threat_data = {"threat_id": threat_id}
picus_threat_response = requests.post(picus_req_url,headers=picus_headers,data=json.dumps(picus_threat_data),verify=verify_certificate)
picus_threat_json_result = json.loads(picus_threat_response.text)["data"]["results"]
l1_category = picus_threat_json_result["l1_category_name"]
vector_name = attacker_peer + " - " + victim_peer
vectors_results = picus_threat_json_result["vectors"]
for i in range(len(vectors_results)):
if vectors_results[i]["name"] == vector_name:
variants_results = vectors_results[i]["variants"]
for j in range(len(variants_results)):
if variants_results[j]["name"] == variant:
last_time = variants_results[j]["last_time"]
threat_result = variants_results[j]["result"]
picus_threat_result = {"l1_category":l1_category,"result":threat_result,"threat_id":threat_id,"last_time":last_time,"status":"success"}
picus_threat_results["results"].append(picus_threat_result)
picus_threat_raw_results += str(threat_id) + "=" + threat_result + ","
except Exception as e:
picus_threat_result = {"l1_category": "null","result": "null","threat_id": threat_id,"last_time": "null","status": "fail"}
picus_threat_results["results"].append(picus_threat_result)
continue
if len(picus_threat_raw_results)!=0:
picus_threat_raw_results = picus_threat_raw_results[:-1]
picus_threat_results = picus_threat_results["results"]
threat_raw_output["results"].append({"threat_results":picus_threat_raw_results})
threat_raw_output["results"].append(picus_threat_results)
table_name = "Picus Threat Results"
table_headers = ['threat_id','result','l1_category','last_time','status']
md_table = tableToMarkdown(table_name, picus_threat_results, headers=table_headers, removeNull=True,headerTransform=string_to_table_header)
results = CommandResults(readable_output=md_table,outputs_prefix="Picus.threatresults",outputs=threat_raw_output,outputs_key_field="results.threat_id")
return results
def filterInsecureAttacks():
threatinfo = demisto.args().get('threatinfo')
threat_ids = ""
threatinfo = list(threatinfo.split(","))
threatinfo = [th_info for th_info in threatinfo if "Insecure" in th_info]
for th_info in threatinfo:
threat_id = th_info.split("=")[0]
threat_ids += str(threat_id) + ","
if len(threat_ids)!=0:
threat_ids = threat_ids[:-1]
results = CommandResults(readable_output=threat_ids,outputs_prefix="Picus.filterinsecure",outputs=threat_ids)
return results
def getMitigationList():
picus_endpoint = "/user-api/v1/threats/mitigations/list"
picus_req_url, picus_headers = generateEndpointURL(getAccessToken(), picus_endpoint)
picus_mitigation_results : Dict[str,Any] = {"results": []}
threat_ids = demisto.args().get('threat_ids')
product = demisto.args().get('product')
product = list(product.split(","))
threat_ids = list(threat_ids.split(","))
for threat_id in threat_ids:
try:
threat_id = int(threat_id)
picus_threat_data = {"threat_id":threat_id,"products":product}
picus_mitigation_response = requests.post(picus_req_url,headers=picus_headers,data=json.dumps(picus_threat_data),verify=verify_certificate)
picus_mitigation_result = json.loads(picus_mitigation_response.text)["data"]["mitigations"]
picus_mitigation_count = json.loads(picus_mitigation_response.text)["data"]["total_count"]
if picus_mitigation_count!=0:
for threat_mitigation in picus_mitigation_result:
mitigation_data = {"threat_id":threat_mitigation["threat"]["id"],"signature_id":threat_mitigation["signature"]["id"],"signature_name":threat_mitigation["signature"]["name"],"vendor":threat_mitigation["product"]}
picus_mitigation_results["results"].append(mitigation_data)
except Exception as e:
continue
picus_mitigation_results = picus_mitigation_results["results"]
table_name = "Picus Mitigation List"
table_headers = ['threat_id','signature_id','signature_name','vendor']
md_table = tableToMarkdown(table_name, picus_mitigation_results, headers=table_headers, removeNull=True,headerTransform=string_to_table_header)
results = CommandResults(readable_output=md_table,outputs_prefix="Picus.mitigationresults",outputs=picus_mitigation_results,outputs_key_field="signature_id")
return results
def getVectorCompare():
picus_endpoint = "/user-api/v1/attack-results/compare-a-vector"
picus_req_url, picus_headers = generateEndpointURL(getAccessToken(), picus_endpoint)
all_vector_results : Dict[str,Any] = {"results": []}
attacker_peer = demisto.args().get('attacker_peer')
victim_peer = demisto.args().get('victim_peer')
days = int(demisto.args().get('days'))
end_date = datetime.now().strftime("%Y-%m-%d")
begin_date = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
picus_post_data_vector = {"trusted":victim_peer,"untrusted":attacker_peer,"begin_date":begin_date,"end_date":end_date}
picus_vector_response = requests.post(picus_req_url, headers=picus_headers, data=json.dumps(picus_post_data_vector),verify=verify_certificate)
picus_vector_results = json.loads(picus_vector_response.text)["data"]["variants"][0]
picus_vector_secure_results = picus_vector_results["secures"]
picus_vector_insecure_results = picus_vector_results["insecures"]
picus_vector_secure_to_insecures_results = picus_vector_results["secure_to_insecures"]
picus_vector_insecure_to_secures_results = picus_vector_results["insecure_to_secures"]
if picus_vector_secure_results is not None:
for result in picus_vector_secure_results:
tmp_result = {"status":"secure","threat_id":result["threat_id"],"name":result["name"]}
all_vector_results["results"].append(tmp_result)
else:
tmp_result = {"status": "secure", "threat_id": "null", "name": "null"}
all_vector_results["results"].append(tmp_result)
if picus_vector_insecure_results is not None:
for result in picus_vector_insecure_results:
tmp_result = {"status":"insecure","threat_id":result["threat_id"],"name":result["name"]}
all_vector_results["results"].append(tmp_result)
else:
tmp_result = {"status": "insecure", "threat_id": "null", "name": "null"}
all_vector_results["results"].append(tmp_result)
if picus_vector_secure_to_insecures_results is not None:
for result in picus_vector_secure_to_insecures_results:
tmp_result = {"status":"secure_to_insecures","threat_id":result["threat_id"],"name":result["name"]}
all_vector_results["results"].append(tmp_result)
else:
tmp_result = {"status": "secure_to_insecures", "threat_id": "null", "name": "null"}
all_vector_results["results"].append(tmp_result)
if picus_vector_insecure_to_secures_results is not None:
for result in picus_vector_insecure_to_secures_results:
tmp_result = {"status":"insecure_to_secures","threat_id":result["threat_id"],"name":result["name"]}
all_vector_results["results"].append(tmp_result)
else:
tmp_result = {"status": "insecure_to_secures", "threat_id": "null", "name": "null"}
all_vector_results["results"].append(tmp_result)
all_vector_results = all_vector_results["results"]
table_name = "Picus Vector Compare Result"
table_headers = ['status','threat_id','name']
md_table = tableToMarkdown(table_name, all_vector_results, headers=table_headers, removeNull=True,headerTransform=string_to_table_header)
results = CommandResults(readable_output=md_table,outputs=all_vector_results,outputs_prefix="Picus.vectorresults",outputs_key_field="threat_id")
return results
def returnListTimeKey(attack_result_list):
return attack_result_list.get("end_time")
def setParamPB():
attacker_peer = demisto.args().get('attacker_peer')
victim_peer = demisto.args().get('victim_peer')
variant = demisto.args().get('variant')
if variant not in VALID_VARIANTS:
return_error("Unknown variant type - "+variant)
mitigation_product = demisto.args().get('mitigation_product')
days = int(demisto.args().get('days'))
param_data = {"attacker_peer":attacker_peer,"victim_peer":victim_peer,"variant":variant,"mitigation_product":mitigation_product,"days":days}
results = CommandResults(outputs=param_data,outputs_prefix="Picus.param")
return results
def getPicusVersion():
picus_endpoint = "/user-api/v1/settings/version"
picus_req_url, picus_headers = generateEndpointURL(getAccessToken(),picus_endpoint)
picus_endpoint_response = requests.post(picus_req_url,headers=picus_headers,verify=verify_certificate)
picus_version_results = json.loads(picus_endpoint_response.text)["data"]
picus_version_info = {"version":picus_version_results["version"],"update_time":picus_version_results["update_time"],"last_update_date":picus_version_results["last_update_date"]}
table_name = "Picus Version"
table_headers = ['version','update_time','last_update_date']
md_table = tableToMarkdown(table_name,picus_version_info,headers=table_headers,removeNull=True,headerTransform=string_to_table_header)
results = CommandResults(readable_output=md_table,outputs=picus_version_info,outputs_prefix="Picus.versioninfo",outputs_key_field="version")
return results
def triggerUpdate():
picus_endpoint = "/user-api/v1/settings/trigger-update"
picus_req_url, picus_headers = generateEndpointURL(getAccessToken(),picus_endpoint)
picus_endpoint_response = requests.post(picus_req_url,headers=picus_headers,verify=verify_certificate)
picus_update_results = json.loads(picus_endpoint_response.text)
table_name = "Picus | |
Side),
UnaryExpression(Keyword('flagtexture'), Object, String),
UnaryExpression(Keyword('fleeing'), Object, Boolean),
UnaryExpression(Keyword('floor'), Number, Number),
UnaryExpression(Keyword('for'), String, ForType),
UnaryExpression(Keyword('for'), Array, ForType),
UnaryExpression(Keyword('forceatpositionrtd'), Array, Array),
UnaryExpression(Keyword('forcegeneratorrtd'), Number, Array),
UnaryExpression(Keyword('forcemap'), Boolean, Nothing),
UnaryExpression(Keyword('forcerespawn'), Object, Nothing),
UnaryExpression(Keyword('format'), Array, String),
UnaryExpression(Keyword('formation'), Object, String),
UnaryExpression(Keyword('formation'), Group, String),
UnaryExpression(Keyword('formation'), TeamMember, String),
UnaryExpression(Keyword('formationdirection'), Object, Number),
UnaryExpression(Keyword('formationleader'), Object, Object),
UnaryExpression(Keyword('formationmembers'), Object, Array),
UnaryExpression(Keyword('formationposition'), Object, Array),
UnaryExpression(Keyword('formationtask'), Object, String),
UnaryExpression(Keyword('formattext'), Array, String),
UnaryExpression(Keyword('formleader'), Object, Object),
UnaryExpression(Keyword('fromeditor'), TeamMember, Boolean),
UnaryExpression(Keyword('fuel'), Object, Number),
UnaryExpression(Keyword('fullcrew'), Object, Array),
UnaryExpression(Keyword('fullcrew'), Array, Array),
UnaryExpression(Keyword('gearidcammocount'), Number, Number),
UnaryExpression(Keyword('gearslotammocount'), Control, Number),
UnaryExpression(Keyword('gearslotdata'), Control, String),
UnaryExpression(Keyword('get3denactionstate'), String, Number),
UnaryExpression(Keyword('get3denconnections'), Type, Array),
UnaryExpression(Keyword('get3denentity'), Number, Anything),
UnaryExpression(Keyword('get3denentityid'), Type, Number),
UnaryExpression(Keyword('get3dengrid'), String, Nothing),
UnaryExpression(Keyword('get3denlayerentities'), Number, Array),
UnaryExpression(Keyword('get3denselected'), String, Array),
UnaryExpression(Keyword('getaimingcoef'), Object, Number),
UnaryExpression(Keyword('getallenvsoundcontrollers'), Array, Array),
UnaryExpression(Keyword('getallhitpointsdamage'), Object, Array),
UnaryExpression(Keyword('getallownedmines'), Object, Array),
UnaryExpression(Keyword('getallsoundcontrollers'), Object, Array),
UnaryExpression(Keyword('getammocargo'), Object, Number),
UnaryExpression(Keyword('getanimaimprecision'), Object, Number),
UnaryExpression(Keyword('getanimspeedcoef'), Object, Number),
UnaryExpression(Keyword('getarray'), Config, Array),
UnaryExpression(Keyword('getartilleryammo'), Array, Array),
UnaryExpression(Keyword('getassignedcuratorlogic'), Object, Object),
UnaryExpression(Keyword('getassignedcuratorunit'), Object, Object),
UnaryExpression(Keyword('getbackpackcargo'), Object, Array),
UnaryExpression(Keyword('getbleedingremaining'), Object, Number),
UnaryExpression(Keyword('getburningvalue'), Object, Number),
UnaryExpression(Keyword('getcameraviewdirection'), Object, Array),
UnaryExpression(Keyword('getcenterofmass'), Object, Array),
UnaryExpression(Keyword('getconnecteduav'), Object, Object),
UnaryExpression(Keyword('getcontainermaxload'), String, Number),
UnaryExpression(Keyword('getcustomaimcoef'), Object, Number),
UnaryExpression(Keyword('getcustomsoundcontroller'), Array, Number),
UnaryExpression(Keyword('getcustomsoundcontrollercount'), Object, Number),
UnaryExpression(Keyword('getdammage'), Object, Number),
UnaryExpression(Keyword('getdescription'), Object, Array),
UnaryExpression(Keyword('getdir'), Object, Number),
UnaryExpression(Keyword('getdirvisual'), Object, Number),
UnaryExpression(Keyword('getdlcassetsusagebyname'), String, Array),
UnaryExpression(Keyword('getdlcs'), Number, Array),
UnaryExpression(Keyword('getdlcusagetime'), Number, Number),
UnaryExpression(Keyword('geteditorcamera'), Control, Object),
UnaryExpression(Keyword('geteditormode'), Control, String),
UnaryExpression(Keyword('getenginetargetrpmrtd'), Object, Array),
UnaryExpression(Keyword('getfatigue'), Object, Number),
UnaryExpression(Keyword('getfieldmanualstartpage'), Display, Array),
UnaryExpression(Keyword('getforcedflagtexture'), Object, String),
UnaryExpression(Keyword('getfuelcargo'), Object, Number),
UnaryExpression(Keyword('getgroupiconparams'), Group, Array),
UnaryExpression(Keyword('getgroupicons'), Group, Array),
UnaryExpression(Keyword('getitemcargo'), Object, Array),
UnaryExpression(Keyword('getmagazinecargo'), Object, Array),
UnaryExpression(Keyword('getmarkercolor'), String, String),
UnaryExpression(Keyword('getmarkerpos'), String, Array),
UnaryExpression(Keyword('getmarkersize'), String, Array),
UnaryExpression(Keyword('getmarkertype'), String, String),
UnaryExpression(Keyword('getmass'), Object, Number),
UnaryExpression(Keyword('getmissionconfig'), String, Config),
UnaryExpression(Keyword('getmissionconfigvalue'), String, Anything),
UnaryExpression(Keyword('getmissionconfigvalue'), Array, Anything),
UnaryExpression(Keyword('getmissionlayerentities'), String, Array),
UnaryExpression(Keyword('getmissionlayerentities'), Number, Array),
UnaryExpression(Keyword('getmodelinfo'), Object, Array),
UnaryExpression(Keyword('getnumber'), Config, Number),
UnaryExpression(Keyword('getobjectdlc'), Object, Number),
UnaryExpression(Keyword('getobjectmaterials'), Object, Array),
UnaryExpression(Keyword('getobjecttextures'), Object, Array),
UnaryExpression(Keyword('getobjecttype'), Object, Number),
UnaryExpression(Keyword('getoxygenremaining'), Object, Number),
UnaryExpression(Keyword('getpersonuseddlcs'), Object, Array),
UnaryExpression(Keyword('getpilotcameradirection'), Object, Array),
UnaryExpression(Keyword('getpilotcameraposition'), Object, Array),
UnaryExpression(Keyword('getpilotcamerarotation'), Object, Array),
UnaryExpression(Keyword('getpilotcameratarget'), Object, Array),
UnaryExpression(Keyword('getplatenumber'), Object, String),
UnaryExpression(Keyword('getplayerchannel'), Object, Number),
UnaryExpression(Keyword('getplayerscores'), Object, Array),
UnaryExpression(Keyword('getplayeruid'), Object, String),
UnaryExpression(Keyword('getpos'), Object, Array),
UnaryExpression(Keyword('getpos'), Location, Array),
UnaryExpression(Keyword('getposasl'), Object, Array),
UnaryExpression(Keyword('getposaslvisual'), Object, Array),
UnaryExpression(Keyword('getposaslw'), Object, Array),
UnaryExpression(Keyword('getposatl'), Object, Array),
UnaryExpression(Keyword('getposatlvisual'), Object, Array),
UnaryExpression(Keyword('getposvisual'), Object, Array),
UnaryExpression(Keyword('getposworld'), Object, Array),
UnaryExpression(Keyword('getpylonmagazines'), Object, Array),
UnaryExpression(Keyword('getrepaircargo'), Object, Number),
UnaryExpression(Keyword('getrotorbrakertd'), Object, Number),
UnaryExpression(Keyword('getshotparents'), Object, Array),
UnaryExpression(Keyword('getslingload'), Object, Object),
UnaryExpression(Keyword('getstamina'), Object, Number),
UnaryExpression(Keyword('getstatvalue'), String, Number),
UnaryExpression(Keyword('getsuppression'), Object, Number),
UnaryExpression(Keyword('getterrainheightasl'), Array, Number),
UnaryExpression(Keyword('gettext'), Config, String),
UnaryExpression(Keyword('gettrimoffsetrtd'), Object, Array),
UnaryExpression(Keyword('getunitloadout'), Object, Array),
UnaryExpression(Keyword('getunitloadout'), Array, Array),
UnaryExpression(Keyword('getunitloadout'), String, Array),
UnaryExpression(Keyword('getunitloadout'), Config, Array),
UnaryExpression(Keyword('getusermfdtext'), Object, Array),
UnaryExpression(Keyword('getusermfdvalue'), Object, Array),
UnaryExpression(Keyword('getvehiclecargo'), Object, Array),
UnaryExpression(Keyword('getweaponcargo'), Object, Array),
UnaryExpression(Keyword('getweaponsway'), Object, Number),
UnaryExpression(Keyword('getwingsorientationrtd'), Object, Number),
UnaryExpression(Keyword('getwingspositionrtd'), Object, Number),
UnaryExpression(Keyword('getwppos'), Array, Array),
UnaryExpression(Keyword('goggles'), Object, String),
UnaryExpression(Keyword('goto'), String, Nothing),
UnaryExpression(Keyword('group'), Object, Group),
UnaryExpression(Keyword('groupfromnetid'), String, Group),
UnaryExpression(Keyword('groupid'), Group, String),
UnaryExpression(Keyword('groupowner'), Group, Number),
UnaryExpression(Keyword('groupselectedunits'), Object, Array),
UnaryExpression(Keyword('gunner'), Object, Object),
UnaryExpression(Keyword('handgunitems'), Object, Array),
UnaryExpression(Keyword('handgunmagazine'), Object, Array),
UnaryExpression(Keyword('handgunweapon'), Object, String),
UnaryExpression(Keyword('handshit'), Object, Number),
UnaryExpression(Keyword('haspilotcamera'), Object, Boolean),
UnaryExpression(Keyword('hcallgroups'), Object, Array),
UnaryExpression(Keyword('hcleader'), Group, Object),
UnaryExpression(Keyword('hcremoveallgroups'), Object, Nothing),
UnaryExpression(Keyword('hcselected'), Object, Array),
UnaryExpression(Keyword('hcshowbar'), Boolean, Nothing),
UnaryExpression(Keyword('headgear'), Object, String),
UnaryExpression(Keyword('hidebody'), Object, Nothing),
UnaryExpression(Keyword('hideobject'), Object, Nothing),
UnaryExpression(Keyword('hideobjectglobal'), Object, Nothing),
UnaryExpression(Keyword('hint'), String, Nothing),
UnaryExpression(Keyword('hint'), String, Nothing),
UnaryExpression(Keyword('hintc'), String, Nothing),
UnaryExpression(Keyword('hintcadet'), String, Nothing),
UnaryExpression(Keyword('hintcadet'), String, Nothing),
UnaryExpression(Keyword('hintsilent'), String, Nothing),
UnaryExpression(Keyword('hintsilent'), String, Nothing),
UnaryExpression(Keyword('hmd'), Object, String),
UnaryExpression(Keyword('hostmission'), Array, Nothing),
UnaryExpression(Keyword('if'), Boolean, IfType),
UnaryExpression(Keyword('image'), String, String),
UnaryExpression(Keyword('importallgroups'), Control, Nothing),
UnaryExpression(Keyword('importance'), Location, Number),
UnaryExpression(Keyword('incapacitatedstate'), Object, String),
UnaryExpression(Keyword('inflamed'), Object, Boolean),
UnaryExpression(Keyword('infopanel'), String, Array),
UnaryExpression(Keyword('infopanels'), Object, Array),
UnaryExpression(Keyword('infopanels'), Array, Array),
UnaryExpression(Keyword('ingameuiseteventhandler'), Array, Nothing),
UnaryExpression(Keyword('inheritsfrom'), Config, Config),
UnaryExpression(Keyword('inputaction'), String, Number),
UnaryExpression(Keyword('isabletobreathe'), Object, Boolean),
UnaryExpression(Keyword('isagent'), TeamMember, Boolean),
UnaryExpression(Keyword('isaimprecisionenabled'), Object, Boolean),
UnaryExpression(Keyword('isarray'), Config, Boolean),
UnaryExpression(Keyword('isautohoveron'), Object, Boolean),
UnaryExpression(Keyword('isautonomous'), Object, Boolean),
UnaryExpression(Keyword('isautostartupenabledrtd'), Object, Array),
UnaryExpression(Keyword('isautotrimonrtd'), Object, Boolean),
UnaryExpression(Keyword('isbleeding'), Object, Boolean),
UnaryExpression(Keyword('isburning'), Object, Boolean),
UnaryExpression(Keyword('isclass'), Config, Boolean),
UnaryExpression(Keyword('iscollisionlighton'), Object, Boolean),
UnaryExpression(Keyword('iscopilotenabled'), Object, Boolean),
UnaryExpression(Keyword('isdamageallowed'), Object, Boolean),
UnaryExpression(Keyword('isdlcavailable'), Number, Boolean),
UnaryExpression(Keyword('isengineon'), Object, Boolean),
UnaryExpression(Keyword('isforcedwalk'), Object, Boolean),
UnaryExpression(Keyword('isformationleader'), Object, Boolean),
UnaryExpression(Keyword('isgroupdeletedwhenempty'), Group, Boolean),
UnaryExpression(Keyword('ishidden'), Object, Boolean),
UnaryExpression(Keyword('isinremainscollector'), Object, Boolean),
UnaryExpression(Keyword('iskeyactive'), String, Boolean),
UnaryExpression(Keyword('islaseron'), Object, Boolean),
UnaryExpression(Keyword('islighton'), Object, Boolean),
UnaryExpression(Keyword('islocalized'), String, Boolean),
UnaryExpression(Keyword('ismanualfire'), Object, Boolean),
UnaryExpression(Keyword('ismarkedforcollection'), Object, Boolean),
UnaryExpression(Keyword('isnil'), Code, Boolean),
UnaryExpression(Keyword('isnil'), String, Boolean),
UnaryExpression(Keyword('isnull'), Object, Boolean),
UnaryExpression(Keyword('isnull'), Group, Boolean),
UnaryExpression(Keyword('isnull'), Script, Boolean),
UnaryExpression(Keyword('isnull'), Config, Boolean),
UnaryExpression(Keyword('isnull'), Display, Boolean),
UnaryExpression(Keyword('isnull'), Control, Boolean),
UnaryExpression(Keyword('isnull'), NetObject, Boolean),
UnaryExpression(Keyword('isnull'), Task, Boolean),
UnaryExpression(Keyword('isnull'), Location, Boolean),
UnaryExpression(Keyword('isnumber'), Config, Boolean),
UnaryExpression(Keyword('isobjecthidden'), Object, Boolean),
UnaryExpression(Keyword('isobjectrtd'), Object, Boolean),
UnaryExpression(Keyword('isonroad'), Object, Boolean),
UnaryExpression(Keyword('isonroad'), Array, Boolean),
UnaryExpression(Keyword('isplayer'), Object, Boolean),
UnaryExpression(Keyword('isrealtime'), Control, Boolean),
UnaryExpression(Keyword('isshowing3dicons'), Control, Boolean),
UnaryExpression(Keyword('issimpleobject'), Object, Boolean),
UnaryExpression(Keyword('issprintallowed'), Object, Boolean),
UnaryExpression(Keyword('isstaminaenabled'), Object, Boolean),
UnaryExpression(Keyword('istext'), Config, Boolean),
UnaryExpression(Keyword('istouchingground'), Object, Boolean),
UnaryExpression(Keyword('isturnedout'), Object, Boolean),
UnaryExpression(Keyword('isuavconnected'), Object, Boolean),
UnaryExpression(Keyword('isvehiclecargo'), Object, Object),
UnaryExpression(Keyword('isvehicleradaron'), Object, Boolean),
UnaryExpression(Keyword('iswalking'), Object, Boolean),
UnaryExpression(Keyword('isweapondeployed'), Object, Boolean),
UnaryExpression(Keyword('isweaponrested'), Object, Boolean),
UnaryExpression(Keyword('itemcargo'), Object, Array),
UnaryExpression(Keyword('items'), Object, Array),
UnaryExpression(Keyword('itemswithmagazines'), Object, Array),
UnaryExpression(Keyword('keyimage'), Number, String),
UnaryExpression(Keyword('keyname'), Number, String),
UnaryExpression(Keyword('landresult'), Object, String),
UnaryExpression(Keyword('lasertarget'), Object, Object),
UnaryExpression(Keyword('lbadd'), Array, Number),
UnaryExpression(Keyword('lbclear'), Control, Nothing),
UnaryExpression(Keyword('lbclear'), Number, Nothing),
UnaryExpression(Keyword('lbcolor'), Array, Array),
UnaryExpression(Keyword('lbcolorright'), Array, Array),
UnaryExpression(Keyword('lbcursel'), Control, Number),
UnaryExpression(Keyword('lbcursel'), Number, Number),
UnaryExpression(Keyword('lbdata'), Array, String),
UnaryExpression(Keyword('lbdelete'), Array, Nothing),
UnaryExpression(Keyword('lbpicture'), Array, String),
UnaryExpression(Keyword('lbpictureright'), Array, String),
UnaryExpression(Keyword('lbselection'), Control, Array),
UnaryExpression(Keyword('lbsetcolor'), Array, Nothing),
UnaryExpression(Keyword('lbsetcolorright'), Array, Nothing),
UnaryExpression(Keyword('lbsetcursel'), Array, Nothing),
UnaryExpression(Keyword('lbsetdata'), Array, Nothing),
UnaryExpression(Keyword('lbsetpicture'), Array, Nothing),
UnaryExpression(Keyword('lbsetpicturecolor'), Array, Nothing),
UnaryExpression(Keyword('lbsetpicturecolordisabled'), Array, Nothing),
UnaryExpression(Keyword('lbsetpicturecolorselected'), Array, Nothing),
UnaryExpression(Keyword('lbsetpictureright'), Array, Nothing),
UnaryExpression(Keyword('lbsetselectcolor'), Array, Nothing),
UnaryExpression(Keyword('lbsetselectcolorright'), Array, Nothing),
UnaryExpression(Keyword('lbsettext'), Array, String),
UnaryExpression(Keyword('lbsettooltip'), Array, Nothing),
UnaryExpression(Keyword('lbsetvalue'), Array, Nothing),
UnaryExpression(Keyword('lbsize'), Control, Number),
UnaryExpression(Keyword('lbsize'), Number, Number),
UnaryExpression(Keyword('lbsort'), Control, Nothing),
UnaryExpression(Keyword('lbsort'), Array, Nothing),
UnaryExpression(Keyword('lbsort'), Number, Nothing),
UnaryExpression(Keyword('lbsortbyvalue'), Control, Nothing),
UnaryExpression(Keyword('lbsortbyvalue'), Number, Nothing),
UnaryExpression(Keyword('lbtext'), Array, String),
UnaryExpression(Keyword('lbtextright'), Array, String),
UnaryExpression(Keyword('lbvalue'), Array, Number),
UnaryExpression(Keyword('leader'), Object, Object),
UnaryExpression(Keyword('leader'), Group, Object),
UnaryExpression(Keyword('leader'), TeamMember, TeamMember),
UnaryExpression(Keyword('leaderboarddeinit'), String, Boolean),
UnaryExpression(Keyword('leaderboardgetrows'), String, Array),
UnaryExpression(Keyword('leaderboardinit'), String, Boolean),
UnaryExpression(Keyword('leaderboardrequestrowsfriends'), String, Boolean),
UnaryExpression(Keyword('leaderboardrequestrowsglobal'), Array, Boolean),
UnaryExpression(Keyword('leaderboardrequestrowsglobalarounduser'), Array, Boolean),
UnaryExpression(Keyword('leaderboardsrequestuploadscore'), Array, Boolean),
UnaryExpression(Keyword('leaderboardsrequestuploadscorekeepbest'), Array, Boolean),
UnaryExpression(Keyword('leaderboardstate'), String, Number),
UnaryExpression(Keyword('lifestate'), Object, String),
UnaryExpression(Keyword('lightdetachobject'), Object, Nothing),
UnaryExpression(Keyword('lightison'), Object, String),
UnaryExpression(Keyword('linearconversion'), Array, Number),
UnaryExpression(Keyword('lineintersects'), Array, Boolean),
UnaryExpression(Keyword('lineintersectsobjs'), Array, Array),
UnaryExpression(Keyword('lineintersectssurfaces'), Array, Array),
UnaryExpression(Keyword('lineintersectswith'), Array, Array),
UnaryExpression(Keyword('list'), Object, Array),
UnaryExpression(Keyword('listremotetargets'), Side, Array),
UnaryExpression(Keyword('listvehiclesensors'), Object, Array),
UnaryExpression(Keyword('ln'), Number, Number),
UnaryExpression(Keyword('lnbaddarray'), Array, Number),
UnaryExpression(Keyword('lnbaddcolumn'), Array, Number),
UnaryExpression(Keyword('lnbaddrow'), Array, Number),
UnaryExpression(Keyword('lnbclear'), Control, Nothing),
UnaryExpression(Keyword('lnbclear'), Number, Nothing),
UnaryExpression(Keyword('lnbcolor'), Array, Array),
UnaryExpression(Keyword('lnbcolorright'), Array, Array),
UnaryExpression(Keyword('lnbcurselrow'), Control, Number),
UnaryExpression(Keyword('lnbcurselrow'), Number, Number),
UnaryExpression(Keyword('lnbdata'), Array, String),
UnaryExpression(Keyword('lnbdeletecolumn'), Array, Nothing),
UnaryExpression(Keyword('lnbdeleterow'), Array, Nothing),
UnaryExpression(Keyword('lnbgetcolumnsposition'), Control, Array),
UnaryExpression(Keyword('lnbgetcolumnsposition'), Number, Array),
UnaryExpression(Keyword('lnbpicture'), Array, String),
UnaryExpression(Keyword('lnbpictureright'), Array, String),
UnaryExpression(Keyword('lnbsetcolor'), Array, Nothing),
UnaryExpression(Keyword('lnbsetcolorright'), Array, Nothing),
UnaryExpression(Keyword('lnbsetcolumnspos'), Array, Nothing),
UnaryExpression(Keyword('lnbsetcurselrow'), Array, Nothing),
UnaryExpression(Keyword('lnbsetdata'), Array, Nothing),
UnaryExpression(Keyword('lnbsetpicture'), Array, Nothing),
UnaryExpression(Keyword('lnbsetpicturecolor'), Array, Nothing),
UnaryExpression(Keyword('lnbsetpicturecolorright'), Array, Nothing),
UnaryExpression(Keyword('lnbsetpicturecolorselected'), Array, Nothing),
UnaryExpression(Keyword('lnbsetpicturecolorselectedright'), Array, Nothing),
UnaryExpression(Keyword('lnbsetpictureright'), Array, Nothing),
UnaryExpression(Keyword('lnbsettext'), Array, Nothing),
UnaryExpression(Keyword('lnbsettextright'), Array, Nothing),
UnaryExpression(Keyword('lnbsetvalue'), Array, Nothing),
UnaryExpression(Keyword('lnbsize'), Control, Array),
UnaryExpression(Keyword('lnbsize'), Number, Array),
UnaryExpression(Keyword('lnbsort'), Array, Nothing),
UnaryExpression(Keyword('lnbsortbyvalue'), Array, Nothing),
UnaryExpression(Keyword('lnbtext'), Array, String),
UnaryExpression(Keyword('lnbtextright'), Array, String),
UnaryExpression(Keyword('lnbvalue'), Array, Number),
UnaryExpression(Keyword('load'), Object, Number),
UnaryExpression(Keyword('loadabs'), Object, Number),
UnaryExpression(Keyword('loadbackpack'), Object, Number),
UnaryExpression(Keyword('loadfile'), String, String),
UnaryExpression(Keyword('loaduniform'), Object, Number),
UnaryExpression(Keyword('loadvest'), Object, Number),
UnaryExpression(Keyword('local'), Object, Boolean),
UnaryExpression(Keyword('local'), Group, Boolean),
UnaryExpression(Keyword('localize'), String, String),
UnaryExpression(Keyword('locationposition'), Location, Array),
UnaryExpression(Keyword('locked'), Object, Number),
UnaryExpression(Keyword('lockeddriver'), Object, Boolean),
UnaryExpression(Keyword('lockidentity'), Object, Boolean),
UnaryExpression(Keyword('log'), Number, Number),
UnaryExpression(Keyword('lognetwork'), Array, Number),
UnaryExpression(Keyword('lognetworkterminate'), Number, Nothing),
UnaryExpression(Keyword('magazinecargo'), Object, Array),
UnaryExpression(Keyword('magazines'), Object, Array),
UnaryExpression(Keyword('magazinesallturrets'), Object, Array),
UnaryExpression(Keyword('magazinesammo'), Object, Array),
UnaryExpression(Keyword('magazinesammocargo'), Object, Array),
UnaryExpression(Keyword('magazinesammofull'), Object, Array),
UnaryExpression(Keyword('magazinesdetail'), Object, Array),
UnaryExpression(Keyword('magazinesdetailbackpack'), Object, Array),
UnaryExpression(Keyword('magazinesdetailuniform'), Object, Array),
UnaryExpression(Keyword('magazinesdetailvest'), Object, Array),
UnaryExpression(Keyword('mapanimadd'), Array, Nothing),
UnaryExpression(Keyword('mapcenteroncamera'), Control, Array),
UnaryExpression(Keyword('mapgridposition'), Object, String),
UnaryExpression(Keyword('mapgridposition'), Array, String),
UnaryExpression(Keyword('markeralpha'), String, Number),
UnaryExpression(Keyword('markerbrush'), String, String),
UnaryExpression(Keyword('markercolor'), String, String),
UnaryExpression(Keyword('markerdir'), String, Number),
UnaryExpression(Keyword('markerpos'), String, Array),
UnaryExpression(Keyword('markershape'), String, String),
UnaryExpression(Keyword('markersize'), String, Array),
UnaryExpression(Keyword('markertext'), String, String),
UnaryExpression(Keyword('markertype'), String, String),
UnaryExpression(Keyword('members'), TeamMember, Array),
UnaryExpression(Keyword('menuaction'), Array, String),
UnaryExpression(Keyword('menuadd'), Array, Number),
UnaryExpression(Keyword('menuchecked'), Array, Boolean),
UnaryExpression(Keyword('menuclear'), Control, Nothing),
UnaryExpression(Keyword('menuclear'), Number, Nothing),
UnaryExpression(Keyword('menucollapse'), Array, Nothing),
UnaryExpression(Keyword('menudata'), Array, String),
UnaryExpression(Keyword('menudelete'), Array, Nothing),
UnaryExpression(Keyword('menuenable'), Array, Nothing),
UnaryExpression(Keyword('menuenabled'), Array, Boolean),
UnaryExpression(Keyword('menuexpand'), Array, Nothing),
UnaryExpression(Keyword('menuhover'), Control, Array),
UnaryExpression(Keyword('menuhover'), Number, Array),
UnaryExpression(Keyword('menupicture'), Array, String),
UnaryExpression(Keyword('menusetaction'), Array, Nothing),
UnaryExpression(Keyword('menusetcheck'), Array, Nothing),
UnaryExpression(Keyword('menusetdata'), Array, Nothing),
UnaryExpression(Keyword('menusetpicture'), Array, Nothing),
UnaryExpression(Keyword('menusetvalue'), Array, Nothing),
UnaryExpression(Keyword('menushortcut'), Array, Number),
UnaryExpression(Keyword('menushortcuttext'), Array, String),
UnaryExpression(Keyword('menusize'), Array, Number),
UnaryExpression(Keyword('menusort'), Array, Nothing),
UnaryExpression(Keyword('menutext'), Array, String),
UnaryExpression(Keyword('menuurl'), Array, String),
UnaryExpression(Keyword('menuvalue'), Array, Number),
UnaryExpression(Keyword('mineactive'), Object, Boolean),
UnaryExpression(Keyword('modparams'), Array, Array),
UnaryExpression(Keyword('moonphase'), Array, Number),
UnaryExpression(Keyword('morale'), Object, Number),
UnaryExpression(Keyword('move3dencamera'), Array, Nothing),
UnaryExpression(Keyword('moveout'), Object, Nothing),
UnaryExpression(Keyword('movetime'), Object, Number),
UnaryExpression(Keyword('movetocompleted'), Object, Boolean),
UnaryExpression(Keyword('movetofailed'), Object, Boolean),
UnaryExpression(Keyword('name'), Object, String),
UnaryExpression(Keyword('name'), Location, String),
UnaryExpression(Keyword('namesound'), Object, String),
UnaryExpression(Keyword('nearestbuilding'), Object, Object),
UnaryExpression(Keyword('nearestbuilding'), Array, Object),
UnaryExpression(Keyword('nearestlocation'), Array, Location),
UnaryExpression(Keyword('nearestlocations'), Array, Array),
UnaryExpression(Keyword('nearestlocationwithdubbing'), Array, Location),
UnaryExpression(Keyword('nearestobject'), Array, Object),
UnaryExpression(Keyword('nearestobjects'), Array, Array),
UnaryExpression(Keyword('nearestterrainobjects'), Array, Array),
UnaryExpression(Keyword('needreload'), Object, Number),
UnaryExpression(Keyword('netid'), Object, String),
UnaryExpression(Keyword('netid'), Group, String),
UnaryExpression(Keyword('nextmenuitemindex'), | |
== key.BRACKETLEFT:
if self.highlighted_cell_one > 1:
self.highlighted_cell_one -= 1
elif self.highlighted_cell_one == 1:
self.highlighted_cell_one = self.get_max_label()
if self.highlight:
self.update_image = True
# ENTER EDIT MODE
if symbol == key.E:
self.edit_mode = True
# update composite with changes, if needed
if not self.hide_annotations:
self.helper_update_composite()
self.update_image = True
# SAVE
if symbol == key.S:
self.mode.update("QUESTION", action="SAVE")
def label_mode_single_keypress_helper(self, symbol, modifiers):
'''
Helper function for keypress handling. The keybinds that are
handled here apply to label-editing mode only if one label is
selected and no actions are awaiting confirmation.
Keybinds:
] (right bracket): increment currently-highlighted label by 1
[ (left bracket): decrement currently-highlighted label by 1
c: prompt creation of new label
f: prompt hole fill
x: prompt deletion of label in frame
'''
# HIGHLIGHT CYCLING
if symbol == key.BRACKETRIGHT:
if (self.highlighted_cell_one < self.get_max_label() and
self.highlighted_cell_one > -1):
self.highlighted_cell_one += 1
elif self.highlighted_cell_one == self.get_max_label():
self.highlighted_cell_one = 1
# deselect label, since highlighting is now decoupled from selection
self.mode.clear()
if self.highlight:
self.update_image = True
if symbol == key.BRACKETLEFT:
if self.highlighted_cell_one > 1:
self.highlighted_cell_one -= 1
elif self.highlighted_cell_one == 1:
self.highlighted_cell_one = self.get_max_label()
# deselect label
self.mode.clear()
if self.highlight:
self.update_image = True
# CREATE CELL
if symbol == key.C:
self.mode.update("QUESTION", action="NEW TRACK", **self.mode.info)
# HOLE FILL
if symbol == key.F:
self.mode.update("PROMPT", action="FILL HOLE", **self.mode.info)
# DELETE CELL
if symbol == key.X:
self.mode.update("QUESTION", action="DELETE", **self.mode.info)
def label_mode_multiple_keypress_helper(self, symbol, modifiers):
'''
Helper function for keypress handling. The keybinds that are
handled here apply to label-editing mode only if two labels are
selected and no actions are awaiting confirmation. (Note: the
two selected labels must be the same label for watershed to work,
and different labels for replace and swap to work.)
Keybinds:
p: prompt assignment of parent/daughter pair
r: prompt replacement of one label with another
s: prompt swap between two labels
w: prompt watershed action
'''
# PARENT
if symbol == key.P:
self.mode.update("QUESTION", action="PARENT", **self.mode.info)
# REPLACE
if symbol == key.R:
self.mode.update("QUESTION", action="REPLACE", **self.mode.info)
# SWAP
if symbol == key.S:
self.mode.update("QUESTION", action="SWAP", **self.mode.info)
# WATERSHED
if symbol == key.W:
self.mode.update("QUESTION", action="WATERSHED", **self.mode.info)
def label_mode_question_keypress_helper(self, symbol, modifiers):
'''
Helper function for keypress handling. The keybinds that are
handled here apply to label-editing mode when actions are awaiting
confirmation. Most actions are confirmed with the space key, while
others have different options mapped to other keys. Keybinds in this
helper function are grouped by the question they are responding to.
Keybinds:
space: carries out action; when action can be applied to single OR
multiple frames, space carries out the multiple frame option
s: carries out single-frame version of action where applicable
'''
# RESPOND TO SAVE QUESTION
if self.mode.action == "SAVE":
if symbol == key.SPACE:
self.save()
self.mode.clear()
# RESPOND TO CREATE QUESTION
elif self.mode.action == "NEW TRACK":
if symbol == key.S:
self.action_new_single_cell()
self.mode.clear()
if symbol == key.SPACE:
self.action_new_track()
self.mode.clear()
# RESPOND TO REPLACE QUESTION
elif self.mode.action == "REPLACE":
if symbol == key.SPACE:
self.action_replace()
self.mode.clear()
# RESPOND TO SWAP QUESTION
elif self.mode.action == "SWAP":
if symbol == key.S:
self.action_single_swap()
self.mode.clear()
if symbol == key.SPACE:
self.action_swap()
self.mode.clear()
# RESPOND TO DELETE QUESTION
elif self.mode.action == "DELETE":
if symbol == key.SPACE:
self.action_delete()
self.mode.clear()
# RESPOND TO WATERSHED QUESTION
elif self.mode.action == "WATERSHED":
if symbol == key.SPACE:
self.action_watershed()
self.mode.clear()
# RESPOND TO TRIM PIXELS QUESTION
elif self.mode.action == "TRIM PIXELS":
if symbol == key.SPACE:
self.action_trim_pixels()
self.mode.clear()
# RESPOND TO FLOOD CELL QUESTION
elif self.mode.action == "FLOOD CELL":
if symbol == key.SPACE:
self.action_flood_contiguous()
self.mode.clear()
elif self.mode.action == "PARENT":
if symbol == key.SPACE:
self.action_parent()
self.mode.clear()
def custom_prompt(self):
if self.mode.kind == "QUESTION":
if self.mode.action == "REPLACE":
self.mode.text = TrackReview.replace_prompt.format(self.mode.label_2,
self.mode.label_1)
def get_raw_current_frame(self):
return self.raw[self.current_frame,:,:,0]
def get_ann_current_frame(self):
return self.tracked[self.current_frame,:,:,0]
def get_label(self):
return int(self.tracked[self.current_frame, self.y, self.x])
def get_max_label(self):
return max(self.tracks)
def get_new_label(self):
return (self.get_max_label() + 1)
def get_label_info(self, label):
info = self.tracks[label].copy()
frames = list(map(list, consecutive(info["frames"])))
frames = '[' + ', '.join(["{}".format(a[0])
if len(a) == 1 else "{}-{}".format(a[0], a[-1])
for a in frames]) + ']'
info["frames"] = frames
return info
def create_frame_text(self):
frame_text = "Frame: {}\n".format(self.current_frame)
return frame_text
def action_new_track(self):
"""
Replacing label
"""
old_label, start_frame = self.mode.label, self.mode.frame
new_label = self.get_new_label()
if start_frame == 0:
raise ValueError("new_track cannot be called on the first frame")
# replace frame labels
for frame in self.tracked[start_frame:]:
frame[frame == old_label] = new_label
# replace fields
track_old = self.tracks[old_label]
track_new = self.tracks[new_label] = {}
idx = track_old["frames"].index(start_frame)
frames_before, frames_after = track_old["frames"][:idx], track_old["frames"][idx:]
track_old["frames"] = frames_before
track_new["frames"] = frames_after
track_new["label"] = new_label
track_new["daughters"] = track_old["daughters"]
track_new["frame_div"] = track_old["frame_div"]
track_new["capped"] = track_old["capped"]
track_new["parent"] = None
track_old["daughters"] = []
track_old["frame_div"] = None
track_old["capped"] = True
self.update_image = True
def action_new_single_cell(self):
"""
Create new label in just one frame
"""
old_label, single_frame = self.mode.label, self.mode.frame
new_label = self.get_new_label()
# replace frame labels
frame = self.tracked[single_frame]
frame[frame == old_label] = new_label
# replace fields
self.del_cell_info(del_label = old_label, frame = single_frame)
self.add_cell_info(add_label = new_label, frame = single_frame)
self.update_image = True
def action_watershed(self):
# Pull the label that is being split and find a new valid label
current_label = self.mode.label_1
new_label = self.get_new_label()
# Locally store the frames to work on
img_raw = self.raw[self.current_frame,:,:,0]
img_ann = self.tracked[self.current_frame,:,:,0]
# Pull the 2 seed locations and store locally
# define a new seeds labeled img that is the same size as raw/annotaiton imgs
seeds_labeled = np.zeros(img_ann.shape)
# create two seed locations
seeds_labeled[self.mode.y1_location, self.mode.x1_location]=current_label
seeds_labeled[self.mode.y2_location, self.mode.x2_location]=new_label
# define the bounding box to apply the transform on and select appropriate sections of 3 inputs (raw, seeds, annotation mask)
props = regionprops(np.squeeze(np.int32(img_ann == current_label)))
minr, minc, maxr, maxc = props[0].bbox
# store these subsections to run the watershed on
img_sub_raw = np.copy(img_raw[minr:maxr, minc:maxc])
img_sub_ann = np.copy(img_ann[minr:maxr, minc:maxc])
img_sub_seeds = np.copy(seeds_labeled[minr:maxr, minc:maxc])
# contrast adjust the raw image to assist the transform
img_sub_raw_scaled = rescale_intensity(img_sub_raw)
# apply watershed transform to the subsections
ws = watershed(-img_sub_raw_scaled, img_sub_seeds, mask=img_sub_ann.astype(bool))
# did watershed effectively create a new label?
new_pixels = np.count_nonzero(np.logical_and(ws == new_label, img_sub_ann == current_label))
# if only a few pixels split, dilate them; new label is "brightest"
# so will expand over other labels and increase area
if new_pixels < 5:
ws = dilation(ws, disk(3))
# ws may only leave a few pixels of old label
old_pixels = np.count_nonzero(ws == current_label)
if old_pixels < 5:
# create dilation image so "dimmer" label is not eroded by "brighter" label
dilated_ws = dilation(np.where(ws==current_label, ws, 0), disk(3))
ws = np.where(dilated_ws==current_label, dilated_ws, ws)
# only update img_sub_ann where ws has changed label from current_label to new_label
img_sub_ann = np.where(np.logical_and(ws == new_label,img_sub_ann == current_label), ws, img_sub_ann)
# reintegrate subsection into original mask
img_ann[minr:maxr, minc:maxc] = img_sub_ann
self.tracked[self.current_frame,:,:,0] = img_ann
# current label doesn't change, but add the neccesary bookkeeping for the new track
self.add_cell_info(add_label = new_label, frame = self.current_frame)
self.update_image = True
def action_swap(self):
def relabel(old_label, new_label):
for frame in self.tracked:
frame[frame == old_label] = new_label
# replace fields
track_new = self.tracks[new_label] = self.tracks[old_label]
track_new["label"] = new_label
del self.tracks[old_label]
for d in track_new["daughters"]:
self.tracks[d]["parent"] = new_label
relabel(self.mode.label_1, -1)
relabel(self.mode.label_2, self.mode.label_1)
relabel(-1, self.mode.label_2)
self.update_image = True
def action_single_swap(self):
'''
swap annotation labels in one frame but do not change lineage info
'''
label_1 = self.mode.label_1
label_2 = self.mode.label_2
frame = self.current_frame
ann_img = self.tracked[frame]
ann_img = np.where(ann_img == label_1, -1, ann_img)
ann_img = np.where(ann_img == label_2, label_1, ann_img)
ann_img = np.where(ann_img == -1, label_2, ann_img)
self.tracked[frame] = ann_img
self.update_image = True
def action_parent(self):
"""
label_1 gave birth to label_2
"""
label_1, label_2, frame_div = self.mode.label_1, self.mode.label_2, self.mode.frame_2
track_1 = self.tracks[label_1]
track_2 = self.tracks[label_2]
#add daughter but don't duplicate entry
daughters = track_1["daughters"].copy()
daughters.append(label_2)
daughters = np.unique(daughters).tolist()
track_1["daughters"] = daughters
track_2["parent"] = label_1
track_1["frame_div"] = frame_div
def action_replace(self):
"""
Replacing label_2 with label_1. Overwrites all instances of label_2 in
movie, and replaces label_2 lineage information with info from label_1.
"""
label_1, label_2 = self.mode.label_1, self.mode.label_2
#replacing a label with itself crashes Caliban, not good
if label_1 == label_2:
pass
else:
# | |
from typing import (
Any,
Callable,
List,
NamedTuple,
Optional,
Tuple,
Type,
Union,
overload,
)
import numpy as np
from scipy import special
Array = Union[np.ndarray]
Numeric = Union[int, float]
# Lists = Union[Numeric, List['Lists']]
Tuplist = Union[Tuple[int, ...], List[int]]
Dim = Union[int, Tuplist]
Arrayable = Union[Numeric, Tuplist, Array]
Tensorable = Union[Arrayable, "Tensor"]
float32 = np.float32
float64 = np.float64
int64 = np.int64
def ensure_array(arr: Arrayable, dtype: Optional[Union[str, Type]] = None) -> Array:
return np.array(arr, dtype=dtype, copy=False)
def ensure_tensor(arr: Tensorable) -> "Tensor":
if not isinstance(arr, Tensor):
return Tensor(data=arr)
return arr
class Dependancy(NamedTuple):
tensor: "Tensor"
grad_fn: Callable[[Array], Array]
class Tensor:
no_grad = False
def __init__(
self,
data: Arrayable,
dtype: Optional[Union[str, Type]] = None,
depends_on: Optional[List[Dependancy]] = None,
requires_grad: bool = False,
) -> None:
self._data: Array = ensure_array(data, dtype=dtype)
self._dtype: str = self._data.dtype.name
if requires_grad and "float" not in self._dtype:
raise RuntimeError("Only float tensors support requires_grad")
self._depends_on: List[Dependancy] = depends_on or []
self._is_leaf: bool = not self._depends_on
self._requires_grad: bool = requires_grad
self._grad: Optional[Tensor] = None
def __neg__(self) -> "Tensor":
return neg(self)
def __add__(self, other: Tensorable) -> "Tensor":
return add(self, ensure_tensor(other))
def __radd__(self, other: Tensorable) -> "Tensor":
return self.__add__(other)
def __iadd__(self, other: Tensorable) -> "Tensor":
self.data += ensure_tensor(other).data
return self
def __sub__(self, other: Tensorable) -> "Tensor":
return sub(self, ensure_tensor(other))
def __rsub__(self, other: Tensorable) -> "Tensor":
return self.__sub__(other)
def __isub__(self, other: Tensorable) -> "Tensor":
self.data -= ensure_tensor(other).data
return self
def __mul__(self, other: Tensorable) -> "Tensor":
return mul(self, ensure_tensor(other))
def __rmul__(self, other: Tensorable) -> "Tensor":
return self.__mul__(other)
def __imul__(self, other: Tensorable) -> "Tensor":
self.data *= ensure_tensor(other).data
return self
def __truediv__(self, other: Tensorable) -> "Tensor":
return div(self, ensure_tensor(other))
def __rtruediv__(self, other: Tensorable) -> "Tensor":
return div(ensure_tensor(other), self)
def __itruediv__(self, other: Tensorable) -> "Tensor":
self.data /= ensure_tensor(other).data
return self
def __pow__(self, other: Numeric) -> "Tensor":
return pow(self, other)
def __matmul__(self, other: Tensorable) -> "Tensor":
return matmul(self, ensure_tensor(other))
def __len__(self) -> int:
return len(self.data)
def __getitem__(
self, indices: Union[None, int, slice, Tuple[Any, ...]]
) -> "Tensor":
return tslice(self, indices)
def __str__(self) -> str:
return self.__repr__()
def __repr__(self) -> str:
return f"tensor({self._data}, requires_grad={self.requires_grad})"
@property
def data(self) -> Array:
return self._data
@data.setter
def data(self, new_data: Array) -> None:
if not self.no_grad and self.requires_grad:
raise RuntimeError(
"Variable that requires grad has been used an in-place operation."
)
self._data = new_data
@property
def dtype(self) -> str:
return self._dtype
@property
def requires_grad(self) -> bool:
return self._requires_grad
@requires_grad.setter
def requires_grad(self, value: bool) -> None:
if not self.is_leaf:
raise RuntimeError(
"you can only change requires_grad flags of leaf variables"
)
self._requires_grad = value
@property
def is_leaf(self) -> bool:
return self._is_leaf
@property
def depends_on(self) -> List[Dependancy]:
return self._depends_on
@property
def grad(self) -> Optional["Tensor"]:
return self._grad
@grad.setter
def grad(self, other: Optional["Tensor"]) -> None:
self._grad = other
def numel(self) -> int:
return numel(self)
@property
def shape(self) -> Tuple[int, ...]:
return self.data.shape # type: ignore
@overload
def size(self) -> Tuple[int, ...]:
...
@overload
def size(self, dim: int) -> int:
...
def size(self, dim: Optional[int] = None) -> Union[int, Tuple[int, ...]]:
if dim is None:
return self.shape
return self.shape[dim]
@property
def ndim(self) -> int:
return len(self.shape)
def dim(self) -> int:
return len(self.shape)
def ndimension(self) -> int:
return len(self.shape)
def reshape(self, shape: Tuplist) -> "Tensor":
return reshape(self, shape)
def view(self, *shape: int) -> "Tensor":
return self.reshape(shape)
def transpose(self, dim0: int, dim1: int) -> "Tensor":
return transpose(self, dim0=dim0, dim1=dim1)
def t(self) -> "Tensor":
return self.transpose(dim0=0, dim1=1)
def item(self) -> Numeric:
return self.data.item() # type: ignore
def tolist(self) -> list:
return self.data.tolist() # type: ignore
def numpy(self) -> Array:
if self.requires_grad:
raise RuntimeError(
"Can't call numpy() on Variable that requires grad. Use .detach().numpy() istead"
)
return self.data
def cpu(self) -> "Tensor":
return self
def cuda(self) -> "Tensor":
return self
def sum(self, dim: Optional[Dim] = None, keepdim: bool = False) -> "Tensor":
return reduce_sum(self, dim=dim, keepdim=keepdim)
def mean(self, dim: Optional[Dim] = None, keepdim: bool = False) -> "Tensor":
return reduce_mean(self, dim=dim, keepdim=keepdim)
@overload
def max(self) -> "Tensor":
...
@overload
def max(self, dim: int) -> Tuple["Tensor", "Tensor"]:
...
@overload
def max(self, dim: int, keepdim: bool) -> Tuple["Tensor", "Tensor"]:
...
def max(
self, dim: Optional[int] = None, keepdim: bool = False
) -> Union["Tensor", Tuple["Tensor", "Tensor"]]:
return reduce_max(self, dim=dim, keepdim=keepdim)
def argmax(self, dim: Optional[int] = None, keepdim: bool = False) -> "Tensor":
return reduce_argmax(self, dim=dim, keepdim=keepdim)
def pow(self, val: Numeric) -> "Tensor":
return pow(self, val)
def exp(self) -> "Tensor":
return exp(self)
def log(self) -> "Tensor":
return log(self)
def log1p(self) -> "Tensor":
return log1p(self)
def sigmoid(self) -> "Tensor":
return sigmoid(self)
def tanh(self) -> "Tensor":
return tanh(self)
def detach(self) -> "Tensor":
return Tensor(data=self.data)
def zero_(self) -> None:
if not Tensor.no_grad and self.requires_grad:
raise RuntimeError(
"a leaf Variable that requires grad has been used in an in-place operation."
)
self._data.fill(0)
def uniform_(self, _from: Numeric = 0, to: Numeric = 1) -> None:
if not Tensor.no_grad and self.requires_grad:
raise RuntimeError(
"a leaf Variable that requires grad has been used in an in-place operation."
)
self._data[:] = np.random.uniform(low=_from, high=to, size=self._data.shape)
def backward(
self, grad: Optional["Tensor"] = None, retain_graph: bool = False
) -> None:
self._backward(grad)
if not retain_graph:
self._free_buffers()
def _backward(self, grad: Optional["Tensor"] = None) -> None:
if not self.requires_grad:
raise RuntimeError("Variable has to be differentiable")
if grad is None:
if np.prod(self.shape) == 1:
grad = Tensor(1, dtype=self.data.dtype)
else:
raise RuntimeError("Gradient shape is not the same as s one")
if self.is_leaf:
if self._grad is None:
self._grad = Tensor(np.zeros_like(self.data))
self._grad.data += grad.data
for dependancy in self.depends_on:
backward_grad = dependancy.grad_fn(grad.data)
dependancy.tensor._backward(Tensor(backward_grad))
def _free_buffers(self) -> None:
for dependancy in self.depends_on:
dependancy.tensor._free_buffers()
self._depends_on = []
def tensor(
data: Arrayable,
dtype: Optional[Union[str, Type]] = None,
requires_grad: bool = False,
) -> Tensor:
return Tensor(data=data, dtype=dtype, requires_grad=requires_grad)
class no_grad:
def __enter__(self) -> None:
self.prev = Tensor.no_grad
Tensor.no_grad = True
def __exit__(self, *args: Any) -> None:
Tensor.no_grad = self.prev
# Tensors
def numel(input: Tensor) -> int:
return input.data.size # type: ignore
# Reduction operations
def reduce_sum(
input: Tensor, dim: Optional[Dim] = None, keepdim: bool = False
) -> Tensor:
if dim is None:
assert not keepdim
data = input.data.sum(axis=dim, keepdims=keepdim)
requires_grad = not Tensor.no_grad and input.requires_grad
depends_on = []
if requires_grad:
def grad_fn(grad: Array) -> Array:
nonlocal dim
shape = [1] * input.data.ndim
if dim is not None:
if not keepdim:
grad = np.expand_dims(grad, dim)
if isinstance(dim, int):
dim = [dim]
for d in dim:
shape[d] = input.shape[d]
adjoint = np.ones(shape=shape, dtype=input.dtype)
return grad * adjoint
depends_on.append(Dependancy(tensor=input, grad_fn=grad_fn))
return Tensor(data=data, depends_on=depends_on, requires_grad=requires_grad)
def reduce_mean(
input: Tensor, dim: Optional[Dim] = None, keepdim: bool = False
) -> Tensor:
shape = np.array(input.shape)[dim]
return reduce_sum(input / np.prod(shape), dim=dim, keepdim=keepdim)
def reduce_max(
input: Tensor, dim: Optional[int] = None, keepdim: bool = False
) -> Union[Tensor, Tuple[Tensor, Tensor]]:
if dim is None:
assert not keepdim
argmax = input.data.argmax(axis=dim)
if dim is not None:
data = np.take_along_axis(
input.data, np.expand_dims(argmax, axis=dim), axis=dim
)
if not keepdim:
data = data.squeeze(axis=dim)
else:
argmax_unravel = np.unravel_index(argmax, input.data.shape)
data = input.data[argmax_unravel]
requires_grad = not Tensor.no_grad and input.requires_grad
depends_on = []
if requires_grad:
def grad_fn(grad: Array) -> Array:
adjoint = np.zeros_like(input.data)
if dim is not None:
np.put_along_axis(
adjoint, np.expand_dims(argmax, axis=dim), 1, axis=dim
)
if not keepdim:
grad = np.expand_dims(grad, axis=dim)
else:
adjoint[argmax_unravel] = 1
return grad * adjoint
depends_on.append(Dependancy(tensor=input, grad_fn=grad_fn))
out = Tensor(data=data, depends_on=depends_on, requires_grad=requires_grad)
if dim is None:
return out
if keepdim:
indices = np.expand_dims(argmax, axis=dim)
else:
indices = argmax
return out, Tensor(data=indices)
def reduce_argmax(
input: Tensor, dim: Optional[int] = None, keepdim: bool = False
) -> Tensor:
if dim is None:
assert not keepdim
data = input.data.argmax(axis=dim)
if keepdim:
data = np.expand_dims(data, axis=dim)
return Tensor(data=data)
# Pointwise operations
def neg(input: Tensor) -> Tensor:
data = -input.data
requires_grad = not Tensor.no_grad and input.requires_grad
depends_on = []
if requires_grad:
def grad_fn(grad: Array) -> Array:
return -grad
depends_on.append(Dependancy(tensor=input, grad_fn=grad_fn))
return Tensor(data=data, depends_on=depends_on, requires_grad=requires_grad)
def handle_grad_broadcasting(grad: Array, shape: Tuplist) -> Array:
# https://stackoverflow.com/questions/45428696/more-pythonic-way-to-compute-derivatives-of-broadcast-addition-in-numpy
ndim = grad.ndim - len(shape)
axis_first = tuple(range(ndim))
axis = axis_first + tuple(i + ndim for i, dim in enumerate(shape) if dim == 1)
grad = np.sum(grad, axis=axis, keepdims=True)
grad = np.squeeze(grad, axis=axis_first)
return grad
def add(left: Tensor, right: Tensor) -> Tensor:
data = left.data + right.data
depends_on = []
if not Tensor.no_grad and left.requires_grad:
| |
<gh_stars>1-10
import numpy as np
import pickle as pkl
import networkx as nx
import scipy.sparse as sp
from scipy.sparse.linalg.eigen.arpack import eigsh
import sys
import tensorflow as tf
import os
import time
import json
from networkx.readwrite import json_graph
from sklearn.metrics import f1_score
import multiprocessing
def parse_index_file(filename):
"""Parse index file."""
index = []
for line in open(filename):
index.append(int(line.strip()))
return index
def sample_mask(idx, l):
"""Create mask."""
mask = np.zeros(l)
mask[idx] = 1
return np.array(mask, dtype=np.bool)
def save_sparse_csr(filename,array):
np.savez(filename,data = array.data ,indices=array.indices,
indptr =array.indptr, shape=array.shape )
def load_sparse_csr(filename):
loader = np.load(filename)
return sp.csr_matrix(( loader['data'], loader['indices'], loader['indptr']),
shape = loader['shape'])
def starfind_4o_nbrs(args):
return find_4o_nbrs(*args)
def find_4o_nbrs(adj, li):
nbrs = []
for i in li:
print(i)
tmp = adj[i]
for ii in np.nonzero(adj[i])[1]:
tmp += adj[ii]
for iii in np.nonzero(adj[ii])[1]:
tmp += adj[iii]
tmp += adj[np.nonzero(adj[iii])[1]].sum(0)
nbrs.append(np.nonzero(tmp)[1])
return nbrs
def load_data(dataset_str, is_sparse):
if dataset_str == "ppi":
return load_graphsage_data('data/ppi/ppi', is_sparse)
"""Load data."""
if dataset_str != 'nell':
names = ['x', 'y', 'tx', 'ty', 'allx', 'ally', 'graph']
objects = []
for i in range(len(names)):
with open("data/ind.{}.{}".format(dataset_str, names[i]), 'rb') as f:
if sys.version_info > (3, 0):
objects.append(pkl.load(f, encoding='latin1'))
else:
objects.append(pkl.load(f))
x, y, tx, ty, allx, ally, graph = tuple(objects)
test_idx_reorder = parse_index_file("data/ind.{}.test.index".format(dataset_str))
test_idx_range = np.sort(test_idx_reorder)
if dataset_str == 'citeseer':
# Fix citeseer dataset (there are some isolated nodes in the graph)
# Find isolated nodes, add them as zero-vecs into the right position
test_idx_range_full = range(min(test_idx_reorder), max(test_idx_reorder)+1)
tx_extended = sp.lil_matrix((len(test_idx_range_full), x.shape[1]))
tx_extended[test_idx_range-min(test_idx_range), :] = tx
tx = tx_extended
ty_extended = np.zeros((len(test_idx_range_full), y.shape[1]))
ty_extended[test_idx_range-min(test_idx_range), :] = ty
ty = ty_extended
features = sp.vstack((allx, tx)).tolil()
features[test_idx_reorder, :] = features[test_idx_range, :]
features = preprocess_features(features, is_sparse)
adj = nx.adjacency_matrix(nx.from_dict_of_lists(graph))
support = preprocess_adj(adj)
labels = np.vstack((ally, ty))
labels[test_idx_reorder, :] = labels[test_idx_range, :]
idx_test = test_idx_range.tolist()
idx_train = range(len(y))
idx_val = range(len(y), len(y)+500)
train_mask = sample_mask(idx_train, labels.shape[0])
val_mask = sample_mask(idx_val, labels.shape[0])
test_mask = sample_mask(idx_test, labels.shape[0])
# y_train = np.zeros(labels.shape)
# y_val = np.zeros(labels.shape)
# y_test = np.zeros(labels.shape)
# y_train = labels[train_mask, :]
# y_val[val_mask, :] = labels[val_mask, :]
# y_test[test_mask, :] = labels[test_mask, :]
else:
names = ['x', 'y', 'tx', 'ty', 'allx', 'ally', 'graph']
objects = []
for i in range(len(names)):
with open("data/savedData/{}.{}".format(dataset_str, names[i]), 'rb') as f:
if sys.version_info > (3, 0):
objects.append(pkl.load(f, encoding='latin1'))
else:
objects.append(pkl.load(f))
x, y, tx, ty, allx, ally, graph = tuple(objects)
test_idx_reorder = parse_index_file("data/savedData/{}.test.index".format(dataset_str))
features = allx.tolil()
adj = nx.adjacency_matrix(nx.from_dict_of_lists(graph))
labels = ally
features = preprocess_features(features, is_sparse)
support = preprocess_adj(adj)
idx_test = test_idx_reorder
idx_train = range(len(y))
idx_val = range(len(y), len(y)+969)
train_mask = sample_mask(idx_train, labels.shape[0])
val_mask = sample_mask(idx_val, labels.shape[0])
test_mask = sample_mask(idx_test, labels.shape[0])
if not os.path.isfile("data/{}.nbrs.npz".format(dataset_str)):
N = adj.shape[0]
pool = multiprocessing.Pool(processes=56)
lis = []
for i in range(32):
li = range(int(N/32)*i, int(N/32)*(i+1))
if i == 31:
li = range(int(N/32)*i, N)
print(li)
lis.append(li)
adjs = [adj] * 32
results = pool.map(starfind_4o_nbrs, zip(adjs, lis))
pool.close()
pool.join()
nbrs = []
for re in results:
nbrs += re
print(len(nbrs))
np.savez("data/{}.nbrs.npz".format(dataset_str), data = nbrs)
else:
loader = np.load("data/{}.nbrs.npz".format(dataset_str))
nbrs = loader['data']
print(adj.shape, len(nbrs))
return nbrs, support, support, features, labels, train_mask, val_mask, test_mask
def sparse_to_tuple(sparse_mx):
"""Convert sparse matrix to tuple representation."""
def to_tuple(mx):
if not sp.isspmatrix_coo(mx):
mx = mx.tocoo()
coords = np.vstack((mx.row, mx.col)).transpose()
values = mx.data
shape = mx.shape
return coords, values, shape
if isinstance(sparse_mx, list):
for i in range(len(sparse_mx)):
sparse_mx[i] = to_tuple(sparse_mx[i])
else:
sparse_mx = to_tuple(sparse_mx)
return sparse_mx
def preprocess_features(features, sparse=True):
"""Row-normalize feature matrix and convert to tuple representation"""
rowsum = np.array(features.sum(1))
r_inv = np.power(rowsum, -1).flatten()
r_inv[np.isinf(r_inv)] = 0.
r_mat_inv = sp.diags(r_inv)
features = r_mat_inv.dot(features)
if sparse:
return sparse_to_tuple(features)
else:
return features.toarray()
def normalize_adj(adj):
"""Symmetrically normalize adjacency matrix."""
adj = sp.coo_matrix(adj)
rowsum = np.array(adj.sum(1))
d_inv_sqrt = np.power(rowsum, -0.5).flatten()
d_inv_sqrt[np.isinf(d_inv_sqrt)] = 0.
d_mat_inv_sqrt = sp.diags(d_inv_sqrt)
return adj.dot(d_mat_inv_sqrt).transpose().dot(d_mat_inv_sqrt).tocoo()
def preprocess_adj(adj):
"""Preprocessing of adjacency matrix for simple GCN model and conversion to tuple representation."""
adj_normalized = normalize_adj(adj + sp.eye(adj.shape[0]))
return sparse_to_tuple(adj_normalized)
def construct_feed_dict(features, support, labels, labels_mask, placeholders, nbrs):
"""Construct feed dictionary."""
feed_dict = dict()
feed_dict.update({placeholders['labels']: labels})
feed_dict.update({placeholders['labels_mask']: labels_mask})
feed_dict.update({placeholders['features']: features})
feed_dict.update({placeholders['support']: support})
feed_dict.update({placeholders['num_features_nonzero']: features[1].shape})
r1 = sample_nodes(nbrs)
feed_dict.update({placeholders['adv_mask1']: r1})
return feed_dict
def chebyshev_polynomials(adj, k):
"""Calculate Chebyshev polynomials up to order k. Return a list of sparse matrices (tuple representation)."""
print("Calculating Chebyshev polynomials up to order {}...".format(k))
adj_normalized = normalize_adj(adj)
laplacian = sp.eye(adj.shape[0]) - adj_normalized
largest_eigval, _ = eigsh(laplacian, 1, which='LM')
scaled_laplacian = (2. / largest_eigval[0]) * laplacian - sp.eye(adj.shape[0])
t_k = list()
t_k.append(sp.eye(adj.shape[0]))
t_k.append(scaled_laplacian)
def chebyshev_recurrence(t_k_minus_one, t_k_minus_two, scaled_lap):
s_lap = sp.csr_matrix(scaled_lap, copy=True)
return 2 * s_lap.dot(t_k_minus_one) - t_k_minus_two
for i in range(2, k+1):
t_k.append(chebyshev_recurrence(t_k[-1], t_k[-2], scaled_laplacian))
return sparse_to_tuple(t_k)
def sample_nodes(nbrs, num=100):
N = len(nbrs)
flag = np.zeros([N])
output = [0] * num
#norm_mtx = np.zeros([N, N])
for i in range(num):
a = np.random.randint(0, N)
while flag[a] == 1:
a = np.random.randint(0, N)
output[i] = a
# for nell to speed up
flag[nbrs[a]] = 1
# tmp = np.zeros([N])
# tmp[nbrs[a]] = 1
#norm_mtx[nbrs[a]] = tmp
# output_ = np.ones([N])
# output_[output] = 0
# output_ = np.nonzero(output_)[0]
return sample_mask(output, N)#, norm_mtx
def kl_divergence_with_logit(q_logit, p_logit, mask=None):
if not mask is None:
q = tf.nn.softmax(q_logit)
mask = tf.cast(mask, dtype=tf.float32)
mask /= tf.reduce_mean(mask)
qlogq = tf.reduce_mean(tf.reduce_sum(q * tf.nn.log_softmax(q_logit), 1) * mask)
qlogp = tf.reduce_mean(tf.reduce_sum(q * tf.nn.log_softmax(p_logit), 1) * mask)
return - qlogp
else:
q = tf.nn.softmax(q_logit)
qlogq = tf.reduce_sum(q * tf.nn.log_softmax(q_logit), 1)
qlogp = tf.reduce_sum(q * tf.nn.log_softmax(p_logit), 1)
return tf.reduce_mean( - qlogp)
def entropy_y_x(logit):
p = tf.nn.softmax(logit)
return -tf.reduce_mean(tf.reduce_sum(p * tf.nn.log_softmax(logit), 1))
def get_normalized_vector(d, sparse=False, indices=None, dense_shape=None):
if sparse:
d /= (1e-12 + tf.reduce_max(tf.abs(d)))
d2 = tf.SparseTensor(indices, tf.square(d), dense_shape)
d = tf.SparseTensor(indices, d, dense_shape)
d /= tf.sqrt(1e-6 + tf.sparse_reduce_sum(d2, 1, keep_dims=True))
return d
else:
d /= (1e-12 + tf.reduce_max(tf.abs(d)))
d /= tf.sqrt(1e-6 + tf.reduce_sum(tf.pow(d, 2.0), 1, keepdims=True))
return d
def get_normalized_matrix(d, sparse=False, indices=None, dense_shape=None):
if not sparse:
return tf.nn.l2_normalize(d, [0,1])
else:
return tf.SparseTensor(indices, tf.nn.l2_normalize(d, [0]), dense_shape)
def load_graphsage_data(prefix, is_sparse, normalize=True, max_degree=-1):
version_info = map(int, nx.__version__.split('.'))
major = version_info[0]
minor = version_info[1]
assert (major <= 1) and (minor <= 11), "networkx major version must be <= 1.11 in order to load graphsage data"
# Save normalized version
if max_degree==-1:
npz_file = prefix + '.npz'
else:
npz_file = '{}_deg{}.npz'.format(prefix, max_degree)
if os.path.exists(npz_file):
start_time = time.time()
print('Found preprocessed dataset {}, loading...'.format(npz_file))
data = np.load(npz_file)
num_data = data['num_data']
feats = data['feats']
labels = data['labels']
train_data = data['train_data']
val_data = data['val_data']
test_data = data['test_data']
train_adj = data['train_adj']
full_adj = data['full_adj']
train_adj_nonormed = sp.csr_matrix((data['train_adj_data'], data['train_adj_indices'], data['train_adj_indptr']), shape=data['train_adj_shape'])
print('Finished in {} seconds.'.format(time.time() - start_time))
else:
print('Loading data...')
start_time = time.time()
G_data = json.load(open(prefix + "-G.json"))
G = json_graph.node_link_graph(G_data)
feats = np.load(prefix + "-feats.npy").astype(np.float32)
id_map = json.load(open(prefix + "-id_map.json"))
if id_map.keys()[0].isdigit():
conversion = lambda n: int(n)
else:
conversion = lambda n: n
id_map = {conversion(k):int(v) for k,v in id_map.iteritems()}
walks = []
class_map = json.load(open(prefix + "-class_map.json"))
if isinstance(class_map.values()[0], list):
lab_conversion = lambda n : n
else:
lab_conversion = lambda n : int(n)
class_map = {conversion(k): lab_conversion(v) for k,v in class_map.iteritems()}
## Remove all nodes that do not have val/test annotations
## (necessary because of networkx weirdness with the Reddit data)
broken_count = 0
to_remove = []
for node in G.nodes():
if not id_map.has_key(node):
#if not G.node[node].has_key('val') or not G.node[node].has_key('test'):
to_remove.append(node)
broken_count += 1
for node in to_remove:
G.remove_node(node)
print("Removed {:d} nodes that lacked proper annotations due to networkx versioning issues".format(broken_count))
# Construct adjacency matrix
print("Loaded data ({} seconds).. now preprocessing..".format(time.time()-start_time))
start_time = time.time()
edges = []
for edge in G.edges():
if id_map.has_key(edge[0]) and id_map.has_key(edge[1]):
edges.append((id_map[edge[0]], id_map[edge[1]]))
print('{} edges'.format(len(edges)))
num_data = len(id_map)
if max_degree != -1:
print('Subsampling edges...')
edges = subsample_edges(edges, num_data, max_degree)
val_data = np.array([id_map[n] for n in G.nodes()
if G.node[n]['val']], dtype=np.int32)
test_data = np.array([id_map[n] for n in G.nodes()
if G.node[n]['test']], dtype=np.int32)
is_train = np.ones((num_data), dtype=np.bool)
is_train[val_data] = False
is_train[test_data] = False
train_data = np.array([n for n in range(num_data) if is_train[n]], dtype=np.int32)
val_data = sample_mask(val_data, num_data)
test_data = sample_mask(test_data, num_data)
train_data = sample_mask(train_data, num_data)
train_edges = [(e[0], e[1]) for e in edges if is_train[e[0]] and is_train[e[1]]]
edges = np.array(edges, dtype=np.int32)
train_edges = np.array(train_edges, dtype=np.int32)
# Process labels
if isinstance(class_map.values()[0], list):
num_classes = len(class_map.values()[0])
labels = np.zeros((num_data, num_classes), dtype=np.float32)
for k in class_map.keys():
labels[id_map[k], :] = np.array(class_map[k])
else:
num_classes = len(set(class_map.values()))
labels = np.zeros((num_data, num_classes), dtype=np.float32)
for k in class_map.keys():
labels[id_map[k], class_map[k]] = | |
<filename>projects/DensePose-Teacher/densepose/engine/trainer.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import imp
import logging
import os
from collections import OrderedDict
from typing import List, Optional, Union
import weakref
from detectron2.engine.defaults import default_writers
import torch
from torch import nn
from fvcore.nn.precise_bn import get_bn_modules
from detectron2.checkpoint import DetectionCheckpointer
from detectron2.config import CfgNode
from detectron2.engine import DefaultTrainer
from detectron2.evaluation import (
DatasetEvaluator,
DatasetEvaluators,
inference_on_dataset,
print_csv_format,
verify_results,
)
from detectron2.solver.build import get_default_optimizer_params, maybe_add_gradient_clipping
from detectron2.solver import build_lr_scheduler
from detectron2.utils import comm
from detectron2.utils.events import EventWriter, get_event_storage
from detectron2.utils.logger import setup_logger
from detectron2.engine.train_loop import TrainerBase
from detectron2.engine import create_ddp_model, hooks
from detectron2.modeling import build_model
from densepose import DensePoseDatasetMapperTTA, DensePoseGeneralizedRCNNWithTTA, load_from_cfg
from densepose.data import (
DatasetMapper,
build_combined_loader,
build_detection_test_loader,
build_detection_train_loader,
build_inference_based_loaders,
has_inference_based_loaders,
)
from densepose.evaluation.d2_evaluator_adapter import Detectron2COCOEvaluatorAdapter
from densepose.evaluation.evaluator import DensePoseCOCOEvaluator, build_densepose_evaluator_storage
from densepose.modeling.cse import Embedder
from .train_loop import SimpleTrainer
from .mean_teacher import MeanTeacher
class SampleCountingLoader:
def __init__(self, loader):
self.loader = loader
def __iter__(self):
it = iter(self.loader)
storage = get_event_storage()
while True:
try:
batch = next(it)
num_inst_per_dataset = {}
for data in batch:
dataset_name = data["dataset"]
if dataset_name not in num_inst_per_dataset:
num_inst_per_dataset[dataset_name] = 0
num_inst = len(data["instances"])
num_inst_per_dataset[dataset_name] += num_inst
for dataset_name in num_inst_per_dataset:
storage.put_scalar(f"batch/{dataset_name}", num_inst_per_dataset[dataset_name])
yield batch
except StopIteration:
break
class SampleCountMetricPrinter(EventWriter):
def __init__(self):
self.logger = logging.getLogger(__name__)
def write(self):
storage = get_event_storage()
batch_stats_strs = []
for key, buf in storage.histories().items():
if key.startswith("batch/"):
batch_stats_strs.append(f"{key} {buf.avg(20)}")
self.logger.info(", ".join(batch_stats_strs))
class Trainer(TrainerBase):
def __init__(self, cfg):
super().__init__()
logger = logging.getLogger("detectron2")
if not logger.isEnabledFor(logging.INFO): # setup_logger is not called for d2
setup_logger()
cfg = DefaultTrainer.auto_scale_workers(cfg, comm.get_world_size())
# Assume these objects must be constructed in this order.
student_model = self.build_model(cfg)
teacher_model = self.build_model(cfg)
optimizer = self.build_optimizer(cfg, student_model)
data_loader = self.build_train_loader(cfg)
student_model = create_ddp_model(student_model, broadcast_buffers=False)
# teacher_model = create_ddp_model(teacher_model, broadcast_buffers=False)
self._trainer = SimpleTrainer({"teacher": teacher_model, "student": student_model}, data_loader, optimizer)
self.scheduler = self.build_lr_scheduler(cfg, optimizer)
self.student_checkpointer = DetectionCheckpointer(
# Assume you want to save checkpoints together with logs/statistics
student_model,
cfg.OUTPUT_DIR,
trainer=weakref.proxy(self),
)
self.teacher_checkpointer = DetectionCheckpointer(
teacher_model,
cfg.MODEL.SEMI.TEACHER_OUTPUT
)
if comm.is_main_process():
if not os.path.exists(cfg.MODEL.SEMI.TEACHER_OUTPUT):
os.mkdir(cfg.MODEL.SEMI.TEACHER_OUTPUT)
self.start_iter = 0
self.max_iter = cfg.SOLVER.MAX_ITER
self.cfg = cfg
self.register_hooks(self.build_hooks())
def resume_or_load(self, resume=True):
"""
If `resume==True` and `cfg.OUTPUT_DIR` contains the last checkpoint (defined by
a `last_checkpoint` file), resume from the file. Resuming means loading all
available states (eg. optimizer and scheduler) and update iteration counter
from the checkpoint. ``cfg.MODEL.WEIGHTS`` will not be used.
Otherwise, this is considered as an independent training. The method will load model
weights from the file `cfg.MODEL.WEIGHTS` (but will not load other states) and start
from iteration 0.
Args:
resume (bool): whether to do resume or not
"""
teacher_weights = self.cfg.MODEL.SEMI.TEACHER_WEIGHTS
if teacher_weights is None or teacher_weights == "":
teacher_weights = self.cfg.MODEL.WEIGHTS
self.teacher_checkpointer.resume_or_load(teacher_weights, resume=resume)
self.student_checkpointer.resume_or_load(self.cfg.MODEL.WEIGHTS, resume=resume)
if resume and self.student_checkpointer.has_checkpoint():
# The checkpoint stores the training iteration that just finished, thus we start
# at the next iteration
self.start_iter = self.iter + 1
def build_hooks(self):
"""
Build a list of default hooks, including timing, evaluation,
checkpointing, lr scheduling, precise BN, writing events.
Returns:
list[HookBase]:
"""
cfg = self.cfg.clone()
cfg.defrost()
cfg.DATALOADER.NUM_WORKERS = 0 # save some memory and time for PreciseBN
ret = [
hooks.IterationTimer(),
hooks.LRScheduler(),
hooks.PreciseBN(
# Run at the same freq as (but before) evaluation.
cfg.TEST.EVAL_PERIOD,
self.student_model,
# Build a new data loader to not affect training
self.build_train_loader(cfg),
cfg.TEST.PRECISE_BN.NUM_ITER,
)
if cfg.TEST.PRECISE_BN.ENABLED and get_bn_modules(self.student_model)
else None,
]
# Do PreciseBN before checkpointer, because it updates the model and need to
# be saved by checkpointer.
# This is not always the best: if checkpointing has a different frequency,
# some checkpoints may have more precise statistics than others.
if comm.is_main_process():
ret.append(hooks.PeriodicCheckpointer(self.teacher_checkpointer, cfg.SOLVER.CHECKPOINT_PERIOD))
ret.append(hooks.PeriodicCheckpointer(self.student_checkpointer, cfg.SOLVER.CHECKPOINT_PERIOD))
ret.append(MeanTeacher())
def test_and_save_results():
if cfg.MODEL.SEMI.INFERENCE_ON == "student":
self._last_eval_results = self.test(self.cfg, self.student_model)
elif cfg.MODEL.SEMI.INFERENCE_ON == "teacher":
self._last_eval_results = self.test(self.cfg, self.teacher_model)
return self._last_eval_results
# Do evaluation after checkpointer, because then if it fails,
# we can use the saved checkpoint to debug.
ret.append(hooks.EvalHook(cfg.TEST.EVAL_PERIOD, test_and_save_results))
if comm.is_main_process():
# Here the default print/log frequency of each writer is used.
# run writers in the end, so that evaluation metrics are written
ret.append(hooks.PeriodicWriter(self.build_writers(), period=20))
return ret
def train(self):
"""
Run training.
Returns:
OrderedDict of results, if evaluation is enabled. Otherwise None.
"""
super().train(self.start_iter, self.max_iter)
if len(self.cfg.TEST.EXPECTED_RESULTS) and comm.is_main_process():
assert hasattr(
self, "_last_eval_results"
), "No evaluation results obtained during training!"
verify_results(self.cfg, self._last_eval_results)
return self._last_eval_results
def run_step(self):
self._trainer.iter = self.iter
self._trainer.run_step()
def state_dict(self):
ret = super().state_dict()
ret["_trainer"] = self._trainer.state_dict()
return ret
def load_state_dict(self, state_dict):
super().load_state_dict(state_dict)
self._trainer.load_state_dict(state_dict["_trainer"])
@classmethod
def build_model(cls, cfg):
"""
Returns:
torch.nn.Module:
It now calls :func:`detectron2.modeling.build_model`.
Overwrite it if you'd like a different model.
"""
model = build_model(cfg)
logger = logging.getLogger(__name__)
logger.info("Model:\n{}".format(model))
return model
@classmethod
def build_lr_scheduler(cls, cfg, optimizer):
"""
It now calls :func:`detectron2.solver.build_lr_scheduler`.
Overwrite it if you'd like a different scheduler.
"""
return build_lr_scheduler(cfg, optimizer)
@staticmethod
def auto_scale_workers(cfg, num_workers: int):
"""
When the config is defined for certain number of workers (according to
``cfg.SOLVER.REFERENCE_WORLD_SIZE``) that's different from the number of
workers currently in use, returns a new cfg where the total batch size
is scaled so that the per-GPU batch size stays the same as the
original ``IMS_PER_BATCH // REFERENCE_WORLD_SIZE``.
Other config options are also scaled accordingly:
* training steps and warmup steps are scaled inverse proportionally.
* learning rate are scaled proportionally, following :paper:`ImageNet in 1h`.
For example, with the original config like the following:
.. code-block:: yaml
IMS_PER_BATCH: 16
BASE_LR: 0.1
REFERENCE_WORLD_SIZE: 8
MAX_ITER: 5000
STEPS: (4000,)
CHECKPOINT_PERIOD: 1000
When this config is used on 16 GPUs instead of the reference number 8,
calling this method will return a new config with:
.. code-block:: yaml
IMS_PER_BATCH: 32
BASE_LR: 0.2
REFERENCE_WORLD_SIZE: 16
MAX_ITER: 2500
STEPS: (2000,)
CHECKPOINT_PERIOD: 500
Note that both the original config and this new config can be trained on 16 GPUs.
It's up to user whether to enable this feature (by setting ``REFERENCE_WORLD_SIZE``).
Returns:
CfgNode: a new config. Same as original if ``cfg.SOLVER.REFERENCE_WORLD_SIZE==0``.
"""
old_world_size = cfg.SOLVER.REFERENCE_WORLD_SIZE
if old_world_size == 0 or old_world_size == num_workers:
return cfg
cfg = cfg.clone()
frozen = cfg.is_frozen()
cfg.defrost()
assert (
cfg.SOLVER.IMS_PER_BATCH % old_world_size == 0
), "Invalid REFERENCE_WORLD_SIZE in config!"
scale = num_workers / old_world_size
bs = cfg.SOLVER.IMS_PER_BATCH = int(round(cfg.SOLVER.IMS_PER_BATCH * scale))
lr = cfg.SOLVER.BASE_LR = cfg.SOLVER.BASE_LR * scale
max_iter = cfg.SOLVER.MAX_ITER = int(round(cfg.SOLVER.MAX_ITER / scale))
warmup_iter = cfg.SOLVER.WARMUP_ITERS = int(round(cfg.SOLVER.WARMUP_ITERS / scale))
cfg.SOLVER.STEPS = tuple(int(round(s / scale)) for s in cfg.SOLVER.STEPS)
cfg.TEST.EVAL_PERIOD = int(round(cfg.TEST.EVAL_PERIOD / scale))
cfg.SOLVER.CHECKPOINT_PERIOD = int(round(cfg.SOLVER.CHECKPOINT_PERIOD / scale))
cfg.SOLVER.REFERENCE_WORLD_SIZE = num_workers # maintain invariant
logger = logging.getLogger(__name__)
logger.info(
f"Auto-scaling the config to batch_size={bs}, learning_rate={lr}, "
f"max_iter={max_iter}, warmup={warmup_iter}."
)
if frozen:
cfg.freeze()
return cfg
@classmethod
def extract_embedder_from_model(cls, model: nn.Module) -> Optional[Embedder]:
if isinstance(model, nn.parallel.DistributedDataParallel):
model = model.module
if hasattr(model, "roi_heads") and hasattr(model.roi_heads, "embedder"):
return model.roi_heads.embedder
return None
# TODO: the only reason to copy the base class code here is to pass the embedder from
# the model to the evaluator; that should be refactored to avoid unnecessary copy-pasting
@classmethod
def test(
cls,
cfg: CfgNode,
model: nn.Module,
evaluators: Optional[Union[DatasetEvaluator, List[DatasetEvaluator]]] = None,
):
"""
Args:
cfg (CfgNode):
model (nn.Module):
evaluators (DatasetEvaluator, list[DatasetEvaluator] or None): if None, will call
:meth:`build_evaluator`. Otherwise, must have the same length as
``cfg.DATASETS.TEST``.
Returns:
dict: a dict of result metrics
"""
logger = logging.getLogger(__name__)
if isinstance(evaluators, DatasetEvaluator):
evaluators = [evaluators]
if evaluators is not None:
assert len(cfg.DATASETS.TEST) == len(evaluators), "{} != {}".format(
len(cfg.DATASETS.TEST), len(evaluators)
)
results = OrderedDict()
for idx, dataset_name in enumerate(cfg.DATASETS.TEST):
data_loader = cls.build_test_loader(cfg, dataset_name)
# When evaluators are passed in as arguments,
# implicitly assume that evaluators can be created before data_loader.
if evaluators is not None:
evaluator = evaluators[idx]
else:
try:
embedder = cls.extract_embedder_from_model(model)
evaluator = cls.build_evaluator(cfg, dataset_name, embedder=embedder)
except NotImplementedError:
logger.warn(
"No evaluator found. Use `DefaultTrainer.test(evaluators=)`, "
"or implement its `build_evaluator` method."
)
results[dataset_name] = {}
continue
if cfg.DENSEPOSE_EVALUATION.DISTRIBUTED_INFERENCE or comm.is_main_process():
results_i = inference_on_dataset(model, data_loader, evaluator)
else:
results_i = {}
results[dataset_name] = results_i
if comm.is_main_process():
assert isinstance(
results_i, dict
), "Evaluator must return a dict on the main process. Got {} instead.".format(
results_i
)
logger.info("Evaluation results for {} in csv format:".format(dataset_name))
print_csv_format(results_i)
if len(results) == 1:
results = list(results.values())[0]
return results
@classmethod
def build_evaluator(
cls,
cfg: CfgNode,
dataset_name: str,
output_folder: Optional[str] = None,
embedder: Optional[Embedder] = None,
) -> DatasetEvaluators:
| |
[]
for ((kk,bb),y1) in buildfftup(uu,vv,ff,xx,xxp,xxrr,xxrrp):
for qq in parter(uu,kk,bb,y1):
for (yy,pp) in roller(qq):
for (jj,p) in zip(yy,pp):
if max(p) + 1 < len(p):
ii = list(zip(cart(uu,jj),p))
ll0.append(ii)
ll = []
for (b,ii) in enumerate(ll0):
w = VarPair((VarPair((VarInt(f),VarInt(l))),VarInt(b+1)))
ww = sset([ValInt(u) for (_,u) in ii])
tt = trans(unit([sunion(ss,ssgl(w,ValInt(u))) for (ss,u) in ii]),sgl(w))
ll.append((tt,(w,ww)))
ll1 = []
for (tt,(w,ww)) in ll:
if all([len(ww) != len(ww1) or und(tt) != und(tt1) or ttpp(tt) != ttpp(tt1) for (tt1,(w1,ww1)) in ll if w > w1]):
ll1.append((tt,(w,ww)))
if len(ll1) > 0:
hh = qqff(sset([tt for (tt,_) in ll1]))
uu1 = uunion(uu,lluu([(w,ww) for (_,(w,ww)) in ll1]))
ffr = [tttr(uu1,tt) for (tt,_) in ll1]
xx1 = apply(xx,ffr)
xxp1 = hrhx(xx1)
xxrr1 = apply(xxrr,ffr)
xxrrp1 = hrhx(xxrr1)
gg = funion(ff,hh)
mm1 = buildffdervar(uu1,vv,gg,xx1,xxp1,xxrr1,xxrrp1)
if len(mm) == 0 or maxr(mm1) > maxr(mm) + repaRounding:
(ffr,ll0,ll,ll1) = (None,None,None,None)
return layer(vv,uu1,gg,mm1,xx1,xxp1,xxrr1,xxrrp1,f,l+1)
return (uu,ff,mm)
if wmax < 0 or lmax < 0 or xmax < 0 or omax < 0 or bmax < 0 or mmax < 1 or umax < 0 or pmax < 0:
return None
if not (sset(hhvvr(xx)).issubset(sset(uvars(uu))) and hhvvr(xx) == hhvvr(xxrr) and hhvvr(xx) == apvvr(xxp) and hhvvr(xx) == apvvr(xxrrp) and vv.issubset(sset(hhvvr(xx)))):
return None
return layer(vv,uu,fudEmpty(),[],xx,xxp,xxrr,xxrrp,f,1)
# parametersSystemsHistoryRepasDecomperMaxRollByMExcludedSelfHighestFmaxRepa ::
# Integer -> Integer -> Integer -> Integer -> Integer -> Integer -> Integer -> Integer -> Integer ->
# Integer -> Integer ->
# System -> Set.Set Variable -> HistoryRepa ->
# Maybe (System, DecompFud)
def parametersSystemsHistoryRepasDecomperMaxRollByMExcludedSelfHighestFmaxRepa(wmax,lmax,xmax,omax,bmax,mmax,umax,pmax,fmax,mult,seed,uu,vv,aa):
repaRounding = 1e-6
dom = relationsDomain
def maxd(mm):
if len(mm) > 0:
return list(sset([(b,a) for (a,b) in mm]))[-1]
return (0,sset())
def tsgl(r):
return sdict([(r,sdict())])
uvars = systemsSetVar
trim = histogramsTrim
aall = histogramsList
def red(aa,vv):
return setVarsHistogramsReduce(vv,aa)
def unit(ss):
return setStatesHistogramUnit(sset([ss]))
aahh = histogramsHistory
hhhr = systemsHistoriesHistoryRepa
def vars(hr):
return sset(historyRepasVectorVar(hr))
size = historyRepasSize
rraa = systemsHistogramRepasHistogram
hrhx = historyRepasRed
def hrhrred(hr,vv):
return setVarsHistoryRepasHistoryRepaReduced(vv,hr)
def hrred(hr,vv):
return setVarsHistoryRepasReduce(1,vv,hr)
def reduce(uu,ww,hh):
return rraa(uu,hrred(hh,ww))
def select(uu,ss,hh):
return historyRepasHistoryRepasHistoryRepaSelection_u(hhhr(uu,aahh(unit(ss))),hh)
hrconcat = vectorHistoryRepasConcat_u
hrshuffle = historyRepasShuffle_u
ffqq = fudsSetTransform
fder = fudsDerived
tttr = systemsTransformsTransformRepa_u
def apply(uu,ff,hh):
return historyRepasListTransformRepasApply(hh,[tttr(uu,tt) for tt in ffqq(ff)])
depends = fudsSetVarsDepends
zzdf = treePairStateFudsDecompFud
def zztrim(df):
pp = []
for ll in treesPaths(df):
(_,ff) = ll[-1]
if len(ff) == 0:
pp.append(ll[:-1])
else:
pp.append(ll)
return pathsTree(pp)
def layerer(uu,xx,f):
z = size(xx)
xxp = hrhx(xx)
xxrr = hrconcat([hrshuffle(xx,seed+i*z) for i in range(1,mult+1)])
xxrrp = hrhx(xxrr)
return parametersSystemsLayererMaxRollByMExcludedSelfHighestRepa(wmax,lmax,xmax,omax,bmax,mmax,umax,pmax,uu,vv,xx,xxp,xxrr,xxrrp,f)
def decomp(uu,zz,qq,f):
if len(zz) == 0:
(uur,ffr,nnr) = layerer(uu,aa,f)
if len(ffr) == 0 or len(nnr) == 0:
return (uu, decompFudEmpty())
(ar,kkr) = maxd(nnr)
if ar <= repaRounding:
return (uu, decompFudEmpty())
ffr1 = depends(ffr,kkr)
aar = apply(uur,ffr1,aa)
aa1 = trim(reduce(uur,fder(ffr1),aar))
zzr = tsgl((stateEmpty(),ffr1))
qq[(stateEmpty(),ffr1)] = (aar,aa1)
(ffr,nnr,kkr) = (None,None,None)
return decomp(uur,zzr,qq,f+1)
if fmax > 0 and f > fmax:
return (uu,zzdf(zztrim(zz)))
mm = []
for (nn,yy) in treesPlaces(zz):
(rr,ff) = nn[-1]
if len(ff) > 0:
(bb,bb1) = qq[(rr,ff)]
tt = dom(treesRoots(yy))
for (ss,a) in aall(red(bb1,fder(ff))):
if a > 0 and ss not in tt:
mm.append((a,(nn,ss,bb)))
if len(mm) == 0:
return (uu,zzdf(zztrim(zz)))
mm.sort(key = lambda x: x[0])
(_,(nn,ss,bb)) = mm[-1]
cc = hrhrred(select(uu,ss,bb),vars(aa))
(uuc,ffc,nnc) = layerer(uu,cc,f)
(ac,kkc) = maxd(nnc)
ffc1 = fudEmpty()
if ac > repaRounding:
ffc1 = depends(ffc,kkc)
ccc = apply(uuc,ffc1,cc)
cc1 = trim(reduce(uuc,fder(ffc1),ccc))
qq[(ss,ffc1)] = (ccc,cc1)
zzc = pathsTree(treesPaths(zz) + [nn+[(ss,ffc1)]])
(mm,cc,ffc,nnc,kkc) = (None,None,None,None,None)
return decomp(uuc,zzc,qq,f+1)
if wmax < 0 or lmax < 0 or xmax < 0 or omax < 0 or bmax < 0 or mmax < 1 or umax < 0 or pmax < 0:
return None
if size(aa) == 0 or mult < 1:
return None
if not (vars(aa).issubset(uvars(uu)) and vv.issubset(vars(aa))):
return None
return decomp(uu,emptyTree(),sdict(),1)
# systemsDecompFudsHistoryRepasAlignmentContentShuffleSummation_u ::
# Integer -> Integer -> System -> DecompFud -> HistoryRepa -> (Double,Double)
def systemsDecompFudsHistoryRepasAlignmentContentShuffleSummation_u(mult,seed,uu,df,aa):
vol = systemsSetVarsVolume_u
vars = histogramsSetVar
size = histogramsSize
def resize(z,aa):
if z > 0:
return histogramsResize(z,aa)
else:
return histogramEmpty()
algn = histogramsAlignment
araa = systemsHistogramRepasHistogram
def hrred(hr,vv):
return setVarsHistoryRepasReduce(1,vv,hr)
fder = fudsDerived
apply = systemsDecompFudsHistoryRepasMultiplyWithShuffle
qq = apply(mult,seed,uu,df,aa)
a = 0.0
ad = 0.0
for ((_,ff),(hr,hrxx)) in qq.items():
aa = araa(uu,hrred(hr,fder(ff)))
u = vol(uu,vars(aa))
m = len(vars(aa))
bb = resize(size(aa),araa(uu,hrred(hrxx,fder(ff))))
b = algn(aa) - algn(bb)
a += b
ad += b/(u**(1.0/m))
return (a,ad)
# systemsDecompFudsHistoryRepasTreeAlignmentContentShuffleSummation_u ::
# Integer -> Integer -> System -> DecompFud -> HistoryRepa -> Map (State,Fud) (Int,(Double,Double))
def systemsDecompFudsHistoryRepasTreeAlignmentContentShuffleSummation_u(mult,seed,uu,df,aa):
vol = systemsSetVarsVolume_u
vars = histogramsSetVar
size = histogramsSize
def resize(z,aa):
if z > 0:
return histogramsResize(z,aa)
else:
return histogramEmpty()
algn = histogramsAlignment
araa = systemsHistogramRepasHistogram
hrsize = historyRepasSize
def hrred(hr,vv):
return setVarsHistoryRepasReduce(1,vv,hr)
fder = fudsDerived
apply = systemsDecompFudsHistoryRepasMultiplyWithShuffle
qq = apply(mult,seed,uu,df,aa)
qq1 = sdict()
for ((ss,ff),(hr,hrxx)) in qq.items():
aa = araa(uu,hrred(hr,fder(ff)))
u = vol(uu,vars(aa))
m = len(vars(aa))
bb = resize(size(aa),araa(uu,hrred(hrxx,fder(ff))))
b = algn(aa) - algn(bb)
qq1[(ss,ff)] = (hrsize(hr),(b,b/(u**(1.0/m))))
return qq1
# parametersBuilderConditionalVarsRepa ::
# Integer -> Integer -> Integer -> Set.Set Variable -> HistoryRepa ->
# Maybe (Map.Map (Set.Set Variable) Double)
def parametersBuilderConditionalVarsRepa(kmax,omax,qmax,ll,aa):
def sgl(x):
return sset([x])
def bot(amax,mm):
return sdict([(x,y) for (y,x) in list(sset([(b,a) for (a,b) in mm.items()]))[:amax]])
vars = historyRepasSetVariable
def red(aa,vv):
return setVarsHistoryRepasCountApproxs_u(vv,aa)
if kmax < 0 or omax < 0 or qmax < 0:
return None
z = historyRepasSize(aa)
def ent(xx):
t = 0
for i in xx:
a = i/z
t += a * log(a)
return - t
def buildc(qq,nn):
pp = sset([kk|sgl(w) for (kk,e) in qq.items() if e > 0 for w in vvk-kk])
mm = bot(omax,sdict([(jj,ent(red(aa,ll|jj))-ent(red(aa,jj))) for jj in pp if len(jj) <= kmax]))
if len(mm) > 0:
nn1 = nn.copy()
nn1.update(mm)
return buildc(mm,nn1)
return nn
vvk = vars(aa) - ll
rr = bot(omax,sdict([(sgl(w),ent(red(aa,ll|sgl(w)))-ent(red(aa,sgl(w)))) for w in vvk]))
return bot(qmax,buildc(rr,rr))
# parametersBuilderConditionalVarsRepa_1 ::
# Integer -> Integer -> Integer -> Set.Set Variable -> HistoryRepa ->
# Maybe (Map.Map (Set.Set Variable) Double)
def parametersBuilderConditionalVarsRepa_1(kmax,omax,qmax,ll,aa):
def sgl(x):
return sset([x])
def bot(amax,mm):
return sdict([(x,y) for (y,x) in list(sset([(b,a) for (a,b) in mm.items()]))[:amax]])
vars = historyRepasSetVariable
def red(aa,vv):
return setVarsHistoryRepasCountApproxs(vv,aa)
if kmax < 0 or omax < 0 or qmax < 0:
return None
z = historyRepasSize(aa)
def ent(xx):
t = 0
for i in xx:
a = i/z
t += a * log(a)
return - t
def buildc(qq,nn):
pp = sset([kk|sgl(w) for (kk,e) in qq.items() if e > 0 for w in vvk-kk])
mm = bot(omax,sdict([(jj,ent(red(aa,ll|jj))-ent(red(aa,jj))) for jj in pp if len(jj) <= kmax]))
if len(mm) > 0:
nn1 = nn.copy()
nn1.update(mm)
return buildc(mm,nn1)
return nn
vvk = vars(aa) - ll
rr = bot(omax,sdict([(sgl(w),ent(red(aa,ll|sgl(w)))-ent(red(aa,sgl(w)))) for w in vvk]))
return bot(qmax,buildc(rr,rr))
# parametersSystemsHistoryRepasDecomperConditionalFmaxRepa ::
# Integer -> Integer -> Integer -> System -> Set.Set Variable -> HistoryRepa ->
# Maybe (System, DecompFud)
def parametersSystemsHistoryRepasDecomperConditionalFmaxRepa(kmax,omax,fmax,uu,ll,aa):
rounding = 1e-14
dom = relationsDomain
def tsgl(r):
return sdict([(r,sdict())])
uunion = pairSystemsUnion
cart = systemsSetVarsSetStateCartesian_u
llss = listsState
sunion = pairStatesUnionLeft
trim = histogramsTrim
aall = histogramsList
def red(aa,vv):
return setVarsHistogramsReduce(vv,aa)
unit = setStatesHistogramUnit
mul = pairHistogramsMultiply
ent = histogramsEntropy
aahh = histogramsHistory
hhhr = systemsHistoriesHistoryRepa
def vars(hr):
return sset(historyRepasVectorVar(hr))
rraa = systemsHistogramRepasHistogram
def hrhrred(hr,vv):
return setVarsHistoryRepasHistoryRepaReduced(vv,hr)
def hrred(hr,vv):
return setVarsHistoryRepasReduce(1,vv,hr)
def reduce(uu,ww,hh):
return rraa(uu,hrred(hh,ww))
def select(uu,ss,hh):
return historyRepasHistoryRepasHistoryRepaSelection_u(hhhr(uu,aahh(unit(sset([ss])))),hh)
trans = histogramsSetVarsTransform_u
tttr = systemsTransformsTransformRepa_u
fsys = fudsSystemImplied
qqff = setTransformsFud_u
ffqq = fudsSetTransform
fder = fudsDerived
def apply(uu,ff,hh):
return historyRepasListTransformRepasApply(hh,[tttr(uu,tt) for tt in ffqq(ff)])
zzdf = treePairStateFudsDecompFud
def vvff(uu,vv,f):
v = VarPair((VarPair((VarInt(f),VarInt(1))),VarInt(1)))
qq = sset([sunion(ss,llss([(v,ValInt(i+1))])) for (i,ss) in enumerate(cart(uu,vv))])
return qqff(sset([trans(unit(qq),sset([v]))]))
def lenter(ll,aa):
return list(parametersBuilderConditionalVarsRepa(kmax,omax,1,ll,aa).items())
vv = vars(aa)
def decomp(uu,zz,qq,f):
if len(zz) == 0:
nnr = lenter(ll,aa)
if len(nnr) == 0:
return (uu, decompFudEmpty())
[(kkr,_)] = nnr
ffr = vvff(uu,kkr,f)
uur = uunion(uu,fsys(ffr))
aar = apply(uur,ffr,aa)
aa1 = trim(reduce(uur,fder(ffr)|ll,aar))
zzr = tsgl((stateEmpty(),ffr))
qq[(stateEmpty(),ffr)] = (aar,aa1)
(ffr,nnr,kkr) = (None,None,None)
return decomp(uur,zzr,qq,f+1)
if fmax > 0 and f > fmax:
return (uu,zzdf(zz))
mm = []
for (nn,yy) in treesPlaces(zz):
(rr,ff) = nn[-1]
(bb,bb1) = qq[(rr,ff)]
tt = dom(treesRoots(yy))
for (ss,a) in aall(red(bb1,fder(ff))):
if a > 0 and ss not in tt:
e = a * ent(red(mul(bb1,unit(sset([ss]))),ll))
if e > rounding:
mm.append((e,(nn,ss,bb)))
if len(mm) == 0:
return (uu,zzdf(zz))
mm.sort(key = lambda x: x[0])
(_,(nn,ss,bb)) = mm[-1]
cc = hrhrred(select(uu,ss,bb),vv)
nnc = lenter(ll,cc)
[(kkc,_)] = | |
of enable_validation. When enabled, if both disable_local_accounts and
enable_local_accounts are specified, raise a MutuallyExclusiveArgumentError.
:return: bool
"""
# read the original value passed by the command
disable_local_accounts = self.raw_param.get("disable_local_accounts")
# In create mode, try to read the property value corresponding to the parameter from the `mc` object.
if self.decorator_mode == DecoratorMode.CREATE:
if (
self.mc and
hasattr(self.mc, "disable_local_accounts") and # backward compatibility
self.mc.disable_local_accounts is not None
):
disable_local_accounts = self.mc.disable_local_accounts
# this parameter does not need dynamic completion
# validation
if enable_validation:
if self.decorator_mode == DecoratorMode.UPDATE:
if disable_local_accounts and self._get_enable_local_accounts(enable_validation=False):
raise MutuallyExclusiveArgumentError(
"Cannot specify --disable-local-accounts and "
"--enable-local-accounts at the same time."
)
return disable_local_accounts
def get_disable_local_accounts(self) -> bool:
"""Obtain the value of disable_local_accounts.
This function will verify the parameter by default. If both disable_local_accounts and enable_local_accounts
are specified, raise a MutuallyExclusiveArgumentError.
:return: bool
"""
return self._get_disable_local_accounts(enable_validation=True)
def _get_enable_local_accounts(self, enable_validation: bool = False) -> bool:
"""Internal function to obtain the value of enable_local_accounts.
This function supports the option of enable_validation. When enabled, if both disable_local_accounts and
enable_local_accounts are specified, raise a MutuallyExclusiveArgumentError.
:return: bool
"""
# read the original value passed by the command
enable_local_accounts = self.raw_param.get("enable_local_accounts")
# We do not support this option in create mode, therefore we do not read the value from `mc`.
# this parameter does not need dynamic completion
# validation
if enable_validation:
if enable_local_accounts and self._get_disable_local_accounts(enable_validation=False):
raise MutuallyExclusiveArgumentError(
"Cannot specify --disable-local-accounts and "
"--enable-local-accounts at the same time."
)
return enable_local_accounts
def get_enable_local_accounts(self) -> bool:
"""Obtain the value of enable_local_accounts.
This function will verify the parameter by default. If both disable_local_accounts and enable_local_accounts
are specified, raise a MutuallyExclusiveArgumentError.
:return: bool
"""
return self._get_enable_local_accounts(enable_validation=True)
def get_edge_zone(self) -> Union[str, None]:
"""Obtain the value of edge_zone.
:return: string or None
"""
# read the original value passed by the command
edge_zone = self.raw_param.get("edge_zone")
# try to read the property value corresponding to the parameter from the `mc` object
# Backward Compatibility: We also support api version v2020.11.01 in profile 2020-09-01-hybrid and there is
# no such attribute.
if (
self.mc and
hasattr(self.mc, "extended_location") and
self.mc.extended_location and
self.mc.extended_location.name is not None
):
edge_zone = self.mc.extended_location.name
# this parameter does not need dynamic completion
# this parameter does not need validation
return edge_zone
def get_node_resource_group(self) -> Union[str, None]:
"""Obtain the value of node_resource_group.
:return: string or None
"""
# read the original value passed by the command
node_resource_group = self.raw_param.get("node_resource_group")
# try to read the property value corresponding to the parameter from the `mc` object
if self.mc and self.mc.node_resource_group is not None:
node_resource_group = self.mc.node_resource_group
# this parameter does not need dynamic completion
# this parameter does not need validation
return node_resource_group
def get_yes(self) -> bool:
"""Obtain the value of yes.
Note: yes will not be decorated into the `mc` object.
:return: bool
"""
# read the original value passed by the command
yes = self.raw_param.get("yes")
# this parameter does not need dynamic completion
# this parameter does not need validation
return yes
def get_no_wait(self) -> bool:
"""Obtain the value of no_wait.
Note: no_wait will not be decorated into the `mc` object.
:return: bool
"""
# read the original value passed by the command
no_wait = self.raw_param.get("no_wait")
# this parameter does not need dynamic completion
# this parameter does not need validation
return no_wait
def get_aks_custom_headers(self) -> Dict[str, str]:
"""Obtain the value of aks_custom_headers.
Note: aks_custom_headers will not be decorated into the `mc` object.
This function will normalize the parameter by default. It will call "extract_comma_separated_string" to extract
comma-separated key value pairs from the string.
:return: dictionary
"""
# read the original value passed by the command
aks_custom_headers = self.raw_param.get("aks_custom_headers")
# normalize user-provided header, extract key-value pairs with comma as separator
# used to enable (preview) features through custom header field or AKSHTTPCustomFeatures (internal only)
aks_custom_headers = extract_comma_separated_string(
aks_custom_headers,
enable_strip=True,
extract_kv=True,
default_value={},
allow_appending_values_to_same_key=True,
)
# this parameter does not need validation
return aks_custom_headers
class AKSManagedClusterCreateDecorator(BaseAKSManagedClusterDecorator):
def __init__(
self, cmd: AzCliCommand, client: ContainerServiceClient, raw_parameters: Dict, resource_type: ResourceType
):
"""Internal controller of aks_create.
Break down the all-in-one aks_create function into several relatively independent functions (some of them have
a certain order dependency) that only focus on a specific profile or process a specific piece of logic.
In addition, an overall control function is provided. By calling the aforementioned independent functions one
by one, a complete ManagedCluster object is gradually decorated and finally requests are sent to create a
cluster.
"""
super().__init__(cmd, client)
self.__raw_parameters = raw_parameters
self.resource_type = resource_type
self.init_models()
self.init_context()
self.agentpool_decorator_mode = AgentPoolDecoratorMode.MANAGED_CLUSTER
self.init_agentpool_decorator_context()
def init_models(self) -> None:
"""Initialize an AKSManagedClusterModels object to store the models.
:return: None
"""
self.models = AKSManagedClusterModels(self.cmd, self.resource_type)
def init_context(self) -> None:
"""Initialize an AKSManagedClusterContext object to store the context in the process of assemble the
ManagedCluster object.
:return: None
"""
self.context = AKSManagedClusterContext(
self.cmd, AKSManagedClusterParamDict(self.__raw_parameters), self.models, DecoratorMode.CREATE
)
def init_agentpool_decorator_context(self) -> None:
"""Initialize an AKSAgentPoolAddDecorator object to assemble the AgentPool profile.
:return: None
"""
self.agentpool_decorator = AKSAgentPoolAddDecorator(
self.cmd, self.client, self.__raw_parameters, self.resource_type, self.agentpool_decorator_mode
)
self.agentpool_context = self.agentpool_decorator.context
self.context.attach_agentpool_context(self.agentpool_context)
def _ensure_mc(self, mc: ManagedCluster) -> None:
"""Internal function to ensure that the incoming `mc` object is valid and the same as the attached
`mc` object in the context.
If the incoming `mc` is not valid or is inconsistent with the `mc` in the context, raise a CLIInternalError.
:return: None
"""
if not isinstance(mc, self.models.ManagedCluster):
raise CLIInternalError(
"Unexpected mc object with type '{}'.".format(type(mc))
)
if self.context.mc != mc:
raise CLIInternalError(
"Inconsistent state detected. The incoming `mc` "
"is not the same as the `mc` in the context."
)
def _remove_defaults_in_mc(self, mc: ManagedCluster) -> ManagedCluster:
"""Internal function to remove values from properties with default values of the `mc` object.
Removing default values is to prevent getters from mistakenly overwriting user provided values with default
values in the object.
:return: the ManagedCluster object
"""
self._ensure_mc(mc)
defaults_in_mc = {}
for attr_name, attr_value in vars(mc).items():
if not attr_name.startswith("_") and attr_name != "location" and attr_value is not None:
defaults_in_mc[attr_name] = attr_value
setattr(mc, attr_name, None)
self.context.set_intermediate("defaults_in_mc", defaults_in_mc, overwrite_exists=True)
return mc
def _restore_defaults_in_mc(self, mc: ManagedCluster) -> ManagedCluster:
"""Internal function to restore values of properties with default values of the `mc` object.
Restoring default values is to keep the content of the request sent by cli consistent with that before the
refactoring.
:return: the ManagedCluster object
"""
self._ensure_mc(mc)
defaults_in_mc = self.context.get_intermediate("defaults_in_mc", {})
for key, value in defaults_in_mc.items():
if getattr(mc, key, None) is None:
setattr(mc, key, value)
return mc
def set_up_defender(self, mc: ManagedCluster) -> ManagedCluster:
"""Set up defender for the ManagedCluster object.
:return: the ManagedCluster object
"""
self._ensure_mc(mc)
defender = self.context.get_defender_config()
if defender:
if mc.security_profile is None:
mc.security_profile = self.models.ManagedClusterSecurityProfile()
mc.security_profile.azure_defender = defender
return mc
def init_mc(self) -> ManagedCluster:
"""Initialize a ManagedCluster object with required parameter location and attach it to internal context.
When location is not assigned, function "get_rg_location" will be called to get the location of the provided
resource group, which internally used ResourceManagementClient to send the request.
:return: the ManagedCluster object
"""
# Initialize a ManagedCluster object with mandatory parameter location.
mc = self.models.ManagedCluster(
location=self.context.get_location(),
)
# attach mc to AKSContext
self.context.attach_mc(mc)
return mc
def set_up_agentpool_profile(self, mc: ManagedCluster) -> ManagedCluster:
"""Set up agent pool profiles for the ManagedCluster object.
:return: the ManagedCluster object
"""
self._ensure_mc(mc)
agentpool_profile = self.agentpool_decorator.construct_agentpool_profile_default()
mc.agent_pool_profiles = [agentpool_profile]
return mc
def set_up_mc_properties(self, mc: ManagedCluster) -> ManagedCluster:
"""Set up misc direct properties for the ManagedCluster object.
:return: the ManagedCluster object
"""
self._ensure_mc(mc)
mc.tags = self.context.get_tags()
mc.kubernetes_version = self.context.get_kubernetes_version()
mc.dns_prefix = self.context.get_dns_name_prefix()
mc.disk_encryption_set_id = self.context.get_node_osdisk_diskencryptionset_id()
mc.disable_local_accounts = self.context.get_disable_local_accounts()
mc.enable_rbac = not self.context.get_disable_rbac()
return mc
def set_up_linux_profile(self, mc: ManagedCluster) -> ManagedCluster:
"""Set up linux profile for the ManagedCluster object.
Linux profile is just used for SSH access to VMs, so it will be omitted if --no-ssh-key option was specified.
:return: the ManagedCluster object
"""
self._ensure_mc(mc)
ssh_key_value, no_ssh_key = self.context.get_ssh_key_value_and_no_ssh_key()
if not no_ssh_key:
ssh_config = self.models.ContainerServiceSshConfiguration(
public_keys=[
self.models.ContainerServiceSshPublicKey(
key_data=ssh_key_value
)
]
)
linux_profile = self.models.ContainerServiceLinuxProfile(
admin_username=self.context.get_admin_username(), ssh=ssh_config
)
| |
"""
This module implements basic kinds of jobs for VASP runs.
"""
import logging
import math
import os
import shutil
import subprocess
import numpy as np
from monty.os.path import which
from monty.serialization import dumpfn, loadfn
from monty.shutil import decompress_dir
from pymatgen.core.structure import Structure
from pymatgen.io.vasp.inputs import Incar, Kpoints, Poscar, VaspInput
from pymatgen.io.vasp.outputs import Outcar, Vasprun
from custodian.custodian import SENTRY_DSN, Job
from custodian.utils import backup
from custodian.vasp.handlers import VASP_BACKUP_FILES
from custodian.vasp.interpreter import VaspModder
logger = logging.getLogger(__name__)
VASP_INPUT_FILES = {"INCAR", "POSCAR", "POTCAR", "KPOINTS"}
VASP_OUTPUT_FILES = [
"DOSCAR",
"INCAR",
"KPOINTS",
"POSCAR",
"PROCAR",
"vasprun.xml",
"CHGCAR",
"CHG",
"EIGENVAL",
"OSZICAR",
"WAVECAR",
"CONTCAR",
"IBZKPT",
"OUTCAR",
]
VASP_NEB_INPUT_FILES = {"INCAR", "POTCAR", "KPOINTS"}
VASP_NEB_OUTPUT_FILES = ["INCAR", "KPOINTS", "POTCAR", "vasprun.xml"]
VASP_NEB_OUTPUT_SUB_FILES = [
"CHG",
"CHGCAR",
"CONTCAR",
"DOSCAR",
"EIGENVAL",
"IBZKPT",
"PCDAT",
"POSCAR",
"REPORT",
"PROCAR",
"OSZICAR",
"OUTCAR",
"WAVECAR",
"XDATCAR",
]
class VaspJob(Job):
"""
A basic vasp job. Just runs whatever is in the directory. But conceivably
can be a complex processing of inputs etc. with initialization.
"""
def __init__(
self,
vasp_cmd,
output_file="vasp.out",
stderr_file="std_err.txt",
suffix="",
final=True,
backup=True,
auto_npar=False,
auto_gamma=True,
settings_override=None,
gamma_vasp_cmd=None,
copy_magmom=False,
auto_continue=False,
):
"""
This constructor is necessarily complex due to the need for
flexibility. For standard kinds of runs, it's often better to use one
of the static constructors. The defaults are usually fine too.
Args:
vasp_cmd (str): Command to run vasp as a list of args. For example,
if you are using mpirun, it can be something like
["mpirun", "pvasp.5.2.11"]
output_file (str): Name of file to direct standard out to.
Defaults to "vasp.out".
stderr_file (str): Name of file to direct standard error to.
Defaults to "std_err.txt".
suffix (str): A suffix to be appended to the final output. E.g.,
to rename all VASP output from say vasp.out to
vasp.out.relax1, provide ".relax1" as the suffix.
final (bool): Indicating whether this is the final vasp job in a
series. Defaults to True.
backup (bool): Whether to backup the initial input files. If True,
the INCAR, KPOINTS, POSCAR and POTCAR will be copied with a
".orig" appended. Defaults to True.
auto_npar (bool): Whether to automatically tune NPAR to be sqrt(
number of cores) as recommended by VASP for DFT calculations.
Generally, this results in significant speedups. Defaults to
True. Set to False for HF, GW and RPA calculations.
auto_gamma (bool): Whether to automatically check if run is a
Gamma 1x1x1 run, and whether a Gamma optimized version of
VASP exists with ".gamma" appended to the name of the VASP
executable (typical setup in many systems). If so, run the
gamma optimized version of VASP instead of regular VASP. You
can also specify the gamma vasp command using the
gamma_vasp_cmd argument if the command is named differently.
settings_override ([dict]): An ansible style list of dict to
override changes. For example, to set ISTART=1 for subsequent
runs and to copy the CONTCAR to the POSCAR, you will provide::
[{"dict": "INCAR", "action": {"_set": {"ISTART": 1}}},
{"file": "CONTCAR",
"action": {"_file_copy": {"dest": "POSCAR"}}}]
gamma_vasp_cmd (str): Command for gamma vasp version when
auto_gamma is True. Should follow the list style of
subprocess. Defaults to None, which means ".gamma" is added
to the last argument of the standard vasp_cmd.
copy_magmom (bool): Whether to copy the final magmom from the
OUTCAR to the next INCAR. Useful for multi-relaxation runs
where the CHGCAR and WAVECAR are sometimes deleted (due to
changes in fft grid, etc.). Only applies to non-final runs.
auto_continue (bool): Whether to automatically continue a run
if a STOPCAR is present. This is very useful if using the
wall-time handler which will write a read-only STOPCAR to
prevent VASP from deleting it once it finishes
"""
self.vasp_cmd = vasp_cmd
self.output_file = output_file
self.stderr_file = stderr_file
self.final = final
self.backup = backup
self.suffix = suffix
self.settings_override = settings_override
self.auto_npar = auto_npar
self.auto_gamma = auto_gamma
self.gamma_vasp_cmd = gamma_vasp_cmd
self.copy_magmom = copy_magmom
self.auto_continue = auto_continue
if SENTRY_DSN:
# if using Sentry logging, add specific VASP executable to scope
from sentry_sdk import configure_scope
with configure_scope() as scope:
try:
if isinstance(vasp_cmd, str):
vasp_path = which(vasp_cmd.split(" ")[-1])
elif isinstance(vasp_cmd, list):
vasp_path = which(vasp_cmd[-1])
scope.set_tag("vasp_path", vasp_path)
scope.set_tag("vasp_cmd", vasp_cmd)
except Exception:
logger.error(f"Failed to detect VASP path: {vasp_cmd}", exc_info=True)
scope.set_tag("vasp_cmd", vasp_cmd)
def setup(self):
"""
Performs initial setup for VaspJob, including overriding any settings
and backing up.
"""
decompress_dir(".")
if self.backup:
for f in VASP_INPUT_FILES:
try:
shutil.copy(f, f"{f}.orig")
except FileNotFoundError: # handle the situation when there is no KPOINTS file
if f == "KPOINTS":
pass
if self.auto_npar:
try:
incar = Incar.from_file("INCAR")
# Only optimized NPAR for non-HF and non-RPA calculations.
if not (incar.get("LHFCALC") or incar.get("LRPA") or incar.get("LEPSILON")):
if incar.get("IBRION") in [5, 6, 7, 8]:
# NPAR should not be set for Hessian matrix
# calculations, whether in DFPT or otherwise.
del incar["NPAR"]
else:
import multiprocessing
# try sge environment variable first
# (since multiprocessing counts cores on the current
# machine only)
ncores = os.environ.get("NSLOTS") or multiprocessing.cpu_count()
ncores = int(ncores)
for npar in range(int(math.sqrt(ncores)), ncores):
if ncores % npar == 0:
incar["NPAR"] = npar
break
incar.write_file("INCAR")
except Exception:
pass
if self.auto_continue:
if os.path.exists("continue.json"):
actions = loadfn("continue.json").get("actions")
logger.info(f"Continuing previous VaspJob. Actions: {actions}")
backup(VASP_BACKUP_FILES, prefix="prev_run")
VaspModder().apply_actions(actions)
else:
# Default functionality is to copy CONTCAR to POSCAR and set
# ISTART to 1 in the INCAR, but other actions can be specified
if self.auto_continue is True:
actions = [
{
"file": "CONTCAR",
"action": {"_file_copy": {"dest": "POSCAR"}},
},
{"dict": "INCAR", "action": {"_set": {"ISTART": 1}}},
]
else:
actions = self.auto_continue
dumpfn({"actions": actions}, "continue.json")
if self.settings_override is not None:
VaspModder().apply_actions(self.settings_override)
def run(self):
"""
Perform the actual VASP run.
Returns:
(subprocess.Popen) Used for monitoring.
"""
cmd = list(self.vasp_cmd)
if self.auto_gamma:
vi = VaspInput.from_directory(".")
kpts = vi["KPOINTS"]
if kpts is not None:
if kpts.style == Kpoints.supported_modes.Gamma and tuple(kpts.kpts[0]) == (1, 1, 1):
if self.gamma_vasp_cmd is not None and which(self.gamma_vasp_cmd[-1]):
cmd = self.gamma_vasp_cmd
elif which(cmd[-1] + ".gamma"):
cmd[-1] += ".gamma"
logger.info(f"Running {' '.join(cmd)}")
with open(self.output_file, "w") as f_std, open(self.stderr_file, "w", buffering=1) as f_err:
# use line buffering for stderr
return subprocess.Popen(cmd, stdout=f_std, stderr=f_err) # pylint: disable=R1732
def postprocess(self):
"""
Postprocessing includes renaming and gzipping where necessary.
Also copies the magmom to the incar if necessary
"""
for f in VASP_OUTPUT_FILES + [self.output_file]:
if os.path.exists(f):
if self.final and self.suffix != "":
shutil.move(f, f"{f}{self.suffix}")
elif self.suffix != "":
shutil.copy(f, f"{f}{self.suffix}")
if self.copy_magmom and not self.final:
try:
outcar = Outcar("OUTCAR")
magmom = [m["tot"] for m in outcar.magnetization]
incar = Incar.from_file("INCAR")
incar["MAGMOM"] = magmom
incar.write_file("INCAR")
except Exception:
logger.error("MAGMOM copy from OUTCAR to INCAR failed")
# Remove continuation so if a subsequent job is run in
# the same directory, will not restart this job.
if os.path.exists("continue.json"):
os.remove("continue.json")
@classmethod
def double_relaxation_run(
cls,
vasp_cmd,
auto_npar=True,
ediffg=-0.05,
half_kpts_first_relax=False,
auto_continue=False,
):
"""
Returns a list of two jobs corresponding to an AFLOW style double
relaxation run.
Args:
vasp_cmd (str): Command to run vasp as a list of args. For example,
if you are using mpirun, it can be something like
["mpirun", "pvasp.5.2.11"]
auto_npar (bool): Whether to automatically tune NPAR to be sqrt(
number of cores) as recommended by VASP for DFT calculations.
Generally, this results in significant speedups. Defaults to
True. Set to False for HF, GW and RPA calculations.
ediffg (float): Force convergence criteria for subsequent runs (
ignored for the initial run.)
half_kpts_first_relax (bool): Whether to halve the kpoint grid
for the first relaxation. Speeds up difficult convergence
considerably. Defaults to False.
Returns:
List of two jobs corresponding to an AFLOW style run.
"""
incar_update = {"ISTART": 1}
if ediffg:
incar_update["EDIFFG"] = ediffg
settings_overide_1 = None
settings_overide_2 = [
{"dict": "INCAR", "action": {"_set": incar_update}},
{"file": "CONTCAR", "action": {"_file_copy": {"dest": "POSCAR"}}},
]
if half_kpts_first_relax and os.path.exists("KPOINTS") and os.path.exists("POSCAR"):
kpts = Kpoints.from_file("KPOINTS")
orig_kpts_dict = kpts.as_dict()
# lattice vectors with length < 8 will get >1 KPOINT
kpts.kpts = np.round(np.maximum(np.array(kpts.kpts) / 2, 1)).astype(int).tolist()
low_kpts_dict = kpts.as_dict()
settings_overide_1 = [{"dict": "KPOINTS", "action": {"_set": low_kpts_dict}}]
settings_overide_2.append({"dict": "KPOINTS", "action": {"_set": orig_kpts_dict}})
return [
VaspJob(
vasp_cmd,
final=False,
suffix=".relax1",
auto_npar=auto_npar,
auto_continue=auto_continue,
settings_override=settings_overide_1,
),
VaspJob(
vasp_cmd,
final=True,
backup=False,
suffix=".relax2",
auto_npar=auto_npar,
auto_continue=auto_continue,
settings_override=settings_overide_2,
),
]
@classmethod
def metagga_opt_run(
cls,
vasp_cmd,
auto_npar=True,
ediffg=-0.05,
half_kpts_first_relax=False,
auto_continue=False,
):
"""
Returns a list of thres jobs to | |
0],
# [0, 1, 0, 0, 0],
# [0, 1, 0, 0, 0],
# [0, 1, 0, 0, 0],
# [0, 1, 0, 0, 0]])
#
# is_finite = ad.helper.statistics.is_finite_object(img, is_continuous_image=True)
# assert is_finite == False
#
# is_finite = ad.helper.statistics.is_finite_object(img, is_continuous_image=False)
# assert is_finite == False
#
#
# #########################################################
# img = np.array([[0, 0, 0, 0, 0],
# [0, 1, 1, 0, 0],
# [0, 1, 1, 0, 0],
# [0, 1, 1, 0, 0],
# [0, 0, 0, 0, 0]])
#
# is_finite = ad.helper.statistics.is_finite_object(img, is_continuous_image=True)
# assert is_finite == True
#
# is_finite = ad.helper.statistics.is_finite_object(img, is_continuous_image=False)
# assert is_finite == True
#
#
# #########################################################
# img = np.array([[0, 0, 0, 0, 0],
# [0, 1, 0, 1, 0],
# [0, 1, 0, 0, 0],
# [0, 1, 1, 0, 0],
# [0, 0, 0, 0, 0]])
#
# is_finite = ad.helper.statistics.is_finite_object(img, is_continuous_image=True)
# assert is_finite == True
#
# is_finite = ad.helper.statistics.is_finite_object(img, is_continuous_image=False)
# assert is_finite == True
#
# #########################################################
# img = np.array([[0, 0, 0, 0, 0],
# [0, 1, 0, 1, 0],
# [1, 1, 1, 1, 1],
# [0, 1, 1, 0, 0],
# [0, 0, 0, 0, 0]])
#
# is_finite = ad.helper.statistics.is_finite_object(img, is_continuous_image=True)
# assert is_finite == False
#
# is_finite = ad.helper.statistics.is_finite_object(img, is_continuous_image=False)
# assert is_finite == False
#
# #########################################################
# img = np.array([[0, 0, 0, 0, 0],
# [0, 1, 0, 1, 0],
# [1, 1, 1, 1, 0],
# [0, 1, 1, 0, 0],
# [0, 0, 0, 0, 0]])
#
# is_finite = ad.helper.statistics.is_finite_object(img, is_continuous_image=True)
# assert is_finite == True
#
# is_finite = ad.helper.statistics.is_finite_object(img, is_continuous_image=False)
# assert is_finite == False
#
# #########################################################
# img = np.array([[0, 0, 0, 0, 0],
# [1, 1, 0, 1, 1],
# [0, 1, 1, 1, 0],
# [0, 1, 1, 0, 0],
# [0, 0, 0, 0, 0]])
#
# is_finite = ad.helper.statistics.is_finite_object(img, is_continuous_image=True)
# assert is_finite == False
#
# is_finite = ad.helper.statistics.is_finite_object(img, is_continuous_image=False)
# assert is_finite == False
#
# #########################################################
# img = np.array([[0, 1, 0, 1, 0],
# [1, 1, 0, 1, 1],
# [0, 0, 0, 0, 0],
# [1, 1, 0, 1, 1],
# [0, 1, 0, 1, 0]])
#
# is_finite = ad.helper.statistics.is_finite_object(img, is_continuous_image=True)
# assert is_finite == True
#
# is_finite = ad.helper.statistics.is_finite_object(img, is_continuous_image=False)
# assert is_finite == False
#
#
# #########################################################
# img = np.array([[0, 0, 0, 0, 0],
# [1, 0, 0, 0, 1],
# [0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0]])
#
# is_finite = ad.helper.statistics.is_finite_object(img, is_continuous_image=True)
# assert is_finite == True
#
# is_finite = ad.helper.statistics.is_finite_object(img, is_continuous_image=False)
# assert is_finite == False
def test_calc_active_binary_segments():
################################################################
################################################################
# CONTINUOUS
################################################################
img = np.array([[0, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 1, 0, 1, 0],
[0, 0, 0, 0, 0]])
exp = np.array([[0, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 1, 0, 1, 0],
[0, 0, 0, 0, 0]])
result_seg, _ = ad.helper.statistics.calc_active_binary_segments(img, r=2)
assert np.all(result_seg == exp)
################################################################
img = np.array([[0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0],
[0, 1, 1, 1, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0]])
exp = np.array([[0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 1, 0, 2, 0],
[0, 1, 0, 1, 0, 2, 0],
[0, 1, 1, 1, 0, 2, 0],
[0, 0, 0, 0, 0, 0, 0]])
result_seg, _ = ad.helper.statistics.calc_active_binary_segments(img, r=1)
assert np.all(result_seg == exp)
################################################################
img = np.array([[0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 1, 0, 1, 0],
[1, 1, 0, 1, 0, 1, 1],
[0, 1, 1, 1, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0]])
exp = np.array([[0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 1, 0, 1, 0],
[1, 1, 0, 1, 0, 1, 1],
[0, 1, 1, 1, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0]])
result_seg, _ = ad.helper.statistics.calc_active_binary_segments(img, r=1)
assert np.all(result_seg == exp)
################################################################
img = np.array([[0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0],
[1, 0, 0, 0, 0, 1, 0],
[0, 1, 1, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0]])
exp = np.array([[0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0],
[1, 0, 0, 0, 0, 1, 0],
[0, 1, 1, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0]])
result_seg, _ = ad.helper.statistics.calc_active_binary_segments(img, r=2)
assert np.all(result_seg == exp)
################################################################
img = np.array([[0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 1],
[0, 1, 1, 0, 0, 1],
[0, 0, 0, 0, 0, 0]])
exp = np.array([[0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 2],
[2, 0, 0, 0, 0, 2],
[0, 3, 3, 0, 0, 2],
[0, 0, 0, 0, 0, 0]])
result_seg, _ = ad.helper.statistics.calc_active_binary_segments(img, r=1)
assert np.all(result_seg == exp)
################################################################
img = np.array([[0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 1],
[0, 1, 1, 0, 0, 1],
[0, 0, 0, 0, 0, 0]])
exp = np.array([[0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 1],
[0, 1, 1, 0, 0, 1],
[0, 0, 0, 0, 0, 0]])
result_seg, _ = ad.helper.statistics.calc_active_binary_segments(img, r=2)
assert np.all(result_seg == exp)
################################################################
################################################################
# NON CONTINUOUS
################################################################
img = np.array([[0, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 1, 0, 1, 0],
[0, 0, 0, 0, 0]])
exp = np.array([[0, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 1, 0, 1, 0],
[0, 0, 0, 0, 0]])
result_seg, _ = ad.helper.statistics.calc_active_binary_segments(img, r=2, is_continuous_image=False)
assert np.all(result_seg == exp)
################################################################
img = np.array([[0, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 0, 0, 0],
[1, 1, 0, 0, 1],
[0, 0, 0, 0, 0]])
exp = np.array([[0, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 0, 0, 0],
[1, 1, 0, 0, 2],
[0, 0, 0, 0, 0]])
result_seg, _ = ad.helper.statistics.calc_active_binary_segments(img, r=2, is_continuous_image=False)
assert np.all(result_seg == exp)
################################################################
img = np.array([[0, 1, 0, 0, 0],
[1, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[1, 1, 0, 0, 1],
[0, 0, 0, 0, 0]])
exp = np.array([[0, 1, 0, 0, 0],
[1, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[1, 1, 0, 0, 2],
[0, 0, 0, 0, 0]])
result_seg, _ = ad.helper.statistics.calc_active_binary_segments(img, r=2, is_continuous_image=False)
assert np.all(result_seg == exp)
# def test_BinareImageSegmenter():
#
# ################################################################
# img = np.array([[0, 0, 0, 0, 0],
# [0, 1, 0, 0, 0],
# [0, 0, 0, 0, 0],
# [0, 1, 0, 1, 0],
# [0, 0, 0, 0, 0]])
#
# exp = np.array([[0, 0, 0, 0, 0],
# [0, 1, 0, 0, 0],
# [0, 0, 0, 0, 0],
# [0, 1, 0, 1, 0],
# [0, 0, 0, 0, 0]])
#
# segmenter = ad.helper.statistics.BinaryImageSegmenter(r=2)
#
# result_seg = segmenter.calc(img)
#
# assert np.all(result_seg == exp)
#
# ################################################################
# img = np.array([[0, 0, 0, 0, 0, 0, 0],
# [0, 1, 0, 1, 0, 1, 0],
# [0, 1, 0, 1, 0, 1, 0],
# [0, 1, 1, 1, 0, 1, 0],
# [0, 0, 0, 0, 0, 0, 0]])
#
# exp = np.array([[0, 0, 0, 0, 0, 0, 0],
# [0, 1, 0, 1, 0, 2, 0],
# [0, 1, 0, 1, 0, 2, 0],
# [0, 1, 1, 1, 0, 2, 0],
# [0, 0, 0, 0, 0, 0, 0]])
#
# segmenter = ad.helper.statistics.BinaryImageSegmenter(r=1)
#
# result_seg = segmenter.calc(img)
#
# assert np.all(result_seg == exp)
#
#
# ################################################################
# img = np.array([[0, 0, 0, 0, 0, 0, 0],
# [0, 1, 0, 1, 0, 1, 0],
# [1, 1, 0, 1, 0, 1, 1],
# [0, 1, 1, 1, 0, 1, 0],
# [0, 0, 0, 0, 0, 0, 0]])
#
# exp = np.array([[0, 0, 0, 0, 0, 0, 0],
# [0, 1, 0, 1, 0, 1, 0],
# [1, 1, 0, 1, 0, 1, 1],
# [0, 1, 1, 1, 0, 1, 0],
# [0, 0, 0, 0, 0, 0, 0]])
#
# segmenter = ad.helper.statistics.BinaryImageSegmenter(r=1)
#
# result_seg = segmenter.calc(img)
#
# assert np.all(result_seg == exp)
#
#
# ################################################################
# img = np.array([[0, 1, 0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0, 1, 0],
# [1, 0, 0, 0, 0, 1, 0],
# [0, 1, 1, 0, 0, | |
<reponame>calemen/permafrostanalytics<filename>ideas/eternal_sunshine/christian/resnet.py
#!/usr/bin/env python3
# Copyright 2019 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
This file has been copied and modified from another project of mine in
order to be used for the purpose of this hackathon.
This module implements the class of Resnet networks described in section 4.2 of
the following paper:
"Deep Residual Learning for Image Recognition", He et al., 2015
https://arxiv.org/abs/1512.03385
"""
import numpy as np
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from batchnorm_layer import BatchNormLayer
class ResNet(nn.Module):
"""A resnet with :math:`6n+2` layers with :math:`3n` residual blocks,
consisting of two layers each.
Args:
in_shape: The shape of an input sample.
.. note::
We assume the Tensorflow format, where the last entry
denotes the number of channels.
num_outs: The number of output neurons.
verbose: Allow printing of general information about the generated
network (such as number of weights).
n: The network will consist of :math:`6n+2` layers. In the
paper :math:`n` has been chosen to be 3, 5, 7, 9 or 18.
no_weights: If set to ``True``, no trainable parameters will be
constructed, i.e., weights are assumed to be produced ad-hoc
by a hypernetwork and passed to the :meth:`forward` method.
Note, this also affects the affine parameters of the
batchnorm layer. I.e., if set to ``True``, then the argument
``affine`` of :class:`utils.batchnorm_layer.BatchNormLayer`
will be set to ``False`` and we expect the batchnorm parameters
to be passed to the :meth:`forward`.
init_weights (optional): This option is for convinience reasons.
The option expects a list of parameter values that are used to
initialize the network weights. As such, it provides a
convinient way of initializing a network with a weight draw
produced by the hypernetwork.
use_batch_norm: Whether batch normalization should used. It will be
applied after all convolutional layers (before the activation).
bn_track_stats: If batch normalization is used, then this option
determines whether running statistics are tracked in these
layers or not (see argument ``track_running_stats`` of class
:class:`utils.batchnorm_layer.BatchNormLayer`).
If ``False``, then batch statistics are utilized even during
evaluation. If ``True``, then running stats are tracked. When
using this network in a continual learning scenario with
different tasks then the running statistics are expected to be
maintained externally. The argument ``stats_id`` of the method
:meth:`utils.batchnorm_layer.BatchNormLayer.forward` can be
provided using the argument ``condition`` of method
:meth:`forward`.
Example:
To maintain the running stats, one can simply iterate over
all batch norm layers and checkpoint the current running
stats (e.g., after learning a task when applying a Continual
Learning scenario).
.. code:: python
for bn_layer in net.batchnorm_layers:
bn_layer.checkpoint_stats()
distill_bn_stats: If ``True``, then the shapes of the batchnorm
statistics will be added to the attribute
:attr:`mnets.mnet_interface.MainNetInterface.\
hyper_shapes_distilled` and the current statistics will be returned by the
method :meth:`distillation_targets`.
Note, this attribute may only be ``True`` if ``bn_track_stats``
is ``True``.
"""
def __init__(
self,
in_shape=[536, 356, 3],
num_outs=1,
verbose=True,
n=5,
no_weights=False,
init_weights=None,
use_batch_norm=True,
bn_track_stats=True,
distill_bn_stats=False,
):
nn.Module.__init__(self)
self._num_outs = num_outs
self._in_shape = in_shape
self._n = n
self._use_context_mod = False
assert init_weights is None or not no_weights
self._no_weights = no_weights
assert not use_batch_norm or (not distill_bn_stats or bn_track_stats)
self._use_batch_norm = use_batch_norm
self._bn_track_stats = bn_track_stats
self._distill_bn_stats = distill_bn_stats and use_batch_norm
self._kernel_size = [3, 3]
self._filter_sizes = [16, 16, 32, 64]
self._has_bias = True
self._has_fc_out = True
# We need to make sure that the last 2 entries of `weights` correspond
# to the weight matrix and bias vector of the last layer.
self._mask_fc_out = True
# We don't use any output non-linearity.
self._has_linear_out = True
self._param_shapes = []
self._weights = None if no_weights else nn.ParameterList()
self._hyper_shapes_learned = None if not no_weights else []
###########################
### Print infos to user ###
###########################
# Compute the total number of weights in this network and display
# them to the user.
# Note, this complicated calculation is not necessary as we can simply
# count the number of weights afterwards. But it's an additional sanity
# check for us.
fs = self._filter_sizes
num_weights = (
np.prod(self._kernel_size)
* (
in_shape[2] * fs[0]
+ np.sum(
[fs[i] * fs[i + 1] + (2 * n - 1) * fs[i + 1] ** 2 for i in range(3)]
)
)
+ (fs[0] + 2 * n * np.sum([fs[i] for i in range(1, 4)]))
+ (fs[-1] * num_outs + num_outs)
)
if use_batch_norm:
# The gamma and beta parameters of a batch norm layer are
# learned as well.
num_weights += 2 * (fs[0] + 2 * n * np.sum([fs[i] for i in range(1, 4)]))
if verbose:
print(
"A ResNet with %d layers and %d weights is created."
% (6 * n + 2, num_weights)
)
################################################
### Define and initialize batch norm weights ###
################################################
self._batchnorm_layers = nn.ModuleList() if use_batch_norm else None
if use_batch_norm:
if distill_bn_stats:
self._hyper_shapes_distilled = []
bn_ind = 0
for i, s in enumerate(self._filter_sizes):
if i == 0:
num = 1
else:
num = 2 * n
for j in range(num):
bn_layer = BatchNormLayer(
s, affine=not no_weights, track_running_stats=bn_track_stats
)
self._batchnorm_layers.append(bn_layer)
if distill_bn_stats:
self._hyper_shapes_distilled.extend(
[list(p.shape) for p in bn_layer.get_stats(0)]
)
if not no_weights and init_weights is not None:
assert len(bn_layer.weights) == 2
for ii in range(2):
assert np.all(
np.equal(
list(init_weights[bn_ind].shape),
list(bn_layer.weights[ii].shape),
)
)
bn_layer.weights[ii].data = init_weights[bn_ind]
bn_ind += 1
if init_weights is not None:
init_weights = init_weights[bn_ind:]
# Note, method `_compute_hyper_shapes` doesn't take context-mod into
# consideration.
self._param_shapes.extend(self._compute_hyper_shapes(no_weights=True))
assert num_weights == np.sum([np.prod(l) for l in self._param_shapes])
self._layer_weight_tensors = nn.ParameterList()
self._layer_bias_vectors = nn.ParameterList()
if no_weights:
if self._hyper_shapes_learned is None:
self._hyper_shapes_learned = self._compute_hyper_shapes()
else:
# Context-mod weights are already included.
self._hyper_shapes_learned.extend(self._compute_hyper_shapes())
self._is_properly_setup()
return
if use_batch_norm:
for bn_layer in self._batchnorm_layers:
self._weights.extend(bn_layer.weights)
############################################
### Define and initialize layer weights ###
###########################################
### Does not include context-mod or batchnorm weights.
# First layer.
self._layer_weight_tensors.append(
nn.Parameter(
torch.Tensor(
self._filter_sizes[0], self._in_shape[2], *self._kernel_size
),
requires_grad=True,
)
)
self._layer_bias_vectors.append(
nn.Parameter(torch.Tensor(self._filter_sizes[0]), requires_grad=True)
)
# Each block consists of 2n layers.
for i in range(1, len(self._filter_sizes)):
in_filters = self._filter_sizes[i - 1]
out_filters = self._filter_sizes[i]
for _ in range(2 * n):
self._layer_weight_tensors.append(
nn.Parameter(
torch.Tensor(out_filters, in_filters, *self._kernel_size),
requires_grad=True,
)
)
self._layer_bias_vectors.append(
nn.Parameter(torch.Tensor(out_filters), requires_grad=True)
)
# Note, that the first layer in this block has potentially a
# different number of input filters.
in_filters = out_filters
# After the average pooling, there is one more dense layer.
self._layer_weight_tensors.append(
nn.Parameter(
torch.Tensor(num_outs, self._filter_sizes[-1]), requires_grad=True
)
)
self._layer_bias_vectors.append(
nn.Parameter(torch.Tensor(num_outs), requires_grad=True)
)
# We add the weights interleaved, such that there are always consecutive
# weight tensor and bias vector per layer. This fulfils the requirements
# of attribute `mask_fc_out`.
for i in range(len(self._layer_weight_tensors)):
self._weights.append(self._layer_weight_tensors[i])
self._weights.append(self._layer_bias_vectors[i])
### Initialize weights.
if init_weights is not None:
num_layers = 6 * n + 2
assert len(init_weights) == 2 * num_layers
offset = 0
if use_batch_norm:
offset = 2 * (6 * n + 1)
assert len(self._weights) == offset + 2 * num_layers
for i in range(len(init_weights)):
j = offset + i
assert np.all(
np.equal(list(init_weights[i].shape), list(self._weights[j].shape))
)
self._weights[j].data = init_weights[i]
else:
for i in range(len(self._layer_weight_tensors)):
init_params(self._layer_weight_tensors[i], self._layer_bias_vectors[i])
def forward(self, x, weights=None, distilled_params=None, condition=None):
"""Compute the output :math:`y` of this network given the input
:math:`x`.
Args:
(....): See docstring of method
:meth:`mnets.mnet_interface.MainNetInterface.forward`. We
provide some more specific information below.
x: Input image.
.. note::
We assume the Tensorflow format, where the last entry
denotes the number of channels.
weights (list or dict): If a list of parameter tensors is given and
context modulation is used (see argument ``use_context_mod`` in
constructor), then these parameters are interpreted as context-
modulation parameters if the length of ``weights`` equals
:code:`2*len(net.context_mod_layers)`. Otherwise, the length is
expected to be equal to the length | |
'\\textnormal{L}', '\\textnormal{C}', '\\tau', \
'\\rho', 'S_0', '\\textnormal{Q}', '\\omega 0']
if len(params_priors) > 1:
fout.write('\\noalign{\\smallskip}\n')
fout.write('Additional parameters{}\n'.format(linend))
fout.write('\\noalign{\\smallskip}\n')
for post in params_priors:
s_param = '~~~'
if post == 'unnamed': continue
if post == 'loglike': continue
elif post[:2] == 'GP':
pvector = post.split('_')
gp_param = pvector[1]
insts = pvector[2:]
for i,elem in enumerate(gp_names):
if elem == gp_param:
gp_param_latex = gp_names_latex[i]
continue
if gp_param not in gp_names: # most likely alpha0, alpha1
gp_param_latex = '\\alpha_{}'.format(gp_param[-1])
s_param += gp_param_latex + '$^{GP}_{\\textnormal{'
for inst in insts:
s_param += inst+','
s_param = s_param[:-1] # to get rid of the last comma
s_param += '}}$'
else:
s_param += '$' + post + '$'
s_param += ' & '
if dataset.priors[post]['distribution'] == 'fixed':
s_param += '{}'.format(dataset.priors[post]['hyperparameters'])
s_param += ' (fixed) & --- & \\textcolor{red}{add}'
elif dataset.priors[post]['distribution'] == 'exponential':
s_param += '$'+dists_types[dataset.priors[post]['distribution']]+'('+str(dataset.priors[post]['hyperparameters'])
s_param += ')$ & --- & \\textcolor{red}{add}'
elif dataset.priors[post]['distribution'] == 'truncatednormal':
s_param += '$'+dists_types[dataset.priors[post]['distribution']]+'('+\
str(dataset.priors[post]['hyperparameters'][0])+','+\
str(dataset.priors[post]['hyperparameters'][1])+','+\
str(dataset.priors[post]['hyperparameters'][2])+','+\
str(dataset.priors[post]['hyperparameters'][3])
s_param += ')$ & --- & \\textcolor{red}{add}'
else:
if dataset.priors[post]['distribution'] not in dists_types:
print('BUG3')
print(post)
print(dataset.priors[post])
print()
quit()
s_param += '$'+dists_types[dataset.priors[post]['distribution']]+'('+\
str(dataset.priors[post]['hyperparameters'][0])+','+\
str(dataset.priors[post]['hyperparameters'][1])
if dataset.priors[post]['distribution'] == 'normal' or dataset.priors[post]['distribution']=='loguniform':
s_param += '^2'
s_param += ')$ &'
print(priors_dict.keys())
if post[:2] == 'GP':
pvector = post.split('_')
gp_param = pvector[1]
insts = pvector[2:]
if post in priors_dict.keys(): s_param += ' --- &' + priors_dict[post]['description']
elif post[:2] == 'GP':
pvector = post.split('_')
gp_param = pvector[1]
if 'GP_'+gp_param in priors_dict.keys():
s_param += ' --- &' + priors_dict['GP_'+gp_param]['description']
else:
s_param += ' --- & \\textcolor{red}{add}'
else: s_param += ' --- & \\textcolor{red}{add}'
s_param += linend
fout.write(s_param+'\n')
params_priors = np.delete(params_priors, np.where(params_priors == post)[0])
if len(params_priors) > 1:
print('% These params were not able to be latexifyed')
print('%',params_priors)
tab_end = ['\\noalign{\\smallskip}', '\\hline', '\\hline', '\\end{tabular}', '\\end{table*}']
for elem in tab_end:
fout.write(elem+'\n')
fout.close()
return
def print_posterior_table(dataset, results, precision=2, printDerived=True, rvunits='ms'):
"""
Parameters
----------
dataset
results
precision
printDerived
rvunits
"""
# lin = 'parameter \t& ${}^{+{}}_{-{}}$ \\\\'.format(precision, precision, precision)
# print(lin)
out_folder = dataset.out_folder
latex_fil = out_folder+'posterior_table.tex'
print('writing to {}.'.format(latex_fil))
fout = open(latex_fil, 'w')
tab_start = ['\\begin{table*}', '\\centering', '\\caption{Posterior parameters}', '\\label{tab:posteriors}', '\\begin{tabular}{lc}',\
'\\hline', '\\hline', '\\noalign{\\smallskip}', 'Parameter name & Posterior estimate \\\\',\
'\\noalign{\\smallskip}', '\\hline', '\\hline']
for elem in tab_start:
fout.write(elem+'\n')
linend = '\\\\'
params_post = np.array([i for i in results.posteriors['posterior_samples'].keys()]) # transform it to array
## Stellar parameters first
if 'rho' in params_post:
fout.write('\\noalign{\\smallskip}\n')
fout.write('Stellar Parameters '+linend+' \n')
fout.write('\\noalign{\\smallskip}\n')
s_param = '~~~'
s_param += '$\\rho_{*} \, \mathrm{(kg/m^3)}$'
s_param += ' & '
val,valup,valdown = juliet.utils.get_quantiles(results.posteriors['posterior_samples']['rho'])
errhi, errlo = round_sig(valup-val, sig=precision), round_sig(val-valdown, sig=precision)
digits = np.max([np.abs(count_this(errhi)), np.abs(count_this(errlo))])
vals = '{0:.{digits}f}'.format(val, digits = digits)
errhis = '{0:.{digits}f}'.format(errhi, digits = digits)
errlos = '{0:.{digits}f}'.format(errlo, digits = digits)
s_param += '$'+vals+'^{+'+errhis+'}_{-'+errlos+'}$' + linend
fout.write(s_param+'\n')
params_post = np.delete(params_post, np.where(params_post == 'rho')[0])
order_planetary = ['P', 't0', 'a', 'r1', 'r2', 'b', 'p', 'K', 'ecc', 'omega', 'sesinomega', 'secosomega',
'esinomega', 'ecosomega']
planet_names = ['', 'b', 'c', 'd', 'e', 'f']
# Save information stored in the prior: the dictionary, number of transiting planets,
# number of RV planets, numbering of transiting and rv planets (e.g., if p1 and p3 transit
# and all of them are RV planets, numbering_transit = [1,3] and numbering_rv = [1,2,3]).
# Save also number of *free* parameters (FIXED don't count here).
rv_planets = dataset.numbering_rv_planets
transiting_planets = dataset.numbering_transiting_planets
for pl in np.unique(np.append(rv_planets, transiting_planets)):
fout.write('\\noalign{\\smallskip}\n')
if len(np.unique(np.append(rv_planets, transiting_planets))) == 1:
fout.write('Planetary parameters'+linend+' \n')
else:
fout.write('Posterior parameters for planet {} '.format(planet_names[pl])+linend+' \n')
fout.write('\\noalign{\\smallskip}\n')
for param in order_planetary:
key = '{}_p{}'.format(param, pl)
if key not in params_post and key not in dataset.priors.keys():
continue
val,valup,valdown = juliet.utils.get_quantiles(results.posteriors['posterior_samples'][key])
s_param = '~~~'
if param == 'P': s_param += '$P_{' + planet_names[pl] + '}$ (d)'
elif param == 't0': s_param += '$t_{0,' + planet_names[pl] + '}$ (BJD UTC)'
elif param == 'a': s_param += '$a_{' + planet_names[pl] + '}/R_*$'
elif param == 'r1': s_param += '$r_{1,' + planet_names[pl] + '}$'
elif param == 'r2': s_param += '$r_{2,' + planet_names[pl] + '}$'
elif param == 'p': s_param += '$R_{' + planet_names[pl] + '}/R_*$'
elif param == 'b': s_param += '$b = (a_{' + planet_names[pl] + '}/R_*) \\cos (i_{'+ planet_names[pl] +'}) $'
elif param == 'K': s_param += '$K_{' + planet_names[pl] + '}$ (m/s)'
elif param == 'ecc': s_param += '$e_{' + planet_names[pl] + '}$'
elif param == 'omega': s_param += '$\\omega_{' + planet_names[pl] + '}$'
elif 'sesinomega' in param:
s_param += '$S_{1,' + planet_names[pl] + '} = \\sqrt{e_'+planet_names[pl]+'}\\sin \\omega_'+planet_names[pl]+'$'
elif param == 'secosomega':
s_param += '$S_{2,' + planet_names[pl] + '} = \\sqrt{e_'+planet_names[pl]+'}\\cos \\omega_'+planet_names[pl]+'$'
elif param == 'esinomega':
s_param += '$S_{1,' + planet_names[pl] + '} = e_'+planet_names[pl]+'\\sin \\omega_'+planet_names[pl]+'$'
elif param == 'ecosomega':
s_param += '$S_{1,' + planet_names[pl] + '} = e_'+planet_names[pl]+'\\cos \\omega_'+planet_names[pl]+'$'
else: s_param += '$' + param + '_{' + planet_names[pl] + '}$'
s_param += ' & '
errhi, errlo = round_sig(valup-val, sig=precision), round_sig(val-valdown, sig=precision)
# print(valup-val, errhi)
# print(val-valdown, errlo)
# print(count_this(errhi), count_this(errlo))
digits = np.max([np.abs(count_this(errhi)), np.abs(count_this(errlo))])
vals = '{0:.{digits}f}'.format(val, digits = digits)
errhis = '{0:.{digits}f}'.format(errhi, digits = digits)
errlos = '{0:.{digits}f}'.format(errlo, digits = digits)
s_param += '$'+vals+'^{+'+errhis+'}_{-'+errlos+'}$' + linend
fout.write(s_param+'\n')
params_post = np.delete(params_post, np.where(params_post == key)[0])
instruments_rv = dataset.inames_rv
instruments_lc = dataset.inames_lc
if instruments_rv is not None and len(instruments_rv):
orderinst_rv = ['mu','sigma_w']
orderinst_rv_latex = ['\\mu', '\\sigma']
fout.write('\\noalign{\\smallskip}\n')
fout.write('RV instrumental parameters'+linend+'\n')
fout.write('\\noalign{\\smallskip}\n')
for inst in instruments_rv:
for param,param_latex in zip(orderinst_rv,orderinst_rv_latex):
s_param = '~~~'
s_param += '$'+param_latex+'_{\\textnormal{'+inst+'}}$ (m/s)'
# if param == 'mu':
# s_param += '$\\mu_{\\textnormal{' + inst + '}}$ (m/s)'
# elif param == 'sigma_w':
# s_param += '$\\sigma_{\\textnormal{' + inst + '}}$ (m/s)'
s_param += ' & '
if '{}_{}'.format(param, inst) not in params_post: # assume it was fixed
val = dataset.priors[param+'_'+inst]['hyperparameters']
s_param += '{} (fixed) {}'.format(val, linend)
else:
val,valup,valdown = juliet.utils.get_quantiles(results.posteriors['posterior_samples']['{}_{}'.format(param, inst)])
errhi, errlo = round_sig(valup-val, sig=precision), round_sig(val-valdown, sig=precision)
# print(valup-val, val-valdown)
# print(errhi, errlo)
# print(count_this(errhi), count_this(errlo))
digits = np.max([np.abs(count_this(errhi)), np.abs(count_this(errlo))])
vals = '{0:.{digits}f}'.format(val, digits = digits)
errhis = '{0:.{digits}f}'.format(errhi, digits = digits)
errlos = '{0:.{digits}f}'.format(errlo, digits = digits)
s_param += '$'+vals+'^{+'+errhis+'}_{-'+errlos+'}$' + linend
fout.write(s_param+'\n')
params_post = np.delete(params_post, np.where(params_post == '{}_{}'.format(param, inst))[0])
if instruments_lc is not None and len(instruments_lc):
orderinst_lc = ['mflux', 'sigma_w', 'q1', 'q2', 'theta0']#, 'mdilution']
fout.write('\\noalign{\\smallskip}\n')
fout.write('Photometry instrumental parameters'+linend+'\n')
fout.write('\\noalign{\\smallskip}\n')
for inst in instruments_lc:
for param in orderinst_lc:
s_param = '~~~'
if param == 'mflux':
s_param += '$M_{\\textnormal{' + inst + '}}$ [ppm]'
elif param == 'sigma_w':
s_param += '$\\sigma_{\\textnormal{' + inst + '}}$ [ppm]'
elif param == 'q1':
s_param += '$q_{1,\\textnormal{' + inst + '}}$'
elif param == 'q2' and '{}_{}'.format(param, inst) in params_post:
s_param += '$q_{2,\\textnormal{' + inst + '}}$'
elif param == 'q2' and ('{}_{}'.format(param, inst) not in params_post or '{}_{}'.format(param, inst) not in dataset.priors.keys()):
continue
# if param == 'theta' and ('{}0_{}'.format(param, inst) not in params_post or '{}0_{}'.format(param, inst) not in dataset.priors.keys()):
# continue
# else:
# hastheta = True
# ind = 0
# while hastheta == True:
elif param == 'theta0' and '{}_{}'.format(param, inst) in params_post:
s_param += '$\\theta_{0,\\textnormal{' + inst + '}}$'
elif param == 'theta0' and ('{}_{}'.format(param, inst) not in params_post or '{}_{}'.format(param, inst) not in dataset.priors.keys()):
continue
s_param += ' & '
if '{}_{}'.format(param, inst) not in params_post: # assume it was fixed
val = dataset.priors[param+'_'+inst]['hyperparameters']
s_param += '{} (fixed) {}'.format(val, linend)
else:
val,valup,valdown = juliet.utils.get_quantiles(results.posteriors['posterior_samples']['{}_{}'.format(param, inst)])
errhi, errlo = round_sig(valup-val, sig=precision), round_sig(val-valdown, sig=precision)
# print(valup-val, val-valdown)
# print(errhi, errlo)
# print(count_this(errhi), count_this(errlo))
digits = np.max([np.abs(count_this(errhi)), np.abs(count_this(errlo))])
vals = '{0:.{digits}f}'.format(val, digits = digits)
errhis = '{0:.{digits}f}'.format(errhi, digits = digits)
errlos = '{0:.{digits}f}'.format(errlo, digits = digits)
s_param += '$'+vals+'^{+'+errhis+'}_{-'+errlos+'}$' + linend
fout.write(s_param+'\n')
params_post = np.delete(params_post, np.where(params_post == '{}_{}'.format(param, inst))[0])
fout.write('\\noalign{\\medskip}\n')
gp_names = ['sigma', 'alpha', 'Gamma', 'Prot', 'B', 'L', 'C', 'timescale', 'rho', 'S0', 'Q', 'omega0']
gp_names_latex = ['\\sigma', '\\alpha', '\\Gamma', 'P_{rot}', \
'\\textnormal{B}', '\\textnormal{L}', '\\textnormal{C}', '\\tau', \
'\\rho', 'S_0', '\\textnormal{Q}', '\\omega 0']
# if len(params_post) > 1:
# fout.write('\\noalign{\\smallskip}\n')
# fout.write('Additional parameters{}\n'.format(linend))
# fout.write('\\noalign{\\smallskip}\n')
for post in params_post:
s_param = '~~~'
if post == 'unnamed': continue
if post | |
import codecs
import locale
import sys
import logging
import random
import time
import traceback
from optparse import OptionGroup, OptionParser
from typing import List, Tuple
from collections import deque
from operator import itemgetter
from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED
from clickhouse_driver import Client, errors
if sys.version >'2' and sys.version >= '3.7':
sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout)
elif sys.version >'2' and sys.version < '3.7':
sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(threadName)s: - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
class CHClient:
def __init__(self, user: str = 'default', password: str = '', host: str = "", port: int = None, database: str = ''):
"""
初始化clickhouse client.
"""
self.host = host
self.user = user
self.password = password
self.database = database
self.port = port
self.settings = {'receive_timeout': 1200, 'send_timeout': 1200}
self.chcli = Client(host=self.host, port=self.port, database=self.database, user=self.user,
password=self.password, send_receive_timeout=1200, settings=self.settings)
def execute(self, sql: str = None, with_column_types: bool = False) -> Tuple[int, List[Tuple]]:
"""
:param sql: 待执行sql
:param with_column_types:result[-1] 返回列的类型
:return: result -> list<tuple>
"""
try:
logger.info(f'host:<{self.host}>: will execute sql :\n{sql}')
res = self.chcli.execute(sql, with_column_types=with_column_types)
return 0, res
except Exception:
err = traceback.format_exc()
# part正在被merge或者mutation
if 'Code: 384.' in err:
logger.warning(f'host:<{self.host}>,ERROR:2: failed to execute sql:\n {sql},\nerr:\n {err}')
return 2, [()]
# part在fetch part前已经被merge或者drop,is not exists
if 'Code: 234.' in err:
logger.warning(f'host:<{self.host}>,ERROR:3: failed to execute sql:\n {sql},\nerr:\n {err}')
return 3, [()]
# detached part 不存在 No part xx in committed state.
if 'Code: 232.' in err:
logger.warning(f'host:<{self.host}>,ERROR:4: failed to execute sql:\n {sql},\nerr:\n {err}')
return 4, [()]
# 过滤掉重放是出现的删除drop detach part不存在的错误,污染log
if 'Code: 233.' in err:
return 5, [()]
# part 过大,拉取超过python client 最大时间,触发超时,但是任务实际仍然在跑
if 'socket.timeout: timed out' in err:
logger.warning(f'host:<{self.host}>,ERROR:90: failed to execute sql:\n {sql},\nerr:\n {err}')
return 90, [()]
# 写锁,因为part还在拉取,如果执行detach时,因为写锁,无法正常detach
if 'Code: 473.' in err:
logger.warning(f'host:<{self.host}>,ERROR:91: failed to execute sql:\n {sql},\nerr:\n {err}')
return 91, [()]
# zk会话过期,命令提交zk,可能失败也可能成功
if 'Code: 999.' in err and 'Session expired' in err:
logger.warning(f'host:<{self.host}>,ERROR:92: failed to execute sql:\n {sql},\nerr:\n {err}')
return 92, [()]
# zk node 连接丢失,和会话过期场景类似,命令提交zk,可能失败也可能成功
if 'Code: 999.' in err and 'Connection loss' in err:
logger.warning(f'host:<{self.host}>,ERROR:93: failed to execute sql:\n {sql},\nerr:\n {err}')
return 93, [()]
# 副本状态不一致,触发不能执行drop和detach part,
if 'Code: 529.' in err and 'DROP PART|PARTITION cannot be done on this replica because it is not a leader' in err:
logger.warning(f'host:<{self.host}>,ERROR:94: failed execute sql:\n {sql},\nerr:\n {err}')
return 94, [()]
# code 16 主要表现为一些列的操作有问题,导致历史part和现在的表结构不一致,一旦part detach后就不能attach,
# 属于特别极端,且难通过程序恢复的错误,需要人为恢复,恢复方式是解决列问题后,重新执行最后输出的attach_sql_list中的命令。
if 'Code: 16.' in err:
logger.error(f'host:<{self.host}>,ERROR:999: failed to execute sql:\n {sql},\nerr:\n {err}')
return 999, [()]
logger.error(f"host:<{self.host}>,ERROR:1: failed to execute sql:\n {sql},\nerr:\n {err}")
return 1, [()]
def exclose(self):
"""
关闭clickhouse连接
:return:
"""
self.chcli.disconnect()
def ping(self) -> Client:
"""
执行 select 1,如果失败,将会重新初始化client
:return:
"""
try:
self.chcli.execute('select 1')
except (errors.NetworkError, errors.ServerException):
self.chcli = Client(host=self.host, port=self.port, database=self.database, user=self.user,
password=self.password)
return self.chcli
class CHSQL:
# 获得节点ip列表
get_nodes = """select shard_num,host_address
from system.clusters
where cluster='{cluster}'
order by shard_num,replica_num"""
# 获得待均衡分区
get_partitions = """select partition
from (
SELECT
a.shard,
a.partition,
sum(b.partition_bytes) AS partition_bytes
FROM (
select t1.shard
,t2.partition
from (
select hostName() AS shard from clusterAllReplicas('{cluster}', system, one)
)t1
cross join (
select distinct partition
from clusterAllReplicas('{cluster}', system, parts)
WHERE (database = '{database}') AND (table = '{table}')
AND (toDate(parseDateTimeBestEffortOrZero(toString(partition))) <= (today() - 7))
AND (bytes_on_disk > ((100 * 1024) * 1024))
AND disk_name<>'hdfs'
group by partition
)t2
)a
left join(
select hostName() as shard
,partition
,sum(toUInt32(bytes_on_disk/1024/1024)) AS partition_bytes
from clusterAllReplicas('{cluster}', system, parts)
WHERE (database = '{database}') AND (table = '{table}')
AND (toDate(parseDateTimeBestEffortOrZero(toString(partition))) <= (today() - 7))
AND (bytes_on_disk > ((100 * 1024) * 1024))
AND disk_name<>'hdfs'
group by shard,partition
)b
on a.shard=b.shard and a.partition=b.partition
group by a.shard,
a.partition
)
GROUP BY partition
HAVING (min(partition_bytes) <= (avg(partition_bytes) * {low_rate}))
and (max(partition_bytes) >= (avg(partition_bytes) * {high_rate}))
order by partition desc"""
# 获得part的列表,并排除掉小于100M的part
get_parts = """select _shard_num
,name as part_name
,rows
,toUInt32(bytes_on_disk/1024/1024) as bytes_on_disk
,disk_name
from cluster('{cluster}',system,parts)
where database='{database}'
and table='{table}'
and partition='{partition}'
and bytes_on_disk>100
and disk_name<>'hdfs'"""
# 借助zk,fetch part
fetch_part = """ALTER TABLE {database}.{table} FETCH PART '{part_name}' FROM '/clickhouse/tables/{layer}-{shard}/{database}.{table}'"""
# 设置参数允许删除detached part
set_drop_detached = """set allow_drop_detached = 1"""
# 删除detached part
drop_detach_part = """ALTER TABLE {database}.{table} DROP DETACHED PART '{part_name}'"""
# attach part 这个是复制的,在一个节点执行,另一个节点会在detached 目录找一致的part,如果有,则挂载,没有从另外一个节点拉取
attach_part = """ALTER TABLE {database}.{table} ATTACH PART '{part_name}'"""
# detach part 这个是复制的,将一个active part detach,part将不会被查询
detach_part = """ALTER TABLE {database}.{table} DETACH PART '{part_name}'"""
# 获得layer宏变量,补充建表时的znode path
get_layer = """select substitution from system.macros where macro='layer'"""
# 获取shard宏变量,补充建表时的znode path
get_shard = """select substitution from system.macros where macro='shard'"""
# 判断part是否存在,存在则会detach,不存在将会返回0或者连接丢失报错
part_is_exists = """select 1 from system.parts where name='{part_name}'"""
# 检查分区的行数和大小,做对账,保证数据一致
check_partitions = """ select sum(rows) as rows,sum(toUInt32(bytes_on_disk/1024/1024)) as bytes
FROM cluster('{cluster}', system, parts)
where database='{database}'
and table='{table}'
and partition='{partition}'
and bytes_on_disk>100
and disk_name<>'hdfs'"""
check_fetch_part_running = """select 1 from system.processes where query like '%FETCH PART \\'{part_name}\\'%'"""
check_attach_part_is_exists = """select 1 from system.parts
where database={database}
and table={table}
and rows={rows}
and toUInt32(bytes_on_disk/1024/1024)={bytes}
and toDate(modification_time)=today()"""
def partition_rebalance(partition: str):
# 获得part信息
logger.info(f"{partition} is rebalancing!")
err_code, part_list = cli.execute(
chsql.get_parts.format(cluster=cluster, database=database, table=table, partition=partition))
node_part_dict = {}
node_stat_dict = {}
# 在搬移之前计算总量和总大小,做对账
err_code, before_check = cli.execute(
chsql.check_partitions.format(cluster=cluster, database=database, table=table, partition=partition))
before_sum_bytes = before_check[0][1]
before_sum_rows = before_check[0][0]
# 得到part信息和搬移前的每个shard的存储和行数信息
for part in part_list:
shard_num = part[0]
if shard_num not in node_part_dict.keys():
node_part_dict[shard_num] = []
if shard_num not in node_stat_dict.keys():
node_stat_dict[shard_num] = {'start_rows': 0, 'start_bytes': 0, 'plan_end_rows': 0, 'plan_end_bytes': 0,
'move_rows': 0, 'move_bytes': 0}
node_part_dict[shard_num].append(part[1:])
node_stat_dict[shard_num]['start_rows'] += part[2]
node_stat_dict[shard_num]['plan_end_rows'] += part[2]
node_stat_dict[shard_num]['start_bytes'] += part[3]
node_stat_dict[shard_num]['plan_end_bytes'] += part[3]
# 补齐节点,可能存在节点没有表的part数据。
for shard_num in node_dict.keys():
if shard_num not in node_stat_dict.keys():
node_stat_dict[shard_num] = {'start_rows': 0, 'start_bytes': 0, 'plan_end_rows': 0, 'plan_end_bytes': 0}
logger.info(f"partition<{partition}>:rows<{before_sum_rows}>,bytes<{before_sum_bytes}MB>")
# 排序,从小的part到大的part 从list pop
avg_bytes = int(before_sum_bytes / len(node_stat_dict.keys()))
for shard_num, part_list in node_part_dict.items():
node_part_dict[shard_num] = sorted(part_list, key=itemgetter(3, 2), reverse=True)
# 从小的part到大的part,依次加入待搬移队列,直到小于平均存储
move_part_list = []
for shard_num, part in node_part_dict.items():
if not part:
continue
m_part = part.pop()
if node_stat_dict[shard_num]['plan_end_bytes'] - m_part[2] >= avg_bytes * high_rate:
while node_stat_dict[shard_num]['plan_end_bytes'] - m_part[2] >= avg_bytes * cp_rate:
move_part_list.append((shard_num, m_part))
node_stat_dict[shard_num]['plan_end_bytes'] -= m_part[2]
node_stat_dict[shard_num]['plan_end_rows'] -= m_part[1]
node_stat_dict[shard_num]['is_push'] = 1
if not part:
break
m_part = part.pop()
logger.info(f"partition<{partition}>:move_part_list<{move_part_list}>")
# 获得需要接收part的节点
need_get_shard_list = []
for shard_num, status in node_stat_dict.items():
if status.get('is_push', 0) == 1:
continue
if status['start_bytes'] <= avg_bytes * low_rate:
need_get_shard_list.append(shard_num)
logger.info(f"partition<{partition}>:need_get_shard_list<{need_get_shard_list}>")
if not move_part_list or not need_get_shard_list:
logger.info(f"partition<{partition}>:no fetch part or partition data is balance")
return 0
# 生成每个part的搬移task
move_op_list = []
while move_part_list and need_get_shard_list:
m_part = move_part_list.pop()
shard_num = random.choice(need_get_shard_list)
if node_stat_dict[shard_num]['plan_end_bytes'] > avg_bytes * rev_rate:
need_get_shard_list.remove(shard_num)
move_part_list.append(m_part)
continue
move_op_list.append((m_part[0], shard_num, m_part[1]))
node_stat_dict[shard_num]['plan_end_bytes'] += m_part[1][2]
node_stat_dict[shard_num]['plan_end_rows'] += m_part[1][1]
logger.info(f"partition<{partition}>:move_op_list<{move_op_list}>")
# shard间并行,但限制:shard同时间只能发一个part,每个接收shard 同时间只能接收一个part,
# mvp 结构 (part src shard, part target shard,part info<part_name,rows,bytes,disk>)
move_op_list = sorted(move_op_list, key=itemgetter(1, 0), reverse=True)
sed_set = set()
recv_set = set()
# pool 定义为100,最大支持200个节点的集群,极限情况下做数据均衡。
pool = ThreadPoolExecutor(100, thread_name_prefix='thread')
move_op_deque = deque(move_op_list)
def callback(res): # 定义回调函数
err_code, mvp = res.result()
send_shard = mvp[0]
recv_shard = mvp[1]
rows = mvp[2][1]
bytes = mvp[2][2]
sed_set.remove(send_shard)
recv_set.remove(recv_shard)
if err_code:
part_name = mvp[2][0]
disk_name = mvp[2][3]
logger.warning(f"partition<{partition}>:{disk_name}:{part_name}:{rows}row:{bytes}MB:"
f"from shard<{send_shard}> move shard<{recv_shard}> is failed")
logger.info(f"{partition}:sed_set remove:{send_shard},recv_shard remove:{recv_shard}")
return
node_stat_dict[send_shard]['move_rows'] -= rows
node_stat_dict[recv_shard]['move_rows'] += rows
node_stat_dict[send_shard]['move_bytes'] -= bytes
node_stat_dict[recv_shard]['move_bytes'] += bytes
node_partition_stat_dict[send_shard]['move_rows_sum'] -= rows
node_partition_stat_dict[recv_shard]['move_rows_sum'] += rows
node_partition_stat_dict[send_shard]['move_bytes_sum'] -= bytes
node_partition_stat_dict[recv_shard]['move_bytes_sum'] += bytes
logger.info(f"{partition}:sed_set remove:{send_shard},recv_shard remove:{recv_shard}")
task_obj_list = []
th_num = 10001
while move_op_deque:
mvp = move_op_deque.pop()
if mvp[0] not in sed_set and mvp[1] not in recv_set:
sed_set.add(mvp[0])
recv_set.add(mvp[1])
obj = pool.submit(fetch_part, th_num, partition, mvp)
obj.add_done_callback(callback)
task_obj_list.append(obj)
th_num += 1
else:
move_op_deque.appendleft(mvp)
time.sleep(2)
wait(task_obj_list, timeout=None, return_when=ALL_COMPLETED)
time.sleep(20)
err_code, after_check = cli.execute(
chsql.check_partitions.format(cluster=cluster, database=database, table=table, partition=partition))
after_sum_bytes = after_check[0][1]
after_sum_rows = after_check[0][0]
logger.debug(f"{partition}:end:node_stat_dict:{node_stat_dict}")
logger.info(f"{partition}:node_partition_stat_dict:{node_partition_stat_dict}")
if before_sum_rows == after_sum_rows:
logger.info(
f"{partition}: Check:partition rows is same: {after_sum_rows},{after_sum_bytes}MB")
return 0 # error=0
else:
logger.error(f"{partition}:Check:partition rows is not same: before:{before_sum_rows},"
f"after:{after_sum_rows}")
not_same_partition.append((partition, before_sum_rows, after_sum_rows))
return 1 # error=1
def fetch_part(th_num, partition, mvp):
send_shard = mvp[0]
recv_shard = mvp[1]
part_name = mvp[2][0]
rows = mvp[2][1]
bytes = mvp[2][2]
disk_name = mvp[2][3]
send_rp1_cli = node_dict[send_shard][0][1]
recv_rp1_cli = node_dict[recv_shard][0][1]
logger.info(f"<{th_num}>:{partition}:disk<{disk_name}>part<{part_name}> is moving,"
f"from shard<{send_shard}>to shard<{recv_shard}>,rows:<{rows}>,bytes:<{bytes}MB>")
if len(node_dict[send_shard]) == 2:
is_source_two_replica = True
else:
is_source_two_replica = False
# 获得来源节点的shard 宏变量
err_code, shard_macro = send_rp1_cli.execute(chsql.get_shard)
if err_code and is_source_two_replica:
err_code, shard_macro = node_dict[send_shard][1][1].execute(chsql.get_shard)
if err_code:
logger.error(f"send_shard<{send_shard}>: can not get right shard_macro")
return 1, mvp
elif err_code:
logger.error(f"send_shard<{send_shard}>: can not get right shard_macro")
return 1, mvp
try:
shard_macro = shard_macro[0][0]
except IndexError:
logger.error(f"send_shard<{send_shard}>: can not get | |
<reponame>chris-price19/cell-mech-memory
#!/usr/bin/python
import math
import numpy as np
import scipy
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
import sys
import re
# import autograd as ag
import torch
from torch.autograd import grad, Variable
from torch.utils.data import Sampler, Dataset, DataLoader, ConcatDataset, WeightedRandomSampler, BatchSampler
# from pyDOE2 import lhs
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from sklearn import metrics
import xgboost as xgb
import timeit
import datetime
import copy
print('reimported at ', end=''); print(datetime.datetime.now())
def df_scale(data, dmean = None, dstd = None):
if dmean is None:
dmean = np.mean(data, axis=0)
if dstd is None:
dstd = np.std(data, axis=0)
return ((data-dmean) / dstd), dmean, dstd
def df_unscale(data, dmean, dstd):
# print(data)
# print(dmean)
# print(dstd)
return data*dstd + dmean
def moving_average(a, n=3) :
ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n
def default(obj):
if isinstance(obj, np.ndarray):
return obj.tolist()
raise TypeError('Not serializable')
class dataset_from_dataframe(Dataset):
def __init__(self, df, cols, transformx = None):
if torch.cuda.is_available() == True:
self.dtype_double = torch.cuda.FloatTensor
self.dtype_int = torch.cuda.LongTensor
else:
self.dtype_double = torch.FloatTensor
self.dtype_int = torch.LongTensor
# self.dtype_
self.df = df
self.f_cols = cols
self.t_cols = [c for c in df.columns if c not in cols]
self.transformx = transformx
def __len__(self):
return len(self.df)
def __getitem__(self, idx):
if torch.is_tensor(idx):
idx = idx.tolist()
data = self.df.iloc[idx]
features = data[self.f_cols].astype(float).values
label = data[self.t_cols]
if self.transformx:
data = self.transformx(data).copy()
return torch.from_numpy(features).type(self.dtype_double), torch.tensor(label, dtype=torch.float32)
class FCNN(torch.nn.Module):
def __init__(self, feature_dim, output_dim):
# inherit torch.nn.Module methods
super(FCNN, self).__init__()
self.dtype = torch.FloatTensor
d1 = 12
d2 = 12
d3 = 12
d4 = 12
# d5 = 12
# keep this consistent
self.feature_dim = feature_dim # train_data[0][0].shape[-1]
self.output_dim = output_dim # train_data[0][1].shape[-1]
self.fc1 = torch.nn.Linear(self.feature_dim, d1)
self.fc2 = torch.nn.Linear(d1, d2)
self.fc3 = torch.nn.Linear(d2, d3)
self.fc4 = torch.nn.Linear(d3, d4)
# self.fc5 = torch.nn.Linear(d4, d5)
self.fc6 = torch.nn.Linear(d4, self.output_dim)
def init_weights(self,layer):
# glorot initialization
if type(layer) == torch.nn.Linear:
torch.nn.init.xavier_normal_(layer.weight)
layer.bias.data.fill_(0.)
return
def forward(self, f_data):
f_data = torch.tanh(self.fc1(f_data))
f_data = torch.tanh(self.fc2(f_data))
f_data = torch.tanh(self.fc3(f_data))
# f_data = torch.tanh(self.fc4(f_data))
# f_data = torch.tanh(self.fc5(f_data))
predictions = self.fc6(f_data)
return predictions
class simpleNN(torch.nn.Module):
def __init__(self, feature_dim, output_dim):
super(simpleNN, self).__init__()
self.dtype = torch.FloatTensor
self.fcnn = FCNN(feature_dim, output_dim)
self.fcnn.apply(self.fcnn.init_weights)
self.optimizer = torch.optim.Adam(self.fcnn.parameters(), lr=1e-2)
self.loss_fn = torch.nn.MSELoss()
def train_m(self, train_loader):
losslist = []
labeltest = [] # measure training distribution
for it, (data, labels) in enumerate(train_loader):
labeltest = labeltest + [i.item() for i in labels]
# print(data.type())
self.optimizer.zero_grad()
outputs = self.fcnn.forward(data)
loss = self.loss_fn(outputs, labels)
loss.backward()
self.optimizer.step()
losslist.append(loss.detach_())
if it % 20 == 0:
print(losslist[-1])
del loss
return losslist, labeltest
def test_m(self, test_loader):
with torch.no_grad():
losslist = []
outputlist = []
labellist = []
for it, (data, labels) in enumerate(test_loader):
# print(data.type())
outputs = self.fcnn.forward(data)
loss = self.loss_fn(outputs, labels)
outputlist += outputs
labellist += labels
losslist.append(loss.detach_())
if it % 20 == 0:
print(losslist[-1])
del loss
return losslist, outputlist, labellist
def run_model(train_df, test_df, cols, epochs = 1, bsize=5000):
if torch.cuda.is_available() == True:
pinning = True
else:
pinning = False
# print(cols)
train_weighted_sampler, _ = make_sampler(train_df['tm_over_tp'].values)
train_dset = dataset_from_dataframe(train_df, cols)
test_dset = dataset_from_dataframe(test_df, cols)
model = simpleNN(train_dset[0][0].shape[-1], train_dset[0][1].shape[-1])
# model.apply(model.init_weights)
train_loader = DataLoader(train_dset, batch_size = bsize, sampler=train_weighted_sampler, pin_memory = pinning) # shuffle=True,
train_losslist = []
train_labels = []
for epoch in range(epochs):
start_time = timeit.default_timer()
losslist, labeltest = model.train_m(train_loader)
if epoch < 10:
train_labels = train_labels + labeltest
elapsed = timeit.default_timer() - start_time
train_losslist += losslist
print('Epoch %d: %f s' % (epoch, elapsed))
plt.hist(train_labels, bins=100)
plt.show()
# sys.exit()
# for weighting the test data
# test_weighted_sampler, _ = make_sampler(test_df['tm_over_tp'].values)
# test_loader = DataLoader(test_dset, batch_size = bsize, sampler=test_weighted_sampler, pin_memory = pinning) # shuffle=True,
test_loader = DataLoader(test_dset, batch_size = bsize, shuffle=True, pin_memory = pinning)
test_losslist, outputlist, labellist = model.test_m(test_loader)
# print(train_losslist)
# print(test_losslist)
return model, train_losslist, test_losslist, outputlist, labellist
def regress_inputs(model, data, metadict, epochs):
""" take in a dataframe corresponding to experiments + random samples of params, and regress using frozen model to tweak param inputs.
"""
feature_cols = metadict['feature_cols']
target_cols = metadict['target_cols']
update_cols = metadict['update_cols']
inputdata = data[feature_cols]
# update_inds = [inputdata.columns.get_loc(i) for i in update_cols]
# fixed_inds = [inputdata.columns.get_loc(i) for i in feature_cols if i not in update_cols]
fixed_cols = [i for i in feature_cols if i not in update_cols]
# print(update_cols)
# print(fixed_cols)
# print(data)
inputdata, _, _ = df_scale(inputdata, metadict['feature_scaling_mean'], metadict['feature_scaling_std'])
targetdata, _, _ = df_scale(data[target_cols], metadict['target_scaling_mean'], metadict['target_scaling_std'])
# print(targetdata)
print(inputdata[update_cols])
inputdata[update_cols] = np.random.normal(size=(len(inputdata),len(update_cols)))
print(inputdata[update_cols])
optimized_inputs = inputdata.copy()
inputfixed = torch.from_numpy(inputdata[fixed_cols].astype(float).values).type(model.dtype).requires_grad_()
inputupdates = torch.from_numpy(inputdata[update_cols].astype(float).values).type(model.dtype).requires_grad_()
targetdata = torch.tensor(targetdata.astype(float).values, dtype=torch.float32)
# print('first')
# print(inputupdates)
optim = torch.optim.Adam([inputupdates], lr=5e-3)
losslist = []
for it, tt in enumerate(np.arange(epochs)):
# print(it)
optim.zero_grad()
### the model must have been trained with update cols on the left, fixed cols on the right
###
# outputs = model.fcnn.forward(torch.cat((inputupdates, inputfixed), dim=1))
outputs = model.fcnn.forward(torch.cat((inputupdates, inputfixed), dim=1))
loss = model.loss_fn(outputs, targetdata)
loss.backward()
# loss.backward(retain_graph=True)
optim.step()
# print(inputupdates)
# print(torch.mean(inputupdates,0))
# print(torch.ones(inputupdates.size()))
# with torch.no_grad():
# print(torch.mean(inputupdates,0).detach_())
inputupdates = torch.mean(inputupdates,0).detach_() * torch.ones(inputupdates.size())
inputupdates.requires_grad_()
optim = torch.optim.Adam([inputupdates], lr=5e-3)
# print(inputupdates)
# print(torch.mean(inputupdates,0))
# print(inputupdates)
losslist.append(loss.detach_())
# sys.exit()
outputs = model.fcnn.forward(torch.cat((inputupdates, inputfixed), dim=1))
inputdata = torch.cat((inputupdates, inputfixed), dim=1).detach().numpy()
inputdata = df_unscale(inputdata, metadict['feature_scaling_mean'], metadict['feature_scaling_std'])
outputs = df_unscale(outputs.detach().numpy(), metadict['target_scaling_mean'], metadict['target_scaling_std'])
optimized_inputs = pd.DataFrame(inputdata, columns=optimized_inputs.columns)
# print(optimized_inputs)
# print(outputs)
optimized_inputs[target_cols[0]] = outputs
# print(optimized_inputs)
# sys.exit()
return optimized_inputs, losslist
def random_forest(train_df, test_df, metadict):
# rgr = RandomForestRegressor(n_estimators=200, min_samples_split=6, max_depth=8)
# rgr.fit(train_df[metadict['feature_cols']], train_df[metadict['target_cols']].values.ravel())
# ytrains = rgr.predict(train_df[metadict['feature_cols']])
# y_pred = rgr.predict(test_df[metadict['feature_cols']])
# train_mse = metrics.mean_squared_error(train_df[metadict['target_cols']].values.ravel(), ytrains)
# mse = metrics.mean_squared_error(test_df[metadict['target_cols']].values.ravel(), y_pred)
# print("Train MSE:", train_mse)
# print("Test MSE:", mse)
# gbr = GradientBoostingRegressor(n_estimators=100, subsample=0.8, min_samples_split=10, max_depth=10)
# gbr.fit(train_df[metadict['feature_cols']], train_df[metadict['target_cols']].values.ravel())
# gbytrains = gbr.predict(train_df[metadict['feature_cols']])
# gby_pred = gbr.predict(test_df[metadict['feature_cols']])
# gbtrain_mse = metrics.mean_squared_error(train_df[metadict['target_cols']].values.ravel(), gbytrains)
# gbmse = metrics.mean_squared_error(test_df[metadict['target_cols']].values.ravel(), gby_pred)
# print("gb Train MSE:", gbtrain_mse)
# print("gb Test MSE:", gbmse)
# pred = gby_pred
# test_labels = test_df[metadict['target_cols']].values.ravel()
# mse = gbmse
xgbr = xgb.XGBRegressor(
gamma=1,
learning_rate=0.005,
max_depth=10,
n_estimators=160,
subsample=1.,
random_state=34
)
xgbr.fit(train_df[metadict['feature_cols']], train_df[metadict['target_cols']])
xgbrytrains = xgbr.predict(train_df[metadict['feature_cols']])
xgbr_preds = xgbr.predict(test_df[metadict['feature_cols']])
xgbrtrain_mse = metrics.mean_squared_error(train_df[metadict['target_cols']].values.ravel(), xgbrytrains)
xgbrmse = metrics.mean_squared_error(test_df[metadict['target_cols']].values.ravel(), xgbr_preds)
print("xgb Train MSE:", xgbrtrain_mse)
print("xgb Test MSE:", xgbrmse)
pred = xgbr_preds
test_labels = test_df[metadict['target_cols']].values.ravel()
mse = xgbrmse
# print(train_df[metadict['target_cols']])
# print(train_df[metadict['feature_cols']])
# print(train_df[metadict['target_cols']].values)
return pred, test_labels, mse
def make_sampler(data):
counts, bins = np.histogram(data, bins=200)
# print(counts)
# print(bins)
# print(np.digitize(data, bins))
# print(np.amax(np.digitize(data, bins[1:], right=True)))
# print(np.amin(np.digitize(data, bins[1:], right=True)))
weights = np.zeros(len(counts))
weights[counts!=0] = 1. / counts[counts != 0]
# print(np.sum(weights))
# print(weights[counts==0])
# sample_weights
sample_weights = weights[np.digitize(data,bins[1:], right=True)]
# print(np.sum(sample_weights==np.amin(weights)))
sampler = WeightedRandomSampler(sample_weights, len(sample_weights), replacement=True)
# sys.exit()
return sampler, sample_weights #counts / np.sum(counts)
if __name__ == '__main__':
cwd = os.getcwd()
pd.set_option('display.expand_frame_repr', False, 'display.max_columns', None)
# df = pd.read_csv('./stiff_results/constant/static_LHS_SG_SR_ng.csv')
# df = pd.read_csv('./stiff_results/staticTS/static_LHS_SG_SR_ng_newdyn.csv')
df = pd.read_csv('./stiff_results/dynamicTS/energy_dependent_LHS_ng_newdyn.csv')
# print(df.loc[df['ptime'] != df['prime_time']])
# (df['ptime'] - df['prime_time']).hist(bins=40)
# plt.show()
# feature_cols = ['tau', 'tau_F', 'tau_SG', 'tau_SR', 'm0', 'n', 'ptime', 'mem_stiff', 'prime_stiff']
# feature_cols = ['tau', 'tau_F', 'tau_R0', 'TV0SG', 'TV0SR', 'm0','n', 'ptime', 'mem_stiff', 'prime_stiff']
# static
update_features = ['tau', 'tau_F', 'tau_SG', 'tau_SR', 'm0', 'n']
# energy dep
update_features = ['tau', 'tau_F', 'tau_R0', 'TV0SG', 'TV0SR', 'm0','n']
fix_features = ['ptime', 'mem_stiff', 'prime_stiff']
feature_cols = update_features + fix_features
df['tm_over_tp'] = df['mem_time'] / df['prime_time']
# print(df.loc[df['mem_time'].isna()])
target_cols = ['tm_over_tp']
df = df[feature_cols + target_cols]
df, d_mean, d_std = df_scale(df)
# df['tm_over_tp'].hist(bins=200)
# plt.show()
# sys.exit()
data_fraction = 1. # to speed up testing, use some random fraction of images.
train_fraction = 0.8
test_fraction = 1 - train_fraction
bsize = 200
epochs = 10
ids = df.index.values
np.random.shuffle(ids)
ushuff = ids[:int(len(ids)*data_fraction)]
utrain = ushuff[:int(len(ushuff) * train_fraction)]
utest = ushuff[int(len(ushuff) * train_fraction):]
train_df = df.iloc[utrain].reset_index(drop=True)
test_df = df.iloc[utest].reset_index(drop=True)
print(train_df.head(5))
model_metadict = {
'feature_cols': feature_cols,
'target_cols': target_cols,
'update_cols': update_features,
'feature_scaling_mean': d_mean[feature_cols].values,
'feature_scaling_std': d_std[feature_cols].values,
'target_scaling_mean': d_mean[target_cols].values,
'target_scaling_std': d_std[target_cols].values,
}
_, sweights = make_sampler(train_df[target_cols].values)
# print(np.shape(sweights))
# print(torch.as_tensor(sweights.flatten(), dtype=torch.double))
# sys.exit()
balanced_inds = torch.multinomial(torch.as_tensor(sweights.flatten(), dtype=torch.double), len(sweights), True)
print(balanced_inds.numpy())
# print(np.sum(sweights.flatten()))
# balanced_inds = np.random.choice(np.arange(len(train_df[target_cols].values)), len(train_df[target_cols].values), True, sweights.flatten())
weighted_df = train_df.iloc[balanced_inds]
# weighted_df[target_cols].hist()
# plt.show()
# sys.exit()
pred, test_labels, mse = random_forest(weighted_df, test_df, model_metadict)
fig3, ax3 = plt.subplots(1,1, figsize=(6,6))
ax3.scatter(pred, test_labels)
ax3.set_xlabel('predicted')
ax3.set_ylabel('true')
ax3.plot([np.amin(test_labels), np.amax(test_labels)], [np.amin(test_labels), np.amax(test_labels)], color='r')
| |
image as a temporary file and return the path
:param path: where temporary files to be stored
:param filename: name(prefix) of the temporary file
:param clean: True if temp files are tobe deleted once the object
is to be destroyed
:param kwargs: used for overloading the PIL save methods. In particular
this method is useful for setting the jpeg compression
level. For JPG see this documentation:
http://www.pythonware.com/library/pil/handbook/format-jpeg.htm
:return:
:Example:
>>> img = Image('phlox')
>>> img.save(tmp=True)
It will return the path that it saved to.
Save also supports IPython Notebooks when passing it a Display object
that has been instainted with the notebook flag.
To do this just use:
>>> disp = Display(displaytype='notebook')
>>> img.save(disp)
:Note:
You must have IPython notebooks installed for this to work path
and filename are valid if and only if temp is set to True.
"""
# TODO, we use the term mode here when we mean format
# TODO, if any params are passed, use PIL
if tmp:
import glob
if filename is None:
filename = 'Image'
if path is None:
path = tempfile.gettempdir()
if glob.os.path.exists(path):
path = glob.os.path.abspath(path)
imfiles = glob.glob(glob.os.path.join(path, filename + '*.png'))
num = [0]
for img in imfiles:
num.append(int(glob.re.findall('[0-9]+$', img[:-4])[-1]))
num.sort()
fnum = num[-1] + 1
filename = glob.os.path.join(path, filename + ('%07d' % fnum) +
'.png')
self._tmp_files.append(filename, clean)
self.save(self._tmp_files[-1][0])
return self._tmp_files[-1][0]
else:
print("Path does not exist!")
else:
if filename:
handle_or_name = filename + '.png'
if not handle_or_name:
if self.filename:
handle_or_name = self.filename
else:
handle_or_name = self.filehandle
if len(self._layers):
img_save = self.apply_layers()
else:
img_save = self
if (self._color_space != ColorSpace.BGR and
self._color_space != ColorSpace.GRAY):
img_save = img_save.to_bgr()
if not isinstance(handle_or_name, str):
fh = handle_or_name
if not PIL_ENABLED:
logger.warning("You need the Pillow to save by file handle")
return 0
if isinstance(fh, 'JpegStreamer'):
fh.jpgdata = StringIO()
# save via PIL to a StringIO handle
img_save.pilimg.save(fh.jpgdata, 'jpeg', **kwargs)
fh.refreshtime = time.time()
self.filename = ''
self.filehandle = fh
elif isinstance(fh, 'VideoStream'):
self.filename = ''
self.filehandle = fh
fh.write_frame(img_save)
elif isinstance(fh, 'Display'):
if fh.display_type == 'notebook':
try:
from IPython.core import Image as IPYImage
except ImportError:
print("Need IPython Notebooks to use the display mode!")
return
from IPython.core import display as IPYDisplay
tf = tempfile.NamedTemporaryFile(suffix='.png')
loc = tf.name
tf.close()
self.save(loc)
IPYDisplay.display(IPYImage(filename=loc))
else:
self.filehandle = fh
fh.write_frame(img_save)
else:
if not mode:
mode = 'jpeg'
try:
# latest version of PIL/PILLOW supports webp,
# try this first, if not gracefully fallback
img_save.pilimg.save(fh, mode, **kwargs)
# set the file name for future save operations
self.filehandle = fh
self.filename = ''
return 1
except Exception as e:
if mode.lower() != 'webp':
raise e
if verbose:
print(self.filename)
if not mode.lower() == 'webp':
return 1
# make a temporary file location if there isn't one
if not handle_or_name:
filename = tempfile.mkstemp(suffix='.png')[-1]
else:
filename = handle_or_name
# allow saving in webp format
if mode == 'webp' or re.search('\.webp$', filename):
try:
# newer versions of PIL support webp format, try that first
self.pilimg.save(filename, **kwargs)
except:
logger.warning("Can't save to webp format!")
if kwargs:
if not mode:
mode = 'jpeg'
img_save.pilimg.save(filename, mode, **kwargs)
return 1
if filename:
cv2.SaveImage(filename, img_save.bitmap)
self.filename = filename
self.filehandle = None
elif self.filename:
cv2.SaveImage(self.filename, img_save.bitmap)
else:
return 0
if verbose:
print(self.filename)
if tmp:
return filename
else:
return 1
def copy(self):
"""
Return a full copy of the Image's bitmap. Note that this is different
from using python's implicit copy function in that only the bitmap itself
is copied. This method essentially performs a deep copy.
:return: a copy of this Image
:Example:
>>> img = Image('lena')
>>> img2 = img.copy()
"""
img = self.zeros()
cv2.Copy(self.bitmap, img)
return Image(img, colorspace=self._color_space)
def scale(self, scalar, interp=cv2.INTER_LINEAR):
"""
Scale the image to a new width and height.
If no height is provided, the width is considered a scaling value
:param scalar: scalar to scale
:param interp: how to generate new pixels that don't match the original
pixels. Argument goes direction to cv2.Resize.
See http://docs.opencv2.org/modules/imgproc/doc/geometric_transformations.html?highlight=resize#cv2.resize for more details
:return: resized image.
:Example:
>>> img.scale(2.0)
"""
if scalar is not None:
w = int(self.width * scalar)
h = int(self.height * scalar)
if w > MAX_DIMS or h > MAX_DIMS or h < 1 or w < 1:
logger.warning("You tried to make an image really big or "
"impossibly small. I can't scale that")
return self
else:
return self
scaled_array = np.zeros((w, h, 3), dtype='uint8')
ret = cv2.resize(self.cvnarray, (w, h), interpolation=interp)
return Image(ret, color_space=self._color_space, cv2image=True)
def resize(self, width=None, height=None):
"""
Resize an image based on a width, a height, or both.
If either width or height is not provided the value is inferred by
keeping the aspect ratio. If both values are provided then the image
is resized accordingly.
:param width: width of the output image in pixels.
:param height: height of the output image in pixels.
:return:
Returns a resized image, if the size is invalid a warning is issued and
None is returned.
:Example:
>>> img = Image("lenna")
>>> img2 = img.resize(w=1024) # h is guessed from w
>>> img3 = img.resize(h=1024) # w is guessed from h
>>> img4 = img.resize(w=200,h=100)
"""
ret = None
if width is None and height is None:
logger.warning("Image.resize has no parameters. No operation is "
"performed")
return None
elif width is not None and height is None:
sfactor = float(width) / float(self.width)
height = int(sfactor * float(self.height))
elif width is None and height is not None:
sfactor = float(height) / float(self.height)
width = int(sfactor * float(self.width))
if width > MAX_DIMS or height > MAX_DIMS:
logger.warning("Image.resize! You tried to make an image really"
" big or impossibly small. I can't scale that")
return ret
scaled_bitmap = cv2.CreateImage((width, height), 8, 3)
cv2.Resize(self.bitmap, scaled_bitmap)
return Image(scaled_bitmap, color_space=self._color_space)
def smooth(self, method='gaussian', aperture=(3, 3), sigma=0,
spatial_sigma=0, grayscale=False):
"""
Smooth the image, by default with the Gaussian blur. If desired,
additional algorithms and apertures can be specified. Optional
parameters are passed directly to OpenCV's cv2.Smooth() function.
If grayscale is true the smoothing operation is only performed
on a single channel otherwise the operation is performed on
each channel of the image. for OpenCV versions >= 2.3.0 it is
advisible to take a look at
- bilateralFilter
- medianFilter
- blur
- gaussianBlur
:param method: valid options are 'blur' or 'gaussian', 'bilateral',
and 'median'.
:param aperture: a tuple for the window size of the gaussian blur as
an (x,y) tuple. should be odd
:param sigma:
:param spatial_sigma:
:param grayscale: return grayscale image
:return: the smoothed image.
:Example:
>>> img = Image('lena')
>>> img2 = img.smooth()
>>> img3 = img.smooth('median')
"""
# TODO: deprecated function -istuple-
if istuple(aperture):
win_x, win_y = aperture
if win_x <= 0 or win_y <= 0 or win_x % 2 == 0 or win_y % 2 == 0:
logger.warning('The size must be odd number and greater than 0')
return None
else:
raise ValueError('Please provide a tuple to aperture')
if method == 'blur':
m = cv2.CV_BLUR
elif method == 'bilateral':
m = cv2.CV_BILATERAL
win_y = win_x # aperture must be square
elif method == 'median':
m = cv2.CV_MEDIAN
win_y = win_x # aperture must be square
else:
m = cv2.CV_GAUSSIAN # default method
if grayscale:
new_img = self.zeros(1)
cv2.Smooth(self._get_gray_narray(), new_img, method, win_x, win_y,
sigma, spatial_sigma)
else:
new_img = self.zeros(3)
r = self.zeros(1)
g = self.zeros(1)
b = self.zeros(1)
ro = self.zeros(1)
go = self.zeros(1)
bo = self.zeros(1)
cv2.Split(self.bitmap, b, g, r, None)
cv2.Smooth(r, ro, method, win_x, win_y, sigma, spatial_sigma)
cv2.Smooth(g, go, method, win_x, win_y, sigma, spatial_sigma)
cv2.Smooth(b, bo, method, win_x, win_y, sigma, spatial_sigma)
cv2.Merge(bo, go, ro, None, new_img)
return Image(new_img, color_space=self._color_space)
def median_filter(self, window=(3, 3), grayscale=False):
"""
Smooths the image, with the median filter. Performs a median
filtering operation to denoise/despeckle the image.
The optional parameter is the window size.
:param window: should be in the form a tuple (win_x,win_y).
Where win_x should be equal to win_y. By default
it is set to 3x3, i.e window = (3, | |
<gh_stars>0
# -*- coding: utf-8 -*-
'''
saveLoadableOIM.py is an example of a plug-in that will save a re-loadable JSON or CSV instance.
(c) Copyright 2015 Mark V Systems Limited, All rights reserved.
'''
import sys, os, io, time, re, json, csv
from decimal import Decimal
from math import isinf, isnan
from collections import defaultdict, OrderedDict
from arelle import ModelDocument, XbrlConst
from arelle.ModelInstanceObject import ModelFact
from arelle.ModelValue import (qname, QName, DateTime, YearMonthDuration,
dayTimeDuration, DayTimeDuration, yearMonthDayTimeDuration, Time,
gYearMonth, gMonthDay, gYear, gMonth, gDay)
from arelle.ModelRelationshipSet import ModelRelationshipSet
from arelle.ValidateXbrlCalcs import inferredDecimals
from arelle.XmlUtil import dateunionValue, elementIndex, xmlstring
from collections import defaultdict
nsOim = "http://www.xbrl.org/DPWD/2016-01-13/oim"
qnOimConceptAspect = qname(nsOim, "oim:concept")
qnOimTypeAspect = qname(nsOim, "oim:type")
qnOimLangAspect = qname(nsOim, "oim:language")
qnOimTupleParentAspect = qname(nsOim, "oim:tupleParent")
qnOimTupleOrderAspect = qname(nsOim, "oim:tupleOrder")
qnOimPeriodAspect = qname(nsOim, "oim:period")
qnOimPeriodStartAspect = qname(nsOim, "oim:periodStart")
qnOimPeriodDurationAspect = qname(nsOim, "oim:periodDuration")
qnOimEntityAspect = qname(nsOim, "oim:entity")
qnOimUnitAspect = qname(nsOim, "oim:unit")
qnOimUnitNumeratorsAspect = qname(nsOim, "oim:unitNumerators")
qnOimUnitDenominatorsAspect = qname(nsOim, "oim:unitDenominators")
ONE = Decimal(1)
TEN = Decimal(10)
NILVALUE = "nil"
SCHEMA_LB_REFS = {qname("{http://www.xbrl.org/2003/linkbase}schemaRef"),
qname("{http://www.xbrl.org/2003/linkbase}linkbaseRef")}
ROLE_REFS = {qname("{http://www.xbrl.org/2003/linkbase}roleRef"),
qname("{http://www.xbrl.org/2003/linkbase}arcroleRef")}
if sys.version[0] >= '3':
csvOpenMode = 'w'
csvOpenNewline = ''
else:
csvOpenMode = 'wb' # for 2.7
csvOpenNewline = None
def saveLoadableOIM(modelXbrl, oimFile):
isJSON = oimFile.endswith(".json")
isCSV = oimFile.endswith(".csv")
namespacePrefixes = {}
def compileQname(qname):
if qname.namespaceURI not in namespacePrefixes:
namespacePrefixes[qname.namespaceURI] = qname.prefix or ""
aspectsDefined = {
qnOimConceptAspect,
qnOimEntityAspect,
qnOimTypeAspect}
if isJSON:
aspectsDefined.add(qnOimPeriodAspect)
elif isCSV:
aspectsDefined.add(qnOimPeriodStartAspect)
aspectsDefined.add(qnOimPeriodDurationAspect)
def oimValue(object, decimals=None):
if isinstance(object, QName):
if object.namespaceURI not in namespacePrefixes:
if object.prefix:
namespacePrefixes[object.namespaceURI] = object.prefix
else:
_prefix = "_{}".format(sum(1 for p in namespacePrefixes if p.startswith("_")))
namespacePrefixes[object.namespaceURI] = _prefix
return "{}:{}".format(namespacePrefixes[object.namespaceURI], object.localName)
if isinstance(object, Decimal):
try:
if isinf(object):
return "-INF" if object < 0 else "INF"
elif isnan(num):
return "NaN"
else:
if object == object.to_integral():
object = object.quantize(ONE) # drop any .0
return "{}".format(object)
except:
return str(object)
if isinstance(object, bool):
return object
if isinstance(object, (DateTime, YearMonthDuration, DayTimeDuration, Time,
gYearMonth, gMonthDay, gYear, gMonth, gDay)):
return str(object)
return object
def oimPeriodValue(cntx):
if cntx.isForeverPeriod:
if isCSV:
return "0000-01-01T00:00:00/P9999Y"
return "forever"
elif cntx.isStartEndPeriod:
d = cntx.startDatetime
duration = yearMonthDayTimeDuration(cntx.startDatetime, cntx.endDatetime)
else: # instant
d = cntx.instantDatetime
duration = "PT0S"
return "{0:04n}-{1:02n}-{2:02n}T{3:02n}:{4:02n}:{5:02n}/{6}".format(
d.year, d.month, d.day, d.hour, d.minute, d.second,
duration)
hasId = False
hasTuple = False
hasType = True
hasLang = False
hasUnits = False
hasUnitMulMeasures = False
hasUnitDivMeasures = False
footnotesRelationshipSet = ModelRelationshipSet(modelXbrl, "XBRL-footnotes")
#compile QNames in instance for OIM
for fact in modelXbrl.factsInInstance:
if (fact.id or fact.isTuple or
footnotesRelationshipSet.toModelObject(fact) or
(isCSV and footnotesRelationshipSet.fromModelObject(fact))):
hasId = True
concept = fact.concept
if concept is not None:
if concept.baseXbrliType in ("string", "normalizedString", "token") and fact.xmlLang:
hasLang = True
compileQname(fact.qname)
if hasattr(fact, "xValue") and isinstance(fact.xValue, QName):
compileQname(fact.xValue)
unit = fact.unit
if unit is not None:
hasUnits = True
if unit.measures[0]:
hasUnitMulMeasures = True
if unit.measures[1]:
hasUnitDivMeasures = True
if fact.modelTupleFacts:
hasTuple = True
entitySchemePrefixes = {}
for cntx in modelXbrl.contexts.values():
if cntx.entityIdentifierElement is not None:
scheme = cntx.entityIdentifier[0]
if scheme not in entitySchemePrefixes:
if not entitySchemePrefixes: # first one is just scheme
if scheme == "http://www.sec.gov/CIK":
_schemePrefix = "cik"
elif scheme == "http://standard.iso.org/iso/17442":
_schemePrefix = "lei"
else:
_schemePrefix = "scheme"
else:
_schemePrefix = "scheme{}".format(len(entitySchemePrefixes) + 1)
entitySchemePrefixes[scheme] = _schemePrefix
namespacePrefixes[scheme] = _schemePrefix
for dim in cntx.qnameDims.values():
compileQname(dim.dimensionQname)
aspectsDefined.add(dim.dimensionQname)
if dim.isExplicit:
compileQname(dim.memberQname)
for unit in modelXbrl.units.values():
if unit is not None:
for measures in unit.measures:
for measure in measures:
compileQname(measure)
if unit.measures[0]:
aspectsDefined.add(qnOimUnitNumeratorsAspect)
if unit.measures[1]:
aspectsDefined.add(qnOimUnitDenominatorsAspect)
if XbrlConst.xbrli in namespacePrefixes and namespacePrefixes[XbrlConst.xbrli] != "xbrli":
namespacePrefixes[XbrlConst.xbrli] = "xbrli" # normalize xbrli prefix
namespacePrefixes[XbrlConst.xsd] = "xsd"
if hasLang: aspectsDefined.add(qnOimLangAspect)
if hasTuple:
aspectsDefined.add(qnOimTupleParentAspect)
aspectsDefined.add(qnOimTupleOrderAspect)
if hasUnits: aspectsDefined.add(qnOimUnitAspect)
# compile footnotes and relationships
'''
factRelationships = []
factFootnotes = []
for rel in modelXbrl.relationshipSet(modelXbrl, "XBRL-footnotes").modelRelationships:
oimRel = {"linkrole": rel.linkrole, "arcrole": rel.arcrole}
factRelationships.append(oimRel)
oimRel["fromIds"] = [obj.id if obj.id
else elementChildSequence(obj)
for obj in rel.fromModelObjects]
oimRel["toIds"] = [obj.id if obj.id
else elementChildSequence(obj)
for obj in rel.toModelObjects]
_order = rel.arcElement.get("order")
if _order is not None:
oimRel["order"] = _order
for obj in rel.toModelObjects:
if isinstance(obj, ModelResource): # footnote
oimFootnote = {"role": obj.role,
"id": obj.id if obj.id
else elementChildSequence(obj),
# value needs work for html elements and for inline footnotes
"value": xmlstring(obj, stripXmlns=True)}
if obj.xmlLang:
oimFootnote["lang"] = obj.xmlLang
factFootnotes.append(oimFootnote)
oimFootnote
'''
dtsReferences = [
{"type": "schema" if doc.type == ModelDocument.Type.SCHEMA
else "linkbase" if doc.type == ModelDocument.Type.LINKBASE
else "other",
"href": doc.uri}
for doc,ref in modelXbrl.modelDocument.referencesDocument.items()
if ref.referringModelObject.qname in SCHEMA_LB_REFS]
'''
roleTypes = [
{"type": "role" if ref.referringModelObject.localName == "roleRef" else "arcroleRef",
"href": ref.referringModelObject["href"]}
for doc,ref in modelXbrl.modelDocument.referencesDocument.items()
if ref.referringModelObject.qname in ROLE_REFS]
'''
def factFootnotes(fact):
footnotes = []
for footnoteRel in footnotesRelationshipSet.fromModelObject(fact):
footnote = OrderedDict((("group", footnoteRel.arcrole),))
footnotes.append(footnote)
if isCSV:
footnote["factId"] = fact.id if fact.id else "f{}".format(fact.objectIndex)
toObj = footnoteRel.toModelObject
if isinstance(toObj, ModelFact):
footnote["factRef"] = toObj.id if toObj.id else "f{}".format(toObj.objectIndex)
else:
footnote["footnoteType"] = toObj.role
footnote["footnote"] = xmlstring(toObj, stripXmlns=True, contentsOnly=True, includeText=True)
if toObj.xmlLang:
footnote["language"] = toObj.xmlLang
return footnotes
def factAspects(fact):
aspects = OrderedDict()
if hasId and fact.id:
aspects["id"] = fact.id
elif (fact.isTuple or
footnotesRelationshipSet.toModelObject(fact) or
(isCSV and footnotesRelationshipSet.fromModelObject(fact))):
aspects["id"] = "f{}".format(fact.objectIndex)
parent = fact.getparent()
concept = fact.concept
if not fact.isTuple:
if concept is not None:
_baseXsdType = concept.baseXsdType
if _baseXsdType == "XBRLI_DATEUNION":
if getattr(fact.xValue, "dateOnly", False):
_baseXsdType = "date"
else:
_baseXsdType = "dateTime"
aspects["baseType"] = "xs:{}".format(_baseXsdType)
if concept.baseXbrliType in ("string", "normalizedString", "token") and fact.xmlLang:
aspects[qnOimLangAspect] = fact.xmlLang
aspects[qnOimTypeAspect] = concept.baseXbrliType
if fact.isItem:
if fact.isNil:
_value = None
_strValue = "nil"
else:
_inferredDecimals = inferredDecimals(fact)
_value = oimValue(fact.xValue, _inferredDecimals)
_strValue = str(_value)
if not isCSV:
aspects["value"] = _strValue
if fact.concept is not None and fact.concept.isNumeric:
_numValue = fact.xValue
if isinstance(_numValue, Decimal) and not isinf(_numValue) and not isnan(_numValue):
if _numValue == _numValue.to_integral():
_numValue = int(_numValue)
else:
_numValue = float(_numValue)
aspects["numericValue"] = _numValue
if not fact.isNil:
if isinf(_inferredDecimals):
if isJSON: _accuracy = "infinity"
elif isCSV: _accuracy = "INF"
else:
_accuracy = _inferredDecimals
aspects["accuracy"] = _inferredDecimals
elif isinstance(_value, bool):
aspects["booleanValue"] = _value
elif isCSV:
aspects["stringValue"] = _strValue
aspects[qnOimConceptAspect] = oimValue(fact.qname)
cntx = fact.context
if cntx is not None:
if cntx.entityIdentifierElement is not None:
aspects[qnOimEntityAspect] = oimValue(qname(*cntx.entityIdentifier))
if cntx.period is not None:
if isJSON:
aspects[qnOimPeriodAspect] = oimPeriodValue(cntx)
elif isCSV:
_periodValue = oimPeriodValue(cntx).split("/") + ["", ""] # default blank if no value
aspects[qnOimPeriodStartAspect] = _periodValue[0]
aspects[qnOimPeriodDurationAspect] = _periodValue[1]
for _qn, dim in sorted(cntx.qnameDims.items(), key=lambda item: item[0]):
aspects[dim.dimensionQname] = (oimValue(dim.memberQname) if dim.isExplicit
else None if dim.typedMember.get("{http://www.w3.org/2001/XMLSchema-instance}nil") in ("true", "1")
else dim.typedMember.stringValue)
unit = fact.unit
if unit is not None:
_mMul, _mDiv = unit.measures
if isJSON:
aspects[qnOimUnitAspect] = OrderedDict( # use tuple instead of list for hashability
(("numerators", tuple(oimValue(m) for m in sorted(_mMul, key=lambda m: oimValue(m)))),)
)
if _mDiv:
aspects[qnOimUnitAspect]["denominators"] = tuple(oimValue(m) for m in sorted(_mDiv, key=lambda m: oimValue(m)))
else: # CSV
if _mMul:
aspects[qnOimUnitNumeratorsAspect] = " ".join(oimValue(m)
for m in sorted(_mMul, key=lambda m: str(m)))
if _mDiv:
aspects[qnOimUnitDenominatorsAspect] = " ".join(oimValue(m)
for m in sorted(_mDiv, key=lambda m: str(m)))
if parent.qname != XbrlConst.qnXbrliXbrl:
aspects[qnOimTupleParentAspect] = parent.id if parent.id else "f{}".format(parent.objectIndex)
aspects[qnOimTupleOrderAspect] = elementIndex(fact)
if isJSON:
_footnotes = factFootnotes(fact)
if _footnotes:
aspects["footnotes"] = _footnotes
return aspects
if isJSON:
# save JSON
oimReport = OrderedDict() # top level of oim json output
oimFacts = []
oimReport["prefixes"] = OrderedDict((p,ns) for ns, p in sorted(namespacePrefixes.items(),
key=lambda item: item[1]))
oimReport["dtsReferences"] = dtsReferences
oimReport["facts"] = oimFacts
def saveJsonFacts(facts, oimFacts, parentFact):
for fact in facts:
oimFact = factAspects(fact)
oimFacts.append(OrderedDict((str(k),v) for k,v in oimFact.items()))
if fact.modelTupleFacts:
saveJsonFacts(fact.modelTupleFacts, oimFacts, fact)
saveJsonFacts(modelXbrl.facts, oimFacts, None)
with open(oimFile, "w", encoding="utf-8") as fh:
fh.write(json.dumps(oimReport, ensure_ascii=False, indent=1, sort_keys=False))
elif isCSV:
# save CSV
aspectQnCol = {}
aspectsHeader = []
factsColumns = []
def addAspectQnCol(aspectQn):
aspectQnCol[aspectQn] = len(aspectsHeader)
_colName = oimValue(aspectQn)
aspectsHeader.append(_colName)
_colDataType = {"id": "Name",
"baseType": "Name",
"oim:concept": "Name",
"oim:periodStart": "dateTime", # forever is 0000-01-01T00:00:00
"oim:periodDuration": "duration", # forever is P9999Y
"oim:tupleOrder": "integer",
"numericValue": "decimal",
"accuracy": "decimal",
"booleanValue": "boolean",
"oim:unitNumerators": OrderedDict((("base","Name"), ("separator"," "))),
"oim:unitDenominators": OrderedDict((("base","Name"), ("separator"," "))),
}.get(_colName, "string")
factsColumns.append(OrderedDict((("name", _colName),
("datatype", _colDataType))))
# pre-ordered aspect columns
if hasId:
addAspectQnCol("id")
if hasType:
addAspectQnCol("baseType")
addAspectQnCol("stringValue")
addAspectQnCol("numericValue")
addAspectQnCol("accuracy")
addAspectQnCol("booleanValue")
if hasTuple:
addAspectQnCol(qnOimTupleParentAspect)
addAspectQnCol(qnOimTupleOrderAspect)
addAspectQnCol(qnOimConceptAspect)
if qnOimEntityAspect in aspectsDefined:
addAspectQnCol(qnOimEntityAspect)
if qnOimPeriodStartAspect in aspectsDefined:
addAspectQnCol(qnOimPeriodStartAspect)
addAspectQnCol(qnOimPeriodDurationAspect)
if qnOimUnitNumeratorsAspect in aspectsDefined:
addAspectQnCol(qnOimUnitNumeratorsAspect)
if qnOimUnitDenominatorsAspect in aspectsDefined:
| |
'''
Created on 2020-06-20
@author: wf
'''
import yaml
import io
import json
import jsons
import os
import re
from collections import OrderedDict
from pyparsing import Keyword,Group,Word,OneOrMore,Optional,ParseResults,Regex,ZeroOrMore,alphas, nums, oneOf
# wait for version 3
#from pyparsing.diagram import to_railroad, railroad_to_html
from num2words import num2words
from collections import Counter
from dicttoxml import dicttoxml
from xml.dom.minidom import parseString
from lodstorage.plot import Plot
class TitleParser(object):
'''
parser for Proceeding titles
'''
def __init__(self,name=None,lookup=None,ptp=None,dictionary=None,ems=None):
'''
Constructor
'''
self.name=name
self.lookup=lookup
self.ptp=ptp
if dictionary is None and ptp is not None:
ptpdictionary=ptp.getDictionary()
if ptpdictionary is not None:
self.dictionary=ptpdictionary
else:
self.dictionary=dictionary
self.ems=ems
self.records=[]
@staticmethod
def getDefault(name=None):
ptp=ProceedingsTitleParser.getInstance()
tp=TitleParser(name,ptp=ptp)
return tp
def parseAll(self):
''' get parse result with the given proceedings title parser, entity manager and list of titles '''
errs=[]
result=[]
tc=Counter()
for record in self.records:
eventTitle=record['title']
if eventTitle is not None:
title=Title(eventTitle,self.ptp.grammar,dictionary=self.dictionary)
for key in ['source','proceedingsUrl']:
if key in record:
title.info[key]=record[key]
if 'eventId' in record:
title.info['eventId']=record['eventId']
try:
notfound=title.parse()
title.pyparse()
tc["success"]+=1
except Exception as ex:
tc["fail"]+=1
errs.append(ex)
if self.ems is not None:
title.lookup(self.ems,notfound)
result.append(title)
return tc,errs,result
def asJson(self,result):
'''convert the given result to JSON '''
events=[]
for title in result:
events.extend(title.events)
jsonResult={"count": len(events), "events": events}
jsons.suppress_warnings()
jsonText=jsons.dumps(jsonResult,indent=4,sort_keys=True)
return jsonText
def getEventDicts(self,result):
'''
get the results as a list of event dicts
'''
events=[]
for title in result:
for event in title.events:
events.append(event.__dict__)
return events
def asXml(self,result,pretty=True):
''' convert result to XML'''
events=self.getEventDicts(result)
item_name = lambda x: "event"
xml=dicttoxml(events, custom_root='events',item_func=item_name, attr_type=False)
if pretty:
dom=parseString(xml)
prettyXml=dom.toprettyxml()
else:
prettyXml=xml
return prettyXml
def fromLines(self,lines,mode='wikidata',clear=True):
''' get my records from the given lines using the given mode '''
if clear:
self.records=[]
''' add records from the given lines '''
for line in lines:
if mode=="wikidata":
if "@en" in line and "Proceedings of" in line:
line=line.strip()
parts=line.split('"')
subject=parts[0]
qref=subject.split("<")[1]
qref=qref.split(">")[0]
title=parts[1]
self.records.append({'source':'wikidata','eventId': qref, 'title': title})
elif mode=="dblp":
m=re.match("<title>(.*)</title>",line)
if m:
title=m.groups()[0]
self.records.append({'title': title})
elif mode=="CEUR-WS":
parts=line.strip().split("|")
title=parts[0]
vol=None
partlen=len(parts)
if partlen>1:
idpart=parts[partlen-1]
# id=Vol-2534
vol=idpart.split("=")[1]
self.records.append({'source':'CEUR-WS','eventId': vol,'title': title})
elif mode=="line":
title=line.strip()
# DOI
# https://www.crossref.org/blog/dois-and-matching-regular-expressions/
if re.match(r'^10.\d{4,9}\/.*',title):
if self.lookup:
record=self.lookup.extractFromDOI(title)
self.records.append(record)
# URL
elif title.startswith('http'):
if self.lookup:
record=self.lookup.extractFromUrl(title)
if record is not None:
self.records.append(record)
else:
self.records.append({'source':'line', 'title': title})
else:
raise Exception("unknown mode %s" % (mode))
def fromFile(self,filePath,mode='wikidata'):
''' read all lines from the given filePath and return a Parser '''
with open(filePath) as f:
lines=f.readlines()
self.fromLines(lines,mode)
class ProceedingsTitleParser(object):
''' a pyparsing based parser for Proceedings Titles supported by a dictionary'''
year=Regex(r'(19|20)?[0123456789][0123456789]')
acronymGroup=Optional("("+Group(Word(alphas)+Optional(year))("acronym")+")")
instance=None
@staticmethod
def getInstance():
''' get a singleton instance of the ProceedingsTitleParser '''
if ProceedingsTitleParser.instance is None:
d=ProceedingsTitleParser.getDictionary()
ProceedingsTitleParser.instance=ProceedingsTitleParser(d)
return ProceedingsTitleParser.instance
@staticmethod
def getDictionary():
path=os.path.dirname(__file__)
d=Dictionary.fromFile(path+"/../dictionary.yaml")
return d
def __init__(self, dictionary):
''' constructor
'''
self.dictionary=dictionary
proc=Keyword("Proceedings") | Keyword("proceedings")
descWord=~proc + Word(alphas+nums+"™æéç)>/'&—‐") # watch the utf-8 dash!
initials="("+OneOrMore(Word(alphas)+".")+")"
desc=Optional("[")+OneOrMore(descWord|initials)+oneOf(". ? : ( , ; -")
enumGroup=dictionary.getGroup("enum")
scopeGroup=dictionary.getGroup("scope")
eventGroup=dictionary.getGroup("eventType")
freqGroup=dictionary.getGroup("frequency")
yearGroup=dictionary.getGroup("year")
cityGroup=dictionary.getGroup("city")
provinceGroup=dictionary.getGroup("province")
countryGroup=dictionary.getGroup("country")
eventClause=dictionary.getClause("eventType")
monthGroup=dictionary.getGroup("month")
extractGroup=dictionary.getGroup("extract")
dateRangeGroup=Group(Optional(Word(nums)+Optional("-"+Word(nums))))("daterange")
prefixGroup=Group(ZeroOrMore(~oneOf(eventClause)+Word(alphas+nums)))("prefix")
topicGroup=Group(ZeroOrMore(~oneOf("held on")+Word(alphas+nums+"-&")))("topic")
part="Part"+oneOf("A B C 1 2 3 4 I II III IV")+"."
whereAndWhen=Optional(oneOf([".",",","held on"])+dateRangeGroup+monthGroup+dateRangeGroup \
+Optional(oneOf(","))+yearGroup \
+Optional(oneOf(","))+cityGroup \
+Optional(oneOf(","))+provinceGroup \
+Optional(oneOf(","))+countryGroup \
+Group(Optional(Word(alphas)))("location"))
self.grammar=Group(ZeroOrMore(desc))("description") \
+Optional(part) \
+Optional(oneOf("[ Conference Scientific")) \
+extractGroup+Optional(oneOf("the The"))+Optional("Official") \
+proc+"of"+Optional(oneOf("the a an")) \
+yearGroup \
+enumGroup \
+freqGroup \
+scopeGroup \
+prefixGroup \
+Optional(oneOf("Scientific Consensus"))+eventGroup \
+Optional(oneOf("on of in :")) \
+topicGroup \
+ProceedingsTitleParser.acronymGroup \
+Optional(oneOf("] )")) \
+whereAndWhen
pass
class Title(object):
''' a single Proceedings title '''
special=['.',',',':','[',']','"','(',')']
def __init__(self,line,grammar=None,dictionary=None):
''' construct me from the given line and dictionary '''
self.line=line
if line and dictionary is not None:
for blanktoken in dictionary.blankTokens:
blankless=blanktoken.replace(" ","_")
line=line.replace(blanktoken,blankless)
if self.line:
self.tokens=re.split(r'[ ,.()"\[\]]',line)
else:
self.tokens=[]
self.dictionary=dictionary
self.enum=None
self.parseResult=None
self.grammar=grammar
self.info={'title':line}
self.md=None
self.events=[]
def addSearchResults(self,ems,search):
''' add search results from the given event managers with the given search keyword
FIXME: a search for e.g CA 2008 does not make much sense since the word CA is ambigous and
probably a province CA=California and not an Acronym
'''
for em in ems:
events=em.lookup(search)
for event in events:
event.foundBy=search
self.events=self.events+events
def lookup(self,ems,wordList=None):
''' look me up with the given event manager use my acronym or optionally a list of Words'''
if "acronym" in self.metadata():
acronym=self.md["acronym"]
if acronym is not None:
self.addSearchResults(ems, acronym)
# last resort search
if len(self.events)==0:
if wordList is not None and "year" in self.info:
year=self.info["year"]
for word in wordList:
self.addSearchResults(ems, word+" "+year)
def __str__(self):
''' create a string representation of this title '''
text=""
delim=""
if self.parseResult is not None:
for pitem in self.parseResult:
if isinstance(pitem,ParseResults):
text+="%s%s=%s" % (delim,pitem.getName(),pitem)
delim="\n"
return text
def hasUrl(self):
result='proceedingsUrl' in self.info or 'url' in self.info
return result
def getUrl(self):
for key in ['proceedingsUrl','url']:
if key in self.info:
return self.info[key]
return None
def asJson(self):
events=[]
events.extend(self.events)
jsonResult={"count": len(self.events), "events": events}
jsonText=json.dumps(jsonResult,indent=4,sort_keys=True)
return jsonText
def metadata(self):
''' extract the metadata of the given title '''
if self.md is None:
# initialize with None values
self.md={
'enum': None,
'description': None,
'delimiter': None,
'daterange': None,
'eventType': None,
'extract': None,
'field': None,
'frequency': None,
'location': None,
'lookupAcronym': None,
'month': None,
'ordinal': None,
'organization': None,
'prefix': None,
'province': None,
'publish': None,
'scope': None,
'syntax': None,
'topic': None,
'year': None
}
if self.parseResult is not None:
for pitem in self.parseResult:
if isinstance(pitem,ParseResults):
value=" ".join(pitem.asList())
if value:
name=pitem.getName()
self.md[name]=value
if self.info is not None:
for name in self.info:
value=self.info[name]
# value is not None per definition
# mdValue might be None
if (not name in self.md) or (self.md[name] is None):
self.md[name]=value
if self.md['year'] is not None:
self.md['year']=int(self.md['year'])
return self.md
def metadataDump(self):
md=self.metadata()
jsonText=json.dumps(md,indent=4,sort_keys=True)
return jsonText
def dump(self):
''' debug print my parseResult '''
print (self.parseResult)
for pitem in self.parseResult:
if isinstance(pitem,ParseResults):
print ("%s=%s" % (pitem.getName(),pitem))
else:
print (pitem)
pass
def parse(self):
'''
parse with dictionary lookup
'''
self.notfound=[]
for token in self.tokens:
dtoken=self.dictionary.getToken(token)
# if ther is a dictionary result
if dtoken is not None:
# for the kind e.g. enum, country, city ...
lookup=dtoken["type"]
# do not set same token e.g. enum twice
if not lookup in token:
if lookup=="enum":
self.info['ordinal']=dtoken["value"]
# set the value for the token
self.info[lookup]=token
else:
self.notfound.append(self.dictionary.searchToken(token))
return self.notfound
def pyparse(self):
if self.grammar is not None:
self.parseResult=self.grammar.parseString(self.line)
class Dictionary(object):
''' a dictionary to support title parsing '''
def __init__(self):
self.blankTokens={}
pass
def countType(self,tokenType):
clause=self.getClause(tokenType)
return len(clause)
def getClause(self,tokenType):
''' get a clause to be used for OneOf pyparsing Operator from dictionary for the given type'''
clause=[]
for key in self.tokens:
entry=self.tokens[key]
if entry["type"]==tokenType:
clause.append(key)
return clause
def getGroup(self,tokenType):
''' get a group for the given token Type'''
clause=self.getClause(tokenType)
group=Group(Optional(oneOf(clause)))(tokenType)
return group
def searchToken(self,token):
''' replace the given token with it's search equivalent by removing special chars '''
search=token
for special in Title.special:
search=token.replace(special,'')
return search
def getToken(self,token):
''' check if this dictionary contains the given token '''
token=token.replace('_',' ') # restore blank
search=self.searchToken(token)
if search in self.tokens:
dtoken=self.tokens[search]
dtoken["label"]=search
return dtoken
return None
@staticmethod
def fromFile(yamlPath):
d=Dictionary()
d.yamlPath=yamlPath
d.read()
d.blankHandling()
return d
def blankHandling(self):
''' handle tokens that contain spaces e.g. "Great Britain", "San Francisco", "New York", "United States"'''
for token in self.tokens:
if " " in token:
self.blankTokens[token]=token
def read(self,yamlPath=None):
''' read the dictionary from the given yaml path'''
if yamlPath is None:
yamlPath=self.yamlPath
with open(yamlPath, 'r') as stream:
self.tokens = yaml.safe_load(stream)
pass
def write(self,yamlPath=None):
''' write the dictionary to a yaml file given py the yamlPath '''
if yamlPath is None:
yamlPath=self.yamlPath
sortedTokens=OrderedDict(sorted(self.tokens.items(), key=lambda x: x[1]['type']))
self.tokens=dict(sortedTokens)
# Write YAML file
with io.open(yamlPath, 'w', encoding='utf8') as outfile:
yaml.dump(self.tokens, outfile, default_flow_style=False, sort_keys=False,allow_unicode=True)
with open(yamlPath, 'r') as original: data = original.read()
comment="""#
# Proceedings title dictionary
#
"""
with open(yamlPath, 'w') as modified: modified.write(comment + data)
def add(self,token,tokenType,value=None):
''' add or replace the token with the given type to the dictionary '''
lookup={}
lookup['type']=tokenType
if value is not None:
lookup['value']=value
self.tokens[token]=lookup
def addEnums(self):
''' add enumerations '''
# https://stackoverflow.com/a/20007730/1497139
ordinal = lambda n: "%d%s" % (n,"tsnrhtdd"[(n/10%10!=1)*(n%10<4)*n%10::4])
for i in range(1,100):
roman=self.toRoman(i)+"."
self.add("%d." % i,'enum',i)
self.add(ordinal(i),'enum',i)
self.add(roman,'enum',i)
ordinal4i=num2words(i, to='ordinal')
self.add(ordinal4i,'enum',i)
title=ordinal4i.title()
self.add(title,'enum',i)
def addYears(self):
for year in range(1960,2030):
self.add("%d" % year,'year',year)
def toRoman(self,number):
''' https://stackoverflow.com/a/11749642/1497139 '''
if (number < 0) or (number > 3999):
raise Exception("number needs | |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'Akshita.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(847, 514)
font = QtGui.QFont()
font.setFamily("URW Bookman [UKWN]")
font.setItalic(True)
Form.setFont(font)
Form.setStyleSheet("QWidget { border: 0; \n"
"\n"
"background-color: rgb(49, 122, 210);}\n"
"")
self.verticalLayout = QtWidgets.QVBoxLayout(Form)
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
self.verticalLayout.setSpacing(0)
self.verticalLayout.setObjectName("verticalLayout")
self.frame = QtWidgets.QFrame(Form)
font = QtGui.QFont()
font.setFamily("Nimbus Sans Narrow [urw]")
self.frame.setFont(font)
self.frame.setAutoFillBackground(False)
self.frame.setStyleSheet("QFrame{\n"
"background-color: rgb(2, 119, 189);\n"
"border:2px;\n"
"border-radius:30px;}\n"
"\n"
"QFrame::pane{\n"
"border:0;}\n"
"\n"
"/* VERTICAL SCROLLBAR */\n"
" QScrollBar:vertical {\n"
" border: none; \n"
" background-color: rgb(209, 209, 209);\n"
" width: 14px;\n"
" margin: 15px 0 15px 0;\n"
" border-radius: 0px;\n"
" }\n"
"\n"
"/* HANDLE BAR VERTICAL */\n"
"QScrollBar::handle:vertical { \n"
" background-color: rgb(119, 118, 123);\n"
" min-height: 30px;\n"
" border-radius: 7px;\n"
"}\n"
"QScrollBar::handle:vertical:hover{ \n"
" \n"
" background-color: rgb(255, 255, 127);\n"
"}\n"
"QScrollBar::handle:vertical:pressed { \n"
" \n"
" background-color:rgb(255, 255, 127);\n"
"}\n"
"\n"
"/* BTN TOP - SCROLLBAR */\n"
"QScrollBar::sub-line:vertical {\n"
" border: none;\n"
" background-color: rgb(119, 118, 123); \n"
" height: 15px;\n"
" border-top-left-radius: 7px;\n"
" border-top-right-radius: 7px;\n"
" subcontrol-position: top;\n"
" subcontrol-origin: margin;\n"
"}\n"
"QScrollBar::sub-line:vertical:hover { \n"
" background-color:rgb(255, 255, 127);\n"
"}\n"
"QScrollBar::sub-line:vertical:pressed { \n"
" background-color:rgb(255, 255, 127);\n"
"}\n"
"\n"
"/* BTN BOTTOM - SCROLLBAR */\n"
"QScrollBar::add-line:vertical {\n"
" border: none;\n"
" background-color: rgb(119, 118, 123);\n"
" height: 15px;\n"
" border-bottom-left-radius: 7px;\n"
" border-bottom-right-radius: 7px;\n"
" subcontrol-position: bottom;\n"
" subcontrol-origin: margin;\n"
"}\n"
"QScrollBar::add-line:vertical:hover { \n"
" background-color:rgb(255, 255, 127);\n"
"}\n"
"QScrollBar::add-line:vertical:pressed { \n"
" background-color: rgb(255, 255, 127);\n"
"}\n"
"\n"
"/* RESET ARROW */\n"
"QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical {\n"
" background: none;\n"
"}\n"
"QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {\n"
" background: none;\n"
"}\n"
"\n"
"/* HORIZONTAL SCROLLBAR */\n"
" QScrollBar:horizontal {\n"
" border: none; \n"
" background-color: rgb(209, 209, 209);\n"
" height: 14px;\n"
" margin: 0px 15px 0px 15px;\n"
" border-radius: 0px;\n"
" }\n"
"\n"
"/* HANDLE BAR HORIZONTAL */\n"
"QScrollBar::handle:horizontal { \n"
" background-color: rgb(119, 118, 123);\n"
" min-width: 30px;\n"
" border-radius: 7px;\n"
"}\n"
"QScrollBar::handle:horizontal:hover{ \n"
" background-color: rgb(255, 255, 127);\n"
"}\n"
"QScrollBar::handle:horizontal:pressed { \n"
" background-color: rgb(255, 255, 127);\n"
"}\n"
"\n"
"/* BTN TOP - SCROLLBAR */\n"
"QScrollBar::sub-line:horizontal {\n"
" border: none;\n"
" background-color: rgb(119, 118, 123); \n"
" width: 15px;\n"
" border-bottom-left-radius: 7px;\n"
" border-bottom-right-radius: 7px;\n"
" subcontrol-position: left;\n"
" subcontrol-origin: margin;\n"
"}\n"
"QScrollBar::sub-line:horizontal:hover { \n"
" background-color: rgb(255, 255, 127);\n"
"}\n"
"QScrollBar::sub-line:horizontal:pressed { \n"
" background-color: rgb(255, 255, 127);\n"
"}\n"
"\n"
"/* BTN BOTTOM - SCROLLBAR */\n"
"QScrollBar::add-line:horizontal{\n"
" border: none;\n"
" background-color: rgb(119, 118, 123);\n"
" width: 15px;\n"
" border-bottom-left-radius: 7px;\n"
" border-bottom-right-radius: 7px;\n"
" subcontrol-position: right;\n"
" subcontrol-origin: margin;\n"
"}\n"
"QScrollBar::add-line:horizontal:hover { \n"
" background-color: rgb(255, 255, 127);\n"
"}\n"
"QScrollBar::add-line:horizontal:pressed { \n"
" background-color: rgb(255, 255, 127);\n"
"}\n"
"\n"
"/* RESET ARROW */\n"
"QScrollBar::up-arrow:horizontal, QScrollBar::down-arrow:horizontal {\n"
" background: none;\n"
"}\n"
"QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {\n"
" background: none;\n"
"}\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"")
self.frame.setFrameShape(QtWidgets.QFrame.NoFrame)
self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame.setLineWidth(2)
self.frame.setObjectName("frame")
self.gridLayout_2 = QtWidgets.QGridLayout(self.frame)
self.gridLayout_2.setObjectName("gridLayout_2")
self.frame_2 = QtWidgets.QFrame(self.frame)
self.frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_2.setObjectName("frame_2")
self.gridLayout = QtWidgets.QGridLayout(self.frame_2)
self.gridLayout.setObjectName("gridLayout")
self.tableWidget = QtWidgets.QTableWidget(self.frame_2)
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(2, 119, 189))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(46, 52, 54))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(2, 119, 189))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(2, 119, 189))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(46, 52, 54, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(2, 119, 189))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(46, 52, 54))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(2, 119, 189))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(2, 119, 189))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(46, 52, 54, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(2, 119, 189))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(146, 148, 149))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(2, 119, 189))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(2, 119, 189))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(46, 52, 54, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.tableWidget.setPalette(palette)
font = QtGui.QFont()
font.setFamily("URW Bookman [UKWN]")
font.setPointSize(11)
font.setItalic(True)
font.setStyleStrategy(QtGui.QFont.PreferAntialias)
self.tableWidget.setFont(font)
self.tableWidget.setStyleSheet(" QHeaderView::section {\n"
" border-top: 0px solid 4181C0;\n"
" border-bottom: 1px solid 4181C0;\n"
" border-right: 1px solid 4181C0; \n"
" \n"
" \n"
" background-color: rgb(53, 132, 228);\n"
" color: rgb(250, 255, 0);}\n"
"\n"
"\n"
"QTableWidget::columns{\n"
" \n"
" \n"
" background-color: #2F2F2F;\n"
" border: 1px solid #4181C0; \n"
" color: rgb(250, 255, 0);\n"
" selection-background-color: #4181C0;\n"
" selection-color: rgb(250, 255, 0);\n"
"\n"
"}\n"
"\n"
"QTableWidget::item{\n"
"color:white;\n"
" \n"
" background-color: rgb(131, 54, 54);\n"
"}\n"
"\n"
"\n"
"\n"
"")
self.tableWidget.setFrameShape(QtWidgets.QFrame.NoFrame)
self.tableWidget.setFrameShadow(QtWidgets.QFrame.Raised)
self.tableWidget.setLineWidth(8)
self.tableWidget.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)
self.tableWidget.setDragEnabled(False)
self.tableWidget.setAlternatingRowColors(False)
self.tableWidget.setShowGrid(True)
self.tableWidget.setGridStyle(QtCore.Qt.DashLine)
self.tableWidget.setWordWrap(True)
self.tableWidget.setCornerButtonEnabled(True)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(7)
self.tableWidget.setRowCount(12)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(1, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(2, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(3, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(4, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(5, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(6, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(7, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(8, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(9, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(10, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(11, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(1, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(2, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(3, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(4, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(5, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(6, item)
item = QtWidgets.QTableWidgetItem()
brush = QtGui.QBrush(QtGui.QColor(255, 247, 14))
brush.setStyle(QtCore.Qt.NoBrush)
item.setForeground(brush)
self.tableWidget.setItem(0, 0, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(0, 1, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(0, 2, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(0, 3, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(0, 4, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(0, 5, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(0, 6, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(1, 0, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(1, 1, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(1, 2, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(1, 3, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(1, 4, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(1, 5, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(1, 6, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(2, 0, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(2, 1, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(2, 2, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(2, 3, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(2, 4, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(2, 5, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(2, 6, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(3, 0, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(3, 1, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(3, 2, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(3, 3, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(3, 4, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(3, 5, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(3, 6, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(4, 0, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(4, 1, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(4, 2, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(4, 3, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(4, 4, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(4, 5, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(4, 6, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(5, 0, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(5, 1, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(5, 2, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(5, 3, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(5, 4, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(5, 5, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(5, 6, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(6, 0, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(6, 1, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(6, 2, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(6, 3, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(6, 4, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(6, 5, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(6, 6, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(7, 0, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(7, 1, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(7, 2, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(7, 3, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(7, 4, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(7, 5, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(7, 6, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(8, 0, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(8, 1, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(8, 2, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(8, 3, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(8, 4, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(8, 5, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(8, 6, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(9, 0, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(9, 1, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(9, 2, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(9, 3, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(9, 4, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(9, 5, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(9, 6, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(10, 0, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(10, 1, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(10, 2, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(10, 3, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(10, 4, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(10, 5, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(10, 6, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(11, 0, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(11, 1, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(11, 2, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(11, 3, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(11, 4, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(11, 5, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(11, 6, item)
self.tableWidget.horizontalHeader().setDefaultSectionSize(119)
self.tableWidget.horizontalHeader().setMinimumSectionSize(24)
self.tableWidget.horizontalHeader().setStretchLastSection(True)
self.tableWidget.verticalHeader().setDefaultSectionSize(70)
self.gridLayout.addWidget(self.tableWidget, 1, 0, 1, 1)
self.frame_btns = QtWidgets.QFrame(self.frame_2)
self.frame_btns.setMaximumSize(QtCore.QSize(100, 16777215))
self.frame_btns.setFrameShape(QtWidgets.QFrame.NoFrame)
self.frame_btns.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_btns.setObjectName("frame_btns")
self.horizontalLayout_5 = QtWidgets.QHBoxLayout(self.frame_btns)
self.horizontalLayout_5.setContentsMargins(5, 1, 3, 4)
self.horizontalLayout_5.setSpacing(4)
self.horizontalLayout_5.setObjectName("horizontalLayout_5")
self.btn_minimize_3 = QtWidgets.QPushButton(self.frame_btns)
self.btn_minimize_3.setMinimumSize(QtCore.QSize(16, 16))
self.btn_minimize_3.setMaximumSize(QtCore.QSize(17, 17))
self.btn_minimize_3.setStyleSheet("QPushButton {\n"
" border: none;\n"
" border-radius: 8px; \n"
" background-color: rgb(255, 170, 0);\n"
"}\n"
"QPushButton:hover { \n"
" background-color: rgba(255, 170, 0, 150);\n"
"}")
self.btn_minimize_3.setText("")
self.btn_minimize_3.setObjectName("btn_minimize_3")
self.horizontalLayout_5.addWidget(self.btn_minimize_3)
self.btn_close_3 = QtWidgets.QPushButton(self.frame_btns)
self.btn_close_3.setMinimumSize(QtCore.QSize(16, 16))
self.btn_close_3.setMaximumSize(QtCore.QSize(17, 17))
self.btn_close_3.setStyleSheet("QPushButton {\n"
" border: none;\n"
" border-radius: 8px; \n"
" background-color: rgb(255, 0, 0);\n"
"}\n"
"QPushButton:hover { \n"
" background-color: rgba(255, 0, 0, 150);\n"
"}")
self.btn_close_3.setText("")
self.btn_close_3.setObjectName("btn_close_3")
self.horizontalLayout_5.addWidget(self.btn_close_3)
self.gridLayout.addWidget(self.frame_btns, 0, 0, 1, | |
id(self) -> pulumi.Input[str]:
"""
A relative uri containing either a Platform Image Repository or user image reference.
"""
return pulumi.get(self, "id")
@id.setter
def id(self, value: pulumi.Input[str]):
pulumi.set(self, "id", value)
@property
@pulumi.getter
def lun(self) -> Optional[pulumi.Input[int]]:
"""
If the disk is created from an image's data disk, this is an index that indicates which of the data disks in the image to use. For OS disks, this field is null.
"""
return pulumi.get(self, "lun")
@lun.setter
def lun(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "lun", value)
@pulumi.input_type
class ImagePurchasePlanArgs:
def __init__(__self__, *,
name: Optional[pulumi.Input[str]] = None,
product: Optional[pulumi.Input[str]] = None,
publisher: Optional[pulumi.Input[str]] = None):
"""
Describes the gallery image definition purchase plan. This is used by marketplace images.
:param pulumi.Input[str] name: The plan ID.
:param pulumi.Input[str] product: The product ID.
:param pulumi.Input[str] publisher: The publisher ID.
"""
if name is not None:
pulumi.set(__self__, "name", name)
if product is not None:
pulumi.set(__self__, "product", product)
if publisher is not None:
pulumi.set(__self__, "publisher", publisher)
@property
@pulumi.getter
def name(self) -> Optional[pulumi.Input[str]]:
"""
The plan ID.
"""
return pulumi.get(self, "name")
@name.setter
def name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "name", value)
@property
@pulumi.getter
def product(self) -> Optional[pulumi.Input[str]]:
"""
The product ID.
"""
return pulumi.get(self, "product")
@product.setter
def product(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "product", value)
@property
@pulumi.getter
def publisher(self) -> Optional[pulumi.Input[str]]:
"""
The publisher ID.
"""
return pulumi.get(self, "publisher")
@publisher.setter
def publisher(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "publisher", value)
@pulumi.input_type
class KeyForDiskEncryptionSetArgs:
def __init__(__self__, *,
key_url: pulumi.Input[str],
source_vault: Optional[pulumi.Input['SourceVaultArgs']] = None):
"""
Key Vault Key Url to be used for server side encryption of Managed Disks and Snapshots
:param pulumi.Input[str] key_url: Fully versioned Key Url pointing to a key in KeyVault
:param pulumi.Input['SourceVaultArgs'] source_vault: Resource id of the KeyVault containing the key or secret. This property is optional and cannot be used if the KeyVault subscription is not the same as the Disk Encryption Set subscription.
"""
pulumi.set(__self__, "key_url", key_url)
if source_vault is not None:
pulumi.set(__self__, "source_vault", source_vault)
@property
@pulumi.getter(name="keyUrl")
def key_url(self) -> pulumi.Input[str]:
"""
Fully versioned Key Url pointing to a key in KeyVault
"""
return pulumi.get(self, "key_url")
@key_url.setter
def key_url(self, value: pulumi.Input[str]):
pulumi.set(self, "key_url", value)
@property
@pulumi.getter(name="sourceVault")
def source_vault(self) -> Optional[pulumi.Input['SourceVaultArgs']]:
"""
Resource id of the KeyVault containing the key or secret. This property is optional and cannot be used if the KeyVault subscription is not the same as the Disk Encryption Set subscription.
"""
return pulumi.get(self, "source_vault")
@source_vault.setter
def source_vault(self, value: Optional[pulumi.Input['SourceVaultArgs']]):
pulumi.set(self, "source_vault", value)
@pulumi.input_type
class KeyVaultAndKeyReferenceArgs:
def __init__(__self__, *,
key_url: pulumi.Input[str],
source_vault: pulumi.Input['SourceVaultArgs']):
"""
Key Vault Key Url and vault id of KeK, KeK is optional and when provided is used to unwrap the encryptionKey
:param pulumi.Input[str] key_url: Url pointing to a key or secret in KeyVault
:param pulumi.Input['SourceVaultArgs'] source_vault: Resource id of the KeyVault containing the key or secret
"""
pulumi.set(__self__, "key_url", key_url)
pulumi.set(__self__, "source_vault", source_vault)
@property
@pulumi.getter(name="keyUrl")
def key_url(self) -> pulumi.Input[str]:
"""
Url pointing to a key or secret in KeyVault
"""
return pulumi.get(self, "key_url")
@key_url.setter
def key_url(self, value: pulumi.Input[str]):
pulumi.set(self, "key_url", value)
@property
@pulumi.getter(name="sourceVault")
def source_vault(self) -> pulumi.Input['SourceVaultArgs']:
"""
Resource id of the KeyVault containing the key or secret
"""
return pulumi.get(self, "source_vault")
@source_vault.setter
def source_vault(self, value: pulumi.Input['SourceVaultArgs']):
pulumi.set(self, "source_vault", value)
@pulumi.input_type
class KeyVaultAndSecretReferenceArgs:
def __init__(__self__, *,
secret_url: pulumi.Input[str],
source_vault: pulumi.Input['SourceVaultArgs']):
"""
Key Vault Secret Url and vault id of the encryption key
:param pulumi.Input[str] secret_url: Url pointing to a key or secret in KeyVault
:param pulumi.Input['SourceVaultArgs'] source_vault: Resource id of the KeyVault containing the key or secret
"""
pulumi.set(__self__, "secret_url", secret_url)
pulumi.set(__self__, "source_vault", source_vault)
@property
@pulumi.getter(name="secretUrl")
def secret_url(self) -> pulumi.Input[str]:
"""
Url pointing to a key or secret in KeyVault
"""
return pulumi.get(self, "secret_url")
@secret_url.setter
def secret_url(self, value: pulumi.Input[str]):
pulumi.set(self, "secret_url", value)
@property
@pulumi.getter(name="sourceVault")
def source_vault(self) -> pulumi.Input['SourceVaultArgs']:
"""
Resource id of the KeyVault containing the key or secret
"""
return pulumi.get(self, "source_vault")
@source_vault.setter
def source_vault(self, value: pulumi.Input['SourceVaultArgs']):
pulumi.set(self, "source_vault", value)
@pulumi.input_type
class OSDiskImageEncryptionArgs:
def __init__(__self__, *,
disk_encryption_set_id: Optional[pulumi.Input[str]] = None):
"""
Contains encryption settings for an OS disk image.
:param pulumi.Input[str] disk_encryption_set_id: A relative URI containing the resource ID of the disk encryption set.
"""
if disk_encryption_set_id is not None:
pulumi.set(__self__, "disk_encryption_set_id", disk_encryption_set_id)
@property
@pulumi.getter(name="diskEncryptionSetId")
def disk_encryption_set_id(self) -> Optional[pulumi.Input[str]]:
"""
A relative URI containing the resource ID of the disk encryption set.
"""
return pulumi.get(self, "disk_encryption_set_id")
@disk_encryption_set_id.setter
def disk_encryption_set_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "disk_encryption_set_id", value)
@pulumi.input_type
class PrivateLinkServiceConnectionStateArgs:
def __init__(__self__, *,
actions_required: Optional[pulumi.Input[str]] = None,
description: Optional[pulumi.Input[str]] = None,
status: Optional[pulumi.Input[Union[str, 'PrivateEndpointServiceConnectionStatus']]] = None):
"""
A collection of information about the state of the connection between service consumer and provider.
:param pulumi.Input[str] actions_required: A message indicating if changes on the service provider require any updates on the consumer.
:param pulumi.Input[str] description: The reason for approval/rejection of the connection.
:param pulumi.Input[Union[str, 'PrivateEndpointServiceConnectionStatus']] status: Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service.
"""
if actions_required is not None:
pulumi.set(__self__, "actions_required", actions_required)
if description is not None:
pulumi.set(__self__, "description", description)
if status is not None:
pulumi.set(__self__, "status", status)
@property
@pulumi.getter(name="actionsRequired")
def actions_required(self) -> Optional[pulumi.Input[str]]:
"""
A message indicating if changes on the service provider require any updates on the consumer.
"""
return pulumi.get(self, "actions_required")
@actions_required.setter
def actions_required(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "actions_required", value)
@property
@pulumi.getter
def description(self) -> Optional[pulumi.Input[str]]:
"""
The reason for approval/rejection of the connection.
"""
return pulumi.get(self, "description")
@description.setter
def description(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "description", value)
@property
@pulumi.getter
def status(self) -> Optional[pulumi.Input[Union[str, 'PrivateEndpointServiceConnectionStatus']]]:
"""
Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service.
"""
return pulumi.get(self, "status")
@status.setter
def status(self, value: Optional[pulumi.Input[Union[str, 'PrivateEndpointServiceConnectionStatus']]]):
pulumi.set(self, "status", value)
@pulumi.input_type
class PurchasePlanArgs:
def __init__(__self__, *,
name: pulumi.Input[str],
product: pulumi.Input[str],
publisher: pulumi.Input[str],
promotion_code: Optional[pulumi.Input[str]] = None):
"""
Used for establishing the purchase context of any 3rd Party artifact through MarketPlace.
:param pulumi.Input[str] name: The plan ID.
:param pulumi.Input[str] product: Specifies the product of the image from the marketplace. This is the same value as Offer under the imageReference element.
:param pulumi.Input[str] publisher: The publisher ID.
:param pulumi.Input[str] promotion_code: The Offer Promotion Code.
"""
pulumi.set(__self__, "name", name)
pulumi.set(__self__, "product", product)
pulumi.set(__self__, "publisher", publisher)
if promotion_code is not None:
pulumi.set(__self__, "promotion_code", promotion_code)
@property
@pulumi.getter
def name(self) -> pulumi.Input[str]:
"""
The plan ID.
"""
return pulumi.get(self, "name")
@name.setter
def name(self, value: pulumi.Input[str]):
pulumi.set(self, "name", value)
@property
@pulumi.getter
def product(self) -> pulumi.Input[str]:
"""
Specifies the product of the image from the marketplace. This is the same value as Offer under the imageReference element.
"""
return pulumi.get(self, "product")
@product.setter
def product(self, value: pulumi.Input[str]):
pulumi.set(self, "product", value)
@property
@pulumi.getter
def publisher(self) -> pulumi.Input[str]:
"""
The publisher ID.
"""
return pulumi.get(self, "publisher")
@publisher.setter
def publisher(self, value: pulumi.Input[str]):
pulumi.set(self, "publisher", value)
@property
@pulumi.getter(name="promotionCode")
def promotion_code(self) -> Optional[pulumi.Input[str]]:
"""
The Offer Promotion Code.
"""
return pulumi.get(self, "promotion_code")
@promotion_code.setter
def promotion_code(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "promotion_code", value)
@pulumi.input_type
class RecommendedMachineConfigurationArgs:
def __init__(__self__, *,
memory: Optional[pulumi.Input['ResourceRangeArgs']] = None,
v_cpus: Optional[pulumi.Input['ResourceRangeArgs']] = None):
"""
The properties describe the recommended machine configuration for this Image Definition. These properties are updatable.
:param pulumi.Input['ResourceRangeArgs'] memory: Describes the resource range.
:param pulumi.Input['ResourceRangeArgs'] v_cpus: Describes the resource range.
"""
if memory is not None:
pulumi.set(__self__, "memory", memory)
if v_cpus is not None:
pulumi.set(__self__, "v_cpus", v_cpus)
@property
@pulumi.getter
def memory(self) -> Optional[pulumi.Input['ResourceRangeArgs']]:
"""
Describes the resource range.
"""
return pulumi.get(self, "memory")
@memory.setter
def memory(self, value: Optional[pulumi.Input['ResourceRangeArgs']]):
pulumi.set(self, "memory", value)
@property
@pulumi.getter(name="vCPUs")
def v_cpus(self) -> Optional[pulumi.Input['ResourceRangeArgs']]:
"""
Describes the resource range.
"""
return pulumi.get(self, "v_cpus")
@v_cpus.setter
def v_cpus(self, value: Optional[pulumi.Input['ResourceRangeArgs']]):
pulumi.set(self, "v_cpus", value)
@pulumi.input_type
class ResourceRangeArgs:
def __init__(__self__, *,
max: Optional[pulumi.Input[int]] = None,
min: Optional[pulumi.Input[int]] = None):
"""
Describes the resource range.
:param pulumi.Input[int] max: The maximum number of the resource.
:param pulumi.Input[int] min: The minimum number of the resource.
"""
if max is not None:
pulumi.set(__self__, "max", max)
if min is not None:
pulumi.set(__self__, "min", min)
@property
@pulumi.getter
def max(self) -> Optional[pulumi.Input[int]]:
"""
The maximum number of the resource.
"""
return pulumi.get(self, "max")
@max.setter
def max(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "max", value)
@property
@pulumi.getter
def min(self) -> Optional[pulumi.Input[int]]:
"""
The minimum number of the resource.
"""
return pulumi.get(self, "min")
@min.setter
def | |
def setXAxisLogarithmic(self, flag):
"""Set the bottom X axis scale (either linear or logarithmic).
:param bool flag: True to use a logarithmic scale, False for linear.
"""
self._xAxis._setLogarithmic(flag)
def isYAxisLogarithmic(self):
"""Return True if Y axis scale is logarithmic, False if linear."""
return self._yAxis._isLogarithmic()
def setYAxisLogarithmic(self, flag):
"""Set the Y axes scale (either linear or logarithmic).
:param bool flag: True to use a logarithmic scale, False for linear.
"""
self._yAxis._setLogarithmic(flag)
def isXAxisAutoScale(self):
"""Return True if X axis is automatically adjusting its limits."""
return self._xAxis.isAutoScale()
def setXAxisAutoScale(self, flag=True):
"""Set the X axis limits adjusting behavior of :meth:`resetZoom`.
:param bool flag: True to resize limits automatically,
False to disable it.
"""
self._xAxis.setAutoScale(flag)
def isYAxisAutoScale(self):
"""Return True if Y axes are automatically adjusting its limits."""
return self._yAxis.isAutoScale()
def setYAxisAutoScale(self, flag=True):
"""Set the Y axis limits adjusting behavior of :meth:`resetZoom`.
:param bool flag: True to resize limits automatically,
False to disable it.
"""
self._yAxis.setAutoScale(flag)
def isKeepDataAspectRatio(self):
"""Returns whether the plot is keeping data aspect ratio or not."""
return self._backend.isKeepDataAspectRatio()
def setKeepDataAspectRatio(self, flag=True):
"""Set whether the plot keeps data aspect ratio or not.
:param bool flag: True to respect data aspect ratio
"""
flag = bool(flag)
if flag == self.isKeepDataAspectRatio():
return
self._backend.setKeepDataAspectRatio(flag=flag)
self._setDirtyPlot()
self._forceResetZoom()
self.notify('setKeepDataAspectRatio', state=flag)
def getGraphGrid(self):
"""Return the current grid mode, either None, 'major' or 'both'.
See :meth:`setGraphGrid`.
"""
return self._grid
def setGraphGrid(self, which=True):
"""Set the type of grid to display.
:param which: None or False to disable the grid,
'major' or True for grid on major ticks (the default),
'both' for grid on both major and minor ticks.
:type which: str of bool
"""
assert which in (None, True, False, 'both', 'major')
if not which:
which = None
elif which is True:
which = 'major'
self._grid = which
self._backend.setGraphGrid(which)
self._setDirtyPlot()
self.notify('setGraphGrid', which=str(which))
# Defaults
def isDefaultPlotPoints(self):
"""Return True if the default Curve symbol is set and False if not."""
return self._defaultPlotPoints == silx.config.DEFAULT_PLOT_CURVE_SYMBOL
def setDefaultPlotPoints(self, flag):
"""Set the default symbol of all curves.
When called, this reset the symbol of all existing curves.
:param bool flag: True to use 'o' as the default curve symbol,
False to use no symbol.
"""
self._defaultPlotPoints = silx.config.DEFAULT_PLOT_CURVE_SYMBOL if flag else ''
# Reset symbol of all curves
curves = self.getAllCurves(just_legend=False, withhidden=True)
if curves:
for curve in curves:
curve.setSymbol(self._defaultPlotPoints)
def isDefaultPlotLines(self):
"""Return True for line as default line style, False for no line."""
return self._plotLines
def setDefaultPlotLines(self, flag):
"""Toggle the use of lines as the default curve line style.
:param bool flag: True to use a line as the default line style,
False to use no line as the default line style.
"""
self._plotLines = bool(flag)
linestyle = '-' if self._plotLines else ' '
# Reset linestyle of all curves
curves = self.getAllCurves(withhidden=True)
if curves:
for curve in curves:
curve.setLineStyle(linestyle)
def getDefaultColormap(self):
"""Return the default colormap used by :meth:`addImage`.
:rtype: ~silx.gui.colors.Colormap
"""
return self._defaultColormap
def setDefaultColormap(self, colormap=None):
"""Set the default colormap used by :meth:`addImage`.
Setting the default colormap do not change any currently displayed
image.
It only affects future calls to :meth:`addImage` without the colormap
parameter.
:param ~silx.gui.colors.Colormap colormap:
The description of the default colormap, or
None to set the colormap to a linear
autoscale gray colormap.
"""
if colormap is None:
colormap = Colormap(name=silx.config.DEFAULT_COLORMAP_NAME,
normalization='linear',
vmin=None,
vmax=None)
if isinstance(colormap, dict):
self._defaultColormap = Colormap._fromDict(colormap)
else:
assert isinstance(colormap, Colormap)
self._defaultColormap = colormap
self.notify('defaultColormapChanged')
@staticmethod
def getSupportedColormaps():
"""Get the supported colormap names as a tuple of str.
The list contains at least:
('gray', 'reversed gray', 'temperature', 'red', 'green', 'blue',
'magma', 'inferno', 'plasma', 'viridis')
"""
return Colormap.getSupportedColormaps()
def _resetColorAndStyle(self):
self._colorIndex = 0
self._styleIndex = 0
def _getColorAndStyle(self):
color = self.colorList[self._colorIndex]
style = self._styleList[self._styleIndex]
# Loop over color and then styles
self._colorIndex += 1
if self._colorIndex >= len(self.colorList):
self._colorIndex = 0
self._styleIndex = (self._styleIndex + 1) % len(self._styleList)
# If color is the one of active curve, take the next one
if colors.rgba(color) == self.getActiveCurveStyle().getColor():
color, style = self._getColorAndStyle()
if not self._plotLines:
style = ' '
return color, style
# Misc.
def getWidgetHandle(self):
"""Return the widget the plot is displayed in.
This widget is owned by the backend.
"""
return self._backend.getWidgetHandle()
def notify(self, event, **kwargs):
"""Send an event to the listeners and send signals.
Event are passed to the registered callback as a dict with an 'event'
key for backward compatibility with PyMca.
:param str event: The type of event
:param kwargs: The information of the event.
"""
eventDict = kwargs.copy()
eventDict['event'] = event
self.sigPlotSignal.emit(eventDict)
if event == 'setKeepDataAspectRatio':
self.sigSetKeepDataAspectRatio.emit(kwargs['state'])
elif event == 'setGraphGrid':
self.sigSetGraphGrid.emit(kwargs['which'])
elif event == 'setGraphCursor':
self.sigSetGraphCursor.emit(kwargs['state'])
elif event == 'contentChanged':
self.sigContentChanged.emit(
kwargs['action'], kwargs['kind'], kwargs['legend'])
elif event == 'activeCurveChanged':
self.sigActiveCurveChanged.emit(
kwargs['previous'], kwargs['legend'])
elif event == 'activeImageChanged':
self.sigActiveImageChanged.emit(
kwargs['previous'], kwargs['legend'])
elif event == 'activeScatterChanged':
self.sigActiveScatterChanged.emit(
kwargs['previous'], kwargs['legend'])
elif event == 'interactiveModeChanged':
self.sigInteractiveModeChanged.emit(kwargs['source'])
eventDict = kwargs.copy()
eventDict['event'] = event
self._callback(eventDict)
def setCallback(self, callbackFunction=None):
"""Attach a listener to the backend.
Limitation: Only one listener at a time.
:param callbackFunction: function accepting a dictionary as input
to handle the graph events
If None (default), use a default listener.
"""
# TODO allow multiple listeners
# allow register listener by event type
if callbackFunction is None:
callbackFunction = WeakMethodProxy(self.graphCallback)
self._callback = callbackFunction
def graphCallback(self, ddict=None):
"""This callback is going to receive all the events from the plot.
Those events will consist on a dictionary and among the dictionary
keys the key 'event' is mandatory to describe the type of event.
This default implementation only handles setting the active curve.
"""
if ddict is None:
ddict = {}
_logger.debug("Received dict keys = %s", str(ddict.keys()))
_logger.debug(str(ddict))
if ddict['event'] in ["legendClicked", "curveClicked"]:
if ddict['button'] == "left":
self.setActiveCurve(ddict['label'])
qt.QToolTip.showText(self.cursor().pos(), ddict['label'])
elif ddict['event'] == 'mouseClicked' and ddict['button'] == 'left':
self.setActiveCurve(None)
def saveGraph(self, filename, fileFormat=None, dpi=None):
"""Save a snapshot of the plot.
Supported file formats depends on the backend in use.
The following file formats are always supported: "png", "svg".
The matplotlib backend supports more formats:
"pdf", "ps", "eps", "tiff", "jpeg", "jpg".
:param filename: Destination
:type filename: str, StringIO or BytesIO
:param str fileFormat: String specifying the format
:return: False if cannot save the plot, True otherwise
"""
if fileFormat is None:
if not hasattr(filename, 'lower'):
_logger.warning(
'saveGraph cancelled, cannot define file format.')
return False
else:
fileFormat = (filename.split(".")[-1]).lower()
supportedFormats = ("png", "svg", "pdf", "ps", "eps",
"tif", "tiff", "jpeg", "jpg")
if fileFormat not in supportedFormats:
_logger.warning('Unsupported format %s', fileFormat)
return False
else:
self._backend.saveGraph(filename,
fileFormat=fileFormat,
dpi=dpi)
return True
def getDataMargins(self):
"""Get the default data margin ratios, see :meth:`setDataMargins`.
:return: The margin ratios for each side (xMin, xMax, yMin, yMax).
:rtype: A 4-tuple of floats.
"""
return self._defaultDataMargins
def setDataMargins(self, xMinMargin=0., xMaxMargin=0.,
yMinMargin=0., yMaxMargin=0.):
"""Set the default data margins to use in :meth:`resetZoom`.
Set the default ratios of margins (as floats) to add around the data
inside the plot area for each side.
"""
self._defaultDataMargins = (xMinMargin, xMaxMargin,
yMinMargin, yMaxMargin)
def getAutoReplot(self):
"""Return True if replot is automatically handled, False otherwise.
See :meth`setAutoReplot`.
"""
return self._autoreplot
def setAutoReplot(self, autoreplot=True):
"""Set automatic replot mode.
When enabled, the plot is redrawn automatically when changed.
When disabled, the plot is not redrawn when its content change.
Instead, it :meth:`replot` must be called.
:param bool autoreplot: True to enable it (default),
False to disable it.
"""
self._autoreplot = bool(autoreplot)
# If the plot is dirty before enabling autoreplot,
# then _backend.postRedisplay will never be called from _setDirtyPlot
if self._autoreplot and self._getDirtyPlot():
self._backend.postRedisplay()
def replot(self):
"""Redraw the plot immediately."""
for item in self._contentToUpdate:
item._update(self._backend)
self._contentToUpdate = []
self._backend.replot()
self._dirty = False # reset dirty flag
def _forceResetZoom(self, dataMargins=None):
"""Reset the plot limits to the bounds of the data and redraw the plot.
This method forces a reset zoom and does not check axis autoscale.
Extra margins can be added around the data inside the plot area
(see :meth:`setDataMargins`).
Margins are given as one ratio of the data range per limit of the
data (xMin, xMax, yMin and | |
import sys
import matplotlib
matplotlib.use('agg')
from matplotlib import pyplot as plt
from matplotlib import gridspec
from matplotlib.font_manager import FontProperties
from matplotlib.patches import Rectangle
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.text import TextPath
from matplotlib.patches import PathPatch
from matplotlib.font_manager import FontProperties
import os
import re
import subprocess
import shelve
import mpld3
from mpld3 import plugins,utils
from new_plugins import InteractiveLegendPlugin,TopToolbar,DownloadProfile,DownloadPNG
import collections
from mpld3.utils import get_id
import pandas as pd
import numpy as np
from flask import make_response
from scipy.stats.stats import spearmanr,pearsonr
import matplotlib.cm as cm
from bokeh.plotting import figure, show, output_file
from bokeh.embed import file_html, components
from bokeh.resources import CDN
from bokeh.palettes import YlOrRd9 as palette
from bokeh.palettes import inferno
from bokeh.palettes import all_palettes
from bokeh.models.glyphs import Text
import bokeh.models as bmo
from bokeh.io import show
from bokeh.models import (
TapTool,
OpenURL,
Range1d,
Label,
FuncTickFormatter,
LogTicker,
ColumnDataSource,
HoverTool,
LinearColorMapper,
LogColorMapper,
BasicTicker,
PrintfTickFormatter,
ColorBar
)
#ViennaRNA can be installed from here https://github.com/ViennaRNA/ViennaRNA
try:
import RNA
vienna_rna = True
except:
print ("Could not import the RNA module, ViennaRNA needs to be installed (https://github.com/ViennaRNA/ViennaRNA), MFE will not be plotted on traninfo plot")
vienna_rna = False
redhex="#FF5F5B"
greenhex="#90E090"
bluehex="#9ACAFF"
yellowhex="#FFFF91"
# Define some CSS to control our custom labels
line_tooltip_css = """
.tooltip
{
color: #000000;
background-color: #d2d4d8;
font-family:Arial, Helvetica, sans-serif;
text-align: left;
}
"""
def nuc_freq_plot(master_dict,title,short_code, background_col,readlength_col,title_size, axis_label_size, subheading_size,marker_size,filename):
labels = ["A","T","G","C"]
returnstr = "Position,A,T,G,C\n"
minpos = min(master_dict.keys())
maxpos = max(master_dict.keys())
x_pos = []
a_counts = []
t_counts = []
g_counts = []
c_counts = []
for i in range(minpos,maxpos):
returnstr += "{},{:.2f},{:.2f},{:.2f},{:.2f}\n".format(i,master_dict[i]["A"],master_dict[i]["T"],master_dict[i]["G"],master_dict[i]["C"])
x_pos.append(i)
a_counts.append(master_dict[i]["A"])
t_counts.append(master_dict[i]["T"])
g_counts.append(master_dict[i]["G"])
c_counts.append(master_dict[i]["C"])
fig, ax = plt.subplots( figsize=(13,12))
#rects1 = ax.bar([20,21,22,23,24,25,26,27,28], [100,200,100,200,100,200,100,200,100], 0.1, color='r',align='center')
ax.set_xlabel('Position (nucleotides)',fontsize=axis_label_size)
#if nuc_comp_type == "nuc_comp_per":
# ax.set_ylim(0,1)
# ax.set_ylabel('Percent',fontsize=axis_label_size,labelpad=50)
#elif nuc_comp_type == "nuc_comp_count":
maxheight = max(max(a_counts), max(t_counts),max(g_counts),max(c_counts))
ax.set_ylim(0,maxheight)
ax.set_ylabel('Count',fontsize=axis_label_size,labelpad=100)
#if nuc_comp_direction == "nuc_comp_five":
# ax.set_xlim(0,maxreadlen)
#elif nuc_comp_direction == "nuc_comp_three":
# ax.set_xlim((maxreadlen*-1),-1)
width = 0.95
#plot it
ax = plt.subplot(111)
title_str = "{} ({})".format(title,short_code)
ax.set_title(title_str, y=1.05,fontsize=title_size)
a_line = ax.plot(x_pos, a_counts, label=labels, color="blue", linewidth=4)
t_line = ax.plot(x_pos, t_counts, label=labels, color="red", linewidth=4)
g_line = ax.plot(x_pos, g_counts, label=labels, color="green", linewidth=4)
c_line = ax.plot(x_pos, c_counts, label=labels, color="orange", linewidth=4)
ax.set_facecolor(background_col)
ax.tick_params('both', labelsize=marker_size)
plt.grid(color="white", linewidth=2,linestyle="solid")
ilp = InteractiveLegendPlugin([a_line, t_line, g_line, c_line], ["A","T","G","C"], alpha_unsel=0,alpha_sel=1,start_visible=True)
plugins.connect(fig, ilp,TopToolbar(yoffset=750,xoffset=600),DownloadProfile(returnstr=returnstr),DownloadPNG(returnstr=title_str))
graph = "<style>.mpld3-xaxis {{font-size: {0}px;}} .mpld3-yaxis {{font-size: {0}px;}}</style>".format(marker_size)
graph += "<div style='padding-left: 55px;padding-top: 22px;'> <a href='https://trips.ucc.ie/short/{0}' target='_blank' ><button class='button centerbutton' type='submit'><b>Direct link to this plot</b></button></a><a href='https://trips.ucc.ie/static/tmp/{1}' target='_blank' ><button class='button centerbutton' type='submit'><b>Download results as fasta file</b></button></a> </div>".format(short_code,filename)
graph += mpld3.fig_to_html(fig)
return graph
def nuc_comp_single(tran, master_dict,title,short_code,background_col,readlength_col,title_size, axis_label_size, subheading_size,marker_size,traninfo):
labels = ["Exon Junctions","CDS markers"]
start_visible=[True,True]
stop_codons = ["TAG","TAA","TGA"]
frame_orfs = {1:[],2:[],3:[]}
color_dict = {'frames': ['#FF4A45', '#64FC44', '#5687F9']}
try:
traninfo["stop_list"] = [int(x) for x in traninfo["stop_list"]]
except:
traninfo["stop_list"] = []
try:
traninfo["start_list"] = [int(x) for x in traninfo["start_list"]]
except:
traninfo["start_list"] = []
if str(traninfo["exon_junctions"][0]) != "":
traninfo["exon_junctions"] = [int(x) for x in traninfo["exon_junctions"]]
else:
traninfo["exon_junctions"] = []
gene = traninfo["gene"]
tranlen = traninfo["length"]
cds_start = traninfo["cds_start"]
cds_stop = traninfo["cds_stop"]
if cds_start == "NULL" or cds_start == None:
cds_start = 0
if cds_stop == "NULL" or cds_stop == None:
cds_stop = 0
all_starts = traninfo["start_list"]
all_stops = {"TAG":[],"TAA":[],"TGA":[]}
exon_junctions = traninfo["exon_junctions"]
seq = traninfo["seq"].upper()
for i in range(0,len(seq)):
if seq[i:i+3] in stop_codons:
all_stops[seq[i:i+3]].append(i+1)
# Error occurs if one of the frames is empty for any given start/stop, so we initialise with -5 as this won't be seen by user and will prevent the error
start_stop_dict = {1:{"starts":[-5], "stops":{"TGA":[-5],"TAG":[-5],"TAA":[-5]}},
2:{"starts":[-5], "stops":{"TGA":[-5],"TAG":[-5],"TAA":[-5]}},
3:{"starts":[-5], "stops":{"TGA":[-5],"TAG":[-5],"TAA":[-5]}}}
for start in all_starts:
rem = ((start-1)%3)+1
start_stop_dict[rem]["starts"].append(start)
for stop in all_stops:
for stop_pos in all_stops[stop]:
rem = ((stop_pos-1)%3)+1
start_stop_dict[rem]["stops"][stop].append(stop_pos)
#find all open reading frames
for frame in [1,2,3]:
for start in start_stop_dict[frame]["starts"]:
best_stop_pos = 10000000
for stop in start_stop_dict[frame]["stops"]:
for stop_pos in start_stop_dict[frame]["stops"][stop]:
if stop_pos > start and stop_pos < best_stop_pos:
best_stop_pos = stop_pos
if best_stop_pos != 10000000:
frame_orfs[frame].append((start, best_stop_pos))
y_max = 100
fig = plt.figure(figsize=(13,8))
ax_main = plt.subplot2grid((30,1), (0,0),rowspan=22)
ax_main.spines['bottom'].set_visible(False)
#ax_main.set_ylabel(label, fontsize=axis_label_size, labelpad=30)
label = 'Position (nucleotides)'
ax_main.set_xlabel(label, fontsize=axis_label_size)
ax_main.set_ylim(0, y_max)
cds_markers = ax_main.plot((cds_start+1,cds_start+1), (0, y_max), color="black",linestyle = 'solid', linewidth=2)
cds_markers += ax_main.plot((cds_stop+1,cds_stop+1), (0, y_max), color="black",linestyle = 'solid', linewidth=2)
ax_f1 = plt.subplot2grid((30,1), (26,0),rowspan=1,sharex=ax_main)
ax_f1.set_facecolor(color_dict['frames'][0])
ax_f2 = plt.subplot2grid((30,1), (27,0),rowspan=1,sharex=ax_main)
ax_f2.set_facecolor(color_dict['frames'][1])
ax_f3 = plt.subplot2grid((30,1), (28,0),rowspan=1,sharex=ax_main)
ax_f3.set_facecolor(color_dict['frames'][2])
ax_nucseq = plt.subplot2grid((30,1), (29,0),rowspan=1,sharex=ax_main)
ax_nucseq.set_xlabel('Transcript: {} Length: {} nt'.format(tran, tranlen), fontsize=subheading_size, labelpad=10)
#plot a dummy exon junction at postion -1, needed in cases there are no exon junctions, this wont be seen
allexons = ax_main.plot((-1,-1), (0, 1), alpha=0.01,color='black',linestyle = '-.', linewidth=2)
for exon in exon_junctions:
allexons += ax_main.plot((exon,exon), (0, y_max), alpha=0.95,color='black',linestyle = '-.', linewidth=3)
xy = 0
ax_nucseq.set_facecolor(background_col)
mrnaseq = seq.replace("T","U")
color_list = ["#FF4A45","#64FC44","#5687F9"]
char_frame = 0
for char in mrnaseq:
ax_nucseq.text((xy+1)-0.1,0.2,mrnaseq[xy],fontsize=20,color=color_list[char_frame%3])
xy += 1
char_frame += 1
for axisname in (ax_f1, ax_f2, ax_f3,ax_nucseq):
axisname.tick_params(top=False, bottom=False, labelleft=False, labelright=False, labelbottom=False)
for label in ax_main.xaxis.get_majorticklabels():
label.set_fontsize(36)
for axis, frame in ((ax_f1, 1), (ax_f2, 2), (ax_f3, 3)):
axis.set_xlim(1, tranlen)
starts = [(item, 1) for item in start_stop_dict[frame]['starts']]
uag_stops = [(item, 1) for item in start_stop_dict[frame]['stops']['TAG']]
uaa_stops = [(item, 1) for item in start_stop_dict[frame]['stops']['TAA']]
uga_stops = [(item, 1) for item in start_stop_dict[frame]['stops']['TGA']]
axis.broken_barh(starts, (0.30, 1),color="white", zorder=2,linewidth=7)
axis.broken_barh(uag_stops, (0, 1), color="black", zorder=2, linewidth=4)
axis.broken_barh(uaa_stops, (0, 1), color="black", zorder=2, linewidth=4)
axis.broken_barh(uga_stops, (0, 1), color="black", zorder=2, linewidth=4)
axis.set_ylim(0, 1)
axis.set_ylabel('{}'.format(frame), labelpad=10, verticalalignment='center',rotation="horizontal",color="black")
title_str = '{} ({})'.format(gene,short_code)
plt.title(title_str, fontsize=title_size,y=36)
line_collections = [allexons,cds_markers]
plot_gc = True
plot_mfe = True
if plot_mfe == True and vienna_rna == True:
step_size = 2
window_size = 60
mfe_dict = collections.OrderedDict()
for i in range(0,len(seq)-(window_size),step_size):
seq_window = str(seq[i:i+window_size])
(ss, mfe) = RNA.fold(seq_window)
mfe_dict[i+(window_size/2)] = abs(mfe)
else:
mfe_dict = {}
if plot_gc == True:
step_size = 2
window_size = 60
a_dict = collections.OrderedDict()
t_dict = collections.OrderedDict()
g_dict = collections.OrderedDict()
c_dict = collections.OrderedDict()
gc_dict = collections.OrderedDict()
for i in range(0,len(seq)-(window_size),step_size):
a_count = 0.0
t_count = 0.0
g_count = 0.0
c_count = 0.0
for x in range(i,i+window_size):
if seq[x] == "A":
a_count += 1
elif seq[x] == "T":
t_count += 1
elif seq[x] == "G":
g_count += 1
elif seq[x] == "C":
c_count += 1
gc_count = g_count + c_count
norm_a = a_count/window_size
norm_t = t_count/window_size
norm_g = g_count/window_size
norm_c = c_count/window_size
norm_gc = gc_count/window_size
final_a = norm_a*y_max
final_t = norm_t*y_max
final_g = norm_g*y_max
final_c = norm_c*y_max
final_gc = norm_gc*y_max
a_dict[i+(window_size/2)] = final_a
t_dict[i+(window_size/2)] = final_t
g_dict[i+(window_size/2)] = final_g
c_dict[i+(window_size/2)] = final_c
gc_dict[i+(window_size/2)] = final_gc
a_plot = ax_main.plot(a_dict.keys(), a_dict.values(), alpha=0.01, label = labels, zorder=1, color=color_dict['frames'][0], linewidth=4)
t_plot = ax_main.plot(t_dict.keys(), t_dict.values(), alpha=0.01, label = labels, zorder=1, color=color_dict['frames'][1], linewidth=4)
g_plot = ax_main.plot(g_dict.keys(), g_dict.values(), alpha=0.01, label = labels, zorder=1, color=color_dict['frames'][2], linewidth=4)
c_plot = ax_main.plot(c_dict.keys(), c_dict.values(), alpha=0.01, label = labels, zorder=1, color='#ffff99', linewidth=4)
gc_plot = ax_main.plot(gc_dict.keys(), gc_dict.values(), alpha=1, label = labels, zorder=1, color='grey', linewidth=4)
mfe_plot = ax_main.plot(mfe_dict.keys(), mfe_dict.values(), alpha=0.01, label = labels, zorder=1,color='#df8500', linewidth=4)
for item,lbl,viz in [(a_plot,"A%",False),(t_plot,"T%",False),(g_plot,"G%",False),(c_plot,"C%",False),(gc_plot,"GC%",True),(mfe_plot,"MFE",False)]:
line_collections.append(item)
labels.append(lbl)
start_visible.append(viz)
leg_offset = (30-17)*5
if leg_offset <0:
leg_offset = 0
ilp = InteractiveLegendPlugin(line_collections, labels, alpha_unsel=0,alpha_sel=0.85,start_visible=start_visible,fontsize=30,xoffset=leg_offset)
htmllabels = {1:[],2:[],3:[]}
all_start_points = {1:[],2:[],3:[]}
points1 =ax_f1.plot(all_start_points[1], [0.75]*len(all_start_points[1]), 'o', color='b',mec='k', ms=13, mew=1, alpha=0, zorder=3)
points2 =ax_f2.plot(all_start_points[2], [0.75]*len(all_start_points[2]), 'o', color='b',mec='k', ms=13, mew=1, alpha=0, zorder=3)
points3 =ax_f3.plot(all_start_points[3], [0.75]*len(all_start_points[3]), 'o', color='b',mec='k', ms=13, mew=1, alpha=0, zorder=3)
ax_f3.axes.get_yaxis().set_ticks([])
ax_f2.axes.get_yaxis().set_ticks([])
ax_f1.axes.get_yaxis().set_ticks([])
plugins.connect(fig, ilp, TopToolbar(yoffset=750,xoffset=600),DownloadProfile(returnstr=""),DownloadPNG(returnstr=tran))
ax_main.set_facecolor(background_col)
# This changes the size of the tick markers, works on both firefox and chrome.
ax_main.tick_params('both', labelsize=marker_size)
ax_main.xaxis.set_major_locator(plt.MaxNLocator(3))
ax_main.yaxis.set_major_locator(plt.MaxNLocator(3))
ax_main.grid(True, color="white", linewidth=30,linestyle="solid")
#Without this style tag the markers sizes will appear correct on browser but be original size when downloaded via png
graph = "<style>.mpld3-xaxis {{font-size: {0}px;}} .mpld3-yaxis {{font-size: {0}px;}}</style>".format(marker_size)
graph += "<div style='padding-left: 55px;padding-top: 22px;'> <a href='https://trips.ucc.ie/short/{0}' target='_blank' ><button class='button centerbutton' type='submit'><b>Direct link to this plot</b></button></a> </div>".format(short_code)
graph += mpld3.fig_to_html(fig)
return graph
def gc_metagene(title, short_code, background_col, readlength_col, title_size, axis_label_size, subheading_size, marker_size, traninfo):
labels = ["CDS markers"]
start_visible=[True]
stop_codons = ["TAG","TAA","TGA"]
frame_orfs = {1:[],2:[],3:[]}
color_dict = {'frames': ['#FF4A45', '#64FC44', '#5687F9']}
gene = ""
y_max = 100
fig = plt.figure(figsize=(13,8))
ax_main = plt.subplot2grid((30,1), (0,0),rowspan=22)
ax_main.spines['bottom'].set_visible(False)
ax_main.set_ylabel("%", fontsize=axis_label_size, labelpad=30)
ax_main.set_ylim(0, y_max)
ax_main.set_xlim(0, 1500)
cds_markers = ax_main.plot((500,500), (0, y_max-3), color="black",linestyle = 'solid', linewidth=2)
cds_markers += ax_main.plot((1000,1000), (0, y_max-3), color="black",linestyle = 'solid', linewidth=2)
#ax_nucseq.set_xlabel('Transcript: {} Length: {} nt'.format(tran, tranlen), fontsize=subheading_size, labelpad=10)
xy = 0
color_list = ["#FF4A45","#64FC44","#5687F9"]
for label in ax_main.xaxis.get_majorticklabels():
label.set_fontsize(36)
title_str = '{} ({})'.format(gene,short_code)
plt.title(title_str, fontsize=title_size,y=36)
line_collections = [cds_markers]
plot_gc = True
plot_mfe = False
if plot_mfe == True and vienna_rna == True:
step_size = 10
window_size = 60
mfe_dict = collections.OrderedDict()
for item in traninfo:
transcript = item[0]
cds_start = float(item[1])
cds_stop = float(item[2])
seq = item[3]
seqlen = len(seq)
for i in range(0,len(seq)-(window_size),step_size):
seq_window = str(seq[i:i+window_size])
(ss, mfe) = RNA.fold(seq_window)
if i < cds_start:
per = (i+(window_size/2)/cds_start)*5
if i >= cds_start and i <= cds_stop:
per = 500+((i+(window_size/2)/(cds_stop-cds_start))*5)
if i > cds_stop:
per = 1000+((i+(window_size/2)/(seqlen-cds_stop))*5)
if per not in mfe_dict:
mfe_dict[per] = [abs(mfe)]
else:
mfe_dict[per].append(abs(mfe))
for per in mfe_dict:
mfe_dict[per] = sum(mfe_dict[per])/len(mfe_dict[per])
if plot_gc == True:
step_size = 10
window_size = 60
a_dict = {}
t_dict = {}
g_dict = {}
c_dict = {}
gc_dict = {}
sorted_a_dict = collections.OrderedDict()
sorted_t_dict = collections.OrderedDict()
sorted_g_dict = collections.OrderedDict()
sorted_c_dict = collections.OrderedDict()
sorted_gc_dict = collections.OrderedDict()
#for i in range(0,1503):
# a_dict[i] = [0]
# t_dict[i] = [0]
# g_dict[i] = [0]
# c_dict[i] = [0]
# gc_dict[i] = [0]
for item in traninfo:
transcript = item[0]
cds_start = float(item[1])
cds_stop = float(item[2])
seq = item[3]
seqlen = len(seq)
for i in range(0,len(seq)-(window_size),step_size):
mid_window = i+(window_size/2)
a_count = 0.0
t_count = 0.0
g_count = 0.0
c_count = 0.0
for x in range(i,i+window_size):
if seq[x] == "A":
a_count += 1
elif seq[x] == "T":
t_count += 1
elif seq[x] == "G":
g_count += 1
elif seq[x] == "C":
c_count += 1
gc_count = g_count + c_count
norm_a = a_count/window_size
norm_t = t_count/window_size
norm_g = g_count/window_size
norm_c = c_count/window_size
norm_gc = gc_count/window_size
final_a = norm_a*y_max
final_t = norm_t*y_max
final_g = norm_g*y_max
final_c = norm_c*y_max
final_gc = norm_gc*y_max
if mid_window < cds_start:
per = mid_window/cds_start
per = per*500
per = int(per)
if mid_window >= cds_start and mid_window <= cds_stop:
per = (mid_window-cds_start)/(cds_stop-cds_start)
per = per*500
per += 500
per = int(per)
if mid_window > cds_stop:
per = (mid_window-cds_stop)/(seqlen-cds_stop)
per = per*500
per += 1000
per = int(per)
if per not in a_dict:
a_dict[per] = [final_a]
else:
a_dict[per].append(final_a)
if per not in t_dict:
t_dict[per] = [final_t]
else:
t_dict[per].append(final_t)
if per not in g_dict:
g_dict[per] = [final_g]
else:
g_dict[per].append(final_g)
if per not in c_dict:
c_dict[per] = [final_c]
else:
c_dict[per].append(final_c)
if per not in gc_dict:
gc_dict[per] = [final_gc]
else:
gc_dict[per].append(final_gc)
for per in a_dict:
a_dict[per] = sum(a_dict[per])/len(a_dict[per])
for per in t_dict:
t_dict[per] = sum(t_dict[per])/len(t_dict[per])
for per in g_dict:
g_dict[per] = sum(g_dict[per])/len(g_dict[per])
for per in c_dict:
c_dict[per] = sum(c_dict[per])/len(c_dict[per])
for per in sorted(gc_dict.keys()):
sorted_gc_dict[per] = sum(gc_dict[per])/len(gc_dict[per])
a_plot = ax_main.plot(a_dict.keys(), a_dict.values(), alpha=0.01, label = labels, zorder=1, color=color_dict['frames'][0], linewidth=4)
t_plot = ax_main.plot(t_dict.keys(), t_dict.values(), alpha=0.01, label = labels, zorder=1, color=color_dict['frames'][1], linewidth=4)
g_plot = ax_main.plot(g_dict.keys(), g_dict.values(), alpha=0.01, label = labels, zorder=1, color=color_dict['frames'][2], linewidth=4)
c_plot = ax_main.plot(c_dict.keys(), c_dict.values(), alpha=0.01, label = labels, | |
<gh_stars>0
from django.contrib.auth.models import User
from django.db import models
# Create your models here.
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
HTTP_CHOICE = (
('HTTP', 'HTTP'),
('HTTPS', 'HTTPS')
)
REQUEST_TYPE_CHOICE = (
('POST', 'POST'),
('GET', 'GET'),
('PUT', 'PUT'),
('DELETE', 'DELETE')
)
REQUEST_PARAMETER_TYPE_CHOICE = (
('form-data', '表单(form-data)'),
('raw', '源数据(raw)'),
('Restful', 'Restful')
)
PARAMETER_TYPE_CHOICE = (
('text', 'text'),
('file', 'file')
)
HTTP_CODE_CHOICE = (
('200', '200'),
('404', '404'),
('400', '400'),
('502', '502'),
('500', '500'),
('302', '302'),
)
EXAMINE_TYPE_CHOICE = (
('no_check', '不校验'),
('only_check_status', '校验http状态'),
('json', 'JSON校验'),
('entirely_check', '完全校验'),
('Regular_check', '正则校验'),
)
UNIT_CHOICE = (
('m', '分'),
('h', '时'),
('d', '天'),
('w', '周'),
)
RESULT_CHOICE = (
('PASS', '成功'),
('FAIL', '失败'),
)
TASK_CHOICE = (
('circulation', '循环'),
('timing', '定时'),
)
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
# ==================扩展用户====================================
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name='用户', related_name='user')
phone = models.CharField(max_length=11, default='', blank=True, verbose_name='手机号')
def __unicode__(self):
return self.user.username
def __str__(self):
return self.phone
class Project(models.Model):
"""
项目表
"""
ProjectType = (
('Web', 'Web'),
('App', 'App')
)
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=50, verbose_name='项目名称')
version = models.CharField(max_length=50, verbose_name='版本')
type = models.CharField(max_length=50, verbose_name='类型', choices=ProjectType)
description = models.CharField(max_length=1024, blank=True, null=True, verbose_name='描述')
status = models.BooleanField(default=True, verbose_name='状态')
LastUpdateTime = models.DateTimeField(auto_now=True, verbose_name='最近修改时间')
createTime = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, max_length=1024, verbose_name='创建人')
def __unicode__(self):
return self.name
def __str__(self):
return self.name
class Meta:
verbose_name = '项目'
verbose_name_plural = '项目'
class ProjectDynamic(models.Model):
"""
项目动态
"""
id = models.AutoField(primary_key=True)
project = models.ForeignKey(Project, related_name='dynamic_project', on_delete=models.CASCADE, verbose_name='所属项目')
time = models.DateTimeField(max_length=128, verbose_name='操作时间')
type = models.CharField(max_length=50, verbose_name='操作类型')
operationObject = models.CharField(max_length=50, verbose_name='操作对象')
user = models.ForeignKey(User, blank=True, null=True, related_name='userName',
on_delete=models.SET_NULL, verbose_name='操作人')
description = models.CharField(max_length=1024, blank=True, null=True, verbose_name='描述')
def __unicode__(self):
return self.type
class Meta:
verbose_name = '项目动态'
verbose_name_plural = '项目动态'
class ProjectMember(models.Model):
"""
项目成员
"""
CHOICES = (
('超级管理员', '超级管理员'),
('开发人员', '开发人员'),
('测试人员', '测试人员')
)
id = models.AutoField(primary_key=True)
permissionType = models.CharField(max_length=50, verbose_name='权限角色', choices=CHOICES)
project = models.ForeignKey(Project, related_name='member_project', on_delete=models.CASCADE, verbose_name='所属项目')
user = models.ForeignKey(User, related_name='member_user', on_delete=models.CASCADE, verbose_name='用户')
def __unicode__(self):
return self.permissionType
def __str__(self):
return self.permissionType
class Meta:
verbose_name = '项目成员'
verbose_name_plural = '项目成员'
class GlobalHost(models.Model):
"""
host域名
"""
id = models.AutoField(primary_key=True)
project = models.ForeignKey(Project, on_delete=models.CASCADE, verbose_name='项目')
name = models.CharField(max_length=50, verbose_name='名称')
host = models.CharField(max_length=1024, verbose_name='Host地址')
description = models.CharField(max_length=1024, blank=True, null=True, verbose_name='描述')
status = models.BooleanField(default=True, verbose_name='状态')
def __unicode__(self):
return self.name
def __str__(self):
return self.name
class Meta:
verbose_name = 'HOST'
verbose_name_plural = 'HOST管理'
class CustomMethod(models.Model):
"""
自定义方法
"""
id = models.AutoField(primary_key=True)
project = models.ForeignKey(Project, on_delete=models.CASCADE, verbose_name='项目')
name = models.CharField(max_length=50, verbose_name='方法名')
description = models.CharField(max_length=1024, blank=True, null=True, verbose_name='描述')
type = models.CharField(max_length=50, verbose_name='类型')
dataCode = models.TextField(verbose_name='代码')
status = models.BooleanField(default=True, verbose_name='状态')
def __unicode__(self):
return self.name
class Meta:
verbose_name = '自定义方法'
verbose_name_plural = '自定义方法'
class ApiGroupLevelFirst(models.Model):
"""
接口一级分组
"""
id = models.AutoField(primary_key=True)
project = models.ForeignKey(Project, on_delete=models.CASCADE, verbose_name='项目')
name = models.CharField(max_length=50, verbose_name='接口一级分组名称')
def __unicode__(self):
return self.name
def __str__(self):
return self.name
class Meta:
verbose_name = '接口分组'
verbose_name_plural = '接口分组'
class ApiInfo(models.Model):
"""
接口信息
"""
id = models.AutoField(primary_key=True)
project = models.ForeignKey(Project, related_name='api_project', on_delete=models.CASCADE, verbose_name='所属项目')
apiGroupLevelFirst = models.ForeignKey(ApiGroupLevelFirst, blank=True, null=True,
related_name='First',
on_delete=models.SET_NULL, verbose_name='所属一级分组')
name = models.CharField(max_length=50, verbose_name='接口名称')
httpType = models.CharField(max_length=50, default='HTTP', verbose_name='http/https', choices=HTTP_CHOICE)
requestType = models.CharField(max_length=50, verbose_name='请求方式', choices=REQUEST_TYPE_CHOICE)
apiAddress = models.CharField(max_length=1024, verbose_name='接口地址')
requestParameterType = models.CharField(max_length=50, verbose_name='请求参数格式', choices=REQUEST_PARAMETER_TYPE_CHOICE)
status = models.BooleanField(default=True, verbose_name='状态')
mockStatus = models.BooleanField(default=False, verbose_name="mock状态")
mockCode = models.CharField(max_length=50, blank=True, null=True, verbose_name='HTTP状态', choices=HTTP_CODE_CHOICE)
data = models.TextField(blank=True, null=True, verbose_name='mock内容')
lastUpdateTime = models.DateTimeField(auto_now=True, verbose_name='最近更新')
userUpdate = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, max_length=50, verbose_name='更新人',
related_name='ApiUpdateUser')
description = models.CharField(max_length=1024, blank=True, null=True, verbose_name='描述')
def __unicode__(self):
return self.name
def __str__(self):
return self.name
class Meta:
verbose_name = '接口'
verbose_name_plural = '接口管理'
class ApiHead(models.Model):
id = models.AutoField(primary_key=True)
api = models.ForeignKey(ApiInfo, on_delete=models.CASCADE, verbose_name="所属接口", related_name='headers')
name = models.CharField(max_length=1024, verbose_name="标签")
value = models.CharField(max_length=1024, blank=True, null=True, verbose_name='内容')
def __unicode__(self):
return self.name
def __str__(self):
return self.name
class Meta:
verbose_name = '请求头'
verbose_name_plural = '请求头管理'
class ApiParameter(models.Model):
id = models.AutoField(primary_key=True)
api = models.ForeignKey(ApiInfo, on_delete=models.CASCADE, verbose_name="所属接口", related_name='requestParameter')
name = models.CharField(max_length=1024, verbose_name="参数名")
_type = models.CharField(default="String", max_length=1024, verbose_name='参数类型', choices=(('Int', 'Int'), ('String', 'String')))
value = models.CharField(max_length=1024, blank=True, null=True, verbose_name='参数值')
required = models.BooleanField(default=True, verbose_name="是否必填")
restrict = models.CharField(max_length=1024, blank=True, null=True, verbose_name="输入限制")
description = models.CharField(max_length=1024, blank=True, null=True, verbose_name="描述")
def __unicode__(self):
return self.name
def __str__(self):
return self.name
class Meta:
verbose_name = '请求参数'
verbose_name_plural = '请求参数管理'
class ApiParameterRaw(models.Model):
id = models.AutoField(primary_key=True)
api = models.OneToOneField(ApiInfo, on_delete=models.CASCADE, verbose_name="所属接口", related_name='requestParameterRaw')
data = models.TextField(blank=True, null=True, verbose_name='内容')
class Meta:
verbose_name = '请求参数Raw'
class ApiResponse(models.Model):
id = models.AutoField(primary_key=True)
api = models.ForeignKey(ApiInfo, on_delete=models.CASCADE, verbose_name="所属接口", related_name='response')
name = models.CharField(max_length=1024, verbose_name="参数名")
_type = models.CharField(default="String", max_length=1024, verbose_name='参数类型', choices=(('Int', 'Int'), ('String', 'String')))
value = models.CharField(max_length=1024, blank=True, null=True, verbose_name='参数值')
required = models.BooleanField(default=True, verbose_name="是否必含")
description = models.CharField(max_length=1024, blank=True, null=True, verbose_name="描述")
def __unicode__(self):
return self.name
def __str__(self):
return self.name
class Meta:
verbose_name = '返回参数'
verbose_name_plural = '返回参数管理'
class APIRequestHistory(models.Model):
"""
接口请求历史
"""
id = models.AutoField(primary_key=True)
api = models.ForeignKey(ApiInfo, on_delete=models.CASCADE, verbose_name='接口')
requestTime = models.DateTimeField(auto_now_add=True, verbose_name='请求时间')
requestType = models.CharField(max_length=50, verbose_name='请求方法')
requestAddress = models.CharField(max_length=1024, verbose_name='请求地址')
httpCode = models.CharField(max_length=50, verbose_name='HTTP状态')
def __unicode__(self):
return self.requestAddress
class Meta:
verbose_name = '接口请求历史'
verbose_name_plural = '接口请求历史'
class ApiOperationHistory(models.Model):
"""
API操作历史
"""
id = models.AutoField(primary_key=True)
api = models.ForeignKey(ApiInfo, on_delete=models.CASCADE, verbose_name='接口')
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, max_length=50, verbose_name='用户姓名')
time = models.DateTimeField(auto_now_add=True, verbose_name='操作时间')
description = models.CharField(max_length=1024, blank=True, null=True, verbose_name='操作内容')
def __unicode__(self):
return self.description
class Meta:
verbose_name = '接口操作历史'
verbose_name_plural = '接口操作历史'
class AutomationGroupLevelFirst(models.Model):
"""
自动化用例一级分组
"""
id = models.AutoField(primary_key=True)
project = models.ForeignKey(Project, on_delete=models.CASCADE, verbose_name='项目')
name = models.CharField(max_length=50, verbose_name='用例一级分组')
def __unicode__(self):
return self.name
def __str__(self):
return self.name
class Meta:
verbose_name = '用例分组'
verbose_name_plural = '用例分组管理'
class AutomationTestCase(models.Model):
"""
自动化测试用例
"""
id = models.AutoField(primary_key=True)
project = models.ForeignKey(Project, on_delete=models.CASCADE, verbose_name='所属项目')
automationGroupLevelFirst = models.ForeignKey(AutomationGroupLevelFirst, blank=True, null=True,
on_delete=models.SET_NULL, verbose_name='所属用例一级分组', related_name="automationGroup")
# automationGroupLevelSecond = models.ForeignKey(AutomationGroupLevelSecond, blank=True, null=True,
# on_delete=models.SET_NULL, verbose_name='所属用例二级分组')
caseName = models.CharField(max_length=50, verbose_name='用例名称')
user = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True, verbose_name="创建人",
related_name="createUser")
description = models.CharField(max_length=1024, blank=True, null=True, verbose_name='描述')
updateTime = models.DateTimeField(auto_now=True, verbose_name='更新时间')
def __unicode__(self):
return self.caseName
def __str__(self):
return self.caseName
class Meta:
verbose_name = '自动化测试用例'
verbose_name_plural = '自动化测试用例'
class AutomationCaseApi(models.Model):
"""
用例执行接口
"""
id = models.AutoField(primary_key=True)
automationTestCase = models.ForeignKey(AutomationTestCase, on_delete=models.CASCADE,
verbose_name='用例', related_name="api")
name = models.CharField(max_length=50, verbose_name='接口名称')
httpType = models.CharField(max_length=50, default='HTTP', verbose_name='HTTP/HTTPS', choices=HTTP_CHOICE)
requestType = models.CharField(max_length=50, verbose_name='请求方式', choices=REQUEST_TYPE_CHOICE)
apiAddress = models.CharField(max_length=1024, verbose_name='接口地址')
requestParameterType = models.CharField(max_length=50, verbose_name='参数请求格式', choices=REQUEST_PARAMETER_TYPE_CHOICE)
formatRaw = models.BooleanField(default=False, verbose_name="是否转换成源数据")
examineType = models.CharField(default='no_check', max_length=50, verbose_name='校验方式', choices=EXAMINE_TYPE_CHOICE)
httpCode = models.CharField(max_length=50, blank=True, null=True, verbose_name='HTTP状态', choices=HTTP_CODE_CHOICE)
responseData = models.TextField(blank=True, null=True, verbose_name='返回内容')
def __unicode__(self):
return self.name
def __str__(self):
return self.name
class Meta:
verbose_name = '用例接口'
verbose_name_plural = '用例接口管理'
class AutomationHead(models.Model):
"""
请求头
"""
id = models.AutoField(primary_key=True)
automationCaseApi = models.ForeignKey(AutomationCaseApi, related_name='header',
on_delete=models.CASCADE, verbose_name='接口')
name = models.CharField(max_length=1024, verbose_name='参数名')
value = models.CharField(max_length=1024, verbose_name='内容')
interrelate = models.BooleanField(default=False, verbose_name='是否关联')
def __unicode__(self):
return self.value
class Meta:
verbose_name = '请求头'
verbose_name_plural = '请求头管理'
class AutomationParameter(models.Model):
"""
请求的参数
"""
id = models.AutoField(primary_key=True)
automationCaseApi = models.ForeignKey(AutomationCaseApi, related_name='parameterList',
on_delete=models.CASCADE, verbose_name='接口')
name = models.CharField(max_length=1024, verbose_name='参数名')
value = models.CharField(max_length=1024, verbose_name='内容', blank=True, null=True)
interrelate = models.BooleanField(default=False, verbose_name='是否关联')
def __unicode__(self):
return self.value
class Meta:
verbose_name = '接口参数'
verbose_name_plural = '接口参数管理'
class AutomationParameterRaw(models.Model):
"""
请求的源数据参数
"""
id = models.AutoField(primary_key=True)
automationCaseApi = models.OneToOneField(AutomationCaseApi, related_name='parameterRaw',
on_delete=models.CASCADE, verbose_name='接口')
data = models.TextField(verbose_name='源数据请求参数', blank=True, null=True)
class Meta:
verbose_name = '源数据参数'
verbose_name_plural = '源数据参数管理'
class AutomationResponseJson(models.Model):
"""
返回JSON参数
"""
id = models.AutoField(primary_key=True)
automationCaseApi = models.ForeignKey(AutomationCaseApi, related_name='response',
on_delete=models.CASCADE, verbose_name='接口')
name = models.CharField(max_length=1024, verbose_name='JSON参数', blank=True, null=True)
tier = models.CharField(max_length=1024, verbose_name='层级关系', blank=True, null=True)
type = models.CharField(max_length=1024, verbose_name="关联类型", default="json", choices=(('json', 'json'),('Regular', 'Regular')))
def __str__(self):
return self.name
class Meta:
verbose_name = '结果JSON参数'
verbose_name_plural = '结果JSON参数管理'
class AutomationTestResult(models.Model):
"""
手动执行结果
"""
id = models.AutoField(primary_key=True)
automationCaseApi = models.OneToOneField(AutomationCaseApi, on_delete=models.CASCADE, verbose_name='接口'
, related_name="test_result")
url = models.CharField(max_length=1024, verbose_name='请求地址')
requestType = models.CharField(max_length=1024, verbose_name='请求方式', choices=REQUEST_TYPE_CHOICE)
host = models.CharField(max_length=1024, verbose_name='测试地址', null=True, blank=True)
header = models.CharField(max_length=1024, blank=True, null=True, verbose_name='请求头')
parameter = models.TextField(blank=True, null=True, verbose_name='请求参数')
statusCode = models.CharField(blank=True, null=True, max_length=1024, verbose_name='期望HTTP状态', choices=HTTP_CODE_CHOICE)
examineType = models.CharField(max_length=1024, verbose_name='匹配规则')
data = models.TextField(blank=True, null=True, verbose_name='规则内容')
result = models.CharField(max_length=50, verbose_name='测试结果', choices=RESULT_CHOICE)
httpStatus = models.CharField(max_length=50, blank=True, null=True, verbose_name='http状态', choices=HTTP_CODE_CHOICE)
responseData = models.TextField(blank=True, null=True, verbose_name='实际返回内容')
testTime = models.DateTimeField(auto_now_add=True, verbose_name='测试时间')
def __unicode__(self):
return self.httpStatus
class Meta:
verbose_name = '手动测试结果'
verbose_name_plural = '手动测试结果管理'
class AutomationTestTask(models.Model):
"""
用例定时任务
"""
id = models.AutoField(primary_key=True)
project = models.OneToOneField(Project, on_delete=models.CASCADE, verbose_name='项目')
Host = models.ForeignKey(GlobalHost, on_delete=models.CASCADE, verbose_name='HOST')
name = models.CharField(max_length=50, verbose_name='任务名称')
type = models.CharField(max_length=50, verbose_name='类型', choices=TASK_CHOICE)
frequency = models.IntegerField(blank=True, null=True, verbose_name='间隔')
unit = models.CharField(max_length=50, blank=True, null=True, verbose_name='单位', choices=UNIT_CHOICE)
startTime = models.DateTimeField(max_length=50, verbose_name='开始时间')
endTime = models.DateTimeField(max_length=50, verbose_name='结束时间')
def __unicode__(self):
return self.name
def __str__(self):
return self.name
class Meta:
verbose_name = '用例定时任务'
verbose_name_plural = '用例定时任务管理'
class AutomationTaskRunTime(models.Model):
"""
用例执行开始和结束时间
"""
id = models.AutoField(primary_key=True)
project = models.ForeignKey(Project, on_delete=models.CASCADE, verbose_name='项目')
startTime = models.CharField(max_length=50, verbose_name='开始时间')
host = models.CharField(max_length=1024, null=True, blank=True, verbose_name='测试地址')
elapsedTime = models.CharField(max_length=50, verbose_name='结束时间')
class Meta:
verbose_name = '用例任务执行时间'
verbose_name_plural | |
<filename>CCPD_Demo.py
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.5.2
# kernelspec:
# display_name: Python(comb_demo)
# language: python
# name: comb_demo
# ---
# %% [markdown]
# # Conformal Change Point Detection demo
# %%
from functools import partial
from CP import pValues
from scipy.interpolate import UnivariateSpline, InterpolatedUnivariateSpline, \
interp1d
import param
from matplotlib.figure import Figure
import panel as pn
import numpy as np
import scipy.stats as ss
from sklearn.model_selection import train_test_split
# %%
from IPython.display import display, HTML
display(HTML("<style>.container {width: 90% !important;} </style>"))
# %%
# pn.extension('mathjax', comm='ipywidgets')
pn.extension('mathjax', comms='vscode')
notes = pn.pane.LaTeX(r"""<h1>Conformal Change-Point Detection</h1>
The framework generally accepted for Change-Point Detection posits a sequence of random variates $X_1, X_2, \dots$, which in a first phase are
each generated independently from a same distribution $p(x)$ up to an index $\tau$ which is a priori unknown. In the second phase, that is, $t < \tau$, the variates $X_t$ are
generated from a different distrbution $q(x)$.<br>
The problem is to detect the change as quickly as possible.<br>
Historically, this problem was studied in the context of industrial quality control to monitor manufacturing processes.
For this reason, the first phase is referred to as "in-control" and the second phase as "out-of-control".
A common class of methods computes a statistics from the sequence of variates and triggers an alarm (i.e. detects a change)
when the statistic exceeds a preset threshold.
The statistic is designed to exhibit small fluctuations in the in-control phase and to diverge during the out-of-control phase.
The lower the threshold, the quickest the detection during the out-of-control phase, but also the higher the chance of false alarm
during the in-control phase.<br>
The established methods, namely CUSUM and Shiryaev-Roberts, require the knowledge of the in-control probability density $p(x)$ as
well as of the out-of-control probability density $q(x)$.<br>
The conformal CPD approach relies only on the availability of a sufficiently sample of in-control variates.
<h2>The demo</h2>
In this demo, the user is presented with a number of controls (sliders, selection boxes) on the left and with charts on the right.
Going from top to bottom, random variates are generated, p-values are calculated, then transformed into Bayes Factors, and finally
a CPD statistic is computed.
<h4>Synthetic Data Set</h4>
The in-control (IC) and out-of-control (OOC) distributions are both Gaussian. The user can change mean and variance.
It is also possible to vary the number of samples for each phase.
The IC variates are represented in green, the OOC variates in red.
A calibration set -- with the IC mean and variance -- is also created (but not shown). The user can control the size of the calibration set.<br>
P-values are computed for the IC and OOC samples and shown in the second chart from the top.
A very simple non-conformity measure is used: $\alpha_i = \left | x_i \right |$.
<h4>Betting Function</h4>
The p-value is transformed via a "calibrator" or "betting function" into a Bayes Factor or e-value.
The following choices of calibrator are offered:<br>
\[
\begin{array}{lc}
\text{power calibrator} & k p ^ {k-1}\\
\text{simple mixture} & \frac{1-p+p\log p }{p \log^2 p }\\
\text{linear} & 2(1-p) \\
\text{negative logarithm} & -\log(p)
\end{array}
\]
<br>
The computation of the betting function can also be bypassed by choosing "None".
<h4>CPD Statistic</h4>
The user can choose among various methods: <br>
\[
\begin{array}{lc}
\text{CUSUM} & S_0=1, \, S_{i+1} = s_i \cdot \max(1,S_i) \\
\text{Shiryaev-Roberts} & S_0=0, \, S_{i+1} = s_i \cdot (1+S_i) \\
\text{First moment}^* & S_0=0, \, S_{i+1} = (s_i-\mu)+S_i \\
\text{Product}^* & S_0=0, \, S_{i+1} = (\log(s_i)+1) + S_i
\end{array}
\]
<br>
The methods marked with an asterisk apply when the betting function is bypassed.<br>
The user can choose the value of the threshold.
The chart shows the behaviour of the statistic and the counts of the alarms, both during the IC phase as well as the OOC phase.
<h2>References</h2>
<ul>
<li> Algorithmic learning in a random world, <NAME>, <NAME>, <NAME>, Springer, 2005
<li> Working papers 24, 26, 29 at <a href="http://www.alrw.net/">ALRW Site</a>
</ul>
""", name="Notes", style={'font-size': '12pt'})
#%%
# srv = notes.show()
# %%
def plot_samples(ic_samples, ooc_samples):
f = Figure(figsize=(12, 3.1))
ax_a = f.add_subplot(1, 1, 1)
x = np.arange(0, ic_samples.shape[0]+ooc_samples.shape[0])
ax_a.plot(x[:ic_samples.shape[0]], ic_samples, "g.",
label="in-control")
ax_a.plot(x[ic_samples.shape[0]:], ooc_samples, "r.",
label="out-of-control")
ax_a.set_title("Samples")
ax_a.legend()
ax_a.set_xlabel('"Time"')
f.tight_layout()
return f
class Synthetic_Data_Set(param.Parameterized):
N_in_control = param.Integer(default=2000, bounds=(100, 10000))
N_out_of_control = param.Integer(default=2000, bounds=(100, 10000))
N_calibration = param.Integer(default=5000, bounds=(100, 10000))
in_control_mean = param.Number(default=0.0, bounds=(-1.0, 1.0), constant=True)
in_control_var = param.Number(default=1.0, bounds=(0.1, 10.0))
out_of_control_mean = param.Number(default=1.0, bounds=(-2.0, 2.0))
out_of_control_var = param.Number(default=1.0, bounds=(0.1, 10.0))
seed = param.Integer(default=0, bounds=(0, 32767))
# Outputs
output = param.Dict(default=dict(),
precedence=-1) # To have all updates in one go
n = 2
def __init__(self, **params):
super(Synthetic_Data_Set, self).__init__(**params)
self.update()
def update(self):
output = dict()
np.random.seed(self.seed)
try:
in_control_samples = ss.norm(loc=self.in_control_mean, scale=np.sqrt(self.in_control_var)).rvs(
size=(self.N_in_control,))
out_of_control_samples = ss.norm(loc=self.out_of_control_mean, scale=np.sqrt(self.out_of_control_var)).rvs(
size=(self.N_out_of_control,))
calibration_samples = ss.norm(loc=self.in_control_mean, scale=np.sqrt(self.in_control_var)).rvs(
size=(self.N_calibration,))
except np.linalg.LinAlgError:
placeholder = np.array([0.0, 1.0])
output['in_control_samples'] = placeholder
output['out_of_control_samples'] = placeholder
output['calibration_samples'] = placeholder
self.output = output
return
output['in_control_samples'] = in_control_samples
output['out_of_control_samples'] = out_of_control_samples
output['calibration_samples'] = calibration_samples
self.output = output
@pn.depends("N_in_control", "N_out_of_control", "N_calibration",
"in_control_mean", "in_control_var",
"out_of_control_mean", "out_of_control_var", "seed")
def view(self):
self.update()
f = plot_samples(
self.output['in_control_samples'], self.output['out_of_control_samples'])
return f
sd = Synthetic_Data_Set(name="Synthetic Data Set")
# %%
# sd_panel = pn.Row(sd, sd.view)
# srv = sd_panel.show()
# %%
# srv.stop()
# %%
def ecdf(x):
v, c = np.unique(x, return_counts='true')
q = np.cumsum(c) / np.sum(c)
return v, q
def ECDF_cal_p(p_test, p_cal):
v, q = ecdf(p_cal)
v = np.concatenate(([0], v))
q = np.concatenate(([0], q))
us = interp1d(v, q, bounds_error=False, fill_value=(0, 1))
return us(p_test)
# %%
# MICP
# %%
# %%
def plot_pVals(ic_samples, ooc_samples):
f = Figure(figsize=(12, 3.1))
ax_a = f.add_subplot(1, 1, 1)
x = np.arange(0, ic_samples.shape[0]+ooc_samples.shape[0])
ax_a.plot(x[:ic_samples.shape[0]], ic_samples, "g.",
label="in-control")
ax_a.plot(x[ic_samples.shape[0]:], ooc_samples, "r.",
label="out-of-control")
ax_a.set_title("p-values")
ax_a.legend()
ax_a.set_xlabel('"Time"')
f.tight_layout()
return f
# %%
def ncm(scores):
return np.abs(scores)
class MICP(param.Parameterized):
sd = param.Parameter(precedence=-1)
ic_pVals = param.Array(precedence=-1)
ooc_pVals = param.Array(precedence=-1)
def __init__(self, sd, **params):
self.sd = sd
super(MICP, self).__init__(**params)
self.update()
def aux_update_(self, in_control_samples, out_of_control_samples, calibration_samples):
randomize = True
with param.batch_watch(self):
self.ic_pVals = pValues(
calibrationAlphas=ncm(calibration_samples),
testAlphas=ncm(in_control_samples),
randomized=randomize)
self.ooc_pVals = pValues(
calibrationAlphas=ncm(calibration_samples),
testAlphas=ncm(out_of_control_samples),
randomized=randomize)
@pn.depends("sd.output", watch=True)
def update(self):
self.aux_update_(**self.sd.output)
@pn.depends("ic_pVals", "ooc_pVals")
def view(self):
return pn.Column(
plot_pVals(self.ic_pVals, self.ooc_pVals)
)
# %%
# Now we compute the p-values with Mondrian Inductive
# %%
micp = MICP(sd)
# %%
micp_panel = pn.Row(micp.sd.param, pn.Column(micp.sd.view,
micp.view))
# %%
# micp_panel
# %%
def power_calibrator(p, k):
return k*(p**(k-1))
def simple_mixture(p):
return (1-p+p*np.log(p))/(p*(np.log(p)*np.log(p)))
class Betting_Function(param.Parameterized):
micp = param.Parameter(precedence=-1)
k = param.Number(default=0.8, bounds=(0.0, 1.0))
ic_bf = param.Array(precedence=-1)
ooc_bf = param.Array(precedence=-1)
betting_function = param.ObjectSelector(default="Power calibrator",
objects=["Power calibrator",
"Simple mixture",
"Linear",
"Negative logarithm",
"None"])
def __init__(self, micp, **params):
self.micp = micp
super(Betting_Function, self).__init__(**params)
self.update()
@pn.depends("k", "betting_function", "micp.ic_pVals", "micp.ooc_pVals", watch=True)
def update(self):
bf_dict = {
"Power calibrator": partial(power_calibrator, k=self.k),
"Simple mixture": simple_mixture,
"Linear": lambda p: 2*(1-p),
"Negative logarithm": lambda p: -np.log(p),
"None": lambda p: p,
}
with param.batch_watch(self):
self.ic_bf = bf_dict[self.betting_function](self.micp.ic_pVals)
self.ooc_bf = bf_dict[self.betting_function](self.micp.ooc_pVals)
@pn.depends("ic_bf", "ic_bf")
def view(self):
return pn.Row(
self.plot_bf()
)
def plot_bf(self):
if self.betting_function=='None':
return None
f = Figure(figsize=(12, 3.1))
ax_a = f.add_subplot(1, 1, 1)
x = np.arange(0, self.ic_bf.shape[0]+self.ooc_bf.shape[0])
ax_a.plot(x[:self.ic_bf.shape[0]], self.ic_bf, "g.",
label="in-control")
ax_a.plot(x[self.ic_bf.shape[0]:], self.ooc_bf, "r.",
label="out-of-control")
ax_a.set_title("e-values")
ax_a.legend()
ax_a.set_xlabel('"Time"')
f.tight_layout()
return f
# %%
bf = Betting_Function(micp, name="Betting Function")
# %%
bf_panel = pn.Column(pn.Row(micp.sd.param, pn.Column(micp.sd.view,
micp.view)),
pn.Row(bf.param, bf.view))
# %%
# srv = bf_panel.show()
# %%
# srv.stop()
# %%
def CPD_r(s, x, s_0, thr):
"""return statistic for change-point detection V_n = s(V_{n-1})*(x_n)
The statistic is reset to s_0 when the threshold is exceeded.
Appropriate choices for s and s_0 give rise to CUSUM and S-R.
NOTE: differs from the usual definition by not having f() and g()."""
S = np.empty_like(x)
S[0] = s_0
for i in range(1, len(x)):
if S[i-1] > thr:
prev = s_0
else:
prev = S[i-1]
S[i] = s(prev)*x[i]
return S
def Conformal_r(x, c, thr):
"""Compute the CPD statistic with conformal method"""
S = np.empty_like(x)
S[0] = c(x[0])
for i in range(1, len(x)):
if np.abs(S[i-1]) > thr:
# if S[i-1] > thr:
S[i] = c(x[i])
else:
S[i] = c(x[i])+S[i-1]
return S
def CPD_Conf(x, r, r_0, thr):
"""Vovk's conformal procedure"""
ratios = x[1:]/x[:-1]
R = np.empty_like(x)
R[0] = r_0
for i in range(1, len(R)):
if R[i-1] > thr:
prev = r_0
else:
prev = R[i-1]
R[i] = r(prev)*ratios[i-1]
return R
# %%
import matplotlib
def plot_martingale(mart, ic_size, thr):
f = Figure(figsize=(12, 3.1))
ax_a: matplotlib.axes.Axes = f.add_subplot(1, 1, 1)
x = np.arange(0, mart.shape[0])
ax_a.plot(x[:ic_size], mart[:ic_size], "g.",
label="in-control")
ax_a.plot(x[ic_size:], mart[ic_size:], "r.",
label="out-of-control")
ic_alarms = np.sum(np.abs(mart[:ic_size]) >= thr)
ooc_alarms = np.sum(np.abs(mart[ic_size:]) >= thr)
ax_a.set_title(f"Martingale (CPD statistic)")
ax_a.legend()
ax_a.set_xlabel('"Time"')
ax_a.annotate(f"Alarms\nin-control: {ic_alarms}, out-of-control:{ooc_alarms}",
| |
The string that contains the
System.Windows.Automation.AutomationProperties.ItemStatus that is returned by
System.Windows.Automation.AutomationProperties.GetItemStatus(System.Windows.Depe
ndencyObject).
"""
pass
def GetItemTypeCore(self, *args): #cannot find CLR method
"""
GetItemTypeCore(self: UIElementAutomationPeer) -> str
Gets a human-readable string that contains the item type that the
System.Windows.UIElement for this
System.Windows.Automation.Peers.UIElementAutomationPeer represents. This method
is called by System.Windows.Automation.Peers.AutomationPeer.GetItemType.
Returns: The string that contains the
System.Windows.Automation.AutomationProperties.ItemType that is returned by
System.Windows.Automation.AutomationProperties.GetItemType(System.Windows.Depend
encyObject).
"""
pass
def GetLabeledByCore(self, *args): #cannot find CLR method
"""
GetLabeledByCore(self: UIElementAutomationPeer) -> AutomationPeer
Gets the System.Windows.Automation.Peers.AutomationPeer for the element that is
targeted to the System.Windows.UIElement for this
System.Windows.Automation.Peers.UIElementAutomationPeer. This method is called
by System.Windows.Automation.Peers.AutomationPeer.GetLabeledBy.
Returns: The System.Windows.Automation.Peers.AutomationPeer for the element that is
targeted to the System.Windows.UIElement for this
System.Windows.Automation.Peers.UIElementAutomationPeer.
"""
pass
def GetLocalizedControlTypeCore(self, *args): #cannot find CLR method
"""
GetLocalizedControlTypeCore(self: AutomationPeer) -> str
When overridden in a derived class, is called by
System.Windows.Automation.Peers.AutomationPeer.GetLocalizedControlType.
Returns: The type of the control.
"""
pass
def GetNameCore(self, *args): #cannot find CLR method
"""
GetNameCore(self: FrameworkElementAutomationPeer) -> str
Gets the text label of the System.Windows.ContentElement that is associated
with this System.Windows.Automation.Peers.ContentElementAutomationPeer. Called
by System.Windows.Automation.Peers.AutomationPeer.GetName.
Returns: The text label of the element that is associated with this automation peer.
"""
pass
def GetOrientationCore(self, *args): #cannot find CLR method
"""
GetOrientationCore(self: ScrollBarAutomationPeer) -> AutomationOrientation
Gets a value that indicates whether the
System.Windows.Controls.Primitives.ScrollBar that is associated with this
System.Windows.Automation.Peers.ScrollBarAutomationPeer is laid out in a
specific direction. Called by
System.Windows.Automation.Peers.AutomationPeer.GetOrientation.
Returns: System.Windows.Automation.Peers.AutomationOrientation.Horizontal or
System.Windows.Automation.Peers.AutomationOrientation.Vertical, depending on
the orientation of the System.Windows.Controls.Primitives.ScrollBar.
"""
pass
def GetPeerFromPointCore(self, *args): #cannot find CLR method
""" GetPeerFromPointCore(self: AutomationPeer, point: Point) -> AutomationPeer """
pass
def HasKeyboardFocusCore(self, *args): #cannot find CLR method
"""
HasKeyboardFocusCore(self: UIElementAutomationPeer) -> bool
Gets a value that indicates whether the System.Windows.UIElement that is
associated with this System.Windows.Automation.Peers.UIElementAutomationPeer
currently has keyboard input focus. This method is called by
System.Windows.Automation.Peers.AutomationPeer.HasKeyboardFocus.
Returns: true if the element has keyboard input focus; otherwise, false.
"""
pass
def IsContentElementCore(self, *args): #cannot find CLR method
""" IsContentElementCore(self: ScrollBarAutomationPeer) -> bool """
pass
def IsControlElementCore(self, *args): #cannot find CLR method
"""
IsControlElementCore(self: UIElementAutomationPeer) -> bool
Gets or sets a value that indicates whether the System.Windows.UIElement that
is associated with this System.Windows.Automation.Peers.UIElementAutomationPeer
is understood by the end user as interactive. Optionally, the user might
understand the System.Windows.UIElement as contributing to the logical
structure of the control in the GUI. This method is called by
System.Windows.Automation.Peers.AutomationPeer.IsControlElement.
Returns: true.
"""
pass
def IsEnabledCore(self, *args): #cannot find CLR method
"""
IsEnabledCore(self: UIElementAutomationPeer) -> bool
Gets a value that indicates whether the System.Windows.UIElement that is
associated with this System.Windows.Automation.Peers.UIElementAutomationPeer
can accept keyboard focus. This method is called by
System.Windows.Automation.Peers.AutomationPeer.IsKeyboardFocusable.
Returns: A boolean that contains the value of System.Windows.UIElement.IsEnabled.
"""
pass
def IsKeyboardFocusableCore(self, *args): #cannot find CLR method
"""
IsKeyboardFocusableCore(self: UIElementAutomationPeer) -> bool
Gets a value that indicates whether the System.Windows.UIElement that is
associated with this System.Windows.Automation.Peers.UIElementAutomationPeer
can accept keyboard focus. This method is called by
System.Windows.Automation.Peers.AutomationPeer.IsKeyboardFocusable.
Returns: true if the element is focusable by the keyboard; otherwise false.
"""
pass
def IsOffscreenCore(self, *args): #cannot find CLR method
"""
IsOffscreenCore(self: UIElementAutomationPeer) -> bool
Gets a value that indicates whether the System.Windows.UIElement that is
associated with this System.Windows.Automation.Peers.UIElementAutomationPeer is
off the screen. This method is called by
System.Windows.Automation.Peers.AutomationPeer.IsOffscreen.
Returns: true if the element is not on the screen; otherwise, false.
"""
pass
def IsPasswordCore(self, *args): #cannot find CLR method
"""
IsPasswordCore(self: UIElementAutomationPeer) -> bool
Gets a value that indicates whether the System.Windows.UIElement that is
associated with this System.Windows.Automation.Peers.UIElementAutomationPeer
contains protected content. This method is called by
System.Windows.Automation.Peers.AutomationPeer.IsPassword.
Returns: false.
"""
pass
def IsRequiredForFormCore(self, *args): #cannot find CLR method
"""
IsRequiredForFormCore(self: UIElementAutomationPeer) -> bool
Gets a value that indicates whether the System.Windows.UIElement that is
associated with this System.Windows.Automation.Peers.UIElementAutomationPeer is
required to be completed on a form. This method is called by
System.Windows.Automation.Peers.AutomationPeer.IsRequiredForForm.
Returns: A boolean that contains the value that is returned by
System.Windows.Automation.AutomationProperties.GetIsRequiredForForm(System.Windo
ws.DependencyObject), if it's set; otherwise false.
"""
pass
def PeerFromProvider(self, *args): #cannot find CLR method
"""
PeerFromProvider(self: AutomationPeer, provider: IRawElementProviderSimple) -> AutomationPeer
Gets an System.Windows.Automation.Peers.AutomationPeer for the specified
System.Windows.Automation.Provider.IRawElementProviderSimple proxy.
provider: The class that implements
System.Windows.Automation.Provider.IRawElementProviderSimple.
Returns: The System.Windows.Automation.Peers.AutomationPeer.
"""
pass
def ProviderFromPeer(self, *args): #cannot find CLR method
"""
ProviderFromPeer(self: AutomationPeer, peer: AutomationPeer) -> IRawElementProviderSimple
Gets the System.Windows.Automation.Provider.IRawElementProviderSimple for the
specified System.Windows.Automation.Peers.AutomationPeer.
peer: The automation peer.
Returns: The proxy.
"""
pass
def SetFocusCore(self, *args): #cannot find CLR method
"""
SetFocusCore(self: UIElementAutomationPeer)
Sets the keyboard input focus on the System.Windows.UIElement that is
associated with this System.Windows.Automation.Peers.UIElementAutomationPeer.
This method is called by
System.Windows.Automation.Peers.AutomationPeer.SetFocus.
"""
pass
def __init__(self, *args): #cannot find CLR method
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod # known case of __new__
def __new__(self, owner):
""" __new__(cls: type, owner: ScrollBar) """
pass
IsHwndHost = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Gets a value that indicates whether the element that is associated with this System.Windows.Automation.Peers.AutomationPeer hosts hwnds in Windows Presentation Foundation (WPF).
"""
class ScrollViewerAutomationPeer(FrameworkElementAutomationPeer, IScrollProvider):
"""
Exposes System.Windows.Controls.ScrollViewer types to UI Automation.
ScrollViewerAutomationPeer(owner: ScrollViewer)
"""
def GetAcceleratorKeyCore(self, *args): #cannot find CLR method
"""
GetAcceleratorKeyCore(self: UIElementAutomationPeer) -> str
Gets the accelerator key for the System.Windows.UIElement that is associated
with this System.Windows.Automation.Peers.UIElementAutomationPeer. This method
is called by System.Windows.Automation.Peers.AutomationPeer.GetAcceleratorKey.
Returns: The System.Windows.Automation.AutomationProperties.AcceleratorKey that is
returned by
System.Windows.Automation.AutomationProperties.GetAcceleratorKey(System.Windows.
DependencyObject).
"""
pass
def GetAccessKeyCore(self, *args): #cannot find CLR method
"""
GetAccessKeyCore(self: UIElementAutomationPeer) -> str
Gets the access key for the System.Windows.UIElement that is associated with
this System.Windows.Automation.Peers.UIElementAutomationPeer.This method is
called by System.Windows.Automation.Peers.AutomationPeer.GetAccessKey.
Returns: The access key for the System.Windows.UIElement that is associated with this
System.Windows.Automation.Peers.UIElementAutomationPeer.
"""
pass
def GetAutomationControlTypeCore(self, *args): #cannot find CLR method
"""
GetAutomationControlTypeCore(self: ScrollViewerAutomationPeer) -> AutomationControlType
Gets the name of the System.Windows.Controls.ScrollViewer that is associated
with this System.Windows.Automation.Peers.ScrollViewerAutomationPeer. This
method is called by
System.Windows.Automation.Peers.AutomationPeer.GetClassName.
Returns: The System.Windows.Automation.Peers.AutomationControlType.Pane enumeration
value.
"""
pass
def GetAutomationIdCore(self, *args): #cannot find CLR method
"""
GetAutomationIdCore(self: FrameworkElementAutomationPeer) -> str
Gets the string that uniquely identifies the System.Windows.FrameworkElement
that is associated with this
System.Windows.Automation.Peers.FrameworkElementAutomationPeer. Called by
System.Windows.Automation.Peers.AutomationPeer.GetAutomationId.
Returns: The automation identifier for the element associated with the
System.Windows.Automation.Peers.FrameworkElementAutomationPeer, or
System.String.Empty if there isn't an automation identifier.
"""
pass
def GetBoundingRectangleCore(self, *args): #cannot find CLR method
"""
GetBoundingRectangleCore(self: UIElementAutomationPeer) -> Rect
Gets the System.Windows.Rect that represents the bounding rectangle of the
System.Windows.UIElement that is associated with this
System.Windows.Automation.Peers.UIElementAutomationPeer. This method is called
by System.Windows.Automation.Peers.AutomationPeer.GetBoundingRectangle.
Returns: The System.Windows.Rect that contains the coordinates of the element.
Optionally, if the element is not both a System.Windows.Interop.HwndSource and
a System.Windows.PresentationSource, this method returns
System.Windows.Rect.Empty.
"""
pass
def GetChildrenCore(self, *args): #cannot find CLR method
"""
GetChildrenCore(self: UIElementAutomationPeer) -> List[AutomationPeer]
Gets the collection of child elements of the System.Windows.UIElement that is
associated with this System.Windows.Automation.Peers.UIElementAutomationPeer.
This method is called by
System.Windows.Automation.Peers.AutomationPeer.GetChildren.
Returns: A list of child System.Windows.Automation.Peers.AutomationPeer elements.
"""
pass
def GetClassNameCore(self, *args): #cannot find CLR method
"""
GetClassNameCore(self: ScrollViewerAutomationPeer) -> str
Gets the name of the System.Windows.Controls.ScrollViewer that is associated
with this System.Windows.Automation.Peers.ScrollViewerAutomationPeer. This
method is called by
System.Windows.Automation.Peers.AutomationPeer.GetClassName.
Returns: A string that contains "ScrollViewer".
"""
pass
def GetClickablePointCore(self, *args): #cannot find CLR method
"""
GetClickablePointCore(self: UIElementAutomationPeer) -> Point
Gets a System.Windows.Point that represents the clickable space that is on | |
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
from typing import List
from math import isclose
import collections.abc
import azlmbr.bus as bus
import azlmbr.editor as editor
import azlmbr.entity as entity
import azlmbr.legacy.general as general
import azlmbr.object
from editor_python_test_tools.utils import TestHelper as helper
def open_base_level():
helper.init_idle()
helper.open_level("Prefab", "Base")
def find_entity_by_name(entity_name):
"""
Gets an entity ID from the entity with the given entity_name
:param entity_name: String of entity name to search for
:return entity ID
"""
search_filter = entity.SearchFilter()
search_filter.names = [entity_name]
matching_entity_list = entity.SearchBus(bus.Broadcast, 'SearchEntities', search_filter)
if matching_entity_list:
matching_entity = matching_entity_list[0]
if matching_entity.IsValid():
print(f'{entity_name} entity found with ID {matching_entity.ToString()}')
return matching_entity
else:
return matching_entity_list
def get_component_type_id(component_name):
"""
Gets the component_type_id from a given component name
:param component_name: String of component name to search for
:return component type ID
"""
type_ids_list = editor.EditorComponentAPIBus(bus.Broadcast, 'FindComponentTypeIdsByEntityType', [component_name],
entity.EntityType().Game)
component_type_id = type_ids_list[0]
return component_type_id
def get_level_component_type_id(component_name):
"""
Gets the component_type_id from a given component name
:param component_name: String of component name to search for
:return component type ID
"""
type_ids_list = editor.EditorComponentAPIBus(bus.Broadcast, 'FindComponentTypeIdsByEntityType', [component_name],
entity.EntityType().Level)
component_type_id = type_ids_list[0]
return component_type_id
def add_level_component(component_name):
"""
Adds the specified component to the Level Inspector
:param component_name: String of component name to search for
:return Component object.
"""
level_component_list = [component_name]
level_component_type_ids_list = editor.EditorComponentAPIBus(bus.Broadcast, 'FindComponentTypeIdsByEntityType',
level_component_list, entity.EntityType().Level)
level_component_outcome = editor.EditorLevelComponentAPIBus(bus.Broadcast, 'AddComponentsOfType',
[level_component_type_ids_list[0]])
if not level_component_outcome.IsSuccess():
print('Failed to add {} level component'.format(component_name))
return None
level_component = level_component_outcome.GetValue()[0]
return level_component
def add_component(componentName, entityId):
"""
Given a component name, finds component TypeId, adds to given entity, and verifies successful add/active state.
:param componentName: String of component name to add.
:param entityId: Entity to add component to.
:return: Component object.
"""
typeIdsList = editor.EditorComponentAPIBus(bus.Broadcast, 'FindComponentTypeIdsByEntityType', [componentName],
entity.EntityType().Game)
typeNamesList = editor.EditorComponentAPIBus(bus.Broadcast, 'FindComponentTypeNames', typeIdsList)
# If the type name comes back as empty, then it means componentName is invalid
if len(typeNamesList) != 1 or not typeNamesList[0]:
print('Unable to find component TypeId for {}'.format(componentName))
return None
componentOutcome = editor.EditorComponentAPIBus(bus.Broadcast, 'AddComponentsOfType', entityId, typeIdsList)
if not componentOutcome.IsSuccess():
print('Failed to add {} component to entity'.format(typeNamesList[0]))
return None
isActive = editor.EditorComponentAPIBus(bus.Broadcast, 'IsComponentEnabled', componentOutcome.GetValue()[0])
hasComponent = editor.EditorComponentAPIBus(bus.Broadcast, 'HasComponentOfType', entityId, typeIdsList[0])
if isActive:
print('{} component was added to entity'.format(typeNamesList[0]))
else:
print('{} component was added to entity, but the component is disabled'.format(typeNamesList[0]))
if hasComponent:
print('Entity has a {} component'.format(typeNamesList[0]))
return componentOutcome.GetValue()[0]
def add_component_of_type(componentTypeId, entityId):
typeIdsList = [componentTypeId]
componentOutcome = editor.EditorComponentAPIBus(
azlmbr.bus.Broadcast, 'AddComponentsOfType', entityId, typeIdsList)
return componentOutcome.GetValue()[0]
def remove_component(component_name, entity_id):
"""
Removes the specified component from the specified entity.
:param component_name: String of component name to remove.
:param entity_id: Entity to remove component from.
:return: EntityComponentIdPair if removal was successful, else None.
"""
type_ids_list = [get_component_type_id(component_name)]
outcome = editor.EditorComponentAPIBus(bus.Broadcast, 'GetComponentOfType', entity_id, type_ids_list[0])
if outcome.IsSuccess():
component_entity_pair = outcome.GetValue()
editor.EditorComponentAPIBus(bus.Broadcast, 'RemoveComponents', [component_entity_pair])
has_component = editor.EditorComponentAPIBus(bus.Broadcast, 'HasComponentOfType', entity_id, type_ids_list[0])
if has_component:
print(f"Failed to remove {component_name}")
return None
else:
print(f"{component_name} was successfully removed")
return component_entity_pair
else:
print(f"{component_name} not found on entity")
return None
def get_component_property_value(component, component_propertyPath):
"""
Given a component name and component property path, outputs the property's value.
:param component: Component object to act on.
:param componentPropertyPath: String of component property. (e.g. 'Settings|Visible')
:return: Value set in given componentPropertyPath
"""
componentPropertyObj = editor.EditorComponentAPIBus(bus.Broadcast, 'GetComponentProperty', component,
component_propertyPath)
if componentPropertyObj.IsSuccess():
componentProperty = componentPropertyObj.GetValue()
print(f'{component_propertyPath} set to {componentProperty}')
return componentProperty
else:
print(f'FAILURE: Could not get value from {component_propertyPath}')
return None
def set_component_property_value(component, component_propertyPath, value):
"""
Given a component name and component property path, set component property value
:param component: Component object to act on.
:param componentPropertyPath: String of component property. (e.g. 'Settings|Visible')
:param value: new value for the variable being changed in the component
"""
componentPropertyObj = editor.EditorComponentAPIBus(bus.Broadcast, 'SetComponentProperty', component,
component_propertyPath, value)
if componentPropertyObj.IsSuccess():
print(f'{component_propertyPath} set to {value}')
else:
print(f'FAILURE: Could not set value in {component_propertyPath}')
def get_property_tree(component):
"""
Given a configured component object, prints the property tree info from that component
:param component: Component object to act on.
"""
pteObj = editor.EditorComponentAPIBus(bus.Broadcast, 'BuildComponentPropertyTreeEditor', component)
pte = pteObj.GetValue()
print(pte.build_paths_list())
return pte
def compare_values(first_object: object, second_object: object, name: str) -> bool:
# Quick case - can we just directly compare the two objects successfully?
if (first_object == second_object):
result = True
# No, so get a lot more specific
elif isinstance(first_object, collections.abc.Container):
# If they aren't both containers, they're different
if not isinstance(second_object, collections.abc.Container):
result = False
# If they have different lengths, they're different
elif len(first_object) != len (second_object):
result = False
# If they're different strings, they're containers but they failed the == check so
# we know they're different
elif isinstance(first_object, str):
result = False
else:
# It's a collection of values, so iterate through them all...
collection_idx = 0
result = True
for val1, val2 in zip(first_object, second_object):
result = result and compare_values(val1, val2, f"{name} (index [{collection_idx}])")
collection_idx = collection_idx + 1
else:
# Do approximate comparisons for floats
if isinstance(first_object, float) and isclose(first_object, second_object, rel_tol=0.001):
result = True
# We currently don't have a generic way to compare PythonProxyObject contents, so return a
# false positive result for now.
elif isinstance(first_object, azlmbr.object.PythonProxyObject):
print(f"{name}: validation inconclusive, the two objects cannot be directly compared.")
result = True
else:
result = False
if not result:
print(f"compare_values failed: {first_object} ({type(first_object)}) vs {second_object} ({type(second_object)})")
print(f"{name}: {'SUCCESS' if result else 'FAILURE'}")
return result
class Entity:
"""
Entity class used to create entity objects
:param name: String for the name of the Entity
:param id: The ID of the entity
"""
def __init__(self, name: str, id: object = entity.EntityId()):
self.name: str = name
self.id: object = id
self.components: List[object] = None
self.parent_id = None
self.parent_name = None
def create_entity(self, entity_position, components, parent_id=entity.EntityId()):
self.id = editor.ToolsApplicationRequestBus(
bus.Broadcast, "CreateNewEntityAtPosition", entity_position, parent_id
)
if self.id.IsValid():
print(f"{self.name} Entity successfully created")
editor.EditorEntityAPIBus(bus.Event, 'SetName', self.id, self.name)
self.components = []
for component in components:
self.add_component(component)
def add_component(self, component):
new_component = add_component(component, self.id)
if new_component:
self.components.append(new_component)
def add_component_of_type(self, componentTypeId):
new_component = add_component_of_type(componentTypeId, self.id)
self.components.append(new_component)
def remove_component(self, component):
removed_component = remove_component(component, self.id)
if removed_component is not None:
self.components.remove(removed_component)
def get_parent_info(self):
"""
Sets the value for parent_id and parent_name on the entity (self)
Prints the string for papertrail
:return: None
"""
self.parent_id = editor.EditorEntityInfoRequestBus(bus.Event, "GetParent", self.id)
self.parent_name = editor.EditorEntityInfoRequestBus(bus.Event, "GetName", self.parent_id)
print(f"The parent entity of {self.name} is {self.parent_name}")
def set_test_parent_entity(self, parent_entity_obj):
editor.EditorEntityAPIBus(bus.Event, "SetParent", self.id, parent_entity_obj.id)
self.get_parent_info()
def get_set_test(self, component_index: int, path: str, value: object, expected_result: object = None) -> bool:
"""
Used to set and validate changes in component values
:param component_index: Index location in the self.components list
:param path: asset path in the component
:param value: new value for the variable being changed in the component
:param expected_result: (optional) check the result against a specific expected value
"""
if expected_result is None:
expected_result = value
# Test Get/Set (get old value, set new value, check that new value was set correctly)
print(f"Entity {self.name} Path {path} Component Index {component_index} ")
component = self.components[component_index]
old_value = get_component_property_value(component, path)
if old_value is not None:
print(f"SUCCESS: Retrieved property Value for {self.name}")
else:
print(f"FAILURE: Failed to find value in {self.name} {path}")
return False
if old_value == expected_result:
print((f"WARNING: get_set_test on {self.name} is setting the same value that already exists ({old_value})."
"The set results will be inconclusive."))
editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", component, path, value)
new_value = get_component_property_value(self.components[component_index], path)
if new_value is not None:
print(f"SUCCESS: Retrieved new property Value for {self.name}")
else:
print(f"FAILURE: Failed to find new value in {self.name}")
return False
return compare_values(new_value, expected_result, f"{self.name} {path}")
def get_set_test(entity: object, component_index: int, path: str, value: object) -> bool:
"""
Used to set and validate changes in component values
:param component_index: Index location in the entity.components list
:param path: asset path in the component
:param value: new value for the variable being changed in the component
"""
return entity.get_set_test(component_index, path, value)
def get_set_property_test(ly_object: object, attribute_name: str, value: object, expected_result: object = None) -> bool:
"""
Used to set and validate BehaviorContext property changes in Open 3D Engine objects
:param ly_object: The Open 3D Engine object to test
:param attribute_name: property (attribute) name in the BehaviorContext
:param value: | |
coordinates loaded into RAM
PARAMS['marked_imgs'] = []
# find the index of the selected image in the new list
n = image_list.index(file_name)
## update the global
PARAMS['index'] = n
# print(" image index = %s, name = %s" % (n, PARAMS['image_list'][n]))
## redraw canvas items with updated global values as the given image index
self.load_img()
except:
showerror("Open Source File", "Failed to read file\n'%s'" % fname)
return
def reset_globals(self):
""" One-stop function for resetting global parameters that often neeed to be reset
when conditions/data changes.
"""
global PARAMS
PARAMS['img_coords'] = {}
PARAMS['img_box_size'] = 0
return
def next_img(self, direction):
""" Increments the current image index based on the direction given to the function.
"""
global PARAMS
n = PARAMS['index']
image_list = PARAMS['img_list']
file_dir = PARAMS['file_dir']
image_coordinates = PARAMS['img_coords']
## save particles into boxfile, if coordinates are present
if len(image_coordinates) > 0 :
self.save_starfile()
if file_dir == '.':
file_dir=os.getcwd()
try:
self.current_dir.config(text=file_dir + "/")
except:
pass
if direction == 'right':
n += 1
# reset index to the first image when going past the last image in the list
if n > len(image_list)-1 :
n = 0
if direction == 'left':
n -= 1
# reset index to the last image in the list when going past 0
if n < 0:
n = len(image_list)-1
## update global
PARAMS['index'] = n
# update image list in case files have been added/removed
image_list = []
image_list = self.images_in_dir(file_dir)
## update global
PARAMS['img_list'] = image_list
## clear global variables for redraw
self.reset_globals()
## load image with index 'n'
self.load_img()
return
def load_img(self, input_img = None):
""" Load image with specified index
PARAMETERS
index = int(); tied to global 'n' variable, indicating which image to load from the list found in the directory
input_img = np.array; optional grayscale image (0 - 255) to load instead of using the index
RETURNS
Void
"""
global PARAMS, IMAGE_LOADED
n = PARAMS['index']
image_list = PARAMS['img_list']
marked_imgs = PARAMS['marked_imgs']
img_pixel_size_x = PARAMS['img_dimensions'][0] # PARAMS['img_pixel_size_x']
img_pixel_size_y = PARAMS['img_dimensions'][1]
file_dir = PARAMS['file_dir']
RESIZE_IMG = PARAMS['RESIZE_IMG']
img_resize_percent = PARAMS['img_resize_percent']
## force a refresh on all canvas objects based on changing global variables
self.canvas.delete('marker')
self.canvas.delete('particle_positions')
image_w_path = file_dir + "/" + image_list[n]
# update label widget
self.input_text.delete(0, tk.END)
self.input_text.insert(0,image_list[n])
## check if an eplicit image was passed in, otherwise load the image as usual
if input_img is None:
# load image onto canvas object using PhotoImage
with PIL_Image.open(image_w_path) as im:
if RESIZE_IMG:
new_dimensions = self.get_resized_dimensions(img_resize_percent, im.size)
im = im.resize(new_dimensions)
print(" Resize image to", new_dimensions)
im = im.convert('L') ## make grascale
self.current_img = ImageTk.PhotoImage(im)
current_im_data = np.asarray(im)
PARAMS['original_img_data'] = current_im_data
PARAMS['current_img_data'] = current_im_data
else:
## load the supplied image
PIL_img = PIL_Image.fromarray(input_img.astype(np.uint8)) #.convert('L')
self.current_img = ImageTk.PhotoImage(PIL_img)
current_im_data = input_img.astype(np.uint8)
PARAMS['current_img_data'] = current_im_data
# self.current_img = PhotoImage(file=image_w_path)
self.display = self.canvas.create_image(0, 0, anchor=tk.NW, image=self.current_img)
self.canvas.display = self.display
## update the global flag
IMAGE_LOADED = True;
## resize canvas to match new image
x,y = self.current_img.width(), self.current_img.height()
self.canvas.config(width=x, height=y)
PARAMS['img_dimensions'] = (x, y)
base_image_name = os.path.splitext(image_list[n])[0] ## get the base name of the .GIF file
## add an inset red border to the canvas depending if the file name exists in a given list
if base_image_name in marked_imgs:
marker_rect = self.canvas.create_rectangle(x-10,y-10, 10, 10, outline='red', width=10, tags='marker')
## update coordinates in buffer only if we are loading a new image, not if we are passing in a modified image
if input_img is None:
## empty any pre-existing image coordinates in memory
image_coordinates = {}
if len(image_coordinates) == 0: ## avoid overwriting an existing image_coordinates dictionary if it is already present
counter = 0
star_coordinate_file = ""
## to find matching files we need precise names to look for, set them up here:
match_file1 = base_image_name + ".star"
match_file2 = base_image_name + "_manualpick.star"
match_file3 = base_image_name + "_CURATED.star"
# print("Match file names = %s, %s, %s" % (match_file1, match_file2, match_file3))
## find the matching star file if it exists
for fname in os.listdir(file_dir): ## iterate over the directory
if fname == match_file1 or fname == match_file2 or fname == match_file3:
# print("MATCH: %s -> %s" % (fname, image_list[n]))
counter += 1
star_coordinate_file = fname
if counter > 1: print(">>> WARNING: Multiple .STAR files found for this image (e.g. multiple files match: " + base_image_name + "*.star)")
## This program writes out ..._CURATED.star files, if we find one - use that over all other available .STAR files
if star_coordinate_file[-13:] == "_CURATED.star": break
## if a star file is found, load its coordinates
# print(" STAR FILE USED FOR COORDS = ", star_coordinate_file)
if (star_coordinate_file != ""):
self.read_coords_from_star(star_coordinate_file)
self.draw_image_coordinates()
return
def is_image(self, file):
""" For a given file name, check if it has an appropriate suffix.
Returns True if it is a file with proper suffix (e.g. .gif)
PARAMETERS
file = str(); name of the file (e.g. 'test.jpg')
"""
image_formats = [".gif", ".jpg", ".jpeg"]
for suffix in image_formats:
if suffix in file:
return True
return False
def images_in_dir(self, path) :
""" Create a list object populated with the names of image files present
PARAMETERS
path = str(), path to the directory with images to view
"""
image_list = []
for file in sorted(os.listdir(path)):
if self.is_image(file):
image_list.append(file)
return image_list
def choose_img(self):
""" When called, finds the matching file name from the current list and
loads its image and index
"""
global PARAMS
image_list = PARAMS['img_list']
n = PARAMS['index']
user_input = self.input_text.get().strip()
if user_input in image_list:
n = image_list.index(user_input)
## update global index
PARAMS['index'] = n
self.load_img()
else:
self.input_text.delete(0, tk.END)
self.input_text.insert(0,"File not found.")
self.canvas.focus_set()
def write_marked(self, file="marked_imgs.txt"):
""" Write marked files (mark files with hotkey 'd') into a file
"""
## save a settings as well
self.save_settings()
global PARAMS
marked_imgs = PARAMS['marked_imgs']
image_coordinates = PARAMS['img_coords']
## if present, determine what entries might already exist in the target file (e.g. if continuing from a previous session)
existing_entries = []
if os.path.exists(file):
with open(file, 'r') as f :
for line in f:
existing_entries.append(line.strip())
## write new marked images into file, if any present
with open(file, 'w') as f :
counter = 0
for marked_img in marked_imgs:
counter += 1
## write all marked_img names into the file from RAM
f.write("%s\n" % marked_img)
print(" >> %s entries written into 'marked_imgs.txt'" % counter)
## indicate which images were dropped from the previous file
for existing_entry in existing_entries:
if not existing_entry in marked_imgs:
print(" ... %s was removed from previous entries after rewriting file" % existing_entry)
## also save current image particle coordinates if they are present
if len(image_coordinates) > 0:
self.save_starfile()
def load_marked_filelist(self):
global PARAMS
marked_imgs = PARAMS['marked_imgs']
n = PARAMS['index']
## load selected file into variable fname
fname = askopenfilename(parent=self.master, initialdir="./", title='Select file', filetypes=( ("File list", "*.txt"),("All files", "*.*") ))
if fname:
try:
## extract file information from selection
logfile_path = str(fname)
## parse logfile into program
with open(logfile_path, 'r') as file_obj :
for line in file_obj:
## ignore header lines indicated by hash marks
if line[0] == '#':
continue
## parse each line with space delimiter into a list using .split() function (e.g. img_name note -> ['img_name', 'note'])
column = line.split()
## eliminate empty lines by removing length 0 lists
if len(column) == 0:
continue
## in cases where multiple entries exist per line, take only the first entry
img_name = column[0]
# mic_name = os.path.splitext(column[0])[0] # os module path.splitext removes .MRC from input name
## skip adding entry to marked list if already present (e.g. duplicates)
if img_name in marked_imgs:
continue
## write entry into dictionary
marked_imgs.append(img_name)
PARAMS['marked_imgs'] = marked_imgs
except:
showerror("Open Source File", "Failed to read file\n'%s'" % fname)
self.load_img() ## reload image in case it has now been marked
return
def draw_image_coordinates(self):
""" Read the global variable list of coordinates with gif and box files associated via a dictionary format, draw all gif coordinates present (regardless if they have associated box coordinates.
"""
global PARAMS
| |
sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV
import matplotlib.pyplot as plt
from .fasta import count_missed_cleavages, count_internal_cleavages
def get_ML_features(df: pd.DataFrame, protease: str='trypsin', **kwargs) -> pd.DataFrame:
"""
Uses the specified score in df to filter psms and to apply the fdr_level threshold.
Args:
df (pd.DataFrame): psms table of search results from alphapept.
protease (str, optional): string specifying the protease that was used for proteolytic digestion. Defaults to 'trypsin'.
Returns:
pd.DataFrame: df including additional scores for subsequent ML.
"""
df['decoy'] = df['sequence'].str[-1].str.islower()
df['abs_delta_m_ppm'] = np.abs(df['delta_m_ppm'])
df['naked_sequence'] = df['sequence'].apply(lambda x: ''.join([_ for _ in x if _.isupper()]))
df['n_AA']= df['naked_sequence'].str.len()
df['matched_ion_fraction'] = df['hits']/(2*df['n_AA'])
df['n_missed'] = df['naked_sequence'].apply(lambda x: count_missed_cleavages(x, protease))
df['n_internal'] = df['naked_sequence'].apply(lambda x: count_internal_cleavages(x, protease))
df['x_tandem'] = get_x_tandem_score(df)
return df
def train_RF(df: pd.DataFrame,
exclude_features: list = ['precursor_idx','ion_idx','fasta_index','feature_rank','raw_rank','rank','db_idx', 'feature_idx', 'precursor', 'query_idx', 'raw_idx','sequence','decoy','naked_sequence','target'],
train_fdr_level: float = 0.1,
ini_score: str = 'x_tandem',
min_train: int = 1000,
test_size: float = 0.8,
max_depth: list = [5,25,50],
max_leaf_nodes: list = [150,200,250],
n_jobs: int = -1,
scoring: str = 'accuracy',
plot:bool = False,
random_state: int = 42,
**kwargs) -> (GridSearchCV, list):
"""
Function to train a random forest classifier to separate targets from decoys via semi-supervised learning.
Args:
df (pd.DataFrame): psms table of search results from alphapept.
exclude_features (list, optional): list with features to exclude for ML. Defaults to ['precursor_idx','ion_idx','fasta_index','feature_rank','raw_rank','rank','db_idx', 'feature_idx', 'precursor', 'query_idx', 'raw_idx','sequence','decoy','naked_sequence','target'].
train_fdr_level (float, optional): Only targets below the train_fdr_level cutoff are considered for training the classifier. Defaults to 0.1.
ini_score (str, optional): Initial score to select psms set for semi-supervised learning. Defaults to 'x_tandem'.
min_train (int, optional): Minimum number of psms in the training set. Defaults to 1000.
test_size (float, optional): Fraction of psms used for testing. Defaults to 0.8.
max_depth (list, optional): List of clf__max_depth parameters to test in the grid search. Defaults to [5,25,50].
max_leaf_nodes (list, optional): List of clf__max_leaf_nodes parameters to test in the grid search. Defaults to [150,200,250].
n_jobs (int, optional): Number of jobs to use for parallelizing the gridsearch. Defaults to -1.
scoring (str, optional): Scoring method for the gridsearch. Defaults to'accuracy'.
plot (bool, optional): flag to enable plot. Defaults to 'False'.
random_state (int, optional): Random state for initializing the RandomForestClassifier. Defaults to 42.
Returns:
[GridSearchCV, list]: GridSearchCV: GridSearchCV object with trained RandomForestClassifier. list: list of features used for training the classifier.
"""
if getattr(sys, 'frozen', False):
logging.info('Using frozen pyinstaller version. Setting n_jobs to 1')
n_jobs = 1
features = [_ for _ in df.columns if _ not in exclude_features]
# Setup ML pipeline
scaler = StandardScaler()
rfc = RandomForestClassifier(random_state=random_state) # class_weight={False:1,True:5},
## Initiate scaling + classification pipeline
pipeline = Pipeline([('scaler', scaler), ('clf', rfc)])
parameters = {'clf__max_depth':(max_depth), 'clf__max_leaf_nodes': (max_leaf_nodes)}
## Setup grid search framework for parameter selection and internal cross validation
cv = GridSearchCV(pipeline, param_grid=parameters, cv=5, scoring=scoring,
verbose=0,return_train_score=True,n_jobs=n_jobs)
# Prepare target and decoy df
df['decoy'] = df['sequence'].str[-1].str.islower()
df['target'] = ~df['decoy']
df['score'] = df[ini_score]
dfT = df[~df.decoy]
dfD = df[df.decoy]
# Select high scoring targets (<= train_fdr_level)
df_prescore = filter_score(df)
df_prescore = filter_precursor(df_prescore)
scored = cut_fdr(df_prescore, fdr_level = train_fdr_level, plot=False)[1]
highT = scored[scored.decoy==False]
dfT_high = dfT[dfT['query_idx'].isin(highT.query_idx)]
dfT_high = dfT_high[dfT_high['db_idx'].isin(highT.db_idx)]
# Determine the number of psms for semi-supervised learning
n_train = int(dfT_high.shape[0])
if dfD.shape[0] < n_train:
n_train = int(dfD.shape[0])
logging.info("The total number of available decoys is lower than the initial set of high scoring targets.")
if n_train < min_train:
raise ValueError("There are fewer high scoring targets or decoys than required by 'min_train'.")
# Subset the targets and decoys datasets to result in a balanced dataset
df_training = dfT_high.sample(n=n_train, random_state=random_state).append(dfD.sample(n=n_train, random_state=random_state))
# Select training and test sets
X = df_training[features]
y = df_training['target'].astype(int)
X_train, X_test, y_train, y_test = train_test_split(X.values, y.values, test_size=test_size, random_state=random_state, stratify=y.values)
# Train the classifier on the training set via 5-fold cross-validation and subsequently test on the test set
logging.info('Training & cross-validation on {} targets and {} decoys'.format(np.sum(y_train),X_train.shape[0]-np.sum(y_train)))
cv.fit(X_train,y_train)
logging.info('The best parameters selected by 5-fold cross-validation were {}'.format(cv.best_params_))
logging.info('The train {} was {}'.format(scoring, cv.score(X_train, y_train)))
logging.info('Testing on {} targets and {} decoys'.format(np.sum(y_test),X_test.shape[0]-np.sum(y_test)))
logging.info('The test {} was {}'.format(scoring, cv.score(X_test, y_test)))
feature_importances=cv.best_estimator_.named_steps['clf'].feature_importances_
indices = np.argsort(feature_importances)[::-1][:40]
top_features = X.columns[indices][:40]
top_score = feature_importances[indices][:40]
feature_dict = dict(zip(top_features, top_score))
logging.info(f"Top features {feature_dict}")
# Inspect feature importances
if plot:
import seaborn as sns
g = sns.barplot(y=X.columns[indices][:40],
x = feature_importances[indices][:40],
orient='h', palette='RdBu')
g.set_xlabel("Relative importance",fontsize=12)
g.set_ylabel("Features",fontsize=12)
g.tick_params(labelsize=9)
g.set_title("Feature importance")
plt.show()
return cv, features
def score_ML(df: pd.DataFrame,
trained_classifier: GridSearchCV,
features: list = None,
fdr_level: float = 0.01,
plot: bool = True,
**kwargs) -> pd.DataFrame:
"""
Applies a trained ML classifier to df and uses the ML score to filter psms and to apply the fdr_level threshold.
Args:
df (pd.DataFrame): psms table of search results from alphapept.
trained_classifier (GridSearchCV): GridSearchCV object returned by train_RF.
features (list): list with features returned by train_RF. Defaults to 'None'.
fdr_level (float, optional): fdr level that should be used for filtering. The value should lie between 0 and 1. Defaults to 0.01.
plot (bool, optional): flag to enable plot. Defaults to 'True'.
Returns:
pd.DataFrame: filtered df with psms within fdr
"""
logging.info('Scoring using Machine Learning')
# Apply the classifier to the entire dataset
df_new = df.copy()
df_new['score'] = trained_classifier.predict_proba(df_new[features])[:,1]
df_new = filter_score(df_new)
df_new = filter_precursor(df_new)
cval, cutoff = cut_fdr(df_new, fdr_level, plot)
return cutoff
def filter_with_ML(df: pd.DataFrame,
trained_classifier: GridSearchCV,
features: list = None,
**kwargs) -> pd.DataFrame:
"""
Filters the psms table by using the x_tandem score, no fdr filter.
TODO: Remove redundancy with score functions, see issue: #275
Args:
df (pd.DataFrame): psms table of search results from alphapept.
trained_classifier (GridSearchCV): GridSearchCV object returned by train_RF.
features (list): list with features returned by train_RF. Defaults to 'None'.
Returns:
pd.DataFrame: psms table with an extra 'score' column from the trained_classifier by ML, filtered for no feature or precursor to be assigned multiple times.
"""
logging.info('Filter df with x_tandem score')
# Apply the classifier to the entire dataset
df_new = df.copy()
df_new['score'] = trained_classifier.predict_proba(df_new[features])[:,1]
df_new = filter_score(df_new)
df_new = filter_precursor(df_new)
return df_new
# Cell
import networkx as nx
def assign_proteins(data: pd.DataFrame, pept_dict: dict) -> (pd.DataFrame, dict):
"""
Assign psms to proteins.
This function appends the dataframe with a column 'n_possible_proteins' which indicates how many proteins a psm could be matched to.
It returns the appended dataframe and a dictionary `found_proteins` where each protein is mapped to the psms indices.
Args:
data (pd.DataFrame): psms table of scored and filtered search results from alphapept.
pept_dict (dict): dictionary that matches peptide sequences to proteins
Returns:
pd.DataFrame: psms table of search results from alphapept appended with the number of matched proteins.
dict: dictionary mapping psms indices to proteins.
"""
data = data.reset_index(drop=True)
data['n_possible_proteins'] = data['sequence'].apply(lambda x: len(pept_dict[x]))
unique_peptides = (data['n_possible_proteins'] == 1).sum()
shared_peptides = (data['n_possible_proteins'] > 1).sum()
logging.info(f'A total of {unique_peptides:,} unique and {shared_peptides:,} shared peptides.')
sub = data[data['n_possible_proteins']==1]
psms_to_protein = sub['sequence'].apply(lambda x: pept_dict[x])
found_proteins = {}
for idx, _ in enumerate(psms_to_protein):
idx_ = psms_to_protein.index[idx]
p_str = 'p' + str(_[0])
if p_str in found_proteins:
found_proteins[p_str] = found_proteins[p_str] + [str(idx_)]
else:
found_proteins[p_str] = [str(idx_)]
return data, found_proteins
def get_shared_proteins(data: pd.DataFrame, found_proteins: dict, pept_dict: dict) -> dict:
"""
Assign peptides to razor proteins.
Args:
data (pd.DataFrame): psms table of scored and filtered search results from alphapept, appended with `n_possible_proteins`.
found_proteins (dict): dictionary mapping psms indices to proteins
pept_dict (dict): dictionary mapping peptide indices to the originating proteins as a list
Returns:
dict: dictionary mapping peptides to razor proteins
"""
G = nx.Graph()
sub = data[data['n_possible_proteins']>1]
for i in range(len(sub)):
seq, score = sub.iloc[i][['sequence','score']]
idx = sub.index[i]
possible_proteins = pept_dict[seq]
for p in possible_proteins:
G.add_edge(str(idx), 'p'+str(p), score=score)
connected_groups = np.array([list(c) for c in sorted(nx.connected_components(G), key=len, reverse=True)], dtype=object)
n_groups = len(connected_groups)
logging.info('A total of {} ambigious proteins'.format(len(connected_groups)))
#Solving with razor:
found_proteins_razor = {}
for a in connected_groups[::-1]:
H = G.subgraph(a).copy()
shared_proteins = list(np.array(a)[np.array(list(i[0] == 'p' for i in a))])
while len(shared_proteins) > 0:
neighbors_list = []
for node in shared_proteins:
shared_peptides = list(H.neighbors(node))
if node in G:
if node in found_proteins.keys():
shared_peptides += found_proteins[node]
n_neigbhors = len(shared_peptides)
neighbors_list.append((n_neigbhors, node, shared_peptides))
#Check if we have a protein_group (e.g. they share the same everythin)
neighbors_list.sort()
# | |
import unittest
from unittest import mock
import os
import yaml
import dbt.flags
import dbt.parser
from dbt.exceptions import CompilationException
from dbt.parser import (
ModelParser, MacroParser, DataTestParser, SchemaParser, ParseResult,
SnapshotParser, AnalysisParser
)
from dbt.parser.schemas import (
TestablePatchParser, SourceParser, AnalysisPatchParser, MacroPatchParser
)
from dbt.parser.search import FileBlock
from dbt.parser.schema_test_builders import YamlBlock
from dbt.parser.manifest import process_docs, process_sources, process_refs
from dbt.node_types import NodeType
from dbt.contracts.files import SourceFile, FileHash, FilePath
from dbt.contracts.graph.manifest import Manifest
from dbt.contracts.graph.model_config import (
NodeConfig, TestConfig, TimestampSnapshotConfig, SnapshotStrategy,
)
from dbt.contracts.graph.parsed import (
ParsedModelNode, ParsedMacro, ParsedNodePatch, DependsOn, ColumnInfo,
ParsedDataTestNode, ParsedSnapshotNode, ParsedAnalysisNode,
UnpatchedSourceDefinition
)
from dbt.contracts.graph.unparsed import Docs
from .utils import config_from_parts_or_dicts, normalize, generate_name_macros, MockNode, MockSource, MockDocumentation
def get_abs_os_path(unix_path):
return normalize(os.path.abspath(unix_path))
class BaseParserTest(unittest.TestCase):
maxDiff = None
def _generate_macros(self):
name_sql = {}
for component in ('database', 'schema', 'alias'):
if component == 'alias':
source = 'node.name'
else:
source = f'target.{component}'
name = f'generate_{component}_name'
sql = f'{{% macro {name}(value, node) %}} {{% if value %}} {{{{ value }}}} {{% else %}} {{{{ {source} }}}} {{% endif %}} {{% endmacro %}}'
name_sql[name] = sql
for name, sql in name_sql.items():
pm = ParsedMacro(
name=name,
resource_type=NodeType.Macro,
unique_id=f'macro.root.{name}',
package_name='root',
original_file_path=normalize('macros/macro.sql'),
root_path=get_abs_os_path('./dbt_modules/root'),
path=normalize('macros/macro.sql'),
macro_sql=sql,
)
yield pm
def setUp(self):
dbt.flags.STRICT_MODE = True
dbt.flags.WARN_ERROR = True
self.maxDiff = None
profile_data = {
'target': 'test',
'quoting': {},
'outputs': {
'test': {
'type': 'redshift',
'host': 'localhost',
'schema': 'analytics',
'user': 'test',
'pass': '<PASSWORD>',
'dbname': 'test',
'port': 1,
}
}
}
root_project = {
'name': 'root',
'version': '0.1',
'profile': 'test',
'project-root': normalize('/usr/src/app'),
}
self.root_project_config = config_from_parts_or_dicts(
project=root_project,
profile=profile_data,
cli_vars='{"test_schema_name": "foo"}'
)
snowplow_project = {
'name': 'snowplow',
'version': '0.1',
'profile': 'test',
'project-root': get_abs_os_path('./dbt_modules/snowplow'),
}
self.snowplow_project_config = config_from_parts_or_dicts(
project=snowplow_project, profile=profile_data
)
self.all_projects = {
'root': self.root_project_config,
'snowplow': self.snowplow_project_config
}
self.root_project_config.dependencies = self.all_projects
self.snowplow_project_config.dependencies = self.all_projects
self.patcher = mock.patch('dbt.context.providers.get_adapter')
self.factory = self.patcher.start()
self.parser_patcher = mock.patch('dbt.parser.base.get_adapter')
self.factory_parser = self.parser_patcher.start()
self.macro_manifest = Manifest.from_macros(
macros={m.unique_id: m for m in generate_name_macros('root')}
)
def tearDown(self):
self.parser_patcher.stop()
self.patcher.stop()
def file_block_for(self, data: str, filename: str, searched: str):
root_dir = get_abs_os_path('./dbt_modules/snowplow')
filename = normalize(filename)
path = FilePath(
searched_path=searched,
relative_path=filename,
project_root=root_dir,
)
source_file = SourceFile(
path=path,
checksum=FileHash.from_contents(data),
)
source_file.contents = data
return FileBlock(file=source_file)
def assert_has_results_length(self, results, files=1, macros=0, nodes=0,
sources=0, docs=0, patches=0, disabled=0):
self.assertEqual(len(results.files), files)
self.assertEqual(len(results.macros), macros)
self.assertEqual(len(results.nodes), nodes)
self.assertEqual(len(results.sources), sources)
self.assertEqual(len(results.docs), docs)
self.assertEqual(len(results.patches), patches)
self.assertEqual(sum(len(v) for v in results.disabled.values()), disabled)
SINGLE_TABLE_SOURCE = '''
version: 2
sources:
- name: my_source
tables:
- name: my_table
'''
SINGLE_TABLE_SOURCE_TESTS = '''
version: 2
sources:
- name: my_source
tables:
- name: my_table
description: A description of my table
columns:
- name: color
tests:
- not_null:
severity: WARN
- accepted_values:
values: ['red', 'blue', 'green']
'''
SINGLE_TABLE_MODEL_TESTS = '''
version: 2
models:
- name: my_model
description: A description of my model
columns:
- name: color
description: The color value
tests:
- not_null:
severity: WARN
- accepted_values:
values: ['red', 'blue', 'green']
- foreign_package.test_case:
arg: 100
'''
SINGLE_TABLE_SOURCE_PATCH = '''
version: 2
sources:
- name: my_source
overrides: snowplow
tables:
- name: my_table
columns:
- name: id
tests:
- not_null
- unique
'''
class SchemaParserTest(BaseParserTest):
def setUp(self):
super().setUp()
self.parser = SchemaParser(
results=ParseResult.rpc(),
project=self.snowplow_project_config,
root_project=self.root_project_config,
macro_manifest=self.macro_manifest,
)
def file_block_for(self, data, filename):
return super().file_block_for(data, filename, 'models')
def yaml_block_for(self, test_yml: str, filename: str):
file_block = self.file_block_for(data=test_yml, filename=filename)
return YamlBlock.from_file_block(
src=file_block,
data=yaml.safe_load(test_yml),
)
class SchemaParserSourceTest(SchemaParserTest):
def test__read_basic_source(self):
block = self.yaml_block_for(SINGLE_TABLE_SOURCE, 'test_one.yml')
analysis_blocks = AnalysisPatchParser(self.parser, block, 'analyses').parse()
model_blocks = TestablePatchParser(self.parser, block, 'models').parse()
source_blocks = SourceParser(self.parser, block, 'sources').parse()
macro_blocks = MacroPatchParser(self.parser, block, 'macros').parse()
self.assertEqual(len(analysis_blocks), 0)
self.assertEqual(len(model_blocks), 0)
self.assertEqual(len(source_blocks), 0)
self.assertEqual(len(macro_blocks), 0)
self.assertEqual(len(list(self.parser.results.patches)), 0)
self.assertEqual(len(list(self.parser.results.nodes)), 0)
results = list(self.parser.results.sources.values())
self.assertEqual(len(results), 1)
self.assertEqual(results[0].source.name, 'my_source')
self.assertEqual(results[0].table.name, 'my_table')
self.assertEqual(results[0].table.description, '')
self.assertEqual(len(results[0].table.columns), 0)
def test__parse_basic_source(self):
block = self.file_block_for(SINGLE_TABLE_SOURCE, 'test_one.yml')
self.parser.parse_file(block)
self.assert_has_results_length(self.parser.results, sources=1)
src = list(self.parser.results.sources.values())[0]
assert isinstance(src, UnpatchedSourceDefinition)
assert src.package_name == 'snowplow'
assert src.source.name == 'my_source'
assert src.table.name == 'my_table'
assert src.resource_type == NodeType.Source
assert src.fqn == ['snowplow', 'my_source', 'my_table']
def test__read_basic_source_tests(self):
block = self.yaml_block_for(SINGLE_TABLE_SOURCE_TESTS, 'test_one.yml')
analysis_tests = AnalysisPatchParser(self.parser, block, 'analyses').parse()
model_tests = TestablePatchParser(self.parser, block, 'models').parse()
source_tests = SourceParser(self.parser, block, 'sources').parse()
macro_tests = MacroPatchParser(self.parser, block, 'macros').parse()
self.assertEqual(len(analysis_tests), 0)
self.assertEqual(len(model_tests), 0)
self.assertEqual(len(source_tests), 0)
self.assertEqual(len(macro_tests), 0)
self.assertEqual(len(list(self.parser.results.nodes)), 0)
self.assertEqual(len(list(self.parser.results.patches)), 0)
self.assertEqual(len(list(self.parser.results.source_patches)), 0)
results = list(self.parser.results.sources.values())
self.assertEqual(len(results), 1)
self.assertEqual(results[0].source.name, 'my_source')
self.assertEqual(results[0].table.name, 'my_table')
self.assertEqual(results[0].table.description, 'A description of my table')
self.assertEqual(len(results[0].table.columns), 1)
def test__parse_basic_source_tests(self):
block = self.file_block_for(SINGLE_TABLE_SOURCE_TESTS, 'test_one.yml')
self.parser.parse_file(block)
self.assertEqual(len(self.parser.results.nodes), 0)
self.assertEqual(len(self.parser.results.sources), 1)
self.assertEqual(len(self.parser.results.patches), 0)
src = list(self.parser.results.sources.values())[0]
self.assertEqual(src.source.name, 'my_source')
self.assertEqual(src.source.schema, None)
self.assertEqual(src.table.name, 'my_table')
self.assertEqual(src.table.description, 'A description of my table')
tests = [
self.parser.parse_source_test(src, test, col)
for test, col in src.get_tests()
]
tests.sort(key=lambda n: n.unique_id)
self.assertEqual(tests[0].config.severity, 'ERROR')
self.assertEqual(tests[0].tags, ['schema'])
self.assertEqual(tests[0].sources, [['my_source', 'my_table']])
self.assertEqual(tests[0].column_name, 'color')
self.assertEqual(tests[0].fqn, ['snowplow', 'schema_test', tests[0].name])
self.assertEqual(tests[1].config.severity, 'WARN')
self.assertEqual(tests[1].tags, ['schema'])
self.assertEqual(tests[1].sources, [['my_source', 'my_table']])
self.assertEqual(tests[1].column_name, 'color')
self.assertEqual(tests[1].fqn, ['snowplow', 'schema_test', tests[1].name])
path = get_abs_os_path('./dbt_modules/snowplow/models/test_one.yml')
self.assertIn(path, self.parser.results.files)
self.assertEqual(self.parser.results.files[path].nodes, [])
self.assertIn(path, self.parser.results.files)
self.assertEqual(self.parser.results.files[path].sources,
['source.snowplow.my_source.my_table'])
self.assertEqual(self.parser.results.files[path].source_patches, [])
def test__read_source_patch(self):
block = self.yaml_block_for(SINGLE_TABLE_SOURCE_PATCH, 'test_one.yml')
analysis_tests = AnalysisPatchParser(self.parser, block, 'analyses').parse()
model_tests = TestablePatchParser(self.parser, block, 'models').parse()
source_tests = SourceParser(self.parser, block, 'sources').parse()
macro_tests = MacroPatchParser(self.parser, block, 'macros').parse()
self.assertEqual(len(analysis_tests), 0)
self.assertEqual(len(model_tests), 0)
self.assertEqual(len(source_tests), 0)
self.assertEqual(len(macro_tests), 0)
self.assertEqual(len(list(self.parser.results.nodes)), 0)
self.assertEqual(len(list(self.parser.results.patches)), 0)
self.assertEqual(len(list(self.parser.results.sources)), 0)
results = list(self.parser.results.source_patches.values())
self.assertEqual(len(results), 1)
self.assertEqual(results[0].name, 'my_source')
self.assertEqual(results[0].overrides, 'snowplow')
self.assertIsNone(results[0].description)
self.assertEqual(len(results[0].tables), 1)
table = results[0].tables[0]
self.assertEqual(table.name, 'my_table')
self.assertIsNone(table.description)
self.assertEqual(len(table.columns), 1)
self.assertEqual(len(table.columns[0].tests), 2)
class SchemaParserModelsTest(SchemaParserTest):
def test__read_basic_model_tests(self):
block = self.yaml_block_for(SINGLE_TABLE_MODEL_TESTS, 'test_one.yml')
self.parser.parse_file(block)
self.assertEqual(len(list(self.parser.results.patches)), 1)
self.assertEqual(len(list(self.parser.results.sources)), 0)
self.assertEqual(len(list(self.parser.results.nodes)), 3)
def test__parse_basic_model_tests(self):
block = self.file_block_for(SINGLE_TABLE_MODEL_TESTS, 'test_one.yml')
self.parser.parse_file(block)
self.assert_has_results_length(self.parser.results, patches=1, nodes=3)
patch = list(self.parser.results.patches.values())[0]
self.assertEqual(len(patch.columns), 1)
self.assertEqual(patch.name, 'my_model')
self.assertEqual(patch.description, 'A description of my model')
expected_patch = ParsedNodePatch(
name='my_model',
description='A description of my model',
columns={'color': ColumnInfo(name='color', description='The color value')},
original_file_path=normalize('models/test_one.yml'),
meta={},
yaml_key='models',
package_name='snowplow',
docs=Docs(show=True),
)
self.assertEqual(patch, expected_patch)
tests = sorted(self.parser.results.nodes.values(), key=lambda n: n.unique_id)
self.assertEqual(tests[0].config.severity, 'ERROR')
self.assertEqual(tests[0].tags, ['schema'])
self.assertEqual(tests[0].refs, [['my_model']])
self.assertEqual(tests[0].column_name, 'color')
self.assertEqual(tests[0].package_name, 'snowplow')
self.assertTrue(tests[0].name.startswith('accepted_values_'))
self.assertEqual(tests[0].fqn, ['snowplow', 'schema_test', tests[0].name])
self.assertEqual(tests[0].unique_id.split('.'), ['test', 'snowplow', tests[0].name])
self.assertEqual(tests[0].test_metadata.name, 'accepted_values')
self.assertIsNone(tests[0].test_metadata.namespace)
self.assertEqual(
tests[0].test_metadata.kwargs,
{
'column_name': 'color',
'model': "{{ ref('my_model') }}",
'values': ['red', 'blue', 'green'],
}
)
# foreign packages are a bit weird, they include the macro package
# name in the test name
self.assertEqual(tests[1].config.severity, 'ERROR')
self.assertEqual(tests[1].tags, ['schema'])
self.assertEqual(tests[1].refs, [['my_model']])
self.assertEqual(tests[1].column_name, 'color')
self.assertEqual(tests[1].column_name, 'color')
self.assertEqual(tests[1].fqn, ['snowplow', 'schema_test', tests[1].name])
self.assertTrue(tests[1].name.startswith('foreign_package_test_case_'))
self.assertEqual(tests[1].package_name, 'snowplow')
self.assertEqual(tests[1].unique_id.split('.'), ['test', 'snowplow', tests[1].name])
self.assertEqual(tests[1].test_metadata.name, 'test_case')
self.assertEqual(tests[1].test_metadata.namespace, 'foreign_package')
self.assertEqual(
tests[1].test_metadata.kwargs,
{
'column_name': 'color',
'model': "{{ ref('my_model') }}",
'arg': 100,
},
)
self.assertEqual(tests[2].config.severity, 'WARN')
self.assertEqual(tests[2].tags, ['schema'])
self.assertEqual(tests[2].refs, [['my_model']])
self.assertEqual(tests[2].column_name, 'color')
self.assertEqual(tests[2].package_name, 'snowplow')
self.assertTrue(tests[2].name.startswith('not_null_'))
self.assertEqual(tests[2].fqn, ['snowplow', 'schema_test', tests[2].name])
self.assertEqual(tests[2].unique_id.split('.'), ['test', 'snowplow', tests[2].name])
self.assertEqual(tests[2].test_metadata.name, 'not_null')
self.assertIsNone(tests[2].test_metadata.namespace)
self.assertEqual(
tests[2].test_metadata.kwargs,
{
'column_name': 'color',
'model': "{{ ref('my_model') }}",
},
)
path = get_abs_os_path('./dbt_modules/snowplow/models/test_one.yml')
self.assertIn(path, self.parser.results.files)
self.assertEqual(sorted(self.parser.results.files[path].nodes),
[t.unique_id for t in tests])
self.assertIn(path, self.parser.results.files)
self.assertEqual(self.parser.results.files[path].patches, ['my_model'])
class ModelParserTest(BaseParserTest):
def setUp(self):
super().setUp()
self.parser = ModelParser(
results=ParseResult.rpc(),
project=self.snowplow_project_config,
root_project=self.root_project_config,
macro_manifest=self.macro_manifest,
)
def file_block_for(self, data, filename):
return super().file_block_for(data, filename, 'models')
def test_basic(self):
raw_sql = '{{ config(materialized="table") }}select 1 as id'
block = self.file_block_for(raw_sql, 'nested/model_1.sql')
self.parser.parse_file(block)
self.assert_has_results_length(self.parser.results, nodes=1)
node = list(self.parser.results.nodes.values())[0]
expected = ParsedModelNode(
alias='model_1',
name='model_1',
database='test',
schema='analytics',
resource_type=NodeType.Model,
unique_id='model.snowplow.model_1',
fqn=['snowplow', 'nested', 'model_1'],
package_name='snowplow',
original_file_path=normalize('models/nested/model_1.sql'),
root_path=get_abs_os_path('./dbt_modules/snowplow'),
config=NodeConfig(materialized='table'),
path=normalize('nested/model_1.sql'),
raw_sql=raw_sql,
checksum=block.file.checksum,
)
self.assertEqual(node, expected)
path = get_abs_os_path('./dbt_modules/snowplow/models/nested/model_1.sql')
self.assertIn(path, self.parser.results.files)
self.assertEqual(self.parser.results.files[path].nodes, ['model.snowplow.model_1'])
def test_parse_error(self):
block = self.file_block_for('{{ SYNTAX ERROR }}', 'nested/model_1.sql')
with self.assertRaises(CompilationException):
self.parser.parse_file(block)
self.assert_has_results_length(self.parser.results, files=0)
class SnapshotParserTest(BaseParserTest):
def setUp(self):
super().setUp()
self.parser = SnapshotParser(
results=ParseResult.rpc(),
project=self.snowplow_project_config,
root_project=self.root_project_config,
macro_manifest=self.macro_manifest,
)
def file_block_for(self, data, filename):
return super().file_block_for(data, filename, 'snapshots')
def test_parse_error(self):
block = self.file_block_for('{% snapshot foo %}select 1 as id{%snapshot bar %}{% endsnapshot %}', 'nested/snap_1.sql')
with self.assertRaises(CompilationException):
self.parser.parse_file(block)
self.assert_has_results_length(self.parser.results, files=0)
def test_single_block(self):
raw_sql = '''{{
config(unique_key="id", target_schema="analytics",
target_database="dbt", strategy="timestamp",
updated_at="last_update")
}}
select 1 as id, now() as last_update'''
full_file = '''
{{% snapshot foo %}}{}{{% endsnapshot %}}
'''.format(raw_sql)
block = self.file_block_for(full_file, 'nested/snap_1.sql')
self.parser.parse_file(block)
self.assert_has_results_length(self.parser.results, nodes=1)
node = list(self.parser.results.nodes.values())[0]
expected = ParsedSnapshotNode(
alias='foo',
name='foo',
# the `database` entry is overrridden by the target_database config
database='dbt',
schema='analytics',
resource_type=NodeType.Snapshot,
unique_id='snapshot.snowplow.foo',
fqn=['snowplow', 'nested', 'snap_1', 'foo'],
package_name='snowplow',
original_file_path=normalize('snapshots/nested/snap_1.sql'),
root_path=get_abs_os_path('./dbt_modules/snowplow'),
config=TimestampSnapshotConfig(
strategy=SnapshotStrategy.Timestamp,
updated_at='last_update',
target_database='dbt',
target_schema='analytics',
unique_key='id',
materialized='snapshot',
),
path=normalize('nested/snap_1.sql'),
raw_sql=raw_sql,
checksum=block.file.checksum,
)
self.assertEqual(node, expected)
path = get_abs_os_path('./dbt_modules/snowplow/snapshots/nested/snap_1.sql')
self.assertIn(path, self.parser.results.files)
self.assertEqual(self.parser.results.files[path].nodes, ['snapshot.snowplow.foo'])
def test_multi_block(self):
raw_1 = '''
{{
config(unique_key="id", target_schema="analytics",
target_database="dbt", strategy="timestamp",
updated_at="last_update")
}}
select 1 as id, now() as last_update
'''
raw_2 = '''
{{
config(unique_key="id", target_schema="analytics",
target_database="dbt", strategy="timestamp",
updated_at="last_update")
}}
select 2 as id, now() as last_update
'''
full_file = '''
{{% snapshot foo %}}{}{{% endsnapshot %}}
{{% snapshot bar %}}{}{{% endsnapshot %}}
'''.format(raw_1, raw_2)
block = self.file_block_for(full_file, 'nested/snap_1.sql')
self.parser.parse_file(block)
self.assert_has_results_length(self.parser.results, nodes=2)
nodes = sorted(self.parser.results.nodes.values(), key=lambda n: n.name)
expect_foo = ParsedSnapshotNode(
alias='foo',
name='foo',
database='dbt',
schema='analytics',
resource_type=NodeType.Snapshot,
unique_id='snapshot.snowplow.foo',
fqn=['snowplow', 'nested', 'snap_1', 'foo'],
package_name='snowplow',
original_file_path=normalize('snapshots/nested/snap_1.sql'),
root_path=get_abs_os_path('./dbt_modules/snowplow'),
config=TimestampSnapshotConfig(
strategy=SnapshotStrategy.Timestamp,
updated_at='last_update',
target_database='dbt',
target_schema='analytics',
unique_key='id',
materialized='snapshot',
),
path=normalize('nested/snap_1.sql'),
raw_sql=raw_1,
checksum=block.file.checksum,
)
expect_bar = ParsedSnapshotNode(
alias='bar',
name='bar',
database='dbt',
schema='analytics',
resource_type=NodeType.Snapshot,
unique_id='snapshot.snowplow.bar',
| |
<reponame>mdivband/arcade_swarm<filename>simulation.py
import arcade
from threading import *
import numpy as np
import random
import scipy, scipy.ndimage
import math
import time
from matplotlib import pyplot as plt
import collections
import os
import timeit
import requests
from fps_test_modules import FPSCounter
import time as timeclock
import datetime
import argparse
from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.image as mpimg
from matplotlib.widgets import Slider, Button
from matplotlib.patches import Rectangle
import pathlib
import cv2
from PIL import Image as im
import warnings
from c_widgets import Annotate
warnings.filterwarnings("ignore")
np.seterr(divide='ignore', invalid='ignore')
EXP_D_T = datetime.datetime.now().strftime("%d-%m-%Y_%H_%M_%S")
'''
Class Object (abstract class)
- A simple class which implements the simplest behaviour of each object in the simulations
- Stores position, velocity and implements a basic movement
'''
class Object(arcade.Sprite):
def __init__(self, x, y, change_x, change_y, scl, img, sim):
super().__init__(img, scl)
self.center_x = x
self.center_y = y
self.change_x = change_x ## speed of movement in x direction per frame
self.change_y = change_y ## speed of movement in y directieno per frame
self.simulation = sim
# Basic movement and keeps object in arena
def update(self):
if self.center_x + self.change_x >= self.simulation.ARENA_WIDTH or self.center_x + self.change_x <= 0:
self.change_x = 0
if self.center_y + self.change_y >= self.simulation.ARENA_HEIGHT or self.center_y + self.change_y <= 0:
self.change_y = 0
self.center_x += self.change_x
self.center_y += self.change_y
class Obstacle(Object):
def __init__(self, x, y, change_x, change_y, scl, sim, obstacle_type):
self.type = obstacle_type
if obstacle_type == 'disk':
super().__init__(x, y, change_x, change_y, scl, "images/obstacle.png", sim)
elif obstacle_type == 'horizontal':
super().__init__(x, y, change_x, change_y, scl, "images/obstacle2.png", sim)
elif obstacle_type == 'vertical':
super().__init__(x, y, change_x, change_y, scl, "images/obstacle5_thin.png", sim)
elif obstacle_type == 'vertical_thin':
super().__init__(x, y, change_x, change_y, scl, "images/obstacle1_thin.png", sim)
def update(self):
super().update()
'''
Class Disaster
- A simple class which implements the behaviour of a disaster
- Extends the behaviour of the class Object
'''
class Disaster(Object):
def __init__(self, x, y, change_x, change_y, scl, sim, moving = False, img = "images/disaster.png"):
super().__init__(x, y, change_x, change_y, scl, img, sim)
self.moving = moving
def update(self):
'''
if self.moving == True:
if self.simulation.timer >= self.simulation.INPUT_TIME/2 and self.simulation.timer < self.simulation.INPUT_TIME/2 + 50:
self.change_y = -5
else:
self.change_y = 0
'''
# Simple movement
if self.moving == True:
if self.simulation.timer >= self.simulation.INPUT_TIME/2 and self.simulation.timer < self.simulation.INPUT_TIME/2 + 100:
if self.change_y == 0:
if self.center_y <= self.simulation.ARENA_HEIGHT/2:
self.change_y = 3
else:
self.change_y = -3
self.change_x = 0
elif self.simulation.timer >= self.simulation.INPUT_TIME/2 + 100 and self.simulation.timer < self.simulation.INPUT_TIME/2 + 200:
if self.change_x == 0:
if self.center_x <= self.simulation.ARENA_WIDTH/2:
self.change_x = 3
else:
self.change_x = -3
self.change_y = 0
else:
self.change_x = 0
self.change_y = 0
super().update()
'''
Class Agent (abstract class)
- Implements the functionality of all agents
'''
class Agent(Object):
def __init__(self, x, y, change_x, change_y, scl, img, sim, reliability = 1, communication_noise = 0):
super().__init__(x, y, change_x, change_y, scl, img, sim)
self.confidence_map= np.array([[0.0 for i in range(self.simulation.GRID_X)] for j in range(self.simulation.GRID_Y)])
self.internal_map= np.array([[0.0 for i in range(self.simulation.GRID_X)] for j in range(self.simulation.GRID_Y)])
self.reliability = reliability
self.communication_noise = communication_noise
self.grid_pos_x = math.trunc((self.center_x * (self.simulation.GRID_X - 1) / self.simulation.ARENA_WIDTH))
self.grid_pos_y = math.trunc(((1 - self.center_y / self.simulation.ARENA_HEIGHT ) * (self.simulation.GRID_Y - 1)))
self.have_communicated = False
self.message_count_succ = 0
self.message_count_fail = 0
self.message = ""
def update(self):
#sensing_noise = np.random.uniform(0, self.simulation.sensing_noise_strength, (self.simulation.GRID_Y, self.simulation.GRID_X))
#s = random.uniform(0, self.simulation.sensing_noise_strength)
#if random.random() < self.simulation.sensing_noise_prob:
# self.internal_map *= (1-s)
super().update()
def communicate(self, agent, how):
'''
if self.simulation.through_walls == False:
#print('ping')
from bresenham import bresenham
visible = True
line_segment = list(bresenham(self.grid_pos_y, self.grid_pos_x, agent.grid_pos_y, agent.grid_pos_x))
for k,j in line_segment:
obstacle = self.is_obstacle_at_position(k, j)
if obstacle == True:
visible = False
break
if visible == True:
self.exchange_data(agent, how)
else:
'''
# if random.random() > self.simulation.communication_noise_prob:
# #self.communication_noise = random.uniform(0, self.simulation.communication_noise_strength)
# if self.have_communicated == False:
# self.exchange_data(agent, how)
# self.message_count_succ += 1
# self.have_communicated = True
# else:
# self.message_count_fail += 1
self.exchange_data(agent, how)
self.message_count_succ += 1
self.have_communicated = True
def exchange_data_old(self, agent, how):
'''if (random.randrange(0, 100) < 50):
coeff = +1
else:
coeff = -1
'''
coeff = 0
if how == 'max':
for j in range(self.simulation.GRID_X):
for i in range(self.simulation.GRID_Y):
if (agent.confidence_map[i][j] > self.confidence_map[i][j]):
self.internal_map[i][j] = agent.reliability * agent.internal_map[i][j] + coeff * self.communication_noise
self.confidence_map[i][j] = agent.confidence_map[i][j] + coeff * self.communication_noise
else:
agent.internal_map[i][j] = self.reliability * self.internal_map[i][j] + coeff * self.communication_noise
agent.confidence_map[i][j] = self.confidence_map[i][j] + coeff * self.communication_noise
elif how == 'average':
#self.message_count_succ += 1
agent.internal_map = self.internal_map = (self.reliability * self.internal_map + agent.reliability * agent.internal_map)/2 + coeff * self.communication_noise
agent.confidence_map = self.confidence_map = (self.confidence_map + agent.confidence_map)/2 + coeff * self.communication_noise
def exchange_data(self, agent, how):
'''if (random.randrange(0, 100) < 50):
coeff = +1
else:
coeff = -1
'''
coeff = 0
#################################
#one of the drones has very HIGH confidence
b_a_mask = np.bitwise_and(agent.confidence_map > 0.8, agent.confidence_map > self.confidence_map)
np.putmask(self.internal_map, b_a_mask, agent.reliability * agent.internal_map + coeff * self.communication_noise)
np.putmask(self.confidence_map, b_a_mask, agent.confidence_map + coeff * self.communication_noise)
b_s_mask = np.bitwise_and(self.confidence_map > 0.8, agent.confidence_map < self.confidence_map)
np.putmask(agent.internal_map, b_s_mask, self.reliability * self.internal_map + coeff * self.communication_noise)
np.putmask(agent.confidence_map, b_s_mask, self.confidence_map + coeff * self.communication_noise)
#one of the drones has very LOW confidence
l_a_mask = np.bitwise_and(agent.confidence_map < 0, agent.confidence_map < self.confidence_map)
np.putmask(agent.internal_map, l_a_mask, agent.reliability * agent.internal_map + coeff * self.communication_noise)
np.putmask(agent.confidence_map, l_a_mask, agent.confidence_map + coeff * self.communication_noise)
l_s_mask = np.bitwise_and(self.confidence_map < 0, agent.confidence_map > self.confidence_map)
np.putmask(self.internal_map, l_s_mask, self.reliability * self.internal_map + coeff * self.communication_noise)
np.putmask(self.confidence_map, l_s_mask, self.confidence_map + coeff * self.communication_noise)
#AVG confidence
ll_a_mask = np.bitwise_or(self.confidence_map < 0.8, self.confidence_map > 0.8)
np.putmask(agent.internal_map, ll_a_mask, (self.reliability * self.internal_map + agent.reliability * agent.internal_map)/2 + coeff * self.communication_noise)
np.putmask(agent.confidence_map, ll_a_mask, (self.confidence_map + agent.confidence_map)/2 + coeff * self.communication_noise)
ll_s_mask = np.bitwise_or(agent.internal_map < 0.8, agent.internal_map > 0)
np.putmask(self.internal_map, ll_s_mask, (self.reliability * self.internal_map + agent.reliability * agent.internal_map)/2 + coeff * self.communication_noise)
np.putmask(self.confidence_map, ll_s_mask, (self.confidence_map + agent.confidence_map)/2 + coeff * self.communication_noise)
# for j in range(self.simulation.GRID_X):
# for i in range(self.simulation.GRID_Y):
# agent_confidence = agent.confidence_map[i][j]
# agent_belief = agent.internal_map[i][j]
# self_confidence = self.confidence_map[i][j]
# self_belief = self.internal_map[i][j]
# #print ('confidence is ' + str(agent_confidence))
# if (agent_confidence > 0.8) or (self_confidence > 0.8):
# if (agent_confidence > self_confidence):
# self_belief = agent.reliability * agent_belief + coeff * self.communication_noise
# self_confidence = agent_confidence + coeff * self.communication_noise
# else:
# agent_belief = self.reliability * self_belief + coeff * self.communication_noise
# agent_confidence = self_confidence + coeff * self.communication_noise
# elif (agent_confidence < 0) or (self_confidence < 0):
# if (agent_confidence < self_confidence):
# self_belief = agent.reliability * agent_belief + coeff * self.communication_noise
# self_confidence = agent_confidence + coeff * self.communication_noise
# else:
# agent_belief = self.reliability * self_belief + coeff * self.communication_noise
# agent_confidence = self_confidence + coeff * self.communication_noise
# else:
# agent_belief = self_belief = (self.reliability * self_belief + agent.reliability * agent_belief)/2 + coeff * self.communication_noise
# agent_confidence = self_confidence = (self_confidence + agent_confidence)/2 + coeff * self.communication_noise
# agent.confidence_map[i][j] = agent_confidence
# agent.internal_map[i][j] = agent_belief
# self.confidence_map[i][j]= self_confidence
# self.internal_map[i][j] = self_belief
'''
#agent.internal_map = self.internal_map = (self.reliability * self.internal_map + agent.reliability * agent.internal_map)/2 + coeff * self.communication_noise
#agent.confidence_map = self.confidence_map = (self.confidence_map + agent.confidence_map)/2 + coeff * self.communication_noise
agent.internal_map = (self.reliability * self.internal_map + agent.reliability * agent.internal_map)/2 + coeff * self.communication_noise
agent.internal_map [agent.internal_map > 1] = 1
agent.internal_map [agent.internal_map < -10] = -10
self.internal_map = (self.reliability * self.internal_map + agent.reliability * agent.internal_map)/2 + coeff * self.communication_noise
self.internal_map [self.internal_map > 1] = 1
self.internal_map [self.internal_map < -10] = -10
agent.confidence_map = (self.reliability * self.confidence_map + agent.reliability * agent.confidence_map)/2 + coeff * self.communication_noise
agent.confidence_map [agent.confidence_map > 1] = 1
agent.confidence_map [agent.confidence_map < -10] = -10
self.confidence_map = (self.reliability * self.confidence_map + agent.reliability * agent.confidence_map)/2 + coeff * self.communication_noise
self.confidence_map [self.confidence_map > 1] = 1
self.confidence_map [self.confidence_map < -10] = -10
'''
#################################
def is_obstacle_at_position(self, k, j):
obstacle = False
for obstacle in self.simulation.obstacle_list:
obstacle_grid_center_pos_x = math.trunc((obstacle.center_x * (self.simulation.GRID_X -1)/self.simulation.ARENA_WIDTH) )
| |
bias group.
"""
_, _, channels, groups = self.get_master_assignment(band)
chs_in_group = []
for i in range(len(channels)):
if groups[i] == group:
chs_in_group.append(channels[i])
return np.array(chs_in_group)
@set_action()
def get_group_number(self, band, ch):
"""
Gets the bias group number of a band, channel pair. The
master_channel_assignment must be filled.
Args
----
band : int
The band number.
ch : int
The channel number.
Returns
-------
bias_group : int
The bias group number.
"""
_, _, channels,groups = self.get_master_assignment(band)
for i in range(len(channels)):
if channels[i] == ch:
return groups[i]
return None
@set_action()
def write_group_assignment(self, bias_group_dict):
'''
Combs master channel assignment and assigns group number to all channels
in ch_list. Does not affect other channels in the master file.
Args
----
bias_group_dict : dict
The output of identify_bias_groups.
'''
bias_groups = list(bias_group_dict.keys())
# Find all unique bands
bands = np.array([], dtype=int)
for bg in bias_groups:
for b in bias_group_dict[bg]['band']:
if b not in bands:
bands = np.append(bands, b)
for b in bands:
# Load previous channel assignment
freqs_master, subbands_master, channels_master, \
groups_master = self.get_master_assignment(b)
for bg in bias_groups:
for i in np.arange(len(bias_group_dict[bg]['channel'])):
ch = bias_group_dict[bg]['channel'][i]
bb = bias_group_dict[bg]['band'][i]
# First check they are in the same band
if bb == b:
idx = np.ravel(np.where(channels_master == ch))
if len(idx) == 1:
groups_master[idx] = bg
# Save the new master channel assignment
self.write_master_assignment(b, freqs_master,
subbands_master,
channels_master,
bias_groups=groups_master)
@set_action()
def relock(self, band, res_num=None, tone_power=None, r2_max=.08,
q_max=100000, q_min=0, check_vals=False, min_gap=None,
write_log=False):
"""
Turns on the tones. Also cuts bad resonators.
Args
----
band : int
The band to relock.
res_num : int array or None, optional, default None
The resonators to lock. If None, tries all the resonators.
tone_power : int or None, optional, default None
The tone amplitudes to set.
r2_max : float, optional, default 0.08
The highest allowable R^2 value.
q_max : float, optional, default 1e5
The maximum resonator Q factor.
q_min : float, optional, default 0
The minimum resonator Q factor.
check_vals : bool, optional, default False
Whether to check r2 and Q values.
min_gap : float or None, optional, default None
The minimum distance between resonators.
"""
n_channels = self.get_number_channels(band)
self.log('Relocking...')
if res_num is None:
res_num = np.arange(n_channels)
else:
res_num = np.array(res_num)
if tone_power is None:
tone_power = self.freq_resp[band]['tone_power']
amplitude_scale = np.zeros(n_channels)
center_freq = np.zeros(n_channels)
feedback_enable = np.zeros(n_channels)
eta_phase = np.zeros(n_channels)
eta_mag = np.zeros(n_channels)
# Extract frequencies from dictionary
f = [self.freq_resp[band]['resonances'][k]['freq']
for k in self.freq_resp[band]['resonances'].keys()]
# Populate arrays
counter = 0
for k in self.freq_resp[band]['resonances'].keys():
ch = self.freq_resp[band]['resonances'][k]['channel']
idx = np.where(f == self.freq_resp[band]['resonances'][k]['freq'])[0][0]
f_gap = None
if len(f) > 1:
f_gap = np.min(np.abs(np.append(f[:idx], f[idx+1:])-f[idx]))
if write_log:
self.log(f'Res {k:03} - Channel {ch}')
for ll, hh in self._bad_mask:
# Check again bad mask list
if f[idx] > ll and f[idx] < hh:
self.log(f'{f[idx]:4.3f} in bad list.')
ch = -1
if ch < 0:
if write_log:
self.log(f'No channel assigned: res {k:03}')
elif min_gap is not None and f_gap is not None and f_gap < min_gap:
# Resonators too close
if write_log:
self.log(f'Closest resonator is {f_gap:3.3f} MHz away')
elif self.freq_resp[band]['resonances'][k]['r2'] > r2_max and check_vals:
# chi squared cut
if write_log:
self.log(f'R2 too high: res {k:03}')
elif k not in res_num:
if write_log:
self.log('Not in resonator list')
else:
# Channels passed all checks so actually turn on
center_freq[ch] = self.freq_resp[band]['resonances'][k]['offset']
amplitude_scale[ch] = tone_power
feedback_enable[ch] = 1
eta_phase[ch] = self.freq_resp[band]['resonances'][k]['eta_phase']
eta_mag[ch] = self.freq_resp[band]['resonances'][k]['eta_scaled']
counter += 1
# Set the actual variables
self.set_center_frequency_array(band, center_freq, write_log=write_log,
log_level=self.LOG_INFO)
self.set_amplitude_scale_array(band, amplitude_scale.astype(int),
write_log=write_log, log_level=self.LOG_INFO)
self.set_feedback_enable_array(band, feedback_enable.astype(int),
write_log=write_log, log_level=self.LOG_INFO)
self.set_eta_phase_array(band, eta_phase, write_log=write_log,
log_level=self.LOG_INFO)
self.set_eta_mag_array(band, eta_mag, write_log=write_log,
log_level=self.LOG_INFO)
self.log(
f'Setting on {counter} channels on band {band}',
self.LOG_USER)
@set_action()
def fast_relock(self, band):
"""
"""
self.log(f'Fast relocking with: {self.tune_file}')
self.set_tune_file_path(self.tune_file)
self.set_load_tune_file(band, 1)
self.log('Done fast relocking')
def _get_eta_scan_result_from_key(self, band, key):
"""
Convenience function to get values from the freq_resp dictionary.
Args
----
band : int
The 500 MHz band to get values from.
key : str
The dictionary value to read out.
Returns
-------
array
The array of values associated with key.
"""
if 'resonances' not in self.freq_resp[band].keys():
self.log('No tuning. Run setup_notches() or load_tune()')
return None
return np.array([self.freq_resp[band]['resonances'][k][key]
for k in self.freq_resp[band]['resonances'].keys()])
def get_eta_scan_result_freq(self, band):
"""
Convenience function that gets the frequency results from eta scans.
Args
----
band : int
The band.
Returns
-------
freq : float array
The frequency in MHz of the resonators.
"""
return self._get_eta_scan_result_from_key(band, 'freq')
def get_eta_scan_result_eta(self, band):
"""
Convenience function that gets thee eta values from eta scans.
Args
----
band : int
The band.
Returns
-------
eta : complex array
The eta of the resonators.
"""
return self._get_eta_scan_result_from_key(band, 'eta')
def get_eta_scan_result_eta_mag(self, band):
"""
Convenience function that gets thee eta mags from
eta scans.
Args
----
band : int
The band.
Returns
-------
eta_mag : float array
The eta of the resonators.
"""
return self._get_eta_scan_result_from_key(band, 'eta_mag')
def get_eta_scan_result_eta_scaled(self, band):
"""
Convenience function that gets the eta scaled from
eta scans. eta_scaled is eta_mag/digitizer_freq_mhz/n_subbands
Args
----
band : int
The band.
Returns
-------
eta_scaled : float array
The eta_scaled of the resonators.
"""
return self._get_eta_scan_result_from_key(band, 'eta_scaled')
def get_eta_scan_result_eta_phase(self, band):
"""
Convenience function that gets the eta phase values from
eta scans.
Args
----
band : int
The band.
Returns
-------
eta_phase : float array
The eta_phase of the resonators.
"""
return self._get_eta_scan_result_from_key(band, 'eta_phase')
def get_eta_scan_result_channel(self, band):
"""
Convenience function that gets the channel assignments from
eta scans.
Args
----
band : int
The band.
Returns
-------
channels : int array
The channels of the resonators.
"""
return self._get_eta_scan_result_from_key(band, 'channel')
def get_eta_scan_result_subband(self, band):
"""
Convenience function that gets the subband from eta scans.
Args
----
band : int
The band.
Returns
-------
subband : float array
The subband of the resonators.
"""
return self._get_eta_scan_result_from_key(band, 'subband')
def get_eta_scan_result_offset(self, band):
"""
Convenience function that gets the offset from center frequency
from eta scans.
Args
----
band : int
The band.
Returns
-------
offset : float array
The offset from the subband centers of the resonators.
"""
return self._get_eta_scan_result_from_key(band, 'offset')
def eta_estimator(self, band, subband, freq, resp, delta_freq=.01,
lock_max_derivative=False):
"""
Estimates eta parameters using the slow eta_scan.
Args
----
band : int
The band.
subband : int
The subband.
freq : float array
Frequencies of scan.
resp : float array
Response from scan.
"""
f_sweep = freq
a_resp = np.abs(resp)
if lock_max_derivative:
self.log('Locking on max derivative instead of res min')
deriv = np.abs(np.diff(a_resp))
idx = np.ravel(np.where(deriv == np.max(deriv)))[0]
else:
idx = np.ravel(np.where(a_resp == np.min(a_resp)))[0]
f0 = f_sweep[idx]
try:
left = np.where(f_sweep < f0 - delta_freq)[0][-1]
except IndexError:
left = 0
try:
right = np.where(f_sweep > f0 + delta_freq)[0][0]
except BaseException:
right = len(f_sweep)-1
eta = (f_sweep[right]-f_sweep[left])/(resp[right]-resp[left])
sb, sbc = self.get_subband_centers(band, as_offset=False)
return f_sweep + sbc[subband], resp, eta
@set_action()
def eta_scan(self, band, subband, freq, tone_power, write_log=False,
sync_group=True):
"""
Same as slow eta scans
"""
if len(self.which_on(band)):
self.band_off(band, write_log=write_log)
n_subband = self.get_number_sub_bands(band)
n_channel = self.get_number_channels(band)
channel_order = self.get_channel_order(band)
first_channel = channel_order[::n_channel//n_subband]
self.set_eta_scan_channel(band, first_channel[subband],
write_log=write_log)
self.set_eta_scan_amplitude(band, tone_power, write_log=write_log)
self.set_eta_scan_freq(band, freq, write_log=write_log)
self.set_eta_scan_dwell(band, 0, write_log=write_log)
self.set_run_eta_scan(band, 1, wait_done=False, write_log=write_log)
pvs = [self._cryo_root(band) + self._eta_scan_results_real,
self._cryo_root(band) + self._eta_scan_results_imag]
if sync_group:
sg = SyncGroup(pvs, skip_first=False)
sg.wait()
vals = sg.get_values()
rr = vals[pvs[0]]
ii = vals[pvs[1]]
else:
rr = self.get_eta_scan_results_real(2, len(freq))
ii = self.get_eta_scan_results_imag(2, len(freq))
self.set_amplitude_scale_channel(band, first_channel[subband], 0)
return rr, ii
@set_action()
def flux_ramp_check(self, band, reset_rate_khz=None,
fraction_full_scale=None, flux_ramp=True, save_plot=True,
show_plot=False, setup_flux_ramp=True):
"""
Tries to measure the V-phi curve in feedback disable mode.
You can also run this with flux ramp off to see the intrinsic
noise on the readout channel.
Args
----
band : int
The band to check.
reset_rate_khz : float or None, optional, default None
The flux ramp rate in kHz.
fraction_full_scale : float or None, optional, default None
The amplitude of the flux ramp from zero to one.
flux_ramp : bool, optional, default True
Whether to flux ramp.
save_plot : bool, optional, default True
Whether to save the plot.
show_plot : bool, optional, default False
Whether to show the plot.
setup_flux_ramp : bool, optional, default True
| |
optimal_ra, optimal_dec = -0.2559168059473027, 0.81079526383
time = time_in_each_ifo("H1", optimal_ra, optimal_dec, 0)
light_time = 6371*10**3 / (3.0*10**8)
assert -np.round(light_time, 4) == np.round(time, 4)
ra = np.random.uniform(-np.pi, np.pi, 100)
dec = np.random.uniform(0, 2*np.pi, 100)
time = np.random.uniform(10000, 20000, 100)
H1_time = time_in_each_ifo("H1", ra, dec, time)
pycbc_time = time + Detector("H1").time_delay_from_earth_center(
ra, dec, time
)
lal_time = time + np.array([TimeDelayFromEarthCenter(
DetectorPrefixToLALDetector('H1').location, ra[ii], dec[ii],
time[ii]) for ii in range(len(ra))
])
difference = np.abs(lal_time - pycbc_time)
dp = np.floor(np.abs(np.log10(np.max(difference))))
assert np.testing.assert_almost_equal(H1_time, pycbc_time, dp) is None
assert np.testing.assert_almost_equal(H1_time, lal_time, dp) is None
def test_lambda_tilde_from_lambda1_lambda2(self):
lambda1 = np.random.uniform(0, 5000, 100)
lambda2 = np.random.uniform(0, 5000, 100)
mass1 = np.random.randint(5, 100, 100)
mass2 = np.random.randint(2, mass1, 100)
pycbc_function = conversions.lambda_tilde
pesummary_function = lambda_tilde_from_lambda1_lambda2
conversion_check(
pesummary_function, [lambda1, lambda2, mass1, mass2],
pycbc_function, [mass1, mass2, lambda1, lambda2]
)
def test_delta_lambda_from_lambda1_lambda2(self):
from bilby.gw.conversion import lambda_1_lambda_2_to_delta_lambda_tilde
lambda1 = np.random.uniform(0, 5000, 100)
lambda2 = np.random.uniform(0, 5000, 100)
mass1 = np.random.randint(5, 100, 100)
mass2 = np.random.randint(2, mass1, 100)
conversion_check(
delta_lambda_from_lambda1_lambda2,
[lambda1, lambda2, mass1, mass2],
lambda_1_lambda_2_to_delta_lambda_tilde,
[lambda1, lambda2, mass1, mass2]
)
def test_lambda1_from_lambda_tilde(self):
from bilby.gw.conversion import lambda_tilde_to_lambda_1_lambda_2
mass1 = np.random.randint(5, 100, 100)
mass2 = np.random.randint(2, mass1, 100)
lambda_tilde = np.random.uniform(-100, 100, 100)
lambda_1 = lambda_tilde_to_lambda_1_lambda_2(
lambda_tilde, mass1, mass2
)[0]
lambda1 = lambda1_from_lambda_tilde(lambda_tilde, mass1, mass2)
assert np.testing.assert_almost_equal(lambda1, lambda_1) is None
#assert np.round(lambda1, 4) == 192.8101
def test_lambda2_from_lambda1(self):
from bilby.gw.conversion import convert_to_lal_binary_neutron_star_parameters
mass1 = np.random.uniform(5, 50, 100)
mass2 = np.random.uniform(2, mass1, 100)
lambda_1 = np.random.uniform(0, 5000, 100)
sample = {"mass_1": mass1, "mass_2": mass2, "lambda_1": lambda_1}
convert = convert_to_lal_binary_neutron_star_parameters(sample)[0]
lambda2 = lambda2_from_lambda1(lambda_1, mass1, mass2)
diff = np.abs(lambda2 - convert["lambda_2"])
ind = np.argmax(diff)
assert np.testing.assert_almost_equal(lambda2, convert["lambda_2"], 5) is None
def test_network_snr(self):
snr_H1 = snr_L1 = snr_V1 = np.array([2., 3.])
assert network_snr([snr_H1[0], snr_L1[0], snr_V1[0]]) == np.sqrt(3) * 2
print(snr_H1)
network = network_snr([snr_H1, snr_L1, snr_V1])
print(network)
assert network[0] == np.sqrt(3) * 2
assert network[1] == np.sqrt(3) * 3
def test_network_matched_filter_snr(self):
"""Samples taken from a lalinference result file
"""
snr_mf_H1 = 7.950207935574794
snr_mf_L1 = 19.232672412819483
snr_mf_V1 = 3.666438738845737
snr_opt_H1 = 9.668043620320788
snr_opt_L1 = 19.0826463504282
snr_opt_V1 = 3.5578582036515236
network = network_matched_filter_snr(
[snr_mf_H1, snr_mf_L1, snr_mf_V1],
[snr_opt_H1, snr_opt_L1, snr_opt_V1]
)
np.testing.assert_almost_equal(network, 21.06984787727566)
network = network_matched_filter_snr(
[[snr_mf_H1] * 2, [snr_mf_L1] * 2, [snr_mf_V1] * 2],
[[snr_opt_H1] * 2, [snr_opt_L1] * 2, [snr_opt_V1] * 2]
)
np.testing.assert_almost_equal(
network, [21.06984787727566] * 2
)
snr_mf_H1 = 7.950207935574794 - 1.004962343498161 * 1j
snr_mf_L1 = 19.232672412819483 - 0.4646531569951501 * 1j
snr_mf_V1 = 3.666438738845737 - 0.08177741915398137 * 1j
network = network_matched_filter_snr(
[snr_mf_H1, snr_mf_L1, snr_mf_V1],
[snr_opt_H1, snr_opt_L1, snr_opt_V1]
)
np.testing.assert_almost_equal(network, 21.06984787727566)
def test_full_conversion(self):
from pesummary.utils.array import Array
from pesummary.gw.conversions import convert
from bilby.gw.conversion import convert_to_lal_binary_black_hole_parameters
from pandas import DataFrame
dictionary = {
"mass_1": [10.],
"mass_2": [2.],
"a_1": [0.2],
"a_2": [0.2],
"cos_theta_jn": [0.5],
"cos_tilt_1": [0.2],
"cos_tilt_2": [0.2],
"luminosity_distance": [0.2],
"geocent_time": [0.2],
"ra": [0.2],
"dec": [0.2],
"psi": [0.2],
"phase": [0.5],
"phi_12": [0.7],
"phi_jl": [0.25],
"H1_matched_filter_abs_snr": [10.0],
"H1_matched_filter_snr_angle": [0.],
"H1_matched_filter_snr": [10.0],
"H1_optimal_snr": [10.0]
}
data = convert(dictionary)
true_params = [
'mass_1', 'mass_2', 'a_1', 'a_2', 'cos_theta_jn', 'cos_tilt_1',
'cos_tilt_2', 'luminosity_distance', 'geocent_time', 'ra', 'dec',
'psi', 'phase', 'phi_12', 'phi_jl', 'H1_matched_filter_abs_snr',
'H1_matched_filter_snr_angle', 'H1_matched_filter_snr', 'theta_jn',
'tilt_1', 'tilt_2', 'mass_ratio', 'inverted_mass_ratio',
'total_mass', 'chirp_mass', 'symmetric_mass_ratio', 'iota',
'spin_1x', 'spin_1y', 'spin_1z', 'spin_2x', 'spin_2y', 'spin_2z',
'phi_1', 'phi_2', 'chi_eff', 'chi_p', 'final_spin_non_evolved',
'peak_luminosity_non_evolved', 'final_mass_non_evolved', 'redshift',
'comoving_distance', 'mass_1_source', 'mass_2_source',
'total_mass_source', 'chirp_mass_source',
'final_mass_source_non_evolved', 'radiated_energy_non_evolved',
'network_matched_filter_snr', 'cos_iota'
]
assert all(i in data.parameters for i in true_params)
assert len(data.parameters) == len(set(data.parameters))
true = {
'mass_1': Array(dictionary["mass_1"]),
'mass_2': Array(dictionary["mass_2"]),
'a_1': Array(dictionary["a_1"]),
'a_2': Array(dictionary["a_2"]),
'cos_theta_jn': Array(dictionary["cos_theta_jn"]),
'cos_tilt_1': Array(dictionary["cos_tilt_1"]),
'cos_tilt_2': Array(dictionary["cos_tilt_2"]),
'luminosity_distance': Array(dictionary["luminosity_distance"]),
'geocent_time': Array(dictionary["geocent_time"]),
'ra': Array(dictionary["ra"]), 'dec': Array(dictionary["dec"]),
'psi': Array(dictionary["psi"]), 'phase': Array(dictionary["phase"]),
'phi_12': Array(dictionary["phi_12"]),
'phi_jl': Array(dictionary["phi_jl"]),
'H1_matched_filter_abs_snr': Array(dictionary["H1_matched_filter_abs_snr"]),
'H1_matched_filter_snr_angle': Array(dictionary["H1_matched_filter_snr_angle"]),
'H1_matched_filter_snr': Array(dictionary["H1_matched_filter_snr"]),
'H1_optimal_snr': Array(dictionary["H1_optimal_snr"]),
'theta_jn': Array(np.arccos(dictionary["cos_theta_jn"])),
'tilt_1': Array(np.arccos(dictionary["cos_tilt_1"])),
'tilt_2': Array(np.arccos(dictionary["cos_tilt_2"])),
'mass_ratio': Array([dictionary["mass_2"][0] / dictionary["mass_1"][0]]),
'inverted_mass_ratio': Array([dictionary["mass_1"][0] / dictionary["mass_2"][0]]),
'total_mass': Array([dictionary["mass_1"][0] + dictionary["mass_2"][0]]),
'chirp_mass': Array([3.67097772]),
'symmetric_mass_ratio': Array([0.13888889]),
'iota': Array([1.01719087]), 'spin_1x': Array([-0.18338713]),
'spin_1y': Array([0.06905911]), 'spin_1z': Array([0.04]),
'spin_2x': Array([-0.18475131]), 'spin_2y': Array([-0.06532192]),
'spin_2z': Array([0.04]), 'phi_1': Array([2.78144141]),
'phi_2': Array([3.48144141]), 'chi_eff': Array([0.04]),
'chi_p': Array([0.19595918]),
'final_spin_non_evolved': Array([0.46198316]),
'peak_luminosity_non_evolved': Array([1.01239394]),
'final_mass_non_evolved': Array([11.78221674]),
'redshift': Array([4.5191183e-05]),
'comoving_distance': Array([0.19999755]),
'mass_1_source': Array([9.99954811]),
'mass_2_source': Array([1.99990962]),
'total_mass_source': Array([11.99945773]),
'chirp_mass_source': Array([3.67081183]),
'final_mass_source_non_evolved': Array([11.78168431]),
'radiated_energy_non_evolved': Array([0.21777342]),
'network_matched_filter_snr': Array([10.0]),
'cos_iota': Array([0.52575756])
}
for key in true.keys():
np.testing.assert_almost_equal(
true[key][0], data[key][0], 5
)
convert = convert_to_lal_binary_black_hole_parameters(dictionary)[0]
for key, item in convert.items():
assert np.testing.assert_almost_equal(
item, true[key], 5
) is None
def test_remove_parameter(self):
from pesummary.gw.conversions import convert
dictionary = {
"mass_1": np.random.uniform(5, 100, 100),
"mass_ratio": [0.1] * 100
}
dictionary["mass_2"] = np.random.uniform(2, dictionary["mass_1"], 100)
incorrect_mass_ratio = convert(dictionary)
data = convert(dictionary, regenerate=["mass_ratio"])
assert all(i != j for i, j in zip(
incorrect_mass_ratio["mass_ratio"], data["mass_ratio"]
))
assert np.testing.assert_almost_equal(
data["mass_ratio"],
q_from_m1_m2(dictionary["mass_1"], dictionary["mass_2"]), 8
) is None
class TestPrecessingSNR(object):
"""Test the precessing_snr conversion
"""
def setup(self):
"""Setup the testing class
"""
np.random.seed(1234)
self.n_samples = 20
self.approx = "IMRPhenomPv2"
self.mass_1 = np.random.uniform(20, 100, self.n_samples)
self.mass_2 = np.random.uniform(5, self.mass_1, self.n_samples)
self.a_1 = np.random.uniform(0, 1, self.n_samples)
self.a_2 = np.random.uniform(0, 1, self.n_samples)
self.tilt_1 = np.arccos(np.random.uniform(-1, 1, self.n_samples))
self.tilt_2 = np.arccos(np.random.uniform(-1, 1, self.n_samples))
self.phi_12 = np.random.uniform(0, 1, self.n_samples)
self.theta_jn = np.arccos(np.random.uniform(-1, 1, self.n_samples))
self.phi_jl = np.random.uniform(0, 1, self.n_samples)
self.f_low = [20.] * self.n_samples
self.f_final = [1024.] * self.n_samples
self.phase = np.random.uniform(0, 1, self.n_samples)
self.distance = np.random.uniform(100, 500, self.n_samples)
self.ra = np.random.uniform(0, np.pi, self.n_samples)
self.dec = np.arccos(np.random.uniform(-1, 1, self.n_samples))
self.psi_l = np.random.uniform(0, 1, self.n_samples)
self.time = [10000.] * self.n_samples
self.beta = opening_angle(
self.mass_1, self.mass_2, self.phi_jl, self.tilt_1,
self.tilt_2, self.phi_12, self.a_1, self.a_2,
[20.] * self.n_samples, self.phase
)
self.spin_1z = self.a_1 * np.cos(self.tilt_1)
self.spin_2z = self.a_2 * np.cos(self.tilt_2)
self.psi_J = psi_J(self.psi_l, self.theta_jn, self.phi_jl, self.beta)
def test_harmonic_overlap(self):
"""Test that the sum of 5 precessing harmonics matches exactly to the
original precessing waveform.
"""
from pycbc import pnutils
from pycbc.psd import aLIGOZeroDetHighPower
from pycbc.detector import Detector
from pesummary.gw.conversions.snr import (
_calculate_precessing_harmonics, _dphi,
_make_waveform_from_precessing_harmonics
)
from pesummary.gw.waveform import fd_waveform
for i in range(self.n_samples):
duration = pnutils.get_imr_duration(
self.mass_1[i], self.mass_2[i], self.spin_1z[i],
self.spin_2z[i], self.f_low[i], "IMRPhenomD"
)
t_len = 2**np.ceil(np.log2(duration) + 1)
df = 1./t_len
flen = int(self.f_final[i] / df) + 1
aLIGOpsd = aLIGOZeroDetHighPower(flen, df, self.f_low[i])
psd = aLIGOpsd
h = fd_waveform(
{
"theta_jn": self.theta_jn[i], "phase": self.phase[i],
"phi_jl": self.phi_jl[i], "psi": self.psi_l[i],
"mass_1": self.mass_1[i], "mass_2": self.mass_2[i],
"tilt_1": self.tilt_1[i], "tilt_2": self.tilt_2[i],
"phi_12": self.phi_12[i], "a_1": self.a_1[i],
"a_2": self.a_2[i], "luminosity_distance": self.distance[i],
"ra": self.ra[i], "dec": self.dec[i],
"geocent_time": self.time[i]
}, self.approx, df, self.f_low[i], self.f_final[i],
f_ref=self.f_low[i], flen=flen, pycbc=True, project="L1"
)
harmonics = _calculate_precessing_harmonics(
self.mass_1[i], self.mass_2[i], self.a_1[i],
self.a_2[i], self.tilt_1[i], self.tilt_2[i],
self.phi_12[i], self.beta[i], self.distance[i],
approx=self.approx, f_final=self.f_final[i],
flen=flen, f_ref=self.f_low[i], f_low=self.f_low[i],
df=df, harmonics=[0, 1, 2, 3, 4]
)
dphi = _dphi(
self.theta_jn[i], self.phi_jl[i], self.beta[i]
)
f_plus_j, f_cross_j = Detector("L1").antenna_pattern(
self.ra[i], self.dec[i], self.psi_J[i], self.time[i]
)
h_all = _make_waveform_from_precessing_harmonics(
harmonics, self.theta_jn[i], self.phi_jl[i],
self.phase[i] - dphi, f_plus_j, f_cross_j
)
overlap = compute_the_overlap(
h, h_all, psd, low_frequency_cutoff=self.f_low[i],
high_frequency_cutoff=self.f_final[i], normalized=True
)
np.testing.assert_almost_equal(np.abs(overlap), 1.0)
np.testing.assert_almost_equal(np.angle(overlap), 0.0)
def test_precessing_snr(self):
"""Test the pesummary.gw.conversions.snr.precessing_snr function
"""
# Use default PSD
rho_p = precessing_snr(
self.mass_1, self.mass_2, self.beta, self.psi_J, self.a_1, self.a_2,
self.tilt_1, self.tilt_2, self.phi_12, self.theta_jn,
self.ra, self.dec, self.time, self.phi_jl, self.distance,
self.phase, f_low=self.f_low, spin_1z=self.spin_1z,
spin_2z=self.spin_2z, multi_process=1, debug=False, df=1./8
)
print(rho_p)
assert len(rho_p) == len(self.mass_1)
np.testing.assert_almost_equal(
rho_p, [
0.68388587, 4.44970478, 1.50271424, 16.3827856, 8.36573959,
10.76045285, 5.56389147, 38.75092541, 19.04936638, 46.08235277,
11.04476231, 22.15809248, 21.83931442, 0.52940244, 18.51671761,
60.36654193, 20.90566198, 7.59963958, 28.81494436, 4.8044846
]
)
class TestMultipoleSNR(TestPrecessingSNR):
"""Test the multipole_snr conversion
"""
def setup(self):
super(TestMultipoleSNR, self).setup()
@pytest.mark.skip(reason="Inherited test")
def test_harmonic_overlap(self):
pass
@pytest.mark.skip(reason="Inherited test")
def test_precessing_snr(self):
pass
def test_multipole_snr(self):
"""Test the pesummary.gw.conversions.multipole_snr function
"""
rho = multipole_snr(
self.mass_1, self.mass_2, self.spin_1z, self.spin_2z, self.psi_l,
self.theta_jn, self.ra, self.dec, self.time, self.distance,
self.phase, multi_process=1, df=1./8, multipole=[21, 33, 44]
)
assert rho.shape[0] == 3
np.testing.assert_almost_equal(
rho[0], [
0.6596921, 2.12974546, 1.93105129, 1.35944417, 0.9120402,
3.80282866, 7.61761295, 1.16740751, 10.21191012, 9.35936201,
0.27350052, 4.43640379, 1.51461019, 4.70872955, 2.7549612,
2.2352616, 3.41052443, 1.10154954, 15.81511232, 0.23764298
]
)
np.testing.assert_almost_equal(
rho[1], [
2.2024227, 5.21268461, 7.38129296, 3.82192114, 1.64048716,
4.24737159, 22.50700374, 14.58858975, 21.1321856, 26.96560935,
2.34024445, 11.63883373, 6.46660159, 16.01541501, 6.23402429,
14.97004104, 12.07573489, 0.71078634, 14.36867389, 3.05641683
]
)
np.testing.assert_almost_equal(
rho[2], [
0.17943241, 2.22706934, 0.92289317, 1.75781028, 4.60991554,
3.27450411, 9.1738965, 13.1496354, 9.69145147, 15.48684113,
1.59531519, 5.40656286, 8.20452335, 4.48912263, 4.92358844,
11.3532783, 4.3573242, 1.01853648, 7.36585491, 9.26232754
]
)
with pytest.raises(ValueError):
rho = multipole_snr(
self.mass_1, self.mass_2, self.spin_1z, self.spin_2z, self.psi_l,
self.theta_jn, self.ra, self.dec, self.time, self.distance,
self.phase, multi_process=1, df=1./8, multipole=[21, 33, 44, 55]
)
class TestNRutils(object):
def setup(self):
self.mass_1 = 100
self.mass_2 = 5
self.total_mass = m_total_from_m1_m2(self.mass_1, self.mass_2)
self.eta = eta_from_m1_m2(self.mass_1, self.mass_2)
self.spin_1z = 0.3
self.spin_2z = 0.5
self.chi_eff | |
<reponame>anxhelahyseni/nball4tree
import os
import decimal
from collections import defaultdict
from nltk.corpus import wordnet as wn
from nball4tree.config import DECIMAL_PRECISION
from nball4tree.util_vec import vec_norm
decimal.getcontext().prec = DECIMAL_PRECISION
def create_ball_file(ballname, word2ballDic=dict(), outputPath=None):
"""
:param ballname:
:param word2ballDic:
:param outputPath:
:return:
"""
if not os.path.exists(outputPath):
os.makedirs(outputPath)
with open(os.path.join(outputPath, ballname), 'w+') as bfh:
blst = word2ballDic[ballname]
bfh.write(' '.join([str(ele) for ele in blst]) + "\n")
def load_one_ball(ball, ipath="/Users/tdong/data/glove/glove.6B/glove.6B.50Xball", word2ballDic=dict()):
"""
:param ball:
:param ipath:
:param word2ballDic:
:return:
"""
with open(os.path.join(ipath, ball), 'r') as ifh:
wlst = ifh.readline()[:-1].split()
word2ballDic[ball] = [decimal.Decimal(ele) for ele in wlst]
return len(wlst), 0, word2ballDic
def load_balls(ipath="/Users/tdong/data/glove/glove.6B/glove.6B.50Xball", word2ballDic=dict()):
"""
:param ipath:
:param word2ballDic:
:return:
"""
print("loading balls....")
sizes = []
dims = []
for fn in [ele for ele in os.listdir(ipath) if len(ele.split('.'))>2]:
sz, mele, word2ballDic = load_one_ball(fn, ipath = ipath, word2ballDic=word2ballDic)
sizes.append(sz)
dims.append(mele)
sizes = list(set(sizes))
print(sizes)
print('totally', len(word2ballDic), ' balls are loaded')
return max(sizes), min(dims), word2ballDic
def load_ball_embeddings(bFile):
"""
:param bFile:
:return:
"""
print("loading balls....")
bdic=dict()
with open(bFile, 'r') as w2v:
for line in w2v.readlines():
wlst = line.strip().split()
bdic[wlst[0]] = [decimal.Decimal(ele) for ele in wlst[1:]]
print(len(bdic),' balls are loaded\n')
return bdic
def get_word_embedding_dic(wordEmbeddingFile):
dic=defaultdict()
with open (wordEmbeddingFile, 'r') as fh:
for line in fh.readlines():
lst = line.split()
v = [decimal.Decimal(ele) for ele in lst[1:]]
dic[lst[0]] = v
return dic
def get_ball_from_file(ball, ballPath = None):
"""
:param ball:
:param ballPath:
:return:
"""
with open(os.path.join(ballPath, ball), 'r') as ifh:
wlst = ifh.readline().strip().split()
ballv = [decimal.Decimal(ele) for ele in wlst]
return ballv
def get_word_embedding_dic(wordEmbeddingFile):
"""
:param wordEmbeddingFile:
:return:
"""
dic=dict()
with open (wordEmbeddingFile, 'r') as fh:
for line in fh.readlines():
lst = line.split()
v = [decimal.Decimal(ele) for ele in lst[1:]]
dic[lst[0]] = v
return dic
def initialize_dictionaries(word2vecFile=None, catDicFile=None, wsChildrenFile = None):
"""
input is pre-trained word2vec
:param word2vecFile:
:param catDicFile:
:param wsChildrenFile:
:return:
"""
wscatCodeDic = dict()
wsChildrenDic = dict()
word2vecDic = dict()
if not os.path.isfile(word2vecFile):
print('file does not exist:', word2vecFile)
return
with open(word2vecFile, 'r', encoding="utf-8-sig") as w2v:
for line in w2v.readlines():
wlst = line.strip().split()
word2vecDic[wlst[0]] = vec_norm([float(ele) for ele in wlst[1:]])
if os.path.isfile(catDicFile):
with open(catDicFile, 'r', encoding="utf-8-sig") as cfh:
for ln in cfh.readlines():
wlst = ln[:-1].split()
wscatCodeDic[wlst[0]] = [int(ele) for ele in wlst[1:]]
if os.path.isfile(wsChildrenFile):
with open(wsChildrenFile, 'r', encoding="ISO-8859-1") as chfh:
for ln in chfh:
wlst = ln[:-1].split()
wsChildrenDic[wlst[0]] = wlst[1:]
return wsChildrenDic, word2vecDic, wscatCodeDic
def merge_balls_into_file(ipath="", outfile=""):
"""
:param ipath:
:param outfile:
:return:
"""
lst = []
for fn in os.listdir(ipath):
if fn.startswith('.'): continue
with open(os.path.join(ipath, fn), "r") as fh:
ln = fh.read()
lst.append(" ".join([fn,ln]))
with open(outfile, 'w+') as oth:
oth.writelines(lst)
def get_all_words(aFile):
with open(aFile) as f:
words = f.read().split()
return words
def create_parent_children_file(ln, ofile="/Users/tdong/data/glove_wordSenseChildren.txt",
w2vile= "/Users/tdong/data/glove/glove.6B.50d.txt"):
"""
the problem of this method is: a->b->c, but b is not in the w2v file, a and c are in the w2v.
the relation between a->c is brocken
:param ln:
:param ofile:
:param w2vile:
:return:
"""
lst = ln.split()
lines = [" ".join(["*root*"] + lst + ["\n"])]
with open(w2vile, 'r') as vfh:
vocLst = [word.split()[0] for word in vfh.readlines()]
while lst:
parent = lst.pop(0)
children = [ele.name() for ele in wn.synset(parent).hyponyms() if ele.name().split('.')[0] in vocLst]
newLine = " ".join([parent] + children + ["\n"])
lines.append(newLine)
print(parent, "::", children)
lst += children
with open(ofile, 'w') as ofh:
ofh.write("".join(lines))
def create_parent_children_file_from_path(ofile="/Users/tdong/data/glove_wordSenseChildren.txt.newest",
w2vFile= "/Users/tdong/data/glove/glove.6B.50d.txt",
wsPath="/Users/tdong/data/glove/wordSensePath.txt.new"):
def find_parent_of(x, ancestor=None):
for lst in [[ele.name() for ele in hlst] for hlst in wn.synset(x).hypernym_paths()]:
if ancestor in lst:
return lst[-2]
voc = []
with open(w2vFile, 'r') as vfh:
for ln in vfh:
voc.append(ln.split()[0])
parentChildDic = defaultdict(list)
rootLst = []
with open(wsPath, 'r') as ifh:
for ln in ifh:
wlst = ln.strip().split()[2:]
if len(wlst) == 0:
continue
if wlst[0] not in rootLst:
rootLst.append(wlst[0])
for p,c in zip(wlst[:-1], wlst[1:]):
pOfC = find_parent_of(c, ancestor=p)
if c not in parentChildDic[pOfC]:
if not pOfC:
if not c:
parentChildDic[c]=[]
elif c in [ele.name() for ele in wn.synset(pOfC).instance_hyponyms()]:
if c not in parentChildDic[p]:
parentChildDic[p] += [ele.name() for ele in wn.synset(pOfC).instance_hyponyms()
if ele.name().split(".")[0] in voc]
elif c in [ele.name() for ele in wn.synset(pOfC).hyponyms()]:
if c not in parentChildDic[p]:
parentChildDic[p] += [ele.name() for ele in wn.synset(pOfC).hyponyms()
if ele.name().split(".")[0] in voc]
elif c not in parentChildDic[p]:
if c.split(".")[0] in voc:
parentChildDic[p] += [c]
parentChildDic["*root*"] = rootLst
lines = []
for k, v in parentChildDic.items():
if type(k) != str:
print("*", k, "*")
lines.append(" ".join([str(k)] + v + ["\n"]))
with open(ofile, 'w') as ofh:
ofh.write("".join(lines))
def clean_parent_children_file(ifile="/Users/tdong/myDocs/glove.6B.tree.input/glove.6B.children.txt",
w2vFile= "/Users/tdong/data/glove/glove.6B.50d.txt",
ofile="/Users/tdong/data/glove_wordSenseChildren.txt"):
lines = []
with open(w2vFile, 'r') as ifh:
vocLst = [ele.split()[0] for ele in ifh.readlines()]
with open(ifile, 'r') as ifh:
for ln in ifh:
wlst = ln.strip().split()
if wlst[0] == "*root*" or len(wlst) == 1:
lines.append(" ".join(wlst+["\n"]))
else :
children = [ele for ele in wlst[1:] if ele.split(".")[0] in vocLst]
lines.append(" ".join([wlst[0]] + children + ["\n"]))
with open(ofile, 'w') as ofh:
ofh.write("".join(lines))
def ball_counter(ifile):
lst = []
with open(ifile, 'r') as ifh:
for ln in ifh:
nlst = [ele for ele in ln.strip().split() if ele not in lst and ele != "*root*"]
lst += nlst
print(len(lst))
def clean_wordsense_path(ifile="", w2vFile ="", ofile=""):
lines = []
with open(w2vFile, 'r') as ifh:
vocLst = [ele.split()[0] for ele in ifh.readlines()]
with open(ifile, 'r') as ifh:
for ln in ifh:
wlst = ln.strip().split()
if len(wlst) > 2:
node = wlst[0]
lsts = [[ele.name() for ele in lst if ele.name().split(".")[0] in vocLst]
for lst in wn.synset(node).hypernym_paths()]
wspath = sorted(lsts, key = len)[-1]
lines.append(" ".join(wlst[:2] + wspath+["\n"]))
else:
lines.append(ln)
with open(ofile, 'w') as ofh:
ofh.write("".join(lines))
def create_ws_path(ifile="/Users/tdong/data/glove_wordSenseChildren57287.txt.newest.clean",
oWsPathfile="/Users/tdong/data/glove_wordSensePath57287.txt.newest"):
"""
load all word-senses and wsChild2ParentDic from ifile
for each ws:
x = ws
path[ws] = [ws]
while x:
x = get_parent_of(x)
path[ws].append(x)
:param ifile:
:param ofile:
:return:
"""
wsParentDic, wsPathDic = defaultdict(list), defaultdict(list)
wsLst = []
with open(ifile, 'r') as cfh:
for ln in cfh.readlines():
lst = ln.strip().split()
newWS = [ele for ele in lst if ele not in wsLst]
wsLst += newWS
for c in lst[1:]:
wsParentDic[c] = lst[0]
for ws in wsLst:
wsPathDic[ws] = [ws]
x = ws
lst = [x]
while x :
x = wsParentDic[x]
"""
'restrain.v.01' and 'inhibit.v.04' have a mutal hyponym relation in WordNet 3.0
'inhibit.v.04' hypernym path does not contain restrain.v.01
manually set 'inhibit.v.04' as the hypernym of 'restrain.v.01'
"""
if x in lst:
print(x)
x = False
break
if x:
lst.append(x)
wsPathDic[ws].append(x)
open(oWsPathfile, 'w').close()
with open(oWsPathfile, 'a+') as ofh:
for ws, apath in wsPathDic.items():
apath.reverse()
ofh.write(" ".join([ws]+apath+["\n"]))
def generate_ws_cat_codes(cpathFile = "",
childrenFile ="",
outFile="", depth=0):
"""
:param cpathFile:
:param childrenFile:
:param outFile:
:param depth:
:return:
"""
wsPathDic, wsChildrenDic = defaultdict(), defaultdict()
with open(cpathFile, 'r') as cfh:
for ln in cfh.readlines():
lst = ln[:-1].split()
wsPathDic[lst[0]] = lst[1:]
with open(childrenFile, 'r') as chfh:
for ln in chfh.readlines():
lst = ln.strip().split()
if len(lst) == 0:
wsChildrenDic[lst[0]] = []
else:
wsChildrenDic[lst[0]] = lst[1:]
ofh = open(outFile, 'a+')
ml, nm = 0, ''
for node, plst in wsPathDic.items():
plst = plst[:-1]
clst = ["1"]
if ml < len(plst):
ml = len(plst)
nm = node
for (parent, child) in zip(plst[:-1], plst[1:]):
children = wsChildrenDic[parent]
clst.append(str(children.index(child) +1))
clst += ['0'] * (depth - len(clst))
line = " ".join([node] + clst) + "\n"
ofh.write(line)
ofh.close()
return nm, ml
def check_whether_tree(ifile="/Users/tdong/data/glove_wordSenseChildren57285.txt.newest",
ofile="/Users/tdong/data/glove_wordSenseChildren57285.txt.newest.clean",
oWsPathfile="/Users/tdong/data/glove_wordSensePath57285.txt.newest.clean",
oCatCodeFile="/Users/tdong/data/glove_wordSenseCatCode57285.txt.newest.clean"):
def appear2times(a, alst):
if a in alst:
loc = alst.index(a)
if p in alst[loc+1:]:
return True
return False
wsDic = defaultdict()
with open(ifile , 'r') as ifh:
for ln in ifh:
wlst = ln.strip().split()
for ws in wlst:
if ws in wsDic:
wsDic[ws] += 1
else:
wsDic[ws] = 1
pLst = [(k, v-2) for k, v in wsDic.items() if v > 2]
with open(ifile, 'r') as ifh:
lines = ifh.readlines()
while pLst:
p, num = pLst.pop()
for lnIndex in range(len(lines)):
wlst = lines[lnIndex].strip().split()
while p in wlst and wlst[0] != p and num > 0:
wIndex = wlst.index(p)
del wlst[wIndex]
lines = lines[:lnIndex] +[" ".join(wlst+["\n"])] + lines[lnIndex+1:]
num -= 1
pLst = [k for k, v in wsDic.items() if v >= 2] # case of 'depression.n.02', case of 'pemphigus.n.01'
print(' depression.n.02 in list', 'depression.n.02' in pLst)
print('pemphigus.n.01 in list', 'pemphigus.n.01' in pLst)
while pLst:
p = pLst.pop()
asLeaf = False
for lnIndex in | |
canonical order
ignore_empty_rows (:obj:`bool`, optional): if :obj:`True`, ignore empty rows
group_objects_by_model (:obj:`bool`, optional): if :obj:`True`, group decoded objects by their
types
validate (:obj:`bool`, optional): if :obj:`True`, validate the data
Returns:
:obj:`dict`: model objects grouped by :obj:`Model` class
Raises:
:obj:`ValueError`: if the input format is not supported, model names are not unique, or the
data is invalid
"""
# cast models to list
if models is None:
models = self.MODELS
if not isinstance(models, (list, tuple)):
models = [models]
# read the JSON into standard Python objects (ints, floats, strings, lists, dicts, etc.)
_, ext = splitext(path)
ext = ext.lower()
with open(path, 'r') as file:
if ext == '.json':
json_objs = json.load(file)
elif ext in ['.yaml', '.yml']:
json_objs = yaml.load(file, Loader=yaml.FullLoader)
else:
raise ValueError('Unsupported format {}'.format(ext))
# read the objects
if group_objects_by_model:
output_format = 'dict'
else:
output_format = 'list'
objs = Model.from_dict(json_objs, models, ignore_extra_models=ignore_extra_models, validate=validate,
output_format=output_format)
# read the metadata
self._doc_metadata = {}
self._model_metadata = {}
if isinstance(json_objs, dict):
self._doc_metadata = json_objs.get('_documentMetadata', {})
assert not schema_name or self._doc_metadata.get('schema', schema_name) == schema_name, \
"Schema must be '{}'".format(schema_name)
all_models = set(models)
for model in list(all_models):
all_models.update(set(utils.get_related_models(model)))
model_names = {model.__name__: model for model in all_models}
self._model_metadata = {}
for model_name, model_metadata in json_objs.get('_classMetadata', {}).items():
model = model_names[model_name]
self._model_metadata[model] = model_metadata
# return the objects
return objs
class WorkbookReader(ReaderBase):
""" Read model objects from an XLSX file or CSV and TSV files """
DOC_METADATA_PATTERN = r"^!!!ObjTables( +(.*?)=('((?:[^'\\]|\\.)*)'|\"((?:[^\"\\]|\\.)*)\"))* *$"
MODEL_METADATA_PATTERN = r"^!!ObjTables( +(.*?)=('((?:[^'\\]|\\.)*)'|\"((?:[^\"\\]|\\.)*)\"))* *$"
def run(self, path, schema_name=None, models=None,
allow_multiple_sheets_per_model=False,
ignore_missing_models=False, ignore_extra_models=False,
ignore_sheet_order=False,
include_all_attributes=True, ignore_missing_attributes=False, ignore_extra_attributes=False,
ignore_attribute_order=False, ignore_empty_rows=True,
group_objects_by_model=True, validate=True):
""" Read a list of model objects from file(s) and, optionally, validate them
File(s) may be a single XLSX workbook with multiple worksheets or a set of delimeter
separated files encoded by a single path with a glob pattern.
Args:
path (:obj:`str`): path to file(s)
schema_name (:obj:`str`, optional): schema name
models (:obj:`types.TypeType` or :obj:`list` of :obj:`types.TypeType`, optional): type or list
of type of objects to read
allow_multiple_sheets_per_model (:obj:`bool`, optional): if :obj:`True`, allow multiple sheets per model
ignore_missing_models (:obj:`bool`, optional): if :obj:`False`, report an error if a worksheet/
file is missing for one or more models
ignore_extra_models (:obj:`bool`, optional): if :obj:`True` and all :obj:`models` are found, ignore
other worksheets or files
ignore_sheet_order (:obj:`bool`, optional): if :obj:`True`, do not require the sheets to be provided
in the canonical order
include_all_attributes (:obj:`bool`, optional): if :obj:`True`, export all attributes including those
not explictly included in :obj:`Model.Meta.attribute_order`
ignore_missing_attributes (:obj:`bool`, optional): if :obj:`False`, report an error if a
worksheet/file doesn't contain all of attributes in a model in :obj:`models`
ignore_extra_attributes (:obj:`bool`, optional): if :obj:`True`, do not report errors if
attributes in the data are not in the model
ignore_attribute_order (:obj:`bool`, optional): if :obj:`True`, do not require the attributes to be provided
in the canonical order
ignore_empty_rows (:obj:`bool`, optional): if :obj:`True`, ignore empty rows
group_objects_by_model (:obj:`bool`, optional): if :obj:`True`, group decoded objects by their
types
validate (:obj:`bool`, optional): if :obj:`True`, validate the data
Returns:
:obj:`obj`: if :obj:`group_objects_by_model` set returns :obj:`dict`: of model objects grouped by :obj:`Model` class;
else returns :obj:`list`: of all model objects
Raises:
:obj:`ValueError`: if
* Sheets cannot be unambiguously mapped to models
* The file(s) indicated by :obj:`path` is missing a sheet for a model and
:obj:`ignore_missing_models` is :obj:`False`
* The file(s) indicated by :obj:`path` contains extra sheets that don't correspond to one
of :obj:`models` and :obj:`ignore_extra_models` is :obj:`False`
* The worksheets are file(s) indicated by :obj:`path` are not in the canonical order and
:obj:`ignore_sheet_order` is :obj:`False`
* Some models are not serializable
* The data contains parsing errors found by :obj:`read_model`
"""
# detect extension
_, ext = splitext(path)
ext = ext.lower()
# initialize reader
reader_cls = wc_utils.workbook.io.get_reader(ext)
reader = reader_cls(path)
# initialize reading
reader.initialize_workbook()
self._doc_metadata = {}
self._model_metadata = {}
# check that at least one model is defined
if models is None:
models = self.MODELS
if not isinstance(models, (list, tuple)):
models = [models]
# map sheet names to model names
sheet_names = reader.get_sheet_names()
model_name_to_sheet_name = collections.OrderedDict()
sheet_name_to_model_name = collections.OrderedDict()
for sheet_name in sheet_names:
if ext == '.xlsx' and not sheet_name.startswith('!!'):
continue
data = reader.read_worksheet(sheet_name)
doc_metadata, model_metadata, _ = self.read_worksheet_metadata(sheet_name, data)
self.merge_doc_metadata(doc_metadata)
assert not schema_name or doc_metadata.get('schema', schema_name) == schema_name, \
"Schema must be '{}'".format(schema_name)
assert not schema_name or model_metadata.get('schema', schema_name) == schema_name, \
"Schema must be '{}'".format(schema_name)
if model_metadata['type'] != DOC_TABLE_TYPE:
continue
assert 'class' in model_metadata, 'Metadata for sheet "{}" must define the class.'.format(sheet_name)
if model_metadata['class'] not in model_name_to_sheet_name:
model_name_to_sheet_name[model_metadata['class']] = []
model_name_to_sheet_name[model_metadata['class']].append(sheet_name)
sheet_name_to_model_name[sheet_name] = model_metadata['class']
# drop metadata models unless they're requested
ignore_model_names = []
for metadata_model in (utils.DataRepoMetadata, utils.SchemaRepoMetadata):
if metadata_model not in models:
ignore_model_names.append(metadata_model.Meta.verbose_name)
for ignore_model_name in ignore_model_names:
model_name_to_sheet_name.pop(ignore_model_name, None)
# build maps between sheet names and models
model_name_to_model = {model.__name__: model for model in models}
model_to_sheet_name = collections.OrderedDict()
for model_name, sheet_names in model_name_to_sheet_name.items():
model = model_name_to_model.get(model_name, None)
if model:
model_to_sheet_name[model] = sheet_names
sheet_name_to_model = collections.OrderedDict()
for sheet_name, model_name in sheet_name_to_model_name.items():
sheet_name_to_model[sheet_name] = model_name_to_model.get(model_name, None)
# optionally, check that each model has only 1 sheet
if not allow_multiple_sheets_per_model:
multiply_defined_models = []
for model_name, sheet_names in model_name_to_sheet_name.items():
if len(sheet_names) > 1:
multiply_defined_models.append(model_name)
if multiply_defined_models:
raise ValueError("Models '{}' should only have one table".format(
"', '".join(sorted(multiply_defined_models))))
# optionally, check every models is defined
if not ignore_missing_models:
missing_models = []
for model in models:
if not inspect.isabstract(model) and \
model.Meta.table_format in [TableFormat.row, TableFormat.column] and \
model not in model_to_sheet_name:
missing_models.append(model.__name__)
if missing_models:
raise ValueError("Models '{}' must be defined".format(
"', '".join(sorted(missing_models))))
# optionally, check no extra sheets are defined
if not ignore_extra_models:
extra_sheet_names = []
for sheet_name, model in sheet_name_to_model.items():
if not model:
extra_sheet_names.append(sheet_name)
if ext == '.xlsx':
prefix = '!!'
else:
prefix = ''
extra_sheet_names = set(extra_sheet_names) - set([prefix + TOC_SHEET_NAME, prefix + SCHEMA_SHEET_NAME])
if ext == '.xlsx':
extra_sheet_names = [n[2:] for n in extra_sheet_names]
if extra_sheet_names:
raise ValueError("No matching models for worksheets with TableIds '{}' in {}".format(
"', '".join(sorted(extra_sheet_names)), os.path.basename(path)))
# optionally, check the models are defined in the canonical order
if ext == '.xlsx' and not ignore_sheet_order:
expected_model_order = []
for model in models:
if model in model_to_sheet_name:
expected_model_order.append(model)
if expected_model_order != list(model_to_sheet_name.keys()):
raise ValueError('The sheets must be provided in this order:\n {}'.format(
'\n '.join(model.__name__ for model in expected_model_order)))
# check that models are valid
for model in models:
model.validate_related_attributes()
# check that models are serializable
for model in models:
if not model.is_serializable():
module = model.__module__ + '.'
if module.startswith('schema_'):
module = ''
raise ValueError(('Class {}{} cannot be serialized. '
'Check that each of the related classes has a primary attribute and '
'that the values of this attribute must be unique.'
).format(module, model.__name__))
# read objects
attributes = {}
data = {}
errors = {}
objects = {}
for model, sheet_names in model_to_sheet_name.items():
attributes[model] = {}
data[model] = {}
objects[model] = {}
for sheet_name in sheet_names:
sheet_attributes, sheet_data, sheet_errors, sheet_objects = self.read_model(
reader, sheet_name, schema_name, model,
include_all_attributes=include_all_attributes,
ignore_missing_attributes=ignore_missing_attributes,
ignore_extra_attributes=ignore_extra_attributes,
ignore_attribute_order=ignore_attribute_order,
ignore_empty_rows=ignore_empty_rows,
validate=validate)
if sheet_data:
attributes[model][sheet_name] = sheet_attributes
data[model][sheet_name] = sheet_data
objects[model][sheet_name] = sheet_objects
if sheet_errors:
if model not in errors:
errors[model] = {}
errors[model][sheet_name] = sheet_errors
if errors:
forest = ["The data cannot be loaded because '{}' contains error(s):".format(basename(path))]
for model, model_errors in errors.items():
forest.append([quote(model.__name__)])
for sheet_errors in model_errors.values():
forest.append([sheet_errors])
raise ValueError(indent_forest(forest))
# merge metadata across all tables of each model
unmerged_model_metadata = self._model_metadata
merged_model_metadata = {}
errors = []
for model, model_metadata in unmerged_model_metadata.items():
merged_model_metadata[model] = {}
for sheet_name, sheet_metadata in model_metadata.items():
# ignore sheet-specific metadata
if 'id' in sheet_metadata:
sheet_metadata.pop('id')
# merge metadata across sheets
for key, val in sheet_metadata.items():
if key in merged_model_metadata[model]:
if merged_model_metadata[model][key] != val:
errors.append('Attribute "{}" for model "{}" is not consistent'.format(
key, model.__name__, ))
else:
merged_model_metadata[model][key] = val
self._model_metadata = merged_model_metadata
if errors:
forest = ["The data cannot be loaded because '{}' contains error(s):".format(basename(path))]
forest.append([['Model metadata must be consistent across each table:']])
forest.append([[errors]])
raise ValueError(indent_forest(forest))
# for models with multiple tables, add a comment to the first instance from each | |
#!/usr/bin/env python
# _*_ coding: utf-8 _*_
import os
import argparse
import csv
import copy
import datetime
import subprocess
import numpy as np
import matplotlib.pyplot as plt
from pymatflow.cmd.structflow import read_structure
"""
Piezoelastic Strain Tensor: IBIRION = 8, LEPSILON = T
Elastic tensor: IBIRION = 6, LEPSILON = T, NFREE = 4, ISIF = 3, to get the TOTAL ELASTIC MODULI, ISIF = 3 and NFREE = 4 is needed.
"""
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--outcars", help="OUTCAR for piezoelectric stress tensor and elastic tensor calculation respectively", type=str, nargs=2, required=True)
parser.add_argument("--poscar", type=str, required=True, help="POSCAR of the structure")
parser.add_argument("--output-csv", type=str, default="./piezo_elastic_data.csv",
help="specify the path for the csv file to store the results")
args = parser.parse_args()
# extract e_from_electrons, e_from_ions and c_elastic: converted to numpy array
# OUTCAR to extract piezoelectric stress tensor
with open(os.path.join(args.outcars[0]), "r") as fin:
outcar_lines = fin.readlines()
e_from_electrons = []
e_from_ions = []
for i in range(len(outcar_lines)):
if len(outcar_lines[i].split()) == 0:
continue
#if outcar_lines[i].split()[0] == "PIEZOELECTRIC" and outcar_lines[i].split()[1] == "TENSOR" and outcar_lines[i].split()[2] == "for" and outcar_lines[i].split()[8].split("\n")[0] == "(C/m^2)":
possible1 = "PIEZOELECTRIC TENSOR for field in x, y, z (C/m^2)"
possible2 = "PIEZOELECTRIC TENSOR (including local field effects) for field in x, y, z (C/m^2)"
# different version of VASP or different method may generate different output
# so possible1 and possible2 should be dealt with at the same time.
if possible1 in outcar_lines[i] or possible2 in outcar_lines[i]:
for j in range(i+3, i+6, 1):
tmp = []
for k in range(6):
tmp.append(float(outcar_lines[j].split()[k+1]))
e_from_electrons.append(tmp)
#if outcar_lines[i].split()[0] == "PIEZOELECTRIC" and outcar_lines[i].split()[1] == "TENSOR" and outcar_lines[i].split()[2] == "IONIC" and outcar_lines[i].split()[10].split("\n")[0] == "(C/m^2)":
if "PIEZOELECTRIC TENSOR IONIC CONTR for field in x, y, z (C/m^2)" in outcar_lines[i]:
for j in range(i+3, i+6, 1):
tmp = []
for k in range(6):
tmp.append(float(outcar_lines[j].split()[k+1]))
e_from_ions.append(tmp)
e_from_electrons = np.array(e_from_electrons)
e_from_ions = np.array(e_from_ions)
# OUTCAR to extract elastic tensor
with open(os.path.join(args.outcars[1]), "r") as fin:
outcar_lines = fin.readlines()
c_elastic = []
for i in range(len(outcar_lines)):
if len(outcar_lines[i].split()) == 0:
continue
#if outcar_lines[i].split()[0] == "TOTAL" and outcar_lines[i].split()[1] == "ELASTIC" and outcar_lines[i].split()[2] == "MODULI" and outcar_lines[i].split()[3].split("\n")[0] == "(kBar)":
if "TOTAL ELASTIC MODULI (kBar)" in outcar_lines[i]:
for j in range(i+3, i+9, 1):
tmp = []
for k in range(6):
tmp.append(float(outcar_lines[j].split()[k+1]))
c_elastic.append(tmp)
c_elastic = np.array(c_elastic)
# e_from_electrons:
# e_from_ions:
# e_total = e_from_electrons + e_from_ions: C/m^2
# c_elastic: kBar = 10^8 N/m^2
# d_ = e_total * c_elastic^-1
e_total = e_from_electrons + e_from_ions
d_piezo_strain = np.dot(e_total, np.linalg.inv(c_elastic * 1.0e+8)) # C/N
d_piezo_strain_pc_n = np.dot(e_total, np.linalg.inv(c_elastic * 1.0e+8)) * 1.0e+12 # pC/N
e_total_pc_m2 = e_total * 1.0e+12 # pC/m^2
print("*********************************************************\n")
print(" Calculated piezoelectric strain constant\n")
print("---------------------------------------------------------\n")
print("Piezoelectric stress tensor (C/m^2)\n")
print("%f %f %f %f %f %f\n" % (e_total[0, 0], e_total[0, 1], e_total[0, 2], e_total[0, 3], e_total[0, 4], e_total[0, 5]))
print("%f %f %f %f %f %f\n" % (e_total[1, 0], e_total[1, 1], e_total[1, 2], e_total[1, 3], e_total[1, 4], e_total[1, 5]))
print("%f %f %f %f %f %f\n" % (e_total[2, 0], e_total[2, 1], e_total[2, 2], e_total[2, 3], e_total[2, 4], e_total[2, 5]))
print("Piezoelectric stress tensor (pC/m^2)\n")
print("%f %f %f %f %f %f\n" % (e_total_pc_m2[0, 0], e_total_pc_m2[0, 1], e_total_pc_m2[0, 2], e_total_pc_m2[0, 3], e_total_pc_m2[0, 4], e_total_pc_m2[0, 5]))
print("%f %f %f %f %f %f\n" % (e_total_pc_m2[1, 0], e_total_pc_m2[1, 1], e_total_pc_m2[1, 2], e_total_pc_m2[1, 3], e_total_pc_m2[1, 4], e_total_pc_m2[1, 5]))
print("%f %f %f %f %f %f\n" % (e_total_pc_m2[2, 0], e_total_pc_m2[2, 1], e_total_pc_m2[2, 2], e_total_pc_m2[2, 3], e_total_pc_m2[2, 4], e_total_pc_m2[2, 5]))
print("Piezoelectric strain tensor (C/N)\n")
print("%f %f %f %f %f %f\n" % (d_piezo_strain[0, 0], d_piezo_strain[0, 1], d_piezo_strain[0, 2], d_piezo_strain[0, 3], d_piezo_strain[0, 4], d_piezo_strain[0, 5]))
print("%f %f %f %f %f %f\n" % (d_piezo_strain[1, 0], d_piezo_strain[1, 1], d_piezo_strain[1, 2], d_piezo_strain[1, 3], d_piezo_strain[1, 4], d_piezo_strain[1, 5]))
print("%f %f %f %f %f %f\n" % (d_piezo_strain[2, 0], d_piezo_strain[2, 1], d_piezo_strain[2, 2], d_piezo_strain[2, 3], d_piezo_strain[2, 4], d_piezo_strain[2, 5]))
print("Piezoelectric strain tensor (pC/N)\n")
print("%f %f %f %f %f %f\n" % (d_piezo_strain_pc_n[0, 0], d_piezo_strain_pc_n[0, 1], d_piezo_strain_pc_n[0, 2], d_piezo_strain_pc_n[0, 3], d_piezo_strain_pc_n[0, 4], d_piezo_strain_pc_n[0, 5]))
print("%f %f %f %f %f %f\n" % (d_piezo_strain_pc_n[1, 0], d_piezo_strain_pc_n[1, 1], d_piezo_strain_pc_n[1, 2], d_piezo_strain_pc_n[1, 3], d_piezo_strain_pc_n[1, 4], d_piezo_strain_pc_n[1, 5]))
print("%f %f %f %f %f %f\n" % (d_piezo_strain_pc_n[2, 0], d_piezo_strain_pc_n[2, 1], d_piezo_strain_pc_n[2, 2], d_piezo_strain_pc_n[2, 3], d_piezo_strain_pc_n[2, 4], d_piezo_strain_pc_n[2, 5]))
print("Total Elastic tensor (kBar)\n")
print("%f %f %f %f %f %f\n" % (c_elastic[0, 0], c_elastic[0, 1], c_elastic[0, 2], c_elastic[0, 3], c_elastic[0, 4], c_elastic[0, 5]))
print("%f %f %f %f %f %f\n" % (c_elastic[1, 0], c_elastic[1, 1], c_elastic[1, 2], c_elastic[1, 3], c_elastic[1, 4], c_elastic[1, 5]))
print("%f %f %f %f %f %f\n" % (c_elastic[2, 0], c_elastic[2, 1], c_elastic[2, 2], c_elastic[2, 3], c_elastic[2, 4], c_elastic[2, 5]))
print("%f %f %f %f %f %f\n" % (c_elastic[3, 0], c_elastic[3, 1], c_elastic[3, 2], c_elastic[3, 3], c_elastic[3, 4], c_elastic[3, 5]))
print("%f %f %f %f %f %f\n" % (c_elastic[4, 0], c_elastic[4, 1], c_elastic[4, 2], c_elastic[4, 3], c_elastic[4, 4], c_elastic[4, 5]))
print("%f %f %f %f %f %f\n" % (c_elastic[5, 0], c_elastic[5, 1], c_elastic[5, 2], c_elastic[5, 3], c_elastic[5, 4], c_elastic[5, 5]))
print("Total Elastic tensor (N/m^2)\n")
c_elastic_n_m2 = c_elastic * 1.0e+8
print("%f %f %f %f %f %f\n" % (c_elastic_n_m2[0, 0], c_elastic_n_m2[0, 1], c_elastic_n_m2[0, 2], c_elastic_n_m2[0, 3], c_elastic_n_m2[0, 4], c_elastic_n_m2[0, 5]))
print("%f %f %f %f %f %f\n" % (c_elastic_n_m2[1, 0], c_elastic_n_m2[1, 1], c_elastic_n_m2[1, 2], c_elastic_n_m2[1, 3], c_elastic_n_m2[1, 4], c_elastic_n_m2[1, 5]))
print("%f %f %f %f %f %f\n" % (c_elastic_n_m2[2, 0], c_elastic_n_m2[2, 1], c_elastic_n_m2[2, 2], c_elastic_n_m2[2, 3], c_elastic_n_m2[2, 4], c_elastic_n_m2[2, 5]))
print("%f %f %f %f %f %f\n" % (c_elastic_n_m2[3, 0], c_elastic_n_m2[3, 1], c_elastic_n_m2[3, 2], c_elastic_n_m2[3, 3], c_elastic_n_m2[3, 4], c_elastic_n_m2[3, 5]))
print("%f %f %f %f %f %f\n" % (c_elastic_n_m2[4, 0], c_elastic_n_m2[4, 1], c_elastic_n_m2[4, 2], c_elastic_n_m2[4, 3], c_elastic_n_m2[4, 4], c_elastic_n_m2[4, 5]))
print("%f %f %f %f %f %f\n" % (c_elastic_n_m2[5, 0], c_elastic_n_m2[5, 1], c_elastic_n_m2[5, 2], c_elastic_n_m2[5, 3], c_elastic_n_m2[5, 4], c_elastic_n_m2[5, 5]))
print("Piezoelectric stress tensor of 2D materials (z as surface direction)\n")
print("Piezoelectric stess tensor in 2D (pC/m)\n")
print("e_ij(2D)\n")
print("e11 e12 e16\n")
print("e21 e22 e26\n")
print("e31 e32 e36\n")
structure = read_structure(filepath=args.poscar)
c = np.linalg.norm(np.array(structure.cell[2]))
e_total_2d_pc_m = []
for i in [1, 2, 3]:
row = []
for j in [1, 2, 6]:
row.append(e_total[i-1, j-1])
e_total_2d_pc_m.append(row)
e_total_2d_pc_m = np.array(e_total_2d_pc_m) * 1.0e+12 * c * 1.0e-10 # pC/m
print("%f %f %f\n" % (e_total_2d_pc_m[0, 0], e_total_2d_pc_m[0, 1], e_total_2d_pc_m[0, 2]))
print("%f %f %f\n" % (e_total_2d_pc_m[1, 0], e_total_2d_pc_m[1, 1], e_total_2d_pc_m[1, 2]))
print("%f %f %f\n" % (e_total_2d_pc_m[2, 0], e_total_2d_pc_m[2, 1], e_total_2d_pc_m[2, 2]))
print("\n")
print("e_ij(2D): absolute value\n")
print("| |e11| |e12| |e16| |\n")
print("| |e21| |e22| |e26| |\n")
print("| |e31| |e32| |e36| |\n")
e_total_2d_pc_m_abs = np.abs(e_total_2d_pc_m) # we use absolute value of eij in 2d condition
print("%f %f %f\n" % (e_total_2d_pc_m_abs[0, 0], e_total_2d_pc_m_abs[0, 1], e_total_2d_pc_m_abs[0, 2]))
print("%f %f %f\n" % (e_total_2d_pc_m_abs[1, 0], e_total_2d_pc_m_abs[1, 1], e_total_2d_pc_m_abs[1, 2]))
print("%f %f %f\n" % (e_total_2d_pc_m_abs[2, 0], e_total_2d_pc_m_abs[2, 1], e_total_2d_pc_m_abs[2, 2]))
print("Elastic tensor in 2D (N/m)\n")
print("C_ij(2D)\n")
print("C11 C12 C16\n")
print("C21 C22 C26\n")
print("C61 C62 C66\n")
# c_elastic: kBar = 1.0e+8 N/m^2
c_elastic_2d_n_m = []
for i in [1, 2, 6]:
row = []
for j in [1, 2, 6]:
row.append(c_elastic[i-1, j-1])
c_elastic_2d_n_m.append(row)
c_elastic_2d_n_m = np.array(c_elastic_2d_n_m) *1.0e+8 * c * 1.0e-10 # N/m
print("%f %f %f\n" % (c_elastic_2d_n_m[0, 0], c_elastic_2d_n_m[0, 1], c_elastic_2d_n_m[0, 2]))
print("%f %f %f\n" % (c_elastic_2d_n_m[1, 0], c_elastic_2d_n_m[1, 1], c_elastic_2d_n_m[1, 2]))
print("%f %f %f\n" % (c_elastic_2d_n_m[2, 0], c_elastic_2d_n_m[2, 1], c_elastic_2d_n_m[2, 2]))
print("Piezoelectric strain tensor in 2D (pC/N)\n")
#d_piezo_strain_2d_pc_n = np.dot(e_total_2d_pc_m, np.linalg.inv(c_elastic_2d_n_m)) # pC/N
#print("%f %f %f\n" % (d_piezo_strain_2d_pc_n[0, 0], d_piezo_strain_2d_pc_n[0, 1], d_piezo_strain_2d_pc_n[0, 2]))
#print("%f %f %f\n" % (d_piezo_strain_2d_pc_n[1, 0], d_piezo_strain_2d_pc_n[1, 1], d_piezo_strain_2d_pc_n[1, 2]))
#print("%f %f %f\n" % (d_piezo_strain_2d_pc_n[2, 0], d_piezo_strain_2d_pc_n[2, 1], d_piezo_strain_2d_pc_n[2, 2]))
d_piezo_strain_2d_pc_n = np.dot(e_total_2d_pc_m_abs, np.linalg.inv(c_elastic_2d_n_m)) # pC/N
print("%f %f %f\n" % (d_piezo_strain_2d_pc_n[0, 0], d_piezo_strain_2d_pc_n[0, 1], d_piezo_strain_2d_pc_n[0, 2]))
print("%f %f %f\n" % (d_piezo_strain_2d_pc_n[1, 0], d_piezo_strain_2d_pc_n[1, 1], d_piezo_strain_2d_pc_n[1, 2]))
print("%f %f %f\n" % (d_piezo_strain_2d_pc_n[2, 0], d_piezo_strain_2d_pc_n[2, 1], d_piezo_strain_2d_pc_n[2, 2]))
# output data to csv file
with open(args.output_csv, "w") as fout:
csv_writer = csv.writer(fout)
csv_writer.writerow(["Piezoelectric stress tensor (C/m^2)"])
csv_writer.writerows(e_total.tolist())
csv_writer.writerow(["Piezoelectric stress tensor (pC/m^2)"])
csv_writer.writerows(e_total_pc_m2.tolist())
csv_writer.writerow(["Piezoelectric strain tensor (C/N)"])
csv_writer.writerows(d_piezo_strain.tolist())
csv_writer.writerow(["Piezoelectric strain tensor (pC/N)"])
csv_writer.writerows(d_piezo_strain_pc_n.tolist())
csv_writer.writerow(["Total Elastic tensor (kBar)"])
csv_writer.writerows(c_elastic.tolist())
csv_writer.writerow(["Total Elastic tensor (N/m^2)"])
csv_writer.writerows(c_elastic_n_m2.tolist())
csv_writer.writerow(["Piezoelectric stress tensor of 2D | |
Screens)
self.mw.resizable(0, 0) #Don't allow resizing in the x or y direction
back = tk.Frame(master=self.mw,bg='Grey')
back.pack_propagate(0) #Don't allow the widgets inside to determine the frame's width / height
back.pack(fill=tk.BOTH, expand=1) #Expand the frame to fill the root window
#Buttons
Stop_OP25 = tk.Button(master=back, text='Stop OP25 Instances', command=stopall, width=14, height=3)
Stop_OP25.grid(row=0, column=3, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
GoToFavorites_OP25 = tk.Button(master=back, text='Go To Favorites', command=self.Favorites, width=14, height=3)
GoToFavorites_OP25.grid(row=0, column=1, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
GoToNCCounties_OP25 = tk.Button(master=back, text='Go To NC Counties', command=self.NC_Counties_Home, width=14, height=3)
GoToNCCounties_OP25.grid(row=0, column=5, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_Oxford_Bi_Com = tk.Button(master=back, text='Oxford_Bi_Com', command=CMD_Oxford_Bi_Com, width=14, height=3)
Button_Oxford_Bi_Com.grid(row=1, column=1, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=1, column=2, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=1, column=3, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=1, column=4, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=1, column=5, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=2, column=1, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=2, column=2, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=2, column=3, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=2, column=4, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=2, column=5, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=3, column=1, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=3, column=2, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=3, column=3, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=3, column=4, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=3, column=5, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=4, column=1, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=4, column=2, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=4, column=3, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=4, column=4, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=4, column=5, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
def Menu_Wake(self):
self.mw.destroy()
self.mw = tk.Tk()
#Specify the attributes for all widgets simply like this.
self.mw.option_add("*Button.Background", "Teal")
self.mw.option_add("*Button.Foreground", "White")
self.mw.title('OP25 Repeater Selector GUI')
#You can set the geometry attribute to change the root windows size
self.mw.geometry("800x420") #You want the size of the app to be 750 X 562.5 Pixels (Slightky Smaller than the RPI 7" Touch Screens)
self.mw.resizable(0, 0) #Don't allow resizing in the x or y direction
back = tk.Frame(master=self.mw,bg='Grey')
back.pack_propagate(0) #Don't allow the widgets inside to determine the frame's width / height
back.pack(fill=tk.BOTH, expand=1) #Expand the frame to fill the root window
#Buttons
Stop_OP25 = tk.Button(master=back, text='Stop OP25 Instances', command=stopall, width=14, height=3)
Stop_OP25.grid(row=0, column=3, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
GoToFavorites_OP25 = tk.Button(master=back, text='Go To Favorites', command=self.Favorites, width=14, height=3)
GoToFavorites_OP25.grid(row=0, column=1, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
GoToNCCounties_OP25 = tk.Button(master=back, text='Go To NC Counties', command=self.NC_Counties_Home, width=14, height=3)
GoToNCCounties_OP25.grid(row=0, column=5, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_Archdale_Building = tk.Button(master=back, text='Archdale_Building', command=CMD_Archdale_Building, width=14, height=3)
Button_Archdale_Building.grid(row=1, column=1, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_West_Raleigh_SHP_C_and_L = tk.Button(master=back, text='West_Raleigh_SHP_C_and_L', command=CMD_West_Raleigh_SHP_C_and_L, width=14, height=3)
Button_West_Raleigh_SHP_C_and_L.grid(row=1, column=2, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_NCSHP_Training_Center = tk.Button(master=back, text='NCSHP_Training_Center', command=CMD_NCSHP_Training_Center, width=14, height=3)
Button_NCSHP_Training_Center.grid(row=1, column=3, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_Wendell_AAA = tk.Button(master=back, text='Wendell_AAA', command=CMD_Wendell_AAA, width=14, height=3)
Button_Wendell_AAA.grid(row=1, column=4, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_Wake_North_Durant = tk.Button(master=back, text='Wake_North_Durant', command=CMD_Wake_North_Durant, width=14, height=3)
Button_Wake_North_Durant.grid(row=1, column=5, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_Wake_South_Holly_Springs = tk.Button(master=back, text='Wake_South_Holly_Springs', command=CMD_Wake_South_Holly_Springs, width=14, height=3)
Button_Wake_South_Holly_Springs.grid(row=2, column=1, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=2, column=2, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=2, column=3, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=2, column=4, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=2, column=5, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=3, column=1, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=3, column=2, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=3, column=3, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=3, column=4, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=3, column=5, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=4, column=1, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=4, column=2, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=4, column=3, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=4, column=4, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=4, column=5, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
def Menu_Warren(self):
self.mw.destroy()
self.mw = tk.Tk()
#Specify the attributes for all widgets simply like this.
self.mw.option_add("*Button.Background", "Teal")
self.mw.option_add("*Button.Foreground", "White")
self.mw.title('OP25 Repeater Selector GUI')
#You can set the geometry attribute to change the root windows size
self.mw.geometry("800x420") #You want the size of the app to be 750 X 562.5 Pixels (Slightky Smaller than the RPI 7" Touch Screens)
self.mw.resizable(0, 0) #Don't allow resizing in the x or y direction
back = tk.Frame(master=self.mw,bg='Grey')
back.pack_propagate(0) #Don't allow the widgets inside to determine the frame's width / height
back.pack(fill=tk.BOTH, expand=1) #Expand the frame to fill the root window
#Buttons
Stop_OP25 = tk.Button(master=back, text='Stop OP25 Instances', command=stopall, width=14, height=3)
Stop_OP25.grid(row=0, column=3, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
GoToFavorites_OP25 = tk.Button(master=back, text='Go To Favorites', command=self.Favorites, width=14, height=3)
GoToFavorites_OP25.grid(row=0, column=1, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
GoToNCCounties_OP25 = tk.Button(master=back, text='Go To NC Counties', command=self.NC_Counties_Home, width=14, height=3)
GoToNCCounties_OP25.grid(row=0, column=5, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_Manson = tk.Button(master=back, text='Manson', command=CMD_Manson, width=14, height=3)
Button_Manson.grid(row=1, column=1, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_Warrenton_VTN = tk.Button(master=back, text='Warrenton_VTN', command=CMD_Warrenton_VTN, width=14, height=3)
Button_Warrenton_VTN.grid(row=1, column=2, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=1, column=3, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=1, column=4, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=1, column=5, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=2, column=1, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=2, column=2, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=2, column=3, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=2, column=4, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=2, column=5, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=3, column=1, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=3, column=2, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=3, column=3, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=3, column=4, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=3, column=5, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=4, column=1, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=4, column=2, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=4, column=3, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=4, column=4, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=4, column=5, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
def Menu_Washington(self):
self.mw.destroy()
self.mw = tk.Tk()
#Specify the attributes for all widgets simply like this.
self.mw.option_add("*Button.Background", "Teal")
self.mw.option_add("*Button.Foreground", "White")
self.mw.title('OP25 Repeater Selector GUI')
#You can set the geometry attribute to change the root windows size
self.mw.geometry("800x420") #You want the size of the app to be 750 X 562.5 Pixels (Slightky Smaller than the RPI 7" Touch Screens)
self.mw.resizable(0, 0) #Don't allow resizing in the x or y direction
back = tk.Frame(master=self.mw,bg='Grey')
back.pack_propagate(0) #Don't allow the widgets inside to determine the frame's width / height
back.pack(fill=tk.BOTH, expand=1) #Expand the frame to fill the root window
#Buttons
Stop_OP25 = tk.Button(master=back, text='Stop OP25 Instances', command=stopall, width=14, height=3)
Stop_OP25.grid(row=0, column=3, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
GoToFavorites_OP25 = tk.Button(master=back, text='Go To Favorites', command=self.Favorites, width=14, height=3)
GoToFavorites_OP25.grid(row=0, column=1, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
GoToNCCounties_OP25 = tk.Button(master=back, text='Go To NC Counties', command=self.NC_Counties_Home, width=14, height=3)
GoToNCCounties_OP25.grid(row=0, column=5, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_Plymouth = tk.Button(master=back, text='Plymouth', command=CMD_Plymouth, width=14, height=3)
Button_Plymouth.grid(row=1, column=1, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=1, column=2, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=1, column=3, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=1, column=4, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ = tk.Button(master=back, text='', command='', width=14, height=3)
Button_.grid(row=1, column=5, sticky=tk.W+tk.E+tk.N+tk.S, padx=9, pady=5)
Button_ | |
from flask import Flask, render_template, request, jsonify, redirect, url_for, session, flash, Response
from flaskext.markdown import Markdown
from pymongo import MongoClient
from steem import Steem
from datetime import date, timedelta, datetime
from dateutil import parser
from slugify import slugify
import sys, traceback, json, textwrap, requests, pprint, time, math, arrow
app = Flask(__name__, static_folder='static', static_url_path='')
app.config.from_envvar('FOMODEALS_SETTINGS')
app.secret_key=app.config['SESSION_SECRET']
admins = app.config['ADMINS'].split(',')
Markdown(app)
db = MongoClient("mongodb://mongodb:27017").fomodeals
def confirm_user():
if not 'token' in session or not 'username' in session:
return False
r = requests.get('https://v2.steemconnect.com/api/me', headers={ 'Authorization': session['token'] })
if r.status_code == 200:
session['authorized'] = False
if r.json()['_id'] != session['username']:
return False
if session['username'] == "fomodeals":
session['authorized'] = True
elif 'account_auths' in r.json()['account']['posting']:
for auth_account in r.json()['account']['posting']['account_auths']:
if auth_account[0] == "fomodeals":
session['authorized'] = True
app.logger.info('Confirmed token and auth of {} successful'.format(session['username']))
return True
else:
session['logged_in'] = False
return False
def post_to_steem(deal, update=False):
comment_options = {
'max_accepted_payout': '1000000.000 SBD',
'percent_steem_dollars': 10000,
'allow_votes': True,
'allow_curation_rewards': True,
'extensions': [[0, {
'beneficiaries': [
{'account': 'fomodeals', 'weight': 1000}
]}
]]
}
permlink = ""
deal_post_data = {}
# populate sanitised deal data
deal_post_data['title'] = deal['title'].strip()
deal_post_data['url'] = deal['url']
deal_post_data['brand_code'] = slugify(deal['brand'])
deal_post_data['description'] = deal['description']
try:
deal_post_data['freebie'] = True if deal['freebie'] == 'on' else False
except KeyError:
deal_post_data['freebie'] = False
# TODO: validate image?
if 'image_url' not in deal or deal['image_url'] == "":
deal_post_data['image_url'] = 'https://fomodeals.org/assets/images/logo_round.png'
else:
deal_post_data['image_url'] = deal['image_url']
if 'global' in deal and deal['global'] == 'on':
deal_post_data['global'] = True
else:
deal_post_data['global'] = False
deal_post_data['country_code'] = deal['country_code']
if not 'coupon_code' in deal or deal['coupon_code'].strip() == "":
deal_post_data['coupon_code'] = False
else:
deal_post_data['coupon_code'] = deal['coupon_code'].strip()
try:
deal_post_data['date_start'] = parser.parse(deal['deal_start']).isoformat()
except ValueError:
deal_post_data['date_start'] = date.today().isoformat()
try:
deal_post_data['date_end'] = parser.parse(deal['deal_end']).isoformat()
except ValueError:
deal_post_data['date_end'] = (parser.parse(deal_post_data['date_start']) + timedelta(days=45)).isoformat()
json_metadata = {
'community': 'fomodeals',
'app': 'fomodeals/1.0.0',
'format': 'markdown',
'tags': [ 'fomodeals' ],
'image': [ "https://steemitimages.com/0x0/" + deal_post_data['image_url'] ],
'deal': deal_post_data
}
if 'country_code' in deal_post_data and not deal_post_data['global']:
json_metadata['tags'].append('fomodeals-'+deal['country_code'])
else:
json_metadata['tags'].append('fomodeals-global')
app.logger.info("deal_post_data: {}".format(deal_post_data))
body = render_template("deal_post.md", deal=deal_post_data)
try:
if 'POST_TO_STEEM' in app.config and app.config['POST_TO_STEEM'] == "1":
s = Steem(nodes=['https://rpc.buildteam.io', 'https://api.steemit.com', 'https://steemd.steemitstage.com'],
keys=[app.config['POSTING_KEY'], app.config['ACTIVE_KEY']])
if update:
p = s.commit.post(title=deal['title'],
body=body,
author=session['username'],
json_metadata=json_metadata)
else:
p = s.commit.post(title=deal['title'],
body=body,
author=session['username'],
json_metadata=json_metadata,
comment_options=comment_options,
self_vote=True)
permlink = p['operations'][0][1]['permlink']
app.logger.info("Posted to STEEM with id={}".format(permlink))
return True
else:
app.logger.info("Skipped posting to steem:\n\n{}".format(body))
return False
except Exception as e:
app.logger.info(e)
traceback.print_exc(file=sys.stdout)
return False
@app.template_filter('humanize')
def _jinja2_filter_humanize(t):
l = arrow.get(parser.parse(t))
return l.humanize()
@app.template_filter('reputation')
def _jinja2_filter_reputation(rep):
rep = int(rep)
calc = (math.log10(abs(rep) - 10) - 9)
if rep < 0:
calc = -calc
return int(calc * 9 + 25)
@app.template_filter('expired')
def _jinja2_filter_expired(date):
date = parser.parse(date)
native = date.replace(hour=23, minute=59, tzinfo=None)
ds = (native-date.today()).total_seconds()
if ds < 0:
return True
else:
return False
@app.template_filter('expires_class')
def _jinja2_filter_expires_class(date, fmt=None):
date = parser.parse(date)
native = date.replace(hour=23, minute=59, tzinfo=None)
days = (native-date.today()).days
if days <= 2:
return "red pulse"
else:
return "grey lighten-1"
@app.template_filter('expires_time')
def _jinja2_filter_expires_time(date, fmt=None):
date = parser.parse(date)
native = date.replace(hour=23, minute=59, tzinfo=None)
days = (native-date.today()).days
ds = (native-date.today()).total_seconds()
if ds < 0:
return "{} day{} ago".format(abs(days), '' if abs(days) == 1 else 's')
elif ds < 86400:
return "now"
elif ds < 172800:
return "soon"
else:
return "in {} day{}".format(days, '' if days == 1 else 's')
@app.template_filter('datetimeformat')
def _jinja2_filter_datetime(date, fmt=None):
date = parser.parse(date)
native = date.replace(tzinfo=None)
format='%b %d, %Y'
return native.strftime(format)
@app.route("/fomodeals/@<author>/<permlink>")
def read_deal(author, permlink):
try:
r = requests.get(
'https://api.steemjs.com/getState?path=/fomodeals/@{}/{}'.format(author, permlink))
if r.status_code == 200:
all_content = r.json()['content']
content = all_content['{}/{}'.format(author, permlink)]
json_metadata = json.loads(content['json_metadata'])
deal_metadata = json_metadata['deal']
payout = float(content['pending_payout_value'].split(" ")[0])
return render_template('details.html', author=author, permlink=permlink, json_metadata=json_metadata, deal=deal_metadata, content=all_content, payout="{0:.2f}".format(payout))
else:
return render_template('404.html'), 404
except Exception as e:
app.logger.info(e)
return redirect('https://steemit.com/fomodeals/@{}/{}'.format(author, permlink))
@app.route("/vote/<author>/<permlink>/<kind>")
def vote(author, permlink, kind):
if 'logged_in' in session and session['logged_in'] and 'authorized' in session and session['authorized'] and 'username' in session:
try:
weight=100
if kind == "flag":
weight=-100
identifier = "@" + author + "/" + permlink
if 'POST_TO_STEEM' in app.config and app.config['POST_TO_STEEM'] == "1":
s = Steem(nodes=['https://rpc.buildteam.io', 'https://api.steemit.com', 'https://steemd.steemitstage.com'],
keys=[app.config['POSTING_KEY'], app.config['ACTIVE_KEY']])
p = s.commit.vote(identifier, weight, account=session['username'])
app.logger.info(p)
return jsonify({ 'status': True })
except Exception as e:
app.logger.info(e)
return jsonify({ 'status': False, 'msg': 'unknown exception' })
else:
return jsonify({ 'status': False, 'msg': 'please login and authorize first' })
@app.route("/whoami")
def whoami():
if 'username' in session:
return jsonify({ 'username': session['username']})
else:
return jsonify({ 'username': "" });
@app.route("/update/<permlink>", methods=['GET', 'POST'])
def update(permlink):
if 'logged_in' in session and session['logged_in'] and 'username' in session and session['username'] in app.config['ADMINS'].split(','):
if request.method == 'POST':
deal_update=request.form.to_dict()
# fix some values
if deal_update['warning'].strip() != "":
deal_update['available'] = False
else:
deal_update['available'] = True
if not 'freebie' in deal_update:
deal_update['freebie'] = ''
if not 'global' in deal_update:
deal_update['global'] = ''
if not 'hide' in deal_update:
deal_update['hide'] = False;
else:
deal_update['hide'] = True;
try:
deal_update['deal_start'] = parser.parse(deal_update['deal_start']).isoformat()
except ValueError:
deal_update['deal_start'] = date.today().isoformat()
try:
deal_update['deal_end'] = parser.parse(deal_update['deal_end']).isoformat()
except ValueError:
deal_update['deal_end'] = (date.today() + timedelta(days=45)).isoformat()
deal_update['deal_expires'] = deal_update['deal_end']
deal_update['brand_code'] = slugify(deal_update['brand'])
# TODO: needs more testing on testnet...
# p = post_to_steem(deal_update, update=True)
# app.logger.info("STEEM updated? {}".format(p))
app.logger.info("updating {}: {}".format(permlink, deal_update))
try:
db.deal.update_one({ 'permlink': permlink },
{ '$set': deal_update }, upsert=False)
except Exception as e:
flash(u'Sorry but there was an error trying to update your deal: ' + textwrap.shorten(str(e), width=80, placeholder="..."), 'error')
return redirect(url_for('index'))
else:
deal = db.deal.find_one({'permlink': permlink })
app.logger.info("requested update of: {}".format(deal))
return render_template('update.html', deal=deal)
else:
app.logger.info("non-authorised update attempt ({}, {})".format(permlink, session['username'] if 'username' in session else 'anon'))
return render_template('login_failed.html'), 401
@app.route("/")
def index():
# TODO: only show non-expired deals... paginate?
deals = []
deal_cursor = db.deal.find({'deal_expires': { '$gte': date.today().isoformat()}, 'hide': { '$ne': True}}).sort([('_id', -1)])
for deal in deal_cursor:
deals.append(deal)
if 'username' in session:
if 'logged_in' in session:
app.logger.info("{} logged_in: {}, authorized: {}".format(session['username'], session['logged_in'], session['authorized']))
else:
app.logger.info("{} logged_in: {}".format(session['username'], False))
else:
app.logger.info("anonymous user")
return render_template('index.html', deals=deals, session=session, admins=admins)
@app.route("/trending")
def trending():
return render_template('trending.html')
@app.route("/created")
def created():
return render_template('created.html')
@app.route("/hot")
def hot():
return render_template('hot.html')
@app.route("/countries")
def countries_json():
countries = db.deal.find({ 'country_code': { '$ne': '' }}).distinct('country_code')
return jsonify(sorted(countries, reverse=True))
@app.route("/country/<country>")
def countries(country):
deals = []
deal_cursor=db.deal.find({'deal_expires': { '$gte': date.today().isoformat()}, 'country_code': country, 'hide': { '$ne': True}}).sort([('_id', -1)])
for deal in deal_cursor:
deals.append(deal)
return render_template('index.html', deals=deals, country=country, session=session, admins=admins)
@app.route("/freebies")
def freebies():
deals = []
deal_cursor=db.deal.find({'deal_expires': { '$gte': date.today().isoformat()}, 'freebie': 'on', 'hide': { '$ne': True}}).sort([('_id', -1)])
for deal in deal_cursor:
deals.append(deal)
return render_template('index.html', deals=deals, session=session, admins=admins)
@app.route("/brand/<brand>")
def brands(brand):
deals = []
deal_cursor=db.deal.find({'deal_expires': { '$gte': date.today().isoformat()}, 'brand_code': brand, 'hide': { '$ne': True}}).sort([('_id', -1)])
for deal in deal_cursor:
deals.append(deal)
return render_template('index.html', deals=deals, session=session, admins=admins)
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@app.route('/logout', methods=['GET'])
def logout():
session.pop('username', None)
session.pop('token', None)
session.pop('authorized', None)
session['logged_in'] = False
return redirect(url_for('index'))
@app.route('/auth', methods=['GET'])
def authorized():
if not 'logged_in' in session or not session['logged_in']:
return render_template('login_failed.html'), 401
r = requests.get('https://v2.steemconnect.com/api/me', headers={ 'Authorization': session['token'] })
if r.status_code == 200:
app.logger.info('Auth of {} successful'.format(session['username']))
session['authorized'] = False
if r.json()['_id'] != session['username']:
session['logged_in'] = False
return render_template('login_failed.html'), 401
if session['username'] == "fomodeals":
session['authorized'] = True
if 'account_auths' in r.json()['account']['posting']:
for auth_account in r.json()['account']['posting']['account_auths']:
if auth_account[0] == "fomodeals":
session['authorized'] = True
return redirect(url_for('index'))
else:
session['logged_in'] = False
return render_template('login_failed.html'), 401
@app.route('/complete/sc/', methods=['GET'])
def complete_sc():
# TODO: verify token
token = request.args.get('access_token')
expire = request.args.get('expires_in')
username = request.args.get('username')
r = requests.get('https://v2.steemconnect.com/api/me', headers={ 'Authorization': token })
if r.status_code == 200:
app.logger.info('Login of {} successful'.format(username))
session['authorized'] = False
session['logged_in'] = username == r.json()['_id']
if username == "fomodeals":
session['authorized'] = True
elif 'account_auths' in r.json()['account']['posting']:
for auth_account in r.json()['account']['posting']['account_auths']:
if auth_account[0] == "fomodeals":
session['authorized'] = True
session['username'] = username
session['token'] = token
return redirect(url_for('index'))
else:
session['logged_in'] = False
return render_template('login_failed.html'), 401
@app.route('/comment/<parent_author>/<parent_permlink>', methods=['POST'])
def post_comment(parent_author, parent_permlink):
if not confirm_user():
return render_template('login_failed.html'), 401
comment_form=request.form.to_dict()
comment_options = {
'max_accepted_payout': '1000000.000 SBD',
'percent_steem_dollars': 10000,
'allow_votes': True,
'allow_curation_rewards': True,
'extensions': [[0, {
'beneficiaries': [
{'account': 'fomodeals', 'weight': 1000}
]}
]]
}
json_metadata = {
'community': 'fomodeals',
'app': 'fomodeals/1.0.0',
'format': 'markdown'
}
try:
if 'POST_TO_STEEM' in app.config and app.config['POST_TO_STEEM'] == "1":
s = Steem(nodes=['https://rpc.buildteam.io', 'https://api.steemit.com', 'https://steemd.steemitstage.com'],
keys=[app.config['POSTING_KEY'], app.config['ACTIVE_KEY']])
p = s.commit.post(body=comment_form['body'],
title="",
author=session['username'],
json_metadata=json_metadata,
reply_identifier="@{}/{}".format(parent_author, parent_permlink),
comment_options=comment_options)
permlink = p['operations'][0][1]['permlink']
app.logger.info("Posted to STEEM with id={}".format(permlink))
else:
app.logger.info("Skipped posting to steem:\n\n{}".format(comment_form['body']))
permlink = "testing-{}".format(int(time.time()))
except Exception as e:
app.logger.info(e)
traceback.print_exc(file=sys.stdout)
flash(u'Sorry but there was an error trying to post your comment: ' + textwrap.shorten(str(e), width=80, placeholder="..."), 'error')
return redirect(url_for("index"))
if 'return_to' in comment_form:
return redirect(comment_form['return_to'], code=302)
else:
return redirect(url_for("index"), code=302)
@app.route('/deal', methods=['POST'])
def deal():
if not confirm_user():
return render_template('login_failed.html'), 401
deal_form=request.form.to_dict()
comment_options = {
'max_accepted_payout': '1000000.000 SBD',
'percent_steem_dollars': 10000,
'allow_votes': True,
'allow_curation_rewards': True,
'extensions': [[0, {
| |
<reponame>sagieppel/Instance-and-semantic-segmentation-of-materials-phases-and-vessels-in-chemistry-laboratory-
#Reader for the coco panoptic data set for pointer based image segmentation
import numpy as np
import os
import scipy.misc as misc
import random
import cv2
import json
import threading
import random
############################################################################################################
#########################################################################################################################
class Reader:
# Initiate reader and define the main parameters for the data reader
def __init__(self, ImageDir,MaskDir,FullSegDir,NumClasses,ClassBalance=True, MaxBatchSize=100,MinSize=250,MaxSize=1000,MaxPixels=800*800*5, AnnotationFileType="png", ImageFileType="jpg",TrainingMode=True):
self.MaxBatchSize=MaxBatchSize # Max number of image in batch
self.MinSize=MinSize # Min image width and hight in pixels
self.MaxSize=MaxSize #Max image width and hight in pixels
self.MaxPixels=MaxPixels # Max number of pixel in all the batch (reduce to solve oom out of memory issues)
self.AnnotationFileType=AnnotationFileType # What is the the type (ending) of the annotation files
self.ImageFileType=ImageFileType # What is the the type (ending) of the image files
self.Epoch = 0 # Training Epoch
self.itr = 0 # Training iteratation
self.ClassBalance=ClassBalance
self.Findx=None
# ----------------------------------------Create list of annotations--------------------------------------------------------------------------------------------------------------
self.AnnotationList = []
self.AnnotationByCat = []
self.NumClasses=NumClasses
self.VesselCats = [44, 46, 47, 51, 86] # This is category in COCO that correspond to vessel
for i in range(NumClasses):
self.AnnotationByCat.append([])
uu=0
#Ann_name.replace(".","__")+"##Class##"+str(seg["Class"])+"##IsThing##"+str(seg["IsThing"])+"IDNum"+str(ii)+".png"
print("Creating file list for reader this might take a while")
for AnnDir in MaskDir:
for Name in os.listdir(AnnDir):
uu+=1
# if uu>4000: break
print(uu)
s = {}
s["MaskFile"] = AnnDir + "/" + Name
s["FullAnnFile"] = FullSegDir + "/"+Name[:Name.find("##Class##")].replace("__", ".")
s["IsThing"] = int(Name[Name.find("##IsThing##") + 11: Name.find('IDNum')])==1
s["ImageFile"] = ImageDir+"/"+Name[:Name.find("##Class##")].replace("__png", ".jpg")
s["Class"] = int(Name[Name.find("##Class##") + 9: Name.find("##IsThing##")])
if not (os.path.exists(s["ImageFile"]) and os.path.exists(s["MaskFile"]) and os.path.exists(s["FullAnnFile"])):
print("Missing:"+s["MaskFile"])
continue
self.AnnotationList.append(s)
self.AnnotationByCat[s["Class"]].append(s)
for i in range(NumClasses):
np.random.shuffle(self.AnnotationByCat[i])
print(str(i) + ")" + str(len(self.AnnotationByCat[i])))
np.random.shuffle(self.AnnotationList)
print("done making file list")
iii=0
if TrainingMode: self.StartLoadBatch()
self.AnnData=False
#############################################################################################################################
# Crop and resize image and mask and ROI to feet batch size
def CropResize(self,Img, Mask,AnnMap,Hb,Wb):
# ========================resize image if it too small to the batch size==================================================================================
bbox= cv2.boundingRect(Mask.astype(np.uint8))
[h, w, d] = Img.shape
Rs = np.max((Hb / h, Wb / w))
Wbox = int(np.floor(bbox[2])) # Segment Bounding box width
Hbox = int(np.floor(bbox[3])) # Segment Bounding box height
if Wbox==0: Wbox+=1
if Hbox == 0: Hbox += 1
Bs = np.min((Hb / Hbox, Wb / Wbox))
if Rs > 1 or Bs<1 or np.random.rand()<0.3: # Resize image and mask to batch size if mask is smaller then batch or if segment bounding box larger then batch image size
h = int(np.max((h * Rs, Hb)))
w = int(np.max((w * Rs, Wb)))
Img = cv2.resize(Img, dsize=(w, h), interpolation=cv2.INTER_LINEAR)
Mask = cv2.resize(Mask.astype(float), dsize=(w, h), interpolation=cv2.INTER_NEAREST)
AnnMap = cv2.resize(AnnMap.astype(float), dsize=(w, h), interpolation=cv2.INTER_NEAREST)
bbox = (np.float32(bbox) * Rs.astype(np.float)).astype(np.int64)
# =======================Crop image to fit batch size===================================================================================
x1 = int(np.floor(bbox[0])) # Bounding box x position
Wbox = int(np.floor(bbox[2])) # Bounding box width
y1 = int(np.floor(bbox[1])) # Bounding box y position
Hbox = int(np.floor(bbox[3])) # Bounding box height
if Wb > Wbox:
Xmax = np.min((w - Wb, x1))
Xmin = np.max((0, x1 - (Wb - Wbox)-1))
else:
Xmin = x1
Xmax = np.min((w - Wb, x1 + (Wbox - Wb)+1))
if Hb > Hbox:
Ymax = np.min((h - Hb, y1))
Ymin = np.max((0, y1 - (Hb - Hbox)-1))
else:
Ymin = y1
Ymax = np.min((h - Hb, y1 + (Hbox - Hb)+1))
if Ymax<=Ymin: y0=Ymin
else: y0 = np.random.randint(low=Ymin, high=Ymax + 1)
if Xmax<=Xmin: x0=Xmin
else: x0 = np.random.randint(low=Xmin, high=Xmax + 1)
# Img[:,:,1]*=Mask
# misc.imshow(Img)
Img = Img[y0:y0 + Hb, x0:x0 + Wb, :]
Mask = Mask[y0:y0 + Hb, x0:x0 + Wb]
AnnMap = AnnMap[y0:y0 + Hb, x0:x0 + Wb]
#------------------------------------------Verify shape match the batch shape----------------------------------------------------------------------------------------
if not (Img.shape[0] == Hb and Img.shape[1] == Wb): Img = cv2.resize(Img, dsize=(Wb, Hb),interpolation=cv2.INTER_LINEAR)
if not (Mask.shape[0] == Hb and Mask.shape[1] == Wb):Mask = cv2.resize(Mask.astype(float), dsize=(Wb, Hb), interpolation=cv2.INTER_NEAREST)
if not (AnnMap.shape[0] == Hb and AnnMap.shape[1] == Wb): AnnMap = cv2.resize(AnnMap.astype(float), dsize=(Wb, Hb),interpolation=cv2.INTER_NEAREST)
#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
return Img,Mask,AnnMap
# misc.imshow(Img)
#################################################Generate Annotaton mask#############################################################################################################333
def GenerateROImask(self, AnnMap,Mask):
x=np.unique(AnnMap)
random.shuffle(x)
ROImask=np.zeros(Mask.shape,dtype=float)
if np.random.rand()<0.05: # Create by random segments number
x=x[:np.random.randint(0,len(x))]
for i in x:
ROImask[AnnMap==i]=1
else: # By size
r=np.random.rand()
for i in x:
ROImask[AnnMap == i] = 1
if ROImask.mean()>r: break
ROImask[Mask>0]=1
return ROImask
#################################################Generate Pointer mask#############################################################################################################333
def GeneratePointermask(self, Mask):
bbox = cv2.boundingRect(Mask.astype(np.uint8))
x1 = int(np.floor(bbox[0])) # Bounding box x position
Wbox = int(np.floor(bbox[2])) # Bounding box width
xmax = np.min([x1 + Wbox+1, Mask.shape[1]])
y1 = int(np.floor(bbox[1])) # Bounding box y position
Hbox = int(np.floor(bbox[3])) # Bounding box height
ymax = np.min([y1 + Hbox+1, Mask.shape[0]])
PointerMask=np.zeros(Mask.shape,dtype=np.float)
if Mask.max()==0:return PointerMask
while(True):
x =np.random.randint(x1,xmax)
y = np.random.randint(y1, ymax)
if Mask[y,x]>0:
PointerMask[y,x]=1
return(PointerMask)
######################################################Augmented mask##################################################################################################################################
def Augment(self,Img,Mask,AnnMap,prob):
if np.random.rand()<0.5: # flip left right
Img=np.fliplr(Img)
Mask = np.fliplr(Mask)
AnnMap = np.fliplr(AnnMap)
if np.random.rand() < 0.1:
Img = np.rot90(Img)
Mask = np.rot90(Mask)
AnnMap = np.rot90(AnnMap)
if np.random.rand()< 0.1: # flip up down
Img=np.flipud(Img)
Mask = np.flipud(Mask)
AnnMap = np.flipud(AnnMap)
if np.random.rand() < 0.4:
Img = Img[..., :: -1]
if np.random.rand() < prob: # resize
r=r2=(0.6 + np.random.rand() * 0.8)
if np.random.rand() < prob*0.3:
r2=(0.65 + np.random.rand() * 0.7)
h = int(Mask.shape[0] * r)
w = int(Mask.shape[1] * r2)
Img = cv2.resize(Img, dsize=(w, h), interpolation=cv2.INTER_LINEAR)
Mask = cv2.resize(Mask.astype(float), dsize=(w, h), interpolation=cv2.INTER_NEAREST)
AnnMap = cv2.resize(AnnMap.astype(float), dsize=(w, h), interpolation=cv2.INTER_NEAREST)
if np.random.rand() < prob: # Dark light
Img = Img * (0.6 + np.random.rand() * 0.7)
Img[Img>255]=255
if np.random.rand() < prob: # GreyScale
Gr=Img.mean(axis=2)
r=np.random.rand()
Img[:, :, 0] = Img[:, :, 0] * r + Gr * (1 - r)
Img[:, :, 1] = Img[:, :, 1] * r + Gr * (1 - r)
Img[:, :, 2] = Img[:, :, 2] * r + Gr * (1 - r)
return Img,Mask,AnnMap
########################################################################################################################################################
# ==========================Read image annotation and data===============================================================================================
def LoadNext(self, batch_pos, Hb=-1, Wb=-1):
# -----------------------------------Image and resize-----------------------------------------------------------------------------------------------------
if self.ClassBalance: # pick with equal class probability
while (True):
CL=np.random.randint(self.NumClasses)
CatSize=len(self.AnnotationByCat[CL])
if CatSize>0: break
Nim = np.random.randint(CatSize)
# print("nim "+str(Nim)+"CL "+str(CL)+" length"+str(len(self.AnnotationByCat[CL])))
Ann=self.AnnotationByCat[CL][Nim]
else: # Pick with equal class probabiliry
Nim = np.random.randint(len(self.AnnotationList))
Ann=self.AnnotationList[Nim]
CatSize=100000000
Img = cv2.imread(Ann["ImageFile"]) # Load Image
Img = Img[..., :: -1]
if (Img.ndim == 2): # If grayscale turn to rgb
Img = np.expand_dims(Img, 3)
Img = np.concatenate([Img, Img, Img], axis=2)
Img = Img[:, :, 0:3] # Get first 3 channels incase there are more
#-------------------------Read annotation--------------------------------------------------------------------------------
Mask = cv2.imread(Ann["MaskFile"],0) # Load mask
AnnMap = cv2.imread(Ann["FullAnnFile"],0) # Load mask
#-------------------------Augment-----------------------------------------------------------------------------------------------
Img,Mask,AnnMap=self.Augment(Img,Mask,AnnMap,np.min([float(1000/CatSize)*0.10+0.03,1]))
#-----------------------------------Crop and resize-----------------------------------------------------------------------------------------------------
if not Hb==-1:
Img, Mask,AnnMap = self.CropResize(Img, Mask, AnnMap, Hb, Wb)
#----------------------------------------------------------------------------------------------------------------------------------
PointerMask=self.GeneratePointermask(Mask)
if np.random.rand()<0.5: ROIMask=self.GenerateROImask(AnnMap,Mask)
else: ROIMask=np.ones(Mask.shape,dtype=float)
#---------------------------------------------------------------------------------------------------------------------------------
self.BPointerMask[batch_pos] = PointerMask
self.BROIMask[batch_pos] = ROIMask
self.BImgs[batch_pos] = Img
self.BSegmentMask[batch_pos] = Mask
self.BIsThing[batch_pos] = Ann["IsThing"]
self.BCatID[batch_pos] = Ann["Class"]
self.BIsVessel[batch_pos] = (Ann["Class"] in self.VesselCats) # Check if category correspond to vessel (glass/bottle...)
# if (Ann["Class"] in self.VesselCats):
# print("333")
############################################################################################################################################################
# Start load batch of images, segment masks, ROI masks, and pointer points for training MultiThreading s
def StartLoadBatch(self):
# =====================Initiate batch=============================================================================================
while True:
Hb = np.random.randint(low=self.MinSize, high=self.MaxSize) # Batch hight
Wb = np.random.randint(low=self.MinSize, high=self.MaxSize) # batch width
if Hb*Wb<self.MaxPixels: break
BatchSize = np.int(np.min((np.floor(self.MaxPixels / (Hb * Wb)), self.MaxBatchSize)))
self.BImgs = np.zeros((BatchSize, Hb, Wb, 3)) # Image
self.BSegmentMask = np.zeros((BatchSize, Hb, Wb)) # Segment mask
self.BROIMask = np.zeros((BatchSize, Hb, Wb)) # ROI region containing the segment
self.BPointerMask = np.zeros((BatchSize, Hb, Wb)) # Random point inside the segment
self.BIsThing = np.zeros((BatchSize))
self.BCatID = np.zeros((BatchSize)) # Segent category
self.BIsVessel = np.zeros((BatchSize)) # Is this an instance of vessel catgory
#====================Start reading data multithreaded===========================================================
self.thread_list = []
for pos in range(BatchSize):
th=threading.Thread(target=self.LoadNext,name="thread"+str(pos),args=(pos,Hb,Wb))
self.thread_list.append(th)
th.start()
self.itr+=BatchSize
##################################################################################################################
def SuffleFileList(self):
random.shuffle(self.FileList)
self.itr = 0
###########################################################################################################
#Wait until the data batch loading started at StartLoadBatch is finished
def WaitLoadBatch(self):
for th in self.thread_list:
th.join()
########################################################################################################################################################################################
def LoadBatch(self):
# Load batch for training (muti threaded run in parallel with the training proccess)
# For training
self.WaitLoadBatch()
Imgs=self.BImgs
SegmentMask=self.BSegmentMask
IsThing=self.BIsThing
CatID=self.BCatID
ROIMask = self.BROIMask
PointerMask = self.BPointerMask
IsVessel=self.BIsVessel
self.StartLoadBatch()
return Imgs, SegmentMask,ROIMask,PointerMask,IsVessel
#Imgs, SegmentMask, ROIMask, PointerMap
############################Load single image data with no augmentation############################################################################################################################################################
def LoadSingle(self, ByClass=False):
print("*************")
print(self.Findx)
if self.Findx==None:
self.Cindx = int(0)
self.Findx = int(0)
self.CindList=np.zeros([len(self.AnnotationByCat)],dtype=int)
self.ClFinished = np.zeros([len(self.AnnotationByCat)],dtype=int)
self.Epoch = int(0)
if ByClass:
while(True):
if self.Cindx>=len(self.AnnotationByCat): self.Cindx=0
if self.CindList[self.Cindx]>=len(self.AnnotationByCat[self.Cindx]):
self.ClFinished[self.Cindx]=1
self.Cindx+=1
if np.mean(self.ClFinished)==1:
self.Cindx = int(0)
self.Findx = int(0)
self.CindList = np.zeros([len(self.AnnotationByCat)], dtype=int)
self.ClFinished = np.zeros([len(self.AnnotationByCat)], dtype=int)
self.Epoch+=1
else:
Ann = self.AnnotationByCat[self.Cindx][self.CindList[self.Cindx]]
self.CindList[self.Cindx]+=1
self.Cindx+=1
break
else: # Pick with equal class probabiliry
| |
Constraint(expr=m.x1516*(118.743516912 + m.x2036) - m.x3954 == 0)
m.c1517 = Constraint(expr=m.x1517*(54.5829056 + m.x2037) - m.x3955 == 0)
m.c1518 = Constraint(expr=m.x1518*(22.880176696 + m.x2038) - m.x3956 == 0)
m.c1519 = Constraint(expr=m.x1519*(10.749094 + m.x2039) - m.x3957 == 0)
m.c1520 = Constraint(expr=m.x1520*(85.0133724208126 + m.x1997) - m.x3958 == 0)
m.c1521 = Constraint(expr=m.x1521*(108.052970594387 + m.x1998) - m.x3959 == 0)
m.c1522 = Constraint(expr=m.x1522*(9.3711459385556 + m.x1999) - m.x3960 == 0)
m.c1523 = Constraint(expr=m.x1523*(10.69589 + m.x2000) - m.x3961 == 0)
m.c1524 = Constraint(expr=m.x1524*(17.932791400734 + m.x2001) - m.x3962 == 0)
m.c1525 = Constraint(expr=m.x1525*(88.805712423724 + m.x2002) - m.x3963 == 0)
m.c1526 = Constraint(expr=m.x1526*(67.92235 + m.x2003) - m.x3964 == 0)
m.c1527 = Constraint(expr=m.x1527*(17.52572 + m.x2004) - m.x3965 == 0)
m.c1528 = Constraint(expr=m.x1528*(75.509965 + m.x2005) - m.x3966 == 0)
m.c1529 = Constraint(expr=m.x1529*(215.1945909789 + m.x2007) - m.x3967 == 0)
m.c1530 = Constraint(expr=m.x1530*(17.9818975244236 + m.x2008) - m.x3968 == 0)
m.c1531 = Constraint(expr=m.x1531*(82.3846155412095 + m.x2009) - m.x3969 == 0)
m.c1532 = Constraint(expr=m.x1532*(15.77529785051 + m.x2010) - m.x3970 == 0)
m.c1533 = Constraint(expr=m.x1533*(20.585074453376 + m.x2011) - m.x3971 == 0)
m.c1534 = Constraint(expr=m.x1534*(17.73824148824 + m.x2012) - m.x3972 == 0)
m.c1535 = Constraint(expr=m.x1535*(9.7831921864888 + m.x2013) - m.x3973 == 0)
m.c1536 = Constraint(expr=m.x1536*(58.3304919073372 + m.x2014) - m.x3974 == 0)
m.c1537 = Constraint(expr=m.x1537*(70.841638270004 + m.x2015) - m.x3975 == 0)
m.c1538 = Constraint(expr=m.x1538*(2.457537796 + m.x2016) - m.x3976 == 0)
m.c1539 = Constraint(expr=m.x1539*(12.908328297966 + m.x2017) - m.x3977 == 0)
m.c1540 = Constraint(expr=m.x1540*(25.5807469993058 + m.x2018) - m.x3978 == 0)
m.c1541 = Constraint(expr=m.x1541*(29.0537838075122 + m.x2019) - m.x3979 == 0)
m.c1542 = Constraint(expr=m.x1542*(11.179067059 + m.x2020) - m.x3980 == 0)
m.c1543 = Constraint(expr=m.x1543*(16.47769975 + m.x2021) - m.x3981 == 0)
m.c1544 = Constraint(expr=m.x1544*(10.8297732214437 + m.x2022) - m.x3982 == 0)
m.c1545 = Constraint(expr=m.x1545*(17.3365643030813 + m.x2025) - m.x3983 == 0)
m.c1546 = Constraint(expr=m.x1546*(277.48319 + m.x2030) - m.x3984 == 0)
m.c1547 = Constraint(expr=m.x1547*(20.035404 + m.x2033) - m.x3985 == 0)
m.c1548 = Constraint(expr=m.x1548*(32.373595 + m.x2034) - m.x3986 == 0)
m.c1549 = Constraint(expr=m.x1549*(46.195028 + m.x2035) - m.x3987 == 0)
m.c1550 = Constraint(expr=m.x1550*(118.743516912 + m.x2036) - m.x3988 == 0)
m.c1551 = Constraint(expr=m.x1551*(54.5829056 + m.x2037) - m.x3989 == 0)
m.c1552 = Constraint(expr=m.x1552*(22.880176696 + m.x2038) - m.x3990 == 0)
m.c1553 = Constraint(expr=m.x1553*(85.0133724208126 + m.x1997) - m.x3991 == 0)
m.c1554 = Constraint(expr=m.x1554*(108.052970594387 + m.x1998) - m.x3992 == 0)
m.c1555 = Constraint(expr=m.x1555*(9.3711459385556 + m.x1999) - m.x3993 == 0)
m.c1556 = Constraint(expr=m.x1556*(10.69589 + m.x2000) - m.x3994 == 0)
m.c1557 = Constraint(expr=m.x1557*(17.932791400734 + m.x2001) - m.x3995 == 0)
m.c1558 = Constraint(expr=m.x1558*(88.805712423724 + m.x2002) - m.x3996 == 0)
m.c1559 = Constraint(expr=m.x1559*(67.92235 + m.x2003) - m.x3997 == 0)
m.c1560 = Constraint(expr=m.x1560*(17.52572 + m.x2004) - m.x3998 == 0)
m.c1561 = Constraint(expr=m.x1561*(75.509965 + m.x2005) - m.x3999 == 0)
m.c1562 = Constraint(expr=m.x1562*(215.1945909789 + m.x2007) - m.x4000 == 0)
m.c1563 = Constraint(expr=m.x1563*(17.9818975244236 + m.x2008) - m.x4001 == 0)
m.c1564 = Constraint(expr=m.x1564*(82.3846155412095 + m.x2009) - m.x4002 == 0)
m.c1565 = Constraint(expr=m.x1565*(15.77529785051 + m.x2010) - m.x4003 == 0)
m.c1566 = Constraint(expr=m.x1566*(20.585074453376 + m.x2011) - m.x4004 == 0)
m.c1567 = Constraint(expr=m.x1567*(17.73824148824 + m.x2012) - m.x4005 == 0)
m.c1568 = Constraint(expr=m.x1568*(9.7831921864888 + m.x2013) - m.x4006 == 0)
m.c1569 = Constraint(expr=m.x1569*(58.3304919073372 + m.x2014) - m.x4007 == 0)
m.c1570 = Constraint(expr=m.x1570*(70.841638270004 + m.x2015) - m.x4008 == 0)
m.c1571 = Constraint(expr=m.x1571*(2.457537796 + m.x2016) - m.x4009 == 0)
m.c1572 = Constraint(expr=m.x1572*(12.908328297966 + m.x2017) - m.x4010 == 0)
m.c1573 = Constraint(expr=m.x1573*(25.5807469993058 + m.x2018) - m.x4011 == 0)
m.c1574 = Constraint(expr=m.x1574*(29.0537838075122 + m.x2019) - m.x4012 == 0)
m.c1575 = Constraint(expr=m.x1575*(11.179067059 + m.x2020) - m.x4013 == 0)
m.c1576 = Constraint(expr=m.x1576*(40.593786 + m.x2029) - m.x4014 == 0)
m.c1577 = Constraint(expr=m.x1577*(277.48319 + m.x2030) - m.x4015 == 0)
m.c1578 = Constraint(expr=m.x1578*(254.79773 + m.x2031) - m.x4016 == 0)
m.c1579 = Constraint(expr=m.x1579*(20.035404 + m.x2033) - m.x4017 == 0)
m.c1580 = Constraint(expr=m.x1580*(32.373595 + m.x2034) - m.x4018 == 0)
m.c1581 = Constraint(expr=m.x1581*(46.195028 + m.x2035) - m.x4019 == 0)
m.c1582 = Constraint(expr=m.x1582*(118.743516912 + m.x2036) - m.x4020 == 0)
m.c1583 = Constraint(expr=m.x1583*(54.5829056 + m.x2037) - m.x4021 == 0)
m.c1584 = Constraint(expr=m.x1584*(22.880176696 + m.x2038) - m.x4022 == 0)
m.c1585 = Constraint(expr=m.x1585*(10.749094 + m.x2039) - m.x4023 == 0)
m.c1586 = Constraint(expr=m.x1586*(85.0133724208126 + m.x1997) - m.x4024 == 0)
m.c1587 = Constraint(expr=m.x1587*(108.052970594387 + m.x1998) - m.x4025 == 0)
m.c1588 = Constraint(expr=m.x1588*(9.3711459385556 + m.x1999) - m.x4026 == 0)
m.c1589 = Constraint(expr=m.x1589*(10.69589 + m.x2000) - m.x4027 == 0)
m.c1590 = Constraint(expr=m.x1590*(17.932791400734 + m.x2001) - m.x4028 == 0)
m.c1591 = Constraint(expr=m.x1591*(88.805712423724 + m.x2002) - m.x4029 == 0)
m.c1592 = Constraint(expr=m.x1592*(67.92235 + m.x2003) - m.x4030 == 0)
m.c1593 = Constraint(expr=m.x1593*(17.52572 + m.x2004) - m.x4031 == 0)
m.c1594 = Constraint(expr=m.x1594*(75.509965 + m.x2005) - m.x4032 == 0)
m.c1595 = Constraint(expr=m.x1595*(68.860513 + m.x2006) - m.x4033 == 0)
m.c1596 = Constraint(expr=m.x1596*(215.1945909789 + m.x2007) - m.x4034 == 0)
m.c1597 = Constraint(expr=m.x1597*(17.9818975244236 + m.x2008) - m.x4035 == 0)
m.c1598 = Constraint(expr=m.x1598*(82.3846155412095 + m.x2009) - m.x4036 == 0)
m.c1599 = Constraint(expr=m.x1599*(15.77529785051 + m.x2010) - m.x4037 == 0)
m.c1600 = Constraint(expr=m.x1600*(20.585074453376 + m.x2011) - m.x4038 == 0)
m.c1601 = Constraint(expr=m.x1601*(17.73824148824 + m.x2012) - m.x4039 == 0)
m.c1602 = Constraint(expr=m.x1602*(9.7831921864888 + m.x2013) - m.x4040 == 0)
m.c1603 = Constraint(expr=m.x1603*(58.3304919073372 + m.x2014) - m.x4041 == 0)
m.c1604 = Constraint(expr=m.x1604*(70.841638270004 + m.x2015) - m.x4042 == 0)
m.c1605 = Constraint(expr=m.x1605*(2.457537796 + m.x2016) - m.x4043 == 0)
m.c1606 = Constraint(expr=m.x1606*(12.908328297966 + m.x2017) - m.x4044 == 0)
m.c1607 = Constraint(expr=m.x1607*(25.5807469993058 + m.x2018) - m.x4045 == 0)
m.c1608 = Constraint(expr=m.x1608*(29.0537838075122 + m.x2019) - m.x4046 == 0)
m.c1609 = Constraint(expr=m.x1609*(11.179067059 + m.x2020) - m.x4047 == 0)
m.c1610 = Constraint(expr=m.x1610*(16.47769975 + m.x2021) - m.x4048 == 0)
m.c1611 = Constraint(expr=m.x1611*(10.8297732214437 + m.x2022) - m.x4049 == 0)
m.c1612 = Constraint(expr=m.x1612*(29.39924999665 + m.x2023) - m.x4050 == 0)
m.c1613 = Constraint(expr=m.x1613*(9.34536262823 + m.x2024) - m.x4051 == 0)
m.c1614 = Constraint(expr=m.x1614*(17.3365643030813 + m.x2025) - m.x4052 == 0)
m.c1615 = Constraint(expr=m.x1615*(48.547749096 + m.x2026) - m.x4053 == 0)
m.c1616 = Constraint(expr=m.x1616*(149.23057111 + m.x2027) - m.x4054 == 0)
m.c1617 = Constraint(expr=m.x1617*(27.47191645805 + m.x2028) - m.x4055 == 0)
m.c1618 = Constraint(expr=m.x1618*(40.593786 + m.x2029) - m.x4056 == 0)
m.c1619 = Constraint(expr=m.x1619*(277.48319 + m.x2030) - m.x4057 == 0)
m.c1620 = Constraint(expr=m.x1620*(254.79773 + m.x2031) - m.x4058 == 0)
m.c1621 = Constraint(expr=m.x1621*(117.202966 + m.x2032) - m.x4059 == 0)
m.c1622 = Constraint(expr=m.x1622*(20.035404 + m.x2033) - m.x4060 == 0)
m.c1623 = Constraint(expr=m.x1623*(32.373595 + m.x2034) - m.x4061 == 0)
m.c1624 = Constraint(expr=m.x1624*(46.195028 + m.x2035) - m.x4062 == 0)
m.c1625 = Constraint(expr=m.x1625*(118.743516912 + m.x2036) - m.x4063 == 0)
m.c1626 = Constraint(expr=m.x1626*(54.5829056 + m.x2037) - m.x4064 == 0)
m.c1627 = Constraint(expr=m.x1627*(22.880176696 + m.x2038) - m.x4065 == 0)
m.c1628 = Constraint(expr=m.x1628*(10.749094 + m.x2039) - m.x4066 == 0)
m.c1629 = Constraint(expr=m.x1629*(133.671263941387 + m.x2082) - m.x4067 == 0)
m.c1630 = Constraint(expr=m.x1630*(115.737915970578 + m.x2083) - m.x4068 == 0)
m.c1631 = Constraint(expr=m.x1631*(96.8913016661464 + m.x2084) - m.x4069 == 0)
m.c1632 = Constraint(expr=m.x1632*(28.3983640089884 + m.x2086) - m.x4070 == 0)
m.c1633 = Constraint(expr=m.x1633*(15.7478032090063 + m.x2087) - m.x4071 == 0)
m.c1634 = Constraint(expr=m.x1634*(175.844560388705 + m.x2094) - m.x4072 == 0)
m.c1635 = Constraint(expr=m.x1635*(8.00892516581441 + m.x2097) - m.x4073 == 0)
m.c1636 = Constraint(expr=m.x1636*(97.3173040663597 + m.x2098) - m.x4074 == 0)
m.c1637 = Constraint(expr=m.x1637*(177.636006160939 + m.x2101) - m.x4075 == 0)
m.c1638 = Constraint(expr=m.x1638*(373.780859160202 + m.x2102) - m.x4076 == 0)
m.c1639 = Constraint(expr=m.x1639*(133.671263941387 + m.x2082) - m.x4077 == 0)
m.c1640 = Constraint(expr=m.x1640*(115.737915970578 + m.x2083) - m.x4078 == 0)
m.c1641 = Constraint(expr=m.x1641*(96.8913016661464 + m.x2084) - m.x4079 == 0)
m.c1642 = Constraint(expr=m.x1642*(130.803845459431 + m.x2085) - m.x4080 == 0)
m.c1643 = Constraint(expr=m.x1643*(28.3983640089884 + m.x2086) - m.x4081 == 0)
m.c1644 = Constraint(expr=m.x1644*(15.7478032090063 + m.x2087) - m.x4082 == 0)
m.c1645 = Constraint(expr=m.x1645*(8.34516172547079 + m.x2088) - m.x4083 == 0)
m.c1646 = Constraint(expr=m.x1646*(11.4163569396134 + m.x2089) - m.x4084 == 0)
m.c1647 = Constraint(expr=m.x1647*(175.844560388705 + m.x2094) - m.x4085 == 0)
m.c1648 = Constraint(expr=m.x1648*(8.00892516581441 + m.x2097) - m.x4086 == 0)
m.c1649 = Constraint(expr=m.x1649*(97.3173040663597 + m.x2098) - m.x4087 == 0)
m.c1650 = Constraint(expr=m.x1650*(177.636006160939 + m.x2101) - m.x4088 == 0)
m.c1651 = Constraint(expr=m.x1651*(373.780859160202 + m.x2102) - m.x4089 == 0)
m.c1652 = Constraint(expr=m.x1652*(133.671263941387 + m.x2082) - m.x4090 == 0)
m.c1653 = Constraint(expr=m.x1653*(115.737915970578 + m.x2083) - m.x4091 == 0)
m.c1654 = Constraint(expr=m.x1654*(96.8913016661464 + m.x2084) - m.x4092 == 0)
m.c1655 = Constraint(expr=m.x1655*(130.803845459431 + m.x2085) - m.x4093 == 0)
m.c1656 = Constraint(expr=m.x1656*(28.3983640089884 + m.x2086) - m.x4094 == 0)
m.c1657 = Constraint(expr=m.x1657*(15.7478032090063 + m.x2087) - m.x4095 == 0)
m.c1658 = Constraint(expr=m.x1658*(8.34516172547079 + m.x2088) - m.x4096 == 0)
m.c1659 = Constraint(expr=m.x1659*(11.4163569396134 + m.x2089) - m.x4097 == 0)
m.c1660 = Constraint(expr=m.x1660*(6.95367819652136 + m.x2091) - m.x4098 == 0)
m.c1661 = Constraint(expr=m.x1661*(68.611061605179 + m.x2092) - m.x4099 == 0)
m.c1662 = Constraint(expr=m.x1662*(175.844560388705 + m.x2094) - m.x4100 == 0)
m.c1663 = Constraint(expr=m.x1663*(8.00892516581441 + m.x2097) - m.x4101 == 0)
m.c1664 = Constraint(expr=m.x1664*(97.3173040663597 + m.x2098) - m.x4102 == 0)
m.c1665 = Constraint(expr=m.x1665*(177.636006160939 + m.x2101) - m.x4103 == 0)
m.c1666 = Constraint(expr=m.x1666*(373.780859160202 + m.x2102) - m.x4104 == 0)
m.c1667 = Constraint(expr=m.x1667*(704.195604713805 + m.x2103) - m.x4105 == 0)
m.c1668 = Constraint(expr=m.x1668*(95.28044 + m.x2106) - m.x4106 == 0)
m.c1669 = Constraint(expr=m.x1669*(158.856788 + m.x2107) - m.x4107 == 0)
m.c1670 = Constraint(expr=m.x1670*(133.671263941387 + m.x2082) - m.x4108 == 0)
m.c1671 = Constraint(expr=m.x1671*(115.737915970578 + m.x2083) - m.x4109 == 0)
m.c1672 = Constraint(expr=m.x1672*(96.8913016661464 + m.x2084) - m.x4110 == 0)
m.c1673 = Constraint(expr=m.x1673*(130.803845459431 + m.x2085) - m.x4111 == 0)
m.c1674 = Constraint(expr=m.x1674*(28.3983640089884 + m.x2086) - m.x4112 == 0)
m.c1675 = Constraint(expr=m.x1675*(15.7478032090063 + m.x2087) - m.x4113 == 0)
m.c1676 = | |
"""
test_scope component that checks for errors related to yields in async code.
This does the following three checks:
- yielding the same thing more than once in the same yield
- yielding an async task in a non-async function
- yielding before using the result of the previous yield
"""
import ast
from ast_decompiler import decompile
import asynq
import contextlib
from dataclasses import dataclass, field
import qcore
import itertools
import logging
from typing import (
Any,
Dict,
Set,
Callable,
ContextManager,
Iterator,
List,
Optional,
Sequence,
TYPE_CHECKING,
Tuple,
)
from .asynq_checker import AsyncFunctionKind
from .error_code import ErrorCode
from .value import Value, KnownValue, UnboundMethodValue, UNINITIALIZED_VALUE
from .analysis_lib import get_indentation, get_line_range_for_node
from .node_visitor import Replacement
if TYPE_CHECKING:
from .name_check_visitor import NameCheckVisitor
@dataclass
class YieldInfo:
"""Wrapper class for yield nodes."""
yield_node: ast.Yield
statement_node: ast.stmt
lines: List[str]
line_range: List[int] = field(init=False)
def __post_init__(self) -> None:
self.line_range = get_line_range_for_node(self.statement_node, self.lines)
def is_assign_or_expr(self) -> bool:
if not isinstance(self.statement_node, (ast.Expr, ast.Assign)):
return False
return self.statement_node.value is self.yield_node
def get_indentation(self) -> int:
return get_indentation(self.lines[self.statement_node.lineno - 1])
def target_and_value(self) -> Tuple[List[ast.AST], List[ast.AST]]:
"""Returns a pair of a list of target nodes and a list of value nodes."""
assert self.yield_node.value is not None
if isinstance(self.statement_node, ast.Assign):
# this branch is for assign statements
# e.g. x = yield y.asynq()
# _ = yield async_fn.asynq()
if not isinstance(self.statement_node.targets[0], ast.Tuple):
# target is one entity
return ([self.statement_node.targets[0]], [self.yield_node.value])
# target is a tuple
elif (
isinstance(self.yield_node.value, ast.Call)
and isinstance(self.yield_node.value.func, ast.Name)
and self.yield_node.value.func.id == "tuple"
and isinstance(self.yield_node.value.args[0], ast.Tuple)
):
# value is a call to tuple()
# e.g. x, y = yield tuple((a.asynq(), b.asynq()))
# in this case we remove the call to tuple and return
# the plain elements of the tuple but we remove the surrounding braces
return (
self.statement_node.targets[0].elts,
self.yield_node.value.args[0].elts,
)
elif isinstance(self.yield_node.value, ast.Tuple):
# value is a tuple too, return both targets and values as such
# but get rid of the parenthesis
return (self.statement_node.targets[0].elts, self.yield_node.value.elts)
# target is a tuple but only one value
# e.g. x, y = yield f.asynq()
# in this case we'll wrap the target with () so that they
# can be combined with another yield
return ([self.statement_node.targets[0]], [self.yield_node.value])
# not an assign statement
# e.g. yield x.asynq()
if not isinstance(self.yield_node.value, ast.Tuple):
# single entity yielded
return ([ast.Name(id="_", ctx=ast.Store())], [self.yield_node.value])
# multiple values yielded e.g. yield x.asynq(), z.asynq()
return (
[ast.Name(id="_", ctx=ast.Store()) for _ in self.yield_node.value.elts],
self.yield_node.value.elts,
)
class VarnameGenerator:
"""Class to generate a unique variable name from an AST node.
Split off into a separate class for ease of testing.
To construct this class, pass in a function that, given a name, returns whether it is available.
Call .get(node) on the instance to get a variable name for an AST node.
"""
def __init__(self, is_available: Callable[[str], bool]) -> None:
self.is_available = is_available
def get(self, node: ast.AST) -> str:
"""Returns a unique variable name for this node."""
candidate = self._get_candidate(node).lstrip("_")
return self._ensure_unique(candidate)
def _get_candidate(self, node: ast.AST) -> str:
if isinstance(node, ast.Name):
camel_cased = _camel_case_to_snake_case(node.id)
if camel_cased != node.id:
return camel_cased
else:
return f"{node.id}_result"
elif isinstance(node, ast.Attribute):
if node.attr == "async" or node.attr == "asynq":
return self._get_candidate(node.value)
elif node.attr.endswith("_async"):
# probably a method call like .get_async
return self._get_candidate(node.value)
else:
varname = node.attr.lstrip("_")
for prefix in ("render_", "get_"):
if varname.startswith(prefix):
return varname[len(prefix) :]
else:
return varname
elif isinstance(node, ast.Call):
if (
isinstance(node.func, ast.Attribute)
and isinstance(node.func.value, ast.Name)
and node.func.value.id == "async_call"
and node.args
):
return self._get_candidate(node.args[0])
return self._get_candidate(node.func)
else:
return "autogenerated_var"
def _ensure_unique(self, varname: str) -> str:
"""Ensures an autogenerated variable name is unique by appending numbers to it."""
if self.is_available(varname):
return varname
else:
for i in itertools.count(2):
next_varname = f"{varname}{i}"
if self.is_available(next_varname):
return next_varname
assert False, "unreachable"
@dataclass
class YieldChecker:
visitor: "NameCheckVisitor"
variables_from_yield_result: Dict[str, bool] = field(default_factory=dict)
in_yield_result_assignment: bool = False
in_non_async_yield: bool = False
last_yield_in_aug_assign: bool = False
previous_yield: Optional[ast.Yield] = None
statement_for_previous_yield: Optional[ast.stmt] = None
used_varnames: Set[str] = field(default_factory=set)
added_decorator: bool = False
@contextlib.contextmanager
def check_yield(
self, node: ast.Yield, current_statement: ast.stmt
) -> Iterator[None]:
assert current_statement is not None
if self.visitor.async_kind == AsyncFunctionKind.normal:
self._check_for_duplicate_yields(node, self.visitor.current_statement)
in_non_async_yield = self.visitor.async_kind == AsyncFunctionKind.non_async
with qcore.override(self, "in_non_async_yield", in_non_async_yield):
yield
if self.visitor.async_kind == AsyncFunctionKind.normal:
self._maybe_show_unnecessary_yield_error(node, current_statement)
if self.last_yield_in_aug_assign:
self._maybe_show_unnecessary_yield_error(node, current_statement)
self.last_yield_in_aug_assign = self._is_augassign_target(node)
self.variables_from_yield_result = {}
self.previous_yield = node
self.statement_for_previous_yield = current_statement
# Unnecessary yield checking
def check_yield_result_assignment(self, in_yield: bool) -> ContextManager[None]:
return qcore.override(self, "in_yield_result_assignment", in_yield)
def record_assignment(self, name: str) -> None:
if self.in_yield_result_assignment:
self.variables_from_yield_result[name] = False
def record_usage(self, name: str, node: ast.AST) -> None:
if name in self.variables_from_yield_result:
if self._is_augassign_target(node):
return
self.variables_from_yield_result[name] = True
def reset_yield_checks(self) -> None:
"""Resets variables for the unnecessary yield check.
This is done while visiting if statements to prevent the unnecessary yield check from
concluding that yields in one branch of the if are unused.
"""
self.variables_from_yield_result = {}
self.last_yield_in_aug_assign = False
# Missing @async detection
def record_call(self, value: Value, node: ast.Call) -> None:
if (
not self.in_non_async_yield
or not self._is_async_call(value, node.func)
or self.added_decorator
):
return
# prevent ourselves from adding the decorator to the same function multiple times
self.added_decorator = True
func_node = self.visitor.node_context.nearest_enclosing(ast.FunctionDef)
lines = self.visitor._lines()
# this doesn't handle decorator order, it just adds @asynq() right before the def
i = func_node.lineno - 1
def_line = lines[i]
indentation = len(def_line) - len(def_line.lstrip())
replacement = Replacement([i + 1], [" " * indentation + "@asynq()\n", def_line])
self.visitor.show_error(
node, error_code=ErrorCode.missing_asynq, replacement=replacement
)
# Internal part
def _is_augassign_target(self, node: ast.AST) -> bool:
return (
isinstance(self.visitor.current_statement, ast.AugAssign)
and node is self.visitor.current_statement.value
)
def _is_async_call(self, value: Value, node: ast.AST) -> bool:
# calls to something.asynq are always async
if isinstance(node, ast.Attribute) and (
node.attr in ("async", "asynq", "future") or node.attr.endswith("_async")
):
return True
if isinstance(value, UnboundMethodValue):
obj = value.get_method()
elif isinstance(value, KnownValue):
obj = value.val
else:
return False
return self.is_async_fn(obj)
def _maybe_show_unnecessary_yield_error(
self, node: ast.Yield, current_statement: ast.stmt
) -> None:
if isinstance(current_statement, ast.Expr) and current_statement.value is node:
return
current_yield_result_vars = self.variables_from_yield_result
# check if we detected anything being used out of the last yield
self.visitor.log(logging.DEBUG, "Yield result", current_yield_result_vars)
if len(current_yield_result_vars) > 0:
if not any(current_yield_result_vars.values()):
unused = list(current_yield_result_vars.keys())
self.show_unnecessary_yield_error(unused, node, current_statement)
def _check_for_duplicate_yields(
self, node: ast.Yield, current_statement: ast.stmt
) -> None:
if not isinstance(node.value, ast.Tuple) or len(node.value.elts) < 2:
return
duplicate_indices = {} # index to first index
seen = {} # ast.dump result to index
for i, member in enumerate(node.value.elts):
# identical AST nodes don't compare equally, so just stringify them for comparison
code = ast.dump(member)
if code in seen:
duplicate_indices[i] = seen[code]
else:
seen[code] = i
if not duplicate_indices:
return
new_members = [
elt for i, elt in enumerate(node.value.elts) if i not in duplicate_indices
]
if len(new_members) == 1:
new_value = new_members[0]
else:
new_value = ast.Tuple(elts=new_members)
new_yield_node = ast.Yield(value=new_value)
if isinstance(current_statement, ast.Expr) and current_statement.value is node:
new_nodes = [ast.Expr(value=new_yield_node)]
elif (
isinstance(current_statement, ast.Assign)
and current_statement.value is node
):
if (
len(current_statement.targets) != 1
or not isinstance(current_statement.targets[0], ast.Tuple)
or len(current_statement.targets[0].elts) != len(node.value.elts)
):
new_nodes = None
else:
new_targets = []
# these are for cases where we do something like
# a, b = yield f.asynq(), f.asynq()
# we turn this into
# a = yield f.asynq()
# b = a
extra_nodes = []
assignment_targets = current_statement.targets[0].elts
for i, target in enumerate(assignment_targets):
if i not in duplicate_indices:
new_targets.append(target)
elif not (isinstance(target, ast.Name) and target.id == "_"):
extra_nodes.append(
ast.Assign(
targets=[target],
value=assignment_targets[duplicate_indices[i]],
)
)
if len(new_targets) == 1:
new_target = new_targets[0]
else:
new_target = ast.Tuple(elts=new_targets)
new_assign = ast.Assign(targets=[new_target], value=new_yield_node)
new_nodes = [new_assign] + extra_nodes
else:
new_nodes = None
if new_nodes is not None:
lines_to_delete = self._lines_of_node(node)
indent = self._indentation_of_node(current_statement)
new_code = "".join(
decompile(node, starting_indentation=indent) for node in new_nodes
)
new_lines = [line + "\n" for line in new_code.splitlines()]
replacement = Replacement(lines_to_delete, new_lines)
else:
replacement = None
self.visitor.show_error(
node, error_code=ErrorCode.duplicate_yield, replacement=replacement
)
def show_unnecessary_yield_error(
self, unused: Sequence[object], node: ast.Yield, current_statement: ast.stmt
) -> None:
if not unused:
message = "Unnecessary yield: += assignments can be combined"
elif len(unused) == 1:
message = "Unnecessary yield: %s was not used before this yield" % (
unused[0],
)
else:
unused_str = ", ".join(map(str, unused))
message = f"Unnecessary yield: | |
value**(0.5)
xleg.append('%s\n%.2f'%(k,value))
ind = np.arange(len(v))
k = 0
p = 0
c = 0
sindx = 0
cv = ColorConverter()
rects1 = list()
rects2 = list()
if (len(v)==2):
pass
for i in range(len(v)):
ind[i]=k
col = colors[c]
rects = self.mpl.axes.bar(k, v[i],color=cv.to_rgb(col))
rects2.append(rects)
k = k+1
p = p+1
if (p==shapes[sindx]):
p = 0
k = k+1
c = c+1
sindx = sindx+1
if (p == 0):
rects1.append(rects)
xmax = int(k-1)
if (len(v)==0):
v = [0,1]
xmax = 1
ymin = min(v)
ymax = max(v)
if (ymin > 0):
ymin = 0
if (ymax < 0):
ymax = 0
self.mpl.axes.axis([0, xmax, ymin*1.05,ymax*1.15])
self.mpl.axes.set_xlabel('Sensoren')
self.mpl.axes.set_ylabel('F,T [N,Nm]')
self.mpl.axes.grid()
self.mpl.axes.legend(rects1,xleg,bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
for i in range(len(rects2)):
rect=rects2[i][0]
text = xtext[i]
height = rect.get_height()
if (v[i] < 0):
height = 0
self.mpl.axes.text(rect.get_x()+rect.get_width()/2., 1.05*height, text,ha='center', va='bottom')
self.mpl.draw()
class Gui(QMainWindow, pymbsMainWindow):
'''
Create the user interface with sliders according to genCoords
'''
def __init__(self, grList, graph, modelName, state, options, **kwargs):
QDialog.__init__(self)
if not grList:
raise PyMbsError('Cannot show system. There are no visualisation '\
'objects defined. Call <addVisualisation.xyz()> '\
'of your MbsSystem-instance to add 3d objects '\
'representing the bodies of your mbs.')
# check and set user's gui options
assert type(options) is dict
self.options = {'qFlexScaling':20,
'qTransRange' :[-3, 3],
'qRotRange' :[-3.14, 3.14]}
for key, val in options.items():
if key not in self.options:
print('Warning: unrecognized key "%s" in options dict' % key)
continue
if key == 'qFlexScaling':
assert isinstance(val, (int, float))
assert val >= 1
elif key in ('qTransRange', 'qRotRange'):
assert isinstance(val, (list, tuple))
assert len(val) == 2
assert val[0] < val[1]
if abs(val[0] > 10) or abs(val[1] > 10):
print('Info: Slider range is quite large. ' \
'Did you use SI units [m, rad]?.')
self.options.update(options)
# default values
self.AAFrames = 0
self.cammpos = None
self.focuspos = None
self.hasFlexibleBodies = False
# timer to update opengl scene periodically
self.updateSceneTimer = QTimer()
self.updateSceneTimer.setInterval(16)
self.updateSceneTimer.timeout.connect(self.updateScene)
# Parse kwargs
for key, value in list(kwargs.items()):
assert( isinstance(key, str) )
# Try Keys
if (key.lower() == 'aaframes'):
assert( isinstance(value, int) )
self.AAFrames = value
elif (key.lower() == 'savetofile'):
assert( isinstance(value, str))
self.saveGraphinfo(value,grList)
else:
print('GUI: Unrecognized Key: "%s"'%key)
# Set up main window and reset button
self.setupMainWindow(self, self.AAFrames)
self.modelName = modelName
self.setWindowTitle('pymbs %s - %s' % (pymbs_VERSION,modelName))
# Obtain state and inital values
self.graph = graph
self.state = state
# Object to draw sensor values with matplotlib
self.sensorsWindow = None
# get number of generalised coords
q = self.graph.getVariable('q')
q_shape = q.shape()
if q_shape:
self.nq = q_shape[0]
else:
self.nq = 1
self.qScaling = [1]*self.nq
# get inital values and start timer to update scene, track q changes
initVals = self.graph.getinitVal(q)
self.q = initVals
self.qChanged = True
self.updateSceneTimer.start()
# Create sliders for genCoords
self.sliders = []
for i in range(self.nq):
slider = LabeledSlider()
qName = str(state.q[i])
slider.setLabelText(qName)
slider.setOrientation(Qt.Horizontal)
# set slider range depending on joint type
if ('_Tx' in qName) or ('_Ty' in qName) or ('_Tz' in qName):
lower, upper = self.options['qTransRange']
slider.setLimits(int(lower*1000), int(upper*1000))
slider.scale = 1000.
elif ('_Rx' in qName) or ('_Ry' in qName) or ('_Rz' in qName):
lower, upper = self.options['qRotRange']
slider.setLimits(int(lower*100), int(upper*100))
slider.scale = 100.
elif 'flexible' in qName:
slider.setLimits(-100,100)
slider.scale = 100.
self.hasFlexibleBodies = True
else:
print('Info: could not determine dof of joint "%s"' % i)
slider.setLimits(-500,500)
slider.scale = 100.
init = float(str(initVals[i]))
slider.setInitVal(init)
slider.slider.setValue(int(init)) # TODO was float, requires int now
self.kintestSliderGroupLayout.addWidget(slider)
self.sliders.append(slider)
# finalize scroll area layout
#self.kintestSliderGroupLayout.addStretch(1.0) # TODO requires int
self.kintestScrollArea.setWidget(self.kintestSliderGroup)
# create a slider to scale flexible bodies state
if self.hasFlexibleBodies:
initVal = self.options['qFlexScaling']
self.qScalingSlider = LabeledSlider(self.tabSimulation)
self.qScalingSlider.setOrientation(Qt.Horizontal)
self.qScalingSlider.name = 'q_flexible_scale'
self.qScalingSlider.setLimits(10, max(2*10*initVal,1000))
self.qScalingSlider.scale = 10.
self.qScalingSlider.setInitVal(initVal)
self.qScalingSlider.slider.setValue(initVal*10)
self.simulationLayout.insertWidget(3, self.qScalingSlider)
# create sliders for inputs
self.inputs = self.graph.getVariables(VarKind.Input)
self.inputSliders = []
for i in range(len(self.inputs)):
shape = self.graph.getShape(self.inputs[i])
if self.graph.getShape(self.inputs[i]) != tuple() :
continue # TODO Nur Workaround, VektorenInputs müssen noch implementiert werden!
slider = LabeledSlider()
slider.setLabelText(str(self.inputs[i]))
slider.setOrientation(Qt.Horizontal)
slider.setLimits(-500,500)
slider.scale = 100.
init = float(str(self.graph.getinitVal(self.inputs[i])))
slider.setInitVal(init)
slider.slider.setValue(init)
self.simulationSliderGroupLayout.addWidget(slider)
self.inputSliders.append(slider)
# finalize scroll area layout
#self.simulationSliderGroupLayout.addStretch(1.0) # TODO requires int
self.simulationScrollArea.setWidget(self.simulationSliderGroup)
# import generated files
# insert tempDir in first place, so that it is searched first
# we had problems if there was a *_visual in the current directory
sys.path.insert(0, tempfile.gettempdir())
# import generated der_state_file
self.mod_der_state = None
self.mod_der_state_setInputs = None
try:
der_state_file = __import__('%s_der_state'%self.modelName, globals(), locals(), [])
self.mod_der_state = getattr(der_state_file,'%s_der_state'%self.modelName)
if hasattr(der_state_file,'%s_setInputs'%self.modelName):
self.mod_der_state_setInputs = getattr(der_state_file,'%s_setInputs'%self.modelName)
except:
print("state derivative file '%s_der_state.py' or needed function inside this file not found! Something went wrong during code generation.\n%s" % (self.modelName,sys.exc_info()), file=sys.stderr)
# import generated sensors_visual_file
self.mod_sensors_visual = None
try:
sensors_visual_file = __import__('%s_visual'%self.modelName, globals(), locals(), [])
self.mod_sensors_visual = getattr(sensors_visual_file,'%s_visual'%self.modelName)
except:
print("sensors file '%s_visual.py' or function '%s_visual' inside this file not found! Something went wrong during code generation.\n%s" % (self.modelName,self.modelName,sys.exc_info()), file=sys.stderr)
# import generated sensors_file if model contains sensors
self.mod_sensors = None
self.mod_sensors_input = None
self.sensorState = None
self.sensorValues = []
# filenames for dynamic libraries if compileModelC is called
self.dynamicLibraries = None
self.sensors =self.graph.getVariables(VarKind.Sensor)
if self.sensors:
try:
sensors_file = __import__('%s_sensors'%self.modelName, globals(), locals(), [])
self.mod_sensors = getattr(sensors_file,'%s_sensors'%self.modelName)
if (hasattr(sensors_file,'%s_setInputs'%self.modelName)):
self.mod_sensors_input = getattr(sensors_file,'%s_setInputs'%self.modelName)
self.showsensorButton.setDisabled(False) #Eigentlich unnötig, aber falls vorher deaktiviert
except ImportError as err:
print("sensors file '%s_sensors.py' or needed function inside this file not found! Maybe it has not been generated? (%s)" % (self.modelName, err), file=sys.stderr)
print("Disabling Show Sensors Button!")
self.showsensorButton.setDisabled(True)
else:
print('Info: model does not contain any sensors')
self.showsensorButton.setDisabled(True)
# Set Up Empty Integrator
self.integrator = None
# Create VtkScene objects
self.vtkObjects = []
for i in grList:
self.vtkObjects.append(VtkSceneObject(i))
# Connect signals and slots
self.resetButton.clicked.connect(self.resetSliders)
self.resetButton.clicked.connect(self.updateKinematics)
self.showsensorButton.clicked.connect(self.showSensors)
self.simulateButton.clicked.connect(self.runSimulation)
self.compileF90Button.clicked.connect(self.compileModelF90)
self.compileCButton.clicked.connect(self.compileModelC)
self.loadResultsButton.clicked.connect(self.loadResults)
self.playResultsButton.clicked.connect(self.startPlayingResults)
self.resetResultsButton.clicked.connect(self.resetResults)
self.resetResultsButton.setEnabled(False)
for i in self.sliders:
i.slider.valueChanged.connect(i.setStateVal)
i.slider.valueChanged.connect(self.updateKinematics)
for i in self.inputSliders:
i.slider.valueChanged.connect(i.setStateVal)
# finalise setup for flexible bodies
if self.hasFlexibleBodies:
self.qScalingSlider.slider.valueChanged.connect(self.qScalingSlider.setStateVal)
self.qScalingSlider.slider.valueChanged.connect(self.updateFlexScale)
self.updateFlexScale()
# Create simulation thread
self.SimThread = PyMbsThread(self.simulate, realTime=True)
# Create result thread
self.ResultThread = PyMbsThread(self.playResults, realTime=True)
# create recorder instance and connect required signals and slots
self.recorder = PIRecorder(self.getSensorData)
self.recordButton.clicked.connect(self.recorder.toggle)
def getSensorData(self):
'''
Return the current state of the system and the dictionary with the
corresponding positions and orientations of the visualisation objects.
'''
return (self.sensorState, self.sensorValues)
def compileModelF90(self):
print('Creating and compiling Fortran90 sources...')
print("Writing sources to '%s'"%tempfile.gettempdir())
self.graph.writeCode('f90', self.modelName, tempfile.gettempdir(), pymbs_wrapper=True)
print("Compiling Fortran Code ...")
compileF90('%s_der_state' % self.modelName, tempfile.gettempdir())
compileF90('%s_visual' % self.modelName, tempfile.gettempdir())
if self.sensors:
compileF90('%s_sensors' % self.modelName, tempfile.gettempdir())
self.mod_der_state = None
self.mod_der_state_setInputs = None
self.mod_sensors_visual = None
try:
der_state_file = __import__('%s_der_state_F90Wrapper' % self.modelName)
self.mod_der_state = der_state_file.ode_int
self.mod_der_state_setInputs = der_state_file.setInputs
sensors_visual_file = __import__('%s_visual_F90Wrapper' % self.modelName)
self.mod_sensors_visual = sensors_visual_file.graphVisualSensors
#getattr(sensors_visual_file,'%s_visual'%self.modelName)
print('Importing generated Fortran module successful')
except Exception as e:
print('Compiled Fortran module not found... (%s)' % e, file=sys.stderr)
if self.sensors:
# import generated sensors_file
self.mod_sensors = None
self.mod_sensors_input = None
try:
sensors_file = __import__('%s_sensors_F90Wrapper'%self.modelName, globals(), locals(), [])
self.mod_sensors = sensors_file.graphSensors
self.mod_sensors_input = sensors_file.setInputs
self.showsensorButton.setDisabled(False) #Eigentlich unnötig, aber falls vorher deaktiviert
except:
print("Fortran sensors file '%s_sensors_F90Wrapper.py' or needed function inside this file not found! Maybe it has not been generated?\n%s" % (self.modelName,sys.exc_info()), file=sys.stderr)
print("Disabling Show Sensors Button!")
self.showsensorButton.setDisabled(True)
def compileModelC(self):
print('Creating and compiling C sources...')
print("Writing sources to '%s'"%tempfile.gettempdir())
self.dynamicLibraries = []
self.graph.writeCode('c', self.modelName, tempfile.gettempdir(), pymbs_wrapper=True)
print("Compiling C Code ...")
self.dynamicLibraries.append(
compileC('%s_der_state' % self.modelName, tempfile.gettempdir()))
self.dynamicLibraries.append(
compileC('%s_visual' % self.modelName, tempfile.gettempdir()))
if self.sensors:
self.dynamicLibraries.append(
compileC('%s_sensors' % self.modelName, tempfile.gettempdir()))
try:
der_state_file = __import__('%s_der_state_CWrapper' % self.modelName)
self.mod_der_state = der_state_file.ode_int
self.mod_der_state_setInputs = der_state_file.setInputs
sensors_visual_file = __import__('%s_visual_CWrapper' % self.modelName)
self.mod_sensors_visual = sensors_visual_file.graphVisualSensors
print('Importing generated C module successful')
except Exception as e:
print('Compiled C module not found... (%s)' % e, file=sys.stderr)
if self.sensors:
# import generated sensors_file
self.mod_sensors = None
self.mod_sensors_input = None
try:
sensors_file = __import__('%s_sensors_CWrapper'%self.modelName, globals(), locals(), [])
self.mod_sensors = sensors_file.graphSensors
self.mod_sensors_input = sensors_file.setInputs
self.showsensorButton.setDisabled(False) #Eigentlich unnötig, aber falls vorher deaktiviert
except:
print("C sensors file '%s_sensors_CWrapper.py' or needed function inside this file not found! Maybe it has not been generated?\n%s" % (self.modelName,sys.exc_info()), file=sys.stderr)
print("Disabling Show Sensors Button!")
self.showsensorButton.setDisabled(True)
def runSimulation(self):
if (self.mod_der_state is None):
print("Sorry! Viewing the model is disabled, since no der_state code is available!")
return
# Stop Playing of Results
if (self.playResultsButton.isChecked()):
self.playResultsButton.setChecked(False)
self.ResultThread.stop()
self.resetResults()
if self.simulateButton.isChecked():
# | |
in def_prm:
if type(def_prm[name]) != bool:
add_general_opt_arg(parser, def_prm, name, type=type(def_prm[name]), help_str=help_dict[name])
else:
add_boolean_opt_arg(parser, def_prm, name, help_str=help_dict[name])
# Post-processing
args = parser.parse_args()
args_dict = args.__dict__
# Create a dict of only parameters that were passed
passed_prm = {}
for i in range(1, len(sys.argv)): # Skip first argument which is this script name
# Clean argument
arg = sys.argv[i].lstrip("-")
if arg.startswith("no-"): arg = arg[3:]
# Check if it is a known parameter (if not, it's an argument value, and we ignore it)
if arg in args.__dict__:
# Replace it in prm_dict, using value already processed by the parser
passed_prm[arg] = args.__dict__[arg]
# Check clashing arguments
if 'use_existing_interp' in passed_prm:
for opt in list(passed_prm.keys()):
if opt.endswith("_hi") or opt == 'hist_interp' or opt == 'num_interp':
print("ERROR: Can't pass an argument regarding hist_interp ('%s') when use_existing_interp=True"%opt)
exit()
if 'only_interp' in passed_prm:
for opt in list(passed_prm.keys()):
if opt.endswith("_ct") or opt == "color_transfer":
print("ERROR: Can't pass an argument regarding color_transfer ('%s') when only_interp=True"%opt)
exit()
if args_dict['hist_interp'] == "euclid":
if 'sig_gamma_hi' in passed_prm and 'gamma_hi' in passed_prm: print("Can't pass both 'sig_gamma_hi' and 'gamma_hi'."); exit()
elif 'sig_gamma_hi' in passed_prm: args_dict['gamma_hi'] = 2*args_dict['sig_gamma_hi']**2
elif 'gamma_hi' in passed_prm: args_dict['sig_gamma_hi'] = np.sqrt(args_dict['gamma_hi']/2)
else: print("Must specify either 'sig_gamma_hi' or 'gamma_hi'"); exit()
if args_dict['color_transfer'] == "euclid" and not ('only_interp' in passed_prm):
if 'sig_gamma_ct' in passed_prm and 'gamma_ct' in passed_prm: print("Can't pass both 'sig_gamma_ct' and 'gamma_ct'."); exit()
elif 'sig_gamma_ct' in passed_prm: args_dict['gamma_ct'] = 2*args_dict['sig_gamma_ct']**2
elif 'gamma_ct' in passed_prm: args_dict['sig_gamma_ct'] = np.sqrt(args_dict['gamma_ct']/2)
else: print("Must specify either 'sig_gamma_ct' or 'gamma_ct'"); exit()
# Positional arguments
in_images = args_dict['in_images']
in_metric = args_dict['in_metric']
# HI arguments
hist_interp = args_dict['hist_interp']
num_prolong_hi = args_dict['num_prolong_hi']
L_hi = args_dict['L_hi']
t_heat_hi = args_dict['t_heat_hi']
k_heat_hi = args_dict['k_heat_hi']
sig_gamma_hi = args_dict['sig_gamma_hi']
gamma_hi = args_dict['gamma_hi']
sink_check_hi = args_dict['sink_check_hi']
# CT arguments
color_transfer = args_dict['color_transfer']
L_ct = args_dict['L_ct']
t_heat_ct = args_dict['t_heat_ct']
k_heat_ct = args_dict['k_heat_ct']
sig_gamma_ct = args_dict['sig_gamma_ct']
gamma_ct = args_dict['gamma_ct']
sink_check_ct = args_dict['sink_check_ct']
apply_bilateral_filter_ct = args_dict['apply_bilateral_filter_ct']
bf_sigmaSpatial_ct = args_dict['bf_sigmaSpatial_ct']
bf_sigmaRange_ct = args_dict['bf_sigmaRange_ct']
# Other arguments
solver_type = args_dict['solver_type']
use_existing_interp = args_dict['use_existing_interp']
only_interp = args_dict['only_interp']
num_interp = args_dict['num_interp']
top_outdir = args_dict['top_outdir']
final_outdir = args_dict['final_outdir']
kernel_check = args_dict['kernel_check']
# Fun with paths
if not (os.path.isfile(in_metric) and in_metric.endswith(".npy")):
print("ERROR: in_metric ('%s') should be an existing metric file with a '.npy' extension."%in_metric)
exit(-1)
param_filename = "0-parameters.json"
in_metric_base = os.path.basename(in_metric)
in_metric_dir = os.path.dirname(in_metric)
# Metric ID is composed of the folderpath, then "I" and the iteration number of the metric read as input.
metric_id = in_metric_dir.replace('/','_') + "I" + re.findall(r'\d+', in_metric_base)[0].lstrip('0')
in_param = os.path.join(in_metric_dir, param_filename)
dataset = in_images.rsplit("/", maxsplit=2)[1]
# Read parameters from param_file
metric_prm = json.load(open(in_param))
# Make sure the set of parameters is compatible with current code version
metric_prm = prm.forward_compatibility_prm_dict(metric_prm)
# Get local parameters from metric_prm
colorspace = metric_prm['colorspace']
# Parameters passed on the command line override those in the metric
if solver_type:
metric_prm['solver_type'] = solver_type
# Histogram interpolation
if use_existing_interp:
existing_interp_metric = json.load(open(os.path.join(use_existing_interp, param_filename)))
# Check if we are using the same metric and images as the ones that were used for those interps
if existing_interp_metric['in_metric'] != in_metric:
print("ERROR: Using a metric ('%s') different from the one used to generate the existing interp ('%s')"%(in_metric, existing_interp_metric['in_metric']))
exit(-1)
if existing_interp_metric['in_images'] != in_images:
print("ERROR: Using images different from the ones used to generate the existing interp")
exit(-1)
# These parameters won't be used, but the param dict will be consistent
# with the parameters that generated the interpolation.
hist_interp = existing_interp_metric['hist_interp']
n_in = existing_interp_metric['n_in']
n_hi = existing_interp_metric['n_hi']
N_hi = existing_interp_metric['N_hi']
L_hi = existing_interp_metric['L_hi']
t_heat_hi = existing_interp_metric['t_heat_hi']
k_heat_hi = existing_interp_metric['k_heat_hi']
num_prolong_hi = existing_interp_metric['num_prolong_hi']
sig_gamma_hi = existing_interp_metric['sig_gamma_hi']
num_interp = existing_interp_metric['num_interp']
# No need to set metric_prm_hi as it won't be used.
else:
metric_prm_hi = metric_prm.copy()
n_in = metric_prm_hi['n']
n_hi = 2**num_prolong_hi * (n_in-1) + 1
N_hi = n_hi**dim
if hist_interp != "linear":
# If the parameter is not 0, use that value, else use the value in metric_prm_hi; Harmonize both variables
L_hi = metric_prm_hi['L'] = L_hi if L_hi else metric_prm_hi['L']
if hist_interp == "input": # If 'euclid', kernel is computed through convolutions, else through heat method
t_heat_hi = metric_prm_hi['t_heat'] = t_heat_hi if t_heat_hi else metric_prm_hi['t_heat']
k_heat_hi = metric_prm_hi['k_heat'] = k_heat_hi if k_heat_hi else metric_prm_hi['k_heat']
# Color transfer
metric_prm_ct = metric_prm.copy()
n_ct = n_hi
N_ct = n_ct**dim
if color_transfer != "linear":
# If the parameter is not 0, use that value, else use the value in metric_prm_ct; Harmonize both variables
L_ct = metric_prm_ct['L'] = L_ct if L_ct else metric_prm_ct['L']
if color_transfer == "input": # If 'euclid', kernel is computed through convolutions, else through heat method
t_heat_ct = metric_prm_ct['t_heat'] = t_heat_ct if t_heat_ct else metric_prm_ct['t_heat']
k_heat_ct = metric_prm_ct['k_heat'] = k_heat_ct if k_heat_ct else metric_prm_ct['k_heat']
# Output dir
# Two modes:
# 1: specify final_outdir, and data will just go there.
if final_outdir:
prm.outdir = final_outdir
# 2: final_outdir is empty and the program generates a name with parameters.
else:
# If we use an existing interp, take the same folder name and append the parameters for color transfer
prm.outdir = top_outdir
if use_existing_interp:
prm.outdir = os.path.join(prm.outdir, os.path.basename(use_existing_interp))
else:
prm.outdir = os.path.join(prm.outdir, "%s_%s__hi%s_nhi%d_Lhi%d"%(dataset,metric_id,hist_interp,n_hi,L_hi))
if hist_interp == "euclid":
prm.outdir += "_ghi%g"%gamma_hi
if hist_interp == "input":
prm.outdir += "_thi%0.2e"%t_heat_hi
prm.outdir += "_Khi%d"%k_heat_hi
if not only_interp:
prm.outdir += "__ct%s_nct%d_Lct%d"%(color_transfer,n_ct,L_ct)
if color_transfer == "euclid":
prm.outdir += "_gct%g"%gamma_ct
if color_transfer == "input":
prm.outdir += "_tct%0.2e"%t_heat_ct
prm.outdir += "_Kct%d"%k_heat_ct
if apply_bilateral_filter_ct:
prm.outdir += "__bf"
if bf_sigmaSpatial_ct or bf_sigmaRange_ct:
prm.outdir += "_sigS%0.2g_sigR%0.2g"%(bf_sigmaSpatial_ct,bf_sigmaRange_ct)
os.makedirs(prm.outdir, exist_ok=True)
# By default enabled, so that it uses the logger when launched like 'python <script>',
# but can be disabled when using a launch script that already redirects output to file.
logger = None
if not args_dict['disable_tee_logger']:
# Logger that duplicates output to terminal and to file
# This one doesn't replace sys.stdout but just adds a tee.
log_file_base = "0-alloutput.txt"
logger = Logger(os.path.join(prm.outdir, log_file_base))
# Print information after having potentially added the logger
# The logger has to be put here because we need to know what the outdir is
print("Dataset: %s"%dataset)
print("Metric ID: %s"%metric_id)
print("Histogram size for interpolation:",n_hi)
print("Histogram size for color transfer:",n_ct)
# Build kernels if necessary
if not use_existing_interp:
if solver_type: prm.solver_type = metric_prm_hi['solver_type']
# Compute kernel for hist interp
if hist_interp == "input":
xi_hi, _, weights = compute_kernel_from_weight_files(in_metric, metric_prm_hi, dim, num_prolong_hi)
elif hist_interp == "euclid":
xi_hi = mlc.compute_3d_euclidean_kernel_native(n_hi, gamma_hi)
else: # "linear"
xi_hi = 0
# Check kernel
if xi_hi and kernel_check:
prm.iter_num = 0 # This is to differentiate files written by check_kernel. 0: hi, 1: ct
mlct.check_kernel(xi_hi,n_hi,N_hi,metric_prm_hi,kernel_io_torch=False)
else:
xi_hi = 0
if not only_interp:
if solver_type: prm.solver_type = metric_prm_ct['solver_type']
# Compute kernel for color transfer
if color_transfer == "input":
xi_ct, _, weights = compute_kernel_from_weight_files(in_metric, metric_prm_ct, dim, num_prolong_hi)
elif color_transfer == "euclid":
# xi_ct = mlc.compute_3d_euclidean_kernel_numpy(n, "convolution_npy", gamma_ct)
xi_ct = mlc.compute_3d_euclidean_kernel_native(n_ct, gamma_ct)
else:
xi_ct = 0
print("Unrecognized value '%s' for color_transfer"%color_transfer)
exit()
# Check kernel
if xi_hi and kernel_check:
prm.iter_num = 1 # This is to differentiate files written by check_kernel. 0: hi, 1: ct
if xi_ct and kernel_check: mlct.check_kernel(xi_ct,n_ct,N_ct,metric_prm_ct,kernel_io_torch=False)
else:
xi_ct = 0
# Read input images
image_files = np.sort(glob.glob(in_images))
for f in image_files:
if not os.path.isfile(f):
print("ERROR: The glob pattern for input images should only match files, not directories.")
exit(-1)
num_in_hist = len(image_files)
if num_in_hist < 2:
print("ERROR: The glob pattern for input images matches %d files. It should match at least 2."%num_in_hist)
exit()
if num_in_hist > 2:
print("The glob pattern for input images matches %d files. I will consider only the first and last file."%num_in_hist)
# Choose number of interpolations
# If num_interp is non-zero, that's the number of interpolation we want.
# If it's zero, set to the number of input images. If num_in_hist==2, set to 10.
if num_interp == 0:
num_interp = num_in_hist if num_in_hist != 2 else 10
vmin = 1e-6 # Add minimal mass to histograms (later divided by N)
normalize = lambda p: p / np.sum(p)
# Load images
images = {} # Allows input images of | |
<filename>src/azure-cli/azure/cli/command_modules/acr/manifest.py
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
try:
from urllib.parse import unquote
except ImportError:
from urllib import unquote
from knack.log import get_logger
from azure.cli.core.util import user_confirmation
from azure.cli.core.azclierror import InvalidArgumentValueError
from .repository import (
_parse_image_name,
get_image_digest,
_obtain_data_from_registry,
_get_manifest_path,
_acr_repository_attributes_helper
)
from ._docker_utils import (
request_data_from_registry,
get_access_credentials,
get_login_server_suffix,
RepoAccessTokenPermission
)
from ._validators import (
BAD_MANIFEST_FQDN,
BAD_REPO_FQDN
)
logger = get_logger(__name__)
ORDERBY_PARAMS = {
'time_asc': 'timeasc',
'time_desc': 'timedesc'
}
DEFAULT_PAGINATION = 100
BAD_ARGS_ERROR_REPO = "You must provide either a fully qualified repository specifier such as"\
" 'myregistry.azurecr.io/hello-world' as a positional parameter or"\
" provide '-r MyRegistry -n hello-world' argument values."
BAD_ARGS_ERROR_MANIFEST = "You must provide either a fully qualified manifest specifier such as"\
" 'myregistry.azurecr.io/hello-world:latest' as a positional parameter or provide"\
" '-r MyRegistry -n hello-world:latest' argument values."
def _get_v2_manifest_path(repository, manifest):
return '/v2/{}/manifests/{}'.format(repository, manifest)
def _get_referrers_path(repository, manifest):
return '/oras/artifacts/v1/{}/manifests/{}/referrers'.format(repository, manifest)
def _get_deleted_manifest_path(repository):
return '/acr/v1/_deleted/{}/_manifests'.format(repository)
def _get_deleted_tag_path(repository):
return '/acr/v1/_deleted/{}/_tags'.format(repository)
def _get_restore_deleted_manifest_path(repository, manifest, force):
return '/acr/v1/_deleted/{}/_manifests/{}?force={}'.format(repository, manifest, force)
def _obtain_manifest_from_registry(login_server,
path,
username,
password,
raw=False):
result, _ = request_data_from_registry(http_method='get',
login_server=login_server,
path=path,
raw=raw,
username=username,
password=password,
result_index=None,
manifest_headers=True)
return result
def _obtain_referrers_from_registry(login_server,
path,
username,
password,
artifact_type=None):
result_list = {'references': []}
execute_next_http_call = True
params = {
'artifactType': artifact_type
}
while execute_next_http_call:
execute_next_http_call = False
result, next_link = request_data_from_registry(
http_method='get',
login_server=login_server,
path=path,
username=username,
password=password,
result_index=None,
params=params)
if result:
result_list['references'].extend(result['references'])
if next_link:
# The registry is telling us there's more items in the list,
# and another call is needed. The link header looks something
# like `Link: </v2/_catalog?last=hello-world&n=1>; rel="next"`
# we should follow the next path indicated in the link header
next_link_path = next_link[(next_link.index('<') + 1):next_link.index('>')]
tokens = next_link_path.split('?', 1)
params = {y[0]: unquote(y[1]) for y in (x.split('=', 1) for x in tokens[1].split('&'))}
execute_next_http_call = True
return result_list
def _parse_fqdn(cmd, fqdn, is_manifest=True, allow_digest=True, default_latest=True):
try:
if fqdn.startswith('https://'):
fqdn = fqdn[len('https://'):]
reg_addr = fqdn.split('/', 1)[0]
registry_name = reg_addr.split('.', 1)[0]
reg_suffix = '.' + reg_addr.split('.', 1)[1]
manifest_spec = fqdn.split('/', 1)[1]
_validate_login_server_suffix(cmd, reg_suffix)
# We must check for this here as the default tag 'latest' gets added in _parse_image_name
if not is_manifest and ':' in manifest_spec:
raise InvalidArgumentValueError("The positional parameter 'repo_id'"
" should not include a tag or digest.")
repository, tag, manifest = _parse_image_name(manifest_spec, allow_digest=allow_digest, default_latest=default_latest)
except IndexError as e:
if is_manifest:
raise InvalidArgumentValueError(BAD_MANIFEST_FQDN) from e
raise InvalidArgumentValueError(BAD_REPO_FQDN) from e
return registry_name, repository, tag, manifest
def _validate_login_server_suffix(cmd, reg_suffix):
cli_ctx = cmd.cli_ctx
login_server_suffix = get_login_server_suffix(cli_ctx)
if reg_suffix != login_server_suffix:
raise InvalidArgumentValueError(f'Provided registry suffix \'{reg_suffix}\' does not match the configured az'
f' cli acr login server suffix \'{login_server_suffix}\'. Check the'
' \'acrLoginServerEndpoint\' value when running \'az cloud show\'.')
def acr_manifest_list(cmd,
registry_name=None,
repository=None,
repo_id=None,
top=None,
orderby=None,
tenant_suffix=None,
username=None,
password=<PASSWORD>):
if (repo_id and repository) or (not repo_id and not (registry_name and repository)):
raise InvalidArgumentValueError(BAD_ARGS_ERROR_REPO)
if repo_id:
registry_name, repository, _, _ = _parse_fqdn(cmd, repo_id[0], is_manifest=False)
login_server, username, password = get_access_credentials(
cmd=cmd,
registry_name=registry_name,
tenant_suffix=tenant_suffix,
username=username,
password=password,
repository=repository,
permission=RepoAccessTokenPermission.PULL_META_READ.value)
raw_result = _obtain_data_from_registry(
login_server=login_server,
path=_get_manifest_path(repository),
top=top,
username=username,
password=password,
result_index='manifests',
orderby=orderby)
digest_list = [x['digest'] for x in raw_result]
manifest_list = []
for digest in digest_list:
manifest_list.append(_obtain_manifest_from_registry(
login_server=login_server,
path=_get_v2_manifest_path(repository, digest),
username=username,
password=password))
return manifest_list
def acr_manifest_metadata_list(cmd,
registry_name=None,
repository=None,
repo_id=None,
top=None,
orderby=None,
tenant_suffix=None,
username=None,
password=<PASSWORD>):
if (repo_id and repository) or (not repo_id and not (registry_name and repository)):
raise InvalidArgumentValueError(BAD_ARGS_ERROR_REPO)
if repo_id:
registry_name, repository, _, _ = _parse_fqdn(cmd, repo_id[0], is_manifest=False)
login_server, username, password = get_access_credentials(
cmd=cmd,
registry_name=registry_name,
tenant_suffix=tenant_suffix,
username=username,
password=password,
repository=repository,
permission=RepoAccessTokenPermission.METADATA_READ.value)
raw_result = _obtain_data_from_registry(
login_server=login_server,
path=_get_manifest_path(repository),
username=username,
password=password,
result_index='manifests',
top=top,
orderby=orderby)
return raw_result
def acr_manifest_deleted_list(cmd,
registry_name=None,
repository=None,
repo_id=None,
tenant_suffix=None,
username=None,
password=<PASSWORD>):
if (repo_id and repository) or (not repo_id and not (registry_name and repository)):
raise InvalidArgumentValueError(BAD_ARGS_ERROR_REPO)
if repo_id:
registry_name, repository, _, _ = _parse_fqdn(cmd, repo_id[0], is_manifest=False)
login_server, username, password = get_access_credentials(
cmd=cmd,
registry_name=registry_name,
tenant_suffix=tenant_suffix,
username=username,
password=password,
repository=repository,
permission=RepoAccessTokenPermission.METADATA_READ.value)
raw_result = _obtain_data_from_registry(
login_server=login_server,
path=_get_deleted_manifest_path(repository),
username=username,
password=password,
result_index='manifests')
return raw_result
def acr_manifest_deleted_tags_list(cmd,
registry_name=None,
permissive_repo=None,
perm_repo_id=None,
tenant_suffix=None,
username=None,
password=<PASSWORD>):
if (perm_repo_id and permissive_repo) or (not perm_repo_id and not (registry_name and permissive_repo)):
raise InvalidArgumentValueError(BAD_ARGS_ERROR_REPO)
if perm_repo_id:
registry_name, repository, tag, _ = _parse_fqdn(cmd, perm_repo_id[0], is_manifest=True, allow_digest=False, default_latest=False)
else:
repository, tag, _ = _parse_image_name(permissive_repo, allow_digest=False, default_latest=False)
login_server, username, password = get_access_credentials(
cmd=cmd,
registry_name=registry_name,
tenant_suffix=tenant_suffix,
username=username,
password=password,
repository=repository,
permission=RepoAccessTokenPermission.METADATA_READ.value)
raw_result = _obtain_data_from_registry(
login_server=login_server,
path=_get_deleted_tag_path(repository),
username=username,
password=password,
result_index='tags')
if tag:
return [x for x in raw_result if x['tag'] == tag]
return raw_result
def acr_manifest_deleted_restore(cmd,
registry_name=None,
manifest_spec=None,
manifest_id=None,
digest=None,
force=False,
yes = False,
tenant_suffix=None,
username=None,
password=<PASSWORD>):
if (manifest_id and manifest_spec) or (not manifest_id and not (registry_name and manifest_spec)):
raise InvalidArgumentValueError(BAD_ARGS_ERROR_MANIFEST)
if manifest_id:
registry_name, repository, tag, _ = _parse_fqdn(cmd, manifest_id[0], allow_digest=False)
else:
repository, tag, _ = _parse_image_name(manifest_spec, allow_digest=False, default_latest=False)
login_server, username, password = get_access_credentials(
cmd=cmd,
registry_name=registry_name,
tenant_suffix=tenant_suffix,
username=username,
password=password,
repository=repository,
permission=RepoAccessTokenPermission.META_WRITE_META_READ.value)
post_payload = {"tag":tag}
if not digest:
tag_obj_list = _obtain_data_from_registry(
login_server=login_server,
path=_get_deleted_tag_path(repository),
username=username,
password=password,
result_index='tags')
digest_list = [x['digest'] for x in tag_obj_list if x['tag'] == tag]
if(len(digest_list) == 0):
raise InvalidArgumentValueError(f'No deleted manifests found for tag: {tag}')
digest = digest_list[-1]
if(len(digest_list) > 1):
user_confirmation("Multiple deleted manifests found for tag: {}. Restoring most recently deleted manifest with digest: {}. Is this okay?".format(tag, digest), yes)
raw_result, _ = request_data_from_registry('post',
login_server,
_get_restore_deleted_manifest_path(repository, digest, force),
username,
password,
result_index=None,
json_payload=post_payload,
file_payload=None,
params=None,
manifest_headers=False,
raw=False,
retry_times=3,
retry_interval=5,
timeout=300)
return raw_result
def acr_manifest_list_referrers(cmd,
registry_name=None,
manifest_spec=None,
artifact_type=None,
manifest_id=None,
recursive=False,
tenant_suffix=None,
username=None,
password=<PASSWORD>):
if (manifest_id and manifest_spec) or (not manifest_id and not (registry_name and manifest_spec)):
raise InvalidArgumentValueError(BAD_ARGS_ERROR_MANIFEST)
if manifest_id:
registry_name, repository, tag, manifest = _parse_fqdn(cmd, manifest_id[0])
else:
repository, tag, manifest = _parse_image_name(manifest_spec, allow_digest=True)
if not manifest:
image = repository + ':' + tag
repository, tag, manifest = get_image_digest(cmd, registry_name, image)
login_server, username, password = get_access_credentials(
cmd=cmd,
registry_name=registry_name,
tenant_suffix=tenant_suffix,
username=username,
password=password,
repository=repository,
permission=RepoAccessTokenPermission.PULL.value)
raw_result = _obtain_referrers_from_registry(
login_server=login_server,
path=_get_referrers_path(repository, manifest),
username=username,
password=password,
artifact_type=artifact_type)
ref_key = "references"
if recursive:
for referrers_obj in raw_result[ref_key]:
internal_referrers_obj = _obtain_referrers_from_registry(
login_server=login_server,
path=_get_referrers_path(repository, referrers_obj["digest"]),
username=username,
password=password)
for ref in internal_referrers_obj[ref_key]:
raw_result[ref_key].append(ref)
return raw_result
def acr_manifest_show(cmd,
registry_name=None,
manifest_spec=None,
manifest_id=None,
raw_output=None,
tenant_suffix=None,
username=None,
password=<PASSWORD>):
if (manifest_id and manifest_spec) or (not manifest_id and not (registry_name and manifest_spec)):
raise InvalidArgumentValueError(BAD_ARGS_ERROR_MANIFEST)
if manifest_id:
registry_name, repository, tag, manifest = _parse_fqdn(cmd, manifest_id[0])
else:
repository, tag, manifest = _parse_image_name(manifest_spec, allow_digest=True)
if not manifest:
image = repository + ':' + tag
repository, tag, manifest = get_image_digest(cmd, registry_name, image)
login_server, username, password = get_access_credentials(
cmd=cmd,
registry_name=registry_name,
tenant_suffix=tenant_suffix,
username=username,
password=password,
repository=repository,
permission=RepoAccessTokenPermission.PULL.value)
raw_result = _obtain_manifest_from_registry(
login_server=login_server,
path=_get_v2_manifest_path(repository, manifest),
raw=raw_output,
username=username,
password=password)
# We are forced to print directly here in order to preserve bit for bit integrity and
# avoid any formatting so that the output can successfully be hashed. Customer will expect that
# 'az acr manifest show myreg.azurecr.io/myrepo@sha256:abc123 --raw | shasum -a 256' will result in 'abc123'
if raw_output:
print(raw_result, end='')
return
return raw_result
def acr_manifest_metadata_show(cmd,
registry_name=None,
manifest_spec=None,
manifest_id=None,
tenant_suffix=None,
username=None,
password=<PASSWORD>):
if (manifest_id and manifest_spec) or (not manifest_id and not (registry_name and manifest_spec)):
raise InvalidArgumentValueError(BAD_ARGS_ERROR_MANIFEST)
if manifest_id:
registry_name, repository, tag, manifest = _parse_fqdn(cmd, manifest_id[0])
manifest_spec = repository + ':' + tag if tag else repository + '@' + manifest
return _acr_repository_attributes_helper(
cmd=cmd,
registry_name=registry_name,
http_method='get',
json_payload=None,
permission=RepoAccessTokenPermission.METADATA_READ.value,
repository=None,
image=manifest_spec,
tenant_suffix=tenant_suffix,
username=username,
password=password)
def acr_manifest_metadata_update(cmd,
registry_name=None,
manifest_spec=None,
manifest_id=None,
tenant_suffix=None,
username=None,
password=<PASSWORD>,
delete_enabled=None,
list_enabled=None,
read_enabled=None,
write_enabled=None):
if (manifest_id and manifest_spec) or (not manifest_id and not (registry_name and manifest_spec)):
raise InvalidArgumentValueError(BAD_ARGS_ERROR_MANIFEST)
if manifest_id:
registry_name, repository, tag, manifest = _parse_fqdn(cmd, manifest_id[0])
manifest_spec = repository + ':' + tag if tag else repository + '@' + manifest
json_payload = {}
if delete_enabled is not None:
json_payload.update({
'deleteEnabled': delete_enabled
})
if list_enabled is not None:
json_payload.update({
'listEnabled': list_enabled
})
if read_enabled is not None:
json_payload.update({
'readEnabled': read_enabled
})
if write_enabled is not None:
json_payload.update({
'writeEnabled': write_enabled
})
permission = RepoAccessTokenPermission.META_WRITE_META_READ.value if json_payload \
else RepoAccessTokenPermission.METADATA_READ.value
return _acr_repository_attributes_helper(
cmd=cmd,
registry_name=registry_name,
http_method='patch' if json_payload else 'get',
json_payload=json_payload,
permission=permission,
repository=None,
image=manifest_spec,
tenant_suffix=tenant_suffix,
username=username,
password=password)
def acr_manifest_delete(cmd,
registry_name=None,
manifest_spec=None,
manifest_id=None,
tenant_suffix=None,
username=None,
password=<PASSWORD>,
yes=False):
if (manifest_id and manifest_spec) or (not manifest_id and not (registry_name and manifest_spec)):
raise InvalidArgumentValueError(BAD_ARGS_ERROR_MANIFEST)
if manifest_id:
registry_name, repository, tag, manifest = _parse_fqdn(cmd, manifest_id[0])
else:
repository, tag, manifest = _parse_image_name(manifest_spec, allow_digest=True)
if not manifest:
image = repository + ':' + tag
repository, tag, manifest = get_image_digest(cmd, registry_name, image)
login_server, username, password = get_access_credentials(
cmd=cmd,
registry_name=registry_name,
tenant_suffix=tenant_suffix,
username=username,
password=password,
repository=repository,
permission=RepoAccessTokenPermission.DELETE.value)
user_confirmation("Are you sure you want | |
<reponame>MyWay404/WordMaker<gh_stars>0
#!/usr/bin/python3
# Import Modules
try:
import os,sys,time,random,threading,platform,readline,configparser,functools
except Exception as F:
exit("\x1b[1;31m [!] \x1b[0;32m%s"%(F)+"\x1b[0;39m")
# Color
A = "\x1b[1;32m"
B = "\x1b[1;31m"
C = "\x1b[1;33m"
D = "\x1b[1;36m"
E = "\x1b[0;39m"
rand = (A,B,C,D)
W = random.choice(rand)
# Adaptor
name = platform.system()
if name == "Windows":
clr = "cls"
else:
clr = "clear"
if sys.version_info[0] != 3:
exit(B+" [!] "+A+"This tool work only on python3!"+E)
else:
pass
# Banner
BR = W+"""
__ __ _ _ _ _
\ \ / /__ _ __ __| | (_)___| |_
\ \ /\ / / _ \| '__/ _` | | / __| __|
\ V V / (_) | | | (_| | | \__ \ |_
\_/\_/ \___/|_| \__,_|_|_|___/\__|
"""+E
# Create wordlist
CONFIG = {}
def informations():
os.system(clr)
print(BR)
profile = {}
print(" "+"\x1b[1;39m-"*64+E)
print(B+" [!] "+A+"Insert the information about the victim to make a dictionary")
print(B+" [!] "+A+"If you don't know all the info,just hit enter when asked! ;)\r\n")
name = input(C+" [+] "+D+"First Name: "+E)
while len(name) == 0 or name == " " or name == " " or name == " ":
print(B+" [!] "+A+"You must enter a name at least!")
name = input(C+" [+] "+D+"Name: "+E)
profile["name"] = str(name)
profile["surname"] = input(C+" [+] "+D+"Surname: "+E)
profile["nick"] = input(C+" [+] "+D+"Nickname: "+E)
birthdate = input(C+" [+] "+D+"Birthdate (DDMMYYYY): "+E)
while len(birthdate) != 0 and len(birthdate) != 8:
print(B+" [!] "+A+"You must enter 8 digits for birthday!")
birthdate = input(C+" [+] "+D+"Birthdate (DDMMYYYY): "+E)
profile["birthdate"] = str(birthdate)
print("\r\n")
profile["wife"] = input(C+" [+] "+D+"Partners) name: "+E)
profile["wifen"] = input(C+" [+] "+D+"Partners) nickname: "+E)
wifeb = input(C+" [+] "+D+"Partners) birthdate (DDMMYYYY): "+E)
while len(wifeb) != 0 and len(wifeb) != 8:
print(B+" [!] "+A+"You must enter 8 digits for birthday!")
wifeb = input(C+" [+] "+D+"Partners birthdate (DDMMYYYY): "+E)
profile["wifeb"] = str(wifeb)
print("\r\n")
profile["kid"] = input(C+" [+] "+D+"Child's name: "+E)
profile["kidn"] = input(C+" [+] "+D+"Child's nickname: "+E)
kidb = input(C+" [+] "+D+"Child's birthdate (DDMMYYYY): "+E)
while len(kidb) != 0 and len(kidb) != 8:
print(B+" [!] "+A+"You must enter 8 digits for birthday!")
kidb = input(C+" [+] "+D+"Child's birthdate (DDMMYYYY): "+E)
profile["kidb"] = str(kidb)
print("\r\n")
profile["pet"] = input(C+" [+] "+D+"Pet's name: "+E)
profile["company"] = input(C+" [+] "+D+"Company name: "+E)
print("\r\n")
profile["words"] = [""]
words1 = input(C+" [+] "+D+"Do you want to add some key words about the victim? Y/[N]: "+E)
words2 = ""
if words1.lower() == "y":
print(B+" [+] "+A+"Please enter the words,separated by comma."+E)
words2 = input(C+" [+] "+D+"[i.e. hacker,juice,black],spaces will be removed: "+E).replace(" ","")
profile["words"] = words2.split(",")
profile["spechars1"] = input(C+" [+] "+D+"Do you want to add special chars at the end of words? Y/[N]: "+E)
profile["randnum"] = input(C+" [+] "+D+"Do you want to add some random numbers at the end of words? Y/[N]:"+E)
profile["leetmode"] = input(C+" [+] "+D+"Leet mode? (i.e. leet = 1337) Y/[N]: "+E)
print("\r\n")
generate(profile)
def read_config(file):
if os.path.isfile(file) == True:
config = configparser.ConfigParser()
config.read(file)
CONFIG["global"] = {
"years": config.get("years","years").split(","),
"chars": config.get("specialchars","chars").split(","),
"numfrom": config.getint("nums","from"),
"numto": config.getint("nums","to"),
"wcfrom": config.getint("nums","wcfrom"),
"wcto": config.getint("nums","wcto")
}
leet = functools.partial(config.get,"leet")
leetc = {}
letters = {"a","i","e","t","o","s","g","z"}
for letter in letters:
leetc[letter] = config.get("leet",letter)
CONFIG["LEET"] = leetc
return True
else:
print(B+" [!] "+A+"Configuration file "+C+file+A+" not found!\n"+B+" [!] "+A+"Exiting "+E+"...")
sys.exit()
return False
def make_leet(x):
for letter,leetletter in CONFIG["LEET"].items():
x = x.replace(letter,leetletter)
return x
def concats(seq,start,stop):
for mystr in seq:
for num in range(start,stop):
yield mystr+str(num)
def komb(seq,start,special=""):
for mystr in seq:
for mystr1 in start:
yield mystr+special+mystr1
def generate(profile):
chars = CONFIG["global"]["chars"]
years = CONFIG["global"]["years"]
numfrom = CONFIG["global"]["numfrom"]
numto = CONFIG["global"]["numto"]
profile["spechars"] = []
if profile["spechars1"].lower() == "y":
for spec1 in chars:
profile["spechars"].append(spec1)
for spec2 in chars:
profile["spechars"].append(spec1+spec2)
for spec3 in chars:
profile["spechars"].append(spec1+spec2+spec3)
print(B+" [!] "+A+"Now making a dictionary"+E+" ...")
birthdate_yy = profile["birthdate"][-2:]
birthdate_yyy = profile["birthdate"][-3:]
birthdate_yyyy = profile["birthdate"][-4:]
birthdate_xd = profile["birthdate"][1:2]
birthdate_xm = profile["birthdate"][3:4]
birthdate_dd = profile["birthdate"][:2]
birthdate_mm = profile["birthdate"][2:4]
wifeb_yy = profile["wifeb"][-2:]
wifeb_yyy = profile["wifeb"][-3:]
wifeb_yyyy = profile["wifeb"][-4:]
wifeb_xd = profile["wifeb"][1:2]
wifeb_xm = profile["wifeb"][3:4]
wifeb_dd = profile["wifeb"][:2]
wifeb_mm = profile["wifeb"][2:4]
kidb_yy = profile["kidb"][-2:]
kidb_yyy = profile["kidb"][-3:]
kidb_yyyy = profile["kidb"][-4:]
kidb_xd = profile["kidb"][1:2]
kidb_xm = profile["kidb"][3:4]
kidb_dd = profile["kidb"][:2]
kidb_mm = profile["kidb"][2:4]
nameup = profile["name"].title()
surnameup = profile["surname"].title()
nickup = profile["nick"].title()
wifeup = profile["wife"].title()
wifenup = profile["wifen"].title()
kidup = profile["kid"].title()
kidnup = profile["kidn"].title()
petup = profile["pet"].title()
companyup = profile["company"].title()
wordsup = []
wordsup = list(map(str.title,profile["words"]))
word = profile["words"]+wordsup
rev_name = profile["name"][::-1]
rev_nameup = nameup[::-1]
rev_nick = profile["nick"][::-1]
rev_nickup = nickup[::-1]
rev_wife = profile["wife"][::-1]
rev_wifeup = wifeup[::-1]
rev_kid = profile["kid"][::-1]
rev_kidup = kidup[::-1]
reverse = [
rev_name,
rev_nameup,
rev_nick,
rev_nickup,
rev_wife,
rev_wifeup,
rev_kid,
rev_kidup,
]
rev_n = [rev_name,rev_nameup,rev_nick,rev_nickup]
rev_w = [rev_wife,rev_wifeup]
rev_k = [rev_kid,rev_kidup]
bds = [
birthdate_yy,
birthdate_yyy,
birthdate_yyyy,
birthdate_xd,
birthdate_xm,
birthdate_dd,
birthdate_mm,
]
bdss = []
for bds1 in bds:
bdss.append(bds1)
for bds2 in bds:
if bds.index(bds1) != bds.index(bds2):
bdss.append(bds1+bds2)
for bds3 in bds:
if (
bds.index(bds1) != bds.index(bds2)
and bds.index(bds2) != bds.index(bds3)
and bds.index(bds1) != bds.index(bds3)
):
bdss.append(bds1+bds2+bds3)
wbds = [wifeb_yy,wifeb_yyy,wifeb_yyyy,wifeb_xd,wifeb_xm,wifeb_dd,wifeb_mm]
wbdss = []
for wbds1 in wbds:
wbdss.append(wbds1)
for wbds2 in wbds:
if wbds.index(wbds1) != wbds.index(wbds2):
wbdss.append(wbds1+wbds2)
for wbds3 in wbds:
if (
wbds.index(wbds1) != wbds.index(wbds2)
and wbds.index(wbds2) != wbds.index(wbds3)
and wbds.index(wbds1) != wbds.index(wbds3)
):
wbdss.append(wbds1+wbds2+wbds3)
kbds = [kidb_yy,kidb_yyy,kidb_yyyy,kidb_xd,kidb_xm,kidb_dd,kidb_mm]
kbdss = []
for kbds1 in kbds:
kbdss.append(kbds1)
for kbds2 in kbds:
if kbds.index(kbds1) != kbds.index(kbds2):
kbdss.append(kbds1+kbds2)
for kbds3 in kbds:
if (
kbds.index(kbds1) != kbds.index(kbds2)
and kbds.index(kbds2) != kbds.index(kbds3)
and kbds.index(kbds1) != kbds.index(kbds3)
):
kbdss.append(kbds1+kbds2+kbds3)
kombinaac = [profile["pet"],petup,profile["company"],companyup]
kombina = [
profile["name"],
profile["surname"],
profile["nick"],
nameup,
surnameup,
nickup,
]
kombinaw = [
profile["wife"],
profile["wifen"],
wifeup,
wifenup,
profile["surname"],
surnameup,
]
kombinak = [
profile["kid"],
profile["kidn"],
kidup,
kidnup,
profile["surname"],
surnameup,
]
kombinaa = []
for kombina1 in kombina:
kombinaa.append(kombina1)
for kombina2 in kombina:
if kombina.index(kombina1) != kombina.index(kombina2) and kombina.index(
kombina1.title()
) != kombina.index(kombina2.title()):
kombinaa.append(kombina1+kombina2)
kombinaaw = []
for kombina1 in kombinaw:
kombinaaw.append(kombina1)
for kombina2 in kombinaw:
if kombinaw.index(kombina1) != kombinaw.index(kombina2) and kombinaw.index(
kombina1.title()
) != kombinaw.index(kombina2.title()):
kombinaaw.append(kombina1+kombina2)
kombinaak = []
for kombina1 in kombinak:
kombinaak.append(kombina1)
for kombina2 in kombinak:
if kombinak.index(kombina1) != kombinak.index(kombina2) and kombinak.index(
kombina1.title()
) != kombinak.index(kombina2.title()):
kombinaak.append(kombina1+kombina2)
kombi = {}
kombi[1] = list(komb(kombinaa,bdss))
kombi[1] += list(komb(kombinaa,bdss,"_"))
kombi[2] = list(komb(kombinaaw,wbdss))
kombi[2] += list(komb(kombinaaw,wbdss,"_"))
kombi[3] = list(komb(kombinaak,kbdss))
kombi[3] += list(komb(kombinaak,kbdss,"_"))
kombi[4] = list(komb(kombinaa,years))
kombi[4] += list(komb(kombinaa,years,"_"))
kombi[5] = list(komb(kombinaac,years))
kombi[5] += list(komb(kombinaac,years,"_"))
kombi[6] = list(komb(kombinaaw,years))
kombi[6] += list(komb(kombinaaw,years,"_"))
kombi[7] = list(komb(kombinaak,years))
kombi[7] += list(komb(kombinaak,years,"_"))
kombi[8] = list(komb(word,bdss))
kombi[8] += list(komb(word,bdss,"_"))
kombi[9] = list(komb(word,wbdss))
kombi[9] += list(komb(word,wbdss,"_"))
kombi[10] = list(komb(word,kbdss))
kombi[10] += list(komb(word,kbdss,"_"))
kombi[11] = list(komb(word,years))
kombi[11] += list(komb(word,years,"_"))
kombi[12] = [""]
kombi[13] = [""]
kombi[14] = [""]
kombi[15] = [""]
kombi[16] = [""]
kombi[21] = [""]
if profile["randnum"].lower() == "y":
kombi[12] = list(concats(word,numfrom,numto))
kombi[13] = list(concats(kombinaa,numfrom,numto))
kombi[14] = list(concats(kombinaac,numfrom,numto))
kombi[15] = list(concats(kombinaaw,numfrom,numto))
kombi[16] = list(concats(kombinaak,numfrom,numto))
kombi[21] = list(concats(reverse,numfrom,numto))
kombi[17] = list(komb(reverse,years))
kombi[17] += list(komb(reverse,years,"_"))
kombi[18] = list(komb(rev_w,wbdss))
kombi[18] += list(komb(rev_w,wbdss,"_"))
kombi[19] = list(komb(rev_k,kbdss))
kombi[19] += list(komb(rev_k,kbdss,"_"))
kombi[20] = list(komb(rev_n,bdss))
kombi[20] += list(komb(rev_n,bdss,"_"))
komb001 = [""]
komb002 = [""]
komb003 = [""]
komb004 = [""]
komb005 = [""]
komb006 = [""]
if len(profile["spechars"]) > 0:
komb001 = list(komb(kombinaa,profile["spechars"]))
komb002 = list(komb(kombinaac,profile["spechars"]))
komb003 = list(komb(kombinaaw,profile["spechars"]))
komb004 = list(komb(kombinaak,profile["spechars"]))
komb005 = list(komb(word,profile["spechars"]))
komb006 = list(komb(reverse,profile["spechars"]))
print(B+" [!] "+A+"Sorting list and removing duplicates "+E+"...")
komb_unique = {}
for i in range(1,22):
komb_unique[i] = list(dict.fromkeys(kombi[i]).keys())
komb_unique01 = list(dict.fromkeys(kombinaa).keys())
komb_unique02 = list(dict.fromkeys(kombinaac).keys())
komb_unique03 = list(dict.fromkeys(kombinaaw).keys())
komb_unique04 = list(dict.fromkeys(kombinaak).keys())
komb_unique05 = list(dict.fromkeys(word).keys())
komb_unique07 = list(dict.fromkeys(komb001).keys())
komb_unique08 = list(dict.fromkeys(komb002).keys())
komb_unique09 = list(dict.fromkeys(komb003).keys())
komb_unique010 = list(dict.fromkeys(komb004).keys())
komb_unique011 = list(dict.fromkeys(komb005).keys())
komb_unique012 = list(dict.fromkeys(komb006).keys())
uniqlist = (
bdss
+wbdss
+kbdss
+reverse
+komb_unique01
+komb_unique02
+komb_unique03
+komb_unique04
+komb_unique05
)
for i in range(1,21):
uniqlist += komb_unique[i]
uniqlist += (
komb_unique07
+komb_unique08
+komb_unique09
+komb_unique010
+komb_unique011
+komb_unique012
)
unique_lista = list(dict.fromkeys(uniqlist).keys())
unique_leet = []
if profile["leetmode"].lower() == "y":
for (
x
) in (
unique_lista
):
x = make_leet(x)
unique_leet.append(x)
unique_list = unique_lista+unique_leet
unique_list_finished = []
unique_list_finished = [
x
for x in unique_list
if len(x) > 5 and len(x) < 12
]
print_to_file(profile["name"]+".txt",unique_list_finished)
def print_to_file(filename,unique_list_finished):
f = open(filename.lower(),"w")
unique_list_finished.sort()
f.write(os.linesep.join(unique_list_finished))
f.close()
f = open(filename.lower(),"r")
lines = 0
for line in f:
lines += 1
f.close()
print(B+" [!] "+A+"Saving dictionary to "+C+filename.lower()+A+",counting "+C+str(lines)+A+" words."+E)
print("\r\n")
| |
testIntToTFIDFWithoutSmoothing(self):
def preprocessing_fn(inputs):
out_index, out_values = tft.tfidf(inputs['a'], 13, smooth=False)
return {'tf_idf': out_values, 'index': out_index}
input_data = [{'a': [2, 2, 0]},
{'a': [2, 6, 2, 0]},
{'a': [8, 10, 12, 12, 12]},
]
input_metadata = tft_unit.metadata_from_feature_spec(
{'a': tf.io.VarLenFeature(tf.int64)})
log_3_over_2 = 1.4054651081
log_3 = 2.0986122886
expected_data = [{
'tf_idf': [(1/3)*log_3_over_2, (2/3)*log_3_over_2],
'index': [0, 2]
}, {
'tf_idf': [(1/4)*log_3_over_2, (2/4)*log_3_over_2, (1/4)*log_3],
'index': [0, 2, 6]
}, {
'tf_idf': [(1/5)*log_3, (1/5)*log_3, (3/5)*log_3],
'index': [8, 10, 12]
}]
expected_schema = tft_unit.metadata_from_feature_spec({
'tf_idf': tf.io.VarLenFeature(tf.float32),
'index': tf.io.VarLenFeature(tf.int64)
})
self.assertAnalyzeAndTransformResults(
input_data, input_metadata, preprocessing_fn, expected_data,
expected_schema)
def testTFIDFWithOOV(self):
test_vocab_size = 3
def preprocessing_fn(inputs):
inputs_as_ints = tft.compute_and_apply_vocabulary(
tf.strings.split(inputs['a']), top_k=test_vocab_size)
out_index, out_values = tft.tfidf(inputs_as_ints,
test_vocab_size+1)
return {
'tf_idf': out_values,
'index': out_index
}
input_data = [{'a': 'hello hello world'},
{'a': 'hello goodbye hello world'},
{'a': 'I like pie pie pie'}]
input_metadata = tft_unit.metadata_from_feature_spec(
{'a': tf.io.FixedLenFeature([], tf.string)})
# IDFs
# hello = log(3/3) = 0
# pie = log(3/2) = 0.4054651081
# world = log(3/3) = 0
# OOV - goodbye, I, like = log(3/3)
log_4_over_2 = 1.69314718056
log_4_over_3 = 1.28768207245
expected_transformed_data = [{
'tf_idf': [(2/3)*log_4_over_3, (1/3)*log_4_over_3],
'index': [0, 2]
}, {
'tf_idf': [(2/4)*log_4_over_3, (1/4)*log_4_over_3, (1/4)*log_4_over_3],
'index': [0, 2, 3]
}, {
'tf_idf': [(3/5)*log_4_over_2, (2/5)*log_4_over_3],
'index': [1, 3]
}]
expected_metadata = tft_unit.metadata_from_feature_spec({
'tf_idf': tf.io.VarLenFeature(tf.float32),
'index': tf.io.VarLenFeature(tf.int64)
})
self.assertAnalyzeAndTransformResults(
input_data, input_metadata, preprocessing_fn, expected_transformed_data,
expected_metadata)
def testTFIDFWithNegatives(self):
def preprocessing_fn(inputs):
out_index, out_values = tft.tfidf(inputs['a'], 14)
return {
'tf_idf': out_values,
'index': out_index
}
input_data = [{'a': [2, 2, -4]},
{'a': [2, 6, 2, -1]},
{'a': [8, 10, 12, 12, 12]},
]
input_metadata = tft_unit.metadata_from_feature_spec(
{'a': tf.io.VarLenFeature(tf.int64)})
log_4_over_2 = 1.69314718056
log_4_over_3 = 1.28768207245
# NOTE: -4 mod 14 = 10
expected_transformed_data = [{
'tf_idf': [(2/3)*log_4_over_3, (1/3)*log_4_over_3],
'index': [2, 10]
}, {
'tf_idf': [(2/4)*log_4_over_3, (1/4)*log_4_over_2, (1/4)*log_4_over_2],
'index': [2, 6, 13]
}, {
'tf_idf': [(1/5)*log_4_over_2, (1/5)*log_4_over_3, (3/5)*log_4_over_2],
'index': [8, 10, 12]
}]
expected_metadata = tft_unit.metadata_from_feature_spec({
'tf_idf': tf.io.VarLenFeature(tf.float32),
'index': tf.io.VarLenFeature(tf.int64)
})
self.assertAnalyzeAndTransformResults(
input_data, input_metadata, preprocessing_fn, expected_transformed_data,
expected_metadata)
@tft_unit.named_parameters(
dict(
testcase_name='string_feature_k2',
feature_label_pairs=[
(b'hello', 1),
(b'hello', 1),
(b'hello', 1),
(b'goodbye', 1),
(b'aaaaa', 1),
(b'aaaaa', 1),
(b'goodbye', 0),
(b'goodbye', 0),
(b'aaaaa', 1),
(b'aaaaa', 1),
(b'goodbye', 1),
(b'goodbye', 0),
],
feature_dtype=tf.string,
expected_data=[-1, -1, -1, 0, 1, 1, 0, 0, 0, 1, 1, 0],
k=2,
),
dict(
testcase_name='string_feature_k1',
feature_label_pairs=[
(b'hello', 1),
(b'hello', 1),
(b'hello', 1),
(b'goodbye', 1),
(b'aaaaa', 1),
(b'aaaaa', 1),
(b'goodbye', 0),
(b'goodbye', 0),
(b'aaaaa', 1),
(b'aaaaa', 1),
(b'goodbye', 1),
(b'goodbye', 0),
],
feature_dtype=tf.string,
expected_data=[-1, -1, -1, 0, -1, -1, 0, 0, 0, -1, -1, 0],
k=1,
),
dict(
testcase_name='int64_feature_k2',
feature_label_pairs=[
(3, 1),
(3, 1),
(3, 1),
(1, 1),
(2, 1),
(2, 1),
(1, 0),
(1, 0),
(2, 1),
(2, 1),
(1, 1),
(1, 0),
],
feature_dtype=tf.int64,
expected_data=[-1, -1, -1, 0, 1, 1, 0, 0, 0, 1, 1, 0],
k=2,
))
def testVocabularyAnalyzerWithLabelsAndTopK(self,
feature_label_pairs,
feature_dtype,
expected_data,
k=2):
input_data = []
for feature, label in feature_label_pairs:
input_data.append({'a': feature, 'label': label})
input_metadata = tft_unit.metadata_from_feature_spec({
'a': tf.io.FixedLenFeature([], feature_dtype),
'label': tf.io.FixedLenFeature([], tf.int64)
})
expected_metadata = tft_unit.metadata_from_feature_spec({
'index': tf.io.FixedLenFeature([], tf.int64),
}, {'index': schema_pb2.IntDomain(min=-1, max=k - 1, is_categorical=True)})
def preprocessing_fn(inputs):
return {
'index':
tft.compute_and_apply_vocabulary(
inputs['a'], labels=inputs['label'], top_k=k)
}
expected_data = [{'index': val} for val in expected_data]
self.assertAnalyzeAndTransformResults(input_data, input_metadata,
preprocessing_fn, expected_data,
expected_metadata)
@tft_unit.named_parameters(
dict(
testcase_name='string_feature',
features=[
b'hello',
b'hello',
b'hello',
b'goodbye',
b'aaaaa',
b'aaaaa',
b'goodbye',
b'goodbye',
b'aaaaa',
b'aaaaa',
b'goodbye',
b'goodbye',
],
feature_dtype=tf.string,
expected_tokens=[b'goodbye', b'aaaaa', b'hello'],
),
dict(
testcase_name='int64_feature',
features=[
3,
3,
3,
1,
2,
2,
1,
1,
2,
2,
1,
1,
],
feature_dtype=tf.int64,
expected_tokens=[1, 2, 3]),
)
def testVocabularyAnalyzerStringVsIntegerFeature(
self, features, feature_dtype, expected_tokens):
"""Ensure string and integer features are treated equivalently."""
labels = [1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0]
input_data = []
for feature, label in zip(features, labels):
input_data.append({'a': feature, 'label': label})
input_metadata = tft_unit.metadata_from_feature_spec({
'a': tf.io.FixedLenFeature([], feature_dtype),
'label': tf.io.FixedLenFeature([], tf.int64)
})
expected_metadata = input_metadata
expected_mi = [1.975322, 1.6600708, 1.2450531]
if feature_dtype != tf.string:
expected_tokens = [str(t).encode() for t in expected_tokens]
expected_vocab = list(zip(expected_tokens, expected_mi))
def preprocessing_fn(inputs):
tft.vocabulary(
inputs['a'],
labels=inputs['label'],
store_frequency=True,
vocab_filename='my_vocab',
min_diff_from_avg=0.0)
return inputs
expected_data = input_data
expected_vocab_file_contents = {'my_vocab': expected_vocab}
self.assertAnalyzeAndTransformResults(
input_data,
input_metadata,
preprocessing_fn,
expected_data,
expected_metadata,
expected_vocab_file_contents=expected_vocab_file_contents)
@tft_unit.named_parameters(
dict(
testcase_name='unadjusted_mi_binary_label',
feature_label_pairs=[
(b'informative', 1),
(b'informative', 1),
(b'informative', 1),
(b'uninformative', 0),
(b'uninformative', 1),
(b'uninformative', 1),
(b'uninformative', 0),
(b'uninformative_rare', 0),
(b'uninformative_rare', 1),
],
expected_vocab=[
(b'informative', 1.7548264),
(b'uninformative', 0.33985),
(b'uninformative_rare', 0.169925),
],
use_adjusted_mutual_info=False),
dict(
testcase_name='unadjusted_mi_multi_class_label',
feature_label_pairs=[
(b'good_predictor_of_0', 0),
(b'good_predictor_of_0', 0),
(b'good_predictor_of_0', 0),
(b'good_predictor_of_1', 1),
(b'good_predictor_of_2', 2),
(b'good_predictor_of_2', 2),
(b'good_predictor_of_2', 2),
(b'good_predictor_of_1', 1),
(b'good_predictor_of_1', 1),
(b'weak_predictor_of_1', 1),
(b'good_predictor_of_0', 0),
(b'good_predictor_of_1', 1),
(b'good_predictor_of_1', 1),
(b'good_predictor_of_1', 1),
(b'weak_predictor_of_1', 0),
],
expected_vocab=[
(b'good_predictor_of_2', 6.9656615),
(b'good_predictor_of_1', 6.5969831),
(b'good_predictor_of_0', 6.3396921),
(b'weak_predictor_of_1', 0.684463),
],
use_adjusted_mutual_info=False),
dict(
testcase_name='unadjusted_mi_binary_label_with_weights',
feature_label_pairs=[
(b'informative_1', 1),
(b'informative_1', 1),
(b'informative_0', 0),
(b'informative_0', 0),
(b'uninformative', 0),
(b'uninformative', 1),
(b'informative_by_weight', 0),
(b'informative_by_weight', 1),
],
# uninformative and informative_by_weight have the same co-occurrence
# relationship with the label but will have different importance
# values due to the weighting.
expected_vocab=[
(b'informative_0', 0.316988),
(b'informative_1', 0.1169884),
(b'informative_by_weight', 0.060964),
(b'uninformative', 0.0169925),
],
weights=[.1, .1, .1, .1, .1, .1, .1, .5],
use_adjusted_mutual_info=False),
dict(
testcase_name='unadjusted_mi_binary_label_min_diff_from_avg',
feature_label_pairs=[
(b'hello', 1),
(b'hello', 1),
(b'hello', 1),
(b'goodbye', 1),
(b'aaaaa', 1),
(b'aaaaa', 1),
(b'goodbye', 0),
(b'goodbye', 0),
(b'aaaaa', 1),
(b'aaaaa', 1),
(b'goodbye', 1),
(b'goodbye', 0),
],
# All features are weak predictors, so all are adjusted to zero.
expected_vocab=[
(b'hello', 0.0),
(b'goodbye', 0.0),
(b'aaaaa', 0.0),
],
use_adjusted_mutual_info=False,
min_diff_from_avg=2),
dict(
testcase_name='adjusted_mi_binary_label',
feature_label_pairs=[
(b'hello', 1),
(b'hello', 1),
(b'hello', 1),
(b'goodbye', 1),
(b'aaaaa', 1),
(b'aaaaa', 1),
(b'goodbye', 0),
(b'goodbye', 0),
(b'aaaaa', 1),
(b'aaaaa', 1),
(b'goodbye', 1),
(b'goodbye', 0),
],
expected_vocab=[
(b'goodbye', 1.4070791),
(b'aaaaa', 0.9987449),
(b'hello', 0.5017179),
],
use_adjusted_mutual_info=True),
dict(
testcase_name='adjusted_mi_binary_label_int64_feature',
feature_label_pairs=[
(3, 1),
(3, 1),
(3, 1),
(1, 1),
(2, 1),
(2, 1),
(1, 0),
(1, 0),
(2, 1),
(2, 1),
(1, 1),
(1, 0),
],
expected_vocab=[
(b'1', 1.4070791),
(b'2', 0.9987449),
(b'3', 0.5017179),
],
feature_dtype=tf.int64,
use_adjusted_mutual_info=True),
dict(
testcase_name='adjusted_mi_multi_class_label',
feature_label_pairs=[
(b'good_predictor_of_0', 0),
(b'good_predictor_of_0', 0),
(b'good_predictor_of_0', 0),
(b'good_predictor_of_1', 1),
(b'good_predictor_of_2', 2),
(b'good_predictor_of_2', 2),
(b'good_predictor_of_2', 2),
(b'good_predictor_of_1', 1),
(b'good_predictor_of_1', 1),
(b'weak_predictor_of_1', 1),
(b'good_predictor_of_0', 0),
(b'good_predictor_of_1', 1),
(b'good_predictor_of_1', 1),
(b'good_predictor_of_1', 1),
(b'weak_predictor_of_1', 0),
],
expected_vocab=[
(b'good_predictor_of_1', 5.4800903),
(b'good_predictor_of_2', 5.386102),
(b'good_predictor_of_0', 4.9054723),
(b'weak_predictor_of_1', -0.9748023),
],
use_adjusted_mutual_info=True),
# TODO(b/128831096): Determine correct interaction between AMI and weights
dict(
testcase_name='adjusted_mi_binary_label_with_weights',
feature_label_pairs=[
(b'informative_1', 1),
(b'informative_1', 1),
(b'informative_0', 0),
(b'informative_0', 0),
(b'uninformative', 0),
(b'uninformative', 1),
(b'informative_by_weight', 0),
(b'informative_by_weight', 1),
],
# uninformative and informative_by_weight have the same co-occurrence
# relationship with the label but will have different importance
# values due to the weighting.
expected_vocab=[
(b'informative_0', 2.3029856),
(b'informative_1', 0.3029896),
(b'informative_by_weight', 0.1713041),
(b'uninformative', -0.6969697),
],
weights=[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 5.0],
use_adjusted_mutual_info=True),
dict(
testcase_name='adjusted_mi_min_diff_from_avg',
feature_label_pairs=[
(b'good_predictor_of_0', 0),
(b'good_predictor_of_0', 0),
(b'good_predictor_of_0', 0),
(b'good_predictor_of_1', 1),
(b'good_predictor_of_0', 0),
(b'good_predictor_of_1', 1),
(b'good_predictor_of_1', 1),
(b'good_predictor_of_1', 1),
(b'good_predictor_of_1', 0),
(b'good_predictor_of_0', 1),
(b'good_predictor_of_1', 1),
(b'good_predictor_of_1', 1),
(b'good_predictor_of_1', 1),
(b'weak_predictor_of_1', 1),
(b'weak_predictor_of_1', 0),
],
# With min_diff_from_avg, the small AMI value is regularized to 0
expected_vocab=[
(b'good_predictor_of_0', 1.8322128),
(b'good_predictor_of_1', 1.7554416),
(b'weak_predictor_of_1', 0),
],
use_adjusted_mutual_info=True,
min_diff_from_avg=1),
)
def testVocabularyWithMutualInformation(self,
feature_label_pairs,
expected_vocab,
weights=None,
use_adjusted_mutual_info=False,
min_diff_from_avg=0.0,
feature_dtype=tf.string):
input_data = []
for (value, label) in feature_label_pairs:
input_data.append({'x': value, 'label': label})
feature_spec = {
'x': tf.io.FixedLenFeature([], feature_dtype),
'label': tf.io.FixedLenFeature([], tf.int64)
}
if weights is not None:
feature_spec['weight'] = tf.io.FixedLenFeature([], tf.float32)
assert len(weights) == len(input_data)
for data, weight in zip(input_data, weights):
data['weight'] = weight
input_metadata = tft_unit.metadata_from_feature_spec(feature_spec)
expected_metadata = input_metadata
def preprocessing_fn(inputs):
tft.vocabulary(
inputs['x'],
labels=inputs['label'],
weights=inputs.get('weight'),
store_frequency=True,
vocab_filename='my_vocab',
use_adjusted_mutual_info=use_adjusted_mutual_info,
min_diff_from_avg=min_diff_from_avg)
return inputs
expected_data = input_data
expected_vocab_file_contents = {
'my_vocab': expected_vocab,
}
self.assertAnalyzeAndTransformResults(
input_data,
input_metadata,
preprocessing_fn,
expected_data,
expected_metadata,
expected_vocab_file_contents=expected_vocab_file_contents)
@tft_unit.named_parameters(
dict(
testcase_name='sparse_feature',
feature_input=[['world', 'hello', 'hello'], ['hello', 'world', 'foo'],
[], ['hello']],
expected_output=[[1, 0, 0], [0, 1, -99], [], [0]],
use_labels=False,
),
dict(
testcase_name='dense_feature',
feature_input=[['world', 'hello', 'hello'], ['hello', 'world', 'moo'],
['hello', 'hello', 'foo'], ['world', 'foo', 'moo']],
expected_output=[[1, 0, 0], [0, 1, -99], [0, 0, -99], [1, -99, -99]],
use_labels=False,
),
dict(
testcase_name='dense_feature_with_labels',
feature_input=[['world', 'hello', 'hi'], ['hello', 'world', 'moo'],
['hello', 'bye', 'foo'], ['world', 'foo', 'moo']],
expected_output=[[-99, -99, 1], [-99, -99, 0], [-99, -99, -99],
[-99, -99, 0]],
use_labels=True,
),
dict(
testcase_name='sparse_feature_with_labels',
feature_input=[['hello', 'world', 'bye', 'moo'],
['world', 'moo', 'foo'], ['hello', 'foo', 'moo'],
['moo']],
expected_output=[[0, -99, 1, -99], [-99, -99, -99], [0, -99, -99],
[-99]],
use_labels=True,
),
dict(
testcase_name='sparse_integer_feature_with_labels',
feature_input=[[0, 1, 3, 2],
[1, 2, 4], [0, 4, 2],
| |
the preceding }')
# If braces come on one side of an else, they should be on both.
# However, we have to worry about "else if" that spans multiple lines!
if Search(r'else if\s*\(', line): # could be multi-line if
brace_on_left = bool(Search(r'}\s*else if\s*\(', line))
# find the ( after the if
pos = line.find('else if')
pos = line.find('(', pos)
if pos > 0:
(endline, _, endpos) = CloseExpression(clean_lines, linenum, pos)
brace_on_right = endline[endpos:].find('{') != -1
if brace_on_left != brace_on_right: # must be brace after if
error(filename, linenum, 'readability/braces', 5,
'If an else has a brace on one side, it should have it on both')
elif Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line):
error(filename, linenum, 'readability/braces', 5,
'If an else has a brace on one side, it should have it on both')
# Likewise, an else should never have the else clause on the same line
if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line):
error(filename, linenum, 'whitespace/newline', 4,
'Else clause should never be on same line as else (use 2 lines)')
# In the same way, a do/while should never be on one line
if Match(r'\s*do [^\s{]', line):
error(filename, linenum, 'whitespace/newline', 4,
'do/while clauses should not be on a single line')
# Check single-line if/else bodies. The style guide says 'curly braces are not
# required for single-line statements'. We additionally allow multi-line,
# single statements, but we reject anything with more than one semicolon in
# it. This means that the first semicolon after the if should be at the end of
# its line, and the line after that should have an indent level equal to or
# lower than the if. We also check for ambiguous if/else nesting without
# braces.
if_else_match = Search(r'\b(if\s*\(|else\b)', line)
if if_else_match and not Match(r'\s*#', line):
if_indent = GetIndentLevel(line)
endline, endlinenum, endpos = line, linenum, if_else_match.end()
if_match = Search(r'\bif\s*\(', line)
if if_match:
# This could be a multiline if condition, so find the end first.
pos = if_match.end() - 1
(endline, endlinenum, endpos) = CloseExpression(clean_lines, linenum, pos)
# Check for an opening brace, either directly after the if or on the next
# line. If found, this isn't a single-statement conditional.
if (not Match(r'\s*{', endline[endpos:])
and not (Match(r'\s*$', endline[endpos:])
and endlinenum < (len(clean_lines.elided) - 1)
and Match(r'\s*{', clean_lines.elided[endlinenum + 1]))):
while (endlinenum < len(clean_lines.elided)
and ';' not in clean_lines.elided[endlinenum][endpos:]):
endlinenum += 1
endpos = 0
if endlinenum < len(clean_lines.elided):
endline = clean_lines.elided[endlinenum]
# We allow a mix of whitespace and closing braces (e.g. for one-liner
# methods) and a single \ after the semicolon (for macros)
endpos = endline.find(';')
if not Match(r';[\s}]*(\\?)$', endline[endpos:]):
# Semicolon isn't the last character, there's something trailing.
# Output a warning if the semicolon is not contained inside
# a lambda expression.
if not Match(r'^[^{};]*\[[^\[\]]*\][^{}]*\{[^{}]*\}\s*\)*[;,]\s*$',
endline):
error(filename, linenum, 'readability/braces', 4,
'If/else bodies with multiple statements require braces')
elif endlinenum < len(clean_lines.elided) - 1:
# Make sure the next line is dedented
next_line = clean_lines.elided[endlinenum + 1]
next_indent = GetIndentLevel(next_line)
# With ambiguous nested if statements, this will error out on the
# if that *doesn't* match the else, regardless of whether it's the
# inner one or outer one.
if (if_match and Match(r'\s*else\b', next_line)
and next_indent != if_indent):
error(filename, linenum, 'readability/braces', 4,
'Else clause should be indented at the same level as if. '
'Ambiguous nested if/else chains require braces.')
elif next_indent > if_indent:
error(filename, linenum, 'readability/braces', 4,
'If/else bodies with multiple statements require braces')
def CheckTrailingSemicolon(filename, clean_lines, linenum, error):
"""Looks for redundant trailing semicolon.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# Block bodies should not be followed by a semicolon. Due to C++11
# brace initialization, there are more places where semicolons are
# required than not, so we use a whitelist approach to check these
# rather than a blacklist. These are the places where "};" should
# be replaced by just "}":
# 1. Some flavor of block following closing parenthesis:
# for (;;) {};
# while (...) {};
# switch (...) {};
# Function(...) {};
# if (...) {};
# if (...) else if (...) {};
#
# 2. else block:
# if (...) else {};
#
# 3. const member function:
# Function(...) const {};
#
# 4. Block following some statement:
# x = 42;
# {};
#
# 5. Block at the beginning of a function:
# Function(...) {
# {};
# }
#
# Note that naively checking for the preceding "{" will also match
# braces inside multi-dimensional arrays, but this is fine since
# that expression will not contain semicolons.
#
# 6. Block following another block:
# while (true) {}
# {};
#
# 7. End of namespaces:
# namespace {};
#
# These semicolons seems far more common than other kinds of
# redundant semicolons, possibly due to people converting classes
# to namespaces. For now we do not warn for this case.
#
# Try matching case 1 first.
match = Match(r'^(.*\)\s*)\{', line)
if match:
# Matched closing parenthesis (case 1). Check the token before the
# matching opening parenthesis, and don't warn if it looks like a
# macro. This avoids these false positives:
# - macro that defines a base class
# - multi-line macro that defines a base class
# - macro that defines the whole class-head
#
# But we still issue warnings for macros that we know are safe to
# warn, specifically:
# - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P
# - TYPED_TEST
# - INTERFACE_DEF
# - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:
#
# We implement a whitelist of safe macros instead of a blacklist of
# unsafe macros, even though the latter appears less frequently in
# google code and would have been easier to implement. This is because
# the downside for getting the whitelist wrong means some extra
# semicolons, while the downside for getting the blacklist wrong
# would result in compile errors.
#
# In addition to macros, we also don't want to warn on
# - Compound literals
# - Lambdas
# - alignas specifier with anonymous structs
# - decltype
closing_brace_pos = match.group(1).rfind(')')
opening_parenthesis = ReverseCloseExpression(
clean_lines, linenum, closing_brace_pos)
if opening_parenthesis[2] > -1:
line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]]
macro = Search(r'\b([A-Z_][A-Z0-9_]*)\s*$', line_prefix)
func = Match(r'^(.*\])\s*$', line_prefix)
if ((macro and
macro.group(1) not in (
'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST',
'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED',
'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or
(func and not Search(r'\boperator\s*\[\s*\]', func.group(1))) or
Search(r'\b(?:struct|union)\s+alignas\s*$', line_prefix) or
Search(r'\bdecltype$', line_prefix) or
Search(r'\s+=\s*$', line_prefix)):
match = None
if (match and
opening_parenthesis[1] > 1 and
Search(r'\]\s*$', clean_lines.elided[opening_parenthesis[1] - 1])):
# Multi-line lambda-expression
match = None
else:
# Try matching cases 2-3.
match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line)
if not match:
# Try matching cases 4-6. These are always matched on separate lines.
#
# Note that we can't simply concatenate the previous line to the
# current line and do a single match, otherwise we may output
# duplicate warnings for the blank line case:
# if (cond) {
# // blank line
# }
prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
if prevline and Search(r'[;{}]\s*$', prevline):
match = Match(r'^(\s*)\{', line)
# Check matching closing brace
if match:
(endline, endlinenum, endpos) = CloseExpression(
clean_lines, linenum, len(match.group(1)))
if endpos > -1 and Match(r'^\s*;', endline[endpos:]):
# Current {} pair is eligible for semicolon check, and we have found
# the redundant semicolon, output warning here.
#
# Note: because we are scanning forward for opening braces, and
# outputting warnings for the matching closing brace, if there are
# nested blocks with trailing semicolons, we will get the error
# messages in reversed order.
# We need to check the line forward | |
delete this lval.
if ccp_attr.value_type == 'integer':
field_val = None
try:
field_val = int(shpfeat['properties'][field_name])
except KeyError:
# Not set in source Shapefile, so just ignore.
pass
except TypeError:
log.warning(
'edited_item_update_item: field not integer: %s / %s'
% (field_name, shpfeat,))
if field_val:
if field_val < 0:
self.delete_lval_attc(the_item, ccp_attr)
self.stats['edit_attr_delete'] += 1
updated_item |= 0x0100
# MAGIC_NUMBER: We ignore '0' or unset from the source;
# if user wants to be deliberate, they can
# use -1 to delete the value. But a 0 or
# null shouldn't cause existing val to reset.
elif field_val > 0:
try:
if the_item.attrs[attr_name] != field_val:
self.update_lval_attc(the_item, ccp_attr,
value_integer=field_val, value_text=None)
self.stats['edit_attr_edit'] += 1
updated_item |= 0x0200
except KeyError:
# the_item.attrs[attr_name] n/a
self.add_new_lval_attc(the_item, ccp_attr,
value_integer=field_val, value_text=None)
self.stats['edit_attr_add'] += 1
# else, field_val is 0 or None, so ignore it.
elif ccp_attr.value_type == 'text':
field_val = None
try:
field_val = shpfeat['properties'][field_name]
except KeyError:
# Not set in source Shapefile, so just ignore.
pass
if field_val:
try:
if the_item.attrs[attr_name] != field_val:
self.update_lval_attc(the_item, ccp_attr,
value_integer=None, value_text=field_val)
self.stats['edit_attr_edit'] += 1
updated_item |= 0x0400
except KeyError:
# the_item.attrs[attr_name] n/a
self.add_new_lval_attc(the_item, ccp_attr,
value_integer=None, value_text=field_val)
self.stats['edit_attr_add'] += 1
else:
g.assurt(False)
# end: for field_name, ccp_attr in self.field_attr_cache_name.iteritems()
add_tags_raw, del_tags_raw = self.tag_list_assemble(shpfeat)
# Ug: user tags are not always lowercase, e.g., on byway:1077570
# is CAUTION.
item_tags = set([x.lower() for x in the_item.tagged])
if add_tags_raw != item_tags:
add_tags = add_tags_raw.difference(item_tags)
del_tags = item_tags.difference(add_tags_raw)
# Not necessary: del_tags += del_tags_raw
# that is, we delete tags that are not referenced in Shapefile.
for tag_name in add_tags:
self.add_new_tag_lval(the_item, tag_name)
self.stats['edit_tag_add'] += 1
misc.dict_count_inc(self.stats['edit_tag_add_name'], tag_name)
updated_item |= 0x1000
for tag_name in del_tags:
the_lval = None
the_tag = self.qb.item_mgr.cache_tag_lookup_by_name(tag_name)
for lval in the_item.link_values.itervalues():
if lval.lhs_stack_id == the_tag.stack_id:
the_lval = lval
break
if the_lval is not None:
self.edited_item_delete_item(the_lval, self.update_lvals)
self.stats['items_delete_lval'] += 1
# 37,104 times on 50,000 features! It's the erroneous
# unpaved/gravel tags that were applied to the state data...
self.stats['edit_tag_delete'] += 1
misc.dict_count_inc(self.stats['edit_tag_del_name'], tag_name)
updated_item |= 0x2000
else:
log.error('tagged indicates tag but not in cache: %s / %s'
% (tag_name, the_item,))
if updated_item and (self.cli_opts.item_type == 'byway'):
the_item.generic_rating_calc(self.qb)
#
def update_lval_attc(self, the_item, lhs_item, value_integer=None,
value_text=None):
try:
the_lval = the_item.link_values[lhs_item.stack_id]
self.update_lval_lval(the_lval, value_integer, value_text)
self.stats['items_edit_lval'] += 1
except KeyError:
log.error('where is the heavyweight lval?: %s / %s'
% (the_item, lhs_item,))
#
def delete_lval_attc(self, the_item, lhs_item):
try:
the_lval = the_item.link_values[lhs_item.stack_id]
the_lval.deleted = True
self.update_lval_lval(the_lval, the_lval.value_integer,
the_lval.value_text)
self.stats['items_delete_lval'] += 1
except KeyError:
log.error('where is the heavyweight lval?: %s / %s'
% (the_item, lhs_item,))
#
def update_lval_lval(self, the_lval, value_integer=None, value_text=None):
the_lval.value_integer = value_integer
the_lval.value_text = value_text
if (not the_lval.fresh) and (not the_lval.valid):
the_lval.system_id = self.qb.db.sequence_get_next(
'item_versioned_system_id_seq')
the_lval.version += 1
the_lval.acl_grouping = 1
the_lval.valid_start_rid = self.qb.item_mgr.rid_new
#
the_lval.clear_item_revisionless_defaults()
the_lval.validize(
self.qb,
is_new_item=False,
dirty_reason=item_base.One.dirty_reason_item_auto,
ref_item=None)
g.assurt(the_lval.stack_id > 0)
g.assurt(the_lval.stack_id not in self.update_lvals)
self.update_lvals[the_lval.stack_id] = the_lval
else:
g.assurt(
(the_lval.fresh and (the_lval.stack_id in self.create_lvals))
or (the_lval.valid and (the_lval.stack_id in self.update_lvals)))
#
def edited_item_delete_item(self, the_item, update_dict):
# MAYBE: The delete is applied to the database immediately.
# We might want to try to bulk-process deleting, like
# we do adding and updating items.
if the_item.deleted:
log.error('process_split_from: the_item already marked deleted?: %s'
% (str(the_item),))
else:
#log.debug('edited_item_delete_item: mark deleted: %s' % (the_item,))
g.assurt(not the_item.valid)
# The mark_deleted command updates that database immediately.
# MAYBE: It also expects self.qb.grac_mgr to be set, which
# we could easily do, but let's try bulk-delete instead.
# g.assurt(self.qb.grac_mgr is None)
# self.qb.grac_mgr = Grac_Manager()
# the_item.mark_deleted(self.qb, f_process_item_hydrated=None)
the_item.system_id = self.qb.db.sequence_get_next(
'item_versioned_system_id_seq')
the_item.version += 1
the_item.acl_grouping = 1
the_item.deleted = True
the_item.valid_start_rid = self.qb.item_mgr.rid_new
#
try:
if the_item.geometry_changed is None:
the_item.geometry_changed = False
except AttributeError:
try:
the_item.geometry_changed = False
# Wasn't set; now it is.
except AttributeError:
pass # Not a geofeature.
#
try:
if not the_item.geometry_wkt.startswith('SRID='):
the_item.geometry_wkt = (
'SRID=%d;%s' % (conf.default_srid, the_item.geometry_wkt,))
except AttributeError:
pass # Not a geofeature.
#
g.assurt(the_item.stack_id not in update_dict)
update_dict[the_item.stack_id] = the_item
#
try:
# FIXME/VERIFY: the_item.link_values should be non-multi lvals,
# like notes, normal attrs, tags, and discussions/posts.
for lval in the_item.link_values.itervalues():
# MAYBE: Do not delete the discussion/posts links...
if lval.link_lhs_type_id in set([Item_Type.TAG,
Item_Type.ATTRIBUTE,
Item_Type.ANNOTATION,]):
# EXPLAIN: This is just so checking out all current
# link_values when populating the cache is faster,
# right?
self.edited_item_delete_item(lval, self.update_lvals)
self.stats['items_delete_lval'] += 1
except AttributeError:
pass # the_item.link_values is None.
# BUG nnnn: Our db contains uppercase chars in tag names...
# seems silly, even if our software always does
# lower().
#
bug_nnnn_bad_tags = ('gravel road', 'unpaved',)
#
def tag_list_assemble(self, shpfeat, check_disconnected=False):
add_tags = set()
del_tags = set()
try:
for tag_name in shpfeat['properties']['item_tags'].split(','):
tag_name = tag_name.strip().lower()
if tag_name:
if tag_name.startswith('-'):
del_tags.add(tag_name)
else:
add_tags.add(tag_name)
if self.cli_opts.fix_gravel_unpaved_issue:
ccp_stack_id = ojint(shpfeat['properties']['CCP_ID'])
if ( (ccp_stack_id >= self.cli_opts.first_suspect)
and (ccp_stack_id <= self.cli_opts.final_suspect)):
for bad_tag in Hausdorff_Import.bug_nnnn_bad_tags:
try:
add_tags.remove(bad_tag)
except KeyError:
pass
del_tags.add(bad_tag)
except AttributeError:
# AttributeError: 'NoneType' object has no attribute 'split'
# i.e., shpfeat['properties']['item_tags'] is None.
pass
# MAGIC_NAME: New disconnected tag.
if ((check_disconnected)
and (self.cli_opts.item_type == 'byway')):
# 2014.07.23: Nowadays the route planner handles is_disconnected.
try:
if shpfeat['properties']['wconnected'] == '1':
del_tags.add('disconnected')
else:
add_tags.add('disconnected')
except KeyError:
pass
return add_tags, del_tags
#
def consolidate_duplisplits(self, shpfeat, target_item, source_item,
first_ref):
# If OPERATION contains a stack ID, it means the feature/item is being
# deleted because it's a duplicate of another item. If CCP_FROMS_
# contains a stack ID, it means the feature/item being created or
# edited should get a clone of the reference item's lvals, etc.
# Skipping: geometry. This is a clone of metadata, not of geometry.
# We only consume values that aren't set in the target, i.e., we won't
# overwrite existing target_item attributes or lvals.
# See: edited_item_update_item(), which is similar, but compares a
# Cyclopath item to a Shapefile feature.
self.merge_byway_fields(shpfeat, target_item, source_item, first_ref)
self.merge_non_user_lvals(shpfeat, target_item, source_item)
self.merge_byway_aadt(shpfeat, target_item, source_item)
self.merge_byway_ratings(shpfeat, target_item, source_item)
self.merge_user_lvals(shpfeat, target_item, source_item)
#
def merge_byway_fields(self, shpfeat, target_item, source_item, first_ref):
# MAGIC_NUMBERS: This binary values ORed together are just for debugging.
# What matters is if the value is 0 or not -- if it's not
# 0, we edited the item and new to save a new version.
updated_item = 0x0000
# Do this first, so cleanup_byway_name has an accurate value.
if ((not target_item.geofeature_layer_id)
and source_item.geofeature_layer_id):
gf_lyr_id, gf_lyr_name = (
self.qb.item_mgr.geofeature_layer_resolve(
self.qb.db, source_item.geofeature_layer_id))
target_item.geofeature_layer_id = gf_lyr_id
shpfeat['properties']['gf_lyr_id'] = gf_lyr_id
shpfeat['properties']['gf_lyr_nom'] = gf_lyr_name
updated_item |= 0x0002
self.stats['split_gfl_id'] += 1
elif target_item.geofeature_layer_id != source_item.geofeature_layer_id:
self.stats['diffs_gfl_id'] += 1
# else, they're equal.
if (not target_item.name) and source_item.name:
target_item.name = source_item.name
updated_item |= 0x0001
self.stats['split_ccp_name'] += 1
elif (target_item.name
and source_item.name
and (target_item.name != source_item.name)):
self.stats['diffs_ccp_name'] += 1
if self.cli_opts.merge_names:
if target_item.name.startswith(source_item.name):
# Already got similar, but elongated, name.
#log.debug('mrg_by_flds: keep longer target name: "%s" ==> "%s"'
# % (source_item.name, target_item.name,))
pass
elif source_item.name.startswith(target_item.name):
# Source name starts with target name but is longer.
# MN Stk IDs: 2920672.
#log.debug('mrg_by_flds: swap longer source name: "%s" ==> "%s"'
# % (target_item.name, source_item.name,))
target_item.name = source_item.name
updated_item |= 0x0001
else:
# We preference the old name by default, since we assume our
# map data is better than the data we're importing!
unclean_merge = '/'.join([source_item.name, target_item.name,])
target_item.name = self.cleanup_byway_name(unclean_merge,
target_item)
updated_item |= 0x0001
#log.debug('mrg_by_flds: merged route names: "%s" ==> "%s"'
# % (target_item.name, source_item.name,))
# else, the names are equal.
shpfeat['properties']['CCP_NAME'] = target_item.name
# BUG nnnn: z-levels for polygons? Or are they just hard-coded?
#
if not target_item.z:
target_item.z = byway.One.z_level_med
if not source_item.z:
source_item.z = byway.One.z_level_med
if ( (target_item.z != byway.One.z_level_med) # != 134
or (source_item.z != byway.One.z_level_med)):
if ( (target_item.z == byway.One.z_level_med)
and (source_item.z != byway.One.z_level_med)):
target_item.z = source_item.z
updated_item |= 0x0004
self.stats['split_z_level'] += 1
elif target_item.z != source_item.z:
self.stats['diffs_z_level'] += 1
# else, they're equal.
shpfeat['properties']['z_level'] = target_item.z
if (not target_item.one_way) and source_item.one_way:
target_item.one_way = source_item.one_way
shpfeat['properties']['one_way'] = target_item.one_way
updated_item |= 0x0008
self.stats['split_one_way'] += 1
elif target_item.one_way != source_item.one_way:
self.stats['diffs_one_way'] += 1
# else, they're equal.
# NOTE: The split_from_stack_id isn't important, or at least
# nothing is implemented that | |
from selenium import webdriver, common
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import math
import time
import os
import demjson
driver = None
all_pokemon_data = demjson.decode(open('pokemon_data.txt', 'r').read())
own_team = []
opponent_team = [None, None, None, None, None, None]
game_state = {'rocks':False, 'spikes': 0, 'tspikes': 0, 'weather':'none', 'trickroom':False, 'terrain':'none'}
turn = 0
own_mon_out = None
opponent_mon_out = None
def open_window(url):
"""Opens window"""
my_dir = os.path.dirname(__file__)
chrome_path = os.path.join(my_dir, 'chromedriver')
new_driver = webdriver.Chrome(chrome_path)
new_driver.get(url)
global driver
driver = new_driver
driver.implicitly_wait(3)
def log_out():
driver.find_element_by_name("openOptions").click()
try:
driver.find_element_by_name("logout").click()
driver.find_element_by_tag_name("strong").click()
except common.exceptions.NoSuchElementException:
pass
driver.refresh()
def log_in(username, password):
log_out()
logged_in = False
driver.find_element_by_name("login").click()
username_field = driver.find_element_by_name("username")
username_field.send_keys(username)
username_field.send_keys(Keys.RETURN)
try:
password_field = driver.find_element_by_name("password")
password_field.send_keys(password)
password_field.send_keys(Keys.RETURN)
except common.exceptions.NoSuchElementException:
logged_in = True
try:
driver.find_element_by_name("input")
logged_in = False
except common.exceptions.NoSuchElementException:
logged_in = True
return logged_in
def start():
open_window("https://play.pokemonshowdown.com")
time.sleep(2)
log_in("cs232-test-5", "cs232")
def find_randbat():
driver.find_element_by_name("search").click()
def act(action, switch=False):
"""Take an action (a move name or a Pokémon name) as a parameter and whether the action is a switch."""
if switch:
pokemon_buttons = driver.find_elements_by_name("chooseSwitch")
for pokemon in pokemon_buttons:
if pokemon.text == action:
pokemon.click()
return True
else:
move_buttons = driver.find_elements_by_name("chooseMove")
for move in move_buttons:
if move.text.split('\n')[0] == action:
move.click()
return True
return False
def send_out_team_preview(pokemon_name):
pokemon_buttons = driver.find_elements_by_name("chooseTeamPreview")
for pokemon in pokemon_buttons:
if pokemon.text == pokemon_name:
pokemon.click()
return True
return False
def send_out_after_KO(pokemon_name):
act(pokemon_name, True)
def mega_evolve():
try:
driver.find_element_by_class("megaevo").click()
return True
except common.exceptions.NoSuchElementException:
return False
def get_preview_options():
options = []
pokemon_buttons = driver.find_elements_by_name("chooseTeamPreview")
for pokemon in pokemon_buttons:
options.append(pokemon.text)
return options
def get_move_options():
moves = []
move_buttons = driver.find_elements_by_name("chooseMove")
for move in move_buttons:
moves.append(move.text.split('\n')[0])
return moves
def get_switch_options():
pokemon_list = []
pokemon_buttons = driver.find_elements_by_name("chooseSwitch")
for pokemon in pokemon_buttons:
pokemon_list.append(pokemon.text)
return pokemon_list
def get_own_team():
"""Precondition: first turn. Returns all Pokémon, including stats, moves and items."""
pokemon_list = []
current_mon = driver.find_element_by_name("chooseDisabled")
hover = ActionChains(driver).move_to_element(current_mon)
hover.perform()
pokemon = driver.find_element_by_id("tooltipwrapper")
pokemon_list.append(parse_own_team(pokemon))
benched_mons = driver.find_elements_by_name("chooseSwitch")
for mon in benched_mons:
hover = ActionChains(driver).move_to_element(mon)
hover.perform()
pokemon_list.append(parse_own_team(driver.find_element_by_id("tooltipwrapper")))
global own_team
own_team = pokemon_list
return pokemon_list
def parse_own_team(element):
text = element.text
# Get health
text = text.split("\n")
name = " ".join(text[0].split(" ")[:len(text[0].split(" "))-1])
level = int(text[0].split(" ")[len(text[0].split(" ")) - 1][1:])
current_health = int(text[1].split(" ")[2].split("/")[0][1:])
total_health_text = text[1].split(" ")[2].split("/")[1]
total_health = int(total_health_text[0:len(total_health_text) - 1])
# Get ability and item
temp = text[2].split(" / ")
try:
ability = " ".join(temp[0].split(" ")[1:])
item = " ".join(temp[1].split(" ")[1:])
except IndexError:
ability = " ".join(temp[0].split(" ")[1:])
# Get stats
stats = text[3].split("/")
temp = []
for i in range(0,5):
pieces = stats[i].split(" ")
for piece in pieces:
if piece != "":
temp.append(int(piece))
break
stats = temp
# Get moves
moves = []
try:
for i in range(4, 8):
moves.append(text[i][2:])
except IndexError:
pass
for move in moves:
query_data(move)
time.sleep(2)
moves = [parse_move_text(i) for i in moves]
images = element.find_elements_by_tag_name("img")
types = []
for image in images:
if image.get_attribute("alt") is not "M" and image.get_attribute("alt") is not "F":
types.append(image.get_attribute("alt"))
if len(types) == 1:
types.append('none')
return Pokemon(name, level, types, moves, item, ability, current_health, total_health, stats)
def query_data(data):
textbox = driver.find_element_by_class_name("battle-log-add").find_elements_by_class_name("textbox")[1]
textbox.send_keys("/data " + data)
textbox.send_keys(Keys.ENTER)
def retrieve_data():
return driver.find_elements_by_class_name("utilichart")
def calc_stats(base_stats, level):
stats = []
stats.append(math.floor((31 + 2 * base_stats[0] + 21) * level/100 + 10 + level))
for i in range(1, 6):
stats.append(math.floor((31 + 2 * base_stats[i] + 21) * level/100 + 5))
return stats
def get_base_stats(mon):
query_data(mon)
time.sleep(1)
all_mons = retrieve_data()
base_stats = []
for pokemon in all_mons:
try:
if pokemon.text.split('\n')[1] == mon:
stat_list = pokemon.find_elements_by_class_name("statcol")
for stat in stat_list:
base_stats.append(int(stat.text.split("\n")[1]))
break
except IndexError:
pass
try:
assert len(base_stats) != 0
except AssertionError:
time.sleep(2)
base_stats = get_base_stats(mon)
return base_stats
def get_possible_moves(name):
return all_pokemon_data[name.replace(" ", "").lower()]['randomBattleMoves']
def handle_list_moves(moves):
for move in moves:
query_data(move)
time.sleep(2)
parsed_moves = [parse_move_text(i) for i in moves]
return parsed_moves
def parse_opposing_mon():
# Get element with data
enemy_mon = driver.find_element_by_class_name("foehint").find_elements_by_tag_name("div")[2]
hover = ActionChains(driver).move_to_element(enemy_mon)
hover.perform()
tooltip = driver.find_element_by_id("tooltipwrapper")
help_text = tooltip.text.split("\n")
name_temp = help_text[0].split(" ")
name = " ".join(name_temp[:len(name_temp) - 1])
level = int(name_temp[len(name_temp) - 1][1:])
base_stats = get_base_stats(name)
stats = calc_stats(base_stats, level)
images = tooltip.find_elements_by_tag_name("img")
types = []
for image in images:
if image.get_attribute("alt") is not "M" and image.get_attribute("alt") is not "F":
types.append(image.get_attribute("alt"))
if len(types) == 1:
types.append('none')
moves = handle_list_moves(get_possible_moves(name))
new_mon = Pokemon(name, level, types, moves, None, None, stats[0], stats[0], stats[1:])
if new_mon not in opponent_team:
for i in range(0, len(opponent_team)):
if opponent_team[i] is None:
opponent_team[i] = new_mon
break
return new_mon
class Pokemon:
def __init__(self, name=None, level=None, type=None, moves=None, item=None, ability=None, presenthealth=None,
totalhealth=None, stats=None, statuses={}, mon=None):
if mon is None:
self.name = name
self.level = level
self.type = type
self.moves = moves
self.item = item
self.ability = ability
self.stats = stats
self.present_health = presenthealth
self.total_health = totalhealth
self.health_percent = presenthealth/totalhealth
self.statuses = statuses
else:
# For form changes ????
self.name = name
self.level = mon.level
self.type = type
self.moves = mon.moves
self.ability = ability
self.present_health = mon.presenthealth
self.total_health = mon.totalhealth
self.stat = stats
self.statuses = mon.statuses
def get_health_percent(self):
self.health_percent = self.present_health/self.total_health
return self.health_percent
def __eq__(self, other):
"""Note that this definition of equality breaks down when comparing Pokémon on opposite teams"""
if self is None:
return False
elif other is None:
return False
else:
return self.name == other.name
def __str__(self):
return self.name
def damage_calc(self, enemy_move, enemy_mon):
enemy_stats = enemy_mon.calc_effective_stats()
my_stats = self.calc_effective_stats()
damage = 0
if enemy_move.category == 'Physical':
damage = \
(((2*enemy_mon.level/5 + 2) * enemy_stats[0]*enemy_move.power/my_stats[1])/50 + 2) * 93/100
elif enemy_move.category == 'Special':
damage = \
(((2*enemy_mon.level/5 + 2) * enemy_stats[2]*enemy_move.power/my_stats[3])/50 + 2) * 93/100
if enemy_move.type in enemy_mon.type:
damage *= 1.5
damage *= self.calculate_type_multiplier(enemy_move.type)
return damage
def calc_effective_stats(self):
real_stats = []
for i in range(0, len(self.stats)):
if i == 0:
# dealing with attack
atk_mod = 1
if "BRN" in self.statuses:
atk_mod *= 0.5
if "Atk" in self.statuses:
atk_mod *= self.statuses["Atk"]
real_stats.append(self.stats[i] * atk_mod)
elif i == 1:
# dealing with defense
try:
real_stats.append(self.stats[i] * self.statuses["Def"])
except KeyError:
real_stats.append(self.stats[i])
elif i == 2:
try:
real_stats.append(self.stats[i] * self.statuses["SpA"])
except KeyError:
real_stats.append(self.stats[i])
elif i == 3:
try:
real_stats.append(self.stats[i] * self.statuses["SpD"])
except KeyError:
real_stats.append(self.stats[i])
elif i == 4:
spe_mod = 1
if "PAR" in self.statuses:
spe_mod *= 0.25
if "Spe" in self.statuses:
spe_mod *= self.statuses["Spe"]
real_stats.append(self.stats[i] * spe_mod)
return real_stats
def calculate_type_multiplier(self, move_type):
type_chart = {
"Normal": {"Rock": .5, "Steel": .5, "Ghost": 0},
"Fighting":{"Normal": 2, "Rock": 2, "Steel": 2, "Ice": 2, "Dark": 2, "Psychic": .5,
"Flying": .5, "Poison": .5, "Bug": .5, "Fairy": .5, "Ghost": 0},
"Dragon":{"Dragon": 2, "Steel": .5, "Fairy": 0},
"Fairy":{"Dragon": 2, "Fighting": 2, "Dark": 2, "Poison": .5, "Steel": .5, "Fire": .5},
"Steel":{"Fairy": 2, "Rock": 2, "Ice": 2, "Steel": .5, "Fire": .5, "Water": .5, "Electric": .5},
"Fire": {"Grass": 2, "Bug": 2, "Steel": 2, "Water": .5, "Rock": .5, "Fire": .5, "Dragon": .5},
"Water":{"Fire": 2, "Rock": 2, "Ground": 2, "Grass": .5, "Water": .5, "Dragon": .5},
"Grass":{"Water": 2, "Rock": 2, "Ground": 2, "Flying": .5, "Fire": .5, "Grass": .5, "Bug": .5,
"Poison": .5, "Steel": .5, "Dragon": .5},
"Bug":{"Grass": 2, "Psychic": 2, "Dark": 2, "Fighting": .5, "Flying": .5, "Poison": .5, "Ghost": .5,
"Steel": .5, "Fire": .5, "Fairy": .5},
"Rock":{"Ice": 2, "Fire": 2, "Flying": 2, "Bug": 2, "Steel": .5, "Fighting": .5, "Ground": .5},
"Ground":{"Fire": 2, "Electric": 2, "Rock": 2, "Steel": 2, "Poison": 2, "Grass": .5, "Bug": .5,
"Flying": 0},
"Electric":{"Water": 2, "Flying": 2, "Grass": .5, "Electric": .5, "Dragon": .5, "Ground": 0},
"Dark":{"Psychic": 2, "Ghost": 2, "Fighting": .5, "Dark": .5, "Fairy": .5},
"Ghost":{"Ghost": 2, "Psychic": 2, "Dark": .5, "Normal": 0},
"Flying":{"Bug": 2, "Grass": 2, "Fighting": 2, "Rock": .5, "Steel": .5, "Electric": .5},
"Poison":{"Grass": 2, "Fairy": 2, "Poison": .5, "Ground": .5, "Rock": .5, "Ghost": .5, "Steel": 0},
"Psychic":{"Fighting": 2, "Poison": 2, "Psychic": .5, "Steel": .5, "Dark": 0},
"Ice":{"Dragon": 2, "Flying": 2, "Ground": 2, "Grass": 2, "Steel": .5, "Fire": .5,
"Water": .5, "Ice": .5}
}
multiplier = 1
if self.type[0] in type_chart[move_type]:
multiplier *= type_chart[move_type][self.type[0]]
if self.type[1] in type_chart[move_type]:
multiplier *= type_chart[move_type][self.type[1]]
return multiplier
class Move:
def __init__(self, type, power, category, text=None, name=None):
self.type = type
self.power = power
self.category = category
self.text = text
self.name = name
def __eq__(self, other):
return self.type == other.type and self.power == other.power and self.category == other.category
def parse_move_text(move):
all_stuff = retrieve_data()
move_data = None
move_name = None
for item in all_stuff:
move_name = item.text.split('\n')[0]
if move_name == move or move_name.replace(" ", "").replace("-", "").lower() == move:
move_data = item
| |
<reponame>jalalium/pyccel<filename>tests/pyccel/test_pyccel.py
# pylint: disable=missing-function-docstring, missing-module-docstring/
import subprocess
import os
import shutil
import sys
import re
import pytest
import numpy as np
#==============================================================================
# UTILITIES
#==============================================================================
#------------------------------------------------------------------------------
def get_abs_path(relative_path):
relative_path = os.path.normpath(relative_path)
base_dir = os.path.dirname(os.path.realpath(__file__))
return os.path.join(base_dir, relative_path)
#------------------------------------------------------------------------------
def get_exe(filename, language=None):
if language!="python":
exefile1 = os.path.splitext(filename)[0]
else:
exefile1 = filename
if sys.platform == "win32" and language!="python":
exefile1 += ".exe"
dirname = os.path.dirname(filename)
basename = "prog_"+os.path.basename(exefile1)
exefile2 = os.path.join(dirname, basename)
if os.path.isfile(exefile2):
return exefile2
else:
assert(os.path.isfile(exefile1))
return exefile1
#------------------------------------------------------------------------------
def insert_pyccel_folder(abs_path):
base_dir = os.path.dirname(abs_path)
base_name = os.path.basename(abs_path)
return os.path.join(base_dir, "__pyccel__", base_name)
#------------------------------------------------------------------------------
def get_python_output(abs_path, cwd = None):
if cwd is None:
p = subprocess.Popen([sys.executable , "%s" % abs_path], stdout=subprocess.PIPE, universal_newlines=True)
else:
p = subprocess.Popen([sys.executable , "%s" % abs_path], stdout=subprocess.PIPE, universal_newlines=True, cwd=cwd)
out, _ = p.communicate()
assert(p.returncode==0)
return out
#------------------------------------------------------------------------------
def compile_pyccel(path_dir,test_file, options = ""):
if "python" in options and "--output" not in options:
options += " --output=__pyccel__"
cmd = [shutil.which("pyccel"), "%s" % test_file]
if options != "":
cmd += options.strip().split(' ')
p = subprocess.Popen(cmd, universal_newlines=True, cwd=path_dir)
p.wait()
assert(p.returncode==0)
#------------------------------------------------------------------------------
def compile_c(path_dir,test_file,dependencies,is_mod=False):
compile_fortran_or_c('gcc', '.c', path_dir,test_file,dependencies,is_mod)
#------------------------------------------------------------------------------
def compile_fortran(path_dir,test_file,dependencies,is_mod=False):
compile_fortran_or_c('gfortran', '.f90', path_dir,test_file,dependencies,is_mod)
#------------------------------------------------------------------------------
def compile_fortran_or_c(compiler,extension,path_dir,test_file,dependencies,is_mod=False):
root = insert_pyccel_folder(test_file)[:-3]
assert(os.path.isfile(root+extension))
deps = [dependencies] if isinstance(dependencies, str) else dependencies
if not is_mod:
base_dir = os.path.dirname(root)
base_name = os.path.basename(root)
prog_root = os.path.join(base_dir, "prog_"+base_name)
if os.path.isfile(prog_root+extension):
compile_fortran(path_dir, test_file, dependencies, is_mod = True)
dependencies.append(test_file)
root = prog_root
if is_mod:
command = [shutil.which(compiler), "-c", root+extension]
else:
command = [shutil.which(compiler), "-O3", root+extension]
for d in deps:
d = insert_pyccel_folder(d)
command.append(d[:-3]+".o")
command.append("-I"+os.path.dirname(d))
command.append("-o")
if is_mod:
command.append("%s.o" % root)
else:
command.append("%s" % test_file[:-3])
p = subprocess.Popen(command, universal_newlines=True, cwd=path_dir)
p.wait()
#------------------------------------------------------------------------------
def get_lang_output(abs_path, language):
abs_path = get_exe(abs_path, language)
if language=="python":
return get_python_output(abs_path)
else:
p = subprocess.Popen(["%s" % abs_path], stdout=subprocess.PIPE, universal_newlines=True)
out, _ = p.communicate()
assert(p.returncode==0)
return out
#------------------------------------------------------------------------------
def get_value(string, regex, conversion):
match = regex.search(string)
assert(match)
value = conversion(match.group())
string = string[match.span()[1]:]
return value, string
def compare_pyth_fort_output_by_type( p_output, f_output, dtype=float, language=None):
if dtype is str:
p_list = [e.strip() for e in re.split('\n', p_output)]
f_list = [e.strip() for e in re.split('\n', f_output)]
assert(p_list==f_list)
elif dtype is complex:
rx = re.compile('[-0-9.eEj]+')
p, p_output = get_value(p_output, rx, complex)
if p.imag == 0:
p2, p_output = get_value(p_output, rx, complex)
p = p+p2
if language == 'python':
f, f_output = get_value(f_output, rx, complex)
if f.imag == 0:
f2, f_output = get_value(f_output, rx, complex)
f = f+f2
else:
rx = re.compile('[-0-9.eE]+')
f, f_output = get_value(f_output, rx, float)
f2, f_output = get_value(f_output, rx, float)
f = f+f2*1j
assert(np.isclose(p,f))
elif dtype is bool:
rx = re.compile('TRUE|True|true|1|T|t|FALSE|False|false|F|f|0')
bool_conversion = lambda m: m.lower() in ['true', 't', '1']
p, p_output = get_value(p_output, rx, bool_conversion)
f, f_output = get_value(f_output, rx, bool_conversion)
assert(p==f)
elif dtype is float:
rx = re.compile('[-0-9.eE]+')
p, p_output = get_value(p_output, rx, float)
f, f_output = get_value(f_output, rx, float)
assert(np.isclose(p,f))
elif dtype is int:
rx = re.compile('[-0-9eE]+')
p, p_output = get_value(p_output, rx, int)
f, f_output = get_value(f_output, rx, int)
assert(p==f)
else:
raise NotImplementedError("Type comparison not implemented")
return p_output,f_output
#------------------------------------------------------------------------------
def compare_pyth_fort_output( p_output, f_output, dtype=float, language=None):
if isinstance(dtype,list):
for d in dtype:
p_output,f_output = compare_pyth_fort_output_by_type(p_output,f_output,d,language=language)
elif dtype is complex:
while len(p_output)>0 and len(f_output)>0:
p_output,f_output = compare_pyth_fort_output_by_type(p_output,f_output,complex, language=language)
elif dtype is str:
compare_pyth_fort_output_by_type(p_output,f_output,dtype)
else:
p_output = p_output.strip().split()
f_output = f_output.strip().split()
for p, f in zip(p_output, f_output):
compare_pyth_fort_output_by_type(p,f,dtype)
#------------------------------------------------------------------------------
def pyccel_test(test_file, dependencies = None, compile_with_pyccel = True,
cwd = None, pyccel_commands = "", output_dtype = float,
language = None, output_dir = None):
"""
Run pyccel and compare the output to ensure that the results
are equivalent
Parameters
----------
test_file : str
The name of the file containing the program.
The path must either be absolute or relative
to the folder containing this file
dependencies : str/list
The name of any files which are called by the
test_file and must therefore be pyccelized in
order to run it
The paths must either be absolute or relative
to the folder containing this file
compile_with_pyccel : bool
Indicates whether the compilation step should
be handled by a basic call to gfortran/gcc (False)
or internally by pyccel (True)
default : True
cwd : str
The directory from which pyccel and other executables
will be called
default : The folder containing the test_file
pyccel_commands : str
Any additional commands which should be passed to
pyccel
output_dtype : type/list of types
The types expected as output of the program.
If one argument is provided then all types are
assumed to be the same
language : str
The language pyccel should translate to
default = 'fortran'
output_dir : str
The folder in which the generated files should be
saved
"""
rel_test_dir = os.path.dirname(test_file)
test_file = os.path.normpath(test_file)
if (cwd is None):
cwd = os.path.dirname(test_file)
cwd = get_abs_path(cwd)
test_file = get_abs_path(test_file)
pyth_out = get_python_output(test_file, cwd)
if language:
pyccel_commands += " --language="+language
else:
language='fortran'
if output_dir is None:
if language=="python":
output_dir = get_abs_path('__pyccel__')
if dependencies:
if isinstance(dependencies, str):
dependencies = [dependencies]
for i, d in enumerate(dependencies):
dependencies[i] = get_abs_path(d)
if output_dir:
rel_path = os.path.relpath(os.path.dirname(d), start=rel_test_dir)
output = get_abs_path(os.path.join(output_dir, rel_path))
pyc_command = pyccel_commands + ' --output={}'.format(output)
else:
pyc_command = pyccel_commands
if not compile_with_pyccel:
compile_pyccel (cwd, dependencies[i], pyc_command+" -t")
if language == 'fortran':
compile_fortran(cwd, dependencies[i], [], is_mod = True)
elif language == 'c':
compile_c(cwd, dependencies[i], [], is_mod = True)
else:
compile_pyccel(cwd, dependencies[i], pyc_command)
if output_dir:
pyccel_commands += " --output "+output_dir
output_test_file = os.path.join(output_dir, os.path.basename(test_file))
else:
output_test_file = test_file
if compile_with_pyccel:
compile_pyccel(cwd, test_file, pyccel_commands)
else:
compile_pyccel (cwd, test_file, pyccel_commands+" -t")
if not dependencies:
dependencies = []
if language=='fortran':
compile_fortran(cwd, output_test_file, dependencies)
elif language == 'c':
compile_c(cwd, output_test_file, dependencies)
lang_out = get_lang_output(output_test_file, language)
compare_pyth_fort_output(pyth_out, lang_out, output_dtype, language)
#==============================================================================
# UNIT TESTS
#==============================================================================
def test_relative_imports_in_project(language):
base_dir = os.path.dirname(os.path.realpath(__file__))
path_dir = os.path.join(base_dir, "project_rel_imports")
dependencies = ['project_rel_imports/project/folder1/mod1.py',
'project_rel_imports/project/folder2/mod2.py',
'project_rel_imports/project/folder2/mod3.py']
pyccel_test("project_rel_imports/runtest.py",dependencies,
cwd = path_dir,
language = language)
#------------------------------------------------------------------------------
def test_absolute_imports_in_project(language):
base_dir = os.path.dirname(os.path.realpath(__file__))
path_dir = os.path.join(base_dir, "project_abs_imports")
dependencies = ['project_abs_imports/project/folder1/mod1.py',
'project_abs_imports/project/folder2/mod2.py',
'project_abs_imports/project/folder2/mod3.py']
pyccel_test("project_abs_imports/runtest.py", dependencies,
cwd = path_dir,
language = language)
#------------------------------------------------------------------------------
def test_rel_imports_python_accessible_folder(language):
# pyccel is called on scripts/folder2/runtest_rel_imports.py from the scripts folder
# From this folder python understands relative imports
base_dir = os.path.dirname(os.path.realpath(__file__))
path_dir = os.path.join(base_dir, "scripts")
from scripts.folder2.runtest_rel_imports import test_func
tmp_dir = os.path.join(base_dir, '__pyccel__')
pyth_out = str(test_func())
pyccel_opt = '--language={}'.format(language)
if language == 'python':
pyccel_opt += ' --output={}'.format(os.path.join(tmp_dir,"folder2"))
compile_pyccel(os.path.join(path_dir, "folder2"), get_abs_path("scripts/folder2/folder2_funcs.py"), pyccel_opt)
compile_pyccel(path_dir, get_abs_path("scripts/folder2/runtest_rel_imports.py"), pyccel_opt)
if language == 'python':
test_location = "__pyccel__.folder2.runtest_rel_imports"
else:
test_location = "scripts.folder2.runtest_rel_imports"
p = subprocess.Popen([sys.executable , "%s" % os.path.join(base_dir, "run_import_function.py"), test_location],
stdout=subprocess.PIPE, universal_newlines=True)
fort_out, _ = p.communicate()
assert(p.returncode==0)
compare_pyth_fort_output(pyth_out, fort_out)
#------------------------------------------------------------------------------
@pytest.mark.xdist_incompatible
def test_imports_compile(language):
pyccel_test("scripts/runtest_imports.py","scripts/funcs.py",
compile_with_pyccel = False, language = language)
#------------------------------------------------------------------------------
@pytest.mark.xdist_incompatible
def test_imports_in_folder(language):
pyccel_test("scripts/runtest_folder_imports.py","scripts/folder1/folder1_funcs.py",
compile_with_pyccel = False, language = language)
#------------------------------------------------------------------------------
@pytest.mark.xdist_incompatible
def test_imports(language):
pyccel_test("scripts/runtest_imports.py","scripts/funcs.py",
language = language)
#------------------------------------------------------------------------------
@pytest.mark.xdist_incompatible
def test_folder_imports(language):
# pyccel is called on scripts/folder2/runtest_imports2.py from the scripts/folder2 folder
# which is where the final .so file should be
# From this folder python doesn't understand relative imports
base_dir = os.path.dirname(os.path.realpath(__file__))
path_dir = os.path.join(base_dir, "scripts")
tmp_dir = os.path.join(base_dir, '__pyccel__')
from scripts.folder2.runtest_imports2 import test_func
pyth_out = str(test_func())
language_opt = '--language={}'.format(language)
pyccel_opt = language_opt
if language == 'python':
pyccel_opt = language_opt+' --output={}'.format(os.path.join(tmp_dir,"folder1"))
compile_pyccel(os.path.join(path_dir,"folder1"), get_abs_path("scripts/folder1/folder1_funcs.py"),
pyccel_opt)
if language == 'python':
pyccel_opt = language_opt+' --output={}'.format(os.path.join(tmp_dir,"folder2"))
compile_pyccel(os.path.join(path_dir,"folder2"), get_abs_path("scripts/folder2/runtest_imports2.py"),
pyccel_opt)
if language == 'python':
test_location = "__pyccel__.folder2.runtest_imports2"
else:
test_location = "scripts.folder2.runtest_imports2"
p = subprocess.Popen([sys.executable , "%s" % os.path.join(base_dir, "run_import_function.py"), test_location],
stdout=subprocess.PIPE, universal_newlines=True)
fort_out, _ = p.communicate()
assert(p.returncode==0)
compare_pyth_fort_output(pyth_out, fort_out)
#------------------------------------------------------------------------------
@pytest.mark.xdist_incompatible
def test_funcs(language):
pyccel_test("scripts/runtest_funcs.py", language = language)
#------------------------------------------------------------------------------
# Enumerate not supported in c
def test_inout_func():
pyccel_test("scripts/runtest_inoutfunc.py")
#------------------------------------------------------------------------------
def test_bool(language):
pyccel_test("scripts/bool_comp.py", output_dtype = bool, language = language)
#------------------------------------------------------------------------------
def test_expressions(language):
types = [float, complex, int, float, float, int] + [float]*3 + \
[complex, int, complex, complex, int, int, float] + [complex]*3 + \
[float]*3 + [int] + [float]*2 + [int] + [float]*3 + [int] + \
[float]*3 + [int]*2 + [float]*2 + [int]*5 + [complex] + [bool]*9
pyccel_test("scripts/expressions.py", language=language,
output_dtype = types)
#------------------------------------------------------------------------------
# See issue #756 for c problem
def test_generic_functions():
pyccel_test("scripts/runtest_generic_functions.py",
dependencies = "scripts/generic_functions.py",
compile_with_pyccel = False,
output_dtype = [float,float,float,float,float,float,
float,float,float,float,float,float,float,int,float,
int,int])
#------------------------------------------------------------------------------
# C does not handle functions in functions
def test_default_arguments():
pyccel_test("scripts/runtest_default_args.py",
dependencies = "scripts/default_args_mod.py",
output_dtype = [int,int,float,float,float,
float,float,float,float,bool,bool,bool,
float,float,float,float])
#------------------------------------------------------------------------------
@pytest.mark.xdist_incompatible
def test_pyccel_calling_directory(language):
cwd = get_abs_path(".")
test_file = get_abs_path("scripts/runtest_funcs.py")
pyth_out = get_python_output(test_file)
language_opt = '--language={}'.format(language)
compile_pyccel(cwd, test_file, language_opt)
if language == "python":
test_file = get_abs_path(os.path.join('__pyccel__',
os.path.basename(test_file)))
fort_out = get_lang_output(test_file, language)
compare_pyth_fort_output( pyth_out, fort_out )
#------------------------------------------------------------------------------
def test_in_specified(language):
pyccel_test("scripts/runtest_degree_in.py", language=language)
#------------------------------------------------------------------------------
@pytest.mark.parametrize( "test_file", ["scripts/hope_benchmarks/hope_fib.py",
"scripts/hope_benchmarks/quicksort.py",
"scripts/hope_benchmarks/hope_pisum.py",
"scripts/hope_benchmarks/hope_ln_python.py",
"scripts/hope_benchmarks/hope_pairwise_python.py",
"scripts/hope_benchmarks/point_spread_func.py",
"scripts/hope_benchmarks/simplify.py",
pytest.param("scripts/hope_benchmarks_decorators/fib.py",
marks = pytest.mark.xfail(reason="Issue 344 : Functions and modules cannot share the same name")),
| |
= None, name = 'conv_8_2') # 500
#features = tl.layers.BatchNormLayer(features, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='bn1')
#feature2 = PReluLayer(feature2, channel_shared = True, name='conv1_2_relu')
#feature3 = Conv1d(sequences, 300, 20, stride = 1, dilation_rate = 4, act = None, name = 'conv_16_2') # 500
#features = tl.layers.BatchNormLayer(features, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='bn1')
#feature3 = PReluLayer(feature3, channel_shared = True, name='conv1_3_relu')
#features = ConcatLayer([feature1, feature2, feature3], name = 'concat')
features = Conv1d(feature1, 32, KERNEL_SIZE, stride = 1, dilation_rate = 1, act = None, name = 'conva_250') # 250
features = tl.layers.BatchNormLayer(features, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='bna2')
features = PReluLayer(features, channel_shared = True, name='conv2a_relu')
if config.TRAIN.DROPOUT:
features = DropoutLayer(features, keep = config.TRAIN.DROPOUT_KEEP, name = 'drop_features', is_fix = True)
features = Conv1d(features, 32, KERNEL_SIZE, stride = 1, dilation_rate = 1, act = None, name = 'conv_250') # 250
features = tl.layers.BatchNormLayer(features, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='bn2')
features = PReluLayer(features, channel_shared = True, name='conv2_relu')
if config.TRAIN.DROPOUT:
features = DropoutLayer(features, keep = config.TRAIN.DROPOUT_KEEP, name = 'drop_features_2', is_fix = True)
features = Conv1d(features, 32, KERNEL_SIZE, stride = 1, dilation_rate = 1, act = None, name = 'conv_125') # 125
features = tl.layers.BatchNormLayer(features, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='bn3')
features = PReluLayer(features, channel_shared = True, name='conv3_relu')
if config.TRAIN.DROPOUT:
features = DropoutLayer(features, keep = config.TRAIN.DROPOUT_KEEP, name = 'drop_features_3', is_fix = True)
#sequences = Conv1d(sequences, 32, KERNEL_SIZE, stride = 4, dilation_rate = 1, act = act, name = 'conv_63') # 125
#sequences = Conv1d(sequences, 32, KERNEL_SIZE, stride = 4, dilation_rate = 1, act = act, name = 'conv_31') # 125
# stacking 3 bi-directiona,l lstm here
features = BiRNNLayer(features, cell_fn = tf.contrib.rnn.LSTMCell, n_hidden = config.TRAIN.RNN_HIDDEN, n_steps = config.TRAIN.RNN_STEPS + 1, return_last = False, name = 'bi1')
#features = PReluLayer(features, channel_shared = True, name='prelu1')
#
'''
features = Conv1d(sequences, 32, KERNEL_SIZE, stride = 2, dilation_rate = 1, act = None, name = 'conv1')
features = tl.layers.BatchNormLayer(features, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='bn1')
features = PReluLayer(features, channel_shared = True, name='conv1_relu')
features = Conv1d(features, 64, KERNEL_SIZE, stride = 2, act = None, name = 'conv1_stride')
features = tl.layers.BatchNormLayer(features, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='bn2')
features = PReluLayer(features, channel_shared = True, name='conv2_relu')
features = Conv1d(features, 64, KERNEL_SIZE, stride = 2, act = None, name = 'conv2_stride')
features = tl.layers.BatchNormLayer(features, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='bn3')
features = PReluLayer(features, channel_shared = True, name='conv3_relu')
'''
return features, feature1.outputs
def sharedFeatureExtractor2(t_sequences, name, reuse = False, is_train = True):
w_init = tf.random_normal_initializer(stddev=stddev)
b_init = None
g_init = tf.random_normal_initializer(1., stddev)
act = lambda x: tf.nn.leaky_relu(x, 0.2)
kernels = config.TRAIN.KERNEL.split('_')
with tf.variable_scope(name, reuse=reuse) as vs:
sequences = InputLayer(t_sequences, name='in')
#return sequences, sequences.outputs
#return sequences
# user larger kernel size for the first layer
feature_conv = Conv1d(sequences, 300, int(kernels[0]), stride = 1, dilation_rate = 1, act = None, name = 'conv_500') # 500
feature1 = tl.layers.BatchNormLayer(feature_conv, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='bn1')
feature1 = PReluLayer(feature1, channel_shared = True, name='conv1_relu')
if config.TRAIN.DROPOUT:
feature1 = DropoutLayer(feature1, keep = config.TRAIN.DROPOUT_KEEP, name = 'drop_features1', is_fix = True, is_train = is_train)
# used to simulate gapped kmer
feature2 = Conv1d(sequences, 300, int(kernels[1]), stride = 1, dilation_rate = 2, act = None, name = 'conv_8_2') # 500
feature2 = tl.layers.BatchNormLayer(feature2, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='feature2_bn')
feature2 = PReluLayer(feature2, channel_shared = True, name='conv1_2_relu')
if config.TRAIN.DROPOUT:
feature2 = DropoutLayer(feature2, keep = config.TRAIN.DROPOUT_KEEP, name = 'drop_features2', is_fix = True, is_train = is_train)
feature3 = Conv1d(sequences, 300, int(kernels[2]), stride = 1, dilation_rate = 4, act = None, name = 'conv_16_2') # 500
feature3 = tl.layers.BatchNormLayer(feature3, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='bn2')
feature3 = PReluLayer(feature3, channel_shared = True, name='conv1_3_relu')
if config.TRAIN.DROPOUT:
feature3 = DropoutLayer(feature3, keep = config.TRAIN.DROPOUT_KEEP, name = 'drop_features3', is_fix = True, is_train = is_train)
features = ConcatLayer([feature1, feature2, feature3], name = 'concat')
features = Conv1d(features, 32, KERNEL_SIZE, stride = 1, dilation_rate = 1, act = None, name = 'conva_250') # 250
features = tl.layers.BatchNormLayer(features, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='bna3')
con_features = PReluLayer(features, channel_shared = True, name='conv2a_relu')
if config.TRAIN.DROPOUT:
con_features = DropoutLayer(con_features, keep = config.TRAIN.DROPOUT_KEEP, name = 'drop_features4', is_fix = True, is_train = is_train)
features = Conv1d(con_features, 32, KERNEL_SIZE, stride = 1, dilation_rate = 1, act = None, name = 'conva_250_c') # 250
features = tl.layers.BatchNormLayer(features, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='bna3_c')
features = PReluLayer(features, channel_shared = True, name='conv2a_relu_c')
if config.TRAIN.DROPOUT:
features = DropoutLayer(features, keep = config.TRAIN.DROPOUT_KEEP, name = 'drop_featuress1', is_fix = True, is_train = is_train)
features = Conv1d(features, 32, KERNEL_SIZE, stride = 1, dilation_rate = 1, act = None, name = 'conv_250') # 250
features = tl.layers.BatchNormLayer(features, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='bn4')
features = PReluLayer(features, channel_shared = True, name='conv2_relu')
if config.TRAIN.DROPOUT:
features = DropoutLayer(features, keep = config.TRAIN.DROPOUT_KEEP, name = 'drop_featuresss2', is_fix = True, is_train = is_train)
features = ElementwiseLayer([features, con_features], tf.add, name = 'elem_add')
features = Conv1d(features, 32, KERNEL_SIZE, stride = 1, dilation_rate = 1, act = None, name = 'conv_125') # 125
features = tl.layers.BatchNormLayer(features, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='bn5')
features = PReluLayer(features, channel_shared = True, name='conv3_relu')
if config.TRAIN.DROPOUT:
features = DropoutLayer(features, keep = config.TRAIN.DROPOUT_KEEP, name = 'drop_featuresss3', is_fix = True, is_train = is_train)
#sequences = Conv1d(sequences, 32, KERNEL_SIZE, stride = 4, dilation_rate = 1, act = act, name = 'conv_63') # 125
#sequences = Conv1d(sequences, 32, KERNEL_SIZE, stride = 4, dilation_rate = 1, act = act, name = 'conv_31') # 125
# stacking 3 bi-directiona,l lstm here
features = BiRNNLayer(features, cell_fn = tf.contrib.rnn.LSTMCell, n_hidden = config.TRAIN.RNN_HIDDEN, n_steps = config.TRAIN.RNN_STEPS + 1, return_last = False, name = 'bi1')
#features = PReluLayer(features, channel_shared = True, name='prelu1')
#features = BiRNNLayer(features, cell_fn = tf.contrib.rnn.LSTMCell, n_hidden = config.TRAIN.RNN_HIDDEN, n_steps = config.TRAIN.RNN_STEPS + 1, return_last = False, name = 'bi2')
#
features = SelfAttentionLayer(features, 8 , 128,name='self-attention')
features = SelfAttentionLayer(features, 8 , 128,name='self-attention2')
'''
features = Conv1d(sequences, 32, KERNEL_SIZE, stride = 2, dilation_rate = 1, act = None, name = 'conv1')
features = tl.layers.BatchNormLayer(features, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='bn1')
features = PReluLayer(features, channel_shared = True, name='conv1_relu')
features = Conv1d(features, 64, KERNEL_SIZE, stride = 2, act = None, name = 'conv1_stride')
features = tl.layers.BatchNormLayer(features, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='bn2')
features = PReluLayer(features, channel_shared = True, name='conv2_relu')
features = Conv1d(features, 64, KERNEL_SIZE, stride = 2, act = None, name = 'conv2_stride')
features = tl.layers.BatchNormLayer(features, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='bn3')
features = PReluLayer(features, channel_shared = True, name='conv3_relu')
'''
return features, feature_conv.outputs#, features.outputs
def attention(feature, name):
hidden = tl.layers.TimeDistributedLayer(feature, layer_class=tl.layers.DenseLayer, args={'n_units':64, 'name':name + 'dense','act' :tf.nn.tanh}, name= name + 'time_dense')
hidden = tl.layers.TimeDistributedLayer(hidden, layer_class=tl.layers.DenseLayer, args={'n_units':1, 'name':name + 'dense2'}, name= name + 'time_dense2')
hidden = tl.layers.FlattenLayer(hidden, name = name + 'flatten')
return LambdaLayer(hidden, fn = tf.nn.softmax, name = name + "_softmax")
def sharedFeatureExtractor2D(t_sequences, name, reuse = False, is_train=True):
w_init = tf.random_normal_initializer(stddev=stddev)
b_init = None
g_init = tf.random_normal_initializer(1., stddev)
act = lambda x: tf.nn.leaky_relu(x, 0.2)
with tf.variable_scope(name, reuse=reuse) as vs:
sequences = InputLayer(t_sequences, name='in')
#return sequences
features = Conv2d(sequences, 32,KERNEL_SIZE , stride = 2, dilation_rate = 1, act = None, name = 'conv_500') # 500
#features = tl.layers.BatchNormLayer(features, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='bn1')
features = PReluLayer(features, channel_shared = True, name='conv1_relu')
features = Conv2d(features, 32, KERNEL_SIZE, stride = 2, dilation_rate = 1, act = None, name = 'conv_250') # 250
#features = tl.layers.BatchNormLayer(features, beta_init = w_init, gamma_init = w_init, is_train = | |
#!/usr/bin/env python
#####
#Description reframe the barcode extraction script to do the following.
#1. Improve speed by storing barcodes by position instead of string searching for them.
#2. Support sequence error handling by filtering and correcting barcodes on the fly using hamming distance.
# Filtering this way will improve speed by reducing reads carried forward to downstream steps.
#3. Store matepair information.
#4. Reduce the number of output files created. Depricate the single .fastq file per cell output format.
#####
import sys
import os
import argparse
import itertools
import json
#from Bio.Seq import Seq
#####
# Set consistent parameters here
Round1_barcode_staticSeq = "CATTCG"
Round2_barcode_staticSeq = "ATCCAC"
Round3_barcode_staticSeq = "GTGGCC"
#####
#####
# Define "print" function to print to stderr
def eprint(*args, **kwargs):
eprint(*args, file=sys.stderr, **kwargs)
#####
# Get arguments
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--inputFastqF', required=False, help='Input a forward .fastq format file')
parser.add_argument('-r', '--inputFastqR', required=False, help='Input a reverse .fastq format file')
parser.add_argument('-o', '--outputDir', required=False, help='Name of the output directory used to store the output.fastq')
parser.add_argument('-b', '--bin', required=False, help='Number of reads to process before saving to disc. Binning helps accomodate large input files')
parser.add_argument('-e', '--errorThreshold', required=False, help='Enter "0" or "1" if to indicate per barcode error threshold')
parser.add_argument('-p', '--performanceMetrics', required=False, action='store_true', help='Provide -p flag to turn on performance metrics reporting', default=False)
parser.add_argument('-t', '--readsPerCellThreshold', required=False, help='Provide a minimum reads per cell threshold for retaining a cell', default=1)
parser.add_argument('-v', '--verbose', required=False, action='store_true', help='Provide -v flag to turn on verbose progress reporting for each bin', default=False)
#parser.add_argument('-b1', '--barcode1', required=False, help='Provied the path to the Round1_barcodes_new5.txt file or a custom Round1 barcodes file'
#parser.add_argument('-d', '--directory', required=True, help='Directory containing the main SPLiT-Seq_demultiplexing materials')
args = parser.parse_args()
######
# Step1: Gather barcode information from provided barcodes.txt files
######
# Read in text files containing possible barcodes store them in a list
Round1_barcodes = []
Round2_barcodes = []
Round3_barcodes = []
Eight_BP_barcode = []
with open('Round1_barcodes_new5.txt', "r") as infile:
for line in infile:
Round1Barcode = line.rstrip()
Round1_barcodes.append(line.rstrip())
Eight_BP_barcode.append(Round1Barcode[8:16]) #Note this is the same for each round
with open('Round2_barcodes_new4.txt', "r") as infile:
for line in infile:
Round2_barcodes.append(line.rstrip())
with open('Round3_barcodes_new4.txt', "r") as infile:
for line in infile:
Round3_barcodes.append(line.rstrip())
# Create a functon to compare barcodes
# Use hamming distance function from a stack overfow question I created "https://stackoverflow.com/questions/65258822/fast-python-short-dna-string-comparison/65259404#65259404"
def hamming(s1, s2):
return sum(c1 != c2 for c1, c2 in zip(s1, s2))
######
# Create bin parameters
######
# Create a value used to bin the dataset
binIterator = int(int(args.bin) * 4)
print("binIterator is set to " + str(binIterator))
# Define workingBin
counter = 0
readCounterFinal = 0
workingBin = counter + binIterator
# Get the number of lines in the input file
with open(args.inputFastqF, "r") as infile:
linesInInputFastq = sum(1 for line in infile)
print("The linesInInputFastq value is set to " + str(linesInInputFastq))
######
# Build a class to store information from each read.
######
class FastQRead():
def __init__(self, name, read, quality, lineNumber):
self.name = name
self.read = read
self.quality = quality
self.lineNumber = lineNumber
def display_read(self):
print("name = " + str(self.name) + "\n" \
"read = " + str(self.read) + "\n" \
"quality = " + str(self.quality) + "\n" \
"lineNumber = " + str(self.lineNumber) + "\n", end='')
def return_fastq(self):
print(str(self.name) + "\n" \
+ str(self.read) + "\n" \
+ "+" + "\n" \
+ str(self.quality) + "\n", end='')
class barcodeRead(FastQRead):
def __init__(self, name, read, quality, lineNumber, barcode1, barcode2, barcode3, umi):
self.name = name
self.read = read
self.quality = quality
self.lineNumber = lineNumber
self.barcode1 = barcode1
self.barcode2 = barcode2
self.barcode3 = barcode3
self.umi = umi
def display_read(self):
print("name = " + str(self.name) + "\n" \
"read = " + str(self.read) + "\n" \
"quality = " + str(self.quality) + "\n" \
"lineNumber = " + str(self.lineNumber) + "\n" \
"Barcodes = " + str(barcode1 + "_" + barcode2 + "_" + barcode3) + "\n"\
"UMI = " + str(umi), end='')
def return_fastq(self):
readID = self.name
readID_split = readID.split("/")
noSpaceReadID = readID_split[0].replace(" ", "")
return(str(noSpaceReadID.strip() + "_" + self.barcode1 + self.barcode2 + self.barcode3 + "_" + self.umi) + "\n" \
+ str(self.read) + "\n" \
+ "+" + "\n" \
+ str(self.quality) + "\n")
######
# Create some lists that need to be outside of the loop in order to aggregate performance metrics
######
Total_barcodes_detected = []
Total_barcodes_passing_minReadThreshold = []
######
# Learn barcode positions from input fastqR
######
print("Learning barcode positions...")
#Set Default Positions
umi_start=0
umi_end=10
barcode3_start=10
barcode3_end=18
barcode2_start=48
barcode2_end=int(48+8)
barcode3_start=86
barcode3_end=int(86+8)
# Code for automated barcode position extractor based on static sequences
line_ct_Learner = 0
learner_bc1_list = []
learner_bc2_list = []
learner_bc3_list = []
with open("position_learner_fastqr.fastq", "r") as infile:
for line in infile:
if (line_ct_Learner % 4 == 1):
learner_bc1_list.append(line.find(Round1_barcode_staticSeq))
learner_bc2_list.append(line.find(Round2_barcode_staticSeq))
learner_bc3_list.append(line.find(Round3_barcode_staticSeq))
line_ct_Learner += 1
foundPosition_Round1_barcode=max(set(learner_bc1_list), key=learner_bc1_list.count)
foundPosition_Round2_barcode=max(set(learner_bc2_list), key=learner_bc2_list.count)
foundPosition_Round3_barcode=max(set(learner_bc3_list), key=learner_bc3_list.count)
print("Extracted position1 = " + str(foundPosition_Round1_barcode))
print("Extracted position2 = " + str(foundPosition_Round2_barcode))
print("Extracted position3 = " + str(foundPosition_Round3_barcode))
# Use extracted static sequence positions to infer barcode positions
umi_start=int(foundPosition_Round3_barcode - 18)
umi_end=int(foundPosition_Round3_barcode - 8)
print("UMI position has been extracted as " + str(umi_start) + ":" + str(umi_end))
barcode3_start=int(foundPosition_Round3_barcode - 8)
barcode3_end=int(foundPosition_Round3_barcode)
print("Barcode3 position has been extracted as " + str(barcode3_start) + ":" + str(barcode3_end))
barcode2_start=int(foundPosition_Round2_barcode - 8)
barcode2_end=int(foundPosition_Round2_barcode)
print("Barcode2 position has been extracted as " + str(barcode2_start) + ":" + str(barcode2_end))
barcode1_start=int(foundPosition_Round1_barcode + 6)
barcode1_end=int(foundPosition_Round1_barcode + 14)
print("Barcode1 position has been extracted as " + str(barcode1_start) + ":" + str(barcode1_end))
######
# Step2: Iterate through input fastqs in bins.
######
bin_counter = 0
for i in range(0,int(linesInInputFastq),int(binIterator)):
# Create dictinaries used to store the parsed read information from the fastq files
readsF = {}
readsR = {}
readsF_BC_UMI_dict = {}
# Create empty lists
filteredBarcode1 = []
filteredBarcode2 = []
filteredBarcode3 = []
#startingline = int(bin_counter * binIterator)
if (args.verbose == True):
print("Processing range " + str(i) + " - " + str(int(i + binIterator)))
# Iterate through the forward reads
with open(args.inputFastqF, "r") as infile:
start_ct = 0
line_ct1 = 0
read_counter = 0 # To get the read counter to match we need to add 1. Each read = 4 lines.
completeReadCounter = 0
starterF = 0
for line in itertools.islice(infile, i, int(i + binIterator)):
if (starterF == 0 and line.startswith('@') == False):
continue
if (starterF == 0 and line.startswith('@') == True):
starterF += 1
lineName=str(line[0:].rstrip())
completeReadCounter += 1
line_ct1 += 1
continue
if (line_ct1 % 4 == 0 and line.startswith('@')):
lineName=str(line[0:].rstrip())
completeReadCounter += 1
if (line_ct1 % 4 == 1):
lineRead=str(line[0:].rstrip())
completeReadCounter += 1
if (line_ct1 % 4 == 3):
lineQuality=str(line[0:].rstrip())
completeReadCounter += 1
if (completeReadCounter == 3):
processedRead = FastQRead(name = lineName, \
read = lineRead, \
quality = lineQuality, \
lineNumber = read_counter)
readsF[str(str(bin_counter) + "_" + str(read_counter))]=processedRead
completeReadCounter = 0
read_counter += 1
if (starterF == 1):
line_ct1 += 1
# if (line.startswith('@') == False and start_ct <=3):
# start_ct += 1
# line_ct = 0
# continue
# Iterate through the reverse reads
with open(args.inputFastqR, "r") as infile:
start_ct = 0
line_ct1 = 0
read_counter = 0
completeReadCounter = 0
starterR = 0
for line in itertools.islice(infile, i, int(i + binIterator)):
if (starterR == 0 and line.startswith('@') == False):
continue
if (starterR == 0 and line.startswith('@') == True):
starterR += 1
lineName=str(line[0:].rstrip())
completeReadCounter += 1
line_ct1 += 1
continue
if (line_ct1 % 4 == 0 and line.startswith('@')):
lineName=str(line[0:].rstrip())
completeReadCounter += 1
if (line_ct1 % 4 == 1):
lineRead=str(line[0:].rstrip())
#lineReadUMI = lineRead[0:10]
lineReadUMI = lineRead[umi_start:umi_end]
#lineReadBarcode3 = lineRead[10:18]
lineReadBarcode3 = lineRead[barcode3_start:barcode3_end]
#lineReadBarcode2 = lineRead[48:int(48+8)]
lineReadBarcode2 = lineRead[barcode2_start:barcode2_end]
#lineReadBarcode1 = lineRead[86:int(86+8)]
lineReadBarcode1 = lineRead[barcode1_start:barcode1_end]
filteredBarcode1 = [s for s in Eight_BP_barcode if hamming(s, lineReadBarcode1) <= int(args.errorThreshold)] # Match each extracted barcode to a greenlist of possible barcodes. If a match within hamming distance of 1 is found move forward with that match (not the extracted sequence).
filteredBarcode2 = [s for s in Eight_BP_barcode if hamming(s, lineReadBarcode2) <= int(args.errorThreshold)]
filteredBarcode3 = [s for s in Eight_BP_barcode if hamming(s, lineReadBarcode3) <= int(args.errorThreshold)]
completeReadCounter += 1
if (line_ct1 % 4 == 3):
lineQuality=str(line[0:].rstrip())
completeReadCounter += 1
if (completeReadCounter == 3):
if len(filteredBarcode1) == 0: # The following if statments break the loop if a barcode does not pass the HD <=1 filter
line_ct1 += 1 # If the barcode observed does not match a barcode in our greenlist we escape the loop, count the line and reset the complete read counter.
completeReadCounter = 0
continue
elif len(filteredBarcode2) == 0:
line_ct1 += 1
completeReadCounter = 0
| |
create_dataset(self, force=False, save=True):
data_file = Path('data/data.csv')
t0 = time()
if data_file.is_file() is False or force is True:
self.load()
self.create_order_features()
self.create_product_features()
self.create_user_features()
# print(self._users.shape)
# print(tt_orders.shape)
self._users = pd.merge(self._users, self._tt_orders, on='user_id')
# print(self._users.shape)
order_stat = self._prior_order_products.groupby('order_id').agg({'order_id': 'size'}) \
.rename(columns={'order_id': 'order_size'}).reset_index()
self._prior_order_products = pd.merge(self._prior_order_products, order_stat, on='order_id')
self._prior_order_products[
'add_to_cart_order_inverted'] = self._prior_order_products.order_size - \
self._prior_order_products.add_to_cart_order
self._prior_order_products[
'add_to_cart_order_relative'] = self._prior_order_products.add_to_cart_order / \
self._prior_order_products.order_size
pivot = pd.pivot_table(self._prior_order_products, index=['user_id', 'product_id'],
aggfunc=(np.mean, 'count', 'min', 'max', 'median', 'sum'))
data = self._prior_order_products[['user_id', 'product_id']].copy()
data.drop_duplicates(inplace=True)
# print(data.shape)
d = dict()
d['num'] = pivot['order_id']['count']
d['first_order'] = pivot['order_number']['min']
d['last_order'] = pivot['order_number']['max']
d['mean_add_to_cart_order'] = pivot['add_to_cart_order']['mean']
d['median_add_to_cart_order'] = pivot['add_to_cart_order']['median']
d['mean_days_since_prior_order'] = pivot['days_since_prior_order']['mean']
d['median_days_since_prior_order'] = pivot['days_since_prior_order']['median']
d['mean_order_dow'] = pivot['order_dow']['mean']
d['median_order_dow'] = pivot['order_dow']['median']
d['mean_order_hour_of_day'] = pivot['order_hour_of_day']['mean']
d['median_order_hour_of_day'] = pivot['order_hour_of_day']['median']
d['mean_add_to_cart_order_inverted'] = pivot['add_to_cart_order_inverted']['mean']
d['median_add_to_cart_order_inverted'] = pivot['add_to_cart_order_inverted']['median']
d['mean_add_to_cart_order_relative'] = pivot['add_to_cart_order_relative']['mean']
d['median_add_to_cart_order_relative'] = pivot['add_to_cart_order_relative']['median']
d['reordered_sum'] = pivot['reordered']['sum']
for i in d:
data = data.join(d[i].to_frame(), on=['user_id', 'product_id'], how='left', rsuffix='_' + i)
del d
del pivot
del order_stat
gc.collect()
data.rename(columns={'count': 'UP_orders',
'min': 'UP_first_order',
'max': 'UP_last_order',
'mean': 'UP_avg_add_to_cart_order'}, inplace=True)
data = pd.merge(data, self._products, on='product_id', how='left')
data = pd.merge(data, self._users, on='user_id', how='left')
data['UP_order_rate'] = data['UP_orders'] / data['US_number_of_orders']
data['UP_orders_since_last_order'] = data['US_number_of_orders'] - data['UP_last_order']
data['UP_order_rate_since_first_order'] = data['UP_orders'] / (data['US_number_of_orders'] -
data['UP_first_order'] + 1)
user_dep_stat = data.groupby(['user_id', 'department_id']).agg(
{'product_id': lambda v: v.nunique(),
'reordered': 'sum'
})
user_dep_stat.rename(columns={'product_id': 'dep_products',
'reordered': 'dep_reordered'}, inplace=True)
user_dep_stat.reset_index(inplace=True)
user_aisle_stat = data.groupby(['user_id', 'aisle_id']).agg(
{'product_id': lambda v: v.nunique(),
'reordered': 'sum'
})
user_aisle_stat.rename(columns={'product_id': 'aisle_products',
'reordered': 'aisle_reordered'}, inplace=True)
user_aisle_stat.reset_index(inplace=True)
print(data.shape)
data = pd.merge(data, user_dep_stat, on=['user_id', 'department_id'])
data = pd.merge(data, user_aisle_stat, on=['user_id', 'aisle_id'])
print(data.head(1))
print(data.shape)
data = pd.merge(data, self._orders_train[['user_id', 'product_id', 'reordered']],
on=['user_id', 'product_id'],
how='left')
#
# Try to see in how many orders of the total this product is in
#
data['UP_product_reorder_percentage'] = data['UP_orders'] / data['US_number_of_orders']
#
# Build PR_unique_total_users / total_users ratio
#
data['UP_utu_to_total_ratio'] = data['PR_unique_total_users'] / self._users.shape[0]
# print(data.head(100))
# print(data.shape)
data['reordered'] = np.where(data.reordered.isnull(), 0, 1)
# Set the train = 0 and the test = 1 to save some memory
data['eval_set'] = np.where(data.eval_set == 'train', 0, 1)
print("Final data shape:", data.shape)
print("Dtypes:", data.columns.to_series().groupby(data.dtypes).groups)
if save is True:
t1 = time()
print("=> Saving dataset to file")
data.to_csv('data/data.csv', index=False)
print("=> Saved the dataset in %fs" % (time() - t1))
del self._tt_orders
del self._products
del self._aisles
del self._departments
del self._orders_prior
del self._orders_train
del self._orders
del self._users
del self._user_order
del self._prior_orders
del self._prior_order_products
print("=> Created the dataset in %fs" % (time() - t0))
else:
data = pd.read_csv('data/data.csv', dtype={
'product_id': np.uint16,
'order_id': np.int32,
'aisle_id': np.uint8,
'department_id': np.uint8,
'user_id': np.int32,
'UP_orders': np.uint16,
'UP_first_order': np.uint16,
'UP_last_order': np.uint16,
'UP_avg_add_to_cart_order': np.float32,
'PR_cluster_id': np.uint16,
'PR_organic': np.int8,
'PR_non_fattening': np.int8,
'PR_recycled': np.int8,
'PR_vegan': np.int8,
'PR_sugar_free': np.int8,
'PR_gluten_free': np.int8,
'PR_total_products_bought': np.uint32,
'PR_reorder_probability': np.float32,
'PR_reorder_times': np.float32,
'PR_reorder_ratio': np.float32,
'PO_avg_product_importance': np.float32,
'PO_min_product_importance': np.float32,
'PO_max_product_importance': np.float32,
'PR_most_similar': np.uint16,
'PR_second_most_similar': np.uint16,
'PR_mean_add_to_cart_order': np.float32,
'PR_mean_order_hour_of_day': np.float32,
'PR_mean_order_dow': np.float32,
'PR_unique_total_users': np.int32,
'US_avg_days_between_orders': np.float32,
'US_avg_order_dow': np.float32,
'US_avg_order_hour_of_day': np.float32,
'US_number_of_orders': np.uint32,
'US_day_span': np.uint16,
'US_total_products_bought': np.uint32,
'US_total_unique_products_bought': np.uint32,
'US_unique_to_total_products_bought': np.float32,
'US_average_basket': np.float32,
'UP_favorite_cluster': np.float32,
'UP_organic_percent': np.float32,
'UP_non_fattening_percent': np.float32,
'UP_recycled_percent': np.float32,
'UP_vegan_percent': np.float32,
'UP_sugar_free_percent': np.float32,
'UP_gluten_free_percent': np.float32,
'UP_favorite_aisle': np.float32,
'UP_favorite_department': np.float32,
'eval_set': np.int8,
'order_number': np.int16,
'order_dow': np.int8,
'order_hour_of_day': np.int8,
'US_time_since_last_order': np.float32, # perhaps not
'OR_num_of_orders_per_dow': np.uint32,
'OR_num_of_orders_per_hod': np.uint32,
'OR_weekend': np.int8,
'OR_weekday': np.int8,
'OR_avg_aisle_per_dow': np.float32,
'OR_avg_department_per_dow': np.float32,
'OR_avg_cluster_per_dow': np.float32,
'OR_avg_aisle_per_hod': np.float32,
'OR_avg_department_per_hod': np.float32,
'OR_avg_cluster_per_hod': np.float32,
'UP_order_rate': np.float32,
'UP_orders_since_last_order': np.uint32,
'UP_order_rate_since_first_order': np.float32,
'reordered': np.int8,
'UP_product_reorder_percentage': np.float32,
'UP_utu_to_total_ratio': np.float32
})
print("=> Loaded dataset from file in %fs" % (time() - t0))
self._train = data[data['eval_set'] == 0].copy()
self._test = data[data['eval_set'] == 1].copy()
self._train.is_copy = False
self._test.is_copy = False
del data
gc.collect()
def handle_missing_departments(self, save=True):
vectorizer = TfidfVectorizer(min_df=0.00009, smooth_idf=True,
encoding='utf8', strip_accents='unicode',
stop_words='english',
use_idf=True,
sublinear_tf=False,
)
train = self._products[self._products.department_id != 21]
test = self._products[self._products.department_id == 21]
train_length = train.shape[0]
dummy = pd.concat([train, test], ignore_index=True, axis=0)
x_all = vectorizer.fit_transform(dummy['product_name'])
x = x_all[:train_length]
x_test = x_all[train_length:]
y_all = train['department_id']
y = y_all[:train_length]
testProductIds = test.product_id
# X_train, X_test_dummy, Y_train, Y_test_dummy = train_test_split(x, y, test_size=0.2, random_state=42)
# from sklearn.model_selection import KFold
# from sklearn.model_selection import GridSearchCV
# kf = KFold(n_splits=3)
# kf.get_n_splits(x)
# for train_index, test_index in kf.split(x):
# X_train, X_test = x[train_index], x[test_index]
# y_train, y_test = y[train_index], y[test_index]
# parameters = {'estimator__kernel': ('linear', 'rbf'), 'estimator__C': [1, 10]}
#
# model_tunning = GridSearchCV(clf, parameters, cv=kf, n_jobs=-1)
# model_tunning.fit(x, y) # set the best parameters
#
# print(model_tunning.best_score_)
# print(model_tunning.best_params_)
# Best: {'estimator__C': 10, 'estimator__kernel': 'linear'}
clf = OneVsOneClassifier(estimator=SVC(random_state=0, verbose=0, C=10, kernel='linear'), n_jobs=-1)
# clf.fit(X_train, Y_train)
# print("=> CLF Score:", clf.score(X_test_dummy, Y_test_dummy))
clf.fit(x, y)
y_pred = clf.predict(x_test)
output = pd.DataFrame({"product_id": testProductIds, "department_id": y_pred})
print(output.shape)
if save is True:
output.to_csv('data/department-classification.csv', index=False)
def handle_missing_aisle(self, save=True):
vectorizer = TfidfVectorizer(min_df=0.00009, smooth_idf=True,
encoding='utf8', strip_accents='unicode',
stop_words='english',
use_idf=True,
sublinear_tf=False,
)
train = self._products[self._products.aisle_id != 100]
test = self._products[self._products.aisle_id == 100]
train_length = train.shape[0]
dummy = pd.concat([train, test], ignore_index=True, axis=0)
dummy['new_product_name'] = dummy['product_name'].map(str) + ' ' + dummy['department'].map(str)
x_all = vectorizer.fit_transform(dummy['new_product_name'])
x = x_all[:train_length]
x_test = x_all[train_length:]
y_all = train['aisle_id']
y = y_all[:train_length]
print(train[train['aisle_id'].isnull()])
testProductIds = test.product_id
clf = OneVsOneClassifier(estimator=SVC(random_state=0, verbose=0, C=10, kernel='linear'), n_jobs=-1)
clf.fit(x, y)
y_pred = clf.predict(x_test)
output = pd.DataFrame({"product_id": testProductIds, "aisle_id": y_pred})
print(output.shape)
if save is True:
output.to_csv('data/aisle-classification.csv', index=False)
def find_cluster_k(self, data, k_range=range(1, 50)):
t0 = time()
from sklearn.cluster import KMeans
from scipy.spatial.distance import cdist, pdist
import matplotlib.pyplot as plt
plt.style.use('ggplot')
KM = [KMeans(n_clusters=k, n_jobs=-1).fit(data) for k in k_range]
centroids = [k.cluster_centers_ for k in KM]
D_k = [cdist(data, cent, 'euclidean') for cent in centroids]
cIdx = [np.argmin(D, axis=1) for D in D_k]
dist = [np.min(D, axis=1) for D in D_k]
avgWithinSS = [sum(d) / data.shape[0] for d in dist]
# Total with-in sum of square
wcss = [sum(d ** 2) for d in dist]
tss = sum(pdist(data) ** 2) / data.shape[0]
bss = tss - wcss
kIdx = 10 - 1
# elbow curve
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(k_range, avgWithinSS, 'b*-')
ax.plot(k_range[kIdx], avgWithinSS[kIdx], marker='o', markersize=12,
markeredgewidth=2, markeredgecolor='r', markerfacecolor='None')
plt.grid(True)
plt.xlabel('Number of clusters')
plt.ylabel('Average within-cluster sum of squares')
plt.title('Elbow for KMeans clustering')
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(k_range, bss / tss * 100, 'b*-')
plt.grid(True)
plt.xlabel('Number of clusters')
plt.ylabel('Percentage of variance explained')
plt.title('Elbow for KMeans clustering')
print("=> Completed in %fs" % (time() - t0))
def cluster_users(self, k):
t0 = time()
from sklearn.cluster import KMeans
x = self._users
kmeans_clustering = KMeans(n_clusters=k, n_jobs=-1)
idx = kmeans_clustering.fit_predict(x)
unique, counts = np.unique(idx, return_counts=True)
print(dict(zip(unique, counts)))
labels = kmeans_clustering.labels_
name = 'kmeans'
sample_size = 300
from sklearn import metrics
print('% 9s %.2fs %i %.3f %.3f %.3f %.3f %.3f %.3f'
% (name, (time() - t0), kmeans_clustering.inertia_,
metrics.homogeneity_score(labels, kmeans_clustering.labels_),
metrics.completeness_score(labels, kmeans_clustering.labels_),
metrics.v_measure_score(labels, kmeans_clustering.labels_),
metrics.adjusted_rand_score(labels, kmeans_clustering.labels_),
metrics.adjusted_mutual_info_score(labels, kmeans_clustering.labels_),
metrics.silhouette_score(x, kmeans_clustering.labels_,
metric='euclidean',
sample_size=sample_size)))
self._users['cluster'] = labels
print(self._users['cluster'])
def do_cv(self, X=None, Y=None, params=None, model_type='xgb', max_rounds=1500, get_f1=False):
if X is None:
X = self._train
if Y is None:
Y = self._train['reordered']
X.drop(['reordered'], axis=1, inplace=True)
if params is None and model_type == 'xgb':
params = self._xgb_params
if params is None and model_type == 'lgb':
params = self._lgb_params
# X_train, X_val, Y_train, Y_val = train_test_split(X, Y, test_size=0.2, random_state=42)
if get_f1 is True:
X_train, X_known_test, Y_train, Y_known_test = train_test_split(X_train, Y_train, test_size=0.2,
random_state=42)
X_known_test.is_copy = False
x_known_ids = X_known_test['order_id']
X_known_test.drop(['order_id'], axis=1, inplace=True)
# Turn off the SettingWithCopyWarning warning
# X_train.is_copy = False
# X_val.is_copy = False
# Drop the order_id from all x datasets
# X_train.drop(['order_id'], axis=1, inplace=True)
# X_val.drop(['order_id'], axis=1, inplace=True)
if model_type == 'lgb':
train_data = lgb.Dataset(X_train, Y_train, free_raw_data=False)
eval_data = lgb.Dataset(X_val, Y_val, free_raw_data=False)
model = lgb.train(params,
train_data,
num_boost_round=max_rounds,
valid_sets=eval_data,
early_stopping_rounds=50)
best = model.best_iteration
print("Best iteration at %d" % best)
# It looks like if the lgb runs out of rounds it sets the best to 0
if best == 0:
best = max_rounds
# predict
y_pred = model.predict(X_val, num_iteration=best)
# from sklearn.metrics import f1_score
# print('[*] The F1 score of prediction in the validation set is:', f1_score(Y_val, y_pred))
return best, 0
else:
def fpreproc(dtrain, dtest, param):
label = dtrain.get_label()
ratio = float(np.sum(label == 0)) / np.sum(label == 1)
param['scale_pos_weight'] = ratio
return (dtrain, dtest, param)
# train_data = xgb.DMatrix(X_train, Y_train, feature_names=X.columns)
# dval = xgb.DMatrix(X_val, Y_val, feature_names=X_val.columns)
# cv_xgb = xgb.train(params, train_data, num_boost_round=max_rounds, evals=[(dval, 'val')],
# early_stopping_rounds=50,
# verbose_eval=20)
train_data = xgb.DMatrix(X.values, | |
<reponame>gpooja3/pyvcloud
# VMware vCloud Director Python SDK
# Copyright (c) 2018 VMware, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from pyvcloud.vcd.client import E
from pyvcloud.vcd.client import E_VMEXT
from pyvcloud.vcd.client import EntityType
from pyvcloud.vcd.client import NSMAP
from pyvcloud.vcd.client import QueryResultFormat
from pyvcloud.vcd.client import RelationType
from pyvcloud.vcd.client import ResourceType
from pyvcloud.vcd.exceptions import EntityNotFoundException
from pyvcloud.vcd.exceptions import InvalidParameterException
from pyvcloud.vcd.gateway import Gateway
from pyvcloud.vcd.platform import Platform
from pyvcloud.vcd.pvdc import PVDC
from pyvcloud.vcd.utils import get_admin_href
class ExternalNetwork(object):
def __init__(self, client, name=None, href=None, resource=None):
"""Constructor for External Network objects.
:param pyvcloud.vcd.client.Client client: the client that will be used
to make REST calls to vCD.
:param str name: name of the entity.
:param str href: URI of the entity.
:param lxml.objectify.ObjectifiedElement resource: object containing
EntityType.EXTERNAL_NETWORK XML data representing the external
network.
"""
self.client = client
self.name = name
if href is None and resource is None:
raise InvalidParameterException(
"External network initialization failed as arguments are "
"either invalid or None")
self.href = href
self.resource = resource
if resource is not None:
self.name = resource.get('name')
self.href = resource.get('href')
self.href_admin = get_admin_href(self.href)
def get_resource(self):
"""Fetches the XML representation of the external network from vCD.
Will serve cached response if possible.
:return: object containing EntityType.EXTERNAL_NETWORK XML data
representing the external network.
:rtype: lxml.objectify.ObjectifiedElement
"""
if self.resource is None:
self.reload()
return self.resource
def reload(self):
"""Reloads the resource representation of the external network.
This method should be called in between two method invocations on the
external network object, if the former call changes the representation
of the external network in vCD.
"""
self.resource = self.client.get_resource(self.href)
if self.resource is not None:
self.name = self.resource.get('name')
self.href = self.resource.get('href')
def add_subnet(self,
name,
gateway_ip,
netmask,
ip_ranges,
primary_dns_ip=None,
secondary_dns_ip=None,
dns_suffix=None):
"""Add subnet to an external network.
:param str name: Name of external network.
:param str gateway_ip: IP address of the gateway of the new network.
:param str netmask: Netmask of the gateway.
:param list ip_ranges: list of IP ranges used for static pool
allocation in the network. For example, [192.168.1.2-192.168.1.49,
192.168.1.100-192.168.1.149].
:param str primary_dns_ip: IP address of primary DNS server.
:param str secondary_dns_ip: IP address of secondary DNS Server.
:param str dns_suffix: DNS suffix.
:rtype: lxml.objectify.ObjectifiedElement
"""
if self.resource is None:
self.reload()
platform = Platform(self.client)
ext_net = platform.get_external_network(name)
config = ext_net['{' + NSMAP['vcloud'] + '}Configuration']
ip_scopes = config.IpScopes
ip_scope = E.IpScope()
ip_scope.append(E.IsInherited(False))
ip_scope.append(E.Gateway(gateway_ip))
ip_scope.append(E.Netmask(netmask))
if primary_dns_ip is not None:
ip_scope.append(E.Dns1(primary_dns_ip))
if secondary_dns_ip is not None:
ip_scope.append(E.Dns2(secondary_dns_ip))
if dns_suffix is not None:
ip_scope.append(E.DnsSuffix(dns_suffix))
ip_scope.append(E.IsEnabled(True))
e_ip_ranges = E.IpRanges()
for ip_range in ip_ranges:
e_ip_range = E.IpRange()
ip_range_token = ip_range.split('-')
e_ip_range.append(E.StartAddress(ip_range_token[0]))
e_ip_range.append(E.EndAddress(ip_range_token[1]))
e_ip_ranges.append(e_ip_range)
ip_scope.append(e_ip_ranges)
ip_scopes.append(ip_scope)
return self.client.put_linked_resource(
ext_net,
rel=RelationType.EDIT,
media_type=EntityType.EXTERNAL_NETWORK.value,
contents=ext_net)
def enable_subnet(self, gateway_ip, is_enabled=None):
"""Enable subnet of an external network.
:param str gateway_ip: IP address of the gateway of external network.
:param bool is_enabled: flag to enable/disable the subnet
:rtype: lxml.objectify.ObjectifiedElement
"""
ext_net = self.client.get_resource(self.href)
config = ext_net['{' + NSMAP['vcloud'] + '}Configuration']
ip_scopes = config.IpScopes
if is_enabled is not None:
for ip_scope in ip_scopes.IpScope:
if ip_scope.Gateway == gateway_ip:
if hasattr(ip_scope, 'IsEnabled'):
ip_scope['IsEnabled'] = E.IsEnabled(is_enabled)
return self.client. \
put_linked_resource(ext_net, rel=RelationType.EDIT,
media_type=EntityType.
EXTERNAL_NETWORK.value,
contents=ext_net)
return ext_net
def add_ip_range(self, gateway_ip, ip_ranges):
"""Add new ip range into a subnet of an external network.
:param str gateway_ip: IP address of the gateway of external network.
:param list ip_ranges: list of IP ranges used for static pool
allocation in the network. For example, [192.168.1.2-192.168.1.49,
192.168.1.100-192.168.1.149]
:rtype: lxml.objectify.ObjectifiedElement
"""
ext_net = self.client.get_resource(self.href)
config = ext_net['{' + NSMAP['vcloud'] + '}Configuration']
ip_scopes = config.IpScopes
for ip_scope in ip_scopes.IpScope:
if ip_scope.Gateway == gateway_ip:
existing_ip_ranges = ip_scope.IpRanges
break
for range in ip_ranges:
range_token = range.split('-')
e_ip_range = E.IpRange()
e_ip_range.append(E.StartAddress(range_token[0]))
e_ip_range.append(E.EndAddress(range_token[1]))
existing_ip_ranges.append(e_ip_range)
return self.client. \
put_linked_resource(ext_net, rel=RelationType.EDIT,
media_type=EntityType.
EXTERNAL_NETWORK.value,
contents=ext_net)
def modify_ip_range(self, gateway_ip, old_ip_range, new_ip_range):
"""Modify ip range of a subnet in external network.
:param str gateway_ip: IP address of the gateway of external
network.
:param str old_ip_range: existing ip range present in the static pool
allocation in the network. For example, [192.168.1.2-192.168.1.20]
:param str new_ip_range: new ip range to replace the existing ip range
present in the static pool allocation in the network.
:return: object containing vmext:VMWExternalNetwork XML element that
representing the external network.
:rtype: lxml.objectify.ObjectifiedElement
"""
if self.resource is None:
self.reload()
ext_net = self.resource
old_ip_addrs = old_ip_range.split('-')
new_ip_addrs = new_ip_range.split('-')
config = ext_net['{' + NSMAP['vcloud'] + '}Configuration']
ip_scopes = config.IpScopes
ip_range_found = False
for ip_scope in ip_scopes.IpScope:
if ip_scope.Gateway == gateway_ip:
for exist_ip_range in ip_scope.IpRanges.IpRange:
if exist_ip_range.StartAddress == \
old_ip_addrs[0] and \
exist_ip_range.EndAddress \
== old_ip_addrs[1]:
exist_ip_range['StartAddress'] = \
E.StartAddress(new_ip_addrs[0])
exist_ip_range['EndAddress'] = \
E.EndAddress(new_ip_addrs[1])
ip_range_found = True
break
if not ip_range_found:
raise EntityNotFoundException(
'IP Range \'%s\' not Found' % old_ip_range)
return self.client. \
put_linked_resource(ext_net, rel=RelationType.EDIT,
media_type=EntityType.
EXTERNAL_NETWORK.value,
contents=ext_net)
def delete_ip_range(self, gateway_ip, ip_ranges):
"""Delete ip range of a subnet in external network.
:param str gateway_ip: IP address of the gateway of external
network.
:param list ip_ranges: existing ip range present in the static pool
allocation in the network to be deleted.
For example, [192.168.1.2-192.168.1.20]
:return: object containing vmext:VMWExternalNetwork XML element that
representing the external network.
:rtype: lxml.objectify.ObjectifiedElement
"""
if self.resource is None:
self.reload()
ext_net = self.resource
config = ext_net['{' + NSMAP['vcloud'] + '}Configuration']
ip_scopes = config.IpScopes
for ip_scope in ip_scopes.IpScope:
if ip_scope.Gateway == gateway_ip:
exist_ip_ranges = ip_scope.IpRanges
self.__remove_ip_range_elements(exist_ip_ranges, ip_ranges)
return self.client. \
put_linked_resource(ext_net, rel=RelationType.EDIT,
media_type=EntityType.
EXTERNAL_NETWORK.value,
contents=ext_net)
def attach_port_group(self, vim_server_name, port_group_name):
"""Attach a portgroup to an external network.
:param str vc_name: name of vc where portgroup is present.
:param str pg_name: name of the portgroup to be attached to
external network.
return: object containing vmext:VMWExternalNetwork XML element that
representing the external network.
:rtype: lxml.objectify.ObjectifiedElement
"""
ext_net = self.get_resource()
platform = Platform(self.client)
if not vim_server_name or not port_group_name:
raise InvalidParameterException(
"Either vCenter Server name is none or portgroup name is none")
vc_record = platform.get_vcenter(vim_server_name)
vc_href = vc_record.get('href')
pg_moref_types = \
platform.get_port_group_moref_types(vim_server_name,
port_group_name)
if hasattr(ext_net, '{' + NSMAP['vmext'] + '}VimPortGroupRef'):
vim_port_group_refs = E_VMEXT.VimPortGroupRefs()
vim_object_ref1 = self.__create_vimobj_ref(
vc_href, pg_moref_types[0], pg_moref_types[1])
# Create a new VimObjectRef using vc href, portgroup moref and type
# from existing VimPortGroupRef. Add the VimObjectRef to
# VimPortGroupRefs and then delete VimPortGroupRef
# from external network.
vim_pg_ref = ext_net['{' + NSMAP['vmext'] + '}VimPortGroupRef']
vc2_href = vim_pg_ref.VimServerRef.get('href')
vim_object_ref2 = self.__create_vimobj_ref(
vc2_href, vim_pg_ref.MoRef.text, vim_pg_ref.VimObjectType.text)
vim_port_group_refs.append(vim_object_ref1)
vim_port_group_refs.append(vim_object_ref2)
ext_net.remove(vim_pg_ref)
ext_net.append(vim_port_group_refs)
else:
vim_port_group_refs = \
ext_net['{' + NSMAP['vmext'] + '}VimPortGroupRefs']
vim_object_ref1 = self.__create_vimobj_ref(
vc_href, pg_moref_types[0], pg_moref_types[1])
vim_port_group_refs.append(vim_object_ref1)
return self.client. \
put_linked_resource(ext_net, rel=RelationType.EDIT,
media_type=EntityType.
EXTERNAL_NETWORK.value,
contents=ext_net)
def __create_vimobj_ref(self, vc_href, pg_moref, pg_type):
"""Creates the VimObjectRef."""
vim_object_ref = E_VMEXT.VimObjectRef()
vim_object_ref.append(E_VMEXT.VimServerRef(href=vc_href))
vim_object_ref.append(E_VMEXT.MoRef(pg_moref))
vim_object_ref.append(E_VMEXT.VimObjectType(pg_type))
return vim_object_ref
def detach_port_group(self, vim_server_name, port_group_name):
"""Detach a portgroup from an external network.
:param str vim_server_name: name of vim server where
portgroup is present.
:param str port_group_name: name of the portgroup to be detached from
external network.
return: object containing vmext:VMWExternalNetwork XML element that
representing the external network.
:rtype: lxml.objectify.ObjectifiedElement
"""
ext_net = self.get_resource()
platform = Platform(self.client)
if not vim_server_name or not port_group_name:
raise InvalidParameterException(
"Either vCenter Server name is none or portgroup name is none")
vc_record = platform.get_vcenter(vim_server_name)
vc_href = vc_record.get('href')
if hasattr(ext_net, 'VimPortGroupRefs'):
pg_moref_types = \
platform.get_port_group_moref_types(vim_server_name,
port_group_name)
else:
raise \
InvalidParameterException("External network"
" has only one port group")
vim_port_group_refs = ext_net.VimPortGroupRefs
vim_obj_refs = vim_port_group_refs.VimObjectRef
for vim_obj_ref in vim_obj_refs:
if vim_obj_ref.VimServerRef.get('href') == vc_href \
and vim_obj_ref.MoRef == pg_moref_types[0] \
and vim_obj_ref.VimObjectType == pg_moref_types[1]:
vim_port_group_refs.remove(vim_obj_ref)
return self.client. \
put_linked_resource(ext_net, rel=RelationType.EDIT,
media_type=EntityType.
EXTERNAL_NETWORK.value,
contents=ext_net)
def list_provider_vdc(self, filter=None):
"""List associated provider vdcs.
:param str filter: filter to fetch the selected pvdc, e.g., name==pvdc*
:return: list of associated provider vdcs
:rtype: list
"""
pvdc_name_list = []
query = self.client.get_typed_query(
ResourceType.PROVIDER_VDC.value,
query_result_format=QueryResultFormat.RECORDS,
qfilter=filter)
records = query.execute()
if records is None:
raise EntityNotFoundException('No Provider Vdc found associated')
for record in |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.