hexsha stringlengths 40 40 | size int64 2 1.02M | ext stringclasses 10
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 245 | max_stars_repo_name stringlengths 6 130 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 245 | max_issues_repo_name stringlengths 6 130 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 245 | max_forks_repo_name stringlengths 6 130 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 2 1.02M | avg_line_length float64 1 417k | max_line_length int64 1 987k | alphanum_fraction float64 0 1 | content_no_comment stringlengths 0 1.01M | is_comment_constant_removed bool 1
class | is_sharp_comment_removed bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f72b5891618054c5f8898c72c812d2bae47239f4 | 3,403 | py | Python | note/meiduo34/mall/apps/users/models.py | gaosong666/taobao | cec3be71376fb94dc38553360253b70e88855594 | [
"MIT"
] | null | null | null | note/meiduo34/mall/apps/users/models.py | gaosong666/taobao | cec3be71376fb94dc38553360253b70e88855594 | [
"MIT"
] | null | null | null | note/meiduo34/mall/apps/users/models.py | gaosong666/taobao | cec3be71376fb94dc38553360253b70e88855594 | [
"MIT"
] | null | null | null | from django.contrib.auth.models import AbstractUser
from django.db import models
# Create your models here.
# from itsdangerous import Serializer
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData
from mall import settings
from utils.models import BaseModel
class User(AbstractUser):
mobile = models.CharField(max_length=11, unique=True, verbose_name='手机号')
email_active = models.BooleanField(default=False, verbose_name='邮箱验证状态')
default_address = models.ForeignKey('Address', related_name='users', null=True, blank=True,
on_delete=models.SET_NULL, verbose_name='默认地址')
class Meta:
db_table = 'tb_users'
verbose_name = '用户'
verbose_name_plural = verbose_name
def generate_verify_email_url(self):
serializer = Serializer(settings.SECRET_KEY, 3600)
# 加载用户信息
token = serializer.dumps({'user_id': self.id, 'email': self.email})
# 注意拼接的过程中对 token进行decode操作
verify_url = 'http://www.meiduo.site:8080/success_verify_email.html?token=' + token.decode()
return verify_url
@staticmethod
def check_verify_email_token(token):
serializer = Serializer(settings.SECRET_KEY, 3600)
try:
# 加载token
result = serializer.loads(token)
except BadData:
return None
else:
user_id = result.get('user_id')
email = result.get('email')
try:
user = User.objects.get(id=user_id, email=email)
except User.DoesNotExist:
user = None
return user
# @classmethod
# def check_active_mail_token(cls, token):
#
# serializer = Serializer(settings.SECRET_KEY, 3600)
#
# try:
# result = serializer.loads(token)
# except BadData:
# return None
# else:
#
# id = result.get('id')
# email = result.get('email')
# try:
# user = User.objects.get(id=id, email=email)
# except User.DoesNotExist:
# user = None
#
# return user
class Address(BaseModel):
"""
用户地址
"""
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='addresses', verbose_name='用户')
title = models.CharField(max_length=20, verbose_name='地址名称')
receiver = models.CharField(max_length=20, verbose_name='收货人')
province = models.ForeignKey('areas.Area', on_delete=models.PROTECT, related_name='province_addresses', verbose_name='省')
city = models.ForeignKey('areas.Area', on_delete=models.PROTECT, related_name='city_addresses', verbose_name='市')
district = models.ForeignKey('areas.Area', on_delete=models.PROTECT, related_name='district_addresses', verbose_name='区')
place = models.CharField(max_length=50, verbose_name='地址')
mobile = models.CharField(max_length=11, verbose_name='手机')
tel = models.CharField(max_length=20, null=True, blank=True, default='', verbose_name='固定电话')
email = models.CharField(max_length=30, null=True, blank=True, default='', verbose_name='电子邮箱')
is_deleted = models.BooleanField(default=False, verbose_name='逻辑删除')
class Meta:
db_table = 'tb_address'
verbose_name = '用户地址'
verbose_name_plural = verbose_name
ordering = ['-update_time'] | 37.395604 | 125 | 0.645901 | from django.contrib.auth.models import AbstractUser
from django.db import models
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData
from mall import settings
from utils.models import BaseModel
class User(AbstractUser):
mobile = models.CharField(max_length=11, unique=True, verbose_name='手机号')
email_active = models.BooleanField(default=False, verbose_name='邮箱验证状态')
default_address = models.ForeignKey('Address', related_name='users', null=True, blank=True,
on_delete=models.SET_NULL, verbose_name='默认地址')
class Meta:
db_table = 'tb_users'
verbose_name = '用户'
verbose_name_plural = verbose_name
def generate_verify_email_url(self):
serializer = Serializer(settings.SECRET_KEY, 3600)
token = serializer.dumps({'user_id': self.id, 'email': self.email})
verify_url = 'http://www.meiduo.site:8080/success_verify_email.html?token=' + token.decode()
return verify_url
@staticmethod
def check_verify_email_token(token):
serializer = Serializer(settings.SECRET_KEY, 3600)
try:
result = serializer.loads(token)
except BadData:
return None
else:
user_id = result.get('user_id')
email = result.get('email')
try:
user = User.objects.get(id=user_id, email=email)
except User.DoesNotExist:
user = None
return user
class Address(BaseModel):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='addresses', verbose_name='用户')
title = models.CharField(max_length=20, verbose_name='地址名称')
receiver = models.CharField(max_length=20, verbose_name='收货人')
province = models.ForeignKey('areas.Area', on_delete=models.PROTECT, related_name='province_addresses', verbose_name='省')
city = models.ForeignKey('areas.Area', on_delete=models.PROTECT, related_name='city_addresses', verbose_name='市')
district = models.ForeignKey('areas.Area', on_delete=models.PROTECT, related_name='district_addresses', verbose_name='区')
place = models.CharField(max_length=50, verbose_name='地址')
mobile = models.CharField(max_length=11, verbose_name='手机')
tel = models.CharField(max_length=20, null=True, blank=True, default='', verbose_name='固定电话')
email = models.CharField(max_length=30, null=True, blank=True, default='', verbose_name='电子邮箱')
is_deleted = models.BooleanField(default=False, verbose_name='逻辑删除')
class Meta:
db_table = 'tb_address'
verbose_name = '用户地址'
verbose_name_plural = verbose_name
ordering = ['-update_time'] | true | true |
f72b58f5171215cd31d5b12f28261a896f30aa4c | 7,827 | py | Python | research/object_detection/training/TFLite_detection_video.py | geometrikal/tensorflow_models | 44a82f3f18a2e62b1cd99b94922f752be0672f46 | [
"Apache-2.0"
] | null | null | null | research/object_detection/training/TFLite_detection_video.py | geometrikal/tensorflow_models | 44a82f3f18a2e62b1cd99b94922f752be0672f46 | [
"Apache-2.0"
] | null | null | null | research/object_detection/training/TFLite_detection_video.py | geometrikal/tensorflow_models | 44a82f3f18a2e62b1cd99b94922f752be0672f46 | [
"Apache-2.0"
] | null | null | null | ######## Webcam Object Detection Using Tensorflow-trained Classifier #########
#
# Author: Evan Juras
# Date: 10/2/19
# Description:
# This program uses a TensorFlow Lite model to perform object detection on a
# video. It draws boxes and scores around the objects of interest in each frame
# from the video.
#
# This code is based off the TensorFlow Lite image classification example at:
# https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/examples/python/label_image.py
#
# I added my own method of drawing boxes and labels using OpenCV.
# Import packages
import os
import argparse
import cv2
import numpy as np
import sys
import importlib.util
def increase_brightness(img, value=30):
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(hsv)
lim = 255 - value
v[v > lim] = 255
v[v <= lim] += value
final_hsv = cv2.merge((h, s, v))
img = cv2.cvtColor(final_hsv, cv2.COLOR_HSV2BGR)
return img
# Define and parse input arguments
parser = argparse.ArgumentParser()
parser.add_argument('--modeldir', help='Folder the .tflite file is located in',
required=True)
parser.add_argument('--graph', help='Name of the .tflite file, if different than detect.tflite',
default='detect.tflite')
parser.add_argument('--labels', help='Name of the labelmap file, if different than labelmap.txt',
default='labelmap.txt')
parser.add_argument('--threshold', help='Minimum confidence threshold for displaying detected objects',
default=0.5)
parser.add_argument('--video', help='Name of the video file',
default='test.mp4')
parser.add_argument('--edgetpu', help='Use Coral Edge TPU Accelerator to speed up detection',
action='store_true')
parser.add_argument('--subsample', type=int, default=1, help='Subsample the input image')
parser.add_argument('--offset', type=int, default=0, help='Offset into file')
args = parser.parse_args()
MODEL_NAME = args.modeldir
GRAPH_NAME = args.graph
LABELMAP_NAME = args.labels
VIDEO_NAME = args.video
min_conf_threshold = float(args.threshold)
use_TPU = args.edgetpu
# Import TensorFlow libraries
# If tflite_runtime is installed, import interpreter from tflite_runtime, else import from regular tensorflow
# If using Coral Edge TPU, import the load_delegate library
pkg = importlib.util.find_spec('tflite_runtime')
if pkg:
from tflite_runtime.interpreter import Interpreter
if use_TPU:
from tflite_runtime.interpreter import load_delegate
else:
from tensorflow.lite.python.interpreter import Interpreter
if use_TPU:
from tensorflow.lite.python.interpreter import load_delegate
# If using Edge TPU, assign filename for Edge TPU model
if use_TPU:
# If user has specified the name of the .tflite file, use that name, otherwise use default 'edgetpu.tflite'
if (GRAPH_NAME == 'detect.tflite'):
GRAPH_NAME = 'edgetpu.tflite'
# Get path to current working directory
CWD_PATH = os.getcwd()
# Path to video file
VIDEO_PATH = os.path.join(CWD_PATH,VIDEO_NAME)
# Path to .tflite file, which contains the model that is used for object detection
PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,GRAPH_NAME)
# Path to label map file
PATH_TO_LABELS = os.path.join(CWD_PATH,MODEL_NAME,LABELMAP_NAME)
# Load the label map
with open(PATH_TO_LABELS, 'r') as f:
labels = [line.strip() for line in f.readlines()]
# Have to do a weird fix for label map if using the COCO "starter model" from
# https://www.tensorflow.org/lite/models/object_detection/overview
# First label is '???', which has to be removed.
if labels[0] == '???':
del(labels[0])
# Load the Tensorflow Lite model.
# If using Edge TPU, use special load_delegate argument
if use_TPU:
interpreter = Interpreter(model_path=PATH_TO_CKPT,
experimental_delegates=[load_delegate('libedgetpu.so.1.0')])
print(PATH_TO_CKPT)
else:
interpreter = Interpreter(model_path=PATH_TO_CKPT)
interpreter.allocate_tensors()
# Get model details
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
height = input_details[0]['shape'][1]
width = input_details[0]['shape'][2]
floating_model = (input_details[0]['dtype'] == np.float32)
input_mean = 127.5
input_std = 127.5
# Open video file
video = cv2.VideoCapture(VIDEO_PATH)
imW = video.get(cv2.CAP_PROP_FRAME_WIDTH)
imH = video.get(cv2.CAP_PROP_FRAME_HEIGHT)
out = cv2.VideoWriter('output.mp4', -1, 20.0, (int(imW),int(imH)))
fidx = 0
while(video.isOpened()):
# Acquire frame and resize to expected shape [1xHxWx3]
ret, frame = video.read()
if not ret:
print('Reached the end of the video!')
break
print(fidx)
fidx += 1
if fidx < args.offset:
continue
if args.subsample > 1:
imH, imW, _ = frame.shape
frame = cv2.resize(frame, (imW // args.subsample, imH // args.subsample))
# frame = increase_brightness(frame, value=70)
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame_resized = cv2.resize(frame_rgb, (width, height))
input_data = np.expand_dims(frame_resized, axis=0)
# Normalize pixel values if using a floating model (i.e. if model is non-quantized)
if floating_model:
input_data = (np.float32(input_data) - input_mean) / input_std
# Perform the actual detection by running the model with the image as input
interpreter.set_tensor(input_details[0]['index'],input_data)
interpreter.invoke()
# Retrieve detection results
boxes = interpreter.get_tensor(output_details[0]['index'])[0] # Bounding box coordinates of detected objects
classes = interpreter.get_tensor(output_details[1]['index'])[0] # Class index of detected objects
scores = interpreter.get_tensor(output_details[2]['index'])[0] # Confidence of detected objects
num = interpreter.get_tensor(output_details[3]['index'])[0] # Total number of detected objects (inaccurate and not needed)
# Loop over all detections and draw detection box if confidence is above minimum threshold
for i in range(int(num)):
# for i in range(len(scores)):
if ((scores[i] > min_conf_threshold) and (scores[i] <= 1.0)):
# Get bounding box coordinates and draw box
# Interpreter can return coordinates that are outside of image dimensions, need to force them to be within image using max() and min()
ymin = int(max(1,(boxes[i][0] * imH)))
xmin = int(max(1,(boxes[i][1] * imW)))
ymax = int(min(imH,(boxes[i][2] * imH)))
xmax = int(min(imW,(boxes[i][3] * imW)))
cv2.rectangle(frame, (xmin,ymin), (xmax,ymax), (10, 255, 0), 4)
# Draw label
object_name = labels[int(classes[i])] # Look up object name from "labels" array using class index
label = '%s: %d%%' % (object_name, int(scores[i]*100)) # Example: 'person: 72%'
labelSize, baseLine = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.7, 2) # Get font size
label_ymin = max(ymin, labelSize[1] + 10) # Make sure not to draw label too close to top of window
cv2.rectangle(frame, (xmin, label_ymin-labelSize[1]-10), (xmin+labelSize[0], label_ymin+baseLine-10), (255, 255, 255), cv2.FILLED) # Draw white box to put label text in
cv2.putText(frame, label, (xmin, label_ymin-7), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 2) # Draw label text
# All the results have been drawn on the frame, so it's time to display it.
out.write(frame)
cv2.imshow('Object detector', frame)
# Press 'q' to quit
if cv2.waitKey(1) == ord('q'):
break
# Clean up
out.release()
video.release()
cv2.destroyAllWindows()
| 37.995146 | 180 | 0.689408 | ument('--graph', help='Name of the .tflite file, if different than detect.tflite',
default='detect.tflite')
parser.add_argument('--labels', help='Name of the labelmap file, if different than labelmap.txt',
default='labelmap.txt')
parser.add_argument('--threshold', help='Minimum confidence threshold for displaying detected objects',
default=0.5)
parser.add_argument('--video', help='Name of the video file',
default='test.mp4')
parser.add_argument('--edgetpu', help='Use Coral Edge TPU Accelerator to speed up detection',
action='store_true')
parser.add_argument('--subsample', type=int, default=1, help='Subsample the input image')
parser.add_argument('--offset', type=int, default=0, help='Offset into file')
args = parser.parse_args()
MODEL_NAME = args.modeldir
GRAPH_NAME = args.graph
LABELMAP_NAME = args.labels
VIDEO_NAME = args.video
min_conf_threshold = float(args.threshold)
use_TPU = args.edgetpu
pkg = importlib.util.find_spec('tflite_runtime')
if pkg:
from tflite_runtime.interpreter import Interpreter
if use_TPU:
from tflite_runtime.interpreter import load_delegate
else:
from tensorflow.lite.python.interpreter import Interpreter
if use_TPU:
from tensorflow.lite.python.interpreter import load_delegate
if use_TPU:
if (GRAPH_NAME == 'detect.tflite'):
GRAPH_NAME = 'edgetpu.tflite'
CWD_PATH = os.getcwd()
VIDEO_PATH = os.path.join(CWD_PATH,VIDEO_NAME)
PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,GRAPH_NAME)
PATH_TO_LABELS = os.path.join(CWD_PATH,MODEL_NAME,LABELMAP_NAME)
with open(PATH_TO_LABELS, 'r') as f:
labels = [line.strip() for line in f.readlines()]
if labels[0] == '???':
del(labels[0])
if use_TPU:
interpreter = Interpreter(model_path=PATH_TO_CKPT,
experimental_delegates=[load_delegate('libedgetpu.so.1.0')])
print(PATH_TO_CKPT)
else:
interpreter = Interpreter(model_path=PATH_TO_CKPT)
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
height = input_details[0]['shape'][1]
width = input_details[0]['shape'][2]
floating_model = (input_details[0]['dtype'] == np.float32)
input_mean = 127.5
input_std = 127.5
video = cv2.VideoCapture(VIDEO_PATH)
imW = video.get(cv2.CAP_PROP_FRAME_WIDTH)
imH = video.get(cv2.CAP_PROP_FRAME_HEIGHT)
out = cv2.VideoWriter('output.mp4', -1, 20.0, (int(imW),int(imH)))
fidx = 0
while(video.isOpened()):
ret, frame = video.read()
if not ret:
print('Reached the end of the video!')
break
print(fidx)
fidx += 1
if fidx < args.offset:
continue
if args.subsample > 1:
imH, imW, _ = frame.shape
frame = cv2.resize(frame, (imW // args.subsample, imH // args.subsample))
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame_resized = cv2.resize(frame_rgb, (width, height))
input_data = np.expand_dims(frame_resized, axis=0)
if floating_model:
input_data = (np.float32(input_data) - input_mean) / input_std
interpreter.set_tensor(input_details[0]['index'],input_data)
interpreter.invoke()
boxes = interpreter.get_tensor(output_details[0]['index'])[0]
classes = interpreter.get_tensor(output_details[1]['index'])[0]
scores = interpreter.get_tensor(output_details[2]['index'])[0]
num = interpreter.get_tensor(output_details[3]['index'])[0]
for i in range(int(num)):
if ((scores[i] > min_conf_threshold) and (scores[i] <= 1.0)):
ymin = int(max(1,(boxes[i][0] * imH)))
xmin = int(max(1,(boxes[i][1] * imW)))
ymax = int(min(imH,(boxes[i][2] * imH)))
xmax = int(min(imW,(boxes[i][3] * imW)))
cv2.rectangle(frame, (xmin,ymin), (xmax,ymax), (10, 255, 0), 4)
object_name = labels[int(classes[i])]
label = '%s: %d%%' % (object_name, int(scores[i]*100))
labelSize, baseLine = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.7, 2)
label_ymin = max(ymin, labelSize[1] + 10)
cv2.rectangle(frame, (xmin, label_ymin-labelSize[1]-10), (xmin+labelSize[0], label_ymin+baseLine-10), (255, 255, 255), cv2.FILLED)
cv2.putText(frame, label, (xmin, label_ymin-7), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 2)
out.write(frame)
cv2.imshow('Object detector', frame)
# Press 'q' to quit
if cv2.waitKey(1) == ord('q'):
break
# Clean up
out.release()
video.release()
cv2.destroyAllWindows()
| true | true |
f72b5994c29c19a3357fc7ba21a214ddbce1dcfd | 8,591 | py | Python | my_test/get_graph.py | RuoyuX-2018/6998DL | a9b75ee63a92c6824db9ac25cc6d931713e0cae5 | [
"BSD-3-Clause"
] | null | null | null | my_test/get_graph.py | RuoyuX-2018/6998DL | a9b75ee63a92c6824db9ac25cc6d931713e0cae5 | [
"BSD-3-Clause"
] | null | null | null | my_test/get_graph.py | RuoyuX-2018/6998DL | a9b75ee63a92c6824db9ac25cc6d931713e0cae5 | [
"BSD-3-Clause"
] | null | null | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 14 15:47:45 2021
@author: xuery
"""
import cv2
import time
import numpy as np
import os
import copy
import pickle
import random
import math
import matplotlib.pyplot as plt
from scipy import spatial
from skimage import morphology
from sklearn.mixture import GaussianMixture
from shapely.geometry import LineString, Point
from mpl_toolkits.mplot3d import Axes3D
class get_graph():
def __init__(self, raw_img):
self.raw_img = cv2.resize(raw_img, (512,512))
self.stride = 30
self.all_centroids = []
def get_binary(self):
gray_img = cv2.cvtColor(self.raw_img, cv2.COLOR_RGB2GRAY)
_, binary_img = cv2.threshold(gray_img, 100, 255, cv2.THRESH_BINARY_INV)
return binary_img
def ske2point(self):
skeleton_img = self.get_binary()
img_w, img_h = skeleton_img.shape
for i in range(img_w//self.stride):
for j in range(img_h//self.stride):
small_img = skeleton_img[i*self.stride:(i+1)*self.stride, j*self.stride:(j+1)*self.stride]
x_idx, y_idx = small_img.nonzero()
if len(x_idx) == 0:
continue
x_center, y_center = sum(x_idx) / len(x_idx) + i * self.stride,\
sum(y_idx) / len(x_idx) + j * self.stride
#all_centorids stores the idx of points
self.all_centroids.append(np.array([int(x_center), int(y_center)]))
self.all_centroids = np.array(self.all_centroids)
self.centroids_copy = copy.deepcopy(self.all_centroids)
def optimization(self, save_path=None):
#for the points in all_centroid that don't belong to the rope, delete it
noise_idx = []
binary_img = self.get_binary()
for i in range(len(self.all_centroids)):
if binary_img[int(self.all_centroids[i][0])][int(self.all_centroids[i][1])] == 0:
noise_idx.append(i)
self.all_centroids = np.delete(self.all_centroids, noise_idx, axis=0)
if save_path != None:
self.img_point_write(save_path, all_centroids, binary_img)
def visualization(self):
self.optimization()
plt.plot(self.all_centroids[:,0], self.all_centroids[:,1], 'bo', ms=5)
plt.show()
def graph(self, num_neigh_points = 10):
self.ske2point()
self.visualization()
tree = spatial.KDTree(self.all_centroids)
start_point = [500, 0]
neigh_points_idx, neigh_points = self.find_neigh_points(tree, start_point, 2)
next_point = neigh_points[0]
query_pair = [start_point, next_point]
point_order = query_pair
while True:
if len(self.all_centroids) < num_neigh_points:
break
if len(self.all_centroids) == 30:
break
tree = spatial.KDTree(self.all_centroids)
neigh_points_idx, neigh_points = self.find_neigh_points(tree, query_pair[1], num_neigh_points)
idx, next_point = self.find_path(query_pair, neigh_points)
if idx == -99:
print("end of construction...")
return point_order
query_pair = [query_pair[1], next_point]
point_order.append(next_point)
#pop out the walked point
self.all_centroids = self.all_centroids.tolist()
self.all_centroids.pop(neigh_points_idx[idx])
self.all_centroids = np.array(self.all_centroids)
print("remain lens of points: ", len(self.all_centroids))
return point_order
def find_neigh_points(self, tree, centroid, num_points):
dist, near_points_idx = tree.query(centroid, k=num_points)
near_points = self.all_centroids[near_points_idx]
return near_points_idx[1:], near_points[1:]
def find_path(self, query_pair, neigh_points):
v_query = query_pair[1] - query_pair[0]
next_point = np.zeros_like(query_pair[0])
angle_diff = np.pi
next_idx = -99
for i in range(len(neigh_points)):
v_compare = query_pair[1] - neigh_points[i]
#if the dist of all neigh_points is more than 65, break. This setting is for noise
if np.linalg.norm(v_compare) >70:
continue
#calculate the angle of two vectors
unit_v1 = v_query / np.linalg.norm(v_query)
unit_v2 = v_compare / np.linalg.norm(v_compare)
dot_product = np.dot(unit_v1, unit_v2)
angle = np.arccos(dot_product) #radian
if np.pi - angle < angle_diff:
next_point = neigh_points[i]
angle_diff = np.pi - angle
next_idx = i
return next_idx, next_point
def find_crossing(self, point_order, visual=False):
#create lines
pairs = []
crossing = []
for i in range(len(point_order)-1):
new_pair = np.array([point_order[i], point_order[i+1]])
pairs.append(new_pair)
for i in range(len(pairs)):
for j in range(len(pairs)-i):
intersec = self.intersection(pairs[i], pairs[j+i])
if intersec is not False:
crossing.append([intersec, pairs[i][0], pairs[j+i][0]])
if visual == True:
self.visualization_final_graph(point_order, crossing)
return crossing
#if no intersection, return False, else return the value of intersection
def intersection(self, pair1, pair2):
#if two pairs has a same point, break
if np.all(pair1[0]-pair2[0]==0) or np.all(pair1[1]-pair2[0]==0) \
or np.all(pair1[0]-pair2[1]==0) or np.all(pair1[1]-pair2[1]==0):
return False
line1 = LineString([pair1[0], pair1[1]])
line2 = LineString([pair2[0], pair2[1]])
intersection_point = line1.intersection(line2)
#no intersection
if intersection_point.is_empty:
return False
else:
return np.array([intersection_point.x, intersection_point.y])
def visualization_final_graph(self, point_order, crossing):
x, y = zip(*point_order)
plt.plot(x, y, '-o', zorder=1)
crossing = np.array(crossing)
c_x = crossing[:,0,0]
c_y = crossing[:,0,1]
plt.scatter(c_x, c_y, 20, 'r', zorder=2)
plt.show()
def trajectory(self, env, sa, point_order, crossing, stride):
picker_pos, particle_pos = sa.action_space.Picker._get_pos()
print(particle_pos)
particle_dist_2d = np.linalg.norm(particle_pos[0] - particle_pos[1])
init_particle = particle_pos[random.randint(0,len(particle_pos))].tolist()
particle_list = []
particle_list.append(init_particle)
for i in range(len(point_order)-stride):
if i % stride != 0:
continue
curr_particle = particle_list[i//stride]
y_o = point_order[i+stride][1] - point_order[i][1]
x_o = point_order[i+stride][0] - point_order[i][0]
orientation = abs(y_o / x_o)
theta = math.atan(orientation)
if x_o == 0:
x_o = 0.1
if y_o == 0:
y_o = 0.1
x = curr_particle[0] + math.cos(theta) * particle_dist_2d * x_o / abs(x_o)
y = curr_particle[2] + math.sin(theta) * particle_dist_2d * y_o / abs(y_o)
next_particle = [x, curr_particle[1], y, curr_particle[3]]
particle_list.append(next_particle)
for i in range(len(particle_list)):
if i == 3:
particle_list[i][1] = 0.0145
if i == 4:
particle_list[i][1] = 0.0245
if i == 5:
particle_list[i][1] = 0.0145
if i == 9:
particle_list[i][1] = 0.0145
if i == 10:
particle_list[i][1] = 0.0245
if i == 11:
particle_list[i][1] = 0.0145
particle_list = np.array(particle_list)
particle_x = particle_list[:, 0]
particle_z = particle_list[:, 1]
particle_y = particle_list[:, 2]
fig=plt.figure()
ax2 = Axes3D(fig)
ax2.scatter3D(particle_x,particle_y,particle_z, cmap='Blues')
ax2.plot3D(particle_x,particle_y,particle_z,'gray')
plt.show()
return particle_list | 38.352679 | 106 | 0.583867 |
import cv2
import time
import numpy as np
import os
import copy
import pickle
import random
import math
import matplotlib.pyplot as plt
from scipy import spatial
from skimage import morphology
from sklearn.mixture import GaussianMixture
from shapely.geometry import LineString, Point
from mpl_toolkits.mplot3d import Axes3D
class get_graph():
def __init__(self, raw_img):
self.raw_img = cv2.resize(raw_img, (512,512))
self.stride = 30
self.all_centroids = []
def get_binary(self):
gray_img = cv2.cvtColor(self.raw_img, cv2.COLOR_RGB2GRAY)
_, binary_img = cv2.threshold(gray_img, 100, 255, cv2.THRESH_BINARY_INV)
return binary_img
def ske2point(self):
skeleton_img = self.get_binary()
img_w, img_h = skeleton_img.shape
for i in range(img_w//self.stride):
for j in range(img_h//self.stride):
small_img = skeleton_img[i*self.stride:(i+1)*self.stride, j*self.stride:(j+1)*self.stride]
x_idx, y_idx = small_img.nonzero()
if len(x_idx) == 0:
continue
x_center, y_center = sum(x_idx) / len(x_idx) + i * self.stride,\
sum(y_idx) / len(x_idx) + j * self.stride
self.all_centroids.append(np.array([int(x_center), int(y_center)]))
self.all_centroids = np.array(self.all_centroids)
self.centroids_copy = copy.deepcopy(self.all_centroids)
def optimization(self, save_path=None):
noise_idx = []
binary_img = self.get_binary()
for i in range(len(self.all_centroids)):
if binary_img[int(self.all_centroids[i][0])][int(self.all_centroids[i][1])] == 0:
noise_idx.append(i)
self.all_centroids = np.delete(self.all_centroids, noise_idx, axis=0)
if save_path != None:
self.img_point_write(save_path, all_centroids, binary_img)
def visualization(self):
self.optimization()
plt.plot(self.all_centroids[:,0], self.all_centroids[:,1], 'bo', ms=5)
plt.show()
def graph(self, num_neigh_points = 10):
self.ske2point()
self.visualization()
tree = spatial.KDTree(self.all_centroids)
start_point = [500, 0]
neigh_points_idx, neigh_points = self.find_neigh_points(tree, start_point, 2)
next_point = neigh_points[0]
query_pair = [start_point, next_point]
point_order = query_pair
while True:
if len(self.all_centroids) < num_neigh_points:
break
if len(self.all_centroids) == 30:
break
tree = spatial.KDTree(self.all_centroids)
neigh_points_idx, neigh_points = self.find_neigh_points(tree, query_pair[1], num_neigh_points)
idx, next_point = self.find_path(query_pair, neigh_points)
if idx == -99:
print("end of construction...")
return point_order
query_pair = [query_pair[1], next_point]
point_order.append(next_point)
#pop out the walked point
self.all_centroids = self.all_centroids.tolist()
self.all_centroids.pop(neigh_points_idx[idx])
self.all_centroids = np.array(self.all_centroids)
print("remain lens of points: ", len(self.all_centroids))
return point_order
def find_neigh_points(self, tree, centroid, num_points):
dist, near_points_idx = tree.query(centroid, k=num_points)
near_points = self.all_centroids[near_points_idx]
return near_points_idx[1:], near_points[1:]
def find_path(self, query_pair, neigh_points):
v_query = query_pair[1] - query_pair[0]
next_point = np.zeros_like(query_pair[0])
angle_diff = np.pi
next_idx = -99
for i in range(len(neigh_points)):
v_compare = query_pair[1] - neigh_points[i]
#if the dist of all neigh_points is more than 65, break. This setting is for noise
if np.linalg.norm(v_compare) >70:
continue
#calculate the angle of two vectors
unit_v1 = v_query / np.linalg.norm(v_query)
unit_v2 = v_compare / np.linalg.norm(v_compare)
dot_product = np.dot(unit_v1, unit_v2)
angle = np.arccos(dot_product) #radian
if np.pi - angle < angle_diff:
next_point = neigh_points[i]
angle_diff = np.pi - angle
next_idx = i
return next_idx, next_point
def find_crossing(self, point_order, visual=False):
#create lines
pairs = []
crossing = []
for i in range(len(point_order)-1):
new_pair = np.array([point_order[i], point_order[i+1]])
pairs.append(new_pair)
for i in range(len(pairs)):
for j in range(len(pairs)-i):
intersec = self.intersection(pairs[i], pairs[j+i])
if intersec is not False:
crossing.append([intersec, pairs[i][0], pairs[j+i][0]])
if visual == True:
self.visualization_final_graph(point_order, crossing)
return crossing
#if no intersection, return False, else return the value of intersection
def intersection(self, pair1, pair2):
#if two pairs has a same point, break
if np.all(pair1[0]-pair2[0]==0) or np.all(pair1[1]-pair2[0]==0) \
or np.all(pair1[0]-pair2[1]==0) or np.all(pair1[1]-pair2[1]==0):
return False
line1 = LineString([pair1[0], pair1[1]])
line2 = LineString([pair2[0], pair2[1]])
intersection_point = line1.intersection(line2)
#no intersection
if intersection_point.is_empty:
return False
else:
return np.array([intersection_point.x, intersection_point.y])
def visualization_final_graph(self, point_order, crossing):
x, y = zip(*point_order)
plt.plot(x, y, '-o', zorder=1)
crossing = np.array(crossing)
c_x = crossing[:,0,0]
c_y = crossing[:,0,1]
plt.scatter(c_x, c_y, 20, 'r', zorder=2)
plt.show()
def trajectory(self, env, sa, point_order, crossing, stride):
picker_pos, particle_pos = sa.action_space.Picker._get_pos()
print(particle_pos)
particle_dist_2d = np.linalg.norm(particle_pos[0] - particle_pos[1])
init_particle = particle_pos[random.randint(0,len(particle_pos))].tolist()
particle_list = []
particle_list.append(init_particle)
for i in range(len(point_order)-stride):
if i % stride != 0:
continue
curr_particle = particle_list[i//stride]
y_o = point_order[i+stride][1] - point_order[i][1]
x_o = point_order[i+stride][0] - point_order[i][0]
orientation = abs(y_o / x_o)
theta = math.atan(orientation)
if x_o == 0:
x_o = 0.1
if y_o == 0:
y_o = 0.1
x = curr_particle[0] + math.cos(theta) * particle_dist_2d * x_o / abs(x_o)
y = curr_particle[2] + math.sin(theta) * particle_dist_2d * y_o / abs(y_o)
next_particle = [x, curr_particle[1], y, curr_particle[3]]
particle_list.append(next_particle)
for i in range(len(particle_list)):
if i == 3:
particle_list[i][1] = 0.0145
if i == 4:
particle_list[i][1] = 0.0245
if i == 5:
particle_list[i][1] = 0.0145
if i == 9:
particle_list[i][1] = 0.0145
if i == 10:
particle_list[i][1] = 0.0245
if i == 11:
particle_list[i][1] = 0.0145
particle_list = np.array(particle_list)
particle_x = particle_list[:, 0]
particle_z = particle_list[:, 1]
particle_y = particle_list[:, 2]
fig=plt.figure()
ax2 = Axes3D(fig)
ax2.scatter3D(particle_x,particle_y,particle_z, cmap='Blues')
ax2.plot3D(particle_x,particle_y,particle_z,'gray')
plt.show()
return particle_list | true | true |
f72b5999064274f48ed6073bf289ff75177ea60f | 4,247 | py | Python | tests/make_entry_test.py | asottile/pypi_practices | a4da562c471198dd35806c52016fac44bb46c08d | [
"MIT"
] | 3 | 2015-02-16T16:41:43.000Z | 2016-08-25T03:35:12.000Z | tests/make_entry_test.py | asottile/pypi_practices | a4da562c471198dd35806c52016fac44bb46c08d | [
"MIT"
] | 1 | 2017-08-15T04:02:30.000Z | 2017-08-15T04:02:30.000Z | tests/make_entry_test.py | asottile/pypi_practices | a4da562c471198dd35806c52016fac44bb46c08d | [
"MIT"
] | null | null | null | from __future__ import absolute_import
from __future__ import unicode_literals
import io
import mock
import os.path
import pytest
import sys
from pypi_practices import five
from pypi_practices.errors import FileValidationError
from pypi_practices.make_entry import make_entry
from testing.util import REMatcher
@pytest.fixture
def fake_entry():
class fake_entry_state(object):
cwd_arg = None
config_arg = None
entry = None
def check_fn(cwd, fix, config):
fake_entry_state.cwd_arg = cwd
fake_entry_state.fix_arg = fix
fake_entry_state.config_arg = config
return 0
fake_entry_state.entry = staticmethod(make_entry(check_fn))
yield fake_entry_state
def test_converts_args_to_text(fake_entry):
# Native str (py2 vs py3)
args = [str('--cwd'), str('path')]
fake_entry.entry(args)
assert type(fake_entry.cwd_arg) is five.text
assert fake_entry.cwd_arg == 'path'
def test_cwd_defaults_to_dot(fake_entry):
fake_entry.entry([])
assert fake_entry.cwd_arg == '.'
def test_fix_calls_fix(fake_entry):
fake_entry.entry(['--fix'])
assert fake_entry.fix_arg is True
def test_ignores_extra_filename_args(fake_entry):
fake_entry.entry(['README.md', 'tox.ini'])
assert fake_entry.cwd_arg == '.'
@pytest.mark.parametrize('args', ([], ['--fix']))
def test_returns_0_for_ok(fake_entry, args):
ret = fake_entry.entry(args)
assert ret == 0
def test_no_args_passed_uses_sys_argv(fake_entry):
with mock.patch.object(sys, 'argv', ['hook-exe', '--cwd', 'foo_cwd']):
fake_entry.entry()
assert fake_entry.cwd_arg == 'foo_cwd'
@pytest.fixture
def print_mock():
with mock.patch.object(five.builtins, 'print') as print_mock:
yield print_mock
def test_ok_prints_nothing(fake_entry, print_mock):
fake_entry.entry([])
assert print_mock.call_count == 0
def test_raises_validation_error(print_mock):
def raising_check(*_):
raise FileValidationError(
'README.md',
'Missing something.'
)
entry = make_entry(raising_check)
ret = entry([])
assert ret == 1
print_mock.assert_called_once_with(
'README.md: Missing something.\n'
'\n'
'Manually edit the file above to fix.'
)
def test_message_contains_line_if_specified(print_mock):
def raising_check_with_line_number(*_):
raise FileValidationError(
'README.md',
'Missing something.',
line=5,
)
entry = make_entry(raising_check_with_line_number)
ret = entry([])
assert ret == 1
print_mock.assert_called_once_with(
'README.md:5: Missing something.\n'
'\n'
'Manually edit the file above to fix.'
)
def test_auto_fixable_prints_auto_fixable(print_mock):
def raising_check_auto_fixable(*_):
raise FileValidationError(
'README.md',
'Missing something.',
is_auto_fixable=True,
)
entry = make_entry(raising_check_auto_fixable)
ret = entry([])
assert ret == 1
print_mock.assert_called_once_with(
'README.md: Missing something.\n'
'\n'
'To attempt automatic fixing, run with --fix.'
)
def test_passes_config(tmpdir, fake_entry):
config_path = os.path.join(tmpdir.strpath, '.pypi-practices-config.yaml')
with io.open(config_path, 'w') as config_file:
config_file.write('autofix: true')
ret = fake_entry.entry(['--cwd', tmpdir.strpath])
assert ret == 0
assert fake_entry.config_arg == {'autofix': True}
def test_failing_config(tmpdir, fake_entry, print_mock):
config_path = os.path.join(tmpdir.strpath, '.pypi-practices-config.yaml')
with io.open(config_path, 'w') as config_file:
config_file.write('foo: "')
ret = fake_entry.entry(['--cwd', tmpdir.strpath])
assert ret == 1
print_mock.assert_called_once_with(REMatcher(
r'.pypi-practices-config.yaml: Invalid Yaml:\n\n'
r'while scanning a quoted scalar\n'
r' in ".+\.pypi-practices-config.yaml", line 1, column 6\n'
r'found unexpected end of stream\n'
r' in ".+/.pypi-practices-config.yaml", line 1, column 7'
))
| 27.224359 | 77 | 0.669178 | from __future__ import absolute_import
from __future__ import unicode_literals
import io
import mock
import os.path
import pytest
import sys
from pypi_practices import five
from pypi_practices.errors import FileValidationError
from pypi_practices.make_entry import make_entry
from testing.util import REMatcher
@pytest.fixture
def fake_entry():
class fake_entry_state(object):
cwd_arg = None
config_arg = None
entry = None
def check_fn(cwd, fix, config):
fake_entry_state.cwd_arg = cwd
fake_entry_state.fix_arg = fix
fake_entry_state.config_arg = config
return 0
fake_entry_state.entry = staticmethod(make_entry(check_fn))
yield fake_entry_state
def test_converts_args_to_text(fake_entry):
args = [str('--cwd'), str('path')]
fake_entry.entry(args)
assert type(fake_entry.cwd_arg) is five.text
assert fake_entry.cwd_arg == 'path'
def test_cwd_defaults_to_dot(fake_entry):
fake_entry.entry([])
assert fake_entry.cwd_arg == '.'
def test_fix_calls_fix(fake_entry):
fake_entry.entry(['--fix'])
assert fake_entry.fix_arg is True
def test_ignores_extra_filename_args(fake_entry):
fake_entry.entry(['README.md', 'tox.ini'])
assert fake_entry.cwd_arg == '.'
@pytest.mark.parametrize('args', ([], ['--fix']))
def test_returns_0_for_ok(fake_entry, args):
ret = fake_entry.entry(args)
assert ret == 0
def test_no_args_passed_uses_sys_argv(fake_entry):
with mock.patch.object(sys, 'argv', ['hook-exe', '--cwd', 'foo_cwd']):
fake_entry.entry()
assert fake_entry.cwd_arg == 'foo_cwd'
@pytest.fixture
def print_mock():
with mock.patch.object(five.builtins, 'print') as print_mock:
yield print_mock
def test_ok_prints_nothing(fake_entry, print_mock):
fake_entry.entry([])
assert print_mock.call_count == 0
def test_raises_validation_error(print_mock):
def raising_check(*_):
raise FileValidationError(
'README.md',
'Missing something.'
)
entry = make_entry(raising_check)
ret = entry([])
assert ret == 1
print_mock.assert_called_once_with(
'README.md: Missing something.\n'
'\n'
'Manually edit the file above to fix.'
)
def test_message_contains_line_if_specified(print_mock):
def raising_check_with_line_number(*_):
raise FileValidationError(
'README.md',
'Missing something.',
line=5,
)
entry = make_entry(raising_check_with_line_number)
ret = entry([])
assert ret == 1
print_mock.assert_called_once_with(
'README.md:5: Missing something.\n'
'\n'
'Manually edit the file above to fix.'
)
def test_auto_fixable_prints_auto_fixable(print_mock):
def raising_check_auto_fixable(*_):
raise FileValidationError(
'README.md',
'Missing something.',
is_auto_fixable=True,
)
entry = make_entry(raising_check_auto_fixable)
ret = entry([])
assert ret == 1
print_mock.assert_called_once_with(
'README.md: Missing something.\n'
'\n'
'To attempt automatic fixing, run with --fix.'
)
def test_passes_config(tmpdir, fake_entry):
config_path = os.path.join(tmpdir.strpath, '.pypi-practices-config.yaml')
with io.open(config_path, 'w') as config_file:
config_file.write('autofix: true')
ret = fake_entry.entry(['--cwd', tmpdir.strpath])
assert ret == 0
assert fake_entry.config_arg == {'autofix': True}
def test_failing_config(tmpdir, fake_entry, print_mock):
config_path = os.path.join(tmpdir.strpath, '.pypi-practices-config.yaml')
with io.open(config_path, 'w') as config_file:
config_file.write('foo: "')
ret = fake_entry.entry(['--cwd', tmpdir.strpath])
assert ret == 1
print_mock.assert_called_once_with(REMatcher(
r'.pypi-practices-config.yaml: Invalid Yaml:\n\n'
r'while scanning a quoted scalar\n'
r' in ".+\.pypi-practices-config.yaml", line 1, column 6\n'
r'found unexpected end of stream\n'
r' in ".+/.pypi-practices-config.yaml", line 1, column 7'
))
| true | true |
f72b59e95919066e8f4ddff2339f880b70006b93 | 17,174 | py | Python | tests/test_coroutine_sink.py | phillipuniverse/loguru | 3d5234541c81318e7f6f725eca7bab294fe09c23 | [
"MIT"
] | 11,391 | 2018-12-08T17:44:13.000Z | 2022-03-31T17:55:24.000Z | tests/test_coroutine_sink.py | vkirilenko/loguru | 68616485f4f0decb5fced36a16040f5e05e2842f | [
"MIT"
] | 610 | 2018-12-08T18:03:03.000Z | 2022-03-31T22:28:14.000Z | tests/test_coroutine_sink.py | vkirilenko/loguru | 68616485f4f0decb5fced36a16040f5e05e2842f | [
"MIT"
] | 601 | 2018-12-08T17:46:42.000Z | 2022-03-30T04:23:56.000Z | import asyncio
import logging
import multiprocessing
import re
import sys
import threading
import pytest
import loguru
from loguru import logger
async def async_writer(msg):
await asyncio.sleep(0.01)
print(msg, end="")
class AsyncWriter:
async def __call__(self, msg):
await asyncio.sleep(0.01)
print(msg, end="")
def test_coroutine_function(capsys):
async def worker():
logger.debug("A message")
await logger.complete()
logger.add(async_writer, format="{message}")
asyncio.run(worker())
out, err = capsys.readouterr()
assert err == ""
assert out == "A message\n"
def test_async_callable_sink(capsys):
async def worker():
logger.debug("A message")
await logger.complete()
logger.add(AsyncWriter(), format="{message}")
asyncio.run(worker())
out, err = capsys.readouterr()
assert err == ""
assert out == "A message\n"
def test_concurrent_execution(capsys):
async def task(i):
logger.debug("=> {}", i)
async def main():
tasks = [task(i) for i in range(10)]
await asyncio.gather(*tasks)
await logger.complete()
logger.add(async_writer, format="{message}")
asyncio.run(main())
out, err = capsys.readouterr()
assert err == ""
assert sorted(out.splitlines()) == sorted("=> %d" % i for i in range(10))
def test_recursive_coroutine(capsys):
async def task(i):
if i == 0:
await logger.complete()
return
logger.info("{}!", i)
await task(i - 1)
logger.add(async_writer, format="{message}")
asyncio.run(task(9))
out, err = capsys.readouterr()
assert err == ""
assert sorted(out.splitlines()) == sorted("%d!" % i for i in range(1, 10))
@pytest.mark.skipif(sys.version_info < (3, 5, 3), reason="Coroutine can't access running loop")
def test_using_another_event_loop(capsys):
async def worker():
logger.debug("A message")
await logger.complete()
loop = asyncio.new_event_loop()
logger.add(async_writer, format="{message}", loop=loop)
loop.run_until_complete(worker())
out, err = capsys.readouterr()
assert err == ""
assert out == "A message\n"
def test_using_another_event_loop_set_global_before_add(capsys):
async def worker():
logger.debug("A message")
await logger.complete()
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
logger.add(async_writer, format="{message}", loop=loop)
loop.run_until_complete(worker())
out, err = capsys.readouterr()
assert err == ""
assert out == "A message\n"
def test_using_another_event_loop_set_global_after_add(capsys):
async def worker():
logger.debug("A message")
await logger.complete()
loop = asyncio.new_event_loop()
logger.add(async_writer, format="{message}", loop=loop)
asyncio.set_event_loop(loop)
loop.run_until_complete(worker())
out, err = capsys.readouterr()
assert err == ""
assert out == "A message\n"
def test_run_mutiple_different_loops(capsys):
async def worker(i):
logger.debug("Message {}", i)
await logger.complete()
logger.add(async_writer, format="{message}", loop=None)
asyncio.run(worker(1))
asyncio.run(worker(2))
out, err = capsys.readouterr()
assert err == ""
assert out == "Message 1\nMessage 2\n"
@pytest.mark.skipif(sys.version_info < (3, 5, 3), reason="Coroutine can't access running loop")
def test_run_multiple_same_loop(capsys):
async def worker(i):
logger.debug("Message {}", i)
await logger.complete()
loop = asyncio.new_event_loop()
logger.add(async_writer, format="{message}", loop=loop)
loop.run_until_complete(worker(1))
loop.run_until_complete(worker(2))
out, err = capsys.readouterr()
assert err == ""
assert out == "Message 1\nMessage 2\n"
def test_run_multiple_same_loop_set_global(capsys):
async def worker(i):
logger.debug("Message {}", i)
await logger.complete()
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
logger.add(async_writer, format="{message}", loop=loop)
loop.run_until_complete(worker(1))
loop.run_until_complete(worker(2))
out, err = capsys.readouterr()
assert err == ""
assert out == "Message 1\nMessage 2\n"
@pytest.mark.skipif(sys.version_info < (3, 5, 3), reason="Coroutine can't access running loop")
def test_complete_in_another_run(capsys):
async def worker_1():
logger.debug("A")
async def worker_2():
logger.debug("B")
await logger.complete()
loop = asyncio.new_event_loop()
logger.add(async_writer, format="{message}", loop=loop)
loop.run_until_complete(worker_1())
loop.run_until_complete(worker_2())
out, err = capsys.readouterr()
assert out == "A\nB\n"
assert err == ""
def test_complete_in_another_run_set_global(capsys):
async def worker_1():
logger.debug("A")
async def worker_2():
logger.debug("B")
await logger.complete()
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
logger.add(async_writer, format="{message}", loop=loop)
loop.run_until_complete(worker_1())
loop.run_until_complete(worker_2())
out, err = capsys.readouterr()
assert out == "A\nB\n"
assert err == ""
def test_tasks_cancelled_on_remove(capsys):
logger.add(async_writer, format="{message}", catch=False)
async def foo():
logger.info("A")
logger.info("B")
logger.info("C")
logger.remove()
await logger.complete()
asyncio.run(foo())
out, err = capsys.readouterr()
assert out == err == ""
def test_remove_without_tasks(capsys):
logger.add(async_writer, format="{message}", catch=False)
logger.remove()
async def foo():
logger.info("!")
await logger.complete()
asyncio.run(foo())
out, err = capsys.readouterr()
assert out == err == ""
def test_complete_without_tasks(capsys):
logger.add(async_writer, catch=False)
async def worker():
await logger.complete()
asyncio.run(worker())
out, err = capsys.readouterr()
assert out == err == ""
def test_complete_stream_noop(capsys):
logger.add(sys.stderr, format="{message}", catch=False)
logger.info("A")
async def worker():
logger.info("B")
await logger.complete()
logger.info("C")
asyncio.run(worker())
logger.info("D")
out, err = capsys.readouterr()
assert out == ""
assert err == "A\nB\nC\nD\n"
def test_complete_file_noop(tmpdir):
filepath = tmpdir.join("test.log")
logger.add(str(filepath), format="{message}", catch=False)
logger.info("A")
async def worker():
logger.info("B")
await logger.complete()
logger.info("C")
asyncio.run(worker())
logger.info("D")
assert filepath.read() == "A\nB\nC\nD\n"
def test_complete_function_noop():
out = ""
def write(msg):
nonlocal out
out += msg
logger.add(write, format="{message}", catch=False)
logger.info("A")
async def worker():
logger.info("B")
await logger.complete()
logger.info("C")
asyncio.run(worker())
logger.info("D")
assert out == "A\nB\nC\nD\n"
def test_complete_standard_noop(capsys):
logger.add(logging.StreamHandler(sys.stderr), format="{message}", catch=False)
logger.info("A")
async def worker():
logger.info("B")
await logger.complete()
logger.info("C")
asyncio.run(worker())
logger.info("D")
out, err = capsys.readouterr()
assert out == ""
assert err == "A\nB\nC\nD\n"
def test_exception_in_coroutine_caught(capsys):
async def sink(msg):
raise Exception("Oh no")
async def main():
logger.add(sink, catch=True)
logger.info("Hello world")
await asyncio.sleep(0.1)
await logger.complete()
asyncio.run(main())
out, err = capsys.readouterr()
lines = err.strip().splitlines()
assert out == ""
assert lines[0] == "--- Logging error in Loguru Handler #0 ---"
assert re.match(r"Record was: \{.*Hello world.*\}", lines[1])
assert lines[-2] == "Exception: Oh no"
assert lines[-1] == "--- End of logging error ---"
def test_exception_in_coroutine_not_caught(capsys, caplog):
async def sink(msg):
raise ValueError("Oh no")
async def main():
logger.add(sink, catch=False)
logger.info("Hello world")
await asyncio.sleep(0.1)
await logger.complete()
asyncio.run(main())
out, err = capsys.readouterr()
assert out == err == ""
records = caplog.records
assert len(records) == 1
record = records[0]
message = record.getMessage()
assert "Logging error in Loguru Handler" not in message
assert "was never retrieved" not in message
exc_type, exc_value, _ = record.exc_info
assert exc_type == ValueError
assert str(exc_value) == "Oh no"
def test_exception_in_coroutine_during_complete_caught(capsys):
async def sink(msg):
await asyncio.sleep(0.1)
raise Exception("Oh no")
async def main():
logger.add(sink, catch=True)
logger.info("Hello world")
await logger.complete()
asyncio.run(main())
out, err = capsys.readouterr()
lines = err.strip().splitlines()
assert out == ""
assert lines[0] == "--- Logging error in Loguru Handler #0 ---"
assert re.match(r"Record was: \{.*Hello world.*\}", lines[1])
assert lines[-2] == "Exception: Oh no"
assert lines[-1] == "--- End of logging error ---"
def test_exception_in_coroutine_during_complete_not_caught(capsys, caplog):
async def sink(msg):
await asyncio.sleep(0.1)
raise ValueError("Oh no")
async def main():
logger.add(sink, catch=False)
logger.info("Hello world")
await logger.complete()
asyncio.run(main())
out, err = capsys.readouterr()
assert out == err == ""
records = caplog.records
assert len(records) == 1
record = records[0]
message = record.getMessage()
assert "Logging error in Loguru Handler" not in message
assert "was never retrieved" not in message
exc_type, exc_value, _ = record.exc_info
assert exc_type == ValueError
assert str(exc_value) == "Oh no"
@pytest.mark.skipif(sys.version_info < (3, 5, 3), reason="Coroutine can't access running loop")
def test_enqueue_coroutine_loop_not_none(capsys):
loop = asyncio.new_event_loop()
logger.add(async_writer, enqueue=True, loop=loop, format="{message}", catch=False)
async def worker():
logger.info("A")
await logger.complete()
loop.run_until_complete(worker())
out, err = capsys.readouterr()
assert out == "A\n"
assert err == ""
def test_enqueue_coroutine_loop_not_none_set_global(capsys):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
logger.add(async_writer, enqueue=True, loop=loop, format="{message}", catch=False)
async def worker():
logger.info("A")
await logger.complete()
loop.run_until_complete(worker())
out, err = capsys.readouterr()
assert out == "A\n"
assert err == ""
@pytest.mark.skipif(sys.version_info < (3, 5, 3), reason="Coroutine can't access running loop")
def test_enqueue_coroutine_loop_is_none(capsys):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
logger.add(async_writer, enqueue=True, loop=None, format="{message}", catch=False)
async def worker(msg):
logger.info(msg)
await logger.complete()
asyncio.run(worker("A"))
out, err = capsys.readouterr()
assert out == err == ""
loop.run_until_complete(worker("B"))
out, err = capsys.readouterr()
assert out == "A\nB\n"
assert err == ""
def test_enqueue_coroutine_loop_is_none_set_global(capsys):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
logger.add(async_writer, enqueue=True, loop=None, format="{message}", catch=False)
async def worker(msg):
logger.info(msg)
await logger.complete()
loop.run_until_complete(worker("A"))
out, err = capsys.readouterr()
assert out == "A\n"
assert err == ""
def test_custom_complete_function(capsys):
awaited = False
class Handler:
def write(self, message):
print(message, end="")
async def complete(self):
nonlocal awaited
awaited = True
async def worker():
logger.info("A")
await logger.complete()
logger.add(Handler(), catch=False, format="{message}")
asyncio.run(worker())
out, err = capsys.readouterr()
assert out == "A\n"
assert err == ""
assert awaited
@pytest.mark.skipif(sys.version_info < (3, 5, 3), reason="Coroutine can't access running loop")
@pytest.mark.parametrize("loop_is_none", [True, False])
def test_complete_from_another_loop(capsys, loop_is_none):
main_loop = asyncio.new_event_loop()
second_loop = asyncio.new_event_loop()
loop = None if loop_is_none else main_loop
logger.add(async_writer, loop=loop, format="{message}")
async def worker_1():
logger.info("A")
async def worker_2():
await logger.complete()
main_loop.run_until_complete(worker_1())
second_loop.run_until_complete(worker_2())
out, err = capsys.readouterr()
assert out == err == ""
main_loop.run_until_complete(worker_2())
out, err = capsys.readouterr()
assert out == "A\n"
assert err == ""
@pytest.mark.parametrize("loop_is_none", [True, False])
def test_complete_from_another_loop_set_global(capsys, loop_is_none):
main_loop = asyncio.new_event_loop()
second_loop = asyncio.new_event_loop()
loop = None if loop_is_none else main_loop
logger.add(async_writer, loop=loop, format="{message}")
async def worker_1():
logger.info("A")
async def worker_2():
await logger.complete()
asyncio.set_event_loop(main_loop)
main_loop.run_until_complete(worker_1())
asyncio.set_event_loop(second_loop)
second_loop.run_until_complete(worker_2())
out, err = capsys.readouterr()
assert out == err == ""
asyncio.set_event_loop(main_loop)
main_loop.run_until_complete(worker_2())
out, err = capsys.readouterr()
assert out == "A\n"
assert err == ""
def test_complete_from_multiple_threads_loop_is_none(capsys):
async def worker(i):
for j in range(100):
await asyncio.sleep(0)
logger.info("{:03}", i)
await logger.complete()
async def sink(msg):
print(msg, end="")
def worker_(i):
asyncio.run(worker(i))
logger.add(sink, catch=False, format="{message}")
threads = [threading.Thread(target=worker_, args=(i,)) for i in range(10)]
for t in threads:
t.start()
for t in threads:
t.join()
out, err = capsys.readouterr()
assert sorted(out.splitlines()) == ["{:03}".format(i) for i in range(10) for _ in range(100)]
assert err == ""
def test_complete_from_multiple_threads_loop_is_not_none(capsys):
async def worker(i):
for j in range(100):
await asyncio.sleep(0)
logger.info("{:03}", i)
await logger.complete()
async def sink(msg):
print(msg, end="")
def worker_(i):
asyncio.run(worker(i))
loop = asyncio.new_event_loop()
logger.add(sink, catch=False, format="{message}", loop=loop)
threads = [threading.Thread(target=worker_, args=(i,)) for i in range(10)]
for t in threads:
t.start()
for t in threads:
t.join()
async def complete():
await logger.complete()
loop.run_until_complete(complete())
out, err = capsys.readouterr()
assert sorted(out.splitlines()) == ["{:03}".format(i) for i in range(10) for _ in range(100)]
assert err == ""
async def async_subworker(logger_):
logger_.info("Child")
await logger_.complete()
async def async_mainworker(logger_):
logger_.info("Main")
await logger_.complete()
def subworker(logger_):
loop = asyncio.get_event_loop()
loop.run_until_complete(async_subworker(logger_))
class Writer:
def __init__(self):
self.output = ""
async def write(self, message):
self.output += message
def test_complete_with_sub_processes(monkeypatch, capsys):
ctx = multiprocessing.get_context("spawn")
monkeypatch.setattr(loguru._handler, "multiprocessing", ctx)
loop = asyncio.new_event_loop()
writer = Writer()
logger.add(writer.write, format="{message}", enqueue=True, loop=loop)
process = ctx.Process(target=subworker, args=[logger])
process.start()
process.join()
async def complete():
await logger.complete()
loop.run_until_complete(complete())
out, err = capsys.readouterr()
assert out == err == ""
assert writer.output == "Child\n"
| 24.120787 | 97 | 0.638116 | import asyncio
import logging
import multiprocessing
import re
import sys
import threading
import pytest
import loguru
from loguru import logger
async def async_writer(msg):
await asyncio.sleep(0.01)
print(msg, end="")
class AsyncWriter:
async def __call__(self, msg):
await asyncio.sleep(0.01)
print(msg, end="")
def test_coroutine_function(capsys):
async def worker():
logger.debug("A message")
await logger.complete()
logger.add(async_writer, format="{message}")
asyncio.run(worker())
out, err = capsys.readouterr()
assert err == ""
assert out == "A message\n"
def test_async_callable_sink(capsys):
async def worker():
logger.debug("A message")
await logger.complete()
logger.add(AsyncWriter(), format="{message}")
asyncio.run(worker())
out, err = capsys.readouterr()
assert err == ""
assert out == "A message\n"
def test_concurrent_execution(capsys):
async def task(i):
logger.debug("=> {}", i)
async def main():
tasks = [task(i) for i in range(10)]
await asyncio.gather(*tasks)
await logger.complete()
logger.add(async_writer, format="{message}")
asyncio.run(main())
out, err = capsys.readouterr()
assert err == ""
assert sorted(out.splitlines()) == sorted("=> %d" % i for i in range(10))
def test_recursive_coroutine(capsys):
async def task(i):
if i == 0:
await logger.complete()
return
logger.info("{}!", i)
await task(i - 1)
logger.add(async_writer, format="{message}")
asyncio.run(task(9))
out, err = capsys.readouterr()
assert err == ""
assert sorted(out.splitlines()) == sorted("%d!" % i for i in range(1, 10))
@pytest.mark.skipif(sys.version_info < (3, 5, 3), reason="Coroutine can't access running loop")
def test_using_another_event_loop(capsys):
async def worker():
logger.debug("A message")
await logger.complete()
loop = asyncio.new_event_loop()
logger.add(async_writer, format="{message}", loop=loop)
loop.run_until_complete(worker())
out, err = capsys.readouterr()
assert err == ""
assert out == "A message\n"
def test_using_another_event_loop_set_global_before_add(capsys):
async def worker():
logger.debug("A message")
await logger.complete()
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
logger.add(async_writer, format="{message}", loop=loop)
loop.run_until_complete(worker())
out, err = capsys.readouterr()
assert err == ""
assert out == "A message\n"
def test_using_another_event_loop_set_global_after_add(capsys):
async def worker():
logger.debug("A message")
await logger.complete()
loop = asyncio.new_event_loop()
logger.add(async_writer, format="{message}", loop=loop)
asyncio.set_event_loop(loop)
loop.run_until_complete(worker())
out, err = capsys.readouterr()
assert err == ""
assert out == "A message\n"
def test_run_mutiple_different_loops(capsys):
async def worker(i):
logger.debug("Message {}", i)
await logger.complete()
logger.add(async_writer, format="{message}", loop=None)
asyncio.run(worker(1))
asyncio.run(worker(2))
out, err = capsys.readouterr()
assert err == ""
assert out == "Message 1\nMessage 2\n"
@pytest.mark.skipif(sys.version_info < (3, 5, 3), reason="Coroutine can't access running loop")
def test_run_multiple_same_loop(capsys):
async def worker(i):
logger.debug("Message {}", i)
await logger.complete()
loop = asyncio.new_event_loop()
logger.add(async_writer, format="{message}", loop=loop)
loop.run_until_complete(worker(1))
loop.run_until_complete(worker(2))
out, err = capsys.readouterr()
assert err == ""
assert out == "Message 1\nMessage 2\n"
def test_run_multiple_same_loop_set_global(capsys):
async def worker(i):
logger.debug("Message {}", i)
await logger.complete()
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
logger.add(async_writer, format="{message}", loop=loop)
loop.run_until_complete(worker(1))
loop.run_until_complete(worker(2))
out, err = capsys.readouterr()
assert err == ""
assert out == "Message 1\nMessage 2\n"
@pytest.mark.skipif(sys.version_info < (3, 5, 3), reason="Coroutine can't access running loop")
def test_complete_in_another_run(capsys):
async def worker_1():
logger.debug("A")
async def worker_2():
logger.debug("B")
await logger.complete()
loop = asyncio.new_event_loop()
logger.add(async_writer, format="{message}", loop=loop)
loop.run_until_complete(worker_1())
loop.run_until_complete(worker_2())
out, err = capsys.readouterr()
assert out == "A\nB\n"
assert err == ""
def test_complete_in_another_run_set_global(capsys):
async def worker_1():
logger.debug("A")
async def worker_2():
logger.debug("B")
await logger.complete()
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
logger.add(async_writer, format="{message}", loop=loop)
loop.run_until_complete(worker_1())
loop.run_until_complete(worker_2())
out, err = capsys.readouterr()
assert out == "A\nB\n"
assert err == ""
def test_tasks_cancelled_on_remove(capsys):
logger.add(async_writer, format="{message}", catch=False)
async def foo():
logger.info("A")
logger.info("B")
logger.info("C")
logger.remove()
await logger.complete()
asyncio.run(foo())
out, err = capsys.readouterr()
assert out == err == ""
def test_remove_without_tasks(capsys):
logger.add(async_writer, format="{message}", catch=False)
logger.remove()
async def foo():
logger.info("!")
await logger.complete()
asyncio.run(foo())
out, err = capsys.readouterr()
assert out == err == ""
def test_complete_without_tasks(capsys):
logger.add(async_writer, catch=False)
async def worker():
await logger.complete()
asyncio.run(worker())
out, err = capsys.readouterr()
assert out == err == ""
def test_complete_stream_noop(capsys):
logger.add(sys.stderr, format="{message}", catch=False)
logger.info("A")
async def worker():
logger.info("B")
await logger.complete()
logger.info("C")
asyncio.run(worker())
logger.info("D")
out, err = capsys.readouterr()
assert out == ""
assert err == "A\nB\nC\nD\n"
def test_complete_file_noop(tmpdir):
filepath = tmpdir.join("test.log")
logger.add(str(filepath), format="{message}", catch=False)
logger.info("A")
async def worker():
logger.info("B")
await logger.complete()
logger.info("C")
asyncio.run(worker())
logger.info("D")
assert filepath.read() == "A\nB\nC\nD\n"
def test_complete_function_noop():
out = ""
def write(msg):
nonlocal out
out += msg
logger.add(write, format="{message}", catch=False)
logger.info("A")
async def worker():
logger.info("B")
await logger.complete()
logger.info("C")
asyncio.run(worker())
logger.info("D")
assert out == "A\nB\nC\nD\n"
def test_complete_standard_noop(capsys):
logger.add(logging.StreamHandler(sys.stderr), format="{message}", catch=False)
logger.info("A")
async def worker():
logger.info("B")
await logger.complete()
logger.info("C")
asyncio.run(worker())
logger.info("D")
out, err = capsys.readouterr()
assert out == ""
assert err == "A\nB\nC\nD\n"
def test_exception_in_coroutine_caught(capsys):
async def sink(msg):
raise Exception("Oh no")
async def main():
logger.add(sink, catch=True)
logger.info("Hello world")
await asyncio.sleep(0.1)
await logger.complete()
asyncio.run(main())
out, err = capsys.readouterr()
lines = err.strip().splitlines()
assert out == ""
assert lines[0] == "--- Logging error in Loguru Handler #0 ---"
assert re.match(r"Record was: \{.*Hello world.*\}", lines[1])
assert lines[-2] == "Exception: Oh no"
assert lines[-1] == "--- End of logging error ---"
def test_exception_in_coroutine_not_caught(capsys, caplog):
async def sink(msg):
raise ValueError("Oh no")
async def main():
logger.add(sink, catch=False)
logger.info("Hello world")
await asyncio.sleep(0.1)
await logger.complete()
asyncio.run(main())
out, err = capsys.readouterr()
assert out == err == ""
records = caplog.records
assert len(records) == 1
record = records[0]
message = record.getMessage()
assert "Logging error in Loguru Handler" not in message
assert "was never retrieved" not in message
exc_type, exc_value, _ = record.exc_info
assert exc_type == ValueError
assert str(exc_value) == "Oh no"
def test_exception_in_coroutine_during_complete_caught(capsys):
async def sink(msg):
await asyncio.sleep(0.1)
raise Exception("Oh no")
async def main():
logger.add(sink, catch=True)
logger.info("Hello world")
await logger.complete()
asyncio.run(main())
out, err = capsys.readouterr()
lines = err.strip().splitlines()
assert out == ""
assert lines[0] == "--- Logging error in Loguru Handler #0 ---"
assert re.match(r"Record was: \{.*Hello world.*\}", lines[1])
assert lines[-2] == "Exception: Oh no"
assert lines[-1] == "--- End of logging error ---"
def test_exception_in_coroutine_during_complete_not_caught(capsys, caplog):
async def sink(msg):
await asyncio.sleep(0.1)
raise ValueError("Oh no")
async def main():
logger.add(sink, catch=False)
logger.info("Hello world")
await logger.complete()
asyncio.run(main())
out, err = capsys.readouterr()
assert out == err == ""
records = caplog.records
assert len(records) == 1
record = records[0]
message = record.getMessage()
assert "Logging error in Loguru Handler" not in message
assert "was never retrieved" not in message
exc_type, exc_value, _ = record.exc_info
assert exc_type == ValueError
assert str(exc_value) == "Oh no"
@pytest.mark.skipif(sys.version_info < (3, 5, 3), reason="Coroutine can't access running loop")
def test_enqueue_coroutine_loop_not_none(capsys):
loop = asyncio.new_event_loop()
logger.add(async_writer, enqueue=True, loop=loop, format="{message}", catch=False)
async def worker():
logger.info("A")
await logger.complete()
loop.run_until_complete(worker())
out, err = capsys.readouterr()
assert out == "A\n"
assert err == ""
def test_enqueue_coroutine_loop_not_none_set_global(capsys):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
logger.add(async_writer, enqueue=True, loop=loop, format="{message}", catch=False)
async def worker():
logger.info("A")
await logger.complete()
loop.run_until_complete(worker())
out, err = capsys.readouterr()
assert out == "A\n"
assert err == ""
@pytest.mark.skipif(sys.version_info < (3, 5, 3), reason="Coroutine can't access running loop")
def test_enqueue_coroutine_loop_is_none(capsys):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
logger.add(async_writer, enqueue=True, loop=None, format="{message}", catch=False)
async def worker(msg):
logger.info(msg)
await logger.complete()
asyncio.run(worker("A"))
out, err = capsys.readouterr()
assert out == err == ""
loop.run_until_complete(worker("B"))
out, err = capsys.readouterr()
assert out == "A\nB\n"
assert err == ""
def test_enqueue_coroutine_loop_is_none_set_global(capsys):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
logger.add(async_writer, enqueue=True, loop=None, format="{message}", catch=False)
async def worker(msg):
logger.info(msg)
await logger.complete()
loop.run_until_complete(worker("A"))
out, err = capsys.readouterr()
assert out == "A\n"
assert err == ""
def test_custom_complete_function(capsys):
awaited = False
class Handler:
def write(self, message):
print(message, end="")
async def complete(self):
nonlocal awaited
awaited = True
async def worker():
logger.info("A")
await logger.complete()
logger.add(Handler(), catch=False, format="{message}")
asyncio.run(worker())
out, err = capsys.readouterr()
assert out == "A\n"
assert err == ""
assert awaited
@pytest.mark.skipif(sys.version_info < (3, 5, 3), reason="Coroutine can't access running loop")
@pytest.mark.parametrize("loop_is_none", [True, False])
def test_complete_from_another_loop(capsys, loop_is_none):
main_loop = asyncio.new_event_loop()
second_loop = asyncio.new_event_loop()
loop = None if loop_is_none else main_loop
logger.add(async_writer, loop=loop, format="{message}")
async def worker_1():
logger.info("A")
async def worker_2():
await logger.complete()
main_loop.run_until_complete(worker_1())
second_loop.run_until_complete(worker_2())
out, err = capsys.readouterr()
assert out == err == ""
main_loop.run_until_complete(worker_2())
out, err = capsys.readouterr()
assert out == "A\n"
assert err == ""
@pytest.mark.parametrize("loop_is_none", [True, False])
def test_complete_from_another_loop_set_global(capsys, loop_is_none):
main_loop = asyncio.new_event_loop()
second_loop = asyncio.new_event_loop()
loop = None if loop_is_none else main_loop
logger.add(async_writer, loop=loop, format="{message}")
async def worker_1():
logger.info("A")
async def worker_2():
await logger.complete()
asyncio.set_event_loop(main_loop)
main_loop.run_until_complete(worker_1())
asyncio.set_event_loop(second_loop)
second_loop.run_until_complete(worker_2())
out, err = capsys.readouterr()
assert out == err == ""
asyncio.set_event_loop(main_loop)
main_loop.run_until_complete(worker_2())
out, err = capsys.readouterr()
assert out == "A\n"
assert err == ""
def test_complete_from_multiple_threads_loop_is_none(capsys):
async def worker(i):
for j in range(100):
await asyncio.sleep(0)
logger.info("{:03}", i)
await logger.complete()
async def sink(msg):
print(msg, end="")
def worker_(i):
asyncio.run(worker(i))
logger.add(sink, catch=False, format="{message}")
threads = [threading.Thread(target=worker_, args=(i,)) for i in range(10)]
for t in threads:
t.start()
for t in threads:
t.join()
out, err = capsys.readouterr()
assert sorted(out.splitlines()) == ["{:03}".format(i) for i in range(10) for _ in range(100)]
assert err == ""
def test_complete_from_multiple_threads_loop_is_not_none(capsys):
async def worker(i):
for j in range(100):
await asyncio.sleep(0)
logger.info("{:03}", i)
await logger.complete()
async def sink(msg):
print(msg, end="")
def worker_(i):
asyncio.run(worker(i))
loop = asyncio.new_event_loop()
logger.add(sink, catch=False, format="{message}", loop=loop)
threads = [threading.Thread(target=worker_, args=(i,)) for i in range(10)]
for t in threads:
t.start()
for t in threads:
t.join()
async def complete():
await logger.complete()
loop.run_until_complete(complete())
out, err = capsys.readouterr()
assert sorted(out.splitlines()) == ["{:03}".format(i) for i in range(10) for _ in range(100)]
assert err == ""
async def async_subworker(logger_):
logger_.info("Child")
await logger_.complete()
async def async_mainworker(logger_):
logger_.info("Main")
await logger_.complete()
def subworker(logger_):
loop = asyncio.get_event_loop()
loop.run_until_complete(async_subworker(logger_))
class Writer:
def __init__(self):
self.output = ""
async def write(self, message):
self.output += message
def test_complete_with_sub_processes(monkeypatch, capsys):
ctx = multiprocessing.get_context("spawn")
monkeypatch.setattr(loguru._handler, "multiprocessing", ctx)
loop = asyncio.new_event_loop()
writer = Writer()
logger.add(writer.write, format="{message}", enqueue=True, loop=loop)
process = ctx.Process(target=subworker, args=[logger])
process.start()
process.join()
async def complete():
await logger.complete()
loop.run_until_complete(complete())
out, err = capsys.readouterr()
assert out == err == ""
assert writer.output == "Child\n"
| true | true |
f72b5a37ff02745e8949ae1f82a9e2a4b599b954 | 20,351 | py | Python | datagen.py | HotaekHan/FCOS | 8e3a0438cf1a53f8916d21ea81d892b260c100a9 | [
"Apache-2.0"
] | null | null | null | datagen.py | HotaekHan/FCOS | 8e3a0438cf1a53f8916d21ea81d892b260c100a9 | [
"Apache-2.0"
] | null | null | null | datagen.py | HotaekHan/FCOS | 8e3a0438cf1a53f8916d21ea81d892b260c100a9 | [
"Apache-2.0"
] | null | null | null | '''Load image/labels/boxes from an annotation file.
The list file is like:
img.jpg width height xmin ymin xmax ymax label xmin ymin xmax ymax label ...
'''
import random
import numpy as np
import json
import os
# from PIL import Image, ImageDraw, ImageFile
# ImageFile.LOAD_TRUNCATED_IMAGES = True
import cv2
import torch
import torch.utils.data as data
import torchvision.transforms as transforms
from encoder import DataEncoder
class jsonDataset(data.Dataset):
def __init__(self, path, classes, transform, input_image_size, num_crops, fpn_level, is_norm_reg_target, radius,
view_image=False, min_cols=1, min_rows=1):
'''
Args:
root: (str) ditectory to images.
list_file: (str) path to index file.
train: (boolean) train or test.
transform: ([transforms]) image transforms.
input_size: (int) image shorter side size.
max_size: (int) maximum image longer side size.
'''
self.path = path
self.classes = classes
self.transform = transform
self.input_size = input_image_size
self.num_crops = num_crops
self.view_img = view_image
self.fpn_level = fpn_level
self.is_norm_reg_target = is_norm_reg_target
self.radius = radius
self.fnames = list()
self.offsets = list()
self.boxes = list()
self.labels = list()
self.num_classes = len(self.classes)
self.label_map = dict()
self.class_idx_map = dict()
# 0 is background class
for idx in range(0, self.num_classes):
self.label_map[self.classes[idx]] = idx+1 # 0 is background
self.class_idx_map[idx+1] = self.classes[idx]
self.data_encoder = DataEncoder(image_size=self.input_size,
num_classes=self.num_classes + 1,
fpn_level=self.fpn_level,
is_norm_reg_target=self.is_norm_reg_target)
fp_read = open(self.path, 'r')
gt_dict = json.load(fp_read)
all_boxes = list()
all_labels = list()
all_img_path = list()
# read gt files
for gt_key in gt_dict:
gt_data = gt_dict[gt_key][0]
box = list()
label = list()
num_boxes = len(gt_data['labels'])
img = cv2.imread(gt_data['image_path'])
img_rows = img.shape[0]
img_cols = img.shape[1]
for iter_box in range(0, num_boxes):
xmin = gt_data['boxes'][iter_box][0]
ymin = gt_data['boxes'][iter_box][1]
xmax = gt_data['boxes'][iter_box][2]
ymax = gt_data['boxes'][iter_box][3]
rows = ymax - ymin
cols = xmax - xmin
if xmin < 0 or ymin < 0:
print('negative coordinate: [xmin: ' + str(xmin) + ', ymin: ' + str(ymin) + ']')
print(gt_data['image_path'])
continue
if xmax > img_cols or ymax > img_rows:
print('over maximum size: [xmax: ' + str(xmax) + ', ymax: ' + str(ymax) + ']')
print(gt_data['image_path'])
continue
if cols < min_cols:
print('cols is lower than ' + str(min_cols) + ': [' + str(xmin) + ', ' + str(ymin) + ', ' +
str(xmax) + ', ' + str(ymax) + '] '
+ str(gt_data['image_path']))
continue
if rows < min_rows:
print('rows is lower than ' + str(min_rows) + ': [' + str(xmin) + ', ' + str(ymin) + ', ' +
str(xmax) + ', ' + str(ymax) + '] '
+ str(gt_data['image_path']))
continue
class_name = gt_data['labels'][iter_box][0]
if class_name not in self.label_map:
print('weired class name: ' + class_name)
print(gt_data['image_path'])
continue
class_idx = self.label_map[class_name]
box.append([float(xmin), float(ymin), float(xmax), float(ymax)])
label.append(int(class_idx))
if len(box) == 0 or len(label) == 0:
print('none of object exist in the image: ' + gt_data['image_path'])
continue
all_boxes.append(box)
all_labels.append(label)
all_img_path.append(gt_data['image_path'])
if len(all_boxes) == len(all_labels) and len(all_boxes) == len(all_img_path):
num_images = len(all_img_path)
else:
print('num. of boxes: ' + str(len(all_boxes)))
print('num. of labels: ' + str(len(all_labels)))
print('num. of paths: ' + str(len(all_img_path)))
raise ValueError('num. of elements are different(all boxes, all_labels, all_img_path)')
if num_crops <= 0:
for idx in range(0, num_images, 1):
self.fnames.append(all_img_path[idx])
self.boxes.append(torch.tensor(all_boxes[idx], dtype=torch.float32))
self.labels.append(torch.tensor(all_labels[idx], dtype=torch.int64))
else:
for idx in range(0, num_images, 1):
ori_boxes = all_boxes[idx]
ori_labels = all_labels[idx]
ori_img = cv2.imread(all_img_path[idx])
img_rows = ori_img.shape[0]
img_cols = ori_img.shape[1]
offsets, crop_boxes, crop_labels = self._do_crop(ori_img_rows=img_rows, ori_img_cols=img_cols,
target_img_size=self.input_size,
boxes=ori_boxes, labels=ori_labels)
num_offsets = len(offsets)
for idx_offset in range(0, num_offsets, 1):
self.fnames.append(all_img_path[idx])
self.offsets.append(offsets[idx_offset])
self.boxes.append(torch.tensor(crop_boxes[idx_offset], dtype=torch.float32))
self.labels.append(torch.tensor(crop_labels[idx_offset], dtype=torch.int64))
self.num_samples = len(self.fnames)
def __getitem__(self, idx):
# Load image and boxes.
fname = self.fnames[idx]
boxes = self.boxes[idx]
labels = self.labels[idx]
img = cv2.imread(fname)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
if self.num_crops > 0:
offset = self.offsets[idx]
crop_rect = (int(offset[0]), int(offset[1]),
int(offset[0]+self.input_size[1]), int(offset[1]+self.input_size[0]))
if offset[0] < 0 or offset[1] < 0:
raise ValueError("negative offset!")
for box in boxes:
if box[0] < 0 or box[1] < 0 or box[2] > self.input_size[1] or box[3] > self.input_size[0]:
raise ValueError("negative box coordinate!")
img = img[crop_rect[1]:crop_rect[3], crop_rect[0]:crop_rect[2]]
bboxes = [bbox.tolist() + [label.item()] for bbox, label in zip(boxes, labels)]
augmented = self.transform(image=img, bboxes=bboxes)
img = augmented['image']
rows, cols = img.shape[1:]
boxes = augmented['bboxes']
boxes = [list(bbox) for bbox in boxes]
labels = [bbox.pop() for bbox in boxes]
if self.view_img is True:
np_img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
np_img = np_img.numpy()
np_img = np.transpose(np_img, (1, 2, 0))
np_img = np.uint8(np_img * 255)
np_img = np.ascontiguousarray(np_img)
for idx_box, box in enumerate(boxes):
cv2.rectangle(np_img, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])), (0, 255, 0))
class_idx = labels[idx_box]
text_size = cv2.getTextSize(self.class_idx_map[class_idx], cv2.FONT_HERSHEY_PLAIN, 1, 1)
cv2.putText(np_img, self.class_idx_map[class_idx], (int(box[0]), int(box[1]) - text_size[1]), cv2.FONT_HERSHEY_PLAIN, 1, (255, 255, 255), 1)
cv2.imwrite(os.path.join("crop_test", str(idx)+".jpg"), np_img)
boxes = torch.tensor(boxes, dtype=torch.float32)
labels = torch.tensor(labels, dtype=torch.int64)
return img, boxes, labels, fname
def __len__(self):
return self.num_samples
# def _resize(self, img, boxes):
# if isinstance(self.input_size, int) is True:
# w = h = self.input_size
# elif isinstance(self.input_size, tuple) is True:
# h = self.input_size[0]
# w = self.input_size[1]
# else:
# raise ValueError('input size should be int or tuple of ints')
#
# ws = 1.0 * w / img.shape[1]
# hs = 1.0 * h / img.shape[0]
# scale = torch.tensor([ws, hs, ws, hs], dtype=torch.float32)
# if boxes.numel() == 0:
# scaled_box = boxes
# else:
# scaled_box = scale * boxes
# return cv2.resize(img, (w, h)), scaled_box
def _do_crop(self, ori_img_rows, ori_img_cols, target_img_size, boxes, labels):
num_boxes = len(boxes)
num_labels = len(labels)
if num_boxes != num_labels:
print("error occur: Random crop")
rand_indices = [0, 1, 2, 3, 4]
np.random.shuffle(rand_indices)
output_offsets = []
output_boxes = []
output_labels = []
for box in boxes:
# box coordinate from 1. not 0.
xmin = box[0]
ymin = box[1]
xmax = box[2]
ymax = box[3]
width = (xmax - xmin)+1
height = (ymax - ymin)+1
if width < 0 or height< 0:
print("negative width/height")
continue
for iter_crop in range(0, self.num_crops, 1):
rand_idx = rand_indices[iter_crop]
margin = np.random.randint(16, 128, size=1)
# top-left
if rand_idx == 0:
offset_x = xmin-1-margin[0]
offset_y = ymin-1-margin[0]
crop_maxx = offset_x + target_img_size[1]
crop_maxy = offset_y + target_img_size[0]
if crop_maxx > ori_img_cols-1 or crop_maxy > ori_img_rows-1:
continue
if offset_x < 0 or offset_y < 0:
continue
crop_rect = [offset_x, offset_y, target_img_size[1], target_img_size[0]]
in_boxes, in_labels = self._find_boxes_in_crop(crop_rect, boxes, labels)
if len(in_boxes) == 0:
continue
output_offsets.append([offset_x, offset_y])
output_boxes.append(in_boxes)
output_labels.append(in_labels)
# top-right
elif rand_idx == 1:
offset_x = xmin - (target_img_size[1] - width)-1+margin[0]
offset_y = ymin-1-margin[0]
crop_maxx = offset_x + target_img_size[1]
crop_maxy = offset_y + target_img_size[0]
if crop_maxx > ori_img_cols-1 or crop_maxy > ori_img_rows-1:
continue
if offset_x < 0 or offset_y < 0:
continue
crop_rect = [offset_x, offset_y, target_img_size[1], target_img_size[0]]
in_boxes, in_labels = self._find_boxes_in_crop(crop_rect, boxes, labels)
if len(in_boxes) == 0:
continue
output_offsets.append([offset_x, offset_y])
output_boxes.append(in_boxes)
output_labels.append(in_labels)
# bottom-left
elif rand_idx == 2:
offset_x = xmin-1-margin[0]
offset_y = ymin - (target_img_size[0] - height)-1+margin[0]
crop_maxx = offset_x + target_img_size[1]
crop_maxy = offset_y + target_img_size[0]
if crop_maxx > ori_img_cols-1 or crop_maxy > ori_img_rows-1:
continue
if offset_x < 0 or offset_y < 0:
continue
crop_rect = [offset_x, offset_y, target_img_size[1], target_img_size[0]]
in_boxes, in_labels = self._find_boxes_in_crop(crop_rect, boxes, labels)
if len(in_boxes) == 0:
continue
output_offsets.append([offset_x, offset_y])
output_boxes.append(in_boxes)
output_labels.append(in_labels)
# bottom-right
elif rand_idx == 3:
offset_x = xmin - (target_img_size[1] - width)-1+margin[0]
offset_y = ymin - (target_img_size[0] - height)-1+margin[0]
crop_maxx = offset_x + target_img_size[1]
crop_maxy = offset_y + target_img_size[0]
if crop_maxx > ori_img_cols-1 or crop_maxy > ori_img_rows-1:
continue
if offset_x < 0 or offset_y < 0:
continue
crop_rect = [offset_x, offset_y, target_img_size[1], target_img_size[0]]
in_boxes, in_labels = self._find_boxes_in_crop(crop_rect, boxes, labels)
if len(in_boxes) == 0:
continue
output_offsets.append([offset_x, offset_y])
output_boxes.append(in_boxes)
output_labels.append(in_labels)
# center
elif rand_idx == 4:
rand_direction = np.random.randint(-1, 1, size=1)
offset_x = (xmin - ((target_img_size[1]-width)/2)-1) + (rand_direction[0] * margin[0])
offset_y = (ymin - ((target_img_size[0]-height)/2)-1) + (rand_direction[0] * margin[0])
crop_maxx = offset_x + target_img_size[1]
crop_maxy = offset_y + target_img_size[0]
if crop_maxx > ori_img_cols-1 or crop_maxy > ori_img_rows-1:
continue
if offset_x < 0 or offset_y < 0:
continue
crop_rect = [offset_x, offset_y, target_img_size[1], target_img_size[0]]
in_boxes, in_labels = self._find_boxes_in_crop(crop_rect, boxes, labels)
if len(in_boxes) == 0:
continue
output_offsets.append([offset_x, offset_y])
output_boxes.append(in_boxes)
output_labels.append(in_labels)
else:
print("exceed possible crop num")
return output_offsets, output_boxes, output_labels
def _find_boxes_in_crop(self, crop_rect, boxes, labels):
num_boxes = len(boxes)
num_labels = len(labels)
if num_boxes != num_labels:
print("error occur: Random crop")
boxes_in_crop=[]
labels_in_crop = []
for idx in range(0, num_boxes, 1):
box_in_crop, label, is_contain = self._find_box_in_crop(crop_rect, boxes[idx], labels[idx])
if is_contain is True:
boxes_in_crop.append(box_in_crop)
labels_in_crop.append(label)
return boxes_in_crop, labels_in_crop
def _find_box_in_crop(self, rect, box, label):
rect_minx = rect[0]
rect_miny = rect[1]
rect_width = rect[2]
rect_height = rect[3]
box_minx = box[0]
box_miny = box[1]
box_maxx = box[2]
box_maxy = box[3]
box_width = (box_maxx - box_minx)+1
box_height = (box_maxy - box_miny)+1
# occlusion_ratio
occlusion_ratio = 0.3
occlusion_width = int(box_width * occlusion_ratio) * -1
occlusion_height = int(box_height * occlusion_ratio) * -1
box_in_crop_minx = box_minx - rect_minx
if box_in_crop_minx <= occlusion_width or box_in_crop_minx >= rect_width:
box_in_rect = []
return box_in_rect, label, False
box_in_crop_miny = box_miny - rect_miny
if box_in_crop_miny <= occlusion_height or box_in_crop_miny >= rect_height:
box_in_rect = []
return box_in_rect, label, False
box_in_crop_maxx = box_maxx - rect_minx
if rect_width - box_in_crop_maxx <= occlusion_width or box_in_crop_maxx <= 0:
box_in_rect = []
return box_in_rect, label, False
box_in_crop_maxy = box_maxy - rect_miny
if rect_height - box_in_crop_maxy <= occlusion_height or box_in_crop_maxy <= 0:
box_in_rect = []
return box_in_rect, label, False
if box_in_crop_minx < 0:
box_in_crop_minx = 0
if box_in_crop_miny < 0:
box_in_crop_miny = 0
if rect_width - box_in_crop_maxx < 0:
box_in_crop_maxx = rect_width-1
if rect_height - box_in_crop_maxy < 0:
box_in_crop_maxy = rect_height-1
box_in_rect = [box_in_crop_minx, box_in_crop_miny, box_in_crop_maxx, box_in_crop_maxy]
return box_in_rect, label, True
def collate_fn(self, batch):
imgs = [x[0] for x in batch]
boxes = [x[1] for x in batch]
labels = [x[2] for x in batch]
paths = [x[3] for x in batch]
num_imgs = len(imgs)
if isinstance(self.input_size, int) is True:
inputs = torch.zeros([num_imgs, 3, self.input_size, self.input_size], dtype=torch.float32)
elif isinstance(self.input_size, tuple) is True:
inputs = torch.zeros([num_imgs, 3, self.input_size[0], self.input_size[1]], dtype=torch.float32)
else:
raise ValueError('input size should be int or tuple of ints')
loc_targets = list()
cls_targets = list()
center_targets = list()
for i in range(num_imgs):
im = imgs[i]
imh, imw = im.size(1), im.size(2)
inputs[i, :, :imh, :imw] = im
# Encode data.
loc_target, cls_target, center_target = self.data_encoder.encode(boxes[i], labels[i], radius=self.radius)
loc_targets.append(loc_target)
cls_targets.append(cls_target)
center_targets.append(center_target)
return inputs, \
torch.stack(loc_targets, dim=0), \
torch.stack(cls_targets, dim=0), \
torch.stack(center_targets, dim=0), \
paths
def test():
import torchvision
# transform = transforms.Compose([
# transforms.ToTensor(),
# transforms.Normalize((0.485,0.456,0.406), (0.229,0.224,0.225))
# ])
# set random seed
random.seed(3000)
np.random.seed(3000)
torch.manual_seed(3000)
transform = transforms.Compose([
transforms.ToTensor()
])
classes = 'person|bicycle|car|motorcycle|bus|truck|cat|dog|rider'
classes = classes.split('|')
dataset = jsonDataset(path='data/voc.json', classes=classes,transform=transform,
input_image_size=(256, 512), num_crops=-1, fpn_level=5, is_norm_reg_target=True, radius=0.8,
view_image=True, do_aug=True)
print(len(dataset))
dataloader = torch.utils.data.DataLoader(dataset, batch_size=32, shuffle=True, num_workers=0,
collate_fn=dataset.collate_fn)
for idx, (images, loc_targets, cls_targets, center_targets, paths) in enumerate(dataloader):
print(loc_targets.shape)
print(cls_targets.shape)
print(center_targets.shape)
pos_ind = cls_targets[:, :, 0] <= 0
print(pos_ind.shape)
print(pos_ind.data.long().sum())
if __name__ == '__main__':
test()
| 38.110487 | 156 | 0.541644 | import random
import numpy as np
import json
import os
import cv2
import torch
import torch.utils.data as data
import torchvision.transforms as transforms
from encoder import DataEncoder
class jsonDataset(data.Dataset):
def __init__(self, path, classes, transform, input_image_size, num_crops, fpn_level, is_norm_reg_target, radius,
view_image=False, min_cols=1, min_rows=1):
self.path = path
self.classes = classes
self.transform = transform
self.input_size = input_image_size
self.num_crops = num_crops
self.view_img = view_image
self.fpn_level = fpn_level
self.is_norm_reg_target = is_norm_reg_target
self.radius = radius
self.fnames = list()
self.offsets = list()
self.boxes = list()
self.labels = list()
self.num_classes = len(self.classes)
self.label_map = dict()
self.class_idx_map = dict()
for idx in range(0, self.num_classes):
self.label_map[self.classes[idx]] = idx+1
self.class_idx_map[idx+1] = self.classes[idx]
self.data_encoder = DataEncoder(image_size=self.input_size,
num_classes=self.num_classes + 1,
fpn_level=self.fpn_level,
is_norm_reg_target=self.is_norm_reg_target)
fp_read = open(self.path, 'r')
gt_dict = json.load(fp_read)
all_boxes = list()
all_labels = list()
all_img_path = list()
for gt_key in gt_dict:
gt_data = gt_dict[gt_key][0]
box = list()
label = list()
num_boxes = len(gt_data['labels'])
img = cv2.imread(gt_data['image_path'])
img_rows = img.shape[0]
img_cols = img.shape[1]
for iter_box in range(0, num_boxes):
xmin = gt_data['boxes'][iter_box][0]
ymin = gt_data['boxes'][iter_box][1]
xmax = gt_data['boxes'][iter_box][2]
ymax = gt_data['boxes'][iter_box][3]
rows = ymax - ymin
cols = xmax - xmin
if xmin < 0 or ymin < 0:
print('negative coordinate: [xmin: ' + str(xmin) + ', ymin: ' + str(ymin) + ']')
print(gt_data['image_path'])
continue
if xmax > img_cols or ymax > img_rows:
print('over maximum size: [xmax: ' + str(xmax) + ', ymax: ' + str(ymax) + ']')
print(gt_data['image_path'])
continue
if cols < min_cols:
print('cols is lower than ' + str(min_cols) + ': [' + str(xmin) + ', ' + str(ymin) + ', ' +
str(xmax) + ', ' + str(ymax) + '] '
+ str(gt_data['image_path']))
continue
if rows < min_rows:
print('rows is lower than ' + str(min_rows) + ': [' + str(xmin) + ', ' + str(ymin) + ', ' +
str(xmax) + ', ' + str(ymax) + '] '
+ str(gt_data['image_path']))
continue
class_name = gt_data['labels'][iter_box][0]
if class_name not in self.label_map:
print('weired class name: ' + class_name)
print(gt_data['image_path'])
continue
class_idx = self.label_map[class_name]
box.append([float(xmin), float(ymin), float(xmax), float(ymax)])
label.append(int(class_idx))
if len(box) == 0 or len(label) == 0:
print('none of object exist in the image: ' + gt_data['image_path'])
continue
all_boxes.append(box)
all_labels.append(label)
all_img_path.append(gt_data['image_path'])
if len(all_boxes) == len(all_labels) and len(all_boxes) == len(all_img_path):
num_images = len(all_img_path)
else:
print('num. of boxes: ' + str(len(all_boxes)))
print('num. of labels: ' + str(len(all_labels)))
print('num. of paths: ' + str(len(all_img_path)))
raise ValueError('num. of elements are different(all boxes, all_labels, all_img_path)')
if num_crops <= 0:
for idx in range(0, num_images, 1):
self.fnames.append(all_img_path[idx])
self.boxes.append(torch.tensor(all_boxes[idx], dtype=torch.float32))
self.labels.append(torch.tensor(all_labels[idx], dtype=torch.int64))
else:
for idx in range(0, num_images, 1):
ori_boxes = all_boxes[idx]
ori_labels = all_labels[idx]
ori_img = cv2.imread(all_img_path[idx])
img_rows = ori_img.shape[0]
img_cols = ori_img.shape[1]
offsets, crop_boxes, crop_labels = self._do_crop(ori_img_rows=img_rows, ori_img_cols=img_cols,
target_img_size=self.input_size,
boxes=ori_boxes, labels=ori_labels)
num_offsets = len(offsets)
for idx_offset in range(0, num_offsets, 1):
self.fnames.append(all_img_path[idx])
self.offsets.append(offsets[idx_offset])
self.boxes.append(torch.tensor(crop_boxes[idx_offset], dtype=torch.float32))
self.labels.append(torch.tensor(crop_labels[idx_offset], dtype=torch.int64))
self.num_samples = len(self.fnames)
def __getitem__(self, idx):
fname = self.fnames[idx]
boxes = self.boxes[idx]
labels = self.labels[idx]
img = cv2.imread(fname)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
if self.num_crops > 0:
offset = self.offsets[idx]
crop_rect = (int(offset[0]), int(offset[1]),
int(offset[0]+self.input_size[1]), int(offset[1]+self.input_size[0]))
if offset[0] < 0 or offset[1] < 0:
raise ValueError("negative offset!")
for box in boxes:
if box[0] < 0 or box[1] < 0 or box[2] > self.input_size[1] or box[3] > self.input_size[0]:
raise ValueError("negative box coordinate!")
img = img[crop_rect[1]:crop_rect[3], crop_rect[0]:crop_rect[2]]
bboxes = [bbox.tolist() + [label.item()] for bbox, label in zip(boxes, labels)]
augmented = self.transform(image=img, bboxes=bboxes)
img = augmented['image']
rows, cols = img.shape[1:]
boxes = augmented['bboxes']
boxes = [list(bbox) for bbox in boxes]
labels = [bbox.pop() for bbox in boxes]
if self.view_img is True:
np_img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
np_img = np_img.numpy()
np_img = np.transpose(np_img, (1, 2, 0))
np_img = np.uint8(np_img * 255)
np_img = np.ascontiguousarray(np_img)
for idx_box, box in enumerate(boxes):
cv2.rectangle(np_img, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])), (0, 255, 0))
class_idx = labels[idx_box]
text_size = cv2.getTextSize(self.class_idx_map[class_idx], cv2.FONT_HERSHEY_PLAIN, 1, 1)
cv2.putText(np_img, self.class_idx_map[class_idx], (int(box[0]), int(box[1]) - text_size[1]), cv2.FONT_HERSHEY_PLAIN, 1, (255, 255, 255), 1)
cv2.imwrite(os.path.join("crop_test", str(idx)+".jpg"), np_img)
boxes = torch.tensor(boxes, dtype=torch.float32)
labels = torch.tensor(labels, dtype=torch.int64)
return img, boxes, labels, fname
def __len__(self):
return self.num_samples
def _do_crop(self, ori_img_rows, ori_img_cols, target_img_size, boxes, labels):
num_boxes = len(boxes)
num_labels = len(labels)
if num_boxes != num_labels:
print("error occur: Random crop")
rand_indices = [0, 1, 2, 3, 4]
np.random.shuffle(rand_indices)
output_offsets = []
output_boxes = []
output_labels = []
for box in boxes:
xmin = box[0]
ymin = box[1]
xmax = box[2]
ymax = box[3]
width = (xmax - xmin)+1
height = (ymax - ymin)+1
if width < 0 or height< 0:
print("negative width/height")
continue
for iter_crop in range(0, self.num_crops, 1):
rand_idx = rand_indices[iter_crop]
margin = np.random.randint(16, 128, size=1)
if rand_idx == 0:
offset_x = xmin-1-margin[0]
offset_y = ymin-1-margin[0]
crop_maxx = offset_x + target_img_size[1]
crop_maxy = offset_y + target_img_size[0]
if crop_maxx > ori_img_cols-1 or crop_maxy > ori_img_rows-1:
continue
if offset_x < 0 or offset_y < 0:
continue
crop_rect = [offset_x, offset_y, target_img_size[1], target_img_size[0]]
in_boxes, in_labels = self._find_boxes_in_crop(crop_rect, boxes, labels)
if len(in_boxes) == 0:
continue
output_offsets.append([offset_x, offset_y])
output_boxes.append(in_boxes)
output_labels.append(in_labels)
elif rand_idx == 1:
offset_x = xmin - (target_img_size[1] - width)-1+margin[0]
offset_y = ymin-1-margin[0]
crop_maxx = offset_x + target_img_size[1]
crop_maxy = offset_y + target_img_size[0]
if crop_maxx > ori_img_cols-1 or crop_maxy > ori_img_rows-1:
continue
if offset_x < 0 or offset_y < 0:
continue
crop_rect = [offset_x, offset_y, target_img_size[1], target_img_size[0]]
in_boxes, in_labels = self._find_boxes_in_crop(crop_rect, boxes, labels)
if len(in_boxes) == 0:
continue
output_offsets.append([offset_x, offset_y])
output_boxes.append(in_boxes)
output_labels.append(in_labels)
elif rand_idx == 2:
offset_x = xmin-1-margin[0]
offset_y = ymin - (target_img_size[0] - height)-1+margin[0]
crop_maxx = offset_x + target_img_size[1]
crop_maxy = offset_y + target_img_size[0]
if crop_maxx > ori_img_cols-1 or crop_maxy > ori_img_rows-1:
continue
if offset_x < 0 or offset_y < 0:
continue
crop_rect = [offset_x, offset_y, target_img_size[1], target_img_size[0]]
in_boxes, in_labels = self._find_boxes_in_crop(crop_rect, boxes, labels)
if len(in_boxes) == 0:
continue
output_offsets.append([offset_x, offset_y])
output_boxes.append(in_boxes)
output_labels.append(in_labels)
elif rand_idx == 3:
offset_x = xmin - (target_img_size[1] - width)-1+margin[0]
offset_y = ymin - (target_img_size[0] - height)-1+margin[0]
crop_maxx = offset_x + target_img_size[1]
crop_maxy = offset_y + target_img_size[0]
if crop_maxx > ori_img_cols-1 or crop_maxy > ori_img_rows-1:
continue
if offset_x < 0 or offset_y < 0:
continue
crop_rect = [offset_x, offset_y, target_img_size[1], target_img_size[0]]
in_boxes, in_labels = self._find_boxes_in_crop(crop_rect, boxes, labels)
if len(in_boxes) == 0:
continue
output_offsets.append([offset_x, offset_y])
output_boxes.append(in_boxes)
output_labels.append(in_labels)
elif rand_idx == 4:
rand_direction = np.random.randint(-1, 1, size=1)
offset_x = (xmin - ((target_img_size[1]-width)/2)-1) + (rand_direction[0] * margin[0])
offset_y = (ymin - ((target_img_size[0]-height)/2)-1) + (rand_direction[0] * margin[0])
crop_maxx = offset_x + target_img_size[1]
crop_maxy = offset_y + target_img_size[0]
if crop_maxx > ori_img_cols-1 or crop_maxy > ori_img_rows-1:
continue
if offset_x < 0 or offset_y < 0:
continue
crop_rect = [offset_x, offset_y, target_img_size[1], target_img_size[0]]
in_boxes, in_labels = self._find_boxes_in_crop(crop_rect, boxes, labels)
if len(in_boxes) == 0:
continue
output_offsets.append([offset_x, offset_y])
output_boxes.append(in_boxes)
output_labels.append(in_labels)
else:
print("exceed possible crop num")
return output_offsets, output_boxes, output_labels
def _find_boxes_in_crop(self, crop_rect, boxes, labels):
num_boxes = len(boxes)
num_labels = len(labels)
if num_boxes != num_labels:
print("error occur: Random crop")
boxes_in_crop=[]
labels_in_crop = []
for idx in range(0, num_boxes, 1):
box_in_crop, label, is_contain = self._find_box_in_crop(crop_rect, boxes[idx], labels[idx])
if is_contain is True:
boxes_in_crop.append(box_in_crop)
labels_in_crop.append(label)
return boxes_in_crop, labels_in_crop
def _find_box_in_crop(self, rect, box, label):
rect_minx = rect[0]
rect_miny = rect[1]
rect_width = rect[2]
rect_height = rect[3]
box_minx = box[0]
box_miny = box[1]
box_maxx = box[2]
box_maxy = box[3]
box_width = (box_maxx - box_minx)+1
box_height = (box_maxy - box_miny)+1
occlusion_ratio = 0.3
occlusion_width = int(box_width * occlusion_ratio) * -1
occlusion_height = int(box_height * occlusion_ratio) * -1
box_in_crop_minx = box_minx - rect_minx
if box_in_crop_minx <= occlusion_width or box_in_crop_minx >= rect_width:
box_in_rect = []
return box_in_rect, label, False
box_in_crop_miny = box_miny - rect_miny
if box_in_crop_miny <= occlusion_height or box_in_crop_miny >= rect_height:
box_in_rect = []
return box_in_rect, label, False
box_in_crop_maxx = box_maxx - rect_minx
if rect_width - box_in_crop_maxx <= occlusion_width or box_in_crop_maxx <= 0:
box_in_rect = []
return box_in_rect, label, False
box_in_crop_maxy = box_maxy - rect_miny
if rect_height - box_in_crop_maxy <= occlusion_height or box_in_crop_maxy <= 0:
box_in_rect = []
return box_in_rect, label, False
if box_in_crop_minx < 0:
box_in_crop_minx = 0
if box_in_crop_miny < 0:
box_in_crop_miny = 0
if rect_width - box_in_crop_maxx < 0:
box_in_crop_maxx = rect_width-1
if rect_height - box_in_crop_maxy < 0:
box_in_crop_maxy = rect_height-1
box_in_rect = [box_in_crop_minx, box_in_crop_miny, box_in_crop_maxx, box_in_crop_maxy]
return box_in_rect, label, True
def collate_fn(self, batch):
imgs = [x[0] for x in batch]
boxes = [x[1] for x in batch]
labels = [x[2] for x in batch]
paths = [x[3] for x in batch]
num_imgs = len(imgs)
if isinstance(self.input_size, int) is True:
inputs = torch.zeros([num_imgs, 3, self.input_size, self.input_size], dtype=torch.float32)
elif isinstance(self.input_size, tuple) is True:
inputs = torch.zeros([num_imgs, 3, self.input_size[0], self.input_size[1]], dtype=torch.float32)
else:
raise ValueError('input size should be int or tuple of ints')
loc_targets = list()
cls_targets = list()
center_targets = list()
for i in range(num_imgs):
im = imgs[i]
imh, imw = im.size(1), im.size(2)
inputs[i, :, :imh, :imw] = im
loc_target, cls_target, center_target = self.data_encoder.encode(boxes[i], labels[i], radius=self.radius)
loc_targets.append(loc_target)
cls_targets.append(cls_target)
center_targets.append(center_target)
return inputs, \
torch.stack(loc_targets, dim=0), \
torch.stack(cls_targets, dim=0), \
torch.stack(center_targets, dim=0), \
paths
def test():
import torchvision
random.seed(3000)
np.random.seed(3000)
torch.manual_seed(3000)
transform = transforms.Compose([
transforms.ToTensor()
])
classes = 'person|bicycle|car|motorcycle|bus|truck|cat|dog|rider'
classes = classes.split('|')
dataset = jsonDataset(path='data/voc.json', classes=classes,transform=transform,
input_image_size=(256, 512), num_crops=-1, fpn_level=5, is_norm_reg_target=True, radius=0.8,
view_image=True, do_aug=True)
print(len(dataset))
dataloader = torch.utils.data.DataLoader(dataset, batch_size=32, shuffle=True, num_workers=0,
collate_fn=dataset.collate_fn)
for idx, (images, loc_targets, cls_targets, center_targets, paths) in enumerate(dataloader):
print(loc_targets.shape)
print(cls_targets.shape)
print(center_targets.shape)
pos_ind = cls_targets[:, :, 0] <= 0
print(pos_ind.shape)
print(pos_ind.data.long().sum())
if __name__ == '__main__':
test()
| true | true |
f72b5bc149c5ba2f2e841366355f1137ce247df7 | 10,256 | py | Python | meatpy/itch50/itch50_message_parser.py | vishalbelsare/MeatPy | d4f22c4aca750b7b51858383c21ee573d6481e44 | [
"BSD-3-Clause"
] | 5 | 2021-07-21T22:19:18.000Z | 2022-03-20T02:39:27.000Z | meatpy/itch50/itch50_message_parser.py | vishalbelsare/MeatPy | d4f22c4aca750b7b51858383c21ee573d6481e44 | [
"BSD-3-Clause"
] | 1 | 2021-09-22T20:13:56.000Z | 2021-09-25T14:47:54.000Z | meatpy/itch50/itch50_message_parser.py | vishalbelsare/MeatPy | d4f22c4aca750b7b51858383c21ee573d6481e44 | [
"BSD-3-Clause"
] | 4 | 2020-12-11T02:29:52.000Z | 2021-11-06T04:00:46.000Z | """itch50_message_parser.py: Message parser class for ITCH 5.0"""
__author__ = "Vincent Grégoire"
__email__ = "vincent.gregoire@gmail.com"
from copy import deepcopy
import meatpy.itch50.itch50_market_message
from meatpy.message_parser import MessageParser
class ITCH50MessageParser(MessageParser):
"""A market message parser for ITCH 5.0 data.
"""
def __init__(self):
self.keep_messages_types = b'SAFECXDUBHRYPQINLVWK'
self.skip_stock_messages = False
self.order_refs = {}
self.stocks = None
self.matches = {}
self.counter = 0
self.stock_directory = []
self.system_messages = []
# Output settings
self.output_prefix = ''
self.message_buffer = 2000 # Per stock buffer size
self.global_write_trigger = 1000000 # Check if buffers exceeded
super(ITCH50MessageParser, self).__init__()
def write_file(self, file, in_messages=None):
"""Write the messages to a csv file in a compatible format
The messages are written to a file that could be again parsed by
the parser. In no messages are provided, the current message queue
is used.
:param file: file to write to
:type file: file
:param in_messages: messages to output
:type in_messages: list of ITCH50MarketMessage
"""
if in_messages is None:
messages = self.stock_directory
else:
messages = in_messages
for x in messages:
file.write(b'\x00')
file.write(chr(x.message_size))
file.write(x.pack())
def parse_file(self, file, write=False):
"""Parse the content of the file to generate ITCH50MarketMessage
objects.
Flag indicates if parsing output is written at the same time instead
of kept in memory.
"""
# Init containers
self.counter = 0
self.order_refs = {}
self.stock_messages = {}
self.matches = {}
self.stock_messages = {}
self.stock_directory = []
self.system_messages = []
self.latest_timestamp = None
maxMessageSize = 52 # Largest possible message in ITCH
cachesize = 1024*4
haveData = True
EOFreached = False
dataBuffer = file.read(cachesize)
buflen = len(dataBuffer)
while haveData is True:
# Process next message
byte = dataBuffer[0:1]
if byte != b'\x00':
raise Exception('ITCH50MessageParser:ITCH_factory',
'Unexpected byte: ' + str(byte))
messageLen = ord(dataBuffer[1:2])
message = self.ITCH_factory(dataBuffer[2:2+messageLen])
self.process_message(message)
if message.type == b'S': # System message
if message.code == b'C': # End of messages
break
# Check if we need to write the cache for the stock
if write and self.counter % self.global_write_trigger == 0:
for x in self.stock_messages:
self.write_stock(x)
# Remove the message from buffer
dataBuffer = dataBuffer[2+messageLen:]
buflen = len(dataBuffer)
if EOFreached and (buflen == 0):
haveData = False
# If we don't have enough, read more
if buflen < maxMessageSize and not EOFreached:
newData = file.read(cachesize)
if newData == b'':
EOFreached = True
if buflen == 0:
haveData = False
else:
dataBuffer = dataBuffer + newData
buflen = len(dataBuffer)
# Write all unempty buffers
if write:
for x in self.stock_messages:
self.write_stock(stock=x, overlook_buffer=True)
def write_stock(self, stock, overlook_buffer=False):
if (len(self.stock_messages[stock]) > self.message_buffer or
overlook_buffer):
stock_str = stock.decode()
with open(self.output_prefix +
stock_str.strip().replace('*', '8')+'.txt', 'a+b') as file:
# * in stock symbols replaced by 8
for x in self.stock_messages[stock]:
file.write(b'\x00')
file.write(bytes([x.message_size]))
file.write(x.pack())
self.stock_messages[stock] = []
def append_stock_message(self, stock, message):
"""Append the message to the stock message queue
Initialises the queue if empty"""
if self.stocks is None or stock in self.stocks:
if self.skip_stock_messages:
return
if stock not in self.stock_messages:
self.stock_messages[stock] = deepcopy(self.system_messages)
self.stock_messages[stock].append(message)
def process_message(self, message):
"""
Looks at the message and decides what to do with it.
Could be keep, discard, send to file, etc.
"""
self.counter += 1
if self.counter % 1000000 == 0:
print( "Processing message no " + str(self.counter))
if message.type not in self.keep_messages_types:
return
if message.type in b'R':
self.stock_directory.append(message)
self.append_stock_message(message.stock, message)
elif message.type in b'SVW':
# Pass-through all system messages
for x in self.stock_messages:
self.append_stock_message(x, message)
self.system_messages.append(message)
elif message.type in b'HYQINKLJh':
if self.stocks is None or message.stock in self.stocks:
self.append_stock_message(message.stock, message)
elif message.type in b'AF':
if self.stocks is None or message.stock in self.stocks:
self.order_refs[message.orderRefNum] = message.stock
self.append_stock_message(message.stock, message)
elif message.type in b'ECXD':
if message.orderRefNum in self.order_refs:
stock = self.order_refs[message.orderRefNum]
self.append_stock_message(stock, message)
if message.type in b'D':
del self.order_refs[message.orderRefNum]
elif message.type in b'EC':
self.matches[message.match] = stock
elif message.type in b'U':
if message.origOrderRefNum in self.order_refs:
stock = self.order_refs[message.origOrderRefNum]
self.append_stock_message(stock, message)
del self.order_refs[message.origOrderRefNum]
self.order_refs[message.newOrderRefNum] = stock
elif message.type in b'B':
if message.match in self.matches:
stock = self.matches[message.match]
self.append_stock_message(stock, message)
elif message.type in b'P':
if self.stocks is None or message.stock in self.stocks:
self.append_stock_message(message.stock, message)
self.matches[message.match] = message.stock
def ITCH_factory(self, message):
'''
Pass this factory an entire bytearray and you will be
given the appropriate ITCH message
'''
msgtype = chr(message[0])
if msgtype == 'S':
return meatpy.itch50.itch50_market_message.SystemEventMessage(message)
elif msgtype == 'R':
return meatpy.itch50.itch50_market_message.StockDirectoryMessage(message)
elif msgtype == 'H':
return meatpy.itch50.itch50_market_message.StockTradingActionMessage(message)
elif msgtype == 'Y':
return meatpy.itch50.itch50_market_message.RegSHOMessage(message)
elif msgtype == 'L':
return meatpy.itch50.itch50_market_message.MarketParticipantPositionMessage(message)
elif msgtype == 'V':
return meatpy.itch50.itch50_market_message.MWCBDeclineLevelMessage(message)
elif msgtype == 'W':
return meatpy.itch50.itch50_market_message.MWCBBreachMessage(message)
elif msgtype == 'K':
return meatpy.itch50.itch50_market_message.IPOQuotingPeriodUpdateMessage(message)
elif msgtype == 'A':
return meatpy.itch50.itch50_market_message.AddOrderMessage(message)
elif msgtype == 'F':
return meatpy.itch50.itch50_market_message.AddOrderMPIDMessage(message)
elif msgtype == 'E':
return meatpy.itch50.itch50_market_message.OrderExecutedMessage(message)
elif msgtype == 'C':
return meatpy.itch50.itch50_market_message.OrderExecutedPriceMessage(message)
elif msgtype == 'X':
return meatpy.itch50.itch50_market_message.OrderCancelMessage(message)
elif msgtype == 'D':
return meatpy.itch50.itch50_market_message.OrderDeleteMessage(message)
elif msgtype == 'U':
return meatpy.itch50.itch50_market_message.OrderReplaceMessage(message)
elif msgtype == 'P':
return meatpy.itch50.itch50_market_message.TradeMessage(message)
elif msgtype == 'Q':
return meatpy.itch50.itch50_market_message.CrossTradeMessage(message)
elif msgtype == 'B':
return meatpy.itch50.itch50_market_message.BrokenTradeMessage(message)
elif msgtype == 'I':
return meatpy.itch50.itch50_market_message.NoiiMessage(message)
elif msgtype == 'N':
return meatpy.itch50.itch50_market_message.RpiiMessage(message)
elif msgtype == 'J':
return meatpy.itch50.itch50_market_message.LULDAuctionCollarMessage(message)
elif msgtype == 'h':
return meatpy.itch50.itch50_market_message.OperationalHaltMessage(message)
else:
raise Exception('ITCH50MessageParser:ITCH_factory',
'Unknown message type: '+ str(msgtype))
| 41.354839 | 96 | 0.604524 |
__author__ = "Vincent Grégoire"
__email__ = "vincent.gregoire@gmail.com"
from copy import deepcopy
import meatpy.itch50.itch50_market_message
from meatpy.message_parser import MessageParser
class ITCH50MessageParser(MessageParser):
def __init__(self):
self.keep_messages_types = b'SAFECXDUBHRYPQINLVWK'
self.skip_stock_messages = False
self.order_refs = {}
self.stocks = None
self.matches = {}
self.counter = 0
self.stock_directory = []
self.system_messages = []
self.output_prefix = ''
self.message_buffer = 2000
self.global_write_trigger = 1000000
super(ITCH50MessageParser, self).__init__()
def write_file(self, file, in_messages=None):
if in_messages is None:
messages = self.stock_directory
else:
messages = in_messages
for x in messages:
file.write(b'\x00')
file.write(chr(x.message_size))
file.write(x.pack())
def parse_file(self, file, write=False):
self.counter = 0
self.order_refs = {}
self.stock_messages = {}
self.matches = {}
self.stock_messages = {}
self.stock_directory = []
self.system_messages = []
self.latest_timestamp = None
maxMessageSize = 52
cachesize = 1024*4
haveData = True
EOFreached = False
dataBuffer = file.read(cachesize)
buflen = len(dataBuffer)
while haveData is True:
byte = dataBuffer[0:1]
if byte != b'\x00':
raise Exception('ITCH50MessageParser:ITCH_factory',
'Unexpected byte: ' + str(byte))
messageLen = ord(dataBuffer[1:2])
message = self.ITCH_factory(dataBuffer[2:2+messageLen])
self.process_message(message)
if message.type == b'S':
if message.code == b'C':
break
if write and self.counter % self.global_write_trigger == 0:
for x in self.stock_messages:
self.write_stock(x)
dataBuffer = dataBuffer[2+messageLen:]
buflen = len(dataBuffer)
if EOFreached and (buflen == 0):
haveData = False
if buflen < maxMessageSize and not EOFreached:
newData = file.read(cachesize)
if newData == b'':
EOFreached = True
if buflen == 0:
haveData = False
else:
dataBuffer = dataBuffer + newData
buflen = len(dataBuffer)
# Write all unempty buffers
if write:
for x in self.stock_messages:
self.write_stock(stock=x, overlook_buffer=True)
def write_stock(self, stock, overlook_buffer=False):
if (len(self.stock_messages[stock]) > self.message_buffer or
overlook_buffer):
stock_str = stock.decode()
with open(self.output_prefix +
stock_str.strip().replace('*', '8')+'.txt', 'a+b') as file:
# * in stock symbols replaced by 8
for x in self.stock_messages[stock]:
file.write(b'\x00')
file.write(bytes([x.message_size]))
file.write(x.pack())
self.stock_messages[stock] = []
def append_stock_message(self, stock, message):
if self.stocks is None or stock in self.stocks:
if self.skip_stock_messages:
return
if stock not in self.stock_messages:
self.stock_messages[stock] = deepcopy(self.system_messages)
self.stock_messages[stock].append(message)
def process_message(self, message):
self.counter += 1
if self.counter % 1000000 == 0:
print( "Processing message no " + str(self.counter))
if message.type not in self.keep_messages_types:
return
if message.type in b'R':
self.stock_directory.append(message)
self.append_stock_message(message.stock, message)
elif message.type in b'SVW':
# Pass-through all system messages
for x in self.stock_messages:
self.append_stock_message(x, message)
self.system_messages.append(message)
elif message.type in b'HYQINKLJh':
if self.stocks is None or message.stock in self.stocks:
self.append_stock_message(message.stock, message)
elif message.type in b'AF':
if self.stocks is None or message.stock in self.stocks:
self.order_refs[message.orderRefNum] = message.stock
self.append_stock_message(message.stock, message)
elif message.type in b'ECXD':
if message.orderRefNum in self.order_refs:
stock = self.order_refs[message.orderRefNum]
self.append_stock_message(stock, message)
if message.type in b'D':
del self.order_refs[message.orderRefNum]
elif message.type in b'EC':
self.matches[message.match] = stock
elif message.type in b'U':
if message.origOrderRefNum in self.order_refs:
stock = self.order_refs[message.origOrderRefNum]
self.append_stock_message(stock, message)
del self.order_refs[message.origOrderRefNum]
self.order_refs[message.newOrderRefNum] = stock
elif message.type in b'B':
if message.match in self.matches:
stock = self.matches[message.match]
self.append_stock_message(stock, message)
elif message.type in b'P':
if self.stocks is None or message.stock in self.stocks:
self.append_stock_message(message.stock, message)
self.matches[message.match] = message.stock
def ITCH_factory(self, message):
msgtype = chr(message[0])
if msgtype == 'S':
return meatpy.itch50.itch50_market_message.SystemEventMessage(message)
elif msgtype == 'R':
return meatpy.itch50.itch50_market_message.StockDirectoryMessage(message)
elif msgtype == 'H':
return meatpy.itch50.itch50_market_message.StockTradingActionMessage(message)
elif msgtype == 'Y':
return meatpy.itch50.itch50_market_message.RegSHOMessage(message)
elif msgtype == 'L':
return meatpy.itch50.itch50_market_message.MarketParticipantPositionMessage(message)
elif msgtype == 'V':
return meatpy.itch50.itch50_market_message.MWCBDeclineLevelMessage(message)
elif msgtype == 'W':
return meatpy.itch50.itch50_market_message.MWCBBreachMessage(message)
elif msgtype == 'K':
return meatpy.itch50.itch50_market_message.IPOQuotingPeriodUpdateMessage(message)
elif msgtype == 'A':
return meatpy.itch50.itch50_market_message.AddOrderMessage(message)
elif msgtype == 'F':
return meatpy.itch50.itch50_market_message.AddOrderMPIDMessage(message)
elif msgtype == 'E':
return meatpy.itch50.itch50_market_message.OrderExecutedMessage(message)
elif msgtype == 'C':
return meatpy.itch50.itch50_market_message.OrderExecutedPriceMessage(message)
elif msgtype == 'X':
return meatpy.itch50.itch50_market_message.OrderCancelMessage(message)
elif msgtype == 'D':
return meatpy.itch50.itch50_market_message.OrderDeleteMessage(message)
elif msgtype == 'U':
return meatpy.itch50.itch50_market_message.OrderReplaceMessage(message)
elif msgtype == 'P':
return meatpy.itch50.itch50_market_message.TradeMessage(message)
elif msgtype == 'Q':
return meatpy.itch50.itch50_market_message.CrossTradeMessage(message)
elif msgtype == 'B':
return meatpy.itch50.itch50_market_message.BrokenTradeMessage(message)
elif msgtype == 'I':
return meatpy.itch50.itch50_market_message.NoiiMessage(message)
elif msgtype == 'N':
return meatpy.itch50.itch50_market_message.RpiiMessage(message)
elif msgtype == 'J':
return meatpy.itch50.itch50_market_message.LULDAuctionCollarMessage(message)
elif msgtype == 'h':
return meatpy.itch50.itch50_market_message.OperationalHaltMessage(message)
else:
raise Exception('ITCH50MessageParser:ITCH_factory',
'Unknown message type: '+ str(msgtype))
| true | true |
f72b5ca0b6e649f1aa5b09952cf5e59898061a4c | 34,977 | py | Python | SigProfilerMatrixGenerator/install.py | edawson/SigProfilerMatrixGenerator | bd6d3bb15e87805cdc7e771c3fdd886f4a9fc29b | [
"BSD-2-Clause"
] | null | null | null | SigProfilerMatrixGenerator/install.py | edawson/SigProfilerMatrixGenerator | bd6d3bb15e87805cdc7e771c3fdd886f4a9fc29b | [
"BSD-2-Clause"
] | null | null | null | SigProfilerMatrixGenerator/install.py | edawson/SigProfilerMatrixGenerator | bd6d3bb15e87805cdc7e771c3fdd886f4a9fc29b | [
"BSD-2-Clause"
] | null | null | null | #!/usr/bin/env python3
#Author: Erik Bergstrom
#Contact: ebergstr@eng.ucsd.edu
from __future__ import print_function
import os
import sys
import re
import subprocess
import argparse
import time
from scipy import spatial
import pandas as pd
import shutil
import logging
import hashlib
from SigProfilerMatrixGenerator.scripts import convert_input_to_simple_files as convertIn
from SigProfilerMatrixGenerator.scripts import SigProfilerMatrixGeneratorFunc as matGen
def md5(fname):
hash_md5 = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return (hash_md5.hexdigest())
def install_chromosomes (genomes, ref_dir, custom, rsync, bash):
if custom:
for genome in genomes:
os.system("gzip -d references/chromosomes/fasta/" + genome + "/*.gz")
chromosome_fasta_path = "references/chromosomes/fasta/" + genome + "/"
os.system("python scripts/save_chrom_strings.py -g " + genome)
print("Chromosome string files for " + genome + " have been created. Continuing with installation.")
#os.system("rm -r " + chromosome_fasta_path)
else:
for genome in genomes:
species = None
chrom_number = None
if genome == 'GRCh37' or genome == 'GRCh38':
species = "homo_sapiens"
chrom_number = 24
elif genome == 'mm10' or genome == 'mm9':
species = "mus_musculus"
chrom_number = 21
elif genome == 'rn6':
species = 'rattus_norvegicus'
chrom_number = 22
else:
print(genome + " is not supported. The following genomes are supported:\nGRCh37, GRCh38, mm10")
sys.exit()
chromosome_string_path = "references/chromosomes/chrom_string/" + genome + "/"
chromosome_fasta_path = "references/chromosomes/fasta/" + genome + "/"
if os.path.exists(ref_dir + "chromosomes/tsb/" + genome) and len(os.listdir(ref_dir + "chromosomes/tsb/" + genome)) >= chrom_number:
break
wget_flag = True
if os.path.exists(chromosome_string_path) == False or len(os.listdir(chromosome_string_path)) <= chrom_number:
print("[DEBUG] Chromosome string files found at: " + ref_dir + chromosome_string_path)
if os.path.exists(chromosome_fasta_path) == False or len(os.listdir(chromosome_fasta_path)) <= chrom_number:
print("[DEBUG] Chromosome fasta files found at: " + ref_dir + chromosome_fasta_path)
print("Chromosomes are not currently saved as individual text files for " + genome + ". Downloading the files now...")
if not rsync:
#os.system("rsync -av -m --include='*/' --include='*.dna.chromosome.*' --exclude='*' rsync://ftp.ensembl.org/ensembl/pub/grch37/update/fasta/homo_sapiens/dna/ " + chromosome_fasta_path + " 2>&1>> install.log")
# try:
# p = subprocess.Popen("wget", stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# except:
# proceed = input("You may not have wget or homebrew installed. Download those dependencies now?[Y/N]").upper()
# if proceed == 'Y':
# try:
# os.system("brew install wget")
# except:
# os.system('/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"')
# os.system("brew install wget")
# else:
# print("Installation has stopped. Please download the chromosome files before proceeding with the installation.")
# wget_flag = False
# sys.exit()
if wget_flag:
try:
if genome == 'GRCh37':
if bash:
os.system("bash -c '" + 'wget -r -l1 -c -nc --no-parent -A "*.dna.chromosome.*" -nd -P ' + chromosome_fasta_path + ' ftp://ftp.ensembl.org/pub/grch37/current/fasta/homo_sapiens/dna/ 2>> install.log' + "'")
else:
os.system('wget -r -l1 -c -nc --no-parent -A "*.dna.chromosome.*" -nd -P ' + chromosome_fasta_path + ' ftp://ftp.ensembl.org/pub/grch37/current/fasta/homo_sapiens/dna/ 2>> install.log')
#os.system("wget -r -l1 -c -nc --no-parent -A '*.dna.chromosome.*' -nd -P " + chromosome_fasta_path + " ftp://ftp.ensembl.org/pub/grch37/update/fasta/homo_sapiens/dna/ 2>> install.log")
elif genome == 'mm9':
if bash:
os.system("bash -c '" + 'wget -r -l1 -c -nc --no-parent -A "*.dna.chromosome.*" -nd -P ' + chromosome_fasta_path + ' ftp://ftp.ensembl.org/pub/release-67/fasta/mus_musculus/dna/ 2>> install.log' + "'")
else:
os.system('wget -r -l1 -c -nc --no-parent -A "*.dna.chromosome.*" -nd -P ' + chromosome_fasta_path + ' ftp://ftp.ensembl.org/pub/release-67/fasta/mus_musculus/dna/ 2>> install.log')
elif genome == 'rn6':
if bash:
os.system("bash -c '" + 'wget -r -l1 -c -nc --no-parent -A "*.dna.chromosome.*" -nd -P ' + chromosome_fasta_path + ' ftp://ftp.ensembl.org/pub/release-96/fasta/rattus_norvegicus/dna/ 2>> install.log' + "'")
else:
os.system('wget -r -l1 -c -nc --no-parent -A "*.dna.chromosome.*" -nd -P ' + chromosome_fasta_path + ' ftp://ftp.ensembl.org/pub/release-96/fasta/rattus_norvegicus/dna/ 2>> install.log')
else:
if bash:
os.system("bash -c '" + 'wget -r -l1 -c -nc --no-parent -A "*.dna.chromosome.*" -nd -P ' + chromosome_fasta_path + ' ftp://ftp.ensembl.org/pub/release-93/fasta/' +species+'/dna/ 2>> install.log' + "'")
else:
os.system('wget -r -l1 -c -nc --no-parent -A "*.dna.chromosome.*" -nd -P ' + chromosome_fasta_path + ' ftp://ftp.ensembl.org/pub/release-93/fasta/' +species+'/dna/ 2>> install.log')
#os.system("gunzip references/chromosomes/fasta/" + genome + "/*.gz")
os.system("gzip -d references/chromosomes/fasta/" + genome + "/*.gz")
except:
print("The ensembl ftp site is not currently responding.")
sys.exit()
else:
try:
if genome == 'GRCh37':
if bash:
os.system("bash -c '" + "rsync -av -m --include='*/' --include='*.dna.chromosome.*' --exclude='*' rsync://ftp.ensembl.org/ensembl/pub/grch37/current/fasta/homo_sapiens/dna/ " + chromosome_fasta_path + " 2>&1>> install.log" + "'")
else:
os.system("rsync -av -m --include='*/' --include='*.dna.chromosome.*' --exclude='*' rsync://ftp.ensembl.org/ensembl/pub/grch37/current/fasta/homo_sapiens/dna/ " + chromosome_fasta_path + " 2>&1>> install.log")
elif genome == 'mm9':
if bash:
os.system("bash -c '" + "rsync -av -m --include='*/' --include='*.dna.chromosome.*' --exclude='*' rsync://ftp.ensembl.org/ensembl/pub/release-67/fasta/mus_musculus/dna/ " + chromosome_fasta_path + " 2>&1>> install.log" + "'")
else:
os.system("rsync -av -m --include='*/' --include='*.dna.chromosome.*' --exclude='*' rsync://ftp.ensembl.org/ensembl/pub/release-67/fasta/mus_musculus/dna/ " + chromosome_fasta_path + " 2>&1>> install.log")
elif genome == 'rn6':
if bash:
os.system("bash -c '" + "rsync -av -m --include='*/' --include='*.dna.chromosome.*' --exclude='*' rsync://ftp.ensembl.org/ensembl/pub/release-96/fasta/rattus_norvegicus/dna/ " + chromosome_fasta_path + " 2>> install.log" + "'")
else:
os.system("rsync -av -m --include='*/' --include='*.dna.chromosome.*' --exclude='*' rsync://ftp.ensembl.org/ensembl/pub/release-96/fasta/rattus_norvegicus/dna/ " + chromosome_fasta_path + " 2>> install.log")
else:
if bash:
os.system("bash -c '" + "rsync -av -m --include='*/' --include='*.dna.chromosome.*' --exclude='*' rsync://ftp.ensembl.org/ensembl/pub/release-93/fasta/"+species+"/dna/ " + chromosome_fasta_path + " 2>&1>> install.log" + "'")
else:
os.system("rsync -av -m --include='*/' --include='*.dna.chromosome.*' --exclude='*' rsync://ftp.ensembl.org/ensembl/pub/release-93/fasta/"+species+"/dna/ " + chromosome_fasta_path + " 2>&1>> install.log")
#os.system("gunzip references/chromosomes/fasta/" + genome + "/*.gz")
os.system("gzip -d references/chromosomes/fasta/" + genome + "/*.gz")
except:
print("The ensembl ftp site is not currently responding.")
sys.exit()
print("Chromosome fasta files for " + genome + " have been installed. Creating the chromosome string files now...")
os.system("python scripts/save_chrom_strings.py -g " + genome)
print("Chromosome string files for " + genome + " have been created. Continuing with installation.")
# os.system("rm -r " + chromosome_fasta_path)
# os.remove(chromosome_fasta_path)
shutil.rmtree(chromosome_fasta_path)
else:
print("Chromosome reference files exist for " + genome + ". Continuing with installation.")
def install_chromosomes_tsb (genomes, ref_dir, custom):
check_sum = {'GRCh37':
{'1':'a7d51305e943cf06ff2029146bd91bca','2':'d24d0185af89356d44614ab0d6fd6a68','3':'ea5e033147dcaf77bfd4c70f50688d37',
'4':'00d7797c7184f1802367e33f6e2bc3da','5':'f74b1eeb329088242a9f22a16322b325','6':'b353cc4c4abc90340e7747509fe7b457',
'7':'bbadde91b3ef958c7d20e2b1088c8cd2','8':'0ff695692e3efebaf00c7905d0d536d7','9':'40b75a18acb66748a37888c53a76dcdb',
'10':'557881b744a932b4ceee8a06d6de85a4','11':'f8b8f118101d7cb04164b29a7acadca4','12':'52c18e9fefc3ed3e35c1d8771d1247de',
'13':'a241d1cdcadccfd94db792300ab000bf','14':'ed3907128336795669bc19d77c0aa409','15':'bfc66ad087c4e9025076d7571cffa30e',
'16':'bd251fddc42400bb54ef95d5e1002ece','17':'fcd36b1bf5c4bd74328dc4caaae244ae','18':'e015d4324c36374827582c5b1214a736',
'19':'5cfa7d47e2d73dbdbf8d68f97c8e8b23','20':'2fa0717bf4e8dddac64cd393f4134ff5','21':'ba5559776d4601b80ca42c82f02102a4',
'22':'ba762b6ae493df40d04d1ff63d9b2933','Y':'0303100be91874b966a998273cd7c8eb','X':'14e331d82736f6cfc177ff8c90f7bd78',
'MT':'dfd6db5743d399516d5c8dadee5bee78'},
'GRCh38':
{'1':'ebe083105e7703a49581a36d73732a96','2':'cd65e36dbdf12a8ac3d2c70ebac8cad4','3':'6c20a7008394f2fa9c304d231a1f391b',
'4':'5c7443e1678868adadeac0e57558f6e8','5':'45573232c8097c679503a6598f61e60b','6':'cfc137c7434d3a9a872332d405b5c553',
'7':'9d8210c22c1962db837e7b62a578975c','8':'665134fd44f21915cbeef955addf89ba','9':'758d0c0c71d8bafbe1ede86587191730',
'10':'397bb21acff1ca3052ac802f2aee06e0','11':'07707ff8a2a964656469a7be7bb3e576','12':'506d02539075e080ee12ebdf63908080',
'13':'03ed22f01ab43145733c0b6a647e0560','14':'8b93447086549e476c65699ed813a567','15':'cd0dfe9fa78cae2fc7becf8f8ec6c693',
'16':'e17bbb66eb4d6b62b7b0e2fbf062b6a6','17':'8fc95bb3101d024d890aa3543eb454c5','18':'a4870628045bb033a90e8c89f818e24d',
'19':'6a9d0c8298f0ba2fa13180e02b969f16','20':'aa75d35969cf3956bb4ace7bdc57b34e','21':'5d55f5ad6271d6a0d8806876924990f7',
'22':'efdb4e1d23ab7964302b828062a33447','Y':'3b38c639ad164d60f1a055b46fcd2748','X':'d5edbea3cf5d1716765dd4a7b41b7656',
'MT':'dfd6db5743d399516d5c8dadee5bee78'},
'mm9':
{'1':'c5afc4b3f7f2119696214511d7a04341','2':'a7b467475a1b032d2c893dac1c419a28','3':'f922bc529a17324f1cd858f9a8723d65',
'4':'f3d6b74e3c04dbd229e2f1e363607506','5':'5fee4f1889c9fe20f7f8562c62bbeb0a','6':'481d47b87da45f3a20181c780fd796c2',
'7':'454ef2bf49a5ba8cfea3d16dfcfc7f25','8':'2f4162d4c824db78a2a2a820cb4fec81','9':'0649e6aec61af1ab8ab4797ea8e54119',
'10':'38296256bcfe886c8ae771418e4fd824','11':'b31cb0ce693e35eaa77031d44b12e474','12':'d2b3e4b015742b6aea30ceec5a972968',
'13':'df77b6d0ed1b133224b128c189736372','14':'0ec3c0e6b3fa2cdb957541f19792e130','15':'44fcaf2ec9b82dae910f85ce41c3cfad',
'16':'ad7a8dbdf46fa7077e0982a54eab70b7','17':'71aee1dee3cd2078e4619c485d88817e','18':'727ec4ed3128ecacd6cd2f7558083553',
'19':'461a7119781ab7f4b654fdd9ef76e0ec','Y':'471ff3bbb4520c020cfaa7ca8371c543','X':'9ccadf96cd3aa0ed9d299894a3d7fde0',
'MT':'a1d56043ed8308908965dd080a4d0c8d'},
'mm10':
{'1':'ef88c5ac276a32a2865c0408f92acd55','2':'ced7325ef9e2dfedea3fbe26428a6059','3':'9cd1794eeea27553077a018038303908',
'4':'da616d7ed6c67f824487eb2ed09cd33b','5':'b327b82da6986bf947105d07c0ad6d2e','6':'fb9a8fa0b85561f8d4de633c22d5157a',
'7':'12457fd80f6806779fc0d4cc8d36fbad','8':'5d98d86bd22bee1cb226406f49ee7caf','9':'b2f26613fcc622a4003e4c945ae55e25',
'10':'e9f3589529e258ede66d2e77bb87d21d','11':'76bcd285c3c66471ad6fccfabe42294c','12':'ac34fc3616c9609d8e75a59069e9007a',
'13':'f81b976e4e4617b25945d06f9aa30846','14':'95dc042eb2aa7d4cc0abe071d4d7966e','15':'fbf2477833aff73ae085537cd7ee0f85',
'16':'77cbcd009ba50891571f785595717ec1','17':'cd9e4dfdd168ed3de05dac4d44c6e692', '18':'945e83694c7c8f69d6186e1a2abc9771',
'19':'e57b25f8869de31a9dbce06510711db6','Y':'c2146ba4ab1ec262f5e38b2a1ebc5f5b','X':'9af543088be046fdc63976c2d41de94c',
'MT':'a1d56043ed8308908965dd080a4d0c8d'},
'rn6':
{'1':'003723513cbdb3708fcc5d737c05199c','2':'53e52c5facc7f05462be533845f37425','3':'8d157a9b71fe9770cf783ea5459b19d7',
'4':'a66dc1999bcc960ff11fe0b24c0d7b14','5':'601cf83411234adbdd9f911b89509564','6':'03b1f4af58fffdf213466ea85b570b3d',
'7':'4ed05ddf9502ef79e121c02e391660e6','8':'3e2458daaf1b3e8ab4d0e0a9e60c067b','9':'8f83caeccec7ea6e35e404737138ee67',
'10':'9c1af453a5facc9bfa821457bcfc4d30','11':'ef0480a905c55d76a3c58e295a85bc75','12':'643b6fe4a3a6363ffe64a6c316fa3e1a',
'13':'102bb3fb420a4104c216bcdf99870374','14':'e26b8b63fba0ea7ced4f0330e93a8cdc','15':'da747616a1362d374d4786102fab6f9f',
'16':'54e4f932eb0eda4cbf31156f96ef7235','17':'46c2facf5415e4eff8b0804161db722d', '18':'f1cb84f002967854b83bf266ec59a7a3',
'19':'b85ca155fd1780fe5c327a4589c212a6','20':'899d3511352d78b9b9dc63f063d91b31','Y':'6a7a3539c329dc540dfa6db006003bb1',
'X':'7a06bafab97c59a819f03633f0a6b7a2'},
'c_elegans':
{'I':'5a3ea8cf3dfbc641716b7bc805edcaae','II':'bf82edaa92809dd2fea2b791c38c9728','III':'d2df34b6743f41d3964549fc76c5f1a2',
'IV':'23396bb57145d3acde2888947b5b8c3a','V':'09df3c53b12e5fd7d9035cc98ca221a3','X':'988046456f1409dfdb5e26444d84d238',
'MtDNA':'48983f530959780de0125f74a87d4fc1'},
'dog':
{'1':'bef8283c1a36f9aef0e407de2ff6af00','2':'9cc961192bb5e58b3847060c3e9c1cfc','3':'d33263fa2de6666b41e140cb7a8da66c',
'4':'cd4ed39ebac1c04800ccf30466ec69f5','5':'c0f48a4a764e58388b48835aca2ec0a4','6':'4b472a2f8d0a53ac75cce04e7dc9279a',
'7':'12a61573a0da2c9306fff705bb1c39c1','8':'e22cf22a27560aa8523dc959ddcf6e25','9':'c079a73d719145cdd5c7c93969a1c392',
'10':'45805a518147f7846bd0457ca038c8df','11':'f38cda8508463a7607dff14a581ee7b0','12':'adb5de197f58bb827fa01fe924eb3a1d',
'13':'055a845ba97baad3b13d4d3359f88290','14':'27f0ba8e47996a058807a3827cf8e4a8','15':'2e9565c687a593eb0acbdd0962bb9255',
'16':'89b2225bb78d88b0fd1d38d9514ab0cb','17':'f0378253e2f083e42b665ea202fde3b0','18':'04d124e273f3b54a685ad6526223cd03',
'19':'67bae093919e6bb5ab6b9806c739d539','20':'5588387165a2e19c4533012cfb4998f3','21':'371cdf18a545728f7964b9db2fc72d5e',
'22':'fbf76865f88a018d93506e036f6a68bc','23':'085145e01d9fd9f0f999fb9e8e8d4400','24':'69b75a9962fb766b447e7d1252cb31ac',
'25':'12d5c6677b3e17170c317c1f5532d2a8','26':'13937d18e56b2b93d12fa5fcba48a138','27':'1d03d8ca5f201f4d156f5e1b38f7a67c',
'28':'c33395dec7fdc13e9d8f10afaa946f8c','29':'174f2db104ecaa5efef770f44241e3b0','30':'047d420ef9aecb933a7d83b6af820b23',
'31':'5be61f0c9944a5f2d7d1a5b2e75fb000','32':'212dcb867e95a642277a243fed8d8e41','33':'08a217b02cdd778cfdb0005dff4828b1',
'34':'4245d6fc370d9049ef4c25314fbef239','35':'1344aba8755b8a4e304629180fc0591a','36':'e4fff6ed84777905dc999ca6d6bc2557',
'37':'60d51ea6ae9e3f2fa316e3d03aff96b2','38':'4090ff76d94e6b38920916ae3ff2441c','X':'bce1372df64037d79b0995311d8ff971'}}
for genome in genomes:
chrom_number = None
if genome == 'GRCh37' or genome == 'GRCh38':
chrom_number = 24
elif genome == 'mm10' or genome == 'mm9':
chrom_number = 21
elif genome == 'rn6':
chrom_number = 22
chromosome_TSB_path = "references/chromosomes/tsb/" + genome + "/"
transcript_files = "references/chromosomes/transcripts/" + genome + "/"
print("[DEBUG] Chromosome tsb files found at: " + ref_dir + chromosome_TSB_path)
if os.path.exists(transcript_files) == False or len(os.listdir(transcript_files)) < 1:
print("Please download the transcript files before proceeding. You can download the files from 'http://www.ensembl.org/biomart/martview'.")
print("Follow the format presented in the README file:\n\n\tGene stable ID Transcript stable ID Chromosome/scaffold name Strand Transcript start (bp) Transcript end (bp)\n\n\n")
sys.exit()
if os.path.exists(chromosome_TSB_path) == False or len(os.listdir(chromosome_TSB_path)) < chrom_number:
print("The transcriptional reference data for " + genome + " has not been saved. Creating these files now")
os.system("python scripts/save_tsb_192.py -g " + genome)
corrupt = False
for files in os.listdir(chromosome_TSB_path):
if "proportions" in files:
continue
if ".DS_Store" in files:
continue
chrom = files.split(".")
chrom = chrom[0]
check = md5(chromosome_TSB_path + files)
if check_sum[genome][chrom] != check:
corrupt = True
os.remove(chromosome_TSB_path + files)
print("[DEBUG] Chromosome " + chrom + " md5sum did not match => reference md5sum: " + str(check_sum[genome][chrom]) + " new file md5sum: " + str(check))
if corrupt:
print("The transcriptional reference data appears to be corrupted. Please reinstall the " + genome + " genome.")
sys.exit()
print("The transcriptional reference data for " + genome + " has been saved.")
def install_chromosomes_tsb_BED (genomes, custom, ref_dir):
for genome in genomes:
if not os.path.exists(ref_dir + "chromosomes/tsb_BED/" + genome + "/") or len(os.listdir(ref_dir + "chromosomes/tsb_BED/" + genome + "/")) < 19:
os.system("python scripts/save_chrom_tsb_separate.py -g " + genome)
print("The TSB BED files for " + genome + " have been saved.")
def benchmark (genome, ref_dir):
#current_dir = os.path.realpath(__file__)
#ref_dir = re.sub('\/install.py$', '', current_dir)
ref_dir = os.path.dirname(os.path.abspath(__file__))
vcf_path = ref_dir + "/references/vcf_files/" + genome + "_bench/"
start_time = time.time()
matGen.SigProfilerMatrixGeneratorFunc(genome + "_bench", genome, vcf_path)
end_time = time.time()
original_matrix_96 = ref_dir + "/scripts/Benchmark/" + genome + "_bench_orig_96.txt"
original_matrix_3072 = ref_dir + "/scripts/Benchmark/" + genome + "_bench_orig_3072.txt"
new_matrix_96 = vcf_path + "output/SBS/" + genome + "_bench.SBS96.all"
new_matrix_3072 = vcf_path + "output/SBS/" + genome + "_bench.SBS6144.all"
#genome = "GRCh37"
############# Cosine Test ###################################################
data_orig = pd.read_csv(original_matrix_96, sep='\t', header=0)
data_new = pd.read_csv(new_matrix_96, sep='\t', header=0)
count = 0
range_count = min(len(data_orig.loc[0]), len(data_new.loc[0]))
for i in range (1, range_count, 1):
orig_list = list(data_orig[data_orig.columns[i]])
new_list = list(data_new[data_new.columns[i]])
cosine_result = (1-spatial.distance.cosine(orig_list,new_list))
if cosine_result != 1:
count += 1
if count != 0:
print("There seems to be some errors in the newly generated matrix. The installation may not have been successful.")
data_orig = pd.read_csv(original_matrix_3072, sep='\t', header=0)
data_new = pd.read_csv(new_matrix_3072, sep='\t', header=0)
count = 0
range_count = min(len(data_orig.loc[0]), len(data_new.loc[0]))
for i in range (1, range_count, 1):
orig_list = data_orig[data_orig.columns[i]]
new_list = data_new[data_new.columns[i]]
cosine_result = (1-spatial.distance.cosine(orig_list,new_list))
if cosine_result <= 0.85:
count += 1
if count != 0:
print("There seems to be some errors in the newly generated matrix. The installation may not have been successful.")
end_time = time.time()
print("Installation was succesful.\nSigProfilerMatrixGenerator took " + str(end_time-start_time) + " seconds to complete.")
def install (genome, custom=False, rsync=False, bash=True, ftp=True):
first_path= os.getcwd()
ref_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(ref_dir)
if os.path.exists("install.log"):
os.remove("install.log")
#ref_dir += "/references/"
chrom_string_dir = ref_dir + "/references/chromosomes/chrom_string/"
chrom_fasta_dir = ref_dir + "/references/chromosomes/fasta/"
chrom_tsb_dir = ref_dir + "/references/chromosomes/tsb/"
matrix_dir = ref_dir + "/references/matrix/"
vcf_dir = ref_dir + "/references/vcf_files/"
bed_dir = ref_dir + "/references/vcf_files/BED/"
log_dir = "logs/"
new_dirs = [ref_dir, chrom_string_dir, chrom_fasta_dir, chrom_tsb_dir, matrix_dir, vcf_dir, bed_dir, log_dir]
for dirs in new_dirs:
if not os.path.exists(dirs):
os.makedirs(dirs)
if ftp:
check_sum = {'GRCh37':
{'1':'a7d51305e943cf06ff2029146bd91bca','2':'d24d0185af89356d44614ab0d6fd6a68','3':'ea5e033147dcaf77bfd4c70f50688d37',
'4':'00d7797c7184f1802367e33f6e2bc3da','5':'f74b1eeb329088242a9f22a16322b325','6':'b353cc4c4abc90340e7747509fe7b457',
'7':'bbadde91b3ef958c7d20e2b1088c8cd2','8':'0ff695692e3efebaf00c7905d0d536d7','9':'40b75a18acb66748a37888c53a76dcdb',
'10':'557881b744a932b4ceee8a06d6de85a4','11':'f8b8f118101d7cb04164b29a7acadca4','12':'52c18e9fefc3ed3e35c1d8771d1247de',
'13':'a241d1cdcadccfd94db792300ab000bf','14':'ed3907128336795669bc19d77c0aa409','15':'bfc66ad087c4e9025076d7571cffa30e',
'16':'bd251fddc42400bb54ef95d5e1002ece','17':'fcd36b1bf5c4bd74328dc4caaae244ae','18':'e015d4324c36374827582c5b1214a736',
'19':'5cfa7d47e2d73dbdbf8d68f97c8e8b23','20':'2fa0717bf4e8dddac64cd393f4134ff5','21':'ba5559776d4601b80ca42c82f02102a4',
'22':'ba762b6ae493df40d04d1ff63d9b2933','Y':'0303100be91874b966a998273cd7c8eb','X':'14e331d82736f6cfc177ff8c90f7bd78',
'MT':'dfd6db5743d399516d5c8dadee5bee78'},
'GRCh38':
{'1':'ebe083105e7703a49581a36d73732a96','2':'cd65e36dbdf12a8ac3d2c70ebac8cad4','3':'6c20a7008394f2fa9c304d231a1f391b',
'4':'5c7443e1678868adadeac0e57558f6e8','5':'45573232c8097c679503a6598f61e60b','6':'cfc137c7434d3a9a872332d405b5c553',
'7':'9d8210c22c1962db837e7b62a578975c','8':'665134fd44f21915cbeef955addf89ba','9':'758d0c0c71d8bafbe1ede86587191730',
'10':'397bb21acff1ca3052ac802f2aee06e0','11':'07707ff8a2a964656469a7be7bb3e576','12':'506d02539075e080ee12ebdf63908080',
'13':'03ed22f01ab43145733c0b6a647e0560','14':'8b93447086549e476c65699ed813a567','15':'cd0dfe9fa78cae2fc7becf8f8ec6c693',
'16':'e17bbb66eb4d6b62b7b0e2fbf062b6a6','17':'8fc95bb3101d024d890aa3543eb454c5','18':'a4870628045bb033a90e8c89f818e24d',
'19':'6a9d0c8298f0ba2fa13180e02b969f16','20':'aa75d35969cf3956bb4ace7bdc57b34e','21':'5d55f5ad6271d6a0d8806876924990f7',
'22':'efdb4e1d23ab7964302b828062a33447','Y':'3b38c639ad164d60f1a055b46fcd2748','X':'d5edbea3cf5d1716765dd4a7b41b7656',
'MT':'dfd6db5743d399516d5c8dadee5bee78'},
'mm9':
{'1':'c5afc4b3f7f2119696214511d7a04341','2':'a7b467475a1b032d2c893dac1c419a28','3':'f922bc529a17324f1cd858f9a8723d65',
'4':'f3d6b74e3c04dbd229e2f1e363607506','5':'5fee4f1889c9fe20f7f8562c62bbeb0a','6':'481d47b87da45f3a20181c780fd796c2',
'7':'454ef2bf49a5ba8cfea3d16dfcfc7f25','8':'2f4162d4c824db78a2a2a820cb4fec81','9':'0649e6aec61af1ab8ab4797ea8e54119',
'10':'38296256bcfe886c8ae771418e4fd824','11':'b31cb0ce693e35eaa77031d44b12e474','12':'d2b3e4b015742b6aea30ceec5a972968',
'13':'df77b6d0ed1b133224b128c189736372','14':'0ec3c0e6b3fa2cdb957541f19792e130','15':'44fcaf2ec9b82dae910f85ce41c3cfad',
'16':'ad7a8dbdf46fa7077e0982a54eab70b7','17':'71aee1dee3cd2078e4619c485d88817e','18':'727ec4ed3128ecacd6cd2f7558083553',
'19':'461a7119781ab7f4b654fdd9ef76e0ec','Y':'471ff3bbb4520c020cfaa7ca8371c543','X':'9ccadf96cd3aa0ed9d299894a3d7fde0',
'MT':'a1d56043ed8308908965dd080a4d0c8d'},
'mm10':
{'1':'ef88c5ac276a32a2865c0408f92acd55','2':'ced7325ef9e2dfedea3fbe26428a6059','3':'9cd1794eeea27553077a018038303908',
'4':'da616d7ed6c67f824487eb2ed09cd33b','5':'b327b82da6986bf947105d07c0ad6d2e','6':'fb9a8fa0b85561f8d4de633c22d5157a',
'7':'12457fd80f6806779fc0d4cc8d36fbad','8':'5d98d86bd22bee1cb226406f49ee7caf','9':'b2f26613fcc622a4003e4c945ae55e25',
'10':'e9f3589529e258ede66d2e77bb87d21d','11':'76bcd285c3c66471ad6fccfabe42294c','12':'ac34fc3616c9609d8e75a59069e9007a',
'13':'f81b976e4e4617b25945d06f9aa30846','14':'95dc042eb2aa7d4cc0abe071d4d7966e','15':'fbf2477833aff73ae085537cd7ee0f85',
'16':'77cbcd009ba50891571f785595717ec1','17':'cd9e4dfdd168ed3de05dac4d44c6e692', '18':'945e83694c7c8f69d6186e1a2abc9771',
'19':'e57b25f8869de31a9dbce06510711db6','Y':'c2146ba4ab1ec262f5e38b2a1ebc5f5b','X':'9af543088be046fdc63976c2d41de94c',
'MT':'a1d56043ed8308908965dd080a4d0c8d'},
'rn6':
{'1':'003723513cbdb3708fcc5d737c05199c','2':'53e52c5facc7f05462be533845f37425','3':'8d157a9b71fe9770cf783ea5459b19d7',
'4':'a66dc1999bcc960ff11fe0b24c0d7b14','5':'601cf83411234adbdd9f911b89509564','6':'03b1f4af58fffdf213466ea85b570b3d',
'7':'4ed05ddf9502ef79e121c02e391660e6','8':'3e2458daaf1b3e8ab4d0e0a9e60c067b','9':'8f83caeccec7ea6e35e404737138ee67',
'10':'9c1af453a5facc9bfa821457bcfc4d30','11':'ef0480a905c55d76a3c58e295a85bc75','12':'643b6fe4a3a6363ffe64a6c316fa3e1a',
'13':'102bb3fb420a4104c216bcdf99870374','14':'e26b8b63fba0ea7ced4f0330e93a8cdc','15':'da747616a1362d374d4786102fab6f9f',
'16':'54e4f932eb0eda4cbf31156f96ef7235','17':'46c2facf5415e4eff8b0804161db722d', '18':'f1cb84f002967854b83bf266ec59a7a3',
'19':'b85ca155fd1780fe5c327a4589c212a6','20':'899d3511352d78b9b9dc63f063d91b31','Y':'6a7a3539c329dc540dfa6db006003bb1',
'X':'7a06bafab97c59a819f03633f0a6b7a2'},
'c_elegans':
{'I':'5a3ea8cf3dfbc641716b7bc805edcaae','II':'bf82edaa92809dd2fea2b791c38c9728','III':'d2df34b6743f41d3964549fc76c5f1a2',
'IV':'23396bb57145d3acde2888947b5b8c3a','V':'09df3c53b12e5fd7d9035cc98ca221a3','X':'988046456f1409dfdb5e26444d84d238',
'MtDNA':'48983f530959780de0125f74a87d4fc1'},
'dog':
{'1':'bef8283c1a36f9aef0e407de2ff6af00','2':'9cc961192bb5e58b3847060c3e9c1cfc','3':'d33263fa2de6666b41e140cb7a8da66c',
'4':'cd4ed39ebac1c04800ccf30466ec69f5','5':'c0f48a4a764e58388b48835aca2ec0a4','6':'4b472a2f8d0a53ac75cce04e7dc9279a',
'7':'12a61573a0da2c9306fff705bb1c39c1','8':'e22cf22a27560aa8523dc959ddcf6e25','9':'c079a73d719145cdd5c7c93969a1c392',
'10':'45805a518147f7846bd0457ca038c8df','11':'f38cda8508463a7607dff14a581ee7b0','12':'adb5de197f58bb827fa01fe924eb3a1d',
'13':'055a845ba97baad3b13d4d3359f88290','14':'27f0ba8e47996a058807a3827cf8e4a8','15':'2e9565c687a593eb0acbdd0962bb9255',
'16':'89b2225bb78d88b0fd1d38d9514ab0cb','17':'f0378253e2f083e42b665ea202fde3b0','18':'04d124e273f3b54a685ad6526223cd03',
'19':'67bae093919e6bb5ab6b9806c739d539','20':'5588387165a2e19c4533012cfb4998f3','21':'371cdf18a545728f7964b9db2fc72d5e',
'22':'fbf76865f88a018d93506e036f6a68bc','23':'085145e01d9fd9f0f999fb9e8e8d4400','24':'69b75a9962fb766b447e7d1252cb31ac',
'25':'12d5c6677b3e17170c317c1f5532d2a8','26':'13937d18e56b2b93d12fa5fcba48a138','27':'1d03d8ca5f201f4d156f5e1b38f7a67c',
'28':'c33395dec7fdc13e9d8f10afaa946f8c','29':'174f2db104ecaa5efef770f44241e3b0','30':'047d420ef9aecb933a7d83b6af820b23',
'31':'5be61f0c9944a5f2d7d1a5b2e75fb000','32':'212dcb867e95a642277a243fed8d8e41','33':'08a217b02cdd778cfdb0005dff4828b1',
'34':'4245d6fc370d9049ef4c25314fbef239','35':'1344aba8755b8a4e304629180fc0591a','36':'e4fff6ed84777905dc999ca6d6bc2557',
'37':'60d51ea6ae9e3f2fa316e3d03aff96b2','38':'4090ff76d94e6b38920916ae3ff2441c','X':'bce1372df64037d79b0995311d8ff971'}}
chromosome_fasta_path = ref_dir + "/references/chromosomes/tsb/"
print("Beginning installation. This may take up to 40 minutes to complete.")
if not rsync:
try:
if bash:
try:
os.system("bash -c '" + 'wget -r -l1 -c -nc --no-parent -nd -P ' + chromosome_fasta_path + 'ftp://alexandrovlab-ftp.ucsd.edu/pub/tools/SigProfilerMatrixGenerator/' + genome + '.tar.gz 2>> install.log' + "'")
except:
print("The UCSD ftp site is not responding...pulling from sanger ftp now.")
try:
os.system("bash -c '" + 'wget -r -l1 -c -nc --no-parent -nd -P ' + chromosome_fasta_path + ' ftp://ngs.sanger.ac.uk/scratch/project/mutographs/SigProf/' + genome + '.tar.gz 2>> install.log' + "'")
except:
print("The Sanger ftp site is not responding. Please check your internet connection/try again later.")
else:
os.system('wget -r -l1 -c -nc --no-parent -nd -P ' + chromosome_fasta_path + ' ftp://ngs.sanger.ac.uk/scratch/project/mutographs/SigProf/' + genome + '.tar.gz 2>> install.log')
os.system("tar -xzf " + ref_dir + "/references/chromosomes/tsb/" + genome + ".tar.gz -C " + ref_dir + "/references/chromosomes/tsb/")
os.remove(ref_dir + "/references/chromosomes/tsb/" + genome + ".tar.gz")
except:
print("The ensembl ftp site is not currently responding.")
sys.exit()
else:
print("Direct download for RSYNC is not yet supported")
sys.exit()
# try:
# if bash:
# os.system("bash -c '" + "rsync -av -m --include='*/' rsync://ftp.ngs.sanger.ac.uk/scratch/project/mutographs/SigProf/" + genome + ".tar.gz " + chromosome_fasta_path + " 2>&1>> install.log" + "'")
# else:
# os.system("rsync -av -m rsync://ftp://ngs.sanger.ac.uk/scratch/project/mutographs/SigProf/" + genome + ".tar.gz " + chromosome_fasta_path + " 2>&1>> install.log")
# os.system("tar -xzf " + ref_dir + "/references/chromosomes/tsb/" + genome + ".tar.gz -C " + ref_dir + "/references/chromosomes/tsb/")
# os.remove(ref_dir + "/references/chromosomes/tsb/" + genome + ".tar.gz")
# except:
# print("The ensembl ftp site is not currently responding.")
# sys.exit()
chromosome_TSB_path = chromosome_fasta_path + genome + "/"
corrupt = False
for files in os.listdir(chromosome_TSB_path):
if "proportions" in files:
continue
if ".DS_Store" in files:
continue
chrom = files.split(".")
chrom = chrom[0]
check = md5(chromosome_TSB_path + files)
if check_sum[genome][chrom] != check:
corrupt = True
os.remove(chromosome_TSB_path + files)
print("[DEBUG] Chromosome " + chrom + " md5sum did not match => reference md5sum: " + str(check_sum[genome][chrom]) + " new file md5sum: " + str(check))
if corrupt:
print("The transcriptional reference data appears to be corrupted. Please reinstall the " + genome + " genome.")
sys.exit()
print("The transcriptional reference data for " + genome + " has been saved.")
else:
print("Beginning installation. This may take up to 20 minutes to complete.")
first_path = os.getcwd()
ref_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(ref_dir)
print("[DEBUG] Path to SigProfilerMatrixGenerator used for the install: ", ref_dir)
genomes = [genome]
if os.path.exists("install.log"):
os.remove("install.log")
# ref_dir += "/references/"
# chrom_string_dir = ref_dir + "chromosomes/chrom_string/"
# chrom_fasta_dir = ref_dir + "chromosomes/fasta/"
# chrom_tsb_dir = ref_dir + "chromosomes/tsb/"
# matrix_dir = ref_dir + "matrix/"
# vcf_dir = ref_dir + "vcf_files/"
# bed_dir = ref_dir + "vcf_files/BED/"
# log_dir = "logs/"
# new_dirs = [ref_dir, chrom_string_dir, chrom_fasta_dir, chrom_tsb_dir, matrix_dir, vcf_dir, bed_dir, log_dir]
# for dirs in new_dirs:
# if not os.path.exists(dirs):
# os.makedirs(dirs)
install_chromosomes(genomes, ref_dir, custom, rsync, bash)
install_chromosomes_tsb (genomes, ref_dir, custom)
if os.path.exists("BRCA_example/"):
shutil.copy("BRCA_example/", "references/vcf_files/")
if os.path.exists("example_test"):
shutil.copy("example_test/", "references/vcf_files/")
if os.path.exists("context_distributions/"):
shutil.copy("context_distributions/", "references/chromosomes/")
print("All reference files have been created.")
if genome != "rn6" and genome != 'dog' and genome != 'c_elegans':
print("Verifying and benchmarking installation now...")
benchmark(genome, ref_dir)
print ("To proceed with matrix_generation, please provide the path to your vcf files and an appropriate output path.")
shutil.rmtree(chrom_string_dir)
print("Installation complete.")
os.chdir(first_path)
def main ():
first_path= os.getcwd()
os.chdir(first_path + "/sigProfilerMatrixGenerator/")
genomes = ['mm9', 'mm10','GRCh37', 'GRCh38' ]
#genomes = ['GRCh37']
custom = False
parser = argparse.ArgumentParser(description="Provide the necessary arguments to install the reference files.")
parser.add_argument("-g", "--genome", nargs='?', help="Optional parameter instructs script to install the custom genome.")
parser.add_argument("-ct", "--custom", help="Optional parameter instructs script to create the reference files for a custom genome", action='store_true')
args = parser.parse_args()
if args.genome:
genomes = [args.genome]
if args.custom:
custom = True
if os.path.exists("install.log"):
os.system("rm install.log")
ref_dir = "references/"
chrom_string_dir = ref_dir + "chromosomes/chrom_string/"
chrom_fasta_dir = ref_dir + "chromosomes/fasta/"
chrom_tsb_dir = ref_dir + "chromosomes/tsb/"
matrix_dir = ref_dir + "matrix/"
vcf_dir = ref_dir + "vcf_files/"
bed_dir = ref_dir + "vcf_files/BED/"
log_dir = "logs/"
new_dirs = [ref_dir, chrom_string_dir, chrom_fasta_dir, chrom_tsb_dir, matrix_dir, vcf_dir, bed_dir, log_dir]
current_dir = os.getcwd()
for dirs in new_dirs:
if not os.path.exists(dirs):
os.makedirs(dirs)
install_chromosomes(genomes, ref_dir, custom)
install_chromosomes_tsb (genomes, ref_dir, custom)
#install_chromosomes_tsb_BED (genomes, custom, ref_dir)
if os.path.exists("BRCA_example/"):
os.system("mv BRCA_example/ references/vcf_files/")
if os.path.exists("example_test"):
os.system("mv example_test/ references/vcf_files/")
if os.path.exists("context_distributions/"):
os.system("mv context_distributions/ references/chromosomes/")
if os.path.exists(chrom_tsb_dir + "GRCh37/"):
print("All reference files have been created.\nVerifying and benchmarking installation now...")
benchmark(ref_dir)
else:
print("All reference files have been created.")
print ("Please place your vcf files for each sample into the 'references/vcf_files/[test]/[mutation_type]/' directory. Once you have done that, you can proceed with the matrix generation.")
#os.system("rm -r " + chrom_string_dir)
print("Installation complete.")
os.chdir(first_path)
if __name__ == '__main__':
main() | 61.255692 | 245 | 0.714527 |
from __future__ import print_function
import os
import sys
import re
import subprocess
import argparse
import time
from scipy import spatial
import pandas as pd
import shutil
import logging
import hashlib
from SigProfilerMatrixGenerator.scripts import convert_input_to_simple_files as convertIn
from SigProfilerMatrixGenerator.scripts import SigProfilerMatrixGeneratorFunc as matGen
def md5(fname):
hash_md5 = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return (hash_md5.hexdigest())
def install_chromosomes (genomes, ref_dir, custom, rsync, bash):
if custom:
for genome in genomes:
os.system("gzip -d references/chromosomes/fasta/" + genome + "/*.gz")
chromosome_fasta_path = "references/chromosomes/fasta/" + genome + "/"
os.system("python scripts/save_chrom_strings.py -g " + genome)
print("Chromosome string files for " + genome + " have been created. Continuing with installation.")
else:
for genome in genomes:
species = None
chrom_number = None
if genome == 'GRCh37' or genome == 'GRCh38':
species = "homo_sapiens"
chrom_number = 24
elif genome == 'mm10' or genome == 'mm9':
species = "mus_musculus"
chrom_number = 21
elif genome == 'rn6':
species = 'rattus_norvegicus'
chrom_number = 22
else:
print(genome + " is not supported. The following genomes are supported:\nGRCh37, GRCh38, mm10")
sys.exit()
chromosome_string_path = "references/chromosomes/chrom_string/" + genome + "/"
chromosome_fasta_path = "references/chromosomes/fasta/" + genome + "/"
if os.path.exists(ref_dir + "chromosomes/tsb/" + genome) and len(os.listdir(ref_dir + "chromosomes/tsb/" + genome)) >= chrom_number:
break
wget_flag = True
if os.path.exists(chromosome_string_path) == False or len(os.listdir(chromosome_string_path)) <= chrom_number:
print("[DEBUG] Chromosome string files found at: " + ref_dir + chromosome_string_path)
if os.path.exists(chromosome_fasta_path) == False or len(os.listdir(chromosome_fasta_path)) <= chrom_number:
print("[DEBUG] Chromosome fasta files found at: " + ref_dir + chromosome_fasta_path)
print("Chromosomes are not currently saved as individual text files for " + genome + ". Downloading the files now...")
if not rsync:
if wget_flag:
try:
if genome == 'GRCh37':
if bash:
os.system("bash -c '" + 'wget -r -l1 -c -nc --no-parent -A "*.dna.chromosome.*" -nd -P ' + chromosome_fasta_path + ' ftp://ftp.ensembl.org/pub/grch37/current/fasta/homo_sapiens/dna/ 2>> install.log' + "'")
else:
os.system('wget -r -l1 -c -nc --no-parent -A "*.dna.chromosome.*" -nd -P ' + chromosome_fasta_path + ' ftp://ftp.ensembl.org/pub/grch37/current/fasta/homo_sapiens/dna/ 2>> install.log')
elif genome == 'mm9':
if bash:
os.system("bash -c '" + 'wget -r -l1 -c -nc --no-parent -A "*.dna.chromosome.*" -nd -P ' + chromosome_fasta_path + ' ftp://ftp.ensembl.org/pub/release-67/fasta/mus_musculus/dna/ 2>> install.log' + "'")
else:
os.system('wget -r -l1 -c -nc --no-parent -A "*.dna.chromosome.*" -nd -P ' + chromosome_fasta_path + ' ftp://ftp.ensembl.org/pub/release-67/fasta/mus_musculus/dna/ 2>> install.log')
elif genome == 'rn6':
if bash:
os.system("bash -c '" + 'wget -r -l1 -c -nc --no-parent -A "*.dna.chromosome.*" -nd -P ' + chromosome_fasta_path + ' ftp://ftp.ensembl.org/pub/release-96/fasta/rattus_norvegicus/dna/ 2>> install.log' + "'")
else:
os.system('wget -r -l1 -c -nc --no-parent -A "*.dna.chromosome.*" -nd -P ' + chromosome_fasta_path + ' ftp://ftp.ensembl.org/pub/release-96/fasta/rattus_norvegicus/dna/ 2>> install.log')
else:
if bash:
os.system("bash -c '" + 'wget -r -l1 -c -nc --no-parent -A "*.dna.chromosome.*" -nd -P ' + chromosome_fasta_path + ' ftp://ftp.ensembl.org/pub/release-93/fasta/' +species+'/dna/ 2>> install.log' + "'")
else:
os.system('wget -r -l1 -c -nc --no-parent -A "*.dna.chromosome.*" -nd -P ' + chromosome_fasta_path + ' ftp://ftp.ensembl.org/pub/release-93/fasta/' +species+'/dna/ 2>> install.log')
os.system("gzip -d references/chromosomes/fasta/" + genome + "/*.gz")
except:
print("The ensembl ftp site is not currently responding.")
sys.exit()
else:
try:
if genome == 'GRCh37':
if bash:
os.system("bash -c '" + "rsync -av -m --include='*/' --include='*.dna.chromosome.*' --exclude='*' rsync://ftp.ensembl.org/ensembl/pub/grch37/current/fasta/homo_sapiens/dna/ " + chromosome_fasta_path + " 2>&1>> install.log" + "'")
else:
os.system("rsync -av -m --include='*/' --include='*.dna.chromosome.*' --exclude='*' rsync://ftp.ensembl.org/ensembl/pub/grch37/current/fasta/homo_sapiens/dna/ " + chromosome_fasta_path + " 2>&1>> install.log")
elif genome == 'mm9':
if bash:
os.system("bash -c '" + "rsync -av -m --include='*/' --include='*.dna.chromosome.*' --exclude='*' rsync://ftp.ensembl.org/ensembl/pub/release-67/fasta/mus_musculus/dna/ " + chromosome_fasta_path + " 2>&1>> install.log" + "'")
else:
os.system("rsync -av -m --include='*/' --include='*.dna.chromosome.*' --exclude='*' rsync://ftp.ensembl.org/ensembl/pub/release-67/fasta/mus_musculus/dna/ " + chromosome_fasta_path + " 2>&1>> install.log")
elif genome == 'rn6':
if bash:
os.system("bash -c '" + "rsync -av -m --include='*/' --include='*.dna.chromosome.*' --exclude='*' rsync://ftp.ensembl.org/ensembl/pub/release-96/fasta/rattus_norvegicus/dna/ " + chromosome_fasta_path + " 2>> install.log" + "'")
else:
os.system("rsync -av -m --include='*/' --include='*.dna.chromosome.*' --exclude='*' rsync://ftp.ensembl.org/ensembl/pub/release-96/fasta/rattus_norvegicus/dna/ " + chromosome_fasta_path + " 2>> install.log")
else:
if bash:
os.system("bash -c '" + "rsync -av -m --include='*/' --include='*.dna.chromosome.*' --exclude='*' rsync://ftp.ensembl.org/ensembl/pub/release-93/fasta/"+species+"/dna/ " + chromosome_fasta_path + " 2>&1>> install.log" + "'")
else:
os.system("rsync -av -m --include='*/' --include='*.dna.chromosome.*' --exclude='*' rsync://ftp.ensembl.org/ensembl/pub/release-93/fasta/"+species+"/dna/ " + chromosome_fasta_path + " 2>&1>> install.log")
os.system("gzip -d references/chromosomes/fasta/" + genome + "/*.gz")
except:
print("The ensembl ftp site is not currently responding.")
sys.exit()
print("Chromosome fasta files for " + genome + " have been installed. Creating the chromosome string files now...")
os.system("python scripts/save_chrom_strings.py -g " + genome)
print("Chromosome string files for " + genome + " have been created. Continuing with installation.")
shutil.rmtree(chromosome_fasta_path)
else:
print("Chromosome reference files exist for " + genome + ". Continuing with installation.")
def install_chromosomes_tsb (genomes, ref_dir, custom):
check_sum = {'GRCh37':
{'1':'a7d51305e943cf06ff2029146bd91bca','2':'d24d0185af89356d44614ab0d6fd6a68','3':'ea5e033147dcaf77bfd4c70f50688d37',
'4':'00d7797c7184f1802367e33f6e2bc3da','5':'f74b1eeb329088242a9f22a16322b325','6':'b353cc4c4abc90340e7747509fe7b457',
'7':'bbadde91b3ef958c7d20e2b1088c8cd2','8':'0ff695692e3efebaf00c7905d0d536d7','9':'40b75a18acb66748a37888c53a76dcdb',
'10':'557881b744a932b4ceee8a06d6de85a4','11':'f8b8f118101d7cb04164b29a7acadca4','12':'52c18e9fefc3ed3e35c1d8771d1247de',
'13':'a241d1cdcadccfd94db792300ab000bf','14':'ed3907128336795669bc19d77c0aa409','15':'bfc66ad087c4e9025076d7571cffa30e',
'16':'bd251fddc42400bb54ef95d5e1002ece','17':'fcd36b1bf5c4bd74328dc4caaae244ae','18':'e015d4324c36374827582c5b1214a736',
'19':'5cfa7d47e2d73dbdbf8d68f97c8e8b23','20':'2fa0717bf4e8dddac64cd393f4134ff5','21':'ba5559776d4601b80ca42c82f02102a4',
'22':'ba762b6ae493df40d04d1ff63d9b2933','Y':'0303100be91874b966a998273cd7c8eb','X':'14e331d82736f6cfc177ff8c90f7bd78',
'MT':'dfd6db5743d399516d5c8dadee5bee78'},
'GRCh38':
{'1':'ebe083105e7703a49581a36d73732a96','2':'cd65e36dbdf12a8ac3d2c70ebac8cad4','3':'6c20a7008394f2fa9c304d231a1f391b',
'4':'5c7443e1678868adadeac0e57558f6e8','5':'45573232c8097c679503a6598f61e60b','6':'cfc137c7434d3a9a872332d405b5c553',
'7':'9d8210c22c1962db837e7b62a578975c','8':'665134fd44f21915cbeef955addf89ba','9':'758d0c0c71d8bafbe1ede86587191730',
'10':'397bb21acff1ca3052ac802f2aee06e0','11':'07707ff8a2a964656469a7be7bb3e576','12':'506d02539075e080ee12ebdf63908080',
'13':'03ed22f01ab43145733c0b6a647e0560','14':'8b93447086549e476c65699ed813a567','15':'cd0dfe9fa78cae2fc7becf8f8ec6c693',
'16':'e17bbb66eb4d6b62b7b0e2fbf062b6a6','17':'8fc95bb3101d024d890aa3543eb454c5','18':'a4870628045bb033a90e8c89f818e24d',
'19':'6a9d0c8298f0ba2fa13180e02b969f16','20':'aa75d35969cf3956bb4ace7bdc57b34e','21':'5d55f5ad6271d6a0d8806876924990f7',
'22':'efdb4e1d23ab7964302b828062a33447','Y':'3b38c639ad164d60f1a055b46fcd2748','X':'d5edbea3cf5d1716765dd4a7b41b7656',
'MT':'dfd6db5743d399516d5c8dadee5bee78'},
'mm9':
{'1':'c5afc4b3f7f2119696214511d7a04341','2':'a7b467475a1b032d2c893dac1c419a28','3':'f922bc529a17324f1cd858f9a8723d65',
'4':'f3d6b74e3c04dbd229e2f1e363607506','5':'5fee4f1889c9fe20f7f8562c62bbeb0a','6':'481d47b87da45f3a20181c780fd796c2',
'7':'454ef2bf49a5ba8cfea3d16dfcfc7f25','8':'2f4162d4c824db78a2a2a820cb4fec81','9':'0649e6aec61af1ab8ab4797ea8e54119',
'10':'38296256bcfe886c8ae771418e4fd824','11':'b31cb0ce693e35eaa77031d44b12e474','12':'d2b3e4b015742b6aea30ceec5a972968',
'13':'df77b6d0ed1b133224b128c189736372','14':'0ec3c0e6b3fa2cdb957541f19792e130','15':'44fcaf2ec9b82dae910f85ce41c3cfad',
'16':'ad7a8dbdf46fa7077e0982a54eab70b7','17':'71aee1dee3cd2078e4619c485d88817e','18':'727ec4ed3128ecacd6cd2f7558083553',
'19':'461a7119781ab7f4b654fdd9ef76e0ec','Y':'471ff3bbb4520c020cfaa7ca8371c543','X':'9ccadf96cd3aa0ed9d299894a3d7fde0',
'MT':'a1d56043ed8308908965dd080a4d0c8d'},
'mm10':
{'1':'ef88c5ac276a32a2865c0408f92acd55','2':'ced7325ef9e2dfedea3fbe26428a6059','3':'9cd1794eeea27553077a018038303908',
'4':'da616d7ed6c67f824487eb2ed09cd33b','5':'b327b82da6986bf947105d07c0ad6d2e','6':'fb9a8fa0b85561f8d4de633c22d5157a',
'7':'12457fd80f6806779fc0d4cc8d36fbad','8':'5d98d86bd22bee1cb226406f49ee7caf','9':'b2f26613fcc622a4003e4c945ae55e25',
'10':'e9f3589529e258ede66d2e77bb87d21d','11':'76bcd285c3c66471ad6fccfabe42294c','12':'ac34fc3616c9609d8e75a59069e9007a',
'13':'f81b976e4e4617b25945d06f9aa30846','14':'95dc042eb2aa7d4cc0abe071d4d7966e','15':'fbf2477833aff73ae085537cd7ee0f85',
'16':'77cbcd009ba50891571f785595717ec1','17':'cd9e4dfdd168ed3de05dac4d44c6e692', '18':'945e83694c7c8f69d6186e1a2abc9771',
'19':'e57b25f8869de31a9dbce06510711db6','Y':'c2146ba4ab1ec262f5e38b2a1ebc5f5b','X':'9af543088be046fdc63976c2d41de94c',
'MT':'a1d56043ed8308908965dd080a4d0c8d'},
'rn6':
{'1':'003723513cbdb3708fcc5d737c05199c','2':'53e52c5facc7f05462be533845f37425','3':'8d157a9b71fe9770cf783ea5459b19d7',
'4':'a66dc1999bcc960ff11fe0b24c0d7b14','5':'601cf83411234adbdd9f911b89509564','6':'03b1f4af58fffdf213466ea85b570b3d',
'7':'4ed05ddf9502ef79e121c02e391660e6','8':'3e2458daaf1b3e8ab4d0e0a9e60c067b','9':'8f83caeccec7ea6e35e404737138ee67',
'10':'9c1af453a5facc9bfa821457bcfc4d30','11':'ef0480a905c55d76a3c58e295a85bc75','12':'643b6fe4a3a6363ffe64a6c316fa3e1a',
'13':'102bb3fb420a4104c216bcdf99870374','14':'e26b8b63fba0ea7ced4f0330e93a8cdc','15':'da747616a1362d374d4786102fab6f9f',
'16':'54e4f932eb0eda4cbf31156f96ef7235','17':'46c2facf5415e4eff8b0804161db722d', '18':'f1cb84f002967854b83bf266ec59a7a3',
'19':'b85ca155fd1780fe5c327a4589c212a6','20':'899d3511352d78b9b9dc63f063d91b31','Y':'6a7a3539c329dc540dfa6db006003bb1',
'X':'7a06bafab97c59a819f03633f0a6b7a2'},
'c_elegans':
{'I':'5a3ea8cf3dfbc641716b7bc805edcaae','II':'bf82edaa92809dd2fea2b791c38c9728','III':'d2df34b6743f41d3964549fc76c5f1a2',
'IV':'23396bb57145d3acde2888947b5b8c3a','V':'09df3c53b12e5fd7d9035cc98ca221a3','X':'988046456f1409dfdb5e26444d84d238',
'MtDNA':'48983f530959780de0125f74a87d4fc1'},
'dog':
{'1':'bef8283c1a36f9aef0e407de2ff6af00','2':'9cc961192bb5e58b3847060c3e9c1cfc','3':'d33263fa2de6666b41e140cb7a8da66c',
'4':'cd4ed39ebac1c04800ccf30466ec69f5','5':'c0f48a4a764e58388b48835aca2ec0a4','6':'4b472a2f8d0a53ac75cce04e7dc9279a',
'7':'12a61573a0da2c9306fff705bb1c39c1','8':'e22cf22a27560aa8523dc959ddcf6e25','9':'c079a73d719145cdd5c7c93969a1c392',
'10':'45805a518147f7846bd0457ca038c8df','11':'f38cda8508463a7607dff14a581ee7b0','12':'adb5de197f58bb827fa01fe924eb3a1d',
'13':'055a845ba97baad3b13d4d3359f88290','14':'27f0ba8e47996a058807a3827cf8e4a8','15':'2e9565c687a593eb0acbdd0962bb9255',
'16':'89b2225bb78d88b0fd1d38d9514ab0cb','17':'f0378253e2f083e42b665ea202fde3b0','18':'04d124e273f3b54a685ad6526223cd03',
'19':'67bae093919e6bb5ab6b9806c739d539','20':'5588387165a2e19c4533012cfb4998f3','21':'371cdf18a545728f7964b9db2fc72d5e',
'22':'fbf76865f88a018d93506e036f6a68bc','23':'085145e01d9fd9f0f999fb9e8e8d4400','24':'69b75a9962fb766b447e7d1252cb31ac',
'25':'12d5c6677b3e17170c317c1f5532d2a8','26':'13937d18e56b2b93d12fa5fcba48a138','27':'1d03d8ca5f201f4d156f5e1b38f7a67c',
'28':'c33395dec7fdc13e9d8f10afaa946f8c','29':'174f2db104ecaa5efef770f44241e3b0','30':'047d420ef9aecb933a7d83b6af820b23',
'31':'5be61f0c9944a5f2d7d1a5b2e75fb000','32':'212dcb867e95a642277a243fed8d8e41','33':'08a217b02cdd778cfdb0005dff4828b1',
'34':'4245d6fc370d9049ef4c25314fbef239','35':'1344aba8755b8a4e304629180fc0591a','36':'e4fff6ed84777905dc999ca6d6bc2557',
'37':'60d51ea6ae9e3f2fa316e3d03aff96b2','38':'4090ff76d94e6b38920916ae3ff2441c','X':'bce1372df64037d79b0995311d8ff971'}}
for genome in genomes:
chrom_number = None
if genome == 'GRCh37' or genome == 'GRCh38':
chrom_number = 24
elif genome == 'mm10' or genome == 'mm9':
chrom_number = 21
elif genome == 'rn6':
chrom_number = 22
chromosome_TSB_path = "references/chromosomes/tsb/" + genome + "/"
transcript_files = "references/chromosomes/transcripts/" + genome + "/"
print("[DEBUG] Chromosome tsb files found at: " + ref_dir + chromosome_TSB_path)
if os.path.exists(transcript_files) == False or len(os.listdir(transcript_files)) < 1:
print("Please download the transcript files before proceeding. You can download the files from 'http://www.ensembl.org/biomart/martview'.")
print("Follow the format presented in the README file:\n\n\tGene stable ID Transcript stable ID Chromosome/scaffold name Strand Transcript start (bp) Transcript end (bp)\n\n\n")
sys.exit()
if os.path.exists(chromosome_TSB_path) == False or len(os.listdir(chromosome_TSB_path)) < chrom_number:
print("The transcriptional reference data for " + genome + " has not been saved. Creating these files now")
os.system("python scripts/save_tsb_192.py -g " + genome)
corrupt = False
for files in os.listdir(chromosome_TSB_path):
if "proportions" in files:
continue
if ".DS_Store" in files:
continue
chrom = files.split(".")
chrom = chrom[0]
check = md5(chromosome_TSB_path + files)
if check_sum[genome][chrom] != check:
corrupt = True
os.remove(chromosome_TSB_path + files)
print("[DEBUG] Chromosome " + chrom + " md5sum did not match => reference md5sum: " + str(check_sum[genome][chrom]) + " new file md5sum: " + str(check))
if corrupt:
print("The transcriptional reference data appears to be corrupted. Please reinstall the " + genome + " genome.")
sys.exit()
print("The transcriptional reference data for " + genome + " has been saved.")
def install_chromosomes_tsb_BED (genomes, custom, ref_dir):
for genome in genomes:
if not os.path.exists(ref_dir + "chromosomes/tsb_BED/" + genome + "/") or len(os.listdir(ref_dir + "chromosomes/tsb_BED/" + genome + "/")) < 19:
os.system("python scripts/save_chrom_tsb_separate.py -g " + genome)
print("The TSB BED files for " + genome + " have been saved.")
def benchmark (genome, ref_dir):
ref_dir = os.path.dirname(os.path.abspath(__file__))
vcf_path = ref_dir + "/references/vcf_files/" + genome + "_bench/"
start_time = time.time()
matGen.SigProfilerMatrixGeneratorFunc(genome + "_bench", genome, vcf_path)
end_time = time.time()
original_matrix_96 = ref_dir + "/scripts/Benchmark/" + genome + "_bench_orig_96.txt"
original_matrix_3072 = ref_dir + "/scripts/Benchmark/" + genome + "_bench_orig_3072.txt"
new_matrix_96 = vcf_path + "output/SBS/" + genome + "_bench.SBS96.all"
new_matrix_3072 = vcf_path + "output/SBS/" + genome + "_bench.SBS6144.all"
05e943cf06ff2029146bd91bca','2':'d24d0185af89356d44614ab0d6fd6a68','3':'ea5e033147dcaf77bfd4c70f50688d37',
'4':'00d7797c7184f1802367e33f6e2bc3da','5':'f74b1eeb329088242a9f22a16322b325','6':'b353cc4c4abc90340e7747509fe7b457',
'7':'bbadde91b3ef958c7d20e2b1088c8cd2','8':'0ff695692e3efebaf00c7905d0d536d7','9':'40b75a18acb66748a37888c53a76dcdb',
'10':'557881b744a932b4ceee8a06d6de85a4','11':'f8b8f118101d7cb04164b29a7acadca4','12':'52c18e9fefc3ed3e35c1d8771d1247de',
'13':'a241d1cdcadccfd94db792300ab000bf','14':'ed3907128336795669bc19d77c0aa409','15':'bfc66ad087c4e9025076d7571cffa30e',
'16':'bd251fddc42400bb54ef95d5e1002ece','17':'fcd36b1bf5c4bd74328dc4caaae244ae','18':'e015d4324c36374827582c5b1214a736',
'19':'5cfa7d47e2d73dbdbf8d68f97c8e8b23','20':'2fa0717bf4e8dddac64cd393f4134ff5','21':'ba5559776d4601b80ca42c82f02102a4',
'22':'ba762b6ae493df40d04d1ff63d9b2933','Y':'0303100be91874b966a998273cd7c8eb','X':'14e331d82736f6cfc177ff8c90f7bd78',
'MT':'dfd6db5743d399516d5c8dadee5bee78'},
'GRCh38':
{'1':'ebe083105e7703a49581a36d73732a96','2':'cd65e36dbdf12a8ac3d2c70ebac8cad4','3':'6c20a7008394f2fa9c304d231a1f391b',
'4':'5c7443e1678868adadeac0e57558f6e8','5':'45573232c8097c679503a6598f61e60b','6':'cfc137c7434d3a9a872332d405b5c553',
'7':'9d8210c22c1962db837e7b62a578975c','8':'665134fd44f21915cbeef955addf89ba','9':'758d0c0c71d8bafbe1ede86587191730',
'10':'397bb21acff1ca3052ac802f2aee06e0','11':'07707ff8a2a964656469a7be7bb3e576','12':'506d02539075e080ee12ebdf63908080',
'13':'03ed22f01ab43145733c0b6a647e0560','14':'8b93447086549e476c65699ed813a567','15':'cd0dfe9fa78cae2fc7becf8f8ec6c693',
'16':'e17bbb66eb4d6b62b7b0e2fbf062b6a6','17':'8fc95bb3101d024d890aa3543eb454c5','18':'a4870628045bb033a90e8c89f818e24d',
'19':'6a9d0c8298f0ba2fa13180e02b969f16','20':'aa75d35969cf3956bb4ace7bdc57b34e','21':'5d55f5ad6271d6a0d8806876924990f7',
'22':'efdb4e1d23ab7964302b828062a33447','Y':'3b38c639ad164d60f1a055b46fcd2748','X':'d5edbea3cf5d1716765dd4a7b41b7656',
'MT':'dfd6db5743d399516d5c8dadee5bee78'},
'mm9':
{'1':'c5afc4b3f7f2119696214511d7a04341','2':'a7b467475a1b032d2c893dac1c419a28','3':'f922bc529a17324f1cd858f9a8723d65',
'4':'f3d6b74e3c04dbd229e2f1e363607506','5':'5fee4f1889c9fe20f7f8562c62bbeb0a','6':'481d47b87da45f3a20181c780fd796c2',
'7':'454ef2bf49a5ba8cfea3d16dfcfc7f25','8':'2f4162d4c824db78a2a2a820cb4fec81','9':'0649e6aec61af1ab8ab4797ea8e54119',
'10':'38296256bcfe886c8ae771418e4fd824','11':'b31cb0ce693e35eaa77031d44b12e474','12':'d2b3e4b015742b6aea30ceec5a972968',
'13':'df77b6d0ed1b133224b128c189736372','14':'0ec3c0e6b3fa2cdb957541f19792e130','15':'44fcaf2ec9b82dae910f85ce41c3cfad',
'16':'ad7a8dbdf46fa7077e0982a54eab70b7','17':'71aee1dee3cd2078e4619c485d88817e','18':'727ec4ed3128ecacd6cd2f7558083553',
'19':'461a7119781ab7f4b654fdd9ef76e0ec','Y':'471ff3bbb4520c020cfaa7ca8371c543','X':'9ccadf96cd3aa0ed9d299894a3d7fde0',
'MT':'a1d56043ed8308908965dd080a4d0c8d'},
'mm10':
{'1':'ef88c5ac276a32a2865c0408f92acd55','2':'ced7325ef9e2dfedea3fbe26428a6059','3':'9cd1794eeea27553077a018038303908',
'4':'da616d7ed6c67f824487eb2ed09cd33b','5':'b327b82da6986bf947105d07c0ad6d2e','6':'fb9a8fa0b85561f8d4de633c22d5157a',
'7':'12457fd80f6806779fc0d4cc8d36fbad','8':'5d98d86bd22bee1cb226406f49ee7caf','9':'b2f26613fcc622a4003e4c945ae55e25',
'10':'e9f3589529e258ede66d2e77bb87d21d','11':'76bcd285c3c66471ad6fccfabe42294c','12':'ac34fc3616c9609d8e75a59069e9007a',
'13':'f81b976e4e4617b25945d06f9aa30846','14':'95dc042eb2aa7d4cc0abe071d4d7966e','15':'fbf2477833aff73ae085537cd7ee0f85',
'16':'77cbcd009ba50891571f785595717ec1','17':'cd9e4dfdd168ed3de05dac4d44c6e692', '18':'945e83694c7c8f69d6186e1a2abc9771',
'19':'e57b25f8869de31a9dbce06510711db6','Y':'c2146ba4ab1ec262f5e38b2a1ebc5f5b','X':'9af543088be046fdc63976c2d41de94c',
'MT':'a1d56043ed8308908965dd080a4d0c8d'},
'rn6':
{'1':'003723513cbdb3708fcc5d737c05199c','2':'53e52c5facc7f05462be533845f37425','3':'8d157a9b71fe9770cf783ea5459b19d7',
'4':'a66dc1999bcc960ff11fe0b24c0d7b14','5':'601cf83411234adbdd9f911b89509564','6':'03b1f4af58fffdf213466ea85b570b3d',
'7':'4ed05ddf9502ef79e121c02e391660e6','8':'3e2458daaf1b3e8ab4d0e0a9e60c067b','9':'8f83caeccec7ea6e35e404737138ee67',
'10':'9c1af453a5facc9bfa821457bcfc4d30','11':'ef0480a905c55d76a3c58e295a85bc75','12':'643b6fe4a3a6363ffe64a6c316fa3e1a',
'13':'102bb3fb420a4104c216bcdf99870374','14':'e26b8b63fba0ea7ced4f0330e93a8cdc','15':'da747616a1362d374d4786102fab6f9f',
'16':'54e4f932eb0eda4cbf31156f96ef7235','17':'46c2facf5415e4eff8b0804161db722d', '18':'f1cb84f002967854b83bf266ec59a7a3',
'19':'b85ca155fd1780fe5c327a4589c212a6','20':'899d3511352d78b9b9dc63f063d91b31','Y':'6a7a3539c329dc540dfa6db006003bb1',
'X':'7a06bafab97c59a819f03633f0a6b7a2'},
'c_elegans':
{'I':'5a3ea8cf3dfbc641716b7bc805edcaae','II':'bf82edaa92809dd2fea2b791c38c9728','III':'d2df34b6743f41d3964549fc76c5f1a2',
'IV':'23396bb57145d3acde2888947b5b8c3a','V':'09df3c53b12e5fd7d9035cc98ca221a3','X':'988046456f1409dfdb5e26444d84d238',
'MtDNA':'48983f530959780de0125f74a87d4fc1'},
'dog':
{'1':'bef8283c1a36f9aef0e407de2ff6af00','2':'9cc961192bb5e58b3847060c3e9c1cfc','3':'d33263fa2de6666b41e140cb7a8da66c',
'4':'cd4ed39ebac1c04800ccf30466ec69f5','5':'c0f48a4a764e58388b48835aca2ec0a4','6':'4b472a2f8d0a53ac75cce04e7dc9279a',
'7':'12a61573a0da2c9306fff705bb1c39c1','8':'e22cf22a27560aa8523dc959ddcf6e25','9':'c079a73d719145cdd5c7c93969a1c392',
'10':'45805a518147f7846bd0457ca038c8df','11':'f38cda8508463a7607dff14a581ee7b0','12':'adb5de197f58bb827fa01fe924eb3a1d',
'13':'055a845ba97baad3b13d4d3359f88290','14':'27f0ba8e47996a058807a3827cf8e4a8','15':'2e9565c687a593eb0acbdd0962bb9255',
'16':'89b2225bb78d88b0fd1d38d9514ab0cb','17':'f0378253e2f083e42b665ea202fde3b0','18':'04d124e273f3b54a685ad6526223cd03',
'19':'67bae093919e6bb5ab6b9806c739d539','20':'5588387165a2e19c4533012cfb4998f3','21':'371cdf18a545728f7964b9db2fc72d5e',
'22':'fbf76865f88a018d93506e036f6a68bc','23':'085145e01d9fd9f0f999fb9e8e8d4400','24':'69b75a9962fb766b447e7d1252cb31ac',
'25':'12d5c6677b3e17170c317c1f5532d2a8','26':'13937d18e56b2b93d12fa5fcba48a138','27':'1d03d8ca5f201f4d156f5e1b38f7a67c',
'28':'c33395dec7fdc13e9d8f10afaa946f8c','29':'174f2db104ecaa5efef770f44241e3b0','30':'047d420ef9aecb933a7d83b6af820b23',
'31':'5be61f0c9944a5f2d7d1a5b2e75fb000','32':'212dcb867e95a642277a243fed8d8e41','33':'08a217b02cdd778cfdb0005dff4828b1',
'34':'4245d6fc370d9049ef4c25314fbef239','35':'1344aba8755b8a4e304629180fc0591a','36':'e4fff6ed84777905dc999ca6d6bc2557',
'37':'60d51ea6ae9e3f2fa316e3d03aff96b2','38':'4090ff76d94e6b38920916ae3ff2441c','X':'bce1372df64037d79b0995311d8ff971'}}
chromosome_fasta_path = ref_dir + "/references/chromosomes/tsb/"
print("Beginning installation. This may take up to 40 minutes to complete.")
if not rsync:
try:
if bash:
try:
os.system("bash -c '" + 'wget -r -l1 -c -nc --no-parent -nd -P ' + chromosome_fasta_path + 'ftp://alexandrovlab-ftp.ucsd.edu/pub/tools/SigProfilerMatrixGenerator/' + genome + '.tar.gz 2>> install.log' + "'")
except:
print("The UCSD ftp site is not responding...pulling from sanger ftp now.")
try:
os.system("bash -c '" + 'wget -r -l1 -c -nc --no-parent -nd -P ' + chromosome_fasta_path + ' ftp://ngs.sanger.ac.uk/scratch/project/mutographs/SigProf/' + genome + '.tar.gz 2>> install.log' + "'")
except:
print("The Sanger ftp site is not responding. Please check your internet connection/try again later.")
else:
os.system('wget -r -l1 -c -nc --no-parent -nd -P ' + chromosome_fasta_path + ' ftp://ngs.sanger.ac.uk/scratch/project/mutographs/SigProf/' + genome + '.tar.gz 2>> install.log')
os.system("tar -xzf " + ref_dir + "/references/chromosomes/tsb/" + genome + ".tar.gz -C " + ref_dir + "/references/chromosomes/tsb/")
os.remove(ref_dir + "/references/chromosomes/tsb/" + genome + ".tar.gz")
except:
print("The ensembl ftp site is not currently responding.")
sys.exit()
else:
print("Direct download for RSYNC is not yet supported")
sys.exit()
chromosome_TSB_path = chromosome_fasta_path + genome + "/"
corrupt = False
for files in os.listdir(chromosome_TSB_path):
if "proportions" in files:
continue
if ".DS_Store" in files:
continue
chrom = files.split(".")
chrom = chrom[0]
check = md5(chromosome_TSB_path + files)
if check_sum[genome][chrom] != check:
corrupt = True
os.remove(chromosome_TSB_path + files)
print("[DEBUG] Chromosome " + chrom + " md5sum did not match => reference md5sum: " + str(check_sum[genome][chrom]) + " new file md5sum: " + str(check))
if corrupt:
print("The transcriptional reference data appears to be corrupted. Please reinstall the " + genome + " genome.")
sys.exit()
print("The transcriptional reference data for " + genome + " has been saved.")
else:
print("Beginning installation. This may take up to 20 minutes to complete.")
first_path = os.getcwd()
ref_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(ref_dir)
print("[DEBUG] Path to SigProfilerMatrixGenerator used for the install: ", ref_dir)
genomes = [genome]
if os.path.exists("install.log"):
os.remove("install.log")
install_chromosomes(genomes, ref_dir, custom, rsync, bash)
install_chromosomes_tsb (genomes, ref_dir, custom)
if os.path.exists("BRCA_example/"):
shutil.copy("BRCA_example/", "references/vcf_files/")
if os.path.exists("example_test"):
shutil.copy("example_test/", "references/vcf_files/")
if os.path.exists("context_distributions/"):
shutil.copy("context_distributions/", "references/chromosomes/")
print("All reference files have been created.")
if genome != "rn6" and genome != 'dog' and genome != 'c_elegans':
print("Verifying and benchmarking installation now...")
benchmark(genome, ref_dir)
print ("To proceed with matrix_generation, please provide the path to your vcf files and an appropriate output path.")
shutil.rmtree(chrom_string_dir)
print("Installation complete.")
os.chdir(first_path)
def main ():
first_path= os.getcwd()
os.chdir(first_path + "/sigProfilerMatrixGenerator/")
genomes = ['mm9', 'mm10','GRCh37', 'GRCh38' ]
custom = False
parser = argparse.ArgumentParser(description="Provide the necessary arguments to install the reference files.")
parser.add_argument("-g", "--genome", nargs='?', help="Optional parameter instructs script to install the custom genome.")
parser.add_argument("-ct", "--custom", help="Optional parameter instructs script to create the reference files for a custom genome", action='store_true')
args = parser.parse_args()
if args.genome:
genomes = [args.genome]
if args.custom:
custom = True
if os.path.exists("install.log"):
os.system("rm install.log")
ref_dir = "references/"
chrom_string_dir = ref_dir + "chromosomes/chrom_string/"
chrom_fasta_dir = ref_dir + "chromosomes/fasta/"
chrom_tsb_dir = ref_dir + "chromosomes/tsb/"
matrix_dir = ref_dir + "matrix/"
vcf_dir = ref_dir + "vcf_files/"
bed_dir = ref_dir + "vcf_files/BED/"
log_dir = "logs/"
new_dirs = [ref_dir, chrom_string_dir, chrom_fasta_dir, chrom_tsb_dir, matrix_dir, vcf_dir, bed_dir, log_dir]
current_dir = os.getcwd()
for dirs in new_dirs:
if not os.path.exists(dirs):
os.makedirs(dirs)
install_chromosomes(genomes, ref_dir, custom)
install_chromosomes_tsb (genomes, ref_dir, custom)
if os.path.exists("BRCA_example/"):
os.system("mv BRCA_example/ references/vcf_files/")
if os.path.exists("example_test"):
os.system("mv example_test/ references/vcf_files/")
if os.path.exists("context_distributions/"):
os.system("mv context_distributions/ references/chromosomes/")
if os.path.exists(chrom_tsb_dir + "GRCh37/"):
print("All reference files have been created.\nVerifying and benchmarking installation now...")
benchmark(ref_dir)
else:
print("All reference files have been created.")
print ("Please place your vcf files for each sample into the 'references/vcf_files/[test]/[mutation_type]/' directory. Once you have done that, you can proceed with the matrix generation.")
print("Installation complete.")
os.chdir(first_path)
if __name__ == '__main__':
main() | true | true |
f72b5d1333df08c7bba72728c8f28fe54e5dda17 | 2,824 | py | Python | storyboard/tests/plugin/test_event_worker.py | Sitcode-Zoograf/storyboard | 5833f87e20722c524a1e4a0b8e1fb82206fb4e5c | [
"Apache-2.0"
] | null | null | null | storyboard/tests/plugin/test_event_worker.py | Sitcode-Zoograf/storyboard | 5833f87e20722c524a1e4a0b8e1fb82206fb4e5c | [
"Apache-2.0"
] | null | null | null | storyboard/tests/plugin/test_event_worker.py | Sitcode-Zoograf/storyboard | 5833f87e20722c524a1e4a0b8e1fb82206fb4e5c | [
"Apache-2.0"
] | null | null | null | # Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
#
# 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 storyboard.db.api.base as db_api_base
import storyboard.plugin.event_worker as plugin_base
import storyboard.tests.base as base
class TestWorkerTaskBase(base.FunctionalTest):
def setUp(self):
super(TestWorkerTaskBase, self).setUp()
def test_resolve_by_name(self):
'''Assert that resolve_resource_by_name works.'''
worker = TestWorkerPlugin({})
with base.HybridSessionManager():
session = db_api_base.get_session()
task = worker.resolve_resource_by_name(session, 'task', 1)
self.assertIsNotNone(task)
self.assertEqual(1, task.id)
project_group = worker.resolve_resource_by_name(session,
'project_group', 1)
self.assertIsNotNone(project_group)
self.assertEqual(1, project_group.id)
project = worker.resolve_resource_by_name(session, 'project', 1)
self.assertIsNotNone(project)
self.assertEqual(1, project.id)
user = worker.resolve_resource_by_name(session, 'user', 1)
self.assertIsNotNone(user)
self.assertEqual(1, user.id)
team = worker.resolve_resource_by_name(session, 'team', 1)
self.assertIsNotNone(team)
self.assertEqual(1, team.id)
story = worker.resolve_resource_by_name(session, 'story', 1)
self.assertIsNotNone(story)
self.assertEqual(1, story.id)
branch = worker.resolve_resource_by_name(session, 'branch', 1)
self.assertIsNotNone(branch)
self.assertEqual(1, branch.id)
milestone = worker.resolve_resource_by_name(session,
'milestone', 1)
self.assertIsNotNone(milestone)
self.assertEqual(1, milestone.id)
class TestWorkerPlugin(plugin_base.WorkerTaskBase):
def handle(self, session, author, method, url, path, query_string, status,
resource, resource_id, sub_resource=None, sub_resource_id=None,
resource_before=None, resource_after=None):
pass
def enabled(self):
return True
| 37.653333 | 79 | 0.651558 |
import storyboard.db.api.base as db_api_base
import storyboard.plugin.event_worker as plugin_base
import storyboard.tests.base as base
class TestWorkerTaskBase(base.FunctionalTest):
def setUp(self):
super(TestWorkerTaskBase, self).setUp()
def test_resolve_by_name(self):
worker = TestWorkerPlugin({})
with base.HybridSessionManager():
session = db_api_base.get_session()
task = worker.resolve_resource_by_name(session, 'task', 1)
self.assertIsNotNone(task)
self.assertEqual(1, task.id)
project_group = worker.resolve_resource_by_name(session,
'project_group', 1)
self.assertIsNotNone(project_group)
self.assertEqual(1, project_group.id)
project = worker.resolve_resource_by_name(session, 'project', 1)
self.assertIsNotNone(project)
self.assertEqual(1, project.id)
user = worker.resolve_resource_by_name(session, 'user', 1)
self.assertIsNotNone(user)
self.assertEqual(1, user.id)
team = worker.resolve_resource_by_name(session, 'team', 1)
self.assertIsNotNone(team)
self.assertEqual(1, team.id)
story = worker.resolve_resource_by_name(session, 'story', 1)
self.assertIsNotNone(story)
self.assertEqual(1, story.id)
branch = worker.resolve_resource_by_name(session, 'branch', 1)
self.assertIsNotNone(branch)
self.assertEqual(1, branch.id)
milestone = worker.resolve_resource_by_name(session,
'milestone', 1)
self.assertIsNotNone(milestone)
self.assertEqual(1, milestone.id)
class TestWorkerPlugin(plugin_base.WorkerTaskBase):
def handle(self, session, author, method, url, path, query_string, status,
resource, resource_id, sub_resource=None, sub_resource_id=None,
resource_before=None, resource_after=None):
pass
def enabled(self):
return True
| true | true |
f72b5ecb16ba78f38ce59b844429ea0150cb7a47 | 8,108 | py | Python | airflow/www/api/experimental/endpoints.py | guiligan/incubator-airflow | b3c0ae003037ae6c652b177b9f86ecac84c792a5 | [
"Apache-2.0"
] | null | null | null | airflow/www/api/experimental/endpoints.py | guiligan/incubator-airflow | b3c0ae003037ae6c652b177b9f86ecac84c792a5 | [
"Apache-2.0"
] | null | null | null | airflow/www/api/experimental/endpoints.py | guiligan/incubator-airflow | b3c0ae003037ae6c652b177b9f86ecac84c792a5 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from flask import (
g, Blueprint, jsonify, request, url_for
)
import airflow.api
from airflow.api.common.experimental import delete_dag as delete
from airflow.api.common.experimental import pool as pool_api
from airflow.api.common.experimental import trigger_dag as trigger
from airflow.api.common.experimental.get_task import get_task
from airflow.api.common.experimental.get_task_instance import get_task_instance
from airflow.exceptions import AirflowException
from airflow.utils import timezone
from airflow.utils.log.logging_mixin import LoggingMixin
from airflow.www.app import csrf
_log = LoggingMixin().log
requires_authentication = airflow.api.api_auth.requires_authentication
api_experimental = Blueprint('api_experimental', __name__)
@csrf.exempt
@api_experimental.route('/dags/<string:dag_id>/dag_runs', methods=['POST'])
@requires_authentication
def trigger_dag(dag_id):
"""
Trigger a new dag run for a Dag with an execution date of now unless
specified in the data.
"""
data = request.get_json(force=True)
run_id = None
if 'run_id' in data:
run_id = data['run_id']
conf = None
if 'conf' in data:
conf = data['conf']
execution_date = None
if 'execution_date' in data and data['execution_date'] is not None:
execution_date = data['execution_date']
# Convert string datetime into actual datetime
try:
execution_date = timezone.parse(execution_date)
except ValueError:
error_message = (
'Given execution date, {}, could not be identified '
'as a date. Example date format: 2015-11-16T14:34:15+00:00'.format(
execution_date))
_log.info(error_message)
response = jsonify({'error': error_message})
response.status_code = 400
return response
try:
dr = trigger.trigger_dag(dag_id, run_id, conf, execution_date)
except AirflowException as err:
_log.error(err)
response = jsonify(error="{}".format(err))
response.status_code = 404
return response
if getattr(g, 'user', None):
_log.info("User {} created {}".format(g.user, dr))
response = jsonify(message="Created {}".format(dr))
return response
@csrf.exempt
@api_experimental.route('/dags/<string:dag_id>', methods=['DELETE'])
@requires_authentication
def delete_dag(dag_id):
"""
Delete all DB records related to the specified Dag.
"""
try:
count = delete.delete_dag(dag_id)
except AirflowException as e:
_log.error(e)
response = jsonify(error="{}".format(e))
response.status_code = getattr(e, 'status', 500)
return response
return jsonify(message="Removed {} record(s)".format(count), count=count)
@api_experimental.route('/test', methods=['GET'])
@requires_authentication
def test():
return jsonify(status='OK')
@api_experimental.route('/dags/<string:dag_id>/tasks/<string:task_id>', methods=['GET'])
@requires_authentication
def task_info(dag_id, task_id):
"""Returns a JSON with a task's public instance variables. """
try:
info = get_task(dag_id, task_id)
except AirflowException as err:
_log.info(err)
response = jsonify(error="{}".format(err))
response.status_code = 404
return response
# JSONify and return.
fields = {k: str(v)
for k, v in vars(info).items()
if not k.startswith('_')}
return jsonify(fields)
@api_experimental.route(
'/dags/<string:dag_id>/dag_runs/<string:execution_date>/tasks/<string:task_id>',
methods=['GET'])
@requires_authentication
def task_instance_info(dag_id, execution_date, task_id):
"""
Returns a JSON with a task instance's public instance variables.
The format for the exec_date is expected to be
"YYYY-mm-DDTHH:MM:SS", for example: "2016-11-16T11:34:15". This will
of course need to have been encoded for URL in the request.
"""
# Convert string datetime into actual datetime
try:
execution_date = timezone.parse(execution_date)
except ValueError:
error_message = (
'Given execution date, {}, could not be identified '
'as a date. Example date format: 2015-11-16T14:34:15+00:00'.format(
execution_date))
_log.info(error_message)
response = jsonify({'error': error_message})
response.status_code = 400
return response
try:
info = get_task_instance(dag_id, task_id, execution_date)
except AirflowException as err:
_log.info(err)
response = jsonify(error="{}".format(err))
response.status_code = 404
return response
# JSONify and return.
fields = {k: str(v)
for k, v in vars(info).items()
if not k.startswith('_')}
return jsonify(fields)
@api_experimental.route('/latest_runs', methods=['GET'])
@requires_authentication
def latest_dag_runs():
"""Returns the latest DagRun for each DAG formatted for the UI. """
from airflow.models import DagRun
dagruns = DagRun.get_latest_runs()
payload = []
for dagrun in dagruns:
if dagrun.execution_date:
payload.append({
'dag_id': dagrun.dag_id,
'execution_date': dagrun.execution_date.isoformat(),
'start_date': ((dagrun.start_date or '') and
dagrun.start_date.isoformat()),
'dag_run_url': url_for('airflow.graph', dag_id=dagrun.dag_id,
execution_date=dagrun.execution_date)
})
return jsonify(items=payload) # old flask versions dont support jsonifying arrays
@api_experimental.route('/pools/<string:name>', methods=['GET'])
@requires_authentication
def get_pool(name):
"""Get pool by a given name."""
try:
pool = pool_api.get_pool(name=name)
except AirflowException as e:
_log.error(e)
response = jsonify(error="{}".format(e))
response.status_code = getattr(e, 'status', 500)
return response
else:
return jsonify(pool.to_json())
@api_experimental.route('/pools', methods=['GET'])
@requires_authentication
def get_pools():
"""Get all pools."""
try:
pools = pool_api.get_pools()
except AirflowException as e:
_log.error(e)
response = jsonify(error="{}".format(e))
response.status_code = getattr(e, 'status', 500)
return response
else:
return jsonify([p.to_json() for p in pools])
@csrf.exempt
@api_experimental.route('/pools', methods=['POST'])
@requires_authentication
def create_pool():
"""Create a pool."""
params = request.get_json(force=True)
try:
pool = pool_api.create_pool(**params)
except AirflowException as e:
_log.error(e)
response = jsonify(error="{}".format(e))
response.status_code = getattr(e, 'status', 500)
return response
else:
return jsonify(pool.to_json())
@csrf.exempt
@api_experimental.route('/pools/<string:name>', methods=['DELETE'])
@requires_authentication
def delete_pool(name):
"""Delete pool."""
try:
pool = pool_api.delete_pool(name=name)
except AirflowException as e:
_log.error(e)
response = jsonify(error="{}".format(e))
response.status_code = getattr(e, 'status', 500)
return response
else:
return jsonify(pool.to_json())
| 32.302789 | 88 | 0.656265 |
from flask import (
g, Blueprint, jsonify, request, url_for
)
import airflow.api
from airflow.api.common.experimental import delete_dag as delete
from airflow.api.common.experimental import pool as pool_api
from airflow.api.common.experimental import trigger_dag as trigger
from airflow.api.common.experimental.get_task import get_task
from airflow.api.common.experimental.get_task_instance import get_task_instance
from airflow.exceptions import AirflowException
from airflow.utils import timezone
from airflow.utils.log.logging_mixin import LoggingMixin
from airflow.www.app import csrf
_log = LoggingMixin().log
requires_authentication = airflow.api.api_auth.requires_authentication
api_experimental = Blueprint('api_experimental', __name__)
@csrf.exempt
@api_experimental.route('/dags/<string:dag_id>/dag_runs', methods=['POST'])
@requires_authentication
def trigger_dag(dag_id):
data = request.get_json(force=True)
run_id = None
if 'run_id' in data:
run_id = data['run_id']
conf = None
if 'conf' in data:
conf = data['conf']
execution_date = None
if 'execution_date' in data and data['execution_date'] is not None:
execution_date = data['execution_date']
try:
execution_date = timezone.parse(execution_date)
except ValueError:
error_message = (
'Given execution date, {}, could not be identified '
'as a date. Example date format: 2015-11-16T14:34:15+00:00'.format(
execution_date))
_log.info(error_message)
response = jsonify({'error': error_message})
response.status_code = 400
return response
try:
dr = trigger.trigger_dag(dag_id, run_id, conf, execution_date)
except AirflowException as err:
_log.error(err)
response = jsonify(error="{}".format(err))
response.status_code = 404
return response
if getattr(g, 'user', None):
_log.info("User {} created {}".format(g.user, dr))
response = jsonify(message="Created {}".format(dr))
return response
@csrf.exempt
@api_experimental.route('/dags/<string:dag_id>', methods=['DELETE'])
@requires_authentication
def delete_dag(dag_id):
try:
count = delete.delete_dag(dag_id)
except AirflowException as e:
_log.error(e)
response = jsonify(error="{}".format(e))
response.status_code = getattr(e, 'status', 500)
return response
return jsonify(message="Removed {} record(s)".format(count), count=count)
@api_experimental.route('/test', methods=['GET'])
@requires_authentication
def test():
return jsonify(status='OK')
@api_experimental.route('/dags/<string:dag_id>/tasks/<string:task_id>', methods=['GET'])
@requires_authentication
def task_info(dag_id, task_id):
try:
info = get_task(dag_id, task_id)
except AirflowException as err:
_log.info(err)
response = jsonify(error="{}".format(err))
response.status_code = 404
return response
fields = {k: str(v)
for k, v in vars(info).items()
if not k.startswith('_')}
return jsonify(fields)
@api_experimental.route(
'/dags/<string:dag_id>/dag_runs/<string:execution_date>/tasks/<string:task_id>',
methods=['GET'])
@requires_authentication
def task_instance_info(dag_id, execution_date, task_id):
try:
execution_date = timezone.parse(execution_date)
except ValueError:
error_message = (
'Given execution date, {}, could not be identified '
'as a date. Example date format: 2015-11-16T14:34:15+00:00'.format(
execution_date))
_log.info(error_message)
response = jsonify({'error': error_message})
response.status_code = 400
return response
try:
info = get_task_instance(dag_id, task_id, execution_date)
except AirflowException as err:
_log.info(err)
response = jsonify(error="{}".format(err))
response.status_code = 404
return response
fields = {k: str(v)
for k, v in vars(info).items()
if not k.startswith('_')}
return jsonify(fields)
@api_experimental.route('/latest_runs', methods=['GET'])
@requires_authentication
def latest_dag_runs():
from airflow.models import DagRun
dagruns = DagRun.get_latest_runs()
payload = []
for dagrun in dagruns:
if dagrun.execution_date:
payload.append({
'dag_id': dagrun.dag_id,
'execution_date': dagrun.execution_date.isoformat(),
'start_date': ((dagrun.start_date or '') and
dagrun.start_date.isoformat()),
'dag_run_url': url_for('airflow.graph', dag_id=dagrun.dag_id,
execution_date=dagrun.execution_date)
})
return jsonify(items=payload)
@api_experimental.route('/pools/<string:name>', methods=['GET'])
@requires_authentication
def get_pool(name):
try:
pool = pool_api.get_pool(name=name)
except AirflowException as e:
_log.error(e)
response = jsonify(error="{}".format(e))
response.status_code = getattr(e, 'status', 500)
return response
else:
return jsonify(pool.to_json())
@api_experimental.route('/pools', methods=['GET'])
@requires_authentication
def get_pools():
try:
pools = pool_api.get_pools()
except AirflowException as e:
_log.error(e)
response = jsonify(error="{}".format(e))
response.status_code = getattr(e, 'status', 500)
return response
else:
return jsonify([p.to_json() for p in pools])
@csrf.exempt
@api_experimental.route('/pools', methods=['POST'])
@requires_authentication
def create_pool():
params = request.get_json(force=True)
try:
pool = pool_api.create_pool(**params)
except AirflowException as e:
_log.error(e)
response = jsonify(error="{}".format(e))
response.status_code = getattr(e, 'status', 500)
return response
else:
return jsonify(pool.to_json())
@csrf.exempt
@api_experimental.route('/pools/<string:name>', methods=['DELETE'])
@requires_authentication
def delete_pool(name):
try:
pool = pool_api.delete_pool(name=name)
except AirflowException as e:
_log.error(e)
response = jsonify(error="{}".format(e))
response.status_code = getattr(e, 'status', 500)
return response
else:
return jsonify(pool.to_json())
| true | true |
f72b5fa86d6b83ca6337f2fcfbd2bd36f1181b33 | 356 | py | Python | src/subplot1.py | AnaharaYasuo/mlPractice | 1a3d110fdc6cf4084ee6b1268d215151de5939cb | [
"Apache-2.0"
] | null | null | null | src/subplot1.py | AnaharaYasuo/mlPractice | 1a3d110fdc6cf4084ee6b1268d215151de5939cb | [
"Apache-2.0"
] | null | null | null | src/subplot1.py | AnaharaYasuo/mlPractice | 1a3d110fdc6cf4084ee6b1268d215151de5939cb | [
"Apache-2.0"
] | null | null | null | import numpy as np
import matplotlib.pyplot as plt
if __name__ == "__main__":
x = np.linspace(-5, 5, 300)
sin_x = np.sin(x)
cos_x = np.cos(x)
flg, aexs = plt.subplots(2, 1)
aexs[0].set_ylim([-1.5,1.5])
aexs[1].set_ylim([-1.5,1.5])
aexs[0].plot(x,sin_x,color="r")
aexs[1].plot(x,cos_x,color="k")
plt.show() | 23.733333 | 39 | 0.564607 | import numpy as np
import matplotlib.pyplot as plt
if __name__ == "__main__":
x = np.linspace(-5, 5, 300)
sin_x = np.sin(x)
cos_x = np.cos(x)
flg, aexs = plt.subplots(2, 1)
aexs[0].set_ylim([-1.5,1.5])
aexs[1].set_ylim([-1.5,1.5])
aexs[0].plot(x,sin_x,color="r")
aexs[1].plot(x,cos_x,color="k")
plt.show() | true | true |
f72b609af987bf7e917700aeb972f5133849bc61 | 6,985 | py | Python | log_caspase/model_378.py | LoLab-VU/Bayesian_Inference_of_Network_Dynamics | 54a5ef7e868be34289836bbbb024a2963c0c9c86 | [
"MIT"
] | null | null | null | log_caspase/model_378.py | LoLab-VU/Bayesian_Inference_of_Network_Dynamics | 54a5ef7e868be34289836bbbb024a2963c0c9c86 | [
"MIT"
] | null | null | null | log_caspase/model_378.py | LoLab-VU/Bayesian_Inference_of_Network_Dynamics | 54a5ef7e868be34289836bbbb024a2963c0c9c86 | [
"MIT"
] | null | null | null | # exported from PySB model 'model'
from pysb import Model, Monomer, Parameter, Expression, Compartment, Rule, Observable, Initial, MatchOnce, Annotation, ANY, WILD
Model()
Monomer('C6A', ['C8pro'])
Monomer('Ligand', ['Receptor'])
Monomer('ParpU', ['C3A'])
Monomer('C3ub')
Monomer('C3A', ['Xiap', 'ParpU', 'C6pro'])
Monomer('Xiap', ['C3A'])
Monomer('C8A', ['C3pro'])
Monomer('C3pro', ['C8A'])
Monomer('Receptor', ['Ligand', 'Fadd'])
Monomer('C6pro', ['C3A'])
Monomer('Fadd', ['Receptor', 'C8pro'])
Monomer('C8pro', ['Fadd', 'C6A'])
Monomer('ParpC')
Parameter('bind_0_Ligand_binder_Receptor_binder_target_2kf', 1.0)
Parameter('bind_0_Ligand_binder_Receptor_binder_target_1kr', 1.0)
Parameter('bind_0_Receptor_binder_Fadd_binder_target_2kf', 1.0)
Parameter('bind_0_Receptor_binder_Fadd_binder_target_1kr', 1.0)
Parameter('substrate_binding_0_Fadd_catalyzer_C8pro_substrate_2kf', 1.0)
Parameter('substrate_binding_0_Fadd_catalyzer_C8pro_substrate_1kr', 1.0)
Parameter('catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product_1kc', 1.0)
Parameter('catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_2kf', 1.0)
Parameter('catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_1kr', 1.0)
Parameter('catalysis_1_C8A_catalyzer_C3pro_substrate_C3A_product_1kc', 1.0)
Parameter('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_2kf', 1.0)
Parameter('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_1kr', 1.0)
Parameter('catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product_1kc', 1.0)
Parameter('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_2kf', 1.0)
Parameter('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_1kr', 1.0)
Parameter('catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product_1kc', 1.0)
Parameter('catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_2kf', 1.0)
Parameter('catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_1kr', 1.0)
Parameter('catalysis_1_C3A_catalyzer_C6pro_substrate_C6A_product_1kc', 1.0)
Parameter('catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_2kf', 1.0)
Parameter('catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_1kr', 1.0)
Parameter('catalysis_1_C6A_catalyzer_C8pro_substrate_C8A_product_1kc', 1.0)
Parameter('C6A_0', 0.0)
Parameter('Ligand_0', 1000.0)
Parameter('ParpU_0', 1000000.0)
Parameter('C3ub_0', 0.0)
Parameter('C3A_0', 0.0)
Parameter('Xiap_0', 94500.0)
Parameter('C8A_0', 0.0)
Parameter('C3pro_0', 21000.0)
Parameter('Receptor_0', 100.0)
Parameter('C6pro_0', 100.0)
Parameter('Fadd_0', 130000.0)
Parameter('C8pro_0', 130000.0)
Parameter('ParpC_0', 0.0)
Observable('C6A_obs', C6A())
Observable('Ligand_obs', Ligand())
Observable('ParpU_obs', ParpU())
Observable('C3ub_obs', C3ub())
Observable('C3A_obs', C3A())
Observable('Xiap_obs', Xiap())
Observable('C8A_obs', C8A())
Observable('C3pro_obs', C3pro())
Observable('Receptor_obs', Receptor())
Observable('C6pro_obs', C6pro())
Observable('Fadd_obs', Fadd())
Observable('C8pro_obs', C8pro())
Observable('ParpC_obs', ParpC())
Rule('bind_0_Ligand_binder_Receptor_binder_target', Ligand(Receptor=None) + Receptor(Ligand=None, Fadd=None) | Ligand(Receptor=1) % Receptor(Ligand=1, Fadd=None), bind_0_Ligand_binder_Receptor_binder_target_2kf, bind_0_Ligand_binder_Receptor_binder_target_1kr)
Rule('bind_0_Receptor_binder_Fadd_binder_target', Receptor(Ligand=ANY, Fadd=None) + Fadd(Receptor=None, C8pro=None) | Receptor(Ligand=ANY, Fadd=1) % Fadd(Receptor=1, C8pro=None), bind_0_Receptor_binder_Fadd_binder_target_2kf, bind_0_Receptor_binder_Fadd_binder_target_1kr)
Rule('substrate_binding_0_Fadd_catalyzer_C8pro_substrate', Fadd(Receptor=ANY, C8pro=None) + C8pro(Fadd=None, C6A=None) | Fadd(Receptor=ANY, C8pro=1) % C8pro(Fadd=1, C6A=None), substrate_binding_0_Fadd_catalyzer_C8pro_substrate_2kf, substrate_binding_0_Fadd_catalyzer_C8pro_substrate_1kr)
Rule('catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product', Fadd(Receptor=ANY, C8pro=1) % C8pro(Fadd=1, C6A=None) >> Fadd(Receptor=ANY, C8pro=None) + C8A(C3pro=None), catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product_1kc)
Rule('catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product', C8A(C3pro=None) + C3pro(C8A=None) | C8A(C3pro=1) % C3pro(C8A=1), catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_2kf, catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_1kr)
Rule('catalysis_1_C8A_catalyzer_C3pro_substrate_C3A_product', C8A(C3pro=1) % C3pro(C8A=1) >> C8A(C3pro=None) + C3A(Xiap=None, ParpU=None, C6pro=None), catalysis_1_C8A_catalyzer_C3pro_substrate_C3A_product_1kc)
Rule('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product', Xiap(C3A=None) + C3A(Xiap=None, ParpU=None, C6pro=None) | Xiap(C3A=1) % C3A(Xiap=1, ParpU=None, C6pro=None), catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_2kf, catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_1kr)
Rule('catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product', Xiap(C3A=1) % C3A(Xiap=1, ParpU=None, C6pro=None) >> Xiap(C3A=None) + C3ub(), catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product_1kc)
Rule('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product', C3A(Xiap=None, ParpU=None, C6pro=None) + ParpU(C3A=None) | C3A(Xiap=None, ParpU=1, C6pro=None) % ParpU(C3A=1), catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_2kf, catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_1kr)
Rule('catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product', C3A(Xiap=None, ParpU=1, C6pro=None) % ParpU(C3A=1) >> C3A(Xiap=None, ParpU=None, C6pro=None) + ParpC(), catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product_1kc)
Rule('catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product', C3A(Xiap=None, ParpU=None, C6pro=None) + C6pro(C3A=None) | C3A(Xiap=None, ParpU=None, C6pro=1) % C6pro(C3A=1), catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_2kf, catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_1kr)
Rule('catalysis_1_C3A_catalyzer_C6pro_substrate_C6A_product', C3A(Xiap=None, ParpU=None, C6pro=1) % C6pro(C3A=1) >> C3A(Xiap=None, ParpU=None, C6pro=None) + C6A(C8pro=None), catalysis_1_C3A_catalyzer_C6pro_substrate_C6A_product_1kc)
Rule('catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product', C6A(C8pro=None) + C8pro(Fadd=None, C6A=None) | C6A(C8pro=1) % C8pro(Fadd=None, C6A=1), catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_2kf, catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_1kr)
Rule('catalysis_1_C6A_catalyzer_C8pro_substrate_C8A_product', C6A(C8pro=1) % C8pro(Fadd=None, C6A=1) >> C6A(C8pro=None) + C8A(C3pro=None), catalysis_1_C6A_catalyzer_C8pro_substrate_C8A_product_1kc)
Initial(C6A(C8pro=None), C6A_0)
Initial(Ligand(Receptor=None), Ligand_0)
Initial(ParpU(C3A=None), ParpU_0)
Initial(C3ub(), C3ub_0)
Initial(C3A(Xiap=None, ParpU=None, C6pro=None), C3A_0)
Initial(Xiap(C3A=None), Xiap_0)
Initial(C8A(C3pro=None), C8A_0)
Initial(C3pro(C8A=None), C3pro_0)
Initial(Receptor(Ligand=None, Fadd=None), Receptor_0)
Initial(C6pro(C3A=None), C6pro_0)
Initial(Fadd(Receptor=None, C8pro=None), Fadd_0)
Initial(C8pro(Fadd=None, C6A=None), C8pro_0)
Initial(ParpC(), ParpC_0)
| 69.85 | 296 | 0.818039 |
from pysb import Model, Monomer, Parameter, Expression, Compartment, Rule, Observable, Initial, MatchOnce, Annotation, ANY, WILD
Model()
Monomer('C6A', ['C8pro'])
Monomer('Ligand', ['Receptor'])
Monomer('ParpU', ['C3A'])
Monomer('C3ub')
Monomer('C3A', ['Xiap', 'ParpU', 'C6pro'])
Monomer('Xiap', ['C3A'])
Monomer('C8A', ['C3pro'])
Monomer('C3pro', ['C8A'])
Monomer('Receptor', ['Ligand', 'Fadd'])
Monomer('C6pro', ['C3A'])
Monomer('Fadd', ['Receptor', 'C8pro'])
Monomer('C8pro', ['Fadd', 'C6A'])
Monomer('ParpC')
Parameter('bind_0_Ligand_binder_Receptor_binder_target_2kf', 1.0)
Parameter('bind_0_Ligand_binder_Receptor_binder_target_1kr', 1.0)
Parameter('bind_0_Receptor_binder_Fadd_binder_target_2kf', 1.0)
Parameter('bind_0_Receptor_binder_Fadd_binder_target_1kr', 1.0)
Parameter('substrate_binding_0_Fadd_catalyzer_C8pro_substrate_2kf', 1.0)
Parameter('substrate_binding_0_Fadd_catalyzer_C8pro_substrate_1kr', 1.0)
Parameter('catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product_1kc', 1.0)
Parameter('catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_2kf', 1.0)
Parameter('catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_1kr', 1.0)
Parameter('catalysis_1_C8A_catalyzer_C3pro_substrate_C3A_product_1kc', 1.0)
Parameter('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_2kf', 1.0)
Parameter('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_1kr', 1.0)
Parameter('catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product_1kc', 1.0)
Parameter('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_2kf', 1.0)
Parameter('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_1kr', 1.0)
Parameter('catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product_1kc', 1.0)
Parameter('catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_2kf', 1.0)
Parameter('catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_1kr', 1.0)
Parameter('catalysis_1_C3A_catalyzer_C6pro_substrate_C6A_product_1kc', 1.0)
Parameter('catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_2kf', 1.0)
Parameter('catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_1kr', 1.0)
Parameter('catalysis_1_C6A_catalyzer_C8pro_substrate_C8A_product_1kc', 1.0)
Parameter('C6A_0', 0.0)
Parameter('Ligand_0', 1000.0)
Parameter('ParpU_0', 1000000.0)
Parameter('C3ub_0', 0.0)
Parameter('C3A_0', 0.0)
Parameter('Xiap_0', 94500.0)
Parameter('C8A_0', 0.0)
Parameter('C3pro_0', 21000.0)
Parameter('Receptor_0', 100.0)
Parameter('C6pro_0', 100.0)
Parameter('Fadd_0', 130000.0)
Parameter('C8pro_0', 130000.0)
Parameter('ParpC_0', 0.0)
Observable('C6A_obs', C6A())
Observable('Ligand_obs', Ligand())
Observable('ParpU_obs', ParpU())
Observable('C3ub_obs', C3ub())
Observable('C3A_obs', C3A())
Observable('Xiap_obs', Xiap())
Observable('C8A_obs', C8A())
Observable('C3pro_obs', C3pro())
Observable('Receptor_obs', Receptor())
Observable('C6pro_obs', C6pro())
Observable('Fadd_obs', Fadd())
Observable('C8pro_obs', C8pro())
Observable('ParpC_obs', ParpC())
Rule('bind_0_Ligand_binder_Receptor_binder_target', Ligand(Receptor=None) + Receptor(Ligand=None, Fadd=None) | Ligand(Receptor=1) % Receptor(Ligand=1, Fadd=None), bind_0_Ligand_binder_Receptor_binder_target_2kf, bind_0_Ligand_binder_Receptor_binder_target_1kr)
Rule('bind_0_Receptor_binder_Fadd_binder_target', Receptor(Ligand=ANY, Fadd=None) + Fadd(Receptor=None, C8pro=None) | Receptor(Ligand=ANY, Fadd=1) % Fadd(Receptor=1, C8pro=None), bind_0_Receptor_binder_Fadd_binder_target_2kf, bind_0_Receptor_binder_Fadd_binder_target_1kr)
Rule('substrate_binding_0_Fadd_catalyzer_C8pro_substrate', Fadd(Receptor=ANY, C8pro=None) + C8pro(Fadd=None, C6A=None) | Fadd(Receptor=ANY, C8pro=1) % C8pro(Fadd=1, C6A=None), substrate_binding_0_Fadd_catalyzer_C8pro_substrate_2kf, substrate_binding_0_Fadd_catalyzer_C8pro_substrate_1kr)
Rule('catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product', Fadd(Receptor=ANY, C8pro=1) % C8pro(Fadd=1, C6A=None) >> Fadd(Receptor=ANY, C8pro=None) + C8A(C3pro=None), catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product_1kc)
Rule('catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product', C8A(C3pro=None) + C3pro(C8A=None) | C8A(C3pro=1) % C3pro(C8A=1), catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_2kf, catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_1kr)
Rule('catalysis_1_C8A_catalyzer_C3pro_substrate_C3A_product', C8A(C3pro=1) % C3pro(C8A=1) >> C8A(C3pro=None) + C3A(Xiap=None, ParpU=None, C6pro=None), catalysis_1_C8A_catalyzer_C3pro_substrate_C3A_product_1kc)
Rule('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product', Xiap(C3A=None) + C3A(Xiap=None, ParpU=None, C6pro=None) | Xiap(C3A=1) % C3A(Xiap=1, ParpU=None, C6pro=None), catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_2kf, catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_1kr)
Rule('catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product', Xiap(C3A=1) % C3A(Xiap=1, ParpU=None, C6pro=None) >> Xiap(C3A=None) + C3ub(), catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product_1kc)
Rule('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product', C3A(Xiap=None, ParpU=None, C6pro=None) + ParpU(C3A=None) | C3A(Xiap=None, ParpU=1, C6pro=None) % ParpU(C3A=1), catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_2kf, catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_1kr)
Rule('catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product', C3A(Xiap=None, ParpU=1, C6pro=None) % ParpU(C3A=1) >> C3A(Xiap=None, ParpU=None, C6pro=None) + ParpC(), catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product_1kc)
Rule('catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product', C3A(Xiap=None, ParpU=None, C6pro=None) + C6pro(C3A=None) | C3A(Xiap=None, ParpU=None, C6pro=1) % C6pro(C3A=1), catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_2kf, catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_1kr)
Rule('catalysis_1_C3A_catalyzer_C6pro_substrate_C6A_product', C3A(Xiap=None, ParpU=None, C6pro=1) % C6pro(C3A=1) >> C3A(Xiap=None, ParpU=None, C6pro=None) + C6A(C8pro=None), catalysis_1_C3A_catalyzer_C6pro_substrate_C6A_product_1kc)
Rule('catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product', C6A(C8pro=None) + C8pro(Fadd=None, C6A=None) | C6A(C8pro=1) % C8pro(Fadd=None, C6A=1), catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_2kf, catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_1kr)
Rule('catalysis_1_C6A_catalyzer_C8pro_substrate_C8A_product', C6A(C8pro=1) % C8pro(Fadd=None, C6A=1) >> C6A(C8pro=None) + C8A(C3pro=None), catalysis_1_C6A_catalyzer_C8pro_substrate_C8A_product_1kc)
Initial(C6A(C8pro=None), C6A_0)
Initial(Ligand(Receptor=None), Ligand_0)
Initial(ParpU(C3A=None), ParpU_0)
Initial(C3ub(), C3ub_0)
Initial(C3A(Xiap=None, ParpU=None, C6pro=None), C3A_0)
Initial(Xiap(C3A=None), Xiap_0)
Initial(C8A(C3pro=None), C8A_0)
Initial(C3pro(C8A=None), C3pro_0)
Initial(Receptor(Ligand=None, Fadd=None), Receptor_0)
Initial(C6pro(C3A=None), C6pro_0)
Initial(Fadd(Receptor=None, C8pro=None), Fadd_0)
Initial(C8pro(Fadd=None, C6A=None), C8pro_0)
Initial(ParpC(), ParpC_0)
| true | true |
f72b6381fc06e7cffc979d54eb10670337ea3e1b | 35,546 | py | Python | sorn/utils.py | Saran-nns/sorn | 619772c508b88aa711780ab9155fe5d0aa5214eb | [
"MIT"
] | 19 | 2019-03-18T21:51:53.000Z | 2022-01-02T01:27:37.000Z | sorn/utils.py | Saran-nns/sorn | 619772c508b88aa711780ab9155fe5d0aa5214eb | [
"MIT"
] | 32 | 2019-03-10T23:55:22.000Z | 2022-01-04T19:28:45.000Z | sorn/utils.py | Saran-nns/sorn | 619772c508b88aa711780ab9155fe5d0aa5214eb | [
"MIT"
] | 4 | 2019-05-07T13:46:47.000Z | 2022-01-07T17:06:41.000Z | from __future__ import division
import numpy as np
from scipy.stats import norm
import random
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.optimize import curve_fit
from scipy import stats
import networkx as nx
import pandas as pd
from mpl_toolkits.axes_grid1.inset_locator import InsetPosition
class Initializer(object):
"""
Helper class to initialize the matrices for the SORN
"""
def __init__(self):
pass
@staticmethod
def generate_strong_inp(length: int, reservoir_size: int):
"""Generate strong one-hot vector of input. Random neurons in the reservoir acts as inputs
Args:
length (int): Number of input neurons
Returns:
inp (array): Input vector of length equals the number of neurons in the reservoir
with randomly chosen neuron set active
idx (list): List of chosen input neurons """
inp = [0] * reservoir_size
x = [0] * length
idx = np.random.choice(length, np.random.randint(reservoir_size))
for i in idx:
x[i] = 1.0e4
inp[: len(x)] = x
return inp, idx
# Generate multi-node one-hot strong inputs
@staticmethod
def multi_one_hot_inp(ne: int, inputs: list, n_nodes_per_inp: int):
"""Generate multi(n_nodes_per_inp) one hot vector for each input.
For each input, set n_nodes_per_inp equals one and the rest of
neurons in the pool recieves no external stimuli
Args:
ne (int): Number of excitatory units in sorn
inputs (list): input labels
n_nodes_per_inp(int): Number of target units in pool that receives single input
Returns:
one_hot_vector for each label with length equals ne
"""
one_hot = np.zeros((ne, len(inputs)))
idxs = []
for _ in range(n_nodes_per_inp):
idxs.append(random.sample(range(0, ne), len(inputs)))
idxs = list(zip(*idxs))
j = 0 # Max(j) = len(inputs)
for idx_list in idxs:
for i in idx_list:
one_hot[i][j] = 1
j += 1
return one_hot, idxs
@staticmethod
def generate_gaussian_inputs(length: int, reservoir_size: int):
"""Generate external stimuli sampled from Gaussian distribution.
Randomly neurons in the reservoir receives this input at each timestep
Args:
length (int): Number of input neurons
Returns:
out (array): Input vector of length equals the number of neurons in the reservoir
with randomly chosen neuron set active
idx (int): List of chosen input neurons
"""
out = [0] * reservoir_size
x = [0] * length
idx = np.random.choice(length, np.random.randint(reservoir_size))
inp = np.random.normal(length)
for i in idx:
x[i] = inp[i]
out[: len(x)] = x
return out, idx
@staticmethod
def normalize_weight_matrix(weight_matrix: np.array):
# Applied only while initializing the weight. During simulation, Synaptic scaling applied on weight matrices
""" Normalize the weights in the matrix such that incoming connections to a neuron sum up to 1
Args:
weight_matrix (array): Incoming Weights from W_ee or W_ei or W_ie
Returns:
weight_matrix (array): Normalized weight matrix"""
normalized_weight_matrix = weight_matrix / np.sum(weight_matrix, axis=0)
return normalized_weight_matrix
@staticmethod
def generate_lambd_connections(
synaptic_connection: str, ne: int, ni: int, lambd_w: int, lambd_std: int
):
"""Generate lambda incoming connections for Excitatory neurons and outgoing connections per Inhibitory neuron
Args:
synaptic_connection (str): Type of sysnpatic connection (EE,EI or IE)
ne (int): Number of excitatory units
ni (int): Number of inhibitory units
lambd_w (int): Average number of incoming connections
lambd_std (int): Standard deviation of average number of connections per neuron
Returns:
connection_weights (array) - Weight matrix
"""
if synaptic_connection == "EE":
"""Choose random lamda connections per neuron"""
# Draw normally distributed ne integers with mean lambd_w
lambdas_incoming = norm.ppf(
np.random.random(ne), loc=lambd_w, scale=lambd_std
).astype(int)
# lambdas_outgoing = norm.ppf(np.random.random(ne), loc=lambd_w, scale=lambd_std).astype(int)
# List of neurons
list_neurons = list(range(ne))
# Connection weights
connection_weights = np.zeros((ne, ne))
# For each lambd value in the above list,
# generate weights for incoming and outgoing connections
# -------------Gaussian Distribution of weights --------------
# weight_matrix = np.random.randn(Sorn.ne, Sorn.ni) + 2 # Small random values from gaussian distribution
# Centered around 2 to make all values positive
# ------------Uniform Distribution --------------------------
global_incoming_weights = np.random.uniform(0.0, 0.1, sum(lambdas_incoming))
# Index Counter
global_incoming_weights_idx = 0
# Choose the neurons in order [0 to 199]
for neuron in list_neurons:
# Choose ramdom unique (lambdas[neuron]) neurons from list_neurons
possible_connections = list_neurons.copy()
possible_connections.remove(
neuron
) # Remove the selected neuron from possible connections i!=j
# Choose random presynaptic neurons
possible_incoming_connections = random.sample(
possible_connections, lambdas_incoming[neuron]
)
incoming_weights_neuron = global_incoming_weights[
global_incoming_weights_idx : global_incoming_weights_idx
+ lambdas_incoming[neuron]
]
# ---------- Update the connection weight matrix ------------
# Update incoming connection weights for selected 'neuron'
for incoming_idx, incoming_weight in enumerate(incoming_weights_neuron):
connection_weights[possible_incoming_connections[incoming_idx]][
neuron
] = incoming_weight
global_incoming_weights_idx += lambdas_incoming[neuron]
return connection_weights
if synaptic_connection == "EI":
"""Choose random lamda connections per neuron"""
# Draw normally distributed ni integers with mean lambd_w
lambdas = norm.ppf(
np.random.random(ni), loc=lambd_w, scale=lambd_std
).astype(int)
# List of neurons
list_neurons = list(range(ni)) # Each i can connect with random ne neurons
# Initializing connection weights variable
connection_weights = np.zeros((ni, ne))
# ------------Uniform Distribution -----------------------------
global_outgoing_weights = np.random.uniform(0.0, 0.1, sum(lambdas))
# Index Counter
global_outgoing_weights_idx = 0
# Choose the neurons in order [0 to 40]
for neuron in list_neurons:
# Choose random unique (lambdas[neuron]) neurons from list_neurons
possible_connections = list(range(ne))
possible_outgoing_connections = random.sample(
possible_connections, lambdas[neuron]
) # possible_outgoing connections to the neuron
# Update weights
outgoing_weights = global_outgoing_weights[
global_outgoing_weights_idx : global_outgoing_weights_idx
+ lambdas[neuron]
]
# ---------- Update the connection weight matrix ------------
# Update outgoing connections for the neuron
for outgoing_idx, outgoing_weight in enumerate(
outgoing_weights
): # Update the columns in the connection matrix
connection_weights[neuron][
possible_outgoing_connections[outgoing_idx]
] = outgoing_weight
# Update the global weight values index
global_outgoing_weights_idx += lambdas[neuron]
return connection_weights
@staticmethod
def get_incoming_connection_dict(weights: np.array):
""" Get the non-zero entries in columns is the incoming connections for the neurons
Args:
weights (np.array): Connection/Synaptic weights
Returns:
dict : Dictionary of incoming connections to each neuron
"""
# Indices of nonzero entries in the columns
connection_dict = dict.fromkeys(range(1, len(weights) + 1), 0)
for i in range(len(weights[0])): # For each neuron
connection_dict[i] = list(np.nonzero(weights[:, i])[0])
return connection_dict
@staticmethod
def get_outgoing_connection_dict(weights: np.array):
"""Get the non-zero entries in rows is the outgoing connections for the neurons
Args:
weights (np.array): Connection/Synaptic weights
Returns:
dict : Dictionary of outgoing connections from each neuron
"""
# Indices of nonzero entries in the rows
connection_dict = dict.fromkeys(range(1, len(weights) + 1), 1)
for i in range(len(weights[0])): # For each neuron
connection_dict[i] = list(np.nonzero(weights[i, :])[0])
return connection_dict
@staticmethod
def prune_small_weights(weights: np.array, cutoff_weight: float):
"""Prune the connections with negative connection strength. The weights less than cutoff_weight set to 0
Args:
weights (np.array): Synaptic strengths
cutoff_weight (float): Lower weight threshold
Returns:
array: Connections weights with values less than cutoff_weight set to 0
"""
weights[weights <= cutoff_weight] = cutoff_weight
return weights
@staticmethod
def set_max_cutoff_weight(weights: np.array, cutoff_weight: float):
""" Set cutoff limit for the values in given array
Args:
weights (np.array): Synaptic strengths
cutoff_weight (float): Higher weight threshold
Returns:
array: Connections weights with values greater than cutoff_weight set to 1
"""
weights[weights > cutoff_weight] = cutoff_weight
return weights
@staticmethod
def get_unconnected_indexes(wee: np.array):
""" Helper function for Structural plasticity to randomly select the unconnected units
Args:
wee (array): Weight matrix
Returns:
list (indices): (row_idx,col_idx)"""
i, j = np.where(wee <= 0.0)
indices = list(zip(i, j))
self_conn_removed = []
for i, idxs in enumerate(indices):
if idxs[0] != idxs[1]:
self_conn_removed.append(indices[i])
return self_conn_removed
@staticmethod
def white_gaussian_noise(mu: float, sigma: float, t: int):
"""Generates white gaussian noise with mean mu, standard deviation sigma and
the noise length equals t
Args:
mu (float): Mean value of Gaussian noise
sigma (float): Standard deviation of Gaussian noise
t (int): Length of noise vector
Returns:
array: White gaussian noise of length t
"""
noise = np.random.normal(mu, sigma, t)
return np.expand_dims(noise, 1)
@staticmethod
def zero_sum_incoming_check(weights: np.array):
"""Make sure, each neuron in the pool has atleast 1 incoming connection
Args:
weights (array): Synaptic strengths
Returns:
array: Synaptic weights of neurons with atleast one positive (non-zero) incoming connection strength
"""
zero_sum_incomings = np.where(np.sum(weights, axis=0) == 0.0)
if len(zero_sum_incomings[-1]) == 0:
return weights
else:
for zero_sum_incoming in zero_sum_incomings[-1]:
rand_indices = np.random.randint(
int(weights.shape[0] * 0.2), size=2
)
rand_values = np.random.uniform(0.0, 0.1, 2)
for i, idx in enumerate(rand_indices):
weights[:, zero_sum_incoming][idx] = rand_values[i]
return weights
class Plotter(object):
"""Wrapper class to call plotting methods
"""
def __init__(self):
pass
@staticmethod
def hist_incoming_conn(
weights: np.array, bin_size: int, histtype: str, savefig: bool
):
"""Plot the histogram of number of presynaptic connections per neuron
Args:
weights (array): Connection weights
bin_size (int): Histogram bin size
histtype (str): Same as histtype matplotlib
savefig (bool): If True plot will be saved as png file in the cwd
Returns:
plot (matplotlib.pyplot): plot object
"""
num_incoming_weights = np.sum(np.array(weights) > 0, axis=0)
plt.figure(figsize=(12, 5))
plt.xlabel("Number of connections")
plt.ylabel("Probability")
# Fit a normal distribution to the data
mu, std = norm.fit(num_incoming_weights)
plt.hist(num_incoming_weights, bins=bin_size, density=True, alpha=0.6, color='b')
# PDF
xmin, xmax = plt.xlim()
x = np.linspace(xmin, xmax, max(num_incoming_weights))
p = norm.pdf(x, mu, std)
plt.plot(x, p, 'k', linewidth=2)
title = "Distribution of presynaptic connections: mu = %.2f, std = %.2f" % (mu, std)
plt.title(title)
if savefig:
plt.savefig("hist_incoming_conn")
return plt.show()
@staticmethod
def hist_outgoing_conn(
weights: np.array, bin_size: int, histtype: str, savefig: bool
):
"""Plot the histogram of number of incoming connections per neuron
Args:
weights (array): Connection weights
bin_size (int): Histogram bin size
histtype (str): Same as histtype matplotlib
savefig (bool): If True plot will be saved as png file in the cwd
Returns:
plot object """
# Plot the histogram of distribution of number of incoming connections in the network
num_outgoing_weights = np.sum(np.array(weights) > 0, axis=1)
plt.figure(figsize=(12, 5))
plt.xlabel("Number of connections")
plt.ylabel("Probability")
# Fit a normal distribution to the data
mu, std = norm.fit(num_outgoing_weights)
plt.hist(num_outgoing_weights, bins=bin_size, density=True, alpha=0.6, color='b')
# PDF
xmin, xmax = plt.xlim()
x = np.linspace(xmin, xmax, max(num_outgoing_weights))
p = norm.pdf(x, mu, std)
plt.plot(x, p, 'k', linewidth=2)
title = "Distribution of post synaptic connections: mu = %.2f, std = %.2f" % (mu, std)
plt.title(title)
if savefig:
plt.savefig("hist_outgoing_conn")
return plt.show()
@staticmethod
def network_connection_dynamics(
connection_counts: np.array, savefig: bool
):
"""Plot number of positive connection in the excitatory pool
Args:
connection_counts (array) - 1D Array of number of connections in the network per time step
savefig (bool) - If True plot will be saved as png file in the cwd
Returns:
plot object
"""
# Plot graph for entire simulation time period
_, ax1 = plt.subplots(figsize=(12, 5))
ax1.plot(connection_counts, label="Connection dynamics")
plt.margins(x=0)
ax1.set_xticks(ax1.get_xticks()[::2])
ax1.set_title("Network connection dynamics")
plt.ylabel("Number of active connections")
plt.xlabel("Time step")
plt.legend(loc="upper right")
plt.tight_layout()
if savefig:
plt.savefig("connection_dynamics")
return plt.show()
@staticmethod
def hist_firing_rate_network(spike_train: np.array, bin_size: int, savefig: bool):
""" Plot the histogram of firing rate (total number of neurons spike at each time step)
Args:
spike_train (array): Array of spike trains
bin_size (int): Histogram bin size
savefig (bool): If True, plot will be saved in the cwd
Returns:
plot object """
fr = np.count_nonzero(spike_train.tolist(), 1)
# Filter zero entries in firing rate list above
fr = list(filter(lambda a: a != 0, fr))
plt.title("Distribution of population activity without inactive time steps")
plt.xlabel("Spikes/time step")
plt.ylabel("Count")
plt.hist(fr, bin_size)
if savefig:
plt.savefig("hist_firing_rate_network.png")
return plt.show()
@staticmethod
def scatter_plot(spike_train: np.array, savefig: bool):
"""Scatter plot of spike trains
Args:
spike_train (list): Array of spike trains
with_firing_rates (bool): If True, firing rate of the network will be plotted
savefig (bool): If True, plot will be saved in the cwd
Returns:
plot object"""
# Conver the list of spike train into array
spike_train = np.asarray(spike_train)
# Get the indices where spike_train is 1
x, y = np.argwhere(spike_train.T == 1).T
plt.figure(figsize=(8, 5))
firing_rates = Statistics.firing_rate_network(spike_train).tolist()
plt.plot(firing_rates, label="Firing rate")
plt.legend(loc="upper left")
plt.scatter(y, x, s=0.1, color="black")
plt.title('Spike Trains')
plt.xlabel("Time step")
plt.ylabel("Neuron")
plt.legend(loc="upper left")
if savefig:
plt.savefig("ScatterSpikeTrain.png")
return plt.show()
@staticmethod
def raster_plot(spike_train: np.array, savefig: bool):
"""Raster plot of spike trains
Args:
spike_train (array): Array of spike trains
with_firing_rates (bool): If True, firing rate of the network will be plotted
savefig (bool): If True, plot will be saved in the cwd
Returns:
plot object"""
# Conver the list of spike train into array
spike_train = np.asarray(spike_train)
plt.figure(figsize=(11, 6))
firing_rates = Statistics.firing_rate_network(spike_train).tolist()
plt.plot(firing_rates, label="Firing rate")
plt.legend(loc="upper left")
plt.title('Spike Trains')
# Get the indices where spike_train is 1
x, y = np.argwhere(spike_train.T == 1).T
plt.plot(y, x, "|r")
plt.xlabel("Time step")
plt.ylabel("Neuron")
if savefig:
plt.savefig("RasterSpikeTrain.png")
return plt.show()
@staticmethod
def correlation(corr: np.array, savefig: bool):
"""Plot correlation between neurons
Args:
corr (array): Correlation matrix
savefig (bool): If true will save the plot at the current working directory
Returns:
matplotlib.pyplot: Neuron Correlation plot
"""
# Generate a mask for the upper triangle
mask = np.zeros_like(corr, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
f, ax = plt.subplots(figsize=(11, 9))
# Custom diverging colormap
cmap = sns.diverging_palette(220, 10, as_cmap=True)
sns.heatmap(
corr,
mask=mask,
cmap=cmap,
xticklabels=5,
yticklabels=5,
vmax=0.1,
center=0,
square=False,
linewidths=0.0,
cbar_kws={"shrink": 0.9},
)
if savefig:
plt.savefig("Correlation between neurons")
return None
@staticmethod
def isi_exponential_fit(
spike_train: np.array, neuron: int, bin_size: int, savefig: bool
):
"""Plot Exponential fit on the inter-spike intervals during training or simulation phase
Args:
spike_train (array): Array of spike trains
neuron (int): Target neuron
bin_size (int): Spike train will be splitted into bins of size bin_size
savefig (bool): If True, plot will be saved in the cwd
Returns:
plot object"""
isi = Statistics.spike_time_intervals(spike_train[:,neuron])
y, x = np.histogram(sorted(isi), bins=bin_size)
x = [int(i) for i in x]
y = [float(i) for i in y]
def exponential_func(y, a, b, c):
return a * np.exp(-b * np.array(y)) - c
# Curve fit
popt, _ = curve_fit(exponential_func, x[1:bin_size], y[1:bin_size])
plt.plot(
x[1:bin_size],
exponential_func(x[1:bin_size], *popt),
label="Exponential fit",
)
plt.title('Distribution of Inter Spike Intervals and Exponential Curve Fit')
plt.scatter(x[1:bin_size], y[1:bin_size], s=2.0, color="black", label="ISI")
plt.xlabel("ISI")
plt.ylabel("Frequency")
plt.legend()
if savefig:
plt.savefig("isi_exponential_fit")
return plt.show()
@staticmethod
def weight_distribution(weights: np.array, bin_size: int, savefig: bool):
"""Plot the distribution of synaptic weights
Args:
weights (array): Connection weights
bin_size (int): Spike train will be splited into bins of size bin_size
savefig (bool): If True, plot will be saved in the cwd
Returns:
plot object"""
weights = weights[
weights >= 0.01
] # Remove the weight values less than 0.01 # As reported in article SORN 2013
y, x = np.histogram(weights, bins=bin_size) # Create histogram with bin_size
plt.title('Synaptic weight distribution')
plt.scatter(x[:-1], y, s=2.0, c="black")
plt.xlabel("Connection strength")
plt.ylabel("Frequency")
if savefig:
plt.savefig("weight_distribution")
return plt.show()
@staticmethod
def linear_lognormal_fit(weights: np.array, num_points: int, savefig: bool):
"""Lognormal curve fit on connection weight distribution
Args:
weights (array): Connection weights
num_points(int): Number of points to be plotted in the x axis
savefig(bool): If True, plot will be saved in the cwd
Returns:
plot object"""
weights = np.array(weights.tolist())
weights = weights[weights >= 0.01]
M = float(np.mean(weights)) # Geometric mean
s = float(np.std(weights)) # Geometric standard deviation
# Lognormal distribution parameters
mu = float(np.mean(np.log(weights))) # Mean of log(X)
sigma = float(np.std(np.log(weights))) # Standard deviation of log(X)
shape = sigma # Scipy's shape parameter
scale = np.exp(mu) # Scipy's scale parameter
median = np.exp(mu)
mode = np.exp(mu - sigma ** 2) # Note that mode depends on both M and s
mean = np.exp(mu + (sigma ** 2 / 2)) # Note that mean depends on both M and s
x = np.linspace(
np.min(weights), np.max(weights), num=num_points
)
pdf = stats.lognorm.pdf(
x, shape, loc=0, scale=scale
)
plt.figure(figsize=(12, 4.5))
plt.title('Curve fit on connection weight distribution')
# Figure on linear scale
plt.subplot(121)
plt.plot(x, pdf)
plt.vlines(mode, 0, pdf.max(), linestyle=":", label="Mode")
plt.vlines(
mean,
0,
stats.lognorm.pdf(mean, shape, loc=0, scale=scale),
linestyle="--",
color="green",
label="Mean",
)
plt.vlines(
median,
0,
stats.lognorm.pdf(median, shape, loc=0, scale=scale),
color="blue",
label="Median",
)
plt.ylim(ymin=0)
plt.xlabel("Weight")
plt.title("Linear scale")
plt.legend()
# Figure on logarithmic scale
plt.subplot(122)
plt.semilogx(x, pdf)
plt.vlines(mode, 0, pdf.max(), linestyle=":", label="Mode")
plt.vlines(
mean,
0,
stats.lognorm.pdf(mean, shape, loc=0, scale=scale),
linestyle="--",
color="green",
label="Mean",
)
plt.vlines(
median,
0,
stats.lognorm.pdf(median, shape, loc=0, scale=scale),
color="blue",
label="Median",
)
plt.ylim(ymin=0)
plt.xlabel("Weight")
plt.title("Logarithmic scale")
plt.legend()
if savefig:
plt.savefig("LinearLognormalFit")
return plt.show()
@staticmethod
def plot_network(corr: np.array, corr_thres: float, fig_name: str = None):
"""Network x graphical visualization of the network using the correlation matrix
Args:
corr (array): Correlation between neurons
corr_thres (array): Threshold to prune the connection. Smaller the threshold,
higher the density of connections
fig_name (array, optional): Name of the figure. Defaults to None.
Returns:
matplotlib.pyplot: Plot instance
"""
df = pd.DataFrame(corr)
links = df.stack().reset_index()
links.columns = ["var1", "var2", "value"]
links_filtered = links.loc[
(links["value"] > corr_thres) & (links["var1"] != links["var2"])
]
G = nx.from_pandas_edgelist(links_filtered, "var1", "var2")
plt.figure(figsize=(50, 50))
nx.draw(
G,
with_labels=True,
node_color="orange",
node_size=50,
linewidths=5,
font_size=10,
)
plt.text(0.1, 0.9, "%s" % corr_thres)
plt.savefig("%s" % fig_name)
plt.show()
@staticmethod
def hamming_distance(hamming_dist: list, savefig: bool):
"""Hamming distance between true netorks states and perturbed network states
Args:
hamming_dist (list): Hamming distance values
savefig (bool): If True, save the fig at current working directory
Returns:
matplotlib.pyplot: Hamming distance between true and perturbed network states
"""
plt.figure(figsize=(15, 6))
plt.title("Hamming distance between actual and perturbed states")
plt.xlabel("Time steps")
plt.ylabel("Hamming distance")
plt.plot(hamming_dist)
if savefig:
plt.savefig("HammingDistance")
return plt.show()
class Statistics(object):
""" Wrapper class for statistical analysis methods """
def __init__(self):
pass
@staticmethod
def firing_rate_neuron(spike_train: np.array, neuron: int, bin_size: int):
"""Measure spike rate of given neuron during given time window
Args:
spike_train (array): Array of spike trains
neuron (int): Target neuron in the reservoir
bin_size (int): Divide the spike trains into bins of size bin_size
Returns:
int: firing_rate """
time_period = len(spike_train[:, 0])
neuron_spike_train = spike_train[:, neuron]
# Split the list(neuron_spike_train) into sub lists of length time_step
samples_spike_train = [
neuron_spike_train[i : i + bin_size]
for i in range(0, len(neuron_spike_train), bin_size)
]
spike_rate = 0.0
for _, spike_train in enumerate(samples_spike_train):
spike_rate += list(spike_train).count(1.0)
spike_rate = spike_rate * bin_size / time_period
return time_period, bin_size, spike_rate
@staticmethod
def firing_rate_network(spike_train: np.array):
"""Calculate number of neurons spikes at each time step.Firing rate of the network
Args:
spike_train (array): Array of spike trains
Returns:
int: firing_rate """
firing_rate = np.count_nonzero(spike_train.tolist(), 1)
return firing_rate
@staticmethod
def scale_dependent_smoothness_measure(firing_rates: list):
"""Smoothem the firing rate depend on its scale. Smaller values corresponds to smoother series
Args:
firing_rates (list): List of number of active neurons per time step
Returns:
sd_diff (list): Float value signifies the smoothness of the semantic changes in firing rates
"""
diff = np.diff(firing_rates)
sd_diff = np.std(diff)
return sd_diff
@staticmethod
def scale_independent_smoothness_measure(firing_rates: list):
"""Smoothem the firing rate independent of its scale. Smaller values corresponds to smoother series
Args:
firing_rates (list): List of number of active neurons per time step
Returns:
coeff_var (list):Float value signifies the smoothness of the semantic changes in firing rates """
diff = np.diff(firing_rates)
mean_diff = np.mean(diff)
sd_diff = np.std(diff)
coeff_var = sd_diff / abs(mean_diff)
return coeff_var
@staticmethod
def autocorr(firing_rates: list, t: int = 2):
"""
Score interpretation
- scores near 1 imply a smoothly varying series
- scores near 0 imply that there's no overall linear relationship between a data point and the following one (that is, plot(x[-length(x)],x[-1]) won't give a scatter plot with any apparent linearity)
- scores near -1 suggest that the series is jagged in a particular way: if one point is above the mean, the next is likely to be below the mean by about the same amount, and vice versa.
Args:
firing_rates (list): Firing rates of the network
t (int, optional): Window size. Defaults to 2.
Returns:
array: Autocorrelation between neurons given their firing rates
"""
return np.corrcoef(
np.array(
[
firing_rates[0 : len(firing_rates) - t],
firing_rates[t : len(firing_rates)],
]
)
)
@staticmethod
def avg_corr_coeff(spike_train: np.array):
"""Measure Average Pearson correlation coeffecient between neurons
Args:
spike_train (array): Neural activity
Returns:
array: Average correlation coeffecient"""
corr_mat = np.corrcoef(np.asarray(spike_train).T)
avg_corr = np.sum(corr_mat, axis=1) / 200
corr_coeff = (
avg_corr.sum() / 200
) # 2D to 1D and either upper or lower half of correlation matrix.
return corr_mat, corr_coeff
@staticmethod
def spike_times(spike_train: np.array):
"""Get the time instants at which neuron spikes
Args:
spike_train (array): Spike trains of neurons
Returns:
(array): Spike time of each neurons in the pool"""
times = np.where(spike_train == 1.0)
return times
@staticmethod
def spike_time_intervals(spike_train):
"""Generate spike time intervals spike_trains
Args:
spike_train (array): Network activity
Returns:
list: Inter spike intervals for each neuron in the reservoir
"""
spike_times = Statistics.spike_times(spike_train)
isi = np.diff(spike_times[-1])
return isi
@staticmethod
def hamming_distance(actual_spike_train: np.array, perturbed_spike_train: np.array):
"""Hamming distance between true netorks states and perturbed network states
Args:
actual_spike_train (np.array): True network's states
perturbed_spike_train (np.array): Perturbated network's states
Returns:
float: Hamming distance between true and perturbed network states
"""
hd = [
np.count_nonzero(actual_spike_train[i] != perturbed_spike_train[i])
for i in range(len(actual_spike_train))
]
return hd
@staticmethod
def fanofactor(spike_train: np.array, neuron: int, window_size: int):
"""Investigate whether neuronal spike generation is a poisson process
Args:
spike_train (np.array): Spike train of neurons in the reservoir
neuron (int): Target neuron in the pool
window_size (int): Sliding window size for time step ranges to be considered for measuring the fanofactor
Returns:
float : Fano factor of the neuron spike train
"""
# Choose activity of random neuron
neuron_act = spike_train[:, neuron]
# Divide total observations into 'tws' time windows of size 'ws' for a neuron 60
tws = np.split(neuron_act, window_size)
fr = []
for i in range(len(tws)):
fr.append(np.count_nonzero(tws[i]))
# print('Firing rate of the neuron during each time window of size %s is %s' %(ws,fr))
mean_firing_rate = np.mean(fr)
variance_firing_rate = np.var(fr)
fano_factor = variance_firing_rate / mean_firing_rate
return mean_firing_rate, variance_firing_rate, fano_factor
@staticmethod
def spike_source_entropy(spike_train: np.array, num_neurons: int):
"""Measure the uncertainty about the origin of spike from the network using entropy
Args:
spike_train (np.array): Spike train of neurons
num_neurons (int): Number of neurons in the reservoir
Returns:
int : Spike source entropy of the network
"""
# Number of spikes from each neuron during the interval
n_spikes = np.count_nonzero(spike_train, axis=0)
p = n_spikes / np.count_nonzero(
spike_train
) # Probability of each neuron that can generate spike in next step
# print(p) # Note: pi shouldn't be zero
sse = np.sum([pi * np.log(pi) for pi in p]) / np.log(
1 / num_neurons
) # Spike source entropy
return sse
| 30.537801 | 207 | 0.596213 | from __future__ import division
import numpy as np
from scipy.stats import norm
import random
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.optimize import curve_fit
from scipy import stats
import networkx as nx
import pandas as pd
from mpl_toolkits.axes_grid1.inset_locator import InsetPosition
class Initializer(object):
def __init__(self):
pass
@staticmethod
def generate_strong_inp(length: int, reservoir_size: int):
inp = [0] * reservoir_size
x = [0] * length
idx = np.random.choice(length, np.random.randint(reservoir_size))
for i in idx:
x[i] = 1.0e4
inp[: len(x)] = x
return inp, idx
@staticmethod
def multi_one_hot_inp(ne: int, inputs: list, n_nodes_per_inp: int):
one_hot = np.zeros((ne, len(inputs)))
idxs = []
for _ in range(n_nodes_per_inp):
idxs.append(random.sample(range(0, ne), len(inputs)))
idxs = list(zip(*idxs))
j = 0
for idx_list in idxs:
for i in idx_list:
one_hot[i][j] = 1
j += 1
return one_hot, idxs
@staticmethod
def generate_gaussian_inputs(length: int, reservoir_size: int):
out = [0] * reservoir_size
x = [0] * length
idx = np.random.choice(length, np.random.randint(reservoir_size))
inp = np.random.normal(length)
for i in idx:
x[i] = inp[i]
out[: len(x)] = x
return out, idx
@staticmethod
def normalize_weight_matrix(weight_matrix: np.array):
normalized_weight_matrix = weight_matrix / np.sum(weight_matrix, axis=0)
return normalized_weight_matrix
@staticmethod
def generate_lambd_connections(
synaptic_connection: str, ne: int, ni: int, lambd_w: int, lambd_std: int
):
if synaptic_connection == "EE":
lambdas_incoming = norm.ppf(
np.random.random(ne), loc=lambd_w, scale=lambd_std
).astype(int)
list_neurons = list(range(ne))
connection_weights = np.zeros((ne, ne))
ncoming_weights = np.random.uniform(0.0, 0.1, sum(lambdas_incoming))
global_incoming_weights_idx = 0
for neuron in list_neurons:
possible_connections = list_neurons.copy()
possible_connections.remove(
neuron
)
possible_incoming_connections = random.sample(
possible_connections, lambdas_incoming[neuron]
)
incoming_weights_neuron = global_incoming_weights[
global_incoming_weights_idx : global_incoming_weights_idx
+ lambdas_incoming[neuron]
]
for incoming_idx, incoming_weight in enumerate(incoming_weights_neuron):
connection_weights[possible_incoming_connections[incoming_idx]][
neuron
] = incoming_weight
global_incoming_weights_idx += lambdas_incoming[neuron]
return connection_weights
if synaptic_connection == "EI":
lambdas = norm.ppf(
np.random.random(ni), loc=lambd_w, scale=lambd_std
).astype(int)
list_neurons = list(range(ni))
connection_weights = np.zeros((ni, ne))
global_outgoing_weights = np.random.uniform(0.0, 0.1, sum(lambdas))
global_outgoing_weights_idx = 0
for neuron in list_neurons:
possible_connections = list(range(ne))
possible_outgoing_connections = random.sample(
possible_connections, lambdas[neuron]
)
outgoing_weights = global_outgoing_weights[
global_outgoing_weights_idx : global_outgoing_weights_idx
+ lambdas[neuron]
]
for outgoing_idx, outgoing_weight in enumerate(
outgoing_weights
):
connection_weights[neuron][
possible_outgoing_connections[outgoing_idx]
] = outgoing_weight
global_outgoing_weights_idx += lambdas[neuron]
return connection_weights
@staticmethod
def get_incoming_connection_dict(weights: np.array):
connection_dict = dict.fromkeys(range(1, len(weights) + 1), 0)
for i in range(len(weights[0])):
connection_dict[i] = list(np.nonzero(weights[:, i])[0])
return connection_dict
@staticmethod
def get_outgoing_connection_dict(weights: np.array):
connection_dict = dict.fromkeys(range(1, len(weights) + 1), 1)
for i in range(len(weights[0])):
connection_dict[i] = list(np.nonzero(weights[i, :])[0])
return connection_dict
@staticmethod
def prune_small_weights(weights: np.array, cutoff_weight: float):
weights[weights <= cutoff_weight] = cutoff_weight
return weights
@staticmethod
def set_max_cutoff_weight(weights: np.array, cutoff_weight: float):
weights[weights > cutoff_weight] = cutoff_weight
return weights
@staticmethod
def get_unconnected_indexes(wee: np.array):
i, j = np.where(wee <= 0.0)
indices = list(zip(i, j))
self_conn_removed = []
for i, idxs in enumerate(indices):
if idxs[0] != idxs[1]:
self_conn_removed.append(indices[i])
return self_conn_removed
@staticmethod
def white_gaussian_noise(mu: float, sigma: float, t: int):
noise = np.random.normal(mu, sigma, t)
return np.expand_dims(noise, 1)
@staticmethod
def zero_sum_incoming_check(weights: np.array):
zero_sum_incomings = np.where(np.sum(weights, axis=0) == 0.0)
if len(zero_sum_incomings[-1]) == 0:
return weights
else:
for zero_sum_incoming in zero_sum_incomings[-1]:
rand_indices = np.random.randint(
int(weights.shape[0] * 0.2), size=2
)
rand_values = np.random.uniform(0.0, 0.1, 2)
for i, idx in enumerate(rand_indices):
weights[:, zero_sum_incoming][idx] = rand_values[i]
return weights
class Plotter(object):
def __init__(self):
pass
@staticmethod
def hist_incoming_conn(
weights: np.array, bin_size: int, histtype: str, savefig: bool
):
num_incoming_weights = np.sum(np.array(weights) > 0, axis=0)
plt.figure(figsize=(12, 5))
plt.xlabel("Number of connections")
plt.ylabel("Probability")
mu, std = norm.fit(num_incoming_weights)
plt.hist(num_incoming_weights, bins=bin_size, density=True, alpha=0.6, color='b')
xmin, xmax = plt.xlim()
x = np.linspace(xmin, xmax, max(num_incoming_weights))
p = norm.pdf(x, mu, std)
plt.plot(x, p, 'k', linewidth=2)
title = "Distribution of presynaptic connections: mu = %.2f, std = %.2f" % (mu, std)
plt.title(title)
if savefig:
plt.savefig("hist_incoming_conn")
return plt.show()
@staticmethod
def hist_outgoing_conn(
weights: np.array, bin_size: int, histtype: str, savefig: bool
):
num_outgoing_weights = np.sum(np.array(weights) > 0, axis=1)
plt.figure(figsize=(12, 5))
plt.xlabel("Number of connections")
plt.ylabel("Probability")
mu, std = norm.fit(num_outgoing_weights)
plt.hist(num_outgoing_weights, bins=bin_size, density=True, alpha=0.6, color='b')
xmin, xmax = plt.xlim()
x = np.linspace(xmin, xmax, max(num_outgoing_weights))
p = norm.pdf(x, mu, std)
plt.plot(x, p, 'k', linewidth=2)
title = "Distribution of post synaptic connections: mu = %.2f, std = %.2f" % (mu, std)
plt.title(title)
if savefig:
plt.savefig("hist_outgoing_conn")
return plt.show()
@staticmethod
def network_connection_dynamics(
connection_counts: np.array, savefig: bool
):
_, ax1 = plt.subplots(figsize=(12, 5))
ax1.plot(connection_counts, label="Connection dynamics")
plt.margins(x=0)
ax1.set_xticks(ax1.get_xticks()[::2])
ax1.set_title("Network connection dynamics")
plt.ylabel("Number of active connections")
plt.xlabel("Time step")
plt.legend(loc="upper right")
plt.tight_layout()
if savefig:
plt.savefig("connection_dynamics")
return plt.show()
@staticmethod
def hist_firing_rate_network(spike_train: np.array, bin_size: int, savefig: bool):
fr = np.count_nonzero(spike_train.tolist(), 1)
fr = list(filter(lambda a: a != 0, fr))
plt.title("Distribution of population activity without inactive time steps")
plt.xlabel("Spikes/time step")
plt.ylabel("Count")
plt.hist(fr, bin_size)
if savefig:
plt.savefig("hist_firing_rate_network.png")
return plt.show()
@staticmethod
def scatter_plot(spike_train: np.array, savefig: bool):
spike_train = np.asarray(spike_train)
x, y = np.argwhere(spike_train.T == 1).T
plt.figure(figsize=(8, 5))
firing_rates = Statistics.firing_rate_network(spike_train).tolist()
plt.plot(firing_rates, label="Firing rate")
plt.legend(loc="upper left")
plt.scatter(y, x, s=0.1, color="black")
plt.title('Spike Trains')
plt.xlabel("Time step")
plt.ylabel("Neuron")
plt.legend(loc="upper left")
if savefig:
plt.savefig("ScatterSpikeTrain.png")
return plt.show()
@staticmethod
def raster_plot(spike_train: np.array, savefig: bool):
spike_train = np.asarray(spike_train)
plt.figure(figsize=(11, 6))
firing_rates = Statistics.firing_rate_network(spike_train).tolist()
plt.plot(firing_rates, label="Firing rate")
plt.legend(loc="upper left")
plt.title('Spike Trains')
x, y = np.argwhere(spike_train.T == 1).T
plt.plot(y, x, "|r")
plt.xlabel("Time step")
plt.ylabel("Neuron")
if savefig:
plt.savefig("RasterSpikeTrain.png")
return plt.show()
@staticmethod
def correlation(corr: np.array, savefig: bool):
mask = np.zeros_like(corr, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
f, ax = plt.subplots(figsize=(11, 9))
cmap = sns.diverging_palette(220, 10, as_cmap=True)
sns.heatmap(
corr,
mask=mask,
cmap=cmap,
xticklabels=5,
yticklabels=5,
vmax=0.1,
center=0,
square=False,
linewidths=0.0,
cbar_kws={"shrink": 0.9},
)
if savefig:
plt.savefig("Correlation between neurons")
return None
@staticmethod
def isi_exponential_fit(
spike_train: np.array, neuron: int, bin_size: int, savefig: bool
):
isi = Statistics.spike_time_intervals(spike_train[:,neuron])
y, x = np.histogram(sorted(isi), bins=bin_size)
x = [int(i) for i in x]
y = [float(i) for i in y]
def exponential_func(y, a, b, c):
return a * np.exp(-b * np.array(y)) - c
popt, _ = curve_fit(exponential_func, x[1:bin_size], y[1:bin_size])
plt.plot(
x[1:bin_size],
exponential_func(x[1:bin_size], *popt),
label="Exponential fit",
)
plt.title('Distribution of Inter Spike Intervals and Exponential Curve Fit')
plt.scatter(x[1:bin_size], y[1:bin_size], s=2.0, color="black", label="ISI")
plt.xlabel("ISI")
plt.ylabel("Frequency")
plt.legend()
if savefig:
plt.savefig("isi_exponential_fit")
return plt.show()
@staticmethod
def weight_distribution(weights: np.array, bin_size: int, savefig: bool):
weights = weights[
weights >= 0.01
] ts, bins=bin_size)
plt.title('Synaptic weight distribution')
plt.scatter(x[:-1], y, s=2.0, c="black")
plt.xlabel("Connection strength")
plt.ylabel("Frequency")
if savefig:
plt.savefig("weight_distribution")
return plt.show()
@staticmethod
def linear_lognormal_fit(weights: np.array, num_points: int, savefig: bool):
weights = np.array(weights.tolist())
weights = weights[weights >= 0.01]
M = float(np.mean(weights))
s = float(np.std(weights))
mu = float(np.mean(np.log(weights)))
sigma = float(np.std(np.log(weights)))
shape = sigma
scale = np.exp(mu) # Scipy's scale parameter
median = np.exp(mu)
mode = np.exp(mu - sigma ** 2)
mean = np.exp(mu + (sigma ** 2 / 2))
x = np.linspace(
np.min(weights), np.max(weights), num=num_points
)
pdf = stats.lognorm.pdf(
x, shape, loc=0, scale=scale
)
plt.figure(figsize=(12, 4.5))
plt.title('Curve fit on connection weight distribution')
plt.subplot(121)
plt.plot(x, pdf)
plt.vlines(mode, 0, pdf.max(), linestyle=":", label="Mode")
plt.vlines(
mean,
0,
stats.lognorm.pdf(mean, shape, loc=0, scale=scale),
linestyle="--",
color="green",
label="Mean",
)
plt.vlines(
median,
0,
stats.lognorm.pdf(median, shape, loc=0, scale=scale),
color="blue",
label="Median",
)
plt.ylim(ymin=0)
plt.xlabel("Weight")
plt.title("Linear scale")
plt.legend()
plt.subplot(122)
plt.semilogx(x, pdf)
plt.vlines(mode, 0, pdf.max(), linestyle=":", label="Mode")
plt.vlines(
mean,
0,
stats.lognorm.pdf(mean, shape, loc=0, scale=scale),
linestyle="--",
color="green",
label="Mean",
)
plt.vlines(
median,
0,
stats.lognorm.pdf(median, shape, loc=0, scale=scale),
color="blue",
label="Median",
)
plt.ylim(ymin=0)
plt.xlabel("Weight")
plt.title("Logarithmic scale")
plt.legend()
if savefig:
plt.savefig("LinearLognormalFit")
return plt.show()
@staticmethod
def plot_network(corr: np.array, corr_thres: float, fig_name: str = None):
df = pd.DataFrame(corr)
links = df.stack().reset_index()
links.columns = ["var1", "var2", "value"]
links_filtered = links.loc[
(links["value"] > corr_thres) & (links["var1"] != links["var2"])
]
G = nx.from_pandas_edgelist(links_filtered, "var1", "var2")
plt.figure(figsize=(50, 50))
nx.draw(
G,
with_labels=True,
node_color="orange",
node_size=50,
linewidths=5,
font_size=10,
)
plt.text(0.1, 0.9, "%s" % corr_thres)
plt.savefig("%s" % fig_name)
plt.show()
@staticmethod
def hamming_distance(hamming_dist: list, savefig: bool):
plt.figure(figsize=(15, 6))
plt.title("Hamming distance between actual and perturbed states")
plt.xlabel("Time steps")
plt.ylabel("Hamming distance")
plt.plot(hamming_dist)
if savefig:
plt.savefig("HammingDistance")
return plt.show()
class Statistics(object):
def __init__(self):
pass
@staticmethod
def firing_rate_neuron(spike_train: np.array, neuron: int, bin_size: int):
time_period = len(spike_train[:, 0])
neuron_spike_train = spike_train[:, neuron]
samples_spike_train = [
neuron_spike_train[i : i + bin_size]
for i in range(0, len(neuron_spike_train), bin_size)
]
spike_rate = 0.0
for _, spike_train in enumerate(samples_spike_train):
spike_rate += list(spike_train).count(1.0)
spike_rate = spike_rate * bin_size / time_period
return time_period, bin_size, spike_rate
@staticmethod
def firing_rate_network(spike_train: np.array):
firing_rate = np.count_nonzero(spike_train.tolist(), 1)
return firing_rate
@staticmethod
def scale_dependent_smoothness_measure(firing_rates: list):
diff = np.diff(firing_rates)
sd_diff = np.std(diff)
return sd_diff
@staticmethod
def scale_independent_smoothness_measure(firing_rates: list):
diff = np.diff(firing_rates)
mean_diff = np.mean(diff)
sd_diff = np.std(diff)
coeff_var = sd_diff / abs(mean_diff)
return coeff_var
@staticmethod
def autocorr(firing_rates: list, t: int = 2):
return np.corrcoef(
np.array(
[
firing_rates[0 : len(firing_rates) - t],
firing_rates[t : len(firing_rates)],
]
)
)
@staticmethod
def avg_corr_coeff(spike_train: np.array):
corr_mat = np.corrcoef(np.asarray(spike_train).T)
avg_corr = np.sum(corr_mat, axis=1) / 200
corr_coeff = (
avg_corr.sum() / 200
)
return corr_mat, corr_coeff
@staticmethod
def spike_times(spike_train: np.array):
times = np.where(spike_train == 1.0)
return times
@staticmethod
def spike_time_intervals(spike_train):
spike_times = Statistics.spike_times(spike_train)
isi = np.diff(spike_times[-1])
return isi
@staticmethod
def hamming_distance(actual_spike_train: np.array, perturbed_spike_train: np.array):
hd = [
np.count_nonzero(actual_spike_train[i] != perturbed_spike_train[i])
for i in range(len(actual_spike_train))
]
return hd
@staticmethod
def fanofactor(spike_train: np.array, neuron: int, window_size: int):
neuron_act = spike_train[:, neuron]
tws = np.split(neuron_act, window_size)
fr = []
for i in range(len(tws)):
fr.append(np.count_nonzero(tws[i]))
mean_firing_rate = np.mean(fr)
variance_firing_rate = np.var(fr)
fano_factor = variance_firing_rate / mean_firing_rate
return mean_firing_rate, variance_firing_rate, fano_factor
@staticmethod
def spike_source_entropy(spike_train: np.array, num_neurons: int):
n_spikes = np.count_nonzero(spike_train, axis=0)
p = n_spikes / np.count_nonzero(
spike_train
)
np.log(pi) for pi in p]) / np.log(
1 / num_neurons
) # Spike source entropy
return sse
| true | true |
f72b65415eb00899b5a39a72574ea82cbc1d04c6 | 21,954 | py | Python | Lib/site-packages/django/conf/global_settings.py | Lucas11200/LocaPy | 5d1f214c091aa3703b2ff7d3c0713a91ed4a1f48 | [
"bzip2-1.0.6"
] | 42 | 2019-03-01T09:51:13.000Z | 2021-07-22T12:22:49.000Z | Lib/site-packages/django/conf/global_settings.py | Lucas11200/LocaPy | 5d1f214c091aa3703b2ff7d3c0713a91ed4a1f48 | [
"bzip2-1.0.6"
] | 31 | 2018-08-26T14:01:16.000Z | 2018-10-19T07:35:57.000Z | virtual/lib/python3.6/site-packages/django/conf/global_settings.py | eyern/instagram_clone | c18da15b35d28d91c3f63904af9d5da4e8e3e8ae | [
"MIT"
] | 145 | 2019-03-14T18:54:45.000Z | 2022-03-04T20:25:31.000Z | """
Default Django settings. Override these with settings in the module pointed to
by the DJANGO_SETTINGS_MODULE environment variable.
"""
# This is defined here as a do-nothing function because we can't import
# django.utils.translation -- that module depends on the settings.
def gettext_noop(s):
return s
####################
# CORE #
####################
DEBUG = False
# Whether the framework should propagate raw exceptions rather than catching
# them. This is useful under some testing situations and should never be used
# on a live site.
DEBUG_PROPAGATE_EXCEPTIONS = False
# People who get code error notifications.
# In the format [('Full Name', 'email@example.com'), ('Full Name', 'anotheremail@example.com')]
ADMINS = []
# List of IP addresses, as strings, that:
# * See debug comments, when DEBUG is true
# * Receive x-headers
INTERNAL_IPS = []
# Hosts/domain names that are valid for this site.
# "*" matches anything, ".example.com" matches example.com and all subdomains
ALLOWED_HOSTS = []
# Local time zone for this installation. All choices can be found here:
# https://en.wikipedia.org/wiki/List_of_tz_zones_by_name (although not all
# systems may support all possibilities). When USE_TZ is True, this is
# interpreted as the default user time zone.
TIME_ZONE = 'America/Chicago'
# If you set this to True, Django will use timezone-aware datetimes.
USE_TZ = False
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
# Languages we provide translations for, out of the box.
LANGUAGES = [
('af', gettext_noop('Afrikaans')),
('ar', gettext_noop('Arabic')),
('ast', gettext_noop('Asturian')),
('az', gettext_noop('Azerbaijani')),
('bg', gettext_noop('Bulgarian')),
('be', gettext_noop('Belarusian')),
('bn', gettext_noop('Bengali')),
('br', gettext_noop('Breton')),
('bs', gettext_noop('Bosnian')),
('ca', gettext_noop('Catalan')),
('cs', gettext_noop('Czech')),
('cy', gettext_noop('Welsh')),
('da', gettext_noop('Danish')),
('de', gettext_noop('German')),
('dsb', gettext_noop('Lower Sorbian')),
('el', gettext_noop('Greek')),
('en', gettext_noop('English')),
('en-au', gettext_noop('Australian English')),
('en-gb', gettext_noop('British English')),
('eo', gettext_noop('Esperanto')),
('es', gettext_noop('Spanish')),
('es-ar', gettext_noop('Argentinian Spanish')),
('es-co', gettext_noop('Colombian Spanish')),
('es-mx', gettext_noop('Mexican Spanish')),
('es-ni', gettext_noop('Nicaraguan Spanish')),
('es-ve', gettext_noop('Venezuelan Spanish')),
('et', gettext_noop('Estonian')),
('eu', gettext_noop('Basque')),
('fa', gettext_noop('Persian')),
('fi', gettext_noop('Finnish')),
('fr', gettext_noop('French')),
('fy', gettext_noop('Frisian')),
('ga', gettext_noop('Irish')),
('gd', gettext_noop('Scottish Gaelic')),
('gl', gettext_noop('Galician')),
('he', gettext_noop('Hebrew')),
('hi', gettext_noop('Hindi')),
('hr', gettext_noop('Croatian')),
('hsb', gettext_noop('Upper Sorbian')),
('hu', gettext_noop('Hungarian')),
('ia', gettext_noop('Interlingua')),
('id', gettext_noop('Indonesian')),
('io', gettext_noop('Ido')),
('is', gettext_noop('Icelandic')),
('it', gettext_noop('Italian')),
('ja', gettext_noop('Japanese')),
('ka', gettext_noop('Georgian')),
('kab', gettext_noop('Kabyle')),
('kk', gettext_noop('Kazakh')),
('km', gettext_noop('Khmer')),
('kn', gettext_noop('Kannada')),
('ko', gettext_noop('Korean')),
('lb', gettext_noop('Luxembourgish')),
('lt', gettext_noop('Lithuanian')),
('lv', gettext_noop('Latvian')),
('mk', gettext_noop('Macedonian')),
('ml', gettext_noop('Malayalam')),
('mn', gettext_noop('Mongolian')),
('mr', gettext_noop('Marathi')),
('my', gettext_noop('Burmese')),
('nb', gettext_noop('Norwegian Bokmål')),
('ne', gettext_noop('Nepali')),
('nl', gettext_noop('Dutch')),
('nn', gettext_noop('Norwegian Nynorsk')),
('os', gettext_noop('Ossetic')),
('pa', gettext_noop('Punjabi')),
('pl', gettext_noop('Polish')),
('pt', gettext_noop('Portuguese')),
('pt-br', gettext_noop('Brazilian Portuguese')),
('ro', gettext_noop('Romanian')),
('ru', gettext_noop('Russian')),
('sk', gettext_noop('Slovak')),
('sl', gettext_noop('Slovenian')),
('sq', gettext_noop('Albanian')),
('sr', gettext_noop('Serbian')),
('sr-latn', gettext_noop('Serbian Latin')),
('sv', gettext_noop('Swedish')),
('sw', gettext_noop('Swahili')),
('ta', gettext_noop('Tamil')),
('te', gettext_noop('Telugu')),
('th', gettext_noop('Thai')),
('tr', gettext_noop('Turkish')),
('tt', gettext_noop('Tatar')),
('udm', gettext_noop('Udmurt')),
('uk', gettext_noop('Ukrainian')),
('ur', gettext_noop('Urdu')),
('vi', gettext_noop('Vietnamese')),
('zh-hans', gettext_noop('Simplified Chinese')),
('zh-hant', gettext_noop('Traditional Chinese')),
]
# Languages using BiDi (right-to-left) layout
LANGUAGES_BIDI = ["he", "ar", "fa", "ur"]
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
LOCALE_PATHS = []
# Settings for language cookie
LANGUAGE_COOKIE_NAME = 'django_language'
LANGUAGE_COOKIE_AGE = None
LANGUAGE_COOKIE_DOMAIN = None
LANGUAGE_COOKIE_PATH = '/'
# If you set this to True, Django will format dates, numbers and calendars
# according to user current locale.
USE_L10N = False
# Not-necessarily-technical managers of the site. They get broken link
# notifications and other various emails.
MANAGERS = ADMINS
# Default content type and charset to use for all HttpResponse objects, if a
# MIME type isn't manually specified. These are used to construct the
# Content-Type header.
DEFAULT_CONTENT_TYPE = 'text/html'
DEFAULT_CHARSET = 'utf-8'
# Encoding of files read from disk (template and initial SQL files).
FILE_CHARSET = 'utf-8'
# Email address that error messages come from.
SERVER_EMAIL = 'root@localhost'
# Database connection info. If left empty, will default to the dummy backend.
DATABASES = {}
# Classes used to implement DB routing behavior.
DATABASE_ROUTERS = []
# The email backend to use. For possible shortcuts see django.core.mail.
# The default is to use the SMTP backend.
# Third-party backends can be specified by providing a Python path
# to a module that defines an EmailBackend class.
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# Host for sending email.
EMAIL_HOST = 'localhost'
# Port for sending email.
EMAIL_PORT = 25
# Whether to send SMTP 'Date' header in the local time zone or in UTC.
EMAIL_USE_LOCALTIME = False
# Optional SMTP authentication information for EMAIL_HOST.
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_USE_TLS = False
EMAIL_USE_SSL = False
EMAIL_SSL_CERTFILE = None
EMAIL_SSL_KEYFILE = None
EMAIL_TIMEOUT = None
# List of strings representing installed apps.
INSTALLED_APPS = []
TEMPLATES = []
# Default form rendering class.
FORM_RENDERER = 'django.forms.renderers.DjangoTemplates'
# Default email address to use for various automated correspondence from
# the site managers.
DEFAULT_FROM_EMAIL = 'webmaster@localhost'
# Subject-line prefix for email messages send with django.core.mail.mail_admins
# or ...mail_managers. Make sure to include the trailing space.
EMAIL_SUBJECT_PREFIX = '[Django] '
# Whether to append trailing slashes to URLs.
APPEND_SLASH = True
# Whether to prepend the "www." subdomain to URLs that don't have it.
PREPEND_WWW = False
# Override the server-derived value of SCRIPT_NAME
FORCE_SCRIPT_NAME = None
# List of compiled regular expression objects representing User-Agent strings
# that are not allowed to visit any page, systemwide. Use this for bad
# robots/crawlers. Here are a few examples:
# import re
# DISALLOWED_USER_AGENTS = [
# re.compile(r'^NaverBot.*'),
# re.compile(r'^EmailSiphon.*'),
# re.compile(r'^SiteSucker.*'),
# re.compile(r'^sohu-search'),
# ]
DISALLOWED_USER_AGENTS = []
ABSOLUTE_URL_OVERRIDES = {}
# List of compiled regular expression objects representing URLs that need not
# be reported by BrokenLinkEmailsMiddleware. Here are a few examples:
# import re
# IGNORABLE_404_URLS = [
# re.compile(r'^/apple-touch-icon.*\.png$'),
# re.compile(r'^/favicon.ico$'),
# re.compile(r'^/robots.txt$'),
# re.compile(r'^/phpmyadmin/'),
# re.compile(r'\.(cgi|php|pl)$'),
# ]
IGNORABLE_404_URLS = []
# A secret key for this particular Django installation. Used in secret-key
# hashing algorithms. Set this in your settings, or Django will complain
# loudly.
SECRET_KEY = ''
# Default file storage mechanism that holds media.
DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage'
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = None
# URL that handles the static files served from STATIC_ROOT.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = None
# List of upload handler classes to be applied in order.
FILE_UPLOAD_HANDLERS = [
'django.core.files.uploadhandler.MemoryFileUploadHandler',
'django.core.files.uploadhandler.TemporaryFileUploadHandler',
]
# Maximum size, in bytes, of a request before it will be streamed to the
# file system instead of into memory.
FILE_UPLOAD_MAX_MEMORY_SIZE = 2621440 # i.e. 2.5 MB
# Maximum size in bytes of request data (excluding file uploads) that will be
# read before a SuspiciousOperation (RequestDataTooBig) is raised.
DATA_UPLOAD_MAX_MEMORY_SIZE = 2621440 # i.e. 2.5 MB
# Maximum number of GET/POST parameters that will be read before a
# SuspiciousOperation (TooManyFieldsSent) is raised.
DATA_UPLOAD_MAX_NUMBER_FIELDS = 1000
# Directory in which upload streamed files will be temporarily saved. A value of
# `None` will make Django use the operating system's default temporary directory
# (i.e. "/tmp" on *nix systems).
FILE_UPLOAD_TEMP_DIR = None
# The numeric mode to set newly-uploaded files to. The value should be a mode
# you'd pass directly to os.chmod; see https://docs.python.org/library/os.html#files-and-directories.
FILE_UPLOAD_PERMISSIONS = None
# The numeric mode to assign to newly-created directories, when uploading files.
# The value should be a mode as you'd pass to os.chmod;
# see https://docs.python.org/library/os.html#files-and-directories.
FILE_UPLOAD_DIRECTORY_PERMISSIONS = None
# Python module path where user will place custom format definition.
# The directory where this setting is pointing should contain subdirectories
# named as the locales, containing a formats.py file
# (i.e. "myproject.locale" for myproject/locale/en/formats.py etc. use)
FORMAT_MODULE_PATH = None
# Default formatting for date objects. See all available format strings here:
# https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'N j, Y'
# Default formatting for datetime objects. See all available format strings here:
# https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATETIME_FORMAT = 'N j, Y, P'
# Default formatting for time objects. See all available format strings here:
# https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
TIME_FORMAT = 'P'
# Default formatting for date objects when only the year and month are relevant.
# See all available format strings here:
# https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
YEAR_MONTH_FORMAT = 'F Y'
# Default formatting for date objects when only the month and day are relevant.
# See all available format strings here:
# https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
MONTH_DAY_FORMAT = 'F j'
# Default short formatting for date objects. See all available format strings here:
# https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
SHORT_DATE_FORMAT = 'm/d/Y'
# Default short formatting for datetime objects.
# See all available format strings here:
# https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
SHORT_DATETIME_FORMAT = 'm/d/Y P'
# Default formats to be used when parsing dates from input boxes, in order
# See all available format string here:
# https://docs.python.org/library/datetime.html#strftime-behavior
# * Note that these format strings are different from the ones to display dates
DATE_INPUT_FORMATS = [
'%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06'
'%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006'
'%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006'
'%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006'
'%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006'
]
# Default formats to be used when parsing times from input boxes, in order
# See all available format string here:
# https://docs.python.org/library/datetime.html#strftime-behavior
# * Note that these format strings are different from the ones to display dates
TIME_INPUT_FORMATS = [
'%H:%M:%S', # '14:30:59'
'%H:%M:%S.%f', # '14:30:59.000200'
'%H:%M', # '14:30'
]
# Default formats to be used when parsing dates and times from input boxes,
# in order
# See all available format string here:
# https://docs.python.org/library/datetime.html#strftime-behavior
# * Note that these format strings are different from the ones to display dates
DATETIME_INPUT_FORMATS = [
'%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59'
'%Y-%m-%d %H:%M:%S.%f', # '2006-10-25 14:30:59.000200'
'%Y-%m-%d %H:%M', # '2006-10-25 14:30'
'%Y-%m-%d', # '2006-10-25'
'%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59'
'%m/%d/%Y %H:%M:%S.%f', # '10/25/2006 14:30:59.000200'
'%m/%d/%Y %H:%M', # '10/25/2006 14:30'
'%m/%d/%Y', # '10/25/2006'
'%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59'
'%m/%d/%y %H:%M:%S.%f', # '10/25/06 14:30:59.000200'
'%m/%d/%y %H:%M', # '10/25/06 14:30'
'%m/%d/%y', # '10/25/06'
]
# First day of week, to be used on calendars
# 0 means Sunday, 1 means Monday...
FIRST_DAY_OF_WEEK = 0
# Decimal separator symbol
DECIMAL_SEPARATOR = '.'
# Boolean that sets whether to add thousand separator when formatting numbers
USE_THOUSAND_SEPARATOR = False
# Number of digits that will be together, when splitting them by
# THOUSAND_SEPARATOR. 0 means no grouping, 3 means splitting by thousands...
NUMBER_GROUPING = 0
# Thousand separator symbol
THOUSAND_SEPARATOR = ','
# The tablespaces to use for each model when not specified otherwise.
DEFAULT_TABLESPACE = ''
DEFAULT_INDEX_TABLESPACE = ''
# Default X-Frame-Options header value
X_FRAME_OPTIONS = 'SAMEORIGIN'
USE_X_FORWARDED_HOST = False
USE_X_FORWARDED_PORT = False
# The Python dotted path to the WSGI application that Django's internal server
# (runserver) will use. If `None`, the return value of
# 'django.core.wsgi.get_wsgi_application' is used, thus preserving the same
# behavior as previous versions of Django. Otherwise this should point to an
# actual WSGI application object.
WSGI_APPLICATION = None
# If your Django app is behind a proxy that sets a header to specify secure
# connections, AND that proxy ensures that user-submitted headers with the
# same name are ignored (so that people can't spoof it), set this value to
# a tuple of (header_name, header_value). For any requests that come in with
# that header/value, request.is_secure() will return True.
# WARNING! Only set this if you fully understand what you're doing. Otherwise,
# you may be opening yourself up to a security risk.
SECURE_PROXY_SSL_HEADER = None
##############
# MIDDLEWARE #
##############
# List of middleware to use. Order is important; in the request phase, these
# middleware will be applied in the order given, and in the response
# phase the middleware will be applied in reverse order.
MIDDLEWARE = []
############
# SESSIONS #
############
# Cache to store session data if using the cache session backend.
SESSION_CACHE_ALIAS = 'default'
# Cookie name. This can be whatever you want.
SESSION_COOKIE_NAME = 'sessionid'
# Age of cookie, in seconds (default: 2 weeks).
SESSION_COOKIE_AGE = 60 * 60 * 24 * 7 * 2
# A string like "example.com", or None for standard domain cookie.
SESSION_COOKIE_DOMAIN = None
# Whether the session cookie should be secure (https:// only).
SESSION_COOKIE_SECURE = False
# The path of the session cookie.
SESSION_COOKIE_PATH = '/'
# Whether to use the non-RFC standard httpOnly flag (IE, FF3+, others)
SESSION_COOKIE_HTTPONLY = True
# Whether to set the flag restricting cookie leaks on cross-site requests.
# This can be 'Lax', 'Strict', or None to disable the flag.
SESSION_COOKIE_SAMESITE = 'Lax'
# Whether to save the session data on every request.
SESSION_SAVE_EVERY_REQUEST = False
# Whether a user's session cookie expires when the Web browser is closed.
SESSION_EXPIRE_AT_BROWSER_CLOSE = False
# The module to store session data
SESSION_ENGINE = 'django.contrib.sessions.backends.db'
# Directory to store session files if using the file session module. If None,
# the backend will use a sensible default.
SESSION_FILE_PATH = None
# class to serialize session data
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'
#########
# CACHE #
#########
# The cache backends to use.
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
}
}
CACHE_MIDDLEWARE_KEY_PREFIX = ''
CACHE_MIDDLEWARE_SECONDS = 600
CACHE_MIDDLEWARE_ALIAS = 'default'
##################
# AUTHENTICATION #
##################
AUTH_USER_MODEL = 'auth.User'
AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend']
LOGIN_URL = '/accounts/login/'
LOGIN_REDIRECT_URL = '/accounts/profile/'
LOGOUT_REDIRECT_URL = None
# The number of days a password reset link is valid for
PASSWORD_RESET_TIMEOUT_DAYS = 3
# the first hasher in this list is the preferred algorithm. any
# password using different algorithms will be converted automatically
# upon login
PASSWORD_HASHERS = [
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.Argon2PasswordHasher',
'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
]
AUTH_PASSWORD_VALIDATORS = []
###########
# SIGNING #
###########
SIGNING_BACKEND = 'django.core.signing.TimestampSigner'
########
# CSRF #
########
# Dotted path to callable to be used as view when a request is
# rejected by the CSRF middleware.
CSRF_FAILURE_VIEW = 'django.views.csrf.csrf_failure'
# Settings for CSRF cookie.
CSRF_COOKIE_NAME = 'csrftoken'
CSRF_COOKIE_AGE = 60 * 60 * 24 * 7 * 52
CSRF_COOKIE_DOMAIN = None
CSRF_COOKIE_PATH = '/'
CSRF_COOKIE_SECURE = False
CSRF_COOKIE_HTTPONLY = False
CSRF_COOKIE_SAMESITE = 'Lax'
CSRF_HEADER_NAME = 'HTTP_X_CSRFTOKEN'
CSRF_TRUSTED_ORIGINS = []
CSRF_USE_SESSIONS = False
############
# MESSAGES #
############
# Class to use as messages backend
MESSAGE_STORAGE = 'django.contrib.messages.storage.fallback.FallbackStorage'
# Default values of MESSAGE_LEVEL and MESSAGE_TAGS are defined within
# django.contrib.messages to avoid imports in this settings file.
###########
# LOGGING #
###########
# The callable to use to configure logging
LOGGING_CONFIG = 'logging.config.dictConfig'
# Custom logging configuration.
LOGGING = {}
# Default exception reporter filter class used in case none has been
# specifically assigned to the HttpRequest instance.
DEFAULT_EXCEPTION_REPORTER_FILTER = 'django.views.debug.SafeExceptionReporterFilter'
###########
# TESTING #
###########
# The name of the class to use to run the test suite
TEST_RUNNER = 'django.test.runner.DiscoverRunner'
# Apps that don't need to be serialized at test database creation time
# (only apps with migrations are to start with)
TEST_NON_SERIALIZED_APPS = []
############
# FIXTURES #
############
# The list of directories to search for fixtures
FIXTURE_DIRS = []
###############
# STATICFILES #
###############
# A list of locations of additional static files
STATICFILES_DIRS = []
# The default file storage backend used during the build process
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
]
##############
# MIGRATIONS #
##############
# Migration module overrides for apps, by app label.
MIGRATION_MODULES = {}
#################
# SYSTEM CHECKS #
#################
# List of all issues generated by system checks that should be silenced. Light
# issues like warnings, infos or debugs will not generate a message. Silencing
# serious issues like errors and criticals does not result in hiding the
# message, but Django will not stop you from e.g. running server.
SILENCED_SYSTEM_CHECKS = []
#######################
# SECURITY MIDDLEWARE #
#######################
SECURE_BROWSER_XSS_FILTER = False
SECURE_CONTENT_TYPE_NOSNIFF = False
SECURE_HSTS_INCLUDE_SUBDOMAINS = False
SECURE_HSTS_PRELOAD = False
SECURE_HSTS_SECONDS = 0
SECURE_REDIRECT_EXEMPT = []
SECURE_SSL_HOST = None
SECURE_SSL_REDIRECT = False
| 34.518868 | 101 | 0.701603 |
# django.utils.translation -- that module depends on the settings.
def gettext_noop(s):
return s
####################
# CORE #
####################
DEBUG = False
# Whether the framework should propagate raw exceptions rather than catching
# them. This is useful under some testing situations and should never be used
# on a live site.
DEBUG_PROPAGATE_EXCEPTIONS = False
# People who get code error notifications.
# In the format [('Full Name', 'email@example.com'), ('Full Name', 'anotheremail@example.com')]
ADMINS = []
# List of IP addresses, as strings, that:
# * See debug comments, when DEBUG is true
# * Receive x-headers
INTERNAL_IPS = []
# Hosts/domain names that are valid for this site.
# "*" matches anything, ".example.com" matches example.com and all subdomains
ALLOWED_HOSTS = []
# Local time zone for this installation. All choices can be found here:
# https://en.wikipedia.org/wiki/List_of_tz_zones_by_name (although not all
# systems may support all possibilities). When USE_TZ is True, this is
# interpreted as the default user time zone.
TIME_ZONE = 'America/Chicago'
# If you set this to True, Django will use timezone-aware datetimes.
USE_TZ = False
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
# Languages we provide translations for, out of the box.
LANGUAGES = [
('af', gettext_noop('Afrikaans')),
('ar', gettext_noop('Arabic')),
('ast', gettext_noop('Asturian')),
('az', gettext_noop('Azerbaijani')),
('bg', gettext_noop('Bulgarian')),
('be', gettext_noop('Belarusian')),
('bn', gettext_noop('Bengali')),
('br', gettext_noop('Breton')),
('bs', gettext_noop('Bosnian')),
('ca', gettext_noop('Catalan')),
('cs', gettext_noop('Czech')),
('cy', gettext_noop('Welsh')),
('da', gettext_noop('Danish')),
('de', gettext_noop('German')),
('dsb', gettext_noop('Lower Sorbian')),
('el', gettext_noop('Greek')),
('en', gettext_noop('English')),
('en-au', gettext_noop('Australian English')),
('en-gb', gettext_noop('British English')),
('eo', gettext_noop('Esperanto')),
('es', gettext_noop('Spanish')),
('es-ar', gettext_noop('Argentinian Spanish')),
('es-co', gettext_noop('Colombian Spanish')),
('es-mx', gettext_noop('Mexican Spanish')),
('es-ni', gettext_noop('Nicaraguan Spanish')),
('es-ve', gettext_noop('Venezuelan Spanish')),
('et', gettext_noop('Estonian')),
('eu', gettext_noop('Basque')),
('fa', gettext_noop('Persian')),
('fi', gettext_noop('Finnish')),
('fr', gettext_noop('French')),
('fy', gettext_noop('Frisian')),
('ga', gettext_noop('Irish')),
('gd', gettext_noop('Scottish Gaelic')),
('gl', gettext_noop('Galician')),
('he', gettext_noop('Hebrew')),
('hi', gettext_noop('Hindi')),
('hr', gettext_noop('Croatian')),
('hsb', gettext_noop('Upper Sorbian')),
('hu', gettext_noop('Hungarian')),
('ia', gettext_noop('Interlingua')),
('id', gettext_noop('Indonesian')),
('io', gettext_noop('Ido')),
('is', gettext_noop('Icelandic')),
('it', gettext_noop('Italian')),
('ja', gettext_noop('Japanese')),
('ka', gettext_noop('Georgian')),
('kab', gettext_noop('Kabyle')),
('kk', gettext_noop('Kazakh')),
('km', gettext_noop('Khmer')),
('kn', gettext_noop('Kannada')),
('ko', gettext_noop('Korean')),
('lb', gettext_noop('Luxembourgish')),
('lt', gettext_noop('Lithuanian')),
('lv', gettext_noop('Latvian')),
('mk', gettext_noop('Macedonian')),
('ml', gettext_noop('Malayalam')),
('mn', gettext_noop('Mongolian')),
('mr', gettext_noop('Marathi')),
('my', gettext_noop('Burmese')),
('nb', gettext_noop('Norwegian Bokmål')),
('ne', gettext_noop('Nepali')),
('nl', gettext_noop('Dutch')),
('nn', gettext_noop('Norwegian Nynorsk')),
('os', gettext_noop('Ossetic')),
('pa', gettext_noop('Punjabi')),
('pl', gettext_noop('Polish')),
('pt', gettext_noop('Portuguese')),
('pt-br', gettext_noop('Brazilian Portuguese')),
('ro', gettext_noop('Romanian')),
('ru', gettext_noop('Russian')),
('sk', gettext_noop('Slovak')),
('sl', gettext_noop('Slovenian')),
('sq', gettext_noop('Albanian')),
('sr', gettext_noop('Serbian')),
('sr-latn', gettext_noop('Serbian Latin')),
('sv', gettext_noop('Swedish')),
('sw', gettext_noop('Swahili')),
('ta', gettext_noop('Tamil')),
('te', gettext_noop('Telugu')),
('th', gettext_noop('Thai')),
('tr', gettext_noop('Turkish')),
('tt', gettext_noop('Tatar')),
('udm', gettext_noop('Udmurt')),
('uk', gettext_noop('Ukrainian')),
('ur', gettext_noop('Urdu')),
('vi', gettext_noop('Vietnamese')),
('zh-hans', gettext_noop('Simplified Chinese')),
('zh-hant', gettext_noop('Traditional Chinese')),
]
# Languages using BiDi (right-to-left) layout
LANGUAGES_BIDI = ["he", "ar", "fa", "ur"]
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
LOCALE_PATHS = []
# Settings for language cookie
LANGUAGE_COOKIE_NAME = 'django_language'
LANGUAGE_COOKIE_AGE = None
LANGUAGE_COOKIE_DOMAIN = None
LANGUAGE_COOKIE_PATH = '/'
# If you set this to True, Django will format dates, numbers and calendars
# according to user current locale.
USE_L10N = False
# Not-necessarily-technical managers of the site. They get broken link
# notifications and other various emails.
MANAGERS = ADMINS
# Default content type and charset to use for all HttpResponse objects, if a
# MIME type isn't manually specified. These are used to construct the
DEFAULT_CONTENT_TYPE = 'text/html'
DEFAULT_CHARSET = 'utf-8'
FILE_CHARSET = 'utf-8'
SERVER_EMAIL = 'root@localhost'
DATABASES = {}
DATABASE_ROUTERS = []
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'localhost'
EMAIL_PORT = 25
EMAIL_USE_LOCALTIME = False
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_USE_TLS = False
EMAIL_USE_SSL = False
EMAIL_SSL_CERTFILE = None
EMAIL_SSL_KEYFILE = None
EMAIL_TIMEOUT = None
INSTALLED_APPS = []
TEMPLATES = []
FORM_RENDERER = 'django.forms.renderers.DjangoTemplates'
DEFAULT_FROM_EMAIL = 'webmaster@localhost'
EMAIL_SUBJECT_PREFIX = '[Django] '
APPEND_SLASH = True
PREPEND_WWW = False
# Override the server-derived value of SCRIPT_NAME
FORCE_SCRIPT_NAME = None
# List of compiled regular expression objects representing User-Agent strings
# that are not allowed to visit any page, systemwide. Use this for bad
# robots/crawlers. Here are a few examples:
# import re
# DISALLOWED_USER_AGENTS = [
# re.compile(r'^NaverBot.*'),
# re.compile(r'^EmailSiphon.*'),
# re.compile(r'^SiteSucker.*'),
# re.compile(r'^sohu-search'),
# ]
DISALLOWED_USER_AGENTS = []
ABSOLUTE_URL_OVERRIDES = {}
# List of compiled regular expression objects representing URLs that need not
# be reported by BrokenLinkEmailsMiddleware. Here are a few examples:
# import re
# IGNORABLE_404_URLS = [
# re.compile(r'^/apple-touch-icon.*\.png$'),
# re.compile(r'^/favicon.ico$'),
# re.compile(r'^/robots.txt$'),
# re.compile(r'^/phpmyadmin/'),
# re.compile(r'\.(cgi|php|pl)$'),
# ]
IGNORABLE_404_URLS = []
# A secret key for this particular Django installation. Used in secret-key
# hashing algorithms. Set this in your settings, or Django will complain
# loudly.
SECRET_KEY = ''
# Default file storage mechanism that holds media.
DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage'
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = None
# URL that handles the static files served from STATIC_ROOT.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = None
# List of upload handler classes to be applied in order.
FILE_UPLOAD_HANDLERS = [
'django.core.files.uploadhandler.MemoryFileUploadHandler',
'django.core.files.uploadhandler.TemporaryFileUploadHandler',
]
# Maximum size, in bytes, of a request before it will be streamed to the
# file system instead of into memory.
FILE_UPLOAD_MAX_MEMORY_SIZE = 2621440 # i.e. 2.5 MB
# Maximum size in bytes of request data (excluding file uploads) that will be
# read before a SuspiciousOperation (RequestDataTooBig) is raised.
DATA_UPLOAD_MAX_MEMORY_SIZE = 2621440 # i.e. 2.5 MB
# Maximum number of GET/POST parameters that will be read before a
# SuspiciousOperation (TooManyFieldsSent) is raised.
DATA_UPLOAD_MAX_NUMBER_FIELDS = 1000
# Directory in which upload streamed files will be temporarily saved. A value of
# `None` will make Django use the operating system's default temporary directory
FILE_UPLOAD_TEMP_DIR = None
FILE_UPLOAD_PERMISSIONS = None
# The numeric mode to assign to newly-created directories, when uploading files.
# The value should be a mode as you'd pass to os.chmod;
PERMISSIONS = None
FORMAT_MODULE_PATH = None
_FORMAT = 'N j, Y'
TIME_FORMAT = 'N j, Y, P'
_FORMAT = 'P'
_MONTH_FORMAT = 'F Y'
H_DAY_FORMAT = 'F j'
T_DATE_FORMAT = 'm/d/Y'
T_DATETIME_FORMAT = 'm/d/Y P'
TS = [
'%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y',
'%b %d %Y', '%b %d, %Y',
'%d %b %Y', '%d %b, %Y',
'%B %d %Y', '%B %d, %Y',
'%d %B %Y', '%d %B, %Y',
]
TS = [
'%H:%M:%S',
'%H:%M:%S.%f',
'%H:%M',
]
ORMATS = [
'%Y-%m-%d %H:%M:%S',
'%Y-%m-%d %H:%M:%S.%f',
'%Y-%m-%d %H:%M',
'%Y-%m-%d',
'%m/%d/%Y %H:%M:%S',
'%m/%d/%Y %H:%M:%S.%f',
'%m/%d/%Y %H:%M',
'%m/%d/%Y',
'%m/%d/%y %H:%M:%S',
'%m/%d/%y %H:%M:%S.%f',
'%m/%d/%y %H:%M',
'%m/%d/%y',
]
FIRST_DAY_OF_WEEK = 0
DECIMAL_SEPARATOR = '.'
USE_THOUSAND_SEPARATOR = False
NUMBER_GROUPING = 0
THOUSAND_SEPARATOR = ','
DEFAULT_TABLESPACE = ''
DEFAULT_INDEX_TABLESPACE = ''
X_FRAME_OPTIONS = 'SAMEORIGIN'
USE_X_FORWARDED_HOST = False
USE_X_FORWARDED_PORT = False
# (runserver) will use. If `None`, the return value of
# 'django.core.wsgi.get_wsgi_application' is used, thus preserving the same
# behavior as previous versions of Django. Otherwise this should point to an
# actual WSGI application object.
WSGI_APPLICATION = None
# If your Django app is behind a proxy that sets a header to specify secure
# connections, AND that proxy ensures that user-submitted headers with the
# same name are ignored (so that people can't spoof it), set this value to
# you may be opening yourself up to a security risk.
SECURE_PROXY_SSL_HEADER = None
##############
# MIDDLEWARE #
##############
# List of middleware to use. Order is important; in the request phase, these
# middleware will be applied in the order given, and in the response
# phase the middleware will be applied in reverse order.
MIDDLEWARE = []
############
# SESSIONS #
############
# Cache to store session data if using the cache session backend.
SESSION_CACHE_ALIAS = 'default'
# Cookie name. This can be whatever you want.
SESSION_COOKIE_NAME = 'sessionid'
# Age of cookie, in seconds (default: 2 weeks).
SESSION_COOKIE_AGE = 60 * 60 * 24 * 7 * 2
# A string like "example.com", or None for standard domain cookie.
SESSION_COOKIE_DOMAIN = None
# Whether the session cookie should be secure (https:// only).
SESSION_COOKIE_SECURE = False
# The path of the session cookie.
SESSION_COOKIE_PATH = '/'
# Whether to use the non-RFC standard httpOnly flag (IE, FF3+, others)
SESSION_COOKIE_HTTPONLY = True
# Whether to set the flag restricting cookie leaks on cross-site requests.
# This can be 'Lax', 'Strict', or None to disable the flag.
SESSION_COOKIE_SAMESITE = 'Lax'
# Whether to save the session data on every request.
SESSION_SAVE_EVERY_REQUEST = False
# Whether a user's session cookie expires when the Web browser is closed.
SESSION_EXPIRE_AT_BROWSER_CLOSE = False
SESSION_ENGINE = 'django.contrib.sessions.backends.db'
SESSION_FILE_PATH = None
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'
ckends.locmem.LocMemCache',
}
}
CACHE_MIDDLEWARE_KEY_PREFIX = ''
CACHE_MIDDLEWARE_SECONDS = 600
CACHE_MIDDLEWARE_ALIAS = 'default'
2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.Argon2PasswordHasher',
'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
]
AUTH_PASSWORD_VALIDATORS = []
= 60 * 60 * 24 * 7 * 52
CSRF_COOKIE_DOMAIN = None
CSRF_COOKIE_PATH = '/'
CSRF_COOKIE_SECURE = False
CSRF_COOKIE_HTTPONLY = False
CSRF_COOKIE_SAMESITE = 'Lax'
CSRF_HEADER_NAME = 'HTTP_X_CSRFTOKEN'
CSRF_TRUSTED_ORIGINS = []
CSRF_USE_SESSIONS = False
ERIALIZED_APPS = []
############
# FIXTURES #
############
# The list of directories to search for fixtures
FIXTURE_DIRS = []
###############
# STATICFILES #
###############
# A list of locations of additional static files
STATICFILES_DIRS = []
# The default file storage backend used during the build process
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
]
##############
# MIGRATIONS #
##############
# Migration module overrides for apps, by app label.
MIGRATION_MODULES = {}
#################
# SYSTEM CHECKS #
#################
# List of all issues generated by system checks that should be silenced. Light
# issues like warnings, infos or debugs will not generate a message. Silencing
# serious issues like errors and criticals does not result in hiding the
# message, but Django will not stop you from e.g. running server.
SILENCED_SYSTEM_CHECKS = []
#######################
# SECURITY MIDDLEWARE #
#######################
SECURE_BROWSER_XSS_FILTER = False
SECURE_CONTENT_TYPE_NOSNIFF = False
SECURE_HSTS_INCLUDE_SUBDOMAINS = False
SECURE_HSTS_PRELOAD = False
SECURE_HSTS_SECONDS = 0
SECURE_REDIRECT_EXEMPT = []
SECURE_SSL_HOST = None
SECURE_SSL_REDIRECT = False
| true | true |
f72b65ae791790eb0c6dae59632f170bfaa9b26d | 984 | py | Python | setup.py | prafulbagai/uwsgi-sloth | b19b9a7e6a0b8edfdc94bfbe9f7a0030ab95db03 | [
"Apache-2.0"
] | 127 | 2015-01-02T11:57:22.000Z | 2022-03-03T02:23:54.000Z | setup.py | prafulbagai/uwsgi-sloth | b19b9a7e6a0b8edfdc94bfbe9f7a0030ab95db03 | [
"Apache-2.0"
] | 8 | 2015-06-15T12:10:13.000Z | 2019-07-21T23:01:18.000Z | setup.py | prafulbagai/uwsgi-sloth | b19b9a7e6a0b8edfdc94bfbe9f7a0030ab95db03 | [
"Apache-2.0"
] | 20 | 2015-01-06T03:27:25.000Z | 2020-09-04T03:53:46.000Z | # -*- coding: utf-8 -*-
from __future__ import print_function
import sys
from setuptools import setup, find_packages
# **Python version check**
if sys.version_info < (3, 5):
error = """
uwsgi-sloth only supports Python 3.5 and above.
If you are using Python 2.7, please install "uwsgi-sloth<3.0.0" instead.
"""
print(error, file=sys.stderr)
sys.exit(1)
setup(
name='uwsgi-sloth',
version='3.0.2',
description='A simple uwsgi access log analyzer',
long_description=open('README.rst').read(),
author='piglei',
author_email='piglei2007@gmail.com',
url='https://github.com/piglei/uwsgi-sloth',
keywords='uwsgi log analyzer',
license='Apache License, Version 2.0',
packages=find_packages(),
package_data={"": ['templates/*.html', 'sample.conf']},
classifiers=[
"Programming Language :: Python :: 3",
],
install_requires=[
'jinja2',
'configobj'
],
scripts=['uwsgi_sloth/uwsgi-sloth']
)
| 24.6 | 72 | 0.648374 |
from __future__ import print_function
import sys
from setuptools import setup, find_packages
if sys.version_info < (3, 5):
error = """
uwsgi-sloth only supports Python 3.5 and above.
If you are using Python 2.7, please install "uwsgi-sloth<3.0.0" instead.
"""
print(error, file=sys.stderr)
sys.exit(1)
setup(
name='uwsgi-sloth',
version='3.0.2',
description='A simple uwsgi access log analyzer',
long_description=open('README.rst').read(),
author='piglei',
author_email='piglei2007@gmail.com',
url='https://github.com/piglei/uwsgi-sloth',
keywords='uwsgi log analyzer',
license='Apache License, Version 2.0',
packages=find_packages(),
package_data={"": ['templates/*.html', 'sample.conf']},
classifiers=[
"Programming Language :: Python :: 3",
],
install_requires=[
'jinja2',
'configobj'
],
scripts=['uwsgi_sloth/uwsgi-sloth']
)
| true | true |
f72b65b992c41b19e9209c007df907202066b8d1 | 2,817 | py | Python | weatherScraper/spiders/weatherbot.py | aabedi/weatherScraper | 069d07c19fbbba93aad5499cd1bb400accbcf644 | [
"MIT"
] | null | null | null | weatherScraper/spiders/weatherbot.py | aabedi/weatherScraper | 069d07c19fbbba93aad5499cd1bb400accbcf644 | [
"MIT"
] | null | null | null | weatherScraper/spiders/weatherbot.py | aabedi/weatherScraper | 069d07c19fbbba93aad5499cd1bb400accbcf644 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
from weatherScraper.items import TempData
from weatherScraper.items import InputData
import scrapy
class WeatherbotSpider(scrapy.Spider):
name = 'weatherbot'
allowed_domains = ['www.wunderground.com']
start_urls = ['http://www.wunderground.com/history/']
def __init__(self, code='', month='', day='', year='', *args, **kwargs): # this will allow spider arguments
super(WeatherbotSpider, self).__init__(*args, **kwargs)
global user_input
user_input = InputData()
user_input['code'] = code
user_input['month'] = month
user_input['day'] = day
user_input['year'] = year
def parse(self, response):
return scrapy.FormRequest.from_response(
response,
formnumber=1, # formnumber set to 1 because location and date are the second form on history page
formdata={'code': user_input['code'],
'month': user_input['month'],
'day': user_input['day'],
'year': user_input['year']},
callback=self.after_post
)
def after_post(self, response):
# check input successful before moving on
if "location you entered was not found" in response.body:
self.logger.error("Location not valid")
return
temperatures = TempData()
# Extract each temperature needed using corresponding css tags
temperatures['actual_mean_temp'] = response.css('#historyTable tr:nth-child(2) .wx-value::text').extract()
temperatures['avg_mean_temp'] = response.css('tr:nth-child(2) .indent~ td+ td .wx-value::text').extract()
temperatures['actual_max_temp'] = response.css('tr:nth-child(3) .indent+ td .wx-value::text').extract()
temperatures['avg_max_temp'] = response.css('#historyTable tr:nth-child(3) td:nth-child(3) .wx-value::text')\
.extract()
temperatures['record_max_temp'] = response.css('tr:nth-child(3) td:nth-child(4) .wx-value::text').extract()
temperatures['actual_min_temp'] = response.css('tr:nth-child(4) .indent+ td .wx-value::text').extract()
temperatures['avg_min_temp'] = response.css('#historyTable tr:nth-child(4) td:nth-child(3) .wx-value::text')\
.extract()
temperatures['record_min_temp'] = response.css('#historyTable tr:nth-child(4) td:nth-child(4) .wx-value::text')\
.extract()
# Check if Fahrenheit or Celsius, then append correct unit
if 'C' in response.css('tr:nth-child(3) .indent+ td .wx-unit::text'):
for key, value in temperatures.iteritems():
value.append('C')
else:
for key, value in temperatures.iteritems():
value.append('F')
yield temperatures
| 48.568966 | 120 | 0.619453 |
from weatherScraper.items import TempData
from weatherScraper.items import InputData
import scrapy
class WeatherbotSpider(scrapy.Spider):
name = 'weatherbot'
allowed_domains = ['www.wunderground.com']
start_urls = ['http://www.wunderground.com/history/']
def __init__(self, code='', month='', day='', year='', *args, **kwargs):
super(WeatherbotSpider, self).__init__(*args, **kwargs)
global user_input
user_input = InputData()
user_input['code'] = code
user_input['month'] = month
user_input['day'] = day
user_input['year'] = year
def parse(self, response):
return scrapy.FormRequest.from_response(
response,
formnumber=1,
formdata={'code': user_input['code'],
'month': user_input['month'],
'day': user_input['day'],
'year': user_input['year']},
callback=self.after_post
)
def after_post(self, response):
if "location you entered was not found" in response.body:
self.logger.error("Location not valid")
return
temperatures = TempData()
temperatures['actual_mean_temp'] = response.css('#historyTable tr:nth-child(2) .wx-value::text').extract()
temperatures['avg_mean_temp'] = response.css('tr:nth-child(2) .indent~ td+ td .wx-value::text').extract()
temperatures['actual_max_temp'] = response.css('tr:nth-child(3) .indent+ td .wx-value::text').extract()
temperatures['avg_max_temp'] = response.css('#historyTable tr:nth-child(3) td:nth-child(3) .wx-value::text')\
.extract()
temperatures['record_max_temp'] = response.css('tr:nth-child(3) td:nth-child(4) .wx-value::text').extract()
temperatures['actual_min_temp'] = response.css('tr:nth-child(4) .indent+ td .wx-value::text').extract()
temperatures['avg_min_temp'] = response.css('#historyTable tr:nth-child(4) td:nth-child(3) .wx-value::text')\
.extract()
temperatures['record_min_temp'] = response.css('#historyTable tr:nth-child(4) td:nth-child(4) .wx-value::text')\
.extract()
if 'C' in response.css('tr:nth-child(3) .indent+ td .wx-unit::text'):
for key, value in temperatures.iteritems():
value.append('C')
else:
for key, value in temperatures.iteritems():
value.append('F')
yield temperatures
| true | true |
f72b65ccd73696678a74b7a0c74f72dda1f6b69c | 3,974 | py | Python | flink-ml-framework/python/setup.py | yangqi199808/dl-on-flink | 3b2ab15ce06e877f90997f5950df44bc30b88b29 | [
"Apache-2.0"
] | null | null | null | flink-ml-framework/python/setup.py | yangqi199808/dl-on-flink | 3b2ab15ce06e877f90997f5950df44bc30b88b29 | [
"Apache-2.0"
] | null | null | null | flink-ml-framework/python/setup.py | yangqi199808/dl-on-flink | 3b2ab15ce06e877f90997f5950df44bc30b88b29 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 The flink-ai-extended 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.
# =============================================================================
import os
import platform
import re
import subprocess
import sys
from distutils.version import LooseVersion
from setuptools import setup, find_packages, Extension
from setuptools.command.build_ext import build_ext
this_directory = os.path.abspath(os.path.dirname(__file__))
version_file = os.path.join(this_directory, 'flink_ml_framework/version.py')
try:
exec(open(version_file).read())
except IOError:
print("Failed to load flink_ml_framework version file for packaging. " +
"'%s' not found!" % version_file,
file=sys.stderr)
sys.exit(-1)
VERSION = __version__ # noqa
class CMakeExtension(Extension):
def __init__(self, name, sourcedir=''):
Extension.__init__(self, name, sources=[])
self.sourcedir = os.path.abspath(sourcedir)
class CMakeBuild(build_ext):
def run(self):
try:
out = subprocess.check_output(['cmake', '--version'])
except OSError:
raise RuntimeError(
"CMake must be installed to build the following extensions: " +
", ".join(e.name for e in self.extensions))
if platform.system() == "Windows":
cmake_version = LooseVersion(re.search(r'version\s*([\d.]+)',
out.decode()).group(1))
if cmake_version < '3.1.0':
raise RuntimeError("CMake >= 3.1.0 is required on Windows")
for ext in self.extensions:
self.build_extension(ext)
def build_extension(self, ext):
extdir = os.path.abspath(
os.path.dirname(self.get_ext_fullpath(ext.name)))
cmake_args = ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=' + extdir,
'-DPYTHON_EXECUTABLE=' + sys.executable]
cfg = 'Debug' if self.debug else 'Release'
build_args = ['--config', cfg]
if platform.system() == "Windows":
cmake_args += ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_{}={}'.format(
cfg.upper(),
extdir)]
if sys.maxsize > 2 ** 32:
cmake_args += ['-A', 'x64']
build_args += ['--', '/m']
else:
cmake_args += ['-DCMAKE_BUILD_TYPE=' + cfg]
build_args += ['--', '-j2']
if platform.system() == "Linux":
build_args += ['-lpthread']
env = os.environ.copy()
env[
'CXXFLAGS'] = '{} -D_GLIBCXX_USE_CXX11_ABI=0 -DVERSION_INFO=\\"{}\\"'.format(
env.get('CXXFLAGS', ''),
self.distribution.get_version())
if not os.path.exists(self.build_temp):
os.makedirs(self.build_temp)
subprocess.check_call(['cmake', ext.sourcedir] + cmake_args,
cwd=self.build_temp, env=env)
subprocess.check_call(['cmake', '--build', '.'] + build_args,
cwd=self.build_temp)
setup(
name='flink_ml_framework',
version=VERSION,
include_package_data=True,
packages=find_packages(),
ext_modules=[CMakeExtension('flink_ml_framework/flink_ml_framework')],
cmdclass=dict(build_ext=CMakeBuild),
zip_safe=False,
url='https://github.com/flink-extended/dl-on-flink',
license='https://www.apache.org/licenses/LICENSE-2.0'
)
| 36.458716 | 89 | 0.605435 |
import os
import platform
import re
import subprocess
import sys
from distutils.version import LooseVersion
from setuptools import setup, find_packages, Extension
from setuptools.command.build_ext import build_ext
this_directory = os.path.abspath(os.path.dirname(__file__))
version_file = os.path.join(this_directory, 'flink_ml_framework/version.py')
try:
exec(open(version_file).read())
except IOError:
print("Failed to load flink_ml_framework version file for packaging. " +
"'%s' not found!" % version_file,
file=sys.stderr)
sys.exit(-1)
VERSION = __version__
class CMakeExtension(Extension):
def __init__(self, name, sourcedir=''):
Extension.__init__(self, name, sources=[])
self.sourcedir = os.path.abspath(sourcedir)
class CMakeBuild(build_ext):
def run(self):
try:
out = subprocess.check_output(['cmake', '--version'])
except OSError:
raise RuntimeError(
"CMake must be installed to build the following extensions: " +
", ".join(e.name for e in self.extensions))
if platform.system() == "Windows":
cmake_version = LooseVersion(re.search(r'version\s*([\d.]+)',
out.decode()).group(1))
if cmake_version < '3.1.0':
raise RuntimeError("CMake >= 3.1.0 is required on Windows")
for ext in self.extensions:
self.build_extension(ext)
def build_extension(self, ext):
extdir = os.path.abspath(
os.path.dirname(self.get_ext_fullpath(ext.name)))
cmake_args = ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=' + extdir,
'-DPYTHON_EXECUTABLE=' + sys.executable]
cfg = 'Debug' if self.debug else 'Release'
build_args = ['--config', cfg]
if platform.system() == "Windows":
cmake_args += ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_{}={}'.format(
cfg.upper(),
extdir)]
if sys.maxsize > 2 ** 32:
cmake_args += ['-A', 'x64']
build_args += ['--', '/m']
else:
cmake_args += ['-DCMAKE_BUILD_TYPE=' + cfg]
build_args += ['--', '-j2']
if platform.system() == "Linux":
build_args += ['-lpthread']
env = os.environ.copy()
env[
'CXXFLAGS'] = '{} -D_GLIBCXX_USE_CXX11_ABI=0 -DVERSION_INFO=\\"{}\\"'.format(
env.get('CXXFLAGS', ''),
self.distribution.get_version())
if not os.path.exists(self.build_temp):
os.makedirs(self.build_temp)
subprocess.check_call(['cmake', ext.sourcedir] + cmake_args,
cwd=self.build_temp, env=env)
subprocess.check_call(['cmake', '--build', '.'] + build_args,
cwd=self.build_temp)
setup(
name='flink_ml_framework',
version=VERSION,
include_package_data=True,
packages=find_packages(),
ext_modules=[CMakeExtension('flink_ml_framework/flink_ml_framework')],
cmdclass=dict(build_ext=CMakeBuild),
zip_safe=False,
url='https://github.com/flink-extended/dl-on-flink',
license='https://www.apache.org/licenses/LICENSE-2.0'
)
| true | true |
f72b65fef7e833abe364975fab274dd40f6a20f9 | 359 | py | Python | predict.py | TomG4/flair | 2db057ec60c25d55f69622a6a6881aedae13be49 | [
"MIT"
] | null | null | null | predict.py | TomG4/flair | 2db057ec60c25d55f69622a6a6881aedae13be49 | [
"MIT"
] | null | null | null | predict.py | TomG4/flair | 2db057ec60c25d55f69622a6a6881aedae13be49 | [
"MIT"
] | null | null | null | #Test
from flair.data import Sentence
from flair.models import SequenceTagger
tagger: SequenceTagger = SequenceTagger.load("ner")
sentence: Sentence = Sentence("George Washington went to Washington .")
tagger.predict(sentence)
print("Analysing the sentence %s" % sentence)
print("\nThe following NER tags are found: \n")
print(sentence.to_tagged_string())
| 27.615385 | 71 | 0.78273 |
from flair.data import Sentence
from flair.models import SequenceTagger
tagger: SequenceTagger = SequenceTagger.load("ner")
sentence: Sentence = Sentence("George Washington went to Washington .")
tagger.predict(sentence)
print("Analysing the sentence %s" % sentence)
print("\nThe following NER tags are found: \n")
print(sentence.to_tagged_string())
| true | true |
f72b66e8e4c78293736c0c00b94f7ce5be92fa9b | 35,288 | py | Python | owscapable/csw.py | b-cube/OwsCapable | a01815418fe982434503d6542cb18e1ac8989684 | [
"BSD-3-Clause"
] | 1 | 2016-02-01T12:55:13.000Z | 2016-02-01T12:55:13.000Z | owscapable/csw.py | b-cube/OwsCapable | a01815418fe982434503d6542cb18e1ac8989684 | [
"BSD-3-Clause"
] | 1 | 2015-06-23T14:07:50.000Z | 2015-06-23T14:07:50.000Z | owscapable/csw.py | b-cube/OwsCapable | a01815418fe982434503d6542cb18e1ac8989684 | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: ISO-8859-15 -*-
# =============================================================================
# Copyright (c) 2009 Tom Kralidis
#
# Authors : Tom Kralidis <tomkralidis@gmail.com>
#
# Contact email: tomkralidis@gmail.com
# =============================================================================
""" CSW request and response processor """
from __future__ import (absolute_import, division, print_function)
import base64
import inspect
import warnings
import StringIO
import random
from urllib import urlencode
from urllib2 import Request, urlopen
from owscapable.util import OrderedDict
from owscapable.etree import etree
from owscapable import fes
from owscapable import util
from owscapable import ows
from owscapable.iso import MD_Metadata
from owscapable.fgdc import Metadata
from owscapable.dif import DIF
from owscapable.namespaces import Namespaces
from owscapable.util import cleanup_namespaces, bind_url, add_namespaces
# default variables
outputformat = 'application/xml'
def get_namespaces():
n = Namespaces()
return n.get_namespaces()
namespaces = get_namespaces()
schema = 'http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd'
schema_location = '%s %s' % (namespaces['csw'], schema)
class CatalogueServiceWeb:
""" csw request class """
def __init__(self, url, xml=None, lang='en-US', version='2.0.2', timeout=10, skip_caps=False,
username=None, password=None):
"""
Construct and process a GetCapabilities request
Parameters
----------
- url: the URL of the CSW
- lang: the language (default is 'en-US')
- version: version (default is '2.0.2')
- timeout: timeout in seconds
- skip_caps: whether to skip GetCapabilities processing on init (default is False)
- username: username for HTTP basic authentication
- password: password for HTTP basic authentication
"""
self.url = url
self.lang = lang
self.version = version
self.timeout = timeout
self.username = username
self.password = password
self.service = 'CSW'
self.exceptionreport = None
self.owscommon = ows.OwsCommon('1.0.0')
if not skip_caps: # process GetCapabilities
if xml:
# load from the response to get _exml
self._parse_response(xml)
else:
# construct request
data = {'service': self.service, 'version': self.version, 'request': 'GetCapabilities'}
self.request = '%s%s' % (bind_url(self.url), urlencode(data))
self._invoke()
if self.exceptionreport is None:
# ServiceIdentification
val = self._exml.find(util.nspath_eval('ows:ServiceIdentification', namespaces))
self.identification=ows.ServiceIdentification(val,self.owscommon.namespace)
# ServiceProvider
val = self._exml.find(util.nspath_eval('ows:ServiceProvider', namespaces))
self.provider=ows.ServiceProvider(val,self.owscommon.namespace)
# ServiceOperations metadata
self.operations=[]
for elem in self._exml.findall(util.nspath_eval('ows:OperationsMetadata/ows:Operation', namespaces)):
self.operations.append(ows.OperationsMetadata(elem, self.owscommon.namespace))
# for harmonization
self.contents = None
# FilterCapabilities
val = self._exml.find(util.nspath_eval('ogc:Filter_Capabilities', namespaces))
self.filters=fes.FilterCapabilities(val)
def describerecord(self, typename='csw:Record', format=outputformat):
"""
Construct and process DescribeRecord request
Parameters
----------
- typename: the typename to describe (default is 'csw:Record')
- format: the outputFormat (default is 'application/xml')
"""
# construct request
node0 = self._setrootelement('csw:DescribeRecord')
node0.set('service', self.service)
node0.set('version', self.version)
node0.set('outputFormat', format)
node0.set('schemaLanguage', namespaces['xs2'])
node0.set(util.nspath_eval('xsi:schemaLocation', namespaces), schema_location)
etree.SubElement(node0, util.nspath_eval('csw:TypeName', namespaces)).text = typename
self.request = node0
self._invoke()
# parse result
# TODO: process the XML Schema (you're on your own for now with self.response)
def getdomain(self, dname, dtype='parameter'):
"""
Construct and process a GetDomain request
Parameters
----------
- dname: the value of the Parameter or Property to query
- dtype: whether to query a parameter (parameter) or property (property)
"""
# construct request
dtypename = 'ParameterName'
node0 = self._setrootelement('csw:GetDomain')
node0.set('service', self.service)
node0.set('version', self.version)
node0.set(util.nspath_eval('xsi:schemaLocation', namespaces), schema_location)
if dtype == 'property':
dtypename = 'PropertyName'
etree.SubElement(node0, util.nspath_eval('csw:%s' % dtypename, namespaces)).text = dname
self.request = node0
self._invoke()
if self.exceptionreport is None:
self.results = {}
val = self._exml.find(util.nspath_eval('csw:DomainValues', namespaces)).attrib.get('type')
self.results['type'] = util.testXMLValue(val, True)
val = self._exml.find(util.nspath_eval('csw:DomainValues/csw:%s' % dtypename, namespaces))
self.results[dtype] = util.testXMLValue(val)
# get the list of values associated with the Domain
self.results['values'] = []
for f in self._exml.findall(util.nspath_eval('csw:DomainValues/csw:ListOfValues/csw:Value', namespaces)):
self.results['values'].append(util.testXMLValue(f))
def getrecords(self, qtype=None, keywords=[], typenames='csw:Record', propertyname='csw:AnyText', bbox=None, esn='summary', sortby=None, outputschema=namespaces['csw'], format=outputformat, startposition=0, maxrecords=10, cql=None, xml=None, resulttype='results'):
"""
Construct and process a GetRecords request
Parameters
----------
- qtype: type of resource to query (i.e. service, dataset)
- keywords: list of keywords
- typenames: the typeNames to query against (default is csw:Record)
- propertyname: the PropertyName to Filter against
- bbox: the bounding box of the spatial query in the form [minx,miny,maxx,maxy]
- esn: the ElementSetName 'full', 'brief' or 'summary' (default is 'summary')
- sortby: property to sort results on
- outputschema: the outputSchema (default is 'http://www.opengis.net/cat/csw/2.0.2')
- format: the outputFormat (default is 'application/xml')
- startposition: requests a slice of the result set, starting at this position (default is 0)
- maxrecords: the maximum number of records to return. No records are returned if 0 (default is 10)
- cql: common query language text. Note this overrides bbox, qtype, keywords
- xml: raw XML request. Note this overrides all other options
- resulttype: the resultType 'hits', 'results', 'validate' (default is 'results')
"""
warnings.warn("""Please use the updated 'getrecords2' method instead of 'getrecords'.
The 'getrecords' method will be upgraded to use the 'getrecords2' parameters
in a future version of OWSLib.""")
if xml is not None:
self.request = etree.fromstring(xml)
val = self.request.find(util.nspath_eval('csw:Query/csw:ElementSetName', namespaces))
if val is not None:
esn = util.testXMLValue(val)
else:
# construct request
node0 = self._setrootelement('csw:GetRecords')
if etree.__name__ != 'lxml.etree': # apply nsmap manually
node0.set('xmlns:ows', namespaces['ows'])
node0.set('xmlns:gmd', namespaces['gmd'])
node0.set('xmlns:dif', namespaces['dif'])
node0.set('xmlns:fgdc', namespaces['fgdc'])
node0.set('outputSchema', outputschema)
node0.set('outputFormat', format)
node0.set('version', self.version)
node0.set('resultType', resulttype)
node0.set('service', self.service)
if startposition > 0:
node0.set('startPosition', str(startposition))
node0.set('maxRecords', str(maxrecords))
node0.set(util.nspath_eval('xsi:schemaLocation', namespaces), schema_location)
node1 = etree.SubElement(node0, util.nspath_eval('csw:Query', namespaces))
node1.set('typeNames', typenames)
etree.SubElement(node1, util.nspath_eval('csw:ElementSetName', namespaces)).text = esn
self._setconstraint(node1, qtype, propertyname, keywords, bbox, cql, None)
if sortby is not None:
fes.setsortby(node1, sortby)
self.request = node0
self._invoke()
if self.exceptionreport is None:
self.results = {}
# process search results attributes
val = self._exml.find(util.nspath_eval('csw:SearchResults', namespaces)).attrib.get('numberOfRecordsMatched')
self.results['matches'] = int(util.testXMLValue(val, True))
val = self._exml.find(util.nspath_eval('csw:SearchResults', namespaces)).attrib.get('numberOfRecordsReturned')
self.results['returned'] = int(util.testXMLValue(val, True))
val = self._exml.find(util.nspath_eval('csw:SearchResults', namespaces)).attrib.get('nextRecord')
self.results['nextrecord'] = int(util.testXMLValue(val, True))
# process list of matching records
self.records = OrderedDict()
self._parserecords(outputschema, esn)
def getrecordbyid(self, id=[], esn='full', outputschema=namespaces['csw'], format=outputformat):
"""
Construct and process a GetRecordById request
Parameters
----------
- id: the list of Ids
- esn: the ElementSetName 'full', 'brief' or 'summary' (default is 'full')
- outputschema: the outputSchema (default is 'http://www.opengis.net/cat/csw/2.0.2')
- format: the outputFormat (default is 'application/xml')
"""
# construct request
data = {
'service': self.service,
'version': self.version,
'request': 'GetRecordById',
'outputFormat': format,
'outputSchema': outputschema,
'elementsetname': esn,
'id': ','.join(id),
}
self.request = '%s%s' % (bind_url(self.url), urlencode(data))
self._invoke()
if self.exceptionreport is None:
self.results = {}
self.records = OrderedDict()
self._parserecords(outputschema, esn)
def getrecords2(self, constraints=[], sortby=None, typenames='csw:Record', esn='summary', outputschema=namespaces['csw'], format=outputformat, startposition=0, maxrecords=10, cql=None, xml=None, resulttype='results'):
"""
Construct and process a GetRecords request
Parameters
----------
- constraints: the list of constraints (OgcExpression from owslib.fes module)
- sortby: an OGC SortBy object (SortBy from owslib.fes module)
- typenames: the typeNames to query against (default is csw:Record)
- esn: the ElementSetName 'full', 'brief' or 'summary' (default is 'summary')
- outputschema: the outputSchema (default is 'http://www.opengis.net/cat/csw/2.0.2')
- format: the outputFormat (default is 'application/xml')
- startposition: requests a slice of the result set, starting at this position (default is 0)
- maxrecords: the maximum number of records to return. No records are returned if 0 (default is 10)
- cql: common query language text. Note this overrides bbox, qtype, keywords
- xml: raw XML request. Note this overrides all other options
- resulttype: the resultType 'hits', 'results', 'validate' (default is 'results')
"""
if xml is not None:
self.request = etree.fromstring(xml)
val = self.request.find(util.nspath_eval('csw:Query/csw:ElementSetName', namespaces))
if val is not None:
esn = util.testXMLValue(val)
else:
# construct request
node0 = self._setrootelement('csw:GetRecords')
if etree.__name__ != 'lxml.etree': # apply nsmap manually
node0.set('xmlns:ows', namespaces['ows'])
node0.set('xmlns:gmd', namespaces['gmd'])
node0.set('xmlns:dif', namespaces['dif'])
node0.set('xmlns:fgdc', namespaces['fgdc'])
node0.set('outputSchema', outputschema)
node0.set('outputFormat', format)
node0.set('version', self.version)
node0.set('service', self.service)
node0.set('resultType', resulttype)
if startposition > 0:
node0.set('startPosition', str(startposition))
node0.set('maxRecords', str(maxrecords))
node0.set(util.nspath_eval('xsi:schemaLocation', namespaces), schema_location)
node1 = etree.SubElement(node0, util.nspath_eval('csw:Query', namespaces))
node1.set('typeNames', typenames)
etree.SubElement(node1, util.nspath_eval('csw:ElementSetName', namespaces)).text = esn
if any([len(constraints) > 0, cql is not None]):
node2 = etree.SubElement(node1, util.nspath_eval('csw:Constraint', namespaces))
node2.set('version', '1.1.0')
flt = fes.FilterRequest()
if len(constraints) > 0:
node2.append(flt.setConstraintList(constraints))
# Now add a CQL filter if passed in
elif cql is not None:
etree.SubElement(node2, util.nspath_eval('csw:CqlText', namespaces)).text = cql
if sortby is not None and isinstance(sortby, fes.SortBy):
node1.append(sortby.toXML())
self.request = node0
self._invoke()
if self.exceptionreport is None:
self.results = {}
# process search results attributes
val = self._exml.find(util.nspath_eval('csw:SearchResults', namespaces)).attrib.get('numberOfRecordsMatched')
self.results['matches'] = int(util.testXMLValue(val, True))
val = self._exml.find(util.nspath_eval('csw:SearchResults', namespaces)).attrib.get('numberOfRecordsReturned')
self.results['returned'] = int(util.testXMLValue(val, True))
val = self._exml.find(util.nspath_eval('csw:SearchResults', namespaces)).attrib.get('nextRecord')
if val is not None:
self.results['nextrecord'] = int(util.testXMLValue(val, True))
else:
warnings.warn("""CSW Server did not supply a nextRecord value (it is optional), so the client
should page through the results in another way.""")
# For more info, see:
# https://github.com/geopython/OWSLib/issues/100
self.results['nextrecord'] = None
# process list of matching records
self.records = OrderedDict()
self._parserecords(outputschema, esn)
def transaction(self, ttype=None, typename='csw:Record', record=None, propertyname=None, propertyvalue=None, bbox=None, keywords=[], cql=None, identifier=None):
"""
Construct and process a Transaction request
Parameters
----------
- ttype: the type of transaction 'insert, 'update', 'delete'
- typename: the typename to describe (default is 'csw:Record')
- record: the XML record to insert
- propertyname: the RecordProperty/PropertyName to Filter against
- propertyvalue: the RecordProperty Value to Filter against (for updates)
- bbox: the bounding box of the spatial query in the form [minx,miny,maxx,maxy]
- keywords: list of keywords
- cql: common query language text. Note this overrides bbox, qtype, keywords
- identifier: record identifier. Note this overrides bbox, qtype, keywords, cql
"""
# construct request
node0 = self._setrootelement('csw:Transaction')
node0.set('version', self.version)
node0.set('service', self.service)
node0.set(util.nspath_eval('xsi:schemaLocation', namespaces), schema_location)
validtransactions = ['insert', 'update', 'delete']
if ttype not in validtransactions: # invalid transaction
raise RuntimeError('Invalid transaction \'%s\'.' % ttype)
node1 = etree.SubElement(node0, util.nspath_eval('csw:%s' % ttype.capitalize(), namespaces))
if ttype != 'update':
node1.set('typeName', typename)
if ttype == 'insert':
if record is None:
raise RuntimeError('Nothing to insert.')
node1.append(etree.fromstring(record))
if ttype == 'update':
if record is not None:
node1.append(etree.fromstring(record))
else:
if propertyname is not None and propertyvalue is not None:
node2 = etree.SubElement(node1, util.nspath_eval('csw:RecordProperty', namespaces))
etree.SubElement(node2, util.nspath_eval('csw:Name', namespaces)).text = propertyname
etree.SubElement(node2, util.nspath_eval('csw:Value', namespaces)).text = propertyvalue
self._setconstraint(node1, qtype, propertyname, keywords, bbox, cql, identifier)
if ttype == 'delete':
self._setconstraint(node1, None, propertyname, keywords, bbox, cql, identifier)
self.request = node0
self._invoke()
self.results = {}
if self.exceptionreport is None:
self._parsetransactionsummary()
self._parseinsertresult()
def harvest(self, source, resourcetype, resourceformat=None, harvestinterval=None, responsehandler=None):
"""
Construct and process a Harvest request
Parameters
----------
- source: a URI to harvest
- resourcetype: namespace identifying the type of resource
- resourceformat: MIME type of the resource
- harvestinterval: frequency of harvesting, in ISO8601
- responsehandler: endpoint that CSW should responsd to with response
"""
# construct request
node0 = self._setrootelement('csw:Harvest')
node0.set('version', self.version)
node0.set('service', self.service)
node0.set(util.nspath_eval('xsi:schemaLocation', namespaces), schema_location)
etree.SubElement(node0, util.nspath_eval('csw:Source', namespaces)).text = source
etree.SubElement(node0, util.nspath_eval('csw:ResourceType', namespaces)).text = resourcetype
if resourceformat is not None:
etree.SubElement(node0, util.nspath_eval('csw:ResourceFormat', namespaces)).text = resourceformat
if harvestinterval is not None:
etree.SubElement(node0, util.nspath_eval('csw:HarvestInterval', namespaces)).text = harvestinterval
if responsehandler is not None:
etree.SubElement(node0, util.nspath_eval('csw:ResponseHandler', namespaces)).text = responsehandler
self.request = node0
self._invoke()
self.results = {}
if self.exceptionreport is None:
val = self._exml.find(util.nspath_eval('csw:Acknowledgement', namespaces))
if util.testXMLValue(val) is not None:
ts = val.attrib.get('timeStamp')
self.timestamp = util.testXMLValue(ts, True)
id = val.find(util.nspath_eval('csw:RequestId', namespaces))
self.id = util.testXMLValue(id)
else:
self._parsetransactionsummary()
self._parseinsertresult()
def get_operation_by_name(self, name):
"""Return a named operation"""
for item in self.operations:
if item.name.lower() == name.lower():
return item
raise KeyError("No operation named %s" % name)
def getService_urls(self, service_string=None):
"""
Return easily identifiable URLs for all service types
Parameters
----------
- service_string: a URI to lookup
"""
urls=[]
for key,rec in self.records.iteritems():
#create a generator object, and iterate through it until the match is found
#if not found, gets the default value (here "none")
url = next((d['url'] for d in rec.references if d['scheme'] == service_string), None)
if url is not None:
urls.append(url)
return urls
def _parseinsertresult(self):
self.results['insertresults'] = []
for i in self._exml.findall(util.nspath_eval('csw:InsertResult', namespaces)):
for j in i.findall(util.nspath_eval('csw:BriefRecord/dc:identifier', namespaces)):
self.results['insertresults'].append(util.testXMLValue(j))
def _parserecords(self, outputschema, esn):
if outputschema == namespaces['gmd']: # iso 19139
for i in self._exml.findall('.//'+util.nspath_eval('gmd:MD_Metadata', namespaces)) or self._exml.findall('.//'+util.nspath_eval('gmi:MI_Metadata', namespaces)):
val = i.find(util.nspath_eval('gmd:fileIdentifier/gco:CharacterString', namespaces))
identifier = self._setidentifierkey(util.testXMLValue(val))
self.records[identifier] = MD_Metadata(i)
elif outputschema == namespaces['fgdc']: # fgdc csdgm
for i in self._exml.findall('.//metadata'):
val = i.find('idinfo/datasetid')
identifier = self._setidentifierkey(util.testXMLValue(val))
self.records[identifier] = Metadata(i)
elif outputschema == namespaces['dif']: # nasa dif
for i in self._exml.findall('.//'+util.nspath_eval('dif:DIF', namespaces)):
val = i.find(util.nspath_eval('dif:Entry_ID', namespaces))
identifier = self._setidentifierkey(util.testXMLValue(val))
self.records[identifier] = DIF(i)
else: # process default
for i in self._exml.findall('.//'+util.nspath_eval('csw:%s' % self._setesnel(esn), namespaces)):
val = i.find(util.nspath_eval('dc:identifier', namespaces))
identifier = self._setidentifierkey(util.testXMLValue(val))
self.records[identifier] = CswRecord(i)
def _parsetransactionsummary(self):
val = self._exml.find(util.nspath_eval('csw:TransactionSummary', namespaces))
if val is not None:
rid = val.attrib.get('requestId')
self.results['requestid'] = util.testXMLValue(rid, True)
ts = val.find(util.nspath_eval('csw:totalInserted', namespaces))
self.results['inserted'] = int(util.testXMLValue(ts))
ts = val.find(util.nspath_eval('csw:totalUpdated', namespaces))
self.results['updated'] = int(util.testXMLValue(ts))
ts = val.find(util.nspath_eval('csw:totalDeleted', namespaces))
self.results['deleted'] = int(util.testXMLValue(ts))
def _setesnel(self, esn):
""" Set the element name to parse depending on the ElementSetName requested """
el = 'Record'
if esn == 'brief':
el = 'BriefRecord'
if esn == 'summary':
el = 'SummaryRecord'
return el
def _setidentifierkey(self, el):
if el is None:
return 'owslib_random_%i' % random.randint(1,65536)
else:
return el
def _setrootelement(self, el):
if etree.__name__ == 'lxml.etree': # apply nsmap
return etree.Element(util.nspath_eval(el, namespaces), nsmap=namespaces)
else:
return etree.Element(util.nspath_eval(el, namespaces))
def _setconstraint(self, parent, qtype=None, propertyname='csw:AnyText', keywords=[], bbox=None, cql=None, identifier=None):
if keywords or bbox is not None or qtype is not None or cql is not None or identifier is not None:
node0 = etree.SubElement(parent, util.nspath_eval('csw:Constraint', namespaces))
node0.set('version', '1.1.0')
if identifier is not None: # set identifier filter, overrides all other parameters
flt = fes.FilterRequest()
node0.append(flt.set(identifier=identifier))
elif cql is not None: # send raw CQL query
# CQL passed, overrides all other parameters
node1 = etree.SubElement(node0, util.nspath_eval('csw:CqlText', namespaces))
node1.text = cql
else: # construct a Filter request
flt = fes.FilterRequest()
node0.append(flt.set(qtype=qtype, keywords=keywords, propertyname=propertyname,bbox=bbox))
def _invoke(self):
# do HTTP request
if isinstance(self.request, basestring): # GET KVP
req = Request(self.request)
if self.username is not None and self.password is not None:
base64string = base64.encodestring('%s:%s' % (self.username, self.password))[:-1]
req.add_header('Authorization', 'Basic %s' % base64string)
self.response = urlopen(req, timeout=self.timeout).read()
else:
xml_post_url = self.url
# Get correct POST URL based on Operation list.
# If skip_caps=True, then self.operations has not been set, so use
# default URL.
if hasattr(self, 'operations'):
caller = inspect.stack()[1][3]
if caller == 'getrecords2': caller = 'getrecords'
try:
op = self.get_operation_by_name(caller)
post_verbs = filter(lambda x: x.get('type').lower() == 'post', op.methods)
if len(post_verbs) > 1:
# Filter by constraints. We must match a PostEncoding of "XML"
try:
xml_post_url = next(x for x in filter(list, ([pv.get('url') for const in pv.get('constraints') if const.name.lower() == "postencoding" and 'xml' in map(lambda x: x.lower(), const.values)] for pv in post_verbs)))[0]
except StopIteration:
# Well, just use the first one.
xml_post_url = post_verbs[0].get('url')
elif len(post_verbs) == 1:
xml_post_url = post_verbs[0].get('url')
except: # no such luck, just go with xml_post_url
pass
self.request = cleanup_namespaces(self.request)
# Add any namespaces used in the "typeNames" attribute of the
# csw:Query element to the query's xml namespaces.
for query in self.request.findall(util.nspath_eval('csw:Query', namespaces)):
ns = query.get("typeNames", None)
if ns is not None:
# Pull out "gmd" from something like "gmd:MD_Metadata" from the list
# of typenames
ns_keys = [x.split(':')[0] for x in ns.split(' ')]
self.request = add_namespaces(self.request, ns_keys)
self.request = util.element_to_string(self.request, encoding='utf-8')
self.response = util.http_post(xml_post_url, self.request, self.lang, self.timeout, self.username, self.password)
self._parse_response(self.response)
def _parse_response(self, response):
'''parse in-memory xml string from a file obj or _invoke
'''
# parse result see if it's XML
self._exml = etree.parse(StringIO.StringIO(response))
# it's XML. Attempt to decipher whether the XML response is CSW-ish """
valid_xpaths = [
util.nspath_eval('ows:ExceptionReport', namespaces),
util.nspath_eval('csw:Capabilities', namespaces),
util.nspath_eval('csw:DescribeRecordResponse', namespaces),
util.nspath_eval('csw:GetDomainResponse', namespaces),
util.nspath_eval('csw:GetRecordsResponse', namespaces),
util.nspath_eval('csw:GetRecordByIdResponse', namespaces),
util.nspath_eval('csw:HarvestResponse', namespaces),
util.nspath_eval('csw:TransactionResponse', namespaces)
]
if self._exml.getroot().tag not in valid_xpaths:
raise RuntimeError('Document is XML, but not CSW-ish')
# check if it's an OGC Exception
val = self._exml.find(util.nspath_eval('ows:Exception', namespaces))
if val is not None:
raise ows.ExceptionReport(self._exml, self.owscommon.namespace)
else:
self.exceptionreport = None
class CswRecord(object):
""" Process csw:Record, csw:BriefRecord, csw:SummaryRecord """
def __init__(self, record):
if hasattr(record, 'getroot'): # standalone document
self.xml = etree.tostring(record.getroot())
else: # part of a larger document
self.xml = etree.tostring(record)
# check to see if Dublin Core record comes from
# rdf:RDF/rdf:Description container
# (child content model is identical)
self.rdf = False
rdf = record.find(util.nspath_eval('rdf:Description', namespaces))
if rdf is not None:
self.rdf = True
record = rdf
# some CSWs return records with multiple identifiers based on
# different schemes. Use the first dc:identifier value to set
# self.identifier, and set self.identifiers as a list of dicts
val = record.find(util.nspath_eval('dc:identifier', namespaces))
self.identifier = util.testXMLValue(val)
self.identifiers = []
for i in record.findall(util.nspath_eval('dc:identifier', namespaces)):
d = {}
d['scheme'] = i.attrib.get('scheme')
d['identifier'] = i.text
self.identifiers.append(d)
val = record.find(util.nspath_eval('dc:type', namespaces))
self.type = util.testXMLValue(val)
val = record.find(util.nspath_eval('dc:title', namespaces))
self.title = util.testXMLValue(val)
val = record.find(util.nspath_eval('dct:alternative', namespaces))
self.alternative = util.testXMLValue(val)
val = record.find(util.nspath_eval('dct:isPartOf', namespaces))
self.ispartof = util.testXMLValue(val)
val = record.find(util.nspath_eval('dct:abstract', namespaces))
self.abstract = util.testXMLValue(val)
val = record.find(util.nspath_eval('dc:date', namespaces))
self.date = util.testXMLValue(val)
val = record.find(util.nspath_eval('dct:created', namespaces))
self.created = util.testXMLValue(val)
val = record.find(util.nspath_eval('dct:issued', namespaces))
self.issued = util.testXMLValue(val)
val = record.find(util.nspath_eval('dc:relation', namespaces))
self.relation = util.testXMLValue(val)
val = record.find(util.nspath_eval('dct:temporal', namespaces))
self.temporal = util.testXMLValue(val)
self.uris = [] # list of dicts
for i in record.findall(util.nspath_eval('dc:URI', namespaces)):
uri = {}
uri['protocol'] = util.testXMLValue(i.attrib.get('protocol'), True)
uri['name'] = util.testXMLValue(i.attrib.get('name'), True)
uri['description'] = util.testXMLValue(i.attrib.get('description'), True)
uri['url'] = util.testXMLValue(i)
self.uris.append(uri)
self.references = [] # list of dicts
for i in record.findall(util.nspath_eval('dct:references', namespaces)):
ref = {}
ref['scheme'] = util.testXMLValue(i.attrib.get('scheme'), True)
ref['url'] = util.testXMLValue(i)
self.references.append(ref)
val = record.find(util.nspath_eval('dct:modified', namespaces))
self.modified = util.testXMLValue(val)
val = record.find(util.nspath_eval('dc:creator', namespaces))
self.creator = util.testXMLValue(val)
val = record.find(util.nspath_eval('dc:publisher', namespaces))
self.publisher = util.testXMLValue(val)
val = record.find(util.nspath_eval('dc:coverage', namespaces))
self.coverage = util.testXMLValue(val)
val = record.find(util.nspath_eval('dc:contributor', namespaces))
self.contributor = util.testXMLValue(val)
val = record.find(util.nspath_eval('dc:language', namespaces))
self.language = util.testXMLValue(val)
val = record.find(util.nspath_eval('dc:source', namespaces))
self.source = util.testXMLValue(val)
val = record.find(util.nspath_eval('dct:rightsHolder', namespaces))
self.rightsholder = util.testXMLValue(val)
val = record.find(util.nspath_eval('dct:accessRights', namespaces))
self.accessrights = util.testXMLValue(val)
val = record.find(util.nspath_eval('dct:license', namespaces))
self.license = util.testXMLValue(val)
val = record.find(util.nspath_eval('dc:format', namespaces))
self.format = util.testXMLValue(val)
self.subjects = []
for i in record.findall(util.nspath_eval('dc:subject', namespaces)):
self.subjects.append(util.testXMLValue(i))
self.rights = []
for i in record.findall(util.nspath_eval('dc:rights', namespaces)):
self.rights.append(util.testXMLValue(i))
val = record.find(util.nspath_eval('dct:spatial', namespaces))
self.spatial = util.testXMLValue(val)
val = record.find(util.nspath_eval('ows:BoundingBox', namespaces))
if val is not None:
self.bbox = ows.BoundingBox(val, namespaces['ows'])
else:
self.bbox = None
val = record.find(util.nspath_eval('ows:WGS84BoundingBox', namespaces))
if val is not None:
self.bbox_wgs84 = ows.WGS84BoundingBox(val, namespaces['ows'])
else:
self.bbox_wgs84 = None
| 43.351351 | 268 | 0.611766 |
from __future__ import (absolute_import, division, print_function)
import base64
import inspect
import warnings
import StringIO
import random
from urllib import urlencode
from urllib2 import Request, urlopen
from owscapable.util import OrderedDict
from owscapable.etree import etree
from owscapable import fes
from owscapable import util
from owscapable import ows
from owscapable.iso import MD_Metadata
from owscapable.fgdc import Metadata
from owscapable.dif import DIF
from owscapable.namespaces import Namespaces
from owscapable.util import cleanup_namespaces, bind_url, add_namespaces
outputformat = 'application/xml'
def get_namespaces():
n = Namespaces()
return n.get_namespaces()
namespaces = get_namespaces()
schema = 'http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd'
schema_location = '%s %s' % (namespaces['csw'], schema)
class CatalogueServiceWeb:
def __init__(self, url, xml=None, lang='en-US', version='2.0.2', timeout=10, skip_caps=False,
username=None, password=None):
self.url = url
self.lang = lang
self.version = version
self.timeout = timeout
self.username = username
self.password = password
self.service = 'CSW'
self.exceptionreport = None
self.owscommon = ows.OwsCommon('1.0.0')
if not skip_caps:
if xml:
self._parse_response(xml)
else:
data = {'service': self.service, 'version': self.version, 'request': 'GetCapabilities'}
self.request = '%s%s' % (bind_url(self.url), urlencode(data))
self._invoke()
if self.exceptionreport is None:
val = self._exml.find(util.nspath_eval('ows:ServiceIdentification', namespaces))
self.identification=ows.ServiceIdentification(val,self.owscommon.namespace)
val = self._exml.find(util.nspath_eval('ows:ServiceProvider', namespaces))
self.provider=ows.ServiceProvider(val,self.owscommon.namespace)
self.operations=[]
for elem in self._exml.findall(util.nspath_eval('ows:OperationsMetadata/ows:Operation', namespaces)):
self.operations.append(ows.OperationsMetadata(elem, self.owscommon.namespace))
self.contents = None
val = self._exml.find(util.nspath_eval('ogc:Filter_Capabilities', namespaces))
self.filters=fes.FilterCapabilities(val)
def describerecord(self, typename='csw:Record', format=outputformat):
node0 = self._setrootelement('csw:DescribeRecord')
node0.set('service', self.service)
node0.set('version', self.version)
node0.set('outputFormat', format)
node0.set('schemaLanguage', namespaces['xs2'])
node0.set(util.nspath_eval('xsi:schemaLocation', namespaces), schema_location)
etree.SubElement(node0, util.nspath_eval('csw:TypeName', namespaces)).text = typename
self.request = node0
self._invoke()
def getdomain(self, dname, dtype='parameter'):
# construct request
dtypename = 'ParameterName'
node0 = self._setrootelement('csw:GetDomain')
node0.set('service', self.service)
node0.set('version', self.version)
node0.set(util.nspath_eval('xsi:schemaLocation', namespaces), schema_location)
if dtype == 'property':
dtypename = 'PropertyName'
etree.SubElement(node0, util.nspath_eval('csw:%s' % dtypename, namespaces)).text = dname
self.request = node0
self._invoke()
if self.exceptionreport is None:
self.results = {}
val = self._exml.find(util.nspath_eval('csw:DomainValues', namespaces)).attrib.get('type')
self.results['type'] = util.testXMLValue(val, True)
val = self._exml.find(util.nspath_eval('csw:DomainValues/csw:%s' % dtypename, namespaces))
self.results[dtype] = util.testXMLValue(val)
# get the list of values associated with the Domain
self.results['values'] = []
for f in self._exml.findall(util.nspath_eval('csw:DomainValues/csw:ListOfValues/csw:Value', namespaces)):
self.results['values'].append(util.testXMLValue(f))
def getrecords(self, qtype=None, keywords=[], typenames='csw:Record', propertyname='csw:AnyText', bbox=None, esn='summary', sortby=None, outputschema=namespaces['csw'], format=outputformat, startposition=0, maxrecords=10, cql=None, xml=None, resulttype='results'):
warnings.warn("""Please use the updated 'getrecords2' method instead of 'getrecords'.
The 'getrecords' method will be upgraded to use the 'getrecords2' parameters
in a future version of OWSLib.""")
if xml is not None:
self.request = etree.fromstring(xml)
val = self.request.find(util.nspath_eval('csw:Query/csw:ElementSetName', namespaces))
if val is not None:
esn = util.testXMLValue(val)
else:
# construct request
node0 = self._setrootelement('csw:GetRecords')
if etree.__name__ != 'lxml.etree': # apply nsmap manually
node0.set('xmlns:ows', namespaces['ows'])
node0.set('xmlns:gmd', namespaces['gmd'])
node0.set('xmlns:dif', namespaces['dif'])
node0.set('xmlns:fgdc', namespaces['fgdc'])
node0.set('outputSchema', outputschema)
node0.set('outputFormat', format)
node0.set('version', self.version)
node0.set('resultType', resulttype)
node0.set('service', self.service)
if startposition > 0:
node0.set('startPosition', str(startposition))
node0.set('maxRecords', str(maxrecords))
node0.set(util.nspath_eval('xsi:schemaLocation', namespaces), schema_location)
node1 = etree.SubElement(node0, util.nspath_eval('csw:Query', namespaces))
node1.set('typeNames', typenames)
etree.SubElement(node1, util.nspath_eval('csw:ElementSetName', namespaces)).text = esn
self._setconstraint(node1, qtype, propertyname, keywords, bbox, cql, None)
if sortby is not None:
fes.setsortby(node1, sortby)
self.request = node0
self._invoke()
if self.exceptionreport is None:
self.results = {}
# process search results attributes
val = self._exml.find(util.nspath_eval('csw:SearchResults', namespaces)).attrib.get('numberOfRecordsMatched')
self.results['matches'] = int(util.testXMLValue(val, True))
val = self._exml.find(util.nspath_eval('csw:SearchResults', namespaces)).attrib.get('numberOfRecordsReturned')
self.results['returned'] = int(util.testXMLValue(val, True))
val = self._exml.find(util.nspath_eval('csw:SearchResults', namespaces)).attrib.get('nextRecord')
self.results['nextrecord'] = int(util.testXMLValue(val, True))
# process list of matching records
self.records = OrderedDict()
self._parserecords(outputschema, esn)
def getrecordbyid(self, id=[], esn='full', outputschema=namespaces['csw'], format=outputformat):
# construct request
data = {
'service': self.service,
'version': self.version,
'request': 'GetRecordById',
'outputFormat': format,
'outputSchema': outputschema,
'elementsetname': esn,
'id': ','.join(id),
}
self.request = '%s%s' % (bind_url(self.url), urlencode(data))
self._invoke()
if self.exceptionreport is None:
self.results = {}
self.records = OrderedDict()
self._parserecords(outputschema, esn)
def getrecords2(self, constraints=[], sortby=None, typenames='csw:Record', esn='summary', outputschema=namespaces['csw'], format=outputformat, startposition=0, maxrecords=10, cql=None, xml=None, resulttype='results'):
if xml is not None:
self.request = etree.fromstring(xml)
val = self.request.find(util.nspath_eval('csw:Query/csw:ElementSetName', namespaces))
if val is not None:
esn = util.testXMLValue(val)
else:
# construct request
node0 = self._setrootelement('csw:GetRecords')
if etree.__name__ != 'lxml.etree': # apply nsmap manually
node0.set('xmlns:ows', namespaces['ows'])
node0.set('xmlns:gmd', namespaces['gmd'])
node0.set('xmlns:dif', namespaces['dif'])
node0.set('xmlns:fgdc', namespaces['fgdc'])
node0.set('outputSchema', outputschema)
node0.set('outputFormat', format)
node0.set('version', self.version)
node0.set('service', self.service)
node0.set('resultType', resulttype)
if startposition > 0:
node0.set('startPosition', str(startposition))
node0.set('maxRecords', str(maxrecords))
node0.set(util.nspath_eval('xsi:schemaLocation', namespaces), schema_location)
node1 = etree.SubElement(node0, util.nspath_eval('csw:Query', namespaces))
node1.set('typeNames', typenames)
etree.SubElement(node1, util.nspath_eval('csw:ElementSetName', namespaces)).text = esn
if any([len(constraints) > 0, cql is not None]):
node2 = etree.SubElement(node1, util.nspath_eval('csw:Constraint', namespaces))
node2.set('version', '1.1.0')
flt = fes.FilterRequest()
if len(constraints) > 0:
node2.append(flt.setConstraintList(constraints))
# Now add a CQL filter if passed in
elif cql is not None:
etree.SubElement(node2, util.nspath_eval('csw:CqlText', namespaces)).text = cql
if sortby is not None and isinstance(sortby, fes.SortBy):
node1.append(sortby.toXML())
self.request = node0
self._invoke()
if self.exceptionreport is None:
self.results = {}
# process search results attributes
val = self._exml.find(util.nspath_eval('csw:SearchResults', namespaces)).attrib.get('numberOfRecordsMatched')
self.results['matches'] = int(util.testXMLValue(val, True))
val = self._exml.find(util.nspath_eval('csw:SearchResults', namespaces)).attrib.get('numberOfRecordsReturned')
self.results['returned'] = int(util.testXMLValue(val, True))
val = self._exml.find(util.nspath_eval('csw:SearchResults', namespaces)).attrib.get('nextRecord')
if val is not None:
self.results['nextrecord'] = int(util.testXMLValue(val, True))
else:
warnings.warn("""CSW Server did not supply a nextRecord value (it is optional), so the client
should page through the results in another way.""")
# For more info, see:
# https://github.com/geopython/OWSLib/issues/100
self.results['nextrecord'] = None
# process list of matching records
self.records = OrderedDict()
self._parserecords(outputschema, esn)
def transaction(self, ttype=None, typename='csw:Record', record=None, propertyname=None, propertyvalue=None, bbox=None, keywords=[], cql=None, identifier=None):
# construct request
node0 = self._setrootelement('csw:Transaction')
node0.set('version', self.version)
node0.set('service', self.service)
node0.set(util.nspath_eval('xsi:schemaLocation', namespaces), schema_location)
validtransactions = ['insert', 'update', 'delete']
if ttype not in validtransactions: # invalid transaction
raise RuntimeError('Invalid transaction \'%s\'.' % ttype)
node1 = etree.SubElement(node0, util.nspath_eval('csw:%s' % ttype.capitalize(), namespaces))
if ttype != 'update':
node1.set('typeName', typename)
if ttype == 'insert':
if record is None:
raise RuntimeError('Nothing to insert.')
node1.append(etree.fromstring(record))
if ttype == 'update':
if record is not None:
node1.append(etree.fromstring(record))
else:
if propertyname is not None and propertyvalue is not None:
node2 = etree.SubElement(node1, util.nspath_eval('csw:RecordProperty', namespaces))
etree.SubElement(node2, util.nspath_eval('csw:Name', namespaces)).text = propertyname
etree.SubElement(node2, util.nspath_eval('csw:Value', namespaces)).text = propertyvalue
self._setconstraint(node1, qtype, propertyname, keywords, bbox, cql, identifier)
if ttype == 'delete':
self._setconstraint(node1, None, propertyname, keywords, bbox, cql, identifier)
self.request = node0
self._invoke()
self.results = {}
if self.exceptionreport is None:
self._parsetransactionsummary()
self._parseinsertresult()
def harvest(self, source, resourcetype, resourceformat=None, harvestinterval=None, responsehandler=None):
# construct request
node0 = self._setrootelement('csw:Harvest')
node0.set('version', self.version)
node0.set('service', self.service)
node0.set(util.nspath_eval('xsi:schemaLocation', namespaces), schema_location)
etree.SubElement(node0, util.nspath_eval('csw:Source', namespaces)).text = source
etree.SubElement(node0, util.nspath_eval('csw:ResourceType', namespaces)).text = resourcetype
if resourceformat is not None:
etree.SubElement(node0, util.nspath_eval('csw:ResourceFormat', namespaces)).text = resourceformat
if harvestinterval is not None:
etree.SubElement(node0, util.nspath_eval('csw:HarvestInterval', namespaces)).text = harvestinterval
if responsehandler is not None:
etree.SubElement(node0, util.nspath_eval('csw:ResponseHandler', namespaces)).text = responsehandler
self.request = node0
self._invoke()
self.results = {}
if self.exceptionreport is None:
val = self._exml.find(util.nspath_eval('csw:Acknowledgement', namespaces))
if util.testXMLValue(val) is not None:
ts = val.attrib.get('timeStamp')
self.timestamp = util.testXMLValue(ts, True)
id = val.find(util.nspath_eval('csw:RequestId', namespaces))
self.id = util.testXMLValue(id)
else:
self._parsetransactionsummary()
self._parseinsertresult()
def get_operation_by_name(self, name):
for item in self.operations:
if item.name.lower() == name.lower():
return item
raise KeyError("No operation named %s" % name)
def getService_urls(self, service_string=None):
urls=[]
for key,rec in self.records.iteritems():
#create a generator object, and iterate through it until the match is found
#if not found, gets the default value (here "none")
url = next((d['url'] for d in rec.references if d['scheme'] == service_string), None)
if url is not None:
urls.append(url)
return urls
def _parseinsertresult(self):
self.results['insertresults'] = []
for i in self._exml.findall(util.nspath_eval('csw:InsertResult', namespaces)):
for j in i.findall(util.nspath_eval('csw:BriefRecord/dc:identifier', namespaces)):
self.results['insertresults'].append(util.testXMLValue(j))
def _parserecords(self, outputschema, esn):
if outputschema == namespaces['gmd']: # iso 19139
for i in self._exml.findall('.//'+util.nspath_eval('gmd:MD_Metadata', namespaces)) or self._exml.findall('.//'+util.nspath_eval('gmi:MI_Metadata', namespaces)):
val = i.find(util.nspath_eval('gmd:fileIdentifier/gco:CharacterString', namespaces))
identifier = self._setidentifierkey(util.testXMLValue(val))
self.records[identifier] = MD_Metadata(i)
elif outputschema == namespaces['fgdc']: # fgdc csdgm
for i in self._exml.findall('.//metadata'):
val = i.find('idinfo/datasetid')
identifier = self._setidentifierkey(util.testXMLValue(val))
self.records[identifier] = Metadata(i)
elif outputschema == namespaces['dif']: # nasa dif
for i in self._exml.findall('.//'+util.nspath_eval('dif:DIF', namespaces)):
val = i.find(util.nspath_eval('dif:Entry_ID', namespaces))
identifier = self._setidentifierkey(util.testXMLValue(val))
self.records[identifier] = DIF(i)
else: # process default
for i in self._exml.findall('.//'+util.nspath_eval('csw:%s' % self._setesnel(esn), namespaces)):
val = i.find(util.nspath_eval('dc:identifier', namespaces))
identifier = self._setidentifierkey(util.testXMLValue(val))
self.records[identifier] = CswRecord(i)
def _parsetransactionsummary(self):
val = self._exml.find(util.nspath_eval('csw:TransactionSummary', namespaces))
if val is not None:
rid = val.attrib.get('requestId')
self.results['requestid'] = util.testXMLValue(rid, True)
ts = val.find(util.nspath_eval('csw:totalInserted', namespaces))
self.results['inserted'] = int(util.testXMLValue(ts))
ts = val.find(util.nspath_eval('csw:totalUpdated', namespaces))
self.results['updated'] = int(util.testXMLValue(ts))
ts = val.find(util.nspath_eval('csw:totalDeleted', namespaces))
self.results['deleted'] = int(util.testXMLValue(ts))
def _setesnel(self, esn):
el = 'Record'
if esn == 'brief':
el = 'BriefRecord'
if esn == 'summary':
el = 'SummaryRecord'
return el
def _setidentifierkey(self, el):
if el is None:
return 'owslib_random_%i' % random.randint(1,65536)
else:
return el
def _setrootelement(self, el):
if etree.__name__ == 'lxml.etree': # apply nsmap
return etree.Element(util.nspath_eval(el, namespaces), nsmap=namespaces)
else:
return etree.Element(util.nspath_eval(el, namespaces))
def _setconstraint(self, parent, qtype=None, propertyname='csw:AnyText', keywords=[], bbox=None, cql=None, identifier=None):
if keywords or bbox is not None or qtype is not None or cql is not None or identifier is not None:
node0 = etree.SubElement(parent, util.nspath_eval('csw:Constraint', namespaces))
node0.set('version', '1.1.0')
if identifier is not None: # set identifier filter, overrides all other parameters
flt = fes.FilterRequest()
node0.append(flt.set(identifier=identifier))
elif cql is not None: # send raw CQL query
# CQL passed, overrides all other parameters
node1 = etree.SubElement(node0, util.nspath_eval('csw:CqlText', namespaces))
node1.text = cql
else: # construct a Filter request
flt = fes.FilterRequest()
node0.append(flt.set(qtype=qtype, keywords=keywords, propertyname=propertyname,bbox=bbox))
def _invoke(self):
# do HTTP request
if isinstance(self.request, basestring): # GET KVP
req = Request(self.request)
if self.username is not None and self.password is not None:
base64string = base64.encodestring('%s:%s' % (self.username, self.password))[:-1]
req.add_header('Authorization', 'Basic %s' % base64string)
self.response = urlopen(req, timeout=self.timeout).read()
else:
xml_post_url = self.url
# Get correct POST URL based on Operation list.
# If skip_caps=True, then self.operations has not been set, so use
# default URL.
if hasattr(self, 'operations'):
caller = inspect.stack()[1][3]
if caller == 'getrecords2': caller = 'getrecords'
try:
op = self.get_operation_by_name(caller)
post_verbs = filter(lambda x: x.get('type').lower() == 'post', op.methods)
if len(post_verbs) > 1:
# Filter by constraints. We must match a PostEncoding of "XML"
try:
xml_post_url = next(x for x in filter(list, ([pv.get('url') for const in pv.get('constraints') if const.name.lower() == "postencoding" and 'xml' in map(lambda x: x.lower(), const.values)] for pv in post_verbs)))[0]
except StopIteration:
# Well, just use the first one.
xml_post_url = post_verbs[0].get('url')
elif len(post_verbs) == 1:
xml_post_url = post_verbs[0].get('url')
except: # no such luck, just go with xml_post_url
pass
self.request = cleanup_namespaces(self.request)
# Add any namespaces used in the "typeNames" attribute of the
# csw:Query element to the query's xml namespaces.
for query in self.request.findall(util.nspath_eval('csw:Query', namespaces)):
ns = query.get("typeNames", None)
if ns is not None:
ns_keys = [x.split(':')[0] for x in ns.split(' ')]
self.request = add_namespaces(self.request, ns_keys)
self.request = util.element_to_string(self.request, encoding='utf-8')
self.response = util.http_post(xml_post_url, self.request, self.lang, self.timeout, self.username, self.password)
self._parse_response(self.response)
def _parse_response(self, response):
self._exml = etree.parse(StringIO.StringIO(response))
# it's XML. Attempt to decipher whether the XML response is CSW-ish """
valid_xpaths = [
util.nspath_eval('ows:ExceptionReport', namespaces),
util.nspath_eval('csw:Capabilities', namespaces),
util.nspath_eval('csw:DescribeRecordResponse', namespaces),
util.nspath_eval('csw:GetDomainResponse', namespaces),
util.nspath_eval('csw:GetRecordsResponse', namespaces),
util.nspath_eval('csw:GetRecordByIdResponse', namespaces),
util.nspath_eval('csw:HarvestResponse', namespaces),
util.nspath_eval('csw:TransactionResponse', namespaces)
]
if self._exml.getroot().tag not in valid_xpaths:
raise RuntimeError('Document is XML, but not CSW-ish')
# check if it's an OGC Exception
val = self._exml.find(util.nspath_eval('ows:Exception', namespaces))
if val is not None:
raise ows.ExceptionReport(self._exml, self.owscommon.namespace)
else:
self.exceptionreport = None
class CswRecord(object):
def __init__(self, record):
if hasattr(record, 'getroot'): # standalone document
self.xml = etree.tostring(record.getroot())
else: # part of a larger document
self.xml = etree.tostring(record)
# check to see if Dublin Core record comes from
# rdf:RDF/rdf:Description container
# (child content model is identical)
self.rdf = False
rdf = record.find(util.nspath_eval('rdf:Description', namespaces))
if rdf is not None:
self.rdf = True
record = rdf
# some CSWs return records with multiple identifiers based on
# different schemes. Use the first dc:identifier value to set
# self.identifier, and set self.identifiers as a list of dicts
val = record.find(util.nspath_eval('dc:identifier', namespaces))
self.identifier = util.testXMLValue(val)
self.identifiers = []
for i in record.findall(util.nspath_eval('dc:identifier', namespaces)):
d = {}
d['scheme'] = i.attrib.get('scheme')
d['identifier'] = i.text
self.identifiers.append(d)
val = record.find(util.nspath_eval('dc:type', namespaces))
self.type = util.testXMLValue(val)
val = record.find(util.nspath_eval('dc:title', namespaces))
self.title = util.testXMLValue(val)
val = record.find(util.nspath_eval('dct:alternative', namespaces))
self.alternative = util.testXMLValue(val)
val = record.find(util.nspath_eval('dct:isPartOf', namespaces))
self.ispartof = util.testXMLValue(val)
val = record.find(util.nspath_eval('dct:abstract', namespaces))
self.abstract = util.testXMLValue(val)
val = record.find(util.nspath_eval('dc:date', namespaces))
self.date = util.testXMLValue(val)
val = record.find(util.nspath_eval('dct:created', namespaces))
self.created = util.testXMLValue(val)
val = record.find(util.nspath_eval('dct:issued', namespaces))
self.issued = util.testXMLValue(val)
val = record.find(util.nspath_eval('dc:relation', namespaces))
self.relation = util.testXMLValue(val)
val = record.find(util.nspath_eval('dct:temporal', namespaces))
self.temporal = util.testXMLValue(val)
self.uris = [] # list of dicts
for i in record.findall(util.nspath_eval('dc:URI', namespaces)):
uri = {}
uri['protocol'] = util.testXMLValue(i.attrib.get('protocol'), True)
uri['name'] = util.testXMLValue(i.attrib.get('name'), True)
uri['description'] = util.testXMLValue(i.attrib.get('description'), True)
uri['url'] = util.testXMLValue(i)
self.uris.append(uri)
self.references = [] # list of dicts
for i in record.findall(util.nspath_eval('dct:references', namespaces)):
ref = {}
ref['scheme'] = util.testXMLValue(i.attrib.get('scheme'), True)
ref['url'] = util.testXMLValue(i)
self.references.append(ref)
val = record.find(util.nspath_eval('dct:modified', namespaces))
self.modified = util.testXMLValue(val)
val = record.find(util.nspath_eval('dc:creator', namespaces))
self.creator = util.testXMLValue(val)
val = record.find(util.nspath_eval('dc:publisher', namespaces))
self.publisher = util.testXMLValue(val)
val = record.find(util.nspath_eval('dc:coverage', namespaces))
self.coverage = util.testXMLValue(val)
val = record.find(util.nspath_eval('dc:contributor', namespaces))
self.contributor = util.testXMLValue(val)
val = record.find(util.nspath_eval('dc:language', namespaces))
self.language = util.testXMLValue(val)
val = record.find(util.nspath_eval('dc:source', namespaces))
self.source = util.testXMLValue(val)
val = record.find(util.nspath_eval('dct:rightsHolder', namespaces))
self.rightsholder = util.testXMLValue(val)
val = record.find(util.nspath_eval('dct:accessRights', namespaces))
self.accessrights = util.testXMLValue(val)
val = record.find(util.nspath_eval('dct:license', namespaces))
self.license = util.testXMLValue(val)
val = record.find(util.nspath_eval('dc:format', namespaces))
self.format = util.testXMLValue(val)
self.subjects = []
for i in record.findall(util.nspath_eval('dc:subject', namespaces)):
self.subjects.append(util.testXMLValue(i))
self.rights = []
for i in record.findall(util.nspath_eval('dc:rights', namespaces)):
self.rights.append(util.testXMLValue(i))
val = record.find(util.nspath_eval('dct:spatial', namespaces))
self.spatial = util.testXMLValue(val)
val = record.find(util.nspath_eval('ows:BoundingBox', namespaces))
if val is not None:
self.bbox = ows.BoundingBox(val, namespaces['ows'])
else:
self.bbox = None
val = record.find(util.nspath_eval('ows:WGS84BoundingBox', namespaces))
if val is not None:
self.bbox_wgs84 = ows.WGS84BoundingBox(val, namespaces['ows'])
else:
self.bbox_wgs84 = None
| true | true |
f72b67fe680c8d3c4ade97a3c8636404858cf558 | 648 | py | Python | setup.py | sufiyanghori/sensu-plugin-python | 6682163a2a2219e8132b4c9e1dd53663fa477ae5 | [
"MIT"
] | null | null | null | setup.py | sufiyanghori/sensu-plugin-python | 6682163a2a2219e8132b4c9e1dd53663fa477ae5 | [
"MIT"
] | null | null | null | setup.py | sufiyanghori/sensu-plugin-python | 6682163a2a2219e8132b4c9e1dd53663fa477ae5 | [
"MIT"
] | null | null | null | from distutils.core import setup
setup(
name='sensu_plugin',
version='0.7.0',
author='Sensu-Plugins and Contributors',
author_email='sensu-users@googlegroups.com',
packages=['sensu_plugin', 'sensu_plugin.tests'],
scripts=[],
url='https://github.com/sensu-plugins/sensu-plugin-python',
license='LICENSE.txt',
description='A framework for writing Python sensu plugins.',
long_description="""
""",
install_requires=[
'argparse',
'requests'
],
tests_require=[
'pycodestyle',
'pylint',
'coverage',
'nose',
'pytest',
'mock'
],
)
| 23.142857 | 64 | 0.594136 | from distutils.core import setup
setup(
name='sensu_plugin',
version='0.7.0',
author='Sensu-Plugins and Contributors',
author_email='sensu-users@googlegroups.com',
packages=['sensu_plugin', 'sensu_plugin.tests'],
scripts=[],
url='https://github.com/sensu-plugins/sensu-plugin-python',
license='LICENSE.txt',
description='A framework for writing Python sensu plugins.',
long_description="""
""",
install_requires=[
'argparse',
'requests'
],
tests_require=[
'pycodestyle',
'pylint',
'coverage',
'nose',
'pytest',
'mock'
],
)
| true | true |
f72b685d506ef171b93f3f1fddeda1a0a511663e | 8,723 | py | Python | tests/test_joint_logprob.py | kc611/aeppl | d24eee80a7448c48b55a8ec41aec150d1dd9d6a7 | [
"MIT"
] | null | null | null | tests/test_joint_logprob.py | kc611/aeppl | d24eee80a7448c48b55a8ec41aec150d1dd9d6a7 | [
"MIT"
] | null | null | null | tests/test_joint_logprob.py | kc611/aeppl | d24eee80a7448c48b55a8ec41aec150d1dd9d6a7 | [
"MIT"
] | null | null | null | import aesara
import aesara.tensor as at
import numpy as np
import pytest
import scipy.stats.distributions as sp
from aesara.graph.basic import Apply, ancestors, equal_computations
from aesara.graph.op import Op
from aesara.tensor.subtensor import (
AdvancedIncSubtensor,
AdvancedIncSubtensor1,
AdvancedSubtensor,
AdvancedSubtensor1,
IncSubtensor,
Subtensor,
)
from aeppl.abstract import MeasurableVariable
from aeppl.joint_logprob import joint_logprob
from aeppl.logprob import _logprob, logprob
from aeppl.utils import rvs_to_value_vars, walk_model
from tests.utils import assert_no_rvs
def test_joint_logprob_basic():
# A simple check for when `joint_logprob` is the same as `logprob`
a = at.random.uniform(0.0, 1.0)
a.name = "a"
a_value_var = a.clone()
a_logp = joint_logprob({a: a_value_var}, sum=False)
a_logp_exp = logprob(a, a_value_var)
assert equal_computations([a_logp], [a_logp_exp])
# Let's try a hierarchical model
sigma = at.random.invgamma(0.5, 0.5)
Y = at.random.normal(0.0, sigma)
sigma_value_var = sigma.clone()
y_value_var = Y.clone()
total_ll = joint_logprob({Y: y_value_var, sigma: sigma_value_var}, sum=False)
# We need to replace the reference to `sigma` in `Y` with its value
# variable
ll_Y = logprob(Y, y_value_var)
(ll_Y,), _ = rvs_to_value_vars(
[ll_Y],
initial_replacements={sigma: sigma_value_var},
)
total_ll_exp = logprob(sigma, sigma_value_var) + ll_Y
assert equal_computations([total_ll], [total_ll_exp])
# Now, make sure we can compute a joint log-probability for a hierarchical
# model with some non-`RandomVariable` nodes
c = at.random.normal()
c.name = "c"
b_l = c * a + 2.0
b = at.random.uniform(b_l, b_l + 1.0)
b.name = "b"
b_value_var = b.clone()
c_value_var = c.clone()
b_logp = joint_logprob({a: a_value_var, b: b_value_var, c: c_value_var})
# There shouldn't be any `RandomVariable`s in the resulting graph
assert_no_rvs(b_logp)
res_ancestors = list(walk_model((b_logp,), walk_past_rvs=True))
assert b_value_var in res_ancestors
assert c_value_var in res_ancestors
assert a_value_var in res_ancestors
def test_joint_logprob_multi_obs():
a = at.random.uniform(0.0, 1.0)
b = at.random.normal(0.0, 1.0)
a_val = a.clone()
b_val = b.clone()
logp = joint_logprob({a: a_val, b: b_val}, sum=False)
logp_exp = logprob(a, a_val) + logprob(b, b_val)
assert equal_computations([logp], [logp_exp])
x = at.random.normal(0, 1)
y = at.random.normal(x, 1)
x_val = x.clone()
y_val = y.clone()
logp = joint_logprob({x: x_val, y: y_val})
exp_logp = joint_logprob({x: x_val, y: y_val})
assert equal_computations([logp], [exp_logp])
def test_joint_logprob_diff_dims():
M = at.matrix("M")
x = at.random.normal(0, 1, size=M.shape[1], name="X")
y = at.random.normal(M.dot(x), 1, name="Y")
x_vv = x.clone()
x_vv.name = "x"
y_vv = y.clone()
y_vv.name = "y"
logp = joint_logprob({x: x_vv, y: y_vv})
M_val = np.random.normal(size=(10, 3))
x_val = np.random.normal(size=(3,))
y_val = np.random.normal(size=(10,))
point = {M: M_val, x_vv: x_val, y_vv: y_val}
logp_val = logp.eval(point)
exp_logp_val = (
sp.norm.logpdf(x_val, 0, 1).sum()
+ sp.norm.logpdf(y_val, M_val.dot(x_val), 1).sum()
)
assert exp_logp_val == pytest.approx(logp_val)
@pytest.mark.parametrize(
"indices, size",
[
(slice(0, 2), 5),
(np.r_[True, True, False, False, True], 5),
(np.r_[0, 1, 4], 5),
((np.array([0, 1, 4]), np.array([0, 1, 4])), (5, 5)),
],
)
def test_joint_logprob_incsubtensor(indices, size):
"""Make sure we can compute a joint log-probability for ``Y[idx] = data`` where ``Y`` is univariate."""
rng = np.random.RandomState(232)
mu = np.power(10, np.arange(np.prod(size))).reshape(size)
sigma = 0.001
data = rng.normal(mu[indices], 1.0)
y_val = rng.normal(mu, sigma, size=size)
Y_rv = at.random.normal(mu, sigma, size=size)
Y_rv.name = "Y"
y_value_var = Y_rv.clone()
y_value_var.name = "y"
Y_sst = at.set_subtensor(Y_rv[indices], data)
assert isinstance(
Y_sst.owner.op, (IncSubtensor, AdvancedIncSubtensor, AdvancedIncSubtensor1)
)
Y_sst_logp = joint_logprob({Y_rv: y_value_var, Y_sst: None}, sum=False)
obs_logps = Y_sst_logp.eval({y_value_var: y_val})
y_val_idx = y_val.copy()
y_val_idx[indices] = data
exp_obs_logps = sp.norm.logpdf(y_val_idx, mu, sigma)
np.testing.assert_almost_equal(obs_logps, exp_obs_logps)
def test_joint_logprob_subtensor():
"""Make sure we can compute a joint log-probability for ``Y[I]`` where ``Y`` and ``I`` are random variables."""
size = 5
mu_base = np.power(10, np.arange(np.prod(size))).reshape(size)
mu = np.stack([mu_base, -mu_base])
sigma = 0.001
rng = aesara.shared(np.random.RandomState(232), borrow=True)
A_rv = at.random.normal(mu, sigma, rng=rng)
A_rv.name = "A"
p = 0.5
I_rv = at.random.bernoulli(p, size=size, rng=rng)
I_rv.name = "I"
A_idx = A_rv[I_rv, at.ogrid[A_rv.shape[-1] :]]
assert isinstance(
A_idx.owner.op, (Subtensor, AdvancedSubtensor, AdvancedSubtensor1)
)
A_idx_value_var = A_idx.type()
A_idx_value_var.name = "A_idx_value"
I_value_var = I_rv.type()
I_value_var.name = "I_value"
A_idx_logp = joint_logprob({A_idx: A_idx_value_var, I_rv: I_value_var}, sum=False)
logp_vals_fn = aesara.function([A_idx_value_var, I_value_var], A_idx_logp)
# The compiled graph should not contain any `RandomVariables`
assert_no_rvs(logp_vals_fn.maker.fgraph.outputs[0])
decimals = 6 if aesara.config.floatX == "float64" else 4
test_val_rng = np.random.RandomState(3238)
for i in range(10):
bern_sp = sp.bernoulli(p)
I_value = bern_sp.rvs(size=size, random_state=test_val_rng).astype(I_rv.dtype)
norm_sp = sp.norm(mu[I_value, np.ogrid[mu.shape[1] :]], sigma)
A_idx_value = norm_sp.rvs(random_state=test_val_rng).astype(A_idx.dtype)
exp_obs_logps = norm_sp.logpdf(A_idx_value)
exp_obs_logps += bern_sp.logpmf(I_value)
logp_vals = logp_vals_fn(A_idx_value, I_value)
np.testing.assert_almost_equal(logp_vals, exp_obs_logps, decimal=decimals)
def test_persist_inputs():
"""Make sure we don't unnecessarily clone variables."""
x = at.scalar("x")
beta_rv = at.random.normal(0, 1, name="beta")
Y_rv = at.random.normal(beta_rv * x, 1, name="y")
beta_vv = beta_rv.type()
y_vv = Y_rv.clone()
logp = joint_logprob({beta_rv: beta_vv, Y_rv: y_vv})
assert x in ancestors([logp])
# Make sure we don't clone value variables when they're graphs.
y_vv_2 = y_vv * 2
logp_2 = joint_logprob({beta_rv: beta_vv, Y_rv: y_vv_2})
assert y_vv_2 in ancestors([logp_2])
def test_ignore_logprob():
x = at.scalar("x")
beta_rv = at.random.normal(0, 1, name="beta")
beta_rv.tag.ignore_logprob = True
y_rv = at.random.normal(beta_rv * x, 1, name="y")
beta = beta_rv.type()
y = y_rv.type()
logp = joint_logprob({beta_rv: beta, y_rv: y})
y_rv_2 = at.random.normal(beta * x, 1, name="y")
logp_exp = joint_logprob({y_rv_2: y})
assert equal_computations([logp], [logp_exp])
def test_ignore_logprob_multiout():
class MyMultiOut(Op):
@staticmethod
def impl(a, b):
res1 = 2 * a
res2 = 2 * b
return [res1, res2]
def make_node(self, a, b):
return Apply(self, [a, b], [a.type(), b.type()])
def perform(self, node, inputs, outputs):
res1, res2 = self.impl(inputs[0], inputs[1])
outputs[0][0] = res1
outputs[1][0] = res2
MeasurableVariable.register(MyMultiOut)
@_logprob.register(MyMultiOut)
def logprob_MyMultiOut(op, value, *inputs, name=None, **kwargs):
return at.zeros_like(value)
Y_1_rv, Y_2_rv = MyMultiOut()(at.vector(), at.vector())
Y_1_rv.tag.ignore_logprob = True
Y_2_rv.tag.ignore_logprob = True
y_1_vv = Y_1_rv.clone()
y_2_vv = Y_2_rv.clone()
logp_exp = joint_logprob({Y_1_rv: y_1_vv, Y_2_rv: y_2_vv})
assert logp_exp is None
def test_multiple_rvs_to_same_value_raises():
x_rv1 = at.random.normal(name="x1")
x_rv2 = at.random.normal(name="x2")
x = x_rv1.type()
x.name = "x"
msg = "More than one logprob factor was assigned to the value var x"
with pytest.raises(ValueError, match=msg):
joint_logprob({x_rv1: x, x_rv2: x})
| 28.6 | 115 | 0.652872 | import aesara
import aesara.tensor as at
import numpy as np
import pytest
import scipy.stats.distributions as sp
from aesara.graph.basic import Apply, ancestors, equal_computations
from aesara.graph.op import Op
from aesara.tensor.subtensor import (
AdvancedIncSubtensor,
AdvancedIncSubtensor1,
AdvancedSubtensor,
AdvancedSubtensor1,
IncSubtensor,
Subtensor,
)
from aeppl.abstract import MeasurableVariable
from aeppl.joint_logprob import joint_logprob
from aeppl.logprob import _logprob, logprob
from aeppl.utils import rvs_to_value_vars, walk_model
from tests.utils import assert_no_rvs
def test_joint_logprob_basic():
a = at.random.uniform(0.0, 1.0)
a.name = "a"
a_value_var = a.clone()
a_logp = joint_logprob({a: a_value_var}, sum=False)
a_logp_exp = logprob(a, a_value_var)
assert equal_computations([a_logp], [a_logp_exp])
sigma = at.random.invgamma(0.5, 0.5)
Y = at.random.normal(0.0, sigma)
sigma_value_var = sigma.clone()
y_value_var = Y.clone()
total_ll = joint_logprob({Y: y_value_var, sigma: sigma_value_var}, sum=False)
# We need to replace the reference to `sigma` in `Y` with its value
# variable
ll_Y = logprob(Y, y_value_var)
(ll_Y,), _ = rvs_to_value_vars(
[ll_Y],
initial_replacements={sigma: sigma_value_var},
)
total_ll_exp = logprob(sigma, sigma_value_var) + ll_Y
assert equal_computations([total_ll], [total_ll_exp])
# Now, make sure we can compute a joint log-probability for a hierarchical
# model with some non-`RandomVariable` nodes
c = at.random.normal()
c.name = "c"
b_l = c * a + 2.0
b = at.random.uniform(b_l, b_l + 1.0)
b.name = "b"
b_value_var = b.clone()
c_value_var = c.clone()
b_logp = joint_logprob({a: a_value_var, b: b_value_var, c: c_value_var})
# There shouldn't be any `RandomVariable`s in the resulting graph
assert_no_rvs(b_logp)
res_ancestors = list(walk_model((b_logp,), walk_past_rvs=True))
assert b_value_var in res_ancestors
assert c_value_var in res_ancestors
assert a_value_var in res_ancestors
def test_joint_logprob_multi_obs():
a = at.random.uniform(0.0, 1.0)
b = at.random.normal(0.0, 1.0)
a_val = a.clone()
b_val = b.clone()
logp = joint_logprob({a: a_val, b: b_val}, sum=False)
logp_exp = logprob(a, a_val) + logprob(b, b_val)
assert equal_computations([logp], [logp_exp])
x = at.random.normal(0, 1)
y = at.random.normal(x, 1)
x_val = x.clone()
y_val = y.clone()
logp = joint_logprob({x: x_val, y: y_val})
exp_logp = joint_logprob({x: x_val, y: y_val})
assert equal_computations([logp], [exp_logp])
def test_joint_logprob_diff_dims():
M = at.matrix("M")
x = at.random.normal(0, 1, size=M.shape[1], name="X")
y = at.random.normal(M.dot(x), 1, name="Y")
x_vv = x.clone()
x_vv.name = "x"
y_vv = y.clone()
y_vv.name = "y"
logp = joint_logprob({x: x_vv, y: y_vv})
M_val = np.random.normal(size=(10, 3))
x_val = np.random.normal(size=(3,))
y_val = np.random.normal(size=(10,))
point = {M: M_val, x_vv: x_val, y_vv: y_val}
logp_val = logp.eval(point)
exp_logp_val = (
sp.norm.logpdf(x_val, 0, 1).sum()
+ sp.norm.logpdf(y_val, M_val.dot(x_val), 1).sum()
)
assert exp_logp_val == pytest.approx(logp_val)
@pytest.mark.parametrize(
"indices, size",
[
(slice(0, 2), 5),
(np.r_[True, True, False, False, True], 5),
(np.r_[0, 1, 4], 5),
((np.array([0, 1, 4]), np.array([0, 1, 4])), (5, 5)),
],
)
def test_joint_logprob_incsubtensor(indices, size):
rng = np.random.RandomState(232)
mu = np.power(10, np.arange(np.prod(size))).reshape(size)
sigma = 0.001
data = rng.normal(mu[indices], 1.0)
y_val = rng.normal(mu, sigma, size=size)
Y_rv = at.random.normal(mu, sigma, size=size)
Y_rv.name = "Y"
y_value_var = Y_rv.clone()
y_value_var.name = "y"
Y_sst = at.set_subtensor(Y_rv[indices], data)
assert isinstance(
Y_sst.owner.op, (IncSubtensor, AdvancedIncSubtensor, AdvancedIncSubtensor1)
)
Y_sst_logp = joint_logprob({Y_rv: y_value_var, Y_sst: None}, sum=False)
obs_logps = Y_sst_logp.eval({y_value_var: y_val})
y_val_idx = y_val.copy()
y_val_idx[indices] = data
exp_obs_logps = sp.norm.logpdf(y_val_idx, mu, sigma)
np.testing.assert_almost_equal(obs_logps, exp_obs_logps)
def test_joint_logprob_subtensor():
size = 5
mu_base = np.power(10, np.arange(np.prod(size))).reshape(size)
mu = np.stack([mu_base, -mu_base])
sigma = 0.001
rng = aesara.shared(np.random.RandomState(232), borrow=True)
A_rv = at.random.normal(mu, sigma, rng=rng)
A_rv.name = "A"
p = 0.5
I_rv = at.random.bernoulli(p, size=size, rng=rng)
I_rv.name = "I"
A_idx = A_rv[I_rv, at.ogrid[A_rv.shape[-1] :]]
assert isinstance(
A_idx.owner.op, (Subtensor, AdvancedSubtensor, AdvancedSubtensor1)
)
A_idx_value_var = A_idx.type()
A_idx_value_var.name = "A_idx_value"
I_value_var = I_rv.type()
I_value_var.name = "I_value"
A_idx_logp = joint_logprob({A_idx: A_idx_value_var, I_rv: I_value_var}, sum=False)
logp_vals_fn = aesara.function([A_idx_value_var, I_value_var], A_idx_logp)
assert_no_rvs(logp_vals_fn.maker.fgraph.outputs[0])
decimals = 6 if aesara.config.floatX == "float64" else 4
test_val_rng = np.random.RandomState(3238)
for i in range(10):
bern_sp = sp.bernoulli(p)
I_value = bern_sp.rvs(size=size, random_state=test_val_rng).astype(I_rv.dtype)
norm_sp = sp.norm(mu[I_value, np.ogrid[mu.shape[1] :]], sigma)
A_idx_value = norm_sp.rvs(random_state=test_val_rng).astype(A_idx.dtype)
exp_obs_logps = norm_sp.logpdf(A_idx_value)
exp_obs_logps += bern_sp.logpmf(I_value)
logp_vals = logp_vals_fn(A_idx_value, I_value)
np.testing.assert_almost_equal(logp_vals, exp_obs_logps, decimal=decimals)
def test_persist_inputs():
x = at.scalar("x")
beta_rv = at.random.normal(0, 1, name="beta")
Y_rv = at.random.normal(beta_rv * x, 1, name="y")
beta_vv = beta_rv.type()
y_vv = Y_rv.clone()
logp = joint_logprob({beta_rv: beta_vv, Y_rv: y_vv})
assert x in ancestors([logp])
y_vv_2 = y_vv * 2
logp_2 = joint_logprob({beta_rv: beta_vv, Y_rv: y_vv_2})
assert y_vv_2 in ancestors([logp_2])
def test_ignore_logprob():
x = at.scalar("x")
beta_rv = at.random.normal(0, 1, name="beta")
beta_rv.tag.ignore_logprob = True
y_rv = at.random.normal(beta_rv * x, 1, name="y")
beta = beta_rv.type()
y = y_rv.type()
logp = joint_logprob({beta_rv: beta, y_rv: y})
y_rv_2 = at.random.normal(beta * x, 1, name="y")
logp_exp = joint_logprob({y_rv_2: y})
assert equal_computations([logp], [logp_exp])
def test_ignore_logprob_multiout():
class MyMultiOut(Op):
@staticmethod
def impl(a, b):
res1 = 2 * a
res2 = 2 * b
return [res1, res2]
def make_node(self, a, b):
return Apply(self, [a, b], [a.type(), b.type()])
def perform(self, node, inputs, outputs):
res1, res2 = self.impl(inputs[0], inputs[1])
outputs[0][0] = res1
outputs[1][0] = res2
MeasurableVariable.register(MyMultiOut)
@_logprob.register(MyMultiOut)
def logprob_MyMultiOut(op, value, *inputs, name=None, **kwargs):
return at.zeros_like(value)
Y_1_rv, Y_2_rv = MyMultiOut()(at.vector(), at.vector())
Y_1_rv.tag.ignore_logprob = True
Y_2_rv.tag.ignore_logprob = True
y_1_vv = Y_1_rv.clone()
y_2_vv = Y_2_rv.clone()
logp_exp = joint_logprob({Y_1_rv: y_1_vv, Y_2_rv: y_2_vv})
assert logp_exp is None
def test_multiple_rvs_to_same_value_raises():
x_rv1 = at.random.normal(name="x1")
x_rv2 = at.random.normal(name="x2")
x = x_rv1.type()
x.name = "x"
msg = "More than one logprob factor was assigned to the value var x"
with pytest.raises(ValueError, match=msg):
joint_logprob({x_rv1: x, x_rv2: x})
| true | true |
f72b69a62107d6763a33183b36f8ec377f171f30 | 2,003 | py | Python | sgmock/fixture/setup.py | blurstudio/sgmock | 6b5b949cbd4bc16db8060f1b07bb8113a624e9e4 | [
"BSD-3-Clause"
] | null | null | null | sgmock/fixture/setup.py | blurstudio/sgmock | 6b5b949cbd4bc16db8060f1b07bb8113a624e9e4 | [
"BSD-3-Clause"
] | null | null | null | sgmock/fixture/setup.py | blurstudio/sgmock | 6b5b949cbd4bc16db8060f1b07bb8113a624e9e4 | [
"BSD-3-Clause"
] | null | null | null | import random
from .base import Fixture
# From various online generators.
project_names = [
'Waiting for Johnson',
'Helping Delilah',
'Finding Gump',
'Double Danger',
'Master of Surrender',
'Compulsive Winter',
'Inner Space',
]
# All of the WesternX sequence codes from previous films.
sequence_names = [
'AB', 'BA', 'BB', 'BD', 'BE', 'BL', 'BS', 'BU', 'BX', 'CD', 'CF', 'CT',
'DB', 'DC', 'DD', 'DR', 'ED', 'FX', 'GB', 'GC', 'GP', 'GR', 'HH', 'HT',
'IC', 'IP', 'JK', 'JS', 'LP', 'MB', 'MD', 'MP', 'MS', 'NP', 'NS', 'OS',
'PB', 'PJ', 'PM', 'PR', 'PV', 'RB', 'RD', 'RF', 'RG', 'RT', 'SD', 'SE',
'SL', 'SM', 'SN', 'SP', 'SS', 'SX', 'UB', 'VX', 'WR', 'ZD'
]
asset_specs = [
('Character', 'Cow'),
('Character', 'Dog'),
('Character', 'Monkey'),
('Character', 'Pig'),
('Character', 'Camel'),
('Character', 'Snake'),
('Environment', 'Moon'),
('Environment', 'Mars'),
('Environment', 'Space'),
('Environment', 'Forest'),
('Environment', 'Volcano'),
]
def full(sg):
fix = Fixture(sg)
steps = fix.default_steps()
random.shuffle(project_names)
random.shuffle(sequence_names)
for proj_i in xrange(4):
proj = fix.Project(project_names.pop())
for seq_i in xrange(random.randint(3, 8)):
seq = proj.Sequence(sequence_names.pop())
for shot_i in xrange(random.randint(3, 8)):
shot = seq.Shot('%s_%03d' % (seq['code'], shot_i + 1))
for step_code in ('Online', 'MM', 'Anm', 'Light', 'Comp'):
shot.Task('Do %s Work' % step_code, steps[step_code])
random.shuffle(asset_specs)
for asset_i in xrange(random.randint(5, 9)):
type_, code = asset_specs[asset_i]
asset = proj.Asset(code, type_)
for step_code in ('Art', 'Model', 'Rig'):
asset.Task('Do %s Work' % step_code, steps[step_code])
| 28.614286 | 75 | 0.51323 | import random
from .base import Fixture
project_names = [
'Waiting for Johnson',
'Helping Delilah',
'Finding Gump',
'Double Danger',
'Master of Surrender',
'Compulsive Winter',
'Inner Space',
]
sequence_names = [
'AB', 'BA', 'BB', 'BD', 'BE', 'BL', 'BS', 'BU', 'BX', 'CD', 'CF', 'CT',
'DB', 'DC', 'DD', 'DR', 'ED', 'FX', 'GB', 'GC', 'GP', 'GR', 'HH', 'HT',
'IC', 'IP', 'JK', 'JS', 'LP', 'MB', 'MD', 'MP', 'MS', 'NP', 'NS', 'OS',
'PB', 'PJ', 'PM', 'PR', 'PV', 'RB', 'RD', 'RF', 'RG', 'RT', 'SD', 'SE',
'SL', 'SM', 'SN', 'SP', 'SS', 'SX', 'UB', 'VX', 'WR', 'ZD'
]
asset_specs = [
('Character', 'Cow'),
('Character', 'Dog'),
('Character', 'Monkey'),
('Character', 'Pig'),
('Character', 'Camel'),
('Character', 'Snake'),
('Environment', 'Moon'),
('Environment', 'Mars'),
('Environment', 'Space'),
('Environment', 'Forest'),
('Environment', 'Volcano'),
]
def full(sg):
fix = Fixture(sg)
steps = fix.default_steps()
random.shuffle(project_names)
random.shuffle(sequence_names)
for proj_i in xrange(4):
proj = fix.Project(project_names.pop())
for seq_i in xrange(random.randint(3, 8)):
seq = proj.Sequence(sequence_names.pop())
for shot_i in xrange(random.randint(3, 8)):
shot = seq.Shot('%s_%03d' % (seq['code'], shot_i + 1))
for step_code in ('Online', 'MM', 'Anm', 'Light', 'Comp'):
shot.Task('Do %s Work' % step_code, steps[step_code])
random.shuffle(asset_specs)
for asset_i in xrange(random.randint(5, 9)):
type_, code = asset_specs[asset_i]
asset = proj.Asset(code, type_)
for step_code in ('Art', 'Model', 'Rig'):
asset.Task('Do %s Work' % step_code, steps[step_code])
| true | true |
f72b6b42f15d1adf79085531fb38312487b1ca0c | 3,816 | py | Python | FairnessTest/models/Seq2Seq_WER/opts.py | zgahhblhc/DialogueFairness | dc00eb8aad7145cdd01f69c99fd79f741b9aa8d4 | [
"MIT"
] | 3 | 2020-12-10T02:20:44.000Z | 2022-02-23T18:03:30.000Z | FairnessTest/models/Seq2Seq_WER/opts.py | zgahhblhc/DialogueFairness | dc00eb8aad7145cdd01f69c99fd79f741b9aa8d4 | [
"MIT"
] | null | null | null | FairnessTest/models/Seq2Seq_WER/opts.py | zgahhblhc/DialogueFairness | dc00eb8aad7145cdd01f69c99fd79f741b9aa8d4 | [
"MIT"
] | 4 | 2020-11-03T18:33:24.000Z | 2022-02-23T18:04:01.000Z | opt = {'task': 'twitter',
'download_path': '/mnt/home/liuhaoc1/ParlAI/downloads',
'datatype': 'train',
'image_mode': 'raw',
'numthreads': 1,
'hide_labels': False,
'batchsize': 32,
'batch_sort': True,
'context_length': -1,
'include_labels': True,
'datapath': '/mnt/home/liuhaoc1/ParlAI/data',
'model': 'legacy:seq2seq:0',
'model_file': '/mnt/home/liuhaoc1/ParlAI/models/seq_twitter_reg_0.25/seq_twitter_reg_0.25',
'dict_class': '',
'evaltask': None,
'display_examples': False,
'num_epochs': -1,
'max_train_time': 205200.0,
# 'validation_every_n_secs': 600.0,
'save_every_n_secs': -1,
'save_after_valid': True,
# 'validation_max_exs': -1,
# 'validation_patience': 18,
# 'validation_metric': 'ppl',
# 'validation_metric_mode': 'min',
# 'validation_cutoff': 1.0,
'dict_build_first': True,
'load_from_checkpoint': True,
'tensorboard_log': False,
'tensorboard_tag': None,
'tensorboard_metrics': None,
'tensorboard_comment': '',
'dict_maxexs': -1,
'dict_include_valid': False,
'dict_include_test': False,
'log_every_n_secs': 15.0,
'image_size': 256,
'image_cropsize': 224,
'init_model': None,
'hiddensize': 1024,
'embeddingsize': 300,
'numlayers': 3,
'learningrate': 1.0,
'dropout': 0.0,
'gradient_clip': 0.1,
'bidirectional': False, 'attention': 'none',
'attention_length': 48, 'attention_time': 'post',
'no_cuda': False, 'gpu': -1,
'rank_candidates': False, 'truncate': 150,
'rnn_class': 'lstm', 'decoder': 'same',
'lookuptable': 'enc_dec', 'optimizer': 'sgd',
'momentum': 0.9, 'embedding_type': 'random',
'numsoftmax': 1, 'report_freq': 0.001,
'history_replies': 'label_else_model',
'person_tokens': False,
'dict_file': '',
'dict_initpath': None,
'dict_language': 'english',
'dict_max_ngram_size': -1, 'dict_minfreq': 0,
'dict_maxtokens': 30000, 'dict_nulltoken': '__NULL__',
'dict_starttoken': '__START__', 'dict_endtoken': '__END__',
'dict_unktoken': '__UNK__', 'dict_tokenizer': 're', 'dict_lower': True,
'parlai_home': '/mnt/home/liuhaoc1/ParlAI',
# 'override': {'task': 'twitter', 'max_train_time': '205200', 'model': 'seq2seq', 'numsoftmax': '1', 'hiddensize': '1024', 'embeddingsize': '300', 'attention': 'none', 'numlayers': '3', 'rnn_class': 'lstm', 'learningrate': '1',
# 'dropout': '0.0',
# 'gradient_clip': '0.1', 'lookuptable': 'enc_dec', 'optimizer': 'sgd', 'embedding_type': 'glove', 'momentum': '0.9', 'batchsize': '32', 'batch_sort': 'True', 'truncate': '150', 'validation_every_n_secs': '600', 'validation_metric': 'ppl', 'validation_metric_mode': 'min', 'validation_patience': '18', 'save_after_valid': 'True', 'load_from_checkpoint': 'True', 'dict_lower': 'True', 'dict_maxtokens': '30000', 'log_every_n_secs': '15', 'model_file': '/mnt/home/liuhaoc1/ParlAI/models/seq_twitter_aug/seq_twitter_aug'},
'starttime': 'Jun15_16-53', 'show_advanced_args': False,
'pytorch_teacher_task': None, 'pytorch_teacher_dataset': None,
'pytorch_datapath': None, 'numworkers': 4, 'pytorch_preprocess': False,
'pytorch_teacher_batch_sort': False, 'batch_sort_cache_type': 'pop',
'batch_length_range': 5, 'shuffle': False, 'batch_sort_field': 'text',
'pytorch_context_length': -1, 'pytorch_include_labels': True, 'num_examples': -1,
'metrics': 'all', 'beam_size': 1, 'beam_log_freq': 0.0, 'topk': 1,
'softmax_layer_bias': False, 'bpe_debug': False, 'dict_textfields': 'text,labels'} | 51.567568 | 539 | 0.60587 | opt = {'task': 'twitter',
'download_path': '/mnt/home/liuhaoc1/ParlAI/downloads',
'datatype': 'train',
'image_mode': 'raw',
'numthreads': 1,
'hide_labels': False,
'batchsize': 32,
'batch_sort': True,
'context_length': -1,
'include_labels': True,
'datapath': '/mnt/home/liuhaoc1/ParlAI/data',
'model': 'legacy:seq2seq:0',
'model_file': '/mnt/home/liuhaoc1/ParlAI/models/seq_twitter_reg_0.25/seq_twitter_reg_0.25',
'dict_class': '',
'evaltask': None,
'display_examples': False,
'num_epochs': -1,
'max_train_time': 205200.0,
'save_every_n_secs': -1,
'save_after_valid': True,
'dict_build_first': True,
'load_from_checkpoint': True,
'tensorboard_log': False,
'tensorboard_tag': None,
'tensorboard_metrics': None,
'tensorboard_comment': '',
'dict_maxexs': -1,
'dict_include_valid': False,
'dict_include_test': False,
'log_every_n_secs': 15.0,
'image_size': 256,
'image_cropsize': 224,
'init_model': None,
'hiddensize': 1024,
'embeddingsize': 300,
'numlayers': 3,
'learningrate': 1.0,
'dropout': 0.0,
'gradient_clip': 0.1,
'bidirectional': False, 'attention': 'none',
'attention_length': 48, 'attention_time': 'post',
'no_cuda': False, 'gpu': -1,
'rank_candidates': False, 'truncate': 150,
'rnn_class': 'lstm', 'decoder': 'same',
'lookuptable': 'enc_dec', 'optimizer': 'sgd',
'momentum': 0.9, 'embedding_type': 'random',
'numsoftmax': 1, 'report_freq': 0.001,
'history_replies': 'label_else_model',
'person_tokens': False,
'dict_file': '',
'dict_initpath': None,
'dict_language': 'english',
'dict_max_ngram_size': -1, 'dict_minfreq': 0,
'dict_maxtokens': 30000, 'dict_nulltoken': '__NULL__',
'dict_starttoken': '__START__', 'dict_endtoken': '__END__',
'dict_unktoken': '__UNK__', 'dict_tokenizer': 're', 'dict_lower': True,
'parlai_home': '/mnt/home/liuhaoc1/ParlAI',
'starttime': 'Jun15_16-53', 'show_advanced_args': False,
'pytorch_teacher_task': None, 'pytorch_teacher_dataset': None,
'pytorch_datapath': None, 'numworkers': 4, 'pytorch_preprocess': False,
'pytorch_teacher_batch_sort': False, 'batch_sort_cache_type': 'pop',
'batch_length_range': 5, 'shuffle': False, 'batch_sort_field': 'text',
'pytorch_context_length': -1, 'pytorch_include_labels': True, 'num_examples': -1,
'metrics': 'all', 'beam_size': 1, 'beam_log_freq': 0.0, 'topk': 1,
'softmax_layer_bias': False, 'bpe_debug': False, 'dict_textfields': 'text,labels'} | true | true |
f72b6b557eea5c628cc1be578fe43d5224c205f4 | 6,820 | py | Python | ivy_tests/test_ivy/test_functional/test_core/test_nest.py | mattbarrett98/ivy | a706e59b907c0f78edb819959cc2035ebf48946f | [
"Apache-2.0"
] | null | null | null | ivy_tests/test_ivy/test_functional/test_core/test_nest.py | mattbarrett98/ivy | a706e59b907c0f78edb819959cc2035ebf48946f | [
"Apache-2.0"
] | null | null | null | ivy_tests/test_ivy/test_functional/test_core/test_nest.py | mattbarrett98/ivy | a706e59b907c0f78edb819959cc2035ebf48946f | [
"Apache-2.0"
] | null | null | null | """
Collection of tests for unified general functions
"""
# global
import copy
import pytest
# local
import ivy
import ivy.functional.backends.numpy
# Helpers #
# --------#
def _snai(n, idx, v):
if len(idx) == 1:
n[idx[0]] = v
else:
_snai(n[idx[0]], idx[1:], v)
def _mnai(n, idx, fn):
if len(idx) == 1:
n[idx[0]] = fn(n[idx[0]])
else:
_mnai(n[idx[0]], idx[1:], fn)
# Tests #
# ------#
# index_nest
@pytest.mark.parametrize(
"nest", [{"a": [[0], [1]], "b": {"c": (((2,), (4,)), ((6,), (8,)))}}]
)
@pytest.mark.parametrize(
"index", [("a", 0, 0), ("a", 1, 0), ("b", "c", 0), ("b", "c", 1, 0)]
)
def test_index_nest(nest, index, device, call):
ret = ivy.index_nest(nest, index)
true_ret = nest
for i in index:
true_ret = true_ret[i]
assert ret == true_ret
# set_nest_at_index
@pytest.mark.parametrize(
"nest", [{"a": [[0], [1]], "b": {"c": [[[2], [4]], [[6], [8]]]}}]
)
@pytest.mark.parametrize(
"index", [("a", 0, 0), ("a", 1, 0), ("b", "c", 0), ("b", "c", 1, 0)]
)
@pytest.mark.parametrize("value", [1])
def test_set_nest_at_index(nest, index, value, device, call):
nest_copy = copy.deepcopy(nest)
ivy.set_nest_at_index(nest, index, value)
_snai(nest_copy, index, value)
assert nest == nest_copy
# map_nest_at_index
@pytest.mark.parametrize(
"nest", [{"a": [[0], [1]], "b": {"c": [[[2], [4]], [[6], [8]]]}}]
)
@pytest.mark.parametrize(
"index", [("a", 0, 0), ("a", 1, 0), ("b", "c", 0, 0, 0), ("b", "c", 1, 0, 0)]
)
@pytest.mark.parametrize("fn", [lambda x: x + 2, lambda x: x**2])
def test_map_nest_at_index(nest, index, fn, device, call):
nest_copy = copy.deepcopy(nest)
ivy.map_nest_at_index(nest, index, fn)
_mnai(nest_copy, index, fn)
assert nest == nest_copy
# multi_index_nest
@pytest.mark.parametrize(
"nest", [{"a": [[0], [1]], "b": {"c": (((2,), (4,)), ((6,), (8,)))}}]
)
@pytest.mark.parametrize(
"multi_indices", [(("a", 0, 0), ("a", 1, 0)), (("b", "c", 0), ("b", "c", 1, 0))]
)
def test_multi_index_nest(nest, multi_indices, device, call):
rets = ivy.multi_index_nest(nest, multi_indices)
true_rets = list()
for indices in multi_indices:
true_ret = nest
for i in indices:
true_ret = true_ret[i]
true_rets.append(true_ret)
assert rets == true_rets
# set_nest_at_indices
@pytest.mark.parametrize(
"nest", [{"a": [[0], [1]], "b": {"c": [[[2], [4]], [[6], [8]]]}}]
)
@pytest.mark.parametrize(
"indices", [(("a", 0, 0), ("a", 1, 0)), (("b", "c", 0), ("b", "c", 1, 0))]
)
@pytest.mark.parametrize("values", [(1, 2)])
def test_set_nest_at_indices(nest, indices, values, device, call):
nest_copy = copy.deepcopy(nest)
ivy.set_nest_at_indices(nest, indices, values)
def snais(n, idxs, vs):
[_snai(n, index, value) for index, value in zip(idxs, vs)]
snais(nest_copy, indices, values)
assert nest == nest_copy
# map_nest_at_indices
@pytest.mark.parametrize(
"nest", [{"a": [[0], [1]], "b": {"c": [[[2], [4]], [[6], [8]]]}}]
)
@pytest.mark.parametrize(
"indices", [(("a", 0, 0), ("a", 1, 0)), (("b", "c", 0, 0, 0), ("b", "c", 1, 0, 0))]
)
@pytest.mark.parametrize("fn", [lambda x: x + 2, lambda x: x**2])
def test_map_nest_at_indices(nest, indices, fn, device, call):
nest_copy = copy.deepcopy(nest)
ivy.map_nest_at_indices(nest, indices, fn)
def mnais(n, idxs, vs):
[_mnai(n, index, fn) for index in idxs]
mnais(nest_copy, indices, fn)
assert nest == nest_copy
# nested_indices_where
@pytest.mark.parametrize(
"nest", [{"a": [[0], [1]], "b": {"c": [[[2], [4]], [[6], [8]]]}}]
)
def test_nested_indices_where(nest, device, call):
indices = ivy.nested_indices_where(nest, lambda x: x < 5)
assert indices[0] == ["a", 0, 0]
assert indices[1] == ["a", 1, 0]
assert indices[2] == ["b", "c", 0, 0, 0]
assert indices[3] == ["b", "c", 0, 1, 0]
# nested_indices_where_w_nest_checks
@pytest.mark.parametrize(
"nest", [{"a": [[0], [1]], "b": {"c": [[[2], [4]], [[6], [8]]]}}]
)
def test_nested_indices_where_w_nest_checks(nest, device, call):
indices = ivy.nested_indices_where(
nest, lambda x: isinstance(x, list) or (isinstance(x, int) and x < 5), True
)
assert indices[0] == ["a", 0, 0]
assert indices[1] == ["a", 0]
assert indices[2] == ["a", 1, 0]
assert indices[3] == ["a", 1]
assert indices[4] == ["a"]
assert indices[5] == ["b", "c", 0, 0, 0]
assert indices[6] == ["b", "c", 0, 0]
assert indices[7] == ["b", "c", 0, 1, 0]
assert indices[8] == ["b", "c", 0, 1]
assert indices[9] == ["b", "c", 0]
assert indices[10] == ["b", "c", 1, 0]
assert indices[11] == ["b", "c", 1, 1]
assert indices[12] == ["b", "c", 1]
assert indices[13] == ["b", "c"]
# all_nested_indices
@pytest.mark.parametrize(
"nest", [{"a": [[0], [1]], "b": {"c": [[[2], [4]], [[6], [8]]]}}]
)
def test_all_nested_indices(nest, device, call):
indices = ivy.all_nested_indices(nest)
assert indices[0] == ["a", 0, 0]
assert indices[1] == ["a", 1, 0]
assert indices[2] == ["b", "c", 0, 0, 0]
assert indices[3] == ["b", "c", 0, 1, 0]
assert indices[4] == ["b", "c", 1, 0, 0]
assert indices[5] == ["b", "c", 1, 1, 0]
# all_nested_indices_w_nest_checks
@pytest.mark.parametrize(
"nest", [{"a": [[0], [1]], "b": {"c": [[[2], [4]], [[6], [8]]]}}]
)
def test_all_nested_indices_w_nest_checks(nest, device, call):
indices = ivy.all_nested_indices(nest, True)
assert indices[0] == ["a", 0, 0]
assert indices[1] == ["a", 0]
assert indices[2] == ["a", 1, 0]
assert indices[3] == ["a", 1]
assert indices[4] == ["a"]
assert indices[5] == ["b", "c", 0, 0, 0]
assert indices[6] == ["b", "c", 0, 0]
assert indices[7] == ["b", "c", 0, 1, 0]
assert indices[8] == ["b", "c", 0, 1]
assert indices[9] == ["b", "c", 0]
assert indices[10] == ["b", "c", 1, 0, 0]
assert indices[11] == ["b", "c", 1, 0]
assert indices[12] == ["b", "c", 1, 1, 0]
assert indices[13] == ["b", "c", 1, 1]
assert indices[14] == ["b", "c", 1]
assert indices[15] == ["b", "c"]
assert indices[16] == ["b"]
# copy_nest
def test_copy_nest(device, call):
nest = {
"a": [ivy.array([0]), ivy.array([1])],
"b": {"c": [ivy.array([[2], [4]]), ivy.array([[6], [8]])]},
}
nest_copy = ivy.copy_nest(nest)
# copied nests
assert nest["a"] is not nest_copy["a"]
assert nest["b"] is not nest_copy["b"]
assert nest["b"]["c"] is not nest_copy["b"]["c"]
# non-copied arrays
assert nest["a"][0] is nest_copy["a"][0]
assert nest["a"][1] is nest_copy["a"][1]
assert nest["b"]["c"][0] is nest_copy["b"]["c"][0]
assert nest["b"]["c"][1] is nest_copy["b"]["c"][1]
| 29.396552 | 87 | 0.532111 |
import copy
import pytest
import ivy
import ivy.functional.backends.numpy
def _snai(n, idx, v):
if len(idx) == 1:
n[idx[0]] = v
else:
_snai(n[idx[0]], idx[1:], v)
def _mnai(n, idx, fn):
if len(idx) == 1:
n[idx[0]] = fn(n[idx[0]])
else:
_mnai(n[idx[0]], idx[1:], fn)
@pytest.mark.parametrize(
"nest", [{"a": [[0], [1]], "b": {"c": (((2,), (4,)), ((6,), (8,)))}}]
)
@pytest.mark.parametrize(
"index", [("a", 0, 0), ("a", 1, 0), ("b", "c", 0), ("b", "c", 1, 0)]
)
def test_index_nest(nest, index, device, call):
ret = ivy.index_nest(nest, index)
true_ret = nest
for i in index:
true_ret = true_ret[i]
assert ret == true_ret
@pytest.mark.parametrize(
"nest", [{"a": [[0], [1]], "b": {"c": [[[2], [4]], [[6], [8]]]}}]
)
@pytest.mark.parametrize(
"index", [("a", 0, 0), ("a", 1, 0), ("b", "c", 0), ("b", "c", 1, 0)]
)
@pytest.mark.parametrize("value", [1])
def test_set_nest_at_index(nest, index, value, device, call):
nest_copy = copy.deepcopy(nest)
ivy.set_nest_at_index(nest, index, value)
_snai(nest_copy, index, value)
assert nest == nest_copy
@pytest.mark.parametrize(
"nest", [{"a": [[0], [1]], "b": {"c": [[[2], [4]], [[6], [8]]]}}]
)
@pytest.mark.parametrize(
"index", [("a", 0, 0), ("a", 1, 0), ("b", "c", 0, 0, 0), ("b", "c", 1, 0, 0)]
)
@pytest.mark.parametrize("fn", [lambda x: x + 2, lambda x: x**2])
def test_map_nest_at_index(nest, index, fn, device, call):
nest_copy = copy.deepcopy(nest)
ivy.map_nest_at_index(nest, index, fn)
_mnai(nest_copy, index, fn)
assert nest == nest_copy
@pytest.mark.parametrize(
"nest", [{"a": [[0], [1]], "b": {"c": (((2,), (4,)), ((6,), (8,)))}}]
)
@pytest.mark.parametrize(
"multi_indices", [(("a", 0, 0), ("a", 1, 0)), (("b", "c", 0), ("b", "c", 1, 0))]
)
def test_multi_index_nest(nest, multi_indices, device, call):
rets = ivy.multi_index_nest(nest, multi_indices)
true_rets = list()
for indices in multi_indices:
true_ret = nest
for i in indices:
true_ret = true_ret[i]
true_rets.append(true_ret)
assert rets == true_rets
@pytest.mark.parametrize(
"nest", [{"a": [[0], [1]], "b": {"c": [[[2], [4]], [[6], [8]]]}}]
)
@pytest.mark.parametrize(
"indices", [(("a", 0, 0), ("a", 1, 0)), (("b", "c", 0), ("b", "c", 1, 0))]
)
@pytest.mark.parametrize("values", [(1, 2)])
def test_set_nest_at_indices(nest, indices, values, device, call):
nest_copy = copy.deepcopy(nest)
ivy.set_nest_at_indices(nest, indices, values)
def snais(n, idxs, vs):
[_snai(n, index, value) for index, value in zip(idxs, vs)]
snais(nest_copy, indices, values)
assert nest == nest_copy
@pytest.mark.parametrize(
"nest", [{"a": [[0], [1]], "b": {"c": [[[2], [4]], [[6], [8]]]}}]
)
@pytest.mark.parametrize(
"indices", [(("a", 0, 0), ("a", 1, 0)), (("b", "c", 0, 0, 0), ("b", "c", 1, 0, 0))]
)
@pytest.mark.parametrize("fn", [lambda x: x + 2, lambda x: x**2])
def test_map_nest_at_indices(nest, indices, fn, device, call):
nest_copy = copy.deepcopy(nest)
ivy.map_nest_at_indices(nest, indices, fn)
def mnais(n, idxs, vs):
[_mnai(n, index, fn) for index in idxs]
mnais(nest_copy, indices, fn)
assert nest == nest_copy
@pytest.mark.parametrize(
"nest", [{"a": [[0], [1]], "b": {"c": [[[2], [4]], [[6], [8]]]}}]
)
def test_nested_indices_where(nest, device, call):
indices = ivy.nested_indices_where(nest, lambda x: x < 5)
assert indices[0] == ["a", 0, 0]
assert indices[1] == ["a", 1, 0]
assert indices[2] == ["b", "c", 0, 0, 0]
assert indices[3] == ["b", "c", 0, 1, 0]
@pytest.mark.parametrize(
"nest", [{"a": [[0], [1]], "b": {"c": [[[2], [4]], [[6], [8]]]}}]
)
def test_nested_indices_where_w_nest_checks(nest, device, call):
indices = ivy.nested_indices_where(
nest, lambda x: isinstance(x, list) or (isinstance(x, int) and x < 5), True
)
assert indices[0] == ["a", 0, 0]
assert indices[1] == ["a", 0]
assert indices[2] == ["a", 1, 0]
assert indices[3] == ["a", 1]
assert indices[4] == ["a"]
assert indices[5] == ["b", "c", 0, 0, 0]
assert indices[6] == ["b", "c", 0, 0]
assert indices[7] == ["b", "c", 0, 1, 0]
assert indices[8] == ["b", "c", 0, 1]
assert indices[9] == ["b", "c", 0]
assert indices[10] == ["b", "c", 1, 0]
assert indices[11] == ["b", "c", 1, 1]
assert indices[12] == ["b", "c", 1]
assert indices[13] == ["b", "c"]
@pytest.mark.parametrize(
"nest", [{"a": [[0], [1]], "b": {"c": [[[2], [4]], [[6], [8]]]}}]
)
def test_all_nested_indices(nest, device, call):
indices = ivy.all_nested_indices(nest)
assert indices[0] == ["a", 0, 0]
assert indices[1] == ["a", 1, 0]
assert indices[2] == ["b", "c", 0, 0, 0]
assert indices[3] == ["b", "c", 0, 1, 0]
assert indices[4] == ["b", "c", 1, 0, 0]
assert indices[5] == ["b", "c", 1, 1, 0]
@pytest.mark.parametrize(
"nest", [{"a": [[0], [1]], "b": {"c": [[[2], [4]], [[6], [8]]]}}]
)
def test_all_nested_indices_w_nest_checks(nest, device, call):
indices = ivy.all_nested_indices(nest, True)
assert indices[0] == ["a", 0, 0]
assert indices[1] == ["a", 0]
assert indices[2] == ["a", 1, 0]
assert indices[3] == ["a", 1]
assert indices[4] == ["a"]
assert indices[5] == ["b", "c", 0, 0, 0]
assert indices[6] == ["b", "c", 0, 0]
assert indices[7] == ["b", "c", 0, 1, 0]
assert indices[8] == ["b", "c", 0, 1]
assert indices[9] == ["b", "c", 0]
assert indices[10] == ["b", "c", 1, 0, 0]
assert indices[11] == ["b", "c", 1, 0]
assert indices[12] == ["b", "c", 1, 1, 0]
assert indices[13] == ["b", "c", 1, 1]
assert indices[14] == ["b", "c", 1]
assert indices[15] == ["b", "c"]
assert indices[16] == ["b"]
def test_copy_nest(device, call):
nest = {
"a": [ivy.array([0]), ivy.array([1])],
"b": {"c": [ivy.array([[2], [4]]), ivy.array([[6], [8]])]},
}
nest_copy = ivy.copy_nest(nest)
assert nest["a"] is not nest_copy["a"]
assert nest["b"] is not nest_copy["b"]
assert nest["b"]["c"] is not nest_copy["b"]["c"]
assert nest["a"][0] is nest_copy["a"][0]
assert nest["a"][1] is nest_copy["a"][1]
assert nest["b"]["c"][0] is nest_copy["b"]["c"][0]
assert nest["b"]["c"][1] is nest_copy["b"]["c"][1]
| true | true |
f72b6e15d5c16951ab125cba7909154559f185ff | 1,850 | py | Python | app/i18n.py | CircuitsBots/discord-i18n | a0832a464566850eeda9bb386d7528d2d63a8fd8 | [
"MIT"
] | 1 | 2021-05-24T15:37:55.000Z | 2021-05-24T15:37:55.000Z | app/i18n.py | CircuitsBots/discord-i18n | a0832a464566850eeda9bb386d7528d2d63a8fd8 | [
"MIT"
] | 1 | 2021-05-26T12:47:11.000Z | 2021-05-26T13:31:31.000Z | app/i18n.py | CircuitsBots/discord-i18n | a0832a464566850eeda9bb386d7528d2d63a8fd8 | [
"MIT"
] | null | null | null | import contextvars
import gettext
import os.path
from glob import glob
from app.t_string import TString
BASE_DIR = ""
LOCALE_DEFAULT = "en_US"
LOCALE_DIR = "locale"
locales = frozenset(
map(
os.path.basename,
filter(os.path.isdir, glob(os.path.join(BASE_DIR, LOCALE_DIR, "*"))),
)
)
gettext_translations = {
locale: gettext.translation(
"bot",
languages=(locale,),
localedir=os.path.join(BASE_DIR, LOCALE_DIR),
)
for locale in locales
}
gettext_translations["en_US"] = gettext.NullTranslations()
locales |= {"en_US"}
def use_current_gettext(*args, **kwargs) -> str:
"""Translate a string using the proper gettext based
on the current_locale context var.
:return: The gettext for the current locale
:rtype: str
"""
if not gettext_translations:
return gettext.gettext(*args, **kwargs)
locale = current_locale.get()
return gettext_translations.get(
locale, gettext_translations[LOCALE_DEFAULT]
).gettext(*args, **kwargs)
def translate(string: str) -> str:
"""Translates text.
:param string: The text that needs translation
:type string: str
:return: The translated text
:rtype: str
"""
tstring = TString(string, use_current_gettext)
return str(tstring) # translate immediatly
def lazy_translate(string: str) -> TString:
"""Lazy translates text.
:param string: The text that needs translation
:type string: str
:return: The TString object that can be translated later
:rtype: TString
"""
tstring = TString(string, use_current_gettext)
return tstring
current_locale: contextvars.ContextVar = contextvars.ContextVar("i18n")
def set_current_locale():
"""Sets the locale to the LOCALE_DEFAULT."""
current_locale.set(LOCALE_DEFAULT)
set_current_locale()
| 23.125 | 77 | 0.687027 | import contextvars
import gettext
import os.path
from glob import glob
from app.t_string import TString
BASE_DIR = ""
LOCALE_DEFAULT = "en_US"
LOCALE_DIR = "locale"
locales = frozenset(
map(
os.path.basename,
filter(os.path.isdir, glob(os.path.join(BASE_DIR, LOCALE_DIR, "*"))),
)
)
gettext_translations = {
locale: gettext.translation(
"bot",
languages=(locale,),
localedir=os.path.join(BASE_DIR, LOCALE_DIR),
)
for locale in locales
}
gettext_translations["en_US"] = gettext.NullTranslations()
locales |= {"en_US"}
def use_current_gettext(*args, **kwargs) -> str:
if not gettext_translations:
return gettext.gettext(*args, **kwargs)
locale = current_locale.get()
return gettext_translations.get(
locale, gettext_translations[LOCALE_DEFAULT]
).gettext(*args, **kwargs)
def translate(string: str) -> str:
tstring = TString(string, use_current_gettext)
return str(tstring)
def lazy_translate(string: str) -> TString:
tstring = TString(string, use_current_gettext)
return tstring
current_locale: contextvars.ContextVar = contextvars.ContextVar("i18n")
def set_current_locale():
current_locale.set(LOCALE_DEFAULT)
set_current_locale()
| true | true |
f72b6e7d0faa806aa74633ee75bd77534ef86dea | 4,079 | py | Python | Saniti/main.py | ChamRoshi/Saniti | ddff09e60df1a2046e79e4356f07573f30210f22 | [
"Apache-2.0"
] | null | null | null | Saniti/main.py | ChamRoshi/Saniti | ddff09e60df1a2046e79e4356f07573f30210f22 | [
"Apache-2.0"
] | null | null | null | Saniti/main.py | ChamRoshi/Saniti | ddff09e60df1a2046e79e4356f07573f30210f22 | [
"Apache-2.0"
] | null | null | null | # import nltk
# import gensim
# import pandas
import string
from nltk.corpus import stopwords
from nltk import word_tokenize
from nltk import WordNetLemmatizer
from nltk import pos_tag
from nltk.stem import PorterStemmer
from gensim.models.doc2vec import TaggedDocument
from gensim.corpora import Dictionary
from gensim.models.phrases import Phrases, Phraser
"""
TODO
stemming - DONE
lemmatizing - DONE
pos filter
tfidf splitter
w2v theme relevence
w2v weightings
frequency filtering (found more than twice)
RESEARCH
kwargumenrts - ad hoc arguments for theme relevence
"""
class saniti:
def __init__(self, text = [], pipeline = [], **kwargs):
#setup
self.processes = {"token": self.token,
"depunct": self.depunct,
"unempty": self.unempty,
"out_tag_doc": self.out_tag_doc,
"out_corp_dict": self.out_corp_dic,
"lemma": self.lemma,
"destop": self.destop,
"posfilter": self.posfilter,
"phrase": self.phrase_gen,
"stem": self.stem}
self.pipeline = pipeline
self.original_text = text
if text != []:
self.text = self.process(text, self.pipeline, **kwargs)
def process(self, text, pipeline, **kwargs):
self.text = text
for line in pipeline:
text = self.processes[line](text, **kwargs)
return text
def destop(self, text, **kwargs):
text = [[word for word in doc if word not in stopwords.words("english")] for doc in text]
return text
def token(self, text, **kwargs):
if "tokenizer" in kwargs:
tokenizer = kwargs["tokenizer"]
else:
tokenizer = word_tokenize
text = [tokenizer(x) for x in text]
return text
def depunct(self, text, **kwargs):
if "puct" in kwargs:
punct = kwargs["punct"]
else:
punct = string.punctuation
punct = str.maketrans("", "", punct)
text = [[s.translate(punct) for s in doc] for doc in text]
return text
def unempty(self, text, **kwargs):
text = [[s for s in doc if s != ""] for doc in text]
return text
def lemma(self, text, **kwargs):
if "lemmatizer" in kwargs:
lemmatizer = kwargs["lemmatizer"]
else:
lemmatizer = WordNetLemmatizer()
text = [[lemmatizer.lemmatize(w) for w in doc] for doc in text]
return text
def phrase_gen(self, text, **kwargs):
if "common_terms" in kwargs:
common_terms = kwargs["common_terms"]
else:
common_terms = stopwords.words("english")
# print(list(common_terms))
phrases = Phrases(text, common_terms=common_terms)
phraser = Phraser(phrases)
text = [phraser[x] for x in text]
return text
def stem(self, text, **kwargs):
if "stemmer" in kwargs:
stemmer = kwargs["stemmer"]
else:
stemmer = PorterStemmer()
text = [[stemmer.stem(word) for word in doc] for doc in text]
return text
def posfilter(self, text, **kwargs):
if "pos_tagger" not in kwargs:
pos_tagger = pos_tag
else:
pos_tagger = kwargs["pos_tagger"]
if "pos_only" not in kwargs:
pos_only = ["NN", "VB"]
else:
pos_only = kwargs["pos_only"]
print(text)
text = [[word[0] for word in pos_tagger(doc) if word[1] in pos_only] if doc != [] else doc for doc in text]
return text
def out_corp_dic(self, text, **kwargs):
dictionary = Dictionary(text)
corpus = [dictionary.doc2bow(doc) for doc in text]
return {"dictionary": dictionary, "corpus": corpus}
def out_tag_doc(self, text, **kwargs):
if "tags" in kwargs:
tags = kwargs["tags"]
else:
tags = []
if tags == []:
if self.original_text != []:
tags = self.original_text
else :
tags = [" ".join(doc) for doc in text]
list2 = []
for xt, xid in zip(text, tags):
try:
td = TaggedDocument(xt, [xid])
list2.append(td)
except:
print(f"disambig {x}")
return(list2)
if __name__ == "__main__":
original_text = ["I like to moves it, move its", "I likeing to move it!", "the of"]
text = saniti(original_text, ["token", "destop", "depunct", "unempty", "phrase"])
print(text.text)
sani1 = saniti()
text = sani1.process(original_text, ["token", "destop", "depunct", "unempty", "lemma", "out_tag_doc"])
print(text)
| 21.356021 | 109 | 0.664379 |
import string
from nltk.corpus import stopwords
from nltk import word_tokenize
from nltk import WordNetLemmatizer
from nltk import pos_tag
from nltk.stem import PorterStemmer
from gensim.models.doc2vec import TaggedDocument
from gensim.corpora import Dictionary
from gensim.models.phrases import Phrases, Phraser
class saniti:
def __init__(self, text = [], pipeline = [], **kwargs):
self.processes = {"token": self.token,
"depunct": self.depunct,
"unempty": self.unempty,
"out_tag_doc": self.out_tag_doc,
"out_corp_dict": self.out_corp_dic,
"lemma": self.lemma,
"destop": self.destop,
"posfilter": self.posfilter,
"phrase": self.phrase_gen,
"stem": self.stem}
self.pipeline = pipeline
self.original_text = text
if text != []:
self.text = self.process(text, self.pipeline, **kwargs)
def process(self, text, pipeline, **kwargs):
self.text = text
for line in pipeline:
text = self.processes[line](text, **kwargs)
return text
def destop(self, text, **kwargs):
text = [[word for word in doc if word not in stopwords.words("english")] for doc in text]
return text
def token(self, text, **kwargs):
if "tokenizer" in kwargs:
tokenizer = kwargs["tokenizer"]
else:
tokenizer = word_tokenize
text = [tokenizer(x) for x in text]
return text
def depunct(self, text, **kwargs):
if "puct" in kwargs:
punct = kwargs["punct"]
else:
punct = string.punctuation
punct = str.maketrans("", "", punct)
text = [[s.translate(punct) for s in doc] for doc in text]
return text
def unempty(self, text, **kwargs):
text = [[s for s in doc if s != ""] for doc in text]
return text
def lemma(self, text, **kwargs):
if "lemmatizer" in kwargs:
lemmatizer = kwargs["lemmatizer"]
else:
lemmatizer = WordNetLemmatizer()
text = [[lemmatizer.lemmatize(w) for w in doc] for doc in text]
return text
def phrase_gen(self, text, **kwargs):
if "common_terms" in kwargs:
common_terms = kwargs["common_terms"]
else:
common_terms = stopwords.words("english")
phrases = Phrases(text, common_terms=common_terms)
phraser = Phraser(phrases)
text = [phraser[x] for x in text]
return text
def stem(self, text, **kwargs):
if "stemmer" in kwargs:
stemmer = kwargs["stemmer"]
else:
stemmer = PorterStemmer()
text = [[stemmer.stem(word) for word in doc] for doc in text]
return text
def posfilter(self, text, **kwargs):
if "pos_tagger" not in kwargs:
pos_tagger = pos_tag
else:
pos_tagger = kwargs["pos_tagger"]
if "pos_only" not in kwargs:
pos_only = ["NN", "VB"]
else:
pos_only = kwargs["pos_only"]
print(text)
text = [[word[0] for word in pos_tagger(doc) if word[1] in pos_only] if doc != [] else doc for doc in text]
return text
def out_corp_dic(self, text, **kwargs):
dictionary = Dictionary(text)
corpus = [dictionary.doc2bow(doc) for doc in text]
return {"dictionary": dictionary, "corpus": corpus}
def out_tag_doc(self, text, **kwargs):
if "tags" in kwargs:
tags = kwargs["tags"]
else:
tags = []
if tags == []:
if self.original_text != []:
tags = self.original_text
else :
tags = [" ".join(doc) for doc in text]
list2 = []
for xt, xid in zip(text, tags):
try:
td = TaggedDocument(xt, [xid])
list2.append(td)
except:
print(f"disambig {x}")
return(list2)
if __name__ == "__main__":
original_text = ["I like to moves it, move its", "I likeing to move it!", "the of"]
text = saniti(original_text, ["token", "destop", "depunct", "unempty", "phrase"])
print(text.text)
sani1 = saniti()
text = sani1.process(original_text, ["token", "destop", "depunct", "unempty", "lemma", "out_tag_doc"])
print(text)
| true | true |
f72b6ec0218d668349c89e6dabbf4bb56ed17158 | 3,294 | py | Python | pytest/testFragmentedBackup.py | RomanValov/ArmoryDB | 625eff9712161676ad83deb03616e6edb48283ca | [
"MIT"
] | 505 | 2016-02-04T15:54:46.000Z | 2022-03-27T18:43:01.000Z | pytest/testFragmentedBackup.py | jimmysong/BitcoinArmory | 1c7190176897a2e0f3e4e198ab2f199059bb2402 | [
"MIT"
] | 528 | 2016-02-06T19:50:12.000Z | 2022-01-15T10:21:16.000Z | pytest/testFragmentedBackup.py | jimmysong/BitcoinArmory | 1c7190176897a2e0f3e4e198ab2f199059bb2402 | [
"MIT"
] | 208 | 2015-01-02T10:31:40.000Z | 2021-12-14T07:37:36.000Z | ################################################################################
# #
# Copyright (C) 2011-2014, Armory Technologies, Inc. #
# Distributed under the GNU Affero General Public License (AGPL v3) #
# See LICENSE or http://www.gnu.org/licenses/agpl.html #
# #
################################################################################
import sys
sys.path.append('..')
from pytest.Tiab import TiabTest
from armoryengine.ArmoryUtils import SplitSecret, binary_to_hex, ReconstructSecret,\
FiniteFieldError
import itertools
import unittest
SECRET = '\x00\x01\x02\x03\x04\x05\x06\x07'
BAD_SECRET = '\xff\xff\xff\xff\xff\xff\xff\xff'
# Fragment combination to String abreviated name for debugging purposes
def c2s(combinationMap):
return '\n'.join([' '.join([str(k), binary_to_hex(v[0]), binary_to_hex(v[1])]) \
for k,v in combinationMap.iteritems()])
def splitSecretToFragmentMap(splitSecret):
fragMap = {}
for i,frag in enumerate(splitSecret):
fragMap[i] = frag
return fragMap
class Test(TiabTest):
def setUp(self):
pass
def tearDown(self):
pass
def getNextCombination(self, fragmentMap, m):
combinationIterator = itertools.combinations(fragmentMap.iterkeys(), m)
for keyList in combinationIterator:
combinationMap = {}
for key in keyList:
combinationMap[key] = fragmentMap[key]
yield combinationMap
def subtestAllFragmentedBackups(self, secret, m, n):
fragmentMap = splitSecretToFragmentMap(SplitSecret(secret, m, n))
for combinationMap in self.getNextCombination(fragmentMap, m):
fragmentList = [value for value in combinationMap.itervalues()]
reconSecret = ReconstructSecret(fragmentList, m, len(secret))
self.assertEqual(reconSecret, secret)
def testFragmentedBackup(self):
self.subtestAllFragmentedBackups(SECRET, 2, 3)
self.subtestAllFragmentedBackups(SECRET, 2, 3)
self.subtestAllFragmentedBackups(SECRET, 3, 4)
self.subtestAllFragmentedBackups(SECRET, 5, 7)
self.subtestAllFragmentedBackups(SECRET, 8, 8)
self.subtestAllFragmentedBackups(SECRET, 2, 12)
# Secret Too big test
self.assertRaises(FiniteFieldError, SplitSecret, BAD_SECRET, 2,3)
# More needed than pieces
self.assertRaises(FiniteFieldError, SplitSecret, SECRET, 4,3)
# Secret Too many needed needed
self.assertRaises(FiniteFieldError, SplitSecret, SECRET, 9, 12)
# Too few pieces needed
self.assertRaises(FiniteFieldError, SplitSecret, SECRET, 1, 12)
# Test Reconstuction failures
fragmentList = SplitSecret(SECRET, 3, 5)
reconSecret = ReconstructSecret(fragmentList[:2], 2, len(SECRET))
self.assertNotEqual(reconSecret, SECRET)
# Running tests with "python <module name>" will NOT work for any Armory tests
# You must run tests with "python -m unittest <module name>" or run all tests with "python -m unittest discover"
# if __name__ == "__main__":
# unittest.main() | 37.862069 | 112 | 0.61779 | true | true | |
f72b6ff661d13354a6eeda99808229daf19f9eb3 | 988 | py | Python | tools/leetcode.223.Rectangle Area/leetcode.223.Rectangle Area.submission3.py | tedye/leetcode | 975d7e3b8cb9b6be9e80e07febf4bcf6414acd46 | [
"MIT"
] | 4 | 2015-10-10T00:30:55.000Z | 2020-07-27T19:45:54.000Z | tools/leetcode.223.Rectangle Area/leetcode.223.Rectangle Area.submission3.py | tedye/leetcode | 975d7e3b8cb9b6be9e80e07febf4bcf6414acd46 | [
"MIT"
] | null | null | null | tools/leetcode.223.Rectangle Area/leetcode.223.Rectangle Area.submission3.py | tedye/leetcode | 975d7e3b8cb9b6be9e80e07febf4bcf6414acd46 | [
"MIT"
] | null | null | null | class Solution:
# @param {integer} A
# @param {integer} B
# @param {integer} C
# @param {integer} D
# @param {integer} E
# @param {integer} F
# @param {integer} G
# @param {integer} H
# @return {integer}
def computeArea(self, A, B, C, D, E, F, G, H):
# calculate the separate areas
w1 = C - A
h1 = D - B
w2 = G - E
h2 = H - F
A1 = w1*h1
A2 = w2*h2
if A1 == 0:
return A2
if A2 == 0:
return A1
# calculate the intersected area
wi = 0
if A <= E:
if E-A < w1:
wi = min(A+w1 - E,w2)
else:
if A - E < w2:
wi = min(E+w2 - A,w1)
hi = 0
if F <= B:
if B - F< h2:
hi = min(F + h2 - B,h1)
else:
if F - B < h1:
hi = min(B + h1 - F,h2)
A3 = wi * hi
return A1+A2-A3
| 988 | 988 | 0.374494 | class Solution:
| true | true |
f72b707bda389dc12a15cc8354b94ca79cf61a68 | 9,096 | py | Python | mfem/_ser/symmat.py | GabrielJie/PyMFEM | fa654447ac6819c5aa0341397b91a299f4ce5492 | [
"BSD-3-Clause"
] | 1 | 2022-01-19T07:16:59.000Z | 2022-01-19T07:16:59.000Z | mfem/_ser/symmat.py | GabrielJie/PyMFEM | fa654447ac6819c5aa0341397b91a299f4ce5492 | [
"BSD-3-Clause"
] | null | null | null | mfem/_ser/symmat.py | GabrielJie/PyMFEM | fa654447ac6819c5aa0341397b91a299f4ce5492 | [
"BSD-3-Clause"
] | null | null | null | # This file was automatically generated by SWIG (http://www.swig.org).
# Version 4.0.2
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info < (2, 7, 0):
raise RuntimeError("Python 2.7 or later required")
# Import the low-level C/C++ module
if __package__ or "." in __name__:
from . import _symmat
else:
import _symmat
try:
import builtins as __builtin__
except ImportError:
import __builtin__
_swig_new_instance_method = _symmat.SWIG_PyInstanceMethod_New
_swig_new_static_method = _symmat.SWIG_PyStaticMethod_New
def _swig_repr(self):
try:
strthis = "proxy of " + self.this.__repr__()
except __builtin__.Exception:
strthis = ""
return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
def _swig_setattr_nondynamic_instance_variable(set):
def set_instance_attr(self, name, value):
if name == "thisown":
self.this.own(value)
elif name == "this":
set(self, name, value)
elif hasattr(self, name) and isinstance(getattr(type(self), name), property):
set(self, name, value)
else:
raise AttributeError("You cannot add instance attributes to %s" % self)
return set_instance_attr
def _swig_setattr_nondynamic_class_variable(set):
def set_class_attr(cls, name, value):
if hasattr(cls, name) and not isinstance(getattr(cls, name), property):
set(cls, name, value)
else:
raise AttributeError("You cannot add class attributes to %s" % cls)
return set_class_attr
def _swig_add_metaclass(metaclass):
"""Class decorator for adding a metaclass to a SWIG wrapped class - a slimmed down version of six.add_metaclass"""
def wrapper(cls):
return metaclass(cls.__name__, cls.__bases__, cls.__dict__.copy())
return wrapper
class _SwigNonDynamicMeta(type):
"""Meta class to enforce nondynamic attributes (no new attributes) for a class"""
__setattr__ = _swig_setattr_nondynamic_class_variable(type.__setattr__)
import weakref
import mfem._ser.globals
import mfem._ser.matrix
import mfem._ser.vector
import mfem._ser.array
import mfem._ser.mem_manager
import mfem._ser.operators
class DenseSymmetricMatrix(mfem._ser.matrix.Matrix):
r"""Proxy of C++ mfem::DenseSymmetricMatrix class."""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
__repr__ = _swig_repr
def __init__(self, *args):
r"""
__init__(DenseSymmetricMatrix self) -> DenseSymmetricMatrix
__init__(DenseSymmetricMatrix self, int s) -> DenseSymmetricMatrix
__init__(DenseSymmetricMatrix self, double * d, int s) -> DenseSymmetricMatrix
"""
_symmat.DenseSymmetricMatrix_swiginit(self, _symmat.new_DenseSymmetricMatrix(*args))
def UseExternalData(self, d, s):
r"""UseExternalData(DenseSymmetricMatrix self, double * d, int s)"""
return _symmat.DenseSymmetricMatrix_UseExternalData(self, d, s)
UseExternalData = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_UseExternalData)
def Reset(self, d, s):
r"""Reset(DenseSymmetricMatrix self, double * d, int s)"""
return _symmat.DenseSymmetricMatrix_Reset(self, d, s)
Reset = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_Reset)
def ClearExternalData(self):
r"""ClearExternalData(DenseSymmetricMatrix self)"""
return _symmat.DenseSymmetricMatrix_ClearExternalData(self)
ClearExternalData = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_ClearExternalData)
def Clear(self):
r"""Clear(DenseSymmetricMatrix self)"""
return _symmat.DenseSymmetricMatrix_Clear(self)
Clear = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_Clear)
def SetSize(self, s):
r"""SetSize(DenseSymmetricMatrix self, int s)"""
return _symmat.DenseSymmetricMatrix_SetSize(self, s)
SetSize = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_SetSize)
def Data(self):
r"""Data(DenseSymmetricMatrix self) -> double *"""
return _symmat.DenseSymmetricMatrix_Data(self)
Data = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_Data)
def GetData(self):
r"""GetData(DenseSymmetricMatrix self) -> double *"""
return _symmat.DenseSymmetricMatrix_GetData(self)
GetData = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_GetData)
def GetMemory(self, *args):
r"""
GetMemory(DenseSymmetricMatrix self) -> mfem::Memory< double >
GetMemory(DenseSymmetricMatrix self) -> mfem::Memory< double > const &
"""
return _symmat.DenseSymmetricMatrix_GetMemory(self, *args)
GetMemory = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_GetMemory)
def OwnsData(self):
r"""OwnsData(DenseSymmetricMatrix self) -> bool"""
return _symmat.DenseSymmetricMatrix_OwnsData(self)
OwnsData = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_OwnsData)
def __call__(self, *args):
r"""
__call__(DenseSymmetricMatrix self, int i, int j) -> double
__call__(DenseSymmetricMatrix self, int i, int j) -> double const &
"""
return _symmat.DenseSymmetricMatrix___call__(self, *args)
__call__ = _swig_new_instance_method(_symmat.DenseSymmetricMatrix___call__)
def Elem(self, *args):
r"""
Elem(DenseSymmetricMatrix self, int i, int j) -> double
Elem(DenseSymmetricMatrix self, int i, int j) -> double const &
"""
return _symmat.DenseSymmetricMatrix_Elem(self, *args)
Elem = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_Elem)
def __imul__(self, c):
r"""__imul__(DenseSymmetricMatrix self, double c) -> DenseSymmetricMatrix"""
return _symmat.DenseSymmetricMatrix___imul__(self, c)
__imul__ = _swig_new_instance_method(_symmat.DenseSymmetricMatrix___imul__)
def MemoryUsage(self):
r"""MemoryUsage(DenseSymmetricMatrix self) -> long"""
return _symmat.DenseSymmetricMatrix_MemoryUsage(self)
MemoryUsage = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_MemoryUsage)
def Read(self, on_dev=True):
r"""Read(DenseSymmetricMatrix self, bool on_dev=True) -> double const *"""
return _symmat.DenseSymmetricMatrix_Read(self, on_dev)
Read = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_Read)
def HostRead(self):
r"""HostRead(DenseSymmetricMatrix self) -> double const *"""
return _symmat.DenseSymmetricMatrix_HostRead(self)
HostRead = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_HostRead)
def Write(self, on_dev=True):
r"""Write(DenseSymmetricMatrix self, bool on_dev=True) -> double *"""
return _symmat.DenseSymmetricMatrix_Write(self, on_dev)
Write = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_Write)
def HostWrite(self):
r"""HostWrite(DenseSymmetricMatrix self) -> double *"""
return _symmat.DenseSymmetricMatrix_HostWrite(self)
HostWrite = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_HostWrite)
def ReadWrite(self, on_dev=True):
r"""ReadWrite(DenseSymmetricMatrix self, bool on_dev=True) -> double *"""
return _symmat.DenseSymmetricMatrix_ReadWrite(self, on_dev)
ReadWrite = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_ReadWrite)
def HostReadWrite(self):
r"""HostReadWrite(DenseSymmetricMatrix self) -> double *"""
return _symmat.DenseSymmetricMatrix_HostReadWrite(self)
HostReadWrite = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_HostReadWrite)
def Mult(self, x, y):
r"""Mult(DenseSymmetricMatrix self, Vector x, Vector y)"""
return _symmat.DenseSymmetricMatrix_Mult(self, x, y)
Mult = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_Mult)
def Inverse(self):
r"""Inverse(DenseSymmetricMatrix self) -> MatrixInverse"""
return _symmat.DenseSymmetricMatrix_Inverse(self)
Inverse = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_Inverse)
__swig_destroy__ = _symmat.delete_DenseSymmetricMatrix
def Print(self, *args):
r"""
Print(DenseSymmetricMatrix self, std::ostream & out=out, int width_=4)
Print(DenseSymmetricMatrix self, char const * file, int precision=16)
"""
return _symmat.DenseSymmetricMatrix_Print(self, *args)
Print = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_Print)
def PrintGZ(self, file, precision=16):
r"""PrintGZ(DenseSymmetricMatrix self, char const * file, int precision=16)"""
return _symmat.DenseSymmetricMatrix_PrintGZ(self, file, precision)
PrintGZ = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_PrintGZ)
# Register DenseSymmetricMatrix in _symmat:
_symmat.DenseSymmetricMatrix_swigregister(DenseSymmetricMatrix)
| 40.972973 | 118 | 0.726143 |
from sys import version_info as _swig_python_version_info
if _swig_python_version_info < (2, 7, 0):
raise RuntimeError("Python 2.7 or later required")
if __package__ or "." in __name__:
from . import _symmat
else:
import _symmat
try:
import builtins as __builtin__
except ImportError:
import __builtin__
_swig_new_instance_method = _symmat.SWIG_PyInstanceMethod_New
_swig_new_static_method = _symmat.SWIG_PyStaticMethod_New
def _swig_repr(self):
try:
strthis = "proxy of " + self.this.__repr__()
except __builtin__.Exception:
strthis = ""
return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
def _swig_setattr_nondynamic_instance_variable(set):
def set_instance_attr(self, name, value):
if name == "thisown":
self.this.own(value)
elif name == "this":
set(self, name, value)
elif hasattr(self, name) and isinstance(getattr(type(self), name), property):
set(self, name, value)
else:
raise AttributeError("You cannot add instance attributes to %s" % self)
return set_instance_attr
def _swig_setattr_nondynamic_class_variable(set):
def set_class_attr(cls, name, value):
if hasattr(cls, name) and not isinstance(getattr(cls, name), property):
set(cls, name, value)
else:
raise AttributeError("You cannot add class attributes to %s" % cls)
return set_class_attr
def _swig_add_metaclass(metaclass):
def wrapper(cls):
return metaclass(cls.__name__, cls.__bases__, cls.__dict__.copy())
return wrapper
class _SwigNonDynamicMeta(type):
__setattr__ = _swig_setattr_nondynamic_class_variable(type.__setattr__)
import weakref
import mfem._ser.globals
import mfem._ser.matrix
import mfem._ser.vector
import mfem._ser.array
import mfem._ser.mem_manager
import mfem._ser.operators
class DenseSymmetricMatrix(mfem._ser.matrix.Matrix):
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
__repr__ = _swig_repr
def __init__(self, *args):
_symmat.DenseSymmetricMatrix_swiginit(self, _symmat.new_DenseSymmetricMatrix(*args))
def UseExternalData(self, d, s):
return _symmat.DenseSymmetricMatrix_UseExternalData(self, d, s)
UseExternalData = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_UseExternalData)
def Reset(self, d, s):
return _symmat.DenseSymmetricMatrix_Reset(self, d, s)
Reset = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_Reset)
def ClearExternalData(self):
return _symmat.DenseSymmetricMatrix_ClearExternalData(self)
ClearExternalData = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_ClearExternalData)
def Clear(self):
return _symmat.DenseSymmetricMatrix_Clear(self)
Clear = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_Clear)
def SetSize(self, s):
return _symmat.DenseSymmetricMatrix_SetSize(self, s)
SetSize = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_SetSize)
def Data(self):
return _symmat.DenseSymmetricMatrix_Data(self)
Data = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_Data)
def GetData(self):
return _symmat.DenseSymmetricMatrix_GetData(self)
GetData = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_GetData)
def GetMemory(self, *args):
return _symmat.DenseSymmetricMatrix_GetMemory(self, *args)
GetMemory = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_GetMemory)
def OwnsData(self):
return _symmat.DenseSymmetricMatrix_OwnsData(self)
OwnsData = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_OwnsData)
def __call__(self, *args):
return _symmat.DenseSymmetricMatrix___call__(self, *args)
__call__ = _swig_new_instance_method(_symmat.DenseSymmetricMatrix___call__)
def Elem(self, *args):
return _symmat.DenseSymmetricMatrix_Elem(self, *args)
Elem = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_Elem)
def __imul__(self, c):
return _symmat.DenseSymmetricMatrix___imul__(self, c)
__imul__ = _swig_new_instance_method(_symmat.DenseSymmetricMatrix___imul__)
def MemoryUsage(self):
return _symmat.DenseSymmetricMatrix_MemoryUsage(self)
MemoryUsage = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_MemoryUsage)
def Read(self, on_dev=True):
return _symmat.DenseSymmetricMatrix_Read(self, on_dev)
Read = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_Read)
def HostRead(self):
return _symmat.DenseSymmetricMatrix_HostRead(self)
HostRead = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_HostRead)
def Write(self, on_dev=True):
return _symmat.DenseSymmetricMatrix_Write(self, on_dev)
Write = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_Write)
def HostWrite(self):
return _symmat.DenseSymmetricMatrix_HostWrite(self)
HostWrite = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_HostWrite)
def ReadWrite(self, on_dev=True):
return _symmat.DenseSymmetricMatrix_ReadWrite(self, on_dev)
ReadWrite = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_ReadWrite)
def HostReadWrite(self):
return _symmat.DenseSymmetricMatrix_HostReadWrite(self)
HostReadWrite = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_HostReadWrite)
def Mult(self, x, y):
return _symmat.DenseSymmetricMatrix_Mult(self, x, y)
Mult = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_Mult)
def Inverse(self):
return _symmat.DenseSymmetricMatrix_Inverse(self)
Inverse = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_Inverse)
__swig_destroy__ = _symmat.delete_DenseSymmetricMatrix
def Print(self, *args):
return _symmat.DenseSymmetricMatrix_Print(self, *args)
Print = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_Print)
def PrintGZ(self, file, precision=16):
return _symmat.DenseSymmetricMatrix_PrintGZ(self, file, precision)
PrintGZ = _swig_new_instance_method(_symmat.DenseSymmetricMatrix_PrintGZ)
_symmat.DenseSymmetricMatrix_swigregister(DenseSymmetricMatrix)
| true | true |
f72b70b8b138e4a1d4a8b2d5b7e35ce0046217f0 | 4,948 | py | Python | src/pretalx/schedule/utils.py | Hydro2shine/sprout | 7dfa5e9fa0a7ef9157517ad0752e393599053873 | [
"Apache-2.0"
] | null | null | null | src/pretalx/schedule/utils.py | Hydro2shine/sprout | 7dfa5e9fa0a7ef9157517ad0752e393599053873 | [
"Apache-2.0"
] | null | null | null | src/pretalx/schedule/utils.py | Hydro2shine/sprout | 7dfa5e9fa0a7ef9157517ad0752e393599053873 | [
"Apache-2.0"
] | null | null | null | from contextlib import suppress
from datetime import timedelta
from dateutil.parser import parse
from django.db import transaction
from django_scopes import scope
from pretalx.person.models import SpeakerProfile, User
from pretalx.schedule.models import Room, TalkSlot
from pretalx.submission.models import (
Submission, SubmissionStates, SubmissionType, Track,
)
def guess_schedule_version(event):
if not event.current_schedule:
return '0.1'
version = event.current_schedule.version
prefix = ''
for separator in [',', '.', '-', '_']:
if separator in version:
prefix, version = version.rsplit(separator, maxsplit=1)
break
if version.isdigit():
version = str(int(version) + 1)
return prefix + separator + version
return ''
@transaction.atomic()
def process_frab(root, event):
"""
Takes an xml document root and an event, and releases a schedule with the data from the xml document.
Called from the `import_schedule` manage command, at least.
"""
with scope(event=event):
for day in root.findall('day'):
for rm in day.findall('room'):
room, _ = Room.objects.get_or_create(event=event, name=rm.attrib['name'])
for talk in rm.findall('event'):
_create_talk(talk=talk, room=room, event=event)
schedule_version = root.find('version').text
try:
event.wip_schedule.freeze(schedule_version, notify_speakers=False)
schedule = event.schedules.get(version=schedule_version)
except Exception:
raise Exception(
f'Could not import "{event.name}" schedule version "{schedule_version}": failed creating schedule release.'
)
schedule.talks.update(is_visible=True)
start = schedule.talks.order_by('start').first().start
end = schedule.talks.order_by('-end').first().end
event.date_from = start.date()
event.date_to = end.date()
event.save()
return (
f'Successfully imported "{event.name}" schedule version "{schedule_version}".'
)
def _create_talk(*, talk, room, event):
date = talk.find('date').text
start = parse(date + ' ' + talk.find('start').text)
hours, minutes = talk.find('duration').text.split(':')
duration = timedelta(hours=int(hours), minutes=int(minutes))
duration_in_minutes = duration.total_seconds() / 60
try:
end = parse(date + ' ' + talk.find('end').text)
except AttributeError:
end = start + duration
sub_type = SubmissionType.objects.filter(
event=event, name=talk.find('type').text, default_duration=duration_in_minutes
).first()
if not sub_type:
sub_type = SubmissionType.objects.create(
name=talk.find('type').text or 'default',
event=event,
default_duration=duration_in_minutes,
)
track = Track.objects.filter(event=event, name=talk.find('track').text).first()
if not track:
track = Track.objects.create(
name=talk.find('track').text or 'default', event=event
)
optout = False
with suppress(AttributeError):
optout = talk.find('recording').find('optout').text == 'true'
code = None
if (
Submission.objects.filter(code__iexact=talk.attrib['id'], event=event).exists()
or not Submission.objects.filter(code__iexact=talk.attrib['id']).exists()
):
code = talk.attrib['id']
elif (
Submission.objects.filter(
code__iexact=talk.attrib['guid'][:16], event=event
).exists()
or not Submission.objects.filter(code__iexact=talk.attrib['guid'][:16]).exists()
):
code = talk.attrib['guid'][:16]
sub, _ = Submission.objects.get_or_create(
event=event, code=code, defaults={'submission_type': sub_type}
)
sub.submission_type = sub_type
sub.track = track
sub.title = talk.find('title').text
sub.description = talk.find('description').text
if talk.find('subtitle').text:
sub.description = talk.find('subtitle').text + '\n' + (sub.description or '')
sub.abstract = talk.find('abstract').text
sub.content_locale = talk.find('language').text or 'en'
sub.do_not_record = optout
sub.state = SubmissionStates.CONFIRMED
sub.save()
for person in talk.find('persons').findall('person'):
user = User.objects.filter(name=person.text[:60]).first()
if not user:
user = User(name=person.text, email=f'{person.text}@localhost')
user.save()
SpeakerProfile.objects.create(user=user, event=event)
sub.speakers.add(user)
slot, _ = TalkSlot.objects.get_or_create(
submission=sub, schedule=event.wip_schedule, is_visible=True
)
slot.room = room
slot.is_visible = True
slot.start = start
slot.end = end
slot.save()
| 34.84507 | 123 | 0.637833 | from contextlib import suppress
from datetime import timedelta
from dateutil.parser import parse
from django.db import transaction
from django_scopes import scope
from pretalx.person.models import SpeakerProfile, User
from pretalx.schedule.models import Room, TalkSlot
from pretalx.submission.models import (
Submission, SubmissionStates, SubmissionType, Track,
)
def guess_schedule_version(event):
if not event.current_schedule:
return '0.1'
version = event.current_schedule.version
prefix = ''
for separator in [',', '.', '-', '_']:
if separator in version:
prefix, version = version.rsplit(separator, maxsplit=1)
break
if version.isdigit():
version = str(int(version) + 1)
return prefix + separator + version
return ''
@transaction.atomic()
def process_frab(root, event):
with scope(event=event):
for day in root.findall('day'):
for rm in day.findall('room'):
room, _ = Room.objects.get_or_create(event=event, name=rm.attrib['name'])
for talk in rm.findall('event'):
_create_talk(talk=talk, room=room, event=event)
schedule_version = root.find('version').text
try:
event.wip_schedule.freeze(schedule_version, notify_speakers=False)
schedule = event.schedules.get(version=schedule_version)
except Exception:
raise Exception(
f'Could not import "{event.name}" schedule version "{schedule_version}": failed creating schedule release.'
)
schedule.talks.update(is_visible=True)
start = schedule.talks.order_by('start').first().start
end = schedule.talks.order_by('-end').first().end
event.date_from = start.date()
event.date_to = end.date()
event.save()
return (
f'Successfully imported "{event.name}" schedule version "{schedule_version}".'
)
def _create_talk(*, talk, room, event):
date = talk.find('date').text
start = parse(date + ' ' + talk.find('start').text)
hours, minutes = talk.find('duration').text.split(':')
duration = timedelta(hours=int(hours), minutes=int(minutes))
duration_in_minutes = duration.total_seconds() / 60
try:
end = parse(date + ' ' + talk.find('end').text)
except AttributeError:
end = start + duration
sub_type = SubmissionType.objects.filter(
event=event, name=talk.find('type').text, default_duration=duration_in_minutes
).first()
if not sub_type:
sub_type = SubmissionType.objects.create(
name=talk.find('type').text or 'default',
event=event,
default_duration=duration_in_minutes,
)
track = Track.objects.filter(event=event, name=talk.find('track').text).first()
if not track:
track = Track.objects.create(
name=talk.find('track').text or 'default', event=event
)
optout = False
with suppress(AttributeError):
optout = talk.find('recording').find('optout').text == 'true'
code = None
if (
Submission.objects.filter(code__iexact=talk.attrib['id'], event=event).exists()
or not Submission.objects.filter(code__iexact=talk.attrib['id']).exists()
):
code = talk.attrib['id']
elif (
Submission.objects.filter(
code__iexact=talk.attrib['guid'][:16], event=event
).exists()
or not Submission.objects.filter(code__iexact=talk.attrib['guid'][:16]).exists()
):
code = talk.attrib['guid'][:16]
sub, _ = Submission.objects.get_or_create(
event=event, code=code, defaults={'submission_type': sub_type}
)
sub.submission_type = sub_type
sub.track = track
sub.title = talk.find('title').text
sub.description = talk.find('description').text
if talk.find('subtitle').text:
sub.description = talk.find('subtitle').text + '\n' + (sub.description or '')
sub.abstract = talk.find('abstract').text
sub.content_locale = talk.find('language').text or 'en'
sub.do_not_record = optout
sub.state = SubmissionStates.CONFIRMED
sub.save()
for person in talk.find('persons').findall('person'):
user = User.objects.filter(name=person.text[:60]).first()
if not user:
user = User(name=person.text, email=f'{person.text}@localhost')
user.save()
SpeakerProfile.objects.create(user=user, event=event)
sub.speakers.add(user)
slot, _ = TalkSlot.objects.get_or_create(
submission=sub, schedule=event.wip_schedule, is_visible=True
)
slot.room = room
slot.is_visible = True
slot.start = start
slot.end = end
slot.save()
| true | true |
f72b726b4dcae39366215f12ae7011d2b2bf9606 | 1,072 | py | Python | Codes-B/matplotlib-py-files/matplot-image.py | sanils2002/PYTHON-CODES | 607fadc2cba4b185a5529bd101faefa08f4c3469 | [
"MIT"
] | null | null | null | Codes-B/matplotlib-py-files/matplot-image.py | sanils2002/PYTHON-CODES | 607fadc2cba4b185a5529bd101faefa08f4c3469 | [
"MIT"
] | null | null | null | Codes-B/matplotlib-py-files/matplot-image.py | sanils2002/PYTHON-CODES | 607fadc2cba4b185a5529bd101faefa08f4c3469 | [
"MIT"
] | null | null | null | # importing required libraries
import matplotlib.pyplot as plt
import matplotlib.image as img
# reading the image
testImage = img.imread('g4g.png')
# displaying the image
plt.imshow(testImage)
# displaying the image as an array
print(testImage)
###############################################
# In the output image, only the mode of the image is modified
# reading the image
testImage = img.imread('g4g.png')
# displaying the shape of the image
print(testImage.shape)
# modifying the shape of the image
modifiedImage = testImage[:, :, 0]
# displaying the modified image
plt.imshow(modifiedImage)
# Here the height of the image is 150 pixels (displaying from the 50th pixel),
# width is 100 pixels (displaying from the 100th pixel) and mode value is 1.
# reading the image
testImage = img.imread('g4g.png')
# displaying the shape of the image
print(testImage.shape)
# modifying the shape of the image
modifiedImage = testImage[50:200, 100:200, 1]
# displaying the modified image
plt.imshow(modifiedImage)
| 23.304348 | 80 | 0.689366 |
import matplotlib.pyplot as plt
import matplotlib.image as img
testImage = img.imread('g4g.png')
plt.imshow(testImage)
print(testImage)
| true | true |
f72b72d7b104572721fe60e33a1bbc59a4784e63 | 827 | py | Python | setup.py | STEMinds/Eduponics-Pi-MQTT | 9a8359aaec6b0f571897cc454341d4df336a0b20 | [
"MIT"
] | 10 | 2020-08-12T08:03:00.000Z | 2021-07-07T05:42:36.000Z | setup.py | STEMinds/Eduponics-Pi-MQTT | 9a8359aaec6b0f571897cc454341d4df336a0b20 | [
"MIT"
] | null | null | null | setup.py | STEMinds/Eduponics-Pi-MQTT | 9a8359aaec6b0f571897cc454341d4df336a0b20 | [
"MIT"
] | 2 | 2020-08-15T06:50:28.000Z | 2020-08-19T06:33:23.000Z | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="eduponics-mqtt-STEMinds", # Replace with your own username
version="0.0.1",
author="Roni Gorodetsky",
author_email="contact@steminds.com",
description="Python MQTT package for STEMinds Eduponics react-native mobile app",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/STEMinds/Eduponics-Pi-MQTT",
packages=setuptools.find_packages(),
install_requires=[
'pyqrcode',
'paho-mqtt',
'pypng'
],
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires='>=3.6',
)
| 29.535714 | 85 | 0.657799 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="eduponics-mqtt-STEMinds",
version="0.0.1",
author="Roni Gorodetsky",
author_email="contact@steminds.com",
description="Python MQTT package for STEMinds Eduponics react-native mobile app",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/STEMinds/Eduponics-Pi-MQTT",
packages=setuptools.find_packages(),
install_requires=[
'pyqrcode',
'paho-mqtt',
'pypng'
],
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires='>=3.6',
)
| true | true |
f72b7400fbb8c82da785145fefce3095b952b913 | 3,480 | py | Python | src/m2_extra.py | josephklaw/99-CapstoneProject-201920 | 0e8b8a652a8694e453c57ff42c412043e02b9800 | [
"MIT"
] | null | null | null | src/m2_extra.py | josephklaw/99-CapstoneProject-201920 | 0e8b8a652a8694e453c57ff42c412043e02b9800 | [
"MIT"
] | null | null | null | src/m2_extra.py | josephklaw/99-CapstoneProject-201920 | 0e8b8a652a8694e453c57ff42c412043e02b9800 | [
"MIT"
] | null | null | null | import ev3dev.ev3 as ev3
import rosebot as robot
import time
def increasing_tone(initial_tone, tone_rate_increase, speed, robot):
""":type robot: rosebot.RoseBot"""
robot.drive_system.go(speed, speed)
starting_distance = robot.sensor_system.ir_proximity_sensor.get_distance_in_inches()
while True:
new_distance = robot.sensor_system.ir_proximity_sensor.get_distance_in_inches()
if new_distance < starting_distance:
initial_tone = initial_tone + tone_rate_increase
starting_distance = new_distance
if robot.sensor_system.ir_proximity_sensor.get_distance_in_inches() < 1:
break
robot.sound_system.tone_maker.play_tone(initial_tone, 150)
robot.drive_system.stop()
robot.arm_and_claw.raise_arm()
def point_to_object(direction, speed, initial_tone, tone_rate_increase, robot):
""":type robot: rosebot.RoseBot"""
p = ev3.Sensor(driver_name="pixy-lego")
p.mode = "SIG1"
if direction == "CCW":
robot.drive_system.spin_counterclockwise_until_sees_object(int(speed), p.value(3) * p.value(4))
if direction == "CW":
robot.drive_system.spin_clockwise_until_sees_object(int(speed), p.value(3) * p.value(4))
increasing_tone(initial_tone, tone_rate_increase, speed, robot)
#Sprint 3 Functions
def color_finder(color, robot):
""":type robot: rosebot.RoseBot"""
robot.drive_system.go(75, 75)
while True:
if robot.sensor_system.color_sensor.get_color() == int(color):
robot.drive_system.stop()
robot.sound_system.speech_maker.speak("I found the color")
print(robot.sensor_system.color_sensor.get_color())
break
def find_object(speed, robot):
""":type robot: rosebot.RoseBot"""
p = ev3.Sensor(driver_name="pixy-lego")
p.mode = "SIG1"
robot.drive_system.go_straight_for_seconds(3, speed)
robot.drive_system.spin_counterclockwise_until_sees_object(int(speed), p.value(3) * p.value(4))
robot.drive_system.go(speed, speed)
while True:
if robot.sensor_system.ir_proximity_sensor.get_distance_in_inches() < 0.75:
break
robot.drive_system.stop()
robot.arm_and_claw.raise_arm()
def line_following(robot):
""":type robot: rosebot.RoseBot"""
robot.drive_system.go(50, 50)
while True:
if robot.sensor_system.color_sensor.get_color() == 1:
robot.drive_system.right_motor.turn_off()
robot.drive_system.left_motor.turn_off()
robot.drive_system.go(50,50)
if robot.sensor_system.color_sensor.get_color() == 4:
robot.drive_system.right_motor.turn_off()
robot.drive_system.right_motor.turn_on(-20)
robot.drive_system.left_motor.turn_off()
robot.drive_system.left_motor.turn_on(50)
if robot.sensor_system.color_sensor.get_color() == 5:
robot.drive_system.right_motor.turn_off()
robot.drive_system.right_motor.turn_on(50)
robot.drive_system.left_motor.turn_off()
robot.drive_system.left_motor.turn_on(-20)
if robot.sensor_system.color_sensor.get_color() == 6:
robot.drive_system.stop()
robot.arm_and_claw.move_arm_to_position(0)
break
time.sleep(0.01)
# # - 1: Black
# - 2: Blue
# - 3: Green
# - 4: Yellow
# - 5: Red
# - 6: White
# - 7: Brown | 36.631579 | 103 | 0.66408 | import ev3dev.ev3 as ev3
import rosebot as robot
import time
def increasing_tone(initial_tone, tone_rate_increase, speed, robot):
robot.drive_system.go(speed, speed)
starting_distance = robot.sensor_system.ir_proximity_sensor.get_distance_in_inches()
while True:
new_distance = robot.sensor_system.ir_proximity_sensor.get_distance_in_inches()
if new_distance < starting_distance:
initial_tone = initial_tone + tone_rate_increase
starting_distance = new_distance
if robot.sensor_system.ir_proximity_sensor.get_distance_in_inches() < 1:
break
robot.sound_system.tone_maker.play_tone(initial_tone, 150)
robot.drive_system.stop()
robot.arm_and_claw.raise_arm()
def point_to_object(direction, speed, initial_tone, tone_rate_increase, robot):
p = ev3.Sensor(driver_name="pixy-lego")
p.mode = "SIG1"
if direction == "CCW":
robot.drive_system.spin_counterclockwise_until_sees_object(int(speed), p.value(3) * p.value(4))
if direction == "CW":
robot.drive_system.spin_clockwise_until_sees_object(int(speed), p.value(3) * p.value(4))
increasing_tone(initial_tone, tone_rate_increase, speed, robot)
def color_finder(color, robot):
robot.drive_system.go(75, 75)
while True:
if robot.sensor_system.color_sensor.get_color() == int(color):
robot.drive_system.stop()
robot.sound_system.speech_maker.speak("I found the color")
print(robot.sensor_system.color_sensor.get_color())
break
def find_object(speed, robot):
p = ev3.Sensor(driver_name="pixy-lego")
p.mode = "SIG1"
robot.drive_system.go_straight_for_seconds(3, speed)
robot.drive_system.spin_counterclockwise_until_sees_object(int(speed), p.value(3) * p.value(4))
robot.drive_system.go(speed, speed)
while True:
if robot.sensor_system.ir_proximity_sensor.get_distance_in_inches() < 0.75:
break
robot.drive_system.stop()
robot.arm_and_claw.raise_arm()
def line_following(robot):
robot.drive_system.go(50, 50)
while True:
if robot.sensor_system.color_sensor.get_color() == 1:
robot.drive_system.right_motor.turn_off()
robot.drive_system.left_motor.turn_off()
robot.drive_system.go(50,50)
if robot.sensor_system.color_sensor.get_color() == 4:
robot.drive_system.right_motor.turn_off()
robot.drive_system.right_motor.turn_on(-20)
robot.drive_system.left_motor.turn_off()
robot.drive_system.left_motor.turn_on(50)
if robot.sensor_system.color_sensor.get_color() == 5:
robot.drive_system.right_motor.turn_off()
robot.drive_system.right_motor.turn_on(50)
robot.drive_system.left_motor.turn_off()
robot.drive_system.left_motor.turn_on(-20)
if robot.sensor_system.color_sensor.get_color() == 6:
robot.drive_system.stop()
robot.arm_and_claw.move_arm_to_position(0)
break
time.sleep(0.01)
| true | true |
f72b748ba56730f9620b2b9c4d086d31b3c8eea7 | 101,044 | py | Python | numpy/random/tests/test_generator_mt19937.py | czgdp1807/numpy | fb314a390851d4c21f3f6a2a87cffd329219c524 | [
"BSD-3-Clause"
] | 1 | 2021-12-27T06:52:12.000Z | 2021-12-27T06:52:12.000Z | numpy/random/tests/test_generator_mt19937.py | zooba/numpy | e4894aef5c93c845081388818a2eb4264c5e1d72 | [
"BSD-3-Clause"
] | 32 | 2019-05-20T02:43:57.000Z | 2022-01-28T21:06:29.000Z | numpy/random/tests/test_generator_mt19937.py | zooba/numpy | e4894aef5c93c845081388818a2eb4264c5e1d72 | [
"BSD-3-Clause"
] | null | null | null | import sys
import hashlib
import pytest
import numpy as np
from numpy.linalg import LinAlgError
from numpy.testing import (
assert_, assert_raises, assert_equal, assert_allclose,
assert_warns, assert_no_warnings, assert_array_equal,
assert_array_almost_equal, suppress_warnings)
from numpy.random import Generator, MT19937, SeedSequence
random = Generator(MT19937())
JUMP_TEST_DATA = [
{
"seed": 0,
"steps": 10,
"initial": {"key_md5": "64eaf265d2203179fb5ffb73380cd589", "pos": 9},
"jumped": {"key_md5": "8cb7b061136efceef5217a9ce2cc9a5a", "pos": 598},
},
{
"seed":384908324,
"steps":312,
"initial": {"key_md5": "e99708a47b82ff51a2c7b0625b81afb5", "pos": 311},
"jumped": {"key_md5": "2ecdbfc47a895b253e6e19ccb2e74b90", "pos": 276},
},
{
"seed": [839438204, 980239840, 859048019, 821],
"steps": 511,
"initial": {"key_md5": "9fcd6280df9199785e17e93162ce283c", "pos": 510},
"jumped": {"key_md5": "433b85229f2ed853cde06cd872818305", "pos": 475},
},
]
@pytest.fixture(scope='module', params=[True, False])
def endpoint(request):
return request.param
class TestSeed:
def test_scalar(self):
s = Generator(MT19937(0))
assert_equal(s.integers(1000), 479)
s = Generator(MT19937(4294967295))
assert_equal(s.integers(1000), 324)
def test_array(self):
s = Generator(MT19937(range(10)))
assert_equal(s.integers(1000), 465)
s = Generator(MT19937(np.arange(10)))
assert_equal(s.integers(1000), 465)
s = Generator(MT19937([0]))
assert_equal(s.integers(1000), 479)
s = Generator(MT19937([4294967295]))
assert_equal(s.integers(1000), 324)
def test_seedsequence(self):
s = MT19937(SeedSequence(0))
assert_equal(s.random_raw(1), 2058676884)
def test_invalid_scalar(self):
# seed must be an unsigned 32 bit integer
assert_raises(TypeError, MT19937, -0.5)
assert_raises(ValueError, MT19937, -1)
def test_invalid_array(self):
# seed must be an unsigned integer
assert_raises(TypeError, MT19937, [-0.5])
assert_raises(ValueError, MT19937, [-1])
assert_raises(ValueError, MT19937, [1, -2, 4294967296])
def test_noninstantized_bitgen(self):
assert_raises(ValueError, Generator, MT19937)
class TestBinomial:
def test_n_zero(self):
# Tests the corner case of n == 0 for the binomial distribution.
# binomial(0, p) should be zero for any p in [0, 1].
# This test addresses issue #3480.
zeros = np.zeros(2, dtype='int')
for p in [0, .5, 1]:
assert_(random.binomial(0, p) == 0)
assert_array_equal(random.binomial(zeros, p), zeros)
def test_p_is_nan(self):
# Issue #4571.
assert_raises(ValueError, random.binomial, 1, np.nan)
class TestMultinomial:
def test_basic(self):
random.multinomial(100, [0.2, 0.8])
def test_zero_probability(self):
random.multinomial(100, [0.2, 0.8, 0.0, 0.0, 0.0])
def test_int_negative_interval(self):
assert_(-5 <= random.integers(-5, -1) < -1)
x = random.integers(-5, -1, 5)
assert_(np.all(-5 <= x))
assert_(np.all(x < -1))
def test_size(self):
# gh-3173
p = [0.5, 0.5]
assert_equal(random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
assert_equal(random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
assert_equal(random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
assert_equal(random.multinomial(1, p, [2, 2]).shape, (2, 2, 2))
assert_equal(random.multinomial(1, p, (2, 2)).shape, (2, 2, 2))
assert_equal(random.multinomial(1, p, np.array((2, 2))).shape,
(2, 2, 2))
assert_raises(TypeError, random.multinomial, 1, p,
float(1))
def test_invalid_prob(self):
assert_raises(ValueError, random.multinomial, 100, [1.1, 0.2])
assert_raises(ValueError, random.multinomial, 100, [-.1, 0.9])
def test_invalid_n(self):
assert_raises(ValueError, random.multinomial, -1, [0.8, 0.2])
assert_raises(ValueError, random.multinomial, [-1] * 10, [0.8, 0.2])
def test_p_non_contiguous(self):
p = np.arange(15.)
p /= np.sum(p[1::3])
pvals = p[1::3]
random = Generator(MT19937(1432985819))
non_contig = random.multinomial(100, pvals=pvals)
random = Generator(MT19937(1432985819))
contig = random.multinomial(100, pvals=np.ascontiguousarray(pvals))
assert_array_equal(non_contig, contig)
def test_multidimensional_pvals(self):
assert_raises(ValueError, random.multinomial, 10, [[0, 1]])
assert_raises(ValueError, random.multinomial, 10, [[0], [1]])
assert_raises(ValueError, random.multinomial, 10, [[[0], [1]], [[1], [0]]])
assert_raises(ValueError, random.multinomial, 10, np.array([[0, 1], [1, 0]]))
class TestMultivariateHypergeometric:
def setup(self):
self.seed = 8675309
def test_argument_validation(self):
# Error cases...
# `colors` must be a 1-d sequence
assert_raises(ValueError, random.multivariate_hypergeometric,
10, 4)
# Negative nsample
assert_raises(ValueError, random.multivariate_hypergeometric,
[2, 3, 4], -1)
# Negative color
assert_raises(ValueError, random.multivariate_hypergeometric,
[-1, 2, 3], 2)
# nsample exceeds sum(colors)
assert_raises(ValueError, random.multivariate_hypergeometric,
[2, 3, 4], 10)
# nsample exceeds sum(colors) (edge case of empty colors)
assert_raises(ValueError, random.multivariate_hypergeometric,
[], 1)
# Validation errors associated with very large values in colors.
assert_raises(ValueError, random.multivariate_hypergeometric,
[999999999, 101], 5, 1, 'marginals')
int64_info = np.iinfo(np.int64)
max_int64 = int64_info.max
max_int64_index = max_int64 // int64_info.dtype.itemsize
assert_raises(ValueError, random.multivariate_hypergeometric,
[max_int64_index - 100, 101], 5, 1, 'count')
@pytest.mark.parametrize('method', ['count', 'marginals'])
def test_edge_cases(self, method):
# Set the seed, but in fact, all the results in this test are
# deterministic, so we don't really need this.
random = Generator(MT19937(self.seed))
x = random.multivariate_hypergeometric([0, 0, 0], 0, method=method)
assert_array_equal(x, [0, 0, 0])
x = random.multivariate_hypergeometric([], 0, method=method)
assert_array_equal(x, [])
x = random.multivariate_hypergeometric([], 0, size=1, method=method)
assert_array_equal(x, np.empty((1, 0), dtype=np.int64))
x = random.multivariate_hypergeometric([1, 2, 3], 0, method=method)
assert_array_equal(x, [0, 0, 0])
x = random.multivariate_hypergeometric([9, 0, 0], 3, method=method)
assert_array_equal(x, [3, 0, 0])
colors = [1, 1, 0, 1, 1]
x = random.multivariate_hypergeometric(colors, sum(colors),
method=method)
assert_array_equal(x, colors)
x = random.multivariate_hypergeometric([3, 4, 5], 12, size=3,
method=method)
assert_array_equal(x, [[3, 4, 5]]*3)
# Cases for nsample:
# nsample < 10
# 10 <= nsample < colors.sum()/2
# colors.sum()/2 < nsample < colors.sum() - 10
# colors.sum() - 10 < nsample < colors.sum()
@pytest.mark.parametrize('nsample', [8, 25, 45, 55])
@pytest.mark.parametrize('method', ['count', 'marginals'])
@pytest.mark.parametrize('size', [5, (2, 3), 150000])
def test_typical_cases(self, nsample, method, size):
random = Generator(MT19937(self.seed))
colors = np.array([10, 5, 20, 25])
sample = random.multivariate_hypergeometric(colors, nsample, size,
method=method)
if isinstance(size, int):
expected_shape = (size,) + colors.shape
else:
expected_shape = size + colors.shape
assert_equal(sample.shape, expected_shape)
assert_((sample >= 0).all())
assert_((sample <= colors).all())
assert_array_equal(sample.sum(axis=-1),
np.full(size, fill_value=nsample, dtype=int))
if isinstance(size, int) and size >= 100000:
# This sample is large enough to compare its mean to
# the expected values.
assert_allclose(sample.mean(axis=0),
nsample * colors / colors.sum(),
rtol=1e-3, atol=0.005)
def test_repeatability1(self):
random = Generator(MT19937(self.seed))
sample = random.multivariate_hypergeometric([3, 4, 5], 5, size=5,
method='count')
expected = np.array([[2, 1, 2],
[2, 1, 2],
[1, 1, 3],
[2, 0, 3],
[2, 1, 2]])
assert_array_equal(sample, expected)
def test_repeatability2(self):
random = Generator(MT19937(self.seed))
sample = random.multivariate_hypergeometric([20, 30, 50], 50,
size=5,
method='marginals')
expected = np.array([[ 9, 17, 24],
[ 7, 13, 30],
[ 9, 15, 26],
[ 9, 17, 24],
[12, 14, 24]])
assert_array_equal(sample, expected)
def test_repeatability3(self):
random = Generator(MT19937(self.seed))
sample = random.multivariate_hypergeometric([20, 30, 50], 12,
size=5,
method='marginals')
expected = np.array([[2, 3, 7],
[5, 3, 4],
[2, 5, 5],
[5, 3, 4],
[1, 5, 6]])
assert_array_equal(sample, expected)
class TestSetState:
def setup(self):
self.seed = 1234567890
self.rg = Generator(MT19937(self.seed))
self.bit_generator = self.rg.bit_generator
self.state = self.bit_generator.state
self.legacy_state = (self.state['bit_generator'],
self.state['state']['key'],
self.state['state']['pos'])
def test_gaussian_reset(self):
# Make sure the cached every-other-Gaussian is reset.
old = self.rg.standard_normal(size=3)
self.bit_generator.state = self.state
new = self.rg.standard_normal(size=3)
assert_(np.all(old == new))
def test_gaussian_reset_in_media_res(self):
# When the state is saved with a cached Gaussian, make sure the
# cached Gaussian is restored.
self.rg.standard_normal()
state = self.bit_generator.state
old = self.rg.standard_normal(size=3)
self.bit_generator.state = state
new = self.rg.standard_normal(size=3)
assert_(np.all(old == new))
def test_negative_binomial(self):
# Ensure that the negative binomial results take floating point
# arguments without truncation.
self.rg.negative_binomial(0.5, 0.5)
class TestIntegers:
rfunc = random.integers
# valid integer/boolean types
itype = [bool, np.int8, np.uint8, np.int16, np.uint16,
np.int32, np.uint32, np.int64, np.uint64]
def test_unsupported_type(self, endpoint):
assert_raises(TypeError, self.rfunc, 1, endpoint=endpoint, dtype=float)
def test_bounds_checking(self, endpoint):
for dt in self.itype:
lbnd = 0 if dt is bool else np.iinfo(dt).min
ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
ubnd = ubnd - 1 if endpoint else ubnd
assert_raises(ValueError, self.rfunc, lbnd - 1, ubnd,
endpoint=endpoint, dtype=dt)
assert_raises(ValueError, self.rfunc, lbnd, ubnd + 1,
endpoint=endpoint, dtype=dt)
assert_raises(ValueError, self.rfunc, ubnd, lbnd,
endpoint=endpoint, dtype=dt)
assert_raises(ValueError, self.rfunc, 1, 0, endpoint=endpoint,
dtype=dt)
assert_raises(ValueError, self.rfunc, [lbnd - 1], ubnd,
endpoint=endpoint, dtype=dt)
assert_raises(ValueError, self.rfunc, [lbnd], [ubnd + 1],
endpoint=endpoint, dtype=dt)
assert_raises(ValueError, self.rfunc, [ubnd], [lbnd],
endpoint=endpoint, dtype=dt)
assert_raises(ValueError, self.rfunc, 1, [0],
endpoint=endpoint, dtype=dt)
def test_bounds_checking_array(self, endpoint):
for dt in self.itype:
lbnd = 0 if dt is bool else np.iinfo(dt).min
ubnd = 2 if dt is bool else np.iinfo(dt).max + (not endpoint)
assert_raises(ValueError, self.rfunc, [lbnd - 1] * 2, [ubnd] * 2,
endpoint=endpoint, dtype=dt)
assert_raises(ValueError, self.rfunc, [lbnd] * 2,
[ubnd + 1] * 2, endpoint=endpoint, dtype=dt)
assert_raises(ValueError, self.rfunc, ubnd, [lbnd] * 2,
endpoint=endpoint, dtype=dt)
assert_raises(ValueError, self.rfunc, [1] * 2, 0,
endpoint=endpoint, dtype=dt)
def test_rng_zero_and_extremes(self, endpoint):
for dt in self.itype:
lbnd = 0 if dt is bool else np.iinfo(dt).min
ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
ubnd = ubnd - 1 if endpoint else ubnd
is_open = not endpoint
tgt = ubnd - 1
assert_equal(self.rfunc(tgt, tgt + is_open, size=1000,
endpoint=endpoint, dtype=dt), tgt)
assert_equal(self.rfunc([tgt], tgt + is_open, size=1000,
endpoint=endpoint, dtype=dt), tgt)
tgt = lbnd
assert_equal(self.rfunc(tgt, tgt + is_open, size=1000,
endpoint=endpoint, dtype=dt), tgt)
assert_equal(self.rfunc(tgt, [tgt + is_open], size=1000,
endpoint=endpoint, dtype=dt), tgt)
tgt = (lbnd + ubnd) // 2
assert_equal(self.rfunc(tgt, tgt + is_open, size=1000,
endpoint=endpoint, dtype=dt), tgt)
assert_equal(self.rfunc([tgt], [tgt + is_open],
size=1000, endpoint=endpoint, dtype=dt),
tgt)
def test_rng_zero_and_extremes_array(self, endpoint):
size = 1000
for dt in self.itype:
lbnd = 0 if dt is bool else np.iinfo(dt).min
ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
ubnd = ubnd - 1 if endpoint else ubnd
tgt = ubnd - 1
assert_equal(self.rfunc([tgt], [tgt + 1],
size=size, dtype=dt), tgt)
assert_equal(self.rfunc(
[tgt] * size, [tgt + 1] * size, dtype=dt), tgt)
assert_equal(self.rfunc(
[tgt] * size, [tgt + 1] * size, size=size, dtype=dt), tgt)
tgt = lbnd
assert_equal(self.rfunc([tgt], [tgt + 1],
size=size, dtype=dt), tgt)
assert_equal(self.rfunc(
[tgt] * size, [tgt + 1] * size, dtype=dt), tgt)
assert_equal(self.rfunc(
[tgt] * size, [tgt + 1] * size, size=size, dtype=dt), tgt)
tgt = (lbnd + ubnd) // 2
assert_equal(self.rfunc([tgt], [tgt + 1],
size=size, dtype=dt), tgt)
assert_equal(self.rfunc(
[tgt] * size, [tgt + 1] * size, dtype=dt), tgt)
assert_equal(self.rfunc(
[tgt] * size, [tgt + 1] * size, size=size, dtype=dt), tgt)
def test_full_range(self, endpoint):
# Test for ticket #1690
for dt in self.itype:
lbnd = 0 if dt is bool else np.iinfo(dt).min
ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
ubnd = ubnd - 1 if endpoint else ubnd
try:
self.rfunc(lbnd, ubnd, endpoint=endpoint, dtype=dt)
except Exception as e:
raise AssertionError("No error should have been raised, "
"but one was with the following "
"message:\n\n%s" % str(e))
def test_full_range_array(self, endpoint):
# Test for ticket #1690
for dt in self.itype:
lbnd = 0 if dt is bool else np.iinfo(dt).min
ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
ubnd = ubnd - 1 if endpoint else ubnd
try:
self.rfunc([lbnd] * 2, [ubnd], endpoint=endpoint, dtype=dt)
except Exception as e:
raise AssertionError("No error should have been raised, "
"but one was with the following "
"message:\n\n%s" % str(e))
def test_in_bounds_fuzz(self, endpoint):
# Don't use fixed seed
random = Generator(MT19937())
for dt in self.itype[1:]:
for ubnd in [4, 8, 16]:
vals = self.rfunc(2, ubnd - endpoint, size=2 ** 16,
endpoint=endpoint, dtype=dt)
assert_(vals.max() < ubnd)
assert_(vals.min() >= 2)
vals = self.rfunc(0, 2 - endpoint, size=2 ** 16, endpoint=endpoint,
dtype=bool)
assert_(vals.max() < 2)
assert_(vals.min() >= 0)
def test_scalar_array_equiv(self, endpoint):
for dt in self.itype:
lbnd = 0 if dt is bool else np.iinfo(dt).min
ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
ubnd = ubnd - 1 if endpoint else ubnd
size = 1000
random = Generator(MT19937(1234))
scalar = random.integers(lbnd, ubnd, size=size, endpoint=endpoint,
dtype=dt)
random = Generator(MT19937(1234))
scalar_array = random.integers([lbnd], [ubnd], size=size,
endpoint=endpoint, dtype=dt)
random = Generator(MT19937(1234))
array = random.integers([lbnd] * size, [ubnd] *
size, size=size, endpoint=endpoint, dtype=dt)
assert_array_equal(scalar, scalar_array)
assert_array_equal(scalar, array)
def test_repeatability(self, endpoint):
# We use a md5 hash of generated sequences of 1000 samples
# in the range [0, 6) for all but bool, where the range
# is [0, 2). Hashes are for little endian numbers.
tgt = {'bool': 'b3300e66d2bb59e493d255d47c3a6cbe',
'int16': '39624ead49ad67e37545744024d2648b',
'int32': '5c4810373f979336c6c0c999996e47a1',
'int64': 'ab126c15edff26f55c50d2b7e37391ac',
'int8': 'ba71ccaffeeeb9eeb1860f8075020b9c',
'uint16': '39624ead49ad67e37545744024d2648b',
'uint32': '5c4810373f979336c6c0c999996e47a1',
'uint64': 'ab126c15edff26f55c50d2b7e37391ac',
'uint8': 'ba71ccaffeeeb9eeb1860f8075020b9c'}
for dt in self.itype[1:]:
random = Generator(MT19937(1234))
# view as little endian for hash
if sys.byteorder == 'little':
val = random.integers(0, 6 - endpoint, size=1000, endpoint=endpoint,
dtype=dt)
else:
val = random.integers(0, 6 - endpoint, size=1000, endpoint=endpoint,
dtype=dt).byteswap()
res = hashlib.md5(val).hexdigest()
assert_(tgt[np.dtype(dt).name] == res)
# bools do not depend on endianness
random = Generator(MT19937(1234))
val = random.integers(0, 2 - endpoint, size=1000, endpoint=endpoint,
dtype=bool).view(np.int8)
res = hashlib.md5(val).hexdigest()
assert_(tgt[np.dtype(bool).name] == res)
def test_repeatability_broadcasting(self, endpoint):
for dt in self.itype:
lbnd = 0 if dt in (bool, np.bool_) else np.iinfo(dt).min
ubnd = 2 if dt in (bool, np.bool_) else np.iinfo(dt).max + 1
ubnd = ubnd - 1 if endpoint else ubnd
# view as little endian for hash
random = Generator(MT19937(1234))
val = random.integers(lbnd, ubnd, size=1000, endpoint=endpoint,
dtype=dt)
random = Generator(MT19937(1234))
val_bc = random.integers([lbnd] * 1000, ubnd, endpoint=endpoint,
dtype=dt)
assert_array_equal(val, val_bc)
random = Generator(MT19937(1234))
val_bc = random.integers([lbnd] * 1000, [ubnd] * 1000,
endpoint=endpoint, dtype=dt)
assert_array_equal(val, val_bc)
@pytest.mark.parametrize(
'bound, expected',
[(2**32 - 1, np.array([517043486, 1364798665, 1733884389, 1353720612,
3769704066, 1170797179, 4108474671])),
(2**32, np.array([517043487, 1364798666, 1733884390, 1353720613,
3769704067, 1170797180, 4108474672])),
(2**32 + 1, np.array([517043487, 1733884390, 3769704068, 4108474673,
1831631863, 1215661561, 3869512430]))]
)
def test_repeatability_32bit_boundary(self, bound, expected):
for size in [None, len(expected)]:
random = Generator(MT19937(1234))
x = random.integers(bound, size=size)
assert_equal(x, expected if size is not None else expected[0])
def test_repeatability_32bit_boundary_broadcasting(self):
desired = np.array([[[1622936284, 3620788691, 1659384060],
[1417365545, 760222891, 1909653332],
[3788118662, 660249498, 4092002593]],
[[3625610153, 2979601262, 3844162757],
[ 685800658, 120261497, 2694012896],
[1207779440, 1586594375, 3854335050]],
[[3004074748, 2310761796, 3012642217],
[2067714190, 2786677879, 1363865881],
[ 791663441, 1867303284, 2169727960]],
[[1939603804, 1250951100, 298950036],
[1040128489, 3791912209, 3317053765],
[3155528714, 61360675, 2305155588]],
[[ 817688762, 1335621943, 3288952434],
[1770890872, 1102951817, 1957607470],
[3099996017, 798043451, 48334215]]])
for size in [None, (5, 3, 3)]:
random = Generator(MT19937(12345))
x = random.integers([[-1], [0], [1]],
[2**32 - 1, 2**32, 2**32 + 1],
size=size)
assert_array_equal(x, desired if size is not None else desired[0])
def test_int64_uint64_broadcast_exceptions(self, endpoint):
configs = {np.uint64: ((0, 2**65), (-1, 2**62), (10, 9), (0, 0)),
np.int64: ((0, 2**64), (-(2**64), 2**62), (10, 9), (0, 0),
(-2**63-1, -2**63-1))}
for dtype in configs:
for config in configs[dtype]:
low, high = config
high = high - endpoint
low_a = np.array([[low]*10])
high_a = np.array([high] * 10)
assert_raises(ValueError, random.integers, low, high,
endpoint=endpoint, dtype=dtype)
assert_raises(ValueError, random.integers, low_a, high,
endpoint=endpoint, dtype=dtype)
assert_raises(ValueError, random.integers, low, high_a,
endpoint=endpoint, dtype=dtype)
assert_raises(ValueError, random.integers, low_a, high_a,
endpoint=endpoint, dtype=dtype)
low_o = np.array([[low]*10], dtype=object)
high_o = np.array([high] * 10, dtype=object)
assert_raises(ValueError, random.integers, low_o, high,
endpoint=endpoint, dtype=dtype)
assert_raises(ValueError, random.integers, low, high_o,
endpoint=endpoint, dtype=dtype)
assert_raises(ValueError, random.integers, low_o, high_o,
endpoint=endpoint, dtype=dtype)
def test_int64_uint64_corner_case(self, endpoint):
# When stored in Numpy arrays, `lbnd` is casted
# as np.int64, and `ubnd` is casted as np.uint64.
# Checking whether `lbnd` >= `ubnd` used to be
# done solely via direct comparison, which is incorrect
# because when Numpy tries to compare both numbers,
# it casts both to np.float64 because there is
# no integer superset of np.int64 and np.uint64. However,
# `ubnd` is too large to be represented in np.float64,
# causing it be round down to np.iinfo(np.int64).max,
# leading to a ValueError because `lbnd` now equals
# the new `ubnd`.
dt = np.int64
tgt = np.iinfo(np.int64).max
lbnd = np.int64(np.iinfo(np.int64).max)
ubnd = np.uint64(np.iinfo(np.int64).max + 1 - endpoint)
# None of these function calls should
# generate a ValueError now.
actual = random.integers(lbnd, ubnd, endpoint=endpoint, dtype=dt)
assert_equal(actual, tgt)
def test_respect_dtype_singleton(self, endpoint):
# See gh-7203
for dt in self.itype:
lbnd = 0 if dt is bool else np.iinfo(dt).min
ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
ubnd = ubnd - 1 if endpoint else ubnd
dt = np.bool_ if dt is bool else dt
sample = self.rfunc(lbnd, ubnd, endpoint=endpoint, dtype=dt)
assert_equal(sample.dtype, dt)
for dt in (bool, int, np.compat.long):
lbnd = 0 if dt is bool else np.iinfo(dt).min
ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
ubnd = ubnd - 1 if endpoint else ubnd
# gh-7284: Ensure that we get Python data types
sample = self.rfunc(lbnd, ubnd, endpoint=endpoint, dtype=dt)
assert not hasattr(sample, 'dtype')
assert_equal(type(sample), dt)
def test_respect_dtype_array(self, endpoint):
# See gh-7203
for dt in self.itype:
lbnd = 0 if dt is bool else np.iinfo(dt).min
ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
ubnd = ubnd - 1 if endpoint else ubnd
dt = np.bool_ if dt is bool else dt
sample = self.rfunc([lbnd], [ubnd], endpoint=endpoint, dtype=dt)
assert_equal(sample.dtype, dt)
sample = self.rfunc([lbnd] * 2, [ubnd] * 2, endpoint=endpoint,
dtype=dt)
assert_equal(sample.dtype, dt)
def test_zero_size(self, endpoint):
# See gh-7203
for dt in self.itype:
sample = self.rfunc(0, 0, (3, 0, 4), endpoint=endpoint, dtype=dt)
assert sample.shape == (3, 0, 4)
assert sample.dtype == dt
assert self.rfunc(0, -10, 0, endpoint=endpoint,
dtype=dt).shape == (0,)
assert_equal(random.integers(0, 0, size=(3, 0, 4)).shape,
(3, 0, 4))
assert_equal(random.integers(0, -10, size=0).shape, (0,))
assert_equal(random.integers(10, 10, size=0).shape, (0,))
def test_error_byteorder(self):
other_byteord_dt = '<i4' if sys.byteorder == 'big' else '>i4'
with pytest.raises(ValueError):
random.integers(0, 200, size=10, dtype=other_byteord_dt)
# chi2max is the maximum acceptable chi-squared value.
@pytest.mark.slow
@pytest.mark.parametrize('sample_size,high,dtype,chi2max',
[(5000000, 5, np.int8, 125.0), # p-value ~4.6e-25
(5000000, 7, np.uint8, 150.0), # p-value ~7.7e-30
(10000000, 2500, np.int16, 3300.0), # p-value ~3.0e-25
(50000000, 5000, np.uint16, 6500.0), # p-value ~3.5e-25
])
def test_integers_small_dtype_chisquared(self, sample_size, high,
dtype, chi2max):
# Regression test for gh-14774.
samples = random.integers(high, size=sample_size, dtype=dtype)
values, counts = np.unique(samples, return_counts=True)
expected = sample_size / high
chi2 = ((counts - expected)**2 / expected).sum()
assert chi2 < chi2max
class TestRandomDist:
# Make sure the random distribution returns the correct value for a
# given seed
def setup(self):
self.seed = 1234567890
def test_integers(self):
random = Generator(MT19937(self.seed))
actual = random.integers(-99, 99, size=(3, 2))
desired = np.array([[-80, -56], [41, 37], [-83, -16]])
assert_array_equal(actual, desired)
def test_integers_masked(self):
# Test masked rejection sampling algorithm to generate array of
# uint32 in an interval.
random = Generator(MT19937(self.seed))
actual = random.integers(0, 99, size=(3, 2), dtype=np.uint32)
desired = np.array([[9, 21], [70, 68], [8, 41]], dtype=np.uint32)
assert_array_equal(actual, desired)
def test_integers_closed(self):
random = Generator(MT19937(self.seed))
actual = random.integers(-99, 99, size=(3, 2), endpoint=True)
desired = np.array([[-80, -56], [ 41, 38], [-83, -15]])
assert_array_equal(actual, desired)
def test_integers_max_int(self):
# Tests whether integers with closed=True can generate the
# maximum allowed Python int that can be converted
# into a C long. Previous implementations of this
# method have thrown an OverflowError when attempting
# to generate this integer.
actual = random.integers(np.iinfo('l').max, np.iinfo('l').max,
endpoint=True)
desired = np.iinfo('l').max
assert_equal(actual, desired)
def test_random(self):
random = Generator(MT19937(self.seed))
actual = random.random((3, 2))
desired = np.array([[0.096999199829214, 0.707517457682192],
[0.084364834598269, 0.767731206553125],
[0.665069021359413, 0.715487190596693]])
assert_array_almost_equal(actual, desired, decimal=15)
random = Generator(MT19937(self.seed))
actual = random.random()
assert_array_almost_equal(actual, desired[0, 0], decimal=15)
def test_random_float(self):
random = Generator(MT19937(self.seed))
actual = random.random((3, 2))
desired = np.array([[0.0969992 , 0.70751746],
[0.08436483, 0.76773121],
[0.66506902, 0.71548719]])
assert_array_almost_equal(actual, desired, decimal=7)
def test_random_float_scalar(self):
random = Generator(MT19937(self.seed))
actual = random.random(dtype=np.float32)
desired = 0.0969992
assert_array_almost_equal(actual, desired, decimal=7)
def test_random_unsupported_type(self):
assert_raises(TypeError, random.random, dtype='int32')
def test_choice_uniform_replace(self):
random = Generator(MT19937(self.seed))
actual = random.choice(4, 4)
desired = np.array([0, 0, 2, 2], dtype=np.int64)
assert_array_equal(actual, desired)
def test_choice_nonuniform_replace(self):
random = Generator(MT19937(self.seed))
actual = random.choice(4, 4, p=[0.4, 0.4, 0.1, 0.1])
desired = np.array([0, 1, 0, 1], dtype=np.int64)
assert_array_equal(actual, desired)
def test_choice_uniform_noreplace(self):
random = Generator(MT19937(self.seed))
actual = random.choice(4, 3, replace=False)
desired = np.array([2, 0, 3], dtype=np.int64)
assert_array_equal(actual, desired)
actual = random.choice(4, 4, replace=False, shuffle=False)
desired = np.arange(4, dtype=np.int64)
assert_array_equal(actual, desired)
def test_choice_nonuniform_noreplace(self):
random = Generator(MT19937(self.seed))
actual = random.choice(4, 3, replace=False, p=[0.1, 0.3, 0.5, 0.1])
desired = np.array([0, 2, 3], dtype=np.int64)
assert_array_equal(actual, desired)
def test_choice_noninteger(self):
random = Generator(MT19937(self.seed))
actual = random.choice(['a', 'b', 'c', 'd'], 4)
desired = np.array(['a', 'a', 'c', 'c'])
assert_array_equal(actual, desired)
def test_choice_multidimensional_default_axis(self):
random = Generator(MT19937(self.seed))
actual = random.choice([[0, 1], [2, 3], [4, 5], [6, 7]], 3)
desired = np.array([[0, 1], [0, 1], [4, 5]])
assert_array_equal(actual, desired)
def test_choice_multidimensional_custom_axis(self):
random = Generator(MT19937(self.seed))
actual = random.choice([[0, 1], [2, 3], [4, 5], [6, 7]], 1, axis=1)
desired = np.array([[0], [2], [4], [6]])
assert_array_equal(actual, desired)
def test_choice_exceptions(self):
sample = random.choice
assert_raises(ValueError, sample, -1, 3)
assert_raises(ValueError, sample, 3., 3)
assert_raises(ValueError, sample, [], 3)
assert_raises(ValueError, sample, [1, 2, 3, 4], 3,
p=[[0.25, 0.25], [0.25, 0.25]])
assert_raises(ValueError, sample, [1, 2], 3, p=[0.4, 0.4, 0.2])
assert_raises(ValueError, sample, [1, 2], 3, p=[1.1, -0.1])
assert_raises(ValueError, sample, [1, 2], 3, p=[0.4, 0.4])
assert_raises(ValueError, sample, [1, 2, 3], 4, replace=False)
# gh-13087
assert_raises(ValueError, sample, [1, 2, 3], -2, replace=False)
assert_raises(ValueError, sample, [1, 2, 3], (-1,), replace=False)
assert_raises(ValueError, sample, [1, 2, 3], (-1, 1), replace=False)
assert_raises(ValueError, sample, [1, 2, 3], 2,
replace=False, p=[1, 0, 0])
def test_choice_return_shape(self):
p = [0.1, 0.9]
# Check scalar
assert_(np.isscalar(random.choice(2, replace=True)))
assert_(np.isscalar(random.choice(2, replace=False)))
assert_(np.isscalar(random.choice(2, replace=True, p=p)))
assert_(np.isscalar(random.choice(2, replace=False, p=p)))
assert_(np.isscalar(random.choice([1, 2], replace=True)))
assert_(random.choice([None], replace=True) is None)
a = np.array([1, 2])
arr = np.empty(1, dtype=object)
arr[0] = a
assert_(random.choice(arr, replace=True) is a)
# Check 0-d array
s = tuple()
assert_(not np.isscalar(random.choice(2, s, replace=True)))
assert_(not np.isscalar(random.choice(2, s, replace=False)))
assert_(not np.isscalar(random.choice(2, s, replace=True, p=p)))
assert_(not np.isscalar(random.choice(2, s, replace=False, p=p)))
assert_(not np.isscalar(random.choice([1, 2], s, replace=True)))
assert_(random.choice([None], s, replace=True).ndim == 0)
a = np.array([1, 2])
arr = np.empty(1, dtype=object)
arr[0] = a
assert_(random.choice(arr, s, replace=True).item() is a)
# Check multi dimensional array
s = (2, 3)
p = [0.1, 0.1, 0.1, 0.1, 0.4, 0.2]
assert_equal(random.choice(6, s, replace=True).shape, s)
assert_equal(random.choice(6, s, replace=False).shape, s)
assert_equal(random.choice(6, s, replace=True, p=p).shape, s)
assert_equal(random.choice(6, s, replace=False, p=p).shape, s)
assert_equal(random.choice(np.arange(6), s, replace=True).shape, s)
# Check zero-size
assert_equal(random.integers(0, 0, size=(3, 0, 4)).shape, (3, 0, 4))
assert_equal(random.integers(0, -10, size=0).shape, (0,))
assert_equal(random.integers(10, 10, size=0).shape, (0,))
assert_equal(random.choice(0, size=0).shape, (0,))
assert_equal(random.choice([], size=(0,)).shape, (0,))
assert_equal(random.choice(['a', 'b'], size=(3, 0, 4)).shape,
(3, 0, 4))
assert_raises(ValueError, random.choice, [], 10)
def test_choice_nan_probabilities(self):
a = np.array([42, 1, 2])
p = [None, None, None]
assert_raises(ValueError, random.choice, a, p=p)
def test_choice_p_non_contiguous(self):
p = np.ones(10) / 5
p[1::2] = 3.0
random = Generator(MT19937(self.seed))
non_contig = random.choice(5, 3, p=p[::2])
random = Generator(MT19937(self.seed))
contig = random.choice(5, 3, p=np.ascontiguousarray(p[::2]))
assert_array_equal(non_contig, contig)
def test_choice_return_type(self):
# gh 9867
p = np.ones(4) / 4.
actual = random.choice(4, 2)
assert actual.dtype == np.int64
actual = random.choice(4, 2, replace=False)
assert actual.dtype == np.int64
actual = random.choice(4, 2, p=p)
assert actual.dtype == np.int64
actual = random.choice(4, 2, p=p, replace=False)
assert actual.dtype == np.int64
def test_choice_large_sample(self):
choice_hash = 'd44962a0b1e92f4a3373c23222244e21'
random = Generator(MT19937(self.seed))
actual = random.choice(10000, 5000, replace=False)
if sys.byteorder != 'little':
actual = actual.byteswap()
res = hashlib.md5(actual.view(np.int8)).hexdigest()
assert_(choice_hash == res)
def test_bytes(self):
random = Generator(MT19937(self.seed))
actual = random.bytes(10)
desired = b'\x86\xf0\xd4\x18\xe1\x81\t8%\xdd'
assert_equal(actual, desired)
def test_shuffle(self):
# Test lists, arrays (of various dtypes), and multidimensional versions
# of both, c-contiguous or not:
for conv in [lambda x: np.array([]),
lambda x: x,
lambda x: np.asarray(x).astype(np.int8),
lambda x: np.asarray(x).astype(np.float32),
lambda x: np.asarray(x).astype(np.complex64),
lambda x: np.asarray(x).astype(object),
lambda x: [(i, i) for i in x],
lambda x: np.asarray([[i, i] for i in x]),
lambda x: np.vstack([x, x]).T,
# gh-11442
lambda x: (np.asarray([(i, i) for i in x],
[("a", int), ("b", int)])
.view(np.recarray)),
# gh-4270
lambda x: np.asarray([(i, i) for i in x],
[("a", object, (1,)),
("b", np.int32, (1,))])]:
random = Generator(MT19937(self.seed))
alist = conv([1, 2, 3, 4, 5, 6, 7, 8, 9, 0])
random.shuffle(alist)
actual = alist
desired = conv([4, 1, 9, 8, 0, 5, 3, 6, 2, 7])
assert_array_equal(actual, desired)
def test_shuffle_custom_axis(self):
random = Generator(MT19937(self.seed))
actual = np.arange(16).reshape((4, 4))
random.shuffle(actual, axis=1)
desired = np.array([[ 0, 3, 1, 2],
[ 4, 7, 5, 6],
[ 8, 11, 9, 10],
[12, 15, 13, 14]])
assert_array_equal(actual, desired)
random = Generator(MT19937(self.seed))
actual = np.arange(16).reshape((4, 4))
random.shuffle(actual, axis=-1)
assert_array_equal(actual, desired)
def test_shuffle_axis_nonsquare(self):
y1 = np.arange(20).reshape(2, 10)
y2 = y1.copy()
random = Generator(MT19937(self.seed))
random.shuffle(y1, axis=1)
random = Generator(MT19937(self.seed))
random.shuffle(y2.T)
assert_array_equal(y1, y2)
def test_shuffle_masked(self):
# gh-3263
a = np.ma.masked_values(np.reshape(range(20), (5, 4)) % 3 - 1, -1)
b = np.ma.masked_values(np.arange(20) % 3 - 1, -1)
a_orig = a.copy()
b_orig = b.copy()
for i in range(50):
random.shuffle(a)
assert_equal(
sorted(a.data[~a.mask]), sorted(a_orig.data[~a_orig.mask]))
random.shuffle(b)
assert_equal(
sorted(b.data[~b.mask]), sorted(b_orig.data[~b_orig.mask]))
def test_shuffle_exceptions(self):
random = Generator(MT19937(self.seed))
arr = np.arange(10)
assert_raises(np.AxisError, random.shuffle, arr, 1)
arr = np.arange(9).reshape((3, 3))
assert_raises(np.AxisError, random.shuffle, arr, 3)
assert_raises(TypeError, random.shuffle, arr, slice(1, 2, None))
arr = [[1, 2, 3], [4, 5, 6]]
assert_raises(NotImplementedError, random.shuffle, arr, 1)
def test_permutation(self):
random = Generator(MT19937(self.seed))
alist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
actual = random.permutation(alist)
desired = [4, 1, 9, 8, 0, 5, 3, 6, 2, 7]
assert_array_equal(actual, desired)
random = Generator(MT19937(self.seed))
arr_2d = np.atleast_2d([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]).T
actual = random.permutation(arr_2d)
assert_array_equal(actual, np.atleast_2d(desired).T)
bad_x_str = "abcd"
assert_raises(np.AxisError, random.permutation, bad_x_str)
bad_x_float = 1.2
assert_raises(np.AxisError, random.permutation, bad_x_float)
random = Generator(MT19937(self.seed))
integer_val = 10
desired = [3, 0, 8, 7, 9, 4, 2, 5, 1, 6]
actual = random.permutation(integer_val)
assert_array_equal(actual, desired)
def test_permutation_custom_axis(self):
a = np.arange(16).reshape((4, 4))
desired = np.array([[ 0, 3, 1, 2],
[ 4, 7, 5, 6],
[ 8, 11, 9, 10],
[12, 15, 13, 14]])
random = Generator(MT19937(self.seed))
actual = random.permutation(a, axis=1)
assert_array_equal(actual, desired)
random = Generator(MT19937(self.seed))
actual = random.permutation(a, axis=-1)
assert_array_equal(actual, desired)
def test_permutation_exceptions(self):
random = Generator(MT19937(self.seed))
arr = np.arange(10)
assert_raises(np.AxisError, random.permutation, arr, 1)
arr = np.arange(9).reshape((3, 3))
assert_raises(np.AxisError, random.permutation, arr, 3)
assert_raises(TypeError, random.permutation, arr, slice(1, 2, None))
def test_beta(self):
random = Generator(MT19937(self.seed))
actual = random.beta(.1, .9, size=(3, 2))
desired = np.array(
[[1.083029353267698e-10, 2.449965303168024e-11],
[2.397085162969853e-02, 3.590779671820755e-08],
[2.830254190078299e-04, 1.744709918330393e-01]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_binomial(self):
random = Generator(MT19937(self.seed))
actual = random.binomial(100.123, .456, size=(3, 2))
desired = np.array([[42, 41],
[42, 48],
[44, 50]])
assert_array_equal(actual, desired)
random = Generator(MT19937(self.seed))
actual = random.binomial(100.123, .456)
desired = 42
assert_array_equal(actual, desired)
def test_chisquare(self):
random = Generator(MT19937(self.seed))
actual = random.chisquare(50, size=(3, 2))
desired = np.array([[32.9850547060149, 39.0219480493301],
[56.2006134779419, 57.3474165711485],
[55.4243733880198, 55.4209797925213]])
assert_array_almost_equal(actual, desired, decimal=13)
def test_dirichlet(self):
random = Generator(MT19937(self.seed))
alpha = np.array([51.72840233779265162, 39.74494232180943953])
actual = random.dirichlet(alpha, size=(3, 2))
desired = np.array([[[0.5439892869558927, 0.45601071304410745],
[0.5588917345860708, 0.4411082654139292 ]],
[[0.5632074165063435, 0.43679258349365657],
[0.54862581112627, 0.45137418887373015]],
[[0.49961831357047226, 0.5003816864295278 ],
[0.52374806183482, 0.47625193816517997]]])
assert_array_almost_equal(actual, desired, decimal=15)
bad_alpha = np.array([5.4e-01, -1.0e-16])
assert_raises(ValueError, random.dirichlet, bad_alpha)
random = Generator(MT19937(self.seed))
alpha = np.array([51.72840233779265162, 39.74494232180943953])
actual = random.dirichlet(alpha)
assert_array_almost_equal(actual, desired[0, 0], decimal=15)
def test_dirichlet_size(self):
# gh-3173
p = np.array([51.72840233779265162, 39.74494232180943953])
assert_equal(random.dirichlet(p, np.uint32(1)).shape, (1, 2))
assert_equal(random.dirichlet(p, np.uint32(1)).shape, (1, 2))
assert_equal(random.dirichlet(p, np.uint32(1)).shape, (1, 2))
assert_equal(random.dirichlet(p, [2, 2]).shape, (2, 2, 2))
assert_equal(random.dirichlet(p, (2, 2)).shape, (2, 2, 2))
assert_equal(random.dirichlet(p, np.array((2, 2))).shape, (2, 2, 2))
assert_raises(TypeError, random.dirichlet, p, float(1))
def test_dirichlet_bad_alpha(self):
# gh-2089
alpha = np.array([5.4e-01, -1.0e-16])
assert_raises(ValueError, random.dirichlet, alpha)
# gh-15876
assert_raises(ValueError, random.dirichlet, [[5, 1]])
assert_raises(ValueError, random.dirichlet, [[5], [1]])
assert_raises(ValueError, random.dirichlet, [[[5], [1]], [[1], [5]]])
assert_raises(ValueError, random.dirichlet, np.array([[5, 1], [1, 5]]))
def test_dirichlet_alpha_non_contiguous(self):
a = np.array([51.72840233779265162, -1.0, 39.74494232180943953])
alpha = a[::2]
random = Generator(MT19937(self.seed))
non_contig = random.dirichlet(alpha, size=(3, 2))
random = Generator(MT19937(self.seed))
contig = random.dirichlet(np.ascontiguousarray(alpha),
size=(3, 2))
assert_array_almost_equal(non_contig, contig)
def test_dirichlet_small_alpha(self):
eps = 1.0e-9 # 1.0e-10 -> runtime x 10; 1e-11 -> runtime x 200, etc.
alpha = eps * np.array([1., 1.0e-3])
random = Generator(MT19937(self.seed))
actual = random.dirichlet(alpha, size=(3, 2))
expected = np.array([
[[1., 0.],
[1., 0.]],
[[1., 0.],
[1., 0.]],
[[1., 0.],
[1., 0.]]
])
assert_array_almost_equal(actual, expected, decimal=15)
@pytest.mark.slow
def test_dirichlet_moderately_small_alpha(self):
# Use alpha.max() < 0.1 to trigger stick breaking code path
alpha = np.array([0.02, 0.04, 0.03])
exact_mean = alpha / alpha.sum()
random = Generator(MT19937(self.seed))
sample = random.dirichlet(alpha, size=20000000)
sample_mean = sample.mean(axis=0)
assert_allclose(sample_mean, exact_mean, rtol=1e-3)
def test_exponential(self):
random = Generator(MT19937(self.seed))
actual = random.exponential(1.1234, size=(3, 2))
desired = np.array([[0.098845481066258, 1.560752510746964],
[0.075730916041636, 1.769098974710777],
[1.488602544592235, 2.49684815275751 ]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_exponential_0(self):
assert_equal(random.exponential(scale=0), 0)
assert_raises(ValueError, random.exponential, scale=-0.)
def test_f(self):
random = Generator(MT19937(self.seed))
actual = random.f(12, 77, size=(3, 2))
desired = np.array([[0.461720027077085, 1.100441958872451],
[1.100337455217484, 0.91421736740018 ],
[0.500811891303113, 0.826802454552058]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_gamma(self):
random = Generator(MT19937(self.seed))
actual = random.gamma(5, 3, size=(3, 2))
desired = np.array([[ 5.03850858902096, 7.9228656732049 ],
[18.73983605132985, 19.57961681699238],
[18.17897755150825, 18.17653912505234]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_gamma_0(self):
assert_equal(random.gamma(shape=0, scale=0), 0)
assert_raises(ValueError, random.gamma, shape=-0., scale=-0.)
def test_geometric(self):
random = Generator(MT19937(self.seed))
actual = random.geometric(.123456789, size=(3, 2))
desired = np.array([[ 1, 10],
[ 1, 12],
[ 9, 10]])
assert_array_equal(actual, desired)
def test_geometric_exceptions(self):
assert_raises(ValueError, random.geometric, 1.1)
assert_raises(ValueError, random.geometric, [1.1] * 10)
assert_raises(ValueError, random.geometric, -0.1)
assert_raises(ValueError, random.geometric, [-0.1] * 10)
with np.errstate(invalid='ignore'):
assert_raises(ValueError, random.geometric, np.nan)
assert_raises(ValueError, random.geometric, [np.nan] * 10)
def test_gumbel(self):
random = Generator(MT19937(self.seed))
actual = random.gumbel(loc=.123456789, scale=2.0, size=(3, 2))
desired = np.array([[ 4.688397515056245, -0.289514845417841],
[ 4.981176042584683, -0.633224272589149],
[-0.055915275687488, -0.333962478257953]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_gumbel_0(self):
assert_equal(random.gumbel(scale=0), 0)
assert_raises(ValueError, random.gumbel, scale=-0.)
def test_hypergeometric(self):
random = Generator(MT19937(self.seed))
actual = random.hypergeometric(10.1, 5.5, 14, size=(3, 2))
desired = np.array([[ 9, 9],
[ 9, 9],
[10, 9]])
assert_array_equal(actual, desired)
# Test nbad = 0
actual = random.hypergeometric(5, 0, 3, size=4)
desired = np.array([3, 3, 3, 3])
assert_array_equal(actual, desired)
actual = random.hypergeometric(15, 0, 12, size=4)
desired = np.array([12, 12, 12, 12])
assert_array_equal(actual, desired)
# Test ngood = 0
actual = random.hypergeometric(0, 5, 3, size=4)
desired = np.array([0, 0, 0, 0])
assert_array_equal(actual, desired)
actual = random.hypergeometric(0, 15, 12, size=4)
desired = np.array([0, 0, 0, 0])
assert_array_equal(actual, desired)
def test_laplace(self):
random = Generator(MT19937(self.seed))
actual = random.laplace(loc=.123456789, scale=2.0, size=(3, 2))
desired = np.array([[-3.156353949272393, 1.195863024830054],
[-3.435458081645966, 1.656882398925444],
[ 0.924824032467446, 1.251116432209336]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_laplace_0(self):
assert_equal(random.laplace(scale=0), 0)
assert_raises(ValueError, random.laplace, scale=-0.)
def test_logistic(self):
random = Generator(MT19937(self.seed))
actual = random.logistic(loc=.123456789, scale=2.0, size=(3, 2))
desired = np.array([[-4.338584631510999, 1.890171436749954],
[-4.64547787337966 , 2.514545562919217],
[ 1.495389489198666, 1.967827627577474]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_lognormal(self):
random = Generator(MT19937(self.seed))
actual = random.lognormal(mean=.123456789, sigma=2.0, size=(3, 2))
desired = np.array([[ 0.0268252166335, 13.9534486483053],
[ 0.1204014788936, 2.2422077497792],
[ 4.2484199496128, 12.0093343977523]])
assert_array_almost_equal(actual, desired, decimal=13)
def test_lognormal_0(self):
assert_equal(random.lognormal(sigma=0), 1)
assert_raises(ValueError, random.lognormal, sigma=-0.)
def test_logseries(self):
random = Generator(MT19937(self.seed))
actual = random.logseries(p=.923456789, size=(3, 2))
desired = np.array([[14, 17],
[3, 18],
[5, 1]])
assert_array_equal(actual, desired)
def test_logseries_exceptions(self):
with np.errstate(invalid='ignore'):
assert_raises(ValueError, random.logseries, np.nan)
assert_raises(ValueError, random.logseries, [np.nan] * 10)
def test_multinomial(self):
random = Generator(MT19937(self.seed))
actual = random.multinomial(20, [1 / 6.] * 6, size=(3, 2))
desired = np.array([[[1, 5, 1, 6, 4, 3],
[4, 2, 6, 2, 4, 2]],
[[5, 3, 2, 6, 3, 1],
[4, 4, 0, 2, 3, 7]],
[[6, 3, 1, 5, 3, 2],
[5, 5, 3, 1, 2, 4]]])
assert_array_equal(actual, desired)
@pytest.mark.parametrize("method", ["svd", "eigh", "cholesky"])
def test_multivariate_normal(self, method):
random = Generator(MT19937(self.seed))
mean = (.123456789, 10)
cov = [[1, 0], [0, 1]]
size = (3, 2)
actual = random.multivariate_normal(mean, cov, size, method=method)
desired = np.array([[[-1.747478062846581, 11.25613495182354 ],
[-0.9967333370066214, 10.342002097029821 ]],
[[ 0.7850019631242964, 11.181113712443013 ],
[ 0.8901349653255224, 8.873825399642492 ]],
[[ 0.7130260107430003, 9.551628690083056 ],
[ 0.7127098726541128, 11.991709234143173 ]]])
assert_array_almost_equal(actual, desired, decimal=15)
# Check for default size, was raising deprecation warning
actual = random.multivariate_normal(mean, cov, method=method)
desired = np.array([0.233278563284287, 9.424140804347195])
assert_array_almost_equal(actual, desired, decimal=15)
# Check that non symmetric covariance input raises exception when
# check_valid='raises' if using default svd method.
mean = [0, 0]
cov = [[1, 2], [1, 2]]
assert_raises(ValueError, random.multivariate_normal, mean, cov,
check_valid='raise')
# Check that non positive-semidefinite covariance warns with
# RuntimeWarning
cov = [[1, 2], [2, 1]]
assert_warns(RuntimeWarning, random.multivariate_normal, mean, cov)
assert_warns(RuntimeWarning, random.multivariate_normal, mean, cov,
method='eigh')
assert_raises(LinAlgError, random.multivariate_normal, mean, cov,
method='cholesky')
# and that it doesn't warn with RuntimeWarning check_valid='ignore'
assert_no_warnings(random.multivariate_normal, mean, cov,
check_valid='ignore')
# and that it raises with RuntimeWarning check_valid='raises'
assert_raises(ValueError, random.multivariate_normal, mean, cov,
check_valid='raise')
assert_raises(ValueError, random.multivariate_normal, mean, cov,
check_valid='raise', method='eigh')
# check degenerate samples from singular covariance matrix
cov = [[1, 1], [1, 1]]
if method in ('svd', 'eigh'):
samples = random.multivariate_normal(mean, cov, size=(3, 2),
method=method)
assert_array_almost_equal(samples[..., 0], samples[..., 1],
decimal=6)
else:
assert_raises(LinAlgError, random.multivariate_normal, mean, cov,
method='cholesky')
cov = np.array([[1, 0.1], [0.1, 1]], dtype=np.float32)
with suppress_warnings() as sup:
random.multivariate_normal(mean, cov, method=method)
w = sup.record(RuntimeWarning)
assert len(w) == 0
mu = np.zeros(2)
cov = np.eye(2)
assert_raises(ValueError, random.multivariate_normal, mean, cov,
check_valid='other')
assert_raises(ValueError, random.multivariate_normal,
np.zeros((2, 1, 1)), cov)
assert_raises(ValueError, random.multivariate_normal,
mu, np.empty((3, 2)))
assert_raises(ValueError, random.multivariate_normal,
mu, np.eye(3))
@pytest.mark.parametrize("method", ["svd", "eigh", "cholesky"])
def test_multivariate_normal_basic_stats(self, method):
random = Generator(MT19937(self.seed))
n_s = 1000
mean = np.array([1, 2])
cov = np.array([[2, 1], [1, 2]])
s = random.multivariate_normal(mean, cov, size=(n_s,), method=method)
s_center = s - mean
cov_emp = (s_center.T @ s_center) / (n_s - 1)
# these are pretty loose and are only designed to detect major errors
assert np.all(np.abs(s_center.mean(-2)) < 0.1)
assert np.all(np.abs(cov_emp - cov) < 0.2)
def test_negative_binomial(self):
random = Generator(MT19937(self.seed))
actual = random.negative_binomial(n=100, p=.12345, size=(3, 2))
desired = np.array([[543, 727],
[775, 760],
[600, 674]])
assert_array_equal(actual, desired)
def test_negative_binomial_exceptions(self):
with np.errstate(invalid='ignore'):
assert_raises(ValueError, random.negative_binomial, 100, np.nan)
assert_raises(ValueError, random.negative_binomial, 100,
[np.nan] * 10)
def test_negative_binomial_p0_exception(self):
# Verify that p=0 raises an exception.
with assert_raises(ValueError):
x = random.negative_binomial(1, 0)
def test_noncentral_chisquare(self):
random = Generator(MT19937(self.seed))
actual = random.noncentral_chisquare(df=5, nonc=5, size=(3, 2))
desired = np.array([[ 1.70561552362133, 15.97378184942111],
[13.71483425173724, 20.17859633310629],
[11.3615477156643 , 3.67891108738029]])
assert_array_almost_equal(actual, desired, decimal=14)
actual = random.noncentral_chisquare(df=.5, nonc=.2, size=(3, 2))
desired = np.array([[9.41427665607629e-04, 1.70473157518850e-04],
[1.14554372041263e+00, 1.38187755933435e-03],
[1.90659181905387e+00, 1.21772577941822e+00]])
assert_array_almost_equal(actual, desired, decimal=14)
random = Generator(MT19937(self.seed))
actual = random.noncentral_chisquare(df=5, nonc=0, size=(3, 2))
desired = np.array([[0.82947954590419, 1.80139670767078],
[6.58720057417794, 7.00491463609814],
[6.31101879073157, 6.30982307753005]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_noncentral_f(self):
random = Generator(MT19937(self.seed))
actual = random.noncentral_f(dfnum=5, dfden=2, nonc=1,
size=(3, 2))
desired = np.array([[0.060310671139 , 0.23866058175939],
[0.86860246709073, 0.2668510459738 ],
[0.23375780078364, 1.88922102885943]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_noncentral_f_nan(self):
random = Generator(MT19937(self.seed))
actual = random.noncentral_f(dfnum=5, dfden=2, nonc=np.nan)
assert np.isnan(actual)
def test_normal(self):
random = Generator(MT19937(self.seed))
actual = random.normal(loc=.123456789, scale=2.0, size=(3, 2))
desired = np.array([[-3.618412914693162, 2.635726692647081],
[-2.116923463013243, 0.807460983059643],
[ 1.446547137248593, 2.485684213886024]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_normal_0(self):
assert_equal(random.normal(scale=0), 0)
assert_raises(ValueError, random.normal, scale=-0.)
def test_pareto(self):
random = Generator(MT19937(self.seed))
actual = random.pareto(a=.123456789, size=(3, 2))
desired = np.array([[1.0394926776069018e+00, 7.7142534343505773e+04],
[7.2640150889064703e-01, 3.4650454783825594e+05],
[4.5852344481994740e+04, 6.5851383009539105e+07]])
# For some reason on 32-bit x86 Ubuntu 12.10 the [1, 0] entry in this
# matrix differs by 24 nulps. Discussion:
# https://mail.python.org/pipermail/numpy-discussion/2012-September/063801.html
# Consensus is that this is probably some gcc quirk that affects
# rounding but not in any important way, so we just use a looser
# tolerance on this test:
np.testing.assert_array_almost_equal_nulp(actual, desired, nulp=30)
def test_poisson(self):
random = Generator(MT19937(self.seed))
actual = random.poisson(lam=.123456789, size=(3, 2))
desired = np.array([[0, 0],
[0, 0],
[0, 0]])
assert_array_equal(actual, desired)
def test_poisson_exceptions(self):
lambig = np.iinfo('int64').max
lamneg = -1
assert_raises(ValueError, random.poisson, lamneg)
assert_raises(ValueError, random.poisson, [lamneg] * 10)
assert_raises(ValueError, random.poisson, lambig)
assert_raises(ValueError, random.poisson, [lambig] * 10)
with np.errstate(invalid='ignore'):
assert_raises(ValueError, random.poisson, np.nan)
assert_raises(ValueError, random.poisson, [np.nan] * 10)
def test_power(self):
random = Generator(MT19937(self.seed))
actual = random.power(a=.123456789, size=(3, 2))
desired = np.array([[1.977857368842754e-09, 9.806792196620341e-02],
[2.482442984543471e-10, 1.527108843266079e-01],
[8.188283434244285e-02, 3.950547209346948e-01]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_rayleigh(self):
random = Generator(MT19937(self.seed))
actual = random.rayleigh(scale=10, size=(3, 2))
desired = np.array([[ 4.51734079831581, 15.6802442485758 ],
[ 4.19850651287094, 17.08718809823704],
[14.7907457708776 , 15.85545333419775]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_rayleigh_0(self):
assert_equal(random.rayleigh(scale=0), 0)
assert_raises(ValueError, random.rayleigh, scale=-0.)
def test_standard_cauchy(self):
random = Generator(MT19937(self.seed))
actual = random.standard_cauchy(size=(3, 2))
desired = np.array([[-1.489437778266206, -3.275389641569784],
[ 0.560102864910406, -0.680780916282552],
[-1.314912905226277, 0.295852965660225]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_standard_exponential(self):
random = Generator(MT19937(self.seed))
actual = random.standard_exponential(size=(3, 2), method='inv')
desired = np.array([[0.102031839440643, 1.229350298474972],
[0.088137284693098, 1.459859985522667],
[1.093830802293668, 1.256977002164613]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_standard_expoential_type_error(self):
assert_raises(TypeError, random.standard_exponential, dtype=np.int32)
def test_standard_gamma(self):
random = Generator(MT19937(self.seed))
actual = random.standard_gamma(shape=3, size=(3, 2))
desired = np.array([[0.62970724056362, 1.22379851271008],
[3.899412530884 , 4.12479964250139],
[3.74994102464584, 3.74929307690815]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_standard_gammma_scalar_float(self):
random = Generator(MT19937(self.seed))
actual = random.standard_gamma(3, dtype=np.float32)
desired = 2.9242148399353027
assert_array_almost_equal(actual, desired, decimal=6)
def test_standard_gamma_float(self):
random = Generator(MT19937(self.seed))
actual = random.standard_gamma(shape=3, size=(3, 2))
desired = np.array([[0.62971, 1.2238 ],
[3.89941, 4.1248 ],
[3.74994, 3.74929]])
assert_array_almost_equal(actual, desired, decimal=5)
def test_standard_gammma_float_out(self):
actual = np.zeros((3, 2), dtype=np.float32)
random = Generator(MT19937(self.seed))
random.standard_gamma(10.0, out=actual, dtype=np.float32)
desired = np.array([[10.14987, 7.87012],
[ 9.46284, 12.56832],
[13.82495, 7.81533]], dtype=np.float32)
assert_array_almost_equal(actual, desired, decimal=5)
random = Generator(MT19937(self.seed))
random.standard_gamma(10.0, out=actual, size=(3, 2), dtype=np.float32)
assert_array_almost_equal(actual, desired, decimal=5)
def test_standard_gamma_unknown_type(self):
assert_raises(TypeError, random.standard_gamma, 1.,
dtype='int32')
def test_out_size_mismatch(self):
out = np.zeros(10)
assert_raises(ValueError, random.standard_gamma, 10.0, size=20,
out=out)
assert_raises(ValueError, random.standard_gamma, 10.0, size=(10, 1),
out=out)
def test_standard_gamma_0(self):
assert_equal(random.standard_gamma(shape=0), 0)
assert_raises(ValueError, random.standard_gamma, shape=-0.)
def test_standard_normal(self):
random = Generator(MT19937(self.seed))
actual = random.standard_normal(size=(3, 2))
desired = np.array([[-1.870934851846581, 1.25613495182354 ],
[-1.120190126006621, 0.342002097029821],
[ 0.661545174124296, 1.181113712443012]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_standard_normal_unsupported_type(self):
assert_raises(TypeError, random.standard_normal, dtype=np.int32)
def test_standard_t(self):
random = Generator(MT19937(self.seed))
actual = random.standard_t(df=10, size=(3, 2))
desired = np.array([[-1.484666193042647, 0.30597891831161 ],
[ 1.056684299648085, -0.407312602088507],
[ 0.130704414281157, -2.038053410490321]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_triangular(self):
random = Generator(MT19937(self.seed))
actual = random.triangular(left=5.12, mode=10.23, right=20.34,
size=(3, 2))
desired = np.array([[ 7.86664070590917, 13.6313848513185 ],
[ 7.68152445215983, 14.36169131136546],
[13.16105603911429, 13.72341621856971]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_uniform(self):
random = Generator(MT19937(self.seed))
actual = random.uniform(low=1.23, high=10.54, size=(3, 2))
desired = np.array([[2.13306255040998 , 7.816987531021207],
[2.015436610109887, 8.377577533009589],
[7.421792588856135, 7.891185744455209]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_uniform_range_bounds(self):
fmin = np.finfo('float').min
fmax = np.finfo('float').max
func = random.uniform
assert_raises(OverflowError, func, -np.inf, 0)
assert_raises(OverflowError, func, 0, np.inf)
assert_raises(OverflowError, func, fmin, fmax)
assert_raises(OverflowError, func, [-np.inf], [0])
assert_raises(OverflowError, func, [0], [np.inf])
# (fmax / 1e17) - fmin is within range, so this should not throw
# account for i386 extended precision DBL_MAX / 1e17 + DBL_MAX >
# DBL_MAX by increasing fmin a bit
random.uniform(low=np.nextafter(fmin, 1), high=fmax / 1e17)
def test_scalar_exception_propagation(self):
# Tests that exceptions are correctly propagated in distributions
# when called with objects that throw exceptions when converted to
# scalars.
#
# Regression test for gh: 8865
class ThrowingFloat(np.ndarray):
def __float__(self):
raise TypeError
throwing_float = np.array(1.0).view(ThrowingFloat)
assert_raises(TypeError, random.uniform, throwing_float,
throwing_float)
class ThrowingInteger(np.ndarray):
def __int__(self):
raise TypeError
throwing_int = np.array(1).view(ThrowingInteger)
assert_raises(TypeError, random.hypergeometric, throwing_int, 1, 1)
def test_vonmises(self):
random = Generator(MT19937(self.seed))
actual = random.vonmises(mu=1.23, kappa=1.54, size=(3, 2))
desired = np.array([[ 1.107972248690106, 2.841536476232361],
[ 1.832602376042457, 1.945511926976032],
[-0.260147475776542, 2.058047492231698]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_vonmises_small(self):
# check infinite loop, gh-4720
random = Generator(MT19937(self.seed))
r = random.vonmises(mu=0., kappa=1.1e-8, size=10**6)
assert_(np.isfinite(r).all())
def test_vonmises_nan(self):
random = Generator(MT19937(self.seed))
r = random.vonmises(mu=0., kappa=np.nan)
assert_(np.isnan(r))
def test_wald(self):
random = Generator(MT19937(self.seed))
actual = random.wald(mean=1.23, scale=1.54, size=(3, 2))
desired = np.array([[0.26871721804551, 3.2233942732115 ],
[2.20328374987066, 2.40958405189353],
[2.07093587449261, 0.73073890064369]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_weibull(self):
random = Generator(MT19937(self.seed))
actual = random.weibull(a=1.23, size=(3, 2))
desired = np.array([[0.138613914769468, 1.306463419753191],
[0.111623365934763, 1.446570494646721],
[1.257145775276011, 1.914247725027957]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_weibull_0(self):
random = Generator(MT19937(self.seed))
assert_equal(random.weibull(a=0, size=12), np.zeros(12))
assert_raises(ValueError, random.weibull, a=-0.)
def test_zipf(self):
random = Generator(MT19937(self.seed))
actual = random.zipf(a=1.23, size=(3, 2))
desired = np.array([[ 1, 1],
[ 10, 867],
[354, 2]])
assert_array_equal(actual, desired)
class TestBroadcast:
# tests that functions that broadcast behave
# correctly when presented with non-scalar arguments
def setup(self):
self.seed = 123456789
def test_uniform(self):
random = Generator(MT19937(self.seed))
low = [0]
high = [1]
uniform = random.uniform
desired = np.array([0.16693771389729, 0.19635129550675, 0.75563050964095])
random = Generator(MT19937(self.seed))
actual = random.uniform(low * 3, high)
assert_array_almost_equal(actual, desired, decimal=14)
random = Generator(MT19937(self.seed))
actual = random.uniform(low, high * 3)
assert_array_almost_equal(actual, desired, decimal=14)
def test_normal(self):
loc = [0]
scale = [1]
bad_scale = [-1]
random = Generator(MT19937(self.seed))
desired = np.array([-0.38736406738527, 0.79594375042255, 0.0197076236097])
random = Generator(MT19937(self.seed))
actual = random.normal(loc * 3, scale)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.normal, loc * 3, bad_scale)
random = Generator(MT19937(self.seed))
normal = random.normal
actual = normal(loc, scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, normal, loc, bad_scale * 3)
def test_beta(self):
a = [1]
b = [2]
bad_a = [-1]
bad_b = [-2]
desired = np.array([0.18719338682602, 0.73234824491364, 0.17928615186455])
random = Generator(MT19937(self.seed))
beta = random.beta
actual = beta(a * 3, b)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, beta, bad_a * 3, b)
assert_raises(ValueError, beta, a * 3, bad_b)
random = Generator(MT19937(self.seed))
actual = random.beta(a, b * 3)
assert_array_almost_equal(actual, desired, decimal=14)
def test_exponential(self):
scale = [1]
bad_scale = [-1]
desired = np.array([0.67245993212806, 0.21380495318094, 0.7177848928629])
random = Generator(MT19937(self.seed))
actual = random.exponential(scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.exponential, bad_scale * 3)
def test_standard_gamma(self):
shape = [1]
bad_shape = [-1]
desired = np.array([0.67245993212806, 0.21380495318094, 0.7177848928629])
random = Generator(MT19937(self.seed))
std_gamma = random.standard_gamma
actual = std_gamma(shape * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, std_gamma, bad_shape * 3)
def test_gamma(self):
shape = [1]
scale = [2]
bad_shape = [-1]
bad_scale = [-2]
desired = np.array([1.34491986425611, 0.42760990636187, 1.4355697857258])
random = Generator(MT19937(self.seed))
gamma = random.gamma
actual = gamma(shape * 3, scale)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, gamma, bad_shape * 3, scale)
assert_raises(ValueError, gamma, shape * 3, bad_scale)
random = Generator(MT19937(self.seed))
gamma = random.gamma
actual = gamma(shape, scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, gamma, bad_shape, scale * 3)
assert_raises(ValueError, gamma, shape, bad_scale * 3)
def test_f(self):
dfnum = [1]
dfden = [2]
bad_dfnum = [-1]
bad_dfden = [-2]
desired = np.array([0.07765056244107, 7.72951397913186, 0.05786093891763])
random = Generator(MT19937(self.seed))
f = random.f
actual = f(dfnum * 3, dfden)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, f, bad_dfnum * 3, dfden)
assert_raises(ValueError, f, dfnum * 3, bad_dfden)
random = Generator(MT19937(self.seed))
f = random.f
actual = f(dfnum, dfden * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, f, bad_dfnum, dfden * 3)
assert_raises(ValueError, f, dfnum, bad_dfden * 3)
def test_noncentral_f(self):
dfnum = [2]
dfden = [3]
nonc = [4]
bad_dfnum = [0]
bad_dfden = [-1]
bad_nonc = [-2]
desired = np.array([2.02434240411421, 12.91838601070124, 1.24395160354629])
random = Generator(MT19937(self.seed))
nonc_f = random.noncentral_f
actual = nonc_f(dfnum * 3, dfden, nonc)
assert_array_almost_equal(actual, desired, decimal=14)
assert np.all(np.isnan(nonc_f(dfnum, dfden, [np.nan] * 3)))
assert_raises(ValueError, nonc_f, bad_dfnum * 3, dfden, nonc)
assert_raises(ValueError, nonc_f, dfnum * 3, bad_dfden, nonc)
assert_raises(ValueError, nonc_f, dfnum * 3, dfden, bad_nonc)
random = Generator(MT19937(self.seed))
nonc_f = random.noncentral_f
actual = nonc_f(dfnum, dfden * 3, nonc)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, nonc_f, bad_dfnum, dfden * 3, nonc)
assert_raises(ValueError, nonc_f, dfnum, bad_dfden * 3, nonc)
assert_raises(ValueError, nonc_f, dfnum, dfden * 3, bad_nonc)
random = Generator(MT19937(self.seed))
nonc_f = random.noncentral_f
actual = nonc_f(dfnum, dfden, nonc * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, nonc_f, bad_dfnum, dfden, nonc * 3)
assert_raises(ValueError, nonc_f, dfnum, bad_dfden, nonc * 3)
assert_raises(ValueError, nonc_f, dfnum, dfden, bad_nonc * 3)
def test_noncentral_f_small_df(self):
random = Generator(MT19937(self.seed))
desired = np.array([0.04714867120827, 0.1239390327694])
actual = random.noncentral_f(0.9, 0.9, 2, size=2)
assert_array_almost_equal(actual, desired, decimal=14)
def test_chisquare(self):
df = [1]
bad_df = [-1]
desired = np.array([0.05573640064251, 1.47220224353539, 2.9469379318589])
random = Generator(MT19937(self.seed))
actual = random.chisquare(df * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.chisquare, bad_df * 3)
def test_noncentral_chisquare(self):
df = [1]
nonc = [2]
bad_df = [-1]
bad_nonc = [-2]
desired = np.array([0.07710766249436, 5.27829115110304, 0.630732147399])
random = Generator(MT19937(self.seed))
nonc_chi = random.noncentral_chisquare
actual = nonc_chi(df * 3, nonc)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, nonc_chi, bad_df * 3, nonc)
assert_raises(ValueError, nonc_chi, df * 3, bad_nonc)
random = Generator(MT19937(self.seed))
nonc_chi = random.noncentral_chisquare
actual = nonc_chi(df, nonc * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, nonc_chi, bad_df, nonc * 3)
assert_raises(ValueError, nonc_chi, df, bad_nonc * 3)
def test_standard_t(self):
df = [1]
bad_df = [-1]
desired = np.array([-1.39498829447098, -1.23058658835223, 0.17207021065983])
random = Generator(MT19937(self.seed))
actual = random.standard_t(df * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.standard_t, bad_df * 3)
def test_vonmises(self):
mu = [2]
kappa = [1]
bad_kappa = [-1]
desired = np.array([2.25935584988528, 2.23326261461399, -2.84152146503326])
random = Generator(MT19937(self.seed))
actual = random.vonmises(mu * 3, kappa)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.vonmises, mu * 3, bad_kappa)
random = Generator(MT19937(self.seed))
actual = random.vonmises(mu, kappa * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.vonmises, mu, bad_kappa * 3)
def test_pareto(self):
a = [1]
bad_a = [-1]
desired = np.array([0.95905052946317, 0.2383810889437 , 1.04988745750013])
random = Generator(MT19937(self.seed))
actual = random.pareto(a * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.pareto, bad_a * 3)
def test_weibull(self):
a = [1]
bad_a = [-1]
desired = np.array([0.67245993212806, 0.21380495318094, 0.7177848928629])
random = Generator(MT19937(self.seed))
actual = random.weibull(a * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.weibull, bad_a * 3)
def test_power(self):
a = [1]
bad_a = [-1]
desired = np.array([0.48954864361052, 0.19249412888486, 0.51216834058807])
random = Generator(MT19937(self.seed))
actual = random.power(a * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.power, bad_a * 3)
def test_laplace(self):
loc = [0]
scale = [1]
bad_scale = [-1]
desired = np.array([-1.09698732625119, -0.93470271947368, 0.71592671378202])
random = Generator(MT19937(self.seed))
laplace = random.laplace
actual = laplace(loc * 3, scale)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, laplace, loc * 3, bad_scale)
random = Generator(MT19937(self.seed))
laplace = random.laplace
actual = laplace(loc, scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, laplace, loc, bad_scale * 3)
def test_gumbel(self):
loc = [0]
scale = [1]
bad_scale = [-1]
desired = np.array([1.70020068231762, 1.52054354273631, -0.34293267607081])
random = Generator(MT19937(self.seed))
gumbel = random.gumbel
actual = gumbel(loc * 3, scale)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, gumbel, loc * 3, bad_scale)
random = Generator(MT19937(self.seed))
gumbel = random.gumbel
actual = gumbel(loc, scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, gumbel, loc, bad_scale * 3)
def test_logistic(self):
loc = [0]
scale = [1]
bad_scale = [-1]
desired = np.array([-1.607487640433, -1.40925686003678, 1.12887112820397])
random = Generator(MT19937(self.seed))
actual = random.logistic(loc * 3, scale)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.logistic, loc * 3, bad_scale)
random = Generator(MT19937(self.seed))
actual = random.logistic(loc, scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.logistic, loc, bad_scale * 3)
assert_equal(random.logistic(1.0, 0.0), 1.0)
def test_lognormal(self):
mean = [0]
sigma = [1]
bad_sigma = [-1]
desired = np.array([0.67884390500697, 2.21653186290321, 1.01990310084276])
random = Generator(MT19937(self.seed))
lognormal = random.lognormal
actual = lognormal(mean * 3, sigma)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, lognormal, mean * 3, bad_sigma)
random = Generator(MT19937(self.seed))
actual = random.lognormal(mean, sigma * 3)
assert_raises(ValueError, random.lognormal, mean, bad_sigma * 3)
def test_rayleigh(self):
scale = [1]
bad_scale = [-1]
desired = np.array([0.60439534475066, 0.66120048396359, 1.67873398389499])
random = Generator(MT19937(self.seed))
actual = random.rayleigh(scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.rayleigh, bad_scale * 3)
def test_wald(self):
mean = [0.5]
scale = [1]
bad_mean = [0]
bad_scale = [-2]
desired = np.array([0.38052407392905, 0.50701641508592, 0.484935249864])
random = Generator(MT19937(self.seed))
actual = random.wald(mean * 3, scale)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.wald, bad_mean * 3, scale)
assert_raises(ValueError, random.wald, mean * 3, bad_scale)
random = Generator(MT19937(self.seed))
actual = random.wald(mean, scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.wald, bad_mean, scale * 3)
assert_raises(ValueError, random.wald, mean, bad_scale * 3)
def test_triangular(self):
left = [1]
right = [3]
mode = [2]
bad_left_one = [3]
bad_mode_one = [4]
bad_left_two, bad_mode_two = right * 2
desired = np.array([1.57781954604754, 1.62665986867957, 2.30090130831326])
random = Generator(MT19937(self.seed))
triangular = random.triangular
actual = triangular(left * 3, mode, right)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, triangular, bad_left_one * 3, mode, right)
assert_raises(ValueError, triangular, left * 3, bad_mode_one, right)
assert_raises(ValueError, triangular, bad_left_two * 3, bad_mode_two,
right)
random = Generator(MT19937(self.seed))
triangular = random.triangular
actual = triangular(left, mode * 3, right)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, triangular, bad_left_one, mode * 3, right)
assert_raises(ValueError, triangular, left, bad_mode_one * 3, right)
assert_raises(ValueError, triangular, bad_left_two, bad_mode_two * 3,
right)
random = Generator(MT19937(self.seed))
triangular = random.triangular
actual = triangular(left, mode, right * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, triangular, bad_left_one, mode, right * 3)
assert_raises(ValueError, triangular, left, bad_mode_one, right * 3)
assert_raises(ValueError, triangular, bad_left_two, bad_mode_two,
right * 3)
assert_raises(ValueError, triangular, 10., 0., 20.)
assert_raises(ValueError, triangular, 10., 25., 20.)
assert_raises(ValueError, triangular, 10., 10., 10.)
def test_binomial(self):
n = [1]
p = [0.5]
bad_n = [-1]
bad_p_one = [-1]
bad_p_two = [1.5]
desired = np.array([0, 0, 1])
random = Generator(MT19937(self.seed))
binom = random.binomial
actual = binom(n * 3, p)
assert_array_equal(actual, desired)
assert_raises(ValueError, binom, bad_n * 3, p)
assert_raises(ValueError, binom, n * 3, bad_p_one)
assert_raises(ValueError, binom, n * 3, bad_p_two)
random = Generator(MT19937(self.seed))
actual = random.binomial(n, p * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, binom, bad_n, p * 3)
assert_raises(ValueError, binom, n, bad_p_one * 3)
assert_raises(ValueError, binom, n, bad_p_two * 3)
def test_negative_binomial(self):
n = [1]
p = [0.5]
bad_n = [-1]
bad_p_one = [-1]
bad_p_two = [1.5]
desired = np.array([0, 2, 1], dtype=np.int64)
random = Generator(MT19937(self.seed))
neg_binom = random.negative_binomial
actual = neg_binom(n * 3, p)
assert_array_equal(actual, desired)
assert_raises(ValueError, neg_binom, bad_n * 3, p)
assert_raises(ValueError, neg_binom, n * 3, bad_p_one)
assert_raises(ValueError, neg_binom, n * 3, bad_p_two)
random = Generator(MT19937(self.seed))
neg_binom = random.negative_binomial
actual = neg_binom(n, p * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, neg_binom, bad_n, p * 3)
assert_raises(ValueError, neg_binom, n, bad_p_one * 3)
assert_raises(ValueError, neg_binom, n, bad_p_two * 3)
def test_poisson(self):
lam = [1]
bad_lam_one = [-1]
desired = np.array([0, 0, 3])
random = Generator(MT19937(self.seed))
max_lam = random._poisson_lam_max
bad_lam_two = [max_lam * 2]
poisson = random.poisson
actual = poisson(lam * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, poisson, bad_lam_one * 3)
assert_raises(ValueError, poisson, bad_lam_two * 3)
def test_zipf(self):
a = [2]
bad_a = [0]
desired = np.array([1, 8, 1])
random = Generator(MT19937(self.seed))
zipf = random.zipf
actual = zipf(a * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, zipf, bad_a * 3)
with np.errstate(invalid='ignore'):
assert_raises(ValueError, zipf, np.nan)
assert_raises(ValueError, zipf, [0, 0, np.nan])
def test_geometric(self):
p = [0.5]
bad_p_one = [-1]
bad_p_two = [1.5]
desired = np.array([1, 1, 3])
random = Generator(MT19937(self.seed))
geometric = random.geometric
actual = geometric(p * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, geometric, bad_p_one * 3)
assert_raises(ValueError, geometric, bad_p_two * 3)
def test_hypergeometric(self):
ngood = [1]
nbad = [2]
nsample = [2]
bad_ngood = [-1]
bad_nbad = [-2]
bad_nsample_one = [-1]
bad_nsample_two = [4]
desired = np.array([0, 0, 1])
random = Generator(MT19937(self.seed))
actual = random.hypergeometric(ngood * 3, nbad, nsample)
assert_array_equal(actual, desired)
assert_raises(ValueError, random.hypergeometric, bad_ngood * 3, nbad, nsample)
assert_raises(ValueError, random.hypergeometric, ngood * 3, bad_nbad, nsample)
assert_raises(ValueError, random.hypergeometric, ngood * 3, nbad, bad_nsample_one)
assert_raises(ValueError, random.hypergeometric, ngood * 3, nbad, bad_nsample_two)
random = Generator(MT19937(self.seed))
actual = random.hypergeometric(ngood, nbad * 3, nsample)
assert_array_equal(actual, desired)
assert_raises(ValueError, random.hypergeometric, bad_ngood, nbad * 3, nsample)
assert_raises(ValueError, random.hypergeometric, ngood, bad_nbad * 3, nsample)
assert_raises(ValueError, random.hypergeometric, ngood, nbad * 3, bad_nsample_one)
assert_raises(ValueError, random.hypergeometric, ngood, nbad * 3, bad_nsample_two)
random = Generator(MT19937(self.seed))
hypergeom = random.hypergeometric
actual = hypergeom(ngood, nbad, nsample * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, hypergeom, bad_ngood, nbad, nsample * 3)
assert_raises(ValueError, hypergeom, ngood, bad_nbad, nsample * 3)
assert_raises(ValueError, hypergeom, ngood, nbad, bad_nsample_one * 3)
assert_raises(ValueError, hypergeom, ngood, nbad, bad_nsample_two * 3)
assert_raises(ValueError, hypergeom, -1, 10, 20)
assert_raises(ValueError, hypergeom, 10, -1, 20)
assert_raises(ValueError, hypergeom, 10, 10, -1)
assert_raises(ValueError, hypergeom, 10, 10, 25)
# ValueError for arguments that are too big.
assert_raises(ValueError, hypergeom, 2**30, 10, 20)
assert_raises(ValueError, hypergeom, 999, 2**31, 50)
assert_raises(ValueError, hypergeom, 999, [2**29, 2**30], 1000)
def test_logseries(self):
p = [0.5]
bad_p_one = [2]
bad_p_two = [-1]
desired = np.array([1, 1, 1])
random = Generator(MT19937(self.seed))
logseries = random.logseries
actual = logseries(p * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, logseries, bad_p_one * 3)
assert_raises(ValueError, logseries, bad_p_two * 3)
def test_multinomial(self):
random = Generator(MT19937(self.seed))
actual = random.multinomial([5, 20], [1 / 6.] * 6, size=(3, 2))
desired = np.array([[[0, 0, 2, 1, 2, 0],
[2, 3, 6, 4, 2, 3]],
[[1, 0, 1, 0, 2, 1],
[7, 2, 2, 1, 4, 4]],
[[0, 2, 0, 1, 2, 0],
[3, 2, 3, 3, 4, 5]]], dtype=np.int64)
assert_array_equal(actual, desired)
random = Generator(MT19937(self.seed))
actual = random.multinomial([5, 20], [1 / 6.] * 6)
desired = np.array([[0, 0, 2, 1, 2, 0],
[2, 3, 6, 4, 2, 3]], dtype=np.int64)
assert_array_equal(actual, desired)
class TestThread:
# make sure each state produces the same sequence even in threads
def setup(self):
self.seeds = range(4)
def check_function(self, function, sz):
from threading import Thread
out1 = np.empty((len(self.seeds),) + sz)
out2 = np.empty((len(self.seeds),) + sz)
# threaded generation
t = [Thread(target=function, args=(Generator(MT19937(s)), o))
for s, o in zip(self.seeds, out1)]
[x.start() for x in t]
[x.join() for x in t]
# the same serial
for s, o in zip(self.seeds, out2):
function(Generator(MT19937(s)), o)
# these platforms change x87 fpu precision mode in threads
if np.intp().dtype.itemsize == 4 and sys.platform == "win32":
assert_array_almost_equal(out1, out2)
else:
assert_array_equal(out1, out2)
def test_normal(self):
def gen_random(state, out):
out[...] = state.normal(size=10000)
self.check_function(gen_random, sz=(10000,))
def test_exp(self):
def gen_random(state, out):
out[...] = state.exponential(scale=np.ones((100, 1000)))
self.check_function(gen_random, sz=(100, 1000))
def test_multinomial(self):
def gen_random(state, out):
out[...] = state.multinomial(10, [1 / 6.] * 6, size=10000)
self.check_function(gen_random, sz=(10000, 6))
# See Issue #4263
class TestSingleEltArrayInput:
def setup(self):
self.argOne = np.array([2])
self.argTwo = np.array([3])
self.argThree = np.array([4])
self.tgtShape = (1,)
def test_one_arg_funcs(self):
funcs = (random.exponential, random.standard_gamma,
random.chisquare, random.standard_t,
random.pareto, random.weibull,
random.power, random.rayleigh,
random.poisson, random.zipf,
random.geometric, random.logseries)
probfuncs = (random.geometric, random.logseries)
for func in funcs:
if func in probfuncs: # p < 1.0
out = func(np.array([0.5]))
else:
out = func(self.argOne)
assert_equal(out.shape, self.tgtShape)
def test_two_arg_funcs(self):
funcs = (random.uniform, random.normal,
random.beta, random.gamma,
random.f, random.noncentral_chisquare,
random.vonmises, random.laplace,
random.gumbel, random.logistic,
random.lognormal, random.wald,
random.binomial, random.negative_binomial)
probfuncs = (random.binomial, random.negative_binomial)
for func in funcs:
if func in probfuncs: # p <= 1
argTwo = np.array([0.5])
else:
argTwo = self.argTwo
out = func(self.argOne, argTwo)
assert_equal(out.shape, self.tgtShape)
out = func(self.argOne[0], argTwo)
assert_equal(out.shape, self.tgtShape)
out = func(self.argOne, argTwo[0])
assert_equal(out.shape, self.tgtShape)
def test_integers(self, endpoint):
itype = [np.bool_, np.int8, np.uint8, np.int16, np.uint16,
np.int32, np.uint32, np.int64, np.uint64]
func = random.integers
high = np.array([1])
low = np.array([0])
for dt in itype:
out = func(low, high, endpoint=endpoint, dtype=dt)
assert_equal(out.shape, self.tgtShape)
out = func(low[0], high, endpoint=endpoint, dtype=dt)
assert_equal(out.shape, self.tgtShape)
out = func(low, high[0], endpoint=endpoint, dtype=dt)
assert_equal(out.shape, self.tgtShape)
def test_three_arg_funcs(self):
funcs = [random.noncentral_f, random.triangular,
random.hypergeometric]
for func in funcs:
out = func(self.argOne, self.argTwo, self.argThree)
assert_equal(out.shape, self.tgtShape)
out = func(self.argOne[0], self.argTwo, self.argThree)
assert_equal(out.shape, self.tgtShape)
out = func(self.argOne, self.argTwo[0], self.argThree)
assert_equal(out.shape, self.tgtShape)
@pytest.mark.parametrize("config", JUMP_TEST_DATA)
def test_jumped(config):
# Each config contains the initial seed, a number of raw steps
# the md5 hashes of the initial and the final states' keys and
# the position of of the initial and the final state.
# These were produced using the original C implementation.
seed = config["seed"]
steps = config["steps"]
mt19937 = MT19937(seed)
# Burn step
mt19937.random_raw(steps)
key = mt19937.state["state"]["key"]
if sys.byteorder == 'big':
key = key.byteswap()
md5 = hashlib.md5(key)
assert mt19937.state["state"]["pos"] == config["initial"]["pos"]
assert md5.hexdigest() == config["initial"]["key_md5"]
jumped = mt19937.jumped()
key = jumped.state["state"]["key"]
if sys.byteorder == 'big':
key = key.byteswap()
md5 = hashlib.md5(key)
assert jumped.state["state"]["pos"] == config["jumped"]["pos"]
assert md5.hexdigest() == config["jumped"]["key_md5"]
| 42.101667 | 90 | 0.581331 | import sys
import hashlib
import pytest
import numpy as np
from numpy.linalg import LinAlgError
from numpy.testing import (
assert_, assert_raises, assert_equal, assert_allclose,
assert_warns, assert_no_warnings, assert_array_equal,
assert_array_almost_equal, suppress_warnings)
from numpy.random import Generator, MT19937, SeedSequence
random = Generator(MT19937())
JUMP_TEST_DATA = [
{
"seed": 0,
"steps": 10,
"initial": {"key_md5": "64eaf265d2203179fb5ffb73380cd589", "pos": 9},
"jumped": {"key_md5": "8cb7b061136efceef5217a9ce2cc9a5a", "pos": 598},
},
{
"seed":384908324,
"steps":312,
"initial": {"key_md5": "e99708a47b82ff51a2c7b0625b81afb5", "pos": 311},
"jumped": {"key_md5": "2ecdbfc47a895b253e6e19ccb2e74b90", "pos": 276},
},
{
"seed": [839438204, 980239840, 859048019, 821],
"steps": 511,
"initial": {"key_md5": "9fcd6280df9199785e17e93162ce283c", "pos": 510},
"jumped": {"key_md5": "433b85229f2ed853cde06cd872818305", "pos": 475},
},
]
@pytest.fixture(scope='module', params=[True, False])
def endpoint(request):
return request.param
class TestSeed:
def test_scalar(self):
s = Generator(MT19937(0))
assert_equal(s.integers(1000), 479)
s = Generator(MT19937(4294967295))
assert_equal(s.integers(1000), 324)
def test_array(self):
s = Generator(MT19937(range(10)))
assert_equal(s.integers(1000), 465)
s = Generator(MT19937(np.arange(10)))
assert_equal(s.integers(1000), 465)
s = Generator(MT19937([0]))
assert_equal(s.integers(1000), 479)
s = Generator(MT19937([4294967295]))
assert_equal(s.integers(1000), 324)
def test_seedsequence(self):
s = MT19937(SeedSequence(0))
assert_equal(s.random_raw(1), 2058676884)
def test_invalid_scalar(self):
assert_raises(TypeError, MT19937, -0.5)
assert_raises(ValueError, MT19937, -1)
def test_invalid_array(self):
assert_raises(TypeError, MT19937, [-0.5])
assert_raises(ValueError, MT19937, [-1])
assert_raises(ValueError, MT19937, [1, -2, 4294967296])
def test_noninstantized_bitgen(self):
assert_raises(ValueError, Generator, MT19937)
class TestBinomial:
def test_n_zero(self):
zeros = np.zeros(2, dtype='int')
for p in [0, .5, 1]:
assert_(random.binomial(0, p) == 0)
assert_array_equal(random.binomial(zeros, p), zeros)
def test_p_is_nan(self):
assert_raises(ValueError, random.binomial, 1, np.nan)
class TestMultinomial:
def test_basic(self):
random.multinomial(100, [0.2, 0.8])
def test_zero_probability(self):
random.multinomial(100, [0.2, 0.8, 0.0, 0.0, 0.0])
def test_int_negative_interval(self):
assert_(-5 <= random.integers(-5, -1) < -1)
x = random.integers(-5, -1, 5)
assert_(np.all(-5 <= x))
assert_(np.all(x < -1))
def test_size(self):
p = [0.5, 0.5]
assert_equal(random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
assert_equal(random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
assert_equal(random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
assert_equal(random.multinomial(1, p, [2, 2]).shape, (2, 2, 2))
assert_equal(random.multinomial(1, p, (2, 2)).shape, (2, 2, 2))
assert_equal(random.multinomial(1, p, np.array((2, 2))).shape,
(2, 2, 2))
assert_raises(TypeError, random.multinomial, 1, p,
float(1))
def test_invalid_prob(self):
assert_raises(ValueError, random.multinomial, 100, [1.1, 0.2])
assert_raises(ValueError, random.multinomial, 100, [-.1, 0.9])
def test_invalid_n(self):
assert_raises(ValueError, random.multinomial, -1, [0.8, 0.2])
assert_raises(ValueError, random.multinomial, [-1] * 10, [0.8, 0.2])
def test_p_non_contiguous(self):
p = np.arange(15.)
p /= np.sum(p[1::3])
pvals = p[1::3]
random = Generator(MT19937(1432985819))
non_contig = random.multinomial(100, pvals=pvals)
random = Generator(MT19937(1432985819))
contig = random.multinomial(100, pvals=np.ascontiguousarray(pvals))
assert_array_equal(non_contig, contig)
def test_multidimensional_pvals(self):
assert_raises(ValueError, random.multinomial, 10, [[0, 1]])
assert_raises(ValueError, random.multinomial, 10, [[0], [1]])
assert_raises(ValueError, random.multinomial, 10, [[[0], [1]], [[1], [0]]])
assert_raises(ValueError, random.multinomial, 10, np.array([[0, 1], [1, 0]]))
class TestMultivariateHypergeometric:
def setup(self):
self.seed = 8675309
def test_argument_validation(self):
assert_raises(ValueError, random.multivariate_hypergeometric,
10, 4)
assert_raises(ValueError, random.multivariate_hypergeometric,
[2, 3, 4], -1)
assert_raises(ValueError, random.multivariate_hypergeometric,
[-1, 2, 3], 2)
assert_raises(ValueError, random.multivariate_hypergeometric,
[2, 3, 4], 10)
assert_raises(ValueError, random.multivariate_hypergeometric,
[], 1)
assert_raises(ValueError, random.multivariate_hypergeometric,
[999999999, 101], 5, 1, 'marginals')
int64_info = np.iinfo(np.int64)
max_int64 = int64_info.max
max_int64_index = max_int64 // int64_info.dtype.itemsize
assert_raises(ValueError, random.multivariate_hypergeometric,
[max_int64_index - 100, 101], 5, 1, 'count')
@pytest.mark.parametrize('method', ['count', 'marginals'])
def test_edge_cases(self, method):
random = Generator(MT19937(self.seed))
x = random.multivariate_hypergeometric([0, 0, 0], 0, method=method)
assert_array_equal(x, [0, 0, 0])
x = random.multivariate_hypergeometric([], 0, method=method)
assert_array_equal(x, [])
x = random.multivariate_hypergeometric([], 0, size=1, method=method)
assert_array_equal(x, np.empty((1, 0), dtype=np.int64))
x = random.multivariate_hypergeometric([1, 2, 3], 0, method=method)
assert_array_equal(x, [0, 0, 0])
x = random.multivariate_hypergeometric([9, 0, 0], 3, method=method)
assert_array_equal(x, [3, 0, 0])
colors = [1, 1, 0, 1, 1]
x = random.multivariate_hypergeometric(colors, sum(colors),
method=method)
assert_array_equal(x, colors)
x = random.multivariate_hypergeometric([3, 4, 5], 12, size=3,
method=method)
assert_array_equal(x, [[3, 4, 5]]*3)
# Cases for nsample:
# nsample < 10
# 10 <= nsample < colors.sum()/2
# colors.sum()/2 < nsample < colors.sum() - 10
# colors.sum() - 10 < nsample < colors.sum()
@pytest.mark.parametrize('nsample', [8, 25, 45, 55])
@pytest.mark.parametrize('method', ['count', 'marginals'])
@pytest.mark.parametrize('size', [5, (2, 3), 150000])
def test_typical_cases(self, nsample, method, size):
random = Generator(MT19937(self.seed))
colors = np.array([10, 5, 20, 25])
sample = random.multivariate_hypergeometric(colors, nsample, size,
method=method)
if isinstance(size, int):
expected_shape = (size,) + colors.shape
else:
expected_shape = size + colors.shape
assert_equal(sample.shape, expected_shape)
assert_((sample >= 0).all())
assert_((sample <= colors).all())
assert_array_equal(sample.sum(axis=-1),
np.full(size, fill_value=nsample, dtype=int))
if isinstance(size, int) and size >= 100000:
# This sample is large enough to compare its mean to
# the expected values.
assert_allclose(sample.mean(axis=0),
nsample * colors / colors.sum(),
rtol=1e-3, atol=0.005)
def test_repeatability1(self):
random = Generator(MT19937(self.seed))
sample = random.multivariate_hypergeometric([3, 4, 5], 5, size=5,
method='count')
expected = np.array([[2, 1, 2],
[2, 1, 2],
[1, 1, 3],
[2, 0, 3],
[2, 1, 2]])
assert_array_equal(sample, expected)
def test_repeatability2(self):
random = Generator(MT19937(self.seed))
sample = random.multivariate_hypergeometric([20, 30, 50], 50,
size=5,
method='marginals')
expected = np.array([[ 9, 17, 24],
[ 7, 13, 30],
[ 9, 15, 26],
[ 9, 17, 24],
[12, 14, 24]])
assert_array_equal(sample, expected)
def test_repeatability3(self):
random = Generator(MT19937(self.seed))
sample = random.multivariate_hypergeometric([20, 30, 50], 12,
size=5,
method='marginals')
expected = np.array([[2, 3, 7],
[5, 3, 4],
[2, 5, 5],
[5, 3, 4],
[1, 5, 6]])
assert_array_equal(sample, expected)
class TestSetState:
def setup(self):
self.seed = 1234567890
self.rg = Generator(MT19937(self.seed))
self.bit_generator = self.rg.bit_generator
self.state = self.bit_generator.state
self.legacy_state = (self.state['bit_generator'],
self.state['state']['key'],
self.state['state']['pos'])
def test_gaussian_reset(self):
# Make sure the cached every-other-Gaussian is reset.
old = self.rg.standard_normal(size=3)
self.bit_generator.state = self.state
new = self.rg.standard_normal(size=3)
assert_(np.all(old == new))
def test_gaussian_reset_in_media_res(self):
# When the state is saved with a cached Gaussian, make sure the
# cached Gaussian is restored.
self.rg.standard_normal()
state = self.bit_generator.state
old = self.rg.standard_normal(size=3)
self.bit_generator.state = state
new = self.rg.standard_normal(size=3)
assert_(np.all(old == new))
def test_negative_binomial(self):
# Ensure that the negative binomial results take floating point
# arguments without truncation.
self.rg.negative_binomial(0.5, 0.5)
class TestIntegers:
rfunc = random.integers
# valid integer/boolean types
itype = [bool, np.int8, np.uint8, np.int16, np.uint16,
np.int32, np.uint32, np.int64, np.uint64]
def test_unsupported_type(self, endpoint):
assert_raises(TypeError, self.rfunc, 1, endpoint=endpoint, dtype=float)
def test_bounds_checking(self, endpoint):
for dt in self.itype:
lbnd = 0 if dt is bool else np.iinfo(dt).min
ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
ubnd = ubnd - 1 if endpoint else ubnd
assert_raises(ValueError, self.rfunc, lbnd - 1, ubnd,
endpoint=endpoint, dtype=dt)
assert_raises(ValueError, self.rfunc, lbnd, ubnd + 1,
endpoint=endpoint, dtype=dt)
assert_raises(ValueError, self.rfunc, ubnd, lbnd,
endpoint=endpoint, dtype=dt)
assert_raises(ValueError, self.rfunc, 1, 0, endpoint=endpoint,
dtype=dt)
assert_raises(ValueError, self.rfunc, [lbnd - 1], ubnd,
endpoint=endpoint, dtype=dt)
assert_raises(ValueError, self.rfunc, [lbnd], [ubnd + 1],
endpoint=endpoint, dtype=dt)
assert_raises(ValueError, self.rfunc, [ubnd], [lbnd],
endpoint=endpoint, dtype=dt)
assert_raises(ValueError, self.rfunc, 1, [0],
endpoint=endpoint, dtype=dt)
def test_bounds_checking_array(self, endpoint):
for dt in self.itype:
lbnd = 0 if dt is bool else np.iinfo(dt).min
ubnd = 2 if dt is bool else np.iinfo(dt).max + (not endpoint)
assert_raises(ValueError, self.rfunc, [lbnd - 1] * 2, [ubnd] * 2,
endpoint=endpoint, dtype=dt)
assert_raises(ValueError, self.rfunc, [lbnd] * 2,
[ubnd + 1] * 2, endpoint=endpoint, dtype=dt)
assert_raises(ValueError, self.rfunc, ubnd, [lbnd] * 2,
endpoint=endpoint, dtype=dt)
assert_raises(ValueError, self.rfunc, [1] * 2, 0,
endpoint=endpoint, dtype=dt)
def test_rng_zero_and_extremes(self, endpoint):
for dt in self.itype:
lbnd = 0 if dt is bool else np.iinfo(dt).min
ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
ubnd = ubnd - 1 if endpoint else ubnd
is_open = not endpoint
tgt = ubnd - 1
assert_equal(self.rfunc(tgt, tgt + is_open, size=1000,
endpoint=endpoint, dtype=dt), tgt)
assert_equal(self.rfunc([tgt], tgt + is_open, size=1000,
endpoint=endpoint, dtype=dt), tgt)
tgt = lbnd
assert_equal(self.rfunc(tgt, tgt + is_open, size=1000,
endpoint=endpoint, dtype=dt), tgt)
assert_equal(self.rfunc(tgt, [tgt + is_open], size=1000,
endpoint=endpoint, dtype=dt), tgt)
tgt = (lbnd + ubnd) // 2
assert_equal(self.rfunc(tgt, tgt + is_open, size=1000,
endpoint=endpoint, dtype=dt), tgt)
assert_equal(self.rfunc([tgt], [tgt + is_open],
size=1000, endpoint=endpoint, dtype=dt),
tgt)
def test_rng_zero_and_extremes_array(self, endpoint):
size = 1000
for dt in self.itype:
lbnd = 0 if dt is bool else np.iinfo(dt).min
ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
ubnd = ubnd - 1 if endpoint else ubnd
tgt = ubnd - 1
assert_equal(self.rfunc([tgt], [tgt + 1],
size=size, dtype=dt), tgt)
assert_equal(self.rfunc(
[tgt] * size, [tgt + 1] * size, dtype=dt), tgt)
assert_equal(self.rfunc(
[tgt] * size, [tgt + 1] * size, size=size, dtype=dt), tgt)
tgt = lbnd
assert_equal(self.rfunc([tgt], [tgt + 1],
size=size, dtype=dt), tgt)
assert_equal(self.rfunc(
[tgt] * size, [tgt + 1] * size, dtype=dt), tgt)
assert_equal(self.rfunc(
[tgt] * size, [tgt + 1] * size, size=size, dtype=dt), tgt)
tgt = (lbnd + ubnd) // 2
assert_equal(self.rfunc([tgt], [tgt + 1],
size=size, dtype=dt), tgt)
assert_equal(self.rfunc(
[tgt] * size, [tgt + 1] * size, dtype=dt), tgt)
assert_equal(self.rfunc(
[tgt] * size, [tgt + 1] * size, size=size, dtype=dt), tgt)
def test_full_range(self, endpoint):
# Test for ticket #1690
for dt in self.itype:
lbnd = 0 if dt is bool else np.iinfo(dt).min
ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
ubnd = ubnd - 1 if endpoint else ubnd
try:
self.rfunc(lbnd, ubnd, endpoint=endpoint, dtype=dt)
except Exception as e:
raise AssertionError("No error should have been raised, "
"but one was with the following "
"message:\n\n%s" % str(e))
def test_full_range_array(self, endpoint):
# Test for ticket #1690
for dt in self.itype:
lbnd = 0 if dt is bool else np.iinfo(dt).min
ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
ubnd = ubnd - 1 if endpoint else ubnd
try:
self.rfunc([lbnd] * 2, [ubnd], endpoint=endpoint, dtype=dt)
except Exception as e:
raise AssertionError("No error should have been raised, "
"but one was with the following "
"message:\n\n%s" % str(e))
def test_in_bounds_fuzz(self, endpoint):
# Don't use fixed seed
random = Generator(MT19937())
for dt in self.itype[1:]:
for ubnd in [4, 8, 16]:
vals = self.rfunc(2, ubnd - endpoint, size=2 ** 16,
endpoint=endpoint, dtype=dt)
assert_(vals.max() < ubnd)
assert_(vals.min() >= 2)
vals = self.rfunc(0, 2 - endpoint, size=2 ** 16, endpoint=endpoint,
dtype=bool)
assert_(vals.max() < 2)
assert_(vals.min() >= 0)
def test_scalar_array_equiv(self, endpoint):
for dt in self.itype:
lbnd = 0 if dt is bool else np.iinfo(dt).min
ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
ubnd = ubnd - 1 if endpoint else ubnd
size = 1000
random = Generator(MT19937(1234))
scalar = random.integers(lbnd, ubnd, size=size, endpoint=endpoint,
dtype=dt)
random = Generator(MT19937(1234))
scalar_array = random.integers([lbnd], [ubnd], size=size,
endpoint=endpoint, dtype=dt)
random = Generator(MT19937(1234))
array = random.integers([lbnd] * size, [ubnd] *
size, size=size, endpoint=endpoint, dtype=dt)
assert_array_equal(scalar, scalar_array)
assert_array_equal(scalar, array)
def test_repeatability(self, endpoint):
tgt = {'bool': 'b3300e66d2bb59e493d255d47c3a6cbe',
'int16': '39624ead49ad67e37545744024d2648b',
'int32': '5c4810373f979336c6c0c999996e47a1',
'int64': 'ab126c15edff26f55c50d2b7e37391ac',
'int8': 'ba71ccaffeeeb9eeb1860f8075020b9c',
'uint16': '39624ead49ad67e37545744024d2648b',
'uint32': '5c4810373f979336c6c0c999996e47a1',
'uint64': 'ab126c15edff26f55c50d2b7e37391ac',
'uint8': 'ba71ccaffeeeb9eeb1860f8075020b9c'}
for dt in self.itype[1:]:
random = Generator(MT19937(1234))
if sys.byteorder == 'little':
val = random.integers(0, 6 - endpoint, size=1000, endpoint=endpoint,
dtype=dt)
else:
val = random.integers(0, 6 - endpoint, size=1000, endpoint=endpoint,
dtype=dt).byteswap()
res = hashlib.md5(val).hexdigest()
assert_(tgt[np.dtype(dt).name] == res)
random = Generator(MT19937(1234))
val = random.integers(0, 2 - endpoint, size=1000, endpoint=endpoint,
dtype=bool).view(np.int8)
res = hashlib.md5(val).hexdigest()
assert_(tgt[np.dtype(bool).name] == res)
def test_repeatability_broadcasting(self, endpoint):
for dt in self.itype:
lbnd = 0 if dt in (bool, np.bool_) else np.iinfo(dt).min
ubnd = 2 if dt in (bool, np.bool_) else np.iinfo(dt).max + 1
ubnd = ubnd - 1 if endpoint else ubnd
random = Generator(MT19937(1234))
val = random.integers(lbnd, ubnd, size=1000, endpoint=endpoint,
dtype=dt)
random = Generator(MT19937(1234))
val_bc = random.integers([lbnd] * 1000, ubnd, endpoint=endpoint,
dtype=dt)
assert_array_equal(val, val_bc)
random = Generator(MT19937(1234))
val_bc = random.integers([lbnd] * 1000, [ubnd] * 1000,
endpoint=endpoint, dtype=dt)
assert_array_equal(val, val_bc)
@pytest.mark.parametrize(
'bound, expected',
[(2**32 - 1, np.array([517043486, 1364798665, 1733884389, 1353720612,
3769704066, 1170797179, 4108474671])),
(2**32, np.array([517043487, 1364798666, 1733884390, 1353720613,
3769704067, 1170797180, 4108474672])),
(2**32 + 1, np.array([517043487, 1733884390, 3769704068, 4108474673,
1831631863, 1215661561, 3869512430]))]
)
def test_repeatability_32bit_boundary(self, bound, expected):
for size in [None, len(expected)]:
random = Generator(MT19937(1234))
x = random.integers(bound, size=size)
assert_equal(x, expected if size is not None else expected[0])
def test_repeatability_32bit_boundary_broadcasting(self):
desired = np.array([[[1622936284, 3620788691, 1659384060],
[1417365545, 760222891, 1909653332],
[3788118662, 660249498, 4092002593]],
[[3625610153, 2979601262, 3844162757],
[ 685800658, 120261497, 2694012896],
[1207779440, 1586594375, 3854335050]],
[[3004074748, 2310761796, 3012642217],
[2067714190, 2786677879, 1363865881],
[ 791663441, 1867303284, 2169727960]],
[[1939603804, 1250951100, 298950036],
[1040128489, 3791912209, 3317053765],
[3155528714, 61360675, 2305155588]],
[[ 817688762, 1335621943, 3288952434],
[1770890872, 1102951817, 1957607470],
[3099996017, 798043451, 48334215]]])
for size in [None, (5, 3, 3)]:
random = Generator(MT19937(12345))
x = random.integers([[-1], [0], [1]],
[2**32 - 1, 2**32, 2**32 + 1],
size=size)
assert_array_equal(x, desired if size is not None else desired[0])
def test_int64_uint64_broadcast_exceptions(self, endpoint):
configs = {np.uint64: ((0, 2**65), (-1, 2**62), (10, 9), (0, 0)),
np.int64: ((0, 2**64), (-(2**64), 2**62), (10, 9), (0, 0),
(-2**63-1, -2**63-1))}
for dtype in configs:
for config in configs[dtype]:
low, high = config
high = high - endpoint
low_a = np.array([[low]*10])
high_a = np.array([high] * 10)
assert_raises(ValueError, random.integers, low, high,
endpoint=endpoint, dtype=dtype)
assert_raises(ValueError, random.integers, low_a, high,
endpoint=endpoint, dtype=dtype)
assert_raises(ValueError, random.integers, low, high_a,
endpoint=endpoint, dtype=dtype)
assert_raises(ValueError, random.integers, low_a, high_a,
endpoint=endpoint, dtype=dtype)
low_o = np.array([[low]*10], dtype=object)
high_o = np.array([high] * 10, dtype=object)
assert_raises(ValueError, random.integers, low_o, high,
endpoint=endpoint, dtype=dtype)
assert_raises(ValueError, random.integers, low, high_o,
endpoint=endpoint, dtype=dtype)
assert_raises(ValueError, random.integers, low_o, high_o,
endpoint=endpoint, dtype=dtype)
def test_int64_uint64_corner_case(self, endpoint):
dt = np.int64
tgt = np.iinfo(np.int64).max
lbnd = np.int64(np.iinfo(np.int64).max)
ubnd = np.uint64(np.iinfo(np.int64).max + 1 - endpoint)
actual = random.integers(lbnd, ubnd, endpoint=endpoint, dtype=dt)
assert_equal(actual, tgt)
def test_respect_dtype_singleton(self, endpoint):
for dt in self.itype:
lbnd = 0 if dt is bool else np.iinfo(dt).min
ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
ubnd = ubnd - 1 if endpoint else ubnd
dt = np.bool_ if dt is bool else dt
sample = self.rfunc(lbnd, ubnd, endpoint=endpoint, dtype=dt)
assert_equal(sample.dtype, dt)
for dt in (bool, int, np.compat.long):
lbnd = 0 if dt is bool else np.iinfo(dt).min
ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
ubnd = ubnd - 1 if endpoint else ubnd
sample = self.rfunc(lbnd, ubnd, endpoint=endpoint, dtype=dt)
assert not hasattr(sample, 'dtype')
assert_equal(type(sample), dt)
def test_respect_dtype_array(self, endpoint):
for dt in self.itype:
lbnd = 0 if dt is bool else np.iinfo(dt).min
ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
ubnd = ubnd - 1 if endpoint else ubnd
dt = np.bool_ if dt is bool else dt
sample = self.rfunc([lbnd], [ubnd], endpoint=endpoint, dtype=dt)
assert_equal(sample.dtype, dt)
sample = self.rfunc([lbnd] * 2, [ubnd] * 2, endpoint=endpoint,
dtype=dt)
assert_equal(sample.dtype, dt)
def test_zero_size(self, endpoint):
for dt in self.itype:
sample = self.rfunc(0, 0, (3, 0, 4), endpoint=endpoint, dtype=dt)
assert sample.shape == (3, 0, 4)
assert sample.dtype == dt
assert self.rfunc(0, -10, 0, endpoint=endpoint,
dtype=dt).shape == (0,)
assert_equal(random.integers(0, 0, size=(3, 0, 4)).shape,
(3, 0, 4))
assert_equal(random.integers(0, -10, size=0).shape, (0,))
assert_equal(random.integers(10, 10, size=0).shape, (0,))
def test_error_byteorder(self):
other_byteord_dt = '<i4' if sys.byteorder == 'big' else '>i4'
with pytest.raises(ValueError):
random.integers(0, 200, size=10, dtype=other_byteord_dt)
@pytest.mark.slow
@pytest.mark.parametrize('sample_size,high,dtype,chi2max',
[(5000000, 5, np.int8, 125.0),
(5000000, 7, np.uint8, 150.0),
(10000000, 2500, np.int16, 3300.0),
(50000000, 5000, np.uint16, 6500.0),
])
def test_integers_small_dtype_chisquared(self, sample_size, high,
dtype, chi2max):
samples = random.integers(high, size=sample_size, dtype=dtype)
values, counts = np.unique(samples, return_counts=True)
expected = sample_size / high
chi2 = ((counts - expected)**2 / expected).sum()
assert chi2 < chi2max
class TestRandomDist:
def setup(self):
self.seed = 1234567890
def test_integers(self):
random = Generator(MT19937(self.seed))
actual = random.integers(-99, 99, size=(3, 2))
desired = np.array([[-80, -56], [41, 37], [-83, -16]])
assert_array_equal(actual, desired)
def test_integers_masked(self):
random = Generator(MT19937(self.seed))
actual = random.integers(0, 99, size=(3, 2), dtype=np.uint32)
desired = np.array([[9, 21], [70, 68], [8, 41]], dtype=np.uint32)
assert_array_equal(actual, desired)
def test_integers_closed(self):
random = Generator(MT19937(self.seed))
actual = random.integers(-99, 99, size=(3, 2), endpoint=True)
desired = np.array([[-80, -56], [ 41, 38], [-83, -15]])
assert_array_equal(actual, desired)
def test_integers_max_int(self):
actual = random.integers(np.iinfo('l').max, np.iinfo('l').max,
endpoint=True)
desired = np.iinfo('l').max
assert_equal(actual, desired)
def test_random(self):
random = Generator(MT19937(self.seed))
actual = random.random((3, 2))
desired = np.array([[0.096999199829214, 0.707517457682192],
[0.084364834598269, 0.767731206553125],
[0.665069021359413, 0.715487190596693]])
assert_array_almost_equal(actual, desired, decimal=15)
random = Generator(MT19937(self.seed))
actual = random.random()
assert_array_almost_equal(actual, desired[0, 0], decimal=15)
def test_random_float(self):
random = Generator(MT19937(self.seed))
actual = random.random((3, 2))
desired = np.array([[0.0969992 , 0.70751746],
[0.08436483, 0.76773121],
[0.66506902, 0.71548719]])
assert_array_almost_equal(actual, desired, decimal=7)
def test_random_float_scalar(self):
random = Generator(MT19937(self.seed))
actual = random.random(dtype=np.float32)
desired = 0.0969992
assert_array_almost_equal(actual, desired, decimal=7)
def test_random_unsupported_type(self):
assert_raises(TypeError, random.random, dtype='int32')
def test_choice_uniform_replace(self):
random = Generator(MT19937(self.seed))
actual = random.choice(4, 4)
desired = np.array([0, 0, 2, 2], dtype=np.int64)
assert_array_equal(actual, desired)
def test_choice_nonuniform_replace(self):
random = Generator(MT19937(self.seed))
actual = random.choice(4, 4, p=[0.4, 0.4, 0.1, 0.1])
desired = np.array([0, 1, 0, 1], dtype=np.int64)
assert_array_equal(actual, desired)
def test_choice_uniform_noreplace(self):
random = Generator(MT19937(self.seed))
actual = random.choice(4, 3, replace=False)
desired = np.array([2, 0, 3], dtype=np.int64)
assert_array_equal(actual, desired)
actual = random.choice(4, 4, replace=False, shuffle=False)
desired = np.arange(4, dtype=np.int64)
assert_array_equal(actual, desired)
def test_choice_nonuniform_noreplace(self):
random = Generator(MT19937(self.seed))
actual = random.choice(4, 3, replace=False, p=[0.1, 0.3, 0.5, 0.1])
desired = np.array([0, 2, 3], dtype=np.int64)
assert_array_equal(actual, desired)
def test_choice_noninteger(self):
random = Generator(MT19937(self.seed))
actual = random.choice(['a', 'b', 'c', 'd'], 4)
desired = np.array(['a', 'a', 'c', 'c'])
assert_array_equal(actual, desired)
def test_choice_multidimensional_default_axis(self):
random = Generator(MT19937(self.seed))
actual = random.choice([[0, 1], [2, 3], [4, 5], [6, 7]], 3)
desired = np.array([[0, 1], [0, 1], [4, 5]])
assert_array_equal(actual, desired)
def test_choice_multidimensional_custom_axis(self):
random = Generator(MT19937(self.seed))
actual = random.choice([[0, 1], [2, 3], [4, 5], [6, 7]], 1, axis=1)
desired = np.array([[0], [2], [4], [6]])
assert_array_equal(actual, desired)
def test_choice_exceptions(self):
sample = random.choice
assert_raises(ValueError, sample, -1, 3)
assert_raises(ValueError, sample, 3., 3)
assert_raises(ValueError, sample, [], 3)
assert_raises(ValueError, sample, [1, 2, 3, 4], 3,
p=[[0.25, 0.25], [0.25, 0.25]])
assert_raises(ValueError, sample, [1, 2], 3, p=[0.4, 0.4, 0.2])
assert_raises(ValueError, sample, [1, 2], 3, p=[1.1, -0.1])
assert_raises(ValueError, sample, [1, 2], 3, p=[0.4, 0.4])
assert_raises(ValueError, sample, [1, 2, 3], 4, replace=False)
assert_raises(ValueError, sample, [1, 2, 3], -2, replace=False)
assert_raises(ValueError, sample, [1, 2, 3], (-1,), replace=False)
assert_raises(ValueError, sample, [1, 2, 3], (-1, 1), replace=False)
assert_raises(ValueError, sample, [1, 2, 3], 2,
replace=False, p=[1, 0, 0])
def test_choice_return_shape(self):
p = [0.1, 0.9]
assert_(np.isscalar(random.choice(2, replace=True)))
assert_(np.isscalar(random.choice(2, replace=False)))
assert_(np.isscalar(random.choice(2, replace=True, p=p)))
assert_(np.isscalar(random.choice(2, replace=False, p=p)))
assert_(np.isscalar(random.choice([1, 2], replace=True)))
assert_(random.choice([None], replace=True) is None)
a = np.array([1, 2])
arr = np.empty(1, dtype=object)
arr[0] = a
assert_(random.choice(arr, replace=True) is a)
s = tuple()
assert_(not np.isscalar(random.choice(2, s, replace=True)))
assert_(not np.isscalar(random.choice(2, s, replace=False)))
assert_(not np.isscalar(random.choice(2, s, replace=True, p=p)))
assert_(not np.isscalar(random.choice(2, s, replace=False, p=p)))
assert_(not np.isscalar(random.choice([1, 2], s, replace=True)))
assert_(random.choice([None], s, replace=True).ndim == 0)
a = np.array([1, 2])
arr = np.empty(1, dtype=object)
arr[0] = a
assert_(random.choice(arr, s, replace=True).item() is a)
s = (2, 3)
p = [0.1, 0.1, 0.1, 0.1, 0.4, 0.2]
assert_equal(random.choice(6, s, replace=True).shape, s)
assert_equal(random.choice(6, s, replace=False).shape, s)
assert_equal(random.choice(6, s, replace=True, p=p).shape, s)
assert_equal(random.choice(6, s, replace=False, p=p).shape, s)
assert_equal(random.choice(np.arange(6), s, replace=True).shape, s)
assert_equal(random.integers(0, 0, size=(3, 0, 4)).shape, (3, 0, 4))
assert_equal(random.integers(0, -10, size=0).shape, (0,))
assert_equal(random.integers(10, 10, size=0).shape, (0,))
assert_equal(random.choice(0, size=0).shape, (0,))
assert_equal(random.choice([], size=(0,)).shape, (0,))
assert_equal(random.choice(['a', 'b'], size=(3, 0, 4)).shape,
(3, 0, 4))
assert_raises(ValueError, random.choice, [], 10)
def test_choice_nan_probabilities(self):
a = np.array([42, 1, 2])
p = [None, None, None]
assert_raises(ValueError, random.choice, a, p=p)
def test_choice_p_non_contiguous(self):
p = np.ones(10) / 5
p[1::2] = 3.0
random = Generator(MT19937(self.seed))
non_contig = random.choice(5, 3, p=p[::2])
random = Generator(MT19937(self.seed))
contig = random.choice(5, 3, p=np.ascontiguousarray(p[::2]))
assert_array_equal(non_contig, contig)
def test_choice_return_type(self):
p = np.ones(4) / 4.
actual = random.choice(4, 2)
assert actual.dtype == np.int64
actual = random.choice(4, 2, replace=False)
assert actual.dtype == np.int64
actual = random.choice(4, 2, p=p)
assert actual.dtype == np.int64
actual = random.choice(4, 2, p=p, replace=False)
assert actual.dtype == np.int64
def test_choice_large_sample(self):
choice_hash = 'd44962a0b1e92f4a3373c23222244e21'
random = Generator(MT19937(self.seed))
actual = random.choice(10000, 5000, replace=False)
if sys.byteorder != 'little':
actual = actual.byteswap()
res = hashlib.md5(actual.view(np.int8)).hexdigest()
assert_(choice_hash == res)
def test_bytes(self):
random = Generator(MT19937(self.seed))
actual = random.bytes(10)
desired = b'\x86\xf0\xd4\x18\xe1\x81\t8%\xdd'
assert_equal(actual, desired)
def test_shuffle(self):
for conv in [lambda x: np.array([]),
lambda x: x,
lambda x: np.asarray(x).astype(np.int8),
lambda x: np.asarray(x).astype(np.float32),
lambda x: np.asarray(x).astype(np.complex64),
lambda x: np.asarray(x).astype(object),
lambda x: [(i, i) for i in x],
lambda x: np.asarray([[i, i] for i in x]),
lambda x: np.vstack([x, x]).T,
lambda x: (np.asarray([(i, i) for i in x],
[("a", int), ("b", int)])
.view(np.recarray)),
lambda x: np.asarray([(i, i) for i in x],
[("a", object, (1,)),
("b", np.int32, (1,))])]:
random = Generator(MT19937(self.seed))
alist = conv([1, 2, 3, 4, 5, 6, 7, 8, 9, 0])
random.shuffle(alist)
actual = alist
desired = conv([4, 1, 9, 8, 0, 5, 3, 6, 2, 7])
assert_array_equal(actual, desired)
def test_shuffle_custom_axis(self):
random = Generator(MT19937(self.seed))
actual = np.arange(16).reshape((4, 4))
random.shuffle(actual, axis=1)
desired = np.array([[ 0, 3, 1, 2],
[ 4, 7, 5, 6],
[ 8, 11, 9, 10],
[12, 15, 13, 14]])
assert_array_equal(actual, desired)
random = Generator(MT19937(self.seed))
actual = np.arange(16).reshape((4, 4))
random.shuffle(actual, axis=-1)
assert_array_equal(actual, desired)
def test_shuffle_axis_nonsquare(self):
y1 = np.arange(20).reshape(2, 10)
y2 = y1.copy()
random = Generator(MT19937(self.seed))
random.shuffle(y1, axis=1)
random = Generator(MT19937(self.seed))
random.shuffle(y2.T)
assert_array_equal(y1, y2)
def test_shuffle_masked(self):
a = np.ma.masked_values(np.reshape(range(20), (5, 4)) % 3 - 1, -1)
b = np.ma.masked_values(np.arange(20) % 3 - 1, -1)
a_orig = a.copy()
b_orig = b.copy()
for i in range(50):
random.shuffle(a)
assert_equal(
sorted(a.data[~a.mask]), sorted(a_orig.data[~a_orig.mask]))
random.shuffle(b)
assert_equal(
sorted(b.data[~b.mask]), sorted(b_orig.data[~b_orig.mask]))
def test_shuffle_exceptions(self):
random = Generator(MT19937(self.seed))
arr = np.arange(10)
assert_raises(np.AxisError, random.shuffle, arr, 1)
arr = np.arange(9).reshape((3, 3))
assert_raises(np.AxisError, random.shuffle, arr, 3)
assert_raises(TypeError, random.shuffle, arr, slice(1, 2, None))
arr = [[1, 2, 3], [4, 5, 6]]
assert_raises(NotImplementedError, random.shuffle, arr, 1)
def test_permutation(self):
random = Generator(MT19937(self.seed))
alist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
actual = random.permutation(alist)
desired = [4, 1, 9, 8, 0, 5, 3, 6, 2, 7]
assert_array_equal(actual, desired)
random = Generator(MT19937(self.seed))
arr_2d = np.atleast_2d([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]).T
actual = random.permutation(arr_2d)
assert_array_equal(actual, np.atleast_2d(desired).T)
bad_x_str = "abcd"
assert_raises(np.AxisError, random.permutation, bad_x_str)
bad_x_float = 1.2
assert_raises(np.AxisError, random.permutation, bad_x_float)
random = Generator(MT19937(self.seed))
integer_val = 10
desired = [3, 0, 8, 7, 9, 4, 2, 5, 1, 6]
actual = random.permutation(integer_val)
assert_array_equal(actual, desired)
def test_permutation_custom_axis(self):
a = np.arange(16).reshape((4, 4))
desired = np.array([[ 0, 3, 1, 2],
[ 4, 7, 5, 6],
[ 8, 11, 9, 10],
[12, 15, 13, 14]])
random = Generator(MT19937(self.seed))
actual = random.permutation(a, axis=1)
assert_array_equal(actual, desired)
random = Generator(MT19937(self.seed))
actual = random.permutation(a, axis=-1)
assert_array_equal(actual, desired)
def test_permutation_exceptions(self):
random = Generator(MT19937(self.seed))
arr = np.arange(10)
assert_raises(np.AxisError, random.permutation, arr, 1)
arr = np.arange(9).reshape((3, 3))
assert_raises(np.AxisError, random.permutation, arr, 3)
assert_raises(TypeError, random.permutation, arr, slice(1, 2, None))
def test_beta(self):
random = Generator(MT19937(self.seed))
actual = random.beta(.1, .9, size=(3, 2))
desired = np.array(
[[1.083029353267698e-10, 2.449965303168024e-11],
[2.397085162969853e-02, 3.590779671820755e-08],
[2.830254190078299e-04, 1.744709918330393e-01]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_binomial(self):
random = Generator(MT19937(self.seed))
actual = random.binomial(100.123, .456, size=(3, 2))
desired = np.array([[42, 41],
[42, 48],
[44, 50]])
assert_array_equal(actual, desired)
random = Generator(MT19937(self.seed))
actual = random.binomial(100.123, .456)
desired = 42
assert_array_equal(actual, desired)
def test_chisquare(self):
random = Generator(MT19937(self.seed))
actual = random.chisquare(50, size=(3, 2))
desired = np.array([[32.9850547060149, 39.0219480493301],
[56.2006134779419, 57.3474165711485],
[55.4243733880198, 55.4209797925213]])
assert_array_almost_equal(actual, desired, decimal=13)
def test_dirichlet(self):
random = Generator(MT19937(self.seed))
alpha = np.array([51.72840233779265162, 39.74494232180943953])
actual = random.dirichlet(alpha, size=(3, 2))
desired = np.array([[[0.5439892869558927, 0.45601071304410745],
[0.5588917345860708, 0.4411082654139292 ]],
[[0.5632074165063435, 0.43679258349365657],
[0.54862581112627, 0.45137418887373015]],
[[0.49961831357047226, 0.5003816864295278 ],
[0.52374806183482, 0.47625193816517997]]])
assert_array_almost_equal(actual, desired, decimal=15)
bad_alpha = np.array([5.4e-01, -1.0e-16])
assert_raises(ValueError, random.dirichlet, bad_alpha)
random = Generator(MT19937(self.seed))
alpha = np.array([51.72840233779265162, 39.74494232180943953])
actual = random.dirichlet(alpha)
assert_array_almost_equal(actual, desired[0, 0], decimal=15)
def test_dirichlet_size(self):
p = np.array([51.72840233779265162, 39.74494232180943953])
assert_equal(random.dirichlet(p, np.uint32(1)).shape, (1, 2))
assert_equal(random.dirichlet(p, np.uint32(1)).shape, (1, 2))
assert_equal(random.dirichlet(p, np.uint32(1)).shape, (1, 2))
assert_equal(random.dirichlet(p, [2, 2]).shape, (2, 2, 2))
assert_equal(random.dirichlet(p, (2, 2)).shape, (2, 2, 2))
assert_equal(random.dirichlet(p, np.array((2, 2))).shape, (2, 2, 2))
assert_raises(TypeError, random.dirichlet, p, float(1))
def test_dirichlet_bad_alpha(self):
alpha = np.array([5.4e-01, -1.0e-16])
assert_raises(ValueError, random.dirichlet, alpha)
assert_raises(ValueError, random.dirichlet, [[5, 1]])
assert_raises(ValueError, random.dirichlet, [[5], [1]])
assert_raises(ValueError, random.dirichlet, [[[5], [1]], [[1], [5]]])
assert_raises(ValueError, random.dirichlet, np.array([[5, 1], [1, 5]]))
def test_dirichlet_alpha_non_contiguous(self):
a = np.array([51.72840233779265162, -1.0, 39.74494232180943953])
alpha = a[::2]
random = Generator(MT19937(self.seed))
non_contig = random.dirichlet(alpha, size=(3, 2))
random = Generator(MT19937(self.seed))
contig = random.dirichlet(np.ascontiguousarray(alpha),
size=(3, 2))
assert_array_almost_equal(non_contig, contig)
def test_dirichlet_small_alpha(self):
eps = 1.0e-9
alpha = eps * np.array([1., 1.0e-3])
random = Generator(MT19937(self.seed))
actual = random.dirichlet(alpha, size=(3, 2))
expected = np.array([
[[1., 0.],
[1., 0.]],
[[1., 0.],
[1., 0.]],
[[1., 0.],
[1., 0.]]
])
assert_array_almost_equal(actual, expected, decimal=15)
@pytest.mark.slow
def test_dirichlet_moderately_small_alpha(self):
alpha = np.array([0.02, 0.04, 0.03])
exact_mean = alpha / alpha.sum()
random = Generator(MT19937(self.seed))
sample = random.dirichlet(alpha, size=20000000)
sample_mean = sample.mean(axis=0)
assert_allclose(sample_mean, exact_mean, rtol=1e-3)
def test_exponential(self):
random = Generator(MT19937(self.seed))
actual = random.exponential(1.1234, size=(3, 2))
desired = np.array([[0.098845481066258, 1.560752510746964],
[0.075730916041636, 1.769098974710777],
[1.488602544592235, 2.49684815275751 ]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_exponential_0(self):
assert_equal(random.exponential(scale=0), 0)
assert_raises(ValueError, random.exponential, scale=-0.)
def test_f(self):
random = Generator(MT19937(self.seed))
actual = random.f(12, 77, size=(3, 2))
desired = np.array([[0.461720027077085, 1.100441958872451],
[1.100337455217484, 0.91421736740018 ],
[0.500811891303113, 0.826802454552058]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_gamma(self):
random = Generator(MT19937(self.seed))
actual = random.gamma(5, 3, size=(3, 2))
desired = np.array([[ 5.03850858902096, 7.9228656732049 ],
[18.73983605132985, 19.57961681699238],
[18.17897755150825, 18.17653912505234]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_gamma_0(self):
assert_equal(random.gamma(shape=0, scale=0), 0)
assert_raises(ValueError, random.gamma, shape=-0., scale=-0.)
def test_geometric(self):
random = Generator(MT19937(self.seed))
actual = random.geometric(.123456789, size=(3, 2))
desired = np.array([[ 1, 10],
[ 1, 12],
[ 9, 10]])
assert_array_equal(actual, desired)
def test_geometric_exceptions(self):
assert_raises(ValueError, random.geometric, 1.1)
assert_raises(ValueError, random.geometric, [1.1] * 10)
assert_raises(ValueError, random.geometric, -0.1)
assert_raises(ValueError, random.geometric, [-0.1] * 10)
with np.errstate(invalid='ignore'):
assert_raises(ValueError, random.geometric, np.nan)
assert_raises(ValueError, random.geometric, [np.nan] * 10)
def test_gumbel(self):
random = Generator(MT19937(self.seed))
actual = random.gumbel(loc=.123456789, scale=2.0, size=(3, 2))
desired = np.array([[ 4.688397515056245, -0.289514845417841],
[ 4.981176042584683, -0.633224272589149],
[-0.055915275687488, -0.333962478257953]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_gumbel_0(self):
assert_equal(random.gumbel(scale=0), 0)
assert_raises(ValueError, random.gumbel, scale=-0.)
def test_hypergeometric(self):
random = Generator(MT19937(self.seed))
actual = random.hypergeometric(10.1, 5.5, 14, size=(3, 2))
desired = np.array([[ 9, 9],
[ 9, 9],
[10, 9]])
assert_array_equal(actual, desired)
actual = random.hypergeometric(5, 0, 3, size=4)
desired = np.array([3, 3, 3, 3])
assert_array_equal(actual, desired)
actual = random.hypergeometric(15, 0, 12, size=4)
desired = np.array([12, 12, 12, 12])
assert_array_equal(actual, desired)
actual = random.hypergeometric(0, 5, 3, size=4)
desired = np.array([0, 0, 0, 0])
assert_array_equal(actual, desired)
actual = random.hypergeometric(0, 15, 12, size=4)
desired = np.array([0, 0, 0, 0])
assert_array_equal(actual, desired)
def test_laplace(self):
random = Generator(MT19937(self.seed))
actual = random.laplace(loc=.123456789, scale=2.0, size=(3, 2))
desired = np.array([[-3.156353949272393, 1.195863024830054],
[-3.435458081645966, 1.656882398925444],
[ 0.924824032467446, 1.251116432209336]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_laplace_0(self):
assert_equal(random.laplace(scale=0), 0)
assert_raises(ValueError, random.laplace, scale=-0.)
def test_logistic(self):
random = Generator(MT19937(self.seed))
actual = random.logistic(loc=.123456789, scale=2.0, size=(3, 2))
desired = np.array([[-4.338584631510999, 1.890171436749954],
[-4.64547787337966 , 2.514545562919217],
[ 1.495389489198666, 1.967827627577474]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_lognormal(self):
random = Generator(MT19937(self.seed))
actual = random.lognormal(mean=.123456789, sigma=2.0, size=(3, 2))
desired = np.array([[ 0.0268252166335, 13.9534486483053],
[ 0.1204014788936, 2.2422077497792],
[ 4.2484199496128, 12.0093343977523]])
assert_array_almost_equal(actual, desired, decimal=13)
def test_lognormal_0(self):
assert_equal(random.lognormal(sigma=0), 1)
assert_raises(ValueError, random.lognormal, sigma=-0.)
def test_logseries(self):
random = Generator(MT19937(self.seed))
actual = random.logseries(p=.923456789, size=(3, 2))
desired = np.array([[14, 17],
[3, 18],
[5, 1]])
assert_array_equal(actual, desired)
def test_logseries_exceptions(self):
with np.errstate(invalid='ignore'):
assert_raises(ValueError, random.logseries, np.nan)
assert_raises(ValueError, random.logseries, [np.nan] * 10)
def test_multinomial(self):
random = Generator(MT19937(self.seed))
actual = random.multinomial(20, [1 / 6.] * 6, size=(3, 2))
desired = np.array([[[1, 5, 1, 6, 4, 3],
[4, 2, 6, 2, 4, 2]],
[[5, 3, 2, 6, 3, 1],
[4, 4, 0, 2, 3, 7]],
[[6, 3, 1, 5, 3, 2],
[5, 5, 3, 1, 2, 4]]])
assert_array_equal(actual, desired)
@pytest.mark.parametrize("method", ["svd", "eigh", "cholesky"])
def test_multivariate_normal(self, method):
random = Generator(MT19937(self.seed))
mean = (.123456789, 10)
cov = [[1, 0], [0, 1]]
size = (3, 2)
actual = random.multivariate_normal(mean, cov, size, method=method)
desired = np.array([[[-1.747478062846581, 11.25613495182354 ],
[-0.9967333370066214, 10.342002097029821 ]],
[[ 0.7850019631242964, 11.181113712443013 ],
[ 0.8901349653255224, 8.873825399642492 ]],
[[ 0.7130260107430003, 9.551628690083056 ],
[ 0.7127098726541128, 11.991709234143173 ]]])
assert_array_almost_equal(actual, desired, decimal=15)
actual = random.multivariate_normal(mean, cov, method=method)
desired = np.array([0.233278563284287, 9.424140804347195])
assert_array_almost_equal(actual, desired, decimal=15)
mean = [0, 0]
cov = [[1, 2], [1, 2]]
assert_raises(ValueError, random.multivariate_normal, mean, cov,
check_valid='raise')
cov = [[1, 2], [2, 1]]
assert_warns(RuntimeWarning, random.multivariate_normal, mean, cov)
assert_warns(RuntimeWarning, random.multivariate_normal, mean, cov,
method='eigh')
assert_raises(LinAlgError, random.multivariate_normal, mean, cov,
method='cholesky')
assert_no_warnings(random.multivariate_normal, mean, cov,
check_valid='ignore')
# and that it raises with RuntimeWarning check_valid='raises'
assert_raises(ValueError, random.multivariate_normal, mean, cov,
check_valid='raise')
assert_raises(ValueError, random.multivariate_normal, mean, cov,
check_valid='raise', method='eigh')
# check degenerate samples from singular covariance matrix
cov = [[1, 1], [1, 1]]
if method in ('svd', 'eigh'):
samples = random.multivariate_normal(mean, cov, size=(3, 2),
method=method)
assert_array_almost_equal(samples[..., 0], samples[..., 1],
decimal=6)
else:
assert_raises(LinAlgError, random.multivariate_normal, mean, cov,
method='cholesky')
cov = np.array([[1, 0.1], [0.1, 1]], dtype=np.float32)
with suppress_warnings() as sup:
random.multivariate_normal(mean, cov, method=method)
w = sup.record(RuntimeWarning)
assert len(w) == 0
mu = np.zeros(2)
cov = np.eye(2)
assert_raises(ValueError, random.multivariate_normal, mean, cov,
check_valid='other')
assert_raises(ValueError, random.multivariate_normal,
np.zeros((2, 1, 1)), cov)
assert_raises(ValueError, random.multivariate_normal,
mu, np.empty((3, 2)))
assert_raises(ValueError, random.multivariate_normal,
mu, np.eye(3))
@pytest.mark.parametrize("method", ["svd", "eigh", "cholesky"])
def test_multivariate_normal_basic_stats(self, method):
random = Generator(MT19937(self.seed))
n_s = 1000
mean = np.array([1, 2])
cov = np.array([[2, 1], [1, 2]])
s = random.multivariate_normal(mean, cov, size=(n_s,), method=method)
s_center = s - mean
cov_emp = (s_center.T @ s_center) / (n_s - 1)
# these are pretty loose and are only designed to detect major errors
assert np.all(np.abs(s_center.mean(-2)) < 0.1)
assert np.all(np.abs(cov_emp - cov) < 0.2)
def test_negative_binomial(self):
random = Generator(MT19937(self.seed))
actual = random.negative_binomial(n=100, p=.12345, size=(3, 2))
desired = np.array([[543, 727],
[775, 760],
[600, 674]])
assert_array_equal(actual, desired)
def test_negative_binomial_exceptions(self):
with np.errstate(invalid='ignore'):
assert_raises(ValueError, random.negative_binomial, 100, np.nan)
assert_raises(ValueError, random.negative_binomial, 100,
[np.nan] * 10)
def test_negative_binomial_p0_exception(self):
# Verify that p=0 raises an exception.
with assert_raises(ValueError):
x = random.negative_binomial(1, 0)
def test_noncentral_chisquare(self):
random = Generator(MT19937(self.seed))
actual = random.noncentral_chisquare(df=5, nonc=5, size=(3, 2))
desired = np.array([[ 1.70561552362133, 15.97378184942111],
[13.71483425173724, 20.17859633310629],
[11.3615477156643 , 3.67891108738029]])
assert_array_almost_equal(actual, desired, decimal=14)
actual = random.noncentral_chisquare(df=.5, nonc=.2, size=(3, 2))
desired = np.array([[9.41427665607629e-04, 1.70473157518850e-04],
[1.14554372041263e+00, 1.38187755933435e-03],
[1.90659181905387e+00, 1.21772577941822e+00]])
assert_array_almost_equal(actual, desired, decimal=14)
random = Generator(MT19937(self.seed))
actual = random.noncentral_chisquare(df=5, nonc=0, size=(3, 2))
desired = np.array([[0.82947954590419, 1.80139670767078],
[6.58720057417794, 7.00491463609814],
[6.31101879073157, 6.30982307753005]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_noncentral_f(self):
random = Generator(MT19937(self.seed))
actual = random.noncentral_f(dfnum=5, dfden=2, nonc=1,
size=(3, 2))
desired = np.array([[0.060310671139 , 0.23866058175939],
[0.86860246709073, 0.2668510459738 ],
[0.23375780078364, 1.88922102885943]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_noncentral_f_nan(self):
random = Generator(MT19937(self.seed))
actual = random.noncentral_f(dfnum=5, dfden=2, nonc=np.nan)
assert np.isnan(actual)
def test_normal(self):
random = Generator(MT19937(self.seed))
actual = random.normal(loc=.123456789, scale=2.0, size=(3, 2))
desired = np.array([[-3.618412914693162, 2.635726692647081],
[-2.116923463013243, 0.807460983059643],
[ 1.446547137248593, 2.485684213886024]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_normal_0(self):
assert_equal(random.normal(scale=0), 0)
assert_raises(ValueError, random.normal, scale=-0.)
def test_pareto(self):
random = Generator(MT19937(self.seed))
actual = random.pareto(a=.123456789, size=(3, 2))
desired = np.array([[1.0394926776069018e+00, 7.7142534343505773e+04],
[7.2640150889064703e-01, 3.4650454783825594e+05],
[4.5852344481994740e+04, 6.5851383009539105e+07]])
# For some reason on 32-bit x86 Ubuntu 12.10 the [1, 0] entry in this
# matrix differs by 24 nulps. Discussion:
# https://mail.python.org/pipermail/numpy-discussion/2012-September/063801.html
# Consensus is that this is probably some gcc quirk that affects
# rounding but not in any important way, so we just use a looser
# tolerance on this test:
np.testing.assert_array_almost_equal_nulp(actual, desired, nulp=30)
def test_poisson(self):
random = Generator(MT19937(self.seed))
actual = random.poisson(lam=.123456789, size=(3, 2))
desired = np.array([[0, 0],
[0, 0],
[0, 0]])
assert_array_equal(actual, desired)
def test_poisson_exceptions(self):
lambig = np.iinfo('int64').max
lamneg = -1
assert_raises(ValueError, random.poisson, lamneg)
assert_raises(ValueError, random.poisson, [lamneg] * 10)
assert_raises(ValueError, random.poisson, lambig)
assert_raises(ValueError, random.poisson, [lambig] * 10)
with np.errstate(invalid='ignore'):
assert_raises(ValueError, random.poisson, np.nan)
assert_raises(ValueError, random.poisson, [np.nan] * 10)
def test_power(self):
random = Generator(MT19937(self.seed))
actual = random.power(a=.123456789, size=(3, 2))
desired = np.array([[1.977857368842754e-09, 9.806792196620341e-02],
[2.482442984543471e-10, 1.527108843266079e-01],
[8.188283434244285e-02, 3.950547209346948e-01]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_rayleigh(self):
random = Generator(MT19937(self.seed))
actual = random.rayleigh(scale=10, size=(3, 2))
desired = np.array([[ 4.51734079831581, 15.6802442485758 ],
[ 4.19850651287094, 17.08718809823704],
[14.7907457708776 , 15.85545333419775]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_rayleigh_0(self):
assert_equal(random.rayleigh(scale=0), 0)
assert_raises(ValueError, random.rayleigh, scale=-0.)
def test_standard_cauchy(self):
random = Generator(MT19937(self.seed))
actual = random.standard_cauchy(size=(3, 2))
desired = np.array([[-1.489437778266206, -3.275389641569784],
[ 0.560102864910406, -0.680780916282552],
[-1.314912905226277, 0.295852965660225]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_standard_exponential(self):
random = Generator(MT19937(self.seed))
actual = random.standard_exponential(size=(3, 2), method='inv')
desired = np.array([[0.102031839440643, 1.229350298474972],
[0.088137284693098, 1.459859985522667],
[1.093830802293668, 1.256977002164613]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_standard_expoential_type_error(self):
assert_raises(TypeError, random.standard_exponential, dtype=np.int32)
def test_standard_gamma(self):
random = Generator(MT19937(self.seed))
actual = random.standard_gamma(shape=3, size=(3, 2))
desired = np.array([[0.62970724056362, 1.22379851271008],
[3.899412530884 , 4.12479964250139],
[3.74994102464584, 3.74929307690815]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_standard_gammma_scalar_float(self):
random = Generator(MT19937(self.seed))
actual = random.standard_gamma(3, dtype=np.float32)
desired = 2.9242148399353027
assert_array_almost_equal(actual, desired, decimal=6)
def test_standard_gamma_float(self):
random = Generator(MT19937(self.seed))
actual = random.standard_gamma(shape=3, size=(3, 2))
desired = np.array([[0.62971, 1.2238 ],
[3.89941, 4.1248 ],
[3.74994, 3.74929]])
assert_array_almost_equal(actual, desired, decimal=5)
def test_standard_gammma_float_out(self):
actual = np.zeros((3, 2), dtype=np.float32)
random = Generator(MT19937(self.seed))
random.standard_gamma(10.0, out=actual, dtype=np.float32)
desired = np.array([[10.14987, 7.87012],
[ 9.46284, 12.56832],
[13.82495, 7.81533]], dtype=np.float32)
assert_array_almost_equal(actual, desired, decimal=5)
random = Generator(MT19937(self.seed))
random.standard_gamma(10.0, out=actual, size=(3, 2), dtype=np.float32)
assert_array_almost_equal(actual, desired, decimal=5)
def test_standard_gamma_unknown_type(self):
assert_raises(TypeError, random.standard_gamma, 1.,
dtype='int32')
def test_out_size_mismatch(self):
out = np.zeros(10)
assert_raises(ValueError, random.standard_gamma, 10.0, size=20,
out=out)
assert_raises(ValueError, random.standard_gamma, 10.0, size=(10, 1),
out=out)
def test_standard_gamma_0(self):
assert_equal(random.standard_gamma(shape=0), 0)
assert_raises(ValueError, random.standard_gamma, shape=-0.)
def test_standard_normal(self):
random = Generator(MT19937(self.seed))
actual = random.standard_normal(size=(3, 2))
desired = np.array([[-1.870934851846581, 1.25613495182354 ],
[-1.120190126006621, 0.342002097029821],
[ 0.661545174124296, 1.181113712443012]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_standard_normal_unsupported_type(self):
assert_raises(TypeError, random.standard_normal, dtype=np.int32)
def test_standard_t(self):
random = Generator(MT19937(self.seed))
actual = random.standard_t(df=10, size=(3, 2))
desired = np.array([[-1.484666193042647, 0.30597891831161 ],
[ 1.056684299648085, -0.407312602088507],
[ 0.130704414281157, -2.038053410490321]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_triangular(self):
random = Generator(MT19937(self.seed))
actual = random.triangular(left=5.12, mode=10.23, right=20.34,
size=(3, 2))
desired = np.array([[ 7.86664070590917, 13.6313848513185 ],
[ 7.68152445215983, 14.36169131136546],
[13.16105603911429, 13.72341621856971]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_uniform(self):
random = Generator(MT19937(self.seed))
actual = random.uniform(low=1.23, high=10.54, size=(3, 2))
desired = np.array([[2.13306255040998 , 7.816987531021207],
[2.015436610109887, 8.377577533009589],
[7.421792588856135, 7.891185744455209]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_uniform_range_bounds(self):
fmin = np.finfo('float').min
fmax = np.finfo('float').max
func = random.uniform
assert_raises(OverflowError, func, -np.inf, 0)
assert_raises(OverflowError, func, 0, np.inf)
assert_raises(OverflowError, func, fmin, fmax)
assert_raises(OverflowError, func, [-np.inf], [0])
assert_raises(OverflowError, func, [0], [np.inf])
# (fmax / 1e17) - fmin is within range, so this should not throw
# account for i386 extended precision DBL_MAX / 1e17 + DBL_MAX >
# DBL_MAX by increasing fmin a bit
random.uniform(low=np.nextafter(fmin, 1), high=fmax / 1e17)
def test_scalar_exception_propagation(self):
# Tests that exceptions are correctly propagated in distributions
# when called with objects that throw exceptions when converted to
# scalars.
#
# Regression test for gh: 8865
class ThrowingFloat(np.ndarray):
def __float__(self):
raise TypeError
throwing_float = np.array(1.0).view(ThrowingFloat)
assert_raises(TypeError, random.uniform, throwing_float,
throwing_float)
class ThrowingInteger(np.ndarray):
def __int__(self):
raise TypeError
throwing_int = np.array(1).view(ThrowingInteger)
assert_raises(TypeError, random.hypergeometric, throwing_int, 1, 1)
def test_vonmises(self):
random = Generator(MT19937(self.seed))
actual = random.vonmises(mu=1.23, kappa=1.54, size=(3, 2))
desired = np.array([[ 1.107972248690106, 2.841536476232361],
[ 1.832602376042457, 1.945511926976032],
[-0.260147475776542, 2.058047492231698]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_vonmises_small(self):
# check infinite loop, gh-4720
random = Generator(MT19937(self.seed))
r = random.vonmises(mu=0., kappa=1.1e-8, size=10**6)
assert_(np.isfinite(r).all())
def test_vonmises_nan(self):
random = Generator(MT19937(self.seed))
r = random.vonmises(mu=0., kappa=np.nan)
assert_(np.isnan(r))
def test_wald(self):
random = Generator(MT19937(self.seed))
actual = random.wald(mean=1.23, scale=1.54, size=(3, 2))
desired = np.array([[0.26871721804551, 3.2233942732115 ],
[2.20328374987066, 2.40958405189353],
[2.07093587449261, 0.73073890064369]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_weibull(self):
random = Generator(MT19937(self.seed))
actual = random.weibull(a=1.23, size=(3, 2))
desired = np.array([[0.138613914769468, 1.306463419753191],
[0.111623365934763, 1.446570494646721],
[1.257145775276011, 1.914247725027957]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_weibull_0(self):
random = Generator(MT19937(self.seed))
assert_equal(random.weibull(a=0, size=12), np.zeros(12))
assert_raises(ValueError, random.weibull, a=-0.)
def test_zipf(self):
random = Generator(MT19937(self.seed))
actual = random.zipf(a=1.23, size=(3, 2))
desired = np.array([[ 1, 1],
[ 10, 867],
[354, 2]])
assert_array_equal(actual, desired)
class TestBroadcast:
# tests that functions that broadcast behave
# correctly when presented with non-scalar arguments
def setup(self):
self.seed = 123456789
def test_uniform(self):
random = Generator(MT19937(self.seed))
low = [0]
high = [1]
uniform = random.uniform
desired = np.array([0.16693771389729, 0.19635129550675, 0.75563050964095])
random = Generator(MT19937(self.seed))
actual = random.uniform(low * 3, high)
assert_array_almost_equal(actual, desired, decimal=14)
random = Generator(MT19937(self.seed))
actual = random.uniform(low, high * 3)
assert_array_almost_equal(actual, desired, decimal=14)
def test_normal(self):
loc = [0]
scale = [1]
bad_scale = [-1]
random = Generator(MT19937(self.seed))
desired = np.array([-0.38736406738527, 0.79594375042255, 0.0197076236097])
random = Generator(MT19937(self.seed))
actual = random.normal(loc * 3, scale)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.normal, loc * 3, bad_scale)
random = Generator(MT19937(self.seed))
normal = random.normal
actual = normal(loc, scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, normal, loc, bad_scale * 3)
def test_beta(self):
a = [1]
b = [2]
bad_a = [-1]
bad_b = [-2]
desired = np.array([0.18719338682602, 0.73234824491364, 0.17928615186455])
random = Generator(MT19937(self.seed))
beta = random.beta
actual = beta(a * 3, b)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, beta, bad_a * 3, b)
assert_raises(ValueError, beta, a * 3, bad_b)
random = Generator(MT19937(self.seed))
actual = random.beta(a, b * 3)
assert_array_almost_equal(actual, desired, decimal=14)
def test_exponential(self):
scale = [1]
bad_scale = [-1]
desired = np.array([0.67245993212806, 0.21380495318094, 0.7177848928629])
random = Generator(MT19937(self.seed))
actual = random.exponential(scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.exponential, bad_scale * 3)
def test_standard_gamma(self):
shape = [1]
bad_shape = [-1]
desired = np.array([0.67245993212806, 0.21380495318094, 0.7177848928629])
random = Generator(MT19937(self.seed))
std_gamma = random.standard_gamma
actual = std_gamma(shape * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, std_gamma, bad_shape * 3)
def test_gamma(self):
shape = [1]
scale = [2]
bad_shape = [-1]
bad_scale = [-2]
desired = np.array([1.34491986425611, 0.42760990636187, 1.4355697857258])
random = Generator(MT19937(self.seed))
gamma = random.gamma
actual = gamma(shape * 3, scale)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, gamma, bad_shape * 3, scale)
assert_raises(ValueError, gamma, shape * 3, bad_scale)
random = Generator(MT19937(self.seed))
gamma = random.gamma
actual = gamma(shape, scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, gamma, bad_shape, scale * 3)
assert_raises(ValueError, gamma, shape, bad_scale * 3)
def test_f(self):
dfnum = [1]
dfden = [2]
bad_dfnum = [-1]
bad_dfden = [-2]
desired = np.array([0.07765056244107, 7.72951397913186, 0.05786093891763])
random = Generator(MT19937(self.seed))
f = random.f
actual = f(dfnum * 3, dfden)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, f, bad_dfnum * 3, dfden)
assert_raises(ValueError, f, dfnum * 3, bad_dfden)
random = Generator(MT19937(self.seed))
f = random.f
actual = f(dfnum, dfden * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, f, bad_dfnum, dfden * 3)
assert_raises(ValueError, f, dfnum, bad_dfden * 3)
def test_noncentral_f(self):
dfnum = [2]
dfden = [3]
nonc = [4]
bad_dfnum = [0]
bad_dfden = [-1]
bad_nonc = [-2]
desired = np.array([2.02434240411421, 12.91838601070124, 1.24395160354629])
random = Generator(MT19937(self.seed))
nonc_f = random.noncentral_f
actual = nonc_f(dfnum * 3, dfden, nonc)
assert_array_almost_equal(actual, desired, decimal=14)
assert np.all(np.isnan(nonc_f(dfnum, dfden, [np.nan] * 3)))
assert_raises(ValueError, nonc_f, bad_dfnum * 3, dfden, nonc)
assert_raises(ValueError, nonc_f, dfnum * 3, bad_dfden, nonc)
assert_raises(ValueError, nonc_f, dfnum * 3, dfden, bad_nonc)
random = Generator(MT19937(self.seed))
nonc_f = random.noncentral_f
actual = nonc_f(dfnum, dfden * 3, nonc)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, nonc_f, bad_dfnum, dfden * 3, nonc)
assert_raises(ValueError, nonc_f, dfnum, bad_dfden * 3, nonc)
assert_raises(ValueError, nonc_f, dfnum, dfden * 3, bad_nonc)
random = Generator(MT19937(self.seed))
nonc_f = random.noncentral_f
actual = nonc_f(dfnum, dfden, nonc * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, nonc_f, bad_dfnum, dfden, nonc * 3)
assert_raises(ValueError, nonc_f, dfnum, bad_dfden, nonc * 3)
assert_raises(ValueError, nonc_f, dfnum, dfden, bad_nonc * 3)
def test_noncentral_f_small_df(self):
random = Generator(MT19937(self.seed))
desired = np.array([0.04714867120827, 0.1239390327694])
actual = random.noncentral_f(0.9, 0.9, 2, size=2)
assert_array_almost_equal(actual, desired, decimal=14)
def test_chisquare(self):
df = [1]
bad_df = [-1]
desired = np.array([0.05573640064251, 1.47220224353539, 2.9469379318589])
random = Generator(MT19937(self.seed))
actual = random.chisquare(df * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.chisquare, bad_df * 3)
def test_noncentral_chisquare(self):
df = [1]
nonc = [2]
bad_df = [-1]
bad_nonc = [-2]
desired = np.array([0.07710766249436, 5.27829115110304, 0.630732147399])
random = Generator(MT19937(self.seed))
nonc_chi = random.noncentral_chisquare
actual = nonc_chi(df * 3, nonc)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, nonc_chi, bad_df * 3, nonc)
assert_raises(ValueError, nonc_chi, df * 3, bad_nonc)
random = Generator(MT19937(self.seed))
nonc_chi = random.noncentral_chisquare
actual = nonc_chi(df, nonc * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, nonc_chi, bad_df, nonc * 3)
assert_raises(ValueError, nonc_chi, df, bad_nonc * 3)
def test_standard_t(self):
df = [1]
bad_df = [-1]
desired = np.array([-1.39498829447098, -1.23058658835223, 0.17207021065983])
random = Generator(MT19937(self.seed))
actual = random.standard_t(df * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.standard_t, bad_df * 3)
def test_vonmises(self):
mu = [2]
kappa = [1]
bad_kappa = [-1]
desired = np.array([2.25935584988528, 2.23326261461399, -2.84152146503326])
random = Generator(MT19937(self.seed))
actual = random.vonmises(mu * 3, kappa)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.vonmises, mu * 3, bad_kappa)
random = Generator(MT19937(self.seed))
actual = random.vonmises(mu, kappa * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.vonmises, mu, bad_kappa * 3)
def test_pareto(self):
a = [1]
bad_a = [-1]
desired = np.array([0.95905052946317, 0.2383810889437 , 1.04988745750013])
random = Generator(MT19937(self.seed))
actual = random.pareto(a * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.pareto, bad_a * 3)
def test_weibull(self):
a = [1]
bad_a = [-1]
desired = np.array([0.67245993212806, 0.21380495318094, 0.7177848928629])
random = Generator(MT19937(self.seed))
actual = random.weibull(a * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.weibull, bad_a * 3)
def test_power(self):
a = [1]
bad_a = [-1]
desired = np.array([0.48954864361052, 0.19249412888486, 0.51216834058807])
random = Generator(MT19937(self.seed))
actual = random.power(a * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.power, bad_a * 3)
def test_laplace(self):
loc = [0]
scale = [1]
bad_scale = [-1]
desired = np.array([-1.09698732625119, -0.93470271947368, 0.71592671378202])
random = Generator(MT19937(self.seed))
laplace = random.laplace
actual = laplace(loc * 3, scale)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, laplace, loc * 3, bad_scale)
random = Generator(MT19937(self.seed))
laplace = random.laplace
actual = laplace(loc, scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, laplace, loc, bad_scale * 3)
def test_gumbel(self):
loc = [0]
scale = [1]
bad_scale = [-1]
desired = np.array([1.70020068231762, 1.52054354273631, -0.34293267607081])
random = Generator(MT19937(self.seed))
gumbel = random.gumbel
actual = gumbel(loc * 3, scale)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, gumbel, loc * 3, bad_scale)
random = Generator(MT19937(self.seed))
gumbel = random.gumbel
actual = gumbel(loc, scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, gumbel, loc, bad_scale * 3)
def test_logistic(self):
loc = [0]
scale = [1]
bad_scale = [-1]
desired = np.array([-1.607487640433, -1.40925686003678, 1.12887112820397])
random = Generator(MT19937(self.seed))
actual = random.logistic(loc * 3, scale)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.logistic, loc * 3, bad_scale)
random = Generator(MT19937(self.seed))
actual = random.logistic(loc, scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.logistic, loc, bad_scale * 3)
assert_equal(random.logistic(1.0, 0.0), 1.0)
def test_lognormal(self):
mean = [0]
sigma = [1]
bad_sigma = [-1]
desired = np.array([0.67884390500697, 2.21653186290321, 1.01990310084276])
random = Generator(MT19937(self.seed))
lognormal = random.lognormal
actual = lognormal(mean * 3, sigma)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, lognormal, mean * 3, bad_sigma)
random = Generator(MT19937(self.seed))
actual = random.lognormal(mean, sigma * 3)
assert_raises(ValueError, random.lognormal, mean, bad_sigma * 3)
def test_rayleigh(self):
scale = [1]
bad_scale = [-1]
desired = np.array([0.60439534475066, 0.66120048396359, 1.67873398389499])
random = Generator(MT19937(self.seed))
actual = random.rayleigh(scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.rayleigh, bad_scale * 3)
def test_wald(self):
mean = [0.5]
scale = [1]
bad_mean = [0]
bad_scale = [-2]
desired = np.array([0.38052407392905, 0.50701641508592, 0.484935249864])
random = Generator(MT19937(self.seed))
actual = random.wald(mean * 3, scale)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.wald, bad_mean * 3, scale)
assert_raises(ValueError, random.wald, mean * 3, bad_scale)
random = Generator(MT19937(self.seed))
actual = random.wald(mean, scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.wald, bad_mean, scale * 3)
assert_raises(ValueError, random.wald, mean, bad_scale * 3)
def test_triangular(self):
left = [1]
right = [3]
mode = [2]
bad_left_one = [3]
bad_mode_one = [4]
bad_left_two, bad_mode_two = right * 2
desired = np.array([1.57781954604754, 1.62665986867957, 2.30090130831326])
random = Generator(MT19937(self.seed))
triangular = random.triangular
actual = triangular(left * 3, mode, right)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, triangular, bad_left_one * 3, mode, right)
assert_raises(ValueError, triangular, left * 3, bad_mode_one, right)
assert_raises(ValueError, triangular, bad_left_two * 3, bad_mode_two,
right)
random = Generator(MT19937(self.seed))
triangular = random.triangular
actual = triangular(left, mode * 3, right)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, triangular, bad_left_one, mode * 3, right)
assert_raises(ValueError, triangular, left, bad_mode_one * 3, right)
assert_raises(ValueError, triangular, bad_left_two, bad_mode_two * 3,
right)
random = Generator(MT19937(self.seed))
triangular = random.triangular
actual = triangular(left, mode, right * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, triangular, bad_left_one, mode, right * 3)
assert_raises(ValueError, triangular, left, bad_mode_one, right * 3)
assert_raises(ValueError, triangular, bad_left_two, bad_mode_two,
right * 3)
assert_raises(ValueError, triangular, 10., 0., 20.)
assert_raises(ValueError, triangular, 10., 25., 20.)
assert_raises(ValueError, triangular, 10., 10., 10.)
def test_binomial(self):
n = [1]
p = [0.5]
bad_n = [-1]
bad_p_one = [-1]
bad_p_two = [1.5]
desired = np.array([0, 0, 1])
random = Generator(MT19937(self.seed))
binom = random.binomial
actual = binom(n * 3, p)
assert_array_equal(actual, desired)
assert_raises(ValueError, binom, bad_n * 3, p)
assert_raises(ValueError, binom, n * 3, bad_p_one)
assert_raises(ValueError, binom, n * 3, bad_p_two)
random = Generator(MT19937(self.seed))
actual = random.binomial(n, p * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, binom, bad_n, p * 3)
assert_raises(ValueError, binom, n, bad_p_one * 3)
assert_raises(ValueError, binom, n, bad_p_two * 3)
def test_negative_binomial(self):
n = [1]
p = [0.5]
bad_n = [-1]
bad_p_one = [-1]
bad_p_two = [1.5]
desired = np.array([0, 2, 1], dtype=np.int64)
random = Generator(MT19937(self.seed))
neg_binom = random.negative_binomial
actual = neg_binom(n * 3, p)
assert_array_equal(actual, desired)
assert_raises(ValueError, neg_binom, bad_n * 3, p)
assert_raises(ValueError, neg_binom, n * 3, bad_p_one)
assert_raises(ValueError, neg_binom, n * 3, bad_p_two)
random = Generator(MT19937(self.seed))
neg_binom = random.negative_binomial
actual = neg_binom(n, p * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, neg_binom, bad_n, p * 3)
assert_raises(ValueError, neg_binom, n, bad_p_one * 3)
assert_raises(ValueError, neg_binom, n, bad_p_two * 3)
def test_poisson(self):
lam = [1]
bad_lam_one = [-1]
desired = np.array([0, 0, 3])
random = Generator(MT19937(self.seed))
max_lam = random._poisson_lam_max
bad_lam_two = [max_lam * 2]
poisson = random.poisson
actual = poisson(lam * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, poisson, bad_lam_one * 3)
assert_raises(ValueError, poisson, bad_lam_two * 3)
def test_zipf(self):
a = [2]
bad_a = [0]
desired = np.array([1, 8, 1])
random = Generator(MT19937(self.seed))
zipf = random.zipf
actual = zipf(a * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, zipf, bad_a * 3)
with np.errstate(invalid='ignore'):
assert_raises(ValueError, zipf, np.nan)
assert_raises(ValueError, zipf, [0, 0, np.nan])
def test_geometric(self):
p = [0.5]
bad_p_one = [-1]
bad_p_two = [1.5]
desired = np.array([1, 1, 3])
random = Generator(MT19937(self.seed))
geometric = random.geometric
actual = geometric(p * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, geometric, bad_p_one * 3)
assert_raises(ValueError, geometric, bad_p_two * 3)
def test_hypergeometric(self):
ngood = [1]
nbad = [2]
nsample = [2]
bad_ngood = [-1]
bad_nbad = [-2]
bad_nsample_one = [-1]
bad_nsample_two = [4]
desired = np.array([0, 0, 1])
random = Generator(MT19937(self.seed))
actual = random.hypergeometric(ngood * 3, nbad, nsample)
assert_array_equal(actual, desired)
assert_raises(ValueError, random.hypergeometric, bad_ngood * 3, nbad, nsample)
assert_raises(ValueError, random.hypergeometric, ngood * 3, bad_nbad, nsample)
assert_raises(ValueError, random.hypergeometric, ngood * 3, nbad, bad_nsample_one)
assert_raises(ValueError, random.hypergeometric, ngood * 3, nbad, bad_nsample_two)
random = Generator(MT19937(self.seed))
actual = random.hypergeometric(ngood, nbad * 3, nsample)
assert_array_equal(actual, desired)
assert_raises(ValueError, random.hypergeometric, bad_ngood, nbad * 3, nsample)
assert_raises(ValueError, random.hypergeometric, ngood, bad_nbad * 3, nsample)
assert_raises(ValueError, random.hypergeometric, ngood, nbad * 3, bad_nsample_one)
assert_raises(ValueError, random.hypergeometric, ngood, nbad * 3, bad_nsample_two)
random = Generator(MT19937(self.seed))
hypergeom = random.hypergeometric
actual = hypergeom(ngood, nbad, nsample * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, hypergeom, bad_ngood, nbad, nsample * 3)
assert_raises(ValueError, hypergeom, ngood, bad_nbad, nsample * 3)
assert_raises(ValueError, hypergeom, ngood, nbad, bad_nsample_one * 3)
assert_raises(ValueError, hypergeom, ngood, nbad, bad_nsample_two * 3)
assert_raises(ValueError, hypergeom, -1, 10, 20)
assert_raises(ValueError, hypergeom, 10, -1, 20)
assert_raises(ValueError, hypergeom, 10, 10, -1)
assert_raises(ValueError, hypergeom, 10, 10, 25)
# ValueError for arguments that are too big.
assert_raises(ValueError, hypergeom, 2**30, 10, 20)
assert_raises(ValueError, hypergeom, 999, 2**31, 50)
assert_raises(ValueError, hypergeom, 999, [2**29, 2**30], 1000)
def test_logseries(self):
p = [0.5]
bad_p_one = [2]
bad_p_two = [-1]
desired = np.array([1, 1, 1])
random = Generator(MT19937(self.seed))
logseries = random.logseries
actual = logseries(p * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, logseries, bad_p_one * 3)
assert_raises(ValueError, logseries, bad_p_two * 3)
def test_multinomial(self):
random = Generator(MT19937(self.seed))
actual = random.multinomial([5, 20], [1 / 6.] * 6, size=(3, 2))
desired = np.array([[[0, 0, 2, 1, 2, 0],
[2, 3, 6, 4, 2, 3]],
[[1, 0, 1, 0, 2, 1],
[7, 2, 2, 1, 4, 4]],
[[0, 2, 0, 1, 2, 0],
[3, 2, 3, 3, 4, 5]]], dtype=np.int64)
assert_array_equal(actual, desired)
random = Generator(MT19937(self.seed))
actual = random.multinomial([5, 20], [1 / 6.] * 6)
desired = np.array([[0, 0, 2, 1, 2, 0],
[2, 3, 6, 4, 2, 3]], dtype=np.int64)
assert_array_equal(actual, desired)
class TestThread:
# make sure each state produces the same sequence even in threads
def setup(self):
self.seeds = range(4)
def check_function(self, function, sz):
from threading import Thread
out1 = np.empty((len(self.seeds),) + sz)
out2 = np.empty((len(self.seeds),) + sz)
# threaded generation
t = [Thread(target=function, args=(Generator(MT19937(s)), o))
for s, o in zip(self.seeds, out1)]
[x.start() for x in t]
[x.join() for x in t]
# the same serial
for s, o in zip(self.seeds, out2):
function(Generator(MT19937(s)), o)
# these platforms change x87 fpu precision mode in threads
if np.intp().dtype.itemsize == 4 and sys.platform == "win32":
assert_array_almost_equal(out1, out2)
else:
assert_array_equal(out1, out2)
def test_normal(self):
def gen_random(state, out):
out[...] = state.normal(size=10000)
self.check_function(gen_random, sz=(10000,))
def test_exp(self):
def gen_random(state, out):
out[...] = state.exponential(scale=np.ones((100, 1000)))
self.check_function(gen_random, sz=(100, 1000))
def test_multinomial(self):
def gen_random(state, out):
out[...] = state.multinomial(10, [1 / 6.] * 6, size=10000)
self.check_function(gen_random, sz=(10000, 6))
# See Issue #4263
class TestSingleEltArrayInput:
def setup(self):
self.argOne = np.array([2])
self.argTwo = np.array([3])
self.argThree = np.array([4])
self.tgtShape = (1,)
def test_one_arg_funcs(self):
funcs = (random.exponential, random.standard_gamma,
random.chisquare, random.standard_t,
random.pareto, random.weibull,
random.power, random.rayleigh,
random.poisson, random.zipf,
random.geometric, random.logseries)
probfuncs = (random.geometric, random.logseries)
for func in funcs:
if func in probfuncs: # p < 1.0
out = func(np.array([0.5]))
else:
out = func(self.argOne)
assert_equal(out.shape, self.tgtShape)
def test_two_arg_funcs(self):
funcs = (random.uniform, random.normal,
random.beta, random.gamma,
random.f, random.noncentral_chisquare,
random.vonmises, random.laplace,
random.gumbel, random.logistic,
random.lognormal, random.wald,
random.binomial, random.negative_binomial)
probfuncs = (random.binomial, random.negative_binomial)
for func in funcs:
if func in probfuncs: # p <= 1
argTwo = np.array([0.5])
else:
argTwo = self.argTwo
out = func(self.argOne, argTwo)
assert_equal(out.shape, self.tgtShape)
out = func(self.argOne[0], argTwo)
assert_equal(out.shape, self.tgtShape)
out = func(self.argOne, argTwo[0])
assert_equal(out.shape, self.tgtShape)
def test_integers(self, endpoint):
itype = [np.bool_, np.int8, np.uint8, np.int16, np.uint16,
np.int32, np.uint32, np.int64, np.uint64]
func = random.integers
high = np.array([1])
low = np.array([0])
for dt in itype:
out = func(low, high, endpoint=endpoint, dtype=dt)
assert_equal(out.shape, self.tgtShape)
out = func(low[0], high, endpoint=endpoint, dtype=dt)
assert_equal(out.shape, self.tgtShape)
out = func(low, high[0], endpoint=endpoint, dtype=dt)
assert_equal(out.shape, self.tgtShape)
def test_three_arg_funcs(self):
funcs = [random.noncentral_f, random.triangular,
random.hypergeometric]
for func in funcs:
out = func(self.argOne, self.argTwo, self.argThree)
assert_equal(out.shape, self.tgtShape)
out = func(self.argOne[0], self.argTwo, self.argThree)
assert_equal(out.shape, self.tgtShape)
out = func(self.argOne, self.argTwo[0], self.argThree)
assert_equal(out.shape, self.tgtShape)
@pytest.mark.parametrize("config", JUMP_TEST_DATA)
def test_jumped(config):
# Each config contains the initial seed, a number of raw steps
# the md5 hashes of the initial and the final states' keys and
seed = config["seed"]
steps = config["steps"]
mt19937 = MT19937(seed)
mt19937.random_raw(steps)
key = mt19937.state["state"]["key"]
if sys.byteorder == 'big':
key = key.byteswap()
md5 = hashlib.md5(key)
assert mt19937.state["state"]["pos"] == config["initial"]["pos"]
assert md5.hexdigest() == config["initial"]["key_md5"]
jumped = mt19937.jumped()
key = jumped.state["state"]["key"]
if sys.byteorder == 'big':
key = key.byteswap()
md5 = hashlib.md5(key)
assert jumped.state["state"]["pos"] == config["jumped"]["pos"]
assert md5.hexdigest() == config["jumped"]["key_md5"]
| true | true |
f72b75b24d8df7b71d3467658ad40886dad96118 | 454 | py | Python | snacks/models.py | anas-abusaif/djangox | 969dbb9ade0f242f250bd65a1a0d6893d1fea07f | [
"MIT"
] | null | null | null | snacks/models.py | anas-abusaif/djangox | 969dbb9ade0f242f250bd65a1a0d6893d1fea07f | [
"MIT"
] | null | null | null | snacks/models.py | anas-abusaif/djangox | 969dbb9ade0f242f250bd65a1a0d6893d1fea07f | [
"MIT"
] | null | null | null | from django.db import models
from django.contrib.auth import get_user_model
from django.urls import reverse
# Create your models here.
class Snack(models.Model):
title = models.CharField(max_length=64)
purchaser = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
description = models.TextField()
def __str__(self) -> str:
return self.title
def get_absolute_url(self):
return reverse("snack_detail", args=[str(self.pk)]) | 28.375 | 75 | 0.759912 | from django.db import models
from django.contrib.auth import get_user_model
from django.urls import reverse
class Snack(models.Model):
title = models.CharField(max_length=64)
purchaser = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
description = models.TextField()
def __str__(self) -> str:
return self.title
def get_absolute_url(self):
return reverse("snack_detail", args=[str(self.pk)]) | true | true |
f72b75d390d9cde5998e85de12cd980938336177 | 5,168 | py | Python | rllib/examples/env/parametric_actions_cartpole.py | daobook/ray | af9f1ef4dc160e0671206556b387f8017f3c3930 | [
"Apache-2.0"
] | 33 | 2020-05-27T14:25:24.000Z | 2022-03-22T06:11:30.000Z | rllib/examples/env/parametric_actions_cartpole.py | daobook/ray | af9f1ef4dc160e0671206556b387f8017f3c3930 | [
"Apache-2.0"
] | 227 | 2021-10-01T08:00:01.000Z | 2021-12-28T16:47:26.000Z | rllib/examples/env/parametric_actions_cartpole.py | gramhagen/ray | c18caa4db36d466718bdbcb2229aa0b2dc03da1f | [
"Apache-2.0"
] | 5 | 2020-08-06T15:53:07.000Z | 2022-02-09T03:31:31.000Z | import gym
from gym.spaces import Box, Dict, Discrete
import numpy as np
import random
class ParametricActionsCartPole(gym.Env):
"""Parametric action version of CartPole.
In this env there are only ever two valid actions, but we pretend there are
actually up to `max_avail_actions` actions that can be taken, and the two
valid actions are randomly hidden among this set.
At each step, we emit a dict of:
- the actual cart observation
- a mask of valid actions (e.g., [0, 0, 1, 0, 0, 1] for 6 max avail)
- the list of action embeddings (w/ zeroes for invalid actions) (e.g.,
[[0, 0],
[0, 0],
[-0.2322, -0.2569],
[0, 0],
[0, 0],
[0.7878, 1.2297]] for max_avail_actions=6)
In a real environment, the actions embeddings would be larger than two
units of course, and also there would be a variable number of valid actions
per step instead of always [LEFT, RIGHT].
"""
def __init__(self, max_avail_actions):
# Use simple random 2-unit action embeddings for [LEFT, RIGHT]
self.left_action_embed = np.random.randn(2)
self.right_action_embed = np.random.randn(2)
self.action_space = Discrete(max_avail_actions)
self.wrapped = gym.make("CartPole-v0")
self.observation_space = Dict({
"action_mask": Box(
0, 1, shape=(max_avail_actions, ), dtype=np.float32),
"avail_actions": Box(-10, 10, shape=(max_avail_actions, 2)),
"cart": self.wrapped.observation_space,
})
def update_avail_actions(self):
self.action_assignments = np.array(
[[0., 0.]] * self.action_space.n, dtype=np.float32)
self.action_mask = np.array(
[0.] * self.action_space.n, dtype=np.float32)
self.left_idx, self.right_idx = random.sample(
range(self.action_space.n), 2)
self.action_assignments[self.left_idx] = self.left_action_embed
self.action_assignments[self.right_idx] = self.right_action_embed
self.action_mask[self.left_idx] = 1
self.action_mask[self.right_idx] = 1
def reset(self):
self.update_avail_actions()
return {
"action_mask": self.action_mask,
"avail_actions": self.action_assignments,
"cart": self.wrapped.reset(),
}
def step(self, action):
if action == self.left_idx:
actual_action = 0
elif action == self.right_idx:
actual_action = 1
else:
raise ValueError(
"Chosen action was not one of the non-zero action embeddings",
action, self.action_assignments, self.action_mask,
self.left_idx, self.right_idx)
orig_obs, rew, done, info = self.wrapped.step(actual_action)
self.update_avail_actions()
self.action_mask = self.action_mask.astype(np.float32)
obs = {
"action_mask": self.action_mask,
"avail_actions": self.action_assignments,
"cart": orig_obs,
}
return obs, rew, done, info
class ParametricActionsCartPoleNoEmbeddings(gym.Env):
"""Same as the above ParametricActionsCartPole.
However, action embeddings are not published inside observations,
but will be learnt by the model.
At each step, we emit a dict of:
- the actual cart observation
- a mask of valid actions (e.g., [0, 0, 1, 0, 0, 1] for 6 max avail)
- action embeddings (w/ "dummy embedding" for invalid actions) are
outsourced in the model and will be learned.
"""
def __init__(self, max_avail_actions):
# Randomly set which two actions are valid and available.
self.left_idx, self.right_idx = random.sample(
range(max_avail_actions), 2)
self.valid_avail_actions_mask = np.array(
[0.] * max_avail_actions, dtype=np.float32)
self.valid_avail_actions_mask[self.left_idx] = 1
self.valid_avail_actions_mask[self.right_idx] = 1
self.action_space = Discrete(max_avail_actions)
self.wrapped = gym.make("CartPole-v0")
self.observation_space = Dict({
"valid_avail_actions_mask": Box(0, 1, shape=(max_avail_actions, )),
"cart": self.wrapped.observation_space,
})
def reset(self):
return {
"valid_avail_actions_mask": self.valid_avail_actions_mask,
"cart": self.wrapped.reset(),
}
def step(self, action):
if action == self.left_idx:
actual_action = 0
elif action == self.right_idx:
actual_action = 1
else:
raise ValueError(
"Chosen action was not one of the non-zero action embeddings",
action, self.valid_avail_actions_mask, self.left_idx,
self.right_idx)
orig_obs, rew, done, info = self.wrapped.step(actual_action)
obs = {
"valid_avail_actions_mask": self.valid_avail_actions_mask,
"cart": orig_obs,
}
return obs, rew, done, info
| 38.567164 | 79 | 0.615906 | import gym
from gym.spaces import Box, Dict, Discrete
import numpy as np
import random
class ParametricActionsCartPole(gym.Env):
def __init__(self, max_avail_actions):
self.left_action_embed = np.random.randn(2)
self.right_action_embed = np.random.randn(2)
self.action_space = Discrete(max_avail_actions)
self.wrapped = gym.make("CartPole-v0")
self.observation_space = Dict({
"action_mask": Box(
0, 1, shape=(max_avail_actions, ), dtype=np.float32),
"avail_actions": Box(-10, 10, shape=(max_avail_actions, 2)),
"cart": self.wrapped.observation_space,
})
def update_avail_actions(self):
self.action_assignments = np.array(
[[0., 0.]] * self.action_space.n, dtype=np.float32)
self.action_mask = np.array(
[0.] * self.action_space.n, dtype=np.float32)
self.left_idx, self.right_idx = random.sample(
range(self.action_space.n), 2)
self.action_assignments[self.left_idx] = self.left_action_embed
self.action_assignments[self.right_idx] = self.right_action_embed
self.action_mask[self.left_idx] = 1
self.action_mask[self.right_idx] = 1
def reset(self):
self.update_avail_actions()
return {
"action_mask": self.action_mask,
"avail_actions": self.action_assignments,
"cart": self.wrapped.reset(),
}
def step(self, action):
if action == self.left_idx:
actual_action = 0
elif action == self.right_idx:
actual_action = 1
else:
raise ValueError(
"Chosen action was not one of the non-zero action embeddings",
action, self.action_assignments, self.action_mask,
self.left_idx, self.right_idx)
orig_obs, rew, done, info = self.wrapped.step(actual_action)
self.update_avail_actions()
self.action_mask = self.action_mask.astype(np.float32)
obs = {
"action_mask": self.action_mask,
"avail_actions": self.action_assignments,
"cart": orig_obs,
}
return obs, rew, done, info
class ParametricActionsCartPoleNoEmbeddings(gym.Env):
def __init__(self, max_avail_actions):
self.left_idx, self.right_idx = random.sample(
range(max_avail_actions), 2)
self.valid_avail_actions_mask = np.array(
[0.] * max_avail_actions, dtype=np.float32)
self.valid_avail_actions_mask[self.left_idx] = 1
self.valid_avail_actions_mask[self.right_idx] = 1
self.action_space = Discrete(max_avail_actions)
self.wrapped = gym.make("CartPole-v0")
self.observation_space = Dict({
"valid_avail_actions_mask": Box(0, 1, shape=(max_avail_actions, )),
"cart": self.wrapped.observation_space,
})
def reset(self):
return {
"valid_avail_actions_mask": self.valid_avail_actions_mask,
"cart": self.wrapped.reset(),
}
def step(self, action):
if action == self.left_idx:
actual_action = 0
elif action == self.right_idx:
actual_action = 1
else:
raise ValueError(
"Chosen action was not one of the non-zero action embeddings",
action, self.valid_avail_actions_mask, self.left_idx,
self.right_idx)
orig_obs, rew, done, info = self.wrapped.step(actual_action)
obs = {
"valid_avail_actions_mask": self.valid_avail_actions_mask,
"cart": orig_obs,
}
return obs, rew, done, info
| true | true |
f72b75dd9e026a6ef00652afd5b76efddbde22d2 | 192 | py | Python | captain_comeback/restart/messages.py | waldo2590/captain-comeback | e02e3774eab62d7b8ba454331a785e2ae32c89fc | [
"MIT"
] | null | null | null | captain_comeback/restart/messages.py | waldo2590/captain-comeback | e02e3774eab62d7b8ba454331a785e2ae32c89fc | [
"MIT"
] | null | null | null | captain_comeback/restart/messages.py | waldo2590/captain-comeback | e02e3774eab62d7b8ba454331a785e2ae32c89fc | [
"MIT"
] | 1 | 2020-10-27T06:40:08.000Z | 2020-10-27T06:40:08.000Z | # coding:utf-8
class RestartRequestedMessage(object):
def __init__(self, cg):
self.cg = cg
class RestartCompleteMessage(object):
def __init__(self, cg):
self.cg = cg
| 19.2 | 38 | 0.661458 |
class RestartRequestedMessage(object):
def __init__(self, cg):
self.cg = cg
class RestartCompleteMessage(object):
def __init__(self, cg):
self.cg = cg
| true | true |
f72b75e5be3cd503344771ffbf3987aff531bc9b | 416 | py | Python | plotly/validators/scatterpolar/_thetasrc.py | faezs/plotly.py | 6009b5b9c746e5d2a2849ad255a4eb234b551ed7 | [
"MIT"
] | 2 | 2020-03-24T11:41:14.000Z | 2021-01-14T07:59:43.000Z | plotly/validators/scatterpolar/_thetasrc.py | faezs/plotly.py | 6009b5b9c746e5d2a2849ad255a4eb234b551ed7 | [
"MIT"
] | null | null | null | plotly/validators/scatterpolar/_thetasrc.py | faezs/plotly.py | 6009b5b9c746e5d2a2849ad255a4eb234b551ed7 | [
"MIT"
] | 4 | 2019-06-03T14:49:12.000Z | 2022-01-06T01:05:12.000Z | import _plotly_utils.basevalidators
class ThetasrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self, plotly_name='thetasrc', parent_name='scatterpolar', **kwargs
):
super(ThetasrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type='none',
role='info',
**kwargs
)
| 26 | 74 | 0.629808 | import _plotly_utils.basevalidators
class ThetasrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self, plotly_name='thetasrc', parent_name='scatterpolar', **kwargs
):
super(ThetasrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type='none',
role='info',
**kwargs
)
| true | true |
f72b76631a7a3c4e17aca32054d6f0a3ca9e33a8 | 14,058 | py | Python | jax_omeroutils/importer.py | mellertd/jax-omeroutils | 0190522109f9476e25f55292693dfa56f1037606 | [
"MIT"
] | null | null | null | jax_omeroutils/importer.py | mellertd/jax-omeroutils | 0190522109f9476e25f55292693dfa56f1037606 | [
"MIT"
] | null | null | null | jax_omeroutils/importer.py | mellertd/jax-omeroutils | 0190522109f9476e25f55292693dfa56f1037606 | [
"MIT"
] | null | null | null | """
This module is for managing OMERO imports, making use of the OMERO CLI,
which can be called from a Python script. Note that this code requires
a properly structured import.json file, which is produced during data
intake (using the intake.py module).
"""
import logging
from ezomero import post_dataset, post_project
from ezomero import get_image_ids, link_images_to_dataset
from ezomero import post_screen, link_plates_to_screen
from importlib import import_module
from omero.cli import CLI
from omero.plugins.sessions import SessionsControl
from omero.rtypes import rstring
from omero.sys import Parameters
from omero.gateway import MapAnnotationWrapper
from pathlib import Path
ImportControl = import_module("omero.plugins.import").ImportControl
# Constants
CURRENT_MD_NS = 'jax.org/omeroutils/user_submitted/v0'
# Functions
def set_or_create_project(conn, project_name):
"""Create a new Project unless one already exists with that name.
Parameter
---------
conn : ``omero.gateway.BlitzGateway`` object.
OMERO connection.
project_name : str
The name of the Project needed. If there is no Project with a matching
name in the group specified in ``conn``, a new Project will be created.
Returns
-------
project_id : int
The id of the Project that was either found or created.
"""
ps = conn.getObjects('Project', attributes={'name': project_name})
ps = list(ps)
if len(ps) == 0:
project_id = post_project(conn, project_name)
print(f'Created new Project:{project_id}')
else:
project_id = ps[0].getId()
return project_id
def set_or_create_dataset(conn, project_id, dataset_name):
"""Create a new Dataset unless one already exists with that name/Project.
Parameter
---------
conn : ``omero.gateway.BlitzGateway`` object.
OMERO connection.
project_id : int
Id of Project in which to find/create Dataset.
dataset_name : str
The name of the Dataset needed. If there is no Dataset with a matching
name in the group specified in ``conn``, in the Project specified with
``project_id``, a new Dataset will be created accordingly.
Returns
-------
dataset_id : int
The id of the Dataset that was either found or created.
"""
ds = conn.getObjects('Dataset',
attributes={'name': dataset_name},
opts={'project': project_id})
ds = list(ds)
if len(ds) == 0:
dataset_id = post_dataset(conn, dataset_name, project_id=project_id)
print(f'Created new Dataset:{dataset_id}')
else:
dataset_id = ds[0].getId()
return dataset_id
def set_or_create_screen(conn, screen_name):
"""Create a new Screen unless one already exists with that name.
Parameter
---------
conn : ``omero.gateway.BlitzGateway`` object.
OMERO connection.
screen_name : str
The name of the Screen needed. If there is no Screen with a matching
name in the group specified in ``conn``, a new Screen will be created.
Returns
-------
screen_id : int
The id of the Project that was either found or created.
"""
ss = conn.getObjects('Screen', attributes={'name': screen_name})
ss = list(ss)
if len(ss) == 0:
screen_id = post_screen(conn, screen_name)
print(f'Created new Screen:{screen_id}')
else:
screen_id = ss[0].getId()
return screen_id
def multi_post_map_annotation(conn, object_type, object_ids, kv_dict, ns):
"""Create a single new MapAnnotation and link to multiple images.
Parameters
----------
conn : ``omero.gateway.BlitzGateway`` object
OMERO connection.
object_type : str
OMERO object type, passed to ``BlitzGateway.getObjects``
object_ids : int or list of ints
IDs of objects to which the new MapAnnotation will be linked.
kv_dict : dict
key-value pairs that will be included in the MapAnnotation
ns : str
Namespace for the MapAnnotation
Notes
-----
All keys and values are converted to strings before saving in OMERO.
Returns
-------
map_ann_id : int
IDs of newly created MapAnnotation
Examples
--------
>>> ns = 'jax.org/jax/example/namespace'
>>> d = {'species': 'human',
'occupation': 'time traveler'
'first name': 'Kyle',
'surname': 'Reese'}
>>> multi_post_map_annotation(conn, "Image", [23,56,78], d, ns)
234
"""
if type(object_ids) not in [list, int]:
raise TypeError('object_ids must be list or integer')
if type(object_ids) is not list:
object_ids = [object_ids]
if len(object_ids) == 0:
raise ValueError('object_ids must contain one or more items')
if type(kv_dict) is not dict:
raise TypeError('kv_dict must be of type `dict`')
kv_pairs = []
for k, v in kv_dict.items():
k = str(k)
v = str(v)
kv_pairs.append([k, v])
map_ann = MapAnnotationWrapper(conn)
map_ann.setNs(str(ns))
map_ann.setValue(kv_pairs)
map_ann.save()
for o in conn.getObjects(object_type, object_ids):
o.linkAnnotation(map_ann)
return map_ann.getId()
# Class definitions
class Importer:
"""Class for managing OMERO imports using OMERO CLI.
Metadata from ``import.json`` (item in 'import_targets') is required for
assigning to Project/Dataset and adding MapAnnotations.
Parameters
----------
conn : ``omero.gateway.BlitzGateway`` object.
OMERO connection.
file_path : pathlike object
Path to the file to imported into OMERO.
import_md : dict
Contains metadata required for import and annotation. Generally, at
item from ``import.json`` ('import_targets').
Attributes
----------
conn : ``omero.gateway.BlitzGateway`` object.
From parameter given at initialization.
file_path : ``pathlib.Path`` object
From parameter given at initialization.
md : dict
From ``import_md`` parameter given at initialization.
session_uuid : str
UUID for OMERO session represented by ``self.conn``. Supplied to
OMERO CLI for connection purposes.
filename : str
Filename of file to be imported. Populated from ``self.md``.
project : str
Name of Project to contain the image. Populated from ``self.md``.
dataset : str
Name of Dataset to contain the image. Poplulated from ``self.md``.
imported : boolean
Flag indicating import status.
image_ids : list of ints
The Ids of the images in OMERO. Populated after a file is imported.
This list may contain one or more images derived from a single file.
"""
def __init__(self, conn, file_path, import_md):
self.conn = conn
self.file_path = Path(file_path)
self.md = import_md
self.session_uuid = conn.getSession().getUuid().val
self.filename = self.md.pop('filename')
if 'project' in self.md.keys():
self.project = self.md.pop('project')
else:
self.project = None
if 'dataset' in self.md.keys():
self.dataset = self.md.pop('dataset')
else:
self.dataset = None
if 'screen' in self.md.keys():
self.screen = self.md.pop('screen')
else:
self.screen = None
self.imported = False
self.image_ids = None
self.plate_ids = None
def get_image_ids(self):
"""Get the Ids of imported images.
Note that this will not find images if they have not been imported.
Also, while image_ids are returned, this method also sets
``self.image_ids``.
Returns
-------
image_ids : list of ints
Ids of images imported from the specified client path, which
itself is derived from ``self.file_path`` and ``self.filename``.
"""
if self.imported is not True:
logging.error(f'File {self.file_path} has not been imported')
return None
else:
q = self.conn.getQueryService()
params = Parameters()
path_query = str(self.file_path).strip('/')
params.map = {"cpath": rstring(path_query)}
results = q.projection(
"SELECT i.id FROM Image i"
" JOIN i.fileset fs"
" JOIN fs.usedFiles u"
" WHERE u.clientPath=:cpath",
params,
self.conn.SERVICE_OPTS
)
self.image_ids = [r[0].val for r in results]
return self.image_ids
def get_plate_ids(self):
"""Get the Ids of imported plates.
Note that this will not find plates if they have not been imported.
Also, while plate_ids are returned, this method also sets
``self.plate_ids``.
Returns
-------
plate_ids : list of ints
Ids of plates imported from the specified client path, which
itself is derived from ``self.file_path`` and ``self.filename``.
"""
if self.imported is not True:
logging.error(f'File {self.file_path} has not been imported')
return None
else:
print("time to get some IDs")
q = self.conn.getQueryService()
print(q)
params = Parameters()
path_query = str(self.file_path).strip('/')
print(f"path query: f{path_query}")
params.map = {"cpath": rstring(path_query)}
print(params)
results = q.projection(
"SELECT DISTINCT p.id FROM Plate p"
" JOIN p.plateAcquisitions pa"
" JOIN pa.wellSample ws"
" JOIN ws.image i"
" JOIN i.fileset fs"
" JOIN fs.usedFiles u"
" WHERE u.clientPath=:cpath",
params,
self.conn.SERVICE_OPTS
)
print(results)
self.plate_ids = [r[0].val for r in results]
return self.plate_ids
def annotate_images(self):
"""Post map annotation (``self.md``) to images ``self.image_ids``.
Returns
-------
map_ann_id : int
The Id of the MapAnnotation that was created.
"""
if len(self.image_ids) == 0:
logging.error('No image ids to annotate')
return None
else:
map_ann_id = multi_post_map_annotation(self.conn, "Image",
self.image_ids, self.md,
CURRENT_MD_NS)
return map_ann_id
def annotate_plates(self):
"""Post map annotation (``self.md``) to plates ``self.plate_ids``.
Returns
-------
map_ann_id : int
The Id of the MapAnnotation that was created.
"""
if len(self.plate_ids) == 0:
logging.error('No plate ids to annotate')
return None
else:
map_ann_id = multi_post_map_annotation(self.conn, "Plate",
self.plate_ids, self.md,
CURRENT_MD_NS)
return map_ann_id
def organize_images(self):
"""Move images to ``self.project``/``self.dataset``.
Returns
-------
image_moved : boolean
True if images were found and moved, else False.
"""
if not self.image_ids:
logging.error('No image ids to organize')
return False
orphans = get_image_ids(self.conn)
for im_id in self.image_ids:
if im_id not in orphans:
logging.error(f'Image:{im_id} not an orphan')
else:
project_id = set_or_create_project(self.conn, self.project)
dataset_id = set_or_create_dataset(self.conn,
project_id,
self.dataset)
link_images_to_dataset(self.conn, [im_id], dataset_id)
print(f'Moved Image:{im_id} to Dataset:{dataset_id}')
return True
def organize_plates(self):
"""Move plates to ``self.screen``.
Returns
-------
plate_moved : boolean
True if plates were found and moved, else False.
"""
if len(self.plate_ids) == 0:
logging.error('No plate ids to organize')
return False
for pl_id in self.plate_ids:
screen_id = set_or_create_screen(self.conn, self.screen)
link_plates_to_screen(self.conn, [pl_id], screen_id)
print(f'Moved Plate:{pl_id} to Screen:{screen_id}')
return True
def import_ln_s(self, host, port):
"""Import file using the ``--transfer=ln_s`` option.
Parameters
----------
host : str
Hostname of OMERO server in which images will be imported.
port : int
Port used to connect to OMERO.server.
Returns
-------
import_status : boolean
True if OMERO import returns a 0 exit status, else False.
"""
cli = CLI()
cli.register('import', ImportControl, '_')
cli.register('sessions', SessionsControl, '_')
cli.invoke(['import',
'-k', self.conn.getSession().getUuid().val,
'-s', host,
'-p', str(port),
'--transfer', 'ln_s',
str(self.file_path)])
if cli.rv == 0:
self.imported = True
print(f'Imported {self.file_path}')
return True
else:
logging.error(f'Import of {self.file_path} has failed!')
return False
| 34.121359 | 79 | 0.583155 |
import logging
from ezomero import post_dataset, post_project
from ezomero import get_image_ids, link_images_to_dataset
from ezomero import post_screen, link_plates_to_screen
from importlib import import_module
from omero.cli import CLI
from omero.plugins.sessions import SessionsControl
from omero.rtypes import rstring
from omero.sys import Parameters
from omero.gateway import MapAnnotationWrapper
from pathlib import Path
ImportControl = import_module("omero.plugins.import").ImportControl
CURRENT_MD_NS = 'jax.org/omeroutils/user_submitted/v0'
def set_or_create_project(conn, project_name):
ps = conn.getObjects('Project', attributes={'name': project_name})
ps = list(ps)
if len(ps) == 0:
project_id = post_project(conn, project_name)
print(f'Created new Project:{project_id}')
else:
project_id = ps[0].getId()
return project_id
def set_or_create_dataset(conn, project_id, dataset_name):
ds = conn.getObjects('Dataset',
attributes={'name': dataset_name},
opts={'project': project_id})
ds = list(ds)
if len(ds) == 0:
dataset_id = post_dataset(conn, dataset_name, project_id=project_id)
print(f'Created new Dataset:{dataset_id}')
else:
dataset_id = ds[0].getId()
return dataset_id
def set_or_create_screen(conn, screen_name):
ss = conn.getObjects('Screen', attributes={'name': screen_name})
ss = list(ss)
if len(ss) == 0:
screen_id = post_screen(conn, screen_name)
print(f'Created new Screen:{screen_id}')
else:
screen_id = ss[0].getId()
return screen_id
def multi_post_map_annotation(conn, object_type, object_ids, kv_dict, ns):
if type(object_ids) not in [list, int]:
raise TypeError('object_ids must be list or integer')
if type(object_ids) is not list:
object_ids = [object_ids]
if len(object_ids) == 0:
raise ValueError('object_ids must contain one or more items')
if type(kv_dict) is not dict:
raise TypeError('kv_dict must be of type `dict`')
kv_pairs = []
for k, v in kv_dict.items():
k = str(k)
v = str(v)
kv_pairs.append([k, v])
map_ann = MapAnnotationWrapper(conn)
map_ann.setNs(str(ns))
map_ann.setValue(kv_pairs)
map_ann.save()
for o in conn.getObjects(object_type, object_ids):
o.linkAnnotation(map_ann)
return map_ann.getId()
class Importer:
def __init__(self, conn, file_path, import_md):
self.conn = conn
self.file_path = Path(file_path)
self.md = import_md
self.session_uuid = conn.getSession().getUuid().val
self.filename = self.md.pop('filename')
if 'project' in self.md.keys():
self.project = self.md.pop('project')
else:
self.project = None
if 'dataset' in self.md.keys():
self.dataset = self.md.pop('dataset')
else:
self.dataset = None
if 'screen' in self.md.keys():
self.screen = self.md.pop('screen')
else:
self.screen = None
self.imported = False
self.image_ids = None
self.plate_ids = None
def get_image_ids(self):
if self.imported is not True:
logging.error(f'File {self.file_path} has not been imported')
return None
else:
q = self.conn.getQueryService()
params = Parameters()
path_query = str(self.file_path).strip('/')
params.map = {"cpath": rstring(path_query)}
results = q.projection(
"SELECT i.id FROM Image i"
" JOIN i.fileset fs"
" JOIN fs.usedFiles u"
" WHERE u.clientPath=:cpath",
params,
self.conn.SERVICE_OPTS
)
self.image_ids = [r[0].val for r in results]
return self.image_ids
def get_plate_ids(self):
if self.imported is not True:
logging.error(f'File {self.file_path} has not been imported')
return None
else:
print("time to get some IDs")
q = self.conn.getQueryService()
print(q)
params = Parameters()
path_query = str(self.file_path).strip('/')
print(f"path query: f{path_query}")
params.map = {"cpath": rstring(path_query)}
print(params)
results = q.projection(
"SELECT DISTINCT p.id FROM Plate p"
" JOIN p.plateAcquisitions pa"
" JOIN pa.wellSample ws"
" JOIN ws.image i"
" JOIN i.fileset fs"
" JOIN fs.usedFiles u"
" WHERE u.clientPath=:cpath",
params,
self.conn.SERVICE_OPTS
)
print(results)
self.plate_ids = [r[0].val for r in results]
return self.plate_ids
def annotate_images(self):
if len(self.image_ids) == 0:
logging.error('No image ids to annotate')
return None
else:
map_ann_id = multi_post_map_annotation(self.conn, "Image",
self.image_ids, self.md,
CURRENT_MD_NS)
return map_ann_id
def annotate_plates(self):
if len(self.plate_ids) == 0:
logging.error('No plate ids to annotate')
return None
else:
map_ann_id = multi_post_map_annotation(self.conn, "Plate",
self.plate_ids, self.md,
CURRENT_MD_NS)
return map_ann_id
def organize_images(self):
if not self.image_ids:
logging.error('No image ids to organize')
return False
orphans = get_image_ids(self.conn)
for im_id in self.image_ids:
if im_id not in orphans:
logging.error(f'Image:{im_id} not an orphan')
else:
project_id = set_or_create_project(self.conn, self.project)
dataset_id = set_or_create_dataset(self.conn,
project_id,
self.dataset)
link_images_to_dataset(self.conn, [im_id], dataset_id)
print(f'Moved Image:{im_id} to Dataset:{dataset_id}')
return True
def organize_plates(self):
if len(self.plate_ids) == 0:
logging.error('No plate ids to organize')
return False
for pl_id in self.plate_ids:
screen_id = set_or_create_screen(self.conn, self.screen)
link_plates_to_screen(self.conn, [pl_id], screen_id)
print(f'Moved Plate:{pl_id} to Screen:{screen_id}')
return True
def import_ln_s(self, host, port):
cli = CLI()
cli.register('import', ImportControl, '_')
cli.register('sessions', SessionsControl, '_')
cli.invoke(['import',
'-k', self.conn.getSession().getUuid().val,
'-s', host,
'-p', str(port),
'--transfer', 'ln_s',
str(self.file_path)])
if cli.rv == 0:
self.imported = True
print(f'Imported {self.file_path}')
return True
else:
logging.error(f'Import of {self.file_path} has failed!')
return False
| true | true |
f72b767f4b0695212462ecc1142bccc223f481ec | 755 | py | Python | meraki/api/content_filtering_categories.py | fsandberg/dashboard-api-python | c01ff038643a39bd12660d2719375eeb05c7ba24 | [
"MIT"
] | null | null | null | meraki/api/content_filtering_categories.py | fsandberg/dashboard-api-python | c01ff038643a39bd12660d2719375eeb05c7ba24 | [
"MIT"
] | null | null | null | meraki/api/content_filtering_categories.py | fsandberg/dashboard-api-python | c01ff038643a39bd12660d2719375eeb05c7ba24 | [
"MIT"
] | null | null | null | class ContentFilteringCategories(object):
def __init__(self, session):
super(ContentFilteringCategories, self).__init__()
self._session = session
def getNetworkContentFilteringCategories(self, networkId: str):
"""
**List all available content filtering categories for an MX network**
https://developer.cisco.com/docs/meraki-api-v0/#!get-network-content-filtering-categories
- networkId (string)
"""
metadata = {
'tags': ['Content filtering categories'],
'operation': 'getNetworkContentFilteringCategories',
}
resource = f'/networks/{networkId}/contentFiltering/categories'
return self._session.get(metadata, resource)
| 34.318182 | 97 | 0.651656 | class ContentFilteringCategories(object):
def __init__(self, session):
super(ContentFilteringCategories, self).__init__()
self._session = session
def getNetworkContentFilteringCategories(self, networkId: str):
metadata = {
'tags': ['Content filtering categories'],
'operation': 'getNetworkContentFilteringCategories',
}
resource = f'/networks/{networkId}/contentFiltering/categories'
return self._session.get(metadata, resource)
| true | true |
f72b76cf495d554aada39527fcd895707831533d | 540 | py | Python | model/group_data.py | AlexeyKozlov/python_training-master | 5e677e8be521bffac027843c5ba049695ca31492 | [
"Apache-2.0"
] | null | null | null | model/group_data.py | AlexeyKozlov/python_training-master | 5e677e8be521bffac027843c5ba049695ca31492 | [
"Apache-2.0"
] | null | null | null | model/group_data.py | AlexeyKozlov/python_training-master | 5e677e8be521bffac027843c5ba049695ca31492 | [
"Apache-2.0"
] | null | null | null |
from sys import maxsize
class Group:
def __init__(self, name=None, header=None, footer=None, id=None):
self.name = name
self.header = header
self.footer = footer
self.id = id
def __repr__(self):
return "%s:%s" % (self.id, self.name)
def __eq__(self, other):
return (self.id is None or other.id is None or self.id == other.id) and self.name == other.name
def id_or_max(self):
if self.id:
return int(self.id)
else:
return maxsize
| 21.6 | 103 | 0.574074 |
from sys import maxsize
class Group:
def __init__(self, name=None, header=None, footer=None, id=None):
self.name = name
self.header = header
self.footer = footer
self.id = id
def __repr__(self):
return "%s:%s" % (self.id, self.name)
def __eq__(self, other):
return (self.id is None or other.id is None or self.id == other.id) and self.name == other.name
def id_or_max(self):
if self.id:
return int(self.id)
else:
return maxsize
| true | true |
f72b773ac9b1776af73d49d00186f6e6bae720af | 576 | py | Python | step4.py | rezabojnordi/learning-image-processing | b0abb4005428af40dda3958561b7a78cfc6bafa6 | [
"MIT"
] | null | null | null | step4.py | rezabojnordi/learning-image-processing | b0abb4005428af40dda3958561b7a78cfc6bafa6 | [
"MIT"
] | null | null | null | step4.py | rezabojnordi/learning-image-processing | b0abb4005428af40dda3958561b7a78cfc6bafa6 | [
"MIT"
] | null | null | null | import cv2
import numpy as np
from matplotlib import pyplot as plt
cap = cv2.VideoCapture(1) # number 0 for one camera
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc,24.0,(640,480)) #params 3 = fram rate speed fram for save
# GRAY SCALE FOR ALL PIC
while(True): #video is pics
ret,fram = cap.read()
gray = cv2.cvtColor(fram,cv2.COLOR_BGR2GRAY) # cv2 =>blue - green -red
out.write(fram)
cv2.imshow('cameras',fram)
if cv2.waitKey(1) & 0XFF == ord('q'):
break
cap.release()
out.release()
cv2.destroyAllWindows() | 28.8 | 100 | 0.689236 | import cv2
import numpy as np
from matplotlib import pyplot as plt
cap = cv2.VideoCapture(1)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc,24.0,(640,480))
while(True):
ret,fram = cap.read()
gray = cv2.cvtColor(fram,cv2.COLOR_BGR2GRAY)
out.write(fram)
cv2.imshow('cameras',fram)
if cv2.waitKey(1) & 0XFF == ord('q'):
break
cap.release()
out.release()
cv2.destroyAllWindows() | true | true |
f72b7753eec3b5170014e7cf49eb5e0152bc3dab | 1,282 | py | Python | custom/new/new.py | freepoet/mmdetection | 74894c36da600014c372646c34ff4838d6968942 | [
"Apache-2.0"
] | 1 | 2021-01-21T14:20:48.000Z | 2021-01-21T14:20:48.000Z | custom/new/new.py | freepoet/mmdetection | 74894c36da600014c372646c34ff4838d6968942 | [
"Apache-2.0"
] | null | null | null | custom/new/new.py | freepoet/mmdetection | 74894c36da600014c372646c34ff4838d6968942 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
#读取mnist数据集字符图片
import torch
import torchvision
from PIL import Image
import cv2
import numpy as np
import os
import gzip
import matplotlib
import matplotlib.pyplot as pltsfas
# 定义加载数据的函数,data_folder为保存gz数据的文件夹,该文件夹下有4个文件
# 'train-labels-idx1-ubyte.gz', 'train-images-idx3-ubyte.gz',
# 't10k-labels-idx1-ubyte.gz', 't10k-images-idx3-ubyte.gz'
def load_data(data_folder):
files = [
'train-labels-idx1-ubyte.gz', 'train-images-idx3-ubyte.gz',
't10k-labels-idx1-ubyte.gz', 't10k-images-idx3-ubyte.gz'
]
paths = []
for fname in files:
paths.append(os.path.join(data_folder,fname))
with gzip.open(paths[0], 'rb') as lbpath:
y_train = np.frombuffer(lbpath.read(), np.uint8, offset=8)
with gzip.open(paths[1], 'rb') as imgpath:
x_train = np.frombuffer(
imgpath.read(), np.uint8, offset=16).reshape(len(y_train), 28, 28)
with gzip.open(paths[2], 'rb') as lbpath:
y_test = np.frombuffer(lbpath.read(), np.uint8, offset=8)
with gzip.open(paths[3], 'rb') as imgpath:
x_test = np.frombuffer(
imgpath.read(), np.uint8, offset=16).reshape(len(y_test), 28, 28)
return (x_train, y_train), (x_test, y_test)
(train_images, train_labels), (test_images, test_labels) = load_data('../../data/MNIST/raw')
| 29.136364 | 92 | 0.690328 |
import torch
import torchvision
from PIL import Image
import cv2
import numpy as np
import os
import gzip
import matplotlib
import matplotlib.pyplot as pltsfas
def load_data(data_folder):
files = [
'train-labels-idx1-ubyte.gz', 'train-images-idx3-ubyte.gz',
't10k-labels-idx1-ubyte.gz', 't10k-images-idx3-ubyte.gz'
]
paths = []
for fname in files:
paths.append(os.path.join(data_folder,fname))
with gzip.open(paths[0], 'rb') as lbpath:
y_train = np.frombuffer(lbpath.read(), np.uint8, offset=8)
with gzip.open(paths[1], 'rb') as imgpath:
x_train = np.frombuffer(
imgpath.read(), np.uint8, offset=16).reshape(len(y_train), 28, 28)
with gzip.open(paths[2], 'rb') as lbpath:
y_test = np.frombuffer(lbpath.read(), np.uint8, offset=8)
with gzip.open(paths[3], 'rb') as imgpath:
x_test = np.frombuffer(
imgpath.read(), np.uint8, offset=16).reshape(len(y_test), 28, 28)
return (x_train, y_train), (x_test, y_test)
(train_images, train_labels), (test_images, test_labels) = load_data('../../data/MNIST/raw')
| true | true |
f72b78257722b6c8736302bff4164efaba35af74 | 176 | py | Python | Day01-15/code/Day02/variable1.py | bdfd/Python_Zero2Hero_DS | 9dafe90b8112fdc3d07e1aa02e41ed3f019f733c | [
"MIT"
] | 3 | 2022-01-15T19:06:19.000Z | 2022-01-18T16:47:27.000Z | Day01-15/code/Day02/variable1.py | bdfd/4.5_Data-Science-Python-Zero2Hero- | 9dafe90b8112fdc3d07e1aa02e41ed3f019f733c | [
"MIT"
] | null | null | null | Day01-15/code/Day02/variable1.py | bdfd/4.5_Data-Science-Python-Zero2Hero- | 9dafe90b8112fdc3d07e1aa02e41ed3f019f733c | [
"MIT"
] | 1 | 2022-01-09T00:18:49.000Z | 2022-01-09T00:18:49.000Z | """
使用变量保存数据并进行操作
Version: 0.1
Author: BDFD
Date: 2018-02-27
"""
a = 321
b = 123
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b)
print(a % b)
print(a ** b)
| 9.777778 | 16 | 0.573864 |
a = 321
b = 123
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b)
print(a % b)
print(a ** b)
| true | true |
f72b7a277c123afcf6d76434f86d3383e699a8fc | 3,379 | py | Python | setup.py | rajivshah3/checkov | c6a6eca21bedae50574814c92973b65d2d963581 | [
"Apache-2.0"
] | 1 | 2021-02-16T15:07:29.000Z | 2021-02-16T15:07:29.000Z | setup.py | rajivshah3/checkov | c6a6eca21bedae50574814c92973b65d2d963581 | [
"Apache-2.0"
] | null | null | null | setup.py | rajivshah3/checkov | c6a6eca21bedae50574814c92973b65d2d963581 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
import logging
import os
from importlib import util
from os import path
import setuptools
from setuptools import setup
# read the contents of your README file
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, "README.md"), encoding="utf-8") as f:
long_description = f.read()
logger = logging.getLogger(__name__)
spec = util.spec_from_file_location(
"checkov.version", os.path.join("checkov", "version.py")
)
# noinspection PyUnresolvedReferences
mod = util.module_from_spec(spec)
spec.loader.exec_module(mod) # type: ignore
version = mod.version # type: ignore
setup(
extras_require={
"dev": [
"alabaster==0.7.12",
"attrs==19.3.0",
"babel==2.7.0",
"certifi==2019.11.28",
"chardet==3.0.4",
"coverage==4.5.4",
"coverage-badge==1.0.1",
"docopt==0.6.2",
"docutils==0.15.2",
"idna==2.8",
"imagesize==1.1.0",
"importlib-metadata==1.1.0; python_version < '3.8'",
"jinja2==2.10.3",
"lark-parser==0.7.8",
"markupsafe==1.1.1",
"more-itertools==8.0.0",
"packaging==19.2",
"pluggy==0.13.1",
"py==1.8.0",
"pygments==2.5.2",
"pyparsing==2.4.5",
"pytest==5.3.1",
"bc-python-hcl2>=0.3.10",
"pytz==2019.3",
"pyyaml==5.3.1",
"requests==2.22.0",
"six==1.15.0",
"snowballstemmer==2.0.0",
"sphinx==2.2.1",
"sphinxcontrib-applehelp==1.0.1",
"sphinxcontrib-devhelp==1.0.1",
"sphinxcontrib-htmlhelp==1.0.2",
"sphinxcontrib-jsmath==1.0.1",
"sphinxcontrib-qthelp==1.0.2",
"sphinxcontrib-serializinghtml==1.1.3",
"urllib3==1.25.10",
"wcwidth==0.1.7",
"zipp==0.6.0",
"GitPython==3.1.7",
"gitdb==4.0.5"
]
},
install_requires=[
"update-checker==0.18.0",
"tqdm==4.49.0",
"boto3==1.12.43",
"chardet==3.0.4",
"colorama==0.4.3",
"docopt==0.6.2",
"idna==2.8",
"jmespath==0.10.0",
"junit-xml==1.8",
"lark-parser==0.7.8",
"bc-python-hcl2>=0.3.11",
"pyyaml==5.3.1",
"requests==2.22.0",
"six==1.15.0",
"tabulate==0.8.6",
"termcolor==1.1.0",
"urllib3==1.25.10",
"dpath==1.5.0",
"GitPython==3.1.7",
"gitdb==4.0.5"
],
license="Apache License 2.0",
name="checkov",
version=version,
description="Infrastructure as code static analysis",
author="bridgecrew",
author_email="meet@bridgecrew.io",
url="https://github.com/bridgecrewio/checkov",
packages=setuptools.find_packages(exclude=["tests*","integration_tests*"]),
scripts=["bin/checkov","bin/checkov.cmd"],
long_description=long_description,
long_description_content_type="text/markdown",
classifiers=[
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Programming Language :: Python :: 3.7',
'Topic :: Security',
'Topic :: Software Development :: Build Tools'
]
)
| 30.441441 | 79 | 0.527671 |
import logging
import os
from importlib import util
from os import path
import setuptools
from setuptools import setup
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, "README.md"), encoding="utf-8") as f:
long_description = f.read()
logger = logging.getLogger(__name__)
spec = util.spec_from_file_location(
"checkov.version", os.path.join("checkov", "version.py")
)
mod = util.module_from_spec(spec)
spec.loader.exec_module(mod)
version = mod.version
setup(
extras_require={
"dev": [
"alabaster==0.7.12",
"attrs==19.3.0",
"babel==2.7.0",
"certifi==2019.11.28",
"chardet==3.0.4",
"coverage==4.5.4",
"coverage-badge==1.0.1",
"docopt==0.6.2",
"docutils==0.15.2",
"idna==2.8",
"imagesize==1.1.0",
"importlib-metadata==1.1.0; python_version < '3.8'",
"jinja2==2.10.3",
"lark-parser==0.7.8",
"markupsafe==1.1.1",
"more-itertools==8.0.0",
"packaging==19.2",
"pluggy==0.13.1",
"py==1.8.0",
"pygments==2.5.2",
"pyparsing==2.4.5",
"pytest==5.3.1",
"bc-python-hcl2>=0.3.10",
"pytz==2019.3",
"pyyaml==5.3.1",
"requests==2.22.0",
"six==1.15.0",
"snowballstemmer==2.0.0",
"sphinx==2.2.1",
"sphinxcontrib-applehelp==1.0.1",
"sphinxcontrib-devhelp==1.0.1",
"sphinxcontrib-htmlhelp==1.0.2",
"sphinxcontrib-jsmath==1.0.1",
"sphinxcontrib-qthelp==1.0.2",
"sphinxcontrib-serializinghtml==1.1.3",
"urllib3==1.25.10",
"wcwidth==0.1.7",
"zipp==0.6.0",
"GitPython==3.1.7",
"gitdb==4.0.5"
]
},
install_requires=[
"update-checker==0.18.0",
"tqdm==4.49.0",
"boto3==1.12.43",
"chardet==3.0.4",
"colorama==0.4.3",
"docopt==0.6.2",
"idna==2.8",
"jmespath==0.10.0",
"junit-xml==1.8",
"lark-parser==0.7.8",
"bc-python-hcl2>=0.3.11",
"pyyaml==5.3.1",
"requests==2.22.0",
"six==1.15.0",
"tabulate==0.8.6",
"termcolor==1.1.0",
"urllib3==1.25.10",
"dpath==1.5.0",
"GitPython==3.1.7",
"gitdb==4.0.5"
],
license="Apache License 2.0",
name="checkov",
version=version,
description="Infrastructure as code static analysis",
author="bridgecrew",
author_email="meet@bridgecrew.io",
url="https://github.com/bridgecrewio/checkov",
packages=setuptools.find_packages(exclude=["tests*","integration_tests*"]),
scripts=["bin/checkov","bin/checkov.cmd"],
long_description=long_description,
long_description_content_type="text/markdown",
classifiers=[
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Programming Language :: Python :: 3.7',
'Topic :: Security',
'Topic :: Software Development :: Build Tools'
]
)
| true | true |
f72b7a44c047b0c5eed99383fa2b7f7c2da824b8 | 3,974 | py | Python | geeksurvey/views.py | NAU-SuperGeeks/geeksurvey | ee2fd0d2869f3b8b5c058d8a39c64c2d0b0c2a26 | [
"MIT"
] | 3 | 2022-01-01T23:00:45.000Z | 2022-02-26T23:35:46.000Z | geeksurvey/views.py | NAU-SuperGeeks/geeksurvey | ee2fd0d2869f3b8b5c058d8a39c64c2d0b0c2a26 | [
"MIT"
] | 5 | 2022-02-12T17:52:52.000Z | 2022-03-02T16:08:08.000Z | geeksurvey/views.py | NAU-SuperGeeks/geeksurvey | ee2fd0d2869f3b8b5c058d8a39c64c2d0b0c2a26 | [
"MIT"
] | 4 | 2022-01-12T18:47:20.000Z | 2022-01-12T19:11:59.000Z | from django.core.mail import send_mail
from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.contrib import messages
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import logout, authenticate, login
from django.contrib.auth.decorators import login_required
from decouple import config
from geeksurvey.settings import *
import json
from .models import Study, Profile
from .forms import *
def index(request):
if request.user.is_authenticated:
profile = Profile.objects.get(user=request.user)
context = {
'profile': profile,
}
else:
context = {}
return render(request, 'home.html', context)
def working(request):
return render(request, 'working.html')
def help(request):
return render(request, 'help.html')
@login_required
def participate(request):
all_studies = Study.objects.all()
enrolled_studies = []
completed_studies = []
for study in all_studies:
if request.user in study.completed.all():
completed_studies.append(study)
elif request.user in study.enrolled.all():
enrolled_studies.append(study)
profile = Profile.objects.get(user=request.user)
context = {
'enrolled_studies':enrolled_studies,
'completed_studies':completed_studies,
'profile': profile,
}
return render(request, 'participate/index.html', context)
@login_required
def part_discover(request):
user_profile = Profile.objects.get(user=request.user)
all_studies = Study.objects.all()
eligible_studies = []
for study in all_studies:
if user_profile.can_enroll(study):
eligible_studies.append(study)
context = {
'studies': eligible_studies,
'profile': user_profile,
}
return render(request, 'participate/discover.html', context)
@login_required
def profile(request):
profile = Profile.objects.get(user=request.user)
context={'profile':profile}
return render(request, 'profile/index.html', context)
# public profile view, accesible by url
def profile_view(request, username):
user = get_object_or_404(User, username=username)
profile = Profile.objects.get(user=user)
context = {
'user':user,
'profile':profile,
}
return render(request, 'profile/view.html', context)
@login_required
def profile_update(request):
profile = Profile.objects.get(user=request.user)
if request.method == 'POST':
u_form = UserUpdateForm(request.POST, instance=request.user)
p_form = ProfileUpdateForm(request.POST,
request.FILES,
instance=request.user.profile)
if u_form.is_valid() and p_form.is_valid():
u_form.save()
new_profile = p_form.save(commit=False)
new_profile.updated_once = True
new_profile.save()
messages.success(request, f'Your account has been updated!')
return redirect('profile') # Redirect back to profile page
else:
u_form = UserUpdateForm(instance=request.user)
p_form = ProfileUpdateForm(instance=request.user.profile)
p_form['open_source_experience'].label = "Experienced With Open Source Development?"
p_form['email_opt_in'].label = "Opt In For Email Notifications?"
context = {
'profile': profile,
'u_form': u_form,
'p_form': p_form
}
return render(request, 'profile/update.html', context)
@login_required
def research(request):
profile = Profile.objects.get(user=request.user)
# show existing studies created by the user
studies = Study.objects.filter(owner=request.user)
context = {
'profile':profile,
'studies':studies
}
return render(request, 'research/index.html', context)
| 29.879699 | 92 | 0.67539 | from django.core.mail import send_mail
from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.contrib import messages
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import logout, authenticate, login
from django.contrib.auth.decorators import login_required
from decouple import config
from geeksurvey.settings import *
import json
from .models import Study, Profile
from .forms import *
def index(request):
if request.user.is_authenticated:
profile = Profile.objects.get(user=request.user)
context = {
'profile': profile,
}
else:
context = {}
return render(request, 'home.html', context)
def working(request):
return render(request, 'working.html')
def help(request):
return render(request, 'help.html')
@login_required
def participate(request):
all_studies = Study.objects.all()
enrolled_studies = []
completed_studies = []
for study in all_studies:
if request.user in study.completed.all():
completed_studies.append(study)
elif request.user in study.enrolled.all():
enrolled_studies.append(study)
profile = Profile.objects.get(user=request.user)
context = {
'enrolled_studies':enrolled_studies,
'completed_studies':completed_studies,
'profile': profile,
}
return render(request, 'participate/index.html', context)
@login_required
def part_discover(request):
user_profile = Profile.objects.get(user=request.user)
all_studies = Study.objects.all()
eligible_studies = []
for study in all_studies:
if user_profile.can_enroll(study):
eligible_studies.append(study)
context = {
'studies': eligible_studies,
'profile': user_profile,
}
return render(request, 'participate/discover.html', context)
@login_required
def profile(request):
profile = Profile.objects.get(user=request.user)
context={'profile':profile}
return render(request, 'profile/index.html', context)
def profile_view(request, username):
user = get_object_or_404(User, username=username)
profile = Profile.objects.get(user=user)
context = {
'user':user,
'profile':profile,
}
return render(request, 'profile/view.html', context)
@login_required
def profile_update(request):
profile = Profile.objects.get(user=request.user)
if request.method == 'POST':
u_form = UserUpdateForm(request.POST, instance=request.user)
p_form = ProfileUpdateForm(request.POST,
request.FILES,
instance=request.user.profile)
if u_form.is_valid() and p_form.is_valid():
u_form.save()
new_profile = p_form.save(commit=False)
new_profile.updated_once = True
new_profile.save()
messages.success(request, f'Your account has been updated!')
return redirect('profile')
else:
u_form = UserUpdateForm(instance=request.user)
p_form = ProfileUpdateForm(instance=request.user.profile)
p_form['open_source_experience'].label = "Experienced With Open Source Development?"
p_form['email_opt_in'].label = "Opt In For Email Notifications?"
context = {
'profile': profile,
'u_form': u_form,
'p_form': p_form
}
return render(request, 'profile/update.html', context)
@login_required
def research(request):
profile = Profile.objects.get(user=request.user)
studies = Study.objects.filter(owner=request.user)
context = {
'profile':profile,
'studies':studies
}
return render(request, 'research/index.html', context)
| true | true |
f72b7a4a8f6c0949e5829db8520e9af17ce1d0a0 | 463 | py | Python | docs/newplatform.py | PlayerG9/PyMessageBox | 21b113c5e1a322e8412a412df071cc392b40d7c5 | [
"MIT"
] | 2 | 2021-06-28T12:35:08.000Z | 2022-03-11T16:48:01.000Z | docs/newplatform.py | PlayerG9/PyMessageBox | 21b113c5e1a322e8412a412df071cc392b40d7c5 | [
"MIT"
] | null | null | null | docs/newplatform.py | PlayerG9/PyMessageBox | 21b113c5e1a322e8412a412df071cc392b40d7c5 | [
"MIT"
] | null | null | null | # -*- coding=utf-8 -*-
r"""
"""
def showinfo(title: str, message: str):
pass
def showwarning(title: str, message: str):
pass
def showerror(title: str, message: str):
pass
def askquestion(title: str, message: str):
pass
def askokcancel(title: str, message: str):
pass
def askyesno(title: str, message: str):
pass
def askyesnocancel(title: str, message: str):
pass
def askretrycancel(title: str, message: str):
pass
| 12.513514 | 45 | 0.641469 |
def showinfo(title: str, message: str):
pass
def showwarning(title: str, message: str):
pass
def showerror(title: str, message: str):
pass
def askquestion(title: str, message: str):
pass
def askokcancel(title: str, message: str):
pass
def askyesno(title: str, message: str):
pass
def askyesnocancel(title: str, message: str):
pass
def askretrycancel(title: str, message: str):
pass
| true | true |
f72b7a657af7cedbaad0f606f0d079a66c7b1ee8 | 314 | py | Python | home/models.py | nikhilchaudhary0126/neva | f86b6d2dfa047360f6e07a621b985faa2120d009 | [
"MIT"
] | null | null | null | home/models.py | nikhilchaudhary0126/neva | f86b6d2dfa047360f6e07a621b985faa2120d009 | [
"MIT"
] | null | null | null | home/models.py | nikhilchaudhary0126/neva | f86b6d2dfa047360f6e07a621b985faa2120d009 | [
"MIT"
] | null | null | null | from django.db import models
class Location(models.Model):
address = models.CharField(max_length=30)
addresstype = models.CharField(max_length=20)
city = models.CharField(max_length=30)
state = models.CharField(max_length=30)
latitude = models.FloatField()
longitude = models.FloatField() | 31.4 | 49 | 0.738854 | from django.db import models
class Location(models.Model):
address = models.CharField(max_length=30)
addresstype = models.CharField(max_length=20)
city = models.CharField(max_length=30)
state = models.CharField(max_length=30)
latitude = models.FloatField()
longitude = models.FloatField() | true | true |
f72b7ac60389bda7cc60bcc36a3a0881db868e79 | 170 | py | Python | tests/model_control/detailed/transf_Quantization/model_control_one_enabled_Quantization_MovingAverage_Seasonal_DayOfMonth_LSTM.py | shaido987/pyaf | b9afd089557bed6b90b246d3712c481ae26a1957 | [
"BSD-3-Clause"
] | 377 | 2016-10-13T20:52:44.000Z | 2022-03-29T18:04:14.000Z | tests/model_control/detailed/transf_Quantization/model_control_one_enabled_Quantization_MovingAverage_Seasonal_DayOfMonth_LSTM.py | ysdede/pyaf | b5541b8249d5a1cfdc01f27fdfd99b6580ed680b | [
"BSD-3-Clause"
] | 160 | 2016-10-13T16:11:53.000Z | 2022-03-28T04:21:34.000Z | tests/model_control/detailed/transf_Quantization/model_control_one_enabled_Quantization_MovingAverage_Seasonal_DayOfMonth_LSTM.py | ysdede/pyaf | b5541b8249d5a1cfdc01f27fdfd99b6580ed680b | [
"BSD-3-Clause"
] | 63 | 2017-03-09T14:51:18.000Z | 2022-03-27T20:52:57.000Z | import tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['Quantization'] , ['MovingAverage'] , ['Seasonal_DayOfMonth'] , ['LSTM'] ); | 42.5 | 97 | 0.770588 | import tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['Quantization'] , ['MovingAverage'] , ['Seasonal_DayOfMonth'] , ['LSTM'] ); | true | true |
f72b7c7528116153eec48525b0ed3411067b3ddc | 4,627 | py | Python | doc/pvtol-nested.py | stelselim/python-control | d73b635d2b130af5c2829eefd59c99b9bd53fb01 | [
"BSD-3-Clause"
] | 1,112 | 2015-01-14T08:01:33.000Z | 2022-03-31T11:54:00.000Z | doc/pvtol-nested.py | stelselim/python-control | d73b635d2b130af5c2829eefd59c99b9bd53fb01 | [
"BSD-3-Clause"
] | 646 | 2015-02-02T15:35:23.000Z | 2022-03-30T08:19:26.000Z | doc/pvtol-nested.py | stelselim/python-control | d73b635d2b130af5c2829eefd59c99b9bd53fb01 | [
"BSD-3-Clause"
] | 366 | 2015-01-28T17:58:06.000Z | 2022-03-29T11:04:10.000Z | # pvtol-nested.py - inner/outer design for vectored thrust aircraft
# RMM, 5 Sep 09
#
# This file works through a fairly complicated control design and
# analysis, corresponding to the planar vertical takeoff and landing
# (PVTOL) aircraft in Astrom and Murray, Chapter 11. It is intended
# to demonstrate the basic functionality of the python-control
# package.
#
from __future__ import print_function
import os
import matplotlib.pyplot as plt # MATLAB plotting functions
from control.matlab import * # MATLAB-like functions
import numpy as np
# System parameters
m = 4 # mass of aircraft
J = 0.0475 # inertia around pitch axis
r = 0.25 # distance to center of force
g = 9.8 # gravitational constant
c = 0.05 # damping factor (estimated)
# Transfer functions for dynamics
Pi = tf([r], [J, 0, 0]) # inner loop (roll)
Po = tf([1], [m, c, 0]) # outer loop (position)
#
# Inner loop control design
#
# This is the controller for the pitch dynamics. Goal is to have
# fast response for the pitch dynamics so that we can use this as a
# control for the lateral dynamics
#
# Design a simple lead controller for the system
k, a, b = 200, 2, 50
Ci = k*tf([1, a], [1, b]) # lead compensator
Li = Pi*Ci
# Bode plot for the open loop process
plt.figure(1)
bode(Pi)
# Bode plot for the loop transfer function, with margins
plt.figure(2)
bode(Li)
# Compute out the gain and phase margins
#! Not implemented
# gm, pm, wcg, wcp = margin(Li)
# Compute the sensitivity and complementary sensitivity functions
Si = feedback(1, Li)
Ti = Li*Si
# Check to make sure that the specification is met
plt.figure(3)
gangof4(Pi, Ci)
# Compute out the actual transfer function from u1 to v1 (see L8.2 notes)
# Hi = Ci*(1-m*g*Pi)/(1+Ci*Pi)
Hi = parallel(feedback(Ci, Pi), -m*g*feedback(Ci*Pi, 1))
plt.figure(4)
plt.clf()
plt.subplot(221)
bode(Hi)
# Now design the lateral control system
a, b, K = 0.02, 5, 2
Co = -K*tf([1, 0.3], [1, 10]) # another lead compensator
Lo = -m*g*Po*Co
plt.figure(5)
bode(Lo) # margin(Lo)
# Finally compute the real outer-loop loop gain + responses
L = Co*Hi*Po
S = feedback(1, L)
T = feedback(L, 1)
# Compute stability margins
gm, pm, wgc, wpc = margin(L)
print("Gain margin: %g at %g" % (gm, wgc))
print("Phase margin: %g at %g" % (pm, wpc))
plt.figure(6)
plt.clf()
bode(L, np.logspace(-4, 3))
# Add crossover line to the magnitude plot
#
# Note: in matplotlib before v2.1, the following code worked:
#
# plt.subplot(211); hold(True);
# loglog([1e-4, 1e3], [1, 1], 'k-')
#
# In later versions of matplotlib the call to plt.subplot will clear the
# axes and so we have to extract the axes that we want to use by hand.
# In addition, hold() is deprecated so we no longer require it.
#
for ax in plt.gcf().axes:
if ax.get_label() == 'control-bode-magnitude':
break
ax.semilogx([1e-4, 1e3], 20*np.log10([1, 1]), 'k-')
#
# Replot phase starting at -90 degrees
#
# Get the phase plot axes
for ax in plt.gcf().axes:
if ax.get_label() == 'control-bode-phase':
break
# Recreate the frequency response and shift the phase
mag, phase, w = freqresp(L, np.logspace(-4, 3))
phase = phase - 360
# Replot the phase by hand
ax.semilogx([1e-4, 1e3], [-180, -180], 'k-')
ax.semilogx(w, np.squeeze(phase), 'b-')
ax.axis([1e-4, 1e3, -360, 0])
plt.xlabel('Frequency [deg]')
plt.ylabel('Phase [deg]')
# plt.set(gca, 'YTick', [-360, -270, -180, -90, 0])
# plt.set(gca, 'XTick', [10^-4, 10^-2, 1, 100])
#
# Nyquist plot for complete design
#
plt.figure(7)
plt.clf()
nyquist(L, (0.0001, 1000))
plt.axis([-700, 5300, -3000, 3000])
# Add a box in the region we are going to expand
plt.plot([-400, -400, 200, 200, -400], [-100, 100, 100, -100, -100], 'r-')
# Expanded region
plt.figure(8)
plt.clf()
plt.subplot(231)
nyquist(L)
plt.axis([-10, 5, -20, 20])
# set up the color
color = 'b'
# Add arrows to the plot
# H1 = L.evalfr(0.4); H2 = L.evalfr(0.41);
# arrow([real(H1), imag(H1)], [real(H2), imag(H2)], AM_normal_arrowsize, \
# 'EdgeColor', color, 'FaceColor', color);
# H1 = freqresp(L, 0.35); H2 = freqresp(L, 0.36);
# arrow([real(H2), -imag(H2)], [real(H1), -imag(H1)], AM_normal_arrowsize, \
# 'EdgeColor', color, 'FaceColor', color);
plt.figure(9)
Yvec, Tvec = step(T, np.linspace(0, 20))
plt.plot(Tvec.T, Yvec.T)
Yvec, Tvec = step(Co*S, np.linspace(0, 20))
plt.plot(Tvec.T, Yvec.T)
plt.figure(10)
plt.clf()
P, Z = pzmap(T, plot=True, grid=True)
print("Closed loop poles and zeros: ", P, Z)
# Gang of Four
plt.figure(11)
plt.clf()
gangof4(Hi*Po, Co)
if 'PYCONTROL_TEST_EXAMPLES' not in os.environ:
plt.show()
| 25.849162 | 76 | 0.661336 |
from __future__ import print_function
import os
import matplotlib.pyplot as plt
from control.matlab import *
import numpy as np
m = 4
J = 0.0475
r = 0.25
g = 9.8
c = 0.05
Pi = tf([r], [J, 0, 0])
Po = tf([1], [m, c, 0])
k, a, b = 200, 2, 50
Ci = k*tf([1, a], [1, b])
Li = Pi*Ci
plt.figure(1)
bode(Pi)
plt.figure(2)
bode(Li)
Si = feedback(1, Li)
Ti = Li*Si
plt.figure(3)
gangof4(Pi, Ci)
Hi = parallel(feedback(Ci, Pi), -m*g*feedback(Ci*Pi, 1))
plt.figure(4)
plt.clf()
plt.subplot(221)
bode(Hi)
a, b, K = 0.02, 5, 2
Co = -K*tf([1, 0.3], [1, 10])
Lo = -m*g*Po*Co
plt.figure(5)
bode(Lo)
L = Co*Hi*Po
S = feedback(1, L)
T = feedback(L, 1)
gm, pm, wgc, wpc = margin(L)
print("Gain margin: %g at %g" % (gm, wgc))
print("Phase margin: %g at %g" % (pm, wpc))
plt.figure(6)
plt.clf()
bode(L, np.logspace(-4, 3))
for ax in plt.gcf().axes:
if ax.get_label() == 'control-bode-magnitude':
break
ax.semilogx([1e-4, 1e3], 20*np.log10([1, 1]), 'k-')
for ax in plt.gcf().axes:
if ax.get_label() == 'control-bode-phase':
break
mag, phase, w = freqresp(L, np.logspace(-4, 3))
phase = phase - 360
ax.semilogx([1e-4, 1e3], [-180, -180], 'k-')
ax.semilogx(w, np.squeeze(phase), 'b-')
ax.axis([1e-4, 1e3, -360, 0])
plt.xlabel('Frequency [deg]')
plt.ylabel('Phase [deg]')
plt.figure(7)
plt.clf()
nyquist(L, (0.0001, 1000))
plt.axis([-700, 5300, -3000, 3000])
plt.plot([-400, -400, 200, 200, -400], [-100, 100, 100, -100, -100], 'r-')
plt.figure(8)
plt.clf()
plt.subplot(231)
nyquist(L)
plt.axis([-10, 5, -20, 20])
color = 'b'
plt.figure(9)
Yvec, Tvec = step(T, np.linspace(0, 20))
plt.plot(Tvec.T, Yvec.T)
Yvec, Tvec = step(Co*S, np.linspace(0, 20))
plt.plot(Tvec.T, Yvec.T)
plt.figure(10)
plt.clf()
P, Z = pzmap(T, plot=True, grid=True)
print("Closed loop poles and zeros: ", P, Z)
plt.figure(11)
plt.clf()
gangof4(Hi*Po, Co)
if 'PYCONTROL_TEST_EXAMPLES' not in os.environ:
plt.show()
| true | true |
f72b7e5c1c47e2d9063b237e29c8de4e5ecad2aa | 4,093 | py | Python | utils/vocab_reader.py | aaj-fullfact/slot_filling_and_intent_detection_of_SLU | 27adf381b9b087caa1e90bfafb88765e5e296192 | [
"Apache-2.0"
] | 361 | 2019-06-17T08:37:49.000Z | 2022-03-29T20:46:15.000Z | utils/vocab_reader.py | aaj-fullfact/slot_filling_and_intent_detection_of_SLU | 27adf381b9b087caa1e90bfafb88765e5e296192 | [
"Apache-2.0"
] | 9 | 2019-07-03T06:38:36.000Z | 2021-12-09T12:08:56.000Z | utils/vocab_reader.py | aaj-fullfact/slot_filling_and_intent_detection_of_SLU | 27adf381b9b087caa1e90bfafb88765e5e296192 | [
"Apache-2.0"
] | 100 | 2019-06-17T03:04:36.000Z | 2022-03-21T21:07:30.000Z | """Data utilities."""
#import torch
import operator
#import json
def read_vocab_file(vocab_path, bos_eos=False, no_pad=False, no_unk=False, separator=':'):
'''file format: "word : idx" '''
word2id, id2word = {}, {}
if not no_pad:
word2id['<pad>'] = len(word2id)
id2word[len(id2word)] = '<pad>'
if not no_unk:
word2id['<unk>'] = len(word2id)
id2word[len(id2word)] = '<unk>'
if bos_eos == True:
word2id['<s>'] = len(word2id)
id2word[len(id2word)] = '<s>'
word2id['</s>'] = len(word2id)
id2word[len(id2word)] = '</s>'
with open(vocab_path, 'r') as f:
for line in f:
if separator in line:
word, idx = line.strip('\r\n').split(' '+separator+' ')
idx = int(idx)
else:
word = line.strip()
idx = len(word2id)
if word not in word2id:
word2id[word] = idx
id2word[idx] = word
return word2id, id2word
def save_vocab(idx2word, vocab_path, separator=':'):
with open(vocab_path, 'w') as f:
for idx in range(len(idx2word)):
f.write(idx2word[idx]+' '+separator+' '+str(idx)+'\n')
def construct_vocab(input_seqs, vocab_config={'mini_word_freq':1, 'bos_eos':False}):
'''
@params:
1. input_seqs: a list of seqs.
2. vocab_config:
mini_word_freq: minimum word frequency
bos_eos: <s> </s>
@return:
1. word2idx
2. idx2word
'''
vocab = {}
for seq in input_seqs:
if type(seq) == type([]):
for word in seq:
if word not in vocab:
vocab[word] = 1
else:
vocab[word] += 1
else:
assert type(seq) == str
if seq not in vocab:
vocab[seq] = 1
else:
vocab[seq] += 1
# Discard start, end, pad and unk tokens if already present
if '<s>' in vocab:
del vocab['<s>']
if '<pad>' in vocab:
del vocab['<pad>']
if '</s>' in vocab:
del vocab['</s>']
if '<unk>' in vocab:
del vocab['<unk>']
if vocab_config['bos_eos'] == True:
word2id = {'<pad>': 0, '<unk>': 1, '<s>': 2, '</s>': 3}
id2word = {0: '<pad>', 1: '<unk>', 2: '<s>', 3: '</s>'}
else:
word2id = {'<pad>': 0, '<unk>': 1,}
id2word = {0: '<pad>', 1: '<unk>',}
sorted_word2id = sorted(
vocab.items(),
key=operator.itemgetter(1),
reverse=True
)
sorted_words = [x[0] for x in sorted_word2id if x[1] >= vocab_config['mini_word_freq']]
for word in sorted_words:
idx = len(word2id)
word2id[word] = idx
id2word[idx] = word
return word2id, id2word
def read_vocab_from_data_file(data_path, vocab_config={'mini_word_freq':1, 'bos_eos':False, 'lowercase':False}, with_tag=True, separator=':'):
'''
Read data from files.
@params:
1. data_path: file path of data
2. vocab_config: config of how to build vocab. It is used when in_vocab == None.
@return:
1. input vocab
'''
print('Reading source data ...')
input_seqs = []
with open(data_path, 'r') as f:
for ind, line in enumerate(f):
slot_tag_line = line.strip('\n\r').split(' <=> ')[0]
if slot_tag_line == "":
continue
in_seq = []
for item in slot_tag_line.split(' '):
if with_tag:
tmp = item.split(separator)
assert len(tmp) >= 2
word, tag = separator.join(tmp[:-1]), tmp[-1]
else:
word = item
if vocab_config['lowercase']:
word = word.lower()
in_seq.append(word)
input_seqs.append(in_seq)
print('Constructing input vocabulary from ', data_path, ' ...')
word2idx, idx2word = construct_vocab(input_seqs, vocab_config)
return (word2idx, idx2word)
| 31.976563 | 142 | 0.50623 |
import operator
def read_vocab_file(vocab_path, bos_eos=False, no_pad=False, no_unk=False, separator=':'):
word2id, id2word = {}, {}
if not no_pad:
word2id['<pad>'] = len(word2id)
id2word[len(id2word)] = '<pad>'
if not no_unk:
word2id['<unk>'] = len(word2id)
id2word[len(id2word)] = '<unk>'
if bos_eos == True:
word2id['<s>'] = len(word2id)
id2word[len(id2word)] = '<s>'
word2id['</s>'] = len(word2id)
id2word[len(id2word)] = '</s>'
with open(vocab_path, 'r') as f:
for line in f:
if separator in line:
word, idx = line.strip('\r\n').split(' '+separator+' ')
idx = int(idx)
else:
word = line.strip()
idx = len(word2id)
if word not in word2id:
word2id[word] = idx
id2word[idx] = word
return word2id, id2word
def save_vocab(idx2word, vocab_path, separator=':'):
with open(vocab_path, 'w') as f:
for idx in range(len(idx2word)):
f.write(idx2word[idx]+' '+separator+' '+str(idx)+'\n')
def construct_vocab(input_seqs, vocab_config={'mini_word_freq':1, 'bos_eos':False}):
vocab = {}
for seq in input_seqs:
if type(seq) == type([]):
for word in seq:
if word not in vocab:
vocab[word] = 1
else:
vocab[word] += 1
else:
assert type(seq) == str
if seq not in vocab:
vocab[seq] = 1
else:
vocab[seq] += 1
if '<s>' in vocab:
del vocab['<s>']
if '<pad>' in vocab:
del vocab['<pad>']
if '</s>' in vocab:
del vocab['</s>']
if '<unk>' in vocab:
del vocab['<unk>']
if vocab_config['bos_eos'] == True:
word2id = {'<pad>': 0, '<unk>': 1, '<s>': 2, '</s>': 3}
id2word = {0: '<pad>', 1: '<unk>', 2: '<s>', 3: '</s>'}
else:
word2id = {'<pad>': 0, '<unk>': 1,}
id2word = {0: '<pad>', 1: '<unk>',}
sorted_word2id = sorted(
vocab.items(),
key=operator.itemgetter(1),
reverse=True
)
sorted_words = [x[0] for x in sorted_word2id if x[1] >= vocab_config['mini_word_freq']]
for word in sorted_words:
idx = len(word2id)
word2id[word] = idx
id2word[idx] = word
return word2id, id2word
def read_vocab_from_data_file(data_path, vocab_config={'mini_word_freq':1, 'bos_eos':False, 'lowercase':False}, with_tag=True, separator=':'):
print('Reading source data ...')
input_seqs = []
with open(data_path, 'r') as f:
for ind, line in enumerate(f):
slot_tag_line = line.strip('\n\r').split(' <=> ')[0]
if slot_tag_line == "":
continue
in_seq = []
for item in slot_tag_line.split(' '):
if with_tag:
tmp = item.split(separator)
assert len(tmp) >= 2
word, tag = separator.join(tmp[:-1]), tmp[-1]
else:
word = item
if vocab_config['lowercase']:
word = word.lower()
in_seq.append(word)
input_seqs.append(in_seq)
print('Constructing input vocabulary from ', data_path, ' ...')
word2idx, idx2word = construct_vocab(input_seqs, vocab_config)
return (word2idx, idx2word)
| true | true |
f72b7f156678de318e745bd933773f338fc00cc7 | 15,626 | py | Python | tests/jet_test.py | machineko/jax | 5a9048a0058d027000afc5707413d24209aa6f9f | [
"Apache-2.0"
] | 7 | 2020-12-04T16:54:54.000Z | 2022-02-15T07:26:56.000Z | tests/jet_test.py | josephrocca/jax | ab544cb26dfea3147c336754d3e3eb457a405e38 | [
"Apache-2.0"
] | 20 | 2021-08-17T20:31:56.000Z | 2022-03-31T11:56:24.000Z | tests/jet_test.py | kbnarayanavit/jax | 1e3c4833c97302caf6046ff99656b8ff21430b8d | [
"Apache-2.0"
] | 1 | 2021-08-11T20:57:59.000Z | 2021-08-11T20:57:59.000Z | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from functools import reduce, partial
from absl.testing import absltest
import numpy as np
import unittest
import jax
from jax import test_util as jtu
import jax.numpy as jnp
import jax.scipy.special
from jax import random
from jax import jacfwd, jit
from jax.experimental import stax
from jax.experimental.jet import jet, fact, zero_series
from jax import lax
from jax.config import config
config.parse_flags_with_absl()
def jvp_taylor(fun, primals, series):
# Computes the Taylor series the slow way, with nested jvp.
order, = set(map(len, series))
primals = tuple(jnp.asarray(p) for p in primals)
def composition(eps):
taylor_terms = [sum([eps ** (i+1) * terms[i] / fact(i + 1)
for i in range(len(terms))]) for terms in series]
nudged_args = [(x + t).astype(x.dtype) for x, t in zip(primals, taylor_terms)]
return fun(*nudged_args)
primal_out = fun(*primals)
terms_out = [repeated(jacfwd, i+1)(composition)(0.) for i in range(order)]
return primal_out, terms_out
def repeated(f, n):
def rfun(p):
return reduce(lambda x, _: f(x), range(n), p)
return rfun
def transform(lims, x):
return x * (lims[1] - lims[0]) + lims[0]
class JetTest(jtu.JaxTestCase):
def check_jet(self, fun, primals, series, atol=1e-5, rtol=1e-5,
check_dtypes=True):
y, terms = jet(fun, primals, series)
expected_y, expected_terms = jvp_taylor(fun, primals, series)
self.assertAllClose(y, expected_y, atol=atol, rtol=rtol,
check_dtypes=check_dtypes)
self.assertAllClose(terms, expected_terms, atol=atol, rtol=rtol,
check_dtypes=check_dtypes)
def check_jet_finite(self, fun, primals, series, atol=1e-5, rtol=1e-5,
check_dtypes=True):
y, terms = jet(fun, primals, series)
expected_y, expected_terms = jvp_taylor(fun, primals, series)
def _convert(x):
return jnp.where(jnp.isfinite(x), x, jnp.nan)
y = _convert(y)
expected_y = _convert(expected_y)
terms = _convert(jnp.asarray(terms))
expected_terms = _convert(jnp.asarray(expected_terms))
self.assertAllClose(y, expected_y, atol=atol, rtol=rtol,
check_dtypes=check_dtypes)
self.assertAllClose(terms, expected_terms, atol=atol, rtol=rtol,
check_dtypes=check_dtypes)
@jtu.skip_on_devices("tpu")
def test_dot(self):
M, K, N = 2, 3, 4
order = 3
rng = np.random.RandomState(0)
x1 = rng.randn(M, K)
x2 = rng.randn(K, N)
primals = (x1, x2)
terms_in1 = [rng.randn(*x1.shape) for _ in range(order)]
terms_in2 = [rng.randn(*x2.shape) for _ in range(order)]
series_in = (terms_in1, terms_in2)
self.check_jet(jnp.dot, primals, series_in)
@jtu.skip_on_devices("tpu")
def test_conv(self):
order = 3
input_shape = (1, 5, 5, 1)
key = random.PRNGKey(0)
# TODO(duvenaud): Check all types of padding
init_fun, apply_fun = stax.Conv(3, (2, 2), padding='VALID')
_, (W, b) = init_fun(key, input_shape)
rng = np.random.RandomState(0)
x = rng.randn(*input_shape)
primals = (W, b, x)
series_in1 = [rng.randn(*W.shape) for _ in range(order)]
series_in2 = [rng.randn(*b.shape) for _ in range(order)]
series_in3 = [rng.randn(*x.shape) for _ in range(order)]
series_in = (series_in1, series_in2, series_in3)
def f(W, b, x):
return apply_fun((W, b), x)
self.check_jet(f, primals, series_in, check_dtypes=False)
def unary_check(self, fun, lims=[-2, 2], order=3, dtype=None, atol=1e-4,
rtol=1e-4):
dims = 2, 3
rng = np.random.RandomState(0)
if dtype is None:
primal_in = transform(lims, rng.rand(*dims))
terms_in = [rng.randn(*dims) for _ in range(order)]
else:
rng = jtu.rand_uniform(rng, *lims)
primal_in = rng(dims, dtype)
terms_in = [rng(dims, dtype) for _ in range(order)]
self.check_jet(fun, (primal_in,), (terms_in,), atol, rtol)
def binary_check(self, fun, lims=[-2, 2], order=3, finite=True, dtype=None):
dims = 2, 3
rng = np.random.RandomState(0)
if isinstance(lims, tuple):
x_lims, y_lims = lims
else:
x_lims, y_lims = lims, lims
if dtype is None:
primal_in = (transform(x_lims, rng.rand(*dims)),
transform(y_lims, rng.rand(*dims)))
series_in = ([rng.randn(*dims) for _ in range(order)],
[rng.randn(*dims) for _ in range(order)])
else:
rng = jtu.rand_uniform(rng, *lims)
primal_in = (rng(dims, dtype),
rng(dims, dtype))
series_in = ([rng(dims, dtype) for _ in range(order)],
[rng(dims, dtype) for _ in range(order)])
if finite:
self.check_jet(fun, primal_in, series_in, atol=1e-4, rtol=1e-4)
else:
self.check_jet_finite(fun, primal_in, series_in, atol=1e-4, rtol=1e-4)
def unary_check_float0(self, fun, lims=[-2, 2], order=3, dtype=None):
# like unary_check but for functions that output integers (so their tangent
# type is float0 arrays)
raise unittest.SkipTest("jet tests must be adapted for integer-output functions")
def binary_check_float0(self, fun, lims=[-2, 2], order=3, finite=True, dtype=None):
# like binary_check but for functions that output integers (so their tangent
# type is float0 arrays)
raise unittest.SkipTest("jet tests must be adapted for integer-output functions")
def expit_check(self, lims=[-2, 2], order=3):
dims = 2, 3
rng = np.random.RandomState(0)
primal_in = transform(lims, rng.rand(*dims))
terms_in = [rng.randn(*dims) for _ in range(order)]
primals = (primal_in, )
series = (terms_in, )
y, terms = jax.experimental.jet._expit_taylor(primals, series)
expected_y, expected_terms = jvp_taylor(jax.scipy.special.expit, primals, series)
atol = 1e-4
rtol = 1e-4
self.assertAllClose(y, expected_y, atol=atol, rtol=rtol)
self.assertAllClose(terms, expected_terms, atol=atol, rtol=rtol)
@jtu.skip_on_devices("tpu")
def test_int_pow(self):
for p in range(6):
self.unary_check(lambda x: x ** p, lims=[-2, 2])
self.unary_check(lambda x: x ** 10, lims=[0, 0])
@jtu.skip_on_devices("tpu")
def test_is_finite(self): self.unary_check_float0(lax.is_finite)
@jtu.skip_on_devices("tpu")
def test_and(self): self.binary_check_float0(lax.bitwise_and, dtype=np.bool_)
@jtu.skip_on_devices("tpu")
def test_or(self): self.binary_check_float0(lax.bitwise_or, dtype=np.bool_)
@jtu.skip_on_devices("tpu")
def test_xor(self): self.binary_check_float0(jnp.bitwise_xor, dtype=np.bool_)
@jtu.skip_on_devices("tpu")
def test_shift_left(self): self.binary_check_float0(lax.shift_left, dtype=np.int32)
@jtu.skip_on_devices("tpu")
def test_shift_right_a(self): self.binary_check_float0(lax.shift_right_arithmetic, dtype=np.int32)
@jtu.skip_on_devices("tpu")
def test_shift_right_l(self): self.binary_check_float0(lax.shift_right_logical, dtype=np.int32)
@jtu.skip_on_devices("tpu")
def test_le(self): self.binary_check_float0(lambda x, y: x <= y)
@jtu.skip_on_devices("tpu")
def test_gt(self): self.binary_check_float0(lambda x, y: x > y)
@jtu.skip_on_devices("tpu")
def test_lt(self): self.binary_check_float0(lambda x, y: x < y)
@jtu.skip_on_devices("tpu")
def test_ge(self): self.binary_check_float0(lambda x, y: x >= y)
@jtu.skip_on_devices("tpu")
def test_eq(self): self.binary_check_float0(lambda x, y: x == y)
@jtu.skip_on_devices("tpu")
def test_ne(self): self.binary_check_float0(lambda x, y: x != y)
@jtu.skip_on_devices("tpu")
def test_not(self): self.unary_check_float0(lax.bitwise_not, dtype=np.bool_)
@jtu.skip_on_devices("tpu")
def test_exp(self): self.unary_check(jnp.exp)
@jtu.skip_on_devices("tpu")
def test_neg(self): self.unary_check(jnp.negative)
@jtu.skip_on_devices("tpu")
def test_floor(self): self.unary_check(jnp.floor)
@jtu.skip_on_devices("tpu")
def test_ceil(self): self.unary_check(jnp.ceil)
@jtu.skip_on_devices("tpu")
def test_round(self): self.unary_check(lax.round)
@jtu.skip_on_devices("tpu")
def test_sign(self): self.unary_check(lax.sign)
@jtu.skip_on_devices("tpu")
def test_real(self): self.unary_check(lax.real, dtype=np.complex64)
@jtu.skip_on_devices("tpu")
def test_conj(self): self.unary_check(lax.conj, dtype=np.complex64)
@jtu.skip_on_devices("tpu")
def test_imag(self): self.unary_check(lax.imag, dtype=np.complex64)
@jtu.skip_on_devices("tpu")
def test_log(self): self.unary_check(jnp.log, lims=[0.8, 4.0])
@jtu.skip_on_devices("tpu")
def test_gather(self): self.unary_check(lambda x: x[1:])
@jtu.skip_on_devices("tpu")
def test_reduce_max(self): self.unary_check(lambda x: x.max(axis=1))
@jtu.skip_on_devices("tpu")
def test_reduce_min(self): self.unary_check(lambda x: x.min(axis=1))
@jtu.skip_on_devices("tpu")
def test_all_max(self): self.unary_check(jnp.max)
@jtu.skip_on_devices("tpu")
def test_all_min(self): self.unary_check(jnp.min)
@jtu.skip_on_devices("tpu")
def test_stopgrad(self): self.unary_check(lax.stop_gradient)
@jtu.skip_on_devices("tpu")
def test_abs(self): self.unary_check(jnp.abs)
@jtu.skip_on_devices("tpu")
def test_fft(self): self.unary_check(jnp.fft.fft)
@jtu.skip_on_devices("tpu")
def test_log1p(self): self.unary_check(jnp.log1p, lims=[0, 4.])
@jtu.skip_on_devices("tpu")
def test_expm1(self): self.unary_check(jnp.expm1)
@jtu.skip_on_devices("tpu")
def test_sin(self): self.unary_check(jnp.sin)
@jtu.skip_on_devices("tpu")
def test_cos(self): self.unary_check(jnp.cos)
@jtu.skip_on_devices("tpu")
def test_sinh(self): self.unary_check(jnp.sinh)
@jtu.skip_on_devices("tpu")
def test_cosh(self): self.unary_check(jnp.cosh)
@jtu.skip_on_devices("tpu")
def test_tanh(self): self.unary_check(jnp.tanh, lims=[-500, 500], order=5)
@jtu.skip_on_devices("tpu")
def test_expit(self): self.unary_check(jax.scipy.special.expit, lims=[-500, 500], order=5)
@jtu.skip_on_devices("tpu")
def test_expit2(self): self.expit_check(lims=[-500, 500], order=5)
@jtu.skip_on_devices("tpu")
def test_sqrt(self): self.unary_check(jnp.sqrt, lims=[0, 5.])
@jtu.skip_on_devices("tpu")
def test_rsqrt(self): self.unary_check(lax.rsqrt, lims=[0, 5000.])
@jtu.skip_on_devices("tpu")
def test_asinh(self): self.unary_check(lax.asinh, lims=[-100, 100])
@jtu.skip_on_devices("tpu")
def test_acosh(self): self.unary_check(lax.acosh, lims=[-100, 100])
@jtu.skip_on_devices("tpu")
def test_atanh(self): self.unary_check(lax.atanh, lims=[-1, 1])
@jtu.skip_on_devices("tpu")
def test_erf(self): self.unary_check(lax.erf)
@jtu.skip_on_devices("tpu")
def test_erfc(self): self.unary_check(lax.erfc)
@jtu.skip_on_devices("tpu")
def test_erf_inv(self): self.unary_check(lax.erf_inv, lims=[-1, 1])
@jtu.skip_on_devices("tpu")
def test_cumsum(self): self.unary_check(jnp.cumsum)
@jtu.skip_on_devices("tpu")
def test_cumprod(self): self.unary_check(jnp.cumprod)
@jtu.skip_on_devices("tpu")
def test_cummax(self): self.unary_check(partial(lax.cummax, axis=0))
@jtu.skip_on_devices("tpu")
def test_cummin(self): self.unary_check(partial(lax.cummin, axis=0))
@jtu.skip_on_devices("tpu")
def test_div(self): self.binary_check(lambda x, y: x / y, lims=[0.8, 4.0])
@jtu.skip_on_devices("tpu")
def test_rem(self): self.binary_check(lax.rem, lims=[0.8, 4.0])
@jtu.skip_on_devices("tpu")
def test_complex(self): self.binary_check(lax.complex)
@jtu.skip_on_devices("tpu")
def test_sub(self): self.binary_check(lambda x, y: x - y)
@jtu.skip_on_devices("tpu")
def test_add(self): self.binary_check(lambda x, y: x + y)
@jtu.skip_on_devices("tpu")
def test_mul(self): self.binary_check(lambda x, y: x * y)
@jtu.skip_on_devices("tpu")
def test_max(self): self.binary_check(lax.max)
@jtu.skip_on_devices("tpu")
def test_min(self): self.binary_check(lax.min)
@jtu.skip_on_devices("tpu")
@jtu.ignore_warning(message="overflow encountered in power")
def test_pow(self): self.binary_check(lambda x, y: x ** y, lims=([0.2, 500], [-500, 500]), finite=False)
@jtu.skip_on_devices("tpu")
def test_atan2(self): self.binary_check(lax.atan2, lims=[-40, 40])
@jtu.skip_on_devices("tpu")
def test_clamp(self):
lims = [-2, 2]
order = 3
dims = 2, 3
rng = np.random.RandomState(0)
primal_in = (transform(lims, rng.rand(*dims)),
transform(lims, rng.rand(*dims)),
transform(lims, rng.rand(*dims)))
series_in = ([rng.randn(*dims) for _ in range(order)],
[rng.randn(*dims) for _ in range(order)],
[rng.randn(*dims) for _ in range(order)])
self.check_jet(lax.clamp, primal_in, series_in, atol=1e-4, rtol=1e-4)
def test_process_call(self):
def f(x):
return jit(lambda x: x * x)(x)
self.unary_check(f, rtol=2e-4)
def test_post_process_call(self):
def f(x):
return jit(lambda y: x * y)(2.)
self.unary_check(f, rtol=5e-4)
def test_select(self):
M, K = 2, 3
order = 3
rng = np.random.RandomState(0)
b = rng.rand(M, K) < 0.5
x = rng.randn(M, K)
y = rng.randn(M, K)
primals = (b, x, y)
terms_b = [rng.randn(*b.shape) for _ in range(order)]
terms_x = [rng.randn(*x.shape) for _ in range(order)]
terms_y = [rng.randn(*y.shape) for _ in range(order)]
series_in = (terms_b, terms_x, terms_y)
self.check_jet(jnp.where, primals, series_in, rtol=5e-4)
def test_inst_zero(self):
def f(x):
return 2.
def g(x):
return 2. + 0 * x
x = jnp.ones(1)
order = 3
f_out_primals, f_out_series = jet(f, (x, ), ([jnp.ones_like(x) for _ in range(order)], ))
assert f_out_series is not zero_series
g_out_primals, g_out_series = jet(g, (x, ), ([jnp.ones_like(x) for _ in range(order)], ))
assert g_out_primals == f_out_primals
assert g_out_series == f_out_series
def test_add_any(self):
# https://github.com/google/jax/issues/5217
f = lambda x, eps: x * eps + eps + x
def g(eps):
x = jnp.array(1.)
return jax.grad(f)(x, eps)
jet(g, (1.,), ([1.],)) # doesn't crash
def test_scatter_add(self):
# very basic test from https://github.com/google/jax/issues/5365
def f(x):
x0 = x[0]
x1 = x[1]
return (x0**5 + x1**5).sum()
def h(eps):
from jax import jacfwd, grad
x = jnp.array([1., 1.])
μ = eps * x
def F(t):
return f(x + t * μ)
return grad(jacfwd(F))(0.)
self.check_jet(h, (0.,), ([1., 2., 3.],), rtol=1e-3)
if __name__ == '__main__':
absltest.main(testLoader=jtu.JaxTestLoader())
| 37.653012 | 114 | 0.656534 |
from functools import reduce, partial
from absl.testing import absltest
import numpy as np
import unittest
import jax
from jax import test_util as jtu
import jax.numpy as jnp
import jax.scipy.special
from jax import random
from jax import jacfwd, jit
from jax.experimental import stax
from jax.experimental.jet import jet, fact, zero_series
from jax import lax
from jax.config import config
config.parse_flags_with_absl()
def jvp_taylor(fun, primals, series):
order, = set(map(len, series))
primals = tuple(jnp.asarray(p) for p in primals)
def composition(eps):
taylor_terms = [sum([eps ** (i+1) * terms[i] / fact(i + 1)
for i in range(len(terms))]) for terms in series]
nudged_args = [(x + t).astype(x.dtype) for x, t in zip(primals, taylor_terms)]
return fun(*nudged_args)
primal_out = fun(*primals)
terms_out = [repeated(jacfwd, i+1)(composition)(0.) for i in range(order)]
return primal_out, terms_out
def repeated(f, n):
def rfun(p):
return reduce(lambda x, _: f(x), range(n), p)
return rfun
def transform(lims, x):
return x * (lims[1] - lims[0]) + lims[0]
class JetTest(jtu.JaxTestCase):
def check_jet(self, fun, primals, series, atol=1e-5, rtol=1e-5,
check_dtypes=True):
y, terms = jet(fun, primals, series)
expected_y, expected_terms = jvp_taylor(fun, primals, series)
self.assertAllClose(y, expected_y, atol=atol, rtol=rtol,
check_dtypes=check_dtypes)
self.assertAllClose(terms, expected_terms, atol=atol, rtol=rtol,
check_dtypes=check_dtypes)
def check_jet_finite(self, fun, primals, series, atol=1e-5, rtol=1e-5,
check_dtypes=True):
y, terms = jet(fun, primals, series)
expected_y, expected_terms = jvp_taylor(fun, primals, series)
def _convert(x):
return jnp.where(jnp.isfinite(x), x, jnp.nan)
y = _convert(y)
expected_y = _convert(expected_y)
terms = _convert(jnp.asarray(terms))
expected_terms = _convert(jnp.asarray(expected_terms))
self.assertAllClose(y, expected_y, atol=atol, rtol=rtol,
check_dtypes=check_dtypes)
self.assertAllClose(terms, expected_terms, atol=atol, rtol=rtol,
check_dtypes=check_dtypes)
@jtu.skip_on_devices("tpu")
def test_dot(self):
M, K, N = 2, 3, 4
order = 3
rng = np.random.RandomState(0)
x1 = rng.randn(M, K)
x2 = rng.randn(K, N)
primals = (x1, x2)
terms_in1 = [rng.randn(*x1.shape) for _ in range(order)]
terms_in2 = [rng.randn(*x2.shape) for _ in range(order)]
series_in = (terms_in1, terms_in2)
self.check_jet(jnp.dot, primals, series_in)
@jtu.skip_on_devices("tpu")
def test_conv(self):
order = 3
input_shape = (1, 5, 5, 1)
key = random.PRNGKey(0)
init_fun, apply_fun = stax.Conv(3, (2, 2), padding='VALID')
_, (W, b) = init_fun(key, input_shape)
rng = np.random.RandomState(0)
x = rng.randn(*input_shape)
primals = (W, b, x)
series_in1 = [rng.randn(*W.shape) for _ in range(order)]
series_in2 = [rng.randn(*b.shape) for _ in range(order)]
series_in3 = [rng.randn(*x.shape) for _ in range(order)]
series_in = (series_in1, series_in2, series_in3)
def f(W, b, x):
return apply_fun((W, b), x)
self.check_jet(f, primals, series_in, check_dtypes=False)
def unary_check(self, fun, lims=[-2, 2], order=3, dtype=None, atol=1e-4,
rtol=1e-4):
dims = 2, 3
rng = np.random.RandomState(0)
if dtype is None:
primal_in = transform(lims, rng.rand(*dims))
terms_in = [rng.randn(*dims) for _ in range(order)]
else:
rng = jtu.rand_uniform(rng, *lims)
primal_in = rng(dims, dtype)
terms_in = [rng(dims, dtype) for _ in range(order)]
self.check_jet(fun, (primal_in,), (terms_in,), atol, rtol)
def binary_check(self, fun, lims=[-2, 2], order=3, finite=True, dtype=None):
dims = 2, 3
rng = np.random.RandomState(0)
if isinstance(lims, tuple):
x_lims, y_lims = lims
else:
x_lims, y_lims = lims, lims
if dtype is None:
primal_in = (transform(x_lims, rng.rand(*dims)),
transform(y_lims, rng.rand(*dims)))
series_in = ([rng.randn(*dims) for _ in range(order)],
[rng.randn(*dims) for _ in range(order)])
else:
rng = jtu.rand_uniform(rng, *lims)
primal_in = (rng(dims, dtype),
rng(dims, dtype))
series_in = ([rng(dims, dtype) for _ in range(order)],
[rng(dims, dtype) for _ in range(order)])
if finite:
self.check_jet(fun, primal_in, series_in, atol=1e-4, rtol=1e-4)
else:
self.check_jet_finite(fun, primal_in, series_in, atol=1e-4, rtol=1e-4)
def unary_check_float0(self, fun, lims=[-2, 2], order=3, dtype=None):
raise unittest.SkipTest("jet tests must be adapted for integer-output functions")
def binary_check_float0(self, fun, lims=[-2, 2], order=3, finite=True, dtype=None):
raise unittest.SkipTest("jet tests must be adapted for integer-output functions")
def expit_check(self, lims=[-2, 2], order=3):
dims = 2, 3
rng = np.random.RandomState(0)
primal_in = transform(lims, rng.rand(*dims))
terms_in = [rng.randn(*dims) for _ in range(order)]
primals = (primal_in, )
series = (terms_in, )
y, terms = jax.experimental.jet._expit_taylor(primals, series)
expected_y, expected_terms = jvp_taylor(jax.scipy.special.expit, primals, series)
atol = 1e-4
rtol = 1e-4
self.assertAllClose(y, expected_y, atol=atol, rtol=rtol)
self.assertAllClose(terms, expected_terms, atol=atol, rtol=rtol)
@jtu.skip_on_devices("tpu")
def test_int_pow(self):
for p in range(6):
self.unary_check(lambda x: x ** p, lims=[-2, 2])
self.unary_check(lambda x: x ** 10, lims=[0, 0])
@jtu.skip_on_devices("tpu")
def test_is_finite(self): self.unary_check_float0(lax.is_finite)
@jtu.skip_on_devices("tpu")
def test_and(self): self.binary_check_float0(lax.bitwise_and, dtype=np.bool_)
@jtu.skip_on_devices("tpu")
def test_or(self): self.binary_check_float0(lax.bitwise_or, dtype=np.bool_)
@jtu.skip_on_devices("tpu")
def test_xor(self): self.binary_check_float0(jnp.bitwise_xor, dtype=np.bool_)
@jtu.skip_on_devices("tpu")
def test_shift_left(self): self.binary_check_float0(lax.shift_left, dtype=np.int32)
@jtu.skip_on_devices("tpu")
def test_shift_right_a(self): self.binary_check_float0(lax.shift_right_arithmetic, dtype=np.int32)
@jtu.skip_on_devices("tpu")
def test_shift_right_l(self): self.binary_check_float0(lax.shift_right_logical, dtype=np.int32)
@jtu.skip_on_devices("tpu")
def test_le(self): self.binary_check_float0(lambda x, y: x <= y)
@jtu.skip_on_devices("tpu")
def test_gt(self): self.binary_check_float0(lambda x, y: x > y)
@jtu.skip_on_devices("tpu")
def test_lt(self): self.binary_check_float0(lambda x, y: x < y)
@jtu.skip_on_devices("tpu")
def test_ge(self): self.binary_check_float0(lambda x, y: x >= y)
@jtu.skip_on_devices("tpu")
def test_eq(self): self.binary_check_float0(lambda x, y: x == y)
@jtu.skip_on_devices("tpu")
def test_ne(self): self.binary_check_float0(lambda x, y: x != y)
@jtu.skip_on_devices("tpu")
def test_not(self): self.unary_check_float0(lax.bitwise_not, dtype=np.bool_)
@jtu.skip_on_devices("tpu")
def test_exp(self): self.unary_check(jnp.exp)
@jtu.skip_on_devices("tpu")
def test_neg(self): self.unary_check(jnp.negative)
@jtu.skip_on_devices("tpu")
def test_floor(self): self.unary_check(jnp.floor)
@jtu.skip_on_devices("tpu")
def test_ceil(self): self.unary_check(jnp.ceil)
@jtu.skip_on_devices("tpu")
def test_round(self): self.unary_check(lax.round)
@jtu.skip_on_devices("tpu")
def test_sign(self): self.unary_check(lax.sign)
@jtu.skip_on_devices("tpu")
def test_real(self): self.unary_check(lax.real, dtype=np.complex64)
@jtu.skip_on_devices("tpu")
def test_conj(self): self.unary_check(lax.conj, dtype=np.complex64)
@jtu.skip_on_devices("tpu")
def test_imag(self): self.unary_check(lax.imag, dtype=np.complex64)
@jtu.skip_on_devices("tpu")
def test_log(self): self.unary_check(jnp.log, lims=[0.8, 4.0])
@jtu.skip_on_devices("tpu")
def test_gather(self): self.unary_check(lambda x: x[1:])
@jtu.skip_on_devices("tpu")
def test_reduce_max(self): self.unary_check(lambda x: x.max(axis=1))
@jtu.skip_on_devices("tpu")
def test_reduce_min(self): self.unary_check(lambda x: x.min(axis=1))
@jtu.skip_on_devices("tpu")
def test_all_max(self): self.unary_check(jnp.max)
@jtu.skip_on_devices("tpu")
def test_all_min(self): self.unary_check(jnp.min)
@jtu.skip_on_devices("tpu")
def test_stopgrad(self): self.unary_check(lax.stop_gradient)
@jtu.skip_on_devices("tpu")
def test_abs(self): self.unary_check(jnp.abs)
@jtu.skip_on_devices("tpu")
def test_fft(self): self.unary_check(jnp.fft.fft)
@jtu.skip_on_devices("tpu")
def test_log1p(self): self.unary_check(jnp.log1p, lims=[0, 4.])
@jtu.skip_on_devices("tpu")
def test_expm1(self): self.unary_check(jnp.expm1)
@jtu.skip_on_devices("tpu")
def test_sin(self): self.unary_check(jnp.sin)
@jtu.skip_on_devices("tpu")
def test_cos(self): self.unary_check(jnp.cos)
@jtu.skip_on_devices("tpu")
def test_sinh(self): self.unary_check(jnp.sinh)
@jtu.skip_on_devices("tpu")
def test_cosh(self): self.unary_check(jnp.cosh)
@jtu.skip_on_devices("tpu")
def test_tanh(self): self.unary_check(jnp.tanh, lims=[-500, 500], order=5)
@jtu.skip_on_devices("tpu")
def test_expit(self): self.unary_check(jax.scipy.special.expit, lims=[-500, 500], order=5)
@jtu.skip_on_devices("tpu")
def test_expit2(self): self.expit_check(lims=[-500, 500], order=5)
@jtu.skip_on_devices("tpu")
def test_sqrt(self): self.unary_check(jnp.sqrt, lims=[0, 5.])
@jtu.skip_on_devices("tpu")
def test_rsqrt(self): self.unary_check(lax.rsqrt, lims=[0, 5000.])
@jtu.skip_on_devices("tpu")
def test_asinh(self): self.unary_check(lax.asinh, lims=[-100, 100])
@jtu.skip_on_devices("tpu")
def test_acosh(self): self.unary_check(lax.acosh, lims=[-100, 100])
@jtu.skip_on_devices("tpu")
def test_atanh(self): self.unary_check(lax.atanh, lims=[-1, 1])
@jtu.skip_on_devices("tpu")
def test_erf(self): self.unary_check(lax.erf)
@jtu.skip_on_devices("tpu")
def test_erfc(self): self.unary_check(lax.erfc)
@jtu.skip_on_devices("tpu")
def test_erf_inv(self): self.unary_check(lax.erf_inv, lims=[-1, 1])
@jtu.skip_on_devices("tpu")
def test_cumsum(self): self.unary_check(jnp.cumsum)
@jtu.skip_on_devices("tpu")
def test_cumprod(self): self.unary_check(jnp.cumprod)
@jtu.skip_on_devices("tpu")
def test_cummax(self): self.unary_check(partial(lax.cummax, axis=0))
@jtu.skip_on_devices("tpu")
def test_cummin(self): self.unary_check(partial(lax.cummin, axis=0))
@jtu.skip_on_devices("tpu")
def test_div(self): self.binary_check(lambda x, y: x / y, lims=[0.8, 4.0])
@jtu.skip_on_devices("tpu")
def test_rem(self): self.binary_check(lax.rem, lims=[0.8, 4.0])
@jtu.skip_on_devices("tpu")
def test_complex(self): self.binary_check(lax.complex)
@jtu.skip_on_devices("tpu")
def test_sub(self): self.binary_check(lambda x, y: x - y)
@jtu.skip_on_devices("tpu")
def test_add(self): self.binary_check(lambda x, y: x + y)
@jtu.skip_on_devices("tpu")
def test_mul(self): self.binary_check(lambda x, y: x * y)
@jtu.skip_on_devices("tpu")
def test_max(self): self.binary_check(lax.max)
@jtu.skip_on_devices("tpu")
def test_min(self): self.binary_check(lax.min)
@jtu.skip_on_devices("tpu")
@jtu.ignore_warning(message="overflow encountered in power")
def test_pow(self): self.binary_check(lambda x, y: x ** y, lims=([0.2, 500], [-500, 500]), finite=False)
@jtu.skip_on_devices("tpu")
def test_atan2(self): self.binary_check(lax.atan2, lims=[-40, 40])
@jtu.skip_on_devices("tpu")
def test_clamp(self):
lims = [-2, 2]
order = 3
dims = 2, 3
rng = np.random.RandomState(0)
primal_in = (transform(lims, rng.rand(*dims)),
transform(lims, rng.rand(*dims)),
transform(lims, rng.rand(*dims)))
series_in = ([rng.randn(*dims) for _ in range(order)],
[rng.randn(*dims) for _ in range(order)],
[rng.randn(*dims) for _ in range(order)])
self.check_jet(lax.clamp, primal_in, series_in, atol=1e-4, rtol=1e-4)
def test_process_call(self):
def f(x):
return jit(lambda x: x * x)(x)
self.unary_check(f, rtol=2e-4)
def test_post_process_call(self):
def f(x):
return jit(lambda y: x * y)(2.)
self.unary_check(f, rtol=5e-4)
def test_select(self):
M, K = 2, 3
order = 3
rng = np.random.RandomState(0)
b = rng.rand(M, K) < 0.5
x = rng.randn(M, K)
y = rng.randn(M, K)
primals = (b, x, y)
terms_b = [rng.randn(*b.shape) for _ in range(order)]
terms_x = [rng.randn(*x.shape) for _ in range(order)]
terms_y = [rng.randn(*y.shape) for _ in range(order)]
series_in = (terms_b, terms_x, terms_y)
self.check_jet(jnp.where, primals, series_in, rtol=5e-4)
def test_inst_zero(self):
def f(x):
return 2.
def g(x):
return 2. + 0 * x
x = jnp.ones(1)
order = 3
f_out_primals, f_out_series = jet(f, (x, ), ([jnp.ones_like(x) for _ in range(order)], ))
assert f_out_series is not zero_series
g_out_primals, g_out_series = jet(g, (x, ), ([jnp.ones_like(x) for _ in range(order)], ))
assert g_out_primals == f_out_primals
assert g_out_series == f_out_series
def test_add_any(self):
f = lambda x, eps: x * eps + eps + x
def g(eps):
x = jnp.array(1.)
return jax.grad(f)(x, eps)
jet(g, (1.,), ([1.],))
def test_scatter_add(self):
# very basic test from https://github.com/google/jax/issues/5365
def f(x):
x0 = x[0]
x1 = x[1]
return (x0**5 + x1**5).sum()
def h(eps):
from jax import jacfwd, grad
x = jnp.array([1., 1.])
μ = eps * x
def F(t):
return f(x + t * μ)
return grad(jacfwd(F))(0.)
self.check_jet(h, (0.,), ([1., 2., 3.],), rtol=1e-3)
if __name__ == '__main__':
absltest.main(testLoader=jtu.JaxTestLoader())
| true | true |
f72b7f5a198735854caf644778be99b784ac4157 | 19,981 | py | Python | Lib/distutils/sysconfig.py | zgrge/cpython | 0e59d247457dde747d84c899e96423647b3da149 | [
"PSF-2.0"
] | null | null | null | Lib/distutils/sysconfig.py | zgrge/cpython | 0e59d247457dde747d84c899e96423647b3da149 | [
"PSF-2.0"
] | null | null | null | Lib/distutils/sysconfig.py | zgrge/cpython | 0e59d247457dde747d84c899e96423647b3da149 | [
"PSF-2.0"
] | 1 | 2021-09-04T13:33:46.000Z | 2021-09-04T13:33:46.000Z | """Provide access to Python's configuration information. The specific
configuration variables available depend heavily on the platform and
configuration. The values may be retrieved using
get_config_var(name), and the list of variables is available via
get_config_vars().keys(). Additional convenience functions are also
available.
Written by: Fred L. Drake, Jr.
Email: <fdrake@acm.org>
"""
import _imp
import os
import re
import sys
from .errors import DistutilsPlatformError
# These are needed in a couple of spots, so just compute them once.
PREFIX = os.path.normpath(sys.prefix)
EXEC_PREFIX = os.path.normpath(sys.exec_prefix)
BASE_PREFIX = os.path.normpath(sys.base_prefix)
BASE_EXEC_PREFIX = os.path.normpath(sys.base_exec_prefix)
# Path to the base directory of the project. On Windows the binary may
# live in project/PCBuild/win32 or project/PCBuild/amd64.
# set for cross builds
if "_PYTHON_PROJECT_BASE" in os.environ:
project_base = os.path.abspath(os.environ["_PYTHON_PROJECT_BASE"])
else:
project_base = os.path.dirname(os.path.abspath(sys.executable))
if (os.name == 'nt' and
project_base.lower().endswith(('\\pcbuild\\win32', '\\pcbuild\\amd64'))):
project_base = os.path.dirname(os.path.dirname(project_base))
# python_build: (Boolean) if true, we're either building Python or
# building an extension with an un-installed Python, so we use
# different (hard-wired) directories.
# Setup.local is available for Makefile builds including VPATH builds,
# Setup.dist is available on Windows
def _is_python_source_dir(d):
for fn in ("Setup.dist", "Setup.local"):
if os.path.isfile(os.path.join(d, "Modules", fn)):
return True
return False
_sys_home = getattr(sys, '_home', None)
if (_sys_home and os.name == 'nt' and
_sys_home.lower().endswith(('\\pcbuild\\win32', '\\pcbuild\\amd64'))):
_sys_home = os.path.dirname(os.path.dirname(_sys_home))
def _python_build():
if _sys_home:
return _is_python_source_dir(_sys_home)
return _is_python_source_dir(project_base)
python_build = _python_build()
# Calculate the build qualifier flags if they are defined. Adding the flags
# to the include and lib directories only makes sense for an installation, not
# an in-source build.
build_flags = ''
try:
if not python_build:
build_flags = sys.abiflags
except AttributeError:
# It's not a configure-based build, so the sys module doesn't have
# this attribute, which is fine.
pass
def get_python_version():
"""Return a string containing the major and minor Python version,
leaving off the patchlevel. Sample return values could be '1.5'
or '2.2'.
"""
return '%d.%d' % sys.version_info[:2]
def get_python_inc(plat_specific=0, prefix=None):
"""Return the directory containing installed Python header files.
If 'plat_specific' is false (the default), this is the path to the
non-platform-specific header files, i.e. Python.h and so on;
otherwise, this is the path to platform-specific header files
(namely pyconfig.h).
If 'prefix' is supplied, use it instead of sys.base_prefix or
sys.base_exec_prefix -- i.e., ignore 'plat_specific'.
"""
if prefix is None:
prefix = plat_specific and BASE_EXEC_PREFIX or BASE_PREFIX
if os.name == "posix":
if python_build:
# Assume the executable is in the build directory. The
# pyconfig.h file should be in the same directory. Since
# the build directory may not be the source directory, we
# must use "srcdir" from the makefile to find the "Include"
# directory.
base = _sys_home or project_base
if plat_specific:
return base
if _sys_home:
incdir = os.path.join(_sys_home, get_config_var('AST_H_DIR'))
else:
incdir = os.path.join(get_config_var('srcdir'), 'Include')
return os.path.normpath(incdir)
python_dir = 'python' + get_python_version() + build_flags
return os.path.join(prefix, "include", python_dir)
elif os.name == "nt":
return os.path.join(prefix, "include")
else:
raise DistutilsPlatformError(
"I don't know where Python installs its C header files "
"on platform '%s'" % os.name)
def get_python_lib(plat_specific=0, standard_lib=0, prefix=None):
"""Return the directory containing the Python library (standard or
site additions).
If 'plat_specific' is true, return the directory containing
platform-specific modules, i.e. any module from a non-pure-Python
module distribution; otherwise, return the platform-shared library
directory. If 'standard_lib' is true, return the directory
containing standard Python library modules; otherwise, return the
directory for site-specific modules.
If 'prefix' is supplied, use it instead of sys.base_prefix or
sys.base_exec_prefix -- i.e., ignore 'plat_specific'.
"""
if prefix is None:
if standard_lib:
prefix = plat_specific and BASE_EXEC_PREFIX or BASE_PREFIX
else:
prefix = plat_specific and EXEC_PREFIX or PREFIX
if os.name == "posix":
libpython = os.path.join(prefix,
"lib", "python" + get_python_version())
if standard_lib:
return libpython
else:
return os.path.join(libpython, "site-packages")
elif os.name == "nt":
if standard_lib:
return os.path.join(prefix, "Lib")
else:
return os.path.join(prefix, "Lib", "site-packages")
else:
raise DistutilsPlatformError(
"I don't know where Python installs its library "
"on platform '%s'" % os.name)
def customize_compiler(compiler):
"""Do any platform-specific customization of a CCompiler instance.
Mainly needed on Unix, so we can plug in the information that
varies across Unices and is stored in Python's Makefile.
"""
if compiler.compiler_type == "unix":
if sys.platform == "darwin":
# Perform first-time customization of compiler-related
# config vars on OS X now that we know we need a compiler.
# This is primarily to support Pythons from binary
# installers. The kind and paths to build tools on
# the user system may vary significantly from the system
# that Python itself was built on. Also the user OS
# version and build tools may not support the same set
# of CPU architectures for universal builds.
global _config_vars
# Use get_config_var() to ensure _config_vars is initialized.
if not get_config_var('CUSTOMIZED_OSX_COMPILER'):
import _osx_support
_osx_support.customize_compiler(_config_vars)
_config_vars['CUSTOMIZED_OSX_COMPILER'] = 'True'
(cc, cxx, opt, cflags, ccshared, ldshared, shlib_suffix, ar, ar_flags) = \
get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS',
'CCSHARED', 'LDSHARED', 'SHLIB_SUFFIX', 'AR', 'ARFLAGS')
if 'CC' in os.environ:
newcc = os.environ['CC']
if (sys.platform == 'darwin'
and 'LDSHARED' not in os.environ
and ldshared.startswith(cc)):
# On OS X, if CC is overridden, use that as the default
# command for LDSHARED as well
ldshared = newcc + ldshared[len(cc):]
cc = newcc
if 'CXX' in os.environ:
cxx = os.environ['CXX']
if 'LDSHARED' in os.environ:
ldshared = os.environ['LDSHARED']
if 'CPP' in os.environ:
cpp = os.environ['CPP']
else:
cpp = cc + " -E" # not always
if 'LDFLAGS' in os.environ:
ldshared = ldshared + ' ' + os.environ['LDFLAGS']
if 'CFLAGS' in os.environ:
cflags = opt + ' ' + os.environ['CFLAGS']
ldshared = ldshared + ' ' + os.environ['CFLAGS']
if 'CPPFLAGS' in os.environ:
cpp = cpp + ' ' + os.environ['CPPFLAGS']
cflags = cflags + ' ' + os.environ['CPPFLAGS']
ldshared = ldshared + ' ' + os.environ['CPPFLAGS']
if 'AR' in os.environ:
ar = os.environ['AR']
if 'ARFLAGS' in os.environ:
archiver = ar + ' ' + os.environ['ARFLAGS']
else:
archiver = ar + ' ' + ar_flags
cc_cmd = cc + ' ' + cflags
compiler.set_executables(
preprocessor=cpp,
compiler=cc_cmd,
compiler_so=cc_cmd + ' ' + ccshared,
compiler_cxx=cxx,
linker_so=ldshared,
linker_exe=cc,
archiver=archiver)
compiler.shared_lib_extension = shlib_suffix
def get_config_h_filename():
"""Return full pathname of installed pyconfig.h file."""
if python_build:
if os.name == "nt":
inc_dir = os.path.join(_sys_home or project_base, "PC")
else:
inc_dir = _sys_home or project_base
else:
inc_dir = get_python_inc(plat_specific=1)
return os.path.join(inc_dir, 'pyconfig.h')
def get_makefile_filename():
"""Return full pathname of installed Makefile from the Python build."""
if python_build:
return os.path.join(_sys_home or project_base, "Makefile")
lib_dir = get_python_lib(plat_specific=0, standard_lib=1)
config_file = 'config-{}{}'.format(get_python_version(), build_flags)
if hasattr(sys.implementation, '_multiarch'):
config_file += '-%s' % sys.implementation._multiarch
return os.path.join(lib_dir, config_file, 'Makefile')
def parse_config_h(fp, g=None):
"""Parse a config.h-style file.
A dictionary containing name/value pairs is returned. If an
optional dictionary is passed in as the second argument, it is
used instead of a new dictionary.
"""
if g is None:
g = {}
define_rx = re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n")
undef_rx = re.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n")
#
while True:
line = fp.readline()
if not line:
break
m = define_rx.match(line)
if m:
n, v = m.group(1, 2)
try: v = int(v)
except ValueError: pass
g[n] = v
else:
m = undef_rx.match(line)
if m:
g[m.group(1)] = 0
return g
# Regexes needed for parsing Makefile (and similar syntaxes,
# like old-style Setup files).
_variable_rx = re.compile("([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)")
_findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)")
_findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}")
def parse_makefile(fn, g=None):
"""Parse a Makefile-style file.
A dictionary containing name/value pairs is returned. If an
optional dictionary is passed in as the second argument, it is
used instead of a new dictionary.
"""
from distutils.text_file import TextFile
fp = TextFile(fn, strip_comments=1, skip_blanks=1, join_lines=1, errors="surrogateescape")
if g is None:
g = {}
done = {}
notdone = {}
while True:
line = fp.readline()
if line is None: # eof
break
m = _variable_rx.match(line)
if m:
n, v = m.group(1, 2)
v = v.strip()
# `$$' is a literal `$' in make
tmpv = v.replace('$$', '')
if "$" in tmpv:
notdone[n] = v
else:
try:
v = int(v)
except ValueError:
# insert literal `$'
done[n] = v.replace('$$', '$')
else:
done[n] = v
# Variables with a 'PY_' prefix in the makefile. These need to
# be made available without that prefix through sysconfig.
# Special care is needed to ensure that variable expansion works, even
# if the expansion uses the name without a prefix.
renamed_variables = ('CFLAGS', 'LDFLAGS', 'CPPFLAGS')
# do variable interpolation here
while notdone:
for name in list(notdone):
value = notdone[name]
m = _findvar1_rx.search(value) or _findvar2_rx.search(value)
if m:
n = m.group(1)
found = True
if n in done:
item = str(done[n])
elif n in notdone:
# get it on a subsequent round
found = False
elif n in os.environ:
# do it like make: fall back to environment
item = os.environ[n]
elif n in renamed_variables:
if name.startswith('PY_') and name[3:] in renamed_variables:
item = ""
elif 'PY_' + n in notdone:
found = False
else:
item = str(done['PY_' + n])
else:
done[n] = item = ""
if found:
after = value[m.end():]
value = value[:m.start()] + item + after
if "$" in after:
notdone[name] = value
else:
try: value = int(value)
except ValueError:
done[name] = value.strip()
else:
done[name] = value
del notdone[name]
if name.startswith('PY_') \
and name[3:] in renamed_variables:
name = name[3:]
if name not in done:
done[name] = value
else:
# bogus variable reference; just drop it since we can't deal
del notdone[name]
fp.close()
# strip spurious spaces
for k, v in done.items():
if isinstance(v, str):
done[k] = v.strip()
# save the results in the global dictionary
g.update(done)
return g
def expand_makefile_vars(s, vars):
"""Expand Makefile-style variables -- "${foo}" or "$(foo)" -- in
'string' according to 'vars' (a dictionary mapping variable names to
values). Variables not present in 'vars' are silently expanded to the
empty string. The variable values in 'vars' should not contain further
variable expansions; if 'vars' is the output of 'parse_makefile()',
you're fine. Returns a variable-expanded version of 's'.
"""
# This algorithm does multiple expansion, so if vars['foo'] contains
# "${bar}", it will expand ${foo} to ${bar}, and then expand
# ${bar}... and so forth. This is fine as long as 'vars' comes from
# 'parse_makefile()', which takes care of such expansions eagerly,
# according to make's variable expansion semantics.
while True:
m = _findvar1_rx.search(s) or _findvar2_rx.search(s)
if m:
(beg, end) = m.span()
s = s[0:beg] + vars.get(m.group(1)) + s[end:]
else:
break
return s
_config_vars = None
def _init_posix():
"""Initialize the module as appropriate for POSIX systems."""
# _sysconfigdata is generated at build time, see the sysconfig module
name = '_sysconfigdata_' + sys.abiflags
_temp = __import__(name, globals(), locals(), ['build_time_vars'], 0)
build_time_vars = _temp.build_time_vars
global _config_vars
_config_vars = {}
_config_vars.update(build_time_vars)
def _init_nt():
"""Initialize the module as appropriate for NT"""
g = {}
# set basic install directories
g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1)
g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1)
# XXX hmmm.. a normal install puts include files here
g['INCLUDEPY'] = get_python_inc(plat_specific=0)
g['EXT_SUFFIX'] = _imp.extension_suffixes()[0]
g['EXE'] = ".exe"
g['VERSION'] = get_python_version().replace(".", "")
g['BINDIR'] = os.path.dirname(os.path.abspath(sys.executable))
global _config_vars
_config_vars = g
def get_config_vars(*args):
"""With no arguments, return a dictionary of all configuration
variables relevant for the current platform. Generally this includes
everything needed to build extensions and install both pure modules and
extensions. On Unix, this means every variable defined in Python's
installed Makefile; on Windows it's a much smaller set.
With arguments, return a list of values that result from looking up
each argument in the configuration variable dictionary.
"""
global _config_vars
if _config_vars is None:
func = globals().get("_init_" + os.name)
if func:
func()
else:
_config_vars = {}
# Normalized versions of prefix and exec_prefix are handy to have;
# in fact, these are the standard versions used most places in the
# Distutils.
_config_vars['prefix'] = PREFIX
_config_vars['exec_prefix'] = EXEC_PREFIX
# For backward compatibility, see issue19555
SO = _config_vars.get('EXT_SUFFIX')
if SO is not None:
_config_vars['SO'] = SO
# Always convert srcdir to an absolute path
srcdir = _config_vars.get('srcdir', project_base)
if os.name == 'posix':
if python_build:
# If srcdir is a relative path (typically '.' or '..')
# then it should be interpreted relative to the directory
# containing Makefile.
base = os.path.dirname(get_makefile_filename())
srcdir = os.path.join(base, srcdir)
else:
# srcdir is not meaningful since the installation is
# spread about the filesystem. We choose the
# directory containing the Makefile since we know it
# exists.
srcdir = os.path.dirname(get_makefile_filename())
_config_vars['srcdir'] = os.path.abspath(os.path.normpath(srcdir))
# Convert srcdir into an absolute path if it appears necessary.
# Normally it is relative to the build directory. However, during
# testing, for example, we might be running a non-installed python
# from a different directory.
if python_build and os.name == "posix":
base = project_base
if (not os.path.isabs(_config_vars['srcdir']) and
base != os.getcwd()):
# srcdir is relative and we are not in the same directory
# as the executable. Assume executable is in the build
# directory and make srcdir absolute.
srcdir = os.path.join(base, _config_vars['srcdir'])
_config_vars['srcdir'] = os.path.normpath(srcdir)
# OS X platforms require special customization to handle
# multi-architecture, multi-os-version installers
if sys.platform == 'darwin':
import _osx_support
_osx_support.customize_config_vars(_config_vars)
if args:
vals = []
for name in args:
vals.append(_config_vars.get(name))
return vals
else:
return _config_vars
def get_config_var(name):
"""Return the value of a single variable using the dictionary
returned by 'get_config_vars()'. Equivalent to
get_config_vars().get(name)
"""
if name == 'SO':
import warnings
warnings.warn('SO is deprecated, use EXT_SUFFIX', DeprecationWarning, 2)
return get_config_vars().get(name)
| 37.629002 | 94 | 0.598619 |
import _imp
import os
import re
import sys
from .errors import DistutilsPlatformError
PREFIX = os.path.normpath(sys.prefix)
EXEC_PREFIX = os.path.normpath(sys.exec_prefix)
BASE_PREFIX = os.path.normpath(sys.base_prefix)
BASE_EXEC_PREFIX = os.path.normpath(sys.base_exec_prefix)
if "_PYTHON_PROJECT_BASE" in os.environ:
project_base = os.path.abspath(os.environ["_PYTHON_PROJECT_BASE"])
else:
project_base = os.path.dirname(os.path.abspath(sys.executable))
if (os.name == 'nt' and
project_base.lower().endswith(('\\pcbuild\\win32', '\\pcbuild\\amd64'))):
project_base = os.path.dirname(os.path.dirname(project_base))
# building an extension with an un-installed Python, so we use
# different (hard-wired) directories.
# Setup.local is available for Makefile builds including VPATH builds,
# Setup.dist is available on Windows
def _is_python_source_dir(d):
for fn in ("Setup.dist", "Setup.local"):
if os.path.isfile(os.path.join(d, "Modules", fn)):
return True
return False
_sys_home = getattr(sys, '_home', None)
if (_sys_home and os.name == 'nt' and
_sys_home.lower().endswith(('\\pcbuild\\win32', '\\pcbuild\\amd64'))):
_sys_home = os.path.dirname(os.path.dirname(_sys_home))
def _python_build():
if _sys_home:
return _is_python_source_dir(_sys_home)
return _is_python_source_dir(project_base)
python_build = _python_build()
# Calculate the build qualifier flags if they are defined. Adding the flags
# to the include and lib directories only makes sense for an installation, not
# an in-source build.
build_flags = ''
try:
if not python_build:
build_flags = sys.abiflags
except AttributeError:
# It's not a configure-based build, so the sys module doesn't have
# this attribute, which is fine.
pass
def get_python_version():
return '%d.%d' % sys.version_info[:2]
def get_python_inc(plat_specific=0, prefix=None):
if prefix is None:
prefix = plat_specific and BASE_EXEC_PREFIX or BASE_PREFIX
if os.name == "posix":
if python_build:
# Assume the executable is in the build directory. The
# pyconfig.h file should be in the same directory. Since
# the build directory may not be the source directory, we
# must use "srcdir" from the makefile to find the "Include"
# directory.
base = _sys_home or project_base
if plat_specific:
return base
if _sys_home:
incdir = os.path.join(_sys_home, get_config_var('AST_H_DIR'))
else:
incdir = os.path.join(get_config_var('srcdir'), 'Include')
return os.path.normpath(incdir)
python_dir = 'python' + get_python_version() + build_flags
return os.path.join(prefix, "include", python_dir)
elif os.name == "nt":
return os.path.join(prefix, "include")
else:
raise DistutilsPlatformError(
"I don't know where Python installs its C header files "
"on platform '%s'" % os.name)
def get_python_lib(plat_specific=0, standard_lib=0, prefix=None):
if prefix is None:
if standard_lib:
prefix = plat_specific and BASE_EXEC_PREFIX or BASE_PREFIX
else:
prefix = plat_specific and EXEC_PREFIX or PREFIX
if os.name == "posix":
libpython = os.path.join(prefix,
"lib", "python" + get_python_version())
if standard_lib:
return libpython
else:
return os.path.join(libpython, "site-packages")
elif os.name == "nt":
if standard_lib:
return os.path.join(prefix, "Lib")
else:
return os.path.join(prefix, "Lib", "site-packages")
else:
raise DistutilsPlatformError(
"I don't know where Python installs its library "
"on platform '%s'" % os.name)
def customize_compiler(compiler):
if compiler.compiler_type == "unix":
if sys.platform == "darwin":
# Perform first-time customization of compiler-related
# config vars on OS X now that we know we need a compiler.
# This is primarily to support Pythons from binary
# installers. The kind and paths to build tools on
# the user system may vary significantly from the system
# that Python itself was built on. Also the user OS
# version and build tools may not support the same set
# of CPU architectures for universal builds.
global _config_vars
# Use get_config_var() to ensure _config_vars is initialized.
if not get_config_var('CUSTOMIZED_OSX_COMPILER'):
import _osx_support
_osx_support.customize_compiler(_config_vars)
_config_vars['CUSTOMIZED_OSX_COMPILER'] = 'True'
(cc, cxx, opt, cflags, ccshared, ldshared, shlib_suffix, ar, ar_flags) = \
get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS',
'CCSHARED', 'LDSHARED', 'SHLIB_SUFFIX', 'AR', 'ARFLAGS')
if 'CC' in os.environ:
newcc = os.environ['CC']
if (sys.platform == 'darwin'
and 'LDSHARED' not in os.environ
and ldshared.startswith(cc)):
# On OS X, if CC is overridden, use that as the default
# command for LDSHARED as well
ldshared = newcc + ldshared[len(cc):]
cc = newcc
if 'CXX' in os.environ:
cxx = os.environ['CXX']
if 'LDSHARED' in os.environ:
ldshared = os.environ['LDSHARED']
if 'CPP' in os.environ:
cpp = os.environ['CPP']
else:
cpp = cc + " -E" # not always
if 'LDFLAGS' in os.environ:
ldshared = ldshared + ' ' + os.environ['LDFLAGS']
if 'CFLAGS' in os.environ:
cflags = opt + ' ' + os.environ['CFLAGS']
ldshared = ldshared + ' ' + os.environ['CFLAGS']
if 'CPPFLAGS' in os.environ:
cpp = cpp + ' ' + os.environ['CPPFLAGS']
cflags = cflags + ' ' + os.environ['CPPFLAGS']
ldshared = ldshared + ' ' + os.environ['CPPFLAGS']
if 'AR' in os.environ:
ar = os.environ['AR']
if 'ARFLAGS' in os.environ:
archiver = ar + ' ' + os.environ['ARFLAGS']
else:
archiver = ar + ' ' + ar_flags
cc_cmd = cc + ' ' + cflags
compiler.set_executables(
preprocessor=cpp,
compiler=cc_cmd,
compiler_so=cc_cmd + ' ' + ccshared,
compiler_cxx=cxx,
linker_so=ldshared,
linker_exe=cc,
archiver=archiver)
compiler.shared_lib_extension = shlib_suffix
def get_config_h_filename():
if python_build:
if os.name == "nt":
inc_dir = os.path.join(_sys_home or project_base, "PC")
else:
inc_dir = _sys_home or project_base
else:
inc_dir = get_python_inc(plat_specific=1)
return os.path.join(inc_dir, 'pyconfig.h')
def get_makefile_filename():
if python_build:
return os.path.join(_sys_home or project_base, "Makefile")
lib_dir = get_python_lib(plat_specific=0, standard_lib=1)
config_file = 'config-{}{}'.format(get_python_version(), build_flags)
if hasattr(sys.implementation, '_multiarch'):
config_file += '-%s' % sys.implementation._multiarch
return os.path.join(lib_dir, config_file, 'Makefile')
def parse_config_h(fp, g=None):
if g is None:
g = {}
define_rx = re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n")
undef_rx = re.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n")
#
while True:
line = fp.readline()
if not line:
break
m = define_rx.match(line)
if m:
n, v = m.group(1, 2)
try: v = int(v)
except ValueError: pass
g[n] = v
else:
m = undef_rx.match(line)
if m:
g[m.group(1)] = 0
return g
# Regexes needed for parsing Makefile (and similar syntaxes,
# like old-style Setup files).
_variable_rx = re.compile("([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)")
_findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)")
_findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}")
def parse_makefile(fn, g=None):
from distutils.text_file import TextFile
fp = TextFile(fn, strip_comments=1, skip_blanks=1, join_lines=1, errors="surrogateescape")
if g is None:
g = {}
done = {}
notdone = {}
while True:
line = fp.readline()
if line is None: # eof
break
m = _variable_rx.match(line)
if m:
n, v = m.group(1, 2)
v = v.strip()
# `$$' is a literal `$' in make
tmpv = v.replace('$$', '')
if "$" in tmpv:
notdone[n] = v
else:
try:
v = int(v)
except ValueError:
# insert literal `$'
done[n] = v.replace('$$', '$')
else:
done[n] = v
renamed_variables = ('CFLAGS', 'LDFLAGS', 'CPPFLAGS')
while notdone:
for name in list(notdone):
value = notdone[name]
m = _findvar1_rx.search(value) or _findvar2_rx.search(value)
if m:
n = m.group(1)
found = True
if n in done:
item = str(done[n])
elif n in notdone:
found = False
elif n in os.environ:
item = os.environ[n]
elif n in renamed_variables:
if name.startswith('PY_') and name[3:] in renamed_variables:
item = ""
elif 'PY_' + n in notdone:
found = False
else:
item = str(done['PY_' + n])
else:
done[n] = item = ""
if found:
after = value[m.end():]
value = value[:m.start()] + item + after
if "$" in after:
notdone[name] = value
else:
try: value = int(value)
except ValueError:
done[name] = value.strip()
else:
done[name] = value
del notdone[name]
if name.startswith('PY_') \
and name[3:] in renamed_variables:
name = name[3:]
if name not in done:
done[name] = value
else:
del notdone[name]
fp.close()
# strip spurious spaces
for k, v in done.items():
if isinstance(v, str):
done[k] = v.strip()
# save the results in the global dictionary
g.update(done)
return g
def expand_makefile_vars(s, vars):
# This algorithm does multiple expansion, so if vars['foo'] contains
# "${bar}", it will expand ${foo} to ${bar}, and then expand
# ${bar}... and so forth. This is fine as long as 'vars' comes from
# 'parse_makefile()', which takes care of such expansions eagerly,
# according to make's variable expansion semantics.
while True:
m = _findvar1_rx.search(s) or _findvar2_rx.search(s)
if m:
(beg, end) = m.span()
s = s[0:beg] + vars.get(m.group(1)) + s[end:]
else:
break
return s
_config_vars = None
def _init_posix():
name = '_sysconfigdata_' + sys.abiflags
_temp = __import__(name, globals(), locals(), ['build_time_vars'], 0)
build_time_vars = _temp.build_time_vars
global _config_vars
_config_vars = {}
_config_vars.update(build_time_vars)
def _init_nt():
g = {}
g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1)
g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1)
g['INCLUDEPY'] = get_python_inc(plat_specific=0)
g['EXT_SUFFIX'] = _imp.extension_suffixes()[0]
g['EXE'] = ".exe"
g['VERSION'] = get_python_version().replace(".", "")
g['BINDIR'] = os.path.dirname(os.path.abspath(sys.executable))
global _config_vars
_config_vars = g
def get_config_vars(*args):
global _config_vars
if _config_vars is None:
func = globals().get("_init_" + os.name)
if func:
func()
else:
_config_vars = {}
_config_vars['prefix'] = PREFIX
_config_vars['exec_prefix'] = EXEC_PREFIX
SO = _config_vars.get('EXT_SUFFIX')
if SO is not None:
_config_vars['SO'] = SO
srcdir = _config_vars.get('srcdir', project_base)
if os.name == 'posix':
if python_build:
base = os.path.dirname(get_makefile_filename())
srcdir = os.path.join(base, srcdir)
else:
srcdir = os.path.dirname(get_makefile_filename())
_config_vars['srcdir'] = os.path.abspath(os.path.normpath(srcdir))
if python_build and os.name == "posix":
base = project_base
if (not os.path.isabs(_config_vars['srcdir']) and
base != os.getcwd()):
srcdir = os.path.join(base, _config_vars['srcdir'])
_config_vars['srcdir'] = os.path.normpath(srcdir)
if sys.platform == 'darwin':
import _osx_support
_osx_support.customize_config_vars(_config_vars)
if args:
vals = []
for name in args:
vals.append(_config_vars.get(name))
return vals
else:
return _config_vars
def get_config_var(name):
if name == 'SO':
import warnings
warnings.warn('SO is deprecated, use EXT_SUFFIX', DeprecationWarning, 2)
return get_config_vars().get(name)
| true | true |
f72b8091065be3b6530f5a20ec604f2dd1b4fe73 | 5,012 | py | Python | core/routine.py | cybert79/Osmedeus | 684d853144e2f85343c3367440120142455f296b | [
"MIT"
] | 1 | 2019-07-14T20:48:19.000Z | 2019-07-14T20:48:19.000Z | core/routine.py | KbaHaxor/Osmedeus | 0894d52ad5949e9151b0fd05d9746ecafc8057b5 | [
"MIT"
] | null | null | null | core/routine.py | KbaHaxor/Osmedeus | 0894d52ad5949e9151b0fd05d9746ecafc8057b5 | [
"MIT"
] | null | null | null | import sys, time
from core import utils
from pprint import pprint
from modules import initials
from modules import subdomain
from modules import recon
from modules import assetfinding
from modules import takeover
from modules import screenshot
from modules import portscan
from modules import gitscan
from modules import burpstate
from modules import brutethings
from modules import dirbrute
from modules import vulnscan
from modules import cors
from modules import ipspace
from modules import sslscan
from modules import headers
from modules import conclusion
from modules import healcheck
# runnning normal routine if none of module specific
def normal(options):
utils.print_good("Running with {0} speed".format(options['SPEED']))
# Create skeleton json
initials.Initials(options)
# Finding subdomain
subdomain.SubdomainScanning(options)
# waiting for previous module
utils.just_waiting(options, 'SubdomainScanning')
# Scanning for subdomain take over
takeover.TakeOverScanning(options)
# Screen shot the target on common service
screenshot.ScreenShot(options)
# Recon
recon.Recon(options)
# Recon
assetfinding.AssetFinding(options)
# Scanning for CorsScan
cors.CorsScan(options)
# Discovery IP space
ipspace.IPSpace(options)
# SSL Scan
sslscan.SSLScan(options)
# Headers Scan
headers.HeadersScan(options)
# Note: From here the module gonna take really long time
# for scanning service and stuff like that
utils.print_info('This gonna take a while')
# Scanning all port using result from subdomain scanning
# and also checking vulnerable service based on version
portscan.PortScan(options)
# Directory scan
dirbrute.DirBrute(options)
# Starting vulnerable scan
vulnscan.VulnScan(options)
# brutethings.BruteThings(options)
conclusion.Conclusion(options)
def specific(options, module):
module = module.lower()
# checking the tool is installed right or not and exit
if 'health' in module:
health = healcheck.Healcheck(options)
if health.checking():
utils.print_good("All things look fine")
else:
utils.print_bad("Installing Osmedeus not correctly done")
utils.just_shutdown_flask(options)
sys.exit(0)
initials.Initials(options)
if 'sub' in module or 'subdomain' in module:
subdomain.SubdomainScanning(options)
takeover.TakeOverScanning(options)
screenshot.ScreenShot(options)
cors.CorsScan(options)
recon.Recon(options)
assetfinding.AssetFinding(options)
if 'ip' in module:
# Discovery IP space
ipspace.IPSpace(options)
if 'screen' in module:
# Discovery IP space
screenshot.ScreenShot(options)
if 'portscan' in module:
# scanning port, service and vuln with masscan and nmap
portscan.PortScan(options)
if 'headers' in module:
headers.HeadersScan(options)
if 'asset' in module:
assetfinding.AssetFinding(options)
if 'vuln' in module:
# scanning vulnerable service based on version
vulnscan.VulnScan(options)
if 'dir' in module:
# run blind directory brute force directly
dirbrute.DirBrute(options)
if 'brute' in module or 'force' in module:
# running brute force things based on scanning result
brutethings.BruteThings(options)
if 'git' in module:
gitscan.GitScan(options)
# if 'burp' in module:
# burpstate.BurpState(options)
conclusion.Conclusion(options)
# just for debug purpose
def debug(options):
utils.print_good("Debug routine")
utils.print_good("Running with {0} speed".format(options['SPEED']))
# Create skeleton json
pprint(options)
initials.Initials(options)
# ##Finding subdomain
subdomain.SubdomainScanning(options)
# ####waiting for previous module
# utils.just_waiting(options, 'SubdomainScanning')
# recon.Recon(options)
# ###Screen shot the target on common service
screenshot.ScreenShot(options)
# ###Scanning for subdomain take over
# takeover.TakeOverScanning(options)
# ##Discovery IP space
# ipspace.IPSpace(options)
# # # ##Scanning for CorsScan
# cors.CorsScan(options)
# ### SSL Scan
# sslscan.SSLScan(options)
# ##Headers Scan
# headers.HeadersScan(options)
# ##### Note: From here the module gonna take really long time for scanning service and stuff like that
# utils.print_info('This gonna take a while')
# dirbrute.DirBrute(options)
# #Scanning all port using result from subdomain scanning and also checking vulnerable service based on version
# portscan.PortScan(options)
# # #Starting vulnerable scan
# vulnscan.VulnScan(options)
# # #Brute force service from port scan result
# # brutethings.BruteThings(options)
# conclusion.Conclusion(options)
| 25.441624 | 115 | 0.70012 | import sys, time
from core import utils
from pprint import pprint
from modules import initials
from modules import subdomain
from modules import recon
from modules import assetfinding
from modules import takeover
from modules import screenshot
from modules import portscan
from modules import gitscan
from modules import burpstate
from modules import brutethings
from modules import dirbrute
from modules import vulnscan
from modules import cors
from modules import ipspace
from modules import sslscan
from modules import headers
from modules import conclusion
from modules import healcheck
def normal(options):
utils.print_good("Running with {0} speed".format(options['SPEED']))
initials.Initials(options)
subdomain.SubdomainScanning(options)
utils.just_waiting(options, 'SubdomainScanning')
takeover.TakeOverScanning(options)
screenshot.ScreenShot(options)
recon.Recon(options)
assetfinding.AssetFinding(options)
cors.CorsScan(options)
ipspace.IPSpace(options)
sslscan.SSLScan(options)
headers.HeadersScan(options)
utils.print_info('This gonna take a while')
portscan.PortScan(options)
dirbrute.DirBrute(options)
vulnscan.VulnScan(options)
conclusion.Conclusion(options)
def specific(options, module):
module = module.lower()
if 'health' in module:
health = healcheck.Healcheck(options)
if health.checking():
utils.print_good("All things look fine")
else:
utils.print_bad("Installing Osmedeus not correctly done")
utils.just_shutdown_flask(options)
sys.exit(0)
initials.Initials(options)
if 'sub' in module or 'subdomain' in module:
subdomain.SubdomainScanning(options)
takeover.TakeOverScanning(options)
screenshot.ScreenShot(options)
cors.CorsScan(options)
recon.Recon(options)
assetfinding.AssetFinding(options)
if 'ip' in module:
ipspace.IPSpace(options)
if 'screen' in module:
screenshot.ScreenShot(options)
if 'portscan' in module:
portscan.PortScan(options)
if 'headers' in module:
headers.HeadersScan(options)
if 'asset' in module:
assetfinding.AssetFinding(options)
if 'vuln' in module:
vulnscan.VulnScan(options)
if 'dir' in module:
dirbrute.DirBrute(options)
if 'brute' in module or 'force' in module:
brutethings.BruteThings(options)
if 'git' in module:
gitscan.GitScan(options)
conclusion.Conclusion(options)
def debug(options):
utils.print_good("Debug routine")
utils.print_good("Running with {0} speed".format(options['SPEED']))
pprint(options)
initials.Initials(options)
ons)
| true | true |
f72b81d4193fded68a3f2f0d2fc449f357b11230 | 108,819 | py | Python | synapse/handlers/federation.py | V02460/synapse | 782dd72037cf71fb3f9e4922b07c56df2f59de75 | [
"Apache-2.0"
] | null | null | null | synapse/handlers/federation.py | V02460/synapse | 782dd72037cf71fb3f9e4922b07c56df2f59de75 | [
"Apache-2.0"
] | null | null | null | synapse/handlers/federation.py | V02460/synapse | 782dd72037cf71fb3f9e4922b07c56df2f59de75 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
# Copyright 2014-2016 OpenMarket Ltd
# Copyright 2017-2018 New Vector Ltd
# Copyright 2019 The Matrix.org Foundation C.I.C.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains handlers for federation events."""
import itertools
import logging
import six
from six import iteritems, itervalues
from six.moves import http_client, zip
from signedjson.key import decode_verify_key_bytes
from signedjson.sign import verify_signed_json
from unpaddedbase64 import decode_base64
from twisted.internet import defer
from synapse.api.constants import EventTypes, Membership, RejectedReason
from synapse.api.errors import (
AuthError,
CodeMessageException,
Codes,
FederationDeniedError,
FederationError,
RequestSendFailed,
StoreError,
SynapseError,
)
from synapse.api.room_versions import KNOWN_ROOM_VERSIONS, RoomVersions
from synapse.crypto.event_signing import compute_event_signature
from synapse.event_auth import auth_types_for_event
from synapse.events.validator import EventValidator
from synapse.logging.context import (
make_deferred_yieldable,
nested_logging_context,
preserve_fn,
run_in_background,
)
from synapse.logging.utils import log_function
from synapse.replication.http.federation import (
ReplicationCleanRoomRestServlet,
ReplicationFederationSendEventsRestServlet,
)
from synapse.replication.http.membership import ReplicationUserJoinedLeftRoomRestServlet
from synapse.state import StateResolutionStore, resolve_events_with_store
from synapse.types import UserID, get_domain_from_id
from synapse.util import unwrapFirstError
from synapse.util.async_helpers import Linearizer
from synapse.util.distributor import user_joined_room
from synapse.util.retryutils import NotRetryingDestination
from synapse.visibility import filter_events_for_server
from ._base import BaseHandler
logger = logging.getLogger(__name__)
def shortstr(iterable, maxitems=5):
"""If iterable has maxitems or fewer, return the stringification of a list
containing those items.
Otherwise, return the stringification of a a list with the first maxitems items,
followed by "...".
Args:
iterable (Iterable): iterable to truncate
maxitems (int): number of items to return before truncating
Returns:
unicode
"""
items = list(itertools.islice(iterable, maxitems + 1))
if len(items) <= maxitems:
return str(items)
return "[" + ", ".join(repr(r) for r in items[:maxitems]) + ", ...]"
class FederationHandler(BaseHandler):
"""Handles events that originated from federation.
Responsible for:
a) handling received Pdus before handing them on as Events to the rest
of the home server (including auth and state conflict resoultion)
b) converting events that were produced by local clients that may need
to be sent to remote home servers.
c) doing the necessary dances to invite remote users and join remote
rooms.
"""
def __init__(self, hs):
super(FederationHandler, self).__init__(hs)
self.hs = hs
self.store = hs.get_datastore()
self.federation_client = hs.get_federation_client()
self.state_handler = hs.get_state_handler()
self.server_name = hs.hostname
self.keyring = hs.get_keyring()
self.action_generator = hs.get_action_generator()
self.is_mine_id = hs.is_mine_id
self.pusher_pool = hs.get_pusherpool()
self.spam_checker = hs.get_spam_checker()
self.event_creation_handler = hs.get_event_creation_handler()
self._server_notices_mxid = hs.config.server_notices_mxid
self.config = hs.config
self.http_client = hs.get_simple_http_client()
self._send_events_to_master = ReplicationFederationSendEventsRestServlet.make_client(
hs
)
self._notify_user_membership_change = ReplicationUserJoinedLeftRoomRestServlet.make_client(
hs
)
self._clean_room_for_join_client = ReplicationCleanRoomRestServlet.make_client(
hs
)
# When joining a room we need to queue any events for that room up
self.room_queues = {}
self._room_pdu_linearizer = Linearizer("fed_room_pdu")
self.third_party_event_rules = hs.get_third_party_event_rules()
@defer.inlineCallbacks
def on_receive_pdu(self, origin, pdu, sent_to_us_directly=False):
""" Process a PDU received via a federation /send/ transaction, or
via backfill of missing prev_events
Args:
origin (str): server which initiated the /send/ transaction. Will
be used to fetch missing events or state.
pdu (FrozenEvent): received PDU
sent_to_us_directly (bool): True if this event was pushed to us; False if
we pulled it as the result of a missing prev_event.
Returns (Deferred): completes with None
"""
room_id = pdu.room_id
event_id = pdu.event_id
logger.info("[%s %s] handling received PDU: %s", room_id, event_id, pdu)
# We reprocess pdus when we have seen them only as outliers
existing = yield self.store.get_event(
event_id, allow_none=True, allow_rejected=True
)
# FIXME: Currently we fetch an event again when we already have it
# if it has been marked as an outlier.
already_seen = existing and (
not existing.internal_metadata.is_outlier()
or pdu.internal_metadata.is_outlier()
)
if already_seen:
logger.debug("[%s %s]: Already seen pdu", room_id, event_id)
return
# do some initial sanity-checking of the event. In particular, make
# sure it doesn't have hundreds of prev_events or auth_events, which
# could cause a huge state resolution or cascade of event fetches.
try:
self._sanity_check_event(pdu)
except SynapseError as err:
logger.warn(
"[%s %s] Received event failed sanity checks", room_id, event_id
)
raise FederationError("ERROR", err.code, err.msg, affected=pdu.event_id)
# If we are currently in the process of joining this room, then we
# queue up events for later processing.
if room_id in self.room_queues:
logger.info(
"[%s %s] Queuing PDU from %s for now: join in progress",
room_id,
event_id,
origin,
)
self.room_queues[room_id].append((pdu, origin))
return
# If we're not in the room just ditch the event entirely. This is
# probably an old server that has come back and thinks we're still in
# the room (or we've been rejoined to the room by a state reset).
#
# Note that if we were never in the room then we would have already
# dropped the event, since we wouldn't know the room version.
is_in_room = yield self.auth.check_host_in_room(room_id, self.server_name)
if not is_in_room:
logger.info(
"[%s %s] Ignoring PDU from %s as we're not in the room",
room_id,
event_id,
origin,
)
return None
state = None
auth_chain = []
# Get missing pdus if necessary.
if not pdu.internal_metadata.is_outlier():
# We only backfill backwards to the min depth.
min_depth = yield self.get_min_depth_for_context(pdu.room_id)
logger.debug("[%s %s] min_depth: %d", room_id, event_id, min_depth)
prevs = set(pdu.prev_event_ids())
seen = yield self.store.have_seen_events(prevs)
if min_depth and pdu.depth < min_depth:
# This is so that we don't notify the user about this
# message, to work around the fact that some events will
# reference really really old events we really don't want to
# send to the clients.
pdu.internal_metadata.outlier = True
elif min_depth and pdu.depth > min_depth:
missing_prevs = prevs - seen
if sent_to_us_directly and missing_prevs:
# If we're missing stuff, ensure we only fetch stuff one
# at a time.
logger.info(
"[%s %s] Acquiring room lock to fetch %d missing prev_events: %s",
room_id,
event_id,
len(missing_prevs),
shortstr(missing_prevs),
)
with (yield self._room_pdu_linearizer.queue(pdu.room_id)):
logger.info(
"[%s %s] Acquired room lock to fetch %d missing prev_events",
room_id,
event_id,
len(missing_prevs),
)
yield self._get_missing_events_for_pdu(
origin, pdu, prevs, min_depth
)
# Update the set of things we've seen after trying to
# fetch the missing stuff
seen = yield self.store.have_seen_events(prevs)
if not prevs - seen:
logger.info(
"[%s %s] Found all missing prev_events",
room_id,
event_id,
)
elif missing_prevs:
logger.info(
"[%s %s] Not recursively fetching %d missing prev_events: %s",
room_id,
event_id,
len(missing_prevs),
shortstr(missing_prevs),
)
if prevs - seen:
# We've still not been able to get all of the prev_events for this event.
#
# In this case, we need to fall back to asking another server in the
# federation for the state at this event. That's ok provided we then
# resolve the state against other bits of the DAG before using it (which
# will ensure that you can't just take over a room by sending an event,
# withholding its prev_events, and declaring yourself to be an admin in
# the subsequent state request).
#
# Now, if we're pulling this event as a missing prev_event, then clearly
# this event is not going to become the only forward-extremity and we are
# guaranteed to resolve its state against our existing forward
# extremities, so that should be fine.
#
# On the other hand, if this event was pushed to us, it is possible for
# it to become the only forward-extremity in the room, and we would then
# trust its state to be the state for the whole room. This is very bad.
# Further, if the event was pushed to us, there is no excuse for us not to
# have all the prev_events. We therefore reject any such events.
#
# XXX this really feels like it could/should be merged with the above,
# but there is an interaction with min_depth that I'm not really
# following.
if sent_to_us_directly:
logger.warn(
"[%s %s] Rejecting: failed to fetch %d prev events: %s",
room_id,
event_id,
len(prevs - seen),
shortstr(prevs - seen),
)
raise FederationError(
"ERROR",
403,
(
"Your server isn't divulging details about prev_events "
"referenced in this event."
),
affected=pdu.event_id,
)
# Calculate the state after each of the previous events, and
# resolve them to find the correct state at the current event.
auth_chains = set()
event_map = {event_id: pdu}
try:
# Get the state of the events we know about
ours = yield self.store.get_state_groups_ids(room_id, seen)
# state_maps is a list of mappings from (type, state_key) to event_id
state_maps = list(
ours.values()
) # type: list[dict[tuple[str, str], str]]
# we don't need this any more, let's delete it.
del ours
# Ask the remote server for the states we don't
# know about
for p in prevs - seen:
logger.info(
"[%s %s] Requesting state at missing prev_event %s",
room_id,
event_id,
p,
)
room_version = yield self.store.get_room_version(room_id)
with nested_logging_context(p):
# note that if any of the missing prevs share missing state or
# auth events, the requests to fetch those events are deduped
# by the get_pdu_cache in federation_client.
remote_state, got_auth_chain = (
yield self.federation_client.get_state_for_room(
origin, room_id, p
)
)
# we want the state *after* p; get_state_for_room returns the
# state *before* p.
remote_event = yield self.federation_client.get_pdu(
[origin], p, room_version, outlier=True
)
if remote_event is None:
raise Exception(
"Unable to get missing prev_event %s" % (p,)
)
if remote_event.is_state():
remote_state.append(remote_event)
# XXX hrm I'm not convinced that duplicate events will compare
# for equality, so I'm not sure this does what the author
# hoped.
auth_chains.update(got_auth_chain)
remote_state_map = {
(x.type, x.state_key): x.event_id for x in remote_state
}
state_maps.append(remote_state_map)
for x in remote_state:
event_map[x.event_id] = x
state_map = yield resolve_events_with_store(
room_version,
state_maps,
event_map,
state_res_store=StateResolutionStore(self.store),
)
# We need to give _process_received_pdu the actual state events
# rather than event ids, so generate that now.
# First though we need to fetch all the events that are in
# state_map, so we can build up the state below.
evs = yield self.store.get_events(
list(state_map.values()),
get_prev_content=False,
check_redacted=False,
)
event_map.update(evs)
state = [event_map[e] for e in six.itervalues(state_map)]
auth_chain = list(auth_chains)
except Exception:
logger.warn(
"[%s %s] Error attempting to resolve state at missing "
"prev_events",
room_id,
event_id,
exc_info=True,
)
raise FederationError(
"ERROR",
403,
"We can't get valid state history.",
affected=event_id,
)
yield self._process_received_pdu(
origin, pdu, state=state, auth_chain=auth_chain
)
@defer.inlineCallbacks
def _get_missing_events_for_pdu(self, origin, pdu, prevs, min_depth):
"""
Args:
origin (str): Origin of the pdu. Will be called to get the missing events
pdu: received pdu
prevs (set(str)): List of event ids which we are missing
min_depth (int): Minimum depth of events to return.
"""
room_id = pdu.room_id
event_id = pdu.event_id
seen = yield self.store.have_seen_events(prevs)
if not prevs - seen:
return
latest = yield self.store.get_latest_event_ids_in_room(room_id)
# We add the prev events that we have seen to the latest
# list to ensure the remote server doesn't give them to us
latest = set(latest)
latest |= seen
logger.info(
"[%s %s]: Requesting missing events between %s and %s",
room_id,
event_id,
shortstr(latest),
event_id,
)
# XXX: we set timeout to 10s to help workaround
# https://github.com/matrix-org/synapse/issues/1733.
# The reason is to avoid holding the linearizer lock
# whilst processing inbound /send transactions, causing
# FDs to stack up and block other inbound transactions
# which empirically can currently take up to 30 minutes.
#
# N.B. this explicitly disables retry attempts.
#
# N.B. this also increases our chances of falling back to
# fetching fresh state for the room if the missing event
# can't be found, which slightly reduces our security.
# it may also increase our DAG extremity count for the room,
# causing additional state resolution? See #1760.
# However, fetching state doesn't hold the linearizer lock
# apparently.
#
# see https://github.com/matrix-org/synapse/pull/1744
#
# ----
#
# Update richvdh 2018/09/18: There are a number of problems with timing this
# request out agressively on the client side:
#
# - it plays badly with the server-side rate-limiter, which starts tarpitting you
# if you send too many requests at once, so you end up with the server carefully
# working through the backlog of your requests, which you have already timed
# out.
#
# - for this request in particular, we now (as of
# https://github.com/matrix-org/synapse/pull/3456) reject any PDUs where the
# server can't produce a plausible-looking set of prev_events - so we becone
# much more likely to reject the event.
#
# - contrary to what it says above, we do *not* fall back to fetching fresh state
# for the room if get_missing_events times out. Rather, we give up processing
# the PDU whose prevs we are missing, which then makes it much more likely that
# we'll end up back here for the *next* PDU in the list, which exacerbates the
# problem.
#
# - the agressive 10s timeout was introduced to deal with incoming federation
# requests taking 8 hours to process. It's not entirely clear why that was going
# on; certainly there were other issues causing traffic storms which are now
# resolved, and I think in any case we may be more sensible about our locking
# now. We're *certainly* more sensible about our logging.
#
# All that said: Let's try increasing the timout to 60s and see what happens.
try:
missing_events = yield self.federation_client.get_missing_events(
origin,
room_id,
earliest_events_ids=list(latest),
latest_events=[pdu],
limit=10,
min_depth=min_depth,
timeout=60000,
)
except RequestSendFailed as e:
# We failed to get the missing events, but since we need to handle
# the case of `get_missing_events` not returning the necessary
# events anyway, it is safe to simply log the error and continue.
logger.warn("[%s %s]: Failed to get prev_events: %s", room_id, event_id, e)
return
logger.info(
"[%s %s]: Got %d prev_events: %s",
room_id,
event_id,
len(missing_events),
shortstr(missing_events),
)
# We want to sort these by depth so we process them and
# tell clients about them in order.
missing_events.sort(key=lambda x: x.depth)
for ev in missing_events:
logger.info(
"[%s %s] Handling received prev_event %s",
room_id,
event_id,
ev.event_id,
)
with nested_logging_context(ev.event_id):
try:
yield self.on_receive_pdu(origin, ev, sent_to_us_directly=False)
except FederationError as e:
if e.code == 403:
logger.warn(
"[%s %s] Received prev_event %s failed history check.",
room_id,
event_id,
ev.event_id,
)
else:
raise
@defer.inlineCallbacks
def _process_received_pdu(self, origin, event, state, auth_chain):
""" Called when we have a new pdu. We need to do auth checks and put it
through the StateHandler.
"""
room_id = event.room_id
event_id = event.event_id
logger.debug("[%s %s] Processing event: %s", room_id, event_id, event)
event_ids = set()
if state:
event_ids |= {e.event_id for e in state}
if auth_chain:
event_ids |= {e.event_id for e in auth_chain}
seen_ids = yield self.store.have_seen_events(event_ids)
if state and auth_chain is not None:
# If we have any state or auth_chain given to us by the replication
# layer, then we should handle them (if we haven't before.)
event_infos = []
for e in itertools.chain(auth_chain, state):
if e.event_id in seen_ids:
continue
e.internal_metadata.outlier = True
auth_ids = e.auth_event_ids()
auth = {
(e.type, e.state_key): e
for e in auth_chain
if e.event_id in auth_ids or e.type == EventTypes.Create
}
event_infos.append({"event": e, "auth_events": auth})
seen_ids.add(e.event_id)
logger.info(
"[%s %s] persisting newly-received auth/state events %s",
room_id,
event_id,
[e["event"].event_id for e in event_infos],
)
yield self._handle_new_events(origin, event_infos)
try:
context = yield self._handle_new_event(origin, event, state=state)
except AuthError as e:
raise FederationError("ERROR", e.code, e.msg, affected=event.event_id)
room = yield self.store.get_room(room_id)
if not room:
try:
yield self.store.store_room(
room_id=room_id, room_creator_user_id="", is_public=False
)
except StoreError:
logger.exception("Failed to store room.")
if event.type == EventTypes.Member:
if event.membership == Membership.JOIN:
# Only fire user_joined_room if the user has acutally
# joined the room. Don't bother if the user is just
# changing their profile info.
newly_joined = True
prev_state_ids = yield context.get_prev_state_ids(self.store)
prev_state_id = prev_state_ids.get((event.type, event.state_key))
if prev_state_id:
prev_state = yield self.store.get_event(
prev_state_id, allow_none=True
)
if prev_state and prev_state.membership == Membership.JOIN:
newly_joined = False
if newly_joined:
user = UserID.from_string(event.state_key)
yield self.user_joined_room(user, room_id)
@log_function
@defer.inlineCallbacks
def backfill(self, dest, room_id, limit, extremities):
""" Trigger a backfill request to `dest` for the given `room_id`
This will attempt to get more events from the remote. If the other side
has no new events to offer, this will return an empty list.
As the events are received, we check their signatures, and also do some
sanity-checking on them. If any of the backfilled events are invalid,
this method throws a SynapseError.
TODO: make this more useful to distinguish failures of the remote
server from invalid events (there is probably no point in trying to
re-fetch invalid events from every other HS in the room.)
"""
if dest == self.server_name:
raise SynapseError(400, "Can't backfill from self.")
room_version = yield self.store.get_room_version(room_id)
events = yield self.federation_client.backfill(
dest, room_id, limit=limit, extremities=extremities
)
# ideally we'd sanity check the events here for excess prev_events etc,
# but it's hard to reject events at this point without completely
# breaking backfill in the same way that it is currently broken by
# events whose signature we cannot verify (#3121).
#
# So for now we accept the events anyway. #3124 tracks this.
#
# for ev in events:
# self._sanity_check_event(ev)
# Don't bother processing events we already have.
seen_events = yield self.store.have_events_in_timeline(
set(e.event_id for e in events)
)
events = [e for e in events if e.event_id not in seen_events]
if not events:
return []
event_map = {e.event_id: e for e in events}
event_ids = set(e.event_id for e in events)
edges = [ev.event_id for ev in events if set(ev.prev_event_ids()) - event_ids]
logger.info("backfill: Got %d events with %d edges", len(events), len(edges))
# For each edge get the current state.
auth_events = {}
state_events = {}
events_to_state = {}
for e_id in edges:
state, auth = yield self.federation_client.get_state_for_room(
destination=dest, room_id=room_id, event_id=e_id
)
auth_events.update({a.event_id: a for a in auth})
auth_events.update({s.event_id: s for s in state})
state_events.update({s.event_id: s for s in state})
events_to_state[e_id] = state
required_auth = set(
a_id
for event in events
+ list(state_events.values())
+ list(auth_events.values())
for a_id in event.auth_event_ids()
)
auth_events.update(
{e_id: event_map[e_id] for e_id in required_auth if e_id in event_map}
)
missing_auth = required_auth - set(auth_events)
failed_to_fetch = set()
# Try and fetch any missing auth events from both DB and remote servers.
# We repeatedly do this until we stop finding new auth events.
while missing_auth - failed_to_fetch:
logger.info("Missing auth for backfill: %r", missing_auth)
ret_events = yield self.store.get_events(missing_auth - failed_to_fetch)
auth_events.update(ret_events)
required_auth.update(
a_id for event in ret_events.values() for a_id in event.auth_event_ids()
)
missing_auth = required_auth - set(auth_events)
if missing_auth - failed_to_fetch:
logger.info(
"Fetching missing auth for backfill: %r",
missing_auth - failed_to_fetch,
)
results = yield make_deferred_yieldable(
defer.gatherResults(
[
run_in_background(
self.federation_client.get_pdu,
[dest],
event_id,
room_version=room_version,
outlier=True,
timeout=10000,
)
for event_id in missing_auth - failed_to_fetch
],
consumeErrors=True,
)
).addErrback(unwrapFirstError)
auth_events.update({a.event_id: a for a in results if a})
required_auth.update(
a_id
for event in results
if event
for a_id in event.auth_event_ids()
)
missing_auth = required_auth - set(auth_events)
failed_to_fetch = missing_auth - set(auth_events)
seen_events = yield self.store.have_seen_events(
set(auth_events.keys()) | set(state_events.keys())
)
# We now have a chunk of events plus associated state and auth chain to
# persist. We do the persistence in two steps:
# 1. Auth events and state get persisted as outliers, plus the
# backward extremities get persisted (as non-outliers).
# 2. The rest of the events in the chunk get persisted one by one, as
# each one depends on the previous event for its state.
#
# The important thing is that events in the chunk get persisted as
# non-outliers, including when those events are also in the state or
# auth chain. Caution must therefore be taken to ensure that they are
# not accidentally marked as outliers.
# Step 1a: persist auth events that *don't* appear in the chunk
ev_infos = []
for a in auth_events.values():
# We only want to persist auth events as outliers that we haven't
# seen and aren't about to persist as part of the backfilled chunk.
if a.event_id in seen_events or a.event_id in event_map:
continue
a.internal_metadata.outlier = True
ev_infos.append(
{
"event": a,
"auth_events": {
(
auth_events[a_id].type,
auth_events[a_id].state_key,
): auth_events[a_id]
for a_id in a.auth_event_ids()
if a_id in auth_events
},
}
)
# Step 1b: persist the events in the chunk we fetched state for (i.e.
# the backwards extremities) as non-outliers.
for e_id in events_to_state:
# For paranoia we ensure that these events are marked as
# non-outliers
ev = event_map[e_id]
assert not ev.internal_metadata.is_outlier()
ev_infos.append(
{
"event": ev,
"state": events_to_state[e_id],
"auth_events": {
(
auth_events[a_id].type,
auth_events[a_id].state_key,
): auth_events[a_id]
for a_id in ev.auth_event_ids()
if a_id in auth_events
},
}
)
yield self._handle_new_events(dest, ev_infos, backfilled=True)
# Step 2: Persist the rest of the events in the chunk one by one
events.sort(key=lambda e: e.depth)
for event in events:
if event in events_to_state:
continue
# For paranoia we ensure that these events are marked as
# non-outliers
assert not event.internal_metadata.is_outlier()
# We store these one at a time since each event depends on the
# previous to work out the state.
# TODO: We can probably do something more clever here.
yield self._handle_new_event(dest, event, backfilled=True)
return events
@defer.inlineCallbacks
def maybe_backfill(self, room_id, current_depth):
"""Checks the database to see if we should backfill before paginating,
and if so do.
"""
extremities = yield self.store.get_oldest_events_with_depth_in_room(room_id)
if not extremities:
logger.debug("Not backfilling as no extremeties found.")
return
# We only want to paginate if we can actually see the events we'll get,
# as otherwise we'll just spend a lot of resources to get redacted
# events.
#
# We do this by filtering all the backwards extremities and seeing if
# any remain. Given we don't have the extremity events themselves, we
# need to actually check the events that reference them.
#
# *Note*: the spec wants us to keep backfilling until we reach the start
# of the room in case we are allowed to see some of the history. However
# in practice that causes more issues than its worth, as a) its
# relatively rare for there to be any visible history and b) even when
# there is its often sufficiently long ago that clients would stop
# attempting to paginate before backfill reached the visible history.
#
# TODO: If we do do a backfill then we should filter the backwards
# extremities to only include those that point to visible portions of
# history.
#
# TODO: Correctly handle the case where we are allowed to see the
# forward event but not the backward extremity, e.g. in the case of
# initial join of the server where we are allowed to see the join
# event but not anything before it. This would require looking at the
# state *before* the event, ignoring the special casing certain event
# types have.
forward_events = yield self.store.get_successor_events(list(extremities))
extremities_events = yield self.store.get_events(
forward_events, check_redacted=False, get_prev_content=False
)
# We set `check_history_visibility_only` as we might otherwise get false
# positives from users having been erased.
filtered_extremities = yield filter_events_for_server(
self.store,
self.server_name,
list(extremities_events.values()),
redact=False,
check_history_visibility_only=True,
)
if not filtered_extremities:
return False
# Check if we reached a point where we should start backfilling.
sorted_extremeties_tuple = sorted(extremities.items(), key=lambda e: -int(e[1]))
max_depth = sorted_extremeties_tuple[0][1]
# We don't want to specify too many extremities as it causes the backfill
# request URI to be too long.
extremities = dict(sorted_extremeties_tuple[:5])
if current_depth > max_depth:
logger.debug(
"Not backfilling as we don't need to. %d < %d", max_depth, current_depth
)
return
# Now we need to decide which hosts to hit first.
# First we try hosts that are already in the room
# TODO: HEURISTIC ALERT.
curr_state = yield self.state_handler.get_current_state(room_id)
def get_domains_from_state(state):
"""Get joined domains from state
Args:
state (dict[tuple, FrozenEvent]): State map from type/state
key to event.
Returns:
list[tuple[str, int]]: Returns a list of servers with the
lowest depth of their joins. Sorted by lowest depth first.
"""
joined_users = [
(state_key, int(event.depth))
for (e_type, state_key), event in iteritems(state)
if e_type == EventTypes.Member and event.membership == Membership.JOIN
]
joined_domains = {}
for u, d in joined_users:
try:
dom = get_domain_from_id(u)
old_d = joined_domains.get(dom)
if old_d:
joined_domains[dom] = min(d, old_d)
else:
joined_domains[dom] = d
except Exception:
pass
return sorted(joined_domains.items(), key=lambda d: d[1])
curr_domains = get_domains_from_state(curr_state)
likely_domains = [
domain for domain, depth in curr_domains if domain != self.server_name
]
@defer.inlineCallbacks
def try_backfill(domains):
# TODO: Should we try multiple of these at a time?
for dom in domains:
try:
yield self.backfill(
dom, room_id, limit=100, extremities=extremities
)
# If this succeeded then we probably already have the
# appropriate stuff.
# TODO: We can probably do something more intelligent here.
return True
except SynapseError as e:
logger.info("Failed to backfill from %s because %s", dom, e)
continue
except CodeMessageException as e:
if 400 <= e.code < 500:
raise
logger.info("Failed to backfill from %s because %s", dom, e)
continue
except NotRetryingDestination as e:
logger.info(str(e))
continue
except RequestSendFailed as e:
logger.info("Falied to get backfill from %s because %s", dom, e)
continue
except FederationDeniedError as e:
logger.info(e)
continue
except Exception as e:
logger.exception("Failed to backfill from %s because %s", dom, e)
continue
return False
success = yield try_backfill(likely_domains)
if success:
return True
# Huh, well *those* domains didn't work out. Lets try some domains
# from the time.
tried_domains = set(likely_domains)
tried_domains.add(self.server_name)
event_ids = list(extremities.keys())
logger.debug("calling resolve_state_groups in _maybe_backfill")
resolve = preserve_fn(self.state_handler.resolve_state_groups_for_events)
states = yield make_deferred_yieldable(
defer.gatherResults(
[resolve(room_id, [e]) for e in event_ids], consumeErrors=True
)
)
# dict[str, dict[tuple, str]], a map from event_id to state map of
# event_ids.
states = dict(zip(event_ids, [s.state for s in states]))
state_map = yield self.store.get_events(
[e_id for ids in itervalues(states) for e_id in itervalues(ids)],
get_prev_content=False,
)
states = {
key: {
k: state_map[e_id]
for k, e_id in iteritems(state_dict)
if e_id in state_map
}
for key, state_dict in iteritems(states)
}
for e_id, _ in sorted_extremeties_tuple:
likely_domains = get_domains_from_state(states[e_id])
success = yield try_backfill(
[dom for dom, _ in likely_domains if dom not in tried_domains]
)
if success:
return True
tried_domains.update(dom for dom, _ in likely_domains)
return False
def _sanity_check_event(self, ev):
"""
Do some early sanity checks of a received event
In particular, checks it doesn't have an excessive number of
prev_events or auth_events, which could cause a huge state resolution
or cascade of event fetches.
Args:
ev (synapse.events.EventBase): event to be checked
Returns: None
Raises:
SynapseError if the event does not pass muster
"""
if len(ev.prev_event_ids()) > 20:
logger.warn(
"Rejecting event %s which has %i prev_events",
ev.event_id,
len(ev.prev_event_ids()),
)
raise SynapseError(http_client.BAD_REQUEST, "Too many prev_events")
if len(ev.auth_event_ids()) > 10:
logger.warn(
"Rejecting event %s which has %i auth_events",
ev.event_id,
len(ev.auth_event_ids()),
)
raise SynapseError(http_client.BAD_REQUEST, "Too many auth_events")
@defer.inlineCallbacks
def send_invite(self, target_host, event):
""" Sends the invite to the remote server for signing.
Invites must be signed by the invitee's server before distribution.
"""
pdu = yield self.federation_client.send_invite(
destination=target_host,
room_id=event.room_id,
event_id=event.event_id,
pdu=event,
)
return pdu
@defer.inlineCallbacks
def on_event_auth(self, event_id):
event = yield self.store.get_event(event_id)
auth = yield self.store.get_auth_chain(
[auth_id for auth_id in event.auth_event_ids()], include_given=True
)
return [e for e in auth]
@log_function
@defer.inlineCallbacks
def do_invite_join(self, target_hosts, room_id, joinee, content):
""" Attempts to join the `joinee` to the room `room_id` via the
server `target_host`.
This first triggers a /make_join/ request that returns a partial
event that we can fill out and sign. This is then sent to the
remote server via /send_join/ which responds with the state at that
event and the auth_chains.
We suspend processing of any received events from this room until we
have finished processing the join.
"""
logger.debug("Joining %s to %s", joinee, room_id)
origin, event, event_format_version = yield self._make_and_verify_event(
target_hosts,
room_id,
joinee,
"join",
content,
params={"ver": KNOWN_ROOM_VERSIONS},
)
# This shouldn't happen, because the RoomMemberHandler has a
# linearizer lock which only allows one operation per user per room
# at a time - so this is just paranoia.
assert room_id not in self.room_queues
self.room_queues[room_id] = []
yield self._clean_room_for_join(room_id)
handled_events = set()
try:
# Try the host we successfully got a response to /make_join/
# request first.
try:
target_hosts.remove(origin)
target_hosts.insert(0, origin)
except ValueError:
pass
ret = yield self.federation_client.send_join(
target_hosts, event, event_format_version
)
origin = ret["origin"]
state = ret["state"]
auth_chain = ret["auth_chain"]
auth_chain.sort(key=lambda e: e.depth)
handled_events.update([s.event_id for s in state])
handled_events.update([a.event_id for a in auth_chain])
handled_events.add(event.event_id)
logger.debug("do_invite_join auth_chain: %s", auth_chain)
logger.debug("do_invite_join state: %s", state)
logger.debug("do_invite_join event: %s", event)
try:
yield self.store.store_room(
room_id=room_id, room_creator_user_id="", is_public=False
)
except Exception:
# FIXME
pass
yield self._persist_auth_tree(origin, auth_chain, state, event)
logger.debug("Finished joining %s to %s", joinee, room_id)
finally:
room_queue = self.room_queues[room_id]
del self.room_queues[room_id]
# we don't need to wait for the queued events to be processed -
# it's just a best-effort thing at this point. We do want to do
# them roughly in order, though, otherwise we'll end up making
# lots of requests for missing prev_events which we do actually
# have. Hence we fire off the deferred, but don't wait for it.
run_in_background(self._handle_queued_pdus, room_queue)
return True
@defer.inlineCallbacks
def _handle_queued_pdus(self, room_queue):
"""Process PDUs which got queued up while we were busy send_joining.
Args:
room_queue (list[FrozenEvent, str]): list of PDUs to be processed
and the servers that sent them
"""
for p, origin in room_queue:
try:
logger.info(
"Processing queued PDU %s which was received "
"while we were joining %s",
p.event_id,
p.room_id,
)
with nested_logging_context(p.event_id):
yield self.on_receive_pdu(origin, p, sent_to_us_directly=True)
except Exception as e:
logger.warn(
"Error handling queued PDU %s from %s: %s", p.event_id, origin, e
)
@defer.inlineCallbacks
@log_function
def on_make_join_request(self, origin, room_id, user_id):
""" We've received a /make_join/ request, so we create a partial
join event for the room and return that. We do *not* persist or
process it until the other server has signed it and sent it back.
Args:
origin (str): The (verified) server name of the requesting server.
room_id (str): Room to create join event in
user_id (str): The user to create the join for
Returns:
Deferred[FrozenEvent]
"""
if get_domain_from_id(user_id) != origin:
logger.info(
"Got /make_join request for user %r from different origin %s, ignoring",
user_id,
origin,
)
raise SynapseError(403, "User not from origin", Codes.FORBIDDEN)
event_content = {"membership": Membership.JOIN}
room_version = yield self.store.get_room_version(room_id)
builder = self.event_builder_factory.new(
room_version,
{
"type": EventTypes.Member,
"content": event_content,
"room_id": room_id,
"sender": user_id,
"state_key": user_id,
},
)
try:
event, context = yield self.event_creation_handler.create_new_client_event(
builder=builder
)
except AuthError as e:
logger.warn("Failed to create join %r because %s", event, e)
raise e
event_allowed = yield self.third_party_event_rules.check_event_allowed(
event, context
)
if not event_allowed:
logger.info("Creation of join %s forbidden by third-party rules", event)
raise SynapseError(
403, "This event is not allowed in this context", Codes.FORBIDDEN
)
# The remote hasn't signed it yet, obviously. We'll do the full checks
# when we get the event back in `on_send_join_request`
yield self.auth.check_from_context(
room_version, event, context, do_sig_check=False
)
return event
@defer.inlineCallbacks
@log_function
def on_send_join_request(self, origin, pdu):
""" We have received a join event for a room. Fully process it and
respond with the current state and auth chains.
"""
event = pdu
logger.debug(
"on_send_join_request: Got event: %s, signatures: %s",
event.event_id,
event.signatures,
)
event.internal_metadata.outlier = False
# Send this event on behalf of the origin server.
#
# The reasons we have the destination server rather than the origin
# server send it are slightly mysterious: the origin server should have
# all the neccessary state once it gets the response to the send_join,
# so it could send the event itself if it wanted to. It may be that
# doing it this way reduces failure modes, or avoids certain attacks
# where a new server selectively tells a subset of the federation that
# it has joined.
#
# The fact is that, as of the current writing, Synapse doesn't send out
# the join event over federation after joining, and changing it now
# would introduce the danger of backwards-compatibility problems.
event.internal_metadata.send_on_behalf_of = origin
context = yield self._handle_new_event(origin, event)
event_allowed = yield self.third_party_event_rules.check_event_allowed(
event, context
)
if not event_allowed:
logger.info("Sending of join %s forbidden by third-party rules", event)
raise SynapseError(
403, "This event is not allowed in this context", Codes.FORBIDDEN
)
logger.debug(
"on_send_join_request: After _handle_new_event: %s, sigs: %s",
event.event_id,
event.signatures,
)
if event.type == EventTypes.Member:
if event.content["membership"] == Membership.JOIN:
user = UserID.from_string(event.state_key)
yield self.user_joined_room(user, event.room_id)
prev_state_ids = yield context.get_prev_state_ids(self.store)
state_ids = list(prev_state_ids.values())
auth_chain = yield self.store.get_auth_chain(state_ids)
state = yield self.store.get_events(list(prev_state_ids.values()))
return {"state": list(state.values()), "auth_chain": auth_chain}
@defer.inlineCallbacks
def on_invite_request(self, origin, pdu):
""" We've got an invite event. Process and persist it. Sign it.
Respond with the now signed event.
"""
event = pdu
if event.state_key is None:
raise SynapseError(400, "The invite event did not have a state key")
is_blocked = yield self.store.is_room_blocked(event.room_id)
if is_blocked:
raise SynapseError(403, "This room has been blocked on this server")
if self.hs.config.block_non_admin_invites:
raise SynapseError(403, "This server does not accept room invites")
if not self.spam_checker.user_may_invite(
event.sender, event.state_key, event.room_id
):
raise SynapseError(
403, "This user is not permitted to send invites to this server/user"
)
membership = event.content.get("membership")
if event.type != EventTypes.Member or membership != Membership.INVITE:
raise SynapseError(400, "The event was not an m.room.member invite event")
sender_domain = get_domain_from_id(event.sender)
if sender_domain != origin:
raise SynapseError(
400, "The invite event was not from the server sending it"
)
if not self.is_mine_id(event.state_key):
raise SynapseError(400, "The invite event must be for this server")
# block any attempts to invite the server notices mxid
if event.state_key == self._server_notices_mxid:
raise SynapseError(http_client.FORBIDDEN, "Cannot invite this user")
event.internal_metadata.outlier = True
event.internal_metadata.out_of_band_membership = True
event.signatures.update(
compute_event_signature(
event.get_pdu_json(), self.hs.hostname, self.hs.config.signing_key[0]
)
)
context = yield self.state_handler.compute_event_context(event)
yield self.persist_events_and_notify([(event, context)])
return event
@defer.inlineCallbacks
def do_remotely_reject_invite(self, target_hosts, room_id, user_id):
origin, event, event_format_version = yield self._make_and_verify_event(
target_hosts, room_id, user_id, "leave"
)
# Mark as outlier as we don't have any state for this event; we're not
# even in the room.
event.internal_metadata.outlier = True
event.internal_metadata.out_of_band_membership = True
# Try the host that we succesfully called /make_leave/ on first for
# the /send_leave/ request.
try:
target_hosts.remove(origin)
target_hosts.insert(0, origin)
except ValueError:
pass
yield self.federation_client.send_leave(target_hosts, event)
context = yield self.state_handler.compute_event_context(event)
yield self.persist_events_and_notify([(event, context)])
return event
@defer.inlineCallbacks
def _make_and_verify_event(
self, target_hosts, room_id, user_id, membership, content={}, params=None
):
origin, event, format_ver = yield self.federation_client.make_membership_event(
target_hosts, room_id, user_id, membership, content, params=params
)
logger.debug("Got response to make_%s: %s", membership, event)
# We should assert some things.
# FIXME: Do this in a nicer way
assert event.type == EventTypes.Member
assert event.user_id == user_id
assert event.state_key == user_id
assert event.room_id == room_id
return origin, event, format_ver
@defer.inlineCallbacks
@log_function
def on_make_leave_request(self, origin, room_id, user_id):
""" We've received a /make_leave/ request, so we create a partial
leave event for the room and return that. We do *not* persist or
process it until the other server has signed it and sent it back.
Args:
origin (str): The (verified) server name of the requesting server.
room_id (str): Room to create leave event in
user_id (str): The user to create the leave for
Returns:
Deferred[FrozenEvent]
"""
if get_domain_from_id(user_id) != origin:
logger.info(
"Got /make_leave request for user %r from different origin %s, ignoring",
user_id,
origin,
)
raise SynapseError(403, "User not from origin", Codes.FORBIDDEN)
room_version = yield self.store.get_room_version(room_id)
builder = self.event_builder_factory.new(
room_version,
{
"type": EventTypes.Member,
"content": {"membership": Membership.LEAVE},
"room_id": room_id,
"sender": user_id,
"state_key": user_id,
},
)
event, context = yield self.event_creation_handler.create_new_client_event(
builder=builder
)
event_allowed = yield self.third_party_event_rules.check_event_allowed(
event, context
)
if not event_allowed:
logger.warning("Creation of leave %s forbidden by third-party rules", event)
raise SynapseError(
403, "This event is not allowed in this context", Codes.FORBIDDEN
)
try:
# The remote hasn't signed it yet, obviously. We'll do the full checks
# when we get the event back in `on_send_leave_request`
yield self.auth.check_from_context(
room_version, event, context, do_sig_check=False
)
except AuthError as e:
logger.warn("Failed to create new leave %r because %s", event, e)
raise e
return event
@defer.inlineCallbacks
@log_function
def on_send_leave_request(self, origin, pdu):
""" We have received a leave event for a room. Fully process it."""
event = pdu
logger.debug(
"on_send_leave_request: Got event: %s, signatures: %s",
event.event_id,
event.signatures,
)
event.internal_metadata.outlier = False
context = yield self._handle_new_event(origin, event)
event_allowed = yield self.third_party_event_rules.check_event_allowed(
event, context
)
if not event_allowed:
logger.info("Sending of leave %s forbidden by third-party rules", event)
raise SynapseError(
403, "This event is not allowed in this context", Codes.FORBIDDEN
)
logger.debug(
"on_send_leave_request: After _handle_new_event: %s, sigs: %s",
event.event_id,
event.signatures,
)
return None
@defer.inlineCallbacks
def get_state_for_pdu(self, room_id, event_id):
"""Returns the state at the event. i.e. not including said event.
"""
event = yield self.store.get_event(
event_id, allow_none=False, check_room_id=room_id
)
state_groups = yield self.store.get_state_groups(room_id, [event_id])
if state_groups:
_, state = list(iteritems(state_groups)).pop()
results = {(e.type, e.state_key): e for e in state}
if event.is_state():
# Get previous state
if "replaces_state" in event.unsigned:
prev_id = event.unsigned["replaces_state"]
if prev_id != event.event_id:
prev_event = yield self.store.get_event(prev_id)
results[(event.type, event.state_key)] = prev_event
else:
del results[(event.type, event.state_key)]
res = list(results.values())
return res
else:
return []
@defer.inlineCallbacks
def get_state_ids_for_pdu(self, room_id, event_id):
"""Returns the state at the event. i.e. not including said event.
"""
event = yield self.store.get_event(
event_id, allow_none=False, check_room_id=room_id
)
state_groups = yield self.store.get_state_groups_ids(room_id, [event_id])
if state_groups:
_, state = list(state_groups.items()).pop()
results = state
if event.is_state():
# Get previous state
if "replaces_state" in event.unsigned:
prev_id = event.unsigned["replaces_state"]
if prev_id != event.event_id:
results[(event.type, event.state_key)] = prev_id
else:
results.pop((event.type, event.state_key), None)
return list(results.values())
else:
return []
@defer.inlineCallbacks
@log_function
def on_backfill_request(self, origin, room_id, pdu_list, limit):
in_room = yield self.auth.check_host_in_room(room_id, origin)
if not in_room:
raise AuthError(403, "Host not in room.")
events = yield self.store.get_backfill_events(room_id, pdu_list, limit)
events = yield filter_events_for_server(self.store, origin, events)
return events
@defer.inlineCallbacks
@log_function
def get_persisted_pdu(self, origin, event_id):
"""Get an event from the database for the given server.
Args:
origin [str]: hostname of server which is requesting the event; we
will check that the server is allowed to see it.
event_id [str]: id of the event being requested
Returns:
Deferred[EventBase|None]: None if we know nothing about the event;
otherwise the (possibly-redacted) event.
Raises:
AuthError if the server is not currently in the room
"""
event = yield self.store.get_event(
event_id, allow_none=True, allow_rejected=True
)
if event:
in_room = yield self.auth.check_host_in_room(event.room_id, origin)
if not in_room:
raise AuthError(403, "Host not in room.")
events = yield filter_events_for_server(self.store, origin, [event])
event = events[0]
return event
else:
return None
def get_min_depth_for_context(self, context):
return self.store.get_min_depth(context)
@defer.inlineCallbacks
def _handle_new_event(
self, origin, event, state=None, auth_events=None, backfilled=False
):
context = yield self._prep_event(
origin, event, state=state, auth_events=auth_events, backfilled=backfilled
)
# reraise does not allow inlineCallbacks to preserve the stacktrace, so we
# hack around with a try/finally instead.
success = False
try:
if not event.internal_metadata.is_outlier() and not backfilled:
yield self.action_generator.handle_push_actions_for_event(
event, context
)
yield self.persist_events_and_notify(
[(event, context)], backfilled=backfilled
)
success = True
finally:
if not success:
run_in_background(
self.store.remove_push_actions_from_staging, event.event_id
)
return context
@defer.inlineCallbacks
def _handle_new_events(self, origin, event_infos, backfilled=False):
"""Creates the appropriate contexts and persists events. The events
should not depend on one another, e.g. this should be used to persist
a bunch of outliers, but not a chunk of individual events that depend
on each other for state calculations.
Notifies about the events where appropriate.
"""
@defer.inlineCallbacks
def prep(ev_info):
event = ev_info["event"]
with nested_logging_context(suffix=event.event_id):
res = yield self._prep_event(
origin,
event,
state=ev_info.get("state"),
auth_events=ev_info.get("auth_events"),
backfilled=backfilled,
)
return res
contexts = yield make_deferred_yieldable(
defer.gatherResults(
[run_in_background(prep, ev_info) for ev_info in event_infos],
consumeErrors=True,
)
)
yield self.persist_events_and_notify(
[
(ev_info["event"], context)
for ev_info, context in zip(event_infos, contexts)
],
backfilled=backfilled,
)
@defer.inlineCallbacks
def _persist_auth_tree(self, origin, auth_events, state, event):
"""Checks the auth chain is valid (and passes auth checks) for the
state and event. Then persists the auth chain and state atomically.
Persists the event separately. Notifies about the persisted events
where appropriate.
Will attempt to fetch missing auth events.
Args:
origin (str): Where the events came from
auth_events (list)
state (list)
event (Event)
Returns:
Deferred
"""
events_to_context = {}
for e in itertools.chain(auth_events, state):
e.internal_metadata.outlier = True
ctx = yield self.state_handler.compute_event_context(e)
events_to_context[e.event_id] = ctx
event_map = {
e.event_id: e for e in itertools.chain(auth_events, state, [event])
}
create_event = None
for e in auth_events:
if (e.type, e.state_key) == (EventTypes.Create, ""):
create_event = e
break
if create_event is None:
# If the state doesn't have a create event then the room is
# invalid, and it would fail auth checks anyway.
raise SynapseError(400, "No create event in state")
room_version = create_event.content.get(
"room_version", RoomVersions.V1.identifier
)
missing_auth_events = set()
for e in itertools.chain(auth_events, state, [event]):
for e_id in e.auth_event_ids():
if e_id not in event_map:
missing_auth_events.add(e_id)
for e_id in missing_auth_events:
m_ev = yield self.federation_client.get_pdu(
[origin], e_id, room_version=room_version, outlier=True, timeout=10000
)
if m_ev and m_ev.event_id == e_id:
event_map[e_id] = m_ev
else:
logger.info("Failed to find auth event %r", e_id)
for e in itertools.chain(auth_events, state, [event]):
auth_for_e = {
(event_map[e_id].type, event_map[e_id].state_key): event_map[e_id]
for e_id in e.auth_event_ids()
if e_id in event_map
}
if create_event:
auth_for_e[(EventTypes.Create, "")] = create_event
try:
self.auth.check(room_version, e, auth_events=auth_for_e)
except SynapseError as err:
# we may get SynapseErrors here as well as AuthErrors. For
# instance, there are a couple of (ancient) events in some
# rooms whose senders do not have the correct sigil; these
# cause SynapseErrors in auth.check. We don't want to give up
# the attempt to federate altogether in such cases.
logger.warn("Rejecting %s because %s", e.event_id, err.msg)
if e == event:
raise
events_to_context[e.event_id].rejected = RejectedReason.AUTH_ERROR
yield self.persist_events_and_notify(
[
(e, events_to_context[e.event_id])
for e in itertools.chain(auth_events, state)
]
)
new_event_context = yield self.state_handler.compute_event_context(
event, old_state=state
)
yield self.persist_events_and_notify([(event, new_event_context)])
@defer.inlineCallbacks
def _prep_event(self, origin, event, state, auth_events, backfilled):
"""
Args:
origin:
event:
state:
auth_events:
backfilled (bool)
Returns:
Deferred, which resolves to synapse.events.snapshot.EventContext
"""
context = yield self.state_handler.compute_event_context(event, old_state=state)
if not auth_events:
prev_state_ids = yield context.get_prev_state_ids(self.store)
auth_events_ids = yield self.auth.compute_auth_events(
event, prev_state_ids, for_verification=True
)
auth_events = yield self.store.get_events(auth_events_ids)
auth_events = {(e.type, e.state_key): e for e in auth_events.values()}
# This is a hack to fix some old rooms where the initial join event
# didn't reference the create event in its auth events.
if event.type == EventTypes.Member and not event.auth_event_ids():
if len(event.prev_event_ids()) == 1 and event.depth < 5:
c = yield self.store.get_event(
event.prev_event_ids()[0], allow_none=True
)
if c and c.type == EventTypes.Create:
auth_events[(c.type, c.state_key)] = c
try:
yield self.do_auth(origin, event, context, auth_events=auth_events)
except AuthError as e:
logger.warn("[%s %s] Rejecting: %s", event.room_id, event.event_id, e.msg)
context.rejected = RejectedReason.AUTH_ERROR
if not context.rejected:
yield self._check_for_soft_fail(event, state, backfilled)
if event.type == EventTypes.GuestAccess and not context.rejected:
yield self.maybe_kick_guest_users(event)
return context
@defer.inlineCallbacks
def _check_for_soft_fail(self, event, state, backfilled):
"""Checks if we should soft fail the event, if so marks the event as
such.
Args:
event (FrozenEvent)
state (dict|None): The state at the event if we don't have all the
event's prev events
backfilled (bool): Whether the event is from backfill
Returns:
Deferred
"""
# For new (non-backfilled and non-outlier) events we check if the event
# passes auth based on the current state. If it doesn't then we
# "soft-fail" the event.
do_soft_fail_check = not backfilled and not event.internal_metadata.is_outlier()
if do_soft_fail_check:
extrem_ids = yield self.store.get_latest_event_ids_in_room(event.room_id)
extrem_ids = set(extrem_ids)
prev_event_ids = set(event.prev_event_ids())
if extrem_ids == prev_event_ids:
# If they're the same then the current state is the same as the
# state at the event, so no point rechecking auth for soft fail.
do_soft_fail_check = False
if do_soft_fail_check:
room_version = yield self.store.get_room_version(event.room_id)
# Calculate the "current state".
if state is not None:
# If we're explicitly given the state then we won't have all the
# prev events, and so we have a gap in the graph. In this case
# we want to be a little careful as we might have been down for
# a while and have an incorrect view of the current state,
# however we still want to do checks as gaps are easy to
# maliciously manufacture.
#
# So we use a "current state" that is actually a state
# resolution across the current forward extremities and the
# given state at the event. This should correctly handle cases
# like bans, especially with state res v2.
state_sets = yield self.store.get_state_groups(
event.room_id, extrem_ids
)
state_sets = list(state_sets.values())
state_sets.append(state)
current_state_ids = yield self.state_handler.resolve_events(
room_version, state_sets, event
)
current_state_ids = {
k: e.event_id for k, e in iteritems(current_state_ids)
}
else:
current_state_ids = yield self.state_handler.get_current_state_ids(
event.room_id, latest_event_ids=extrem_ids
)
logger.debug(
"Doing soft-fail check for %s: state %s",
event.event_id,
current_state_ids,
)
# Now check if event pass auth against said current state
auth_types = auth_types_for_event(event)
current_state_ids = [
e for k, e in iteritems(current_state_ids) if k in auth_types
]
current_auth_events = yield self.store.get_events(current_state_ids)
current_auth_events = {
(e.type, e.state_key): e for e in current_auth_events.values()
}
try:
self.auth.check(room_version, event, auth_events=current_auth_events)
except AuthError as e:
logger.warn("Soft-failing %r because %s", event, e)
event.internal_metadata.soft_failed = True
@defer.inlineCallbacks
def on_query_auth(
self, origin, event_id, room_id, remote_auth_chain, rejects, missing
):
in_room = yield self.auth.check_host_in_room(room_id, origin)
if not in_room:
raise AuthError(403, "Host not in room.")
event = yield self.store.get_event(
event_id, allow_none=False, check_room_id=room_id
)
# Just go through and process each event in `remote_auth_chain`. We
# don't want to fall into the trap of `missing` being wrong.
for e in remote_auth_chain:
try:
yield self._handle_new_event(origin, e)
except AuthError:
pass
# Now get the current auth_chain for the event.
local_auth_chain = yield self.store.get_auth_chain(
[auth_id for auth_id in event.auth_event_ids()], include_given=True
)
# TODO: Check if we would now reject event_id. If so we need to tell
# everyone.
ret = yield self.construct_auth_difference(local_auth_chain, remote_auth_chain)
logger.debug("on_query_auth returning: %s", ret)
return ret
@defer.inlineCallbacks
def on_get_missing_events(
self, origin, room_id, earliest_events, latest_events, limit
):
in_room = yield self.auth.check_host_in_room(room_id, origin)
if not in_room:
raise AuthError(403, "Host not in room.")
limit = min(limit, 20)
missing_events = yield self.store.get_missing_events(
room_id=room_id,
earliest_events=earliest_events,
latest_events=latest_events,
limit=limit,
)
missing_events = yield filter_events_for_server(
self.store, origin, missing_events
)
return missing_events
@defer.inlineCallbacks
@log_function
def do_auth(self, origin, event, context, auth_events):
"""
Args:
origin (str):
event (synapse.events.EventBase):
context (synapse.events.snapshot.EventContext):
auth_events (dict[(str, str)->synapse.events.EventBase]):
Map from (event_type, state_key) to event
What we expect the event's auth_events to be, based on the event's
position in the dag. I think? maybe??
Also NB that this function adds entries to it.
Returns:
defer.Deferred[None]
"""
room_version = yield self.store.get_room_version(event.room_id)
try:
yield self._update_auth_events_and_context_for_auth(
origin, event, context, auth_events
)
except Exception:
# We don't really mind if the above fails, so lets not fail
# processing if it does. However, it really shouldn't fail so
# let's still log as an exception since we'll still want to fix
# any bugs.
logger.exception(
"Failed to double check auth events for %s with remote. "
"Ignoring failure and continuing processing of event.",
event.event_id,
)
try:
self.auth.check(room_version, event, auth_events=auth_events)
except AuthError as e:
logger.warn("Failed auth resolution for %r because %s", event, e)
raise e
@defer.inlineCallbacks
def _update_auth_events_and_context_for_auth(
self, origin, event, context, auth_events
):
"""Helper for do_auth. See there for docs.
Checks whether a given event has the expected auth events. If it
doesn't then we talk to the remote server to compare state to see if
we can come to a consensus (e.g. if one server missed some valid
state).
This attempts to resovle any potential divergence of state between
servers, but is not essential and so failures should not block further
processing of the event.
Args:
origin (str):
event (synapse.events.EventBase):
context (synapse.events.snapshot.EventContext):
auth_events (dict[(str, str)->synapse.events.EventBase]):
Returns:
defer.Deferred[None]
"""
event_auth_events = set(event.auth_event_ids())
if event.is_state():
event_key = (event.type, event.state_key)
else:
event_key = None
# if the event's auth_events refers to events which are not in our
# calculated auth_events, we need to fetch those events from somewhere.
#
# we start by fetching them from the store, and then try calling /event_auth/.
missing_auth = event_auth_events.difference(
e.event_id for e in auth_events.values()
)
if missing_auth:
# TODO: can we use store.have_seen_events here instead?
have_events = yield self.store.get_seen_events_with_rejections(missing_auth)
logger.debug("Got events %s from store", have_events)
missing_auth.difference_update(have_events.keys())
else:
have_events = {}
have_events.update({e.event_id: "" for e in auth_events.values()})
if missing_auth:
# If we don't have all the auth events, we need to get them.
logger.info("auth_events contains unknown events: %s", missing_auth)
try:
try:
remote_auth_chain = yield self.federation_client.get_event_auth(
origin, event.room_id, event.event_id
)
except RequestSendFailed as e:
# The other side isn't around or doesn't implement the
# endpoint, so lets just bail out.
logger.info("Failed to get event auth from remote: %s", e)
return
seen_remotes = yield self.store.have_seen_events(
[e.event_id for e in remote_auth_chain]
)
for e in remote_auth_chain:
if e.event_id in seen_remotes:
continue
if e.event_id == event.event_id:
continue
try:
auth_ids = e.auth_event_ids()
auth = {
(e.type, e.state_key): e
for e in remote_auth_chain
if e.event_id in auth_ids or e.type == EventTypes.Create
}
e.internal_metadata.outlier = True
logger.debug(
"do_auth %s missing_auth: %s", event.event_id, e.event_id
)
yield self._handle_new_event(origin, e, auth_events=auth)
if e.event_id in event_auth_events:
auth_events[(e.type, e.state_key)] = e
except AuthError:
pass
have_events = yield self.store.get_seen_events_with_rejections(
event.auth_event_ids()
)
except Exception:
# FIXME:
logger.exception("Failed to get auth chain")
if event.internal_metadata.is_outlier():
logger.info("Skipping auth_event fetch for outlier")
return
# FIXME: Assumes we have and stored all the state for all the
# prev_events
different_auth = event_auth_events.difference(
e.event_id for e in auth_events.values()
)
if not different_auth:
return
logger.info(
"auth_events refers to events which are not in our calculated auth "
"chain: %s",
different_auth,
)
room_version = yield self.store.get_room_version(event.room_id)
different_events = yield make_deferred_yieldable(
defer.gatherResults(
[
run_in_background(
self.store.get_event, d, allow_none=True, allow_rejected=False
)
for d in different_auth
if d in have_events and not have_events[d]
],
consumeErrors=True,
)
).addErrback(unwrapFirstError)
if different_events:
local_view = dict(auth_events)
remote_view = dict(auth_events)
remote_view.update(
{(d.type, d.state_key): d for d in different_events if d}
)
new_state = yield self.state_handler.resolve_events(
room_version,
[list(local_view.values()), list(remote_view.values())],
event,
)
logger.info(
"After state res: updating auth_events with new state %s",
{
(d.type, d.state_key): d.event_id
for d in new_state.values()
if auth_events.get((d.type, d.state_key)) != d
},
)
auth_events.update(new_state)
different_auth = event_auth_events.difference(
e.event_id for e in auth_events.values()
)
yield self._update_context_for_auth_events(
event, context, auth_events, event_key
)
if not different_auth:
# we're done
return
logger.info(
"auth_events still refers to events which are not in the calculated auth "
"chain after state resolution: %s",
different_auth,
)
# Only do auth resolution if we have something new to say.
# We can't prove an auth failure.
do_resolution = False
for e_id in different_auth:
if e_id in have_events:
if have_events[e_id] == RejectedReason.NOT_ANCESTOR:
do_resolution = True
break
if not do_resolution:
logger.info(
"Skipping auth resolution due to lack of provable rejection reasons"
)
return
logger.info("Doing auth resolution")
prev_state_ids = yield context.get_prev_state_ids(self.store)
# 1. Get what we think is the auth chain.
auth_ids = yield self.auth.compute_auth_events(event, prev_state_ids)
local_auth_chain = yield self.store.get_auth_chain(auth_ids, include_given=True)
try:
# 2. Get remote difference.
try:
result = yield self.federation_client.query_auth(
origin, event.room_id, event.event_id, local_auth_chain
)
except RequestSendFailed as e:
# The other side isn't around or doesn't implement the
# endpoint, so lets just bail out.
logger.info("Failed to query auth from remote: %s", e)
return
seen_remotes = yield self.store.have_seen_events(
[e.event_id for e in result["auth_chain"]]
)
# 3. Process any remote auth chain events we haven't seen.
for ev in result["auth_chain"]:
if ev.event_id in seen_remotes:
continue
if ev.event_id == event.event_id:
continue
try:
auth_ids = ev.auth_event_ids()
auth = {
(e.type, e.state_key): e
for e in result["auth_chain"]
if e.event_id in auth_ids or event.type == EventTypes.Create
}
ev.internal_metadata.outlier = True
logger.debug(
"do_auth %s different_auth: %s", event.event_id, e.event_id
)
yield self._handle_new_event(origin, ev, auth_events=auth)
if ev.event_id in event_auth_events:
auth_events[(ev.type, ev.state_key)] = ev
except AuthError:
pass
except Exception:
# FIXME:
logger.exception("Failed to query auth chain")
# 4. Look at rejects and their proofs.
# TODO.
yield self._update_context_for_auth_events(
event, context, auth_events, event_key
)
@defer.inlineCallbacks
def _update_context_for_auth_events(self, event, context, auth_events, event_key):
"""Update the state_ids in an event context after auth event resolution,
storing the changes as a new state group.
Args:
event (Event): The event we're handling the context for
context (synapse.events.snapshot.EventContext): event context
to be updated
auth_events (dict[(str, str)->str]): Events to update in the event
context.
event_key ((str, str)): (type, state_key) for the current event.
this will not be included in the current_state in the context.
"""
state_updates = {
k: a.event_id for k, a in iteritems(auth_events) if k != event_key
}
current_state_ids = yield context.get_current_state_ids(self.store)
current_state_ids = dict(current_state_ids)
current_state_ids.update(state_updates)
prev_state_ids = yield context.get_prev_state_ids(self.store)
prev_state_ids = dict(prev_state_ids)
prev_state_ids.update({k: a.event_id for k, a in iteritems(auth_events)})
# create a new state group as a delta from the existing one.
prev_group = context.state_group
state_group = yield self.store.store_state_group(
event.event_id,
event.room_id,
prev_group=prev_group,
delta_ids=state_updates,
current_state_ids=current_state_ids,
)
yield context.update_state(
state_group=state_group,
current_state_ids=current_state_ids,
prev_state_ids=prev_state_ids,
prev_group=prev_group,
delta_ids=state_updates,
)
@defer.inlineCallbacks
def construct_auth_difference(self, local_auth, remote_auth):
""" Given a local and remote auth chain, find the differences. This
assumes that we have already processed all events in remote_auth
Params:
local_auth (list)
remote_auth (list)
Returns:
dict
"""
logger.debug("construct_auth_difference Start!")
# TODO: Make sure we are OK with local_auth or remote_auth having more
# auth events in them than strictly necessary.
def sort_fun(ev):
return ev.depth, ev.event_id
logger.debug("construct_auth_difference after sort_fun!")
# We find the differences by starting at the "bottom" of each list
# and iterating up on both lists. The lists are ordered by depth and
# then event_id, we iterate up both lists until we find the event ids
# don't match. Then we look at depth/event_id to see which side is
# missing that event, and iterate only up that list. Repeat.
remote_list = list(remote_auth)
remote_list.sort(key=sort_fun)
local_list = list(local_auth)
local_list.sort(key=sort_fun)
local_iter = iter(local_list)
remote_iter = iter(remote_list)
logger.debug("construct_auth_difference before get_next!")
def get_next(it, opt=None):
try:
return next(it)
except Exception:
return opt
current_local = get_next(local_iter)
current_remote = get_next(remote_iter)
logger.debug("construct_auth_difference before while")
missing_remotes = []
missing_locals = []
while current_local or current_remote:
if current_remote is None:
missing_locals.append(current_local)
current_local = get_next(local_iter)
continue
if current_local is None:
missing_remotes.append(current_remote)
current_remote = get_next(remote_iter)
continue
if current_local.event_id == current_remote.event_id:
current_local = get_next(local_iter)
current_remote = get_next(remote_iter)
continue
if current_local.depth < current_remote.depth:
missing_locals.append(current_local)
current_local = get_next(local_iter)
continue
if current_local.depth > current_remote.depth:
missing_remotes.append(current_remote)
current_remote = get_next(remote_iter)
continue
# They have the same depth, so we fall back to the event_id order
if current_local.event_id < current_remote.event_id:
missing_locals.append(current_local)
current_local = get_next(local_iter)
if current_local.event_id > current_remote.event_id:
missing_remotes.append(current_remote)
current_remote = get_next(remote_iter)
continue
logger.debug("construct_auth_difference after while")
# missing locals should be sent to the server
# We should find why we are missing remotes, as they will have been
# rejected.
# Remove events from missing_remotes if they are referencing a missing
# remote. We only care about the "root" rejected ones.
missing_remote_ids = [e.event_id for e in missing_remotes]
base_remote_rejected = list(missing_remotes)
for e in missing_remotes:
for e_id in e.auth_event_ids():
if e_id in missing_remote_ids:
try:
base_remote_rejected.remove(e)
except ValueError:
pass
reason_map = {}
for e in base_remote_rejected:
reason = yield self.store.get_rejection_reason(e.event_id)
if reason is None:
# TODO: e is not in the current state, so we should
# construct some proof of that.
continue
reason_map[e.event_id] = reason
if reason == RejectedReason.AUTH_ERROR:
pass
elif reason == RejectedReason.REPLACED:
# TODO: Get proof
pass
elif reason == RejectedReason.NOT_ANCESTOR:
# TODO: Get proof.
pass
logger.debug("construct_auth_difference returning")
return {
"auth_chain": local_auth,
"rejects": {
e.event_id: {"reason": reason_map[e.event_id], "proof": None}
for e in base_remote_rejected
},
"missing": [e.event_id for e in missing_locals],
}
@defer.inlineCallbacks
@log_function
def exchange_third_party_invite(
self, sender_user_id, target_user_id, room_id, signed
):
third_party_invite = {"signed": signed}
event_dict = {
"type": EventTypes.Member,
"content": {
"membership": Membership.INVITE,
"third_party_invite": third_party_invite,
},
"room_id": room_id,
"sender": sender_user_id,
"state_key": target_user_id,
}
if (yield self.auth.check_host_in_room(room_id, self.hs.hostname)):
room_version = yield self.store.get_room_version(room_id)
builder = self.event_builder_factory.new(room_version, event_dict)
EventValidator().validate_builder(builder)
event, context = yield self.event_creation_handler.create_new_client_event(
builder=builder
)
event_allowed = yield self.third_party_event_rules.check_event_allowed(
event, context
)
if not event_allowed:
logger.info(
"Creation of threepid invite %s forbidden by third-party rules",
event,
)
raise SynapseError(
403, "This event is not allowed in this context", Codes.FORBIDDEN
)
event, context = yield self.add_display_name_to_third_party_invite(
room_version, event_dict, event, context
)
EventValidator().validate_new(event)
# We need to tell the transaction queue to send this out, even
# though the sender isn't a local user.
event.internal_metadata.send_on_behalf_of = self.hs.hostname
try:
yield self.auth.check_from_context(room_version, event, context)
except AuthError as e:
logger.warn("Denying new third party invite %r because %s", event, e)
raise e
yield self._check_signature(event, context)
member_handler = self.hs.get_room_member_handler()
yield member_handler.send_membership_event(None, event, context)
else:
destinations = set(x.split(":", 1)[-1] for x in (sender_user_id, room_id))
yield self.federation_client.forward_third_party_invite(
destinations, room_id, event_dict
)
@defer.inlineCallbacks
@log_function
def on_exchange_third_party_invite_request(self, room_id, event_dict):
"""Handle an exchange_third_party_invite request from a remote server
The remote server will call this when it wants to turn a 3pid invite
into a normal m.room.member invite.
Args:
room_id (str): The ID of the room.
event_dict (dict[str, Any]): Dictionary containing the event body.
Returns:
Deferred: resolves (to None)
"""
room_version = yield self.store.get_room_version(room_id)
# NB: event_dict has a particular specced format we might need to fudge
# if we change event formats too much.
builder = self.event_builder_factory.new(room_version, event_dict)
event, context = yield self.event_creation_handler.create_new_client_event(
builder=builder
)
event_allowed = yield self.third_party_event_rules.check_event_allowed(
event, context
)
if not event_allowed:
logger.warning(
"Exchange of threepid invite %s forbidden by third-party rules", event
)
raise SynapseError(
403, "This event is not allowed in this context", Codes.FORBIDDEN
)
event, context = yield self.add_display_name_to_third_party_invite(
room_version, event_dict, event, context
)
try:
self.auth.check_from_context(room_version, event, context)
except AuthError as e:
logger.warn("Denying third party invite %r because %s", event, e)
raise e
yield self._check_signature(event, context)
# We need to tell the transaction queue to send this out, even
# though the sender isn't a local user.
event.internal_metadata.send_on_behalf_of = get_domain_from_id(event.sender)
member_handler = self.hs.get_room_member_handler()
yield member_handler.send_membership_event(None, event, context)
@defer.inlineCallbacks
def add_display_name_to_third_party_invite(
self, room_version, event_dict, event, context
):
key = (
EventTypes.ThirdPartyInvite,
event.content["third_party_invite"]["signed"]["token"],
)
original_invite = None
prev_state_ids = yield context.get_prev_state_ids(self.store)
original_invite_id = prev_state_ids.get(key)
if original_invite_id:
original_invite = yield self.store.get_event(
original_invite_id, allow_none=True
)
if original_invite:
display_name = original_invite.content["display_name"]
event_dict["content"]["third_party_invite"]["display_name"] = display_name
else:
logger.info(
"Could not find invite event for third_party_invite: %r", event_dict
)
# We don't discard here as this is not the appropriate place to do
# auth checks. If we need the invite and don't have it then the
# auth check code will explode appropriately.
builder = self.event_builder_factory.new(room_version, event_dict)
EventValidator().validate_builder(builder)
event, context = yield self.event_creation_handler.create_new_client_event(
builder=builder
)
EventValidator().validate_new(event)
return (event, context)
@defer.inlineCallbacks
def _check_signature(self, event, context):
"""
Checks that the signature in the event is consistent with its invite.
Args:
event (Event): The m.room.member event to check
context (EventContext):
Raises:
AuthError: if signature didn't match any keys, or key has been
revoked,
SynapseError: if a transient error meant a key couldn't be checked
for revocation.
"""
signed = event.content["third_party_invite"]["signed"]
token = signed["token"]
prev_state_ids = yield context.get_prev_state_ids(self.store)
invite_event_id = prev_state_ids.get((EventTypes.ThirdPartyInvite, token))
invite_event = None
if invite_event_id:
invite_event = yield self.store.get_event(invite_event_id, allow_none=True)
if not invite_event:
raise AuthError(403, "Could not find invite")
logger.debug("Checking auth on event %r", event.content)
last_exception = None
# for each public key in the 3pid invite event
for public_key_object in self.hs.get_auth().get_public_keys(invite_event):
try:
# for each sig on the third_party_invite block of the actual invite
for server, signature_block in signed["signatures"].items():
for key_name, encoded_signature in signature_block.items():
if not key_name.startswith("ed25519:"):
continue
logger.debug(
"Attempting to verify sig with key %s from %r "
"against pubkey %r",
key_name,
server,
public_key_object,
)
try:
public_key = public_key_object["public_key"]
verify_key = decode_verify_key_bytes(
key_name, decode_base64(public_key)
)
verify_signed_json(signed, server, verify_key)
logger.debug(
"Successfully verified sig with key %s from %r "
"against pubkey %r",
key_name,
server,
public_key_object,
)
except Exception:
logger.info(
"Failed to verify sig with key %s from %r "
"against pubkey %r",
key_name,
server,
public_key_object,
)
raise
try:
if "key_validity_url" in public_key_object:
yield self._check_key_revocation(
public_key, public_key_object["key_validity_url"]
)
except Exception:
logger.info(
"Failed to query key_validity_url %s",
public_key_object["key_validity_url"],
)
raise
return
except Exception as e:
last_exception = e
raise last_exception
@defer.inlineCallbacks
def _check_key_revocation(self, public_key, url):
"""
Checks whether public_key has been revoked.
Args:
public_key (str): base-64 encoded public key.
url (str): Key revocation URL.
Raises:
AuthError: if they key has been revoked.
SynapseError: if a transient error meant a key couldn't be checked
for revocation.
"""
try:
response = yield self.http_client.get_json(url, {"public_key": public_key})
except Exception:
raise SynapseError(502, "Third party certificate could not be checked")
if "valid" not in response or not response["valid"]:
raise AuthError(403, "Third party certificate was invalid")
@defer.inlineCallbacks
def persist_events_and_notify(self, event_and_contexts, backfilled=False):
"""Persists events and tells the notifier/pushers about them, if
necessary.
Args:
event_and_contexts(list[tuple[FrozenEvent, EventContext]])
backfilled (bool): Whether these events are a result of
backfilling or not
Returns:
Deferred
"""
if self.config.worker_app:
yield self._send_events_to_master(
store=self.store,
event_and_contexts=event_and_contexts,
backfilled=backfilled,
)
else:
max_stream_id = yield self.store.persist_events(
event_and_contexts, backfilled=backfilled
)
if not backfilled: # Never notify for backfilled events
for event, _ in event_and_contexts:
yield self._notify_persisted_event(event, max_stream_id)
def _notify_persisted_event(self, event, max_stream_id):
"""Checks to see if notifier/pushers should be notified about the
event or not.
Args:
event (FrozenEvent)
max_stream_id (int): The max_stream_id returned by persist_events
"""
extra_users = []
if event.type == EventTypes.Member:
target_user_id = event.state_key
# We notify for memberships if its an invite for one of our
# users
if event.internal_metadata.is_outlier():
if event.membership != Membership.INVITE:
if not self.is_mine_id(target_user_id):
return
target_user = UserID.from_string(target_user_id)
extra_users.append(target_user)
elif event.internal_metadata.is_outlier():
return
event_stream_id = event.internal_metadata.stream_ordering
self.notifier.on_new_room_event(
event, event_stream_id, max_stream_id, extra_users=extra_users
)
return self.pusher_pool.on_new_notifications(event_stream_id, max_stream_id)
def _clean_room_for_join(self, room_id):
"""Called to clean up any data in DB for a given room, ready for the
server to join the room.
Args:
room_id (str)
"""
if self.config.worker_app:
return self._clean_room_for_join_client(room_id)
else:
return self.store.clean_room_for_join(room_id)
def user_joined_room(self, user, room_id):
"""Called when a new user has joined the room
"""
if self.config.worker_app:
return self._notify_user_membership_change(
room_id=room_id, user_id=user.to_string(), change="joined"
)
else:
return user_joined_room(self.distributor, user, room_id)
@defer.inlineCallbacks
def get_room_complexity(self, remote_room_hosts, room_id):
"""
Fetch the complexity of a remote room over federation.
Args:
remote_room_hosts (list[str]): The remote servers to ask.
room_id (str): The room ID to ask about.
Returns:
Deferred[dict] or Deferred[None]: Dict contains the complexity
metric versions, while None means we could not fetch the complexity.
"""
for host in remote_room_hosts:
res = yield self.federation_client.get_room_complexity(host, room_id)
# We got a result, return it.
if res:
defer.returnValue(res)
# We fell off the bottom, couldn't get the complexity from anyone. Oh
# well.
defer.returnValue(None)
| 38.411225 | 99 | 0.5732 |
import itertools
import logging
import six
from six import iteritems, itervalues
from six.moves import http_client, zip
from signedjson.key import decode_verify_key_bytes
from signedjson.sign import verify_signed_json
from unpaddedbase64 import decode_base64
from twisted.internet import defer
from synapse.api.constants import EventTypes, Membership, RejectedReason
from synapse.api.errors import (
AuthError,
CodeMessageException,
Codes,
FederationDeniedError,
FederationError,
RequestSendFailed,
StoreError,
SynapseError,
)
from synapse.api.room_versions import KNOWN_ROOM_VERSIONS, RoomVersions
from synapse.crypto.event_signing import compute_event_signature
from synapse.event_auth import auth_types_for_event
from synapse.events.validator import EventValidator
from synapse.logging.context import (
make_deferred_yieldable,
nested_logging_context,
preserve_fn,
run_in_background,
)
from synapse.logging.utils import log_function
from synapse.replication.http.federation import (
ReplicationCleanRoomRestServlet,
ReplicationFederationSendEventsRestServlet,
)
from synapse.replication.http.membership import ReplicationUserJoinedLeftRoomRestServlet
from synapse.state import StateResolutionStore, resolve_events_with_store
from synapse.types import UserID, get_domain_from_id
from synapse.util import unwrapFirstError
from synapse.util.async_helpers import Linearizer
from synapse.util.distributor import user_joined_room
from synapse.util.retryutils import NotRetryingDestination
from synapse.visibility import filter_events_for_server
from ._base import BaseHandler
logger = logging.getLogger(__name__)
def shortstr(iterable, maxitems=5):
items = list(itertools.islice(iterable, maxitems + 1))
if len(items) <= maxitems:
return str(items)
return "[" + ", ".join(repr(r) for r in items[:maxitems]) + ", ...]"
class FederationHandler(BaseHandler):
def __init__(self, hs):
super(FederationHandler, self).__init__(hs)
self.hs = hs
self.store = hs.get_datastore()
self.federation_client = hs.get_federation_client()
self.state_handler = hs.get_state_handler()
self.server_name = hs.hostname
self.keyring = hs.get_keyring()
self.action_generator = hs.get_action_generator()
self.is_mine_id = hs.is_mine_id
self.pusher_pool = hs.get_pusherpool()
self.spam_checker = hs.get_spam_checker()
self.event_creation_handler = hs.get_event_creation_handler()
self._server_notices_mxid = hs.config.server_notices_mxid
self.config = hs.config
self.http_client = hs.get_simple_http_client()
self._send_events_to_master = ReplicationFederationSendEventsRestServlet.make_client(
hs
)
self._notify_user_membership_change = ReplicationUserJoinedLeftRoomRestServlet.make_client(
hs
)
self._clean_room_for_join_client = ReplicationCleanRoomRestServlet.make_client(
hs
)
self.room_queues = {}
self._room_pdu_linearizer = Linearizer("fed_room_pdu")
self.third_party_event_rules = hs.get_third_party_event_rules()
@defer.inlineCallbacks
def on_receive_pdu(self, origin, pdu, sent_to_us_directly=False):
room_id = pdu.room_id
event_id = pdu.event_id
logger.info("[%s %s] handling received PDU: %s", room_id, event_id, pdu)
existing = yield self.store.get_event(
event_id, allow_none=True, allow_rejected=True
)
already_seen = existing and (
not existing.internal_metadata.is_outlier()
or pdu.internal_metadata.is_outlier()
)
if already_seen:
logger.debug("[%s %s]: Already seen pdu", room_id, event_id)
return
# could cause a huge state resolution or cascade of event fetches.
try:
self._sanity_check_event(pdu)
except SynapseError as err:
logger.warn(
"[%s %s] Received event failed sanity checks", room_id, event_id
)
raise FederationError("ERROR", err.code, err.msg, affected=pdu.event_id)
# If we are currently in the process of joining this room, then we
# queue up events for later processing.
if room_id in self.room_queues:
logger.info(
"[%s %s] Queuing PDU from %s for now: join in progress",
room_id,
event_id,
origin,
)
self.room_queues[room_id].append((pdu, origin))
return
# If we're not in the room just ditch the event entirely. This is
# the room (or we've been rejoined to the room by a state reset).
is_in_room = yield self.auth.check_host_in_room(room_id, self.server_name)
if not is_in_room:
logger.info(
"[%s %s] Ignoring PDU from %s as we're not in the room",
room_id,
event_id,
origin,
)
return None
state = None
auth_chain = []
if not pdu.internal_metadata.is_outlier():
min_depth = yield self.get_min_depth_for_context(pdu.room_id)
logger.debug("[%s %s] min_depth: %d", room_id, event_id, min_depth)
prevs = set(pdu.prev_event_ids())
seen = yield self.store.have_seen_events(prevs)
if min_depth and pdu.depth < min_depth:
# message, to work around the fact that some events will
# reference really really old events we really don't want to
pdu.internal_metadata.outlier = True
elif min_depth and pdu.depth > min_depth:
missing_prevs = prevs - seen
if sent_to_us_directly and missing_prevs:
# at a time.
logger.info(
"[%s %s] Acquiring room lock to fetch %d missing prev_events: %s",
room_id,
event_id,
len(missing_prevs),
shortstr(missing_prevs),
)
with (yield self._room_pdu_linearizer.queue(pdu.room_id)):
logger.info(
"[%s %s] Acquired room lock to fetch %d missing prev_events",
room_id,
event_id,
len(missing_prevs),
)
yield self._get_missing_events_for_pdu(
origin, pdu, prevs, min_depth
)
# Update the set of things we've seen after trying to
seen = yield self.store.have_seen_events(prevs)
if not prevs - seen:
logger.info(
"[%s %s] Found all missing prev_events",
room_id,
event_id,
)
elif missing_prevs:
logger.info(
"[%s %s] Not recursively fetching %d missing prev_events: %s",
room_id,
event_id,
len(missing_prevs),
shortstr(missing_prevs),
)
if prevs - seen:
#
# In this case, we need to fall back to asking another server in the
# federation for the state at this event. That's ok provided we then
# withholding its prev_events, and declaring yourself to be an admin in
# the subsequent state request).
#
# Now, if we're pulling this event as a missing prev_event, then clearly
# following.
if sent_to_us_directly:
logger.warn(
"[%s %s] Rejecting: failed to fetch %d prev events: %s",
room_id,
event_id,
len(prevs - seen),
shortstr(prevs - seen),
)
raise FederationError(
"ERROR",
403,
(
"Your server isn't divulging details about prev_events "
"referenced in this event."
),
affected=pdu.event_id,
)
auth_chains = set()
event_map = {event_id: pdu}
try:
ours = yield self.store.get_state_groups_ids(room_id, seen)
state_maps = list(
ours.values()
)
del ours
# know about
for p in prevs - seen:
logger.info(
"[%s %s] Requesting state at missing prev_event %s",
room_id,
event_id,
p,
)
room_version = yield self.store.get_room_version(room_id)
with nested_logging_context(p):
# note that if any of the missing prevs share missing state or
# auth events, the requests to fetch those events are deduped
# by the get_pdu_cache in federation_client.
remote_state, got_auth_chain = (
yield self.federation_client.get_state_for_room(
origin, room_id, p
)
)
# we want the state *after* p; get_state_for_room returns the
# state *before* p.
remote_event = yield self.federation_client.get_pdu(
[origin], p, room_version, outlier=True
)
if remote_event is None:
raise Exception(
"Unable to get missing prev_event %s" % (p,)
)
if remote_event.is_state():
remote_state.append(remote_event)
# XXX hrm I'm not convinced that duplicate events will compare
# hoped.
auth_chains.update(got_auth_chain)
remote_state_map = {
(x.type, x.state_key): x.event_id for x in remote_state
}
state_maps.append(remote_state_map)
for x in remote_state:
event_map[x.event_id] = x
state_map = yield resolve_events_with_store(
room_version,
state_maps,
event_map,
state_res_store=StateResolutionStore(self.store),
)
# We need to give _process_received_pdu the actual state events
# rather than event ids, so generate that now.
# First though we need to fetch all the events that are in
# state_map, so we can build up the state below.
evs = yield self.store.get_events(
list(state_map.values()),
get_prev_content=False,
check_redacted=False,
)
event_map.update(evs)
state = [event_map[e] for e in six.itervalues(state_map)]
auth_chain = list(auth_chains)
except Exception:
logger.warn(
"[%s %s] Error attempting to resolve state at missing "
"prev_events",
room_id,
event_id,
exc_info=True,
)
raise FederationError(
"ERROR",
403,
"We can't get valid state history.",
affected=event_id,
)
yield self._process_received_pdu(
origin, pdu, state=state, auth_chain=auth_chain
)
@defer.inlineCallbacks
def _get_missing_events_for_pdu(self, origin, pdu, prevs, min_depth):
room_id = pdu.room_id
event_id = pdu.event_id
seen = yield self.store.have_seen_events(prevs)
if not prevs - seen:
return
latest = yield self.store.get_latest_event_ids_in_room(room_id)
latest = set(latest)
latest |= seen
logger.info(
"[%s %s]: Requesting missing events between %s and %s",
room_id,
event_id,
shortstr(latest),
event_id,
)
# XXX: we set timeout to 10s to help workaround
# https://github.com/matrix-org/synapse/issues/1733.
# The reason is to avoid holding the linearizer lock
# whilst processing inbound /send transactions, causing
# FDs to stack up and block other inbound transactions
# which empirically can currently take up to 30 minutes.
#
# N.B. this explicitly disables retry attempts.
#
# N.B. this also increases our chances of falling back to
# fetching fresh state for the room if the missing event
# can't be found, which slightly reduces our security.
# apparently.
#
# see https://github.com/matrix-org/synapse/pull/1744
#
# ----
#
# Update richvdh 2018/09/18: There are a number of problems with timing this
# request out agressively on the client side:
#
# - it plays badly with the server-side rate-limiter, which starts tarpitting you
# if you send too many requests at once, so you end up with the server carefully
# working through the backlog of your requests, which you have already timed
# out.
#
# - for this request in particular, we now (as of
# https://github.com/matrix-org/synapse/pull/3456) reject any PDUs where the
# server can't produce a plausible-looking set of prev_events - so we becone
# problem.
#
# - the agressive 10s timeout was introduced to deal with incoming federation
# requests taking 8 hours to process. It's not entirely clear why that was going
#
# All that said: Let's try increasing the timout to 60s and see what happens.
try:
missing_events = yield self.federation_client.get_missing_events(
origin,
room_id,
earliest_events_ids=list(latest),
latest_events=[pdu],
limit=10,
min_depth=min_depth,
timeout=60000,
)
except RequestSendFailed as e:
logger.warn("[%s %s]: Failed to get prev_events: %s", room_id, event_id, e)
return
logger.info(
"[%s %s]: Got %d prev_events: %s",
room_id,
event_id,
len(missing_events),
shortstr(missing_events),
)
missing_events.sort(key=lambda x: x.depth)
for ev in missing_events:
logger.info(
"[%s %s] Handling received prev_event %s",
room_id,
event_id,
ev.event_id,
)
with nested_logging_context(ev.event_id):
try:
yield self.on_receive_pdu(origin, ev, sent_to_us_directly=False)
except FederationError as e:
if e.code == 403:
logger.warn(
"[%s %s] Received prev_event %s failed history check.",
room_id,
event_id,
ev.event_id,
)
else:
raise
@defer.inlineCallbacks
def _process_received_pdu(self, origin, event, state, auth_chain):
room_id = event.room_id
event_id = event.event_id
logger.debug("[%s %s] Processing event: %s", room_id, event_id, event)
event_ids = set()
if state:
event_ids |= {e.event_id for e in state}
if auth_chain:
event_ids |= {e.event_id for e in auth_chain}
seen_ids = yield self.store.have_seen_events(event_ids)
if state and auth_chain is not None:
event_infos = []
for e in itertools.chain(auth_chain, state):
if e.event_id in seen_ids:
continue
e.internal_metadata.outlier = True
auth_ids = e.auth_event_ids()
auth = {
(e.type, e.state_key): e
for e in auth_chain
if e.event_id in auth_ids or e.type == EventTypes.Create
}
event_infos.append({"event": e, "auth_events": auth})
seen_ids.add(e.event_id)
logger.info(
"[%s %s] persisting newly-received auth/state events %s",
room_id,
event_id,
[e["event"].event_id for e in event_infos],
)
yield self._handle_new_events(origin, event_infos)
try:
context = yield self._handle_new_event(origin, event, state=state)
except AuthError as e:
raise FederationError("ERROR", e.code, e.msg, affected=event.event_id)
room = yield self.store.get_room(room_id)
if not room:
try:
yield self.store.store_room(
room_id=room_id, room_creator_user_id="", is_public=False
)
except StoreError:
logger.exception("Failed to store room.")
if event.type == EventTypes.Member:
if event.membership == Membership.JOIN:
# Only fire user_joined_room if the user has acutally
# joined the room. Don't bother if the user is just
newly_joined = True
prev_state_ids = yield context.get_prev_state_ids(self.store)
prev_state_id = prev_state_ids.get((event.type, event.state_key))
if prev_state_id:
prev_state = yield self.store.get_event(
prev_state_id, allow_none=True
)
if prev_state and prev_state.membership == Membership.JOIN:
newly_joined = False
if newly_joined:
user = UserID.from_string(event.state_key)
yield self.user_joined_room(user, room_id)
@log_function
@defer.inlineCallbacks
def backfill(self, dest, room_id, limit, extremities):
if dest == self.server_name:
raise SynapseError(400, "Can't backfill from self.")
room_version = yield self.store.get_room_version(room_id)
events = yield self.federation_client.backfill(
dest, room_id, limit=limit, extremities=extremities
)
# ideally we'd sanity check the events here for excess prev_events etc,
# breaking backfill in the same way that it is currently broken by
# events whose signature we cannot verify (#3121).
#
# So for now we accept the events anyway. #3124 tracks this.
#
# for ev in events:
# self._sanity_check_event(ev)
# Don't bother processing events we already have.
seen_events = yield self.store.have_events_in_timeline(
set(e.event_id for e in events)
)
events = [e for e in events if e.event_id not in seen_events]
if not events:
return []
event_map = {e.event_id: e for e in events}
event_ids = set(e.event_id for e in events)
edges = [ev.event_id for ev in events if set(ev.prev_event_ids()) - event_ids]
logger.info("backfill: Got %d events with %d edges", len(events), len(edges))
auth_events = {}
state_events = {}
events_to_state = {}
for e_id in edges:
state, auth = yield self.federation_client.get_state_for_room(
destination=dest, room_id=room_id, event_id=e_id
)
auth_events.update({a.event_id: a for a in auth})
auth_events.update({s.event_id: s for s in state})
state_events.update({s.event_id: s for s in state})
events_to_state[e_id] = state
required_auth = set(
a_id
for event in events
+ list(state_events.values())
+ list(auth_events.values())
for a_id in event.auth_event_ids()
)
auth_events.update(
{e_id: event_map[e_id] for e_id in required_auth if e_id in event_map}
)
missing_auth = required_auth - set(auth_events)
failed_to_fetch = set()
while missing_auth - failed_to_fetch:
logger.info("Missing auth for backfill: %r", missing_auth)
ret_events = yield self.store.get_events(missing_auth - failed_to_fetch)
auth_events.update(ret_events)
required_auth.update(
a_id for event in ret_events.values() for a_id in event.auth_event_ids()
)
missing_auth = required_auth - set(auth_events)
if missing_auth - failed_to_fetch:
logger.info(
"Fetching missing auth for backfill: %r",
missing_auth - failed_to_fetch,
)
results = yield make_deferred_yieldable(
defer.gatherResults(
[
run_in_background(
self.federation_client.get_pdu,
[dest],
event_id,
room_version=room_version,
outlier=True,
timeout=10000,
)
for event_id in missing_auth - failed_to_fetch
],
consumeErrors=True,
)
).addErrback(unwrapFirstError)
auth_events.update({a.event_id: a for a in results if a})
required_auth.update(
a_id
for event in results
if event
for a_id in event.auth_event_ids()
)
missing_auth = required_auth - set(auth_events)
failed_to_fetch = missing_auth - set(auth_events)
seen_events = yield self.store.have_seen_events(
set(auth_events.keys()) | set(state_events.keys())
)
ev_infos = []
for a in auth_events.values():
# We only want to persist auth events as outliers that we haven't
if a.event_id in seen_events or a.event_id in event_map:
continue
a.internal_metadata.outlier = True
ev_infos.append(
{
"event": a,
"auth_events": {
(
auth_events[a_id].type,
auth_events[a_id].state_key,
): auth_events[a_id]
for a_id in a.auth_event_ids()
if a_id in auth_events
},
}
)
# Step 1b: persist the events in the chunk we fetched state for (i.e.
# the backwards extremities) as non-outliers.
for e_id in events_to_state:
# For paranoia we ensure that these events are marked as
# non-outliers
ev = event_map[e_id]
assert not ev.internal_metadata.is_outlier()
ev_infos.append(
{
"event": ev,
"state": events_to_state[e_id],
"auth_events": {
(
auth_events[a_id].type,
auth_events[a_id].state_key,
): auth_events[a_id]
for a_id in ev.auth_event_ids()
if a_id in auth_events
},
}
)
yield self._handle_new_events(dest, ev_infos, backfilled=True)
# Step 2: Persist the rest of the events in the chunk one by one
events.sort(key=lambda e: e.depth)
for event in events:
if event in events_to_state:
continue
# For paranoia we ensure that these events are marked as
# non-outliers
assert not event.internal_metadata.is_outlier()
# We store these one at a time since each event depends on the
# previous to work out the state.
# TODO: We can probably do something more clever here.
yield self._handle_new_event(dest, event, backfilled=True)
return events
@defer.inlineCallbacks
def maybe_backfill(self, room_id, current_depth):
extremities = yield self.store.get_oldest_events_with_depth_in_room(room_id)
if not extremities:
logger.debug("Not backfilling as no extremeties found.")
return
# We only want to paginate if we can actually see the events we'll get,
# events.
#
# We do this by filtering all the backwards extremities and seeing if
# any remain. Given we don't have the extremity events themselves, we
forward_events = yield self.store.get_successor_events(list(extremities))
extremities_events = yield self.store.get_events(
forward_events, check_redacted=False, get_prev_content=False
)
filtered_extremities = yield filter_events_for_server(
self.store,
self.server_name,
list(extremities_events.values()),
redact=False,
check_history_visibility_only=True,
)
if not filtered_extremities:
return False
sorted_extremeties_tuple = sorted(extremities.items(), key=lambda e: -int(e[1]))
max_depth = sorted_extremeties_tuple[0][1]
# request URI to be too long.
extremities = dict(sorted_extremeties_tuple[:5])
if current_depth > max_depth:
logger.debug(
"Not backfilling as we don't need to. %d < %d", max_depth, current_depth
)
return
curr_state = yield self.state_handler.get_current_state(room_id)
def get_domains_from_state(state):
joined_users = [
(state_key, int(event.depth))
for (e_type, state_key), event in iteritems(state)
if e_type == EventTypes.Member and event.membership == Membership.JOIN
]
joined_domains = {}
for u, d in joined_users:
try:
dom = get_domain_from_id(u)
old_d = joined_domains.get(dom)
if old_d:
joined_domains[dom] = min(d, old_d)
else:
joined_domains[dom] = d
except Exception:
pass
return sorted(joined_domains.items(), key=lambda d: d[1])
curr_domains = get_domains_from_state(curr_state)
likely_domains = [
domain for domain, depth in curr_domains if domain != self.server_name
]
@defer.inlineCallbacks
def try_backfill(domains):
for dom in domains:
try:
yield self.backfill(
dom, room_id, limit=100, extremities=extremities
)
return True
except SynapseError as e:
logger.info("Failed to backfill from %s because %s", dom, e)
continue
except CodeMessageException as e:
if 400 <= e.code < 500:
raise
logger.info("Failed to backfill from %s because %s", dom, e)
continue
except NotRetryingDestination as e:
logger.info(str(e))
continue
except RequestSendFailed as e:
logger.info("Falied to get backfill from %s because %s", dom, e)
continue
except FederationDeniedError as e:
logger.info(e)
continue
except Exception as e:
logger.exception("Failed to backfill from %s because %s", dom, e)
continue
return False
success = yield try_backfill(likely_domains)
if success:
return True
# from the time.
tried_domains = set(likely_domains)
tried_domains.add(self.server_name)
event_ids = list(extremities.keys())
logger.debug("calling resolve_state_groups in _maybe_backfill")
resolve = preserve_fn(self.state_handler.resolve_state_groups_for_events)
states = yield make_deferred_yieldable(
defer.gatherResults(
[resolve(room_id, [e]) for e in event_ids], consumeErrors=True
)
)
# dict[str, dict[tuple, str]], a map from event_id to state map of
# event_ids.
states = dict(zip(event_ids, [s.state for s in states]))
state_map = yield self.store.get_events(
[e_id for ids in itervalues(states) for e_id in itervalues(ids)],
get_prev_content=False,
)
states = {
key: {
k: state_map[e_id]
for k, e_id in iteritems(state_dict)
if e_id in state_map
}
for key, state_dict in iteritems(states)
}
for e_id, _ in sorted_extremeties_tuple:
likely_domains = get_domains_from_state(states[e_id])
success = yield try_backfill(
[dom for dom, _ in likely_domains if dom not in tried_domains]
)
if success:
return True
tried_domains.update(dom for dom, _ in likely_domains)
return False
def _sanity_check_event(self, ev):
if len(ev.prev_event_ids()) > 20:
logger.warn(
"Rejecting event %s which has %i prev_events",
ev.event_id,
len(ev.prev_event_ids()),
)
raise SynapseError(http_client.BAD_REQUEST, "Too many prev_events")
if len(ev.auth_event_ids()) > 10:
logger.warn(
"Rejecting event %s which has %i auth_events",
ev.event_id,
len(ev.auth_event_ids()),
)
raise SynapseError(http_client.BAD_REQUEST, "Too many auth_events")
@defer.inlineCallbacks
def send_invite(self, target_host, event):
pdu = yield self.federation_client.send_invite(
destination=target_host,
room_id=event.room_id,
event_id=event.event_id,
pdu=event,
)
return pdu
@defer.inlineCallbacks
def on_event_auth(self, event_id):
event = yield self.store.get_event(event_id)
auth = yield self.store.get_auth_chain(
[auth_id for auth_id in event.auth_event_ids()], include_given=True
)
return [e for e in auth]
@log_function
@defer.inlineCallbacks
def do_invite_join(self, target_hosts, room_id, joinee, content):
logger.debug("Joining %s to %s", joinee, room_id)
origin, event, event_format_version = yield self._make_and_verify_event(
target_hosts,
room_id,
joinee,
"join",
content,
params={"ver": KNOWN_ROOM_VERSIONS},
)
# This shouldn't happen, because the RoomMemberHandler has a
assert room_id not in self.room_queues
self.room_queues[room_id] = []
yield self._clean_room_for_join(room_id)
handled_events = set()
try:
try:
target_hosts.remove(origin)
target_hosts.insert(0, origin)
except ValueError:
pass
ret = yield self.federation_client.send_join(
target_hosts, event, event_format_version
)
origin = ret["origin"]
state = ret["state"]
auth_chain = ret["auth_chain"]
auth_chain.sort(key=lambda e: e.depth)
handled_events.update([s.event_id for s in state])
handled_events.update([a.event_id for a in auth_chain])
handled_events.add(event.event_id)
logger.debug("do_invite_join auth_chain: %s", auth_chain)
logger.debug("do_invite_join state: %s", state)
logger.debug("do_invite_join event: %s", event)
try:
yield self.store.store_room(
room_id=room_id, room_creator_user_id="", is_public=False
)
except Exception:
pass
yield self._persist_auth_tree(origin, auth_chain, state, event)
logger.debug("Finished joining %s to %s", joinee, room_id)
finally:
room_queue = self.room_queues[room_id]
del self.room_queues[room_id]
# it's just a best-effort thing at this point. We do want to do
# lots of requests for missing prev_events which we do actually
# have. Hence we fire off the deferred, but don't wait for it.
run_in_background(self._handle_queued_pdus, room_queue)
return True
@defer.inlineCallbacks
def _handle_queued_pdus(self, room_queue):
for p, origin in room_queue:
try:
logger.info(
"Processing queued PDU %s which was received "
"while we were joining %s",
p.event_id,
p.room_id,
)
with nested_logging_context(p.event_id):
yield self.on_receive_pdu(origin, p, sent_to_us_directly=True)
except Exception as e:
logger.warn(
"Error handling queued PDU %s from %s: %s", p.event_id, origin, e
)
@defer.inlineCallbacks
@log_function
def on_make_join_request(self, origin, room_id, user_id):
if get_domain_from_id(user_id) != origin:
logger.info(
"Got /make_join request for user %r from different origin %s, ignoring",
user_id,
origin,
)
raise SynapseError(403, "User not from origin", Codes.FORBIDDEN)
event_content = {"membership": Membership.JOIN}
room_version = yield self.store.get_room_version(room_id)
builder = self.event_builder_factory.new(
room_version,
{
"type": EventTypes.Member,
"content": event_content,
"room_id": room_id,
"sender": user_id,
"state_key": user_id,
},
)
try:
event, context = yield self.event_creation_handler.create_new_client_event(
builder=builder
)
except AuthError as e:
logger.warn("Failed to create join %r because %s", event, e)
raise e
event_allowed = yield self.third_party_event_rules.check_event_allowed(
event, context
)
if not event_allowed:
logger.info("Creation of join %s forbidden by third-party rules", event)
raise SynapseError(
403, "This event is not allowed in this context", Codes.FORBIDDEN
)
yield self.auth.check_from_context(
room_version, event, context, do_sig_check=False
)
return event
@defer.inlineCallbacks
@log_function
def on_send_join_request(self, origin, pdu):
event = pdu
logger.debug(
"on_send_join_request: Got event: %s, signatures: %s",
event.event_id,
event.signatures,
)
event.internal_metadata.outlier = False
# the join event over federation after joining, and changing it now
# would introduce the danger of backwards-compatibility problems.
event.internal_metadata.send_on_behalf_of = origin
context = yield self._handle_new_event(origin, event)
event_allowed = yield self.third_party_event_rules.check_event_allowed(
event, context
)
if not event_allowed:
logger.info("Sending of join %s forbidden by third-party rules", event)
raise SynapseError(
403, "This event is not allowed in this context", Codes.FORBIDDEN
)
logger.debug(
"on_send_join_request: After _handle_new_event: %s, sigs: %s",
event.event_id,
event.signatures,
)
if event.type == EventTypes.Member:
if event.content["membership"] == Membership.JOIN:
user = UserID.from_string(event.state_key)
yield self.user_joined_room(user, event.room_id)
prev_state_ids = yield context.get_prev_state_ids(self.store)
state_ids = list(prev_state_ids.values())
auth_chain = yield self.store.get_auth_chain(state_ids)
state = yield self.store.get_events(list(prev_state_ids.values()))
return {"state": list(state.values()), "auth_chain": auth_chain}
@defer.inlineCallbacks
def on_invite_request(self, origin, pdu):
event = pdu
if event.state_key is None:
raise SynapseError(400, "The invite event did not have a state key")
is_blocked = yield self.store.is_room_blocked(event.room_id)
if is_blocked:
raise SynapseError(403, "This room has been blocked on this server")
if self.hs.config.block_non_admin_invites:
raise SynapseError(403, "This server does not accept room invites")
if not self.spam_checker.user_may_invite(
event.sender, event.state_key, event.room_id
):
raise SynapseError(
403, "This user is not permitted to send invites to this server/user"
)
membership = event.content.get("membership")
if event.type != EventTypes.Member or membership != Membership.INVITE:
raise SynapseError(400, "The event was not an m.room.member invite event")
sender_domain = get_domain_from_id(event.sender)
if sender_domain != origin:
raise SynapseError(
400, "The invite event was not from the server sending it"
)
if not self.is_mine_id(event.state_key):
raise SynapseError(400, "The invite event must be for this server")
# block any attempts to invite the server notices mxid
if event.state_key == self._server_notices_mxid:
raise SynapseError(http_client.FORBIDDEN, "Cannot invite this user")
event.internal_metadata.outlier = True
event.internal_metadata.out_of_band_membership = True
event.signatures.update(
compute_event_signature(
event.get_pdu_json(), self.hs.hostname, self.hs.config.signing_key[0]
)
)
context = yield self.state_handler.compute_event_context(event)
yield self.persist_events_and_notify([(event, context)])
return event
@defer.inlineCallbacks
def do_remotely_reject_invite(self, target_hosts, room_id, user_id):
origin, event, event_format_version = yield self._make_and_verify_event(
target_hosts, room_id, user_id, "leave"
)
# Mark as outlier as we don't have any state for this event; we're not
# even in the room.
event.internal_metadata.outlier = True
event.internal_metadata.out_of_band_membership = True
# Try the host that we succesfully called /make_leave/ on first for
# the /send_leave/ request.
try:
target_hosts.remove(origin)
target_hosts.insert(0, origin)
except ValueError:
pass
yield self.federation_client.send_leave(target_hosts, event)
context = yield self.state_handler.compute_event_context(event)
yield self.persist_events_and_notify([(event, context)])
return event
@defer.inlineCallbacks
def _make_and_verify_event(
self, target_hosts, room_id, user_id, membership, content={}, params=None
):
origin, event, format_ver = yield self.federation_client.make_membership_event(
target_hosts, room_id, user_id, membership, content, params=params
)
logger.debug("Got response to make_%s: %s", membership, event)
# We should assert some things.
# FIXME: Do this in a nicer way
assert event.type == EventTypes.Member
assert event.user_id == user_id
assert event.state_key == user_id
assert event.room_id == room_id
return origin, event, format_ver
@defer.inlineCallbacks
@log_function
def on_make_leave_request(self, origin, room_id, user_id):
if get_domain_from_id(user_id) != origin:
logger.info(
"Got /make_leave request for user %r from different origin %s, ignoring",
user_id,
origin,
)
raise SynapseError(403, "User not from origin", Codes.FORBIDDEN)
room_version = yield self.store.get_room_version(room_id)
builder = self.event_builder_factory.new(
room_version,
{
"type": EventTypes.Member,
"content": {"membership": Membership.LEAVE},
"room_id": room_id,
"sender": user_id,
"state_key": user_id,
},
)
event, context = yield self.event_creation_handler.create_new_client_event(
builder=builder
)
event_allowed = yield self.third_party_event_rules.check_event_allowed(
event, context
)
if not event_allowed:
logger.warning("Creation of leave %s forbidden by third-party rules", event)
raise SynapseError(
403, "This event is not allowed in this context", Codes.FORBIDDEN
)
try:
# The remote hasn't signed it yet, obviously. We'll do the full checks
# when we get the event back in `on_send_leave_request`
yield self.auth.check_from_context(
room_version, event, context, do_sig_check=False
)
except AuthError as e:
logger.warn("Failed to create new leave %r because %s", event, e)
raise e
return event
@defer.inlineCallbacks
@log_function
def on_send_leave_request(self, origin, pdu):
event = pdu
logger.debug(
"on_send_leave_request: Got event: %s, signatures: %s",
event.event_id,
event.signatures,
)
event.internal_metadata.outlier = False
context = yield self._handle_new_event(origin, event)
event_allowed = yield self.third_party_event_rules.check_event_allowed(
event, context
)
if not event_allowed:
logger.info("Sending of leave %s forbidden by third-party rules", event)
raise SynapseError(
403, "This event is not allowed in this context", Codes.FORBIDDEN
)
logger.debug(
"on_send_leave_request: After _handle_new_event: %s, sigs: %s",
event.event_id,
event.signatures,
)
return None
@defer.inlineCallbacks
def get_state_for_pdu(self, room_id, event_id):
event = yield self.store.get_event(
event_id, allow_none=False, check_room_id=room_id
)
state_groups = yield self.store.get_state_groups(room_id, [event_id])
if state_groups:
_, state = list(iteritems(state_groups)).pop()
results = {(e.type, e.state_key): e for e in state}
if event.is_state():
# Get previous state
if "replaces_state" in event.unsigned:
prev_id = event.unsigned["replaces_state"]
if prev_id != event.event_id:
prev_event = yield self.store.get_event(prev_id)
results[(event.type, event.state_key)] = prev_event
else:
del results[(event.type, event.state_key)]
res = list(results.values())
return res
else:
return []
@defer.inlineCallbacks
def get_state_ids_for_pdu(self, room_id, event_id):
event = yield self.store.get_event(
event_id, allow_none=False, check_room_id=room_id
)
state_groups = yield self.store.get_state_groups_ids(room_id, [event_id])
if state_groups:
_, state = list(state_groups.items()).pop()
results = state
if event.is_state():
# Get previous state
if "replaces_state" in event.unsigned:
prev_id = event.unsigned["replaces_state"]
if prev_id != event.event_id:
results[(event.type, event.state_key)] = prev_id
else:
results.pop((event.type, event.state_key), None)
return list(results.values())
else:
return []
@defer.inlineCallbacks
@log_function
def on_backfill_request(self, origin, room_id, pdu_list, limit):
in_room = yield self.auth.check_host_in_room(room_id, origin)
if not in_room:
raise AuthError(403, "Host not in room.")
events = yield self.store.get_backfill_events(room_id, pdu_list, limit)
events = yield filter_events_for_server(self.store, origin, events)
return events
@defer.inlineCallbacks
@log_function
def get_persisted_pdu(self, origin, event_id):
event = yield self.store.get_event(
event_id, allow_none=True, allow_rejected=True
)
if event:
in_room = yield self.auth.check_host_in_room(event.room_id, origin)
if not in_room:
raise AuthError(403, "Host not in room.")
events = yield filter_events_for_server(self.store, origin, [event])
event = events[0]
return event
else:
return None
def get_min_depth_for_context(self, context):
return self.store.get_min_depth(context)
@defer.inlineCallbacks
def _handle_new_event(
self, origin, event, state=None, auth_events=None, backfilled=False
):
context = yield self._prep_event(
origin, event, state=state, auth_events=auth_events, backfilled=backfilled
)
# reraise does not allow inlineCallbacks to preserve the stacktrace, so we
# hack around with a try/finally instead.
success = False
try:
if not event.internal_metadata.is_outlier() and not backfilled:
yield self.action_generator.handle_push_actions_for_event(
event, context
)
yield self.persist_events_and_notify(
[(event, context)], backfilled=backfilled
)
success = True
finally:
if not success:
run_in_background(
self.store.remove_push_actions_from_staging, event.event_id
)
return context
@defer.inlineCallbacks
def _handle_new_events(self, origin, event_infos, backfilled=False):
@defer.inlineCallbacks
def prep(ev_info):
event = ev_info["event"]
with nested_logging_context(suffix=event.event_id):
res = yield self._prep_event(
origin,
event,
state=ev_info.get("state"),
auth_events=ev_info.get("auth_events"),
backfilled=backfilled,
)
return res
contexts = yield make_deferred_yieldable(
defer.gatherResults(
[run_in_background(prep, ev_info) for ev_info in event_infos],
consumeErrors=True,
)
)
yield self.persist_events_and_notify(
[
(ev_info["event"], context)
for ev_info, context in zip(event_infos, contexts)
],
backfilled=backfilled,
)
@defer.inlineCallbacks
def _persist_auth_tree(self, origin, auth_events, state, event):
events_to_context = {}
for e in itertools.chain(auth_events, state):
e.internal_metadata.outlier = True
ctx = yield self.state_handler.compute_event_context(e)
events_to_context[e.event_id] = ctx
event_map = {
e.event_id: e for e in itertools.chain(auth_events, state, [event])
}
create_event = None
for e in auth_events:
if (e.type, e.state_key) == (EventTypes.Create, ""):
create_event = e
break
if create_event is None:
# If the state doesn't have a create event then the room is
raise SynapseError(400, "No create event in state")
room_version = create_event.content.get(
"room_version", RoomVersions.V1.identifier
)
missing_auth_events = set()
for e in itertools.chain(auth_events, state, [event]):
for e_id in e.auth_event_ids():
if e_id not in event_map:
missing_auth_events.add(e_id)
for e_id in missing_auth_events:
m_ev = yield self.federation_client.get_pdu(
[origin], e_id, room_version=room_version, outlier=True, timeout=10000
)
if m_ev and m_ev.event_id == e_id:
event_map[e_id] = m_ev
else:
logger.info("Failed to find auth event %r", e_id)
for e in itertools.chain(auth_events, state, [event]):
auth_for_e = {
(event_map[e_id].type, event_map[e_id].state_key): event_map[e_id]
for e_id in e.auth_event_ids()
if e_id in event_map
}
if create_event:
auth_for_e[(EventTypes.Create, "")] = create_event
try:
self.auth.check(room_version, e, auth_events=auth_for_e)
except SynapseError as err:
# the attempt to federate altogether in such cases.
logger.warn("Rejecting %s because %s", e.event_id, err.msg)
if e == event:
raise
events_to_context[e.event_id].rejected = RejectedReason.AUTH_ERROR
yield self.persist_events_and_notify(
[
(e, events_to_context[e.event_id])
for e in itertools.chain(auth_events, state)
]
)
new_event_context = yield self.state_handler.compute_event_context(
event, old_state=state
)
yield self.persist_events_and_notify([(event, new_event_context)])
@defer.inlineCallbacks
def _prep_event(self, origin, event, state, auth_events, backfilled):
context = yield self.state_handler.compute_event_context(event, old_state=state)
if not auth_events:
prev_state_ids = yield context.get_prev_state_ids(self.store)
auth_events_ids = yield self.auth.compute_auth_events(
event, prev_state_ids, for_verification=True
)
auth_events = yield self.store.get_events(auth_events_ids)
auth_events = {(e.type, e.state_key): e for e in auth_events.values()}
# This is a hack to fix some old rooms where the initial join event
# didn't reference the create event in its auth events.
if event.type == EventTypes.Member and not event.auth_event_ids():
if len(event.prev_event_ids()) == 1 and event.depth < 5:
c = yield self.store.get_event(
event.prev_event_ids()[0], allow_none=True
)
if c and c.type == EventTypes.Create:
auth_events[(c.type, c.state_key)] = c
try:
yield self.do_auth(origin, event, context, auth_events=auth_events)
except AuthError as e:
logger.warn("[%s %s] Rejecting: %s", event.room_id, event.event_id, e.msg)
context.rejected = RejectedReason.AUTH_ERROR
if not context.rejected:
yield self._check_for_soft_fail(event, state, backfilled)
if event.type == EventTypes.GuestAccess and not context.rejected:
yield self.maybe_kick_guest_users(event)
return context
@defer.inlineCallbacks
def _check_for_soft_fail(self, event, state, backfilled):
# "soft-fail" the event.
do_soft_fail_check = not backfilled and not event.internal_metadata.is_outlier()
if do_soft_fail_check:
extrem_ids = yield self.store.get_latest_event_ids_in_room(event.room_id)
extrem_ids = set(extrem_ids)
prev_event_ids = set(event.prev_event_ids())
if extrem_ids == prev_event_ids:
# If they're the same then the current state is the same as the
do_soft_fail_check = False
if do_soft_fail_check:
room_version = yield self.store.get_room_version(event.room_id)
if state is not None:
state_sets = yield self.store.get_state_groups(
event.room_id, extrem_ids
)
state_sets = list(state_sets.values())
state_sets.append(state)
current_state_ids = yield self.state_handler.resolve_events(
room_version, state_sets, event
)
current_state_ids = {
k: e.event_id for k, e in iteritems(current_state_ids)
}
else:
current_state_ids = yield self.state_handler.get_current_state_ids(
event.room_id, latest_event_ids=extrem_ids
)
logger.debug(
"Doing soft-fail check for %s: state %s",
event.event_id,
current_state_ids,
)
auth_types = auth_types_for_event(event)
current_state_ids = [
e for k, e in iteritems(current_state_ids) if k in auth_types
]
current_auth_events = yield self.store.get_events(current_state_ids)
current_auth_events = {
(e.type, e.state_key): e for e in current_auth_events.values()
}
try:
self.auth.check(room_version, event, auth_events=current_auth_events)
except AuthError as e:
logger.warn("Soft-failing %r because %s", event, e)
event.internal_metadata.soft_failed = True
@defer.inlineCallbacks
def on_query_auth(
self, origin, event_id, room_id, remote_auth_chain, rejects, missing
):
in_room = yield self.auth.check_host_in_room(room_id, origin)
if not in_room:
raise AuthError(403, "Host not in room.")
event = yield self.store.get_event(
event_id, allow_none=False, check_room_id=room_id
)
for e in remote_auth_chain:
try:
yield self._handle_new_event(origin, e)
except AuthError:
pass
# Now get the current auth_chain for the event.
local_auth_chain = yield self.store.get_auth_chain(
[auth_id for auth_id in event.auth_event_ids()], include_given=True
)
# TODO: Check if we would now reject event_id. If so we need to tell
# everyone.
ret = yield self.construct_auth_difference(local_auth_chain, remote_auth_chain)
logger.debug("on_query_auth returning: %s", ret)
return ret
@defer.inlineCallbacks
def on_get_missing_events(
self, origin, room_id, earliest_events, latest_events, limit
):
in_room = yield self.auth.check_host_in_room(room_id, origin)
if not in_room:
raise AuthError(403, "Host not in room.")
limit = min(limit, 20)
missing_events = yield self.store.get_missing_events(
room_id=room_id,
earliest_events=earliest_events,
latest_events=latest_events,
limit=limit,
)
missing_events = yield filter_events_for_server(
self.store, origin, missing_events
)
return missing_events
@defer.inlineCallbacks
@log_function
def do_auth(self, origin, event, context, auth_events):
room_version = yield self.store.get_room_version(event.room_id)
try:
yield self._update_auth_events_and_context_for_auth(
origin, event, context, auth_events
)
except Exception:
# We don't really mind if the above fails, so lets not fail
# let's still log as an exception since we'll still want to fix
# any bugs.
logger.exception(
"Failed to double check auth events for %s with remote. "
"Ignoring failure and continuing processing of event.",
event.event_id,
)
try:
self.auth.check(room_version, event, auth_events=auth_events)
except AuthError as e:
logger.warn("Failed auth resolution for %r because %s", event, e)
raise e
@defer.inlineCallbacks
def _update_auth_events_and_context_for_auth(
self, origin, event, context, auth_events
):
event_auth_events = set(event.auth_event_ids())
if event.is_state():
event_key = (event.type, event.state_key)
else:
event_key = None
# if the event's auth_events refers to events which are not in our
missing_auth = event_auth_events.difference(
e.event_id for e in auth_events.values()
)
if missing_auth:
have_events = yield self.store.get_seen_events_with_rejections(missing_auth)
logger.debug("Got events %s from store", have_events)
missing_auth.difference_update(have_events.keys())
else:
have_events = {}
have_events.update({e.event_id: "" for e in auth_events.values()})
if missing_auth:
logger.info("auth_events contains unknown events: %s", missing_auth)
try:
try:
remote_auth_chain = yield self.federation_client.get_event_auth(
origin, event.room_id, event.event_id
)
except RequestSendFailed as e:
# The other side isn't around or doesn't implement the
# endpoint, so lets just bail out.
logger.info("Failed to get event auth from remote: %s", e)
return
seen_remotes = yield self.store.have_seen_events(
[e.event_id for e in remote_auth_chain]
)
for e in remote_auth_chain:
if e.event_id in seen_remotes:
continue
if e.event_id == event.event_id:
continue
try:
auth_ids = e.auth_event_ids()
auth = {
(e.type, e.state_key): e
for e in remote_auth_chain
if e.event_id in auth_ids or e.type == EventTypes.Create
}
e.internal_metadata.outlier = True
logger.debug(
"do_auth %s missing_auth: %s", event.event_id, e.event_id
)
yield self._handle_new_event(origin, e, auth_events=auth)
if e.event_id in event_auth_events:
auth_events[(e.type, e.state_key)] = e
except AuthError:
pass
have_events = yield self.store.get_seen_events_with_rejections(
event.auth_event_ids()
)
except Exception:
# FIXME:
logger.exception("Failed to get auth chain")
if event.internal_metadata.is_outlier():
logger.info("Skipping auth_event fetch for outlier")
return
# FIXME: Assumes we have and stored all the state for all the
# prev_events
different_auth = event_auth_events.difference(
e.event_id for e in auth_events.values()
)
if not different_auth:
return
logger.info(
"auth_events refers to events which are not in our calculated auth "
"chain: %s",
different_auth,
)
room_version = yield self.store.get_room_version(event.room_id)
different_events = yield make_deferred_yieldable(
defer.gatherResults(
[
run_in_background(
self.store.get_event, d, allow_none=True, allow_rejected=False
)
for d in different_auth
if d in have_events and not have_events[d]
],
consumeErrors=True,
)
).addErrback(unwrapFirstError)
if different_events:
local_view = dict(auth_events)
remote_view = dict(auth_events)
remote_view.update(
{(d.type, d.state_key): d for d in different_events if d}
)
new_state = yield self.state_handler.resolve_events(
room_version,
[list(local_view.values()), list(remote_view.values())],
event,
)
logger.info(
"After state res: updating auth_events with new state %s",
{
(d.type, d.state_key): d.event_id
for d in new_state.values()
if auth_events.get((d.type, d.state_key)) != d
},
)
auth_events.update(new_state)
different_auth = event_auth_events.difference(
e.event_id for e in auth_events.values()
)
yield self._update_context_for_auth_events(
event, context, auth_events, event_key
)
if not different_auth:
# we're done
return
logger.info(
"auth_events still refers to events which are not in the calculated auth "
"chain after state resolution: %s",
different_auth,
)
do_resolution = False
for e_id in different_auth:
if e_id in have_events:
if have_events[e_id] == RejectedReason.NOT_ANCESTOR:
do_resolution = True
break
if not do_resolution:
logger.info(
"Skipping auth resolution due to lack of provable rejection reasons"
)
return
logger.info("Doing auth resolution")
prev_state_ids = yield context.get_prev_state_ids(self.store)
# 1. Get what we think is the auth chain.
auth_ids = yield self.auth.compute_auth_events(event, prev_state_ids)
local_auth_chain = yield self.store.get_auth_chain(auth_ids, include_given=True)
try:
# 2. Get remote difference.
try:
result = yield self.federation_client.query_auth(
origin, event.room_id, event.event_id, local_auth_chain
)
except RequestSendFailed as e:
# The other side isn't around or doesn't implement the
# endpoint, so lets just bail out.
logger.info("Failed to query auth from remote: %s", e)
return
seen_remotes = yield self.store.have_seen_events(
[e.event_id for e in result["auth_chain"]]
)
# 3. Process any remote auth chain events we haven't seen.
for ev in result["auth_chain"]:
if ev.event_id in seen_remotes:
continue
if ev.event_id == event.event_id:
continue
try:
auth_ids = ev.auth_event_ids()
auth = {
(e.type, e.state_key): e
for e in result["auth_chain"]
if e.event_id in auth_ids or event.type == EventTypes.Create
}
ev.internal_metadata.outlier = True
logger.debug(
"do_auth %s different_auth: %s", event.event_id, e.event_id
)
yield self._handle_new_event(origin, ev, auth_events=auth)
if ev.event_id in event_auth_events:
auth_events[(ev.type, ev.state_key)] = ev
except AuthError:
pass
except Exception:
logger.exception("Failed to query auth chain")
yield self._update_context_for_auth_events(
event, context, auth_events, event_key
)
@defer.inlineCallbacks
def _update_context_for_auth_events(self, event, context, auth_events, event_key):
state_updates = {
k: a.event_id for k, a in iteritems(auth_events) if k != event_key
}
current_state_ids = yield context.get_current_state_ids(self.store)
current_state_ids = dict(current_state_ids)
current_state_ids.update(state_updates)
prev_state_ids = yield context.get_prev_state_ids(self.store)
prev_state_ids = dict(prev_state_ids)
prev_state_ids.update({k: a.event_id for k, a in iteritems(auth_events)})
prev_group = context.state_group
state_group = yield self.store.store_state_group(
event.event_id,
event.room_id,
prev_group=prev_group,
delta_ids=state_updates,
current_state_ids=current_state_ids,
)
yield context.update_state(
state_group=state_group,
current_state_ids=current_state_ids,
prev_state_ids=prev_state_ids,
prev_group=prev_group,
delta_ids=state_updates,
)
@defer.inlineCallbacks
def construct_auth_difference(self, local_auth, remote_auth):
logger.debug("construct_auth_difference Start!")
def sort_fun(ev):
return ev.depth, ev.event_id
logger.debug("construct_auth_difference after sort_fun!")
# missing that event, and iterate only up that list. Repeat.
remote_list = list(remote_auth)
remote_list.sort(key=sort_fun)
local_list = list(local_auth)
local_list.sort(key=sort_fun)
local_iter = iter(local_list)
remote_iter = iter(remote_list)
logger.debug("construct_auth_difference before get_next!")
def get_next(it, opt=None):
try:
return next(it)
except Exception:
return opt
current_local = get_next(local_iter)
current_remote = get_next(remote_iter)
logger.debug("construct_auth_difference before while")
missing_remotes = []
missing_locals = []
while current_local or current_remote:
if current_remote is None:
missing_locals.append(current_local)
current_local = get_next(local_iter)
continue
if current_local is None:
missing_remotes.append(current_remote)
current_remote = get_next(remote_iter)
continue
if current_local.event_id == current_remote.event_id:
current_local = get_next(local_iter)
current_remote = get_next(remote_iter)
continue
if current_local.depth < current_remote.depth:
missing_locals.append(current_local)
current_local = get_next(local_iter)
continue
if current_local.depth > current_remote.depth:
missing_remotes.append(current_remote)
current_remote = get_next(remote_iter)
continue
# They have the same depth, so we fall back to the event_id order
if current_local.event_id < current_remote.event_id:
missing_locals.append(current_local)
current_local = get_next(local_iter)
if current_local.event_id > current_remote.event_id:
missing_remotes.append(current_remote)
current_remote = get_next(remote_iter)
continue
logger.debug("construct_auth_difference after while")
# missing locals should be sent to the server
# We should find why we are missing remotes, as they will have been
# rejected.
# Remove events from missing_remotes if they are referencing a missing
# remote. We only care about the "root" rejected ones.
missing_remote_ids = [e.event_id for e in missing_remotes]
base_remote_rejected = list(missing_remotes)
for e in missing_remotes:
for e_id in e.auth_event_ids():
if e_id in missing_remote_ids:
try:
base_remote_rejected.remove(e)
except ValueError:
pass
reason_map = {}
for e in base_remote_rejected:
reason = yield self.store.get_rejection_reason(e.event_id)
if reason is None:
# TODO: e is not in the current state, so we should
# construct some proof of that.
continue
reason_map[e.event_id] = reason
if reason == RejectedReason.AUTH_ERROR:
pass
elif reason == RejectedReason.REPLACED:
# TODO: Get proof
pass
elif reason == RejectedReason.NOT_ANCESTOR:
# TODO: Get proof.
pass
logger.debug("construct_auth_difference returning")
return {
"auth_chain": local_auth,
"rejects": {
e.event_id: {"reason": reason_map[e.event_id], "proof": None}
for e in base_remote_rejected
},
"missing": [e.event_id for e in missing_locals],
}
@defer.inlineCallbacks
@log_function
def exchange_third_party_invite(
self, sender_user_id, target_user_id, room_id, signed
):
third_party_invite = {"signed": signed}
event_dict = {
"type": EventTypes.Member,
"content": {
"membership": Membership.INVITE,
"third_party_invite": third_party_invite,
},
"room_id": room_id,
"sender": sender_user_id,
"state_key": target_user_id,
}
if (yield self.auth.check_host_in_room(room_id, self.hs.hostname)):
room_version = yield self.store.get_room_version(room_id)
builder = self.event_builder_factory.new(room_version, event_dict)
EventValidator().validate_builder(builder)
event, context = yield self.event_creation_handler.create_new_client_event(
builder=builder
)
event_allowed = yield self.third_party_event_rules.check_event_allowed(
event, context
)
if not event_allowed:
logger.info(
"Creation of threepid invite %s forbidden by third-party rules",
event,
)
raise SynapseError(
403, "This event is not allowed in this context", Codes.FORBIDDEN
)
event, context = yield self.add_display_name_to_third_party_invite(
room_version, event_dict, event, context
)
EventValidator().validate_new(event)
# We need to tell the transaction queue to send this out, even
# though the sender isn't a local user.
event.internal_metadata.send_on_behalf_of = self.hs.hostname
try:
yield self.auth.check_from_context(room_version, event, context)
except AuthError as e:
logger.warn("Denying new third party invite %r because %s", event, e)
raise e
yield self._check_signature(event, context)
member_handler = self.hs.get_room_member_handler()
yield member_handler.send_membership_event(None, event, context)
else:
destinations = set(x.split(":", 1)[-1] for x in (sender_user_id, room_id))
yield self.federation_client.forward_third_party_invite(
destinations, room_id, event_dict
)
@defer.inlineCallbacks
@log_function
def on_exchange_third_party_invite_request(self, room_id, event_dict):
room_version = yield self.store.get_room_version(room_id)
builder = self.event_builder_factory.new(room_version, event_dict)
event, context = yield self.event_creation_handler.create_new_client_event(
builder=builder
)
event_allowed = yield self.third_party_event_rules.check_event_allowed(
event, context
)
if not event_allowed:
logger.warning(
"Exchange of threepid invite %s forbidden by third-party rules", event
)
raise SynapseError(
403, "This event is not allowed in this context", Codes.FORBIDDEN
)
event, context = yield self.add_display_name_to_third_party_invite(
room_version, event_dict, event, context
)
try:
self.auth.check_from_context(room_version, event, context)
except AuthError as e:
logger.warn("Denying third party invite %r because %s", event, e)
raise e
yield self._check_signature(event, context)
event.internal_metadata.send_on_behalf_of = get_domain_from_id(event.sender)
member_handler = self.hs.get_room_member_handler()
yield member_handler.send_membership_event(None, event, context)
@defer.inlineCallbacks
def add_display_name_to_third_party_invite(
self, room_version, event_dict, event, context
):
key = (
EventTypes.ThirdPartyInvite,
event.content["third_party_invite"]["signed"]["token"],
)
original_invite = None
prev_state_ids = yield context.get_prev_state_ids(self.store)
original_invite_id = prev_state_ids.get(key)
if original_invite_id:
original_invite = yield self.store.get_event(
original_invite_id, allow_none=True
)
if original_invite:
display_name = original_invite.content["display_name"]
event_dict["content"]["third_party_invite"]["display_name"] = display_name
else:
logger.info(
"Could not find invite event for third_party_invite: %r", event_dict
)
# We don't discard here as this is not the appropriate place to do
# auth check code will explode appropriately.
builder = self.event_builder_factory.new(room_version, event_dict)
EventValidator().validate_builder(builder)
event, context = yield self.event_creation_handler.create_new_client_event(
builder=builder
)
EventValidator().validate_new(event)
return (event, context)
@defer.inlineCallbacks
def _check_signature(self, event, context):
signed = event.content["third_party_invite"]["signed"]
token = signed["token"]
prev_state_ids = yield context.get_prev_state_ids(self.store)
invite_event_id = prev_state_ids.get((EventTypes.ThirdPartyInvite, token))
invite_event = None
if invite_event_id:
invite_event = yield self.store.get_event(invite_event_id, allow_none=True)
if not invite_event:
raise AuthError(403, "Could not find invite")
logger.debug("Checking auth on event %r", event.content)
last_exception = None
# for each public key in the 3pid invite event
for public_key_object in self.hs.get_auth().get_public_keys(invite_event):
try:
# for each sig on the third_party_invite block of the actual invite
for server, signature_block in signed["signatures"].items():
for key_name, encoded_signature in signature_block.items():
if not key_name.startswith("ed25519:"):
continue
logger.debug(
"Attempting to verify sig with key %s from %r "
"against pubkey %r",
key_name,
server,
public_key_object,
)
try:
public_key = public_key_object["public_key"]
verify_key = decode_verify_key_bytes(
key_name, decode_base64(public_key)
)
verify_signed_json(signed, server, verify_key)
logger.debug(
"Successfully verified sig with key %s from %r "
"against pubkey %r",
key_name,
server,
public_key_object,
)
except Exception:
logger.info(
"Failed to verify sig with key %s from %r "
"against pubkey %r",
key_name,
server,
public_key_object,
)
raise
try:
if "key_validity_url" in public_key_object:
yield self._check_key_revocation(
public_key, public_key_object["key_validity_url"]
)
except Exception:
logger.info(
"Failed to query key_validity_url %s",
public_key_object["key_validity_url"],
)
raise
return
except Exception as e:
last_exception = e
raise last_exception
@defer.inlineCallbacks
def _check_key_revocation(self, public_key, url):
try:
response = yield self.http_client.get_json(url, {"public_key": public_key})
except Exception:
raise SynapseError(502, "Third party certificate could not be checked")
if "valid" not in response or not response["valid"]:
raise AuthError(403, "Third party certificate was invalid")
@defer.inlineCallbacks
def persist_events_and_notify(self, event_and_contexts, backfilled=False):
if self.config.worker_app:
yield self._send_events_to_master(
store=self.store,
event_and_contexts=event_and_contexts,
backfilled=backfilled,
)
else:
max_stream_id = yield self.store.persist_events(
event_and_contexts, backfilled=backfilled
)
if not backfilled: # Never notify for backfilled events
for event, _ in event_and_contexts:
yield self._notify_persisted_event(event, max_stream_id)
def _notify_persisted_event(self, event, max_stream_id):
extra_users = []
if event.type == EventTypes.Member:
target_user_id = event.state_key
# We notify for memberships if its an invite for one of our
# users
if event.internal_metadata.is_outlier():
if event.membership != Membership.INVITE:
if not self.is_mine_id(target_user_id):
return
target_user = UserID.from_string(target_user_id)
extra_users.append(target_user)
elif event.internal_metadata.is_outlier():
return
event_stream_id = event.internal_metadata.stream_ordering
self.notifier.on_new_room_event(
event, event_stream_id, max_stream_id, extra_users=extra_users
)
return self.pusher_pool.on_new_notifications(event_stream_id, max_stream_id)
def _clean_room_for_join(self, room_id):
if self.config.worker_app:
return self._clean_room_for_join_client(room_id)
else:
return self.store.clean_room_for_join(room_id)
def user_joined_room(self, user, room_id):
if self.config.worker_app:
return self._notify_user_membership_change(
room_id=room_id, user_id=user.to_string(), change="joined"
)
else:
return user_joined_room(self.distributor, user, room_id)
@defer.inlineCallbacks
def get_room_complexity(self, remote_room_hosts, room_id):
for host in remote_room_hosts:
res = yield self.federation_client.get_room_complexity(host, room_id)
# We got a result, return it.
if res:
defer.returnValue(res)
# We fell off the bottom, couldn't get the complexity from anyone. Oh
defer.returnValue(None)
| true | true |
f72b820782f5de6dce810345423aa0c625f54b34 | 53,798 | py | Python | mysql-utilities-1.6.0/mysql/utilities/common/rpl_sync.py | bopopescu/mysql-dbcompare | 1e912fd87282be3b3bed48487e6beb0ecb1de339 | [
"Apache-2.0"
] | 2 | 2018-03-20T07:42:58.000Z | 2018-03-20T07:43:49.000Z | mysql-utilities-1.6.0/mysql/utilities/common/rpl_sync.py | bopopescu/mysql-dbcompare | 1e912fd87282be3b3bed48487e6beb0ecb1de339 | [
"Apache-2.0"
] | null | null | null | mysql-utilities-1.6.0/mysql/utilities/common/rpl_sync.py | bopopescu/mysql-dbcompare | 1e912fd87282be3b3bed48487e6beb0ecb1de339 | [
"Apache-2.0"
] | 1 | 2020-07-23T23:07:08.000Z | 2020-07-23T23:07:08.000Z | #
# Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
"""
This file contains features to check the data consistency in a replication
topology (i.e., between the master and its slaves, or only slaves), providing
synchronization features to perform the check over the (supposed) same data of
a system with replication active (running).
"""
import re
import sys
from multiprocessing.pool import ThreadPool
from mysql.utilities.command.dbcompare import diff_objects, get_common_objects
from mysql.utilities.common.database import Database
from mysql.utilities.common.messages import ERROR_USER_WITHOUT_PRIVILEGES
from mysql.utilities.common.pattern_matching import convertSQL_LIKE2REGEXP
from mysql.utilities.common.replication import (get_last_server_gtid,
gtid_set_cardinality,
gtid_set_union)
from mysql.utilities.common.sql_transform import quote_with_backticks
from mysql.utilities.common.topology import Topology
from mysql.utilities.common.user import User
from mysql.utilities.exception import UtilError
# Regular expression to handle the server version format.
_RE_VERSION_FORMAT = r'^(\d+\.\d+(\.\d+)*).*$'
class RPLSynchronizer(object):
"""Class to manage the features of the replication synchronization checker.
The RPLSynchronizer class is used to manage synchronization check between
servers of a replication topology, namely between the master and its
slaves or only between slaves. It provides functions to determine the
slaves missing transactions (i.e., missing GTIDs) and check data
consistency.
"""
def __init__(self, master_cnx_dic, slaves_cnx_dic_lst, options):
"""Constructor.
options[in] dictionary of options (e.g., discover, timeouts,
verbosity).
"""
self._verbosity = options.get('verbosity')
self._rpl_timeout = options.get('rpl_timeout')
self._checksum_timeout = options.get('checksum_timeout')
self._interval = options.get('interval')
self._rpl_topology = Topology(master_cnx_dic, slaves_cnx_dic_lst,
options)
self._slaves = self._rpl_topology.get_slaves_dict()
# Set base server used as reference for comparisons.
self._base_server = None
self._base_server_key = None
self._set_base_server()
# Check user permissions to perform the consistency check.
self._check_privileges()
# Check usage of replication filters.
self._master_rpl_filters = {}
self._slaves_rpl_filters = {}
self._check_rpl_filters()
def _set_base_server(self):
"""Set the base server used for comparison in the internal state.
Set the master if used or the first slave from the topology as the
base server. The base server is the one used as a reference for
comparison with the others. This method sets two instance variables:
_base_server with the Server instance, and _base_server_key with the
string identifying the server (format: 'host@port').
Note: base server might need to be changed (set again) if it is
removed from the topology for some reason (e.g. GTID disabled).
"""
master = self._get_master()
self._base_server = master if master \
else self._rpl_topology.slaves[0]['instance']
self._base_server_key = "{0}@{1}".format(self._base_server.host,
self._base_server.port)
def _get_slave(self, slave_key):
"""Get the slave server instance for the specified key 'host@port'.
This function retrieves the Server instance of for a slave from the
internal state by specifying the key that uniquely identifies it,
i.e. 'host@port'.
slave_key[in] String with the format 'host@port' that uniquely
identifies a server.
Returns a Server instance of the slave with the specified key value
(i.e., 'host@port').
"""
slave_dict = self._slaves[slave_key]
return slave_dict['instance']
def _get_master(self):
"""Get the master server instance.
This function retrieves the Server instance of the master (in the
replication topology).
Returns a Server instance of the master.
"""
return self._rpl_topology.master
def _check_privileges(self):
"""Check required privileges to perform the synchronization check.
This method check if the used users for the master and slaves possess
the required privileges to perform the synchronization check. More
specifically, the following privileges are required:
- on the master: SUPER or REPLICATION CLIENT, LOCK TABLES and
SELECT;
- on slaves: SUPER and SELECT.
An exception is thrown if users doesn't have enough privileges.
"""
if self._verbosity:
print("# Checking users permission to perform consistency check.\n"
"#")
# Check privileges for master.
master_priv = [('SUPER', 'REPLICATION CLIENT'), ('LOCK TABLES',),
('SELECT',)]
master_priv_str = "SUPER or REPLICATION CLIENT, LOCK TABLES and SELECT"
if self._get_master():
server = self._get_master()
user_obj = User(server, "{0}@{1}".format(server.user, server.host))
for any_priv_tuple in master_priv:
has_privilege = any(
[user_obj.has_privilege('*', '*', priv)
for priv in any_priv_tuple]
)
if not has_privilege:
raise UtilError(ERROR_USER_WITHOUT_PRIVILEGES.format(
user=server.user, host=server.host, port=server.port,
operation='perform the synchronization check',
req_privileges=master_priv_str
))
# Check privileges for slaves.
slave_priv = [('SUPER',), ('SELECT',)]
slave_priv_str = "SUPER and SELECT"
for slave_key in self._slaves:
server = self._get_slave(slave_key)
user_obj = User(server, "{0}@{1}".format(server.user, server.host))
for any_priv_tuple in slave_priv:
has_privilege = any(
[user_obj.has_privilege('*', '*', priv)
for priv in any_priv_tuple]
)
if not has_privilege:
raise UtilError(
"User '{0}' on '{1}@{2}' does not have sufficient "
"privileges to perform the synchronization check "
"(required: {3}).".format(server.user, server.host,
server.port, slave_priv_str)
)
def _check_rpl_filters(self):
"""Check usage of replication filters.
Check the usage of replication filtering option on the master (if
defined) and slaves, and set the internal state with the found options
(to check later).
"""
# Get binlog filtering option for the master.
if self._get_master():
m_filters = self._get_master().get_binlog_exceptions()
if m_filters:
# Set filtering option for master.
self._master_rpl_filters['binlog_do_db'] = \
m_filters[0][1].split(',') if m_filters[0][1] else None
self._master_rpl_filters['binlog_ignore_db'] = \
m_filters[0][2].split(',') if m_filters[0][2] else None
# Get replication filtering options for each slave.
for slave_key in self._slaves:
slave = self._get_slave(slave_key)
s_filters = slave.get_slave_rpl_filters()
if s_filters:
# Handle known server issues with some replication filters,
# leading to inconsistent GTID sets. Sync not supported for
# server with those issues.
issues = [(0, 'replicate_do_db'), (1, 'replicate_ignore_db'),
(4, 'replicate_wild_do_table')]
for index, rpl_opt in issues:
if s_filters[index]:
raise UtilError(
"Use of {0} option is not supported. There is a "
"known issue with the use this replication filter "
"and GTID for some server versions. Issue "
"detected for '{1}'.".format(rpl_opt, slave_key))
# Set map (dictionary) with the slave filtering options.
filters_map = {
'replicate_do_db':
s_filters[0].split(',') if s_filters[0] else None,
'replicate_ignore_db':
s_filters[1].split(',') if s_filters[1] else None,
'replicate_do_table':
s_filters[2].split(',') if s_filters[2] else None,
'replicate_ignore_table':
s_filters[3].split(',') if s_filters[3] else None,
}
# Handle wild-*-table filters differently to create
# corresponding regexp.
if s_filters[4]:
wild_list = s_filters[4].split(',')
filters_map['replicate_wild_do_table'] = wild_list
# Create auxiliary list with compiled regexp to match.
regexp_list = []
for wild in wild_list:
regexp = re.compile(convertSQL_LIKE2REGEXP(wild))
regexp_list.append(regexp)
filters_map['regexp_do_table'] = regexp_list
else:
filters_map['replicate_wild_do_table'] = None
filters_map['regexp_do_table'] = None
if s_filters[5]:
wild_list = s_filters[5].split(',')
filters_map['replicate_wild_ignore_table'] = wild_list
# Create auxiliary list with compiled regexp to match.
regexp_list = []
for wild in wild_list:
regexp = re.compile(convertSQL_LIKE2REGEXP(wild))
regexp_list.append(regexp)
filters_map['regexp_ignore_table'] = regexp_list
else:
filters_map['replicate_wild_ignore_table'] = None
filters_map['regexp_ignore_table'] = None
# Set filtering options for the slave.
self._slaves_rpl_filters[slave_key] = filters_map
# Print warning if filters are found.
if self._master_rpl_filters or self._slaves_rpl_filters:
print("# WARNING: Replication filters found on checked "
"servers. This can lead data consistency issues "
"depending on how statements are evaluated.\n"
"# More information: "
"http://dev.mysql.com/doc/en/replication-rules.html")
if self._verbosity:
# Print filter options in verbose mode.
if self._master_rpl_filters:
print("# Master '{0}@{1}':".format(
self._get_master().host, self._get_master().port
))
for rpl_filter in self._master_rpl_filters:
if self._master_rpl_filters[rpl_filter]:
print("# - {0}: {1}".format(
rpl_filter,
', '.join(
self._master_rpl_filters[rpl_filter]
)
))
if self._slaves_rpl_filters:
for slave_key in self._slaves_rpl_filters:
print("# Slave '{0}':".format(slave_key))
filters_map = self._slaves_rpl_filters[slave_key]
for rpl_filter in filters_map:
if (rpl_filter.startswith('replicate')
and filters_map[rpl_filter]):
print("# - {0}: {1}".format(
rpl_filter,
', '.join(filters_map[rpl_filter])
))
def _is_rpl_filtered(self, db_name, tbl_name=None, slave=None):
""" Check if the given object is to be filtered by replication.
This method checks if the given database or table name is
supposed to be filtered by replication (i.e., not replicated),
according to the defined replication filters for the master or
the specified slave.
db_name[in] Name of the database to check (not backtick quoted) or
associated to the table to check..
tbl_name[in] Name of the table to check (not backtick quoted).
Table level filtering rules are only checked if this
value is not None. By default None, meaning that only
the database level rules are checked.
slave[in] Identification of the slave in the format 'host@port'
to check, determining which filtering rules will be
checked. If None only the master filtering rules are
checked, otherwise the rule of the specified slaves
are used. By default: None.
Returns a boolean value indicating if the given database or table is
supposed to be filtered by the replication or not. More precisely,
if True then updates associated to the object are (supposedly) not
replicated, otherwise they are replicated.
"""
def match_regexp(name, regex_list):
""" Check if 'name' matches one of the regex in the given list.
"""
for regex in regex_list:
if regex.match(name):
return True
return False
# Determine object to check and set full qualified name.
is_db = tbl_name is None
obj_name = db_name if is_db else '{0}.{1}'.format(db_name, tbl_name)
# Match replication filter for Master.
if not slave and is_db and self._master_rpl_filters:
if self._master_rpl_filters['binlog_do_db']:
if obj_name in self._master_rpl_filters['binlog_do_db']:
return False
else:
return True
elif self._master_rpl_filters['binlog_ignore_db']:
if obj_name in self._master_rpl_filters['binlog_ignore_db']:
return True
# Match replication filters for the specified slave.
if slave and slave in self._slaves_rpl_filters:
rpl_filter = self._slaves_rpl_filters[slave]
if is_db:
if rpl_filter['replicate_do_db']:
if obj_name in rpl_filter['replicate_do_db']:
return False
else:
return True
elif (rpl_filter['replicate_ignore_db']
and obj_name in rpl_filter['replicate_ignore_db']):
return True
else:
if (rpl_filter['replicate_do_table']
and obj_name in rpl_filter['replicate_do_table']):
return False
if (rpl_filter['replicate_ignore_table']
and obj_name in rpl_filter['replicate_ignore_table']):
return True
if (rpl_filter['replicate_wild_do_table']
and match_regexp(obj_name,
rpl_filter['regexp_do_table'])):
return False
if (rpl_filter['replicate_wild_ignore_table']
and match_regexp(obj_name,
rpl_filter['regexp_ignore_table'])):
return True
if (rpl_filter['replicate_do_table']
or rpl_filter['replicate_wild_do_table']):
return True
# Do not filter replication for object (if no filter rule matched).
return False
def _apply_for_all_slaves(self, slaves, function, args=(), kwargs=None,
multithreading=False):
"""Apply specified function to all given slaves.
This function allow the execution (concurrently or not) of the
specified function with the given arguments on all the specified
slaves.
slaves[in] List of slaves to apply the function. It is assumed
that the list is composed by strings with the
format 'host@port', identifying each slave.
function[in] Name of the function (string) to apply on all
slaves.
args[in] Tuple with all the function arguments (except
keyword arguments).
kwargs[in] Dictionary with all the function keyword arguments.
multithreading[in] Boolean value indicating if the function will be
applied concurrently on all slaves. By default
False, no concurrency.
Return a list of tuples composed by two elements: a string identifying
the slave ('host@port') and the result of the execution of the target
function for the corresponding slave.
"""
if kwargs is None:
kwargs = {}
if multithreading:
# Create a pool of threads to execute the method for each slave.
pool = ThreadPool(processes=len(slaves))
thread_res_lst = []
for slave_key in slaves:
slave = self._get_slave(slave_key)
thread_res = pool.apply_async(getattr(slave, function), args,
kwargs)
thread_res_lst.append((slave_key, thread_res))
pool.close()
# Wait for all threads to finish here to avoid RuntimeErrors when
# waiting for the result of a thread that is already dead.
pool.join()
# Get the result from each slave and return the results.
res = []
for slave_key, thread_res in thread_res_lst:
res.append((slave_key, thread_res.get()))
return res
else:
res = []
for slave_key in slaves:
slave = self._get_slave(slave_key)
slave_res = getattr(slave, function)(*args, **kwargs)
res.append((slave_key, slave_res))
return res
def check_server_versions(self):
"""Check server versions.
Check all server versions and report version differences.
"""
srv_versions = {}
# Get the server version of the master if used.
master = self._get_master()
if master:
master_version = master.get_version()
match = re.match(_RE_VERSION_FORMAT, master_version.strip())
if match:
# Add .0 as release version if not provided.
if not match.group(2):
master_version = "{0}.0".format(match.group(1))
else:
master_version = match.group(1)
master_id = '{0}@{1}'.format(master.host, master.port)
# Store the master version.
srv_versions[master_version] = [master_id]
# Get the server version for all slaves.
for slave_key in self._slaves:
slave = self._get_slave(slave_key)
version = slave.get_version()
match = re.match(_RE_VERSION_FORMAT, version.strip())
if match:
# Add .0 as release version if not provided.
if not match.group(2):
version = "{0}.0".format(match.group(1))
else:
version = match.group(1)
# Store the slave version.
if version in srv_versions:
srv_versions[version].append(slave_key)
else:
srv_versions[version] = [slave_key]
# Check the servers versions and issue a warning if different.
if len(srv_versions) > 1:
print("# WARNING: Servers using different versions:")
for version in srv_versions:
servers_str = ",".join(srv_versions[version])
print("# - {0} for {1}.".format(version, servers_str))
print("#")
def check_gtid_sync(self):
"""Check GTIDs synchronization.
Perform several GTID checks (enabled and errant transactions). If the
master is available (was specified) then it also checks if GTIDs are
in sync between master and its slaves and report the amount of
transaction (i.e., GTIDs) behind the master for each slave.
GTID differences might be an indicator of the existence of data
consistency issues.
Note: The master may not be specified, its use is not mandatory.
"""
# Check if GTIDs are enabled on the topology.
if self._get_master(): # Use of Master is not mandatory.
# GTIDs must be enabled on the master.
if self._get_master().supports_gtid().upper() != 'ON':
raise UtilError(
"Master must support GTIDs and have GTID_MODE=ON."
)
# Skip slaves without GTID enabled and warn user.
reset_base_srv = False
for slave_key, slave_dict in self._slaves.items():
slave = slave_dict['instance']
support_gtid = slave.supports_gtid().upper()
if support_gtid != 'ON':
reason = "GTID_MODE=OFF" if support_gtid == 'OFF' \
else "not support GTIDs"
print("# WARNING: Slave '{0}' will be skipped - "
"{1}.".format(slave_key, reason))
print("#")
del self._slaves[slave_key]
self._rpl_topology.remove_slave(slave_dict)
if slave_key == self._base_server_key:
reset_base_srv = True
# At least on slave must have GTIDs enabled.
if len(self._slaves) == 0:
raise UtilError("No slaves found with GTID support and "
"GTID_MODE=ON.")
# Reset base server if needed (it must have GTID_MODE=ON).
if reset_base_srv:
self._set_base_server()
# Check the set of executed GTIDs and report differences, only if the
# master is specified.
if self._get_master():
master_gtids = self._get_master().get_gtid_executed()
slaves_gtids_data = \
self._rpl_topology.slaves_gtid_subtract_executed(
master_gtids, multithreading=True
)
print("#\n# GTID differences between Master and Slaves:")
for host, port, gtids_missing in slaves_gtids_data:
slave_key = '{0}@{1}'.format(host, port)
gtid_size = gtid_set_cardinality(gtids_missing)
if gtid_size:
plural = 's' if gtid_size > 1 else ''
print("# - Slave '{0}' is {1} transaction{2} behind "
"Master.".format(slave_key, gtid_size, plural))
if self._verbosity:
print("# Missing GTIDs: "
"{0}".format(gtids_missing))
else:
print("# - Slave '{0}' is up-to-date.".format(slave_key))
print("#")
@staticmethod
def _exist_in_obj_list(obj_name, obj_type, obj_list):
"""Check if object (name and type) exists in the given list.
This function checks if the database object for the specified name and
type exists in the specified list of database objects.
obj_name[in] Name of the object to check.
obj_type[in] Type of the object to check.
obj_list[in] List of objects to check. It is assumed that the list
has the format of the ones returned by the function
mysql.utilities.command.dbcompare.get_common_objects().
More precisely with the format:
[(obj_type1, (obj_name1,))..(obj_typeN, (obj_nameN,))]
Returns a boolean value indicating if object with the specified name
and type exists in the specified list of objects.
"""
for obj_row in obj_list:
if obj_row[0] == obj_type and obj_row[1][0] == obj_name:
return True
return False
def _split_active_slaves(self, slaves):
"""Get the list of slaves with replication running and not.
This method separates the list of given slaves into active (with the
IO and SQL thread running) and non active slaves (with one of the
threads stopped).
slaves[in] List of target slaves to separate.
Returns a tuple with two elements, first with the list of active slaves
and the second with the list of not active ones.
"""
# Get slaves status.
slaves_state = self._apply_for_all_slaves(slaves, 'get_slaves_errors',
multithreading=True)
# Store IO and SQL thread status.
active_slaves = []
not_active_slaves = []
for slave_key, state in slaves_state:
# Locally store IO and SQL threads status.
io_running = state[3].upper() == 'YES'
self._slaves[slave_key]['IO_Running'] = io_running
sql_running = state[4].upper() == 'YES'
self._slaves[slave_key]['SQL_Running'] = sql_running
if io_running and sql_running:
active_slaves.append(slave_key)
else:
not_active_slaves.append(slave_key)
print("# WARNING: Slave not active '{0}' - "
"Sync skipped.".format(slave_key))
if self._verbosity:
# Print warning if slave is stopped due to an error.
if not io_running and state[2]:
print("# - IO thread stopped: ERROR {0} - "
"{1}".format(state[1], state[2]))
if not sql_running and state[6]:
print("# - SQL thread stopped: ERROR {0} - "
"{1}".format(state[5], state[6]))
# Return separated list of active and non active replication slaves.
return active_slaves, not_active_slaves
def _compute_sync_point(self, active_slaves=None):
"""Compute the GTID synchronization point.
This method computes the GTID synchronization point based based on the
GTID_EXECUTED set. If a master is available for synchronization the
last GTID from the GTID_EXECUTED set is used as sync point If no
master is available the union of the GTID_EXECUTED sets among all
active slaves is used as the sync point.
active_slaves[in] List of active slaves to consider. Only required
if the master is not available. It is assumed
that the list is composed by strings with the
format 'host@port', identifying each slave.
Return a GTID set representing to synchronization point (to wait for
slaves to catch up and stop).
"""
if self._get_master():
gtid_set = self._get_master().get_gtid_executed()
master_uuid = self._get_master().get_server_uuid()
return get_last_server_gtid(gtid_set, master_uuid)
else:
# Get GTID_EXECUTED on all slaves.
all_gtid_executed = self._apply_for_all_slaves(
active_slaves, 'get_gtid_executed', multithreading=True
)
# Compute the union of all GTID sets for each UUID among slaves.
gtid_sets_by_uuid = {}
for _, gtid_executed in all_gtid_executed:
gtids_list = gtid_executed.split("\n")
for gtid in gtids_list:
gtid_set = gtid.rstrip(', ')
uuid = gtid_set.split(':')[0]
if uuid not in gtid_sets_by_uuid:
gtid_sets_by_uuid[uuid] = gtid_set
else:
union_set = gtid_set_union(gtid_sets_by_uuid[uuid],
gtid_set)
gtid_sets_by_uuid[uuid] = union_set
# Return union of all know executed GTID.
return ",".join(gtid_sets_by_uuid.itervalues())
def _sync_slaves(self, slaves, gtid):
"""Set synchronization point (specified GTID set) for the given slaves.
The method set the synchronization point for the given slaves by
(concurrently) stopping and immediately executing START SLAVE UNTIL
on all given slaves in order to stop upon reaching the given GTID set
(i.e., committing all corresponding transactions for the given GTID
sync point).
slaves[in] List of target slaves to synchronize (i.e., instruct
to stop upon reaching the synchronization point).
gtid[in] GTID set used as the synchronization point.
"""
# Make running slaves stop until sync point (GTID) is reached.
if self._verbosity:
print("# Setting data synchronization point for slaves.")
# STOP slave (only SQL thread).
self._apply_for_all_slaves(slaves, 'stop_sql_thread',
multithreading=True)
# START slave UNTIL sync point is reached.
# Note: Only the SQL thread is stopped when the condition is reached.
until_ops = {'until_gtid_set': gtid, 'sql_after_gtid': True,
'only_sql_thread': True}
self._apply_for_all_slaves(slaves, 'start', (), until_ops,
multithreading=True)
def _checksum_and_resume_rpl(self, not_sync_slaves, sync_slave, table):
"""Checksum table and resume replication on slaves.
This method computes (concurrently) the table checksum of the given
slaves lists (those synced and not synced). For the list of not synced
slaves the table checksum is immediately computed. For the list of
synced slaves, first it waits for them to catch up and the sync point
and only then compute the table checksum and resume replication.
not_sync_slaves[in] List of not synced slaves.
sync_slave[in] List of (previously) synced slaves.
table[in] Target table to compute the checksum.
Returns a list of tuples, each tuple containing the identification of
the server and the corresponding checksum result.
"""
if self._verbosity:
print("# Compute checksum on slaves (wait to catch up and resume"
" replication).")
sys.stdout.flush()
not_sync_checksum = []
if not_sync_slaves:
not_sync_checksum = self._apply_for_all_slaves(
not_sync_slaves, 'checksum_table', (table,),
{'exec_timeout': self._checksum_timeout},
multithreading=True
)
sync_checksum = []
if sync_slave:
sync_checksum = self._apply_for_all_slaves(
sync_slave, 'wait_checksum_and_start', (table,),
{'wait_timeout': self._rpl_timeout,
'wait_interval': self._interval,
'checksum_timeout': self._checksum_timeout},
multithreading=True
)
return not_sync_checksum + sync_checksum
def _check_table_data_sync(self, table, slaves):
"""Check table data synchronization for specified slaves.
This method check the data consistency for the specified table between
the base server (master or slave) and the specified salves. This
operation requires the definition of a "synchronization point" in order
to ensure that the "supposed" same data is compared between servers.
This coordination process is based on GTIDs (checking that all data
until a given GTID has been processed on the slaves). A different
algorithm is used to set the "synchronization point" depending if the
master is used or not. The data consistency is checked relying on the
CHECKSUM TABLE query.
If an error occur during this process, any locked table must be
unlocked and both master and slaves should resume their previous
activity.
Important note: this method assumes that the table exists on the base
server and all specified slaves, therefore checking the existence of
the table as well as other integrity checks (server versions, GTID
definitions, etc.) need to be performed outside the scope of this
method.
table[in] Qualified name of the table to check (quoted with
backticks).
slaves[in] List of slaves to check. Each element of the list must
be a string with the format 'host@port'.
Returns the number of data consistency found.
"""
success = False
checksum_issues = 0
# If no master used then add base server (slave) to slaves to sync.
if not self._get_master():
slaves = slaves + [self._base_server_key]
# Separate active from non active slaves.
active_slaves, not_active_slaves = self._split_active_slaves(slaves)
if self._get_master():
# Lock the table on the master to get GTID synchronization point
# and perform the table checksum.
try:
self._get_master().exec_query(
"LOCK TABLES {0} READ".format(table)
)
last_exec_gtid = self._compute_sync_point()
if self._verbosity > 2:
print("# Sync point GTID: {0}".format(last_exec_gtid))
# Immediately instruct active slaves to stop on sync point.
if active_slaves:
self._sync_slaves(active_slaves, last_exec_gtid)
# Perform table checksum on master.
base_server_checksum = self._get_master().checksum_table(
table, self._checksum_timeout
)
if base_server_checksum[0]:
success = True # Successful checksum for base server.
if self._verbosity > 2:
print("# Checksum on base server (Master): "
"{0}".format(base_server_checksum[0][1]))
else:
print("# [SKIP] {0} checksum on base server (Master) - "
"{1}".format(table, base_server_checksum[1]))
finally:
# Unlock table.
self._get_master().exec_query("UNLOCK TABLES")
elif active_slaves:
# Perform sync without master, only based on active slave (if any).
try:
# Stop all active slaves to get the GTID synchronization point.
self._apply_for_all_slaves(
active_slaves, 'stop_sql_thread', multithreading=True
)
sync_gtids = self._compute_sync_point(active_slaves)
if self._verbosity > 2:
print("# Sync point GTID: {0}".format(sync_gtids))
# Instruct active slaves to stop on sync point.
self._sync_slaves(active_slaves, sync_gtids)
except UtilError:
# Try to restart the slaves in case an error occurs.
self._apply_for_all_slaves(
active_slaves, 'star_sql_thread', multithreading=True
)
# Compute checksum on all slaves and return to previous state.
slaves_checksum = self._checksum_and_resume_rpl(not_active_slaves,
active_slaves, table)
# Check if checksum for base server was successfully computed.
if not self._get_master():
for slave_key, checksum in slaves_checksum:
if slave_key == self._base_server_key:
if checksum[0]:
success = True # Successful checksum for base server.
base_server_checksum = checksum
slaves_checksum.remove((slave_key, checksum))
if self._verbosity > 2:
print("# Checksum on base server: "
"{0}".format(base_server_checksum[0][1]))
else:
print("# [SKIP] {0} checksum on base server - "
"{1}".format(table, checksum[1]))
break
# Compare checksum and report results.
if success and slaves_checksum:
for slave_key, checksum_res in slaves_checksum:
if checksum_res[0] is None:
print("# [SKIP] {0} checksum for Slave '{1}' - "
"{2}.".format(table, slave_key, checksum_res[1]))
else:
if self._verbosity > 2:
checksum_val = ': {0}'.format(checksum_res[0][1])
else:
checksum_val = ''
if checksum_res[0] != base_server_checksum[0]:
print("# [DIFF] {0} checksum for server '{1}'"
"{2}.".format(table, slave_key, checksum_val))
checksum_issues += 1
else:
print("# [OK] {0} checksum for server '{1}'"
"{2}.".format(table, slave_key, checksum_val))
return checksum_issues
def check_data_sync(self, options, data_to_include, data_to_exclude):
"""Check data synchronization.
Check if the data (in all tables) is in sync between the checked
servers (master and its slaves, or only slaves). It reports structure
difference database/tables missing or with a different definition and
data differences between a base server and the others.
Note: A different algorithm is applied to perform the synchronization,
depending if the master is specified (available) or not.
options[in] Dictionary of options.
data_to_include[in] Dictionary of data (set of tables) by database to
check.
data_to_exclude[in] Dictionary of data (set of tables) by database to
exclude from check.
Returns the number of consistency issues found (comparing database
definitions and data).
"""
issues_count = 0
# Skip all database objects, except tables.
options['skip_views'] = True
options['skip_triggers'] = True
options['skip_procs'] = True
options['skip_funcs'] = True
options['skip_events'] = True
options['skip_grants'] = True
diff_options = {}
diff_options.update(options)
diff_options['quiet'] = True # Do not print messages.
diff_options['suppress_sql'] = True # Do not print SQL statements.
diff_options['skip_table_opts'] = True # Ignore AUTO_INCREMENT diffs.
# Check the server version requirement to support sync features.
# Slave servers of version >= 5.6.14 are required due to a known issue
# for START SLAVE UNTIL with the SQL_AFTER_GTIDS option. More info:
# https://dev.mysql.com/doc/refman/5.6/en/start-slave.html
for slave_key in self._slaves:
if not self._get_slave(slave_key).check_version_compat(5, 6, 14):
raise UtilError(
"Server '{0}' version must be 5.6.14 or greater. Sync is "
"not supported for versions prior to 5.6.14 due to a "
"known issue with START SLAVE UNTIL and the "
"SQL_AFTER_GTIDS option.".format(slave_key))
print("# Checking data consistency.\n#")
base_srv_type = 'Master' if self._get_master() else 'Slave'
print("# Using {0} '{1}' as base server for comparison."
"".format(base_srv_type, self._base_server_key))
# Get all databases from the base server.
db_rows = self._base_server.get_all_databases()
base_server_dbs = set([row[0] for row in db_rows])
# Process databases to include/exclude from check.
db_to_include = set()
if data_to_include:
db_to_include = set([db for db in data_to_include])
base_server_dbs = base_server_dbs & db_to_include
not_exist_db = db_to_include - base_server_dbs
if not_exist_db:
plurals = ('s', '') if len(not_exist_db) > 1 else ('', 'es')
print('# WARNING: specified database{0} to check do{1} not '
'exist on base server and will be skipped: '
'{2}.'.format(plurals[0], plurals[1],
", ".join(not_exist_db)))
db_to_exclude = set()
if data_to_exclude:
db_to_exclude = set(
[db for db in data_to_exclude if not data_to_exclude[db]]
)
base_server_dbs = base_server_dbs - db_to_exclude
# Check databases on slaves (except the base server).
slaves_except_base = [key for key in self._slaves
if key != self._base_server_key]
for slave_key in slaves_except_base:
slave = self._get_slave(slave_key)
db_rows = slave.get_all_databases()
slave_dbs = set([row[0] for row in db_rows])
# Process databases to include/exclude.
if db_to_include:
slave_dbs = slave_dbs & db_to_include
if db_to_exclude:
slave_dbs = slave_dbs - db_to_exclude
# Add slave databases set to internal state.
self._slaves[slave_key]['databases'] = slave_dbs
# Report databases not on base server and filtered by replication.
dbs_not_in_base_srv = slave_dbs - base_server_dbs
filtered_dbs = set(
[db for db in dbs_not_in_base_srv
if self._is_rpl_filtered(db, slave=self._base_server_key)]
)
dbs_not_in_base_srv -= filtered_dbs
for db in filtered_dbs:
print("# [SKIP] Database '{0}' - filtered by replication "
"rule on base server.".format(db))
if dbs_not_in_base_srv:
issues_count += len(dbs_not_in_base_srv)
plural = 's' if len(dbs_not_in_base_srv) > 1 else ''
print("# [DIFF] Database{0} NOT on base server but found on "
"'{1}': {2}".format(plural, slave_key,
",".join(dbs_not_in_base_srv)))
# Determine server to check base replication filtering options.
filter_srv = None if self._get_master() else self._base_server_key
# Check data consistency for each table on the base server.
for db_name in base_server_dbs:
# Skip database if filtered by defined replication rules.
if self._is_rpl_filtered(db_name, slave=filter_srv):
print("# [SKIP] Database '{0}' check - filtered by "
"replication rule.".format(db_name))
continue
print("# Checking '{0}' database...".format(db_name))
slaves_to_check = {}
# Check if database exists on slaves (except the base server).
for slave_key in slaves_except_base:
# Skip database if filtered by defined replication rules.
if self._is_rpl_filtered(db_name, slave=slave_key):
print("# [SKIP] Database '{0}' check for '{1}' - filtered "
"by replication rule.".format(db_name, slave_key))
continue
if db_name in self._slaves[slave_key]['databases']:
# Store slave database instance and common objects.
slave_db = Database(self._get_slave(slave_key), db_name,
options)
slave_db.init()
slave_dic = {'db': slave_db}
in_both, in_basesrv, not_in_basesrv = get_common_objects(
self._base_server, self._get_slave(slave_key),
db_name, db_name, False, options)
# Process tables to include/exclude from check (on slaves).
if (data_to_include and db_name in data_to_include
and data_to_include[db_name]):
in_both = [
obj_row for obj_row in in_both
if obj_row[1][0] in data_to_include[db_name]
]
in_basesrv = [
obj_row for obj_row in in_basesrv
if obj_row[1][0] in data_to_include[db_name]
]
not_in_basesrv = [
obj_row for obj_row in not_in_basesrv
if obj_row[1][0] in data_to_include[db_name]
]
if (data_to_exclude and db_name in data_to_exclude
and data_to_exclude[db_name]):
in_both = [
obj_row for obj_row in in_both
if obj_row[1][0] not in data_to_exclude[db_name]
]
in_basesrv = [
obj_row for obj_row in in_basesrv
if obj_row[1][0] not in data_to_exclude[db_name]
]
not_in_basesrv = [
obj_row for obj_row in not_in_basesrv
if obj_row[1][0] not in data_to_exclude[db_name]
]
slave_dic['in_both'] = in_both
slave_dic['in_basesrv'] = in_basesrv
slaves_to_check[slave_key] = slave_dic
# Report tables not on base server and filtered by
# replication.
tbls_not_in = set(
[obj_row[1][0] for obj_row in not_in_basesrv
if obj_row[0] == 'TABLE']
)
filtered_tbls = set(
[tbl for tbl in tbls_not_in if self._is_rpl_filtered(
db_name, tbl_name=tbl, slave=self._base_server_key
)]
)
tbls_not_in -= filtered_tbls
for tbl in filtered_tbls:
print("# [SKIP] Table '{0}' - filtered by replication "
"rule on base server.".format(tbl))
if tbls_not_in:
plural = 's' if len(tbls_not_in) > 1 else ''
print("# [DIFF] Table{0} NOT on base server but "
"found on '{1}': "
"{2}".format(plural, slave_key,
", ".join(tbls_not_in)))
issues_count += len(tbls_not_in)
else:
print("# [DIFF] Database '{0}' NOT on server "
"'{1}'.".format(db_name, slave_key))
issues_count += 1
# Only check database if at least one slave has it.
if slaves_to_check:
db = Database(self._base_server, db_name, options)
db.init()
for db_obj in db.get_next_object():
obj_type = db_obj[0]
obj_name = db_obj[1][0]
# Process tables to include/exclude from check (on base
# server).
if (data_to_include and data_to_include[db_name]
and obj_name not in data_to_include[db_name]):
# Skip to the next object if not in data to include.
continue
if (data_to_exclude and data_to_exclude[db_name]
and obj_name in data_to_exclude[db_name]):
# Skip to the next object if in data to exclude.
continue
checksum_task = []
# Check object data on all valid slaves.
for slave_key in slaves_to_check:
# Skip table if filtered by defined replication rules.
if (obj_type == 'TABLE'
and self._is_rpl_filtered(db_name, obj_name,
slave=slave_key)):
print("# [SKIP] Table '{0}' check for '{1}' - "
"filtered by replication rule."
"".format(obj_name, slave_key))
continue
slave_dic = slaves_to_check[slave_key]
# Check if object does not exist on Slave.
if self._exist_in_obj_list(obj_name, obj_type,
slave_dic['in_basesrv']):
print("# [DIFF] {0} '{1}.{2}' NOT on server "
"'{3}'.".format(obj_type.capitalize(),
db_name, obj_name,
slave_key))
issues_count += 1
continue
# Quote object name with backticks.
q_obj = '{0}.{1}'.format(
quote_with_backticks(db_name),
quote_with_backticks(obj_name)
)
# Check object definition.
def_diff = diff_objects(
self._base_server, self._get_slave(slave_key),
q_obj, q_obj, diff_options, obj_type
)
if def_diff:
print("# [DIFF] {0} {1} definition is "
"different on '{2}'."
"".format(obj_type.capitalize(), q_obj,
slave_key))
issues_count += 1
if self._verbosity:
for diff in def_diff[3:]:
print("# {0}".format(diff))
continue
# Add slave to table checksum task.
checksum_task.append(slave_key)
# Perform table checksum on valid slaves.
if checksum_task and obj_type == 'TABLE':
print("# - Checking '{0}' table data..."
"".format(obj_name))
num_issues = self._check_table_data_sync(q_obj,
checksum_task)
issues_count += num_issues
print("#\n#...done.\n#")
str_issues_count = 'No' if issues_count == 0 else str(issues_count)
plural = 's' if issues_count > 1 else ''
print("# SUMMARY: {0} data consistency issue{1} found.\n"
"#".format(str_issues_count, plural))
return issues_count
| 48.379496 | 79 | 0.549686 |
import re
import sys
from multiprocessing.pool import ThreadPool
from mysql.utilities.command.dbcompare import diff_objects, get_common_objects
from mysql.utilities.common.database import Database
from mysql.utilities.common.messages import ERROR_USER_WITHOUT_PRIVILEGES
from mysql.utilities.common.pattern_matching import convertSQL_LIKE2REGEXP
from mysql.utilities.common.replication import (get_last_server_gtid,
gtid_set_cardinality,
gtid_set_union)
from mysql.utilities.common.sql_transform import quote_with_backticks
from mysql.utilities.common.topology import Topology
from mysql.utilities.common.user import User
from mysql.utilities.exception import UtilError
_RE_VERSION_FORMAT = r'^(\d+\.\d+(\.\d+)*).*$'
class RPLSynchronizer(object):
def __init__(self, master_cnx_dic, slaves_cnx_dic_lst, options):
self._verbosity = options.get('verbosity')
self._rpl_timeout = options.get('rpl_timeout')
self._checksum_timeout = options.get('checksum_timeout')
self._interval = options.get('interval')
self._rpl_topology = Topology(master_cnx_dic, slaves_cnx_dic_lst,
options)
self._slaves = self._rpl_topology.get_slaves_dict()
self._base_server = None
self._base_server_key = None
self._set_base_server()
self._check_privileges()
self._master_rpl_filters = {}
self._slaves_rpl_filters = {}
self._check_rpl_filters()
def _set_base_server(self):
master = self._get_master()
self._base_server = master if master \
else self._rpl_topology.slaves[0]['instance']
self._base_server_key = "{0}@{1}".format(self._base_server.host,
self._base_server.port)
def _get_slave(self, slave_key):
slave_dict = self._slaves[slave_key]
return slave_dict['instance']
def _get_master(self):
return self._rpl_topology.master
def _check_privileges(self):
if self._verbosity:
print("# Checking users permission to perform consistency check.\n"
"#")
master_priv = [('SUPER', 'REPLICATION CLIENT'), ('LOCK TABLES',),
('SELECT',)]
master_priv_str = "SUPER or REPLICATION CLIENT, LOCK TABLES and SELECT"
if self._get_master():
server = self._get_master()
user_obj = User(server, "{0}@{1}".format(server.user, server.host))
for any_priv_tuple in master_priv:
has_privilege = any(
[user_obj.has_privilege('*', '*', priv)
for priv in any_priv_tuple]
)
if not has_privilege:
raise UtilError(ERROR_USER_WITHOUT_PRIVILEGES.format(
user=server.user, host=server.host, port=server.port,
operation='perform the synchronization check',
req_privileges=master_priv_str
))
slave_priv = [('SUPER',), ('SELECT',)]
slave_priv_str = "SUPER and SELECT"
for slave_key in self._slaves:
server = self._get_slave(slave_key)
user_obj = User(server, "{0}@{1}".format(server.user, server.host))
for any_priv_tuple in slave_priv:
has_privilege = any(
[user_obj.has_privilege('*', '*', priv)
for priv in any_priv_tuple]
)
if not has_privilege:
raise UtilError(
"User '{0}' on '{1}@{2}' does not have sufficient "
"privileges to perform the synchronization check "
"(required: {3}).".format(server.user, server.host,
server.port, slave_priv_str)
)
def _check_rpl_filters(self):
if self._get_master():
m_filters = self._get_master().get_binlog_exceptions()
if m_filters:
self._master_rpl_filters['binlog_do_db'] = \
m_filters[0][1].split(',') if m_filters[0][1] else None
self._master_rpl_filters['binlog_ignore_db'] = \
m_filters[0][2].split(',') if m_filters[0][2] else None
for slave_key in self._slaves:
slave = self._get_slave(slave_key)
s_filters = slave.get_slave_rpl_filters()
if s_filters:
issues = [(0, 'replicate_do_db'), (1, 'replicate_ignore_db'),
(4, 'replicate_wild_do_table')]
for index, rpl_opt in issues:
if s_filters[index]:
raise UtilError(
"Use of {0} option is not supported. There is a "
"known issue with the use this replication filter "
"and GTID for some server versions. Issue "
"detected for '{1}'.".format(rpl_opt, slave_key))
filters_map = {
'replicate_do_db':
s_filters[0].split(',') if s_filters[0] else None,
'replicate_ignore_db':
s_filters[1].split(',') if s_filters[1] else None,
'replicate_do_table':
s_filters[2].split(',') if s_filters[2] else None,
'replicate_ignore_table':
s_filters[3].split(',') if s_filters[3] else None,
}
if s_filters[4]:
wild_list = s_filters[4].split(',')
filters_map['replicate_wild_do_table'] = wild_list
regexp_list = []
for wild in wild_list:
regexp = re.compile(convertSQL_LIKE2REGEXP(wild))
regexp_list.append(regexp)
filters_map['regexp_do_table'] = regexp_list
else:
filters_map['replicate_wild_do_table'] = None
filters_map['regexp_do_table'] = None
if s_filters[5]:
wild_list = s_filters[5].split(',')
filters_map['replicate_wild_ignore_table'] = wild_list
regexp_list = []
for wild in wild_list:
regexp = re.compile(convertSQL_LIKE2REGEXP(wild))
regexp_list.append(regexp)
filters_map['regexp_ignore_table'] = regexp_list
else:
filters_map['replicate_wild_ignore_table'] = None
filters_map['regexp_ignore_table'] = None
self._slaves_rpl_filters[slave_key] = filters_map
if self._master_rpl_filters or self._slaves_rpl_filters:
print("# WARNING: Replication filters found on checked "
"servers. This can lead data consistency issues "
"depending on how statements are evaluated.\n"
"# More information: "
"http://dev.mysql.com/doc/en/replication-rules.html")
if self._verbosity:
if self._master_rpl_filters:
print("# Master '{0}@{1}':".format(
self._get_master().host, self._get_master().port
))
for rpl_filter in self._master_rpl_filters:
if self._master_rpl_filters[rpl_filter]:
print("# - {0}: {1}".format(
rpl_filter,
', '.join(
self._master_rpl_filters[rpl_filter]
)
))
if self._slaves_rpl_filters:
for slave_key in self._slaves_rpl_filters:
print("# Slave '{0}':".format(slave_key))
filters_map = self._slaves_rpl_filters[slave_key]
for rpl_filter in filters_map:
if (rpl_filter.startswith('replicate')
and filters_map[rpl_filter]):
print("# - {0}: {1}".format(
rpl_filter,
', '.join(filters_map[rpl_filter])
))
def _is_rpl_filtered(self, db_name, tbl_name=None, slave=None):
def match_regexp(name, regex_list):
for regex in regex_list:
if regex.match(name):
return True
return False
is_db = tbl_name is None
obj_name = db_name if is_db else '{0}.{1}'.format(db_name, tbl_name)
if not slave and is_db and self._master_rpl_filters:
if self._master_rpl_filters['binlog_do_db']:
if obj_name in self._master_rpl_filters['binlog_do_db']:
return False
else:
return True
elif self._master_rpl_filters['binlog_ignore_db']:
if obj_name in self._master_rpl_filters['binlog_ignore_db']:
return True
if slave and slave in self._slaves_rpl_filters:
rpl_filter = self._slaves_rpl_filters[slave]
if is_db:
if rpl_filter['replicate_do_db']:
if obj_name in rpl_filter['replicate_do_db']:
return False
else:
return True
elif (rpl_filter['replicate_ignore_db']
and obj_name in rpl_filter['replicate_ignore_db']):
return True
else:
if (rpl_filter['replicate_do_table']
and obj_name in rpl_filter['replicate_do_table']):
return False
if (rpl_filter['replicate_ignore_table']
and obj_name in rpl_filter['replicate_ignore_table']):
return True
if (rpl_filter['replicate_wild_do_table']
and match_regexp(obj_name,
rpl_filter['regexp_do_table'])):
return False
if (rpl_filter['replicate_wild_ignore_table']
and match_regexp(obj_name,
rpl_filter['regexp_ignore_table'])):
return True
if (rpl_filter['replicate_do_table']
or rpl_filter['replicate_wild_do_table']):
return True
return False
def _apply_for_all_slaves(self, slaves, function, args=(), kwargs=None,
multithreading=False):
if kwargs is None:
kwargs = {}
if multithreading:
pool = ThreadPool(processes=len(slaves))
thread_res_lst = []
for slave_key in slaves:
slave = self._get_slave(slave_key)
thread_res = pool.apply_async(getattr(slave, function), args,
kwargs)
thread_res_lst.append((slave_key, thread_res))
pool.close()
pool.join()
res = []
for slave_key, thread_res in thread_res_lst:
res.append((slave_key, thread_res.get()))
return res
else:
res = []
for slave_key in slaves:
slave = self._get_slave(slave_key)
slave_res = getattr(slave, function)(*args, **kwargs)
res.append((slave_key, slave_res))
return res
def check_server_versions(self):
srv_versions = {}
master = self._get_master()
if master:
master_version = master.get_version()
match = re.match(_RE_VERSION_FORMAT, master_version.strip())
if match:
if not match.group(2):
master_version = "{0}.0".format(match.group(1))
else:
master_version = match.group(1)
master_id = '{0}@{1}'.format(master.host, master.port)
srv_versions[master_version] = [master_id]
for slave_key in self._slaves:
slave = self._get_slave(slave_key)
version = slave.get_version()
match = re.match(_RE_VERSION_FORMAT, version.strip())
if match:
if not match.group(2):
version = "{0}.0".format(match.group(1))
else:
version = match.group(1)
if version in srv_versions:
srv_versions[version].append(slave_key)
else:
srv_versions[version] = [slave_key]
if len(srv_versions) > 1:
print("# WARNING: Servers using different versions:")
for version in srv_versions:
servers_str = ",".join(srv_versions[version])
print("# - {0} for {1}.".format(version, servers_str))
print("#")
def check_gtid_sync(self):
if self._get_master():
if self._get_master().supports_gtid().upper() != 'ON':
raise UtilError(
"Master must support GTIDs and have GTID_MODE=ON."
)
reset_base_srv = False
for slave_key, slave_dict in self._slaves.items():
slave = slave_dict['instance']
support_gtid = slave.supports_gtid().upper()
if support_gtid != 'ON':
reason = "GTID_MODE=OFF" if support_gtid == 'OFF' \
else "not support GTIDs"
print("# WARNING: Slave '{0}' will be skipped - "
"{1}.".format(slave_key, reason))
print("#")
del self._slaves[slave_key]
self._rpl_topology.remove_slave(slave_dict)
if slave_key == self._base_server_key:
reset_base_srv = True
if len(self._slaves) == 0:
raise UtilError("No slaves found with GTID support and "
"GTID_MODE=ON.")
if reset_base_srv:
self._set_base_server()
if self._get_master():
master_gtids = self._get_master().get_gtid_executed()
slaves_gtids_data = \
self._rpl_topology.slaves_gtid_subtract_executed(
master_gtids, multithreading=True
)
print("#\n# GTID differences between Master and Slaves:")
for host, port, gtids_missing in slaves_gtids_data:
slave_key = '{0}@{1}'.format(host, port)
gtid_size = gtid_set_cardinality(gtids_missing)
if gtid_size:
plural = 's' if gtid_size > 1 else ''
print("# - Slave '{0}' is {1} transaction{2} behind "
"Master.".format(slave_key, gtid_size, plural))
if self._verbosity:
print("# Missing GTIDs: "
"{0}".format(gtids_missing))
else:
print("# - Slave '{0}' is up-to-date.".format(slave_key))
print("#")
@staticmethod
def _exist_in_obj_list(obj_name, obj_type, obj_list):
for obj_row in obj_list:
if obj_row[0] == obj_type and obj_row[1][0] == obj_name:
return True
return False
def _split_active_slaves(self, slaves):
slaves_state = self._apply_for_all_slaves(slaves, 'get_slaves_errors',
multithreading=True)
active_slaves = []
not_active_slaves = []
for slave_key, state in slaves_state:
io_running = state[3].upper() == 'YES'
self._slaves[slave_key]['IO_Running'] = io_running
sql_running = state[4].upper() == 'YES'
self._slaves[slave_key]['SQL_Running'] = sql_running
if io_running and sql_running:
active_slaves.append(slave_key)
else:
not_active_slaves.append(slave_key)
print("# WARNING: Slave not active '{0}' - "
"Sync skipped.".format(slave_key))
if self._verbosity:
if not io_running and state[2]:
print("# - IO thread stopped: ERROR {0} - "
"{1}".format(state[1], state[2]))
if not sql_running and state[6]:
print("# - SQL thread stopped: ERROR {0} - "
"{1}".format(state[5], state[6]))
return active_slaves, not_active_slaves
def _compute_sync_point(self, active_slaves=None):
if self._get_master():
gtid_set = self._get_master().get_gtid_executed()
master_uuid = self._get_master().get_server_uuid()
return get_last_server_gtid(gtid_set, master_uuid)
else:
all_gtid_executed = self._apply_for_all_slaves(
active_slaves, 'get_gtid_executed', multithreading=True
)
gtid_sets_by_uuid = {}
for _, gtid_executed in all_gtid_executed:
gtids_list = gtid_executed.split("\n")
for gtid in gtids_list:
gtid_set = gtid.rstrip(', ')
uuid = gtid_set.split(':')[0]
if uuid not in gtid_sets_by_uuid:
gtid_sets_by_uuid[uuid] = gtid_set
else:
union_set = gtid_set_union(gtid_sets_by_uuid[uuid],
gtid_set)
gtid_sets_by_uuid[uuid] = union_set
return ",".join(gtid_sets_by_uuid.itervalues())
def _sync_slaves(self, slaves, gtid):
if self._verbosity:
print("# Setting data synchronization point for slaves.")
self._apply_for_all_slaves(slaves, 'stop_sql_thread',
multithreading=True)
until_ops = {'until_gtid_set': gtid, 'sql_after_gtid': True,
'only_sql_thread': True}
self._apply_for_all_slaves(slaves, 'start', (), until_ops,
multithreading=True)
def _checksum_and_resume_rpl(self, not_sync_slaves, sync_slave, table):
if self._verbosity:
print("# Compute checksum on slaves (wait to catch up and resume"
" replication).")
sys.stdout.flush()
not_sync_checksum = []
if not_sync_slaves:
not_sync_checksum = self._apply_for_all_slaves(
not_sync_slaves, 'checksum_table', (table,),
{'exec_timeout': self._checksum_timeout},
multithreading=True
)
sync_checksum = []
if sync_slave:
sync_checksum = self._apply_for_all_slaves(
sync_slave, 'wait_checksum_and_start', (table,),
{'wait_timeout': self._rpl_timeout,
'wait_interval': self._interval,
'checksum_timeout': self._checksum_timeout},
multithreading=True
)
return not_sync_checksum + sync_checksum
def _check_table_data_sync(self, table, slaves):
success = False
checksum_issues = 0
if not self._get_master():
slaves = slaves + [self._base_server_key]
active_slaves, not_active_slaves = self._split_active_slaves(slaves)
if self._get_master():
try:
self._get_master().exec_query(
"LOCK TABLES {0} READ".format(table)
)
last_exec_gtid = self._compute_sync_point()
if self._verbosity > 2:
print("# Sync point GTID: {0}".format(last_exec_gtid))
if active_slaves:
self._sync_slaves(active_slaves, last_exec_gtid)
base_server_checksum = self._get_master().checksum_table(
table, self._checksum_timeout
)
if base_server_checksum[0]:
success = True
if self._verbosity > 2:
print("# Checksum on base server (Master): "
"{0}".format(base_server_checksum[0][1]))
else:
print("# [SKIP] {0} checksum on base server (Master) - "
"{1}".format(table, base_server_checksum[1]))
finally:
self._get_master().exec_query("UNLOCK TABLES")
elif active_slaves:
try:
self._apply_for_all_slaves(
active_slaves, 'stop_sql_thread', multithreading=True
)
sync_gtids = self._compute_sync_point(active_slaves)
if self._verbosity > 2:
print("# Sync point GTID: {0}".format(sync_gtids))
self._sync_slaves(active_slaves, sync_gtids)
except UtilError:
self._apply_for_all_slaves(
active_slaves, 'star_sql_thread', multithreading=True
)
slaves_checksum = self._checksum_and_resume_rpl(not_active_slaves,
active_slaves, table)
if not self._get_master():
for slave_key, checksum in slaves_checksum:
if slave_key == self._base_server_key:
if checksum[0]:
success = True
base_server_checksum = checksum
slaves_checksum.remove((slave_key, checksum))
if self._verbosity > 2:
print("# Checksum on base server: "
"{0}".format(base_server_checksum[0][1]))
else:
print("# [SKIP] {0} checksum on base server - "
"{1}".format(table, checksum[1]))
break
if success and slaves_checksum:
for slave_key, checksum_res in slaves_checksum:
if checksum_res[0] is None:
print("# [SKIP] {0} checksum for Slave '{1}' - "
"{2}.".format(table, slave_key, checksum_res[1]))
else:
if self._verbosity > 2:
checksum_val = ': {0}'.format(checksum_res[0][1])
else:
checksum_val = ''
if checksum_res[0] != base_server_checksum[0]:
print("# [DIFF] {0} checksum for server '{1}'"
"{2}.".format(table, slave_key, checksum_val))
checksum_issues += 1
else:
print("# [OK] {0} checksum for server '{1}'"
"{2}.".format(table, slave_key, checksum_val))
return checksum_issues
def check_data_sync(self, options, data_to_include, data_to_exclude):
issues_count = 0
options['skip_views'] = True
options['skip_triggers'] = True
options['skip_procs'] = True
options['skip_funcs'] = True
options['skip_events'] = True
options['skip_grants'] = True
diff_options = {}
diff_options.update(options)
diff_options['quiet'] = True
diff_options['suppress_sql'] = True
diff_options['skip_table_opts'] = True
for slave_key in self._slaves:
if not self._get_slave(slave_key).check_version_compat(5, 6, 14):
raise UtilError(
"Server '{0}' version must be 5.6.14 or greater. Sync is "
"not supported for versions prior to 5.6.14 due to a "
"known issue with START SLAVE UNTIL and the "
"SQL_AFTER_GTIDS option.".format(slave_key))
print("# Checking data consistency.\n#")
base_srv_type = 'Master' if self._get_master() else 'Slave'
print("# Using {0} '{1}' as base server for comparison."
"".format(base_srv_type, self._base_server_key))
db_rows = self._base_server.get_all_databases()
base_server_dbs = set([row[0] for row in db_rows])
db_to_include = set()
if data_to_include:
db_to_include = set([db for db in data_to_include])
base_server_dbs = base_server_dbs & db_to_include
not_exist_db = db_to_include - base_server_dbs
if not_exist_db:
plurals = ('s', '') if len(not_exist_db) > 1 else ('', 'es')
print('# WARNING: specified database{0} to check do{1} not '
'exist on base server and will be skipped: '
'{2}.'.format(plurals[0], plurals[1],
", ".join(not_exist_db)))
db_to_exclude = set()
if data_to_exclude:
db_to_exclude = set(
[db for db in data_to_exclude if not data_to_exclude[db]]
)
base_server_dbs = base_server_dbs - db_to_exclude
slaves_except_base = [key for key in self._slaves
if key != self._base_server_key]
for slave_key in slaves_except_base:
slave = self._get_slave(slave_key)
db_rows = slave.get_all_databases()
slave_dbs = set([row[0] for row in db_rows])
if db_to_include:
slave_dbs = slave_dbs & db_to_include
if db_to_exclude:
slave_dbs = slave_dbs - db_to_exclude
self._slaves[slave_key]['databases'] = slave_dbs
dbs_not_in_base_srv = slave_dbs - base_server_dbs
filtered_dbs = set(
[db for db in dbs_not_in_base_srv
if self._is_rpl_filtered(db, slave=self._base_server_key)]
)
dbs_not_in_base_srv -= filtered_dbs
for db in filtered_dbs:
print("# [SKIP] Database '{0}' - filtered by replication "
"rule on base server.".format(db))
if dbs_not_in_base_srv:
issues_count += len(dbs_not_in_base_srv)
plural = 's' if len(dbs_not_in_base_srv) > 1 else ''
print("# [DIFF] Database{0} NOT on base server but found on "
"'{1}': {2}".format(plural, slave_key,
",".join(dbs_not_in_base_srv)))
filter_srv = None if self._get_master() else self._base_server_key
for db_name in base_server_dbs:
if self._is_rpl_filtered(db_name, slave=filter_srv):
print("# [SKIP] Database '{0}' check - filtered by "
"replication rule.".format(db_name))
continue
print("# Checking '{0}' database...".format(db_name))
slaves_to_check = {}
for slave_key in slaves_except_base:
if self._is_rpl_filtered(db_name, slave=slave_key):
print("# [SKIP] Database '{0}' check for '{1}' - filtered "
"by replication rule.".format(db_name, slave_key))
continue
if db_name in self._slaves[slave_key]['databases']:
slave_db = Database(self._get_slave(slave_key), db_name,
options)
slave_db.init()
slave_dic = {'db': slave_db}
in_both, in_basesrv, not_in_basesrv = get_common_objects(
self._base_server, self._get_slave(slave_key),
db_name, db_name, False, options)
if (data_to_include and db_name in data_to_include
and data_to_include[db_name]):
in_both = [
obj_row for obj_row in in_both
if obj_row[1][0] in data_to_include[db_name]
]
in_basesrv = [
obj_row for obj_row in in_basesrv
if obj_row[1][0] in data_to_include[db_name]
]
not_in_basesrv = [
obj_row for obj_row in not_in_basesrv
if obj_row[1][0] in data_to_include[db_name]
]
if (data_to_exclude and db_name in data_to_exclude
and data_to_exclude[db_name]):
in_both = [
obj_row for obj_row in in_both
if obj_row[1][0] not in data_to_exclude[db_name]
]
in_basesrv = [
obj_row for obj_row in in_basesrv
if obj_row[1][0] not in data_to_exclude[db_name]
]
not_in_basesrv = [
obj_row for obj_row in not_in_basesrv
if obj_row[1][0] not in data_to_exclude[db_name]
]
slave_dic['in_both'] = in_both
slave_dic['in_basesrv'] = in_basesrv
slaves_to_check[slave_key] = slave_dic
tbls_not_in = set(
[obj_row[1][0] for obj_row in not_in_basesrv
if obj_row[0] == 'TABLE']
)
filtered_tbls = set(
[tbl for tbl in tbls_not_in if self._is_rpl_filtered(
db_name, tbl_name=tbl, slave=self._base_server_key
)]
)
tbls_not_in -= filtered_tbls
for tbl in filtered_tbls:
print("# [SKIP] Table '{0}' - filtered by replication "
"rule on base server.".format(tbl))
if tbls_not_in:
plural = 's' if len(tbls_not_in) > 1 else ''
print("# [DIFF] Table{0} NOT on base server but "
"found on '{1}': "
"{2}".format(plural, slave_key,
", ".join(tbls_not_in)))
issues_count += len(tbls_not_in)
else:
print("# [DIFF] Database '{0}' NOT on server "
"'{1}'.".format(db_name, slave_key))
issues_count += 1
if slaves_to_check:
db = Database(self._base_server, db_name, options)
db.init()
for db_obj in db.get_next_object():
obj_type = db_obj[0]
obj_name = db_obj[1][0]
if (data_to_include and data_to_include[db_name]
and obj_name not in data_to_include[db_name]):
continue
if (data_to_exclude and data_to_exclude[db_name]
and obj_name in data_to_exclude[db_name]):
continue
checksum_task = []
for slave_key in slaves_to_check:
if (obj_type == 'TABLE'
and self._is_rpl_filtered(db_name, obj_name,
slave=slave_key)):
print("# [SKIP] Table '{0}' check for '{1}' - "
"filtered by replication rule."
"".format(obj_name, slave_key))
continue
slave_dic = slaves_to_check[slave_key]
if self._exist_in_obj_list(obj_name, obj_type,
slave_dic['in_basesrv']):
print("# [DIFF] {0} '{1}.{2}' NOT on server "
"'{3}'.".format(obj_type.capitalize(),
db_name, obj_name,
slave_key))
issues_count += 1
continue
q_obj = '{0}.{1}'.format(
quote_with_backticks(db_name),
quote_with_backticks(obj_name)
)
def_diff = diff_objects(
self._base_server, self._get_slave(slave_key),
q_obj, q_obj, diff_options, obj_type
)
if def_diff:
print("# [DIFF] {0} {1} definition is "
"different on '{2}'."
"".format(obj_type.capitalize(), q_obj,
slave_key))
issues_count += 1
if self._verbosity:
for diff in def_diff[3:]:
print("# {0}".format(diff))
continue
checksum_task.append(slave_key)
if checksum_task and obj_type == 'TABLE':
print("# - Checking '{0}' table data..."
"".format(obj_name))
num_issues = self._check_table_data_sync(q_obj,
checksum_task)
issues_count += num_issues
print("#\n#...done.\n#")
str_issues_count = 'No' if issues_count == 0 else str(issues_count)
plural = 's' if issues_count > 1 else ''
print("# SUMMARY: {0} data consistency issue{1} found.\n"
"#".format(str_issues_count, plural))
return issues_count
| true | true |
f72b84523234516e230f5570be8f20af24029148 | 29,913 | py | Python | rbc/remotejit.py | guilhermeleobas/rbc | 4b568b91c6ce3ef7727fee001169302c3803c4fd | [
"BSD-3-Clause"
] | null | null | null | rbc/remotejit.py | guilhermeleobas/rbc | 4b568b91c6ce3ef7727fee001169302c3803c4fd | [
"BSD-3-Clause"
] | null | null | null | rbc/remotejit.py | guilhermeleobas/rbc | 4b568b91c6ce3ef7727fee001169302c3803c4fd | [
"BSD-3-Clause"
] | null | null | null | """RemoteJIT client/server config functions
"""
__all__ = ['RemoteJIT', 'Signature', 'Caller']
import os
import inspect
import warnings
import ctypes
from contextlib import nullcontext
from . import irtools
from .typesystem import Type, get_signature
from .thrift import Server, Dispatcher, dispatchermethod, Data, Client
from .utils import get_local_ip
from .targetinfo import TargetInfo
from .rbclib import tracing_allocator
# XXX WIP: the OmnisciCompilerPipeline is no longer omnisci-specific because
# we support Arrays even without omnisci, so it must be renamed and moved
# somewhere elsef
from .omnisci_backend import OmnisciCompilerPipeline
def isfunctionlike(obj):
"""Return True if object is function alike.
"""
if obj is None or isinstance(obj, (Signature, list, tuple, str, Caller)):
return False
return True
def extract_templates(options):
"""Extract templates mapping data from options dictionary.
If options does not contain "templates", it will be constructed
from all unknown options that have list values. Otherwise, the
corresponding value is returned with no further processing of
options content.
Parameters
----------
options : dict
Returns
-------
options : dict
A copy of input without templates mapping data.
templates : dict
Templates mapping which is a collections of pairs of template
name and a list of concrete types. Template name cannot
correspond to a concrete type.
"""
known_options = ['devices', 'local']
new_options = {}
templates = options.get('templates')
if templates is not None:
new_options.update(options)
del new_options['templates']
else:
templates = {}
for k, v in options.items():
if (isinstance(k, str) and isinstance(v, list) and k not in known_options):
templates[k] = v
else:
new_options[k] = v
return new_options, templates
class Signature(object):
"""Signature decorator for Python functions.
A Signature decorator may contain many signature objects
representing the prototypes of functions.
Signature decorators are re-usable and composeable. For example:
.. highlight:: python
.. code-block:: python
rjit = RemoteJIT(host='localhost' port=6274)
# remotebinaryfunc is Signature instance
remotebinaryfunc = rjit('int32(int32, int32)',
'float32(float32, float32)', ...)
# add will be Caller instance
@remotebinaryfunc
def add(a, b):
return a + b
# sub will be Caller instance
@remotebinaryfunc
def sub(a, b):
return a - b
add(1, 2) # returns 3
sub(1.0, 2.0) # returns -1.0
"""
def __init__(self, remotejit):
assert isinstance(remotejit, RemoteJIT), type(remotejit)
self.remotejit = remotejit
self.signatures = []
self.signature_devices = {}
self.signature_templates = {}
@property
def debug(self):
return self.remotejit.debug
@property
def local(self):
sig = Signature(self.remotejit.local)
sig.signatures.extend(self.signatures)
assert not self.signature_devices
assert not self.signature_templates
return sig
def __str__(self):
lst = ["'%s'" % (s,) for s in self.signatures]
return '%s(%s)' % (self.__class__.__name__, ', '.join(lst))
def __call__(self, obj, **options):
"""Decorate signatures or a function.
Parameters
----------
obj : {str, Signature, function, ...}
Specify object that represents a function type.
Keyword parameters
------------------
devices : list
Specify device names for the given set of signatures.
templates : dict
Specify template types mapping.
Returns
-------
result : {Signature, Caller}
If obj is a function, return Caller. Otherwise return self
that is extended with new signatures from obj.
Note
----
The validity of the input argument is not checked here. This
is because the bit-size of certain C types (e.g. size_t, long,
etc) depend on the target device which information will be
available at the compile stage. The target dependent
signatures can be retrieved using
`signature.get_signatures()`.
"""
if obj is None:
return self
options, templates = extract_templates(options)
devices = options.get('devices')
if isinstance(obj, Signature):
self.signatures.extend(obj.signatures)
self.signature_devices.update(obj.signature_devices)
self.remotejit.discard_last_compile()
if devices is not None:
for s in obj.signatures:
self.signature_devices[s] = devices
assert not templates
for s in obj.signatures:
t = obj.signature_templates.get(s)
if t is not None:
self.signature_templates[s] = t
return self
if isinstance(obj, Caller):
# return new Caller with extended signatures set
assert obj.remotejit is self.remotejit
final = Signature(self.remotejit)
final(self) # copies the signatures from self to final
final(obj.signature) # copies the signatures from obj to final
assert devices is None
assert not templates
return Caller(obj.func, final)
if isfunctionlike(obj):
final = Signature(self.remotejit)
final(self) # copies the signatures from self to final
assert devices is None
assert not templates
return Caller(obj, final)
self.signatures.append(obj)
self.remotejit.discard_last_compile()
if devices is not None:
self.signature_devices[obj] = devices
if templates:
self.signature_templates[obj] = templates
return self
def best_match(self, func, atypes: tuple) -> Type:
"""Return function type from signatures that matches best with given
argument types.
If no match is found, raise TypeError.
Parameters
----------
atypes : Type-tuple
Specify a tuple of argument types.
Returns
-------
ftype : Type
Function type that arguments match best with given argument
types.
"""
ftype = None
match_penalty = None
available_types = self.normalized(func).signatures
for typ in available_types:
penalty = typ.match(atypes)
if penalty is not None:
if ftype is None or penalty < match_penalty:
ftype = typ
match_penalty = penalty
if ftype is None:
satypes = ', '.join(map(str, atypes))
available = '; '.join(map(str, available_types))
raise TypeError(
f'found no matching function type to given argument types'
f' `{satypes}`. Available function types: {available}')
return ftype
def normalized(self, func=None):
"""Return a copy of Signature object where all signatures are
normalized to Type instances using the current target device
information.
Parameters
----------
func : {None, callable}
Python function that annotations are attached to signature.
Returns
-------
signature : Signature
"""
signature = Signature(self.remotejit)
fsig = Type.fromcallable(func) if func is not None else None
nargs = fsig.arity if func is not None else None
target_info = TargetInfo()
for sig in self.signatures:
devices = self.signature_devices.get(sig)
if not target_info.check_enabled(devices):
if self.debug:
print(f'{type(self).__name__}.normalized: skipping {sig} as'
f' not supported by devices: {devices}')
continue
templates = self.signature_templates.get(sig, {})
sig = Type.fromobject(sig)
if not sig.is_complete:
warnings.warn(f'Incomplete signature {sig} will be ignored')
continue
if not sig.is_function:
raise ValueError(
'expected signature representing function type,'
f' got `{sig}`')
if nargs is None:
nargs = sig.arity
elif sig.arity != nargs:
raise ValueError(f'signature `{sig}` must have arity {nargs}'
f' but got {len(sig[1])}')
if fsig is not None:
sig.inherit_annotations(fsig)
if not sig.is_concrete:
for csig in sig.apply_templates(templates):
assert isinstance(csig, Type), (sig, csig, type(csig))
if csig not in signature.signatures:
signature.signatures.append(csig)
else:
if sig not in signature.signatures:
signature.signatures.append(sig)
if fsig is not None and fsig.is_complete:
if fsig not in signature.signatures:
signature.signatures.append(fsig)
return signature
class Caller(object):
"""Remote JIT caller, holds the decorated function that can be
executed remotely.
"""
def __init__(self, func, signature: Signature):
"""Construct remote JIT caller instance.
Parameters
----------
func : callable
Specify a Python function that is used as a template to
remotely JIT compiled functions.
signature : Signature
Specify a collection of signatures.
local : bool
When True, local process will be interpreted as
remote. Useful for debugging.
"""
self.remotejit = signature.remotejit
self.signature = signature
func = self.remotejit.preprocess_callable(func)
self.func = func
self.nargs = len(get_signature(func).parameters)
# Attributes used in RBC user-interface
self._is_compiled = set() # items are (fname, ftype)
self._client = None
self.remotejit.add_caller(self)
@property
def local(self):
"""Return Caller instance that executes function calls on the local
host. Useful for debugging.
"""
return Caller(self.func, self.signature.local)
def __repr__(self):
return '%s(%s, %s, local=%s)' % (type(self).__name__, self.func,
self.signature, self.local)
def __str__(self):
return self.describe()
def describe(self):
"""Return LLVM IRs of all target devices.
"""
lst = ['']
fid = 0
for device, target_info in self.remotejit.targets.items():
with Type.alias(**self.remotejit.typesystem_aliases):
with target_info:
lst.append(f'{device:-^80}')
signatures = self.get_signatures()
signatures_map = {}
for sig in signatures:
fid += 1
signatures_map[fid] = sig
llvm_module, succesful_fids = irtools.compile_to_LLVM(
[(self.func, signatures_map)],
target_info,
pipeline_class=OmnisciCompilerPipeline,
debug=self.remotejit.debug)
lst.append(str(llvm_module))
lst.append(f'{"":-^80}')
return '\n'.join(lst)
def get_signatures(self):
"""Return a list of normalized signatures for given target device.
"""
return self.signature.normalized(self.func).signatures
# RBC user-interface
def __call__(self, *arguments, **options):
"""Return the result of a remote JIT compiled function call.
"""
device = options.get('device')
targets = self.remotejit.targets
if device is None:
if len(targets) > 1:
raise TypeError(
f'specifying device is required when target has more than'
f' one device. Available devices: {", ".join(targets)}')
device = tuple(targets)[0]
target_info = targets[device]
with target_info:
atypes = tuple(map(Type.fromvalue, arguments))
ftype = self.signature.best_match(self.func, atypes)
key = self.func.__name__, ftype
if key not in self._is_compiled:
self.remotejit.remote_compile(self.func, ftype, target_info)
self._is_compiled.add(key)
return self.remotejit.remote_call(self.func, ftype, arguments)
class RemoteJIT(object):
"""RemoteJIT is a decorator generator for user functions to be
remotely JIT compiled.
To use, define
.. highlight:: python
.. code-block:: python
rjit = RemoteJIT(host='localhost', port=6274)
@rjit
def foo(a: int, b: int) -> int:
return a + b
@rjit('double(double, double)',
'int64(int64, int64)')
def bar(a, b):
return a + b
# Finally, call
c = foo(1, 2) # c = 3
b = bar(7.0, 1.0) # b = 8.0
The sum will be evaluated in the remote host.
"""
multiplexed = True
thrift_content = None
typesystem_aliases = dict()
def __init__(self, host='localhost', port=11532,
local=False, debug=False, use_tracing_allocator=False):
"""Construct remote JIT function decorator.
The decorator is re-usable for different functions.
Parameters
----------
host : str
Specify the host name of IP of JIT server
port : {int, str}
Specify the service port of the JIT server
local : bool
When True, use local client. Useful for debugging.
debug : bool
When True, output debug messages.
use_tracing_allocator : bool
When True, enable the automatic detection of memory leaks.
"""
if host == 'localhost':
host = get_local_ip()
if use_tracing_allocator and not local:
raise ValueError('use_tracing_allocator=True can be used only with local=True')
self.debug = debug
self.use_tracing_allocator = use_tracing_allocator
self.host = host
self.port = int(port)
self.server_process = None
# A collection of Caller instances. Each represents a function
# that have many argument type dependent implementations.
self._callers = []
self._last_compile = None
self._targets = None
if local:
self._client = LocalClient(debug=debug,
use_tracing_allocator=use_tracing_allocator)
else:
self._client = None
@property
def local(self):
localjit = type(self)(local=True, debug=self.debug)
localjit._callers.extend(self._callers)
return localjit
def add_caller(self, caller):
self._callers.append(caller)
self.discard_last_compile()
def get_callers(self):
return self._callers
def reset(self):
"""Drop all callers definitions and compilation results.
"""
self._callers.clear()
self.discard_last_compile()
@property
def have_last_compile(self):
"""Check if compile data exists.
See `set_last_compile` method for more information.
"""
return self._last_compile is not None
def discard_last_compile(self):
"""Discard compile data.
See `set_last_compile` method for more information.
"""
self._last_compile = None
def set_last_compile(self, compile_data):
"""Save compile data.
The caller is responsible for discarding previous compiler
data by calling `discard_last_compile` method.
Parameters
----------
compile_data : object
Compile data can be any Python object. When None, it is
interpreted as no compile data is available.
Notes
-----
The have/discard/set_last_compile methods provide a way to
avoid unnecessary compilations when the remote server supports
registration of compiled functions. The corresponding
`register` method is expected to use the following pattern:
.. code-block:: python
def register(self):
if self.have_last_compile:
return
<compile defined functions>
self.set_last_compile(<compilation results>)
The `discard_last_compile()` method is called when the compile
data becomes obsolete or needs to be discarded. For instance,
the compile data will be discarded when calling the following
methods: `reset`, `add_caller`. Note that the `add_caller`
call is triggered when applying the remotejit decorator to a
Python function to be compiled.
"""
assert self._last_compile is None
self._last_compile = compile_data
def get_pending_names(self):
"""Return the names of functions that have not been registered to the
remote server.
"""
names = set()
if not self.have_last_compile:
for caller in reversed(self.get_callers()):
names.add(caller.func.__name__)
return names
def retrieve_targets(self):
"""Retrieve target device information from remote client.
Redefine this method if remote client is not native.
Returns
-------
targets : dict
Map of target device names and informations.
"""
# TODO: rename thrift API targets to get_device_parameters?
response = self.client(remotejit=dict(targets=()))
targets = {}
for device, data in response['remotejit']['targets'].items():
targets[device] = TargetInfo.fromjson(data)
return targets
@property
def targets(self):
"""Return device-target_info mapping of the remote server.
"""
if self._targets is None:
self._targets = self.retrieve_targets()
return self._targets
def __call__(self, *signatures, **options):
"""Define a remote JIT function signatures and template.
Parameters
----------
signatures : tuple
Specify signatures of a remote JIT function, or a Python
function as a template from which the remote JIT function
will be compiled.
Keyword parameters
------------------
local : bool
devices : list
Specify device names for the given set of signatures.
templates : dict
Specify template types mapping.
Returns
-------
sig: {Signature, Caller}
Signature decorator or Caller
Notes
-----
The signatures can be strings in the following form:
"<return type>(<argument type 1>, <argument type 2>, ...)"
or any other object that can be converted to function type,
see `Type.fromobject` for more information.
"""
if options.get('local'):
s = Signature(self.local)
else:
s = Signature(self)
devices = options.get('devices')
options, templates = extract_templates(options)
for sig in signatures:
s = s(sig, devices=devices, templates=templates)
return s
def start_server(self, background=False):
"""Start remotejit server from client.
"""
thrift_file = os.path.join(os.path.dirname(__file__),
'remotejit.thrift')
print('staring rpc.thrift server: %s' % (thrift_file), end='',
flush=True)
if self.debug:
print(flush=True)
dispatcher = DebugDispatcherRJIT
else:
dispatcher = DispatcherRJIT
if background:
ps = Server.run_bg(dispatcher, thrift_file,
dict(host=self.host, port=self.port,
debug=self.debug))
self.server_process = ps
else:
Server.run(dispatcher, thrift_file,
dict(host=self.host, port=self.port,
debug=self.debug))
print('... rpc.thrift server stopped', flush=True)
def stop_server(self):
"""Stop remotejit server from client.
"""
if self.server_process is not None and self.server_process.is_alive():
print('... stopping rpc.thrift server')
self.server_process.terminate()
self.server_process = None
@property
def client(self):
"""Return remote host connection as Client instance.
"""
if self._client is None:
self._client = Client(
host=self.host,
port=self.port,
multiplexed=self.multiplexed,
thrift_content=self.thrift_content,
socket_timeout=60000)
return self._client
def remote_compile(self, func, ftype: Type, target_info: TargetInfo):
"""Remote compile function and signatures to machine code.
The input function `func` is compiled to LLVM IR module, the
LLVM IR module is sent to remote host where the remote host is
expected to complete the compilation process.
Return the corresponding LLVM IR module instance which may be
useful for debugging.
"""
if self.debug:
print(f'remote_compile({func}, {ftype})')
llvm_module, succesful_fids = irtools.compile_to_LLVM(
[(func, {0: ftype})],
target_info,
pipeline_class=OmnisciCompilerPipeline,
debug=self.debug)
ir = str(llvm_module)
mangled_signatures = ';'.join([s.mangle() for s in [ftype]])
response = self.client(remotejit=dict(
compile=(func.__name__, mangled_signatures, ir)))
assert response['remotejit']['compile'], response
return llvm_module
def remote_call(self, func, ftype: Type, arguments: tuple):
"""Call function remotely on given arguments.
The input function `func` is called remotely by sending the
arguments data to remote host where the previously compiled
function (see `remote_compile` method) is applied to the
arguments, and the result is returned to local process.
"""
if self.debug:
print(f'remote_call({func}, {ftype}, {arguments})')
fullname = func.__name__ + ftype.mangle()
response = self.client(remotejit=dict(call=(fullname, arguments)))
return response['remotejit']['call']
def python(self, statement):
"""Execute Python statement remotely.
"""
response = self.client(remotejit=dict(python=(statement,)))
return response['remotejit']['python']
def preprocess_callable(self, func):
"""Preprocess func to be used as a remotejit function definition.
Parameters
----------
func : callable
Returns
-------
func : callable
Preprocessed func.
"""
return func
class DispatcherRJIT(Dispatcher):
"""Implements remotejit service methods.
"""
def __init__(self, server, debug=False, use_tracing_allocator=False):
super().__init__(server, debug=debug)
self.use_tracing_allocator = use_tracing_allocator
self.compiled_functions = dict()
self.engines = dict()
self.python_globals = dict()
self.python_locals = dict()
@dispatchermethod
def targets(self) -> dict:
"""Retrieve target device information.
Returns
-------
info : dict
Map of target devices and their properties.
"""
if self.use_tracing_allocator:
target_info = TargetInfo.host(name='host_cpu_tracing_allocator',
use_tracing_allocator=True)
else:
target_info = TargetInfo.host()
target_info.set('has_numba', True)
target_info.set('has_cpython', True)
return dict(cpu=target_info.tojson())
@dispatchermethod
def compile(self, name: str, signatures: str, ir: str) -> int:
"""JIT compile function.
Parameters
----------
name : str
Specify the function name.
signatures : str
Specify semi-colon separated list of mangled signatures.
ir : str
Specify LLVM IR representation of the function.
"""
engine = irtools.compile_IR(ir)
for msig in signatures.split(';'):
sig = Type.demangle(msig)
ctypes_sig = sig.toctypes()
assert sig.is_function
if sig[0].is_aggregate:
raise RuntimeError(
f'Functions with aggregate return type values are not supported,'
f' got function `{name}` with `{sig}` signature')
fullname = name + msig
addr = engine.get_function_address(fullname)
if self.debug:
print(f'compile({name}, {sig}) -> {hex(addr)}')
# storing engine as the owner of function addresses
if addr:
self.compiled_functions[fullname] = engine, ctypes_sig(addr), sig, ctypes_sig
else:
warnings.warn('No compilation result for {name}|{sig=}')
return True
@dispatchermethod
def call(self, fullname: str, arguments: tuple) -> Data:
"""Call JIT compiled function
Parameters
----------
fullname : str
Specify the full name of the function that is in form
"<name><mangled signature>"
arguments : tuple
Specify the arguments to the function.
"""
# if we are using a tracing allocator, automatically detect memory leaks
# at each call.
if self.use_tracing_allocator:
leak_detector = tracing_allocator.new_leak_detector()
else:
leak_detector = nullcontext()
with leak_detector:
return self._do_call(fullname, arguments)
def _do_call(self, fullname, arguments):
if self.debug:
print(f'call({fullname}, {arguments})')
ef = self.compiled_functions.get(fullname)
if ef is None:
raise RuntimeError(
f'no such compiled function `{fullname}`. Available functions:\n'
f' {"; ".join(list(self.compiled_functions))}\n.')
sig = ef[2]
ctypes_sig = ef[3]
if len(arguments) == 0:
assert sig.arity == 1 and sig[1][0].is_void, sig
else:
assert len(arguments) == sig.arity, (len(arguments), sig.arity)
ctypes_arguments = []
for typ, ctypes_typ, value in zip(sig[1], ctypes_sig._argtypes_, arguments):
if typ.is_custom:
typ = typ.get_struct_type()
if typ.is_struct:
if isinstance(value, tuple):
member_values = [t.toctypes()(value[i]) for i, t in enumerate(typ)]
else:
member_values = [t.toctypes()(getattr(value, t.name)) for t in typ]
ctypes_arguments.extend(member_values)
elif typ.is_pointer:
if isinstance(value, ctypes.c_void_p):
value = ctypes.cast(value, ctypes_typ)
else:
value = ctypes.cast(value, ctypes_typ)
ctypes_arguments.append(value)
else:
ctypes_arguments.append(value)
r = ef[1](*ctypes_arguments)
if sig[0].is_pointer and sig[0][0].is_void and isinstance(r, int):
r = ctypes.c_void_p(r)
if self.debug:
print(f'-> {r}')
if hasattr(r, 'topython'):
return r.topython()
return r
@dispatchermethod
def python(self, statement: str) -> int:
"""Execute Python statement.
"""
if self.debug:
print(f'python({statement!r})')
exec(statement, self.python_globals, self.python_locals)
return True
class DebugDispatcherRJIT(DispatcherRJIT):
"""
Enables debug messages.
"""
debug = True
class LocalClient(object):
"""Pretender of thrift.Client.
All calls will be made in a local process. Useful for debbuging.
"""
def __init__(self, debug=False, use_tracing_allocator=False):
self.dispatcher = DispatcherRJIT(None, debug=debug,
use_tracing_allocator=use_tracing_allocator)
def __call__(self, **services):
results = {}
for service_name, query_dict in services.items():
results[service_name] = {}
for mthname, args in query_dict.items():
mth = getattr(self.dispatcher, mthname)
mth = inspect.unwrap(mth)
results[service_name][mthname] = mth(self.dispatcher, *args)
return results
| 34.2254 | 93 | 0.585063 |
__all__ = ['RemoteJIT', 'Signature', 'Caller']
import os
import inspect
import warnings
import ctypes
from contextlib import nullcontext
from . import irtools
from .typesystem import Type, get_signature
from .thrift import Server, Dispatcher, dispatchermethod, Data, Client
from .utils import get_local_ip
from .targetinfo import TargetInfo
from .rbclib import tracing_allocator
from .omnisci_backend import OmnisciCompilerPipeline
def isfunctionlike(obj):
if obj is None or isinstance(obj, (Signature, list, tuple, str, Caller)):
return False
return True
def extract_templates(options):
known_options = ['devices', 'local']
new_options = {}
templates = options.get('templates')
if templates is not None:
new_options.update(options)
del new_options['templates']
else:
templates = {}
for k, v in options.items():
if (isinstance(k, str) and isinstance(v, list) and k not in known_options):
templates[k] = v
else:
new_options[k] = v
return new_options, templates
class Signature(object):
def __init__(self, remotejit):
assert isinstance(remotejit, RemoteJIT), type(remotejit)
self.remotejit = remotejit
self.signatures = []
self.signature_devices = {}
self.signature_templates = {}
@property
def debug(self):
return self.remotejit.debug
@property
def local(self):
sig = Signature(self.remotejit.local)
sig.signatures.extend(self.signatures)
assert not self.signature_devices
assert not self.signature_templates
return sig
def __str__(self):
lst = ["'%s'" % (s,) for s in self.signatures]
return '%s(%s)' % (self.__class__.__name__, ', '.join(lst))
def __call__(self, obj, **options):
if obj is None:
return self
options, templates = extract_templates(options)
devices = options.get('devices')
if isinstance(obj, Signature):
self.signatures.extend(obj.signatures)
self.signature_devices.update(obj.signature_devices)
self.remotejit.discard_last_compile()
if devices is not None:
for s in obj.signatures:
self.signature_devices[s] = devices
assert not templates
for s in obj.signatures:
t = obj.signature_templates.get(s)
if t is not None:
self.signature_templates[s] = t
return self
if isinstance(obj, Caller):
assert obj.remotejit is self.remotejit
final = Signature(self.remotejit)
final(self)
final(obj.signature)
assert devices is None
assert not templates
return Caller(obj.func, final)
if isfunctionlike(obj):
final = Signature(self.remotejit)
final(self)
assert devices is None
assert not templates
return Caller(obj, final)
self.signatures.append(obj)
self.remotejit.discard_last_compile()
if devices is not None:
self.signature_devices[obj] = devices
if templates:
self.signature_templates[obj] = templates
return self
def best_match(self, func, atypes: tuple) -> Type:
ftype = None
match_penalty = None
available_types = self.normalized(func).signatures
for typ in available_types:
penalty = typ.match(atypes)
if penalty is not None:
if ftype is None or penalty < match_penalty:
ftype = typ
match_penalty = penalty
if ftype is None:
satypes = ', '.join(map(str, atypes))
available = '; '.join(map(str, available_types))
raise TypeError(
f'found no matching function type to given argument types'
f' `{satypes}`. Available function types: {available}')
return ftype
def normalized(self, func=None):
signature = Signature(self.remotejit)
fsig = Type.fromcallable(func) if func is not None else None
nargs = fsig.arity if func is not None else None
target_info = TargetInfo()
for sig in self.signatures:
devices = self.signature_devices.get(sig)
if not target_info.check_enabled(devices):
if self.debug:
print(f'{type(self).__name__}.normalized: skipping {sig} as'
f' not supported by devices: {devices}')
continue
templates = self.signature_templates.get(sig, {})
sig = Type.fromobject(sig)
if not sig.is_complete:
warnings.warn(f'Incomplete signature {sig} will be ignored')
continue
if not sig.is_function:
raise ValueError(
'expected signature representing function type,'
f' got `{sig}`')
if nargs is None:
nargs = sig.arity
elif sig.arity != nargs:
raise ValueError(f'signature `{sig}` must have arity {nargs}'
f' but got {len(sig[1])}')
if fsig is not None:
sig.inherit_annotations(fsig)
if not sig.is_concrete:
for csig in sig.apply_templates(templates):
assert isinstance(csig, Type), (sig, csig, type(csig))
if csig not in signature.signatures:
signature.signatures.append(csig)
else:
if sig not in signature.signatures:
signature.signatures.append(sig)
if fsig is not None and fsig.is_complete:
if fsig not in signature.signatures:
signature.signatures.append(fsig)
return signature
class Caller(object):
def __init__(self, func, signature: Signature):
self.remotejit = signature.remotejit
self.signature = signature
func = self.remotejit.preprocess_callable(func)
self.func = func
self.nargs = len(get_signature(func).parameters)
self._is_compiled = set()
self._client = None
self.remotejit.add_caller(self)
@property
def local(self):
return Caller(self.func, self.signature.local)
def __repr__(self):
return '%s(%s, %s, local=%s)' % (type(self).__name__, self.func,
self.signature, self.local)
def __str__(self):
return self.describe()
def describe(self):
lst = ['']
fid = 0
for device, target_info in self.remotejit.targets.items():
with Type.alias(**self.remotejit.typesystem_aliases):
with target_info:
lst.append(f'{device:-^80}')
signatures = self.get_signatures()
signatures_map = {}
for sig in signatures:
fid += 1
signatures_map[fid] = sig
llvm_module, succesful_fids = irtools.compile_to_LLVM(
[(self.func, signatures_map)],
target_info,
pipeline_class=OmnisciCompilerPipeline,
debug=self.remotejit.debug)
lst.append(str(llvm_module))
lst.append(f'{"":-^80}')
return '\n'.join(lst)
def get_signatures(self):
return self.signature.normalized(self.func).signatures
def __call__(self, *arguments, **options):
device = options.get('device')
targets = self.remotejit.targets
if device is None:
if len(targets) > 1:
raise TypeError(
f'specifying device is required when target has more than'
f' one device. Available devices: {", ".join(targets)}')
device = tuple(targets)[0]
target_info = targets[device]
with target_info:
atypes = tuple(map(Type.fromvalue, arguments))
ftype = self.signature.best_match(self.func, atypes)
key = self.func.__name__, ftype
if key not in self._is_compiled:
self.remotejit.remote_compile(self.func, ftype, target_info)
self._is_compiled.add(key)
return self.remotejit.remote_call(self.func, ftype, arguments)
class RemoteJIT(object):
multiplexed = True
thrift_content = None
typesystem_aliases = dict()
def __init__(self, host='localhost', port=11532,
local=False, debug=False, use_tracing_allocator=False):
if host == 'localhost':
host = get_local_ip()
if use_tracing_allocator and not local:
raise ValueError('use_tracing_allocator=True can be used only with local=True')
self.debug = debug
self.use_tracing_allocator = use_tracing_allocator
self.host = host
self.port = int(port)
self.server_process = None
self._callers = []
self._last_compile = None
self._targets = None
if local:
self._client = LocalClient(debug=debug,
use_tracing_allocator=use_tracing_allocator)
else:
self._client = None
@property
def local(self):
localjit = type(self)(local=True, debug=self.debug)
localjit._callers.extend(self._callers)
return localjit
def add_caller(self, caller):
self._callers.append(caller)
self.discard_last_compile()
def get_callers(self):
return self._callers
def reset(self):
self._callers.clear()
self.discard_last_compile()
@property
def have_last_compile(self):
return self._last_compile is not None
def discard_last_compile(self):
self._last_compile = None
def set_last_compile(self, compile_data):
assert self._last_compile is None
self._last_compile = compile_data
def get_pending_names(self):
names = set()
if not self.have_last_compile:
for caller in reversed(self.get_callers()):
names.add(caller.func.__name__)
return names
def retrieve_targets(self):
response = self.client(remotejit=dict(targets=()))
targets = {}
for device, data in response['remotejit']['targets'].items():
targets[device] = TargetInfo.fromjson(data)
return targets
@property
def targets(self):
if self._targets is None:
self._targets = self.retrieve_targets()
return self._targets
def __call__(self, *signatures, **options):
if options.get('local'):
s = Signature(self.local)
else:
s = Signature(self)
devices = options.get('devices')
options, templates = extract_templates(options)
for sig in signatures:
s = s(sig, devices=devices, templates=templates)
return s
def start_server(self, background=False):
thrift_file = os.path.join(os.path.dirname(__file__),
'remotejit.thrift')
print('staring rpc.thrift server: %s' % (thrift_file), end='',
flush=True)
if self.debug:
print(flush=True)
dispatcher = DebugDispatcherRJIT
else:
dispatcher = DispatcherRJIT
if background:
ps = Server.run_bg(dispatcher, thrift_file,
dict(host=self.host, port=self.port,
debug=self.debug))
self.server_process = ps
else:
Server.run(dispatcher, thrift_file,
dict(host=self.host, port=self.port,
debug=self.debug))
print('... rpc.thrift server stopped', flush=True)
def stop_server(self):
if self.server_process is not None and self.server_process.is_alive():
print('... stopping rpc.thrift server')
self.server_process.terminate()
self.server_process = None
@property
def client(self):
if self._client is None:
self._client = Client(
host=self.host,
port=self.port,
multiplexed=self.multiplexed,
thrift_content=self.thrift_content,
socket_timeout=60000)
return self._client
def remote_compile(self, func, ftype: Type, target_info: TargetInfo):
if self.debug:
print(f'remote_compile({func}, {ftype})')
llvm_module, succesful_fids = irtools.compile_to_LLVM(
[(func, {0: ftype})],
target_info,
pipeline_class=OmnisciCompilerPipeline,
debug=self.debug)
ir = str(llvm_module)
mangled_signatures = ';'.join([s.mangle() for s in [ftype]])
response = self.client(remotejit=dict(
compile=(func.__name__, mangled_signatures, ir)))
assert response['remotejit']['compile'], response
return llvm_module
def remote_call(self, func, ftype: Type, arguments: tuple):
if self.debug:
print(f'remote_call({func}, {ftype}, {arguments})')
fullname = func.__name__ + ftype.mangle()
response = self.client(remotejit=dict(call=(fullname, arguments)))
return response['remotejit']['call']
def python(self, statement):
response = self.client(remotejit=dict(python=(statement,)))
return response['remotejit']['python']
def preprocess_callable(self, func):
return func
class DispatcherRJIT(Dispatcher):
def __init__(self, server, debug=False, use_tracing_allocator=False):
super().__init__(server, debug=debug)
self.use_tracing_allocator = use_tracing_allocator
self.compiled_functions = dict()
self.engines = dict()
self.python_globals = dict()
self.python_locals = dict()
@dispatchermethod
def targets(self) -> dict:
if self.use_tracing_allocator:
target_info = TargetInfo.host(name='host_cpu_tracing_allocator',
use_tracing_allocator=True)
else:
target_info = TargetInfo.host()
target_info.set('has_numba', True)
target_info.set('has_cpython', True)
return dict(cpu=target_info.tojson())
@dispatchermethod
def compile(self, name: str, signatures: str, ir: str) -> int:
engine = irtools.compile_IR(ir)
for msig in signatures.split(';'):
sig = Type.demangle(msig)
ctypes_sig = sig.toctypes()
assert sig.is_function
if sig[0].is_aggregate:
raise RuntimeError(
f'Functions with aggregate return type values are not supported,'
f' got function `{name}` with `{sig}` signature')
fullname = name + msig
addr = engine.get_function_address(fullname)
if self.debug:
print(f'compile({name}, {sig}) -> {hex(addr)}')
if addr:
self.compiled_functions[fullname] = engine, ctypes_sig(addr), sig, ctypes_sig
else:
warnings.warn('No compilation result for {name}|{sig=}')
return True
@dispatchermethod
def call(self, fullname: str, arguments: tuple) -> Data:
if self.use_tracing_allocator:
leak_detector = tracing_allocator.new_leak_detector()
else:
leak_detector = nullcontext()
with leak_detector:
return self._do_call(fullname, arguments)
def _do_call(self, fullname, arguments):
if self.debug:
print(f'call({fullname}, {arguments})')
ef = self.compiled_functions.get(fullname)
if ef is None:
raise RuntimeError(
f'no such compiled function `{fullname}`. Available functions:\n'
f' {"; ".join(list(self.compiled_functions))}\n.')
sig = ef[2]
ctypes_sig = ef[3]
if len(arguments) == 0:
assert sig.arity == 1 and sig[1][0].is_void, sig
else:
assert len(arguments) == sig.arity, (len(arguments), sig.arity)
ctypes_arguments = []
for typ, ctypes_typ, value in zip(sig[1], ctypes_sig._argtypes_, arguments):
if typ.is_custom:
typ = typ.get_struct_type()
if typ.is_struct:
if isinstance(value, tuple):
member_values = [t.toctypes()(value[i]) for i, t in enumerate(typ)]
else:
member_values = [t.toctypes()(getattr(value, t.name)) for t in typ]
ctypes_arguments.extend(member_values)
elif typ.is_pointer:
if isinstance(value, ctypes.c_void_p):
value = ctypes.cast(value, ctypes_typ)
else:
value = ctypes.cast(value, ctypes_typ)
ctypes_arguments.append(value)
else:
ctypes_arguments.append(value)
r = ef[1](*ctypes_arguments)
if sig[0].is_pointer and sig[0][0].is_void and isinstance(r, int):
r = ctypes.c_void_p(r)
if self.debug:
print(f'-> {r}')
if hasattr(r, 'topython'):
return r.topython()
return r
@dispatchermethod
def python(self, statement: str) -> int:
if self.debug:
print(f'python({statement!r})')
exec(statement, self.python_globals, self.python_locals)
return True
class DebugDispatcherRJIT(DispatcherRJIT):
debug = True
class LocalClient(object):
def __init__(self, debug=False, use_tracing_allocator=False):
self.dispatcher = DispatcherRJIT(None, debug=debug,
use_tracing_allocator=use_tracing_allocator)
def __call__(self, **services):
results = {}
for service_name, query_dict in services.items():
results[service_name] = {}
for mthname, args in query_dict.items():
mth = getattr(self.dispatcher, mthname)
mth = inspect.unwrap(mth)
results[service_name][mthname] = mth(self.dispatcher, *args)
return results
| true | true |
f72b8471d48e46d56ffa1ffa9f9a1797ba37c49a | 521 | py | Python | objectivec/test/testdata/single_add_gen.py | kimjungwow/onnxruntime-riscv | 3c21abef03190648fe68a6633ac026725e6dfc58 | [
"MIT"
] | 18 | 2020-05-19T12:48:07.000Z | 2021-04-28T06:41:57.000Z | objectivec/test/testdata/single_add_gen.py | kimjungwow/onnxruntime-riscv | 3c21abef03190648fe68a6633ac026725e6dfc58 | [
"MIT"
] | 61 | 2021-05-31T05:15:41.000Z | 2022-03-29T22:34:33.000Z | objectivec/test/testdata/single_add_gen.py | ekmixon/onnxruntime | 1ab8a95eb6675afb6d0ad9d93600ef0022e2ddb5 | [
"MIT"
] | 9 | 2021-05-14T20:17:26.000Z | 2022-03-20T11:44:29.000Z | import onnx
from onnx import helper
from onnx import TensorProto
graph = helper.make_graph(
[ # nodes
helper.make_node("Add", ["A", "B"], ["C"], "Add"),
],
"SingleAdd", # name
[ # inputs
helper.make_tensor_value_info('A', TensorProto.FLOAT, [1]),
helper.make_tensor_value_info('B', TensorProto.FLOAT, [1]),
],
[ # outputs
helper.make_tensor_value_info('C', TensorProto.FLOAT, [1]),
])
model = helper.make_model(graph)
onnx.save(model, r'single_add.onnx')
| 26.05 | 67 | 0.619962 | import onnx
from onnx import helper
from onnx import TensorProto
graph = helper.make_graph(
[
helper.make_node("Add", ["A", "B"], ["C"], "Add"),
],
"SingleAdd",
[
helper.make_tensor_value_info('A', TensorProto.FLOAT, [1]),
helper.make_tensor_value_info('B', TensorProto.FLOAT, [1]),
],
[
helper.make_tensor_value_info('C', TensorProto.FLOAT, [1]),
])
model = helper.make_model(graph)
onnx.save(model, r'single_add.onnx')
| true | true |
f72b855250840e726278906521e0e8944c433f43 | 426 | py | Python | src/ploomber/sources/__init__.py | MarcoJHB/ploomber | 4849ef6915572f7934392443b4faf138172b9596 | [
"Apache-2.0"
] | 2,141 | 2020-02-14T02:34:34.000Z | 2022-03-31T22:43:20.000Z | src/ploomber/sources/__init__.py | MarcoJHB/ploomber | 4849ef6915572f7934392443b4faf138172b9596 | [
"Apache-2.0"
] | 660 | 2020-02-06T16:15:57.000Z | 2022-03-31T22:55:01.000Z | src/ploomber/sources/__init__.py | MarcoJHB/ploomber | 4849ef6915572f7934392443b4faf138172b9596 | [
"Apache-2.0"
] | 122 | 2020-02-14T18:53:05.000Z | 2022-03-27T22:33:24.000Z | from ploomber.sources.sources import (SQLScriptSource, SQLQuerySource,
GenericSource, FileSource, EmptySource)
from ploomber.sources.notebooksource import NotebookSource
from ploomber.sources.pythoncallablesource import PythonCallableSource
__all__ = [
'PythonCallableSource', 'SQLScriptSource', 'SQLQuerySource',
'GenericSource', 'FileSource', 'NotebookSource', 'EmptySource'
]
| 42.6 | 77 | 0.744131 | from ploomber.sources.sources import (SQLScriptSource, SQLQuerySource,
GenericSource, FileSource, EmptySource)
from ploomber.sources.notebooksource import NotebookSource
from ploomber.sources.pythoncallablesource import PythonCallableSource
__all__ = [
'PythonCallableSource', 'SQLScriptSource', 'SQLQuerySource',
'GenericSource', 'FileSource', 'NotebookSource', 'EmptySource'
]
| true | true |
f72b86570c3337610eec48f13a1fb108a1bdff30 | 21,794 | py | Python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_08_01/operations/_vpn_connections_operations.py | beltr0n/azure-sdk-for-python | 2f7fb8bee881b0fc0386a0ad5385755ceedd0453 | [
"MIT"
] | 2 | 2021-03-24T06:26:11.000Z | 2021-04-18T15:55:59.000Z | sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_08_01/operations/_vpn_connections_operations.py | beltr0n/azure-sdk-for-python | 2f7fb8bee881b0fc0386a0ad5385755ceedd0453 | [
"MIT"
] | 4 | 2019-04-17T17:57:49.000Z | 2020-04-24T21:11:22.000Z | sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_08_01/operations/_vpn_connections_operations.py | beltr0n/azure-sdk-for-python | 2f7fb8bee881b0fc0386a0ad5385755ceedd0453 | [
"MIT"
] | 2 | 2021-05-23T16:46:31.000Z | 2021-05-26T23:51:09.000Z | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRequest, HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
class VpnConnectionsOperations(object):
"""VpnConnectionsOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.network.v2019_08_01.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def get(
self,
resource_group_name, # type: str
gateway_name, # type: str
connection_name, # type: str
**kwargs # type: Any
):
# type: (...) -> "_models.VpnConnection"
"""Retrieves the details of a vpn connection.
:param resource_group_name: The resource group name of the VpnGateway.
:type resource_group_name: str
:param gateway_name: The name of the gateway.
:type gateway_name: str
:param connection_name: The name of the vpn connection.
:type connection_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: VpnConnection, or the result of cls(response)
:rtype: ~azure.mgmt.network.v2019_08_01.models.VpnConnection
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.VpnConnection"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-08-01"
accept = "application/json"
# Construct URL
url = self.get.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('VpnConnection', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'} # type: ignore
def _create_or_update_initial(
self,
resource_group_name, # type: str
gateway_name, # type: str
connection_name, # type: str
vpn_connection_parameters, # type: "_models.VpnConnection"
**kwargs # type: Any
):
# type: (...) -> "_models.VpnConnection"
cls = kwargs.pop('cls', None) # type: ClsType["_models.VpnConnection"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-08-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self._create_or_update_initial.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(vpn_connection_parameters, 'VpnConnection')
body_content_kwargs['content'] = body_content
request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('VpnConnection', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('VpnConnection', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'} # type: ignore
def begin_create_or_update(
self,
resource_group_name, # type: str
gateway_name, # type: str
connection_name, # type: str
vpn_connection_parameters, # type: "_models.VpnConnection"
**kwargs # type: Any
):
# type: (...) -> LROPoller["_models.VpnConnection"]
"""Creates a vpn connection to a scalable vpn gateway if it doesn't exist else updates the
existing connection.
:param resource_group_name: The resource group name of the VpnGateway.
:type resource_group_name: str
:param gateway_name: The name of the gateway.
:type gateway_name: str
:param connection_name: The name of the connection.
:type connection_name: str
:param vpn_connection_parameters: Parameters supplied to create or Update a VPN Connection.
:type vpn_connection_parameters: ~azure.mgmt.network.v2019_08_01.models.VpnConnection
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of LROPoller that returns either VpnConnection or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.network.v2019_08_01.models.VpnConnection]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.VpnConnection"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_or_update_initial(
resource_group_name=resource_group_name,
gateway_name=gateway_name,
connection_name=connection_name,
vpn_connection_parameters=vpn_connection_parameters,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('VpnConnection', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
}
if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'} # type: ignore
def _delete_initial(
self,
resource_group_name, # type: str
gateway_name, # type: str
connection_name, # type: str
**kwargs # type: Any
):
# type: (...) -> None
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-08-01"
accept = "application/json"
# Construct URL
url = self._delete_initial.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.delete(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'} # type: ignore
def begin_delete(
self,
resource_group_name, # type: str
gateway_name, # type: str
connection_name, # type: str
**kwargs # type: Any
):
# type: (...) -> LROPoller[None]
"""Deletes a vpn connection.
:param resource_group_name: The resource group name of the VpnGateway.
:type resource_group_name: str
:param gateway_name: The name of the gateway.
:type gateway_name: str
:param connection_name: The name of the connection.
:type connection_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType[None]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial(
resource_group_name=resource_group_name,
gateway_name=gateway_name,
connection_name=connection_name,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
if cls:
return cls(pipeline_response, None, {})
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
}
if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'} # type: ignore
def list_by_vpn_gateway(
self,
resource_group_name, # type: str
gateway_name, # type: str
**kwargs # type: Any
):
# type: (...) -> Iterable["_models.ListVpnConnectionsResult"]
"""Retrieves all vpn connections for a particular virtual wan vpn gateway.
:param resource_group_name: The resource group name of the VpnGateway.
:type resource_group_name: str
:param gateway_name: The name of the gateway.
:type gateway_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ListVpnConnectionsResult or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.network.v2019_08_01.models.ListVpnConnectionsResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ListVpnConnectionsResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-08-01"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list_by_vpn_gateway.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
def extract_data(pipeline_response):
deserialized = self._deserialize('ListVpnConnectionsResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list_by_vpn_gateway.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections'} # type: ignore
| 49.307692 | 220 | 0.663944 |
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRequest, HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
if TYPE_CHECKING:
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
class VpnConnectionsOperations(object):
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def get(
self,
resource_group_name,
gateway_name,
connection_name,
**kwargs
):
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-08-01"
accept = "application/json"
url = self.get.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
header_parameters = {}
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('VpnConnection', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'}
def _create_or_update_initial(
self,
resource_group_name,
gateway_name,
connection_name,
vpn_connection_parameters,
**kwargs
):
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-08-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
url = self._create_or_update_initial.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
header_parameters = {}
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {}
body_content = self._serialize.body(vpn_connection_parameters, 'VpnConnection')
body_content_kwargs['content'] = body_content
request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('VpnConnection', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('VpnConnection', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'}
def begin_create_or_update(
self,
resource_group_name,
gateway_name,
connection_name,
vpn_connection_parameters,
**kwargs
):
polling = kwargs.pop('polling', True)
cls = kwargs.pop('cls', None)
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None)
if cont_token is None:
raw_result = self._create_or_update_initial(
resource_group_name=resource_group_name,
gateway_name=gateway_name,
connection_name=connection_name,
vpn_connection_parameters=vpn_connection_parameters,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('VpnConnection', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
}
if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'}
def _delete_initial(
self,
resource_group_name,
gateway_name,
connection_name,
**kwargs
):
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-08-01"
accept = "application/json"
url = self._delete_initial.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
header_parameters = {}
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.delete(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'}
def begin_delete(
self,
resource_group_name,
gateway_name,
connection_name,
**kwargs
):
polling = kwargs.pop('polling', True)
cls = kwargs.pop('cls', None)
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None)
if cont_token is None:
raw_result = self._delete_initial(
resource_group_name=resource_group_name,
gateway_name=gateway_name,
connection_name=connection_name,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
if cls:
return cls(pipeline_response, None, {})
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
}
if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'}
def list_by_vpn_gateway(
self,
resource_group_name,
gateway_name,
**kwargs
):
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-08-01"
accept = "application/json"
def prepare_request(next_link=None):
header_parameters = {}
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
url = self.list_by_vpn_gateway.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {}
request = self._client.get(url, query_parameters, header_parameters)
return request
def extract_data(pipeline_response):
deserialized = self._deserialize('ListVpnConnectionsResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list_by_vpn_gateway.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections'}
| true | true |
f72b87aee4ad934ef97feead34023c03afde9798 | 1,084 | py | Python | cloudfunc/client.py | jadbin/cloudfunc | 6d54bd993a784d20baba34e8ff897401efb12a22 | [
"MIT"
] | 2 | 2020-08-03T11:39:29.000Z | 2020-08-05T07:09:17.000Z | cloudfunc/client.py | jadbin/cloudfunc | 6d54bd993a784d20baba34e8ff897401efb12a22 | [
"MIT"
] | null | null | null | cloudfunc/client.py | jadbin/cloudfunc | 6d54bd993a784d20baba34e8ff897401efb12a22 | [
"MIT"
] | null | null | null | # coding=utf-8
import os
import pickle
import requests
from .errors import CloudFuncError
class CloudFuncClient:
def __init__(self, serve_address: str = None):
if serve_address is None:
serve_address = os.environ['CLOUDFUNC_SERVE_ADDRESS']
assert serve_address is not None, 'cloudfunc-serve address is not given'
self.serve_address = serve_address
self.session = requests.Session()
def run(self, cloud_func_name: str, *args, **kwargs):
data = pickle.dumps((args, kwargs))
try:
resp = self.session.post(
f'http://{self.serve_address}/cloud-funcs/run',
params={'name': cloud_func_name},
data=data,
headers={'Content-Type': 'application/octet-stream'}
)
except Exception as e:
raise CloudFuncError(e)
else:
try:
resp.raise_for_status()
except requests.HTTPError:
raise CloudFuncError(resp.text)
return pickle.loads(resp.content)
| 30.111111 | 80 | 0.595941 |
import os
import pickle
import requests
from .errors import CloudFuncError
class CloudFuncClient:
def __init__(self, serve_address: str = None):
if serve_address is None:
serve_address = os.environ['CLOUDFUNC_SERVE_ADDRESS']
assert serve_address is not None, 'cloudfunc-serve address is not given'
self.serve_address = serve_address
self.session = requests.Session()
def run(self, cloud_func_name: str, *args, **kwargs):
data = pickle.dumps((args, kwargs))
try:
resp = self.session.post(
f'http://{self.serve_address}/cloud-funcs/run',
params={'name': cloud_func_name},
data=data,
headers={'Content-Type': 'application/octet-stream'}
)
except Exception as e:
raise CloudFuncError(e)
else:
try:
resp.raise_for_status()
except requests.HTTPError:
raise CloudFuncError(resp.text)
return pickle.loads(resp.content)
| true | true |
f72b87c6dad7aa35765c68a88cffd6f561ea82e6 | 3,138 | py | Python | tests/beta_tests/test_shorted_ipv6_address.py | the-zebulan/CodeWars | 1eafd1247d60955a5dfb63e4882e8ce86019f43a | [
"MIT"
] | 40 | 2016-03-09T12:26:20.000Z | 2022-03-23T08:44:51.000Z | tests/beta_tests/test_shorted_ipv6_address.py | akalynych/CodeWars | 1eafd1247d60955a5dfb63e4882e8ce86019f43a | [
"MIT"
] | null | null | null | tests/beta_tests/test_shorted_ipv6_address.py | akalynych/CodeWars | 1eafd1247d60955a5dfb63e4882e8ce86019f43a | [
"MIT"
] | 36 | 2016-11-07T19:59:58.000Z | 2022-03-31T11:18:27.000Z | import unittest
from katas.beta.shorten_ipv6_address import shorten
class ShortenIPv6TestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(shorten('2642:0006:0006:0000:0000:0000:0000:9147'),
'2642:6:6::9147')
def test_equal_2(self):
self.assertEqual(shorten('1234:0000:5678:0000:0000:90AB:0000:CDEF'),
'1234:0:5678::90AB:0:CDEF')
def test_equal_3(self):
self.assertEqual(shorten('1111:0000:0000:2222:0000:0000:3333:4444'),
'1111::2222:0:0:3333:4444')
def test_equal_4(self):
self.assertEqual(shorten('A43B:1CF6:541C:98AA:CC43:1092:E932:90AD'),
'A43B:1CF6:541C:98AA:CC43:1092:E932:90AD')
def test_equal_5(self):
self.assertEqual(shorten('9000:B004:C13A:594C:19CD:102D:394F:FCD1'),
'9000:B004:C13A:594C:19CD:102D:394F:FCD1')
def test_equal_6(self):
self.assertEqual(shorten('043B:00F6:541C:08AA:0003:1092:000D:90AD'),
'43B:F6:541C:8AA:3:1092:D:90AD')
def test_equal_7(self):
self.assertEqual(shorten('9000:0004:000A:094C:00CD:102D:394F:0001'),
'9000:4:A:94C:CD:102D:394F:1')
def test_equal_8(self):
self.assertEqual(shorten('3BDF:000E:0004:0ECD:0000:0009:3C7F:734F'),
'3BDF:E:4:ECD::9:3C7F:734F')
def test_equal_9(self):
self.assertEqual(shorten('0388:0B7B:004D:0000:00D3:FDC1:E0E8:08D7'),
'388:B7B:4D::D3:FDC1:E0E8:8D7')
def test_equal_10(self):
self.assertEqual(shorten('0018:000A:0F0C:10B2:668D:0000:0000:009B'),
'18:A:F0C:10B2:668D::9B')
def test_equal_11(self):
self.assertEqual(shorten('00AF:0000:0000:0000:0000:704E:EC20:3DAA'),
'AF::704E:EC20:3DAA')
def test_equal_12(self):
self.assertEqual(shorten('A2A5:03DB:0000:60A5:0000:0005:BD22:0000'),
'A2A5:3DB::60A5:0:5:BD22:0')
def test_equal_13(self):
self.assertEqual(shorten('0000:0FBA:0000:0000:0000:0000:057E:AFFD'),
'0:FBA::57E:AFFD')
def test_equal_14(self):
self.assertEqual(shorten('0000:0000:0000:0000:0000:0C30:00DA:29CB'),
'::C30:DA:29CB')
def test_equal_15(self):
self.assertEqual(shorten('97CA:4C84:B62B:C3A8:00F4:0000:0000:0000'),
'97CA:4C84:B62B:C3A8:F4::')
def test_equal_16(self):
self.assertEqual(shorten('0000:0391:F08E:0F28:0000:0003:0037:0006'),
'::391:F08E:F28:0:3:37:6')
def test_equal_17(self):
self.assertEqual(shorten('00C8:0000:0243:0050:ED26:008F:0000:0000'),
'C8:0:243:50:ED26:8F::')
def test_equal_18(self):
self.assertEqual(shorten('0000:0000:0001:0007:0F63:0000:4FF7:0000'),
'::1:7:F63:0:4FF7:0')
def test_equal_19(self):
self.assertEqual(shorten('0000:0000:6B6F:63B3:0000:0001:0000:0000'),
'::6B6F:63B3:0:1:0:0')
| 38.268293 | 76 | 0.581899 | import unittest
from katas.beta.shorten_ipv6_address import shorten
class ShortenIPv6TestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(shorten('2642:0006:0006:0000:0000:0000:0000:9147'),
'2642:6:6::9147')
def test_equal_2(self):
self.assertEqual(shorten('1234:0000:5678:0000:0000:90AB:0000:CDEF'),
'1234:0:5678::90AB:0:CDEF')
def test_equal_3(self):
self.assertEqual(shorten('1111:0000:0000:2222:0000:0000:3333:4444'),
'1111::2222:0:0:3333:4444')
def test_equal_4(self):
self.assertEqual(shorten('A43B:1CF6:541C:98AA:CC43:1092:E932:90AD'),
'A43B:1CF6:541C:98AA:CC43:1092:E932:90AD')
def test_equal_5(self):
self.assertEqual(shorten('9000:B004:C13A:594C:19CD:102D:394F:FCD1'),
'9000:B004:C13A:594C:19CD:102D:394F:FCD1')
def test_equal_6(self):
self.assertEqual(shorten('043B:00F6:541C:08AA:0003:1092:000D:90AD'),
'43B:F6:541C:8AA:3:1092:D:90AD')
def test_equal_7(self):
self.assertEqual(shorten('9000:0004:000A:094C:00CD:102D:394F:0001'),
'9000:4:A:94C:CD:102D:394F:1')
def test_equal_8(self):
self.assertEqual(shorten('3BDF:000E:0004:0ECD:0000:0009:3C7F:734F'),
'3BDF:E:4:ECD::9:3C7F:734F')
def test_equal_9(self):
self.assertEqual(shorten('0388:0B7B:004D:0000:00D3:FDC1:E0E8:08D7'),
'388:B7B:4D::D3:FDC1:E0E8:8D7')
def test_equal_10(self):
self.assertEqual(shorten('0018:000A:0F0C:10B2:668D:0000:0000:009B'),
'18:A:F0C:10B2:668D::9B')
def test_equal_11(self):
self.assertEqual(shorten('00AF:0000:0000:0000:0000:704E:EC20:3DAA'),
'AF::704E:EC20:3DAA')
def test_equal_12(self):
self.assertEqual(shorten('A2A5:03DB:0000:60A5:0000:0005:BD22:0000'),
'A2A5:3DB::60A5:0:5:BD22:0')
def test_equal_13(self):
self.assertEqual(shorten('0000:0FBA:0000:0000:0000:0000:057E:AFFD'),
'0:FBA::57E:AFFD')
def test_equal_14(self):
self.assertEqual(shorten('0000:0000:0000:0000:0000:0C30:00DA:29CB'),
'::C30:DA:29CB')
def test_equal_15(self):
self.assertEqual(shorten('97CA:4C84:B62B:C3A8:00F4:0000:0000:0000'),
'97CA:4C84:B62B:C3A8:F4::')
def test_equal_16(self):
self.assertEqual(shorten('0000:0391:F08E:0F28:0000:0003:0037:0006'),
'::391:F08E:F28:0:3:37:6')
def test_equal_17(self):
self.assertEqual(shorten('00C8:0000:0243:0050:ED26:008F:0000:0000'),
'C8:0:243:50:ED26:8F::')
def test_equal_18(self):
self.assertEqual(shorten('0000:0000:0001:0007:0F63:0000:4FF7:0000'),
'::1:7:F63:0:4FF7:0')
def test_equal_19(self):
self.assertEqual(shorten('0000:0000:6B6F:63B3:0000:0001:0000:0000'),
'::6B6F:63B3:0:1:0:0')
| true | true |
f72b8813889944a82a8a131828595a1454d68cd2 | 116,092 | py | Python | electrum/lnworker.py | vhn0912/electrum | a65b97d25c3e37c0e77484f1846e537f9d5be274 | [
"MIT"
] | 1 | 2022-02-24T14:05:49.000Z | 2022-02-24T14:05:49.000Z | electrum/lnworker.py | vhn0912/electrum | a65b97d25c3e37c0e77484f1846e537f9d5be274 | [
"MIT"
] | null | null | null | electrum/lnworker.py | vhn0912/electrum | a65b97d25c3e37c0e77484f1846e537f9d5be274 | [
"MIT"
] | null | null | null | # Copyright (C) 2018 The Electrum developers
# Distributed under the MIT software license, see the accompanying
# file LICENCE or http://www.opensource.org/licenses/mit-license.php
import asyncio
import os
from decimal import Decimal
import random
import time
from typing import (Optional, Sequence, Tuple, List, Set, Dict, TYPE_CHECKING,
NamedTuple, Union, Mapping, Any, Iterable, AsyncGenerator, DefaultDict)
import threading
import socket
import aiohttp
import json
from datetime import datetime, timezone
from functools import partial
from collections import defaultdict
import concurrent
from concurrent import futures
import urllib.parse
import dns.resolver
import dns.exception
from aiorpcx import run_in_thread, NetAddress, ignore_after
from . import constants, util
from . import keystore
from .util import profiler, chunks, OldTaskGroup
from .invoices import PR_TYPE_LN, PR_UNPAID, PR_EXPIRED, PR_PAID, PR_INFLIGHT, PR_FAILED, PR_ROUTING, LNInvoice, LN_EXPIRY_NEVER
from .util import NetworkRetryManager, JsonRPCClient
from .lnutil import LN_MAX_FUNDING_SAT
from .keystore import BIP32_KeyStore
from .bitcoin import COIN
from .bitcoin import opcodes, make_op_return, address_to_scripthash
from .transaction import Transaction
from .transaction import get_script_type_from_output_script
from .crypto import sha256
from .bip32 import BIP32Node
from .util import bh2u, bfh, InvoiceError, resolve_dns_srv, is_ip_address, log_exceptions
from .crypto import chacha20_encrypt, chacha20_decrypt
from .util import ignore_exceptions, make_aiohttp_session
from .util import timestamp_to_datetime, random_shuffled_copy
from .util import MyEncoder, is_private_netaddress, UnrelatedTransactionException
from .logging import Logger
from .lntransport import LNTransport, LNResponderTransport, LNTransportBase
from .lnpeer import Peer, LN_P2P_NETWORK_TIMEOUT
from .lnaddr import lnencode, LnAddr, lndecode
from .ecc import der_sig_from_sig_string
from .lnchannel import Channel, AbstractChannel
from .lnchannel import ChannelState, PeerState, HTLCWithStatus
from .lnrater import LNRater
from . import lnutil
from .lnutil import funding_output_script
from .bitcoin import redeem_script_to_address
from .lnutil import (Outpoint, LNPeerAddr,
get_compressed_pubkey_from_bech32, extract_nodeid,
PaymentFailure, split_host_port, ConnStringFormatError,
generate_keypair, LnKeyFamily, LOCAL, REMOTE,
MIN_FINAL_CLTV_EXPIRY_FOR_INVOICE,
NUM_MAX_EDGES_IN_PAYMENT_PATH, SENT, RECEIVED, HTLCOwner,
UpdateAddHtlc, Direction, LnFeatures, ShortChannelID,
HtlcLog, derive_payment_secret_from_payment_preimage,
NoPathFound, InvalidGossipMsg)
from .lnutil import ln_dummy_address, ln_compare_features, IncompatibleLightningFeatures
from .transaction import PartialTxOutput, PartialTransaction, PartialTxInput
from .lnonion import OnionFailureCode, OnionRoutingFailure
from .lnmsg import decode_msg
from .i18n import _
from .lnrouter import (RouteEdge, LNPaymentRoute, LNPaymentPath, is_route_sane_to_use,
NoChannelPolicy, LNPathInconsistent)
from .address_synchronizer import TX_HEIGHT_LOCAL
from . import lnsweep
from .lnwatcher import LNWalletWatcher
from .crypto import pw_encode_with_version_and_mac, pw_decode_with_version_and_mac
from .lnutil import ImportedChannelBackupStorage, OnchainChannelBackupStorage
from .lnchannel import ChannelBackup
from .channel_db import UpdateStatus
from .channel_db import get_mychannel_info, get_mychannel_policy
from .submarine_swaps import SwapManager
from .channel_db import ChannelInfo, Policy
from .mpp_split import suggest_splits
from .trampoline import create_trampoline_route_and_onion, TRAMPOLINE_FEES, is_legacy_relay
if TYPE_CHECKING:
from .network import Network
from .wallet import Abstract_Wallet
from .channel_db import ChannelDB
from .simple_config import SimpleConfig
SAVED_PR_STATUS = [PR_PAID, PR_UNPAID] # status that are persisted
NUM_PEERS_TARGET = 4
# onchain channel backup data
CB_VERSION = 0
CB_MAGIC_BYTES = bytes([0, 0, 0, CB_VERSION])
FALLBACK_NODE_LIST_TESTNET = (
LNPeerAddr(host='203.132.95.10', port=9735, pubkey=bfh('038863cf8ab91046230f561cd5b386cbff8309fa02e3f0c3ed161a3aeb64a643b9')),
LNPeerAddr(host='2401:d002:4402:0:bf1d:986a:7598:6d49', port=9735, pubkey=bfh('038863cf8ab91046230f561cd5b386cbff8309fa02e3f0c3ed161a3aeb64a643b9')),
LNPeerAddr(host='50.116.3.223', port=9734, pubkey=bfh('03236a685d30096b26692dce0cf0fa7c8528bdf61dbf5363a3ef6d5c92733a3016')),
LNPeerAddr(host='3.16.119.191', port=9735, pubkey=bfh('03d5e17a3c213fe490e1b0c389f8cfcfcea08a29717d50a9f453735e0ab2a7c003')),
LNPeerAddr(host='34.250.234.192', port=9735, pubkey=bfh('03933884aaf1d6b108397e5efe5c86bcf2d8ca8d2f700eda99db9214fc2712b134')),
LNPeerAddr(host='88.99.209.230', port=9735, pubkey=bfh('0260d9119979caedc570ada883ff614c6efb93f7f7382e25d73ecbeba0b62df2d7')),
LNPeerAddr(host='160.16.233.215', port=9735, pubkey=bfh('023ea0a53af875580899da0ab0a21455d9c19160c4ea1b7774c9d4be6810b02d2c')),
LNPeerAddr(host='197.155.6.173', port=9735, pubkey=bfh('0269a94e8b32c005e4336bfb743c08a6e9beb13d940d57c479d95c8e687ccbdb9f')),
LNPeerAddr(host='2c0f:fb18:406::4', port=9735, pubkey=bfh('0269a94e8b32c005e4336bfb743c08a6e9beb13d940d57c479d95c8e687ccbdb9f')),
LNPeerAddr(host='163.172.94.64', port=9735, pubkey=bfh('030f0bf260acdbd3edcad84d7588ec7c5df4711e87e6a23016f989b8d3a4147230')),
LNPeerAddr(host='23.237.77.12', port=9735, pubkey=bfh('02312627fdf07fbdd7e5ddb136611bdde9b00d26821d14d94891395452f67af248')),
LNPeerAddr(host='197.155.6.172', port=9735, pubkey=bfh('02ae2f22b02375e3e9b4b4a2db4f12e1b50752b4062dbefd6e01332acdaf680379')),
LNPeerAddr(host='2c0f:fb18:406::3', port=9735, pubkey=bfh('02ae2f22b02375e3e9b4b4a2db4f12e1b50752b4062dbefd6e01332acdaf680379')),
LNPeerAddr(host='23.239.23.44', port=9740, pubkey=bfh('034fe52e98a0e9d3c21b767e1b371881265d8c7578c21f5afd6d6438da10348b36')),
LNPeerAddr(host='2600:3c01::f03c:91ff:fe05:349c', port=9740, pubkey=bfh('034fe52e98a0e9d3c21b767e1b371881265d8c7578c21f5afd6d6438da10348b36')),
)
FALLBACK_NODE_LIST_MAINNET = [
LNPeerAddr(host='172.81.181.3', port=9735, pubkey=bfh('0214382bdce7750dfcb8126df8e2b12de38536902dc36abcebdaeefdeca1df8284')),
LNPeerAddr(host='35.230.100.60', port=9735, pubkey=bfh('023f5e3582716bed96f6f26cfcd8037e07474d7b4743afdc8b07e692df63464d7e')),
LNPeerAddr(host='40.69.71.114', port=9735, pubkey=bfh('028303182c9885da93b3b25c9621d22cf34475e63c123942e402ab530c0556e675')),
LNPeerAddr(host='94.177.171.73', port=9735, pubkey=bfh('0276e09a267592e7451a939c932cf685f0754de382a3ca85d2fb3a864d4c365ad5')),
LNPeerAddr(host='34.236.113.58', port=9735, pubkey=bfh('02fa50c72ee1e2eb5f1b6d9c3032080c4c864373c4201dfa2966aa34eee1051f97')),
LNPeerAddr(host='52.50.244.44', port=9735, pubkey=bfh('030c3f19d742ca294a55c00376b3b355c3c90d61c6b6b39554dbc7ac19b141c14f')),
LNPeerAddr(host='157.245.68.47', port=9735, pubkey=bfh('03c2abfa93eacec04721c019644584424aab2ba4dff3ac9bdab4e9c97007491dda')),
LNPeerAddr(host='18.221.23.28', port=9735, pubkey=bfh('03abf6f44c355dec0d5aa155bdbdd6e0c8fefe318eff402de65c6eb2e1be55dc3e')),
LNPeerAddr(host='52.224.178.244', port=9735, pubkey=bfh('026b105ac13212c48714c6be9b11577a9ce10f10e1c88a45ce217e6331209faf8b')),
LNPeerAddr(host='34.239.230.56', port=9735, pubkey=bfh('03864ef025fde8fb587d989186ce6a4a186895ee44a926bfc370e2c366597a3f8f')),
LNPeerAddr(host='46.229.165.136', port=9735, pubkey=bfh('0390b5d4492dc2f5318e5233ab2cebf6d48914881a33ef6a9c6bcdbb433ad986d0')),
LNPeerAddr(host='157.230.28.160', port=9735, pubkey=bfh('0279c22ed7a068d10dc1a38ae66d2d6461e269226c60258c021b1ddcdfe4b00bc4')),
LNPeerAddr(host='74.108.13.152', port=9735, pubkey=bfh('0331f80652fb840239df8dc99205792bba2e559a05469915804c08420230e23c7c')),
LNPeerAddr(host='167.172.44.148', port=9735, pubkey=bfh('0395033b252c6f40e3756984162d68174e2bd8060a129c0d3462a9370471c6d28f')),
LNPeerAddr(host='138.68.14.104', port=9735, pubkey=bfh('03bb88ccc444534da7b5b64b4f7b15e1eccb18e102db0e400d4b9cfe93763aa26d')),
LNPeerAddr(host='3.124.63.44', port=9735, pubkey=bfh('0242a4ae0c5bef18048fbecf995094b74bfb0f7391418d71ed394784373f41e4f3')),
LNPeerAddr(host='2001:470:8:2e1::43', port=9735, pubkey=bfh('03baa70886d9200af0ffbd3f9e18d96008331c858456b16e3a9b41e735c6208fef')),
LNPeerAddr(host='2601:186:c100:6bcd:219:d1ff:fe75:dc2f', port=9735, pubkey=bfh('0298f6074a454a1f5345cb2a7c6f9fce206cd0bf675d177cdbf0ca7508dd28852f')),
LNPeerAddr(host='2001:41d0:e:734::1', port=9735, pubkey=bfh('03a503d8e30f2ff407096d235b5db63b4fcf3f89a653acb6f43d3fc492a7674019')),
LNPeerAddr(host='2a01:4f9:2b:2254::2', port=9735, pubkey=bfh('02f3069a342ae2883a6f29e275f06f28a56a6ea2e2d96f5888a3266444dcf542b6')),
LNPeerAddr(host='2a02:8070:24c1:100:528c:2997:6dbc:a054', port=9735, pubkey=bfh('02a45def9ae014fdd2603dd7033d157faa3a55a72b06a63ae22ef46d9fafdc6e8d')),
LNPeerAddr(host='2600:3c01::f03c:91ff:fe05:349c', port=9736, pubkey=bfh('02731b798b39a09f9f14e90ee601afb6ebb796d6e5797de14582a978770b33700f')),
LNPeerAddr(host='2a00:8a60:e012:a00::21', port=9735, pubkey=bfh('027ce055380348d7812d2ae7745701c9f93e70c1adeb2657f053f91df4f2843c71')),
LNPeerAddr(host='2604:a880:400:d1::8bd:1001', port=9735, pubkey=bfh('03649c72a4816f0cd546f84aafbd657e92a30ab474de7ab795e8b5650a427611f7')),
LNPeerAddr(host='2a01:4f8:c0c:7b31::1', port=9735, pubkey=bfh('02c16cca44562b590dd279c942200bdccfd4f990c3a69fad620c10ef2f8228eaff')),
LNPeerAddr(host='2001:41d0:1:b40d::1', port=9735, pubkey=bfh('026726a4b043d413b45b334876d17b8a98848129604429ec65532ba286a42efeac')),
]
from .trampoline import trampolines_by_id, hardcoded_trampoline_nodes, is_hardcoded_trampoline
class PaymentInfo(NamedTuple):
payment_hash: bytes
amount_msat: Optional[int]
direction: int
status: int
class ErrorAddingPeer(Exception): pass
# set some feature flags as baseline for both LNWallet and LNGossip
# note that e.g. DATA_LOSS_PROTECT is needed for LNGossip as many peers require it
BASE_FEATURES = LnFeatures(0)\
| LnFeatures.OPTION_DATA_LOSS_PROTECT_OPT\
| LnFeatures.OPTION_STATIC_REMOTEKEY_OPT\
| LnFeatures.VAR_ONION_OPT\
| LnFeatures.PAYMENT_SECRET_OPT\
| LnFeatures.OPTION_UPFRONT_SHUTDOWN_SCRIPT_OPT\
# we do not want to receive unrequested gossip (see lnpeer.maybe_save_remote_update)
LNWALLET_FEATURES = BASE_FEATURES\
| LnFeatures.OPTION_DATA_LOSS_PROTECT_REQ\
| LnFeatures.OPTION_STATIC_REMOTEKEY_REQ\
| LnFeatures.GOSSIP_QUERIES_REQ\
| LnFeatures.BASIC_MPP_OPT\
| LnFeatures.OPTION_TRAMPOLINE_ROUTING_OPT\
| LnFeatures.OPTION_SHUTDOWN_ANYSEGWIT_OPT\
| LnFeatures.OPTION_CHANNEL_TYPE_OPT\
LNGOSSIP_FEATURES = BASE_FEATURES\
| LnFeatures.GOSSIP_QUERIES_OPT\
| LnFeatures.GOSSIP_QUERIES_REQ\
class LNWorker(Logger, NetworkRetryManager[LNPeerAddr]):
INITIAL_TRAMPOLINE_FEE_LEVEL = 1 # only used for trampoline payments. set to 0 in tests.
def __init__(self, xprv, features: LnFeatures):
Logger.__init__(self)
NetworkRetryManager.__init__(
self,
max_retry_delay_normal=3600,
init_retry_delay_normal=600,
max_retry_delay_urgent=300,
init_retry_delay_urgent=4,
)
self.lock = threading.RLock()
self.node_keypair = generate_keypair(BIP32Node.from_xkey(xprv), LnKeyFamily.NODE_KEY)
self.backup_key = generate_keypair(BIP32Node.from_xkey(xprv), LnKeyFamily.BACKUP_CIPHER).privkey
self._peers = {} # type: Dict[bytes, Peer] # pubkey -> Peer # needs self.lock
self.taskgroup = OldTaskGroup()
self.listen_server = None # type: Optional[asyncio.AbstractServer]
self.features = features
self.network = None # type: Optional[Network]
self.config = None # type: Optional[SimpleConfig]
self.stopping_soon = False # whether we are being shut down
util.register_callback(self.on_proxy_changed, ['proxy_set'])
@property
def channel_db(self):
return self.network.channel_db if self.network else None
@property
def peers(self) -> Mapping[bytes, Peer]:
"""Returns a read-only copy of peers."""
with self.lock:
return self._peers.copy()
def channels_for_peer(self, node_id: bytes) -> Dict[bytes, Channel]:
return {}
def get_node_alias(self, node_id: bytes) -> Optional[str]:
"""Returns the alias of the node, or None if unknown."""
node_alias = None
if self.channel_db:
node_info = self.channel_db.get_node_info_for_node_id(node_id)
if node_info:
node_alias = node_info.alias
else:
for k, v in hardcoded_trampoline_nodes().items():
if v.pubkey == node_id:
node_alias = k
break
return node_alias
async def maybe_listen(self):
# FIXME: only one LNWorker can listen at a time (single port)
listen_addr = self.config.get('lightning_listen')
if listen_addr:
self.logger.info(f'lightning_listen enabled. will try to bind: {listen_addr!r}')
try:
netaddr = NetAddress.from_string(listen_addr)
except Exception as e:
self.logger.error(f"failed to parse config key 'lightning_listen'. got: {e!r}")
return
addr = str(netaddr.host)
async def cb(reader, writer):
transport = LNResponderTransport(self.node_keypair.privkey, reader, writer)
try:
node_id = await transport.handshake()
except Exception as e:
self.logger.info(f'handshake failure from incoming connection: {e!r}')
return
await self._add_peer_from_transport(node_id=node_id, transport=transport)
try:
self.listen_server = await asyncio.start_server(cb, addr, netaddr.port)
except OSError as e:
self.logger.error(f"cannot listen for lightning p2p. error: {e!r}")
@ignore_exceptions # don't kill outer taskgroup
async def main_loop(self):
self.logger.info("starting taskgroup.")
try:
async with self.taskgroup as group:
await group.spawn(self._maintain_connectivity())
except Exception as e:
self.logger.exception("taskgroup died.")
finally:
self.logger.info("taskgroup stopped.")
async def _maintain_connectivity(self):
while True:
await asyncio.sleep(1)
if self.stopping_soon:
return
now = time.time()
if len(self._peers) >= NUM_PEERS_TARGET:
continue
peers = await self._get_next_peers_to_try()
for peer in peers:
if self._can_retry_addr(peer, now=now):
try:
await self._add_peer(peer.host, peer.port, peer.pubkey)
except ErrorAddingPeer as e:
self.logger.info(f"failed to add peer: {peer}. exc: {e!r}")
async def _add_peer(self, host: str, port: int, node_id: bytes) -> Peer:
if node_id in self._peers:
return self._peers[node_id]
port = int(port)
peer_addr = LNPeerAddr(host, port, node_id)
self._trying_addr_now(peer_addr)
self.logger.info(f"adding peer {peer_addr}")
if node_id == self.node_keypair.pubkey:
raise ErrorAddingPeer("cannot connect to self")
transport = LNTransport(self.node_keypair.privkey, peer_addr,
proxy=self.network.proxy)
peer = await self._add_peer_from_transport(node_id=node_id, transport=transport)
return peer
async def _add_peer_from_transport(self, *, node_id: bytes, transport: LNTransportBase) -> Peer:
peer = Peer(self, node_id, transport)
with self.lock:
existing_peer = self._peers.get(node_id)
if existing_peer:
existing_peer.close_and_cleanup()
assert node_id not in self._peers
self._peers[node_id] = peer
await self.taskgroup.spawn(peer.main_loop())
return peer
def peer_closed(self, peer: Peer) -> None:
with self.lock:
peer2 = self._peers.get(peer.pubkey)
if peer2 is peer:
self._peers.pop(peer.pubkey)
def num_peers(self) -> int:
return sum([p.is_initialized() for p in self.peers.values()])
def start_network(self, network: 'Network'):
assert network
self.network = network
self.config = network.config
self._add_peers_from_config()
asyncio.run_coroutine_threadsafe(self.main_loop(), self.network.asyncio_loop)
async def stop(self):
if self.listen_server:
self.listen_server.close()
util.unregister_callback(self.on_proxy_changed)
await self.taskgroup.cancel_remaining()
def _add_peers_from_config(self):
peer_list = self.config.get('lightning_peers', [])
for host, port, pubkey in peer_list:
asyncio.run_coroutine_threadsafe(
self._add_peer(host, int(port), bfh(pubkey)),
self.network.asyncio_loop)
def is_good_peer(self, peer: LNPeerAddr) -> bool:
# the purpose of this method is to filter peers that advertise the desired feature bits
# it is disabled for now, because feature bits published in node announcements seem to be unreliable
return True
node_id = peer.pubkey
node = self.channel_db._nodes.get(node_id)
if not node:
return False
try:
ln_compare_features(self.features, node.features)
except IncompatibleLightningFeatures:
return False
#self.logger.info(f'is_good {peer.host}')
return True
def on_peer_successfully_established(self, peer: Peer) -> None:
if isinstance(peer.transport, LNTransport):
peer_addr = peer.transport.peer_addr
# reset connection attempt count
self._on_connection_successfully_established(peer_addr)
# add into channel db
if self.channel_db:
self.channel_db.add_recent_peer(peer_addr)
# save network address into channels we might have with peer
for chan in peer.channels.values():
chan.add_or_update_peer_addr(peer_addr)
async def _get_next_peers_to_try(self) -> Sequence[LNPeerAddr]:
now = time.time()
await self.channel_db.data_loaded.wait()
# first try from recent peers
recent_peers = self.channel_db.get_recent_peers()
for peer in recent_peers:
if not peer:
continue
if peer.pubkey in self._peers:
continue
if not self._can_retry_addr(peer, now=now):
continue
if not self.is_good_peer(peer):
continue
return [peer]
# try random peer from graph
unconnected_nodes = self.channel_db.get_200_randomly_sorted_nodes_not_in(self.peers.keys())
if unconnected_nodes:
for node_id in unconnected_nodes:
addrs = self.channel_db.get_node_addresses(node_id)
if not addrs:
continue
host, port, timestamp = self.choose_preferred_address(list(addrs))
try:
peer = LNPeerAddr(host, port, node_id)
except ValueError:
continue
if not self._can_retry_addr(peer, now=now):
continue
if not self.is_good_peer(peer):
continue
#self.logger.info('taking random ln peer from our channel db')
return [peer]
# getting desperate... let's try hardcoded fallback list of peers
if constants.net in (constants.BitcoinTestnet,):
fallback_list = FALLBACK_NODE_LIST_TESTNET
elif constants.net in (constants.BitcoinMainnet,):
fallback_list = FALLBACK_NODE_LIST_MAINNET
else:
return [] # regtest??
fallback_list = [peer for peer in fallback_list if self._can_retry_addr(peer, now=now)]
if fallback_list:
return [random.choice(fallback_list)]
# last resort: try dns seeds (BOLT-10)
return await run_in_thread(self._get_peers_from_dns_seeds)
def _get_peers_from_dns_seeds(self) -> Sequence[LNPeerAddr]:
# NOTE: potentially long blocking call, do not run directly on asyncio event loop.
# Return several peers to reduce the number of dns queries.
if not constants.net.LN_DNS_SEEDS:
return []
dns_seed = random.choice(constants.net.LN_DNS_SEEDS)
self.logger.info('asking dns seed "{}" for ln peers'.format(dns_seed))
try:
# note: this might block for several seconds
# this will include bech32-encoded-pubkeys and ports
srv_answers = resolve_dns_srv('r{}.{}'.format(
constants.net.LN_REALM_BYTE, dns_seed))
except dns.exception.DNSException as e:
self.logger.info(f'failed querying (1) dns seed "{dns_seed}" for ln peers: {repr(e)}')
return []
random.shuffle(srv_answers)
num_peers = 2 * NUM_PEERS_TARGET
srv_answers = srv_answers[:num_peers]
# we now have pubkeys and ports but host is still needed
peers = []
for srv_ans in srv_answers:
try:
# note: this might block for several seconds
answers = dns.resolver.resolve(srv_ans['host'])
except dns.exception.DNSException as e:
self.logger.info(f'failed querying (2) dns seed "{dns_seed}" for ln peers: {repr(e)}')
continue
try:
ln_host = str(answers[0])
port = int(srv_ans['port'])
bech32_pubkey = srv_ans['host'].split('.')[0]
pubkey = get_compressed_pubkey_from_bech32(bech32_pubkey)
peers.append(LNPeerAddr(ln_host, port, pubkey))
except Exception as e:
self.logger.info(f'error with parsing peer from dns seed: {repr(e)}')
continue
self.logger.info(f'got {len(peers)} ln peers from dns seed')
return peers
@staticmethod
def choose_preferred_address(addr_list: Sequence[Tuple[str, int, int]]) -> Tuple[str, int, int]:
assert len(addr_list) >= 1
# choose first one that is an IP
for host, port, timestamp in addr_list:
if is_ip_address(host):
return host, port, timestamp
# otherwise choose one at random
# TODO maybe filter out onion if not on tor?
choice = random.choice(addr_list)
return choice
def on_proxy_changed(self, event, *args):
for peer in self.peers.values():
peer.close_and_cleanup()
self._clear_addr_retry_times()
@log_exceptions
async def add_peer(self, connect_str: str) -> Peer:
node_id, rest = extract_nodeid(connect_str)
peer = self._peers.get(node_id)
if not peer:
if rest is not None:
host, port = split_host_port(rest)
else:
if not self.channel_db:
addr = trampolines_by_id().get(node_id)
if not addr:
raise ConnStringFormatError(_('Address unknown for node:') + ' ' + bh2u(node_id))
host, port = addr.host, addr.port
else:
addrs = self.channel_db.get_node_addresses(node_id)
if not addrs:
raise ConnStringFormatError(_('Don\'t know any addresses for node:') + ' ' + bh2u(node_id))
host, port, timestamp = self.choose_preferred_address(list(addrs))
port = int(port)
# Try DNS-resolving the host (if needed). This is simply so that
# the caller gets a nice exception if it cannot be resolved.
try:
await asyncio.get_event_loop().getaddrinfo(host, port)
except socket.gaierror:
raise ConnStringFormatError(_('Hostname does not resolve (getaddrinfo failed)'))
# add peer
peer = await self._add_peer(host, port, node_id)
return peer
class LNGossip(LNWorker):
max_age = 14*24*3600
LOGGING_SHORTCUT = 'g'
def __init__(self):
seed = os.urandom(32)
node = BIP32Node.from_rootseed(seed, xtype='standard')
xprv = node.to_xprv()
super().__init__(xprv, LNGOSSIP_FEATURES)
self.unknown_ids = set()
def start_network(self, network: 'Network'):
assert network
super().start_network(network)
asyncio.run_coroutine_threadsafe(self.taskgroup.spawn(self.maintain_db()), self.network.asyncio_loop)
async def maintain_db(self):
await self.channel_db.data_loaded.wait()
while True:
if len(self.unknown_ids) == 0:
self.channel_db.prune_old_policies(self.max_age)
self.channel_db.prune_orphaned_channels()
await asyncio.sleep(120)
async def add_new_ids(self, ids: Iterable[bytes]):
known = self.channel_db.get_channel_ids()
new = set(ids) - set(known)
self.unknown_ids.update(new)
util.trigger_callback('unknown_channels', len(self.unknown_ids))
util.trigger_callback('gossip_peers', self.num_peers())
util.trigger_callback('ln_gossip_sync_progress')
def get_ids_to_query(self) -> Sequence[bytes]:
N = 500
l = list(self.unknown_ids)
self.unknown_ids = set(l[N:])
util.trigger_callback('unknown_channels', len(self.unknown_ids))
util.trigger_callback('ln_gossip_sync_progress')
return l[0:N]
def get_sync_progress_estimate(self) -> Tuple[Optional[int], Optional[int], Optional[int]]:
"""Estimates the gossip synchronization process and returns the number
of synchronized channels, the total channels in the network and a
rescaled percentage of the synchronization process."""
if self.num_peers() == 0:
return None, None, None
nchans_with_0p, nchans_with_1p, nchans_with_2p = self.channel_db.get_num_channels_partitioned_by_policy_count()
num_db_channels = nchans_with_0p + nchans_with_1p + nchans_with_2p
# some channels will never have two policies (only one is in gossip?...)
# so if we have at least 1 policy for a channel, we consider that channel "complete" here
current_est = num_db_channels - nchans_with_0p
total_est = len(self.unknown_ids) + num_db_channels
progress = current_est / total_est if total_est and current_est else 0
progress_percent = (1.0 / 0.95 * progress) * 100
progress_percent = min(progress_percent, 100)
progress_percent = round(progress_percent)
# take a minimal number of synchronized channels to get a more accurate
# percentage estimate
if current_est < 200:
progress_percent = 0
return current_est, total_est, progress_percent
async def process_gossip(self, chan_anns, node_anns, chan_upds):
# note: we run in the originating peer's TaskGroup, so we can safely raise here
# and disconnect only from that peer
await self.channel_db.data_loaded.wait()
self.logger.debug(f'process_gossip {len(chan_anns)} {len(node_anns)} {len(chan_upds)}')
# channel announcements
def process_chan_anns():
for payload in chan_anns:
self.channel_db.verify_channel_announcement(payload)
self.channel_db.add_channel_announcements(chan_anns)
await run_in_thread(process_chan_anns)
# node announcements
def process_node_anns():
for payload in node_anns:
self.channel_db.verify_node_announcement(payload)
self.channel_db.add_node_announcements(node_anns)
await run_in_thread(process_node_anns)
# channel updates
categorized_chan_upds = await run_in_thread(partial(
self.channel_db.add_channel_updates,
chan_upds,
max_age=self.max_age))
orphaned = categorized_chan_upds.orphaned
if orphaned:
self.logger.info(f'adding {len(orphaned)} unknown channel ids')
orphaned_ids = [c['short_channel_id'] for c in orphaned]
await self.add_new_ids(orphaned_ids)
if categorized_chan_upds.good:
self.logger.debug(f'on_channel_update: {len(categorized_chan_upds.good)}/{len(chan_upds)}')
class LNWallet(LNWorker):
lnwatcher: Optional['LNWalletWatcher']
MPP_EXPIRY = 120
TIMEOUT_SHUTDOWN_FAIL_PENDING_HTLCS = 3 # seconds
def __init__(self, wallet: 'Abstract_Wallet', xprv):
self.wallet = wallet
self.db = wallet.db
Logger.__init__(self)
LNWorker.__init__(self, xprv, LNWALLET_FEATURES)
self.config = wallet.config
self.lnwatcher = None
self.lnrater: LNRater = None
self.payments = self.db.get_dict('lightning_payments') # RHASH -> amount, direction, is_paid
self.preimages = self.db.get_dict('lightning_preimages') # RHASH -> preimage
# note: this sweep_address is only used as fallback; as it might result in address-reuse
self.sweep_address = wallet.get_new_sweep_address_for_channel()
self.logs = defaultdict(list) # type: Dict[str, List[HtlcLog]] # key is RHASH # (not persisted)
# used in tests
self.enable_htlc_settle = True
self.enable_htlc_forwarding = True
# note: accessing channels (besides simple lookup) needs self.lock!
self._channels = {} # type: Dict[bytes, Channel]
channels = self.db.get_dict("channels")
for channel_id, c in random_shuffled_copy(channels.items()):
self._channels[bfh(channel_id)] = Channel(c, sweep_address=self.sweep_address, lnworker=self)
self._channel_backups = {} # type: Dict[bytes, ChannelBackup]
# order is important: imported should overwrite onchain
for name in ["onchain_channel_backups", "imported_channel_backups"]:
channel_backups = self.db.get_dict(name)
for channel_id, storage in channel_backups.items():
self._channel_backups[bfh(channel_id)] = ChannelBackup(storage, sweep_address=self.sweep_address, lnworker=self)
self.sent_htlcs = defaultdict(asyncio.Queue) # type: Dict[bytes, asyncio.Queue[HtlcLog]]
self.sent_htlcs_info = dict() # (RHASH, scid, htlc_id) -> route, payment_secret, amount_msat, bucket_msat, trampoline_fee_level
self.sent_buckets = dict() # payment_secret -> (amount_sent, amount_failed)
self.received_mpp_htlcs = dict() # RHASH -> mpp_status, htlc_set
self.swap_manager = SwapManager(wallet=self.wallet, lnworker=self)
# detect inflight payments
self.inflight_payments = set() # (not persisted) keys of invoices that are in PR_INFLIGHT state
for payment_hash in self.get_payments(status='inflight').keys():
self.set_invoice_status(payment_hash.hex(), PR_INFLIGHT)
self.trampoline_forwarding_failures = {} # todo: should be persisted
# map forwarded htlcs (fw_info=(scid_hex, htlc_id)) to originating peer pubkeys
self.downstream_htlc_to_upstream_peer_map = {} # type: Dict[Tuple[str, int], bytes]
def has_deterministic_node_id(self) -> bool:
return bool(self.db.get('lightning_xprv'))
def can_have_recoverable_channels(self) -> bool:
return (self.has_deterministic_node_id()
and not (self.config.get('lightning_listen')))
def has_recoverable_channels(self) -> bool:
"""Whether *future* channels opened by this wallet would be recoverable
from seed (via putting OP_RETURN outputs into funding txs).
"""
return (self.can_have_recoverable_channels()
and self.config.get('use_recoverable_channels', True))
@property
def channels(self) -> Mapping[bytes, Channel]:
"""Returns a read-only copy of channels."""
with self.lock:
return self._channels.copy()
@property
def channel_backups(self) -> Mapping[bytes, ChannelBackup]:
"""Returns a read-only copy of channels."""
with self.lock:
return self._channel_backups.copy()
def get_channel_by_id(self, channel_id: bytes) -> Optional[Channel]:
return self._channels.get(channel_id, None)
def diagnostic_name(self):
return self.wallet.diagnostic_name()
@ignore_exceptions
@log_exceptions
async def sync_with_local_watchtower(self):
watchtower = self.network.local_watchtower
if watchtower:
while True:
for chan in self.channels.values():
await self.sync_channel_with_watchtower(chan, watchtower.sweepstore)
await asyncio.sleep(5)
@ignore_exceptions
@log_exceptions
async def sync_with_remote_watchtower(self):
while True:
# periodically poll if the user updated 'watchtower_url'
await asyncio.sleep(5)
watchtower_url = self.config.get('watchtower_url')
if not watchtower_url:
continue
parsed_url = urllib.parse.urlparse(watchtower_url)
if not (parsed_url.scheme == 'https' or is_private_netaddress(parsed_url.hostname)):
self.logger.warning(f"got watchtower URL for remote tower but we won't use it! "
f"can only use HTTPS (except if private IP): not using {watchtower_url!r}")
continue
# try to sync with the remote watchtower
try:
async with make_aiohttp_session(proxy=self.network.proxy) as session:
watchtower = JsonRPCClient(session, watchtower_url)
watchtower.add_method('get_ctn')
watchtower.add_method('add_sweep_tx')
for chan in self.channels.values():
await self.sync_channel_with_watchtower(chan, watchtower)
except aiohttp.client_exceptions.ClientConnectorError:
self.logger.info(f'could not contact remote watchtower {watchtower_url}')
async def sync_channel_with_watchtower(self, chan: Channel, watchtower):
outpoint = chan.funding_outpoint.to_str()
addr = chan.get_funding_address()
current_ctn = chan.get_oldest_unrevoked_ctn(REMOTE)
watchtower_ctn = await watchtower.get_ctn(outpoint, addr)
for ctn in range(watchtower_ctn + 1, current_ctn):
sweeptxs = chan.create_sweeptxs(ctn)
for tx in sweeptxs:
await watchtower.add_sweep_tx(outpoint, ctn, tx.inputs()[0].prevout.to_str(), tx.serialize())
def start_network(self, network: 'Network'):
assert network
self.network = network
self.config = network.config
self.lnwatcher = LNWalletWatcher(self, network)
self.lnwatcher.start_network(network)
self.swap_manager.start_network(network=network, lnwatcher=self.lnwatcher)
self.lnrater = LNRater(self, network)
for chan in self.channels.values():
self.lnwatcher.add_channel(chan.funding_outpoint.to_str(), chan.get_funding_address())
for cb in self.channel_backups.values():
self.lnwatcher.add_channel(cb.funding_outpoint.to_str(), cb.get_funding_address())
for coro in [
self.maybe_listen(),
self.lnwatcher.on_network_update('network_updated'), # shortcut (don't block) if funding tx locked and verified
self.reestablish_peers_and_channels(),
self.sync_with_local_watchtower(),
self.sync_with_remote_watchtower(),
]:
tg_coro = self.taskgroup.spawn(coro)
asyncio.run_coroutine_threadsafe(tg_coro, self.network.asyncio_loop)
async def stop(self):
self.stopping_soon = True
if self.listen_server: # stop accepting new peers
self.listen_server.close()
async with ignore_after(self.TIMEOUT_SHUTDOWN_FAIL_PENDING_HTLCS):
await self.wait_for_received_pending_htlcs_to_get_removed()
await LNWorker.stop(self)
if self.lnwatcher:
await self.lnwatcher.stop()
self.lnwatcher = None
async def wait_for_received_pending_htlcs_to_get_removed(self):
assert self.stopping_soon is True
# We try to fail pending MPP HTLCs, and wait a bit for them to get removed.
# Note: even without MPP, if we just failed/fulfilled an HTLC, it is good
# to wait a bit for it to become irrevocably removed.
# Note: we don't wait for *all htlcs* to get removed, only for those
# that we can already fail/fulfill. e.g. forwarded htlcs cannot be removed
async with OldTaskGroup() as group:
for peer in self.peers.values():
await group.spawn(peer.wait_one_htlc_switch_iteration())
while True:
if all(not peer.received_htlcs_pending_removal for peer in self.peers.values()):
break
async with OldTaskGroup(wait=any) as group:
for peer in self.peers.values():
await group.spawn(peer.received_htlc_removed_event.wait())
def peer_closed(self, peer):
for chan in self.channels_for_peer(peer.pubkey).values():
chan.peer_state = PeerState.DISCONNECTED
util.trigger_callback('channel', self.wallet, chan)
super().peer_closed(peer)
def get_payments(self, *, status=None) -> Mapping[bytes, List[HTLCWithStatus]]:
out = defaultdict(list)
for chan in self.channels.values():
d = chan.get_payments(status=status)
for payment_hash, plist in d.items():
out[payment_hash] += plist
return out
def get_payment_value(
self, info: Optional['PaymentInfo'], plist: List[HTLCWithStatus],
) -> Tuple[int, int, int]:
assert plist
amount_msat = 0
fee_msat = None
for htlc_with_status in plist:
htlc = htlc_with_status.htlc
_direction = htlc_with_status.direction
amount_msat += int(_direction) * htlc.amount_msat
if _direction == SENT and info and info.amount_msat:
fee_msat = (fee_msat or 0) - info.amount_msat - amount_msat
timestamp = min([htlc_with_status.htlc.timestamp for htlc_with_status in plist])
return amount_msat, fee_msat, timestamp
def get_lightning_history(self):
out = {}
for payment_hash, plist in self.get_payments(status='settled').items():
if len(plist) == 0:
continue
key = payment_hash.hex()
info = self.get_payment_info(payment_hash)
amount_msat, fee_msat, timestamp = self.get_payment_value(info, plist)
if info is not None:
label = self.wallet.get_label(key)
direction = ('sent' if info.direction == SENT else 'received') if len(plist)==1 else 'self-payment'
else:
direction = 'forwarding'
label = _('Forwarding')
preimage = self.get_preimage(payment_hash).hex()
item = {
'type': 'payment',
'label': label,
'timestamp': timestamp or 0,
'date': timestamp_to_datetime(timestamp),
'direction': direction,
'amount_msat': amount_msat,
'fee_msat': fee_msat,
'payment_hash': key,
'preimage': preimage,
}
# add group_id to swap transactions
swap = self.swap_manager.get_swap(payment_hash)
if swap:
if swap.is_reverse:
item['group_id'] = swap.spending_txid
item['group_label'] = 'Reverse swap' + ' ' + self.config.format_amount_and_units(swap.lightning_amount)
else:
item['group_id'] = swap.funding_txid
item['group_label'] = 'Forward swap' + ' ' + self.config.format_amount_and_units(swap.onchain_amount)
# done
out[payment_hash] = item
return out
def get_onchain_history(self):
current_height = self.wallet.get_local_height()
out = {}
# add funding events
for chan in self.channels.values():
item = chan.get_funding_height()
if item is None:
continue
if not self.lnwatcher:
continue # lnwatcher not available with --offline (its data is not persisted)
funding_txid, funding_height, funding_timestamp = item
tx_height = self.lnwatcher.get_tx_height(funding_txid)
item = {
'channel_id': bh2u(chan.channel_id),
'type': 'channel_opening',
'label': self.wallet.get_label_for_txid(funding_txid) or (_('Open channel') + ' ' + chan.get_id_for_log()),
'txid': funding_txid,
'amount_msat': chan.balance(LOCAL, ctn=0),
'direction': 'received',
'timestamp': tx_height.timestamp,
'date': timestamp_to_datetime(tx_height.timestamp),
'fee_sat': None,
'fee_msat': None,
'height': tx_height.height,
'confirmations': tx_height.conf,
}
out[funding_txid] = item
item = chan.get_closing_height()
if item is None:
continue
closing_txid, closing_height, closing_timestamp = item
tx_height = self.lnwatcher.get_tx_height(closing_txid)
item = {
'channel_id': bh2u(chan.channel_id),
'txid': closing_txid,
'label': self.wallet.get_label_for_txid(closing_txid) or (_('Close channel') + ' ' + chan.get_id_for_log()),
'type': 'channel_closure',
'amount_msat': -chan.balance_minus_outgoing_htlcs(LOCAL),
'direction': 'sent',
'timestamp': tx_height.timestamp,
'date': timestamp_to_datetime(tx_height.timestamp),
'fee_sat': None,
'fee_msat': None,
'height': tx_height.height,
'confirmations': tx_height.conf,
}
out[closing_txid] = item
# add info about submarine swaps
settled_payments = self.get_payments(status='settled')
for payment_hash_hex, swap in self.swap_manager.swaps.items():
txid = swap.spending_txid if swap.is_reverse else swap.funding_txid
if txid is None:
continue
payment_hash = bytes.fromhex(payment_hash_hex)
if payment_hash in settled_payments:
plist = settled_payments[payment_hash]
info = self.get_payment_info(payment_hash)
amount_msat, fee_msat, timestamp = self.get_payment_value(info, plist)
else:
amount_msat = 0
label = 'Reverse swap' if swap.is_reverse else 'Forward swap'
delta = current_height - swap.locktime
if not swap.is_redeemed and swap.spending_txid is None and delta < 0:
label += f' (refundable in {-delta} blocks)' # fixme: only if unspent
out[txid] = {
'txid': txid,
'group_id': txid,
'amount_msat': 0,
#'amount_msat': amount_msat, # must not be added
'type': 'swap',
'label': self.wallet.get_label_for_txid(txid) or label,
}
return out
def get_history(self):
out = list(self.get_lightning_history().values()) + list(self.get_onchain_history().values())
# sort by timestamp
out.sort(key=lambda x: (x.get('timestamp') or float("inf")))
balance_msat = 0
for item in out:
balance_msat += item['amount_msat']
item['balance_msat'] = balance_msat
return out
def channel_peers(self) -> List[bytes]:
node_ids = [chan.node_id for chan in self.channels.values() if not chan.is_closed()]
return node_ids
def channels_for_peer(self, node_id):
assert type(node_id) is bytes
return {chan_id: chan for (chan_id, chan) in self.channels.items()
if chan.node_id == node_id}
def channel_state_changed(self, chan: Channel):
if type(chan) is Channel:
self.save_channel(chan)
util.trigger_callback('channel', self.wallet, chan)
def save_channel(self, chan: Channel):
assert type(chan) is Channel
if chan.config[REMOTE].next_per_commitment_point == chan.config[REMOTE].current_per_commitment_point:
raise Exception("Tried to save channel with next_point == current_point, this should not happen")
self.wallet.save_db()
util.trigger_callback('channel', self.wallet, chan)
def channel_by_txo(self, txo: str) -> Optional[AbstractChannel]:
for chan in self.channels.values():
if chan.funding_outpoint.to_str() == txo:
return chan
for chan in self.channel_backups.values():
if chan.funding_outpoint.to_str() == txo:
return chan
async def on_channel_update(self, chan: Channel):
if type(chan) is ChannelBackup:
util.trigger_callback('channel', self.wallet, chan)
return
if chan.get_state() == ChannelState.OPEN and chan.should_be_closed_due_to_expiring_htlcs(self.network.get_local_height()):
self.logger.info(f"force-closing due to expiring htlcs")
await self.schedule_force_closing(chan.channel_id)
elif chan.get_state() == ChannelState.FUNDED:
peer = self._peers.get(chan.node_id)
if peer and peer.is_initialized():
peer.send_funding_locked(chan)
elif chan.get_state() == ChannelState.OPEN:
peer = self._peers.get(chan.node_id)
if peer:
await peer.maybe_update_fee(chan)
conf = self.lnwatcher.get_tx_height(chan.funding_outpoint.txid).conf
peer.on_network_update(chan, conf)
elif chan.get_state() == ChannelState.FORCE_CLOSING:
force_close_tx = chan.force_close_tx()
txid = force_close_tx.txid()
height = self.lnwatcher.get_tx_height(txid).height
if height == TX_HEIGHT_LOCAL:
self.logger.info('REBROADCASTING CLOSING TX')
await self.network.try_broadcasting(force_close_tx, 'force-close')
@log_exceptions
async def _open_channel_coroutine(
self, *,
connect_str: str,
funding_tx: PartialTransaction,
funding_sat: int,
push_sat: int,
password: Optional[str]) -> Tuple[Channel, PartialTransaction]:
peer = await self.add_peer(connect_str)
coro = peer.channel_establishment_flow(
funding_tx=funding_tx,
funding_sat=funding_sat,
push_msat=push_sat * 1000,
temp_channel_id=os.urandom(32))
chan, funding_tx = await asyncio.wait_for(coro, LN_P2P_NETWORK_TIMEOUT)
util.trigger_callback('channels_updated', self.wallet)
self.wallet.add_transaction(funding_tx) # save tx as local into the wallet
self.wallet.sign_transaction(funding_tx, password)
self.wallet.set_label(funding_tx.txid(), _('Open channel'))
if funding_tx.is_complete():
await self.network.try_broadcasting(funding_tx, 'open_channel')
return chan, funding_tx
def add_channel(self, chan: Channel):
with self.lock:
self._channels[chan.channel_id] = chan
self.lnwatcher.add_channel(chan.funding_outpoint.to_str(), chan.get_funding_address())
def add_new_channel(self, chan: Channel):
self.add_channel(chan)
channels_db = self.db.get_dict('channels')
channels_db[chan.channel_id.hex()] = chan.storage
for addr in chan.get_wallet_addresses_channel_might_want_reserved():
self.wallet.set_reserved_state_of_address(addr, reserved=True)
try:
self.save_channel(chan)
backup_dir = self.config.get_backup_dir()
if backup_dir is not None:
self.wallet.save_backup(backup_dir)
except:
chan.set_state(ChannelState.REDEEMED)
self.remove_channel(chan.channel_id)
raise
def cb_data(self, node_id):
return CB_MAGIC_BYTES + node_id[0:16]
def decrypt_cb_data(self, encrypted_data, funding_address):
funding_scripthash = bytes.fromhex(address_to_scripthash(funding_address))
nonce = funding_scripthash[0:12]
return chacha20_decrypt(key=self.backup_key, data=encrypted_data, nonce=nonce)
def encrypt_cb_data(self, data, funding_address):
funding_scripthash = bytes.fromhex(address_to_scripthash(funding_address))
nonce = funding_scripthash[0:12]
return chacha20_encrypt(key=self.backup_key, data=data, nonce=nonce)
def mktx_for_open_channel(
self, *,
coins: Sequence[PartialTxInput],
funding_sat: int,
node_id: bytes,
fee_est=None) -> PartialTransaction:
outputs = [PartialTxOutput.from_address_and_value(ln_dummy_address(), funding_sat)]
if self.has_recoverable_channels():
dummy_scriptpubkey = make_op_return(self.cb_data(node_id))
outputs.append(PartialTxOutput(scriptpubkey=dummy_scriptpubkey, value=0))
tx = self.wallet.make_unsigned_transaction(
coins=coins,
outputs=outputs,
fee=fee_est)
tx.set_rbf(False)
return tx
def open_channel(self, *, connect_str: str, funding_tx: PartialTransaction,
funding_sat: int, push_amt_sat: int, password: str = None) -> Tuple[Channel, PartialTransaction]:
if funding_sat > LN_MAX_FUNDING_SAT:
raise Exception(_("Requested channel capacity is over protocol allowed maximum."))
coro = self._open_channel_coroutine(
connect_str=connect_str, funding_tx=funding_tx, funding_sat=funding_sat,
push_sat=push_amt_sat, password=password)
fut = asyncio.run_coroutine_threadsafe(coro, self.network.asyncio_loop)
try:
chan, funding_tx = fut.result()
except concurrent.futures.TimeoutError:
raise Exception(_("open_channel timed out"))
return chan, funding_tx
def get_channel_by_short_id(self, short_channel_id: bytes) -> Optional[Channel]:
for chan in self.channels.values():
if chan.short_channel_id == short_channel_id:
return chan
@log_exceptions
async def pay_invoice(
self, invoice: str, *,
amount_msat: int = None,
attempts: int = 1,
full_path: LNPaymentPath = None) -> Tuple[bool, List[HtlcLog]]:
lnaddr = self._check_invoice(invoice, amount_msat=amount_msat)
min_cltv_expiry = lnaddr.get_min_final_cltv_expiry()
payment_hash = lnaddr.paymenthash
key = payment_hash.hex()
payment_secret = lnaddr.payment_secret
invoice_pubkey = lnaddr.pubkey.serialize()
invoice_features = lnaddr.get_features()
r_tags = lnaddr.get_routing_info('r')
amount_to_pay = lnaddr.get_amount_msat()
status = self.get_payment_status(payment_hash)
if status == PR_PAID:
raise PaymentFailure(_("This invoice has been paid already"))
if status == PR_INFLIGHT:
raise PaymentFailure(_("A payment was already initiated for this invoice"))
if payment_hash in self.get_payments(status='inflight'):
raise PaymentFailure(_("A previous attempt to pay this invoice did not clear"))
info = PaymentInfo(payment_hash, amount_to_pay, SENT, PR_UNPAID)
self.save_payment_info(info)
self.wallet.set_label(key, lnaddr.get_description())
self.set_invoice_status(key, PR_INFLIGHT)
try:
await self.pay_to_node(
node_pubkey=invoice_pubkey,
payment_hash=payment_hash,
payment_secret=payment_secret,
amount_to_pay=amount_to_pay,
min_cltv_expiry=min_cltv_expiry,
r_tags=r_tags,
invoice_features=invoice_features,
attempts=attempts,
full_path=full_path)
success = True
except PaymentFailure as e:
self.logger.info(f'payment failure: {e!r}')
success = False
reason = str(e)
if success:
self.set_invoice_status(key, PR_PAID)
util.trigger_callback('payment_succeeded', self.wallet, key)
else:
self.set_invoice_status(key, PR_UNPAID)
util.trigger_callback('payment_failed', self.wallet, key, reason)
log = self.logs[key]
return success, log
async def pay_to_node(
self, *,
node_pubkey: bytes,
payment_hash: bytes,
payment_secret: Optional[bytes],
amount_to_pay: int, # in msat
min_cltv_expiry: int,
r_tags,
invoice_features: int,
attempts: int = 1,
full_path: LNPaymentPath = None,
fwd_trampoline_onion=None,
fwd_trampoline_fee=None,
fwd_trampoline_cltv_delta=None) -> None:
if fwd_trampoline_onion:
# todo: compare to the fee of the actual route we found
if fwd_trampoline_fee < 1000:
raise OnionRoutingFailure(code=OnionFailureCode.TRAMPOLINE_FEE_INSUFFICIENT, data=b'')
if fwd_trampoline_cltv_delta < 576:
raise OnionRoutingFailure(code=OnionFailureCode.TRAMPOLINE_EXPIRY_TOO_SOON, data=b'')
self.logs[payment_hash.hex()] = log = []
# when encountering trampoline forwarding difficulties in the legacy case, we
# sometimes need to fall back to a single trampoline forwarder, at the expense
# of privacy
use_two_trampolines = True
trampoline_fee_level = self.INITIAL_TRAMPOLINE_FEE_LEVEL
amount_inflight = 0 # what we sent in htlcs (that receiver gets, without fees)
while True:
amount_to_send = amount_to_pay - amount_inflight
if amount_to_send > 0:
# 1. create a set of routes for remaining amount.
# note: path-finding runs in a separate thread so that we don't block the asyncio loop
# graph updates might occur during the computation
routes = self.create_routes_for_payment(
amount_msat=amount_to_send,
final_total_msat=amount_to_pay,
invoice_pubkey=node_pubkey,
min_cltv_expiry=min_cltv_expiry,
r_tags=r_tags,
invoice_features=invoice_features,
full_path=full_path,
payment_hash=payment_hash,
payment_secret=payment_secret,
trampoline_fee_level=trampoline_fee_level,
use_two_trampolines=use_two_trampolines,
fwd_trampoline_onion=fwd_trampoline_onion
)
# 2. send htlcs
async for route, amount_msat, total_msat, amount_receiver_msat, cltv_delta, bucket_payment_secret, trampoline_onion in routes:
amount_inflight += amount_receiver_msat
if amount_inflight > amount_to_pay: # safety belts
raise Exception(f"amount_inflight={amount_inflight} > amount_to_pay={amount_to_pay}")
await self.pay_to_route(
route=route,
amount_msat=amount_msat,
total_msat=total_msat,
amount_receiver_msat=amount_receiver_msat,
payment_hash=payment_hash,
payment_secret=bucket_payment_secret,
min_cltv_expiry=cltv_delta,
trampoline_onion=trampoline_onion,
trampoline_fee_level=trampoline_fee_level)
util.trigger_callback('invoice_status', self.wallet, payment_hash.hex())
# 3. await a queue
self.logger.info(f"amount inflight {amount_inflight}")
htlc_log = await self.sent_htlcs[payment_hash].get()
amount_inflight -= htlc_log.amount_msat
if amount_inflight < 0:
raise Exception(f"amount_inflight={amount_inflight} < 0")
log.append(htlc_log)
if htlc_log.success:
if self.network.path_finder:
# TODO: report every route to liquidity hints for mpp
# in the case of success, we report channels of the
# route as being able to send the same amount in the future,
# as we assume to not know the capacity
self.network.path_finder.update_liquidity_hints(htlc_log.route, htlc_log.amount_msat)
# remove inflight htlcs from liquidity hints
self.network.path_finder.update_inflight_htlcs(htlc_log.route, add_htlcs=False)
return
# htlc failed
if len(log) >= attempts:
raise PaymentFailure('Giving up after %d attempts'%len(log))
# if we get a tmp channel failure, it might work to split the amount and try more routes
# if we get a channel update, we might retry the same route and amount
route = htlc_log.route
sender_idx = htlc_log.sender_idx
erring_node_id = route[sender_idx].node_id
failure_msg = htlc_log.failure_msg
code, data = failure_msg.code, failure_msg.data
self.logger.info(f"UPDATE_FAIL_HTLC. code={repr(code)}. "
f"decoded_data={failure_msg.decode_data()}. data={data.hex()!r}")
self.logger.info(f"error reported by {bh2u(erring_node_id)}")
if code == OnionFailureCode.MPP_TIMEOUT:
raise PaymentFailure(failure_msg.code_name())
# trampoline
if not self.channel_db:
# FIXME The trampoline nodes in the path are chosen randomly.
# Some of the errors might depend on how we have chosen them.
# Having more attempts is currently useful in part because of the randomness,
# instead we should give feedback to create_routes_for_payment.
if code in (OnionFailureCode.TRAMPOLINE_FEE_INSUFFICIENT,
OnionFailureCode.TRAMPOLINE_EXPIRY_TOO_SOON):
# TODO: parse the node policy here (not returned by eclair yet)
# TODO: erring node is always the first trampoline even if second
# trampoline demands more fees, we can't influence this
if htlc_log.trampoline_fee_level == trampoline_fee_level:
trampoline_fee_level += 1
self.logger.info(f'raising trampoline fee level {trampoline_fee_level}')
else:
self.logger.info(f'NOT raising trampoline fee level, already at {trampoline_fee_level}')
continue
elif use_two_trampolines:
use_two_trampolines = False
elif code in (OnionFailureCode.UNKNOWN_NEXT_PEER,
OnionFailureCode.TEMPORARY_NODE_FAILURE):
continue
else:
raise PaymentFailure(failure_msg.code_name())
else:
self.handle_error_code_from_failed_htlc(
route=route, sender_idx=sender_idx, failure_msg=failure_msg, amount=htlc_log.amount_msat)
async def pay_to_route(
self, *,
route: LNPaymentRoute,
amount_msat: int,
total_msat: int,
amount_receiver_msat:int,
payment_hash: bytes,
payment_secret: Optional[bytes],
min_cltv_expiry: int,
trampoline_onion: bytes = None,
trampoline_fee_level: int) -> None:
# send a single htlc
short_channel_id = route[0].short_channel_id
chan = self.get_channel_by_short_id(short_channel_id)
peer = self._peers.get(route[0].node_id)
if not peer:
raise PaymentFailure('Dropped peer')
await peer.initialized
htlc = peer.pay(
route=route,
chan=chan,
amount_msat=amount_msat,
total_msat=total_msat,
payment_hash=payment_hash,
min_final_cltv_expiry=min_cltv_expiry,
payment_secret=payment_secret,
trampoline_onion=trampoline_onion)
key = (payment_hash, short_channel_id, htlc.htlc_id)
self.sent_htlcs_info[key] = route, payment_secret, amount_msat, total_msat, amount_receiver_msat, trampoline_fee_level
# if we sent MPP to a trampoline, add item to sent_buckets
if not self.channel_db and amount_msat != total_msat:
if payment_secret not in self.sent_buckets:
self.sent_buckets[payment_secret] = (0, 0)
amount_sent, amount_failed = self.sent_buckets[payment_secret]
amount_sent += amount_receiver_msat
self.sent_buckets[payment_secret] = amount_sent, amount_failed
if self.network.path_finder:
# add inflight htlcs to liquidity hints
self.network.path_finder.update_inflight_htlcs(route, add_htlcs=True)
util.trigger_callback('htlc_added', chan, htlc, SENT)
def handle_error_code_from_failed_htlc(
self,
*,
route: LNPaymentRoute,
sender_idx: int,
failure_msg: OnionRoutingFailure,
amount: int) -> None:
assert self.channel_db # cannot be in trampoline mode
assert self.network.path_finder
# remove inflight htlcs from liquidity hints
self.network.path_finder.update_inflight_htlcs(route, add_htlcs=False)
code, data = failure_msg.code, failure_msg.data
# TODO can we use lnmsg.OnionWireSerializer here?
# TODO update onion_wire.csv
# handle some specific error codes
failure_codes = {
OnionFailureCode.TEMPORARY_CHANNEL_FAILURE: 0,
OnionFailureCode.AMOUNT_BELOW_MINIMUM: 8,
OnionFailureCode.FEE_INSUFFICIENT: 8,
OnionFailureCode.INCORRECT_CLTV_EXPIRY: 4,
OnionFailureCode.EXPIRY_TOO_SOON: 0,
OnionFailureCode.CHANNEL_DISABLED: 2,
}
# determine a fallback channel to blacklist if we don't get the erring
# channel via the payload
if sender_idx is None:
raise PaymentFailure(failure_msg.code_name())
try:
fallback_channel = route[sender_idx + 1].short_channel_id
except IndexError:
raise PaymentFailure(f'payment destination reported error: {failure_msg.code_name()}') from None
# TODO: handle unknown next peer?
# handle failure codes that include a channel update
if code in failure_codes:
offset = failure_codes[code]
channel_update_len = int.from_bytes(data[offset:offset+2], byteorder="big")
channel_update_as_received = data[offset+2: offset+2+channel_update_len]
payload = self._decode_channel_update_msg(channel_update_as_received)
if payload is None:
self.logger.info(f'could not decode channel_update for failed htlc: '
f'{channel_update_as_received.hex()}')
self.network.path_finder.liquidity_hints.add_to_blacklist(fallback_channel)
else:
# apply the channel update or get blacklisted
blacklist, update = self._handle_chanupd_from_failed_htlc(
payload, route=route, sender_idx=sender_idx)
# we interpret a temporary channel failure as a liquidity issue
# in the channel and update our liquidity hints accordingly
if code == OnionFailureCode.TEMPORARY_CHANNEL_FAILURE:
self.network.path_finder.update_liquidity_hints(
route,
amount,
failing_channel=ShortChannelID(payload['short_channel_id']))
elif blacklist:
self.network.path_finder.liquidity_hints.add_to_blacklist(
payload['short_channel_id'])
# if we can't decide on some action, we are stuck
if not (blacklist or update):
raise PaymentFailure(failure_msg.code_name())
# for errors that do not include a channel update
else:
self.network.path_finder.liquidity_hints.add_to_blacklist(fallback_channel)
def _handle_chanupd_from_failed_htlc(self, payload, *, route, sender_idx) -> Tuple[bool, bool]:
blacklist = False
update = False
try:
r = self.channel_db.add_channel_update(payload, verify=True)
except InvalidGossipMsg:
return True, False # blacklist
short_channel_id = ShortChannelID(payload['short_channel_id'])
if r == UpdateStatus.GOOD:
self.logger.info(f"applied channel update to {short_channel_id}")
# TODO: add test for this
# FIXME: this does not work for our own unannounced channels.
for chan in self.channels.values():
if chan.short_channel_id == short_channel_id:
chan.set_remote_update(payload)
update = True
elif r == UpdateStatus.ORPHANED:
# maybe it is a private channel (and data in invoice was outdated)
self.logger.info(f"Could not find {short_channel_id}. maybe update is for private channel?")
start_node_id = route[sender_idx].node_id
update = self.channel_db.add_channel_update_for_private_channel(payload, start_node_id)
blacklist = not update
elif r == UpdateStatus.EXPIRED:
blacklist = True
elif r == UpdateStatus.DEPRECATED:
self.logger.info(f'channel update is not more recent.')
blacklist = True
elif r == UpdateStatus.UNCHANGED:
blacklist = True
return blacklist, update
@classmethod
def _decode_channel_update_msg(cls, chan_upd_msg: bytes) -> Optional[Dict[str, Any]]:
channel_update_as_received = chan_upd_msg
channel_update_typed = (258).to_bytes(length=2, byteorder="big") + channel_update_as_received
# note: some nodes put channel updates in error msgs with the leading msg_type already there.
# we try decoding both ways here.
try:
message_type, payload = decode_msg(channel_update_typed)
if payload['chain_hash'] != constants.net.rev_genesis_bytes(): raise Exception()
payload['raw'] = channel_update_typed
return payload
except: # FIXME: too broad
try:
message_type, payload = decode_msg(channel_update_as_received)
if payload['chain_hash'] != constants.net.rev_genesis_bytes(): raise Exception()
payload['raw'] = channel_update_as_received
return payload
except:
return None
@staticmethod
def _check_invoice(invoice: str, *, amount_msat: int = None) -> LnAddr:
addr = lndecode(invoice)
if addr.is_expired():
raise InvoiceError(_("This invoice has expired"))
if amount_msat: # replace amt in invoice. main usecase is paying zero amt invoices
existing_amt_msat = addr.get_amount_msat()
if existing_amt_msat and amount_msat < existing_amt_msat:
raise Exception("cannot pay lower amt than what is originally in LN invoice")
addr.amount = Decimal(amount_msat) / COIN / 1000
if addr.amount is None:
raise InvoiceError(_("Missing amount"))
if addr.get_min_final_cltv_expiry() > lnutil.NBLOCK_CLTV_EXPIRY_TOO_FAR_INTO_FUTURE:
raise InvoiceError("{}\n{}".format(
_("Invoice wants us to risk locking funds for unreasonably long."),
f"min_final_cltv_expiry: {addr.get_min_final_cltv_expiry()}"))
return addr
def is_trampoline_peer(self, node_id: bytes) -> bool:
# until trampoline is advertised in lnfeatures, check against hardcoded list
if is_hardcoded_trampoline(node_id):
return True
peer = self._peers.get(node_id)
if peer and peer.their_features.supports(LnFeatures.OPTION_TRAMPOLINE_ROUTING_OPT):
return True
return False
def suggest_peer(self) -> Optional[bytes]:
if self.channel_db:
return self.lnrater.suggest_peer()
else:
return random.choice(list(hardcoded_trampoline_nodes().values())).pubkey
async def create_routes_for_payment(
self, *,
amount_msat: int, # part of payment amount we want routes for now
final_total_msat: int, # total payment amount final receiver will get
invoice_pubkey,
min_cltv_expiry,
r_tags,
invoice_features: int,
payment_hash,
payment_secret,
trampoline_fee_level: int,
use_two_trampolines: bool,
fwd_trampoline_onion=None,
full_path: LNPaymentPath = None) -> AsyncGenerator[Tuple[LNPaymentRoute, int], None]:
"""Creates multiple routes for splitting a payment over the available
private channels.
We first try to conduct the payment over a single channel. If that fails
and mpp is supported by the receiver, we will split the payment."""
invoice_features = LnFeatures(invoice_features)
trampoline_features = LnFeatures.VAR_ONION_OPT
local_height = self.network.get_local_height()
my_active_channels = [chan for chan in self.channels.values() if
chan.is_active() and not chan.is_frozen_for_sending()]
try:
self.logger.info("trying single-part payment")
# try to send over a single channel
if not self.channel_db:
for chan in my_active_channels:
if not self.is_trampoline_peer(chan.node_id):
continue
if chan.node_id == invoice_pubkey:
trampoline_onion = None
trampoline_payment_secret = payment_secret
trampoline_total_msat = final_total_msat
amount_with_fees = amount_msat
cltv_delta = min_cltv_expiry
else:
trampoline_onion, amount_with_fees, cltv_delta = create_trampoline_route_and_onion(
amount_msat=amount_msat,
total_msat=final_total_msat,
min_cltv_expiry=min_cltv_expiry,
my_pubkey=self.node_keypair.pubkey,
invoice_pubkey=invoice_pubkey,
invoice_features=invoice_features,
node_id=chan.node_id,
r_tags=r_tags,
payment_hash=payment_hash,
payment_secret=payment_secret,
local_height=local_height,
trampoline_fee_level=trampoline_fee_level,
use_two_trampolines=use_two_trampolines)
trampoline_payment_secret = os.urandom(32)
trampoline_total_msat = amount_with_fees
if chan.available_to_spend(LOCAL, strict=True) < amount_with_fees:
continue
route = [
RouteEdge(
start_node=self.node_keypair.pubkey,
end_node=chan.node_id,
short_channel_id=chan.short_channel_id,
fee_base_msat=0,
fee_proportional_millionths=0,
cltv_expiry_delta=0,
node_features=trampoline_features)
]
yield route, amount_with_fees, trampoline_total_msat, amount_msat, cltv_delta, trampoline_payment_secret, trampoline_onion
break
else:
raise NoPathFound()
else: # local single-part route computation
route = await run_in_thread(
partial(
self.create_route_for_payment,
amount_msat=amount_msat,
invoice_pubkey=invoice_pubkey,
min_cltv_expiry=min_cltv_expiry,
r_tags=r_tags,
invoice_features=invoice_features,
my_sending_channels=my_active_channels,
full_path=full_path
)
)
yield route, amount_msat, final_total_msat, amount_msat, min_cltv_expiry, payment_secret, fwd_trampoline_onion
except NoPathFound: # fall back to payment splitting
self.logger.info("no path found, trying multi-part payment")
if not invoice_features.supports(LnFeatures.BASIC_MPP_OPT):
raise
channels_with_funds = {(chan.channel_id, chan.node_id): int(chan.available_to_spend(HTLCOwner.LOCAL))
for chan in my_active_channels}
self.logger.info(f"channels_with_funds: {channels_with_funds}")
if not self.channel_db:
# in the case of a legacy payment, we don't allow splitting via different
# trampoline nodes, as currently no forwarder supports this
use_single_node, _ = is_legacy_relay(invoice_features, r_tags)
split_configurations = suggest_splits(
amount_msat,
channels_with_funds,
exclude_multinode_payments=use_single_node,
exclude_single_part_payments=True,
# we don't split within a channel when sending to a trampoline node,
# the trampoline node will split for us
exclude_single_channel_splits=True,
)
self.logger.info(f'suggest_split {amount_msat} returned {len(split_configurations)} configurations')
for sc in split_configurations:
try:
self.logger.info(f"trying split configuration: {sc.config.values()} rating: {sc.rating}")
per_trampoline_channel_amounts = defaultdict(list)
# categorize by trampoline nodes for trampolin mpp construction
for (chan_id, _), part_amounts_msat in sc.config.items():
chan = self.channels[chan_id]
for part_amount_msat in part_amounts_msat:
per_trampoline_channel_amounts[chan.node_id].append((chan_id, part_amount_msat))
# for each trampoline forwarder, construct mpp trampoline
routes = []
for trampoline_node_id, trampoline_parts in per_trampoline_channel_amounts.items():
per_trampoline_amount = sum([x[1] for x in trampoline_parts])
trampoline_onion, per_trampoline_amount_with_fees, per_trampoline_cltv_delta = create_trampoline_route_and_onion(
amount_msat=per_trampoline_amount,
total_msat=final_total_msat,
min_cltv_expiry=min_cltv_expiry,
my_pubkey=self.node_keypair.pubkey,
invoice_pubkey=invoice_pubkey,
invoice_features=invoice_features,
node_id=trampoline_node_id,
r_tags=r_tags,
payment_hash=payment_hash,
payment_secret=payment_secret,
local_height=local_height,
trampoline_fee_level=trampoline_fee_level,
use_two_trampolines=use_two_trampolines)
# node_features is only used to determine is_tlv
per_trampoline_secret = os.urandom(32)
per_trampoline_fees = per_trampoline_amount_with_fees - per_trampoline_amount
self.logger.info(f'per trampoline fees: {per_trampoline_fees}')
for chan_id, part_amount_msat in trampoline_parts:
chan = self.channels[chan_id]
margin = chan.available_to_spend(LOCAL, strict=True) - part_amount_msat
delta_fee = min(per_trampoline_fees, margin)
# TODO: distribute trampoline fee over several channels?
part_amount_msat_with_fees = part_amount_msat + delta_fee
per_trampoline_fees -= delta_fee
route = [
RouteEdge(
start_node=self.node_keypair.pubkey,
end_node=trampoline_node_id,
short_channel_id=chan.short_channel_id,
fee_base_msat=0,
fee_proportional_millionths=0,
cltv_expiry_delta=0,
node_features=trampoline_features)
]
self.logger.info(f'adding route {part_amount_msat} {delta_fee} {margin}')
routes.append((route, part_amount_msat_with_fees, per_trampoline_amount_with_fees, part_amount_msat, per_trampoline_cltv_delta, per_trampoline_secret, trampoline_onion))
if per_trampoline_fees != 0:
self.logger.info('not enough margin to pay trampoline fee')
raise NoPathFound()
for route in routes:
yield route
return
except NoPathFound:
continue
else:
split_configurations = suggest_splits(
amount_msat,
channels_with_funds,
exclude_single_part_payments=True,
)
# We atomically loop through a split configuration. If there was
# a failure to find a path for a single part, we give back control
# after exhausting the split configuration.
yielded_from_split_configuration = False
self.logger.info(f'suggest_split {amount_msat} returned {len(split_configurations)} configurations')
for sc in split_configurations:
self.logger.info(f"trying split configuration: {list(sc.config.values())} rating: {sc.rating}")
for (chan_id, _), part_amounts_msat in sc.config.items():
for part_amount_msat in part_amounts_msat:
channel = self.channels[chan_id]
try:
route = await run_in_thread(
partial(
self.create_route_for_payment,
amount_msat=part_amount_msat,
invoice_pubkey=invoice_pubkey,
min_cltv_expiry=min_cltv_expiry,
r_tags=r_tags,
invoice_features=invoice_features,
my_sending_channels=[channel],
full_path=None
)
)
yield route, part_amount_msat, final_total_msat, part_amount_msat, min_cltv_expiry, payment_secret, fwd_trampoline_onion
yielded_from_split_configuration = True
except NoPathFound:
continue
if yielded_from_split_configuration:
return
raise NoPathFound()
@profiler
def create_route_for_payment(
self, *,
amount_msat: int,
invoice_pubkey: bytes,
min_cltv_expiry: int,
r_tags,
invoice_features: int,
my_sending_channels: List[Channel],
full_path: Optional[LNPaymentPath]) -> LNPaymentRoute:
my_sending_channels = {chan.short_channel_id: chan for chan in my_sending_channels
if chan.short_channel_id is not None}
# Collect all private edges from route hints.
# Note: if some route hints are multiple edges long, and these paths cross each other,
# we allow our path finding to cross the paths; i.e. the route hints are not isolated.
private_route_edges = {} # type: Dict[ShortChannelID, RouteEdge]
for private_path in r_tags:
# we need to shift the node pubkey by one towards the destination:
private_path_nodes = [edge[0] for edge in private_path][1:] + [invoice_pubkey]
private_path_rest = [edge[1:] for edge in private_path]
start_node = private_path[0][0]
for end_node, edge_rest in zip(private_path_nodes, private_path_rest):
short_channel_id, fee_base_msat, fee_proportional_millionths, cltv_expiry_delta = edge_rest
short_channel_id = ShortChannelID(short_channel_id)
# if we have a routing policy for this edge in the db, that takes precedence,
# as it is likely from a previous failure
channel_policy = self.channel_db.get_policy_for_node(
short_channel_id=short_channel_id,
node_id=start_node,
my_channels=my_sending_channels)
if channel_policy:
fee_base_msat = channel_policy.fee_base_msat
fee_proportional_millionths = channel_policy.fee_proportional_millionths
cltv_expiry_delta = channel_policy.cltv_expiry_delta
node_info = self.channel_db.get_node_info_for_node_id(node_id=end_node)
route_edge = RouteEdge(
start_node=start_node,
end_node=end_node,
short_channel_id=short_channel_id,
fee_base_msat=fee_base_msat,
fee_proportional_millionths=fee_proportional_millionths,
cltv_expiry_delta=cltv_expiry_delta,
node_features=node_info.features if node_info else 0)
private_route_edges[route_edge.short_channel_id] = route_edge
start_node = end_node
# now find a route, end to end: between us and the recipient
try:
route = self.network.path_finder.find_route(
nodeA=self.node_keypair.pubkey,
nodeB=invoice_pubkey,
invoice_amount_msat=amount_msat,
path=full_path,
my_sending_channels=my_sending_channels,
private_route_edges=private_route_edges)
except NoChannelPolicy as e:
raise NoPathFound() from e
if not route:
raise NoPathFound()
# test sanity
if not is_route_sane_to_use(route, amount_msat, min_cltv_expiry):
self.logger.info(f"rejecting insane route {route}")
raise NoPathFound()
assert len(route) > 0
if route[-1].end_node != invoice_pubkey:
raise LNPathInconsistent("last node_id != invoice pubkey")
# add features from invoice
route[-1].node_features |= invoice_features
return route
def add_request(self, amount_sat, message, expiry) -> str:
coro = self._add_request_coro(amount_sat, message, expiry)
fut = asyncio.run_coroutine_threadsafe(coro, self.network.asyncio_loop)
try:
return fut.result(timeout=5)
except concurrent.futures.TimeoutError:
raise Exception(_("add invoice timed out"))
@log_exceptions
async def create_invoice(
self, *,
amount_msat: Optional[int],
message: str,
expiry: int,
write_to_disk: bool = True,
) -> Tuple[LnAddr, str]:
timestamp = int(time.time())
routing_hints = await self._calc_routing_hints_for_invoice(amount_msat)
if not routing_hints:
self.logger.info(
"Warning. No routing hints added to invoice. "
"Other clients will likely not be able to send to us.")
# if not all hints are trampoline, do not create trampoline invoice
invoice_features = self.features.for_invoice()
trampoline_hints = []
for r in routing_hints:
node_id, short_channel_id, fee_base_msat, fee_proportional_millionths, cltv_expiry_delta = r[1][0]
if len(r[1])== 1 and self.is_trampoline_peer(node_id):
trampoline_hints.append(('t', (node_id, fee_base_msat, fee_proportional_millionths, cltv_expiry_delta)))
payment_preimage = os.urandom(32)
payment_hash = sha256(payment_preimage)
info = PaymentInfo(payment_hash, amount_msat, RECEIVED, PR_UNPAID)
amount_btc = amount_msat/Decimal(COIN*1000) if amount_msat else None
if expiry == 0:
expiry = LN_EXPIRY_NEVER
lnaddr = LnAddr(
paymenthash=payment_hash,
amount=amount_btc,
tags=[
('d', message),
('c', MIN_FINAL_CLTV_EXPIRY_FOR_INVOICE),
('x', expiry),
('9', invoice_features)]
+ routing_hints
+ trampoline_hints,
date=timestamp,
payment_secret=derive_payment_secret_from_payment_preimage(payment_preimage))
invoice = lnencode(lnaddr, self.node_keypair.privkey)
self.save_preimage(payment_hash, payment_preimage, write_to_disk=False)
self.save_payment_info(info, write_to_disk=False)
if write_to_disk:
self.wallet.save_db()
return lnaddr, invoice
async def _add_request_coro(self, amount_sat: Optional[int], message, expiry: int) -> str:
amount_msat = amount_sat * 1000 if amount_sat is not None else None
lnaddr, invoice = await self.create_invoice(
amount_msat=amount_msat,
message=message,
expiry=expiry,
write_to_disk=False,
)
key = bh2u(lnaddr.paymenthash)
req = LNInvoice.from_bech32(invoice)
self.wallet.add_payment_request(req, write_to_disk=False)
self.wallet.set_label(key, message)
self.wallet.save_db()
return key
def save_preimage(self, payment_hash: bytes, preimage: bytes, *, write_to_disk: bool = True):
assert sha256(preimage) == payment_hash
self.preimages[bh2u(payment_hash)] = bh2u(preimage)
if write_to_disk:
self.wallet.save_db()
def get_preimage(self, payment_hash: bytes) -> Optional[bytes]:
r = self.preimages.get(bh2u(payment_hash))
return bfh(r) if r else None
def get_payment_info(self, payment_hash: bytes) -> Optional[PaymentInfo]:
"""returns None if payment_hash is a payment we are forwarding"""
key = payment_hash.hex()
with self.lock:
if key in self.payments:
amount_msat, direction, status = self.payments[key]
return PaymentInfo(payment_hash, amount_msat, direction, status)
def save_payment_info(self, info: PaymentInfo, *, write_to_disk: bool = True) -> None:
key = info.payment_hash.hex()
assert info.status in SAVED_PR_STATUS
with self.lock:
self.payments[key] = info.amount_msat, info.direction, info.status
if write_to_disk:
self.wallet.save_db()
def check_received_mpp_htlc(self, payment_secret, short_channel_id, htlc: UpdateAddHtlc, expected_msat: int) -> Optional[bool]:
""" return MPP status: True (accepted), False (expired) or None """
payment_hash = htlc.payment_hash
is_expired, is_accepted, htlc_set = self.received_mpp_htlcs.get(payment_secret, (False, False, set()))
if self.get_payment_status(payment_hash) == PR_PAID:
# payment_status is persisted
is_accepted = True
is_expired = False
key = (short_channel_id, htlc)
if key not in htlc_set:
htlc_set.add(key)
if not is_accepted and not is_expired:
total = sum([_htlc.amount_msat for scid, _htlc in htlc_set])
first_timestamp = min([_htlc.timestamp for scid, _htlc in htlc_set])
if self.stopping_soon:
is_expired = True # try to time out pending HTLCs before shutting down
elif time.time() - first_timestamp > self.MPP_EXPIRY:
is_expired = True
elif total == expected_msat:
is_accepted = True
if is_accepted or is_expired:
htlc_set.remove(key)
if len(htlc_set) > 0:
self.received_mpp_htlcs[payment_secret] = is_expired, is_accepted, htlc_set
elif payment_secret in self.received_mpp_htlcs:
self.received_mpp_htlcs.pop(payment_secret)
return True if is_accepted else (False if is_expired else None)
def get_payment_status(self, payment_hash: bytes) -> int:
info = self.get_payment_info(payment_hash)
return info.status if info else PR_UNPAID
def get_invoice_status(self, invoice: LNInvoice) -> int:
key = invoice.rhash
log = self.logs[key]
if key in self.inflight_payments:
return PR_INFLIGHT
# status may be PR_FAILED
status = self.get_payment_status(bfh(key))
if status == PR_UNPAID and log:
status = PR_FAILED
return status
def set_invoice_status(self, key: str, status: int) -> None:
if status == PR_INFLIGHT:
self.inflight_payments.add(key)
elif key in self.inflight_payments:
self.inflight_payments.remove(key)
if status in SAVED_PR_STATUS:
self.set_payment_status(bfh(key), status)
util.trigger_callback('invoice_status', self.wallet, key)
def set_request_status(self, payment_hash: bytes, status: int) -> None:
if self.get_payment_status(payment_hash) != status:
self.set_payment_status(payment_hash, status)
util.trigger_callback('request_status', self.wallet, payment_hash.hex(), status)
def set_payment_status(self, payment_hash: bytes, status: int) -> None:
info = self.get_payment_info(payment_hash)
if info is None:
# if we are forwarding
return
info = info._replace(status=status)
self.save_payment_info(info)
def _on_maybe_forwarded_htlc_resolved(self, chan: Channel, htlc_id: int) -> None:
"""Called when an HTLC we offered on chan gets irrevocably fulfilled or failed.
If we find this was a forwarded HTLC, the upstream peer is notified.
"""
fw_info = chan.short_channel_id.hex(), htlc_id
upstream_peer_pubkey = self.downstream_htlc_to_upstream_peer_map.get(fw_info)
if not upstream_peer_pubkey:
return
upstream_peer = self.peers.get(upstream_peer_pubkey)
if not upstream_peer:
return
upstream_peer.downstream_htlc_resolved_event.set()
upstream_peer.downstream_htlc_resolved_event.clear()
def htlc_fulfilled(self, chan: Channel, payment_hash: bytes, htlc_id: int):
util.trigger_callback('htlc_fulfilled', payment_hash, chan, htlc_id)
self._on_maybe_forwarded_htlc_resolved(chan=chan, htlc_id=htlc_id)
q = self.sent_htlcs.get(payment_hash)
if q:
route, payment_secret, amount_msat, bucket_msat, amount_receiver_msat, trampoline_fee_level = self.sent_htlcs_info[(payment_hash, chan.short_channel_id, htlc_id)]
htlc_log = HtlcLog(
success=True,
route=route,
amount_msat=amount_receiver_msat,
trampoline_fee_level=trampoline_fee_level)
q.put_nowait(htlc_log)
else:
key = payment_hash.hex()
self.set_invoice_status(key, PR_PAID)
util.trigger_callback('payment_succeeded', self.wallet, key)
def htlc_failed(
self,
chan: Channel,
payment_hash: bytes,
htlc_id: int,
error_bytes: Optional[bytes],
failure_message: Optional['OnionRoutingFailure']):
util.trigger_callback('htlc_failed', payment_hash, chan, htlc_id)
self._on_maybe_forwarded_htlc_resolved(chan=chan, htlc_id=htlc_id)
q = self.sent_htlcs.get(payment_hash)
if q:
# detect if it is part of a bucket
# if yes, wait until the bucket completely failed
key = (payment_hash, chan.short_channel_id, htlc_id)
route, payment_secret, amount_msat, bucket_msat, amount_receiver_msat, trampoline_fee_level = self.sent_htlcs_info[key]
if error_bytes:
# TODO "decode_onion_error" might raise, catch and maybe blacklist/penalise someone?
try:
failure_message, sender_idx = chan.decode_onion_error(error_bytes, route, htlc_id)
except Exception as e:
sender_idx = None
failure_message = OnionRoutingFailure(-1, str(e))
else:
# probably got "update_fail_malformed_htlc". well... who to penalise now?
assert failure_message is not None
sender_idx = None
self.logger.info(f"htlc_failed {failure_message}")
# check sent_buckets if we use trampoline
if not self.channel_db and payment_secret in self.sent_buckets:
amount_sent, amount_failed = self.sent_buckets[payment_secret]
amount_failed += amount_receiver_msat
self.sent_buckets[payment_secret] = amount_sent, amount_failed
if amount_sent != amount_failed:
self.logger.info('bucket still active...')
return
self.logger.info('bucket failed')
amount_receiver_msat = amount_sent
htlc_log = HtlcLog(
success=False,
route=route,
amount_msat=amount_receiver_msat,
error_bytes=error_bytes,
failure_msg=failure_message,
sender_idx=sender_idx,
trampoline_fee_level=trampoline_fee_level)
q.put_nowait(htlc_log)
else:
self.logger.info(f"received unknown htlc_failed, probably from previous session")
key = payment_hash.hex()
self.set_invoice_status(key, PR_UNPAID)
util.trigger_callback('payment_failed', self.wallet, key, '')
async def _calc_routing_hints_for_invoice(self, amount_msat: Optional[int]):
"""calculate routing hints (BOLT-11 'r' field)"""
routing_hints = []
channels = list(self.channels.values())
# do minimal filtering of channels.
# we include channels that cannot *right now* receive (e.g. peer disconnected or balance insufficient)
channels = [chan for chan in channels
if (chan.is_open() and not chan.is_frozen_for_receiving())]
# Filter out channels that have very low receive capacity compared to invoice amt.
# Even with MPP, below a certain threshold, including these channels probably
# hurts more than help, as they lead to many failed attempts for the sender.
channels = [chan for chan in channels
if chan.available_to_spend(REMOTE) > (amount_msat or 0) * 0.05]
# cap max channels to include to keep QR code reasonably scannable
channels = sorted(channels, key=lambda chan: (not chan.is_active(), -chan.available_to_spend(REMOTE)))
channels = channels[:15]
random.shuffle(channels) # let's not leak channel order
scid_to_my_channels = {chan.short_channel_id: chan for chan in channels
if chan.short_channel_id is not None}
for chan in channels:
chan_id = chan.short_channel_id
assert isinstance(chan_id, bytes), chan_id
channel_info = get_mychannel_info(chan_id, scid_to_my_channels)
# note: as a fallback, if we don't have a channel update for the
# incoming direction of our private channel, we fill the invoice with garbage.
# the sender should still be able to pay us, but will incur an extra round trip
# (they will get the channel update from the onion error)
# at least, that's the theory. https://github.com/lightningnetwork/lnd/issues/2066
fee_base_msat = fee_proportional_millionths = 0
cltv_expiry_delta = 1 # lnd won't even try with zero
missing_info = True
if channel_info:
policy = get_mychannel_policy(channel_info.short_channel_id, chan.node_id, scid_to_my_channels)
if policy:
fee_base_msat = policy.fee_base_msat
fee_proportional_millionths = policy.fee_proportional_millionths
cltv_expiry_delta = policy.cltv_expiry_delta
missing_info = False
if missing_info:
self.logger.info(
f"Warning. Missing channel update for our channel {chan_id}; "
f"filling invoice with incorrect data.")
routing_hints.append(('r', [(
chan.node_id,
chan_id,
fee_base_msat,
fee_proportional_millionths,
cltv_expiry_delta)]))
return routing_hints
def delete_payment(self, payment_hash_hex: str):
try:
with self.lock:
del self.payments[payment_hash_hex]
except KeyError:
return
self.wallet.save_db()
def get_balance(self):
with self.lock:
return Decimal(sum(
chan.balance(LOCAL) if not chan.is_closed() else 0
for chan in self.channels.values())) / 1000
def num_sats_can_send(self) -> Decimal:
can_send = 0
with self.lock:
if self.channels:
for c in self.channels.values():
if c.is_active() and not c.is_frozen_for_sending():
can_send += c.available_to_spend(LOCAL)
# Here we have to guess a fee, because some callers (submarine swaps)
# use this method to initiate a payment, which would otherwise fail.
fee_base_msat = TRAMPOLINE_FEES[3]['fee_base_msat']
fee_proportional_millionths = TRAMPOLINE_FEES[3]['fee_proportional_millionths']
# inverse of fee_for_edge_msat
can_send_minus_fees = (can_send - fee_base_msat) * 1_000_000 // ( 1_000_000 + fee_proportional_millionths)
can_send_minus_fees = max(0, can_send_minus_fees)
return Decimal(can_send_minus_fees) / 1000
def num_sats_can_receive(self) -> Decimal:
with self.lock:
channels = [
c for c in self.channels.values()
if c.is_active() and not c.is_frozen_for_receiving()
]
can_receive = sum([c.available_to_spend(REMOTE) for c in channels]) if channels else 0
return Decimal(can_receive) / 1000
def num_sats_can_receive_no_mpp(self) -> Decimal:
with self.lock:
channels = [
c for c in self.channels.values()
if c.is_active() and not c.is_frozen_for_receiving()
]
can_receive = max([c.available_to_spend(REMOTE) for c in channels]) if channels else 0
return Decimal(can_receive) / 1000
def can_pay_invoice(self, invoice: LNInvoice) -> bool:
return invoice.get_amount_sat() <= self.num_sats_can_send()
def can_receive_invoice(self, invoice: LNInvoice) -> bool:
return invoice.get_amount_sat() <= self.num_sats_can_receive()
async def close_channel(self, chan_id):
chan = self._channels[chan_id]
peer = self._peers[chan.node_id]
return await peer.close_channel(chan_id)
def _force_close_channel(self, chan_id: bytes) -> Transaction:
chan = self._channels[chan_id]
tx = chan.force_close_tx()
# We set the channel state to make sure we won't sign new commitment txs.
# We expect the caller to try to broadcast this tx, after which it is
# not safe to keep using the channel even if the broadcast errors (server could be lying).
# Until the tx is seen in the mempool, there will be automatic rebroadcasts.
chan.set_state(ChannelState.FORCE_CLOSING)
# Add local tx to wallet to also allow manual rebroadcasts.
try:
self.wallet.add_transaction(tx)
except UnrelatedTransactionException:
pass # this can happen if (~all the balance goes to REMOTE)
return tx
async def force_close_channel(self, chan_id: bytes) -> str:
"""Force-close the channel. Network-related exceptions are propagated to the caller.
(automatic rebroadcasts will be scheduled)
"""
# note: as we are async, it can take a few event loop iterations between the caller
# "calling us" and us getting to run, and we only set the channel state now:
tx = self._force_close_channel(chan_id)
await self.network.broadcast_transaction(tx)
return tx.txid()
def schedule_force_closing(self, chan_id: bytes) -> 'asyncio.Task[None]':
"""Schedules a task to force-close the channel and returns it.
Network-related exceptions are suppressed.
(automatic rebroadcasts will be scheduled)
Note: this method is intentionally not async so that callers have a guarantee
that the channel state is set immediately.
"""
tx = self._force_close_channel(chan_id)
return asyncio.create_task(self.network.try_broadcasting(tx, 'force-close'))
def remove_channel(self, chan_id):
chan = self.channels[chan_id]
assert chan.can_be_deleted()
with self.lock:
self._channels.pop(chan_id)
self.db.get('channels').pop(chan_id.hex())
for addr in chan.get_wallet_addresses_channel_might_want_reserved():
self.wallet.set_reserved_state_of_address(addr, reserved=False)
util.trigger_callback('channels_updated', self.wallet)
util.trigger_callback('wallet_updated', self.wallet)
@ignore_exceptions
@log_exceptions
async def reestablish_peer_for_given_channel(self, chan: Channel) -> None:
now = time.time()
peer_addresses = []
if not self.channel_db:
addr = trampolines_by_id().get(chan.node_id)
if addr:
peer_addresses.append(addr)
else:
# will try last good address first, from gossip
last_good_addr = self.channel_db.get_last_good_address(chan.node_id)
if last_good_addr:
peer_addresses.append(last_good_addr)
# will try addresses for node_id from gossip
addrs_from_gossip = self.channel_db.get_node_addresses(chan.node_id) or []
for host, port, ts in addrs_from_gossip:
peer_addresses.append(LNPeerAddr(host, port, chan.node_id))
# will try addresses stored in channel storage
peer_addresses += list(chan.get_peer_addresses())
# Done gathering addresses.
# Now select first one that has not failed recently.
for peer in peer_addresses:
if self._can_retry_addr(peer, urgent=True, now=now):
await self._add_peer(peer.host, peer.port, peer.pubkey)
return
async def reestablish_peers_and_channels(self):
while True:
await asyncio.sleep(1)
if self.stopping_soon:
return
for chan in self.channels.values():
if chan.is_closed():
continue
# reestablish
if not chan.should_try_to_reestablish_peer():
continue
peer = self._peers.get(chan.node_id, None)
if peer:
await peer.taskgroup.spawn(peer.reestablish_channel(chan))
else:
await self.taskgroup.spawn(self.reestablish_peer_for_given_channel(chan))
def current_feerate_per_kw(self):
from .simple_config import FEE_LN_ETA_TARGET, FEERATE_FALLBACK_STATIC_FEE, FEERATE_REGTEST_HARDCODED
from .simple_config import FEERATE_PER_KW_MIN_RELAY_LIGHTNING
if constants.net is constants.BitcoinRegtest:
return FEERATE_REGTEST_HARDCODED // 4
feerate_per_kvbyte = self.network.config.eta_target_to_fee(FEE_LN_ETA_TARGET)
if feerate_per_kvbyte is None:
feerate_per_kvbyte = FEERATE_FALLBACK_STATIC_FEE
return max(FEERATE_PER_KW_MIN_RELAY_LIGHTNING, feerate_per_kvbyte // 4)
def create_channel_backup(self, channel_id):
chan = self._channels[channel_id]
# do not backup old-style channels
assert chan.is_static_remotekey_enabled()
peer_addresses = list(chan.get_peer_addresses())
peer_addr = peer_addresses[0]
return ImportedChannelBackupStorage(
node_id = chan.node_id,
privkey = self.node_keypair.privkey,
funding_txid = chan.funding_outpoint.txid,
funding_index = chan.funding_outpoint.output_index,
funding_address = chan.get_funding_address(),
host = peer_addr.host,
port = peer_addr.port,
is_initiator = chan.constraints.is_initiator,
channel_seed = chan.config[LOCAL].channel_seed,
local_delay = chan.config[LOCAL].to_self_delay,
remote_delay = chan.config[REMOTE].to_self_delay,
remote_revocation_pubkey = chan.config[REMOTE].revocation_basepoint.pubkey,
remote_payment_pubkey = chan.config[REMOTE].payment_basepoint.pubkey)
def export_channel_backup(self, channel_id):
xpub = self.wallet.get_fingerprint()
backup_bytes = self.create_channel_backup(channel_id).to_bytes()
assert backup_bytes == ImportedChannelBackupStorage.from_bytes(backup_bytes).to_bytes(), "roundtrip failed"
encrypted = pw_encode_with_version_and_mac(backup_bytes, xpub)
assert backup_bytes == pw_decode_with_version_and_mac(encrypted, xpub), "encrypt failed"
return 'channel_backup:' + encrypted
async def request_force_close(self, channel_id: bytes, *, connect_str=None) -> None:
if channel_id in self.channels:
chan = self.channels[channel_id]
peer = self._peers.get(chan.node_id)
if not peer:
raise Exception('Peer not found')
chan.should_request_force_close = True
peer.close_and_cleanup()
elif connect_str:
peer = await self.add_peer(connect_str)
await peer.trigger_force_close(channel_id)
elif channel_id in self.channel_backups:
await self._request_force_close_from_backup(channel_id)
else:
raise Exception(f'Unknown channel {channel_id.hex()}')
def import_channel_backup(self, data):
assert data.startswith('channel_backup:')
encrypted = data[15:]
xpub = self.wallet.get_fingerprint()
decrypted = pw_decode_with_version_and_mac(encrypted, xpub)
cb_storage = ImportedChannelBackupStorage.from_bytes(decrypted)
channel_id = cb_storage.channel_id()
if channel_id.hex() in self.db.get_dict("channels"):
raise Exception('Channel already in wallet')
self.logger.info(f'importing channel backup: {channel_id.hex()}')
d = self.db.get_dict("imported_channel_backups")
d[channel_id.hex()] = cb_storage
with self.lock:
cb = ChannelBackup(cb_storage, sweep_address=self.sweep_address, lnworker=self)
self._channel_backups[channel_id] = cb
self.wallet.save_db()
util.trigger_callback('channels_updated', self.wallet)
self.lnwatcher.add_channel(cb.funding_outpoint.to_str(), cb.get_funding_address())
def has_conflicting_backup_with(self, remote_node_id: bytes):
""" Returns whether we have an active channel with this node on another device, using same local node id. """
channel_backup_peers = [
cb.node_id for cb in self.channel_backups.values()
if (not cb.is_closed() and cb.get_local_pubkey() == self.node_keypair.pubkey)]
return any(remote_node_id.startswith(cb_peer_nodeid) for cb_peer_nodeid in channel_backup_peers)
def remove_channel_backup(self, channel_id):
chan = self.channel_backups[channel_id]
assert chan.can_be_deleted()
onchain_backups = self.db.get_dict("onchain_channel_backups")
imported_backups = self.db.get_dict("imported_channel_backups")
if channel_id.hex() in onchain_backups:
onchain_backups.pop(channel_id.hex())
elif channel_id.hex() in imported_backups:
imported_backups.pop(channel_id.hex())
else:
raise Exception('Channel not found')
with self.lock:
self._channel_backups.pop(channel_id)
self.wallet.save_db()
util.trigger_callback('channels_updated', self.wallet)
@log_exceptions
async def _request_force_close_from_backup(self, channel_id: bytes):
cb = self.channel_backups.get(channel_id)
if not cb:
raise Exception(f'channel backup not found {self.channel_backups}')
cb = cb.cb # storage
self.logger.info(f'requesting channel force close: {channel_id.hex()}')
if isinstance(cb, ImportedChannelBackupStorage):
node_id = cb.node_id
privkey = cb.privkey
addresses = [(cb.host, cb.port, 0)]
# TODO also try network addresses from gossip db (as it might have changed)
else:
assert isinstance(cb, OnchainChannelBackupStorage)
if not self.channel_db:
raise Exception('Enable gossip first')
node_id = self.network.channel_db.get_node_by_prefix(cb.node_id_prefix)
privkey = self.node_keypair.privkey
addresses = self.network.channel_db.get_node_addresses(node_id)
if not addresses:
raise Exception('Peer not found in gossip database')
for host, port, timestamp in addresses:
peer_addr = LNPeerAddr(host, port, node_id)
transport = LNTransport(privkey, peer_addr, proxy=self.network.proxy)
peer = Peer(self, node_id, transport, is_channel_backup=True)
try:
async with OldTaskGroup(wait=any) as group:
await group.spawn(peer._message_loop())
await group.spawn(peer.trigger_force_close(channel_id))
return
except Exception as e:
self.logger.info(f'failed to connect {host} {e}')
continue
else:
raise Exception('failed to connect')
def maybe_add_backup_from_tx(self, tx):
funding_address = None
node_id_prefix = None
for i, o in enumerate(tx.outputs()):
script_type = get_script_type_from_output_script(o.scriptpubkey)
if script_type == 'p2wsh':
funding_index = i
funding_address = o.address
for o2 in tx.outputs():
if o2.scriptpubkey.startswith(bytes([opcodes.OP_RETURN])):
encrypted_data = o2.scriptpubkey[2:]
data = self.decrypt_cb_data(encrypted_data, funding_address)
if data.startswith(CB_MAGIC_BYTES):
node_id_prefix = data[4:]
if node_id_prefix is None:
return
funding_txid = tx.txid()
cb_storage = OnchainChannelBackupStorage(
node_id_prefix = node_id_prefix,
funding_txid = funding_txid,
funding_index = funding_index,
funding_address = funding_address,
is_initiator = True)
channel_id = cb_storage.channel_id().hex()
if channel_id in self.db.get_dict("channels"):
return
self.logger.info(f"adding backup from tx")
d = self.db.get_dict("onchain_channel_backups")
d[channel_id] = cb_storage
cb = ChannelBackup(cb_storage, sweep_address=self.sweep_address, lnworker=self)
self.wallet.save_db()
with self.lock:
self._channel_backups[bfh(channel_id)] = cb
util.trigger_callback('channels_updated', self.wallet)
self.lnwatcher.add_channel(cb.funding_outpoint.to_str(), cb.get_funding_address())
| 49.358844 | 201 | 0.631671 |
import asyncio
import os
from decimal import Decimal
import random
import time
from typing import (Optional, Sequence, Tuple, List, Set, Dict, TYPE_CHECKING,
NamedTuple, Union, Mapping, Any, Iterable, AsyncGenerator, DefaultDict)
import threading
import socket
import aiohttp
import json
from datetime import datetime, timezone
from functools import partial
from collections import defaultdict
import concurrent
from concurrent import futures
import urllib.parse
import dns.resolver
import dns.exception
from aiorpcx import run_in_thread, NetAddress, ignore_after
from . import constants, util
from . import keystore
from .util import profiler, chunks, OldTaskGroup
from .invoices import PR_TYPE_LN, PR_UNPAID, PR_EXPIRED, PR_PAID, PR_INFLIGHT, PR_FAILED, PR_ROUTING, LNInvoice, LN_EXPIRY_NEVER
from .util import NetworkRetryManager, JsonRPCClient
from .lnutil import LN_MAX_FUNDING_SAT
from .keystore import BIP32_KeyStore
from .bitcoin import COIN
from .bitcoin import opcodes, make_op_return, address_to_scripthash
from .transaction import Transaction
from .transaction import get_script_type_from_output_script
from .crypto import sha256
from .bip32 import BIP32Node
from .util import bh2u, bfh, InvoiceError, resolve_dns_srv, is_ip_address, log_exceptions
from .crypto import chacha20_encrypt, chacha20_decrypt
from .util import ignore_exceptions, make_aiohttp_session
from .util import timestamp_to_datetime, random_shuffled_copy
from .util import MyEncoder, is_private_netaddress, UnrelatedTransactionException
from .logging import Logger
from .lntransport import LNTransport, LNResponderTransport, LNTransportBase
from .lnpeer import Peer, LN_P2P_NETWORK_TIMEOUT
from .lnaddr import lnencode, LnAddr, lndecode
from .ecc import der_sig_from_sig_string
from .lnchannel import Channel, AbstractChannel
from .lnchannel import ChannelState, PeerState, HTLCWithStatus
from .lnrater import LNRater
from . import lnutil
from .lnutil import funding_output_script
from .bitcoin import redeem_script_to_address
from .lnutil import (Outpoint, LNPeerAddr,
get_compressed_pubkey_from_bech32, extract_nodeid,
PaymentFailure, split_host_port, ConnStringFormatError,
generate_keypair, LnKeyFamily, LOCAL, REMOTE,
MIN_FINAL_CLTV_EXPIRY_FOR_INVOICE,
NUM_MAX_EDGES_IN_PAYMENT_PATH, SENT, RECEIVED, HTLCOwner,
UpdateAddHtlc, Direction, LnFeatures, ShortChannelID,
HtlcLog, derive_payment_secret_from_payment_preimage,
NoPathFound, InvalidGossipMsg)
from .lnutil import ln_dummy_address, ln_compare_features, IncompatibleLightningFeatures
from .transaction import PartialTxOutput, PartialTransaction, PartialTxInput
from .lnonion import OnionFailureCode, OnionRoutingFailure
from .lnmsg import decode_msg
from .i18n import _
from .lnrouter import (RouteEdge, LNPaymentRoute, LNPaymentPath, is_route_sane_to_use,
NoChannelPolicy, LNPathInconsistent)
from .address_synchronizer import TX_HEIGHT_LOCAL
from . import lnsweep
from .lnwatcher import LNWalletWatcher
from .crypto import pw_encode_with_version_and_mac, pw_decode_with_version_and_mac
from .lnutil import ImportedChannelBackupStorage, OnchainChannelBackupStorage
from .lnchannel import ChannelBackup
from .channel_db import UpdateStatus
from .channel_db import get_mychannel_info, get_mychannel_policy
from .submarine_swaps import SwapManager
from .channel_db import ChannelInfo, Policy
from .mpp_split import suggest_splits
from .trampoline import create_trampoline_route_and_onion, TRAMPOLINE_FEES, is_legacy_relay
if TYPE_CHECKING:
from .network import Network
from .wallet import Abstract_Wallet
from .channel_db import ChannelDB
from .simple_config import SimpleConfig
SAVED_PR_STATUS = [PR_PAID, PR_UNPAID]
NUM_PEERS_TARGET = 4
CB_VERSION = 0
CB_MAGIC_BYTES = bytes([0, 0, 0, CB_VERSION])
FALLBACK_NODE_LIST_TESTNET = (
LNPeerAddr(host='203.132.95.10', port=9735, pubkey=bfh('038863cf8ab91046230f561cd5b386cbff8309fa02e3f0c3ed161a3aeb64a643b9')),
LNPeerAddr(host='2401:d002:4402:0:bf1d:986a:7598:6d49', port=9735, pubkey=bfh('038863cf8ab91046230f561cd5b386cbff8309fa02e3f0c3ed161a3aeb64a643b9')),
LNPeerAddr(host='50.116.3.223', port=9734, pubkey=bfh('03236a685d30096b26692dce0cf0fa7c8528bdf61dbf5363a3ef6d5c92733a3016')),
LNPeerAddr(host='3.16.119.191', port=9735, pubkey=bfh('03d5e17a3c213fe490e1b0c389f8cfcfcea08a29717d50a9f453735e0ab2a7c003')),
LNPeerAddr(host='34.250.234.192', port=9735, pubkey=bfh('03933884aaf1d6b108397e5efe5c86bcf2d8ca8d2f700eda99db9214fc2712b134')),
LNPeerAddr(host='88.99.209.230', port=9735, pubkey=bfh('0260d9119979caedc570ada883ff614c6efb93f7f7382e25d73ecbeba0b62df2d7')),
LNPeerAddr(host='160.16.233.215', port=9735, pubkey=bfh('023ea0a53af875580899da0ab0a21455d9c19160c4ea1b7774c9d4be6810b02d2c')),
LNPeerAddr(host='197.155.6.173', port=9735, pubkey=bfh('0269a94e8b32c005e4336bfb743c08a6e9beb13d940d57c479d95c8e687ccbdb9f')),
LNPeerAddr(host='2c0f:fb18:406::4', port=9735, pubkey=bfh('0269a94e8b32c005e4336bfb743c08a6e9beb13d940d57c479d95c8e687ccbdb9f')),
LNPeerAddr(host='163.172.94.64', port=9735, pubkey=bfh('030f0bf260acdbd3edcad84d7588ec7c5df4711e87e6a23016f989b8d3a4147230')),
LNPeerAddr(host='23.237.77.12', port=9735, pubkey=bfh('02312627fdf07fbdd7e5ddb136611bdde9b00d26821d14d94891395452f67af248')),
LNPeerAddr(host='197.155.6.172', port=9735, pubkey=bfh('02ae2f22b02375e3e9b4b4a2db4f12e1b50752b4062dbefd6e01332acdaf680379')),
LNPeerAddr(host='2c0f:fb18:406::3', port=9735, pubkey=bfh('02ae2f22b02375e3e9b4b4a2db4f12e1b50752b4062dbefd6e01332acdaf680379')),
LNPeerAddr(host='23.239.23.44', port=9740, pubkey=bfh('034fe52e98a0e9d3c21b767e1b371881265d8c7578c21f5afd6d6438da10348b36')),
LNPeerAddr(host='2600:3c01::f03c:91ff:fe05:349c', port=9740, pubkey=bfh('034fe52e98a0e9d3c21b767e1b371881265d8c7578c21f5afd6d6438da10348b36')),
)
FALLBACK_NODE_LIST_MAINNET = [
LNPeerAddr(host='172.81.181.3', port=9735, pubkey=bfh('0214382bdce7750dfcb8126df8e2b12de38536902dc36abcebdaeefdeca1df8284')),
LNPeerAddr(host='35.230.100.60', port=9735, pubkey=bfh('023f5e3582716bed96f6f26cfcd8037e07474d7b4743afdc8b07e692df63464d7e')),
LNPeerAddr(host='40.69.71.114', port=9735, pubkey=bfh('028303182c9885da93b3b25c9621d22cf34475e63c123942e402ab530c0556e675')),
LNPeerAddr(host='94.177.171.73', port=9735, pubkey=bfh('0276e09a267592e7451a939c932cf685f0754de382a3ca85d2fb3a864d4c365ad5')),
LNPeerAddr(host='34.236.113.58', port=9735, pubkey=bfh('02fa50c72ee1e2eb5f1b6d9c3032080c4c864373c4201dfa2966aa34eee1051f97')),
LNPeerAddr(host='52.50.244.44', port=9735, pubkey=bfh('030c3f19d742ca294a55c00376b3b355c3c90d61c6b6b39554dbc7ac19b141c14f')),
LNPeerAddr(host='157.245.68.47', port=9735, pubkey=bfh('03c2abfa93eacec04721c019644584424aab2ba4dff3ac9bdab4e9c97007491dda')),
LNPeerAddr(host='18.221.23.28', port=9735, pubkey=bfh('03abf6f44c355dec0d5aa155bdbdd6e0c8fefe318eff402de65c6eb2e1be55dc3e')),
LNPeerAddr(host='52.224.178.244', port=9735, pubkey=bfh('026b105ac13212c48714c6be9b11577a9ce10f10e1c88a45ce217e6331209faf8b')),
LNPeerAddr(host='34.239.230.56', port=9735, pubkey=bfh('03864ef025fde8fb587d989186ce6a4a186895ee44a926bfc370e2c366597a3f8f')),
LNPeerAddr(host='46.229.165.136', port=9735, pubkey=bfh('0390b5d4492dc2f5318e5233ab2cebf6d48914881a33ef6a9c6bcdbb433ad986d0')),
LNPeerAddr(host='157.230.28.160', port=9735, pubkey=bfh('0279c22ed7a068d10dc1a38ae66d2d6461e269226c60258c021b1ddcdfe4b00bc4')),
LNPeerAddr(host='74.108.13.152', port=9735, pubkey=bfh('0331f80652fb840239df8dc99205792bba2e559a05469915804c08420230e23c7c')),
LNPeerAddr(host='167.172.44.148', port=9735, pubkey=bfh('0395033b252c6f40e3756984162d68174e2bd8060a129c0d3462a9370471c6d28f')),
LNPeerAddr(host='138.68.14.104', port=9735, pubkey=bfh('03bb88ccc444534da7b5b64b4f7b15e1eccb18e102db0e400d4b9cfe93763aa26d')),
LNPeerAddr(host='3.124.63.44', port=9735, pubkey=bfh('0242a4ae0c5bef18048fbecf995094b74bfb0f7391418d71ed394784373f41e4f3')),
LNPeerAddr(host='2001:470:8:2e1::43', port=9735, pubkey=bfh('03baa70886d9200af0ffbd3f9e18d96008331c858456b16e3a9b41e735c6208fef')),
LNPeerAddr(host='2601:186:c100:6bcd:219:d1ff:fe75:dc2f', port=9735, pubkey=bfh('0298f6074a454a1f5345cb2a7c6f9fce206cd0bf675d177cdbf0ca7508dd28852f')),
LNPeerAddr(host='2001:41d0:e:734::1', port=9735, pubkey=bfh('03a503d8e30f2ff407096d235b5db63b4fcf3f89a653acb6f43d3fc492a7674019')),
LNPeerAddr(host='2a01:4f9:2b:2254::2', port=9735, pubkey=bfh('02f3069a342ae2883a6f29e275f06f28a56a6ea2e2d96f5888a3266444dcf542b6')),
LNPeerAddr(host='2a02:8070:24c1:100:528c:2997:6dbc:a054', port=9735, pubkey=bfh('02a45def9ae014fdd2603dd7033d157faa3a55a72b06a63ae22ef46d9fafdc6e8d')),
LNPeerAddr(host='2600:3c01::f03c:91ff:fe05:349c', port=9736, pubkey=bfh('02731b798b39a09f9f14e90ee601afb6ebb796d6e5797de14582a978770b33700f')),
LNPeerAddr(host='2a00:8a60:e012:a00::21', port=9735, pubkey=bfh('027ce055380348d7812d2ae7745701c9f93e70c1adeb2657f053f91df4f2843c71')),
LNPeerAddr(host='2604:a880:400:d1::8bd:1001', port=9735, pubkey=bfh('03649c72a4816f0cd546f84aafbd657e92a30ab474de7ab795e8b5650a427611f7')),
LNPeerAddr(host='2a01:4f8:c0c:7b31::1', port=9735, pubkey=bfh('02c16cca44562b590dd279c942200bdccfd4f990c3a69fad620c10ef2f8228eaff')),
LNPeerAddr(host='2001:41d0:1:b40d::1', port=9735, pubkey=bfh('026726a4b043d413b45b334876d17b8a98848129604429ec65532ba286a42efeac')),
]
from .trampoline import trampolines_by_id, hardcoded_trampoline_nodes, is_hardcoded_trampoline
class PaymentInfo(NamedTuple):
payment_hash: bytes
amount_msat: Optional[int]
direction: int
status: int
class ErrorAddingPeer(Exception): pass
BASE_FEATURES = LnFeatures(0)\
| LnFeatures.OPTION_DATA_LOSS_PROTECT_OPT\
| LnFeatures.OPTION_STATIC_REMOTEKEY_OPT\
| LnFeatures.VAR_ONION_OPT\
| LnFeatures.PAYMENT_SECRET_OPT\
| LnFeatures.OPTION_UPFRONT_SHUTDOWN_SCRIPT_OPT\
LNWALLET_FEATURES = BASE_FEATURES\
| LnFeatures.OPTION_DATA_LOSS_PROTECT_REQ\
| LnFeatures.OPTION_STATIC_REMOTEKEY_REQ\
| LnFeatures.GOSSIP_QUERIES_REQ\
| LnFeatures.BASIC_MPP_OPT\
| LnFeatures.OPTION_TRAMPOLINE_ROUTING_OPT\
| LnFeatures.OPTION_SHUTDOWN_ANYSEGWIT_OPT\
| LnFeatures.OPTION_CHANNEL_TYPE_OPT\
LNGOSSIP_FEATURES = BASE_FEATURES\
| LnFeatures.GOSSIP_QUERIES_OPT\
| LnFeatures.GOSSIP_QUERIES_REQ\
class LNWorker(Logger, NetworkRetryManager[LNPeerAddr]):
INITIAL_TRAMPOLINE_FEE_LEVEL = 1
def __init__(self, xprv, features: LnFeatures):
Logger.__init__(self)
NetworkRetryManager.__init__(
self,
max_retry_delay_normal=3600,
init_retry_delay_normal=600,
max_retry_delay_urgent=300,
init_retry_delay_urgent=4,
)
self.lock = threading.RLock()
self.node_keypair = generate_keypair(BIP32Node.from_xkey(xprv), LnKeyFamily.NODE_KEY)
self.backup_key = generate_keypair(BIP32Node.from_xkey(xprv), LnKeyFamily.BACKUP_CIPHER).privkey
self._peers = {} f.listen_server = None
self.features = features
self.network = None
self.config = None
self.stopping_soon = False
util.register_callback(self.on_proxy_changed, ['proxy_set'])
@property
def channel_db(self):
return self.network.channel_db if self.network else None
@property
def peers(self) -> Mapping[bytes, Peer]:
with self.lock:
return self._peers.copy()
def channels_for_peer(self, node_id: bytes) -> Dict[bytes, Channel]:
return {}
def get_node_alias(self, node_id: bytes) -> Optional[str]:
node_alias = None
if self.channel_db:
node_info = self.channel_db.get_node_info_for_node_id(node_id)
if node_info:
node_alias = node_info.alias
else:
for k, v in hardcoded_trampoline_nodes().items():
if v.pubkey == node_id:
node_alias = k
break
return node_alias
async def maybe_listen(self):
listen_addr = self.config.get('lightning_listen')
if listen_addr:
self.logger.info(f'lightning_listen enabled. will try to bind: {listen_addr!r}')
try:
netaddr = NetAddress.from_string(listen_addr)
except Exception as e:
self.logger.error(f"failed to parse config key 'lightning_listen'. got: {e!r}")
return
addr = str(netaddr.host)
async def cb(reader, writer):
transport = LNResponderTransport(self.node_keypair.privkey, reader, writer)
try:
node_id = await transport.handshake()
except Exception as e:
self.logger.info(f'handshake failure from incoming connection: {e!r}')
return
await self._add_peer_from_transport(node_id=node_id, transport=transport)
try:
self.listen_server = await asyncio.start_server(cb, addr, netaddr.port)
except OSError as e:
self.logger.error(f"cannot listen for lightning p2p. error: {e!r}")
@ignore_exceptions
async def main_loop(self):
self.logger.info("starting taskgroup.")
try:
async with self.taskgroup as group:
await group.spawn(self._maintain_connectivity())
except Exception as e:
self.logger.exception("taskgroup died.")
finally:
self.logger.info("taskgroup stopped.")
async def _maintain_connectivity(self):
while True:
await asyncio.sleep(1)
if self.stopping_soon:
return
now = time.time()
if len(self._peers) >= NUM_PEERS_TARGET:
continue
peers = await self._get_next_peers_to_try()
for peer in peers:
if self._can_retry_addr(peer, now=now):
try:
await self._add_peer(peer.host, peer.port, peer.pubkey)
except ErrorAddingPeer as e:
self.logger.info(f"failed to add peer: {peer}. exc: {e!r}")
async def _add_peer(self, host: str, port: int, node_id: bytes) -> Peer:
if node_id in self._peers:
return self._peers[node_id]
port = int(port)
peer_addr = LNPeerAddr(host, port, node_id)
self._trying_addr_now(peer_addr)
self.logger.info(f"adding peer {peer_addr}")
if node_id == self.node_keypair.pubkey:
raise ErrorAddingPeer("cannot connect to self")
transport = LNTransport(self.node_keypair.privkey, peer_addr,
proxy=self.network.proxy)
peer = await self._add_peer_from_transport(node_id=node_id, transport=transport)
return peer
async def _add_peer_from_transport(self, *, node_id: bytes, transport: LNTransportBase) -> Peer:
peer = Peer(self, node_id, transport)
with self.lock:
existing_peer = self._peers.get(node_id)
if existing_peer:
existing_peer.close_and_cleanup()
assert node_id not in self._peers
self._peers[node_id] = peer
await self.taskgroup.spawn(peer.main_loop())
return peer
def peer_closed(self, peer: Peer) -> None:
with self.lock:
peer2 = self._peers.get(peer.pubkey)
if peer2 is peer:
self._peers.pop(peer.pubkey)
def num_peers(self) -> int:
return sum([p.is_initialized() for p in self.peers.values()])
def start_network(self, network: 'Network'):
assert network
self.network = network
self.config = network.config
self._add_peers_from_config()
asyncio.run_coroutine_threadsafe(self.main_loop(), self.network.asyncio_loop)
async def stop(self):
if self.listen_server:
self.listen_server.close()
util.unregister_callback(self.on_proxy_changed)
await self.taskgroup.cancel_remaining()
def _add_peers_from_config(self):
peer_list = self.config.get('lightning_peers', [])
for host, port, pubkey in peer_list:
asyncio.run_coroutine_threadsafe(
self._add_peer(host, int(port), bfh(pubkey)),
self.network.asyncio_loop)
def is_good_peer(self, peer: LNPeerAddr) -> bool:
# the purpose of this method is to filter peers that advertise the desired feature bits
# it is disabled for now, because feature bits published in node announcements seem to be unreliable
return True
node_id = peer.pubkey
node = self.channel_db._nodes.get(node_id)
if not node:
return False
try:
ln_compare_features(self.features, node.features)
except IncompatibleLightningFeatures:
return False
#self.logger.info(f'is_good {peer.host}')
return True
def on_peer_successfully_established(self, peer: Peer) -> None:
if isinstance(peer.transport, LNTransport):
peer_addr = peer.transport.peer_addr
# reset connection attempt count
self._on_connection_successfully_established(peer_addr)
# add into channel db
if self.channel_db:
self.channel_db.add_recent_peer(peer_addr)
# save network address into channels we might have with peer
for chan in peer.channels.values():
chan.add_or_update_peer_addr(peer_addr)
async def _get_next_peers_to_try(self) -> Sequence[LNPeerAddr]:
now = time.time()
await self.channel_db.data_loaded.wait()
# first try from recent peers
recent_peers = self.channel_db.get_recent_peers()
for peer in recent_peers:
if not peer:
continue
if peer.pubkey in self._peers:
continue
if not self._can_retry_addr(peer, now=now):
continue
if not self.is_good_peer(peer):
continue
return [peer]
# try random peer from graph
unconnected_nodes = self.channel_db.get_200_randomly_sorted_nodes_not_in(self.peers.keys())
if unconnected_nodes:
for node_id in unconnected_nodes:
addrs = self.channel_db.get_node_addresses(node_id)
if not addrs:
continue
host, port, timestamp = self.choose_preferred_address(list(addrs))
try:
peer = LNPeerAddr(host, port, node_id)
except ValueError:
continue
if not self._can_retry_addr(peer, now=now):
continue
if not self.is_good_peer(peer):
continue
#self.logger.info('taking random ln peer from our channel db')
return [peer]
# getting desperate... let's try hardcoded fallback list of peers
if constants.net in (constants.BitcoinTestnet,):
fallback_list = FALLBACK_NODE_LIST_TESTNET
elif constants.net in (constants.BitcoinMainnet,):
fallback_list = FALLBACK_NODE_LIST_MAINNET
else:
return []
fallback_list = [peer for peer in fallback_list if self._can_retry_addr(peer, now=now)]
if fallback_list:
return [random.choice(fallback_list)]
return await run_in_thread(self._get_peers_from_dns_seeds)
def _get_peers_from_dns_seeds(self) -> Sequence[LNPeerAddr]:
if not constants.net.LN_DNS_SEEDS:
return []
dns_seed = random.choice(constants.net.LN_DNS_SEEDS)
self.logger.info('asking dns seed "{}" for ln peers'.format(dns_seed))
try:
srv_answers = resolve_dns_srv('r{}.{}'.format(
constants.net.LN_REALM_BYTE, dns_seed))
except dns.exception.DNSException as e:
self.logger.info(f'failed querying (1) dns seed "{dns_seed}" for ln peers: {repr(e)}')
return []
random.shuffle(srv_answers)
num_peers = 2 * NUM_PEERS_TARGET
srv_answers = srv_answers[:num_peers]
peers = []
for srv_ans in srv_answers:
try:
answers = dns.resolver.resolve(srv_ans['host'])
except dns.exception.DNSException as e:
self.logger.info(f'failed querying (2) dns seed "{dns_seed}" for ln peers: {repr(e)}')
continue
try:
ln_host = str(answers[0])
port = int(srv_ans['port'])
bech32_pubkey = srv_ans['host'].split('.')[0]
pubkey = get_compressed_pubkey_from_bech32(bech32_pubkey)
peers.append(LNPeerAddr(ln_host, port, pubkey))
except Exception as e:
self.logger.info(f'error with parsing peer from dns seed: {repr(e)}')
continue
self.logger.info(f'got {len(peers)} ln peers from dns seed')
return peers
@staticmethod
def choose_preferred_address(addr_list: Sequence[Tuple[str, int, int]]) -> Tuple[str, int, int]:
assert len(addr_list) >= 1
for host, port, timestamp in addr_list:
if is_ip_address(host):
return host, port, timestamp
choice = random.choice(addr_list)
return choice
def on_proxy_changed(self, event, *args):
for peer in self.peers.values():
peer.close_and_cleanup()
self._clear_addr_retry_times()
@log_exceptions
async def add_peer(self, connect_str: str) -> Peer:
node_id, rest = extract_nodeid(connect_str)
peer = self._peers.get(node_id)
if not peer:
if rest is not None:
host, port = split_host_port(rest)
else:
if not self.channel_db:
addr = trampolines_by_id().get(node_id)
if not addr:
raise ConnStringFormatError(_('Address unknown for node:') + ' ' + bh2u(node_id))
host, port = addr.host, addr.port
else:
addrs = self.channel_db.get_node_addresses(node_id)
if not addrs:
raise ConnStringFormatError(_('Don\'t know any addresses for node:') + ' ' + bh2u(node_id))
host, port, timestamp = self.choose_preferred_address(list(addrs))
port = int(port)
# Try DNS-resolving the host (if needed). This is simply so that
# the caller gets a nice exception if it cannot be resolved.
try:
await asyncio.get_event_loop().getaddrinfo(host, port)
except socket.gaierror:
raise ConnStringFormatError(_('Hostname does not resolve (getaddrinfo failed)'))
# add peer
peer = await self._add_peer(host, port, node_id)
return peer
class LNGossip(LNWorker):
max_age = 14*24*3600
LOGGING_SHORTCUT = 'g'
def __init__(self):
seed = os.urandom(32)
node = BIP32Node.from_rootseed(seed, xtype='standard')
xprv = node.to_xprv()
super().__init__(xprv, LNGOSSIP_FEATURES)
self.unknown_ids = set()
def start_network(self, network: 'Network'):
assert network
super().start_network(network)
asyncio.run_coroutine_threadsafe(self.taskgroup.spawn(self.maintain_db()), self.network.asyncio_loop)
async def maintain_db(self):
await self.channel_db.data_loaded.wait()
while True:
if len(self.unknown_ids) == 0:
self.channel_db.prune_old_policies(self.max_age)
self.channel_db.prune_orphaned_channels()
await asyncio.sleep(120)
async def add_new_ids(self, ids: Iterable[bytes]):
known = self.channel_db.get_channel_ids()
new = set(ids) - set(known)
self.unknown_ids.update(new)
util.trigger_callback('unknown_channels', len(self.unknown_ids))
util.trigger_callback('gossip_peers', self.num_peers())
util.trigger_callback('ln_gossip_sync_progress')
def get_ids_to_query(self) -> Sequence[bytes]:
N = 500
l = list(self.unknown_ids)
self.unknown_ids = set(l[N:])
util.trigger_callback('unknown_channels', len(self.unknown_ids))
util.trigger_callback('ln_gossip_sync_progress')
return l[0:N]
def get_sync_progress_estimate(self) -> Tuple[Optional[int], Optional[int], Optional[int]]:
if self.num_peers() == 0:
return None, None, None
nchans_with_0p, nchans_with_1p, nchans_with_2p = self.channel_db.get_num_channels_partitioned_by_policy_count()
num_db_channels = nchans_with_0p + nchans_with_1p + nchans_with_2p
# some channels will never have two policies (only one is in gossip?...)
# so if we have at least 1 policy for a channel, we consider that channel "complete" here
current_est = num_db_channels - nchans_with_0p
total_est = len(self.unknown_ids) + num_db_channels
progress = current_est / total_est if total_est and current_est else 0
progress_percent = (1.0 / 0.95 * progress) * 100
progress_percent = min(progress_percent, 100)
progress_percent = round(progress_percent)
# take a minimal number of synchronized channels to get a more accurate
# percentage estimate
if current_est < 200:
progress_percent = 0
return current_est, total_est, progress_percent
async def process_gossip(self, chan_anns, node_anns, chan_upds):
# note: we run in the originating peer's TaskGroup, so we can safely raise here
await self.channel_db.data_loaded.wait()
self.logger.debug(f'process_gossip {len(chan_anns)} {len(node_anns)} {len(chan_upds)}')
def process_chan_anns():
for payload in chan_anns:
self.channel_db.verify_channel_announcement(payload)
self.channel_db.add_channel_announcements(chan_anns)
await run_in_thread(process_chan_anns)
def process_node_anns():
for payload in node_anns:
self.channel_db.verify_node_announcement(payload)
self.channel_db.add_node_announcements(node_anns)
await run_in_thread(process_node_anns)
categorized_chan_upds = await run_in_thread(partial(
self.channel_db.add_channel_updates,
chan_upds,
max_age=self.max_age))
orphaned = categorized_chan_upds.orphaned
if orphaned:
self.logger.info(f'adding {len(orphaned)} unknown channel ids')
orphaned_ids = [c['short_channel_id'] for c in orphaned]
await self.add_new_ids(orphaned_ids)
if categorized_chan_upds.good:
self.logger.debug(f'on_channel_update: {len(categorized_chan_upds.good)}/{len(chan_upds)}')
class LNWallet(LNWorker):
lnwatcher: Optional['LNWalletWatcher']
MPP_EXPIRY = 120
TIMEOUT_SHUTDOWN_FAIL_PENDING_HTLCS = 3
def __init__(self, wallet: 'Abstract_Wallet', xprv):
self.wallet = wallet
self.db = wallet.db
Logger.__init__(self)
LNWorker.__init__(self, xprv, LNWALLET_FEATURES)
self.config = wallet.config
self.lnwatcher = None
self.lnrater: LNRater = None
self.payments = self.db.get_dict('lightning_payments')
self.preimages = self.db.get_dict('lightning_preimages')
self.sweep_address = wallet.get_new_sweep_address_for_channel()
self.logs = defaultdict(list) self.enable_htlc_forwarding = True
self._channels = {}
channels = self.db.get_dict("channels")
for channel_id, c in random_shuffled_copy(channels.items()):
self._channels[bfh(channel_id)] = Channel(c, sweep_address=self.sweep_address, lnworker=self)
self._channel_backups = {}
for name in ["onchain_channel_backups", "imported_channel_backups"]:
channel_backups = self.db.get_dict(name)
for channel_id, storage in channel_backups.items():
self._channel_backups[bfh(channel_id)] = ChannelBackup(storage, sweep_address=self.sweep_address, lnworker=self)
self.sent_htlcs = defaultdict(asyncio.Queue)
self.sent_htlcs_info = dict()
self.sent_buckets = dict()
self.received_mpp_htlcs = dict()
self.swap_manager = SwapManager(wallet=self.wallet, lnworker=self)
self.inflight_payments = set()
for payment_hash in self.get_payments(status='inflight').keys():
self.set_invoice_status(payment_hash.hex(), PR_INFLIGHT)
self.trampoline_forwarding_failures = {}
self.downstream_htlc_to_upstream_peer_map = {}
def has_deterministic_node_id(self) -> bool:
return bool(self.db.get('lightning_xprv'))
def can_have_recoverable_channels(self) -> bool:
return (self.has_deterministic_node_id()
and not (self.config.get('lightning_listen')))
def has_recoverable_channels(self) -> bool:
return (self.can_have_recoverable_channels()
and self.config.get('use_recoverable_channels', True))
@property
def channels(self) -> Mapping[bytes, Channel]:
with self.lock:
return self._channels.copy()
@property
def channel_backups(self) -> Mapping[bytes, ChannelBackup]:
with self.lock:
return self._channel_backups.copy()
def get_channel_by_id(self, channel_id: bytes) -> Optional[Channel]:
return self._channels.get(channel_id, None)
def diagnostic_name(self):
return self.wallet.diagnostic_name()
@ignore_exceptions
@log_exceptions
async def sync_with_local_watchtower(self):
watchtower = self.network.local_watchtower
if watchtower:
while True:
for chan in self.channels.values():
await self.sync_channel_with_watchtower(chan, watchtower.sweepstore)
await asyncio.sleep(5)
@ignore_exceptions
@log_exceptions
async def sync_with_remote_watchtower(self):
while True:
await asyncio.sleep(5)
watchtower_url = self.config.get('watchtower_url')
if not watchtower_url:
continue
parsed_url = urllib.parse.urlparse(watchtower_url)
if not (parsed_url.scheme == 'https' or is_private_netaddress(parsed_url.hostname)):
self.logger.warning(f"got watchtower URL for remote tower but we won't use it! "
f"can only use HTTPS (except if private IP): not using {watchtower_url!r}")
continue
# try to sync with the remote watchtower
try:
async with make_aiohttp_session(proxy=self.network.proxy) as session:
watchtower = JsonRPCClient(session, watchtower_url)
watchtower.add_method('get_ctn')
watchtower.add_method('add_sweep_tx')
for chan in self.channels.values():
await self.sync_channel_with_watchtower(chan, watchtower)
except aiohttp.client_exceptions.ClientConnectorError:
self.logger.info(f'could not contact remote watchtower {watchtower_url}')
async def sync_channel_with_watchtower(self, chan: Channel, watchtower):
outpoint = chan.funding_outpoint.to_str()
addr = chan.get_funding_address()
current_ctn = chan.get_oldest_unrevoked_ctn(REMOTE)
watchtower_ctn = await watchtower.get_ctn(outpoint, addr)
for ctn in range(watchtower_ctn + 1, current_ctn):
sweeptxs = chan.create_sweeptxs(ctn)
for tx in sweeptxs:
await watchtower.add_sweep_tx(outpoint, ctn, tx.inputs()[0].prevout.to_str(), tx.serialize())
def start_network(self, network: 'Network'):
assert network
self.network = network
self.config = network.config
self.lnwatcher = LNWalletWatcher(self, network)
self.lnwatcher.start_network(network)
self.swap_manager.start_network(network=network, lnwatcher=self.lnwatcher)
self.lnrater = LNRater(self, network)
for chan in self.channels.values():
self.lnwatcher.add_channel(chan.funding_outpoint.to_str(), chan.get_funding_address())
for cb in self.channel_backups.values():
self.lnwatcher.add_channel(cb.funding_outpoint.to_str(), cb.get_funding_address())
for coro in [
self.maybe_listen(),
self.lnwatcher.on_network_update('network_updated'), # shortcut (don't block) if funding tx locked and verified
self.reestablish_peers_and_channels(),
self.sync_with_local_watchtower(),
self.sync_with_remote_watchtower(),
]:
tg_coro = self.taskgroup.spawn(coro)
asyncio.run_coroutine_threadsafe(tg_coro, self.network.asyncio_loop)
async def stop(self):
self.stopping_soon = True
if self.listen_server:
self.listen_server.close()
async with ignore_after(self.TIMEOUT_SHUTDOWN_FAIL_PENDING_HTLCS):
await self.wait_for_received_pending_htlcs_to_get_removed()
await LNWorker.stop(self)
if self.lnwatcher:
await self.lnwatcher.stop()
self.lnwatcher = None
async def wait_for_received_pending_htlcs_to_get_removed(self):
assert self.stopping_soon is True
# that we can already fail/fulfill. e.g. forwarded htlcs cannot be removed
async with OldTaskGroup() as group:
for peer in self.peers.values():
await group.spawn(peer.wait_one_htlc_switch_iteration())
while True:
if all(not peer.received_htlcs_pending_removal for peer in self.peers.values()):
break
async with OldTaskGroup(wait=any) as group:
for peer in self.peers.values():
await group.spawn(peer.received_htlc_removed_event.wait())
def peer_closed(self, peer):
for chan in self.channels_for_peer(peer.pubkey).values():
chan.peer_state = PeerState.DISCONNECTED
util.trigger_callback('channel', self.wallet, chan)
super().peer_closed(peer)
def get_payments(self, *, status=None) -> Mapping[bytes, List[HTLCWithStatus]]:
out = defaultdict(list)
for chan in self.channels.values():
d = chan.get_payments(status=status)
for payment_hash, plist in d.items():
out[payment_hash] += plist
return out
def get_payment_value(
self, info: Optional['PaymentInfo'], plist: List[HTLCWithStatus],
) -> Tuple[int, int, int]:
assert plist
amount_msat = 0
fee_msat = None
for htlc_with_status in plist:
htlc = htlc_with_status.htlc
_direction = htlc_with_status.direction
amount_msat += int(_direction) * htlc.amount_msat
if _direction == SENT and info and info.amount_msat:
fee_msat = (fee_msat or 0) - info.amount_msat - amount_msat
timestamp = min([htlc_with_status.htlc.timestamp for htlc_with_status in plist])
return amount_msat, fee_msat, timestamp
def get_lightning_history(self):
out = {}
for payment_hash, plist in self.get_payments(status='settled').items():
if len(plist) == 0:
continue
key = payment_hash.hex()
info = self.get_payment_info(payment_hash)
amount_msat, fee_msat, timestamp = self.get_payment_value(info, plist)
if info is not None:
label = self.wallet.get_label(key)
direction = ('sent' if info.direction == SENT else 'received') if len(plist)==1 else 'self-payment'
else:
direction = 'forwarding'
label = _('Forwarding')
preimage = self.get_preimage(payment_hash).hex()
item = {
'type': 'payment',
'label': label,
'timestamp': timestamp or 0,
'date': timestamp_to_datetime(timestamp),
'direction': direction,
'amount_msat': amount_msat,
'fee_msat': fee_msat,
'payment_hash': key,
'preimage': preimage,
}
# add group_id to swap transactions
swap = self.swap_manager.get_swap(payment_hash)
if swap:
if swap.is_reverse:
item['group_id'] = swap.spending_txid
item['group_label'] = 'Reverse swap' + ' ' + self.config.format_amount_and_units(swap.lightning_amount)
else:
item['group_id'] = swap.funding_txid
item['group_label'] = 'Forward swap' + ' ' + self.config.format_amount_and_units(swap.onchain_amount)
# done
out[payment_hash] = item
return out
def get_onchain_history(self):
current_height = self.wallet.get_local_height()
out = {}
# add funding events
for chan in self.channels.values():
item = chan.get_funding_height()
if item is None:
continue
if not self.lnwatcher:
continue # lnwatcher not available with --offline (its data is not persisted)
funding_txid, funding_height, funding_timestamp = item
tx_height = self.lnwatcher.get_tx_height(funding_txid)
item = {
'channel_id': bh2u(chan.channel_id),
'type': 'channel_opening',
'label': self.wallet.get_label_for_txid(funding_txid) or (_('Open channel') + ' ' + chan.get_id_for_log()),
'txid': funding_txid,
'amount_msat': chan.balance(LOCAL, ctn=0),
'direction': 'received',
'timestamp': tx_height.timestamp,
'date': timestamp_to_datetime(tx_height.timestamp),
'fee_sat': None,
'fee_msat': None,
'height': tx_height.height,
'confirmations': tx_height.conf,
}
out[funding_txid] = item
item = chan.get_closing_height()
if item is None:
continue
closing_txid, closing_height, closing_timestamp = item
tx_height = self.lnwatcher.get_tx_height(closing_txid)
item = {
'channel_id': bh2u(chan.channel_id),
'txid': closing_txid,
'label': self.wallet.get_label_for_txid(closing_txid) or (_('Close channel') + ' ' + chan.get_id_for_log()),
'type': 'channel_closure',
'amount_msat': -chan.balance_minus_outgoing_htlcs(LOCAL),
'direction': 'sent',
'timestamp': tx_height.timestamp,
'date': timestamp_to_datetime(tx_height.timestamp),
'fee_sat': None,
'fee_msat': None,
'height': tx_height.height,
'confirmations': tx_height.conf,
}
out[closing_txid] = item
# add info about submarine swaps
settled_payments = self.get_payments(status='settled')
for payment_hash_hex, swap in self.swap_manager.swaps.items():
txid = swap.spending_txid if swap.is_reverse else swap.funding_txid
if txid is None:
continue
payment_hash = bytes.fromhex(payment_hash_hex)
if payment_hash in settled_payments:
plist = settled_payments[payment_hash]
info = self.get_payment_info(payment_hash)
amount_msat, fee_msat, timestamp = self.get_payment_value(info, plist)
else:
amount_msat = 0
label = 'Reverse swap' if swap.is_reverse else 'Forward swap'
delta = current_height - swap.locktime
if not swap.is_redeemed and swap.spending_txid is None and delta < 0:
label += f' (refundable in {-delta} blocks)' # fixme: only if unspent
out[txid] = {
'txid': txid,
'group_id': txid,
'amount_msat': 0,
#'amount_msat': amount_msat, # must not be added
'type': 'swap',
'label': self.wallet.get_label_for_txid(txid) or label,
}
return out
def get_history(self):
out = list(self.get_lightning_history().values()) + list(self.get_onchain_history().values())
# sort by timestamp
out.sort(key=lambda x: (x.get('timestamp') or float("inf")))
balance_msat = 0
for item in out:
balance_msat += item['amount_msat']
item['balance_msat'] = balance_msat
return out
def channel_peers(self) -> List[bytes]:
node_ids = [chan.node_id for chan in self.channels.values() if not chan.is_closed()]
return node_ids
def channels_for_peer(self, node_id):
assert type(node_id) is bytes
return {chan_id: chan for (chan_id, chan) in self.channels.items()
if chan.node_id == node_id}
def channel_state_changed(self, chan: Channel):
if type(chan) is Channel:
self.save_channel(chan)
util.trigger_callback('channel', self.wallet, chan)
def save_channel(self, chan: Channel):
assert type(chan) is Channel
if chan.config[REMOTE].next_per_commitment_point == chan.config[REMOTE].current_per_commitment_point:
raise Exception("Tried to save channel with next_point == current_point, this should not happen")
self.wallet.save_db()
util.trigger_callback('channel', self.wallet, chan)
def channel_by_txo(self, txo: str) -> Optional[AbstractChannel]:
for chan in self.channels.values():
if chan.funding_outpoint.to_str() == txo:
return chan
for chan in self.channel_backups.values():
if chan.funding_outpoint.to_str() == txo:
return chan
async def on_channel_update(self, chan: Channel):
if type(chan) is ChannelBackup:
util.trigger_callback('channel', self.wallet, chan)
return
if chan.get_state() == ChannelState.OPEN and chan.should_be_closed_due_to_expiring_htlcs(self.network.get_local_height()):
self.logger.info(f"force-closing due to expiring htlcs")
await self.schedule_force_closing(chan.channel_id)
elif chan.get_state() == ChannelState.FUNDED:
peer = self._peers.get(chan.node_id)
if peer and peer.is_initialized():
peer.send_funding_locked(chan)
elif chan.get_state() == ChannelState.OPEN:
peer = self._peers.get(chan.node_id)
if peer:
await peer.maybe_update_fee(chan)
conf = self.lnwatcher.get_tx_height(chan.funding_outpoint.txid).conf
peer.on_network_update(chan, conf)
elif chan.get_state() == ChannelState.FORCE_CLOSING:
force_close_tx = chan.force_close_tx()
txid = force_close_tx.txid()
height = self.lnwatcher.get_tx_height(txid).height
if height == TX_HEIGHT_LOCAL:
self.logger.info('REBROADCASTING CLOSING TX')
await self.network.try_broadcasting(force_close_tx, 'force-close')
@log_exceptions
async def _open_channel_coroutine(
self, *,
connect_str: str,
funding_tx: PartialTransaction,
funding_sat: int,
push_sat: int,
password: Optional[str]) -> Tuple[Channel, PartialTransaction]:
peer = await self.add_peer(connect_str)
coro = peer.channel_establishment_flow(
funding_tx=funding_tx,
funding_sat=funding_sat,
push_msat=push_sat * 1000,
temp_channel_id=os.urandom(32))
chan, funding_tx = await asyncio.wait_for(coro, LN_P2P_NETWORK_TIMEOUT)
util.trigger_callback('channels_updated', self.wallet)
self.wallet.add_transaction(funding_tx) # save tx as local into the wallet
self.wallet.sign_transaction(funding_tx, password)
self.wallet.set_label(funding_tx.txid(), _('Open channel'))
if funding_tx.is_complete():
await self.network.try_broadcasting(funding_tx, 'open_channel')
return chan, funding_tx
def add_channel(self, chan: Channel):
with self.lock:
self._channels[chan.channel_id] = chan
self.lnwatcher.add_channel(chan.funding_outpoint.to_str(), chan.get_funding_address())
def add_new_channel(self, chan: Channel):
self.add_channel(chan)
channels_db = self.db.get_dict('channels')
channels_db[chan.channel_id.hex()] = chan.storage
for addr in chan.get_wallet_addresses_channel_might_want_reserved():
self.wallet.set_reserved_state_of_address(addr, reserved=True)
try:
self.save_channel(chan)
backup_dir = self.config.get_backup_dir()
if backup_dir is not None:
self.wallet.save_backup(backup_dir)
except:
chan.set_state(ChannelState.REDEEMED)
self.remove_channel(chan.channel_id)
raise
def cb_data(self, node_id):
return CB_MAGIC_BYTES + node_id[0:16]
def decrypt_cb_data(self, encrypted_data, funding_address):
funding_scripthash = bytes.fromhex(address_to_scripthash(funding_address))
nonce = funding_scripthash[0:12]
return chacha20_decrypt(key=self.backup_key, data=encrypted_data, nonce=nonce)
def encrypt_cb_data(self, data, funding_address):
funding_scripthash = bytes.fromhex(address_to_scripthash(funding_address))
nonce = funding_scripthash[0:12]
return chacha20_encrypt(key=self.backup_key, data=data, nonce=nonce)
def mktx_for_open_channel(
self, *,
coins: Sequence[PartialTxInput],
funding_sat: int,
node_id: bytes,
fee_est=None) -> PartialTransaction:
outputs = [PartialTxOutput.from_address_and_value(ln_dummy_address(), funding_sat)]
if self.has_recoverable_channels():
dummy_scriptpubkey = make_op_return(self.cb_data(node_id))
outputs.append(PartialTxOutput(scriptpubkey=dummy_scriptpubkey, value=0))
tx = self.wallet.make_unsigned_transaction(
coins=coins,
outputs=outputs,
fee=fee_est)
tx.set_rbf(False)
return tx
def open_channel(self, *, connect_str: str, funding_tx: PartialTransaction,
funding_sat: int, push_amt_sat: int, password: str = None) -> Tuple[Channel, PartialTransaction]:
if funding_sat > LN_MAX_FUNDING_SAT:
raise Exception(_("Requested channel capacity is over protocol allowed maximum."))
coro = self._open_channel_coroutine(
connect_str=connect_str, funding_tx=funding_tx, funding_sat=funding_sat,
push_sat=push_amt_sat, password=password)
fut = asyncio.run_coroutine_threadsafe(coro, self.network.asyncio_loop)
try:
chan, funding_tx = fut.result()
except concurrent.futures.TimeoutError:
raise Exception(_("open_channel timed out"))
return chan, funding_tx
def get_channel_by_short_id(self, short_channel_id: bytes) -> Optional[Channel]:
for chan in self.channels.values():
if chan.short_channel_id == short_channel_id:
return chan
@log_exceptions
async def pay_invoice(
self, invoice: str, *,
amount_msat: int = None,
attempts: int = 1,
full_path: LNPaymentPath = None) -> Tuple[bool, List[HtlcLog]]:
lnaddr = self._check_invoice(invoice, amount_msat=amount_msat)
min_cltv_expiry = lnaddr.get_min_final_cltv_expiry()
payment_hash = lnaddr.paymenthash
key = payment_hash.hex()
payment_secret = lnaddr.payment_secret
invoice_pubkey = lnaddr.pubkey.serialize()
invoice_features = lnaddr.get_features()
r_tags = lnaddr.get_routing_info('r')
amount_to_pay = lnaddr.get_amount_msat()
status = self.get_payment_status(payment_hash)
if status == PR_PAID:
raise PaymentFailure(_("This invoice has been paid already"))
if status == PR_INFLIGHT:
raise PaymentFailure(_("A payment was already initiated for this invoice"))
if payment_hash in self.get_payments(status='inflight'):
raise PaymentFailure(_("A previous attempt to pay this invoice did not clear"))
info = PaymentInfo(payment_hash, amount_to_pay, SENT, PR_UNPAID)
self.save_payment_info(info)
self.wallet.set_label(key, lnaddr.get_description())
self.set_invoice_status(key, PR_INFLIGHT)
try:
await self.pay_to_node(
node_pubkey=invoice_pubkey,
payment_hash=payment_hash,
payment_secret=payment_secret,
amount_to_pay=amount_to_pay,
min_cltv_expiry=min_cltv_expiry,
r_tags=r_tags,
invoice_features=invoice_features,
attempts=attempts,
full_path=full_path)
success = True
except PaymentFailure as e:
self.logger.info(f'payment failure: {e!r}')
success = False
reason = str(e)
if success:
self.set_invoice_status(key, PR_PAID)
util.trigger_callback('payment_succeeded', self.wallet, key)
else:
self.set_invoice_status(key, PR_UNPAID)
util.trigger_callback('payment_failed', self.wallet, key, reason)
log = self.logs[key]
return success, log
async def pay_to_node(
self, *,
node_pubkey: bytes,
payment_hash: bytes,
payment_secret: Optional[bytes],
amount_to_pay: int, # in msat
min_cltv_expiry: int,
r_tags,
invoice_features: int,
attempts: int = 1,
full_path: LNPaymentPath = None,
fwd_trampoline_onion=None,
fwd_trampoline_fee=None,
fwd_trampoline_cltv_delta=None) -> None:
if fwd_trampoline_onion:
# todo: compare to the fee of the actual route we found
if fwd_trampoline_fee < 1000:
raise OnionRoutingFailure(code=OnionFailureCode.TRAMPOLINE_FEE_INSUFFICIENT, data=b'')
if fwd_trampoline_cltv_delta < 576:
raise OnionRoutingFailure(code=OnionFailureCode.TRAMPOLINE_EXPIRY_TOO_SOON, data=b'')
self.logs[payment_hash.hex()] = log = []
# when encountering trampoline forwarding difficulties in the legacy case, we
# sometimes need to fall back to a single trampoline forwarder, at the expense
# of privacy
use_two_trampolines = True
trampoline_fee_level = self.INITIAL_TRAMPOLINE_FEE_LEVEL
amount_inflight = 0 # what we sent in htlcs (that receiver gets, without fees)
while True:
amount_to_send = amount_to_pay - amount_inflight
if amount_to_send > 0:
# 1. create a set of routes for remaining amount.
# note: path-finding runs in a separate thread so that we don't block the asyncio loop
routes = self.create_routes_for_payment(
amount_msat=amount_to_send,
final_total_msat=amount_to_pay,
invoice_pubkey=node_pubkey,
min_cltv_expiry=min_cltv_expiry,
r_tags=r_tags,
invoice_features=invoice_features,
full_path=full_path,
payment_hash=payment_hash,
payment_secret=payment_secret,
trampoline_fee_level=trampoline_fee_level,
use_two_trampolines=use_two_trampolines,
fwd_trampoline_onion=fwd_trampoline_onion
)
async for route, amount_msat, total_msat, amount_receiver_msat, cltv_delta, bucket_payment_secret, trampoline_onion in routes:
amount_inflight += amount_receiver_msat
if amount_inflight > amount_to_pay:
raise Exception(f"amount_inflight={amount_inflight} > amount_to_pay={amount_to_pay}")
await self.pay_to_route(
route=route,
amount_msat=amount_msat,
total_msat=total_msat,
amount_receiver_msat=amount_receiver_msat,
payment_hash=payment_hash,
payment_secret=bucket_payment_secret,
min_cltv_expiry=cltv_delta,
trampoline_onion=trampoline_onion,
trampoline_fee_level=trampoline_fee_level)
util.trigger_callback('invoice_status', self.wallet, payment_hash.hex())
self.logger.info(f"amount inflight {amount_inflight}")
htlc_log = await self.sent_htlcs[payment_hash].get()
amount_inflight -= htlc_log.amount_msat
if amount_inflight < 0:
raise Exception(f"amount_inflight={amount_inflight} < 0")
log.append(htlc_log)
if htlc_log.success:
if self.network.path_finder:
self.network.path_finder.update_liquidity_hints(htlc_log.route, htlc_log.amount_msat)
self.network.path_finder.update_inflight_htlcs(htlc_log.route, add_htlcs=False)
return
if len(log) >= attempts:
raise PaymentFailure('Giving up after %d attempts'%len(log))
route = htlc_log.route
sender_idx = htlc_log.sender_idx
erring_node_id = route[sender_idx].node_id
failure_msg = htlc_log.failure_msg
code, data = failure_msg.code, failure_msg.data
self.logger.info(f"UPDATE_FAIL_HTLC. code={repr(code)}. "
f"decoded_data={failure_msg.decode_data()}. data={data.hex()!r}")
self.logger.info(f"error reported by {bh2u(erring_node_id)}")
if code == OnionFailureCode.MPP_TIMEOUT:
raise PaymentFailure(failure_msg.code_name())
if not self.channel_db:
if code in (OnionFailureCode.TRAMPOLINE_FEE_INSUFFICIENT,
OnionFailureCode.TRAMPOLINE_EXPIRY_TOO_SOON):
if htlc_log.trampoline_fee_level == trampoline_fee_level:
trampoline_fee_level += 1
self.logger.info(f'raising trampoline fee level {trampoline_fee_level}')
else:
self.logger.info(f'NOT raising trampoline fee level, already at {trampoline_fee_level}')
continue
elif use_two_trampolines:
use_two_trampolines = False
elif code in (OnionFailureCode.UNKNOWN_NEXT_PEER,
OnionFailureCode.TEMPORARY_NODE_FAILURE):
continue
else:
raise PaymentFailure(failure_msg.code_name())
else:
self.handle_error_code_from_failed_htlc(
route=route, sender_idx=sender_idx, failure_msg=failure_msg, amount=htlc_log.amount_msat)
async def pay_to_route(
self, *,
route: LNPaymentRoute,
amount_msat: int,
total_msat: int,
amount_receiver_msat:int,
payment_hash: bytes,
payment_secret: Optional[bytes],
min_cltv_expiry: int,
trampoline_onion: bytes = None,
trampoline_fee_level: int) -> None:
# send a single htlc
short_channel_id = route[0].short_channel_id
chan = self.get_channel_by_short_id(short_channel_id)
peer = self._peers.get(route[0].node_id)
if not peer:
raise PaymentFailure('Dropped peer')
await peer.initialized
htlc = peer.pay(
route=route,
chan=chan,
amount_msat=amount_msat,
total_msat=total_msat,
payment_hash=payment_hash,
min_final_cltv_expiry=min_cltv_expiry,
payment_secret=payment_secret,
trampoline_onion=trampoline_onion)
key = (payment_hash, short_channel_id, htlc.htlc_id)
self.sent_htlcs_info[key] = route, payment_secret, amount_msat, total_msat, amount_receiver_msat, trampoline_fee_level
# if we sent MPP to a trampoline, add item to sent_buckets
if not self.channel_db and amount_msat != total_msat:
if payment_secret not in self.sent_buckets:
self.sent_buckets[payment_secret] = (0, 0)
amount_sent, amount_failed = self.sent_buckets[payment_secret]
amount_sent += amount_receiver_msat
self.sent_buckets[payment_secret] = amount_sent, amount_failed
if self.network.path_finder:
# add inflight htlcs to liquidity hints
self.network.path_finder.update_inflight_htlcs(route, add_htlcs=True)
util.trigger_callback('htlc_added', chan, htlc, SENT)
def handle_error_code_from_failed_htlc(
self,
*,
route: LNPaymentRoute,
sender_idx: int,
failure_msg: OnionRoutingFailure,
amount: int) -> None:
assert self.channel_db # cannot be in trampoline mode
assert self.network.path_finder
# remove inflight htlcs from liquidity hints
self.network.path_finder.update_inflight_htlcs(route, add_htlcs=False)
code, data = failure_msg.code, failure_msg.data
# TODO can we use lnmsg.OnionWireSerializer here?
# TODO update onion_wire.csv
# handle some specific error codes
failure_codes = {
OnionFailureCode.TEMPORARY_CHANNEL_FAILURE: 0,
OnionFailureCode.AMOUNT_BELOW_MINIMUM: 8,
OnionFailureCode.FEE_INSUFFICIENT: 8,
OnionFailureCode.INCORRECT_CLTV_EXPIRY: 4,
OnionFailureCode.EXPIRY_TOO_SOON: 0,
OnionFailureCode.CHANNEL_DISABLED: 2,
}
# determine a fallback channel to blacklist if we don't get the erring
if sender_idx is None:
raise PaymentFailure(failure_msg.code_name())
try:
fallback_channel = route[sender_idx + 1].short_channel_id
except IndexError:
raise PaymentFailure(f'payment destination reported error: {failure_msg.code_name()}') from None
if code in failure_codes:
offset = failure_codes[code]
channel_update_len = int.from_bytes(data[offset:offset+2], byteorder="big")
channel_update_as_received = data[offset+2: offset+2+channel_update_len]
payload = self._decode_channel_update_msg(channel_update_as_received)
if payload is None:
self.logger.info(f'could not decode channel_update for failed htlc: '
f'{channel_update_as_received.hex()}')
self.network.path_finder.liquidity_hints.add_to_blacklist(fallback_channel)
else:
blacklist, update = self._handle_chanupd_from_failed_htlc(
payload, route=route, sender_idx=sender_idx)
if code == OnionFailureCode.TEMPORARY_CHANNEL_FAILURE:
self.network.path_finder.update_liquidity_hints(
route,
amount,
failing_channel=ShortChannelID(payload['short_channel_id']))
elif blacklist:
self.network.path_finder.liquidity_hints.add_to_blacklist(
payload['short_channel_id'])
if not (blacklist or update):
raise PaymentFailure(failure_msg.code_name())
# for errors that do not include a channel update
else:
self.network.path_finder.liquidity_hints.add_to_blacklist(fallback_channel)
def _handle_chanupd_from_failed_htlc(self, payload, *, route, sender_idx) -> Tuple[bool, bool]:
blacklist = False
update = False
try:
r = self.channel_db.add_channel_update(payload, verify=True)
except InvalidGossipMsg:
return True, False # blacklist
short_channel_id = ShortChannelID(payload['short_channel_id'])
if r == UpdateStatus.GOOD:
self.logger.info(f"applied channel update to {short_channel_id}")
# TODO: add test for this
# FIXME: this does not work for our own unannounced channels.
for chan in self.channels.values():
if chan.short_channel_id == short_channel_id:
chan.set_remote_update(payload)
update = True
elif r == UpdateStatus.ORPHANED:
# maybe it is a private channel (and data in invoice was outdated)
self.logger.info(f"Could not find {short_channel_id}. maybe update is for private channel?")
start_node_id = route[sender_idx].node_id
update = self.channel_db.add_channel_update_for_private_channel(payload, start_node_id)
blacklist = not update
elif r == UpdateStatus.EXPIRED:
blacklist = True
elif r == UpdateStatus.DEPRECATED:
self.logger.info(f'channel update is not more recent.')
blacklist = True
elif r == UpdateStatus.UNCHANGED:
blacklist = True
return blacklist, update
@classmethod
def _decode_channel_update_msg(cls, chan_upd_msg: bytes) -> Optional[Dict[str, Any]]:
channel_update_as_received = chan_upd_msg
channel_update_typed = (258).to_bytes(length=2, byteorder="big") + channel_update_as_received
# note: some nodes put channel updates in error msgs with the leading msg_type already there.
# we try decoding both ways here.
try:
message_type, payload = decode_msg(channel_update_typed)
if payload['chain_hash'] != constants.net.rev_genesis_bytes(): raise Exception()
payload['raw'] = channel_update_typed
return payload
except: # FIXME: too broad
try:
message_type, payload = decode_msg(channel_update_as_received)
if payload['chain_hash'] != constants.net.rev_genesis_bytes(): raise Exception()
payload['raw'] = channel_update_as_received
return payload
except:
return None
@staticmethod
def _check_invoice(invoice: str, *, amount_msat: int = None) -> LnAddr:
addr = lndecode(invoice)
if addr.is_expired():
raise InvoiceError(_("This invoice has expired"))
if amount_msat: # replace amt in invoice. main usecase is paying zero amt invoices
existing_amt_msat = addr.get_amount_msat()
if existing_amt_msat and amount_msat < existing_amt_msat:
raise Exception("cannot pay lower amt than what is originally in LN invoice")
addr.amount = Decimal(amount_msat) / COIN / 1000
if addr.amount is None:
raise InvoiceError(_("Missing amount"))
if addr.get_min_final_cltv_expiry() > lnutil.NBLOCK_CLTV_EXPIRY_TOO_FAR_INTO_FUTURE:
raise InvoiceError("{}\n{}".format(
_("Invoice wants us to risk locking funds for unreasonably long."),
f"min_final_cltv_expiry: {addr.get_min_final_cltv_expiry()}"))
return addr
def is_trampoline_peer(self, node_id: bytes) -> bool:
# until trampoline is advertised in lnfeatures, check against hardcoded list
if is_hardcoded_trampoline(node_id):
return True
peer = self._peers.get(node_id)
if peer and peer.their_features.supports(LnFeatures.OPTION_TRAMPOLINE_ROUTING_OPT):
return True
return False
def suggest_peer(self) -> Optional[bytes]:
if self.channel_db:
return self.lnrater.suggest_peer()
else:
return random.choice(list(hardcoded_trampoline_nodes().values())).pubkey
async def create_routes_for_payment(
self, *,
amount_msat: int, # part of payment amount we want routes for now
final_total_msat: int, # total payment amount final receiver will get
invoice_pubkey,
min_cltv_expiry,
r_tags,
invoice_features: int,
payment_hash,
payment_secret,
trampoline_fee_level: int,
use_two_trampolines: bool,
fwd_trampoline_onion=None,
full_path: LNPaymentPath = None) -> AsyncGenerator[Tuple[LNPaymentRoute, int], None]:
invoice_features = LnFeatures(invoice_features)
trampoline_features = LnFeatures.VAR_ONION_OPT
local_height = self.network.get_local_height()
my_active_channels = [chan for chan in self.channels.values() if
chan.is_active() and not chan.is_frozen_for_sending()]
try:
self.logger.info("trying single-part payment")
# try to send over a single channel
if not self.channel_db:
for chan in my_active_channels:
if not self.is_trampoline_peer(chan.node_id):
continue
if chan.node_id == invoice_pubkey:
trampoline_onion = None
trampoline_payment_secret = payment_secret
trampoline_total_msat = final_total_msat
amount_with_fees = amount_msat
cltv_delta = min_cltv_expiry
else:
trampoline_onion, amount_with_fees, cltv_delta = create_trampoline_route_and_onion(
amount_msat=amount_msat,
total_msat=final_total_msat,
min_cltv_expiry=min_cltv_expiry,
my_pubkey=self.node_keypair.pubkey,
invoice_pubkey=invoice_pubkey,
invoice_features=invoice_features,
node_id=chan.node_id,
r_tags=r_tags,
payment_hash=payment_hash,
payment_secret=payment_secret,
local_height=local_height,
trampoline_fee_level=trampoline_fee_level,
use_two_trampolines=use_two_trampolines)
trampoline_payment_secret = os.urandom(32)
trampoline_total_msat = amount_with_fees
if chan.available_to_spend(LOCAL, strict=True) < amount_with_fees:
continue
route = [
RouteEdge(
start_node=self.node_keypair.pubkey,
end_node=chan.node_id,
short_channel_id=chan.short_channel_id,
fee_base_msat=0,
fee_proportional_millionths=0,
cltv_expiry_delta=0,
node_features=trampoline_features)
]
yield route, amount_with_fees, trampoline_total_msat, amount_msat, cltv_delta, trampoline_payment_secret, trampoline_onion
break
else:
raise NoPathFound()
else: # local single-part route computation
route = await run_in_thread(
partial(
self.create_route_for_payment,
amount_msat=amount_msat,
invoice_pubkey=invoice_pubkey,
min_cltv_expiry=min_cltv_expiry,
r_tags=r_tags,
invoice_features=invoice_features,
my_sending_channels=my_active_channels,
full_path=full_path
)
)
yield route, amount_msat, final_total_msat, amount_msat, min_cltv_expiry, payment_secret, fwd_trampoline_onion
except NoPathFound: # fall back to payment splitting
self.logger.info("no path found, trying multi-part payment")
if not invoice_features.supports(LnFeatures.BASIC_MPP_OPT):
raise
channels_with_funds = {(chan.channel_id, chan.node_id): int(chan.available_to_spend(HTLCOwner.LOCAL))
for chan in my_active_channels}
self.logger.info(f"channels_with_funds: {channels_with_funds}")
if not self.channel_db:
# in the case of a legacy payment, we don't allow splitting via different
use_single_node, _ = is_legacy_relay(invoice_features, r_tags)
split_configurations = suggest_splits(
amount_msat,
channels_with_funds,
exclude_multinode_payments=use_single_node,
exclude_single_part_payments=True,
# the trampoline node will split for us
exclude_single_channel_splits=True,
)
self.logger.info(f'suggest_split {amount_msat} returned {len(split_configurations)} configurations')
for sc in split_configurations:
try:
self.logger.info(f"trying split configuration: {sc.config.values()} rating: {sc.rating}")
per_trampoline_channel_amounts = defaultdict(list)
# categorize by trampoline nodes for trampolin mpp construction
for (chan_id, _), part_amounts_msat in sc.config.items():
chan = self.channels[chan_id]
for part_amount_msat in part_amounts_msat:
per_trampoline_channel_amounts[chan.node_id].append((chan_id, part_amount_msat))
# for each trampoline forwarder, construct mpp trampoline
routes = []
for trampoline_node_id, trampoline_parts in per_trampoline_channel_amounts.items():
per_trampoline_amount = sum([x[1] for x in trampoline_parts])
trampoline_onion, per_trampoline_amount_with_fees, per_trampoline_cltv_delta = create_trampoline_route_and_onion(
amount_msat=per_trampoline_amount,
total_msat=final_total_msat,
min_cltv_expiry=min_cltv_expiry,
my_pubkey=self.node_keypair.pubkey,
invoice_pubkey=invoice_pubkey,
invoice_features=invoice_features,
node_id=trampoline_node_id,
r_tags=r_tags,
payment_hash=payment_hash,
payment_secret=payment_secret,
local_height=local_height,
trampoline_fee_level=trampoline_fee_level,
use_two_trampolines=use_two_trampolines)
# node_features is only used to determine is_tlv
per_trampoline_secret = os.urandom(32)
per_trampoline_fees = per_trampoline_amount_with_fees - per_trampoline_amount
self.logger.info(f'per trampoline fees: {per_trampoline_fees}')
for chan_id, part_amount_msat in trampoline_parts:
chan = self.channels[chan_id]
margin = chan.available_to_spend(LOCAL, strict=True) - part_amount_msat
delta_fee = min(per_trampoline_fees, margin)
# TODO: distribute trampoline fee over several channels?
part_amount_msat_with_fees = part_amount_msat + delta_fee
per_trampoline_fees -= delta_fee
route = [
RouteEdge(
start_node=self.node_keypair.pubkey,
end_node=trampoline_node_id,
short_channel_id=chan.short_channel_id,
fee_base_msat=0,
fee_proportional_millionths=0,
cltv_expiry_delta=0,
node_features=trampoline_features)
]
self.logger.info(f'adding route {part_amount_msat} {delta_fee} {margin}')
routes.append((route, part_amount_msat_with_fees, per_trampoline_amount_with_fees, part_amount_msat, per_trampoline_cltv_delta, per_trampoline_secret, trampoline_onion))
if per_trampoline_fees != 0:
self.logger.info('not enough margin to pay trampoline fee')
raise NoPathFound()
for route in routes:
yield route
return
except NoPathFound:
continue
else:
split_configurations = suggest_splits(
amount_msat,
channels_with_funds,
exclude_single_part_payments=True,
)
# We atomically loop through a split configuration. If there was
# a failure to find a path for a single part, we give back control
# after exhausting the split configuration.
yielded_from_split_configuration = False
self.logger.info(f'suggest_split {amount_msat} returned {len(split_configurations)} configurations')
for sc in split_configurations:
self.logger.info(f"trying split configuration: {list(sc.config.values())} rating: {sc.rating}")
for (chan_id, _), part_amounts_msat in sc.config.items():
for part_amount_msat in part_amounts_msat:
channel = self.channels[chan_id]
try:
route = await run_in_thread(
partial(
self.create_route_for_payment,
amount_msat=part_amount_msat,
invoice_pubkey=invoice_pubkey,
min_cltv_expiry=min_cltv_expiry,
r_tags=r_tags,
invoice_features=invoice_features,
my_sending_channels=[channel],
full_path=None
)
)
yield route, part_amount_msat, final_total_msat, part_amount_msat, min_cltv_expiry, payment_secret, fwd_trampoline_onion
yielded_from_split_configuration = True
except NoPathFound:
continue
if yielded_from_split_configuration:
return
raise NoPathFound()
@profiler
def create_route_for_payment(
self, *,
amount_msat: int,
invoice_pubkey: bytes,
min_cltv_expiry: int,
r_tags,
invoice_features: int,
my_sending_channels: List[Channel],
full_path: Optional[LNPaymentPath]) -> LNPaymentRoute:
my_sending_channels = {chan.short_channel_id: chan for chan in my_sending_channels
if chan.short_channel_id is not None}
# Collect all private edges from route hints.
# Note: if some route hints are multiple edges long, and these paths cross each other,
# we allow our path finding to cross the paths; i.e. the route hints are not isolated.
private_route_edges = {} # type: Dict[ShortChannelID, RouteEdge]
for private_path in r_tags:
# we need to shift the node pubkey by one towards the destination:
private_path_nodes = [edge[0] for edge in private_path][1:] + [invoice_pubkey]
private_path_rest = [edge[1:] for edge in private_path]
start_node = private_path[0][0]
for end_node, edge_rest in zip(private_path_nodes, private_path_rest):
short_channel_id, fee_base_msat, fee_proportional_millionths, cltv_expiry_delta = edge_rest
short_channel_id = ShortChannelID(short_channel_id)
# if we have a routing policy for this edge in the db, that takes precedence,
# as it is likely from a previous failure
channel_policy = self.channel_db.get_policy_for_node(
short_channel_id=short_channel_id,
node_id=start_node,
my_channels=my_sending_channels)
if channel_policy:
fee_base_msat = channel_policy.fee_base_msat
fee_proportional_millionths = channel_policy.fee_proportional_millionths
cltv_expiry_delta = channel_policy.cltv_expiry_delta
node_info = self.channel_db.get_node_info_for_node_id(node_id=end_node)
route_edge = RouteEdge(
start_node=start_node,
end_node=end_node,
short_channel_id=short_channel_id,
fee_base_msat=fee_base_msat,
fee_proportional_millionths=fee_proportional_millionths,
cltv_expiry_delta=cltv_expiry_delta,
node_features=node_info.features if node_info else 0)
private_route_edges[route_edge.short_channel_id] = route_edge
start_node = end_node
# now find a route, end to end: between us and the recipient
try:
route = self.network.path_finder.find_route(
nodeA=self.node_keypair.pubkey,
nodeB=invoice_pubkey,
invoice_amount_msat=amount_msat,
path=full_path,
my_sending_channels=my_sending_channels,
private_route_edges=private_route_edges)
except NoChannelPolicy as e:
raise NoPathFound() from e
if not route:
raise NoPathFound()
# test sanity
if not is_route_sane_to_use(route, amount_msat, min_cltv_expiry):
self.logger.info(f"rejecting insane route {route}")
raise NoPathFound()
assert len(route) > 0
if route[-1].end_node != invoice_pubkey:
raise LNPathInconsistent("last node_id != invoice pubkey")
# add features from invoice
route[-1].node_features |= invoice_features
return route
def add_request(self, amount_sat, message, expiry) -> str:
coro = self._add_request_coro(amount_sat, message, expiry)
fut = asyncio.run_coroutine_threadsafe(coro, self.network.asyncio_loop)
try:
return fut.result(timeout=5)
except concurrent.futures.TimeoutError:
raise Exception(_("add invoice timed out"))
@log_exceptions
async def create_invoice(
self, *,
amount_msat: Optional[int],
message: str,
expiry: int,
write_to_disk: bool = True,
) -> Tuple[LnAddr, str]:
timestamp = int(time.time())
routing_hints = await self._calc_routing_hints_for_invoice(amount_msat)
if not routing_hints:
self.logger.info(
"Warning. No routing hints added to invoice. "
"Other clients will likely not be able to send to us.")
# if not all hints are trampoline, do not create trampoline invoice
invoice_features = self.features.for_invoice()
trampoline_hints = []
for r in routing_hints:
node_id, short_channel_id, fee_base_msat, fee_proportional_millionths, cltv_expiry_delta = r[1][0]
if len(r[1])== 1 and self.is_trampoline_peer(node_id):
trampoline_hints.append(('t', (node_id, fee_base_msat, fee_proportional_millionths, cltv_expiry_delta)))
payment_preimage = os.urandom(32)
payment_hash = sha256(payment_preimage)
info = PaymentInfo(payment_hash, amount_msat, RECEIVED, PR_UNPAID)
amount_btc = amount_msat/Decimal(COIN*1000) if amount_msat else None
if expiry == 0:
expiry = LN_EXPIRY_NEVER
lnaddr = LnAddr(
paymenthash=payment_hash,
amount=amount_btc,
tags=[
('d', message),
('c', MIN_FINAL_CLTV_EXPIRY_FOR_INVOICE),
('x', expiry),
('9', invoice_features)]
+ routing_hints
+ trampoline_hints,
date=timestamp,
payment_secret=derive_payment_secret_from_payment_preimage(payment_preimage))
invoice = lnencode(lnaddr, self.node_keypair.privkey)
self.save_preimage(payment_hash, payment_preimage, write_to_disk=False)
self.save_payment_info(info, write_to_disk=False)
if write_to_disk:
self.wallet.save_db()
return lnaddr, invoice
async def _add_request_coro(self, amount_sat: Optional[int], message, expiry: int) -> str:
amount_msat = amount_sat * 1000 if amount_sat is not None else None
lnaddr, invoice = await self.create_invoice(
amount_msat=amount_msat,
message=message,
expiry=expiry,
write_to_disk=False,
)
key = bh2u(lnaddr.paymenthash)
req = LNInvoice.from_bech32(invoice)
self.wallet.add_payment_request(req, write_to_disk=False)
self.wallet.set_label(key, message)
self.wallet.save_db()
return key
def save_preimage(self, payment_hash: bytes, preimage: bytes, *, write_to_disk: bool = True):
assert sha256(preimage) == payment_hash
self.preimages[bh2u(payment_hash)] = bh2u(preimage)
if write_to_disk:
self.wallet.save_db()
def get_preimage(self, payment_hash: bytes) -> Optional[bytes]:
r = self.preimages.get(bh2u(payment_hash))
return bfh(r) if r else None
def get_payment_info(self, payment_hash: bytes) -> Optional[PaymentInfo]:
key = payment_hash.hex()
with self.lock:
if key in self.payments:
amount_msat, direction, status = self.payments[key]
return PaymentInfo(payment_hash, amount_msat, direction, status)
def save_payment_info(self, info: PaymentInfo, *, write_to_disk: bool = True) -> None:
key = info.payment_hash.hex()
assert info.status in SAVED_PR_STATUS
with self.lock:
self.payments[key] = info.amount_msat, info.direction, info.status
if write_to_disk:
self.wallet.save_db()
def check_received_mpp_htlc(self, payment_secret, short_channel_id, htlc: UpdateAddHtlc, expected_msat: int) -> Optional[bool]:
payment_hash = htlc.payment_hash
is_expired, is_accepted, htlc_set = self.received_mpp_htlcs.get(payment_secret, (False, False, set()))
if self.get_payment_status(payment_hash) == PR_PAID:
# payment_status is persisted
is_accepted = True
is_expired = False
key = (short_channel_id, htlc)
if key not in htlc_set:
htlc_set.add(key)
if not is_accepted and not is_expired:
total = sum([_htlc.amount_msat for scid, _htlc in htlc_set])
first_timestamp = min([_htlc.timestamp for scid, _htlc in htlc_set])
if self.stopping_soon:
is_expired = True # try to time out pending HTLCs before shutting down
elif time.time() - first_timestamp > self.MPP_EXPIRY:
is_expired = True
elif total == expected_msat:
is_accepted = True
if is_accepted or is_expired:
htlc_set.remove(key)
if len(htlc_set) > 0:
self.received_mpp_htlcs[payment_secret] = is_expired, is_accepted, htlc_set
elif payment_secret in self.received_mpp_htlcs:
self.received_mpp_htlcs.pop(payment_secret)
return True if is_accepted else (False if is_expired else None)
def get_payment_status(self, payment_hash: bytes) -> int:
info = self.get_payment_info(payment_hash)
return info.status if info else PR_UNPAID
def get_invoice_status(self, invoice: LNInvoice) -> int:
key = invoice.rhash
log = self.logs[key]
if key in self.inflight_payments:
return PR_INFLIGHT
# status may be PR_FAILED
status = self.get_payment_status(bfh(key))
if status == PR_UNPAID and log:
status = PR_FAILED
return status
def set_invoice_status(self, key: str, status: int) -> None:
if status == PR_INFLIGHT:
self.inflight_payments.add(key)
elif key in self.inflight_payments:
self.inflight_payments.remove(key)
if status in SAVED_PR_STATUS:
self.set_payment_status(bfh(key), status)
util.trigger_callback('invoice_status', self.wallet, key)
def set_request_status(self, payment_hash: bytes, status: int) -> None:
if self.get_payment_status(payment_hash) != status:
self.set_payment_status(payment_hash, status)
util.trigger_callback('request_status', self.wallet, payment_hash.hex(), status)
def set_payment_status(self, payment_hash: bytes, status: int) -> None:
info = self.get_payment_info(payment_hash)
if info is None:
# if we are forwarding
return
info = info._replace(status=status)
self.save_payment_info(info)
def _on_maybe_forwarded_htlc_resolved(self, chan: Channel, htlc_id: int) -> None:
fw_info = chan.short_channel_id.hex(), htlc_id
upstream_peer_pubkey = self.downstream_htlc_to_upstream_peer_map.get(fw_info)
if not upstream_peer_pubkey:
return
upstream_peer = self.peers.get(upstream_peer_pubkey)
if not upstream_peer:
return
upstream_peer.downstream_htlc_resolved_event.set()
upstream_peer.downstream_htlc_resolved_event.clear()
def htlc_fulfilled(self, chan: Channel, payment_hash: bytes, htlc_id: int):
util.trigger_callback('htlc_fulfilled', payment_hash, chan, htlc_id)
self._on_maybe_forwarded_htlc_resolved(chan=chan, htlc_id=htlc_id)
q = self.sent_htlcs.get(payment_hash)
if q:
route, payment_secret, amount_msat, bucket_msat, amount_receiver_msat, trampoline_fee_level = self.sent_htlcs_info[(payment_hash, chan.short_channel_id, htlc_id)]
htlc_log = HtlcLog(
success=True,
route=route,
amount_msat=amount_receiver_msat,
trampoline_fee_level=trampoline_fee_level)
q.put_nowait(htlc_log)
else:
key = payment_hash.hex()
self.set_invoice_status(key, PR_PAID)
util.trigger_callback('payment_succeeded', self.wallet, key)
def htlc_failed(
self,
chan: Channel,
payment_hash: bytes,
htlc_id: int,
error_bytes: Optional[bytes],
failure_message: Optional['OnionRoutingFailure']):
util.trigger_callback('htlc_failed', payment_hash, chan, htlc_id)
self._on_maybe_forwarded_htlc_resolved(chan=chan, htlc_id=htlc_id)
q = self.sent_htlcs.get(payment_hash)
if q:
# detect if it is part of a bucket
# if yes, wait until the bucket completely failed
key = (payment_hash, chan.short_channel_id, htlc_id)
route, payment_secret, amount_msat, bucket_msat, amount_receiver_msat, trampoline_fee_level = self.sent_htlcs_info[key]
if error_bytes:
# TODO "decode_onion_error" might raise, catch and maybe blacklist/penalise someone?
try:
failure_message, sender_idx = chan.decode_onion_error(error_bytes, route, htlc_id)
except Exception as e:
sender_idx = None
failure_message = OnionRoutingFailure(-1, str(e))
else:
# probably got "update_fail_malformed_htlc". well... who to penalise now?
assert failure_message is not None
sender_idx = None
self.logger.info(f"htlc_failed {failure_message}")
# check sent_buckets if we use trampoline
if not self.channel_db and payment_secret in self.sent_buckets:
amount_sent, amount_failed = self.sent_buckets[payment_secret]
amount_failed += amount_receiver_msat
self.sent_buckets[payment_secret] = amount_sent, amount_failed
if amount_sent != amount_failed:
self.logger.info('bucket still active...')
return
self.logger.info('bucket failed')
amount_receiver_msat = amount_sent
htlc_log = HtlcLog(
success=False,
route=route,
amount_msat=amount_receiver_msat,
error_bytes=error_bytes,
failure_msg=failure_message,
sender_idx=sender_idx,
trampoline_fee_level=trampoline_fee_level)
q.put_nowait(htlc_log)
else:
self.logger.info(f"received unknown htlc_failed, probably from previous session")
key = payment_hash.hex()
self.set_invoice_status(key, PR_UNPAID)
util.trigger_callback('payment_failed', self.wallet, key, '')
async def _calc_routing_hints_for_invoice(self, amount_msat: Optional[int]):
routing_hints = []
channels = list(self.channels.values())
# do minimal filtering of channels.
# we include channels that cannot *right now* receive (e.g. peer disconnected or balance insufficient)
channels = [chan for chan in channels
if (chan.is_open() and not chan.is_frozen_for_receiving())]
# Filter out channels that have very low receive capacity compared to invoice amt.
# Even with MPP, below a certain threshold, including these channels probably
# hurts more than help, as they lead to many failed attempts for the sender.
channels = [chan for chan in channels
if chan.available_to_spend(REMOTE) > (amount_msat or 0) * 0.05]
# cap max channels to include to keep QR code reasonably scannable
channels = sorted(channels, key=lambda chan: (not chan.is_active(), -chan.available_to_spend(REMOTE)))
channels = channels[:15]
random.shuffle(channels) # let's not leak channel order
scid_to_my_channels = {chan.short_channel_id: chan for chan in channels
if chan.short_channel_id is not None}
for chan in channels:
chan_id = chan.short_channel_id
assert isinstance(chan_id, bytes), chan_id
channel_info = get_mychannel_info(chan_id, scid_to_my_channels)
# incoming direction of our private channel, we fill the invoice with garbage.
# the sender should still be able to pay us, but will incur an extra round trip
# (they will get the channel update from the onion error)
# at least, that's the theory. https://github.com/lightningnetwork/lnd/issues/2066
fee_base_msat = fee_proportional_millionths = 0
cltv_expiry_delta = 1
missing_info = True
if channel_info:
policy = get_mychannel_policy(channel_info.short_channel_id, chan.node_id, scid_to_my_channels)
if policy:
fee_base_msat = policy.fee_base_msat
fee_proportional_millionths = policy.fee_proportional_millionths
cltv_expiry_delta = policy.cltv_expiry_delta
missing_info = False
if missing_info:
self.logger.info(
f"Warning. Missing channel update for our channel {chan_id}; "
f"filling invoice with incorrect data.")
routing_hints.append(('r', [(
chan.node_id,
chan_id,
fee_base_msat,
fee_proportional_millionths,
cltv_expiry_delta)]))
return routing_hints
def delete_payment(self, payment_hash_hex: str):
try:
with self.lock:
del self.payments[payment_hash_hex]
except KeyError:
return
self.wallet.save_db()
def get_balance(self):
with self.lock:
return Decimal(sum(
chan.balance(LOCAL) if not chan.is_closed() else 0
for chan in self.channels.values())) / 1000
def num_sats_can_send(self) -> Decimal:
can_send = 0
with self.lock:
if self.channels:
for c in self.channels.values():
if c.is_active() and not c.is_frozen_for_sending():
can_send += c.available_to_spend(LOCAL)
# Here we have to guess a fee, because some callers (submarine swaps)
# use this method to initiate a payment, which would otherwise fail.
fee_base_msat = TRAMPOLINE_FEES[3]['fee_base_msat']
fee_proportional_millionths = TRAMPOLINE_FEES[3]['fee_proportional_millionths']
# inverse of fee_for_edge_msat
can_send_minus_fees = (can_send - fee_base_msat) * 1_000_000 // ( 1_000_000 + fee_proportional_millionths)
can_send_minus_fees = max(0, can_send_minus_fees)
return Decimal(can_send_minus_fees) / 1000
def num_sats_can_receive(self) -> Decimal:
with self.lock:
channels = [
c for c in self.channels.values()
if c.is_active() and not c.is_frozen_for_receiving()
]
can_receive = sum([c.available_to_spend(REMOTE) for c in channels]) if channels else 0
return Decimal(can_receive) / 1000
def num_sats_can_receive_no_mpp(self) -> Decimal:
with self.lock:
channels = [
c for c in self.channels.values()
if c.is_active() and not c.is_frozen_for_receiving()
]
can_receive = max([c.available_to_spend(REMOTE) for c in channels]) if channels else 0
return Decimal(can_receive) / 1000
def can_pay_invoice(self, invoice: LNInvoice) -> bool:
return invoice.get_amount_sat() <= self.num_sats_can_send()
def can_receive_invoice(self, invoice: LNInvoice) -> bool:
return invoice.get_amount_sat() <= self.num_sats_can_receive()
async def close_channel(self, chan_id):
chan = self._channels[chan_id]
peer = self._peers[chan.node_id]
return await peer.close_channel(chan_id)
def _force_close_channel(self, chan_id: bytes) -> Transaction:
chan = self._channels[chan_id]
tx = chan.force_close_tx()
# We set the channel state to make sure we won't sign new commitment txs.
chan.set_state(ChannelState.FORCE_CLOSING)
try:
self.wallet.add_transaction(tx)
except UnrelatedTransactionException:
pass
return tx
async def force_close_channel(self, chan_id: bytes) -> str:
tx = self._force_close_channel(chan_id)
await self.network.broadcast_transaction(tx)
return tx.txid()
def schedule_force_closing(self, chan_id: bytes) -> 'asyncio.Task[None]':
tx = self._force_close_channel(chan_id)
return asyncio.create_task(self.network.try_broadcasting(tx, 'force-close'))
def remove_channel(self, chan_id):
chan = self.channels[chan_id]
assert chan.can_be_deleted()
with self.lock:
self._channels.pop(chan_id)
self.db.get('channels').pop(chan_id.hex())
for addr in chan.get_wallet_addresses_channel_might_want_reserved():
self.wallet.set_reserved_state_of_address(addr, reserved=False)
util.trigger_callback('channels_updated', self.wallet)
util.trigger_callback('wallet_updated', self.wallet)
@ignore_exceptions
@log_exceptions
async def reestablish_peer_for_given_channel(self, chan: Channel) -> None:
now = time.time()
peer_addresses = []
if not self.channel_db:
addr = trampolines_by_id().get(chan.node_id)
if addr:
peer_addresses.append(addr)
else:
last_good_addr = self.channel_db.get_last_good_address(chan.node_id)
if last_good_addr:
peer_addresses.append(last_good_addr)
addrs_from_gossip = self.channel_db.get_node_addresses(chan.node_id) or []
for host, port, ts in addrs_from_gossip:
peer_addresses.append(LNPeerAddr(host, port, chan.node_id))
peer_addresses += list(chan.get_peer_addresses())
for peer in peer_addresses:
if self._can_retry_addr(peer, urgent=True, now=now):
await self._add_peer(peer.host, peer.port, peer.pubkey)
return
async def reestablish_peers_and_channels(self):
while True:
await asyncio.sleep(1)
if self.stopping_soon:
return
for chan in self.channels.values():
if chan.is_closed():
continue
if not chan.should_try_to_reestablish_peer():
continue
peer = self._peers.get(chan.node_id, None)
if peer:
await peer.taskgroup.spawn(peer.reestablish_channel(chan))
else:
await self.taskgroup.spawn(self.reestablish_peer_for_given_channel(chan))
def current_feerate_per_kw(self):
from .simple_config import FEE_LN_ETA_TARGET, FEERATE_FALLBACK_STATIC_FEE, FEERATE_REGTEST_HARDCODED
from .simple_config import FEERATE_PER_KW_MIN_RELAY_LIGHTNING
if constants.net is constants.BitcoinRegtest:
return FEERATE_REGTEST_HARDCODED // 4
feerate_per_kvbyte = self.network.config.eta_target_to_fee(FEE_LN_ETA_TARGET)
if feerate_per_kvbyte is None:
feerate_per_kvbyte = FEERATE_FALLBACK_STATIC_FEE
return max(FEERATE_PER_KW_MIN_RELAY_LIGHTNING, feerate_per_kvbyte // 4)
def create_channel_backup(self, channel_id):
chan = self._channels[channel_id]
assert chan.is_static_remotekey_enabled()
peer_addresses = list(chan.get_peer_addresses())
peer_addr = peer_addresses[0]
return ImportedChannelBackupStorage(
node_id = chan.node_id,
privkey = self.node_keypair.privkey,
funding_txid = chan.funding_outpoint.txid,
funding_index = chan.funding_outpoint.output_index,
funding_address = chan.get_funding_address(),
host = peer_addr.host,
port = peer_addr.port,
is_initiator = chan.constraints.is_initiator,
channel_seed = chan.config[LOCAL].channel_seed,
local_delay = chan.config[LOCAL].to_self_delay,
remote_delay = chan.config[REMOTE].to_self_delay,
remote_revocation_pubkey = chan.config[REMOTE].revocation_basepoint.pubkey,
remote_payment_pubkey = chan.config[REMOTE].payment_basepoint.pubkey)
def export_channel_backup(self, channel_id):
xpub = self.wallet.get_fingerprint()
backup_bytes = self.create_channel_backup(channel_id).to_bytes()
assert backup_bytes == ImportedChannelBackupStorage.from_bytes(backup_bytes).to_bytes(), "roundtrip failed"
encrypted = pw_encode_with_version_and_mac(backup_bytes, xpub)
assert backup_bytes == pw_decode_with_version_and_mac(encrypted, xpub), "encrypt failed"
return 'channel_backup:' + encrypted
async def request_force_close(self, channel_id: bytes, *, connect_str=None) -> None:
if channel_id in self.channels:
chan = self.channels[channel_id]
peer = self._peers.get(chan.node_id)
if not peer:
raise Exception('Peer not found')
chan.should_request_force_close = True
peer.close_and_cleanup()
elif connect_str:
peer = await self.add_peer(connect_str)
await peer.trigger_force_close(channel_id)
elif channel_id in self.channel_backups:
await self._request_force_close_from_backup(channel_id)
else:
raise Exception(f'Unknown channel {channel_id.hex()}')
def import_channel_backup(self, data):
assert data.startswith('channel_backup:')
encrypted = data[15:]
xpub = self.wallet.get_fingerprint()
decrypted = pw_decode_with_version_and_mac(encrypted, xpub)
cb_storage = ImportedChannelBackupStorage.from_bytes(decrypted)
channel_id = cb_storage.channel_id()
if channel_id.hex() in self.db.get_dict("channels"):
raise Exception('Channel already in wallet')
self.logger.info(f'importing channel backup: {channel_id.hex()}')
d = self.db.get_dict("imported_channel_backups")
d[channel_id.hex()] = cb_storage
with self.lock:
cb = ChannelBackup(cb_storage, sweep_address=self.sweep_address, lnworker=self)
self._channel_backups[channel_id] = cb
self.wallet.save_db()
util.trigger_callback('channels_updated', self.wallet)
self.lnwatcher.add_channel(cb.funding_outpoint.to_str(), cb.get_funding_address())
def has_conflicting_backup_with(self, remote_node_id: bytes):
channel_backup_peers = [
cb.node_id for cb in self.channel_backups.values()
if (not cb.is_closed() and cb.get_local_pubkey() == self.node_keypair.pubkey)]
return any(remote_node_id.startswith(cb_peer_nodeid) for cb_peer_nodeid in channel_backup_peers)
def remove_channel_backup(self, channel_id):
chan = self.channel_backups[channel_id]
assert chan.can_be_deleted()
onchain_backups = self.db.get_dict("onchain_channel_backups")
imported_backups = self.db.get_dict("imported_channel_backups")
if channel_id.hex() in onchain_backups:
onchain_backups.pop(channel_id.hex())
elif channel_id.hex() in imported_backups:
imported_backups.pop(channel_id.hex())
else:
raise Exception('Channel not found')
with self.lock:
self._channel_backups.pop(channel_id)
self.wallet.save_db()
util.trigger_callback('channels_updated', self.wallet)
@log_exceptions
async def _request_force_close_from_backup(self, channel_id: bytes):
cb = self.channel_backups.get(channel_id)
if not cb:
raise Exception(f'channel backup not found {self.channel_backups}')
cb = cb.cb
self.logger.info(f'requesting channel force close: {channel_id.hex()}')
if isinstance(cb, ImportedChannelBackupStorage):
node_id = cb.node_id
privkey = cb.privkey
addresses = [(cb.host, cb.port, 0)]
else:
assert isinstance(cb, OnchainChannelBackupStorage)
if not self.channel_db:
raise Exception('Enable gossip first')
node_id = self.network.channel_db.get_node_by_prefix(cb.node_id_prefix)
privkey = self.node_keypair.privkey
addresses = self.network.channel_db.get_node_addresses(node_id)
if not addresses:
raise Exception('Peer not found in gossip database')
for host, port, timestamp in addresses:
peer_addr = LNPeerAddr(host, port, node_id)
transport = LNTransport(privkey, peer_addr, proxy=self.network.proxy)
peer = Peer(self, node_id, transport, is_channel_backup=True)
try:
async with OldTaskGroup(wait=any) as group:
await group.spawn(peer._message_loop())
await group.spawn(peer.trigger_force_close(channel_id))
return
except Exception as e:
self.logger.info(f'failed to connect {host} {e}')
continue
else:
raise Exception('failed to connect')
def maybe_add_backup_from_tx(self, tx):
funding_address = None
node_id_prefix = None
for i, o in enumerate(tx.outputs()):
script_type = get_script_type_from_output_script(o.scriptpubkey)
if script_type == 'p2wsh':
funding_index = i
funding_address = o.address
for o2 in tx.outputs():
if o2.scriptpubkey.startswith(bytes([opcodes.OP_RETURN])):
encrypted_data = o2.scriptpubkey[2:]
data = self.decrypt_cb_data(encrypted_data, funding_address)
if data.startswith(CB_MAGIC_BYTES):
node_id_prefix = data[4:]
if node_id_prefix is None:
return
funding_txid = tx.txid()
cb_storage = OnchainChannelBackupStorage(
node_id_prefix = node_id_prefix,
funding_txid = funding_txid,
funding_index = funding_index,
funding_address = funding_address,
is_initiator = True)
channel_id = cb_storage.channel_id().hex()
if channel_id in self.db.get_dict("channels"):
return
self.logger.info(f"adding backup from tx")
d = self.db.get_dict("onchain_channel_backups")
d[channel_id] = cb_storage
cb = ChannelBackup(cb_storage, sweep_address=self.sweep_address, lnworker=self)
self.wallet.save_db()
with self.lock:
self._channel_backups[bfh(channel_id)] = cb
util.trigger_callback('channels_updated', self.wallet)
self.lnwatcher.add_channel(cb.funding_outpoint.to_str(), cb.get_funding_address())
| true | true |
f72b88a082eaa6db2a20df009f1b14a4cabb69cb | 355 | py | Python | unified_api/utils/utils.py | campos537/deep-fashion-system | 1de31dd6260cc967e1832cff63ae7e537a3a4e9d | [
"Unlicense"
] | 1 | 2021-04-06T00:43:26.000Z | 2021-04-06T00:43:26.000Z | unified_api/utils/utils.py | campos537/deep-fashion-system | 1de31dd6260cc967e1832cff63ae7e537a3a4e9d | [
"Unlicense"
] | null | null | null | unified_api/utils/utils.py | campos537/deep-fashion-system | 1de31dd6260cc967e1832cff63ae7e537a3a4e9d | [
"Unlicense"
] | null | null | null | def valid_pubsub(config):
if (config.get("topic_id") is not None and config.get("project_id") is not None
and config.get("subscription_id") is not None):
return True
return False
def valid_kafka(config):
if config.get("bootstrap_server") is not None and config.get("port") is not None:
return True
return False | 35.5 | 85 | 0.673239 | def valid_pubsub(config):
if (config.get("topic_id") is not None and config.get("project_id") is not None
and config.get("subscription_id") is not None):
return True
return False
def valid_kafka(config):
if config.get("bootstrap_server") is not None and config.get("port") is not None:
return True
return False | true | true |
f72b8a6bcb330314847fdb6f9ab7b88b743e3aa1 | 3,094 | py | Python | sdk/python/kfp/cli/diagnose_me/kubernetes_cluster_test.py | ConverJens/pipelines | a1d453af214ec9eebad73fb05845dd3499d60d00 | [
"Apache-2.0"
] | 6 | 2020-05-19T02:35:11.000Z | 2020-05-29T17:58:42.000Z | sdk/python/kfp/cli/diagnose_me/kubernetes_cluster_test.py | ConverJens/pipelines | a1d453af214ec9eebad73fb05845dd3499d60d00 | [
"Apache-2.0"
] | 1,932 | 2021-01-25T11:23:37.000Z | 2022-03-31T17:10:18.000Z | sdk/python/kfp/cli/diagnose_me/kubernetes_cluster_test.py | ConverJens/pipelines | a1d453af214ec9eebad73fb05845dd3499d60d00 | [
"Apache-2.0"
] | 11 | 2020-05-19T22:26:41.000Z | 2021-01-25T09:56:21.000Z | # Lint as: python3
# Copyright 2019 Google LLC. 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.
"""Tests for diagnose_me.kubernetes_cluster."""
from typing import Text
import unittest
from unittest import mock
from . import kubernetes_cluster as dkc
from . import utility
class KubernetesClusterTest(unittest.TestCase):
@mock.patch.object(dkc, 'execute_kubectl_command', autospec=True)
def test_project_configuration_gcloud(self, mock_execute_kubectl_command):
"""Tests gcloud commands."""
dkc.get_kubectl_configuration(dkc.Commands.GET_PODS)
mock_execute_kubectl_command.assert_called_once_with(
['get', 'pods', '--all-namespaces'], human_readable=False)
dkc.get_kubectl_configuration(dkc.Commands.GET_CONFIGURED_CONTEXT)
mock_execute_kubectl_command.assert_called_with(['config', 'view'],
human_readable=False)
dkc.get_kubectl_configuration(dkc.Commands.GET_KUBECTL_VERSION)
mock_execute_kubectl_command.assert_called_with(['version'],
human_readable=False)
dkc.get_kubectl_configuration(
dkc.Commands.GET_PODS, kubernetes_context='test_context')
mock_execute_kubectl_command.assert_called_with(
['get', 'pods', '--context', 'test_context', '--all-namespaces'],
human_readable=False)
dkc.get_kubectl_configuration(
dkc.Commands.GET_PODS, kubernetes_context='test_context')
mock_execute_kubectl_command.assert_called_with(
['get', 'pods', '--context', 'test_context', '--all-namespaces'],
human_readable=False)
def test_Commands(self):
"""Verify commands are formaated properly."""
for command in dkc.Commands:
self.assertIsInstance(dkc._command_string[command], Text)
self.assertNotIn('\t', dkc._command_string[command])
self.assertNotIn('\n', dkc._command_string[command])
@mock.patch.object(utility, 'ExecutorResponse', autospec=True)
def test_execute_kubectl_command(self, mock_executor_response):
"""Test execute_gsutil_command."""
dkc.execute_kubectl_command(
[dkc._command_string[dkc.Commands.GET_KUBECTL_VERSION]])
mock_executor_response().execute_command.assert_called_once_with(
['kubectl', 'version', '-o', 'json'])
dkc.execute_kubectl_command(
[dkc._command_string[dkc.Commands.GET_KUBECTL_VERSION]],
human_readable=True)
mock_executor_response().execute_command.assert_called_with(
['kubectl', 'version'])
if __name__ == '__main__':
unittest.main()
| 40.181818 | 76 | 0.724952 |
from typing import Text
import unittest
from unittest import mock
from . import kubernetes_cluster as dkc
from . import utility
class KubernetesClusterTest(unittest.TestCase):
@mock.patch.object(dkc, 'execute_kubectl_command', autospec=True)
def test_project_configuration_gcloud(self, mock_execute_kubectl_command):
dkc.get_kubectl_configuration(dkc.Commands.GET_PODS)
mock_execute_kubectl_command.assert_called_once_with(
['get', 'pods', '--all-namespaces'], human_readable=False)
dkc.get_kubectl_configuration(dkc.Commands.GET_CONFIGURED_CONTEXT)
mock_execute_kubectl_command.assert_called_with(['config', 'view'],
human_readable=False)
dkc.get_kubectl_configuration(dkc.Commands.GET_KUBECTL_VERSION)
mock_execute_kubectl_command.assert_called_with(['version'],
human_readable=False)
dkc.get_kubectl_configuration(
dkc.Commands.GET_PODS, kubernetes_context='test_context')
mock_execute_kubectl_command.assert_called_with(
['get', 'pods', '--context', 'test_context', '--all-namespaces'],
human_readable=False)
dkc.get_kubectl_configuration(
dkc.Commands.GET_PODS, kubernetes_context='test_context')
mock_execute_kubectl_command.assert_called_with(
['get', 'pods', '--context', 'test_context', '--all-namespaces'],
human_readable=False)
def test_Commands(self):
for command in dkc.Commands:
self.assertIsInstance(dkc._command_string[command], Text)
self.assertNotIn('\t', dkc._command_string[command])
self.assertNotIn('\n', dkc._command_string[command])
@mock.patch.object(utility, 'ExecutorResponse', autospec=True)
def test_execute_kubectl_command(self, mock_executor_response):
dkc.execute_kubectl_command(
[dkc._command_string[dkc.Commands.GET_KUBECTL_VERSION]])
mock_executor_response().execute_command.assert_called_once_with(
['kubectl', 'version', '-o', 'json'])
dkc.execute_kubectl_command(
[dkc._command_string[dkc.Commands.GET_KUBECTL_VERSION]],
human_readable=True)
mock_executor_response().execute_command.assert_called_with(
['kubectl', 'version'])
if __name__ == '__main__':
unittest.main()
| true | true |
f72b8a7bda68abbe8202a4c1804acb456c64dc74 | 1,096 | py | Python | synth.py | athakor/java-monitoring | 6c013839c5b349e4402a3fa87245930d8d1cc20b | [
"Apache-2.0"
] | null | null | null | synth.py | athakor/java-monitoring | 6c013839c5b349e4402a3fa87245930d8d1cc20b | [
"Apache-2.0"
] | null | null | null | synth.py | athakor/java-monitoring | 6c013839c5b349e4402a3fa87245930d8d1cc20b | [
"Apache-2.0"
] | null | null | null | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This script is used to synthesize generated parts of this library."""
import synthtool as s
import synthtool.gcp as gcp
import synthtool.languages.java as java
gapic = gcp.GAPICGenerator()
service = 'monitoring'
versions = ['v3']
config_pattern = '/google/monitoring/artman_monitoring.yaml'
for version in versions:
java.gapic_library(
service=service,
version=version,
config_pattern=config_pattern,
package_pattern='com.google.{service}.{version}',
gapic=gapic
)
java.common_templates()
| 29.621622 | 74 | 0.756387 |
import synthtool as s
import synthtool.gcp as gcp
import synthtool.languages.java as java
gapic = gcp.GAPICGenerator()
service = 'monitoring'
versions = ['v3']
config_pattern = '/google/monitoring/artman_monitoring.yaml'
for version in versions:
java.gapic_library(
service=service,
version=version,
config_pattern=config_pattern,
package_pattern='com.google.{service}.{version}',
gapic=gapic
)
java.common_templates()
| true | true |
f72b8af740fb1cc78203d79551f725c340162fdf | 49 | py | Python | typings/bl_rna_utils/__init__.py | Argmaster/PyR3 | 6786bcb6a101fe4bd4cc50fe43767b8178504b15 | [
"MIT"
] | 2 | 2021-12-12T18:51:52.000Z | 2022-02-23T09:49:16.000Z | typings/bl_rna_utils/__init__.py | Argmaster/PyR3 | 6786bcb6a101fe4bd4cc50fe43767b8178504b15 | [
"MIT"
] | 2 | 2021-11-08T12:09:02.000Z | 2021-12-12T23:01:12.000Z | typings/bl_rna_utils/__init__.py | Argmaster/PyR3 | 6786bcb6a101fe4bd4cc50fe43767b8178504b15 | [
"MIT"
] | null | null | null | import sys
import typing
from . import data_path
| 12.25 | 23 | 0.816327 | import sys
import typing
from . import data_path
| true | true |
f72b8b472726026675a7b89a1c670dce52cfa9b7 | 2,274 | py | Python | tests/model/model_discovery_test.py | nickgaya/bravado-core | 16e752963bfceb4adfa43724085bc4127eefcd59 | [
"BSD-3-Clause"
] | 122 | 2015-04-22T17:31:18.000Z | 2021-11-08T10:29:57.000Z | tests/model/model_discovery_test.py | nickgaya/bravado-core | 16e752963bfceb4adfa43724085bc4127eefcd59 | [
"BSD-3-Clause"
] | 364 | 2015-04-10T22:19:23.000Z | 2022-02-25T08:55:10.000Z | tests/model/model_discovery_test.py | nickgaya/bravado-core | 16e752963bfceb4adfa43724085bc4127eefcd59 | [
"BSD-3-Clause"
] | 118 | 2015-04-20T15:11:53.000Z | 2021-12-09T10:03:34.000Z | # -*- coding: utf-8 -*-
import mock
import pytest
from bravado_core.model import _run_post_processing
from bravado_core.model import model_discovery
from bravado_core.spec import Spec
@pytest.fixture
def wrap__run_post_processing():
with mock.patch(
'bravado_core.model._run_post_processing',
wraps=_run_post_processing,
) as _wrap__run_post_processing:
yield _wrap__run_post_processing
def test_model_discovery_flow_no_ref_dereference(wrap__run_post_processing, minimal_swagger_dict):
spec = Spec(
spec_dict=minimal_swagger_dict,
config={
'internally_dereference_refs': False,
},
)
model_discovery(swagger_spec=spec)
wrap__run_post_processing.assert_called_once_with(spec)
def test_model_discovery_flow_with_ref_dereference(wrap__run_post_processing, minimal_swagger_dict):
spec = Spec(
spec_dict=dict(minimal_swagger_dict, definitions={'model': {'type': 'object'}}),
config={
'internally_dereference_refs': True,
},
origin_url='',
)
model_discovery(swagger_spec=spec)
# _run_post_processing is called 3 times
# 1. post processing on initial specs
# 2. post processing on on bravado_core.spec_flattening.flattened_spec
# 3. post processing to rebuild definitions to remove possible references in the model specs
assert wrap__run_post_processing.call_count == 3
@pytest.mark.parametrize(
'model_dict',
[
{
'properties': {
'allOf': {
'type': 'string',
},
'title': {'type': 'string'},
'type': {'type': 'string'},
},
'type': 'object',
},
],
)
def test_model_discovery_for_models_with_not_string_title_x_model(minimal_swagger_dict, model_dict):
# This test case has been extracted from the Kubernetes Swagger specs
# https://raw.githubusercontent.com/kubernetes/kubernetes/release-1.15/api/openapi-spec/swagger.json#/definitions/io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaProps
spec = Spec.from_dict(spec_dict=dict(minimal_swagger_dict, definitions={'Model': model_dict}))
assert set(spec.definitions) == {'Model'}
| 33.940299 | 195 | 0.690413 |
import mock
import pytest
from bravado_core.model import _run_post_processing
from bravado_core.model import model_discovery
from bravado_core.spec import Spec
@pytest.fixture
def wrap__run_post_processing():
with mock.patch(
'bravado_core.model._run_post_processing',
wraps=_run_post_processing,
) as _wrap__run_post_processing:
yield _wrap__run_post_processing
def test_model_discovery_flow_no_ref_dereference(wrap__run_post_processing, minimal_swagger_dict):
spec = Spec(
spec_dict=minimal_swagger_dict,
config={
'internally_dereference_refs': False,
},
)
model_discovery(swagger_spec=spec)
wrap__run_post_processing.assert_called_once_with(spec)
def test_model_discovery_flow_with_ref_dereference(wrap__run_post_processing, minimal_swagger_dict):
spec = Spec(
spec_dict=dict(minimal_swagger_dict, definitions={'model': {'type': 'object'}}),
config={
'internally_dereference_refs': True,
},
origin_url='',
)
model_discovery(swagger_spec=spec)
assert wrap__run_post_processing.call_count == 3
@pytest.mark.parametrize(
'model_dict',
[
{
'properties': {
'allOf': {
'type': 'string',
},
'title': {'type': 'string'},
'type': {'type': 'string'},
},
'type': 'object',
},
],
)
def test_model_discovery_for_models_with_not_string_title_x_model(minimal_swagger_dict, model_dict):
_dict}))
assert set(spec.definitions) == {'Model'}
| true | true |
f72b8df9aa69d2cc28657e451f4a61aca75b3217 | 2,091 | py | Python | toys/sqlalchemy_bakery.py | mikegreen7892003/PythonToy | e9218cdee4a38835fdbebad0e429ddf52bb444b4 | [
"MIT"
] | null | null | null | toys/sqlalchemy_bakery.py | mikegreen7892003/PythonToy | e9218cdee4a38835fdbebad0e429ddf52bb444b4 | [
"MIT"
] | null | null | null | toys/sqlalchemy_bakery.py | mikegreen7892003/PythonToy | e9218cdee4a38835fdbebad0e429ddf52bb444b4 | [
"MIT"
] | null | null | null | """
Just for Python 3
"""
import logging
import pprint
import tornado.web
import tornado.httpserver
from tornado.options import define, options, parse_command_line
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext import baked
from sqlalchemy.orm import Session
# models
BAKERY = baked.bakery()
Base = declarative_base()
ENGINE = create_engine('sqlite:///:memory:', echo=False)
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
fullname = Column(String)
password = Column(String)
def __repr__(self):
return "<User(name='%s', fullname='%s', password='%s')>" % (
self.name, self.fullname, self.password)
# request
class MainHandler(tornado.web.RequestHandler):
@property
def session(self):
return Session(bind=ENGINE)
def get(self):
uid = self.get_argument("uid")
def fn(session):
logging.warn("call fn %s", fn)
return session.query(User).filter(User.id == uid)
baked_query = BAKERY(fn)
logging.info("fn %s", fn.__code__)
logging.warn("baked_query _cache_key: %s", baked_query._cache_key)
user_list = baked_query(self.session).all()
self.write("user_list:\n{}\n".format(pprint.pformat(user_list)))
def main():
Base.metadata.create_all(ENGINE)
# add test user
session = Session(bind=ENGINE)
for uid in range(20):
user = User(name='ed {}'.format(uid), fullname='Ed Jones {}'.format(uid), password='edspassword')
session.add(user)
session.commit()
# start application
application = tornado.web.Application([
(r"/", MainHandler),
], )
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(options.port)
tornado.ioloop.IOLoop.current().start()
if __name__ == "__main__":
define("port", default=8888, help="run on the given port", type=int)
parse_command_line()
main()
| 23.761364 | 105 | 0.659971 |
import logging
import pprint
import tornado.web
import tornado.httpserver
from tornado.options import define, options, parse_command_line
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext import baked
from sqlalchemy.orm import Session
BAKERY = baked.bakery()
Base = declarative_base()
ENGINE = create_engine('sqlite:///:memory:', echo=False)
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
fullname = Column(String)
password = Column(String)
def __repr__(self):
return "<User(name='%s', fullname='%s', password='%s')>" % (
self.name, self.fullname, self.password)
class MainHandler(tornado.web.RequestHandler):
@property
def session(self):
return Session(bind=ENGINE)
def get(self):
uid = self.get_argument("uid")
def fn(session):
logging.warn("call fn %s", fn)
return session.query(User).filter(User.id == uid)
baked_query = BAKERY(fn)
logging.info("fn %s", fn.__code__)
logging.warn("baked_query _cache_key: %s", baked_query._cache_key)
user_list = baked_query(self.session).all()
self.write("user_list:\n{}\n".format(pprint.pformat(user_list)))
def main():
Base.metadata.create_all(ENGINE)
session = Session(bind=ENGINE)
for uid in range(20):
user = User(name='ed {}'.format(uid), fullname='Ed Jones {}'.format(uid), password='edspassword')
session.add(user)
session.commit()
application = tornado.web.Application([
(r"/", MainHandler),
], )
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(options.port)
tornado.ioloop.IOLoop.current().start()
if __name__ == "__main__":
define("port", default=8888, help="run on the given port", type=int)
parse_command_line()
main()
| true | true |
f72b8dfa12eefecf24dc259425f0b7961d8f210a | 28,498 | py | Python | tests/gce_virtual_machine_test.py | mikeweng/PerfKitBenchmarker | e929a69f04e2f91a0fed7da8db8a321edf58f403 | [
"Apache-2.0"
] | null | null | null | tests/gce_virtual_machine_test.py | mikeweng/PerfKitBenchmarker | e929a69f04e2f91a0fed7da8db8a321edf58f403 | [
"Apache-2.0"
] | null | null | null | tests/gce_virtual_machine_test.py | mikeweng/PerfKitBenchmarker | e929a69f04e2f91a0fed7da8db8a321edf58f403 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 PerfKitBenchmarker 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.
"""Tests for perfkitbenchmarker.providers.gcp.gce_virtual_machine."""
import contextlib
import copy
import json
import re
import unittest
from absl import flags
import builtins
import mock
from perfkitbenchmarker import benchmark_spec
from perfkitbenchmarker import context
from perfkitbenchmarker import errors
from perfkitbenchmarker import os_types
from perfkitbenchmarker import providers
from perfkitbenchmarker import virtual_machine
from perfkitbenchmarker import vm_util
from perfkitbenchmarker.configs import benchmark_config_spec
from perfkitbenchmarker.providers.gcp import gce_network
from perfkitbenchmarker.providers.gcp import gce_virtual_machine
from perfkitbenchmarker.providers.gcp import util
from tests import pkb_common_test_case
FLAGS = flags.FLAGS
_BENCHMARK_NAME = 'name'
_BENCHMARK_UID = 'benchmark_uid'
_COMPONENT = 'test_component'
_FLAGS = None
_FAKE_INSTANCE_METADATA = {
'id': '123456',
'networkInterfaces': [
{
'accessConfigs': [
{
'natIP': '1.2.3.4'
}
],
'networkIP': '1.2.3.4'
}
]
}
_FAKE_DISK_METADATA = {
'id': '123456',
'kind': 'compute#disk',
'name': 'fakedisk',
'sizeGb': '10',
'sourceImage': '',
'type': 'pd-standard'
}
@contextlib.contextmanager
def PatchCriticalObjects(retvals=None):
"""A context manager that patches a few critical objects with mocks."""
def ReturnVal(*unused_arg, **unused_kwargs):
del unused_arg
del unused_kwargs
return ('', '', 0) if retvals is None else retvals.pop(0)
with mock.patch(
vm_util.__name__ + '.IssueCommand',
side_effect=ReturnVal) as issue_command, mock.patch(
builtins.__name__ + '.open'), mock.patch(
vm_util.__name__ +
'.NamedTemporaryFile'), mock.patch(util.__name__ +
'.GetDefaultProject'):
yield issue_command
class GceVmSpecTestCase(pkb_common_test_case.PkbCommonTestCase):
def testStringMachineType(self):
result = gce_virtual_machine.GceVmSpec(_COMPONENT,
machine_type='n1-standard-8')
self.assertEqual(result.machine_type, 'n1-standard-8')
self.assertEqual(result.cpus, None)
self.assertEqual(result.memory, None)
def testStringMachineTypeWithGpus(self):
gpu_count = 2
gpu_type = 'k80'
result = gce_virtual_machine.GceVmSpec(_COMPONENT,
machine_type='n1-standard-8',
gpu_count=gpu_count,
gpu_type=gpu_type)
self.assertEqual(result.machine_type, 'n1-standard-8')
self.assertEqual(result.gpu_type, 'k80')
self.assertEqual(result.gpu_count, 2)
def testCustomMachineType(self):
result = gce_virtual_machine.GceVmSpec(_COMPONENT, machine_type={
'cpus': 1, 'memory': '7.5GiB'})
self.assertEqual(result.machine_type, None)
self.assertEqual(result.cpus, 1)
self.assertEqual(result.memory, 7680)
def testCustomMachineTypeWithGpus(self):
gpu_count = 2
gpu_type = 'k80'
result = gce_virtual_machine.GceVmSpec(_COMPONENT,
machine_type={
'cpus': 1,
'memory': '7.5GiB'
},
gpu_count=gpu_count,
gpu_type=gpu_type)
self.assertEqual(result.cpus, 1)
self.assertEqual(result.memory, 7680)
self.assertEqual(result.gpu_type, 'k80')
self.assertEqual(result.gpu_count, 2)
def testStringMachineTypeFlagOverride(self):
FLAGS['machine_type'].parse('n1-standard-8')
result = gce_virtual_machine.GceVmSpec(
_COMPONENT,
flag_values=FLAGS,
machine_type={
'cpus': 1,
'memory': '7.5GiB'
})
self.assertEqual(result.machine_type, 'n1-standard-8')
self.assertEqual(result.cpus, None)
self.assertEqual(result.memory, None)
def testCustomMachineTypeFlagOverride(self):
FLAGS['machine_type'].parse('{cpus: 1, memory: 7.5GiB}')
result = gce_virtual_machine.GceVmSpec(
_COMPONENT, flag_values=FLAGS, machine_type='n1-standard-8')
self.assertEqual(result.machine_type, None)
self.assertEqual(result.cpus, 1)
self.assertEqual(result.memory, 7680)
class GceVirtualMachineTestCase(pkb_common_test_case.PkbCommonTestCase):
def setUp(self):
super(GceVirtualMachineTestCase, self).setUp()
p = mock.patch(gce_virtual_machine.__name__ +
'.gce_network.GceNetwork.GetNetwork')
self.mock_get_network = p.start()
self.addCleanup(p.stop)
p = mock.patch(gce_virtual_machine.__name__ +
'.gce_network.GceFirewall.GetFirewall')
self.mock_get_firewall = p.start()
self.addCleanup(p.stop)
get_tmp_dir_mock = mock.patch(
vm_util.__name__ + '.GetTempDir', return_value='TempDir')
get_tmp_dir_mock.start()
self.addCleanup(get_tmp_dir_mock.stop)
def testVmWithMachineTypeNonPreemptible(self):
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT, machine_type='test_machine_type', project='p')
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
vm.created = True
self.assertDictContainsSubset(
{'dedicated_host': False, 'machine_type': 'test_machine_type',
'project': 'p'},
vm.GetResourceMetadata()
)
def testVmWithMachineTypePreemptible(self):
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT, machine_type='test_machine_type', preemptible=True,
project='p')
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
vm.created = True
self.assertDictContainsSubset(
{'dedicated_host': False, 'machine_type': 'test_machine_type',
'preemptible': True, 'project': 'p'},
vm.GetResourceMetadata()
)
def testCustomVmNonPreemptible(self):
spec = gce_virtual_machine.GceVmSpec(_COMPONENT, machine_type={
'cpus': 1, 'memory': '1.0GiB'}, project='p')
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
vm.created = True
self.assertDictContainsSubset(
{'cpus': 1, 'memory_mib': 1024, 'project': 'p',
'dedicated_host': False},
vm.GetResourceMetadata())
def testCustomVmPreemptible(self):
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT, machine_type={'cpus': 1, 'memory': '1.0GiB'},
preemptible=True,
project='fakeproject')
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
vm.created = True
self.assertDictContainsSubset({
'cpus': 1, 'memory_mib': 1024, 'project': 'fakeproject',
'dedicated_host': False, 'preemptible': True}, vm.GetResourceMetadata())
def testCustomVmWithGpus(self):
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT,
machine_type={'cpus': 1, 'memory': '1.0GiB'},
gpu_count=2,
gpu_type='k80',
project='fakeproject')
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
vm.created = True
self.assertDictContainsSubset({
'cpus': 1, 'memory_mib': 1024, 'project': 'fakeproject',
'dedicated_host': False, 'gpu_count': 2, 'gpu_type': 'k80'
}, vm.GetResourceMetadata())
def _CreateFakeDiskMetadata(image):
fake_disk = copy.copy(_FAKE_DISK_METADATA)
fake_disk['sourceImage'] = image
return fake_disk
class GceVirtualMachineOsTypesTestCase(pkb_common_test_case.PkbCommonTestCase):
def setUp(self):
super(GceVirtualMachineOsTypesTestCase, self).setUp()
FLAGS.gcp_instance_metadata_from_file = ''
FLAGS.gcp_instance_metadata = ''
FLAGS.gcloud_path = 'gcloud'
p = mock.patch(gce_virtual_machine.__name__ +
'.gce_network.GceNetwork.GetNetwork')
self.mock_get_network = p.start()
self.addCleanup(p.stop)
p = mock.patch(gce_virtual_machine.__name__ +
'.gce_network.GceFirewall.GetFirewall')
self.mock_get_firewall = p.start()
self.addCleanup(p.stop)
self.spec = gce_virtual_machine.GceVmSpec(_COMPONENT,
machine_type='fake-machine-type')
p = mock.patch(gce_virtual_machine.__name__ +
'.linux_vm.BaseLinuxMixin._GetNumCpus')
self.mock_get_num_cpus = p.start()
self.addCleanup(p.stop)
get_tmp_dir_mock = mock.patch(
vm_util.__name__ + '.GetTempDir', return_value='TempDir')
get_tmp_dir_mock.start()
self.addCleanup(get_tmp_dir_mock.stop)
def _CreateFakeReturnValues(self, fake_image=''):
fake_rets = [('', '', 0), (json.dumps(_FAKE_INSTANCE_METADATA), '', 0)]
if fake_image:
fake_rets.append((json.dumps(_CreateFakeDiskMetadata(fake_image)), '', 0))
return fake_rets
def testCreateUbuntu1604(self):
vm_class = virtual_machine.GetVmClass(providers.GCP, os_types.UBUNTU1604)
fake_image = 'fake-ubuntu1604'
with PatchCriticalObjects(
self._CreateFakeReturnValues(fake_image)) as issue_command:
vm = vm_class(self.spec)
vm._Create()
vm.created = True
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn('gcloud compute instances create', command_string)
self.assertIn(
'--image-family ubuntu-1604-lts --image-project ubuntu-os-cloud',
command_string)
self.assertNotIn('--boot-disk-size', command_string)
self.assertNotIn('--boot-disk-type', command_string)
vm._PostCreate()
self.assertEqual(issue_command.call_count, 3)
self.assertDictContainsSubset({'image': fake_image,
'image_family': 'ubuntu-1604-lts',
'image_project': 'ubuntu-os-cloud',
'boot_disk_size': '10',
'boot_disk_type': 'pd-standard'},
vm.GetResourceMetadata())
def testCreateUbuntuInCustomProject(self):
"""Test simulating passing --image and --image_project."""
vm_class = virtual_machine.GetVmClass(providers.GCP, os_types.UBUNTU1604)
fake_image = 'fake-ubuntu1604'
fake_image_project = 'fake-project'
spec = gce_virtual_machine.GceVmSpec(_COMPONENT,
machine_type='fake-machine-type',
image=fake_image,
image_project=fake_image_project)
with PatchCriticalObjects(
self._CreateFakeReturnValues(fake_image)) as issue_command:
vm = vm_class(spec)
vm._Create()
vm.created = True
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn('gcloud compute instances create', command_string)
self.assertIn(
'--image fake-ubuntu1604 --image-project fake-project',
command_string)
self.assertNotIn('--image-family', command_string)
vm._PostCreate()
self.assertEqual(issue_command.call_count, 3)
vm_metadata = vm.GetResourceMetadata()
self.assertDictContainsSubset({'image': fake_image,
'image_project': 'fake-project'},
vm_metadata)
self.assertNotIn('image_family', vm_metadata)
def testCreateUbuntuInCustomDisk(self):
"""Test simulating passing --image and --image_project."""
vm_class = virtual_machine.GetVmClass(providers.GCP, os_types.UBUNTU1604)
fake_image = 'fake-ubuntu1604'
fake_image_project = 'fake-project'
spec = gce_virtual_machine.GceVmSpec(_COMPONENT,
machine_type='fake-machine-type',
image=fake_image,
image_project=fake_image_project,
boot_disk_size=20,
boot_disk_type='fake-disk-type')
with PatchCriticalObjects(
self._CreateFakeReturnValues(fake_image)) as issue_command:
vm = vm_class(spec)
vm._Create()
vm.created = True
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn('gcloud compute instances create', command_string)
self.assertIn('--boot-disk-size 20', command_string)
self.assertIn('--boot-disk-type fake-disk-type', command_string)
vm._PostCreate()
self.assertEqual(issue_command.call_count, 2)
vm_metadata = vm.GetResourceMetadata()
self.assertDictContainsSubset({'image': fake_image,
'image_project': 'fake-project',
'boot_disk_size': 20,
'boot_disk_type': 'fake-disk-type'},
vm_metadata)
self.assertNotIn('image_family', vm_metadata)
def testCreateUbuntu1804(self):
vm_class = virtual_machine.GetVmClass(providers.GCP, os_types.UBUNTU1804)
fake_image = 'fake-ubuntu1804'
with PatchCriticalObjects(
self._CreateFakeReturnValues(fake_image)) as issue_command:
vm = vm_class(self.spec)
vm._Create()
vm.created = True
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn('gcloud compute instances create', command_string)
self.assertIn(
'--image-family ubuntu-1804-lts --image-project ubuntu-os-cloud',
command_string)
vm._PostCreate()
self.assertEqual(issue_command.call_count, 3)
self.assertDictContainsSubset({'image': fake_image,
'image_family': 'ubuntu-1804-lts',
'image_project': 'ubuntu-os-cloud'},
vm.GetResourceMetadata())
def testCreateRhel7CustomImage(self):
vm_class = virtual_machine.GetVmClass(providers.GCP, os_types.RHEL7)
fake_image = 'fake-custom-rhel-image'
spec = gce_virtual_machine.GceVmSpec(_COMPONENT,
machine_type='fake-machine-type',
image=fake_image)
with PatchCriticalObjects(
self._CreateFakeReturnValues(fake_image)) as issue_command:
vm = vm_class(spec)
vm._Create()
vm.created = True
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn('gcloud compute instances create', command_string)
self.assertIn('--image ' + fake_image, command_string)
self.assertIn('--image-project rhel-cloud', command_string)
vm._PostCreate()
self.assertEqual(issue_command.call_count, 3)
vm_metadata = vm.GetResourceMetadata()
self.assertDictContainsSubset({'image': fake_image,
'image_project': 'rhel-cloud'},
vm_metadata)
self.assertNotIn('image_family', vm_metadata)
def testCreateCentOs7CustomImage(self):
vm_class = virtual_machine.GetVmClass(providers.GCP, os_types.CENTOS7)
fake_image = 'fake-custom-centos7-image'
spec = gce_virtual_machine.GceVmSpec(_COMPONENT,
machine_type='fake-machine-type',
image=fake_image)
with PatchCriticalObjects(
self._CreateFakeReturnValues(fake_image)) as issue_command:
vm = vm_class(spec)
vm._Create()
vm.created = True
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn('gcloud compute instances create', command_string)
self.assertIn('--image ' + fake_image, command_string)
self.assertIn('--image-project centos-cloud', command_string)
vm._PostCreate()
self.assertEqual(issue_command.call_count, 3)
vm_metadata = vm.GetResourceMetadata()
self.assertDictContainsSubset({'image': fake_image,
'image_project': 'centos-cloud'},
vm_metadata)
self.assertNotIn('image_family', vm_metadata)
class GCEVMFlagsTestCase(pkb_common_test_case.PkbCommonTestCase):
def setUp(self):
super(GCEVMFlagsTestCase, self).setUp()
FLAGS.cloud = providers.GCP
FLAGS.gcloud_path = 'test_gcloud'
FLAGS.run_uri = 'aaaaaa'
FLAGS.gcp_instance_metadata = []
FLAGS.gcp_instance_metadata_from_file = []
# Creating a VM object causes network objects to be added to the current
# thread's benchmark spec. Create such a benchmark spec for these tests.
self.addCleanup(context.SetThreadBenchmarkSpec, None)
config_spec = benchmark_config_spec.BenchmarkConfigSpec(
_BENCHMARK_NAME, flag_values=FLAGS, vm_groups={})
self._benchmark_spec = benchmark_spec.BenchmarkSpec(
mock.MagicMock(), config_spec, _BENCHMARK_UID)
get_tmp_dir_mock = mock.patch(
vm_util.__name__ + '.GetTempDir', return_value='TempDir')
get_tmp_dir_mock.start()
self.addCleanup(get_tmp_dir_mock.stop)
def _CreateVmCommand(self, **flag_kwargs):
with PatchCriticalObjects() as issue_command:
for key, value in flag_kwargs.items():
FLAGS[key].parse(value)
vm_spec = gce_virtual_machine.GceVmSpec(
'test_vm_spec.GCP',
FLAGS,
image='image',
machine_type='test_machine_type')
vm = pkb_common_test_case.TestGceVirtualMachine(vm_spec)
vm._Create()
return ' '.join(issue_command.call_args[0][0]), issue_command.call_count
def testPreemptibleVMFlag(self):
cmd, call_count = self._CreateVmCommand(gce_preemptible_vms=True)
self.assertEqual(call_count, 1)
self.assertIn('--preemptible', cmd)
def testMigrateOnMaintenanceFlagTrueWithGpus(self):
with self.assertRaises(errors.Config.InvalidValue) as cm:
self._CreateVmCommand(
gce_migrate_on_maintenance=True, gpu_count=1, gpu_type='k80')
self.assertEqual(str(cm.exception), (
'Cannot set flag gce_migrate_on_maintenance on '
'instances with GPUs, as it is not supported by GCP.'))
def testMigrateOnMaintenanceFlagFalseWithGpus(self):
_, call_count = self._CreateVmCommand(
gce_migrate_on_maintenance=False, gpu_count=1, gpu_type='k80')
self.assertEqual(call_count, 1)
def testAcceleratorTypeOverrideFlag(self):
cmd, call_count = self._CreateVmCommand(
gce_accelerator_type_override='fake_type', gpu_count=1, gpu_type='k80')
self.assertEqual(call_count, 1)
self.assertIn('--accelerator', cmd)
self.assertIn('type=fake_type,count=1', cmd)
def testImageProjectFlag(self):
"""Tests that custom image_project flag is supported."""
cmd, call_count = self._CreateVmCommand(image_project='bar')
self.assertEqual(call_count, 1)
self.assertIn('--image-project bar', cmd)
def testNetworkTierFlagPremium(self):
"""Tests that the premium network tier flag is supported."""
cmd, call_count = self._CreateVmCommand(gce_network_tier='premium')
self.assertEqual(call_count, 1)
self.assertIn('--network-tier PREMIUM', cmd)
def testNetworkTierFlagStandard(self):
"""Tests that the standard network tier flag is supported."""
cmd, call_count = self._CreateVmCommand(gce_network_tier='standard')
self.assertEqual(call_count, 1)
self.assertIn('--network-tier STANDARD', cmd)
def testGcpInstanceMetadataFlag(self):
cmd, call_count = self._CreateVmCommand(
gcp_instance_metadata=['k1:v1', 'k2:v2,k3:v3'], owner='test-owner')
self.assertEqual(call_count, 1)
actual_metadata = re.compile(
r'--metadata\s+(.*)(\s+--)?').search(cmd).group(1)
self.assertIn('k1=v1', actual_metadata)
self.assertIn('k2=v2', actual_metadata)
self.assertIn('k3=v3', actual_metadata)
# Assert that FLAGS.owner is honored and added to instance metadata.
self.assertIn('owner=test-owner', actual_metadata)
def testGcpInstanceMetadataFromFileFlag(self):
cmd, call_count = self._CreateVmCommand(
gcp_instance_metadata_from_file=['k1:p1', 'k2:p2,k3:p3'])
self.assertEqual(call_count, 1)
actual_metadata_from_file = re.compile(
r'--metadata-from-file\s+(.*)(\s+--)?').search(cmd).group(1)
self.assertIn('k1=p1', actual_metadata_from_file)
self.assertIn('k2=p2', actual_metadata_from_file)
self.assertIn('k3=p3', actual_metadata_from_file)
def testGceTags(self):
self.assertIn('--tags perfkitbenchmarker', self._CreateVmCommand()[0])
self.assertIn('--tags perfkitbenchmarker,testtag',
self._CreateVmCommand(gce_tags=['testtag'])[0])
def testShieldedSecureBootFlag(self):
"""Tests that the custom shielded secure boot flag is supported."""
cmd, call_count = self._CreateVmCommand(
gce_shielded_secure_boot=True)
self.assertEqual(call_count, 1)
self.assertIn('--shielded-secure-boot', cmd)
class GCEVMCreateTestCase(pkb_common_test_case.PkbCommonTestCase):
def setUp(self):
super(GCEVMCreateTestCase, self).setUp()
p = mock.patch(gce_virtual_machine.__name__ +
'.gce_network.GceNetwork.GetNetwork')
self.mock_get_network = p.start()
self.addCleanup(p.stop)
p = mock.patch(gce_virtual_machine.__name__ +
'.gce_network.GceFirewall.GetFirewall')
self.mock_get_firewall = p.start()
self.addCleanup(p.stop)
get_tmp_dir_mock = mock.patch(
vm_util.__name__ + '.GetTempDir', return_value='TempDir')
get_tmp_dir_mock.start()
self.addCleanup(get_tmp_dir_mock.stop)
@mock.patch('time.sleep', side_effect=lambda _: None)
def testCreateRateLimitedMachineCreated(self, mock_cmd):
fake_rets = [('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'The resource already exists', 1)]
with PatchCriticalObjects(fake_rets) as issue_command:
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT, machine_type={
'cpus': 1,
'memory': '1.0GiB',
})
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
vm._Create() # No error should be thrown.
self.assertEqual(issue_command.call_count, 5)
@mock.patch('time.sleep', side_effect=lambda _: None)
def testCreateRateLimitedMachineCreatedFailure(self, mock_cmd):
fake_rets = []
for _ in range(0, 100):
fake_rets.append(('stdout', 'Rate Limit Exceeded', 1))
with PatchCriticalObjects(fake_rets) as issue_command:
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT, machine_type={
'cpus': 1,
'memory': '1.0GiB',
})
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
with self.assertRaises(
errors.Benchmarks.QuotaFailure.RateLimitExceededError):
vm._Create()
self.assertEqual(issue_command.call_count,
util.RATE_LIMITED_MAX_RETRIES + 1)
def testCreateVMAlreadyExists(self):
fake_rets = [('stdout', 'The resource already exists', 1)]
with PatchCriticalObjects(fake_rets):
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT, machine_type={
'cpus': 1,
'memory': '1.0GiB',
})
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
with self.assertRaises(errors.Resource.CreationError):
vm._Create()
def testVmWithoutGpu(self):
with PatchCriticalObjects() as issue_command:
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT, machine_type={
'cpus': 1,
'memory': '1.0GiB',
})
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
vm._Create()
self.assertEqual(issue_command.call_count, 1)
self.assertNotIn('--accelerator', issue_command.call_args[0][0])
def testVmWithGpu(self):
with PatchCriticalObjects() as issue_command:
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT,
machine_type='n1-standard-8',
gpu_count=2,
gpu_type='k80')
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
vm._Create()
self.assertEqual(issue_command.call_count, 1)
self.assertIn('--accelerator', issue_command.call_args[0][0])
self.assertIn('type=nvidia-tesla-k80,count=2',
issue_command.call_args[0][0])
self.assertIn('--maintenance-policy', issue_command.call_args[0][0])
self.assertIn('TERMINATE', issue_command.call_args[0][0])
class GceFirewallRuleTest(pkb_common_test_case.PkbCommonTestCase):
@mock.patch('time.sleep', side_effect=lambda _: None)
def testGceFirewallRuleSuccessfulAfterRateLimited(self, mock_cmd):
fake_rets = [('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'some warning perhaps', 0)]
with PatchCriticalObjects(fake_rets) as issue_command:
fr = gce_network.GceFirewallRule('name', 'project', 'allow',
'network_name')
fr._Create()
self.assertEqual(issue_command.call_count, 2)
@mock.patch('time.sleep', side_effect=lambda _: None)
def testGceFirewallRuleGenericErrorAfterRateLimited(self, mock_cmd):
fake_rets = [('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'some random firewall error', 1)]
with PatchCriticalObjects(fake_rets) as issue_command:
with self.assertRaises(errors.VmUtil.IssueCommandError):
fr = gce_network.GceFirewallRule('name', 'project', 'allow',
'network_name')
fr._Create()
self.assertEqual(issue_command.call_count, 3)
@mock.patch('time.sleep', side_effect=lambda _: None)
def testGceFirewallRuleAlreadyExistsAfterRateLimited(self, mock_cmd):
fake_rets = [('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'firewall already exists', 1)]
with PatchCriticalObjects(fake_rets) as issue_command:
fr = gce_network.GceFirewallRule('name', 'project', 'allow',
'network_name')
fr._Create()
self.assertEqual(issue_command.call_count, 3)
@mock.patch('time.sleep', side_effect=lambda _: None)
def testGceFirewallRuleGenericError(self, mock_cmd):
fake_rets = [('stdout', 'some random firewall error', 1)]
with PatchCriticalObjects(fake_rets) as issue_command:
with self.assertRaises(errors.VmUtil.IssueCommandError):
fr = gce_network.GceFirewallRule('name', 'project', 'allow',
'network_name')
fr._Create()
self.assertEqual(issue_command.call_count, 1)
class GceNetworkTest(pkb_common_test_case.PkbCommonTestCase):
def setUp(self):
super(GceNetworkTest, self).setUp()
# need a benchmarkspec in the context to run
config_spec = benchmark_config_spec.BenchmarkConfigSpec(
'cluster_boot', flag_values=FLAGS)
benchmark_spec.BenchmarkSpec(mock.Mock(), config_spec, 'uid')
def testGetNetwork(self):
project = 'myproject'
zone = 'us-east1-a'
vm = mock.Mock(zone=zone, project=project, cidr=None)
net = gce_network.GceNetwork.GetNetwork(vm)
self.assertEqual(project, net.project)
self.assertEqual(zone, net.zone)
if __name__ == '__main__':
unittest.main()
| 40.422695 | 80 | 0.65573 |
import contextlib
import copy
import json
import re
import unittest
from absl import flags
import builtins
import mock
from perfkitbenchmarker import benchmark_spec
from perfkitbenchmarker import context
from perfkitbenchmarker import errors
from perfkitbenchmarker import os_types
from perfkitbenchmarker import providers
from perfkitbenchmarker import virtual_machine
from perfkitbenchmarker import vm_util
from perfkitbenchmarker.configs import benchmark_config_spec
from perfkitbenchmarker.providers.gcp import gce_network
from perfkitbenchmarker.providers.gcp import gce_virtual_machine
from perfkitbenchmarker.providers.gcp import util
from tests import pkb_common_test_case
FLAGS = flags.FLAGS
_BENCHMARK_NAME = 'name'
_BENCHMARK_UID = 'benchmark_uid'
_COMPONENT = 'test_component'
_FLAGS = None
_FAKE_INSTANCE_METADATA = {
'id': '123456',
'networkInterfaces': [
{
'accessConfigs': [
{
'natIP': '1.2.3.4'
}
],
'networkIP': '1.2.3.4'
}
]
}
_FAKE_DISK_METADATA = {
'id': '123456',
'kind': 'compute#disk',
'name': 'fakedisk',
'sizeGb': '10',
'sourceImage': '',
'type': 'pd-standard'
}
@contextlib.contextmanager
def PatchCriticalObjects(retvals=None):
def ReturnVal(*unused_arg, **unused_kwargs):
del unused_arg
del unused_kwargs
return ('', '', 0) if retvals is None else retvals.pop(0)
with mock.patch(
vm_util.__name__ + '.IssueCommand',
side_effect=ReturnVal) as issue_command, mock.patch(
builtins.__name__ + '.open'), mock.patch(
vm_util.__name__ +
'.NamedTemporaryFile'), mock.patch(util.__name__ +
'.GetDefaultProject'):
yield issue_command
class GceVmSpecTestCase(pkb_common_test_case.PkbCommonTestCase):
def testStringMachineType(self):
result = gce_virtual_machine.GceVmSpec(_COMPONENT,
machine_type='n1-standard-8')
self.assertEqual(result.machine_type, 'n1-standard-8')
self.assertEqual(result.cpus, None)
self.assertEqual(result.memory, None)
def testStringMachineTypeWithGpus(self):
gpu_count = 2
gpu_type = 'k80'
result = gce_virtual_machine.GceVmSpec(_COMPONENT,
machine_type='n1-standard-8',
gpu_count=gpu_count,
gpu_type=gpu_type)
self.assertEqual(result.machine_type, 'n1-standard-8')
self.assertEqual(result.gpu_type, 'k80')
self.assertEqual(result.gpu_count, 2)
def testCustomMachineType(self):
result = gce_virtual_machine.GceVmSpec(_COMPONENT, machine_type={
'cpus': 1, 'memory': '7.5GiB'})
self.assertEqual(result.machine_type, None)
self.assertEqual(result.cpus, 1)
self.assertEqual(result.memory, 7680)
def testCustomMachineTypeWithGpus(self):
gpu_count = 2
gpu_type = 'k80'
result = gce_virtual_machine.GceVmSpec(_COMPONENT,
machine_type={
'cpus': 1,
'memory': '7.5GiB'
},
gpu_count=gpu_count,
gpu_type=gpu_type)
self.assertEqual(result.cpus, 1)
self.assertEqual(result.memory, 7680)
self.assertEqual(result.gpu_type, 'k80')
self.assertEqual(result.gpu_count, 2)
def testStringMachineTypeFlagOverride(self):
FLAGS['machine_type'].parse('n1-standard-8')
result = gce_virtual_machine.GceVmSpec(
_COMPONENT,
flag_values=FLAGS,
machine_type={
'cpus': 1,
'memory': '7.5GiB'
})
self.assertEqual(result.machine_type, 'n1-standard-8')
self.assertEqual(result.cpus, None)
self.assertEqual(result.memory, None)
def testCustomMachineTypeFlagOverride(self):
FLAGS['machine_type'].parse('{cpus: 1, memory: 7.5GiB}')
result = gce_virtual_machine.GceVmSpec(
_COMPONENT, flag_values=FLAGS, machine_type='n1-standard-8')
self.assertEqual(result.machine_type, None)
self.assertEqual(result.cpus, 1)
self.assertEqual(result.memory, 7680)
class GceVirtualMachineTestCase(pkb_common_test_case.PkbCommonTestCase):
def setUp(self):
super(GceVirtualMachineTestCase, self).setUp()
p = mock.patch(gce_virtual_machine.__name__ +
'.gce_network.GceNetwork.GetNetwork')
self.mock_get_network = p.start()
self.addCleanup(p.stop)
p = mock.patch(gce_virtual_machine.__name__ +
'.gce_network.GceFirewall.GetFirewall')
self.mock_get_firewall = p.start()
self.addCleanup(p.stop)
get_tmp_dir_mock = mock.patch(
vm_util.__name__ + '.GetTempDir', return_value='TempDir')
get_tmp_dir_mock.start()
self.addCleanup(get_tmp_dir_mock.stop)
def testVmWithMachineTypeNonPreemptible(self):
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT, machine_type='test_machine_type', project='p')
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
vm.created = True
self.assertDictContainsSubset(
{'dedicated_host': False, 'machine_type': 'test_machine_type',
'project': 'p'},
vm.GetResourceMetadata()
)
def testVmWithMachineTypePreemptible(self):
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT, machine_type='test_machine_type', preemptible=True,
project='p')
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
vm.created = True
self.assertDictContainsSubset(
{'dedicated_host': False, 'machine_type': 'test_machine_type',
'preemptible': True, 'project': 'p'},
vm.GetResourceMetadata()
)
def testCustomVmNonPreemptible(self):
spec = gce_virtual_machine.GceVmSpec(_COMPONENT, machine_type={
'cpus': 1, 'memory': '1.0GiB'}, project='p')
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
vm.created = True
self.assertDictContainsSubset(
{'cpus': 1, 'memory_mib': 1024, 'project': 'p',
'dedicated_host': False},
vm.GetResourceMetadata())
def testCustomVmPreemptible(self):
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT, machine_type={'cpus': 1, 'memory': '1.0GiB'},
preemptible=True,
project='fakeproject')
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
vm.created = True
self.assertDictContainsSubset({
'cpus': 1, 'memory_mib': 1024, 'project': 'fakeproject',
'dedicated_host': False, 'preemptible': True}, vm.GetResourceMetadata())
def testCustomVmWithGpus(self):
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT,
machine_type={'cpus': 1, 'memory': '1.0GiB'},
gpu_count=2,
gpu_type='k80',
project='fakeproject')
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
vm.created = True
self.assertDictContainsSubset({
'cpus': 1, 'memory_mib': 1024, 'project': 'fakeproject',
'dedicated_host': False, 'gpu_count': 2, 'gpu_type': 'k80'
}, vm.GetResourceMetadata())
def _CreateFakeDiskMetadata(image):
fake_disk = copy.copy(_FAKE_DISK_METADATA)
fake_disk['sourceImage'] = image
return fake_disk
class GceVirtualMachineOsTypesTestCase(pkb_common_test_case.PkbCommonTestCase):
def setUp(self):
super(GceVirtualMachineOsTypesTestCase, self).setUp()
FLAGS.gcp_instance_metadata_from_file = ''
FLAGS.gcp_instance_metadata = ''
FLAGS.gcloud_path = 'gcloud'
p = mock.patch(gce_virtual_machine.__name__ +
'.gce_network.GceNetwork.GetNetwork')
self.mock_get_network = p.start()
self.addCleanup(p.stop)
p = mock.patch(gce_virtual_machine.__name__ +
'.gce_network.GceFirewall.GetFirewall')
self.mock_get_firewall = p.start()
self.addCleanup(p.stop)
self.spec = gce_virtual_machine.GceVmSpec(_COMPONENT,
machine_type='fake-machine-type')
p = mock.patch(gce_virtual_machine.__name__ +
'.linux_vm.BaseLinuxMixin._GetNumCpus')
self.mock_get_num_cpus = p.start()
self.addCleanup(p.stop)
get_tmp_dir_mock = mock.patch(
vm_util.__name__ + '.GetTempDir', return_value='TempDir')
get_tmp_dir_mock.start()
self.addCleanup(get_tmp_dir_mock.stop)
def _CreateFakeReturnValues(self, fake_image=''):
fake_rets = [('', '', 0), (json.dumps(_FAKE_INSTANCE_METADATA), '', 0)]
if fake_image:
fake_rets.append((json.dumps(_CreateFakeDiskMetadata(fake_image)), '', 0))
return fake_rets
def testCreateUbuntu1604(self):
vm_class = virtual_machine.GetVmClass(providers.GCP, os_types.UBUNTU1604)
fake_image = 'fake-ubuntu1604'
with PatchCriticalObjects(
self._CreateFakeReturnValues(fake_image)) as issue_command:
vm = vm_class(self.spec)
vm._Create()
vm.created = True
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn('gcloud compute instances create', command_string)
self.assertIn(
'--image-family ubuntu-1604-lts --image-project ubuntu-os-cloud',
command_string)
self.assertNotIn('--boot-disk-size', command_string)
self.assertNotIn('--boot-disk-type', command_string)
vm._PostCreate()
self.assertEqual(issue_command.call_count, 3)
self.assertDictContainsSubset({'image': fake_image,
'image_family': 'ubuntu-1604-lts',
'image_project': 'ubuntu-os-cloud',
'boot_disk_size': '10',
'boot_disk_type': 'pd-standard'},
vm.GetResourceMetadata())
def testCreateUbuntuInCustomProject(self):
vm_class = virtual_machine.GetVmClass(providers.GCP, os_types.UBUNTU1604)
fake_image = 'fake-ubuntu1604'
fake_image_project = 'fake-project'
spec = gce_virtual_machine.GceVmSpec(_COMPONENT,
machine_type='fake-machine-type',
image=fake_image,
image_project=fake_image_project)
with PatchCriticalObjects(
self._CreateFakeReturnValues(fake_image)) as issue_command:
vm = vm_class(spec)
vm._Create()
vm.created = True
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn('gcloud compute instances create', command_string)
self.assertIn(
'--image fake-ubuntu1604 --image-project fake-project',
command_string)
self.assertNotIn('--image-family', command_string)
vm._PostCreate()
self.assertEqual(issue_command.call_count, 3)
vm_metadata = vm.GetResourceMetadata()
self.assertDictContainsSubset({'image': fake_image,
'image_project': 'fake-project'},
vm_metadata)
self.assertNotIn('image_family', vm_metadata)
def testCreateUbuntuInCustomDisk(self):
vm_class = virtual_machine.GetVmClass(providers.GCP, os_types.UBUNTU1604)
fake_image = 'fake-ubuntu1604'
fake_image_project = 'fake-project'
spec = gce_virtual_machine.GceVmSpec(_COMPONENT,
machine_type='fake-machine-type',
image=fake_image,
image_project=fake_image_project,
boot_disk_size=20,
boot_disk_type='fake-disk-type')
with PatchCriticalObjects(
self._CreateFakeReturnValues(fake_image)) as issue_command:
vm = vm_class(spec)
vm._Create()
vm.created = True
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn('gcloud compute instances create', command_string)
self.assertIn('--boot-disk-size 20', command_string)
self.assertIn('--boot-disk-type fake-disk-type', command_string)
vm._PostCreate()
self.assertEqual(issue_command.call_count, 2)
vm_metadata = vm.GetResourceMetadata()
self.assertDictContainsSubset({'image': fake_image,
'image_project': 'fake-project',
'boot_disk_size': 20,
'boot_disk_type': 'fake-disk-type'},
vm_metadata)
self.assertNotIn('image_family', vm_metadata)
def testCreateUbuntu1804(self):
vm_class = virtual_machine.GetVmClass(providers.GCP, os_types.UBUNTU1804)
fake_image = 'fake-ubuntu1804'
with PatchCriticalObjects(
self._CreateFakeReturnValues(fake_image)) as issue_command:
vm = vm_class(self.spec)
vm._Create()
vm.created = True
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn('gcloud compute instances create', command_string)
self.assertIn(
'--image-family ubuntu-1804-lts --image-project ubuntu-os-cloud',
command_string)
vm._PostCreate()
self.assertEqual(issue_command.call_count, 3)
self.assertDictContainsSubset({'image': fake_image,
'image_family': 'ubuntu-1804-lts',
'image_project': 'ubuntu-os-cloud'},
vm.GetResourceMetadata())
def testCreateRhel7CustomImage(self):
vm_class = virtual_machine.GetVmClass(providers.GCP, os_types.RHEL7)
fake_image = 'fake-custom-rhel-image'
spec = gce_virtual_machine.GceVmSpec(_COMPONENT,
machine_type='fake-machine-type',
image=fake_image)
with PatchCriticalObjects(
self._CreateFakeReturnValues(fake_image)) as issue_command:
vm = vm_class(spec)
vm._Create()
vm.created = True
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn('gcloud compute instances create', command_string)
self.assertIn('--image ' + fake_image, command_string)
self.assertIn('--image-project rhel-cloud', command_string)
vm._PostCreate()
self.assertEqual(issue_command.call_count, 3)
vm_metadata = vm.GetResourceMetadata()
self.assertDictContainsSubset({'image': fake_image,
'image_project': 'rhel-cloud'},
vm_metadata)
self.assertNotIn('image_family', vm_metadata)
def testCreateCentOs7CustomImage(self):
vm_class = virtual_machine.GetVmClass(providers.GCP, os_types.CENTOS7)
fake_image = 'fake-custom-centos7-image'
spec = gce_virtual_machine.GceVmSpec(_COMPONENT,
machine_type='fake-machine-type',
image=fake_image)
with PatchCriticalObjects(
self._CreateFakeReturnValues(fake_image)) as issue_command:
vm = vm_class(spec)
vm._Create()
vm.created = True
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn('gcloud compute instances create', command_string)
self.assertIn('--image ' + fake_image, command_string)
self.assertIn('--image-project centos-cloud', command_string)
vm._PostCreate()
self.assertEqual(issue_command.call_count, 3)
vm_metadata = vm.GetResourceMetadata()
self.assertDictContainsSubset({'image': fake_image,
'image_project': 'centos-cloud'},
vm_metadata)
self.assertNotIn('image_family', vm_metadata)
class GCEVMFlagsTestCase(pkb_common_test_case.PkbCommonTestCase):
def setUp(self):
super(GCEVMFlagsTestCase, self).setUp()
FLAGS.cloud = providers.GCP
FLAGS.gcloud_path = 'test_gcloud'
FLAGS.run_uri = 'aaaaaa'
FLAGS.gcp_instance_metadata = []
FLAGS.gcp_instance_metadata_from_file = []
self.addCleanup(context.SetThreadBenchmarkSpec, None)
config_spec = benchmark_config_spec.BenchmarkConfigSpec(
_BENCHMARK_NAME, flag_values=FLAGS, vm_groups={})
self._benchmark_spec = benchmark_spec.BenchmarkSpec(
mock.MagicMock(), config_spec, _BENCHMARK_UID)
get_tmp_dir_mock = mock.patch(
vm_util.__name__ + '.GetTempDir', return_value='TempDir')
get_tmp_dir_mock.start()
self.addCleanup(get_tmp_dir_mock.stop)
def _CreateVmCommand(self, **flag_kwargs):
with PatchCriticalObjects() as issue_command:
for key, value in flag_kwargs.items():
FLAGS[key].parse(value)
vm_spec = gce_virtual_machine.GceVmSpec(
'test_vm_spec.GCP',
FLAGS,
image='image',
machine_type='test_machine_type')
vm = pkb_common_test_case.TestGceVirtualMachine(vm_spec)
vm._Create()
return ' '.join(issue_command.call_args[0][0]), issue_command.call_count
def testPreemptibleVMFlag(self):
cmd, call_count = self._CreateVmCommand(gce_preemptible_vms=True)
self.assertEqual(call_count, 1)
self.assertIn('--preemptible', cmd)
def testMigrateOnMaintenanceFlagTrueWithGpus(self):
with self.assertRaises(errors.Config.InvalidValue) as cm:
self._CreateVmCommand(
gce_migrate_on_maintenance=True, gpu_count=1, gpu_type='k80')
self.assertEqual(str(cm.exception), (
'Cannot set flag gce_migrate_on_maintenance on '
'instances with GPUs, as it is not supported by GCP.'))
def testMigrateOnMaintenanceFlagFalseWithGpus(self):
_, call_count = self._CreateVmCommand(
gce_migrate_on_maintenance=False, gpu_count=1, gpu_type='k80')
self.assertEqual(call_count, 1)
def testAcceleratorTypeOverrideFlag(self):
cmd, call_count = self._CreateVmCommand(
gce_accelerator_type_override='fake_type', gpu_count=1, gpu_type='k80')
self.assertEqual(call_count, 1)
self.assertIn('--accelerator', cmd)
self.assertIn('type=fake_type,count=1', cmd)
def testImageProjectFlag(self):
cmd, call_count = self._CreateVmCommand(image_project='bar')
self.assertEqual(call_count, 1)
self.assertIn('--image-project bar', cmd)
def testNetworkTierFlagPremium(self):
cmd, call_count = self._CreateVmCommand(gce_network_tier='premium')
self.assertEqual(call_count, 1)
self.assertIn('--network-tier PREMIUM', cmd)
def testNetworkTierFlagStandard(self):
cmd, call_count = self._CreateVmCommand(gce_network_tier='standard')
self.assertEqual(call_count, 1)
self.assertIn('--network-tier STANDARD', cmd)
def testGcpInstanceMetadataFlag(self):
cmd, call_count = self._CreateVmCommand(
gcp_instance_metadata=['k1:v1', 'k2:v2,k3:v3'], owner='test-owner')
self.assertEqual(call_count, 1)
actual_metadata = re.compile(
r'--metadata\s+(.*)(\s+--)?').search(cmd).group(1)
self.assertIn('k1=v1', actual_metadata)
self.assertIn('k2=v2', actual_metadata)
self.assertIn('k3=v3', actual_metadata)
# Assert that FLAGS.owner is honored and added to instance metadata.
self.assertIn('owner=test-owner', actual_metadata)
def testGcpInstanceMetadataFromFileFlag(self):
cmd, call_count = self._CreateVmCommand(
gcp_instance_metadata_from_file=['k1:p1', 'k2:p2,k3:p3'])
self.assertEqual(call_count, 1)
actual_metadata_from_file = re.compile(
r'--metadata-from-file\s+(.*)(\s+--)?').search(cmd).group(1)
self.assertIn('k1=p1', actual_metadata_from_file)
self.assertIn('k2=p2', actual_metadata_from_file)
self.assertIn('k3=p3', actual_metadata_from_file)
def testGceTags(self):
self.assertIn('--tags perfkitbenchmarker', self._CreateVmCommand()[0])
self.assertIn('--tags perfkitbenchmarker,testtag',
self._CreateVmCommand(gce_tags=['testtag'])[0])
def testShieldedSecureBootFlag(self):
cmd, call_count = self._CreateVmCommand(
gce_shielded_secure_boot=True)
self.assertEqual(call_count, 1)
self.assertIn('--shielded-secure-boot', cmd)
class GCEVMCreateTestCase(pkb_common_test_case.PkbCommonTestCase):
def setUp(self):
super(GCEVMCreateTestCase, self).setUp()
p = mock.patch(gce_virtual_machine.__name__ +
'.gce_network.GceNetwork.GetNetwork')
self.mock_get_network = p.start()
self.addCleanup(p.stop)
p = mock.patch(gce_virtual_machine.__name__ +
'.gce_network.GceFirewall.GetFirewall')
self.mock_get_firewall = p.start()
self.addCleanup(p.stop)
get_tmp_dir_mock = mock.patch(
vm_util.__name__ + '.GetTempDir', return_value='TempDir')
get_tmp_dir_mock.start()
self.addCleanup(get_tmp_dir_mock.stop)
@mock.patch('time.sleep', side_effect=lambda _: None)
def testCreateRateLimitedMachineCreated(self, mock_cmd):
fake_rets = [('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'The resource already exists', 1)]
with PatchCriticalObjects(fake_rets) as issue_command:
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT, machine_type={
'cpus': 1,
'memory': '1.0GiB',
})
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
vm._Create() # No error should be thrown.
self.assertEqual(issue_command.call_count, 5)
@mock.patch('time.sleep', side_effect=lambda _: None)
def testCreateRateLimitedMachineCreatedFailure(self, mock_cmd):
fake_rets = []
for _ in range(0, 100):
fake_rets.append(('stdout', 'Rate Limit Exceeded', 1))
with PatchCriticalObjects(fake_rets) as issue_command:
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT, machine_type={
'cpus': 1,
'memory': '1.0GiB',
})
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
with self.assertRaises(
errors.Benchmarks.QuotaFailure.RateLimitExceededError):
vm._Create()
self.assertEqual(issue_command.call_count,
util.RATE_LIMITED_MAX_RETRIES + 1)
def testCreateVMAlreadyExists(self):
fake_rets = [('stdout', 'The resource already exists', 1)]
with PatchCriticalObjects(fake_rets):
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT, machine_type={
'cpus': 1,
'memory': '1.0GiB',
})
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
with self.assertRaises(errors.Resource.CreationError):
vm._Create()
def testVmWithoutGpu(self):
with PatchCriticalObjects() as issue_command:
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT, machine_type={
'cpus': 1,
'memory': '1.0GiB',
})
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
vm._Create()
self.assertEqual(issue_command.call_count, 1)
self.assertNotIn('--accelerator', issue_command.call_args[0][0])
def testVmWithGpu(self):
with PatchCriticalObjects() as issue_command:
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT,
machine_type='n1-standard-8',
gpu_count=2,
gpu_type='k80')
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
vm._Create()
self.assertEqual(issue_command.call_count, 1)
self.assertIn('--accelerator', issue_command.call_args[0][0])
self.assertIn('type=nvidia-tesla-k80,count=2',
issue_command.call_args[0][0])
self.assertIn('--maintenance-policy', issue_command.call_args[0][0])
self.assertIn('TERMINATE', issue_command.call_args[0][0])
class GceFirewallRuleTest(pkb_common_test_case.PkbCommonTestCase):
@mock.patch('time.sleep', side_effect=lambda _: None)
def testGceFirewallRuleSuccessfulAfterRateLimited(self, mock_cmd):
fake_rets = [('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'some warning perhaps', 0)]
with PatchCriticalObjects(fake_rets) as issue_command:
fr = gce_network.GceFirewallRule('name', 'project', 'allow',
'network_name')
fr._Create()
self.assertEqual(issue_command.call_count, 2)
@mock.patch('time.sleep', side_effect=lambda _: None)
def testGceFirewallRuleGenericErrorAfterRateLimited(self, mock_cmd):
fake_rets = [('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'some random firewall error', 1)]
with PatchCriticalObjects(fake_rets) as issue_command:
with self.assertRaises(errors.VmUtil.IssueCommandError):
fr = gce_network.GceFirewallRule('name', 'project', 'allow',
'network_name')
fr._Create()
self.assertEqual(issue_command.call_count, 3)
@mock.patch('time.sleep', side_effect=lambda _: None)
def testGceFirewallRuleAlreadyExistsAfterRateLimited(self, mock_cmd):
fake_rets = [('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'firewall already exists', 1)]
with PatchCriticalObjects(fake_rets) as issue_command:
fr = gce_network.GceFirewallRule('name', 'project', 'allow',
'network_name')
fr._Create()
self.assertEqual(issue_command.call_count, 3)
@mock.patch('time.sleep', side_effect=lambda _: None)
def testGceFirewallRuleGenericError(self, mock_cmd):
fake_rets = [('stdout', 'some random firewall error', 1)]
with PatchCriticalObjects(fake_rets) as issue_command:
with self.assertRaises(errors.VmUtil.IssueCommandError):
fr = gce_network.GceFirewallRule('name', 'project', 'allow',
'network_name')
fr._Create()
self.assertEqual(issue_command.call_count, 1)
class GceNetworkTest(pkb_common_test_case.PkbCommonTestCase):
def setUp(self):
super(GceNetworkTest, self).setUp()
# need a benchmarkspec in the context to run
config_spec = benchmark_config_spec.BenchmarkConfigSpec(
'cluster_boot', flag_values=FLAGS)
benchmark_spec.BenchmarkSpec(mock.Mock(), config_spec, 'uid')
def testGetNetwork(self):
project = 'myproject'
zone = 'us-east1-a'
vm = mock.Mock(zone=zone, project=project, cidr=None)
net = gce_network.GceNetwork.GetNetwork(vm)
self.assertEqual(project, net.project)
self.assertEqual(zone, net.zone)
if __name__ == '__main__':
unittest.main()
| true | true |
f72b8e84fb1e9a3b3bd3404c7c3d64a53cc6b63f | 4,233 | py | Python | Chapter 05/enc_dec/model.py | bpbpublications/Time-Series-Forecasting-using-Deep-Learning | fd84553d33e912edb4a1400af0f9374e72747457 | [
"MIT"
] | 7 | 2021-12-13T20:00:05.000Z | 2022-03-11T08:44:43.000Z | Chapter 05/enc_dec/model.py | bpbpublications/Time-Series-Forecasting-using-Deep-Learning | fd84553d33e912edb4a1400af0f9374e72747457 | [
"MIT"
] | 1 | 2022-02-22T10:39:12.000Z | 2022-02-22T10:39:12.000Z | Chapter 05/enc_dec/model.py | bpbpublications/Time-Series-Forecasting-using-Deep-Learning | fd84553d33e912edb4a1400af0f9374e72747457 | [
"MIT"
] | null | null | null | import numpy as np
import random
import torch
import torch.nn as nn
from torch import optim
class Encoder(nn.Module):
def __init__(self, input_size, hidden_size, num_layers = 1):
super(Encoder, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.num_layers = num_layers
self.lstm = nn.LSTM(input_size = input_size, hidden_size = hidden_size, num_layers = num_layers)
def forward(self, x):
flat = x.view(x.shape[0], x.shape[1], self.input_size)
out, h = self.lstm(flat)
return out, h
class Decoder(nn.Module):
def __init__(self, input_size, hidden_size, output_size = 1, num_layers = 1):
super(Decoder, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.num_layers = num_layers
self.output_size = output_size
self.lstm = nn.LSTM(input_size = input_size, hidden_size = hidden_size, num_layers = num_layers)
self.linear = nn.Linear(hidden_size, output_size)
def forward(self, x, h):
out, h = self.lstm(x.unsqueeze(0), h)
y = self.linear(out.squeeze(0))
return y, h
class EncoderDecoder(nn.Module):
def __init__(self, hidden_size, input_size = 1, output_size = 1):
super(EncoderDecoder, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.encoder = Encoder(input_size = input_size, hidden_size = hidden_size)
self.decoder = Decoder(input_size = input_size, hidden_size = hidden_size, output_size = output_size)
def train_model(
self, train, target, epochs, target_len, method = 'recursive',
tfr = 0.5, lr = 0.01, dynamic_tf = False
):
losses = np.full(epochs, np.nan)
optimizer = optim.Adam(self.parameters(), lr = lr)
criterion = nn.MSELoss()
for e in range(epochs):
predicted = torch.zeros(target_len, train.shape[1], train.shape[2])
optimizer.zero_grad()
_, enc_h = self.encoder(train)
dec_in = train[-1, :, :]
dec_h = enc_h
if method == 'recursive':
for t in range(target_len):
dec_out, dec_h = self.decoder(dec_in, dec_h)
predicted[t] = dec_out
dec_in = dec_out
if method == 'teacher_forcing':
# use teacher forcing
if random.random() < tfr:
for t in range(target_len):
dec_out, dec_h = self.decoder(dec_in, dec_h)
predicted[t] = dec_out
dec_in = target[t, :, :]
# predict recursively
else:
for t in range(target_len):
dec_out, dec_h = self.decoder(dec_in, dec_h)
predicted[t] = dec_out
dec_in = dec_out
if method == 'mixed_teacher_forcing':
# predict using mixed teacher forcing
for t in range(target_len):
dec_out, dec_h = self.decoder(dec_in, dec_h)
predicted[t] = dec_out
# predict with teacher forcing
if random.random() < tfr:
dec_in = target[t, :, :]
# predict recursively
else:
dec_in = dec_out
loss = criterion(predicted, target)
loss.backward()
optimizer.step()
losses[e] = loss.item()
if e % 10 == 0:
print(f'Epoch {e}/{epochs}: {round(loss.item(), 4)}')
# dynamic teacher forcing
if dynamic_tf and tfr > 0:
tfr = tfr - 0.02
return losses
def predict(self, x, target_len):
y = torch.zeros(target_len, x.shape[1], x.shape[2])
_, enc_h = self.encoder(x)
dec_in = x[-1, :, :]
dec_h = enc_h
for t in range(target_len):
dec_out, dec_h = self.decoder(dec_in, dec_h)
y[t] = dec_out
dec_in = dec_out
return y
| 33.070313 | 109 | 0.541932 | import numpy as np
import random
import torch
import torch.nn as nn
from torch import optim
class Encoder(nn.Module):
def __init__(self, input_size, hidden_size, num_layers = 1):
super(Encoder, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.num_layers = num_layers
self.lstm = nn.LSTM(input_size = input_size, hidden_size = hidden_size, num_layers = num_layers)
def forward(self, x):
flat = x.view(x.shape[0], x.shape[1], self.input_size)
out, h = self.lstm(flat)
return out, h
class Decoder(nn.Module):
def __init__(self, input_size, hidden_size, output_size = 1, num_layers = 1):
super(Decoder, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.num_layers = num_layers
self.output_size = output_size
self.lstm = nn.LSTM(input_size = input_size, hidden_size = hidden_size, num_layers = num_layers)
self.linear = nn.Linear(hidden_size, output_size)
def forward(self, x, h):
out, h = self.lstm(x.unsqueeze(0), h)
y = self.linear(out.squeeze(0))
return y, h
class EncoderDecoder(nn.Module):
def __init__(self, hidden_size, input_size = 1, output_size = 1):
super(EncoderDecoder, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.encoder = Encoder(input_size = input_size, hidden_size = hidden_size)
self.decoder = Decoder(input_size = input_size, hidden_size = hidden_size, output_size = output_size)
def train_model(
self, train, target, epochs, target_len, method = 'recursive',
tfr = 0.5, lr = 0.01, dynamic_tf = False
):
losses = np.full(epochs, np.nan)
optimizer = optim.Adam(self.parameters(), lr = lr)
criterion = nn.MSELoss()
for e in range(epochs):
predicted = torch.zeros(target_len, train.shape[1], train.shape[2])
optimizer.zero_grad()
_, enc_h = self.encoder(train)
dec_in = train[-1, :, :]
dec_h = enc_h
if method == 'recursive':
for t in range(target_len):
dec_out, dec_h = self.decoder(dec_in, dec_h)
predicted[t] = dec_out
dec_in = dec_out
if method == 'teacher_forcing':
if random.random() < tfr:
for t in range(target_len):
dec_out, dec_h = self.decoder(dec_in, dec_h)
predicted[t] = dec_out
dec_in = target[t, :, :]
else:
for t in range(target_len):
dec_out, dec_h = self.decoder(dec_in, dec_h)
predicted[t] = dec_out
dec_in = dec_out
if method == 'mixed_teacher_forcing':
for t in range(target_len):
dec_out, dec_h = self.decoder(dec_in, dec_h)
predicted[t] = dec_out
if random.random() < tfr:
dec_in = target[t, :, :]
else:
dec_in = dec_out
loss = criterion(predicted, target)
loss.backward()
optimizer.step()
losses[e] = loss.item()
if e % 10 == 0:
print(f'Epoch {e}/{epochs}: {round(loss.item(), 4)}')
if dynamic_tf and tfr > 0:
tfr = tfr - 0.02
return losses
def predict(self, x, target_len):
y = torch.zeros(target_len, x.shape[1], x.shape[2])
_, enc_h = self.encoder(x)
dec_in = x[-1, :, :]
dec_h = enc_h
for t in range(target_len):
dec_out, dec_h = self.decoder(dec_in, dec_h)
y[t] = dec_out
dec_in = dec_out
return y
| true | true |
f72b917ba1bfdb505c6c57281ee679daa562ced3 | 4,564 | py | Python | galaxy/tools/deps/__init__.py | jmchilton/pulsar | 783b90cf0bce893a11c347fcaf6778b98e0bb062 | [
"Apache-2.0"
] | null | null | null | galaxy/tools/deps/__init__.py | jmchilton/pulsar | 783b90cf0bce893a11c347fcaf6778b98e0bb062 | [
"Apache-2.0"
] | 1 | 2015-02-21T18:48:19.000Z | 2015-02-27T15:50:32.000Z | galaxy/tools/deps/__init__.py | jmchilton/pulsar | 783b90cf0bce893a11c347fcaf6778b98e0bb062 | [
"Apache-2.0"
] | 3 | 2015-02-22T13:34:16.000Z | 2020-10-01T01:28:04.000Z | """
Dependency management for tools.
"""
import os.path
import logging
log = logging.getLogger( __name__ )
from .resolvers import INDETERMINATE_DEPENDENCY
from .resolvers.galaxy_packages import GalaxyPackageDependencyResolver
from .resolvers.tool_shed_packages import ToolShedPackageDependencyResolver
from galaxy.util import plugin_config
def build_dependency_manager( config ):
if getattr( config, "use_tool_dependencies", False ):
dependency_manager_kwds = {
'default_base_path': config.tool_dependency_dir,
'conf_file': config.dependency_resolvers_config_file,
}
dependency_manager = DependencyManager( **dependency_manager_kwds )
else:
dependency_manager = NullDependencyManager()
return dependency_manager
class NullDependencyManager( object ):
def uses_tool_shed_dependencies(self):
return False
def dependency_shell_commands( self, requirements, **kwds ):
return []
def find_dep( self, name, version=None, type='package', **kwds ):
return INDETERMINATE_DEPENDENCY
class DependencyManager( object ):
"""
A DependencyManager attempts to resolve named and versioned dependencies by
searching for them under a list of directories. Directories should be
of the form:
$BASE/name/version/...
and should each contain a file 'env.sh' which can be sourced to make the
dependency available in the current shell environment.
"""
def __init__( self, default_base_path, conf_file=None ):
"""
Create a new dependency manager looking for packages under the paths listed
in `base_paths`. The default base path is app.config.tool_dependency_dir.
"""
if not os.path.exists( default_base_path ):
log.warn( "Path '%s' does not exist, ignoring", default_base_path )
if not os.path.isdir( default_base_path ):
log.warn( "Path '%s' is not directory, ignoring", default_base_path )
self.default_base_path = os.path.abspath( default_base_path )
self.resolver_classes = self.__resolvers_dict()
self.dependency_resolvers = self.__build_dependency_resolvers( conf_file )
def dependency_shell_commands( self, requirements, **kwds ):
commands = []
for requirement in requirements:
log.debug( "Building dependency shell command for dependency '%s'", requirement.name )
dependency = INDETERMINATE_DEPENDENCY
if requirement.type in [ 'package', 'set_environment' ]:
dependency = self.find_dep( name=requirement.name,
version=requirement.version,
type=requirement.type,
**kwds )
dependency_commands = dependency.shell_commands( requirement )
if not dependency_commands:
log.warn( "Failed to resolve dependency on '%s', ignoring", requirement.name )
else:
commands.append( dependency_commands )
return commands
def uses_tool_shed_dependencies(self):
return any( map( lambda r: isinstance( r, ToolShedPackageDependencyResolver ), self.dependency_resolvers ) )
def find_dep( self, name, version=None, type='package', **kwds ):
for resolver in self.dependency_resolvers:
dependency = resolver.resolve( name, version, type, **kwds )
if dependency != INDETERMINATE_DEPENDENCY:
return dependency
return INDETERMINATE_DEPENDENCY
def __build_dependency_resolvers( self, conf_file ):
if not conf_file or not os.path.exists( conf_file ):
return self.__default_dependency_resolvers()
plugin_source = plugin_config.plugin_source_from_path( conf_file )
return self.__parse_resolver_conf_xml( plugin_source )
def __default_dependency_resolvers( self ):
return [
ToolShedPackageDependencyResolver(self),
GalaxyPackageDependencyResolver(self),
GalaxyPackageDependencyResolver(self, versionless=True),
]
def __parse_resolver_conf_xml(self, plugin_source):
"""
"""
extra_kwds = dict( dependency_manager=self )
return plugin_config.load_plugins( self.resolver_classes, plugin_source, extra_kwds )
def __resolvers_dict( self ):
import galaxy.tools.deps.resolvers
return plugin_config.plugins_dict( galaxy.tools.deps.resolvers, 'resolver_type' )
| 40.035088 | 116 | 0.675066 |
import os.path
import logging
log = logging.getLogger( __name__ )
from .resolvers import INDETERMINATE_DEPENDENCY
from .resolvers.galaxy_packages import GalaxyPackageDependencyResolver
from .resolvers.tool_shed_packages import ToolShedPackageDependencyResolver
from galaxy.util import plugin_config
def build_dependency_manager( config ):
if getattr( config, "use_tool_dependencies", False ):
dependency_manager_kwds = {
'default_base_path': config.tool_dependency_dir,
'conf_file': config.dependency_resolvers_config_file,
}
dependency_manager = DependencyManager( **dependency_manager_kwds )
else:
dependency_manager = NullDependencyManager()
return dependency_manager
class NullDependencyManager( object ):
def uses_tool_shed_dependencies(self):
return False
def dependency_shell_commands( self, requirements, **kwds ):
return []
def find_dep( self, name, version=None, type='package', **kwds ):
return INDETERMINATE_DEPENDENCY
class DependencyManager( object ):
def __init__( self, default_base_path, conf_file=None ):
if not os.path.exists( default_base_path ):
log.warn( "Path '%s' does not exist, ignoring", default_base_path )
if not os.path.isdir( default_base_path ):
log.warn( "Path '%s' is not directory, ignoring", default_base_path )
self.default_base_path = os.path.abspath( default_base_path )
self.resolver_classes = self.__resolvers_dict()
self.dependency_resolvers = self.__build_dependency_resolvers( conf_file )
def dependency_shell_commands( self, requirements, **kwds ):
commands = []
for requirement in requirements:
log.debug( "Building dependency shell command for dependency '%s'", requirement.name )
dependency = INDETERMINATE_DEPENDENCY
if requirement.type in [ 'package', 'set_environment' ]:
dependency = self.find_dep( name=requirement.name,
version=requirement.version,
type=requirement.type,
**kwds )
dependency_commands = dependency.shell_commands( requirement )
if not dependency_commands:
log.warn( "Failed to resolve dependency on '%s', ignoring", requirement.name )
else:
commands.append( dependency_commands )
return commands
def uses_tool_shed_dependencies(self):
return any( map( lambda r: isinstance( r, ToolShedPackageDependencyResolver ), self.dependency_resolvers ) )
def find_dep( self, name, version=None, type='package', **kwds ):
for resolver in self.dependency_resolvers:
dependency = resolver.resolve( name, version, type, **kwds )
if dependency != INDETERMINATE_DEPENDENCY:
return dependency
return INDETERMINATE_DEPENDENCY
def __build_dependency_resolvers( self, conf_file ):
if not conf_file or not os.path.exists( conf_file ):
return self.__default_dependency_resolvers()
plugin_source = plugin_config.plugin_source_from_path( conf_file )
return self.__parse_resolver_conf_xml( plugin_source )
def __default_dependency_resolvers( self ):
return [
ToolShedPackageDependencyResolver(self),
GalaxyPackageDependencyResolver(self),
GalaxyPackageDependencyResolver(self, versionless=True),
]
def __parse_resolver_conf_xml(self, plugin_source):
extra_kwds = dict( dependency_manager=self )
return plugin_config.load_plugins( self.resolver_classes, plugin_source, extra_kwds )
def __resolvers_dict( self ):
import galaxy.tools.deps.resolvers
return plugin_config.plugins_dict( galaxy.tools.deps.resolvers, 'resolver_type' )
| true | true |
f72b91de3aa8e38ef7f1435603855433b8cce9c5 | 6,254 | py | Python | python/fate_arch/protobuf/python/model_service_pb2_grpc.py | hubert-he/FATE | 6758e150bd7ca7d6f788f9a7a8c8aea7e6500363 | [
"Apache-2.0"
] | 3,787 | 2019-08-30T04:55:10.000Z | 2022-03-31T23:30:07.000Z | python/fate_arch/protobuf/python/model_service_pb2_grpc.py | JavaGreenHands/FATE | ea1e94b6be50c70c354d1861093187e523af32f2 | [
"Apache-2.0"
] | 1,439 | 2019-08-29T16:35:52.000Z | 2022-03-31T11:55:31.000Z | python/fate_arch/protobuf/python/model_service_pb2_grpc.py | JavaGreenHands/FATE | ea1e94b6be50c70c354d1861093187e523af32f2 | [
"Apache-2.0"
] | 1,179 | 2019-08-29T16:18:32.000Z | 2022-03-31T12:55:38.000Z | #
# Copyright 2019 The FATE 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.
#
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
import model_service_pb2 as model__service__pb2
class ModelServiceStub(object):
# missing associated documentation comment in .proto file
pass
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.publishLoad = channel.unary_unary(
'/com.webank.ai.fate.api.mlmodel.manager.ModelService/publishLoad',
request_serializer=model__service__pb2.PublishRequest.SerializeToString,
response_deserializer=model__service__pb2.PublishResponse.FromString,
)
self.publishBind = channel.unary_unary(
'/com.webank.ai.fate.api.mlmodel.manager.ModelService/publishBind',
request_serializer=model__service__pb2.PublishRequest.SerializeToString,
response_deserializer=model__service__pb2.PublishResponse.FromString,
)
self.publishOnline = channel.unary_unary(
'/com.webank.ai.fate.api.mlmodel.manager.ModelService/publishOnline',
request_serializer=model__service__pb2.PublishRequest.SerializeToString,
response_deserializer=model__service__pb2.PublishResponse.FromString,
)
self.queryModel = channel.unary_unary(
'/com.webank.ai.fate.api.mlmodel.manager.ModelService/queryModel',
request_serializer=model__service__pb2.QueryModelRequest.SerializeToString,
response_deserializer=model__service__pb2.QueryModelResponse.FromString,
)
self.unload = channel.unary_unary(
'/com.webank.ai.fate.api.mlmodel.manager.ModelService/unload',
request_serializer=model__service__pb2.UnloadRequest.SerializeToString,
response_deserializer=model__service__pb2.UnloadResponse.FromString,
)
self.unbind = channel.unary_unary(
'/com.webank.ai.fate.api.mlmodel.manager.ModelService/unbind',
request_serializer=model__service__pb2.UnbindRequest.SerializeToString,
response_deserializer=model__service__pb2.UnbindResponse.FromString,
)
class ModelServiceServicer(object):
# missing associated documentation comment in .proto file
pass
def publishLoad(self, request, context):
# missing associated documentation comment in .proto file
pass
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def publishBind(self, request, context):
# missing associated documentation comment in .proto file
pass
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def publishOnline(self, request, context):
# missing associated documentation comment in .proto file
pass
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def queryModel(self, request, context):
# missing associated documentation comment in .proto file
pass
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def unload(self, request, context):
# missing associated documentation comment in .proto file
pass
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def unbind(self, request, context):
# missing associated documentation comment in .proto file
pass
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_ModelServiceServicer_to_server(servicer, server):
rpc_method_handlers = {
'publishLoad': grpc.unary_unary_rpc_method_handler(
servicer.publishLoad,
request_deserializer=model__service__pb2.PublishRequest.FromString,
response_serializer=model__service__pb2.PublishResponse.SerializeToString,
),
'publishBind': grpc.unary_unary_rpc_method_handler(
servicer.publishBind,
request_deserializer=model__service__pb2.PublishRequest.FromString,
response_serializer=model__service__pb2.PublishResponse.SerializeToString,
),
'publishOnline': grpc.unary_unary_rpc_method_handler(
servicer.publishOnline,
request_deserializer=model__service__pb2.PublishRequest.FromString,
response_serializer=model__service__pb2.PublishResponse.SerializeToString,
),
'queryModel': grpc.unary_unary_rpc_method_handler(
servicer.queryModel,
request_deserializer=model__service__pb2.QueryModelRequest.FromString,
response_serializer=model__service__pb2.QueryModelResponse.SerializeToString,
),
'unload': grpc.unary_unary_rpc_method_handler(
servicer.unload,
request_deserializer=model__service__pb2.UnloadRequest.FromString,
response_serializer=model__service__pb2.UnloadResponse.SerializeToString,
),
'unbind': grpc.unary_unary_rpc_method_handler(
servicer.unbind,
request_deserializer=model__service__pb2.UnbindRequest.FromString,
response_serializer=model__service__pb2.UnbindResponse.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'com.webank.ai.fate.api.mlmodel.manager.ModelService', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
| 42.544218 | 87 | 0.756316 |
import grpc
import model_service_pb2 as model__service__pb2
class ModelServiceStub(object):
pass
def __init__(self, channel):
self.publishLoad = channel.unary_unary(
'/com.webank.ai.fate.api.mlmodel.manager.ModelService/publishLoad',
request_serializer=model__service__pb2.PublishRequest.SerializeToString,
response_deserializer=model__service__pb2.PublishResponse.FromString,
)
self.publishBind = channel.unary_unary(
'/com.webank.ai.fate.api.mlmodel.manager.ModelService/publishBind',
request_serializer=model__service__pb2.PublishRequest.SerializeToString,
response_deserializer=model__service__pb2.PublishResponse.FromString,
)
self.publishOnline = channel.unary_unary(
'/com.webank.ai.fate.api.mlmodel.manager.ModelService/publishOnline',
request_serializer=model__service__pb2.PublishRequest.SerializeToString,
response_deserializer=model__service__pb2.PublishResponse.FromString,
)
self.queryModel = channel.unary_unary(
'/com.webank.ai.fate.api.mlmodel.manager.ModelService/queryModel',
request_serializer=model__service__pb2.QueryModelRequest.SerializeToString,
response_deserializer=model__service__pb2.QueryModelResponse.FromString,
)
self.unload = channel.unary_unary(
'/com.webank.ai.fate.api.mlmodel.manager.ModelService/unload',
request_serializer=model__service__pb2.UnloadRequest.SerializeToString,
response_deserializer=model__service__pb2.UnloadResponse.FromString,
)
self.unbind = channel.unary_unary(
'/com.webank.ai.fate.api.mlmodel.manager.ModelService/unbind',
request_serializer=model__service__pb2.UnbindRequest.SerializeToString,
response_deserializer=model__service__pb2.UnbindResponse.FromString,
)
class ModelServiceServicer(object):
pass
def publishLoad(self, request, context):
pass
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def publishBind(self, request, context):
pass
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def publishOnline(self, request, context):
pass
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def queryModel(self, request, context):
pass
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def unload(self, request, context):
pass
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def unbind(self, request, context):
pass
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_ModelServiceServicer_to_server(servicer, server):
rpc_method_handlers = {
'publishLoad': grpc.unary_unary_rpc_method_handler(
servicer.publishLoad,
request_deserializer=model__service__pb2.PublishRequest.FromString,
response_serializer=model__service__pb2.PublishResponse.SerializeToString,
),
'publishBind': grpc.unary_unary_rpc_method_handler(
servicer.publishBind,
request_deserializer=model__service__pb2.PublishRequest.FromString,
response_serializer=model__service__pb2.PublishResponse.SerializeToString,
),
'publishOnline': grpc.unary_unary_rpc_method_handler(
servicer.publishOnline,
request_deserializer=model__service__pb2.PublishRequest.FromString,
response_serializer=model__service__pb2.PublishResponse.SerializeToString,
),
'queryModel': grpc.unary_unary_rpc_method_handler(
servicer.queryModel,
request_deserializer=model__service__pb2.QueryModelRequest.FromString,
response_serializer=model__service__pb2.QueryModelResponse.SerializeToString,
),
'unload': grpc.unary_unary_rpc_method_handler(
servicer.unload,
request_deserializer=model__service__pb2.UnloadRequest.FromString,
response_serializer=model__service__pb2.UnloadResponse.SerializeToString,
),
'unbind': grpc.unary_unary_rpc_method_handler(
servicer.unbind,
request_deserializer=model__service__pb2.UnbindRequest.FromString,
response_serializer=model__service__pb2.UnbindResponse.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'com.webank.ai.fate.api.mlmodel.manager.ModelService', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
| true | true |
f72b929b8804ad874d618eb5b43b2fb64fdfe7ad | 123 | py | Python | app/api/__init__.py | oyasr/mudawen | 6f0161ab783536d7c5d695225ef28ce4947a46e3 | [
"MIT"
] | null | null | null | app/api/__init__.py | oyasr/mudawen | 6f0161ab783536d7c5d695225ef28ce4947a46e3 | [
"MIT"
] | null | null | null | app/api/__init__.py | oyasr/mudawen | 6f0161ab783536d7c5d695225ef28ce4947a46e3 | [
"MIT"
] | null | null | null | from flask import Blueprint
api = Blueprint('api', __name__)
from . import authentication, comments, errors, posts, users | 24.6 | 60 | 0.772358 | from flask import Blueprint
api = Blueprint('api', __name__)
from . import authentication, comments, errors, posts, users | true | true |
f72b92ac89e1858b89e04e9891a5197b9c3b4cbe | 112,673 | py | Python | youtube_dl/YoutubeDL.py | hylinktree/youtube-dl | e4cc49f0c0cd9939c4d7992ba54ab0737fdaa9b0 | [
"Unlicense"
] | null | null | null | youtube_dl/YoutubeDL.py | hylinktree/youtube-dl | e4cc49f0c0cd9939c4d7992ba54ab0737fdaa9b0 | [
"Unlicense"
] | null | null | null | youtube_dl/YoutubeDL.py | hylinktree/youtube-dl | e4cc49f0c0cd9939c4d7992ba54ab0737fdaa9b0 | [
"Unlicense"
] | null | null | null | #!/usr/bin/env python
# coding: utf-8
from __future__ import absolute_import, unicode_literals
import collections
import contextlib
import copy
import datetime
import errno
import fileinput
import io
import itertools
import json
import locale
import operator
import os
import platform
import re
import shutil
import subprocess
import socket
import sys
import time
import tokenize
import traceback
import random
from string import ascii_letters
from .compat import (
compat_basestring,
compat_cookiejar,
compat_get_terminal_size,
compat_http_client,
compat_kwargs,
compat_numeric_types,
compat_os_name,
compat_str,
compat_tokenize_tokenize,
compat_urllib_error,
compat_urllib_request,
compat_urllib_request_DataHandler,
)
from .utils import (
age_restricted,
args_to_str,
ContentTooShortError,
date_from_str,
DateRange,
DEFAULT_OUTTMPL,
determine_ext,
determine_protocol,
DownloadError,
encode_compat_str,
encodeFilename,
error_to_compat_str,
expand_path,
ExtractorError,
format_bytes,
formatSeconds,
GeoRestrictedError,
int_or_none,
ISO3166Utils,
locked_file,
make_HTTPS_handler,
MaxDownloadsReached,
orderedSet,
PagedList,
parse_filesize,
PerRequestProxyHandler,
platform_name,
PostProcessingError,
preferredencoding,
prepend_extension,
register_socks_protocols,
render_table,
replace_extension,
SameFileError,
sanitize_filename,
sanitize_path,
sanitize_url,
sanitized_Request,
std_headers,
str_or_none,
subtitles_filename,
UnavailableVideoError,
url_basename,
version_tuple,
write_json_file,
write_string,
YoutubeDLCookieJar,
YoutubeDLCookieProcessor,
YoutubeDLHandler,
YoutubeDLRedirectHandler,
)
from .cache import Cache
from .extractor import get_info_extractor, gen_extractor_classes, _LAZY_LOADER
from .extractor.openload import PhantomJSwrapper
from .downloader import get_suitable_downloader
from .downloader.rtmp import rtmpdump_version
from .postprocessor import (
FFmpegFixupM3u8PP,
FFmpegFixupM4aPP,
FFmpegFixupStretchedPP,
FFmpegMergerPP,
FFmpegPostProcessor,
get_postprocessor,
)
from .version import __version__
if compat_os_name == 'nt':
import ctypes
class YoutubeDL(object):
"""YoutubeDL class.
YoutubeDL objects are the ones responsible of downloading the
actual video file and writing it to disk if the user has requested
it, among some other tasks. In most cases there should be one per
program. As, given a video URL, the downloader doesn't know how to
extract all the needed information, task that InfoExtractors do, it
has to pass the URL to one of them.
For this, YoutubeDL objects have a method that allows
InfoExtractors to be registered in a given order. When it is passed
a URL, the YoutubeDL object handles it to the first InfoExtractor it
finds that reports being able to handle it. The InfoExtractor extracts
all the information about the video or videos the URL refers to, and
YoutubeDL process the extracted information, possibly using a File
Downloader to download the video.
YoutubeDL objects accept a lot of parameters. In order not to saturate
the object constructor with arguments, it receives a dictionary of
options instead. These options are available through the params
attribute for the InfoExtractors to use. The YoutubeDL also
registers itself as the downloader in charge for the InfoExtractors
that are added to it, so this is a "mutual registration".
Available options:
username: Username for authentication purposes.
password: Password for authentication purposes.
videopassword: Password for accessing a video.
ap_mso: Adobe Pass multiple-system operator identifier.
ap_username: Multiple-system operator account username.
ap_password: Multiple-system operator account password.
usenetrc: Use netrc for authentication instead.
verbose: Print additional info to stdout.
quiet: Do not print messages to stdout.
no_warnings: Do not print out anything for warnings.
forceurl: Force printing final URL.
forcetitle: Force printing title.
forceid: Force printing ID.
forcethumbnail: Force printing thumbnail URL.
forcedescription: Force printing description.
forcefilename: Force printing final filename.
forceduration: Force printing duration.
forcejson: Force printing info_dict as JSON.
dump_single_json: Force printing the info_dict of the whole playlist
(or video) as a single JSON line.
simulate: Do not download the video files.
format: Video format code. See options.py for more information.
outtmpl: Template for output names.
outtmpl_na_placeholder: Placeholder for unavailable meta fields.
restrictfilenames: Do not allow "&" and spaces in file names
ignoreerrors: Do not stop on download errors.
force_generic_extractor: Force downloader to use the generic extractor
nooverwrites: Prevent overwriting files.
playliststart: Playlist item to start at.
playlistend: Playlist item to end at.
playlist_items: Specific indices of playlist to download.
playlistreverse: Download playlist items in reverse order.
playlistrandom: Download playlist items in random order.
matchtitle: Download only matching titles.
rejecttitle: Reject downloads for matching titles.
logger: Log messages to a logging.Logger instance.
logtostderr: Log messages to stderr instead of stdout.
writedescription: Write the video description to a .description file
writeinfojson: Write the video description to a .info.json file
writeannotations: Write the video annotations to a .annotations.xml file
writethumbnail: Write the thumbnail image to a file
write_all_thumbnails: Write all thumbnail formats to files
writesubtitles: Write the video subtitles to a file
writeautomaticsub: Write the automatically generated subtitles to a file
allsubtitles: Downloads all the subtitles of the video
(requires writesubtitles or writeautomaticsub)
listsubtitles: Lists all available subtitles for the video
subtitlesformat: The format code for subtitles
subtitleslangs: List of languages of the subtitles to download
keepvideo: Keep the video file after post-processing
daterange: A DateRange object, download only if the upload_date is in the range.
skip_download: Skip the actual download of the video file
cachedir: Location of the cache files in the filesystem.
False to disable filesystem cache.
noplaylist: Download single video instead of a playlist if in doubt.
age_limit: An integer representing the user's age in years.
Unsuitable videos for the given age are skipped.
min_views: An integer representing the minimum view count the video
must have in order to not be skipped.
Videos without view count information are always
downloaded. None for no limit.
max_views: An integer representing the maximum view count.
Videos that are more popular than that are not
downloaded.
Videos without view count information are always
downloaded. None for no limit.
download_archive: File name of a file where all downloads are recorded.
Videos already present in the file are not downloaded
again.
cookiefile: File name where cookies should be read from and dumped to.
nocheckcertificate:Do not verify SSL certificates
prefer_insecure: Use HTTP instead of HTTPS to retrieve information.
At the moment, this is only supported by YouTube.
proxy: URL of the proxy server to use
geo_verification_proxy: URL of the proxy to use for IP address verification
on geo-restricted sites.
socket_timeout: Time to wait for unresponsive hosts, in seconds
bidi_workaround: Work around buggy terminals without bidirectional text
support, using fridibi
debug_printtraffic:Print out sent and received HTTP traffic
include_ads: Download ads as well
default_search: Prepend this string if an input url is not valid.
'auto' for elaborate guessing
encoding: Use this encoding instead of the system-specified.
extract_flat: Do not resolve URLs, return the immediate result.
Pass in 'in_playlist' to only show this behavior for
playlist items.
postprocessors: A list of dictionaries, each with an entry
* key: The name of the postprocessor. See
youtube_dl/postprocessor/__init__.py for a list.
as well as any further keyword arguments for the
postprocessor.
progress_hooks: A list of functions that get called on download
progress, with a dictionary with the entries
* status: One of "downloading", "error", or "finished".
Check this first and ignore unknown values.
If status is one of "downloading", or "finished", the
following properties may also be present:
* filename: The final filename (always present)
* tmpfilename: The filename we're currently writing to
* downloaded_bytes: Bytes on disk
* total_bytes: Size of the whole file, None if unknown
* total_bytes_estimate: Guess of the eventual file size,
None if unavailable.
* elapsed: The number of seconds since download started.
* eta: The estimated time in seconds, None if unknown
* speed: The download speed in bytes/second, None if
unknown
* fragment_index: The counter of the currently
downloaded video fragment.
* fragment_count: The number of fragments (= individual
files that will be merged)
Progress hooks are guaranteed to be called at least once
(with status "finished") if the download is successful.
merge_output_format: Extension to use when merging formats.
fixup: Automatically correct known faults of the file.
One of:
- "never": do nothing
- "warn": only emit a warning
- "detect_or_warn": check whether we can do anything
about it, warn otherwise (default)
source_address: Client-side IP address to bind to.
call_home: Boolean, true iff we are allowed to contact the
youtube-dl servers for debugging.
sleep_interval: Number of seconds to sleep before each download when
used alone or a lower bound of a range for randomized
sleep before each download (minimum possible number
of seconds to sleep) when used along with
max_sleep_interval.
max_sleep_interval:Upper bound of a range for randomized sleep before each
download (maximum possible number of seconds to sleep).
Must only be used along with sleep_interval.
Actual sleep time will be a random float from range
[sleep_interval; max_sleep_interval].
listformats: Print an overview of available video formats and exit.
list_thumbnails: Print a table of all thumbnails and exit.
match_filter: A function that gets called with the info_dict of
every video.
If it returns a message, the video is ignored.
If it returns None, the video is downloaded.
match_filter_func in utils.py is one example for this.
no_color: Do not emit color codes in output.
geo_bypass: Bypass geographic restriction via faking X-Forwarded-For
HTTP header
geo_bypass_country:
Two-letter ISO 3166-2 country code that will be used for
explicit geographic restriction bypassing via faking
X-Forwarded-For HTTP header
geo_bypass_ip_block:
IP range in CIDR notation that will be used similarly to
geo_bypass_country
The following options determine which downloader is picked:
external_downloader: Executable of the external downloader to call.
None or unset for standard (built-in) downloader.
hls_prefer_native: Use the native HLS downloader instead of ffmpeg/avconv
if True, otherwise use ffmpeg/avconv if False, otherwise
use downloader suggested by extractor if None.
The following parameters are not used by YoutubeDL itself, they are used by
the downloader (see youtube_dl/downloader/common.py):
nopart, updatetime, buffersize, ratelimit, min_filesize, max_filesize, test,
noresizebuffer, retries, continuedl, noprogress, consoletitle,
xattr_set_filesize, external_downloader_args, hls_use_mpegts,
http_chunk_size.
The following options are used by the post processors:
prefer_ffmpeg: If False, use avconv instead of ffmpeg if both are available,
otherwise prefer ffmpeg.
ffmpeg_location: Location of the ffmpeg/avconv binary; either the path
to the binary or its containing directory.
postprocessor_args: A list of additional command-line arguments for the
postprocessor.
The following options are used by the Youtube extractor:
youtube_include_dash_manifest: If True (default), DASH manifests and related
data will be downloaded and processed by extractor.
You can reduce network I/O by disabling it if you don't
care about DASH.
"""
_NUMERIC_FIELDS = set((
'width', 'height', 'tbr', 'abr', 'asr', 'vbr', 'fps', 'filesize', 'filesize_approx',
'timestamp', 'upload_year', 'upload_month', 'upload_day',
'duration', 'view_count', 'like_count', 'dislike_count', 'repost_count',
'average_rating', 'comment_count', 'age_limit',
'start_time', 'end_time',
'chapter_number', 'season_number', 'episode_number',
'track_number', 'disc_number', 'release_year',
'playlist_index',
))
params = None
_ies = []
_pps = []
_download_retcode = None
_num_downloads = None
_playlist_level = 0
_playlist_urls = set()
_screen_file = None
def __init__(self, params=None, auto_init=True):
"""Create a FileDownloader object with the given options."""
if params is None:
params = {}
self._ies = []
self._ies_instances = {}
self._pps = []
self._progress_hooks = []
self._download_retcode = 0
self._num_downloads = 0
self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
self._err_file = sys.stderr
self.params = {
# Default parameters
'nocheckcertificate': False,
}
self.params.update(params)
self.cache = Cache(self)
def check_deprecated(param, option, suggestion):
if self.params.get(param) is not None:
self.report_warning(
'%s is deprecated. Use %s instead.' % (option, suggestion))
return True
return False
if check_deprecated('cn_verification_proxy', '--cn-verification-proxy', '--geo-verification-proxy'):
if self.params.get('geo_verification_proxy') is None:
self.params['geo_verification_proxy'] = self.params['cn_verification_proxy']
check_deprecated('autonumber_size', '--autonumber-size', 'output template with %(autonumber)0Nd, where N in the number of digits')
check_deprecated('autonumber', '--auto-number', '-o "%(autonumber)s-%(title)s.%(ext)s"')
check_deprecated('usetitle', '--title', '-o "%(title)s-%(id)s.%(ext)s"')
if params.get('bidi_workaround', False):
try:
import pty
master, slave = pty.openpty()
width = compat_get_terminal_size().columns
if width is None:
width_args = []
else:
width_args = ['-w', str(width)]
sp_kwargs = dict(
stdin=subprocess.PIPE,
stdout=slave,
stderr=self._err_file)
try:
self._output_process = subprocess.Popen(
['bidiv'] + width_args, **sp_kwargs
)
except OSError:
self._output_process = subprocess.Popen(
['fribidi', '-c', 'UTF-8'] + width_args, **sp_kwargs)
self._output_channel = os.fdopen(master, 'rb')
except OSError as ose:
if ose.errno == errno.ENOENT:
self.report_warning('Could not find fribidi executable, ignoring --bidi-workaround . Make sure that fribidi is an executable file in one of the directories in your $PATH.')
else:
raise
if (sys.platform != 'win32'
and sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968']
and not params.get('restrictfilenames', False)):
# Unicode filesystem API will throw errors (#1474, #13027)
self.report_warning(
'Assuming --restrict-filenames since file system encoding '
'cannot encode all characters. '
'Set the LC_ALL environment variable to fix this.')
self.params['restrictfilenames'] = True
if isinstance(params.get('outtmpl'), bytes):
self.report_warning(
'Parameter outtmpl is bytes, but should be a unicode string. '
'Put from __future__ import unicode_literals at the top of your code file or consider switching to Python 3.x.')
self._setup_opener()
if auto_init:
self.print_debug_header()
self.add_default_info_extractors()
for pp_def_raw in self.params.get('postprocessors', []):
pp_class = get_postprocessor(pp_def_raw['key'])
pp_def = dict(pp_def_raw)
del pp_def['key']
pp = pp_class(self, **compat_kwargs(pp_def))
self.add_post_processor(pp)
for ph in self.params.get('progress_hooks', []):
self.add_progress_hook(ph)
register_socks_protocols()
def warn_if_short_id(self, argv):
# short YouTube ID starting with dash?
idxs = [
i for i, a in enumerate(argv)
if re.match(r'^-[0-9A-Za-z_-]{10}$', a)]
if idxs:
correct_argv = (
['youtube-dl']
+ [a for i, a in enumerate(argv) if i not in idxs]
+ ['--'] + [argv[i] for i in idxs]
)
self.report_warning(
'Long argument string detected. '
'Use -- to separate parameters and URLs, like this:\n%s\n' %
args_to_str(correct_argv))
def add_info_extractor(self, ie):
"""Add an InfoExtractor object to the end of the list."""
self._ies.append(ie)
if not isinstance(ie, type):
self._ies_instances[ie.ie_key()] = ie
ie.set_downloader(self)
def get_info_extractor(self, ie_key):
"""
Get an instance of an IE with name ie_key, it will try to get one from
the _ies list, if there's no instance it will create a new one and add
it to the extractor list.
"""
ie = self._ies_instances.get(ie_key)
if ie is None:
ie = get_info_extractor(ie_key)()
self.add_info_extractor(ie)
return ie
def add_default_info_extractors(self):
"""
Add the InfoExtractors returned by gen_extractors to the end of the list
"""
for ie in gen_extractor_classes():
self.add_info_extractor(ie)
def add_post_processor(self, pp):
"""Add a PostProcessor object to the end of the chain."""
self._pps.append(pp)
pp.set_downloader(self)
def add_progress_hook(self, ph):
"""Add the progress hook (currently only for the file downloader)"""
self._progress_hooks.append(ph)
def _bidi_workaround(self, message):
if not hasattr(self, '_output_channel'):
return message
assert hasattr(self, '_output_process')
assert isinstance(message, compat_str)
line_count = message.count('\n') + 1
self._output_process.stdin.write((message + '\n').encode('utf-8'))
self._output_process.stdin.flush()
res = ''.join(self._output_channel.readline().decode('utf-8')
for _ in range(line_count))
return res[:-len('\n')]
def to_screen(self, message, skip_eol=False):
"""Print message to stdout if not in quiet mode."""
return self.to_stdout(message, skip_eol, check_quiet=True)
def _write_string(self, s, out=None):
write_string(s, out=out, encoding=self.params.get('encoding'))
def to_stdout(self, message, skip_eol=False, check_quiet=False):
"""Print message to stdout if not in quiet mode."""
if self.params.get('logger'):
self.params['logger'].debug(message)
elif not check_quiet or not self.params.get('quiet', False):
message = self._bidi_workaround(message)
terminator = ['\n', ''][skip_eol]
output = message + terminator
self._write_string(output, self._screen_file)
def to_stderr(self, message):
"""Print message to stderr."""
assert isinstance(message, compat_str)
if self.params.get('logger'):
self.params['logger'].error(message)
else:
message = self._bidi_workaround(message)
output = message + '\n'
self._write_string(output, self._err_file)
def to_console_title(self, message):
if not self.params.get('consoletitle', False):
return
if compat_os_name == 'nt':
if ctypes.windll.kernel32.GetConsoleWindow():
# c_wchar_p() might not be necessary if `message` is
# already of type unicode()
ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
elif 'TERM' in os.environ:
self._write_string('\033]0;%s\007' % message, self._screen_file)
def save_console_title(self):
if not self.params.get('consoletitle', False):
return
if self.params.get('simulate', False):
return
if compat_os_name != 'nt' and 'TERM' in os.environ:
# Save the title on stack
self._write_string('\033[22;0t', self._screen_file)
def restore_console_title(self):
if not self.params.get('consoletitle', False):
return
if self.params.get('simulate', False):
return
if compat_os_name != 'nt' and 'TERM' in os.environ:
# Restore the title from stack
self._write_string('\033[23;0t', self._screen_file)
def __enter__(self):
self.save_console_title()
return self
def __exit__(self, *args):
self.restore_console_title()
if self.params.get('cookiefile') is not None:
self.cookiejar.save(ignore_discard=True, ignore_expires=True)
def trouble(self, message=None, tb=None):
"""Determine action to take when a download problem appears.
Depending on if the downloader has been configured to ignore
download errors or not, this method may throw an exception or
not when errors are found, after printing the message.
tb, if given, is additional traceback information.
"""
if message is not None:
self.to_stderr(message)
if self.params.get('verbose'):
if tb is None:
if sys.exc_info()[0]: # if .trouble has been called from an except block
tb = ''
if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
tb += encode_compat_str(traceback.format_exc())
else:
tb_data = traceback.format_list(traceback.extract_stack())
tb = ''.join(tb_data)
self.to_stderr(tb)
if not self.params.get('ignoreerrors', False):
if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
exc_info = sys.exc_info()[1].exc_info
else:
exc_info = sys.exc_info()
raise DownloadError(message, exc_info)
self._download_retcode = 1
def report_warning(self, message):
'''
Print the message to stderr, it will be prefixed with 'WARNING:'
If stderr is a tty file the 'WARNING:' will be colored
'''
if self.params.get('logger') is not None:
self.params['logger'].warning(message)
else:
if self.params.get('no_warnings'):
return
if not self.params.get('no_color') and self._err_file.isatty() and compat_os_name != 'nt':
_msg_header = '\033[0;33mWARNING:\033[0m'
else:
_msg_header = 'WARNING:'
warning_message = '%s %s' % (_msg_header, message)
self.to_stderr(warning_message)
def report_error(self, message, tb=None):
'''
Do the same as trouble, but prefixes the message with 'ERROR:', colored
in red if stderr is a tty file.
'''
if not self.params.get('no_color') and self._err_file.isatty() and compat_os_name != 'nt':
_msg_header = '\033[0;31mERROR:\033[0m'
else:
_msg_header = 'ERROR:'
error_message = '%s %s' % (_msg_header, message)
self.trouble(error_message, tb)
def report_file_already_downloaded(self, file_name):
"""Report file has already been fully downloaded."""
try:
self.to_screen('[download] %s has already been downloaded' % file_name)
except UnicodeEncodeError:
self.to_screen('[download] The file has already been downloaded')
def prepare_filename(self, info_dict):
"""Generate the output filename."""
try:
template_dict = dict(info_dict)
template_dict['epoch'] = int(time.time())
autonumber_size = self.params.get('autonumber_size')
if autonumber_size is None:
autonumber_size = 5
template_dict['autonumber'] = self.params.get('autonumber_start', 1) - 1 + self._num_downloads
if template_dict.get('resolution') is None:
if template_dict.get('width') and template_dict.get('height'):
template_dict['resolution'] = '%dx%d' % (template_dict['width'], template_dict['height'])
elif template_dict.get('height'):
template_dict['resolution'] = '%sp' % template_dict['height']
elif template_dict.get('width'):
template_dict['resolution'] = '%dx?' % template_dict['width']
sanitize = lambda k, v: sanitize_filename(
compat_str(v),
restricted=self.params.get('restrictfilenames'),
is_id=(k == 'id' or k.endswith('_id')))
template_dict = dict((k, v if isinstance(v, compat_numeric_types) else sanitize(k, v))
for k, v in template_dict.items()
if v is not None and not isinstance(v, (list, tuple, dict)))
template_dict = collections.defaultdict(lambda: self.params.get('outtmpl_na_placeholder', 'NA'), template_dict)
outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
# For fields playlist_index and autonumber convert all occurrences
# of %(field)s to %(field)0Nd for backward compatibility
field_size_compat_map = {
'playlist_index': len(str(template_dict['n_entries'])),
'autonumber': autonumber_size,
}
FIELD_SIZE_COMPAT_RE = r'(?<!%)%\((?P<field>autonumber|playlist_index)\)s'
mobj = re.search(FIELD_SIZE_COMPAT_RE, outtmpl)
if mobj:
outtmpl = re.sub(
FIELD_SIZE_COMPAT_RE,
r'%%(\1)0%dd' % field_size_compat_map[mobj.group('field')],
outtmpl)
# Missing numeric fields used together with integer presentation types
# in format specification will break the argument substitution since
# string NA placeholder is returned for missing fields. We will patch
# output template for missing fields to meet string presentation type.
for numeric_field in self._NUMERIC_FIELDS:
if numeric_field not in template_dict:
# As of [1] format syntax is:
# %[mapping_key][conversion_flags][minimum_width][.precision][length_modifier]type
# 1. https://docs.python.org/2/library/stdtypes.html#string-formatting
FORMAT_RE = r'''(?x)
(?<!%)
%
\({0}\) # mapping key
(?:[#0\-+ ]+)? # conversion flags (optional)
(?:\d+)? # minimum field width (optional)
(?:\.\d+)? # precision (optional)
[hlL]? # length modifier (optional)
[diouxXeEfFgGcrs%] # conversion type
'''
outtmpl = re.sub(
FORMAT_RE.format(numeric_field),
r'%({0})s'.format(numeric_field), outtmpl)
# expand_path translates '%%' into '%' and '$$' into '$'
# correspondingly that is not what we want since we need to keep
# '%%' intact for template dict substitution step. Working around
# with boundary-alike separator hack.
sep = ''.join([random.choice(ascii_letters) for _ in range(32)])
# print('hychu, {%s}' % outtmpl)
outtmpl = outtmpl.replace('%%', '%{0}%'.format(sep)).replace('$$', '${0}$'.format(sep))
# outtmpl should be expand_path'ed before template dict substitution
# because meta fields may contain env variables we don't want to
# be expanded. For example, for outtmpl "%(title)s.%(ext)s" and
# title "Hello $PATH", we don't want `$PATH` to be expanded.
filename = expand_path(outtmpl).replace(sep, '') % template_dict
# filename = os.path.join('out', filename)
# print('hychu, The filename is {%s}.{%s}' % (outtmpl, filename))
# Temporary fix for #4787
# 'Treat' all problem characters by passing filename through preferredencoding
# to workaround encoding issues with subprocess on python2 @ Windows
if sys.version_info < (3, 0) and sys.platform == 'win32':
filename = encodeFilename(filename, True).decode(preferredencoding())
return sanitize_path(filename)
except ValueError as err:
self.report_error('Error in output template: ' + str(err) + ' (encoding: ' + repr(preferredencoding()) + ')')
return None
def _match_entry(self, info_dict, incomplete):
""" Returns None iff the file should be downloaded """
video_title = info_dict.get('title', info_dict.get('id', 'video'))
if 'title' in info_dict:
# This can happen when we're just evaluating the playlist
title = info_dict['title']
matchtitle = self.params.get('matchtitle', False)
if matchtitle:
if not re.search(matchtitle, title, re.IGNORECASE):
return '"' + title + '" title did not match pattern "' + matchtitle + '"'
rejecttitle = self.params.get('rejecttitle', False)
if rejecttitle:
if re.search(rejecttitle, title, re.IGNORECASE):
return '"' + title + '" title matched reject pattern "' + rejecttitle + '"'
date = info_dict.get('upload_date')
if date is not None:
dateRange = self.params.get('daterange', DateRange())
if date not in dateRange:
return '%s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
view_count = info_dict.get('view_count')
if view_count is not None:
min_views = self.params.get('min_views')
if min_views is not None and view_count < min_views:
return 'Skipping %s, because it has not reached minimum view count (%d/%d)' % (video_title, view_count, min_views)
max_views = self.params.get('max_views')
if max_views is not None and view_count > max_views:
return 'Skipping %s, because it has exceeded the maximum view count (%d/%d)' % (video_title, view_count, max_views)
if age_restricted(info_dict.get('age_limit'), self.params.get('age_limit')):
return 'Skipping "%s" because it is age restricted' % video_title
if self.in_download_archive(info_dict):
return '%s has already been recorded in archive' % video_title
if not incomplete:
match_filter = self.params.get('match_filter')
if match_filter is not None:
ret = match_filter(info_dict)
if ret is not None:
return ret
return None
@staticmethod
def add_extra_info(info_dict, extra_info):
'''Set the keys from extra_info in info dict if they are missing'''
for key, value in extra_info.items():
info_dict.setdefault(key, value)
def extract_info(self, url, download=True, ie_key=None, extra_info={},
process=True, force_generic_extractor=False):
'''
Returns a list with a dictionary for each video we find.
If 'download', also downloads the videos.
extra_info is a dict containing the extra values to add to each result
'''
if not ie_key and force_generic_extractor:
ie_key = 'Generic'
if ie_key:
ies = [self.get_info_extractor(ie_key)]
else:
ies = self._ies
for ie in ies:
if not ie.suitable(url):
continue
ie = self.get_info_extractor(ie.ie_key())
if not ie.working():
self.report_warning('The program functionality for this site has been marked as broken, '
'and will probably not work.')
return self.__extract_info(url, ie, download, extra_info, process)
else:
self.report_error('no suitable InfoExtractor for URL %s' % url)
def __handle_extraction_exceptions(func):
def wrapper(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except GeoRestrictedError as e:
msg = e.msg
if e.countries:
msg += '\nThis video is available in %s.' % ', '.join(
map(ISO3166Utils.short2full, e.countries))
msg += '\nYou might want to use a VPN or a proxy server (with --proxy) to workaround.'
self.report_error(msg)
except ExtractorError as e: # An error we somewhat expected
self.report_error(compat_str(e), e.format_traceback())
except MaxDownloadsReached:
raise
except Exception as e:
if self.params.get('ignoreerrors', False):
self.report_error(error_to_compat_str(e), tb=encode_compat_str(traceback.format_exc()))
else:
raise
return wrapper
@__handle_extraction_exceptions
def __extract_info(self, url, ie, download, extra_info, process):
ie_result = ie.extract(url)
if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
return
if isinstance(ie_result, list):
# Backwards compatibility: old IE result format
ie_result = {
'_type': 'compat_list',
'entries': ie_result,
}
self.add_default_extra_info(ie_result, ie, url)
if process:
return self.process_ie_result(ie_result, download, extra_info)
else:
return ie_result
def add_default_extra_info(self, ie_result, ie, url):
self.add_extra_info(ie_result, {
'extractor': ie.IE_NAME,
'webpage_url': url,
'webpage_url_basename': url_basename(url),
'extractor_key': ie.ie_key(),
})
def process_ie_result(self, ie_result, download=True, extra_info={}):
"""
Take the result of the ie(may be modified) and resolve all unresolved
references (URLs, playlist items).
It will also download the videos if 'download'.
Returns the resolved ie_result.
"""
result_type = ie_result.get('_type', 'video')
if result_type in ('url', 'url_transparent'):
ie_result['url'] = sanitize_url(ie_result['url'])
extract_flat = self.params.get('extract_flat', False)
if ((extract_flat == 'in_playlist' and 'playlist' in extra_info)
or extract_flat is True):
self.__forced_printings(
ie_result, self.prepare_filename(ie_result),
incomplete=True)
return ie_result
if result_type == 'video':
self.add_extra_info(ie_result, extra_info)
return self.process_video_result(ie_result, download=download)
elif result_type == 'url':
# We have to add extra_info to the results because it may be
# contained in a playlist
return self.extract_info(ie_result['url'],
download,
ie_key=ie_result.get('ie_key'),
extra_info=extra_info)
elif result_type == 'url_transparent':
# Use the information from the embedding page
info = self.extract_info(
ie_result['url'], ie_key=ie_result.get('ie_key'),
extra_info=extra_info, download=False, process=False)
# extract_info may return None when ignoreerrors is enabled and
# extraction failed with an error, don't crash and return early
# in this case
if not info:
return info
force_properties = dict(
(k, v) for k, v in ie_result.items() if v is not None)
for f in ('_type', 'url', 'id', 'extractor', 'extractor_key', 'ie_key'):
if f in force_properties:
del force_properties[f]
new_result = info.copy()
new_result.update(force_properties)
# Extracted info may not be a video result (i.e.
# info.get('_type', 'video') != video) but rather an url or
# url_transparent. In such cases outer metadata (from ie_result)
# should be propagated to inner one (info). For this to happen
# _type of info should be overridden with url_transparent. This
# fixes issue from https://github.com/ytdl-org/youtube-dl/pull/11163.
if new_result.get('_type') == 'url':
new_result['_type'] = 'url_transparent'
return self.process_ie_result(
new_result, download=download, extra_info=extra_info)
elif result_type in ('playlist', 'multi_video'):
# Protect from infinite recursion due to recursively nested playlists
# (see https://github.com/ytdl-org/youtube-dl/issues/27833)
webpage_url = ie_result['webpage_url']
if webpage_url in self._playlist_urls:
self.to_screen(
'[download] Skipping already downloaded playlist: %s'
% ie_result.get('title') or ie_result.get('id'))
return
self._playlist_level += 1
self._playlist_urls.add(webpage_url)
try:
return self.__process_playlist(ie_result, download)
finally:
self._playlist_level -= 1
if not self._playlist_level:
self._playlist_urls.clear()
elif result_type == 'compat_list':
self.report_warning(
'Extractor %s returned a compat_list result. '
'It needs to be updated.' % ie_result.get('extractor'))
def _fixup(r):
self.add_extra_info(
r,
{
'extractor': ie_result['extractor'],
'webpage_url': ie_result['webpage_url'],
'webpage_url_basename': url_basename(ie_result['webpage_url']),
'extractor_key': ie_result['extractor_key'],
}
)
return r
ie_result['entries'] = [
self.process_ie_result(_fixup(r), download, extra_info)
for r in ie_result['entries']
]
return ie_result
else:
raise Exception('Invalid result type: %s' % result_type)
def __process_playlist(self, ie_result, download):
# We process each entry in the playlist
playlist = ie_result.get('title') or ie_result.get('id')
self.to_screen('[download] Downloading playlist: %s' % playlist)
playlist_results = []
playliststart = self.params.get('playliststart', 1) - 1
playlistend = self.params.get('playlistend')
# For backwards compatibility, interpret -1 as whole list
if playlistend == -1:
playlistend = None
playlistitems_str = self.params.get('playlist_items')
playlistitems = None
if playlistitems_str is not None:
def iter_playlistitems(format):
for string_segment in format.split(','):
if '-' in string_segment:
start, end = string_segment.split('-')
for item in range(int(start), int(end) + 1):
yield int(item)
else:
yield int(string_segment)
playlistitems = orderedSet(iter_playlistitems(playlistitems_str))
ie_entries = ie_result['entries']
def make_playlistitems_entries(list_ie_entries):
num_entries = len(list_ie_entries)
return [
list_ie_entries[i - 1] for i in playlistitems
if -num_entries <= i - 1 < num_entries]
def report_download(num_entries):
self.to_screen(
'[%s] playlist %s: Downloading %d videos' %
(ie_result['extractor'], playlist, num_entries))
if isinstance(ie_entries, list):
n_all_entries = len(ie_entries)
if playlistitems:
entries = make_playlistitems_entries(ie_entries)
else:
entries = ie_entries[playliststart:playlistend]
n_entries = len(entries)
self.to_screen(
'[%s] playlist %s: Collected %d video ids (downloading %d of them)' %
(ie_result['extractor'], playlist, n_all_entries, n_entries))
elif isinstance(ie_entries, PagedList):
if playlistitems:
entries = []
for item in playlistitems:
entries.extend(ie_entries.getslice(
item - 1, item
))
else:
entries = ie_entries.getslice(
playliststart, playlistend)
n_entries = len(entries)
report_download(n_entries)
else: # iterable
if playlistitems:
entries = make_playlistitems_entries(list(itertools.islice(
ie_entries, 0, max(playlistitems))))
else:
entries = list(itertools.islice(
ie_entries, playliststart, playlistend))
n_entries = len(entries)
report_download(n_entries)
if self.params.get('playlistreverse', False):
entries = entries[::-1]
if self.params.get('playlistrandom', False):
random.shuffle(entries)
x_forwarded_for = ie_result.get('__x_forwarded_for_ip')
for i, entry in enumerate(entries, 1):
self.to_screen('[download] Downloading video %s of %s' % (i, n_entries))
# This __x_forwarded_for_ip thing is a bit ugly but requires
# minimal changes
if x_forwarded_for:
entry['__x_forwarded_for_ip'] = x_forwarded_for
extra = {
'n_entries': n_entries,
'playlist': playlist,
'playlist_id': ie_result.get('id'),
'playlist_title': ie_result.get('title'),
'playlist_uploader': ie_result.get('uploader'),
'playlist_uploader_id': ie_result.get('uploader_id'),
'playlist_index': playlistitems[i - 1] if playlistitems else i + playliststart,
'extractor': ie_result['extractor'],
'webpage_url': ie_result['webpage_url'],
'webpage_url_basename': url_basename(ie_result['webpage_url']),
'extractor_key': ie_result['extractor_key'],
}
reason = self._match_entry(entry, incomplete=True)
if reason is not None:
self.to_screen('[download] ' + reason)
continue
entry_result = self.__process_iterable_entry(entry, download, extra)
# TODO: skip failed (empty) entries?
playlist_results.append(entry_result)
ie_result['entries'] = playlist_results
self.to_screen('[download] Finished downloading playlist: %s' % playlist)
return ie_result
@__handle_extraction_exceptions
def __process_iterable_entry(self, entry, download, extra_info):
return self.process_ie_result(
entry, download=download, extra_info=extra_info)
def _build_format_filter(self, filter_spec):
" Returns a function to filter the formats according to the filter_spec "
OPERATORS = {
'<': operator.lt,
'<=': operator.le,
'>': operator.gt,
'>=': operator.ge,
'=': operator.eq,
'!=': operator.ne,
}
operator_rex = re.compile(r'''(?x)\s*
(?P<key>width|height|tbr|abr|vbr|asr|filesize|filesize_approx|fps)
\s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
(?P<value>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)
$
''' % '|'.join(map(re.escape, OPERATORS.keys())))
m = operator_rex.search(filter_spec)
if m:
try:
comparison_value = int(m.group('value'))
except ValueError:
comparison_value = parse_filesize(m.group('value'))
if comparison_value is None:
comparison_value = parse_filesize(m.group('value') + 'B')
if comparison_value is None:
raise ValueError(
'Invalid value %r in format specification %r' % (
m.group('value'), filter_spec))
op = OPERATORS[m.group('op')]
if not m:
STR_OPERATORS = {
'=': operator.eq,
'^=': lambda attr, value: attr.startswith(value),
'$=': lambda attr, value: attr.endswith(value),
'*=': lambda attr, value: value in attr,
}
str_operator_rex = re.compile(r'''(?x)
\s*(?P<key>ext|acodec|vcodec|container|protocol|format_id|language)
\s*(?P<negation>!\s*)?(?P<op>%s)(?P<none_inclusive>\s*\?)?
\s*(?P<value>[a-zA-Z0-9._-]+)
\s*$
''' % '|'.join(map(re.escape, STR_OPERATORS.keys())))
m = str_operator_rex.search(filter_spec)
if m:
comparison_value = m.group('value')
str_op = STR_OPERATORS[m.group('op')]
if m.group('negation'):
op = lambda attr, value: not str_op(attr, value)
else:
op = str_op
if not m:
raise ValueError('Invalid filter specification %r' % filter_spec)
def _filter(f):
actual_value = f.get(m.group('key'))
if actual_value is None:
return m.group('none_inclusive')
return op(actual_value, comparison_value)
return _filter
def _default_format_spec(self, info_dict, download=True):
def can_merge():
merger = FFmpegMergerPP(self)
return merger.available and merger.can_merge()
def prefer_best():
if self.params.get('simulate', False):
return False
if not download:
return False
if self.params.get('outtmpl', DEFAULT_OUTTMPL) == '-':
return True
if info_dict.get('is_live'):
return True
if not can_merge():
return True
return False
req_format_list = ['bestvideo+bestaudio', 'best']
if prefer_best():
req_format_list.reverse()
return '/'.join(req_format_list)
def build_format_selector(self, format_spec):
def syntax_error(note, start):
message = (
'Invalid format specification: '
'{0}\n\t{1}\n\t{2}^'.format(note, format_spec, ' ' * start[1]))
return SyntaxError(message)
PICKFIRST = 'PICKFIRST'
MERGE = 'MERGE'
SINGLE = 'SINGLE'
GROUP = 'GROUP'
FormatSelector = collections.namedtuple('FormatSelector', ['type', 'selector', 'filters'])
def _parse_filter(tokens):
filter_parts = []
for type, string, start, _, _ in tokens:
if type == tokenize.OP and string == ']':
return ''.join(filter_parts)
else:
filter_parts.append(string)
def _remove_unused_ops(tokens):
# Remove operators that we don't use and join them with the surrounding strings
# for example: 'mp4' '-' 'baseline' '-' '16x9' is converted to 'mp4-baseline-16x9'
ALLOWED_OPS = ('/', '+', ',', '(', ')')
last_string, last_start, last_end, last_line = None, None, None, None
for type, string, start, end, line in tokens:
if type == tokenize.OP and string == '[':
if last_string:
yield tokenize.NAME, last_string, last_start, last_end, last_line
last_string = None
yield type, string, start, end, line
# everything inside brackets will be handled by _parse_filter
for type, string, start, end, line in tokens:
yield type, string, start, end, line
if type == tokenize.OP and string == ']':
break
elif type == tokenize.OP and string in ALLOWED_OPS:
if last_string:
yield tokenize.NAME, last_string, last_start, last_end, last_line
last_string = None
yield type, string, start, end, line
elif type in [tokenize.NAME, tokenize.NUMBER, tokenize.OP]:
if not last_string:
last_string = string
last_start = start
last_end = end
else:
last_string += string
if last_string:
yield tokenize.NAME, last_string, last_start, last_end, last_line
def _parse_format_selection(tokens, inside_merge=False, inside_choice=False, inside_group=False):
selectors = []
current_selector = None
for type, string, start, _, _ in tokens:
# ENCODING is only defined in python 3.x
if type == getattr(tokenize, 'ENCODING', None):
continue
elif type in [tokenize.NAME, tokenize.NUMBER]:
current_selector = FormatSelector(SINGLE, string, [])
elif type == tokenize.OP:
if string == ')':
if not inside_group:
# ')' will be handled by the parentheses group
tokens.restore_last_token()
break
elif inside_merge and string in ['/', ',']:
tokens.restore_last_token()
break
elif inside_choice and string == ',':
tokens.restore_last_token()
break
elif string == ',':
if not current_selector:
raise syntax_error('"," must follow a format selector', start)
selectors.append(current_selector)
current_selector = None
elif string == '/':
if not current_selector:
raise syntax_error('"/" must follow a format selector', start)
first_choice = current_selector
second_choice = _parse_format_selection(tokens, inside_choice=True)
current_selector = FormatSelector(PICKFIRST, (first_choice, second_choice), [])
elif string == '[':
if not current_selector:
current_selector = FormatSelector(SINGLE, 'best', [])
format_filter = _parse_filter(tokens)
current_selector.filters.append(format_filter)
elif string == '(':
if current_selector:
raise syntax_error('Unexpected "("', start)
group = _parse_format_selection(tokens, inside_group=True)
current_selector = FormatSelector(GROUP, group, [])
elif string == '+':
if inside_merge:
raise syntax_error('Unexpected "+"', start)
video_selector = current_selector
audio_selector = _parse_format_selection(tokens, inside_merge=True)
if not video_selector or not audio_selector:
raise syntax_error('"+" must be between two format selectors', start)
current_selector = FormatSelector(MERGE, (video_selector, audio_selector), [])
else:
raise syntax_error('Operator not recognized: "{0}"'.format(string), start)
elif type == tokenize.ENDMARKER:
break
if current_selector:
selectors.append(current_selector)
return selectors
def _build_selector_function(selector):
if isinstance(selector, list):
fs = [_build_selector_function(s) for s in selector]
def selector_function(ctx):
for f in fs:
for format in f(ctx):
yield format
return selector_function
elif selector.type == GROUP:
selector_function = _build_selector_function(selector.selector)
elif selector.type == PICKFIRST:
fs = [_build_selector_function(s) for s in selector.selector]
def selector_function(ctx):
for f in fs:
picked_formats = list(f(ctx))
if picked_formats:
return picked_formats
return []
elif selector.type == SINGLE:
format_spec = selector.selector
def selector_function(ctx):
formats = list(ctx['formats'])
if not formats:
return
if format_spec == 'all':
for f in formats:
yield f
elif format_spec in ['best', 'worst', None]:
format_idx = 0 if format_spec == 'worst' else -1
audiovideo_formats = [
f for f in formats
if f.get('vcodec') != 'none' and f.get('acodec') != 'none']
if audiovideo_formats:
yield audiovideo_formats[format_idx]
# for extractors with incomplete formats (audio only (soundcloud)
# or video only (imgur)) we will fallback to best/worst
# {video,audio}-only format
elif ctx['incomplete_formats']:
yield formats[format_idx]
elif format_spec == 'bestaudio':
audio_formats = [
f for f in formats
if f.get('vcodec') == 'none']
if audio_formats:
yield audio_formats[-1]
elif format_spec == 'worstaudio':
audio_formats = [
f for f in formats
if f.get('vcodec') == 'none']
if audio_formats:
yield audio_formats[0]
elif format_spec == 'bestvideo':
video_formats = [
f for f in formats
if f.get('acodec') == 'none']
if video_formats:
yield video_formats[-1]
elif format_spec == 'worstvideo':
video_formats = [
f for f in formats
if f.get('acodec') == 'none']
if video_formats:
yield video_formats[0]
else:
extensions = ['mp4', 'flv', 'webm', '3gp', 'm4a', 'mp3', 'ogg', 'aac', 'wav']
if format_spec in extensions:
filter_f = lambda f: f['ext'] == format_spec
else:
filter_f = lambda f: f['format_id'] == format_spec
matches = list(filter(filter_f, formats))
if matches:
yield matches[-1]
elif selector.type == MERGE:
def _merge(formats_info):
format_1, format_2 = [f['format_id'] for f in formats_info]
# The first format must contain the video and the
# second the audio
if formats_info[0].get('vcodec') == 'none':
self.report_error('The first format must '
'contain the video, try using '
'"-f %s+%s"' % (format_2, format_1))
return
# Formats must be opposite (video+audio)
if formats_info[0].get('acodec') == 'none' and formats_info[1].get('acodec') == 'none':
self.report_error(
'Both formats %s and %s are video-only, you must specify "-f video+audio"'
% (format_1, format_2))
return
output_ext = (
formats_info[0]['ext']
if self.params.get('merge_output_format') is None
else self.params['merge_output_format'])
return {
'requested_formats': formats_info,
'format': '%s+%s' % (formats_info[0].get('format'),
formats_info[1].get('format')),
'format_id': '%s+%s' % (formats_info[0].get('format_id'),
formats_info[1].get('format_id')),
'width': formats_info[0].get('width'),
'height': formats_info[0].get('height'),
'resolution': formats_info[0].get('resolution'),
'fps': formats_info[0].get('fps'),
'vcodec': formats_info[0].get('vcodec'),
'vbr': formats_info[0].get('vbr'),
'stretched_ratio': formats_info[0].get('stretched_ratio'),
'acodec': formats_info[1].get('acodec'),
'abr': formats_info[1].get('abr'),
'ext': output_ext,
}
video_selector, audio_selector = map(_build_selector_function, selector.selector)
def selector_function(ctx):
for pair in itertools.product(
video_selector(copy.deepcopy(ctx)), audio_selector(copy.deepcopy(ctx))):
yield _merge(pair)
filters = [self._build_format_filter(f) for f in selector.filters]
def final_selector(ctx):
ctx_copy = copy.deepcopy(ctx)
for _filter in filters:
ctx_copy['formats'] = list(filter(_filter, ctx_copy['formats']))
return selector_function(ctx_copy)
return final_selector
stream = io.BytesIO(format_spec.encode('utf-8'))
try:
tokens = list(_remove_unused_ops(compat_tokenize_tokenize(stream.readline)))
except tokenize.TokenError:
raise syntax_error('Missing closing/opening brackets or parenthesis', (0, len(format_spec)))
class TokenIterator(object):
def __init__(self, tokens):
self.tokens = tokens
self.counter = 0
def __iter__(self):
return self
def __next__(self):
if self.counter >= len(self.tokens):
raise StopIteration()
value = self.tokens[self.counter]
self.counter += 1
return value
next = __next__
def restore_last_token(self):
self.counter -= 1
parsed_selector = _parse_format_selection(iter(TokenIterator(tokens)))
return _build_selector_function(parsed_selector)
def _calc_headers(self, info_dict):
res = std_headers.copy()
add_headers = info_dict.get('http_headers')
if add_headers:
res.update(add_headers)
cookies = self._calc_cookies(info_dict)
if cookies:
res['Cookie'] = cookies
if 'X-Forwarded-For' not in res:
x_forwarded_for_ip = info_dict.get('__x_forwarded_for_ip')
if x_forwarded_for_ip:
res['X-Forwarded-For'] = x_forwarded_for_ip
return res
def _calc_cookies(self, info_dict):
pr = sanitized_Request(info_dict['url'])
self.cookiejar.add_cookie_header(pr)
return pr.get_header('Cookie')
def process_video_result(self, info_dict, download=True):
assert info_dict.get('_type', 'video') == 'video'
if 'id' not in info_dict:
raise ExtractorError('Missing "id" field in extractor result')
if 'title' not in info_dict:
raise ExtractorError('Missing "title" field in extractor result')
def report_force_conversion(field, field_not, conversion):
self.report_warning(
'"%s" field is not %s - forcing %s conversion, there is an error in extractor'
% (field, field_not, conversion))
def sanitize_string_field(info, string_field):
field = info.get(string_field)
if field is None or isinstance(field, compat_str):
return
report_force_conversion(string_field, 'a string', 'string')
info[string_field] = compat_str(field)
def sanitize_numeric_fields(info):
for numeric_field in self._NUMERIC_FIELDS:
field = info.get(numeric_field)
if field is None or isinstance(field, compat_numeric_types):
continue
report_force_conversion(numeric_field, 'numeric', 'int')
info[numeric_field] = int_or_none(field)
sanitize_string_field(info_dict, 'id')
sanitize_numeric_fields(info_dict)
if 'playlist' not in info_dict:
# It isn't part of a playlist
info_dict['playlist'] = None
info_dict['playlist_index'] = None
thumbnails = info_dict.get('thumbnails')
if thumbnails is None:
thumbnail = info_dict.get('thumbnail')
if thumbnail:
info_dict['thumbnails'] = thumbnails = [{'url': thumbnail}]
if thumbnails:
thumbnails.sort(key=lambda t: (
t.get('preference') if t.get('preference') is not None else -1,
t.get('width') if t.get('width') is not None else -1,
t.get('height') if t.get('height') is not None else -1,
t.get('id') if t.get('id') is not None else '', t.get('url')))
for i, t in enumerate(thumbnails):
t['url'] = sanitize_url(t['url'])
if t.get('width') and t.get('height'):
t['resolution'] = '%dx%d' % (t['width'], t['height'])
if t.get('id') is None:
t['id'] = '%d' % i
if self.params.get('list_thumbnails'):
self.list_thumbnails(info_dict)
return
thumbnail = info_dict.get('thumbnail')
if thumbnail:
info_dict['thumbnail'] = sanitize_url(thumbnail)
elif thumbnails:
info_dict['thumbnail'] = thumbnails[-1]['url']
if 'display_id' not in info_dict and 'id' in info_dict:
info_dict['display_id'] = info_dict['id']
for ts_key, date_key in (
('timestamp', 'upload_date'),
('release_timestamp', 'release_date'),
):
if info_dict.get(date_key) is None and info_dict.get(ts_key) is not None:
# Working around out-of-range timestamp values (e.g. negative ones on Windows,
# see http://bugs.python.org/issue1646728)
try:
upload_date = datetime.datetime.utcfromtimestamp(info_dict[ts_key])
info_dict[date_key] = upload_date.strftime('%Y%m%d')
except (ValueError, OverflowError, OSError):
pass
# Auto generate title fields corresponding to the *_number fields when missing
# in order to always have clean titles. This is very common for TV series.
for field in ('chapter', 'season', 'episode'):
if info_dict.get('%s_number' % field) is not None and not info_dict.get(field):
info_dict[field] = '%s %d' % (field.capitalize(), info_dict['%s_number' % field])
for cc_kind in ('subtitles', 'automatic_captions'):
cc = info_dict.get(cc_kind)
if cc:
for _, subtitle in cc.items():
for subtitle_format in subtitle:
if subtitle_format.get('url'):
subtitle_format['url'] = sanitize_url(subtitle_format['url'])
if subtitle_format.get('ext') is None:
subtitle_format['ext'] = determine_ext(subtitle_format['url']).lower()
automatic_captions = info_dict.get('automatic_captions')
subtitles = info_dict.get('subtitles')
if self.params.get('listsubtitles', False):
if 'automatic_captions' in info_dict:
self.list_subtitles(
info_dict['id'], automatic_captions, 'automatic captions')
self.list_subtitles(info_dict['id'], subtitles, 'subtitles')
return
info_dict['requested_subtitles'] = self.process_subtitles(
info_dict['id'], subtitles, automatic_captions)
# We now pick which formats have to be downloaded
if info_dict.get('formats') is None:
# There's only one format available
formats = [info_dict]
else:
formats = info_dict['formats']
if not formats:
raise ExtractorError('No video formats found!')
def is_wellformed(f):
url = f.get('url')
if not url:
self.report_warning(
'"url" field is missing or empty - skipping format, '
'there is an error in extractor')
return False
if isinstance(url, bytes):
sanitize_string_field(f, 'url')
return True
# Filter out malformed formats for better extraction robustness
formats = list(filter(is_wellformed, formats))
formats_dict = {}
# We check that all the formats have the format and format_id fields
for i, format in enumerate(formats):
sanitize_string_field(format, 'format_id')
sanitize_numeric_fields(format)
format['url'] = sanitize_url(format['url'])
if not format.get('format_id'):
format['format_id'] = compat_str(i)
else:
# Sanitize format_id from characters used in format selector expression
format['format_id'] = re.sub(r'[\s,/+\[\]()]', '_', format['format_id'])
format_id = format['format_id']
if format_id not in formats_dict:
formats_dict[format_id] = []
formats_dict[format_id].append(format)
# Make sure all formats have unique format_id
for format_id, ambiguous_formats in formats_dict.items():
if len(ambiguous_formats) > 1:
for i, format in enumerate(ambiguous_formats):
format['format_id'] = '%s-%d' % (format_id, i)
for i, format in enumerate(formats):
if format.get('format') is None:
format['format'] = '{id} - {res}{note}'.format(
id=format['format_id'],
res=self.format_resolution(format),
note=' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
)
# Automatically determine file extension if missing
if format.get('ext') is None:
format['ext'] = determine_ext(format['url']).lower()
# Automatically determine protocol if missing (useful for format
# selection purposes)
if format.get('protocol') is None:
format['protocol'] = determine_protocol(format)
# Add HTTP headers, so that external programs can use them from the
# json output
full_format_info = info_dict.copy()
full_format_info.update(format)
format['http_headers'] = self._calc_headers(full_format_info)
# Remove private housekeeping stuff
if '__x_forwarded_for_ip' in info_dict:
del info_dict['__x_forwarded_for_ip']
# TODO Central sorting goes here
if formats[0] is not info_dict:
# only set the 'formats' fields if the original info_dict list them
# otherwise we end up with a circular reference, the first (and unique)
# element in the 'formats' field in info_dict is info_dict itself,
# which can't be exported to json
info_dict['formats'] = formats
if self.params.get('listformats'):
self.list_formats(info_dict)
return
req_format = self.params.get('format')
if req_format is None:
req_format = self._default_format_spec(info_dict, download=download)
if self.params.get('verbose'):
self._write_string('[debug] Default format spec: %s\n' % req_format)
format_selector = self.build_format_selector(req_format)
# While in format selection we may need to have an access to the original
# format set in order to calculate some metrics or do some processing.
# For now we need to be able to guess whether original formats provided
# by extractor are incomplete or not (i.e. whether extractor provides only
# video-only or audio-only formats) for proper formats selection for
# extractors with such incomplete formats (see
# https://github.com/ytdl-org/youtube-dl/pull/5556).
# Since formats may be filtered during format selection and may not match
# the original formats the results may be incorrect. Thus original formats
# or pre-calculated metrics should be passed to format selection routines
# as well.
# We will pass a context object containing all necessary additional data
# instead of just formats.
# This fixes incorrect format selection issue (see
# https://github.com/ytdl-org/youtube-dl/issues/10083).
incomplete_formats = (
# All formats are video-only or
all(f.get('vcodec') != 'none' and f.get('acodec') == 'none' for f in formats)
# all formats are audio-only
or all(f.get('vcodec') == 'none' and f.get('acodec') != 'none' for f in formats))
ctx = {
'formats': formats,
'incomplete_formats': incomplete_formats,
}
formats_to_download = list(format_selector(ctx))
if not formats_to_download:
raise ExtractorError('requested format not available',
expected=True)
if download:
if len(formats_to_download) > 1:
self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
for format in formats_to_download:
new_info = dict(info_dict)
new_info.update(format)
self.process_info(new_info)
# We update the info dict with the best quality format (backwards compatibility)
info_dict.update(formats_to_download[-1])
return info_dict
def process_subtitles(self, video_id, normal_subtitles, automatic_captions):
"""Select the requested subtitles and their format"""
available_subs = {}
if normal_subtitles and self.params.get('writesubtitles'):
available_subs.update(normal_subtitles)
if automatic_captions and self.params.get('writeautomaticsub'):
for lang, cap_info in automatic_captions.items():
if lang not in available_subs:
available_subs[lang] = cap_info
if (not self.params.get('writesubtitles') and not
self.params.get('writeautomaticsub') or not
available_subs):
return None
if self.params.get('allsubtitles', False):
requested_langs = available_subs.keys()
else:
if self.params.get('subtitleslangs', False):
requested_langs = self.params.get('subtitleslangs')
elif 'en' in available_subs:
requested_langs = ['en']
else:
requested_langs = [list(available_subs.keys())[0]]
formats_query = self.params.get('subtitlesformat', 'best')
formats_preference = formats_query.split('/') if formats_query else []
subs = {}
for lang in requested_langs:
formats = available_subs.get(lang)
if formats is None:
self.report_warning('%s subtitles not available for %s' % (lang, video_id))
continue
for ext in formats_preference:
if ext == 'best':
f = formats[-1]
break
matches = list(filter(lambda f: f['ext'] == ext, formats))
if matches:
f = matches[-1]
break
else:
f = formats[-1]
self.report_warning(
'No subtitle format found matching "%s" for language %s, '
'using %s' % (formats_query, lang, f['ext']))
subs[lang] = f
return subs
def __forced_printings(self, info_dict, filename, incomplete):
def print_mandatory(field):
if (self.params.get('force%s' % field, False)
and (not incomplete or info_dict.get(field) is not None)):
self.to_stdout(info_dict[field])
def print_optional(field):
if (self.params.get('force%s' % field, False)
and info_dict.get(field) is not None):
self.to_stdout(info_dict[field])
print_mandatory('title')
print_mandatory('id')
if self.params.get('forceurl', False) and not incomplete:
if info_dict.get('requested_formats') is not None:
for f in info_dict['requested_formats']:
self.to_stdout(f['url'] + f.get('play_path', ''))
else:
# For RTMP URLs, also include the playpath
self.to_stdout(info_dict['url'] + info_dict.get('play_path', ''))
print_optional('thumbnail')
print_optional('description')
if self.params.get('forcefilename', False) and filename is not None:
self.to_stdout(filename)
if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
self.to_stdout(formatSeconds(info_dict['duration']))
print_mandatory('format')
if self.params.get('forcejson', False):
self.to_stdout(json.dumps(info_dict))
def process_info(self, info_dict):
"""Process a single resolved IE result."""
assert info_dict.get('_type', 'video') == 'video'
max_downloads = self.params.get('max_downloads')
if max_downloads is not None:
if self._num_downloads >= int(max_downloads):
raise MaxDownloadsReached()
# TODO: backward compatibility, to be removed
info_dict['fulltitle'] = info_dict['title']
if 'format' not in info_dict:
info_dict['format'] = info_dict['ext']
reason = self._match_entry(info_dict, incomplete=False)
if reason is not None:
self.to_screen('[download] ' + reason)
return
self._num_downloads += 1
info_dict['_filename'] = filename = self.prepare_filename(info_dict)
# Forced printings
self.__forced_printings(info_dict, filename, incomplete=False)
# Do nothing else if in simulate mode
if self.params.get('simulate', False):
return
if filename is None:
return
def ensure_dir_exists(path):
try:
dn = os.path.dirname(path)
if dn and not os.path.exists(dn):
os.makedirs(dn)
return True
except (OSError, IOError) as err:
if isinstance(err, OSError) and err.errno == errno.EEXIST:
return True
self.report_error('unable to create directory ' + error_to_compat_str(err))
return False
if not ensure_dir_exists(sanitize_path(encodeFilename(filename))):
return
if self.params.get('writedescription', False):
descfn = replace_extension(filename, 'description', info_dict.get('ext'))
if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
self.to_screen('[info] Video description is already present')
elif info_dict.get('description') is None:
self.report_warning('There\'s no description to write.')
else:
try:
self.to_screen('[info] Writing video description to: ' + descfn)
with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
descfile.write(info_dict['description'])
except (OSError, IOError):
self.report_error('Cannot write description file ' + descfn)
return
if self.params.get('writeannotations', False):
annofn = replace_extension(filename, 'annotations.xml', info_dict.get('ext'))
if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
self.to_screen('[info] Video annotations are already present')
elif not info_dict.get('annotations'):
self.report_warning('There are no annotations to write.')
else:
try:
self.to_screen('[info] Writing video annotations to: ' + annofn)
with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
annofile.write(info_dict['annotations'])
except (KeyError, TypeError):
self.report_warning('There are no annotations to write.')
except (OSError, IOError):
self.report_error('Cannot write annotations file: ' + annofn)
return
subtitles_are_requested = any([self.params.get('writesubtitles', False),
self.params.get('writeautomaticsub')])
if subtitles_are_requested and info_dict.get('requested_subtitles'):
# subtitles download errors are already managed as troubles in relevant IE
# that way it will silently go on when used with unsupporting IE
subtitles = info_dict['requested_subtitles']
ie = self.get_info_extractor(info_dict['extractor_key'])
for sub_lang, sub_info in subtitles.items():
sub_format = sub_info['ext']
sub_filename = subtitles_filename(filename, sub_lang, sub_format, info_dict.get('ext'))
if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
self.to_screen('[info] Video subtitle %s.%s is already present' % (sub_lang, sub_format))
else:
self.to_screen('[info] Writing video subtitles to: ' + sub_filename)
if sub_info.get('data') is not None:
try:
# Use newline='' to prevent conversion of newline characters
# See https://github.com/ytdl-org/youtube-dl/issues/10268
with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8', newline='') as subfile:
subfile.write(sub_info['data'])
except (OSError, IOError):
self.report_error('Cannot write subtitles file ' + sub_filename)
return
else:
try:
sub_data = ie._request_webpage(
sub_info['url'], info_dict['id'], note=False).read()
with io.open(encodeFilename(sub_filename), 'wb') as subfile:
subfile.write(sub_data)
except (ExtractorError, IOError, OSError, ValueError) as err:
self.report_warning('Unable to download subtitle for "%s": %s' %
(sub_lang, error_to_compat_str(err)))
continue
if self.params.get('writeinfojson', False):
infofn = replace_extension(filename, 'info.json', info_dict.get('ext'))
if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
self.to_screen('[info] Video description metadata is already present')
else:
self.to_screen('[info] Writing video description metadata as JSON to: ' + infofn)
try:
write_json_file(self.filter_requested_info(info_dict), infofn)
except (OSError, IOError):
self.report_error('Cannot write metadata to JSON file ' + infofn)
return
self._write_thumbnails(info_dict, filename)
if not self.params.get('skip_download', False):
try:
def dl(name, info):
fd = get_suitable_downloader(info, self.params)(self, self.params)
for ph in self._progress_hooks:
fd.add_progress_hook(ph)
if self.params.get('verbose'):
self.to_screen('[debug] Invoking downloader on %r' % info.get('url'))
return fd.download(name, info)
if info_dict.get('requested_formats') is not None:
downloaded = []
success = True
merger = FFmpegMergerPP(self)
if not merger.available:
postprocessors = []
self.report_warning('You have requested multiple '
'formats but ffmpeg or avconv are not installed.'
' The formats won\'t be merged.')
else:
postprocessors = [merger]
def compatible_formats(formats):
video, audio = formats
# Check extension
video_ext, audio_ext = video.get('ext'), audio.get('ext')
if video_ext and audio_ext:
COMPATIBLE_EXTS = (
('mp3', 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v', 'ismv', 'isma'),
('webm')
)
for exts in COMPATIBLE_EXTS:
if video_ext in exts and audio_ext in exts:
return True
# TODO: Check acodec/vcodec
return False
filename_real_ext = os.path.splitext(filename)[1][1:]
filename_wo_ext = (
os.path.splitext(filename)[0]
if filename_real_ext == info_dict['ext']
else filename)
requested_formats = info_dict['requested_formats']
if self.params.get('merge_output_format') is None and not compatible_formats(requested_formats):
info_dict['ext'] = 'mkv'
self.report_warning(
'Requested formats are incompatible for merge and will be merged into mkv.')
# Ensure filename always has a correct extension for successful merge
filename = '%s.%s' % (filename_wo_ext, info_dict['ext'])
if os.path.exists(encodeFilename(filename)):
self.to_screen(
'[download] %s has already been downloaded and '
'merged' % filename)
else:
for f in requested_formats:
new_info = dict(info_dict)
new_info.update(f)
fname = prepend_extension(
self.prepare_filename(new_info),
'f%s' % f['format_id'], new_info['ext'])
if not ensure_dir_exists(fname):
return
downloaded.append(fname)
partial_success = dl(fname, new_info)
success = success and partial_success
info_dict['__postprocessors'] = postprocessors
info_dict['__files_to_merge'] = downloaded
else:
# Just a single file
success = dl(filename, info_dict)
except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
self.report_error('unable to download video data: %s' % error_to_compat_str(err))
return
except (OSError, IOError) as err:
raise UnavailableVideoError(err)
except (ContentTooShortError, ) as err:
self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
return
if success and filename != '-':
# Fixup content
fixup_policy = self.params.get('fixup')
if fixup_policy is None:
fixup_policy = 'detect_or_warn'
INSTALL_FFMPEG_MESSAGE = 'Install ffmpeg or avconv to fix this automatically.'
stretched_ratio = info_dict.get('stretched_ratio')
if stretched_ratio is not None and stretched_ratio != 1:
if fixup_policy == 'warn':
self.report_warning('%s: Non-uniform pixel ratio (%s)' % (
info_dict['id'], stretched_ratio))
elif fixup_policy == 'detect_or_warn':
stretched_pp = FFmpegFixupStretchedPP(self)
if stretched_pp.available:
info_dict.setdefault('__postprocessors', [])
info_dict['__postprocessors'].append(stretched_pp)
else:
self.report_warning(
'%s: Non-uniform pixel ratio (%s). %s'
% (info_dict['id'], stretched_ratio, INSTALL_FFMPEG_MESSAGE))
else:
assert fixup_policy in ('ignore', 'never')
if (info_dict.get('requested_formats') is None
and info_dict.get('container') == 'm4a_dash'):
if fixup_policy == 'warn':
self.report_warning(
'%s: writing DASH m4a. '
'Only some players support this container.'
% info_dict['id'])
elif fixup_policy == 'detect_or_warn':
fixup_pp = FFmpegFixupM4aPP(self)
if fixup_pp.available:
info_dict.setdefault('__postprocessors', [])
info_dict['__postprocessors'].append(fixup_pp)
else:
self.report_warning(
'%s: writing DASH m4a. '
'Only some players support this container. %s'
% (info_dict['id'], INSTALL_FFMPEG_MESSAGE))
else:
assert fixup_policy in ('ignore', 'never')
if (info_dict.get('protocol') == 'm3u8_native'
or info_dict.get('protocol') == 'm3u8'
and self.params.get('hls_prefer_native')):
if fixup_policy == 'warn':
self.report_warning('%s: malformed AAC bitstream detected.' % (
info_dict['id']))
elif fixup_policy == 'detect_or_warn':
fixup_pp = FFmpegFixupM3u8PP(self)
if fixup_pp.available:
info_dict.setdefault('__postprocessors', [])
info_dict['__postprocessors'].append(fixup_pp)
else:
self.report_warning(
'%s: malformed AAC bitstream detected. %s'
% (info_dict['id'], INSTALL_FFMPEG_MESSAGE))
else:
assert fixup_policy in ('ignore', 'never')
try:
self.post_process(filename, info_dict)
except (PostProcessingError) as err:
self.report_error('postprocessing: %s' % str(err))
return
self.record_download_archive(info_dict)
def download(self, url_list):
"""Download a given list of URLs."""
outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
if (len(url_list) > 1
and outtmpl != '-'
and '%' not in outtmpl
and self.params.get('max_downloads') != 1):
raise SameFileError(outtmpl)
for url in url_list:
try:
# It also downloads the videos
res = self.extract_info(
url, force_generic_extractor=self.params.get('force_generic_extractor', False))
except UnavailableVideoError:
self.report_error('unable to download video')
except MaxDownloadsReached:
self.to_screen('[info] Maximum number of downloaded files reached.')
raise
else:
if self.params.get('dump_single_json', False):
self.to_stdout(json.dumps(res))
return self._download_retcode
def download_with_info_file(self, info_filename):
with contextlib.closing(fileinput.FileInput(
[info_filename], mode='r',
openhook=fileinput.hook_encoded('utf-8'))) as f:
# FileInput doesn't have a read method, we can't call json.load
info = self.filter_requested_info(json.loads('\n'.join(f)))
try:
self.process_ie_result(info, download=True)
except DownloadError:
webpage_url = info.get('webpage_url')
if webpage_url is not None:
self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
return self.download([webpage_url])
else:
raise
return self._download_retcode
@staticmethod
def filter_requested_info(info_dict):
return dict(
(k, v) for k, v in info_dict.items()
if k not in ['requested_formats', 'requested_subtitles'])
def post_process(self, filename, ie_info):
"""Run all the postprocessors on the given file."""
info = dict(ie_info)
info['filepath'] = filename
pps_chain = []
if ie_info.get('__postprocessors') is not None:
pps_chain.extend(ie_info['__postprocessors'])
pps_chain.extend(self._pps)
for pp in pps_chain:
files_to_delete = []
try:
files_to_delete, info = pp.run(info)
except PostProcessingError as e:
self.report_error(e.msg)
if files_to_delete and not self.params.get('keepvideo', False):
for old_filename in files_to_delete:
self.to_screen('Deleting original file %s (pass -k to keep)' % old_filename)
try:
os.remove(encodeFilename(old_filename))
except (IOError, OSError):
self.report_warning('Unable to remove downloaded original file')
def _make_archive_id(self, info_dict):
video_id = info_dict.get('id')
if not video_id:
return
# Future-proof against any change in case
# and backwards compatibility with prior versions
extractor = info_dict.get('extractor_key') or info_dict.get('ie_key') # key in a playlist
if extractor is None:
url = str_or_none(info_dict.get('url'))
if not url:
return
# Try to find matching extractor for the URL and take its ie_key
for ie in self._ies:
if ie.suitable(url):
extractor = ie.ie_key()
break
else:
return
return extractor.lower() + ' ' + video_id
def in_download_archive(self, info_dict):
fn = self.params.get('download_archive')
if fn is None:
return False
vid_id = self._make_archive_id(info_dict)
if not vid_id:
return False # Incomplete video information
try:
with locked_file(fn, 'r', encoding='utf-8') as archive_file:
for line in archive_file:
if line.strip() == vid_id:
return True
except IOError as ioe:
if ioe.errno != errno.ENOENT:
raise
return False
def record_download_archive(self, info_dict):
fn = self.params.get('download_archive')
if fn is None:
return
vid_id = self._make_archive_id(info_dict)
assert vid_id
with locked_file(fn, 'a', encoding='utf-8') as archive_file:
archive_file.write(vid_id + '\n')
@staticmethod
def format_resolution(format, default='unknown'):
if format.get('vcodec') == 'none':
return 'audio only'
if format.get('resolution') is not None:
return format['resolution']
if format.get('height') is not None:
if format.get('width') is not None:
res = '%sx%s' % (format['width'], format['height'])
else:
res = '%sp' % format['height']
elif format.get('width') is not None:
res = '%dx?' % format['width']
else:
res = default
return res
def _format_note(self, fdict):
res = ''
if fdict.get('ext') in ['f4f', 'f4m']:
res += '(unsupported) '
if fdict.get('language'):
if res:
res += ' '
res += '[%s] ' % fdict['language']
if fdict.get('format_note') is not None:
res += fdict['format_note'] + ' '
if fdict.get('tbr') is not None:
res += '%4dk ' % fdict['tbr']
if fdict.get('container') is not None:
if res:
res += ', '
res += '%s container' % fdict['container']
if (fdict.get('vcodec') is not None
and fdict.get('vcodec') != 'none'):
if res:
res += ', '
res += fdict['vcodec']
if fdict.get('vbr') is not None:
res += '@'
elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
res += 'video@'
if fdict.get('vbr') is not None:
res += '%4dk' % fdict['vbr']
if fdict.get('fps') is not None:
if res:
res += ', '
res += '%sfps' % fdict['fps']
if fdict.get('acodec') is not None:
if res:
res += ', '
if fdict['acodec'] == 'none':
res += 'video only'
else:
res += '%-5s' % fdict['acodec']
elif fdict.get('abr') is not None:
if res:
res += ', '
res += 'audio'
if fdict.get('abr') is not None:
res += '@%3dk' % fdict['abr']
if fdict.get('asr') is not None:
res += ' (%5dHz)' % fdict['asr']
if fdict.get('filesize') is not None:
if res:
res += ', '
res += format_bytes(fdict['filesize'])
elif fdict.get('filesize_approx') is not None:
if res:
res += ', '
res += '~' + format_bytes(fdict['filesize_approx'])
return res
def list_formats(self, info_dict):
formats = info_dict.get('formats', [info_dict])
table = [
[f['format_id'], f['ext'], self.format_resolution(f), self._format_note(f)]
for f in formats
if f.get('preference') is None or f['preference'] >= -1000]
if len(formats) > 1:
table[-1][-1] += (' ' if table[-1][-1] else '') + '(best)'
header_line = ['format code', 'extension', 'resolution', 'note']
self.to_screen(
'[info] Available formats for %s:\n%s' %
(info_dict['id'], render_table(header_line, table)))
def list_thumbnails(self, info_dict):
thumbnails = info_dict.get('thumbnails')
if not thumbnails:
self.to_screen('[info] No thumbnails present for %s' % info_dict['id'])
return
self.to_screen(
'[info] Thumbnails for %s:' % info_dict['id'])
self.to_screen(render_table(
['ID', 'width', 'height', 'URL'],
[[t['id'], t.get('width', 'unknown'), t.get('height', 'unknown'), t['url']] for t in thumbnails]))
def list_subtitles(self, video_id, subtitles, name='subtitles'):
if not subtitles:
self.to_screen('%s has no %s' % (video_id, name))
return
self.to_screen(
'Available %s for %s:' % (name, video_id))
self.to_screen(render_table(
['Language', 'formats'],
[[lang, ', '.join(f['ext'] for f in reversed(formats))]
for lang, formats in subtitles.items()]))
def urlopen(self, req):
""" Start an HTTP download """
if isinstance(req, compat_basestring):
req = sanitized_Request(req)
return self._opener.open(req, timeout=self._socket_timeout)
def print_debug_header(self):
if not self.params.get('verbose'):
return
if type('') is not compat_str:
# Python 2.6 on SLES11 SP1 (https://github.com/ytdl-org/youtube-dl/issues/3326)
self.report_warning(
'Your Python is broken! Update to a newer and supported version')
stdout_encoding = getattr(
sys.stdout, 'encoding', 'missing (%s)' % type(sys.stdout).__name__)
encoding_str = (
'[debug] Encodings: locale %s, fs %s, out %s, pref %s\n' % (
locale.getpreferredencoding(),
sys.getfilesystemencoding(),
stdout_encoding,
self.get_encoding()))
write_string(encoding_str, encoding=None)
self._write_string('[debug] youtube-dl version ' + __version__ + '\n')
if _LAZY_LOADER:
self._write_string('[debug] Lazy loading extractors enabled' + '\n')
try:
sp = subprocess.Popen(
['git', 'rev-parse', '--short', 'HEAD'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
cwd=os.path.dirname(os.path.abspath(__file__)))
out, err = sp.communicate()
out = out.decode().strip()
if re.match('[0-9a-f]+', out):
self._write_string('[debug] Git HEAD: ' + out + '\n')
except Exception:
try:
sys.exc_clear()
except Exception:
pass
def python_implementation():
impl_name = platform.python_implementation()
if impl_name == 'PyPy' and hasattr(sys, 'pypy_version_info'):
return impl_name + ' version %d.%d.%d' % sys.pypy_version_info[:3]
return impl_name
self._write_string('[debug] Python version %s (%s) - %s\n' % (
platform.python_version(), python_implementation(),
platform_name()))
exe_versions = FFmpegPostProcessor.get_versions(self)
exe_versions['rtmpdump'] = rtmpdump_version()
exe_versions['phantomjs'] = PhantomJSwrapper._version()
exe_str = ', '.join(
'%s %s' % (exe, v)
for exe, v in sorted(exe_versions.items())
if v
)
if not exe_str:
exe_str = 'none'
self._write_string('[debug] exe versions: %s\n' % exe_str)
proxy_map = {}
for handler in self._opener.handlers:
if hasattr(handler, 'proxies'):
proxy_map.update(handler.proxies)
self._write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
if self.params.get('call_home', False):
ipaddr = self.urlopen('https://yt-dl.org/ip').read().decode('utf-8')
self._write_string('[debug] Public IP address: %s\n' % ipaddr)
latest_version = self.urlopen(
'https://yt-dl.org/latest/version').read().decode('utf-8')
if version_tuple(latest_version) > version_tuple(__version__):
self.report_warning(
'You are using an outdated version (newest version: %s)! '
'See https://yt-dl.org/update if you need help updating.' %
latest_version)
def _setup_opener(self):
timeout_val = self.params.get('socket_timeout')
self._socket_timeout = 600 if timeout_val is None else float(timeout_val)
opts_cookiefile = self.params.get('cookiefile')
opts_proxy = self.params.get('proxy')
if opts_cookiefile is None:
self.cookiejar = compat_cookiejar.CookieJar()
else:
opts_cookiefile = expand_path(opts_cookiefile)
self.cookiejar = YoutubeDLCookieJar(opts_cookiefile)
if os.access(opts_cookiefile, os.R_OK):
self.cookiejar.load(ignore_discard=True, ignore_expires=True)
cookie_processor = YoutubeDLCookieProcessor(self.cookiejar)
if opts_proxy is not None:
if opts_proxy == '':
proxies = {}
else:
proxies = {'http': opts_proxy, 'https': opts_proxy}
else:
proxies = compat_urllib_request.getproxies()
# Set HTTPS proxy to HTTP one if given (https://github.com/ytdl-org/youtube-dl/issues/805)
if 'http' in proxies and 'https' not in proxies:
proxies['https'] = proxies['http']
proxy_handler = PerRequestProxyHandler(proxies)
debuglevel = 1 if self.params.get('debug_printtraffic') else 0
https_handler = make_HTTPS_handler(self.params, debuglevel=debuglevel)
ydlh = YoutubeDLHandler(self.params, debuglevel=debuglevel)
redirect_handler = YoutubeDLRedirectHandler()
data_handler = compat_urllib_request_DataHandler()
# When passing our own FileHandler instance, build_opener won't add the
# default FileHandler and allows us to disable the file protocol, which
# can be used for malicious purposes (see
# https://github.com/ytdl-org/youtube-dl/issues/8227)
file_handler = compat_urllib_request.FileHandler()
def file_open(*args, **kwargs):
raise compat_urllib_error.URLError('file:// scheme is explicitly disabled in youtube-dl for security reasons')
file_handler.file_open = file_open
opener = compat_urllib_request.build_opener(
proxy_handler, https_handler, cookie_processor, ydlh, redirect_handler, data_handler, file_handler)
# Delete the default user-agent header, which would otherwise apply in
# cases where our custom HTTP handler doesn't come into play
# (See https://github.com/ytdl-org/youtube-dl/issues/1309 for details)
opener.addheaders = []
self._opener = opener
def encode(self, s):
if isinstance(s, bytes):
return s # Already encoded
try:
return s.encode(self.get_encoding())
except UnicodeEncodeError as err:
err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
raise
def get_encoding(self):
encoding = self.params.get('encoding')
if encoding is None:
encoding = preferredencoding()
return encoding
def _write_thumbnails(self, info_dict, filename):
if self.params.get('writethumbnail', False):
thumbnails = info_dict.get('thumbnails')
if thumbnails:
thumbnails = [thumbnails[-1]]
elif self.params.get('write_all_thumbnails', False):
thumbnails = info_dict.get('thumbnails')
else:
return
if not thumbnails:
# No thumbnails present, so return immediately
return
for t in thumbnails:
thumb_ext = determine_ext(t['url'], 'jpg')
suffix = '_%s' % t['id'] if len(thumbnails) > 1 else ''
thumb_display_id = '%s ' % t['id'] if len(thumbnails) > 1 else ''
t['filename'] = thumb_filename = replace_extension(filename + suffix, thumb_ext, info_dict.get('ext'))
if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
self.to_screen('[%s] %s: Thumbnail %sis already present' %
(info_dict['extractor'], info_dict['id'], thumb_display_id))
else:
self.to_screen('[%s] %s: Downloading thumbnail %s...' %
(info_dict['extractor'], info_dict['id'], thumb_display_id))
try:
uf = self.urlopen(t['url'])
with open(encodeFilename(thumb_filename), 'wb') as thumbf:
shutil.copyfileobj(uf, thumbf)
self.to_screen('[%s] %s: Writing thumbnail %sto: %s' %
(info_dict['extractor'], info_dict['id'], thumb_display_id, thumb_filename))
except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
self.report_warning('Unable to download thumbnail "%s": %s' %
(t['url'], error_to_compat_str(err)))
| 45.727679 | 194 | 0.557267 |
from __future__ import absolute_import, unicode_literals
import collections
import contextlib
import copy
import datetime
import errno
import fileinput
import io
import itertools
import json
import locale
import operator
import os
import platform
import re
import shutil
import subprocess
import socket
import sys
import time
import tokenize
import traceback
import random
from string import ascii_letters
from .compat import (
compat_basestring,
compat_cookiejar,
compat_get_terminal_size,
compat_http_client,
compat_kwargs,
compat_numeric_types,
compat_os_name,
compat_str,
compat_tokenize_tokenize,
compat_urllib_error,
compat_urllib_request,
compat_urllib_request_DataHandler,
)
from .utils import (
age_restricted,
args_to_str,
ContentTooShortError,
date_from_str,
DateRange,
DEFAULT_OUTTMPL,
determine_ext,
determine_protocol,
DownloadError,
encode_compat_str,
encodeFilename,
error_to_compat_str,
expand_path,
ExtractorError,
format_bytes,
formatSeconds,
GeoRestrictedError,
int_or_none,
ISO3166Utils,
locked_file,
make_HTTPS_handler,
MaxDownloadsReached,
orderedSet,
PagedList,
parse_filesize,
PerRequestProxyHandler,
platform_name,
PostProcessingError,
preferredencoding,
prepend_extension,
register_socks_protocols,
render_table,
replace_extension,
SameFileError,
sanitize_filename,
sanitize_path,
sanitize_url,
sanitized_Request,
std_headers,
str_or_none,
subtitles_filename,
UnavailableVideoError,
url_basename,
version_tuple,
write_json_file,
write_string,
YoutubeDLCookieJar,
YoutubeDLCookieProcessor,
YoutubeDLHandler,
YoutubeDLRedirectHandler,
)
from .cache import Cache
from .extractor import get_info_extractor, gen_extractor_classes, _LAZY_LOADER
from .extractor.openload import PhantomJSwrapper
from .downloader import get_suitable_downloader
from .downloader.rtmp import rtmpdump_version
from .postprocessor import (
FFmpegFixupM3u8PP,
FFmpegFixupM4aPP,
FFmpegFixupStretchedPP,
FFmpegMergerPP,
FFmpegPostProcessor,
get_postprocessor,
)
from .version import __version__
if compat_os_name == 'nt':
import ctypes
class YoutubeDL(object):
_NUMERIC_FIELDS = set((
'width', 'height', 'tbr', 'abr', 'asr', 'vbr', 'fps', 'filesize', 'filesize_approx',
'timestamp', 'upload_year', 'upload_month', 'upload_day',
'duration', 'view_count', 'like_count', 'dislike_count', 'repost_count',
'average_rating', 'comment_count', 'age_limit',
'start_time', 'end_time',
'chapter_number', 'season_number', 'episode_number',
'track_number', 'disc_number', 'release_year',
'playlist_index',
))
params = None
_ies = []
_pps = []
_download_retcode = None
_num_downloads = None
_playlist_level = 0
_playlist_urls = set()
_screen_file = None
def __init__(self, params=None, auto_init=True):
if params is None:
params = {}
self._ies = []
self._ies_instances = {}
self._pps = []
self._progress_hooks = []
self._download_retcode = 0
self._num_downloads = 0
self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
self._err_file = sys.stderr
self.params = {
'nocheckcertificate': False,
}
self.params.update(params)
self.cache = Cache(self)
def check_deprecated(param, option, suggestion):
if self.params.get(param) is not None:
self.report_warning(
'%s is deprecated. Use %s instead.' % (option, suggestion))
return True
return False
if check_deprecated('cn_verification_proxy', '--cn-verification-proxy', '--geo-verification-proxy'):
if self.params.get('geo_verification_proxy') is None:
self.params['geo_verification_proxy'] = self.params['cn_verification_proxy']
check_deprecated('autonumber_size', '--autonumber-size', 'output template with %(autonumber)0Nd, where N in the number of digits')
check_deprecated('autonumber', '--auto-number', '-o "%(autonumber)s-%(title)s.%(ext)s"')
check_deprecated('usetitle', '--title', '-o "%(title)s-%(id)s.%(ext)s"')
if params.get('bidi_workaround', False):
try:
import pty
master, slave = pty.openpty()
width = compat_get_terminal_size().columns
if width is None:
width_args = []
else:
width_args = ['-w', str(width)]
sp_kwargs = dict(
stdin=subprocess.PIPE,
stdout=slave,
stderr=self._err_file)
try:
self._output_process = subprocess.Popen(
['bidiv'] + width_args, **sp_kwargs
)
except OSError:
self._output_process = subprocess.Popen(
['fribidi', '-c', 'UTF-8'] + width_args, **sp_kwargs)
self._output_channel = os.fdopen(master, 'rb')
except OSError as ose:
if ose.errno == errno.ENOENT:
self.report_warning('Could not find fribidi executable, ignoring --bidi-workaround . Make sure that fribidi is an executable file in one of the directories in your $PATH.')
else:
raise
if (sys.platform != 'win32'
and sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968']
and not params.get('restrictfilenames', False)):
ort_warning(
'Assuming --restrict-filenames since file system encoding '
'cannot encode all characters. '
'Set the LC_ALL environment variable to fix this.')
self.params['restrictfilenames'] = True
if isinstance(params.get('outtmpl'), bytes):
self.report_warning(
'Parameter outtmpl is bytes, but should be a unicode string. '
'Put from __future__ import unicode_literals at the top of your code file or consider switching to Python 3.x.')
self._setup_opener()
if auto_init:
self.print_debug_header()
self.add_default_info_extractors()
for pp_def_raw in self.params.get('postprocessors', []):
pp_class = get_postprocessor(pp_def_raw['key'])
pp_def = dict(pp_def_raw)
del pp_def['key']
pp = pp_class(self, **compat_kwargs(pp_def))
self.add_post_processor(pp)
for ph in self.params.get('progress_hooks', []):
self.add_progress_hook(ph)
register_socks_protocols()
def warn_if_short_id(self, argv):
idxs = [
i for i, a in enumerate(argv)
if re.match(r'^-[0-9A-Za-z_-]{10}$', a)]
if idxs:
correct_argv = (
['youtube-dl']
+ [a for i, a in enumerate(argv) if i not in idxs]
+ ['--'] + [argv[i] for i in idxs]
)
self.report_warning(
'Long argument string detected. '
'Use -- to separate parameters and URLs, like this:\n%s\n' %
args_to_str(correct_argv))
def add_info_extractor(self, ie):
self._ies.append(ie)
if not isinstance(ie, type):
self._ies_instances[ie.ie_key()] = ie
ie.set_downloader(self)
def get_info_extractor(self, ie_key):
ie = self._ies_instances.get(ie_key)
if ie is None:
ie = get_info_extractor(ie_key)()
self.add_info_extractor(ie)
return ie
def add_default_info_extractors(self):
for ie in gen_extractor_classes():
self.add_info_extractor(ie)
def add_post_processor(self, pp):
self._pps.append(pp)
pp.set_downloader(self)
def add_progress_hook(self, ph):
self._progress_hooks.append(ph)
def _bidi_workaround(self, message):
if not hasattr(self, '_output_channel'):
return message
assert hasattr(self, '_output_process')
assert isinstance(message, compat_str)
line_count = message.count('\n') + 1
self._output_process.stdin.write((message + '\n').encode('utf-8'))
self._output_process.stdin.flush()
res = ''.join(self._output_channel.readline().decode('utf-8')
for _ in range(line_count))
return res[:-len('\n')]
def to_screen(self, message, skip_eol=False):
return self.to_stdout(message, skip_eol, check_quiet=True)
def _write_string(self, s, out=None):
write_string(s, out=out, encoding=self.params.get('encoding'))
def to_stdout(self, message, skip_eol=False, check_quiet=False):
if self.params.get('logger'):
self.params['logger'].debug(message)
elif not check_quiet or not self.params.get('quiet', False):
message = self._bidi_workaround(message)
terminator = ['\n', ''][skip_eol]
output = message + terminator
self._write_string(output, self._screen_file)
def to_stderr(self, message):
assert isinstance(message, compat_str)
if self.params.get('logger'):
self.params['logger'].error(message)
else:
message = self._bidi_workaround(message)
output = message + '\n'
self._write_string(output, self._err_file)
def to_console_title(self, message):
if not self.params.get('consoletitle', False):
return
if compat_os_name == 'nt':
if ctypes.windll.kernel32.GetConsoleWindow():
ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
elif 'TERM' in os.environ:
self._write_string('\033]0;%s\007' % message, self._screen_file)
def save_console_title(self):
if not self.params.get('consoletitle', False):
return
if self.params.get('simulate', False):
return
if compat_os_name != 'nt' and 'TERM' in os.environ:
self._write_string('\033[22;0t', self._screen_file)
def restore_console_title(self):
if not self.params.get('consoletitle', False):
return
if self.params.get('simulate', False):
return
if compat_os_name != 'nt' and 'TERM' in os.environ:
self._write_string('\033[23;0t', self._screen_file)
def __enter__(self):
self.save_console_title()
return self
def __exit__(self, *args):
self.restore_console_title()
if self.params.get('cookiefile') is not None:
self.cookiejar.save(ignore_discard=True, ignore_expires=True)
def trouble(self, message=None, tb=None):
if message is not None:
self.to_stderr(message)
if self.params.get('verbose'):
if tb is None:
if sys.exc_info()[0]:
tb = ''
if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
tb += encode_compat_str(traceback.format_exc())
else:
tb_data = traceback.format_list(traceback.extract_stack())
tb = ''.join(tb_data)
self.to_stderr(tb)
if not self.params.get('ignoreerrors', False):
if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
exc_info = sys.exc_info()[1].exc_info
else:
exc_info = sys.exc_info()
raise DownloadError(message, exc_info)
self._download_retcode = 1
def report_warning(self, message):
if self.params.get('logger') is not None:
self.params['logger'].warning(message)
else:
if self.params.get('no_warnings'):
return
if not self.params.get('no_color') and self._err_file.isatty() and compat_os_name != 'nt':
_msg_header = '\033[0;33mWARNING:\033[0m'
else:
_msg_header = 'WARNING:'
warning_message = '%s %s' % (_msg_header, message)
self.to_stderr(warning_message)
def report_error(self, message, tb=None):
if not self.params.get('no_color') and self._err_file.isatty() and compat_os_name != 'nt':
_msg_header = '\033[0;31mERROR:\033[0m'
else:
_msg_header = 'ERROR:'
error_message = '%s %s' % (_msg_header, message)
self.trouble(error_message, tb)
def report_file_already_downloaded(self, file_name):
try:
self.to_screen('[download] %s has already been downloaded' % file_name)
except UnicodeEncodeError:
self.to_screen('[download] The file has already been downloaded')
def prepare_filename(self, info_dict):
try:
template_dict = dict(info_dict)
template_dict['epoch'] = int(time.time())
autonumber_size = self.params.get('autonumber_size')
if autonumber_size is None:
autonumber_size = 5
template_dict['autonumber'] = self.params.get('autonumber_start', 1) - 1 + self._num_downloads
if template_dict.get('resolution') is None:
if template_dict.get('width') and template_dict.get('height'):
template_dict['resolution'] = '%dx%d' % (template_dict['width'], template_dict['height'])
elif template_dict.get('height'):
template_dict['resolution'] = '%sp' % template_dict['height']
elif template_dict.get('width'):
template_dict['resolution'] = '%dx?' % template_dict['width']
sanitize = lambda k, v: sanitize_filename(
compat_str(v),
restricted=self.params.get('restrictfilenames'),
is_id=(k == 'id' or k.endswith('_id')))
template_dict = dict((k, v if isinstance(v, compat_numeric_types) else sanitize(k, v))
for k, v in template_dict.items()
if v is not None and not isinstance(v, (list, tuple, dict)))
template_dict = collections.defaultdict(lambda: self.params.get('outtmpl_na_placeholder', 'NA'), template_dict)
outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
field_size_compat_map = {
'playlist_index': len(str(template_dict['n_entries'])),
'autonumber': autonumber_size,
}
FIELD_SIZE_COMPAT_RE = r'(?<!%)%\((?P<field>autonumber|playlist_index)\)s'
mobj = re.search(FIELD_SIZE_COMPAT_RE, outtmpl)
if mobj:
outtmpl = re.sub(
FIELD_SIZE_COMPAT_RE,
r'%%(\1)0%dd' % field_size_compat_map[mobj.group('field')],
outtmpl)
for numeric_field in self._NUMERIC_FIELDS:
if numeric_field not in template_dict:
FORMAT_RE = r'''(?x)
(?<!%)
%
\({0}\) # mapping key
(?:[#0\-+ ]+)? # conversion flags (optional)
(?:\d+)? # minimum field width (optional)
(?:\.\d+)? # precision (optional)
[hlL]? # length modifier (optional)
[diouxXeEfFgGcrs%] # conversion type
'''
outtmpl = re.sub(
FORMAT_RE.format(numeric_field),
r'%({0})s'.format(numeric_field), outtmpl)
sep = ''.join([random.choice(ascii_letters) for _ in range(32)])
outtmpl = outtmpl.replace('%%', '%{0}%'.format(sep)).replace('$$', '${0}$'.format(sep))
# because meta fields may contain env variables we don't want to
filename = expand_path(outtmpl).replace(sep, '') % template_dict
# filename = os.path.join('out', filename)
# print('hychu, The filename is {%s}.{%s}' % (outtmpl, filename))
# Temporary fix for #4787
# 'Treat' all problem characters by passing filename through preferredencoding
# to workaround encoding issues with subprocess on python2 @ Windows
if sys.version_info < (3, 0) and sys.platform == 'win32':
filename = encodeFilename(filename, True).decode(preferredencoding())
return sanitize_path(filename)
except ValueError as err:
self.report_error('Error in output template: ' + str(err) + ' (encoding: ' + repr(preferredencoding()) + ')')
return None
def _match_entry(self, info_dict, incomplete):
video_title = info_dict.get('title', info_dict.get('id', 'video'))
if 'title' in info_dict:
# This can happen when we're just evaluating the playlist
title = info_dict['title']
matchtitle = self.params.get('matchtitle', False)
if matchtitle:
if not re.search(matchtitle, title, re.IGNORECASE):
return '"' + title + '" title did not match pattern "' + matchtitle + '"'
rejecttitle = self.params.get('rejecttitle', False)
if rejecttitle:
if re.search(rejecttitle, title, re.IGNORECASE):
return '"' + title + '" title matched reject pattern "' + rejecttitle + '"'
date = info_dict.get('upload_date')
if date is not None:
dateRange = self.params.get('daterange', DateRange())
if date not in dateRange:
return '%s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
view_count = info_dict.get('view_count')
if view_count is not None:
min_views = self.params.get('min_views')
if min_views is not None and view_count < min_views:
return 'Skipping %s, because it has not reached minimum view count (%d/%d)' % (video_title, view_count, min_views)
max_views = self.params.get('max_views')
if max_views is not None and view_count > max_views:
return 'Skipping %s, because it has exceeded the maximum view count (%d/%d)' % (video_title, view_count, max_views)
if age_restricted(info_dict.get('age_limit'), self.params.get('age_limit')):
return 'Skipping "%s" because it is age restricted' % video_title
if self.in_download_archive(info_dict):
return '%s has already been recorded in archive' % video_title
if not incomplete:
match_filter = self.params.get('match_filter')
if match_filter is not None:
ret = match_filter(info_dict)
if ret is not None:
return ret
return None
@staticmethod
def add_extra_info(info_dict, extra_info):
for key, value in extra_info.items():
info_dict.setdefault(key, value)
def extract_info(self, url, download=True, ie_key=None, extra_info={},
process=True, force_generic_extractor=False):
if not ie_key and force_generic_extractor:
ie_key = 'Generic'
if ie_key:
ies = [self.get_info_extractor(ie_key)]
else:
ies = self._ies
for ie in ies:
if not ie.suitable(url):
continue
ie = self.get_info_extractor(ie.ie_key())
if not ie.working():
self.report_warning('The program functionality for this site has been marked as broken, '
'and will probably not work.')
return self.__extract_info(url, ie, download, extra_info, process)
else:
self.report_error('no suitable InfoExtractor for URL %s' % url)
def __handle_extraction_exceptions(func):
def wrapper(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except GeoRestrictedError as e:
msg = e.msg
if e.countries:
msg += '\nThis video is available in %s.' % ', '.join(
map(ISO3166Utils.short2full, e.countries))
msg += '\nYou might want to use a VPN or a proxy server (with --proxy) to workaround.'
self.report_error(msg)
except ExtractorError as e:
self.report_error(compat_str(e), e.format_traceback())
except MaxDownloadsReached:
raise
except Exception as e:
if self.params.get('ignoreerrors', False):
self.report_error(error_to_compat_str(e), tb=encode_compat_str(traceback.format_exc()))
else:
raise
return wrapper
@__handle_extraction_exceptions
def __extract_info(self, url, ie, download, extra_info, process):
ie_result = ie.extract(url)
if ie_result is None:
return
if isinstance(ie_result, list):
ie_result = {
'_type': 'compat_list',
'entries': ie_result,
}
self.add_default_extra_info(ie_result, ie, url)
if process:
return self.process_ie_result(ie_result, download, extra_info)
else:
return ie_result
def add_default_extra_info(self, ie_result, ie, url):
self.add_extra_info(ie_result, {
'extractor': ie.IE_NAME,
'webpage_url': url,
'webpage_url_basename': url_basename(url),
'extractor_key': ie.ie_key(),
})
def process_ie_result(self, ie_result, download=True, extra_info={}):
result_type = ie_result.get('_type', 'video')
if result_type in ('url', 'url_transparent'):
ie_result['url'] = sanitize_url(ie_result['url'])
extract_flat = self.params.get('extract_flat', False)
if ((extract_flat == 'in_playlist' and 'playlist' in extra_info)
or extract_flat is True):
self.__forced_printings(
ie_result, self.prepare_filename(ie_result),
incomplete=True)
return ie_result
if result_type == 'video':
self.add_extra_info(ie_result, extra_info)
return self.process_video_result(ie_result, download=download)
elif result_type == 'url':
return self.extract_info(ie_result['url'],
download,
ie_key=ie_result.get('ie_key'),
extra_info=extra_info)
elif result_type == 'url_transparent':
info = self.extract_info(
ie_result['url'], ie_key=ie_result.get('ie_key'),
extra_info=extra_info, download=False, process=False)
# in this case
if not info:
return info
force_properties = dict(
(k, v) for k, v in ie_result.items() if v is not None)
for f in ('_type', 'url', 'id', 'extractor', 'extractor_key', 'ie_key'):
if f in force_properties:
del force_properties[f]
new_result = info.copy()
new_result.update(force_properties)
# Extracted info may not be a video result (i.e.
# info.get('_type', 'video') != video) but rather an url or
# url_transparent. In such cases outer metadata (from ie_result)
# should be propagated to inner one (info). For this to happen
# _type of info should be overridden with url_transparent. This
# fixes issue from https://github.com/ytdl-org/youtube-dl/pull/11163.
if new_result.get('_type') == 'url':
new_result['_type'] = 'url_transparent'
return self.process_ie_result(
new_result, download=download, extra_info=extra_info)
elif result_type in ('playlist', 'multi_video'):
# Protect from infinite recursion due to recursively nested playlists
# (see https://github.com/ytdl-org/youtube-dl/issues/27833)
webpage_url = ie_result['webpage_url']
if webpage_url in self._playlist_urls:
self.to_screen(
'[download] Skipping already downloaded playlist: %s'
% ie_result.get('title') or ie_result.get('id'))
return
self._playlist_level += 1
self._playlist_urls.add(webpage_url)
try:
return self.__process_playlist(ie_result, download)
finally:
self._playlist_level -= 1
if not self._playlist_level:
self._playlist_urls.clear()
elif result_type == 'compat_list':
self.report_warning(
'Extractor %s returned a compat_list result. '
'It needs to be updated.' % ie_result.get('extractor'))
def _fixup(r):
self.add_extra_info(
r,
{
'extractor': ie_result['extractor'],
'webpage_url': ie_result['webpage_url'],
'webpage_url_basename': url_basename(ie_result['webpage_url']),
'extractor_key': ie_result['extractor_key'],
}
)
return r
ie_result['entries'] = [
self.process_ie_result(_fixup(r), download, extra_info)
for r in ie_result['entries']
]
return ie_result
else:
raise Exception('Invalid result type: %s' % result_type)
def __process_playlist(self, ie_result, download):
# We process each entry in the playlist
playlist = ie_result.get('title') or ie_result.get('id')
self.to_screen('[download] Downloading playlist: %s' % playlist)
playlist_results = []
playliststart = self.params.get('playliststart', 1) - 1
playlistend = self.params.get('playlistend')
# For backwards compatibility, interpret -1 as whole list
if playlistend == -1:
playlistend = None
playlistitems_str = self.params.get('playlist_items')
playlistitems = None
if playlistitems_str is not None:
def iter_playlistitems(format):
for string_segment in format.split(','):
if '-' in string_segment:
start, end = string_segment.split('-')
for item in range(int(start), int(end) + 1):
yield int(item)
else:
yield int(string_segment)
playlistitems = orderedSet(iter_playlistitems(playlistitems_str))
ie_entries = ie_result['entries']
def make_playlistitems_entries(list_ie_entries):
num_entries = len(list_ie_entries)
return [
list_ie_entries[i - 1] for i in playlistitems
if -num_entries <= i - 1 < num_entries]
def report_download(num_entries):
self.to_screen(
'[%s] playlist %s: Downloading %d videos' %
(ie_result['extractor'], playlist, num_entries))
if isinstance(ie_entries, list):
n_all_entries = len(ie_entries)
if playlistitems:
entries = make_playlistitems_entries(ie_entries)
else:
entries = ie_entries[playliststart:playlistend]
n_entries = len(entries)
self.to_screen(
'[%s] playlist %s: Collected %d video ids (downloading %d of them)' %
(ie_result['extractor'], playlist, n_all_entries, n_entries))
elif isinstance(ie_entries, PagedList):
if playlistitems:
entries = []
for item in playlistitems:
entries.extend(ie_entries.getslice(
item - 1, item
))
else:
entries = ie_entries.getslice(
playliststart, playlistend)
n_entries = len(entries)
report_download(n_entries)
else: # iterable
if playlistitems:
entries = make_playlistitems_entries(list(itertools.islice(
ie_entries, 0, max(playlistitems))))
else:
entries = list(itertools.islice(
ie_entries, playliststart, playlistend))
n_entries = len(entries)
report_download(n_entries)
if self.params.get('playlistreverse', False):
entries = entries[::-1]
if self.params.get('playlistrandom', False):
random.shuffle(entries)
x_forwarded_for = ie_result.get('__x_forwarded_for_ip')
for i, entry in enumerate(entries, 1):
self.to_screen('[download] Downloading video %s of %s' % (i, n_entries))
# This __x_forwarded_for_ip thing is a bit ugly but requires
# minimal changes
if x_forwarded_for:
entry['__x_forwarded_for_ip'] = x_forwarded_for
extra = {
'n_entries': n_entries,
'playlist': playlist,
'playlist_id': ie_result.get('id'),
'playlist_title': ie_result.get('title'),
'playlist_uploader': ie_result.get('uploader'),
'playlist_uploader_id': ie_result.get('uploader_id'),
'playlist_index': playlistitems[i - 1] if playlistitems else i + playliststart,
'extractor': ie_result['extractor'],
'webpage_url': ie_result['webpage_url'],
'webpage_url_basename': url_basename(ie_result['webpage_url']),
'extractor_key': ie_result['extractor_key'],
}
reason = self._match_entry(entry, incomplete=True)
if reason is not None:
self.to_screen('[download] ' + reason)
continue
entry_result = self.__process_iterable_entry(entry, download, extra)
# TODO: skip failed (empty) entries?
playlist_results.append(entry_result)
ie_result['entries'] = playlist_results
self.to_screen('[download] Finished downloading playlist: %s' % playlist)
return ie_result
@__handle_extraction_exceptions
def __process_iterable_entry(self, entry, download, extra_info):
return self.process_ie_result(
entry, download=download, extra_info=extra_info)
def _build_format_filter(self, filter_spec):
OPERATORS = {
'<': operator.lt,
'<=': operator.le,
'>': operator.gt,
'>=': operator.ge,
'=': operator.eq,
'!=': operator.ne,
}
operator_rex = re.compile(r'''(?x)\s*
(?P<key>width|height|tbr|abr|vbr|asr|filesize|filesize_approx|fps)
\s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
(?P<value>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)
$
''' % '|'.join(map(re.escape, OPERATORS.keys())))
m = operator_rex.search(filter_spec)
if m:
try:
comparison_value = int(m.group('value'))
except ValueError:
comparison_value = parse_filesize(m.group('value'))
if comparison_value is None:
comparison_value = parse_filesize(m.group('value') + 'B')
if comparison_value is None:
raise ValueError(
'Invalid value %r in format specification %r' % (
m.group('value'), filter_spec))
op = OPERATORS[m.group('op')]
if not m:
STR_OPERATORS = {
'=': operator.eq,
'^=': lambda attr, value: attr.startswith(value),
'$=': lambda attr, value: attr.endswith(value),
'*=': lambda attr, value: value in attr,
}
str_operator_rex = re.compile(r'''(?x)
\s*(?P<key>ext|acodec|vcodec|container|protocol|format_id|language)
\s*(?P<negation>!\s*)?(?P<op>%s)(?P<none_inclusive>\s*\?)?
\s*(?P<value>[a-zA-Z0-9._-]+)
\s*$
''' % '|'.join(map(re.escape, STR_OPERATORS.keys())))
m = str_operator_rex.search(filter_spec)
if m:
comparison_value = m.group('value')
str_op = STR_OPERATORS[m.group('op')]
if m.group('negation'):
op = lambda attr, value: not str_op(attr, value)
else:
op = str_op
if not m:
raise ValueError('Invalid filter specification %r' % filter_spec)
def _filter(f):
actual_value = f.get(m.group('key'))
if actual_value is None:
return m.group('none_inclusive')
return op(actual_value, comparison_value)
return _filter
def _default_format_spec(self, info_dict, download=True):
def can_merge():
merger = FFmpegMergerPP(self)
return merger.available and merger.can_merge()
def prefer_best():
if self.params.get('simulate', False):
return False
if not download:
return False
if self.params.get('outtmpl', DEFAULT_OUTTMPL) == '-':
return True
if info_dict.get('is_live'):
return True
if not can_merge():
return True
return False
req_format_list = ['bestvideo+bestaudio', 'best']
if prefer_best():
req_format_list.reverse()
return '/'.join(req_format_list)
def build_format_selector(self, format_spec):
def syntax_error(note, start):
message = (
'Invalid format specification: '
'{0}\n\t{1}\n\t{2}^'.format(note, format_spec, ' ' * start[1]))
return SyntaxError(message)
PICKFIRST = 'PICKFIRST'
MERGE = 'MERGE'
SINGLE = 'SINGLE'
GROUP = 'GROUP'
FormatSelector = collections.namedtuple('FormatSelector', ['type', 'selector', 'filters'])
def _parse_filter(tokens):
filter_parts = []
for type, string, start, _, _ in tokens:
if type == tokenize.OP and string == ']':
return ''.join(filter_parts)
else:
filter_parts.append(string)
def _remove_unused_ops(tokens):
# Remove operators that we don't use and join them with the surrounding strings
ALLOWED_OPS = ('/', '+', ',', '(', ')')
last_string, last_start, last_end, last_line = None, None, None, None
for type, string, start, end, line in tokens:
if type == tokenize.OP and string == '[':
if last_string:
yield tokenize.NAME, last_string, last_start, last_end, last_line
last_string = None
yield type, string, start, end, line
for type, string, start, end, line in tokens:
yield type, string, start, end, line
if type == tokenize.OP and string == ']':
break
elif type == tokenize.OP and string in ALLOWED_OPS:
if last_string:
yield tokenize.NAME, last_string, last_start, last_end, last_line
last_string = None
yield type, string, start, end, line
elif type in [tokenize.NAME, tokenize.NUMBER, tokenize.OP]:
if not last_string:
last_string = string
last_start = start
last_end = end
else:
last_string += string
if last_string:
yield tokenize.NAME, last_string, last_start, last_end, last_line
def _parse_format_selection(tokens, inside_merge=False, inside_choice=False, inside_group=False):
selectors = []
current_selector = None
for type, string, start, _, _ in tokens:
if type == getattr(tokenize, 'ENCODING', None):
continue
elif type in [tokenize.NAME, tokenize.NUMBER]:
current_selector = FormatSelector(SINGLE, string, [])
elif type == tokenize.OP:
if string == ')':
if not inside_group:
tokens.restore_last_token()
break
elif inside_merge and string in ['/', ',']:
tokens.restore_last_token()
break
elif inside_choice and string == ',':
tokens.restore_last_token()
break
elif string == ',':
if not current_selector:
raise syntax_error('"," must follow a format selector', start)
selectors.append(current_selector)
current_selector = None
elif string == '/':
if not current_selector:
raise syntax_error('"/" must follow a format selector', start)
first_choice = current_selector
second_choice = _parse_format_selection(tokens, inside_choice=True)
current_selector = FormatSelector(PICKFIRST, (first_choice, second_choice), [])
elif string == '[':
if not current_selector:
current_selector = FormatSelector(SINGLE, 'best', [])
format_filter = _parse_filter(tokens)
current_selector.filters.append(format_filter)
elif string == '(':
if current_selector:
raise syntax_error('Unexpected "("', start)
group = _parse_format_selection(tokens, inside_group=True)
current_selector = FormatSelector(GROUP, group, [])
elif string == '+':
if inside_merge:
raise syntax_error('Unexpected "+"', start)
video_selector = current_selector
audio_selector = _parse_format_selection(tokens, inside_merge=True)
if not video_selector or not audio_selector:
raise syntax_error('"+" must be between two format selectors', start)
current_selector = FormatSelector(MERGE, (video_selector, audio_selector), [])
else:
raise syntax_error('Operator not recognized: "{0}"'.format(string), start)
elif type == tokenize.ENDMARKER:
break
if current_selector:
selectors.append(current_selector)
return selectors
def _build_selector_function(selector):
if isinstance(selector, list):
fs = [_build_selector_function(s) for s in selector]
def selector_function(ctx):
for f in fs:
for format in f(ctx):
yield format
return selector_function
elif selector.type == GROUP:
selector_function = _build_selector_function(selector.selector)
elif selector.type == PICKFIRST:
fs = [_build_selector_function(s) for s in selector.selector]
def selector_function(ctx):
for f in fs:
picked_formats = list(f(ctx))
if picked_formats:
return picked_formats
return []
elif selector.type == SINGLE:
format_spec = selector.selector
def selector_function(ctx):
formats = list(ctx['formats'])
if not formats:
return
if format_spec == 'all':
for f in formats:
yield f
elif format_spec in ['best', 'worst', None]:
format_idx = 0 if format_spec == 'worst' else -1
audiovideo_formats = [
f for f in formats
if f.get('vcodec') != 'none' and f.get('acodec') != 'none']
if audiovideo_formats:
yield audiovideo_formats[format_idx]
elif ctx['incomplete_formats']:
yield formats[format_idx]
elif format_spec == 'bestaudio':
audio_formats = [
f for f in formats
if f.get('vcodec') == 'none']
if audio_formats:
yield audio_formats[-1]
elif format_spec == 'worstaudio':
audio_formats = [
f for f in formats
if f.get('vcodec') == 'none']
if audio_formats:
yield audio_formats[0]
elif format_spec == 'bestvideo':
video_formats = [
f for f in formats
if f.get('acodec') == 'none']
if video_formats:
yield video_formats[-1]
elif format_spec == 'worstvideo':
video_formats = [
f for f in formats
if f.get('acodec') == 'none']
if video_formats:
yield video_formats[0]
else:
extensions = ['mp4', 'flv', 'webm', '3gp', 'm4a', 'mp3', 'ogg', 'aac', 'wav']
if format_spec in extensions:
filter_f = lambda f: f['ext'] == format_spec
else:
filter_f = lambda f: f['format_id'] == format_spec
matches = list(filter(filter_f, formats))
if matches:
yield matches[-1]
elif selector.type == MERGE:
def _merge(formats_info):
format_1, format_2 = [f['format_id'] for f in formats_info]
if formats_info[0].get('vcodec') == 'none':
self.report_error('The first format must '
'contain the video, try using '
'"-f %s+%s"' % (format_2, format_1))
return
if formats_info[0].get('acodec') == 'none' and formats_info[1].get('acodec') == 'none':
self.report_error(
'Both formats %s and %s are video-only, you must specify "-f video+audio"'
% (format_1, format_2))
return
output_ext = (
formats_info[0]['ext']
if self.params.get('merge_output_format') is None
else self.params['merge_output_format'])
return {
'requested_formats': formats_info,
'format': '%s+%s' % (formats_info[0].get('format'),
formats_info[1].get('format')),
'format_id': '%s+%s' % (formats_info[0].get('format_id'),
formats_info[1].get('format_id')),
'width': formats_info[0].get('width'),
'height': formats_info[0].get('height'),
'resolution': formats_info[0].get('resolution'),
'fps': formats_info[0].get('fps'),
'vcodec': formats_info[0].get('vcodec'),
'vbr': formats_info[0].get('vbr'),
'stretched_ratio': formats_info[0].get('stretched_ratio'),
'acodec': formats_info[1].get('acodec'),
'abr': formats_info[1].get('abr'),
'ext': output_ext,
}
video_selector, audio_selector = map(_build_selector_function, selector.selector)
def selector_function(ctx):
for pair in itertools.product(
video_selector(copy.deepcopy(ctx)), audio_selector(copy.deepcopy(ctx))):
yield _merge(pair)
filters = [self._build_format_filter(f) for f in selector.filters]
def final_selector(ctx):
ctx_copy = copy.deepcopy(ctx)
for _filter in filters:
ctx_copy['formats'] = list(filter(_filter, ctx_copy['formats']))
return selector_function(ctx_copy)
return final_selector
stream = io.BytesIO(format_spec.encode('utf-8'))
try:
tokens = list(_remove_unused_ops(compat_tokenize_tokenize(stream.readline)))
except tokenize.TokenError:
raise syntax_error('Missing closing/opening brackets or parenthesis', (0, len(format_spec)))
class TokenIterator(object):
def __init__(self, tokens):
self.tokens = tokens
self.counter = 0
def __iter__(self):
return self
def __next__(self):
if self.counter >= len(self.tokens):
raise StopIteration()
value = self.tokens[self.counter]
self.counter += 1
return value
next = __next__
def restore_last_token(self):
self.counter -= 1
parsed_selector = _parse_format_selection(iter(TokenIterator(tokens)))
return _build_selector_function(parsed_selector)
def _calc_headers(self, info_dict):
res = std_headers.copy()
add_headers = info_dict.get('http_headers')
if add_headers:
res.update(add_headers)
cookies = self._calc_cookies(info_dict)
if cookies:
res['Cookie'] = cookies
if 'X-Forwarded-For' not in res:
x_forwarded_for_ip = info_dict.get('__x_forwarded_for_ip')
if x_forwarded_for_ip:
res['X-Forwarded-For'] = x_forwarded_for_ip
return res
def _calc_cookies(self, info_dict):
pr = sanitized_Request(info_dict['url'])
self.cookiejar.add_cookie_header(pr)
return pr.get_header('Cookie')
def process_video_result(self, info_dict, download=True):
assert info_dict.get('_type', 'video') == 'video'
if 'id' not in info_dict:
raise ExtractorError('Missing "id" field in extractor result')
if 'title' not in info_dict:
raise ExtractorError('Missing "title" field in extractor result')
def report_force_conversion(field, field_not, conversion):
self.report_warning(
'"%s" field is not %s - forcing %s conversion, there is an error in extractor'
% (field, field_not, conversion))
def sanitize_string_field(info, string_field):
field = info.get(string_field)
if field is None or isinstance(field, compat_str):
return
report_force_conversion(string_field, 'a string', 'string')
info[string_field] = compat_str(field)
def sanitize_numeric_fields(info):
for numeric_field in self._NUMERIC_FIELDS:
field = info.get(numeric_field)
if field is None or isinstance(field, compat_numeric_types):
continue
report_force_conversion(numeric_field, 'numeric', 'int')
info[numeric_field] = int_or_none(field)
sanitize_string_field(info_dict, 'id')
sanitize_numeric_fields(info_dict)
if 'playlist' not in info_dict:
info_dict['playlist'] = None
info_dict['playlist_index'] = None
thumbnails = info_dict.get('thumbnails')
if thumbnails is None:
thumbnail = info_dict.get('thumbnail')
if thumbnail:
info_dict['thumbnails'] = thumbnails = [{'url': thumbnail}]
if thumbnails:
thumbnails.sort(key=lambda t: (
t.get('preference') if t.get('preference') is not None else -1,
t.get('width') if t.get('width') is not None else -1,
t.get('height') if t.get('height') is not None else -1,
t.get('id') if t.get('id') is not None else '', t.get('url')))
for i, t in enumerate(thumbnails):
t['url'] = sanitize_url(t['url'])
if t.get('width') and t.get('height'):
t['resolution'] = '%dx%d' % (t['width'], t['height'])
if t.get('id') is None:
t['id'] = '%d' % i
if self.params.get('list_thumbnails'):
self.list_thumbnails(info_dict)
return
thumbnail = info_dict.get('thumbnail')
if thumbnail:
info_dict['thumbnail'] = sanitize_url(thumbnail)
elif thumbnails:
info_dict['thumbnail'] = thumbnails[-1]['url']
if 'display_id' not in info_dict and 'id' in info_dict:
info_dict['display_id'] = info_dict['id']
for ts_key, date_key in (
('timestamp', 'upload_date'),
('release_timestamp', 'release_date'),
):
if info_dict.get(date_key) is None and info_dict.get(ts_key) is not None:
# Working around out-of-range timestamp values (e.g. negative ones on Windows,
# see http://bugs.python.org/issue1646728)
try:
upload_date = datetime.datetime.utcfromtimestamp(info_dict[ts_key])
info_dict[date_key] = upload_date.strftime('%Y%m%d')
except (ValueError, OverflowError, OSError):
pass
# Auto generate title fields corresponding to the *_number fields when missing
# in order to always have clean titles. This is very common for TV series.
for field in ('chapter', 'season', 'episode'):
if info_dict.get('%s_number' % field) is not None and not info_dict.get(field):
info_dict[field] = '%s %d' % (field.capitalize(), info_dict['%s_number' % field])
for cc_kind in ('subtitles', 'automatic_captions'):
cc = info_dict.get(cc_kind)
if cc:
for _, subtitle in cc.items():
for subtitle_format in subtitle:
if subtitle_format.get('url'):
subtitle_format['url'] = sanitize_url(subtitle_format['url'])
if subtitle_format.get('ext') is None:
subtitle_format['ext'] = determine_ext(subtitle_format['url']).lower()
automatic_captions = info_dict.get('automatic_captions')
subtitles = info_dict.get('subtitles')
if self.params.get('listsubtitles', False):
if 'automatic_captions' in info_dict:
self.list_subtitles(
info_dict['id'], automatic_captions, 'automatic captions')
self.list_subtitles(info_dict['id'], subtitles, 'subtitles')
return
info_dict['requested_subtitles'] = self.process_subtitles(
info_dict['id'], subtitles, automatic_captions)
# We now pick which formats have to be downloaded
if info_dict.get('formats') is None:
# There's only one format available
formats = [info_dict]
else:
formats = info_dict['formats']
if not formats:
raise ExtractorError('No video formats found!')
def is_wellformed(f):
url = f.get('url')
if not url:
self.report_warning(
'"url" field is missing or empty - skipping format, '
'there is an error in extractor')
return False
if isinstance(url, bytes):
sanitize_string_field(f, 'url')
return True
formats = list(filter(is_wellformed, formats))
formats_dict = {}
for i, format in enumerate(formats):
sanitize_string_field(format, 'format_id')
sanitize_numeric_fields(format)
format['url'] = sanitize_url(format['url'])
if not format.get('format_id'):
format['format_id'] = compat_str(i)
else:
format['format_id'] = re.sub(r'[\s,/+\[\]()]', '_', format['format_id'])
format_id = format['format_id']
if format_id not in formats_dict:
formats_dict[format_id] = []
formats_dict[format_id].append(format)
for format_id, ambiguous_formats in formats_dict.items():
if len(ambiguous_formats) > 1:
for i, format in enumerate(ambiguous_formats):
format['format_id'] = '%s-%d' % (format_id, i)
for i, format in enumerate(formats):
if format.get('format') is None:
format['format'] = '{id} - {res}{note}'.format(
id=format['format_id'],
res=self.format_resolution(format),
note=' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
)
if format.get('ext') is None:
format['ext'] = determine_ext(format['url']).lower()
if format.get('protocol') is None:
format['protocol'] = determine_protocol(format)
full_format_info = info_dict.copy()
full_format_info.update(format)
format['http_headers'] = self._calc_headers(full_format_info)
if '__x_forwarded_for_ip' in info_dict:
del info_dict['__x_forwarded_for_ip']
if formats[0] is not info_dict:
info_dict['formats'] = formats
if self.params.get('listformats'):
self.list_formats(info_dict)
return
req_format = self.params.get('format')
if req_format is None:
req_format = self._default_format_spec(info_dict, download=download)
if self.params.get('verbose'):
self._write_string('[debug] Default format spec: %s\n' % req_format)
format_selector = self.build_format_selector(req_format)
# While in format selection we may need to have an access to the original
# format set in order to calculate some metrics or do some processing.
# For now we need to be able to guess whether original formats provided
# by extractor are incomplete or not (i.e. whether extractor provides only
# video-only or audio-only formats) for proper formats selection for
# extractors with such incomplete formats (see
# https://github.com/ytdl-org/youtube-dl/pull/5556).
# Since formats may be filtered during format selection and may not match
# the original formats the results may be incorrect. Thus original formats
# or pre-calculated metrics should be passed to format selection routines
# as well.
# We will pass a context object containing all necessary additional data
# instead of just formats.
# This fixes incorrect format selection issue (see
# https://github.com/ytdl-org/youtube-dl/issues/10083).
incomplete_formats = (
# All formats are video-only or
all(f.get('vcodec') != 'none' and f.get('acodec') == 'none' for f in formats)
# all formats are audio-only
or all(f.get('vcodec') == 'none' and f.get('acodec') != 'none' for f in formats))
ctx = {
'formats': formats,
'incomplete_formats': incomplete_formats,
}
formats_to_download = list(format_selector(ctx))
if not formats_to_download:
raise ExtractorError('requested format not available',
expected=True)
if download:
if len(formats_to_download) > 1:
self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
for format in formats_to_download:
new_info = dict(info_dict)
new_info.update(format)
self.process_info(new_info)
# We update the info dict with the best quality format (backwards compatibility)
info_dict.update(formats_to_download[-1])
return info_dict
def process_subtitles(self, video_id, normal_subtitles, automatic_captions):
available_subs = {}
if normal_subtitles and self.params.get('writesubtitles'):
available_subs.update(normal_subtitles)
if automatic_captions and self.params.get('writeautomaticsub'):
for lang, cap_info in automatic_captions.items():
if lang not in available_subs:
available_subs[lang] = cap_info
if (not self.params.get('writesubtitles') and not
self.params.get('writeautomaticsub') or not
available_subs):
return None
if self.params.get('allsubtitles', False):
requested_langs = available_subs.keys()
else:
if self.params.get('subtitleslangs', False):
requested_langs = self.params.get('subtitleslangs')
elif 'en' in available_subs:
requested_langs = ['en']
else:
requested_langs = [list(available_subs.keys())[0]]
formats_query = self.params.get('subtitlesformat', 'best')
formats_preference = formats_query.split('/') if formats_query else []
subs = {}
for lang in requested_langs:
formats = available_subs.get(lang)
if formats is None:
self.report_warning('%s subtitles not available for %s' % (lang, video_id))
continue
for ext in formats_preference:
if ext == 'best':
f = formats[-1]
break
matches = list(filter(lambda f: f['ext'] == ext, formats))
if matches:
f = matches[-1]
break
else:
f = formats[-1]
self.report_warning(
'No subtitle format found matching "%s" for language %s, '
'using %s' % (formats_query, lang, f['ext']))
subs[lang] = f
return subs
def __forced_printings(self, info_dict, filename, incomplete):
def print_mandatory(field):
if (self.params.get('force%s' % field, False)
and (not incomplete or info_dict.get(field) is not None)):
self.to_stdout(info_dict[field])
def print_optional(field):
if (self.params.get('force%s' % field, False)
and info_dict.get(field) is not None):
self.to_stdout(info_dict[field])
print_mandatory('title')
print_mandatory('id')
if self.params.get('forceurl', False) and not incomplete:
if info_dict.get('requested_formats') is not None:
for f in info_dict['requested_formats']:
self.to_stdout(f['url'] + f.get('play_path', ''))
else:
# For RTMP URLs, also include the playpath
self.to_stdout(info_dict['url'] + info_dict.get('play_path', ''))
print_optional('thumbnail')
print_optional('description')
if self.params.get('forcefilename', False) and filename is not None:
self.to_stdout(filename)
if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
self.to_stdout(formatSeconds(info_dict['duration']))
print_mandatory('format')
if self.params.get('forcejson', False):
self.to_stdout(json.dumps(info_dict))
def process_info(self, info_dict):
assert info_dict.get('_type', 'video') == 'video'
max_downloads = self.params.get('max_downloads')
if max_downloads is not None:
if self._num_downloads >= int(max_downloads):
raise MaxDownloadsReached()
# TODO: backward compatibility, to be removed
info_dict['fulltitle'] = info_dict['title']
if 'format' not in info_dict:
info_dict['format'] = info_dict['ext']
reason = self._match_entry(info_dict, incomplete=False)
if reason is not None:
self.to_screen('[download] ' + reason)
return
self._num_downloads += 1
info_dict['_filename'] = filename = self.prepare_filename(info_dict)
# Forced printings
self.__forced_printings(info_dict, filename, incomplete=False)
# Do nothing else if in simulate mode
if self.params.get('simulate', False):
return
if filename is None:
return
def ensure_dir_exists(path):
try:
dn = os.path.dirname(path)
if dn and not os.path.exists(dn):
os.makedirs(dn)
return True
except (OSError, IOError) as err:
if isinstance(err, OSError) and err.errno == errno.EEXIST:
return True
self.report_error('unable to create directory ' + error_to_compat_str(err))
return False
if not ensure_dir_exists(sanitize_path(encodeFilename(filename))):
return
if self.params.get('writedescription', False):
descfn = replace_extension(filename, 'description', info_dict.get('ext'))
if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
self.to_screen('[info] Video description is already present')
elif info_dict.get('description') is None:
self.report_warning('There\'s no description to write.')
else:
try:
self.to_screen('[info] Writing video description to: ' + descfn)
with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
descfile.write(info_dict['description'])
except (OSError, IOError):
self.report_error('Cannot write description file ' + descfn)
return
if self.params.get('writeannotations', False):
annofn = replace_extension(filename, 'annotations.xml', info_dict.get('ext'))
if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
self.to_screen('[info] Video annotations are already present')
elif not info_dict.get('annotations'):
self.report_warning('There are no annotations to write.')
else:
try:
self.to_screen('[info] Writing video annotations to: ' + annofn)
with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
annofile.write(info_dict['annotations'])
except (KeyError, TypeError):
self.report_warning('There are no annotations to write.')
except (OSError, IOError):
self.report_error('Cannot write annotations file: ' + annofn)
return
subtitles_are_requested = any([self.params.get('writesubtitles', False),
self.params.get('writeautomaticsub')])
if subtitles_are_requested and info_dict.get('requested_subtitles'):
subtitles = info_dict['requested_subtitles']
ie = self.get_info_extractor(info_dict['extractor_key'])
for sub_lang, sub_info in subtitles.items():
sub_format = sub_info['ext']
sub_filename = subtitles_filename(filename, sub_lang, sub_format, info_dict.get('ext'))
if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
self.to_screen('[info] Video subtitle %s.%s is already present' % (sub_lang, sub_format))
else:
self.to_screen('[info] Writing video subtitles to: ' + sub_filename)
if sub_info.get('data') is not None:
try:
with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8', newline='') as subfile:
subfile.write(sub_info['data'])
except (OSError, IOError):
self.report_error('Cannot write subtitles file ' + sub_filename)
return
else:
try:
sub_data = ie._request_webpage(
sub_info['url'], info_dict['id'], note=False).read()
with io.open(encodeFilename(sub_filename), 'wb') as subfile:
subfile.write(sub_data)
except (ExtractorError, IOError, OSError, ValueError) as err:
self.report_warning('Unable to download subtitle for "%s": %s' %
(sub_lang, error_to_compat_str(err)))
continue
if self.params.get('writeinfojson', False):
infofn = replace_extension(filename, 'info.json', info_dict.get('ext'))
if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
self.to_screen('[info] Video description metadata is already present')
else:
self.to_screen('[info] Writing video description metadata as JSON to: ' + infofn)
try:
write_json_file(self.filter_requested_info(info_dict), infofn)
except (OSError, IOError):
self.report_error('Cannot write metadata to JSON file ' + infofn)
return
self._write_thumbnails(info_dict, filename)
if not self.params.get('skip_download', False):
try:
def dl(name, info):
fd = get_suitable_downloader(info, self.params)(self, self.params)
for ph in self._progress_hooks:
fd.add_progress_hook(ph)
if self.params.get('verbose'):
self.to_screen('[debug] Invoking downloader on %r' % info.get('url'))
return fd.download(name, info)
if info_dict.get('requested_formats') is not None:
downloaded = []
success = True
merger = FFmpegMergerPP(self)
if not merger.available:
postprocessors = []
self.report_warning('You have requested multiple '
'formats but ffmpeg or avconv are not installed.'
' The formats won\'t be merged.')
else:
postprocessors = [merger]
def compatible_formats(formats):
video, audio = formats
# Check extension
video_ext, audio_ext = video.get('ext'), audio.get('ext')
if video_ext and audio_ext:
COMPATIBLE_EXTS = (
('mp3', 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v', 'ismv', 'isma'),
('webm')
)
for exts in COMPATIBLE_EXTS:
if video_ext in exts and audio_ext in exts:
return True
# TODO: Check acodec/vcodec
return False
filename_real_ext = os.path.splitext(filename)[1][1:]
filename_wo_ext = (
os.path.splitext(filename)[0]
if filename_real_ext == info_dict['ext']
else filename)
requested_formats = info_dict['requested_formats']
if self.params.get('merge_output_format') is None and not compatible_formats(requested_formats):
info_dict['ext'] = 'mkv'
self.report_warning(
'Requested formats are incompatible for merge and will be merged into mkv.')
# Ensure filename always has a correct extension for successful merge
filename = '%s.%s' % (filename_wo_ext, info_dict['ext'])
if os.path.exists(encodeFilename(filename)):
self.to_screen(
'[download] %s has already been downloaded and '
'merged' % filename)
else:
for f in requested_formats:
new_info = dict(info_dict)
new_info.update(f)
fname = prepend_extension(
self.prepare_filename(new_info),
'f%s' % f['format_id'], new_info['ext'])
if not ensure_dir_exists(fname):
return
downloaded.append(fname)
partial_success = dl(fname, new_info)
success = success and partial_success
info_dict['__postprocessors'] = postprocessors
info_dict['__files_to_merge'] = downloaded
else:
# Just a single file
success = dl(filename, info_dict)
except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
self.report_error('unable to download video data: %s' % error_to_compat_str(err))
return
except (OSError, IOError) as err:
raise UnavailableVideoError(err)
except (ContentTooShortError, ) as err:
self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
return
if success and filename != '-':
# Fixup content
fixup_policy = self.params.get('fixup')
if fixup_policy is None:
fixup_policy = 'detect_or_warn'
INSTALL_FFMPEG_MESSAGE = 'Install ffmpeg or avconv to fix this automatically.'
stretched_ratio = info_dict.get('stretched_ratio')
if stretched_ratio is not None and stretched_ratio != 1:
if fixup_policy == 'warn':
self.report_warning('%s: Non-uniform pixel ratio (%s)' % (
info_dict['id'], stretched_ratio))
elif fixup_policy == 'detect_or_warn':
stretched_pp = FFmpegFixupStretchedPP(self)
if stretched_pp.available:
info_dict.setdefault('__postprocessors', [])
info_dict['__postprocessors'].append(stretched_pp)
else:
self.report_warning(
'%s: Non-uniform pixel ratio (%s). %s'
% (info_dict['id'], stretched_ratio, INSTALL_FFMPEG_MESSAGE))
else:
assert fixup_policy in ('ignore', 'never')
if (info_dict.get('requested_formats') is None
and info_dict.get('container') == 'm4a_dash'):
if fixup_policy == 'warn':
self.report_warning(
'%s: writing DASH m4a. '
'Only some players support this container.'
% info_dict['id'])
elif fixup_policy == 'detect_or_warn':
fixup_pp = FFmpegFixupM4aPP(self)
if fixup_pp.available:
info_dict.setdefault('__postprocessors', [])
info_dict['__postprocessors'].append(fixup_pp)
else:
self.report_warning(
'%s: writing DASH m4a. '
'Only some players support this container. %s'
% (info_dict['id'], INSTALL_FFMPEG_MESSAGE))
else:
assert fixup_policy in ('ignore', 'never')
if (info_dict.get('protocol') == 'm3u8_native'
or info_dict.get('protocol') == 'm3u8'
and self.params.get('hls_prefer_native')):
if fixup_policy == 'warn':
self.report_warning('%s: malformed AAC bitstream detected.' % (
info_dict['id']))
elif fixup_policy == 'detect_or_warn':
fixup_pp = FFmpegFixupM3u8PP(self)
if fixup_pp.available:
info_dict.setdefault('__postprocessors', [])
info_dict['__postprocessors'].append(fixup_pp)
else:
self.report_warning(
'%s: malformed AAC bitstream detected. %s'
% (info_dict['id'], INSTALL_FFMPEG_MESSAGE))
else:
assert fixup_policy in ('ignore', 'never')
try:
self.post_process(filename, info_dict)
except (PostProcessingError) as err:
self.report_error('postprocessing: %s' % str(err))
return
self.record_download_archive(info_dict)
def download(self, url_list):
outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
if (len(url_list) > 1
and outtmpl != '-'
and '%' not in outtmpl
and self.params.get('max_downloads') != 1):
raise SameFileError(outtmpl)
for url in url_list:
try:
# It also downloads the videos
res = self.extract_info(
url, force_generic_extractor=self.params.get('force_generic_extractor', False))
except UnavailableVideoError:
self.report_error('unable to download video')
except MaxDownloadsReached:
self.to_screen('[info] Maximum number of downloaded files reached.')
raise
else:
if self.params.get('dump_single_json', False):
self.to_stdout(json.dumps(res))
return self._download_retcode
def download_with_info_file(self, info_filename):
with contextlib.closing(fileinput.FileInput(
[info_filename], mode='r',
openhook=fileinput.hook_encoded('utf-8'))) as f:
# FileInput doesn't have a read method, we can't call json.load
info = self.filter_requested_info(json.loads('\n'.join(f)))
try:
self.process_ie_result(info, download=True)
except DownloadError:
webpage_url = info.get('webpage_url')
if webpage_url is not None:
self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
return self.download([webpage_url])
else:
raise
return self._download_retcode
@staticmethod
def filter_requested_info(info_dict):
return dict(
(k, v) for k, v in info_dict.items()
if k not in ['requested_formats', 'requested_subtitles'])
def post_process(self, filename, ie_info):
info = dict(ie_info)
info['filepath'] = filename
pps_chain = []
if ie_info.get('__postprocessors') is not None:
pps_chain.extend(ie_info['__postprocessors'])
pps_chain.extend(self._pps)
for pp in pps_chain:
files_to_delete = []
try:
files_to_delete, info = pp.run(info)
except PostProcessingError as e:
self.report_error(e.msg)
if files_to_delete and not self.params.get('keepvideo', False):
for old_filename in files_to_delete:
self.to_screen('Deleting original file %s (pass -k to keep)' % old_filename)
try:
os.remove(encodeFilename(old_filename))
except (IOError, OSError):
self.report_warning('Unable to remove downloaded original file')
def _make_archive_id(self, info_dict):
video_id = info_dict.get('id')
if not video_id:
return
# Future-proof against any change in case
# and backwards compatibility with prior versions
extractor = info_dict.get('extractor_key') or info_dict.get('ie_key') # key in a playlist
if extractor is None:
url = str_or_none(info_dict.get('url'))
if not url:
return
# Try to find matching extractor for the URL and take its ie_key
for ie in self._ies:
if ie.suitable(url):
extractor = ie.ie_key()
break
else:
return
return extractor.lower() + ' ' + video_id
def in_download_archive(self, info_dict):
fn = self.params.get('download_archive')
if fn is None:
return False
vid_id = self._make_archive_id(info_dict)
if not vid_id:
return False # Incomplete video information
try:
with locked_file(fn, 'r', encoding='utf-8') as archive_file:
for line in archive_file:
if line.strip() == vid_id:
return True
except IOError as ioe:
if ioe.errno != errno.ENOENT:
raise
return False
def record_download_archive(self, info_dict):
fn = self.params.get('download_archive')
if fn is None:
return
vid_id = self._make_archive_id(info_dict)
assert vid_id
with locked_file(fn, 'a', encoding='utf-8') as archive_file:
archive_file.write(vid_id + '\n')
@staticmethod
def format_resolution(format, default='unknown'):
if format.get('vcodec') == 'none':
return 'audio only'
if format.get('resolution') is not None:
return format['resolution']
if format.get('height') is not None:
if format.get('width') is not None:
res = '%sx%s' % (format['width'], format['height'])
else:
res = '%sp' % format['height']
elif format.get('width') is not None:
res = '%dx?' % format['width']
else:
res = default
return res
def _format_note(self, fdict):
res = ''
if fdict.get('ext') in ['f4f', 'f4m']:
res += '(unsupported) '
if fdict.get('language'):
if res:
res += ' '
res += '[%s] ' % fdict['language']
if fdict.get('format_note') is not None:
res += fdict['format_note'] + ' '
if fdict.get('tbr') is not None:
res += '%4dk ' % fdict['tbr']
if fdict.get('container') is not None:
if res:
res += ', '
res += '%s container' % fdict['container']
if (fdict.get('vcodec') is not None
and fdict.get('vcodec') != 'none'):
if res:
res += ', '
res += fdict['vcodec']
if fdict.get('vbr') is not None:
res += '@'
elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
res += 'video@'
if fdict.get('vbr') is not None:
res += '%4dk' % fdict['vbr']
if fdict.get('fps') is not None:
if res:
res += ', '
res += '%sfps' % fdict['fps']
if fdict.get('acodec') is not None:
if res:
res += ', '
if fdict['acodec'] == 'none':
res += 'video only'
else:
res += '%-5s' % fdict['acodec']
elif fdict.get('abr') is not None:
if res:
res += ', '
res += 'audio'
if fdict.get('abr') is not None:
res += '@%3dk' % fdict['abr']
if fdict.get('asr') is not None:
res += ' (%5dHz)' % fdict['asr']
if fdict.get('filesize') is not None:
if res:
res += ', '
res += format_bytes(fdict['filesize'])
elif fdict.get('filesize_approx') is not None:
if res:
res += ', '
res += '~' + format_bytes(fdict['filesize_approx'])
return res
def list_formats(self, info_dict):
formats = info_dict.get('formats', [info_dict])
table = [
[f['format_id'], f['ext'], self.format_resolution(f), self._format_note(f)]
for f in formats
if f.get('preference') is None or f['preference'] >= -1000]
if len(formats) > 1:
table[-1][-1] += (' ' if table[-1][-1] else '') + '(best)'
header_line = ['format code', 'extension', 'resolution', 'note']
self.to_screen(
'[info] Available formats for %s:\n%s' %
(info_dict['id'], render_table(header_line, table)))
def list_thumbnails(self, info_dict):
thumbnails = info_dict.get('thumbnails')
if not thumbnails:
self.to_screen('[info] No thumbnails present for %s' % info_dict['id'])
return
self.to_screen(
'[info] Thumbnails for %s:' % info_dict['id'])
self.to_screen(render_table(
['ID', 'width', 'height', 'URL'],
[[t['id'], t.get('width', 'unknown'), t.get('height', 'unknown'), t['url']] for t in thumbnails]))
def list_subtitles(self, video_id, subtitles, name='subtitles'):
if not subtitles:
self.to_screen('%s has no %s' % (video_id, name))
return
self.to_screen(
'Available %s for %s:' % (name, video_id))
self.to_screen(render_table(
['Language', 'formats'],
[[lang, ', '.join(f['ext'] for f in reversed(formats))]
for lang, formats in subtitles.items()]))
def urlopen(self, req):
if isinstance(req, compat_basestring):
req = sanitized_Request(req)
return self._opener.open(req, timeout=self._socket_timeout)
def print_debug_header(self):
if not self.params.get('verbose'):
return
if type('') is not compat_str:
# Python 2.6 on SLES11 SP1 (https://github.com/ytdl-org/youtube-dl/issues/3326)
self.report_warning(
'Your Python is broken! Update to a newer and supported version')
stdout_encoding = getattr(
sys.stdout, 'encoding', 'missing (%s)' % type(sys.stdout).__name__)
encoding_str = (
'[debug] Encodings: locale %s, fs %s, out %s, pref %s\n' % (
locale.getpreferredencoding(),
sys.getfilesystemencoding(),
stdout_encoding,
self.get_encoding()))
write_string(encoding_str, encoding=None)
self._write_string('[debug] youtube-dl version ' + __version__ + '\n')
if _LAZY_LOADER:
self._write_string('[debug] Lazy loading extractors enabled' + '\n')
try:
sp = subprocess.Popen(
['git', 'rev-parse', '--short', 'HEAD'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
cwd=os.path.dirname(os.path.abspath(__file__)))
out, err = sp.communicate()
out = out.decode().strip()
if re.match('[0-9a-f]+', out):
self._write_string('[debug] Git HEAD: ' + out + '\n')
except Exception:
try:
sys.exc_clear()
except Exception:
pass
def python_implementation():
impl_name = platform.python_implementation()
if impl_name == 'PyPy' and hasattr(sys, 'pypy_version_info'):
return impl_name + ' version %d.%d.%d' % sys.pypy_version_info[:3]
return impl_name
self._write_string('[debug] Python version %s (%s) - %s\n' % (
platform.python_version(), python_implementation(),
platform_name()))
exe_versions = FFmpegPostProcessor.get_versions(self)
exe_versions['rtmpdump'] = rtmpdump_version()
exe_versions['phantomjs'] = PhantomJSwrapper._version()
exe_str = ', '.join(
'%s %s' % (exe, v)
for exe, v in sorted(exe_versions.items())
if v
)
if not exe_str:
exe_str = 'none'
self._write_string('[debug] exe versions: %s\n' % exe_str)
proxy_map = {}
for handler in self._opener.handlers:
if hasattr(handler, 'proxies'):
proxy_map.update(handler.proxies)
self._write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
if self.params.get('call_home', False):
ipaddr = self.urlopen('https://yt-dl.org/ip').read().decode('utf-8')
self._write_string('[debug] Public IP address: %s\n' % ipaddr)
latest_version = self.urlopen(
'https://yt-dl.org/latest/version').read().decode('utf-8')
if version_tuple(latest_version) > version_tuple(__version__):
self.report_warning(
'You are using an outdated version (newest version: %s)! '
'See https://yt-dl.org/update if you need help updating.' %
latest_version)
def _setup_opener(self):
timeout_val = self.params.get('socket_timeout')
self._socket_timeout = 600 if timeout_val is None else float(timeout_val)
opts_cookiefile = self.params.get('cookiefile')
opts_proxy = self.params.get('proxy')
if opts_cookiefile is None:
self.cookiejar = compat_cookiejar.CookieJar()
else:
opts_cookiefile = expand_path(opts_cookiefile)
self.cookiejar = YoutubeDLCookieJar(opts_cookiefile)
if os.access(opts_cookiefile, os.R_OK):
self.cookiejar.load(ignore_discard=True, ignore_expires=True)
cookie_processor = YoutubeDLCookieProcessor(self.cookiejar)
if opts_proxy is not None:
if opts_proxy == '':
proxies = {}
else:
proxies = {'http': opts_proxy, 'https': opts_proxy}
else:
proxies = compat_urllib_request.getproxies()
# Set HTTPS proxy to HTTP one if given (https://github.com/ytdl-org/youtube-dl/issues/805)
if 'http' in proxies and 'https' not in proxies:
proxies['https'] = proxies['http']
proxy_handler = PerRequestProxyHandler(proxies)
debuglevel = 1 if self.params.get('debug_printtraffic') else 0
https_handler = make_HTTPS_handler(self.params, debuglevel=debuglevel)
ydlh = YoutubeDLHandler(self.params, debuglevel=debuglevel)
redirect_handler = YoutubeDLRedirectHandler()
data_handler = compat_urllib_request_DataHandler()
# When passing our own FileHandler instance, build_opener won't add the
file_handler = compat_urllib_request.FileHandler()
def file_open(*args, **kwargs):
raise compat_urllib_error.URLError('file:// scheme is explicitly disabled in youtube-dl for security reasons')
file_handler.file_open = file_open
opener = compat_urllib_request.build_opener(
proxy_handler, https_handler, cookie_processor, ydlh, redirect_handler, data_handler, file_handler)
# (See https://github.com/ytdl-org/youtube-dl/issues/1309 for details)
opener.addheaders = []
self._opener = opener
def encode(self, s):
if isinstance(s, bytes):
return s # Already encoded
try:
return s.encode(self.get_encoding())
except UnicodeEncodeError as err:
err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
raise
def get_encoding(self):
encoding = self.params.get('encoding')
if encoding is None:
encoding = preferredencoding()
return encoding
def _write_thumbnails(self, info_dict, filename):
if self.params.get('writethumbnail', False):
thumbnails = info_dict.get('thumbnails')
if thumbnails:
thumbnails = [thumbnails[-1]]
elif self.params.get('write_all_thumbnails', False):
thumbnails = info_dict.get('thumbnails')
else:
return
if not thumbnails:
# No thumbnails present, so return immediately
return
for t in thumbnails:
thumb_ext = determine_ext(t['url'], 'jpg')
suffix = '_%s' % t['id'] if len(thumbnails) > 1 else ''
thumb_display_id = '%s ' % t['id'] if len(thumbnails) > 1 else ''
t['filename'] = thumb_filename = replace_extension(filename + suffix, thumb_ext, info_dict.get('ext'))
if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
self.to_screen('[%s] %s: Thumbnail %sis already present' %
(info_dict['extractor'], info_dict['id'], thumb_display_id))
else:
self.to_screen('[%s] %s: Downloading thumbnail %s...' %
(info_dict['extractor'], info_dict['id'], thumb_display_id))
try:
uf = self.urlopen(t['url'])
with open(encodeFilename(thumb_filename), 'wb') as thumbf:
shutil.copyfileobj(uf, thumbf)
self.to_screen('[%s] %s: Writing thumbnail %sto: %s' %
(info_dict['extractor'], info_dict['id'], thumb_display_id, thumb_filename))
except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
self.report_warning('Unable to download thumbnail "%s": %s' %
(t['url'], error_to_compat_str(err)))
| true | true |
f72b941393c5f93b8853905303a2c759da17e1f7 | 9,291 | py | Python | invenio_app_ils/circulation/api.py | topless/invenio-app-ils | 38f5a6b61cdeaf5fa5776613073fa46af28737a9 | [
"MIT"
] | null | null | null | invenio_app_ils/circulation/api.py | topless/invenio-app-ils | 38f5a6b61cdeaf5fa5776613073fa46af28737a9 | [
"MIT"
] | 21 | 2018-11-02T14:19:53.000Z | 2021-06-25T15:16:42.000Z | invenio_app_ils/circulation/api.py | topless/invenio-app-ils | 38f5a6b61cdeaf5fa5776613073fa46af28737a9 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
#
# Copyright (C) 2018-2020 CERN.
#
# invenio-app-ils is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Invenio App ILS Circulation APIs."""
import uuid
from copy import copy, deepcopy
from datetime import date, timedelta
from functools import partial
from elasticsearch import VERSION as ES_VERSION
from flask import current_app
from flask_login import current_user
from invenio_circulation.api import Loan
from invenio_circulation.config import (CIRCULATION_STATES_LOAN_ACTIVE,
CIRCULATION_STATES_LOAN_COMPLETED)
from invenio_circulation.pidstore.pids import CIRCULATION_LOAN_PID_TYPE
from invenio_circulation.proxies import current_circulation
from invenio_circulation.search.api import search_by_patron_item_or_document
from invenio_db import db
from invenio_pidstore.models import PIDStatus
from invenio_pidstore.providers.recordid_v2 import RecordIdProviderV2
from invenio_app_ils.errors import (IlsException, InvalidParameterError,
MissingRequiredParameterError,
PatronHasLoanOnDocumentError,
PatronHasLoanOnItemError,
PatronHasRequestOnDocumentError)
from invenio_app_ils.fetchers import pid_fetcher
from invenio_app_ils.items.api import Item
from invenio_app_ils.minters import pid_minter
from invenio_app_ils.proxies import current_app_ils
lt_es7 = ES_VERSION[0] < 7
# override default `invenio-circulation` minters to use the base32 PIDs
# CIRCULATION_LOAN_PID_TYPE is already defined in `invenio-circulation`
ILS_CIRCULATION_LOAN_MINTER = "ilsloanid"
ILS_CIRCULATION_LOAN_FETCHER = "ilsloanid"
IlsCirculationLoanIdProvider = type(
"IlsCirculationLoanIdProvider",
(RecordIdProviderV2,),
dict(
pid_type=CIRCULATION_LOAN_PID_TYPE, default_status=PIDStatus.REGISTERED
),
)
ils_circulation_loan_pid_minter = partial(
pid_minter, provider_cls=IlsCirculationLoanIdProvider
)
ils_circulation_loan_pid_fetcher = partial(
pid_fetcher, provider_cls=IlsCirculationLoanIdProvider
)
def _validate_delivery(delivery):
"""Validate `delivery` param."""
methods = list(
current_app.config.get("ILS_CIRCULATION_DELIVERY_METHODS", {}).keys()
)
if methods:
if not delivery or delivery["method"] not in methods:
raise MissingRequiredParameterError(
description="A valid 'delivery' is required on loan request"
)
def _set_item_to_can_circulate(item_pid):
"""Change the item status to CAN_CIRCULATE."""
item = Item.get_record_by_pid(item_pid["value"])
if item["status"] != "CAN_CIRCULATE":
item["status"] = "CAN_CIRCULATE"
item.commit()
db.session.commit()
current_app_ils.item_indexer.index(item)
def patron_has_active_loan_or_request_on_document(patron_pid, document_pid):
"""Return True if patron has an active loan/request for given document."""
states = (
current_app.config["CIRCULATION_STATES_LOAN_REQUEST"]
+ current_app.config["CIRCULATION_STATES_LOAN_ACTIVE"]
)
search = search_by_patron_item_or_document(
patron_pid=patron_pid, document_pid=document_pid, filter_states=states
)
search_result = search.execute()
return (
search_result,
search_result.hits.total > 0
if lt_es7
else search_result.hits.total.value > 0,
)
def request_loan(
document_pid,
patron_pid,
transaction_location_pid,
transaction_user_pid=None,
**kwargs
):
"""Create a new loan and trigger the first transition to PENDING."""
search_result, loan_found = patron_has_active_loan_or_request_on_document(
patron_pid, document_pid
)
if loan_found:
if (
search_result.hits[0].state
in current_app.config["CIRCULATION_STATES_LOAN_REQUEST"]
):
raise PatronHasRequestOnDocumentError(patron_pid, document_pid)
raise PatronHasLoanOnDocumentError(patron_pid, document_pid)
_validate_delivery(kwargs.get("delivery"))
transaction_user_pid = transaction_user_pid or str(current_user.id)
# create a new loan
record_uuid = uuid.uuid4()
new_loan = dict(
patron_pid=patron_pid,
transaction_location_pid=transaction_location_pid,
transaction_user_pid=transaction_user_pid,
)
pid = ils_circulation_loan_pid_minter(record_uuid, data=new_loan)
loan = Loan.create(data=new_loan, id_=record_uuid)
params = deepcopy(loan)
params.update(document_pid=document_pid, **kwargs)
# trigger the transition to request
loan = current_circulation.circulation.trigger(
loan, **dict(params, trigger="request")
)
return pid, loan
def patron_has_active_loan_on_item(patron_pid, item_pid):
"""Return True if patron has a active Loan for given item."""
search = search_by_patron_item_or_document(
patron_pid=patron_pid,
item_pid=item_pid,
filter_states=current_app.config["CIRCULATION_STATES_LOAN_ACTIVE"],
)
search_result = search.execute()
return (
search_result.hits.total > 0
if lt_es7
else search_result.hits.total.value > 0
)
def checkout_loan(
item_pid,
patron_pid,
transaction_location_pid,
transaction_user_pid=None,
force=False,
**kwargs
):
"""Create a new loan and trigger the first transition to ITEM_ON_LOAN.
:param item_pid: a dict containing `value` and `type` fields to
uniquely identify the item.
:param patron_pid: the PID value of the patron
:param transaction_location_pid: the PID value of the location where the
checkout is performed
:param transaction_user_pid: the PID value of the user that performed the
checkout
:param force: if True, ignore the current status of the item and do perform
the checkout. If False, the checkout will fail when the item cannot
circulate.
"""
if patron_has_active_loan_on_item(
patron_pid=patron_pid, item_pid=item_pid
):
raise PatronHasLoanOnItemError(patron_pid, item_pid)
optional_delivery = kwargs.get("delivery")
if optional_delivery:
_validate_delivery(optional_delivery)
if force:
_set_item_to_can_circulate(item_pid)
transaction_user_pid = transaction_user_pid or str(current_user.id)
# create a new loan
record_uuid = uuid.uuid4()
new_loan = dict(
patron_pid=patron_pid,
transaction_location_pid=transaction_location_pid,
transaction_user_pid=transaction_user_pid,
)
pid = ils_circulation_loan_pid_minter(record_uuid, data=new_loan)
loan = Loan.create(data=new_loan, id_=record_uuid)
params = deepcopy(loan)
params.update(item_pid=item_pid, **kwargs)
# trigger the transition to request
loan = current_circulation.circulation.trigger(
loan, **dict(params, trigger="checkout")
)
return pid, loan
def update_dates_loan(record, start_date=None, end_date=None, request_start_date=None, request_expire_date=None):
"""Updates the dates of a loan."""
state = record["state"]
is_active_or_completed = state in CIRCULATION_STATES_LOAN_ACTIVE \
or state in CIRCULATION_STATES_LOAN_COMPLETED
data = copy(record)
if is_active_or_completed:
today = date.today().strftime("%Y-%m-%d")
if request_start_date or request_expire_date:
raise IlsException(description="Cannot modify request dates of an active or completed loan.")
if start_date:
if start_date > today:
raise InvalidParameterError(description="Start date cannot be in the future for active loans.")
data["start_date"] = start_date
if end_date:
data["end_date"] = end_date
if data["end_date"] < data["start_date"]:
raise InvalidParameterError(description="Negative date range.")
else: # Pending or cancelled
if start_date or end_date:
raise IlsException(description="Cannot modify dates of a pending or cancelled loan.")
if request_start_date:
data["request_start_date"] = request_start_date
if request_expire_date:
data["request_expire_date"] = request_expire_date
if data["request_expire_date"] < data["request_start_date"]:
raise InvalidParameterError(description="Negative date range.")
record.update(data)
record.commit()
db.session.commit()
current_circulation.loan_indexer().index(record)
return record
def circulation_default_loan_duration_for_item(item):
"""Transform circulation restrictions to timedelta for the given item."""
value = item.get("circulation_restriction", "NO_RESTRICTION")
if value == "ONE_WEEK":
return timedelta(weeks=1)
elif value == "TWO_WEEKS":
return timedelta(weeks=2)
elif value == "THREE_WEEKS":
return timedelta(weeks=3)
elif value == "FOUR_WEEKS":
return timedelta(weeks=4)
else:
# default: NO_RESTRICTION
return timedelta(weeks=4)
| 34.66791 | 113 | 0.708966 |
import uuid
from copy import copy, deepcopy
from datetime import date, timedelta
from functools import partial
from elasticsearch import VERSION as ES_VERSION
from flask import current_app
from flask_login import current_user
from invenio_circulation.api import Loan
from invenio_circulation.config import (CIRCULATION_STATES_LOAN_ACTIVE,
CIRCULATION_STATES_LOAN_COMPLETED)
from invenio_circulation.pidstore.pids import CIRCULATION_LOAN_PID_TYPE
from invenio_circulation.proxies import current_circulation
from invenio_circulation.search.api import search_by_patron_item_or_document
from invenio_db import db
from invenio_pidstore.models import PIDStatus
from invenio_pidstore.providers.recordid_v2 import RecordIdProviderV2
from invenio_app_ils.errors import (IlsException, InvalidParameterError,
MissingRequiredParameterError,
PatronHasLoanOnDocumentError,
PatronHasLoanOnItemError,
PatronHasRequestOnDocumentError)
from invenio_app_ils.fetchers import pid_fetcher
from invenio_app_ils.items.api import Item
from invenio_app_ils.minters import pid_minter
from invenio_app_ils.proxies import current_app_ils
lt_es7 = ES_VERSION[0] < 7
ILS_CIRCULATION_LOAN_MINTER = "ilsloanid"
ILS_CIRCULATION_LOAN_FETCHER = "ilsloanid"
IlsCirculationLoanIdProvider = type(
"IlsCirculationLoanIdProvider",
(RecordIdProviderV2,),
dict(
pid_type=CIRCULATION_LOAN_PID_TYPE, default_status=PIDStatus.REGISTERED
),
)
ils_circulation_loan_pid_minter = partial(
pid_minter, provider_cls=IlsCirculationLoanIdProvider
)
ils_circulation_loan_pid_fetcher = partial(
pid_fetcher, provider_cls=IlsCirculationLoanIdProvider
)
def _validate_delivery(delivery):
methods = list(
current_app.config.get("ILS_CIRCULATION_DELIVERY_METHODS", {}).keys()
)
if methods:
if not delivery or delivery["method"] not in methods:
raise MissingRequiredParameterError(
description="A valid 'delivery' is required on loan request"
)
def _set_item_to_can_circulate(item_pid):
item = Item.get_record_by_pid(item_pid["value"])
if item["status"] != "CAN_CIRCULATE":
item["status"] = "CAN_CIRCULATE"
item.commit()
db.session.commit()
current_app_ils.item_indexer.index(item)
def patron_has_active_loan_or_request_on_document(patron_pid, document_pid):
states = (
current_app.config["CIRCULATION_STATES_LOAN_REQUEST"]
+ current_app.config["CIRCULATION_STATES_LOAN_ACTIVE"]
)
search = search_by_patron_item_or_document(
patron_pid=patron_pid, document_pid=document_pid, filter_states=states
)
search_result = search.execute()
return (
search_result,
search_result.hits.total > 0
if lt_es7
else search_result.hits.total.value > 0,
)
def request_loan(
document_pid,
patron_pid,
transaction_location_pid,
transaction_user_pid=None,
**kwargs
):
search_result, loan_found = patron_has_active_loan_or_request_on_document(
patron_pid, document_pid
)
if loan_found:
if (
search_result.hits[0].state
in current_app.config["CIRCULATION_STATES_LOAN_REQUEST"]
):
raise PatronHasRequestOnDocumentError(patron_pid, document_pid)
raise PatronHasLoanOnDocumentError(patron_pid, document_pid)
_validate_delivery(kwargs.get("delivery"))
transaction_user_pid = transaction_user_pid or str(current_user.id)
record_uuid = uuid.uuid4()
new_loan = dict(
patron_pid=patron_pid,
transaction_location_pid=transaction_location_pid,
transaction_user_pid=transaction_user_pid,
)
pid = ils_circulation_loan_pid_minter(record_uuid, data=new_loan)
loan = Loan.create(data=new_loan, id_=record_uuid)
params = deepcopy(loan)
params.update(document_pid=document_pid, **kwargs)
loan = current_circulation.circulation.trigger(
loan, **dict(params, trigger="request")
)
return pid, loan
def patron_has_active_loan_on_item(patron_pid, item_pid):
search = search_by_patron_item_or_document(
patron_pid=patron_pid,
item_pid=item_pid,
filter_states=current_app.config["CIRCULATION_STATES_LOAN_ACTIVE"],
)
search_result = search.execute()
return (
search_result.hits.total > 0
if lt_es7
else search_result.hits.total.value > 0
)
def checkout_loan(
item_pid,
patron_pid,
transaction_location_pid,
transaction_user_pid=None,
force=False,
**kwargs
):
if patron_has_active_loan_on_item(
patron_pid=patron_pid, item_pid=item_pid
):
raise PatronHasLoanOnItemError(patron_pid, item_pid)
optional_delivery = kwargs.get("delivery")
if optional_delivery:
_validate_delivery(optional_delivery)
if force:
_set_item_to_can_circulate(item_pid)
transaction_user_pid = transaction_user_pid or str(current_user.id)
record_uuid = uuid.uuid4()
new_loan = dict(
patron_pid=patron_pid,
transaction_location_pid=transaction_location_pid,
transaction_user_pid=transaction_user_pid,
)
pid = ils_circulation_loan_pid_minter(record_uuid, data=new_loan)
loan = Loan.create(data=new_loan, id_=record_uuid)
params = deepcopy(loan)
params.update(item_pid=item_pid, **kwargs)
loan = current_circulation.circulation.trigger(
loan, **dict(params, trigger="checkout")
)
return pid, loan
def update_dates_loan(record, start_date=None, end_date=None, request_start_date=None, request_expire_date=None):
state = record["state"]
is_active_or_completed = state in CIRCULATION_STATES_LOAN_ACTIVE \
or state in CIRCULATION_STATES_LOAN_COMPLETED
data = copy(record)
if is_active_or_completed:
today = date.today().strftime("%Y-%m-%d")
if request_start_date or request_expire_date:
raise IlsException(description="Cannot modify request dates of an active or completed loan.")
if start_date:
if start_date > today:
raise InvalidParameterError(description="Start date cannot be in the future for active loans.")
data["start_date"] = start_date
if end_date:
data["end_date"] = end_date
if data["end_date"] < data["start_date"]:
raise InvalidParameterError(description="Negative date range.")
else:
if start_date or end_date:
raise IlsException(description="Cannot modify dates of a pending or cancelled loan.")
if request_start_date:
data["request_start_date"] = request_start_date
if request_expire_date:
data["request_expire_date"] = request_expire_date
if data["request_expire_date"] < data["request_start_date"]:
raise InvalidParameterError(description="Negative date range.")
record.update(data)
record.commit()
db.session.commit()
current_circulation.loan_indexer().index(record)
return record
def circulation_default_loan_duration_for_item(item):
value = item.get("circulation_restriction", "NO_RESTRICTION")
if value == "ONE_WEEK":
return timedelta(weeks=1)
elif value == "TWO_WEEKS":
return timedelta(weeks=2)
elif value == "THREE_WEEKS":
return timedelta(weeks=3)
elif value == "FOUR_WEEKS":
return timedelta(weeks=4)
else:
return timedelta(weeks=4)
| true | true |
f72b9483d7b40b72fb27e1e57c80b24dc691d800 | 6,368 | py | Python | tests/functional/testplan/testing/test_tagging.py | raoyitao/testplan | aae3e9cee597ca3d01b6d64eed2642c421c56cbb | [
"Apache-2.0"
] | 96 | 2018-03-14T13:14:50.000Z | 2021-01-14T08:26:08.000Z | tests/functional/testplan/testing/test_tagging.py | raoyitao/testplan | aae3e9cee597ca3d01b6d64eed2642c421c56cbb | [
"Apache-2.0"
] | 135 | 2018-06-28T02:41:05.000Z | 2021-01-19T02:16:58.000Z | tests/functional/testplan/testing/test_tagging.py | raoyitao/testplan | aae3e9cee597ca3d01b6d64eed2642c421c56cbb | [
"Apache-2.0"
] | 53 | 2018-03-17T14:39:15.000Z | 2021-01-21T10:54:13.000Z | import pytest
from testplan.common.utils.testing import check_report
from testplan.report import TestReport, TestGroupReport, TestCaseReport
from testplan.testing.multitest import MultiTest, testsuite, testcase
@testsuite(tags={"color": ["red", "blue"]})
class AlphaSuite(object):
@testcase
def test_method_0(self, env, result):
pass
@testcase(tags=("foo", "bar"))
def test_method_1(self, env, result):
pass
@testcase(tags={"color": "green"})
def test_method_2(self, env, result):
pass
@testsuite(tags={"color": "yellow"})
class BetaSuite(object):
@testcase
def test_method_0(self, env, result):
pass
@testcase(tags="foo")
def test_method_1(self, env, result):
pass
@testcase(tags={"color": "red"})
def test_method_2(self, env, result):
pass
@testsuite
class GammaSuite(object):
@testcase
def test_method_0(self, env, result):
pass
@testcase(
parameters=("AAA", "BBB"),
tag_func=lambda kwargs: {"symbol": kwargs["value"].lower()},
tags={"speed": "slow"},
)
def test_param(self, env, result, value):
pass
@testcase(parameters=("XXX", "YYY"), tags={"speed": "fast"})
def test_param_2(self, env, result, value):
pass
report_for_multitest_without_tags = TestGroupReport(
name="MyMultitest",
category="multitest",
entries=[
TestGroupReport(
name="AlphaSuite",
category="testsuite",
tags={"color": {"red", "blue"}},
entries=[
TestCaseReport(name="test_method_0"),
TestCaseReport(
name="test_method_1", tags={"simple": {"foo", "bar"}}
),
TestCaseReport(
name="test_method_2", tags={"color": {"green"}}
),
],
),
TestGroupReport(
name="BetaSuite",
category="testsuite",
tags={"color": {"yellow"}},
entries=[
TestCaseReport(name="test_method_0"),
TestCaseReport(name="test_method_1", tags={"simple": {"foo"}}),
TestCaseReport(name="test_method_2", tags={"color": {"red"}}),
],
),
TestGroupReport(
name="GammaSuite",
category="testsuite",
entries=[
TestCaseReport(name="test_method_0"),
TestGroupReport(
name="test_param",
category="parametrization",
tags={"speed": {"slow"}},
entries=[
TestCaseReport(
name="test_param <value='AAA'>",
tags={"symbol": {"aaa"}},
),
TestCaseReport(
name="test_param <value='BBB'>",
tags={"symbol": {"bbb"}},
),
],
),
TestGroupReport(
name="test_param_2",
category="parametrization",
tags={"speed": {"fast"}},
entries=[
TestCaseReport(name="test_param_2 <value='XXX'>"),
TestCaseReport(name="test_param_2 <value='YYY'>"),
],
),
],
),
],
)
report_for_multitest_with_tags = TestGroupReport(
name="MyMultitest",
category="multitest",
tags={"color": {"orange"}, "environment": {"server"}},
entries=[
TestGroupReport(
name="AlphaSuite",
category="testsuite",
tags={"color": {"red", "blue"}},
entries=[
TestCaseReport(name="test_method_0"),
TestCaseReport(
name="test_method_1", tags={"simple": {"foo", "bar"}}
),
TestCaseReport(
name="test_method_2", tags={"color": {"green"}}
),
],
),
TestGroupReport(
name="BetaSuite",
category="testsuite",
tags={"color": {"yellow"}},
entries=[
TestCaseReport(name="test_method_0"),
TestCaseReport(name="test_method_1", tags={"simple": {"foo"}}),
TestCaseReport(name="test_method_2", tags={"color": {"red"}}),
],
),
TestGroupReport(
name="GammaSuite",
category="testsuite",
entries=[
TestCaseReport(name="test_method_0"),
TestGroupReport(
name="test_param",
category="parametrization",
tags={"speed": {"slow"}},
entries=[
TestCaseReport(
name="test_param <value='AAA'>",
tags={"symbol": {"aaa"}},
),
TestCaseReport(
name="test_param <value='BBB'>",
tags={"symbol": {"bbb"}},
),
],
),
TestGroupReport(
name="test_param_2",
category="parametrization",
tags={"speed": {"fast"}},
entries=[
TestCaseReport(name="test_param_2 <value='XXX'>"),
TestCaseReport(name="test_param_2 <value='YYY'>"),
],
),
],
),
],
)
@pytest.mark.parametrize(
"multitest_tags,expected_report",
(
({}, report_for_multitest_without_tags),
(
{"color": "orange", "environment": "server"},
report_for_multitest_with_tags,
),
),
)
def test_multitest_tagging(mockplan, multitest_tags, expected_report):
multitest = MultiTest(
name="MyMultitest",
suites=[AlphaSuite(), BetaSuite(), GammaSuite()],
tags=multitest_tags,
)
mockplan.add(multitest)
mockplan.run()
check_report(
expected=TestReport(name="plan", entries=[expected_report]),
actual=mockplan.report,
)
| 30.4689 | 79 | 0.468907 | import pytest
from testplan.common.utils.testing import check_report
from testplan.report import TestReport, TestGroupReport, TestCaseReport
from testplan.testing.multitest import MultiTest, testsuite, testcase
@testsuite(tags={"color": ["red", "blue"]})
class AlphaSuite(object):
@testcase
def test_method_0(self, env, result):
pass
@testcase(tags=("foo", "bar"))
def test_method_1(self, env, result):
pass
@testcase(tags={"color": "green"})
def test_method_2(self, env, result):
pass
@testsuite(tags={"color": "yellow"})
class BetaSuite(object):
@testcase
def test_method_0(self, env, result):
pass
@testcase(tags="foo")
def test_method_1(self, env, result):
pass
@testcase(tags={"color": "red"})
def test_method_2(self, env, result):
pass
@testsuite
class GammaSuite(object):
@testcase
def test_method_0(self, env, result):
pass
@testcase(
parameters=("AAA", "BBB"),
tag_func=lambda kwargs: {"symbol": kwargs["value"].lower()},
tags={"speed": "slow"},
)
def test_param(self, env, result, value):
pass
@testcase(parameters=("XXX", "YYY"), tags={"speed": "fast"})
def test_param_2(self, env, result, value):
pass
report_for_multitest_without_tags = TestGroupReport(
name="MyMultitest",
category="multitest",
entries=[
TestGroupReport(
name="AlphaSuite",
category="testsuite",
tags={"color": {"red", "blue"}},
entries=[
TestCaseReport(name="test_method_0"),
TestCaseReport(
name="test_method_1", tags={"simple": {"foo", "bar"}}
),
TestCaseReport(
name="test_method_2", tags={"color": {"green"}}
),
],
),
TestGroupReport(
name="BetaSuite",
category="testsuite",
tags={"color": {"yellow"}},
entries=[
TestCaseReport(name="test_method_0"),
TestCaseReport(name="test_method_1", tags={"simple": {"foo"}}),
TestCaseReport(name="test_method_2", tags={"color": {"red"}}),
],
),
TestGroupReport(
name="GammaSuite",
category="testsuite",
entries=[
TestCaseReport(name="test_method_0"),
TestGroupReport(
name="test_param",
category="parametrization",
tags={"speed": {"slow"}},
entries=[
TestCaseReport(
name="test_param <value='AAA'>",
tags={"symbol": {"aaa"}},
),
TestCaseReport(
name="test_param <value='BBB'>",
tags={"symbol": {"bbb"}},
),
],
),
TestGroupReport(
name="test_param_2",
category="parametrization",
tags={"speed": {"fast"}},
entries=[
TestCaseReport(name="test_param_2 <value='XXX'>"),
TestCaseReport(name="test_param_2 <value='YYY'>"),
],
),
],
),
],
)
report_for_multitest_with_tags = TestGroupReport(
name="MyMultitest",
category="multitest",
tags={"color": {"orange"}, "environment": {"server"}},
entries=[
TestGroupReport(
name="AlphaSuite",
category="testsuite",
tags={"color": {"red", "blue"}},
entries=[
TestCaseReport(name="test_method_0"),
TestCaseReport(
name="test_method_1", tags={"simple": {"foo", "bar"}}
),
TestCaseReport(
name="test_method_2", tags={"color": {"green"}}
),
],
),
TestGroupReport(
name="BetaSuite",
category="testsuite",
tags={"color": {"yellow"}},
entries=[
TestCaseReport(name="test_method_0"),
TestCaseReport(name="test_method_1", tags={"simple": {"foo"}}),
TestCaseReport(name="test_method_2", tags={"color": {"red"}}),
],
),
TestGroupReport(
name="GammaSuite",
category="testsuite",
entries=[
TestCaseReport(name="test_method_0"),
TestGroupReport(
name="test_param",
category="parametrization",
tags={"speed": {"slow"}},
entries=[
TestCaseReport(
name="test_param <value='AAA'>",
tags={"symbol": {"aaa"}},
),
TestCaseReport(
name="test_param <value='BBB'>",
tags={"symbol": {"bbb"}},
),
],
),
TestGroupReport(
name="test_param_2",
category="parametrization",
tags={"speed": {"fast"}},
entries=[
TestCaseReport(name="test_param_2 <value='XXX'>"),
TestCaseReport(name="test_param_2 <value='YYY'>"),
],
),
],
),
],
)
@pytest.mark.parametrize(
"multitest_tags,expected_report",
(
({}, report_for_multitest_without_tags),
(
{"color": "orange", "environment": "server"},
report_for_multitest_with_tags,
),
),
)
def test_multitest_tagging(mockplan, multitest_tags, expected_report):
multitest = MultiTest(
name="MyMultitest",
suites=[AlphaSuite(), BetaSuite(), GammaSuite()],
tags=multitest_tags,
)
mockplan.add(multitest)
mockplan.run()
check_report(
expected=TestReport(name="plan", entries=[expected_report]),
actual=mockplan.report,
)
| true | true |
f72b94a2fc75245f4a10ca168ed20ceaddbee478 | 12,107 | py | Python | test/functional/mining_basic.py | onixcoin-io/onix | 37c158a6229fa98c1a86f8b65e91226e36355fd6 | [
"MIT"
] | 6 | 2021-10-31T04:53:09.000Z | 2021-12-16T08:27:06.000Z | test/functional/mining_basic.py | onixcoin-io/onix | 37c158a6229fa98c1a86f8b65e91226e36355fd6 | [
"MIT"
] | 1 | 2021-11-29T08:45:38.000Z | 2021-11-29T08:45:38.000Z | test/functional/mining_basic.py | onixcoin-io/onix | 37c158a6229fa98c1a86f8b65e91226e36355fd6 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# Copyright (c) 2014-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test mining RPCs
- getmininginfo
- getblocktemplate proposal mode
- submitblock"""
import copy
from decimal import Decimal
from test_framework.blocktools import (
create_coinbase,
TIME_GENESIS_BLOCK,
)
from test_framework.messages import (
CBlock,
CBlockHeader
)
from test_framework.mininode import (
P2PDataStore,
)
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_equal,
assert_raises_rpc_error,
connect_nodes,
)
from test_framework.script import CScriptNum
BLOCK_HEADER_SIZE = len(CBlockHeader().serialize())
def assert_template(node, block, expect, rehash=True):
if rehash:
block.hashMerkleRoot = block.calc_merkle_root()
rsp = node.getblocktemplate(template_request={'data': block.serialize().hex(), 'mode': 'proposal', 'rules': ['segwit']})
assert_equal(rsp, expect)
class MiningTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 2
self.setup_clean_chain = True
self.supports_cli = False
def mine_chain(self):
self.log.info('Create some old blocks')
for t in range(TIME_GENESIS_BLOCK, TIME_GENESIS_BLOCK + 600 * 600, 600):
self.nodes[0].setmocktime(t)
self.nodes[0].generate(1)
mining_info = self.nodes[0].getmininginfo()
assert_equal(mining_info['blocks'], 600)
assert_equal(mining_info['currentblocktx'], 0)
assert_equal(mining_info['currentblockweight'], 4000)
self.restart_node(0)
connect_nodes(self.nodes[0], 1)
def run_test(self):
self.mine_chain()
node = self.nodes[0]
def assert_submitblock(block, result_str_1, result_str_2=None):
block.solve()
result_str_2 = result_str_2 or 'duplicate-invalid'
assert_equal(result_str_1, node.submitblock(hexdata=block.serialize().hex()))
assert_equal(result_str_2, node.submitblock(hexdata=block.serialize().hex()))
self.log.info('getmininginfo')
mining_info = node.getmininginfo()
assert_equal(mining_info['blocks'], 600)
assert_equal(mining_info['chain'], self.chain)
assert 'currentblocktx' not in mining_info
assert 'currentblockweight' not in mining_info
assert_equal(mining_info['difficulty']['proof-of-work'], Decimal('4.656542373906925E-10'))
assert_equal(mining_info['networkhashps'], Decimal('0.003333333333333334'))
assert_equal(mining_info['pooledtx'], 0)
# Mine a block to leave initial block download
node.generatetoaddress(1, node.get_deterministic_priv_key().address)
tmpl = node.getblocktemplate({'rules': ['segwit']})
self.log.info("getblocktemplate: Test capability advertised")
assert 'proposal' in tmpl['capabilities']
assert 'coinbasetxn' not in tmpl
coinbase_tx = create_coinbase(height=int(tmpl["height"]))
# sequence numbers must not be max for nLockTime to have effect
coinbase_tx.vin[0].nSequence = 2 ** 32 - 2
coinbase_tx.rehash()
# round-trip the encoded bip34 block height commitment
assert_equal(CScriptNum.decode(coinbase_tx.vin[0].scriptSig), 602)
# round-trip negative and multi-byte CScriptNums to catch python regression
assert_equal(CScriptNum.decode(CScriptNum.encode(CScriptNum(1500))), 1500)
assert_equal(CScriptNum.decode(CScriptNum.encode(CScriptNum(-1500))), -1500)
assert_equal(CScriptNum.decode(CScriptNum.encode(CScriptNum(-1))), -1)
block = CBlock()
block.nVersion = tmpl["version"]
block.hashPrevBlock = int(tmpl["previousblockhash"], 16)
block.nTime = tmpl["curtime"]
block.nBits = int(tmpl["bits"], 16)
block.nNonce = 0
block.vtx = [coinbase_tx]
self.log.info("getblocktemplate: segwit rule must be set")
assert_raises_rpc_error(-8, "getblocktemplate must be called with the segwit rule set", node.getblocktemplate)
self.log.info("getblocktemplate: Test valid block")
assert_template(node, block, None)
self.log.info("submitblock: Test block decode failure")
assert_raises_rpc_error(-22, "Block decode failed", node.submitblock, block.serialize()[:-15].hex())
self.log.info("getblocktemplate: Test bad input hash for coinbase transaction")
bad_block = copy.deepcopy(block)
bad_block.vtx[0].vin[0].prevout.hash += 1
bad_block.vtx[0].rehash()
assert_template(node, bad_block, 'bad-cb-missing')
self.log.info("submitblock: Test invalid coinbase transaction")
assert_raises_rpc_error(-22, "Block does not start with a coinbase", node.submitblock, bad_block.serialize().hex())
self.log.info("getblocktemplate: Test truncated final transaction")
assert_raises_rpc_error(-22, "Block decode failed", node.getblocktemplate, {'data': block.serialize()[:-1].hex(), 'mode': 'proposal', 'rules': ['segwit']})
self.log.info("getblocktemplate: Test duplicate transaction")
bad_block = copy.deepcopy(block)
bad_block.vtx.append(bad_block.vtx[0])
assert_template(node, bad_block, 'bad-txns-duplicate')
assert_submitblock(bad_block, 'bad-txns-duplicate', 'bad-txns-duplicate')
self.log.info("getblocktemplate: Test invalid transaction")
bad_block = copy.deepcopy(block)
bad_tx = copy.deepcopy(bad_block.vtx[0])
bad_tx.vin[0].prevout.hash = 255
bad_tx.rehash()
bad_block.vtx.append(bad_tx)
assert_template(node, bad_block, 'bad-txns-inputs-missingorspent')
assert_submitblock(bad_block, 'bad-txns-inputs-missingorspent')
self.log.info("getblocktemplate: Test nonfinal transaction")
bad_block = copy.deepcopy(block)
bad_block.vtx[0].nLockTime = 2 ** 32 - 1
bad_block.vtx[0].rehash()
assert_template(node, bad_block, 'bad-txns-nonfinal')
assert_submitblock(bad_block, 'bad-txns-nonfinal')
self.log.info("getblocktemplate: Test bad tx count")
# The tx count is immediately after the block header
TX_COUNT_OFFSET = 181
bad_block_sn = bytearray(block.serialize())
assert_equal(bad_block_sn[BLOCK_HEADER_SIZE], 1)
bad_block_sn[BLOCK_HEADER_SIZE] += 1
assert_raises_rpc_error(-22, "Block decode failed", node.getblocktemplate, {'data': bad_block_sn.hex(), 'mode': 'proposal', 'rules': ['segwit']})
self.log.info("getblocktemplate: Test bad bits")
bad_block = copy.deepcopy(block)
bad_block.nBits = 469762303 # impossible in the real world
assert_template(node, bad_block, 'bad-diffbits')
self.log.info("getblocktemplate: Test bad merkle root")
bad_block = copy.deepcopy(block)
bad_block.hashMerkleRoot += 1
assert_template(node, bad_block, 'bad-txnmrklroot', False)
assert_submitblock(bad_block, 'bad-txnmrklroot', 'bad-txnmrklroot')
#self.log.info("getblocktemplate: Test bad timestamps")
#bad_block = copy.deepcopy(block)
#bad_block.nTime = 2 ** 31 - 1
#assert_template(node, bad_block, 'time-too-new')
#assert_submitblock(bad_block, 'time-too-new', 'time-too-new')
#bad_block.nTime = 0
#assert_template(node, bad_block, 'time-too-old')
#assert_submitblock(bad_block, 'time-too-old', 'time-too-old')
self.log.info("getblocktemplate: Test not best block")
bad_block = copy.deepcopy(block)
bad_block.hashPrevBlock = 123
assert_template(node, bad_block, 'inconclusive-not-best-prevblk')
assert_submitblock(bad_block, 'prev-blk-not-found', 'prev-blk-not-found')
self.log.info('submitheader tests')
assert_raises_rpc_error(-22, 'Block header decode failed', lambda: node.submitheader(hexdata='xx' * BLOCK_HEADER_SIZE))
assert_raises_rpc_error(-22, 'Block header decode failed', lambda: node.submitheader(hexdata='ff' * (BLOCK_HEADER_SIZE-2)))
assert_raises_rpc_error(-25, 'Must submit previous header', lambda: node.submitheader(hexdata=super(CBlock, bad_block).serialize().hex()))
block.nTime += 1
block.solve()
def chain_tip(b_hash, *, status='headers-only', branchlen=1):
return {'hash': b_hash, 'height': 602, 'branchlen': branchlen, 'status': status}
assert chain_tip(block.hash) not in node.getchaintips()
node.submitheader(hexdata=block.serialize().hex())
assert chain_tip(block.hash) in node.getchaintips()
node.submitheader(hexdata=CBlockHeader(block).serialize().hex()) # Noop
assert chain_tip(block.hash) in node.getchaintips()
bad_block_root = copy.deepcopy(block)
bad_block_root.hashMerkleRoot += 2
bad_block_root.solve()
assert chain_tip(bad_block_root.hash) not in node.getchaintips()
node.submitheader(hexdata=CBlockHeader(bad_block_root).serialize().hex())
assert chain_tip(bad_block_root.hash) in node.getchaintips()
# Should still reject invalid blocks, even if we have the header:
assert_equal(node.submitblock(hexdata=bad_block_root.serialize().hex()), 'bad-txnmrklroot')
assert_equal(node.submitblock(hexdata=bad_block_root.serialize().hex()), 'bad-txnmrklroot')
assert chain_tip(bad_block_root.hash) in node.getchaintips()
# We know the header for this invalid block, so should just return early without error:
node.submitheader(hexdata=CBlockHeader(bad_block_root).serialize().hex())
assert chain_tip(bad_block_root.hash) in node.getchaintips()
bad_block_lock = copy.deepcopy(block)
bad_block_lock.vtx[0].nLockTime = 2**32 - 1
bad_block_lock.vtx[0].rehash()
bad_block_lock.hashMerkleRoot = bad_block_lock.calc_merkle_root()
bad_block_lock.solve()
assert_equal(node.submitblock(hexdata=bad_block_lock.serialize().hex()), 'bad-txns-nonfinal')
assert_equal(node.submitblock(hexdata=bad_block_lock.serialize().hex()), 'duplicate-invalid')
# Build a "good" block on top of the submitted bad block
bad_block2 = copy.deepcopy(block)
bad_block2.hashPrevBlock = bad_block_lock.sha256
bad_block2.solve()
assert_raises_rpc_error(-25, 'bad-prevblk', lambda: node.submitheader(hexdata=CBlockHeader(bad_block2).serialize().hex()))
# Should reject invalid header right away, only applies to PoS blocks in onix.
#bad_block_time = copy.deepcopy(block)
#bad_block_time.nTime = 1
#bad_block_time.solve()
#assert_raises_rpc_error(-25, 'time-too-old', lambda: node.submitheader(hexdata=CBlockHeader(bad_block_time).serialize().hex()))
# Should ask for the block from a p2p node, if they announce the header as well:
node.add_p2p_connection(P2PDataStore())
node.p2p.wait_for_getheaders(timeout=5) # Drop the first getheaders
node.p2p.send_blocks_and_test(blocks=[block], node=node)
# Must be active now:
assert chain_tip(block.hash, status='active', branchlen=0) in node.getchaintips()
# Building a few blocks should give the same results
node.generatetoaddress(10, node.get_deterministic_priv_key().address)
#assert_raises_rpc_error(-25, 'time-too-old', lambda: node.submitheader(hexdata=CBlockHeader(bad_block_time).serialize().hex()))
assert_raises_rpc_error(-25, 'bad-prevblk', lambda: node.submitheader(hexdata=CBlockHeader(bad_block2).serialize().hex()))
node.submitheader(hexdata=CBlockHeader(block).serialize().hex())
node.submitheader(hexdata=CBlockHeader(bad_block_root).serialize().hex())
assert_equal(node.submitblock(hexdata=block.serialize().hex()), 'duplicate') # valid
if __name__ == '__main__':
MiningTest().main()
| 48.043651 | 163 | 0.690262 |
import copy
from decimal import Decimal
from test_framework.blocktools import (
create_coinbase,
TIME_GENESIS_BLOCK,
)
from test_framework.messages import (
CBlock,
CBlockHeader
)
from test_framework.mininode import (
P2PDataStore,
)
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_equal,
assert_raises_rpc_error,
connect_nodes,
)
from test_framework.script import CScriptNum
BLOCK_HEADER_SIZE = len(CBlockHeader().serialize())
def assert_template(node, block, expect, rehash=True):
if rehash:
block.hashMerkleRoot = block.calc_merkle_root()
rsp = node.getblocktemplate(template_request={'data': block.serialize().hex(), 'mode': 'proposal', 'rules': ['segwit']})
assert_equal(rsp, expect)
class MiningTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 2
self.setup_clean_chain = True
self.supports_cli = False
def mine_chain(self):
self.log.info('Create some old blocks')
for t in range(TIME_GENESIS_BLOCK, TIME_GENESIS_BLOCK + 600 * 600, 600):
self.nodes[0].setmocktime(t)
self.nodes[0].generate(1)
mining_info = self.nodes[0].getmininginfo()
assert_equal(mining_info['blocks'], 600)
assert_equal(mining_info['currentblocktx'], 0)
assert_equal(mining_info['currentblockweight'], 4000)
self.restart_node(0)
connect_nodes(self.nodes[0], 1)
def run_test(self):
self.mine_chain()
node = self.nodes[0]
def assert_submitblock(block, result_str_1, result_str_2=None):
block.solve()
result_str_2 = result_str_2 or 'duplicate-invalid'
assert_equal(result_str_1, node.submitblock(hexdata=block.serialize().hex()))
assert_equal(result_str_2, node.submitblock(hexdata=block.serialize().hex()))
self.log.info('getmininginfo')
mining_info = node.getmininginfo()
assert_equal(mining_info['blocks'], 600)
assert_equal(mining_info['chain'], self.chain)
assert 'currentblocktx' not in mining_info
assert 'currentblockweight' not in mining_info
assert_equal(mining_info['difficulty']['proof-of-work'], Decimal('4.656542373906925E-10'))
assert_equal(mining_info['networkhashps'], Decimal('0.003333333333333334'))
assert_equal(mining_info['pooledtx'], 0)
node.generatetoaddress(1, node.get_deterministic_priv_key().address)
tmpl = node.getblocktemplate({'rules': ['segwit']})
self.log.info("getblocktemplate: Test capability advertised")
assert 'proposal' in tmpl['capabilities']
assert 'coinbasetxn' not in tmpl
coinbase_tx = create_coinbase(height=int(tmpl["height"]))
coinbase_tx.vin[0].nSequence = 2 ** 32 - 2
coinbase_tx.rehash()
assert_equal(CScriptNum.decode(coinbase_tx.vin[0].scriptSig), 602)
assert_equal(CScriptNum.decode(CScriptNum.encode(CScriptNum(1500))), 1500)
assert_equal(CScriptNum.decode(CScriptNum.encode(CScriptNum(-1500))), -1500)
assert_equal(CScriptNum.decode(CScriptNum.encode(CScriptNum(-1))), -1)
block = CBlock()
block.nVersion = tmpl["version"]
block.hashPrevBlock = int(tmpl["previousblockhash"], 16)
block.nTime = tmpl["curtime"]
block.nBits = int(tmpl["bits"], 16)
block.nNonce = 0
block.vtx = [coinbase_tx]
self.log.info("getblocktemplate: segwit rule must be set")
assert_raises_rpc_error(-8, "getblocktemplate must be called with the segwit rule set", node.getblocktemplate)
self.log.info("getblocktemplate: Test valid block")
assert_template(node, block, None)
self.log.info("submitblock: Test block decode failure")
assert_raises_rpc_error(-22, "Block decode failed", node.submitblock, block.serialize()[:-15].hex())
self.log.info("getblocktemplate: Test bad input hash for coinbase transaction")
bad_block = copy.deepcopy(block)
bad_block.vtx[0].vin[0].prevout.hash += 1
bad_block.vtx[0].rehash()
assert_template(node, bad_block, 'bad-cb-missing')
self.log.info("submitblock: Test invalid coinbase transaction")
assert_raises_rpc_error(-22, "Block does not start with a coinbase", node.submitblock, bad_block.serialize().hex())
self.log.info("getblocktemplate: Test truncated final transaction")
assert_raises_rpc_error(-22, "Block decode failed", node.getblocktemplate, {'data': block.serialize()[:-1].hex(), 'mode': 'proposal', 'rules': ['segwit']})
self.log.info("getblocktemplate: Test duplicate transaction")
bad_block = copy.deepcopy(block)
bad_block.vtx.append(bad_block.vtx[0])
assert_template(node, bad_block, 'bad-txns-duplicate')
assert_submitblock(bad_block, 'bad-txns-duplicate', 'bad-txns-duplicate')
self.log.info("getblocktemplate: Test invalid transaction")
bad_block = copy.deepcopy(block)
bad_tx = copy.deepcopy(bad_block.vtx[0])
bad_tx.vin[0].prevout.hash = 255
bad_tx.rehash()
bad_block.vtx.append(bad_tx)
assert_template(node, bad_block, 'bad-txns-inputs-missingorspent')
assert_submitblock(bad_block, 'bad-txns-inputs-missingorspent')
self.log.info("getblocktemplate: Test nonfinal transaction")
bad_block = copy.deepcopy(block)
bad_block.vtx[0].nLockTime = 2 ** 32 - 1
bad_block.vtx[0].rehash()
assert_template(node, bad_block, 'bad-txns-nonfinal')
assert_submitblock(bad_block, 'bad-txns-nonfinal')
self.log.info("getblocktemplate: Test bad tx count")
TX_COUNT_OFFSET = 181
bad_block_sn = bytearray(block.serialize())
assert_equal(bad_block_sn[BLOCK_HEADER_SIZE], 1)
bad_block_sn[BLOCK_HEADER_SIZE] += 1
assert_raises_rpc_error(-22, "Block decode failed", node.getblocktemplate, {'data': bad_block_sn.hex(), 'mode': 'proposal', 'rules': ['segwit']})
self.log.info("getblocktemplate: Test bad bits")
bad_block = copy.deepcopy(block)
bad_block.nBits = 469762303
assert_template(node, bad_block, 'bad-diffbits')
self.log.info("getblocktemplate: Test bad merkle root")
bad_block = copy.deepcopy(block)
bad_block.hashMerkleRoot += 1
assert_template(node, bad_block, 'bad-txnmrklroot', False)
assert_submitblock(bad_block, 'bad-txnmrklroot', 'bad-txnmrklroot')
self.log.info("getblocktemplate: Test not best block")
bad_block = copy.deepcopy(block)
bad_block.hashPrevBlock = 123
assert_template(node, bad_block, 'inconclusive-not-best-prevblk')
assert_submitblock(bad_block, 'prev-blk-not-found', 'prev-blk-not-found')
self.log.info('submitheader tests')
assert_raises_rpc_error(-22, 'Block header decode failed', lambda: node.submitheader(hexdata='xx' * BLOCK_HEADER_SIZE))
assert_raises_rpc_error(-22, 'Block header decode failed', lambda: node.submitheader(hexdata='ff' * (BLOCK_HEADER_SIZE-2)))
assert_raises_rpc_error(-25, 'Must submit previous header', lambda: node.submitheader(hexdata=super(CBlock, bad_block).serialize().hex()))
block.nTime += 1
block.solve()
def chain_tip(b_hash, *, status='headers-only', branchlen=1):
return {'hash': b_hash, 'height': 602, 'branchlen': branchlen, 'status': status}
assert chain_tip(block.hash) not in node.getchaintips()
node.submitheader(hexdata=block.serialize().hex())
assert chain_tip(block.hash) in node.getchaintips()
node.submitheader(hexdata=CBlockHeader(block).serialize().hex())
assert chain_tip(block.hash) in node.getchaintips()
bad_block_root = copy.deepcopy(block)
bad_block_root.hashMerkleRoot += 2
bad_block_root.solve()
assert chain_tip(bad_block_root.hash) not in node.getchaintips()
node.submitheader(hexdata=CBlockHeader(bad_block_root).serialize().hex())
assert chain_tip(bad_block_root.hash) in node.getchaintips()
assert_equal(node.submitblock(hexdata=bad_block_root.serialize().hex()), 'bad-txnmrklroot')
assert_equal(node.submitblock(hexdata=bad_block_root.serialize().hex()), 'bad-txnmrklroot')
assert chain_tip(bad_block_root.hash) in node.getchaintips()
node.submitheader(hexdata=CBlockHeader(bad_block_root).serialize().hex())
assert chain_tip(bad_block_root.hash) in node.getchaintips()
bad_block_lock = copy.deepcopy(block)
bad_block_lock.vtx[0].nLockTime = 2**32 - 1
bad_block_lock.vtx[0].rehash()
bad_block_lock.hashMerkleRoot = bad_block_lock.calc_merkle_root()
bad_block_lock.solve()
assert_equal(node.submitblock(hexdata=bad_block_lock.serialize().hex()), 'bad-txns-nonfinal')
assert_equal(node.submitblock(hexdata=bad_block_lock.serialize().hex()), 'duplicate-invalid')
bad_block2 = copy.deepcopy(block)
bad_block2.hashPrevBlock = bad_block_lock.sha256
bad_block2.solve()
assert_raises_rpc_error(-25, 'bad-prevblk', lambda: node.submitheader(hexdata=CBlockHeader(bad_block2).serialize().hex()))
node.add_p2p_connection(P2PDataStore())
node.p2p.wait_for_getheaders(timeout=5)
node.p2p.send_blocks_and_test(blocks=[block], node=node)
assert chain_tip(block.hash, status='active', branchlen=0) in node.getchaintips()
node.generatetoaddress(10, node.get_deterministic_priv_key().address)
assert_raises_rpc_error(-25, 'bad-prevblk', lambda: node.submitheader(hexdata=CBlockHeader(bad_block2).serialize().hex()))
node.submitheader(hexdata=CBlockHeader(block).serialize().hex())
node.submitheader(hexdata=CBlockHeader(bad_block_root).serialize().hex())
assert_equal(node.submitblock(hexdata=block.serialize().hex()), 'duplicate')
if __name__ == '__main__':
MiningTest().main()
| true | true |
f72b9664774aac869ec7bb4e09b59f25f377508a | 3,245 | py | Python | twikoto3/mainwindow.py | azyobuzin/twikoto3 | 8a4efc4ff7280a559f448234cbc3a0bc740e8388 | [
"Apache-2.0"
] | 1 | 2017-12-27T09:50:47.000Z | 2017-12-27T09:50:47.000Z | twikoto3/mainwindow.py | azyobuzin/twikoto3 | 8a4efc4ff7280a559f448234cbc3a0bc740e8388 | [
"Apache-2.0"
] | null | null | null | twikoto3/mainwindow.py | azyobuzin/twikoto3 | 8a4efc4ff7280a559f448234cbc3a0bc740e8388 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
"""
twikoto3 - Twitter Client
Copyright (C) 2012 azyobuzin
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from PyQt4 import QtCore, QtGui
import twikoto3
from twikoto3.extension import *
from twikoto3.twittertext import validator
class TweetTextEdit(QtGui.QTextEdit):
def __init__(self, parent = None):
super(TweetTextEdit, self).__init__(parent)
self.tweetaction = None
def keyPressEvent(self, e):
if e.key() == QtCore.Qt.Key_Return and (e.modifiers() and QtCore.Qt.ControlModifier):
self.tweetaction()
else:
super(TweetTextEdit, self).keyPressEvent(e)
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent = None):
super(MainWindow, self).__init__(parent)
self.setWindowTitle("ついこと 3")
self.layout = QtGui.QVBoxLayout()
self.textedit_tweet = TweetTextEdit()
self.textedit_tweet.setMinimumHeight(46)
self.textedit_tweet.textChanged.connect(self.textedit_tweet_textChanged)
self.textedit_tweet.tweetaction = self.button_tweet_clicked
self.layout.addWidget(self.textedit_tweet)
self.layout_tweetbutton = QtGui.QHBoxLayout()
self.layout.addLayout(self.layout_tweetbutton)
self.label_textcount = QtGui.QLabel("140")
self.layout_tweetbutton.addWidget(self.label_textcount)
self.button_tweet = QtGui.QPushButton("Tweet")
self.button_tweet.clicked.connect(self.button_tweet_clicked)
self.layout_tweetbutton.addWidget(self.button_tweet)
self.centralWidget = QtGui.QWidget()
self.centralWidget.setLayout(self.layout)
self.setCentralWidget(self.centralWidget)
def button_tweet_clicked(self):
status = self.textedit_tweet.toPlainText()
if status | noneoremptystr():
return
self.button_tweet.setEnabled(False)
thread = twikoto3.twitter.updatestatus(status)
def finished():
self.button_tweet.setEnabled(True)
if thread.response is not None:
self.textedit_tweet.setPlainText("")
else:
QtGui.QMessageBox.critical(self, "投稿失敗", str(thread.exception))
thread.finished.connect(finished)
thread.start()
def textedit_tweet_textChanged(self):
self.label_textcount.setText(str(validator.MAX_TWEET_LENGTH - validator.getTweetLength(self.textedit_tweet.toPlainText())))
instance = None
def getinstance():
if MainWindow.instance is None:
MainWindow.instance = MainWindow()
return MainWindow.instance
| 35.659341 | 131 | 0.693991 |
from PyQt4 import QtCore, QtGui
import twikoto3
from twikoto3.extension import *
from twikoto3.twittertext import validator
class TweetTextEdit(QtGui.QTextEdit):
def __init__(self, parent = None):
super(TweetTextEdit, self).__init__(parent)
self.tweetaction = None
def keyPressEvent(self, e):
if e.key() == QtCore.Qt.Key_Return and (e.modifiers() and QtCore.Qt.ControlModifier):
self.tweetaction()
else:
super(TweetTextEdit, self).keyPressEvent(e)
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent = None):
super(MainWindow, self).__init__(parent)
self.setWindowTitle("ついこと 3")
self.layout = QtGui.QVBoxLayout()
self.textedit_tweet = TweetTextEdit()
self.textedit_tweet.setMinimumHeight(46)
self.textedit_tweet.textChanged.connect(self.textedit_tweet_textChanged)
self.textedit_tweet.tweetaction = self.button_tweet_clicked
self.layout.addWidget(self.textedit_tweet)
self.layout_tweetbutton = QtGui.QHBoxLayout()
self.layout.addLayout(self.layout_tweetbutton)
self.label_textcount = QtGui.QLabel("140")
self.layout_tweetbutton.addWidget(self.label_textcount)
self.button_tweet = QtGui.QPushButton("Tweet")
self.button_tweet.clicked.connect(self.button_tweet_clicked)
self.layout_tweetbutton.addWidget(self.button_tweet)
self.centralWidget = QtGui.QWidget()
self.centralWidget.setLayout(self.layout)
self.setCentralWidget(self.centralWidget)
def button_tweet_clicked(self):
status = self.textedit_tweet.toPlainText()
if status | noneoremptystr():
return
self.button_tweet.setEnabled(False)
thread = twikoto3.twitter.updatestatus(status)
def finished():
self.button_tweet.setEnabled(True)
if thread.response is not None:
self.textedit_tweet.setPlainText("")
else:
QtGui.QMessageBox.critical(self, "投稿失敗", str(thread.exception))
thread.finished.connect(finished)
thread.start()
def textedit_tweet_textChanged(self):
self.label_textcount.setText(str(validator.MAX_TWEET_LENGTH - validator.getTweetLength(self.textedit_tweet.toPlainText())))
instance = None
def getinstance():
if MainWindow.instance is None:
MainWindow.instance = MainWindow()
return MainWindow.instance
| true | true |
f72b96fd84fbba9e15af0f1cd90ccc4befda2a17 | 519 | py | Python | dataset/processes/make_center_points.py | Challenging6/YoloDB | bdc1c4239ec112c21a65df64b9f4dc8447b739fa | [
"MIT"
] | null | null | null | dataset/processes/make_center_points.py | Challenging6/YoloDB | bdc1c4239ec112c21a65df64b9f4dc8447b739fa | [
"MIT"
] | null | null | null | dataset/processes/make_center_points.py | Challenging6/YoloDB | bdc1c4239ec112c21a65df64b9f4dc8447b739fa | [
"MIT"
] | null | null | null | import numpy as np
#from concern.config import State
from .data_process import DataProcess
class MakeCenterPoints(DataProcess):
box_key = 'charboxes'
size = 32
def process(self, data):
shape = data['image'].shape[:2]
points = np.zeros((self.size, 2), dtype=np.float32)
boxes = np.array(data[self.box_key])[:self.size]
size = boxes.shape[0]
points[:size] = boxes.mean(axis=1)
data['points'] = (points / shape[::-1]).astype(np.float32)
return data
| 25.95 | 66 | 0.626204 | import numpy as np
from .data_process import DataProcess
class MakeCenterPoints(DataProcess):
box_key = 'charboxes'
size = 32
def process(self, data):
shape = data['image'].shape[:2]
points = np.zeros((self.size, 2), dtype=np.float32)
boxes = np.array(data[self.box_key])[:self.size]
size = boxes.shape[0]
points[:size] = boxes.mean(axis=1)
data['points'] = (points / shape[::-1]).astype(np.float32)
return data
| true | true |
f72b995a0c976a846d2650b3d530e5ff685e31e0 | 1,456 | py | Python | setup.py | ammurdoch/graphql-core | 03c2b06e4636ed8a89c7a4c7e56d244fd9d00bde | [
"MIT"
] | 1 | 2021-07-27T20:47:34.000Z | 2021-07-27T20:47:34.000Z | setup.py | vpetrovykh/graphql-core | 7af97e22afb27861fc1b7d7ca0292095f8427ecb | [
"MIT"
] | null | null | null | setup.py | vpetrovykh/graphql-core | 7af97e22afb27861fc1b7d7ca0292095f8427ecb | [
"MIT"
] | null | null | null | from re import search
from setuptools import setup, find_packages
with open("src/graphql/version.py") as version_file:
version = search('version = "(.*)"', version_file.read()).group(1)
with open("README.md") as readme_file:
readme = readme_file.read()
setup(
name="graphql-core",
version=version,
description="GraphQL implementation for Python, a port of GraphQL.js,"
" the JavaScript reference implementation for GraphQL.",
long_description=readme,
long_description_content_type="text/markdown",
keywords="graphql",
url="https://github.com/graphql-python/graphql-core",
author="Christoph Zwerschke",
author_email="cito@online.de",
license="MIT license",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Topic :: Software Development :: Libraries",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
],
install_requires=[],
python_requires=">=3.6,<4",
packages=find_packages("src"),
package_dir={"": "src"},
# PEP-561: https://www.python.org/dev/peps/pep-0561/
package_data={"graphql": ["py.typed"]},
include_package_data=True,
zip_safe=False,
)
| 34.666667 | 74 | 0.651099 | from re import search
from setuptools import setup, find_packages
with open("src/graphql/version.py") as version_file:
version = search('version = "(.*)"', version_file.read()).group(1)
with open("README.md") as readme_file:
readme = readme_file.read()
setup(
name="graphql-core",
version=version,
description="GraphQL implementation for Python, a port of GraphQL.js,"
" the JavaScript reference implementation for GraphQL.",
long_description=readme,
long_description_content_type="text/markdown",
keywords="graphql",
url="https://github.com/graphql-python/graphql-core",
author="Christoph Zwerschke",
author_email="cito@online.de",
license="MIT license",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Topic :: Software Development :: Libraries",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
],
install_requires=[],
python_requires=">=3.6,<4",
packages=find_packages("src"),
package_dir={"": "src"},
package_data={"graphql": ["py.typed"]},
include_package_data=True,
zip_safe=False,
)
| true | true |
f72b99ae1a3457bb9180b67219d05ac2ccfc50cd | 1,200 | py | Python | Noise Elimination/mean_elimination_script.py | BAD-Classifier/Signal-Processing | 8163657fb8b8e1ec32ea299a5b4cda9473b91fd0 | [
"MIT"
] | null | null | null | Noise Elimination/mean_elimination_script.py | BAD-Classifier/Signal-Processing | 8163657fb8b8e1ec32ea299a5b4cda9473b91fd0 | [
"MIT"
] | null | null | null | Noise Elimination/mean_elimination_script.py | BAD-Classifier/Signal-Processing | 8163657fb8b8e1ec32ea299a5b4cda9473b91fd0 | [
"MIT"
] | null | null | null | import numpy
import librosa
import glob
import os
import shutil
full_clips = glob.glob("Full_Clips/*.mp3")
print("Number of full clips: " + str(len(full_clips)))
for clip in full_clips:
clip_name = clip[11:]
print("Current clip: " + clip_name)
signal, fs = librosa.load(clip)
signal_abs = numpy.absolute(signal)
search_name = "Cut_Clips/" + clip_name[:-4] + "*[0-9].*"
cut_clips = glob.glob(search_name)
print("Number of clip segments: " + str(len(cut_clips)))
total_mean = numpy.mean(signal_abs)
print("Signal Total mean: " + str(total_mean))
condition = total_mean*0.25
for record in cut_clips:
signal_segment, sample_rate_segment = librosa.load(record)
mean = numpy.mean(numpy.abs(signal_segment))
if mean < condition:
print(record)
print("Segment mean: " + str(mean))
shutil.move(record,"Rejected_noise/")
rejected_clips = glob.glob("Rejected_noise/*.wav")
print(rejected_clips)
for item in rejected_clips:
name = item[15:]
new_name = "All_MFCCs/" + name[:-3] + "png"
if os.path.isfile(new_name):
shutil.move(new_name, "Rejected_MFCCS/")
| 30.769231 | 66 | 0.643333 | import numpy
import librosa
import glob
import os
import shutil
full_clips = glob.glob("Full_Clips/*.mp3")
print("Number of full clips: " + str(len(full_clips)))
for clip in full_clips:
clip_name = clip[11:]
print("Current clip: " + clip_name)
signal, fs = librosa.load(clip)
signal_abs = numpy.absolute(signal)
search_name = "Cut_Clips/" + clip_name[:-4] + "*[0-9].*"
cut_clips = glob.glob(search_name)
print("Number of clip segments: " + str(len(cut_clips)))
total_mean = numpy.mean(signal_abs)
print("Signal Total mean: " + str(total_mean))
condition = total_mean*0.25
for record in cut_clips:
signal_segment, sample_rate_segment = librosa.load(record)
mean = numpy.mean(numpy.abs(signal_segment))
if mean < condition:
print(record)
print("Segment mean: " + str(mean))
shutil.move(record,"Rejected_noise/")
rejected_clips = glob.glob("Rejected_noise/*.wav")
print(rejected_clips)
for item in rejected_clips:
name = item[15:]
new_name = "All_MFCCs/" + name[:-3] + "png"
if os.path.isfile(new_name):
shutil.move(new_name, "Rejected_MFCCS/")
| true | true |
f72b9a83a149804ec5bf2fd5f521cbb2d63c0d98 | 1,384 | py | Python | tests/parser/syntax/test_functions_call.py | Solexplorer/vyper | 135edd6a91d47c72de105066d6e6c1bdfe9ea66e | [
"MIT"
] | 1 | 2021-04-23T21:48:20.000Z | 2021-04-23T21:48:20.000Z | tests/parser/syntax/test_functions_call.py | Solexplorer/vyper | 135edd6a91d47c72de105066d6e6c1bdfe9ea66e | [
"MIT"
] | null | null | null | tests/parser/syntax/test_functions_call.py | Solexplorer/vyper | 135edd6a91d47c72de105066d6e6c1bdfe9ea66e | [
"MIT"
] | 1 | 2020-01-27T05:21:46.000Z | 2020-01-27T05:21:46.000Z | import pytest
from pytest import (
raises,
)
from vyper import (
compiler,
)
from vyper.exceptions import (
ParserException,
StructureException,
)
fail_list = [
"""
@public
def foo() -> uint256:
doesnotexist(2, uint256)
return convert(2, uint256)
""",
"""
@public
def foo() -> uint256:
convert(2, uint256)
return convert(2, uint256)
""",
("""
@private
def test(a : uint256):
pass
@public
def burn(_value: uint256):
self.test(msg.sender._value)
""", ParserException)
]
@pytest.mark.parametrize('bad_code', fail_list)
def test_functions_call_fail(bad_code):
if isinstance(bad_code, tuple):
with raises(bad_code[1]):
compiler.compile_code(bad_code[0])
else:
with raises(StructureException):
compiler.compile_code(bad_code)
valid_list = [
"""
@public
def foo() -> uint256:
return convert(2, uint256)
""",
"""
from vyper.interfaces import ERC20
contract Factory:
def getExchange(token_addr: address) -> address: constant
token: ERC20
factory: Factory
@public
def setup(token_addr: address):
self.token = ERC20(token_addr)
assert self.factory.getExchange(self.token) == self
"""
]
@pytest.mark.parametrize('good_code', valid_list)
def test_functions_call_success(good_code):
assert compiler.compile_code(good_code) is not None
| 17.74359 | 61 | 0.664017 | import pytest
from pytest import (
raises,
)
from vyper import (
compiler,
)
from vyper.exceptions import (
ParserException,
StructureException,
)
fail_list = [
"""
@public
def foo() -> uint256:
doesnotexist(2, uint256)
return convert(2, uint256)
""",
"""
@public
def foo() -> uint256:
convert(2, uint256)
return convert(2, uint256)
""",
("""
@private
def test(a : uint256):
pass
@public
def burn(_value: uint256):
self.test(msg.sender._value)
""", ParserException)
]
@pytest.mark.parametrize('bad_code', fail_list)
def test_functions_call_fail(bad_code):
if isinstance(bad_code, tuple):
with raises(bad_code[1]):
compiler.compile_code(bad_code[0])
else:
with raises(StructureException):
compiler.compile_code(bad_code)
valid_list = [
"""
@public
def foo() -> uint256:
return convert(2, uint256)
""",
"""
from vyper.interfaces import ERC20
contract Factory:
def getExchange(token_addr: address) -> address: constant
token: ERC20
factory: Factory
@public
def setup(token_addr: address):
self.token = ERC20(token_addr)
assert self.factory.getExchange(self.token) == self
"""
]
@pytest.mark.parametrize('good_code', valid_list)
def test_functions_call_success(good_code):
assert compiler.compile_code(good_code) is not None
| true | true |
f72b9b0270340672ef3e38e9ca7507f43250ba2a | 222 | py | Python | aws_test/testapp/views.py | shivavh123/django | 1f94b50d0f5cf5b0b90dcf86afbc267500a3732b | [
"MIT"
] | null | null | null | aws_test/testapp/views.py | shivavh123/django | 1f94b50d0f5cf5b0b90dcf86afbc267500a3732b | [
"MIT"
] | null | null | null | aws_test/testapp/views.py | shivavh123/django | 1f94b50d0f5cf5b0b90dcf86afbc267500a3732b | [
"MIT"
] | null | null | null | from django.shortcuts import render
from django.http import *
# Create your views here.
def test_view(request,name):
data = "Hi, Welcome {}, this is first view in AWS....".format(name)
return HttpResponse(data) | 22.2 | 71 | 0.711712 | from django.shortcuts import render
from django.http import *
def test_view(request,name):
data = "Hi, Welcome {}, this is first view in AWS....".format(name)
return HttpResponse(data) | true | true |
f72b9b18157277dd97c650ac9b1513b389eba29b | 1,411 | py | Python | channels_graphql_ws/__init__.py | hozblok/DjangoChannelsGraphqlWs | 77b406fb19053fcb9220a5bb23e1349fde4fbda3 | [
"MIT"
] | null | null | null | channels_graphql_ws/__init__.py | hozblok/DjangoChannelsGraphqlWs | 77b406fb19053fcb9220a5bb23e1349fde4fbda3 | [
"MIT"
] | null | null | null | channels_graphql_ws/__init__.py | hozblok/DjangoChannelsGraphqlWs | 77b406fb19053fcb9220a5bb23e1349fde4fbda3 | [
"MIT"
] | null | null | null | #
# coding: utf-8
# Copyright (c) 2019 DATADVANCE
#
# 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.
"""Websocket GraphQL server with subscriptions.
Django Channels based WebSocket GraphQL server with Graphene-like
subscriptions.
"""
from .client import GraphqlWsClient, GraphqlWsResponseError
from .graphql_ws import GraphqlWsConsumer, Subscription
from .transport import GraphqlWsTransportAiohttp
| 41.5 | 72 | 0.79022 |
from .client import GraphqlWsClient, GraphqlWsResponseError
from .graphql_ws import GraphqlWsConsumer, Subscription
from .transport import GraphqlWsTransportAiohttp
| true | true |
f72b9b237c832c25f3a47690b75b5f4398085165 | 4,558 | py | Python | alphazero/mcts.py | bartekx43/AlphaTTT | a01c38833a7f841483146bebeef73323d527d812 | [
"MIT"
] | null | null | null | alphazero/mcts.py | bartekx43/AlphaTTT | a01c38833a7f841483146bebeef73323d527d812 | [
"MIT"
] | null | null | null | alphazero/mcts.py | bartekx43/AlphaTTT | a01c38833a7f841483146bebeef73323d527d812 | [
"MIT"
] | null | null | null | import os
import sys
import math
import random
import numpy as np
from copy import deepcopy
sys.path.append(os.path.join(os.environ["HOME"], "AlphaTTT"))
from environment import Environment
from alphazero.database import prepare_state
np.random.seed(80085)
random.seed(80085)
def PUCT_score(child_value, child_prior, parent_visit_count, child_visit_count, c_puct):
pb_c = child_prior * math.sqrt(parent_visit_count) / (child_visit_count + 1)
return child_value + c_puct * pb_c
class MCTS():
def __init__(self, model, root_state, args):
'''
model - class with predict method that returns a valid policy and value
root_state - board_len x board_len array with the initial state of the game
args:
num_simulations - number of leaf node expansions per search
alpha - mixing constant between policy and dirichlet noise
dirichlet_alpha - dirichlet constant for generating dirichlet distribution
c_puct - exploration constant in PUCT score
'''
self.model = model
self.root = deepcopy(root_state)
self.args = args
self.Qsa = {} # self.Qsa(s, a) = Q value for (s, a)
self.Nsa = {} # self.Nsa(s, a) = (s, a) visit count
self.Ns = {} # self.Ns(s) = s visit count
self.Ps = {} # self.Ps(s) = list of available actions in s and corresponding raw probabilities
self.Es = {} # terminal states, potentially going to do this if not too computationally expensive and dirty
# Add dirichlet noise to initial root node
self.add_dirichlet()
def add_dirichlet(self):
rs = self.root.tobytes()
if rs not in self.Ps:
self.find_leaf(deepcopy(self.root))
if self.Es[rs] == 10:
dirichlet = np.random.dirichlet([self.args["dirichlet_alpha"]]*len(self.Ps[rs]))
for i, (move, prob) in enumerate(self.Ps[rs]):
self.Ps[rs][i] = (move, (1 - self.args["alpha"]) * prob + dirichlet[i] * self.args["alpha"])
def search(self): # builds the search tree from the root node
for i in range(self.args["num_simulations"]):
self.find_leaf(deepcopy(self.root))
return
def find_leaf(self, state):
s = state.tobytes()
if s not in self.Es:
self.Es[s] = Environment.game_over(state)
if self.Es[s] != 10:
# terminal state
return -self.Es[s]
if s not in self.Ps: # expand leaf node
p, v = self.model.predict(prepare_state(state))
availability_mask = (state == 0)
p *= availability_mask
if np.sum(p) > 0.0:
p /= np.sum(p) # re-normalize
move_probs = []
for i, row in enumerate(p):
for j, prob in enumerate(row):
if state[i][j] == 0:
move_probs.append(((i, j), prob))
self.Ps[s] = move_probs
self.Ns[s] = 1
return -v
max_puct = -float('inf')
max_action = None
for move, prob in self.Ps[s]:
(Nc, Qc) = (self.Nsa[(s, move)], self.Qsa[(s, move)]) if (s, move) in self.Nsa else (0, 0.0)
puct = PUCT_score(Qc, prob, self.Ns[s], Nc, self.args["c_puct"])
if puct > max_puct:
max_puct = puct
max_action = move
a = max_action
state[a] = 1
state *= -1
v = self.find_leaf(state)
if (s, a) in self.Nsa:
self.Nsa[(s, a)] += 1
self.Qsa[(s, a)] = (self.Nsa[(s, a)] * self.Qsa[(s, a)] + v) / (self.Nsa[(s, a)] + 1)
else:
self.Nsa[(s, a)] = 1
self.Qsa[(s, a)] = v
self.Ns[s] += 1
return -v
def get_pi(self, tau=1.0, as_prob=True):
move_dist = np.zeros((len(self.root), len(self.root)))
rs = self.root.tobytes()
for move, _ in self.Ps[rs]:
move_dist[move] = self.Nsa[(rs, move)] if (rs, move) in self.Nsa else 0
if as_prob is True:
if tau < 0.1: # protecting from numerical overflow
z = np.zeros(move_dist.shape)
move = np.unravel_index(np.argmax(move_dist), move_dist.shape)
z[move[0]][move[1]] = 1.0
move_dist = z
else:
move_dist = np.power(move_dist, 1.0/tau)
if np.sum(move_dist) > 0.0:
move_dist /= np.sum(move_dist)
return move_dist
def select_move(self, tau=1.0, external_move=None):
if external_move is None:
probas = self.get_pi(tau)
selected_move = int(np.random.choice(len(probas.flatten()), 1, p=probas.flatten()))
selected_move = np.unravel_index(selected_move, probas.shape)
else:
selected_move = external_move
self.root[selected_move] = 1
self.root *= -1
# Add dirichlet noise to new root node:
self.add_dirichlet()
return selected_move
| 31.006803 | 111 | 0.623958 | import os
import sys
import math
import random
import numpy as np
from copy import deepcopy
sys.path.append(os.path.join(os.environ["HOME"], "AlphaTTT"))
from environment import Environment
from alphazero.database import prepare_state
np.random.seed(80085)
random.seed(80085)
def PUCT_score(child_value, child_prior, parent_visit_count, child_visit_count, c_puct):
pb_c = child_prior * math.sqrt(parent_visit_count) / (child_visit_count + 1)
return child_value + c_puct * pb_c
class MCTS():
def __init__(self, model, root_state, args):
self.model = model
self.root = deepcopy(root_state)
self.args = args
self.Qsa = {}
self.Nsa = {}
self.Ns = {}
self.Ps = {}
self.Es = {}
self.add_dirichlet()
def add_dirichlet(self):
rs = self.root.tobytes()
if rs not in self.Ps:
self.find_leaf(deepcopy(self.root))
if self.Es[rs] == 10:
dirichlet = np.random.dirichlet([self.args["dirichlet_alpha"]]*len(self.Ps[rs]))
for i, (move, prob) in enumerate(self.Ps[rs]):
self.Ps[rs][i] = (move, (1 - self.args["alpha"]) * prob + dirichlet[i] * self.args["alpha"])
def search(self):
for i in range(self.args["num_simulations"]):
self.find_leaf(deepcopy(self.root))
return
def find_leaf(self, state):
s = state.tobytes()
if s not in self.Es:
self.Es[s] = Environment.game_over(state)
if self.Es[s] != 10:
return -self.Es[s]
if s not in self.Ps:
p, v = self.model.predict(prepare_state(state))
availability_mask = (state == 0)
p *= availability_mask
if np.sum(p) > 0.0:
p /= np.sum(p)
move_probs = []
for i, row in enumerate(p):
for j, prob in enumerate(row):
if state[i][j] == 0:
move_probs.append(((i, j), prob))
self.Ps[s] = move_probs
self.Ns[s] = 1
return -v
max_puct = -float('inf')
max_action = None
for move, prob in self.Ps[s]:
(Nc, Qc) = (self.Nsa[(s, move)], self.Qsa[(s, move)]) if (s, move) in self.Nsa else (0, 0.0)
puct = PUCT_score(Qc, prob, self.Ns[s], Nc, self.args["c_puct"])
if puct > max_puct:
max_puct = puct
max_action = move
a = max_action
state[a] = 1
state *= -1
v = self.find_leaf(state)
if (s, a) in self.Nsa:
self.Nsa[(s, a)] += 1
self.Qsa[(s, a)] = (self.Nsa[(s, a)] * self.Qsa[(s, a)] + v) / (self.Nsa[(s, a)] + 1)
else:
self.Nsa[(s, a)] = 1
self.Qsa[(s, a)] = v
self.Ns[s] += 1
return -v
def get_pi(self, tau=1.0, as_prob=True):
move_dist = np.zeros((len(self.root), len(self.root)))
rs = self.root.tobytes()
for move, _ in self.Ps[rs]:
move_dist[move] = self.Nsa[(rs, move)] if (rs, move) in self.Nsa else 0
if as_prob is True:
if tau < 0.1:
z = np.zeros(move_dist.shape)
move = np.unravel_index(np.argmax(move_dist), move_dist.shape)
z[move[0]][move[1]] = 1.0
move_dist = z
else:
move_dist = np.power(move_dist, 1.0/tau)
if np.sum(move_dist) > 0.0:
move_dist /= np.sum(move_dist)
return move_dist
def select_move(self, tau=1.0, external_move=None):
if external_move is None:
probas = self.get_pi(tau)
selected_move = int(np.random.choice(len(probas.flatten()), 1, p=probas.flatten()))
selected_move = np.unravel_index(selected_move, probas.shape)
else:
selected_move = external_move
self.root[selected_move] = 1
self.root *= -1
self.add_dirichlet()
return selected_move
| true | true |
f72b9b71cfe4c76f04ff852319ec57e7120fbde7 | 70 | py | Python | tests/test_graph_container.py | harangju/wikinet | 903cf94e30f6dae3de3a3615ce6cd67091f512dc | [
"MIT"
] | 9 | 2020-10-19T12:36:49.000Z | 2021-09-07T02:31:52.000Z | tests/test_graph_container.py | harangju/wikinet | 903cf94e30f6dae3de3a3615ce6cd67091f512dc | [
"MIT"
] | 1 | 2022-03-30T09:34:56.000Z | 2022-03-30T14:08:48.000Z | tests/test_graph_container.py | harangju/wikinet | 903cf94e30f6dae3de3a3615ce6cd67091f512dc | [
"MIT"
] | 5 | 2020-10-20T01:39:14.000Z | 2022-03-30T17:12:30.000Z | import wikinet
print('hello world')
print(wikinet.GraphContainer())
| 11.666667 | 31 | 0.771429 | import wikinet
print('hello world')
print(wikinet.GraphContainer())
| true | true |
f72b9c283b7d0547ed71c29c45e273ec49018748 | 876 | py | Python | paneldata_dash/resources/category.py | clarencejlee/jdp | d3d31db0138ff06f2f5ec592d85317941af4f280 | [
"MIT"
] | null | null | null | paneldata_dash/resources/category.py | clarencejlee/jdp | d3d31db0138ff06f2f5ec592d85317941af4f280 | [
"MIT"
] | null | null | null | paneldata_dash/resources/category.py | clarencejlee/jdp | d3d31db0138ff06f2f5ec592d85317941af4f280 | [
"MIT"
] | null | null | null | from flask import request
from flask_restful import Resource
from models.category import CategoryModel
from schemas.category import CategorySchema
category_schema = CategorySchema()
category_list_schema = CategorySchema(many=True)
class Category(Resource):
@classmethod
def get(cls, name: str):
category = CategoryModel.find_by_name(name)
if category:
return category_schema.dump(category), 200
return {"message": "Category not found"}, 404
class CategoryList(Resource):
@classmethod
def get(cls):
page = 1 if (request.args.get("page") is None or request.args.get("page") == 0) \
else int(request.args.get("page")) + 1
size = 10 if request.args.get("size") is None else int(request.args.get("size"))
return {"categories": category_list_schema.dump(CategoryModel.find_all())}, 200
| 30.206897 | 89 | 0.692922 | from flask import request
from flask_restful import Resource
from models.category import CategoryModel
from schemas.category import CategorySchema
category_schema = CategorySchema()
category_list_schema = CategorySchema(many=True)
class Category(Resource):
@classmethod
def get(cls, name: str):
category = CategoryModel.find_by_name(name)
if category:
return category_schema.dump(category), 200
return {"message": "Category not found"}, 404
class CategoryList(Resource):
@classmethod
def get(cls):
page = 1 if (request.args.get("page") is None or request.args.get("page") == 0) \
else int(request.args.get("page")) + 1
size = 10 if request.args.get("size") is None else int(request.args.get("size"))
return {"categories": category_list_schema.dump(CategoryModel.find_all())}, 200
| true | true |
f72b9e6674fbda39b41025e89556f609b84326ea | 2,699 | py | Python | masonite/drivers/UploadS3Driver.py | w3x10e8/core | d8f0ca29c2bd5e86d199391fa916ce2f5c9b0f49 | [
"MIT"
] | null | null | null | masonite/drivers/UploadS3Driver.py | w3x10e8/core | d8f0ca29c2bd5e86d199391fa916ce2f5c9b0f49 | [
"MIT"
] | null | null | null | masonite/drivers/UploadS3Driver.py | w3x10e8/core | d8f0ca29c2bd5e86d199391fa916ce2f5c9b0f49 | [
"MIT"
] | null | null | null | """ Upload S3 Driver """
from masonite.contracts import UploadContract
from masonite.drivers import BaseUploadDriver
from masonite.exceptions import DriverLibraryNotFound
from masonite.managers import UploadManager
from masonite.app import App
class UploadS3Driver(BaseUploadDriver, UploadContract):
"""
Amazon S3 Upload driver
"""
def __init__(self, upload: UploadManager, app: App):
"""Upload Disk Driver Constructor
Arguments:
UploadManager {masonite.managers.UploadManager} -- The Upload Manager object.
StorageConfig {config.storage} -- Storage configuration.
"""
self.upload = upload
self.config = app.make('StorageConfig')
def store(self, fileitem, location=None):
"""Store the file into Amazon S3 server.
Arguments:
fileitem {cgi.Storage} -- Storage object.
Keyword Arguments:
location {string} -- The location on disk you would like to store the file. (default: {None})
Raises:
DriverLibraryNotFound -- Raises when the boto3 library is not installed.
Returns:
string -- Returns the file name just saved.
"""
driver = self.upload.driver('disk')
driver.store(fileitem, location)
file_location = driver.file_location
# Check if is a valid extension
self.validate_extension(fileitem.filename)
try:
import boto3
except ImportError:
raise DriverLibraryNotFound(
'Could not find the "boto3" library. Please pip install this library by running "pip install boto3"')
session = boto3.Session(
aws_access_key_id=self.config.DRIVERS['s3']['client'],
aws_secret_access_key=self.config.DRIVERS['s3']['secret'],
)
s3 = session.resource('s3')
s3.meta.client.upload_file(
file_location,
self.config.DRIVERS['s3']['bucket'],
fileitem.filename
)
return fileitem.filename
def store_prepend(self, fileitem, prepend, location=None):
"""Store the file onto the Amazon S3 server but with a prepended file name.
Arguments:
fileitem {cgi.Storage} -- Storage object.
prepend {string} -- The prefix you want to prepend to the file name.
Keyword Arguments:
location {string} -- The location on disk you would like to store the file. (default: {None})
Returns:
string -- Returns the file name just saved.
"""
fileitem.filename = prepend + fileitem.filename
return self.store(fileitem, location=location)
| 31.022989 | 117 | 0.632086 |
from masonite.contracts import UploadContract
from masonite.drivers import BaseUploadDriver
from masonite.exceptions import DriverLibraryNotFound
from masonite.managers import UploadManager
from masonite.app import App
class UploadS3Driver(BaseUploadDriver, UploadContract):
def __init__(self, upload: UploadManager, app: App):
self.upload = upload
self.config = app.make('StorageConfig')
def store(self, fileitem, location=None):
driver = self.upload.driver('disk')
driver.store(fileitem, location)
file_location = driver.file_location
self.validate_extension(fileitem.filename)
try:
import boto3
except ImportError:
raise DriverLibraryNotFound(
'Could not find the "boto3" library. Please pip install this library by running "pip install boto3"')
session = boto3.Session(
aws_access_key_id=self.config.DRIVERS['s3']['client'],
aws_secret_access_key=self.config.DRIVERS['s3']['secret'],
)
s3 = session.resource('s3')
s3.meta.client.upload_file(
file_location,
self.config.DRIVERS['s3']['bucket'],
fileitem.filename
)
return fileitem.filename
def store_prepend(self, fileitem, prepend, location=None):
fileitem.filename = prepend + fileitem.filename
return self.store(fileitem, location=location)
| true | true |
f72b9ebf1fe11a999e122be4418851c61b594f29 | 9,487 | py | Python | ensemble/control/operational/TestOperationalLayerEnsembleVissim.py | licit-lab/ensemble | 7a78ef0d69610d4fcfc5e008f931ade15e35acbf | [
"Linux-OpenIB"
] | null | null | null | ensemble/control/operational/TestOperationalLayerEnsembleVissim.py | licit-lab/ensemble | 7a78ef0d69610d4fcfc5e008f931ade15e35acbf | [
"Linux-OpenIB"
] | null | null | null | ensemble/control/operational/TestOperationalLayerEnsembleVissim.py | licit-lab/ensemble | 7a78ef0d69610d4fcfc5e008f931ade15e35acbf | [
"Linux-OpenIB"
] | null | null | null | import os
import sys
import ctypes
import platform
import os
import numpy as np
from random import gauss
import win32com.client as com
def get_acceleration(lead_veh_acceleration,lead_veh_id,lead_veh_rel_velocity,lead_veh_type,timestep,
veh_id,veh_setspeed,veh_type,veh_used_distance_headway,veh_used_rel_vel,veh_velocity,
veh_distance_headway,prev_veh_executed_acceleration,
prev_veh_cc_setpoint,prev_veh_cruisecontrol_acceleration):
if platform.system() == 'Windows':
print('Running on win')
filepath = "L:\\UserData\\Kingsley\\PythonEnsembleTestBed"
file_dll = os.path.join(filepath, 'OperationalDLL.dll')
#file_dll = './OperationalDLL.dll'
elif platform.system() == 'Darwin':
print('Running on mac')
file_dll = 'OperationalDLL.dylib'
else:
print('System not supported')
sys.exit()
# Load operational DLL
lib = None
try:
lib = ctypes.cdll.LoadLibrary(file_dll)
except:
print('Error: DLL file could not be found')
quit()
# Set input values: Write value's for current vehicle, in current timestep
curr_lead_veh_acceleration = ctypes.c_double(lead_veh_acceleration) #2.0
curr_lead_veh_id = ctypes.c_long(lead_veh_id) #40
curr_lead_veh_rel_velocity = ctypes.c_double(lead_veh_rel_velocity ) #-1.0
curr_lead_veh_type = ctypes.c_long(lead_veh_type) #10
curr_timestep = ctypes.c_double(timestep) #55.0
curr_ts_length = ctypes.c_double(0.1)
curr_veh_id = ctypes.c_long(veh_id) #10
curr_veh_setspeed = ctypes.c_double(veh_setspeed) #88/3.6
curr_veh_type = ctypes.c_long(veh_type) #10
curr_veh_controller_in_use = ctypes.c_long(1) # from tactical layer 1=ACC,2=CACC
curr_veh_ACC_h = ctypes.c_double(1.6)
curr_veh_CACC_h = ctypes.c_double(0.6)
curr_veh_used_distance_headway = ctypes.c_double(veh_used_distance_headway)#20.0
curr_veh_used_rel_vel = ctypes.c_double(veh_used_rel_vel) #-1.0
curr_veh_velocity = ctypes.c_double(veh_velocity) #85/3.6
curr_veh_autonomous_operational_warning = ctypes.c_long(10)
curr_veh_platooning_max_acceleration = ctypes.c_double(2.0)
prev_veh_cc_setpoint = ctypes.c_double(prev_veh_cc_setpoint)
prev_veh_cruisecontrol_acceleration = ctypes.c_double(prev_veh_cruisecontrol_acceleration)
prev_veh_distance_headway = ctypes.c_double(veh_distance_headway) #20.0
prev_veh_executed_acceleration = ctypes.c_double(prev_veh_executed_acceleration) #-2.0
# Define variables for return values: These are placeholders, no action required
veh_autonomous_operational_acceleration = ctypes.c_double(1)
veh_autonomous_operational_mixingmode = ctypes.c_long(1)
veh_autonomous_operational_warning = ctypes.c_double(1)
veh_cc_setpoint = ctypes.c_double(1)
veh_cruisecontrol_acceleration = ctypes.c_double(1)
success = ctypes.c_int(0)
print("Now call the OL itself...")
# Call operational controller
lib.operational_controller(
curr_lead_veh_acceleration,
curr_lead_veh_id,
curr_lead_veh_rel_velocity,
curr_lead_veh_type,
curr_timestep,
curr_ts_length,
curr_veh_id,
curr_veh_setspeed,
curr_veh_type,
curr_veh_controller_in_use,
curr_veh_ACC_h,
curr_veh_CACC_h,
curr_veh_used_distance_headway,
curr_veh_used_rel_vel,
curr_veh_velocity,
curr_veh_autonomous_operational_warning,
curr_veh_platooning_max_acceleration,
prev_veh_cc_setpoint,
prev_veh_cruisecontrol_acceleration,
prev_veh_distance_headway,
prev_veh_executed_acceleration,
ctypes.byref(veh_autonomous_operational_acceleration),
ctypes.byref(veh_autonomous_operational_mixingmode),
ctypes.byref(veh_autonomous_operational_warning),
ctypes.byref(veh_cc_setpoint),
ctypes.byref(veh_cruisecontrol_acceleration),
ctypes.byref(success))
# Print the return values
if success.value > 0:
veh_acceleration=veh_autonomous_operational_acceleration.value
#print(veh_autonomous_operational_mixingmode.value)
#print(veh_autonomous_operational_warning.value)
veh_cc_set_point=veh_cc_setpoint.value
veh_cruise_control_acceleration=veh_cruisecontrol_acceleration.value
else:
veh_acceleration=-999
veh_cc_setpoint=-999
veh_cruise_control_acceleration=-999
print('An error occurred while calling DLL')
return veh_acceleration,veh_cc_setpoint,veh_cruise_control_acceleration
Vissim = com.gencache.EnsureDispatch("Vissim.Vissim")
GlosaNetworkPath='D:\\Projects\\ENSEMBLE\\Vissim_networks\\Pipeline'#'L:\\UserData\\Kingsley\\Ensemble'
#'L:\\UserData\\Kingsley\\SafeDriving'
#'L:\\UserData\\Kingsley\\Ensemble'#'C:\\Users\\Public\\Documents\\GLOSA\\GlosaTrafficLight'
Filename= os.path.join(GlosaNetworkPath, 'Pipeline.inpx')
#os.path.join(GlosaNetworkPath, 'KnooppuntZonzeelBackup.inpx') #os.path.join(GlosaNetworkPath, 'GlosaTestNetwork2.inpx')
#os.path.join(GlosaNetworkPath, 'TestNetwork.inpx')
flag_read_additionally = False # you can read network(elements) additionally, in this case set "flag_read_additionally" to true
Vissim.LoadNet(Filename, flag_read_additionally)
## Load a Layout:
Filename = os.path.join(GlosaNetworkPath, 'Pipeline.layx')
#os.path.join(GlosaNetworkPath, 'KnooppuntZonzeelBackup.layx')
#os.path.join(GlosaNetworkPath, 'TestNetwork.layx')
#os.path.join(GlosaNetworkPath, 'KnooppuntZonzeelBackup.layx')#os.path.join(GlosaNetworkPath, 'GlosaTestNetwork2.layx')
Vissim.LoadLayout(Filename)
End_of_simulation = 6000 # simulation second [s]
Simulation_Resolution = 10 # simulation second [s]
Number_Runs=4
Simulation_Period=300
Vissim.Simulation.SetAttValue('SimRes', Simulation_Resolution)
Vissim.Simulation.SetAttValue('NumRuns', Number_Runs)
Vissim.Simulation.SetAttValue('SimPeriod', Simulation_Period)
#UDA6
#Vissim.Net.UserDefinedAttributes.AddUserDefinedDataAttribute(6,'Vehicle','vehAcceleration','vehAcceleration',2,0)
#Vissim.Net.UserDefinedAttributes.ItemByKey(6).SetAttValue('DefValue',-1)
#UDA6
Vissim.Net.UserDefinedAttributes.AddUserDefinedDataAttribute(3,'Vehicle','COM_cruise_control_Ac','COM_cruise_control_Ac',2,0)
Vissim.Net.UserDefinedAttributes.ItemByKey(3).SetAttValue('DefValue',-1)
#UDA
Vissim.Net.UserDefinedAttributes.AddUserDefinedDataAttribute(4,'Vehicle','COM_cc_setpoint','COM_cc_setpoint',2,0)
Vissim.Net.UserDefinedAttributes.ItemByKey(4).SetAttValue('DefValue',-1)
def get_leader_info(Vehicle):
lead_veh_id = Vehicle.AttValue('LeadTargNo')
lead_veh_type = Vehicle.AttValue('LeadTargType')
if lead_veh_type == 'VEHICLE' and lead_veh_id != None:
try:
front_vehicle = Vissim.Net.Vehicles.ItemByKey(lead_veh_id)
except:
front_vehicle = -1
else:
front_vehicle=-1
return front_vehicle
#prev_veh_cc_setpoint = np.zeros(number_of_vehicles)
for i in range(6000):
for Vehicle in Vissim.Net.Vehicles.FilteredBy("[VEHTYPE\\NO]=210"):
lead_veh=get_leader_info(Vehicle)
if lead_veh!=-1 and (Vehicle.AttValue('Lane')==lead_veh.AttValue('Lane')):
#simulation info
timestep=Vehicle.AttValue('SimSec')
#Ego Info
print((Vehicle.AttValue('Lane')))
veh_id=Vehicle.AttValue('No')
veh_setspeed=Vehicle.AttValue('DesSpeed')/3.6
veh_type=Vehicle.AttValue('VehType\\No')
veh_used_distance_headway=Vehicle.AttValue('FollowDistNet')
veh_used_rel_vel=(Vehicle.AttValue('Speed')-lead_veh.AttValue('Speed'))/3.6
veh_velocity=Vehicle.AttValue('Speed')/3.6
veh_distance_headway=Vehicle.AttValue('FollowDistNet')
prev_veh_executed_acceleration = Vehicle.AttValue('COM_Ac')
prev_veh_cc_setpoint = Vehicle.AttValue('COM_cc_setpoint')
prev_veh_cruisecontrol_acceleration=Vehicle.AttValue('COM_cruise_control_Ac')
#veh_executed_acceleration=a_prev[veh_id]
#veh_cc_setpoint=prev_veh_cc_setpoint[veh_id]
# Leader Info
lead_veh_acceleration=lead_veh.AttValue('Acceleration')
lead_veh_id=lead_veh.AttValue('No')
lead_veh_rel_velocity=(Vehicle.AttValue('Speed')-lead_veh.AttValue('Speed'))/3.6
lead_veh_type=lead_veh.AttValue('VehType\\No')
curr_veh_executed_acceleration,curr_veh_cc_set_point,curr_veh_cruisecontrol_acceleration=get_acceleration(lead_veh_acceleration,lead_veh_id,lead_veh_rel_velocity,lead_veh_type,timestep,
veh_id,veh_setspeed,veh_type,veh_used_distance_headway,veh_used_rel_vel,veh_velocity,
veh_distance_headway,prev_veh_executed_acceleration,
prev_veh_cc_setpoint,prev_veh_cruisecontrol_acceleration)
# a=call vehicle_model(curr_veh_executed_acceleration)
write_file('file_variables.txt')
Vehicle.SetAttValue('COM_Ac',curr_veh_executed_acceleration)
#Vehicle.SetAttValue('COM_Ac', a)
Vehicle.SetAttValue('COM_At',3)
Vehicle.SetAttValue('COM_cc_setpoint', curr_veh_cc_set_point)
Vehicle.SetAttValue('COM_cruise_control_Ac', curr_veh_cruisecontrol_acceleration)
else:
continue
Vissim.Simulation.RunSingleStep()
| 47.673367 | 197 | 0.733214 | import os
import sys
import ctypes
import platform
import os
import numpy as np
from random import gauss
import win32com.client as com
def get_acceleration(lead_veh_acceleration,lead_veh_id,lead_veh_rel_velocity,lead_veh_type,timestep,
veh_id,veh_setspeed,veh_type,veh_used_distance_headway,veh_used_rel_vel,veh_velocity,
veh_distance_headway,prev_veh_executed_acceleration,
prev_veh_cc_setpoint,prev_veh_cruisecontrol_acceleration):
if platform.system() == 'Windows':
print('Running on win')
filepath = "L:\\UserData\\Kingsley\\PythonEnsembleTestBed"
file_dll = os.path.join(filepath, 'OperationalDLL.dll')
elif platform.system() == 'Darwin':
print('Running on mac')
file_dll = 'OperationalDLL.dylib'
else:
print('System not supported')
sys.exit()
lib = None
try:
lib = ctypes.cdll.LoadLibrary(file_dll)
except:
print('Error: DLL file could not be found')
quit()
curr_lead_veh_acceleration = ctypes.c_double(lead_veh_acceleration) #2.0
curr_lead_veh_id = ctypes.c_long(lead_veh_id) #40
curr_lead_veh_rel_velocity = ctypes.c_double(lead_veh_rel_velocity ) #-1.0
curr_lead_veh_type = ctypes.c_long(lead_veh_type) #10
curr_timestep = ctypes.c_double(timestep) #55.0
curr_ts_length = ctypes.c_double(0.1)
curr_veh_id = ctypes.c_long(veh_id) #10
curr_veh_setspeed = ctypes.c_double(veh_setspeed) #88/3.6
curr_veh_type = ctypes.c_long(veh_type) #10
curr_veh_controller_in_use = ctypes.c_long(1) # from tactical layer 1=ACC,2=CACC
curr_veh_ACC_h = ctypes.c_double(1.6)
curr_veh_CACC_h = ctypes.c_double(0.6)
curr_veh_used_distance_headway = ctypes.c_double(veh_used_distance_headway)#20.0
curr_veh_used_rel_vel = ctypes.c_double(veh_used_rel_vel) #-1.0
curr_veh_velocity = ctypes.c_double(veh_velocity) #85/3.6
curr_veh_autonomous_operational_warning = ctypes.c_long(10)
curr_veh_platooning_max_acceleration = ctypes.c_double(2.0)
prev_veh_cc_setpoint = ctypes.c_double(prev_veh_cc_setpoint)
prev_veh_cruisecontrol_acceleration = ctypes.c_double(prev_veh_cruisecontrol_acceleration)
prev_veh_distance_headway = ctypes.c_double(veh_distance_headway) #20.0
prev_veh_executed_acceleration = ctypes.c_double(prev_veh_executed_acceleration) #-2.0
# Define variables for return values: These are placeholders, no action required
veh_autonomous_operational_acceleration = ctypes.c_double(1)
veh_autonomous_operational_mixingmode = ctypes.c_long(1)
veh_autonomous_operational_warning = ctypes.c_double(1)
veh_cc_setpoint = ctypes.c_double(1)
veh_cruisecontrol_acceleration = ctypes.c_double(1)
success = ctypes.c_int(0)
print("Now call the OL itself...")
# Call operational controller
lib.operational_controller(
curr_lead_veh_acceleration,
curr_lead_veh_id,
curr_lead_veh_rel_velocity,
curr_lead_veh_type,
curr_timestep,
curr_ts_length,
curr_veh_id,
curr_veh_setspeed,
curr_veh_type,
curr_veh_controller_in_use,
curr_veh_ACC_h,
curr_veh_CACC_h,
curr_veh_used_distance_headway,
curr_veh_used_rel_vel,
curr_veh_velocity,
curr_veh_autonomous_operational_warning,
curr_veh_platooning_max_acceleration,
prev_veh_cc_setpoint,
prev_veh_cruisecontrol_acceleration,
prev_veh_distance_headway,
prev_veh_executed_acceleration,
ctypes.byref(veh_autonomous_operational_acceleration),
ctypes.byref(veh_autonomous_operational_mixingmode),
ctypes.byref(veh_autonomous_operational_warning),
ctypes.byref(veh_cc_setpoint),
ctypes.byref(veh_cruisecontrol_acceleration),
ctypes.byref(success))
# Print the return values
if success.value > 0:
veh_acceleration=veh_autonomous_operational_acceleration.value
#print(veh_autonomous_operational_mixingmode.value)
#print(veh_autonomous_operational_warning.value)
veh_cc_set_point=veh_cc_setpoint.value
veh_cruise_control_acceleration=veh_cruisecontrol_acceleration.value
else:
veh_acceleration=-999
veh_cc_setpoint=-999
veh_cruise_control_acceleration=-999
print('An error occurred while calling DLL')
return veh_acceleration,veh_cc_setpoint,veh_cruise_control_acceleration
Vissim = com.gencache.EnsureDispatch("Vissim.Vissim")
GlosaNetworkPath='D:\\Projects\\ENSEMBLE\\Vissim_networks\\Pipeline'#'L:\\UserData\\Kingsley\\Ensemble'
#'L:\\UserData\\Kingsley\\SafeDriving'
#'L:\\UserData\\Kingsley\\Ensemble'#'C:\\Users\\Public\\Documents\\GLOSA\\GlosaTrafficLight'
Filename= os.path.join(GlosaNetworkPath, 'Pipeline.inpx')
#os.path.join(GlosaNetworkPath, 'KnooppuntZonzeelBackup.inpx') #os.path.join(GlosaNetworkPath, 'GlosaTestNetwork2.inpx')
#os.path.join(GlosaNetworkPath, 'TestNetwork.inpx')
flag_read_additionally = False # you can read network(elements) additionally, in this case set "flag_read_additionally" to true
Vissim.LoadNet(Filename, flag_read_additionally)
## Load a Layout:
Filename = os.path.join(GlosaNetworkPath, 'Pipeline.layx')
#os.path.join(GlosaNetworkPath, 'KnooppuntZonzeelBackup.layx')
#os.path.join(GlosaNetworkPath, 'TestNetwork.layx')
#os.path.join(GlosaNetworkPath, 'KnooppuntZonzeelBackup.layx')#os.path.join(GlosaNetworkPath, 'GlosaTestNetwork2.layx')
Vissim.LoadLayout(Filename)
End_of_simulation = 6000 # simulation second [s]
Simulation_Resolution = 10 # simulation second [s]
Number_Runs=4
Simulation_Period=300
Vissim.Simulation.SetAttValue('SimRes', Simulation_Resolution)
Vissim.Simulation.SetAttValue('NumRuns', Number_Runs)
Vissim.Simulation.SetAttValue('SimPeriod', Simulation_Period)
#UDA6
#Vissim.Net.UserDefinedAttributes.AddUserDefinedDataAttribute(6,'Vehicle','vehAcceleration','vehAcceleration',2,0)
#Vissim.Net.UserDefinedAttributes.ItemByKey(6).SetAttValue('DefValue',-1)
#UDA6
Vissim.Net.UserDefinedAttributes.AddUserDefinedDataAttribute(3,'Vehicle','COM_cruise_control_Ac','COM_cruise_control_Ac',2,0)
Vissim.Net.UserDefinedAttributes.ItemByKey(3).SetAttValue('DefValue',-1)
#UDA
Vissim.Net.UserDefinedAttributes.AddUserDefinedDataAttribute(4,'Vehicle','COM_cc_setpoint','COM_cc_setpoint',2,0)
Vissim.Net.UserDefinedAttributes.ItemByKey(4).SetAttValue('DefValue',-1)
def get_leader_info(Vehicle):
lead_veh_id = Vehicle.AttValue('LeadTargNo')
lead_veh_type = Vehicle.AttValue('LeadTargType')
if lead_veh_type == 'VEHICLE' and lead_veh_id != None:
try:
front_vehicle = Vissim.Net.Vehicles.ItemByKey(lead_veh_id)
except:
front_vehicle = -1
else:
front_vehicle=-1
return front_vehicle
#prev_veh_cc_setpoint = np.zeros(number_of_vehicles)
for i in range(6000):
for Vehicle in Vissim.Net.Vehicles.FilteredBy("[VEHTYPE\\NO]=210"):
lead_veh=get_leader_info(Vehicle)
if lead_veh!=-1 and (Vehicle.AttValue('Lane')==lead_veh.AttValue('Lane')):
#simulation info
timestep=Vehicle.AttValue('SimSec')
#Ego Info
print((Vehicle.AttValue('Lane')))
veh_id=Vehicle.AttValue('No')
veh_setspeed=Vehicle.AttValue('DesSpeed')/3.6
veh_type=Vehicle.AttValue('VehType\\No')
veh_used_distance_headway=Vehicle.AttValue('FollowDistNet')
veh_used_rel_vel=(Vehicle.AttValue('Speed')-lead_veh.AttValue('Speed'))/3.6
veh_velocity=Vehicle.AttValue('Speed')/3.6
veh_distance_headway=Vehicle.AttValue('FollowDistNet')
prev_veh_executed_acceleration = Vehicle.AttValue('COM_Ac')
prev_veh_cc_setpoint = Vehicle.AttValue('COM_cc_setpoint')
prev_veh_cruisecontrol_acceleration=Vehicle.AttValue('COM_cruise_control_Ac')
#veh_executed_acceleration=a_prev[veh_id]
#veh_cc_setpoint=prev_veh_cc_setpoint[veh_id]
# Leader Info
lead_veh_acceleration=lead_veh.AttValue('Acceleration')
lead_veh_id=lead_veh.AttValue('No')
lead_veh_rel_velocity=(Vehicle.AttValue('Speed')-lead_veh.AttValue('Speed'))/3.6
lead_veh_type=lead_veh.AttValue('VehType\\No')
curr_veh_executed_acceleration,curr_veh_cc_set_point,curr_veh_cruisecontrol_acceleration=get_acceleration(lead_veh_acceleration,lead_veh_id,lead_veh_rel_velocity,lead_veh_type,timestep,
veh_id,veh_setspeed,veh_type,veh_used_distance_headway,veh_used_rel_vel,veh_velocity,
veh_distance_headway,prev_veh_executed_acceleration,
prev_veh_cc_setpoint,prev_veh_cruisecontrol_acceleration)
# a=call vehicle_model(curr_veh_executed_acceleration)
write_file('file_variables.txt')
Vehicle.SetAttValue('COM_Ac',curr_veh_executed_acceleration)
#Vehicle.SetAttValue('COM_Ac', a)
Vehicle.SetAttValue('COM_At',3)
Vehicle.SetAttValue('COM_cc_setpoint', curr_veh_cc_set_point)
Vehicle.SetAttValue('COM_cruise_control_Ac', curr_veh_cruisecontrol_acceleration)
else:
continue
Vissim.Simulation.RunSingleStep()
| true | true |
f72b9f3d90e40913efdff7e7d1f1b70359588488 | 15,361 | py | Python | main.py | SultanAbuGhazal/3detr | f9725ae655c6ced290c3ec2c53c07566350270f4 | [
"Apache-2.0"
] | null | null | null | main.py | SultanAbuGhazal/3detr | f9725ae655c6ced290c3ec2c53c07566350270f4 | [
"Apache-2.0"
] | null | null | null | main.py | SultanAbuGhazal/3detr | f9725ae655c6ced290c3ec2c53c07566350270f4 | [
"Apache-2.0"
] | null | null | null | # Copyright (c) Facebook, Inc. and its affiliates.
import argparse
import os
import sys
import pickle
import numpy as np
import torch
from torch.multiprocessing import set_start_method
from torch.utils.data import DataLoader, DistributedSampler
# 3DETR codebase specific imports
from datasets import build_dataset
from engine import evaluate, train_one_epoch
from models import build_model
from optimizer import build_optimizer
from criterion import build_criterion
from utils.dist import init_distributed, is_distributed, is_primary, get_rank, barrier
from utils.misc import my_worker_init_fn
from utils.io import save_checkpoint, resume_if_possible
from utils.logger import Logger
def make_args_parser():
parser = argparse.ArgumentParser("3D Detection Using Transformers", add_help=False)
##### Optimizer #####
parser.add_argument("--base_lr", default=5e-4, type=float)
parser.add_argument("--warm_lr", default=1e-6, type=float)
parser.add_argument("--warm_lr_epochs", default=9, type=int)
parser.add_argument("--final_lr", default=1e-6, type=float)
parser.add_argument("--lr_scheduler", default="cosine", type=str)
parser.add_argument("--weight_decay", default=0.1, type=float)
parser.add_argument("--filter_biases_wd", default=False, action="store_true")
parser.add_argument(
"--clip_gradient", default=0.1, type=float, help="Max L2 norm of the gradient"
)
##### Model #####
parser.add_argument(
"--model_name",
default="3detr",
type=str,
help="Name of the model",
choices=["3detr"],
)
### Encoder
parser.add_argument(
"--enc_type", default="vanilla", choices=["masked", "maskedv2", "vanilla"]
)
# Below options are only valid for vanilla encoder
parser.add_argument("--enc_nlayers", default=3, type=int)
parser.add_argument("--enc_dim", default=256, type=int)
parser.add_argument("--enc_ffn_dim", default=128, type=int)
parser.add_argument("--enc_dropout", default=0.1, type=float)
parser.add_argument("--enc_nhead", default=4, type=int)
parser.add_argument("--enc_pos_embed", default=None, type=str)
parser.add_argument("--enc_activation", default="relu", type=str)
### Decoder
parser.add_argument("--dec_nlayers", default=8, type=int)
parser.add_argument("--dec_dim", default=256, type=int)
parser.add_argument("--dec_ffn_dim", default=256, type=int)
parser.add_argument("--dec_dropout", default=0.1, type=float)
parser.add_argument("--dec_nhead", default=4, type=int)
### MLP heads for predicting bounding boxes
parser.add_argument("--mlp_dropout", default=0.3, type=float)
parser.add_argument(
"--nsemcls",
default=-1,
type=int,
help="Number of semantic object classes. Can be inferred from dataset",
)
### Other model params
parser.add_argument("--preenc_npoints", default=2048, type=int)
parser.add_argument(
"--pos_embed", default="fourier", type=str, choices=["fourier", "sine"]
)
parser.add_argument("--nqueries", default=256, type=int)
parser.add_argument("--use_color", default=False, action="store_true")
##### Set Loss #####
### Matcher
parser.add_argument("--matcher_giou_cost", default=2, type=float)
parser.add_argument("--matcher_cls_cost", default=1, type=float)
parser.add_argument("--matcher_center_cost", default=0, type=float)
parser.add_argument("--matcher_objectness_cost", default=0, type=float)
### Loss Weights
parser.add_argument("--loss_giou_weight", default=0, type=float)
parser.add_argument("--loss_sem_cls_weight", default=1, type=float)
parser.add_argument(
"--loss_no_object_weight", default=0.2, type=float
) # "no object" or "background" class for detection
parser.add_argument("--loss_angle_cls_weight", default=0.1, type=float)
parser.add_argument("--loss_angle_reg_weight", default=0.5, type=float)
parser.add_argument("--loss_center_weight", default=5.0, type=float)
parser.add_argument("--loss_size_weight", default=1.0, type=float)
##### Dataset #####
parser.add_argument(
"--dataset_name", required=True, type=str, choices=["scannet", "sunrgbd"]
)
parser.add_argument(
"--dataset_root_dir",
type=str,
default=None,
help="Root directory containing the dataset files. \
If None, default values from scannet.py/sunrgbd.py are used",
)
# parser.add_argument(
# "--meta_data_dir",
# type=str,
# default=None,
# help="Root directory containing the metadata files. \
# If None, default values from scannet.py/sunrgbd.py are used",
# )
parser.add_argument("--dataset_num_workers", default=4, type=int)
parser.add_argument("--batchsize_per_gpu", default=8, type=int)
##### Training #####
parser.add_argument("--start_epoch", default=-1, type=int)
parser.add_argument("--max_epoch", default=720, type=int)
parser.add_argument("--eval_every_epoch", default=10, type=int)
parser.add_argument("--seed", default=0, type=int)
##### Testing #####
parser.add_argument("--test_only", default=False, action="store_true")
parser.add_argument("--test_ckpt", default=None, type=str)
##### I/O #####
parser.add_argument("--checkpoint_dir", default=None, type=str)
parser.add_argument("--log_every", default=10, type=int)
parser.add_argument("--log_metrics_every", default=20, type=int)
parser.add_argument("--save_separate_checkpoint_every_epoch", default=100, type=int)
##### Distributed Training #####
parser.add_argument("--ngpus", default=1, type=int)
parser.add_argument("--dist_url", default="tcp://localhost:12345", type=str)
return parser
def do_train(
args,
model,
model_no_ddp,
optimizer,
criterion,
dataset_config,
dataloaders,
best_val_metrics,
):
"""
Main training loop.
This trains the model for `args.max_epoch` epochs and tests the model after every `args.eval_every_epoch`.
We always evaluate the final checkpoint and report both the final AP and best AP on the val set.
"""
num_iters_per_epoch = len(dataloaders["train"])
num_iters_per_eval_epoch = len(dataloaders["test"])
print(f"Model is {model}")
print(f"Training started at epoch {args.start_epoch} until {args.max_epoch}.")
print(f"One training epoch = {num_iters_per_epoch} iters.")
print(f"One eval epoch = {num_iters_per_eval_epoch} iters.")
final_eval = os.path.join(args.checkpoint_dir, "final_eval.txt")
final_eval_pkl = os.path.join(args.checkpoint_dir, "final_eval.pkl")
if os.path.isfile(final_eval):
print(f"Found final eval file {final_eval}. Skipping training.")
return
logger = Logger(args.checkpoint_dir)
for epoch in range(args.start_epoch, args.max_epoch):
if is_distributed():
dataloaders["train_sampler"].set_epoch(epoch)
aps = train_one_epoch(
args,
epoch,
model,
optimizer,
criterion,
dataset_config,
dataloaders["train"],
logger,
)
# latest checkpoint is always stored in checkpoint.pth
save_checkpoint(
args.checkpoint_dir,
model_no_ddp,
optimizer,
epoch,
args,
best_val_metrics,
filename="checkpoint.pth",
)
metrics = aps.compute_metrics()
metric_str = aps.metrics_to_str(metrics, per_class=False)
metrics_dict = aps.metrics_to_dict(metrics)
curr_iter = epoch * len(dataloaders["train"])
if is_primary():
print("==" * 10)
print(f"Epoch [{epoch}/{args.max_epoch}]; Metrics {metric_str}")
print("==" * 10)
logger.log_scalars(metrics_dict, curr_iter, prefix="Train/")
if (
epoch > 0
and args.save_separate_checkpoint_every_epoch > 0
and epoch % args.save_separate_checkpoint_every_epoch == 0
):
# separate checkpoints are stored as checkpoint_{epoch}.pth
save_checkpoint(
args.checkpoint_dir,
model_no_ddp,
optimizer,
epoch,
args,
best_val_metrics,
)
if epoch % args.eval_every_epoch == 0 or epoch == (args.max_epoch - 1):
ap_calculator = evaluate(
args,
epoch,
model,
criterion,
dataset_config,
dataloaders["test"],
logger,
curr_iter,
)
metrics = ap_calculator.compute_metrics()
ap25 = metrics[0.25]["mAP"]
metric_str = ap_calculator.metrics_to_str(metrics, per_class=True)
metrics_dict = ap_calculator.metrics_to_dict(metrics)
if is_primary():
print("==" * 10)
print(f"Evaluate Epoch [{epoch}/{args.max_epoch}]; Metrics {metric_str}")
print("==" * 10)
logger.log_scalars(metrics_dict, curr_iter, prefix="Test/")
if is_primary() and (
len(best_val_metrics) == 0 or best_val_metrics[0.25]["mAP"] < ap25
):
best_val_metrics = metrics
filename = "checkpoint_best.pth"
save_checkpoint(
args.checkpoint_dir,
model_no_ddp,
optimizer,
epoch,
args,
best_val_metrics,
filename=filename,
)
print(
f"Epoch [{epoch}/{args.max_epoch}] saved current best val checkpoint at {filename}; ap25 {ap25}"
)
# always evaluate last checkpoint
epoch = args.max_epoch - 1
curr_iter = epoch * len(dataloaders["train"])
ap_calculator = evaluate(
args,
epoch,
model,
criterion,
dataset_config,
dataloaders["test"],
logger,
curr_iter,
)
metrics = ap_calculator.compute_metrics()
metric_str = ap_calculator.metrics_to_str(metrics)
if is_primary():
print("==" * 10)
print(f"Evaluate Final [{epoch}/{args.max_epoch}]; Metrics {metric_str}")
print("==" * 10)
with open(final_eval, "w") as fh:
fh.write("Training Finished.\n")
fh.write("==" * 10)
fh.write("Final Eval Numbers.\n")
fh.write(metric_str)
fh.write("\n")
fh.write("==" * 10)
fh.write("Best Eval Numbers.\n")
fh.write(ap_calculator.metrics_to_str(best_val_metrics))
fh.write("\n")
with open(final_eval_pkl, "wb") as fh:
pickle.dump(metrics, fh)
def test_model(args, model, model_no_ddp, criterion, dataset_config, dataloaders):
if args.test_ckpt is None or not os.path.isfile(args.test_ckpt):
f"Please specify a test checkpoint using --test_ckpt. Found invalid value {args.test_ckpt}"
sys.exit(1)
sd = torch.load(args.test_ckpt, map_location=torch.device("cpu"))
model_no_ddp.load_state_dict(sd["model"])
logger = Logger()
criterion = None # do not compute loss for speed-up; Comment out to see test loss
epoch = -1
curr_iter = 0
ap_calculator = evaluate(
args,
epoch,
model,
criterion,
dataset_config,
dataloaders["test"],
logger,
curr_iter,
)
metrics = ap_calculator.compute_metrics()
metric_str = ap_calculator.metrics_to_str(metrics)
if is_primary():
print("==" * 10)
print(f"Test model; Metrics {metric_str}")
print("==" * 10)
def main(local_rank, args):
if args.ngpus > 1:
print(
"Initializing Distributed Training. This is in BETA mode and hasn't been tested thoroughly. Use at your own risk :)"
)
print("To get the maximum speed-up consider reducing evaluations on val set by setting --eval_every_epoch to greater than 50")
init_distributed(
local_rank,
global_rank=local_rank,
world_size=args.ngpus,
dist_url=args.dist_url,
dist_backend="nccl",
)
print(f"Called with args: {args}")
torch.cuda.set_device(local_rank)
np.random.seed(args.seed + get_rank())
torch.manual_seed(args.seed + get_rank())
if torch.cuda.is_available():
torch.cuda.manual_seed_all(args.seed + get_rank())
datasets, dataset_config = build_dataset(args)
model, _ = build_model(args, dataset_config)
model = model.cuda(local_rank)
model_no_ddp = model
if is_distributed():
model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model)
model = torch.nn.parallel.DistributedDataParallel(
model, device_ids=[local_rank]
)
criterion = build_criterion(args, dataset_config)
criterion = criterion.cuda(local_rank)
dataloaders = {}
if args.test_only:
dataset_splits = ["test"]
else:
dataset_splits = ["train", "test"]
for split in dataset_splits:
if split == "train":
shuffle = True
else:
shuffle = False
if is_distributed():
sampler = DistributedSampler(datasets[split], shuffle=shuffle)
elif shuffle:
sampler = torch.utils.data.RandomSampler(datasets[split])
else:
sampler = torch.utils.data.SequentialSampler(datasets[split])
dataloaders[split] = DataLoader(
datasets[split],
sampler=sampler,
batch_size=args.batchsize_per_gpu,
num_workers=args.dataset_num_workers,
worker_init_fn=my_worker_init_fn,
)
dataloaders[split + "_sampler"] = sampler
if args.test_only:
criterion = None # faster evaluation
test_model(args, model, model_no_ddp, criterion, dataset_config, dataloaders)
else:
assert (
args.checkpoint_dir is not None
), f"Please specify a checkpoint dir using --checkpoint_dir"
if is_primary() and not os.path.isdir(args.checkpoint_dir):
os.makedirs(args.checkpoint_dir, exist_ok=True)
optimizer = build_optimizer(args, model_no_ddp)
loaded_epoch, best_val_metrics = resume_if_possible(
args.checkpoint_dir, model_no_ddp, optimizer
)
args.start_epoch = loaded_epoch + 1
do_train(
args,
model,
model_no_ddp,
optimizer,
criterion,
dataset_config,
dataloaders,
best_val_metrics,
)
def launch_distributed(args):
world_size = args.ngpus
if world_size == 1:
main(local_rank=0, args=args)
else:
torch.multiprocessing.spawn(main, nprocs=world_size, args=(args,))
if __name__ == "__main__":
parser = make_args_parser()
args = parser.parse_args()
try:
set_start_method("spawn")
except RuntimeError:
pass
launch_distributed(args)
| 35.312644 | 134 | 0.621639 |
import argparse
import os
import sys
import pickle
import numpy as np
import torch
from torch.multiprocessing import set_start_method
from torch.utils.data import DataLoader, DistributedSampler
from datasets import build_dataset
from engine import evaluate, train_one_epoch
from models import build_model
from optimizer import build_optimizer
from criterion import build_criterion
from utils.dist import init_distributed, is_distributed, is_primary, get_rank, barrier
from utils.misc import my_worker_init_fn
from utils.io import save_checkpoint, resume_if_possible
from utils.logger import Logger
def make_args_parser():
parser = argparse.ArgumentParser("3D Detection Using Transformers", add_help=False)
--warm_lr", default=1e-6, type=float)
parser.add_argument("--warm_lr_epochs", default=9, type=int)
parser.add_argument("--final_lr", default=1e-6, type=float)
parser.add_argument("--lr_scheduler", default="cosine", type=str)
parser.add_argument("--weight_decay", default=0.1, type=float)
parser.add_argument("--filter_biases_wd", default=False, action="store_true")
parser.add_argument(
"--clip_gradient", default=0.1, type=float, help="Max L2 norm of the gradient"
)
,
type=str,
help="Name of the model",
choices=["3detr"],
)
ument(
"--enc_type", default="vanilla", choices=["masked", "maskedv2", "vanilla"]
)
parser.add_argument("--enc_nlayers", default=3, type=int)
parser.add_argument("--enc_dim", default=256, type=int)
parser.add_argument("--enc_ffn_dim", default=128, type=int)
parser.add_argument("--enc_dropout", default=0.1, type=float)
parser.add_argument("--enc_nhead", default=4, type=int)
parser.add_argument("--enc_pos_embed", default=None, type=str)
parser.add_argument("--enc_activation", default="relu", type=str)
ument("--dec_nlayers", default=8, type=int)
parser.add_argument("--dec_dim", default=256, type=int)
parser.add_argument("--dec_ffn_dim", default=256, type=int)
parser.add_argument("--dec_dropout", default=0.1, type=float)
parser.add_argument("--dec_nhead", default=4, type=int)
rgument(
"--nsemcls",
default=-1,
type=int,
help="Number of semantic object classes. Can be inferred from dataset",
)
s", default=2048, type=int)
parser.add_argument(
"--pos_embed", default="fourier", type=str, choices=["fourier", "sine"]
)
parser.add_argument("--nqueries", default=256, type=int)
parser.add_argument("--use_color", default=False, action="store_true")
atcher_cls_cost", default=1, type=float)
parser.add_argument("--matcher_center_cost", default=0, type=float)
parser.add_argument("--matcher_objectness_cost", default=0, type=float)
oss_giou_weight", default=0, type=float)
parser.add_argument("--loss_sem_cls_weight", default=1, type=float)
parser.add_argument(
"--loss_no_object_weight", default=0.2, type=float
)
parser.add_argument("--loss_angle_cls_weight", default=0.1, type=float)
parser.add_argument("--loss_angle_reg_weight", default=0.5, type=float)
parser.add_argument("--loss_center_weight", default=5.0, type=float)
parser.add_argument("--loss_size_weight", default=1.0, type=float)
ces=["scannet", "sunrgbd"]
)
parser.add_argument(
"--dataset_root_dir",
type=str,
default=None,
help="Root directory containing the dataset files. \
If None, default values from scannet.py/sunrgbd.py are used",
)
# If None, default values from scannet.py/sunrgbd.py are used",
parser.add_argument("--dataset_num_workers", default=4, type=int)
parser.add_argument("--batchsize_per_gpu", default=8, type=int)
nt("--max_epoch", default=720, type=int)
parser.add_argument("--eval_every_epoch", default=10, type=int)
parser.add_argument("--seed", default=0, type=int)
arser.add_argument("--test_ckpt", default=None, type=str)
tr)
parser.add_argument("--log_every", default=10, type=int)
parser.add_argument("--log_metrics_every", default=20, type=int)
parser.add_argument("--save_separate_checkpoint_every_epoch", default=100, type=int)
str)
return parser
def do_train(
args,
model,
model_no_ddp,
optimizer,
criterion,
dataset_config,
dataloaders,
best_val_metrics,
):
num_iters_per_epoch = len(dataloaders["train"])
num_iters_per_eval_epoch = len(dataloaders["test"])
print(f"Model is {model}")
print(f"Training started at epoch {args.start_epoch} until {args.max_epoch}.")
print(f"One training epoch = {num_iters_per_epoch} iters.")
print(f"One eval epoch = {num_iters_per_eval_epoch} iters.")
final_eval = os.path.join(args.checkpoint_dir, "final_eval.txt")
final_eval_pkl = os.path.join(args.checkpoint_dir, "final_eval.pkl")
if os.path.isfile(final_eval):
print(f"Found final eval file {final_eval}. Skipping training.")
return
logger = Logger(args.checkpoint_dir)
for epoch in range(args.start_epoch, args.max_epoch):
if is_distributed():
dataloaders["train_sampler"].set_epoch(epoch)
aps = train_one_epoch(
args,
epoch,
model,
optimizer,
criterion,
dataset_config,
dataloaders["train"],
logger,
)
save_checkpoint(
args.checkpoint_dir,
model_no_ddp,
optimizer,
epoch,
args,
best_val_metrics,
filename="checkpoint.pth",
)
metrics = aps.compute_metrics()
metric_str = aps.metrics_to_str(metrics, per_class=False)
metrics_dict = aps.metrics_to_dict(metrics)
curr_iter = epoch * len(dataloaders["train"])
if is_primary():
print("==" * 10)
print(f"Epoch [{epoch}/{args.max_epoch}]; Metrics {metric_str}")
print("==" * 10)
logger.log_scalars(metrics_dict, curr_iter, prefix="Train/")
if (
epoch > 0
and args.save_separate_checkpoint_every_epoch > 0
and epoch % args.save_separate_checkpoint_every_epoch == 0
):
save_checkpoint(
args.checkpoint_dir,
model_no_ddp,
optimizer,
epoch,
args,
best_val_metrics,
)
if epoch % args.eval_every_epoch == 0 or epoch == (args.max_epoch - 1):
ap_calculator = evaluate(
args,
epoch,
model,
criterion,
dataset_config,
dataloaders["test"],
logger,
curr_iter,
)
metrics = ap_calculator.compute_metrics()
ap25 = metrics[0.25]["mAP"]
metric_str = ap_calculator.metrics_to_str(metrics, per_class=True)
metrics_dict = ap_calculator.metrics_to_dict(metrics)
if is_primary():
print("==" * 10)
print(f"Evaluate Epoch [{epoch}/{args.max_epoch}]; Metrics {metric_str}")
print("==" * 10)
logger.log_scalars(metrics_dict, curr_iter, prefix="Test/")
if is_primary() and (
len(best_val_metrics) == 0 or best_val_metrics[0.25]["mAP"] < ap25
):
best_val_metrics = metrics
filename = "checkpoint_best.pth"
save_checkpoint(
args.checkpoint_dir,
model_no_ddp,
optimizer,
epoch,
args,
best_val_metrics,
filename=filename,
)
print(
f"Epoch [{epoch}/{args.max_epoch}] saved current best val checkpoint at {filename}; ap25 {ap25}"
)
epoch = args.max_epoch - 1
curr_iter = epoch * len(dataloaders["train"])
ap_calculator = evaluate(
args,
epoch,
model,
criterion,
dataset_config,
dataloaders["test"],
logger,
curr_iter,
)
metrics = ap_calculator.compute_metrics()
metric_str = ap_calculator.metrics_to_str(metrics)
if is_primary():
print("==" * 10)
print(f"Evaluate Final [{epoch}/{args.max_epoch}]; Metrics {metric_str}")
print("==" * 10)
with open(final_eval, "w") as fh:
fh.write("Training Finished.\n")
fh.write("==" * 10)
fh.write("Final Eval Numbers.\n")
fh.write(metric_str)
fh.write("\n")
fh.write("==" * 10)
fh.write("Best Eval Numbers.\n")
fh.write(ap_calculator.metrics_to_str(best_val_metrics))
fh.write("\n")
with open(final_eval_pkl, "wb") as fh:
pickle.dump(metrics, fh)
def test_model(args, model, model_no_ddp, criterion, dataset_config, dataloaders):
if args.test_ckpt is None or not os.path.isfile(args.test_ckpt):
f"Please specify a test checkpoint using --test_ckpt. Found invalid value {args.test_ckpt}"
sys.exit(1)
sd = torch.load(args.test_ckpt, map_location=torch.device("cpu"))
model_no_ddp.load_state_dict(sd["model"])
logger = Logger()
criterion = None
epoch = -1
curr_iter = 0
ap_calculator = evaluate(
args,
epoch,
model,
criterion,
dataset_config,
dataloaders["test"],
logger,
curr_iter,
)
metrics = ap_calculator.compute_metrics()
metric_str = ap_calculator.metrics_to_str(metrics)
if is_primary():
print("==" * 10)
print(f"Test model; Metrics {metric_str}")
print("==" * 10)
def main(local_rank, args):
if args.ngpus > 1:
print(
"Initializing Distributed Training. This is in BETA mode and hasn't been tested thoroughly. Use at your own risk :)"
)
print("To get the maximum speed-up consider reducing evaluations on val set by setting --eval_every_epoch to greater than 50")
init_distributed(
local_rank,
global_rank=local_rank,
world_size=args.ngpus,
dist_url=args.dist_url,
dist_backend="nccl",
)
print(f"Called with args: {args}")
torch.cuda.set_device(local_rank)
np.random.seed(args.seed + get_rank())
torch.manual_seed(args.seed + get_rank())
if torch.cuda.is_available():
torch.cuda.manual_seed_all(args.seed + get_rank())
datasets, dataset_config = build_dataset(args)
model, _ = build_model(args, dataset_config)
model = model.cuda(local_rank)
model_no_ddp = model
if is_distributed():
model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model)
model = torch.nn.parallel.DistributedDataParallel(
model, device_ids=[local_rank]
)
criterion = build_criterion(args, dataset_config)
criterion = criterion.cuda(local_rank)
dataloaders = {}
if args.test_only:
dataset_splits = ["test"]
else:
dataset_splits = ["train", "test"]
for split in dataset_splits:
if split == "train":
shuffle = True
else:
shuffle = False
if is_distributed():
sampler = DistributedSampler(datasets[split], shuffle=shuffle)
elif shuffle:
sampler = torch.utils.data.RandomSampler(datasets[split])
else:
sampler = torch.utils.data.SequentialSampler(datasets[split])
dataloaders[split] = DataLoader(
datasets[split],
sampler=sampler,
batch_size=args.batchsize_per_gpu,
num_workers=args.dataset_num_workers,
worker_init_fn=my_worker_init_fn,
)
dataloaders[split + "_sampler"] = sampler
if args.test_only:
criterion = None # faster evaluation
test_model(args, model, model_no_ddp, criterion, dataset_config, dataloaders)
else:
assert (
args.checkpoint_dir is not None
), f"Please specify a checkpoint dir using --checkpoint_dir"
if is_primary() and not os.path.isdir(args.checkpoint_dir):
os.makedirs(args.checkpoint_dir, exist_ok=True)
optimizer = build_optimizer(args, model_no_ddp)
loaded_epoch, best_val_metrics = resume_if_possible(
args.checkpoint_dir, model_no_ddp, optimizer
)
args.start_epoch = loaded_epoch + 1
do_train(
args,
model,
model_no_ddp,
optimizer,
criterion,
dataset_config,
dataloaders,
best_val_metrics,
)
def launch_distributed(args):
world_size = args.ngpus
if world_size == 1:
main(local_rank=0, args=args)
else:
torch.multiprocessing.spawn(main, nprocs=world_size, args=(args,))
if __name__ == "__main__":
parser = make_args_parser()
args = parser.parse_args()
try:
set_start_method("spawn")
except RuntimeError:
pass
launch_distributed(args)
| true | true |
f72ba096355b4c9e07406e66b05f1d1a8c1dce09 | 9,312 | py | Python | metadata-ingestion/src/datahub/ingestion/source/ldap.py | zhongjinhan/datahub | 3bf5ffab5db02bed21d9b04fd65860927fce8088 | [
"Apache-2.0"
] | null | null | null | metadata-ingestion/src/datahub/ingestion/source/ldap.py | zhongjinhan/datahub | 3bf5ffab5db02bed21d9b04fd65860927fce8088 | [
"Apache-2.0"
] | 1 | 2021-03-09T19:40:53.000Z | 2021-03-15T17:36:26.000Z | metadata-ingestion/src/datahub/ingestion/source/ldap.py | zhongjinhan/datahub | 3bf5ffab5db02bed21d9b04fd65860927fce8088 | [
"Apache-2.0"
] | null | null | null | """LDAP Source"""
from dataclasses import dataclass
from typing import Any, Dict, Iterable, List, Optional
import ldap
from ldap.controls import SimplePagedResultsControl
from datahub.configuration.common import ConfigModel, ConfigurationError
from datahub.ingestion.api.common import PipelineContext
from datahub.ingestion.api.source import Source, SourceReport
from datahub.ingestion.source.metadata_common import MetadataWorkUnit
from datahub.metadata.com.linkedin.pegasus2avro.mxe import MetadataChangeEvent
from datahub.metadata.schema_classes import (
CorpGroupInfoClass,
CorpGroupSnapshotClass,
CorpUserInfoClass,
CorpUserSnapshotClass,
)
def create_controls(pagesize: int) -> SimplePagedResultsControl:
"""
Create an LDAP control with a page size of "pagesize".
"""
return SimplePagedResultsControl(True, size=pagesize, cookie="")
def get_pctrls(
serverctrls: List[SimplePagedResultsControl],
) -> List[SimplePagedResultsControl]:
"""
Lookup an LDAP paged control object from the returned controls.
"""
return [
c for c in serverctrls if c.controlType == SimplePagedResultsControl.controlType
]
def set_cookie(
lc_object: SimplePagedResultsControl,
pctrls: List[SimplePagedResultsControl],
) -> bool:
"""
Push latest cookie back into the page control.
"""
cookie = pctrls[0].cookie
lc_object.cookie = cookie
return bool(cookie)
def guess_person_ldap(attrs: Dict[str, Any]) -> Optional[str]:
"""Determine the user's LDAP based on the DN and attributes."""
if "sAMAccountName" in attrs:
return attrs["sAMAccountName"][0].decode()
if "uid" in attrs:
return attrs["uid"][0].decode()
return None
class LDAPSourceConfig(ConfigModel):
"""Config used by the LDAP Source."""
# Server configuration.
ldap_server: str
ldap_user: str
ldap_password: str
# Extraction configuration.
base_dn: str
filter: str = "(objectClass=*)"
page_size: int = 20
@dataclass
class LDAPSource(Source):
"""LDAP Source Class."""
config: LDAPSourceConfig
report: SourceReport
def __init__(self, ctx: PipelineContext, config: LDAPSourceConfig):
"""Constructor."""
super().__init__(ctx)
self.config = config
self.report = SourceReport()
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW)
ldap.set_option(ldap.OPT_REFERRALS, 0)
self.ldap_client = ldap.initialize(self.config.ldap_server)
self.ldap_client.protocol_version = 3
try:
self.ldap_client.simple_bind_s(
self.config.ldap_user, self.config.ldap_password
)
except ldap.LDAPError as e:
raise ConfigurationError("LDAP connection failed") from e
self.lc = create_controls(self.config.page_size)
@classmethod
def create(cls, config_dict: Dict[str, Any], ctx: PipelineContext) -> "LDAPSource":
"""Factory method."""
config = LDAPSourceConfig.parse_obj(config_dict)
return cls(ctx, config)
def get_workunits(self) -> Iterable[MetadataWorkUnit]:
"""Returns an Iterable containing the workunits to ingest LDAP users or groups."""
cookie = True
while cookie:
try:
msgid = self.ldap_client.search_ext(
self.config.base_dn,
ldap.SCOPE_SUBTREE,
self.config.filter,
serverctrls=[self.lc],
)
_rtype, rdata, _rmsgid, serverctrls = self.ldap_client.result3(msgid)
except ldap.LDAPError as e:
self.report.report_failure(
"ldap-control", "LDAP search failed: {}".format(e)
)
break
for dn, attrs in rdata:
if (
b"inetOrgPerson" in attrs["objectClass"]
or b"posixAccount" in attrs["objectClass"]
):
yield from self.handle_user(dn, attrs)
if (
b"posixGroup" in attrs["objectClass"]
or b"organizationalUnit" in attrs["objectClass"]
):
yield from self.handle_group(dn, attrs)
pctrls = get_pctrls(serverctrls)
if not pctrls:
self.report.report_failure(
"ldap-control", "Server ignores RFC 2696 control."
)
break
cookie = set_cookie(self.lc, pctrls)
def handle_user(self, dn: str, attrs: Dict[str, Any]) -> Iterable[MetadataWorkUnit]:
"""
Handle a DN and attributes by adding manager info and constructing a
work unit based on the information.
"""
manager_ldap = None
if "manager" in attrs:
try:
m_cn = attrs["manager"][0].split(b",")[0]
manager_msgid = self.ldap_client.search_ext(
self.config.base_dn,
ldap.SCOPE_SUBTREE,
f"({m_cn.decode()})",
serverctrls=[self.lc],
)
_m_dn, m_attrs = self.ldap_client.result3(manager_msgid)[1][0]
manager_ldap = guess_person_ldap(m_attrs)
except ldap.LDAPError as e:
self.report.report_warning(
dn, "manager LDAP search failed: {}".format(e)
)
mce = self.build_corp_user_mce(dn, attrs, manager_ldap)
if mce:
wu = MetadataWorkUnit(dn, mce)
self.report.report_workunit(wu)
yield wu
yield from []
def handle_group(
self, dn: str, attrs: Dict[str, Any]
) -> Iterable[MetadataWorkUnit]:
"""Creates a workunit for LDAP groups."""
mce = self.build_corp_group_mce(attrs)
if mce:
wu = MetadataWorkUnit(dn, mce)
self.report.report_workunit(wu)
yield wu
yield from []
def build_corp_user_mce(
self, dn: str, attrs: dict, manager_ldap: Optional[str]
) -> Optional[MetadataChangeEvent]:
"""
Create the MetadataChangeEvent via DN and attributes.
"""
ldap_user = guess_person_ldap(attrs)
full_name = attrs["cn"][0].decode()
first_name = attrs["givenName"][0].decode()
last_name = attrs["sn"][0].decode()
email = (attrs["mail"][0]).decode() if "mail" in attrs else ldap_user
display_name = (
(attrs["displayName"][0]).decode() if "displayName" in attrs else full_name
)
department = (
(attrs["departmentNumber"][0]).decode()
if "departmentNumber" in attrs
else None
)
title = attrs["title"][0].decode() if "title" in attrs else None
manager_urn = f"urn:li:corpuser:{manager_ldap}" if manager_ldap else None
return MetadataChangeEvent(
proposedSnapshot=CorpUserSnapshotClass(
urn=f"urn:li:corpuser:{ldap_user}",
aspects=[
CorpUserInfoClass(
active=True,
email=email,
fullName=full_name,
firstName=first_name,
lastName=last_name,
departmentName=department,
displayName=display_name,
title=title,
managerUrn=manager_urn,
)
],
)
)
def build_corp_group_mce(self, attrs: dict) -> Optional[MetadataChangeEvent]:
"""Creates a MetadataChangeEvent for LDAP groups."""
cn = attrs.get("cn")
if cn:
full_name = cn[0].decode()
owners = parse_from_attrs(attrs, "owner")
members = parse_from_attrs(attrs, "uniqueMember")
email = attrs["mail"][0].decode() if "mail" in attrs else full_name
return MetadataChangeEvent(
proposedSnapshot=CorpGroupSnapshotClass(
urn=f"urn:li:corpGroup:{full_name}",
aspects=[
CorpGroupInfoClass(
email=email,
admins=owners,
members=members,
groups=[],
)
],
)
)
return None
def get_report(self) -> SourceReport:
"""Returns the sourcereport."""
return self.report
def close(self) -> None:
"""Closes the Source."""
self.ldap_client.unbind()
def parse_from_attrs(attrs: Dict[str, Any], filter_key: str) -> List[str]:
"""Converts a list of LDAP formats to Datahub corpuser strings."""
if filter_key in attrs:
return [
f"urn:li:corpuser:{strip_ldap_info(ldap_user)}"
for ldap_user in attrs[filter_key]
]
return []
def strip_ldap_info(input_clean: bytes) -> str:
"""Converts a b'uid=username,ou=Groups,dc=internal,dc=machines'
format to username"""
return input_clean.decode().split(",")[0].lstrip("uid=")
| 33.376344 | 90 | 0.575387 | from dataclasses import dataclass
from typing import Any, Dict, Iterable, List, Optional
import ldap
from ldap.controls import SimplePagedResultsControl
from datahub.configuration.common import ConfigModel, ConfigurationError
from datahub.ingestion.api.common import PipelineContext
from datahub.ingestion.api.source import Source, SourceReport
from datahub.ingestion.source.metadata_common import MetadataWorkUnit
from datahub.metadata.com.linkedin.pegasus2avro.mxe import MetadataChangeEvent
from datahub.metadata.schema_classes import (
CorpGroupInfoClass,
CorpGroupSnapshotClass,
CorpUserInfoClass,
CorpUserSnapshotClass,
)
def create_controls(pagesize: int) -> SimplePagedResultsControl:
return SimplePagedResultsControl(True, size=pagesize, cookie="")
def get_pctrls(
serverctrls: List[SimplePagedResultsControl],
) -> List[SimplePagedResultsControl]:
return [
c for c in serverctrls if c.controlType == SimplePagedResultsControl.controlType
]
def set_cookie(
lc_object: SimplePagedResultsControl,
pctrls: List[SimplePagedResultsControl],
) -> bool:
cookie = pctrls[0].cookie
lc_object.cookie = cookie
return bool(cookie)
def guess_person_ldap(attrs: Dict[str, Any]) -> Optional[str]:
if "sAMAccountName" in attrs:
return attrs["sAMAccountName"][0].decode()
if "uid" in attrs:
return attrs["uid"][0].decode()
return None
class LDAPSourceConfig(ConfigModel):
ldap_server: str
ldap_user: str
ldap_password: str
base_dn: str
filter: str = "(objectClass=*)"
page_size: int = 20
@dataclass
class LDAPSource(Source):
config: LDAPSourceConfig
report: SourceReport
def __init__(self, ctx: PipelineContext, config: LDAPSourceConfig):
super().__init__(ctx)
self.config = config
self.report = SourceReport()
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW)
ldap.set_option(ldap.OPT_REFERRALS, 0)
self.ldap_client = ldap.initialize(self.config.ldap_server)
self.ldap_client.protocol_version = 3
try:
self.ldap_client.simple_bind_s(
self.config.ldap_user, self.config.ldap_password
)
except ldap.LDAPError as e:
raise ConfigurationError("LDAP connection failed") from e
self.lc = create_controls(self.config.page_size)
@classmethod
def create(cls, config_dict: Dict[str, Any], ctx: PipelineContext) -> "LDAPSource":
config = LDAPSourceConfig.parse_obj(config_dict)
return cls(ctx, config)
def get_workunits(self) -> Iterable[MetadataWorkUnit]:
cookie = True
while cookie:
try:
msgid = self.ldap_client.search_ext(
self.config.base_dn,
ldap.SCOPE_SUBTREE,
self.config.filter,
serverctrls=[self.lc],
)
_rtype, rdata, _rmsgid, serverctrls = self.ldap_client.result3(msgid)
except ldap.LDAPError as e:
self.report.report_failure(
"ldap-control", "LDAP search failed: {}".format(e)
)
break
for dn, attrs in rdata:
if (
b"inetOrgPerson" in attrs["objectClass"]
or b"posixAccount" in attrs["objectClass"]
):
yield from self.handle_user(dn, attrs)
if (
b"posixGroup" in attrs["objectClass"]
or b"organizationalUnit" in attrs["objectClass"]
):
yield from self.handle_group(dn, attrs)
pctrls = get_pctrls(serverctrls)
if not pctrls:
self.report.report_failure(
"ldap-control", "Server ignores RFC 2696 control."
)
break
cookie = set_cookie(self.lc, pctrls)
def handle_user(self, dn: str, attrs: Dict[str, Any]) -> Iterable[MetadataWorkUnit]:
manager_ldap = None
if "manager" in attrs:
try:
m_cn = attrs["manager"][0].split(b",")[0]
manager_msgid = self.ldap_client.search_ext(
self.config.base_dn,
ldap.SCOPE_SUBTREE,
f"({m_cn.decode()})",
serverctrls=[self.lc],
)
_m_dn, m_attrs = self.ldap_client.result3(manager_msgid)[1][0]
manager_ldap = guess_person_ldap(m_attrs)
except ldap.LDAPError as e:
self.report.report_warning(
dn, "manager LDAP search failed: {}".format(e)
)
mce = self.build_corp_user_mce(dn, attrs, manager_ldap)
if mce:
wu = MetadataWorkUnit(dn, mce)
self.report.report_workunit(wu)
yield wu
yield from []
def handle_group(
self, dn: str, attrs: Dict[str, Any]
) -> Iterable[MetadataWorkUnit]:
mce = self.build_corp_group_mce(attrs)
if mce:
wu = MetadataWorkUnit(dn, mce)
self.report.report_workunit(wu)
yield wu
yield from []
def build_corp_user_mce(
self, dn: str, attrs: dict, manager_ldap: Optional[str]
) -> Optional[MetadataChangeEvent]:
ldap_user = guess_person_ldap(attrs)
full_name = attrs["cn"][0].decode()
first_name = attrs["givenName"][0].decode()
last_name = attrs["sn"][0].decode()
email = (attrs["mail"][0]).decode() if "mail" in attrs else ldap_user
display_name = (
(attrs["displayName"][0]).decode() if "displayName" in attrs else full_name
)
department = (
(attrs["departmentNumber"][0]).decode()
if "departmentNumber" in attrs
else None
)
title = attrs["title"][0].decode() if "title" in attrs else None
manager_urn = f"urn:li:corpuser:{manager_ldap}" if manager_ldap else None
return MetadataChangeEvent(
proposedSnapshot=CorpUserSnapshotClass(
urn=f"urn:li:corpuser:{ldap_user}",
aspects=[
CorpUserInfoClass(
active=True,
email=email,
fullName=full_name,
firstName=first_name,
lastName=last_name,
departmentName=department,
displayName=display_name,
title=title,
managerUrn=manager_urn,
)
],
)
)
def build_corp_group_mce(self, attrs: dict) -> Optional[MetadataChangeEvent]:
cn = attrs.get("cn")
if cn:
full_name = cn[0].decode()
owners = parse_from_attrs(attrs, "owner")
members = parse_from_attrs(attrs, "uniqueMember")
email = attrs["mail"][0].decode() if "mail" in attrs else full_name
return MetadataChangeEvent(
proposedSnapshot=CorpGroupSnapshotClass(
urn=f"urn:li:corpGroup:{full_name}",
aspects=[
CorpGroupInfoClass(
email=email,
admins=owners,
members=members,
groups=[],
)
],
)
)
return None
def get_report(self) -> SourceReport:
return self.report
def close(self) -> None:
self.ldap_client.unbind()
def parse_from_attrs(attrs: Dict[str, Any], filter_key: str) -> List[str]:
if filter_key in attrs:
return [
f"urn:li:corpuser:{strip_ldap_info(ldap_user)}"
for ldap_user in attrs[filter_key]
]
return []
def strip_ldap_info(input_clean: bytes) -> str:
return input_clean.decode().split(",")[0].lstrip("uid=")
| true | true |
f72ba1d7778091106a4581741203288c6ae24e0e | 1,378 | py | Python | tests/benchmarks/constructs/LocalVariableAssign.py | Mortal/Nuitka | 5150eeff7ff845ed4993c773449cd81b7f127c6b | [
"Apache-2.0"
] | null | null | null | tests/benchmarks/constructs/LocalVariableAssign.py | Mortal/Nuitka | 5150eeff7ff845ed4993c773449cd81b7f127c6b | [
"Apache-2.0"
] | null | null | null | tests/benchmarks/constructs/LocalVariableAssign.py | Mortal/Nuitka | 5150eeff7ff845ed4993c773449cd81b7f127c6b | [
"Apache-2.0"
] | 1 | 2018-12-16T23:51:18.000Z | 2018-12-16T23:51:18.000Z | # Copyright 2018, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Python test originally created or extracted from other peoples work. The
# parts from me are licensed as below. It is at least Free Software where
# it's copied from other people. In these cases, that will normally be
# indicated.
#
# 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.
#
module_value1 = 1000
module_value2 = 50
def calledRepeatedly():
# Force frame and eliminate forward propagation (currently).
module_value1
local_value = module_value1
local_value2 = module_value2
# construct_begin
local_value2 = local_value * 2
# construct_alternative
local_value * 2
# construct_end
local_value2 = local_value * 4
return local_value
import itertools
for x in itertools.repeat(None, 50000):
calledRepeatedly()
print("OK.")
| 30.622222 | 78 | 0.722787 |
# indicated.
#
# 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.
#
module_value1 = 1000
module_value2 = 50
def calledRepeatedly():
# Force frame and eliminate forward propagation (currently).
module_value1
local_value = module_value1
local_value2 = module_value2
# construct_begin
local_value2 = local_value * 2
# construct_alternative
local_value * 2
# construct_end
local_value2 = local_value * 4
return local_value
import itertools
for x in itertools.repeat(None, 50000):
calledRepeatedly()
print("OK.")
| true | true |
f72ba2b63d4ac4e8dc4c0d2dd40a513c05d534df | 3,551 | py | Python | tests/test_graph.py | arky/followthemoney | e6e4f5749aadc51893d131aac9744e1184d12f92 | [
"MIT"
] | 137 | 2017-10-20T09:36:32.000Z | 2022-03-24T18:49:16.000Z | tests/test_graph.py | arky/followthemoney | e6e4f5749aadc51893d131aac9744e1184d12f92 | [
"MIT"
] | 505 | 2017-10-24T13:14:06.000Z | 2022-03-28T20:21:45.000Z | tests/test_graph.py | malteos/followthemoney | 7fde00488b4f2bf6acc69d922bd0ca9d2defbe0f | [
"MIT"
] | 32 | 2017-12-19T15:22:07.000Z | 2022-02-18T11:01:28.000Z | from unittest import TestCase
from followthemoney import model
from followthemoney.types import registry
from followthemoney.graph import Graph, Node
ENTITY = {
"id": "ralph",
"schema": "Person",
"properties": {
"name": ["Ralph Tester"],
"birthDate": ["1972-05-01"],
"idNumber": ["9177171", "8e839023"],
"website": ["https://ralphtester.me"],
"phone": ["+12025557612"],
"email": ["info@ralphtester.me"],
"topics": ["role.spy"],
},
}
ENTITY2 = {
"id": "jodie",
"schema": "Person",
"properties": {"name": ["Jodie Tester"], "birthDate": ["1972-05-01"]},
}
REL = {
"id": "jodie2ralph",
"schema": "Family",
"properties": {"person": ["jodie"], "relative": ["ralph"]},
}
PASS = {
"id": "passpoat",
"schema": "Passport",
"properties": {"holder": ["jodie"], "passportNumber": ["HJSJHAS"]},
}
class GraphTestCase(TestCase):
def test_basic_graph(self):
proxy = model.get_proxy(ENTITY, cleaned=False)
graph = Graph(edge_types=registry.pivots)
graph.add(proxy)
assert len(graph.iternodes()) > 1, graph.to_dict()
assert len(graph.proxies) == 1, graph.proxies
assert len(graph.queued) == 0, graph.proxies
graph.add(None)
assert len(graph.proxies) == 1, graph.proxies
assert len(graph.queued) == 0, graph.proxies
def test_adjacent(self):
graph = Graph(edge_types=registry.pivots)
graph.add(model.get_proxy(ENTITY, cleaned=False))
graph.add(model.get_proxy(ENTITY2, cleaned=False))
graph.add(model.get_proxy(REL, cleaned=False))
graph.add(model.get_proxy(PASS, cleaned=False))
node = Node(registry.entity, "jodie")
adj = list(graph.get_adjacent(node))
assert len(adj) == 3, adj
node = Node(registry.entity, "ralph")
adj = list(graph.get_adjacent(node))
assert len(adj) == 7, adj
node = Node(registry.entity, "passpoat")
adj = list(graph.get_adjacent(node))
assert len(adj) == 2, adj
node = Node(registry.entity, "passpoat")
prop = model.get_qname("Identification:holder")
adj = list(graph.get_adjacent(node, prop))
assert len(adj) == 1, adj
assert adj[0].source_prop == prop, adj[0].source_prop
assert adj[0].target_prop == prop.reverse, adj[0].target_prop
node = Node(registry.entity, "jodie")
prop = model.get_qname("Person:familyPerson")
adj = list(graph.get_adjacent(node, prop))
assert len(adj) == 1, adj
assert adj[0].source_prop == prop, adj[0].source_prop
node = Node(registry.entity, "ralph")
prop = model.get_qname("Person:familyRelative")
adj2 = list(graph.get_adjacent(node, prop))
assert len(adj2) == 1, adj2
assert adj2[0].target_prop == prop, adj2[0].target_prop
assert adj[0] == adj2[0], (adj[0], adj2[0])
assert adj[0].id in repr(adj[0]), repr(adj[0])
def test_to_dict(self):
proxy = model.get_proxy(ENTITY, cleaned=False)
graph = Graph(edge_types=registry.pivots)
graph.add(proxy)
data = graph.to_dict()
assert "nodes" in data, data
assert "edges" in data, data
def test_nodes(self):
node = Node(registry.phone, "+4917778271717")
assert "+49177" in repr(node), repr(node)
assert node == node, repr(node)
assert node.caption == str(node), str(node)
assert hash(node) == hash(node.id), repr(node)
| 33.819048 | 74 | 0.599549 | from unittest import TestCase
from followthemoney import model
from followthemoney.types import registry
from followthemoney.graph import Graph, Node
ENTITY = {
"id": "ralph",
"schema": "Person",
"properties": {
"name": ["Ralph Tester"],
"birthDate": ["1972-05-01"],
"idNumber": ["9177171", "8e839023"],
"website": ["https://ralphtester.me"],
"phone": ["+12025557612"],
"email": ["info@ralphtester.me"],
"topics": ["role.spy"],
},
}
ENTITY2 = {
"id": "jodie",
"schema": "Person",
"properties": {"name": ["Jodie Tester"], "birthDate": ["1972-05-01"]},
}
REL = {
"id": "jodie2ralph",
"schema": "Family",
"properties": {"person": ["jodie"], "relative": ["ralph"]},
}
PASS = {
"id": "passpoat",
"schema": "Passport",
"properties": {"holder": ["jodie"], "passportNumber": ["HJSJHAS"]},
}
class GraphTestCase(TestCase):
def test_basic_graph(self):
proxy = model.get_proxy(ENTITY, cleaned=False)
graph = Graph(edge_types=registry.pivots)
graph.add(proxy)
assert len(graph.iternodes()) > 1, graph.to_dict()
assert len(graph.proxies) == 1, graph.proxies
assert len(graph.queued) == 0, graph.proxies
graph.add(None)
assert len(graph.proxies) == 1, graph.proxies
assert len(graph.queued) == 0, graph.proxies
def test_adjacent(self):
graph = Graph(edge_types=registry.pivots)
graph.add(model.get_proxy(ENTITY, cleaned=False))
graph.add(model.get_proxy(ENTITY2, cleaned=False))
graph.add(model.get_proxy(REL, cleaned=False))
graph.add(model.get_proxy(PASS, cleaned=False))
node = Node(registry.entity, "jodie")
adj = list(graph.get_adjacent(node))
assert len(adj) == 3, adj
node = Node(registry.entity, "ralph")
adj = list(graph.get_adjacent(node))
assert len(adj) == 7, adj
node = Node(registry.entity, "passpoat")
adj = list(graph.get_adjacent(node))
assert len(adj) == 2, adj
node = Node(registry.entity, "passpoat")
prop = model.get_qname("Identification:holder")
adj = list(graph.get_adjacent(node, prop))
assert len(adj) == 1, adj
assert adj[0].source_prop == prop, adj[0].source_prop
assert adj[0].target_prop == prop.reverse, adj[0].target_prop
node = Node(registry.entity, "jodie")
prop = model.get_qname("Person:familyPerson")
adj = list(graph.get_adjacent(node, prop))
assert len(adj) == 1, adj
assert adj[0].source_prop == prop, adj[0].source_prop
node = Node(registry.entity, "ralph")
prop = model.get_qname("Person:familyRelative")
adj2 = list(graph.get_adjacent(node, prop))
assert len(adj2) == 1, adj2
assert adj2[0].target_prop == prop, adj2[0].target_prop
assert adj[0] == adj2[0], (adj[0], adj2[0])
assert adj[0].id in repr(adj[0]), repr(adj[0])
def test_to_dict(self):
proxy = model.get_proxy(ENTITY, cleaned=False)
graph = Graph(edge_types=registry.pivots)
graph.add(proxy)
data = graph.to_dict()
assert "nodes" in data, data
assert "edges" in data, data
def test_nodes(self):
node = Node(registry.phone, "+4917778271717")
assert "+49177" in repr(node), repr(node)
assert node == node, repr(node)
assert node.caption == str(node), str(node)
assert hash(node) == hash(node.id), repr(node)
| true | true |
f72ba3d5f708cc3f9400d201f0cc2f6315f72c8b | 832 | py | Python | tests_no_pytest/test_write.py | jzuhone/xija | 1e423d0c48056cc4ea9e4993d28e34794c1420fa | [
"BSD-3-Clause"
] | 2 | 2016-01-05T19:20:43.000Z | 2021-06-04T08:23:08.000Z | tests_no_pytest/test_write.py | jzuhone/xija | 1e423d0c48056cc4ea9e4993d28e34794c1420fa | [
"BSD-3-Clause"
] | 61 | 2015-02-24T02:27:11.000Z | 2022-03-23T13:52:15.000Z | tests_no_pytest/test_write.py | jzuhone/xija | 1e423d0c48056cc4ea9e4993d28e34794c1420fa | [
"BSD-3-Clause"
] | 1 | 2016-01-04T21:08:17.000Z | 2016-01-04T21:08:17.000Z | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import os
import json
import numpy as np
import xija
mdl = xija.ThermalModel(start='2010:001', stop='2010:004')
tephin = mdl.add(xija.Node, 'tephin')
tcylaft6 = mdl.add(xija.Node, 'tcylaft6', predict=False)
coup_tephin_tcylaft6 = mdl.add(xija.Coupling, tephin, tcylaft6, tau=20)
aosares1 = mdl.add(xija.TelemData, 'aosares1')
tephin_solar = mdl.add(xija.SolarHeat, tephin, aosares1,
Ps=[0.1, 0.5, 1.0, 1.5, 2.0],
dPs=[0.01, 0.02, 0.03, 0.04, 0.05])
tephin_heatsink = mdl.add(xija.HeatSink, tephin, T=0.0, tau=20.0)
mdl.make()
mdl.write('test_write.json')
model_spec = json.load(open('test_write.json'))
mdl2 = xija.ThermalModel(start='2010:001', stop='2010:004', model_spec=model_spec)
os.unlink('test_write.json')
| 30.814815 | 82 | 0.68149 |
import os
import json
import numpy as np
import xija
mdl = xija.ThermalModel(start='2010:001', stop='2010:004')
tephin = mdl.add(xija.Node, 'tephin')
tcylaft6 = mdl.add(xija.Node, 'tcylaft6', predict=False)
coup_tephin_tcylaft6 = mdl.add(xija.Coupling, tephin, tcylaft6, tau=20)
aosares1 = mdl.add(xija.TelemData, 'aosares1')
tephin_solar = mdl.add(xija.SolarHeat, tephin, aosares1,
Ps=[0.1, 0.5, 1.0, 1.5, 2.0],
dPs=[0.01, 0.02, 0.03, 0.04, 0.05])
tephin_heatsink = mdl.add(xija.HeatSink, tephin, T=0.0, tau=20.0)
mdl.make()
mdl.write('test_write.json')
model_spec = json.load(open('test_write.json'))
mdl2 = xija.ThermalModel(start='2010:001', stop='2010:004', model_spec=model_spec)
os.unlink('test_write.json')
| true | true |
f72ba4bad6d7541d57491bf18fb1649b5f900db5 | 17,871 | py | Python | src/tests/test_api_functions.py | ArieLevs/NalkinsCloud-Django | 3fab970e4545db2e0b3e63a4bc8a5a1488a4a2bf | [
"Apache-2.0"
] | 6 | 2019-01-07T15:34:27.000Z | 2020-05-16T14:40:38.000Z | src/tests/test_api_functions.py | ArieLevs/NalkinsCloud-Django | 3fab970e4545db2e0b3e63a4bc8a5a1488a4a2bf | [
"Apache-2.0"
] | 9 | 2019-12-28T12:08:36.000Z | 2021-09-22T17:44:41.000Z | src/tests/test_api_functions.py | ArieLevs/NalkinsCloud-Django-Backend | 3fab970e4545db2e0b3e63a4bc8a5a1488a4a2bf | [
"Apache-2.0"
] | null | null | null |
from django.utils.crypto import get_random_string
from django.urls import reverse
from django.utils import timezone
from rest_framework.test import APITestCase
from oauth2_provider.models import AccessToken
from oauth2_provider.models import Application
from nalkinscloud_mosquitto.models import Device, DeviceType, DeviceModel, CustomerDevice
from django_user_email_extension.models import User
import datetime
import logging
from nalkinscloud_django.settings import PROJECT_NAME
# Define logger
logger = logging.getLogger(PROJECT_NAME)
class APIViewsTestCase(APITestCase):
def setUp(self):
# Create OAuth application
self.oauth_client_id = 'some_client_id'
self.oauth_client_secret = 'some_client_secret'
self.oauth_client = Application.objects.create(client_id=self.oauth_client_id,
client_secret=self.oauth_client_secret)
self.email = "test@nalkins.cloud"
self.password = "nalkinscloud"
# Generate basic test user
self.user = User.objects.create_user(
email=self.email,
password=self.password,
is_active=True
)
# Generate access token (oauth) for test user
expires = timezone.now() + datetime.timedelta(seconds=36000)
self.access_token = AccessToken.objects.create(
user=self.user,
application=self.oauth_client,
scope='',
token=get_random_string(length=32),
expires=expires)
self.access_token.save()
# Generate test device
self.device_id = 'api_test_device_id'
self.device_password = 'nalkinscloud'
self.device_model = 'esp8266'
self.device_type = 'dht'
self.device = Device.objects.create_device(device_id=self.device_id, password=self.device_password,
model=DeviceModel.objects.get(model=self.device_model),
type=DeviceType.objects.get(type=self.device_type))
# Generate users device
self.user_device_id = self.user.email
self.user_device_model = 'application'
self.user_device_type = 'user'
self.user_device = Device.objects.create_device(device_id=self.user_device_id, password=self.device_password,
model=DeviceModel.objects.get(model=self.user_device_model),
type=DeviceType.objects.get(type=self.user_device_type))
# Set current client with a token fot authentication
self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + str(self.access_token))
self.health_check_url = reverse('nalkinscloud_api:health_check')
self.registration_url = reverse('nalkinscloud_api:register')
self.device_activation_url = reverse('nalkinscloud_api:device_activation')
self.device_list_url = reverse('nalkinscloud_api:device_list')
self.forgot_password_url = reverse('nalkinscloud_api:forgot_password')
self.get_device_pass_url = reverse('nalkinscloud_api:get_device_pass')
self.remove_device_url = reverse('nalkinscloud_api:remove_device')
self.reset_password_url = reverse('nalkinscloud_api:reset_password')
self.update_device_pass_url = reverse('nalkinscloud_api:update_device_pass')
def test_registration(self):
"""
Test Registration view
"""
post_body = {
'client_secret': self.oauth_client_secret,
'email': 'arielev@nalkins.cloud',
'password': self.password,
'first_name': 'Arie',
'last_name': 'Lev'
}
response = self.client.post(self.registration_url, data=post_body, format='json')
logger.debug("test_registration response: " + str(response.json()))
self.assertEqual(201, response.status_code, "Should return 201, register new user successfully")
# Perform same registration process again
response = self.client.post(self.registration_url, data=post_body, format='json')
self.assertEqual(409, response.status_code, "Should return 409 conflict, email already exists")
# Change client_secret to non valid value
post_body['client_secret'] = 'some_non_existing_client_id'
response = self.client.post(self.registration_url, data=post_body, format='json')
self.assertEqual(401, response.status_code, "Should return not authorized")
self.assertEqual(User.objects.count(), 2, "Two users should be present in the system by this point")
def test_health_check_view(self):
"""
Test Health Check view
:return:
"""
response = self.client.post(self.health_check_url)
logger.debug('test_health_check_view response: ' + str(response.json()))
self.assertEqual(200, response.status_code, "Should return username")
def test_device_activation_view_204(self):
"""
Test case when trying to attach a device that does not exists
:return:
"""
post_body = {
'device_id': 'non_existing_device',
'device_name': 'device_activation_test'
}
response = self.client.post(self.device_activation_url, data=post_body)
self.assertEqual(204, response.status_code, "Should return 204 since device does not exists")
def test_device_activation_view_400_1(self):
"""
Test case when calling the api with no data
:return:
"""
response = self.client.post(self.device_activation_url)
logger.debug('test_device_activation_view_400_1 response: ' + str(response.json()))
self.assertEqual(400, response.status_code, "Should return error 400 since there are missing values")
def test_device_activation_view_400_2(self):
"""
Test case when one of data parameters empty
:return:
"""
post_body = {
'device_id': '',
'device_name': 'device_activation_test'
}
response = self.client.post(self.device_activation_url, data=post_body)
logger.debug('test_device_activation_view_400_2 response: ' + str(response.json()))
self.assertEqual(400, response.status_code, "Should return 400 since 'device_id' is blank")
self.assertEqual(response.json(), {'device_id': ['This field may not be blank.']},
"Should return blank field not allowed")
def test_device_activation_view_409(self):
"""
Test case when a device has an owner and its not the current user
:return:
"""
# Generate another test user
user = User.objects.create_user(
email='device@activate.test',
password=self.password,
is_active=True
)
# Generate another test device
device = Device.objects.create_device(device_id='device_activation_test_id', password=self.device_password,
model=DeviceModel.objects.get(model=self.device_model),
type=DeviceType.objects.get(type=self.device_type))
# Attach just created user and device
CustomerDevice.objects.create(user_id=user, device_id=device)
# Test attaching other users device to current user
post_body = {
'device_id': device,
'device_name': 'device_activation_test'
}
response = self.client.post(self.device_activation_url, data=post_body)
logger.debug('test_device_activation_view_409 response: ' + str(response.json()))
self.assertEqual(409, response.status_code, "Should return 409 conflict, device owned by other user")
def test_device_activation_view_200_1(self):
"""
Test case when all is OK and an non owned device attached to current user
:return:
"""
post_body = {
'device_id': self.device_id,
'device_name': 'device_activation_test'
}
response = self.client.post(self.device_activation_url, data=post_body)
logger.debug('test_device_activation_view_200_1 response: ' + str(response.json()))
self.assertEqual(200, response.status_code, "Should return 200, device attached")
def test_device_activation_view_200_2(self):
"""
Test case when trying to attach a device that is already attached
:return:
"""
CustomerDevice.objects.create(user_id=self.user, device_id=self.device)
post_body = {
'device_id': self.device_id,
'device_name': 'test_device_activation_view_200_2'
}
response = self.client.post(self.device_activation_url, data=post_body)
logger.debug('test_device_activation_view_200_2 response: ' + str(response.json()))
self.assertEqual(200, response.status_code, "Should return 200, device already attached to current user")
CustomerDevice.objects.filter(user_id=self.user, device_id=self.user_device).delete()
def test_device_list_view_204(self):
"""
Test case that should return an empty device list
:return:
"""
response = self.client.post(self.device_list_url)
self.assertEqual(204, response.status_code, "Should return empty list")
def test_device_list_view_200(self):
"""
Test case that should return at least 1 length device list
:return:
"""
CustomerDevice.objects.create(user_id=self.user, device_id=self.device)
response = self.client.post(self.device_list_url)
logger.debug('test_device_list_view_200 response: ' + str(response.json()))
self.assertEqual(200, response.status_code, "Should return devices list")
CustomerDevice.objects.filter(user_id=self.user, device_id=self.user_device).delete()
def test_forgot_password_view_400(self):
"""
Test case when no data provided
:return:
"""
response = self.client.post(self.forgot_password_url)
logger.debug('test_forgot_password_view_400 response: ' + str(response.json()))
self.assertEqual(400, response.status_code, "Should return 400, since missing data")
def test_forgot_password_view_401(self):
"""
Test case when wrong client secret used
:return:
"""
post_data = {
'client_secret': 'some_non_valid_client_secret',
'email': self.user.email
}
response = self.client.post(self.forgot_password_url, data=post_data)
logger.debug('test_forgot_password_view_401 response: ' + str(response.json()))
self.assertEqual(401, response.status_code, "Should return 401, since client secret not exists")
def test_forgot_password_view_200_1(self):
"""
Test case when non existing email requested forgot password
:return:
"""
post_body = {
'client_secret': self.oauth_client_secret,
'email': 'some@not_existing.email',
}
response = self.client.post(self.forgot_password_url, data=post_body, format='json')
self.assertEqual(200, response.status_code, "Should return 200, although email does not exists")
def test_forgot_password_view_200_2(self):
"""
Test case when process should pass successfully
:return:
"""
post_data = {
'client_secret': self.oauth_client_secret,
'email': self.user.email,
}
response = self.client.post(self.forgot_password_url, data=post_data, format='json')
logger.debug('test_forgot_password_view_200_2 response: ' + str(response.json()))
self.assertEqual(200, response.status_code, "Should return 200, process completed")
def test_get_device_pass_view_400(self):
"""
Test case when no data received
:return:
"""
response = self.client.post(self.get_device_pass_url)
logger.debug('test_get_device_pass_view_400 response: ' + str(response.json()))
self.assertEqual(400, response.status_code, "Should return 400, since missing data")
def test_get_device_pass_view_204(self):
"""
Test case when non existing device id received
:return:
"""
post_data = {
'device_id': 'some_non_existing_device_id'
}
response = self.client.post(self.get_device_pass_url, data=post_data)
self.assertEqual(204, response.status_code, "Should return 204, since device id does not exists")
def test_get_device_pass_view_409(self):
"""
Test case when trying to update password for a device that's owned by another user
:return:
"""
# Generate another test user
user = User.objects.create_user(
email='device@get_pass.test',
password=self.password,
is_active=True
)
# Generate another test device
device = Device.objects.create_device(device_id='get_device_pass_test_id', password=self.device_password,
model=DeviceModel.objects.get(model=self.device_model),
type=DeviceType.objects.get(type=self.device_type))
# Attach just created user and device
CustomerDevice.objects.create(user_id=user, device_id=device)
post_data = {
'device_id': device.device_id
}
response = self.client.post(self.get_device_pass_url, data=post_data)
self.assertEqual(409, response.status_code, "Should return 409, since device belongs to another user")
def test_get_device_pass_view_200(self):
"""
Test case when process should pass successfully
:return:
"""
CustomerDevice.objects.create(user_id=self.user, device_id=self.device)
post_data = {
'device_id': self.device.device_id
}
response = self.client.post(self.get_device_pass_url, data=post_data)
self.assertEqual(200, response.status_code, "Should return 200, process succeeded")
def test_remove_device_view_400(self):
"""
Test case when no data received
:return:
"""
response = self.client.post(self.remove_device_url)
logger.debug('test_remove_device_view_400 response: ' + str(response.json()))
self.assertEqual(400, response.status_code, "Should return 400, since missing data")
def test_remove_device_view_409_200(self):
"""
Test case when no data received
:return:
"""
# Generate another test device
device = Device.objects.create_device(device_id='remove_device_test_id', password=self.device_password,
model=DeviceModel.objects.get(model=self.device_model),
type=DeviceType.objects.get(type=self.device_type))
post_data = {
'device_id': device.device_id
}
response = self.client.post(self.remove_device_url, data=post_data)
logger.debug('test_remove_device_view_409_200 response: ' + str(response.json()))
self.assertEqual(409, response.status_code, "Should return 409, since device is not owned by current user")
# Attach just created device to current user
CustomerDevice.objects.create(user_id=self.user, device_id=device)
response = self.client.post(self.remove_device_url, data=post_data)
logger.debug('test_remove_device_view_409_200 response: ' + str(response.json()))
self.assertEqual(200, response.status_code, "Should return 200, since device owned by current user")
def test_reset_password_view_400(self):
"""
Test case when no data received
:return:
"""
post_data = {
'current_password': '',
'new_password': self.password
}
response = self.client.post(self.reset_password_url, data=post_data)
logger.debug('test_reset_password_view_400 response: ' + str(response.json()))
self.assertEqual(400, response.status_code, "Should return 400, since missing data")
def test_reset_password_view_422(self):
"""
Test case when wrong incorrect password received
:return:
"""
post_data = {
'current_password': 'somE_RandOm_PassWorD',
'new_password': self.password
}
response = self.client.post(self.reset_password_url, data=post_data)
logger.debug('test_reset_password_view_422 response: ' + str(response.json()))
self.assertEqual(422, response.status_code, "Should return 422, since current password is incorrect")
def test_reset_password_view_200(self):
"""
Test case when wrong correct password received
:return:
"""
post_data = {
'current_password': self.password,
'new_password': self.password
}
response = self.client.post(self.reset_password_url, data=post_data)
logger.debug('test_reset_password_view_200 response: ' + str(response.json()))
self.assertEqual(200, response.status_code, "Should return 200, since current password is correct")
def test_update_mqtt_user_pass_view_200(self):
"""
Test case when pass updates successfully
:return:
"""
response = self.client.post(self.update_device_pass_url)
logger.debug('test_update_mqtt_user_pass_view_200 response: ' + str(response.json()))
self.assertEqual(200, response.status_code, "Should return 200")
| 43.587805 | 117 | 0.650607 |
from django.utils.crypto import get_random_string
from django.urls import reverse
from django.utils import timezone
from rest_framework.test import APITestCase
from oauth2_provider.models import AccessToken
from oauth2_provider.models import Application
from nalkinscloud_mosquitto.models import Device, DeviceType, DeviceModel, CustomerDevice
from django_user_email_extension.models import User
import datetime
import logging
from nalkinscloud_django.settings import PROJECT_NAME
logger = logging.getLogger(PROJECT_NAME)
class APIViewsTestCase(APITestCase):
def setUp(self):
self.oauth_client_id = 'some_client_id'
self.oauth_client_secret = 'some_client_secret'
self.oauth_client = Application.objects.create(client_id=self.oauth_client_id,
client_secret=self.oauth_client_secret)
self.email = "test@nalkins.cloud"
self.password = "nalkinscloud"
self.user = User.objects.create_user(
email=self.email,
password=self.password,
is_active=True
)
expires = timezone.now() + datetime.timedelta(seconds=36000)
self.access_token = AccessToken.objects.create(
user=self.user,
application=self.oauth_client,
scope='',
token=get_random_string(length=32),
expires=expires)
self.access_token.save()
self.device_id = 'api_test_device_id'
self.device_password = 'nalkinscloud'
self.device_model = 'esp8266'
self.device_type = 'dht'
self.device = Device.objects.create_device(device_id=self.device_id, password=self.device_password,
model=DeviceModel.objects.get(model=self.device_model),
type=DeviceType.objects.get(type=self.device_type))
self.user_device_id = self.user.email
self.user_device_model = 'application'
self.user_device_type = 'user'
self.user_device = Device.objects.create_device(device_id=self.user_device_id, password=self.device_password,
model=DeviceModel.objects.get(model=self.user_device_model),
type=DeviceType.objects.get(type=self.user_device_type))
self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + str(self.access_token))
self.health_check_url = reverse('nalkinscloud_api:health_check')
self.registration_url = reverse('nalkinscloud_api:register')
self.device_activation_url = reverse('nalkinscloud_api:device_activation')
self.device_list_url = reverse('nalkinscloud_api:device_list')
self.forgot_password_url = reverse('nalkinscloud_api:forgot_password')
self.get_device_pass_url = reverse('nalkinscloud_api:get_device_pass')
self.remove_device_url = reverse('nalkinscloud_api:remove_device')
self.reset_password_url = reverse('nalkinscloud_api:reset_password')
self.update_device_pass_url = reverse('nalkinscloud_api:update_device_pass')
def test_registration(self):
post_body = {
'client_secret': self.oauth_client_secret,
'email': 'arielev@nalkins.cloud',
'password': self.password,
'first_name': 'Arie',
'last_name': 'Lev'
}
response = self.client.post(self.registration_url, data=post_body, format='json')
logger.debug("test_registration response: " + str(response.json()))
self.assertEqual(201, response.status_code, "Should return 201, register new user successfully")
response = self.client.post(self.registration_url, data=post_body, format='json')
self.assertEqual(409, response.status_code, "Should return 409 conflict, email already exists")
post_body['client_secret'] = 'some_non_existing_client_id'
response = self.client.post(self.registration_url, data=post_body, format='json')
self.assertEqual(401, response.status_code, "Should return not authorized")
self.assertEqual(User.objects.count(), 2, "Two users should be present in the system by this point")
def test_health_check_view(self):
response = self.client.post(self.health_check_url)
logger.debug('test_health_check_view response: ' + str(response.json()))
self.assertEqual(200, response.status_code, "Should return username")
def test_device_activation_view_204(self):
post_body = {
'device_id': 'non_existing_device',
'device_name': 'device_activation_test'
}
response = self.client.post(self.device_activation_url, data=post_body)
self.assertEqual(204, response.status_code, "Should return 204 since device does not exists")
def test_device_activation_view_400_1(self):
response = self.client.post(self.device_activation_url)
logger.debug('test_device_activation_view_400_1 response: ' + str(response.json()))
self.assertEqual(400, response.status_code, "Should return error 400 since there are missing values")
def test_device_activation_view_400_2(self):
post_body = {
'device_id': '',
'device_name': 'device_activation_test'
}
response = self.client.post(self.device_activation_url, data=post_body)
logger.debug('test_device_activation_view_400_2 response: ' + str(response.json()))
self.assertEqual(400, response.status_code, "Should return 400 since 'device_id' is blank")
self.assertEqual(response.json(), {'device_id': ['This field may not be blank.']},
"Should return blank field not allowed")
def test_device_activation_view_409(self):
user = User.objects.create_user(
email='device@activate.test',
password=self.password,
is_active=True
)
device = Device.objects.create_device(device_id='device_activation_test_id', password=self.device_password,
model=DeviceModel.objects.get(model=self.device_model),
type=DeviceType.objects.get(type=self.device_type))
CustomerDevice.objects.create(user_id=user, device_id=device)
post_body = {
'device_id': device,
'device_name': 'device_activation_test'
}
response = self.client.post(self.device_activation_url, data=post_body)
logger.debug('test_device_activation_view_409 response: ' + str(response.json()))
self.assertEqual(409, response.status_code, "Should return 409 conflict, device owned by other user")
def test_device_activation_view_200_1(self):
post_body = {
'device_id': self.device_id,
'device_name': 'device_activation_test'
}
response = self.client.post(self.device_activation_url, data=post_body)
logger.debug('test_device_activation_view_200_1 response: ' + str(response.json()))
self.assertEqual(200, response.status_code, "Should return 200, device attached")
def test_device_activation_view_200_2(self):
CustomerDevice.objects.create(user_id=self.user, device_id=self.device)
post_body = {
'device_id': self.device_id,
'device_name': 'test_device_activation_view_200_2'
}
response = self.client.post(self.device_activation_url, data=post_body)
logger.debug('test_device_activation_view_200_2 response: ' + str(response.json()))
self.assertEqual(200, response.status_code, "Should return 200, device already attached to current user")
CustomerDevice.objects.filter(user_id=self.user, device_id=self.user_device).delete()
def test_device_list_view_204(self):
response = self.client.post(self.device_list_url)
self.assertEqual(204, response.status_code, "Should return empty list")
def test_device_list_view_200(self):
CustomerDevice.objects.create(user_id=self.user, device_id=self.device)
response = self.client.post(self.device_list_url)
logger.debug('test_device_list_view_200 response: ' + str(response.json()))
self.assertEqual(200, response.status_code, "Should return devices list")
CustomerDevice.objects.filter(user_id=self.user, device_id=self.user_device).delete()
def test_forgot_password_view_400(self):
response = self.client.post(self.forgot_password_url)
logger.debug('test_forgot_password_view_400 response: ' + str(response.json()))
self.assertEqual(400, response.status_code, "Should return 400, since missing data")
def test_forgot_password_view_401(self):
post_data = {
'client_secret': 'some_non_valid_client_secret',
'email': self.user.email
}
response = self.client.post(self.forgot_password_url, data=post_data)
logger.debug('test_forgot_password_view_401 response: ' + str(response.json()))
self.assertEqual(401, response.status_code, "Should return 401, since client secret not exists")
def test_forgot_password_view_200_1(self):
post_body = {
'client_secret': self.oauth_client_secret,
'email': 'some@not_existing.email',
}
response = self.client.post(self.forgot_password_url, data=post_body, format='json')
self.assertEqual(200, response.status_code, "Should return 200, although email does not exists")
def test_forgot_password_view_200_2(self):
post_data = {
'client_secret': self.oauth_client_secret,
'email': self.user.email,
}
response = self.client.post(self.forgot_password_url, data=post_data, format='json')
logger.debug('test_forgot_password_view_200_2 response: ' + str(response.json()))
self.assertEqual(200, response.status_code, "Should return 200, process completed")
def test_get_device_pass_view_400(self):
response = self.client.post(self.get_device_pass_url)
logger.debug('test_get_device_pass_view_400 response: ' + str(response.json()))
self.assertEqual(400, response.status_code, "Should return 400, since missing data")
def test_get_device_pass_view_204(self):
post_data = {
'device_id': 'some_non_existing_device_id'
}
response = self.client.post(self.get_device_pass_url, data=post_data)
self.assertEqual(204, response.status_code, "Should return 204, since device id does not exists")
def test_get_device_pass_view_409(self):
user = User.objects.create_user(
email='device@get_pass.test',
password=self.password,
is_active=True
)
device = Device.objects.create_device(device_id='get_device_pass_test_id', password=self.device_password,
model=DeviceModel.objects.get(model=self.device_model),
type=DeviceType.objects.get(type=self.device_type))
CustomerDevice.objects.create(user_id=user, device_id=device)
post_data = {
'device_id': device.device_id
}
response = self.client.post(self.get_device_pass_url, data=post_data)
self.assertEqual(409, response.status_code, "Should return 409, since device belongs to another user")
def test_get_device_pass_view_200(self):
CustomerDevice.objects.create(user_id=self.user, device_id=self.device)
post_data = {
'device_id': self.device.device_id
}
response = self.client.post(self.get_device_pass_url, data=post_data)
self.assertEqual(200, response.status_code, "Should return 200, process succeeded")
def test_remove_device_view_400(self):
response = self.client.post(self.remove_device_url)
logger.debug('test_remove_device_view_400 response: ' + str(response.json()))
self.assertEqual(400, response.status_code, "Should return 400, since missing data")
def test_remove_device_view_409_200(self):
device = Device.objects.create_device(device_id='remove_device_test_id', password=self.device_password,
model=DeviceModel.objects.get(model=self.device_model),
type=DeviceType.objects.get(type=self.device_type))
post_data = {
'device_id': device.device_id
}
response = self.client.post(self.remove_device_url, data=post_data)
logger.debug('test_remove_device_view_409_200 response: ' + str(response.json()))
self.assertEqual(409, response.status_code, "Should return 409, since device is not owned by current user")
CustomerDevice.objects.create(user_id=self.user, device_id=device)
response = self.client.post(self.remove_device_url, data=post_data)
logger.debug('test_remove_device_view_409_200 response: ' + str(response.json()))
self.assertEqual(200, response.status_code, "Should return 200, since device owned by current user")
def test_reset_password_view_400(self):
post_data = {
'current_password': '',
'new_password': self.password
}
response = self.client.post(self.reset_password_url, data=post_data)
logger.debug('test_reset_password_view_400 response: ' + str(response.json()))
self.assertEqual(400, response.status_code, "Should return 400, since missing data")
def test_reset_password_view_422(self):
post_data = {
'current_password': 'somE_RandOm_PassWorD',
'new_password': self.password
}
response = self.client.post(self.reset_password_url, data=post_data)
logger.debug('test_reset_password_view_422 response: ' + str(response.json()))
self.assertEqual(422, response.status_code, "Should return 422, since current password is incorrect")
def test_reset_password_view_200(self):
post_data = {
'current_password': self.password,
'new_password': self.password
}
response = self.client.post(self.reset_password_url, data=post_data)
logger.debug('test_reset_password_view_200 response: ' + str(response.json()))
self.assertEqual(200, response.status_code, "Should return 200, since current password is correct")
def test_update_mqtt_user_pass_view_200(self):
response = self.client.post(self.update_device_pass_url)
logger.debug('test_update_mqtt_user_pass_view_200 response: ' + str(response.json()))
self.assertEqual(200, response.status_code, "Should return 200")
| true | true |
f72ba7d3fb86b7009f80264071c2ffe104766198 | 4,051 | py | Python | events/desucon2018/migrations/0001_initial.py | darkismus/kompassi | 35dea2c7af2857a69cae5c5982b48f01ba56da1f | [
"CC-BY-3.0"
] | 13 | 2015-11-29T12:19:12.000Z | 2021-02-21T15:42:11.000Z | events/desucon2018/migrations/0001_initial.py | darkismus/kompassi | 35dea2c7af2857a69cae5c5982b48f01ba56da1f | [
"CC-BY-3.0"
] | 23 | 2015-04-29T19:43:34.000Z | 2021-02-10T05:50:17.000Z | events/desucon2018/migrations/0001_initial.py | darkismus/kompassi | 35dea2c7af2857a69cae5c5982b48f01ba56da1f | [
"CC-BY-3.0"
] | 11 | 2015-09-20T18:59:00.000Z | 2020-02-07T08:47:34.000Z | # -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-01-28 15:36
from django.db import migrations, models
import django.db.models.deletion
import labour.models.signup_extras
class Migration(migrations.Migration):
initial = True
dependencies = [
('core', '0029_auto_20170827_1818'),
]
operations = [
migrations.CreateModel(
name='SignupExtra',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('is_active', models.BooleanField(default=True)),
('shift_type', models.CharField(choices=[('none', 'Ei väliä'), ('4h', 'Pari pitkää vuoroa'), ('yli4h', 'Useita lyhyitä vuoroja')], help_text='Haluatko tehdä yhden pitkän työvuoron vaiko monta lyhyempää vuoroa?', max_length=15, verbose_name='Toivottu työvuoron pituus')),
('prior_experience', models.TextField(blank=True, help_text='Kerro tässä kentässä, jos sinulla on aiempaa kokemusta vastaavista tehtävistä tai muuta sellaista työkokemusta, josta arvioit olevan hyötyä hakemassasi tehtävässä.', verbose_name='Työkokemus')),
('free_text', models.TextField(blank=True, help_text='Jos haluat sanoa hakemuksesi käsittelijöille jotain sellaista, jolle ei ole omaa kenttää yllä, käytä tätä kenttää. Jos haet valokuvaajaksi, kerro lisäksi millaista kuvauskalustoa sinulla on käytettävissäsi ja listaamuutamia gallerialinkkejä, joista pääsemme ihailemaan ottamiasi kuvia. ', verbose_name='Vapaa alue')),
('special_diet_other', models.TextField(blank=True, help_text='Jos noudatat erikoisruokavaliota, jota ei ole yllä olevassa listassa, ilmoita se tässä. Tapahtuman järjestäjä pyrkii ottamaan erikoisruokavaliot huomioon, mutta kaikkia erikoisruokavalioita ei välttämättä pystytä järjestämään.', verbose_name='Muu erikoisruokavalio')),
('shirt_size', models.CharField(choices=[('NO_SHIRT', 'Ei paitaa'), ('XS', 'XS Unisex'), ('S', 'S Unisex'), ('M', 'M Unisex'), ('L', 'L Unisex'), ('XL', 'XL Unisex'), ('XXL', 'XXL Unisex'), ('3XL', '3XL Unisex'), ('4XL', '4XL Unisex'), ('5XL', '5XL Unisex'), ('LF_XS', 'XS Ladyfit'), ('LF_S', 'S Ladyfit'), ('LF_M', 'M Ladyfit'), ('LF_L', 'L Ladyfit'), ('LF_XL', 'XL Ladyfit')], default='NO_SHIRT', help_text='Ajoissa ilmoittautuneet saavat maksuttoman työvoimapaidan. Kokotaulukot: <a href="http://www.bc-collection.eu/uploads/sizes/TU004.jpg" target="_blank">unisex-paita</a>, <a href="http://www.bc-collection.eu/uploads/sizes/TW040.jpg" target="_blank">ladyfit-paita</a>', max_length=8, verbose_name='Paidan koko')),
('shirt_type', models.CharField(choices=[('STAFF', 'Staff'), ('DESURITY', 'Desurity'), ('KUVAAJA', 'Kuvaaja'), ('VENDOR', 'Myynti'), ('TOOLATE', 'Myöhästyi paitatilauksesta')], default='TOOLATE', max_length=8, verbose_name='Paidan tyyppi')),
('night_work', models.BooleanField(default=False, verbose_name='Olen valmis tekemään yötöitä')),
('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='desucon2018_signup_extras', to='core.Event')),
('person', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='desucon2018_signup_extra', to='core.Person')),
],
options={
'abstract': False,
},
bases=(labour.models.signup_extras.SignupExtraMixin, models.Model),
),
migrations.CreateModel(
name='SpecialDiet',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=63)),
],
),
migrations.AddField(
model_name='signupextra',
name='special_diet',
field=models.ManyToManyField(blank=True, related_name='_signupextra_special_diet_+', to='desucon2018.SpecialDiet', verbose_name='Erikoisruokavalio'),
),
]
| 81.02 | 736 | 0.671933 |
from django.db import migrations, models
import django.db.models.deletion
import labour.models.signup_extras
class Migration(migrations.Migration):
initial = True
dependencies = [
('core', '0029_auto_20170827_1818'),
]
operations = [
migrations.CreateModel(
name='SignupExtra',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('is_active', models.BooleanField(default=True)),
('shift_type', models.CharField(choices=[('none', 'Ei väliä'), ('4h', 'Pari pitkää vuoroa'), ('yli4h', 'Useita lyhyitä vuoroja')], help_text='Haluatko tehdä yhden pitkän työvuoron vaiko monta lyhyempää vuoroa?', max_length=15, verbose_name='Toivottu työvuoron pituus')),
('prior_experience', models.TextField(blank=True, help_text='Kerro tässä kentässä, jos sinulla on aiempaa kokemusta vastaavista tehtävistä tai muuta sellaista työkokemusta, josta arvioit olevan hyötyä hakemassasi tehtävässä.', verbose_name='Työkokemus')),
('free_text', models.TextField(blank=True, help_text='Jos haluat sanoa hakemuksesi käsittelijöille jotain sellaista, jolle ei ole omaa kenttää yllä, käytä tätä kenttää. Jos haet valokuvaajaksi, kerro lisäksi millaista kuvauskalustoa sinulla on käytettävissäsi ja listaamuutamia gallerialinkkejä, joista pääsemme ihailemaan ottamiasi kuvia. ', verbose_name='Vapaa alue')),
('special_diet_other', models.TextField(blank=True, help_text='Jos noudatat erikoisruokavaliota, jota ei ole yllä olevassa listassa, ilmoita se tässä. Tapahtuman järjestäjä pyrkii ottamaan erikoisruokavaliot huomioon, mutta kaikkia erikoisruokavalioita ei välttämättä pystytä järjestämään.', verbose_name='Muu erikoisruokavalio')),
('shirt_size', models.CharField(choices=[('NO_SHIRT', 'Ei paitaa'), ('XS', 'XS Unisex'), ('S', 'S Unisex'), ('M', 'M Unisex'), ('L', 'L Unisex'), ('XL', 'XL Unisex'), ('XXL', 'XXL Unisex'), ('3XL', '3XL Unisex'), ('4XL', '4XL Unisex'), ('5XL', '5XL Unisex'), ('LF_XS', 'XS Ladyfit'), ('LF_S', 'S Ladyfit'), ('LF_M', 'M Ladyfit'), ('LF_L', 'L Ladyfit'), ('LF_XL', 'XL Ladyfit')], default='NO_SHIRT', help_text='Ajoissa ilmoittautuneet saavat maksuttoman työvoimapaidan. Kokotaulukot: <a href="http://www.bc-collection.eu/uploads/sizes/TU004.jpg" target="_blank">unisex-paita</a>, <a href="http://www.bc-collection.eu/uploads/sizes/TW040.jpg" target="_blank">ladyfit-paita</a>', max_length=8, verbose_name='Paidan koko')),
('shirt_type', models.CharField(choices=[('STAFF', 'Staff'), ('DESURITY', 'Desurity'), ('KUVAAJA', 'Kuvaaja'), ('VENDOR', 'Myynti'), ('TOOLATE', 'Myöhästyi paitatilauksesta')], default='TOOLATE', max_length=8, verbose_name='Paidan tyyppi')),
('night_work', models.BooleanField(default=False, verbose_name='Olen valmis tekemään yötöitä')),
('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='desucon2018_signup_extras', to='core.Event')),
('person', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='desucon2018_signup_extra', to='core.Person')),
],
options={
'abstract': False,
},
bases=(labour.models.signup_extras.SignupExtraMixin, models.Model),
),
migrations.CreateModel(
name='SpecialDiet',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=63)),
],
),
migrations.AddField(
model_name='signupextra',
name='special_diet',
field=models.ManyToManyField(blank=True, related_name='_signupextra_special_diet_+', to='desucon2018.SpecialDiet', verbose_name='Erikoisruokavalio'),
),
]
| true | true |
f72ba8a9a4446d79a62e8b823b38942abbb5f5f3 | 232 | py | Python | my_awesome_project/users/serializers.py | mikejuliano/drf-react-native | 71d40dd168407096e213157c0141588d474ae3d0 | [
"MIT"
] | null | null | null | my_awesome_project/users/serializers.py | mikejuliano/drf-react-native | 71d40dd168407096e213157c0141588d474ae3d0 | [
"MIT"
] | null | null | null | my_awesome_project/users/serializers.py | mikejuliano/drf-react-native | 71d40dd168407096e213157c0141588d474ae3d0 | [
"MIT"
] | null | null | null | from rest_framework import serializers
# from django.contrib.auth.models import User
from .models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username',)
| 21.090909 | 50 | 0.728448 | from rest_framework import serializers
from .models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username',)
| true | true |
f72ba8c520fc112f474edccb7228fd1f7e57e095 | 5,326 | py | Python | PythonAPI/carissma_project/lib/python3.5/site-packages/matplotlib/tri/tripcolor.py | AbdulHoffmann/carla_carissma | 8d382769ffa02a6c61a22c57160285505f5ff0a4 | [
"MIT"
] | 445 | 2019-01-26T13:50:26.000Z | 2022-03-18T05:17:38.000Z | venv/lib/python3.7/site-packages/matplotlib/tri/tripcolor.py | John1001Song/Big-Data-Robo-Adviser | 9444dce96954c546333d5aecc92a06c3bfd19aa5 | [
"MIT"
] | 242 | 2019-01-29T15:48:27.000Z | 2022-03-31T22:09:21.000Z | venv/lib/python3.7/site-packages/matplotlib/tri/tripcolor.py | John1001Song/Big-Data-Robo-Adviser | 9444dce96954c546333d5aecc92a06c3bfd19aa5 | [
"MIT"
] | 64 | 2018-04-25T08:51:57.000Z | 2022-01-29T14:13:57.000Z | import numpy as np
from matplotlib.collections import PolyCollection, TriMesh
from matplotlib.colors import Normalize
from matplotlib.tri.triangulation import Triangulation
def tripcolor(ax, *args, alpha=1.0, norm=None, cmap=None, vmin=None,
vmax=None, shading='flat', facecolors=None, **kwargs):
"""
Create a pseudocolor plot of an unstructured triangular grid.
The triangulation can be specified in one of two ways; either::
tripcolor(triangulation, ...)
where triangulation is a :class:`matplotlib.tri.Triangulation`
object, or
::
tripcolor(x, y, ...)
tripcolor(x, y, triangles, ...)
tripcolor(x, y, triangles=triangles, ...)
tripcolor(x, y, mask=mask, ...)
tripcolor(x, y, triangles, mask=mask, ...)
in which case a Triangulation object will be created. See
:class:`~matplotlib.tri.Triangulation` for a explanation of these
possibilities.
The next argument must be *C*, the array of color values, either
one per point in the triangulation if color values are defined at
points, or one per triangle in the triangulation if color values
are defined at triangles. If there are the same number of points
and triangles in the triangulation it is assumed that color
values are defined at points; to force the use of color values at
triangles use the kwarg ``facecolors=C`` instead of just ``C``.
*shading* may be 'flat' (the default) or 'gouraud'. If *shading*
is 'flat' and C values are defined at points, the color values
used for each triangle are from the mean C of the triangle's
three points. If *shading* is 'gouraud' then color values must be
defined at points.
The remaining kwargs are the same as for
:meth:`~matplotlib.axes.Axes.pcolor`.
"""
if shading not in ['flat', 'gouraud']:
raise ValueError("shading must be one of ['flat', 'gouraud'] "
"not {0}".format(shading))
tri, args, kwargs = Triangulation.get_from_args_and_kwargs(*args, **kwargs)
# C is the colors array defined at either points or faces (i.e. triangles).
# If facecolors is None, C are defined at points.
# If facecolors is not None, C are defined at faces.
if facecolors is not None:
C = facecolors
else:
C = np.asarray(args[0])
# If there are a different number of points and triangles in the
# triangulation, can omit facecolors kwarg as it is obvious from
# length of C whether it refers to points or faces.
# Do not do this for gouraud shading.
if (facecolors is None and len(C) == len(tri.triangles) and
len(C) != len(tri.x) and shading != 'gouraud'):
facecolors = C
# Check length of C is OK.
if ((facecolors is None and len(C) != len(tri.x)) or
(facecolors is not None and len(C) != len(tri.triangles))):
raise ValueError('Length of color values array must be the same '
'as either the number of triangulation points '
'or triangles')
# Handling of linewidths, shading, edgecolors and antialiased as
# in Axes.pcolor
linewidths = (0.25,)
if 'linewidth' in kwargs:
kwargs['linewidths'] = kwargs.pop('linewidth')
kwargs.setdefault('linewidths', linewidths)
edgecolors = 'none'
if 'edgecolor' in kwargs:
kwargs['edgecolors'] = kwargs.pop('edgecolor')
ec = kwargs.setdefault('edgecolors', edgecolors)
if 'antialiased' in kwargs:
kwargs['antialiaseds'] = kwargs.pop('antialiased')
if 'antialiaseds' not in kwargs and ec.lower() == "none":
kwargs['antialiaseds'] = False
if shading == 'gouraud':
if facecolors is not None:
raise ValueError('Gouraud shading does not support the use '
'of facecolors kwarg')
if len(C) != len(tri.x):
raise ValueError('For gouraud shading, the length of color '
'values array must be the same as the '
'number of triangulation points')
collection = TriMesh(tri, **kwargs)
else:
# Vertices of triangles.
maskedTris = tri.get_masked_triangles()
verts = np.stack((tri.x[maskedTris], tri.y[maskedTris]), axis=-1)
# Color values.
if facecolors is None:
# One color per triangle, the mean of the 3 vertex color values.
C = C[maskedTris].mean(axis=1)
elif tri.mask is not None:
# Remove color values of masked triangles.
C = C.compress(1-tri.mask)
collection = PolyCollection(verts, **kwargs)
collection.set_alpha(alpha)
collection.set_array(C)
if norm is not None and not isinstance(norm, Normalize):
raise ValueError("'norm' must be an instance of 'Normalize'")
collection.set_cmap(cmap)
collection.set_norm(norm)
if vmin is not None or vmax is not None:
collection.set_clim(vmin, vmax)
else:
collection.autoscale_None()
ax.grid(False)
minx = tri.x.min()
maxx = tri.x.max()
miny = tri.y.min()
maxy = tri.y.max()
corners = (minx, miny), (maxx, maxy)
ax.update_datalim(corners)
ax.autoscale_view()
ax.add_collection(collection)
return collection
| 38.042857 | 79 | 0.639504 | import numpy as np
from matplotlib.collections import PolyCollection, TriMesh
from matplotlib.colors import Normalize
from matplotlib.tri.triangulation import Triangulation
def tripcolor(ax, *args, alpha=1.0, norm=None, cmap=None, vmin=None,
vmax=None, shading='flat', facecolors=None, **kwargs):
if shading not in ['flat', 'gouraud']:
raise ValueError("shading must be one of ['flat', 'gouraud'] "
"not {0}".format(shading))
tri, args, kwargs = Triangulation.get_from_args_and_kwargs(*args, **kwargs)
if facecolors is not None:
C = facecolors
else:
C = np.asarray(args[0])
if (facecolors is None and len(C) == len(tri.triangles) and
len(C) != len(tri.x) and shading != 'gouraud'):
facecolors = C
if ((facecolors is None and len(C) != len(tri.x)) or
(facecolors is not None and len(C) != len(tri.triangles))):
raise ValueError('Length of color values array must be the same '
'as either the number of triangulation points '
'or triangles')
linewidths = (0.25,)
if 'linewidth' in kwargs:
kwargs['linewidths'] = kwargs.pop('linewidth')
kwargs.setdefault('linewidths', linewidths)
edgecolors = 'none'
if 'edgecolor' in kwargs:
kwargs['edgecolors'] = kwargs.pop('edgecolor')
ec = kwargs.setdefault('edgecolors', edgecolors)
if 'antialiased' in kwargs:
kwargs['antialiaseds'] = kwargs.pop('antialiased')
if 'antialiaseds' not in kwargs and ec.lower() == "none":
kwargs['antialiaseds'] = False
if shading == 'gouraud':
if facecolors is not None:
raise ValueError('Gouraud shading does not support the use '
'of facecolors kwarg')
if len(C) != len(tri.x):
raise ValueError('For gouraud shading, the length of color '
'values array must be the same as the '
'number of triangulation points')
collection = TriMesh(tri, **kwargs)
else:
maskedTris = tri.get_masked_triangles()
verts = np.stack((tri.x[maskedTris], tri.y[maskedTris]), axis=-1)
if facecolors is None:
C = C[maskedTris].mean(axis=1)
elif tri.mask is not None:
C = C.compress(1-tri.mask)
collection = PolyCollection(verts, **kwargs)
collection.set_alpha(alpha)
collection.set_array(C)
if norm is not None and not isinstance(norm, Normalize):
raise ValueError("'norm' must be an instance of 'Normalize'")
collection.set_cmap(cmap)
collection.set_norm(norm)
if vmin is not None or vmax is not None:
collection.set_clim(vmin, vmax)
else:
collection.autoscale_None()
ax.grid(False)
minx = tri.x.min()
maxx = tri.x.max()
miny = tri.y.min()
maxy = tri.y.max()
corners = (minx, miny), (maxx, maxy)
ax.update_datalim(corners)
ax.autoscale_view()
ax.add_collection(collection)
return collection
| true | true |
f72ba8feede17a2888058de31640869ebe5db2d9 | 1,794 | py | Python | app/features/steps/value_propagation_test.py | muglyon/https-github.com-muglyon-DCOP-Decentralised-Control-of-Intelligent-Devices | 68cb868a0875f5e119ac0dbea024c17d241347ac | [
"MIT"
] | 3 | 2020-04-10T09:13:17.000Z | 2021-04-08T07:14:03.000Z | app/features/steps/value_propagation_test.py | muglyon/https-github.com-muglyon-DCOP-Decentralised-Control-of-Intelligent-Devices | 68cb868a0875f5e119ac0dbea024c17d241347ac | [
"MIT"
] | 8 | 2020-09-26T00:55:30.000Z | 2022-01-13T02:32:04.000Z | app/features/steps/value_propagation_test.py | muglyon/https-github.com-muglyon-DCOP-Decentralised-Control-of-Intelligent-Devices | 68cb868a0875f5e119ac0dbea024c17d241347ac | [
"MIT"
] | 2 | 2020-04-12T10:08:15.000Z | 2022-01-20T09:34:50.000Z | #! python3
# value_propagation_test.py - Test the VALUE Propagation behavior
from behave import *
from hamcrest import *
import numpy
@when('get VALUE from parent after UTIL propagation')
def step_impl(context):
set_up(context)
context.dpop_to_test.util_manager.JOIN = context.util_matrix
@then('should select the optimal assignment')
def step_impl(context):
index = context.dpop_to_test.value_manager.get_index_of_best_value_with(
context.data,
context.dpop_to_test.util_manager.matrix_dimensions_order,
context.dpop_to_test.util_manager.JOIN
)
assert_that(index, equal_to(2))
@when('parent send values to wrong format')
def step_impl(context):
set_up(context)
context.data = 'wrong format'
@when('matrix is Null')
def step_impl(context):
set_up(context)
context.util_matrix = None
@then('should raise an exception')
def step_impl(context):
assert_that(calling(context.dpop_to_test.value_manager.get_index_of_best_value_with)
.with_args(context.data, context.util_matrix), raises(Exception))
@when('matrix has 1 dimension')
def step_impl(context):
set_up(context)
context.dpop_to_test.util_manager.JOIN = numpy.asmatrix([[1], [0], [1]])
@then('should return the min value index')
def step_impl(context):
index = context.dpop_to_test.value_manager.get_index_of_best_value_with(
context.data,
context.dpop_to_test.util_manager.matrix_dimensions_order,
context.dpop_to_test.util_manager.JOIN
)
assert_that(index, equal_to(1))
###
# Privates Methods
###
def set_up(context):
context.dpop_to_test.util_manager.matrix_dimensions_order = [1]
context.util_matrix = numpy.arange(start=11, stop=2, step=-1).reshape(3, 3)
context.data = {"1": 1}
| 26.382353 | 88 | 0.731884 |
from behave import *
from hamcrest import *
import numpy
@when('get VALUE from parent after UTIL propagation')
def step_impl(context):
set_up(context)
context.dpop_to_test.util_manager.JOIN = context.util_matrix
@then('should select the optimal assignment')
def step_impl(context):
index = context.dpop_to_test.value_manager.get_index_of_best_value_with(
context.data,
context.dpop_to_test.util_manager.matrix_dimensions_order,
context.dpop_to_test.util_manager.JOIN
)
assert_that(index, equal_to(2))
@when('parent send values to wrong format')
def step_impl(context):
set_up(context)
context.data = 'wrong format'
@when('matrix is Null')
def step_impl(context):
set_up(context)
context.util_matrix = None
@then('should raise an exception')
def step_impl(context):
assert_that(calling(context.dpop_to_test.value_manager.get_index_of_best_value_with)
.with_args(context.data, context.util_matrix), raises(Exception))
@when('matrix has 1 dimension')
def step_impl(context):
set_up(context)
context.dpop_to_test.util_manager.JOIN = numpy.asmatrix([[1], [0], [1]])
@then('should return the min value index')
def step_impl(context):
index = context.dpop_to_test.value_manager.get_index_of_best_value_with(
context.data,
context.dpop_to_test.util_manager.matrix_dimensions_order,
context.dpop_to_test.util_manager.JOIN
)
assert_that(index, equal_to(1))
ef set_up(context):
context.dpop_to_test.util_manager.matrix_dimensions_order = [1]
context.util_matrix = numpy.arange(start=11, stop=2, step=-1).reshape(3, 3)
context.data = {"1": 1}
| true | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.