code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import os
import shutil
from contextlib import (
contextmanager,
)
from pathlib import Path
import pytest
@pytest.fixture(scope='function', autouse=True)
def cleanup():
test_generate_dir = (Path('.') / 'tests' / 'biisan_data')
if test_generate_dir.exists():
shutil.rmtree(test_generate_dir)
yield
if test_generate_dir.exists():
shutil.rmtree(test_generate_dir)
@pytest.fixture(scope='function', autouse=True)
def setenv():
os.environ['BIISAN_SETTINGS_MODULE'] = 'tests.biisan_data.data.biisan_local_settings'
yield
del os.environ['BIISAN_SETTINGS_MODULE']
@contextmanager
def cd(to):
prev_cwd = Path.cwd()
os.chdir(to)
try:
yield
finally:
os.chdir(prev_cwd)
def _copy_blog(entry_file):
src = Path('.') / 'test_data' / entry_file
dest = Path('.') / 'biisan_data' / 'data' / 'blog' / entry_file
shutil.copyfile(src, dest)
def copy_first_blog():
_copy_blog('my_first_blog.rst')
def copy_second_blog():
_copy_blog('my_second_blog.rst')
def copy_test_local_settings():
src = Path('.') / 'test_data' / 'biisan_local_settings.py'
dest = Path('.') / 'biisan_data' / 'data' / 'biisan_local_settings.py'
shutil.copyfile(src, dest)
| [
"pathlib.Path",
"pathlib.Path.cwd",
"os.chdir",
"shutil.copyfile",
"shutil.rmtree",
"pytest.fixture"
] | [((114, 160), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""', 'autouse': '(True)'}), "(scope='function', autouse=True)\n", (128, 160), False, 'import pytest\n'), ((403, 449), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""', 'autouse': '(True)'}), "(scope='function', autouse=True)\n", (417, 449), False, 'import pytest\n'), ((654, 664), 'pathlib.Path.cwd', 'Path.cwd', ([], {}), '()\n', (662, 664), False, 'from pathlib import Path\n'), ((669, 681), 'os.chdir', 'os.chdir', (['to'], {}), '(to)\n', (677, 681), False, 'import os\n'), ((894, 920), 'shutil.copyfile', 'shutil.copyfile', (['src', 'dest'], {}), '(src, dest)\n', (909, 920), False, 'import shutil\n'), ((1221, 1247), 'shutil.copyfile', 'shutil.copyfile', (['src', 'dest'], {}), '(src, dest)\n', (1236, 1247), False, 'import shutil\n'), ((281, 313), 'shutil.rmtree', 'shutil.rmtree', (['test_generate_dir'], {}), '(test_generate_dir)\n', (294, 313), False, 'import shutil\n'), ((367, 399), 'shutil.rmtree', 'shutil.rmtree', (['test_generate_dir'], {}), '(test_generate_dir)\n', (380, 399), False, 'import shutil\n'), ((726, 744), 'os.chdir', 'os.chdir', (['prev_cwd'], {}), '(prev_cwd)\n', (734, 744), False, 'import os\n'), ((201, 210), 'pathlib.Path', 'Path', (['"""."""'], {}), "('.')\n", (205, 210), False, 'from pathlib import Path\n'), ((785, 794), 'pathlib.Path', 'Path', (['"""."""'], {}), "('.')\n", (789, 794), False, 'from pathlib import Path\n'), ((1089, 1098), 'pathlib.Path', 'Path', (['"""."""'], {}), "('.')\n", (1093, 1098), False, 'from pathlib import Path\n'), ((1153, 1162), 'pathlib.Path', 'Path', (['"""."""'], {}), "('.')\n", (1157, 1162), False, 'from pathlib import Path\n'), ((833, 842), 'pathlib.Path', 'Path', (['"""."""'], {}), "('.')\n", (837, 842), False, 'from pathlib import Path\n')] |
"""
File: stanCodoshop.py
Name: <NAME>
----------------------------------------------
SC101_Assignment3
Adapted from <NAME>'s
Ghost assignment by <NAME>.
-----------------------------------------------
Remove people or abnormal objects in a certain photo.
"""
import os
import sys
import time
from simpleimage import SimpleImage
def get_pixel_dist(pixel, red, green, blue):
"""
Returns the color distance between pixel and mean RGB value
Input:
pixel (Pixel): pixel with RGB values to be compared
red (int): average red value across all images
green (int): average green value across all images
blue (int): average blue value across all images
Returns:
dist (int): color distance between red, green, and blue pixel values
"""
dist = (((red - pixel.red) ** 2) + ((green - pixel.green) ** 2) + ((blue - pixel.blue) ** 2)) ** (1/2)
return dist
def get_average(pixels):
"""
Given a list of pixels, finds the average red, blue, and green values
Input:
pixels (List[Pixel]): list of pixels to be averaged
Returns:
rgb (List[int]): list of average red, green, blue values across pixels respectively
Assumes you are returning in the order: [red, green, blue]
"""
# Create three variables to add up all pixel values.
red = 0
green = 0
blue = 0
for pixel in pixels:
red += pixel.red
green += pixel.green
blue += pixel.blue
return [red // len(pixels), green // len(pixels), blue // len(pixels)]
def get_best_pixel(pixels):
"""
Given a list of pixels, returns the pixel with the smallest
distance from the average red, green, and blue values across all pixels.
Input:
pixels (List[Pixel]): list of pixels to be averaged and compared
Returns:
best (Pixel): pixel closest to RGB averages
"""
red_avg = get_average(pixels)[0]
green_avg = get_average(pixels)[1]
blue_avg = get_average(pixels)[2]
dist = float('inf')
# Variable 'index' represents the index of pixel in list pixels.
best = get_pixel_dist(pixels[0], red_avg, green_avg, blue_avg)
for pixel in pixels:
# Set condition to renew variables.
if get_pixel_dist(pixel, red_avg, green_avg, blue_avg) < dist:
# Renew value of dist.
dist = get_pixel_dist(pixel, red_avg, green_avg, blue_avg)
# Renew value of index.
best = pixel
return best
# Method 2 #
# dist = []
# for i in range(len(pixels)):
# dist.append(get_pixel_dist(pixels[i], red_avg, green_avg, blue_avg))
# index = dist.index(min(dist))
# best = pixels[index]
# return best
# End Method 2 #
def solve(images):
"""
Given a list of image objects, compute and display a Ghost solution image
based on these images. There will be at least 3 images and they will all
be the same size.
Input:
images (List[SimpleImage]): list of images to be processed
"""
start = time.time()
width = images[0].width
height = images[0].height
result = SimpleImage.blank(width, height)
# Scan through all pixels.
for x in range(width):
for y in range(height):
# Create a list of pixels for the function 'get_best_pixel'.
pixels = []
for image in images:
pixels.append(image.get_pixel(x, y))
# Best pixel of a certain pixel in the image.
best = get_best_pixel(pixels)
# Each pixel of the result image is set as best
result.set_pixel(x, y, best)
end = time.time()
print(end-start)
# Method 2 #
# for x in range(width):
# for y in range(height):
# pixels = []
# result_pix = result.get_pixel(x, y)
# for image in images:
# pixels.append(image.get_pixel(x, y))
# best = get_best_pixel(pixels)
# result_pix.red = best.red
# result_pix.green = best.green
# result_pix.blue = best.blue
# End Method 2 #
print("Displaying image!")
result.show()
def jpgs_in_dir(direc):
"""
(provided, DO NOT MODIFY)
Given the name of a directory, returns a list of the .jpg filenames
within it.
Input:
dir (string): name of directory
Returns:
filenames(List[string]): names of jpg files in directory
"""
filenames = []
for filename in os.listdir(direc):
if filename.endswith('.jpg'):
filenames.append(os.path.join(direc, filename))
return filenames
def load_images(direc):
"""
(provided, DO NOT MODIFY)
Given a directory name, reads all the .jpg files within it into memory and
returns them in a list. Prints the filenames out as it goes.
Input:
dir (string): name of directory
Returns:
images (List[SimpleImages]): list of images in directory
"""
images = []
jpgs = jpgs_in_dir(direc)
for filename in jpgs:
print("Loading", filename)
image = SimpleImage(filename)
images.append(image)
return images
def main():
# (provided, DO NOT MODIFY)
args = sys.argv[1:]
# We just take 1 argument, the folder containing all the images.
# The load_images() capability is provided above.
images = load_images(args[0])
solve(images)
if __name__ == '__main__':
main()
| [
"os.listdir",
"simpleimage.SimpleImage.blank",
"os.path.join",
"simpleimage.SimpleImage",
"time.time"
] | [((3042, 3053), 'time.time', 'time.time', ([], {}), '()\n', (3051, 3053), False, 'import time\n'), ((3125, 3157), 'simpleimage.SimpleImage.blank', 'SimpleImage.blank', (['width', 'height'], {}), '(width, height)\n', (3142, 3157), False, 'from simpleimage import SimpleImage\n'), ((3642, 3653), 'time.time', 'time.time', ([], {}), '()\n', (3651, 3653), False, 'import time\n'), ((4489, 4506), 'os.listdir', 'os.listdir', (['direc'], {}), '(direc)\n', (4499, 4506), False, 'import os\n'), ((5096, 5117), 'simpleimage.SimpleImage', 'SimpleImage', (['filename'], {}), '(filename)\n', (5107, 5117), False, 'from simpleimage import SimpleImage\n'), ((4575, 4604), 'os.path.join', 'os.path.join', (['direc', 'filename'], {}), '(direc, filename)\n', (4587, 4604), False, 'import os\n')] |
# coding: utf-8
#
# This code is part of qclib.
#
# Copyright (c) 2021, <NAME>
import numpy as np
from ..math import apply_statevec, apply_density, density_matrix
from .measure import measure_qubit, measure_qubit_rho
class DensityMatrix:
def __init__(self, mat):
self._data = np.asarray(mat)
def __len__(self):
return len(self._data)
def __iter__(self):
return iter(self._data)
def __getitem__(self, item):
return self._data[item]
def __str__(self):
return str(self._data)
def copy(self):
return self.__class__(self._data.copy())
def apply(self, operator):
self._data = apply_density(self._data, operator)
def measure(self, qubit, eigvals=None, eigvecs=None):
res, self._data = measure_qubit_rho(self._data, qubit, eigvals, eigvecs)
return res
class StateVector:
def __init__(self, vec):
self._data = np.asarray(vec)
def __len__(self):
return len(self._data)
def __iter__(self):
return iter(self._data)
def __getitem__(self, item):
return self._data[item]
def __str__(self):
return str(self._data)
def copy(self):
return self.__class__(self._data.copy())
def apply(self, operator):
self._data = apply_statevec(self._data, operator)
def measure(self, qubit, eigvals=None, eigvecs=None):
res, self._data = measure_qubit(self._data, qubit, eigvals, eigvecs)
return res
def to_density(self):
return DensityMatrix(density_matrix(self._data))
| [
"numpy.asarray"
] | [((292, 307), 'numpy.asarray', 'np.asarray', (['mat'], {}), '(mat)\n', (302, 307), True, 'import numpy as np\n'), ((931, 946), 'numpy.asarray', 'np.asarray', (['vec'], {}), '(vec)\n', (941, 946), True, 'import numpy as np\n')] |
#!/usr/bin/env python
# coding: utf-8
# #### Modeling the elemental stoichiometry of phytoplankton and surrounding surface waters in and upwelling or estuarine system
# >Steps to complete project:
# >1. Translate matlab physical model into python
# >2. Substitute Dynamic CFM into model for eco component
# >3. Analyze the results
#
# In[1]:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import math as m
from math import pi
import time
import pylab as lab
# In[2]:
#create the time grid
sperd=60*60*24 #seconds per day
spery=365*sperd #seconds per year
nyr=1 #number of years to simulate. This can be chagned by the user
T=spery*nyr #length of time in seconds to simulate
dt=spery/720 #time step
t=np.arange(0,T+dt,dt) #create a time array
Nt=T/dt+1 #number of time grid points
Nt=int(Nt)
# In[3]:
#create the spatial grid
Lx=5e5 #length in meters
dx=1e3 #grid spacing
Nx=(Lx/dx)+1 #number of grid points
Nx=int(Nx)
xx=np.arange(0,Lx+dx,dx) #create a space array
# In[4]:
#wind forcing
U0=0.1 #velocity (m/s) subject to change
# In[5]:
#initial conditions of nutrient variables NO3 (Nnut) and PO4 (Pnut)
Pnut=2*np.ones(Nx) #creating a ones array the size of the number of spatial grid points
Pnut_i=Pnut[0] #initial value of phosphorus at the coastal boundary
Rup_Po=10*Pnut_i/spery #baseline P uptake rate (will be changed with CFM-Phyto)
Nnut=Pnut*15 #assume NO3 concentration higher than PO4. Change based on field observations
Nnut_i=Pnut_i*15 #intial value of NO3 available at the coastal boundary
Rup_No=10*Nnut_i/spery #baseline N uptake rate (will be changed with CFM-Phyto)
# In[6]:
#initial condition of biomass variables- to be replaced with CFM later
Pbio=0.01*Pnut
Pbio_i=0.01*Pnut_i #phytoplankton P at coast (boundary condition)
Nbio=0.01*Nnut
Nbio_i=0.01*Nnut_i #phytoplankton N at coast (boundary condition)
print(np.size(Nbio))
# In[7]:
#initial biological parameters
Kp=0.1 #half-saturation constant for Pnut
Kn=1 #half-saturation constant for Nnut
mu= 1/sperd #growth rate per sec
phi=0.5 #fraction of uptake remineralized locally
Snp=16 #redfield N:P ratio of phytoplankton
m2=mu*0.2 #quadratic mortality
# In[8]:
#
Period=1 #period of oscillation in forcing (velocity) (yr)
w=(2*pi)/Period #frequency of oscillation
A0=0.5 #amplitude of oscillation
nn=0 #year counter
# In[9]:
it_Nx=np.arange(0,Nx-1,1)
it_Nt=np.arange(0,Nt+1,1)
f=[]
Ua=[]
for n in it_Nt:
#vary the circulation rates
for y in t:
f=A0*(m.sin(w*y/spery))
#fn.append(f)
U0_array=np.full_like(f,U0)
Ua=U0*f
U=U0+Ua
#calculate the biological rates-to be replaced by CFM
RgrowN=mu*Nbio*(Nnut/(Nnut+Kn))
RmortN=m2*Nbio**2
RbioN=RgrowN-RmortN
RnutN=-RgrowN+phi*RmortN
RbioP=RbioN/Snp
RnutP=RnutN/Snp
#update the distribution: Advection scheme
for i in it_Nx:
Pnut[i+1]=((dt/dx)*U*Pnut[i]+Pnut[i+1]+RnutP[i]*dt)/(1+dt/dx*U)
Nnut[i+1]=((dt/dx)*U*Nnut[i]+Nnut[i+1]+RnutN[i]*dt)/(1+dt/dx*U)
Pbio[i+1]=((dt/dx)*U*Pbio[i]+Pbio[i+1]+RbioP[i]*dt)/(1+dt/dx*U)
Nbio[i+1]=((dt/dx)*U*Nbio[i]+Nbio[i+1]+RbioN[i]*dt)/(1+dt/dx*U)
print((Pnut))
# In[33]:
#some plotting
ax=plt.figure(1)
plt.subplot(2,2,1)
x=np.arange(0,Lx+dx,dx)
x=x*1e-3
plt.plot(x,Pnut,marker='o',color='orange')
plt.xlabel('horizontal distance (km)')
plt.ylabel('PO4 (uM)')
plt.subplot(2,2,2)
plt.plot(x,Nnut,marker='o',color='green')
plt.xlabel('horizontal distance (km)')
plt.ylabel('NO3 (uM)')
plt.subplot(2,2,3)
plt.plot(x,Pbio,marker='o',color='red')
plt.xlabel('horizontal distance (km)')
plt.ylabel('Phyto P (uM)')
plt.subplot(2,2,4)
plt.plot(x,Nbio,marker='o',color='blue')
plt.xlabel('horizontal distance (km)')
plt.ylabel('Phyto N (uM)')
plt.tight_layout()
plt.savefig('Nutrient_Concentrations.png')
plt.show()
# In[ ]:
| [
"matplotlib.pyplot.savefig",
"numpy.ones",
"numpy.full_like",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.size",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.tight_layout",
"math.sin",
"matplotlib.pyplot.subplot",
"numpy.arange",
"matplotlib.pyp... | [((757, 781), 'numpy.arange', 'np.arange', (['(0)', '(T + dt)', 'dt'], {}), '(0, T + dt, dt)\n', (766, 781), True, 'import numpy as np\n'), ((1016, 1041), 'numpy.arange', 'np.arange', (['(0)', '(Lx + dx)', 'dx'], {}), '(0, Lx + dx, dx)\n', (1025, 1041), True, 'import numpy as np\n'), ((2479, 2502), 'numpy.arange', 'np.arange', (['(0)', '(Nx - 1)', '(1)'], {}), '(0, Nx - 1, 1)\n', (2488, 2502), True, 'import numpy as np\n'), ((2505, 2528), 'numpy.arange', 'np.arange', (['(0)', '(Nt + 1)', '(1)'], {}), '(0, Nt + 1, 1)\n', (2514, 2528), True, 'import numpy as np\n'), ((3347, 3360), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (3357, 3360), True, 'import matplotlib.pyplot as plt\n'), ((3361, 3381), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(1)'], {}), '(2, 2, 1)\n', (3372, 3381), True, 'import matplotlib.pyplot as plt\n'), ((3382, 3407), 'numpy.arange', 'np.arange', (['(0)', '(Lx + dx)', 'dx'], {}), '(0, Lx + dx, dx)\n', (3391, 3407), True, 'import numpy as np\n'), ((3413, 3458), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'Pnut'], {'marker': '"""o"""', 'color': '"""orange"""'}), "(x, Pnut, marker='o', color='orange')\n", (3421, 3458), True, 'import matplotlib.pyplot as plt\n'), ((3456, 3494), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""horizontal distance (km)"""'], {}), "('horizontal distance (km)')\n", (3466, 3494), True, 'import matplotlib.pyplot as plt\n'), ((3495, 3517), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""PO4 (uM)"""'], {}), "('PO4 (uM)')\n", (3505, 3517), True, 'import matplotlib.pyplot as plt\n'), ((3518, 3538), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(2)'], {}), '(2, 2, 2)\n', (3529, 3538), True, 'import matplotlib.pyplot as plt\n'), ((3537, 3581), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'Nnut'], {'marker': '"""o"""', 'color': '"""green"""'}), "(x, Nnut, marker='o', color='green')\n", (3545, 3581), True, 'import matplotlib.pyplot as plt\n'), ((3579, 3617), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""horizontal distance (km)"""'], {}), "('horizontal distance (km)')\n", (3589, 3617), True, 'import matplotlib.pyplot as plt\n'), ((3618, 3640), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""NO3 (uM)"""'], {}), "('NO3 (uM)')\n", (3628, 3640), True, 'import matplotlib.pyplot as plt\n'), ((3641, 3661), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(3)'], {}), '(2, 2, 3)\n', (3652, 3661), True, 'import matplotlib.pyplot as plt\n'), ((3660, 3702), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'Pbio'], {'marker': '"""o"""', 'color': '"""red"""'}), "(x, Pbio, marker='o', color='red')\n", (3668, 3702), True, 'import matplotlib.pyplot as plt\n'), ((3700, 3738), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""horizontal distance (km)"""'], {}), "('horizontal distance (km)')\n", (3710, 3738), True, 'import matplotlib.pyplot as plt\n'), ((3739, 3765), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Phyto P (uM)"""'], {}), "('Phyto P (uM)')\n", (3749, 3765), True, 'import matplotlib.pyplot as plt\n'), ((3766, 3786), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(4)'], {}), '(2, 2, 4)\n', (3777, 3786), True, 'import matplotlib.pyplot as plt\n'), ((3785, 3828), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'Nbio'], {'marker': '"""o"""', 'color': '"""blue"""'}), "(x, Nbio, marker='o', color='blue')\n", (3793, 3828), True, 'import matplotlib.pyplot as plt\n'), ((3826, 3864), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""horizontal distance (km)"""'], {}), "('horizontal distance (km)')\n", (3836, 3864), True, 'import matplotlib.pyplot as plt\n'), ((3865, 3891), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Phyto N (uM)"""'], {}), "('Phyto N (uM)')\n", (3875, 3891), True, 'import matplotlib.pyplot as plt\n'), ((3893, 3911), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (3909, 3911), True, 'import matplotlib.pyplot as plt\n'), ((3912, 3954), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""Nutrient_Concentrations.png"""'], {}), "('Nutrient_Concentrations.png')\n", (3923, 3954), True, 'import matplotlib.pyplot as plt\n'), ((3955, 3965), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3963, 3965), True, 'import matplotlib.pyplot as plt\n'), ((1221, 1232), 'numpy.ones', 'np.ones', (['Nx'], {}), '(Nx)\n', (1228, 1232), True, 'import numpy as np\n'), ((1969, 1982), 'numpy.size', 'np.size', (['Nbio'], {}), '(Nbio)\n', (1976, 1982), True, 'import numpy as np\n'), ((2671, 2690), 'numpy.full_like', 'np.full_like', (['f', 'U0'], {}), '(f, U0)\n', (2683, 2690), True, 'import numpy as np\n'), ((2614, 2634), 'math.sin', 'm.sin', (['(w * y / spery)'], {}), '(w * y / spery)\n', (2619, 2634), True, 'import math as m\n')] |
import requests
sess = requests.session()
import gzip
import json
import time
import os
def downloadyear(year):
print("fetching year", year)
url = "https://nvd.nist.gov/feeds/json/cve/1.1/nvdcve-1.1-{year}.json.gz".format(year=year)
req = sess.get(url, stream=True)
return gzip.open(req.raw).read().decode()
def getdata(year):
# {"id": ["CWE1/CWE2", "CVSSV3 score", "CVSSV2 score", "vector V3", "vector V2"]}
# example: "CVE-2011-1474": ["CWE-400/CWE-835", 5.5, 4.9, "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H", "AV:L/AC:L/Au:N/C:N/I:N/A:C"]
data = json.loads(downloadyear(year))
res = {}
for item in data["CVE_Items"]:
id = item["cve"]["CVE_data_meta"]["ID"]
cwes = [i["value"] for i in item["cve"]["problemtype"]["problemtype_data"][0]["description"]]
cwe = "/".join(cwes)
try:
cvssv3_score, vector_v3 = item["impact"]["baseMetricV3"]["cvssV3"]["baseScore"], item["impact"]["baseMetricV3"]["cvssV3"]["vectorString"]
except:
cvssv3_score, vector_v3 = -1, ""
try:
cvssv2_score, vector_v2 = item["impact"]["baseMetricV2"]["cvssV2"]["baseScore"], item["impact"]["baseMetricV2"]["cvssV2"]["vectorString"]
except:
cvssv2_score, vector_v2 = -1, ""
date = item["publishedDate"].split("T")[0]
res[id] = [cwe, cvssv3_score, cvssv2_score, vector_v3, vector_v2, date]
return res
def fullupdate():
res = {}
currentyear = int(time.strftime("%Y"))
for year in range(2002, currentyear+1):
res.update(getdata(year))
res.update(getdata("recent"))
return res
def writetofile(filepath, data):
d = sorted(data.items(), key=lambda i:(int(i[0].split("-")[1]),int(i[0].split("-")[2])))
with open(filepath, "w") as fp:
for id, itemdata in d:
fp.write(",".join([str(i) for i in [id]+itemdata])+"\n")
def readfromfile(filepath):
data = {}
for _line in open(filepath):
id, cwe, cvssv3_score, cvssv2_score, vector_v3, vector_v2 = _line.strip().split(",")
data[id] = [cwe, float(cvssv3_score), float(cvssv2_score), vector_v3, vector_v2]
return data
if __name__ == "__main__":
#print(getdata("recent"))
#print(os.path.getmtime("/tmp/cvssdata/cvss.csv"), time.time()-os.path.getmtime("/tmp/cvssdata/cvss.csv"))
data = fullupdate()
writetofile("/tmp/cvssdata/cvss.csv", data)
# TODO: add meta data comparation to avoid full update
| [
"requests.session",
"time.strftime",
"gzip.open"
] | [((24, 42), 'requests.session', 'requests.session', ([], {}), '()\n', (40, 42), False, 'import requests\n'), ((1524, 1543), 'time.strftime', 'time.strftime', (['"""%Y"""'], {}), "('%Y')\n", (1537, 1543), False, 'import time\n'), ((301, 319), 'gzip.open', 'gzip.open', (['req.raw'], {}), '(req.raw)\n', (310, 319), False, 'import gzip\n')] |
#!/usr/bin/env python3
''' Perimeterator Enumerator.
This wrapper is intended to allow for simplified AWS based deployment of the
Perimeterator enumerator. This allows for a cost effective method of
execution, as the Perimeterator poller component only needs to execute on a
defined schedule in order to detect changes.
'''
import os
import logging
import perimeterator
# TODO: This should likely be configurable.
MODULES = [
'rds',
'ec2',
'elb',
'elbv2',
'es',
]
def lambda_handler(event, context):
''' An AWS Lambda wrapper for the Perimeterator enumerator. '''
# Strip off any existing handlers that may have been installed by AWS.
logger = logging.getLogger()
for handler in logger.handlers:
logger.removeHandler(handler)
# Reconfigure the root logger the way we want it.
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(process)d - [%(levelname)s] %(message)s'
)
# Get the account id for the current AWS account.
account = perimeterator.helper.aws_account_id()
logger.info("Running in AWS account %s", account)
# Get configurable options from environment variables.
regions = os.getenv("ENUMERATOR_REGIONS", "us-west-2").split(",")
sqs_queue = os.getenv("ENUMERATOR_SQS_QUEUE", None)
logger.info("Configured results SQS queue is %s", sqs_queue)
logger.info(
"Configured regions for resource enumeration are %s",
", ".join(regions)
)
# Setup the SQS dispatcher for submission of addresses to scanners.
queue = perimeterator.dispatcher.sqs.Dispatcher(queue=sqs_queue)
# Process regions one at a time, enumerating addresses for all configured
# resources in the given region. Currently, it's not possible to only
# enumerate different resources types by region. Maybe later! :)
for region in regions:
logger.info("Attempting to enumerate resources in %s", region)
for module in MODULES:
logger.info("Attempting to enumerate %s resources", module)
try:
# Ensure a handler exists for this type of resource.
hndl = getattr(perimeterator.enumerator, module).Enumerator(
region=region
)
except AttributeError as err:
logger.error(
"Handler for %s resources not found, skipping: %s",
module,
err
)
continue
# Get all addresses and dispatch to SQS for processing.
logger.info(
"Submitting %s resources in %s for processing",
module,
region
)
queue.dispatch(account, hndl.get())
if __name__ == '__main__':
''' Allow the script to be invoked outside of Lambda. '''
lambda_handler(
dict(), # No real 'event' data.
dict() # No real 'context' data.
)
| [
"logging.getLogger",
"logging.basicConfig",
"perimeterator.helper.aws_account_id",
"os.getenv",
"perimeterator.dispatcher.sqs.Dispatcher"
] | [((681, 700), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (698, 700), False, 'import logging\n'), ((834, 944), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'format': '"""%(asctime)s - %(process)d - [%(levelname)s] %(message)s"""'}), "(level=logging.INFO, format=\n '%(asctime)s - %(process)d - [%(levelname)s] %(message)s')\n", (853, 944), False, 'import logging\n'), ((1031, 1068), 'perimeterator.helper.aws_account_id', 'perimeterator.helper.aws_account_id', ([], {}), '()\n', (1066, 1068), False, 'import perimeterator\n'), ((1269, 1308), 'os.getenv', 'os.getenv', (['"""ENUMERATOR_SQS_QUEUE"""', 'None'], {}), "('ENUMERATOR_SQS_QUEUE', None)\n", (1278, 1308), False, 'import os\n'), ((1571, 1627), 'perimeterator.dispatcher.sqs.Dispatcher', 'perimeterator.dispatcher.sqs.Dispatcher', ([], {'queue': 'sqs_queue'}), '(queue=sqs_queue)\n', (1610, 1627), False, 'import perimeterator\n'), ((1197, 1241), 'os.getenv', 'os.getenv', (['"""ENUMERATOR_REGIONS"""', '"""us-west-2"""'], {}), "('ENUMERATOR_REGIONS', 'us-west-2')\n", (1206, 1241), False, 'import os\n')] |
# Copyright 2020 Ford Motor Company
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os.path
import subprocess
from cookiecutterassert import messager
class RunScriptRule:
def __init__(self, options, testFolder, runFolder, script):
self.script = script
self.runFolder = runFolder
self.testFolder = testFolder
self.options = options
def execute(self, outputFolder):
workingDir = str(os.path.join(outputFolder, self.runFolder))
scriptprocess = subprocess.Popen(self.script, cwd = workingDir, shell=True)
scriptprocess.wait()
success = scriptprocess.returncode == 0
if (not success):
errorMessage = "assertion runScript {} {} failed. with non-zero return code [{}]".format(self.runFolder, self.script, scriptprocess.returncode)
messager.printError(errorMessage)
return success
def __eq__(self, obj):
return isinstance(obj, RunScriptRule) \
and obj.script == self.script \
and obj.runFolder == self.runFolder \
and obj.testFolder == self.testFolder \
and obj.options == self.options
def __ne__(self, obj):
return not self == obj
def __str__(self):
return "{0}: [testFolder={1}, runFolder={2}, script={3}, options={4}]".format(type(self).__name__, self.testFolder, self.runFolder, self.script, self.options)
def __repr__(self):
return self.__str__() | [
"subprocess.Popen",
"cookiecutterassert.messager.printError"
] | [((1029, 1086), 'subprocess.Popen', 'subprocess.Popen', (['self.script'], {'cwd': 'workingDir', 'shell': '(True)'}), '(self.script, cwd=workingDir, shell=True)\n', (1045, 1086), False, 'import subprocess\n'), ((1361, 1394), 'cookiecutterassert.messager.printError', 'messager.printError', (['errorMessage'], {}), '(errorMessage)\n', (1380, 1394), False, 'from cookiecutterassert import messager\n')] |
"""Test weighted path counting methods."""
# pylint: disable=redefined-outer-name,too-few-public-methods
# pylint: disable=too-many-branches
import pytest
from pytest import approx
import numpy as np
import pandas as pd
from pathcensus.definitions import PathDefinitionsWeighted
from pathcensus import PathCensus
@pytest.fixture(scope="session")
def paths_edges(random_graph):
"""Fixture for generating path census data frames
for edges and node/global counts based `random_graph` fixture.
"""
_, S = random_graph
E = S.census("edges")
return E, S
@pytest.fixture(scope="session")
def paths_edges_nodes(paths_edges):
"""Get edge and node path/cycle counts."""
E, S = paths_edges
return E, S.census("nodes")
@pytest.fixture(scope="session")
def paths_edges_global(paths_edges):
"""Get edge and global path/cycle counts."""
E, S = paths_edges
return E, S.census("global")
@pytest.fixture(scope="session")
def graph_weights_one(random_graph):
"""Pair of :py:class:`pathcensus.PathCensus` objects for weighted and
unweighted version of the same graph with all weights equal to ``1``.
"""
G, _ = random_graph
G.es["weight"] = np.ones((G.ecount(),))
P0 = PathCensus(G, weighted=False)
P1 = PathCensus(G, weighted=True)
return P0, P1
@pytest.fixture(scope="session")
def graph_weights_uniform(random_graph):
"""Pair of :py:class:`pathcensus.PathCensus` objects for weighted and
unweighted version of the same graph with all weights being uniform
but other than ``1``.
"""
G, _ = random_graph
G.es["weight"] = 3*np.ones((G.ecount(),))
P0 = PathCensus(G, weighted=False)
P1 = PathCensus(G, weighted=True)
return P0, P1
class TestPathCounting:
"""Tests of different path counting methods.
All main path counting methods are defined for overall graph counts,
node counts and node-pair (edge) counts. The below tests check whether
the results of all different counting methods are consistent in a sense
that they give the same answers after proper summing.
"""
class TestAggregationConsistency:
"""Tests of aggregation consistency between edge, node
and global counts.
"""
paths = PathDefinitionsWeighted().get_column_names()
@pytest.mark.parametrize("path", paths)
def test_edges_to_nodes(self, path, paths_edges_nodes):
"""Check consistency between edge and node counts
of paths and cycles.
"""
E, N = paths_edges_nodes
m0 = N[path].dropna()
m1 = E[path].groupby(level="i").sum() \
.reindex(N.index) \
.fillna(0)
arules = PathDefinitionsWeighted().aggregation.get("nodes", {})
m1 /= arules.get(path, 1)
assert np.allclose(m0, m1)
@pytest.mark.parametrize("path", paths)
def test_edges_to_global(self, path, paths_edges_global):
"""Check consistency between edge and global counts
of paths and cycles.
"""
E, G = paths_edges_global
m0 = G[path].iloc[0]
m1 = E[path].sum()
arules = PathDefinitionsWeighted().aggregation.get("global", {})
m1 /= arules.get(path, 1)
assert m0 == approx(m1)
class TestCountingAgainstOtherImplementations:
"""Test weighted path counting against mean weighted local
clustering coefficient as defined by Barrat et al.
and implemented in :py:mod:`igraph`.
In general, weighted `t`-clustering should be equal to
the method by Barrat et al.
"""
@pytest.mark.parametrize("undefined", ["nan", "zero"])
def test_mean_local_clustering(self, random_graph, undefined):
G, P = random_graph
c0 = G.transitivity_avglocal_undirected(weights="weight", mode=undefined)
c1 = P.tclust(undefined=undefined).mean(skipna=False)
assert np.isnan([c0, c1]).all() or c0 == approx(c1)
class TestConsistencyBounds:
"""Test consistency in terms of bounds between open
and closed paths. In particular, closed paths (e.g. triangles)
cannot be more frequent than their open counterparts.
Moreover, relational coefficients (similarity and complementarity)
must be bounded between their min/max of their corresponding
clustering and closure coefficients.
"""
@pytest.mark.parametrize("mode", ["edges", "nodes", "global"])
def test_path_counts_consistency(self, random_graph, mode):
_, P = random_graph
C = P.census(mode)
tol = 1e-6
assert (C.values >= 0).all()
assert (C["twc"] <= C["tw"] + tol).all()
assert (C["thc"] <= C["th"] + tol).all()
assert (C["q0wc"] <= C["qw"] + tol).all()
assert (C["q0hc"] <= C["qh"] + tol).all()
@pytest.mark.parametrize("mode", ["edges", "nodes", "global"])
def test_similarity_coefs_consistency(self, random_graph, mode):
_, P = random_graph
C = P.coefs(mode).dropna()
vals = C.values
assert (vals >= -1e-6).all() and (vals <= 1+1e-6).all()
if mode == "nodes":
m0 = C[["tclust", "tclosure"]].min(axis=1)
m1 = C[["tclust", "tclosure"]].max(axis=1)
assert (C["sim"].between(m0, m1)).all()
@pytest.mark.parametrize("mode", ["edges", "nodes", "global"])
def test_complementarity_coefs_consistency(self, random_graph, mode):
_, P = random_graph
C = P.coefs(mode).dropna()
vals = C.values
assert (vals >= -1e-6).all() and (vals <= 1+1e-6).all()
if mode == "nodes":
m0 = C[["qclust", "qclosure"]].min(axis=1)
m1 = C[["qclust", "qclosure"]].max(axis=1)
assert (C["comp"].between(m0, m1)).all()
class TestConsistencyWithUnweightedMethods:
"""Test whether weighted counts with uniform weights
are consistent with the unweighted counts etc.
"""
@staticmethod
def to_unweighted(df):
"""Combine weighted counts so they have the same columns
as unweighted counts.
"""
return pd.DataFrame({
"t": (df["twc"] + df["thc"]) / 2,
"tw": df["tw"],
"th": df["th"],
"q0": (df["q0wc"] + df["q0hc"]) / 2,
"qw": df["qw"],
"qh": df["qh"]
})
@pytest.mark.parametrize("mode", ["edges", "nodes", "global"])
def test_path_counts_consistency(self, graph_weights_one, mode):
"""Test consistency of path counts."""
P0, P1 = graph_weights_one
assert P1.weighted
p0 = P0.census(mode)
p1 = self.to_unweighted(P1.census(mode))
assert np.allclose(p0.values, p1.values)
@pytest.mark.parametrize("mode", ["edges", "nodes", "global"])
def test_coefs_consistency(self, graph_weights_uniform, mode):
"""Test consistency of coefficients."""
P0, P1 = graph_weights_uniform
assert P1.weighted
c0 = P0.coefs(mode, undefined="zero")
c1 = P1.coefs(mode, undefined="zero")
assert np.allclose(c0.values, c1.values)
class TestSimpleMotifs:
"""Test agreement with counts expected for simple motifs
such as triangle, quadrangle and star.
"""
simcoefs = ("sim_g", "sim", "tclust", "tclosure")
compcoefs = ("comp_g", "comp", "qclust", "qclosure")
def approx_in(self, obj, vals, allow_nan=False, **kwds):
"""Auxiliary method for approximate testing if
values in ``objs`` are in ``vals``.
"""
x = obj.values
l = np.zeros_like(x, dtype=bool)
for val in vals:
if allow_nan:
l |= np.isnan(x) | np.isclose(x, val, **kwds)
else:
l |= np.isclose(x, val, **kwds)
return l.all()
def approx_between(self, obj, lo, hi, allow_nan=False, tol=1e-6):
"""Auxiliary method for approximate testing if
valuesin ``obj`` are between ``lo`` and ``hi``.
"""
x = obj.values
l = np.isnan(x) if allow_nan else np.zeros_like(x, dtype=bool)
return (l | (x >= lo-tol) | (x <= hi+tol)).all()
@pytest.mark.parametrize("undefined", ["nan", "zero"])
def test_simple_motifs_global(self, simple_motif, undefined):
"""Check values of global structural coefficients
in simple motifs.
"""
motif, P = simple_motif
kwds = dict(undefined=undefined)
sim = P.simcoefs("global", **kwds)
comp = P.compcoefs("global", **kwds)
if motif == "triangle":
assert self.approx_in(sim, [1])
assert self.approx_in(comp, [0], allow_nan=True)
elif motif == "quadrangle":
assert self.approx_in(sim, [0])
assert self.approx_in(comp, [1])
@pytest.mark.parametrize("undefined", ["nan", "zero"])
def test_simple_motifs_nodes(self, simple_motif, undefined):
"""Check values of node-wise structural coefficients
in simple motifs.
"""
motif, P = simple_motif
kwds = dict(undefined=undefined)
sim = P.simcoefs("nodes", **kwds)
comp = P.compcoefs("nodes", **kwds)
if motif == "triangle":
assert self.approx_in(sim, [1])
assert self.approx_in(comp, [0], allow_nan=True)
elif motif == "quadrangle":
assert self.approx_in(sim, [0])
assert self.approx_in(comp, [1])
@pytest.mark.parametrize("undefined", ["nan", "zero"])
def test_simple_motifs_edges(self, simple_motif, undefined):
"""Check values of edge-wise structural coefficients
in simple motifs.
"""
motif, P = simple_motif
kwds = dict(undefined=undefined)
sim = P.similarity("edges", **kwds)
comp = P.complementarity("edges", **kwds)
if motif == "triangle":
assert self.approx_in(sim, [1])
assert self.approx_in(comp, [0], allow_nan=True)
elif motif == "quadrangle":
assert self.approx_in(sim, [0])
assert self.approx_in(comp, [1])
| [
"pathcensus.PathCensus",
"pytest.approx",
"numpy.allclose",
"numpy.isclose",
"pandas.DataFrame",
"pathcensus.definitions.PathDefinitionsWeighted",
"pytest.mark.parametrize",
"numpy.isnan",
"pytest.fixture",
"numpy.zeros_like"
] | [((316, 347), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (330, 347), False, 'import pytest\n'), ((575, 606), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (589, 606), False, 'import pytest\n'), ((746, 777), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (760, 777), False, 'import pytest\n'), ((922, 953), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (936, 953), False, 'import pytest\n'), ((1312, 1343), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (1326, 1343), False, 'import pytest\n'), ((1224, 1253), 'pathcensus.PathCensus', 'PathCensus', (['G'], {'weighted': '(False)'}), '(G, weighted=False)\n', (1234, 1253), False, 'from pathcensus import PathCensus\n'), ((1263, 1291), 'pathcensus.PathCensus', 'PathCensus', (['G'], {'weighted': '(True)'}), '(G, weighted=True)\n', (1273, 1291), False, 'from pathcensus import PathCensus\n'), ((1644, 1673), 'pathcensus.PathCensus', 'PathCensus', (['G'], {'weighted': '(False)'}), '(G, weighted=False)\n', (1654, 1673), False, 'from pathcensus import PathCensus\n'), ((1683, 1711), 'pathcensus.PathCensus', 'PathCensus', (['G'], {'weighted': '(True)'}), '(G, weighted=True)\n', (1693, 1711), False, 'from pathcensus import PathCensus\n'), ((2307, 2345), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""path"""', 'paths'], {}), "('path', paths)\n", (2330, 2345), False, 'import pytest\n'), ((2871, 2909), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""path"""', 'paths'], {}), "('path', paths)\n", (2894, 2909), False, 'import pytest\n'), ((3688, 3741), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""undefined"""', "['nan', 'zero']"], {}), "('undefined', ['nan', 'zero'])\n", (3711, 3741), False, 'import pytest\n'), ((4499, 4560), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""mode"""', "['edges', 'nodes', 'global']"], {}), "('mode', ['edges', 'nodes', 'global'])\n", (4522, 4560), False, 'import pytest\n'), ((4980, 5041), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""mode"""', "['edges', 'nodes', 'global']"], {}), "('mode', ['edges', 'nodes', 'global'])\n", (5003, 5041), False, 'import pytest\n'), ((5498, 5559), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""mode"""', "['edges', 'nodes', 'global']"], {}), "('mode', ['edges', 'nodes', 'global'])\n", (5521, 5559), False, 'import pytest\n'), ((6651, 6712), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""mode"""', "['edges', 'nodes', 'global']"], {}), "('mode', ['edges', 'nodes', 'global'])\n", (6674, 6712), False, 'import pytest\n'), ((7056, 7117), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""mode"""', "['edges', 'nodes', 'global']"], {}), "('mode', ['edges', 'nodes', 'global'])\n", (7079, 7117), False, 'import pytest\n'), ((8611, 8664), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""undefined"""', "['nan', 'zero']"], {}), "('undefined', ['nan', 'zero'])\n", (8634, 8664), False, 'import pytest\n'), ((9320, 9373), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""undefined"""', "['nan', 'zero']"], {}), "('undefined', ['nan', 'zero'])\n", (9343, 9373), False, 'import pytest\n'), ((10029, 10082), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""undefined"""', "['nan', 'zero']"], {}), "('undefined', ['nan', 'zero'])\n", (10052, 10082), False, 'import pytest\n'), ((2841, 2860), 'numpy.allclose', 'np.allclose', (['m0', 'm1'], {}), '(m0, m1)\n', (2852, 2860), True, 'import numpy as np\n'), ((6381, 6540), 'pandas.DataFrame', 'pd.DataFrame', (["{'t': (df['twc'] + df['thc']) / 2, 'tw': df['tw'], 'th': df['th'], 'q0': (\n df['q0wc'] + df['q0hc']) / 2, 'qw': df['qw'], 'qh': df['qh']}"], {}), "({'t': (df['twc'] + df['thc']) / 2, 'tw': df['tw'], 'th': df[\n 'th'], 'q0': (df['q0wc'] + df['q0hc']) / 2, 'qw': df['qw'], 'qh': df['qh']}\n )\n", (6393, 6540), True, 'import pandas as pd\n'), ((7012, 7045), 'numpy.allclose', 'np.allclose', (['p0.values', 'p1.values'], {}), '(p0.values, p1.values)\n', (7023, 7045), True, 'import numpy as np\n'), ((7434, 7467), 'numpy.allclose', 'np.allclose', (['c0.values', 'c1.values'], {}), '(c0.values, c1.values)\n', (7445, 7467), True, 'import numpy as np\n'), ((7973, 8001), 'numpy.zeros_like', 'np.zeros_like', (['x'], {'dtype': 'bool'}), '(x, dtype=bool)\n', (7986, 8001), True, 'import numpy as np\n'), ((2252, 2277), 'pathcensus.definitions.PathDefinitionsWeighted', 'PathDefinitionsWeighted', ([], {}), '()\n', (2275, 2277), False, 'from pathcensus.definitions import PathDefinitionsWeighted\n'), ((3332, 3342), 'pytest.approx', 'approx', (['m1'], {}), '(m1)\n', (3338, 3342), False, 'from pytest import approx\n'), ((8481, 8492), 'numpy.isnan', 'np.isnan', (['x'], {}), '(x)\n', (8489, 8492), True, 'import numpy as np\n'), ((8511, 8539), 'numpy.zeros_like', 'np.zeros_like', (['x'], {'dtype': 'bool'}), '(x, dtype=bool)\n', (8524, 8539), True, 'import numpy as np\n'), ((4050, 4060), 'pytest.approx', 'approx', (['c1'], {}), '(c1)\n', (4056, 4060), False, 'from pytest import approx\n'), ((8174, 8200), 'numpy.isclose', 'np.isclose', (['x', 'val'], {}), '(x, val, **kwds)\n', (8184, 8200), True, 'import numpy as np\n'), ((2729, 2754), 'pathcensus.definitions.PathDefinitionsWeighted', 'PathDefinitionsWeighted', ([], {}), '()\n', (2752, 2754), False, 'from pathcensus.definitions import PathDefinitionsWeighted\n'), ((3213, 3238), 'pathcensus.definitions.PathDefinitionsWeighted', 'PathDefinitionsWeighted', ([], {}), '()\n', (3236, 3238), False, 'from pathcensus.definitions import PathDefinitionsWeighted\n'), ((4016, 4034), 'numpy.isnan', 'np.isnan', (['[c0, c1]'], {}), '([c0, c1])\n', (4024, 4034), True, 'import numpy as np\n'), ((8086, 8097), 'numpy.isnan', 'np.isnan', (['x'], {}), '(x)\n', (8094, 8097), True, 'import numpy as np\n'), ((8100, 8126), 'numpy.isclose', 'np.isclose', (['x', 'val'], {}), '(x, val, **kwds)\n', (8110, 8126), True, 'import numpy as np\n')] |
""" Custom Fairness Metrics
Note that ratio and difference computation is handled by AIF360's
sklearn.metrics module. As of the V 0.4.0 release, these are calculated as
[unprivileged/privileged] and [unprivileged - privileged], respectively
"""
from typing import Callable
from aif360.sklearn.metrics import difference, ratio
import numpy as np
import pandas as pd
from warnings import catch_warnings, filterwarnings
from .performance_metrics import (
false_positive_rate,
true_positive_rate,
true_negative_rate,
false_negative_rate,
precision,
)
def __manage_undefined_ratios(func: Callable):
""" Wraps ratio functions to return NaN values instead of 0.0 in cases
where the ratio is undefined
"""
def wrapper(*args, **kwargs):
funcname = getattr(func, "__name__", "an unknown function")
msg = (
"The ratio is ill-defined and being set to 0.0 because"
+ f" '{funcname}' for privileged samples is 0."
)
with catch_warnings(record=True) as w:
filterwarnings("ignore", message=msg)
res = func(*args, **kwargs)
if len(w) > 0:
return np.nan
else:
return res
return wrapper
@__manage_undefined_ratios
def ppv_ratio(y_true: pd.Series, y_pred: pd.Series, pa_name: str, priv_grp: int = 1):
""" Returns the between-group ratio of Postive Predictive Values
Args:
y_true (pd.Series): true target values
y_pred (pd.Series): predicted target values
prtc_attr (str): name of the protected attribute
priv_grp (int, optional): . Defaults to 1.
Returns:
Number
"""
return ratio(precision, y_true, y_pred, prot_attr=pa_name, priv_group=priv_grp)
@__manage_undefined_ratios
def tpr_ratio(y_true: pd.Series, y_pred: pd.Series, pa_name: str, priv_grp: int = 1):
""" Returns the between-group ratio of True Positive Rates
Args:
y_true (pd.Series): true target values
y_pred (pd.Series): predicted target values
prtc_attr (str): name of the protected attribute
priv_grp (int, optional): . Defaults to 1.
Returns:
Number
"""
return ratio(
true_positive_rate, y_true, y_pred, prot_attr=pa_name, priv_group=priv_grp
)
@__manage_undefined_ratios
def fpr_ratio(y_true: pd.Series, y_pred: pd.Series, pa_name: str, priv_grp: int = 1):
""" Returns the between-group ratio of False Positive Rates
Args:
y_true (pd.Series): true target values
y_pred (pd.Series): predicted target values
prtc_attr (str): name of the protected attribute
priv_grp (int, optional): . Defaults to 1.
Returns:
Number
"""
return ratio(
false_positive_rate, y_true, y_pred, prot_attr=pa_name, priv_group=priv_grp
)
@__manage_undefined_ratios
def tnr_ratio(y_true: pd.Series, y_pred: pd.Series, pa_name: str, priv_grp: int = 1):
""" Returns the between-group ratio of True Negative Rates
Args:
y_true (pd.Series): true target values
y_pred (pd.Series): predicted target values
prtc_attr (str): name of the protected attribute
priv_grp (int, optional): . Defaults to 1.
Returns:
Number
"""
return ratio(
true_negative_rate, y_true, y_pred, prot_attr=pa_name, priv_group=priv_grp
)
@__manage_undefined_ratios
def fnr_ratio(y_true: pd.Series, y_pred: pd.Series, pa_name: str, priv_grp: int = 1):
""" Returns the between-group ratio of False Negative Rates
Args:
y_true (pd.Series): true target values
y_pred (pd.Series): predicted target values
prtc_attr (str): name of the protected attribute
priv_grp (int, optional): . Defaults to 1.
Returns:
Number
"""
return ratio(
false_negative_rate, y_true, y_pred, prot_attr=pa_name, priv_group=priv_grp
)
def ppv_diff(y_true: pd.Series, y_pred: pd.Series, pa_name: str, priv_grp: int = 1):
""" Returns the between-group difference of Positive Predictive Values
Args:
y_true (pd.Series): true target values
y_pred (pd.Series): predicted target values
prtc_attr (str): name of the protected attribute
priv_grp (int, optional): . Defaults to 1.
Returns:
Number
"""
return difference(precision, y_true, y_pred, prot_attr=pa_name, priv_group=priv_grp)
def tpr_diff(y_true: pd.Series, y_pred: pd.Series, pa_name: str, priv_grp: int = 1):
""" Returns the between-group difference of True Positive Rates
Args:
y_true (pd.Series): true target values
y_pred (pd.Series): predicted target values
prtc_attr (str): name of the protected attribute
priv_grp (int, optional): . Defaults to 1.
Returns:
Number
"""
return difference(
true_positive_rate, y_true, y_pred, prot_attr=pa_name, priv_group=priv_grp
)
def fpr_diff(y_true: pd.Series, y_pred: pd.Series, pa_name: str, priv_grp: int = 1):
""" Returns the between-group difference of False Positive Rates
Args:
y_true (pd.Series): true target values
y_pred (pd.Series): predicted target values
prtc_attr (str): name of the protected attribute
priv_grp (int, optional): . Defaults to 1.
Returns:
Number
"""
return difference(
false_positive_rate, y_true, y_pred, prot_attr=pa_name, priv_group=priv_grp
)
def tnr_diff(y_true: pd.Series, y_pred: pd.Series, pa_name: str, priv_grp: int = 1):
""" Returns the between-group difference of True Negative Rates
Args:
y_true (pd.Series): true target values
y_pred (pd.Series): predicted target values
prtc_attr (str): name of the protected attribute
priv_grp (int, optional): . Defaults to 1.
Returns:
Number
"""
return difference(
true_negative_rate, y_true, y_pred, prot_attr=pa_name, priv_group=priv_grp
)
def fnr_diff(y_true: pd.Series, y_pred: pd.Series, pa_name: str, priv_grp: int = 1):
""" Returns the between-group difference of False Negative Rates
Args:
y_true (pd.Series): true target values
y_pred (pd.Series): predicted target values
prtc_attr (str): name of the protected attribute
priv_grp (int, optional): . Defaults to 1.
Returns:
Number
"""
return difference(
false_negative_rate, y_true, y_pred, prot_attr=pa_name, priv_group=priv_grp
)
""" Combined Metrics """
def eq_odds_diff(y_true: pd.Series, y_pred: pd.Series, pa_name: str, priv_grp: int = 1):
""" Returns the greatest discrepancy between the between-group FPR
difference and the between-group TPR difference
Args:
y_true (pd.Series): true target values
y_pred (pd.Series): predicted target values
prtc_attr (str): name of the protected attribute
priv_grp (int, optional): . Defaults to 1.
Returns:
Number
"""
fprD = fpr_diff(y_true, y_pred, pa_name=pa_name, priv_grp=priv_grp)
tprD = tpr_diff(y_true, y_pred, pa_name=pa_name, priv_grp=priv_grp)
if abs(fprD) > abs(tprD):
return fprD
else:
return tprD
def eq_odds_ratio(
y_true: pd.Series, y_pred: pd.Series, pa_name: str, priv_grp: int = 1
):
""" Returns the greatest discrepancy between the between-group FPR
ratio and the between-group TPR ratio
Args:
y_true (pd.Series): true target values
y_pred (pd.Series): predicted target values
priv_grp (int, optional): . Defaults to 1.
"""
fprR = fpr_ratio(y_true, y_pred, pa_name=pa_name, priv_grp=priv_grp)
tprR = tpr_ratio(y_true, y_pred, pa_name=pa_name, priv_grp=priv_grp)
if np.isnan(fprR) or np.isnan(tprR):
return np.nan
elif round(abs(fprR - 1), 6) > round(abs(tprR - 1), 6):
return fprR
else:
return tprR
| [
"aif360.sklearn.metrics.ratio",
"aif360.sklearn.metrics.difference",
"warnings.catch_warnings",
"numpy.isnan",
"warnings.filterwarnings"
] | [((1702, 1774), 'aif360.sklearn.metrics.ratio', 'ratio', (['precision', 'y_true', 'y_pred'], {'prot_attr': 'pa_name', 'priv_group': 'priv_grp'}), '(precision, y_true, y_pred, prot_attr=pa_name, priv_group=priv_grp)\n', (1707, 1774), False, 'from aif360.sklearn.metrics import difference, ratio\n'), ((2221, 2307), 'aif360.sklearn.metrics.ratio', 'ratio', (['true_positive_rate', 'y_true', 'y_pred'], {'prot_attr': 'pa_name', 'priv_group': 'priv_grp'}), '(true_positive_rate, y_true, y_pred, prot_attr=pa_name, priv_group=\n priv_grp)\n', (2226, 2307), False, 'from aif360.sklearn.metrics import difference, ratio\n'), ((2764, 2851), 'aif360.sklearn.metrics.ratio', 'ratio', (['false_positive_rate', 'y_true', 'y_pred'], {'prot_attr': 'pa_name', 'priv_group': 'priv_grp'}), '(false_positive_rate, y_true, y_pred, prot_attr=pa_name, priv_group=\n priv_grp)\n', (2769, 2851), False, 'from aif360.sklearn.metrics import difference, ratio\n'), ((3307, 3393), 'aif360.sklearn.metrics.ratio', 'ratio', (['true_negative_rate', 'y_true', 'y_pred'], {'prot_attr': 'pa_name', 'priv_group': 'priv_grp'}), '(true_negative_rate, y_true, y_pred, prot_attr=pa_name, priv_group=\n priv_grp)\n', (3312, 3393), False, 'from aif360.sklearn.metrics import difference, ratio\n'), ((3850, 3937), 'aif360.sklearn.metrics.ratio', 'ratio', (['false_negative_rate', 'y_true', 'y_pred'], {'prot_attr': 'pa_name', 'priv_group': 'priv_grp'}), '(false_negative_rate, y_true, y_pred, prot_attr=pa_name, priv_group=\n priv_grp)\n', (3855, 3937), False, 'from aif360.sklearn.metrics import difference, ratio\n'), ((4377, 4454), 'aif360.sklearn.metrics.difference', 'difference', (['precision', 'y_true', 'y_pred'], {'prot_attr': 'pa_name', 'priv_group': 'priv_grp'}), '(precision, y_true, y_pred, prot_attr=pa_name, priv_group=priv_grp)\n', (4387, 4454), False, 'from aif360.sklearn.metrics import difference, ratio\n'), ((4878, 4968), 'aif360.sklearn.metrics.difference', 'difference', (['true_positive_rate', 'y_true', 'y_pred'], {'prot_attr': 'pa_name', 'priv_group': 'priv_grp'}), '(true_positive_rate, y_true, y_pred, prot_attr=pa_name,\n priv_group=priv_grp)\n', (4888, 4968), False, 'from aif360.sklearn.metrics import difference, ratio\n'), ((5403, 5494), 'aif360.sklearn.metrics.difference', 'difference', (['false_positive_rate', 'y_true', 'y_pred'], {'prot_attr': 'pa_name', 'priv_group': 'priv_grp'}), '(false_positive_rate, y_true, y_pred, prot_attr=pa_name,\n priv_group=priv_grp)\n', (5413, 5494), False, 'from aif360.sklearn.metrics import difference, ratio\n'), ((5928, 6018), 'aif360.sklearn.metrics.difference', 'difference', (['true_negative_rate', 'y_true', 'y_pred'], {'prot_attr': 'pa_name', 'priv_group': 'priv_grp'}), '(true_negative_rate, y_true, y_pred, prot_attr=pa_name,\n priv_group=priv_grp)\n', (5938, 6018), False, 'from aif360.sklearn.metrics import difference, ratio\n'), ((6453, 6544), 'aif360.sklearn.metrics.difference', 'difference', (['false_negative_rate', 'y_true', 'y_pred'], {'prot_attr': 'pa_name', 'priv_group': 'priv_grp'}), '(false_negative_rate, y_true, y_pred, prot_attr=pa_name,\n priv_group=priv_grp)\n', (6463, 6544), False, 'from aif360.sklearn.metrics import difference, ratio\n'), ((7819, 7833), 'numpy.isnan', 'np.isnan', (['fprR'], {}), '(fprR)\n', (7827, 7833), True, 'import numpy as np\n'), ((7837, 7851), 'numpy.isnan', 'np.isnan', (['tprR'], {}), '(tprR)\n', (7845, 7851), True, 'import numpy as np\n'), ((1020, 1047), 'warnings.catch_warnings', 'catch_warnings', ([], {'record': '(True)'}), '(record=True)\n', (1034, 1047), False, 'from warnings import catch_warnings, filterwarnings\n'), ((1066, 1103), 'warnings.filterwarnings', 'filterwarnings', (['"""ignore"""'], {'message': 'msg'}), "('ignore', message=msg)\n", (1080, 1103), False, 'from warnings import catch_warnings, filterwarnings\n')] |
"""The Kostal piko integration."""
import logging
import xmltodict
from datetime import timedelta
from homeassistant.const import (
CONF_USERNAME,
CONF_PASSWORD,
CONF_HOST,
CONF_MONITORED_CONDITIONS,
)
from homeassistant.components.sensor import SensorEntity
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from .const import SENSOR_TYPES, MIN_TIME_BETWEEN_UPDATES, DOMAIN
_LOGGER = logging.getLogger(__name__)
SCAN_INTERVAL = timedelta(seconds=10)
async def async_setup_entry(hass, entry, async_add_entities):
"""Add an Kostal piko entry."""
# Add the needed sensors to hass
data = PikoData(entry.data[CONF_HOST], entry.data[CONF_USERNAME], entry.data[CONF_PASSWORD], hass)
await data.async_update()
entities = []
for sensor in entry.data[CONF_MONITORED_CONDITIONS]:
entities.append(PikoInverter(data, sensor, entry.title))
async_add_entities(entities)
class PikoInverter(SensorEntity):
"""Representation of a Piko inverter."""
def __init__(self, piko_data, sensor_type, name):
"""Initialize the sensor."""
self.entity_description = SENSOR_TYPES[sensor_type]
self._attr_name = f"{self.name}"
self._attr_unique_id = f"{piko_data.host}_{self.entity_description.key}"
self._name = name
self.type = sensor_type
self.piko = piko_data
self._state = None
self.serial_number = None
self.model = None
@property
def state(self):
"""Return the state of the device."""
return self._state
@property
def device_info(self):
"""Return information about the device."""
return {
"identifiers": {(DOMAIN, self.serial_number)},
"name": self._name,
"manufacturer": "Kostal",
"model": self.model,
}
async def async_update(self):
"""Update data."""
await self.piko.async_update()
self.serial_number = self.piko.info['sn']
self.model = self.piko.info['model']
if self.type == "solar_generator_power":
if "AC_Power" in self.piko.measurements:
self._state = self.piko.measurements['AC_Power']
else:
return "No value available"
elif self.type == "ac_voltage":
if "AC_Voltage" in self.piko.measurements:
self._state = self.piko.measurements['AC_Voltage']
else:
return "No value available"
elif self.type == "ac_current":
if "AC_Current" in self.piko.measurements:
self._state = self.piko.measurements['AC_Current']
else:
return "No value available"
elif self.type == "total_solar_power":
if "Produced_Total" in self.piko.yields:
self._state = self.piko.yields['Produced_Total']
else:
return "No value available"
class PikoData(Entity):
"""Representation of a Piko inverter."""
def __init__(self, host, username, password, hass):
"""Initialize the data object."""
self.host = host
self.hass = hass
self.info = {}
self.measurements = None
self.yields = None
self.session = async_get_clientsession(hass)
async def retrieve(self):
async with self.session.get(self.host + '/all.xml') as resp:
text = await resp.text()
if resp.status != 200:
_LOGGER.error("Error while fetching the data from kostal: %d %s", resp.status, text)
else:
obj = xmltodict.parse(text)
self.info['model'] = obj["root"]["Device"]["@Name"]
self.info['sn'] = obj["root"]["Device"]["@Serial"]
self.measurements = {}
self.yields = {}
for i in obj["root"]["Device"]["Measurements"]["Measurement"]:
if '@Value' in i and '@Type' in i:
self.measurements[i["@Type"]] = float(i["@Value"])
# <Measurement Value="241.4" Unit="V" Type="AC_Voltage"/>
# <Measurement Value="0.876" Unit="A" Type="AC_Current"/>
# <Measurement Value="206.7" Unit="W" Type="AC_Power"/>
# <Measurement Value="205.8" Unit="W" Type="AC_Power_fast"/>
# <Measurement Value="49.976" Unit="Hz" Type="AC_Frequency"/>
# <Measurement Value="267.9" Unit="V" Type="DC_Voltage"/>
# <Measurement Value="0.854" Unit="A" Type="DC_Current"/>
# <Measurement Value="357.2" Unit="V" Type="LINK_Voltage"/>
# <Measurement Unit="W" Type="GridPower"/>
# <Measurement Unit="W" Type="GridConsumedPower"/>
# <Measurement Unit="W" Type="GridInjectedPower"/>
# <Measurement Unit="W" Type="OwnConsumedPower"/>
# <Measurement Value="100.0" Unit="%" Type="Derating"/>
for i in obj["root"]["Device"]["Yields"]:
o = obj["root"]["Device"]["Yields"][i]
if '@Type' in o and '@Slot' in o:
self.yields[o["@Type"] + "_" + o["@Slot"]] = float(o["YieldValue"]["@Value"])
@Throttle(MIN_TIME_BETWEEN_UPDATES)
async def async_update(self):
"""Update inverter data."""
# pylint: disable=protected-access
await self.retrieve()
_LOGGER.debug(self.measurements)
_LOGGER.debug(self.yields)
_LOGGER.debug(self.info)
if __name__ == "__main__":
import sys
data = PikoData(sys.argv[1], None, None, None)
print(data.measurements)
print(data.yields)
print(data.info) | [
"logging.getLogger",
"xmltodict.parse",
"homeassistant.util.Throttle",
"datetime.timedelta",
"homeassistant.helpers.aiohttp_client.async_get_clientsession"
] | [((539, 566), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (556, 566), False, 'import logging\n'), ((586, 607), 'datetime.timedelta', 'timedelta', ([], {'seconds': '(10)'}), '(seconds=10)\n', (595, 607), False, 'from datetime import timedelta\n'), ((5557, 5591), 'homeassistant.util.Throttle', 'Throttle', (['MIN_TIME_BETWEEN_UPDATES'], {}), '(MIN_TIME_BETWEEN_UPDATES)\n', (5565, 5591), False, 'from homeassistant.util import Throttle\n'), ((3481, 3510), 'homeassistant.helpers.aiohttp_client.async_get_clientsession', 'async_get_clientsession', (['hass'], {}), '(hass)\n', (3504, 3510), False, 'from homeassistant.helpers.aiohttp_client import async_get_clientsession\n'), ((3832, 3853), 'xmltodict.parse', 'xmltodict.parse', (['text'], {}), '(text)\n', (3847, 3853), False, 'import xmltodict\n')] |
import re
import os
import time
class LogReader(object):
def __init__(self):
self.log_file_sizes = {}
# (if the file changes more than this, ignore ) - 1 MB
self.max_file_size_change = 1000000
# (if the time between checks is greater, ignore ) - 5 minutes
self.max_file_time_change = 1000
def read_file(self, path):
# prevent traversing directories
if re.search('r^.+\.\.\\.+$', path):
return False
# must be a valid log path and log file
if not re.search(r'^.+[\\|\/](userraw|mods)[\\|\/].+.log$', path):
return False
# set the initialze size to the current file size
file_size = 0
if path not in self.log_file_sizes:
self.log_file_sizes[path] = {
'length' : self.file_length(path),
'read': time.time()
}
return ''
# grab the previous values
last_length = self.log_file_sizes[path]['length']
last_read = self.log_file_sizes[path]['read']
# the file is being tracked already
new_file_size = self.file_length(path)
# the log size was unable to be read (probably the wrong path)
if new_file_size < 0:
return False
now = time.time()
file_size_difference = new_file_size - last_length
time_difference = now - last_read
# update the new size and actually read the data
self.log_file_sizes[path] = {
'length': new_file_size,
'read': now
}
# if it's been too long since we read and the amount changed is too great, discard it
# todo: do we really want old events? maybe make this an "or"
if file_size_difference > self.max_file_size_change and time_difference > self.max_file_time_change:
return ''
new_log_info = self.get_file_lines(path, file_size_difference)
return new_log_info
def get_file_lines(self, path, length):
try:
file_handle = open(path, 'rb')
file_handle.seek(-length, 2)
file_data = file_handle.read(length)
file_handle.close()
return file_data.decode('utf-8')
except:
return False
def file_length(self, path):
try:
return os.stat(path).st_size
except:
return -1
reader = LogReader()
| [
"os.stat",
"time.time",
"re.search"
] | [((418, 452), 're.search', 're.search', (['"""r^.+\\\\.\\\\.\\\\.+$"""', 'path'], {}), "('r^.+\\\\.\\\\.\\\\.+$', path)\n", (427, 452), False, 'import re\n'), ((1308, 1319), 'time.time', 'time.time', ([], {}), '()\n', (1317, 1319), False, 'import time\n'), ((540, 603), 're.search', 're.search', (['"""^.+[\\\\\\\\|\\\\/](userraw|mods)[\\\\\\\\|\\\\/].+.log$"""', 'path'], {}), "('^.+[\\\\\\\\|\\\\/](userraw|mods)[\\\\\\\\|\\\\/].+.log$', path)\n", (549, 603), False, 'import re\n'), ((867, 878), 'time.time', 'time.time', ([], {}), '()\n', (876, 878), False, 'import time\n'), ((2384, 2397), 'os.stat', 'os.stat', (['path'], {}), '(path)\n', (2391, 2397), False, 'import os\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import __future__
import sys
import json
def banner():
ban = '====' * 30
print("{}\nSAMPLE INP:\n{}\n{}".format(ban,ban,open(ip, 'r').read()))
print("{}\nSAMPLE OUT:\n{}\n{}".format(ban,ban,open(op, 'r').read()))
print("{}\nSTART:\n{}".format(ban,ban))
sys.stdin = open(ip, 'r')
cnt = -1
def comp(inp,ln):
outl = output_arr[ln]
if str(inp) != outl:
raise Exception("Error input output: line {}, file: {}\ngot: {} expected: {}".format(ln,op,inp,outl))
ip = "./challenge_sample_input"
op = "./challenge_sample_output"
ip = "./input01.txt"
op = "./output01.txt"
output_arr = map(str,open(op,'r').read().split('\n'))
banner()
# https://www.hackerrank.com/challenges/defaultdict-tutorial/problem
import sys
from collections import defaultdict
n,m = map(int,raw_input().split(' '))
A = [raw_input() for _ in range(n)]
B = [raw_input() for _ in range(m)]
track = defaultdict(list)
for idx,v in enumerate(A):
track[v].append(idx + 1)
for i in B:
if i not in A:
print(-1)
else:
print(" ".join(map(str,track[i])))
| [
"collections.defaultdict"
] | [((945, 962), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (956, 962), False, 'from collections import defaultdict\n')] |
from django import http
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.decorators import login_required
from django.core import urlresolvers
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils.translation import ugettext_lazy as _
from satchmo.configuration import config_value, config_get_group, SettingNotSet
from satchmo.contact import signals, CUSTOMER_ID
from satchmo.contact.forms import ExtendedContactInfoForm
from satchmo.contact.models import Contact
from satchmo.shop.models import Config
import logging
log = logging.getLogger('satchmo.contact.views')
def view(request):
"""View contact info."""
try:
user_data = Contact.objects.get(user=request.user.id)
except Contact.DoesNotExist:
user_data = None
contact_dict = {
'user_data': user_data,
}
signals.satchmo_contact_view.send(user_data, contact=user_data, contact_dict=contact_dict)
context = RequestContext(request, contact_dict)
return render_to_response('contact/view_profile.html', context)
view = login_required(view)
def update(request):
"""Update contact info"""
init_data = {}
shop = Config.objects.get_current()
try:
contact = Contact.objects.from_request(request, create=False)
except Contact.DoesNotExist:
contact = None
if request.method == "POST":
new_data = request.POST.copy()
form = ExtendedContactInfoForm(new_data, shop=shop, contact=contact, shippable=True,
initial=init_data)
if form.is_valid():
if contact is None and request.user:
contact = Contact(user=request.user)
custID = form.save(contact=contact)
request.session[CUSTOMER_ID] = custID
redirect_to = request.REQUEST.get(REDIRECT_FIELD_NAME, '')
if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
redirect_to = urlresolvers.reverse('satchmo_account_info')
return http.HttpResponseRedirect(redirect_to)
else:
signals.satchmo_contact_view.send(contact, contact=contact, contact_dict=init_data)
else:
if contact:
#If a person has their contact info, make sure we populate it in the form
for item in contact.__dict__.keys():
init_data[item] = getattr(contact,item)
if contact.shipping_address:
for item in contact.shipping_address.__dict__.keys():
init_data["ship_"+item] = getattr(contact.shipping_address,item)
if contact.billing_address:
for item in contact.billing_address.__dict__.keys():
init_data[item] = getattr(contact.billing_address,item)
if contact.primary_phone:
init_data['phone'] = contact.primary_phone.phone
signals.satchmo_contact_view.send(contact, contact=contact, contact_dict=init_data)
form = ExtendedContactInfoForm(shop=shop, contact=contact, shippable=True, initial=init_data)
init_data['form'] = form
if shop.in_country_only:
init_data['country'] = shop.sales_country
else:
countries = shop.countries()
if countries and countries.count() == 1:
init_data['country'] = countries[0]
context = RequestContext(request, init_data)
return render_to_response('contact/update_form.html', context)
update = login_required(update)
| [
"logging.getLogger",
"django.http.HttpResponseRedirect",
"satchmo.contact.forms.ExtendedContactInfoForm",
"satchmo.contact.models.Contact.objects.from_request",
"django.template.RequestContext",
"django.core.urlresolvers.reverse",
"satchmo.contact.models.Contact.objects.get",
"satchmo.shop.models.Conf... | [((609, 651), 'logging.getLogger', 'logging.getLogger', (['"""satchmo.contact.views"""'], {}), "('satchmo.contact.views')\n", (626, 651), False, 'import logging\n'), ((1133, 1153), 'django.contrib.auth.decorators.login_required', 'login_required', (['view'], {}), '(view)\n', (1147, 1153), False, 'from django.contrib.auth.decorators import login_required\n'), ((3547, 3569), 'django.contrib.auth.decorators.login_required', 'login_required', (['update'], {}), '(update)\n', (3561, 3569), False, 'from django.contrib.auth.decorators import login_required\n'), ((896, 990), 'satchmo.contact.signals.satchmo_contact_view.send', 'signals.satchmo_contact_view.send', (['user_data'], {'contact': 'user_data', 'contact_dict': 'contact_dict'}), '(user_data, contact=user_data,\n contact_dict=contact_dict)\n', (929, 990), False, 'from satchmo.contact import signals, CUSTOMER_ID\n'), ((1014, 1051), 'django.template.RequestContext', 'RequestContext', (['request', 'contact_dict'], {}), '(request, contact_dict)\n', (1028, 1051), False, 'from django.template import RequestContext\n'), ((1068, 1124), 'django.shortcuts.render_to_response', 'render_to_response', (['"""contact/view_profile.html"""', 'context'], {}), "('contact/view_profile.html', context)\n", (1086, 1124), False, 'from django.shortcuts import render_to_response\n'), ((1237, 1265), 'satchmo.shop.models.Config.objects.get_current', 'Config.objects.get_current', ([], {}), '()\n', (1263, 1265), False, 'from satchmo.shop.models import Config\n'), ((3426, 3460), 'django.template.RequestContext', 'RequestContext', (['request', 'init_data'], {}), '(request, init_data)\n', (3440, 3460), False, 'from django.template import RequestContext\n'), ((3481, 3536), 'django.shortcuts.render_to_response', 'render_to_response', (['"""contact/update_form.html"""', 'context'], {}), "('contact/update_form.html', context)\n", (3499, 3536), False, 'from django.shortcuts import render_to_response\n'), ((730, 771), 'satchmo.contact.models.Contact.objects.get', 'Contact.objects.get', ([], {'user': 'request.user.id'}), '(user=request.user.id)\n', (749, 771), False, 'from satchmo.contact.models import Contact\n'), ((1294, 1345), 'satchmo.contact.models.Contact.objects.from_request', 'Contact.objects.from_request', (['request'], {'create': '(False)'}), '(request, create=False)\n', (1322, 1345), False, 'from satchmo.contact.models import Contact\n'), ((1495, 1596), 'satchmo.contact.forms.ExtendedContactInfoForm', 'ExtendedContactInfoForm', (['new_data'], {'shop': 'shop', 'contact': 'contact', 'shippable': '(True)', 'initial': 'init_data'}), '(new_data, shop=shop, contact=contact, shippable=\n True, initial=init_data)\n', (1518, 1596), False, 'from satchmo.contact.forms import ExtendedContactInfoForm\n'), ((2968, 3056), 'satchmo.contact.signals.satchmo_contact_view.send', 'signals.satchmo_contact_view.send', (['contact'], {'contact': 'contact', 'contact_dict': 'init_data'}), '(contact, contact=contact, contact_dict=\n init_data)\n', (3001, 3056), False, 'from satchmo.contact import signals, CUSTOMER_ID\n'), ((3067, 3158), 'satchmo.contact.forms.ExtendedContactInfoForm', 'ExtendedContactInfoForm', ([], {'shop': 'shop', 'contact': 'contact', 'shippable': '(True)', 'initial': 'init_data'}), '(shop=shop, contact=contact, shippable=True, initial\n =init_data)\n', (3090, 3158), False, 'from satchmo.contact.forms import ExtendedContactInfoForm\n'), ((2092, 2130), 'django.http.HttpResponseRedirect', 'http.HttpResponseRedirect', (['redirect_to'], {}), '(redirect_to)\n', (2117, 2130), False, 'from django import http\n'), ((2157, 2245), 'satchmo.contact.signals.satchmo_contact_view.send', 'signals.satchmo_contact_view.send', (['contact'], {'contact': 'contact', 'contact_dict': 'init_data'}), '(contact, contact=contact, contact_dict=\n init_data)\n', (2190, 2245), False, 'from satchmo.contact import signals, CUSTOMER_ID\n'), ((1708, 1734), 'satchmo.contact.models.Contact', 'Contact', ([], {'user': 'request.user'}), '(user=request.user)\n', (1715, 1734), False, 'from satchmo.contact.models import Contact\n'), ((2011, 2055), 'django.core.urlresolvers.reverse', 'urlresolvers.reverse', (['"""satchmo_account_info"""'], {}), "('satchmo_account_info')\n", (2031, 2055), False, 'from django.core import urlresolvers\n')] |
#***************************************************#
# This file is part of PFNET. #
# #
# Copyright (c) 2015, <NAME>. #
# #
# PFNET is released under the BSD 2-clause license. #
#***************************************************#
# Optimization Problems - Constraints
import sys
sys.path.append('.')
import pfnet
net = pfnet.Parser(sys.argv[1]).parse(sys.argv[1])
net.set_flags('bus',
'variable',
'any',
['voltage magnitude','voltage angle'])
print(net.num_vars == 2*net.num_buses)
constr = pfnet.Constraint('AC power balance',net)
print(constr.name == 'AC power balance')
x = net.get_var_values()
constr.analyze()
print(constr.num_extra_vars)
constr.eval(x + 0.01)
constr.eval(x)
import numpy as np
f = constr.f
print(type(f), f.shape)
print(np.linalg.norm(f,np.inf))
bus = net.get_bus(5)
Hi = constr.get_H_single(bus.dP_index)
print(type(Hi), Hi.shape, Hi.nnz)
coefficients = np.random.randn(f.size)
constr.combine_H(coefficients)
H = constr.H_combined
print(type(H), H.shape, H.nnz)
| [
"pfnet.Parser",
"pfnet.Constraint",
"numpy.linalg.norm",
"sys.path.append",
"numpy.random.randn"
] | [((413, 433), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (428, 433), False, 'import sys\n'), ((671, 712), 'pfnet.Constraint', 'pfnet.Constraint', (['"""AC power balance"""', 'net'], {}), "('AC power balance', net)\n", (687, 712), False, 'import pfnet\n'), ((1071, 1094), 'numpy.random.randn', 'np.random.randn', (['f.size'], {}), '(f.size)\n', (1086, 1094), True, 'import numpy as np\n'), ((932, 957), 'numpy.linalg.norm', 'np.linalg.norm', (['f', 'np.inf'], {}), '(f, np.inf)\n', (946, 957), True, 'import numpy as np\n'), ((454, 479), 'pfnet.Parser', 'pfnet.Parser', (['sys.argv[1]'], {}), '(sys.argv[1])\n', (466, 479), False, 'import pfnet\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from logging import StreamHandler, INFO
from flask import Flask
from flask.ext.mail import Message, Mail
from api import create_api
from database import init_db
API_VERSION = "v1"
def check_environment(app):
file_backend = os.environ.get('FILE_BACKEND', 'file').lower()
if 'FILE_BACKEND' not in os.environ:
app.logger.info('FILE_BACKEND is not set, will default to "%s"',
file_backend)
if file_backend == 's3':
if 'S3_BUCKET' not in os.environ:
app.logger.warn('S3_BUCKET is not set, will default to "flod"')
if 'AWS_ACCESS_KEY_ID' not in os.environ:
raise EnvironmentError(('AWS_ACCESS_KEY_ID must be set for S3 '
'backend'))
if 'AWS_SECRET_ACCESS_KEY' not in os.environ:
raise EnvironmentError(('AWS_SECRET_ACCESS_KEY must be set for'
' S3 backend'))
if file_backend == 'file' and 'UPLOAD_PATH' not in os.environ:
app.logger.info('UPLOAD_PATH is not set, will default to /tmp')
if 'AUTH_TOKEN_SECRET' not in os.environ:
raise EnvironmentError('AUTH_TOKEN_SECRET must be set')
def create_app(db_url):
app = Flask(__name__)
(app.db_session, app.db_metadata, app.db_engine) = init_db(db_url)
@app.teardown_request
def shutdown_session(exception=None):
app.db_session.remove()
create_api(app, API_VERSION)
if not app.debug:
stream_handler = StreamHandler()
app.logger.addHandler(stream_handler)
app.logger.setLevel(INFO)
check_environment(app)
return app
if __name__ == "__main__":
port = int(os.environ.get('PORT', 5000))
app = create_app(os.environ.get('DATABASE_URL'))
app.run(host='0.0.0.0', port=port, debug=True)
| [
"api.create_api",
"logging.StreamHandler",
"flask.Flask",
"database.init_db",
"os.environ.get"
] | [((1277, 1292), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (1282, 1292), False, 'from flask import Flask\n'), ((1348, 1363), 'database.init_db', 'init_db', (['db_url'], {}), '(db_url)\n', (1355, 1363), False, 'from database import init_db\n'), ((1470, 1498), 'api.create_api', 'create_api', (['app', 'API_VERSION'], {}), '(app, API_VERSION)\n', (1480, 1498), False, 'from api import create_api\n'), ((1546, 1561), 'logging.StreamHandler', 'StreamHandler', ([], {}), '()\n', (1559, 1561), False, 'from logging import StreamHandler, INFO\n'), ((1730, 1758), 'os.environ.get', 'os.environ.get', (['"""PORT"""', '(5000)'], {}), "('PORT', 5000)\n", (1744, 1758), False, 'import os\n'), ((1781, 1811), 'os.environ.get', 'os.environ.get', (['"""DATABASE_URL"""'], {}), "('DATABASE_URL')\n", (1795, 1811), False, 'import os\n'), ((288, 326), 'os.environ.get', 'os.environ.get', (['"""FILE_BACKEND"""', '"""file"""'], {}), "('FILE_BACKEND', 'file')\n", (302, 326), False, 'import os\n')] |
# -*- coding: utf-8 -*-
import unittest
from app import app
class TestPingView(unittest.TestCase):
def setUp(self):
app.config['TESTING'] = True
self.client = app.test_client()
def test_ping(self):
response = self.client.get('/ping')
assert response.data.decode('utf-8') == 'pong'
| [
"app.app.test_client"
] | [((182, 199), 'app.app.test_client', 'app.test_client', ([], {}), '()\n', (197, 199), False, 'from app import app\n')] |
import pytest
from dataclasses import dataclass, field
from functools import reduce
from typing import List, Optional
from helpers.basetest import BaseTestBtc, LedgerjsApdu, TxData, CONSENSUS_BRANCH_ID
from helpers.deviceappbtc import DeviceAppBtc, CommException
# Test data below is from a Zcash test log from Live team"
test_zcash_prefix_cmds = [
LedgerjsApdu( # Get version
commands=["b001000000"],
# expected_resp="01055a63617368--------------0102" # i.e. "Zcash" + "1.3.23" (not checked)
),
LedgerjsApdu(
commands=[
"e040000015058000002c80000085800000000000000000000000", # GET PUBLIC KEY - on 44'/133'/0'/0/0 path
"e016000000", # Coin info
],
expected_resp="1cb81cbd01055a63617368035a4543" # "Zcash" + "ZEC"
),
LedgerjsApdu(
commands=[
"e040000009028000002c80000085", # Get Public Key - on path 44'/133'
"e016000000", # Coin info
],
expected_resp="1cb81cbd01055a63617368035a4543"
),
LedgerjsApdu(
commands=[
"e040000009028000002c80000085", # path 44'/133'
"e04000000d038000002c8000008580000000", # path 44'/133'/0'
"e04000000d038000002c8000008580000001", # path 44'/133'/1'
"b001000000"
],
# expected_resp="01055a63617368--------------0102"
),
LedgerjsApdu(
commands=[
"e040000015058000002c80000085800000000000000000000004", # Get Public Key - on path 44'/133'/0'/0/4
"e016000000", # Coin info
],
expected_resp="1cb81cbd01055a63617368035a4543"
),
LedgerjsApdu(
commands=["b001000000"],
# expected_resp="01055a63617368--------------0102"
),
LedgerjsApdu(
commands=[
"e040000015058000002c80000085800000000000000000000004", # Get Public Key - on path 44'/133'/0'/0/4
"e016000000"
],
expected_resp="1cb81cbd01055a63617368035a4543"
),
LedgerjsApdu(
commands=["b001000000"],
# expected_resp="01055a63617368--------------0102"
)
]
test_zcash_tx_sign_gti = [
LedgerjsApdu( # GET TRUSTED INPUT
commands=[
"e042000009000000010400008001",
"e042800025edc69b8179fd7c6a11a8a1ba5d17017df5e09296c3a1acdada0d94e199f68857010000006b",
"e042800032483045022100e8043cd498714122a78b6ecbf8ced1f74d1c65093c5e2649336dfa248aea9ccf022023b13e57595635452130",
"e0428000321c91ed0fe7072d295aa232215e74e50d01a73b005dac01210201e1c9d8186c093d116ec619b7dad2b7ff0e7dd16f42d458da",
"e04280000b1100831dc4ff72ffffff00",
"e04280000102",
"e042800022a0860100000000001976a914fa9737ab9964860ca0c3e9ad6c7eb3bc9c8f6fb588ac",
"e0428000224d949100000000001976a914b714c60805804d86eb72a38c65ba8370582d09e888ac",
"e04280000400000000",
],
expected_resp="3200" + "--"*2 + "20b7c68231303b2425a91b12f05bd6935072e9901137ae30222ef6d60849fc51010000004d94910000000000" + "--"*8
),
]
test_zcash_tx_to_sign_abandonned = [
LedgerjsApdu( # GET PUBLIC KEY
commands=["e040000015058000002c80000085800000000000000100000001"], # on 44'/133'/0'/1/1
),
LedgerjsApdu( # UNTRUSTED HASH TRANSACTION INPUT START
commands=[
"e0440005090400008085202f8901",
"e04480053b013832004d0420b7c68231303b2425a91b12f05bd6935072e9901137ae30222ef6d60849fc51010000004d9491000000000045e1e144cb88d4d800",
"e044800504ffffff00",
]
),
LedgerjsApdu( # UNTRUSTED HASH TRANSACTION INPUT FINALIZE FULL
commands=[
"e04aff0015058000002c80000085800000000000000100000003",
# "e04a0000320240420f00000000001976a91490360f7a0b0e50d5dd0c924fc1d6e7adb8519c9388ac39498200000000001976a91425ea06"
"e04a0000230140420f00000000001976a91490360f7a0b0e50d5dd0c924fc1d6e7adb8519c9388ac"
], # tx aborted on 2nd command
expected_sw="6985"
),
]
test_zcash_tx_sign_restart_prefix_cmds = [
LedgerjsApdu(
commands=["b001000000"],
# expected_resp="01055a63617368--------------0102"
),
LedgerjsApdu(
commands=[
"e040000015058000002c80000085800000000000000000000004",
"e016000000",
],
expected_resp="1cb81cbd01055a63617368035a4543"
),
LedgerjsApdu(
commands=["b001000000"],
# expected_resp="01055a63617368--------------0102"
)
]
test_zcash_tx_to_sign_finalized = test_zcash_tx_sign_gti + [
LedgerjsApdu( # GET PUBLIC KEY
commands=["e040000015058000002c80000085800000000000000100000001"], # on 44'/133'/0'/1/1
),
LedgerjsApdu( # UNTRUSTED HASH TRANSACTION INPUT START
commands=[
"e0440005090400008085202f8901",
"e04480053b""013832004d""0420b7c68231303b2425a91b12f05bd6935072e9901137ae30222ef6d60849fc51""01000000""4d94910000000000""45e1e144cb88d4d8""00",
"e044800504ffffff00",
]
),
LedgerjsApdu( # UNTRUSTED HASH TRANSACTION INPUT FINALIZE FULL
commands=[
"e04aff0015058000002c80000085800000000000000100000003",
# "e04a0000320240420f00000000001976a91490360f7a0b0e50d5dd0c924fc1d6e7adb8519c9388ac39498200000000001976a91425ea06"
"e04a0000230140420f00000000001976a91490360f7a0b0e50d5dd0c924fc1d6e7adb8519c9388ac"
"e04a8000045eb3f840"
],
expected_resp="0000"
),
LedgerjsApdu(
commands=[
"e044008509""0400008085202f8901",
"e04480853b""013832004d04""20b7c68231303b2425a91b12f05bd6935072e9901137ae30222ef6d60849fc51""01000000""4d94910000000000""45e1e144cb88d4d8""19",
"e04480851d""76a9140a146582553b2f5537e13cef6659e82ed8f69b8f88ac""ffffff00",
"e048000015""058000002c80000085800000000000000100000001"
],
check_sig_format=True
)
]
ledgerjs_test_data = [
test_zcash_prefix_cmds, test_zcash_tx_sign_gti, test_zcash_tx_to_sign_abandonned,
test_zcash_tx_sign_restart_prefix_cmds, test_zcash_tx_to_sign_finalized
]
utxo_single = bytes.fromhex(
# https://sochain.com/api/v2/tx/ZEC/ec9033381c1cc53ada837ef9981c03ead1c7c41700ff3a954389cfaddc949256
# Version @offset 0
"04000080"
# versionGroupId @offset 4
"85202f89"
# Input count @offset 8
"01"
# Input prevout hash @offset 9
"53685b8809efc50dd7d5cb0906b307a1b8aa5157baa5fc1bd6fe2d0344dd193a"
# Input prevout idx @offset 41
"00000000"
# Input script length @offset 45
"6b"
# Input script (107 bytes) @ offset 46
"483045022100ca0be9f37a4975432a52bb65b25e483f6f93d577955290bb7fb0"
"060a93bfc92002203e0627dff004d3c72a957dc9f8e4e0e696e69d125e4d8e27"
"5d119001924d3b48012103b243171fae5516d1dc15f9178cfcc5fdc67b0a8830"
"55c117b01ba8af29b953f6"
# Input sequence @offset 151
"ffffffff"
# Output count @offset 155
"01"
# Output #1 value @offset 156
"4072070000000000"
# Output #1 script length @offset 164
"19"
# Output #1 script (25 bytes) @offset 165
"76a91449964a736f3713d64283fd0018626ba50091c7e988ac"
# Locktime @offset 190
"00000000"
# Extra payload (size of everything remaining, specific to btc app inner protocol @offset 194
"0F"
# Expiry @offset 195
"00000000"
# valueBalance @offset 199
"0000000000000000"
# vShieldedSpend @offset 207
"00"
# vShieldedOutput @offset 208
"00"
# vJoinSplit @offset 209
"00"
)
utxos = [
# Considered a segwit tx - segwit flags couldn't be extracted from raw
# Get Trusted Input APDUs as they are not supposed to be sent w/ these APDUs.
bytes.fromhex(
# Version @offset 0
"04000080"
# versionGroupId @offset 4
"85202f89"
# Input count @offset 8
"01"
# Input prevout hash @offset 9
"edc69b8179fd7c6a11a8a1ba5d17017df5e09296c3a1acdada0d94e199f68857"
# Input prevout idx @offset 41
"01000000"
# Input script length @offset 45
"6b"
# Input script (107 bytes) @ offset 46
"483045022100e8043cd498714122a78b6ecbf8ced1f74d1c65093c5e2649336d"
"fa248aea9ccf022023b13e575956354521301c91ed0fe7072d295aa232215e74"
"e50d01a73b005dac01210201e1c9d8186c093d116ec619b7dad2b7ff0e7dd16f"
"42d458da1100831dc4ff72"
# Input sequence @offset 153
"ffffff00"
# Output count @offset 157
"02"
# Output #1 value @offset 160
"a086010000000000"
# Output #1 script length @offset 168
"19"
# Output #1 script (25 bytes) @offset 167
"76a914fa9737ab9964860ca0c3e9ad6c7eb3bc9c8f6fb588ac"
# Output #2 value @offset 192
"4d94910000000000" # 9 540 685 units of ZEC smallest currency available
# Output #2 script length @offset 200
"19"
# Output #2 script (25 bytes) @offset 201
"76a914b714c60805804d86eb72a38c65ba8370582d09e888ac"
# Locktime @offset 226
"00000000"
# Extra payload (size of everything remaining, specific to btc app inner protocol @offset 230
"0F"
# Expiry @offset 231
"00000000"
# valueBalance @offset 235
"0000000000000000"
# vShieldedSpend @offset 243
"00"
# vShieldedOutput @offset 244
"00"
# vJoinSplit @offset 245
"00"
)
]
tx_to_sign = bytes.fromhex(
# version @offset 0
"04000080"
# Some Zcash flags (?) @offset 4
"85202f89"
# Input count @offset 8
"01"
# Input's prevout hash @offset 9
"d35f0793da27a5eacfe984c73b1907af4b50f3aa3794ba1bb555b9233addf33f"
# Prevout idx @offset 41
"01000000"
# input sequence @offset 45
"ffffff00"
# Output count @offset 49
"02"
# Output #1 value @offset 50
"40420f0000000000" # 1 000 000 units of available balance spent
# Output #1 script (26 bytes) @offset 58
"1976a91490360f7a0b0e50d5dd0c924fc1d6e7adb8519c9388ac"
# Output #2 value @offset 84
"2b51820000000000"
# Output #2 scritp (26 bytes) @offset 92
"1976a91490360f7a0b0e50d5dd0c924fc1d6e7adb8519c9388ac"
# Locktime @offset 118
"5eb3f840"
)
change_path = bytes.fromhex("058000002c80000085800000000000000100000003") # 44'/133'/0'/1/3
output_paths = [
bytes.fromhex("058000002c80000085800000000000000100000001"), # 44'/133'/0'/1/1
bytes.fromhex("058000002c80000085800000000000000000000004") # 44'/133'/0'/0/4
]
@pytest.mark.zcash
class TestLedgerjsZcashTx(BaseTestBtc):
def _send_raw_apdus(self, apdus: List[LedgerjsApdu], device: DeviceAppBtc):
# Send the Get Version APDUs
for apdu in apdus:
try:
for command in apdu.commands:
response = device.sendRawApdu(bytes.fromhex(command))
if apdu.expected_resp is not None:
self.check_raw_apdu_resp(apdu.expected_resp, response)
elif apdu.check_sig_format is not None and apdu.check_sig_format == True:
self.check_signature(response) # Only format is checked
except CommException as error:
if apdu.expected_sw is not None and error.sw.hex() == apdu.expected_sw:
continue
raise error
@pytest.mark.skip(reason="Hardcoded TrustedInput can't be replayed on a different device than the one that generated it")
@pytest.mark.manual
@pytest.mark.parametrize('test_data', ledgerjs_test_data)
def test_replay_zcash_test(self, test_data: List[LedgerjsApdu]) -> None:
"""
Replay of raw apdus from @gre.
First time an output is presented for validation, it must be rejected by user
Then tx will be restarted and on 2nd presentation of outputs they have to be
accepted.
"""
apdus = test_data
btc = DeviceAppBtc()
self._send_raw_apdus(apdus, btc)
@pytest.mark.manual
def test_get_single_trusted_input(self) -> None:
btc = DeviceAppBtc()
# 1. Get Trusted Input
print("\n--* Get Trusted Input - from utxos")
input_datum = bytes.fromhex("00000000") + utxo_single
utxo_chunk_len = [
4 + 5 + 4, # len(prevout_index (BE)||version||input_count||versionGroupId)
37, # len(prevout_hash||prevout_index||len(scriptSig))
-1, # len(scriptSig, from last byte of previous chunk) + len(input_sequence)
1, # len(output_count)
34, # len(output_value #1||len(scriptPubkey #1)||scriptPubkey #1)
4 + 1, # len(locktime || extra_data)
4+16+1+1+1 # len(Expiry||valueBalance||vShieldedSpend||vShieldedOutput||vJoinSplit)
]
trusted_input = btc.getTrustedInput(data=input_datum, chunks_len=utxo_chunk_len)
self.check_trusted_input(
trusted_input,
out_index=bytes.fromhex("00000000"),
out_amount=bytes.fromhex("4072070000000000"),
out_hash=bytes.fromhex("569294dcadcf8943953aff0017c4c7d1ea031c98f97e83da3ac51c1c383390ec")
)
print(" OK")
@pytest.mark.manual
def test_replay_zcash_test2(self) -> None:
"""
Adapted version to work around some hw limitations
"""
# Send the Get Version raw apdus
apdus = test_zcash_prefix_cmds
btc = DeviceAppBtc()
self._send_raw_apdus(apdus, btc)
# 1. Get Trusted Input
print("\n--* Get Trusted Input - from utxos")
output_indexes = [
tx_to_sign[41+4-1:41-1:-1], # out_index in tx_to_sign input must be passed BE as prefix to utxo tx
]
input_data = [out_idx + utxo for out_idx, utxo in zip(output_indexes, utxos)]
utxos_chunks_len = [
[ # utxo #1
4+5+4, # len(prevout_index (BE)||version||input_count||versionGroupId)
37, # len(prevout_hash||prevout_index||len(scriptSig))
-1, # len(scriptSig, from last byte of previous chunk) + len(input_sequence)
1, # len(output_count)
34, # len(output_value #1||len(scriptPubkey #1)||scriptPubkey #1)
34, # len(output_value #2||len(scriptPubkey #2)||scriptPubkey #2)
4 + 1, # len(locktime)
4 + 16 + 1 + 1 + 1 # len(Expiry||valueBalance||vShieldedSpend||vShieldedOutput||vJoinSplit)
]
]
trusted_inputs = [
btc.getTrustedInput(
data=input_datum,
chunks_len=chunks_len
)
for (input_datum, chunks_len) in zip(input_data, utxos_chunks_len)
]
print(" OK")
out_amounts = [utxos[0][192:192+8]] # UTXO tx's 2nd output's value
prevout_hashes = [tx_to_sign[9:9+32]]
for trusted_input, out_idx, out_amount, prevout_hash in zip(
trusted_inputs, output_indexes, out_amounts, prevout_hashes
):
self.check_trusted_input(
trusted_input,
out_index=out_idx[::-1], # LE for comparison w/ out_idx in trusted_input
out_amount=out_amount, # utxo output #1 is requested in tx to sign input
out_hash=prevout_hash # prevout hash in tx to sign
)
# 2.0 Get public keys for output paths & compute their hashes
print("\n--* Get Wallet Public Key - for each tx output path")
wpk_responses = [btc.getWalletPublicKey(output_path) for output_path in output_paths]
print(" OK")
pubkeys_data = [self.split_pubkey_data(data) for data in wpk_responses]
for pubkey in pubkeys_data:
print(pubkey)
# 2.1 Construct a pseudo-tx without input script, to be hashed 1st.
print("\n--* Untrusted Transaction Input Hash Start - Hash tx to sign first w/ all inputs having a null script length")
input_sequences = [tx_to_sign[45:45+4]]
ptx_to_hash_part1 = [tx_to_sign[:9]]
for trusted_input, input_sequence in zip(trusted_inputs, input_sequences):
ptx_to_hash_part1.extend([
bytes.fromhex("01"), # TrustedInput marker byte, triggers the TrustedInput's HMAC verification
bytes([len(trusted_input)]),
trusted_input,
bytes.fromhex("00"), # Input script length = 0 (no sigScript)
input_sequence
])
ptx_to_hash_part1 = reduce(lambda x, y: x+y, ptx_to_hash_part1) # Get a single bytes object
ptx_to_hash_part1_chunks_len = [
9 # len(version||flags||input_count) - skip segwit version+flag bytes
]
for trusted_input in trusted_inputs:
ptx_to_hash_part1_chunks_len.extend([
1 + 1 + len(trusted_input) + 1, # len(trusted_input_marker||len(trusted_input)||trusted_input||len(scriptSig) == 0)
4 # len(input_sequence)
])
btc.untrustedTxInputHashStart(
p1="00",
p2="05", # Value used for Zcash
data=ptx_to_hash_part1,
chunks_len=ptx_to_hash_part1_chunks_len
)
print(" OK")
# 2.2 Finalize the input-centric-, pseudo-tx hash with the remainder of that tx
# 2.2.1 Start with change address path
print("\n--* Untrusted Transaction Input Hash Finalize Full - Handle change address")
ptx_to_hash_part2 = change_path
ptx_to_hash_part2_chunks_len = [len(ptx_to_hash_part2)]
btc.untrustedTxInputHashFinalize(
p1="ff", # to derive BIP 32 change address
data=ptx_to_hash_part2,
chunks_len=ptx_to_hash_part2_chunks_len
)
print(" OK")
# 2.2.2 Continue w/ tx to sign outputs & scripts
print("\n--* Untrusted Transaction Input Hash Finalize Full - Continue w/ hash of tx output")
ptx_to_hash_part3 = tx_to_sign[49:118] # output_count||repeated(output_amount||scriptPubkey)
ptx_to_hash_part3_chunks_len = [len(ptx_to_hash_part3)]
response = btc.untrustedTxInputHashFinalize(
p1="00",
data=ptx_to_hash_part3,
chunks_len=ptx_to_hash_part3_chunks_len
)
assert response == bytes.fromhex("0000")
print(" OK")
# We're done w/ the hashing of the pseudo-tx with all inputs w/o scriptSig.
# 2.2.3. Zcash-specific: "When using Overwinter/Sapling, UNTRUSTED HASH SIGN is
# called with an empty authorization and nExpiryHeight following the first
# UNTRUSTED HASH TRANSACTION INPUT FINALIZE FULL"
print("\n--* Untrusted Has Sign - with empty Auth & nExpiryHeight")
branch_id_data = [
bytes.fromhex(
"00" # Number of derivations (None)
"00" # Empty validation code
),
tx_to_sign[-4:], # locktime
bytes.fromhex("01"), # SigHashType - always 01
bytes.fromhex("00000000") # Empty nExpiryHeight
]
response = btc.untrustedHashSign(
data = reduce(lambda x, y: x+y, branch_id_data)
)
# 3. Sign each input individually. Because inputs are segwit, hash each input with its scriptSig
# and sequence individually, each in a pseudo-tx w/o output_count, outputs nor locktime.
print("\n--* Untrusted Transaction Input Hash Start, step 2 - Hash again each input individually (only 1)")
# Inputs are P2WPKH, so use 0x1976a914{20-byte-pubkey-hash}88ac from utxo as scriptSig in this step.
#
# From btc.asc: "The input scripts shall be prepared by the host for the transaction signing process as
# per bitcoin rules : the current input script being signed shall be the previous output script (or the
# redeeming script when consuming a P2SH output, or the scriptCode when consuming a BIP 143 output), and
# other input script shall be null."
input_scripts = [utxos[0][196:196 + utxos[0][196] + 1]]
# input_scripts = [tx_to_sign[45:45 + tx_to_sign[45] + 1]]
# input_scripts = [bytes.fromhex("1976a914") + pubkey.pubkey_hash + bytes.fromhex("88ac")
# for pubkey in pubkeys_data]
ptx_for_inputs = [
[ tx_to_sign[:8], # Tx version||zcash flags
bytes.fromhex("0101"), # Input_count||TrustedInput marker byte
bytes([len(trusted_input)]),
trusted_input,
input_script,
input_sequence
] for trusted_input, input_script, input_sequence in zip(trusted_inputs, input_scripts, input_sequences)
]
ptx_chunks_lengths = [
[
9, # len(version||zcash flags||input_count) - segwit flag+version not sent
1 + 1 + len(trusted_input) + 1, # len(trusted_input_marker||len(trusted_input)||trusted_input||scriptSig_len == 0x19)
-1 # get len(scripSig) from last byte of previous chunk + len(input_sequence)
] for trusted_input in trusted_inputs
]
# Hash & sign each input individually
for ptx_for_input, ptx_chunks_len, output_path in zip(ptx_for_inputs, ptx_chunks_lengths, output_paths):
# 3.1 Send pseudo-tx w/ sigScript
btc.untrustedTxInputHashStart(
p1="00",
p2="80", # to continue previously started tx hash, be it BTc or other BTC-like coin
data=reduce(lambda x,y: x+y, ptx_for_input),
chunks_len=ptx_chunks_len
)
print(" Final hash OK")
# 3.2 Sign tx at last. Param is:
# Num_derivs||Dest output path||RFU (0x00)||tx locktime||sigHashType(always 0x01)||Branch_id for overwinter (4B)
print("\n--* Untrusted Transaction Hash Sign")
tx_to_sign_data = output_path \
+ bytes.fromhex("00") \
+ tx_to_sign[-4:] \
+ bytes.fromhex("01") \
+ bytes.fromhex("00000000")
response = btc.untrustedHashSign(
data = tx_to_sign_data
)
self.check_signature(response) # Check sig format only
# self.check_signature(response, expected_der_sig) # Can't test sig value as it depends on signing device seed
print(" Signature OK\n")
| [
"functools.reduce",
"helpers.basetest.LedgerjsApdu",
"pytest.mark.skip",
"helpers.deviceappbtc.DeviceAppBtc",
"pytest.mark.parametrize"
] | [((355, 392), 'helpers.basetest.LedgerjsApdu', 'LedgerjsApdu', ([], {'commands': "['b001000000']"}), "(commands=['b001000000'])\n", (367, 392), False, 'from helpers.basetest import BaseTestBtc, LedgerjsApdu, TxData, CONSENSUS_BRANCH_ID\n'), ((528, 678), 'helpers.basetest.LedgerjsApdu', 'LedgerjsApdu', ([], {'commands': "['e040000015058000002c80000085800000000000000000000000', 'e016000000']", 'expected_resp': '"""1cb81cbd01055a63617368035a4543"""'}), "(commands=[\n 'e040000015058000002c80000085800000000000000000000000', 'e016000000'],\n expected_resp='1cb81cbd01055a63617368035a4543')\n", (540, 678), False, 'from helpers.basetest import BaseTestBtc, LedgerjsApdu, TxData, CONSENSUS_BRANCH_ID\n'), ((809, 930), 'helpers.basetest.LedgerjsApdu', 'LedgerjsApdu', ([], {'commands': "['e040000009028000002c80000085', 'e016000000']", 'expected_resp': '"""1cb81cbd01055a63617368035a4543"""'}), "(commands=['e040000009028000002c80000085', 'e016000000'],\n expected_resp='1cb81cbd01055a63617368035a4543')\n", (821, 930), False, 'from helpers.basetest import BaseTestBtc, LedgerjsApdu, TxData, CONSENSUS_BRANCH_ID\n'), ((1041, 1198), 'helpers.basetest.LedgerjsApdu', 'LedgerjsApdu', ([], {'commands': "['e040000009028000002c80000085', 'e04000000d038000002c8000008580000000',\n 'e04000000d038000002c8000008580000001', 'b001000000']"}), "(commands=['e040000009028000002c80000085',\n 'e04000000d038000002c8000008580000000',\n 'e04000000d038000002c8000008580000001', 'b001000000'])\n", (1053, 1198), False, 'from helpers.basetest import BaseTestBtc, LedgerjsApdu, TxData, CONSENSUS_BRANCH_ID\n'), ((1402, 1552), 'helpers.basetest.LedgerjsApdu', 'LedgerjsApdu', ([], {'commands': "['e040000015058000002c80000085800000000000000000000004', 'e016000000']", 'expected_resp': '"""1cb81cbd01055a63617368035a4543"""'}), "(commands=[\n 'e040000015058000002c80000085800000000000000000000004', 'e016000000'],\n expected_resp='1cb81cbd01055a63617368035a4543')\n", (1414, 1552), False, 'from helpers.basetest import BaseTestBtc, LedgerjsApdu, TxData, CONSENSUS_BRANCH_ID\n'), ((1665, 1702), 'helpers.basetest.LedgerjsApdu', 'LedgerjsApdu', ([], {'commands': "['b001000000']"}), "(commands=['b001000000'])\n", (1677, 1702), False, 'from helpers.basetest import BaseTestBtc, LedgerjsApdu, TxData, CONSENSUS_BRANCH_ID\n'), ((1782, 1932), 'helpers.basetest.LedgerjsApdu', 'LedgerjsApdu', ([], {'commands': "['e040000015058000002c80000085800000000000000000000004', 'e016000000']", 'expected_resp': '"""1cb81cbd01055a63617368035a4543"""'}), "(commands=[\n 'e040000015058000002c80000085800000000000000000000004', 'e016000000'],\n expected_resp='1cb81cbd01055a63617368035a4543')\n", (1794, 1932), False, 'from helpers.basetest import BaseTestBtc, LedgerjsApdu, TxData, CONSENSUS_BRANCH_ID\n'), ((2030, 2067), 'helpers.basetest.LedgerjsApdu', 'LedgerjsApdu', ([], {'commands': "['b001000000']"}), "(commands=['b001000000'])\n", (2042, 2067), False, 'from helpers.basetest import BaseTestBtc, LedgerjsApdu, TxData, CONSENSUS_BRANCH_ID\n'), ((2177, 2977), 'helpers.basetest.LedgerjsApdu', 'LedgerjsApdu', ([], {'commands': "['e042000009000000010400008001',\n 'e042800025edc69b8179fd7c6a11a8a1ba5d17017df5e09296c3a1acdada0d94e199f68857010000006b'\n ,\n 'e042800032483045022100e8043cd498714122a78b6ecbf8ced1f74d1c65093c5e2649336dfa248aea9ccf022023b13e57595635452130'\n ,\n 'e0428000321c91ed0fe7072d295aa232215e74e50d01a73b005dac01210201e1c9d8186c093d116ec619b7dad2b7ff0e7dd16f42d458da'\n , 'e04280000b1100831dc4ff72ffffff00', 'e04280000102',\n 'e042800022a0860100000000001976a914fa9737ab9964860ca0c3e9ad6c7eb3bc9c8f6fb588ac'\n ,\n 'e0428000224d949100000000001976a914b714c60805804d86eb72a38c65ba8370582d09e888ac'\n , 'e04280000400000000']", 'expected_resp': "('3200' + '--' * 2 +\n '20b7c68231303b2425a91b12f05bd6935072e9901137ae30222ef6d60849fc51010000004d94910000000000'\n + '--' * 8)"}), "(commands=['e042000009000000010400008001',\n 'e042800025edc69b8179fd7c6a11a8a1ba5d17017df5e09296c3a1acdada0d94e199f68857010000006b'\n ,\n 'e042800032483045022100e8043cd498714122a78b6ecbf8ced1f74d1c65093c5e2649336dfa248aea9ccf022023b13e57595635452130'\n ,\n 'e0428000321c91ed0fe7072d295aa232215e74e50d01a73b005dac01210201e1c9d8186c093d116ec619b7dad2b7ff0e7dd16f42d458da'\n , 'e04280000b1100831dc4ff72ffffff00', 'e04280000102',\n 'e042800022a0860100000000001976a914fa9737ab9964860ca0c3e9ad6c7eb3bc9c8f6fb588ac'\n ,\n 'e0428000224d949100000000001976a914b714c60805804d86eb72a38c65ba8370582d09e888ac'\n , 'e04280000400000000'], expected_resp='3200' + '--' * 2 +\n '20b7c68231303b2425a91b12f05bd6935072e9901137ae30222ef6d60849fc51010000004d94910000000000'\n + '--' * 8)\n", (2189, 2977), False, 'from helpers.basetest import BaseTestBtc, LedgerjsApdu, TxData, CONSENSUS_BRANCH_ID\n'), ((3129, 3208), 'helpers.basetest.LedgerjsApdu', 'LedgerjsApdu', ([], {'commands': "['e040000015058000002c80000085800000000000000100000001']"}), "(commands=['e040000015058000002c80000085800000000000000100000001'])\n", (3141, 3208), False, 'from helpers.basetest import BaseTestBtc, LedgerjsApdu, TxData, CONSENSUS_BRANCH_ID\n'), ((3270, 3488), 'helpers.basetest.LedgerjsApdu', 'LedgerjsApdu', ([], {'commands': "['e0440005090400008085202f8901',\n 'e04480053b013832004d0420b7c68231303b2425a91b12f05bd6935072e9901137ae30222ef6d60849fc51010000004d9491000000000045e1e144cb88d4d800'\n , 'e044800504ffffff00']"}), "(commands=['e0440005090400008085202f8901',\n 'e04480053b013832004d0420b7c68231303b2425a91b12f05bd6935072e9901137ae30222ef6d60849fc51010000004d9491000000000045e1e144cb88d4d800'\n , 'e044800504ffffff00'])\n", (3282, 3488), False, 'from helpers.basetest import BaseTestBtc, LedgerjsApdu, TxData, CONSENSUS_BRANCH_ID\n'), ((3589, 3786), 'helpers.basetest.LedgerjsApdu', 'LedgerjsApdu', ([], {'commands': "['e04aff0015058000002c80000085800000000000000100000003',\n 'e04a0000230140420f00000000001976a91490360f7a0b0e50d5dd0c924fc1d6e7adb8519c9388ac'\n ]", 'expected_sw': '"""6985"""'}), "(commands=[\n 'e04aff0015058000002c80000085800000000000000100000003',\n 'e04a0000230140420f00000000001976a91490360f7a0b0e50d5dd0c924fc1d6e7adb8519c9388ac'\n ], expected_sw='6985')\n", (3601, 3786), False, 'from helpers.basetest import BaseTestBtc, LedgerjsApdu, TxData, CONSENSUS_BRANCH_ID\n'), ((4087, 4124), 'helpers.basetest.LedgerjsApdu', 'LedgerjsApdu', ([], {'commands': "['b001000000']"}), "(commands=['b001000000'])\n", (4099, 4124), False, 'from helpers.basetest import BaseTestBtc, LedgerjsApdu, TxData, CONSENSUS_BRANCH_ID\n'), ((4204, 4354), 'helpers.basetest.LedgerjsApdu', 'LedgerjsApdu', ([], {'commands': "['e040000015058000002c80000085800000000000000000000004', 'e016000000']", 'expected_resp': '"""1cb81cbd01055a63617368035a4543"""'}), "(commands=[\n 'e040000015058000002c80000085800000000000000000000004', 'e016000000'],\n expected_resp='1cb81cbd01055a63617368035a4543')\n", (4216, 4354), False, 'from helpers.basetest import BaseTestBtc, LedgerjsApdu, TxData, CONSENSUS_BRANCH_ID\n'), ((4408, 4445), 'helpers.basetest.LedgerjsApdu', 'LedgerjsApdu', ([], {'commands': "['b001000000']"}), "(commands=['b001000000'])\n", (4420, 4445), False, 'from helpers.basetest import BaseTestBtc, LedgerjsApdu, TxData, CONSENSUS_BRANCH_ID\n'), ((11434, 11564), 'pytest.mark.skip', 'pytest.mark.skip', ([], {'reason': '"""Hardcoded TrustedInput can\'t be replayed on a different device than the one that generated it"""'}), '(reason=\n "Hardcoded TrustedInput can\'t be replayed on a different device than the one that generated it"\n )\n', (11450, 11564), False, 'import pytest\n'), ((11584, 11640), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""test_data"""', 'ledgerjs_test_data'], {}), "('test_data', ledgerjs_test_data)\n", (11607, 11640), False, 'import pytest\n'), ((4588, 4667), 'helpers.basetest.LedgerjsApdu', 'LedgerjsApdu', ([], {'commands': "['e040000015058000002c80000085800000000000000100000001']"}), "(commands=['e040000015058000002c80000085800000000000000100000001'])\n", (4600, 4667), False, 'from helpers.basetest import BaseTestBtc, LedgerjsApdu, TxData, CONSENSUS_BRANCH_ID\n'), ((4729, 4947), 'helpers.basetest.LedgerjsApdu', 'LedgerjsApdu', ([], {'commands': "['e0440005090400008085202f8901',\n 'e04480053b013832004d0420b7c68231303b2425a91b12f05bd6935072e9901137ae30222ef6d60849fc51010000004d9491000000000045e1e144cb88d4d800'\n , 'e044800504ffffff00']"}), "(commands=['e0440005090400008085202f8901',\n 'e04480053b013832004d0420b7c68231303b2425a91b12f05bd6935072e9901137ae30222ef6d60849fc51010000004d9491000000000045e1e144cb88d4d800'\n , 'e044800504ffffff00'])\n", (4741, 4947), False, 'from helpers.basetest import BaseTestBtc, LedgerjsApdu, TxData, CONSENSUS_BRANCH_ID\n'), ((5060, 5277), 'helpers.basetest.LedgerjsApdu', 'LedgerjsApdu', ([], {'commands': "['e04aff0015058000002c80000085800000000000000100000003',\n 'e04a0000230140420f00000000001976a91490360f7a0b0e50d5dd0c924fc1d6e7adb8519c9388ace04a8000045eb3f840'\n ]", 'expected_resp': '"""0000"""'}), "(commands=[\n 'e04aff0015058000002c80000085800000000000000100000003',\n 'e04a0000230140420f00000000001976a91490360f7a0b0e50d5dd0c924fc1d6e7adb8519c9388ace04a8000045eb3f840'\n ], expected_resp='0000')\n", (5072, 5277), False, 'from helpers.basetest import BaseTestBtc, LedgerjsApdu, TxData, CONSENSUS_BRANCH_ID\n'), ((5532, 5891), 'helpers.basetest.LedgerjsApdu', 'LedgerjsApdu', ([], {'commands': "['e0440085090400008085202f8901',\n 'e04480853b013832004d0420b7c68231303b2425a91b12f05bd6935072e9901137ae30222ef6d60849fc51010000004d9491000000000045e1e144cb88d4d819'\n ,\n 'e04480851d76a9140a146582553b2f5537e13cef6659e82ed8f69b8f88acffffff00',\n 'e048000015058000002c80000085800000000000000100000001']", 'check_sig_format': '(True)'}), "(commands=['e0440085090400008085202f8901',\n 'e04480853b013832004d0420b7c68231303b2425a91b12f05bd6935072e9901137ae30222ef6d60849fc51010000004d9491000000000045e1e144cb88d4d819'\n ,\n 'e04480851d76a9140a146582553b2f5537e13cef6659e82ed8f69b8f88acffffff00',\n 'e048000015058000002c80000085800000000000000100000001'],\n check_sig_format=True)\n", (5544, 5891), False, 'from helpers.basetest import BaseTestBtc, LedgerjsApdu, TxData, CONSENSUS_BRANCH_ID\n'), ((12021, 12035), 'helpers.deviceappbtc.DeviceAppBtc', 'DeviceAppBtc', ([], {}), '()\n', (12033, 12035), False, 'from helpers.deviceappbtc import DeviceAppBtc, CommException\n'), ((12170, 12184), 'helpers.deviceappbtc.DeviceAppBtc', 'DeviceAppBtc', ([], {}), '()\n', (12182, 12184), False, 'from helpers.deviceappbtc import DeviceAppBtc, CommException\n'), ((13525, 13539), 'helpers.deviceappbtc.DeviceAppBtc', 'DeviceAppBtc', ([], {}), '()\n', (13537, 13539), False, 'from helpers.deviceappbtc import DeviceAppBtc, CommException\n'), ((16760, 16805), 'functools.reduce', 'reduce', (['(lambda x, y: x + y)', 'ptx_to_hash_part1'], {}), '(lambda x, y: x + y, ptx_to_hash_part1)\n', (16766, 16805), False, 'from functools import reduce\n'), ((19551, 19593), 'functools.reduce', 'reduce', (['(lambda x, y: x + y)', 'branch_id_data'], {}), '(lambda x, y: x + y, branch_id_data)\n', (19557, 19593), False, 'from functools import reduce\n'), ((22060, 22101), 'functools.reduce', 'reduce', (['(lambda x, y: x + y)', 'ptx_for_input'], {}), '(lambda x, y: x + y, ptx_for_input)\n', (22066, 22101), False, 'from functools import reduce\n')] |
import atexit
import grpc
import logging
import os
import server_pb2
import server_pb2_grpc
port: str = None
def init_env() -> None:
global port
port = os.environ['PORT']
logging.info('Found PORT at %s', port)
def init_atexit() -> None:
def end():
logging.info('bye')
atexit.register(end)
def init_logging() -> None:
logging.basicConfig(
format='%(asctime)s %(levelname)-8s %(message)s',
level=logging.INFO,
datefmt='%Y-%m-%d %H:%M:%S')
logging.info('hi')
def set_service(stub, service: str) -> server_pb2.ReadyStatus:
response = stub.RegisterService(server_pb2.ReadyService(name=service))
ack: bool = response.ready
logging.info('Registered service "%s" - got response %r', service, ack)
def get_inv(stub) -> None:
response = stub.GetInventory(server_pb2.ReadyStatus(ready=True))
for s in response.entry:
logging.info('Got service "%s" with status %r', s.name, s.ready)
def get_status(stub, service: str) -> None:
response = stub.RegisterService(server_pb2.Ready(name=service))
ack: bool = response.ready
logging.info('Got service "%s" - got status %r', service, ack)
def init_client() -> None:
addr: str = f'localhost:{port}'
logging.info('Calling %s', addr)
channel = grpc.insecure_channel(addr)
stub = server_pb2_grpc.ReadyStub(channel)
services: List[str] = ['A', 'B', 'C']
for s in services:
set_service(stub, s)
get_inv(stub)
response2 = stub.GetKey(server_pb2.ConfKey(key=key))
logging.info('Queried key "%s" and got "%s"', key, value)
def init() -> None:
init_logging()
init_atexit()
init_env()
init_client()
def main() -> None:
init()
if __name__ == '__main__':
main()
| [
"logging.basicConfig",
"server_pb2_grpc.ReadyStub",
"grpc.insecure_channel",
"server_pb2.ConfKey",
"server_pb2.ReadyService",
"server_pb2.Ready",
"server_pb2.ReadyStatus",
"logging.info",
"atexit.register"
] | [((189, 227), 'logging.info', 'logging.info', (['"""Found PORT at %s"""', 'port'], {}), "('Found PORT at %s', port)\n", (201, 227), False, 'import logging\n'), ((305, 325), 'atexit.register', 'atexit.register', (['end'], {}), '(end)\n', (320, 325), False, 'import atexit\n'), ((360, 483), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s %(levelname)-8s %(message)s"""', 'level': 'logging.INFO', 'datefmt': '"""%Y-%m-%d %H:%M:%S"""'}), "(format='%(asctime)s %(levelname)-8s %(message)s', level\n =logging.INFO, datefmt='%Y-%m-%d %H:%M:%S')\n", (379, 483), False, 'import logging\n'), ((509, 527), 'logging.info', 'logging.info', (['"""hi"""'], {}), "('hi')\n", (521, 527), False, 'import logging\n'), ((703, 774), 'logging.info', 'logging.info', (['"""Registered service "%s" - got response %r"""', 'service', 'ack'], {}), '(\'Registered service "%s" - got response %r\', service, ack)\n', (715, 774), False, 'import logging\n'), ((1124, 1186), 'logging.info', 'logging.info', (['"""Got service "%s" - got status %r"""', 'service', 'ack'], {}), '(\'Got service "%s" - got status %r\', service, ack)\n', (1136, 1186), False, 'import logging\n'), ((1256, 1288), 'logging.info', 'logging.info', (['"""Calling %s"""', 'addr'], {}), "('Calling %s', addr)\n", (1268, 1288), False, 'import logging\n'), ((1304, 1331), 'grpc.insecure_channel', 'grpc.insecure_channel', (['addr'], {}), '(addr)\n', (1325, 1331), False, 'import grpc\n'), ((1343, 1377), 'server_pb2_grpc.ReadyStub', 'server_pb2_grpc.ReadyStub', (['channel'], {}), '(channel)\n', (1368, 1377), False, 'import server_pb2_grpc\n'), ((1553, 1610), 'logging.info', 'logging.info', (['"""Queried key "%s" and got "%s\\""""', 'key', 'value'], {}), '(\'Queried key "%s" and got "%s"\', key, value)\n', (1565, 1610), False, 'import logging\n'), ((280, 299), 'logging.info', 'logging.info', (['"""bye"""'], {}), "('bye')\n", (292, 299), False, 'import logging\n'), ((629, 666), 'server_pb2.ReadyService', 'server_pb2.ReadyService', ([], {'name': 'service'}), '(name=service)\n', (652, 666), False, 'import server_pb2\n'), ((837, 871), 'server_pb2.ReadyStatus', 'server_pb2.ReadyStatus', ([], {'ready': '(True)'}), '(ready=True)\n', (859, 871), False, 'import server_pb2\n'), ((910, 974), 'logging.info', 'logging.info', (['"""Got service "%s" with status %r"""', 's.name', 's.ready'], {}), '(\'Got service "%s" with status %r\', s.name, s.ready)\n', (922, 974), False, 'import logging\n'), ((1057, 1087), 'server_pb2.Ready', 'server_pb2.Ready', ([], {'name': 'service'}), '(name=service)\n', (1073, 1087), False, 'import server_pb2\n'), ((1520, 1547), 'server_pb2.ConfKey', 'server_pb2.ConfKey', ([], {'key': 'key'}), '(key=key)\n', (1538, 1547), False, 'import server_pb2\n')] |
import base64
import shutil
import json
import re
from enum import Enum, auto
from typing import Optional
import py7zr
from cachetools import TTLCache, cached
from ruamel.yaml import YAML, YAMLError
from logger import getLogger
import os
import tempfile
import zipfile
import requests
from bs4 import BeautifulSoup
l = getLogger("main")
class CurationType(Enum):
FLASH_GAME = auto()
OTHER_GAME = auto()
ANIMATION = auto()
def validate_curation(filename: str) -> tuple[list,
list,
Optional[bool],
Optional[CurationType],
Optional[dict],
Optional[list[dict]]]:
errors: list = []
warnings: list = []
# process archive
filenames: list = []
max_uncompressed_size = 50 * 1000 * 1000 * 1000
base_path = None
if filename.endswith(".7z"):
try:
l.debug(f"reading archive '{filename}'...")
archive = py7zr.SevenZipFile(filename, mode='r')
uncompressed_size = archive.archiveinfo().uncompressed
if uncompressed_size > max_uncompressed_size:
warnings.append(
f"The archive is too large to be validated (`{uncompressed_size // 1000000}MB/{max_uncompressed_size // 1000000}MB`).")
archive.close()
return errors, warnings, None, None, None, None
filenames = archive.getnames()
base_path = tempfile.mkdtemp(prefix="curation_validator_") + "/"
archive.extractall(path=base_path)
archive.close()
except Exception as e:
l.error(f"there was an error while reading file '{filename}': {e}")
errors.append("There seems to a problem with your 7z file.")
return errors, warnings, None, None, None, None
elif filename.endswith(".zip"):
try:
l.debug(f"reading archive '{filename}'...")
archive = zipfile.ZipFile(filename, mode='r')
uncompressed_size = sum([zinfo.file_size for zinfo in archive.filelist])
if uncompressed_size > max_uncompressed_size:
warnings.append(
f"The archive is too large to be validated (`{uncompressed_size // 1000000}MB/{max_uncompressed_size // 1000000}MB`).")
archive.close()
return errors, warnings, None, None, None, None
filenames = archive.namelist()
base_path = tempfile.mkdtemp(prefix="curation_validator_") + "/"
archive.extractall(path=base_path)
archive.close()
except Exception as e:
l.error(f"there was an error while reading file '{filename}': {e}")
errors.append("There seems to a problem with your zip file.")
return errors, warnings, None, None, None, None
elif filename.endswith(".rar"):
errors.append("Curations must be either .zip or .7z, not .rar.")
return errors, warnings, None, None, None, None
else:
l.warn(f"file type of file '{filename}' not supported")
errors.append(f"file type of file '{filename}' not supported")
return errors, warnings, None, None, None, None
# check files
l.debug(f"validating archive data for '{filename}'...")
uuid_folder_regex = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/?$")
uuid_folder = [match for match in filenames if uuid_folder_regex.match(match) is not None]
logo = []
ss = []
if len(uuid_folder) == 0: # legacy or broken curation
content_folder_regex = re.compile(r"^[^/]+/content/?$")
meta_regex = re.compile(r"^[^/]+/meta\.(yaml|yml|txt)$")
logo_regex = re.compile(r"^[^/]+/logo\.(png)$")
logo_regex_case = re.compile(r"(?i)^[^/]+/logo\.(png)$")
ss_regex = re.compile(r"^[^/]+/ss\.(png)$")
ss_regex_case = re.compile(r"(?i)^[^/]+/ss\.(png)$")
content_folder = [match for match in filenames if content_folder_regex.match(match) is not None]
meta = [match for match in filenames if meta_regex.match(match) is not None]
logo = [match for match in filenames if logo_regex.match(match) is not None]
logo_case = [match for match in filenames if logo_regex_case.match(match) is not None]
ss = [match for match in filenames if ss_regex.match(match) is not None]
ss_case = [match for match in filenames if ss_regex_case.match(match) is not None]
else: # core curation
content_folder_regex = re.compile(
r"^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/content/?$")
meta_regex = re.compile(
r"^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/meta\.(yaml|yml|txt)$")
logo_regex = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/logo\.png$")
logo_regex_case = re.compile(
r"(?i)^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/logo\.(png)$")
ss_regex = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/ss\.png$")
ss_regex_case = re.compile(
r"(?i)^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/ss\.(png)$")
content_folder = [match for match in filenames if content_folder_regex.match(match) is not None]
meta = [match for match in filenames if meta_regex.match(match) is not None]
logo = [match for match in filenames if logo_regex.match(match) is not None]
logo_case = [match for match in filenames if logo_regex_case.match(match) is not None]
ss = [match for match in filenames if ss_regex.match(match) is not None]
ss_case = [match for match in filenames if ss_regex_case.match(match) is not None]
if len(logo) == 0 and len(ss) == 0 and len(content_folder) == 0 and len(meta) == 0:
errors.append("Logo, screenshot, content folder and meta not found. Is your curation structured properly?")
archive_cleanup(filename, base_path)
return errors, warnings, None, None, None, None
if set(logo) != set(logo_case):
errors.append("Logo file extension must be lowercase.")
else:
if len(logo) == 0:
errors.append("Logo file is either missing or its filename is incorrect.")
if set(ss) != set(ss_case):
errors.append("Screenshot file extension must be lowercase.")
else:
if len(ss) == 0:
errors.append("Screenshot file is either missing or its filename is incorrect.")
# check content
if len(content_folder) == 0:
errors.append("Content folder not found.")
else:
content_folder_path = base_path + content_folder[0]
filecount_in_content = sum([len(files) for r, d, files in os.walk(content_folder_path)])
if filecount_in_content == 0:
errors.append("No files found in content folder.")
# localflash checking
if 'localflash' in os.listdir(content_folder_path):
files_in_localflash = os.listdir(content_folder_path + '/localflash')
if len(files_in_localflash) > 1:
errors.append("Content must be in additional folder in localflash rather than in localflash directly.")
else:
with open("data/common_localflash_names.json") as f:
bad_localflash_names = json.load(f)["names"]
for file in files_in_localflash:
filepath = content_folder_path + '/localflash/' + file
if os.path.isfile(filepath):
errors.append(
"Content must be in additional folder in localflash rather than in localflash directly.")
break
elif file in bad_localflash_names:
errors.append("Extremely common localflash containing folder name, please change.")
with open("data/bad_system_files.json") as f:
bad_system_files = json.load(f)["names"]
for name in bad_system_files:
if any(name in s for s in filenames):
errors.append(f"{name} file found in curation, please remove.")
# process meta
is_extreme = False
curation_type = None
props: dict = {}
if len(meta) == 0:
errors.append(
"Meta file is either missing or its filename is incorrect. Are you using Flashpoint Core for curating?")
else:
meta_filename = meta[0]
with open(base_path + meta_filename, mode='r', encoding='utf8') as meta_file:
if meta_filename.endswith(".yml") or meta_filename.endswith(".yaml"):
try:
yaml = YAML(typ="safe")
props: dict = yaml.load(meta_file)
if props is None:
errors.append("The meta file seems to be empty.")
archive_cleanup(filename, base_path)
return errors, warnings, None, None, None, None
except YAMLError:
errors.append("Unable to load meta YAML file")
archive_cleanup(filename, base_path)
return errors, warnings, None, None, None, None
except ValueError:
errors.append("Invalid release date. Ensure entered date is valid.")
archive_cleanup(filename, base_path)
return errors, warnings, None, None, None, None
elif meta_filename.endswith(".txt"):
break_index: int = 0
while break_index != -1:
props, break_index = parse_lines_until_multiline(meta_file.readlines(), props,
break_index)
props, break_index = parse_multiline(meta_file.readlines(), props, break_index)
if props.get("Genre") is not None:
props["Tags"] = props["Genre"]
else:
errors.append(
"Meta file is either missing or its filename is incorrect. Are you using Flashpoint Core for curating?")
archive_cleanup(filename, base_path)
return errors, warnings, None, None, None, None
title: tuple[str, bool] = ("Title", bool(props.get("Title")))
# developer: tuple[str, bool] = ("Developer", bool(props["Developer"]))
release_date: tuple[str, bool] = ("Release Date", bool(props.get("Release Date")))
if release_date[1]:
date_string = str(props.get("Release Date")).strip()
if len(date_string) > 0:
date_regex = re.compile(r"^\d{4}(-\d{2}){0,2}$")
if not date_regex.match(date_string):
errors.append(
f"Release date {date_string} is incorrect. Release dates should always be in `YYYY-MM-DD` format.")
language_properties: tuple[str, bool] = "Languages", bool(props.get("Languages"))
if language_properties[1]:
with open("data/language-codes.json") as f:
list_of_language_codes: list[dict] = json.load(f)
with open("data/lang_replacements.json") as f:
replacements: dict = json.load(f)
language_str: str = props.get("Languages", "")
language_codes = language_str.split(";")
language_codes = [x.strip() for x in language_codes]
valid_language_codes = []
for x in list_of_language_codes:
valid_language_codes.append(x["alpha2"])
for language_code in language_codes:
replacement_code = replacements.get(language_code)
if language_code not in valid_language_codes:
if language_code == "":
pass
elif ',' in language_code:
errors.append("Languages should be separated with semicolons, not commas.")
elif language_code in [x["English"] for x in list_of_language_codes]:
for x in list_of_language_codes:
if language_code in x["English"]:
errors.append(
f"Languages must be in ISO 639-1 format, so please use `{x['alpha2']}` instead of `{language_code}`")
elif replacement_code is not None:
language_name = ""
for x in list_of_language_codes:
if replacement_code == x["alpha2"]:
language_name = x["English"]
errors.append(
f"The correct ISO 639-1 language code for {language_name} is `{replacement_code}`, not `{language_code}`.")
else:
errors.append(f"Code `{language_code}` is not a valid ISO 639-1 language code.")
# tag: tuple[str, bool] = ("Tags", bool(props["Tags"]))
source: tuple[str, bool] = ("Source", bool(props.get("Source")))
status: tuple[str, bool] = ("Status", bool(props.get("Status")))
launch_command: tuple[str, bool] = ("Launch Command", bool(props.get("Launch Command")))
application_path: tuple[str, bool] = ("Application Path", bool(props.get("Application Path")))
# TODO check description?
# description: tuple[str, bool] = ("Description", bool(props["Original Description"]))
# if description[1] is False and (
# bool(props["Curation Notes"]) or bool(props["Game Notes"])):
# reply += "Make sure you didn't put your description in the notes section.\n"
simple_mandatory_props: list[tuple[str, bool]] = [title, language_properties, source, launch_command, status,
application_path]
if not all([x[1] for x in simple_mandatory_props]):
for prop in simple_mandatory_props:
if prop[1] is False:
errors.append(f"The `{prop[0]}` property in the meta file is mandatory.")
if launch_command[1] and "https" in props["Launch Command"]:
errors.append("Found `https` in launch command. All launch commands must use `http` instead of `https`.")
if launch_command[1] and props["Launch Command"] in get_launch_commands_bluebot():
errors.append(
"Identical launch command already present in the master database. Is your curation a duplicate?")
# TODO check optional props?
# optional_props: list[tuple[str, bool]] = [developer, release_date, tag, description]
# if not all(optional_props[1]): for x in optional_props: if x[1] is False: reply += x[0] +
# "is missing, but not necessary. Add it if you can find it, but it's okay if you can't.\n"
tags: list[str] = props.get("Tags", "").split(";") if props.get("Tags", "") is not None else ""
tags: list[str] = [x.strip() for x in tags]
tags: list[str] = [x for x in tags if len(x) > 0]
master_tag_list = get_tag_list()
if not tags:
errors.append("Missing tags. At least one tag must be specified.")
else:
for tag in tags:
if tag not in master_tag_list:
warnings.append(f"Tag `{tag}` is not a known tag, please verify (did you write it correctly?).")
extreme: tuple[str, bool] = ("Extreme", bool(props.get("Extreme")))
extreme_tags = get_extreme_tag_list_file()
is_extreme = False
if extreme[1] and (props["Extreme"] == "Yes" or props["Extreme"] is True):
is_extreme = True
if tags:
has_extreme_tags = bool([tag for tag in tags if tag in extreme_tags])
has_legacy_extreme = "LEGACY-Extreme" in tags
if has_extreme_tags or has_legacy_extreme:
is_extreme = True
if is_extreme and not has_extreme_tags:
errors.append("Curation is extreme but lacks extreme tags.")
if props.get("Library") is not None and "theatre" in props.get("Library"):
curation_type = CurationType.ANIMATION
else:
platform: Optional[str] = props.get("Platform")
if platform is None or "Flash" in platform:
curation_type = CurationType.FLASH_GAME
else:
curation_type = CurationType.OTHER_GAME
images = []
if len(logo) == 1:
logo = logo[0]
image_path = f"{base_path}{logo}"
images.append({"type": "logo", "data": encode_image(image_path)})
for screenshot in ss:
image_path = f"{base_path}{screenshot}"
images.append({"type": f"screenshot", "data": encode_image(image_path)})
archive_cleanup(filename, base_path)
return errors, warnings, is_extreme, curation_type, props, images
def encode_image(image_path):
l.debug(f"encoding file '{image_path}' into base64")
with open(image_path, "rb") as f:
return base64.b64encode(f.read())
def archive_cleanup(filename, base_path):
l.debug(f"cleaning up extracted files in {base_path} after the archive '{filename}'...")
shutil.rmtree(base_path, True)
@cached(cache=TTLCache(maxsize=1, ttl=600))
def get_launch_commands_bluebot() -> list[str]:
l.debug(f"getting launch commands from bluebot...")
resp = requests.get(url="https://bluebot.unstable.life/launch-commands")
return resp.json()["launch_commands"]
@cached(cache=TTLCache(maxsize=1, ttl=600))
def get_tag_list_bluebot() -> list[str]:
l.debug(f"getting tags from bluebot...")
resp = requests.get(url="https://bluebot.unstable.life/tags")
return resp.json()["tags"]
@cached(cache=TTLCache(maxsize=1, ttl=3600))
def get_tag_list_file() -> list[str]:
l.debug(f"getting tags from file...")
with open("data/category_tags.json", "r", encoding="utf-8") as f:
data = json.load(f)
return data["tags"]
@cached(cache=TTLCache(maxsize=1, ttl=3600))
def get_extreme_tag_list_file() -> list[str]:
l.debug(f"getting tags from file...")
with open("data/extreme_tags.json", "r", encoding="utf-8") as f:
data = json.load(f)
return data["tags"]
@cached(cache=TTLCache(maxsize=1, ttl=60))
def get_tag_list_wiki() -> list[str]:
l.debug(f"getting tags from wiki...")
tags = []
resp = requests.get(url="https://bluemaxima.org/flashpoint/datahub/Tags")
soup = BeautifulSoup(resp.text, "html.parser")
tables = soup.find_all("table")
for table in tables:
rows = table.find_all("tr")
for row in rows:
cols = row.find_all('td')
if len(cols) > 0:
col = cols[0]
links = row.find_all('a')
if len(links) > 0:
tags.append(links[0].contents[0].strip())
else:
tags.append(col.contents[0].strip())
return tags
def get_tag_list() -> list[str]:
bluebot_tags = get_tag_list_bluebot()
file_tags = get_tag_list_file()
wiki_tags = get_tag_list_wiki()
return list(set(file_tags + wiki_tags + bluebot_tags))
def parse_lines_until_multiline(lines: list[str], d: dict, starting_number: int):
break_number: int = -1
for idx, line in enumerate(lines[starting_number:]):
if '|' not in line and line.strip():
split: list[str] = line.split(":")
split: list[str] = [x.strip(' ') for x in split]
d.update({split[0]: split[1]})
else:
break_number = idx
break
return d, break_number
def parse_multiline(lines: list[str], d: dict, starting_number: int):
break_number = -1
key: str = ""
val: str = ""
for idx, line in enumerate(lines[starting_number:]):
if idx is starting_number:
split = line.split(':')
split = [x.strip(' ') for x in split]
key = split[0]
else:
if line.startswith('\t'):
line = line.strip(" \t")
val += line
else:
break_number = idx
break
d.update({key: val})
return d, break_number
| [
"os.listdir",
"enum.auto",
"py7zr.SevenZipFile",
"re.compile",
"zipfile.ZipFile",
"requests.get",
"ruamel.yaml.YAML",
"bs4.BeautifulSoup",
"os.path.isfile",
"cachetools.TTLCache",
"tempfile.mkdtemp",
"shutil.rmtree",
"json.load",
"logger.getLogger",
"os.walk"
] | [((322, 339), 'logger.getLogger', 'getLogger', (['"""main"""'], {}), "('main')\n", (331, 339), False, 'from logger import getLogger\n'), ((385, 391), 'enum.auto', 'auto', ([], {}), '()\n', (389, 391), False, 'from enum import Enum, auto\n'), ((409, 415), 'enum.auto', 'auto', ([], {}), '()\n', (413, 415), False, 'from enum import Enum, auto\n'), ((432, 438), 'enum.auto', 'auto', ([], {}), '()\n', (436, 438), False, 'from enum import Enum, auto\n'), ((3462, 3552), 're.compile', 're.compile', (['"""^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/?$"""'], {}), "(\n '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/?$')\n", (3472, 3552), False, 'import re\n'), ((17552, 17582), 'shutil.rmtree', 'shutil.rmtree', (['base_path', '(True)'], {}), '(base_path, True)\n', (17565, 17582), False, 'import shutil\n'), ((17744, 17809), 'requests.get', 'requests.get', ([], {'url': '"""https://bluebot.unstable.life/launch-commands"""'}), "(url='https://bluebot.unstable.life/launch-commands')\n", (17756, 17809), False, 'import requests\n'), ((17995, 18049), 'requests.get', 'requests.get', ([], {'url': '"""https://bluebot.unstable.life/tags"""'}), "(url='https://bluebot.unstable.life/tags')\n", (18007, 18049), False, 'import requests\n'), ((18744, 18810), 'requests.get', 'requests.get', ([], {'url': '"""https://bluemaxima.org/flashpoint/datahub/Tags"""'}), "(url='https://bluemaxima.org/flashpoint/datahub/Tags')\n", (18756, 18810), False, 'import requests\n'), ((18822, 18861), 'bs4.BeautifulSoup', 'BeautifulSoup', (['resp.text', '"""html.parser"""'], {}), "(resp.text, 'html.parser')\n", (18835, 18861), False, 'from bs4 import BeautifulSoup\n'), ((3762, 3793), 're.compile', 're.compile', (['"""^[^/]+/content/?$"""'], {}), "('^[^/]+/content/?$')\n", (3772, 3793), False, 'import re\n'), ((3816, 3859), 're.compile', 're.compile', (['"""^[^/]+/meta\\\\.(yaml|yml|txt)$"""'], {}), "('^[^/]+/meta\\\\.(yaml|yml|txt)$')\n", (3826, 3859), False, 'import re\n'), ((3881, 3915), 're.compile', 're.compile', (['"""^[^/]+/logo\\\\.(png)$"""'], {}), "('^[^/]+/logo\\\\.(png)$')\n", (3891, 3915), False, 'import re\n'), ((3942, 3980), 're.compile', 're.compile', (['"""(?i)^[^/]+/logo\\\\.(png)$"""'], {}), "('(?i)^[^/]+/logo\\\\.(png)$')\n", (3952, 3980), False, 'import re\n'), ((4000, 4032), 're.compile', 're.compile', (['"""^[^/]+/ss\\\\.(png)$"""'], {}), "('^[^/]+/ss\\\\.(png)$')\n", (4010, 4032), False, 'import re\n'), ((4057, 4093), 're.compile', 're.compile', (['"""(?i)^[^/]+/ss\\\\.(png)$"""'], {}), "('(?i)^[^/]+/ss\\\\.(png)$')\n", (4067, 4093), False, 'import re\n'), ((4694, 4797), 're.compile', 're.compile', (['"""^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/content/?$"""'], {}), "(\n '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/content/?$'\n )\n", (4704, 4797), False, 'import re\n'), ((4823, 4938), 're.compile', 're.compile', (['"""^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/meta\\\\.(yaml|yml|txt)$"""'], {}), "(\n '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/meta\\\\.(yaml|yml|txt)$'\n )\n", (4833, 4938), False, 'import re\n'), ((4963, 5067), 're.compile', 're.compile', (['"""^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/logo\\\\.png$"""'], {}), "(\n '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/logo\\\\.png$'\n )\n", (4973, 5067), False, 'import re\n'), ((5084, 5194), 're.compile', 're.compile', (['"""(?i)^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/logo\\\\.(png)$"""'], {}), "(\n '(?i)^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/logo\\\\.(png)$'\n )\n", (5094, 5194), False, 'import re\n'), ((5217, 5319), 're.compile', 're.compile', (['"""^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/ss\\\\.png$"""'], {}), "(\n '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/ss\\\\.png$'\n )\n", (5227, 5319), False, 'import re\n'), ((5334, 5442), 're.compile', 're.compile', (['"""(?i)^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/ss\\\\.(png)$"""'], {}), "(\n '(?i)^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/ss\\\\.(png)$'\n )\n", (5344, 5442), False, 'import re\n'), ((17599, 17627), 'cachetools.TTLCache', 'TTLCache', ([], {'maxsize': '(1)', 'ttl': '(600)'}), '(maxsize=1, ttl=600)\n', (17607, 17627), False, 'from cachetools import TTLCache, cached\n'), ((17868, 17896), 'cachetools.TTLCache', 'TTLCache', ([], {'maxsize': '(1)', 'ttl': '(600)'}), '(maxsize=1, ttl=600)\n', (17876, 17896), False, 'from cachetools import TTLCache, cached\n'), ((18293, 18305), 'json.load', 'json.load', (['f'], {}), '(f)\n', (18302, 18305), False, 'import json\n'), ((18097, 18126), 'cachetools.TTLCache', 'TTLCache', ([], {'maxsize': '(1)', 'ttl': '(3600)'}), '(maxsize=1, ttl=3600)\n', (18105, 18126), False, 'from cachetools import TTLCache, cached\n'), ((18553, 18565), 'json.load', 'json.load', (['f'], {}), '(f)\n', (18562, 18565), False, 'import json\n'), ((18350, 18379), 'cachetools.TTLCache', 'TTLCache', ([], {'maxsize': '(1)', 'ttl': '(3600)'}), '(maxsize=1, ttl=3600)\n', (18358, 18379), False, 'from cachetools import TTLCache, cached\n'), ((18610, 18637), 'cachetools.TTLCache', 'TTLCache', ([], {'maxsize': '(1)', 'ttl': '(60)'}), '(maxsize=1, ttl=60)\n', (18618, 18637), False, 'from cachetools import TTLCache, cached\n'), ((1102, 1140), 'py7zr.SevenZipFile', 'py7zr.SevenZipFile', (['filename'], {'mode': '"""r"""'}), "(filename, mode='r')\n", (1120, 1140), False, 'import py7zr\n'), ((7181, 7212), 'os.listdir', 'os.listdir', (['content_folder_path'], {}), '(content_folder_path)\n', (7191, 7212), False, 'import os\n'), ((7248, 7295), 'os.listdir', 'os.listdir', (["(content_folder_path + '/localflash')"], {}), "(content_folder_path + '/localflash')\n", (7258, 7295), False, 'import os\n'), ((8246, 8258), 'json.load', 'json.load', (['f'], {}), '(f)\n', (8255, 8258), False, 'import json\n'), ((1604, 1650), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {'prefix': '"""curation_validator_"""'}), "(prefix='curation_validator_')\n", (1620, 1650), False, 'import tempfile\n'), ((2103, 2138), 'zipfile.ZipFile', 'zipfile.ZipFile', (['filename'], {'mode': '"""r"""'}), "(filename, mode='r')\n", (2118, 2138), False, 'import zipfile\n'), ((10948, 10984), 're.compile', 're.compile', (['"""^\\\\d{4}(-\\\\d{2}){0,2}$"""'], {}), "('^\\\\d{4}(-\\\\d{2}){0,2}$')\n", (10958, 10984), False, 'import re\n'), ((11432, 11444), 'json.load', 'json.load', (['f'], {}), '(f)\n', (11441, 11444), False, 'import json\n'), ((11541, 11553), 'json.load', 'json.load', (['f'], {}), '(f)\n', (11550, 11553), False, 'import json\n'), ((2620, 2666), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {'prefix': '"""curation_validator_"""'}), "(prefix='curation_validator_')\n", (2636, 2666), False, 'import tempfile\n'), ((6992, 7020), 'os.walk', 'os.walk', (['content_folder_path'], {}), '(content_folder_path)\n', (6999, 7020), False, 'import os\n'), ((8946, 8962), 'ruamel.yaml.YAML', 'YAML', ([], {'typ': '"""safe"""'}), "(typ='safe')\n", (8950, 8962), False, 'from ruamel.yaml import YAML, YAMLError\n'), ((7591, 7603), 'json.load', 'json.load', (['f'], {}), '(f)\n', (7600, 7603), False, 'import json\n'), ((7772, 7796), 'os.path.isfile', 'os.path.isfile', (['filepath'], {}), '(filepath)\n', (7786, 7796), False, 'import os\n')] |
# -*- encoding: utf-8 -*-
"""
License: MIT
Copyright (c) 2019 - present AppSeed.us
"""
from django.urls import path
from .views import login_view, register_user, reset_password
from django.contrib.auth.views import LogoutView
from .views import *
urlpatterns = [
path('login/', login_view, name="login"),
path('register/', register_user, name="register"),
path("logout/", LogoutView.as_view(), name="logout"),
path('reset/', reset_view, name="reset"),
path('reset_password/<str:pk>/',reset_password, name="reset_password"),
]
| [
"django.urls.path",
"django.contrib.auth.views.LogoutView.as_view"
] | [((269, 309), 'django.urls.path', 'path', (['"""login/"""', 'login_view'], {'name': '"""login"""'}), "('login/', login_view, name='login')\n", (273, 309), False, 'from django.urls import path\n'), ((315, 364), 'django.urls.path', 'path', (['"""register/"""', 'register_user'], {'name': '"""register"""'}), "('register/', register_user, name='register')\n", (319, 364), False, 'from django.urls import path\n'), ((428, 468), 'django.urls.path', 'path', (['"""reset/"""', 'reset_view'], {'name': '"""reset"""'}), "('reset/', reset_view, name='reset')\n", (432, 468), False, 'from django.urls import path\n'), ((474, 545), 'django.urls.path', 'path', (['"""reset_password/<str:pk>/"""', 'reset_password'], {'name': '"""reset_password"""'}), "('reset_password/<str:pk>/', reset_password, name='reset_password')\n", (478, 545), False, 'from django.urls import path\n'), ((386, 406), 'django.contrib.auth.views.LogoutView.as_view', 'LogoutView.as_view', ([], {}), '()\n', (404, 406), False, 'from django.contrib.auth.views import LogoutView\n')] |
from flask import Blueprint
admin_blu = Blueprint("admin", __name__, url_prefix="/admin")
from .views import *
@admin_blu.before_request
def admin_identification():
"""
进入后台之前的校验
:return:
"""
# 我先从你的session获取下is_admin 如果能获取到 说明你是管理员
# 如果访问的接口是/admin/login 那么可以直接访问
is_login = request.url.endswith("/login") # 判断请求的url是否以/login结尾,即登录页面
is_admin = session.get("is_admin") # 判断用户是否是管理员
if not is_admin and not is_login:
return redirect("/")
| [
"flask.Blueprint"
] | [((42, 91), 'flask.Blueprint', 'Blueprint', (['"""admin"""', '__name__'], {'url_prefix': '"""/admin"""'}), "('admin', __name__, url_prefix='/admin')\n", (51, 91), False, 'from flask import Blueprint\n')] |
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from recipe.models import Tag
from recipe.serializers import TagSerializer
from core.tests.utils import sample_tag, sample_user
TAG_LIST_URL = reverse('recipe:list-tag')
TAG_CREATE_URL = reverse('recipe:create-tag')
class PublicTagListAPI(TestCase):
def setUp(self):
self.user = sample_user()
self.tag = sample_tag(user=self.user)
self.client = APIClient()
self.payload = {
"user": self.user.id,
"name": "Unit Test Tag"
}
def test_list_tag_unauthenticated(self):
"""Test listing tag without log-in"""
res = self.client.get(TAG_LIST_URL)
self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)
def test_create_tag_unauthenticated(self):
"""Test creating tag without log-in"""
res = self.client.post(TAG_CREATE_URL, self.payload, format="json")
self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)
class PrivateTagListApiTest(TestCase):
def setUp(self):
self.user = sample_user()
self.tag = sample_tag(user=self.user)
self.client = APIClient()
self.client.force_authenticate(self.user)
self.payload = {
"user": self.user.id,
"name": "Unit Test Tag"
}
def test_list_tag_authenticated(self):
"""Test listing tag with log-in"""
res = self.client.get(TAG_LIST_URL)
self.assertEqual(res.status_code, status.HTTP_200_OK)
tags = TagSerializer(Tag.objects.all(), many=True)
self.assertEqual(res.data, tags.data)
def test_tags_limited_to_user(self):
"""Test that tags returned are for the authenticated user"""
user2 = sample_user(email="<EMAIL>")
sample_tag(user=user2, name="test tag 2")
res = self.client.get(TAG_LIST_URL)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(len(res.data), 1)
self.assertEqual(res.data[0]["name"], self.tag.name)
def test_create_tag_authenticated(self):
"""Test creating tag withd log-in"""
res = self.client.post(TAG_CREATE_URL, self.payload, format="json")
self.assertEqual(res.status_code, status.HTTP_201_CREATED)
created_tag = Tag.objects.get(**self.payload)
self.assertEqual(res.data["name"], created_tag.name)
def test_create_tag_invalid_payload(self):
invalid_payload = {}
res = self.client.post(TAG_CREATE_URL, invalid_payload, format="json")
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
| [
"recipe.models.Tag.objects.get",
"core.tests.utils.sample_tag",
"rest_framework.test.APIClient",
"recipe.models.Tag.objects.all",
"django.urls.reverse",
"core.tests.utils.sample_user"
] | [((335, 361), 'django.urls.reverse', 'reverse', (['"""recipe:list-tag"""'], {}), "('recipe:list-tag')\n", (342, 361), False, 'from django.urls import reverse\n'), ((379, 407), 'django.urls.reverse', 'reverse', (['"""recipe:create-tag"""'], {}), "('recipe:create-tag')\n", (386, 407), False, 'from django.urls import reverse\n'), ((485, 498), 'core.tests.utils.sample_user', 'sample_user', ([], {}), '()\n', (496, 498), False, 'from core.tests.utils import sample_tag, sample_user\n'), ((518, 544), 'core.tests.utils.sample_tag', 'sample_tag', ([], {'user': 'self.user'}), '(user=self.user)\n', (528, 544), False, 'from core.tests.utils import sample_tag, sample_user\n'), ((567, 578), 'rest_framework.test.APIClient', 'APIClient', ([], {}), '()\n', (576, 578), False, 'from rest_framework.test import APIClient\n'), ((1217, 1230), 'core.tests.utils.sample_user', 'sample_user', ([], {}), '()\n', (1228, 1230), False, 'from core.tests.utils import sample_tag, sample_user\n'), ((1250, 1276), 'core.tests.utils.sample_tag', 'sample_tag', ([], {'user': 'self.user'}), '(user=self.user)\n', (1260, 1276), False, 'from core.tests.utils import sample_tag, sample_user\n'), ((1299, 1310), 'rest_framework.test.APIClient', 'APIClient', ([], {}), '()\n', (1308, 1310), False, 'from rest_framework.test import APIClient\n'), ((1892, 1920), 'core.tests.utils.sample_user', 'sample_user', ([], {'email': '"""<EMAIL>"""'}), "(email='<EMAIL>')\n", (1903, 1920), False, 'from core.tests.utils import sample_tag, sample_user\n'), ((1929, 1970), 'core.tests.utils.sample_tag', 'sample_tag', ([], {'user': 'user2', 'name': '"""test tag 2"""'}), "(user=user2, name='test tag 2')\n", (1939, 1970), False, 'from core.tests.utils import sample_tag, sample_user\n'), ((2438, 2469), 'recipe.models.Tag.objects.get', 'Tag.objects.get', ([], {}), '(**self.payload)\n', (2453, 2469), False, 'from recipe.models import Tag\n'), ((1688, 1705), 'recipe.models.Tag.objects.all', 'Tag.objects.all', ([], {}), '()\n', (1703, 1705), False, 'from recipe.models import Tag\n')] |
from sfsidb import load as sload
from sfsidb import toolkit
from sfsidb import checking_tools as ct
from sfsidb import sensor_file_reader as sfr
from tests.conftest import TEST_DATA_DIR
def test_get_depth_from_sensor_code():
sensor_ffp = TEST_DATA_DIR + "test-sensor-file.json"
si = sfr.read_json_sensor_file(sensor_ffp)
mtype = "ACC"
sensor_number = 2
code = sload.get_sensor_code_by_number(si, mtype, sensor_number)
assert code == "ACCX-NFF-S-M"
print(code)
depth = toolkit.get_depth_by_code(si, code)
assert depth == 0.0
code = "ACCX-UB2-L2C-M" # number = 4
depth = toolkit.get_depth_by_code(si, code)
assert ct.isclose(depth, 63.6)
def test_old_style_sensor_code_file():
sensor_ffp = TEST_DATA_DIR + "test-old-sensor-file.json"
si = sfr.read_json_sensor_file(sensor_ffp)
sensor_code = "ACCX-NFF-L2C-M"
depth = toolkit.get_depth_by_code(si, sensor_code)
assert ct.isclose(depth, 63.6)
if __name__ == '__main__':
test_old_style_sensor_code_file() | [
"sfsidb.toolkit.get_depth_by_code",
"sfsidb.load.get_sensor_code_by_number",
"sfsidb.checking_tools.isclose",
"sfsidb.sensor_file_reader.read_json_sensor_file"
] | [((294, 331), 'sfsidb.sensor_file_reader.read_json_sensor_file', 'sfr.read_json_sensor_file', (['sensor_ffp'], {}), '(sensor_ffp)\n', (319, 331), True, 'from sfsidb import sensor_file_reader as sfr\n'), ((383, 440), 'sfsidb.load.get_sensor_code_by_number', 'sload.get_sensor_code_by_number', (['si', 'mtype', 'sensor_number'], {}), '(si, mtype, sensor_number)\n', (414, 440), True, 'from sfsidb import load as sload\n'), ((503, 538), 'sfsidb.toolkit.get_depth_by_code', 'toolkit.get_depth_by_code', (['si', 'code'], {}), '(si, code)\n', (528, 538), False, 'from sfsidb import toolkit\n'), ((618, 653), 'sfsidb.toolkit.get_depth_by_code', 'toolkit.get_depth_by_code', (['si', 'code'], {}), '(si, code)\n', (643, 653), False, 'from sfsidb import toolkit\n'), ((665, 688), 'sfsidb.checking_tools.isclose', 'ct.isclose', (['depth', '(63.6)'], {}), '(depth, 63.6)\n', (675, 688), True, 'from sfsidb import checking_tools as ct\n'), ((800, 837), 'sfsidb.sensor_file_reader.read_json_sensor_file', 'sfr.read_json_sensor_file', (['sensor_ffp'], {}), '(sensor_ffp)\n', (825, 837), True, 'from sfsidb import sensor_file_reader as sfr\n'), ((885, 927), 'sfsidb.toolkit.get_depth_by_code', 'toolkit.get_depth_by_code', (['si', 'sensor_code'], {}), '(si, sensor_code)\n', (910, 927), False, 'from sfsidb import toolkit\n'), ((939, 962), 'sfsidb.checking_tools.isclose', 'ct.isclose', (['depth', '(63.6)'], {}), '(depth, 63.6)\n', (949, 962), True, 'from sfsidb import checking_tools as ct\n')] |
# Setup procedures -- WIP
import os
import re
import arcpy
arcpy.env.workspace = "in_memory"
# TODO: out_gdb = "//cityfiles/DEVServices/WallyG/projects/NhoodProfiles/nhoods/data/NhoodAmenities.gdb/MtStatePlane"
# DATA PROCESSING
# Nhood_buffers:
arcpy.Buffer_analysis("Nhoods", "nhood_buffers",
buffer_distance_or_field="100 Feet",
line_side="FULL", line_end_type="ROUND",
dissolve_option="LIST", dissolve_field="Name",
method="PLANAR")
# Parks:
parks = os.path.join(
r"\\cityfiles\Shared\PARKS AND RECREATION SHARED\GIS Data",
r"Parks Data.gdb\Parks")
arcpy.FeatureClassToFeatureClass_conversion(parks, "in_memory", "mem_parks")
# Delete Parks Fields
arcpy.DeleteField_management("mem_parks", drop_field="Reference;Rec_Date;Doc_Links;Subtype;Ownership;Origin;Maintenance;Platted_Size;Maint_Level;Status;Assessors_Parcel_No;Acres;Dev_Status;Owner_Type;Maint_Responsibility;Shape_Length;Shape_Area")
# COMMON AREAS
CAMA = r"W:\DATA\CAMA\Missoula\MissoulaOwnerParcel_shp\MissoulaOwnerParcel_shp.shp"
arcpy.Select_analysis(CAMA, "in_memory/mem_commons", '''"LegalDescr" LIKE
\'%COMMON%\'''')
# make new field "CAName"
arcpy.AddField_management("mem_commons", "CAName", "TEXT", "", "", 50)
with arcpy.da.UpdateCursor("mem_commons", ["LegalDescr", "CAName"]) as cur:
for row in cur:
row[1] = re.split("\W\s", row[0])[0].strip().title()
cur.updateRow(row)
arcpy.Dissolve_management(in_features="mem_commons", out_feature_class="in_memory/mem_commons_Diss", dissolve_field="CAName", statistics_fields="", multi_part="SINGLE_PART", unsplit_lines="DISSOLVE_LINES")
# Merge
| [
"re.split",
"arcpy.Dissolve_management",
"arcpy.DeleteField_management",
"arcpy.AddField_management",
"arcpy.Select_analysis",
"arcpy.FeatureClassToFeatureClass_conversion",
"os.path.join",
"arcpy.Buffer_analysis",
"arcpy.da.UpdateCursor"
] | [((251, 451), 'arcpy.Buffer_analysis', 'arcpy.Buffer_analysis', (['"""Nhoods"""', '"""nhood_buffers"""'], {'buffer_distance_or_field': '"""100 Feet"""', 'line_side': '"""FULL"""', 'line_end_type': '"""ROUND"""', 'dissolve_option': '"""LIST"""', 'dissolve_field': '"""Name"""', 'method': '"""PLANAR"""'}), "('Nhoods', 'nhood_buffers', buffer_distance_or_field=\n '100 Feet', line_side='FULL', line_end_type='ROUND', dissolve_option=\n 'LIST', dissolve_field='Name', method='PLANAR')\n", (272, 451), False, 'import arcpy\n'), ((549, 654), 'os.path.join', 'os.path.join', (['"""\\\\\\\\cityfiles\\\\Shared\\\\PARKS AND RECREATION SHARED\\\\GIS Data"""', '"""Parks Data.gdb\\\\Parks"""'], {}), "('\\\\\\\\cityfiles\\\\Shared\\\\PARKS AND RECREATION SHARED\\\\GIS Data',\n 'Parks Data.gdb\\\\Parks')\n", (561, 654), False, 'import os\n'), ((657, 733), 'arcpy.FeatureClassToFeatureClass_conversion', 'arcpy.FeatureClassToFeatureClass_conversion', (['parks', '"""in_memory"""', '"""mem_parks"""'], {}), "(parks, 'in_memory', 'mem_parks')\n", (700, 733), False, 'import arcpy\n'), ((757, 1013), 'arcpy.DeleteField_management', 'arcpy.DeleteField_management', (['"""mem_parks"""'], {'drop_field': '"""Reference;Rec_Date;Doc_Links;Subtype;Ownership;Origin;Maintenance;Platted_Size;Maint_Level;Status;Assessors_Parcel_No;Acres;Dev_Status;Owner_Type;Maint_Responsibility;Shape_Length;Shape_Area"""'}), "('mem_parks', drop_field=\n 'Reference;Rec_Date;Doc_Links;Subtype;Ownership;Origin;Maintenance;Platted_Size;Maint_Level;Status;Assessors_Parcel_No;Acres;Dev_Status;Owner_Type;Maint_Responsibility;Shape_Length;Shape_Area'\n )\n", (785, 1013), False, 'import arcpy\n'), ((1107, 1199), 'arcpy.Select_analysis', 'arcpy.Select_analysis', (['CAMA', '"""in_memory/mem_commons"""', '""""LegalDescr" LIKE\n\'%COMMON%\'"""'], {}), '(CAMA, \'in_memory/mem_commons\',\n """"LegalDescr" LIKE\n\'%COMMON%\'""")\n', (1128, 1199), False, 'import arcpy\n'), ((1225, 1295), 'arcpy.AddField_management', 'arcpy.AddField_management', (['"""mem_commons"""', '"""CAName"""', '"""TEXT"""', '""""""', '""""""', '(50)'], {}), "('mem_commons', 'CAName', 'TEXT', '', '', 50)\n", (1250, 1295), False, 'import arcpy\n'), ((1483, 1702), 'arcpy.Dissolve_management', 'arcpy.Dissolve_management', ([], {'in_features': '"""mem_commons"""', 'out_feature_class': '"""in_memory/mem_commons_Diss"""', 'dissolve_field': '"""CAName"""', 'statistics_fields': '""""""', 'multi_part': '"""SINGLE_PART"""', 'unsplit_lines': '"""DISSOLVE_LINES"""'}), "(in_features='mem_commons', out_feature_class=\n 'in_memory/mem_commons_Diss', dissolve_field='CAName',\n statistics_fields='', multi_part='SINGLE_PART', unsplit_lines=\n 'DISSOLVE_LINES')\n", (1508, 1702), False, 'import arcpy\n'), ((1302, 1364), 'arcpy.da.UpdateCursor', 'arcpy.da.UpdateCursor', (['"""mem_commons"""', "['LegalDescr', 'CAName']"], {}), "('mem_commons', ['LegalDescr', 'CAName'])\n", (1323, 1364), False, 'import arcpy\n'), ((1410, 1436), 're.split', 're.split', (['"""\\\\W\\\\s"""', 'row[0]'], {}), "('\\\\W\\\\s', row[0])\n", (1418, 1436), False, 'import re\n')] |
from ptrlib import *
import re
import time
def create(name):
sock.recvuntil("> ")
sock.sendline("1")
sock.sendline(name)
def add(index, value):
sock.recvuntil("> ")
sock.sendline("2")
sock.sendline(str(index))
sock.sendline(str(value))
def view(index, pos):
sock.recvuntil("> ")
sock.sendline("3")
sock.sendline(str(index))
sock.recvuntil("into list:\n")
sock.sendline(str(pos))
line = sock.recvline()
r = re.findall(b"(.+)\[(.+)\] = (.+)", line)
w = int(r[0][2])
if w < 0:
w = (0xffffffff ^ (- w - 1))
return r[0][0], int(r[0][1]), w
def dup(index, name):
sock.recvuntil("> ")
sock.sendline("4")
sock.sendline(str(index))
sock.sendline(name)
def remove(index):
sock.recvuntil("> ")
sock.sendline("5")
sock.sendline(str(index))
libc = ELF("./libc-2.27.so")
sock = Process("./babylist")#Socket("localhost", 4001)
#sock = Socket("challenges3.fbctf.com", 1343)
main_arena = 0x3ebc40 + 0x60
one_gadget = 0x10a38c
create("0") # 0
for i in range(0x50 // 4):
add(0, 0x1111)
dup(0, "1") # 1
for i in range(0x50 // 4):
add(1, 0x2222)
create("libc leak") # 2
remove(1)
# fill up tcache for 0x21
for i in range(8):
create(str(i)) # 3-9
remove(1)
for i in range(3, 9):
remove(i)
remove(2)
# libc leak
addr_main_arena = (view(0, 1)[2] << 32) | view(0, 0)[2]
libc_base = addr_main_arena - main_arena
logger.info("libc base = " + hex(libc_base))
# double free
create("1") # 1
for i in range(8):
add(1, 0xcafe)
dup(1, "PON") # 2
for i in range(8):
add(1, i + 4)
add(2, i + 4)
# TCache Poisoning
target = libc_base + libc.symbol('__free_hook') - 8
create("evil") # 3
add(3, target & 0xffffffff)
add(3, target >> 32)
for i in range(3):
add(3, 0xdead)
#addr_one_gadget = libc_base + one_gadget
addr_system = libc_base + libc.symbol("system")
create("dummy") # 4
for i in range(5):
add(4, 0xbeef)
create("free hook") # 5
add(5, u32("/bin"))
add(5, u32("/sh\x00"))
add(5, addr_system & 0xffffffff)
add(5, addr_system >> 32)
add(5, 0)
sock.interactive()
| [
"re.findall"
] | [((465, 507), 're.findall', 're.findall', (["b'(.+)\\\\[(.+)\\\\] = (.+)'", 'line'], {}), "(b'(.+)\\\\[(.+)\\\\] = (.+)', line)\n", (475, 507), False, 'import re\n')] |
# coding: utf-8
"""
PKS
PKS API # noqa: E501
OpenAPI spec version: 1.1.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
# python 2 and python 3 compatibility library
import six
from container_service_extension.lib.pksclient.api_client import ApiClient
class ProfileApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def add_compute_profile(self, body, **kwargs): # noqa: E501
"""Create a new compute profile # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_compute_profile(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param ComputeProfileRequest body: Compute profile info (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.add_compute_profile_with_http_info(body, **kwargs) # noqa: E501
else:
(data) = self.add_compute_profile_with_http_info(body, **kwargs) # noqa: E501
return data
def add_compute_profile_with_http_info(self, body, **kwargs): # noqa: E501
"""Create a new compute profile # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_compute_profile_with_http_info(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param ComputeProfileRequest body: Compute profile info (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method add_compute_profile" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params or
params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `add_compute_profile`") # noqa: E501
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['basicAuth', 'uaa'] # noqa: E501
return self.api_client.call_api(
'/compute-profiles', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def add_kubernetes_profile(self, body, **kwargs): # noqa: E501
"""Create a new kubernetes profile # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_kubernetes_profile(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param KubernetesProfileRequest body: Kubernetes profile info (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.add_kubernetes_profile_with_http_info(body, **kwargs) # noqa: E501
else:
(data) = self.add_kubernetes_profile_with_http_info(body, **kwargs) # noqa: E501
return data
def add_kubernetes_profile_with_http_info(self, body, **kwargs): # noqa: E501
"""Create a new kubernetes profile # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_kubernetes_profile_with_http_info(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param KubernetesProfileRequest body: Kubernetes profile info (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method add_kubernetes_profile" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params or
params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `add_kubernetes_profile`") # noqa: E501
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['basicAuth', 'uaa'] # noqa: E501
return self.api_client.call_api(
'/kubernetes-profiles', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def add_network_profile(self, body, **kwargs): # noqa: E501
"""Create a new network profile # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_network_profile(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param NetworkProfileRequest body: Network profile info (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.add_network_profile_with_http_info(body, **kwargs) # noqa: E501
else:
(data) = self.add_network_profile_with_http_info(body, **kwargs) # noqa: E501
return data
def add_network_profile_with_http_info(self, body, **kwargs): # noqa: E501
"""Create a new network profile # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_network_profile_with_http_info(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param NetworkProfileRequest body: Network profile info (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method add_network_profile" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params or
params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `add_network_profile`") # noqa: E501
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['basicAuth', 'uaa'] # noqa: E501
return self.api_client.call_api(
'/network-profiles', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_compute_profile(self, profile_name, **kwargs): # noqa: E501
"""delete_compute_profile # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_compute_profile(profile_name, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str profile_name: The compute profile name (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.delete_compute_profile_with_http_info(profile_name, **kwargs) # noqa: E501
else:
(data) = self.delete_compute_profile_with_http_info(profile_name, **kwargs) # noqa: E501
return data
def delete_compute_profile_with_http_info(self, profile_name, **kwargs): # noqa: E501
"""delete_compute_profile # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_compute_profile_with_http_info(profile_name, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str profile_name: The compute profile name (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['profile_name'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_compute_profile" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'profile_name' is set
if ('profile_name' not in params or
params['profile_name'] is None):
raise ValueError("Missing the required parameter `profile_name` when calling `delete_compute_profile`") # noqa: E501
collection_formats = {}
path_params = {}
if 'profile_name' in params:
path_params['profileName'] = params['profile_name'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['basicAuth', 'uaa'] # noqa: E501
return self.api_client.call_api(
'/compute-profiles/{profileName}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_kubernetes_profile(self, name, **kwargs): # noqa: E501
"""delete_kubernetes_profile # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_kubernetes_profile(name, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: The kubernetes profile name (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.delete_kubernetes_profile_with_http_info(name, **kwargs) # noqa: E501
else:
(data) = self.delete_kubernetes_profile_with_http_info(name, **kwargs) # noqa: E501
return data
def delete_kubernetes_profile_with_http_info(self, name, **kwargs): # noqa: E501
"""delete_kubernetes_profile # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_kubernetes_profile_with_http_info(name, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: The kubernetes profile name (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_kubernetes_profile" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params or
params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `delete_kubernetes_profile`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['basicAuth', 'uaa'] # noqa: E501
return self.api_client.call_api(
'/kubernetes-profiles/{name}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_network_profile(self, profile_name, **kwargs): # noqa: E501
"""delete_network_profile # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_network_profile(profile_name, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str profile_name: The network profile name (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.delete_network_profile_with_http_info(profile_name, **kwargs) # noqa: E501
else:
(data) = self.delete_network_profile_with_http_info(profile_name, **kwargs) # noqa: E501
return data
def delete_network_profile_with_http_info(self, profile_name, **kwargs): # noqa: E501
"""delete_network_profile # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_network_profile_with_http_info(profile_name, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str profile_name: The network profile name (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['profile_name'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_network_profile" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'profile_name' is set
if ('profile_name' not in params or
params['profile_name'] is None):
raise ValueError("Missing the required parameter `profile_name` when calling `delete_network_profile`") # noqa: E501
collection_formats = {}
path_params = {}
if 'profile_name' in params:
path_params['profileName'] = params['profile_name'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['basicAuth', 'uaa'] # noqa: E501
return self.api_client.call_api(
'/network-profiles/{profileName}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_compute_profile(self, profile_name, **kwargs): # noqa: E501
"""get_compute_profile # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_compute_profile(profile_name, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str profile_name: The compute profile name (required)
:return: ComputeProfile
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_compute_profile_with_http_info(profile_name, **kwargs) # noqa: E501
else:
(data) = self.get_compute_profile_with_http_info(profile_name, **kwargs) # noqa: E501
return data
def get_compute_profile_with_http_info(self, profile_name, **kwargs): # noqa: E501
"""get_compute_profile # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_compute_profile_with_http_info(profile_name, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str profile_name: The compute profile name (required)
:return: ComputeProfile
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['profile_name'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_compute_profile" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'profile_name' is set
if ('profile_name' not in params or
params['profile_name'] is None):
raise ValueError("Missing the required parameter `profile_name` when calling `get_compute_profile`") # noqa: E501
collection_formats = {}
path_params = {}
if 'profile_name' in params:
path_params['profileName'] = params['profile_name'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['basicAuth', 'uaa'] # noqa: E501
return self.api_client.call_api(
'/compute-profiles/{profileName}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='ComputeProfile', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_kubernetes_profile(self, name, **kwargs): # noqa: E501
"""get_kubernetes_profile # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_kubernetes_profile(name, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: The kubernetes profile name (required)
:return: KubernetesProfile
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_kubernetes_profile_with_http_info(name, **kwargs) # noqa: E501
else:
(data) = self.get_kubernetes_profile_with_http_info(name, **kwargs) # noqa: E501
return data
def get_kubernetes_profile_with_http_info(self, name, **kwargs): # noqa: E501
"""get_kubernetes_profile # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_kubernetes_profile_with_http_info(name, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: The kubernetes profile name (required)
:return: KubernetesProfile
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_kubernetes_profile" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params or
params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `get_kubernetes_profile`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['basicAuth', 'uaa'] # noqa: E501
return self.api_client.call_api(
'/kubernetes-profiles/{name}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='KubernetesProfile', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_network_profile(self, profile_name, **kwargs): # noqa: E501
"""get_network_profile # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_network_profile(profile_name, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str profile_name: The network profile name (required)
:return: NetworkProfile
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_network_profile_with_http_info(profile_name, **kwargs) # noqa: E501
else:
(data) = self.get_network_profile_with_http_info(profile_name, **kwargs) # noqa: E501
return data
def get_network_profile_with_http_info(self, profile_name, **kwargs): # noqa: E501
"""get_network_profile # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_network_profile_with_http_info(profile_name, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str profile_name: The network profile name (required)
:return: NetworkProfile
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['profile_name'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_network_profile" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'profile_name' is set
if ('profile_name' not in params or
params['profile_name'] is None):
raise ValueError("Missing the required parameter `profile_name` when calling `get_network_profile`") # noqa: E501
collection_formats = {}
path_params = {}
if 'profile_name' in params:
path_params['profileName'] = params['profile_name'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['basicAuth', 'uaa'] # noqa: E501
return self.api_client.call_api(
'/network-profiles/{profileName}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='NetworkProfile', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def list_compute_profiles(self, **kwargs): # noqa: E501
"""List all compute profiles # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_compute_profiles(async_req=True)
>>> result = thread.get()
:param async_req bool
:return: list[ComputeProfile]
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.list_compute_profiles_with_http_info(**kwargs) # noqa: E501
else:
(data) = self.list_compute_profiles_with_http_info(**kwargs) # noqa: E501
return data
def list_compute_profiles_with_http_info(self, **kwargs): # noqa: E501
"""List all compute profiles # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_compute_profiles_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:return: list[ComputeProfile]
If the method is called asynchronously,
returns the request thread.
"""
all_params = [] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_compute_profiles" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['basicAuth', 'uaa'] # noqa: E501
return self.api_client.call_api(
'/compute-profiles', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='list[ComputeProfile]', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def list_kubernetes_profiles(self, **kwargs): # noqa: E501
"""List all kubernetes profiles # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_kubernetes_profiles(async_req=True)
>>> result = thread.get()
:param async_req bool
:return: list[KubernetesProfile]
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.list_kubernetes_profiles_with_http_info(**kwargs) # noqa: E501
else:
(data) = self.list_kubernetes_profiles_with_http_info(**kwargs) # noqa: E501
return data
def list_kubernetes_profiles_with_http_info(self, **kwargs): # noqa: E501
"""List all kubernetes profiles # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_kubernetes_profiles_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:return: list[KubernetesProfile]
If the method is called asynchronously,
returns the request thread.
"""
all_params = [] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_kubernetes_profiles" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['basicAuth', 'uaa'] # noqa: E501
return self.api_client.call_api(
'/kubernetes-profiles', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='list[KubernetesProfile]', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def list_network_profiles(self, **kwargs): # noqa: E501
"""List all network profiles # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_network_profiles(async_req=True)
>>> result = thread.get()
:param async_req bool
:return: list[NetworkProfile]
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.list_network_profiles_with_http_info(**kwargs) # noqa: E501
else:
(data) = self.list_network_profiles_with_http_info(**kwargs) # noqa: E501
return data
def list_network_profiles_with_http_info(self, **kwargs): # noqa: E501
"""List all network profiles # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_network_profiles_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:return: list[NetworkProfile]
If the method is called asynchronously,
returns the request thread.
"""
all_params = [] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_network_profiles" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['basicAuth', 'uaa'] # noqa: E501
return self.api_client.call_api(
'/network-profiles', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='list[NetworkProfile]', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
| [
"six.iteritems",
"container_service_extension.lib.pksclient.api_client.ApiClient"
] | [((2560, 2591), 'six.iteritems', 'six.iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (2573, 2591), False, 'import six\n'), ((6353, 6384), 'six.iteritems', 'six.iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (6366, 6384), False, 'import six\n'), ((10119, 10150), 'six.iteritems', 'six.iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (10132, 10150), False, 'import six\n'), ((13880, 13911), 'six.iteritems', 'six.iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (13893, 13911), False, 'import six\n'), ((17514, 17545), 'six.iteritems', 'six.iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (17527, 17545), False, 'import six\n'), ((21137, 21168), 'six.iteritems', 'six.iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (21150, 21168), False, 'import six\n'), ((24809, 24840), 'six.iteritems', 'six.iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (24822, 24840), False, 'import six\n'), ((28448, 28479), 'six.iteritems', 'six.iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (28461, 28479), False, 'import six\n'), ((32073, 32104), 'six.iteritems', 'six.iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (32086, 32104), False, 'import six\n'), ((35548, 35579), 'six.iteritems', 'six.iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (35561, 35579), False, 'import six\n'), ((38650, 38681), 'six.iteritems', 'six.iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (38663, 38681), False, 'import six\n'), ((41731, 41762), 'six.iteritems', 'six.iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (41744, 41762), False, 'import six\n'), ((650, 661), 'container_service_extension.lib.pksclient.api_client.ApiClient', 'ApiClient', ([], {}), '()\n', (659, 661), False, 'from container_service_extension.lib.pksclient.api_client import ApiClient\n')] |
import os
import pytest
import pandas as pd
import numpy as np
from shclassify.utils import (inverse_logit,
choose_from_multinomial_probs,
choose_from_binary_probs)
def test_inverse_logit():
assert inverse_logit(0) == 0.5
def test_choose_from_multinomial_probs():
n_obs = 3
classes = ['a', 'b', 'c']
df = pd.DataFrame(
np.random.uniform(size=(n_obs,len(classes))), columns=classes
)
classes = choose_from_multinomial_probs(df)
assert type(classes) is pd.DataFrame
assert classes.shape == (n_obs, 1)
assert classes.columns == ['class']
def in_classes(x, classes=classes):
x in classes
assert classes['class'].apply(in_classes).all()
def test_choose_from_multinomial_probs_with_bad_input():
n_obs = 3
classes = ['a']
df = pd.DataFrame(
np.random.uniform(size=(n_obs,len(classes))), columns=classes
)
with pytest.raises(ValueError) as e:
choose_from_multinomial_probs(df)
assert 'Data frame must have more than 1 column' in str(e.value)
def test_choose_from_binary_probs():
n_obs = 3
df = pd.DataFrame(
np.random.uniform(size=(n_obs,1))
)
classes = choose_from_binary_probs(df, 'true', 'false')
assert type(classes) is pd.DataFrame
assert classes.shape == (n_obs, 1)
assert classes.applymap(lambda x: x in ['true', 'false']).all()[0]
assert classes.columns == ['class']
def test_choose_from_binary_probs_with_bad_shape():
n_obs = 3
classes = ['a', 'b']
df = pd.DataFrame(
np.random.uniform(size=(n_obs,len(classes))), columns=classes
)
with pytest.raises(ValueError) as e:
choose_from_binary_probs(df, 'true', 'false')
assert 'Data frame must have 1 column' == str(e.value)
def test_choose_from_binary_probs_with_bad_args():
n_obs = 3
df = pd.DataFrame(
np.random.uniform(size=(n_obs,1))
)
with pytest.raises(ValueError) as e:
classes = choose_from_binary_probs(df, 'true', 'true')
assert 'Class names for true and false results must differ' == str(e.value)
with pytest.raises(ValueError) as e:
classes = choose_from_binary_probs(df, 'true', 'false', threshold=50)
assert 'Threshold must be between 0 and 1' == str(e.value)
| [
"shclassify.utils.choose_from_multinomial_probs",
"shclassify.utils.inverse_logit",
"pytest.raises",
"numpy.random.uniform",
"shclassify.utils.choose_from_binary_probs"
] | [((489, 522), 'shclassify.utils.choose_from_multinomial_probs', 'choose_from_multinomial_probs', (['df'], {}), '(df)\n', (518, 522), False, 'from shclassify.utils import inverse_logit, choose_from_multinomial_probs, choose_from_binary_probs\n'), ((1242, 1287), 'shclassify.utils.choose_from_binary_probs', 'choose_from_binary_probs', (['df', '"""true"""', '"""false"""'], {}), "(df, 'true', 'false')\n", (1266, 1287), False, 'from shclassify.utils import inverse_logit, choose_from_multinomial_probs, choose_from_binary_probs\n'), ((264, 280), 'shclassify.utils.inverse_logit', 'inverse_logit', (['(0)'], {}), '(0)\n', (277, 280), False, 'from shclassify.utils import inverse_logit, choose_from_multinomial_probs, choose_from_binary_probs\n'), ((960, 985), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (973, 985), False, 'import pytest\n'), ((1000, 1033), 'shclassify.utils.choose_from_multinomial_probs', 'choose_from_multinomial_probs', (['df'], {}), '(df)\n', (1029, 1033), False, 'from shclassify.utils import inverse_logit, choose_from_multinomial_probs, choose_from_binary_probs\n'), ((1187, 1221), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': '(n_obs, 1)'}), '(size=(n_obs, 1))\n', (1204, 1221), True, 'import numpy as np\n'), ((1681, 1706), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1694, 1706), False, 'import pytest\n'), ((1721, 1766), 'shclassify.utils.choose_from_binary_probs', 'choose_from_binary_probs', (['df', '"""true"""', '"""false"""'], {}), "(df, 'true', 'false')\n", (1745, 1766), False, 'from shclassify.utils import inverse_logit, choose_from_multinomial_probs, choose_from_binary_probs\n'), ((1924, 1958), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': '(n_obs, 1)'}), '(size=(n_obs, 1))\n', (1941, 1958), True, 'import numpy as np\n'), ((1974, 1999), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1987, 1999), False, 'import pytest\n'), ((2024, 2068), 'shclassify.utils.choose_from_binary_probs', 'choose_from_binary_probs', (['df', '"""true"""', '"""true"""'], {}), "(df, 'true', 'true')\n", (2048, 2068), False, 'from shclassify.utils import inverse_logit, choose_from_multinomial_probs, choose_from_binary_probs\n'), ((2160, 2185), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (2173, 2185), False, 'import pytest\n'), ((2210, 2269), 'shclassify.utils.choose_from_binary_probs', 'choose_from_binary_probs', (['df', '"""true"""', '"""false"""'], {'threshold': '(50)'}), "(df, 'true', 'false', threshold=50)\n", (2234, 2269), False, 'from shclassify.utils import inverse_logit, choose_from_multinomial_probs, choose_from_binary_probs\n')] |
"""Module used polling SNMP enabled targets."""
import sys
# PIP3 imports
import easysnmp
from easysnmp import exceptions
# Import Pattoo libraries
from pattoo_shared import log
from pattoo_shared.variables import DataPoint
from pattoo_shared.constants import (
DATA_INT, DATA_COUNT64, DATA_COUNT, DATA_STRING, DATA_NONE)
from pattoo_agents.snmp import oid as class_oid
from pattoo_agents.snmp.variables import SNMPVariable
class SNMP():
"""Class to interact with targets using SNMP."""
def __init__(self, snmpvariable):
"""Initialize the class.
Args:
snmpvariable: SNMPVariable object
Returns:
None
"""
# Initialize key variables
self._snmp_ip_target = snmpvariable.ip_target
self._snmp_version = snmpvariable.snmpauth.version
self._snmpvariable = snmpvariable
def contactable(self):
"""Check if target is contactable.
Args:
target_id: Target ID
Returns:
_contactable: True if a contactable
"""
# Define key variables
_contactable = False
result = None
# Get target data
target_name = self._snmp_ip_target
# Try to reach target
try:
# If we can poll the SNMP sysObjectID,
# then the target is contactable
result = self.sysobjectid(check_reachability=True)
if bool(result) is True:
_contactable = True
except Exception as exception_error:
# Not contactable
_contactable = False
# Log a message
log_message = ('''\
Unable to access target {} via SNMP. Make sure target is contactable and \
that the database\'s SNMP parameters for the target are correct. Fix, repeat \
your command AND make sure you set --.valid=True. Error: {}\
'''.format(target_name, exception_error))
log.log2see(51035, log_message)
except:
# Not contactable
_contactable = False
# Log a message
log_message = (
'Unexpected SNMP error for target {}'
''.format(target_name))
log.log2see(51036, log_message)
# Return
return _contactable
def sysobjectid(self, check_reachability=False):
"""Get the sysObjectID of the target.
Args:
check_reachability:
Set if testing for connectivity. Some session
errors are ignored so that a null result is returned
Returns:
object_id: sysObjectID value
"""
# Initialize key variables
oid = '.1.3.6.1.2.1.1.2.0'
object_id = None
# Get sysObjectID
results = self.get(oid, check_reachability=check_reachability)
if bool(results) is True:
object_id = results
# Return
return object_id
def oid_exists(self, oid_to_get, context_name=''):
"""Determine existence of OID on target.
Args:
oid_to_get: OID to get
context_name: Set the contextName used for SNMPv3 messages.
The default contextName is the empty string "". Overrides the
defContext token in the snmp.conf file.
Returns:
validity: True if exists
"""
# Initialize key variables
validity = False
# Process
(_, validity, result) = self.query(
oid_to_get,
get=True,
check_reachability=True, context_name=context_name,
check_existence=True)
# If we get no result, then override validity
if bool(result) is False:
validity = False
else:
validity = True
# Return
return validity
def branch_exists(self, oid_to_get, context_name=''):
"""Determine existence of OID on target.
Args:
oid_to_get: OID to get
context_name: Set the contextName used for SNMPv3 messages.
The default contextName is the empty string "". Overrides the
defContext token in the snmp.conf file.
Returns:
validity: True if exists
"""
# Initialize key variables
validity = False
# Process
(_, validity, results) = self.query(
oid_to_get, get=False,
check_reachability=True,
context_name=context_name,
check_existence=True)
# If we get no result, then override validity
if bool(results) is False:
validity = False
else:
validity = True
# Return
return validity
def walk(
self, oid_to_get, check_reachability=True,
check_existence=False, context_name=''):
"""Do an SNMPwalk.
Args:
oid_to_get: OID to walk
check_reachability:
Set if testing for connectivity. Some session
errors are ignored so that a null result is returned
check_existence:
Set if checking for the existence of the OID
context_name: Set the contextName used for SNMPv3 messages.
The default contextName is the empty string "". Overrides the
defContext token in the snmp.conf file.
Returns:
result: Dictionary of tuples (OID, value)
"""
(_, _, result) = self.query(
oid_to_get, get=False,
check_reachability=check_reachability,
check_existence=check_existence,
context_name=context_name)
return result
def get(
self, oid_to_get, check_reachability=True,
check_existence=False, context_name=''):
"""Do an SNMPget.
Args:
oid_to_get: OID to get
check_reachability:
Set if testing for connectivity. Some session
errors are ignored so that a null result is returned
check_existence:
Set if checking for the existence of the OID
context_name: Set the contextName used for SNMPv3 messages.
The default contextName is the empty string "". Overrides the
defContext token in the snmp.conf file.
Returns:
Dictionary of tuples (OID, value)
"""
(_, _, _result) = self.query(
oid_to_get, get=True,
check_reachability=check_reachability,
check_existence=check_existence,
context_name=context_name)
if bool(_result) is True:
result = _result
else:
result = None
return result
def query(
self, oid_to_get, get=False, check_reachability=True,
check_existence=False, context_name=''):
"""Do an SNMP query.
Args:
oid_to_get: OID to walk
get: Flag determining whether to do a GET or WALK
check_reachability:
Set if testing for connectivity. Some session
errors are ignored so that a null result is returned
check_existence:
Set if checking for the existence of the OID
context_name: Set the contextName used for SNMPv3 messages.
The default contextName is the empty string "". Overrides the
defContext token in the snmp.conf file.
Returns:
Dictionary of tuples (OID, value)
"""
# Initialize variables
_contactable = True
exists = True
results = []
# Create OID string object
oid_string = class_oid.OIDstring(oid_to_get)
# Check if OID is valid
valid_format = oid_string.valid_format()
if valid_format is False:
log_message = ('OID {} has an invalid format'.format(oid_to_get))
log.log2die(51449, log_message)
# Create SNMP session
session = _Session(
self._snmpvariable, context_name=context_name).session
# Create failure log message
try_log_message = (
'Error occurred during SNMPget {}, SNMPwalk {} query against '
'target {} OID {} for context "{}"'
''.format(
get, not get, self._snmp_ip_target,
oid_to_get, context_name))
# Fill the results object by getting OID data
try:
# Get the data
if get is True:
results = [session.get(oid_to_get)]
else:
if self._snmp_version != 1:
# Bulkwalk for SNMPv2 and SNMPv3
results = session.bulkwalk(
oid_to_get, non_repeaters=0, max_repetitions=25)
else:
# Bulkwalk not supported in SNMPv1
results = session.walk(oid_to_get)
# Crash on error, return blank results if doing certain types of
# connectivity checks
except (
exceptions.EasySNMPConnectionError,
exceptions.EasySNMPTimeoutError,
exceptions.EasySNMPUnknownObjectIDError,
exceptions.EasySNMPNoSuchNameError,
exceptions.EasySNMPNoSuchObjectError,
exceptions.EasySNMPNoSuchInstanceError,
exceptions.EasySNMPUndeterminedTypeError) as exception_error:
# Update the error message
try_log_message = ("""\
{}: [{}, {}, {}]""".format(try_log_message, sys.exc_info()[0],
sys.exc_info()[1], sys.exc_info()[2]))
# Process easysnmp errors
(_contactable, exists) = _process_error(
try_log_message, exception_error,
check_reachability, check_existence)
except SystemError as exception_error:
# Update the error message
try_log_message = ("""\
{}: [{}, {}, {}]""".format(try_log_message, sys.exc_info()[0],
sys.exc_info()[1], sys.exc_info()[2]))
# Process easysnmp errors
(_contactable, exists) = _process_error(
try_log_message, exception_error,
check_reachability, check_existence, system_error=True)
except:
log_message = (
'Unexpected error: {}, {}, {}, {}'
''.format(
sys.exc_info()[0],
sys.exc_info()[1],
sys.exc_info()[2],
self._snmp_ip_target))
log.log2die(51029, log_message)
# Format results
values = _convert_results(results)
# Return
return (_contactable, exists, values)
class _Session():
"""Class to create an SNMP session with a target."""
def __init__(self, snmpvariable, context_name=''):
"""Initialize the class.
Args:
snmpvariable: SNMPVariable object
context_name: Name of context
Returns:
session: SNMP session
"""
# Initialize key variables
self._context_name = context_name
self._snmp_ip_target = snmpvariable.ip_target
self._snmp_port = snmpvariable.snmpauth.port
self._snmp_version = snmpvariable.snmpauth.version
self._snmp_community = snmpvariable.snmpauth.community
self._snmp_secname = snmpvariable.snmpauth.secname
self._snmp_authprotocol = snmpvariable.snmpauth.authprotocol
self._snmp_authpassword = snmpvariable.snmpauth.authpassword
self._snmp_privprotocol = snmpvariable.snmpauth.privprotocol
self._snmp_privpassword = snmpvariable.snmpauth.privpassword
# Fail if snmpvariable dictionary is empty
if self._snmp_version is None:
log_message = (
'SNMP version is "None". Non existent host? - {}'
''.format(self._snmp_ip_target))
log.log2die(51223, log_message)
# Fail if snmpvariable dictionary is empty
if bool(snmpvariable) is False:
log_message = ('SNMP parameters provided are blank. '
'Non existent host?')
log.log2die(51215, log_message)
# Fail if invalid snmpvariable
if isinstance(snmpvariable, SNMPVariable) is False:
log_message = ('Invalid SNMPVariable parameters')
log.log2die(51216, log_message)
# Create SNMP session
self.session = self._session()
def _session(self):
"""Create an SNMP session for queries.
Args:
None
Returns:
session: SNMP session
"""
# Create session
if self._snmp_version != 3:
session = easysnmp.Session(
community=self._snmp_community,
hostname=self._snmp_ip_target,
version=self._snmp_version,
remote_port=self._snmp_port,
use_numeric=True,
context=self._context_name
)
else:
session = easysnmp.Session(
hostname=self._snmp_ip_target,
version=self._snmp_version,
remote_port=self._snmp_port,
use_numeric=True,
context=self._context_name,
security_level=self._security_level(),
security_username=self._snmp_secname,
privacy_protocol=self._priv_protocol(),
privacy_password=self._snmp_privpassword,
auth_protocol=self._auth_protocol(),
auth_password=self._snmp_authpassword
)
# Return
return session
def _security_level(self):
"""Create string for security level.
Args:
snmp_params: Dict of SNMP paramerters
Returns:
result: security level
"""
# Determine the security level
if bool(self._snmp_authprotocol) is True:
if bool(self._snmp_privprotocol) is True:
result = 'authPriv'
else:
result = 'authNoPriv'
else:
result = 'noAuthNoPriv'
# Return
return result
def _auth_protocol(self):
"""Get AuthProtocol to use.
Args:
snmp_params: Dict of SNMP paramerters
Returns:
result: Protocol to be used in session
"""
# Initialize key variables
protocol = self._snmp_authprotocol
# Setup AuthProtocol (Default SHA)
if bool(protocol) is False:
result = 'DEFAULT'
else:
if protocol.lower() == 'md5':
result = 'MD5'
else:
result = 'SHA'
# Return
return result
def _priv_protocol(self):
"""Get privProtocol to use.
Args:
snmp_params: Dict of SNMP paramerters
Returns:
result: Protocol to be used in session
"""
# Initialize key variables
protocol = self._snmp_privprotocol
# Setup privProtocol (Default AES256)
if bool(protocol) is False:
result = 'DEFAULT'
else:
if protocol.lower() == 'des':
result = 'DES'
else:
result = 'AES'
# Return
return result
def _process_error(
log_message, exception_error, check_reachability,
check_existence, system_error=False):
"""Process the SNMP error.
Args:
params_dict: Dict of SNMP parameters to try
Returns:
alive: True if contactable
"""
# Initialize key varialbes
_contactable = True
exists = True
if system_error is False:
error_name = 'EasySNMPError'
else:
error_name = 'SystemError'
# Check existence of OID
if check_existence is True:
if system_error is False:
if isinstance(
exception_error,
easysnmp.exceptions.EasySNMPUnknownObjectIDError) is True:
exists = False
return (_contactable, exists)
elif isinstance(
exception_error,
easysnmp.exceptions.EasySNMPNoSuchNameError) is True:
exists = False
return (_contactable, exists)
elif isinstance(
exception_error,
easysnmp.exceptions.EasySNMPNoSuchObjectError) is True:
exists = False
return (_contactable, exists)
elif isinstance(
exception_error,
easysnmp.exceptions.EasySNMPNoSuchInstanceError) is True:
exists = False
return (_contactable, exists)
else:
exists = False
return (_contactable, exists)
# Checking if the target is reachable
if check_reachability is True:
_contactable = False
exists = False
return (_contactable, exists)
# Die an agonizing death!
log_message = ('{}: {}'.format(error_name, log_message))
log.log2die(51569, log_message)
return None
def _convert_results(inbound):
"""Convert results from easysnmp.variables.SNMPVariable to DataPoint.
Args:
inbound: SNMP query result as list of easysnmp.variables.SNMPVariable
Returns:
outbound: DataPoint formatted equivalent
"""
# Initialize key variables
outbound = []
# Format the results to DataPoint format
for item in inbound:
# Initialize loop variables
converted = None
snmp_type = item.snmp_type
data_type = DATA_INT
# Convert string type values to bytes
if snmp_type.upper() == 'OCTETSTR':
converted = item.value
data_type = DATA_STRING
elif snmp_type.upper() == 'OPAQUE':
converted = item.value
data_type = DATA_STRING
elif snmp_type.upper() == 'BITS':
converted = item.value
data_type = DATA_STRING
elif snmp_type.upper() == 'IPADDR':
converted = item.value
data_type = DATA_STRING
elif snmp_type.upper() == 'NETADDR':
converted = item.value
data_type = DATA_STRING
elif snmp_type.upper() == 'OBJECTID':
# DO NOT CHANGE !!!
# converted = bytes(str(value), 'utf-8')
converted = item.value
data_type = DATA_STRING
elif snmp_type.upper() == 'NOSUCHOBJECT':
# Nothing if OID not found
converted = None
data_type = DATA_NONE
elif snmp_type.upper() == 'NOSUCHINSTANCE':
# Nothing if OID not found
converted = None
data_type = DATA_NONE
elif snmp_type.upper() == 'ENDOFMIBVIEW':
# Nothing
converted = None
data_type = DATA_NONE
elif snmp_type.upper() == 'NULL':
# Nothing
converted = None
data_type = DATA_NONE
elif snmp_type.upper() == 'COUNTER':
# Numeric values
converted = int(item.value)
data_type = DATA_COUNT
elif snmp_type.upper() == 'COUNTER64':
# Numeric values
converted = int(item.value)
data_type = DATA_COUNT64
else:
# Convert everything else into integer values
# rfc1902.Integer
# rfc1902.Integer32
# rfc1902.Gauge32
# rfc1902.Unsigned32
# rfc1902.TimeTicks
converted = int(item.value)
# Convert result to DataPoint
key = '{}.{}'.format(item.oid, item.oid_index)
datapoint = DataPoint(key, converted, data_type=data_type)
# Append to outbound result
outbound.append(datapoint)
# Return
return outbound
| [
"pattoo_shared.log.log2die",
"pattoo_shared.variables.DataPoint",
"pattoo_shared.log.log2see",
"pattoo_agents.snmp.oid.OIDstring",
"sys.exc_info",
"easysnmp.Session"
] | [((17306, 17337), 'pattoo_shared.log.log2die', 'log.log2die', (['(51569)', 'log_message'], {}), '(51569, log_message)\n', (17317, 17337), False, 'from pattoo_shared import log\n'), ((7759, 7790), 'pattoo_agents.snmp.oid.OIDstring', 'class_oid.OIDstring', (['oid_to_get'], {}), '(oid_to_get)\n', (7778, 7790), True, 'from pattoo_agents.snmp import oid as class_oid\n'), ((19943, 19989), 'pattoo_shared.variables.DataPoint', 'DataPoint', (['key', 'converted'], {'data_type': 'data_type'}), '(key, converted, data_type=data_type)\n', (19952, 19989), False, 'from pattoo_shared.variables import DataPoint\n'), ((7997, 8028), 'pattoo_shared.log.log2die', 'log.log2die', (['(51449)', 'log_message'], {}), '(51449, log_message)\n', (8008, 8028), False, 'from pattoo_shared import log\n'), ((12072, 12103), 'pattoo_shared.log.log2die', 'log.log2die', (['(51223)', 'log_message'], {}), '(51223, log_message)\n', (12083, 12103), False, 'from pattoo_shared import log\n'), ((12323, 12354), 'pattoo_shared.log.log2die', 'log.log2die', (['(51215)', 'log_message'], {}), '(51215, log_message)\n', (12334, 12354), False, 'from pattoo_shared import log\n'), ((12529, 12560), 'pattoo_shared.log.log2die', 'log.log2die', (['(51216)', 'log_message'], {}), '(51216, log_message)\n', (12540, 12560), False, 'from pattoo_shared import log\n'), ((12883, 13075), 'easysnmp.Session', 'easysnmp.Session', ([], {'community': 'self._snmp_community', 'hostname': 'self._snmp_ip_target', 'version': 'self._snmp_version', 'remote_port': 'self._snmp_port', 'use_numeric': '(True)', 'context': 'self._context_name'}), '(community=self._snmp_community, hostname=self.\n _snmp_ip_target, version=self._snmp_version, remote_port=self.\n _snmp_port, use_numeric=True, context=self._context_name)\n', (12899, 13075), False, 'import easysnmp\n'), ((1936, 1967), 'pattoo_shared.log.log2see', 'log.log2see', (['(51035)', 'log_message'], {}), '(51035, log_message)\n', (1947, 1967), False, 'from pattoo_shared import log\n'), ((2211, 2242), 'pattoo_shared.log.log2see', 'log.log2see', (['(51036)', 'log_message'], {}), '(51036, log_message)\n', (2222, 2242), False, 'from pattoo_shared import log\n'), ((10686, 10717), 'pattoo_shared.log.log2die', 'log.log2die', (['(51029)', 'log_message'], {}), '(51029, log_message)\n', (10697, 10717), False, 'from pattoo_shared import log\n'), ((9645, 9659), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (9657, 9659), False, 'import sys\n'), ((9691, 9705), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (9703, 9705), False, 'import sys\n'), ((9710, 9724), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (9722, 9724), False, 'import sys\n'), ((10092, 10106), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (10104, 10106), False, 'import sys\n'), ((10138, 10152), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (10150, 10152), False, 'import sys\n'), ((10157, 10171), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (10169, 10171), False, 'import sys\n'), ((10534, 10548), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (10546, 10548), False, 'import sys\n'), ((10573, 10587), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (10585, 10587), False, 'import sys\n'), ((10612, 10626), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (10624, 10626), False, 'import sys\n')] |
"""
Ref: https://dacon.io/competitions/official/235673/talkboard/401911?page=1&dtype=recent
"""
import os
import re
import platform
import itertools
import collections
import pkg_resources # pip install py-rouge
from io import open
if platform.system() == "Windows":
try:
from eunjeon import Mecab
except:
print("please install eunjeon module")
else: # Ubuntu일 경우
from konlpy.tag import Mecab
class Rouge:
DEFAULT_METRICS = {"rouge-n"}
DEFAULT_N = 1
STATS = ["f", "p", "r"]
AVAILABLE_METRICS = {"rouge-n", "rouge-l", "rouge-w"}
AVAILABLE_LENGTH_LIMIT_TYPES = {"words", "bytes"}
REMOVE_CHAR_PATTERN = re.compile("[^A-Za-z0-9가-힣]")
def __init__(
self,
metrics=None,
max_n=None,
limit_length=True,
length_limit=1000,
length_limit_type="words",
apply_avg=True,
apply_best=False,
use_tokenizer=True,
alpha=0.5,
weight_factor=1.0,
):
self.metrics = metrics[:] if metrics is not None else Rouge.DEFAULT_METRICS
for m in self.metrics:
if m not in Rouge.AVAILABLE_METRICS:
raise ValueError("Unknown metric '{}'".format(m))
self.max_n = max_n if "rouge-n" in self.metrics else None
# Add all rouge-n metrics
if self.max_n is not None:
index_rouge_n = self.metrics.index("rouge-n")
del self.metrics[index_rouge_n]
self.metrics += ["rouge-{}".format(n) for n in range(1, self.max_n + 1)]
self.metrics = set(self.metrics)
self.limit_length = limit_length
if self.limit_length:
if length_limit_type not in Rouge.AVAILABLE_LENGTH_LIMIT_TYPES:
raise ValueError(
"Unknown length_limit_type '{}'".format(length_limit_type)
)
self.length_limit = length_limit
if self.length_limit == 0:
self.limit_length = False
self.length_limit_type = length_limit_type
self.use_tokenizer = use_tokenizer
if use_tokenizer:
self.tokenizer = Mecab()
self.apply_avg = apply_avg
self.apply_best = apply_best
self.alpha = alpha
self.weight_factor = weight_factor
if self.weight_factor <= 0:
raise ValueError("ROUGE-W weight factor must greater than 0.")
def tokenize_text(self, text):
if self.use_tokenizer:
return self.tokenizer.morphs(text)
else:
return text
@staticmethod
def split_into_sentences(text):
return text.split("\n")
@staticmethod
def _get_ngrams(n, text):
ngram_set = collections.defaultdict(int)
max_index_ngram_start = len(text) - n
for i in range(max_index_ngram_start + 1):
ngram_set[tuple(text[i : i + n])] += 1
return ngram_set
@staticmethod
def _split_into_words(sentences):
return list(itertools.chain(*[_.split() for _ in sentences]))
@staticmethod
def _get_word_ngrams_and_length(n, sentences):
assert len(sentences) > 0
assert n > 0
tokens = Rouge._split_into_words(sentences)
return Rouge._get_ngrams(n, tokens), tokens, len(tokens) - (n - 1)
@staticmethod
def _get_unigrams(sentences):
assert len(sentences) > 0
tokens = Rouge._split_into_words(sentences)
unigram_set = collections.defaultdict(int)
for token in tokens:
unigram_set[token] += 1
return unigram_set, len(tokens)
@staticmethod
def _compute_p_r_f_score(
evaluated_count,
reference_count,
overlapping_count,
alpha=0.5,
weight_factor=1.0,
):
precision = (
0.0 if evaluated_count == 0 else overlapping_count / float(evaluated_count)
)
if weight_factor != 1.0:
precision = precision ** (1.0 / weight_factor)
recall = (
0.0 if reference_count == 0 else overlapping_count / float(reference_count)
)
if weight_factor != 1.0:
recall = recall ** (1.0 / weight_factor)
f1_score = Rouge._compute_f_score(precision, recall, alpha)
return {"f": f1_score, "p": precision, "r": recall}
@staticmethod
def _compute_f_score(precision, recall, alpha=0.5):
return (
0.0
if (recall == 0.0 or precision == 0.0)
else precision * recall / ((1 - alpha) * precision + alpha * recall)
)
@staticmethod
def _compute_ngrams(evaluated_sentences, reference_sentences, n):
if len(evaluated_sentences) <= 0 or len(reference_sentences) <= 0:
raise ValueError("Collections must contain at least 1 sentence.")
evaluated_ngrams, _, evaluated_count = Rouge._get_word_ngrams_and_length(
n, evaluated_sentences
)
reference_ngrams, _, reference_count = Rouge._get_word_ngrams_and_length(
n, reference_sentences
)
# Gets the overlapping ngrams between evaluated and reference
overlapping_ngrams = set(evaluated_ngrams.keys()).intersection(
set(reference_ngrams.keys())
)
overlapping_count = 0
for ngram in overlapping_ngrams:
overlapping_count += min(evaluated_ngrams[ngram], reference_ngrams[ngram])
return evaluated_count, reference_count, overlapping_count
@staticmethod
def _compute_ngrams_lcs(
evaluated_sentences, reference_sentences, weight_factor=1.0
):
def _lcs(x, y):
m = len(x)
n = len(y)
vals = collections.defaultdict(int)
dirs = collections.defaultdict(int)
for i in range(1, m + 1):
for j in range(1, n + 1):
if x[i - 1] == y[j - 1]:
vals[i, j] = vals[i - 1, j - 1] + 1
dirs[i, j] = "|"
elif vals[i - 1, j] >= vals[i, j - 1]:
vals[i, j] = vals[i - 1, j]
dirs[i, j] = "^"
else:
vals[i, j] = vals[i, j - 1]
dirs[i, j] = "<"
return vals, dirs
def _wlcs(x, y, weight_factor):
m = len(x)
n = len(y)
vals = collections.defaultdict(float)
dirs = collections.defaultdict(int)
lengths = collections.defaultdict(int)
for i in range(1, m + 1):
for j in range(1, n + 1):
if x[i - 1] == y[j - 1]:
length_tmp = lengths[i - 1, j - 1]
vals[i, j] = (
vals[i - 1, j - 1]
+ (length_tmp + 1) ** weight_factor
- length_tmp ** weight_factor
)
dirs[i, j] = "|"
lengths[i, j] = length_tmp + 1
elif vals[i - 1, j] >= vals[i, j - 1]:
vals[i, j] = vals[i - 1, j]
dirs[i, j] = "^"
lengths[i, j] = 0
else:
vals[i, j] = vals[i, j - 1]
dirs[i, j] = "<"
lengths[i, j] = 0
return vals, dirs
def _mark_lcs(mask, dirs, m, n):
while m != 0 and n != 0:
if dirs[m, n] == "|":
m -= 1
n -= 1
mask[m] = 1
elif dirs[m, n] == "^":
m -= 1
elif dirs[m, n] == "<":
n -= 1
else:
raise UnboundLocalError("Illegal move")
return mask
if len(evaluated_sentences) <= 0 or len(reference_sentences) <= 0:
raise ValueError("Collections must contain at least 1 sentence.")
evaluated_unigrams_dict, evaluated_count = Rouge._get_unigrams(
evaluated_sentences
)
reference_unigrams_dict, reference_count = Rouge._get_unigrams(
reference_sentences
)
# Has to use weight factor for WLCS
use_WLCS = weight_factor != 1.0
if use_WLCS:
evaluated_count = evaluated_count ** weight_factor
reference_count = 0
overlapping_count = 0.0
for reference_sentence in reference_sentences:
reference_sentence_tokens = reference_sentence.split()
if use_WLCS:
reference_count += len(reference_sentence_tokens) ** weight_factor
hit_mask = [0 for _ in range(len(reference_sentence_tokens))]
for evaluated_sentence in evaluated_sentences:
evaluated_sentence_tokens = evaluated_sentence.split()
if use_WLCS:
_, lcs_dirs = _wlcs(
reference_sentence_tokens,
evaluated_sentence_tokens,
weight_factor,
)
else:
_, lcs_dirs = _lcs(
reference_sentence_tokens, evaluated_sentence_tokens
)
_mark_lcs(
hit_mask,
lcs_dirs,
len(reference_sentence_tokens),
len(evaluated_sentence_tokens),
)
overlapping_count_length = 0
for ref_token_id, val in enumerate(hit_mask):
if val == 1:
token = reference_sentence_tokens[ref_token_id]
if (
evaluated_unigrams_dict[token] > 0
and reference_unigrams_dict[token] > 0
):
evaluated_unigrams_dict[token] -= 1
reference_unigrams_dict[ref_token_id] -= 1
if use_WLCS:
overlapping_count_length += 1
if (
ref_token_id + 1 < len(hit_mask)
and hit_mask[ref_token_id + 1] == 0
) or ref_token_id + 1 == len(hit_mask):
overlapping_count += (
overlapping_count_length ** weight_factor
)
overlapping_count_length = 0
else:
overlapping_count += 1
if use_WLCS:
reference_count = reference_count ** weight_factor
return evaluated_count, reference_count, overlapping_count
def get_scores(self, hypothesis, references):
if isinstance(hypothesis, str):
hypothesis, references = [hypothesis], [references]
if type(hypothesis) != type(references):
raise ValueError("'hyps' and 'refs' are not of the same type")
if len(hypothesis) != len(references):
raise ValueError("'hyps' and 'refs' do not have the same length")
scores = {}
has_rouge_n_metric = (
len([metric for metric in self.metrics if metric.split("-")[-1].isdigit()])
> 0
)
if has_rouge_n_metric:
scores.update(self._get_scores_rouge_n(hypothesis, references))
# scores = {**scores, **self._get_scores_rouge_n(hypothesis, references)}
has_rouge_l_metric = (
len(
[
metric
for metric in self.metrics
if metric.split("-")[-1].lower() == "l"
]
)
> 0
)
if has_rouge_l_metric:
scores.update(self._get_scores_rouge_l_or_w(hypothesis, references, False))
# scores = {**scores, **self._get_scores_rouge_l_or_w(hypothesis, references, False)}
has_rouge_w_metric = (
len(
[
metric
for metric in self.metrics
if metric.split("-")[-1].lower() == "w"
]
)
> 0
)
if has_rouge_w_metric:
scores.update(self._get_scores_rouge_l_or_w(hypothesis, references, True))
# scores = {**scores, **self._get_scores_rouge_l_or_w(hypothesis, references, True)}
return scores
def _get_scores_rouge_n(self, all_hypothesis, all_references):
metrics = [metric for metric in self.metrics if metric.split("-")[-1].isdigit()]
if self.apply_avg or self.apply_best:
scores = {metric: {stat: 0.0 for stat in Rouge.STATS} for metric in metrics}
else:
scores = {
metric: [
{stat: [] for stat in Rouge.STATS}
for _ in range(len(all_hypothesis))
]
for metric in metrics
}
for sample_id, (hypothesis, references) in enumerate(
zip(all_hypothesis, all_references)
):
assert isinstance(hypothesis, str)
has_multiple_references = False
if isinstance(references, list):
has_multiple_references = len(references) > 1
if not has_multiple_references:
references = references[0]
# Prepare hypothesis and reference(s)
hypothesis = self._preprocess_summary_as_a_whole(hypothesis)
references = (
[
self._preprocess_summary_as_a_whole(reference)
for reference in references
]
if has_multiple_references
else [self._preprocess_summary_as_a_whole(references)]
)
# Compute scores
for metric in metrics:
suffix = metric.split("-")[-1]
n = int(suffix)
# Aggregate
if self.apply_avg:
# average model
total_hypothesis_ngrams_count = 0
total_reference_ngrams_count = 0
total_ngrams_overlapping_count = 0
for reference in references:
(
hypothesis_count,
reference_count,
overlapping_ngrams,
) = Rouge._compute_ngrams(hypothesis, reference, n)
total_hypothesis_ngrams_count += hypothesis_count
total_reference_ngrams_count += reference_count
total_ngrams_overlapping_count += overlapping_ngrams
score = Rouge._compute_p_r_f_score(
total_hypothesis_ngrams_count,
total_reference_ngrams_count,
total_ngrams_overlapping_count,
self.alpha,
)
for stat in Rouge.STATS:
scores[metric][stat] += score[stat]
else:
# Best model
if self.apply_best:
best_current_score = None
for reference in references:
(
hypothesis_count,
reference_count,
overlapping_ngrams,
) = Rouge._compute_ngrams(hypothesis, reference, n)
score = Rouge._compute_p_r_f_score(
hypothesis_count,
reference_count,
overlapping_ngrams,
self.alpha,
)
if (
best_current_score is None
or score["r"] > best_current_score["r"]
):
best_current_score = score
for stat in Rouge.STATS:
scores[metric][stat] += best_current_score[stat]
# Keep all
else:
for reference in references:
(
hypothesis_count,
reference_count,
overlapping_ngrams,
) = Rouge._compute_ngrams(hypothesis, reference, n)
score = Rouge._compute_p_r_f_score(
hypothesis_count,
reference_count,
overlapping_ngrams,
self.alpha,
)
for stat in Rouge.STATS:
scores[metric][sample_id][stat].append(score[stat])
# Compute final score with the average or the the max
if (self.apply_avg or self.apply_best) and len(all_hypothesis) > 1:
for metric in metrics:
for stat in Rouge.STATS:
scores[metric][stat] /= len(all_hypothesis)
return scores
def _get_scores_rouge_l_or_w(self, all_hypothesis, all_references, use_w=False):
metric = "rouge-w" if use_w else "rouge-l"
if self.apply_avg or self.apply_best:
scores = {metric: {stat: 0.0 for stat in Rouge.STATS}}
else:
scores = {
metric: [
{stat: [] for stat in Rouge.STATS}
for _ in range(len(all_hypothesis))
]
}
for sample_id, (hypothesis_sentences, references_sentences) in enumerate(
zip(all_hypothesis, all_references)
):
assert isinstance(hypothesis_sentences, str)
has_multiple_references = False
if isinstance(references_sentences, list):
has_multiple_references = len(references_sentences) > 1
if not has_multiple_references:
references_sentences = references_sentences[0]
# Prepare hypothesis and reference(s)
hypothesis_sentences = self._preprocess_summary_per_sentence(
hypothesis_sentences
)
references_sentences = (
[
self._preprocess_summary_per_sentence(reference)
for reference in references_sentences
]
if has_multiple_references
else [self._preprocess_summary_per_sentence(references_sentences)]
)
# Compute scores
# Aggregate
if self.apply_avg:
# average model
total_hypothesis_ngrams_count = 0
total_reference_ngrams_count = 0
total_ngrams_overlapping_count = 0
for reference_sentences in references_sentences:
(
hypothesis_count,
reference_count,
overlapping_ngrams,
) = Rouge._compute_ngrams_lcs(
hypothesis_sentences,
reference_sentences,
self.weight_factor if use_w else 1.0,
)
total_hypothesis_ngrams_count += hypothesis_count
total_reference_ngrams_count += reference_count
total_ngrams_overlapping_count += overlapping_ngrams
score = Rouge._compute_p_r_f_score(
total_hypothesis_ngrams_count,
total_reference_ngrams_count,
total_ngrams_overlapping_count,
self.alpha,
self.weight_factor if use_w else 1.0,
)
for stat in Rouge.STATS:
scores[metric][stat] += score[stat]
else:
# Best model
if self.apply_best:
best_current_score = None
best_current_score_wlcs = None
for reference_sentences in references_sentences:
(
hypothesis_count,
reference_count,
overlapping_ngrams,
) = Rouge._compute_ngrams_lcs(
hypothesis_sentences,
reference_sentences,
self.weight_factor if use_w else 1.0,
)
score = Rouge._compute_p_r_f_score(
total_hypothesis_ngrams_count,
total_reference_ngrams_count,
total_ngrams_overlapping_count,
self.alpha,
self.weight_factor if use_w else 1.0,
)
if use_w:
reference_count_for_score = reference_count ** (
1.0 / self.weight_factor
)
overlapping_ngrams_for_score = overlapping_ngrams
score_wlcs = (
overlapping_ngrams_for_score / reference_count_for_score
) ** (1.0 / self.weight_factor)
if (
best_current_score_wlcs is None
or score_wlcs > best_current_score_wlcs
):
best_current_score = score
best_current_score_wlcs = score_wlcs
else:
if (
best_current_score is None
or score["r"] > best_current_score["r"]
):
best_current_score = score
for stat in Rouge.STATS:
scores[metric][stat] += best_current_score[stat]
# Keep all
else:
for reference_sentences in references_sentences:
(
hypothesis_count,
reference_count,
overlapping_ngrams,
) = Rouge._compute_ngrams_lcs(
hypothesis_sentences,
reference_sentences,
self.weight_factor if use_w else 1.0,
)
score = Rouge._compute_p_r_f_score(
hypothesis_count,
reference_count,
overlapping_ngrams,
self.alpha,
self.weight_factor,
)
for stat in Rouge.STATS:
scores[metric][sample_id][stat].append(score[stat])
# Compute final score with the average or the the max
if (self.apply_avg or self.apply_best) and len(all_hypothesis) > 1:
for stat in Rouge.STATS:
scores[metric][stat] /= len(all_hypothesis)
return scores
def _preprocess_summary_as_a_whole(self, summary):
sentences = Rouge.split_into_sentences(summary)
# Truncate
if self.limit_length:
# By words
if self.length_limit_type == "words":
summary = " ".join(sentences)
all_tokens = summary.split() # Counting as in the perls script
summary = " ".join(all_tokens[: self.length_limit])
# By bytes
elif self.length_limit_type == "bytes":
summary = ""
current_len = 0
for sentence in sentences:
sentence = sentence.strip()
sentence_len = len(sentence)
if current_len + sentence_len < self.length_limit:
if current_len != 0:
summary += " "
summary += sentence
current_len += sentence_len
else:
if current_len > 0:
summary += " "
summary += sentence[: self.length_limit - current_len]
break
else:
summary = " ".join(sentences)
summary = Rouge.REMOVE_CHAR_PATTERN.sub(" ", summary.lower()).strip()
tokens = self.tokenize_text(Rouge.REMOVE_CHAR_PATTERN.sub(" ", summary))
preprocessed_summary = [" ".join(tokens)]
return preprocessed_summary
def _preprocess_summary_per_sentence(self, summary):
sentences = Rouge.split_into_sentences(summary)
# Truncate
if self.limit_length:
final_sentences = []
current_len = 0
# By words
if self.length_limit_type == "words":
for sentence in sentences:
tokens = sentence.strip().split()
tokens_len = len(tokens)
if current_len + tokens_len < self.length_limit:
sentence = " ".join(tokens)
final_sentences.append(sentence)
current_len += tokens_len
else:
sentence = " ".join(tokens[: self.length_limit - current_len])
final_sentences.append(sentence)
break
# By bytes
elif self.length_limit_type == "bytes":
for sentence in sentences:
sentence = sentence.strip()
sentence_len = len(sentence)
if current_len + sentence_len < self.length_limit:
final_sentences.append(sentence)
current_len += sentence_len
else:
sentence = sentence[: self.length_limit - current_len]
final_sentences.append(sentence)
break
sentences = final_sentences
final_sentences = []
for sentence in sentences:
sentence = Rouge.REMOVE_CHAR_PATTERN.sub(" ", sentence.lower()).strip()
tokens = self.tokenize_text(Rouge.REMOVE_CHAR_PATTERN.sub(" ", sentence))
sentence = " ".join(tokens)
final_sentences.append(sentence)
return final_sentences
| [
"platform.system",
"collections.defaultdict",
"eunjeon.Mecab",
"re.compile"
] | [((238, 255), 'platform.system', 'platform.system', ([], {}), '()\n', (253, 255), False, 'import platform\n'), ((658, 687), 're.compile', 're.compile', (['"""[^A-Za-z0-9가-힣]"""'], {}), "('[^A-Za-z0-9가-힣]')\n", (668, 687), False, 'import re\n'), ((2691, 2719), 'collections.defaultdict', 'collections.defaultdict', (['int'], {}), '(int)\n', (2714, 2719), False, 'import collections\n'), ((3435, 3463), 'collections.defaultdict', 'collections.defaultdict', (['int'], {}), '(int)\n', (3458, 3463), False, 'import collections\n'), ((2121, 2128), 'eunjeon.Mecab', 'Mecab', ([], {}), '()\n', (2126, 2128), False, 'from eunjeon import Mecab\n'), ((5670, 5698), 'collections.defaultdict', 'collections.defaultdict', (['int'], {}), '(int)\n', (5693, 5698), False, 'import collections\n'), ((5718, 5746), 'collections.defaultdict', 'collections.defaultdict', (['int'], {}), '(int)\n', (5741, 5746), False, 'import collections\n'), ((6382, 6412), 'collections.defaultdict', 'collections.defaultdict', (['float'], {}), '(float)\n', (6405, 6412), False, 'import collections\n'), ((6432, 6460), 'collections.defaultdict', 'collections.defaultdict', (['int'], {}), '(int)\n', (6455, 6460), False, 'import collections\n'), ((6483, 6511), 'collections.defaultdict', 'collections.defaultdict', (['int'], {}), '(int)\n', (6506, 6511), False, 'import collections\n')] |
from django.contrib import admin
from .. import models
@admin.register(models.Contest)
class ContestAdmin(admin.ModelAdmin):
"""
대회관리
"""
list_display = ['contest_name', 'start_time', 'end_time', 'message', 'host_email', 'after_open']
class Meta:
model = models.Contest
@admin.register(models.ContestProblem)
class ContestProblemAdmin(admin.ModelAdmin):
"""
대회 문제관리
"""
list_display = ['contest', 'problem']
class Meta:
model = models.ContestProblem
@admin.register(models.Participant)
class ParticipantAdmin(admin.ModelAdmin):
"""
참가자관리
"""
list_display = ['contest', 'participant']
class Meta:
model = models.Participant
| [
"django.contrib.admin.register"
] | [((59, 89), 'django.contrib.admin.register', 'admin.register', (['models.Contest'], {}), '(models.Contest)\n', (73, 89), False, 'from django.contrib import admin\n'), ((305, 342), 'django.contrib.admin.register', 'admin.register', (['models.ContestProblem'], {}), '(models.ContestProblem)\n', (319, 342), False, 'from django.contrib import admin\n'), ((516, 550), 'django.contrib.admin.register', 'admin.register', (['models.Participant'], {}), '(models.Participant)\n', (530, 550), False, 'from django.contrib import admin\n')] |
import logging
import predix.admin.cf.api
import predix.admin.cf.orgs
import predix.admin.cf.apps
import predix.admin.cf.services
class Space(object):
"""
Operations and data for Cloud Foundry Spaces.
"""
def __init__(self, *args, **kwargs):
super(Space, self).__init__(*args, **kwargs)
self.api = predix.admin.cf.api.API()
self.name = self.api.config.get_space_name()
self.guid = self.api.config.get_space_guid()
self.org = predix.admin.cf.orgs.Org()
def _get_spaces(self):
"""
Get the marketplace services.
"""
guid = self.api.config.get_organization_guid()
uri = '/v2/organizations/%s/spaces' % (guid)
return self.api.get(uri)
def get_spaces(self):
"""
Return a flat list of the names for spaces in the organization.
"""
self.spaces = []
for resource in self._get_spaces()['resources']:
self.spaces.append(resource['entity']['name'])
return self.spaces
def get_space_services(self):
"""
Returns the services available for use in the space. This may
not always be the same as the full marketplace.
"""
uri = '/v2/spaces/%s/services' % (self.guid)
return self.api.get(uri)
def create_space(self, space_name):
"""
Create a new space of the given name.
"""
body = {
'name': space_name,
'organization_guid': self.api.config.get_organization_guid()
}
return self.api.post('/v2/spaces', body)
def delete_space(self, space_name):
"""
Delete a space of the given name.
"""
return self.api.delete("/v2/spaces/%s" % (self.guid))
def get_space_summary(self):
"""
Returns a summary of apps and services within a given
cloud foundry space.
It is the call used by `cf s` or `cf a` for quicker
responses.
"""
uri = '/v2/spaces/%s/summary' % (self.guid)
return self.api.get(uri)
def _get_apps(self):
"""
Returns raw results for all apps in the space.
"""
uri = '/v2/spaces/%s/apps' % (self.guid)
return self.api.get(uri)
def get_apps(self):
"""
Returns a list of all of the apps in the space.
"""
apps = []
for resource in self._get_apps()['resources']:
apps.append(resource['entity']['name'])
return apps
def has_app(self, app_name):
"""
Simple test to see if we have a name conflict
for the application.
"""
return app_name in self.get_apps()
def _get_services(self):
"""
Return the available services for this space.
"""
uri = '/v2/spaces/%s/services' % (self.guid)
return self.api.get(uri)
def get_services(self):
"""
Returns a flat list of the service names available
from the marketplace for this space.
"""
services = []
for resource in self._get_services()['resources']:
services.append(resource['entity']['label'])
return services
def _get_instances(self):
"""
Returns the service instances activated in this space.
"""
uri = '/v2/spaces/%s/service_instances' % (self.guid)
return self.api.get(uri)
def get_instances(self):
"""
Returns a flat list of the names of services created
in this space.
"""
services = []
for resource in self._get_instances()['resources']:
services.append(resource['entity']['name'])
return services
def has_service_with_name(self, service_name):
"""
Tests whether a service with the given name exists in
this space.
"""
return service_name in self.get_instances()
def has_service_of_type(self, service_type):
"""
Tests whether a service instance exists for the given
service.
"""
summary = self.get_space_summary()
for instance in summary['services']:
if service_type == instance['service_plan']['service']['label']:
return True
return False
def purge(self):
"""
Remove all services and apps from the space.
Will leave the space itself, call delete_space() if you
want to remove that too.
Similar to `cf delete-space -f <space-name>`.
"""
logging.warn("Purging all services from space %s" %
(self.name))
service = predix.admin.cf.services.Service()
for service_name in self.get_instances():
service.purge(service_name)
apps = predix.admin.cf.apps.App()
for app_name in self.get_apps():
apps.delete_app(app_name)
| [
"logging.warn"
] | [((4573, 4635), 'logging.warn', 'logging.warn', (["('Purging all services from space %s' % self.name)"], {}), "('Purging all services from space %s' % self.name)\n", (4585, 4635), False, 'import logging\n')] |
import logging
from fastapi import APIRouter
from starlette import status
from api.endpoints.dependencies.tenant_security import get_from_context
from api.endpoints.models.v1.tenant import TenantGetResponse
from api.services.v1 import tenant_service
router = APIRouter()
logger = logging.getLogger(__name__)
@router.post(
"/make-issuer", status_code=status.HTTP_200_OK, response_model=TenantGetResponse
)
async def initialize_issuer() -> TenantGetResponse:
"""
If the innkeeper has authorized your tenant to become an issuer, initialize
here to write a endorsed public did the configured Hyperledger-Indy service
"""
wallet_id = get_from_context("TENANT_WALLET_ID")
tenant_id = get_from_context("TENANT_ID")
item = await tenant_service.make_issuer(
tenant_id,
wallet_id,
)
links = [] # TODO: determine useful links for /make-issuer
return TenantGetResponse(item=item, links=links)
| [
"logging.getLogger",
"api.endpoints.dependencies.tenant_security.get_from_context",
"api.services.v1.tenant_service.make_issuer",
"fastapi.APIRouter",
"api.endpoints.models.v1.tenant.TenantGetResponse"
] | [((265, 276), 'fastapi.APIRouter', 'APIRouter', ([], {}), '()\n', (274, 276), False, 'from fastapi import APIRouter\n'), ((286, 313), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (303, 313), False, 'import logging\n'), ((661, 697), 'api.endpoints.dependencies.tenant_security.get_from_context', 'get_from_context', (['"""TENANT_WALLET_ID"""'], {}), "('TENANT_WALLET_ID')\n", (677, 697), False, 'from api.endpoints.dependencies.tenant_security import get_from_context\n'), ((714, 743), 'api.endpoints.dependencies.tenant_security.get_from_context', 'get_from_context', (['"""TENANT_ID"""'], {}), "('TENANT_ID')\n", (730, 743), False, 'from api.endpoints.dependencies.tenant_security import get_from_context\n'), ((911, 952), 'api.endpoints.models.v1.tenant.TenantGetResponse', 'TenantGetResponse', ([], {'item': 'item', 'links': 'links'}), '(item=item, links=links)\n', (928, 952), False, 'from api.endpoints.models.v1.tenant import TenantGetResponse\n'), ((762, 810), 'api.services.v1.tenant_service.make_issuer', 'tenant_service.make_issuer', (['tenant_id', 'wallet_id'], {}), '(tenant_id, wallet_id)\n', (788, 810), False, 'from api.services.v1 import tenant_service\n')] |
import numpy as np
from scipy import interpolate, signal
from scipy.special import gamma
import ndmath
import warnings
import pkg_resources
class PlaningBoat():
"""Prismatic planing craft
Attributes:
speed (float): Speed (m/s). It is an input to :class:`PlaningBoat`.
weight (float): Weight (N). It is an input to :class:`PlaningBoat`.
beam (float): Beam (m). It is an input to :class:`PlaningBoat`.
lcg (float): Longitudinal center of gravity, measured from the stern (m). It is an input to :class:`PlaningBoat`.
vcg (float): Vertical center of gravity, measured from the keel (m). It is an input to :class:`PlaningBoat`.
r_g (float): Radius of gyration (m). It is an input to :class:`PlaningBoat`.
beta (float): Deadrise (deg). It is an input to :class:`PlaningBoat`.
epsilon (float): Thrust angle w.r.t. keel, CCW with body-fixed origin at 9 o'clock (deg). It is an input to :class:`PlaningBoat`.
vT (float): Thrust vertical distance, measured from keel, and positive up (m). It is an input to :class:`PlaningBoat`.
lT (float): Thrust horizontal distance, measured from stern, and positive forward (m). It is an input to :class:`PlaningBoat`.
length (float): Vessel LOA for seaway behavior estimates (m). Defaults to None. It is an input to :class:`PlaningBoat`.
H_sig (float): Significant wave heigth in an irregular sea state (m). Defaults to None. It is an input to :class:`PlaningBoat`.
ahr (float): Average hull roughness (m). Defaults to 150*10**-6. It is an input to :class:`PlaningBoat`.
Lf (float): Flap chord (m). Defaults to 0. It is an input to :class:`PlaningBoat`.
sigma (float): Flap span-beam ratio (dimensionless). Defaults to 0. It is an input to :class:`PlaningBoat`.
delta (float): Flap deflection (deg). Defaults to 0. It is an input to :class:`PlaningBoat`.
l_air (float): Distance from stern to center of air pressure (m). Defaults to 0. It is an input to :class:`PlaningBoat`.
h_air (float): Height from keel to top of square which bounds the air-drag-inducing area (m). Defaults to 0. It is an input to :class:`PlaningBoat`.
b_air (float): Transverse width of square which bounds the air-drag-inducing area (m). Defaults to 0. It is an input to :class:`PlaningBoat`.
C_shape (float): Area coefficient for air-drag-inducing area (dimensionless). C_shape = 1 means the air drag reference area is h_air*b_air. Defaults to 0. It is an input to :class:`PlaningBoat`.
C_D (float): Air drag coefficient (dimensionless). Defaults to 0.7. It is an input to :class:`PlaningBoat`.
rho (float): Water density (kg/m^3). Defaults to 1025.87. It is an input to :class:`PlaningBoat`.
nu (float): Water kinematic viscosity (m^2/s). Defaults to 1.19*10**-6. It is an input to :class:`PlaningBoat`.
rho_air (float): Air density (kg/m^3). Defaults to 1.225. It is an input to :class:`PlaningBoat`.
g (float): Gravitational acceleration (m/s^2). Defaults to 9.8066. It is an input to :class:`PlaningBoat`.
z_wl (float): Vertical distance of center of gravity to the calm water line (m). Defaults to 0. It is an input to :class:`PlaningBoat`, but modified when running :meth:`get_steady_trim`.
tau (float): Trim angle (deg). Defaults to 5. It is an input to :class:`PlaningBoat`, but modified when running :meth:`get_steady_trim`.
eta_3 (float): Additional heave (m). Initiates to 0.
eta_5 (float): Additional trim (deg). Initiates to zero.
wetted_lengths_type (int): 1 = Use Faltinsen 2005 wave rise approximation, 2 = Use Savitsky's '64 approach, 3 = Use Savitsky's '76 approach. Defaults to 1. It is an input to :class:`PlaningBoat`.
z_max_type (int): 1 = Uses 3rd order polynomial fit, 2 = Uses cubic interpolation from table. This is only used if wetted_lenghts_type == 1. Defaults to 1. It is an input to :class:`PlaningBoat`.
L_K (float): Keel wetted length (m). It is updated when running :meth:`get_geo_lengths`.
L_C (float): Chine wetted length (m). It is updated when running :meth:`get_geo_lengths`.
lambda_W (float): Mean wetted-length to beam ratio, (L_K+L_C)/(2*beam) (dimensionless). It is updated when running :meth:`get_geo_lengths`.
x_s (float): Distance from keel/water-line intersection to start of wetted chine (m). It is updated when running :meth:`get_geo_lengths`.
z_max (float): Maximum pressure coordinate coefficient, z_max/Ut (dimensionless). It is updated when running :meth:`get_geo_lengths`.
hydrodynamic_force ((3,) ndarray): Hydrodynamic force (N, N, N*m). [F_x, F_z, M_cg] with x, y, rot directions in intertial coordinates. It is updated when running :meth:`get_forces`.
skin_friction ((3,) ndarray): Skin friction force (N, N, N*m). [F_x, F_z, M_cg]. It is updated when running :meth:`get_forces`.
air_resistance ((3,) ndarray): Air resistance force (N, N, N*m). [F_x, F_z, M_cg]. It is updated when running :meth:`get_forces`.
flap_force ((3,) ndarray): Flap resultant force (N, N, N*m). [F_x, F_z, M_cg]. It is updated when running :meth:`get_forces`.
thrust_force ((3,) ndarray): Thrust resultant force (N, N, N*m). [F_x, F_z, M_cg]. It is updated when running :meth:`get_forces`.
net_force ((3,) ndarray): Net force (N, N, N*m). [F_x, F_z, M_cg]. It is updated when running :meth:`get_forces`.
mass_matrix ((2, 2) ndarray): Mass coefficients matrix. [[A_33 (kg), A_35 (kg*m/rad)], [A_53 (kg*m), A_55 (kg*m^2/rad)]]. It is updated when running :meth:`get_eom_matrices`.
damping_matrix ((2, 2) ndarray): Damping coefficients matrix. [[B_33 (kg/s), B_35 (kg*m/(s*rad))], [B_53 (kg*m/s), B_55 (kg*m**2/(s*rad))]]. It is updated when running :meth:`get_eom_matrices`.
restoring_matrix ((2, 2) ndarray): Restoring coefficients matrix. [[C_33 (N/m), C_35 (N/rad)], [C_53 (N), C_55 (N*m/rad)]]. It is updated when running :meth:`get_eom_matrices`.
porpoising (list): [[eigenvalue result (bool), est. pitch settling time (s)], [Savitsky chart result (bool), critical trim angle (deg)]]. It is updated when running :meth:`check_porpoising`.
seaway_drag_type (int): 1 = Use Savitsky's '76 approximation, 2 = Use Fridsma's '71 designs charts. Defaults to 1. It is an input to :class:`PlaningBoat`.
avg_impact_acc ((2,) ndarray): Average impact acceleration at center of gravity and bow (g's). [n_cg, n_bow]. It is updated when running :meth:`get_seaway_behavior`.
R_AW (float): Added resistance in waves (N). It is updated when running :meth:`get_seaway_behavior`.
"""
def __init__(self, speed, weight, beam, lcg, vcg, r_g, beta, epsilon, vT, lT, length=None, H_sig=None, ahr=150e-6, Lf=0, sigma=0, delta=0, l_air=0, h_air=0, b_air=0, C_shape=0, C_D=0.7, z_wl=0, tau=5, rho=1025.87, nu=1.19e-6, rho_air=1.225, g=9.8066, wetted_lengths_type=1, z_max_type=1, seaway_drag_type=1):
"""Initialize attributes for PlaningBoat
Args:
speed (float): Speed (m/s).
weight (float): Weidght (N).
beam (float): Beam (m).
lcg (float): Longitudinal center of gravity, measured from the stern (m).
vcg (float): Vertical center of gravity, measured from the keel (m).
r_g (float): Radius of gyration (m).
beta (float): Deadrise (deg).
epsilon (float): Thrust angle w.r.t. keel, CCW with body-fixed origin at 9 o'clock (deg).
vT (float): Thrust vertical distance, measured from keel, and positive up (m).
lT (float): Thrust horizontal distance, measured from stern, and positive forward (m).
length (float, optional): Vessel LOA for seaway behavior estimates (m). Defaults to None.
H_sig (float, optional): Significant wave heigth in an irregular sea state (m). Defaults to None.
ahr (float, optional): Average hull roughness (m). Defaults to 150*10**-6.
Lf (float, optional): Flap chord (m). Defaults to 0.
sigma (float, optional): Flap span-beam ratio (dimensionless). Defaults to 0.
delta (float, optional): Flap deflection (deg). Defaults to 0.
l_air (float, optional): Distance from stern to center of air pressure (m). Defaults to 0.
h_air (float, optional): Height from keel to top of square which bounds the air-drag-inducing area (m). Defaults to 0.
b_air (float, optional): Transverse width of square which bounds the air-drag-inducing area (m). Defaults to 0.
C_shape (float, optional): Area coefficient for air-drag-inducing area (dimensionless). C_shape = 1 means the air drag reference area is h_air*b_air. Defaults to 0.
C_D (float, optional): Air drag coefficient (dimensionless). Defaults to 0.7.
z_wl (float, optional): Vertical distance of center of gravity to the calm water line (m). Defaults to 0.
tau (float, optional): Trim angle (deg). Defaults to 5.
rho (float, optional): Water density (kg/m^3). Defaults to 1025.87.
nu (float, optional): Water kinematic viscosity (m^2/s). Defaults to 1.19*10**-6.
rho_air (float, optional): Air density (kg/m^3). Defaults to 1.225.
g (float, optional): Gravitational acceleration (m/s^2). Defaults to 9.8066.
wetted_lengths_type (int, optional): 1 = Use Faltinsen 2005 wave rise approximation, 2 = Use Savitsky's '64 approach, 3 = Use Savitsky's '76 approach. Defaults to 1.
z_max_type (int, optional): 1 = Uses 3rd order polynomial fit, 2 = Uses cubic interpolation from table. This is only used if wetted_lenghts_type == 1. Defaults to 1.
seaway_drag_type (int, optional): 1 = Use Savitsky's '76 approximation, 2 = Use Fridsma's '71 designs charts. Defaults to 1.
"""
self.speed = speed
self.weight = weight
self.beam = beam
self.lcg = lcg
self.vcg = vcg
self.r_g = r_g
self.beta = beta
self.epsilon = epsilon
self.vT = vT
self.lT = lT
self.length = length
self.H_sig = H_sig
self.ahr = ahr
self.Lf = Lf
self.sigma = sigma
self.delta = delta
self.l_air = l_air
self.h_air = h_air
self.b_air= b_air
self.C_shape = C_shape
self.z_wl = z_wl
self.tau = tau
self.eta_3 = 0
self.eta_5 = 0
self.rho = rho
self.nu = nu
self.rho_air = rho_air
self.C_D = C_D
self.g = g
self.gravity_force = np.array([0, -self.weight, 0])
self.wetted_lengths_type = wetted_lengths_type
self.z_max_type = z_max_type
self.seaway_drag_type = seaway_drag_type
def print_description(self, sigFigs=7, runAllFunctions=True):
"""Returns a formatted description of the vessel.
Args:
sigFigs (int, optional): Number of significant figures to display. Defaults to 7.
runAllFunctions (bool, optional): Runs all functions with default values before printing results. Defaults to True.
"""
if runAllFunctions:
self.get_geo_lengths()
self.get_forces(runGeoLengths=False)
self.get_eom_matrices(runGeoLengths=False)
self.get_seaway_behavior()
self.check_porpoising()
volume = self.weight/(self.g*self.rho)
table = [
['---VESSEL---'],
['Speed', self.speed, 'm/s'],
['V_k', self.speed*1.944, 'knot'],
['Fn (beam)', self.speed/np.sqrt(self.g*self.beam), ''],
['Fn (volume)', self.speed/np.sqrt(self.g*(self.weight/(self.g*self.rho))**(1/3)), ''],
[''],
['Weight', self.weight, 'N'],
['Mass', self.weight/self.g, 'kg'],
['Volume', self.weight/(self.g*self.rho), 'm\u00B3'],
['Beam', self.beam, 'm'],
['LCG', self.lcg, 'm from stern'],
['VCG', self.vcg, 'm from keel'],
['R_g', self.r_g, 'm'],
['Deadrise', self.beta, 'deg'], #'\N{greek small letter beta}'
[''],
['LOA', self.length, 'm'],
['AHR', self.ahr, 'm, average hull roughness'],
[''],
['---ATTITUDE---'],
['z_wl', self.z_wl, 'm, vertical distance of center of gravity to the calm water line'],
['tau', self.tau, 'deg, trim angle'],
['\u03B7\u2083', self.eta_3, 'deg, additional heave'],
['\u03B7\u2085', self.eta_5, 'deg, additional trim'],
['Transom draft', self.L_K*np.sin((self.tau+self.eta_5)*np.pi/180), 'm, draft of keel at transom'],
[''],
['---PROPULSION---'],
['Thrust angle', self.epsilon, 'deg w.r.t. keel (CCW with body-fixed origin at 9 o\'clock)'],
['LCT', self.lT, 'm from stern, positive forward'],
['VCT', self.vT, 'm from keel, positive up'],
[''],
['---FLAP---'],
['Chord', self.Lf, 'm'],
['Span/Beam', self.sigma, ''],
['Angle', self.delta, 'deg w.r.t. keel (CCW with body-fixed origin at 9 o\'clock)'],
[''],
['---AIR DRAG---'],
['l_air', self.l_air, 'm, distance from stern to center of air pressure'],
['h_air', self.h_air, 'm, height from keel to top of square which bounds the air-drag-inducing shape'],
['b_air', self.b_air, 'm, transverse width of square which bounds the air-drag-inducing shape'],
['C_shape', self.C_shape, 'area coefficient for air-drag-inducing shape. C_shape = 1 means the air drag reference area is h_air*b_air'],
['C_D', self.C_D, 'air drag coefficient'],
[''],
['---ENVIRONMENT---'],
['\u03C1', self.rho, 'kg/m\u00B3, water density'],
['\u03BD', self.nu, 'm\u00B2/s, water kinematic viscosity'],
['\u03C1_air', self.rho_air, 'kg/m\u00B3, air density'],
['g', self.g, 'm/s\u00B2, gravitational acceleration'],
[''],
['---WETTED LENGTH OPTIONS---'],
['wetted_lengths_type', self.wetted_lengths_type, '(1 = Use Faltinsen 2005 wave rise approximation, 2 = Use Savitsky\'s \'64 approach, 3 = Use Savitsky\'s \'76 approach)'],
['z_max_type', self.z_max_type, '(1 = Uses 3rd order polynomial fit (faster, recommended), 2 = Use cubic interpolation)'],
[''],
['---WETTED LENGTHS---'],
['L_K', self.L_K, 'm, keel wetted length'],
['L_C', self.L_C, 'm, chine wetted length'],
['\u03BB', self.lambda_W, 'mean wetted-length to beam ratio (L_K+L_C)/(2*beam)'],
['x_s', self.x_s, 'm, distance from keel/water-line intersection to start of wetted chine'],
['z_max', self.z_max, 'maximum pressure coordinate coefficient (z_max/Ut)'],
[''],
['---FORCES [F_x (N, +aft), F_z (N, +up), M_cg (N*m, +pitch up)]---'],
['Hydrodynamic Force', self.hydrodynamic_force, ''],
['Skin Friction', self.skin_friction, ''],
['Air Resistance', self.air_resistance, ''],
['Flap Force', self.flap_force, ''],
['Net Force', self.net_force, ''],
['Resultant Thrust', self.thrust_force, ''],
[''],
['---THURST & POWER---'],
['Thrust Magnitude', np.sqrt(self.thrust_force[0]**2+self.thrust_force[1]**2), 'N'],
['Effective Thrust', -self.thrust_force[0], 'N'],
['Eff. Power', -self.thrust_force[0]*self.speed/1000, 'kW'],
['Eff. Horsepower', -self.thrust_force[0]*self.speed/1000/0.7457, 'hp'],
[''],
['---EOM MATRICES---'],
['Mass matrix, [kg, kg*m/rad; kg*m, kg*m\u00B2/rad]', self.mass_matrix, ''],
['Damping matrix, [kg/s, kg*m/(s*rad); kg*m/s, kg*m\u00B2/(s*rad)]', self.damping_matrix, ''],
['Restoring matrix, [N/m, N/rad; N, N*m/rad]', self.restoring_matrix, ''],
[''],
['---PORPOISING---'],
['[[Eigenvalue check result, Est. pitch settling time (s)],\n [Savitsky chart result, Critical trim angle (deg)]]', np.array(self.porpoising), ''],
[''],
['---BEHAVIOR IN WAVES---'],
['H_sig', self.H_sig, 'm, significant wave heigth'],
['R_AW', self.R_AW, 'N, added resistance in waves'],
['Average impact acceleration [n_cg, n_bow] (g\'s)', self.avg_impact_acc, ''],
]
cLens=[16,0,0] #Min spacing for columns
for row in table:
if len(row)==3:
if row[1] is None:
print('{desc:<{cL0}} {val:<{cL1}} {unit:<{cL2}}'.format(desc=row[0], val=row[1], unit='None', cL0='', cL1=cLens[1], cL2=cLens[2]))
elif isinstance(row[1], (list,np.ndarray)):
print(row[0]+' =')
with np.printoptions(formatter={'float': f'{{:.{sigFigs}g}}'.format}):
print(row[1])
print(row[2])
else:
print('{desc:<{cL0}} {val:<{cL1}.{sNum}g} {unit:<{cL2}}'.format(desc=row[0], val=row[1], unit=row[2], cL0=cLens[0], cL1=cLens[1], cL2=cLens[2], sNum=sigFigs))
else:
print(row[0])
def get_geo_lengths(self):
"""This function outputs the geometric lengths.
Adds/updates the following attributes:
- :attr:`L_K`
- :attr:`L_C`
- :attr:`lambda_W`
- :attr:`x_s`
- :attr:`z_max`
"""
b = self.beam
lcg = self.lcg
vcg = self.vcg
z_wl = self.z_wl
tau = self.tau
beta = self.beta
eta_3 = self.eta_3
eta_5 = self.eta_5
pi = np.pi
wetted_lengths_type = self.wetted_lengths_type
z_max_type = self.z_max_type
#Keel wetted length, Eq. 9.50 of Faltinsen 2005, page 367
L_K = lcg + vcg / np.tan(pi/180*(tau + eta_5)) - (z_wl + eta_3) / np.sin(pi/180*(tau + eta_5))
if L_K < 0:
L_K = 0
if wetted_lengths_type == 1:
#z_max/Vt coefficient, Table 8.3 of Faltinsen 2005, page 303---------------
beta_table = [4, 7.5, 10, 15, 20, 25, 30, 40]
z_max_table = [0.5695, 0.5623, 0.5556, 0.5361, 0.5087, 0.4709, 0.4243, 0.2866]
#Extrapolation warning
if beta < beta_table[0] or beta > beta_table[-1]:
warnings.warn('Deadrise ({0:.3f}) outside the interpolation range of 4-40 deg (Table 8.3 of Faltinsen 2005). Extrapolated values might be inaccurate.'.format(beta), stacklevel=2)
if z_max_type == 1:
z_max = np.polyval([-2.100644618790201e-006, -6.815747611588763e-005, -1.130563334939335e-003, 5.754510457848798e-001], beta)
elif z_max_type == 2:
z_max_func = interpolate.interp1d(beta_table, z_max_table, kind='cubic', fill_value='extrapolate') #Interpolation of the table
z_max = z_max_func(beta)
#--------------------------------------------------------------------------
#Distance from keel/water-line intersection to start of wetted chine (Eq. 9.10 of Faltinsen)
x_s = 0.5 * b * np.tan(pi/180*beta) / ((1 + z_max) * (pi/180)*(tau + eta_5))
if x_s < 0:
x_s = 0
#Chine wetted length, Eq. 9.51 of Faltinsen 2005
L_C = L_K - x_s
if L_C < 0:
L_C = 0
x_s = L_K
warnings.warn('Vessel operating with dry chines (L_C = 0).', stacklevel=2)
#Mean wetted length-to-beam ratio
lambda_W = (L_K + L_C) / (2 * b)
elif wetted_lengths_type == 2:
#Eq. 3 of Savitsky '64
x_s = b/pi*np.tan(pi/180*beta)/np.tan(pi/180*(tau + eta_5))
#Chine wetted length
L_C = L_K - x_s
if L_C < 0:
L_C = 0
x_s = L_K
warnings.warn('Vessel operating with dry chines (L_C = 0).', stacklevel=2)
#Mean wetted length-to-beam ratio
lambda_W = (L_K + L_C)/(2*b)
#z_max/Vt coefficient (E. 9.10 of Faltinsen 2005 rearranged)
z_max = 0.5 * b * np.tan(pi/180*beta) / (x_s * (pi/180)*(tau + eta_5)) - 1
elif wetted_lengths_type == 3:
#Eq. 12 of Savitsky '76
w = (0.57 + beta/1000)*(np.tan(pi/180*beta)/(2*np.tan(pi/180*(tau+eta_5)))-beta/167)
lambda_K = L_K/b
#Eq. 14 of Savitsky '76
lambda_C = (lambda_K-w)-0.2*np.exp(-(lambda_K-w)/0.3)
if lambda_C < 0:
lambda_C = 0
L_C = lambda_C*b
#Mean wetted length-to-beam ratio, Eq. 15 of Savitsky '76
lambda_W = (lambda_K + lambda_C)/2+0.03
x_s = L_K-L_C
#z_max/Vt coefficient (E. 9.10 of Faltinsen 2005 rearranged)
z_max = 0.5 * b * np.tan(pi/180*beta) / (x_s * (pi/180)*(tau + eta_5)) - 1
if self.length is not None:
if L_K > self.length:
warnings.warn('The estimated wetted chine length ({0:.3f}) is larger than the vessel length ({1:.3f}).'.format(L_K, self.length), stacklevel=2)
#Update values
self.L_K = L_K
self.L_C = L_C
self.lambda_W = lambda_W
self.x_s = x_s
self.z_max = z_max
def get_forces(self, runGeoLengths=True):
"""This function calls all the force functions to update the respective object attributes.
Adds/updates the following attributes:
- :attr:`hydrodynamic_force`
- :attr:`skin_friction`
- :attr:`air_resistance`
- :attr:`flap_force`
- :attr:`thrust_force`
- :attr:`net_force`
Args:
runGeoLengths (boolean, optional): Calculate the wetted lengths before calculating the forces. Defaults to True.
Methods:
get_hydrodynamic_force(): This function follows Savitsky 1964 and Faltinsen 2005 in calculating the vessel's hydrodynamic forces and moment.
get_skin_friction(): This function outputs the frictional force of the vessel using ITTC 1957 and the Bowden and Davison 1974 roughness coefficient.
get_air_resistance(): This function estimates the air drag. It assumes a square shape projected area with a shape coefficient.
get_flap_force(): This function outputs the flap forces w.r.t. global coordinates (Savitsky & Brown 1976). Horz: Positive Aft, Vert: Positive Up, Moment: Positive CCW.
sum_forces(): This function gets the sum of forces and moments, and consequently the required net thrust. The coordinates are positive aft, positive up, and positive counterclockwise.
"""
if runGeoLengths:
self.get_geo_lengths() #Calculated wetted lengths in get_forces()
g = self.g
rho_air = self.rho_air
C_D = self.C_D
rho = self.rho
nu = self.nu
AHR = self.ahr
W = self.weight
epsilon = self.epsilon
vT = self.vT
lT = self.lT
U = self.speed
b = self.beam
lcg = self.lcg
vcg = self.vcg
Lf = self.Lf
sigma = self.sigma
delta = self.delta
beam = self.beam
l_air = self.l_air
h_air = self.h_air
b_air = self.b_air
C_shape = self.C_shape
z_wl = self.z_wl
tau = self.tau
beta = self.beta
eta_3 = self.eta_3
eta_5 = self.eta_5
L_K = self.L_K
L_C = self.L_C
lambda_W = self.lambda_W
x_s = self.x_s
z_max = self.z_max
pi = np.pi
def get_hydrodynamic_force():
"""This function follows Savitsky 1964 and Faltinsen 2005 in calculating the vessel's hydrodynamic forces and moment.
"""
#Beam Froude number
Fn_B = U/np.sqrt(g*b)
#Warnings
if Fn_B < 0.6 or Fn_B > 13:
warnings.warn('Beam Froude number = {0:.3f}, outside of range of applicability (0.60 <= U/sqrt(g*b) <= 13.00) for planing lift equation. Results are extrapolations.'.format(Fn_B), stacklevel=2)
if lambda_W > 4:
warnings.warn('Mean wetted length-beam ratio = {0:.3f}, outside of range of applicability (lambda <= 4) for planing lift equation. Results are extrapolations.'.format(lambda_W), stacklevel=2)
if tau < 2 or tau > 15:
warnings.warn('Vessel trim = {0:.3f}, outside of range of applicability (2 deg <= tau <= 15 deg) for planing lift equation. Results are extrapolations.'.format(tau), stacklevel=2)
#0-Deadrise lift coefficient
C_L0 = (tau + eta_5)**1.1 * (0.012 * lambda_W**0.5 + 0.0055 * lambda_W**2.5 / Fn_B**2)
#Lift coefficient with deadrise, C_Lbeta
C_Lbeta = C_L0 - 0.0065 * beta * C_L0**0.6
#Vertical force (lift)
F_z = C_Lbeta * 0.5 * rho * U**2 * b**2
#Horizontal force
F_x = F_z*np.tan(pi/180*(tau + eta_5))
#Lift's Normal force w.r.t. keel
F_N = F_z / np.cos(pi/180*(tau + eta_5))
#Longitudinal position of the center of pressure, l_p (Eq. 4.41, Doctors 1985)
l_p = lambda_W * b * (0.75 - 1 / (5.21 * (Fn_B / lambda_W)**2 + 2.39)) #Limits for this is (0.60 < Fn_B < 13.0, lambda < 4.0)
#Moment about CG (Axis consistent with Fig. 9.24 of Faltinsen (P. 366)
M_cg = - F_N * (lcg - l_p)
#Update values
self.hydrodynamic_force = np.array([F_x, F_z, M_cg])
def get_skin_friction():
"""This function outputs the frictional force of the vessel using ITTC 1957 and the Bowden and Davison 1974 roughness coefficient.
"""
#Surface area of the dry-chine region
S1 = x_s * b / (2 * np.cos(pi/180*beta))
if L_K < x_s:
S1 = S1 * (L_K / x_s)**2
#Surface area of the wetted-chine region
S2 = b * L_C / np.cos(pi/180*beta)
#Total surface area
S = S1 + S2
if S == 0:
F_x = 0
F_z = 0
M_cg = 0
else:
#Mean bottom fluid velocity, Savitsky 1964 - Hadler's empirical formula
V_m = U * np.sqrt(1 - (0.012 * tau**1.1 * np.sqrt(lambda_W) - 0.0065 * beta * (0.012 * np.sqrt(lambda_W) * tau**1.1)**0.6) / (lambda_W * np.cos(tau * pi/180)))
#Reynolds number (with bottom fluid velocity)
Rn = V_m * lambda_W * b / nu
#'Friction coefficient' ITTC 1957
C_f = 0.075/(np.log10(Rn) - 2)**2
#Additional 'friction coefficient' due to skin friction, Bowden and Davison (1974)
deltaC_f = (44*((AHR/(lambda_W*b))**(1/3) - 10*Rn**(-1/3)) + 0.125)/10**3
#Frictional force
R_f = 0.5 * rho * (C_f + deltaC_f) * S * U**2
#Geometric vertical distance from keel
l_f = (b / 4 * np.tan(pi/180*beta) * S2 + b / 6 * np.tan(pi/180*beta) * S1) / (S1 + S2)
#Horizontal force
F_x = R_f * np.cos(pi/180*(tau + eta_5))
#Vertical force
F_z = - R_f * np.sin(pi/180*(tau + eta_5))
#Moment about CG (Axis consistent with Fig. 9.24 of Faltinsen (P. 366))
M_cg = R_f * (l_f - vcg)
#Update values
self.skin_friction = np.array([F_x, F_z, M_cg])
def get_air_resistance():
"""This function estimates the air drag. It assumes a square shape projected area with a shape coefficient.
"""
if C_shape == 0 or b_air == 0:
self.air_resistance = np.array([0, 0, 0])
return
#Vertical distance from calm water line to keel at LOA
a_dist = np.sin(pi/180*(tau + eta_5))*(l_air-L_K)
#Vertical distance from keel to horizontal line level with boat's height
b_dist = np.cos(pi/180*(tau + eta_5))*h_air
#Vertical distance from CG to center of square (moment arm, positive is CG above)
momArm = z_wl - (a_dist + b_dist)/2
#Square projected area
Area = (a_dist+b_dist)*b_air*C_shape
if Area < 0:
Area = 0
#Horizontal force (Positive aft)
F_x = 0.5*rho_air*C_D*Area*U**2
#Vertical force (Positive up)
F_z = 0
#Moment (positve CCW)
M_cg = -F_x*momArm
#Update values
self.air_resistance = np.array([F_x, F_x, M_cg])
def get_flap_force():
"""This function outputs the flap forces w.r.t. global coordinates (Savitsky & Brown 1976). Horz: Positive Aft, Vert: Positive Up, Moment: Positive CCW.
"""
if Lf == 0:
self.flap_force = np.array([0, 0, 0])
return
#Warnings
if Lf > 0.10*(L_K + L_C)/2 or Lf < 0:
warnings.warn('Flap chord = {0:.3f} outside of bounds (0-10% of mean wetted length) for flap forces estimates with Savitsky & Brown 1976'.format(Lf), stacklevel=2)
if delta < 0 or delta > 15:
warnings.warn('Flap deflection angle = {0:.3f} out of bounds (0-15 deg) for flap forces estimates with Savitsky & Brown 1976'.format(delta), stacklevel=2)
Fn_B = U/np.sqrt(g*b)
if Fn_B < 2 or Fn_B > 7:
warnings.warn('Beam-based Froude number Fn_B = {0:.3f} out of bounds (2-7) for flap forces estimates with Savitsky & Brown 1976'.format(Fn_B), stacklevel=2)
F_z = 0.046*(Lf*3.28084)*delta*sigma*(b*3.28084)*(rho/515.379)/2*(U*3.28084)**2*4.44822
F_x = 0.0052*F_z*(tau+eta_5+delta)
l_flap = 0.6*b+Lf*(1-sigma)
M_cg = -F_z*(lcg-l_flap)
#Update values
self.flap_force = np.array([F_x, F_z, M_cg])
def sum_forces():
"""This function gets the sum of forces and moments, and consequently the required net thrust. The coordinates are positive aft, positive up, and positive counterclockwise.
"""
#Call all force functions-------
get_hydrodynamic_force()
get_skin_friction()
get_air_resistance()
get_flap_force()
#-------------------------------
forcesMatrix = np.column_stack((self.gravity_force, self.hydrodynamic_force, self.skin_friction, self.air_resistance, self.flap_force)) #Forces and moments
F_sum = np.sum(forcesMatrix, axis=1) #F[0] is x-dir, F[1] is z-dir, and F[2] is moment
#Required thrust and resultant forces
T = F_sum[0]/np.cos(pi/180*(epsilon+tau+eta_5)); #Magnitude
T_z = T*np.sin(pi/180*(epsilon+tau+eta_5)); #Vertical
T_cg = T*np.cos(pi/180*epsilon)*(vcg - vT) - T*np.sin(pi/180*epsilon)*(lcg - lT); #Moment about cg
#Update resultant thurst values
self.thrust_force = np.array([-F_sum[0], T_z, T_cg])
#Include resultant thrust forces in sum
F_sum[1] = F_sum[1]+T_z
F_sum[2] = F_sum[2]+T_cg
#Update values
self.net_force = F_sum
#Call functions
sum_forces()
def get_steady_trim(self, x0=[0, 3], tauLims=[0.5, 35], tolF=10**-6, maxiter=50):
"""This function finds and sets the equilibrium point when the vessel is steadily running in calm water.
Updates the following attributes:
- :attr:`z_wl`
- :attr:`tau`
Args:
x0 (list of float): Initial guess for equilibirum point [z_wl (m), tau (deg)]. Defaults to [0, 3].
tauLims (list of float): Limits for equilibrium trim search. Defaults to [0.5, 35].
tolF (float): Tolerance for convergence to zero. Defaults to 10**-6.
maxiter (float): Maximum iterations. Defaults to 50.
"""
def _boatForces(x):
self.z_wl = x[0]/10 #the division is for normalization of the variables
self.tau = x[1]
self.get_forces()
return self.net_force[1:3]
def _boatForcesPrime(x):
return ndmath.complexGrad(_boatForces, x)
def _L_K(x):
# self.z_wl = x[0]/10
# self.tau = x[1]
# self.get_geo_lengths() #No need to call, because ndmath's nDimNewton allways calls the obj function before calling this "constraint"
return [-self.L_K]
xlims = np.array([[-np.Inf, np.Inf], tauLims])
warnings.filterwarnings("ignore", category=UserWarning)
[self.z_wl, self.tau] = ndmath.nDimNewton(_boatForces, x0, _boatForcesPrime, tolF, maxiter, xlims, hehcon=_L_K)/[10, 1]
warnings.filterwarnings("default", category=UserWarning)
def get_eom_matrices(self, runGeoLengths=True):
"""This function returns the mass, damping, and stiffness matrices following Faltinsen 2005.
Adds/updates the following parameters:
- :attr:`mass_matrix`
- :attr:`damping_matrix`
- :attr:`restoring_matrix`
Args:
runGeoLengths (boolean, optional): Calculate the wetted lengths before calculating the EOM matrices. Defaults to True.
Methods:
get_mass_matrix(): This function returns the added mass coefficients following Sec. 9.4.1 of Faltinsen 2005, including weight and moment of inertia.
get_damping_matrix(): This function returns the damping coefficients following Sec. 9.4.1 of Faltinsen 2005.
get_restoring_matrix(diffType=1, step=10**-6.6): This function returns the restoring coefficients following the approach in Sec. 9.4.1 of Faltinsen 2005.
"""
if runGeoLengths:
self.get_geo_lengths() #Calculated wetted lengths in get_eom_matrices()
W = self.weight
U = self.speed
rho = self.rho
b = self.beam
lcg = self.lcg
tau = self.tau
beta = self.beta
g = self.g
r_g = self.r_g
eta_5 = self.eta_5
L_K = self.L_K
L_C = self.L_C
lambda_W = self.lambda_W
x_s = self.x_s
z_max = self.z_max
pi = np.pi
def get_mass_matrix():
"""This function returns the added mass coefficients following Sec. 9.4.1 of Faltinsen 2005, including weight and moment of inertia
"""
#Distance of CG from keel-WL intersection
x_G = L_K - lcg
#K constant (Eq. 9.63 of Faltinsen 2005)
K = (pi / np.sin(pi/180*beta) * gamma(1.5 - beta/180) / (gamma(1 - beta/180)**2 * gamma(0.5 + beta/180)) - 1) / np.tan(pi/180*beta)
kappa = (1 + z_max) * (pi/180)*(tau + eta_5) #User defined constant
#Based on Faltinsen's
A1_33 = rho * kappa**2 * K * x_s**3 / 3
A1_35 = A1_33 * (x_G - x_s * 3/4)
A1_53 = A1_35
A1_55 = A1_33 * (x_G**2 - 3/2 * x_G * x_s + 3/5 * x_s**2)
#Contribution from wet-chine region
if L_C > 0:
C_1 = 2 * np.tan(pi/180*beta)**2 / pi * K
A2_33 = (rho * b**3) * C_1 * pi / 8 * L_C / b
A2_35 = (rho * b**4) * (- C_1 * pi / 16 * ((L_K / b)**2 - (x_s / b)**2) + x_G / b * A2_33 / (rho * b**3))
A2_53 = A2_35
A2_55 = (rho * b**5) * (C_1 * pi / 24 * ((L_K / b)**3 - (x_s / b)**3) - C_1 / 8 * pi * (x_G / b) * ((L_K / b)**2 - (x_s / b)**2) + (x_G / b)**2 * A2_33 / (rho * b**3))
else:
A2_33 = 0
A2_35 = 0
A2_53 = 0
A2_55 = 0
#Total added mass & update values
A_33 = A1_33 + A2_33 + W/g # kg, A_33
A_35 = A1_35 + A2_35 # kg*m/rad, A_35
A_53 = A1_53 + A2_53 # kg*m, A_53
A_55 = A1_55 + A2_55 + W/g*r_g**2 # kg*m^2/rad, A_55
self.mass_matrix = np.array([[A_33, A_35], [A_53, A_55]])
def get_damping_matrix():
"""This function returns the damping coefficients following Sec. 9.4.1 of Faltinsen 2005
"""
#Heave-heave added mass (need to substract W/g since it was added)
A_33 = self.mass_matrix[0,0] - W/g
if L_C > 0:
d = 0.5 * b * np.tan(pi/180*beta)
else:
d = (1 + z_max) * (pi/180)*(tau + eta_5) * L_K
#K constant (Eq. 9.63 of Faltinsen 2005, P. 369)
K = (pi / np.sin(pi/180*beta) * gamma(1.5 - beta/180) / (gamma(1 - beta/180)**2 * gamma(0.5 + beta/180)) - 1) / np.tan(pi/180*beta)
#2D Added mass coefficient in heave
a_33 = rho * d**2 * K
#Infinite Fn lift coefficient
C_L0 = (tau + eta_5)**1.1 * 0.012 * lambda_W**0.5
#Derivative w.r.t. tau (rad) of inf. Fn C_L0
dC_L0 = (180 / pi)**1.1 * 0.0132 * (pi/180*(tau + eta_5))**0.1 * lambda_W**0.5
#Derivative w.r.t. tau (rad) of inf. Fn C_Lbeta
dC_Lbeta = dC_L0 * (1 - 0.0039 * beta * C_L0**-0.4)
#Damping coefficients & update values
B_33 = rho / 2 * U * b**2 * dC_Lbeta # kg/s, B_33, Savitsky based
B_35 = - U * (A_33 + lcg * a_33) # kg*m/(s*rad), B_35, Infinite frequency based
B_53 = B_33 * (0.75 * lambda_W * b - lcg) # kg*m/s, B_53, Savitsky based
B_55 = U * lcg**2 * a_33 # kg*m**2/(s*rad), B_55, Infinite frequency based
self.damping_matrix = np.array([[B_33, B_35], [B_53, B_55]])
def get_restoring_matrix(diffType=1, step=10**-6.6):
"""This function returns the restoring coefficients following the approach in Sec. 9.4.1 of Faltinsen 2005
Args:
diffType (int, optional): 1 (recommended) = Complex step method, 2 = Foward step difference. Defaults to 1.
step (float, optional): Step size if using diffType == 2. Defaults to 10**-6.
"""
def _func(eta):
self.eta_3 = eta[0]
self.eta_5 = eta[1]
self.get_forces()
return self.net_force[1:3]
temp_eta_3 = self.eta_3
temp_eta_5 = self.eta_5
if diffType == 1:
C_full = -ndmath.complexGrad(_func, [temp_eta_3, temp_eta_5])
elif diffType == 2:
C_full = -ndmath.finiteGrad(_func, [temp_eta_3, temp_eta_5], 10**-6.6)
#Reset values
self.eta_3 = temp_eta_3
self.eta_5 = temp_eta_5
self.get_forces()
#Conversion deg to rad (degree in denominator)
C_full[0,1] = C_full[0,1] / (pi/180) # N/rad, C_35
C_full[1,1] = C_full[1,1] / (pi/180) # N*m/rad, C_55
#Update values
self.restoring_matrix = C_full
#Call functions
get_mass_matrix()
get_damping_matrix()
get_restoring_matrix()
def check_porpoising(self, stepEstimateType=1):
"""This function checks for porpoising.
Adds/updates the following parameters:
- :attr:`porpoising` (list):
Args:
stepEstimateType (int, optional): Pitch step response settling time estimate type, 1 = -3/np.real(eigVals[0])], 2 = Time-domain simulation estimate. Defaults to 1.
"""
#Eigenvalue analysis
try:
self.mass_matrix
except AttributeError:
warnings.warn('No Equation Of Motion (EOM) matrices found. Running get_eom_matrices().', stacklevel=2)
self.get_eom_matrices()
M = self.mass_matrix
C = self.damping_matrix
K = self.restoring_matrix
nDim = len(M)
A_ss = np.concatenate((np.concatenate((np.zeros((nDim,nDim)), np.identity(nDim)), axis=1), np.concatenate((-np.linalg.solve(M,K), -np.linalg.solve(M,C)), axis=1))) #State space reprecentation
eigVals = np.linalg.eigvals(A_ss)
eig_porpoise = any(eigVal >= 0 for eigVal in eigVals)
if stepEstimateType == 1:
settling_time = -3/np.real(eigVals[0])
elif stepEstimateType == 2:
B_ss = np.array([[1],[0],[0],[0]]) #Pitch only
C_ss = np.array([[1,0,0,0]]) #Pitch only
D_ss = np.array([[0]])
system = (A_ss,B_ss,C_ss,D_ss)
t, y = signal.step(system)
settling_time = (t[next(len(y)-i for i in range(2,len(y)-1) if abs(y[-i]/y[-1])>1.02)]-t[0])
#Savitsky '64 chart method
C_L = self.weight/(1/2*self.rho*self.speed**2*self.beam**2)
x = np.sqrt(C_L/2)
#Warnings
if x > 0.3 or x < 0.13:
warnings.warn('Lift Coefficient = {0:.3f} outside of bounds (0.0338-0.18) for porpoising estimates with Savitsky 1964. Results are extrapolations.'.format(C_L), stacklevel=2)
if self.beta > 20:
warnings.warn('Deadrise = {0:.3f} outside of bounds (0-20 deg) for porpoising estimates with Savitsky 1964. Results are extrapolations.'.format(self.beta), stacklevel=2)
tau_crit_0 = -376.37*x**3 + 329.74*x**2 - 38.485*x + 1.3415
tau_crit_10 = -356.05*x**3 + 314.36*x**2 - 41.674*x + 3.5786
tau_crit_20 = -254.51*x**3 + 239.65*x**2 - 23.936*x + 3.0195
tau_crit_func = interpolate.interp1d([0, 10, 20], [tau_crit_0, tau_crit_10, tau_crit_20], kind='quadratic', fill_value='extrapolate')
tau_crit = tau_crit_func(self.beta)
if self.tau > tau_crit:
chart_porpoise = True
else:
chart_porpoise = False
#Update values
self.porpoising = [[eig_porpoise, settling_time], [chart_porpoise, float(tau_crit)]]
def get_seaway_behavior(self):
"""This function calculates the seaway behavior as stated in Savitsky & Brown '76.
Adds/updates the following parameters:
- :attr:`avg_impact_acc`
- :attr:`R_AW`
"""
if self.H_sig is None:
self.H_sig = self.beam*0.5 #Arbitrary wave height if no user-defined wave height
warnings.warn('Significant wave height has not been specified. Using beam*0.5 = {0:.3f} m.'.format(self.H_sig), stacklevel=2)
if self.length is None:
self.length = self.beam*3
warnings.warn('Vessel length has not been specified. Using beam*3 = {0:.3f} m.'.format(self.length), stacklevel=2)
H_sig = self.H_sig
W = self.weight
beta = self.beta
tau = self.tau
pi = np.pi
Delta_LT = W/9964 #Displacement in long tons
Delta = Delta_LT*2240 #Displacement in lbf
L = self.length*3.281 #Length in ft
b = self.beam*3.281 #Beam in ft
Vk = self.speed*1.944 #Speed in knots
Vk_L = Vk/np.sqrt(L) #Vk/sqrt(L)
H_sig = H_sig*3.281 #Significant wave height in ft
w = self.rho*self.g/(4.448*35.315) #Specific weight in lbf/ft^3
C_Delta = Delta/(w*b**3) #Static beam-loading coefficient
if self.seaway_drag_type == 1: #Savitsky '76
#Check that variables are inside range of applicability (P. 395 of Savitsky & Brown '76)
P1 = Delta_LT/(0.01*L)**3
P2 = L/b
P5 = H_sig/b
P6 = Vk_L
if P1 < 100 or P1 > 250:
warnings.warn('Vessel displacement coefficient = {0:.3f}, outside of range of applicability (100 <= Delta_LT/(0.01*L)^3 <= 250, with units LT/ft^3). Results are extrapolations.'.format(P1), stacklevel=2)
if P2 < 3 or P2 > 5:
warnings.warn('Vessel length/beam = {0:.3f}, outside of range of applicability (3 <= L/b <= 5). Results are extrapolations.'.format(P2), stacklevel=2)
if tau < 3 or tau > 7:
warnings.warn('Vessel trim = {0:.3f}, outside of range of applicability (3 deg <= tau <= 7 deg). Results are extrapolations.'.format(tau), stacklevel=2)
if beta < 10 or beta > 30:
warnings.warn('Vessel deadrise = {0:.3f}, outside of range of applicability (10 deg <= beta <= 30 deg). Results are extrapolations.'.format(beta), stacklevel=2)
if P5 < 0.2 or P5 > 0.7:
warnings.warn('Significant wave height / beam = {0:.3f}, outside of range of applicability (0.2 <= H_sig/b <= 0.7). Results are extrapolations.'.format(P5), stacklevel=2)
if P6 < 2 or P6 > 6:
warnings.warn('Speed coefficient = {0:.3f}, outside of range of applicability (2 <= Vk/sqrt(L) <= 6, with units knots/ft^0.5). Results are extrapolations.'.format(P6), stacklevel=2)
R_AW_2 = (w*b**3)*66*10**-6*(H_sig/b+0.5)*(L/b)**3/C_Delta+0.0043*(tau-4) #Added resistance at Vk/sqrt(L) = 2
R_AW_4 = (Delta)*(0.3*H_sig/b)/(1+2*H_sig/b)*(1.76-tau/6-2*np.tan(beta*pi/180)**3) #Vk/sqrt(L) = 4
R_AW_6 = (w*b**3)*(0.158*H_sig/b)/(1+(H_sig/b)*(0.12*beta-21*C_Delta*(5.6-L/b)+7.5*(6-L/b))) #Vk/sqrt(L) = 6
R_AWs = np.array([R_AW_2, R_AW_4, R_AW_6])
R_AWs_interp = interpolate.interp1d([2,4,6], R_AWs, kind='quadratic', fill_value='extrapolate')
R_AW = R_AWs_interp([Vk_L])[0]
elif self.seaway_drag_type == 2: #Fridsma '71 design charts
#Check that variables are inside range of applicability (P. R-1495 of Fridsma '71)
if C_Delta < 0.3 or C_Delta > 0.9:
warnings.warn('C_Delta = {0:.3f}, outside of range of applicability (0.3 <= C_Delta <= 0.9). Results are extrapolations'.format(C_Delta), stacklevel=2)
if L/b < 3 or L/b > 6:
warnings.warn('L/b = {0:.3f}, outside of range of applicability (3 <= L/b <= 6). Results are extrapolations'.format(L/b), stacklevel=2)
if C_Delta/(L/b) < 0.06 or C_Delta/(L/b) > 0.18:
warnings.warn('C_Delta/(L/b) = {0:.3f}, outside of range of applicability (0.06 <= C_Delta/(L/b) <= 0.18). Results are extrapolations'.format(C_Delta/(L/b)), stacklevel=2)
if tau < 3 or tau > 7:
warnings.warn('tau = {0:.3f}, outside of range of applicability (3 <= tau <= 7). Results are extrapolations'.format(tau), stacklevel=2)
if beta < 10 or beta > 30:
warnings.warn('beta = {0:.3f}, outside of range of applicability (10 <= beta <= 30). Results are extrapolations'.format(beta), stacklevel=2)
if H_sig/b > 0.8:
warnings.warn('H_sig/b = {0:.3f}, outside of range of applicability (H_sig/b <= 0.8). Results are extrapolations'.format(H_sig/b), stacklevel=2)
if Vk_L > 6:
warnings.warn('Vk_L = {0:.3f}, outside of range of applicability (Vk_L <= 6). Results are extrapolations'.format(Vk_L), stacklevel=2)
#Get data tables (required for when package is distributed)
Raw2_tab = pkg_resources.resource_filename(__name__, 'tables\Raw_0.2.csv')
Raw4_tab = pkg_resources.resource_filename(__name__, 'tables\Raw_0.4.csv')
Raw6_tab = pkg_resources.resource_filename(__name__, 'tables\Raw_0.6.csv')
V2_tab = pkg_resources.resource_filename(__name__, 'tables\V_0.2.csv')
V4_tab = pkg_resources.resource_filename(__name__, 'tables\V_0.4.csv')
RawV2_tab = pkg_resources.resource_filename(__name__, 'tables\Raw_V_0.2.csv')
RawV4_tab = pkg_resources.resource_filename(__name__, 'tables\Raw_V_0.4.csv')
RawV6_tab = pkg_resources.resource_filename(__name__, 'tables\Raw_V_0.6.csv')
#Read values from extracted chart points
arr_Raw2 = np.genfromtxt(Raw2_tab, delimiter=',', skip_header=1)
arr_Raw4 = np.genfromtxt(Raw4_tab, delimiter=',', skip_header=1)
arr_Raw6 = np.genfromtxt(Raw6_tab, delimiter=',', skip_header=1)
arr_V2 = np.genfromtxt(V2_tab, delimiter=',', skip_header=1)
arr_V4 = np.genfromtxt(V4_tab, delimiter=',', skip_header=1)
arr_Raw_V2 = np.genfromtxt(RawV2_tab, delimiter=',', skip_header=1)
arr_Raw_V4 = np.genfromtxt(RawV4_tab, delimiter=',', skip_header=1)
arr_Raw_V6 = np.genfromtxt(RawV6_tab, delimiter=',', skip_header=1)
#Create interpolation functions
interp1Type = 'linear'
interp2Type = 'linear'
Raw2m_interp = interpolate.interp2d(arr_Raw2[:, 1], arr_Raw2[:, 0], arr_Raw2[:, 2], kind=interp2Type)
Raw4m_interp = interpolate.interp2d(arr_Raw4[:, 1], arr_Raw4[:, 0], arr_Raw4[:, 2], kind=interp2Type)
Raw6m_interp = interpolate.interp2d(arr_Raw6[:, 1], arr_Raw6[:, 0], arr_Raw6[:, 2], kind=interp2Type)
V2m_interp = interpolate.interp2d(arr_V2[:, 1], arr_V2[:, 0], arr_V2[:, 2], kind=interp2Type)
V4m_interp = interpolate.interp2d(arr_V4[:, 1], arr_V4[:, 0], arr_V4[:, 2], kind=interp2Type)
V6m_interp = V4m_interp
RawRaw2m_interp = interpolate.interp1d(arr_Raw_V2[:, 0], arr_Raw_V2[:, 1], kind=interp1Type, fill_value='extrapolate')
RawRaw4m_interp = interpolate.interp1d(arr_Raw_V4[:, 0], arr_Raw_V4[:, 1], kind=interp1Type, fill_value='extrapolate')
RawRaw6m_interp = interpolate.interp1d(arr_Raw_V6[:, 0], arr_Raw_V6[:, 1], kind=interp1Type, fill_value='extrapolate')
#Get values following procedure shown in Fridsma 1971 paper
VLm = [V2m_interp(beta, tau)[0], V4m_interp(beta, tau)[0], V6m_interp(beta, tau)[0]]
Rwbm = [Raw2m_interp(beta, tau)[0], Raw4m_interp(beta, tau)[0], Raw6m_interp(beta, tau)[0]]
VVm = Vk_L/VLm
RRm = [RawRaw2m_interp(VVm[0]), RawRaw4m_interp(VVm[1]), RawRaw6m_interp(VVm[2])]
Rwb = np.multiply(RRm, Rwbm)
E1 = lambda H_sig: 1 + ((L/b)**2/25 - 1)/(1 + 0.895*(H_sig/b - 0.6)) #V/sqrt(L) = 2
E2 = lambda H_sig: 1 + 10*H_sig/b*(C_Delta/(L/b) - 0.12) #V/sqrt(L) = 4
E3 = lambda H_sig: 1 + 2*H_sig/b*(0.9*(C_Delta-0.6)-0.7*(C_Delta-0.6)**2) #V/sqrt(L) = 6
E_interp = lambda H_sig: interpolate.interp1d([2, 4, 6], [E1(H_sig), E2(H_sig), E3(H_sig)], kind=interp1Type, fill_value='extrapolate')
E = [E_interp(0.2*b)(Vk_L), E_interp(0.4*b)(Vk_L), E_interp(0.6*b)(Vk_L)]
Rwb_final = np.multiply(Rwb,E)
Rwb_final_interp = interpolate.interp1d([0.2, 0.4, 0.6], Rwb_final, kind=interp1Type, fill_value='extrapolate')
R_AW = Rwb_final_interp(H_sig/b)*w*b**3
warnings.warn('Average impact acceleration based on the Fridsma charts is currently not implemented. Using Savitsky & Brown approximation.', stacklevel=2)
n_cg = 0.0104*(H_sig/b+0.084)*tau/4*(5/3-beta/30)*(Vk_L)**2*L/b/C_Delta #g, at CG
n_bow = n_cg*(1+3.8*(L/b-2.25)/(Vk_L)) #g, at bow
avg_impact_acc = np.array([n_cg, n_bow])
#Update values
self.avg_impact_acc = avg_impact_acc
self.R_AW = R_AW*4.448 #lbf to N conversion
| [
"numpy.log10",
"numpy.sqrt",
"ndmath.complexGrad",
"numpy.column_stack",
"scipy.interpolate.interp1d",
"numpy.array",
"numpy.sin",
"numpy.genfromtxt",
"scipy.interpolate.interp2d",
"ndmath.nDimNewton",
"scipy.signal.step",
"numpy.multiply",
"numpy.exp",
"numpy.real",
"numpy.polyval",
"... | [((10728, 10758), 'numpy.array', 'np.array', (['[0, -self.weight, 0]'], {}), '([0, -self.weight, 0])\n', (10736, 10758), True, 'import numpy as np\n'), ((33506, 33544), 'numpy.array', 'np.array', (['[[-np.Inf, np.Inf], tauLims]'], {}), '([[-np.Inf, np.Inf], tauLims])\n', (33514, 33544), True, 'import numpy as np\n'), ((33553, 33608), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'UserWarning'}), "('ignore', category=UserWarning)\n", (33576, 33608), False, 'import warnings\n'), ((33745, 33801), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""default"""'], {'category': 'UserWarning'}), "('default', category=UserWarning)\n", (33768, 33801), False, 'import warnings\n'), ((41166, 41189), 'numpy.linalg.eigvals', 'np.linalg.eigvals', (['A_ss'], {}), '(A_ss)\n', (41183, 41189), True, 'import numpy as np\n'), ((41855, 41871), 'numpy.sqrt', 'np.sqrt', (['(C_L / 2)'], {}), '(C_L / 2)\n', (41862, 41871), True, 'import numpy as np\n'), ((42549, 42670), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (['[0, 10, 20]', '[tau_crit_0, tau_crit_10, tau_crit_20]'], {'kind': '"""quadratic"""', 'fill_value': '"""extrapolate"""'}), "([0, 10, 20], [tau_crit_0, tau_crit_10, tau_crit_20],\n kind='quadratic', fill_value='extrapolate')\n", (42569, 42670), False, 'from scipy import interpolate, signal\n'), ((52146, 52169), 'numpy.array', 'np.array', (['[n_cg, n_bow]'], {}), '([n_cg, n_bow])\n', (52154, 52169), True, 'import numpy as np\n'), ((26165, 26191), 'numpy.array', 'np.array', (['[F_x, F_z, M_cg]'], {}), '([F_x, F_z, M_cg])\n', (26173, 26191), True, 'import numpy as np\n'), ((28154, 28180), 'numpy.array', 'np.array', (['[F_x, F_z, M_cg]'], {}), '([F_x, F_z, M_cg])\n', (28162, 28180), True, 'import numpy as np\n'), ((29400, 29426), 'numpy.array', 'np.array', (['[F_x, F_x, M_cg]'], {}), '([F_x, F_x, M_cg])\n', (29408, 29426), True, 'import numpy as np\n'), ((30778, 30804), 'numpy.array', 'np.array', (['[F_x, F_z, M_cg]'], {}), '([F_x, F_z, M_cg])\n', (30786, 30804), True, 'import numpy as np\n'), ((31302, 31427), 'numpy.column_stack', 'np.column_stack', (['(self.gravity_force, self.hydrodynamic_force, self.skin_friction, self.\n air_resistance, self.flap_force)'], {}), '((self.gravity_force, self.hydrodynamic_force, self.\n skin_friction, self.air_resistance, self.flap_force))\n', (31317, 31427), True, 'import numpy as np\n'), ((31463, 31491), 'numpy.sum', 'np.sum', (['forcesMatrix'], {'axis': '(1)'}), '(forcesMatrix, axis=1)\n', (31469, 31491), True, 'import numpy as np\n'), ((31931, 31963), 'numpy.array', 'np.array', (['[-F_sum[0], T_z, T_cg]'], {}), '([-F_sum[0], T_z, T_cg])\n', (31939, 31963), True, 'import numpy as np\n'), ((33182, 33216), 'ndmath.complexGrad', 'ndmath.complexGrad', (['_boatForces', 'x'], {}), '(_boatForces, x)\n', (33200, 33216), False, 'import ndmath\n'), ((33641, 33732), 'ndmath.nDimNewton', 'ndmath.nDimNewton', (['_boatForces', 'x0', '_boatForcesPrime', 'tolF', 'maxiter', 'xlims'], {'hehcon': '_L_K'}), '(_boatForces, x0, _boatForcesPrime, tolF, maxiter, xlims,\n hehcon=_L_K)\n', (33658, 33732), False, 'import ndmath\n'), ((37017, 37055), 'numpy.array', 'np.array', (['[[A_33, A_35], [A_53, A_55]]'], {}), '([[A_33, A_35], [A_53, A_55]])\n', (37025, 37055), True, 'import numpy as np\n'), ((38597, 38635), 'numpy.array', 'np.array', (['[[B_33, B_35], [B_53, B_55]]'], {}), '([[B_33, B_35], [B_53, B_55]])\n', (38605, 38635), True, 'import numpy as np\n'), ((44076, 44086), 'numpy.sqrt', 'np.sqrt', (['L'], {}), '(L)\n', (44083, 44086), True, 'import numpy as np\n'), ((46298, 46332), 'numpy.array', 'np.array', (['[R_AW_2, R_AW_4, R_AW_6]'], {}), '([R_AW_2, R_AW_4, R_AW_6])\n', (46306, 46332), True, 'import numpy as np\n'), ((46373, 46460), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (['[2, 4, 6]', 'R_AWs'], {'kind': '"""quadratic"""', 'fill_value': '"""extrapolate"""'}), "([2, 4, 6], R_AWs, kind='quadratic', fill_value=\n 'extrapolate')\n", (46393, 46460), False, 'from scipy import interpolate, signal\n'), ((15647, 15709), 'numpy.sqrt', 'np.sqrt', (['(self.thrust_force[0] ** 2 + self.thrust_force[1] ** 2)'], {}), '(self.thrust_force[0] ** 2 + self.thrust_force[1] ** 2)\n', (15654, 15709), True, 'import numpy as np\n'), ((16448, 16473), 'numpy.array', 'np.array', (['self.porpoising'], {}), '(self.porpoising)\n', (16456, 16473), True, 'import numpy as np\n'), ((18328, 18360), 'numpy.sin', 'np.sin', (['(pi / 180 * (tau + eta_5))'], {}), '(pi / 180 * (tau + eta_5))\n', (18334, 18360), True, 'import numpy as np\n'), ((19030, 19144), 'numpy.polyval', 'np.polyval', (['[-2.100644618790201e-06, -6.815747611588763e-05, -0.001130563334939335, \n 0.5754510457848798]', 'beta'], {}), '([-2.100644618790201e-06, -6.815747611588763e-05, -\n 0.001130563334939335, 0.5754510457848798], beta)\n', (19040, 19144), True, 'import numpy as np\n'), ((19877, 19951), 'warnings.warn', 'warnings.warn', (['"""Vessel operating with dry chines (L_C = 0)."""'], {'stacklevel': '(2)'}), "('Vessel operating with dry chines (L_C = 0).', stacklevel=2)\n", (19890, 19951), False, 'import warnings\n'), ((24448, 24462), 'numpy.sqrt', 'np.sqrt', (['(g * b)'], {}), '(g * b)\n', (24455, 24462), True, 'import numpy as np\n'), ((25606, 25638), 'numpy.tan', 'np.tan', (['(pi / 180 * (tau + eta_5))'], {}), '(pi / 180 * (tau + eta_5))\n', (25612, 25638), True, 'import numpy as np\n'), ((25705, 25737), 'numpy.cos', 'np.cos', (['(pi / 180 * (tau + eta_5))'], {}), '(pi / 180 * (tau + eta_5))\n', (25711, 25737), True, 'import numpy as np\n'), ((26649, 26672), 'numpy.cos', 'np.cos', (['(pi / 180 * beta)'], {}), '(pi / 180 * beta)\n', (26655, 26672), True, 'import numpy as np\n'), ((28449, 28468), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (28457, 28468), True, 'import numpy as np\n'), ((28581, 28613), 'numpy.sin', 'np.sin', (['(pi / 180 * (tau + eta_5))'], {}), '(pi / 180 * (tau + eta_5))\n', (28587, 28613), True, 'import numpy as np\n'), ((28741, 28773), 'numpy.cos', 'np.cos', (['(pi / 180 * (tau + eta_5))'], {}), '(pi / 180 * (tau + eta_5))\n', (28747, 28773), True, 'import numpy as np\n'), ((29705, 29724), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (29713, 29724), True, 'import numpy as np\n'), ((30245, 30259), 'numpy.sqrt', 'np.sqrt', (['(g * b)'], {}), '(g * b)\n', (30252, 30259), True, 'import numpy as np\n'), ((31618, 31660), 'numpy.cos', 'np.cos', (['(pi / 180 * (epsilon + tau + eta_5))'], {}), '(pi / 180 * (epsilon + tau + eta_5))\n', (31624, 31660), True, 'import numpy as np\n'), ((31685, 31727), 'numpy.sin', 'np.sin', (['(pi / 180 * (epsilon + tau + eta_5))'], {}), '(pi / 180 * (epsilon + tau + eta_5))\n', (31691, 31727), True, 'import numpy as np\n'), ((35746, 35769), 'numpy.tan', 'np.tan', (['(pi / 180 * beta)'], {}), '(pi / 180 * beta)\n', (35752, 35769), True, 'import numpy as np\n'), ((37688, 37711), 'numpy.tan', 'np.tan', (['(pi / 180 * beta)'], {}), '(pi / 180 * beta)\n', (37694, 37711), True, 'import numpy as np\n'), ((40660, 40771), 'warnings.warn', 'warnings.warn', (['"""No Equation Of Motion (EOM) matrices found. Running get_eom_matrices()."""'], {'stacklevel': '(2)'}), "(\n 'No Equation Of Motion (EOM) matrices found. Running get_eom_matrices().',\n stacklevel=2)\n", (40673, 40771), False, 'import warnings\n'), ((41327, 41346), 'numpy.real', 'np.real', (['eigVals[0]'], {}), '(eigVals[0])\n', (41334, 41346), True, 'import numpy as np\n'), ((41403, 41433), 'numpy.array', 'np.array', (['[[1], [0], [0], [0]]'], {}), '([[1], [0], [0], [0]])\n', (41411, 41433), True, 'import numpy as np\n'), ((41462, 41486), 'numpy.array', 'np.array', (['[[1, 0, 0, 0]]'], {}), '([[1, 0, 0, 0]])\n', (41470, 41486), True, 'import numpy as np\n'), ((41515, 41530), 'numpy.array', 'np.array', (['[[0]]'], {}), '([[0]])\n', (41523, 41530), True, 'import numpy as np\n'), ((41606, 41625), 'scipy.signal.step', 'signal.step', (['system'], {}), '(system)\n', (41617, 41625), False, 'from scipy import interpolate, signal\n'), ((48157, 48221), 'pkg_resources.resource_filename', 'pkg_resources.resource_filename', (['__name__', '"""tables\\\\Raw_0.2.csv"""'], {}), "(__name__, 'tables\\\\Raw_0.2.csv')\n", (48188, 48221), False, 'import pkg_resources\n'), ((48244, 48308), 'pkg_resources.resource_filename', 'pkg_resources.resource_filename', (['__name__', '"""tables\\\\Raw_0.4.csv"""'], {}), "(__name__, 'tables\\\\Raw_0.4.csv')\n", (48275, 48308), False, 'import pkg_resources\n'), ((48331, 48395), 'pkg_resources.resource_filename', 'pkg_resources.resource_filename', (['__name__', '"""tables\\\\Raw_0.6.csv"""'], {}), "(__name__, 'tables\\\\Raw_0.6.csv')\n", (48362, 48395), False, 'import pkg_resources\n'), ((48417, 48479), 'pkg_resources.resource_filename', 'pkg_resources.resource_filename', (['__name__', '"""tables\\\\V_0.2.csv"""'], {}), "(__name__, 'tables\\\\V_0.2.csv')\n", (48448, 48479), False, 'import pkg_resources\n'), ((48500, 48562), 'pkg_resources.resource_filename', 'pkg_resources.resource_filename', (['__name__', '"""tables\\\\V_0.4.csv"""'], {}), "(__name__, 'tables\\\\V_0.4.csv')\n", (48531, 48562), False, 'import pkg_resources\n'), ((48599, 48665), 'pkg_resources.resource_filename', 'pkg_resources.resource_filename', (['__name__', '"""tables\\\\Raw_V_0.2.csv"""'], {}), "(__name__, 'tables\\\\Raw_V_0.2.csv')\n", (48630, 48665), False, 'import pkg_resources\n'), ((48689, 48755), 'pkg_resources.resource_filename', 'pkg_resources.resource_filename', (['__name__', '"""tables\\\\Raw_V_0.4.csv"""'], {}), "(__name__, 'tables\\\\Raw_V_0.4.csv')\n", (48720, 48755), False, 'import pkg_resources\n'), ((48779, 48845), 'pkg_resources.resource_filename', 'pkg_resources.resource_filename', (['__name__', '"""tables\\\\Raw_V_0.6.csv"""'], {}), "(__name__, 'tables\\\\Raw_V_0.6.csv')\n", (48810, 48845), False, 'import pkg_resources\n'), ((48922, 48975), 'numpy.genfromtxt', 'np.genfromtxt', (['Raw2_tab'], {'delimiter': '""","""', 'skip_header': '(1)'}), "(Raw2_tab, delimiter=',', skip_header=1)\n", (48935, 48975), True, 'import numpy as np\n'), ((48999, 49052), 'numpy.genfromtxt', 'np.genfromtxt', (['Raw4_tab'], {'delimiter': '""","""', 'skip_header': '(1)'}), "(Raw4_tab, delimiter=',', skip_header=1)\n", (49012, 49052), True, 'import numpy as np\n'), ((49076, 49129), 'numpy.genfromtxt', 'np.genfromtxt', (['Raw6_tab'], {'delimiter': '""","""', 'skip_header': '(1)'}), "(Raw6_tab, delimiter=',', skip_header=1)\n", (49089, 49129), True, 'import numpy as np\n'), ((49152, 49203), 'numpy.genfromtxt', 'np.genfromtxt', (['V2_tab'], {'delimiter': '""","""', 'skip_header': '(1)'}), "(V2_tab, delimiter=',', skip_header=1)\n", (49165, 49203), True, 'import numpy as np\n'), ((49225, 49276), 'numpy.genfromtxt', 'np.genfromtxt', (['V4_tab'], {'delimiter': '""","""', 'skip_header': '(1)'}), "(V4_tab, delimiter=',', skip_header=1)\n", (49238, 49276), True, 'import numpy as np\n'), ((49303, 49357), 'numpy.genfromtxt', 'np.genfromtxt', (['RawV2_tab'], {'delimiter': '""","""', 'skip_header': '(1)'}), "(RawV2_tab, delimiter=',', skip_header=1)\n", (49316, 49357), True, 'import numpy as np\n'), ((49383, 49437), 'numpy.genfromtxt', 'np.genfromtxt', (['RawV4_tab'], {'delimiter': '""","""', 'skip_header': '(1)'}), "(RawV4_tab, delimiter=',', skip_header=1)\n", (49396, 49437), True, 'import numpy as np\n'), ((49463, 49517), 'numpy.genfromtxt', 'np.genfromtxt', (['RawV6_tab'], {'delimiter': '""","""', 'skip_header': '(1)'}), "(RawV6_tab, delimiter=',', skip_header=1)\n", (49476, 49517), True, 'import numpy as np\n'), ((49673, 49764), 'scipy.interpolate.interp2d', 'interpolate.interp2d', (['arr_Raw2[:, 1]', 'arr_Raw2[:, 0]', 'arr_Raw2[:, 2]'], {'kind': 'interp2Type'}), '(arr_Raw2[:, 1], arr_Raw2[:, 0], arr_Raw2[:, 2], kind=\n interp2Type)\n', (49693, 49764), False, 'from scipy import interpolate, signal\n'), ((49787, 49878), 'scipy.interpolate.interp2d', 'interpolate.interp2d', (['arr_Raw4[:, 1]', 'arr_Raw4[:, 0]', 'arr_Raw4[:, 2]'], {'kind': 'interp2Type'}), '(arr_Raw4[:, 1], arr_Raw4[:, 0], arr_Raw4[:, 2], kind=\n interp2Type)\n', (49807, 49878), False, 'from scipy import interpolate, signal\n'), ((49901, 49992), 'scipy.interpolate.interp2d', 'interpolate.interp2d', (['arr_Raw6[:, 1]', 'arr_Raw6[:, 0]', 'arr_Raw6[:, 2]'], {'kind': 'interp2Type'}), '(arr_Raw6[:, 1], arr_Raw6[:, 0], arr_Raw6[:, 2], kind=\n interp2Type)\n', (49921, 49992), False, 'from scipy import interpolate, signal\n'), ((50014, 50099), 'scipy.interpolate.interp2d', 'interpolate.interp2d', (['arr_V2[:, 1]', 'arr_V2[:, 0]', 'arr_V2[:, 2]'], {'kind': 'interp2Type'}), '(arr_V2[:, 1], arr_V2[:, 0], arr_V2[:, 2], kind=interp2Type\n )\n', (50034, 50099), False, 'from scipy import interpolate, signal\n'), ((50120, 50205), 'scipy.interpolate.interp2d', 'interpolate.interp2d', (['arr_V4[:, 1]', 'arr_V4[:, 0]', 'arr_V4[:, 2]'], {'kind': 'interp2Type'}), '(arr_V4[:, 1], arr_V4[:, 0], arr_V4[:, 2], kind=interp2Type\n )\n', (50140, 50205), False, 'from scipy import interpolate, signal\n'), ((50268, 50372), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (['arr_Raw_V2[:, 0]', 'arr_Raw_V2[:, 1]'], {'kind': 'interp1Type', 'fill_value': '"""extrapolate"""'}), "(arr_Raw_V2[:, 0], arr_Raw_V2[:, 1], kind=interp1Type,\n fill_value='extrapolate')\n", (50288, 50372), False, 'from scipy import interpolate, signal\n'), ((50399, 50503), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (['arr_Raw_V4[:, 0]', 'arr_Raw_V4[:, 1]'], {'kind': 'interp1Type', 'fill_value': '"""extrapolate"""'}), "(arr_Raw_V4[:, 0], arr_Raw_V4[:, 1], kind=interp1Type,\n fill_value='extrapolate')\n", (50419, 50503), False, 'from scipy import interpolate, signal\n'), ((50530, 50634), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (['arr_Raw_V6[:, 0]', 'arr_Raw_V6[:, 1]'], {'kind': 'interp1Type', 'fill_value': '"""extrapolate"""'}), "(arr_Raw_V6[:, 0], arr_Raw_V6[:, 1], kind=interp1Type,\n fill_value='extrapolate')\n", (50550, 50634), False, 'from scipy import interpolate, signal\n'), ((51044, 51066), 'numpy.multiply', 'np.multiply', (['RRm', 'Rwbm'], {}), '(RRm, Rwbm)\n', (51055, 51066), True, 'import numpy as np\n'), ((51608, 51627), 'numpy.multiply', 'np.multiply', (['Rwb', 'E'], {}), '(Rwb, E)\n', (51619, 51627), True, 'import numpy as np\n'), ((51658, 51754), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (['[0.2, 0.4, 0.6]', 'Rwb_final'], {'kind': 'interp1Type', 'fill_value': '"""extrapolate"""'}), "([0.2, 0.4, 0.6], Rwb_final, kind=interp1Type,\n fill_value='extrapolate')\n", (51678, 51754), False, 'from scipy import interpolate, signal\n'), ((51817, 51981), 'warnings.warn', 'warnings.warn', (['"""Average impact acceleration based on the Fridsma charts is currently not implemented. Using Savitsky & Brown approximation."""'], {'stacklevel': '(2)'}), "(\n 'Average impact acceleration based on the Fridsma charts is currently not implemented. Using Savitsky & Brown approximation.'\n , stacklevel=2)\n", (51830, 51981), False, 'import warnings\n'), ((11781, 11808), 'numpy.sqrt', 'np.sqrt', (['(self.g * self.beam)'], {}), '(self.g * self.beam)\n', (11788, 11808), True, 'import numpy as np\n'), ((11852, 11916), 'numpy.sqrt', 'np.sqrt', (['(self.g * (self.weight / (self.g * self.rho)) ** (1 / 3))'], {}), '(self.g * (self.weight / (self.g * self.rho)) ** (1 / 3))\n', (11859, 11916), True, 'import numpy as np\n'), ((12819, 12864), 'numpy.sin', 'np.sin', (['((self.tau + self.eta_5) * np.pi / 180)'], {}), '((self.tau + self.eta_5) * np.pi / 180)\n', (12825, 12864), True, 'import numpy as np\n'), ((18280, 18312), 'numpy.tan', 'np.tan', (['(pi / 180 * (tau + eta_5))'], {}), '(pi / 180 * (tau + eta_5))\n', (18286, 18312), True, 'import numpy as np\n'), ((19211, 19301), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (['beta_table', 'z_max_table'], {'kind': '"""cubic"""', 'fill_value': '"""extrapolate"""'}), "(beta_table, z_max_table, kind='cubic', fill_value=\n 'extrapolate')\n", (19231, 19301), False, 'from scipy import interpolate, signal\n'), ((19588, 19611), 'numpy.tan', 'np.tan', (['(pi / 180 * beta)'], {}), '(pi / 180 * beta)\n', (19594, 19611), True, 'import numpy as np\n'), ((20174, 20206), 'numpy.tan', 'np.tan', (['(pi / 180 * (tau + eta_5))'], {}), '(pi / 180 * (tau + eta_5))\n', (20180, 20206), True, 'import numpy as np\n'), ((20367, 20441), 'warnings.warn', 'warnings.warn', (['"""Vessel operating with dry chines (L_C = 0)."""'], {'stacklevel': '(2)'}), "('Vessel operating with dry chines (L_C = 0).', stacklevel=2)\n", (20380, 20441), False, 'import warnings\n'), ((26479, 26502), 'numpy.cos', 'np.cos', (['(pi / 180 * beta)'], {}), '(pi / 180 * beta)\n', (26485, 26502), True, 'import numpy as np\n'), ((27826, 27858), 'numpy.cos', 'np.cos', (['(pi / 180 * (tau + eta_5))'], {}), '(pi / 180 * (tau + eta_5))\n', (27832, 27858), True, 'import numpy as np\n'), ((27918, 27950), 'numpy.sin', 'np.sin', (['(pi / 180 * (tau + eta_5))'], {}), '(pi / 180 * (tau + eta_5))\n', (27924, 27950), True, 'import numpy as np\n'), ((37401, 37424), 'numpy.tan', 'np.tan', (['(pi / 180 * beta)'], {}), '(pi / 180 * beta)\n', (37407, 37424), True, 'import numpy as np\n'), ((39426, 39477), 'ndmath.complexGrad', 'ndmath.complexGrad', (['_func', '[temp_eta_3, temp_eta_5]'], {}), '(_func, [temp_eta_3, temp_eta_5])\n', (39444, 39477), False, 'import ndmath\n'), ((20154, 20177), 'numpy.tan', 'np.tan', (['(pi / 180 * beta)'], {}), '(pi / 180 * beta)\n', (20160, 20177), True, 'import numpy as np\n'), ((31752, 31778), 'numpy.cos', 'np.cos', (['(pi / 180 * epsilon)'], {}), '(pi / 180 * epsilon)\n', (31758, 31778), True, 'import numpy as np\n'), ((31790, 31816), 'numpy.sin', 'np.sin', (['(pi / 180 * epsilon)'], {}), '(pi / 180 * epsilon)\n', (31796, 31816), True, 'import numpy as np\n'), ((39536, 39598), 'ndmath.finiteGrad', 'ndmath.finiteGrad', (['_func', '[temp_eta_3, temp_eta_5]', '(10 ** -6.6)'], {}), '(_func, [temp_eta_3, temp_eta_5], 10 ** -6.6)\n', (39553, 39598), False, 'import ndmath\n'), ((40985, 41007), 'numpy.zeros', 'np.zeros', (['(nDim, nDim)'], {}), '((nDim, nDim))\n', (40993, 41007), True, 'import numpy as np\n'), ((41008, 41025), 'numpy.identity', 'np.identity', (['nDim'], {}), '(nDim)\n', (41019, 41025), True, 'import numpy as np\n'), ((17203, 17267), 'numpy.printoptions', 'np.printoptions', ([], {'formatter': "{'float': f'{{:.{sigFigs}g}}'.format}"}), "(formatter={'float': f'{{:.{sigFigs}g}}'.format})\n", (17218, 17267), True, 'import numpy as np\n'), ((20646, 20669), 'numpy.tan', 'np.tan', (['(pi / 180 * beta)'], {}), '(pi / 180 * beta)\n', (20652, 20669), True, 'import numpy as np\n'), ((20992, 21021), 'numpy.exp', 'np.exp', (['(-(lambda_K - w) / 0.3)'], {}), '(-(lambda_K - w) / 0.3)\n', (20998, 21021), True, 'import numpy as np\n'), ((27295, 27307), 'numpy.log10', 'np.log10', (['Rn'], {}), '(Rn)\n', (27303, 27307), True, 'import numpy as np\n'), ((35666, 35689), 'scipy.special.gamma', 'gamma', (['(1.5 - beta / 180)'], {}), '(1.5 - beta / 180)\n', (35671, 35689), False, 'from scipy.special import gamma\n'), ((35716, 35739), 'scipy.special.gamma', 'gamma', (['(0.5 + beta / 180)'], {}), '(0.5 + beta / 180)\n', (35721, 35739), False, 'from scipy.special import gamma\n'), ((37608, 37631), 'scipy.special.gamma', 'gamma', (['(1.5 - beta / 180)'], {}), '(1.5 - beta / 180)\n', (37613, 37631), False, 'from scipy.special import gamma\n'), ((37658, 37681), 'scipy.special.gamma', 'gamma', (['(0.5 + beta / 180)'], {}), '(0.5 + beta / 180)\n', (37663, 37681), False, 'from scipy.special import gamma\n'), ((41054, 41075), 'numpy.linalg.solve', 'np.linalg.solve', (['M', 'K'], {}), '(M, K)\n', (41069, 41075), True, 'import numpy as np\n'), ((41077, 41098), 'numpy.linalg.solve', 'np.linalg.solve', (['M', 'C'], {}), '(M, C)\n', (41092, 41098), True, 'import numpy as np\n'), ((46117, 46140), 'numpy.tan', 'np.tan', (['(beta * pi / 180)'], {}), '(beta * pi / 180)\n', (46123, 46140), True, 'import numpy as np\n'), ((20823, 20846), 'numpy.tan', 'np.tan', (['(pi / 180 * beta)'], {}), '(pi / 180 * beta)\n', (20829, 20846), True, 'import numpy as np\n'), ((21359, 21382), 'numpy.tan', 'np.tan', (['(pi / 180 * beta)'], {}), '(pi / 180 * beta)\n', (21365, 21382), True, 'import numpy as np\n'), ((27690, 27713), 'numpy.tan', 'np.tan', (['(pi / 180 * beta)'], {}), '(pi / 180 * beta)\n', (27696, 27713), True, 'import numpy as np\n'), ((27725, 27748), 'numpy.tan', 'np.tan', (['(pi / 180 * beta)'], {}), '(pi / 180 * beta)\n', (27731, 27748), True, 'import numpy as np\n'), ((35644, 35667), 'numpy.sin', 'np.sin', (['(pi / 180 * beta)'], {}), '(pi / 180 * beta)\n', (35650, 35667), True, 'import numpy as np\n'), ((35691, 35712), 'scipy.special.gamma', 'gamma', (['(1 - beta / 180)'], {}), '(1 - beta / 180)\n', (35696, 35712), False, 'from scipy.special import gamma\n'), ((36175, 36198), 'numpy.tan', 'np.tan', (['(pi / 180 * beta)'], {}), '(pi / 180 * beta)\n', (36181, 36198), True, 'import numpy as np\n'), ((37586, 37609), 'numpy.sin', 'np.sin', (['(pi / 180 * beta)'], {}), '(pi / 180 * beta)\n', (37592, 37609), True, 'import numpy as np\n'), ((37633, 37654), 'scipy.special.gamma', 'gamma', (['(1 - beta / 180)'], {}), '(1 - beta / 180)\n', (37638, 37654), False, 'from scipy.special import gamma\n'), ((20846, 20878), 'numpy.tan', 'np.tan', (['(pi / 180 * (tau + eta_5))'], {}), '(pi / 180 * (tau + eta_5))\n', (20852, 20878), True, 'import numpy as np\n'), ((27084, 27106), 'numpy.cos', 'np.cos', (['(tau * pi / 180)'], {}), '(tau * pi / 180)\n', (27090, 27106), True, 'import numpy as np\n'), ((26989, 27006), 'numpy.sqrt', 'np.sqrt', (['lambda_W'], {}), '(lambda_W)\n', (26996, 27006), True, 'import numpy as np\n'), ((27034, 27051), 'numpy.sqrt', 'np.sqrt', (['lambda_W'], {}), '(lambda_W)\n', (27041, 27051), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 6 09:54:17 2015
@author: jmilli
"""
import numpy as np
from scipy.interpolate import interp1d
def create2dMap(values,inputRadii=None,maxRadius=None):
"""
This function takes a 1D radial distribution in input and builds a 2map
"""
nbValues=len(values)
if inputRadii==None:
inputRadii=np.arange(0,nbValues)
maxRadius=nbValues
else:
if maxRadius==None:
raise ValueError('You must provide a maximum radius')
imageAxis = np.arange(-maxRadius/2,maxRadius/2)
x,y = np.meshgrid(imageAxis,imageAxis)
distmap = abs(x+1j*y)
# map2d = np.ndarray(distmap.shape)
radiusOK = np.isfinite(values)
func = interp1d(inputRadii[radiusOK],values[radiusOK],kind='cubic',
bounds_error=False,fill_value=np.nan)
map2d = func(distmap)
return map2d,distmap
| [
"numpy.meshgrid",
"numpy.isfinite",
"numpy.arange",
"scipy.interpolate.interp1d"
] | [((533, 573), 'numpy.arange', 'np.arange', (['(-maxRadius / 2)', '(maxRadius / 2)'], {}), '(-maxRadius / 2, maxRadius / 2)\n', (542, 573), True, 'import numpy as np\n'), ((579, 612), 'numpy.meshgrid', 'np.meshgrid', (['imageAxis', 'imageAxis'], {}), '(imageAxis, imageAxis)\n', (590, 612), True, 'import numpy as np\n'), ((692, 711), 'numpy.isfinite', 'np.isfinite', (['values'], {}), '(values)\n', (703, 711), True, 'import numpy as np\n'), ((723, 829), 'scipy.interpolate.interp1d', 'interp1d', (['inputRadii[radiusOK]', 'values[radiusOK]'], {'kind': '"""cubic"""', 'bounds_error': '(False)', 'fill_value': 'np.nan'}), "(inputRadii[radiusOK], values[radiusOK], kind='cubic', bounds_error\n =False, fill_value=np.nan)\n", (731, 829), False, 'from scipy.interpolate import interp1d\n'), ((364, 386), 'numpy.arange', 'np.arange', (['(0)', 'nbValues'], {}), '(0, nbValues)\n', (373, 386), True, 'import numpy as np\n')] |
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Helper functions for the Keras implementations of models."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import tensorflow as tf
from tensorflow.python.eager import profiler
class BatchTimestamp(object):
"""A structure to store batch time stamp."""
def __init__(self, batch_index, timestamp):
self.batch_index = batch_index
self.timestamp = timestamp
def __repr__(self):
return "'BatchTimestamp<batch_index: {}, timestamp: {}>'".format(
self.batch_index, self.timestamp)
class TimeHistory(tf.keras.callbacks.Callback):
"""Callback for Keras models."""
def __init__(self, batch_size, log_steps):
"""Callback for logging performance (# examples/second).
Args:
batch_size: Total batch size.
log_steps: Interval of time history logs.
"""
self.batch_size = batch_size
super(TimeHistory, self).__init__()
self.log_steps = log_steps
# Logs start of step 0 then end of each step based on log_steps interval.
self.timestamp_log = []
def on_train_begin(self, logs=None):
self.record_batch = True
def on_train_end(self, logs=None):
self.train_finish_time = time.time()
def on_batch_begin(self, batch, logs=None):
if self.record_batch:
timestamp = time.time()
self.start_time = timestamp
self.record_batch = False
if batch == 0:
self.timestamp_log.append(BatchTimestamp(batch, timestamp))
def on_batch_end(self, batch, logs=None):
if batch % self.log_steps == 0:
timestamp = time.time()
elapsed_time = timestamp - self.start_time
examples_per_second = (self.batch_size * self.log_steps) / elapsed_time
if batch != 0:
self.record_batch = True
self.timestamp_log.append(BatchTimestamp(batch, timestamp))
tf.compat.v1.logging.info(
"BenchmarkMetric: {'num_batches':%d, 'time_taken': %f,"
"'examples_per_second': %f}" %
(batch, elapsed_time, examples_per_second))
def get_profiler_callback(model_dir, profile_steps, enable_tensorboard):
"""Validate profile_steps flag value and return profiler callback."""
profile_steps_error_message = (
'profile_steps must be a comma separated pair of positive integers, '
'specifying the first and last steps to be profiled.'
)
try:
profile_steps = [int(i) for i in profile_steps.split(',')]
except ValueError:
raise ValueError(profile_steps_error_message)
if len(profile_steps) != 2:
raise ValueError(profile_steps_error_message)
start_step, stop_step = profile_steps
if start_step < 0 or start_step > stop_step:
raise ValueError(profile_steps_error_message)
if enable_tensorboard:
tf.compat.v1.logging.warn(
'Both TensorBoard and profiler callbacks are used. Note that the '
'TensorBoard callback profiles the 2nd step (unless otherwise '
'specified). Please make sure the steps profiled by the two callbacks '
'do not overlap.')
return ProfilerCallback(model_dir, start_step, stop_step)
class ProfilerCallback(tf.keras.callbacks.Callback):
"""Save profiles in specified step range to log directory."""
def __init__(self, log_dir, start_step, stop_step):
super(ProfilerCallback, self).__init__()
self.log_dir = log_dir
self.start_step = start_step
self.stop_step = stop_step
def on_batch_begin(self, batch, logs=None):
if batch == self.start_step:
profiler.start()
tf.compat.v1.logging.info('Profiler started at Step %s', self.start_step)
def on_batch_end(self, batch, logs=None):
if batch == self.stop_step:
results = profiler.stop()
profiler.save(self.log_dir, results)
tf.compat.v1.logging.info(
'Profiler saved profiles for steps between %s and %s to %s',
self.start_step, self.stop_step, self.log_dir)
| [
"tensorflow.compat.v1.logging.warn",
"tensorflow.python.eager.profiler.stop",
"tensorflow.python.eager.profiler.save",
"tensorflow.python.eager.profiler.start",
"time.time",
"tensorflow.compat.v1.logging.info"
] | [((1916, 1927), 'time.time', 'time.time', ([], {}), '()\n', (1925, 1927), False, 'import time\n'), ((3456, 3704), 'tensorflow.compat.v1.logging.warn', 'tf.compat.v1.logging.warn', (['"""Both TensorBoard and profiler callbacks are used. Note that the TensorBoard callback profiles the 2nd step (unless otherwise specified). Please make sure the steps profiled by the two callbacks do not overlap."""'], {}), "(\n 'Both TensorBoard and profiler callbacks are used. Note that the TensorBoard callback profiles the 2nd step (unless otherwise specified). Please make sure the steps profiled by the two callbacks do not overlap.'\n )\n", (3481, 3704), True, 'import tensorflow as tf\n'), ((2019, 2030), 'time.time', 'time.time', ([], {}), '()\n', (2028, 2030), False, 'import time\n'), ((2285, 2296), 'time.time', 'time.time', ([], {}), '()\n', (2294, 2296), False, 'import time\n'), ((4194, 4210), 'tensorflow.python.eager.profiler.start', 'profiler.start', ([], {}), '()\n', (4208, 4210), False, 'from tensorflow.python.eager import profiler\n'), ((4217, 4290), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""Profiler started at Step %s"""', 'self.start_step'], {}), "('Profiler started at Step %s', self.start_step)\n", (4242, 4290), True, 'import tensorflow as tf\n'), ((4384, 4399), 'tensorflow.python.eager.profiler.stop', 'profiler.stop', ([], {}), '()\n', (4397, 4399), False, 'from tensorflow.python.eager import profiler\n'), ((4406, 4442), 'tensorflow.python.eager.profiler.save', 'profiler.save', (['self.log_dir', 'results'], {}), '(self.log_dir, results)\n', (4419, 4442), False, 'from tensorflow.python.eager import profiler\n'), ((4449, 4592), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""Profiler saved profiles for steps between %s and %s to %s"""', 'self.start_step', 'self.stop_step', 'self.log_dir'], {}), "(\n 'Profiler saved profiles for steps between %s and %s to %s', self.\n start_step, self.stop_step, self.log_dir)\n", (4474, 4592), True, 'import tensorflow as tf\n'), ((2554, 2717), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['("BenchmarkMetric: {\'num_batches\':%d, \'time_taken\': %f,\'examples_per_second\': %f}"\n % (batch, elapsed_time, examples_per_second))'], {}), '(\n "BenchmarkMetric: {\'num_batches\':%d, \'time_taken\': %f,\'examples_per_second\': %f}"\n % (batch, elapsed_time, examples_per_second))\n', (2579, 2717), True, 'import tensorflow as tf\n')] |
# Copyright 2015 Google 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.
"""Common utility functions for sql operations."""
import time
from apitools.base.py import exceptions
from googlecloudsdk.api_lib.sql import errors
from googlecloudsdk.core.console import progress_tracker as console_progress_tracker
from googlecloudsdk.core.util import retry
class _BaseOperations(object):
"""Common utility functions for sql operations."""
_PRE_START_SLEEP_SEC = 1
_INITIAL_SLEEP_MS = 2000
_MAX_WAIT_MS = 300000
_WAIT_CEILING_MS = 20000
_HTTP_MAX_RETRY_MS = 2000
@classmethod
def WaitForOperation(cls, sql_client, operation_ref, message):
"""Wait for a Cloud SQL operation to complete.
No operation is done instantly. Wait for it to finish following this logic:
First wait 1s, then query, then retry waiting exponentially more from 2s.
We want to limit to 20s between retries to maintain some responsiveness.
Finally, we want to limit the whole process to a conservative 300s. If we
get to that point it means something is wrong and we can throw an exception.
Args:
sql_client: apitools.BaseApiClient, The client used to make requests.
operation_ref: resources.Resource, A reference for the operation to poll.
message: str, The string to print while polling.
Returns:
True if the operation succeeded without error.
Raises:
OperationError: If the operation has an error code, is in UNKNOWN state,
or if the operation takes more than 300s.
"""
def ShouldRetryFunc(result, state):
# In case of HttpError, retry for up to _HTTP_MAX_RETRY_MS at most.
if isinstance(result, exceptions.HttpError):
if state.time_passed_ms > _BaseOperations._HTTP_MAX_RETRY_MS:
raise result
return True
# In case of other Exceptions, raise them immediately.
if isinstance(result, Exception):
raise result
# Otherwise let the retryer do it's job until the Operation is done.
return not result
with console_progress_tracker.ProgressTracker(
message, autotick=False) as pt:
time.sleep(_BaseOperations._PRE_START_SLEEP_SEC)
retryer = retry.Retryer(exponential_sleep_multiplier=2,
max_wait_ms=_BaseOperations._MAX_WAIT_MS,
wait_ceiling_ms=_BaseOperations._WAIT_CEILING_MS)
try:
retryer.RetryOnResult(cls.GetOperationStatus,
[sql_client, operation_ref],
{'progress_tracker': pt},
should_retry_if=ShouldRetryFunc,
sleep_ms=_BaseOperations._INITIAL_SLEEP_MS)
except retry.WaitException:
raise errors.OperationError(
('Operation {0} is taking longer than expected. You can continue '
'waiting for the operation by running `{1}`').format(
operation_ref,
cls.GetOperationWaitCommand(operation_ref)))
class OperationsV1Beta3(_BaseOperations):
"""Common utility functions for sql operations V1Beta3."""
@staticmethod
def GetOperationStatus(sql_client, operation_ref, progress_tracker=None):
"""Helper function for getting the status of an operation for V1Beta3 API.
Args:
sql_client: apitools.BaseApiClient, The client used to make requests.
operation_ref: resources.Resource, A reference for the operation to poll.
progress_tracker: progress_tracker.ProgressTracker, A reference for the
progress tracker to tick, in case this function is used in a Retryer.
Returns:
True: if the operation succeeded without error.
False: if the operation is not yet done.
OperationError: If the operation has an error code or is in UNKNOWN state.
Exception: Any other exception that can occur when calling Get
"""
if progress_tracker:
progress_tracker.Tick()
try:
op = sql_client.operations.Get(
sql_client.MESSAGES_MODULE.SqlOperationsGetRequest(
project=operation_ref.project,
instance=operation_ref.instance,
operation=operation_ref.operation))
except Exception as e: # pylint:disable=broad-except
# Since we use this function in a retryer.RetryOnResult block, where we
# retry for different exceptions up to different amounts of time, we
# have to catch all exceptions here and return them.
return e
if op.error:
return errors.OperationError(op.error[0].code)
if op.state == 'UNKNOWN':
return errors.OperationError(op.state)
if op.state == 'DONE':
return True
return False
@staticmethod
def GetOperationWaitCommand(operation_ref):
return 'gcloud sql operations wait -i {0} --project {1} {2}'.format(
operation_ref.instance, operation_ref.project, operation_ref.operation)
class OperationsV1Beta4(_BaseOperations):
"""Common utility functions for sql operations V1Beta4."""
@staticmethod
def GetOperationStatus(sql_client, operation_ref, progress_tracker=None):
"""Helper function for getting the status of an operation for V1Beta4 API.
Args:
sql_client: apitools.BaseApiClient, The client used to make requests.
operation_ref: resources.Resource, A reference for the operation to poll.
progress_tracker: progress_tracker.ProgressTracker, A reference for the
progress tracker to tick, in case this function is used in a Retryer.
Returns:
True: if the operation succeeded without error.
False: if the operation is not yet done.
OperationError: If the operation has an error code or is in UNKNOWN state.
Exception: Any other exception that can occur when calling Get
"""
if progress_tracker:
progress_tracker.Tick()
try:
op = sql_client.operations.Get(
sql_client.MESSAGES_MODULE.SqlOperationsGetRequest(
project=operation_ref.project,
operation=operation_ref.operation))
except Exception as e: # pylint:disable=broad-except
# Since we use this function in a retryer.RetryOnResult block, where we
# retry for different exceptions up to different amounts of time, we
# have to catch all exceptions here and return them.
return e
if op.error and op.error.errors:
return errors.OperationError(op.error.errors[0].code)
if op.status == 'UNKNOWN':
return errors.OperationError(op.status)
if op.status == 'DONE':
return True
return False
@staticmethod
def GetOperationWaitCommand(operation_ref):
return 'gcloud beta sql operations wait --project {0} {1}'.format(
operation_ref.project, operation_ref.operation)
| [
"googlecloudsdk.api_lib.sql.errors.OperationError",
"googlecloudsdk.core.console.progress_tracker.ProgressTracker",
"googlecloudsdk.core.util.retry.Retryer",
"time.sleep"
] | [((2574, 2639), 'googlecloudsdk.core.console.progress_tracker.ProgressTracker', 'console_progress_tracker.ProgressTracker', (['message'], {'autotick': '(False)'}), '(message, autotick=False)\n', (2614, 2639), True, 'from googlecloudsdk.core.console import progress_tracker as console_progress_tracker\n'), ((2662, 2710), 'time.sleep', 'time.sleep', (['_BaseOperations._PRE_START_SLEEP_SEC'], {}), '(_BaseOperations._PRE_START_SLEEP_SEC)\n', (2672, 2710), False, 'import time\n'), ((2727, 2869), 'googlecloudsdk.core.util.retry.Retryer', 'retry.Retryer', ([], {'exponential_sleep_multiplier': '(2)', 'max_wait_ms': '_BaseOperations._MAX_WAIT_MS', 'wait_ceiling_ms': '_BaseOperations._WAIT_CEILING_MS'}), '(exponential_sleep_multiplier=2, max_wait_ms=_BaseOperations.\n _MAX_WAIT_MS, wait_ceiling_ms=_BaseOperations._WAIT_CEILING_MS)\n', (2740, 2869), False, 'from googlecloudsdk.core.util import retry\n'), ((5050, 5089), 'googlecloudsdk.api_lib.sql.errors.OperationError', 'errors.OperationError', (['op.error[0].code'], {}), '(op.error[0].code)\n', (5071, 5089), False, 'from googlecloudsdk.api_lib.sql import errors\n'), ((5133, 5164), 'googlecloudsdk.api_lib.sql.errors.OperationError', 'errors.OperationError', (['op.state'], {}), '(op.state)\n', (5154, 5164), False, 'from googlecloudsdk.api_lib.sql import errors\n'), ((6913, 6959), 'googlecloudsdk.api_lib.sql.errors.OperationError', 'errors.OperationError', (['op.error.errors[0].code'], {}), '(op.error.errors[0].code)\n', (6934, 6959), False, 'from googlecloudsdk.api_lib.sql import errors\n'), ((7004, 7036), 'googlecloudsdk.api_lib.sql.errors.OperationError', 'errors.OperationError', (['op.status'], {}), '(op.status)\n', (7025, 7036), False, 'from googlecloudsdk.api_lib.sql import errors\n')] |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Marshmallow loader for record deserialization.
Use marshmallow schema to transform a JSON sent via the REST API from an
external to an internal JSON presentation. The marshmallow schema further
allows for advanced data validation.
"""
from __future__ import absolute_import, print_function
import json
from flask import request
from invenio_rest.errors import RESTValidationError
def _flatten_marshmallow_errors(errors):
"""Flatten marshmallow errors."""
res = []
for field, error in errors.items():
if isinstance(error, list):
res.append(
dict(field=field, message=' '.join([str(x) for x in error])))
elif isinstance(error, dict):
res.extend(_flatten_marshmallow_errors(error))
return res
class MarshmallowErrors(RESTValidationError):
"""Marshmallow validation errors.
Responsible for formatting a JSON response to a user when a validation
error happens.
"""
def __init__(self, errors):
"""Store marshmallow errors."""
self._it = None
self.errors = _flatten_marshmallow_errors(errors)
super(MarshmallowErrors, self).__init__()
def __str__(self):
"""Print exception with errors."""
return "{base}. Encountered errors: {errors}".format(
base=super(RESTValidationError, self).__str__(),
errors=self.errors)
def __iter__(self):
"""Get iterator."""
self._it = iter(self.errors)
return self
def next(self):
"""Python 2.7 compatibility."""
return self.__next__() # pragma: no cover
def __next__(self):
"""Get next file item."""
return next(self._it)
def get_body(self, environ=None):
"""Get the request body."""
body = dict(
status=self.code,
message=self.get_description(environ),
)
if self.errors:
body['errors'] = self.errors
return json.dumps(body)
def marshmallow_loader(schema_class):
"""Marshmallow loader for JSON requests."""
def json_loader():
request_json = request.get_json()
context = {}
pid_data = request.view_args.get('pid_value')
if pid_data:
pid, record = pid_data.data
context['pid'] = pid
context['record'] = record
result = schema_class(context=context).load(request_json)
if result.errors:
raise MarshmallowErrors(result.errors)
return result.data
return json_loader
def json_patch_loader():
"""Dummy loader for json-patch requests."""
return request.get_json(force=True)
| [
"flask.request.get_json",
"json.dumps",
"flask.request.view_args.get"
] | [((2862, 2890), 'flask.request.get_json', 'request.get_json', ([], {'force': '(True)'}), '(force=True)\n', (2878, 2890), False, 'from flask import request\n'), ((2202, 2218), 'json.dumps', 'json.dumps', (['body'], {}), '(body)\n', (2212, 2218), False, 'import json\n'), ((2353, 2371), 'flask.request.get_json', 'request.get_json', ([], {}), '()\n', (2369, 2371), False, 'from flask import request\n'), ((2413, 2447), 'flask.request.view_args.get', 'request.view_args.get', (['"""pid_value"""'], {}), "('pid_value')\n", (2434, 2447), False, 'from flask import request\n')] |
#!/usr/bin/env python
# coding: utf-8
# vim: set ts=4 sw=4 expandtab sts=4:
# Copyright (c) 2011-2013 <NAME> & contributors
#
# 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.
"""
syncs the remote database to the local db
"""
from pycarddav import backend
from pycarddav import carddav
from pycarddav import model
from pycarddav import ui
from os import path
import logging
import sys
def query(conf):
# testing if the db exists
if not path.exists(conf.sqlite__path):
sys.exit(str(conf.sqlite__path) + " file does not exist, please sync"
" with pycardsyncer first.")
search_string = conf.cmd__search_string.decode("utf-8")
my_dbtool = backend.SQLiteDb(conf.sqlite__path, "utf-8", "stricts", False)
#import:
if conf.cmd__importing:
cards = model.cards_from_file(conf.cmd__importing)
for card in cards:
my_dbtool.update(card, status=backend.NEW)
sys.exit()
# backup:
if conf.cmd__backup:
with open(conf.cmd__backup, 'w') as vcf_file:
if search_string == "":
hreflist = my_dbtool.get_all_vref_from_db()
else:
hreflist = my_dbtool.search(search_string)
for href in hreflist:
vcard = my_dbtool.get_vcard_from_db(href)
vcf_file.write(vcard.vcf.encode('utf-8'))
sys.exit()
# editing a card:
#if conf.cmd__edit:
# names = my_dbtool.select_entry2(search_string)
# href = ui.select_entry(names)
# if href is None:
# sys.exit("Found no matching cards.")
# mark a card for deletion
if conf.cmd__delete:
hrefs = my_dbtool.search(search_string)
if len(hrefs) is 0:
sys.exit('Found no matching cards.')
elif len(hrefs) is 1:
href = hrefs[0]
else:
pane = ui.VCardChooserPane(my_dbtool, hrefs)
ui.start_pane(pane)
card = pane._walker.selected_vcard
href = card.href
if href in my_dbtool.get_new():
# cards not yet on the server get deleted directly, otherwise we
# will try to delete them on the server later (where they don't
# exist) and this will raise an exception
my_dbtool.delete_vcard_from_db(href)
else:
my_dbtool.mark_delete(href)
print('vcard "%s" deleted from local db, will be deleted ' % href +
'on the server on the next sync')
sys.exit()
print("searching for " + conf.cmd__search_string + "...")
result = my_dbtool.search(search_string)
for one in result:
vcard = my_dbtool.get_vcard_from_db(one)
if conf.cmd__mutt:
lines = vcard.print_email()
elif conf.cmd__tel:
lines = vcard.print_tel()
elif conf.cmd__display_all:
lines = vcard.pretty
else:
lines = vcard.pretty_min
if not lines == '':
print(lines.encode('utf-8'))
return 0
def sync(conf):
"""this should probably be seperated from the class definitions"""
syncer = carddav.PyCardDAV(conf.dav__resource,
user=conf.dav__user,
passwd=conf.dav__passwd,
write_support=conf.write_support,
verify=conf.dav__verify,
auth=conf.dav__auth)
my_dbtool = backend.SQLiteDb(conf.sqlite__path, "utf-8", "stricts", conf.debug)
# sync:
abook = syncer.get_abook() # type (abook): dict
for href, etag in abook.iteritems():
if my_dbtool.needs_update(href, etag):
logging.debug("getting %s etag: %s", href, etag)
vcard = syncer.get_vcard(href)
my_dbtool.update(vcard, href, etag=etag)
remote_changed = False
# for now local changes overwritten by remote changes
logging.debug("looking for locally changed vcards...")
hrefs = my_dbtool.changed
for href in hrefs:
logging.debug("trying to update %s", href)
card = my_dbtool.get_vcard_from_db(href)
logging.debug("%s", my_dbtool.get_etag(href))
syncer.update_vcard(card.vcf, href, None)
my_dbtool.reset_flag(href)
remote_changed = True
# uploading
hrefs = my_dbtool.get_new()
for href in hrefs:
logging.debug("trying to upload new card %s", href)
card = my_dbtool.get_vcard_from_db(href)
(href_new, etag_new) = syncer.upload_new_card(card.vcf)
my_dbtool.update_href(href, href_new, status=backend.OK)
remote_changed = True
# deleting locally deleted cards on the server
hrefs_etags = my_dbtool.get_marked_delete()
for href, etag in hrefs_etags:
logging.debug('trying to delete card %s', href)
syncer.delete_vcard(href, etag)
my_dbtool.delete_vcard_from_db(href)
remote_changed = True
# detecting remote-deleted cards
# is there a better way to compare a list of unicode() with a list of str()
# objects?
if remote_changed:
abook = syncer.get_abook() # type (abook): dict
rlist = my_dbtool.get_all_vref_from_db_not_new()
delete = set(rlist).difference(abook.keys())
for href in delete:
my_dbtool.delete_vcard_from_db(href)
| [
"os.path.exists",
"logging.debug",
"pycarddav.carddav.PyCardDAV",
"pycarddav.ui.start_pane",
"pycarddav.model.cards_from_file",
"sys.exit",
"pycarddav.ui.VCardChooserPane",
"pycarddav.backend.SQLiteDb"
] | [((1715, 1777), 'pycarddav.backend.SQLiteDb', 'backend.SQLiteDb', (['conf.sqlite__path', '"""utf-8"""', '"""stricts"""', '(False)'], {}), "(conf.sqlite__path, 'utf-8', 'stricts', False)\n", (1731, 1777), False, 'from pycarddav import backend\n'), ((4173, 4345), 'pycarddav.carddav.PyCardDAV', 'carddav.PyCardDAV', (['conf.dav__resource'], {'user': 'conf.dav__user', 'passwd': 'conf.dav__passwd', 'write_support': 'conf.write_support', 'verify': 'conf.dav__verify', 'auth': 'conf.dav__auth'}), '(conf.dav__resource, user=conf.dav__user, passwd=conf.\n dav__passwd, write_support=conf.write_support, verify=conf.dav__verify,\n auth=conf.dav__auth)\n', (4190, 4345), False, 'from pycarddav import carddav\n'), ((4509, 4576), 'pycarddav.backend.SQLiteDb', 'backend.SQLiteDb', (['conf.sqlite__path', '"""utf-8"""', '"""stricts"""', 'conf.debug'], {}), "(conf.sqlite__path, 'utf-8', 'stricts', conf.debug)\n", (4525, 4576), False, 'from pycarddav import backend\n'), ((4979, 5033), 'logging.debug', 'logging.debug', (['"""looking for locally changed vcards..."""'], {}), "('looking for locally changed vcards...')\n", (4992, 5033), False, 'import logging\n'), ((1456, 1486), 'os.path.exists', 'path.exists', (['conf.sqlite__path'], {}), '(conf.sqlite__path)\n', (1467, 1486), False, 'from os import path\n'), ((1836, 1878), 'pycarddav.model.cards_from_file', 'model.cards_from_file', (['conf.cmd__importing'], {}), '(conf.cmd__importing)\n', (1857, 1878), False, 'from pycarddav import model\n'), ((1969, 1979), 'sys.exit', 'sys.exit', ([], {}), '()\n', (1977, 1979), False, 'import sys\n'), ((2405, 2415), 'sys.exit', 'sys.exit', ([], {}), '()\n', (2413, 2415), False, 'import sys\n'), ((3543, 3553), 'sys.exit', 'sys.exit', ([], {}), '()\n', (3551, 3553), False, 'import sys\n'), ((5095, 5137), 'logging.debug', 'logging.debug', (['"""trying to update %s"""', 'href'], {}), "('trying to update %s', href)\n", (5108, 5137), False, 'import logging\n'), ((5435, 5486), 'logging.debug', 'logging.debug', (['"""trying to upload new card %s"""', 'href'], {}), "('trying to upload new card %s', href)\n", (5448, 5486), False, 'import logging\n'), ((5838, 5885), 'logging.debug', 'logging.debug', (['"""trying to delete card %s"""', 'href'], {}), "('trying to delete card %s', href)\n", (5851, 5885), False, 'import logging\n'), ((2779, 2815), 'sys.exit', 'sys.exit', (['"""Found no matching cards."""'], {}), "('Found no matching cards.')\n", (2787, 2815), False, 'import sys\n'), ((4744, 4792), 'logging.debug', 'logging.debug', (['"""getting %s etag: %s"""', 'href', 'etag'], {}), "('getting %s etag: %s', href, etag)\n", (4757, 4792), False, 'import logging\n'), ((2907, 2944), 'pycarddav.ui.VCardChooserPane', 'ui.VCardChooserPane', (['my_dbtool', 'hrefs'], {}), '(my_dbtool, hrefs)\n', (2926, 2944), False, 'from pycarddav import ui\n'), ((2957, 2976), 'pycarddav.ui.start_pane', 'ui.start_pane', (['pane'], {}), '(pane)\n', (2970, 2976), False, 'from pycarddav import ui\n')] |
import re
from flask_restful import Resource, reqparse
acceptedCreditCards = {
"visa": r"/^4[0-9]{12}(?:[0-9]{3})?$/",
"mastercard": r"/^5[1-5][0-9]{14}$|^2(?:2(?:2[1-9]|[3-9][0-9])|[3-6][0-9][0-9]|7(?:[01][0-9]|20))[0-9]{12}$/",
"amex": r"/^3[47][0-9]{13}$/",
"discover": r"/^65[4-9][0-9]{13}|64[4-9][0-9]{13}|6011[0-9]{12}|(622(?:12[6-9]|1[3-9][0-9]|[2-8][0-9][0-9]|9[01][0-9]|92[0-5])[0-9]{10})$/",
"diners_club": r"/^3(?:0[0-5]|[68][0-9])[0-9]{11}$/",
"jcb": r"/^(?:2131|1800|35[0-9]{3})[0-9]{11}$/"
};
def validate_card(card_number):
count_number_of_matchs = 0
for name_compaing, card_number_regex in acceptedCreditCards.items():
if re.match(card_number, card_number_regex):
count_number_of_matchs += 1
name = name_compaing
if count_number_of_matchs == 1:
return [True, name]
if count_number_of_matchs > 1 or count_number_of_matchs == 0:
return [False, None]
def validate_cvv(cvv):
# sourcery skip: assign-if-exp, boolean-if-exp-identity, remove-unnecessary-cast
try:
cvv = int(cvv)
except Exception as error:
return False
else:
cvv = str(cvv)
if len(cvv) in {3, 4}:
return True
else:
return False
def validate_name(name):
regex_name = r"^[A-Za-z ]+$"
return bool(re.match(regex_name, name))
def validate_due_date(date):
regex_date = r"""
^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|
(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|
[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)
?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|
[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?
:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$
"""
return bool(re.match(regex_date, date))
class Payments(Resource):
@staticmethod
def post():
argumentos = reqparse.RequestParser()
argumentos.add_argument('nome')
argumentos.add_argument('num_card')
argumentos.add_argument('cvv')
argumentos.add_argument('data')
dados = argumentos.parse_args()
bool_card_number, card = validate_card(dados['num_card'])
if bool_card_number:
if validate_cvv(dados['cvv']):
if validate_due_date(dados['data']):
if validate_name(dados['nome']):
return {
'msg': 'sucessfull payment',
'card': card
}
return {
'msg': 'name error'
}
return {
'msg': 'date error'
}
return {
'msg': 'cvv error'
}
return {
'msg': 'number card error'
} | [
"re.match",
"flask_restful.reqparse.RequestParser"
] | [((678, 718), 're.match', 're.match', (['card_number', 'card_number_regex'], {}), '(card_number, card_number_regex)\n', (686, 718), False, 'import re\n'), ((1415, 1441), 're.match', 're.match', (['regex_name', 'name'], {}), '(regex_name, name)\n', (1423, 1441), False, 'import re\n'), ((1882, 1908), 're.match', 're.match', (['regex_date', 'date'], {}), '(regex_date, date)\n', (1890, 1908), False, 'import re\n'), ((2006, 2030), 'flask_restful.reqparse.RequestParser', 'reqparse.RequestParser', ([], {}), '()\n', (2028, 2030), False, 'from flask_restful import Resource, reqparse\n')] |
import asyncio
import unittest
from asyncio import (
gather,
sleep,
)
from unittest.mock import (
AsyncMock,
call,
)
from uuid import (
uuid4,
)
import aiopg
from minos.common import (
NotProvidedException,
)
from minos.common.testing import (
PostgresAsyncTestCase,
)
from minos.networks import (
BrokerConsumer,
BrokerMessageStatus,
BrokerMessageStrategy,
BrokerProducer,
BrokerPublisher,
)
from tests.utils import (
BASE_PATH,
FakeModel,
)
class TestProducer(PostgresAsyncTestCase):
CONFIG_FILE_PATH = BASE_PATH / "test_config.yml"
def setUp(self) -> None:
super().setUp()
self.consumer = BrokerConsumer.from_config(self.config)
self.producer = BrokerProducer.from_config(self.config, consumer=self.consumer)
async def asyncSetUp(self):
await super().asyncSetUp()
await self.consumer.setup()
await self.producer.setup()
async def asyncTearDown(self):
await self.producer.destroy()
await self.consumer.destroy()
await super().asyncTearDown()
def test_from_config_default(self):
self.assertIsInstance(self.producer, BrokerProducer)
async def test_from_config_raises(self):
with self.assertRaises(NotProvidedException):
BrokerProducer.from_config(config=self.config)
async def test_dispatch_one_internal_true(self):
mock = AsyncMock()
self.consumer.enqueue = mock
ok = await self.producer.dispatch_one((0, "GetOrder", bytes(), BrokerMessageStrategy.UNICAST))
self.assertTrue(ok)
self.assertEqual(1, mock.call_count)
self.assertEqual(call("GetOrder", -1, bytes()), mock.call_args)
async def test_dispatch_one_internal_false(self):
self.producer.consumer = None
publish_mock = AsyncMock()
self.producer.publish = publish_mock
ok = await self.producer.dispatch_one((0, "GetOrder", bytes(), BrokerMessageStrategy.UNICAST))
self.assertTrue(ok)
self.assertEqual(1, publish_mock.call_count)
self.assertEqual(call("GetOrder", bytes()), publish_mock.call_args)
async def test_dispatch_one_external_true(self):
mock = AsyncMock()
self.producer.publish = mock
ok = await self.producer.dispatch_one((0, "GetProduct", bytes(), BrokerMessageStrategy.UNICAST))
self.assertTrue(ok)
self.assertEqual(1, mock.call_count)
self.assertEqual(call("GetProduct", bytes()), mock.call_args)
async def test_dispatch_one_external_true_event(self):
mock = AsyncMock()
self.producer.publish = mock
ok = await self.producer.dispatch_one((0, "TicketAdded", bytes(), BrokerMessageStrategy.MULTICAST))
self.assertTrue(ok)
self.assertEqual(1, mock.call_count)
self.assertEqual(call("TicketAdded", bytes()), mock.call_args)
async def test_dispatch_one_external_false(self):
self.producer.publish = AsyncMock(return_value=False)
ok = await self.producer.dispatch_one((0, "GetOrder", bytes(), BrokerMessageStrategy.MULTICAST))
self.assertFalse(ok)
async def test_publish_true(self):
ok = await self.producer.publish(topic="TestKafkaSend", message=bytes())
self.assertTrue(ok)
async def test_publish_false(self):
self.producer.client.send_and_wait = AsyncMock(side_effect=ValueError)
ok = await self.producer.publish(topic="TestKafkaSend", message=bytes())
self.assertFalse(ok)
async def test_dispatch_forever(self):
mock = AsyncMock(side_effect=ValueError)
self.producer.dispatch = mock
try:
await gather(self.producer.dispatch_forever(), self._notify("producer_queue"))
except ValueError:
pass
self.assertEqual(1, mock.call_count)
async def test_dispatch_forever_without_notify(self):
mock_dispatch = AsyncMock(side_effect=[None, ValueError])
mock_count = AsyncMock(side_effect=[1, 0, 1])
self.producer.dispatch = mock_dispatch
self.producer._get_count = mock_count
try:
await self.producer.dispatch_forever(max_wait=0.01)
except ValueError:
pass
self.assertEqual(2, mock_dispatch.call_count)
self.assertEqual(3, mock_count.call_count)
async def test_concurrency_dispatcher(self):
model = FakeModel("foo")
identifier = uuid4()
broker_publisher = BrokerPublisher.from_config(config=self.config)
async with broker_publisher:
for x in range(60):
await broker_publisher.send(
model, "CommandBroker-Delete", identifier=identifier, reply_topic="TestDeleteReply"
)
async with aiopg.connect(**self.broker_queue_db) as connect:
async with connect.cursor() as cur:
await cur.execute("SELECT COUNT(*) FROM producer_queue")
records = await cur.fetchone()
assert records[0] == 60
await asyncio.gather(*(self.producer.dispatch() for _ in range(6)))
async with aiopg.connect(**self.broker_queue_db) as connect:
async with connect.cursor() as cur:
await cur.execute("SELECT COUNT(*) FROM producer_queue")
records = await cur.fetchone()
assert records[0] == 0
async def test_if_commands_was_deleted(self):
async with BrokerPublisher.from_config(config=self.config) as broker_publisher:
await broker_publisher.send(FakeModel("Foo"), "TestDeleteReply")
await broker_publisher.send(FakeModel("Foo"), "TestDeleteReply")
await self.producer.dispatch()
async with aiopg.connect(**self.broker_queue_db) as connection:
async with connection.cursor() as cursor:
await cursor.execute("SELECT COUNT(*) FROM producer_queue WHERE topic = '%s'" % "TestDeleteReply")
self.assertEqual(0, (await cursor.fetchone())[0])
async def test_if_commands_retry_was_incremented(self):
model = FakeModel("foo")
identifier = uuid4()
async with BrokerPublisher.from_config(config=self.config) as broker_publisher:
await broker_publisher.send(
model, "TestDeleteOrderReply", identifier=identifier, status=BrokerMessageStatus.SUCCESS
)
await broker_publisher.send(
model, "TestDeleteOrderReply", identifier=identifier, status=BrokerMessageStatus.SUCCESS
)
self.producer.publish = AsyncMock(return_value=False)
await self.producer.dispatch()
async with aiopg.connect(**self.broker_queue_db) as connection:
async with connection.cursor() as cursor:
await cursor.execute("SELECT COUNT(*) FROM producer_queue WHERE topic = 'TestDeleteOrderReply'")
self.assertEqual(2, (await cursor.fetchone())[0])
await cursor.execute("SELECT retry FROM producer_queue WHERE id=1;")
self.assertEqual(1, (await cursor.fetchone())[0])
await cursor.execute("SELECT retry FROM producer_queue WHERE id=2;")
self.assertEqual(1, (await cursor.fetchone())[0])
async def _notify(self, name):
await sleep(0.2)
async with aiopg.connect(**self.broker_queue_db) as connect:
async with connect.cursor() as cur:
await cur.execute(f"NOTIFY {name!s};")
if __name__ == "__main__":
unittest.main()
| [
"minos.networks.BrokerPublisher.from_config",
"minos.networks.BrokerProducer.from_config",
"unittest.mock.AsyncMock",
"minos.networks.BrokerConsumer.from_config",
"uuid.uuid4",
"asyncio.sleep",
"unittest.main",
"tests.utils.FakeModel",
"aiopg.connect"
] | [((7562, 7577), 'unittest.main', 'unittest.main', ([], {}), '()\n', (7575, 7577), False, 'import unittest\n'), ((678, 717), 'minos.networks.BrokerConsumer.from_config', 'BrokerConsumer.from_config', (['self.config'], {}), '(self.config)\n', (704, 717), False, 'from minos.networks import BrokerConsumer, BrokerMessageStatus, BrokerMessageStrategy, BrokerProducer, BrokerPublisher\n'), ((742, 805), 'minos.networks.BrokerProducer.from_config', 'BrokerProducer.from_config', (['self.config'], {'consumer': 'self.consumer'}), '(self.config, consumer=self.consumer)\n', (768, 805), False, 'from minos.networks import BrokerConsumer, BrokerMessageStatus, BrokerMessageStrategy, BrokerProducer, BrokerPublisher\n'), ((1426, 1437), 'unittest.mock.AsyncMock', 'AsyncMock', ([], {}), '()\n', (1435, 1437), False, 'from unittest.mock import AsyncMock, call\n'), ((1842, 1853), 'unittest.mock.AsyncMock', 'AsyncMock', ([], {}), '()\n', (1851, 1853), False, 'from unittest.mock import AsyncMock, call\n'), ((2230, 2241), 'unittest.mock.AsyncMock', 'AsyncMock', ([], {}), '()\n', (2239, 2241), False, 'from unittest.mock import AsyncMock, call\n'), ((2604, 2615), 'unittest.mock.AsyncMock', 'AsyncMock', ([], {}), '()\n', (2613, 2615), False, 'from unittest.mock import AsyncMock, call\n'), ((2992, 3021), 'unittest.mock.AsyncMock', 'AsyncMock', ([], {'return_value': '(False)'}), '(return_value=False)\n', (3001, 3021), False, 'from unittest.mock import AsyncMock, call\n'), ((3391, 3424), 'unittest.mock.AsyncMock', 'AsyncMock', ([], {'side_effect': 'ValueError'}), '(side_effect=ValueError)\n', (3400, 3424), False, 'from unittest.mock import AsyncMock, call\n'), ((3594, 3627), 'unittest.mock.AsyncMock', 'AsyncMock', ([], {'side_effect': 'ValueError'}), '(side_effect=ValueError)\n', (3603, 3627), False, 'from unittest.mock import AsyncMock, call\n'), ((3943, 3984), 'unittest.mock.AsyncMock', 'AsyncMock', ([], {'side_effect': '[None, ValueError]'}), '(side_effect=[None, ValueError])\n', (3952, 3984), False, 'from unittest.mock import AsyncMock, call\n'), ((4006, 4038), 'unittest.mock.AsyncMock', 'AsyncMock', ([], {'side_effect': '[1, 0, 1]'}), '(side_effect=[1, 0, 1])\n', (4015, 4038), False, 'from unittest.mock import AsyncMock, call\n'), ((4426, 4442), 'tests.utils.FakeModel', 'FakeModel', (['"""foo"""'], {}), "('foo')\n", (4435, 4442), False, 'from tests.utils import BASE_PATH, FakeModel\n'), ((4464, 4471), 'uuid.uuid4', 'uuid4', ([], {}), '()\n', (4469, 4471), False, 'from uuid import uuid4\n'), ((4500, 4547), 'minos.networks.BrokerPublisher.from_config', 'BrokerPublisher.from_config', ([], {'config': 'self.config'}), '(config=self.config)\n', (4527, 4547), False, 'from minos.networks import BrokerConsumer, BrokerMessageStatus, BrokerMessageStrategy, BrokerProducer, BrokerPublisher\n'), ((6121, 6137), 'tests.utils.FakeModel', 'FakeModel', (['"""foo"""'], {}), "('foo')\n", (6130, 6137), False, 'from tests.utils import BASE_PATH, FakeModel\n'), ((6159, 6166), 'uuid.uuid4', 'uuid4', ([], {}), '()\n', (6164, 6166), False, 'from uuid import uuid4\n'), ((1310, 1356), 'minos.networks.BrokerProducer.from_config', 'BrokerProducer.from_config', ([], {'config': 'self.config'}), '(config=self.config)\n', (1336, 1356), False, 'from minos.networks import BrokerConsumer, BrokerMessageStatus, BrokerMessageStrategy, BrokerProducer, BrokerPublisher\n'), ((4805, 4842), 'aiopg.connect', 'aiopg.connect', ([], {}), '(**self.broker_queue_db)\n', (4818, 4842), False, 'import aiopg\n'), ((5153, 5190), 'aiopg.connect', 'aiopg.connect', ([], {}), '(**self.broker_queue_db)\n', (5166, 5190), False, 'import aiopg\n'), ((5473, 5520), 'minos.networks.BrokerPublisher.from_config', 'BrokerPublisher.from_config', ([], {'config': 'self.config'}), '(config=self.config)\n', (5500, 5520), False, 'from minos.networks import BrokerConsumer, BrokerMessageStatus, BrokerMessageStrategy, BrokerProducer, BrokerPublisher\n'), ((5756, 5793), 'aiopg.connect', 'aiopg.connect', ([], {}), '(**self.broker_queue_db)\n', (5769, 5793), False, 'import aiopg\n'), ((6187, 6234), 'minos.networks.BrokerPublisher.from_config', 'BrokerPublisher.from_config', ([], {'config': 'self.config'}), '(config=self.config)\n', (6214, 6234), False, 'from minos.networks import BrokerConsumer, BrokerMessageStatus, BrokerMessageStrategy, BrokerProducer, BrokerPublisher\n'), ((6613, 6642), 'unittest.mock.AsyncMock', 'AsyncMock', ([], {'return_value': '(False)'}), '(return_value=False)\n', (6622, 6642), False, 'from unittest.mock import AsyncMock, call\n'), ((6706, 6743), 'aiopg.connect', 'aiopg.connect', ([], {}), '(**self.broker_queue_db)\n', (6719, 6743), False, 'import aiopg\n'), ((7346, 7356), 'asyncio.sleep', 'sleep', (['(0.2)'], {}), '(0.2)\n', (7351, 7356), False, 'from asyncio import gather, sleep\n'), ((7376, 7413), 'aiopg.connect', 'aiopg.connect', ([], {}), '(**self.broker_queue_db)\n', (7389, 7413), False, 'import aiopg\n'), ((5582, 5598), 'tests.utils.FakeModel', 'FakeModel', (['"""Foo"""'], {}), "('Foo')\n", (5591, 5598), False, 'from tests.utils import BASE_PATH, FakeModel\n'), ((5659, 5675), 'tests.utils.FakeModel', 'FakeModel', (['"""Foo"""'], {}), "('Foo')\n", (5668, 5675), False, 'from tests.utils import BASE_PATH, FakeModel\n')] |
# -*- coding: utf-8 -*-
"""
Highcharts Demos
Donut chart: http://www.highcharts.com/demo/pie-donut
"""
from highcharts import Highchart
H = Highchart(width = 850, height = 400)
data = [{
'y': 55.11,
'color': 'Highcharts.getOptions().colors[0]',
'drilldown': {
'name': 'MSIE versions',
'categories': ['MSIE 6.0', 'MSIE 7.0', 'MSIE 8.0', 'MSIE 9.0'],
'data': [10.85, 7.35, 33.06, 2.81],
'color': 'Highcharts.getOptions().colors[0]'
}
}, {
'y': 21.63,
'color': 'Highcharts.getOptions().colors[1]',
'drilldown': {
'name': 'Firefox versions',
'categories': ['Firefox 2.0', 'Firefox 3.0', 'Firefox 3.5', 'Firefox 3.6', 'Firefox 4.0'],
'data': [0.20, 0.83, 1.58, 13.12, 5.43],
'color': 'Highcharts.getOptions().colors[1]'
}
}, {
'y': 11.94,
'color': 'Highcharts.getOptions().colors[2]',
'drilldown': {
'name': 'Chrome versions',
'categories': ['Chrome 5.0', 'Chrome 6.0', 'Chrome 7.0', 'Chrome 8.0', 'Chrome 9.0',
'Chrome 10.0', 'Chrome 11.0', 'Chrome 12.0'],
'data': [0.12, 0.19, 0.12, 0.36, 0.32, 9.91, 0.50, 0.22],
'color': 'Highcharts.getOptions().colors[2]'
}
}, {
'y': 7.15,
'color': 'Highcharts.getOptions().colors[3]',
'drilldown': {
'name': 'Safari versions',
'categories': ['Safari 5.0', 'Safari 4.0', 'Safari Win 5.0', 'Safari 4.1', 'Safari/Maxthon',
'Safari 3.1', 'Safari 4.1'],
'data': [4.55, 1.42, 0.23, 0.21, 0.20, 0.19, 0.14],
'color': 'Highcharts.getOptions().colors[3]'
}
}, {
'y': 2.14,
'color': 'Highcharts.getOptions().colors[4]',
'drilldown': {
'name': 'Opera versions',
'categories': ['Opera 9.x', 'Opera 10.x', 'Opera 11.x'],
'data': [ 0.12, 0.37, 1.65],
'color': 'Highcharts.getOptions().colors[4]'
}
}]
options = {
'chart': {
'type': 'pie'
},
'title': {
'text': 'Browser market share, April, 2011'
},
'yAxis': {
'title': {
'text': 'Total percent market share'
}
},
'plotOptions': {
'pie': {
'shadow': False,
'center': ['50%', '50%']
}
},
'tooltip': {
'valueSuffix': '%'
},
}
categories = ['MSIE', 'Firefox', 'Chrome', 'Safari', 'Opera']
browserData = []
versionsData = []
for i in range(len(data)):
browserData.append({
'name': categories[i],
'y': data[i]['y'],
'color': data[i]['color']
})
drillDataLen = len(data[i]['drilldown']['data'])
for j in range(drillDataLen):
brightness = 0.2 - (j / drillDataLen) / 5;
versionsData.append({
'name': data[i]['drilldown']['categories'][j],
'y': data[i]['drilldown']['data'][j],
'color': 'Highcharts.Color(' + data[i]['color'] + ').brighten(' + str(brightness) + ').get()'
})
H.set_dict_options(options)
H.add_data_set(browserData, 'pie', 'Browsers', size='60%',
dataLabels={
'formatter': 'function () { \
return this.y > 5 ? this.point.name : null;\
}',
'color': 'white',
'distance': -30
})
H.add_data_set(versionsData, 'pie', 'Versions', size='80%',
innerSize='60%',
dataLabels={
'formatter': "function () {\
return this.y > 1 ? '<b>' + this.point.name + ':</b> ' + this.y + '%' : null;\
}"
})
H.htmlcontent | [
"highcharts.Highchart"
] | [((141, 173), 'highcharts.Highchart', 'Highchart', ([], {'width': '(850)', 'height': '(400)'}), '(width=850, height=400)\n', (150, 173), False, 'from highcharts import Highchart\n')] |
import discord
import os
import asyncio
from discord.ext import commands
from random import randint
from cogs.libs import Settings
from cogs.libs import Utils
class Messages(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_message(self, message):
channel = message.channel
if isinstance(channel, discord.TextChannel):
content_of_message = message.content
content_of_message = content_of_message.lower()
author_id = str(message.author.id)
author_name = message.author.name
# message_mentions = message.mentions
if author_id != str(Settings.CIRILABOTID):
print("\nAlguien escribio un mensaje")
print(author_name)
await channel.send("Hola")
def setup(bot):
bot.add_cog(Messages(bot)) | [
"discord.ext.commands.Cog.listener"
] | [((248, 271), 'discord.ext.commands.Cog.listener', 'commands.Cog.listener', ([], {}), '()\n', (269, 271), False, 'from discord.ext import commands\n')] |
import argparse
import multiprocessing
import random
import time
import torch.optim as optim
from auto_LiRPA.eps_scheduler import LinearScheduler, AdaptiveScheduler, SmoothedScheduler, FixedScheduler
from auto_LiRPA.perturbations import *
from auto_LiRPA.utils import MultiAverageMeter
from torch.nn import CrossEntropyLoss
from torch.utils.data import DataLoader
from lirpa_integration import SemanticTransformation
from transformations.twisting import TwistingZ
from relaxations.interval import Interval
from data_processing import datasets
from auto_LiRPA import BoundedModule, BoundedTensor
from pointnet.model import PointNet
from util.argparse import parse_theta
parser = argparse.ArgumentParser()
parser.add_argument("--verify", action="store_true", help='verification mode, do not train')
parser.add_argument("--load", type=str, default="", help='Load pretrained model')
parser.add_argument("--device", type=str, default="cuda", choices=["cpu", "cuda"], help='use cpu or cuda')
parser.add_argument("--data", type=str, default="MNIST", choices=["MNIST", "CIFAR"], help='dataset')
parser.add_argument("--seed", type=int, default=100, help='random seed')
parser.add_argument("--eps", type=float, default=0.01, help='Target training epsilon')
parser.add_argument("--bound_type", type=str, default="CROWN-IBP",
choices=["IBP", "CROWN-IBP", "CROWN", "CROWN-FAST"], help='method of bound analysis')
parser.add_argument("--model", type=str, default="resnet", help='model name (mlp_3layer, cnn_4layer, cnn_6layer, cnn_7layer, resnet)')
parser.add_argument("--num_epochs", type=int, default=100, help='number of total epochs')
parser.add_argument("--batch_size", type=int, default=256, help='batch size')
parser.add_argument("--lr", type=float, default=5e-4, help='learning rate')
parser.add_argument("--scheduler_name", type=str, default="SmoothedScheduler",
choices=["LinearScheduler", "AdaptiveScheduler", "SmoothedScheduler", "FixedScheduler"], help='epsilon scheduler')
parser.add_argument("--scheduler_opts", type=str, default="start=3,length=60", help='options for epsilon scheduler')
parser.add_argument("--bound_opts", type=str, default=None, choices=["same-slope", "zero-lb", "one-lb"],
help='bound options')
parser.add_argument("--conv_mode", type=str, choices=["matrix", "patches"], default="matrix")
parser.add_argument("--save_model", type=str, default='')
parser.add_argument("--num_points", type=int, default=64)
parser.add_argument('--pooling', type=str, default='max', choices=['max', 'avg'], help="The pooling function to use")
args = parser.parse_args()
def Train(model, t, loader, eps_scheduler, norm, train, opt, bound_type, method='robust'):
num_class = 40
meter = MultiAverageMeter()
if train:
model.train()
eps_scheduler.train()
eps_scheduler.step_epoch()
eps_scheduler.set_epoch_length(int((len(loader.dataset) + loader.batch_size - 1) / loader.batch_size))
else:
model.eval()
eps_scheduler.eval()
for i, (data, _, labels) in enumerate(loader):
start = time.time()
data = data.float()
labels = labels.squeeze()
eps_scheduler.step_batch()
eps = eps_scheduler.get_eps()
# For small eps just use natural training, no need to compute LiRPA bounds
batch_method = method
if eps < 1e-20:
batch_method = "natural"
if train:
opt.zero_grad()
# generate specifications
c = torch.eye(num_class).type_as(data)[labels].unsqueeze(1) - torch.eye(num_class).type_as(data).unsqueeze(0)
# remove specifications to self
I = (~(labels.data.unsqueeze(1) == torch.arange(num_class).type_as(labels.data).unsqueeze(0)))
c = (c[I].view(data.size(0), num_class - 1, num_class))
# bound input for Linf norm used only
data_ub = data + eps
data_lb = data - eps
if list(model.parameters())[0].is_cuda:
data, labels, c = data.cuda(), labels.cuda(), c.cuda()
data_lb, data_ub = data_lb.cuda(), data_ub.cuda()
ptb = PerturbationLpNorm(norm=np.inf, eps=eps, x_L=data_lb, x_U=data_ub)
x = BoundedTensor(data, ptb)
output = model(x)
regular_ce = CrossEntropyLoss()(output, labels) # regular CrossEntropyLoss used for warming up
meter.update('CE', regular_ce.item(), x.size(0))
meter.update('Err', torch.sum(torch.argmax(output, dim=1) != labels).cpu().detach().numpy() / x.size(0), x.size(0))
if batch_method == "robust":
if bound_type == "IBP":
lb, ub = model.compute_bounds(IBP=True, C=c, method=None)
elif bound_type == "CROWN":
lb, ub = model.compute_bounds(IBP=False, C=c, method="backward", bound_upper=False)
elif bound_type == "CROWN-IBP":
# lb, ub = model.compute_bounds(ptb=ptb, IBP=True, x=data, C=c, method="backward") # pure IBP bound
# we use a mixed IBP and CROWN-IBP bounds, leading to better performance (Zhang et al., ICLR 2020)
factor = (eps_scheduler.get_max_eps() - eps) / eps_scheduler.get_max_eps()
ilb, iub = model.compute_bounds(IBP=True, C=c, method=None)
if factor < 1e-5:
lb = ilb
else:
clb, cub = model.compute_bounds(IBP=False, C=c, method="backward", bound_upper=False)
lb = clb * factor + ilb * (1 - factor)
elif bound_type == "CROWN-FAST":
# model.compute_bounds(IBP=True, C=c, method=None)
lb, ub = model.compute_bounds(IBP=True, C=c, method=None)
lb, ub = model.compute_bounds(IBP=False, C=c, method="backward", bound_upper=False)
# Pad zero at the beginning for each example, and use fake label "0" for all examples
lb_padded = torch.cat((torch.zeros(size=(lb.size(0), 1), dtype=lb.dtype, device=lb.device), lb), dim=1)
fake_labels = torch.zeros(size=(lb.size(0),), dtype=torch.int64, device=lb.device)
robust_ce = CrossEntropyLoss()(-lb_padded, fake_labels)
if batch_method == "robust":
loss = robust_ce
elif batch_method == "natural":
loss = regular_ce
if train:
loss.backward()
eps_scheduler.update_loss(loss.item() - regular_ce.item())
opt.step()
meter.update('Loss', loss.item(), data.size(0))
if batch_method != "natural":
meter.update('Robust_CE', robust_ce.item(), data.size(0))
# For an example, if lower bounds of margins is >0 for all classes, the output is verifiably correct.
# If any margin is < 0 this example is counted as an error
meter.update('Verified_Err', torch.sum((lb < 0).any(dim=1)).item() / data.size(0), data.size(0))
meter.update('Time', time.time() - start)
if i % 50 == 0 and train:
print('[{:2d}:{:4d}]: eps={:.8f} {}'.format(t, i, eps, meter))
print('[{:2d}:{:4d}]: eps={:.8f} {}'.format(t, i, eps, meter))
def main(args):
torch.manual_seed(args.seed)
torch.cuda.manual_seed_all(args.seed)
random.seed(args.seed)
np.random.seed(args.seed)
## Step 1: Initial original model as usual, see model details in models/example_feedforward.py and models/example_resnet.py
model_ori = PointNet(
number_points=args.num_points,
num_classes=40,
pool_function=args.pooling
)
if args.load:
state_dict = torch.load(args.load)
model_ori.load_state_dict(state_dict)
print(state_dict)
## Step 2: Prepare dataset as usual
train_data = datasets.modelnet40(num_points=args.num_points, split='train', rotate='z')
test_data = datasets.modelnet40(num_points=args.num_points, split='test', rotate='none')
train_data = DataLoader(
dataset=train_data,
batch_size=args.batch_size,
shuffle=True,
num_workers=4
)
test_data = DataLoader(
dataset=test_data,
batch_size=args.batch_size,
shuffle=False,
num_workers=4
)
dummy_input = torch.randn(2, args.num_points, 3)
## Step 3: wrap model with auto_LiRPA
# The second parameter dummy_input is for constructing the trace of the computational graph.
model = BoundedModule(model_ori, dummy_input, bound_opts={'relu': args.bound_opts, 'conv_mode': args.conv_mode}, device=args.device)
## Step 4 prepare optimizer, epsilon scheduler and learning rate scheduler
opt = optim.Adam(model.parameters(), lr=args.lr)
norm = float(args.norm)
lr_scheduler = optim.lr_scheduler.StepLR(opt, step_size=10, gamma=0.5)
eps_scheduler = eval(args.scheduler_name)(args.eps, args.scheduler_opts)
print("Model structure: \n", str(model_ori))
## Step 5: start training
if args.verify:
eps_scheduler = FixedScheduler(args.eps)
with torch.no_grad():
Train(model, 1, test_data, eps_scheduler, norm, False, None, args.bound_type)
else:
timer = 0.0
for t in range(1, args.num_epochs + 1):
if eps_scheduler.reached_max_eps():
# Only decay learning rate after reaching the maximum eps
lr_scheduler.step()
print("Epoch {}, learning rate {}".format(t, lr_scheduler.get_lr()))
start_time = time.time()
Train(model, t, train_data, eps_scheduler, norm, True, opt, args.bound_type)
epoch_time = time.time() - start_time
timer += epoch_time
print('Epoch time: {:.4f}, Total time: {:.4f}'.format(epoch_time, timer))
print("Evaluating...")
with torch.no_grad():
Train(model, t, test_data, eps_scheduler, norm, False, None, args.bound_type)
torch.save(model.state_dict(), args.save_model if args.save_model != "" else args.model)
if __name__ == "__main__":
main(args)
| [
"torch.nn.CrossEntropyLoss",
"argparse.ArgumentParser",
"pointnet.model.PointNet",
"auto_LiRPA.eps_scheduler.FixedScheduler",
"torch.optim.lr_scheduler.StepLR",
"random.seed",
"data_processing.datasets.modelnet40",
"auto_LiRPA.BoundedModule",
"auto_LiRPA.BoundedTensor",
"torch.utils.data.DataLoade... | [((682, 707), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (705, 707), False, 'import argparse\n'), ((2762, 2781), 'auto_LiRPA.utils.MultiAverageMeter', 'MultiAverageMeter', ([], {}), '()\n', (2779, 2781), False, 'from auto_LiRPA.utils import MultiAverageMeter\n'), ((7264, 7286), 'random.seed', 'random.seed', (['args.seed'], {}), '(args.seed)\n', (7275, 7286), False, 'import random\n'), ((7462, 7550), 'pointnet.model.PointNet', 'PointNet', ([], {'number_points': 'args.num_points', 'num_classes': '(40)', 'pool_function': 'args.pooling'}), '(number_points=args.num_points, num_classes=40, pool_function=args.\n pooling)\n', (7470, 7550), False, 'from pointnet.model import PointNet\n'), ((7769, 7843), 'data_processing.datasets.modelnet40', 'datasets.modelnet40', ([], {'num_points': 'args.num_points', 'split': '"""train"""', 'rotate': '"""z"""'}), "(num_points=args.num_points, split='train', rotate='z')\n", (7788, 7843), False, 'from data_processing import datasets\n'), ((7860, 7936), 'data_processing.datasets.modelnet40', 'datasets.modelnet40', ([], {'num_points': 'args.num_points', 'split': '"""test"""', 'rotate': '"""none"""'}), "(num_points=args.num_points, split='test', rotate='none')\n", (7879, 7936), False, 'from data_processing import datasets\n'), ((7955, 8046), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'train_data', 'batch_size': 'args.batch_size', 'shuffle': '(True)', 'num_workers': '(4)'}), '(dataset=train_data, batch_size=args.batch_size, shuffle=True,\n num_workers=4)\n', (7965, 8046), False, 'from torch.utils.data import DataLoader\n'), ((8097, 8188), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'test_data', 'batch_size': 'args.batch_size', 'shuffle': '(False)', 'num_workers': '(4)'}), '(dataset=test_data, batch_size=args.batch_size, shuffle=False,\n num_workers=4)\n', (8107, 8188), False, 'from torch.utils.data import DataLoader\n'), ((8428, 8556), 'auto_LiRPA.BoundedModule', 'BoundedModule', (['model_ori', 'dummy_input'], {'bound_opts': "{'relu': args.bound_opts, 'conv_mode': args.conv_mode}", 'device': 'args.device'}), "(model_ori, dummy_input, bound_opts={'relu': args.bound_opts,\n 'conv_mode': args.conv_mode}, device=args.device)\n", (8441, 8556), False, 'from auto_LiRPA import BoundedModule, BoundedTensor\n'), ((8733, 8788), 'torch.optim.lr_scheduler.StepLR', 'optim.lr_scheduler.StepLR', (['opt'], {'step_size': '(10)', 'gamma': '(0.5)'}), '(opt, step_size=10, gamma=0.5)\n', (8758, 8788), True, 'import torch.optim as optim\n'), ((3122, 3133), 'time.time', 'time.time', ([], {}), '()\n', (3131, 3133), False, 'import time\n'), ((4225, 4249), 'auto_LiRPA.BoundedTensor', 'BoundedTensor', (['data', 'ptb'], {}), '(data, ptb)\n', (4238, 4249), False, 'from auto_LiRPA import BoundedModule, BoundedTensor\n'), ((8990, 9014), 'auto_LiRPA.eps_scheduler.FixedScheduler', 'FixedScheduler', (['args.eps'], {}), '(args.eps)\n', (9004, 9014), False, 'from auto_LiRPA.eps_scheduler import LinearScheduler, AdaptiveScheduler, SmoothedScheduler, FixedScheduler\n'), ((4298, 4316), 'torch.nn.CrossEntropyLoss', 'CrossEntropyLoss', ([], {}), '()\n', (4314, 4316), False, 'from torch.nn import CrossEntropyLoss\n'), ((9477, 9488), 'time.time', 'time.time', ([], {}), '()\n', (9486, 9488), False, 'import time\n'), ((6163, 6181), 'torch.nn.CrossEntropyLoss', 'CrossEntropyLoss', ([], {}), '()\n', (6179, 6181), False, 'from torch.nn import CrossEntropyLoss\n'), ((6970, 6981), 'time.time', 'time.time', ([], {}), '()\n', (6979, 6981), False, 'import time\n'), ((9603, 9614), 'time.time', 'time.time', ([], {}), '()\n', (9612, 9614), False, 'import time\n')] |
# !/usr/bin/env python
# Copyright (c) 2019 Computer Vision Center (CVC) at the Universitat Autonoma de
# Barcelona (UAB).
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
#
# Modified by <NAME> on 20 April 2020
import argparse
import datetime
import glob
import os
import random
import sys
import time
from PIL import Image
from PIL.PngImagePlugin import PngInfo
try:
sys.path.append(glob.glob('../carla/dist/carla-*%d.%d-%s.egg' % (
sys.version_info.major,
sys.version_info.minor,
'win-amd64' if os.name == 'nt' else 'linux-x86_64'))[0])
except IndexError:
pass
import carla
import math
from dotmap import DotMap
try:
import pygame
except ImportError:
raise RuntimeError('cannot import pygame, make sure pygame package is installed')
try:
import numpy as np
except ImportError:
raise RuntimeError('cannot import numpy, make sure numpy package is installed')
try:
import queue
except ImportError:
import Queue as queue
from agents.navigation.agent import Agent, AgentState
from agents.navigation.local_planner import LocalPlanner
from agents.navigation.global_route_planner import GlobalRoutePlanner
from agents.tools.misc import is_within_distance_ahead, compute_magnitude_angle
from agents.navigation.global_route_planner_dao import GlobalRoutePlannerDAO
def is_within_distance(target_location, current_location, orientation, max_distance, d_angle_th_up, d_angle_th_low=0):
"""
Check if a target object is within a certain distance from a reference object.
A vehicle in front would be something around 0 deg, while one behind around 180 deg.
:param target_location: location of the target object
:param current_location: location of the reference object
:param orientation: orientation of the reference object
:param max_distance: maximum allowed distance
:param d_angle_th_up: upper thereshold for angle
:param d_angle_th_low: low thereshold for angle (optional, default is 0)
:return: True if target object is within max_distance ahead of the reference object
"""
target_vector = np.array([target_location.x - current_location.x, target_location.y - current_location.y])
norm_target = np.linalg.norm(target_vector)
# If the vector is too short, we can simply stop here
if norm_target < 0.001:
return True
if norm_target > max_distance:
return False
forward_vector = np.array(
[math.cos(math.radians(orientation)), math.sin(math.radians(orientation))])
d_angle = math.degrees(math.acos(np.clip(np.dot(forward_vector, target_vector) / norm_target, -1., 1.)))
return d_angle_th_low < d_angle < d_angle_th_up
def compute_distance(location_1, location_2):
"""
Euclidean distance between 3D points
:param location_1, location_2: 3D points
"""
x = location_2.x - location_1.x
y = location_2.y - location_1.y
z = location_2.z - location_1.z
norm = np.linalg.norm([x, y, z]) + np.finfo(float).eps
return norm
class CarlaSyncMode(object):
"""
Context manager to synchronize output from different sensors. Synchronous
mode is enabled as long as we are inside this context
with CarlaSyncMode(world, sensors) as sync_mode:
while True:
data = sync_mode.tick(timeout=1.0)
"""
def __init__(self, world, *sensors, **kwargs):
self.world = world
self.sensors = sensors
self.frame = None
self.delta_seconds = 1.0 / kwargs.get('fps', 20)
self._queues = []
self._settings = None
self.start()
def start(self):
self._settings = self.world.get_settings()
self.frame = self.world.apply_settings(carla.WorldSettings(
no_rendering_mode=False,
synchronous_mode=True,
fixed_delta_seconds=self.delta_seconds))
def make_queue(register_event):
q = queue.Queue()
register_event(q.put)
self._queues.append(q)
make_queue(self.world.on_tick)
for sensor in self.sensors:
make_queue(sensor.listen)
def tick(self, timeout):
self.frame = self.world.tick()
data = [self._retrieve_data(q, timeout) for q in self._queues]
assert all(x.frame == self.frame for x in data)
return data
def __exit__(self, *args, **kwargs):
self.world.apply_settings(self._settings)
def _retrieve_data(self, sensor_queue, timeout):
while True:
data = sensor_queue.get(timeout=timeout)
if data.frame == self.frame:
return data
def draw_image(surface, image, blend=False):
array = np.frombuffer(image.raw_data, dtype=np.dtype("uint8"))
array = np.reshape(array, (image.height, image.width, 4))
array = array[:, :, :3]
array = array[:, :, ::-1]
image_surface = pygame.surfarray.make_surface(array.swapaxes(0, 1))
if blend:
image_surface.set_alpha(100)
surface.blit(image_surface, (0, 0))
def get_font():
fonts = [x for x in pygame.font.get_fonts()]
default_font = 'ubuntumono'
font = default_font if default_font in fonts else fonts[0]
font = pygame.font.match_font(font)
return pygame.font.Font(font, 14)
def should_quit():
for event in pygame.event.get():
if event.type == pygame.QUIT:
return True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_ESCAPE:
return True
return False
def clamp(value, minimum=0.0, maximum=100.0):
return max(minimum, min(value, maximum))
class Sun(object):
def __init__(self, azimuth, altitude):
self.azimuth = azimuth
self.altitude = altitude
self._t = 0.0
def tick(self, delta_seconds):
self._t += 0.008 * delta_seconds
self._t %= 2.0 * math.pi
self.azimuth += 0.25 * delta_seconds
self.azimuth %= 360.0
min_alt, max_alt = [20, 90]
self.altitude = 0.5 * (max_alt + min_alt) + 0.5 * (max_alt - min_alt) * math.cos(self._t)
def __str__(self):
return 'Sun(alt: %.2f, azm: %.2f)' % (self.altitude, self.azimuth)
class Storm(object):
def __init__(self, precipitation):
self._t = precipitation if precipitation > 0.0 else -50.0
self._increasing = True
self.clouds = 0.0
self.rain = 0.0
self.wetness = 0.0
self.puddles = 0.0
self.wind = 0.0
self.fog = 0.0
def tick(self, delta_seconds):
delta = (1.3 if self._increasing else -1.3) * delta_seconds
self._t = clamp(delta + self._t, -250.0, 100.0)
self.clouds = clamp(self._t + 40.0, 0.0, 90.0)
self.clouds = clamp(self._t + 40.0, 0.0, 60.0)
self.rain = clamp(self._t, 0.0, 80.0)
delay = -10.0 if self._increasing else 90.0
self.puddles = clamp(self._t + delay, 0.0, 85.0)
self.wetness = clamp(self._t * 5, 0.0, 100.0)
self.wind = 5.0 if self.clouds <= 20 else 90 if self.clouds >= 70 else 40
self.fog = clamp(self._t - 10, 0.0, 30.0)
if self._t == -250.0:
self._increasing = True
if self._t == 100.0:
self._increasing = False
def __str__(self):
return 'Storm(clouds=%d%%, rain=%d%%, wind=%d%%)' % (self.clouds, self.rain, self.wind)
class Weather(object):
def __init__(self, world, changing_weather_speed):
self.world = world
self.reset()
self.weather = world.get_weather()
self.changing_weather_speed = changing_weather_speed
self._sun = Sun(self.weather.sun_azimuth_angle, self.weather.sun_altitude_angle)
self._storm = Storm(self.weather.precipitation)
def reset(self):
weather_params = carla.WeatherParameters(sun_altitude_angle=90.)
self.world.set_weather(weather_params)
def tick(self):
self._sun.tick(self.changing_weather_speed)
self._storm.tick(self.changing_weather_speed)
self.weather.cloudiness = self._storm.clouds
self.weather.precipitation = self._storm.rain
self.weather.precipitation_deposits = self._storm.puddles
self.weather.wind_intensity = self._storm.wind
self.weather.fog_density = self._storm.fog
self.weather.wetness = self._storm.wetness
self.weather.sun_azimuth_angle = self._sun.azimuth
self.weather.sun_altitude_angle = self._sun.altitude
self.world.set_weather(self.weather)
def __str__(self):
return '%s %s' % (self._sun, self._storm)
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--vision_size', type=int, default=84)
parser.add_argument('--vision_fov', type=int, default=90)
parser.add_argument('--weather', default=False, action='store_true')
parser.add_argument('--frame_skip', type=int, default=1),
parser.add_argument('--steps', type=int, default=100000)
parser.add_argument('--multiagent', default=False, action='store_true'),
parser.add_argument('--lane', type=int, default=0)
parser.add_argument('--lights', default=False, action='store_true')
args = parser.parse_args()
return args
class LocalPlannerModified(LocalPlanner):
def __del__(self):
pass # otherwise it deletes our vehicle object
def run_step(self):
return super().run_step(debug=False) # otherwise by default shows waypoints, that interfere with our camera
class RoamingAgent(Agent):
"""
RoamingAgent implements a basic agent that navigates scenes making random
choices when facing an intersection.
This agent respects traffic lights and other vehicles.
NOTE: need to re-create after each env reset
"""
def __init__(self, env):
"""
:param vehicle: actor to apply to local planner logic onto
"""
vehicle = env.vehicle
follow_traffic_lights = env.follow_traffic_lights
super(RoamingAgent, self).__init__(vehicle)
self._proximity_threshold = 10.0 # meters
self._state = AgentState.NAVIGATING
self._local_planner = LocalPlannerModified(self._vehicle)
self._follow_traffic_lights = follow_traffic_lights
def compute_action(self):
action, traffic_light = self.run_step()
throttle = action.throttle
brake = action.brake
steer = action.steer
#print('tbsl:', throttle, brake, steer, traffic_light)
if brake == 0.0:
return np.array([throttle, steer])
else:
return np.array([-brake, steer])
def run_step(self):
"""
Execute one step of navigation.
:return: carla.VehicleControl
"""
# is there an obstacle in front of us?
hazard_detected = False
# retrieve relevant elements for safe navigation, i.e.: traffic lights and other vehicles
actor_list = self._world.get_actors()
vehicle_list = actor_list.filter("*vehicle*")
lights_list = actor_list.filter("*traffic_light*")
# check possible obstacles
vehicle_state, vehicle = self._is_vehicle_hazard(vehicle_list)
if vehicle_state:
self._state = AgentState.BLOCKED_BY_VEHICLE
hazard_detected = True
# check for the state of the traffic lights
traffic_light_color = self._is_light_red(lights_list)
if traffic_light_color == 'RED' and self._follow_traffic_lights:
self._state = AgentState.BLOCKED_RED_LIGHT
hazard_detected = True
if hazard_detected:
control = self.emergency_stop()
else:
self._state = AgentState.NAVIGATING
# standard local planner behavior
control = self._local_planner.run_step()
#print ('Action chosen: ', control)
return control, traffic_light_color
# override case class
def _is_light_red_europe_style(self, lights_list):
"""
This method is specialized to check European style traffic lights.
Only suitable for Towns 03 -- 07.
"""
ego_vehicle_location = self._vehicle.get_location()
ego_vehicle_waypoint = self._map.get_waypoint(ego_vehicle_location)
traffic_light_color = "NONE" # default, if no traffic lights are seen
for traffic_light in lights_list:
object_waypoint = self._map.get_waypoint(traffic_light.get_location())
if object_waypoint.road_id != ego_vehicle_waypoint.road_id or \
object_waypoint.lane_id != ego_vehicle_waypoint.lane_id:
continue
if is_within_distance_ahead(traffic_light.get_transform(),
self._vehicle.get_transform(),
self._proximity_threshold):
if traffic_light.state == carla.TrafficLightState.Red:
return "RED"
elif traffic_light.state == carla.TrafficLightState.Yellow:
traffic_light_color = "YELLOW"
elif traffic_light.state == carla.TrafficLightState.Green:
if traffic_light_color is not "YELLOW": # (more severe)
traffic_light_color = "GREEN"
else:
import pdb; pdb.set_trace()
# investigate https://carla.readthedocs.io/en/latest/python_api/#carlatrafficlightstate
return traffic_light_color
# override case class
def _is_light_red_us_style(self, lights_list, debug=False):
ego_vehicle_location = self._vehicle.get_location()
ego_vehicle_waypoint = self._map.get_waypoint(ego_vehicle_location)
traffic_light_color = "NONE" # default, if no traffic lights are seen
if ego_vehicle_waypoint.is_junction:
# It is too late. Do not block the intersection! Keep going!
return "JUNCTION"
if self._local_planner.target_waypoint is not None:
if self._local_planner.target_waypoint.is_junction:
min_angle = 180.0
sel_magnitude = 0.0
sel_traffic_light = None
for traffic_light in lights_list:
loc = traffic_light.get_location()
magnitude, angle = compute_magnitude_angle(loc,
ego_vehicle_location,
self._vehicle.get_transform().rotation.yaw)
if magnitude < 60.0 and angle < min(25.0, min_angle):
sel_magnitude = magnitude
sel_traffic_light = traffic_light
min_angle = angle
if sel_traffic_light is not None:
if debug:
print('=== Magnitude = {} | Angle = {} | ID = {}'.format(
sel_magnitude, min_angle, sel_traffic_light.id))
if self._last_traffic_light is None:
self._last_traffic_light = sel_traffic_light
if self._last_traffic_light.state == carla.TrafficLightState.Red:
return "RED"
elif self._last_traffic_light.state == carla.TrafficLightState.Yellow:
traffic_light_color = "YELLOW"
elif self._last_traffic_light.state == carla.TrafficLightState.Green:
if traffic_light_color is not "YELLOW": # (more severe)
traffic_light_color = "GREEN"
else:
import pdb; pdb.set_trace()
# investigate https://carla.readthedocs.io/en/latest/python_api/#carlatrafficlightstate
else:
self._last_traffic_light = None
return traffic_light_color
if __name__ == '__main__':
# example call:
# ./PythonAPI/util/config.py --map Town01 --delta-seconds 0.05
# python PythonAPI/carla/agents/navigation/data_collection_agent.py --vision_size 256 --vision_fov 90 --steps 10000 --weather --lights
args = parse_args()
env = CarlaEnv(args)
try:
done = False
while not done:
action, traffic_light_color = env.compute_action()
next_obs, reward, done, info = env.step(action, traffic_light_color)
print ('Reward: ', reward, 'Done: ', done, 'Location: ', env.vehicle.get_location())
if done:
# env.reset_init()
# env.reset()
done = False
finally:
env.finish()
| [
"numpy.dtype",
"pygame.font.get_fonts",
"numpy.reshape",
"argparse.ArgumentParser",
"pygame.event.get",
"carla.WeatherParameters",
"pygame.font.match_font",
"math.radians",
"math.cos",
"numpy.array",
"numpy.dot",
"pdb.set_trace",
"numpy.linalg.norm",
"numpy.finfo",
"pygame.font.Font",
... | [((2198, 2292), 'numpy.array', 'np.array', (['[target_location.x - current_location.x, target_location.y - current_location.y\n ]'], {}), '([target_location.x - current_location.x, target_location.y -\n current_location.y])\n', (2206, 2292), True, 'import numpy as np\n'), ((2307, 2336), 'numpy.linalg.norm', 'np.linalg.norm', (['target_vector'], {}), '(target_vector)\n', (2321, 2336), True, 'import numpy as np\n'), ((4855, 4904), 'numpy.reshape', 'np.reshape', (['array', '(image.height, image.width, 4)'], {}), '(array, (image.height, image.width, 4))\n', (4865, 4904), True, 'import numpy as np\n'), ((5299, 5327), 'pygame.font.match_font', 'pygame.font.match_font', (['font'], {}), '(font)\n', (5321, 5327), False, 'import pygame\n'), ((5339, 5365), 'pygame.font.Font', 'pygame.font.Font', (['font', '(14)'], {}), '(font, 14)\n', (5355, 5365), False, 'import pygame\n'), ((5404, 5422), 'pygame.event.get', 'pygame.event.get', ([], {}), '()\n', (5420, 5422), False, 'import pygame\n'), ((8700, 8725), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (8723, 8725), False, 'import argparse\n'), ((3052, 3077), 'numpy.linalg.norm', 'np.linalg.norm', (['[x, y, z]'], {}), '([x, y, z])\n', (3066, 3077), True, 'import numpy as np\n'), ((7876, 7924), 'carla.WeatherParameters', 'carla.WeatherParameters', ([], {'sun_altitude_angle': '(90.0)'}), '(sun_altitude_angle=90.0)\n', (7899, 7924), False, 'import carla\n'), ((462, 620), 'glob.glob', 'glob.glob', (["('../carla/dist/carla-*%d.%d-%s.egg' % (sys.version_info.major, sys.\n version_info.minor, 'win-amd64' if os.name == 'nt' else 'linux-x86_64'))"], {}), "('../carla/dist/carla-*%d.%d-%s.egg' % (sys.version_info.major,\n sys.version_info.minor, 'win-amd64' if os.name == 'nt' else 'linux-x86_64')\n )\n", (471, 620), False, 'import glob\n'), ((3080, 3095), 'numpy.finfo', 'np.finfo', (['float'], {}), '(float)\n', (3088, 3095), True, 'import numpy as np\n'), ((3825, 3936), 'carla.WorldSettings', 'carla.WorldSettings', ([], {'no_rendering_mode': '(False)', 'synchronous_mode': '(True)', 'fixed_delta_seconds': 'self.delta_seconds'}), '(no_rendering_mode=False, synchronous_mode=True,\n fixed_delta_seconds=self.delta_seconds)\n', (3844, 3936), False, 'import carla\n'), ((4028, 4041), 'Queue.Queue', 'queue.Queue', ([], {}), '()\n', (4039, 4041), True, 'import Queue as queue\n'), ((4824, 4841), 'numpy.dtype', 'np.dtype', (['"""uint8"""'], {}), "('uint8')\n", (4832, 4841), True, 'import numpy as np\n'), ((5168, 5191), 'pygame.font.get_fonts', 'pygame.font.get_fonts', ([], {}), '()\n', (5189, 5191), False, 'import pygame\n'), ((10600, 10627), 'numpy.array', 'np.array', (['[throttle, steer]'], {}), '([throttle, steer])\n', (10608, 10627), True, 'import numpy as np\n'), ((10661, 10686), 'numpy.array', 'np.array', (['[-brake, steer]'], {}), '([-brake, steer])\n', (10669, 10686), True, 'import numpy as np\n'), ((2551, 2576), 'math.radians', 'math.radians', (['orientation'], {}), '(orientation)\n', (2563, 2576), False, 'import math\n'), ((2588, 2613), 'math.radians', 'math.radians', (['orientation'], {}), '(orientation)\n', (2600, 2613), False, 'import math\n'), ((6161, 6178), 'math.cos', 'math.cos', (['self._t'], {}), '(self._t)\n', (6169, 6178), False, 'import math\n'), ((2662, 2699), 'numpy.dot', 'np.dot', (['forward_vector', 'target_vector'], {}), '(forward_vector, target_vector)\n', (2668, 2699), True, 'import numpy as np\n'), ((13423, 13438), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (13436, 13438), False, 'import pdb\n'), ((15792, 15807), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (15805, 15807), False, 'import pdb\n')] |
import SpiceInterface
import TestUtilities
# create the test utility object
test_utilities_obj = TestUtilities.TestUtilities()
test_utilities_obj.netlist_generation('bandgap_opamp_test_op.sch', 'rundir')
# create the spice interface
spice_interface_obj = SpiceInterface.SpiceInterface(netlist_path="rundir/bandgap_opamp_test_op.spice")
spice_interface_obj.config['simulator']['shared'] = True
# add the op save parameters
devices = ['xbmr.XMcurr', 'xbmr.XMcurr1', 'xbmr.XM2', 'xbmr.XM3']
spice_interface_obj.insert_op_save(devices, ['vsat_marg'])
# run the simulation
spice_interface_obj.run_simulation()
# analyse the results
spice_interface_obj.plot_op_save(devices, ['vsat_marg'], 'temp-sweep')
['xbmr.XMcurr', 'xbmr.XMcurr1', 'xbmr.XM2', 'xbmr.XM3'] | [
"SpiceInterface.SpiceInterface",
"TestUtilities.TestUtilities"
] | [((99, 128), 'TestUtilities.TestUtilities', 'TestUtilities.TestUtilities', ([], {}), '()\n', (126, 128), False, 'import TestUtilities\n'), ((258, 343), 'SpiceInterface.SpiceInterface', 'SpiceInterface.SpiceInterface', ([], {'netlist_path': '"""rundir/bandgap_opamp_test_op.spice"""'}), "(netlist_path='rundir/bandgap_opamp_test_op.spice'\n )\n", (287, 343), False, 'import SpiceInterface\n')] |
# fa19-516-170 E.Cloudmesh.Common.2
from cloudmesh.common.dotdict import dotdict
color = {"red": 255, "blue": 255, "green": 255, "alpha": 0}
color = dotdict(color)
print("A RGB color: ", color.red, color.blue, color.green, color.alpha) | [
"cloudmesh.common.dotdict.dotdict"
] | [((151, 165), 'cloudmesh.common.dotdict.dotdict', 'dotdict', (['color'], {}), '(color)\n', (158, 165), False, 'from cloudmesh.common.dotdict import dotdict\n')] |
'''
对windows的注册表进行操作
_open_key: 返回key
_read_key_value:读取key下一个value的值和类型
_save_key_value:以某种类型的方式,把值保存到某个key中
read_PATH_value:读取环境变量PATH的值
append_value_in_PATH:为PATH添加一个值
del_value_in_PATH:从PATH中删除一个值
check_key_value_exists(key,value_name):检查某个key小,value_name是否存在
create_value(key,value_name,value_type,value): 直接调用_save_key_value
delete_value(key,value_name): 删除key下的value
'''
import winreg
def _open_key(root_key_name,sub_key_name):
try:
key = winreg.OpenKey(root_key_name, sub_key_name,0 ,winreg.KEY_ALL_ACCESS)
except Exception as e:
if root_key_name == winreg.HKEY_CURRENT_USER:
root_key_name = 'HKEY_CURRENT_USER'
elif root_key_name == winreg.HKEY_CLASSES_ROOT:
root_key_name = 'HKEY_CLASSES_ROOT'
elif root_key_name == winreg.HKEY_CURRENT_CONFIG:
root_key_name = 'HKEY_CURRENT_CONFIG'
elif root_key_name == winreg.HKEY_DYN_DATA:
root_key_name = 'HKEY_DYN_DATA'
elif root_key_name == winreg.HKEY_LOCAL_MACHINE:
root_key_name = 'HKEY_LOCAL_MACHINE'
elif root_key_name == winreg.HKEY_PERFORMANCE_DATA:
root_key_name = 'HKEY_PERFORMANCE_DATA'
elif root_key_name == winreg.HKEY_USERS:
root_key_name = 'HKEY_USERS'
raise EnvironmentError('注册表的项%s\%s不存在' % (root_key_name,sub_key_name))
return key
# val, tpe = winreg.QueryValueEx(sub_item, key_name)
def _read_key_value(key,value_name):
val, tpe = winreg.QueryValueEx(key, value_name)
return val,tpe
def _save_key_value(key,value_name,value_type,value):
# key = winreg.OpenKey(sub_item,key_name)
# v,t = _read_key_value(sub_item,key_name)
winreg.SetValueEx(key,value_name, 0, value_type, value)
def check_key_value_exists(key,value_name):
# key = _open_key(winreg.HKEY_CURRENT_USER, r'Environment')
sub_key_num, value_num, last_modified = winreg.QueryInfoKey(key)
# print(winreg.EnumValue(sub_item, 2))
# winreg.EnumKey(sub_item, 1)
# print(list(range(0,key_num)))
if value_num > 0:
for idx in list(range(0, value_num)):
tmp_val_name, tmp_val, idx = winreg.EnumValue(key, idx)
if tmp_val_name.lower() == value_name.lower():
return True
return False
def create_value(key,value_name,value_type,value):
_save_key_value(key,value_name,value_type,value)
def delete_value(key,value_name):
winreg.DeleteValue(key,value_name)
def read_PATH_value():
'''
读取windown环境变量PATH的内容
:return:
'''
root_key = winreg.HKEY_CURRENT_USER
sub_key_name = r'Environment'
value_name = r'PATH'
key = _open_key(root_key, sub_key_name)
val, tpe = _read_key_value(key, value_name)
return val,tpe
# print(val)
def append_value_in_PATH(v):
'''
把v添加到系统变量PATH中去
:param v:
:return:
'''
root_key = winreg.HKEY_CURRENT_USER
sub_key_name = r'Environment'
value_name = r'PATH'
key = _open_key(root_key, sub_key_name)
val, tpe = _read_key_value(key,value_name)
#检测是否包含
tmp = val.split(';')
if v not in tmp:
_save_key_value(key, value_name, tpe,val+';'+v)
winreg.CloseKey(key)
def del_value_in_PATH(v):
'''
把v添加到系统变量PATH中去
:param v:
:return:
'''
root_key = winreg.HKEY_CURRENT_USER
sub_key_name = r'Environment'
value_name = r'PATH'
key = _open_key(root_key, sub_key_name)
val, tpe = _read_key_value(key,value_name)
tmp = val.split(';')
tmp.remove(v)
_save_key_value(key, value_name, tpe,';'.join(tmp))
winreg.CloseKey(key)
# key = _open_key(winreg.HKEY_CURRENT_USER, r'Environment')
# delete_value(key, 'test') | [
"winreg.CloseKey",
"winreg.QueryValueEx",
"winreg.OpenKey",
"winreg.DeleteValue",
"winreg.EnumValue",
"winreg.SetValueEx",
"winreg.QueryInfoKey"
] | [((1481, 1517), 'winreg.QueryValueEx', 'winreg.QueryValueEx', (['key', 'value_name'], {}), '(key, value_name)\n', (1500, 1517), False, 'import winreg\n'), ((1689, 1745), 'winreg.SetValueEx', 'winreg.SetValueEx', (['key', 'value_name', '(0)', 'value_type', 'value'], {}), '(key, value_name, 0, value_type, value)\n', (1706, 1745), False, 'import winreg\n'), ((1898, 1922), 'winreg.QueryInfoKey', 'winreg.QueryInfoKey', (['key'], {}), '(key)\n', (1917, 1922), False, 'import winreg\n'), ((2420, 2455), 'winreg.DeleteValue', 'winreg.DeleteValue', (['key', 'value_name'], {}), '(key, value_name)\n', (2438, 2455), False, 'import winreg\n'), ((3162, 3182), 'winreg.CloseKey', 'winreg.CloseKey', (['key'], {}), '(key)\n', (3177, 3182), False, 'import winreg\n'), ((3568, 3588), 'winreg.CloseKey', 'winreg.CloseKey', (['key'], {}), '(key)\n', (3583, 3588), False, 'import winreg\n'), ((462, 531), 'winreg.OpenKey', 'winreg.OpenKey', (['root_key_name', 'sub_key_name', '(0)', 'winreg.KEY_ALL_ACCESS'], {}), '(root_key_name, sub_key_name, 0, winreg.KEY_ALL_ACCESS)\n', (476, 531), False, 'import winreg\n'), ((2145, 2171), 'winreg.EnumValue', 'winreg.EnumValue', (['key', 'idx'], {}), '(key, idx)\n', (2161, 2171), False, 'import winreg\n')] |
import warnings
from collections.abc import Iterable
from collections import OrderedDict
import torch
import numpy as np
from torch.utils.data import Dataset
from deep_staple.utils.torch_utils import interpolate_sample, augmentNoise, spatial_augment, torch_manual_seeded, ensure_dense
from deep_staple.utils.common_utils import LabelDisturbanceMode
class HybridIdLoader(Dataset):
def __init__(self,
data_load_function,
ensure_labeled_pairs=True, use_additional_data=False, resample=True,
size:tuple=(96,96,60), normalize:bool=True,
max_load_3d_num=None, crop_3d_w_dim_range=None, modified_3d_label_override=None,
prevent_disturbance=False,
use_2d_normal_to=None, crop_2d_slices_gt_num_threshold=None, pre_interpolation_factor=2.,
fixed_weight_file = None, fixed_weight_min_quantile=None, fixed_weight_min_value=None
):
self.label_tags = []
self.use_2d_normal_to = use_2d_normal_to
self.crop_2d_slices_gt_num_threshold = crop_2d_slices_gt_num_threshold
self.prevent_disturbance = prevent_disturbance
self.do_augment = False
self.use_modified = False
self.disturbed_idxs = []
self.augment_at_collate = False
self.pre_interpolation_factor = pre_interpolation_factor
self.extract_3d_id = lambda _:_
self.extract_short_3d_id = lambda _:_
self.img_paths = {}
self.label_paths = {}
self.img_data_3d = {}
self.label_data_3d = {}
self.modified_label_data_3d = {}
# Load base 3D data
(self.img_paths, self.label_paths,
self.img_data_3d, self.label_data_3d,
self.modified_label_data_3d,
self.extract_3d_id, self.extract_short_3d_id) = data_load_function()
# Retrieve slices and plugin modified data
self.img_data_2d = {}
self.label_data_2d = {}
self.modified_label_data_2d = {}
# Postprocessing of 3d volumes
print("Postprocessing 3D volumes")
orig_3d_num = len(self.label_data_3d.keys())
if ensure_labeled_pairs:
labelled_keys = set(self.label_data_3d.keys())
unlabelled_imgs = set(self.img_data_3d.keys()) - labelled_keys
unlabelled_modified_labels = set([self.extract_3d_id(key) for key in self.modified_label_data_3d.keys()]) - labelled_keys
for del_key in unlabelled_imgs:
del self.img_data_3d[del_key]
for del_key in unlabelled_modified_labels:
del self.modified_label_data_3d[del_key]
if max_load_3d_num:
for del_key in sorted(list(self.img_data_3d.keys()))[max_load_3d_num:]:
del self.img_data_3d[del_key]
for del_key in sorted(list(self.label_data_3d.keys()))[max_load_3d_num:]:
del self.label_data_3d[del_key]
for del_key in sorted(list(self.modified_label_data_3d.keys()))[max_load_3d_num:]:
del self.modified_label_data_3d[del_key]
postprocessed_3d_num = len(self.label_data_3d.keys())
print(f"Removed {orig_3d_num - postprocessed_3d_num} 3D images in postprocessing")
#check for consistency
print(f"Equal image and label numbers: {set(self.img_data_3d)==set(self.label_data_3d)==set(self.modified_label_data_3d)} ({len(self.img_data_3d)})")
img_stack = torch.stack(list(self.img_data_3d.values()), dim=0)
img_mean, img_std = img_stack.mean(), img_stack.std()
label_stack = torch.stack(list(self.label_data_3d.values()), dim=0)
print("Image shape: {}, mean.: {:.2f}, std.: {:.2f}".format(img_stack.shape, img_mean, img_std))
print("Label shape: {}, max.: {}".format(label_stack.shape,torch.max(label_stack)))
if use_2d_normal_to:
if use_2d_normal_to == "D":
slice_dim = -3
if use_2d_normal_to == "H":
slice_dim = -2
if use_2d_normal_to == "W":
slice_dim = -1
for _3d_id, image in self.img_data_3d.items():
for idx, img_slc in [(slice_idx, image.select(slice_dim, slice_idx)) \
for slice_idx in range(image.shape[slice_dim])]:
# Set data view for id like "003rW100"
self.img_data_2d[f"{_3d_id}{use_2d_normal_to}{idx:03d}"] = img_slc
for _3d_id, label in self.label_data_3d.items():
for idx, lbl_slc in [(slice_idx, label.select(slice_dim, slice_idx)) \
for slice_idx in range(label.shape[slice_dim])]:
# Set data view for id like "003rW100"
self.label_data_2d[f"{_3d_id}{use_2d_normal_to}{idx:03d}"] = lbl_slc
for _3d_id, label in self.modified_label_data_3d.items():
for idx, lbl_slc in [(slice_idx, label.select(slice_dim, slice_idx)) \
for slice_idx in range(label.shape[slice_dim])]:
# Set data view for id like "003rW100"
self.modified_label_data_2d[f"{_3d_id}{use_2d_normal_to}{idx:03d}"] = lbl_slc
# Postprocessing of 2d slices
print("Postprocessing 2D slices")
orig_2d_num = len(self.label_data_2d.keys())
if self.crop_2d_slices_gt_num_threshold > 0:
for key, label in list(self.label_data_2d.items()):
uniq_vals = label.unique()
if sum(label[label > 0]) < self.crop_2d_slices_gt_num_threshold:
# Delete 2D slices with less than n gt-pixels (but keep 3d data)
del self.img_data_2d[key]
del self.label_data_2d[key]
del self.modified_label_data_2d[key]
postprocessed_2d_num = len(self.label_data_2d.keys())
print(f"Removed {orig_2d_num - postprocessed_2d_num} of {orig_2d_num} 2D slices in postprocessing")
if fixed_weight_file is not None and any([fixed_weight_min_quantile, fixed_weight_min_value]):
fixed_weightdata = torch.load(fixed_weight_file)
fixed_weights = fixed_weightdata['data_parameters'].detach().cpu()
fixed_d_ids = fixed_weightdata['d_ids']
print(f"Fixed weight quantiles are: {np.quantile(fixed_weights, np.linspace(0.,1.,5))}")
if fixed_weight_min_quantile is not None:
fixed_weight_min_value = np.quantile(fixed_weights, fixed_weight_min_quantile)
elif fixed_weight_min_value is not None:
pass
fixed_del_counter = 0
for key, weight in zip(fixed_d_ids, fixed_weights):
if weight < fixed_weight_min_value:
if use_2d_normal_to:
del self.img_data_2d[key]
del self.label_data_2d[key]
del self.modified_label_data_2d[key]
else:
del self.img_data_3d[key]
del self.label_data_3d[key]
del self.modified_label_data_3d[key]
fixed_del_counter+=1
print(f"Removed {fixed_del_counter} data samples by cropping data with fixed weight min value = {fixed_weight_min_value:.3f}")
# Now make sure dicts are ordered
self.img_paths = OrderedDict(sorted(self.img_paths.items()))
self.label_paths = OrderedDict(sorted(self.label_paths.items()))
self.img_data_3d = OrderedDict(sorted(self.img_data_3d.items()))
self.label_data_3d = OrderedDict(sorted(self.label_data_3d.items()))
self.modified_label_data_3d = OrderedDict(sorted(self.modified_label_data_3d.items()))
self.img_data_2d = OrderedDict(sorted(self.img_data_2d.items()))
self.label_data_2d = OrderedDict(sorted(self.label_data_2d.items()))
self.modified_label_data_2d = OrderedDict(sorted(self.modified_label_data_2d.items()))
nonzero_lbl_percentage = torch.tensor([lbl.sum((-2,-1)) > 0 for lbl in self.label_data_2d.values()]).sum()
nonzero_lbl_percentage = nonzero_lbl_percentage/len(self.label_data_2d)
print(f"Nonzero labels: " f"{nonzero_lbl_percentage*100:.2f}%")
nonzero_mod_lbl_percentage = torch.tensor([ensure_dense(lbl)[0].sum((-2,-1)) > 0 for lbl in self.modified_label_data_2d.values()]).sum()
nonzero_mod_lbl_percentage = nonzero_mod_lbl_percentage/len(self.modified_label_data_2d)
print(f"Nonzero modified labels: " f"{nonzero_mod_lbl_percentage*100:.2f}%")
print(f"Loader will use {postprocessed_2d_num} of {orig_2d_num} 2D slices.")
print("Data import finished.")
print(f"Dataloader will yield {'2D' if self.use_2d_normal_to else '3D'} samples")
def get_short_3d_ids(self):
return [self.extract_short_3d_id(_id) for _id in self.get_3d_ids()]
def get_3d_ids(self):
return list(self.img_data_3d.keys())
def get_2d_ids(self):
assert self.use_2d(), "Dataloader does not provide 2D data."
return list(self.img_data_2d.keys())
def get_id_dicts(self, use_2d_override=None):
all_3d_ids = self.get_3d_ids()
id_dicts = []
if self.use_2d(use_2d_override):
for _2d_dataset_idx, _2d_id in enumerate(self.get_2d_ids()):
_3d_id = _2d_id[:-4]
id_dicts.append(
{
'2d_id': _2d_id,
'2d_dataset_idx': _2d_dataset_idx,
'3d_id': _3d_id,
'3d_dataset_idx': all_3d_ids.index(_3d_id),
}
)
else:
for _3d_dataset_idx, _3d_id in enumerate(self.get_3d_ids()):
id_dicts.append(
{
'3d_id': _3d_id,
'3d_dataset_idx': all_3d_ids.index(_3d_id),
}
)
return id_dicts
def switch_2d_identifiers(self, _2d_identifiers):
assert self.use_2d(), "Dataloader does not provide 2D data."
if isinstance(_2d_identifiers, (torch.Tensor, np.ndarray)):
_2d_identifiers = _2d_identifiers.tolist()
elif not isinstance(_2d_identifiers, Iterable) or isinstance(_2d_identifiers, str):
_2d_identifiers = [_2d_identifiers]
_ids = self.get_2d_ids()
if all([isinstance(elem, int) for elem in _2d_identifiers]):
vals = [_ids[elem] for elem in _2d_identifiers]
elif all([isinstance(elem, str) for elem in _2d_identifiers]):
vals = [_ids.index(elem) for elem in _2d_identifiers]
else:
raise ValueError
return vals[0] if len(vals) == 1 else vals
def switch_3d_identifiers(self, _3d_identifiers):
if isinstance(_3d_identifiers, (torch.Tensor, np.ndarray)):
_3d_identifiers = _3d_identifiers.tolist()
elif not isinstance(_3d_identifiers, Iterable) or isinstance(_3d_identifiers, str):
_3d_identifiers = [_3d_identifiers]
_ids = self.get_3d_ids()
if all([isinstance(elem, int) for elem in _3d_identifiers]):
vals = [_ids[elem] for elem in _3d_identifiers]
elif all([isinstance(elem, str) for elem in _3d_identifiers]):
vals = [_ids.index(elem) if elem in _ids else None for elem in _3d_identifiers]
else:
raise ValueError
return vals[0] if len(vals) == 1 else vals
def get_3d_from_2d_identifiers(self, _2d_identifiers, retrn='id'):
assert self.use_2d(), "Dataloader does not provide 2D data."
assert retrn in ['id', 'idx']
if isinstance(_2d_identifiers, (torch.Tensor, np.ndarray)):
_2d_identifiers = _2d_identifiers.tolist()
elif not isinstance(_2d_identifiers, Iterable) or isinstance(_2d_identifiers, str):
_2d_identifiers = [_2d_identifiers]
if isinstance(_2d_identifiers[0], int):
_2d_identifiers = self.switch_2d_identifiers(_2d_identifiers)
vals = []
for item in _2d_identifiers:
_3d_id = self.extract_3d_id(item)
if retrn == 'id':
vals.append(_3d_id)
elif retrn == 'idx':
vals.append(self.switch_3d_identifiers(_3d_id))
return vals[0] if len(vals) == 1 else vals
def use_2d(self, override=None):
if not self.use_2d_normal_to:
return False
elif override is not None:
return override
else:
return True
def __len__(self, use_2d_override=None):
if self.use_2d(use_2d_override):
return len(self.img_data_2d)
return len(self.img_data_3d)
def __getitem__(self, dataset_idx, use_2d_override=None):
use_2d = self.use_2d(use_2d_override)
if use_2d:
all_ids = self.get_2d_ids()
_id = all_ids[dataset_idx]
image = self.img_data_2d.get(_id, torch.tensor([]))
label = self.label_data_2d.get(_id, torch.tensor([]))
# For 2D id cut last 4 "003rW100"
_3d_id = self.get_3d_from_2d_identifiers(_id)
image_path = self.img_paths[_3d_id]
label_path = self.label_paths[_3d_id]
else:
all_ids = self.get_3d_ids()
_id = all_ids[dataset_idx]
image = self.img_data_3d.get(_id, torch.tensor([]))
label = self.label_data_3d.get(_id, torch.tensor([]))
image_path = self.img_paths[_id]
label_path = self.label_paths[_id]
spat_augment_grid = []
if self.use_modified:
if use_2d:
modified_label = self.modified_label_data_2d.get(_id, label.detach().clone())
else:
modified_label = self.modified_label_data_3d.get(_id, label.detach().clone())
else:
modified_label = label.detach().clone()
b_image = image.unsqueeze(0).cuda()
b_label = label.unsqueeze(0).cuda()
modified_label, _ = ensure_dense(modified_label)
b_modified_label = modified_label.unsqueeze(0).cuda()
if self.do_augment and not self.augment_at_collate:
b_image, b_label, b_spat_augment_grid = self.augment(
b_image, b_label, use_2d, pre_interpolation_factor=self.pre_interpolation_factor
)
_, b_modified_label, _ = spatial_augment(
b_label=b_modified_label, use_2d=use_2d, b_grid_override=b_spat_augment_grid,
pre_interpolation_factor=self.pre_interpolation_factor
)
spat_augment_grid = b_spat_augment_grid.squeeze(0).detach().cpu().clone()
elif not self.do_augment:
b_image, b_label = interpolate_sample(b_image, b_label, 2., use_2d)
_, b_modified_label = interpolate_sample(b_label=b_modified_label, scale_factor=2.,
use_2d=use_2d)
image = b_image.squeeze(0).cpu()
label = b_label.squeeze(0).cpu()
modified_label = b_modified_label.squeeze(0).cpu()
if use_2d:
assert image.dim() == label.dim() == 2
else:
assert image.dim() == label.dim() == 3
return {
'image': image,
'label': label,
'modified_label': modified_label,
# if disturbance is off, modified label is equals label
'dataset_idx': dataset_idx,
'id': _id,
'image_path': image_path,
'label_path': label_path,
'spat_augment_grid': spat_augment_grid
}
def get_3d_item(self, _3d_dataset_idx):
return self.__getitem__(_3d_dataset_idx, use_2d_override=False)
def get_data(self, use_2d_override=None):
if self.use_2d(use_2d_override):
img_stack = torch.stack(list(self.img_data_2d.values()), dim=0)
label_stack = torch.stack(list(self.label_data_2d.values()), dim=0)
modified_label_stack = torch.stack(list(self.modified_label_data_2d.values()), dim=0)
else:
img_stack = torch.stack(list(self.img_data_3d.values()), dim=0)
label_stack = torch.stack(list(self.label_data_3d.values()), dim=0)
modified_label_stack = torch.stack(list(self.modified_label_data_3d.values()), dim=0)
return img_stack, label_stack, modified_label_stack
def disturb_idxs(self, all_idxs, disturbance_mode, disturbance_strength=1., use_2d_override=None):
if self.prevent_disturbance:
warnings.warn("Disturbed idxs shall be set but disturbance is prevented for dataset.")
return
use_2d = self.use_2d(use_2d_override)
if all_idxs is not None:
if isinstance(all_idxs, (np.ndarray, torch.Tensor)):
all_idxs = all_idxs.tolist()
self.disturbed_idxs = all_idxs
else:
self.disturbed_idxs = []
# Reset modified data
for idx in range(self.__len__(use_2d_override=use_2d)):
if use_2d:
label_id = self.get_2d_ids()[idx]
self.modified_label_data_2d[label_id] = self.label_data_2d[label_id]
else:
label_id = self.get_3d_ids()[idx]
self.modified_label_data_3d[label_id] = self.label_data_3d[label_id]
# Now apply disturbance
if idx in self.disturbed_idxs:
if use_2d:
label = self.modified_label_data_2d[label_id].detach().clone()
else:
label = self.modified_label_data_3d[label_id].detach().clone()
with torch_manual_seeded(idx):
if str(disturbance_mode)==str(LabelDisturbanceMode.FLIP_ROLL):
roll_strength = 10*disturbance_strength
if use_2d:
modified_label = \
torch.roll(
label.transpose(-2,-1),
(
int(torch.randn(1)*roll_strength),
int(torch.randn(1)*roll_strength)
),(-2,-1)
)
else:
modified_label = \
torch.roll(
label.permute(1,2,0),
(
int(torch.randn(1)*roll_strength),
int(torch.randn(1)*roll_strength),
int(torch.randn(1)*roll_strength)
),(-3,-2,-1)
)
elif str(disturbance_mode)==str(LabelDisturbanceMode.AFFINE):
b_modified_label = label.unsqueeze(0).cuda()
_, b_modified_label, _ = spatial_augment(b_label=b_modified_label, use_2d=use_2d,
bspline_num_ctl_points=6, bspline_strength=0., bspline_probability=0.,
affine_strength=0.09*disturbance_strength,
add_affine_translation=0.18*disturbance_strength, affine_probability=1.)
modified_label = b_modified_label.squeeze(0).cpu()
else:
raise ValueError(f"Disturbance mode {disturbance_mode} is not implemented.")
if use_2d:
self.modified_label_data_2d[label_id] = modified_label
else:
self.modified_label_data_3d[label_id] = modified_label
def train(self, augment=True, use_modified=True):
self.do_augment = augment
self.use_modified = use_modified
def eval(self, augment=False, use_modified=False):
self.train(augment, use_modified)
def set_augment_at_collate(self, augment_at_collate=True):
self.augment_at_collate = augment_at_collate
def get_efficient_augmentation_collate_fn(self):
use_2d = True if self.use_2d_normal_to else False
def collate_closure(batch):
batch = torch.utils.data._utils.collate.default_collate(batch)
if self.augment_at_collate and self.do_augment:
# Augment the whole batch not just one sample
b_image = batch['image'].cuda()
b_label = batch['label'].cuda()
b_modified_label = batch['modified_label'].cuda()
b_image, b_label, b_spat_augment_grid = self.augment(
b_image, b_label, use_2d, pre_interpolation_factor=self.pre_interpolation_factor
)
_, b_modified_label, _ = spatial_augment(
b_label=b_modified_label, use_2d=use_2d, b_grid_override=b_spat_augment_grid,
pre_interpolation_factor=self.pre_interpolation_factor
)
b_spat_augment_grid = b_spat_augment_grid.detach().clone()
batch['image'], batch['label'], batch['modified_label'], batch['spat_augment_grid'] = b_image, b_label, b_modified_label, b_spat_augment_grid
return batch
return collate_closure
def augment(self, b_image, b_label, use_2d,
noise_strength=0.05,
bspline_num_ctl_points=6, bspline_strength=0.03, bspline_probability=.95,
affine_strength=0.2, affine_probability=.45,
pre_interpolation_factor=2.):
if use_2d:
assert b_image.dim() == b_label.dim() == 3, \
f"Augmenting 2D. Input batch of image and " \
f"label should be BxHxW but are {b_image.shape} and {b_label.shape}"
else:
assert b_image.dim() == b_label.dim() == 4, \
f"Augmenting 3D. Input batch of image and " \
f"label should be BxDxHxW but are {b_image.shape} and {b_label.shape}"
b_image = augmentNoise(b_image, strength=noise_strength)
b_image, b_label, b_spat_augment_grid = spatial_augment(
b_image, b_label,
bspline_num_ctl_points=bspline_num_ctl_points, bspline_strength=bspline_strength, bspline_probability=bspline_probability,
affine_strength=affine_strength, affine_probability=affine_probability,
pre_interpolation_factor=pre_interpolation_factor, use_2d=use_2d)
b_label = b_label.long()
return b_image, b_label, b_spat_augment_grid | [
"torch.utils.data._utils.collate.default_collate",
"deep_staple.utils.torch_utils.ensure_dense",
"torch.load",
"torch.max",
"deep_staple.utils.torch_utils.augmentNoise",
"torch.tensor",
"numpy.quantile",
"numpy.linspace",
"deep_staple.utils.torch_utils.interpolate_sample",
"deep_staple.utils.torch... | [((14231, 14259), 'deep_staple.utils.torch_utils.ensure_dense', 'ensure_dense', (['modified_label'], {}), '(modified_label)\n', (14243, 14259), False, 'from deep_staple.utils.torch_utils import interpolate_sample, augmentNoise, spatial_augment, torch_manual_seeded, ensure_dense\n'), ((22241, 22287), 'deep_staple.utils.torch_utils.augmentNoise', 'augmentNoise', (['b_image'], {'strength': 'noise_strength'}), '(b_image, strength=noise_strength)\n', (22253, 22287), False, 'from deep_staple.utils.torch_utils import interpolate_sample, augmentNoise, spatial_augment, torch_manual_seeded, ensure_dense\n'), ((22336, 22648), 'deep_staple.utils.torch_utils.spatial_augment', 'spatial_augment', (['b_image', 'b_label'], {'bspline_num_ctl_points': 'bspline_num_ctl_points', 'bspline_strength': 'bspline_strength', 'bspline_probability': 'bspline_probability', 'affine_strength': 'affine_strength', 'affine_probability': 'affine_probability', 'pre_interpolation_factor': 'pre_interpolation_factor', 'use_2d': 'use_2d'}), '(b_image, b_label, bspline_num_ctl_points=\n bspline_num_ctl_points, bspline_strength=bspline_strength,\n bspline_probability=bspline_probability, affine_strength=\n affine_strength, affine_probability=affine_probability,\n pre_interpolation_factor=pre_interpolation_factor, use_2d=use_2d)\n', (22351, 22648), False, 'from deep_staple.utils.torch_utils import interpolate_sample, augmentNoise, spatial_augment, torch_manual_seeded, ensure_dense\n'), ((6159, 6188), 'torch.load', 'torch.load', (['fixed_weight_file'], {}), '(fixed_weight_file)\n', (6169, 6188), False, 'import torch\n'), ((14597, 14756), 'deep_staple.utils.torch_utils.spatial_augment', 'spatial_augment', ([], {'b_label': 'b_modified_label', 'use_2d': 'use_2d', 'b_grid_override': 'b_spat_augment_grid', 'pre_interpolation_factor': 'self.pre_interpolation_factor'}), '(b_label=b_modified_label, use_2d=use_2d, b_grid_override=\n b_spat_augment_grid, pre_interpolation_factor=self.pre_interpolation_factor\n )\n', (14612, 14756), False, 'from deep_staple.utils.torch_utils import interpolate_sample, augmentNoise, spatial_augment, torch_manual_seeded, ensure_dense\n'), ((16728, 16819), 'warnings.warn', 'warnings.warn', (['"""Disturbed idxs shall be set but disturbance is prevented for dataset."""'], {}), "(\n 'Disturbed idxs shall be set but disturbance is prevented for dataset.')\n", (16741, 16819), False, 'import warnings\n'), ((20456, 20510), 'torch.utils.data._utils.collate.default_collate', 'torch.utils.data._utils.collate.default_collate', (['batch'], {}), '(batch)\n', (20503, 20510), False, 'import torch\n'), ((3757, 3779), 'torch.max', 'torch.max', (['label_stack'], {}), '(label_stack)\n', (3766, 3779), False, 'import torch\n'), ((6518, 6571), 'numpy.quantile', 'np.quantile', (['fixed_weights', 'fixed_weight_min_quantile'], {}), '(fixed_weights, fixed_weight_min_quantile)\n', (6529, 6571), True, 'import numpy as np\n'), ((13152, 13168), 'torch.tensor', 'torch.tensor', (['[]'], {}), '([])\n', (13164, 13168), False, 'import torch\n'), ((13218, 13234), 'torch.tensor', 'torch.tensor', (['[]'], {}), '([])\n', (13230, 13234), False, 'import torch\n'), ((13579, 13595), 'torch.tensor', 'torch.tensor', (['[]'], {}), '([])\n', (13591, 13595), False, 'import torch\n'), ((13645, 13661), 'torch.tensor', 'torch.tensor', (['[]'], {}), '([])\n', (13657, 13661), False, 'import torch\n'), ((14945, 14994), 'deep_staple.utils.torch_utils.interpolate_sample', 'interpolate_sample', (['b_image', 'b_label', '(2.0)', 'use_2d'], {}), '(b_image, b_label, 2.0, use_2d)\n', (14963, 14994), False, 'from deep_staple.utils.torch_utils import interpolate_sample, augmentNoise, spatial_augment, torch_manual_seeded, ensure_dense\n'), ((15028, 15105), 'deep_staple.utils.torch_utils.interpolate_sample', 'interpolate_sample', ([], {'b_label': 'b_modified_label', 'scale_factor': '(2.0)', 'use_2d': 'use_2d'}), '(b_label=b_modified_label, scale_factor=2.0, use_2d=use_2d)\n', (15046, 15105), False, 'from deep_staple.utils.torch_utils import interpolate_sample, augmentNoise, spatial_augment, torch_manual_seeded, ensure_dense\n'), ((21026, 21185), 'deep_staple.utils.torch_utils.spatial_augment', 'spatial_augment', ([], {'b_label': 'b_modified_label', 'use_2d': 'use_2d', 'b_grid_override': 'b_spat_augment_grid', 'pre_interpolation_factor': 'self.pre_interpolation_factor'}), '(b_label=b_modified_label, use_2d=use_2d, b_grid_override=\n b_spat_augment_grid, pre_interpolation_factor=self.pre_interpolation_factor\n )\n', (21041, 21185), False, 'from deep_staple.utils.torch_utils import interpolate_sample, augmentNoise, spatial_augment, torch_manual_seeded, ensure_dense\n'), ((17843, 17867), 'deep_staple.utils.torch_utils.torch_manual_seeded', 'torch_manual_seeded', (['idx'], {}), '(idx)\n', (17862, 17867), False, 'from deep_staple.utils.torch_utils import interpolate_sample, augmentNoise, spatial_augment, torch_manual_seeded, ensure_dense\n'), ((6397, 6421), 'numpy.linspace', 'np.linspace', (['(0.0)', '(1.0)', '(5)'], {}), '(0.0, 1.0, 5)\n', (6408, 6421), True, 'import numpy as np\n'), ((19194, 19457), 'deep_staple.utils.torch_utils.spatial_augment', 'spatial_augment', ([], {'b_label': 'b_modified_label', 'use_2d': 'use_2d', 'bspline_num_ctl_points': '(6)', 'bspline_strength': '(0.0)', 'bspline_probability': '(0.0)', 'affine_strength': '(0.09 * disturbance_strength)', 'add_affine_translation': '(0.18 * disturbance_strength)', 'affine_probability': '(1.0)'}), '(b_label=b_modified_label, use_2d=use_2d,\n bspline_num_ctl_points=6, bspline_strength=0.0, bspline_probability=0.0,\n affine_strength=0.09 * disturbance_strength, add_affine_translation=\n 0.18 * disturbance_strength, affine_probability=1.0)\n', (19209, 19457), False, 'from deep_staple.utils.torch_utils import interpolate_sample, augmentNoise, spatial_augment, torch_manual_seeded, ensure_dense\n'), ((8419, 8436), 'deep_staple.utils.torch_utils.ensure_dense', 'ensure_dense', (['lbl'], {}), '(lbl)\n', (8431, 8436), False, 'from deep_staple.utils.torch_utils import interpolate_sample, augmentNoise, spatial_augment, torch_manual_seeded, ensure_dense\n'), ((18284, 18298), 'torch.randn', 'torch.randn', (['(1)'], {}), '(1)\n', (18295, 18298), False, 'import torch\n'), ((18359, 18373), 'torch.randn', 'torch.randn', (['(1)'], {}), '(1)\n', (18370, 18373), False, 'import torch\n'), ((18730, 18744), 'torch.randn', 'torch.randn', (['(1)'], {}), '(1)\n', (18741, 18744), False, 'import torch\n'), ((18805, 18819), 'torch.randn', 'torch.randn', (['(1)'], {}), '(1)\n', (18816, 18819), False, 'import torch\n'), ((18880, 18894), 'torch.randn', 'torch.randn', (['(1)'], {}), '(1)\n', (18891, 18894), False, 'import torch\n')] |
# -*- coding: UTF-8 -*-
from base_plugin import SimpleCommandPlugin
from plugins.core.player_manager_plugin import permissions, UserLevels
from utility_functions import build_packet, move_ship_to_coords, extract_name
from packets import (
Packets,
WarpAliasType,
WarpWorldType,
WarpActionType,
player_warp,
player_warp_toworld_write,
player_warp_toplayer_write,
player_warp_toalias_write,
fly_ship,
fly_ship_write
)
class Warpy(SimpleCommandPlugin):
"""
Plugin that allows privileged players to warp around as they like.
"""
name = 'warpy_plugin'
depends = ['command_plugin', 'player_manager_plugin']
commands = ['warp', 'warp_ship', 'outpost']
def activate(self):
super(Warpy, self).activate()
self.player_manager = self.plugins[
'player_manager_plugin'
].player_manager
@permissions(UserLevels.MODERATOR)
def warp(self, name):
"""
Warps you to a player's ship (or player to player).
Syntax: /warp [player] (to player)
"""
if name:
self.protocol.send_chat_message(self.warp.__doc__)
return
try:
first_name, rest = extract_name(name)
except ValueError as e:
self.protocol.send_chat_message(str(e))
return
if not rest:
self.warp_self_to_player([first_name])
else:
try:
second_name = extract_name(rest)[0]
except ValueError as e:
self.protocol.send_chat_message(str(e))
return
self.warp_player_to_player(first_name, second_name)
@permissions(UserLevels.ADMIN)
def warp_ship(self, location):
"""
Warps a player ship to another players ship.
Syntax: /warp_ship [player] (to player)
"""
if location:
self.protocol.send_chat_message(self.warp_ship.__doc__)
return
try:
first_name, rest = extract_name(location)
except ValueError as e:
self.protocol.send_chat_message(str(e))
return
if not rest:
self.move_own_ship_to_player(first_name)
else:
try:
second_name = extract_name(rest)[0]
except ValueError as e:
self.protocol.send_chat_message(str(e))
return
self.move_player_ship_to_other(first_name, second_name)
@permissions(UserLevels.MODERATOR)
def outpost(self, name):
"""
Warps you (or another player) to the outpost.
Syntax: /outpost [player]
"""
if name:
self.warp_player_to_outpost(self.protocol.player.name)
else:
try:
player_name, rest = extract_name(name)
except ValueError as e:
self.protocol.send_chat_message(str(e))
return
self.warp_player_to_outpost(player_name)
def warp_self_to_player(self, name):
self.logger.debug(
'Warp command called by %s to %s', self.protocol.player.name, name
)
name = ' '.join(name)
self.warp_player_to_player(self.protocol.player.name, name)
def warp_player_to_player(self, from_string, to_string):
self.logger.debug(
'Warp player-to-player command called by %s: %s to %s',
self.protocol.player.name, from_string, to_string
)
from_player = self.player_manager.get_logged_in_by_name(from_string)
to_player = self.player_manager.get_logged_in_by_name(to_string)
if from_player is not None:
if to_player is not None:
from_protocol = self.factory.protocols[from_player.protocol]
if from_player is not to_player:
self.logger.debug('target: %s', to_player.uuid)
warp_packet = build_packet(
Packets.PLAYER_WARP,
player_warp_toplayer_write(uuid=to_player.uuid)
)
else:
warp_packet = build_packet(
Packets.PLAYER_WARP,
player_warp_toalias_write(alias=WarpAliasType.SHIP)
)
from_protocol.client_protocol.transport.write(warp_packet)
if from_string != to_string:
self.protocol.send_chat_message(
'Warped ^yellow;{}^green;'
' to ^yellow;{}^green;.'.format(from_string, to_string)
)
else:
self.protocol.send_chat_message(
'Warped to ^yellow;{}^green;.'.format(to_string)
)
else:
self.protocol.send_chat_message(
'No player by the name ^yellow;{}^green; found.'.format(
to_string
)
)
self.protocol.send_chat_message(self.warp.__doc__)
return
else:
self.protocol.send_chat_message(
'No player by the name ^yellow;{}^green; found.'.format(
to_player
)
)
self.protocol.send_chat_message(self.warp.__doc__)
def move_player_ship(self, protocol, location):
if len(location) < 5:
self.logger.warning(
'Couldn\'t derive a warp location in move_player_ship. '
'Coordinates given: ^cyan;%s',
':'.join(location)
)
self.protocol.send_chat_message('Sorry, an error occurred.')
return
if len(location) == 5:
satellite = 0
else:
satellite = int(location.pop())
planet = int(location.pop())
z = int(location.pop())
y = int(location.pop())
x = int(location.pop())
move_ship_to_coords(protocol, x, y, z, planet, satellite)
def move_own_ship_to_player(self, player_name):
t = self.player_manager.get_logged_in_by_name(player_name)
if t is None:
self.protocol.send_chat_message(
'No player by the name ^yellow;{}^green; found.'.format(
player_name
)
)
self.protocol.send_chat_message(self.warp.__doc__)
return
if not t.planet:
self.protocol.send_chat_message(
'Sorry, we don\'t have a tracked planet location for '
'^yellow;{}^green;. Perhaps they haven\'t warped down '
'to a planet since logging in?'.format(t.name)
)
return
self.move_player_ship(self.protocol, t.planet.split(':'))
self.protocol.send_chat_message(
'Warp drive engaged. Warping to ^yellow;{}^green;.'.format(
player_name
)
)
def move_player_ship_to_other(self, from_player, to_player):
f = self.player_manager.get_logged_in_by_name(from_player)
t = self.player_manager.get_logged_in_by_name(to_player)
if f is None:
self.protocol.send_chat_message(
'No player by the name ^yellow;{}^green; found.'.format(
from_player
)
)
self.protocol.send_chat_message(self.warp.__doc__)
return
if t is None:
self.protocol.send_chat_message(
'No player by the name ^yellow;{}^green; found.'.format(
to_player
)
)
self.protocol.send_chat_message(self.warp.__doc__)
return
if not t.planet:
self.protocol.send_chat_message(
'Sorry, we don\'t have a tracked planet location for {}. '
'Perhaps they haven\'t warped to'
' a planet since logging in?'.format(to_player)
)
return
self.move_player_ship(
self.factory.protocols[f.protocol], t.planet.split(':')
)
self.protocol.send_chat_message(
'Warp drive engaged. Warping '
'^yellow;{}^green; to ^yellow;{}^green;.'.format(
from_player, to_player
)
)
def warp_player_to_outpost(self, player_string):
self.logger.debug(
'Warp player-to-outpost command called by %s: '
'sending %s to the outpost',
self.protocol.player.name, player_string
)
player_to_send = self.player_manager.get_logged_in_by_name(
player_string
)
if player_to_send is not None:
player_protocol = self.factory.protocols[player_to_send.protocol]
warp_packet = build_packet(
Packets.PLAYER_WARP,
player_warp_toworld_write(
world_type=WarpWorldType.UNIQUE_WORLD,
destination='outpost'
)
)
player_protocol.client_protocol.transport.write(warp_packet)
self.protocol.send_chat_message(
'Warped ^yellow;{}^green; to the outpost.'.format(
player_string
)
)
else:
self.protocol.send_chat_message(
'No player by the name ^yellow;{}^green; found.'.format(
player_string
)
)
self.protocol.send_chat_message(self.warp.__doc__)
| [
"utility_functions.move_ship_to_coords",
"plugins.core.player_manager_plugin.permissions",
"utility_functions.extract_name",
"packets.player_warp_toplayer_write",
"packets.player_warp_toworld_write",
"packets.player_warp_toalias_write"
] | [((885, 918), 'plugins.core.player_manager_plugin.permissions', 'permissions', (['UserLevels.MODERATOR'], {}), '(UserLevels.MODERATOR)\n', (896, 918), False, 'from plugins.core.player_manager_plugin import permissions, UserLevels\n'), ((1677, 1706), 'plugins.core.player_manager_plugin.permissions', 'permissions', (['UserLevels.ADMIN'], {}), '(UserLevels.ADMIN)\n', (1688, 1706), False, 'from plugins.core.player_manager_plugin import permissions, UserLevels\n'), ((2491, 2524), 'plugins.core.player_manager_plugin.permissions', 'permissions', (['UserLevels.MODERATOR'], {}), '(UserLevels.MODERATOR)\n', (2502, 2524), False, 'from plugins.core.player_manager_plugin import permissions, UserLevels\n'), ((6002, 6059), 'utility_functions.move_ship_to_coords', 'move_ship_to_coords', (['protocol', 'x', 'y', 'z', 'planet', 'satellite'], {}), '(protocol, x, y, z, planet, satellite)\n', (6021, 6059), False, 'from utility_functions import build_packet, move_ship_to_coords, extract_name\n'), ((1215, 1233), 'utility_functions.extract_name', 'extract_name', (['name'], {}), '(name)\n', (1227, 1233), False, 'from utility_functions import build_packet, move_ship_to_coords, extract_name\n'), ((2019, 2041), 'utility_functions.extract_name', 'extract_name', (['location'], {}), '(location)\n', (2031, 2041), False, 'from utility_functions import build_packet, move_ship_to_coords, extract_name\n'), ((2817, 2835), 'utility_functions.extract_name', 'extract_name', (['name'], {}), '(name)\n', (2829, 2835), False, 'from utility_functions import build_packet, move_ship_to_coords, extract_name\n'), ((8943, 9034), 'packets.player_warp_toworld_write', 'player_warp_toworld_write', ([], {'world_type': 'WarpWorldType.UNIQUE_WORLD', 'destination': '"""outpost"""'}), "(world_type=WarpWorldType.UNIQUE_WORLD,\n destination='outpost')\n", (8968, 9034), False, 'from packets import Packets, WarpAliasType, WarpWorldType, WarpActionType, player_warp, player_warp_toworld_write, player_warp_toplayer_write, player_warp_toalias_write, fly_ship, fly_ship_write\n'), ((1470, 1488), 'utility_functions.extract_name', 'extract_name', (['rest'], {}), '(rest)\n', (1482, 1488), False, 'from utility_functions import build_packet, move_ship_to_coords, extract_name\n'), ((2280, 2298), 'utility_functions.extract_name', 'extract_name', (['rest'], {}), '(rest)\n', (2292, 2298), False, 'from utility_functions import build_packet, move_ship_to_coords, extract_name\n'), ((4025, 4072), 'packets.player_warp_toplayer_write', 'player_warp_toplayer_write', ([], {'uuid': 'to_player.uuid'}), '(uuid=to_player.uuid)\n', (4051, 4072), False, 'from packets import Packets, WarpAliasType, WarpWorldType, WarpActionType, player_warp, player_warp_toworld_write, player_warp_toplayer_write, player_warp_toalias_write, fly_ship, fly_ship_write\n'), ((4234, 4285), 'packets.player_warp_toalias_write', 'player_warp_toalias_write', ([], {'alias': 'WarpAliasType.SHIP'}), '(alias=WarpAliasType.SHIP)\n', (4259, 4285), False, 'from packets import Packets, WarpAliasType, WarpWorldType, WarpActionType, player_warp, player_warp_toworld_write, player_warp_toplayer_write, player_warp_toalias_write, fly_ship, fly_ship_write\n')] |
#!/usr/bin/env python
# Copyright (c) 2018, 2019, 2020 Pure Storage, Inc.
#
# * Overview
#
# This short Nagios/Icinga plugin code shows how to build a simple plugin to monitor Pure Storage FlashArrays.
# The Pure Storage Python REST Client is used to query the FlashArray.
#
# * Installation
#
# The script should be copied to the Nagios plugins directory on the machine hosting the Nagios server or the NRPE
# for example the /usr/lib/nagios/plugins folder.
# Change the execution rights of the program to allow the execution to 'all' (usually chmod 0755).
#
# * Dependencies
#
# nagiosplugin helper Python class library for Nagios plugins (https://github.com/mpounsett/nagiosplugin)
# purestorage Pure Storage Python REST Client (https://github.com/purestorage/rest-client)
"""Pure Storage FlashArray hardware components status
Nagios plugin to retrieve the current status of hardware components from a Pure Storage FlashArray.
Hardware status indicators are collected from the target FA using the REST call.
The plugin has three mandatory arguments: 'endpoint', which specifies the target FA, 'apitoken', which
specifies the autentication token for the REST call session and 'component', that is the name of the
hardware component to be monitored. The component must be specified using the internal naming schema of
the Pure FlashArray: i.e CH0 for the main chassis, CH1 for the secondary chassis (shelf 1), CT0 for controller 0,i
CT1 for controller 1i, CH0.NVB0 for the first NVRAM module, CH0.NVB1 for the second NVRAM module, CH0.BAY0 for
the first flash module, CH0.BAY10 for the tenth flash module, CH1.BAY1, for the first flash module on the
first additional shelf,...
"""
import argparse
import logging
import logging.handlers
import nagiosplugin
import purestorage
import urllib3
class PureFAhw(nagiosplugin.Resource):
"""Pure Storage FlashArray hardware status
Retrieves FA hardware component status
"""
def __init__(self, endpoint, apitoken, component):
self.endpoint = endpoint
self.apitoken = apitoken
self.component = component
self.logger = logging.getLogger(self.name)
handler = logging.handlers.SysLogHandler(address = '/dev/log')
handler.setLevel(logging.ERROR)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
self.logger.addHandler(handler)
@property
def name(self):
return 'PURE_FA_HW_' + str(self.component)
def get_status(self):
"""Gets hardware element status from flasharray."""
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
fainfo={}
try:
fa = purestorage.FlashArray(self.endpoint, api_token=self.apitoken)
fainfo = fa.get_hardware(component=self.component)
fa.invalidate_cookie()
except Exception as e:
self.logger.error('FA REST call returned "%s" ', e)
return(fainfo)
def probe(self):
fainfo = self.get_status()
status = fainfo.get('status')
name = fainfo.get('name')
if (status == 'not_installed') or (name != self.component):
return []
if (status == 'ok'):
metric = nagiosplugin.Metric(self.component + ' status', 0, context='default' )
else:
metric = nagiosplugin.Metric(self.component + ' status', 1, context='default')
return metric
def parse_args():
argp = argparse.ArgumentParser()
argp.add_argument('endpoint', help="FA hostname or ip address")
argp.add_argument('apitoken', help="FA api_token")
argp.add_argument('component', help="FA hardware component")
argp.add_argument('-v', '--verbose', action='count', default=0,
help='increase output verbosity (use up to 3 times)')
argp.add_argument('-t', '--timeout', default=30,
help='abort execution after TIMEOUT seconds')
return argp.parse_args()
@nagiosplugin.guarded
def main():
args = parse_args()
check = nagiosplugin.Check( PureFAhw(args.endpoint, args.apitoken, args.component) )
check.add(nagiosplugin.ScalarContext('default', '', '@1:1'))
check.main(args.verbose, args.timeout)
if __name__ == '__main__':
main()
| [
"logging.getLogger",
"argparse.ArgumentParser",
"logging.Formatter",
"nagiosplugin.Metric",
"purestorage.FlashArray",
"urllib3.disable_warnings",
"nagiosplugin.ScalarContext",
"logging.handlers.SysLogHandler"
] | [((3546, 3571), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (3569, 3571), False, 'import argparse\n'), ((2157, 2185), 'logging.getLogger', 'logging.getLogger', (['self.name'], {}), '(self.name)\n', (2174, 2185), False, 'import logging\n'), ((2204, 2254), 'logging.handlers.SysLogHandler', 'logging.handlers.SysLogHandler', ([], {'address': '"""/dev/log"""'}), "(address='/dev/log')\n", (2234, 2254), False, 'import logging\n'), ((2317, 2390), 'logging.Formatter', 'logging.Formatter', (['"""%(asctime)s - %(name)s - %(levelname)s - %(message)s"""'], {}), "('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n", (2334, 2390), False, 'import logging\n'), ((2652, 2719), 'urllib3.disable_warnings', 'urllib3.disable_warnings', (['urllib3.exceptions.InsecureRequestWarning'], {}), '(urllib3.exceptions.InsecureRequestWarning)\n', (2676, 2719), False, 'import urllib3\n'), ((4217, 4266), 'nagiosplugin.ScalarContext', 'nagiosplugin.ScalarContext', (['"""default"""', '""""""', '"""@1:1"""'], {}), "('default', '', '@1:1')\n", (4243, 4266), False, 'import nagiosplugin\n'), ((2768, 2830), 'purestorage.FlashArray', 'purestorage.FlashArray', (['self.endpoint'], {'api_token': 'self.apitoken'}), '(self.endpoint, api_token=self.apitoken)\n', (2790, 2830), False, 'import purestorage\n'), ((3317, 3386), 'nagiosplugin.Metric', 'nagiosplugin.Metric', (["(self.component + ' status')", '(0)'], {'context': '"""default"""'}), "(self.component + ' status', 0, context='default')\n", (3336, 3386), False, 'import nagiosplugin\n'), ((3423, 3492), 'nagiosplugin.Metric', 'nagiosplugin.Metric', (["(self.component + ' status')", '(1)'], {'context': '"""default"""'}), "(self.component + ' status', 1, context='default')\n", (3442, 3492), False, 'import nagiosplugin\n')] |
from __future__ import annotations
from argparse import ArgumentParser
from collections import deque
import numpy as np
def count_lte(mat: np.ndarray) -> np.ndarray:
"""
lte[i,j] = count (neighbours <= mat[i,j])
. t .
l . r
. b .
"""
aug = np.pad(mat.astype(float), (1, 1), mode="constant", constant_values=np.inf)
l = aug[1:-1, :-2] <= mat
r = aug[1:-1, 2:] <= mat
t = aug[:-2, 1:-1] <= mat
b = aug[2:, 1:-1] <= mat
return l + r + t + b
def part1(xs):
lte = count_lte(xs)
return np.sum(1 + xs[lte == 0])
def get_basin(xs: np.ndarray, row: int, col: int) -> list[tuple[int, int]]:
"""
Return the indices of the locations flowing towards the low point `row, col`.
"""
h, w = xs.shape
out = []
q = deque()
v = np.zeros_like(xs).astype(bool)
q.append((row, col))
v[row, col] = True
while q:
i, j = q.popleft()
out.append((i, j))
for di, dj in [(0, -1), (0, 1), (-1, 0), (1, 0)]:
i2 = i + di
j2 = j + dj
if not (0 <= i2 < h) or not (0 <= j2 < w):
continue
if v[i2, j2]:
continue
if xs[i2, j2] == 9:
continue
q.append((i2, j2))
v[i2, j2] = True
return out
def part2(xs):
lte = count_lte(xs)
basins = [get_basin(xs, row, col) for row, col in zip(*np.where(lte == 0))]
top = sorted(map(len, basins), reverse=True)
return np.product(top[:3])
def visualize(xs):
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.colors import ListedColormap
lte = count_lte(xs)
cmap = cm.Blues_r(np.linspace(0, 1, 10))
cmap[-1] = [0, 0, 0, 1]
plt.imshow(xs, cmap=ListedColormap(cmap))
basins = sorted(
[get_basin(xs, row, col) for row, col in zip(*np.where(lte == 0))],
key=len,
reverse=True,
)
cmap = cm.viridis(np.linspace(0.8, 0.2, 6))
for i in range(3):
r, c = zip(*basins[i])
plt.scatter(c, r, c=[cmap[i * 2]], marker="s")
r, c = np.where(lte == 0)
plt.scatter(c, r, c="red", marker="x")
plt.show()
def main():
with open(args.file) as fp:
xs = np.array([[int(i) for i in x.strip()] for x in fp.readlines()])
if args.visualize:
visualize(xs)
return
print("Part 1:", part1(xs))
print("Part 2:", part2(xs))
if __name__ == "__main__":
parser = ArgumentParser()
parser.add_argument("--file", type=str, required=True)
parser.add_argument(
"--visualize",
action="store_true",
help="Visualize the map with low points and basins",
)
args = parser.parse_args()
main()
| [
"numpy.product",
"collections.deque",
"argparse.ArgumentParser",
"numpy.where",
"matplotlib.colors.ListedColormap",
"numpy.sum",
"numpy.linspace",
"matplotlib.pyplot.scatter",
"numpy.zeros_like",
"matplotlib.pyplot.show"
] | [((544, 568), 'numpy.sum', 'np.sum', (['(1 + xs[lte == 0])'], {}), '(1 + xs[lte == 0])\n', (550, 568), True, 'import numpy as np\n'), ((787, 794), 'collections.deque', 'deque', ([], {}), '()\n', (792, 794), False, 'from collections import deque\n'), ((1510, 1529), 'numpy.product', 'np.product', (['top[:3]'], {}), '(top[:3])\n', (1520, 1529), True, 'import numpy as np\n'), ((2125, 2143), 'numpy.where', 'np.where', (['(lte == 0)'], {}), '(lte == 0)\n', (2133, 2143), True, 'import numpy as np\n'), ((2148, 2186), 'matplotlib.pyplot.scatter', 'plt.scatter', (['c', 'r'], {'c': '"""red"""', 'marker': '"""x"""'}), "(c, r, c='red', marker='x')\n", (2159, 2186), True, 'import matplotlib.pyplot as plt\n'), ((2192, 2202), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2200, 2202), True, 'import matplotlib.pyplot as plt\n'), ((2494, 2510), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (2508, 2510), False, 'from argparse import ArgumentParser\n'), ((1714, 1735), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(10)'], {}), '(0, 1, 10)\n', (1725, 1735), True, 'import numpy as np\n'), ((1978, 2002), 'numpy.linspace', 'np.linspace', (['(0.8)', '(0.2)', '(6)'], {}), '(0.8, 0.2, 6)\n', (1989, 2002), True, 'import numpy as np\n'), ((2066, 2112), 'matplotlib.pyplot.scatter', 'plt.scatter', (['c', 'r'], {'c': '[cmap[i * 2]]', 'marker': '"""s"""'}), "(c, r, c=[cmap[i * 2]], marker='s')\n", (2077, 2112), True, 'import matplotlib.pyplot as plt\n'), ((803, 820), 'numpy.zeros_like', 'np.zeros_like', (['xs'], {}), '(xs)\n', (816, 820), True, 'import numpy as np\n'), ((1790, 1810), 'matplotlib.colors.ListedColormap', 'ListedColormap', (['cmap'], {}), '(cmap)\n', (1804, 1810), False, 'from matplotlib.colors import ListedColormap\n'), ((1427, 1445), 'numpy.where', 'np.where', (['(lte == 0)'], {}), '(lte == 0)\n', (1435, 1445), True, 'import numpy as np\n'), ((1888, 1906), 'numpy.where', 'np.where', (['(lte == 0)'], {}), '(lte == 0)\n', (1896, 1906), True, 'import numpy as np\n')] |
import numpy as np
import tensorflow as tf
def split_reim(array):
"""Split a complex valued matrix into its real and imaginary parts.
Args:
array(complex): An array of shape (batch_size, N, N) or (batch_size, N, N, 1)
Returns:
split_array(float): An array of shape (batch_size, N, N, 2) containing the real part on one channel and the imaginary part on another channel
"""
real = np.real(array)
imag = np.imag(array)
split_array = np.stack((real, imag), axis=3)
return split_array
def split_reim_tensor(array):
"""Split a complex valued tensor into its real and imaginary parts.
Args:
array(complex): A tensor of shape (batch_size, N, N) or (batch_size, N, N, 1)
Returns:
split_array(float): A tensor of shape (batch_size, N, N, 2) containing the real part on one channel and the imaginary part on another channel
"""
real = tf.math.real(array)
imag = tf.math.imag(array)
split_array = tf.stack((real, imag), axis=3)
return split_array
def split_reim_channels(array):
"""Split a complex valued tensor into its real and imaginary parts.
Args:
array(complex): A tensor of shape (batch_size, N, N) or (batch_size, N, N, 1)
Returns:
split_array(float): A tensor of shape (batch_size, N, N, 2) containing the real part on one channel and the imaginary part on another channel
"""
real = tf.math.real(array)
imag = tf.math.imag(array)
n_ch = array.get_shape().as_list()[3]
split_array = tf.concat((real, imag), axis=3)
return split_array
def join_reim(array):
"""Join the real and imaginary channels of a matrix to a single complex-valued matrix.
Args:
array(float): An array of shape (batch_size, N, N, 2)
Returns:
joined_array(complex): An complex-valued array of shape (batch_size, N, N, 1)
"""
joined_array = array[:, :, :, 0] + 1j * array[:, :, :, 1]
return joined_array
def join_reim_tensor(array):
"""Join the real and imaginary channels of a matrix to a single complex-valued matrix.
Args:
array(float): An array of shape (batch_size, N, N, 2)
Returns:
joined_array(complex): A complex-valued array of shape (batch_size, N, N)
"""
joined_array = tf.cast(array[:, :, :, 0], 'complex64') + \
1j * tf.cast(array[:, :, :, 1], 'complex64')
return joined_array
def join_reim_channels(array):
"""Join the real and imaginary channels of a matrix to a single complex-valued matrix.
Args:
array(float): An array of shape (batch_size, N, N, ch)
Returns:
joined_array(complex): A complex-valued array of shape (batch_size, N, N, ch/2)
"""
ch = array.get_shape().as_list()[3]
joined_array = tf.cast(array[:,
:,
:,
:int(ch / 2)],
dtype=tf.complex64) + 1j * tf.cast(array[:,
:,
:,
int(ch / 2):],
dtype=tf.complex64)
return joined_array
def convert_to_frequency_domain(images):
"""Convert an array of images to their Fourier transforms.
Args:
images(float): An array of shape (batch_size, N, N, 2)
Returns:
spectra(float): An FFT-ed array of shape (batch_size, N, N, 2)
"""
n = images.shape[1]
spectra = split_reim(np.fft.fft2(join_reim(images), axes=(1, 2)))
return spectra
def convert_tensor_to_frequency_domain(images):
"""Convert a tensor of images to their Fourier transforms.
Args:
images(float): A tensor of shape (batch_size, N, N, 2)
Returns:
spectra(float): An FFT-ed tensor of shape (batch_size, N, N, 2)
"""
n = images.shape[1]
spectra = split_reim_tensor(tf.signal.fft2d(join_reim_tensor(images)))
return spectra
def convert_to_image_domain(spectra):
"""Convert an array of Fourier spectra to the corresponding images.
Args:
spectra(float): An array of shape (batch_size, N, N, 2)
Returns:
images(float): An IFFT-ed array of shape (batch_size, N, N, 2)
"""
n = spectra.shape[1]
images = split_reim(np.fft.ifft2(join_reim(spectra), axes=(1, 2)))
return images
def convert_tensor_to_image_domain(spectra):
"""Convert an array of Fourier spectra to the corresponding images.
Args:
spectra(float): An array of shape (batch_size, N, N, 2)
Returns:
images(float): An IFFT-ed array of shape (batch_size, N, N, 2)
"""
n = spectra.shape[1]
images = split_reim_tensor(tf.signal.ifft2d(join_reim_tensor(spectra)))
return images
| [
"tensorflow.math.imag",
"numpy.real",
"numpy.stack",
"tensorflow.concat",
"tensorflow.math.real",
"tensorflow.cast",
"numpy.imag",
"tensorflow.stack"
] | [((417, 431), 'numpy.real', 'np.real', (['array'], {}), '(array)\n', (424, 431), True, 'import numpy as np\n'), ((443, 457), 'numpy.imag', 'np.imag', (['array'], {}), '(array)\n', (450, 457), True, 'import numpy as np\n'), ((476, 506), 'numpy.stack', 'np.stack', (['(real, imag)'], {'axis': '(3)'}), '((real, imag), axis=3)\n', (484, 506), True, 'import numpy as np\n'), ((911, 930), 'tensorflow.math.real', 'tf.math.real', (['array'], {}), '(array)\n', (923, 930), True, 'import tensorflow as tf\n'), ((942, 961), 'tensorflow.math.imag', 'tf.math.imag', (['array'], {}), '(array)\n', (954, 961), True, 'import tensorflow as tf\n'), ((980, 1010), 'tensorflow.stack', 'tf.stack', (['(real, imag)'], {'axis': '(3)'}), '((real, imag), axis=3)\n', (988, 1010), True, 'import tensorflow as tf\n'), ((1417, 1436), 'tensorflow.math.real', 'tf.math.real', (['array'], {}), '(array)\n', (1429, 1436), True, 'import tensorflow as tf\n'), ((1448, 1467), 'tensorflow.math.imag', 'tf.math.imag', (['array'], {}), '(array)\n', (1460, 1467), True, 'import tensorflow as tf\n'), ((1528, 1559), 'tensorflow.concat', 'tf.concat', (['(real, imag)'], {'axis': '(3)'}), '((real, imag), axis=3)\n', (1537, 1559), True, 'import tensorflow as tf\n'), ((2277, 2316), 'tensorflow.cast', 'tf.cast', (['array[:, :, :, 0]', '"""complex64"""'], {}), "(array[:, :, :, 0], 'complex64')\n", (2284, 2316), True, 'import tensorflow as tf\n'), ((2334, 2373), 'tensorflow.cast', 'tf.cast', (['array[:, :, :, 1]', '"""complex64"""'], {}), "(array[:, :, :, 1], 'complex64')\n", (2341, 2373), True, 'import tensorflow as tf\n')] |
#!/usr/bin/env python
'''
modify camera parameters using v4l
'''
import os
# change /dev/video6 resolution
#os.system('v4l2-ctl -d /dev/video6 -v width=640,height=480')
os.system('v4l2-ctl -d /dev/video6 -v width=160,height=120')
| [
"os.system"
] | [((172, 232), 'os.system', 'os.system', (['"""v4l2-ctl -d /dev/video6 -v width=160,height=120"""'], {}), "('v4l2-ctl -d /dev/video6 -v width=160,height=120')\n", (181, 232), False, 'import os\n')] |
# /bin/env python
# coding: utf-8
from __future__ import print_function
import sys
import argparse
import logging
import os
import math
import cv2
import numpy as np
class GenerateSyntheticData:
import PythonMagick as Magick
def __init__(self, logger=None):
if logger == None:
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
self.logger = logging.getLogger()
else:
self.logger = logger
@staticmethod
def appendArgumentParser(argparser):
argparser.add_argument('--shift-x', type=int, help='')
argparser.add_argument('--shift-y', type=int, help='')
argparser.add_argument('--skew-x', type=float, help='')
argparser.add_argument('--skew-y', type=float, help='')
argparser.add_argument('--rotate', type=float, help='rotates image clock- or counterclock-wise (angle in degrees)')
argparser.add_argument('--horizontal_flip', action='store_true', help='horizontally flips image')
argparser.add_argument('--zoom', type=str, help='resize image; argument given in percentage')
argparser.add_argument('--contrast', type=int, help='default=0; 0~infinity (integer times contract is applided to image)')
argparser.add_argument('--brightness', type=float, help='default=100')
argparser.add_argument('--saturation', type=float, help='default=100')
argparser.add_argument('--hue', type=float, help='default=100')
argparser.add_argument('--blur', action='store_true', help='')
argparser.add_argument('--blur_radius', type=float, default=10, help='')
argparser.add_argument('--blur_sigma', type=float, default=1, help='')
argparser.add_argument('--gaussianBlur', action='store_true', help='')
argparser.add_argument('--gaussianBlur_width', type=float, default=5, help='')
argparser.add_argument('--gaussianBlur_sigma', type=float, default=1, help='')
argparser.add_argument('--despeckle', action='store_true', help='')
argparser.add_argument('--enhance', action='store_true', help='')
argparser.add_argument('--equalize', action='store_true', help='')
argparser.add_argument('--gamma', type=float, help='0 ~ 2; 1 is default')
argparser.add_argument('--implode', type=float, help='Implode factor 0~1; 0 (nothing) to 1 (full); 0.0 ~ 0.5 recommended.')
argparser.add_argument('--negate', action='store_true', help='')
argparser.add_argument('--normalize', action='store_true', help='')
argparser.add_argument('--quantize', action='store_true', help='')
argparser.add_argument('--reduceNoise', type=int, help='default=1')
argparser.add_argument('--shade', action='store_true', help='')
argparser.add_argument('--shade_azimuth', type=float, default=50, help='')
argparser.add_argument('--shade_elevation', type=float, default=50, help='')
argparser.add_argument('--sharpen', action='store_true', help='')
argparser.add_argument('--sharpen_radius', type=float, default=1, help='')
argparser.add_argument('--sharpen_sigma', type=float, default=0.5, help='')
argparser.add_argument('--swirl', type=float, help='degree; default=10')
argparser.add_argument('--wave', action='store_true', help='')
argparser.add_argument('--wave_amplitude', type=float, default=5, help='')
argparser.add_argument('--wave_wavelength', type=float, default=100, help='')
argparser.add_argument('--auto', action='store_true', help='')
argparser.add_argument('--auto_ops', type=str, default='', help='')
argparser.add_argument('--auto_rotate_min', type=float, default=0, help='')
argparser.add_argument('--auto_rotate_max', type=float, default=0, help='')
argparser.add_argument('--auto_zoom_min', type=float, default=0, help='')
argparser.add_argument('--auto_zoom_max', type=float, default=0, help='')
def generateRandomOptions(self, cmdArg):
def _generateRandomOptionsShift(args):
args.shift_x = int(np.abs(np.random.normal(0, 3))) # -10 ~ +10
args.shift_y = int(np.abs(np.random.normal(0, 1))) # -3 ~ +3
def _generateRandomOptionsSkew(args):
args.skew_x = int(np.random.normal(0, 3)) # -10 ~ +10
args.skew_y = int(np.random.normal(0, 3)) # -10 ~ +10
def _generateRandomOptionsRotate(args):
if cmdArg.auto_rotate_min != cmdArg.auto_rotate_max:
args.rotate = int(np.random.uniform(cmdArg.auto_rotate_min, cmdArg.auto_rotate_max))
else:
args.rotate = int(np.random.normal(0, 3)) # -10 ~ +10
def _generateRandomOptionsZoom(args):
if cmdArg.auto_zoom_min != cmdArg.auto_zoom_max:
args.zoom = str(int(np.random.uniform(cmdArg.auto_zoom_min, cmdArg.auto_zoom_max))) + '%'
else:
args.zoom = str(int(np.random.normal(100, 3))) + '%' # 90% ~ 110%
def _generateRandomOptionsContrast(args):
args.contrast = int(np.abs(np.random.normal(0, 1))) # 0 ~ +3
def _generateRandomOptionsBrightness(args):
args.brightness = np.random.normal(100, 5) # 85 ~ 115
def _generateRandomOptionsSaturation(args):
args.saturation = np.random.normal(100, 5) # 85 ~ 115
def _generateRandomOptionsHue(args):
args.hue = np.random.normal(100, 5) # 85 ~ 115
def _generateRandomOptionsBlur(args):
if np.random.binomial(1,0.1): # do blur
if np.random.binomial(1,0.5):
args.blur = True
else:
args.gaussianBlur = True
if args.blur:
args.blur_radius = np.abs(np.random.normal(0, 3)) # 0 ~ 10
args.blur_sigma = np.abs(np.random.normal(0, 0.7)) # 0 ~ 2
if args.gaussianBlur:
args.gaussianBlur_width = np.abs(np.random.normal(0, 3)) # 0 ~ 10
args.gaussianBlur_sigma = np.abs(np.random.normal(0, 0.7)) # 0 ~ 2
def _generateRandomOptionsHorizontalFlip(args):
args.horizontal_flip = (np.random.binomial(1,0.1) > 0)
def _generateRandomOptionsDespeckle(args):
args.despeckle = (np.random.binomial(1,0.5) > 0)
def _generateRandomOptionsEnhance(args):
args.enhance = (np.random.binomial(1,0.5) > 0)
def _generateRandomOptionsEqualize(args):
args.equalize = (np.random.binomial(1,0.1) == 1)
def _generateRandomOptionsNegate(args):
args.negate = (np.random.binomial(1,0.1) == 1)
def _generateRandomOptionsNormalize(args):
args.normalize = (np.random.binomial(1,0.1) > 0)
def _generateRandomOptionsQuantize(args):
args.quantize = (np.random.binomial(1,0.1) > 0)
def _generateRandomOptionsGamma(args):
args.gamma = np.abs(np.random.normal(1, 0.03)) # 0 ~ 2
def _generateRandomOptionsImplode(args):
args.implode = 0
if np.random.binomial(1,0.5) > 0:
args.implode = np.random.normal(0, 0.15) # -0.5 ~ 0.5
def _generateRandomOptionsReduceNoise(args):
args.reduceNoise = int(np.abs(np.random.normal(0, 0.7))) # 0 ~ 2
def _generateRandomOptionsShade(args):
args.shade = (np.random.binomial(1,0.1) > 0)
if args.shade:
args.shade_azimuth = np.random.normal(50, 17) # 0 ~ 100
args.shade_elevation = np.random.normal(50, 17) # 0 ~ 100
def _generateRandomOptionsSharpen(args):
args.sharpen = (np.random.binomial(1,0.1) > 0)
if args.sharpen:
args.sharpen_radius = np.abs(np.random.normal(0, 0.7)) # 0 ~ 2
args.sharpen_sigma = np.abs(np.random.normal(0, 0.3)) # 0 ~ 1
def _generateRandomOptionsSwirl(args):
args.swirl = np.random.normal(0, 5) # -15 ~ +15
def _generateRandomOptionsWave(args):
args.wave = (np.random.binomial(1,0.3) > 0)
if args.wave:
args.wave_amplitude = np.abs(np.random.normal(5, 0.3)) # 0 ~ 10
args.wave_wavelength = np.abs(np.random.normal(100, 10)) # 0 ~ 200
args = argparse.Namespace()
args.shift_x = args.shift_y = None
args.skew_x = args.skew_y = None
args.rotate = args.zoom = None
args.contrast = args.brightness = args.saturation = args.hue = None
args.blur = args.gaussianBlur = None
args.horizontal_flip = None
args.despeckle = args.enhance = args.reduceNoise = None
args.equalize = args.negate = args.normalize = args.quantize = args.gamma = None
args.shade = None
args.sharpen = None
args.implode = args.swirl = args.wave = None
if len(cmdArg.auto_ops)>0:
for op in cmdArg.auto_ops.split(","):
if op == 'shift': _generateRandomOptionsShift(args)
elif op == 'skew': _generateRandomOptionsSkew(args)
elif op == 'rotate': _generateRandomOptionsRotate(args)
elif op == 'zoom': _generateRandomOptionsZoom(args)
elif op == 'contrast': _generateRandomOptionsContrast(args)
elif op == 'brightness': _generateRandomOptionsBrightness(args)
elif op == 'saturation': _generateRandomOptionsSaturation(args)
elif op == 'hue': _generateRandomOptionsHue(args)
elif op == 'blur': _generateRandomOptionsBlur(args)
elif op == 'horizontal_flip': _generateRandomOptionsHorizontalFlip(args)
elif op == 'despeckle': _generateRandomOptionsDespeckle(args)
elif op == 'enhance': _generateRandomOptionsEnhance(args)
elif op == 'equalize': _generateRandomOptionsEqualize(args)
elif op == 'negate': _generateRandomOptionsNegate(args)
elif op == 'normalize': _generateRandomOptionsNormalize(args)
elif op == 'quantize': _generateRandomOptionsQuantize(args)
elif op == 'gamma': _generateRandomOptionsGamma(args)
elif op == 'implode': _generateRandomOptionsImplode(args)
elif op == 'reduceNoise': _generateRandomOptionsReduceNoise(args)
elif op == 'shade': _generateRandomOptionsShade(args)
elif op == 'sharpen': _generateRandomOptionsSharpen(args)
elif op == 'swirl': _generateRandomOptionsSwirl(args)
elif op == 'wave': _generateRandomOptionsWave(args)
else:
self.logger.error('Unknown Operation Name ' + op)
else: # apply all operations
_generateRandomOptionsShift(args)
_generateRandomOptionsSkew(args)
_generateRandomOptionsRotate(args)
_generateRandomOptionsZoom(args)
_generateRandomOptionsContrast(args)
_generateRandomOptionsBrightness(args)
_generateRandomOptionsSaturation(args)
_generateRandomOptionsHue(args)
_generateRandomOptionsBlur(args)
#_generateRandomOptionsHorizontalFlip(args)
_generateRandomOptionsDespeckle(args)
_generateRandomOptionsEnhance(args)
#_generateRandomOptionsEqualize(args)
#_generateRandomOptionsNegate(args)
_generateRandomOptionsNormalize(args)
_generateRandomOptionsQuantize(args)
_generateRandomOptionsGamma(args)
_generateRandomOptionsImplode(args)
_generateRandomOptionsReduceNoise(args)
_generateRandomOptionsShade(args)
_generateRandomOptionsSharpen(args)
_generateRandomOptionsSwirl(args)
#_generateRandomOptionsWave(args)
self.logger.debug('Randomly generated options: ')
for key in vars(args):
self.logger.debug(' -- %s: %s' % (key, getattr(args, key)))
self.logger.debug('')
return args
def isVideo(self, inputF):
video_file_extensions = (
'.264', '.3g2', '.3gp', '.3gp2', '.3gpp', '.3gpp2', '.3mm', '.3p2', '.60d', '.787', '.89', '.aaf', '.aec', '.aep', '.aepx',
'.aet', '.aetx', '.ajp', '.ale', '.am', '.amc', '.amv', '.amx', '.anim', '.aqt', '.arcut', '.arf', '.asf', '.asx', '.avb',
'.avc', '.avd', '.avi', '.avp', '.avs', '.avs', '.avv', '.axm', '.bdm', '.bdmv', '.bdt2', '.bdt3', '.bik', '.bin', '.bix',
'.bmk', '.bnp', '.box', '.bs4', '.bsf', '.bvr', '.byu', '.camproj', '.camrec', '.camv', '.ced', '.cel', '.cine', '.cip',
'.clpi', '.cmmp', '.cmmtpl', '.cmproj', '.cmrec', '.cpi', '.cst', '.cvc', '.cx3', '.d2v', '.d3v', '.dat', '.dav', '.dce',
'.dck', '.dcr', '.dcr', '.ddat', '.dif', '.dir', '.divx', '.dlx', '.dmb', '.dmsd', '.dmsd3d', '.dmsm', '.dmsm3d', '.dmss',
'.dmx', '.dnc', '.dpa', '.dpg', '.dream', '.dsy', '.dv', '.dv-avi', '.dv4', '.dvdmedia', '.dvr', '.dvr-ms', '.dvx', '.dxr',
'.dzm', '.dzp', '.dzt', '.edl', '.evo', '.eye', '.ezt', '.f4p', '.f4v', '.fbr', '.fbr', '.fbz', '.fcp', '.fcproject',
'.ffd', '.flc', '.flh', '.fli', '.flv', '.flx', '.gfp', '.gl', '.gom', '.grasp', '.gts', '.gvi', '.gvp', '.h264', '.hdmov',
'.hkm', '.ifo', '.imovieproj', '.imovieproject', '.ircp', '.irf', '.ism', '.ismc', '.ismv', '.iva', '.ivf', '.ivr', '.ivs',
'.izz', '.izzy', '.jss', '.jts', '.jtv', '.k3g', '.kmv', '.ktn', '.lrec', '.lsf', '.lsx', '.m15', '.m1pg', '.m1v', '.m21',
'.m21', '.m2a', '.m2p', '.m2t', '.m2ts', '.m2v', '.m4e', '.m4u', '.m4v', '.m75', '.mani', '.meta', '.mgv', '.mj2', '.mjp',
'.mjpg', '.mk3d', '.mkv', '.mmv', '.mnv', '.mob', '.mod', '.modd', '.moff', '.moi', '.moov', '.mov', '.movie', '.mp21',
'.mp21', '.mp2v', '.mp4', '.mp4v', '.mpe', '.mpeg', '.mpeg1', '.mpeg4', '.mpf', '.mpg', '.mpg2', '.mpgindex', '.mpl',
'.mpl', '.mpls', '.mpsub', '.mpv', '.mpv2', '.mqv', '.msdvd', '.mse', '.msh', '.mswmm', '.mts', '.mtv', '.mvb', '.mvc',
'.mvd', '.mve', '.mvex', '.mvp', '.mvp', '.mvy', '.mxf', '.mxv', '.mys', '.ncor', '.nsv', '.nut', '.nuv', '.nvc', '.ogm',
'.ogv', '.ogx', '.osp', '.otrkey', '.pac', '.par', '.pds', '.pgi', '.photoshow', '.piv', '.pjs', '.playlist', '.plproj',
'.pmf', '.pmv', '.pns', '.ppj', '.prel', '.pro', '.prproj', '.prtl', '.psb', '.psh', '.pssd', '.pva', '.pvr', '.pxv',
'.qt', '.qtch', '.qtindex', '.qtl', '.qtm', '.qtz', '.r3d', '.rcd', '.rcproject', '.rdb', '.rec', '.rm', '.rmd', '.rmd',
'.rmp', '.rms', '.rmv', '.rmvb', '.roq', '.rp', '.rsx', '.rts', '.rts', '.rum', '.rv', '.rvid', '.rvl', '.sbk', '.sbt',
'.scc', '.scm', '.scm', '.scn', '.screenflow', '.sec', '.sedprj', '.seq', '.sfd', '.sfvidcap', '.siv', '.smi', '.smi',
'.smil', '.smk', '.sml', '.smv', '.spl', '.sqz', '.srt', '.ssf', '.ssm', '.stl', '.str', '.stx', '.svi', '.swf', '.swi',
'.swt', '.tda3mt', '.tdx', '.thp', '.tivo', '.tix', '.tod', '.tp', '.tp0', '.tpd', '.tpr', '.trp', '.ts', '.tsp', '.ttxt',
'.tvs', '.usf', '.usm', '.vc1', '.vcpf', '.vcr', '.vcv', '.vdo', '.vdr', '.vdx', '.veg', '.vem', '.vep', '.vf', '.vft',
'.vfw', '.vfz', '.vgz', '.vid', '.video', '.viewlet', '.viv', '.vivo', '.vlab', '.vob', '.vp3', '.vp6', '.vp7', '.vpj',
'.vro', '.vs4', '.vse', '.vsp', '.w32', '.wcp', '.webm', '.wlmp', '.wm', '.wmd', '.wmmp', '.wmv', '.wmx', '.wot', '.wp3',
'.wpl', '.wtv', '.wve', '.wvx', '.xej', '.xel', '.xesc', '.xfl', '.xlmv', '.xmv', '.xvid', '.y4m', '.yog', '.yuv', '.zeg',
'.zm1', '.zm2', '.zm3', '.zmv')
if inputF.endswith((video_file_extensions)):
return True
return False
def getFPS(self, vF):
video = cv2.VideoCapture(vF);
major_ver, _, _ = (cv2.__version__).split('.')
if int(major_ver) < 3 :
fps = video.get(cv2.cv.CV_CAP_PROP_FPS)
else :
fps = video.get(cv2.CAP_PROP_FPS)
video.release()
return fps
def splitFromVideo(self, inputF, outputFPrefix):
retVal = []
vid = cv2.VideoCapture(inputF)
idx = 0
while(True):
ret, frame = vid.read()
if not ret:
break
name = outputFPrefix + '_frame' + str(idx) + '.png'
cv2.imwrite(name, frame)
retVal.append(name)
idx += 1
return retVal
def mergeIntoVideo(self, inFs, outputF, FPS):
frame = cv2.imread(inFs[0])
height, width, _ = frame.shape
video = cv2.VideoWriter(outputF, cv2.VideoWriter_fourcc(*'mp4v'), FPS, (width, height))
for inF in inFs:
video.write(cv2.imread(inF))
video.release()
def generate(self, inputF, outputF, args):
if args.auto:
auto_options = self.generateRandomOptions(args)
logger.info('Random options: ' + str(auto_options))
if self.isVideo(inputF):
FPS = self.getFPS(inputF)
inputFs = self.splitFromVideo(inputF, outputF+'_input')
outputFs = []
for idx in range(0, len(inputFs)):
iF = inputFs[idx]
oF = outputF + '_output_frame' + str(idx) + '.png'
if args.auto:
self._generate(iF, oF, auto_options)
else:
self._generate(iF, oF, args)
outputFs.append(oF)
self.mergeIntoVideo(outputFs, outputF, FPS)
for f in inputFs:
os.remove(f)
for f in outputFs:
os.remove(f)
return True
else:
if args.auto:
return self._generate(inputF, outputF, auto_options)
else:
return self._generate(inputF, outputF, args)
def _generate(self, inputF, outputF, args):
inputImage = self.Magick.Image(inputF)
input_width = inputImage.size().width()
input_height = inputImage.size().height()
self.logger.debug('Input width and height: %d x %d' % (input_width, input_height))
# make image ready to be modified
inputImage.modifyImage()
inputImage.backgroundColor(self.Magick.Color('black'))
if args.shift_x != None:
inputImage.roll(args.shift_x, 0)
if args.shift_y != None:
inputImage.roll(0, args.shift_y)
if args.skew_x != None and args.skew_y != None:
inputImage.shear(args.skew_x, args.skew_y)
elif args.skew_x != None:
inputImage.shear(args.skew_x, 0)
if args.skew_y != None:
inputImage.shear(0, args.skew_y)
if args.rotate != None:
inputImage.rotate(args.rotate)
inputImage.crop(self.Magick.Geometry(input_width, input_height, 0, 0))
if args.horizontal_flip:
inputImage.flop()
if args.zoom != None:
inputImage.sample(self.Magick.Geometry(args.zoom))
if int(args.zoom.strip()[0:-1]) >= 100:
inputImage.crop(self.Magick.Geometry(input_width,
input_height,
int((inputImage.size().width() - input_width) / 2),
int((inputImage.size().height() - input_height) / 2)))
else:
# PythonMagick is missing extent() API
# inputImage.exent(Magick.Geometry(input_width, input_height), Magick.GravityType.CenterGravity)
smallWidth = inputImage.size().width()
smallHeight = inputImage.size().height()
inputImage.size(self.Magick.Geometry(input_width, input_height))
inputImage.draw(self.Magick.DrawableRectangle(smallWidth, smallHeight, input_width, input_height))
inputImage.draw(self.Magick.DrawableRectangle(smallWidth, 0, input_width, smallHeight))
inputImage.draw(self.Magick.DrawableRectangle(0, smallHeight, smallWidth, input_height))
inputImage.roll(int((input_width - smallWidth) / 2), int((input_height - smallHeight) / 2))
if args.contrast != None:
for _ in range(0, args.contrast):
inputImage.contrast(args.contrast)
if args.brightness != None or args.saturation != None or args.hue != None:
if args.brightness is None:
args.brightness = 100
if args.saturation is None:
args.saturation = 100
if args.hue is None:
args.hue = 100
inputImage.modulate(args.brightness, args.saturation, args.hue)
if args.blur:
inputImage.blur(args.blur_radius, args.blur_sigma)
if args.gaussianBlur:
inputImage.gaussianBlur(args.gaussianBlur_width, args.gaussianBlur_sigma)
if args.despeckle:
inputImage.despeckle()
if args.enhance:
inputImage.enhance()
if args.equalize:
inputImage.equalize()
if args.gamma != None:
inputImage.gamma(args.gamma)
if args.implode != None:
inputImage.implode(args.implode)
if args.negate:
inputImage.negate()
if args.normalize:
inputImage.normalize()
if args.quantize:
inputImage.quantize()
if args.reduceNoise != None:
inputImage.reduceNoise(args.reduceNoise)
if args.shade:
inputImage.shade(args.shade_azimuth, args.shade_elevation)
if args.sharpen:
inputImage.sharpen(args.sharpen_radius, args.sharpen_sigma)
if args.swirl != None:
inputImage.swirl(args.swirl)
if args.wave:
inputImage.wave(args.wave_amplitude, args.wave_wavelength)
inputImage.crop(self.Magick.Geometry(input_width,
input_height,
int(math.fabs((inputImage.size().width() - input_width) / 2)),
int(math.fabs((inputImage.size().height() - input_height) / 2))))
inputImage.write(outputF)
self.logger.debug('Output width and height: %d x %d' % (inputImage.size().width(), inputImage.size().height()))
return True
if __name__ == "__main__":
argparser = argparse.ArgumentParser()
argparser.add_argument('-l', '--log-level', default='INFO', help="log-level (INFO|WARN|DEBUG|FATAL|ERROR)")
argparser.add_argument('-i', '--input', required=True, help='Input image file name')
argparser.add_argument('-o', '--output', required=True, help='Output image file name')
argparser.add_argument('-w', '--overwrite', action='store_true', help='If set, will overwrite the existing output file')
GenerateSyntheticData.appendArgumentParser(argparser)
args = argparser.parse_args()
logging.basicConfig(stream=sys.stdout, level=args.log_level)
logger = logging.getLogger("DragonFly-ASL-GSD")
logger.debug('CLI arguments')
for key in vars(args):
logger.debug(' -- %s: %s' % (key, getattr(args, key)))
logger.debug('')
# check input file exists
if not os.path.isfile(args.input):
logger.error('Input file %s does not exist: ' % args.input)
sys.exit(1)
# check if output file exists
if os.path.isfile(args.output) and not args.overwrite:
try: input = raw_input
except NameError: pass
yn = input('Do you wish to overwrite %s? (y/n) ' % args.output)
if yn != 'y' and yn != 'Y':
logger.error('Output file %s will not be overwritten.' % args.output)
sys.exit(1)
GSD = GenerateSyntheticData(logger=logger)
status = GSD.generate(args.input, args.output, args)
logger.debug('Generation status: %r' % status)
| [
"logging.basicConfig",
"logging.getLogger",
"cv2.__version__.split",
"numpy.random.normal",
"cv2.imwrite",
"argparse.ArgumentParser",
"os.path.isfile",
"numpy.random.uniform",
"argparse.Namespace",
"cv2.VideoCapture",
"cv2.VideoWriter_fourcc",
"sys.exit",
"cv2.imread",
"numpy.random.binomi... | [((23128, 23153), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (23151, 23153), False, 'import argparse\n'), ((23668, 23728), 'logging.basicConfig', 'logging.basicConfig', ([], {'stream': 'sys.stdout', 'level': 'args.log_level'}), '(stream=sys.stdout, level=args.log_level)\n', (23687, 23728), False, 'import logging\n'), ((23742, 23780), 'logging.getLogger', 'logging.getLogger', (['"""DragonFly-ASL-GSD"""'], {}), "('DragonFly-ASL-GSD')\n", (23759, 23780), False, 'import logging\n'), ((8491, 8511), 'argparse.Namespace', 'argparse.Namespace', ([], {}), '()\n', (8509, 8511), False, 'import argparse\n'), ((16372, 16392), 'cv2.VideoCapture', 'cv2.VideoCapture', (['vF'], {}), '(vF)\n', (16388, 16392), False, 'import cv2\n'), ((16420, 16446), 'cv2.__version__.split', 'cv2.__version__.split', (['"""."""'], {}), "('.')\n", (16441, 16446), False, 'import cv2\n'), ((16726, 16750), 'cv2.VideoCapture', 'cv2.VideoCapture', (['inputF'], {}), '(inputF)\n', (16742, 16750), False, 'import cv2\n'), ((17113, 17132), 'cv2.imread', 'cv2.imread', (['inFs[0]'], {}), '(inFs[0])\n', (17123, 17132), False, 'import cv2\n'), ((23969, 23995), 'os.path.isfile', 'os.path.isfile', (['args.input'], {}), '(args.input)\n', (23983, 23995), False, 'import os\n'), ((24073, 24084), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (24081, 24084), False, 'import sys\n'), ((24126, 24153), 'os.path.isfile', 'os.path.isfile', (['args.output'], {}), '(args.output)\n', (24140, 24153), False, 'import os\n'), ((311, 369), 'logging.basicConfig', 'logging.basicConfig', ([], {'stream': 'sys.stdout', 'level': 'logging.INFO'}), '(stream=sys.stdout, level=logging.INFO)\n', (330, 369), False, 'import logging\n'), ((396, 415), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (413, 415), False, 'import logging\n'), ((5361, 5385), 'numpy.random.normal', 'np.random.normal', (['(100)', '(5)'], {}), '(100, 5)\n', (5377, 5385), True, 'import numpy as np\n'), ((5485, 5509), 'numpy.random.normal', 'np.random.normal', (['(100)', '(5)'], {}), '(100, 5)\n', (5501, 5509), True, 'import numpy as np\n'), ((5591, 5615), 'numpy.random.normal', 'np.random.normal', (['(100)', '(5)'], {}), '(100, 5)\n', (5607, 5615), True, 'import numpy as np\n'), ((5690, 5716), 'numpy.random.binomial', 'np.random.binomial', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (5708, 5716), True, 'import numpy as np\n'), ((8145, 8167), 'numpy.random.normal', 'np.random.normal', (['(0)', '(5)'], {}), '(0, 5)\n', (8161, 8167), True, 'import numpy as np\n'), ((16946, 16970), 'cv2.imwrite', 'cv2.imwrite', (['name', 'frame'], {}), '(name, frame)\n', (16957, 16970), False, 'import cv2\n'), ((17213, 17244), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["*'mp4v'"], {}), "(*'mp4v')\n", (17235, 17244), False, 'import cv2\n'), ((24442, 24453), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (24450, 24453), False, 'import sys\n'), ((4426, 4448), 'numpy.random.normal', 'np.random.normal', (['(0)', '(3)'], {}), '(0, 3)\n', (4442, 4448), True, 'import numpy as np\n'), ((4493, 4515), 'numpy.random.normal', 'np.random.normal', (['(0)', '(3)'], {}), '(0, 3)\n', (4509, 4515), True, 'import numpy as np\n'), ((5747, 5773), 'numpy.random.binomial', 'np.random.binomial', (['(1)', '(0.5)'], {}), '(1, 0.5)\n', (5765, 5773), True, 'import numpy as np\n'), ((6350, 6376), 'numpy.random.binomial', 'np.random.binomial', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (6368, 6376), True, 'import numpy as np\n'), ((6463, 6489), 'numpy.random.binomial', 'np.random.binomial', (['(1)', '(0.5)'], {}), '(1, 0.5)\n', (6481, 6489), True, 'import numpy as np\n'), ((6572, 6598), 'numpy.random.binomial', 'np.random.binomial', (['(1)', '(0.5)'], {}), '(1, 0.5)\n', (6590, 6598), True, 'import numpy as np\n'), ((6683, 6709), 'numpy.random.binomial', 'np.random.binomial', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (6701, 6709), True, 'import numpy as np\n'), ((6791, 6817), 'numpy.random.binomial', 'np.random.binomial', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (6809, 6817), True, 'import numpy as np\n'), ((6909, 6935), 'numpy.random.binomial', 'np.random.binomial', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (6927, 6935), True, 'import numpy as np\n'), ((7020, 7046), 'numpy.random.binomial', 'np.random.binomial', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (7038, 7046), True, 'import numpy as np\n'), ((7131, 7156), 'numpy.random.normal', 'np.random.normal', (['(1)', '(0.03)'], {}), '(1, 0.03)\n', (7147, 7156), True, 'import numpy as np\n'), ((7261, 7287), 'numpy.random.binomial', 'np.random.binomial', (['(1)', '(0.5)'], {}), '(1, 0.5)\n', (7279, 7287), True, 'import numpy as np\n'), ((7323, 7348), 'numpy.random.normal', 'np.random.normal', (['(0)', '(0.15)'], {}), '(0, 0.15)\n', (7339, 7348), True, 'import numpy as np\n'), ((7569, 7595), 'numpy.random.binomial', 'np.random.binomial', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (7587, 7595), True, 'import numpy as np\n'), ((7664, 7688), 'numpy.random.normal', 'np.random.normal', (['(50)', '(17)'], {}), '(50, 17)\n', (7680, 7688), True, 'import numpy as np\n'), ((7739, 7763), 'numpy.random.normal', 'np.random.normal', (['(50)', '(17)'], {}), '(50, 17)\n', (7755, 7763), True, 'import numpy as np\n'), ((7853, 7879), 'numpy.random.binomial', 'np.random.binomial', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (7871, 7879), True, 'import numpy as np\n'), ((8253, 8279), 'numpy.random.binomial', 'np.random.binomial', (['(1)', '(0.3)'], {}), '(1, 0.3)\n', (8271, 8279), True, 'import numpy as np\n'), ((17317, 17332), 'cv2.imread', 'cv2.imread', (['inF'], {}), '(inF)\n', (17327, 17332), False, 'import cv2\n'), ((18165, 18177), 'os.remove', 'os.remove', (['f'], {}), '(f)\n', (18174, 18177), False, 'import os\n'), ((18225, 18237), 'os.remove', 'os.remove', (['f'], {}), '(f)\n', (18234, 18237), False, 'import os\n'), ((4237, 4259), 'numpy.random.normal', 'np.random.normal', (['(0)', '(3)'], {}), '(0, 3)\n', (4253, 4259), True, 'import numpy as np\n'), ((4313, 4335), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)'], {}), '(0, 1)\n', (4329, 4335), True, 'import numpy as np\n'), ((4678, 4743), 'numpy.random.uniform', 'np.random.uniform', (['cmdArg.auto_rotate_min', 'cmdArg.auto_rotate_max'], {}), '(cmdArg.auto_rotate_min, cmdArg.auto_rotate_max)\n', (4695, 4743), True, 'import numpy as np\n'), ((4797, 4819), 'numpy.random.normal', 'np.random.normal', (['(0)', '(3)'], {}), '(0, 3)\n', (4813, 4819), True, 'import numpy as np\n'), ((5239, 5261), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)'], {}), '(0, 1)\n', (5255, 5261), True, 'import numpy as np\n'), ((5946, 5968), 'numpy.random.normal', 'np.random.normal', (['(0)', '(3)'], {}), '(0, 3)\n', (5962, 5968), True, 'import numpy as np\n'), ((6021, 6045), 'numpy.random.normal', 'np.random.normal', (['(0)', '(0.7)'], {}), '(0, 0.7)\n', (6037, 6045), True, 'import numpy as np\n'), ((6139, 6161), 'numpy.random.normal', 'np.random.normal', (['(0)', '(3)'], {}), '(0, 3)\n', (6155, 6161), True, 'import numpy as np\n'), ((6222, 6246), 'numpy.random.normal', 'np.random.normal', (['(0)', '(0.7)'], {}), '(0, 0.7)\n', (6238, 6246), True, 'import numpy as np\n'), ((7459, 7483), 'numpy.random.normal', 'np.random.normal', (['(0)', '(0.7)'], {}), '(0, 0.7)\n', (7475, 7483), True, 'import numpy as np\n'), ((7958, 7982), 'numpy.random.normal', 'np.random.normal', (['(0)', '(0.7)'], {}), '(0, 0.7)\n', (7974, 7982), True, 'import numpy as np\n'), ((8037, 8061), 'numpy.random.normal', 'np.random.normal', (['(0)', '(0.3)'], {}), '(0, 0.3)\n', (8053, 8061), True, 'import numpy as np\n'), ((8355, 8379), 'numpy.random.normal', 'np.random.normal', (['(5)', '(0.3)'], {}), '(5, 0.3)\n', (8371, 8379), True, 'import numpy as np\n'), ((8437, 8462), 'numpy.random.normal', 'np.random.normal', (['(100)', '(10)'], {}), '(100, 10)\n', (8453, 8462), True, 'import numpy as np\n'), ((4978, 5039), 'numpy.random.uniform', 'np.random.uniform', (['cmdArg.auto_zoom_min', 'cmdArg.auto_zoom_max'], {}), '(cmdArg.auto_zoom_min, cmdArg.auto_zoom_max)\n', (4995, 5039), True, 'import numpy as np\n'), ((5102, 5126), 'numpy.random.normal', 'np.random.normal', (['(100)', '(3)'], {}), '(100, 3)\n', (5118, 5126), True, 'import numpy as np\n')] |
from service_objects import services
import numpy as np
import pandas as pd
from django.db import connection
import datetime
from front.models import Match, Match_Stats, Player, Tourney, Tourney_Level, Surface
class IngestMatchesService(services.Service):
def process(self):
cursor = connection.cursor()
errors = ''
total_matches_updated = 0
total_matches_inserted = 0
tourneys = {}
surfaces = {}
tourney_levels = {}
players = {}
for year in range(1990, 2021):
csv_file = pd.read_csv('https://raw.githubusercontent.com/JeffSackmann/tennis_atp/master/atp_matches_' + str(year) + '.csv', header=1, names=self.getColumns())
for row in csv_file.itertuples():
created_at = datetime.datetime.now()
updated_at = datetime.datetime.now()
#try:
id = str(row.tourney_id) + '-' + str(row.match_num)
match = Match.objects.filter(id=id)
if (not match):
match = Match()
match.id = id
match.year = row.tourney_id.split('-')[0]
match.match_num = row.match_num
match.result = row.score
match.best_of = row.best_of
match.minutes = None if np.isnan(row.minutes) else row.minutes
match.round = row.round
if not tourneys.get(str(row.tourney_id)):
tourney = Tourney.objects.filter(id=row.tourney_id)
if (not tourney):
tourney = Tourney()
tourney.id = row.tourney_id
tourney.name = row.tourney_name
tourney.date = datetime.datetime.strptime(str(int(row.tourney_date)), '%Y%m%d').date()
tourney.created_at = created_at
tourney.updated_at = updated_at
if not surfaces.get(str(row.surface)):
surfaces[str(row.surface)] = self.getSurface(str(row.surface))
tourney.surface = surfaces[str(row.surface)]
if not tourney_levels.get(str(row.tourney_level)):
tourney_levels[str(row.tourney_level)] = self.getTourneyLevel(str(row.tourney_level))
tourney.tourney_level = tourney_levels[str(row.tourney_level)]
tourney.created_at = created_at
tourney.updated_at = updated_at
tourney.save()
else:
tourney = tourney[0]
tourneys[str(row.tourney_id)] = tourney
match.tourney = tourneys[str(row.tourney_id)]
match.created_at = created_at
match.updated_at = updated_at
match.save()
total_matches_inserted += 1
else:
match[0].year = row.tourney_id.split('-')[0]
match[0].save()
total_matches_updated += 1
match = match[0]
match_stats_id = str(row.tourney_id) + '-' + str(row.match_num) + '-' + str(row.winner_id)
match_stats = Match_Stats.objects.filter(id=match_stats_id)
if (not match_stats):
seed = row.winner_seed
if pd.isnull(row.winner_seed) or not str(row.winner_seed).isnumeric():
seed = None
match_stats = Match_Stats()
match_stats.id = match_stats_id
match_stats.type = ""
match_stats.seed = seed
match_stats.aces = None if np.isnan(row.w_ace) else row.w_ace
match_stats.double_faults = None if np.isnan(row.w_df) else row.w_df
match_stats.service_points = None if np.isnan(row.w_svpt) else row.w_svpt
match_stats.first_services = None if np.isnan(row.w_1stIn) else row.w_1stIn
match_stats.first_services_won = None if np.isnan(row.w_1stWon) else row.w_1stWon
match_stats.second_services_won = None if np.isnan(row.w_2ndWon) else row.w_2ndWon
match_stats.service_game_won = None if np.isnan(row.w_SvGms) else row.w_SvGms
match_stats.break_points_saved = None if np.isnan(row.w_bpSaved) else row.w_bpSaved
match_stats.break_points_played = None if np.isnan(row.w_bpFaced) else row.w_bpFaced
match_stats.rank = None if np.isnan(row.winner_rank) else row.winner_rank
match_stats.rank_points = None if np.isnan(row.winner_rank_points) else row.winner_rank_points
match_stats.is_winner = True
match_stats.created_at = created_at
match_stats.updated_at = updated_at
players[row.winner_id] = self.getPlayer(str(row.winner_id))
match_stats.player = players[row.winner_id]
match_stats.match = match
match_stats.save()
match_stats_id = str(row.tourney_id) + '-' + str(row.match_num) + '-' + str(row.loser_id)
match_stats = Match_Stats.objects.filter(id=match_stats_id)
if (not match_stats):
seed = row.loser_seed
if pd.isnull(row.loser_seed) or not str(row.loser_seed).isnumeric():
seed = None
match_stats = Match_Stats()
match_stats.id = match_stats_id
match_stats.type = ""
match_stats.seed = seed
match_stats.aces = None if np.isnan(row.l_ace) else row.l_ace
match_stats.double_faults = None if np.isnan(row.l_df) else row.l_df
match_stats.service_points = None if np.isnan(row.l_svpt) else row.l_svpt
match_stats.first_services = None if np.isnan(row.l_1stIn) else row.l_1stIn
match_stats.first_services_won = None if np.isnan(row.l_1stWon) else row.l_1stWon
match_stats.second_services_won = None if np.isnan(row.l_2ndWon) else row.l_2ndWon
match_stats.service_game_won = None if np.isnan(row.l_SvGms) else row.l_SvGms
match_stats.break_points_saved = None if np.isnan(row.l_bpSaved) else row.l_bpSaved
match_stats.break_points_played = None if np.isnan(row.l_bpFaced) else row.l_bpFaced
match_stats.rank = None if np.isnan(row.loser_rank) else row.loser_rank
match_stats.rank_points = None if np.isnan(row.loser_rank_points) else row.loser_rank_points
match_stats.is_winner = False
match_stats.created_at = created_at
match_stats.updated_at = updated_at
players[row.loser_id] = self.getPlayer(str(row.loser_id))
match_stats.player = players[row.loser_id]
match_stats.match = match
match_stats.save()
#except:
# assert False, (row.tourney_date, )
#errors = errors + '|||' + str(row.tourney_id) + '-' + str(row.match_num)
return {'inserts': total_matches_inserted, 'updates': total_matches_updated}
def getColumns(self):
return ["tourney_id","tourney_name","surface","draw_size","tourney_level","tourney_date","match_num","winner_id","winner_seed","winner_entry","winner_name","winner_hand","winner_ht","winner_ioc","winner_age",
"loser_id","loser_seed","loser_entry","loser_name","loser_hand","loser_ht","loser_ioc","loser_age","score","best_of","round","minutes","w_ace","w_df","w_svpt","w_1stIn","w_1stWon","w_2ndWon","w_SvGms","w_bpSaved",
"w_bpFaced","l_ace","l_df","l_svpt","l_1stIn","l_1stWon","l_2ndWon","l_SvGms","l_bpSaved","l_bpFaced","winner_rank","winner_rank_points","loser_rank","loser_rank_points"]
def getPlayer(self, id):
player = Player.objects.filter(id=id)
if (not player):
return None
else:
player = player[0]
return player
def getSurface(self, name):
surface = Surface.objects.filter(name=name)
if (not surface):
surface = Surface()
surface.name = name
surface.created_at = datetime.datetime.now()
surface.updated_at = datetime.datetime.now()
surface.save()
else:
surface = surface[0]
return surface
def getTourneyLevel(self, code):
tourney_level = Tourney_Level.objects.filter(code=code)
if (not tourney_level):
tourney_level = Tourney_Level()
tourney_level.code = code
tourney_level.name = code
tourney_level.created_at = datetime.datetime.now()
tourney_level.updated_at = datetime.datetime.now()
tourney_level.save()
else:
tourney_level = tourney_level[0]
return tourney_level | [
"front.models.Tourney_Level.objects.filter",
"pandas.isnull",
"front.models.Match.objects.filter",
"front.models.Surface",
"front.models.Tourney_Level",
"datetime.datetime.now",
"front.models.Match_Stats.objects.filter",
"front.models.Player.objects.filter",
"django.db.connection.cursor",
"numpy.i... | [((299, 318), 'django.db.connection.cursor', 'connection.cursor', ([], {}), '()\n', (316, 318), False, 'from django.db import connection\n'), ((9006, 9034), 'front.models.Player.objects.filter', 'Player.objects.filter', ([], {'id': 'id'}), '(id=id)\n', (9027, 9034), False, 'from front.models import Match, Match_Stats, Player, Tourney, Tourney_Level, Surface\n'), ((9206, 9239), 'front.models.Surface.objects.filter', 'Surface.objects.filter', ([], {'name': 'name'}), '(name=name)\n', (9228, 9239), False, 'from front.models import Match, Match_Stats, Player, Tourney, Tourney_Level, Surface\n'), ((9611, 9650), 'front.models.Tourney_Level.objects.filter', 'Tourney_Level.objects.filter', ([], {'code': 'code'}), '(code=code)\n', (9639, 9650), False, 'from front.models import Match, Match_Stats, Player, Tourney, Tourney_Level, Surface\n'), ((9288, 9297), 'front.models.Surface', 'Surface', ([], {}), '()\n', (9295, 9297), False, 'from front.models import Match, Match_Stats, Player, Tourney, Tourney_Level, Surface\n'), ((9363, 9386), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (9384, 9386), False, 'import datetime\n'), ((9420, 9443), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (9441, 9443), False, 'import datetime\n'), ((9712, 9727), 'front.models.Tourney_Level', 'Tourney_Level', ([], {}), '()\n', (9725, 9727), False, 'from front.models import Match, Match_Stats, Player, Tourney, Tourney_Level, Surface\n'), ((9843, 9866), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (9864, 9866), False, 'import datetime\n'), ((9906, 9929), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (9927, 9929), False, 'import datetime\n'), ((797, 820), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (818, 820), False, 'import datetime\n'), ((854, 877), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (875, 877), False, 'import datetime\n'), ((1000, 1027), 'front.models.Match.objects.filter', 'Match.objects.filter', ([], {'id': 'id'}), '(id=id)\n', (1020, 1027), False, 'from front.models import Match, Match_Stats, Player, Tourney, Tourney_Level, Surface\n'), ((3823, 3868), 'front.models.Match_Stats.objects.filter', 'Match_Stats.objects.filter', ([], {'id': 'match_stats_id'}), '(id=match_stats_id)\n', (3849, 3868), False, 'from front.models import Match, Match_Stats, Player, Tourney, Tourney_Level, Surface\n'), ((6011, 6056), 'front.models.Match_Stats.objects.filter', 'Match_Stats.objects.filter', ([], {'id': 'match_stats_id'}), '(id=match_stats_id)\n', (6037, 6056), False, 'from front.models import Match, Match_Stats, Player, Tourney, Tourney_Level, Surface\n'), ((1097, 1104), 'front.models.Match', 'Match', ([], {}), '()\n', (1102, 1104), False, 'from front.models import Match, Match_Stats, Player, Tourney, Tourney_Level, Surface\n'), ((4132, 4145), 'front.models.Match_Stats', 'Match_Stats', ([], {}), '()\n', (4143, 4145), False, 'from front.models import Match, Match_Stats, Player, Tourney, Tourney_Level, Surface\n'), ((6317, 6330), 'front.models.Match_Stats', 'Match_Stats', ([], {}), '()\n', (6328, 6330), False, 'from front.models import Match, Match_Stats, Player, Tourney, Tourney_Level, Surface\n'), ((1414, 1435), 'numpy.isnan', 'np.isnan', (['row.minutes'], {}), '(row.minutes)\n', (1422, 1435), True, 'import numpy as np\n'), ((1650, 1691), 'front.models.Tourney.objects.filter', 'Tourney.objects.filter', ([], {'id': 'row.tourney_id'}), '(id=row.tourney_id)\n', (1672, 1691), False, 'from front.models import Match, Match_Stats, Player, Tourney, Tourney_Level, Surface\n'), ((3985, 4011), 'pandas.isnull', 'pd.isnull', (['row.winner_seed'], {}), '(row.winner_seed)\n', (3994, 4011), True, 'import pandas as pd\n'), ((4347, 4366), 'numpy.isnan', 'np.isnan', (['row.w_ace'], {}), '(row.w_ace)\n', (4355, 4366), True, 'import numpy as np\n'), ((4442, 4460), 'numpy.isnan', 'np.isnan', (['row.w_df'], {}), '(row.w_df)\n', (4450, 4460), True, 'import numpy as np\n'), ((4536, 4556), 'numpy.isnan', 'np.isnan', (['row.w_svpt'], {}), '(row.w_svpt)\n', (4544, 4556), True, 'import numpy as np\n'), ((4634, 4655), 'numpy.isnan', 'np.isnan', (['row.w_1stIn'], {}), '(row.w_1stIn)\n', (4642, 4655), True, 'import numpy as np\n'), ((4738, 4760), 'numpy.isnan', 'np.isnan', (['row.w_1stWon'], {}), '(row.w_1stWon)\n', (4746, 4760), True, 'import numpy as np\n'), ((4845, 4867), 'numpy.isnan', 'np.isnan', (['row.w_2ndWon'], {}), '(row.w_2ndWon)\n', (4853, 4867), True, 'import numpy as np\n'), ((4949, 4970), 'numpy.isnan', 'np.isnan', (['row.w_SvGms'], {}), '(row.w_SvGms)\n', (4957, 4970), True, 'import numpy as np\n'), ((5053, 5076), 'numpy.isnan', 'np.isnan', (['row.w_bpSaved'], {}), '(row.w_bpSaved)\n', (5061, 5076), True, 'import numpy as np\n'), ((5162, 5185), 'numpy.isnan', 'np.isnan', (['row.w_bpFaced'], {}), '(row.w_bpFaced)\n', (5170, 5185), True, 'import numpy as np\n'), ((5256, 5281), 'numpy.isnan', 'np.isnan', (['row.winner_rank'], {}), '(row.winner_rank)\n', (5264, 5281), True, 'import numpy as np\n'), ((5361, 5393), 'numpy.isnan', 'np.isnan', (['row.winner_rank_points'], {}), '(row.winner_rank_points)\n', (5369, 5393), True, 'import numpy as np\n'), ((6172, 6197), 'pandas.isnull', 'pd.isnull', (['row.loser_seed'], {}), '(row.loser_seed)\n', (6181, 6197), True, 'import pandas as pd\n'), ((6532, 6551), 'numpy.isnan', 'np.isnan', (['row.l_ace'], {}), '(row.l_ace)\n', (6540, 6551), True, 'import numpy as np\n'), ((6627, 6645), 'numpy.isnan', 'np.isnan', (['row.l_df'], {}), '(row.l_df)\n', (6635, 6645), True, 'import numpy as np\n'), ((6721, 6741), 'numpy.isnan', 'np.isnan', (['row.l_svpt'], {}), '(row.l_svpt)\n', (6729, 6741), True, 'import numpy as np\n'), ((6819, 6840), 'numpy.isnan', 'np.isnan', (['row.l_1stIn'], {}), '(row.l_1stIn)\n', (6827, 6840), True, 'import numpy as np\n'), ((6923, 6945), 'numpy.isnan', 'np.isnan', (['row.l_1stWon'], {}), '(row.l_1stWon)\n', (6931, 6945), True, 'import numpy as np\n'), ((7030, 7052), 'numpy.isnan', 'np.isnan', (['row.l_2ndWon'], {}), '(row.l_2ndWon)\n', (7038, 7052), True, 'import numpy as np\n'), ((7134, 7155), 'numpy.isnan', 'np.isnan', (['row.l_SvGms'], {}), '(row.l_SvGms)\n', (7142, 7155), True, 'import numpy as np\n'), ((7238, 7261), 'numpy.isnan', 'np.isnan', (['row.l_bpSaved'], {}), '(row.l_bpSaved)\n', (7246, 7261), True, 'import numpy as np\n'), ((7347, 7370), 'numpy.isnan', 'np.isnan', (['row.l_bpFaced'], {}), '(row.l_bpFaced)\n', (7355, 7370), True, 'import numpy as np\n'), ((7441, 7465), 'numpy.isnan', 'np.isnan', (['row.loser_rank'], {}), '(row.loser_rank)\n', (7449, 7465), True, 'import numpy as np\n'), ((7544, 7575), 'numpy.isnan', 'np.isnan', (['row.loser_rank_points'], {}), '(row.loser_rank_points)\n', (7552, 7575), True, 'import numpy as np\n'), ((1780, 1789), 'front.models.Tourney', 'Tourney', ([], {}), '()\n', (1787, 1789), False, 'from front.models import Match, Match_Stats, Player, Tourney, Tourney_Level, Surface\n')] |
import subprocess
import secrets
import getpass
import os
import requests
import urllib.parse
import time
from google.colab import files, drive, auth
from google.cloud import storage
import glob
def connect(LOG_DIR = '/log/fit'):
print('It may take a few seconds for processing. Please wait.')
root_password = secrets.token_urlsafe()
subprocess.call('apt-get update -qq', shell=True)
subprocess.call('apt-get install -qq -o=Dpkg::Use-Pty=0 openssh-server pwgen > /dev/null', shell=True)
subprocess.call(f'echo root:{root_password} | chpasswd', shell=True)
subprocess.call('mkdir -p /var/run/sshd', shell=True)
subprocess.call('echo "PermitRootLogin yes" >> /etc/ssh/sshd_config', shell=True)
subprocess.call('echo "PasswordAuthentication yes" >> /etc/ssh/sshd_config', shell=True)
get_ipython().system_raw('/usr/sbin/sshd -D &')
subprocess.call('mkdir -p /content/ngrok-ssh', shell=True)
os.chdir('/content/ngrok-ssh')
subprocess.call('wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip -O ngrok-stable-linux-amd64.zip', shell=True)
subprocess.call('unzip -u ngrok-stable-linux-amd64.zip', shell=True)
subprocess.call('cp /content/ngrok-ssh/ngrok /ngrok', shell=True)
subprocess.call('chmod +x /ngrok', shell=True)
print("Copy&paste your authtoken from https://dashboard.ngrok.com/auth")
authtoken = getpass.getpass()
get_ipython().system_raw(f'/ngrok authtoken {authtoken} &')
_create_tunnels()
get_ipython().system_raw(f'tensorboard --logdir {LOG_DIR} --host 0.0.0.0 --port 6006 &')
time.sleep(3) # synchronize.
with open('/content/ngrok-ssh/ngrok-tunnel-info.txt', 'w') as f:
url, port = urllib.parse.urlparse(_get_ngrok_url('ssh')).netloc.split(':')
# f.write('Run the command below on local machines to SSH into the Colab instance:\n')
f.write(f'ssh -p {port} root@{url}\n')
f.write('Password:\n')
f.write(f'{root_password}\n')
if 'COLAB_TPU_ADDR' in os.environ:
tpu_address = 'grpc://' + os.environ['COLAB_TPU_ADDR']
f.write(f"""Copy and paste the commands below to the beginning of your TPU program:
import tensorflow as tf
resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='{tpu_address}')
tf.config.experimental_connect_to_cluster(resolver)
tf.tpu.experimental.initialize_tpu_system(resolver)
strategy = tf.distribute.experimental.TPUStrategy(resolver)""")
url_tensorboard = _get_ngrok_url('tensorboard')
# f.write(f'To view tensorboard, visit {url_tensorboard}')
f.write(f'Tensorboard: {url_tensorboard}')
# f.write('after running the following two commands on the Colab notebook:\n')
# f.write(f' %load_ext tensorboard')
# f.write(f' %tensorboard --logdir {LOG_DIR}')
# f.write('Run kill() to close all the tunnels.\n')
# print('SSH connection is successfully established. Run info() for connection configuration.')
def info():
with open('/content/ngrok-ssh/ngrok-tunnel-info.txt', 'r') as f:
lines = f.readlines()
for line in lines:
print(line)
def kill():
os.system("kill $(ps aux | grep ngrok | awk '{print $2}')")
print('Done.')
def _create_tunnels():
with open('/content/ngrok-ssh/ssh.yml', 'w') as f:
f.write('tunnels:\n')
f.write(' ssh:\n')
f.write(' proto: tcp\n')
f.write(' addr: 22')
with open('/content/ngrok-ssh/tensorboard.yml', 'w') as f:
f.write('tunnels:\n')
f.write(' tensorboard:\n')
f.write(' proto: http\n')
f.write(' addr: 6006\n')
f.write(' inspect: false\n')
f.write(' bind_tls: true')
with open('/content/ngrok-ssh/http8080.yml', 'w') as f:
f.write('tunnels:\n')
f.write(' http8080:\n')
f.write(' proto: http\n')
f.write(' addr: 8080\n')
f.write(' inspect: false\n')
f.write(' bind_tls: true')
with open('/content/ngrok-ssh/tcp8080.yml', 'w') as f:
f.write('tunnels:\n')
f.write(' tcp8080:\n')
f.write(' proto: tcp\n')
f.write(' addr: 8080')
if 'COLAB_TPU_ADDR' in os.environ:
with open('/content/ngrok-ssh/tpu.yml', 'w') as f:
COLAB_TPU_ADDR = os.environ['COLAB_TPU_ADDR']
f.write('tunnels:\n')
f.write(' tpu:\n')
f.write(' proto: tcp\n')
f.write(f' addr: {COLAB_TPU_ADDR}')
with open('/content/ngrok-ssh/run_ngrok.sh', 'w') as f:
f.write('#!/bin/sh\n')
f.write('set -x\n')
if 'COLAB_TPU_ADDR' in os.environ:
f.write('/ngrok start --config ~/.ngrok2/ngrok.yml --config /content/ngrok-ssh/ssh.yml --log=stdout --config /content/ngrok-ssh/tensorboard.yml --config /content/ngrok-ssh/http8080.yml --config /content/ngrok-ssh/tcp8080.yml --config /content/ngrok-ssh/tpu.yml "$@"')
else:
f.write('/ngrok start --config ~/.ngrok2/ngrok.yml --config /content/ngrok-ssh/ssh.yml --log=stdout --config /content/ngrok-ssh/tensorboard.yml --config /content/ngrok-ssh/http8080.yml --config /content/ngrok-ssh/tcp8080.yml "$@"')
if 'COLAB_TPU_ADDR' in os.environ:
get_ipython().system_raw('bash /content/ngrok-ssh/run_ngrok.sh ssh tensorboard tcp8080 tpu &')
else:
get_ipython().system_raw('bash /content/ngrok-ssh/run_ngrok.sh ssh tensorboard tcp8080 &')
def _get_ngrok_info():
return requests.get('http://localhost:4040/api/tunnels').json()
def _get_ngrok_tunnels():
for tunnel in _get_ngrok_info()['tunnels']:
name = tunnel['name']
yield name, tunnel
def _get_ngrok_tunnel(name):
for name1, tunnel in _get_ngrok_tunnels():
if name == name1:
return tunnel
def _get_ngrok_url(name, local=False):
if local:
return _get_ngrok_tunnel(name)['config']['addr']
else:
return _get_ngrok_tunnel(name)['public_url']
def kaggle(data='tabular-playground-series-mar-2021', output='/kaggle/input'):
subprocess.call('sudo apt -q update', shell=True)
subprocess.call('sudo apt -q install unar nano less p7zip', shell=True)
subprocess.call('pip install -q --upgrade --force-reinstall --no-deps kaggle kaggle-cli', shell=True)
subprocess.call('mkdir -p /root/.kaggle', shell=True)
os.chdir('/root/.kaggle')
if 'kaggle.json' not in os.listdir('/root/.kaggle'):
print('Upload your kaggle API token')
files.upload()
subprocess.call('chmod 600 /root/.kaggle/kaggle.json', shell=True)
subprocess.call(f'mkdir -p {output}', shell=True)
os.chdir(f'{output}')
subprocess.call(f'kaggle competitions download -c {data}', shell=True)
subprocess.call(f'7z x {data}.zip -o{output}', shell=True)
print(f'\nUnzipped {data}.zip to {output}.')
subprocess.call('mkdir -p /kaggle/working', shell=True)
os.chdir('/kaggle/working')
def google_drive(dir='/gdrive'):
print(f'\nGoogle Drive authentication starts...')
drive.mount(dir)
def GCSconnect(key_file=None):
if key_file:
if not os.path.exists('/root/.kaggle/'):
os.makedirs('/root/.kaggle/')
print('Upload your Google Storage API token')
os.chdir('/root/.kaggle/')
files.upload()
subprocess.call(f'chmod 600 /root/.kaggle/{key_file}', shell=True)
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = f'/root/.kaggle/{key_file}'
subprocess.call('echo $GOOGLE_APPLICATION_CREDENTIALS', shell=True)
else:
print('\nGCS authentication starts...')
auth.authenticate_user()
def _create_bucket(project, bucket_name):
storage_client = storage.Client(project=project)
bucket = storage_client.bucket(bucket_name)
bucket.create(location='US')
print(f'bucket {bucket.name} created.')
def _list_blobs(project, bucket_name):
storage_client = storage.Client(project=project)
blobs = storage_client.list_blobs(bucket_name)
blist = []
for blob in blobs:
blist.append(blob.name)
if not len(blist):
print('empty bucket!')
else:
print('\n'.join(blist))
def create_bucket(project, bucket_name):
try:
_create_bucket(project, bucket_name)
except Exception as e:
print(f"create_bucket('{bucket_name}') fails. Code:", e)
def list_blobs(project, bucket_name):
try:
_list_blobs(project, bucket_name)
except Exception as e:
print(f"list_blobs('{bucket_name}') fails. Code:", e)
def upload_to_gcs(project, bucket_name, destination_blob, source_directory):
# Upload file(s) from Google Colaboratory to GCS Bucket.
# type: {string} project name
# {string} bucket name
# {string} source directory
# rtype: None
# usage:
# upload_to_gcs("strategic-howl-123", "gcs-station-16", 'temp8/a.pkl', '/a.pkl')
# note: DON'T put a leading slash in the third argument.
storage_client = storage.Client(project=project)
bucket = storage_client.get_bucket(bucket_name)
# paths = glob.glob(os.path.join(source_directory, file if file else f'*.{ext}'))
# for path in paths:
# filename = os.path.join(source_directory, file) if file else path.split('/')[-1]
# blob = bucket.blob(filename)
# blob.upload_from_filename(path)
# print(f'{path} uploaded to {os.path.join(bucket_name, filename)}')
blob = bucket.blob(destination_blob)
blob.upload_from_filename(source_directory)
def download_to_colab(project, bucket_name, destination_directory, remote_blob_path='', local_file_name=''):
# Download file(s) from Google Cloud Storage Bucket to Colaboratory.
# type: {string} project name
# {string} bucket name
# {string} destination directory
# {string} (optional) filename: If set, the target file is downloaded.
# rtype: None
# usage:
# project = "strategic-howl-123456522"
# bucket_name = "gcs-station-168"
# >>> download_to_colab(project, bucket_name, '/temp8')
# >>> download_to_colab(project, bucket_name, destination_directory = '/temp9/fun', remote_blob_path='tps-apr-2021-label/data_fare_age.pkl', local_file_name='data_fare_age.pkl')
storage_client = storage.Client(project=project)
os.makedirs(destination_directory, exist_ok = True)
if local_file_name and remote_blob_path:
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(remote_blob_path)
blob.download_to_filename(os.path.join(destination_directory, local_file_name))
print('download finished.')
else:
from pathlib import Path
os.chdir(destination_directory)
blobs = storage_client.list_blobs(bucket_name)
count = 1
for blob in blobs:
if blob.name.endswith("/"): continue #
file_split = blob.name.split("/")
directory = "/".join(file_split[0:-1])
Path(directory).mkdir(parents=True, exist_ok=True) # (2)
blob.download_to_filename(blob.name)
des = os.path.join(destination_directory, directory)
if count==1: print(f"Destination: {des}")
print(f'{count}. {blob.name.split("/")[-1]:>50s}')
count += 1
| [
"google.cloud.storage.Client",
"os.path.exists",
"os.listdir",
"os.makedirs",
"google.colab.drive.mount",
"pathlib.Path",
"secrets.token_urlsafe",
"google.colab.files.upload",
"time.sleep",
"getpass.getpass",
"os.chdir",
"google.colab.auth.authenticate_user",
"requests.get",
"os.path.join"... | [((319, 342), 'secrets.token_urlsafe', 'secrets.token_urlsafe', ([], {}), '()\n', (340, 342), False, 'import secrets\n'), ((347, 396), 'subprocess.call', 'subprocess.call', (['"""apt-get update -qq"""'], {'shell': '(True)'}), "('apt-get update -qq', shell=True)\n", (362, 396), False, 'import subprocess\n'), ((401, 512), 'subprocess.call', 'subprocess.call', (['"""apt-get install -qq -o=Dpkg::Use-Pty=0 openssh-server pwgen > /dev/null"""'], {'shell': '(True)'}), "(\n 'apt-get install -qq -o=Dpkg::Use-Pty=0 openssh-server pwgen > /dev/null',\n shell=True)\n", (416, 512), False, 'import subprocess\n'), ((508, 576), 'subprocess.call', 'subprocess.call', (['f"""echo root:{root_password} | chpasswd"""'], {'shell': '(True)'}), "(f'echo root:{root_password} | chpasswd', shell=True)\n", (523, 576), False, 'import subprocess\n'), ((581, 634), 'subprocess.call', 'subprocess.call', (['"""mkdir -p /var/run/sshd"""'], {'shell': '(True)'}), "('mkdir -p /var/run/sshd', shell=True)\n", (596, 634), False, 'import subprocess\n'), ((639, 725), 'subprocess.call', 'subprocess.call', (['"""echo "PermitRootLogin yes" >> /etc/ssh/sshd_config"""'], {'shell': '(True)'}), '(\'echo "PermitRootLogin yes" >> /etc/ssh/sshd_config\', shell\n =True)\n', (654, 725), False, 'import subprocess\n'), ((725, 817), 'subprocess.call', 'subprocess.call', (['"""echo "PasswordAuthentication yes" >> /etc/ssh/sshd_config"""'], {'shell': '(True)'}), '(\'echo "PasswordAuthentication yes" >> /etc/ssh/sshd_config\',\n shell=True)\n', (740, 817), False, 'import subprocess\n'), ((875, 933), 'subprocess.call', 'subprocess.call', (['"""mkdir -p /content/ngrok-ssh"""'], {'shell': '(True)'}), "('mkdir -p /content/ngrok-ssh', shell=True)\n", (890, 933), False, 'import subprocess\n'), ((938, 968), 'os.chdir', 'os.chdir', (['"""/content/ngrok-ssh"""'], {}), "('/content/ngrok-ssh')\n", (946, 968), False, 'import os\n'), ((973, 1116), 'subprocess.call', 'subprocess.call', (['"""wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip -O ngrok-stable-linux-amd64.zip"""'], {'shell': '(True)'}), "(\n 'wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip -O ngrok-stable-linux-amd64.zip'\n , shell=True)\n", (988, 1116), False, 'import subprocess\n'), ((1111, 1179), 'subprocess.call', 'subprocess.call', (['"""unzip -u ngrok-stable-linux-amd64.zip"""'], {'shell': '(True)'}), "('unzip -u ngrok-stable-linux-amd64.zip', shell=True)\n", (1126, 1179), False, 'import subprocess\n'), ((1184, 1249), 'subprocess.call', 'subprocess.call', (['"""cp /content/ngrok-ssh/ngrok /ngrok"""'], {'shell': '(True)'}), "('cp /content/ngrok-ssh/ngrok /ngrok', shell=True)\n", (1199, 1249), False, 'import subprocess\n'), ((1254, 1300), 'subprocess.call', 'subprocess.call', (['"""chmod +x /ngrok"""'], {'shell': '(True)'}), "('chmod +x /ngrok', shell=True)\n", (1269, 1300), False, 'import subprocess\n'), ((1394, 1411), 'getpass.getpass', 'getpass.getpass', ([], {}), '()\n', (1409, 1411), False, 'import getpass\n'), ((1600, 1613), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (1610, 1613), False, 'import time\n'), ((3197, 3256), 'os.system', 'os.system', (['"""kill $(ps aux | grep ngrok | awk \'{print $2}\')"""'], {}), '("kill $(ps aux | grep ngrok | awk \'{print $2}\')")\n', (3206, 3256), False, 'import os\n'), ((6126, 6175), 'subprocess.call', 'subprocess.call', (['"""sudo apt -q update"""'], {'shell': '(True)'}), "('sudo apt -q update', shell=True)\n", (6141, 6175), False, 'import subprocess\n'), ((6180, 6251), 'subprocess.call', 'subprocess.call', (['"""sudo apt -q install unar nano less p7zip"""'], {'shell': '(True)'}), "('sudo apt -q install unar nano less p7zip', shell=True)\n", (6195, 6251), False, 'import subprocess\n'), ((6256, 6366), 'subprocess.call', 'subprocess.call', (['"""pip install -q --upgrade --force-reinstall --no-deps kaggle kaggle-cli"""'], {'shell': '(True)'}), "(\n 'pip install -q --upgrade --force-reinstall --no-deps kaggle kaggle-cli',\n shell=True)\n", (6271, 6366), False, 'import subprocess\n'), ((6362, 6415), 'subprocess.call', 'subprocess.call', (['"""mkdir -p /root/.kaggle"""'], {'shell': '(True)'}), "('mkdir -p /root/.kaggle', shell=True)\n", (6377, 6415), False, 'import subprocess\n'), ((6420, 6445), 'os.chdir', 'os.chdir', (['"""/root/.kaggle"""'], {}), "('/root/.kaggle')\n", (6428, 6445), False, 'import os\n'), ((6651, 6700), 'subprocess.call', 'subprocess.call', (['f"""mkdir -p {output}"""'], {'shell': '(True)'}), "(f'mkdir -p {output}', shell=True)\n", (6666, 6700), False, 'import subprocess\n'), ((6705, 6726), 'os.chdir', 'os.chdir', (['f"""{output}"""'], {}), "(f'{output}')\n", (6713, 6726), False, 'import os\n'), ((6731, 6801), 'subprocess.call', 'subprocess.call', (['f"""kaggle competitions download -c {data}"""'], {'shell': '(True)'}), "(f'kaggle competitions download -c {data}', shell=True)\n", (6746, 6801), False, 'import subprocess\n'), ((6806, 6864), 'subprocess.call', 'subprocess.call', (['f"""7z x {data}.zip -o{output}"""'], {'shell': '(True)'}), "(f'7z x {data}.zip -o{output}', shell=True)\n", (6821, 6864), False, 'import subprocess\n'), ((6918, 6973), 'subprocess.call', 'subprocess.call', (['"""mkdir -p /kaggle/working"""'], {'shell': '(True)'}), "('mkdir -p /kaggle/working', shell=True)\n", (6933, 6973), False, 'import subprocess\n'), ((6978, 7005), 'os.chdir', 'os.chdir', (['"""/kaggle/working"""'], {}), "('/kaggle/working')\n", (6986, 7005), False, 'import os\n'), ((7098, 7114), 'google.colab.drive.mount', 'drive.mount', (['dir'], {}), '(dir)\n', (7109, 7114), False, 'from google.colab import files, drive, auth\n'), ((7773, 7804), 'google.cloud.storage.Client', 'storage.Client', ([], {'project': 'project'}), '(project=project)\n', (7787, 7804), False, 'from google.cloud import storage\n'), ((7991, 8022), 'google.cloud.storage.Client', 'storage.Client', ([], {'project': 'project'}), '(project=project)\n', (8005, 8022), False, 'from google.cloud import storage\n'), ((9021, 9052), 'google.cloud.storage.Client', 'storage.Client', ([], {'project': 'project'}), '(project=project)\n', (9035, 9052), False, 'from google.cloud import storage\n'), ((10272, 10303), 'google.cloud.storage.Client', 'storage.Client', ([], {'project': 'project'}), '(project=project)\n', (10286, 10303), False, 'from google.cloud import storage\n'), ((10308, 10357), 'os.makedirs', 'os.makedirs', (['destination_directory'], {'exist_ok': '(True)'}), '(destination_directory, exist_ok=True)\n', (10319, 10357), False, 'import os\n'), ((6474, 6501), 'os.listdir', 'os.listdir', (['"""/root/.kaggle"""'], {}), "('/root/.kaggle')\n", (6484, 6501), False, 'import os\n'), ((6557, 6571), 'google.colab.files.upload', 'files.upload', ([], {}), '()\n', (6569, 6571), False, 'from google.colab import files, drive, auth\n'), ((6580, 6646), 'subprocess.call', 'subprocess.call', (['"""chmod 600 /root/.kaggle/kaggle.json"""'], {'shell': '(True)'}), "('chmod 600 /root/.kaggle/kaggle.json', shell=True)\n", (6595, 6646), False, 'import subprocess\n'), ((7325, 7351), 'os.chdir', 'os.chdir', (['"""/root/.kaggle/"""'], {}), "('/root/.kaggle/')\n", (7333, 7351), False, 'import os\n'), ((7360, 7374), 'google.colab.files.upload', 'files.upload', ([], {}), '()\n', (7372, 7374), False, 'from google.colab import files, drive, auth\n'), ((7383, 7449), 'subprocess.call', 'subprocess.call', (['f"""chmod 600 /root/.kaggle/{key_file}"""'], {'shell': '(True)'}), "(f'chmod 600 /root/.kaggle/{key_file}', shell=True)\n", (7398, 7449), False, 'import subprocess\n'), ((7550, 7617), 'subprocess.call', 'subprocess.call', (['"""echo $GOOGLE_APPLICATION_CREDENTIALS"""'], {'shell': '(True)'}), "('echo $GOOGLE_APPLICATION_CREDENTIALS', shell=True)\n", (7565, 7617), False, 'import subprocess\n'), ((7684, 7708), 'google.colab.auth.authenticate_user', 'auth.authenticate_user', ([], {}), '()\n', (7706, 7708), False, 'from google.colab import files, drive, auth\n'), ((10677, 10708), 'os.chdir', 'os.chdir', (['destination_directory'], {}), '(destination_directory)\n', (10685, 10708), False, 'import os\n'), ((5530, 5579), 'requests.get', 'requests.get', (['"""http://localhost:4040/api/tunnels"""'], {}), "('http://localhost:4040/api/tunnels')\n", (5542, 5579), False, 'import requests\n'), ((7179, 7211), 'os.path.exists', 'os.path.exists', (['"""/root/.kaggle/"""'], {}), "('/root/.kaggle/')\n", (7193, 7211), False, 'import os\n'), ((7225, 7254), 'os.makedirs', 'os.makedirs', (['"""/root/.kaggle/"""'], {}), "('/root/.kaggle/')\n", (7236, 7254), False, 'import os\n'), ((10536, 10588), 'os.path.join', 'os.path.join', (['destination_directory', 'local_file_name'], {}), '(destination_directory, local_file_name)\n', (10548, 10588), False, 'import os\n'), ((11095, 11141), 'os.path.join', 'os.path.join', (['destination_directory', 'directory'], {}), '(destination_directory, directory)\n', (11107, 11141), False, 'import os\n'), ((10970, 10985), 'pathlib.Path', 'Path', (['directory'], {}), '(directory)\n', (10974, 10985), False, 'from pathlib import Path\n')] |
# -*- coding: utf-8 -*-
import pymysql
import json
def countNum(table):
# 打开数据库连接
db = pymysql.connect("cd-cdb-6sbfm2hw.sql.tencentcdb.com", "root", "Mrsnow@0", "spider")
# 使用cursor()方法创建一个可以执行SQL语句的游标对象cursor
cursor = db.cursor()
sql = "SELECT COUNT(*) FROM" + table + "WHERE text like '%川大%'"
cursor.execute(sql)
number_row = cursor.fetchone()[0] # number_row是指定表中包含关键词的记录总条数
# 关闭数据库连接
db.close()
return number_row
if __name__ == "__main__":
numList = []
# 根据数据库中数据返回一串结果到本地,以json格式返回给echarts图表
for day in ["date20200606","date20200607","date20200608","date20200609","date20200610","date20200611","date20200612"]:
numList.append(countNum(day))
print(numList)
# json.dumps(numList)
| [
"pymysql.connect"
] | [((97, 184), 'pymysql.connect', 'pymysql.connect', (['"""cd-cdb-6sbfm2hw.sql.tencentcdb.com"""', '"""root"""', '"""Mrsnow@0"""', '"""spider"""'], {}), "('cd-cdb-6sbfm2hw.sql.tencentcdb.com', 'root', 'Mrsnow@0',\n 'spider')\n", (112, 184), False, 'import pymysql\n')] |
import pytest
import sys
import ray
from ray._private.test_utils import wait_for_condition
def test_list_named_actors_basic(ray_start_regular):
@ray.remote
class A:
pass
a = A.remote()
assert not ray.util.list_named_actors()
a = A.options(name="hi").remote()
assert len(ray.util.list_named_actors()) == 1
assert "hi" in ray.util.list_named_actors()
b = A.options(name="hi2").remote()
assert len(ray.util.list_named_actors()) == 2
assert "hi" in ray.util.list_named_actors()
assert "hi2" in ray.util.list_named_actors()
def one_actor():
actors = ray.util.list_named_actors()
return actors == ["hi2"]
del a
wait_for_condition(one_actor)
del b
wait_for_condition(lambda: not ray.util.list_named_actors())
@pytest.mark.parametrize("ray_start_regular", [{"local_mode": True}], indirect=True)
def test_list_named_actors_basic_local_mode(ray_start_regular):
@ray.remote
class A:
pass
a = A.remote()
assert not ray.util.list_named_actors()
a = A.options(name="hi").remote() # noqa: F841
assert len(ray.util.list_named_actors()) == 1
assert "hi" in ray.util.list_named_actors()
b = A.options(name="hi2").remote() # noqa: F841
assert len(ray.util.list_named_actors()) == 2
assert "hi" in ray.util.list_named_actors()
assert "hi2" in ray.util.list_named_actors()
if __name__ == "__main__":
import os
# Test suite is timing out. Disable on windows for now.
if os.environ.get("PARALLEL_CI"):
sys.exit(pytest.main(["-n", "auto", "--boxed", "-vs", __file__]))
else:
sys.exit(pytest.main(["-sv", __file__]))
| [
"os.environ.get",
"ray.util.list_named_actors",
"pytest.main",
"pytest.mark.parametrize",
"ray._private.test_utils.wait_for_condition"
] | [((802, 889), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ray_start_regular"""', "[{'local_mode': True}]"], {'indirect': '(True)'}), "('ray_start_regular', [{'local_mode': True}],\n indirect=True)\n", (825, 889), False, 'import pytest\n'), ((693, 722), 'ray._private.test_utils.wait_for_condition', 'wait_for_condition', (['one_actor'], {}), '(one_actor)\n', (711, 722), False, 'from ray._private.test_utils import wait_for_condition\n'), ((1519, 1548), 'os.environ.get', 'os.environ.get', (['"""PARALLEL_CI"""'], {}), "('PARALLEL_CI')\n", (1533, 1548), False, 'import os\n'), ((224, 252), 'ray.util.list_named_actors', 'ray.util.list_named_actors', ([], {}), '()\n', (250, 252), False, 'import ray\n'), ((361, 389), 'ray.util.list_named_actors', 'ray.util.list_named_actors', ([], {}), '()\n', (387, 389), False, 'import ray\n'), ((499, 527), 'ray.util.list_named_actors', 'ray.util.list_named_actors', ([], {}), '()\n', (525, 527), False, 'import ray\n'), ((548, 576), 'ray.util.list_named_actors', 'ray.util.list_named_actors', ([], {}), '()\n', (574, 576), False, 'import ray\n'), ((616, 644), 'ray.util.list_named_actors', 'ray.util.list_named_actors', ([], {}), '()\n', (642, 644), False, 'import ray\n'), ((1027, 1055), 'ray.util.list_named_actors', 'ray.util.list_named_actors', ([], {}), '()\n', (1053, 1055), False, 'import ray\n'), ((1178, 1206), 'ray.util.list_named_actors', 'ray.util.list_named_actors', ([], {}), '()\n', (1204, 1206), False, 'import ray\n'), ((1330, 1358), 'ray.util.list_named_actors', 'ray.util.list_named_actors', ([], {}), '()\n', (1356, 1358), False, 'import ray\n'), ((1379, 1407), 'ray.util.list_named_actors', 'ray.util.list_named_actors', ([], {}), '()\n', (1405, 1407), False, 'import ray\n'), ((307, 335), 'ray.util.list_named_actors', 'ray.util.list_named_actors', ([], {}), '()\n', (333, 335), False, 'import ray\n'), ((445, 473), 'ray.util.list_named_actors', 'ray.util.list_named_actors', ([], {}), '()\n', (471, 473), False, 'import ray\n'), ((1124, 1152), 'ray.util.list_named_actors', 'ray.util.list_named_actors', ([], {}), '()\n', (1150, 1152), False, 'import ray\n'), ((1276, 1304), 'ray.util.list_named_actors', 'ray.util.list_named_actors', ([], {}), '()\n', (1302, 1304), False, 'import ray\n'), ((1567, 1622), 'pytest.main', 'pytest.main', (["['-n', 'auto', '--boxed', '-vs', __file__]"], {}), "(['-n', 'auto', '--boxed', '-vs', __file__])\n", (1578, 1622), False, 'import pytest\n'), ((1651, 1681), 'pytest.main', 'pytest.main', (["['-sv', __file__]"], {}), "(['-sv', __file__])\n", (1662, 1681), False, 'import pytest\n'), ((769, 797), 'ray.util.list_named_actors', 'ray.util.list_named_actors', ([], {}), '()\n', (795, 797), False, 'import ray\n')] |
"""Main/example start-up script for the pyjobserver
Use this as a guide if importing pyjobserver into another app instead
"""
# Built-Ins:
import asyncio
from logging import getLogger, Logger
import os
from pathlib import Path
# External Dependencies:
from aiohttp import web
import click
from dotenv import load_dotenv
# Local Dependencies:
from .access_control import get_authentication_middleware
from .config import load as load_config, Config
from .jobs.example import example_job_fn
from .runner import JobRunner
# (Only entry point scripts should load dotenvs)
load_dotenv(os.getcwd() + "/.env")
async def alive_handler(request) -> web.Response:
"""Basic server aliveness indicator
"""
return web.json_response({"ok": True})
async def init_app(config: Config, LOGGER: Logger):
"""Create an application instance.
:return: application instance
"""
app = web.Application(logger=LOGGER)
app.router.add_get("/", alive_handler)
authentication_middleware = get_authentication_middleware(config)
runner = JobRunner(config)
# ADD YOUR JOB TYPES LIKE THIS:
# The job function must be conformant including the correct signature type annotations.
runner.register_job_handler("example", example_job_fn)
runner_app = await runner.webapp(middlewares=[authentication_middleware] if authentication_middleware else None)
app.add_subapp("/api", runner_app)
return app
# Note we need to separate out the main_coro from main() because click (our command line args processor) can't decorate
# async functions
async def main_coro(manifest: str):
"""Initialise and serve application.
Function is called when the module is run directly
"""
config = await load_config(Path(manifest) if manifest else None)
LOGGER = getLogger(__name__)
app = await init_app(config, LOGGER)
runner = web.AppRunner(app, handle_signals=True)
await runner.setup()
site = web.TCPSite(runner, port=config.server.port)
await site.start()
LOGGER.info("Server running on port %i", config.server.port)
# TODO: Are we supposed to expose the runner somehow to clean up on shutdown?
#await runner.cleanup()
@click.command()
@click.option("--manifest", default="", help="Location of (optional) manifest file relative to current working dir")
def main(manifest: str):
loop = asyncio.get_event_loop()
loop.run_until_complete(main_coro(manifest))
loop.run_forever()
if __name__ == "__main__":
# Linter error here is caused by PyLint not understanding the click decorator:
main() # pylint: disable=no-value-for-parameter
| [
"logging.getLogger",
"pathlib.Path",
"click.option",
"asyncio.get_event_loop",
"aiohttp.web.Application",
"aiohttp.web.AppRunner",
"os.getcwd",
"aiohttp.web.TCPSite",
"aiohttp.web.json_response",
"click.command"
] | [((2190, 2205), 'click.command', 'click.command', ([], {}), '()\n', (2203, 2205), False, 'import click\n'), ((2207, 2327), 'click.option', 'click.option', (['"""--manifest"""'], {'default': '""""""', 'help': '"""Location of (optional) manifest file relative to current working dir"""'}), "('--manifest', default='', help=\n 'Location of (optional) manifest file relative to current working dir')\n", (2219, 2327), False, 'import click\n'), ((719, 750), 'aiohttp.web.json_response', 'web.json_response', (["{'ok': True}"], {}), "({'ok': True})\n", (736, 750), False, 'from aiohttp import web\n'), ((896, 926), 'aiohttp.web.Application', 'web.Application', ([], {'logger': 'LOGGER'}), '(logger=LOGGER)\n', (911, 926), False, 'from aiohttp import web\n'), ((1794, 1813), 'logging.getLogger', 'getLogger', (['__name__'], {}), '(__name__)\n', (1803, 1813), False, 'from logging import getLogger, Logger\n'), ((1868, 1907), 'aiohttp.web.AppRunner', 'web.AppRunner', (['app'], {'handle_signals': '(True)'}), '(app, handle_signals=True)\n', (1881, 1907), False, 'from aiohttp import web\n'), ((1944, 1988), 'aiohttp.web.TCPSite', 'web.TCPSite', (['runner'], {'port': 'config.server.port'}), '(runner, port=config.server.port)\n', (1955, 1988), False, 'from aiohttp import web\n'), ((2359, 2383), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (2381, 2383), False, 'import asyncio\n'), ((585, 596), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (594, 596), False, 'import os\n'), ((1743, 1757), 'pathlib.Path', 'Path', (['manifest'], {}), '(manifest)\n', (1747, 1757), False, 'from pathlib import Path\n')] |
""" Provide function to load a wasm module into the current process.
Note that for this to work, we require compiled wasm code and a runtime.
The wasm runtime contains the following:
- Implement function like sqrt, floor, bit rotations etc..
"""
import os
import abc
import shelve
import io
import struct
import logging
from types import ModuleType
from ..arch.arch_info import TypeInfo
from ..utils.codepage import load_obj, MemoryPage
from ..utils.reporting import DummyReportGenerator
from ..irutils import verify_module
from .. import ir
from . import wasm_to_ir
from .components import Export, Import
from .wasm2ppci import create_memories
from .util import PAGE_SIZE
from .runtime import create_runtime
__all__ = ('instantiate',)
logger = logging.getLogger('instantiate')
def instantiate(module, imports, target='native', reporter=None,
cache_file=None):
""" Instantiate a wasm module.
Args:
module (ppci.wasm.Module): The wasm-module to instantiate
imports: A collection of functions available to the wasm module.
target: Use 'native' to compile wasm to machine code.
Use 'python' to generate python code. This option is slower
but more reliable.
reporter: A reporter which can record detailed compilation information.
cache_file: a file to use as cache
"""
if reporter is None:
reporter = DummyReportGenerator()
reporter.heading(2, 'Wasm instantiation')
# Check if all required imports are given:
for definition in module:
if isinstance(definition, Import):
modname, name = definition.modname, definition.name
if modname not in imports:
raise ValueError(
'imported module "{}" not found'.format(modname))
if name not in imports[modname]:
raise ValueError(
'imported object "{}" not found in "{}"'.format(
name, modname))
# Inject wasm runtime functions:
if 'wasm_rt' in imports:
raise ValueError('wasm_rt is a special import section')
imports = imports.copy() # otherwise we'd render the imports unsuable
imports['wasm_rt'] = create_runtime()
imports = flatten_imports(imports)
if target == 'native':
instance = native_instantiate(module, imports, reporter, cache_file)
elif target == 'python':
instance = python_instantiate(module, imports, reporter, cache_file)
else:
raise ValueError('Unknown instantiation target {}'.format(target))
# Call magic function _run_init which initializes tables and optionally
# calls start function as defined by the wasm start section.
instance._run_init()
return instance
def native_instantiate(module, imports, reporter, cache_file):
""" Load wasm module native """
from ..api import ir_to_object, get_current_arch
logger.info('Instantiating wasm module as native code')
arch = get_current_arch()
key = (arch, module)
# TODO: think of clever caching trickery:
cache_file = None
if cache_file and os.path.exists(cache_file):
logger.info('Using cached object from %s', cache_file)
with shelve.open(cache_file) as s:
obj = s['obj']
ppci_module = s['ppci_module']
else:
# TODO: use cache here to short circuit re-compilation
# hash(key)
# print(hash(key))
# hgkfdg
ppci_module = wasm_to_ir(
module, arch.info.get_type_info('ptr'), reporter=reporter)
verify_module(ppci_module)
obj = ir_to_object([ppci_module], arch, debug=True, reporter=reporter)
if cache_file:
logger.info('Saving object to %s for later use', cache_file)
with shelve.open(cache_file) as s:
s['obj'] = obj
s['ppci_module'] = ppci_module
instance = NativeModuleInstance(obj, imports)
instance.load_memory(module)
# Export all exported functions
for definition in module:
if isinstance(definition, Export):
if definition.kind == 'func':
exported_name = ppci_module._wasm_function_names[definition.ref.index]
instance.exports._function_map[definition.name] = \
getattr(instance._code_module, exported_name)
elif definition.kind == 'global':
global_name = ppci_module._wasm_globals[definition.ref.index]
instance.exports._function_map[definition.name] = \
NativeWasmGlobal(global_name, instance._code_module)
logger.debug('global exported')
elif definition.kind == 'memory':
memory = instance._memories[definition.ref.index]
instance.exports._function_map[definition.name] = memory
logger.debug('memory exported')
else:
raise NotImplementedError(definition.kind)
return instance
def python_instantiate(module, imports, reporter, cache_file):
""" Load wasm module as a PythonModuleInstance """
from ..api import ir_to_python
logger.info('Instantiating wasm module as python')
ptr_info = TypeInfo(4, 4)
ppci_module = wasm_to_ir(module, ptr_info, reporter=reporter)
verify_module(ppci_module)
f = io.StringIO()
ir_to_python([ppci_module], f, reporter=reporter)
pysrc = f.getvalue()
pycode = compile(pysrc, '<string>', 'exec')
_py_module = ModuleType('gen')
exec(pycode, _py_module.__dict__)
instance = PythonModuleInstance(_py_module, imports)
# Initialize memory:
instance.load_memory(module)
# Export all exported functions
for definition in module:
if isinstance(definition, Import):
pass
# TODO: maybe validate imported functions?
elif isinstance(definition, Export):
if definition.kind == 'func':
exported_name = ppci_module._wasm_function_names[definition.ref.index]
instance.exports._function_map[definition.name] = \
getattr(instance._py_module, exported_name)
elif definition.kind == 'global':
global_name = ppci_module._wasm_globals[definition.ref.index]
instance.exports._function_map[definition.name] = \
PythonWasmGlobal(global_name, instance)
logger.debug('global exported')
elif definition.kind == 'memory':
memory = instance._memories[definition.ref.index]
instance.exports._function_map[definition.name] = memory
logger.debug('memory exported')
else:
raise NotImplementedError(definition.kind)
return instance
def flatten_imports(imports):
""" Go from a two level dict to a single level dict """
flat_imports = {}
for mod_name, funcs in imports.items():
for func_name, func in funcs.items():
flat_imports['{}_{}'.format(mod_name, func_name)] = func
return flat_imports
class ModuleInstance:
""" Web assembly module instance """
""" Instantiated module """
def __init__(self):
self.exports = Exports()
self._memories = []
def memory_size(self) -> int:
""" return memory size in pages """
# TODO: idea is to have multiple memories and query the memory:
memory_index = 0
memory = self._memories[memory_index]
return memory.memory_size()
class NativeModuleInstance(ModuleInstance):
""" Wasm module loaded as natively compiled code """
def __init__(self, obj, imports):
super().__init__()
imports['wasm_rt_memory_grow'] = self.memory_grow
imports['wasm_rt_memory_size'] = self.memory_size
self._code_module = load_obj(obj, imports=imports)
def _run_init(self):
self._code_module._run_init()
def memory_size(self) -> int:
""" return memory size in pages """
return self._data_page.size // PAGE_SIZE
def memory_grow(self, amount: int) -> int:
""" Grow memory and return the old size.
Current strategy:
- claim new memory
- copy all data
- free old memory
- update wasm memory base pointer
"""
max_size = self._memories[0].max_size
old_size = self.memory_size()
new_size = old_size + amount
# Keep memory within sensible bounds:
if new_size >= 0x10000:
return -1
if max_size is not None and new_size > max_size:
return -1
# Read old data:
self._data_page.seek(0)
old_data = self._data_page.read()
# Create new page and fill with old data:
self._data_page = MemoryPage(new_size * PAGE_SIZE)
self._data_page.write(old_data)
# Update pointer:
self.set_mem_base_ptr(self._data_page.addr)
return old_size
def load_memory(self, module):
memories = create_memories(module)
if memories:
assert len(memories) == 1
memory, min_size, max_size = memories[0]
self._data_page = MemoryPage(len(memory))
self._data_page.write(memory)
mem0 = NativeWasmMemory(min_size, max_size)
# mem0._data_page = self._data_page
mem0._instance = self
self._memories.append(mem0)
base_addr = self._data_page.addr
self.set_mem_base_ptr(base_addr)
def set_mem_base_ptr(self, base_addr):
""" Set memory base address """
baseptr = self._code_module.get_symbol_offset('wasm_mem0_address')
print(baseptr)
# TODO: major hack:
# TODO: too many assumptions made here ...
self._code_module._data_page.seek(baseptr)
self._code_module._data_page.write(struct.pack('Q', base_addr))
class WasmGlobal(metaclass=abc.ABCMeta):
def __init__(self, name):
self.name = name
@abc.abstractmethod
def read(self):
raise NotImplementedError()
@abc.abstractmethod
def write(self, value):
raise NotImplementedError()
# TODO: we might implement the descriptor protocol in some way?
class PythonWasmGlobal(WasmGlobal):
def __init__(self, name, memory):
super().__init__(name)
self.instance = memory
def _get_ptr(self):
addr = getattr(self.instance._py_module, self.name[1].name)
return addr
def read(self):
addr = self._get_ptr()
# print('Reading', self.name, addr)
mp = {
ir.i32: self.instance._py_module.load_i32,
ir.i64: self.instance._py_module.load_i64,
}
f = mp[self.name[0]]
return f(addr)
def write(self, value):
addr = self._get_ptr()
# print('Writing', self.name, addr)
mp = {
ir.i32: self.instance._py_module.write_i32,
ir.i64: self.instance._py_module.write_i64,
}
f = mp[self.name[0]]
f(addr, value)
class NativeWasmGlobal(WasmGlobal):
def __init__(self, name, memory):
super().__init__(name)
self._code_obj = memory
def _get_ptr(self):
# print('Getting address of', self.name)
vpointer = getattr(self._code_obj, self.name[1].name)
return vpointer
def read(self):
addr = self._get_ptr()
# print('Reading', self.name, addr)
value = addr.contents.value
return value
def write(self, value):
addr = self._get_ptr()
# print('Writing', self.name, addr, value)
addr.contents.value = value
class WasmMemory(metaclass=abc.ABCMeta):
def __init__(self, min_size, max_size):
self.min_size = min_size
self.max_size = max_size
def __setitem__(self, location, data):
assert isinstance(location, slice)
assert location.step is None
if location.start is None:
address = location.stop
size = 1
else:
address = location.start
size = location.stop - location.start
assert len(data) == size
self.write(address, data)
def __getitem__(self, location):
assert isinstance(location, slice)
assert location.step is None
if location.start is None:
address = location.stop
size = 1
else:
address = location.start
size = location.stop - location.start
data = self.read(address, size)
assert len(data) == size
return data
@abc.abstractmethod
def write(self, address, data):
raise NotImplementedError()
@abc.abstractmethod
def read(self, address, size):
raise NotImplementedError()
class NativeWasmMemory(WasmMemory):
""" Native wasm memory emulation """
def memory_size(self) -> int:
""" return memory size in pages """
return self._data_page.size // PAGE_SIZE
def write(self, address, data):
self._instance._data_page.seek(address)
self._instance._data_page.write(data)
def read(self, address, size):
self._instance._data_page.seek(address)
data = self._instance._data_page.read(size)
assert len(data) == size
return data
class PythonWasmMemory(WasmMemory):
""" Python wasm memory emulation """
def write(self, address, data):
address = self._module.mem0_start + address
self._module._py_module.write_mem(address, data)
def read(self, address, size):
address = self._module.mem0_start + address
data = self._module._py_module.read_mem(address, size)
assert len(data) == size
return data
class PythonModuleInstance(ModuleInstance):
""" Wasm module loaded a generated python module """
def __init__(self, module, imports):
super().__init__()
self._py_module = module
self.mem_end = self._py_module.heap_top()
# Magical python memory interface, add it now:
imports['wasm_rt_memory_grow'] = self.memory_grow
imports['wasm_rt_memory_size'] = self.memory_size
# Link all imports:
for name, f in imports.items():
# TODO: make a choice between those two options:
# gen_rocket_wasm.externals[name] = f
setattr(self._py_module, name, f)
def _run_init(self):
self._py_module._run_init()
def load_memory(self, module):
memories = create_memories(module)
if memories:
assert len(memories) == 1
memory, min_size, max_size = memories[0]
self.mem0_start = self._py_module.heap_top()
self._py_module.heap.extend(memory)
mem0_ptr_ptr = self._py_module.wasm_mem0_address
self._py_module.store_i32(self.mem0_start, mem0_ptr_ptr)
mem0 = PythonWasmMemory(min_size, max_size)
# TODO: HACK HACK HACK:
mem0._module = self
self._memories.append(mem0)
def memory_grow(self, amount):
""" Grow memory and return the old size """
# Limit the bounds of memory somewhat:
if amount >= 0x10000:
return -1
else:
max_size = self._memories[0].max_size
old_size = self.memory_size()
new_size = old_size + amount
if max_size is not None and new_size > max_size:
return -1
else:
self._py_module.heap.extend(bytes(amount * PAGE_SIZE))
return old_size
def memory_size(self):
""" return memory size in pages """
size = (self._py_module.heap_top() - self.mem0_start) // PAGE_SIZE
return size
class Exports:
def __init__(self):
self._function_map = {}
""" Container for exported functions """
def __getitem__(self, key):
assert isinstance(key, str)
return self._function_map[key]
def __getattr__(self, name):
if name in self._function_map:
return self._function_map[name]
else:
raise AttributeError('Name "{}" was not exported'.format(name))
| [
"logging.getLogger",
"os.path.exists",
"types.ModuleType",
"struct.pack",
"shelve.open",
"io.StringIO"
] | [((753, 785), 'logging.getLogger', 'logging.getLogger', (['"""instantiate"""'], {}), "('instantiate')\n", (770, 785), False, 'import logging\n'), ((5364, 5377), 'io.StringIO', 'io.StringIO', ([], {}), '()\n', (5375, 5377), False, 'import io\n'), ((5522, 5539), 'types.ModuleType', 'ModuleType', (['"""gen"""'], {}), "('gen')\n", (5532, 5539), False, 'from types import ModuleType\n'), ((3137, 3163), 'os.path.exists', 'os.path.exists', (['cache_file'], {}), '(cache_file)\n', (3151, 3163), False, 'import os\n'), ((3241, 3264), 'shelve.open', 'shelve.open', (['cache_file'], {}), '(cache_file)\n', (3252, 3264), False, 'import shelve\n'), ((9905, 9932), 'struct.pack', 'struct.pack', (['"""Q"""', 'base_addr'], {}), "('Q', base_addr)\n", (9916, 9932), False, 'import struct\n'), ((3810, 3833), 'shelve.open', 'shelve.open', (['cache_file'], {}), '(cache_file)\n', (3821, 3833), False, 'import shelve\n')] |
import numpy as np
import cv2
import os
from matplotlib import pyplot as plt
#### INPUT ####
# folder that contains datapoints
folderName = '2dIR'
#### SETTINGS ####
# settings listed below are suitable for 2D data
# intensity of noise filtering; higher values mean more blurring
medianKernel = 5
# blurring radius in x and y direction; higher values mean more blurring; note: these values need to be odd
gaussian_x = 9
gaussian_y = 181
# decay blurring strength; higher values mean blurring will be more focused on the center
gaussianSigma = 60
# number of pixels that are averaged on both sides when iterating over each pixel in a row
pixelsAveraged1 = 10
# number of pixels that are averaged on both sides when iterating over pixels closer to the leading edge; this number should be smaller than pixelsAveraged1 since higher precision is needed
pixelsAveraged2 = 6
# vertical range of pixels considered when determining transition line; range is selected so that noise at the root and the tip is disregarded
rangeVer = (40, 400)
# maximal fraction of standard deviation for the point to be included during filtering
maxStd = 0.9
# minimal fraction of the points left after filtering for the line to be considered as transition line
minFiltered = 0.5
# critical angle at which the line closest to the leading edge is considered to be the transition line
criticalAngle = 7.5
# margin of averaged pixels between the leading edge and detected transition points
margin = 2
# minimal average difference of the more aft lines to be considered as transition line
minDifference1 = 4.68
# minimal average difference of the more forward lines to be considered as transition line
minDifference2 = 3.1
# width of the cropped image
width = 360
# settings listed below are suitable for 3D data
# medianKernel = 5
# gaussian_x = 9
# gaussian_y = 181
# gaussianSigma = 60
# pixelsAveraged1 = 9
# pixelsAveraged2 = 6
# rangeVer = (40, 400)
# maxStd = 1.5
# minFiltered = 0.5
# criticalAngle = 9.5
# margin = 2
# minDifference1 = 3.84
# minDifference2 = 3.1
# width = 360
# processing image
def findTransition(data, angle):
# removing NaN values from the array
data = data[:, ~np.isnan(data).all(axis=0)]
# normalising data
data = ((data - np.amin(data)) / (np.amax(data) - np.amin(data)) * 255)
# converting to pixel data
data = data.astype(np.uint8)
# processing data using median and gaussian blur
blurred = cv2.medianBlur(data, medianKernel)
blurred = cv2.GaussianBlur(blurred, (gaussian_x, gaussian_y), gaussianSigma)
# creating empty arrays to store locations of edges and potential transitions
edges = np.zeros((len(blurred), 2), dtype=int)
edge = (0, 0)
differencesVer = np.zeros((len(blurred), 3))
transitions1 = np.zeros((len(blurred), 2), dtype=int)
transitions2 = np.zeros((len(blurred), 2), dtype=int)
# iterating over each row of pixels
for i in range(len(blurred)):
# iterating over each pixel in a row and calculating differences between pixels to the right and to the left
differencesHor1 = np.zeros(len(blurred[i]))
for j in range(len(blurred[i])):
if j - pixelsAveraged1 >= 0 and j + pixelsAveraged1 <= len(blurred[i]):
differencesHor1[j] = np.absolute(np.average(blurred[i, j - pixelsAveraged1:j]) - np.average(blurred[i, j:j + pixelsAveraged1]))
# selecting two locations where differences are the highest
edges[i, 0] = np.argmax(differencesHor1)
for j in range(len(differencesHor1)):
if differencesHor1[j] > differencesHor1[edges[i, 1]] and np.absolute(edges[i, 0] - j) > pixelsAveraged1:
edges[i, 1] = j
edges = np.sort(edges, axis=1)
# averaging the detected locations to determine position of the edges
edge = int(np.average(edges[rangeVer[0]:rangeVer[1], 0])), int(np.average([edges[rangeVer[0]:rangeVer[1], 1]]))
# iterating over each pixel between edges and calculating differences between pixels to the right and to the left
differencesHor1 = np.zeros(len(blurred[i]))
for j in range(len(blurred[i])):
if edges[i, 0] + 2 * pixelsAveraged1 <= j <= edges[i, 1] - margin * pixelsAveraged1:
differencesHor1[j] = np.absolute(np.average(blurred[i, j - pixelsAveraged1:j]) - np.average(blurred[i, j:j + pixelsAveraged1]))
# selecting two locations where differences are the highest
transitions1[i, 0] = np.argmax(differencesHor1)
for j in range(len(differencesHor1)):
if differencesHor1[j] > differencesHor1[transitions1[i, 1]] and np.absolute(transitions1[i, 0] - j) > 3 * pixelsAveraged1:
transitions1[i, 1] = j
transitions1 = np.sort(transitions1, axis=1)
# iterating over pixels closer to the leading edge and calculating differences between pixels to the right and to the left
differencesHor2 = np.zeros(len(blurred[i]))
for j in range(len(blurred[i])):
if edges[i, 0] + 10 * pixelsAveraged2 <= j <= edges[i, 1] - pixelsAveraged2:
differencesHor2[j] = np.absolute(np.average(blurred[i, j - pixelsAveraged2:j]) - np.average(blurred[i, j:j + pixelsAveraged2]))
# selecting two locations where differences are the highest
transitions2[i, 0] = np.argmax(differencesHor2)
for j in range(len(differencesHor2)):
if differencesHor2[j] > differencesHor2[transitions2[i, 1]] and np.absolute(transitions2[i, 0] - j) > pixelsAveraged2:
transitions2[i, 1] = j
transitions2 = np.sort(transitions2, axis=1)
# saving maximal horizontal differences to calculate vertical differences
differencesVer[i, 0] = differencesHor1[transitions1[i, 0]]
differencesVer[i, 1] = differencesHor1[transitions1[i, 1]]
differencesVer[i, 2] = differencesHor2[transitions2[i, 0]]
# cropping locations of transitions and vertical differences
transitions1 = transitions1[rangeVer[0]:rangeVer[1], :]
transitions2 = transitions2[rangeVer[0]:rangeVer[1], :]
differencesVer = differencesVer[rangeVer[0]:rangeVer[1], :]
# calculating average and standard deviation of the first detected transition line
transitions1Avg = np.average(transitions1[:, 0])
transitions1Std = np.std(transitions1[:, 0])
# filtering locations that are too far from the average
transitions1Filtered = []
for i in range(len(transitions1)):
if round(transitions1Avg - maxStd * transitions1Std) <= transitions1[i, 0] <= round(transitions1Avg + maxStd * transitions1Std):
transitions1Filtered.append(transitions1[i, 0])
# calculating average and standard deviation of the second detected transition line
transitions2Avg = np.average(transitions1[:, 1])
transitions2Std = np.std(transitions1[:, 1])
# filtering locations that are too far from the average
transitions2Filtered = []
for i in range(len(transitions1)):
if round(transitions2Avg - maxStd * transitions2Std) <= transitions1[i, 1] <= round(transitions2Avg + maxStd * transitions2Std):
transitions2Filtered.append(transitions1[i, 1])
# calculating average and standard deviation of the third detected transition line
transitions3Avg = [np.average(transitions2[:, 0]), np.average(transitions2[:, 1])]
transitions3Std = [np.std(transitions2[:, 0]), np.std(transitions2[:, 1])]
# filtering locations that are too far from the average
transitions3Filtered = []
for i in range(len(transitions2)):
if round(transitions3Avg[0] - maxStd * transitions3Std[0]) <= transitions2[i, 0] <= round(transitions3Avg[0] + maxStd * transitions3Std[0]) \
and round(transitions3Avg[1] - maxStd * transitions3Std[1]) <= transitions2[i, 1] <= round(transitions3Avg[1] + maxStd * transitions3Std[1]):
transitions3Filtered.append(np.average(transitions2[i, :]))
# calculating the average of vertical differences for each transition line
differences = np.zeros(3)
differences[0] = np.average(differencesVer[:, 0])
differences[1] = np.average(differencesVer[:, 1])
differences[2] = np.average(differencesVer[:, 2])
# choosing one of the three detected lines
if differences[0] >= minDifference1 and len(transitions1Filtered) > minFiltered * (rangeVer[1] - rangeVer[0]) and angle < criticalAngle:
transition = round(np.average(transitions1Filtered))
elif differences[1] >= minDifference1 and len(transitions2Filtered) > minFiltered * (rangeVer[1] - rangeVer[0]) and angle < criticalAngle:
transition = round(np.average(transitions2Filtered))
elif differences[2] >= minDifference2:
transition = round(np.average(transitions3Filtered))
else:
transition = edge[1]
# printing parameters for debugging
# print('Differences 1: ' + differences[0])
# print('Differences 2: ' + differences[1])
# print('Differences 3: ' + differences[2])
# print('Length of filtered transitions 1:' + str(len(transitions1Filtered)))
# print('Length of filtered transitions 1:' + str(len(transitions2Filtered)))
# print('Length of filtered transitions 1:' + str(len(transitions3Filtered)))
# calculating the location of transition as percentage of chord length
XC = 1 - ((transition - edge[0]) / (edge[1] - edge[0]))
# printing edges and transition line on the generated image
for i in range(len(data)):
data[i, edge[0] - 1:edge[0] + 1] = 0
data[i, edge[1] - 1:edge[1] + 1] = 0
data[i, transition - 1:transition + 1] = 0
# data[i, edges[i, 0] - 1:edges[i, 0] + 1] = 0
# data[i, edges[i, 1] - 1:edges[i, 1] + 1] = 0
# printing detected lines on the generated image
# for i in range(len(transitions1)):
# data[i + rangeVer[0], transitions1[i, 0] - 1:transitions1[i, 0] + 1] = 0
# data[i + rangeVer[0], transitions1[i, 1] - 1:transitions1[i, 1] + 1] = 0
# data[i + rangeVer[0], transitions2[i, 0] - 1:transitions2[i, 0] + 1] = 0
# data[i + rangeVer[0], transitions2[i, 1] - 1:transitions2[i, 1] + 1] = 0
# calculating midpoint between edges and cropping the image
midpoint = int((edge[1] - edge[0]) / 2 + edge[0])
data = data[:, int(midpoint - width / 2):int(midpoint + width / 2)]
blurred = blurred[:, int(midpoint - width / 2):int(midpoint + width / 2)]
# converting data to contiguous array
data = np.ascontiguousarray(data, dtype=np.uint8)
# settings for placing AoA and transition location on the image
text1 = 'AoA: ' + str(angle)
text2 = 'x/c = ' + str(round(XC, 3))
org1 = (60, 20)
org2 = (60, 40)
font = cv2.FONT_HERSHEY_SIMPLEX
fontScale = 0.5
color = (255, 0, 0)
thickness = 1
# inserting text to the image
data = cv2.putText(data, text1, org1, font, fontScale, color, thickness, cv2.LINE_AA)
data = cv2.putText(data, text2, org2, font, fontScale, color, thickness, cv2.LINE_AA)
# showing generated images
# cv2.imshow("data", data)
# cv2.imshow("blurred", blurred)
# cv2.waitKey(0)
# saving generated images
path = 'Images'
fileName = 'AoA=' + str(angle) + ',XC=' + str(round(XC, 3)) + '.jpg'
cv2.imwrite(os.path.join(path, fileName), data)
# cv2.imwrite(os.path.join(path, 'blurred.jpg'), blurred)
return XC
# detecting all folders in the selected directory
folders = os.listdir(folderName + '/.')
# creating empty array for results
results = np.zeros((len(folders), 2))
# iterating over each folder
for i, folder in enumerate(folders):
# detecting all files in the selected folder
folderPath = folderName + '/' + folder + '/.'
files = os.listdir(folderPath)
# creating empty array in the size of data
dataPoints = np.zeros((480, 640))
# monitoring progress of the program
print('---------------------------------------')
print('Progress: ' + str(round(i / len(folders) * 100, 2)) + '%')
print('AoA: ' + folder)
# iterating over detected files
for file in files:
# importing data into array
filePath = folderName + '/' + folder + '/' + file
dataPoint = np.genfromtxt(filePath, delimiter=';')
# removing NaN values from the array
dataPoint = dataPoint[:, ~np.isnan(dataPoint).all(axis=0)]
# adding imported data to the array
dataPoints += dataPoint
break
# calculating average of the data
# dataPoints = dataPoints / len(files)
# calculating location of transition and saving it into the results
transitionXC = findTransition(dataPoints, float(folder))
results[i] = [float(folder), transitionXC]
# saving results to text file
results = results[results[:, 0].argsort()]
np.savetxt('results.txt', results, delimiter=',')
# generating graph of location vs angle of attack
plt.plot(results[:, 0], results[:, 1])
plt.xlabel("Angle of attack [deg]")
plt.ylabel("Location of transition [x/c]")
plt.show()
| [
"matplotlib.pyplot.ylabel",
"numpy.ascontiguousarray",
"numpy.genfromtxt",
"os.listdir",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.sort",
"cv2.medianBlur",
"numpy.amin",
"numpy.average",
"numpy.argmax",
"cv2.putText",
"numpy.isnan",
"numpy.savetxt",
"numpy.std",
"cv2... | [((11748, 11777), 'os.listdir', 'os.listdir', (["(folderName + '/.')"], {}), "(folderName + '/.')\n", (11758, 11777), False, 'import os\n'), ((13133, 13182), 'numpy.savetxt', 'np.savetxt', (['"""results.txt"""', 'results'], {'delimiter': '""","""'}), "('results.txt', results, delimiter=',')\n", (13143, 13182), True, 'import numpy as np\n'), ((13237, 13275), 'matplotlib.pyplot.plot', 'plt.plot', (['results[:, 0]', 'results[:, 1]'], {}), '(results[:, 0], results[:, 1])\n', (13245, 13275), True, 'from matplotlib import pyplot as plt\n'), ((13277, 13312), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Angle of attack [deg]"""'], {}), "('Angle of attack [deg]')\n", (13287, 13312), True, 'from matplotlib import pyplot as plt\n'), ((13314, 13356), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Location of transition [x/c]"""'], {}), "('Location of transition [x/c]')\n", (13324, 13356), True, 'from matplotlib import pyplot as plt\n'), ((13358, 13368), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (13366, 13368), True, 'from matplotlib import pyplot as plt\n'), ((2527, 2561), 'cv2.medianBlur', 'cv2.medianBlur', (['data', 'medianKernel'], {}), '(data, medianKernel)\n', (2541, 2561), False, 'import cv2\n'), ((2577, 2643), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['blurred', '(gaussian_x, gaussian_y)', 'gaussianSigma'], {}), '(blurred, (gaussian_x, gaussian_y), gaussianSigma)\n', (2593, 2643), False, 'import cv2\n'), ((6442, 6472), 'numpy.average', 'np.average', (['transitions1[:, 0]'], {}), '(transitions1[:, 0])\n', (6452, 6472), True, 'import numpy as np\n'), ((6496, 6522), 'numpy.std', 'np.std', (['transitions1[:, 0]'], {}), '(transitions1[:, 0])\n', (6502, 6522), True, 'import numpy as np\n'), ((6970, 7000), 'numpy.average', 'np.average', (['transitions1[:, 1]'], {}), '(transitions1[:, 1])\n', (6980, 7000), True, 'import numpy as np\n'), ((7024, 7050), 'numpy.std', 'np.std', (['transitions1[:, 1]'], {}), '(transitions1[:, 1])\n', (7030, 7050), True, 'import numpy as np\n'), ((8260, 8271), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (8268, 8271), True, 'import numpy as np\n'), ((8294, 8326), 'numpy.average', 'np.average', (['differencesVer[:, 0]'], {}), '(differencesVer[:, 0])\n', (8304, 8326), True, 'import numpy as np\n'), ((8349, 8381), 'numpy.average', 'np.average', (['differencesVer[:, 1]'], {}), '(differencesVer[:, 1])\n', (8359, 8381), True, 'import numpy as np\n'), ((8404, 8436), 'numpy.average', 'np.average', (['differencesVer[:, 2]'], {}), '(differencesVer[:, 2])\n', (8414, 8436), True, 'import numpy as np\n'), ((10742, 10784), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['data'], {'dtype': 'np.uint8'}), '(data, dtype=np.uint8)\n', (10762, 10784), True, 'import numpy as np\n'), ((11125, 11203), 'cv2.putText', 'cv2.putText', (['data', 'text1', 'org1', 'font', 'fontScale', 'color', 'thickness', 'cv2.LINE_AA'], {}), '(data, text1, org1, font, fontScale, color, thickness, cv2.LINE_AA)\n', (11136, 11203), False, 'import cv2\n'), ((11216, 11294), 'cv2.putText', 'cv2.putText', (['data', 'text2', 'org2', 'font', 'fontScale', 'color', 'thickness', 'cv2.LINE_AA'], {}), '(data, text2, org2, font, fontScale, color, thickness, cv2.LINE_AA)\n', (11227, 11294), False, 'import cv2\n'), ((12041, 12063), 'os.listdir', 'os.listdir', (['folderPath'], {}), '(folderPath)\n', (12051, 12063), False, 'import os\n'), ((12132, 12152), 'numpy.zeros', 'np.zeros', (['(480, 640)'], {}), '((480, 640))\n', (12140, 12152), True, 'import numpy as np\n'), ((3585, 3611), 'numpy.argmax', 'np.argmax', (['differencesHor1'], {}), '(differencesHor1)\n', (3594, 3611), True, 'import numpy as np\n'), ((3827, 3849), 'numpy.sort', 'np.sort', (['edges'], {'axis': '(1)'}), '(edges, axis=1)\n', (3834, 3849), True, 'import numpy as np\n'), ((4616, 4642), 'numpy.argmax', 'np.argmax', (['differencesHor1'], {}), '(differencesHor1)\n', (4625, 4642), True, 'import numpy as np\n'), ((4890, 4919), 'numpy.sort', 'np.sort', (['transitions1'], {'axis': '(1)'}), '(transitions1, axis=1)\n', (4897, 4919), True, 'import numpy as np\n'), ((5485, 5511), 'numpy.argmax', 'np.argmax', (['differencesHor2'], {}), '(differencesHor2)\n', (5494, 5511), True, 'import numpy as np\n'), ((5755, 5784), 'numpy.sort', 'np.sort', (['transitions2'], {'axis': '(1)'}), '(transitions2, axis=1)\n', (5762, 5784), True, 'import numpy as np\n'), ((7498, 7528), 'numpy.average', 'np.average', (['transitions2[:, 0]'], {}), '(transitions2[:, 0])\n', (7508, 7528), True, 'import numpy as np\n'), ((7530, 7560), 'numpy.average', 'np.average', (['transitions2[:, 1]'], {}), '(transitions2[:, 1])\n', (7540, 7560), True, 'import numpy as np\n'), ((7586, 7612), 'numpy.std', 'np.std', (['transitions2[:, 0]'], {}), '(transitions2[:, 0])\n', (7592, 7612), True, 'import numpy as np\n'), ((7614, 7640), 'numpy.std', 'np.std', (['transitions2[:, 1]'], {}), '(transitions2[:, 1])\n', (7620, 7640), True, 'import numpy as np\n'), ((11566, 11594), 'os.path.join', 'os.path.join', (['path', 'fileName'], {}), '(path, fileName)\n', (11578, 11594), False, 'import os\n'), ((12533, 12571), 'numpy.genfromtxt', 'np.genfromtxt', (['filePath'], {'delimiter': '""";"""'}), "(filePath, delimiter=';')\n", (12546, 12571), True, 'import numpy as np\n'), ((8657, 8689), 'numpy.average', 'np.average', (['transitions1Filtered'], {}), '(transitions1Filtered)\n', (8667, 8689), True, 'import numpy as np\n'), ((2334, 2347), 'numpy.amin', 'np.amin', (['data'], {}), '(data)\n', (2341, 2347), True, 'import numpy as np\n'), ((2352, 2365), 'numpy.amax', 'np.amax', (['data'], {}), '(data)\n', (2359, 2365), True, 'import numpy as np\n'), ((2368, 2381), 'numpy.amin', 'np.amin', (['data'], {}), '(data)\n', (2375, 2381), True, 'import numpy as np\n'), ((3951, 3996), 'numpy.average', 'np.average', (['edges[rangeVer[0]:rangeVer[1], 0]'], {}), '(edges[rangeVer[0]:rangeVer[1], 0])\n', (3961, 3996), True, 'import numpy as np\n'), ((4003, 4050), 'numpy.average', 'np.average', (['[edges[rangeVer[0]:rangeVer[1], 1]]'], {}), '([edges[rangeVer[0]:rangeVer[1], 1]])\n', (4013, 4050), True, 'import numpy as np\n'), ((8127, 8157), 'numpy.average', 'np.average', (['transitions2[i, :]'], {}), '(transitions2[i, :])\n', (8137, 8157), True, 'import numpy as np\n'), ((8863, 8895), 'numpy.average', 'np.average', (['transitions2Filtered'], {}), '(transitions2Filtered)\n', (8873, 8895), True, 'import numpy as np\n'), ((3729, 3757), 'numpy.absolute', 'np.absolute', (['(edges[i, 0] - j)'], {}), '(edges[i, 0] - j)\n', (3740, 3757), True, 'import numpy as np\n'), ((4767, 4802), 'numpy.absolute', 'np.absolute', (['(transitions1[i, 0] - j)'], {}), '(transitions1[i, 0] - j)\n', (4778, 4802), True, 'import numpy as np\n'), ((5636, 5671), 'numpy.absolute', 'np.absolute', (['(transitions2[i, 0] - j)'], {}), '(transitions2[i, 0] - j)\n', (5647, 5671), True, 'import numpy as np\n'), ((8969, 9001), 'numpy.average', 'np.average', (['transitions3Filtered'], {}), '(transitions3Filtered)\n', (8979, 9001), True, 'import numpy as np\n'), ((2261, 2275), 'numpy.isnan', 'np.isnan', (['data'], {}), '(data)\n', (2269, 2275), True, 'import numpy as np\n'), ((3396, 3441), 'numpy.average', 'np.average', (['blurred[i, j - pixelsAveraged1:j]'], {}), '(blurred[i, j - pixelsAveraged1:j])\n', (3406, 3441), True, 'import numpy as np\n'), ((3444, 3489), 'numpy.average', 'np.average', (['blurred[i, j:j + pixelsAveraged1]'], {}), '(blurred[i, j:j + pixelsAveraged1])\n', (3454, 3489), True, 'import numpy as np\n'), ((4420, 4465), 'numpy.average', 'np.average', (['blurred[i, j - pixelsAveraged1:j]'], {}), '(blurred[i, j - pixelsAveraged1:j])\n', (4430, 4465), True, 'import numpy as np\n'), ((4468, 4513), 'numpy.average', 'np.average', (['blurred[i, j:j + pixelsAveraged1]'], {}), '(blurred[i, j:j + pixelsAveraged1])\n', (4478, 4513), True, 'import numpy as np\n'), ((5289, 5334), 'numpy.average', 'np.average', (['blurred[i, j - pixelsAveraged2:j]'], {}), '(blurred[i, j - pixelsAveraged2:j])\n', (5299, 5334), True, 'import numpy as np\n'), ((5337, 5382), 'numpy.average', 'np.average', (['blurred[i, j:j + pixelsAveraged2]'], {}), '(blurred[i, j:j + pixelsAveraged2])\n', (5347, 5382), True, 'import numpy as np\n'), ((12655, 12674), 'numpy.isnan', 'np.isnan', (['dataPoint'], {}), '(dataPoint)\n', (12663, 12674), True, 'import numpy as np\n')] |
from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
import matplotlib.pyplot as plt
plt.plot([1, 23, 2, 4])
plt.ylabel('some numbers')
class MyApp(App):
def build(self):
box = BoxLayout()
box.add_widget(FigureCanvasKivyAgg(plt.gcf()))
return box
MyApp().run()
| [
"matplotlib.pyplot.gcf",
"matplotlib.pyplot.plot",
"kivy.uix.boxlayout.BoxLayout",
"matplotlib.pyplot.ylabel"
] | [((170, 193), 'matplotlib.pyplot.plot', 'plt.plot', (['[1, 23, 2, 4]'], {}), '([1, 23, 2, 4])\n', (178, 193), True, 'import matplotlib.pyplot as plt\n'), ((194, 220), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""some numbers"""'], {}), "('some numbers')\n", (204, 220), True, 'import matplotlib.pyplot as plt\n'), ((276, 287), 'kivy.uix.boxlayout.BoxLayout', 'BoxLayout', ([], {}), '()\n', (285, 287), False, 'from kivy.uix.boxlayout import BoxLayout\n'), ((331, 340), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (338, 340), True, 'import matplotlib.pyplot as plt\n')] |
import os
import random
from tqdm import tqdm
from collections import defaultdict
from data_genie.data_genie_config import *
from data_genie.data_genie_utils import TRAINING_DATA_PATH, CACHED_KENDALL_TAU_PATH, load_obj, save_obj
from data_genie.data_genie_utils import count_performance_retained, get_best_results
from utils import INF
def get_data_pointwise(dataset):
PATH = TRAINING_DATA_PATH(dataset, "pointwise")
if not os.path.exists(PATH + ".pkl"): prep_data(dataset)
return load_obj(PATH)
def get_data_pairwise(dataset):
PATH = TRAINING_DATA_PATH(dataset, "pairwise")
if not os.path.exists(PATH + ".pkl"): prep_data(dataset)
return load_obj(PATH)
def prep_data(dataset):
# Get model runs
results = get_results(dataset)
# Build train, val, and test data
val_data = [ [], [], [], [], [] ]
test_data = copy.deepcopy(val_data)
train_data_pointwise = copy.deepcopy(val_data)
train_data_pairwise = copy.deepcopy(val_data)
for task, metrics in scenarios:
all_options = []
for m in metrics:
for sampling_percent in percent_rns_options:
all_options.append([ m, sampling_percent ])
random.shuffle(all_options)
val_indices = [ all_options[0] ]
if len(metrics) == 1: test_indices, train_indices = [ all_options[1] ], all_options[2:]
else: test_indices, train_indices = all_options[1:4], all_options[4:]
# Validation/testing data
for container, indices in [ (val_data, val_indices), (test_data, test_indices) ]:
for m, sampling_percent in indices:
for sampling in all_samplers:
container[0].append(get_embedding_id(task, 'complete_data', 0))
container[1].append(get_embedding_id(task, sampling, sampling_percent))
container[2].append(task_map[task])
container[3].append(metric_map[m])
container[4].append(
count_performance_retained(results[task][m][sampling_percent][sampling], m, scaled = False)
)
# Training data
for m, sampling_percent in train_indices:
y = [ count_performance_retained(
results[task][m][sampling_percent][sampling], m, scaled = False
) for sampling in all_samplers ]
# Pointwise
for at, sampling in enumerate(all_samplers):
if y[at] in [ INF, -INF ]: continue
train_data_pointwise[0].append(get_embedding_id(task, 'complete_data', 0))
train_data_pointwise[1].append(get_embedding_id(task, sampling, sampling_percent))
train_data_pointwise[2].append(task_map[task])
train_data_pointwise[3].append(metric_map[m])
train_data_pointwise[4].append(y[at])
# Pairwise
for i in range(len(all_samplers)):
for j in range(i+1, len(all_samplers)):
if y[i] in [ INF, -INF ]: continue
if y[j] in [ INF, -INF ]: continue
if y[i] == y[j]: continue
if y[i] > y[j]: better, lower = i, j
else: better, lower = j, i
train_data_pairwise[0].append(get_embedding_id(task, 'complete_data', 0))
train_data_pairwise[1].append(get_embedding_id(task, all_samplers[better], sampling_percent))
train_data_pairwise[2].append(get_embedding_id(task, all_samplers[lower], sampling_percent))
train_data_pairwise[3].append(task_map[task])
train_data_pairwise[4].append(metric_map[m])
save_obj([ train_data_pointwise, val_data, test_data ], TRAINING_DATA_PATH(dataset, "pointwise"))
save_obj([ train_data_pairwise, val_data, test_data ], TRAINING_DATA_PATH(dataset, "pairwise"))
def get_results(dataset):
PATH = CACHED_KENDALL_TAU_PATH(dataset)
if os.path.exists(PATH + ".pkl"): return load_obj(PATH)
loop = tqdm(
total = len(scenarios) * ((len(svp_methods) * len(sampling_svp)) + len(sampling_kinds)) * \
len(methods_to_compare) * len(percent_rns_options)
)
y = {}
for task, metrics_to_return in scenarios:
# Structure of `y`
y[task] = {}
for m in metrics_to_return:
y[task][m] = {}
for percent_rns in percent_rns_options:
y[task][m][percent_rns] = defaultdict(list)
# Random/graph-based sampling
for sampling_kind in sampling_kinds:
for method in methods_to_compare:
complete_data_metrics = get_best_results(
dataset, 0, 'complete_data', method, task, metrics_to_return
)
for percent_rns in percent_rns_options:
loop.update(1)
metrics = get_best_results(
dataset, percent_rns, sampling_kind, method, task, metrics_to_return
)
if metrics is None: continue
for at, m in enumerate(metrics_to_return):
y[task][m][percent_rns][sampling_kind].append([
metrics[at], complete_data_metrics[at]
])
# SVP sampling
for svp_method in svp_methods:
for sampling_kind in sampling_svp:
for method in methods_to_compare:
complete_data_metrics = get_best_results(
dataset, 0, 'complete_data', method, task, metrics_to_return
)
for percent_rns in percent_rns_options:
loop.update(1)
metrics = get_best_results(
dataset, percent_rns, "svp_{}".format(svp_method), method, task, metrics_to_return,
sampling_svp = sampling_kind
)
if metrics is None: continue
for at, m in enumerate(metrics_to_return):
y[task][m][percent_rns]["svp_{}_{}".format(svp_method, sampling_kind)].append([
metrics[at], complete_data_metrics[at]
])
save_obj(y, PATH)
return y
| [
"os.path.exists",
"data_genie.data_genie_utils.count_performance_retained",
"random.shuffle",
"data_genie.data_genie_utils.get_best_results",
"data_genie.data_genie_utils.load_obj",
"data_genie.data_genie_utils.TRAINING_DATA_PATH",
"collections.defaultdict",
"data_genie.data_genie_utils.CACHED_KENDALL... | [((380, 420), 'data_genie.data_genie_utils.TRAINING_DATA_PATH', 'TRAINING_DATA_PATH', (['dataset', '"""pointwise"""'], {}), "(dataset, 'pointwise')\n", (398, 420), False, 'from data_genie.data_genie_utils import TRAINING_DATA_PATH, CACHED_KENDALL_TAU_PATH, load_obj, save_obj\n'), ((487, 501), 'data_genie.data_genie_utils.load_obj', 'load_obj', (['PATH'], {}), '(PATH)\n', (495, 501), False, 'from data_genie.data_genie_utils import TRAINING_DATA_PATH, CACHED_KENDALL_TAU_PATH, load_obj, save_obj\n'), ((543, 582), 'data_genie.data_genie_utils.TRAINING_DATA_PATH', 'TRAINING_DATA_PATH', (['dataset', '"""pairwise"""'], {}), "(dataset, 'pairwise')\n", (561, 582), False, 'from data_genie.data_genie_utils import TRAINING_DATA_PATH, CACHED_KENDALL_TAU_PATH, load_obj, save_obj\n'), ((650, 664), 'data_genie.data_genie_utils.load_obj', 'load_obj', (['PATH'], {}), '(PATH)\n', (658, 664), False, 'from data_genie.data_genie_utils import TRAINING_DATA_PATH, CACHED_KENDALL_TAU_PATH, load_obj, save_obj\n'), ((3397, 3429), 'data_genie.data_genie_utils.CACHED_KENDALL_TAU_PATH', 'CACHED_KENDALL_TAU_PATH', (['dataset'], {}), '(dataset)\n', (3420, 3429), False, 'from data_genie.data_genie_utils import TRAINING_DATA_PATH, CACHED_KENDALL_TAU_PATH, load_obj, save_obj\n'), ((3434, 3463), 'os.path.exists', 'os.path.exists', (["(PATH + '.pkl')"], {}), "(PATH + '.pkl')\n", (3448, 3463), False, 'import os\n'), ((5211, 5228), 'data_genie.data_genie_utils.save_obj', 'save_obj', (['y', 'PATH'], {}), '(y, PATH)\n', (5219, 5228), False, 'from data_genie.data_genie_utils import TRAINING_DATA_PATH, CACHED_KENDALL_TAU_PATH, load_obj, save_obj\n'), ((429, 458), 'os.path.exists', 'os.path.exists', (["(PATH + '.pkl')"], {}), "(PATH + '.pkl')\n", (443, 458), False, 'import os\n'), ((591, 620), 'os.path.exists', 'os.path.exists', (["(PATH + '.pkl')"], {}), "(PATH + '.pkl')\n", (605, 620), False, 'import os\n'), ((1115, 1142), 'random.shuffle', 'random.shuffle', (['all_options'], {}), '(all_options)\n', (1129, 1142), False, 'import random\n'), ((3223, 3263), 'data_genie.data_genie_utils.TRAINING_DATA_PATH', 'TRAINING_DATA_PATH', (['dataset', '"""pointwise"""'], {}), "(dataset, 'pointwise')\n", (3241, 3263), False, 'from data_genie.data_genie_utils import TRAINING_DATA_PATH, CACHED_KENDALL_TAU_PATH, load_obj, save_obj\n'), ((3321, 3360), 'data_genie.data_genie_utils.TRAINING_DATA_PATH', 'TRAINING_DATA_PATH', (['dataset', '"""pairwise"""'], {}), "(dataset, 'pairwise')\n", (3339, 3360), False, 'from data_genie.data_genie_utils import TRAINING_DATA_PATH, CACHED_KENDALL_TAU_PATH, load_obj, save_obj\n'), ((3472, 3486), 'data_genie.data_genie_utils.load_obj', 'load_obj', (['PATH'], {}), '(PATH)\n', (3480, 3486), False, 'from data_genie.data_genie_utils import TRAINING_DATA_PATH, CACHED_KENDALL_TAU_PATH, load_obj, save_obj\n'), ((1958, 2051), 'data_genie.data_genie_utils.count_performance_retained', 'count_performance_retained', (['results[task][m][sampling_percent][sampling]', 'm'], {'scaled': '(False)'}), '(results[task][m][sampling_percent][sampling], m,\n scaled=False)\n', (1984, 2051), False, 'from data_genie.data_genie_utils import count_performance_retained, get_best_results\n'), ((3867, 3884), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (3878, 3884), False, 'from collections import defaultdict\n'), ((4029, 4107), 'data_genie.data_genie_utils.get_best_results', 'get_best_results', (['dataset', '(0)', '"""complete_data"""', 'method', 'task', 'metrics_to_return'], {}), "(dataset, 0, 'complete_data', method, task, metrics_to_return)\n", (4045, 4107), False, 'from data_genie.data_genie_utils import count_performance_retained, get_best_results\n'), ((4200, 4290), 'data_genie.data_genie_utils.get_best_results', 'get_best_results', (['dataset', 'percent_rns', 'sampling_kind', 'method', 'task', 'metrics_to_return'], {}), '(dataset, percent_rns, sampling_kind, method, task,\n metrics_to_return)\n', (4216, 4290), False, 'from data_genie.data_genie_utils import count_performance_retained, get_best_results\n'), ((4651, 4729), 'data_genie.data_genie_utils.get_best_results', 'get_best_results', (['dataset', '(0)', '"""complete_data"""', 'method', 'task', 'metrics_to_return'], {}), "(dataset, 0, 'complete_data', method, task, metrics_to_return)\n", (4667, 4729), False, 'from data_genie.data_genie_utils import count_performance_retained, get_best_results\n'), ((1787, 1880), 'data_genie.data_genie_utils.count_performance_retained', 'count_performance_retained', (['results[task][m][sampling_percent][sampling]', 'm'], {'scaled': '(False)'}), '(results[task][m][sampling_percent][sampling], m,\n scaled=False)\n', (1813, 1880), False, 'from data_genie.data_genie_utils import count_performance_retained, get_best_results\n')] |
import numpy as np
from matplotlib import pyplot as plt
from env import DrivingEnv
from solvers import GridSolver, SampleGraphSolver
def time_compare(seed=1234, min_sample=10, max_sample=50, count=10):
sample_count = np.linspace(min_sample, max_sample, count).astype(int)
grid_times = []
graph_times = []
for size in sample_count:
env = DrivingEnv(15, random_seed=seed)
solver = GridSolver(size)
grid_times.append(solver.solve(env, max_steps=500))
env = DrivingEnv(15, random_seed=seed)
solver = SampleGraphSolver(size*size)
graph_times.append(solver.solve(env, max_steps=500))
plt.figure()
plt.semilogy(sample_count, grid_times, label="Grid-based")
plt.semilogy(sample_count, graph_times, label="Graph-based")
plt.xlabel("Equivalent sample size")
plt.ylabel("Running time (s)")
plt.legend()
plt.show()
def grid_size_reward_compare(seed=1234, min_sample=10, max_sample=50, count=10, repeat=5):
env = DrivingEnv(15, random_seed=seed)
size_list = np.linspace(min_sample, max_sample, count).astype(int)
cost_list = []
for size in size_list:
cost_cases = []
for _ in range(repeat):
solver = SampleGraphSolver(size*size)
solver.solve(env, max_steps=200, early_stop=False)
states, cost = env.simulate(solver)
cost_cases.append(cost)
cost_list.append(cost_cases)
plt.figure()
plt.plot(size_list, np.mean(cost_list, axis=1))
plt.xlabel("Graph size")
plt.ylabel("Time and safety cost")
plt.title("Graph based policy performance versus graph size")
plt.show()
def grid_with_different_safety_cost(cost_type="linear"):
env = DrivingEnv(15, random_seed=1234)
def render_graph(solver, ax):
solution = solver.report_solution()
solution_set = set()
for i in range(len(solution) - 1):
solution_set.add((solution[i], solution[i+1]))
for n1, n2 in solver._connections:
if (n1, n2) in solution_set or (n2, n1) in solution_set:
color = "#1A090D"
lwidth = 5
else:
color = "#4A139488"
lwidth = 1
ax.plot([solver._samples[n1].x, solver._samples[n2].x], [solver._samples[n1].y, solver._samples[n2].y], lw=lwidth, c=color)
ax.scatter([p.x for p in solver._samples], [p.y for p in solver._samples], c=solver._safety_cost_cache)
solver = SampleGraphSolver(800)
solver.solve(env, max_steps=200, safety_weight=100, safety_type=cost_type)
fig, ax = plt.subplots(1)
env.render(ax)
render_graph(solver, ax)
plt.title("Graph-based solution with %s cost" % cost_type)
plt.show()
def graph_with_different_weight(seed=1234, ratio_count=7):
ratios = np.logspace(-3, 3, ratio_count)
fig, ax = plt.subplots(1)
DrivingEnv(15, random_seed=seed).render(ax)
handles = [None] * ratio_count
for rid, ratio in enumerate(ratios):
coeff = np.sqrt(ratio)
env = DrivingEnv(15, random_seed=seed)
solver = SampleGraphSolver(800)
solver.solve(env, max_steps=100, early_stop=False, safety_weight=coeff, time_weight=1/coeff, safety_type="linear")
solution = solver.report_solution()
solution_set = set()
for i in range(len(solution) - 1):
solution_set.add((solution[i], solution[i+1]))
for n1, n2 in solver._connections:
if (n1, n2) in solution_set or (n2, n1) in solution_set:
lwidth, color = 4, "C%d" % rid
handles[rid], = ax.plot([solver._samples[n1].x, solver._samples[n2].x], [solver._samples[n1].y, solver._samples[n2].y], lw=lwidth, c=color)
# fig.legend(handles, ["safety/time=%f" % ratio for ratio in ratios], loc=1)
plt.title("Difference path under different weights")
plt.show()
graph_with_different_weight()
| [
"matplotlib.pyplot.semilogy",
"env.DrivingEnv",
"solvers.SampleGraphSolver",
"numpy.mean",
"numpy.sqrt",
"matplotlib.pyplot.ylabel",
"solvers.GridSolver",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.figure",
"numpy.linspace",
"matplotlib.pyplot.title",
"numpy.logspace",
"matplotlib.pyplot... | [((650, 662), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (660, 662), True, 'from matplotlib import pyplot as plt\n'), ((667, 725), 'matplotlib.pyplot.semilogy', 'plt.semilogy', (['sample_count', 'grid_times'], {'label': '"""Grid-based"""'}), "(sample_count, grid_times, label='Grid-based')\n", (679, 725), True, 'from matplotlib import pyplot as plt\n'), ((730, 790), 'matplotlib.pyplot.semilogy', 'plt.semilogy', (['sample_count', 'graph_times'], {'label': '"""Graph-based"""'}), "(sample_count, graph_times, label='Graph-based')\n", (742, 790), True, 'from matplotlib import pyplot as plt\n'), ((795, 831), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Equivalent sample size"""'], {}), "('Equivalent sample size')\n", (805, 831), True, 'from matplotlib import pyplot as plt\n'), ((836, 866), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Running time (s)"""'], {}), "('Running time (s)')\n", (846, 866), True, 'from matplotlib import pyplot as plt\n'), ((871, 883), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (881, 883), True, 'from matplotlib import pyplot as plt\n'), ((888, 898), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (896, 898), True, 'from matplotlib import pyplot as plt\n'), ((1001, 1033), 'env.DrivingEnv', 'DrivingEnv', (['(15)'], {'random_seed': 'seed'}), '(15, random_seed=seed)\n', (1011, 1033), False, 'from env import DrivingEnv\n'), ((1446, 1458), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1456, 1458), True, 'from matplotlib import pyplot as plt\n'), ((1515, 1539), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Graph size"""'], {}), "('Graph size')\n", (1525, 1539), True, 'from matplotlib import pyplot as plt\n'), ((1544, 1578), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Time and safety cost"""'], {}), "('Time and safety cost')\n", (1554, 1578), True, 'from matplotlib import pyplot as plt\n'), ((1583, 1644), 'matplotlib.pyplot.title', 'plt.title', (['"""Graph based policy performance versus graph size"""'], {}), "('Graph based policy performance versus graph size')\n", (1592, 1644), True, 'from matplotlib import pyplot as plt\n'), ((1649, 1659), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1657, 1659), True, 'from matplotlib import pyplot as plt\n'), ((1728, 1760), 'env.DrivingEnv', 'DrivingEnv', (['(15)'], {'random_seed': '(1234)'}), '(15, random_seed=1234)\n', (1738, 1760), False, 'from env import DrivingEnv\n'), ((2488, 2510), 'solvers.SampleGraphSolver', 'SampleGraphSolver', (['(800)'], {}), '(800)\n', (2505, 2510), False, 'from solvers import GridSolver, SampleGraphSolver\n'), ((2605, 2620), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)'], {}), '(1)\n', (2617, 2620), True, 'from matplotlib import pyplot as plt\n'), ((2673, 2731), 'matplotlib.pyplot.title', 'plt.title', (["('Graph-based solution with %s cost' % cost_type)"], {}), "('Graph-based solution with %s cost' % cost_type)\n", (2682, 2731), True, 'from matplotlib import pyplot as plt\n'), ((2736, 2746), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2744, 2746), True, 'from matplotlib import pyplot as plt\n'), ((2820, 2851), 'numpy.logspace', 'np.logspace', (['(-3)', '(3)', 'ratio_count'], {}), '(-3, 3, ratio_count)\n', (2831, 2851), True, 'import numpy as np\n'), ((2867, 2882), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)'], {}), '(1)\n', (2879, 2882), True, 'from matplotlib import pyplot as plt\n'), ((3827, 3879), 'matplotlib.pyplot.title', 'plt.title', (['"""Difference path under different weights"""'], {}), "('Difference path under different weights')\n", (3836, 3879), True, 'from matplotlib import pyplot as plt\n'), ((3884, 3894), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3892, 3894), True, 'from matplotlib import pyplot as plt\n'), ((363, 395), 'env.DrivingEnv', 'DrivingEnv', (['(15)'], {'random_seed': 'seed'}), '(15, random_seed=seed)\n', (373, 395), False, 'from env import DrivingEnv\n'), ((413, 429), 'solvers.GridSolver', 'GridSolver', (['size'], {}), '(size)\n', (423, 429), False, 'from solvers import GridSolver, SampleGraphSolver\n'), ((505, 537), 'env.DrivingEnv', 'DrivingEnv', (['(15)'], {'random_seed': 'seed'}), '(15, random_seed=seed)\n', (515, 537), False, 'from env import DrivingEnv\n'), ((555, 585), 'solvers.SampleGraphSolver', 'SampleGraphSolver', (['(size * size)'], {}), '(size * size)\n', (572, 585), False, 'from solvers import GridSolver, SampleGraphSolver\n'), ((1483, 1509), 'numpy.mean', 'np.mean', (['cost_list'], {'axis': '(1)'}), '(cost_list, axis=1)\n', (1490, 1509), True, 'import numpy as np\n'), ((3024, 3038), 'numpy.sqrt', 'np.sqrt', (['ratio'], {}), '(ratio)\n', (3031, 3038), True, 'import numpy as np\n'), ((3053, 3085), 'env.DrivingEnv', 'DrivingEnv', (['(15)'], {'random_seed': 'seed'}), '(15, random_seed=seed)\n', (3063, 3085), False, 'from env import DrivingEnv\n'), ((3103, 3125), 'solvers.SampleGraphSolver', 'SampleGraphSolver', (['(800)'], {}), '(800)\n', (3120, 3125), False, 'from solvers import GridSolver, SampleGraphSolver\n'), ((223, 265), 'numpy.linspace', 'np.linspace', (['min_sample', 'max_sample', 'count'], {}), '(min_sample, max_sample, count)\n', (234, 265), True, 'import numpy as np\n'), ((1050, 1092), 'numpy.linspace', 'np.linspace', (['min_sample', 'max_sample', 'count'], {}), '(min_sample, max_sample, count)\n', (1061, 1092), True, 'import numpy as np\n'), ((1228, 1258), 'solvers.SampleGraphSolver', 'SampleGraphSolver', (['(size * size)'], {}), '(size * size)\n', (1245, 1258), False, 'from solvers import GridSolver, SampleGraphSolver\n'), ((2887, 2919), 'env.DrivingEnv', 'DrivingEnv', (['(15)'], {'random_seed': 'seed'}), '(15, random_seed=seed)\n', (2897, 2919), False, 'from env import DrivingEnv\n')] |
import cherrypy, cherrypy_cors, os
import tca_ng.example_maps
import tca_ng.models
import random
class TCAServer(object):
@cherrypy.expose
@cherrypy.tools.json_out()
def start(self):
self.automaton = tca_ng.models.Automaton()
self.automaton.topology = tca_ng.example_maps.simple_map(10)
return self.automaton.topology.json_view()
@cherrypy.expose
@cherrypy.tools.json_out()
def update(self):
self.automaton.update()
print()
print('total cars', len(self.automaton.topology.cars))
for car in self.automaton.topology.cars:
if car.id % 10 == 0:
print('car %3s %8s route: %s' % (
car.id,
tuple(car.cell.viewer_address),
car.route
))
# modify a light
light = random.choice(self.automaton.topology.lights)
change = random.randint(-2, 2)
print(light, light.time, change)
light.time += change
print()
return self.automaton.topology.json_view()
PATH = os.path.abspath(os.path.dirname(__file__))
def serve(ip, port):
cherrypy_cors.install()
config = {
'/': {
'tools.staticdir.on': True,
'tools.staticdir.dir': PATH,
'tools.staticdir.index': 'index.html',
'cors.expose.on': True,
}
}
cherrypy.server.socket_host = ip
cherrypy.server.socket_port = port
cherrypy.quickstart(TCAServer(), '/', config)
if __name__ == '__main__':
serve('localhost', 5555)
| [
"cherrypy.tools.json_out",
"random.choice",
"cherrypy_cors.install",
"os.path.dirname",
"random.randint"
] | [((155, 180), 'cherrypy.tools.json_out', 'cherrypy.tools.json_out', ([], {}), '()\n', (178, 180), False, 'import cherrypy, cherrypy_cors, os\n'), ((404, 429), 'cherrypy.tools.json_out', 'cherrypy.tools.json_out', ([], {}), '()\n', (427, 429), False, 'import cherrypy, cherrypy_cors, os\n'), ((1154, 1179), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (1169, 1179), False, 'import cherrypy, cherrypy_cors, os\n'), ((1208, 1231), 'cherrypy_cors.install', 'cherrypy_cors.install', ([], {}), '()\n', (1229, 1231), False, 'import cherrypy, cherrypy_cors, os\n'), ((895, 940), 'random.choice', 'random.choice', (['self.automaton.topology.lights'], {}), '(self.automaton.topology.lights)\n', (908, 940), False, 'import random\n'), ((958, 979), 'random.randint', 'random.randint', (['(-2)', '(2)'], {}), '(-2, 2)\n', (972, 979), False, 'import random\n')] |
from rest_framework import viewsets
from api.serializers import LabelSerializer, ItemSerializer
from api.models import Label, Item
class LabelViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows labels to be viewed or edited.
"""
queryset = Label.objects.all().order_by('name')
serializer_class = LabelSerializer
class ItemViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows items to be viewed or edited.
"""
queryset = Item.objects.all().order_by('title')
serializer_class = ItemSerializer
| [
"api.models.Label.objects.all",
"api.models.Item.objects.all"
] | [((268, 287), 'api.models.Label.objects.all', 'Label.objects.all', ([], {}), '()\n', (285, 287), False, 'from api.models import Label, Item\n'), ((478, 496), 'api.models.Item.objects.all', 'Item.objects.all', ([], {}), '()\n', (494, 496), False, 'from api.models import Label, Item\n')] |
import numpy as np
import math
from scipy.stats import truncnorm
class ElectricMotor:
"""
Base class for all technical electrical motor models.
A motor consists of the ode-state. These are the dynamic quantities of its ODE.
For example:
ODE-State of a DC-shunt motor: `` [i_a, i_e ] ``
* i_a: Anchor circuit current
* i_e: Exciting circuit current
Each electric motor can be parametrized by a dictionary of motor parameters,
the nominal state dictionary and the limit dictionary.
Initialization is given by initializer(dict). Can be constant state value
or random value in given interval.
dict should be like:
{ 'states'(dict): with state names and initital values
'interval'(array like): boundaries for each state
(only for random init), shape(num states, 2)
'random_init'(str): 'uniform' or 'normal'
'random_params(tuple): mue(float), sigma(int)
Example initializer(dict) for constant initialization:
{ 'states': {'omega': 16.0}}
Example initializer(dict) for random initialization:
{ 'random_init': 'normal'}
"""
#: Parameter indicating if the class is implementing the optional jacobian function
HAS_JACOBIAN = False
#: CURRENTS_IDX(list(int)): Indices for accessing all motor currents.
CURRENTS_IDX = []
#: CURRENTS(list(str)): List of the motor currents names
CURRENTS = []
#: VOLTAGES(list(str)): List of the motor input voltages names
VOLTAGES = []
#: _default_motor_parameter(dict): Default parameter dictionary for the motor
_default_motor_parameter = {}
#: _default_nominal_values(dict(float)): Default nominal motor state array
_default_nominal_values = {}
#: _default_limits(dict(float)): Default motor limits (0 for unbounded limits)
_default_limits = {}
#: _default_initial_state(dict): Default initial motor-state values
#_default_initializer = {}
_default_initializer = {'states': {},
'interval': None,
'random_init': None,
'random_params': None}
#: _default_initial_limits(dict): Default limit for initialization
_default_initial_limits = {}
@property
def nominal_values(self):
"""
Readonly motors nominal values.
Returns:
dict(float): Current nominal values of the motor.
"""
return self._nominal_values
@property
def limits(self):
"""
Readonly motors limit state array. Entries are set to the maximum physical possible values
in case of unspecified limits.
Returns:
dict(float): Limits of the motor.
"""
return self._limits
@property
def motor_parameter(self):
"""
Returns:
dict(float): The motors parameter dictionary
"""
return self._motor_parameter
@property
def initializer(self):
"""
Returns:
dict: Motor initial state and additional initializer parameter
"""
return self._initializer
@property
def initial_limits(self):
"""
Returns:
dict: nominal motor limits for choosing initial values
"""
return self._initial_limits
def __init__(self, motor_parameter=None, nominal_values=None,
limit_values=None, motor_initializer=None, initial_limits=None,
**__):
"""
:param motor_parameter: Motor parameter dictionary. Contents specified
for each motor.
:param nominal_values: Nominal values for the motor quantities.
:param limit_values: Limits for the motor quantities.
:param motor_initializer: Initial motor states (currents)
('constant', 'uniform', 'gaussian' sampled from
given interval or out of nominal motor values)
:param initial_limits: limits for of the initial state-value
"""
motor_parameter = motor_parameter or {}
self._motor_parameter = self._default_motor_parameter.copy()
self._motor_parameter.update(motor_parameter)
limit_values = limit_values or {}
self._limits = self._default_limits.copy()
self._limits.update(limit_values)
nominal_values = nominal_values or {}
self._nominal_values = self._default_nominal_values.copy()
self._nominal_values.update(nominal_values)
motor_initializer = motor_initializer or {}
self._initializer = self._default_initializer.copy()
self._initializer.update(motor_initializer)
self._initial_states = {}
if self._initializer['states'] is not None:
self._initial_states.update(self._initializer['states'])
# intialize limits, in general they're not needed to be changed
# during training or episodes
initial_limits = initial_limits or {}
self._initial_limits = self._nominal_values.copy()
self._initial_limits.update(initial_limits)
# preventing wrong user input for the basic case
assert isinstance(self._initializer, dict), 'wrong initializer'
def electrical_ode(self, state, u_in, omega, *_):
"""
Calculation of the derivatives of each motor state variable for the given inputs / The motors ODE-System.
Args:
state(ndarray(float)): The motors state.
u_in(list(float)): The motors input voltages.
omega(float): Angular velocity of the motor
Returns:
ndarray(float): Derivatives of the motors ODE-system for the given inputs.
"""
raise NotImplementedError
def electrical_jacobian(self, state, u_in, omega, *_):
"""
Calculation of the jacobian of each motor ODE for the given inputs / The motors ODE-System.
Overriding this method is optional for each subclass. If it is overridden, the parameter HAS_JACOBIAN must also
be set to True. Otherwise, the jacobian will not be called.
Args:
state(ndarray(float)): The motors state.
u_in(list(float)): The motors input voltages.
omega(float): Angular velocity of the motor
Returns:
Tuple(ndarray, ndarray, ndarray):
[0]: Derivatives of all electrical motor states over all electrical motor states shape:(states x states)
[1]: Derivatives of all electrical motor states over omega shape:(states,)
[2]: Derivative of Torque over all motor states shape:(states,)
"""
pass
def initialize(self,
state_space,
state_positions,
**__):
"""
Initializes given state values. Values can be given as a constant or
sampled random out of a statistical distribution. Initial value is in
range of the nominal values or a given interval. Values are written in
initial_states attribute
Args:
state_space(gym.Box): normalized state space boundaries (given by
physical system)
state_positions(dict): indexes of system states (given by physical
system)
Returns:
"""
# for organization purposes
interval = self._initializer['interval']
random_dist = self._initializer['random_init']
random_params = self._initializer['random_params']
self._initial_states.update(self._default_initializer['states'])
if self._initializer['states'] is not None:
self._initial_states.update(self._initializer['states'])
# different limits for InductionMotor
if any(map(lambda state: state in self._initial_states.keys(),
['psi_ralpha', 'psi_rbeta'])):
nominal_values_ = [self._initial_limits[state]
for state in self._initial_states]
upper_bound = np.asarray(np.abs(nominal_values_), dtype=float)
# state space for Induction Envs based on documentation
# ['i_salpha', 'i_sbeta', 'psi_ralpha', 'psi_rbeta', 'epsilon']
# hardcoded for Inductionmotors currently given in the toolbox
state_space_low = np.array([-1, -1, -1, -1, -1])
lower_bound = upper_bound * state_space_low
else:
if isinstance(self._nominal_values, dict):
nominal_values_ = [self._nominal_values[state]
for state in self._initial_states.keys()]
nominal_values_ = np.asarray(nominal_values_)
else:
nominal_values_ = np.asarray(self._nominal_values)
state_space_idx = [state_positions[state] for state in
self._initial_states.keys()]
upper_bound = np.asarray(nominal_values_, dtype=float)
lower_bound = upper_bound * \
np.asarray(state_space.low, dtype=float)[state_space_idx]
# clip nominal boundaries to user defined
if interval is not None:
lower_bound = np.clip(lower_bound,
a_min=
np.asarray(interval, dtype=float).T[0],
a_max=None)
upper_bound = np.clip(upper_bound,
a_min=None,
a_max=
np.asarray(interval, dtype=float).T[1])
# random initialization for each motor state (current, epsilon)
if random_dist is not None:
if random_dist == 'uniform':
initial_value = (upper_bound - lower_bound) * \
np.random.random_sample(
len(self._initial_states.keys())) + \
lower_bound
# writing initial values in initial_states dict
random_states = \
{state: initial_value[idx]
for idx, state in enumerate(self._initial_states.keys())}
self._initial_states.update(random_states)
elif random_dist in ['normal', 'gaussian']:
# specific input or middle of interval
mue = random_params[0] or (upper_bound - lower_bound) / 2 + lower_bound
sigma = random_params[1] or 1
a, b = (lower_bound - mue) / sigma, (upper_bound - mue) / sigma
initial_value = truncnorm.rvs(a, b,
loc=mue,
scale=sigma,
size=(len(self._initial_states.keys())))
# writing initial values in initial_states dict
random_states = \
{state: initial_value[idx]
for idx, state in enumerate(self._initial_states.keys())}
self._initial_states.update(random_states)
else:
# todo implement other distribution
raise NotImplementedError
# constant initialization for each motor state (current, epsilon)
elif self._initial_states is not None:
initial_value = np.atleast_1d(list(self._initial_states.values()))
# check init_value meets interval boundaries
if ((lower_bound <= initial_value).all()
and (initial_value <= upper_bound).all()):
initial_states_ = \
{state: initial_value[idx]
for idx, state in enumerate(self._initial_states.keys())}
self._initial_states.update(initial_states_)
else:
raise Exception('Initialization value has to be within nominal boundaries')
else:
raise Exception('No matching Initialization Case')
def reset(self,
state_space,
state_positions,
**__):
"""
Reset the motors state to a new initial state. (Default 0)
Args:
state_space(gym.Box): normalized state space boundaries
state_positions(dict): indexes of system states
Returns:
numpy.ndarray(float): The initial motor states.
"""
# check for valid initializer
if self._initializer and self._initializer['states']:
self.initialize(state_space, state_positions)
return np.asarray(list(self._initial_states.values()))
else:
return np.zeros(len(self.CURRENTS))
def i_in(self, state):
"""
Args:
state(ndarray(float)): ODE state of the motor
Returns:
list(float): List of all currents flowing into the motor.
"""
raise NotImplementedError
def _update_limits(self, limits_d={}, nominal_d={}):
"""Replace missing limits and nominal values with physical maximums.
Args:
limits_d(dict): Mapping: quantitity to its limit if not specified
"""
# omega is replaced the same way for all motor types
limits_d.update(dict(omega=self._default_limits['omega']))
for qty, lim in limits_d.items():
if self._limits.get(qty, 0) == 0:
self._limits[qty] = lim
for entry in self._limits.keys():
if self._nominal_values.get(entry, 0) == 0:
self._nominal_values[entry] = nominal_d.get(entry, None) or \
self._limits[entry]
def _update_initial_limits(self, nominal_new={}, **kwargs):
"""
Complete initial states with further state limits
Args:
nominal_new(dict): new/further state limits
"""
self._initial_limits.update(nominal_new)
class DcMotor(ElectricMotor):
"""
The DcMotor and its subclasses implement the technical system of a dc motor.
This includes the system equations, the motor parameters of the equivalent circuit diagram,
as well as limits.
===================== ========== ============= ===========================================
Motor Parameter Unit Default Value Description
===================== ========== ============= ===========================================
r_a Ohm 0.78 Armature circuit resistance
r_e Ohm 25 Exciting circuit resistance
l_a H 6.3e-3 Armature circuit inductance
l_e H 1.2 Exciting circuit inductance
l_e_prime H 0.0094 Effective excitation inductance
j_rotor kg/m^2 0.017 Moment of inertia of the rotor
===================== ========== ============= ===========================================
=============== ====== =============================================
Motor Currents Unit Description
=============== ====== =============================================
i_a A Armature circuit current
i_e A Exciting circuit current
=============== ====== =============================================
=============== ====== =============================================
Motor Voltages Unit Description
=============== ====== =============================================
u_a V Armature circuit voltage
u_e v Exciting circuit voltage
=============== ====== =============================================
======== ===========================================================
Limits / Nominal Value Dictionary Entries:
-------- -----------------------------------------------------------
Entry Description
======== ===========================================================
i_a Armature current
i_e Exciting current
omega Angular Velocity
torque Motor generated torque
u_a Armature Voltage
u_e Exciting Voltage
======== ===========================================================
"""
# Indices for array accesses
I_A_IDX = 0
I_E_IDX = 1
CURRENTS_IDX = [0, 1]
CURRENTS = ['i_a', 'i_e']
VOLTAGES = ['u_a', 'u_e']
_default_motor_parameter = {
'r_a': 0.78, 'r_e': 25, 'l_a': 6.3e-3, 'l_e': 1.2, 'l_e_prime': 0.0094,
'j_rotor': 0.017,
}
_default_nominal_values = {'omega': 368, 'torque': 0.0, 'i_a': 50,
'i_e': 1.2, 'u': 420}
_default_limits = {'omega': 500, 'torque': 0.0, 'i_a': 75, 'i_e': 2,
'u': 420}
_default_initializer = {'states': {'i_a': 0.0, 'i_e': 0.0},
'interval': None,
'random_init': None,
'random_params': (None, None)}
def __init__(self, motor_parameter=None, nominal_values=None,
limit_values=None, motor_initializer=None, **__):
# Docstring of superclass
super().__init__(motor_parameter, nominal_values,
limit_values, motor_initializer)
#: Matrix that contains the constant parameters of the systems equation for faster computation
self._model_constants = None
self._update_model()
self._update_limits()
def _update_model(self):
"""
Update the motors model parameters with the motor parameters.
Called internally when the motor parameters are changed or the motor is initialized.
"""
mp = self._motor_parameter
self._model_constants = np.array([
[-mp['r_a'], 0, -mp['l_e_prime'], 1, 0],
[0, -mp['r_e'], 0, 0, 1]
])
self._model_constants[self.I_A_IDX] = self._model_constants[
self.I_A_IDX] / mp['l_a']
self._model_constants[self.I_E_IDX] = self._model_constants[
self.I_E_IDX] / mp['l_e']
def torque(self, currents):
# Docstring of superclass
return self._motor_parameter['l_e_prime'] * currents[self.I_A_IDX] * \
currents[self.I_E_IDX]
def i_in(self, currents):
# Docstring of superclass
return list(currents)
def electrical_ode(self, state, u_in, omega, *_):
# Docstring of superclass
return np.matmul(self._model_constants, np.array([
state[self.I_A_IDX],
state[self.I_E_IDX],
omega * state[self.I_E_IDX],
u_in[0],
u_in[1],
]))
def get_state_space(self, input_currents, input_voltages):
"""
Calculate the possible normalized state space for the motor as a tuple of dictionaries "low" and "high".
Args:
input_currents: Tuple of the two converters possible output currents.
input_voltages: Tuple of the two converters possible output voltages.
Returns:
tuple(dict,dict): Dictionaries defining if positive and negative values are possible for each motors state.
"""
a_converter = 0
e_converter = 1
low = {
'omega': -1 if input_voltages.low[a_converter] == -1
or input_voltages.low[e_converter] == -1 else 0,
'torque': -1 if input_currents.low[a_converter] == -1
or input_currents.low[e_converter] == -1 else 0,
'i_a': -1 if input_currents.low[a_converter] == -1 else 0,
'i_e': -1 if input_currents.low[e_converter] == -1 else 0,
'u_a': -1 if input_voltages.low[a_converter] == -1 else 0,
'u_e': -1 if input_voltages.low[e_converter] == -1 else 0,
}
high = {
'omega': 1,
'torque': 1,
'i_a': 1,
'i_e': 1,
'u_a': 1,
'u_e': 1
}
return low, high
def _update_limits(self, limits_d={}):
# Docstring of superclass
# torque is replaced the same way for all DC motors
limits_d.update(dict(torque=self.torque([self._limits[state] for state
in self.CURRENTS])))
super()._update_limits(limits_d)
class DcShuntMotor(DcMotor):
"""
The DcShuntMotor is a DC motor with parallel armature and exciting circuit connected to one input voltage.
===================== ========== ============= ===========================================
Motor Parameter Unit Default Value Description
===================== ========== ============= ===========================================
r_a Ohm 0.78 Armature circuit resistance
r_e Ohm 25 Exciting circuit resistance
l_a H 6.3e-3 Armature circuit inductance
l_e H 1.2 Exciting circuit inductance
l_e_prime H 0.0094 Effective excitation inductance
j_rotor kg/m^2 0.017 Moment of inertia of the rotor
===================== ========== ============= ===========================================
=============== ====== =============================================
Motor Currents Unit Description
=============== ====== =============================================
i_a A Armature circuit current
i_e A Exciting circuit current
=============== ====== =============================================
=============== ====== =============================================
Motor Voltages Unit Description
=============== ====== =============================================
u V Voltage applied to both circuits
=============== ====== =============================================
======== ===========================================================
Limits / Nominal Value Dictionary Entries:
-------- -----------------------------------------------------------
Entry Description
======== ===========================================================
i_a Armature current
i_e Exciting current
omega Angular Velocity
torque Motor generated torque
u Voltage
======== ===========================================================
"""
HAS_JACOBIAN = True
VOLTAGES = ['u']
_default_nominal_values = {'omega': 368, 'torque': 0.0, 'i_a': 50,
'i_e': 1.2, 'u': 420}
_default_limits = {'omega': 500, 'torque': 0.0, 'i_a': 75, 'i_e': 2,
'u': 420}
_default_initializer = {'states': {'i_a': 0.0, 'i_e': 0.0},
'interval': None,
'random_init': None,
'random_params': (None, None)}
def i_in(self, state):
# Docstring of superclass
return [state[self.I_A_IDX] + state[self.I_E_IDX]]
def electrical_ode(self, state, u_in, omega, *_):
# Docstring of superclass
return super().electrical_ode(state, (u_in[0], u_in[0]), omega)
def electrical_jacobian(self, state, u_in, omega, *_):
mp = self._motor_parameter
return (
np.array([
[-mp['r_a'] / mp['l_a'], -mp['l_e_prime'] / mp['l_a'] * omega],
[0, -mp['r_e'] / mp['l_e']]
]),
np.array([-mp['l_e_prime'] * state[self.I_E_IDX] / mp['l_a'], 0]),
np.array([mp['l_e_prime'] * state[self.I_E_IDX],
mp['l_e_prime'] * state[self.I_A_IDX]])
)
def get_state_space(self, input_currents, input_voltages):
"""
Calculate the possible normalized state space for the motor as a tuple of dictionaries "low" and "high".
Args:
input_currents: The converters possible output currents.
input_voltages: The converters possible output voltages.
Returns:
tuple(dict,dict): Dictionaries defining if positive and negative values are possible for each motors state.
"""
lower_limit = 0
low = {
'omega': 0,
'torque': -1 if input_currents.low[0] == -1 else 0,
'i_a': -1 if input_currents.low[0] == -1 else 0,
'i_e': -1 if input_currents.low[0] == -1 else 0,
'u': -1 if input_voltages.low[0] == -1 else 0,
}
high = {
'omega': 1,
'torque': 1,
'i_a': 1,
'i_e': 1,
'u': 1,
}
return low, high
def _update_limits(self):
# Docstring of superclass
# R_a might be 0, protect against that
r_a = 1 if self._motor_parameter['r_a'] == 0 else self._motor_parameter['r_a']
limit_agenda = \
{'u': self._default_limits['u'],
'i_a': self._limits.get('i', None) or
self._limits['u'] / r_a,
'i_e': self._limits.get('i', None) or
self._limits['u'] / self.motor_parameter['r_e'],
}
super()._update_limits(limit_agenda)
class DcSeriesMotor(DcMotor):
"""
The DcSeriesMotor is a DcMotor with an armature and exciting circuit connected in series to one input voltage.
===================== ========== ============= ===========================================
Motor Parameter Unit Default Value Description
===================== ========== ============= ===========================================
r_a Ohm 2.78 Armature circuit resistance
r_e Ohm 1.0 Exciting circuit resistance
l_a H 6.3e-3 Armature circuit inductance
l_e H 1.6e-3 Exciting circuit inductance
l_e_prime H 0.05 Effective excitation inductance
j_rotor kg/m^2 0.017 Moment of inertia of the rotor
===================== ========== ============= ===========================================
=============== ====== =============================================
Motor Currents Unit Description
=============== ====== =============================================
i A Circuit current
=============== ====== =============================================
=============== ====== =============================================
Motor Voltages Unit Description
=============== ====== =============================================
u V Circuit voltage
=============== ====== =============================================
======== ===========================================================
Limits / Nominal Value Dictionary Entries:
-------- -----------------------------------------------------------
Entry Description
======== ===========================================================
i Circuit Current
omega Angular Velocity
torque Motor generated torque
u Circuit Voltage
======== ===========================================================
"""
HAS_JACOBIAN = True
I_IDX = 0
CURRENTS_IDX = [0]
CURRENTS = ['i']
VOLTAGES = ['u']
_default_motor_parameter = {
'r_a': 2.78, 'r_e': 1.0, 'l_a': 6.3e-3, 'l_e': 1.6e-3,
'l_e_prime': 0.05, 'j_rotor': 0.017,
}
_default_nominal_values = dict(omega=80, torque=0.0, i=50, u=420)
_default_limits = dict(omega=100, torque=0.0, i=100, u=420)
_default_initializer = {'states': {'i': 0.0},
'interval': None,
'random_init': None,
'random_params': (None, None)}
def _update_model(self):
# Docstring of superclass
mp = self._motor_parameter
self._model_constants = np.array([
[-mp['r_a'] - mp['r_e'], -mp['l_e_prime'], 1]
])
self._model_constants[self.I_IDX] = self._model_constants[
self.I_IDX] / (
mp['l_a'] + mp['l_e'])
def torque(self, currents):
# Docstring of superclass
return super().torque([currents[self.I_IDX], currents[self.I_IDX]])
def electrical_ode(self, state, u_in, omega, *_):
# Docstring of superclass
return np.matmul(
self._model_constants,
np.array([
state[self.I_IDX],
omega * state[self.I_IDX],
u_in[0]
])
)
def i_in(self, state):
# Docstring of superclass
return state[self.CURRENTS_IDX]
def _update_limits(self):
# Docstring of superclass
# R_a might be 0, protect against that
r_a = 1 if self._motor_parameter['r_a'] == 0 else self._motor_parameter['r_a']
limits_agenda = {
'u': self._default_limits['u'],
'i': self._limits['u'] / (r_a + self._motor_parameter['r_e']),
}
super()._update_limits(limits_agenda)
def get_state_space(self, input_currents, input_voltages):
# Docstring of superclass
lower_limit = 0
low = {
'omega': 0,
'torque': 0,
'i': -1 if input_currents.low[0] == -1 else 0,
'u': -1 if input_voltages.low[0] == -1 else 0,
}
high = {
'omega': 1,
'torque': 1,
'i': 1,
'u': 1,
}
return low, high
def electrical_jacobian(self, state, u_in, omega, *_):
mp = self._motor_parameter
return (
np.array([[-(mp['r_a'] + mp['r_e'] + mp['l_e_prime'] * omega) / (
mp['l_a'] + mp['l_e'])]]),
np.array([-mp['l_e_prime'] * state[self.I_IDX] / (
mp['l_a'] + mp['l_e'])]),
np.array([2 * mp['l_e_prime'] * state[self.I_IDX]])
)
class DcPermanentlyExcitedMotor(DcMotor):
"""
The DcPermanentlyExcitedMotor is a DcMotor with a Permanent Magnet instead of the excitation circuit.
===================== ========== ============= ===========================================
Motor Parameter Unit Default Value Description
===================== ========== ============= ===========================================
r_a Ohm 25.0 Armature circuit resistance
l_a H 3.438e-2 Armature circuit inductance
psi_e Wb 18 Magnetic Flux of the permanent magnet
j_rotor kg/m^2 0.017 Moment of inertia of the rotor
===================== ========== ============= ===========================================
=============== ====== =============================================
Motor Currents Unit Description
=============== ====== =============================================
i A Circuit current
=============== ====== =============================================
=============== ====== =============================================
Motor Voltages Unit Description
=============== ====== =============================================
u V Circuit voltage
=============== ====== =============================================
======== ===========================================================
Limits / Nominal Value Dictionary Entries:
-------- -----------------------------------------------------------
Entry Description
======== ===========================================================
i Circuit Current
omega Angular Velocity
torque Motor generated torque
u Circuit Voltage
======== ===========================================================
"""
I_IDX = 0
CURRENTS_IDX = [0]
CURRENTS = ['i']
VOLTAGES = ['u']
HAS_JACOBIAN = True
_default_motor_parameter = {
'r_a': 25.0, 'l_a': 3.438e-2, 'psi_e': 18, 'j_rotor': 0.017
}
_default_nominal_values = dict(omega=22, torque=0.0, i=16, u=400)
_default_limits = dict(omega=50, torque=0.0, i=25, u=400)
_default_initializer = {'states': {'i': 0.0},
'interval': None,
'random_init': None,
'random_params': (None, None)}
# placeholder for omega, currents and u_in
_ode_placeholder = np.zeros(2 + len(CURRENTS_IDX), dtype=np.float64)
def torque(self, state):
# Docstring of superclass
return self._motor_parameter['psi_e'] * state[self.I_IDX]
def _update_model(self):
# Docstring of superclass
mp = self._motor_parameter
self._model_constants = np.array([
[-mp['psi_e'], -mp['r_a'], 1.0]
])
self._model_constants[self.I_IDX] /= mp['l_a']
def i_in(self, state):
# Docstring of superclass
return state[self.CURRENTS_IDX]
def electrical_ode(self, state, u_in, omega, *_):
# Docstring of superclass
self._ode_placeholder[:] = [omega] + np.atleast_1d(
state[self.I_IDX]).tolist() \
+ [u_in[0]]
return np.matmul(self._model_constants, self._ode_placeholder)
def electrical_jacobian(self, state, u_in, omega, *_):
mp = self._motor_parameter
return (
np.array([[-mp['r_a'] / mp['l_a']]]),
np.array([-mp['psi_e'] / mp['l_a']]),
np.array([mp['psi_e']])
)
def _update_limits(self):
# Docstring of superclass
# R_a might be 0, protect against that
r_a = 1 if self._motor_parameter['r_a'] == 0 else self._motor_parameter['r_a']
limits_agenda = {
'u': self._default_limits['u'],
'i': self._limits['u'] / r_a,
}
super()._update_limits(limits_agenda)
def get_state_space(self, input_currents, input_voltages):
# Docstring of superclass
lower_limit = 0
low = {
'omega': -1 if input_voltages.low[0] == -1 else 0,
'torque': -1 if input_currents.low[0] == -1 else 0,
'i': -1 if input_currents.low[0] == -1 else 0,
'u': -1 if input_voltages.low[0] == -1 else 0,
}
high = {
'omega': 1,
'torque': 1,
'i': 1,
'u': 1,
}
return low, high
class DcExternallyExcitedMotor(DcMotor):
# Equals DC Base Motor
HAS_JACOBIAN = True
def electrical_jacobian(self, state, u_in, omega, *_):
mp = self._motor_parameter
return (
np.array([
[-mp['r_a'] / mp['l_a'], -mp['l_e_prime'] / mp['l_a'] * omega],
[0, -mp['r_e'] / mp['l_e']]
]),
np.array([-mp['l_e_prime'] * state[self.I_E_IDX] / mp['l_a'], 0]),
np.array([mp['l_e_prime'] * state[self.I_E_IDX],
mp['l_e_prime'] * state[self.I_A_IDX]])
)
def _update_limits(self):
# Docstring of superclass
# R_a might be 0, protect against that
r_a = 1 if self._motor_parameter['r_a'] == 0 else self._motor_parameter['r_a']
limit_agenda = \
{'u_a': self._default_limits['u'],
'u_e': self._default_limits['u'],
'i_a': self._limits.get('i', None) or
self._limits['u'] / r_a,
'i_e': self._limits.get('i', None) or
self._limits['u'] / self.motor_parameter['r_e'],
}
super()._update_limits(limit_agenda)
class ThreePhaseMotor(ElectricMotor):
"""
The ThreePhaseMotor and its subclasses implement the technical system of Three Phase Motors.
This includes the system equations, the motor parameters of the equivalent circuit diagram,
as well as limits and bandwidth.
"""
# transformation matrix from abc to alpha-beta representation
_t23 = 2 / 3 * np.array([
[1, -0.5, -0.5],
[0, 0.5 * np.sqrt(3), -0.5 * np.sqrt(3)]
])
# transformation matrix from alpha-beta to abc representation
_t32 = np.array([
[1, 0],
[-0.5, 0.5 * np.sqrt(3)],
[-0.5, -0.5 * np.sqrt(3)]
])
@staticmethod
def t_23(quantities):
"""
Transformation from abc representation to alpha-beta representation
Args:
quantities: The properties in the abc representation like ''[u_a, u_b, u_c]''
Returns:
The converted quantities in the alpha-beta representation like ''[u_alpha, u_beta]''
"""
return np.matmul(ThreePhaseMotor._t23, quantities)
@staticmethod
def t_32(quantities):
"""
Transformation from alpha-beta representation to abc representation
Args:
quantities: The properties in the alpha-beta representation like ``[u_alpha, u_beta]``
Returns:
The converted quantities in the abc representation like ``[u_a, u_b, u_c]``
"""
return np.matmul(ThreePhaseMotor._t32, quantities)
@staticmethod
def q(quantities, epsilon):
"""
Transformation of the dq-representation into alpha-beta using the electrical angle
Args:
quantities: Array of two quantities in dq-representation. Example [i_d, i_q]
epsilon: Current electrical angle of the motor
Returns:
Array of the two quantities converted to alpha-beta-representation. Example [u_alpha, u_beta]
"""
cos = math.cos(epsilon)
sin = math.sin(epsilon)
return cos * quantities[0] - sin * quantities[1], sin * quantities[
0] + cos * quantities[1]
@staticmethod
def q_inv(quantities, epsilon):
"""
Transformation of the alpha-beta-representation into dq using the electrical angle
Args:
quantities: Array of two quantities in alpha-beta-representation. Example [u_alpha, u_beta]
epsilon: Current electrical angle of the motor
Returns:
Array of the two quantities converted to dq-representation. Example [u_d, u_q]
Note:
The transformation from alpha-beta to dq is just its inverse conversion with negated epsilon.
So this method calls q(quantities, -epsilon).
"""
return SynchronousMotor.q(quantities, -epsilon)
def q_me(self, quantities, epsilon):
"""
Transformation of the dq-representation into alpha-beta using the mechanical angle
Args:
quantities: Array of two quantities in dq-representation. Example [i_d, i_q]
epsilon: Current mechanical angle of the motor
Returns:
Array of the two quantities converted to alpha-beta-representation. Example [u_alpha, u_beta]
"""
return self.q(quantities, epsilon * self._motor_parameter['p'])
def q_inv_me(self, quantities, epsilon):
"""
Transformation of the alpha-beta-representation into dq using the mechanical angle
Args:
quantities: Array of two quantities in alpha-beta-representation. Example [u_alpha, u_beta]
epsilon: Current mechanical angle of the motor
Returns:
Array of the two quantities converted to dq-representation. Example [u_d, u_q]
Note:
The transformation from alpha-beta to dq is just its inverse conversion with negated epsilon.
So this method calls q(quantities, -epsilon).
"""
return self.q_me(quantities, -epsilon)
def _torque_limit(self):
"""
Returns:
Maximal possible torque for the given limits in self._limits
"""
raise NotImplementedError()
def _update_limits(self, limits_d={}, nominal_d={}):
# Docstring of superclass
super()._update_limits(limits_d, nominal_d)
super()._update_limits(dict(torque=self._torque_limit()))
def _update_initial_limits(self, nominal_new={}, **kwargs):
# Docstring of superclass
super()._update_initial_limits(self._nominal_values)
super()._update_initial_limits(nominal_new)
class SynchronousMotor(ThreePhaseMotor):
"""
The SynchronousMotor and its subclasses implement the technical system of a three phase synchronous motor.
This includes the system equations, the motor parameters of the equivalent circuit diagram,
as well as limits and bandwidth.
===================== ========== ============= ===========================================
Motor Parameter Unit Default Value Description
===================== ========== ============= ===========================================
r_s Ohm 0.78 Stator resistance
l_d H 1.2 Direct axis inductance
l_q H 6.3e-3 Quadrature axis inductance
psi_p Wb 0.0094 Effective excitation flux (PMSM only)
p 1 2 Pole pair number
j_rotor kg/m^2 0.017 Moment of inertia of the rotor
===================== ========== ============= ===========================================
=============== ====== =============================================
Motor Currents Unit Description
=============== ====== =============================================
i_sd A Direct axis current
i_sq A Quadrature axis current
i_a A Current through branch a
i_b A Current through branch b
i_c A Current through branch c
i_alpha A Current in alpha axis
i_beta A Current in beta axis
=============== ====== =============================================
=============== ====== =============================================
Motor Voltages Unit Description
=============== ====== =============================================
u_sd A Direct axis voltage
u_sq A Quadrature axis voltage
u_a A Voltage through branch a
u_b A Voltage through branch b
u_c A Voltage through branch c
u_alpha A Voltage in alpha axis
u_beta A Voltage in beta axis
=============== ====== =============================================
======== ===========================================================
Limits / Nominal Value Dictionary Entries:
-------- -----------------------------------------------------------
Entry Description
======== ===========================================================
i General current limit / nominal value
i_a Current in phase a
i_b Current in phase b
i_c Current in phase c
i_alpha Current in alpha axis
i_beta Current in beta axis
i_sd Current in direct axis
i_sq Current in quadrature axis
omega Mechanical angular Velocity
epsilon Electrical rotational angle
torque Motor generated torque
u_a Voltage in phase a
u_b Voltage in phase b
u_c Voltage in phase c
u_alpha Voltage in alpha axis
u_beta Voltage in beta axis
u_sd Voltage in direct axis
u_sq Voltage in quadrature axis
======== ===========================================================
Note:
The voltage limits should be the amplitude of the phase voltage (:math:`\hat{u}_S`).
Typically the rms value for the line voltage (:math:`U_L`) is given.
:math:`\hat{u}_S=\sqrt{2/3}~U_L`
The current limits should be the amplitude of the phase current (:math:`\hat{i}_S`).
Typically the rms value for the phase current (:math:`I_S`) is given.
:math:`\hat{i}_S = \sqrt{2}~I_S`
If not specified, nominal values are equal to their corresponding limit values.
Furthermore, if specific limits/nominal values (e.g. i_a) are not specified they are inferred from
the general limits/nominal values (e.g. i)
"""
I_SD_IDX = 0
I_SQ_IDX = 1
EPSILON_IDX = 2
CURRENTS_IDX = [0, 1]
CURRENTS = ['i_sd', 'i_sq']
VOLTAGES = ['u_sd', 'u_sq']
_model_constants = None
_initializer = None
def __init__(self, motor_parameter=None, nominal_values=None,
limit_values=None, motor_initializer=None, **kwargs):
# Docstring of superclass
nominal_values = nominal_values or {}
limit_values = limit_values or {}
super().__init__(motor_parameter, nominal_values,
limit_values, motor_initializer)
self._update_model()
self._update_limits()
@property
def motor_parameter(self):
# Docstring of superclass
return self._motor_parameter
@property
def initializer(self):
# Docstring of superclass
return self._initializer
def reset(self, state_space,
state_positions,
**__):
# Docstring of superclass
if self._initializer and self._initializer['states']:
self.initialize(state_space, state_positions)
return np.asarray(list(self._initial_states.values()))
else:
return np.zeros(len(self.CURRENTS) + 1)
def torque(self, state):
# Docstring of superclass
raise NotImplementedError
def _update_model(self):
"""
Set motor parameters into a matrix for faster computation
"""
raise NotImplementedError
def electrical_ode(self, state, u_dq, omega, *_):
"""
The differential equation of the Synchronous Motor.
Args:
state: The current state of the motor. [i_sd, i_sq, epsilon]
omega: The mechanical load
u_qd: The input voltages [u_sd, u_sq]
Returns:
The derivatives of the state vector d/dt([i_sd, i_sq, epsilon])
"""
return np.matmul(self._model_constants, np.array([
omega,
state[self.I_SD_IDX],
state[self.I_SQ_IDX],
u_dq[0],
u_dq[1],
omega * state[self.I_SD_IDX],
omega * state[self.I_SQ_IDX],
]))
def i_in(self, state):
# Docstring of superclass
return state[self.CURRENTS_IDX]
def _update_limits(self):
# Docstring of superclass
voltage_limit = 0.5 * self._limits['u']
voltage_nominal = 0.5 * self._nominal_values['u']
limits_agenda = {}
nominal_agenda = {}
for u, i in zip(self.IO_VOLTAGES, self.IO_CURRENTS):
limits_agenda[u] = voltage_limit
nominal_agenda[u] = voltage_nominal
limits_agenda[i] = self._limits.get('i', None) or \
self._limits[u] / self._motor_parameter['r_s']
nominal_agenda[i] = self._nominal_values.get('i', None) or \
self._nominal_values[u] / \
self._motor_parameter['r_s']
super()._update_limits(limits_agenda, nominal_agenda)
# def initialize(self,
# state_space,
# state_positions,
# **__):
# super().initialize(state_space, state_positions)
class SynchronousReluctanceMotor(SynchronousMotor):
"""
===================== ========== ============= ===========================================
Motor Parameter Unit Default Value Description
===================== ========== ============= ===========================================
r_s Ohm 0.78 Stator resistance
l_d H 1.2 Direct axis inductance
l_q H 6.3e-3 Quadrature axis inductance
p 1 2 Pole pair number
j_rotor kg/m^2 0.017 Moment of inertia of the rotor
===================== ========== ============= ===========================================
=============== ====== =============================================
Motor Currents Unit Description
=============== ====== =============================================
i_sd A Direct axis current
i_sq A Quadrature axis current
i_a A Current through branch a
i_b A Current through branch b
i_c A Current through branch c
i_alpha A Current in alpha axis
i_beta A Current in beta axis
=============== ====== =============================================
=============== ====== =============================================
Motor Voltages Unit Description
=============== ====== =============================================
u_sd V Direct axis voltage
u_sq V Quadrature axis voltage
u_a V Voltage through branch a
u_b V Voltage through branch b
u_c V Voltage through branch c
u_alpha V Voltage in alpha axis
u_beta V Voltage in beta axis
=============== ====== =============================================
======== ===========================================================
Limits / Nominal Value Dictionary Entries:
-------- -----------------------------------------------------------
Entry Description
======== ===========================================================
i General current limit / nominal value
i_a Current in phase a
i_b Current in phase b
i_c Current in phase c
i_alpha Current in alpha axis
i_beta Current in beta axis
i_sd Current in direct axis
i_sq Current in quadrature axis
omega Mechanical angular Velocity
epsilon Electrical rotational angle
torque Motor generated torque
u_a Voltage in phase a
u_b Voltage in phase b
u_c Voltage in phase c
u_alpha Voltage in alpha axis
u_beta Voltage in beta axis
u_sd Voltage in direct axis
u_sq Voltage in quadrature axis
======== ===========================================================
Note:
The voltage limits should be the amplitude of the phase voltage (:math:`\hat{u}_S`).
Typically the rms value for the line voltage (:math:`U_L`) is given.
:math:`\hat{u}_S=\sqrt{2/3}~U_L`
The current limits should be the amplitude of the phase current (:math:`\hat{i}_S`).
Typically the rms value for the phase current (:math:`I_S`) is given.
:math:`\hat{i}_S = \sqrt{2}~I_S`
If not specified, nominal values are equal to their corresponding limit values.
Furthermore, if specific limits/nominal values (e.g. i_a) are not specified they are inferred from
the general limits/nominal values (e.g. i)
"""
HAS_JACOBIAN = True
#### Parameters taken from DOI: 10.1109/AMC.2008.4516099 (<NAME>, <NAME>, <NAME>)
_default_motor_parameter = {'p': 4,
'l_d': 10.1e-3,
'l_q': 4.1e-3,
'j_rotor': 0.8e-3,
'r_s': 0.57
}
_default_nominal_values = {'i': 10, 'torque': 0, 'omega': 3e3 * np.pi / 30, 'epsilon': np.pi, 'u': 100}
_default_limits = {'i': 13, 'torque': 0, 'omega': 4.3e3 * np.pi / 30, 'epsilon': np.pi, 'u': 100}
_default_initializer = {'states': {'i_sq': 0.0, 'i_sd': 0.0, 'epsilon': 0.0},
'interval': None,
'random_init': None,
'random_params': (None, None)}
IO_VOLTAGES = ['u_a', 'u_b', 'u_c', 'u_sd', 'u_sq']
IO_CURRENTS = ['i_a', 'i_b', 'i_c', 'i_sd', 'i_sq']
def _update_model(self):
# Docstring of superclass
mp = self._motor_parameter
self._model_constants = np.array([
# omega, i_sd, i_sq, u_sd, u_sq, omega * i_sd, omega * i_sq
[ 0, -mp['r_s'], 0, 1, 0, 0, mp['l_q'] * mp['p']],
[ 0, 0, -mp['r_s'], 0, 1, -mp['l_d'] * mp['p'], 0],
[mp['p'], 0, 0, 0, 0, 0, 0]
])
self._model_constants[self.I_SD_IDX] = self._model_constants[self.I_SD_IDX] / mp['l_d']
self._model_constants[self.I_SQ_IDX] = self._model_constants[self.I_SQ_IDX] / mp['l_q']
def _torque_limit(self):
# Docstring of superclass
return self.torque([self._limits['i_sd'] / np.sqrt(2), self._limits['i_sq'] / np.sqrt(2), 0])
def torque(self, currents):
# Docstring of superclass
mp = self._motor_parameter
return 1.5 * mp['p'] * (
(mp['l_d'] - mp['l_q']) * currents[self.I_SD_IDX]) * \
currents[self.I_SQ_IDX]
def electrical_jacobian(self, state, u_in, omega, *_):
mp = self._motor_parameter
return (
np.array([
[-mp['r_s'] / mp['l_d'], mp['l_q'] / mp['l_d'] * mp['p'] * omega, 0],
[-mp['l_d'] / mp['l_q'] * mp['p'] * omega, -mp['r_s'] / mp['l_q'], 0],
[0, 0, 0]
]),
np.array([
mp['p'] * mp['l_q'] / mp['l_d'] * state[self.I_SQ_IDX],
- mp['p'] * mp['l_d'] / mp['l_q'] * state[self.I_SD_IDX],
mp['p']
]),
np.array([
1.5 * mp['p'] * (mp['l_d'] - mp['l_q']) * state[self.I_SQ_IDX],
1.5 * mp['p'] * (mp['l_d'] - mp['l_q']) * state[self.I_SD_IDX],
0
])
)
class PermanentMagnetSynchronousMotor(SynchronousMotor):
"""
===================== ========== ============= ===========================================
Motor Parameter Unit Default Value Description
===================== ========== ============= ===========================================
r_s Ohm 0.78 Stator resistance
l_d H 1.2 Direct axis inductance
l_q H 6.3e-3 Quadrature axis inductance
p 1 2 Pole pair number
j_rotor kg/m^2 0.017 Moment of inertia of the rotor
===================== ========== ============= ===========================================
=============== ====== =============================================
Motor Currents Unit Description
=============== ====== =============================================
i_sd A Direct axis current
i_sq A Quadrature axis current
i_a A Current through branch a
i_b A Current through branch b
i_c A Current through branch c
i_alpha A Current in alpha axis
i_beta A Current in beta axis
=============== ====== =============================================
=============== ====== =============================================
Motor Voltages Unit Description
=============== ====== =============================================
u_sd V Direct axis voltage
u_sq V Quadrature axis voltage
u_a V Voltage through branch a
u_b V Voltage through branch b
u_c V Voltage through branch c
u_alpha V Voltage in alpha axis
u_beta V Voltage in beta axis
=============== ====== =============================================
======== ===========================================================
Limits / Nominal Value Dictionary Entries:
-------- -----------------------------------------------------------
Entry Description
======== ===========================================================
i General current limit / nominal value
i_a Current in phase a
i_b Current in phase b
i_c Current in phase c
i_alpha Current in alpha axis
i_beta Current in beta axis
i_sd Current in direct axis
i_sq Current in quadrature axis
omega Mechanical angular Velocity
torque Motor generated torque
epsilon Electrical rotational angle
u_a Voltage in phase a
u_b Voltage in phase b
u_c Voltage in phase c
u_alpha Voltage in alpha axis
u_beta Voltage in beta axis
u_sd Voltage in direct axis
u_sq Voltage in quadrature axis
======== ===========================================================
Note:
The voltage limits should be the amplitude of the phase voltage (:math:`\hat{u}_S`).
Typically the rms value for the line voltage (:math:`U_L`) is given.
:math:`\hat{u}_S=\sqrt{2/3}~U_L`
The current limits should be the amplitude of the phase current (:math:`\hat{i}_S`).
Typically the rms value for the phase current (:math:`I_S`) is given.
:math:`\hat{i}_S = \sqrt{2}~I_S`
If not specified, nominal values are equal to their corresponding limit values.
Furthermore, if specific limits/nominal values (e.g. i_a) are not specified they are inferred from
the general limits/nominal values (e.g. i)
"""
#### Parameters taken from DOI: 10.1109/TPEL.2020.3006779 (<NAME>, <NAME>, <NAME>, <NAME>)
#### and DOI: 10.1109/IEMDC.2019.8785122 (<NAME>, <NAME>, <NAME>)
_default_motor_parameter = {
'p': 3,
'l_d': 0.37e-3,
'l_q': 1.2e-3,
'j_rotor': 0.3883,
'r_s': 18e-3,
'psi_p': 66e-3,
}
HAS_JACOBIAN = True
_default_limits = dict(omega=12e3 * np.pi / 30, torque=0.0, i=260, epsilon=math.pi, u=300)
_default_nominal_values = dict(omega=3e3 * np.pi / 30, torque=0.0, i=240, epsilon=math.pi, u=300)
_default_initializer = {'states': {'i_sq': 0.0, 'i_sd': 0.0, 'epsilon': 0.0},
'interval': None,
'random_init': None,
'random_params': (None, None)}
IO_VOLTAGES = ['u_a', 'u_b', 'u_c', 'u_sd', 'u_sq']
IO_CURRENTS = ['i_a', 'i_b', 'i_c', 'i_sd', 'i_sq']
def _update_model(self):
# Docstring of superclass
mp = self._motor_parameter
self._model_constants = np.array([
# omega, i_d, i_q, u_d, u_q, omega * i_d, omega * i_q
[ 0, -mp['r_s'], 0, 1, 0, 0, mp['l_q'] * mp['p']],
[-mp['psi_p'] * mp['p'], 0, -mp['r_s'], 0, 1, -mp['l_d'] * mp['p'], 0],
[ mp['p'], 0, 0, 0, 0, 0, 0],
])
self._model_constants[self.I_SD_IDX] = self._model_constants[self.I_SD_IDX] / mp['l_d']
self._model_constants[self.I_SQ_IDX] = self._model_constants[self.I_SQ_IDX] / mp['l_q']
def _torque_limit(self):
# Docstring of superclass
mp = self._motor_parameter
if mp['l_d'] == mp['l_q']:
return self.torque([0, self._limits['i_sq'], 0])
else:
i_n = self.nominal_values['i']
_p = mp['psi_p'] / (2 * (mp['l_d'] - mp['l_q']))
_q = - i_n ** 2 / 2
i_d_opt = - _p / 2 - np.sqrt( (_p / 2) ** 2 - _q)
i_q_opt = np.sqrt(i_n ** 2 - i_d_opt ** 2)
return self.torque([i_d_opt, i_q_opt, 0])
def torque(self, currents):
# Docstring of superclass
mp = self._motor_parameter
return 1.5 * mp['p'] * (mp['psi_p'] + (mp['l_d'] - mp['l_q']) * currents[self.I_SD_IDX]) * currents[self.I_SQ_IDX]
def electrical_jacobian(self, state, u_in, omega, *args):
mp = self._motor_parameter
return (
np.array([ # dx'/dx
[-mp['r_s'] / mp['l_d'], mp['l_q']/mp['l_d'] * omega * mp['p'], 0],
[-mp['l_d'] / mp['l_q'] * omega * mp['p'], - mp['r_s'] / mp['l_q'], 0],
[0, 0, 0]
]),
np.array([ # dx'/dw
mp['p'] * mp['l_q'] / mp['l_d'] * state[self.I_SQ_IDX],
- mp['p'] * mp['l_d'] / mp['l_q'] * state[self.I_SD_IDX] - mp['p'] * mp['psi_p'] / mp['l_q'],
mp['p']
]),
np.array([ # dT/dx
1.5 * mp['p'] * (mp['l_d'] - mp['l_q']) * state[self.I_SQ_IDX],
1.5 * mp['p'] * (mp['psi_p'] + (mp['l_d'] - mp['l_q']) * state[self.I_SD_IDX]),
0
])
)
class InductionMotor(ThreePhaseMotor):
"""
The InductionMotor and its subclasses implement the technical system of a three phase induction motor.
This includes the system equations, the motor parameters of the equivalent circuit diagram,
as well as limits and bandwidth.
===================== ========== ============= ===========================================
Motor Parameter Unit Default Value Description
===================== ========== ============= ===========================================
r_s Ohm 2.9338 Stator resistance
r_r Ohm 1.355 Rotor resistance
l_m H 143.75e-3 Main inductance
l_sigs H 5.87e-3 Stator-side stray inductance
l_sigr H 5.87e-3 Rotor-side stray inductance
p 1 2 Pole pair number
j_rotor kg/m^2 0.0011 Moment of inertia of the rotor
===================== ========== ============= ===========================================
=============== ====== =============================================
Motor Currents Unit Description
=============== ====== =============================================
i_sd A Direct axis current
i_sq A Quadrature axis current
i_sa A Current through branch a
i_sb A Current through branch b
i_sc A Current through branch c
i_salpha A Current in alpha axis
i_sbeta A Current in beta axis
=============== ====== =============================================
=============== ====== =============================================
Motor Voltages Unit Description
=============== ====== =============================================
u_sd V Direct axis voltage
u_sq V Quadrature axis voltage
u_sa V Voltage through branch a
u_sb V Voltage through branch b
u_sc V Voltage through branch c
u_salpha V Voltage in alpha axis
u_sbeta V Voltage in beta axis
=============== ====== =============================================
======== ===========================================================
Limits / Nominal Value Dictionary Entries:
-------- -----------------------------------------------------------
Entry Description
======== ===========================================================
i General current limit / nominal value
i_sa Current in phase a
i_sb Current in phase b
i_sc Current in phase c
i_salpha Current in alpha axis
i_sbeta Current in beta axis
i_sd Current in direct axis
i_sq Current in quadrature axis
omega Mechanical angular Velocity
torque Motor generated torque
u_sa Voltage in phase a
u_sb Voltage in phase b
u_sc Voltage in phase c
u_salpha Voltage in alpha axis
u_sbeta Voltage in beta axis
u_sd Voltage in direct axis
u_sq Voltage in quadrature axis
======== ===========================================================
Note:
The voltage limits should be the amplitude of the phase voltage (:math:`\hat{u}_S`).
Typically the rms value for the line voltage (:math:`U_L`) is given.
:math:`\hat{u}_S=\sqrt{2/3}~U_L`
The current limits should be the amplitude of the phase current (:math:`\hat{i}_S`).
Typically the rms value for the phase current (:math:`I_S`) is given.
:math:`\hat{i}_S = \sqrt{2}~I_S`
If not specified, nominal values are equal to their corresponding limit values.
Furthermore, if specific limits/nominal values (e.g. i_a) are not specified they are inferred from
the general limits/nominal values (e.g. i)
"""
I_SALPHA_IDX = 0
I_SBETA_IDX = 1
PSI_RALPHA_IDX = 2
PSI_RBETA_IDX = 3
EPSILON_IDX = 4
CURRENTS_IDX = [0, 1]
FLUX_IDX = [2, 3]
CURRENTS = ['i_salpha', 'i_sbeta']
FLUXES = ['psi_ralpha', 'psi_rbeta']
STATOR_VOLTAGES = ['u_salpha', 'u_sbeta']
IO_VOLTAGES = ['u_sa', 'u_sb', 'u_sc', 'u_salpha', 'u_sbeta', 'u_sd',
'u_sq']
IO_CURRENTS = ['i_sa', 'i_sb', 'i_sc', 'i_salpha', 'i_sbeta', 'i_sd',
'i_sq']
HAS_JACOBIAN = True
#### Parameters taken from DOI: 10.1109/EPEPEMC.2018.8522008 (<NAME>, <NAME>, <NAME>)
_default_motor_parameter = {
'p': 2,
'l_m': 143.75e-3,
'l_sigs': 5.87e-3,
'l_sigr': 5.87e-3,
'j_rotor': 1.1e-3,
'r_s': 2.9338,
'r_r': 1.355,
}
_default_limits = dict(omega=4e3 * np.pi / 30, torque=0.0, i=5.5, epsilon=math.pi, u=560)
_default_nominal_values = dict(omega=3e3 * np.pi / 30, torque=0.0, i=3.9, epsilon=math.pi, u=560)
_model_constants = None
_default_initializer = {'states': {'i_salpha': 0.0, 'i_sbeta': 0.0,
'psi_ralpha': 0.0, 'psi_rbeta': 0.0,
'epsilon': 0.0},
'interval': None,
'random_init': None,
'random_params': (None, None)}
_initializer = None
@property
def motor_parameter(self):
# Docstring of superclass
return self._motor_parameter
@property
def initializer(self):
# Docstring of superclass
return self._initializer
def __init__(self, motor_parameter=None, nominal_values=None,
limit_values=None, motor_initializer=None, initial_limits=None,
**__):
# Docstring of superclass
# convert placeholder i and u to actual IO quantities
_nominal_values = self._default_nominal_values.copy()
_nominal_values.update({u: _nominal_values['u'] for u in self.IO_VOLTAGES})
_nominal_values.update({i: _nominal_values['i'] for i in self.IO_CURRENTS})
del _nominal_values['u'], _nominal_values['i']
_nominal_values.update(nominal_values or {})
# same for limits
_limit_values = self._default_limits.copy()
_limit_values.update({u: _limit_values['u'] for u in self.IO_VOLTAGES})
_limit_values.update({i: _limit_values['i'] for i in self.IO_CURRENTS})
del _limit_values['u'], _limit_values['i']
_limit_values.update(limit_values or {})
super().__init__(motor_parameter, nominal_values,
limit_values, motor_initializer, initial_limits)
self._update_model()
self._update_limits(_limit_values, _nominal_values)
def reset(self,
state_space,
state_positions,
omega=None):
# Docstring of superclass
if self._initializer and self._initializer['states']:
self._update_initial_limits(omega=omega)
self.initialize(state_space, state_positions)
return np.asarray(list(self._initial_states.values()))
else:
return np.zeros(len(self.CURRENTS) + len(self.FLUXES) + 1)
def electrical_ode(self, state, u_sr_alphabeta, omega, *args):
"""
The differential equation of the Induction Motor.
Args:
state: The momentary state of the motor. [i_salpha, i_sbeta, psi_ralpha, psi_rbeta, epsilon]
omega: The mechanical load
u_sr_alphabeta: The input voltages [u_salpha, u_sbeta, u_ralpha, u_rbeta]
Returns:
The derivatives of the state vector d/dt( [i_salpha, i_sbeta, psi_ralpha, psi_rbeta, epsilon])
"""
return np.matmul(self._model_constants, np.array([
# omega, i_alpha, i_beta, psi_ralpha, psi_rbeta, omega * psi_ralpha, omega * psi_rbeta, u_salpha, u_sbeta, u_ralpha, u_rbeta,
omega,
state[self.I_SALPHA_IDX],
state[self.I_SBETA_IDX],
state[self.PSI_RALPHA_IDX],
state[self.PSI_RBETA_IDX],
omega * state[self.PSI_RALPHA_IDX],
omega * state[self.PSI_RBETA_IDX],
u_sr_alphabeta[0, 0],
u_sr_alphabeta[0, 1],
u_sr_alphabeta[1, 0],
u_sr_alphabeta[1, 1],
]))
def i_in(self, state):
# Docstring of superclass
return state[self.CURRENTS_IDX]
def _torque_limit(self):
# Docstring of superclass
mp = self._motor_parameter
return 1.5 * mp['p'] * mp['l_m'] ** 2/(mp['l_m']+mp['l_sigr']) * self._limits['i_sd'] * self._limits['i_sq'] / 2
def torque(self, states):
# Docstring of superclass
mp = self._motor_parameter
return 1.5 * mp['p'] * mp['l_m']/(mp['l_m'] + mp['l_sigr']) * (states[self.PSI_RALPHA_IDX] * states[self.I_SBETA_IDX] - states[self.PSI_RBETA_IDX] * states[self.I_SALPHA_IDX])
def _flux_limit(self, omega=0, eps_mag=0, u_q_max=0.0, u_rq_max=0.0):
"""
Calculate Flux limits for given current and magnetic-field angle
Args:
omega(float): speed given by mechanical load
eps_mag(float): magnetic field angle
u_q_max(float): maximal strator voltage in q-system
u_rq_max(float): maximal rotor voltage in q-system
returns:
maximal flux values(list) in alpha-beta-system
"""
mp = self.motor_parameter
l_s = mp['l_m'] + mp['l_sigs']
l_r = mp['l_m'] + mp['l_sigr']
l_mr = mp['l_m'] / l_r
sigma = (l_s * l_r - mp['l_m'] ** 2) / (l_s * l_r)
# limiting flux for a low omega
if omega == 0:
psi_d_max = mp['l_m'] * self._nominal_values['i_sd']
else:
i_d, i_q = self.q_inv([self._initial_states['i_salpha'],
self._initial_states['i_sbeta']],
eps_mag)
psi_d_max = mp['p'] * omega * sigma * l_s * i_d + \
(mp['r_s'] + mp['r_r'] * l_mr**2) * i_q + \
u_q_max + \
l_mr * u_rq_max
psi_d_max /= - mp['p'] * omega * l_mr
# clipping flux and setting nominal limit
psi_d_max = 0.9 * np.clip(psi_d_max, a_min=0, a_max=np.abs(mp['l_m'] * i_d))
# returning flux in alpha, beta system
return self.q([psi_d_max, 0], eps_mag)
def _update_model(self):
# Docstring of superclass
mp = self._motor_parameter
l_s = mp['l_m']+mp['l_sigs']
l_r = mp['l_m']+mp['l_sigr']
sigma = (l_s*l_r-mp['l_m']**2) /(l_s*l_r)
tau_r = l_r / mp['r_r']
tau_sig = sigma * l_s / (
mp['r_s'] + mp['r_r'] * (mp['l_m'] ** 2) / (l_r ** 2))
self._model_constants = np.array([
# omega, i_alpha, i_beta, psi_ralpha, psi_rbeta, omega * psi_ralpha, omega * psi_rbeta, u_salpha, u_sbeta, u_ralpha, u_rbeta,
[0, -1 / tau_sig, 0,mp['l_m'] * mp['r_r'] / (sigma * l_s * l_r ** 2), 0, 0,
+mp['l_m'] * mp['p'] / (sigma * l_r * l_s), 1 / (sigma * l_s), 0,
-mp['l_m'] / (sigma * l_r * l_s), 0, ], # i_ralpha_dot
[0, 0, -1 / tau_sig, 0,
mp['l_m'] * mp['r_r'] / (sigma * l_s * l_r ** 2),
-mp['l_m'] * mp['p'] / (sigma * l_r * l_s), 0, 0,
1 / (sigma * l_s), 0, -mp['l_m'] / (sigma * l_r * l_s), ],
# i_rbeta_dot
[0, mp['l_m'] / tau_r, 0, -1 / tau_r, 0, 0, -mp['p'], 0, 0, 1,
0, ], # psi_ralpha_dot
[0, 0, mp['l_m'] / tau_r, 0, -1 / tau_r, mp['p'], 0, 0, 0, 0, 1, ],
# psi_rbeta_dot
[mp['p'], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], # epsilon_dot
])
def electrical_jacobian(self, state, u_in, omega, *args):
mp = self._motor_parameter
l_s = mp['l_m'] + mp['l_sigs']
l_r = mp['l_m'] + mp['l_sigr']
sigma = (l_s * l_r - mp['l_m'] ** 2) / (l_s * l_r)
tau_r = l_r / mp['r_r']
tau_sig = sigma * l_s / (
mp['r_s'] + mp['r_r'] * (mp['l_m'] ** 2) / (l_r ** 2))
return (
np.array([ # dx'/dx
# i_alpha i_beta psi_alpha psi_beta epsilon
[-1 / tau_sig, 0,
mp['l_m'] * mp['r_r'] / (sigma * l_s * l_r ** 2),
omega * mp['l_m'] * mp['p'] / (sigma * l_r * l_s), 0],
[0, - 1 / tau_sig,
- omega * mp['l_m'] * mp['p'] / (sigma * l_r * l_s),
mp['l_m'] * mp['r_r'] / (sigma * l_s * l_r ** 2), 0],
[mp['l_m'] / tau_r, 0, - 1 / tau_r, - omega * mp['p'], 0],
[0, mp['l_m'] / tau_r, omega * mp['p'], - 1 / tau_r, 0],
[0, 0, 0, 0, 0]
]),
np.array([ # dx'/dw
mp['l_m'] * mp['p'] / (sigma * l_r * l_s) * state[
self.PSI_RBETA_IDX],
- mp['l_m'] * mp['p'] / (sigma * l_r * l_s) * state[
self.PSI_RALPHA_IDX],
- mp['p'] * state[self.PSI_RBETA_IDX],
mp['p'] * state[self.PSI_RALPHA_IDX],
mp['p']
]),
np.array([ # dT/dx
- state[self.PSI_RBETA_IDX] * 3 / 2 * mp['p'] * mp[
'l_m'] / l_r,
state[self.PSI_RALPHA_IDX] * 3 / 2 * mp['p'] * mp['l_m'] / l_r,
state[self.I_SBETA_IDX] * 3 / 2 * mp['p'] * mp['l_m'] / l_r,
- state[self.I_SALPHA_IDX] * 3 / 2 * mp['p'] * mp['l_m'] / l_r,
0
])
)
class SquirrelCageInductionMotor(InductionMotor):
"""
===================== ========== ============= ===========================================
Motor Parameter Unit Default Value Description
===================== ========== ============= ===========================================
r_s Ohm 2.9338 Stator resistance
r_r Ohm 1.355 Rotor resistance
l_m H 143.75e-3 Main inductance
l_sigs H 5.87e-3 Stator-side stray inductance
l_sigr H 5.87e-3 Rotor-side stray inductance
p 1 2 Pole pair number
j_rotor kg/m^2 0.0011 Moment of inertia of the rotor
===================== ========== ============= ===========================================
=============== ====== =============================================
Motor Currents Unit Description
=============== ====== =============================================
i_sd A Direct axis current
i_sq A Quadrature axis current
i_sa A Stator current through branch a
i_sb A Stator current through branch b
i_sc A Stator current through branch c
i_salpha A Stator current in alpha direction
i_sbeta A Stator current in beta direction
=============== ====== =============================================
=============== ====== =============================================
Rotor flux Unit Description
=============== ====== =============================================
psi_rd Vs Direct axis of the rotor oriented flux
psi_rq Vs Quadrature axis of the rotor oriented flux
psi_ra Vs Rotor oriented flux in branch a
psi_rb Vs Rotor oriented flux in branch b
psi_rc Vs Rotor oriented flux in branch c
psi_ralpha Vs Rotor oriented flux in alpha direction
psi_rbeta Vs Rotor oriented flux in beta direction
=============== ====== =============================================
=============== ====== =============================================
Motor Voltages Unit Description
=============== ====== =============================================
u_sd V Direct axis voltage
u_sq V Quadrature axis voltage
u_sa V Stator voltage through branch a
u_sb V Stator voltage through branch b
u_sc V Stator voltage through branch c
u_salpha V Stator voltage in alpha axis
u_sbeta V Stator voltage in beta axis
=============== ====== =============================================
======== ===========================================================
Limits / Nominal Value Dictionary Entries:
-------- -----------------------------------------------------------
Entry Description
======== ===========================================================
i General current limit / nominal value
i_sa Current in phase a
i_sb Current in phase b
i_sc Current in phase c
i_salpha Current in alpha axis
i_sbeta Current in beta axis
i_sd Current in direct axis
i_sq Current in quadrature axis
omega Mechanical angular Velocity
torque Motor generated torque
u_sa Voltage in phase a
u_sb Voltage in phase b
u_sc Voltage in phase c
u_salpha Voltage in alpha axis
u_sbeta Voltage in beta axis
u_sd Voltage in direct axis
u_sq Voltage in quadrature axis
======== ===========================================================
Note:
The voltage limits should be the amplitude of the phase voltage (:math:`\hat{u}_S`).
Typically the rms value for the line voltage (:math:`U_L`) is given.
:math:`\hat{u}_S=\sqrt{2/3}~U_L`
The current limits should be the amplitude of the phase current (:math:`\hat{i}_S`).
Typically the rms value for the phase current (:math:`I_S`) is given.
:math:`\hat{i}_S = \sqrt{2}~I_S`
If not specified, nominal values are equal to their corresponding limit values.
Furthermore, if specific limits/nominal values (e.g. i_a) are not specified they are inferred from
the general limits/nominal values (e.g. i)
"""
#### Parameters taken from DOI: 10.1109/EPEPEMC.2018.8522008 (<NAME>, <NAME>, <NAME>)
_default_motor_parameter = {
'p': 2,
'l_m': 143.75e-3,
'l_sigs': 5.87e-3,
'l_sigr': 5.87e-3,
'j_rotor': 1.1e-3,
'r_s': 2.9338,
'r_r': 1.355,
}
_default_limits = dict(omega=4e3 * np.pi / 30, torque=0.0, i=5.5, epsilon=math.pi, u=560)
_default_nominal_values = dict(omega=3e3 * np.pi / 30, torque=0.0, i=3.9, epsilon=math.pi, u=560)
_default_initializer = {'states': {'i_salpha': 0.0, 'i_sbeta': 0.0,
'psi_ralpha': 0.0, 'psi_rbeta': 0.0,
'epsilon': 0.0},
'interval': None,
'random_init': None,
'random_params': (None, None)}
def electrical_ode(self, state, u_salphabeta, omega, *args):
"""
The differential equation of the SCIM.
Sets u_ralpha = u_rbeta = 0 before calling the respective super function.
"""
u_ralphabeta = np.zeros_like(u_salphabeta)
u_sr_aphabeta = np.array([u_salphabeta, u_ralphabeta])
return super().electrical_ode(state, u_sr_aphabeta, omega, *args)
def _update_limits(self, limit_values={}, nominal_values={}):
# Docstring of superclass
voltage_limit = 0.5 * self._limits['u']
voltage_nominal = 0.5 * self._nominal_values['u']
limits_agenda = {}
nominal_agenda = {}
for u, i in zip(self.IO_VOLTAGES, self.IO_CURRENTS):
limits_agenda[u] = voltage_limit
nominal_agenda[u] = voltage_nominal
limits_agenda[i] = self._limits.get('i', None) or \
self._limits[u] / self._motor_parameter['r_s']
nominal_agenda[i] = self._nominal_values.get('i', None) or \
self._nominal_values[u] / self._motor_parameter['r_s']
super()._update_limits(limits_agenda, nominal_agenda)
def _update_initial_limits(self, nominal_new={}, omega=None):
# Docstring of superclass
# draw a sample magnetic field angle from [-pi,pi]
eps_mag = 2 * np.pi * np.random.random_sample() - np.pi
flux_alphabeta_limits = self._flux_limit(omega=omega,
eps_mag=eps_mag,
u_q_max=self._nominal_values['u_sq'])
# using absolute value, because limits should describe upper limit
# after abs-operator, norm of alphabeta flux still equal to
# d-component of flux
flux_alphabeta_limits = np.abs(flux_alphabeta_limits)
flux_nominal_limits = {state: value for state, value in
zip(self.FLUXES, flux_alphabeta_limits)}
flux_nominal_limits.update(nominal_new)
super()._update_initial_limits(flux_nominal_limits)
class DoublyFedInductionMotor(InductionMotor):
"""
===================== ========== ============= ===========================================
Motor Parameter Unit Default Value Description
===================== ========== ============= ===========================================
r_s Ohm 12e-3 Stator resistance
r_r Ohm 21e-3 Rotor resistance
l_m H 13.5e-3 Main inductance
l_sigs H 0.2e-3 Stator-side stray inductance
l_sigr H 0.1e-3 Rotor-side stray inductance
p 1 2 Pole pair number
j_rotor kg/m^2 1e3 Moment of inertia of the rotor
===================== ========== ============= ===========================================
=============== ====== =============================================
Motor Currents Unit Description
=============== ====== =============================================
i_sd A Direct axis current
i_sq A Quadrature axis current
i_sa A Current through branch a
i_sb A Current through branch b
i_sc A Current through branch c
i_salpha A Current in alpha axis
i_sbeta A Current in beta axis
=============== ====== =============================================
=============== ====== =============================================
Rotor flux Unit Description
=============== ====== =============================================
psi_rd Vs Direct axis of the rotor oriented flux
psi_rq Vs Quadrature axis of the rotor oriented flux
psi_ra Vs Rotor oriented flux in branch a
psi_rb Vs Rotor oriented flux in branch b
psi_rc Vs Rotor oriented flux in branch c
psi_ralpha Vs Rotor oriented flux in alpha direction
psi_rbeta Vs Rotor oriented flux in beta direction
=============== ====== =============================================
=============== ====== =============================================
Motor Voltages Unit Description
=============== ====== =============================================
u_sd V Direct axis voltage
u_sq V Quadrature axis voltage
u_sa V Stator voltage through branch a
u_sb V Stator voltage through branch b
u_sc V Stator voltage through branch c
u_salpha V Stator voltage in alpha axis
u_sbeta V Stator voltage in beta axis
u_ralpha V Rotor voltage in alpha axis
u_rbeta V Rotor voltage in beta axis
=============== ====== =============================================
======== ===========================================================
Limits / Nominal Value Dictionary Entries:
-------- -----------------------------------------------------------
Entry Description
======== ===========================================================
i General current limit / nominal value
i_sa Current in phase a
i_sb Current in phase b
i_sc Current in phase c
i_salpha Current in alpha axis
i_sbeta Current in beta axis
i_sd Current in direct axis
i_sq Current in quadrature axis
omega Mechanical angular Velocity
torque Motor generated torque
u_sa Voltage in phase a
u_sb Voltage in phase b
u_sc Voltage in phase c
u_salpha Voltage in alpha axis
u_sbeta Voltage in beta axis
u_sd Voltage in direct axis
u_sq Voltage in quadrature axis
u_ralpha Rotor voltage in alpha axis
u_rbeta Rotor voltage in beta axis
======== ===========================================================
Note:
The voltage limits should be the amplitude of the phase voltage (:math:`\hat{u}_S`).
Typically the rms value for the line voltage (:math:`U_L`) is given.
:math:`\hat{u}_S=\sqrt{2/3}~U_L`
The current limits should be the amplitude of the phase current (:math:`\hat{i}_S`).
Typically the rms value for the phase current (:math:`I_S`) is given.
:math:`\hat{i}_S = \sqrt{2}~I_S`
If not specified, nominal values are equal to their corresponding limit values.
Furthermore, if specific limits/nominal values (e.g. i_a) are not specified they are inferred from
the general limits/nominal values (e.g. i)
"""
ROTOR_VOLTAGES = ['u_ralpha', 'u_rbeta']
ROTOR_CURRENTS = ['i_ralpha', 'i_rbeta']
IO_ROTOR_VOLTAGES = ['u_ra', 'u_rb', 'u_rc', 'u_rd', 'u_rq']
IO_ROTOR_CURRENTS = ['i_ra', 'i_rb', 'i_rc', 'i_rd', 'i_rq']
#### Parameters taken from DOI: 10.1016/j.jestch.2016.01.015 (<NAME>, <NAME>, <NAME>)
_default_motor_parameter = {
'p': 2,
'l_m': 297.5e-3,
'l_sigs': 25.71e-3,
'l_sigr': 25.71e-3,
'j_rotor': 13.695e-3,
'r_s': 4.42,
'r_r': 3.51,
}
_default_limits = dict(omega=1800 * np.pi / 30, torque=0.0, i=9, epsilon=math.pi, u=720)
_default_nominal_values = dict(omega=1650 * np.pi / 30, torque=0.0, i=7.5, epsilon=math.pi, u=720)
_default_initializer = {'states': {'i_salpha': 0.0, 'i_sbeta': 0.0,
'psi_ralpha': 0.0, 'psi_rbeta': 0.0,
'epsilon': 0.0},
'interval': None,
'random_init': None,
'random_params': (None, None)}
def __init__(self, **kwargs):
self.IO_VOLTAGES += self.IO_ROTOR_VOLTAGES
self.IO_CURRENTS += self.IO_ROTOR_CURRENTS
super().__init__(**kwargs)
def _update_limits(self, limit_values={}, nominal_values={}):
# Docstring of superclass
voltage_limit = 0.5 * self._limits['u']
voltage_nominal = 0.5 * self._nominal_values['u']
limits_agenda = {}
nominal_agenda = {}
for u, i in zip(self.IO_VOLTAGES+self.ROTOR_VOLTAGES,
self.IO_CURRENTS+self.ROTOR_CURRENTS):
limits_agenda[u] = voltage_limit
nominal_agenda[u] = voltage_nominal
limits_agenda[i] = self._limits.get('i', None) or \
self._limits[u] / self._motor_parameter['r_r']
nominal_agenda[i] = self._nominal_values.get('i', None) or \
self._nominal_values[u] / \
self._motor_parameter['r_r']
super()._update_limits(limits_agenda, nominal_agenda)
def _update_initial_limits(self, nominal_new={}, omega=None):
# Docstring of superclass
# draw a sample magnetic field angle from [-pi,pi]
eps_mag = 2 * np.pi * np.random.random_sample() - np.pi
flux_alphabeta_limits = self._flux_limit(omega=omega,
eps_mag=eps_mag,
u_q_max=self._nominal_values['u_sq'],
u_rq_max=self._nominal_values['u_rq'])
flux_nominal_limits = {state: value for state, value in
zip(self.FLUXES, flux_alphabeta_limits)}
super()._update_initial_limits(flux_nominal_limits) | [
"numpy.abs",
"numpy.sqrt",
"numpy.random.random_sample",
"numpy.asarray",
"math.cos",
"numpy.array",
"numpy.matmul",
"math.sin",
"numpy.zeros_like",
"numpy.atleast_1d"
] | [((18618, 18695), 'numpy.array', 'np.array', (["[[-mp['r_a'], 0, -mp['l_e_prime'], 1, 0], [0, -mp['r_e'], 0, 0, 1]]"], {}), "([[-mp['r_a'], 0, -mp['l_e_prime'], 1, 0], [0, -mp['r_e'], 0, 0, 1]])\n", (18626, 18695), True, 'import numpy as np\n'), ((29603, 29660), 'numpy.array', 'np.array', (["[[-mp['r_a'] - mp['r_e'], -mp['l_e_prime'], 1]]"], {}), "([[-mp['r_a'] - mp['r_e'], -mp['l_e_prime'], 1]])\n", (29611, 29660), True, 'import numpy as np\n'), ((34832, 34875), 'numpy.array', 'np.array', (["[[-mp['psi_e'], -mp['r_a'], 1.0]]"], {}), "([[-mp['psi_e'], -mp['r_a'], 1.0]])\n", (34840, 34875), True, 'import numpy as np\n'), ((35322, 35377), 'numpy.matmul', 'np.matmul', (['self._model_constants', 'self._ode_placeholder'], {}), '(self._model_constants, self._ode_placeholder)\n', (35331, 35377), True, 'import numpy as np\n'), ((38868, 38911), 'numpy.matmul', 'np.matmul', (['ThreePhaseMotor._t23', 'quantities'], {}), '(ThreePhaseMotor._t23, quantities)\n', (38877, 38911), True, 'import numpy as np\n'), ((39305, 39348), 'numpy.matmul', 'np.matmul', (['ThreePhaseMotor._t32', 'quantities'], {}), '(ThreePhaseMotor._t32, quantities)\n', (39314, 39348), True, 'import numpy as np\n'), ((39830, 39847), 'math.cos', 'math.cos', (['epsilon'], {}), '(epsilon)\n', (39838, 39847), False, 'import math\n'), ((39863, 39880), 'math.sin', 'math.sin', (['epsilon'], {}), '(epsilon)\n', (39871, 39880), False, 'import math\n'), ((55462, 55607), 'numpy.array', 'np.array', (["[[0, -mp['r_s'], 0, 1, 0, 0, mp['l_q'] * mp['p']], [0, 0, -mp['r_s'], 0, 1,\n -mp['l_d'] * mp['p'], 0], [mp['p'], 0, 0, 0, 0, 0, 0]]"], {}), "([[0, -mp['r_s'], 0, 1, 0, 0, mp['l_q'] * mp['p']], [0, 0, -mp[\n 'r_s'], 0, 1, -mp['l_d'] * mp['p'], 0], [mp['p'], 0, 0, 0, 0, 0, 0]])\n", (55470, 55607), True, 'import numpy as np\n'), ((62464, 62633), 'numpy.array', 'np.array', (["[[0, -mp['r_s'], 0, 1, 0, 0, mp['l_q'] * mp['p']], [-mp['psi_p'] * mp['p'],\n 0, -mp['r_s'], 0, 1, -mp['l_d'] * mp['p'], 0], [mp['p'], 0, 0, 0, 0, 0, 0]]"], {}), "([[0, -mp['r_s'], 0, 1, 0, 0, mp['l_q'] * mp['p']], [-mp['psi_p'] *\n mp['p'], 0, -mp['r_s'], 0, 1, -mp['l_d'] * mp['p'], 0], [mp['p'], 0, 0,\n 0, 0, 0, 0]])\n", (62472, 62633), True, 'import numpy as np\n'), ((76319, 76895), 'numpy.array', 'np.array', (["[[0, -1 / tau_sig, 0, mp['l_m'] * mp['r_r'] / (sigma * l_s * l_r ** 2), 0, \n 0, +mp['l_m'] * mp['p'] / (sigma * l_r * l_s), 1 / (sigma * l_s), 0, -\n mp['l_m'] / (sigma * l_r * l_s), 0], [0, 0, -1 / tau_sig, 0, mp['l_m'] *\n mp['r_r'] / (sigma * l_s * l_r ** 2), -mp['l_m'] * mp['p'] / (sigma *\n l_r * l_s), 0, 0, 1 / (sigma * l_s), 0, -mp['l_m'] / (sigma * l_r * l_s\n )], [0, mp['l_m'] / tau_r, 0, -1 / tau_r, 0, 0, -mp['p'], 0, 0, 1, 0],\n [0, 0, mp['l_m'] / tau_r, 0, -1 / tau_r, mp['p'], 0, 0, 0, 0, 1], [mp[\n 'p'], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]"], {}), "([[0, -1 / tau_sig, 0, mp['l_m'] * mp['r_r'] / (sigma * l_s * l_r **\n 2), 0, 0, +mp['l_m'] * mp['p'] / (sigma * l_r * l_s), 1 / (sigma * l_s),\n 0, -mp['l_m'] / (sigma * l_r * l_s), 0], [0, 0, -1 / tau_sig, 0, mp[\n 'l_m'] * mp['r_r'] / (sigma * l_s * l_r ** 2), -mp['l_m'] * mp['p'] / (\n sigma * l_r * l_s), 0, 0, 1 / (sigma * l_s), 0, -mp['l_m'] / (sigma *\n l_r * l_s)], [0, mp['l_m'] / tau_r, 0, -1 / tau_r, 0, 0, -mp['p'], 0, 0,\n 1, 0], [0, 0, mp['l_m'] / tau_r, 0, -1 / tau_r, mp['p'], 0, 0, 0, 0, 1],\n [mp['p'], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])\n", (76327, 76895), True, 'import numpy as np\n'), ((85548, 85575), 'numpy.zeros_like', 'np.zeros_like', (['u_salphabeta'], {}), '(u_salphabeta)\n', (85561, 85575), True, 'import numpy as np\n'), ((85601, 85639), 'numpy.array', 'np.array', (['[u_salphabeta, u_ralphabeta]'], {}), '([u_salphabeta, u_ralphabeta])\n', (85609, 85639), True, 'import numpy as np\n'), ((87168, 87197), 'numpy.abs', 'np.abs', (['flux_alphabeta_limits'], {}), '(flux_alphabeta_limits)\n', (87174, 87197), True, 'import numpy as np\n'), ((8728, 8758), 'numpy.array', 'np.array', (['[-1, -1, -1, -1, -1]'], {}), '([-1, -1, -1, -1, -1])\n', (8736, 8758), True, 'import numpy as np\n'), ((9333, 9373), 'numpy.asarray', 'np.asarray', (['nominal_values_'], {'dtype': 'float'}), '(nominal_values_, dtype=float)\n', (9343, 9373), True, 'import numpy as np\n'), ((19456, 19560), 'numpy.array', 'np.array', (['[state[self.I_A_IDX], state[self.I_E_IDX], omega * state[self.I_E_IDX],\n u_in[0], u_in[1]]'], {}), '([state[self.I_A_IDX], state[self.I_E_IDX], omega * state[self.\n I_E_IDX], u_in[0], u_in[1]])\n', (19464, 19560), True, 'import numpy as np\n'), ((24653, 24761), 'numpy.array', 'np.array', (["[[-mp['r_a'] / mp['l_a'], -mp['l_e_prime'] / mp['l_a'] * omega], [0, -mp[\n 'r_e'] / mp['l_e']]]"], {}), "([[-mp['r_a'] / mp['l_a'], -mp['l_e_prime'] / mp['l_a'] * omega], [\n 0, -mp['r_e'] / mp['l_e']]])\n", (24661, 24761), True, 'import numpy as np\n'), ((24820, 24885), 'numpy.array', 'np.array', (["[-mp['l_e_prime'] * state[self.I_E_IDX] / mp['l_a'], 0]"], {}), "([-mp['l_e_prime'] * state[self.I_E_IDX] / mp['l_a'], 0])\n", (24828, 24885), True, 'import numpy as np\n'), ((24900, 24993), 'numpy.array', 'np.array', (["[mp['l_e_prime'] * state[self.I_E_IDX], mp['l_e_prime'] * state[self.I_A_IDX]]"], {}), "([mp['l_e_prime'] * state[self.I_E_IDX], mp['l_e_prime'] * state[\n self.I_A_IDX]])\n", (24908, 24993), True, 'import numpy as np\n'), ((30209, 30274), 'numpy.array', 'np.array', (['[state[self.I_IDX], omega * state[self.I_IDX], u_in[0]]'], {}), '([state[self.I_IDX], omega * state[self.I_IDX], u_in[0]])\n', (30217, 30274), True, 'import numpy as np\n'), ((31472, 31566), 'numpy.array', 'np.array', (["[[-(mp['r_a'] + mp['r_e'] + mp['l_e_prime'] * omega) / (mp['l_a'] + mp['l_e'])]\n ]"], {}), "([[-(mp['r_a'] + mp['r_e'] + mp['l_e_prime'] * omega) / (mp['l_a'] +\n mp['l_e'])]])\n", (31480, 31566), True, 'import numpy as np\n'), ((31599, 31673), 'numpy.array', 'np.array', (["[-mp['l_e_prime'] * state[self.I_IDX] / (mp['l_a'] + mp['l_e'])]"], {}), "([-mp['l_e_prime'] * state[self.I_IDX] / (mp['l_a'] + mp['l_e'])])\n", (31607, 31673), True, 'import numpy as np\n'), ((31710, 31761), 'numpy.array', 'np.array', (["[2 * mp['l_e_prime'] * state[self.I_IDX]]"], {}), "([2 * mp['l_e_prime'] * state[self.I_IDX]])\n", (31718, 31761), True, 'import numpy as np\n'), ((35507, 35543), 'numpy.array', 'np.array', (["[[-mp['r_a'] / mp['l_a']]]"], {}), "([[-mp['r_a'] / mp['l_a']]])\n", (35515, 35543), True, 'import numpy as np\n'), ((35558, 35594), 'numpy.array', 'np.array', (["[-mp['psi_e'] / mp['l_a']]"], {}), "([-mp['psi_e'] / mp['l_a']])\n", (35566, 35594), True, 'import numpy as np\n'), ((35609, 35632), 'numpy.array', 'np.array', (["[mp['psi_e']]"], {}), "([mp['psi_e']])\n", (35617, 35632), True, 'import numpy as np\n'), ((36804, 36912), 'numpy.array', 'np.array', (["[[-mp['r_a'] / mp['l_a'], -mp['l_e_prime'] / mp['l_a'] * omega], [0, -mp[\n 'r_e'] / mp['l_e']]]"], {}), "([[-mp['r_a'] / mp['l_a'], -mp['l_e_prime'] / mp['l_a'] * omega], [\n 0, -mp['r_e'] / mp['l_e']]])\n", (36812, 36912), True, 'import numpy as np\n'), ((36971, 37036), 'numpy.array', 'np.array', (["[-mp['l_e_prime'] * state[self.I_E_IDX] / mp['l_a'], 0]"], {}), "([-mp['l_e_prime'] * state[self.I_E_IDX] / mp['l_a'], 0])\n", (36979, 37036), True, 'import numpy as np\n'), ((37051, 37144), 'numpy.array', 'np.array', (["[mp['l_e_prime'] * state[self.I_E_IDX], mp['l_e_prime'] * state[self.I_A_IDX]]"], {}), "([mp['l_e_prime'] * state[self.I_E_IDX], mp['l_e_prime'] * state[\n self.I_A_IDX]])\n", (37059, 37144), True, 'import numpy as np\n'), ((48965, 49109), 'numpy.array', 'np.array', (['[omega, state[self.I_SD_IDX], state[self.I_SQ_IDX], u_dq[0], u_dq[1], omega *\n state[self.I_SD_IDX], omega * state[self.I_SQ_IDX]]'], {}), '([omega, state[self.I_SD_IDX], state[self.I_SQ_IDX], u_dq[0], u_dq[\n 1], omega * state[self.I_SD_IDX], omega * state[self.I_SQ_IDX]])\n', (48973, 49109), True, 'import numpy as np\n'), ((56653, 56824), 'numpy.array', 'np.array', (["[[-mp['r_s'] / mp['l_d'], mp['l_q'] / mp['l_d'] * mp['p'] * omega, 0], [-mp\n ['l_d'] / mp['l_q'] * mp['p'] * omega, -mp['r_s'] / mp['l_q'], 0], [0, \n 0, 0]]"], {}), "([[-mp['r_s'] / mp['l_d'], mp['l_q'] / mp['l_d'] * mp['p'] * omega,\n 0], [-mp['l_d'] / mp['l_q'] * mp['p'] * omega, -mp['r_s'] / mp['l_q'], \n 0], [0, 0, 0]])\n", (56661, 56824), True, 'import numpy as np\n'), ((56896, 57032), 'numpy.array', 'np.array', (["[mp['p'] * mp['l_q'] / mp['l_d'] * state[self.I_SQ_IDX], -mp['p'] * mp[\n 'l_d'] / mp['l_q'] * state[self.I_SD_IDX], mp['p']]"], {}), "([mp['p'] * mp['l_q'] / mp['l_d'] * state[self.I_SQ_IDX], -mp['p'] *\n mp['l_d'] / mp['l_q'] * state[self.I_SD_IDX], mp['p']])\n", (56904, 57032), True, 'import numpy as np\n'), ((57110, 57256), 'numpy.array', 'np.array', (["[1.5 * mp['p'] * (mp['l_d'] - mp['l_q']) * state[self.I_SQ_IDX], 1.5 * mp[\n 'p'] * (mp['l_d'] - mp['l_q']) * state[self.I_SD_IDX], 0]"], {}), "([1.5 * mp['p'] * (mp['l_d'] - mp['l_q']) * state[self.I_SQ_IDX], \n 1.5 * mp['p'] * (mp['l_d'] - mp['l_q']) * state[self.I_SD_IDX], 0])\n", (57118, 57256), True, 'import numpy as np\n'), ((63587, 63619), 'numpy.sqrt', 'np.sqrt', (['(i_n ** 2 - i_d_opt ** 2)'], {}), '(i_n ** 2 - i_d_opt ** 2)\n', (63594, 63619), True, 'import numpy as np\n'), ((64039, 64210), 'numpy.array', 'np.array', (["[[-mp['r_s'] / mp['l_d'], mp['l_q'] / mp['l_d'] * omega * mp['p'], 0], [-mp\n ['l_d'] / mp['l_q'] * omega * mp['p'], -mp['r_s'] / mp['l_q'], 0], [0, \n 0, 0]]"], {}), "([[-mp['r_s'] / mp['l_d'], mp['l_q'] / mp['l_d'] * omega * mp['p'],\n 0], [-mp['l_d'] / mp['l_q'] * omega * mp['p'], -mp['r_s'] / mp['l_q'], \n 0], [0, 0, 0]])\n", (64047, 64210), True, 'import numpy as np\n'), ((64290, 64466), 'numpy.array', 'np.array', (["[mp['p'] * mp['l_q'] / mp['l_d'] * state[self.I_SQ_IDX], -mp['p'] * mp[\n 'l_d'] / mp['l_q'] * state[self.I_SD_IDX] - mp['p'] * mp['psi_p'] / mp[\n 'l_q'], mp['p']]"], {}), "([mp['p'] * mp['l_q'] / mp['l_d'] * state[self.I_SQ_IDX], -mp['p'] *\n mp['l_d'] / mp['l_q'] * state[self.I_SD_IDX] - mp['p'] * mp['psi_p'] /\n mp['l_q'], mp['p']])\n", (64298, 64466), True, 'import numpy as np\n'), ((64549, 64716), 'numpy.array', 'np.array', (["[1.5 * mp['p'] * (mp['l_d'] - mp['l_q']) * state[self.I_SQ_IDX], 1.5 * mp[\n 'p'] * (mp['psi_p'] + (mp['l_d'] - mp['l_q']) * state[self.I_SD_IDX]), 0]"], {}), "([1.5 * mp['p'] * (mp['l_d'] - mp['l_q']) * state[self.I_SQ_IDX], \n 1.5 * mp['p'] * (mp['psi_p'] + (mp['l_d'] - mp['l_q']) * state[self.\n I_SD_IDX]), 0])\n", (64557, 64716), True, 'import numpy as np\n'), ((73165, 73462), 'numpy.array', 'np.array', (['[omega, state[self.I_SALPHA_IDX], state[self.I_SBETA_IDX], state[self.\n PSI_RALPHA_IDX], state[self.PSI_RBETA_IDX], omega * state[self.\n PSI_RALPHA_IDX], omega * state[self.PSI_RBETA_IDX], u_sr_alphabeta[0, 0\n ], u_sr_alphabeta[0, 1], u_sr_alphabeta[1, 0], u_sr_alphabeta[1, 1]]'], {}), '([omega, state[self.I_SALPHA_IDX], state[self.I_SBETA_IDX], state[\n self.PSI_RALPHA_IDX], state[self.PSI_RBETA_IDX], omega * state[self.\n PSI_RALPHA_IDX], omega * state[self.PSI_RBETA_IDX], u_sr_alphabeta[0, 0\n ], u_sr_alphabeta[0, 1], u_sr_alphabeta[1, 0], u_sr_alphabeta[1, 1]])\n', (73173, 73462), True, 'import numpy as np\n'), ((77841, 78249), 'numpy.array', 'np.array', (["[[-1 / tau_sig, 0, mp['l_m'] * mp['r_r'] / (sigma * l_s * l_r ** 2), omega *\n mp['l_m'] * mp['p'] / (sigma * l_r * l_s), 0], [0, -1 / tau_sig, -omega *\n mp['l_m'] * mp['p'] / (sigma * l_r * l_s), mp['l_m'] * mp['r_r'] / (\n sigma * l_s * l_r ** 2), 0], [mp['l_m'] / tau_r, 0, -1 / tau_r, -omega *\n mp['p'], 0], [0, mp['l_m'] / tau_r, omega * mp['p'], -1 / tau_r, 0], [0,\n 0, 0, 0, 0]]"], {}), "([[-1 / tau_sig, 0, mp['l_m'] * mp['r_r'] / (sigma * l_s * l_r ** 2\n ), omega * mp['l_m'] * mp['p'] / (sigma * l_r * l_s), 0], [0, -1 /\n tau_sig, -omega * mp['l_m'] * mp['p'] / (sigma * l_r * l_s), mp['l_m'] *\n mp['r_r'] / (sigma * l_s * l_r ** 2), 0], [mp['l_m'] / tau_r, 0, -1 /\n tau_r, -omega * mp['p'], 0], [0, mp['l_m'] / tau_r, omega * mp['p'], -1 /\n tau_r, 0], [0, 0, 0, 0, 0]])\n", (77849, 78249), True, 'import numpy as np\n'), ((78583, 78837), 'numpy.array', 'np.array', (["[mp['l_m'] * mp['p'] / (sigma * l_r * l_s) * state[self.PSI_RBETA_IDX], -mp\n ['l_m'] * mp['p'] / (sigma * l_r * l_s) * state[self.PSI_RALPHA_IDX], -\n mp['p'] * state[self.PSI_RBETA_IDX], mp['p'] * state[self.\n PSI_RALPHA_IDX], mp['p']]"], {}), "([mp['l_m'] * mp['p'] / (sigma * l_r * l_s) * state[self.\n PSI_RBETA_IDX], -mp['l_m'] * mp['p'] / (sigma * l_r * l_s) * state[self\n .PSI_RALPHA_IDX], -mp['p'] * state[self.PSI_RBETA_IDX], mp['p'] * state\n [self.PSI_RALPHA_IDX], mp['p']])\n", (78591, 78837), True, 'import numpy as np\n'), ((78993, 79273), 'numpy.array', 'np.array', (["[-state[self.PSI_RBETA_IDX] * 3 / 2 * mp['p'] * mp['l_m'] / l_r, state[self\n .PSI_RALPHA_IDX] * 3 / 2 * mp['p'] * mp['l_m'] / l_r, state[self.\n I_SBETA_IDX] * 3 / 2 * mp['p'] * mp['l_m'] / l_r, -state[self.\n I_SALPHA_IDX] * 3 / 2 * mp['p'] * mp['l_m'] / l_r, 0]"], {}), "([-state[self.PSI_RBETA_IDX] * 3 / 2 * mp['p'] * mp['l_m'] / l_r, \n state[self.PSI_RALPHA_IDX] * 3 / 2 * mp['p'] * mp['l_m'] / l_r, state[\n self.I_SBETA_IDX] * 3 / 2 * mp['p'] * mp['l_m'] / l_r, -state[self.\n I_SALPHA_IDX] * 3 / 2 * mp['p'] * mp['l_m'] / l_r, 0])\n", (79001, 79273), True, 'import numpy as np\n'), ((8437, 8460), 'numpy.abs', 'np.abs', (['nominal_values_'], {}), '(nominal_values_)\n', (8443, 8460), True, 'import numpy as np\n'), ((9064, 9091), 'numpy.asarray', 'np.asarray', (['nominal_values_'], {}), '(nominal_values_)\n', (9074, 9091), True, 'import numpy as np\n'), ((9146, 9178), 'numpy.asarray', 'np.asarray', (['self._nominal_values'], {}), '(self._nominal_values)\n', (9156, 9178), True, 'import numpy as np\n'), ((63535, 63562), 'numpy.sqrt', 'np.sqrt', (['((_p / 2) ** 2 - _q)'], {}), '((_p / 2) ** 2 - _q)\n', (63542, 63562), True, 'import numpy as np\n'), ((86707, 86732), 'numpy.random.random_sample', 'np.random.random_sample', ([], {}), '()\n', (86730, 86732), True, 'import numpy as np\n'), ((95012, 95037), 'numpy.random.random_sample', 'np.random.random_sample', ([], {}), '()\n', (95035, 95037), True, 'import numpy as np\n'), ((9444, 9484), 'numpy.asarray', 'np.asarray', (['state_space.low'], {'dtype': 'float'}), '(state_space.low, dtype=float)\n', (9454, 9484), True, 'import numpy as np\n'), ((38419, 38429), 'numpy.sqrt', 'np.sqrt', (['(3)'], {}), '(3)\n', (38426, 38429), True, 'import numpy as np\n'), ((38455, 38465), 'numpy.sqrt', 'np.sqrt', (['(3)'], {}), '(3)\n', (38462, 38465), True, 'import numpy as np\n'), ((56221, 56231), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (56228, 56231), True, 'import numpy as np\n'), ((56256, 56266), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (56263, 56266), True, 'import numpy as np\n'), ((35200, 35232), 'numpy.atleast_1d', 'np.atleast_1d', (['state[self.I_IDX]'], {}), '(state[self.I_IDX])\n', (35213, 35232), True, 'import numpy as np\n'), ((38249, 38259), 'numpy.sqrt', 'np.sqrt', (['(3)'], {}), '(3)\n', (38256, 38259), True, 'import numpy as np\n'), ((38268, 38278), 'numpy.sqrt', 'np.sqrt', (['(3)'], {}), '(3)\n', (38275, 38278), True, 'import numpy as np\n'), ((75793, 75816), 'numpy.abs', 'np.abs', (["(mp['l_m'] * i_d)"], {}), "(mp['l_m'] * i_d)\n", (75799, 75816), True, 'import numpy as np\n'), ((9712, 9745), 'numpy.asarray', 'np.asarray', (['interval'], {'dtype': 'float'}), '(interval, dtype=float)\n', (9722, 9745), True, 'import numpy as np\n'), ((9971, 10004), 'numpy.asarray', 'np.asarray', (['interval'], {'dtype': 'float'}), '(interval, dtype=float)\n', (9981, 10004), True, 'import numpy as np\n')] |
#!/usr/bin/env python
# -- Content-Encoding: UTF-8 --
"""
Voting system core service
:author: <NAME>
:license: Apache Software License 2.0
:version: 1.1.0
..
Copyright 2014 isandlaTech
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.
"""
# Standard library
import logging
# iPOPO Decorators
from pelix.ipopo.decorators import ComponentFactory, Provides, Requires, \
Instantiate
# Voting system
import cohorte.vote
import cohorte.vote.beans as beans
# ------------------------------------------------------------------------------
# Bundle version
import cohorte.version
__version__=cohorte.version.__version__
# ------------------------------------------------------------------------------
_logger = logging.getLogger(__name__)
# ------------------------------------------------------------------------------
@ComponentFactory()
@Provides(cohorte.vote.SERVICE_VOTE_CORE)
@Requires('_store', cohorte.vote.SERVICE_VOTE_STORE)
@Requires('_engines', cohorte.vote.SERVICE_VOTE_ENGINE,
aggregate=True, optional=False)
@Instantiate('vote-core')
class VoteCore(object):
"""
Voting system core service
"""
def __init__(self):
"""
Sets up members
"""
# Vote engines
self._engines = []
# Vote results storage
self._store = None
# Votes counter
self._nb_votes = 0
def get_kinds(self):
"""
Returns the list of supported kinds of vote
"""
return [engine.get_kind() for engine in self._engines]
def vote(self, electors, candidates, subject=None, name=None,
kind=None, parameters=None):
"""
Runs a vote for the given
:param electors: List of electors
:param candidates: List of candidates
:param subject: Subject of the vote (optional)
:param name: Name of the vote
:param kind: Kind of vote
:param parameters: Parameters for the vote engine
:return: The result of the election (kind-dependent)
:raise NameError: Unknown kind of vote
"""
# 1. Select the engine
if kind is None:
if not self._engines:
# No engine available
raise NameError("No engine available")
# Use the first engine
engine = self._engines[0]
kind = engine.get_kind()
else:
# Engine given
for engine in self._engines:
if engine.get_kind() == kind:
break
else:
raise NameError("Unknown kind of vote: {0}".format(kind))
# 2. Normalize parameters
if not isinstance(parameters, dict):
# No valid parameters given
parameters = {}
else:
parameters = parameters.copy()
if not name:
# Generate a vote name
self._nb_votes += 1
name = "Vote {0} ({1})".format(self._nb_votes, kind)
# Do not try to shortcut the vote if there is only one candidate:
# it is possible that an elector has to be notified of the votes
# Prepare the results bean
vote_bean = beans.VoteResults(name, kind, candidates, electors,
subject, parameters)
# Vote until we have a result
vote_round = 1
result = None
while True:
try:
# 3. Vote
ballots = []
for elector in electors:
ballot = beans.Ballot(elector)
# TODO: add a "last resort" candidate
# (if no candidate works)
elector.vote(tuple(candidates), subject, ballot)
ballots.append(ballot)
# Store the ballots of this round
vote_bean.set_ballots(ballots)
# 4. Analyze votes
result = engine.analyze(vote_round, ballots, tuple(candidates),
parameters, vote_bean)
break
except beans.CoupdEtat as ex:
# Putch = Coup d'etat !
_logger.debug("A putch is perpetrated by [%s]", ex.claimant)
vote_bean.coup_d_etat = True
result = ex.claimant
break
except beans.NextRound as ex:
# Another round is necessary
candidates = ex.candidates
vote_round += 1
vote_bean.next_round(candidates)
if len(candidates) == 1:
# Tricky engine...
result = candidates[0]
break
else:
_logger.debug("New round required with: %s", candidates)
# Store the vote results
vote_bean.set_vote_results(result)
self._store.store_vote(vote_bean)
return result
| [
"logging.getLogger",
"pelix.ipopo.decorators.Provides",
"pelix.ipopo.decorators.ComponentFactory",
"pelix.ipopo.decorators.Instantiate",
"cohorte.vote.beans.Ballot",
"pelix.ipopo.decorators.Requires",
"cohorte.vote.beans.VoteResults"
] | [((1231, 1258), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1248, 1258), False, 'import logging\n'), ((1344, 1362), 'pelix.ipopo.decorators.ComponentFactory', 'ComponentFactory', ([], {}), '()\n', (1360, 1362), False, 'from pelix.ipopo.decorators import ComponentFactory, Provides, Requires, Instantiate\n'), ((1364, 1404), 'pelix.ipopo.decorators.Provides', 'Provides', (['cohorte.vote.SERVICE_VOTE_CORE'], {}), '(cohorte.vote.SERVICE_VOTE_CORE)\n', (1372, 1404), False, 'from pelix.ipopo.decorators import ComponentFactory, Provides, Requires, Instantiate\n'), ((1406, 1457), 'pelix.ipopo.decorators.Requires', 'Requires', (['"""_store"""', 'cohorte.vote.SERVICE_VOTE_STORE'], {}), "('_store', cohorte.vote.SERVICE_VOTE_STORE)\n", (1414, 1457), False, 'from pelix.ipopo.decorators import ComponentFactory, Provides, Requires, Instantiate\n'), ((1459, 1549), 'pelix.ipopo.decorators.Requires', 'Requires', (['"""_engines"""', 'cohorte.vote.SERVICE_VOTE_ENGINE'], {'aggregate': '(True)', 'optional': '(False)'}), "('_engines', cohorte.vote.SERVICE_VOTE_ENGINE, aggregate=True,\n optional=False)\n", (1467, 1549), False, 'from pelix.ipopo.decorators import ComponentFactory, Provides, Requires, Instantiate\n'), ((1557, 1581), 'pelix.ipopo.decorators.Instantiate', 'Instantiate', (['"""vote-core"""'], {}), "('vote-core')\n", (1568, 1581), False, 'from pelix.ipopo.decorators import ComponentFactory, Provides, Requires, Instantiate\n'), ((3703, 3775), 'cohorte.vote.beans.VoteResults', 'beans.VoteResults', (['name', 'kind', 'candidates', 'electors', 'subject', 'parameters'], {}), '(name, kind, candidates, electors, subject, parameters)\n', (3720, 3775), True, 'import cohorte.vote.beans as beans\n'), ((4060, 4081), 'cohorte.vote.beans.Ballot', 'beans.Ballot', (['elector'], {}), '(elector)\n', (4072, 4081), True, 'import cohorte.vote.beans as beans\n')] |
import socket
from ast import literal_eval
import Yetiborg.Drive as Yetiborg
HEADERSIZE = 2
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("localhost", 12345)) # 192.168.0.11 / localhost / 192.168.0.108
# car always looks up at the beginning
car = Yetiborg.Yetiborg((0, 1))
"""
fs: finished
"""
def move(vec):
print(vec)
# movement command at motors
car.calculate_movement(vec)
pass
def stop():
print("Stop")
exit()
def command_decoder(str):
# decodes the send command into an action
cmd = str[:2]
if cmd == "mv":
# gets the direction (tuple) from the command
move(literal_eval(str[2:]))
elif cmd == "en":
stop()
pass
while True:
full_cmd = ""
header = s.recv(HEADERSIZE).decode("utf-8")
print("New message length:", header[:HEADERSIZE])
cmd_len = int(header[:HEADERSIZE])
full_cmd = s.recv(cmd_len).decode("utf-8")
command_decoder(full_cmd)
# send finished execution signal
s.send(bytes("fs", "utf-8"))
| [
"ast.literal_eval",
"Yetiborg.Drive.Yetiborg",
"socket.socket"
] | [((98, 147), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (111, 147), False, 'import socket\n'), ((271, 296), 'Yetiborg.Drive.Yetiborg', 'Yetiborg.Yetiborg', (['(0, 1)'], {}), '((0, 1))\n', (288, 296), True, 'import Yetiborg.Drive as Yetiborg\n'), ((652, 673), 'ast.literal_eval', 'literal_eval', (['str[2:]'], {}), '(str[2:])\n', (664, 673), False, 'from ast import literal_eval\n')] |
# Copyright 2020 <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.
import base64
import json
import os
import struct
from .ModelNodeConvert import ModelNodeVertexStream, ModelNodeGeometryData, addModelType
from .SceneResourcesConvert import modelVertexAttribEnum
class Object:
pass
gltfVertexAttribEnum = {
'POSITION': modelVertexAttribEnum['Position'],
'NORMAL': modelVertexAttribEnum['Normal'],
'TANGENT': modelVertexAttribEnum['Tangent'],
'TEXCOORD_0': modelVertexAttribEnum['TexCoord0'],
'TEXCOORD`1': modelVertexAttribEnum['TexCoord1'],
'TEXCOORD`2': modelVertexAttribEnum['TexCoord2'],
'TEXCOORD`3': modelVertexAttribEnum['TexCoord3'],
'TEXCOORD`4': modelVertexAttribEnum['TexCoord4'],
'TEXCOORD`5': modelVertexAttribEnum['TexCoord5'],
'TEXCOORD`6': modelVertexAttribEnum['TexCoord6'],
'TEXCOORD`7': modelVertexAttribEnum['TexCoord7'],
'COLOR_0': modelVertexAttribEnum['Color0'],
'COLOR_1': modelVertexAttribEnum['Color1'],
'JOINTS_0': modelVertexAttribEnum['BlendIndices'],
'WEIGHTS_0': modelVertexAttribEnum['BlendWeights'],
}
gltfTypeMap = {
('SCALAR', 5120): ('X8', 'Int'),
('SCALAR', 5121): ('X8', 'UInt'),
('SCALAR', 5122): ('X16', 'Int'),
('SCALAR', 5123): ('X16', 'UInt'),
('SCALAR', 5125): ('X32', 'UInt'),
('SCALAR', 5126): ('X32', 'Float'),
('VEC2', 5120): ('X8Y8', 'Int'),
('VEC2', 5121): ('X8Y8', 'UInt'),
('VEC2', 5122): ('X16Y16', 'Int'),
('VEC2', 5123): ('X16Y16', 'UInt'),
('VEC2', 5126): ('X32Y32', 'Float'),
('VEC3', 5120): ('X8Y8Z8', 'Int'),
('VEC3', 5121): ('X8Y8Z8', 'UInt'),
('VEC3', 5122): ('X16Y16Z16', 'Int'),
('VEC3', 5123): ('X16Y16Z16', 'UInt'),
('VEC3', 5126): ('X32Y32Z32', 'Float'),
('VEC4', 5120): ('X8Y8Z8W8', 'Int'),
('VEC4', 5121): ('X8Y8Z8W8', 'UInt'),
('VEC4', 5122): ('X16Y16Z16W16', 'Int'),
('VEC4', 5123): ('X16Y16Z16W16', 'UInt'),
('VEC4', 5126): ('X32Y32Z32W32', 'Float')
}
gltfPrimitiveTypeMap = ['PointList', 'LineList', 'LineStrip', 'LineStrip', 'TriangleList',
'TriangleStrip', 'TriangleFan']
def convertGLTFModel(convertContext, path):
"""
Converts an GLTF model for use with ModelNodeConvert.
If the "name" element is provided for a mesh, it will be used for the name of the model
geometry. Otherwise, the name will be "mesh#", where # is the index of the mesh. If multiple
sets of primitives are used, the index will be appended to the name, separated with '.'.
Limitations:
- Only meshes and dependent data (accessors, buffer views, and buffers) are extracted. All other
parts of the scene are ignored, including transforms.
- Morph targets aren't supported.
- Materials aren't read, and are instead provided in the DeepSea scene configuration.
- Buffer data may either be embedded or a file path relative to the main model file. General
URIs are not supported.
"""
with open(path) as f:
try:
data = json.load(f)
except:
raise Exception('Invalid GLTF file "' + path + '".')
parentDir = os.path.dirname(path)
try:
# Read the buffers.
buffers = []
bufferInfos = data['buffers']
dataPrefix = 'data:application/octet-stream;base64,'
try:
for bufferInfo in bufferInfos:
uri = bufferInfo['uri']
if uri.startswith(dataPrefix):
try:
buffers.append(base64.b64decode(uri[len(dataPrefix):]))
except:
raise Exception('Invalid buffer data for GLTF file "' + path + '".')
else:
with open(os.path.join(parentDir, uri), 'rb') as f:
buffers.append(f.read())
except (TypeError, ValueError):
raise Exception('Buffers must be an array of objects for GLTF file "' + path + '".')
except KeyError as e:
raise Exception('Buffer doesn\'t contain element "' + str(e) +
'" for GLTF file "' + path + '".')
# Read the buffer views.
bufferViews = []
bufferViewInfos = data['bufferViews']
try:
for bufferViewInfo in bufferViewInfos:
bufferView = Object()
try:
bufferData = buffers[bufferViewInfo['buffer']]
except (IndexError, TypeError):
raise Exception('Invalid buffer index for GLTF file "' + path + '".')
offset = bufferViewInfo['byteOffset']
length = bufferViewInfo['byteLength']
try:
bufferView.buffer = bufferData[offset:offset + length]
except (IndexError, TypeError):
raise Exception('Invalid buffer view range for GLTF file "' + path + '".')
bufferViews.append(bufferView)
except (TypeError, ValueError):
raise Exception(
'Buffer views must be an array of objects for GLTF file "' + path + '".')
except KeyError as e:
raise Exception('Buffer view doesn\'t contain element "' + str(e) +
'" for GLTF file "' + path + '".')
# Read the accessors.
accessors = []
accessorInfos = data['accessors']
try:
for accessorInfo in accessorInfos:
accessor = Object()
try:
accessor.bufferView = bufferViews[accessorInfo['bufferView']]
except (IndexError, TypeError):
raise Exception('Invalid buffer view index for GLTF file "' + path + '".')
gltfType = accessorInfo['type']
componentType = accessorInfo['componentType']
try:
accessorType, decorator = gltfTypeMap[(gltfType, componentType)]
except (KeyError, TypeError):
raise Exception('Invalid accessor type (' + str(gltfType) + ', ' +
str(componentType) + ') for GLTF file "' + path + '".')
accessor.type = accessorType
accessor.decorator = decorator
accessor.count = accessorInfo['count']
accessors.append(accessor)
except (TypeError, ValueError):
raise Exception('Accessors must be an array of objects for GLTF file "' + path + '".')
except KeyError as e:
raise Exception('Accessor doesn\'t contain element "' + str(e) +
'" for GLTF file "' + path + '".')
# Read the meshes.
meshes = []
meshInfos = data['meshes']
try:
meshIndex = 0
for meshInfo in meshInfos:
meshName = meshInfo.get('name', 'mesh' + str(meshIndex))
primitiveInfos = meshInfo['primitives']
try:
primitiveIndex = 0
for primitiveInfo in primitiveInfos:
mesh = Object()
mesh.attributes = []
mesh.name = meshName
if len(primitiveInfos) > 1:
mesh.name += '.' + str(primitiveIndex)
primitiveIndex += 1
try:
for attrib, index in primitiveInfo['attributes'].items():
if attrib not in gltfVertexAttribEnum:
raise Exception('Unsupported attribute "' + str(attrib) +
'" for GLTF file "' + path + '".')
try:
mesh.attributes.append((gltfVertexAttribEnum[attrib],
accessors[index]))
except (IndexError, TypeError):
raise Exception('Invalid accessor index for GLTF file "' +
path + '".')
except (TypeError, ValueError):
raise Exception(
'Mesh primitives attributes must be an object containing attribute '
'mappings for GLTF file "' + path + '".')
if 'indices' in primitiveInfo:
try:
mesh.indices = accessors[primitiveInfo['indices']]
except (IndexError, TypeError):
raise Exception(
'Invalid accessor index for GLTF file "' + path + '".')
else:
mesh.indices = None
mode = primitiveInfo.get('mode', 4)
try:
mesh.primitiveType = gltfPrimitiveTypeMap[mode]
except (IndexError, TypeError):
raise Exception('Unsupported primitive mode for GLTF file "' + path + '".')
meshes.append(mesh)
except (TypeError, ValueError):
raise Exception(
'Mesh primitives must be an array of objects for GLTF file "' + path + '".')
except KeyError as e:
raise Exception('Mesh primitives doesn\'t contain element "' + str(e) +
'" for GLTF file "' + path + '".')
meshIndex += 1
except (TypeError, ValueError):
raise Exception('Meshes must be an array of objects for GLTF file "' + path + '".')
except KeyError as e:
raise Exception('Mesh doesn\'t contain element "' + str(e) + '" for GLTF file "' +
path + '".')
except (TypeError, ValueError):
raise Exception('Root value in GLTF file "' + path + '" must be an object.')
except KeyError as e:
raise Exception('GLTF file "' + path + '" doesn\'t contain element "' + str(e) + '".')
# Convert meshes to geometry list. GLTF uses separate vertex streams rather than interleved
# vertices, so the index buffer will need to be separate for each. This will have some
# data duplication during processing, but isn't expected to be a large amount in practice.
geometry = []
for mesh in meshes:
if mesh.indices:
indexData = mesh.indices.bufferView.buffer
if mesh.indices.type == 'X16':
indexSize = 2
elif mesh.indices.type == 'X32':
indexSize = 4
else:
raise Exception('Unsupported index type "' + mesh.indices.type +
'" for GLTF file "' + path + '".')
else:
indexData = None
indexSize = 0
vertexStreams = []
for attrib, accessor in mesh.attributes:
vertexFormat = [(attrib, accessor.type, accessor.decorator)]
vertexStreams.append(ModelNodeVertexStream(vertexFormat, accessor.bufferView.buffer,
indexSize, indexData))
geometry.append(ModelNodeGeometryData(mesh.name, vertexStreams, mesh.primitiveType))
return geometry
def registerGLTFModelType(convertContext):
"""
Registers the GLTF model type under the name "gltf".
"""
addModelType(convertContext, 'gltf', convertGLTFModel)
| [
"json.load",
"os.path.dirname",
"os.path.join"
] | [((3425, 3446), 'os.path.dirname', 'os.path.dirname', (['path'], {}), '(path)\n', (3440, 3446), False, 'import os\n'), ((3332, 3344), 'json.load', 'json.load', (['f'], {}), '(f)\n', (3341, 3344), False, 'import json\n'), ((3867, 3895), 'os.path.join', 'os.path.join', (['parentDir', 'uri'], {}), '(parentDir, uri)\n', (3879, 3895), False, 'import os\n')] |
import pdfkit
import boto3
s3 = boto3.client('s3')
def lambda_handler(event, context):
pdfkit.from_url('http://google.com', '/tmp/out.pdf')
with open('/tmp/out.pdf', 'rb') as f:
response = s3.put_object(
Bucket='temp-awseabsgddev',
Key='juni/google.pdf',
Body=f.read()
)
return {'response': response}
| [
"boto3.client",
"pdfkit.from_url"
] | [((33, 51), 'boto3.client', 'boto3.client', (['"""s3"""'], {}), "('s3')\n", (45, 51), False, 'import boto3\n'), ((94, 146), 'pdfkit.from_url', 'pdfkit.from_url', (['"""http://google.com"""', '"""/tmp/out.pdf"""'], {}), "('http://google.com', '/tmp/out.pdf')\n", (109, 146), False, 'import pdfkit\n')] |
import pytest
import torch
from packaging.version import parse as V
from torch_complex import ComplexTensor
from espnet2.enh.layers.complex_utils import is_complex
from espnet2.enh.separator.dc_crn_separator import DC_CRNSeparator
is_torch_1_9_plus = V(torch.__version__) >= V("1.9.0")
@pytest.mark.parametrize("input_dim", [33, 65])
@pytest.mark.parametrize("num_spk", [1, 2])
@pytest.mark.parametrize("input_channels", [[2, 4], [2, 4, 4]])
@pytest.mark.parametrize("enc_hid_channels", [2, 5])
@pytest.mark.parametrize("enc_layers", [2])
@pytest.mark.parametrize("glstm_groups", [2])
@pytest.mark.parametrize("glstm_layers", [1, 2])
@pytest.mark.parametrize("glstm_bidirectional", [True, False])
@pytest.mark.parametrize("glstm_rearrange", [True, False])
@pytest.mark.parametrize("mode", ["mapping", "masking"])
def test_dc_crn_separator_forward_backward_complex(
input_dim,
num_spk,
input_channels,
enc_hid_channels,
enc_layers,
glstm_groups,
glstm_layers,
glstm_bidirectional,
glstm_rearrange,
mode,
):
model = DC_CRNSeparator(
input_dim=input_dim,
num_spk=num_spk,
input_channels=input_channels,
enc_hid_channels=enc_hid_channels,
enc_kernel_size=(1, 3),
enc_padding=(0, 1),
enc_last_kernel_size=(1, 3),
enc_last_stride=(1, 2),
enc_last_padding=(0, 1),
enc_layers=enc_layers,
skip_last_kernel_size=(1, 3),
skip_last_stride=(1, 1),
skip_last_padding=(0, 1),
glstm_groups=glstm_groups,
glstm_layers=glstm_layers,
glstm_bidirectional=glstm_bidirectional,
glstm_rearrange=glstm_rearrange,
mode=mode,
)
model.train()
real = torch.rand(2, 10, input_dim)
imag = torch.rand(2, 10, input_dim)
x = torch.complex(real, imag) if is_torch_1_9_plus else ComplexTensor(real, imag)
x_lens = torch.tensor([10, 8], dtype=torch.long)
masked, flens, others = model(x, ilens=x_lens)
assert is_complex(masked[0])
assert len(masked) == num_spk
masked[0].abs().mean().backward()
@pytest.mark.parametrize("num_spk", [1, 2])
@pytest.mark.parametrize("input_channels", [[4, 4], [6, 4, 4]])
@pytest.mark.parametrize(
"enc_kernel_size, enc_padding", [((1, 3), (0, 1)), ((1, 5), (0, 2))]
)
@pytest.mark.parametrize("enc_last_stride", [(1, 2)])
@pytest.mark.parametrize(
"enc_last_kernel_size, enc_last_padding",
[((1, 4), (0, 1)), ((1, 5), (0, 2))],
)
@pytest.mark.parametrize("skip_last_stride", [(1, 1)])
@pytest.mark.parametrize(
"skip_last_kernel_size, skip_last_padding",
[((1, 3), (0, 1)), ((1, 5), (0, 2))],
)
def test_dc_crn_separator_multich_input(
num_spk,
input_channels,
enc_kernel_size,
enc_padding,
enc_last_kernel_size,
enc_last_stride,
enc_last_padding,
skip_last_kernel_size,
skip_last_stride,
skip_last_padding,
):
model = DC_CRNSeparator(
input_dim=33,
num_spk=num_spk,
input_channels=input_channels,
enc_hid_channels=2,
enc_kernel_size=enc_kernel_size,
enc_padding=enc_padding,
enc_last_kernel_size=enc_last_kernel_size,
enc_last_stride=enc_last_stride,
enc_last_padding=enc_last_padding,
enc_layers=3,
skip_last_kernel_size=skip_last_kernel_size,
skip_last_stride=skip_last_stride,
skip_last_padding=skip_last_padding,
)
model.train()
real = torch.rand(2, 10, input_channels[0] // 2, 33)
imag = torch.rand(2, 10, input_channels[0] // 2, 33)
x = torch.complex(real, imag) if is_torch_1_9_plus else ComplexTensor(real, imag)
x_lens = torch.tensor([10, 8], dtype=torch.long)
masked, flens, others = model(x, ilens=x_lens)
assert is_complex(masked[0])
assert len(masked) == num_spk
masked[0].abs().mean().backward()
def test_dc_crn_separator_invalid_enc_layer():
with pytest.raises(AssertionError):
DC_CRNSeparator(
input_dim=17,
input_channels=[2, 2, 4],
enc_layers=1,
)
def test_dc_crn_separator_invalid_type():
with pytest.raises(ValueError):
DC_CRNSeparator(
input_dim=17,
input_channels=[2, 2, 4],
mode="xxx",
)
def test_dc_crn_separator_output():
real = torch.rand(2, 10, 17)
imag = torch.rand(2, 10, 17)
x = torch.complex(real, imag) if is_torch_1_9_plus else ComplexTensor(real, imag)
x_lens = torch.tensor([10, 8], dtype=torch.long)
for num_spk in range(1, 3):
model = DC_CRNSeparator(
input_dim=17,
num_spk=num_spk,
input_channels=[2, 2, 4],
)
model.eval()
specs, _, others = model(x, x_lens)
assert isinstance(specs, list)
assert isinstance(others, dict)
for n in range(num_spk):
assert "mask_spk{}".format(n + 1) in others
assert specs[n].shape == others["mask_spk{}".format(n + 1)].shape
| [
"torch_complex.ComplexTensor",
"pytest.mark.parametrize",
"torch.tensor",
"pytest.raises",
"torch.complex",
"espnet2.enh.separator.dc_crn_separator.DC_CRNSeparator",
"packaging.version.parse",
"espnet2.enh.layers.complex_utils.is_complex",
"torch.rand"
] | [((291, 337), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""input_dim"""', '[33, 65]'], {}), "('input_dim', [33, 65])\n", (314, 337), False, 'import pytest\n'), ((339, 381), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""num_spk"""', '[1, 2]'], {}), "('num_spk', [1, 2])\n", (362, 381), False, 'import pytest\n'), ((383, 445), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""input_channels"""', '[[2, 4], [2, 4, 4]]'], {}), "('input_channels', [[2, 4], [2, 4, 4]])\n", (406, 445), False, 'import pytest\n'), ((447, 498), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""enc_hid_channels"""', '[2, 5]'], {}), "('enc_hid_channels', [2, 5])\n", (470, 498), False, 'import pytest\n'), ((500, 542), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""enc_layers"""', '[2]'], {}), "('enc_layers', [2])\n", (523, 542), False, 'import pytest\n'), ((544, 588), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""glstm_groups"""', '[2]'], {}), "('glstm_groups', [2])\n", (567, 588), False, 'import pytest\n'), ((590, 637), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""glstm_layers"""', '[1, 2]'], {}), "('glstm_layers', [1, 2])\n", (613, 637), False, 'import pytest\n'), ((639, 700), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""glstm_bidirectional"""', '[True, False]'], {}), "('glstm_bidirectional', [True, False])\n", (662, 700), False, 'import pytest\n'), ((702, 759), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""glstm_rearrange"""', '[True, False]'], {}), "('glstm_rearrange', [True, False])\n", (725, 759), False, 'import pytest\n'), ((761, 816), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""mode"""', "['mapping', 'masking']"], {}), "('mode', ['mapping', 'masking'])\n", (784, 816), False, 'import pytest\n'), ((2098, 2140), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""num_spk"""', '[1, 2]'], {}), "('num_spk', [1, 2])\n", (2121, 2140), False, 'import pytest\n'), ((2142, 2204), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""input_channels"""', '[[4, 4], [6, 4, 4]]'], {}), "('input_channels', [[4, 4], [6, 4, 4]])\n", (2165, 2204), False, 'import pytest\n'), ((2206, 2303), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""enc_kernel_size, enc_padding"""', '[((1, 3), (0, 1)), ((1, 5), (0, 2))]'], {}), "('enc_kernel_size, enc_padding', [((1, 3), (0, 1)),\n ((1, 5), (0, 2))])\n", (2229, 2303), False, 'import pytest\n'), ((2307, 2359), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""enc_last_stride"""', '[(1, 2)]'], {}), "('enc_last_stride', [(1, 2)])\n", (2330, 2359), False, 'import pytest\n'), ((2361, 2468), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""enc_last_kernel_size, enc_last_padding"""', '[((1, 4), (0, 1)), ((1, 5), (0, 2))]'], {}), "('enc_last_kernel_size, enc_last_padding', [((1, 4),\n (0, 1)), ((1, 5), (0, 2))])\n", (2384, 2468), False, 'import pytest\n'), ((2477, 2530), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""skip_last_stride"""', '[(1, 1)]'], {}), "('skip_last_stride', [(1, 1)])\n", (2500, 2530), False, 'import pytest\n'), ((2532, 2642), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""skip_last_kernel_size, skip_last_padding"""', '[((1, 3), (0, 1)), ((1, 5), (0, 2))]'], {}), "('skip_last_kernel_size, skip_last_padding', [((1, 3\n ), (0, 1)), ((1, 5), (0, 2))])\n", (2555, 2642), False, 'import pytest\n'), ((253, 273), 'packaging.version.parse', 'V', (['torch.__version__'], {}), '(torch.__version__)\n', (254, 273), True, 'from packaging.version import parse as V\n'), ((277, 287), 'packaging.version.parse', 'V', (['"""1.9.0"""'], {}), "('1.9.0')\n", (278, 287), True, 'from packaging.version import parse as V\n'), ((1062, 1578), 'espnet2.enh.separator.dc_crn_separator.DC_CRNSeparator', 'DC_CRNSeparator', ([], {'input_dim': 'input_dim', 'num_spk': 'num_spk', 'input_channels': 'input_channels', 'enc_hid_channels': 'enc_hid_channels', 'enc_kernel_size': '(1, 3)', 'enc_padding': '(0, 1)', 'enc_last_kernel_size': '(1, 3)', 'enc_last_stride': '(1, 2)', 'enc_last_padding': '(0, 1)', 'enc_layers': 'enc_layers', 'skip_last_kernel_size': '(1, 3)', 'skip_last_stride': '(1, 1)', 'skip_last_padding': '(0, 1)', 'glstm_groups': 'glstm_groups', 'glstm_layers': 'glstm_layers', 'glstm_bidirectional': 'glstm_bidirectional', 'glstm_rearrange': 'glstm_rearrange', 'mode': 'mode'}), '(input_dim=input_dim, num_spk=num_spk, input_channels=\n input_channels, enc_hid_channels=enc_hid_channels, enc_kernel_size=(1, \n 3), enc_padding=(0, 1), enc_last_kernel_size=(1, 3), enc_last_stride=(1,\n 2), enc_last_padding=(0, 1), enc_layers=enc_layers,\n skip_last_kernel_size=(1, 3), skip_last_stride=(1, 1),\n skip_last_padding=(0, 1), glstm_groups=glstm_groups, glstm_layers=\n glstm_layers, glstm_bidirectional=glstm_bidirectional, glstm_rearrange=\n glstm_rearrange, mode=mode)\n', (1077, 1578), False, 'from espnet2.enh.separator.dc_crn_separator import DC_CRNSeparator\n'), ((1728, 1756), 'torch.rand', 'torch.rand', (['(2)', '(10)', 'input_dim'], {}), '(2, 10, input_dim)\n', (1738, 1756), False, 'import torch\n'), ((1768, 1796), 'torch.rand', 'torch.rand', (['(2)', '(10)', 'input_dim'], {}), '(2, 10, input_dim)\n', (1778, 1796), False, 'import torch\n'), ((1896, 1935), 'torch.tensor', 'torch.tensor', (['[10, 8]'], {'dtype': 'torch.long'}), '([10, 8], dtype=torch.long)\n', (1908, 1935), False, 'import torch\n'), ((2000, 2021), 'espnet2.enh.layers.complex_utils.is_complex', 'is_complex', (['masked[0]'], {}), '(masked[0])\n', (2010, 2021), False, 'from espnet2.enh.layers.complex_utils import is_complex\n'), ((2917, 3335), 'espnet2.enh.separator.dc_crn_separator.DC_CRNSeparator', 'DC_CRNSeparator', ([], {'input_dim': '(33)', 'num_spk': 'num_spk', 'input_channels': 'input_channels', 'enc_hid_channels': '(2)', 'enc_kernel_size': 'enc_kernel_size', 'enc_padding': 'enc_padding', 'enc_last_kernel_size': 'enc_last_kernel_size', 'enc_last_stride': 'enc_last_stride', 'enc_last_padding': 'enc_last_padding', 'enc_layers': '(3)', 'skip_last_kernel_size': 'skip_last_kernel_size', 'skip_last_stride': 'skip_last_stride', 'skip_last_padding': 'skip_last_padding'}), '(input_dim=33, num_spk=num_spk, input_channels=\n input_channels, enc_hid_channels=2, enc_kernel_size=enc_kernel_size,\n enc_padding=enc_padding, enc_last_kernel_size=enc_last_kernel_size,\n enc_last_stride=enc_last_stride, enc_last_padding=enc_last_padding,\n enc_layers=3, skip_last_kernel_size=skip_last_kernel_size,\n skip_last_stride=skip_last_stride, skip_last_padding=skip_last_padding)\n', (2932, 3335), False, 'from espnet2.enh.separator.dc_crn_separator import DC_CRNSeparator\n'), ((3456, 3501), 'torch.rand', 'torch.rand', (['(2)', '(10)', '(input_channels[0] // 2)', '(33)'], {}), '(2, 10, input_channels[0] // 2, 33)\n', (3466, 3501), False, 'import torch\n'), ((3513, 3558), 'torch.rand', 'torch.rand', (['(2)', '(10)', '(input_channels[0] // 2)', '(33)'], {}), '(2, 10, input_channels[0] // 2, 33)\n', (3523, 3558), False, 'import torch\n'), ((3658, 3697), 'torch.tensor', 'torch.tensor', (['[10, 8]'], {'dtype': 'torch.long'}), '([10, 8], dtype=torch.long)\n', (3670, 3697), False, 'import torch\n'), ((3762, 3783), 'espnet2.enh.layers.complex_utils.is_complex', 'is_complex', (['masked[0]'], {}), '(masked[0])\n', (3772, 3783), False, 'from espnet2.enh.layers.complex_utils import is_complex\n'), ((4323, 4344), 'torch.rand', 'torch.rand', (['(2)', '(10)', '(17)'], {}), '(2, 10, 17)\n', (4333, 4344), False, 'import torch\n'), ((4356, 4377), 'torch.rand', 'torch.rand', (['(2)', '(10)', '(17)'], {}), '(2, 10, 17)\n', (4366, 4377), False, 'import torch\n'), ((4477, 4516), 'torch.tensor', 'torch.tensor', (['[10, 8]'], {'dtype': 'torch.long'}), '([10, 8], dtype=torch.long)\n', (4489, 4516), False, 'import torch\n'), ((1805, 1830), 'torch.complex', 'torch.complex', (['real', 'imag'], {}), '(real, imag)\n', (1818, 1830), False, 'import torch\n'), ((1857, 1882), 'torch_complex.ComplexTensor', 'ComplexTensor', (['real', 'imag'], {}), '(real, imag)\n', (1870, 1882), False, 'from torch_complex import ComplexTensor\n'), ((3567, 3592), 'torch.complex', 'torch.complex', (['real', 'imag'], {}), '(real, imag)\n', (3580, 3592), False, 'import torch\n'), ((3619, 3644), 'torch_complex.ComplexTensor', 'ComplexTensor', (['real', 'imag'], {}), '(real, imag)\n', (3632, 3644), False, 'from torch_complex import ComplexTensor\n'), ((3915, 3944), 'pytest.raises', 'pytest.raises', (['AssertionError'], {}), '(AssertionError)\n', (3928, 3944), False, 'import pytest\n'), ((3954, 4023), 'espnet2.enh.separator.dc_crn_separator.DC_CRNSeparator', 'DC_CRNSeparator', ([], {'input_dim': '(17)', 'input_channels': '[2, 2, 4]', 'enc_layers': '(1)'}), '(input_dim=17, input_channels=[2, 2, 4], enc_layers=1)\n', (3969, 4023), False, 'from espnet2.enh.separator.dc_crn_separator import DC_CRNSeparator\n'), ((4124, 4149), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (4137, 4149), False, 'import pytest\n'), ((4159, 4226), 'espnet2.enh.separator.dc_crn_separator.DC_CRNSeparator', 'DC_CRNSeparator', ([], {'input_dim': '(17)', 'input_channels': '[2, 2, 4]', 'mode': '"""xxx"""'}), "(input_dim=17, input_channels=[2, 2, 4], mode='xxx')\n", (4174, 4226), False, 'from espnet2.enh.separator.dc_crn_separator import DC_CRNSeparator\n'), ((4386, 4411), 'torch.complex', 'torch.complex', (['real', 'imag'], {}), '(real, imag)\n', (4399, 4411), False, 'import torch\n'), ((4438, 4463), 'torch_complex.ComplexTensor', 'ComplexTensor', (['real', 'imag'], {}), '(real, imag)\n', (4451, 4463), False, 'from torch_complex import ComplexTensor\n'), ((4566, 4638), 'espnet2.enh.separator.dc_crn_separator.DC_CRNSeparator', 'DC_CRNSeparator', ([], {'input_dim': '(17)', 'num_spk': 'num_spk', 'input_channels': '[2, 2, 4]'}), '(input_dim=17, num_spk=num_spk, input_channels=[2, 2, 4])\n', (4581, 4638), False, 'from espnet2.enh.separator.dc_crn_separator import DC_CRNSeparator\n')] |
from django.conf.urls import url
from usaspending_api.download.v2 import views
urlpatterns = [
url(r'^awards', views.RowLimitedAwardDownloadViewSet.as_view()),
url(r'^accounts', views.AccountDownloadViewSet.as_view()),
# url(r'^columns', views.DownloadColumnsViewSet.as_view()),
url(r'^status', views.DownloadStatusViewSet.as_view()),
url(r'^transactions', views.RowLimitedTransactionDownloadViewSet.as_view()),
# Note: This is commented out for now as it may be used in the near future
# url(r'^subawards', views.RowLimitedSubawardDownloadViewSet.as_view()),
url(r'^count', views.DownloadTransactionCountViewSet.as_view())
]
| [
"usaspending_api.download.v2.views.RowLimitedAwardDownloadViewSet.as_view",
"usaspending_api.download.v2.views.AccountDownloadViewSet.as_view",
"usaspending_api.download.v2.views.RowLimitedTransactionDownloadViewSet.as_view",
"usaspending_api.download.v2.views.DownloadStatusViewSet.as_view",
"usaspending_ap... | [((118, 164), 'usaspending_api.download.v2.views.RowLimitedAwardDownloadViewSet.as_view', 'views.RowLimitedAwardDownloadViewSet.as_view', ([], {}), '()\n', (162, 164), False, 'from usaspending_api.download.v2 import views\n'), ((189, 227), 'usaspending_api.download.v2.views.AccountDownloadViewSet.as_view', 'views.AccountDownloadViewSet.as_view', ([], {}), '()\n', (225, 227), False, 'from usaspending_api.download.v2 import views\n'), ((314, 351), 'usaspending_api.download.v2.views.DownloadStatusViewSet.as_view', 'views.DownloadStatusViewSet.as_view', ([], {}), '()\n', (349, 351), False, 'from usaspending_api.download.v2 import views\n'), ((380, 432), 'usaspending_api.download.v2.views.RowLimitedTransactionDownloadViewSet.as_view', 'views.RowLimitedTransactionDownloadViewSet.as_view', ([], {}), '()\n', (430, 432), False, 'from usaspending_api.download.v2 import views\n'), ((610, 657), 'usaspending_api.download.v2.views.DownloadTransactionCountViewSet.as_view', 'views.DownloadTransactionCountViewSet.as_view', ([], {}), '()\n', (655, 657), False, 'from usaspending_api.download.v2 import views\n')] |
import os
import sys
sys.path.append('.')
import argparse
import numpy as np
import os.path as osp
from multiprocessing import Process, Pool
from glob import glob
from tqdm import tqdm
import tensorflow as tf
from PIL import Image
from lib.core.config import INSTA_DIR, INSTA_IMG_DIR
def process_single_record(fname, outdir, split):
sess = tf.Session()
#print(fname)
record_name = fname.split('/')[-1]
for vid_idx, serialized_ex in enumerate(tf.python_io.tf_record_iterator(fname)):
#print(vid_idx)
os.makedirs(osp.join(outdir, split, record_name, str(vid_idx)), exist_ok=True)
example = tf.train.Example()
example.ParseFromString(serialized_ex)
N = int(example.features.feature['meta/N'].int64_list.value[0])
images_data = example.features.feature[
'image/encoded'].bytes_list.value
for i in range(N):
image = np.expand_dims(sess.run(tf.image.decode_jpeg(images_data[i], channels=3)), axis=0)
#video.append(image)
image = Image.fromarray(np.squeeze(image, axis=0))
image.save(osp.join(outdir, split, record_name, str(vid_idx), str(i)+".jpg"))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--inp_dir', type=str, help='tfrecords file path', default=INSTA_DIR)
parser.add_argument('--n', type=int, help='total num of workers')
parser.add_argument('--i', type=int, help='current index of worker (from 0 to n-1)')
parser.add_argument('--split', type=str, help='train or test')
parser.add_argument('--out_dir', type=str, help='output images path', default=INSTA_IMG_DIR)
args = parser.parse_args()
fpaths = glob(f'{args.inp_dir}/{args.split}/*.tfrecord')
fpaths = sorted(fpaths)
total = len(fpaths)
fpaths = fpaths[args.i*total//args.n : (args.i+1)*total//args.n]
#print(fpaths)
#print(len(fpaths))
os.makedirs(args.out_dir, exist_ok=True)
for idx, fp in enumerate(fpaths):
process_single_record(fp, args.out_dir, args.split) | [
"tensorflow.train.Example",
"os.makedirs",
"argparse.ArgumentParser",
"tensorflow.python_io.tf_record_iterator",
"tensorflow.Session",
"numpy.squeeze",
"sys.path.append",
"glob.glob",
"tensorflow.image.decode_jpeg"
] | [((21, 41), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (36, 41), False, 'import sys\n'), ((348, 360), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (358, 360), True, 'import tensorflow as tf\n'), ((1226, 1251), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1249, 1251), False, 'import argparse\n'), ((1714, 1761), 'glob.glob', 'glob', (['f"""{args.inp_dir}/{args.split}/*.tfrecord"""'], {}), "(f'{args.inp_dir}/{args.split}/*.tfrecord')\n", (1718, 1761), False, 'from glob import glob\n'), ((1937, 1977), 'os.makedirs', 'os.makedirs', (['args.out_dir'], {'exist_ok': '(True)'}), '(args.out_dir, exist_ok=True)\n', (1948, 1977), False, 'import os\n'), ((462, 500), 'tensorflow.python_io.tf_record_iterator', 'tf.python_io.tf_record_iterator', (['fname'], {}), '(fname)\n', (493, 500), True, 'import tensorflow as tf\n'), ((632, 650), 'tensorflow.train.Example', 'tf.train.Example', ([], {}), '()\n', (648, 650), True, 'import tensorflow as tf\n'), ((1067, 1092), 'numpy.squeeze', 'np.squeeze', (['image'], {'axis': '(0)'}), '(image, axis=0)\n', (1077, 1092), True, 'import numpy as np\n'), ((939, 987), 'tensorflow.image.decode_jpeg', 'tf.image.decode_jpeg', (['images_data[i]'], {'channels': '(3)'}), '(images_data[i], channels=3)\n', (959, 987), True, 'import tensorflow as tf\n')] |
# Generated by Django 3.1.5 on 2021-03-22 17:30
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('movies', '0010_actors_moved'),
('person', '0003_refactoring_movie_person_m2m_rels'),
]
operations = [
migrations.AddField(
model_name='person',
name='movies',
field=models.ManyToManyField(related_name='persons', through='person.PersonRole', to='movies.Movie'),
),
migrations.AddField(
model_name='personrole',
name='role_name',
field=models.CharField(max_length=100, null=True),
),
]
| [
"django.db.models.ManyToManyField",
"django.db.models.CharField"
] | [((389, 487), 'django.db.models.ManyToManyField', 'models.ManyToManyField', ([], {'related_name': '"""persons"""', 'through': '"""person.PersonRole"""', 'to': '"""movies.Movie"""'}), "(related_name='persons', through='person.PersonRole',\n to='movies.Movie')\n", (411, 487), False, 'from django.db import migrations, models\n'), ((610, 653), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)', 'null': '(True)'}), '(max_length=100, null=True)\n', (626, 653), False, 'from django.db import migrations, models\n')] |
from pathlib import Path
import sys
path = str(Path(Path(__file__).parent.absolute()).parent.absolute())
sys.path.insert(0, path)
from mnist_utils.util import _x, _y_int
from sklearn.cluster import MiniBatchKMeans
from sklearn.metrics import accuracy_score, adjusted_rand_score
import numpy as np
from fast_pytorch_kmeans import KMeans
import torch
from tabulate import tabulate
#global vars
kmeans_main = None
cluster_ids_x = None
def classify_clusters(l1, l2):
ref_labels = {}
for i in range(len(np.unique(l1))):
index = np.where(l1 == i,1,0)
ref_labels[i] = np.bincount(l2[index==1]).argmax()
decimal_labels = np.zeros(len(l1))
for i in range(len(l1)):
decimal_labels[i] = ref_labels[l1[i]]
return decimal_labels
def init_clustring_scikit(cluster_count=10):
global kmeans_main
kmeans_main = MiniBatchKMeans(n_clusters=cluster_count, verbose=False)
kmeans_main.fit(_x)
def test_accuracy_scikit():
global kmeans_main
decimal_labels = classify_clusters(kmeans_main.labels_, _y_int)
print("predicted labels:\t", decimal_labels[:16].astype('int'))
print("true labels:\t\t",_y_int[:16])
print(60 * '_')
AP = accuracy_score(decimal_labels,_y_int)
RI = adjusted_rand_score(decimal_labels,_y_int)
print("Accuracy (PURITY):" , AP)
print("Accuracy (RAND INDEX):" , RI)
return AP, RI
def init_clustring_torch(cluster_count=10):
global clusters_from_label, cluster_ids_x
_kmeans = KMeans(n_clusters=cluster_count, mode='euclidean', verbose=1)
x = torch.from_numpy(_x)
cluster_ids_x = _kmeans.fit_predict(x)
def test_accuracy_torch():
global cluster_ids_x
decimal_labels = classify_clusters(cluster_ids_x.cpu().detach().numpy(), _y_int)
print("predicted labels:\t", decimal_labels[:16].astype('int'))
print("true labels:\t\t",_y_int[:16])
print(60 * '_')
AP = accuracy_score(decimal_labels,_y_int)
RI = adjusted_rand_score(decimal_labels,_y_int)
print("Accuracy (PURITY):" , AP)
print("Accuracy (RAND INDEX):" , RI)
return AP, RI
def pipeline(lib="torch", cluster_count_max=300, coefficient=2):
cluster_count = len(np.unique(_y_int))
result = []
if lib == "torch":
while cluster_count <= cluster_count_max:
print(10 * "*" + "TRYING WITH " + str(cluster_count) + 10 * "*")
init_clustring_torch(cluster_count)
AP, RI = test_accuracy_torch()
result.append([cluster_count, AP, RI])
cluster_count *= coefficient
cluster_count = int(cluster_count)
elif lib == "scikit":
while cluster_count <= cluster_count_max:
print(10 * "*" + "TRYING WITH " + str(cluster_count) + 10 * "*")
init_clustring_scikit(cluster_count)
AP, RI = test_accuracy_scikit()
result.append([cluster_count, AP, RI])
cluster_count *= coefficient
cluster_count = int(cluster_count)
else:
print("LIB NOT SUPPORTED")
print(tabulate(result, headers=['K', 'AP', 'RI']))
pipeline(cluster_count_max=200, coefficient=3, lib="scikit")
| [
"fast_pytorch_kmeans.KMeans",
"tabulate.tabulate",
"sys.path.insert",
"numpy.unique",
"pathlib.Path",
"numpy.where",
"sklearn.cluster.MiniBatchKMeans",
"sklearn.metrics.adjusted_rand_score",
"torch.from_numpy",
"numpy.bincount",
"sklearn.metrics.accuracy_score"
] | [((105, 129), 'sys.path.insert', 'sys.path.insert', (['(0)', 'path'], {}), '(0, path)\n', (120, 129), False, 'import sys\n'), ((849, 905), 'sklearn.cluster.MiniBatchKMeans', 'MiniBatchKMeans', ([], {'n_clusters': 'cluster_count', 'verbose': '(False)'}), '(n_clusters=cluster_count, verbose=False)\n', (864, 905), False, 'from sklearn.cluster import MiniBatchKMeans\n'), ((1189, 1227), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['decimal_labels', '_y_int'], {}), '(decimal_labels, _y_int)\n', (1203, 1227), False, 'from sklearn.metrics import accuracy_score, adjusted_rand_score\n'), ((1236, 1279), 'sklearn.metrics.adjusted_rand_score', 'adjusted_rand_score', (['decimal_labels', '_y_int'], {}), '(decimal_labels, _y_int)\n', (1255, 1279), False, 'from sklearn.metrics import accuracy_score, adjusted_rand_score\n'), ((1481, 1542), 'fast_pytorch_kmeans.KMeans', 'KMeans', ([], {'n_clusters': 'cluster_count', 'mode': '"""euclidean"""', 'verbose': '(1)'}), "(n_clusters=cluster_count, mode='euclidean', verbose=1)\n", (1487, 1542), False, 'from fast_pytorch_kmeans import KMeans\n'), ((1551, 1571), 'torch.from_numpy', 'torch.from_numpy', (['_x'], {}), '(_x)\n', (1567, 1571), False, 'import torch\n'), ((1893, 1931), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['decimal_labels', '_y_int'], {}), '(decimal_labels, _y_int)\n', (1907, 1931), False, 'from sklearn.metrics import accuracy_score, adjusted_rand_score\n'), ((1940, 1983), 'sklearn.metrics.adjusted_rand_score', 'adjusted_rand_score', (['decimal_labels', '_y_int'], {}), '(decimal_labels, _y_int)\n', (1959, 1983), False, 'from sklearn.metrics import accuracy_score, adjusted_rand_score\n'), ((541, 564), 'numpy.where', 'np.where', (['(l1 == i)', '(1)', '(0)'], {}), '(l1 == i, 1, 0)\n', (549, 564), True, 'import numpy as np\n'), ((2169, 2186), 'numpy.unique', 'np.unique', (['_y_int'], {}), '(_y_int)\n', (2178, 2186), True, 'import numpy as np\n'), ((3027, 3070), 'tabulate.tabulate', 'tabulate', (['result'], {'headers': "['K', 'AP', 'RI']"}), "(result, headers=['K', 'AP', 'RI'])\n", (3035, 3070), False, 'from tabulate import tabulate\n'), ((508, 521), 'numpy.unique', 'np.unique', (['l1'], {}), '(l1)\n', (517, 521), True, 'import numpy as np\n'), ((587, 614), 'numpy.bincount', 'np.bincount', (['l2[index == 1]'], {}), '(l2[index == 1])\n', (598, 614), True, 'import numpy as np\n'), ((52, 66), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (56, 66), False, 'from pathlib import Path\n')] |
import graphene
import os
from promise import Promise
from datetime import datetime
from promise.dataloader import DataLoader
import requests
from core.graphql.types import CountryType
from core.models import Country
class Natura2000FeatureType(graphene.ObjectType):
id = graphene.String()
site_code = graphene.String()
site_name = graphene.String()
country = graphene.Field(CountryType)
released_at = graphene.DateTime()
wkt_type = graphene.String()
site_types = graphene.List(graphene.String)
class Natura2000IntersectionType(graphene.ObjectType):
id = graphene.String()
intersects = graphene.Boolean()
minimum_distance = graphene.Float()
intersection = graphene.Float()
natura2000_feature = graphene.Field(Natura2000FeatureType)
class Natura2000IntersectionLoader(DataLoader):
def batch_load_fn(self, lpis_parcel_ids):
url = os.getenv('FAST_API_PARCEL_NATURA2000_URL')
data = requests.post(url, params={'search': '10000'}, json=lpis_parcel_ids).json()
# Sort the results in the same order as the request
sorting = {lpis_parcel_id: index for index, lpis_parcel_id in enumerate(lpis_parcel_ids)}
data = sorted(data, key=lambda x: sorting[x['_id']])
results = []
for lpis_parcel_id, d in zip(lpis_parcel_ids, data):
result = []
for n in d['natura2000']:
if n is None:
continue
# Create a real Country vertex
country = Country.objects.filter(pk=n.get('country').upper()).get()
released_at = datetime.strptime(n.get('releaseDate'), '%Y-%m-%d')
# The feature that is intersecting
natura2000_feature = Natura2000FeatureType(id=n.get('_id'),
site_code=n.get('siteCode'),
site_name=n.get('siteName'),
wkt_type=n.get('wktType'),
country=country,
released_at=released_at,
site_types=n.get('siteTypes'))
# The intersection itself
intersection = Natura2000IntersectionType(id=lpis_parcel_id + '.' + n.get('_id'),
intersects=n.get('intersects'),
minimum_distance=n.get('minDistance'),
intersection=n.get('intersection'),
natura2000_feature=natura2000_feature)
result += [intersection]
results += [result]
return Promise.resolve(results)
natura2000_intersections_loader = Natura2000IntersectionLoader() | [
"graphene.String",
"requests.post",
"graphene.Field",
"graphene.List",
"os.getenv",
"graphene.Float",
"graphene.DateTime",
"promise.Promise.resolve",
"graphene.Boolean"
] | [((278, 295), 'graphene.String', 'graphene.String', ([], {}), '()\n', (293, 295), False, 'import graphene\n'), ((312, 329), 'graphene.String', 'graphene.String', ([], {}), '()\n', (327, 329), False, 'import graphene\n'), ((346, 363), 'graphene.String', 'graphene.String', ([], {}), '()\n', (361, 363), False, 'import graphene\n'), ((378, 405), 'graphene.Field', 'graphene.Field', (['CountryType'], {}), '(CountryType)\n', (392, 405), False, 'import graphene\n'), ((424, 443), 'graphene.DateTime', 'graphene.DateTime', ([], {}), '()\n', (441, 443), False, 'import graphene\n'), ((459, 476), 'graphene.String', 'graphene.String', ([], {}), '()\n', (474, 476), False, 'import graphene\n'), ((494, 524), 'graphene.List', 'graphene.List', (['graphene.String'], {}), '(graphene.String)\n', (507, 524), False, 'import graphene\n'), ((591, 608), 'graphene.String', 'graphene.String', ([], {}), '()\n', (606, 608), False, 'import graphene\n'), ((626, 644), 'graphene.Boolean', 'graphene.Boolean', ([], {}), '()\n', (642, 644), False, 'import graphene\n'), ((668, 684), 'graphene.Float', 'graphene.Float', ([], {}), '()\n', (682, 684), False, 'import graphene\n'), ((704, 720), 'graphene.Float', 'graphene.Float', ([], {}), '()\n', (718, 720), False, 'import graphene\n'), ((746, 783), 'graphene.Field', 'graphene.Field', (['Natura2000FeatureType'], {}), '(Natura2000FeatureType)\n', (760, 783), False, 'import graphene\n'), ((894, 937), 'os.getenv', 'os.getenv', (['"""FAST_API_PARCEL_NATURA2000_URL"""'], {}), "('FAST_API_PARCEL_NATURA2000_URL')\n", (903, 937), False, 'import os\n'), ((2920, 2944), 'promise.Promise.resolve', 'Promise.resolve', (['results'], {}), '(results)\n', (2935, 2944), False, 'from promise import Promise\n'), ((953, 1021), 'requests.post', 'requests.post', (['url'], {'params': "{'search': '10000'}", 'json': 'lpis_parcel_ids'}), "(url, params={'search': '10000'}, json=lpis_parcel_ids)\n", (966, 1021), False, 'import requests\n')] |
from _satoshitx import *
import struct
#https://bitcoincore.org/en/segwit_wallet_dev/
class SWitnessTransaction(STransaction):
def __init__(version,flag,ins,outs,witness,locktime):
super(SWitnessTransaction,self).__init__(version,ins,outs,locktime)
self.flag=flag
self.witness=witness
def serialize(self):
txo=self
#if(not isinstance(txo,SWitnessTransaction) and isinstance(txo,STransaction)):
# return STransaction._sc_serialize(txo)
out=bytearray()
out+=struct.pack('<L',txo.version)
out+=b'\x00'
out+=struct.pack('B',txo.flag)
out+=SVarInt(len(txo.ins)).serialize()
for inv in txo.ins:
out+=inv.serialize()
out+=SVarInt(len(txo.outs)).serialize()
for ot in txo.outs:
out+=ot.serialize()
if(len(txo.witness) != len(txo.ins)):
raise Exception("Witness data not the same length as number of inputs")
for wit in txo.witness: #load witness data
out+=SVarInt(len(wit)).serialize()
for wititem in wit:
out+=SVarInt(len(wititem)).serialize()
out+=wititem #TODO: .serialize()
out+=struct.pack('<L',txo.locktime)
return out
@staticmethod
def _sc_deserialize(sio):
version=struct.unpack('<L',sio.read(4))[0]
num_ins=SVarInt._sc_deserialize(sio)
if(num_ins!=0): #this is not a witness transaction
return STransaction._sc_deserialize(StringIO(sio.getvalue()))
flag=ord(sio.read(1))
num_ins=SVarInt._sc_deserialize(sio)
ins=[SInput._sc_deserialize(sio) for k in range(num_ins)]
num_outs=SVarInt._sc_deserialize(sio)
outs=[SOutput._sc_deserialize(sio) for k in range(num_outs)]
witness=[]
for _ in range(num_ins):
num_wititems=SVarInt._sc_deserialize(sio)
wititems=[]
for _ in range(num_wititems):
witsize=SVarInt._sc_deserialize(sio)
wititmes.append(sio.read(witsize))
witness.append(wititems)
locktime=struct.unpack('<L',sio.read(4))[0]
return SWitnessTransaction(version,flag,ins,outs,witness,locktime)
#TODO: from tx that calls coin.signature
def txid_hash(self):
return dblsha256(super(SWitnessTransaction,self).serialize())
def wtxid_hash(self):
return dblsha256(self.serialize())
def segwit_get_prevouthash(stxo):
out=bytearray()
for inp in stxo.ins:
out+=inp.outpoint.serialize()
return dblsha256(out)
"""template <class T>
uint256 GetPrevoutHash(const T& txTo)
{
CHashWriter ss(SER_GETHASH, 0);
for (const auto& txin : txTo.vin) {
ss << txin.prevout;
}
return ss.GetHash();
}"""
def segwit_get_sequencehash(stxo):
out=bytearray()
for inp in stxo.ins:
out+=struct.pack('<L',inp.sequence)
return dblsha256(out)
"""template <class T>
uint256 GetSequenceHash(const T& txTo)
{
CHashWriter ss(SER_GETHASH, 0);
for (const auto& txin : txTo.vin) {
ss << txin.nSequence;
}
return ss.GetHash();
}"""
def segwit_get_outputshash(stxo):
out=bytearray()
for outp in stxo.outs:
out+=outp.serialize()
return dblsha256(out)
"""template <class T>
uint256 GetOutputsHash(const T& txTo)
{
CHashWriter ss(SER_GETHASH, 0);
for (const auto& txout : txTo.vout) {
ss << txout;
}
return ss.GetHash();
}
"""
#TODO: segwit needs the right thing provided in script (redeemscript for p2sh or witness script or scriptPubKey for p2pkh)
#https://bitcoin.stackexchange.com/questions/57994/what-is-scriptcode
def segwit_preimage(stxo,script,input_index,nhashtype,amount=None):
hashPrevouts=b'\x00'*32
hashSequence=b'\x00'*32
hashOutputs=b'\x00'*32
nhashtype=int(nhashtype)
sho=SigHashOptions(nhashtype)
"""if (sigversion == SigVersion::WITNESS_V0) {
uint256 hashPrevouts;
uint256 hashSequence;
uint256 hashOutputs;
const bool cacheready = cache && cache->ready;
if (!(nHashType & SIGHASH_ANYONECANPAY)) {
hashPrevouts = cacheready ? cache->hashPrevouts : GetPrevoutHash(txTo);
}
if (!(nHashType & SIGHASH_ANYONECANPAY) && (nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
hashSequence = cacheready ? cache->hashSequence : GetSequenceHash(txTo);
}
if ((nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
hashOutputs = cacheready ? cache->hashOutputs : GetOutputsHash(txTo);
} else if ((nHashType & 0x1f) == SIGHASH_SINGLE && nIn < txTo.vout.size()) {
CHashWriter ss(SER_GETHASH, 0);
ss << txTo.vout[nIn];
hashOutputs = ss.GetHash();
}"""
if(not sho.anyonecanpay):
hashPrevouts=segwit_get_prevouthash(stxo)
if(not sho.anyonecanpay and sho.mode != SIGHASH_NONE and sho.mode != SIGHASH_SINGLE):
hashSequence=segwit_get_sequencehash(stxo)
if(sho.mode != SIGHASH_SINGLE and sho.mode != SIGHASH_NONE):
hashOutputs=segwit_get_outputshash(stxo)
elif(sho.mode == SIGHASH_SINGLE and input_index < len(stxo.ins)):
hashOutputs=dblsha256(stxo.outs[input_index].serialize())
"""
CHashWriter ss(SER_GETHASH, 0);
// Version
ss << txTo.nVersion;
// Input prevouts/nSequence (none/all, depending on flags)
ss << hashPrevouts;
ss << hashSequence;
// The input being signed (replacing the scriptSig with scriptCode + amount)
// The prevout may already be contained in hashPrevout, and the nSequence
// may already be contain in hashSequence.
ss << txTo.vin[nIn].prevout;
ss << scriptCode;
ss << amount;
ss << txTo.vin[nIn].nSequence;
// Outputs (none/one/all, depending on flags)
ss << hashOutputs;
// Locktime
ss << txTo.nLockTime;
// Sighash type
ss << nHashType;
return ss.GetHash();"""
out=bytearray()
out+=struct.pack('<L',stxo.version)
out+=hashPrevouts
out+=hashSequence
out+=stxo.ins[input_index].outpoint.serialize()
out+=SVarInt(len(script)).serialize()
out+=script
if(amount is None):
a=stxo.ins[input_index].prevout.value
else:
a=int(amount)
out+=struct.pack('<Q',a)
out+=struct.pack('<L',stxo.ins[input_index].sequence)
out+=hashOutputs;
out+=struct.pack('<L',stxo.locktime)
out+=struct.pack('<L',sho.nhashtype)
return out
def segwit_sighash(stxo,input_index,nhashtype,script=None,amount=None):
if(script is None):
#if(p2pkh)USE for
script=stxo.ins[input_index].prevout.scriptPubKey #TODO: is this correct? script seems to be the redeemScript for p2sh and other stuff YEAH use for p2sh when redeemScript includes CHECKSIG
#if(p2sh)
#script=stxo.ins[input_index].scriptSig[0] #redeemscript from scriptSig of input gives pubkey o
preimage=segwit_preimage(stxo,script,input_index,nhashtype,amount)
return dblsha256(preimage)
| [
"struct.pack"
] | [((5665, 5696), 'struct.pack', 'struct.pack', (['"""<L"""', 'stxo.version'], {}), "('<L', stxo.version)\n", (5676, 5696), False, 'import struct\n'), ((5927, 5947), 'struct.pack', 'struct.pack', (['"""<Q"""', 'a'], {}), "('<Q', a)\n", (5938, 5947), False, 'import struct\n'), ((5953, 6002), 'struct.pack', 'struct.pack', (['"""<L"""', 'stxo.ins[input_index].sequence'], {}), "('<L', stxo.ins[input_index].sequence)\n", (5964, 6002), False, 'import struct\n'), ((6027, 6059), 'struct.pack', 'struct.pack', (['"""<L"""', 'stxo.locktime'], {}), "('<L', stxo.locktime)\n", (6038, 6059), False, 'import struct\n'), ((6065, 6097), 'struct.pack', 'struct.pack', (['"""<L"""', 'sho.nhashtype'], {}), "('<L', sho.nhashtype)\n", (6076, 6097), False, 'import struct\n'), ((478, 508), 'struct.pack', 'struct.pack', (['"""<L"""', 'txo.version'], {}), "('<L', txo.version)\n", (489, 508), False, 'import struct\n'), ((530, 556), 'struct.pack', 'struct.pack', (['"""B"""', 'txo.flag'], {}), "('B', txo.flag)\n", (541, 556), False, 'import struct\n'), ((1047, 1078), 'struct.pack', 'struct.pack', (['"""<L"""', 'txo.locktime'], {}), "('<L', txo.locktime)\n", (1058, 1078), False, 'import struct\n'), ((2529, 2560), 'struct.pack', 'struct.pack', (['"""<L"""', 'inp.sequence'], {}), "('<L', inp.sequence)\n", (2540, 2560), False, 'import struct\n')] |
from tarfile import open as tarfile_open
from pandas import read_csv
def read_correlate_copynumber_vs_mrnaseq(tar_gz_file_path, genes):
with tarfile_open(tar_gz_file_path) as tar_gz_file:
n = read_csv(
tar_gz_file.extractfile(
tuple(file for file in tar_gz_file if file.name.endswith("qa.txt"))[0]
),
sep="\t",
index_col=0,
).loc["sample", "comm"]
df = read_csv(
tar_gz_file.extractfile(
tuple(file for file in tar_gz_file if file.name.endswith("cors.txt"))[0]
),
sep="\t",
index_col=1,
)
return n, df.loc[genes, "cor"].to_dict()
| [
"tarfile.open"
] | [((149, 179), 'tarfile.open', 'tarfile_open', (['tar_gz_file_path'], {}), '(tar_gz_file_path)\n', (161, 179), True, 'from tarfile import open as tarfile_open\n')] |
#!/usr/bin/env python3
import sys
if sys.version_info >= (3, 3):
import importlib
def import_file(module_path='', module=''):
importlib.invalidate_caches()
if module in sys.modules:
del sys.modules[module]
sys.path.insert(0, module_path)
loader = importlib.find_loader(module)
del sys.path[0]
m = loader.load_module(module)
return m
elif sys.version_info >= (2, 7):
def import_file(module_path='', module=''):
if module in sys.modules:
del sys.modules[module]
sys.path.insert(0, module_path)
m = __import__(module)
del sys.path[0]
return m
else:
raise NotImplementedError('This modules functions are not implemented for python <2.7')
if __name__ == '__main__':
# test this module with path and module name as arguments
# will print modules namespace (without __builtins__)
import pprint
p, n = sys.argv[1:]
m = import_file(p, n)
d = m.__dict__
del d['__builtins__']
pprint.pprint(d)
| [
"importlib.find_loader",
"sys.path.insert",
"importlib.invalidate_caches",
"pprint.pprint"
] | [((1050, 1066), 'pprint.pprint', 'pprint.pprint', (['d'], {}), '(d)\n', (1063, 1066), False, 'import pprint\n'), ((146, 175), 'importlib.invalidate_caches', 'importlib.invalidate_caches', ([], {}), '()\n', (173, 175), False, 'import importlib\n'), ((254, 285), 'sys.path.insert', 'sys.path.insert', (['(0)', 'module_path'], {}), '(0, module_path)\n', (269, 285), False, 'import sys\n'), ((303, 332), 'importlib.find_loader', 'importlib.find_loader', (['module'], {}), '(module)\n', (324, 332), False, 'import importlib\n'), ((575, 606), 'sys.path.insert', 'sys.path.insert', (['(0)', 'module_path'], {}), '(0, module_path)\n', (590, 606), False, 'import sys\n')] |
import os
from pathlib import Path
from flask import Flask, current_app, jsonify, request
from flask_cors import CORS
from mongoengine import connect, MongoEngineConnectionError
import namesgenerator
from model import Doc
from app_logic import random_df, call_r
def create_app(config=None):
app = Flask(__name__)
CORS(app)
app.config.from_object(config)
mongo_host = os.environ.get('MONGO_HOST', default='mongodb://127.0.0.1:27017')
try:
connect(db='pyr',
host=mongo_host)
except MongoEngineConnectionError as exc:
raise exc
@app.route('/api/python')
def test():
"""Random pandas df"""
df = random_df()
return jsonify({'py': df.to_json()}), 200
@app.route('/api/r')
def from_r():
"""Dataframe from an R tibble using rpy2"""
df = call_r(Path(current_app.config['R_LOCATION'], 'rapp.r'))
return jsonify({'r': df.to_json()}), 200
"""MONGO IO API SIMULATION"""
@app.route('/api/add', methods=['POST'])
def add_doc():
try:
d = Doc(title=namesgenerator.get_random_name())
d.save()
return d.to_json(), 201
except Exception as ex:
raise ex
@app.route('/api/remove', methods=['DELETE'])
def remove_doc():
id = request.args.get('id')
try:
d = Doc.objects.get(id=id)
if d:
d.delete()
return jsonify({'ok': 1}), 200
except Exception as ex:
raise ex
return app
| [
"flask.request.args.get",
"namesgenerator.get_random_name",
"flask_cors.CORS",
"flask.Flask",
"pathlib.Path",
"os.environ.get",
"model.Doc.objects.get",
"app_logic.random_df",
"mongoengine.connect",
"flask.jsonify"
] | [((303, 318), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (308, 318), False, 'from flask import Flask, current_app, jsonify, request\n'), ((323, 332), 'flask_cors.CORS', 'CORS', (['app'], {}), '(app)\n', (327, 332), False, 'from flask_cors import CORS\n'), ((386, 451), 'os.environ.get', 'os.environ.get', (['"""MONGO_HOST"""'], {'default': '"""mongodb://127.0.0.1:27017"""'}), "('MONGO_HOST', default='mongodb://127.0.0.1:27017')\n", (400, 451), False, 'import os\n'), ((470, 504), 'mongoengine.connect', 'connect', ([], {'db': '"""pyr"""', 'host': 'mongo_host'}), "(db='pyr', host=mongo_host)\n", (477, 504), False, 'from mongoengine import connect, MongoEngineConnectionError\n'), ((676, 687), 'app_logic.random_df', 'random_df', ([], {}), '()\n', (685, 687), False, 'from app_logic import random_df, call_r\n'), ((1323, 1345), 'flask.request.args.get', 'request.args.get', (['"""id"""'], {}), "('id')\n", (1339, 1345), False, 'from flask import Flask, current_app, jsonify, request\n'), ((854, 902), 'pathlib.Path', 'Path', (["current_app.config['R_LOCATION']", '"""rapp.r"""'], {}), "(current_app.config['R_LOCATION'], 'rapp.r')\n", (858, 902), False, 'from pathlib import Path\n'), ((1375, 1397), 'model.Doc.objects.get', 'Doc.objects.get', ([], {'id': 'id'}), '(id=id)\n', (1390, 1397), False, 'from model import Doc\n'), ((1463, 1481), 'flask.jsonify', 'jsonify', (["{'ok': 1}"], {}), "({'ok': 1})\n", (1470, 1481), False, 'from flask import Flask, current_app, jsonify, request\n'), ((1091, 1123), 'namesgenerator.get_random_name', 'namesgenerator.get_random_name', ([], {}), '()\n', (1121, 1123), False, 'import namesgenerator\n')] |
import os
from configurations.importer import install
from mypy.version import __version__ # noqa: F401
from mypy_django_plugin import main
def plugin(version):
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')
os.environ.setdefault('DJANGO_CONFIGURATION', 'Development')
install()
return main.plugin(version)
| [
"os.environ.setdefault",
"configurations.importer.install",
"mypy_django_plugin.main.plugin"
] | [((169, 233), 'os.environ.setdefault', 'os.environ.setdefault', (['"""DJANGO_SETTINGS_MODULE"""', '"""core.settings"""'], {}), "('DJANGO_SETTINGS_MODULE', 'core.settings')\n", (190, 233), False, 'import os\n'), ((238, 298), 'os.environ.setdefault', 'os.environ.setdefault', (['"""DJANGO_CONFIGURATION"""', '"""Development"""'], {}), "('DJANGO_CONFIGURATION', 'Development')\n", (259, 298), False, 'import os\n'), ((303, 312), 'configurations.importer.install', 'install', ([], {}), '()\n', (310, 312), False, 'from configurations.importer import install\n'), ((324, 344), 'mypy_django_plugin.main.plugin', 'main.plugin', (['version'], {}), '(version)\n', (335, 344), False, 'from mypy_django_plugin import main\n')] |
import numpy as np
from JacobiPolynomials import *
import math
# 1D - LINE
#------------------------------------------------------------------------------------------------------------------#
#------------------------------------------------------------------------------------------------------------------#
#------------------------------------------------------------------------------------------------------------------#
def NormalisedJacobi1D(C,x):
p = np.zeros(C+2)
for i in range(0,C+2):
p[i] = JacobiPolynomials(i,x,0,0)[-1]*np.sqrt((2.*i+1.)/2.)
return p
# 2D - TRI
#------------------------------------------------------------------------------------------------------------------#
#------------------------------------------------------------------------------------------------------------------#
#------------------------------------------------------------------------------------------------------------------#
def NormalisedJacobi2D(C,x):
""" Computes the orthogonal base of 2D polynomials of degree less
or equal to C+1 at the point x=(r,s) in [-1,1]^2 (i.e. on the reference quad)
"""
N = int( (C+2.)*(C+3.)/2. )
p = np.zeros(N)
r = x[0]; s = x[1]
# Ordering: 1st increasing the degree and 2nd lexicogafic order
ncount = 0 # counter for the polynomials order
# Loop on degree
for nDeg in range(0,C+2):
# Loop by increasing i
for i in range(0,nDeg+1):
if i==0:
p_i = 1.; q_i = 1.
else:
p_i = JacobiPolynomials(i,r,0.,0.)[-1]; q_i = q_i*(1.-s)/2.
# Value for j
j = nDeg-i
if j==0:
p_j = 1.
else:
p_j = JacobiPolynomials(j,s,2.*i+1.,0.)[-1]
# factor = np.sqrt( (2.*i+1.)*(i+j+1.)/2. )
factor = math.sqrt( (2.*i+1.)*(i+j+1.)/2. )
p[ncount] = ( p_i*q_i*p_j )*factor
ncount += 1
return p
def NormalisedJacobiTri(C,x):
""" Computes the orthogonal base of 2D polynomials of degree less
or equal to n at the point x=(xi,eta) in the reference triangle
"""
xi = x[0]; eta = x[1]
if eta==1:
r = -1.; s=1.;
else:
r = 2.*(1+xi)/(1.-eta)-1.
s = eta
return NormalisedJacobi2D(C,np.array([r,s]))
def GradNormalisedJacobiTri(C,x,EvalOpt=0):
""" Computes the orthogonal base of 2D polynomials of degree less
or equal to n at the point x=(xi,eta) in the reference triangle
"""
N = int((C+2.)*(C+3.)/2.)
p = np.zeros(N);
dp_dxi = np.zeros(N)
dp_deta = np.zeros(N)
r = x[0]; s = x[1]
# THIS MAY RUIN THE CONVERGENCE, BUT FOR POST PROCESSING ITS FINE
if EvalOpt==1:
if s==1:
s=0.99999999999999
xi = (1.+r)*(1.-s)/2.-1
eta = s
dr_dxi = 2./(1.-eta)
dr_deta = 2.*(1.+xi)/(1.-eta)**2
# Derivative of s is not needed because s=eta
# Ordering: 1st increasing the degree and 2nd lexicogafic order
ncount = 0
# Loop on degree
for nDeg in range(0,C+2):
# Loop increasing i
for i in range(0,nDeg+1):
if i==0:
p_i = 1; q_i = 1; dp_i = 0; dq_i = 0
else:
p_i = JacobiPolynomials(i,r,0.,0.)[-1]; dp_i = JacobiPolynomials(i-1,r,1.,1.)[-1]*(i+1.)/2.
q_i = q_i*(1.-s)/2.; dq_i = 1.*q_i*(-i)/(1-s)
# Value for j
j = nDeg-i
if j==0:
p_j = 1; dp_j = 0
else:
p_j = JacobiPolynomials(j,s,2.*i+1.,0.)[-1]; dp_j = JacobiPolynomials(j-1,s,2.*i+2.,1.)[-1]*(j+2.*i+2.)/2.
factor = math.sqrt( (2.*i+1.)*(i+j+1.)/2. )
# Normalized polynomial
p[ncount] = ( p_i*q_i*p_j )*factor
# Derivatives with respect to (r,s)
dp_dr = ( (dp_i)*q_i*p_j )*factor
dp_ds = ( p_i*(dq_i*p_j+q_i*dp_j) )*factor
# Derivatives with respect to (xi,eta)
dp_dxi[ncount] = dp_dr*dr_dxi
dp_deta[ncount] = dp_dr*dr_deta + dp_ds
ncount += 1
return p,dp_dxi,dp_deta
# 3D - TET
#------------------------------------------------------------------------------------------------------------------#
#------------------------------------------------------------------------------------------------------------------#
#------------------------------------------------------------------------------------------------------------------#
def NormalisedJacobi3D(C,x):
"""Computes the orthogonal base of 3D polynomials of degree less
or equal to n at the point x=(r,s,t) in [-1,1]^3
"""
N = int((C+2)*(C+3)*(C+4)/6.)
p = np.zeros(N)
r = x[0]; s = x[1]; t = x[2]
# Ordering: 1st incresing the degree and 2nd lexicogafic order
ncount = 0
# Loop on degree
for nDeg in range(0,C+2):
# Loop increasing i
for i in range(0,nDeg+1):
if i==0:
p_i = 1; q_i = 1
else:
p_i = JacobiPolynomials(i,r,0.,0.)[-1]; q_i = q_i*(1.-s)/2.
# Loop increasing j
for j in range(0,nDeg-i+1):
if j==0:
p_j = 1; q_j = ((1.-t)/2.)**i
else:
p_j = JacobiPolynomials(j,s,2.*i+1.,0.)[-1]; q_j = q_j*(1.-t)/2.
# Value for k
k = nDeg-(i+j)
if k==0:
p_k = 1.
else:
p_k = JacobiPolynomials(k,t,2.*(i+j)+2.,0.)[-1]
factor = math.sqrt( (2.*i+1.)*(i+j+1.)*(2.*(i+j+k)+3.)/4. )
p[ncount] = ( p_i*q_i*p_j*q_j*p_k )*factor
ncount += 1
return p
def NormalisedJacobiTet(C,x):
"""Computes the orthogonal base of 3D polynomials of degree less
or equal to n at the point x=(r,s,t) in [-1,1]^3
"""
xi = x[0]; eta = x[1]; zeta = x[2]
if (eta+zeta)==0:
r = -1; s=1
elif zeta==1:
r = -1; s=1 # or s=-1 (check that nothing changes)
else:
r = -2.*(1+xi)/(eta+zeta)-1.;
s = 2.*(1+eta)/(1-zeta)-1.;
t = zeta
return NormalisedJacobi3D(C,[r,s,t])
# return NormalisedJacobi3D_Native(C,[r,s,t])
def GradNormalisedJacobiTet(C,x,EvalOpt=0):
"""Computes the orthogonal base of 3D polynomials of degree less
or equal to n at the point x=(r,s,t) in [-1,1]^3
"""
N = int((C+2)*(C+3)*(C+4)/6.)
p = np.zeros(N)
dp_dxi = np.zeros(N)
dp_deta = np.zeros(N)
dp_dzeta = np.zeros(N)
r = x[0]; s = x[1]; t = x[2]
# THIS MAY RUIN THE CONVERGENCE, BUT FOR POST PROCESSING ITS FINE
if EvalOpt==1:
if t==1.:
t=0.999999999999
if np.isclose(s,1.):
s=0.999999999999
if np.isclose(s,1.):
s=0.99999999999999
eta = (1./2.)*(s-s*t-1.-t)
xi = -(1./2.)*(r+1)*(eta+t)-1.
zeta = 1.0*t
# THIS MAY RUIN THE CONVERGENCE, BUT FOR POST PROCESSING ITS FINE
if eta == 0. and zeta == 0.:
eta = 1.0e-14
zeta = 1e-14
eta_zeta = eta+zeta
if np.isclose(eta_zeta,0.):
eta_zeta = 0.000000001
dr_dxi = -2./eta_zeta
dr_deta = 2.*(1.+xi)/eta_zeta**2
dr_dzeta = dr_deta
ds_deta = 2./(1.-zeta)
ds_dzeta = 2.*(1.+eta)/(1.-zeta)**2
# Derivative of t is not needed because t=zeta
#--------------------------------------------------------
# if np.allclose(eta+zeta,0):
# dr_dxi = -2./(0.001)**2
# dr_deta = 2.*(1.+xi)/(0.001)**2
# else:
# dr_dxi = -2./(eta+zeta)
# dr_deta = 2.*(1.+xi)/(eta+zeta)**2
# dr_dzeta = dr_deta
# if np.allclose(eta+zeta,0):
# ds_deta = 2./(0.001)
# ds_dzeta = 2.*(1.+eta)/(0.001)**2
# else:
# ds_deta = 2./(1.-zeta)
# ds_dzeta = 2.*(1.+eta)/(1.-zeta)**2
#--------------------------------------------------------
# Ordering: 1st increasing the degree and 2nd lexicogafic order
ncount = 0
# Loop on degree
for nDeg in range(0,C+2):
# Loop increasing i
for i in range(0,nDeg+1):
if i==0:
p_i = 1.; q_i = 1.; dp_i = 0.; dq_i = 0.
else:
p_i = JacobiPolynomials(i,r,0.,0.)[-1]; dp_i = JacobiPolynomials(i-1,r,1.,1.)[-1]*(i+1.)/2.
q_i = q_i*(1.-s)/2.; dq_i = q_i*(-i)/(1.-s)
# Loop increasing j
for j in range(0,nDeg-i+1):
if j==0:
p_j = 1; q_j = ((1.-t)/2.)**i; dp_j = 0; dq_j = q_j*(-(i+j))/(1.-t);
else:
p_j = JacobiPolynomials(j,s,2.*i+1.,0.)[-1]; dp_j = JacobiPolynomials(j-1,s,2.*i+2.,1.)[-1]*(j+2.*i+2.)/2.
q_j = q_j*(1.-t)/2.; dq_j = q_j*(-(i+j))/(1.-t)
# Value for k
k = nDeg-(i+j);
if k==0:
p_k = 1.; dp_k = 0.;
else:
p_k = JacobiPolynomials(k,t,2.*(i+j)+2.,0.)[-1]; dp_k = JacobiPolynomials(k-1,t,2.*(i+j)+3.,1.)[-1]*(k+2.*i+2.*j+3.)/2.
factor = math.sqrt( (2.*i+1.)*(i+j+1.)*(2.*(i+j+k)+3.)/4. )
# Normalized polynomial
p[ncount] = ( p_i*q_i*p_j*q_j*p_k )*factor
# Derivatives with respect to (r,s,t)
dp_dr = ( (dp_i)*q_i*p_j*q_j*p_k )*factor
dp_ds = ( p_i*(dq_i*p_j+q_i*dp_j)*q_j*p_k )*factor
dp_dt = ( p_i*q_i*p_j*(dq_j*p_k+q_j*dp_k) )*factor
# Derivatives with respect to (xi,eta,zeta)
dp_dxi[ncount] = dp_dr*dr_dxi
dp_deta[ncount] = dp_dr*dr_deta + dp_ds*ds_deta
dp_dzeta[ncount] = dp_dr*dr_dzeta + dp_ds*ds_dzeta + dp_dt
ncount += 1
return p,dp_dxi,dp_deta,dp_dzeta | [
"numpy.sqrt",
"numpy.isclose",
"math.sqrt",
"numpy.array",
"numpy.zeros"
] | [((464, 479), 'numpy.zeros', 'np.zeros', (['(C + 2)'], {}), '(C + 2)\n', (472, 479), True, 'import numpy as np\n'), ((1188, 1199), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (1196, 1199), True, 'import numpy as np\n'), ((2575, 2586), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (2583, 2586), True, 'import numpy as np\n'), ((2602, 2613), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (2610, 2613), True, 'import numpy as np\n'), ((2628, 2639), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (2636, 2639), True, 'import numpy as np\n'), ((4724, 4735), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (4732, 4735), True, 'import numpy as np\n'), ((6497, 6508), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (6505, 6508), True, 'import numpy as np\n'), ((6525, 6536), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (6533, 6536), True, 'import numpy as np\n'), ((6552, 6563), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (6560, 6563), True, 'import numpy as np\n'), ((6579, 6590), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (6587, 6590), True, 'import numpy as np\n'), ((6828, 6846), 'numpy.isclose', 'np.isclose', (['s', '(1.0)'], {}), '(s, 1.0)\n', (6838, 6846), True, 'import numpy as np\n'), ((7140, 7165), 'numpy.isclose', 'np.isclose', (['eta_zeta', '(0.0)'], {}), '(eta_zeta, 0.0)\n', (7150, 7165), True, 'import numpy as np\n'), ((2322, 2338), 'numpy.array', 'np.array', (['[r, s]'], {}), '([r, s])\n', (2330, 2338), True, 'import numpy as np\n'), ((6773, 6791), 'numpy.isclose', 'np.isclose', (['s', '(1.0)'], {}), '(s, 1.0)\n', (6783, 6791), True, 'import numpy as np\n'), ((552, 582), 'numpy.sqrt', 'np.sqrt', (['((2.0 * i + 1.0) / 2.0)'], {}), '((2.0 * i + 1.0) / 2.0)\n', (559, 582), True, 'import numpy as np\n'), ((1862, 1910), 'math.sqrt', 'math.sqrt', (['((2.0 * i + 1.0) * (i + j + 1.0) / 2.0)'], {}), '((2.0 * i + 1.0) * (i + j + 1.0) / 2.0)\n', (1871, 1910), False, 'import math\n'), ((3685, 3733), 'math.sqrt', 'math.sqrt', (['((2.0 * i + 1.0) * (i + j + 1.0) / 2.0)'], {}), '((2.0 * i + 1.0) * (i + j + 1.0) / 2.0)\n', (3694, 3733), False, 'import math\n'), ((5606, 5682), 'math.sqrt', 'math.sqrt', (['((2.0 * i + 1.0) * (i + j + 1.0) * (2.0 * (i + j + k) + 3.0) / 4.0)'], {}), '((2.0 * i + 1.0) * (i + j + 1.0) * (2.0 * (i + j + k) + 3.0) / 4.0)\n', (5615, 5682), False, 'import math\n'), ((9156, 9232), 'math.sqrt', 'math.sqrt', (['((2.0 * i + 1.0) * (i + j + 1.0) * (2.0 * (i + j + k) + 3.0) / 4.0)'], {}), '((2.0 * i + 1.0) * (i + j + 1.0) * (2.0 * (i + j + k) + 3.0) / 4.0)\n', (9165, 9232), False, 'import math\n')] |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import calendar
import frappe
from datetime import datetime
from frappe.utils import today
from frappe import _
from frappe.model.document import Document
class LeaveType(Document):
def validate(self):
if self.is_lwp:
leave_allocation = frappe.get_all("Leave Allocation", filters={
'leave_type': self.name,
'from_date': ("<=", today()),
'to_date': (">=", today())
}, fields=['name'])
leave_allocation = [l['name'] for l in leave_allocation]
if leave_allocation:
frappe.throw(_('Leave application is linked with leave allocations {0}. Leave application cannot be set as leave without pay').format(", ".join(leave_allocation))) #nosec
if self.is_lwp and self.is_ppl:
frappe.throw(_("Leave Type can be either without pay or partial pay"))
if self.is_ppl and (self.fraction_of_daily_salary_per_leave < 0 or self.fraction_of_daily_salary_per_leave > 1):
frappe.throw(_("The fraction of Daily Salary per Leave should be between 0 and 1"))
| [
"frappe.utils.today",
"frappe._"
] | [((885, 941), 'frappe._', '_', (['"""Leave Type can be either without pay or partial pay"""'], {}), "('Leave Type can be either without pay or partial pay')\n", (886, 941), False, 'from frappe import _\n'), ((1076, 1145), 'frappe._', '_', (['"""The fraction of Daily Salary per Leave should be between 0 and 1"""'], {}), "('The fraction of Daily Salary per Leave should be between 0 and 1')\n", (1077, 1145), False, 'from frappe import _\n'), ((511, 518), 'frappe.utils.today', 'today', ([], {}), '()\n', (516, 518), False, 'from frappe.utils import today\n'), ((543, 550), 'frappe.utils.today', 'today', ([], {}), '()\n', (548, 550), False, 'from frappe.utils import today\n'), ((676, 794), 'frappe._', '_', (['"""Leave application is linked with leave allocations {0}. Leave application cannot be set as leave without pay"""'], {}), "('Leave application is linked with leave allocations {0}. Leave application cannot be set as leave without pay'\n )\n", (677, 794), False, 'from frappe import _\n')] |
import os
import torch
import librosa
import pickle
import soundfile as sf
from synthesis import build_model
from synthesis import wavegen
spect_vc = pickle.load(open('results.pkl', 'rb'))
device = torch.device("cuda")
model = build_model().to(device)
checkpoint = torch.load("checkpoint_step001000000_ema.pth")
model.load_state_dict(checkpoint["state_dict"])
outputDir = './wavs'
for spect in spect_vc:
name = spect[0]
c = spect[1]
print(name)
waveform = wavegen(model, c=c)
#librosa.output.write_wav(name+'.wav', waveform, sr=16000)
sf.write(os.path.join(outputDir, name+'.wav'), waveform, 16000) | [
"synthesis.wavegen",
"synthesis.build_model",
"torch.load",
"os.path.join",
"torch.device"
] | [((199, 219), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (211, 219), False, 'import torch\n'), ((266, 312), 'torch.load', 'torch.load', (['"""checkpoint_step001000000_ema.pth"""'], {}), "('checkpoint_step001000000_ema.pth')\n", (276, 312), False, 'import torch\n'), ((475, 494), 'synthesis.wavegen', 'wavegen', (['model'], {'c': 'c'}), '(model, c=c)\n', (482, 494), False, 'from synthesis import wavegen\n'), ((228, 241), 'synthesis.build_model', 'build_model', ([], {}), '()\n', (239, 241), False, 'from synthesis import build_model\n'), ((574, 612), 'os.path.join', 'os.path.join', (['outputDir', "(name + '.wav')"], {}), "(outputDir, name + '.wav')\n", (586, 612), False, 'import os\n')] |
import time
from contextlib import suppress, contextmanager
from astropy import units as u
from panoptes.utils import error
from panoptes.utils.utils import get_quantity_value
from panoptes.utils.time import current_time, wait_for_events, CountdownTimer
from panoptes.pocs.observatory import Observatory
from panoptes.pocs.scheduler.observation.bias import BiasObservation
from huntsman.pocs.utils.logger import get_logger
from huntsman.pocs.guide.bisque import Guide
from huntsman.pocs.archive.utils import remove_empty_directories
from huntsman.pocs.scheduler.observation.dark import DarkObservation
from huntsman.pocs.utils.flats import make_flat_field_sequences, make_flat_field_observation
from huntsman.pocs.utils.flats import get_cameras_with_filter
from huntsman.pocs.utils.safety import get_solar_altaz
from huntsman.pocs.camera.group import CameraGroup, dispatch_parallel
from huntsman.pocs.error import NotTwilightError
class HuntsmanObservatory(Observatory):
def __init__(self, with_autoguider=True, hdr_mode=False, take_flats=True, logger=None,
*args, **kwargs):
"""Huntsman POCS Observatory
Args:
with_autoguider (bool, optional): If autoguider is attached, defaults to True.
hdr_mode (bool, optional): If pics should be taken in HDR mode, defaults to False.
take_flats (bool, optional): If flat field images should be taken, defaults to True.
logger (logger, optional): The logger instance. If not provided, use default Huntsman
logger.
*args: Parsed to Observatory init function.
**kwargs: Parsed to Observatory init function.
"""
if not logger:
logger = get_logger()
super().__init__(logger=logger, *args, **kwargs)
# Make a camera group
self.camera_group = CameraGroup(self.cameras)
self._has_hdr_mode = hdr_mode
self._has_autoguider = with_autoguider
self.flat_fields_required = take_flats
# Focusing
self.last_coarse_focus_time = None
self.last_coarse_focus_temp = None
self._coarse_focus_interval = self.get_config('focusing.coarse.interval_hours', 1) * u.hour
self._coarse_focus_filter = self.get_config('focusing.coarse.filter_name')
self._coarse_focus_temptol = self.get_config('focusing.coarse.temp_tol_deg', 5) * u.Celsius
self.last_fine_focus_time = None
self.last_fine_focus_temp = None
self._fine_focus_interval = self.get_config('focusing.fine.interval_hours', 1) * u.hour
self._fine_focus_temptol = self.get_config('focusing.fine.temp_tol_deg', 5) * u.Celsius
if self.has_autoguider:
self.logger.info("Setting up autoguider")
try:
self._create_autoguider()
except Exception as e:
self._has_autoguider = False
self.logger.warning(f"Problem setting autoguider, continuing without: {e!r}")
# Hack solution to the observatory not knowing whether it is safe or not
# This can be overridden when creating the HuntsmanPOCS instance
self._is_safe = None
# Properties
@property
def has_hdr_mode(self):
""" Does camera support HDR mode
Returns:
bool: HDR enabled, default False
"""
return self._has_hdr_mode
@property
def has_autoguider(self):
""" Does camera have attached autoguider
Returns:
bool: True if has autoguider
"""
return self._has_autoguider
@property
def coarse_focus_required(self):
""" Return True if we should do a coarse focus. """
return self._focus_required(coarse=True)
@property
def fine_focus_required(self):
""" Return True if we should do a fine focus. """
return self._focus_required()
@property
def is_past_midnight(self):
"""Check if it's morning, useful for going into either morning or evening flats."""
# Get the time of the nearest midnight to now
# If the nearest midnight is in the past, it's the morning
midnight = self.observer.midnight(current_time(), which='nearest')
return midnight < current_time()
@property
def is_twilight(self):
""" Return True if it is twilight, else False. """
return self.is_dark(horizon="twilight_max") and not self.is_dark(horizon="twilight_min")
@property
def temperature(self):
""" Return the ambient temperature. """
temp = None
try:
reading = self.db.get_current("weather")["data"]["ambient_temp_C"]
temp = get_quantity_value(reading, u.Celsius) * u.Celsius
except (KeyError, TypeError) as err:
self.logger.warning(f"Unable to determine temperature: {err!r}")
return temp
@property
def solar_altaz(self):
""" Return the current solar alt az. """
return get_solar_altaz(location=self.earth_location, time=current_time())
# Context managers
@contextmanager
def safety_checking(self, *args, **kwargs):
""" Check safety before and after the code block.
To be used with a "with" statement, e.g.:
with self.safety_checking():
print(x)
Args:
*args, **kwargs: Parsed to self._assert_safe
Raises:
RuntimeError: If not safe.
"""
self._assert_safe(*args, **kwargs)
try:
yield None
finally:
self._assert_safe(*args, **kwargs)
# Methods
def initialize(self):
"""Initialize the observatory and connected hardware """
super().initialize()
if self.has_autoguider:
self.logger.debug("Connecting to autoguider")
self.autoguider.connect()
def is_safe(self, park_if_not_safe=False, *args, **kwargs):
""" Return True if it is safe, else False.
Args:
*args, **kwargs: Parsed to self._is_safe. See panoptes.pocs.core.POCS.is_safe.
park_if_not_safe (bool): If True, park if safety fails. Default: False.
Returns:
bool: True if safe, else False.
"""
if self._is_safe is not None:
return self._is_safe(park_if_not_safe=park_if_not_safe, *args, **kwargs)
self.logger.warning("Safety function not set. Returning False")
return False
def remove_camera(self, cam_name):
""" Remove a camera from the observatory.
Args:
cam_name (str): The name of the camera to remove.
"""
super().remove_camera(cam_name)
with suppress(KeyError):
del self.camera_group.cameras[cam_name]
def autofocus_cameras(self, coarse=False, filter_name=None, default_timeout=900,
blocking=True, **kwargs):
""" Override autofocus_cameras to update the last focus time and move filterwheels.
Args:
coarse (bool, optional): Perform coarse focus? Default False.
filter_name (str, optional): The filter name to focus with. If None (default), will
attempt to get from config, by default using the coarse focus filter.
*args, **kwargs: Parsed to `pocs.observatory.Observatory.autofocus_cameras`.
Returns:
threading.Event: The autofocus event.
"""
focus_type = "coarse" if coarse else "fine"
# Choose the filter to focus with
# TODO: Move this logic to the camera level
if filter_name is None:
if coarse:
filter_name = self._coarse_focus_filter
else:
try:
filter_name = self.current_observation.filter_name
except AttributeError:
filter_name = self._coarse_focus_filter
self.logger.warning("Unable to retrieve filter name from current observation."
f" Defaulting to coarse focus filter ({filter_name}).")
# Asyncronously dispatch autofocus calls
with self.safety_checking(horizon="focus"):
events = self.camera_group.autofocus(coarse=coarse, filter_name=filter_name, **kwargs)
# Wait for sequences to finish
if blocking:
timeout = self.get_config(f"focusing.{focus_type}.timeout", default_timeout)
if not wait_for_events(list(events.values()), timeout=timeout):
raise error.Timeout(f"Timeout of {timeout} reached while waiting for fine focus.")
# Update last focus time
setattr(self, f"last_{focus_type}_focus_time", current_time())
# Update last focus temperature
setattr(self, f"last_{focus_type}_focus_temp", self.temperature)
return events
def cleanup_observations(self, *args, **kwargs):
""" Override method to remove empty directories. Called in housekeeping state."""
super().cleanup_observations(*args, **kwargs)
self.logger.info("Removing empty directories in images directory.")
images_dir = self.get_config("directories.images")
remove_empty_directories(images_dir)
self.logger.info("Removing empty directories in archive directory.")
archive_dir = self.get_config("directories.archive")
remove_empty_directories(archive_dir)
def take_flat_fields(self, cameras=None, **kwargs):
""" Take flat fields for each camera in each filter, respecting filter order.
Args:
cameras (dict): Dict of cam_name: camera pairs. If None (default), use all cameras.
**kwargs: Overrides config entries under `calibs.flat`.
"""
if cameras is None:
cameras = self.cameras
# Load the flat field config, allowing overrides from kwargs
flat_config = self.get_config('calibs.flat', default=dict())
flat_config.update(kwargs)
# Specify filter order
filter_order = flat_config['filter_order'].copy()
if self.is_past_midnight: # If it's the morning, order is reversed
filter_order.reverse()
# Take flat fields in each filter
for filter_name in filter_order:
if not (self.is_safe(horizon="twilight_max") and self.is_twilight):
raise RuntimeError("Not safe for twilight flats. Aborting.")
# Get a dict of cameras that have this filter
cameras_with_filter = get_cameras_with_filter(cameras, filter_name)
# Go to next filter if there are no cameras with this one
if not cameras_with_filter:
self.logger.warning(f'No cameras found with {filter_name} filter.')
continue
# Get the flat field observation
observation = make_flat_field_observation(self.earth_location, filter_name=filter_name)
observation.seq_time = current_time(flatten=True)
# Take the flats for each camera in this filter
self.logger.info(f'Taking flat fields in {filter_name} filter.')
autoflat_config = flat_config.get("autoflats", {})
try:
self._take_autoflats(cameras_with_filter, observation, **autoflat_config)
# Break out of loop if no longer twilight
# Catch the error so the state machine keeps running
except NotTwilightError as err:
self.logger.warning(f"{err!r}")
break
self.logger.info('Finished flat-fielding.')
def prepare_cameras(self, drop=True, *args, **kwargs):
""" Make sure cameras are all cooled and ready.
Args:
drop (bool): If True, drop cameras that do not become ready in time. Default: True.
*args, **kwargs: Parsed to self.camera_group.wait_until_ready.
"""
self.logger.info(f"Preparing {len(self.cameras)} cameras.")
failed_cameras = self.camera_group.wait_until_ready(*args, **kwargs)
# Remove cameras that didn't become ready in time
if drop:
for cam_name in failed_cameras:
self.logger.debug(f'Removing {cam_name} from {self} for not being ready.')
self.remove_camera(cam_name)
def take_observation_block(self, observation, cameras=None, timeout=60 * u.second,
remove_on_error=False, do_focus=True, safety_kwargs=None,
do_slew=True):
""" Macro function to take an observation block.
This function will perform:
- slewing (when necessary)
- fine focusing (when necessary)
- observation exposures
- safety checking
Args:
observation (Observation): The observation object.
cameras (dict, optional): Dict of cam_name: camera pairs. If None (default), use all
cameras.
timeout (float, optional): The timeout in addition to the exposure time. Default 60s.
remove_on_error (bool, default False): If True, remove cameras that timeout. If False,
raise a TimeoutError instead.
do_slew (bool, optional): If True, do not attempt to slew the telescope. Default
False.
**safety_kwargs (dict, optional): Extra kwargs to be parsed to safety function.
Raises:
RuntimeError: If safety check fails.
"""
if cameras is None:
cameras = self.cameras
safety_kwargs = {} if safety_kwargs is None else safety_kwargs
self._assert_safe(**safety_kwargs)
# Set the sequence time of the observation
if observation.seq_time is None:
observation.seq_time = current_time(flatten=True)
headers = self.get_standard_headers(observation=observation)
# Take the observation block
self.logger.info(f"Starting observation block for {observation}")
# The start new set flag is True before we enter the loop and is set to False
# immediately inside the loop. This allows the loop to start a new set in case
# the set_is_finished condition is already satisfied.
start_new_set = True
current_field = None
while (start_new_set or not observation.set_is_finished):
start_new_set = False # We don't want to start another set after this one
# Perform the slew if necessary
slew_required = (current_field != observation.field) and do_slew
if slew_required:
with self.safety_checking(**safety_kwargs):
self.slew_to_observation(observation)
current_field = observation.field
# Fine focus the cameras if necessary
focus_required = self.fine_focus_required or observation.current_exp_num == 0
if do_focus and focus_required:
with self.safety_checking(**safety_kwargs):
self.autofocus_cameras(blocking=True, filter_name=observation.filter_name)
# Set a common start time for this batch of exposures
headers['start_time'] = current_time(flatten=True)
# Start the exposures and get events
with self.safety_checking(**safety_kwargs):
events = self.camera_group.take_observation(observation, headers=headers)
# Wait for the exposures (blocking)
# TODO: Use same timeout as camera client
try:
self._wait_for_camera_events(events, duration=observation.exptime + timeout,
remove_on_error=remove_on_error, **safety_kwargs)
except error.Timeout as err:
self.logger.error(f"{err!r}")
self.logger.warning("Continuing with observation block after error.")
# Explicitly mark the observation as complete
with suppress(AttributeError):
observation.mark_exposure_complete()
self.logger.info(f"Observation status: {observation.status}")
def take_dark_observation(self, bias=False, **kwargs):
""" Take a bias observation block on each camera (blocking).
Args:
bias (bool, optional): If True, take Bias observation instead of dark observation.
Default: False.
**kwargs: Parsed to `self.take_observation_block`.
"""
# Move telescope to park position
if not self.mount.is_parked:
self.logger.info("Moving telescope to park position for dark observation.")
self.mount.park()
# Create the observation
# Keep the mount where it is since we are just taking darks
position = self.mount.get_current_coordinates()
ObsClass = BiasObservation if bias else DarkObservation
observation = ObsClass(position=position)
# Dark observations don't care if it's dark or not
safety_kwargs = {"ignore": ["is_dark"]}
# Can ignore weather safety if dome is closed
with suppress(AttributeError):
if self.dome.is_closed:
self.logger.warning(f"Ignoring weather safety for {observation}.")
safety_kwargs["ignore"].append("good_weather")
# Take the observation (blocking)
self.take_observation_block(observation, do_focus=False, do_slew=False,
safety_kwargs=safety_kwargs, **kwargs)
def slew_to_observation(self, observation, min_solar_alt=10 * u.deg):
""" Slew to the observation field coordinates.
Args:
observation (Observation): The observation object.
min_solar_alt (astropy.Quantity, optional): The minimum solar altitude above which the
FWs will be moved to their dark positions before slewing.
"""
self.logger.info(f"Slewing to target coordinates for {observation}.")
if not self.mount.set_target_coordinates(observation.field.coord):
raise RuntimeError(f"Unable to set target coordinates for {observation.field}.")
# Move FWs to dark pos if Sun too high to minimise damage potential
move_fws = self.solar_altaz.alt > get_quantity_value(min_solar_alt, u.deg) * u.deg
if move_fws:
self.logger.warning("Solar altitude above minimum for safe slew. Moving FWs to dark"
" positions.")
# Record curent positions so we can put them back after slew
# NOTE: These positions could include the dark position so can't use last_light_position
current_fw_positions = {}
for cam_name, cam in self.cameras.items():
if cam.has_filterwheel:
current_fw_positions[cam_name] = cam.filterwheel.current_filter
self.camera_group.filterwheel_move_to(current_fw_positions)
self.mount.slew_to_target()
if move_fws:
self.logger.info("Moving FWs back to last positions.")
self.camera_group.filterwheel_move_to(current_fw_positions)
# Private methods
def _create_autoguider(self):
guider_config = self.get_config('guider')
guider = Guide(**guider_config)
self.autoguider = guider
def _take_autoflats(
self, cameras, observation, target_scaling=0.17, scaling_tolerance=0.05, timeout=60,
bias=32, remove_on_error=False, sleep_time=300, evening_initial_flat_exptime=0.01,
morning_initial_flat_exptime=1, **kwargs):
""" Take flat fields using automatic updates for exposure times.
Args:
cameras (dict): Dict of camera name: Camera pairs.
observation: The flat field observation. TODO: Integrate with FlatFieldSequence.
target_scaling (float, optional): Required to be between [0, 1] so
target_adu is proportionally between 0 and digital saturation level.
Default: 0.17.
scaling_tolerance (float, optional): The minimum precision on the average counts
required to keep the exposure, expressed as a fraction of the dynamic range.
Default: 0.05.
timeout (float): The timeout on top of the exposure time, default 60s.
bias (int): The bias to subtract from the frames. TODO: Use a real bias image!
remove_on_error (bool, default False): If True, remove cameras that timeout. If False,
raise a TimeoutError instead.
**kwargs: Parsed to FlatFieldSequence.
"""
# set the initial exposure time
if self.is_past_midnight:
initial_exptime = morning_initial_flat_exptime
else:
initial_exptime = evening_initial_flat_exptime
# Create a flat field sequence for each camera
sequences = make_flat_field_sequences(cameras, target_scaling, scaling_tolerance,
bias, initial_exposure_time=initial_exptime, **kwargs)
# Loop until sequence has finished
self.logger.info(f"Starting flat field sequence for {len(self.cameras)} cameras.")
while True:
if not self.is_twilight:
raise NotTwilightError("No longer twilight. Aborting flat fields.")
# Slew to field
with self.safety_checking(horizon="twilight_max"):
self.slew_to_observation(observation)
# Get standard fits headers
headers = self.get_standard_headers(observation=observation)
events = {}
exptimes = {}
filenames = {}
start_times = {}
# Define function to start the exposures
def func(cam_name):
seq = sequences[cam_name]
camera = cameras[cam_name]
# Get exposure time, filename and current time
exptimes[cam_name] = seq.get_next_exptime(past_midnight=self.is_past_midnight)
filenames[cam_name] = observation.get_exposure_filename(camera)
start_times[cam_name] = current_time()
try:
events[cam_name] = camera.take_observation(
observation, headers=headers, filename=filenames[cam_name],
exptime=exptimes[cam_name])
except error.PanError as err:
self.logger.error(f"{err!r}")
self.logger.warning("Continuing with flat observation after error.")
# Start the exposures in parallel
dispatch_parallel(func, list(cameras.keys()))
# Wait for the exposures
self.logger.info('Waiting for flat field exposures to complete.')
duration = get_quantity_value(max(exptimes.values()), u.second) + timeout
try:
self._wait_for_camera_events(events, duration, remove_on_error=remove_on_error,
horizon="twilight_max")
except error.Timeout as err:
self.logger.error(f"{err!r}")
self.logger.warning("Continuing with flat observation after timeout error.")
# Mark the current exposure as complete
observation.mark_exposure_complete()
# Update the flat field sequences with new data
for cam_name in list(sequences.keys()):
# Remove sequence for any removed cameras
if cam_name not in self.cameras:
del sequences[cam_name]
continue
# Attempt to update the exposure sequence for this camera.
# If the exposure failed, use info from the last successful exposure.
try:
sequences[cam_name].update(filename=filenames[cam_name],
exptime=exptimes[cam_name],
time_start=start_times[cam_name])
except (KeyError, FileNotFoundError) as err:
self.logger.warning(f"Unable to update flat field sequence for {cam_name}:"
f" {err!r}")
# Log sequence status
status = sequences[cam_name].status
status["filter_name"] = observation.filter_name
self.logger.info(f"Flat field status for {cam_name}: {status}")
# Check if sequences are complete
if all([s.is_finished for s in sequences.values()]):
self.logger.info("All flat field sequences finished.")
break
# Check if counts are ok
if self.is_past_midnight:
# Terminate if Sun is coming up and all exposures are too bright
if all([s.min_exptime_reached for s in sequences.values()]):
self.logger.info(f"Terminating flat sequence for {observation.filter_name}"
f" filter because min exposure time reached.")
break
# Wait if Sun is coming up and all exposures are too faint
elif all([s.max_exptime_reached for s in sequences.values()]):
self.logger.info(f"All exposures are too faint. Waiting for {sleep_time}s")
self._safe_sleep(sleep_time, horizon="twilight_max")
else:
# Terminate if Sun is going down and all exposures are too faint
if all([s.max_exptime_reached for s in sequences.values()]):
self.logger.info(f"Terminating flat sequence for {observation.filter_name}"
f" filter because max exposure time reached.")
break
# Wait if Sun is going down and all exposures are too bright
elif all([s.max_exptime_reached for s in sequences.values()]):
self.logger.info(f"All exposures are too bright. Waiting for {sleep_time}s")
self._safe_sleep(sleep_time, horizon="twilight_max")
def _wait_for_camera_events(self, events, duration, remove_on_error=False, sleep=1, **kwargs):
""" Wait for camera events to be set.
Args:
events (dict of camera_name: threading.Event): The events to wait for.
duration (float): The total amount of time to wait for (should include exptime).
remove_on_error (bool, default False): If True, remove cameras that timeout. If False,
raise a TimeoutError instead.
sleep (float): Sleep this long between event checks. Default 1s.
**kwargs: Parsed to self._assert_safe.
"""
self.logger.debug(f'Waiting for {len(events)} events with timeout of {duration}.')
timer = CountdownTimer(duration)
while not timer.expired():
# Check safety here
self._assert_safe(**kwargs)
# Check if all cameras have finished
if all([e.is_set() for e in events.values()]):
break
time.sleep(sleep)
# Make sure events are set
for cam_name, event in events.items():
if not event.is_set():
if remove_on_error:
self.logger.warning(f"Timeout while waiting for camera event on {cam_name}. "
"Removing from observatory.")
self.remove_camera(cam_name)
else:
raise error.Timeout(f"Timeout while waiting for camera event on {cam_name}.")
def _focus_required(self, coarse=False):
""" Check if a focus is required based on current conditions.
Args:
coarse (bool): If True, check if we need to do a coarse focus. Default: False.
Returns:
bool: True if focus required, else False.
"""
focus_type = "coarse" if coarse else "fine"
# If a long time period has passed then focus again
last_focus_time = getattr(self, f"last_{focus_type}_focus_time")
interval = getattr(self, f"_{focus_type}_focus_interval")
if last_focus_time is None: # If we haven't focused yet
self.logger.info(f"{focus_type} focus required because we haven't focused yet.")
return True
if current_time() - last_focus_time > interval:
self.logger.info(f"{focus_type} focus required because of time difference.")
return True
# If there has been a large change in temperature then we need to focus again
last_focus_temp = getattr(self, f"last_{focus_type}_focus_temp")
temptol = getattr(self, f"_{focus_type}_focus_temptol")
if (last_focus_temp is not None) and (self.temperature is not None):
if abs(last_focus_temp - self.temperature) > temptol:
self.logger.info(f"{focus_type} focus required because of temperature change.")
return True
return False
def _assert_safe(self, *args, **kwargs):
""" Raise a RuntimeError if not safe to continue.
TODO: Raise a custom error type indicating lack of safety.
Args:
*args, **kwargs: Parsed to self.is_safe.
"""
if not self.is_safe(*args, **kwargs):
raise RuntimeError("Safety check failed!")
def _safe_sleep(self, duration, interval=1, *args, **kwargs):
""" Sleep for a specified amount of time while ensuring safety.
A RuntimeError is raised if safety fails while waiting.
Args:
duration (float or Quantity): The time to wait.
interval (float): The time in between safety checks.
*args, **kwargs: Parsed to is_safe.
Raises:
RuntimeError: If safety fails while waiting.
"""
self.logger.debug(f"Safe sleeping for {duration}")
timer = CountdownTimer(duration)
while not timer.expired():
self._assert_safe(*args, **kwargs)
time.sleep(interval)
| [
"huntsman.pocs.camera.group.CameraGroup",
"huntsman.pocs.utils.flats.get_cameras_with_filter",
"huntsman.pocs.guide.bisque.Guide",
"huntsman.pocs.archive.utils.remove_empty_directories",
"huntsman.pocs.utils.logger.get_logger",
"panoptes.utils.time.CountdownTimer",
"panoptes.utils.time.current_time",
... | [((1860, 1885), 'huntsman.pocs.camera.group.CameraGroup', 'CameraGroup', (['self.cameras'], {}), '(self.cameras)\n', (1871, 1885), False, 'from huntsman.pocs.camera.group import CameraGroup, dispatch_parallel\n'), ((9216, 9252), 'huntsman.pocs.archive.utils.remove_empty_directories', 'remove_empty_directories', (['images_dir'], {}), '(images_dir)\n', (9240, 9252), False, 'from huntsman.pocs.archive.utils import remove_empty_directories\n'), ((9400, 9437), 'huntsman.pocs.archive.utils.remove_empty_directories', 'remove_empty_directories', (['archive_dir'], {}), '(archive_dir)\n', (9424, 9437), False, 'from huntsman.pocs.archive.utils import remove_empty_directories\n'), ((19339, 19361), 'huntsman.pocs.guide.bisque.Guide', 'Guide', ([], {}), '(**guider_config)\n', (19344, 19361), False, 'from huntsman.pocs.guide.bisque import Guide\n'), ((20987, 21115), 'huntsman.pocs.utils.flats.make_flat_field_sequences', 'make_flat_field_sequences', (['cameras', 'target_scaling', 'scaling_tolerance', 'bias'], {'initial_exposure_time': 'initial_exptime'}), '(cameras, target_scaling, scaling_tolerance, bias,\n initial_exposure_time=initial_exptime, **kwargs)\n', (21012, 21115), False, 'from huntsman.pocs.utils.flats import make_flat_field_sequences, make_flat_field_observation\n'), ((27008, 27032), 'panoptes.utils.time.CountdownTimer', 'CountdownTimer', (['duration'], {}), '(duration)\n', (27022, 27032), False, 'from panoptes.utils.time import current_time, wait_for_events, CountdownTimer\n'), ((30117, 30141), 'panoptes.utils.time.CountdownTimer', 'CountdownTimer', (['duration'], {}), '(duration)\n', (30131, 30141), False, 'from panoptes.utils.time import current_time, wait_for_events, CountdownTimer\n'), ((1731, 1743), 'huntsman.pocs.utils.logger.get_logger', 'get_logger', ([], {}), '()\n', (1741, 1743), False, 'from huntsman.pocs.utils.logger import get_logger\n'), ((4207, 4221), 'panoptes.utils.time.current_time', 'current_time', ([], {}), '()\n', (4219, 4221), False, 'from panoptes.utils.time import current_time, wait_for_events, CountdownTimer\n'), ((4266, 4280), 'panoptes.utils.time.current_time', 'current_time', ([], {}), '()\n', (4278, 4280), False, 'from panoptes.utils.time import current_time, wait_for_events, CountdownTimer\n'), ((6704, 6722), 'contextlib.suppress', 'suppress', (['KeyError'], {}), '(KeyError)\n', (6712, 6722), False, 'from contextlib import suppress, contextmanager\n'), ((8721, 8735), 'panoptes.utils.time.current_time', 'current_time', ([], {}), '()\n', (8733, 8735), False, 'from panoptes.utils.time import current_time, wait_for_events, CountdownTimer\n'), ((10544, 10589), 'huntsman.pocs.utils.flats.get_cameras_with_filter', 'get_cameras_with_filter', (['cameras', 'filter_name'], {}), '(cameras, filter_name)\n', (10567, 10589), False, 'from huntsman.pocs.utils.flats import get_cameras_with_filter\n'), ((10882, 10955), 'huntsman.pocs.utils.flats.make_flat_field_observation', 'make_flat_field_observation', (['self.earth_location'], {'filter_name': 'filter_name'}), '(self.earth_location, filter_name=filter_name)\n', (10909, 10955), False, 'from huntsman.pocs.utils.flats import make_flat_field_sequences, make_flat_field_observation\n'), ((10991, 11017), 'panoptes.utils.time.current_time', 'current_time', ([], {'flatten': '(True)'}), '(flatten=True)\n', (11003, 11017), False, 'from panoptes.utils.time import current_time, wait_for_events, CountdownTimer\n'), ((13827, 13853), 'panoptes.utils.time.current_time', 'current_time', ([], {'flatten': '(True)'}), '(flatten=True)\n', (13839, 13853), False, 'from panoptes.utils.time import current_time, wait_for_events, CountdownTimer\n'), ((15248, 15274), 'panoptes.utils.time.current_time', 'current_time', ([], {'flatten': '(True)'}), '(flatten=True)\n', (15260, 15274), False, 'from panoptes.utils.time import current_time, wait_for_events, CountdownTimer\n'), ((17172, 17196), 'contextlib.suppress', 'suppress', (['AttributeError'], {}), '(AttributeError)\n', (17180, 17196), False, 'from contextlib import suppress, contextmanager\n'), ((27284, 27301), 'time.sleep', 'time.sleep', (['sleep'], {}), '(sleep)\n', (27294, 27301), False, 'import time\n'), ((30236, 30256), 'time.sleep', 'time.sleep', (['interval'], {}), '(interval)\n', (30246, 30256), False, 'import time\n'), ((4700, 4738), 'panoptes.utils.utils.get_quantity_value', 'get_quantity_value', (['reading', 'u.Celsius'], {}), '(reading, u.Celsius)\n', (4718, 4738), False, 'from panoptes.utils.utils import get_quantity_value\n'), ((5050, 5064), 'panoptes.utils.time.current_time', 'current_time', ([], {}), '()\n', (5062, 5064), False, 'from panoptes.utils.time import current_time, wait_for_events, CountdownTimer\n'), ((8555, 8631), 'panoptes.utils.error.Timeout', 'error.Timeout', (['f"""Timeout of {timeout} reached while waiting for fine focus."""'], {}), "(f'Timeout of {timeout} reached while waiting for fine focus.')\n", (8568, 8631), False, 'from panoptes.utils import error\n'), ((16028, 16052), 'contextlib.suppress', 'suppress', (['AttributeError'], {}), '(AttributeError)\n', (16036, 16052), False, 'from contextlib import suppress, contextmanager\n'), ((18336, 18376), 'panoptes.utils.utils.get_quantity_value', 'get_quantity_value', (['min_solar_alt', 'u.deg'], {}), '(min_solar_alt, u.deg)\n', (18354, 18376), False, 'from panoptes.utils.utils import get_quantity_value\n'), ((21373, 21434), 'huntsman.pocs.error.NotTwilightError', 'NotTwilightError', (['"""No longer twilight. Aborting flat fields."""'], {}), "('No longer twilight. Aborting flat fields.')\n", (21389, 21434), False, 'from huntsman.pocs.error import NotTwilightError\n'), ((22252, 22266), 'panoptes.utils.time.current_time', 'current_time', ([], {}), '()\n', (22264, 22266), False, 'from panoptes.utils.time import current_time, wait_for_events, CountdownTimer\n'), ((28544, 28558), 'panoptes.utils.time.current_time', 'current_time', ([], {}), '()\n', (28556, 28558), False, 'from panoptes.utils.time import current_time, wait_for_events, CountdownTimer\n'), ((27721, 27792), 'panoptes.utils.error.Timeout', 'error.Timeout', (['f"""Timeout while waiting for camera event on {cam_name}."""'], {}), "(f'Timeout while waiting for camera event on {cam_name}.')\n", (27734, 27792), False, 'from panoptes.utils import error\n')] |
from django.conf.urls import url
from dist import views
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^add$', views.AddCategoryView.as_view(), name='add_category'),
url(r'^(?P<cat_id>\d+)/$', views.CategoryView.as_view(), name='category'),
]
| [
"dist.views.CategoryView.as_view",
"dist.views.IndexView.as_view",
"dist.views.AddCategoryView.as_view"
] | [((89, 114), 'dist.views.IndexView.as_view', 'views.IndexView.as_view', ([], {}), '()\n', (112, 114), False, 'from dist import views\n'), ((149, 180), 'dist.views.AddCategoryView.as_view', 'views.AddCategoryView.as_view', ([], {}), '()\n', (178, 180), False, 'from dist import views\n'), ((235, 263), 'dist.views.CategoryView.as_view', 'views.CategoryView.as_view', ([], {}), '()\n', (261, 263), False, 'from dist import views\n')] |
# Generated by Django 3.1.5 on 2021-01-10 04:06
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='article',
old_name='descripton',
new_name='description',
),
]
| [
"django.db.migrations.RenameField"
] | [((212, 307), 'django.db.migrations.RenameField', 'migrations.RenameField', ([], {'model_name': '"""article"""', 'old_name': '"""descripton"""', 'new_name': '"""description"""'}), "(model_name='article', old_name='descripton',\n new_name='description')\n", (234, 307), False, 'from django.db import migrations\n')] |
from conans import ConanFile, tools
class HapplyConan(ConanFile):
name = "happly"
url = "https://github.com/conan-io/conan-center-index"
homepage = "https://github.com/nmwsharp/happly"
topics = ("conan", "happly", "ply", "3D")
license = "MIT"
description = "A C++ header-only parser for the PLY file format. Parse .ply happily!"
settings = "compiler"
no_copy_source = True
@property
def _source_subfolder(self):
return "source_subfolder"
def validate(self):
if self.settings.compiler.cppstd:
tools.check_min_cppstd(self, 11)
def source(self):
tools.get(**self.conan_data["sources"][self.version], destination=self._source_subfolder, strip_root=True)
def package(self):
self.copy("LICENSE", src=self._source_subfolder, dst="licenses")
self.copy("happly.h", src=self._source_subfolder, dst="include")
def package_id(self):
self.info.header_only()
| [
"conans.tools.check_min_cppstd",
"conans.tools.get"
] | [((632, 743), 'conans.tools.get', 'tools.get', ([], {'destination': 'self._source_subfolder', 'strip_root': '(True)'}), "(**self.conan_data['sources'][self.version], destination=self.\n _source_subfolder, strip_root=True)\n", (641, 743), False, 'from conans import ConanFile, tools\n'), ((568, 600), 'conans.tools.check_min_cppstd', 'tools.check_min_cppstd', (['self', '(11)'], {}), '(self, 11)\n', (590, 600), False, 'from conans import ConanFile, tools\n')] |
from djitellopy import Tello
from time import sleep
# Initialize and Connect
tello = Tello()
tello.connect()
# Takeoff and move up to 6 feet (183cm)
tello.takeoff()
tello.move_up(101)
# Move forward (east) 5 feet (152cm)
tello.move_forward(152)
sleep(.5)
# rotate 90 degrees CCW
tello.rotate_counter_clockwise(90)
# move forward (north) 6 feet (183cm)
tello.move_forward(183)
sleep(.5)
# rotate CW 90 degrees
tello.rotate_clockwise(90)
# move down to 3 feet (91cm)
tello.move_down(91)
# move forward (east)
tello.move_forward(91)
sleep(.5)
# rotate 90 degrees CW
tello.rotate_clockwise(90)
# move up 1 foot (to 4 feet, 121cm)
tello.move_up(30)
# move forward 3 feet (91cm)
tello.move_forward(91)
sleep(.5)
# rotate CCW 90 degrees
tello.rotate_counter_clockwise(90)
# move forward 6 feet (183cm)
tello.move_forward(183)
sleep(.5)
tello.land()
| [
"time.sleep",
"djitellopy.Tello"
] | [((86, 93), 'djitellopy.Tello', 'Tello', ([], {}), '()\n', (91, 93), False, 'from djitellopy import Tello\n'), ((248, 258), 'time.sleep', 'sleep', (['(0.5)'], {}), '(0.5)\n', (253, 258), False, 'from time import sleep\n'), ((381, 391), 'time.sleep', 'sleep', (['(0.5)'], {}), '(0.5)\n', (386, 391), False, 'from time import sleep\n'), ((538, 548), 'time.sleep', 'sleep', (['(0.5)'], {}), '(0.5)\n', (543, 548), False, 'from time import sleep\n'), ((707, 717), 'time.sleep', 'sleep', (['(0.5)'], {}), '(0.5)\n', (712, 717), False, 'from time import sleep\n'), ((832, 842), 'time.sleep', 'sleep', (['(0.5)'], {}), '(0.5)\n', (837, 842), False, 'from time import sleep\n')] |
import cv2
import numpy as np
import math
# img = cv2.imread('/home/geesara/Pictures/bp8OO.jpg', 0)
# img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)[1] # ensure binary
# ret, labels = cv2.connectedComponents(img)
#
# print("Number of labels" , len(labels))
#
# def imshow_components(labels):
# # Map component labels to hue val
# label_hue = np.uint8(179*labels/np.max(labels))
# blank_ch = 255*np.ones_like(label_hue)
# labeled_img = cv2.merge([label_hue, blank_ch, blank_ch])
#
# # cvt to BGR for display
# labeled_img = cv2.cvtColor(labeled_img, cv2.COLOR_HSV2BGR)
#
# # set bg label to black
# labeled_img[label_hue==0] = 0
#
# cv2.imshow('labeled.png', labeled_img)
# cv2.waitKey()
# imshow_components(labels)
def sigmoid(x):
return 1 / (1 + math.exp(-x))
d = sigmoid(2)
ddf = 45
f = 0.869
P = 0.645
R = (f*P)/(2*P-f) | [
"math.exp"
] | [((801, 813), 'math.exp', 'math.exp', (['(-x)'], {}), '(-x)\n', (809, 813), False, 'import math\n')] |
# Generated by Django 2.2 on 2019-10-11 17:25
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('review', '0002_auto_20191009_1119'),
]
operations = [
migrations.RenameField(
model_name='review',
old_name='is_deleted',
new_name='is_rejected',
),
]
| [
"django.db.migrations.RenameField"
] | [((224, 319), 'django.db.migrations.RenameField', 'migrations.RenameField', ([], {'model_name': '"""review"""', 'old_name': '"""is_deleted"""', 'new_name': '"""is_rejected"""'}), "(model_name='review', old_name='is_deleted', new_name\n ='is_rejected')\n", (246, 319), False, 'from django.db import migrations\n')] |
import math
import random
from PIL import Image
import cairo
from wyggles import Dna
PI = math.pi
RADIUS = 32
WIDTH = RADIUS
HEIGHT = RADIUS
class WyggleDna(Dna):
def __init__(self, klass):
super().__init__(klass)
name = self.name
r = random.uniform(0, .75)
r1 = r + .20
r2 = r + .25
g = random.uniform(0, .75)
g1 = g + .20
g2 = g + .25
b = random.uniform(0, .75)
b1 = b + .20
b2 = b + .25
self.color1 = r,g,b,1
self.color2 = r1,g1,b1,1
self.color3 = r2,g2,b2,1
#
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT)
ctx = cairo.Context(surface)
#ctx.scale(1, 1) # Normalizing the canvas
imgsize = (RADIUS, RADIUS) #The size of the image
self.draw_segment(ctx)
self.tail_texture = self.create_texture(surface, name + 'tail', imgsize)
#Eating
self.draw_munchy_face(ctx)
self.munchy_face_texture = self.create_texture(surface, name + 'munchy_face', imgsize)
#Sad
self.draw_happy_face(ctx, -1)
self.sadFaceImage = self.create_texture(surface, name + 'sadFace', imgsize)
#Neutral
self.draw_happy_face(ctx, 0)
self.neutralFaceImage = self.create_texture(surface, name + 'neutralFace', imgsize)
#Happy
self.draw_happy_face(ctx, 1)
self.happy_face_texture = self.create_texture(surface, name + 'happy_face', imgsize)
#
self.face_texture = self.happy_face_texture
def draw_segment(self, ctx):
r1, g1, b1, a1 = self.color1
r2, g2, b2, a2 = self.color2
r3, g3, b3, a3 = self.color3
pat = cairo.RadialGradient(16,16,16, 8,8,4)
pat.add_color_stop_rgba(1, r3, g3, b3, a3)
pat.add_color_stop_rgba(0.9, r2, g2, b2, a2)
pat.add_color_stop_rgba(0, r1, g1, b1, a1)
ctx.arc(16, 16, 12, 0, PI*2)
ctx.close_path()
ctx.set_source(pat)
ctx.fill()
def draw_happy_face(self, ctx, valence):
self.draw_face(ctx)
#Mouth
x0 = 8
y0 = 20 - (4 * valence)
x1 = 16
y1 = 26 + (4 * valence)
x2 = 24
y2 = y0
#
#ctx.move_to(x0, y0)
ctx.curve_to(x0, y0, x1, y1, x2, y2)
ctx.set_line_width(2)
ctx.set_source_rgb(255, 0, 0) #red
ctx.stroke()
def draw_munchy_face(self, ctx):
self.draw_face(ctx)
#Mouth
ctx.arc(16, 16, 8, PI, 2 * PI)
ctx.close_path()
ctx.set_source_rgb(255, 0, 0) #red
ctx.fill()
def draw_face(self, ctx):
self.draw_segment(ctx)
#Eyes - Whites
ctx.arc(8, 8, 4, 0, PI*2)
ctx.arc(24, 8, 4, 0, PI*2)
ctx.close_path()
ctx.set_source_rgb(255, 255, 255)
ctx.fill()
#Eyes - Darks
ctx.arc(8, 8, 2, 0, PI*2)
ctx.arc(24, 8, 2, 0, PI*2)
ctx.close_path()
ctx.set_source_rgb(0,0,0)
ctx.fill()
| [
"cairo.Context",
"random.uniform",
"cairo.ImageSurface",
"cairo.RadialGradient"
] | [((267, 290), 'random.uniform', 'random.uniform', (['(0)', '(0.75)'], {}), '(0, 0.75)\n', (281, 290), False, 'import random\n'), ((344, 367), 'random.uniform', 'random.uniform', (['(0)', '(0.75)'], {}), '(0, 0.75)\n', (358, 367), False, 'import random\n'), ((421, 444), 'random.uniform', 'random.uniform', (['(0)', '(0.75)'], {}), '(0, 0.75)\n', (435, 444), False, 'import random\n'), ((617, 671), 'cairo.ImageSurface', 'cairo.ImageSurface', (['cairo.FORMAT_ARGB32', 'WIDTH', 'HEIGHT'], {}), '(cairo.FORMAT_ARGB32, WIDTH, HEIGHT)\n', (635, 671), False, 'import cairo\n'), ((686, 708), 'cairo.Context', 'cairo.Context', (['surface'], {}), '(surface)\n', (699, 708), False, 'import cairo\n'), ((1726, 1767), 'cairo.RadialGradient', 'cairo.RadialGradient', (['(16)', '(16)', '(16)', '(8)', '(8)', '(4)'], {}), '(16, 16, 16, 8, 8, 4)\n', (1746, 1767), False, 'import cairo\n')] |
#!/usr/bin/python3
from tools import *
from sys import argv
from os.path import join
import h5py
import matplotlib.pylab as plt
from matplotlib.patches import Wedge
import numpy as np
if len(argv) > 1:
pathToSimFolder = argv[1]
else:
pathToSimFolder = "../data/"
parameters, electrodes = readParameters(pathToSimFolder)
electrodeNumber = len(electrodes)
acceptorPos = np.zeros((int(parameters["acceptorNumber"]), 2))
try:
donorPos = np.zeros((int(parameters["donorNumber"]), 2))
except KeyError:
donorPos = np.zeros(
(int(parameters["acceptorNumber"] * parameters["compensationFactor"]), 2)
)
with open(join(pathToSimFolder, "device.txt")) as deviceFile:
line = next(deviceFile)
line = next(deviceFile)
for i in range(acceptorPos.shape[0]):
acceptorPos[i] = next(deviceFile).split(" ")
line = next(deviceFile)
line = next(deviceFile)
for i in range(donorPos.shape[0]):
donorPos[i] = next(deviceFile).split(" ")
# print(acceptorPos)
# print(donorPos)
electrodePositions = np.empty((len(electrodes), 2))
for i in range(len(electrodes)):
if parameters["geometry"] == "rect":
if electrodes[i][1] == 0:
electrodePositions[i] = [0, electrodes[i][0] * parameters["lenY"]]
if electrodes[i][1] == 1:
electrodePositions[i] = [
parameters["lenX"],
electrodes[i][0] * parameters["lenY"],
]
if electrodes[i][1] == 2:
electrodePositions[i] = [electrodes[i][0] * parameters["lenX"], 0]
if electrodes[i][1] == 3:
electrodePositions[i] = [
electrodes[i][0] * parameters["lenX"],
parameters["lenY"],
]
elif parameters["geometry"] == "circle":
electrodePositions[i] = [
parameters["radius"] * np.cos(electrodes[i][0] / 360 * 2 * np.pi),
parameters["radius"] * np.sin(electrodes[i][0] / 360 * 2 * np.pi),
]
# print(electrodePositions)
def colorMaker(x):
from matplotlib import colors
from scipy.interpolate import interp1d
cols = ["darkred", "darkgreen"]
rgbaData = np.array([colors.to_rgba(c) for c in cols])
rInterpolater = interp1d(np.linspace(0, 1, len(cols)), rgbaData[:, 0])
gInterpolater = interp1d(np.linspace(0, 1, len(cols)), rgbaData[:, 1])
bInterpolater = interp1d(np.linspace(0, 1, len(cols)), rgbaData[:, 2])
return np.array([rInterpolater(x), gInterpolater(x), bInterpolater(x), 1])
inp = ["0_0", "0_1", "1_0", "1_1"]
for fileNumber in [1, 2, 3, 4]:
print(inp[fileNumber - 1])
# for fileNumber in [1]:
data = np.genfromtxt(
join(pathToSimFolder, f"swapTrackFile{fileNumber}.txt"),
delimiter=";",
dtype=int,
)
trajectoriesSortedByStartEnd = [
[[] for j in range(len(electrodes))] for i in range(len(electrodes))
]
trajectories = []
hops = 20000
IDs = {}
hitID = 0
for i in range(hops):
hoppingSite1 = data[i, 0]
hoppingSite2 = data[i, 1]
# print("hoppingSite1",hoppingSite1,"hoppingSite2",hoppingSite2)
if hoppingSite1 in IDs:
ID = IDs[hoppingSite1]
del IDs[hoppingSite1]
# print("found ID",ID)
else:
ID = hitID
hitID += 1
trajectories.append([])
# print("new ID", ID)
if hoppingSite2 < parameters["acceptorNumber"]:
IDs[hoppingSite2] = ID
trajectories[ID].append([hoppingSite1, hoppingSite2])
# sort trajectories
for i in range(len(trajectories)):
if trajectories[i][0][0] >= parameters["acceptorNumber"]:
if trajectories[i][-1][1] >= parameters["acceptorNumber"]:
trajectoriesSortedByStartEnd[
trajectories[i][0][0] - int(parameters["acceptorNumber"])
][trajectories[i][-1][1] - int(parameters["acceptorNumber"])].append(
trajectories[i]
)
# print(trajectories[i][0][0], trajectories[i][-1][1])
for k in range(len(electrodes)):
fig, ax = plt.subplots(1, 1, figsize=(4.980614173228346, 3.2))
electodePlotWidth = 8
for i in range(len(electrodes)):
if i == parameters["outputElectrode"]:
col = "blue"
elif i == parameters["inputElectrode1"]:
if fileNumber in [3, 4]:
col = "red"
else:
col = "rosybrown"
elif i == parameters["inputElectrode2"]:
if fileNumber in [2, 4]:
col = "red"
else:
col = "rosybrown"
else:
col = "green"
if parameters["geometry"] == "rect":
if electrodes[i][1] == 0:
angle = 0
xy = (
0 - electodePlotWidth / 2,
electrodes[i][0] * parameters["lenY"]
- parameters["electrodeWidth"] / 2,
)
elif electrodes[i][1] == 1:
angle = 0
xy = (
parameters["lenX"] - electodePlotWidth / 2,
electrodes[i][0] * parameters["lenY"]
- parameters["electrodeWidth"] / 2,
)
elif electrodes[i][1] == 2:
angle = 90
xy = (
electrodes[i][0] * parameters["lenX"]
+ parameters["electrodeWidth"] / 2,
0 - electodePlotWidth / 2,
)
elif electrodes[i][1] == 3:
angle = 90
xy = (
electrodes[i][0] * parameters["lenX"]
+ parameters["electrodeWidth"] / 2,
parameters["lenY"] - electodePlotWidth / 2,
)
ax.add_artist(
plt.Rectangle(
xy,
electodePlotWidth,
parameters["electrodeWidth"],
angle=angle,
fc=col,
ec=col,
zorder=-1,
)
)
elif parameters["geometry"] == "circle":
electrodeWidth = (
parameters["electrodeWidth"]
/ (parameters["radius"] * 2 * np.pi)
* 360
) # in degrees
ax.add_artist(
Wedge(
(0, 0),
parameters["radius"] + electodePlotWidth / 2,
electrodes[i][0] - electrodeWidth / 2,
electrodes[i][0] + electrodeWidth / 2,
width=electodePlotWidth,
fc=col,
ec=col,
zorder=-1,
)
)
ax.scatter(acceptorPos[:, 0], acceptorPos[:, 1], c="k", marker=".", s=20)
ax.scatter(donorPos[:, 0], donorPos[:, 1], c="k", marker="x", s=20)
for l in range(len(electrodes)):
trajectories = trajectoriesSortedByStartEnd[k][l]
for i in range(len(trajectories)):
for j in range(len(trajectories[i])):
hoppingSite1 = trajectories[i][j][0]
hoppingSite2 = trajectories[i][j][1]
if hoppingSite1 >= parameters["acceptorNumber"]:
x1, y1 = (
electrodePositions[
hoppingSite1 - int(parameters["acceptorNumber"])
][0],
electrodePositions[
hoppingSite1 - int(parameters["acceptorNumber"])
][1],
)
else:
x1, y1 = (
acceptorPos[hoppingSite1, 0],
acceptorPos[hoppingSite1, 1],
)
if hoppingSite2 >= parameters["acceptorNumber"]:
x2, y2 = (
electrodePositions[
hoppingSite2 - int(parameters["acceptorNumber"])
][0],
electrodePositions[
hoppingSite2 - int(parameters["acceptorNumber"])
][1],
)
else:
x2, y2 = (
acceptorPos[hoppingSite2, 0],
acceptorPos[hoppingSite2, 1],
)
# ax.plot([x1,x2],[y1,y2],"-",alpha=0.05,color="k",linewidth=2)
ax.plot(
[x1, x2],
[y1, y2],
"-",
alpha=0.05,
color=color(l, len(electrodes)),
linewidth=2,
)
# if currentRatio>0.5:
# ax.arrow((x2+x1)/2,(y2+y1)/2,(x2-x1)*0.001,(y2-y1)*0.001,color=colorMaker(abs(currentRatio-0.5)*2),ec=None,alpha=absBins[i,j],linewidth=0,head_width=(currentRatio-0.5)*20)
ax.axis("off")
if parameters["geometry"] == "circle":
ax.add_artist(
plt.Circle((0, 0), parameters["radius"], fc="none", ec="k", zorder=-2)
)
elif parameters["geometry"] == "rect":
ax.add_artist(
plt.Rectangle(
(0, 0),
parameters["lenX"],
parameters["lenY"],
fc="none",
ec="k",
zorder=-2,
)
)
if parameters["geometry"] == "rect":
ax.set_xlim(
-electodePlotWidth / 2, parameters["lenX"] + electodePlotWidth / 2
)
ax.set_ylim(
-electodePlotWidth / 2, parameters["lenY"] + electodePlotWidth / 2
)
elif parameters["geometry"] == "circle":
ax.set_xlim(
-parameters["radius"] - electodePlotWidth,
parameters["radius"] + electodePlotWidth,
)
ax.set_ylim(
-parameters["radius"] - electodePlotWidth,
parameters["radius"] + electodePlotWidth,
)
ax.set_aspect("equal")
plt.savefig(
join(pathToSimFolder, f"trajectory_fromEl_{k}_{inp[fileNumber-1]}.png"),
bbox_inches="tight",
dpi=300,
)
# plt.show()
plt.close(fig)
for k in range(len(electrodes)):
fig, ax = plt.subplots(1, 1, figsize=(4.980614173228346, 3.2))
electodePlotWidth = 8
for i in range(len(electrodes)):
if i == parameters["outputElectrode"]:
col = "blue"
elif i == parameters["inputElectrode1"]:
if fileNumber in [3, 4]:
col = "red"
else:
col = "rosybrown"
elif i == parameters["inputElectrode2"]:
if fileNumber in [2, 4]:
col = "red"
else:
col = "rosybrown"
else:
col = "green"
if parameters["geometry"] == "rect":
if electrodes[i][1] == 0:
angle = 0
xy = (
0 - electodePlotWidth / 2,
electrodes[i][0] * parameters["lenY"]
- parameters["electrodeWidth"] / 2,
)
elif electrodes[i][1] == 1:
angle = 0
xy = (
parameters["lenX"] - electodePlotWidth / 2,
electrodes[i][0] * parameters["lenY"]
- parameters["electrodeWidth"] / 2,
)
elif electrodes[i][1] == 2:
angle = 90
xy = (
electrodes[i][0] * parameters["lenX"]
+ parameters["electrodeWidth"] / 2,
0 - electodePlotWidth / 2,
)
elif electrodes[i][1] == 3:
angle = 90
xy = (
electrodes[i][0] * parameters["lenX"]
+ parameters["electrodeWidth"] / 2,
parameters["lenY"] - electodePlotWidth / 2,
)
ax.add_artist(
plt.Rectangle(
xy,
electodePlotWidth,
parameters["electrodeWidth"],
angle=angle,
fc=col,
ec=col,
zorder=-1,
)
)
elif parameters["geometry"] == "circle":
electrodeWidth = (
parameters["electrodeWidth"]
/ (parameters["radius"] * 2 * np.pi)
* 360
) # in degrees
ax.add_artist(
Wedge(
(0, 0),
parameters["radius"] + electodePlotWidth / 2,
electrodes[i][0] - electrodeWidth / 2,
electrodes[i][0] + electrodeWidth / 2,
width=electodePlotWidth,
fc=col,
ec=col,
zorder=-1,
)
)
ax.scatter(acceptorPos[:, 0], acceptorPos[:, 1], c="k", marker=".", s=20)
ax.scatter(donorPos[:, 0], donorPos[:, 1], c="k", marker="x", s=20)
for l in range(len(electrodes)):
trajectories = trajectoriesSortedByStartEnd[l][k]
for i in range(len(trajectories)):
for j in range(len(trajectories[i])):
hoppingSite1 = trajectories[i][j][0]
hoppingSite2 = trajectories[i][j][1]
if hoppingSite1 >= parameters["acceptorNumber"]:
x1, y1 = (
electrodePositions[
hoppingSite1 - int(parameters["acceptorNumber"])
][0],
electrodePositions[
hoppingSite1 - int(parameters["acceptorNumber"])
][1],
)
else:
x1, y1 = (
acceptorPos[hoppingSite1, 0],
acceptorPos[hoppingSite1, 1],
)
if hoppingSite2 >= parameters["acceptorNumber"]:
x2, y2 = (
electrodePositions[
hoppingSite2 - int(parameters["acceptorNumber"])
][0],
electrodePositions[
hoppingSite2 - int(parameters["acceptorNumber"])
][1],
)
else:
x2, y2 = (
acceptorPos[hoppingSite2, 0],
acceptorPos[hoppingSite2, 1],
)
# ax.plot([x1,x2],[y1,y2],"-",alpha=0.05,color="k",linewidth=2)
ax.plot(
[x1, x2],
[y1, y2],
"-",
alpha=0.05,
color=color(l, len(electrodes)),
linewidth=2,
)
# if currentRatio>0.5:
# ax.arrow((x2+x1)/2,(y2+y1)/2,(x2-x1)*0.001,(y2-y1)*0.001,color=colorMaker(abs(currentRatio-0.5)*2),ec=None,alpha=absBins[i,j],linewidth=0,head_width=(currentRatio-0.5)*20)
ax.axis("off")
if parameters["geometry"] == "circle":
ax.add_artist(
plt.Circle((0, 0), parameters["radius"], fc="none", ec="k", zorder=-2)
)
elif parameters["geometry"] == "rect":
ax.add_artist(
plt.Rectangle(
(0, 0),
parameters["lenX"],
parameters["lenY"],
fc="none",
ec="k",
zorder=-2,
)
)
if parameters["geometry"] == "rect":
ax.set_xlim(
-electodePlotWidth / 2, parameters["lenX"] + electodePlotWidth / 2
)
ax.set_ylim(
-electodePlotWidth / 2, parameters["lenY"] + electodePlotWidth / 2
)
elif parameters["geometry"] == "circle":
ax.set_xlim(
-parameters["radius"] - electodePlotWidth,
parameters["radius"] + electodePlotWidth,
)
ax.set_ylim(
-parameters["radius"] - electodePlotWidth,
parameters["radius"] + electodePlotWidth,
)
ax.set_aspect("equal")
plt.savefig(
join(pathToSimFolder, f"trajectory_toEl_{k}_{inp[fileNumber-1]}.png"),
bbox_inches="tight",
dpi=300,
)
# plt.show()
plt.close(fig)
| [
"matplotlib.pylab.subplots",
"matplotlib.pylab.Circle",
"matplotlib.patches.Wedge",
"matplotlib.colors.to_rgba",
"os.path.join",
"matplotlib.pylab.Rectangle",
"numpy.cos",
"numpy.sin",
"matplotlib.pylab.close"
] | [((637, 672), 'os.path.join', 'join', (['pathToSimFolder', '"""device.txt"""'], {}), "(pathToSimFolder, 'device.txt')\n", (641, 672), False, 'from os.path import join\n'), ((2671, 2726), 'os.path.join', 'join', (['pathToSimFolder', 'f"""swapTrackFile{fileNumber}.txt"""'], {}), "(pathToSimFolder, f'swapTrackFile{fileNumber}.txt')\n", (2675, 2726), False, 'from os.path import join\n'), ((4144, 4196), 'matplotlib.pylab.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(4.980614173228346, 3.2)'}), '(1, 1, figsize=(4.980614173228346, 3.2))\n', (4156, 4196), True, 'import matplotlib.pylab as plt\n'), ((10953, 10967), 'matplotlib.pylab.close', 'plt.close', (['fig'], {}), '(fig)\n', (10962, 10967), True, 'import matplotlib.pylab as plt\n'), ((11025, 11077), 'matplotlib.pylab.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(4.980614173228346, 3.2)'}), '(1, 1, figsize=(4.980614173228346, 3.2))\n', (11037, 11077), True, 'import matplotlib.pylab as plt\n'), ((17832, 17846), 'matplotlib.pylab.close', 'plt.close', (['fig'], {}), '(fig)\n', (17841, 17846), True, 'import matplotlib.pylab as plt\n'), ((2169, 2186), 'matplotlib.colors.to_rgba', 'colors.to_rgba', (['c'], {}), '(c)\n', (2183, 2186), False, 'from matplotlib import colors\n'), ((10786, 10859), 'os.path.join', 'join', (['pathToSimFolder', 'f"""trajectory_fromEl_{k}_{inp[fileNumber - 1]}.png"""'], {}), "(pathToSimFolder, f'trajectory_fromEl_{k}_{inp[fileNumber - 1]}.png')\n", (10790, 10859), False, 'from os.path import join\n'), ((17667, 17738), 'os.path.join', 'join', (['pathToSimFolder', 'f"""trajectory_toEl_{k}_{inp[fileNumber - 1]}.png"""'], {}), "(pathToSimFolder, f'trajectory_toEl_{k}_{inp[fileNumber - 1]}.png')\n", (17671, 17738), False, 'from os.path import join\n'), ((9649, 9719), 'matplotlib.pylab.Circle', 'plt.Circle', (['(0, 0)', "parameters['radius']"], {'fc': '"""none"""', 'ec': '"""k"""', 'zorder': '(-2)'}), "((0, 0), parameters['radius'], fc='none', ec='k', zorder=-2)\n", (9659, 9719), True, 'import matplotlib.pylab as plt\n'), ((16530, 16600), 'matplotlib.pylab.Circle', 'plt.Circle', (['(0, 0)', "parameters['radius']"], {'fc': '"""none"""', 'ec': '"""k"""', 'zorder': '(-2)'}), "((0, 0), parameters['radius'], fc='none', ec='k', zorder=-2)\n", (16540, 16600), True, 'import matplotlib.pylab as plt\n'), ((1846, 1888), 'numpy.cos', 'np.cos', (['(electrodes[i][0] / 360 * 2 * np.pi)'], {}), '(electrodes[i][0] / 360 * 2 * np.pi)\n', (1852, 1888), True, 'import numpy as np\n'), ((1925, 1967), 'numpy.sin', 'np.sin', (['(electrodes[i][0] / 360 * 2 * np.pi)'], {}), '(electrodes[i][0] / 360 * 2 * np.pi)\n', (1931, 1967), True, 'import numpy as np\n'), ((6088, 6199), 'matplotlib.pylab.Rectangle', 'plt.Rectangle', (['xy', 'electodePlotWidth', "parameters['electrodeWidth']"], {'angle': 'angle', 'fc': 'col', 'ec': 'col', 'zorder': '(-1)'}), "(xy, electodePlotWidth, parameters['electrodeWidth'], angle=\n angle, fc=col, ec=col, zorder=-1)\n", (6101, 6199), True, 'import matplotlib.pylab as plt\n'), ((9824, 9920), 'matplotlib.pylab.Rectangle', 'plt.Rectangle', (['(0, 0)', "parameters['lenX']", "parameters['lenY']"], {'fc': '"""none"""', 'ec': '"""k"""', 'zorder': '(-2)'}), "((0, 0), parameters['lenX'], parameters['lenY'], fc='none', ec\n ='k', zorder=-2)\n", (9837, 9920), True, 'import matplotlib.pylab as plt\n'), ((12969, 13080), 'matplotlib.pylab.Rectangle', 'plt.Rectangle', (['xy', 'electodePlotWidth', "parameters['electrodeWidth']"], {'angle': 'angle', 'fc': 'col', 'ec': 'col', 'zorder': '(-1)'}), "(xy, electodePlotWidth, parameters['electrodeWidth'], angle=\n angle, fc=col, ec=col, zorder=-1)\n", (12982, 13080), True, 'import matplotlib.pylab as plt\n'), ((16705, 16801), 'matplotlib.pylab.Rectangle', 'plt.Rectangle', (['(0, 0)', "parameters['lenX']", "parameters['lenY']"], {'fc': '"""none"""', 'ec': '"""k"""', 'zorder': '(-2)'}), "((0, 0), parameters['lenX'], parameters['lenY'], fc='none', ec\n ='k', zorder=-2)\n", (16718, 16801), True, 'import matplotlib.pylab as plt\n'), ((6707, 6906), 'matplotlib.patches.Wedge', 'Wedge', (['(0, 0)', "(parameters['radius'] + electodePlotWidth / 2)", '(electrodes[i][0] - electrodeWidth / 2)', '(electrodes[i][0] + electrodeWidth / 2)'], {'width': 'electodePlotWidth', 'fc': 'col', 'ec': 'col', 'zorder': '(-1)'}), "((0, 0), parameters['radius'] + electodePlotWidth / 2, electrodes[i][0\n ] - electrodeWidth / 2, electrodes[i][0] + electrodeWidth / 2, width=\n electodePlotWidth, fc=col, ec=col, zorder=-1)\n", (6712, 6906), False, 'from matplotlib.patches import Wedge\n'), ((13588, 13787), 'matplotlib.patches.Wedge', 'Wedge', (['(0, 0)', "(parameters['radius'] + electodePlotWidth / 2)", '(electrodes[i][0] - electrodeWidth / 2)', '(electrodes[i][0] + electrodeWidth / 2)'], {'width': 'electodePlotWidth', 'fc': 'col', 'ec': 'col', 'zorder': '(-1)'}), "((0, 0), parameters['radius'] + electodePlotWidth / 2, electrodes[i][0\n ] - electrodeWidth / 2, electrodes[i][0] + electrodeWidth / 2, width=\n electodePlotWidth, fc=col, ec=col, zorder=-1)\n", (13593, 13787), False, 'from matplotlib.patches import Wedge\n')] |
import pytest
import stweet as st
from tests.test_util import get_temp_test_file_name, get_tweets_to_tweet_output_test, \
two_lists_assert_equal
def test_csv_serialization():
csv_filename = get_temp_test_file_name('csv')
tweets_collector = st.CollectorTweetOutput()
get_tweets_to_tweet_output_test([
st.CsvTweetOutput(csv_filename),
tweets_collector
])
tweets_from_csv = st.read_tweets_from_csv_file(csv_filename)
two_lists_assert_equal(tweets_from_csv, tweets_collector.get_raw_list())
def test_file_json_lines_serialization():
jl_filename = get_temp_test_file_name('jl')
tweets_collector = st.CollectorTweetOutput()
get_tweets_to_tweet_output_test([
st.JsonLineFileTweetOutput(jl_filename),
tweets_collector
])
tweets_from_jl = st.read_tweets_from_json_lines_file(jl_filename)
two_lists_assert_equal(tweets_from_jl, tweets_collector.get_raw_list())
| [
"stweet.read_tweets_from_csv_file",
"tests.test_util.get_temp_test_file_name",
"stweet.read_tweets_from_json_lines_file",
"stweet.CollectorTweetOutput",
"stweet.JsonLineFileTweetOutput",
"stweet.CsvTweetOutput"
] | [((201, 231), 'tests.test_util.get_temp_test_file_name', 'get_temp_test_file_name', (['"""csv"""'], {}), "('csv')\n", (224, 231), False, 'from tests.test_util import get_temp_test_file_name, get_tweets_to_tweet_output_test, two_lists_assert_equal\n'), ((255, 280), 'stweet.CollectorTweetOutput', 'st.CollectorTweetOutput', ([], {}), '()\n', (278, 280), True, 'import stweet as st\n'), ((414, 456), 'stweet.read_tweets_from_csv_file', 'st.read_tweets_from_csv_file', (['csv_filename'], {}), '(csv_filename)\n', (442, 456), True, 'import stweet as st\n'), ((596, 625), 'tests.test_util.get_temp_test_file_name', 'get_temp_test_file_name', (['"""jl"""'], {}), "('jl')\n", (619, 625), False, 'from tests.test_util import get_temp_test_file_name, get_tweets_to_tweet_output_test, two_lists_assert_equal\n'), ((649, 674), 'stweet.CollectorTweetOutput', 'st.CollectorTweetOutput', ([], {}), '()\n', (672, 674), True, 'import stweet as st\n'), ((815, 863), 'stweet.read_tweets_from_json_lines_file', 'st.read_tweets_from_json_lines_file', (['jl_filename'], {}), '(jl_filename)\n', (850, 863), True, 'import stweet as st\n'), ((327, 358), 'stweet.CsvTweetOutput', 'st.CsvTweetOutput', (['csv_filename'], {}), '(csv_filename)\n', (344, 358), True, 'import stweet as st\n'), ((721, 760), 'stweet.JsonLineFileTweetOutput', 'st.JsonLineFileTweetOutput', (['jl_filename'], {}), '(jl_filename)\n', (747, 760), True, 'import stweet as st\n')] |
# coding=utf-8
"""
Setup for scikit-surgerytf
"""
from setuptools import setup, find_packages
import versioneer
# Get the long description
with open('README.rst') as f:
long_description = f.read()
setup(
name='scikit-surgerytf',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
description='scikit-surgerytf is a Python package for Tensor Flow examples and utilities',
long_description=long_description,
long_description_content_type='text/x-rst',
url='https://github.com/UCL/scikit-surgerytf',
author='<NAME>',
author_email='<EMAIL>',
license='Apache Software License 2.0',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Intended Audience :: Healthcare Industry',
'Intended Audience :: Information Technology',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Scientific/Engineering :: Information Analysis',
'Topic :: Scientific/Engineering :: Medical Science Apps.',
],
keywords='medical imaging',
packages=find_packages(
exclude=[
'docs',
'tests',
]
),
install_requires=[
'pyyaml',
'h5py',
'ipykernel',
'nbsphinx',
'Pillow',
'scipy',
'opencv-contrib-python==4.1.1.26',
'tensorflow==2.0.0',
'tensorflow-datasets==1.3.0',
'matplotlib==3.1.1'
],
entry_points={
'console_scripts': [
'sksurgeryfashion=sksurgerytf.ui.sksurgery_fashion_command_line:main',
'sksurgeryrgbunet=sksurgerytf.ui.sksurgery_rgbunet_command_line:main',
'sksurgerysegstats=sksurgerytf.ui.sksurgery_segstats_command_line:main'
],
},
)
| [
"versioneer.get_cmdclass",
"setuptools.find_packages",
"versioneer.get_version"
] | [((252, 276), 'versioneer.get_version', 'versioneer.get_version', ([], {}), '()\n', (274, 276), False, 'import versioneer\n'), ((291, 316), 'versioneer.get_cmdclass', 'versioneer.get_cmdclass', ([], {}), '()\n', (314, 316), False, 'import versioneer\n'), ((1294, 1334), 'setuptools.find_packages', 'find_packages', ([], {'exclude': "['docs', 'tests']"}), "(exclude=['docs', 'tests'])\n", (1307, 1334), False, 'from setuptools import setup, find_packages\n')] |
# coding: utf-8
"""
2018-03-19.
Maximum screenshots in 1 second by computing BGRA raw values to RGB.
GNU/Linux
pil_frombytes 139
mss_rgb 119
pil_frombytes_rgb 51
numpy_flip 31
numpy_slice 29
macOS
pil_frombytes 209
mss_rgb 174
pil_frombytes_rgb 113
numpy_flip 39
numpy_slice 36
Windows
pil_frombytes 81
mss_rgb 66
pil_frombytes_rgb 42
numpy_flip 25
numpy_slice 22
"""
from __future__ import print_function
import time
import numpy
from PIL import Image
import mss
def mss_rgb(im):
return im.rgb
def numpy_flip(im):
frame = numpy.array(im, dtype=numpy.uint8)
return numpy.flip(frame[:, :, :3], 2).tobytes()
def numpy_slice(im):
return numpy.array(im, dtype=numpy.uint8)[..., [2, 1, 0]].tobytes()
def pil_frombytes_rgb(im):
return Image.frombytes('RGB', im.size, im.rgb).tobytes()
def pil_frombytes(im):
return Image.frombytes('RGB', im.size, im.bgra, 'raw', 'BGRX').tobytes()
def benchmark():
with mss.mss() as sct:
im = sct.grab(sct.monitors[0])
for func in (pil_frombytes,
mss_rgb,
pil_frombytes_rgb,
numpy_flip,
numpy_slice):
count = 0
start = time.time()
while (time.time() - start) <= 1:
func(im)
im._ScreenShot__rgb = None
count += 1
print(func.__name__.ljust(17), count)
benchmark()
| [
"numpy.flip",
"mss.mss",
"numpy.array",
"PIL.Image.frombytes",
"time.time"
] | [((655, 689), 'numpy.array', 'numpy.array', (['im'], {'dtype': 'numpy.uint8'}), '(im, dtype=numpy.uint8)\n', (666, 689), False, 'import numpy\n'), ((1057, 1066), 'mss.mss', 'mss.mss', ([], {}), '()\n', (1064, 1066), False, 'import mss\n'), ((701, 731), 'numpy.flip', 'numpy.flip', (['frame[:, :, :3]', '(2)'], {}), '(frame[:, :, :3], 2)\n', (711, 731), False, 'import numpy\n'), ((877, 916), 'PIL.Image.frombytes', 'Image.frombytes', (['"""RGB"""', 'im.size', 'im.rgb'], {}), "('RGB', im.size, im.rgb)\n", (892, 916), False, 'from PIL import Image\n'), ((963, 1018), 'PIL.Image.frombytes', 'Image.frombytes', (['"""RGB"""', 'im.size', 'im.bgra', '"""raw"""', '"""BGRX"""'], {}), "('RGB', im.size, im.bgra, 'raw', 'BGRX')\n", (978, 1018), False, 'from PIL import Image\n'), ((1330, 1341), 'time.time', 'time.time', ([], {}), '()\n', (1339, 1341), False, 'import time\n'), ((776, 810), 'numpy.array', 'numpy.array', (['im'], {'dtype': 'numpy.uint8'}), '(im, dtype=numpy.uint8)\n', (787, 810), False, 'import numpy\n'), ((1361, 1372), 'time.time', 'time.time', ([], {}), '()\n', (1370, 1372), False, 'import time\n')] |
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# pylint: disable=no-member,relative-import
"""Unit tests for blink_idl_parser.py."""
import unittest
from blink_idl_parser import BlinkIDLParser
class BlinkIDLParserTest(unittest.TestCase):
def test_missing_semicolon_between_definitions(self):
# No semicolon after enum definition.
text = '''enum TestEnum { "value" } dictionary TestDictionary {};'''
parser = BlinkIDLParser()
parser.ParseText(filename='', data=text)
self.assertGreater(parser.GetErrors(), 0)
| [
"blink_idl_parser.BlinkIDLParser"
] | [((556, 572), 'blink_idl_parser.BlinkIDLParser', 'BlinkIDLParser', ([], {}), '()\n', (570, 572), False, 'from blink_idl_parser import BlinkIDLParser\n')] |
import calc
def caesar_cipher(word, base):
up_alpha = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
low_alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
new_word = ''
base = base if abs(base) <= 26 else calc.base_finder(base)
for letter in word:
if letter.isnumeric() == True or letter.isalpha()==False:
new_word += letter
elif letter.isupper() == True:
try:
new_word += up_alpha[up_alpha.index(letter)+base]
except IndexError:
difference = (up_alpha.index(letter)+base) - 26
print(difference)
new_word += up_alpha[difference]
else:
try:
new_word += low_alpha[low_alpha.index(letter)+base]
except IndexError:
difference_low = (low_alpha.index(letter)+base) - 26
print(difference_low)
new_word += low_alpha[difference_low]
return new_word
def substitution(word, substitute, specify): #proto
char_list = list(substitute)
new_word = ''
counter = 0
if len(substitute) != len(specify):
return "Second and third arguments were not entered correctly"
for letter in word:
counter=0
for sub in char_list:
if letter == sub:
counter+=1
new_word+=specify[char_list.index(sub)]
if counter==0:
new_word+=letter
return new_word
def binary(number):
new_number = bin(number) + ""
new_number = new_number[2:]
return new_number
def hexadecimal(number):
new_number = hex(int(number))
new_number = new_number[2:]
return new_number | [
"calc.base_finder"
] | [((387, 409), 'calc.base_finder', 'calc.base_finder', (['base'], {}), '(base)\n', (403, 409), False, 'import calc\n')] |
"""
Allows easy loading of pixmaps used in UI elements.
Provides support for frozen environments as well.
"""
import os, sys, pickle
from ..functions import makeQImage
from ..Qt import QtGui
from ..python2_3 import basestring
if sys.version_info[0] == 2:
from . import pixmapData_2 as pixmapData
else:
from . import pixmapData_3 as pixmapData
def getPixmap(name):
"""
Return a QPixmap corresponding to the image file with the given name.
(eg. getPixmap('auto') loads pyqtgraph/pixmaps/auto.png)
"""
key = name+'.png'
data = pixmapData.pixmapData[key]
if isinstance(data, basestring) or isinstance(data, bytes):
pixmapData.pixmapData[key] = pickle.loads(data)
arr = pixmapData.pixmapData[key]
return QtGui.QPixmap(makeQImage(arr, alpha=True))
| [
"pickle.loads"
] | [((711, 729), 'pickle.loads', 'pickle.loads', (['data'], {}), '(data)\n', (723, 729), False, 'import os, sys, pickle\n')] |