max_stars_repo_path stringlengths 4 286 | max_stars_repo_name stringlengths 5 119 | max_stars_count int64 0 191k | id stringlengths 1 7 | content stringlengths 6 1.03M | content_cleaned stringlengths 6 1.03M | language stringclasses 111
values | language_score float64 0.03 1 | comments stringlengths 0 556k | edu_score float64 0.32 5.03 | edu_int_score int64 0 5 |
|---|---|---|---|---|---|---|---|---|---|---|
3-factor-model.py | VincentGaoHJ/Fama-French-3-Factor-Model | 9 | 6627951 | # -*- coding: utf-8 -*-
"""
@Date: Created on Tue Apr 9 01:01:00 2019
@Author: <NAME>
@Description: Fama-French 3-factor model
首先直观感受三因子模型的有效性:
按照市值分成五组,感受市值与收益率关系
按照账面市值比分成五组,感受账面市值比与收益率关系
按照市值和账面市值比分成二十五组,感受两个因子与收益率关系
"""
import pandas as pd
class Portafolio(object):
"""
创建组合的类
idnum [组合的代号 00-44(str)]
num [组合所包含的数据的条目数量(int)]
rank_Msmv [组合所代表的市值属性大小 0最小,4最大(int)]
rank_Bktomk [组合所代表的账面市值比属性大小 0最小,4最大(int)]
Mretwd [平均考虑现金红利再投资的月个股回报率(float)]
Mretnd [平均不考虑现金红利再投资的月个股回报率(float)]
Msmvosd [平均月个股流通市值(float)] - 个股的流通股数与月收盘价的乘积
Msmvttl [平均月个股总市值(float)] - 个股的发行总股数与月收盘价的乘积
Bktomk [平均账面市值比(float)]
"""
def __init__(self, idnum, num, rank_Msmv, rank_Bktomk, Msmvosd, Msmvttl, Mretwd, Mretnd, Bktomk):
self.idnum = idnum
self.num = num
self.rank_Msmv = rank_Msmv
self.rank_Bktomk = rank_Bktomk
self.Msmvosd = Msmvosd
self.Msmvttl = Msmvttl
self.Mretwd = Mretwd
self.Mretnd = Mretnd
self.Bktomk = Bktomk
def prepare_Portafolio(num):
"""
读取每一个二十五个以csv文件储存的Portafolio
:param num: 所需要的数据的年份,如果传入的num为零,则使用所有年份的数据
:return: 为每一个Portafolio创建一个类对象
"""
for i in range(25):
a = int(i / 5)
b = i % 5
path = ".\\pf25_data\\pfdata_" + str(i) + ".csv"
data_df = pd.read_csv(path)
if num != 0:
data_df = data_df.loc[data_df["Trdmnt_year"] == num]
temp_idnum = str(i)
temp_num = data_df.shape[0]
temp_rank_Msmv = a
temp_rank_Bktomk = b
temp_Msmvosd = data_df["Msmvosd"].mean()
temp_Msmvttl = data_df["Msmvttl"].mean()
temp_Mretwd = data_df["Mretwd"].mean()
temp_Mretnd = data_df["Mretnd"].mean()
temp_Bktomk = data_df["bemeA"].mean()
Portafolio_dict[str(i)] = Portafolio(temp_idnum, temp_num, temp_rank_Msmv, temp_rank_Bktomk,
temp_Msmvosd, temp_Msmvttl, temp_Mretwd, temp_Mretnd, temp_Bktomk)
return Portafolio_dict
def Msmv_portafolio(Portafolio_dict):
"""
根据市值大小分成五个Portafolio,并且输出他们的信息
:param Portafolio_dict: 类对象字典
:return:
"""
print("\n根据市值大小输出\n")
for i in range(5):
value_rank_Msmv = value_Msmvosd = value_Msmvttl = value_Bktomk = value_Mretwd = value_Mretnd = 0
for j in range(5):
id = str(i * 5 + j)
value_rank_Msmv = Portafolio_dict[id].rank_Msmv
value_Msmvosd += Portafolio_dict[id].Msmvosd
value_Msmvttl += Portafolio_dict[id].Msmvttl
value_Bktomk += Portafolio_dict[id].Bktomk
value_Mretwd += Portafolio_dict[id].Mretwd
value_Mretnd += Portafolio_dict[id].Mretnd
print(value_rank_Msmv, end="\t")
print(value_Msmvosd / 5, end="\t")
print(value_Msmvttl / 5, end="\t")
print(value_Bktomk / 5, end="\t")
print(value_Mretwd / 5, end="\t")
print(value_Mretnd / 5)
def Bktomk_portafolio(Portafolio_dict):
"""
根据账面市值比大小分成五个 Portafolio,并且输出他们的信息
:param Portafolio_dict: 类对象字典
:return:
"""
print("\n根据账面市值比大小输出\n")
for i in range(5):
value_rank_Bktomk = value_Msmvosd = value_Msmvttl = value_Bktomk = value_Mretwd = value_Mretnd = 0
for j in range(5):
id = str(i + j * 5)
value_rank_Bktomk = Portafolio_dict[id].rank_Bktomk
value_Msmvosd += Portafolio_dict[id].Msmvosd
value_Msmvttl += Portafolio_dict[id].Msmvttl
value_Bktomk += Portafolio_dict[id].Bktomk
value_Mretwd += Portafolio_dict[id].Mretwd
value_Mretnd += Portafolio_dict[id].Mretnd
print(value_rank_Bktomk, end="\t")
print(value_Msmvosd / 5, end="\t")
print(value_Msmvttl / 5, end="\t")
print(value_Bktomk / 5, end="\t")
print(value_Mretwd / 5, end="\t")
print(value_Mretnd / 5)
def twentyfive_Mretwd_portafolio(Portafolio_dict):
"""
根据账面市值比大小和市值分成25个 Portafolio,并且输出他们的Mretwd
:param Portafolio_dict: 类对象字典
:return:
"""
print("\n根据账面市值比与市值大小输出Mretwd\n")
for i in range(5):
for j in range(5):
id = str(i * 5 + j)
value_Mretwd = Portafolio_dict[id].Mretwd
print(value_Mretwd, end="\t")
print(end="\n")
def twentyfive_Mretnd_portafolio(Portafolio_dict):
"""
根据账面市值比大小和市值分成25个 Portafolio,并且输出他们的Mretnd
:param Portafolio_dict: 类对象字典
:return:
"""
print("\n根据账面市值比与市值大小输出Mretnd\n")
for i in range(5):
for j in range(5):
id = str(i * 5 + j)
value_Mretnd = Portafolio_dict[id].Mretnd
print(value_Mretnd, end="\t")
print(end="\n")
def twentyfive_Bktomk_portafolio(Portafolio_dict):
"""
根据账面市值比大小和市值分成25个Portafolio,并且输出他们的 Bktomk
:param Portafolio_dict: 类对象字典
:return:
"""
print("\n根据账面市值比与市值大小输出账面市值比Bktomk\n")
for i in range(5):
for j in range(5):
id = str(i * 5 + j)
value_Bktomk = Portafolio_dict[id].Bktomk
print(value_Bktomk, end="\t")
print(end="\n")
def twentyfive_Msmvttl_portafolio(Portafolio_dict):
"""
根据账面市值比大小和市值分成25个Portafolio,并且输出他们的 Msmvttl
:param Portafolio_dict: 类对象字典
:return:
"""
print("\n根据账面市值比与市值大小输出市值Msmvttl\n")
for i in range(5):
for j in range(5):
id = str(i * 5 + j)
value_Msmvttl = Portafolio_dict[id].Msmvttl
print(value_Msmvttl, end="\t")
print(end="\n")
def twentyfive_Msmvosd_portafolio(Portafolio_dict):
"""
根据账面市值比大小和市值分成25个Portafolio,并且输出他们的 Msmvosd
:param Portafolio_dict: 类对象字典
:return:
"""
print("\n根据账面市值比与市值大小输出市值Msmvosd\n")
for i in range(5):
for j in range(5):
id = str(i * 5 + j)
value_Msmvosd = Portafolio_dict[id].Msmvosd
print(value_Msmvosd, end="\t")
print(end="\n")
def print_matrix(dictionary):
"""
根据25个Portafolio输出相关的矩阵
:param dictionary: 类对象字典
:return:
"""
Msmv_portafolio(dictionary)
Bktomk_portafolio(dictionary)
twentyfive_Mretwd_portafolio(dictionary)
twentyfive_Mretnd_portafolio(dictionary)
twentyfive_Bktomk_portafolio(dictionary)
twentyfive_Msmvttl_portafolio(dictionary)
twentyfive_Msmvosd_portafolio(dictionary)
# 创建25个类对象,并且用一个字典进行管理
Portafolio_dict = {}
Portafolio_dict = prepare_Portafolio(0)
print_matrix(Portafolio_dict)
# Portafolio_dict = prepare_Portafolio(2018)
# print_matrix(Portafolio_dict)
| # -*- coding: utf-8 -*-
"""
@Date: Created on Tue Apr 9 01:01:00 2019
@Author: <NAME>
@Description: Fama-French 3-factor model
首先直观感受三因子模型的有效性:
按照市值分成五组,感受市值与收益率关系
按照账面市值比分成五组,感受账面市值比与收益率关系
按照市值和账面市值比分成二十五组,感受两个因子与收益率关系
"""
import pandas as pd
class Portafolio(object):
"""
创建组合的类
idnum [组合的代号 00-44(str)]
num [组合所包含的数据的条目数量(int)]
rank_Msmv [组合所代表的市值属性大小 0最小,4最大(int)]
rank_Bktomk [组合所代表的账面市值比属性大小 0最小,4最大(int)]
Mretwd [平均考虑现金红利再投资的月个股回报率(float)]
Mretnd [平均不考虑现金红利再投资的月个股回报率(float)]
Msmvosd [平均月个股流通市值(float)] - 个股的流通股数与月收盘价的乘积
Msmvttl [平均月个股总市值(float)] - 个股的发行总股数与月收盘价的乘积
Bktomk [平均账面市值比(float)]
"""
def __init__(self, idnum, num, rank_Msmv, rank_Bktomk, Msmvosd, Msmvttl, Mretwd, Mretnd, Bktomk):
self.idnum = idnum
self.num = num
self.rank_Msmv = rank_Msmv
self.rank_Bktomk = rank_Bktomk
self.Msmvosd = Msmvosd
self.Msmvttl = Msmvttl
self.Mretwd = Mretwd
self.Mretnd = Mretnd
self.Bktomk = Bktomk
def prepare_Portafolio(num):
"""
读取每一个二十五个以csv文件储存的Portafolio
:param num: 所需要的数据的年份,如果传入的num为零,则使用所有年份的数据
:return: 为每一个Portafolio创建一个类对象
"""
for i in range(25):
a = int(i / 5)
b = i % 5
path = ".\\pf25_data\\pfdata_" + str(i) + ".csv"
data_df = pd.read_csv(path)
if num != 0:
data_df = data_df.loc[data_df["Trdmnt_year"] == num]
temp_idnum = str(i)
temp_num = data_df.shape[0]
temp_rank_Msmv = a
temp_rank_Bktomk = b
temp_Msmvosd = data_df["Msmvosd"].mean()
temp_Msmvttl = data_df["Msmvttl"].mean()
temp_Mretwd = data_df["Mretwd"].mean()
temp_Mretnd = data_df["Mretnd"].mean()
temp_Bktomk = data_df["bemeA"].mean()
Portafolio_dict[str(i)] = Portafolio(temp_idnum, temp_num, temp_rank_Msmv, temp_rank_Bktomk,
temp_Msmvosd, temp_Msmvttl, temp_Mretwd, temp_Mretnd, temp_Bktomk)
return Portafolio_dict
def Msmv_portafolio(Portafolio_dict):
"""
根据市值大小分成五个Portafolio,并且输出他们的信息
:param Portafolio_dict: 类对象字典
:return:
"""
print("\n根据市值大小输出\n")
for i in range(5):
value_rank_Msmv = value_Msmvosd = value_Msmvttl = value_Bktomk = value_Mretwd = value_Mretnd = 0
for j in range(5):
id = str(i * 5 + j)
value_rank_Msmv = Portafolio_dict[id].rank_Msmv
value_Msmvosd += Portafolio_dict[id].Msmvosd
value_Msmvttl += Portafolio_dict[id].Msmvttl
value_Bktomk += Portafolio_dict[id].Bktomk
value_Mretwd += Portafolio_dict[id].Mretwd
value_Mretnd += Portafolio_dict[id].Mretnd
print(value_rank_Msmv, end="\t")
print(value_Msmvosd / 5, end="\t")
print(value_Msmvttl / 5, end="\t")
print(value_Bktomk / 5, end="\t")
print(value_Mretwd / 5, end="\t")
print(value_Mretnd / 5)
def Bktomk_portafolio(Portafolio_dict):
"""
根据账面市值比大小分成五个 Portafolio,并且输出他们的信息
:param Portafolio_dict: 类对象字典
:return:
"""
print("\n根据账面市值比大小输出\n")
for i in range(5):
value_rank_Bktomk = value_Msmvosd = value_Msmvttl = value_Bktomk = value_Mretwd = value_Mretnd = 0
for j in range(5):
id = str(i + j * 5)
value_rank_Bktomk = Portafolio_dict[id].rank_Bktomk
value_Msmvosd += Portafolio_dict[id].Msmvosd
value_Msmvttl += Portafolio_dict[id].Msmvttl
value_Bktomk += Portafolio_dict[id].Bktomk
value_Mretwd += Portafolio_dict[id].Mretwd
value_Mretnd += Portafolio_dict[id].Mretnd
print(value_rank_Bktomk, end="\t")
print(value_Msmvosd / 5, end="\t")
print(value_Msmvttl / 5, end="\t")
print(value_Bktomk / 5, end="\t")
print(value_Mretwd / 5, end="\t")
print(value_Mretnd / 5)
def twentyfive_Mretwd_portafolio(Portafolio_dict):
"""
根据账面市值比大小和市值分成25个 Portafolio,并且输出他们的Mretwd
:param Portafolio_dict: 类对象字典
:return:
"""
print("\n根据账面市值比与市值大小输出Mretwd\n")
for i in range(5):
for j in range(5):
id = str(i * 5 + j)
value_Mretwd = Portafolio_dict[id].Mretwd
print(value_Mretwd, end="\t")
print(end="\n")
def twentyfive_Mretnd_portafolio(Portafolio_dict):
"""
根据账面市值比大小和市值分成25个 Portafolio,并且输出他们的Mretnd
:param Portafolio_dict: 类对象字典
:return:
"""
print("\n根据账面市值比与市值大小输出Mretnd\n")
for i in range(5):
for j in range(5):
id = str(i * 5 + j)
value_Mretnd = Portafolio_dict[id].Mretnd
print(value_Mretnd, end="\t")
print(end="\n")
def twentyfive_Bktomk_portafolio(Portafolio_dict):
"""
根据账面市值比大小和市值分成25个Portafolio,并且输出他们的 Bktomk
:param Portafolio_dict: 类对象字典
:return:
"""
print("\n根据账面市值比与市值大小输出账面市值比Bktomk\n")
for i in range(5):
for j in range(5):
id = str(i * 5 + j)
value_Bktomk = Portafolio_dict[id].Bktomk
print(value_Bktomk, end="\t")
print(end="\n")
def twentyfive_Msmvttl_portafolio(Portafolio_dict):
"""
根据账面市值比大小和市值分成25个Portafolio,并且输出他们的 Msmvttl
:param Portafolio_dict: 类对象字典
:return:
"""
print("\n根据账面市值比与市值大小输出市值Msmvttl\n")
for i in range(5):
for j in range(5):
id = str(i * 5 + j)
value_Msmvttl = Portafolio_dict[id].Msmvttl
print(value_Msmvttl, end="\t")
print(end="\n")
def twentyfive_Msmvosd_portafolio(Portafolio_dict):
"""
根据账面市值比大小和市值分成25个Portafolio,并且输出他们的 Msmvosd
:param Portafolio_dict: 类对象字典
:return:
"""
print("\n根据账面市值比与市值大小输出市值Msmvosd\n")
for i in range(5):
for j in range(5):
id = str(i * 5 + j)
value_Msmvosd = Portafolio_dict[id].Msmvosd
print(value_Msmvosd, end="\t")
print(end="\n")
def print_matrix(dictionary):
"""
根据25个Portafolio输出相关的矩阵
:param dictionary: 类对象字典
:return:
"""
Msmv_portafolio(dictionary)
Bktomk_portafolio(dictionary)
twentyfive_Mretwd_portafolio(dictionary)
twentyfive_Mretnd_portafolio(dictionary)
twentyfive_Bktomk_portafolio(dictionary)
twentyfive_Msmvttl_portafolio(dictionary)
twentyfive_Msmvosd_portafolio(dictionary)
# 创建25个类对象,并且用一个字典进行管理
Portafolio_dict = {}
Portafolio_dict = prepare_Portafolio(0)
print_matrix(Portafolio_dict)
# Portafolio_dict = prepare_Portafolio(2018)
# print_matrix(Portafolio_dict)
| zh | 0.665858 | # -*- coding: utf-8 -*- @Date: Created on Tue Apr 9 01:01:00 2019 @Author: <NAME> @Description: Fama-French 3-factor model 首先直观感受三因子模型的有效性: 按照市值分成五组,感受市值与收益率关系 按照账面市值比分成五组,感受账面市值比与收益率关系 按照市值和账面市值比分成二十五组,感受两个因子与收益率关系 创建组合的类 idnum [组合的代号 00-44(str)] num [组合所包含的数据的条目数量(int)] rank_Msmv [组合所代表的市值属性大小 0最小,4最大(int)] rank_Bktomk [组合所代表的账面市值比属性大小 0最小,4最大(int)] Mretwd [平均考虑现金红利再投资的月个股回报率(float)] Mretnd [平均不考虑现金红利再投资的月个股回报率(float)] Msmvosd [平均月个股流通市值(float)] - 个股的流通股数与月收盘价的乘积 Msmvttl [平均月个股总市值(float)] - 个股的发行总股数与月收盘价的乘积 Bktomk [平均账面市值比(float)] 读取每一个二十五个以csv文件储存的Portafolio :param num: 所需要的数据的年份,如果传入的num为零,则使用所有年份的数据 :return: 为每一个Portafolio创建一个类对象 根据市值大小分成五个Portafolio,并且输出他们的信息 :param Portafolio_dict: 类对象字典 :return: 根据账面市值比大小分成五个 Portafolio,并且输出他们的信息 :param Portafolio_dict: 类对象字典 :return: 根据账面市值比大小和市值分成25个 Portafolio,并且输出他们的Mretwd :param Portafolio_dict: 类对象字典 :return: 根据账面市值比大小和市值分成25个 Portafolio,并且输出他们的Mretnd :param Portafolio_dict: 类对象字典 :return: 根据账面市值比大小和市值分成25个Portafolio,并且输出他们的 Bktomk :param Portafolio_dict: 类对象字典 :return: 根据账面市值比大小和市值分成25个Portafolio,并且输出他们的 Msmvttl :param Portafolio_dict: 类对象字典 :return: 根据账面市值比大小和市值分成25个Portafolio,并且输出他们的 Msmvosd :param Portafolio_dict: 类对象字典 :return: 根据25个Portafolio输出相关的矩阵 :param dictionary: 类对象字典 :return: # 创建25个类对象,并且用一个字典进行管理 # Portafolio_dict = prepare_Portafolio(2018) # print_matrix(Portafolio_dict) | 2.769933 | 3 |
sponge-integration-tests/examples/core/processors_metadata_enhanced.py | mnpas/sponge | 9 | 6627952 | """
Sponge Knowledge Base
Processors enhanced metadata
"""
class EdvancedMetaAction(Action):
def onConfigure(self):
self.withFeatures({"isVisibleMethod":"isVisible"})
def onCall(self, text):
return text.upper()
def isVisible(self, context):
return context == "day"
| """
Sponge Knowledge Base
Processors enhanced metadata
"""
class EdvancedMetaAction(Action):
def onConfigure(self):
self.withFeatures({"isVisibleMethod":"isVisible"})
def onCall(self, text):
return text.upper()
def isVisible(self, context):
return context == "day"
| en | 0.624775 | Sponge Knowledge Base
Processors enhanced metadata | 2.16426 | 2 |
app/okex/client.py | lanzhizhuxia/orange-tuiles | 0 | 6627953 | import requests
import json
from . import consts as c, utils, exceptions
class Client(object):
def __init__(self, api_key, api_secret_key, passphrase, use_server_time=False, test=False, first=False):
self.API_KEY = api_key
self.API_SECRET_KEY = api_secret_key
self.PASSPHRASE = passphrase
self.use_server_time = use_server_time
self.first = first
self.test = test
def _request(self, method, request_path, params, cursor=False):
if method == c.GET:
request_path = request_path + utils.parse_params_to_str(params)
# url
url = c.API_URL + request_path
# 获取本地时间
timestamp = utils.get_timestamp()
# sign & header
if self.use_server_time:
# 获取服务器时间
timestamp = self._get_timestamp()
body = json.dumps(params) if method == c.POST else ""
sign = utils.sign(utils.pre_hash(timestamp, method, request_path, str(body)), self.API_SECRET_KEY)
header = utils.get_header(self.API_KEY, sign, timestamp, self.PASSPHRASE)
if self.test:
header['x-simulated-trading'] = '1'
if self.first:
print("url:", url)
self.first = False
print("url:", url)
# print("headers:", header)
print("body:", body)
# send request
response = None
if method == c.GET:
response = requests.get(url, headers=header)
elif method == c.POST:
response = requests.post(url, data=body, headers=header)
elif method == c.DELETE:
response = requests.delete(url, headers=header)
# exception handle
if not str(response.status_code).startswith('2'):
raise exceptions.OkexAPIException(response)
try:
res_header = response.headers
if cursor:
r = dict()
try:
r['before'] = res_header['OK-BEFORE']
r['after'] = res_header['OK-AFTER']
except:
pass
return response.json(), r
else:
return response.json()
except ValueError:
raise exceptions.OkexRequestException('Invalid Response: %s' % response.text)
def _request_without_params(self, method, request_path):
return self._request(method, request_path, {})
def _request_with_params(self, method, request_path, params, cursor=False):
return self._request(method, request_path, params, cursor)
def _get_timestamp(self):
url = c.API_URL + c.SERVER_TIMESTAMP_URL
response = requests.get(url)
if response.status_code == 200:
return response.json()['iso']
else:
return ""
| import requests
import json
from . import consts as c, utils, exceptions
class Client(object):
def __init__(self, api_key, api_secret_key, passphrase, use_server_time=False, test=False, first=False):
self.API_KEY = api_key
self.API_SECRET_KEY = api_secret_key
self.PASSPHRASE = passphrase
self.use_server_time = use_server_time
self.first = first
self.test = test
def _request(self, method, request_path, params, cursor=False):
if method == c.GET:
request_path = request_path + utils.parse_params_to_str(params)
# url
url = c.API_URL + request_path
# 获取本地时间
timestamp = utils.get_timestamp()
# sign & header
if self.use_server_time:
# 获取服务器时间
timestamp = self._get_timestamp()
body = json.dumps(params) if method == c.POST else ""
sign = utils.sign(utils.pre_hash(timestamp, method, request_path, str(body)), self.API_SECRET_KEY)
header = utils.get_header(self.API_KEY, sign, timestamp, self.PASSPHRASE)
if self.test:
header['x-simulated-trading'] = '1'
if self.first:
print("url:", url)
self.first = False
print("url:", url)
# print("headers:", header)
print("body:", body)
# send request
response = None
if method == c.GET:
response = requests.get(url, headers=header)
elif method == c.POST:
response = requests.post(url, data=body, headers=header)
elif method == c.DELETE:
response = requests.delete(url, headers=header)
# exception handle
if not str(response.status_code).startswith('2'):
raise exceptions.OkexAPIException(response)
try:
res_header = response.headers
if cursor:
r = dict()
try:
r['before'] = res_header['OK-BEFORE']
r['after'] = res_header['OK-AFTER']
except:
pass
return response.json(), r
else:
return response.json()
except ValueError:
raise exceptions.OkexRequestException('Invalid Response: %s' % response.text)
def _request_without_params(self, method, request_path):
return self._request(method, request_path, {})
def _request_with_params(self, method, request_path, params, cursor=False):
return self._request(method, request_path, params, cursor)
def _get_timestamp(self):
url = c.API_URL + c.SERVER_TIMESTAMP_URL
response = requests.get(url)
if response.status_code == 200:
return response.json()['iso']
else:
return ""
| zh | 0.160722 | # url # 获取本地时间 # sign & header # 获取服务器时间 # print("headers:", header) # send request # exception handle | 2.853435 | 3 |
src/Display/avt_window.py | schmouk/ArcheryVideoTraining | 0 | 6627954 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (c) 2021 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
#=============================================================================
import cv2
import numpy as np
from typing import ForwardRef, Tuple
from threading import Lock
from src.App.avt_config import AVTConfig
from src.GUIItems.Cursor.cursor import Cursor_NORMAL
from src.Utils.rgb_color import RGBColor
from .view import View
from src.GUIItems.viewable import Viewable
#=============================================================================
AVTWindowRef = ForwardRef( "AVTWindow" )
#=============================================================================
class AVTWindow( Viewable ):
"""The base class for all windows in Archery Video Training application.
"""
#-------------------------------------------------------------------------
def __init__(self, name : str = None,
title : str = None,
width : int = None,
height : int = None,
bg_color: RGBColor = AVTConfig.DEFAULT_BACKGROUND,
*,
full_screen: bool = False) -> None:
'''Constructor.
Args:
name: str
The name for this window. This is used by OpenCV
for referencing windows. If not set, a default and
unique one will be created. Notice: the default
naming is thread safe.
title: str
The title of this window, as display in the top
bar of it.
width: int
The wished width for this window when displayed.
Is not set, will be displayed according to the
width of its content. Ignored when 'full_screen'
is set to True. Defaults to not set.
height: int
The wished height for this window when displayed.
Is not set, will be displayed according to the
height of its content. Ignored when 'full_screen'
is set to True. Defaults to not set.
bg_color: RGBColor
A reference to he background solid color for this
window. Defaults to some dark gray.
full_screen: bool
Set this to True to get a full screen displayed
window. No title bar will then be displayed. This
takes precedence over 'width' and 'height' when
set to True. Defaults to False (i.e. not full
screen). This argument must be named at call time.
Raises:
ValueError: width and height must be both set or both
None. If not, a ValueError exception is raised.
Furthermore, this exception is raised when width
or size are negative or zero.
'''
self.lock = Lock()
self.name = self._get_default_name() if name is None else str(name)
self.bg_color = bg_color
self.full_screen = full_screen
self.fixed_size = True
if full_screen:
cv2.namedWindow( self.name, cv2.WINDOW_FULLSCREEN )
elif width is None:
if height is not None:
raise ValueError( 'args width and height must be both None or both set.' )
cv2.namedWindow( self.name, cv2.WINDOW_AUTOSIZE | cv2.WINDOW_KEEPRATIO | cv2.WINDOW_GUI_EXPANDED )
self.fixed_size = False
else:
if width is None:
raise ValueError( 'args width and height must be both None or both set.' )
if width <= 0 or height <= 0:
raise ValueError ( f"width and height ({width}, {height}) must be both greater than 0" )
cv2.namedWindow( self.name, cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO | cv2.WINDOW_GUI_EXPANDED )
cv2.resizeWindow( self.name, width, height )
Cursor_NORMAL.activate()
self.set_title( f"AVT Window # {self.__WINDOWS_COUNT}" if title is None else title )
width, height = self.get_size()
super().__init__( 0, 0, width, height, bg_color )
#-------------------------------------------------------------------------
def draw(self, hit_delay_ms: int = 1) -> int:
'''Draws a content into this window.
Notice: the content will automatically be resized to
the window current size if this window has
been created with a specified size.
Args:
hit_delay_ms: int
A delay, expressed in milliseconds, used for
the scanning of keyboards hits. If any key is
hit within this delay, its integer code is
immediately returned as the result of this
method, otherwise -1 is returned. If delay is
0 or negative, the application is stopped
until a key is hit. Defaults to 1 ms, which
is the shortest delay that is available before
completing this method.
Returns:
The integer code of the key that was hit while
displaying this content, or -1 if no key was
hit after expressed delay.
'''
with self.lock:
if not self.fixed_size:
#-- the window size adapts itself to the content size
cv2.imshow( self.name, self.content )
else:
#-- the content size adapts itself to the window size
content_height, content_width = self.content.shape[:2]
window_width, window_height = self.get_size()
height_ratio = window_height / content_height
width_ratio = window_width / content_width
ratio = height_ratio if height_ratio <= width_ratio else width_ratio
if ratio != 1.0 and ratio > 0.0:
window_content = np.zeros( (window_height, window_width, 3), np.uint8 )
new_content = cv2.resize( self.content, None,
fx=ratio, fy=ratio,
interpolation=cv2.INTER_LINEAR )
new_height, new_width = new_content.shape[:2]
if new_width > window_width:
new_width = window_width
if new_height > window_height:
new_height = window_height
x = (window_width - new_width) // 2
y = (window_height - new_height) // 2
window_content[ y:y+new_height,
x:x+new_width, : ] = new_content[ :new_height, :new_width, : ]
cv2.imshow( self.name, window_content )
else:
cv2.imshow( self.name, self.content )
return cv2.waitKey( hit_delay_ms )
#-------------------------------------------------------------------------
def get_pos(self) -> Tuple[int, int]:
'''Returns the current (x, y) position of this window, expressed in pixels.
'''
return cv2.getWindowImageRect( self.name )[:2]
#-------------------------------------------------------------------------
def get_rect(self) -> Tuple[int, int, int, int]:
'''Returns the current rectangle (x, y, width, height) of this window, expressed in pixels.
'''
return cv2.getWindowImageRect( self.name )
#-------------------------------------------------------------------------
def get_size(self) -> Tuple[int, int]:
'''Returns the current (width, height) of this window, expressed in pixels.
'''
return cv2.getWindowImageRect( self.name )[2:]
#-------------------------------------------------------------------------
def insert_view_content(self, view: View) -> None:
'''Inserts the content of a view in this window content.
Args:
view: View
A reference to the view from which the content
is to be inserted in this window content.
'''
with self.lock:
content_height, content_width = self.content.shape[:2]
width = min( view.width , content_width - view.x )
height = min( view.height, content_height - view.y )
try:
self.content[ view.y:view.y+height,
view.x:view.x+width, : ] = view.content[ :height, :width, : ]
except:
pass
#-------------------------------------------------------------------------
def set_title(self, title: str) -> None:
'''Sets the title of this window as shown in its top bar.
Args:
title: str
The text for this window title.
'''
cv2.setWindowTitle( self.name, str(title) )
#-------------------------------------------------------------------------
def _get_default_name(self) -> str:
'''Returns a unique default name for this window.
Notice: this is a private method which should not
have to be called in inheriting classes.
It is thread safe.
'''
with self.lock:
name = f"AVT-Window-{self.__WINDOWS_COUNT:03d}"
self.__WINDOWS_COUNT += 1
return name
#-------------------------------------------------------------------------
# Class data
__WINDOWS_COUNT = 0
#===== end of src.Display.avt_window =====#
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (c) 2021 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
#=============================================================================
import cv2
import numpy as np
from typing import ForwardRef, Tuple
from threading import Lock
from src.App.avt_config import AVTConfig
from src.GUIItems.Cursor.cursor import Cursor_NORMAL
from src.Utils.rgb_color import RGBColor
from .view import View
from src.GUIItems.viewable import Viewable
#=============================================================================
AVTWindowRef = ForwardRef( "AVTWindow" )
#=============================================================================
class AVTWindow( Viewable ):
"""The base class for all windows in Archery Video Training application.
"""
#-------------------------------------------------------------------------
def __init__(self, name : str = None,
title : str = None,
width : int = None,
height : int = None,
bg_color: RGBColor = AVTConfig.DEFAULT_BACKGROUND,
*,
full_screen: bool = False) -> None:
'''Constructor.
Args:
name: str
The name for this window. This is used by OpenCV
for referencing windows. If not set, a default and
unique one will be created. Notice: the default
naming is thread safe.
title: str
The title of this window, as display in the top
bar of it.
width: int
The wished width for this window when displayed.
Is not set, will be displayed according to the
width of its content. Ignored when 'full_screen'
is set to True. Defaults to not set.
height: int
The wished height for this window when displayed.
Is not set, will be displayed according to the
height of its content. Ignored when 'full_screen'
is set to True. Defaults to not set.
bg_color: RGBColor
A reference to he background solid color for this
window. Defaults to some dark gray.
full_screen: bool
Set this to True to get a full screen displayed
window. No title bar will then be displayed. This
takes precedence over 'width' and 'height' when
set to True. Defaults to False (i.e. not full
screen). This argument must be named at call time.
Raises:
ValueError: width and height must be both set or both
None. If not, a ValueError exception is raised.
Furthermore, this exception is raised when width
or size are negative or zero.
'''
self.lock = Lock()
self.name = self._get_default_name() if name is None else str(name)
self.bg_color = bg_color
self.full_screen = full_screen
self.fixed_size = True
if full_screen:
cv2.namedWindow( self.name, cv2.WINDOW_FULLSCREEN )
elif width is None:
if height is not None:
raise ValueError( 'args width and height must be both None or both set.' )
cv2.namedWindow( self.name, cv2.WINDOW_AUTOSIZE | cv2.WINDOW_KEEPRATIO | cv2.WINDOW_GUI_EXPANDED )
self.fixed_size = False
else:
if width is None:
raise ValueError( 'args width and height must be both None or both set.' )
if width <= 0 or height <= 0:
raise ValueError ( f"width and height ({width}, {height}) must be both greater than 0" )
cv2.namedWindow( self.name, cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO | cv2.WINDOW_GUI_EXPANDED )
cv2.resizeWindow( self.name, width, height )
Cursor_NORMAL.activate()
self.set_title( f"AVT Window # {self.__WINDOWS_COUNT}" if title is None else title )
width, height = self.get_size()
super().__init__( 0, 0, width, height, bg_color )
#-------------------------------------------------------------------------
def draw(self, hit_delay_ms: int = 1) -> int:
'''Draws a content into this window.
Notice: the content will automatically be resized to
the window current size if this window has
been created with a specified size.
Args:
hit_delay_ms: int
A delay, expressed in milliseconds, used for
the scanning of keyboards hits. If any key is
hit within this delay, its integer code is
immediately returned as the result of this
method, otherwise -1 is returned. If delay is
0 or negative, the application is stopped
until a key is hit. Defaults to 1 ms, which
is the shortest delay that is available before
completing this method.
Returns:
The integer code of the key that was hit while
displaying this content, or -1 if no key was
hit after expressed delay.
'''
with self.lock:
if not self.fixed_size:
#-- the window size adapts itself to the content size
cv2.imshow( self.name, self.content )
else:
#-- the content size adapts itself to the window size
content_height, content_width = self.content.shape[:2]
window_width, window_height = self.get_size()
height_ratio = window_height / content_height
width_ratio = window_width / content_width
ratio = height_ratio if height_ratio <= width_ratio else width_ratio
if ratio != 1.0 and ratio > 0.0:
window_content = np.zeros( (window_height, window_width, 3), np.uint8 )
new_content = cv2.resize( self.content, None,
fx=ratio, fy=ratio,
interpolation=cv2.INTER_LINEAR )
new_height, new_width = new_content.shape[:2]
if new_width > window_width:
new_width = window_width
if new_height > window_height:
new_height = window_height
x = (window_width - new_width) // 2
y = (window_height - new_height) // 2
window_content[ y:y+new_height,
x:x+new_width, : ] = new_content[ :new_height, :new_width, : ]
cv2.imshow( self.name, window_content )
else:
cv2.imshow( self.name, self.content )
return cv2.waitKey( hit_delay_ms )
#-------------------------------------------------------------------------
def get_pos(self) -> Tuple[int, int]:
'''Returns the current (x, y) position of this window, expressed in pixels.
'''
return cv2.getWindowImageRect( self.name )[:2]
#-------------------------------------------------------------------------
def get_rect(self) -> Tuple[int, int, int, int]:
'''Returns the current rectangle (x, y, width, height) of this window, expressed in pixels.
'''
return cv2.getWindowImageRect( self.name )
#-------------------------------------------------------------------------
def get_size(self) -> Tuple[int, int]:
'''Returns the current (width, height) of this window, expressed in pixels.
'''
return cv2.getWindowImageRect( self.name )[2:]
#-------------------------------------------------------------------------
def insert_view_content(self, view: View) -> None:
'''Inserts the content of a view in this window content.
Args:
view: View
A reference to the view from which the content
is to be inserted in this window content.
'''
with self.lock:
content_height, content_width = self.content.shape[:2]
width = min( view.width , content_width - view.x )
height = min( view.height, content_height - view.y )
try:
self.content[ view.y:view.y+height,
view.x:view.x+width, : ] = view.content[ :height, :width, : ]
except:
pass
#-------------------------------------------------------------------------
def set_title(self, title: str) -> None:
'''Sets the title of this window as shown in its top bar.
Args:
title: str
The text for this window title.
'''
cv2.setWindowTitle( self.name, str(title) )
#-------------------------------------------------------------------------
def _get_default_name(self) -> str:
'''Returns a unique default name for this window.
Notice: this is a private method which should not
have to be called in inheriting classes.
It is thread safe.
'''
with self.lock:
name = f"AVT-Window-{self.__WINDOWS_COUNT:03d}"
self.__WINDOWS_COUNT += 1
return name
#-------------------------------------------------------------------------
# Class data
__WINDOWS_COUNT = 0
#===== end of src.Display.avt_window =====#
| en | 0.741395 | #!/usr/bin/env python # -*- coding: utf-8 -*- Copyright (c) 2021 <NAME> 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. #============================================================================= #============================================================================= #============================================================================= The base class for all windows in Archery Video Training application. #------------------------------------------------------------------------- Constructor. Args: name: str The name for this window. This is used by OpenCV for referencing windows. If not set, a default and unique one will be created. Notice: the default naming is thread safe. title: str The title of this window, as display in the top bar of it. width: int The wished width for this window when displayed. Is not set, will be displayed according to the width of its content. Ignored when 'full_screen' is set to True. Defaults to not set. height: int The wished height for this window when displayed. Is not set, will be displayed according to the height of its content. Ignored when 'full_screen' is set to True. Defaults to not set. bg_color: RGBColor A reference to he background solid color for this window. Defaults to some dark gray. full_screen: bool Set this to True to get a full screen displayed window. No title bar will then be displayed. This takes precedence over 'width' and 'height' when set to True. Defaults to False (i.e. not full screen). This argument must be named at call time. Raises: ValueError: width and height must be both set or both None. If not, a ValueError exception is raised. Furthermore, this exception is raised when width or size are negative or zero. # {self.__WINDOWS_COUNT}" if title is None else title ) #------------------------------------------------------------------------- Draws a content into this window. Notice: the content will automatically be resized to the window current size if this window has been created with a specified size. Args: hit_delay_ms: int A delay, expressed in milliseconds, used for the scanning of keyboards hits. If any key is hit within this delay, its integer code is immediately returned as the result of this method, otherwise -1 is returned. If delay is 0 or negative, the application is stopped until a key is hit. Defaults to 1 ms, which is the shortest delay that is available before completing this method. Returns: The integer code of the key that was hit while displaying this content, or -1 if no key was hit after expressed delay. #-- the window size adapts itself to the content size #-- the content size adapts itself to the window size #------------------------------------------------------------------------- Returns the current (x, y) position of this window, expressed in pixels. #------------------------------------------------------------------------- Returns the current rectangle (x, y, width, height) of this window, expressed in pixels. #------------------------------------------------------------------------- Returns the current (width, height) of this window, expressed in pixels. #------------------------------------------------------------------------- Inserts the content of a view in this window content. Args: view: View A reference to the view from which the content is to be inserted in this window content. #------------------------------------------------------------------------- Sets the title of this window as shown in its top bar. Args: title: str The text for this window title. #------------------------------------------------------------------------- Returns a unique default name for this window. Notice: this is a private method which should not have to be called in inheriting classes. It is thread safe. #------------------------------------------------------------------------- # Class data #===== end of src.Display.avt_window =====# | 1.512177 | 2 |
SVM.py | hishamzargar/test | 0 | 6627955 | import pickle
import matplotlib.pyplot as plt
from sklearn.svm import SVC, LinearSVC
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import classification_report, confusion_matrix
import numpy as np
import scikitplot as skplt
# Opening the files about data
X = pickle.load(open("X_train.pickle", "rb"))
y_train = pickle.load(open("y_train.pickle", "rb"))
Y = pickle.load(open("X_test.pickle","rb"))
y_test = pickle.load(open("y_test.pickle","rb"))
# normalizing data (a pixel goes from 0 to 255) for faster recognition
X = X/255.0
Y = Y/255.0
#reshaping the numpy array from 4D to 2D to fit in SVM classifier
X_train = np.reshape(X, [128,784])
X_test = np.reshape(Y,[40,784])
#training the data
svclassifier = SVC(kernel='linear')
svclassifier.fit(X_train, y_train)
#predicting the data
y_pred = svclassifier.predict(X_test)
#output metrics
print(confusion_matrix(y_test,y_pred))
print(classification_report(y_test,y_pred))
#Ploting the confusion matrix with scikitplot library
skplt.metrics.plot_confusion_matrix(y_test,y_pred)
plt.show()
| import pickle
import matplotlib.pyplot as plt
from sklearn.svm import SVC, LinearSVC
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import classification_report, confusion_matrix
import numpy as np
import scikitplot as skplt
# Opening the files about data
X = pickle.load(open("X_train.pickle", "rb"))
y_train = pickle.load(open("y_train.pickle", "rb"))
Y = pickle.load(open("X_test.pickle","rb"))
y_test = pickle.load(open("y_test.pickle","rb"))
# normalizing data (a pixel goes from 0 to 255) for faster recognition
X = X/255.0
Y = Y/255.0
#reshaping the numpy array from 4D to 2D to fit in SVM classifier
X_train = np.reshape(X, [128,784])
X_test = np.reshape(Y,[40,784])
#training the data
svclassifier = SVC(kernel='linear')
svclassifier.fit(X_train, y_train)
#predicting the data
y_pred = svclassifier.predict(X_test)
#output metrics
print(confusion_matrix(y_test,y_pred))
print(classification_report(y_test,y_pred))
#Ploting the confusion matrix with scikitplot library
skplt.metrics.plot_confusion_matrix(y_test,y_pred)
plt.show()
| en | 0.701174 | # Opening the files about data # normalizing data (a pixel goes from 0 to 255) for faster recognition #reshaping the numpy array from 4D to 2D to fit in SVM classifier #training the data #predicting the data #output metrics #Ploting the confusion matrix with scikitplot library | 3.196096 | 3 |
tests/2019/test_24_planet_of_discord.py | wimglenn/advent-of-code-wim | 20 | 6627956 | <filename>tests/2019/test_24_planet_of_discord.py
from aoc_wim.aoc2019 import q24
test_bugs = """\
....#
#..#.
#..##
..#..
#....
"""
def test_example_b():
result = q24.part_b(test_bugs, t=10)
assert result == 99
| <filename>tests/2019/test_24_planet_of_discord.py
from aoc_wim.aoc2019 import q24
test_bugs = """\
....#
#..#.
#..##
..#..
#....
"""
def test_example_b():
result = q24.part_b(test_bugs, t=10)
assert result == 99
| en | 0.312578 | \ ....# #..#. #..## ..#.. #.... | 1.52939 | 2 |
mpa/modules/datasets/task_adapt_dataset.py | openvinotoolkit/model_preparation_algorithm | 0 | 6627957 | # Copyright (C) 2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
from mmdet.datasets import PIPELINES, DATASETS, build_dataset
# import torch
import numpy as np
from mpa.modules.utils.task_adapt import map_class_names, map_cat_and_cls_as_order
@DATASETS.register_module()
class TaskAdaptEvalDataset(object):
"""Dataset wrapper for task-adative evaluation.
"""
def __init__(self, model_classes, **kwargs):
dataset_cfg = kwargs.copy()
org_type = dataset_cfg.pop('org_type')
dataset_cfg['type'] = org_type
self.dataset = build_dataset(dataset_cfg)
self.model_classes = model_classes
self.CLASSES = self.dataset.CLASSES
self.data2model = map_class_names(self.CLASSES, self.model_classes)
if org_type == 'CocoDataset':
self.dataset.cat2label, self.dataset.cat_ids = map_cat_and_cls_as_order(
self.CLASSES, self.dataset.coco.cats)
def __getitem__(self, idx):
return self.dataset[idx]
def __len__(self):
return len(self.dataset)
def evaluate(self, results, **kwargs):
# Filter & reorder detection results
adapt_results = []
for result in results: # for each image
adapt_result = []
for model_class_index in self.data2model: # for each class
# Gather per-class results according to index mapping
if model_class_index >= 0:
adapt_result.append(result[model_class_index])
else:
adapt_result.append(np.empty([0, 5]))
adapt_results.append(adapt_result)
# Call evaluation w/ org arguments
return self.dataset.evaluate(adapt_results, **kwargs)
@PIPELINES.register_module()
class AdaptClassLabels(object):
"""Data processor for task-adative annotation loading.
"""
def __init__(self, src_classes, dst_classes):
self.src2dst = map_class_names(src_classes, dst_classes)
print('AdaptClassLabels')
print('src_classes', src_classes)
print('dst_classes', dst_classes)
print('src2dst', self.src2dst)
def __call__(self, data):
src_labels = data['gt_labels']
dst_labels = []
for src_label in src_labels:
dst_labels.append(self.src2dst[src_label])
data['gt_labels'] = np.array(dst_labels)
return data
| # Copyright (C) 2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
from mmdet.datasets import PIPELINES, DATASETS, build_dataset
# import torch
import numpy as np
from mpa.modules.utils.task_adapt import map_class_names, map_cat_and_cls_as_order
@DATASETS.register_module()
class TaskAdaptEvalDataset(object):
"""Dataset wrapper for task-adative evaluation.
"""
def __init__(self, model_classes, **kwargs):
dataset_cfg = kwargs.copy()
org_type = dataset_cfg.pop('org_type')
dataset_cfg['type'] = org_type
self.dataset = build_dataset(dataset_cfg)
self.model_classes = model_classes
self.CLASSES = self.dataset.CLASSES
self.data2model = map_class_names(self.CLASSES, self.model_classes)
if org_type == 'CocoDataset':
self.dataset.cat2label, self.dataset.cat_ids = map_cat_and_cls_as_order(
self.CLASSES, self.dataset.coco.cats)
def __getitem__(self, idx):
return self.dataset[idx]
def __len__(self):
return len(self.dataset)
def evaluate(self, results, **kwargs):
# Filter & reorder detection results
adapt_results = []
for result in results: # for each image
adapt_result = []
for model_class_index in self.data2model: # for each class
# Gather per-class results according to index mapping
if model_class_index >= 0:
adapt_result.append(result[model_class_index])
else:
adapt_result.append(np.empty([0, 5]))
adapt_results.append(adapt_result)
# Call evaluation w/ org arguments
return self.dataset.evaluate(adapt_results, **kwargs)
@PIPELINES.register_module()
class AdaptClassLabels(object):
"""Data processor for task-adative annotation loading.
"""
def __init__(self, src_classes, dst_classes):
self.src2dst = map_class_names(src_classes, dst_classes)
print('AdaptClassLabels')
print('src_classes', src_classes)
print('dst_classes', dst_classes)
print('src2dst', self.src2dst)
def __call__(self, data):
src_labels = data['gt_labels']
dst_labels = []
for src_label in src_labels:
dst_labels.append(self.src2dst[src_label])
data['gt_labels'] = np.array(dst_labels)
return data
| en | 0.63818 | # Copyright (C) 2022 Intel Corporation # SPDX-License-Identifier: Apache-2.0 # # import torch Dataset wrapper for task-adative evaluation. # Filter & reorder detection results # for each image # for each class # Gather per-class results according to index mapping # Call evaluation w/ org arguments Data processor for task-adative annotation loading. | 2.05399 | 2 |
goto2_timing.py | ArtUshak/gotoHackBlitz | 0 | 6627958 | <reponame>ArtUshak/gotoHackBlitz
import time
events = []
steps = []
def register_event_data(user_id, action, step_id, time):
global events
events += [{'user_id':user_id, 'action':action, 'step_id':step_id, 'time':time}]
def register_step_data(step_id, module_position, lesson_position, step_position):
global steps
steps += [{'step_id':step_id, 'module_position':module_position, 'lesson_position':lesson_position, 'step_position':step_position, 'visitors':{}, 'revisitors':[]}]
def get_step_pos(step_id):
for i in range(len(steps)):
if steps[i]['step_id'] == step_id:
return i
def process_event(event):
user_id = event['user_id']
action = event['action']
step_id = event['step_id']
time = event['time']
step_pos = get_step_pos(step_id)
if not user_id in steps[step_pos]['visitors']:
steps[step_pos]['visitors'][user_id] = {'user_id':user_id, 'first_time':time, 'last_time':time}
else:
if step_pos+1 < len(steps):
if not user_id in steps[step_pos]['revisitors']:
if user_id in steps[step_pos+1]['visitors']:
if steps[step_pos]['visitors'][user_id]['first_time'] < steps[step_pos+1]['visitors'][user_id]['last_time']:
steps[step_pos]['revisitors'] += [user_id]
steps[step_pos]['visitors'][user_id]['last_time'] = time
t1 = time.perf_counter()
with open('course-217-structure.csv') as file_steps:
for line in file_steps:
line = line.strip()
data = line.split(',')
if data[0] == 'course_id':
continue
register_step_data(int(data[5]), int(data[2]), int(data[4]), int(data[6]))
t2 = time.perf_counter()
with open('course-217-events.csv') as file_events:
for line in file_events:
line = line.strip()
data = line.split(',')
if data[0] == 'user_id':
continue
register_event_data(int(data[0]), data[1], int(data[2]), int(data[3]))
t3 = time.perf_counter()
steps.sort(key=lambda step: [step['module_position'], step['lesson_position'], step['step_position']])
events.sort(key=lambda event: event['time'])
t4 = time.perf_counter()
for event in events:
process_event(event)
t5 = time.perf_counter()
for step in steps:
step['revisit_k'] = len(step['revisitors']) / len(step['visitors'])
result_steps = sorted(steps, key=lambda step: step['revisit_k'])[::-1]
t6 = time.perf_counter()
print(t2 - t1)
print(t3 - t2)
print(t4 - t3)
print(t5 - t4)
print(t6 - t5)
for result_step in result_steps[0:9]:
print(result_step['step_id'], end=',')
print(result_steps[9]['step_id'])
| import time
events = []
steps = []
def register_event_data(user_id, action, step_id, time):
global events
events += [{'user_id':user_id, 'action':action, 'step_id':step_id, 'time':time}]
def register_step_data(step_id, module_position, lesson_position, step_position):
global steps
steps += [{'step_id':step_id, 'module_position':module_position, 'lesson_position':lesson_position, 'step_position':step_position, 'visitors':{}, 'revisitors':[]}]
def get_step_pos(step_id):
for i in range(len(steps)):
if steps[i]['step_id'] == step_id:
return i
def process_event(event):
user_id = event['user_id']
action = event['action']
step_id = event['step_id']
time = event['time']
step_pos = get_step_pos(step_id)
if not user_id in steps[step_pos]['visitors']:
steps[step_pos]['visitors'][user_id] = {'user_id':user_id, 'first_time':time, 'last_time':time}
else:
if step_pos+1 < len(steps):
if not user_id in steps[step_pos]['revisitors']:
if user_id in steps[step_pos+1]['visitors']:
if steps[step_pos]['visitors'][user_id]['first_time'] < steps[step_pos+1]['visitors'][user_id]['last_time']:
steps[step_pos]['revisitors'] += [user_id]
steps[step_pos]['visitors'][user_id]['last_time'] = time
t1 = time.perf_counter()
with open('course-217-structure.csv') as file_steps:
for line in file_steps:
line = line.strip()
data = line.split(',')
if data[0] == 'course_id':
continue
register_step_data(int(data[5]), int(data[2]), int(data[4]), int(data[6]))
t2 = time.perf_counter()
with open('course-217-events.csv') as file_events:
for line in file_events:
line = line.strip()
data = line.split(',')
if data[0] == 'user_id':
continue
register_event_data(int(data[0]), data[1], int(data[2]), int(data[3]))
t3 = time.perf_counter()
steps.sort(key=lambda step: [step['module_position'], step['lesson_position'], step['step_position']])
events.sort(key=lambda event: event['time'])
t4 = time.perf_counter()
for event in events:
process_event(event)
t5 = time.perf_counter()
for step in steps:
step['revisit_k'] = len(step['revisitors']) / len(step['visitors'])
result_steps = sorted(steps, key=lambda step: step['revisit_k'])[::-1]
t6 = time.perf_counter()
print(t2 - t1)
print(t3 - t2)
print(t4 - t3)
print(t5 - t4)
print(t6 - t5)
for result_step in result_steps[0:9]:
print(result_step['step_id'], end=',')
print(result_steps[9]['step_id']) | none | 1 | 2.649255 | 3 | |
treecorr/ggcorrelation.py | zchvsre/TreeCorr | 0 | 6627959 | <reponame>zchvsre/TreeCorr<filename>treecorr/ggcorrelation.py<gh_stars>0
# Copyright (c) 2003-2019 by <NAME>
#
# TreeCorr is free software: redistribution and use in source and binary forms,
# with or without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions, and the disclaimer given in the accompanying LICENSE
# file.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the disclaimer given in the documentation
# and/or other materials provided with the distribution.
"""
.. module:: ggcorrelation
"""
import treecorr
import numpy as np
class GGCorrelation(treecorr.BinnedCorr2):
"""This class handles the calculation and storage of a 2-point shear-shear correlation
function.
Ojects of this class holds the following attributes:
Attributes:
nbins: The number of bins in logr
bin_size: The size of the bins in logr
min_sep: The minimum separation being considered
max_sep: The maximum separation being considered
In addition, the following attributes are numpy arrays of length (nbins):
Attributes:
logr: The nominal center of the bin in log(r) (the natural logarithm of r).
rnom: The nominal center of the bin converted to regular distance.
i.e. r = exp(logr).
meanr: The (weighted) mean value of r for the pairs in each bin.
If there are no pairs in a bin, then exp(logr) will be used instead.
meanlogr: The (weighted) mean value of log(r) for the pairs in each bin.
If there are no pairs in a bin, then logr will be used instead.
xip: The correlation function, :math:`\\xi_+(r)`.
xim: The correlation funciton, :math:`\\xi_-(r)`.
xip_im: The imaginary part of :math:`\\xi_+(r)`.
xim_im: The imaginary part of :math:`\\xi_-(r)`.
varxip: The variance of xip, only including the shape noise propagated into
the final correlation. This does not include sample variance, so it
is always an underestimate of the actual variance.
varxim: The variance of xim, only including the shape noise propagated into
the final correlation. This does not include sample variance, so it
is always an underestimate of the actual variance.
weight: The total weight in each bin.
npairs: The number of pairs going into each bin.
If **sep_units** are given (either in the config dict or as a named kwarg) then the distances
will all be in these units. Note however, that if you separate out the steps of the
`process` command and use `process_auto` and/or `process_cross`, then the
units will not be applied to **meanr** or **meanlogr** until the `finalize` function is
called.
The typical usage pattern is as follows:
>>> gg = treecorr.GGCorrelation(config)
>>> gg.process(cat) # For auto-correlation.
>>> gg.process(cat1,cat2) # For cross-correlation.
>>> gg.write(file_name) # Write out to a file.
>>> xip = gg.xip # Or access the correlation function directly.
Parameters:
config (dict): A configuration dict that can be used to pass in kwargs if desired.
This dict is allowed to have addition entries in addition to those listed
in `BinnedCorr2`, which are ignored here. (default: None)
logger: If desired, a logger object for logging. (default: None, in which case
one will be built according to the config dict's verbose level.)
See the documentation for `BinnedCorr2` for the list of other allowed kwargs,
which may be passed either directly or in the config dict.
"""
def __init__(self, config=None, logger=None, **kwargs):
treecorr.BinnedCorr2.__init__(self, config, logger, **kwargs)
self._d1 = 3 # GData
self._d2 = 3 # GData
self.xip = np.zeros_like(self.rnom, dtype=float)
self.xim = np.zeros_like(self.rnom, dtype=float)
self.xip_im = np.zeros_like(self.rnom, dtype=float)
self.xim_im = np.zeros_like(self.rnom, dtype=float)
self.varxip = np.zeros_like(self.rnom, dtype=float)
self.varxim = np.zeros_like(self.rnom, dtype=float)
self.meanr = np.zeros_like(self.rnom, dtype=float)
self.meanlogr = np.zeros_like(self.rnom, dtype=float)
self.weight = np.zeros_like(self.rnom, dtype=float)
self.npairs = np.zeros_like(self.rnom, dtype=float)
self._build_corr()
self.logger.debug('Finished building GGCorr')
def _build_corr(self):
from treecorr.util import double_ptr as dp
self.corr = treecorr._lib.BuildCorr2(
self._d1, self._d2, self._bintype,
self._min_sep,self._max_sep,self._nbins,self._bin_size,self.b,
self.min_rpar, self.max_rpar, self.xperiod, self.yperiod, self.zperiod,
dp(self.xip),dp(self.xip_im),dp(self.xim),dp(self.xim_im),
dp(self.meanr),dp(self.meanlogr),dp(self.weight),dp(self.npairs))
def __del__(self):
# Using memory allocated from the C layer means we have to explicitly deallocate it
# rather than being able to rely on the Python memory manager.
# In case __init__ failed to get that far
if hasattr(self,'corr'): # pragma: no branch
if not treecorr._ffi._lock.locked(): # pragma: no branch
treecorr._lib.DestroyCorr2(self.corr, self._d1, self._d2, self._bintype)
def __eq__(self, other):
"""Return whether two GGCorrelations are equal"""
return (isinstance(other, GGCorrelation) and
self.nbins == other.nbins and
self.bin_size == other.bin_size and
self.min_sep == other.min_sep and
self.max_sep == other.max_sep and
self.sep_units == other.sep_units and
self.coords == other.coords and
self.bin_type == other.bin_type and
self.bin_slop == other.bin_slop and
self.min_rpar == other.min_rpar and
self.max_rpar == other.max_rpar and
self.xperiod == other.xperiod and
self.yperiod == other.yperiod and
self.zperiod == other.zperiod and
np.array_equal(self.meanr, other.meanr) and
np.array_equal(self.meanlogr, other.meanlogr) and
np.array_equal(self.xip, other.xip) and
np.array_equal(self.xim, other.xim) and
np.array_equal(self.xip_im, other.xip_im) and
np.array_equal(self.xim_im, other.xim_im) and
np.array_equal(self.varxip, other.varxip) and
np.array_equal(self.varxim, other.varxim) and
np.array_equal(self.weight, other.weight) and
np.array_equal(self.npairs, other.npairs))
def copy(self):
"""Make a copy"""
import copy
return copy.deepcopy(self)
def __getstate__(self):
d = self.__dict__.copy()
del d['corr']
del d['logger'] # Oh well. This is just lost in the copy. Can't be pickled.
return d
def __setstate__(self, d):
self.__dict__ = d
self._build_corr()
self.logger = treecorr.config.setup_logger(
treecorr.config.get(self.config,'verbose',int,1),
self.config.get('log_file',None))
def __repr__(self):
return 'GGCorrelation(config=%r)'%self.config
def process_auto(self, cat, metric=None, num_threads=None):
"""Process a single catalog, accumulating the auto-correlation.
This accumulates the weighted sums into the bins, but does not finalize
the calculation by dividing by the total weight at the end. After
calling this function as often as desired, the `finalize` command will
finish the calculation.
Parameters:
cat (Catalog): The catalog to process
metric (str): Which metric to use. See `Metrics` for details.
(default: 'Euclidean'; this value can also be given in the
constructor in the config dict.)
num_threads (int): How many OpenMP threads to use during the calculation.
(default: use the number of cpu cores; this value can also be given
in the constructor in the config dict.)
"""
if cat.name == '':
self.logger.info('Starting process GG auto-correlations')
else:
self.logger.info('Starting process GG auto-correlations for cat %s.',cat.name)
self._set_metric(metric, cat.coords)
self._set_num_threads(num_threads)
min_size, max_size = self._get_minmax_size()
field = cat.getGField(min_size, max_size, self.split_method,
bool(self.brute), self.min_top, self.max_top, self.coords)
self.logger.info('Starting %d jobs.',field.nTopLevelNodes)
treecorr._lib.ProcessAuto2(self.corr, field.data, self.output_dots,
field._d, self._coords, self._bintype, self._metric)
def process_cross(self, cat1, cat2, metric=None, num_threads=None):
"""Process a single pair of catalogs, accumulating the cross-correlation.
This accumulates the weighted sums into the bins, but does not finalize
the calculation by dividing by the total weight at the end. After
calling this function as often as desired, the `finalize` command will
finish the calculation.
Parameters:
cat1 (Catalog): The first catalog to process
cat2 (Catalog): The second catalog to process
metric (str): Which metric to use. See `Metrics` for details.
(default: 'Euclidean'; this value can also be given in the
constructor in the config dict.)
num_threads (int): How many OpenMP threads to use during the calculation.
(default: use the number of cpu cores; this value can also be given
in the constructor in the config dict.)
"""
if cat1.name == '' and cat2.name == '':
self.logger.info('Starting process GG cross-correlations')
else:
self.logger.info('Starting process GG cross-correlations for cats %s, %s.',
cat1.name, cat2.name)
self._set_metric(metric, cat1.coords, cat2.coords)
self._set_num_threads(num_threads)
min_size, max_size = self._get_minmax_size()
f1 = cat1.getGField(min_size, max_size, self.split_method,
self.brute is True or self.brute is 1,
self.min_top, self.max_top, self.coords)
f2 = cat2.getGField(min_size, max_size, self.split_method,
self.brute is True or self.brute is 2,
self.min_top, self.max_top, self.coords)
self.logger.info('Starting %d jobs.',f1.nTopLevelNodes)
treecorr._lib.ProcessCross2(self.corr, f1.data, f2.data, self.output_dots,
f1._d, f2._d, self._coords, self._bintype, self._metric)
def process_pairwise(self, cat1, cat2, metric=None, num_threads=None):
"""Process a single pair of catalogs, accumulating the cross-correlation, only using
the corresponding pairs of objects in each catalog.
This accumulates the weighted sums into the bins, but does not finalize
the calculation by dividing by the total weight at the end. After
calling this function as often as desired, the `finalize` command will
finish the calculation.
Parameters:
cat1 (Catalog): The first catalog to process
cat2 (Catalog): The second catalog to process
metric (str): Which metric to use. See `process` for
details. (default: 'Euclidean'; this value can also be given in the
constructor in the config dict.)
num_threads (int): How many OpenMP threads to use during the calculation.
(default: use the number of cpu cores; this value can also be given
in the constructor in the config dict.)
"""
if cat1.name == '' and cat2.name == '':
self.logger.info('Starting process GG pairwise-correlations')
else:
self.logger.info('Starting process GG pairwise-correlations for cats %s, %s.',
cat1.name, cat2.name)
self._set_metric(metric, cat1.coords, cat2.coords)
self._set_num_threads(num_threads)
f1 = cat1.getGSimpleField()
f2 = cat2.getGSimpleField()
treecorr._lib.ProcessPair(self.corr, f1.data, f2.data, self.output_dots,
f1._d, f2._d, self._coords, self._bintype, self._metric)
def finalize(self, varg1, varg2):
"""Finalize the calculation of the correlation function.
The `process_auto` and `process_cross` commands accumulate values in each bin,
so they can be called multiple times if appropriate. Afterwards, this command
finishes the calculation by dividing each column by the total weight.
Parameters:
varg1 (float): The shear variance per component for the first field.
varg2 (float): The shear variance per component for the second field.
"""
mask1 = self.weight != 0
mask2 = self.weight == 0
self.xip[mask1] /= self.weight[mask1]
self.xim[mask1] /= self.weight[mask1]
self.xip_im[mask1] /= self.weight[mask1]
self.xim_im[mask1] /= self.weight[mask1]
self.meanr[mask1] /= self.weight[mask1]
self.meanlogr[mask1] /= self.weight[mask1]
self.varxip[mask1] = 2 * varg1 * varg2 / self.weight[mask1]
self.varxim[mask1] = 2 * varg1 * varg2 / self.weight[mask1]
# Update the units of meanr, meanlogr
self._apply_units(mask1)
# Use meanr, meanlogr when available, but set to nominal when no pairs in bin.
self.meanr[mask2] = self.rnom[mask2]
self.meanlogr[mask2] = self.logr[mask2]
self.varxip[mask2] = 0.
self.varxim[mask2] = 0.
def clear(self):
"""Clear the data vectors
"""
self.xip.ravel()[:] = 0
self.xim.ravel()[:] = 0
self.xip_im.ravel()[:] = 0
self.xim_im.ravel()[:] = 0
self.meanr.ravel()[:] = 0
self.meanlogr.ravel()[:] = 0
self.weight.ravel()[:] = 0
self.npairs.ravel()[:] = 0
def __iadd__(self, other):
"""Add a second GGCorrelation's data to this one.
.. note::
For this to make sense, both Correlation objects should have been using
`process_auto` and/or `process_cross`, and they should not have had `finalize`
called yet. Then, after adding them together, you should call `finalize` on the sum.
"""
if not isinstance(other, GGCorrelation):
raise TypeError("Can only add another GGCorrelation object")
if not (self._nbins == other._nbins and
self.min_sep == other.min_sep and
self.max_sep == other.max_sep):
raise ValueError("GGCorrelation to be added is not compatible with this one.")
self._set_metric(other.metric, other.coords)
self.xip.ravel()[:] += other.xip.ravel()[:]
self.xim.ravel()[:] += other.xim.ravel()[:]
self.xip_im.ravel()[:] += other.xip_im.ravel()[:]
self.xim_im.ravel()[:] += other.xim_im.ravel()[:]
self.meanr.ravel()[:] += other.meanr.ravel()[:]
self.meanlogr.ravel()[:] += other.meanlogr.ravel()[:]
self.weight.ravel()[:] += other.weight.ravel()[:]
self.npairs.ravel()[:] += other.npairs.ravel()[:]
return self
def process(self, cat1, cat2=None, metric=None, num_threads=None):
"""Compute the correlation function.
If only 1 argument is given, then compute an auto-correlation function.
If 2 arguments are given, then compute a cross-correlation function.
Both arguments may be lists, in which case all items in the list are used
for that element of the correlation.
Parameters:
cat1 (Catalog): A catalog or list of catalogs for the first G field.
cat2 (Catalog): A catalog or list of catalogs for the second G field, if any.
(default: None)
metric (str): Which metric to use. See `Metrics` for details.
(default: 'Euclidean'; this value can also be given in the
constructor in the config dict.)
num_threads (int): How many OpenMP threads to use during the calculation.
(default: use the number of cpu cores; this value can also be given
in the constructor in the config dict.)
"""
import math
self.clear()
if not isinstance(cat1,list): cat1 = [cat1]
if cat2 is not None and not isinstance(cat2,list): cat2 = [cat2]
if cat2 is None:
varg1 = treecorr.calculateVarG(cat1)
varg2 = varg1
self.logger.info("varg = %f: sig_sn (per component) = %f",varg1,math.sqrt(varg1))
self._process_all_auto(cat1, metric, num_threads)
else:
varg1 = treecorr.calculateVarG(cat1)
varg2 = treecorr.calculateVarG(cat2)
self.logger.info("varg1 = %f: sig_sn (per component) = %f",varg1,math.sqrt(varg1))
self.logger.info("varg2 = %f: sig_sn (per component) = %f",varg2,math.sqrt(varg2))
self._process_all_cross(cat1,cat2, metric, num_threads)
self.finalize(varg1,varg2)
def write(self, file_name, file_type=None, precision=None):
"""Write the correlation function to the file, file_name.
The output file will include the following columns:
========= =========================================================
Column Description
========= =========================================================
r_nom The nominal center of the bin in r
meanr The mean value <r> of pairs that fell into each bin
meanlogr The mean value <log(r)> of pairs that fell into each bin
xip The real part of the :math:`\\xi_+` correlation function
xim The real part of the :math:`\\xi_-` correlation function
xip_im The imag part of the :math:`\\xi_+` correlation function
xim_im The imag part of the :math:`\\xi_-` correlation function
sigma_xip The sqrt of the variance estimate of :math:`\\xi_+`
sigma_xim The sqrt of the variance estimate of :math:`\\xi_-`
weight The total weight contributing to each bin
npairs The number of pairs contributing ot each bin
========= =========================================================
If **sep_units** was given at construction, then the distances will all be in these units.
Otherwise, they will be in either the same units as x,y,z (for flat or 3d coordinates) or
radians (for spherical coordinates).
Parameters:
file_name (str): The name of the file to write to.
file_type (str): The type of file to write ('ASCII' or 'FITS'). (default: determine
the type automatically from the extension of file_name.)
precision (int): For ASCII output catalogs, the desired precision. (default: 4;
this value can also be given in the constructor in the config dict.)
"""
self.logger.info('Writing GG correlations to %s',file_name)
if precision is None:
precision = treecorr.config.get(self.config,'precision',int,4)
params = { 'coords' : self.coords, 'metric' : self.metric,
'sep_units' : self.sep_units, 'bin_type' : self.bin_type }
treecorr.util.gen_write(
file_name,
['r_nom','meanr','meanlogr','xip','xim','xip_im','xim_im','sigma_xip','sigma_xim',
'weight','npairs'],
[ self.rnom, self.meanr, self.meanlogr,
self.xip, self.xim, self.xip_im, self.xim_im,
np.sqrt(self.varxip), np.sqrt(self.varxim),
self.weight, self.npairs ],
params=params, precision=precision, file_type=file_type, logger=self.logger)
def read(self, file_name, file_type=None):
"""Read in values from a file.
This should be a file that was written by TreeCorr, preferably a FITS file, so there
is no loss of information.
Warning: The GGCorrelation object should be constructed with the same configuration
parameters as the one being read. e.g. the same min_sep, max_sep, etc. This is not
checked by the read function.
Parameters:
file_name (str): The name of the file to read in.
file_type (str): The type of file ('ASCII' or 'FITS'). (default: determine the type
automatically from the extension of file_name.)
"""
self.logger.info('Reading GG correlations from %s',file_name)
data, params = treecorr.util.gen_read(file_name, file_type=file_type, logger=self.logger)
if 'R_nom' in data.dtype.names: # pragma: no cover
self.rnom = data['R_nom']
self.meanr = data['meanR']
self.meanlogr = data['meanlogR']
else:
self.rnom = data['r_nom']
self.meanr = data['meanr']
self.meanlogr = data['meanlogr']
self.logr = np.log(self.rnom)
self.xip = data['xip']
self.xim = data['xim']
self.xip_im = data['xip_im']
self.xim_im = data['xim_im']
# Read old output files without error.
if 'sigma_xi' in data.dtype.names: # pragma: no cover
self.varxip = data['sigma_xi']**2
self.varxim = data['sigma_xi']**2
else:
self.varxip = data['sigma_xip']**2
self.varxim = data['sigma_xim']**2
self.weight = data['weight']
self.npairs = data['npairs']
self.coords = params['coords'].strip()
self.metric = params['metric'].strip()
self.sep_units = params['sep_units'].strip()
self.bin_type = params['bin_type'].strip()
self._build_corr()
def calculateMapSq(self, R=None, m2_uform=None):
"""Calculate the aperture mass statistics from the correlation function.
.. math::
\\langle M_{ap}^2 \\rangle(R) &= \\int_{0}^{rmax} \\frac{r dr}{2R^2}
\\left [ T_+\\left(\\frac{r}{R}\\right) \\xi_+(r) +
T_-\\left(\\frac{r}{R}\\right) \\xi_-(r) \\right] \\\\
\\langle M_\\times^2 \\rangle(R) &= \\int_{0}^{rmax} \\frac{r dr}{2R^2}
\\left [ T_+\\left(\\frac{r}{R}\\right) \\xi_+(r) -
T_-\\left(\\frac{r}{R}\\right) \\xi_-(r) \\right]
The **m2_uform** parameter sets which definition of the aperture mass to use.
The default is to use 'Crittenden'.
If **m2_uform** is 'Crittenden':
.. math::
U(r) &= \\frac{1}{2\\pi} (1-r^2) \\exp(-r^2/2) \\\\
Q(r) &= \\frac{1}{4\\pi} r^2 \\exp(-r^2/2) \\\\
T_+(s) &= \\frac{s^4 - 16s^2 + 32}{128} \\exp(-s^2/4) \\\\
T_-(s) &= \\frac{s^4}{128} \\exp(-s^2/4) \\\\
rmax &= \\infty
cf. Crittenden, et al (2002): ApJ, 568, 20
If **m2_uform** is 'Schneider':
.. math::
U(r) &= \\frac{9}{\\pi} (1-r^2) (1/3-r^2) \\\\
Q(r) &= \\frac{6}{\\pi} r^2 (1-r^2) \\\\
T_+(s) &= \\frac{12}{5\\pi} (2-15s^2) \\arccos(s/2) \\\\
&\qquad + \\frac{1}{100\\pi} s \\sqrt{4-s^2} (120 + 2320s^2 - 754s^4 + 132s^6 - 9s^8) \\\\
T_-(s) &= \\frac{3}{70\\pi} s^3 (4-s^2)^{7/2} \\\\
rmax &= 2R
cf. Schneider, et al (2002): A&A, 389, 729
.. note::
This function is only implemented for Log binning.
Parameters:
R (array): The R values at which to calculate the aperture mass statistics.
(default: None, which means use self.rnom)
m2_uform (str): Which form to use for the aperture mass, as described above.
(default: 'Crittenden'; this value can also be given in the
constructor in the config dict.)
Returns:
Tuple containing
- mapsq = array of :math:`\\langle M_{ap}^2 \\rangle(R)`
- mapsq_im = the imaginary part of mapsq, which is an estimate of
:math:`\\langle M_{ap} M_\\times \\rangle(R)`
- mxsq = array of :math:`\\langle M_\\times^2 \\rangle(R)`
- mxsq_im = the imaginary part of mxsq, which is an estimate of
:math:`\\langle M_{ap} M_\\times \\rangle(R)`
- varmapsq = array of the variance estimate of either mapsq or mxsq
"""
if m2_uform is None:
m2_uform = treecorr.config.get(self.config,'m2_uform',str,'Crittenden')
if m2_uform not in ['Crittenden', 'Schneider']:
raise ValueError("Invalid m2_uform")
if self.bin_type is not 'Log':
raise ValueError("calculateMapSq requires Log binning.")
if R is None:
R = self.rnom
# Make s a matrix, so we can eventually do the integral by doing a matrix product.
s = np.outer(1./R, self.meanr)
ssq = s*s
if m2_uform == 'Crittenden':
exp_factor = np.exp(-ssq/4.)
Tp = (32. + ssq*(-16. + ssq)) / 128. * exp_factor
Tm = ssq * ssq / 128. * exp_factor
else:
Tp = np.zeros_like(s)
Tm = np.zeros_like(s)
sa = s[s<2.]
ssqa = ssq[s<2.]
Tp[s<2.] = 12./(5.*np.pi) * (2.-15.*ssqa) * np.arccos(sa/2.)
Tp[s<2.] += 1./(100.*np.pi) * sa * np.sqrt(4.-ssqa) * (
120. + ssqa*(2320. + ssqa*(-754. + ssqa*(132. - 9.*ssqa))))
Tm[s<2.] = 3./(70.*np.pi) * sa * ssqa * (4.-ssqa)**3.5
Tp *= ssq
Tm *= ssq
# Now do the integral by taking the matrix products.
# Note that dlogr = bin_size
Tpxip = Tp.dot(self.xip)
Tmxim = Tm.dot(self.xim)
mapsq = (Tpxip + Tmxim) * 0.5 * self.bin_size
mxsq = (Tpxip - Tmxim) * 0.5 * self.bin_size
Tpxip_im = Tp.dot(self.xip_im)
Tmxim_im = Tm.dot(self.xim_im)
mapsq_im = (Tpxip_im + Tmxim_im) * 0.5 * self.bin_size
mxsq_im = (Tpxip_im - Tmxim_im) * 0.5 * self.bin_size
# The variance of each of these is
# Var(<Map^2>(R)) = int_r=0..2R [1/4 s^4 dlogr^2 (T+(s)^2 + T-(s)^2) Var(xi)]
varmapsq = (Tp**2).dot(self.varxip) + (Tm**2).dot(self.varxim)
varmapsq *= 0.25 * self.bin_size**2
return mapsq, mapsq_im, mxsq, mxsq_im, varmapsq
def calculateGamSq(self, R=None, eb=False):
"""Calculate the tophat shear variance from the correlation function.
.. math::
\\langle \\gamma^2 \\rangle(R) &= \\int_0^{2R} \\frac{r dr}{R^2} S_+(s) \\xi_+(r) \\\\
\\langle \\gamma^2 \\rangle_E(R) &= \\int_0^{2R} \\frac{r dr}{2 R^2}
\\left [ S_+\\left(\\frac{r}{R}\\right) \\xi_+(r) +
S_-\\left(\\frac{r}{R}\\right) \\xi_-(r) \\right ] \\\\
\\langle \\gamma^2 \\rangle_B(R) &= \\int_0^{2R} \\frac{r dr}{2 R^2}
\\left [ S_+\\left(\\frac{r}{R}\\right) \\xi_+(r) -
S_-\\left(\\frac{r}{R}\\right) \\xi_-(r) \\right ] \\\\
S_+(s) &= \\frac{1}{\\pi} \\left(4 \\arccos(s/2) - s \\sqrt{4-s^2} \\right) \\\\
S_-(s) &= \\begin{cases}
s<=2, & [ s \\sqrt{4-s^2} (6-s^2) - 8(3-s^2) \\arcsin(s/2) ] / (\\pi s^4) \\\\
s>=2, & 4(s^2-3)/(s^4)
\\end{cases}
cf. Schneider, et al (2002): A&A, 389, 729
The default behavior is not to compute the E/B versions. They are calculated if
eb is set to True.
.. note::
This function is only implemented for Log binning.
Parameters:
R (array): The R values at which to calculate the shear variance.
(default: None, which means use self.rnom)
eb (bool): Whether to include the E/B decomposition as well as the total
:math:`\\langle \\gamma^2\\rangle`. (default: False)
Returns:
Tuple containing
- gamsq = array of :math:`\\langle \\gamma^2 \\rangle(R)`
- vargamsq = array of the variance estimate of gamsq
- gamsq_e (Only if eb is True) = array of :math:`\\langle \\gamma^2 \\rangle_E(R)`
- gamsq_b (Only if eb is True) = array of :math:`\\langle \\gamma^2 \\rangle_B(R)`
- vargamsq_e (Only if eb is True) = array of the variance estimate of
gamsq_e or gamsq_b
"""
if self.bin_type is not 'Log':
raise ValueError("calculateGamSq requires Log binning.")
if R is None:
R = self.rnom
s = np.outer(1./R, self.meanr)
ssq = s*s
Sp = np.zeros_like(s)
sa = s[s<2]
ssqa = ssq[s<2]
Sp[s<2.] = 1./np.pi * ssqa * (4.*np.arccos(sa/2.) - sa*np.sqrt(4.-ssqa))
# Now do the integral by taking the matrix products.
# Note that dlogr = bin_size
Spxip = Sp.dot(self.xip)
gamsq = Spxip * self.bin_size
vargamsq = (Sp**2).dot(self.varxip) * self.bin_size**2
# Stop here if eb is False
if not eb: return gamsq, vargamsq
Sm = np.empty_like(s)
Sm[s<2.] = 1./(ssqa*np.pi) * (sa*np.sqrt(4.-ssqa)*(6.-ssqa)
-8.*(3.-ssqa)*np.arcsin(sa/2.))
Sm[s>=2.] = 4.*(ssq[s>=2]-3.)/ssq[s>=2]
# This already includes the extra ssq factor.
Smxim = Sm.dot(self.xim)
gamsq_e = (Spxip + Smxim) * 0.5 * self.bin_size
gamsq_b = (Spxip - Smxim) * 0.5 * self.bin_size
vargamsq_e = (Sp**2).dot(self.varxip) + (Sm**2).dot(self.varxim)
vargamsq_e *= 0.25 * self.bin_size**2
return gamsq, vargamsq, gamsq_e, gamsq_b, vargamsq_e
def writeMapSq(self, file_name, R=None, m2_uform=None, file_type=None, precision=None):
"""Write the aperture mass statistics based on the correlation function to the
file, file_name.
See `calculateMapSq` for an explanation of the **m2_uform** parameter.
The output file will include the following columns:
========= ==========================================================
Column Description
========= ==========================================================
R The aperture radius
Mapsq The real part of <M_ap^2> (cf. `calculateMapSq`)
Mxsq The real part of <M_x^2>
MMxa The imag part of <M_ap^2>: an estimator of <M_ap Mx>
MMxa The imag part of <M_x^2>: an estimator of <M_ap Mx>
sig_map The sqrt of the variance estimate of <M_ap^2>
Gamsq The tophat shear variance <gamma^2> (cf. `calculateGamSq`)
sig_gam The sqrt of the variance estimate of <gamma^2>
========= ==========================================================
Parameters:
file_name (str): The name of the file to write to.
R (array): The R values at which to calculate the statistics.
(default: None, which means use self.rnom)
m2_uform (str): Which form to use for the aperture mass. (default: 'Crittenden';
this value can also be given in the constructor in the config dict.)
file_type (str): The type of file to write ('ASCII' or 'FITS'). (default: determine
the type automatically from the extension of file_name.)
precision (int): For ASCII output catalogs, the desired precision. (default: 4;
this value can also be given in the constructor in the config dict.)
"""
self.logger.info('Writing Map^2 from GG correlations to %s',file_name)
if R is None:
R = self.rnom
mapsq, mapsq_im, mxsq, mxsq_im, varmapsq = self.calculateMapSq(R, m2_uform=m2_uform)
gamsq, vargamsq = self.calculateGamSq(R)
if precision is None:
precision = treecorr.config.get(self.config,'precision',int,4)
treecorr.util.gen_write(
file_name,
['R','Mapsq','Mxsq','MMxa','MMxb','sig_map','Gamsq','sig_gam'],
[ R,
mapsq, mxsq, mapsq_im, -mxsq_im, np.sqrt(varmapsq),
gamsq, np.sqrt(vargamsq) ],
precision=precision, file_type=file_type, logger=self.logger)
| # Copyright (c) 2003-2019 by <NAME>
#
# TreeCorr is free software: redistribution and use in source and binary forms,
# with or without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions, and the disclaimer given in the accompanying LICENSE
# file.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the disclaimer given in the documentation
# and/or other materials provided with the distribution.
"""
.. module:: ggcorrelation
"""
import treecorr
import numpy as np
class GGCorrelation(treecorr.BinnedCorr2):
"""This class handles the calculation and storage of a 2-point shear-shear correlation
function.
Ojects of this class holds the following attributes:
Attributes:
nbins: The number of bins in logr
bin_size: The size of the bins in logr
min_sep: The minimum separation being considered
max_sep: The maximum separation being considered
In addition, the following attributes are numpy arrays of length (nbins):
Attributes:
logr: The nominal center of the bin in log(r) (the natural logarithm of r).
rnom: The nominal center of the bin converted to regular distance.
i.e. r = exp(logr).
meanr: The (weighted) mean value of r for the pairs in each bin.
If there are no pairs in a bin, then exp(logr) will be used instead.
meanlogr: The (weighted) mean value of log(r) for the pairs in each bin.
If there are no pairs in a bin, then logr will be used instead.
xip: The correlation function, :math:`\\xi_+(r)`.
xim: The correlation funciton, :math:`\\xi_-(r)`.
xip_im: The imaginary part of :math:`\\xi_+(r)`.
xim_im: The imaginary part of :math:`\\xi_-(r)`.
varxip: The variance of xip, only including the shape noise propagated into
the final correlation. This does not include sample variance, so it
is always an underestimate of the actual variance.
varxim: The variance of xim, only including the shape noise propagated into
the final correlation. This does not include sample variance, so it
is always an underestimate of the actual variance.
weight: The total weight in each bin.
npairs: The number of pairs going into each bin.
If **sep_units** are given (either in the config dict or as a named kwarg) then the distances
will all be in these units. Note however, that if you separate out the steps of the
`process` command and use `process_auto` and/or `process_cross`, then the
units will not be applied to **meanr** or **meanlogr** until the `finalize` function is
called.
The typical usage pattern is as follows:
>>> gg = treecorr.GGCorrelation(config)
>>> gg.process(cat) # For auto-correlation.
>>> gg.process(cat1,cat2) # For cross-correlation.
>>> gg.write(file_name) # Write out to a file.
>>> xip = gg.xip # Or access the correlation function directly.
Parameters:
config (dict): A configuration dict that can be used to pass in kwargs if desired.
This dict is allowed to have addition entries in addition to those listed
in `BinnedCorr2`, which are ignored here. (default: None)
logger: If desired, a logger object for logging. (default: None, in which case
one will be built according to the config dict's verbose level.)
See the documentation for `BinnedCorr2` for the list of other allowed kwargs,
which may be passed either directly or in the config dict.
"""
def __init__(self, config=None, logger=None, **kwargs):
treecorr.BinnedCorr2.__init__(self, config, logger, **kwargs)
self._d1 = 3 # GData
self._d2 = 3 # GData
self.xip = np.zeros_like(self.rnom, dtype=float)
self.xim = np.zeros_like(self.rnom, dtype=float)
self.xip_im = np.zeros_like(self.rnom, dtype=float)
self.xim_im = np.zeros_like(self.rnom, dtype=float)
self.varxip = np.zeros_like(self.rnom, dtype=float)
self.varxim = np.zeros_like(self.rnom, dtype=float)
self.meanr = np.zeros_like(self.rnom, dtype=float)
self.meanlogr = np.zeros_like(self.rnom, dtype=float)
self.weight = np.zeros_like(self.rnom, dtype=float)
self.npairs = np.zeros_like(self.rnom, dtype=float)
self._build_corr()
self.logger.debug('Finished building GGCorr')
def _build_corr(self):
from treecorr.util import double_ptr as dp
self.corr = treecorr._lib.BuildCorr2(
self._d1, self._d2, self._bintype,
self._min_sep,self._max_sep,self._nbins,self._bin_size,self.b,
self.min_rpar, self.max_rpar, self.xperiod, self.yperiod, self.zperiod,
dp(self.xip),dp(self.xip_im),dp(self.xim),dp(self.xim_im),
dp(self.meanr),dp(self.meanlogr),dp(self.weight),dp(self.npairs))
def __del__(self):
# Using memory allocated from the C layer means we have to explicitly deallocate it
# rather than being able to rely on the Python memory manager.
# In case __init__ failed to get that far
if hasattr(self,'corr'): # pragma: no branch
if not treecorr._ffi._lock.locked(): # pragma: no branch
treecorr._lib.DestroyCorr2(self.corr, self._d1, self._d2, self._bintype)
def __eq__(self, other):
"""Return whether two GGCorrelations are equal"""
return (isinstance(other, GGCorrelation) and
self.nbins == other.nbins and
self.bin_size == other.bin_size and
self.min_sep == other.min_sep and
self.max_sep == other.max_sep and
self.sep_units == other.sep_units and
self.coords == other.coords and
self.bin_type == other.bin_type and
self.bin_slop == other.bin_slop and
self.min_rpar == other.min_rpar and
self.max_rpar == other.max_rpar and
self.xperiod == other.xperiod and
self.yperiod == other.yperiod and
self.zperiod == other.zperiod and
np.array_equal(self.meanr, other.meanr) and
np.array_equal(self.meanlogr, other.meanlogr) and
np.array_equal(self.xip, other.xip) and
np.array_equal(self.xim, other.xim) and
np.array_equal(self.xip_im, other.xip_im) and
np.array_equal(self.xim_im, other.xim_im) and
np.array_equal(self.varxip, other.varxip) and
np.array_equal(self.varxim, other.varxim) and
np.array_equal(self.weight, other.weight) and
np.array_equal(self.npairs, other.npairs))
def copy(self):
"""Make a copy"""
import copy
return copy.deepcopy(self)
def __getstate__(self):
d = self.__dict__.copy()
del d['corr']
del d['logger'] # Oh well. This is just lost in the copy. Can't be pickled.
return d
def __setstate__(self, d):
self.__dict__ = d
self._build_corr()
self.logger = treecorr.config.setup_logger(
treecorr.config.get(self.config,'verbose',int,1),
self.config.get('log_file',None))
def __repr__(self):
return 'GGCorrelation(config=%r)'%self.config
def process_auto(self, cat, metric=None, num_threads=None):
"""Process a single catalog, accumulating the auto-correlation.
This accumulates the weighted sums into the bins, but does not finalize
the calculation by dividing by the total weight at the end. After
calling this function as often as desired, the `finalize` command will
finish the calculation.
Parameters:
cat (Catalog): The catalog to process
metric (str): Which metric to use. See `Metrics` for details.
(default: 'Euclidean'; this value can also be given in the
constructor in the config dict.)
num_threads (int): How many OpenMP threads to use during the calculation.
(default: use the number of cpu cores; this value can also be given
in the constructor in the config dict.)
"""
if cat.name == '':
self.logger.info('Starting process GG auto-correlations')
else:
self.logger.info('Starting process GG auto-correlations for cat %s.',cat.name)
self._set_metric(metric, cat.coords)
self._set_num_threads(num_threads)
min_size, max_size = self._get_minmax_size()
field = cat.getGField(min_size, max_size, self.split_method,
bool(self.brute), self.min_top, self.max_top, self.coords)
self.logger.info('Starting %d jobs.',field.nTopLevelNodes)
treecorr._lib.ProcessAuto2(self.corr, field.data, self.output_dots,
field._d, self._coords, self._bintype, self._metric)
def process_cross(self, cat1, cat2, metric=None, num_threads=None):
"""Process a single pair of catalogs, accumulating the cross-correlation.
This accumulates the weighted sums into the bins, but does not finalize
the calculation by dividing by the total weight at the end. After
calling this function as often as desired, the `finalize` command will
finish the calculation.
Parameters:
cat1 (Catalog): The first catalog to process
cat2 (Catalog): The second catalog to process
metric (str): Which metric to use. See `Metrics` for details.
(default: 'Euclidean'; this value can also be given in the
constructor in the config dict.)
num_threads (int): How many OpenMP threads to use during the calculation.
(default: use the number of cpu cores; this value can also be given
in the constructor in the config dict.)
"""
if cat1.name == '' and cat2.name == '':
self.logger.info('Starting process GG cross-correlations')
else:
self.logger.info('Starting process GG cross-correlations for cats %s, %s.',
cat1.name, cat2.name)
self._set_metric(metric, cat1.coords, cat2.coords)
self._set_num_threads(num_threads)
min_size, max_size = self._get_minmax_size()
f1 = cat1.getGField(min_size, max_size, self.split_method,
self.brute is True or self.brute is 1,
self.min_top, self.max_top, self.coords)
f2 = cat2.getGField(min_size, max_size, self.split_method,
self.brute is True or self.brute is 2,
self.min_top, self.max_top, self.coords)
self.logger.info('Starting %d jobs.',f1.nTopLevelNodes)
treecorr._lib.ProcessCross2(self.corr, f1.data, f2.data, self.output_dots,
f1._d, f2._d, self._coords, self._bintype, self._metric)
def process_pairwise(self, cat1, cat2, metric=None, num_threads=None):
"""Process a single pair of catalogs, accumulating the cross-correlation, only using
the corresponding pairs of objects in each catalog.
This accumulates the weighted sums into the bins, but does not finalize
the calculation by dividing by the total weight at the end. After
calling this function as often as desired, the `finalize` command will
finish the calculation.
Parameters:
cat1 (Catalog): The first catalog to process
cat2 (Catalog): The second catalog to process
metric (str): Which metric to use. See `process` for
details. (default: 'Euclidean'; this value can also be given in the
constructor in the config dict.)
num_threads (int): How many OpenMP threads to use during the calculation.
(default: use the number of cpu cores; this value can also be given
in the constructor in the config dict.)
"""
if cat1.name == '' and cat2.name == '':
self.logger.info('Starting process GG pairwise-correlations')
else:
self.logger.info('Starting process GG pairwise-correlations for cats %s, %s.',
cat1.name, cat2.name)
self._set_metric(metric, cat1.coords, cat2.coords)
self._set_num_threads(num_threads)
f1 = cat1.getGSimpleField()
f2 = cat2.getGSimpleField()
treecorr._lib.ProcessPair(self.corr, f1.data, f2.data, self.output_dots,
f1._d, f2._d, self._coords, self._bintype, self._metric)
def finalize(self, varg1, varg2):
"""Finalize the calculation of the correlation function.
The `process_auto` and `process_cross` commands accumulate values in each bin,
so they can be called multiple times if appropriate. Afterwards, this command
finishes the calculation by dividing each column by the total weight.
Parameters:
varg1 (float): The shear variance per component for the first field.
varg2 (float): The shear variance per component for the second field.
"""
mask1 = self.weight != 0
mask2 = self.weight == 0
self.xip[mask1] /= self.weight[mask1]
self.xim[mask1] /= self.weight[mask1]
self.xip_im[mask1] /= self.weight[mask1]
self.xim_im[mask1] /= self.weight[mask1]
self.meanr[mask1] /= self.weight[mask1]
self.meanlogr[mask1] /= self.weight[mask1]
self.varxip[mask1] = 2 * varg1 * varg2 / self.weight[mask1]
self.varxim[mask1] = 2 * varg1 * varg2 / self.weight[mask1]
# Update the units of meanr, meanlogr
self._apply_units(mask1)
# Use meanr, meanlogr when available, but set to nominal when no pairs in bin.
self.meanr[mask2] = self.rnom[mask2]
self.meanlogr[mask2] = self.logr[mask2]
self.varxip[mask2] = 0.
self.varxim[mask2] = 0.
def clear(self):
"""Clear the data vectors
"""
self.xip.ravel()[:] = 0
self.xim.ravel()[:] = 0
self.xip_im.ravel()[:] = 0
self.xim_im.ravel()[:] = 0
self.meanr.ravel()[:] = 0
self.meanlogr.ravel()[:] = 0
self.weight.ravel()[:] = 0
self.npairs.ravel()[:] = 0
def __iadd__(self, other):
"""Add a second GGCorrelation's data to this one.
.. note::
For this to make sense, both Correlation objects should have been using
`process_auto` and/or `process_cross`, and they should not have had `finalize`
called yet. Then, after adding them together, you should call `finalize` on the sum.
"""
if not isinstance(other, GGCorrelation):
raise TypeError("Can only add another GGCorrelation object")
if not (self._nbins == other._nbins and
self.min_sep == other.min_sep and
self.max_sep == other.max_sep):
raise ValueError("GGCorrelation to be added is not compatible with this one.")
self._set_metric(other.metric, other.coords)
self.xip.ravel()[:] += other.xip.ravel()[:]
self.xim.ravel()[:] += other.xim.ravel()[:]
self.xip_im.ravel()[:] += other.xip_im.ravel()[:]
self.xim_im.ravel()[:] += other.xim_im.ravel()[:]
self.meanr.ravel()[:] += other.meanr.ravel()[:]
self.meanlogr.ravel()[:] += other.meanlogr.ravel()[:]
self.weight.ravel()[:] += other.weight.ravel()[:]
self.npairs.ravel()[:] += other.npairs.ravel()[:]
return self
def process(self, cat1, cat2=None, metric=None, num_threads=None):
"""Compute the correlation function.
If only 1 argument is given, then compute an auto-correlation function.
If 2 arguments are given, then compute a cross-correlation function.
Both arguments may be lists, in which case all items in the list are used
for that element of the correlation.
Parameters:
cat1 (Catalog): A catalog or list of catalogs for the first G field.
cat2 (Catalog): A catalog or list of catalogs for the second G field, if any.
(default: None)
metric (str): Which metric to use. See `Metrics` for details.
(default: 'Euclidean'; this value can also be given in the
constructor in the config dict.)
num_threads (int): How many OpenMP threads to use during the calculation.
(default: use the number of cpu cores; this value can also be given
in the constructor in the config dict.)
"""
import math
self.clear()
if not isinstance(cat1,list): cat1 = [cat1]
if cat2 is not None and not isinstance(cat2,list): cat2 = [cat2]
if cat2 is None:
varg1 = treecorr.calculateVarG(cat1)
varg2 = varg1
self.logger.info("varg = %f: sig_sn (per component) = %f",varg1,math.sqrt(varg1))
self._process_all_auto(cat1, metric, num_threads)
else:
varg1 = treecorr.calculateVarG(cat1)
varg2 = treecorr.calculateVarG(cat2)
self.logger.info("varg1 = %f: sig_sn (per component) = %f",varg1,math.sqrt(varg1))
self.logger.info("varg2 = %f: sig_sn (per component) = %f",varg2,math.sqrt(varg2))
self._process_all_cross(cat1,cat2, metric, num_threads)
self.finalize(varg1,varg2)
def write(self, file_name, file_type=None, precision=None):
"""Write the correlation function to the file, file_name.
The output file will include the following columns:
========= =========================================================
Column Description
========= =========================================================
r_nom The nominal center of the bin in r
meanr The mean value <r> of pairs that fell into each bin
meanlogr The mean value <log(r)> of pairs that fell into each bin
xip The real part of the :math:`\\xi_+` correlation function
xim The real part of the :math:`\\xi_-` correlation function
xip_im The imag part of the :math:`\\xi_+` correlation function
xim_im The imag part of the :math:`\\xi_-` correlation function
sigma_xip The sqrt of the variance estimate of :math:`\\xi_+`
sigma_xim The sqrt of the variance estimate of :math:`\\xi_-`
weight The total weight contributing to each bin
npairs The number of pairs contributing ot each bin
========= =========================================================
If **sep_units** was given at construction, then the distances will all be in these units.
Otherwise, they will be in either the same units as x,y,z (for flat or 3d coordinates) or
radians (for spherical coordinates).
Parameters:
file_name (str): The name of the file to write to.
file_type (str): The type of file to write ('ASCII' or 'FITS'). (default: determine
the type automatically from the extension of file_name.)
precision (int): For ASCII output catalogs, the desired precision. (default: 4;
this value can also be given in the constructor in the config dict.)
"""
self.logger.info('Writing GG correlations to %s',file_name)
if precision is None:
precision = treecorr.config.get(self.config,'precision',int,4)
params = { 'coords' : self.coords, 'metric' : self.metric,
'sep_units' : self.sep_units, 'bin_type' : self.bin_type }
treecorr.util.gen_write(
file_name,
['r_nom','meanr','meanlogr','xip','xim','xip_im','xim_im','sigma_xip','sigma_xim',
'weight','npairs'],
[ self.rnom, self.meanr, self.meanlogr,
self.xip, self.xim, self.xip_im, self.xim_im,
np.sqrt(self.varxip), np.sqrt(self.varxim),
self.weight, self.npairs ],
params=params, precision=precision, file_type=file_type, logger=self.logger)
def read(self, file_name, file_type=None):
"""Read in values from a file.
This should be a file that was written by TreeCorr, preferably a FITS file, so there
is no loss of information.
Warning: The GGCorrelation object should be constructed with the same configuration
parameters as the one being read. e.g. the same min_sep, max_sep, etc. This is not
checked by the read function.
Parameters:
file_name (str): The name of the file to read in.
file_type (str): The type of file ('ASCII' or 'FITS'). (default: determine the type
automatically from the extension of file_name.)
"""
self.logger.info('Reading GG correlations from %s',file_name)
data, params = treecorr.util.gen_read(file_name, file_type=file_type, logger=self.logger)
if 'R_nom' in data.dtype.names: # pragma: no cover
self.rnom = data['R_nom']
self.meanr = data['meanR']
self.meanlogr = data['meanlogR']
else:
self.rnom = data['r_nom']
self.meanr = data['meanr']
self.meanlogr = data['meanlogr']
self.logr = np.log(self.rnom)
self.xip = data['xip']
self.xim = data['xim']
self.xip_im = data['xip_im']
self.xim_im = data['xim_im']
# Read old output files without error.
if 'sigma_xi' in data.dtype.names: # pragma: no cover
self.varxip = data['sigma_xi']**2
self.varxim = data['sigma_xi']**2
else:
self.varxip = data['sigma_xip']**2
self.varxim = data['sigma_xim']**2
self.weight = data['weight']
self.npairs = data['npairs']
self.coords = params['coords'].strip()
self.metric = params['metric'].strip()
self.sep_units = params['sep_units'].strip()
self.bin_type = params['bin_type'].strip()
self._build_corr()
def calculateMapSq(self, R=None, m2_uform=None):
"""Calculate the aperture mass statistics from the correlation function.
.. math::
\\langle M_{ap}^2 \\rangle(R) &= \\int_{0}^{rmax} \\frac{r dr}{2R^2}
\\left [ T_+\\left(\\frac{r}{R}\\right) \\xi_+(r) +
T_-\\left(\\frac{r}{R}\\right) \\xi_-(r) \\right] \\\\
\\langle M_\\times^2 \\rangle(R) &= \\int_{0}^{rmax} \\frac{r dr}{2R^2}
\\left [ T_+\\left(\\frac{r}{R}\\right) \\xi_+(r) -
T_-\\left(\\frac{r}{R}\\right) \\xi_-(r) \\right]
The **m2_uform** parameter sets which definition of the aperture mass to use.
The default is to use 'Crittenden'.
If **m2_uform** is 'Crittenden':
.. math::
U(r) &= \\frac{1}{2\\pi} (1-r^2) \\exp(-r^2/2) \\\\
Q(r) &= \\frac{1}{4\\pi} r^2 \\exp(-r^2/2) \\\\
T_+(s) &= \\frac{s^4 - 16s^2 + 32}{128} \\exp(-s^2/4) \\\\
T_-(s) &= \\frac{s^4}{128} \\exp(-s^2/4) \\\\
rmax &= \\infty
cf. Crittenden, et al (2002): ApJ, 568, 20
If **m2_uform** is 'Schneider':
.. math::
U(r) &= \\frac{9}{\\pi} (1-r^2) (1/3-r^2) \\\\
Q(r) &= \\frac{6}{\\pi} r^2 (1-r^2) \\\\
T_+(s) &= \\frac{12}{5\\pi} (2-15s^2) \\arccos(s/2) \\\\
&\qquad + \\frac{1}{100\\pi} s \\sqrt{4-s^2} (120 + 2320s^2 - 754s^4 + 132s^6 - 9s^8) \\\\
T_-(s) &= \\frac{3}{70\\pi} s^3 (4-s^2)^{7/2} \\\\
rmax &= 2R
cf. Schneider, et al (2002): A&A, 389, 729
.. note::
This function is only implemented for Log binning.
Parameters:
R (array): The R values at which to calculate the aperture mass statistics.
(default: None, which means use self.rnom)
m2_uform (str): Which form to use for the aperture mass, as described above.
(default: 'Crittenden'; this value can also be given in the
constructor in the config dict.)
Returns:
Tuple containing
- mapsq = array of :math:`\\langle M_{ap}^2 \\rangle(R)`
- mapsq_im = the imaginary part of mapsq, which is an estimate of
:math:`\\langle M_{ap} M_\\times \\rangle(R)`
- mxsq = array of :math:`\\langle M_\\times^2 \\rangle(R)`
- mxsq_im = the imaginary part of mxsq, which is an estimate of
:math:`\\langle M_{ap} M_\\times \\rangle(R)`
- varmapsq = array of the variance estimate of either mapsq or mxsq
"""
if m2_uform is None:
m2_uform = treecorr.config.get(self.config,'m2_uform',str,'Crittenden')
if m2_uform not in ['Crittenden', 'Schneider']:
raise ValueError("Invalid m2_uform")
if self.bin_type is not 'Log':
raise ValueError("calculateMapSq requires Log binning.")
if R is None:
R = self.rnom
# Make s a matrix, so we can eventually do the integral by doing a matrix product.
s = np.outer(1./R, self.meanr)
ssq = s*s
if m2_uform == 'Crittenden':
exp_factor = np.exp(-ssq/4.)
Tp = (32. + ssq*(-16. + ssq)) / 128. * exp_factor
Tm = ssq * ssq / 128. * exp_factor
else:
Tp = np.zeros_like(s)
Tm = np.zeros_like(s)
sa = s[s<2.]
ssqa = ssq[s<2.]
Tp[s<2.] = 12./(5.*np.pi) * (2.-15.*ssqa) * np.arccos(sa/2.)
Tp[s<2.] += 1./(100.*np.pi) * sa * np.sqrt(4.-ssqa) * (
120. + ssqa*(2320. + ssqa*(-754. + ssqa*(132. - 9.*ssqa))))
Tm[s<2.] = 3./(70.*np.pi) * sa * ssqa * (4.-ssqa)**3.5
Tp *= ssq
Tm *= ssq
# Now do the integral by taking the matrix products.
# Note that dlogr = bin_size
Tpxip = Tp.dot(self.xip)
Tmxim = Tm.dot(self.xim)
mapsq = (Tpxip + Tmxim) * 0.5 * self.bin_size
mxsq = (Tpxip - Tmxim) * 0.5 * self.bin_size
Tpxip_im = Tp.dot(self.xip_im)
Tmxim_im = Tm.dot(self.xim_im)
mapsq_im = (Tpxip_im + Tmxim_im) * 0.5 * self.bin_size
mxsq_im = (Tpxip_im - Tmxim_im) * 0.5 * self.bin_size
# The variance of each of these is
# Var(<Map^2>(R)) = int_r=0..2R [1/4 s^4 dlogr^2 (T+(s)^2 + T-(s)^2) Var(xi)]
varmapsq = (Tp**2).dot(self.varxip) + (Tm**2).dot(self.varxim)
varmapsq *= 0.25 * self.bin_size**2
return mapsq, mapsq_im, mxsq, mxsq_im, varmapsq
def calculateGamSq(self, R=None, eb=False):
"""Calculate the tophat shear variance from the correlation function.
.. math::
\\langle \\gamma^2 \\rangle(R) &= \\int_0^{2R} \\frac{r dr}{R^2} S_+(s) \\xi_+(r) \\\\
\\langle \\gamma^2 \\rangle_E(R) &= \\int_0^{2R} \\frac{r dr}{2 R^2}
\\left [ S_+\\left(\\frac{r}{R}\\right) \\xi_+(r) +
S_-\\left(\\frac{r}{R}\\right) \\xi_-(r) \\right ] \\\\
\\langle \\gamma^2 \\rangle_B(R) &= \\int_0^{2R} \\frac{r dr}{2 R^2}
\\left [ S_+\\left(\\frac{r}{R}\\right) \\xi_+(r) -
S_-\\left(\\frac{r}{R}\\right) \\xi_-(r) \\right ] \\\\
S_+(s) &= \\frac{1}{\\pi} \\left(4 \\arccos(s/2) - s \\sqrt{4-s^2} \\right) \\\\
S_-(s) &= \\begin{cases}
s<=2, & [ s \\sqrt{4-s^2} (6-s^2) - 8(3-s^2) \\arcsin(s/2) ] / (\\pi s^4) \\\\
s>=2, & 4(s^2-3)/(s^4)
\\end{cases}
cf. Schneider, et al (2002): A&A, 389, 729
The default behavior is not to compute the E/B versions. They are calculated if
eb is set to True.
.. note::
This function is only implemented for Log binning.
Parameters:
R (array): The R values at which to calculate the shear variance.
(default: None, which means use self.rnom)
eb (bool): Whether to include the E/B decomposition as well as the total
:math:`\\langle \\gamma^2\\rangle`. (default: False)
Returns:
Tuple containing
- gamsq = array of :math:`\\langle \\gamma^2 \\rangle(R)`
- vargamsq = array of the variance estimate of gamsq
- gamsq_e (Only if eb is True) = array of :math:`\\langle \\gamma^2 \\rangle_E(R)`
- gamsq_b (Only if eb is True) = array of :math:`\\langle \\gamma^2 \\rangle_B(R)`
- vargamsq_e (Only if eb is True) = array of the variance estimate of
gamsq_e or gamsq_b
"""
if self.bin_type is not 'Log':
raise ValueError("calculateGamSq requires Log binning.")
if R is None:
R = self.rnom
s = np.outer(1./R, self.meanr)
ssq = s*s
Sp = np.zeros_like(s)
sa = s[s<2]
ssqa = ssq[s<2]
Sp[s<2.] = 1./np.pi * ssqa * (4.*np.arccos(sa/2.) - sa*np.sqrt(4.-ssqa))
# Now do the integral by taking the matrix products.
# Note that dlogr = bin_size
Spxip = Sp.dot(self.xip)
gamsq = Spxip * self.bin_size
vargamsq = (Sp**2).dot(self.varxip) * self.bin_size**2
# Stop here if eb is False
if not eb: return gamsq, vargamsq
Sm = np.empty_like(s)
Sm[s<2.] = 1./(ssqa*np.pi) * (sa*np.sqrt(4.-ssqa)*(6.-ssqa)
-8.*(3.-ssqa)*np.arcsin(sa/2.))
Sm[s>=2.] = 4.*(ssq[s>=2]-3.)/ssq[s>=2]
# This already includes the extra ssq factor.
Smxim = Sm.dot(self.xim)
gamsq_e = (Spxip + Smxim) * 0.5 * self.bin_size
gamsq_b = (Spxip - Smxim) * 0.5 * self.bin_size
vargamsq_e = (Sp**2).dot(self.varxip) + (Sm**2).dot(self.varxim)
vargamsq_e *= 0.25 * self.bin_size**2
return gamsq, vargamsq, gamsq_e, gamsq_b, vargamsq_e
def writeMapSq(self, file_name, R=None, m2_uform=None, file_type=None, precision=None):
"""Write the aperture mass statistics based on the correlation function to the
file, file_name.
See `calculateMapSq` for an explanation of the **m2_uform** parameter.
The output file will include the following columns:
========= ==========================================================
Column Description
========= ==========================================================
R The aperture radius
Mapsq The real part of <M_ap^2> (cf. `calculateMapSq`)
Mxsq The real part of <M_x^2>
MMxa The imag part of <M_ap^2>: an estimator of <M_ap Mx>
MMxa The imag part of <M_x^2>: an estimator of <M_ap Mx>
sig_map The sqrt of the variance estimate of <M_ap^2>
Gamsq The tophat shear variance <gamma^2> (cf. `calculateGamSq`)
sig_gam The sqrt of the variance estimate of <gamma^2>
========= ==========================================================
Parameters:
file_name (str): The name of the file to write to.
R (array): The R values at which to calculate the statistics.
(default: None, which means use self.rnom)
m2_uform (str): Which form to use for the aperture mass. (default: 'Crittenden';
this value can also be given in the constructor in the config dict.)
file_type (str): The type of file to write ('ASCII' or 'FITS'). (default: determine
the type automatically from the extension of file_name.)
precision (int): For ASCII output catalogs, the desired precision. (default: 4;
this value can also be given in the constructor in the config dict.)
"""
self.logger.info('Writing Map^2 from GG correlations to %s',file_name)
if R is None:
R = self.rnom
mapsq, mapsq_im, mxsq, mxsq_im, varmapsq = self.calculateMapSq(R, m2_uform=m2_uform)
gamsq, vargamsq = self.calculateGamSq(R)
if precision is None:
precision = treecorr.config.get(self.config,'precision',int,4)
treecorr.util.gen_write(
file_name,
['R','Mapsq','Mxsq','MMxa','MMxb','sig_map','Gamsq','sig_gam'],
[ R,
mapsq, mxsq, mapsq_im, -mxsq_im, np.sqrt(varmapsq),
gamsq, np.sqrt(vargamsq) ],
precision=precision, file_type=file_type, logger=self.logger) | en | 0.745584 | # Copyright (c) 2003-2019 by <NAME> # # TreeCorr is free software: redistribution and use in source and binary forms, # with or without modification, are permitted provided that the following # conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions, and the disclaimer given in the accompanying LICENSE # file. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions, and the disclaimer given in the documentation # and/or other materials provided with the distribution. .. module:: ggcorrelation This class handles the calculation and storage of a 2-point shear-shear correlation function. Ojects of this class holds the following attributes: Attributes: nbins: The number of bins in logr bin_size: The size of the bins in logr min_sep: The minimum separation being considered max_sep: The maximum separation being considered In addition, the following attributes are numpy arrays of length (nbins): Attributes: logr: The nominal center of the bin in log(r) (the natural logarithm of r). rnom: The nominal center of the bin converted to regular distance. i.e. r = exp(logr). meanr: The (weighted) mean value of r for the pairs in each bin. If there are no pairs in a bin, then exp(logr) will be used instead. meanlogr: The (weighted) mean value of log(r) for the pairs in each bin. If there are no pairs in a bin, then logr will be used instead. xip: The correlation function, :math:`\\xi_+(r)`. xim: The correlation funciton, :math:`\\xi_-(r)`. xip_im: The imaginary part of :math:`\\xi_+(r)`. xim_im: The imaginary part of :math:`\\xi_-(r)`. varxip: The variance of xip, only including the shape noise propagated into the final correlation. This does not include sample variance, so it is always an underestimate of the actual variance. varxim: The variance of xim, only including the shape noise propagated into the final correlation. This does not include sample variance, so it is always an underestimate of the actual variance. weight: The total weight in each bin. npairs: The number of pairs going into each bin. If **sep_units** are given (either in the config dict or as a named kwarg) then the distances will all be in these units. Note however, that if you separate out the steps of the `process` command and use `process_auto` and/or `process_cross`, then the units will not be applied to **meanr** or **meanlogr** until the `finalize` function is called. The typical usage pattern is as follows: >>> gg = treecorr.GGCorrelation(config) >>> gg.process(cat) # For auto-correlation. >>> gg.process(cat1,cat2) # For cross-correlation. >>> gg.write(file_name) # Write out to a file. >>> xip = gg.xip # Or access the correlation function directly. Parameters: config (dict): A configuration dict that can be used to pass in kwargs if desired. This dict is allowed to have addition entries in addition to those listed in `BinnedCorr2`, which are ignored here. (default: None) logger: If desired, a logger object for logging. (default: None, in which case one will be built according to the config dict's verbose level.) See the documentation for `BinnedCorr2` for the list of other allowed kwargs, which may be passed either directly or in the config dict. # GData # GData # Using memory allocated from the C layer means we have to explicitly deallocate it # rather than being able to rely on the Python memory manager. # In case __init__ failed to get that far # pragma: no branch # pragma: no branch Return whether two GGCorrelations are equal Make a copy # Oh well. This is just lost in the copy. Can't be pickled. Process a single catalog, accumulating the auto-correlation. This accumulates the weighted sums into the bins, but does not finalize the calculation by dividing by the total weight at the end. After calling this function as often as desired, the `finalize` command will finish the calculation. Parameters: cat (Catalog): The catalog to process metric (str): Which metric to use. See `Metrics` for details. (default: 'Euclidean'; this value can also be given in the constructor in the config dict.) num_threads (int): How many OpenMP threads to use during the calculation. (default: use the number of cpu cores; this value can also be given in the constructor in the config dict.) Process a single pair of catalogs, accumulating the cross-correlation. This accumulates the weighted sums into the bins, but does not finalize the calculation by dividing by the total weight at the end. After calling this function as often as desired, the `finalize` command will finish the calculation. Parameters: cat1 (Catalog): The first catalog to process cat2 (Catalog): The second catalog to process metric (str): Which metric to use. See `Metrics` for details. (default: 'Euclidean'; this value can also be given in the constructor in the config dict.) num_threads (int): How many OpenMP threads to use during the calculation. (default: use the number of cpu cores; this value can also be given in the constructor in the config dict.) Process a single pair of catalogs, accumulating the cross-correlation, only using the corresponding pairs of objects in each catalog. This accumulates the weighted sums into the bins, but does not finalize the calculation by dividing by the total weight at the end. After calling this function as often as desired, the `finalize` command will finish the calculation. Parameters: cat1 (Catalog): The first catalog to process cat2 (Catalog): The second catalog to process metric (str): Which metric to use. See `process` for details. (default: 'Euclidean'; this value can also be given in the constructor in the config dict.) num_threads (int): How many OpenMP threads to use during the calculation. (default: use the number of cpu cores; this value can also be given in the constructor in the config dict.) Finalize the calculation of the correlation function. The `process_auto` and `process_cross` commands accumulate values in each bin, so they can be called multiple times if appropriate. Afterwards, this command finishes the calculation by dividing each column by the total weight. Parameters: varg1 (float): The shear variance per component for the first field. varg2 (float): The shear variance per component for the second field. # Update the units of meanr, meanlogr # Use meanr, meanlogr when available, but set to nominal when no pairs in bin. Clear the data vectors Add a second GGCorrelation's data to this one. .. note:: For this to make sense, both Correlation objects should have been using `process_auto` and/or `process_cross`, and they should not have had `finalize` called yet. Then, after adding them together, you should call `finalize` on the sum. Compute the correlation function. If only 1 argument is given, then compute an auto-correlation function. If 2 arguments are given, then compute a cross-correlation function. Both arguments may be lists, in which case all items in the list are used for that element of the correlation. Parameters: cat1 (Catalog): A catalog or list of catalogs for the first G field. cat2 (Catalog): A catalog or list of catalogs for the second G field, if any. (default: None) metric (str): Which metric to use. See `Metrics` for details. (default: 'Euclidean'; this value can also be given in the constructor in the config dict.) num_threads (int): How many OpenMP threads to use during the calculation. (default: use the number of cpu cores; this value can also be given in the constructor in the config dict.) Write the correlation function to the file, file_name. The output file will include the following columns: ========= ========================================================= Column Description ========= ========================================================= r_nom The nominal center of the bin in r meanr The mean value <r> of pairs that fell into each bin meanlogr The mean value <log(r)> of pairs that fell into each bin xip The real part of the :math:`\\xi_+` correlation function xim The real part of the :math:`\\xi_-` correlation function xip_im The imag part of the :math:`\\xi_+` correlation function xim_im The imag part of the :math:`\\xi_-` correlation function sigma_xip The sqrt of the variance estimate of :math:`\\xi_+` sigma_xim The sqrt of the variance estimate of :math:`\\xi_-` weight The total weight contributing to each bin npairs The number of pairs contributing ot each bin ========= ========================================================= If **sep_units** was given at construction, then the distances will all be in these units. Otherwise, they will be in either the same units as x,y,z (for flat or 3d coordinates) or radians (for spherical coordinates). Parameters: file_name (str): The name of the file to write to. file_type (str): The type of file to write ('ASCII' or 'FITS'). (default: determine the type automatically from the extension of file_name.) precision (int): For ASCII output catalogs, the desired precision. (default: 4; this value can also be given in the constructor in the config dict.) Read in values from a file. This should be a file that was written by TreeCorr, preferably a FITS file, so there is no loss of information. Warning: The GGCorrelation object should be constructed with the same configuration parameters as the one being read. e.g. the same min_sep, max_sep, etc. This is not checked by the read function. Parameters: file_name (str): The name of the file to read in. file_type (str): The type of file ('ASCII' or 'FITS'). (default: determine the type automatically from the extension of file_name.) # pragma: no cover # Read old output files without error. # pragma: no cover Calculate the aperture mass statistics from the correlation function. .. math:: \\langle M_{ap}^2 \\rangle(R) &= \\int_{0}^{rmax} \\frac{r dr}{2R^2} \\left [ T_+\\left(\\frac{r}{R}\\right) \\xi_+(r) + T_-\\left(\\frac{r}{R}\\right) \\xi_-(r) \\right] \\\\ \\langle M_\\times^2 \\rangle(R) &= \\int_{0}^{rmax} \\frac{r dr}{2R^2} \\left [ T_+\\left(\\frac{r}{R}\\right) \\xi_+(r) - T_-\\left(\\frac{r}{R}\\right) \\xi_-(r) \\right] The **m2_uform** parameter sets which definition of the aperture mass to use. The default is to use 'Crittenden'. If **m2_uform** is 'Crittenden': .. math:: U(r) &= \\frac{1}{2\\pi} (1-r^2) \\exp(-r^2/2) \\\\ Q(r) &= \\frac{1}{4\\pi} r^2 \\exp(-r^2/2) \\\\ T_+(s) &= \\frac{s^4 - 16s^2 + 32}{128} \\exp(-s^2/4) \\\\ T_-(s) &= \\frac{s^4}{128} \\exp(-s^2/4) \\\\ rmax &= \\infty cf. Crittenden, et al (2002): ApJ, 568, 20 If **m2_uform** is 'Schneider': .. math:: U(r) &= \\frac{9}{\\pi} (1-r^2) (1/3-r^2) \\\\ Q(r) &= \\frac{6}{\\pi} r^2 (1-r^2) \\\\ T_+(s) &= \\frac{12}{5\\pi} (2-15s^2) \\arccos(s/2) \\\\ &\qquad + \\frac{1}{100\\pi} s \\sqrt{4-s^2} (120 + 2320s^2 - 754s^4 + 132s^6 - 9s^8) \\\\ T_-(s) &= \\frac{3}{70\\pi} s^3 (4-s^2)^{7/2} \\\\ rmax &= 2R cf. Schneider, et al (2002): A&A, 389, 729 .. note:: This function is only implemented for Log binning. Parameters: R (array): The R values at which to calculate the aperture mass statistics. (default: None, which means use self.rnom) m2_uform (str): Which form to use for the aperture mass, as described above. (default: 'Crittenden'; this value can also be given in the constructor in the config dict.) Returns: Tuple containing - mapsq = array of :math:`\\langle M_{ap}^2 \\rangle(R)` - mapsq_im = the imaginary part of mapsq, which is an estimate of :math:`\\langle M_{ap} M_\\times \\rangle(R)` - mxsq = array of :math:`\\langle M_\\times^2 \\rangle(R)` - mxsq_im = the imaginary part of mxsq, which is an estimate of :math:`\\langle M_{ap} M_\\times \\rangle(R)` - varmapsq = array of the variance estimate of either mapsq or mxsq # Make s a matrix, so we can eventually do the integral by doing a matrix product. # Now do the integral by taking the matrix products. # Note that dlogr = bin_size # The variance of each of these is # Var(<Map^2>(R)) = int_r=0..2R [1/4 s^4 dlogr^2 (T+(s)^2 + T-(s)^2) Var(xi)] Calculate the tophat shear variance from the correlation function. .. math:: \\langle \\gamma^2 \\rangle(R) &= \\int_0^{2R} \\frac{r dr}{R^2} S_+(s) \\xi_+(r) \\\\ \\langle \\gamma^2 \\rangle_E(R) &= \\int_0^{2R} \\frac{r dr}{2 R^2} \\left [ S_+\\left(\\frac{r}{R}\\right) \\xi_+(r) + S_-\\left(\\frac{r}{R}\\right) \\xi_-(r) \\right ] \\\\ \\langle \\gamma^2 \\rangle_B(R) &= \\int_0^{2R} \\frac{r dr}{2 R^2} \\left [ S_+\\left(\\frac{r}{R}\\right) \\xi_+(r) - S_-\\left(\\frac{r}{R}\\right) \\xi_-(r) \\right ] \\\\ S_+(s) &= \\frac{1}{\\pi} \\left(4 \\arccos(s/2) - s \\sqrt{4-s^2} \\right) \\\\ S_-(s) &= \\begin{cases} s<=2, & [ s \\sqrt{4-s^2} (6-s^2) - 8(3-s^2) \\arcsin(s/2) ] / (\\pi s^4) \\\\ s>=2, & 4(s^2-3)/(s^4) \\end{cases} cf. Schneider, et al (2002): A&A, 389, 729 The default behavior is not to compute the E/B versions. They are calculated if eb is set to True. .. note:: This function is only implemented for Log binning. Parameters: R (array): The R values at which to calculate the shear variance. (default: None, which means use self.rnom) eb (bool): Whether to include the E/B decomposition as well as the total :math:`\\langle \\gamma^2\\rangle`. (default: False) Returns: Tuple containing - gamsq = array of :math:`\\langle \\gamma^2 \\rangle(R)` - vargamsq = array of the variance estimate of gamsq - gamsq_e (Only if eb is True) = array of :math:`\\langle \\gamma^2 \\rangle_E(R)` - gamsq_b (Only if eb is True) = array of :math:`\\langle \\gamma^2 \\rangle_B(R)` - vargamsq_e (Only if eb is True) = array of the variance estimate of gamsq_e or gamsq_b # Now do the integral by taking the matrix products. # Note that dlogr = bin_size # Stop here if eb is False # This already includes the extra ssq factor. Write the aperture mass statistics based on the correlation function to the file, file_name. See `calculateMapSq` for an explanation of the **m2_uform** parameter. The output file will include the following columns: ========= ========================================================== Column Description ========= ========================================================== R The aperture radius Mapsq The real part of <M_ap^2> (cf. `calculateMapSq`) Mxsq The real part of <M_x^2> MMxa The imag part of <M_ap^2>: an estimator of <M_ap Mx> MMxa The imag part of <M_x^2>: an estimator of <M_ap Mx> sig_map The sqrt of the variance estimate of <M_ap^2> Gamsq The tophat shear variance <gamma^2> (cf. `calculateGamSq`) sig_gam The sqrt of the variance estimate of <gamma^2> ========= ========================================================== Parameters: file_name (str): The name of the file to write to. R (array): The R values at which to calculate the statistics. (default: None, which means use self.rnom) m2_uform (str): Which form to use for the aperture mass. (default: 'Crittenden'; this value can also be given in the constructor in the config dict.) file_type (str): The type of file to write ('ASCII' or 'FITS'). (default: determine the type automatically from the extension of file_name.) precision (int): For ASCII output catalogs, the desired precision. (default: 4; this value can also be given in the constructor in the config dict.) | 2.391111 | 2 |
arelle/plugin/logging/dpmSignature.py | theredpea/Arelle | 1 | 6627960 | '''
Created on Dec 12, 2013
@author: Mark V Systems Limited
(c) Copyright 2013 Mark V Systems Limited, All rights reserved.
'''
from arelle.ModelDtsObject import ModelConcept
from arelle.ModelInstanceObject import ModelFact
from arelle.XmlUtil import xmlstring
# key for use in dFact only when there's a dim that behaves as or is typed
def metDimTypedKey(fact):
cntx = fact.context
key = "MET({})".format(fact.qname)
if cntx is not None and cntx.qnameDims:
key += '|' + '|'.join(sorted("{}({})".format(dim.dimensionQname,
dim.memberQname if dim.isExplicit
else "nil" if dim.typedMember.get("{http://www.w3.org/2001/XMLSchema-instance}nil") in ("true", "1")
else xmlstring(dim.typedMember, stripXmlns=True))
for dim in cntx.qnameDims.values()))
return key
def loggingRefAttributes(arg, refAttributes, codedArgs):
# arg may be a ModelFact, or any other ModelObject
if isinstance(arg, ModelFact):
refAttributes["dpmSignature"] = metDimTypedKey(arg)
elif isinstance(arg, ModelConcept):
refAttributes["dpmSignature"] = "MET({})".format(arg.qname)
elif "dpmSignature" in codedArgs: # signature may be passed in as arg for non-fact error
refAttributes["dpmSignature"] = codedArgs["dpmSignature"]
__pluginInfo__ = {
# Do not use _( ) in pluginInfo itself (it is applied later, after loading
'name': 'Logging - DPM Signature',
'version': '0.9',
'description': '''DPM Signature, for data points (facts), concepts, dimensions, and members.
For a data point (fact): MET(conceptQName)|dimQName(mem)... (does not include period, unit, or entity identifier)
For a concept, MET(conceptQName).''',
'license': 'Apache-2',
'author': '<NAME>',
'copyright': '(c) Copyright 2014 Mark V Systems Limited, All rights reserved.',
# classes of mount points (required)
'Logging.Ref.Attributes': loggingRefAttributes
}
| '''
Created on Dec 12, 2013
@author: Mark V Systems Limited
(c) Copyright 2013 Mark V Systems Limited, All rights reserved.
'''
from arelle.ModelDtsObject import ModelConcept
from arelle.ModelInstanceObject import ModelFact
from arelle.XmlUtil import xmlstring
# key for use in dFact only when there's a dim that behaves as or is typed
def metDimTypedKey(fact):
cntx = fact.context
key = "MET({})".format(fact.qname)
if cntx is not None and cntx.qnameDims:
key += '|' + '|'.join(sorted("{}({})".format(dim.dimensionQname,
dim.memberQname if dim.isExplicit
else "nil" if dim.typedMember.get("{http://www.w3.org/2001/XMLSchema-instance}nil") in ("true", "1")
else xmlstring(dim.typedMember, stripXmlns=True))
for dim in cntx.qnameDims.values()))
return key
def loggingRefAttributes(arg, refAttributes, codedArgs):
# arg may be a ModelFact, or any other ModelObject
if isinstance(arg, ModelFact):
refAttributes["dpmSignature"] = metDimTypedKey(arg)
elif isinstance(arg, ModelConcept):
refAttributes["dpmSignature"] = "MET({})".format(arg.qname)
elif "dpmSignature" in codedArgs: # signature may be passed in as arg for non-fact error
refAttributes["dpmSignature"] = codedArgs["dpmSignature"]
__pluginInfo__ = {
# Do not use _( ) in pluginInfo itself (it is applied later, after loading
'name': 'Logging - DPM Signature',
'version': '0.9',
'description': '''DPM Signature, for data points (facts), concepts, dimensions, and members.
For a data point (fact): MET(conceptQName)|dimQName(mem)... (does not include period, unit, or entity identifier)
For a concept, MET(conceptQName).''',
'license': 'Apache-2',
'author': '<NAME>',
'copyright': '(c) Copyright 2014 Mark V Systems Limited, All rights reserved.',
# classes of mount points (required)
'Logging.Ref.Attributes': loggingRefAttributes
}
| en | 0.818867 | Created on Dec 12, 2013 @author: Mark V Systems Limited (c) Copyright 2013 Mark V Systems Limited, All rights reserved. # key for use in dFact only when there's a dim that behaves as or is typed # arg may be a ModelFact, or any other ModelObject # signature may be passed in as arg for non-fact error # Do not use _( ) in pluginInfo itself (it is applied later, after loading DPM Signature, for data points (facts), concepts, dimensions, and members. For a data point (fact): MET(conceptQName)|dimQName(mem)... (does not include period, unit, or entity identifier) For a concept, MET(conceptQName). # classes of mount points (required) | 1.79678 | 2 |
doc/examples/cookbook/wave_stab.py | markendr/esys-escript.github.io | 0 | 6627961 | <reponame>markendr/esys-escript.github.io<gh_stars>0
##############################################################################
#
# Copyright (c) 2009-2018 by The University of Queensland
# http://www.uq.edu.au
#
# Primary Business: Queensland, Australia
# Licensed under the Apache License, version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
#
# Development until 2012 by Earth Systems Science Computational Center (ESSCC)
# Development 2012-2013 by School of Earth Sciences
# Development from 2014 by Centre for Geoscience Computing (GeoComp)
#
##############################################################################
from __future__ import division, print_function
__copyright__="""Copyright (c) 2009-2018 by The University of Queensland
http://www.uq.edu.au
Primary Business: Queensland, Australia"""
__license__="""Licensed under the Apache License, version 2.0
http://www.apache.org/licenses/LICENSE-2.0"""
__url__="https://launchpad.net/escript-finley"
# <NAME>
# Acoustic Wave Equation Simulation
# Importing all the necessary modules required.
import matplotlib
matplotlib.use('agg') #It's just here for automated testing
import numpy as np
import pylab as pl
#Geometric and material property related variables.
mx = 1000. # model lenght
ndx = np.arange(0.,20.,.1)
mtim= np.zeros(len(ndx),'float')
nvel= np.arange(500.,5000.,500.)
for vel in nvel:
mtim=ndx/vel
pl.plot(ndx,mtim,label='%d m/s'%vel)
pl.title('Maximum time steps calculations by velocity')
pl.xlabel('Minimum grid spacing (m)')
pl.ylabel('Maximum stable time step (s)')
pl.legend()
pl.show()
| ##############################################################################
#
# Copyright (c) 2009-2018 by The University of Queensland
# http://www.uq.edu.au
#
# Primary Business: Queensland, Australia
# Licensed under the Apache License, version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
#
# Development until 2012 by Earth Systems Science Computational Center (ESSCC)
# Development 2012-2013 by School of Earth Sciences
# Development from 2014 by Centre for Geoscience Computing (GeoComp)
#
##############################################################################
from __future__ import division, print_function
__copyright__="""Copyright (c) 2009-2018 by The University of Queensland
http://www.uq.edu.au
Primary Business: Queensland, Australia"""
__license__="""Licensed under the Apache License, version 2.0
http://www.apache.org/licenses/LICENSE-2.0"""
__url__="https://launchpad.net/escript-finley"
# <NAME>
# Acoustic Wave Equation Simulation
# Importing all the necessary modules required.
import matplotlib
matplotlib.use('agg') #It's just here for automated testing
import numpy as np
import pylab as pl
#Geometric and material property related variables.
mx = 1000. # model lenght
ndx = np.arange(0.,20.,.1)
mtim= np.zeros(len(ndx),'float')
nvel= np.arange(500.,5000.,500.)
for vel in nvel:
mtim=ndx/vel
pl.plot(ndx,mtim,label='%d m/s'%vel)
pl.title('Maximum time steps calculations by velocity')
pl.xlabel('Minimum grid spacing (m)')
pl.ylabel('Maximum stable time step (s)')
pl.legend()
pl.show() | en | 0.578654 | ############################################################################## # # Copyright (c) 2009-2018 by The University of Queensland # http://www.uq.edu.au # # Primary Business: Queensland, Australia # Licensed under the Apache License, version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # # Development until 2012 by Earth Systems Science Computational Center (ESSCC) # Development 2012-2013 by School of Earth Sciences # Development from 2014 by Centre for Geoscience Computing (GeoComp) # ############################################################################## Copyright (c) 2009-2018 by The University of Queensland http://www.uq.edu.au Primary Business: Queensland, Australia Licensed under the Apache License, version 2.0 http://www.apache.org/licenses/LICENSE-2.0 # <NAME> # Acoustic Wave Equation Simulation # Importing all the necessary modules required. #It's just here for automated testing #Geometric and material property related variables. # model lenght | 1.827083 | 2 |
examples/dialogpt_medium.py | ibivibiv/openchat | 0 | 6627962 | from openchat import OpenChat
if __name__ == '__main__':
OpenChat(model="dialogpt.medium", device="cuda") | from openchat import OpenChat
if __name__ == '__main__':
OpenChat(model="dialogpt.medium", device="cuda") | none | 1 | 1.527873 | 2 | |
lib/spack/spack/cmd/fetch.py | xiki-tempula/spack | 2 | 6627963 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import llnl.util.tty as tty
import spack.cmd
import spack.cmd.common.arguments as arguments
import spack.config
import spack.repo
description = "fetch archives for packages"
section = "build"
level = "long"
def setup_parser(subparser):
arguments.add_common_arguments(subparser, ['no_checksum'])
subparser.add_argument(
'-m', '--missing', action='store_true',
help="fetch only missing (not yet installed) dependencies")
subparser.add_argument(
'-D', '--dependencies', action='store_true',
help="also fetch all dependencies")
arguments.add_common_arguments(subparser, ['specs'])
def fetch(parser, args):
if not args.specs:
tty.die("fetch requires at least one package argument")
if args.no_checksum:
spack.config.set('config:checksum', False, scope='command_line')
specs = spack.cmd.parse_specs(args.specs, concretize=True)
for spec in specs:
if args.missing or args.dependencies:
for s in spec.traverse():
package = spack.repo.get(s)
# Skip already-installed packages with --missing
if args.missing and package.installed:
continue
# Do not attempt to fetch externals (they're local)
if package.spec.external:
continue
package.do_fetch()
package = spack.repo.get(spec)
package.do_fetch()
| # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import llnl.util.tty as tty
import spack.cmd
import spack.cmd.common.arguments as arguments
import spack.config
import spack.repo
description = "fetch archives for packages"
section = "build"
level = "long"
def setup_parser(subparser):
arguments.add_common_arguments(subparser, ['no_checksum'])
subparser.add_argument(
'-m', '--missing', action='store_true',
help="fetch only missing (not yet installed) dependencies")
subparser.add_argument(
'-D', '--dependencies', action='store_true',
help="also fetch all dependencies")
arguments.add_common_arguments(subparser, ['specs'])
def fetch(parser, args):
if not args.specs:
tty.die("fetch requires at least one package argument")
if args.no_checksum:
spack.config.set('config:checksum', False, scope='command_line')
specs = spack.cmd.parse_specs(args.specs, concretize=True)
for spec in specs:
if args.missing or args.dependencies:
for s in spec.traverse():
package = spack.repo.get(s)
# Skip already-installed packages with --missing
if args.missing and package.installed:
continue
# Do not attempt to fetch externals (they're local)
if package.spec.external:
continue
package.do_fetch()
package = spack.repo.get(spec)
package.do_fetch()
| en | 0.786292 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) # Skip already-installed packages with --missing # Do not attempt to fetch externals (they're local) | 2.214219 | 2 |
gamer/models/core.py | sirfoga/gamer | 0 | 6627964 | <filename>gamer/models/core.py
# !/usr/bin/python2
# coding: utf-8
""" GAME models """
import json
import os
import shutil
import time
from multiprocessing import Process
from game.models import Game, FilesConfig, LabelsConfig
from gamer.config import OUTPUT_FOLDER, PROCESSES_COUNT
from gamer.emails.mailer import notify_user_of_start, notify_user_of_end
from gamer.models.logs import Logger
from gamer.utils.files import get_folders, name_of_folder
class Runner(Logger):
""" Runs GAME models """
def __init__(self, features, additional_features, inputs_file, errors_file,
labels_file,
output_folder, email, verbose=True):
Logger.__init__(self, verbose)
self.output_folder = output_folder
self.output_filename = os.path.join(output_folder, "output.dat")
self.output_extra_filename = None
self.labels = features
self.additional_features = additional_features
files = FilesConfig(
inputs_file,
errors_file,
labels_file,
output_folder,
True
)
labels = LabelsConfig(
features, # todo check format, should be ['G0', 'N' ..]
additional_features # todo check format, should be ['G0', 'N' ..]
)
self.driver = Game(
files,
PROCESSES_COUNT,
10000,
labels
)
self.email = email
self.successful_run = False
def start(self):
self.successful_run = notify_user_of_start(self.email)
def run(self):
try:
self.log("Starting GAME driver:")
self.log("labels:", self.driver.labels_config.output)
self.log("input file:", self.driver.filename_config.filename_int)
self.log("errors file:", self.driver.filename_config.filename_err)
self.log("labels file:",
self.driver.filename_config.filename_libraru)
self.log("output file:", self.driver.filename_config.output_folder)
self.driver.run()
except Exception as e:
self.successful_run = False
self.log(self.email, "stopped GAME due to", e)
def end(self):
notify_user_of_end(
self.email,
self.successful_run,
self.output_filename,
"", # todo debug file
self.output_extra_filename
)
class GameConfig(Logger):
""" Config files for GAME models """
def __init__(self, config_folder):
"""
:param config_folder: str
Path to config file
"""
Logger.__init__(self, True)
self.folder = config_folder
self.file = os.path.join(config_folder, "data.json") or None
self.raw_data = None
self.raw_data = self.parse()
def parse(self):
"""
:return: void
Parses raw data
"""
if self.raw_data is None:
try:
with open(self.file, "r") as in_file:
self.raw_data = json.loads(
in_file.read()
) # read and return json object
except Exception as e:
self.log("Cannot parse raw data of", self.file, ", due to", e)
return self.raw_data
def get_arg(self, key):
"""
:param key: str
Key to get
:return: obj
Value in data
"""
if key in self.raw_data:
return self.raw_data[key]
return None
def get_args(self):
"""
:return: tuple (...)
Args written in config file
"""
return self.get_arg("labels"), \
self.get_arg("additional labels"), \
self.get_arg("InputFile"), \
self.get_arg("ErrorFile"), \
self.get_arg("LabelsFile"), \
self.get_arg("UploadFolder"), \
self.get_arg("Email")
class Gamer(Logger):
""" Controls GAME models """
def __init__(self, config_folder, sec_between_runs):
"""
:param config_folder: str
Path to folder containing config files
"""
Logger.__init__(self, True)
self.config_folder = config_folder
self.configs = []
self.runners = []
self.slaves = []
self.sleep_time = float(sec_between_runs)
def parse_configs(self):
"""
:return: void
Scans config folder and finds config files
"""
self.configs = [
GameConfig(config)
for config in get_folders(self.config_folder)
]
self.create_gamers()
self.log("Found", len(self.configs), "config")
def create_gamers(self):
self.runners = [
Runner(
*config.get_args()
) for config in self.configs
]
self.slaves = [
Process(target=runner.run) for runner in self.runners
]
def launch_models(self):
for runner in self.runners:
runner.start()
for slave in self.slaves: # start
slave.start()
for slave in self.slaves: # wait until all are done todo find better
slave.join()
for runner in self.runners:
runner.end()
self.end_run()
def end_run(self):
"""
:return: void
Ends run and move config to output folder
"""
for config in self.configs:
output_folder = os.path.join(
OUTPUT_FOLDER,
name_of_folder(config.folder)
)
shutil.move(config.folder, output_folder)
self.log("Written output to", output_folder)
def run(self):
while True:
self.parse_configs()
self.launch_models()
time.sleep(self.sleep_time)
| <filename>gamer/models/core.py
# !/usr/bin/python2
# coding: utf-8
""" GAME models """
import json
import os
import shutil
import time
from multiprocessing import Process
from game.models import Game, FilesConfig, LabelsConfig
from gamer.config import OUTPUT_FOLDER, PROCESSES_COUNT
from gamer.emails.mailer import notify_user_of_start, notify_user_of_end
from gamer.models.logs import Logger
from gamer.utils.files import get_folders, name_of_folder
class Runner(Logger):
""" Runs GAME models """
def __init__(self, features, additional_features, inputs_file, errors_file,
labels_file,
output_folder, email, verbose=True):
Logger.__init__(self, verbose)
self.output_folder = output_folder
self.output_filename = os.path.join(output_folder, "output.dat")
self.output_extra_filename = None
self.labels = features
self.additional_features = additional_features
files = FilesConfig(
inputs_file,
errors_file,
labels_file,
output_folder,
True
)
labels = LabelsConfig(
features, # todo check format, should be ['G0', 'N' ..]
additional_features # todo check format, should be ['G0', 'N' ..]
)
self.driver = Game(
files,
PROCESSES_COUNT,
10000,
labels
)
self.email = email
self.successful_run = False
def start(self):
self.successful_run = notify_user_of_start(self.email)
def run(self):
try:
self.log("Starting GAME driver:")
self.log("labels:", self.driver.labels_config.output)
self.log("input file:", self.driver.filename_config.filename_int)
self.log("errors file:", self.driver.filename_config.filename_err)
self.log("labels file:",
self.driver.filename_config.filename_libraru)
self.log("output file:", self.driver.filename_config.output_folder)
self.driver.run()
except Exception as e:
self.successful_run = False
self.log(self.email, "stopped GAME due to", e)
def end(self):
notify_user_of_end(
self.email,
self.successful_run,
self.output_filename,
"", # todo debug file
self.output_extra_filename
)
class GameConfig(Logger):
""" Config files for GAME models """
def __init__(self, config_folder):
"""
:param config_folder: str
Path to config file
"""
Logger.__init__(self, True)
self.folder = config_folder
self.file = os.path.join(config_folder, "data.json") or None
self.raw_data = None
self.raw_data = self.parse()
def parse(self):
"""
:return: void
Parses raw data
"""
if self.raw_data is None:
try:
with open(self.file, "r") as in_file:
self.raw_data = json.loads(
in_file.read()
) # read and return json object
except Exception as e:
self.log("Cannot parse raw data of", self.file, ", due to", e)
return self.raw_data
def get_arg(self, key):
"""
:param key: str
Key to get
:return: obj
Value in data
"""
if key in self.raw_data:
return self.raw_data[key]
return None
def get_args(self):
"""
:return: tuple (...)
Args written in config file
"""
return self.get_arg("labels"), \
self.get_arg("additional labels"), \
self.get_arg("InputFile"), \
self.get_arg("ErrorFile"), \
self.get_arg("LabelsFile"), \
self.get_arg("UploadFolder"), \
self.get_arg("Email")
class Gamer(Logger):
""" Controls GAME models """
def __init__(self, config_folder, sec_between_runs):
"""
:param config_folder: str
Path to folder containing config files
"""
Logger.__init__(self, True)
self.config_folder = config_folder
self.configs = []
self.runners = []
self.slaves = []
self.sleep_time = float(sec_between_runs)
def parse_configs(self):
"""
:return: void
Scans config folder and finds config files
"""
self.configs = [
GameConfig(config)
for config in get_folders(self.config_folder)
]
self.create_gamers()
self.log("Found", len(self.configs), "config")
def create_gamers(self):
self.runners = [
Runner(
*config.get_args()
) for config in self.configs
]
self.slaves = [
Process(target=runner.run) for runner in self.runners
]
def launch_models(self):
for runner in self.runners:
runner.start()
for slave in self.slaves: # start
slave.start()
for slave in self.slaves: # wait until all are done todo find better
slave.join()
for runner in self.runners:
runner.end()
self.end_run()
def end_run(self):
"""
:return: void
Ends run and move config to output folder
"""
for config in self.configs:
output_folder = os.path.join(
OUTPUT_FOLDER,
name_of_folder(config.folder)
)
shutil.move(config.folder, output_folder)
self.log("Written output to", output_folder)
def run(self):
while True:
self.parse_configs()
self.launch_models()
time.sleep(self.sleep_time)
| en | 0.591168 | # !/usr/bin/python2 # coding: utf-8 GAME models Runs GAME models # todo check format, should be ['G0', 'N' ..] # todo check format, should be ['G0', 'N' ..] # todo debug file Config files for GAME models :param config_folder: str Path to config file :return: void Parses raw data # read and return json object :param key: str Key to get :return: obj Value in data :return: tuple (...) Args written in config file Controls GAME models :param config_folder: str Path to folder containing config files :return: void Scans config folder and finds config files # start # wait until all are done todo find better :return: void Ends run and move config to output folder | 2.480907 | 2 |
romanize/eng.py | markomanninen/abnum | 2 | 6627965 | <filename>romanize/eng.py
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
# file: eng.py
import re
from collections import OrderedDict
from romanize.romanizer import romanizer
has_capitals = True
data = OrderedDict()
data['a'] = dict(letter=[u'a'], name=u'αλφα', segment='vowel', subsegment='short', transliteration=u'a', order=1)
data['b'] = dict(letter=[u'b'], name=u'βητα', segment='consonant', subsegment='mute', transliteration=u'b', order=2)
data['c'] = dict(letter=[u'c'], name=u'γαμμα', segment='consonant', subsegment='mute', transliteration=u'c', order=3)
data['d'] = dict(letter=[u'd'], name=u'δελτα', segment='consonant', subsegment='mute', transliteration=u'd', order=4)
data['e'] = dict(letter=[u'e'], name=u'ε ψιλον', segment='vowel', subsegment='short', transliteration=u'e', order=5)
data['f'] = dict(letter=[u'f'], name=u'διγαμμα', segment='numeral', subsegment='', transliteration=u'f', order=6)
data['g'] = dict(letter=[u'g'], name=u'ζητα', segment='consonant', subsegment='double', transliteration=u'g', order=7)
data['h'] = dict(letter=[u'h'], name=u'ητα', segment='vowel', subsegment='long', transliteration=u'h', order=8)
data['i'] = dict(letter=[u'i'], name=u'θητα', segment='consonant', subsegment='mute', transliteration=u'i', order=9)
data['j'] = dict(letter=[u'j'], name=u'ιωτα', segment='vowel', subsegment='short', transliteration=u'j', order=10)
data['k'] = dict(letter=[u'k'], name=u'καππα', segment='consonant', subsegment='mute', transliteration=u'k', order=11)
data['l'] = dict(letter=[u'l'], name=u'λαμβδα', segment='consonant', subsegment='semivowel', transliteration=u'l', order=12)
data['m'] = dict(letter=[u'm'], name=u'μυ', segment='consonant', subsegment='semivowel', transliteration=u'm', order=13)
data['n'] = dict(letter=[u'n'], name=u'νυ', segment='consonant', subsegment='semivowel', transliteration=u'n', order=14)
data['o'] = dict(letter=[u'o'], name=u'ξει', segment='consonant', subsegment='double', transliteration=u'o', order=15)
data['p'] = dict(letter=[u'p'], name=u'ο μικρον', segment='vowel', subsegment='short', transliteration=u'p', order=16)
data['q'] = dict(letter=[u'q'], name=u'πει', segment='consonant', subsegment='mute', transliteration=u'r', order=17)
data['r'] = dict(letter=[u'r'], name=u'κοππα', segment='numeral', subsegment='', transliteration=u'r', order=18)
data['s'] = dict(letter=[u's'], name=u'ρω', segment='consonant', subsegment='semivowel', transliteration=u's', order=19)
data['t'] = dict(letter=[u't'], name=u'σιγμα', segment='consonant', subsegment='semivowel', transliteration=u't', order=20)
data['u'] = dict(letter=[u'u'], name=u'ταυ', segment='consonant', subsegment='mute', transliteration=u'u', order=21)
data['v'] = dict(letter=[u'v'], name=u'υ ψιλον', segment='vowel', subsegment='short', transliteration=u'v', order=22)
data['w'] = dict(letter=[u'w'], name=u'φει', segment='consonant', subsegment='mute', transliteration=u'w', order=23)
data['x'] = dict(letter=[u'x'], name=u'χει', segment='consonant', subsegment='mute', transliteration=u'x', order=24)
data['y'] = dict(letter=[u'y'], name=u'ψει', segment='consonant', subsegment='double', transliteration=u'y', order=25)
data['z'] = dict(letter=[u'z'], name=u'ω μεγα', segment='vowel', subsegment='long', transliteration=u'z', order=26)
r = romanizer(data)
# collect letters from data dictionary for preprocessing function
letters = ''.join(data.keys())
regex = re.compile('[^%s ]+' % letters)
def preprocess(string):
"""
Preprocess string to transform all diacritics and remove other special characters
:param string:
:return:
"""
return regex.sub('', string).encode('utf-8')
def convert(string, sanitize=False):
"""
Swap characters from script to transliterated version and vice versa.
Optionally sanitize string by using preprocess function.
:param sanitize:
:param string:
:return:
"""
return r.convert(string, (preprocess if sanitize else False)) | <filename>romanize/eng.py
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
# file: eng.py
import re
from collections import OrderedDict
from romanize.romanizer import romanizer
has_capitals = True
data = OrderedDict()
data['a'] = dict(letter=[u'a'], name=u'αλφα', segment='vowel', subsegment='short', transliteration=u'a', order=1)
data['b'] = dict(letter=[u'b'], name=u'βητα', segment='consonant', subsegment='mute', transliteration=u'b', order=2)
data['c'] = dict(letter=[u'c'], name=u'γαμμα', segment='consonant', subsegment='mute', transliteration=u'c', order=3)
data['d'] = dict(letter=[u'd'], name=u'δελτα', segment='consonant', subsegment='mute', transliteration=u'd', order=4)
data['e'] = dict(letter=[u'e'], name=u'ε ψιλον', segment='vowel', subsegment='short', transliteration=u'e', order=5)
data['f'] = dict(letter=[u'f'], name=u'διγαμμα', segment='numeral', subsegment='', transliteration=u'f', order=6)
data['g'] = dict(letter=[u'g'], name=u'ζητα', segment='consonant', subsegment='double', transliteration=u'g', order=7)
data['h'] = dict(letter=[u'h'], name=u'ητα', segment='vowel', subsegment='long', transliteration=u'h', order=8)
data['i'] = dict(letter=[u'i'], name=u'θητα', segment='consonant', subsegment='mute', transliteration=u'i', order=9)
data['j'] = dict(letter=[u'j'], name=u'ιωτα', segment='vowel', subsegment='short', transliteration=u'j', order=10)
data['k'] = dict(letter=[u'k'], name=u'καππα', segment='consonant', subsegment='mute', transliteration=u'k', order=11)
data['l'] = dict(letter=[u'l'], name=u'λαμβδα', segment='consonant', subsegment='semivowel', transliteration=u'l', order=12)
data['m'] = dict(letter=[u'm'], name=u'μυ', segment='consonant', subsegment='semivowel', transliteration=u'm', order=13)
data['n'] = dict(letter=[u'n'], name=u'νυ', segment='consonant', subsegment='semivowel', transliteration=u'n', order=14)
data['o'] = dict(letter=[u'o'], name=u'ξει', segment='consonant', subsegment='double', transliteration=u'o', order=15)
data['p'] = dict(letter=[u'p'], name=u'ο μικρον', segment='vowel', subsegment='short', transliteration=u'p', order=16)
data['q'] = dict(letter=[u'q'], name=u'πει', segment='consonant', subsegment='mute', transliteration=u'r', order=17)
data['r'] = dict(letter=[u'r'], name=u'κοππα', segment='numeral', subsegment='', transliteration=u'r', order=18)
data['s'] = dict(letter=[u's'], name=u'ρω', segment='consonant', subsegment='semivowel', transliteration=u's', order=19)
data['t'] = dict(letter=[u't'], name=u'σιγμα', segment='consonant', subsegment='semivowel', transliteration=u't', order=20)
data['u'] = dict(letter=[u'u'], name=u'ταυ', segment='consonant', subsegment='mute', transliteration=u'u', order=21)
data['v'] = dict(letter=[u'v'], name=u'υ ψιλον', segment='vowel', subsegment='short', transliteration=u'v', order=22)
data['w'] = dict(letter=[u'w'], name=u'φει', segment='consonant', subsegment='mute', transliteration=u'w', order=23)
data['x'] = dict(letter=[u'x'], name=u'χει', segment='consonant', subsegment='mute', transliteration=u'x', order=24)
data['y'] = dict(letter=[u'y'], name=u'ψει', segment='consonant', subsegment='double', transliteration=u'y', order=25)
data['z'] = dict(letter=[u'z'], name=u'ω μεγα', segment='vowel', subsegment='long', transliteration=u'z', order=26)
r = romanizer(data)
# collect letters from data dictionary for preprocessing function
letters = ''.join(data.keys())
regex = re.compile('[^%s ]+' % letters)
def preprocess(string):
"""
Preprocess string to transform all diacritics and remove other special characters
:param string:
:return:
"""
return regex.sub('', string).encode('utf-8')
def convert(string, sanitize=False):
"""
Swap characters from script to transliterated version and vice versa.
Optionally sanitize string by using preprocess function.
:param sanitize:
:param string:
:return:
"""
return r.convert(string, (preprocess if sanitize else False)) | en | 0.703684 | #!/usr/local/bin/python # -*- coding: utf-8 -*- # file: eng.py # collect letters from data dictionary for preprocessing function Preprocess string to transform all diacritics and remove other special characters :param string: :return: Swap characters from script to transliterated version and vice versa. Optionally sanitize string by using preprocess function. :param sanitize: :param string: :return: | 2.881873 | 3 |
dash/figures.py | afo/covid19 | 3 | 6627966 | import json
import plotly
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pickle
import pandas as pd
import numpy as np
import utilities as utils
import constants as const
def plot_map(date_index, total, iva, death, mobility):
"""Generates the map in the dashboard
TODO(<EMAIL>)
callbacks do no work currently.
Needs to be inspected
Arguments:
date_index {int} -- index of the date used (from slider)
total {Boolean} -- If to visualize: Confirmed cases
iva {Boolean} -- If to visualize: Intensive care
death {Boolean} -- If to visualize: Deaths
mobility {Boolean} -- If to visualize: Mobility
Returns:
Plotly Figure
"""
date = utils.get_date_from_index(date_index)
column = "Deaths"
if total:
column = "Tested_Confirmed"
if death:
column = "Deaths"
if iva:
column = "ICU_Patients"
if mobility:
column = "Mobility"
from urllib.request import urlopen
# Example data
with open('data/features.geojson') as response:
counties = json.load(response)
df = pd.read_csv('data/map_data.csv')
fig = px.choropleth_mapbox(df, geojson=counties, color=column,
locations="id",
center={'lat': 62.598584, 'lon': 12.961619},
mapbox_style="carto-positron", zoom=4, hover_name='NAME_1',
hover_data=['Deaths', 'Mobility',
'Tested_Confirmed', 'ICU_Patients'],
color_continuous_scale=plotly.colors.diverging.RdYlGn[::-1],
#labels={'id':'Unique ID'},
category_orders={'id': None})
fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})
fig.update_layout(hovermode="closest", width=800, height=700)
return fig
def plot_graph_with_mobility(data, politics, per_mn, scale="linear"):
"""Generates a plot with mobility data on a second yaxis
Arguments:
data {dictionary} -- containing dataframes for each country
politics {Boolean} -- If political decision is going to be shown
per_mn {Boolean} -- Show per million inhabitants
Keyword Arguments:
scale {str} -- which scale to use (default: {"linear"})
Returns:
Plotly Figure
"""
titley = ''
if per_mn:
titley = "Number of people per Million"
else:
titley = "Number of People"
fig = make_subplots(specs=[[{"secondary_y": True}]])
max_val = 0
for country, df in data.items():
for col in df.columns:
if 'mobility' not in col:
fig.add_trace(go.Scatter(
x=df.index, y=df[col], name=country+' '+const.legends[col],
line={'dash': const.lines[col], 'color': const.colors[country]},),
secondary_y=True)
else:
if max_val < df[col].max():
max_val = df[col].max()
if country not in ['Sweden', 'Denmark']:
continue
fig.add_trace(go.Scatter(
x=df.index, y=df[col], name="Mobility " + country, fill='tozeroy',
fillcolor=const.fillcolors[country], line={'color': const.colors[country], 'dash': 'dot'}),
secondary_y=False
)
fig.update_layout(template="plotly_white", title_text="Covid 19 Analysis",
xaxis_title="Dates",
hovermode='x',
xaxis_rangeslider_visible=False)
fig.update_yaxes(title_text="Mobility %",
secondary_y=False)
fig.update_yaxes(title_text=titley, secondary_y=True)
if politics:
fig = add_political_decision(fig, max_val)
return fig
def plot_graph(data, politics, per_mn, scale='linear'):
"""Generates a plot with data predetermined on the dashboard
Arguments:
data {dictionary} -- containing dataframes for each country
politics {Boolean} -- If political decision is going to be shown
per_mn {Boolean} -- Show per million inhabitants
Keyword Arguments:
scale {str} -- which scale to use (default: {"linear"})
Returns:
Plotly Figure
"""
titley = ''
if per_mn:
titley = "Number of peopler per Million"
else:
titley = "Number of People"
fig = go.Figure()
max_val = 0
for country, df in data.items():
for col in df.columns:
if max_val < df[col].max():
max_val = df[col].max()
fig.add_trace(go.Scatter(
x=df.index, y=df[col], name=country+' '+const.legends[col],
line={'dash': const.lines[col], 'color': const.colors[country]}))
fig.update_layout(template="plotly_white", title_text="Covid 19 Analysis",
xaxis_title="Dates",
yaxis_title=titley, yaxis=dict(fixedrange=True),
hovermode='x',
xaxis_rangeslider_visible=False)
if scale == 'on':
fig.update_layout(yaxis_type='log', yaxis_exponentformat="power")
if politics:
fig = add_political_decision(fig, max_val)
return fig
def add_political_decision(fig, max_val):
"""Adds political decisions to a plotly figure
Arguments:
fig {Plotly figure} -- figure to add decision to
max_val {float} -- Where to set the politics decision on y-axis
Returns:
Plotly Figure
"""
df_dec = pd.read_csv('data/decisions.csv')
df_dec['Date'] = pd.to_datetime(df_dec['Date'], yearfirst=True)
df_dec = df_dec.set_index('Date')
fig.add_trace(go.Scatter(
x=df_dec.index,
marker_symbol='x-dot',
marker_line_color="black",
marker_line_width=2, marker_size=10,
y=np.repeat(max_val, df_dec.shape[0]),
mode="markers",
text=df_dec['Event'],
hoverinfo="text",
hoverlabel=dict(bgcolor='rgba(7, 164, 181, 0.5)'),
marker=dict(color=px.colors.sequential.RdBu[-2]), name='Swedish Political Decisions'))
fig.update_layout(
shapes=[dict(
type="line",
x0=date,
y0=0,
x1=date,
y1=max_val,
line=dict(
color="RoyalBlue",
width=2
)
) for date in df_dec.index])
return fig
| import json
import plotly
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pickle
import pandas as pd
import numpy as np
import utilities as utils
import constants as const
def plot_map(date_index, total, iva, death, mobility):
"""Generates the map in the dashboard
TODO(<EMAIL>)
callbacks do no work currently.
Needs to be inspected
Arguments:
date_index {int} -- index of the date used (from slider)
total {Boolean} -- If to visualize: Confirmed cases
iva {Boolean} -- If to visualize: Intensive care
death {Boolean} -- If to visualize: Deaths
mobility {Boolean} -- If to visualize: Mobility
Returns:
Plotly Figure
"""
date = utils.get_date_from_index(date_index)
column = "Deaths"
if total:
column = "Tested_Confirmed"
if death:
column = "Deaths"
if iva:
column = "ICU_Patients"
if mobility:
column = "Mobility"
from urllib.request import urlopen
# Example data
with open('data/features.geojson') as response:
counties = json.load(response)
df = pd.read_csv('data/map_data.csv')
fig = px.choropleth_mapbox(df, geojson=counties, color=column,
locations="id",
center={'lat': 62.598584, 'lon': 12.961619},
mapbox_style="carto-positron", zoom=4, hover_name='NAME_1',
hover_data=['Deaths', 'Mobility',
'Tested_Confirmed', 'ICU_Patients'],
color_continuous_scale=plotly.colors.diverging.RdYlGn[::-1],
#labels={'id':'Unique ID'},
category_orders={'id': None})
fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})
fig.update_layout(hovermode="closest", width=800, height=700)
return fig
def plot_graph_with_mobility(data, politics, per_mn, scale="linear"):
"""Generates a plot with mobility data on a second yaxis
Arguments:
data {dictionary} -- containing dataframes for each country
politics {Boolean} -- If political decision is going to be shown
per_mn {Boolean} -- Show per million inhabitants
Keyword Arguments:
scale {str} -- which scale to use (default: {"linear"})
Returns:
Plotly Figure
"""
titley = ''
if per_mn:
titley = "Number of people per Million"
else:
titley = "Number of People"
fig = make_subplots(specs=[[{"secondary_y": True}]])
max_val = 0
for country, df in data.items():
for col in df.columns:
if 'mobility' not in col:
fig.add_trace(go.Scatter(
x=df.index, y=df[col], name=country+' '+const.legends[col],
line={'dash': const.lines[col], 'color': const.colors[country]},),
secondary_y=True)
else:
if max_val < df[col].max():
max_val = df[col].max()
if country not in ['Sweden', 'Denmark']:
continue
fig.add_trace(go.Scatter(
x=df.index, y=df[col], name="Mobility " + country, fill='tozeroy',
fillcolor=const.fillcolors[country], line={'color': const.colors[country], 'dash': 'dot'}),
secondary_y=False
)
fig.update_layout(template="plotly_white", title_text="Covid 19 Analysis",
xaxis_title="Dates",
hovermode='x',
xaxis_rangeslider_visible=False)
fig.update_yaxes(title_text="Mobility %",
secondary_y=False)
fig.update_yaxes(title_text=titley, secondary_y=True)
if politics:
fig = add_political_decision(fig, max_val)
return fig
def plot_graph(data, politics, per_mn, scale='linear'):
"""Generates a plot with data predetermined on the dashboard
Arguments:
data {dictionary} -- containing dataframes for each country
politics {Boolean} -- If political decision is going to be shown
per_mn {Boolean} -- Show per million inhabitants
Keyword Arguments:
scale {str} -- which scale to use (default: {"linear"})
Returns:
Plotly Figure
"""
titley = ''
if per_mn:
titley = "Number of peopler per Million"
else:
titley = "Number of People"
fig = go.Figure()
max_val = 0
for country, df in data.items():
for col in df.columns:
if max_val < df[col].max():
max_val = df[col].max()
fig.add_trace(go.Scatter(
x=df.index, y=df[col], name=country+' '+const.legends[col],
line={'dash': const.lines[col], 'color': const.colors[country]}))
fig.update_layout(template="plotly_white", title_text="Covid 19 Analysis",
xaxis_title="Dates",
yaxis_title=titley, yaxis=dict(fixedrange=True),
hovermode='x',
xaxis_rangeslider_visible=False)
if scale == 'on':
fig.update_layout(yaxis_type='log', yaxis_exponentformat="power")
if politics:
fig = add_political_decision(fig, max_val)
return fig
def add_political_decision(fig, max_val):
"""Adds political decisions to a plotly figure
Arguments:
fig {Plotly figure} -- figure to add decision to
max_val {float} -- Where to set the politics decision on y-axis
Returns:
Plotly Figure
"""
df_dec = pd.read_csv('data/decisions.csv')
df_dec['Date'] = pd.to_datetime(df_dec['Date'], yearfirst=True)
df_dec = df_dec.set_index('Date')
fig.add_trace(go.Scatter(
x=df_dec.index,
marker_symbol='x-dot',
marker_line_color="black",
marker_line_width=2, marker_size=10,
y=np.repeat(max_val, df_dec.shape[0]),
mode="markers",
text=df_dec['Event'],
hoverinfo="text",
hoverlabel=dict(bgcolor='rgba(7, 164, 181, 0.5)'),
marker=dict(color=px.colors.sequential.RdBu[-2]), name='Swedish Political Decisions'))
fig.update_layout(
shapes=[dict(
type="line",
x0=date,
y0=0,
x1=date,
y1=max_val,
line=dict(
color="RoyalBlue",
width=2
)
) for date in df_dec.index])
return fig
| en | 0.669656 | Generates the map in the dashboard TODO(<EMAIL>) callbacks do no work currently. Needs to be inspected Arguments: date_index {int} -- index of the date used (from slider) total {Boolean} -- If to visualize: Confirmed cases iva {Boolean} -- If to visualize: Intensive care death {Boolean} -- If to visualize: Deaths mobility {Boolean} -- If to visualize: Mobility Returns: Plotly Figure # Example data #labels={'id':'Unique ID'}, Generates a plot with mobility data on a second yaxis Arguments: data {dictionary} -- containing dataframes for each country politics {Boolean} -- If political decision is going to be shown per_mn {Boolean} -- Show per million inhabitants Keyword Arguments: scale {str} -- which scale to use (default: {"linear"}) Returns: Plotly Figure Generates a plot with data predetermined on the dashboard Arguments: data {dictionary} -- containing dataframes for each country politics {Boolean} -- If political decision is going to be shown per_mn {Boolean} -- Show per million inhabitants Keyword Arguments: scale {str} -- which scale to use (default: {"linear"}) Returns: Plotly Figure Adds political decisions to a plotly figure Arguments: fig {Plotly figure} -- figure to add decision to max_val {float} -- Where to set the politics decision on y-axis Returns: Plotly Figure | 3.17056 | 3 |
python/taichi/aot/module.py | zstone12/taichi | 1 | 6627967 | from contextlib import contextmanager
from pathlib import Path, PurePosixPath
from taichi.lang import impl, kernel_impl
from taichi.lang.field import ScalarField
from taichi.lang.matrix import MatrixField
from taichi.type.annotations import ArgAnyArray, template
class KernelTemplate:
def __init__(self, kernel_fn, aot_module):
self._kernel_fn = kernel_fn
self._aot_module = aot_module
@staticmethod
def keygen(v, key_p, fields):
if isinstance(v, (int, float, bool)):
key_p += '=' + str(v) + '/'
return key_p
for ky, val in fields:
if (val is v):
key_p += <KEY>
return key_p
raise RuntimeError('Arg type must be of type int/float/boolean' +
'or taichi field. Type ' + str(type(v)) +
' is not supported')
def instantiate(self, **kwargs):
name = self._kernel_fn.__name__
kernel = self._kernel_fn._primal
assert isinstance(kernel, kernel_impl.Kernel)
injected_args = []
key_p = ''
anno_index = 0
template_args = {}
for index, (key, value) in enumerate(kwargs.items()):
template_args[index] = (key, value)
for i in range(len(kernel.argument_annotations)):
anno = kernel.argument_annotations[i]
if isinstance(anno, template):
(k, v) = template_args[anno_index]
key_p += k
key_p = self.keygen(v, key_p, self._aot_module._fields.items())
injected_args.append(v)
anno_index += 1
else:
injected_args.append(0)
kernel.ensure_compiled(*injected_args)
self._aot_module._aot_builder.add_kernel_template(
name, key_p, kernel.kernel_cpp)
# kernel AOT
self._aot_module._kernels.append(kernel)
class Module:
"""An AOT module to save and load Taichi kernels.
This module serializes the Taichi kernels for a specific arch. The
serialized module can later be loaded to run on that backend, without the
Python environment.
Example:
Usage::
m = ti.aot.Module(ti.metal)
m.add_kernel(foo)
m.add_kernel(bar)
m.save('/path/to/module')
# Now the module file '/path/to/module' contains the Metal kernels
# for running ``foo`` and ``bar``.
"""
def __init__(self, arch):
"""Creates a new AOT module instance
Args:
arch: Target backend architecture. This is ignored for now. The AOT
backend still uses the one specified in :func:`~taichi.lang.init`.
"""
self._arch = arch
self._kernels = []
self._fields = {}
rtm = impl.get_runtime()
rtm._finalize_root_fb_for_aot()
self._aot_builder = rtm.prog.make_aot_module_builder(arch)
def add_field(self, name, field):
"""Add a taichi field to the AOT module.
Args:
name: name of taichi field
field: taichi field
Example:
Usage::
a = ti.field(ti.f32, shape=(4,4))
b = ti.field("something")
m.add_field(a)
m.add_field(b)
# Must add in sequence
"""
is_scalar = True
self._fields[name] = field
column_num = 1
row_num = 1
if isinstance(field, MatrixField):
is_scalar = False
row_num = field.m
column_num = field.n
else:
assert isinstance(field, ScalarField)
self._aot_builder.add_field(name, field.snode.ptr, is_scalar,
field.dtype, field.snode.shape, row_num,
column_num)
def add_kernel(self, kernel_fn, name=None):
"""Add a taichi kernel to the AOT module.
Args:
kernel_fn (Function): the function decorated by taichi `kernel`.
name (str): Name to identify this kernel in the module. If not
provided, uses the built-in ``__name__`` attribute of `kernel_fn`.
TODO:
* Support external array
"""
name = name or kernel_fn.__name__
kernel = kernel_fn._primal
assert isinstance(kernel, kernel_impl.Kernel)
injected_args = []
for i in range(len(kernel.argument_annotations)):
anno = kernel.argument_annotations[i]
if isinstance(anno, ArgAnyArray):
raise RuntimeError(
'Arg type `ext_arr`/`any_arr` not supported yet')
else:
# For primitive types, we can just inject a dummy value.
injected_args.append(0)
kernel.ensure_compiled(*injected_args)
self._aot_builder.add(name, kernel.kernel_cpp)
# kernel AOT
self._kernels.append(kernel)
@contextmanager
def add_kernel_template(self, kernel_fn):
"""Add a taichi kernel (with template parameters) to the AOT module.
Args:
kernel_fn (Function): the function decorated by taichi `kernel`.
Example:
Usage::
@ti.kernel
def bar_tmpl(a: ti.template()):
x = a
# or y = a
# do something with `x` or `y`
m = ti.aot.Module(arch)
with m.add_kernel_template(bar_tmpl) as kt:
kt.instantiate(a=x)
kt.instantiate(a=y)
@ti.kernel
def bar_tmpl_multiple_args(a: ti.template(), b: ti.template())
x = a
y = b
# do something with `x` and `y`
with m.add_kernel_template(bar_tmpl) as kt:
kt.instantiate(a=x, b=y)
TODO:
* Support external array
"""
kt = KernelTemplate(kernel_fn, self)
yield kt
def save(self, filepath, filename):
"""
Args:
filepath (str): path to a folder to store aot files.
filename (str): filename prefix for stored aot files.
"""
filepath = str(PurePosixPath(Path(filepath).resolve()))
self._aot_builder.dump(filepath, filename)
| from contextlib import contextmanager
from pathlib import Path, PurePosixPath
from taichi.lang import impl, kernel_impl
from taichi.lang.field import ScalarField
from taichi.lang.matrix import MatrixField
from taichi.type.annotations import ArgAnyArray, template
class KernelTemplate:
def __init__(self, kernel_fn, aot_module):
self._kernel_fn = kernel_fn
self._aot_module = aot_module
@staticmethod
def keygen(v, key_p, fields):
if isinstance(v, (int, float, bool)):
key_p += '=' + str(v) + '/'
return key_p
for ky, val in fields:
if (val is v):
key_p += <KEY>
return key_p
raise RuntimeError('Arg type must be of type int/float/boolean' +
'or taichi field. Type ' + str(type(v)) +
' is not supported')
def instantiate(self, **kwargs):
name = self._kernel_fn.__name__
kernel = self._kernel_fn._primal
assert isinstance(kernel, kernel_impl.Kernel)
injected_args = []
key_p = ''
anno_index = 0
template_args = {}
for index, (key, value) in enumerate(kwargs.items()):
template_args[index] = (key, value)
for i in range(len(kernel.argument_annotations)):
anno = kernel.argument_annotations[i]
if isinstance(anno, template):
(k, v) = template_args[anno_index]
key_p += k
key_p = self.keygen(v, key_p, self._aot_module._fields.items())
injected_args.append(v)
anno_index += 1
else:
injected_args.append(0)
kernel.ensure_compiled(*injected_args)
self._aot_module._aot_builder.add_kernel_template(
name, key_p, kernel.kernel_cpp)
# kernel AOT
self._aot_module._kernels.append(kernel)
class Module:
"""An AOT module to save and load Taichi kernels.
This module serializes the Taichi kernels for a specific arch. The
serialized module can later be loaded to run on that backend, without the
Python environment.
Example:
Usage::
m = ti.aot.Module(ti.metal)
m.add_kernel(foo)
m.add_kernel(bar)
m.save('/path/to/module')
# Now the module file '/path/to/module' contains the Metal kernels
# for running ``foo`` and ``bar``.
"""
def __init__(self, arch):
"""Creates a new AOT module instance
Args:
arch: Target backend architecture. This is ignored for now. The AOT
backend still uses the one specified in :func:`~taichi.lang.init`.
"""
self._arch = arch
self._kernels = []
self._fields = {}
rtm = impl.get_runtime()
rtm._finalize_root_fb_for_aot()
self._aot_builder = rtm.prog.make_aot_module_builder(arch)
def add_field(self, name, field):
"""Add a taichi field to the AOT module.
Args:
name: name of taichi field
field: taichi field
Example:
Usage::
a = ti.field(ti.f32, shape=(4,4))
b = ti.field("something")
m.add_field(a)
m.add_field(b)
# Must add in sequence
"""
is_scalar = True
self._fields[name] = field
column_num = 1
row_num = 1
if isinstance(field, MatrixField):
is_scalar = False
row_num = field.m
column_num = field.n
else:
assert isinstance(field, ScalarField)
self._aot_builder.add_field(name, field.snode.ptr, is_scalar,
field.dtype, field.snode.shape, row_num,
column_num)
def add_kernel(self, kernel_fn, name=None):
"""Add a taichi kernel to the AOT module.
Args:
kernel_fn (Function): the function decorated by taichi `kernel`.
name (str): Name to identify this kernel in the module. If not
provided, uses the built-in ``__name__`` attribute of `kernel_fn`.
TODO:
* Support external array
"""
name = name or kernel_fn.__name__
kernel = kernel_fn._primal
assert isinstance(kernel, kernel_impl.Kernel)
injected_args = []
for i in range(len(kernel.argument_annotations)):
anno = kernel.argument_annotations[i]
if isinstance(anno, ArgAnyArray):
raise RuntimeError(
'Arg type `ext_arr`/`any_arr` not supported yet')
else:
# For primitive types, we can just inject a dummy value.
injected_args.append(0)
kernel.ensure_compiled(*injected_args)
self._aot_builder.add(name, kernel.kernel_cpp)
# kernel AOT
self._kernels.append(kernel)
@contextmanager
def add_kernel_template(self, kernel_fn):
"""Add a taichi kernel (with template parameters) to the AOT module.
Args:
kernel_fn (Function): the function decorated by taichi `kernel`.
Example:
Usage::
@ti.kernel
def bar_tmpl(a: ti.template()):
x = a
# or y = a
# do something with `x` or `y`
m = ti.aot.Module(arch)
with m.add_kernel_template(bar_tmpl) as kt:
kt.instantiate(a=x)
kt.instantiate(a=y)
@ti.kernel
def bar_tmpl_multiple_args(a: ti.template(), b: ti.template())
x = a
y = b
# do something with `x` and `y`
with m.add_kernel_template(bar_tmpl) as kt:
kt.instantiate(a=x, b=y)
TODO:
* Support external array
"""
kt = KernelTemplate(kernel_fn, self)
yield kt
def save(self, filepath, filename):
"""
Args:
filepath (str): path to a folder to store aot files.
filename (str): filename prefix for stored aot files.
"""
filepath = str(PurePosixPath(Path(filepath).resolve()))
self._aot_builder.dump(filepath, filename)
| en | 0.424763 | # kernel AOT An AOT module to save and load Taichi kernels. This module serializes the Taichi kernels for a specific arch. The serialized module can later be loaded to run on that backend, without the Python environment. Example: Usage:: m = ti.aot.Module(ti.metal) m.add_kernel(foo) m.add_kernel(bar) m.save('/path/to/module') # Now the module file '/path/to/module' contains the Metal kernels # for running ``foo`` and ``bar``. Creates a new AOT module instance Args: arch: Target backend architecture. This is ignored for now. The AOT backend still uses the one specified in :func:`~taichi.lang.init`. Add a taichi field to the AOT module. Args: name: name of taichi field field: taichi field Example: Usage:: a = ti.field(ti.f32, shape=(4,4)) b = ti.field("something") m.add_field(a) m.add_field(b) # Must add in sequence Add a taichi kernel to the AOT module. Args: kernel_fn (Function): the function decorated by taichi `kernel`. name (str): Name to identify this kernel in the module. If not provided, uses the built-in ``__name__`` attribute of `kernel_fn`. TODO: * Support external array # For primitive types, we can just inject a dummy value. # kernel AOT Add a taichi kernel (with template parameters) to the AOT module. Args: kernel_fn (Function): the function decorated by taichi `kernel`. Example: Usage:: @ti.kernel def bar_tmpl(a: ti.template()): x = a # or y = a # do something with `x` or `y` m = ti.aot.Module(arch) with m.add_kernel_template(bar_tmpl) as kt: kt.instantiate(a=x) kt.instantiate(a=y) @ti.kernel def bar_tmpl_multiple_args(a: ti.template(), b: ti.template()) x = a y = b # do something with `x` and `y` with m.add_kernel_template(bar_tmpl) as kt: kt.instantiate(a=x, b=y) TODO: * Support external array Args: filepath (str): path to a folder to store aot files. filename (str): filename prefix for stored aot files. | 2.019794 | 2 |
402-Using-IAM-Authentication-with-RDS/cdk-AWS-Cookbook-402/cdk_aws_cookbook_402/cdk_aws_cookbook_402_stack.py | AWSCookbook/Databases | 6 | 6627968 | <reponame>AWSCookbook/Databases<filename>402-Using-IAM-Authentication-with-RDS/cdk-AWS-Cookbook-402/cdk_aws_cookbook_402/cdk_aws_cookbook_402_stack.py
from constructs import Construct
from aws_cdk import (
aws_ec2 as ec2,
aws_s3 as s3,
aws_s3_deployment,
aws_rds as rds,
aws_iam as iam,
Stack,
CfnOutput,
RemovalPolicy
)
class CdkAwsCookbook402Stack(Stack):
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)
# create s3 bucket
s3_Bucket = s3.Bucket(
self,
"AWS-Cookbook-Recipe-402",
removal_policy=RemovalPolicy.DESTROY
)
aws_s3_deployment.BucketDeployment(
self,
'S3Deployment',
destination_bucket=s3_Bucket,
sources=[aws_s3_deployment.Source.asset("./s3_content")],
retain_on_delete=False
)
isolated_subnets = ec2.SubnetConfiguration(
name="ISOLATED",
subnet_type=ec2.SubnetType.PRIVATE_ISOLATED,
cidr_mask=24
)
# create VPC
vpc = ec2.Vpc(
self,
'AWS-Cookbook-VPC',
cidr='10.10.0.0/23',
subnet_configuration=[isolated_subnets]
)
vpc.add_interface_endpoint(
'VPCSecretsManagerInterfaceEndpoint',
service=ec2.InterfaceVpcEndpointAwsService('secretsmanager'), # Find names with - aws ec2 describe-vpc-endpoint-services | jq '.ServiceNames'
private_dns_enabled=True,
subnets=ec2.SubnetSelection(
one_per_az=False,
subnet_type=ec2.SubnetType.PRIVATE_ISOLATED
),
)
vpc.add_interface_endpoint(
'VPCRDSInterfaceEndpoint',
service=ec2.InterfaceVpcEndpointAwsService('rds'), # Find names with - aws ec2 describe-vpc-endpoint-services | jq '.ServiceNames'
private_dns_enabled=True,
subnets=ec2.SubnetSelection(
one_per_az=False,
subnet_type=ec2.SubnetType.PRIVATE_ISOLATED
),
)
vpc.add_gateway_endpoint(
's3GateWayEndPoint',
service=ec2.GatewayVpcEndpointAwsService('s3'),
subnets=[ec2.SubnetSelection(subnet_type=ec2.SubnetType.PRIVATE_ISOLATED)],
)
rds_security_group = ec2.SecurityGroup(
self,
'rds_security_group',
description='Security Group for the RDS Instance',
allow_all_outbound=True,
vpc=vpc
)
rds_instance = rds.DatabaseInstance(
self,
'DBInstance',
engine=rds.DatabaseInstanceEngine.mysql(
version=rds.MysqlEngineVersion.VER_8_0_23
),
instance_type=ec2.InstanceType("m5.large"),
vpc=vpc,
database_name='AWSCookbookRecipe402',
instance_identifier='awscookbookrecipe402',
delete_automated_backups=True,
deletion_protection=False,
removal_policy=RemovalPolicy.DESTROY,
allocated_storage=8,
vpc_subnets=ec2.SubnetSelection(
one_per_az=False,
subnet_type=ec2.SubnetType.PRIVATE_ISOLATED
),
security_groups=[rds_security_group]
)
# -------- Begin EC2 Helper ---------
vpc.add_interface_endpoint(
'VPCSSMInterfaceEndpoint',
service=ec2.InterfaceVpcEndpointAwsService('ssm'), # Find names with - aws ec2 describe-vpc-endpoint-services | jq '.ServiceNames'
private_dns_enabled=True,
subnets=ec2.SubnetSelection(
one_per_az=False,
subnet_type=ec2.SubnetType.PRIVATE_ISOLATED
),
)
vpc.add_interface_endpoint(
'VPCEC2MessagesInterfaceEndpoint',
service=ec2.InterfaceVpcEndpointAwsService('ec2messages'), # Find names with - aws ec2 describe-vpc-endpoint-services | jq '.ServiceNames'
private_dns_enabled=True,
subnets=ec2.SubnetSelection(
one_per_az=False,
subnet_type=ec2.SubnetType.PRIVATE_ISOLATED
),
)
vpc.add_interface_endpoint(
'VPCSSMMessagesInterfaceEndpoint',
service=ec2.InterfaceVpcEndpointAwsService('ssmmessages'), # Find names with - aws ec2 describe-vpc-endpoint-services | jq '.ServiceNames'
private_dns_enabled=True,
subnets=ec2.SubnetSelection(
one_per_az=False,
subnet_type=ec2.SubnetType.PRIVATE_ISOLATED
),
)
ami = ec2.MachineImage.latest_amazon_linux(
generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2,
edition=ec2.AmazonLinuxEdition.STANDARD,
virtualization=ec2.AmazonLinuxVirt.HVM,
storage=ec2.AmazonLinuxStorage.GENERAL_PURPOSE
)
iam_role = iam.Role(self, "InstanceSSM", assumed_by=iam.ServicePrincipal("ec2.amazonaws.com"))
iam_role.add_managed_policy(iam.ManagedPolicy.from_aws_managed_policy_name("service-role/AmazonEC2RoleforSSM"))
instance = ec2.Instance(
self,
"Instance",
instance_type=ec2.InstanceType("t3.nano"),
machine_image=ami,
role=iam_role,
vpc=vpc,
)
CfnOutput(
self,
'InstanceId',
value=instance.instance_id
)
# -------- End EC2 Helper ---------
rds_instance.secret.grant_read(instance)
# allow connection from ec2 instance to DB
rds_instance.connections.allow_from(
instance.connections, ec2.Port.tcp(3306), "Ingress")
s3_Bucket.grant_read(instance)
# outputs
CfnOutput(
self,
'VpcId',
value=vpc.vpc_id
)
CfnOutput(
self,
'RdsSecurityGroup',
value=rds_security_group.security_group_id
)
CfnOutput(
self,
'RdsDatabaseId',
value=rds_instance.instance_identifier
)
CfnOutput(
self,
'RdsEndpoint',
value=rds_instance.db_instance_endpoint_address
)
CfnOutput(
self,
'RdsPort',
value=rds_instance.db_instance_endpoint_port
)
CfnOutput(
self,
'BucketName',
value=s3_Bucket.bucket_name
)
isolated_subnets = vpc.select_subnets(subnet_type=ec2.SubnetType.PRIVATE_ISOLATED)
CfnOutput(
self,
'IsolatedSubnets',
value=', '.join(map(str, isolated_subnets.subnet_ids))
)
CfnOutput(
self,
'InstanceRoleName',
value=iam_role.role_name
)
CfnOutput(
self,
'RdsSecretArn',
value=rds_instance.secret.secret_full_arn
)
| from constructs import Construct
from aws_cdk import (
aws_ec2 as ec2,
aws_s3 as s3,
aws_s3_deployment,
aws_rds as rds,
aws_iam as iam,
Stack,
CfnOutput,
RemovalPolicy
)
class CdkAwsCookbook402Stack(Stack):
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)
# create s3 bucket
s3_Bucket = s3.Bucket(
self,
"AWS-Cookbook-Recipe-402",
removal_policy=RemovalPolicy.DESTROY
)
aws_s3_deployment.BucketDeployment(
self,
'S3Deployment',
destination_bucket=s3_Bucket,
sources=[aws_s3_deployment.Source.asset("./s3_content")],
retain_on_delete=False
)
isolated_subnets = ec2.SubnetConfiguration(
name="ISOLATED",
subnet_type=ec2.SubnetType.PRIVATE_ISOLATED,
cidr_mask=24
)
# create VPC
vpc = ec2.Vpc(
self,
'AWS-Cookbook-VPC',
cidr='10.10.0.0/23',
subnet_configuration=[isolated_subnets]
)
vpc.add_interface_endpoint(
'VPCSecretsManagerInterfaceEndpoint',
service=ec2.InterfaceVpcEndpointAwsService('secretsmanager'), # Find names with - aws ec2 describe-vpc-endpoint-services | jq '.ServiceNames'
private_dns_enabled=True,
subnets=ec2.SubnetSelection(
one_per_az=False,
subnet_type=ec2.SubnetType.PRIVATE_ISOLATED
),
)
vpc.add_interface_endpoint(
'VPCRDSInterfaceEndpoint',
service=ec2.InterfaceVpcEndpointAwsService('rds'), # Find names with - aws ec2 describe-vpc-endpoint-services | jq '.ServiceNames'
private_dns_enabled=True,
subnets=ec2.SubnetSelection(
one_per_az=False,
subnet_type=ec2.SubnetType.PRIVATE_ISOLATED
),
)
vpc.add_gateway_endpoint(
's3GateWayEndPoint',
service=ec2.GatewayVpcEndpointAwsService('s3'),
subnets=[ec2.SubnetSelection(subnet_type=ec2.SubnetType.PRIVATE_ISOLATED)],
)
rds_security_group = ec2.SecurityGroup(
self,
'rds_security_group',
description='Security Group for the RDS Instance',
allow_all_outbound=True,
vpc=vpc
)
rds_instance = rds.DatabaseInstance(
self,
'DBInstance',
engine=rds.DatabaseInstanceEngine.mysql(
version=rds.MysqlEngineVersion.VER_8_0_23
),
instance_type=ec2.InstanceType("m5.large"),
vpc=vpc,
database_name='AWSCookbookRecipe402',
instance_identifier='awscookbookrecipe402',
delete_automated_backups=True,
deletion_protection=False,
removal_policy=RemovalPolicy.DESTROY,
allocated_storage=8,
vpc_subnets=ec2.SubnetSelection(
one_per_az=False,
subnet_type=ec2.SubnetType.PRIVATE_ISOLATED
),
security_groups=[rds_security_group]
)
# -------- Begin EC2 Helper ---------
vpc.add_interface_endpoint(
'VPCSSMInterfaceEndpoint',
service=ec2.InterfaceVpcEndpointAwsService('ssm'), # Find names with - aws ec2 describe-vpc-endpoint-services | jq '.ServiceNames'
private_dns_enabled=True,
subnets=ec2.SubnetSelection(
one_per_az=False,
subnet_type=ec2.SubnetType.PRIVATE_ISOLATED
),
)
vpc.add_interface_endpoint(
'VPCEC2MessagesInterfaceEndpoint',
service=ec2.InterfaceVpcEndpointAwsService('ec2messages'), # Find names with - aws ec2 describe-vpc-endpoint-services | jq '.ServiceNames'
private_dns_enabled=True,
subnets=ec2.SubnetSelection(
one_per_az=False,
subnet_type=ec2.SubnetType.PRIVATE_ISOLATED
),
)
vpc.add_interface_endpoint(
'VPCSSMMessagesInterfaceEndpoint',
service=ec2.InterfaceVpcEndpointAwsService('ssmmessages'), # Find names with - aws ec2 describe-vpc-endpoint-services | jq '.ServiceNames'
private_dns_enabled=True,
subnets=ec2.SubnetSelection(
one_per_az=False,
subnet_type=ec2.SubnetType.PRIVATE_ISOLATED
),
)
ami = ec2.MachineImage.latest_amazon_linux(
generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2,
edition=ec2.AmazonLinuxEdition.STANDARD,
virtualization=ec2.AmazonLinuxVirt.HVM,
storage=ec2.AmazonLinuxStorage.GENERAL_PURPOSE
)
iam_role = iam.Role(self, "InstanceSSM", assumed_by=iam.ServicePrincipal("ec2.amazonaws.com"))
iam_role.add_managed_policy(iam.ManagedPolicy.from_aws_managed_policy_name("service-role/AmazonEC2RoleforSSM"))
instance = ec2.Instance(
self,
"Instance",
instance_type=ec2.InstanceType("t3.nano"),
machine_image=ami,
role=iam_role,
vpc=vpc,
)
CfnOutput(
self,
'InstanceId',
value=instance.instance_id
)
# -------- End EC2 Helper ---------
rds_instance.secret.grant_read(instance)
# allow connection from ec2 instance to DB
rds_instance.connections.allow_from(
instance.connections, ec2.Port.tcp(3306), "Ingress")
s3_Bucket.grant_read(instance)
# outputs
CfnOutput(
self,
'VpcId',
value=vpc.vpc_id
)
CfnOutput(
self,
'RdsSecurityGroup',
value=rds_security_group.security_group_id
)
CfnOutput(
self,
'RdsDatabaseId',
value=rds_instance.instance_identifier
)
CfnOutput(
self,
'RdsEndpoint',
value=rds_instance.db_instance_endpoint_address
)
CfnOutput(
self,
'RdsPort',
value=rds_instance.db_instance_endpoint_port
)
CfnOutput(
self,
'BucketName',
value=s3_Bucket.bucket_name
)
isolated_subnets = vpc.select_subnets(subnet_type=ec2.SubnetType.PRIVATE_ISOLATED)
CfnOutput(
self,
'IsolatedSubnets',
value=', '.join(map(str, isolated_subnets.subnet_ids))
)
CfnOutput(
self,
'InstanceRoleName',
value=iam_role.role_name
)
CfnOutput(
self,
'RdsSecretArn',
value=rds_instance.secret.secret_full_arn
) | en | 0.408306 | # create s3 bucket # create VPC # Find names with - aws ec2 describe-vpc-endpoint-services | jq '.ServiceNames' # Find names with - aws ec2 describe-vpc-endpoint-services | jq '.ServiceNames' # -------- Begin EC2 Helper --------- # Find names with - aws ec2 describe-vpc-endpoint-services | jq '.ServiceNames' # Find names with - aws ec2 describe-vpc-endpoint-services | jq '.ServiceNames' # Find names with - aws ec2 describe-vpc-endpoint-services | jq '.ServiceNames' # -------- End EC2 Helper --------- # allow connection from ec2 instance to DB # outputs | 1.925596 | 2 |
pydmga/container.py | robsontpm/BIOPHYS-cholesterol-association | 0 | 6627969 | <filename>pydmga/container.py
import geometry
import dmga2py
#TODO: make get_particles(subset = None) for Container
#TODO: dodac klasy reprezentujace kinetic_structure
class ContainerIterator:
'''
used to iterate over Container like::
for particle in container:
pass
:param container: Container for iteration
'''
def __init__(self, container):
self._container = container
self._container_handle = container._container_handle
self._i = -1
self._max = container.size()
'''
:return: self
'''
def __iter__(self):
return self
'''
:return: next particle as a tuple of (id, x, y, z)
'''
def next(self):
self._i += 1
if (self._i >= self._max):
raise StopIteration
return dmga2py.basic_container_get(self._container_handle, self._i)
class Container:
'''
This holds particles in simulations
'''
def __init__(self, geometry):
'''
creates new container
:param geometry: Geometry object to define the simulation box
'''
self.geometry = geometry;
self._container_handle = dmga2py.new_basic_container(geometry._geometry_handle)
self._size = 0
def size(self):
'''
:return: number of particles in this container
'''
#TODO: maybe use the api?
return self._size;
#returns number of affected items
def add(self, *args):
'''
Adds elements to this container.
May work on many different elements:
* add(tuple): tuple must contain 5 elements: (id, x, y, z, r), id is integer, others are double
* add(iterable): iterable must contain tuples (as above)
* add(id, z, y, z, r): elements as in tuple above
* add(id, z, y, z): as above, but r is assumed to be 1.0
Rises TypeError when elements are not tuples.
'''
if len(args) == 1 and isinstance(args[0], tuple):
(id, x, y, z, r) = args[0]
elif len(args) == 1:
try:
for (id, x, y, z, r) in args[0]:
self.add_by_coords(id, x, y, z, r)
return
except TypeError:
raise TypeError("Container::add: Not an iterable of tuples!")
elif len(args) == 5:
id = args[0]
x = args[1]
y = args[2]
z = args[3]
r = args[4]
elif len(args) == 4:
id = args[0]
x = args[1]
y = args[2]
z = args[3]
r = 1.0 #default
else:
raise TypeError("Container::add: cannot add that type of item!")
self.add_by_coords(id, x, y, z, r)
def add_by_coords(self, id, x, y, z, r):
'''
for internal use, adds one element
'''
self._size += 1 #TODO: maybe use the api?
(id, x, y, z, r) = self.geometry.transform(id, x, y, z, r)
dmga2py.basic_container_add(self._container_handle, id, x, y, z, r)
def add_raw(self, id, x, y, z, r):
'''
This adds one element without doing transformation on coordinates
for boosting inserts, when we know that no transform is needed
and we really need the speed...
'''
self._size += 1 #TODO: maybe use the api?
dmga2py.basic_container_add(self._container_handle, id, x, y, z, r)
def get(self, number):
'''
Get the i-th inserted particle as a tuple (id, x, y, z)
:param number: integer in range [0, size())
:return: a particle with a given number
**NOTE** number is not an ID! To get element by ID use find(ID)
'''
return dmga2py.basic_container_get(self._container_handle, number)
def find(self, id):
'''
Returns element with given ID
:param id: is integer
'''
return dmga2py.basic_container_find(self._container_handle, id)
def __del__(self):
'''
free all C++ objects if necessary
'''
# print "freeing container_handle", self._container_handle
dmga2py.free_object(self._container_handle)
def __iter__(self):
'''
makes this class iterable
'''
return ContainerIterator(self)
| <filename>pydmga/container.py
import geometry
import dmga2py
#TODO: make get_particles(subset = None) for Container
#TODO: dodac klasy reprezentujace kinetic_structure
class ContainerIterator:
'''
used to iterate over Container like::
for particle in container:
pass
:param container: Container for iteration
'''
def __init__(self, container):
self._container = container
self._container_handle = container._container_handle
self._i = -1
self._max = container.size()
'''
:return: self
'''
def __iter__(self):
return self
'''
:return: next particle as a tuple of (id, x, y, z)
'''
def next(self):
self._i += 1
if (self._i >= self._max):
raise StopIteration
return dmga2py.basic_container_get(self._container_handle, self._i)
class Container:
'''
This holds particles in simulations
'''
def __init__(self, geometry):
'''
creates new container
:param geometry: Geometry object to define the simulation box
'''
self.geometry = geometry;
self._container_handle = dmga2py.new_basic_container(geometry._geometry_handle)
self._size = 0
def size(self):
'''
:return: number of particles in this container
'''
#TODO: maybe use the api?
return self._size;
#returns number of affected items
def add(self, *args):
'''
Adds elements to this container.
May work on many different elements:
* add(tuple): tuple must contain 5 elements: (id, x, y, z, r), id is integer, others are double
* add(iterable): iterable must contain tuples (as above)
* add(id, z, y, z, r): elements as in tuple above
* add(id, z, y, z): as above, but r is assumed to be 1.0
Rises TypeError when elements are not tuples.
'''
if len(args) == 1 and isinstance(args[0], tuple):
(id, x, y, z, r) = args[0]
elif len(args) == 1:
try:
for (id, x, y, z, r) in args[0]:
self.add_by_coords(id, x, y, z, r)
return
except TypeError:
raise TypeError("Container::add: Not an iterable of tuples!")
elif len(args) == 5:
id = args[0]
x = args[1]
y = args[2]
z = args[3]
r = args[4]
elif len(args) == 4:
id = args[0]
x = args[1]
y = args[2]
z = args[3]
r = 1.0 #default
else:
raise TypeError("Container::add: cannot add that type of item!")
self.add_by_coords(id, x, y, z, r)
def add_by_coords(self, id, x, y, z, r):
'''
for internal use, adds one element
'''
self._size += 1 #TODO: maybe use the api?
(id, x, y, z, r) = self.geometry.transform(id, x, y, z, r)
dmga2py.basic_container_add(self._container_handle, id, x, y, z, r)
def add_raw(self, id, x, y, z, r):
'''
This adds one element without doing transformation on coordinates
for boosting inserts, when we know that no transform is needed
and we really need the speed...
'''
self._size += 1 #TODO: maybe use the api?
dmga2py.basic_container_add(self._container_handle, id, x, y, z, r)
def get(self, number):
'''
Get the i-th inserted particle as a tuple (id, x, y, z)
:param number: integer in range [0, size())
:return: a particle with a given number
**NOTE** number is not an ID! To get element by ID use find(ID)
'''
return dmga2py.basic_container_get(self._container_handle, number)
def find(self, id):
'''
Returns element with given ID
:param id: is integer
'''
return dmga2py.basic_container_find(self._container_handle, id)
def __del__(self):
'''
free all C++ objects if necessary
'''
# print "freeing container_handle", self._container_handle
dmga2py.free_object(self._container_handle)
def __iter__(self):
'''
makes this class iterable
'''
return ContainerIterator(self)
| en | 0.71894 | #TODO: make get_particles(subset = None) for Container #TODO: dodac klasy reprezentujace kinetic_structure used to iterate over Container like::
for particle in container:
pass
:param container: Container for iteration :return: self :return: next particle as a tuple of (id, x, y, z) This holds particles in simulations creates new container
:param geometry: Geometry object to define the simulation box :return: number of particles in this container #TODO: maybe use the api? #returns number of affected items Adds elements to this container.
May work on many different elements:
* add(tuple): tuple must contain 5 elements: (id, x, y, z, r), id is integer, others are double
* add(iterable): iterable must contain tuples (as above)
* add(id, z, y, z, r): elements as in tuple above
* add(id, z, y, z): as above, but r is assumed to be 1.0
Rises TypeError when elements are not tuples. #default for internal use, adds one element #TODO: maybe use the api? This adds one element without doing transformation on coordinates
for boosting inserts, when we know that no transform is needed
and we really need the speed... #TODO: maybe use the api? Get the i-th inserted particle as a tuple (id, x, y, z)
:param number: integer in range [0, size())
:return: a particle with a given number
**NOTE** number is not an ID! To get element by ID use find(ID) Returns element with given ID
:param id: is integer free all C++ objects if necessary # print "freeing container_handle", self._container_handle makes this class iterable | 2.974475 | 3 |
scm-plugins/scm-hg-plugin/src/main/resources/sonia/scm/python/version.py | awltux/scm-manager | 0 | 6627970 | <gh_stars>0
#
# Copyright (c) 2010, <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# 3. Neither the name of SCM-Manager; nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# http://bitbucket.org/sdorra/scm-manager
#
#
import sys
from mercurial import util
from xml.dom.minidom import Document
pyVersion = sys.version_info
pyVersion = str(pyVersion.major) + "." + str(pyVersion.minor) + "." + str(pyVersion.micro)
hgVersion = util.version()
doc = Document()
root = doc.createElement('version')
pyNode = doc.createElement('python')
pyNode.appendChild(doc.createTextNode(pyVersion))
root.appendChild(pyNode)
hgNode = doc.createElement('mercurial')
hgNode.appendChild(doc.createTextNode(hgVersion))
root.appendChild(hgNode)
doc.appendChild(root)
doc.writexml(sys.stdout, encoding='UTF-8') | #
# Copyright (c) 2010, <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# 3. Neither the name of SCM-Manager; nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# http://bitbucket.org/sdorra/scm-manager
#
#
import sys
from mercurial import util
from xml.dom.minidom import Document
pyVersion = sys.version_info
pyVersion = str(pyVersion.major) + "." + str(pyVersion.minor) + "." + str(pyVersion.micro)
hgVersion = util.version()
doc = Document()
root = doc.createElement('version')
pyNode = doc.createElement('python')
pyNode.appendChild(doc.createTextNode(pyVersion))
root.appendChild(pyNode)
hgNode = doc.createElement('mercurial')
hgNode.appendChild(doc.createTextNode(hgVersion))
root.appendChild(hgNode)
doc.appendChild(root)
doc.writexml(sys.stdout, encoding='UTF-8') | en | 0.714628 | # # Copyright (c) 2010, <NAME> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # 3. Neither the name of SCM-Manager; nor the names of its # contributors may be used to endorse or promote products derived from this # software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # http://bitbucket.org/sdorra/scm-manager # # | 1.307606 | 1 |
tests/plugins/fail_htlcs.py | jooray/lightning | 1 | 6627971 | <reponame>jooray/lightning
#!/usr/bin/env python3
from lightning import Plugin
plugin = Plugin()
@plugin.hook("htlc_accepted")
def on_htlc_accepted(htlc, onion, plugin):
plugin.log("Failing htlc on purpose")
plugin.log("onion: %r" % (onion))
return {"result": "fail", "failure_code": 16399}
plugin.run()
| #!/usr/bin/env python3
from lightning import Plugin
plugin = Plugin()
@plugin.hook("htlc_accepted")
def on_htlc_accepted(htlc, onion, plugin):
plugin.log("Failing htlc on purpose")
plugin.log("onion: %r" % (onion))
return {"result": "fail", "failure_code": 16399}
plugin.run() | fr | 0.221828 | #!/usr/bin/env python3 | 2.004856 | 2 |
scipy_test.py | hustic/Armageddon | 0 | 6627972 | <filename>scipy_test.py<gh_stars>0
import numpy as np
from scipy.integrate import solve_ivp
import pandas as pd
def sci_sol(radius=10, velocity=20e3, density=3000, strength=10e5, angle=45, init_altitude=100e3, distance=0, dt=0.05, fragmentation=True, num_scheme='RK45', radians=False, C_D=1., C_H=0.1, Q=1e7, C_L=1e-3, R_p=6371e3, g=9.81, rho_0=1.2, H=8000, alpha=0.3):
'''
Solves analytical solution for meteroid impact
Parameters
----------
radius : float
The radius of the asteroid in meters
velocity : float
The entery speed of the asteroid in meters/second
density : float
The density of the asteroid in kg/m^3
strength : float
The strength of the asteroid (i.e., the ram pressure above which
fragmentation and spreading occurs) in N/m^2 (Pa)
angle : float
The initial trajectory angle of the asteroid to the horizontal
By default, input is in degrees. If 'radians' is set to True, the
input should be in radians
init_altitude : float, optional
Initial altitude in m
radians : logical, optional
Whether angles should be given in degrees or radians. Default=False
Angles returned in the DataFrame will have the same units as the
input
Returns
-------
Result : DataFrame
pandas dataFrame with collumns:
altitude, velocity, dedz
'''
if radians is False: # converts degrees to radians
angle = angle * (np.pi) / 180
mass = 4 / 3 * np.pi * (radius ** 3) * density
y = np.array([velocity, mass, angle, init_altitude, distance, radius])
rho_a = lambda x: rho_0 * np.exp(-x/H)
def f(self, y):
'''
0: velocity
1: mass
2: angle
3: altitude
4: distance
5: radius
'''
f = np.zeros_like(y)
f[0] = - (C_D * rho_a(y[3]) * y[0]**2 * np.pi * y[5]**2) / (2 * y[1]) + (g * np.sin(y[2]))
f[1] = - (C_H * rho_a(y[3]) * np.pi * y[5]**2 * y[0]**3) / (2 * Q)
f[2] = g * np.cos(y[2]) / y[0] - (C_L * rho_a(y[3]) * np.pi * y[5]**2 * y[0]) / (2 * y[1]) - (y[0] * np.cos(y[2])) / (R_p + y[3])
f[3] = - y[0] * np.sin(y[2])
f[4] = (y[0] * np.cos(y[2])) / (1 + y[3] / R_p)
if fragmentation == True and strength <= (rho_a(y[3]) * y[0]**2):
f[5] = np.sqrt(7/2 * alpha * rho_a(y[3]) / density) * y[0]
else:
f[5] = 0
return f
tmax = 12000
t = np.arange(0, tmax, dt)
result = solve_ivp(f, [0, tmax], y, method=num_scheme, t_eval=t)
result = result.y
dedz = np.zeros(len(result[0]))
ke = ((1/2 * result[1, 1:] * result[0, 1:]**2) - (1 / 2 * result[1, :-1] * result[0, :-1]**2)) / 4.184e12
alt = (result[3, 1:] - result[3, :-1]) / 1e3
dedz[1:] = ke / alt
i = np.where(dedz < 0)
dedz[i] = 0
result = pd.DataFrame({'velocity': result[0], 'mass': result[1], 'angle': result[2], 'altitude': result[3], 'distance': result[4], 'radius': result[5], 'time': t, 'dedz': dedz})
return result
| <filename>scipy_test.py<gh_stars>0
import numpy as np
from scipy.integrate import solve_ivp
import pandas as pd
def sci_sol(radius=10, velocity=20e3, density=3000, strength=10e5, angle=45, init_altitude=100e3, distance=0, dt=0.05, fragmentation=True, num_scheme='RK45', radians=False, C_D=1., C_H=0.1, Q=1e7, C_L=1e-3, R_p=6371e3, g=9.81, rho_0=1.2, H=8000, alpha=0.3):
'''
Solves analytical solution for meteroid impact
Parameters
----------
radius : float
The radius of the asteroid in meters
velocity : float
The entery speed of the asteroid in meters/second
density : float
The density of the asteroid in kg/m^3
strength : float
The strength of the asteroid (i.e., the ram pressure above which
fragmentation and spreading occurs) in N/m^2 (Pa)
angle : float
The initial trajectory angle of the asteroid to the horizontal
By default, input is in degrees. If 'radians' is set to True, the
input should be in radians
init_altitude : float, optional
Initial altitude in m
radians : logical, optional
Whether angles should be given in degrees or radians. Default=False
Angles returned in the DataFrame will have the same units as the
input
Returns
-------
Result : DataFrame
pandas dataFrame with collumns:
altitude, velocity, dedz
'''
if radians is False: # converts degrees to radians
angle = angle * (np.pi) / 180
mass = 4 / 3 * np.pi * (radius ** 3) * density
y = np.array([velocity, mass, angle, init_altitude, distance, radius])
rho_a = lambda x: rho_0 * np.exp(-x/H)
def f(self, y):
'''
0: velocity
1: mass
2: angle
3: altitude
4: distance
5: radius
'''
f = np.zeros_like(y)
f[0] = - (C_D * rho_a(y[3]) * y[0]**2 * np.pi * y[5]**2) / (2 * y[1]) + (g * np.sin(y[2]))
f[1] = - (C_H * rho_a(y[3]) * np.pi * y[5]**2 * y[0]**3) / (2 * Q)
f[2] = g * np.cos(y[2]) / y[0] - (C_L * rho_a(y[3]) * np.pi * y[5]**2 * y[0]) / (2 * y[1]) - (y[0] * np.cos(y[2])) / (R_p + y[3])
f[3] = - y[0] * np.sin(y[2])
f[4] = (y[0] * np.cos(y[2])) / (1 + y[3] / R_p)
if fragmentation == True and strength <= (rho_a(y[3]) * y[0]**2):
f[5] = np.sqrt(7/2 * alpha * rho_a(y[3]) / density) * y[0]
else:
f[5] = 0
return f
tmax = 12000
t = np.arange(0, tmax, dt)
result = solve_ivp(f, [0, tmax], y, method=num_scheme, t_eval=t)
result = result.y
dedz = np.zeros(len(result[0]))
ke = ((1/2 * result[1, 1:] * result[0, 1:]**2) - (1 / 2 * result[1, :-1] * result[0, :-1]**2)) / 4.184e12
alt = (result[3, 1:] - result[3, :-1]) / 1e3
dedz[1:] = ke / alt
i = np.where(dedz < 0)
dedz[i] = 0
result = pd.DataFrame({'velocity': result[0], 'mass': result[1], 'angle': result[2], 'altitude': result[3], 'distance': result[4], 'radius': result[5], 'time': t, 'dedz': dedz})
return result
| en | 0.678155 | Solves analytical solution for meteroid impact Parameters ---------- radius : float The radius of the asteroid in meters velocity : float The entery speed of the asteroid in meters/second density : float The density of the asteroid in kg/m^3 strength : float The strength of the asteroid (i.e., the ram pressure above which fragmentation and spreading occurs) in N/m^2 (Pa) angle : float The initial trajectory angle of the asteroid to the horizontal By default, input is in degrees. If 'radians' is set to True, the input should be in radians init_altitude : float, optional Initial altitude in m radians : logical, optional Whether angles should be given in degrees or radians. Default=False Angles returned in the DataFrame will have the same units as the input Returns ------- Result : DataFrame pandas dataFrame with collumns: altitude, velocity, dedz # converts degrees to radians 0: velocity 1: mass 2: angle 3: altitude 4: distance 5: radius | 3.144808 | 3 |
unpack.py | ahrnbom/rabloromi | 1 | 6627973 | <filename>unpack.py
# You only need to run this once!
from pathlib import Path
from zipfile import ZipFile
cards_folder = Path('static') / 'cards'
def verify():
if not cards_folder.is_dir():
return False
files = [f for f in cards_folder.glob('*.png') if f.is_file()]
if len(files) >= 1:
return True
return False
def convert(zip_style):
if zip_style == "back":
return zip_style
map_types = {'ace': '1', 'king': 'k', 'queen': 'q', 'jack': 'j'}
if "joker" in zip_style:
card_col, _ = zip_style.split('_')
card_type = "joker"
card_suit = ""
if card_col == "red":
card_suit = "2"
else:
card_type, _, card_suit = zip_style.split('_')
card_suit = card_suit[0]
if card_type in map_types:
card_type = map_types[card_type]
return card_type + card_suit
def unpack_files():
if not verify():
print("Extracting files...")
cards_zip = Path('static') / 'cards.zip'
cards_folder.mkdir(exist_ok=True)
for path in cards_folder.glob('*.svg'):
path.unlink()
for path in cards_folder.glob('*.png'):
path.unlink()
with ZipFile(cards_zip) as z:
for file_name in z.namelist():
z.extract(file_name, cards_folder)
file_path = cards_folder / file_name
assert(file_path.is_file())
new_path = cards_folder / f"{convert(file_path.stem)}.png"
file_path.rename(new_path)
assert(new_path.is_file())
print(f"Extracted {new_path}...")
print("Done!")
if __name__ == "__main__":
unpack_files()
| <filename>unpack.py
# You only need to run this once!
from pathlib import Path
from zipfile import ZipFile
cards_folder = Path('static') / 'cards'
def verify():
if not cards_folder.is_dir():
return False
files = [f for f in cards_folder.glob('*.png') if f.is_file()]
if len(files) >= 1:
return True
return False
def convert(zip_style):
if zip_style == "back":
return zip_style
map_types = {'ace': '1', 'king': 'k', 'queen': 'q', 'jack': 'j'}
if "joker" in zip_style:
card_col, _ = zip_style.split('_')
card_type = "joker"
card_suit = ""
if card_col == "red":
card_suit = "2"
else:
card_type, _, card_suit = zip_style.split('_')
card_suit = card_suit[0]
if card_type in map_types:
card_type = map_types[card_type]
return card_type + card_suit
def unpack_files():
if not verify():
print("Extracting files...")
cards_zip = Path('static') / 'cards.zip'
cards_folder.mkdir(exist_ok=True)
for path in cards_folder.glob('*.svg'):
path.unlink()
for path in cards_folder.glob('*.png'):
path.unlink()
with ZipFile(cards_zip) as z:
for file_name in z.namelist():
z.extract(file_name, cards_folder)
file_path = cards_folder / file_name
assert(file_path.is_file())
new_path = cards_folder / f"{convert(file_path.stem)}.png"
file_path.rename(new_path)
assert(new_path.is_file())
print(f"Extracted {new_path}...")
print("Done!")
if __name__ == "__main__":
unpack_files()
| en | 0.925495 | # You only need to run this once! | 3.199125 | 3 |
install_compiler.py | ssrg-vt/mklinux-compiler | 0 | 6627974 | <filename>install_compiler.py<gh_stars>0
#!/usr/bin/env python2
from __future__ import print_function
import argparse
import os, os.path
import shutil
import subprocess
import sys
import tarfile
import urllib
import multiprocessing
#================================================
# GLOBALS
#================================================
# LLVM 3.7.1 SVN URL
llvm_url = 'http://llvm.org/svn/llvm-project/llvm/tags/RELEASE_371/final'
# Clang SVN URL
clang_url = 'http://llvm.org/svn/llvm-project/cfe/tags/RELEASE_371/final'
# Binutils 2.27 URL
binutils_url = 'http://ftp.gnu.org/gnu/binutils/binutils-2.27.tar.bz2'
#================================================
# LOG CLASS
# Logs all output to outfile as well as stdout
#================================================
class Log(object):
def __init__(self, name, mode):
self.file = open(name, mode)
def __del__(self):
self.file.close()
def write(self, data):
self.file.write(data)
#================================================
# ARGUMENT PARSING
#================================================
def setup_argument_parsing():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
config_opts = parser.add_argument_group('Configuration Options')
config_opts.add_argument("--base-path",
help="Base path of popcorn-compiler repo",
default=os.getcwd(),
dest="base_path")
config_opts.add_argument("--install-path",
help="Install path of Popcorn compiler",
default="/usr/local/popcorn",
dest="install_path")
config_opts.add_argument("--threads",
help="Number of threads to build compiler with",
type=int,
default=multiprocessing.cpu_count())
process_opts = parser.add_argument_group('Process Options (skip steps)')
process_opts.add_argument("--skip-prereq-check",
help="Skip checking for prerequisites (see README)",
action="store_true",
dest="skip_prereq_check")
process_opts.add_argument("--skip-llvm-clang-install",
help="Skip installation of LLVM and Clang",
action="store_true",
dest="skip_llvm_clang_install")
process_opts.add_argument("--skip-binutils-install",
help="Skip installation of binutils",
action="store_true",
dest="skip_binutils_install")
process_opts.add_argument("--skip-libraries-install",
help="Skip installation of libraries",
action="store_true",
dest="skip_libraries_install")
process_opts.add_argument("--skip-tools-install",
help="Skip installation of tools",
action="store_true",
dest="skip_tools_install")
process_opts.add_argument("--skip-utils-install",
help="Skip installation of util scripts",
action="store_true",
dest="skip_utils_install")
process_opts.add_argument("--skip-namespace",
help="Skip building namespace tools",
action="store_true",
dest="skip_namespace")
process_opts.add_argument("--install-call-info-library",
help="Install application call information library",
action="store_true",
dest="install_call_info_library")
build_opts = parser.add_argument_group('Build options (per-step)')
build_opts.add_argument("--make-all-targets",
help="[LLVM/Clang] Build all LLVM targets, " + \
"not only x86 & AArch64",
action="store_true",
dest="make_all_targets")
build_opts.add_argument("--debug-stack-transformation",
help="Enable debug for stack transformation library",
action="store_true",
dest="debug_stack_transformation")
build_opts.add_argument("--libmigration-type",
help="Choose configuration for libmigration " + \
"(see INSTALL for more details)",
choices=['env_select', 'native', 'debug'],
dest="libmigration_type")
build_opts.add_argument("--enable-libmigration-timing",
help="Turn on timing in migration library",
action="store_true",
dest="enable_libmigration_timing")
return parser
#================================================
# PREREQUISITE CHECKING
# Determines if all needed prerequisites are installed
# See popcorn-compiler/README for more details
#================================================
def _check_for_prerequisite(prereq):
try:
out = subprocess.check_output([prereq, '--version'],
stderr=subprocess.STDOUT)
except Exception:
print('{} not found!'.format(prereq))
return None
else:
out = out.split('\n')[0]
return out
def _check_javac():
try:
out = subprocess.check_output(['javac', '-version'],
stderr=subprocess.STDOUT)
except Exception:
print('javac not found!')
return None
else:
out = out.split('\n')[0]
return out
def check_for_prerequisites():
success = True
print('Checking for prerequisites (see README for more info)...')
gcc_prerequisites = ['aarch64-linux-gnu-gcc',
'x86_64-linux-gnu-gcc',
'x86_64-linux-gnu-g++']
other_prequisites = ['flex', 'bison', 'svn', 'cmake']
for prereq in gcc_prerequisites:
out = _check_for_prerequisite(prereq)
if out:
major, minor, micro = [int(v) for v in out.split()[3].split('.')]
version = major * 10 + minor
if not (version >= 48):
print('{} 4.8 or higher required to continue'.format(prereq))
success = False
else:
success = False
for prereq in other_prequisites:
out = _check_for_prerequisite(prereq)
if not out:
success = False
if not _check_javac():
success = False
return success
def install_clang_llvm(base_path, install_path, num_threads, make_all_targets):
llvm_download_path = os.path.join(install_path, 'src/llvm')
clang_download_path = os.path.join(llvm_download_path, 'tools/clang')
llvm_patch_path = os.path.join(base_path, 'patches/llvm/llvm-3.7.1.patch')
clang_patch_path = os.path.join(base_path, 'patches/llvm/clang-3.7.1.patch')
cmake_flags = ['-DCMAKE_BUILD_TYPE=Debug',
'-DCMAKE_INSTALL_PREFIX={}'.format(install_path),
'-DLLVM_ENABLE_RTTI=ON']
if not make_all_targets:
cmake_flags += ['-DLLVM_TARGETS_TO_BUILD=AArch64;X86']
with open(os.devnull, 'wb') as FNULL:
#=====================================================
# DOWNLOAD LLVM
#=====================================================
print('Downloading LLVM source...')
try:
rv = subprocess.check_call(['svn', 'co', llvm_url,
llvm_download_path],
#stdout=FNULL,
stderr=subprocess.STDOUT)
except Exception as e:
print('Could not download LLVM source ({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('LLVM source download failed.')
sys.exit(1)
#=====================================================
# DOWNLOAD CLANG
#=====================================================
print('Downloading Clang source...')
try:
rv = subprocess.check_call(['svn', 'co', clang_url,
clang_download_path],
#stdout=FNULL,
stderr=subprocess.STDOUT)
except Exception as e:
print('Could not download Clang source ({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('Clang source download failed.')
sys.exit(1)
# PATCH LLVM
with open(llvm_patch_path, 'r') as patch_file:
try:
print("Patching LLVM...")
rv = subprocess.check_call(['patch', '-p0', '-d',
llvm_download_path],
stdin=patch_file,
#stdout=FNULL,
stderr=subprocess.STDOUT)
except Exception as e:
print('Could not patch LLVM({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('LLVM patch failed.')
sys.exit(1)
# PATCH CLANG
with open(clang_patch_path, 'r') as patch_file:
try:
print("Patching clang...")
rv = subprocess.check_call(['patch', '-p0', '-d',
clang_download_path],
stdin=patch_file,
#stdout=FNULL,
stderr=subprocess.STDOUT)
except Exception as e:
print('Could not patch clang({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('clang patch failed.')
sys.exit(1)
# BUILD AND INSTALL LLVM
cur_dir = os.getcwd()
os.chdir(llvm_download_path)
os.mkdir('build')
os.chdir('build')
try:
print('Running CMake...')
rv = subprocess.check_call(['cmake'] + cmake_flags + ['..'],
##stdout=FNULL,
stderr=subprocess.STDOUT)
except Exception as e:
print('Could not run CMake ({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('CMake failed.')
sys.exit(1)
try:
print('Running Make...')
rv = subprocess.check_call(['make', 'REQUIRES_RTTI=1',
'-j', str(num_threads)])
rv = subprocess.check_call(['make', 'install',
'-j', str(num_threads)])
except Exception as e:
print('Could not run Make ({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('Make failed.')
sys.exit(1)
os.chdir(cur_dir)
def install_binutils(base_path, install_path, num_threads):
binutils_install_path = os.path.join(install_path, 'src/binutils-2.27')
patch_path = os.path.join(base_path,
'patches/binutils-gold/binutils-2.27-gold.patch')
configure_flags = ['--prefix={}'.format(install_path),
'--enable-gold',
'--disable-ld',
'--disable-libquadmath',
'--disable-libquadmath-support',
'--disable-libstdcxx']
with open(os.devnull, 'wb') as FNULL:
# DOWNLOAD BINUTILS
print('Downloading binutils source...')
try:
urllib.urlretrieve(binutils_url, 'binutils-2.27.tar.bz2')
except Exception as e:
print('Could not download binutils source ({})!'.format(e))
sys.exit(1)
else:
with tarfile.open('binutils-2.27.tar.bz2', 'r:bz2') as f:
f.extractall(path=os.path.join(install_path, 'src'))
# PATCH BINUTILS
print("Patching binutils...")
with open(patch_path, 'r') as patch_file:
try:
rv = subprocess.check_call(['patch', '-p0', '-d',
binutils_install_path],
stdin=patch_file,
#stdout=FNULL,
stderr=subprocess.STDOUT)
except Exception as e:
print('Could not patch LLVM({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('LLVM patch failed.')
sys.exit(1)
# BUILD AND INSTALL BINUTILS
cur_dir = os.getcwd()
os.chdir(binutils_install_path)
os.mkdir('build')
os.chdir('build')
print("Configuring binutils...")
try:
rv = subprocess.check_call(['../configure'] + configure_flags,
#stdout=FNULL,
stderr=subprocess.STDOUT)
except Exception as e:
print('Could not configure binutils({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('binutils configure failed.')
sys.exit(1)
print('Making binutils...')
try:
print('Running Make...')
rv = subprocess.check_call(['make', '-j', str(num_threads)])
rv = subprocess.check_call(['make', 'install'])
except Exception as e:
print('Could not run Make ({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('Make failed.')
sys.exit(1)
os.chdir(cur_dir)
def install_libraries(base_path, install_path, num_threads, st_debug,
libmigration_type, enable_libmigration_timing):
cur_dir = os.getcwd()
aarch64_install_path = os.path.join(install_path, 'aarch64')
x86_64_install_path = os.path.join(install_path, 'x86_64')
with open(os.devnull, 'wb') as FNULL:
#=====================================================
# CONFIGURE & INSTALL MUSL
#=====================================================
os.chdir(os.path.join(base_path, 'lib/musl-1.1.10'))
if os.path.isfile('Makefile'):
try:
rv = subprocess.check_call(['make', 'distclean'])
except Exception as e:
print('ERROR running distclean!')
sys.exit(1)
else:
if rv != 0:
print('Make distclean failed.')
sys.exit(1)
print("Configuring musl (aarch64)...")
try:
rv = subprocess.check_call(" ".join(['./configure',
'--prefix=' + aarch64_install_path,
'--target=aarch64-linux-gnu',
'--enable-debug',
'--enable-gcc-wrapper',
'--enable-optimize',
'--disable-shared',
'CC={}/bin/clang'.format(install_path),
'CFLAGS="-target aarch64-linux-gnu ' +
'-popcorn-libc -fno-common"']),
#stdout=FNULL,
stderr=subprocess.STDOUT,
shell=True)
except Exception as e:
print('Could not configure musl({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('musl configure failed.')
sys.exit(1)
print('Making musl...')
try:
print('Running Make...')
rv = subprocess.check_call(['make', '-j', str(num_threads)])
rv = subprocess.check_call(['make', 'install'])
except Exception as e:
print('Could not run Make ({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('Make failed.')
sys.exit(1)
try:
rv = subprocess.check_call(['make', 'distclean'])
except Exception as e:
print('ERROR running distclean!')
sys.exit(1)
else:
if rv != 0:
print('Make distclean failed.')
sys.exit(1)
print("Configuring musl (x86-64)...")
try:
rv = subprocess.check_call(" ".join(['./configure',
'--prefix=' + x86_64_install_path,
'--target=x86_64-linux-gnu',
'--enable-debug',
'--enable-gcc-wrapper',
'--enable-optimize',
'--disable-shared',
'CC={}/bin/clang'.format(install_path),
'CFLAGS="-target x86_64-linux-gnu ' +
'-popcorn-libc -fno-common"']),
#stdout=FNULL,
stderr=subprocess.STDOUT,
shell=True)
except Exception as e:
print('Could not configure musl({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('musl configure failed.')
sys.exit(1)
print('Making musl...')
try:
print('Running Make...')
rv = subprocess.check_call(['make', '-j', str(num_threads)])
rv = subprocess.check_call(['make', 'install'])
except Exception as e:
print('Could not run Make ({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('Make failed.')
sys.exit(1)
os.chdir(cur_dir)
#=====================================================
# CONFIGURE & INSTALL LIBELF
#=====================================================
os.chdir(os.path.join(base_path, 'lib/libelf'))
if os.path.isfile('Makefile'):
try:
rv = subprocess.check_call(['make', 'distclean'])
except Exception as e:
print('ERROR running distclean!')
sys.exit(1)
else:
if rv != 0:
print('Make distclean failed.')
sys.exit(1)
print("Configuring libelf (aarch64)...")
try:
cflags = 'CFLAGS="-O3 -ffunction-sections -fdata-sections ' + \
'-specs {}" LDFLAGS="-static"'.format(os.path.join(aarch64_install_path,
'lib/musl-gcc.specs'))
rv = subprocess.check_call(" ".join([cflags,
'./configure',
'--host=aarch64-linux-gnu',
'--prefix=' + aarch64_install_path,
'--enable-elf64',
'--disable-shared',
'--enable-extended-format']),
#stdout=FNULL,
stderr=subprocess.STDOUT,
shell=True)
except Exception as e:
print('Could not configure libelf ({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('libelf configure failed.')
sys.exit(1)
print('Making libelf...')
try:
print('Running Make...')
rv = subprocess.check_call(['make', '-j', str(num_threads)])
rv = subprocess.check_call(['make', 'install'])
except Exception as e:
print('Could not run Make ({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('Make failed.')
sys.exit(1)
try:
rv = subprocess.check_call(['make', 'distclean'])
except Exception as e:
print('ERROR running distclean!')
sys.exit(1)
else:
if rv != 0:
print('Make distclean failed.')
sys.exit(1)
print("Configuring libelf (x86_64)...")
try:
cflags = 'CFLAGS="-O3 -ffunction-sections -fdata-sections ' +\
'-specs {}" LDFLAGS="-static"'.format(os.path.join(x86_64_install_path,
'lib/musl-gcc.specs'))
rv = subprocess.check_call(" ".join([cflags,
'./configure',
'--prefix=' + x86_64_install_path,
'--enable-elf64',
'--disable-shared',
'--enable-extended-format']),
#stdout=FNULL,
stderr=subprocess.STDOUT,
shell=True)
except Exception as e:
print('Could not configure libelf({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('libelf configure failed.')
sys.exit(1)
print('Making libelf...')
try:
print('Running Make...')
rv = subprocess.check_call(['make', '-j', str(num_threads)])
rv = subprocess.check_call(['make', 'install'])
except Exception as e:
print('Could not run Make ({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('Make failed.')
sys.exit(1)
os.chdir(cur_dir)
#=====================================================
# CONFIGURE & INSTALL LIBBOMP
#=====================================================
#os.chdir(os.path.join(base_path, 'lib/libbomp'))
#print('Making libbomp...')
#try:
# print('Running Make...')
# rv = subprocess.check_call(['make', '-j', str(num_threads),
# 'POPCORN={}'.format(install_path)])
# rv = subprocess.check_call(['make', 'install',
# 'POPCORN={}'.format(install_path)])
#except Exception as e:
# print('Could not run Make ({})!'.format(e))
# sys.exit(1)
#else:
# if rv != 0:
# print('Make failed.')
# sys.exit(1)
#os.chdir(cur_dir)
#=====================================================
# CONFIGURE & INSTALL STACK TRANSFORMATION LIBRARY
#=====================================================
os.chdir(os.path.join(base_path, 'lib/stack_transformation'))
if not st_debug:
flags = ''
else:
flags = 'type=debug'
print('Making stack_transformation...')
try:
print('Running Make...')
if flags != '':
rv = subprocess.check_call(['make', flags, '-j',
str(num_threads),
'POPCORN={}'.format(install_path)])
else:
rv = subprocess.check_call(['make', '-j', str(num_threads),
'POPCORN={}'.format(install_path)])
rv = subprocess.check_call(['make', 'install',
'POPCORN={}'.format(install_path)])
except Exception as e:
print('Could not run Make ({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('Make failed.')
sys.exit(1)
os.chdir(cur_dir)
#=====================================================
# CONFIGURE & INSTALL MIGRATION LIBRARY
#=====================================================
os.chdir(os.path.join(base_path, 'lib/migration'))
if not libmigration_type and not enable_libmigration_timing:
flags = ''
else:
flags = 'type='
if libmigration_type and enable_libmigration_timing:
flags += libmigration_type + ',timing'
elif libmigration_type:
flags += libmigration_type
elif enable_libmigration_timing:
flags += 'timing'
print('Making libmigration...')
try:
print('Running Make...')
if flags != '':
rv = subprocess.check_call(['make', flags, '-j',
str(num_threads),
'POPCORN={}'.format(install_path)])
else:
rv = subprocess.check_call(['make', '-j', str(num_threads),
'POPCORN={}'.format(install_path)])
rv = subprocess.check_call(['make', 'install',
'POPCORN={}'.format(install_path)])
except Exception as e:
print('Could not run Make ({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('Make failed.')
sys.exit(1)
os.chdir(cur_dir)
def install_tools(base_path, install_path, num_threads):
cur_dir = os.getcwd()
#=====================================================
# INSTALL ALIGNMENT TOOL
#=====================================================
# 1. Old java tool, TODO remove it later
os.chdir(os.path.join(base_path, 'tool/alignment/old-alignment'))
print('Making java alignment tool...')
try:
print('Running Make...')
rv = subprocess.check_call(['make', '-j', str(num_threads),
'POPCORN={}'.format(install_path)])
tmp = install_path.replace('/', '\/')
sed_cmd = "sed -i -e 's/^POPCORN=.*/POPCORN=\"{}\"/g' ./scripts/mlink_armObjs.sh".format(tmp)
rv = subprocess.check_call(sed_cmd, stderr=subprocess.STDOUT,shell=True)
sed_cmd = "sed -i -e 's/^POPCORN=.*/POPCORN=\"{}\"/g' ./scripts/mlink_x86Objs.sh".format(tmp)
rv = subprocess.check_call(sed_cmd, stderr=subprocess.STDOUT,shell=True)
rv = subprocess.check_call(['make', 'install',
'POPCORN={}'.format(install_path)])
except Exception as e:
print('Could not run Make ({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('Make failed.')
sys.exit(1)
os.chdir(cur_dir)
# 2. Pyalign
os.chdir(os.path.join(base_path, 'tool/alignment/pyalign'))
print('Making pyalign...')
try:
print('Running Make...')
rv = subprocess.check_call(['make', '-j', str(num_threads),
'POPCORN={}'.format(install_path), 'install'])
except Exception as e:
print('Could not run Make ({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('Make failed')
sys.exit(1)
os.chdir(cur_dir)
#=====================================================
# INSTALL STACK METADATA TOOL
#=====================================================
os.chdir(os.path.join(base_path, 'tool/stack_metadata'))
print('Making stack metadata tool...')
try:
print('Running Make...')
rv = subprocess.check_call(['make', '-j', str(num_threads),
'POPCORN={}'.format(install_path)])
rv = subprocess.check_call(['make', 'install',
'POPCORN={}'.format(install_path)])
except Exception as e:
print('Could not run Make ({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('Make failed.')
sys.exit(1)
os.chdir(cur_dir)
def install_call_info_library(base_path, install_path, num_threads):
cur_dir = os.getcwd()
#=====================================================
# INSTALL STACK DEPTH LIBRARY
#=====================================================
os.chdir(os.path.join(base_path, 'lib/stack_depth'))
print('Making stack depth library...')
try:
print('Running Make...')
rv = subprocess.check_call(['make', '-j', str(num_threads),
'POPCORN={}'.format(install_path)])
rv = subprocess.check_call(['make', 'install',
'POPCORN={}'.format(install_path)])
except Exception as e:
print('Could not run Make ({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('Make failed.')
sys.exit(1)
os.chdir(cur_dir)
def install_utils(base_path, install_path, num_threads):
#=====================================================
# MODIFY MAKEFILE TEMPLATE
#=====================================================
print("Updating util/Makefile.template to reflect system setup and install path...")
try:
tmp = install_path.replace('/', '\/')
sed_cmd = "sed -i -e 's/^POPCORN := .*/POPCORN := {}/g' ./util/Makefile.template".format(tmp)
rv = subprocess.check_call(sed_cmd, stderr=subprocess.STDOUT,shell=True)
except Exception as e:
print('Could not modify Makefile.template ({})'.format(e))
else:
if rv != 0:
print('sed failed.')
#=====================================================
# COPY SCRIPTS
#=====================================================
print("Copying util/scripts to {}/bin...".format(install_path))
for item in os.listdir('./util/scripts'):
s = os.path.join('./util/scripts/', item)
d = os.path.join(os.path.join(install_path, 'bin'), item)
shutil.copy(s, d)
def build_namespace(base_path):
print("Building namespace tools...")
try:
make_cmd = "make -C {}/tool/namespace".format(base_path)
rv = subprocess.check_call(["make", "-C",
base_path + "/tool/namespace"])
except Exception as e:
print('Could not build namespace tools ({})'.format(e))
else:
if rv != 0:
print('make failed')
def main(args):
cpus = multiprocessing.cpu_count()
if not args.skip_llvm_clang_install:
install_clang_llvm(args.base_path, args.install_path, cpus,
args.make_all_targets)
if not args.skip_binutils_install:
install_binutils(args.base_path, args.install_path, cpus)
if not args.skip_libraries_install:
install_libraries(args.base_path, args.install_path, cpus,
args.debug_stack_transformation,
args.libmigration_type,
args.enable_libmigration_timing)
if not args.skip_tools_install:
install_tools(args.base_path, args.install_path, cpus)
if args.install_call_info_library:
install_call_info_library(args.base_path, args.install_path,
cpus)
if not args.skip_utils_install:
install_utils(args.base_path, args.install_path, cpus)
if not args.skip_namespace:
build_namespace(args.base_path)
if __name__ == '__main__':
parser = setup_argument_parsing()
args = parser.parse_args()
if not args.skip_prereq_check:
success = check_for_prerequisites()
if success != True:
print('All prerequisites were not satisfied!')
sys.exit(1)
main(args)
| <filename>install_compiler.py<gh_stars>0
#!/usr/bin/env python2
from __future__ import print_function
import argparse
import os, os.path
import shutil
import subprocess
import sys
import tarfile
import urllib
import multiprocessing
#================================================
# GLOBALS
#================================================
# LLVM 3.7.1 SVN URL
llvm_url = 'http://llvm.org/svn/llvm-project/llvm/tags/RELEASE_371/final'
# Clang SVN URL
clang_url = 'http://llvm.org/svn/llvm-project/cfe/tags/RELEASE_371/final'
# Binutils 2.27 URL
binutils_url = 'http://ftp.gnu.org/gnu/binutils/binutils-2.27.tar.bz2'
#================================================
# LOG CLASS
# Logs all output to outfile as well as stdout
#================================================
class Log(object):
def __init__(self, name, mode):
self.file = open(name, mode)
def __del__(self):
self.file.close()
def write(self, data):
self.file.write(data)
#================================================
# ARGUMENT PARSING
#================================================
def setup_argument_parsing():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
config_opts = parser.add_argument_group('Configuration Options')
config_opts.add_argument("--base-path",
help="Base path of popcorn-compiler repo",
default=os.getcwd(),
dest="base_path")
config_opts.add_argument("--install-path",
help="Install path of Popcorn compiler",
default="/usr/local/popcorn",
dest="install_path")
config_opts.add_argument("--threads",
help="Number of threads to build compiler with",
type=int,
default=multiprocessing.cpu_count())
process_opts = parser.add_argument_group('Process Options (skip steps)')
process_opts.add_argument("--skip-prereq-check",
help="Skip checking for prerequisites (see README)",
action="store_true",
dest="skip_prereq_check")
process_opts.add_argument("--skip-llvm-clang-install",
help="Skip installation of LLVM and Clang",
action="store_true",
dest="skip_llvm_clang_install")
process_opts.add_argument("--skip-binutils-install",
help="Skip installation of binutils",
action="store_true",
dest="skip_binutils_install")
process_opts.add_argument("--skip-libraries-install",
help="Skip installation of libraries",
action="store_true",
dest="skip_libraries_install")
process_opts.add_argument("--skip-tools-install",
help="Skip installation of tools",
action="store_true",
dest="skip_tools_install")
process_opts.add_argument("--skip-utils-install",
help="Skip installation of util scripts",
action="store_true",
dest="skip_utils_install")
process_opts.add_argument("--skip-namespace",
help="Skip building namespace tools",
action="store_true",
dest="skip_namespace")
process_opts.add_argument("--install-call-info-library",
help="Install application call information library",
action="store_true",
dest="install_call_info_library")
build_opts = parser.add_argument_group('Build options (per-step)')
build_opts.add_argument("--make-all-targets",
help="[LLVM/Clang] Build all LLVM targets, " + \
"not only x86 & AArch64",
action="store_true",
dest="make_all_targets")
build_opts.add_argument("--debug-stack-transformation",
help="Enable debug for stack transformation library",
action="store_true",
dest="debug_stack_transformation")
build_opts.add_argument("--libmigration-type",
help="Choose configuration for libmigration " + \
"(see INSTALL for more details)",
choices=['env_select', 'native', 'debug'],
dest="libmigration_type")
build_opts.add_argument("--enable-libmigration-timing",
help="Turn on timing in migration library",
action="store_true",
dest="enable_libmigration_timing")
return parser
#================================================
# PREREQUISITE CHECKING
# Determines if all needed prerequisites are installed
# See popcorn-compiler/README for more details
#================================================
def _check_for_prerequisite(prereq):
try:
out = subprocess.check_output([prereq, '--version'],
stderr=subprocess.STDOUT)
except Exception:
print('{} not found!'.format(prereq))
return None
else:
out = out.split('\n')[0]
return out
def _check_javac():
try:
out = subprocess.check_output(['javac', '-version'],
stderr=subprocess.STDOUT)
except Exception:
print('javac not found!')
return None
else:
out = out.split('\n')[0]
return out
def check_for_prerequisites():
success = True
print('Checking for prerequisites (see README for more info)...')
gcc_prerequisites = ['aarch64-linux-gnu-gcc',
'x86_64-linux-gnu-gcc',
'x86_64-linux-gnu-g++']
other_prequisites = ['flex', 'bison', 'svn', 'cmake']
for prereq in gcc_prerequisites:
out = _check_for_prerequisite(prereq)
if out:
major, minor, micro = [int(v) for v in out.split()[3].split('.')]
version = major * 10 + minor
if not (version >= 48):
print('{} 4.8 or higher required to continue'.format(prereq))
success = False
else:
success = False
for prereq in other_prequisites:
out = _check_for_prerequisite(prereq)
if not out:
success = False
if not _check_javac():
success = False
return success
def install_clang_llvm(base_path, install_path, num_threads, make_all_targets):
llvm_download_path = os.path.join(install_path, 'src/llvm')
clang_download_path = os.path.join(llvm_download_path, 'tools/clang')
llvm_patch_path = os.path.join(base_path, 'patches/llvm/llvm-3.7.1.patch')
clang_patch_path = os.path.join(base_path, 'patches/llvm/clang-3.7.1.patch')
cmake_flags = ['-DCMAKE_BUILD_TYPE=Debug',
'-DCMAKE_INSTALL_PREFIX={}'.format(install_path),
'-DLLVM_ENABLE_RTTI=ON']
if not make_all_targets:
cmake_flags += ['-DLLVM_TARGETS_TO_BUILD=AArch64;X86']
with open(os.devnull, 'wb') as FNULL:
#=====================================================
# DOWNLOAD LLVM
#=====================================================
print('Downloading LLVM source...')
try:
rv = subprocess.check_call(['svn', 'co', llvm_url,
llvm_download_path],
#stdout=FNULL,
stderr=subprocess.STDOUT)
except Exception as e:
print('Could not download LLVM source ({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('LLVM source download failed.')
sys.exit(1)
#=====================================================
# DOWNLOAD CLANG
#=====================================================
print('Downloading Clang source...')
try:
rv = subprocess.check_call(['svn', 'co', clang_url,
clang_download_path],
#stdout=FNULL,
stderr=subprocess.STDOUT)
except Exception as e:
print('Could not download Clang source ({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('Clang source download failed.')
sys.exit(1)
# PATCH LLVM
with open(llvm_patch_path, 'r') as patch_file:
try:
print("Patching LLVM...")
rv = subprocess.check_call(['patch', '-p0', '-d',
llvm_download_path],
stdin=patch_file,
#stdout=FNULL,
stderr=subprocess.STDOUT)
except Exception as e:
print('Could not patch LLVM({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('LLVM patch failed.')
sys.exit(1)
# PATCH CLANG
with open(clang_patch_path, 'r') as patch_file:
try:
print("Patching clang...")
rv = subprocess.check_call(['patch', '-p0', '-d',
clang_download_path],
stdin=patch_file,
#stdout=FNULL,
stderr=subprocess.STDOUT)
except Exception as e:
print('Could not patch clang({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('clang patch failed.')
sys.exit(1)
# BUILD AND INSTALL LLVM
cur_dir = os.getcwd()
os.chdir(llvm_download_path)
os.mkdir('build')
os.chdir('build')
try:
print('Running CMake...')
rv = subprocess.check_call(['cmake'] + cmake_flags + ['..'],
##stdout=FNULL,
stderr=subprocess.STDOUT)
except Exception as e:
print('Could not run CMake ({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('CMake failed.')
sys.exit(1)
try:
print('Running Make...')
rv = subprocess.check_call(['make', 'REQUIRES_RTTI=1',
'-j', str(num_threads)])
rv = subprocess.check_call(['make', 'install',
'-j', str(num_threads)])
except Exception as e:
print('Could not run Make ({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('Make failed.')
sys.exit(1)
os.chdir(cur_dir)
def install_binutils(base_path, install_path, num_threads):
binutils_install_path = os.path.join(install_path, 'src/binutils-2.27')
patch_path = os.path.join(base_path,
'patches/binutils-gold/binutils-2.27-gold.patch')
configure_flags = ['--prefix={}'.format(install_path),
'--enable-gold',
'--disable-ld',
'--disable-libquadmath',
'--disable-libquadmath-support',
'--disable-libstdcxx']
with open(os.devnull, 'wb') as FNULL:
# DOWNLOAD BINUTILS
print('Downloading binutils source...')
try:
urllib.urlretrieve(binutils_url, 'binutils-2.27.tar.bz2')
except Exception as e:
print('Could not download binutils source ({})!'.format(e))
sys.exit(1)
else:
with tarfile.open('binutils-2.27.tar.bz2', 'r:bz2') as f:
f.extractall(path=os.path.join(install_path, 'src'))
# PATCH BINUTILS
print("Patching binutils...")
with open(patch_path, 'r') as patch_file:
try:
rv = subprocess.check_call(['patch', '-p0', '-d',
binutils_install_path],
stdin=patch_file,
#stdout=FNULL,
stderr=subprocess.STDOUT)
except Exception as e:
print('Could not patch LLVM({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('LLVM patch failed.')
sys.exit(1)
# BUILD AND INSTALL BINUTILS
cur_dir = os.getcwd()
os.chdir(binutils_install_path)
os.mkdir('build')
os.chdir('build')
print("Configuring binutils...")
try:
rv = subprocess.check_call(['../configure'] + configure_flags,
#stdout=FNULL,
stderr=subprocess.STDOUT)
except Exception as e:
print('Could not configure binutils({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('binutils configure failed.')
sys.exit(1)
print('Making binutils...')
try:
print('Running Make...')
rv = subprocess.check_call(['make', '-j', str(num_threads)])
rv = subprocess.check_call(['make', 'install'])
except Exception as e:
print('Could not run Make ({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('Make failed.')
sys.exit(1)
os.chdir(cur_dir)
def install_libraries(base_path, install_path, num_threads, st_debug,
libmigration_type, enable_libmigration_timing):
cur_dir = os.getcwd()
aarch64_install_path = os.path.join(install_path, 'aarch64')
x86_64_install_path = os.path.join(install_path, 'x86_64')
with open(os.devnull, 'wb') as FNULL:
#=====================================================
# CONFIGURE & INSTALL MUSL
#=====================================================
os.chdir(os.path.join(base_path, 'lib/musl-1.1.10'))
if os.path.isfile('Makefile'):
try:
rv = subprocess.check_call(['make', 'distclean'])
except Exception as e:
print('ERROR running distclean!')
sys.exit(1)
else:
if rv != 0:
print('Make distclean failed.')
sys.exit(1)
print("Configuring musl (aarch64)...")
try:
rv = subprocess.check_call(" ".join(['./configure',
'--prefix=' + aarch64_install_path,
'--target=aarch64-linux-gnu',
'--enable-debug',
'--enable-gcc-wrapper',
'--enable-optimize',
'--disable-shared',
'CC={}/bin/clang'.format(install_path),
'CFLAGS="-target aarch64-linux-gnu ' +
'-popcorn-libc -fno-common"']),
#stdout=FNULL,
stderr=subprocess.STDOUT,
shell=True)
except Exception as e:
print('Could not configure musl({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('musl configure failed.')
sys.exit(1)
print('Making musl...')
try:
print('Running Make...')
rv = subprocess.check_call(['make', '-j', str(num_threads)])
rv = subprocess.check_call(['make', 'install'])
except Exception as e:
print('Could not run Make ({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('Make failed.')
sys.exit(1)
try:
rv = subprocess.check_call(['make', 'distclean'])
except Exception as e:
print('ERROR running distclean!')
sys.exit(1)
else:
if rv != 0:
print('Make distclean failed.')
sys.exit(1)
print("Configuring musl (x86-64)...")
try:
rv = subprocess.check_call(" ".join(['./configure',
'--prefix=' + x86_64_install_path,
'--target=x86_64-linux-gnu',
'--enable-debug',
'--enable-gcc-wrapper',
'--enable-optimize',
'--disable-shared',
'CC={}/bin/clang'.format(install_path),
'CFLAGS="-target x86_64-linux-gnu ' +
'-popcorn-libc -fno-common"']),
#stdout=FNULL,
stderr=subprocess.STDOUT,
shell=True)
except Exception as e:
print('Could not configure musl({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('musl configure failed.')
sys.exit(1)
print('Making musl...')
try:
print('Running Make...')
rv = subprocess.check_call(['make', '-j', str(num_threads)])
rv = subprocess.check_call(['make', 'install'])
except Exception as e:
print('Could not run Make ({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('Make failed.')
sys.exit(1)
os.chdir(cur_dir)
#=====================================================
# CONFIGURE & INSTALL LIBELF
#=====================================================
os.chdir(os.path.join(base_path, 'lib/libelf'))
if os.path.isfile('Makefile'):
try:
rv = subprocess.check_call(['make', 'distclean'])
except Exception as e:
print('ERROR running distclean!')
sys.exit(1)
else:
if rv != 0:
print('Make distclean failed.')
sys.exit(1)
print("Configuring libelf (aarch64)...")
try:
cflags = 'CFLAGS="-O3 -ffunction-sections -fdata-sections ' + \
'-specs {}" LDFLAGS="-static"'.format(os.path.join(aarch64_install_path,
'lib/musl-gcc.specs'))
rv = subprocess.check_call(" ".join([cflags,
'./configure',
'--host=aarch64-linux-gnu',
'--prefix=' + aarch64_install_path,
'--enable-elf64',
'--disable-shared',
'--enable-extended-format']),
#stdout=FNULL,
stderr=subprocess.STDOUT,
shell=True)
except Exception as e:
print('Could not configure libelf ({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('libelf configure failed.')
sys.exit(1)
print('Making libelf...')
try:
print('Running Make...')
rv = subprocess.check_call(['make', '-j', str(num_threads)])
rv = subprocess.check_call(['make', 'install'])
except Exception as e:
print('Could not run Make ({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('Make failed.')
sys.exit(1)
try:
rv = subprocess.check_call(['make', 'distclean'])
except Exception as e:
print('ERROR running distclean!')
sys.exit(1)
else:
if rv != 0:
print('Make distclean failed.')
sys.exit(1)
print("Configuring libelf (x86_64)...")
try:
cflags = 'CFLAGS="-O3 -ffunction-sections -fdata-sections ' +\
'-specs {}" LDFLAGS="-static"'.format(os.path.join(x86_64_install_path,
'lib/musl-gcc.specs'))
rv = subprocess.check_call(" ".join([cflags,
'./configure',
'--prefix=' + x86_64_install_path,
'--enable-elf64',
'--disable-shared',
'--enable-extended-format']),
#stdout=FNULL,
stderr=subprocess.STDOUT,
shell=True)
except Exception as e:
print('Could not configure libelf({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('libelf configure failed.')
sys.exit(1)
print('Making libelf...')
try:
print('Running Make...')
rv = subprocess.check_call(['make', '-j', str(num_threads)])
rv = subprocess.check_call(['make', 'install'])
except Exception as e:
print('Could not run Make ({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('Make failed.')
sys.exit(1)
os.chdir(cur_dir)
#=====================================================
# CONFIGURE & INSTALL LIBBOMP
#=====================================================
#os.chdir(os.path.join(base_path, 'lib/libbomp'))
#print('Making libbomp...')
#try:
# print('Running Make...')
# rv = subprocess.check_call(['make', '-j', str(num_threads),
# 'POPCORN={}'.format(install_path)])
# rv = subprocess.check_call(['make', 'install',
# 'POPCORN={}'.format(install_path)])
#except Exception as e:
# print('Could not run Make ({})!'.format(e))
# sys.exit(1)
#else:
# if rv != 0:
# print('Make failed.')
# sys.exit(1)
#os.chdir(cur_dir)
#=====================================================
# CONFIGURE & INSTALL STACK TRANSFORMATION LIBRARY
#=====================================================
os.chdir(os.path.join(base_path, 'lib/stack_transformation'))
if not st_debug:
flags = ''
else:
flags = 'type=debug'
print('Making stack_transformation...')
try:
print('Running Make...')
if flags != '':
rv = subprocess.check_call(['make', flags, '-j',
str(num_threads),
'POPCORN={}'.format(install_path)])
else:
rv = subprocess.check_call(['make', '-j', str(num_threads),
'POPCORN={}'.format(install_path)])
rv = subprocess.check_call(['make', 'install',
'POPCORN={}'.format(install_path)])
except Exception as e:
print('Could not run Make ({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('Make failed.')
sys.exit(1)
os.chdir(cur_dir)
#=====================================================
# CONFIGURE & INSTALL MIGRATION LIBRARY
#=====================================================
os.chdir(os.path.join(base_path, 'lib/migration'))
if not libmigration_type and not enable_libmigration_timing:
flags = ''
else:
flags = 'type='
if libmigration_type and enable_libmigration_timing:
flags += libmigration_type + ',timing'
elif libmigration_type:
flags += libmigration_type
elif enable_libmigration_timing:
flags += 'timing'
print('Making libmigration...')
try:
print('Running Make...')
if flags != '':
rv = subprocess.check_call(['make', flags, '-j',
str(num_threads),
'POPCORN={}'.format(install_path)])
else:
rv = subprocess.check_call(['make', '-j', str(num_threads),
'POPCORN={}'.format(install_path)])
rv = subprocess.check_call(['make', 'install',
'POPCORN={}'.format(install_path)])
except Exception as e:
print('Could not run Make ({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('Make failed.')
sys.exit(1)
os.chdir(cur_dir)
def install_tools(base_path, install_path, num_threads):
cur_dir = os.getcwd()
#=====================================================
# INSTALL ALIGNMENT TOOL
#=====================================================
# 1. Old java tool, TODO remove it later
os.chdir(os.path.join(base_path, 'tool/alignment/old-alignment'))
print('Making java alignment tool...')
try:
print('Running Make...')
rv = subprocess.check_call(['make', '-j', str(num_threads),
'POPCORN={}'.format(install_path)])
tmp = install_path.replace('/', '\/')
sed_cmd = "sed -i -e 's/^POPCORN=.*/POPCORN=\"{}\"/g' ./scripts/mlink_armObjs.sh".format(tmp)
rv = subprocess.check_call(sed_cmd, stderr=subprocess.STDOUT,shell=True)
sed_cmd = "sed -i -e 's/^POPCORN=.*/POPCORN=\"{}\"/g' ./scripts/mlink_x86Objs.sh".format(tmp)
rv = subprocess.check_call(sed_cmd, stderr=subprocess.STDOUT,shell=True)
rv = subprocess.check_call(['make', 'install',
'POPCORN={}'.format(install_path)])
except Exception as e:
print('Could not run Make ({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('Make failed.')
sys.exit(1)
os.chdir(cur_dir)
# 2. Pyalign
os.chdir(os.path.join(base_path, 'tool/alignment/pyalign'))
print('Making pyalign...')
try:
print('Running Make...')
rv = subprocess.check_call(['make', '-j', str(num_threads),
'POPCORN={}'.format(install_path), 'install'])
except Exception as e:
print('Could not run Make ({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('Make failed')
sys.exit(1)
os.chdir(cur_dir)
#=====================================================
# INSTALL STACK METADATA TOOL
#=====================================================
os.chdir(os.path.join(base_path, 'tool/stack_metadata'))
print('Making stack metadata tool...')
try:
print('Running Make...')
rv = subprocess.check_call(['make', '-j', str(num_threads),
'POPCORN={}'.format(install_path)])
rv = subprocess.check_call(['make', 'install',
'POPCORN={}'.format(install_path)])
except Exception as e:
print('Could not run Make ({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('Make failed.')
sys.exit(1)
os.chdir(cur_dir)
def install_call_info_library(base_path, install_path, num_threads):
cur_dir = os.getcwd()
#=====================================================
# INSTALL STACK DEPTH LIBRARY
#=====================================================
os.chdir(os.path.join(base_path, 'lib/stack_depth'))
print('Making stack depth library...')
try:
print('Running Make...')
rv = subprocess.check_call(['make', '-j', str(num_threads),
'POPCORN={}'.format(install_path)])
rv = subprocess.check_call(['make', 'install',
'POPCORN={}'.format(install_path)])
except Exception as e:
print('Could not run Make ({})!'.format(e))
sys.exit(1)
else:
if rv != 0:
print('Make failed.')
sys.exit(1)
os.chdir(cur_dir)
def install_utils(base_path, install_path, num_threads):
#=====================================================
# MODIFY MAKEFILE TEMPLATE
#=====================================================
print("Updating util/Makefile.template to reflect system setup and install path...")
try:
tmp = install_path.replace('/', '\/')
sed_cmd = "sed -i -e 's/^POPCORN := .*/POPCORN := {}/g' ./util/Makefile.template".format(tmp)
rv = subprocess.check_call(sed_cmd, stderr=subprocess.STDOUT,shell=True)
except Exception as e:
print('Could not modify Makefile.template ({})'.format(e))
else:
if rv != 0:
print('sed failed.')
#=====================================================
# COPY SCRIPTS
#=====================================================
print("Copying util/scripts to {}/bin...".format(install_path))
for item in os.listdir('./util/scripts'):
s = os.path.join('./util/scripts/', item)
d = os.path.join(os.path.join(install_path, 'bin'), item)
shutil.copy(s, d)
def build_namespace(base_path):
print("Building namespace tools...")
try:
make_cmd = "make -C {}/tool/namespace".format(base_path)
rv = subprocess.check_call(["make", "-C",
base_path + "/tool/namespace"])
except Exception as e:
print('Could not build namespace tools ({})'.format(e))
else:
if rv != 0:
print('make failed')
def main(args):
cpus = multiprocessing.cpu_count()
if not args.skip_llvm_clang_install:
install_clang_llvm(args.base_path, args.install_path, cpus,
args.make_all_targets)
if not args.skip_binutils_install:
install_binutils(args.base_path, args.install_path, cpus)
if not args.skip_libraries_install:
install_libraries(args.base_path, args.install_path, cpus,
args.debug_stack_transformation,
args.libmigration_type,
args.enable_libmigration_timing)
if not args.skip_tools_install:
install_tools(args.base_path, args.install_path, cpus)
if args.install_call_info_library:
install_call_info_library(args.base_path, args.install_path,
cpus)
if not args.skip_utils_install:
install_utils(args.base_path, args.install_path, cpus)
if not args.skip_namespace:
build_namespace(args.base_path)
if __name__ == '__main__':
parser = setup_argument_parsing()
args = parser.parse_args()
if not args.skip_prereq_check:
success = check_for_prerequisites()
if success != True:
print('All prerequisites were not satisfied!')
sys.exit(1)
main(args)
| en | 0.322181 | #!/usr/bin/env python2 #================================================ # GLOBALS #================================================ # LLVM 3.7.1 SVN URL # Clang SVN URL # Binutils 2.27 URL #================================================ # LOG CLASS # Logs all output to outfile as well as stdout #================================================ #================================================ # ARGUMENT PARSING #================================================ #================================================ # PREREQUISITE CHECKING # Determines if all needed prerequisites are installed # See popcorn-compiler/README for more details #================================================ #===================================================== # DOWNLOAD LLVM #===================================================== #stdout=FNULL, #===================================================== # DOWNLOAD CLANG #===================================================== #stdout=FNULL, # PATCH LLVM #stdout=FNULL, # PATCH CLANG #stdout=FNULL, # BUILD AND INSTALL LLVM ##stdout=FNULL, # DOWNLOAD BINUTILS # PATCH BINUTILS #stdout=FNULL, # BUILD AND INSTALL BINUTILS #stdout=FNULL, #===================================================== # CONFIGURE & INSTALL MUSL #===================================================== #stdout=FNULL, #stdout=FNULL, #===================================================== # CONFIGURE & INSTALL LIBELF #===================================================== #stdout=FNULL, #stdout=FNULL, #===================================================== # CONFIGURE & INSTALL LIBBOMP #===================================================== #os.chdir(os.path.join(base_path, 'lib/libbomp')) #print('Making libbomp...') #try: # print('Running Make...') # rv = subprocess.check_call(['make', '-j', str(num_threads), # 'POPCORN={}'.format(install_path)]) # rv = subprocess.check_call(['make', 'install', # 'POPCORN={}'.format(install_path)]) #except Exception as e: # print('Could not run Make ({})!'.format(e)) # sys.exit(1) #else: # if rv != 0: # print('Make failed.') # sys.exit(1) #os.chdir(cur_dir) #===================================================== # CONFIGURE & INSTALL STACK TRANSFORMATION LIBRARY #===================================================== #===================================================== # CONFIGURE & INSTALL MIGRATION LIBRARY #===================================================== #===================================================== # INSTALL ALIGNMENT TOOL #===================================================== # 1. Old java tool, TODO remove it later # 2. Pyalign #===================================================== # INSTALL STACK METADATA TOOL #===================================================== #===================================================== # INSTALL STACK DEPTH LIBRARY #===================================================== #===================================================== # MODIFY MAKEFILE TEMPLATE #===================================================== #===================================================== # COPY SCRIPTS #===================================================== | 2.177704 | 2 |
internal/endtoend/testdata/emit_pydantic_models/postgresql/models.py | BearerPipelineTest/sqlc | 0 | 6627975 | # Code generated by sqlc. DO NOT EDIT.
# versions:
# sqlc v1.13.0
import pydantic
from typing import Optional
class Author(pydantic.BaseModel):
id: int
name: str
bio: Optional[str]
| # Code generated by sqlc. DO NOT EDIT.
# versions:
# sqlc v1.13.0
import pydantic
from typing import Optional
class Author(pydantic.BaseModel):
id: int
name: str
bio: Optional[str]
| en | 0.725095 | # Code generated by sqlc. DO NOT EDIT. # versions: # sqlc v1.13.0 | 2.247664 | 2 |
venv/Lib/site-packages/cryptography/hazmat/backends/openssl/dh.py | gilbertekalea/booking.com_crawler | 7 | 6627976 | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from cryptography.exceptions import UnsupportedAlgorithm, _Reasons
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import dh
def _dh_params_dup(dh_cdata, backend):
lib = backend._lib
ffi = backend._ffi
param_cdata = lib.DHparams_dup(dh_cdata)
backend.openssl_assert(param_cdata != ffi.NULL)
param_cdata = ffi.gc(param_cdata, lib.DH_free)
if lib.CRYPTOGRAPHY_IS_LIBRESSL:
# In libressl DHparams_dup don't copy q
q = ffi.new("BIGNUM **")
lib.DH_get0_pqg(dh_cdata, ffi.NULL, q, ffi.NULL)
q_dup = lib.BN_dup(q[0])
res = lib.DH_set0_pqg(param_cdata, ffi.NULL, q_dup, ffi.NULL)
backend.openssl_assert(res == 1)
return param_cdata
def _dh_cdata_to_parameters(dh_cdata, backend):
param_cdata = _dh_params_dup(dh_cdata, backend)
return _DHParameters(backend, param_cdata)
class _DHParameters(dh.DHParameters):
def __init__(self, backend, dh_cdata):
self._backend = backend
self._dh_cdata = dh_cdata
def parameter_numbers(self) -> dh.DHParameterNumbers:
p = self._backend._ffi.new("BIGNUM **")
g = self._backend._ffi.new("BIGNUM **")
q = self._backend._ffi.new("BIGNUM **")
self._backend._lib.DH_get0_pqg(self._dh_cdata, p, q, g)
self._backend.openssl_assert(p[0] != self._backend._ffi.NULL)
self._backend.openssl_assert(g[0] != self._backend._ffi.NULL)
if q[0] == self._backend._ffi.NULL:
q_val = None
else:
q_val = self._backend._bn_to_int(q[0])
return dh.DHParameterNumbers(
p=self._backend._bn_to_int(p[0]),
g=self._backend._bn_to_int(g[0]),
q=q_val,
)
def generate_private_key(self) -> dh.DHPrivateKey:
return self._backend.generate_dh_private_key(self)
def parameter_bytes(
self,
encoding: serialization.Encoding,
format: serialization.ParameterFormat,
) -> bytes:
if format is not serialization.ParameterFormat.PKCS3:
raise ValueError("Only PKCS3 serialization is supported")
if not self._backend._lib.Cryptography_HAS_EVP_PKEY_DHX:
q = self._backend._ffi.new("BIGNUM **")
self._backend._lib.DH_get0_pqg(
self._dh_cdata,
self._backend._ffi.NULL,
q,
self._backend._ffi.NULL,
)
if q[0] != self._backend._ffi.NULL:
raise UnsupportedAlgorithm(
"DH X9.42 serialization is not supported",
_Reasons.UNSUPPORTED_SERIALIZATION,
)
return self._backend._parameter_bytes(encoding, format, self._dh_cdata)
def _get_dh_num_bits(backend, dh_cdata) -> int:
p = backend._ffi.new("BIGNUM **")
backend._lib.DH_get0_pqg(dh_cdata, p, backend._ffi.NULL, backend._ffi.NULL)
backend.openssl_assert(p[0] != backend._ffi.NULL)
return backend._lib.BN_num_bits(p[0])
class _DHPrivateKey(dh.DHPrivateKey):
def __init__(self, backend, dh_cdata, evp_pkey):
self._backend = backend
self._dh_cdata = dh_cdata
self._evp_pkey = evp_pkey
self._key_size_bytes = self._backend._lib.DH_size(dh_cdata)
@property
def key_size(self) -> int:
return _get_dh_num_bits(self._backend, self._dh_cdata)
def private_numbers(self) -> dh.DHPrivateNumbers:
p = self._backend._ffi.new("BIGNUM **")
g = self._backend._ffi.new("BIGNUM **")
q = self._backend._ffi.new("BIGNUM **")
self._backend._lib.DH_get0_pqg(self._dh_cdata, p, q, g)
self._backend.openssl_assert(p[0] != self._backend._ffi.NULL)
self._backend.openssl_assert(g[0] != self._backend._ffi.NULL)
if q[0] == self._backend._ffi.NULL:
q_val = None
else:
q_val = self._backend._bn_to_int(q[0])
pub_key = self._backend._ffi.new("BIGNUM **")
priv_key = self._backend._ffi.new("BIGNUM **")
self._backend._lib.DH_get0_key(self._dh_cdata, pub_key, priv_key)
self._backend.openssl_assert(pub_key[0] != self._backend._ffi.NULL)
self._backend.openssl_assert(priv_key[0] != self._backend._ffi.NULL)
return dh.DHPrivateNumbers(
public_numbers=dh.DHPublicNumbers(
parameter_numbers=dh.DHParameterNumbers(
p=self._backend._bn_to_int(p[0]),
g=self._backend._bn_to_int(g[0]),
q=q_val,
),
y=self._backend._bn_to_int(pub_key[0]),
),
x=self._backend._bn_to_int(priv_key[0]),
)
def exchange(self, peer_public_key: dh.DHPublicKey) -> bytes:
if not isinstance(peer_public_key, _DHPublicKey):
raise TypeError("peer_public_key must be a DHPublicKey")
ctx = self._backend._lib.EVP_PKEY_CTX_new(
self._evp_pkey, self._backend._ffi.NULL
)
self._backend.openssl_assert(ctx != self._backend._ffi.NULL)
ctx = self._backend._ffi.gc(ctx, self._backend._lib.EVP_PKEY_CTX_free)
res = self._backend._lib.EVP_PKEY_derive_init(ctx)
self._backend.openssl_assert(res == 1)
res = self._backend._lib.EVP_PKEY_derive_set_peer(
ctx, peer_public_key._evp_pkey
)
# Invalid kex errors here in OpenSSL 3.0 because checks were moved
# to EVP_PKEY_derive_set_peer
self._exchange_assert(res == 1)
keylen = self._backend._ffi.new("size_t *")
res = self._backend._lib.EVP_PKEY_derive(
ctx, self._backend._ffi.NULL, keylen
)
# Invalid kex errors here in OpenSSL < 3
self._exchange_assert(res == 1)
self._backend.openssl_assert(keylen[0] > 0)
buf = self._backend._ffi.new("unsigned char[]", keylen[0])
res = self._backend._lib.EVP_PKEY_derive(ctx, buf, keylen)
self._backend.openssl_assert(res == 1)
key = self._backend._ffi.buffer(buf, keylen[0])[:]
pad = self._key_size_bytes - len(key)
if pad > 0:
key = (b"\x00" * pad) + key
return key
def _exchange_assert(self, ok):
if not ok:
errors_with_text = self._backend._consume_errors_with_text()
raise ValueError(
"Error computing shared key.",
errors_with_text,
)
def public_key(self) -> dh.DHPublicKey:
dh_cdata = _dh_params_dup(self._dh_cdata, self._backend)
pub_key = self._backend._ffi.new("BIGNUM **")
self._backend._lib.DH_get0_key(
self._dh_cdata, pub_key, self._backend._ffi.NULL
)
self._backend.openssl_assert(pub_key[0] != self._backend._ffi.NULL)
pub_key_dup = self._backend._lib.BN_dup(pub_key[0])
self._backend.openssl_assert(pub_key_dup != self._backend._ffi.NULL)
res = self._backend._lib.DH_set0_key(
dh_cdata, pub_key_dup, self._backend._ffi.NULL
)
self._backend.openssl_assert(res == 1)
evp_pkey = self._backend._dh_cdata_to_evp_pkey(dh_cdata)
return _DHPublicKey(self._backend, dh_cdata, evp_pkey)
def parameters(self) -> dh.DHParameters:
return _dh_cdata_to_parameters(self._dh_cdata, self._backend)
def private_bytes(
self,
encoding: serialization.Encoding,
format: serialization.PrivateFormat,
encryption_algorithm: serialization.KeySerializationEncryption,
) -> bytes:
if format is not serialization.PrivateFormat.PKCS8:
raise ValueError(
"DH private keys support only PKCS8 serialization"
)
if not self._backend._lib.Cryptography_HAS_EVP_PKEY_DHX:
q = self._backend._ffi.new("BIGNUM **")
self._backend._lib.DH_get0_pqg(
self._dh_cdata,
self._backend._ffi.NULL,
q,
self._backend._ffi.NULL,
)
if q[0] != self._backend._ffi.NULL:
raise UnsupportedAlgorithm(
"DH X9.42 serialization is not supported",
_Reasons.UNSUPPORTED_SERIALIZATION,
)
return self._backend._private_key_bytes(
encoding,
format,
encryption_algorithm,
self,
self._evp_pkey,
self._dh_cdata,
)
class _DHPublicKey(dh.DHPublicKey):
def __init__(self, backend, dh_cdata, evp_pkey):
self._backend = backend
self._dh_cdata = dh_cdata
self._evp_pkey = evp_pkey
self._key_size_bits = _get_dh_num_bits(self._backend, self._dh_cdata)
@property
def key_size(self) -> int:
return self._key_size_bits
def public_numbers(self) -> dh.DHPublicNumbers:
p = self._backend._ffi.new("BIGNUM **")
g = self._backend._ffi.new("BIGNUM **")
q = self._backend._ffi.new("BIGNUM **")
self._backend._lib.DH_get0_pqg(self._dh_cdata, p, q, g)
self._backend.openssl_assert(p[0] != self._backend._ffi.NULL)
self._backend.openssl_assert(g[0] != self._backend._ffi.NULL)
if q[0] == self._backend._ffi.NULL:
q_val = None
else:
q_val = self._backend._bn_to_int(q[0])
pub_key = self._backend._ffi.new("BIGNUM **")
self._backend._lib.DH_get0_key(
self._dh_cdata, pub_key, self._backend._ffi.NULL
)
self._backend.openssl_assert(pub_key[0] != self._backend._ffi.NULL)
return dh.DHPublicNumbers(
parameter_numbers=dh.DHParameterNumbers(
p=self._backend._bn_to_int(p[0]),
g=self._backend._bn_to_int(g[0]),
q=q_val,
),
y=self._backend._bn_to_int(pub_key[0]),
)
def parameters(self) -> dh.DHParameters:
return _dh_cdata_to_parameters(self._dh_cdata, self._backend)
def public_bytes(
self,
encoding: serialization.Encoding,
format: serialization.PublicFormat,
) -> bytes:
if format is not serialization.PublicFormat.SubjectPublicKeyInfo:
raise ValueError(
"DH public keys support only "
"SubjectPublicKeyInfo serialization"
)
if not self._backend._lib.Cryptography_HAS_EVP_PKEY_DHX:
q = self._backend._ffi.new("BIGNUM **")
self._backend._lib.DH_get0_pqg(
self._dh_cdata,
self._backend._ffi.NULL,
q,
self._backend._ffi.NULL,
)
if q[0] != self._backend._ffi.NULL:
raise UnsupportedAlgorithm(
"DH X9.42 serialization is not supported",
_Reasons.UNSUPPORTED_SERIALIZATION,
)
return self._backend._public_key_bytes(
encoding, format, self, self._evp_pkey, None
)
| # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from cryptography.exceptions import UnsupportedAlgorithm, _Reasons
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import dh
def _dh_params_dup(dh_cdata, backend):
lib = backend._lib
ffi = backend._ffi
param_cdata = lib.DHparams_dup(dh_cdata)
backend.openssl_assert(param_cdata != ffi.NULL)
param_cdata = ffi.gc(param_cdata, lib.DH_free)
if lib.CRYPTOGRAPHY_IS_LIBRESSL:
# In libressl DHparams_dup don't copy q
q = ffi.new("BIGNUM **")
lib.DH_get0_pqg(dh_cdata, ffi.NULL, q, ffi.NULL)
q_dup = lib.BN_dup(q[0])
res = lib.DH_set0_pqg(param_cdata, ffi.NULL, q_dup, ffi.NULL)
backend.openssl_assert(res == 1)
return param_cdata
def _dh_cdata_to_parameters(dh_cdata, backend):
param_cdata = _dh_params_dup(dh_cdata, backend)
return _DHParameters(backend, param_cdata)
class _DHParameters(dh.DHParameters):
def __init__(self, backend, dh_cdata):
self._backend = backend
self._dh_cdata = dh_cdata
def parameter_numbers(self) -> dh.DHParameterNumbers:
p = self._backend._ffi.new("BIGNUM **")
g = self._backend._ffi.new("BIGNUM **")
q = self._backend._ffi.new("BIGNUM **")
self._backend._lib.DH_get0_pqg(self._dh_cdata, p, q, g)
self._backend.openssl_assert(p[0] != self._backend._ffi.NULL)
self._backend.openssl_assert(g[0] != self._backend._ffi.NULL)
if q[0] == self._backend._ffi.NULL:
q_val = None
else:
q_val = self._backend._bn_to_int(q[0])
return dh.DHParameterNumbers(
p=self._backend._bn_to_int(p[0]),
g=self._backend._bn_to_int(g[0]),
q=q_val,
)
def generate_private_key(self) -> dh.DHPrivateKey:
return self._backend.generate_dh_private_key(self)
def parameter_bytes(
self,
encoding: serialization.Encoding,
format: serialization.ParameterFormat,
) -> bytes:
if format is not serialization.ParameterFormat.PKCS3:
raise ValueError("Only PKCS3 serialization is supported")
if not self._backend._lib.Cryptography_HAS_EVP_PKEY_DHX:
q = self._backend._ffi.new("BIGNUM **")
self._backend._lib.DH_get0_pqg(
self._dh_cdata,
self._backend._ffi.NULL,
q,
self._backend._ffi.NULL,
)
if q[0] != self._backend._ffi.NULL:
raise UnsupportedAlgorithm(
"DH X9.42 serialization is not supported",
_Reasons.UNSUPPORTED_SERIALIZATION,
)
return self._backend._parameter_bytes(encoding, format, self._dh_cdata)
def _get_dh_num_bits(backend, dh_cdata) -> int:
p = backend._ffi.new("BIGNUM **")
backend._lib.DH_get0_pqg(dh_cdata, p, backend._ffi.NULL, backend._ffi.NULL)
backend.openssl_assert(p[0] != backend._ffi.NULL)
return backend._lib.BN_num_bits(p[0])
class _DHPrivateKey(dh.DHPrivateKey):
def __init__(self, backend, dh_cdata, evp_pkey):
self._backend = backend
self._dh_cdata = dh_cdata
self._evp_pkey = evp_pkey
self._key_size_bytes = self._backend._lib.DH_size(dh_cdata)
@property
def key_size(self) -> int:
return _get_dh_num_bits(self._backend, self._dh_cdata)
def private_numbers(self) -> dh.DHPrivateNumbers:
p = self._backend._ffi.new("BIGNUM **")
g = self._backend._ffi.new("BIGNUM **")
q = self._backend._ffi.new("BIGNUM **")
self._backend._lib.DH_get0_pqg(self._dh_cdata, p, q, g)
self._backend.openssl_assert(p[0] != self._backend._ffi.NULL)
self._backend.openssl_assert(g[0] != self._backend._ffi.NULL)
if q[0] == self._backend._ffi.NULL:
q_val = None
else:
q_val = self._backend._bn_to_int(q[0])
pub_key = self._backend._ffi.new("BIGNUM **")
priv_key = self._backend._ffi.new("BIGNUM **")
self._backend._lib.DH_get0_key(self._dh_cdata, pub_key, priv_key)
self._backend.openssl_assert(pub_key[0] != self._backend._ffi.NULL)
self._backend.openssl_assert(priv_key[0] != self._backend._ffi.NULL)
return dh.DHPrivateNumbers(
public_numbers=dh.DHPublicNumbers(
parameter_numbers=dh.DHParameterNumbers(
p=self._backend._bn_to_int(p[0]),
g=self._backend._bn_to_int(g[0]),
q=q_val,
),
y=self._backend._bn_to_int(pub_key[0]),
),
x=self._backend._bn_to_int(priv_key[0]),
)
def exchange(self, peer_public_key: dh.DHPublicKey) -> bytes:
if not isinstance(peer_public_key, _DHPublicKey):
raise TypeError("peer_public_key must be a DHPublicKey")
ctx = self._backend._lib.EVP_PKEY_CTX_new(
self._evp_pkey, self._backend._ffi.NULL
)
self._backend.openssl_assert(ctx != self._backend._ffi.NULL)
ctx = self._backend._ffi.gc(ctx, self._backend._lib.EVP_PKEY_CTX_free)
res = self._backend._lib.EVP_PKEY_derive_init(ctx)
self._backend.openssl_assert(res == 1)
res = self._backend._lib.EVP_PKEY_derive_set_peer(
ctx, peer_public_key._evp_pkey
)
# Invalid kex errors here in OpenSSL 3.0 because checks were moved
# to EVP_PKEY_derive_set_peer
self._exchange_assert(res == 1)
keylen = self._backend._ffi.new("size_t *")
res = self._backend._lib.EVP_PKEY_derive(
ctx, self._backend._ffi.NULL, keylen
)
# Invalid kex errors here in OpenSSL < 3
self._exchange_assert(res == 1)
self._backend.openssl_assert(keylen[0] > 0)
buf = self._backend._ffi.new("unsigned char[]", keylen[0])
res = self._backend._lib.EVP_PKEY_derive(ctx, buf, keylen)
self._backend.openssl_assert(res == 1)
key = self._backend._ffi.buffer(buf, keylen[0])[:]
pad = self._key_size_bytes - len(key)
if pad > 0:
key = (b"\x00" * pad) + key
return key
def _exchange_assert(self, ok):
if not ok:
errors_with_text = self._backend._consume_errors_with_text()
raise ValueError(
"Error computing shared key.",
errors_with_text,
)
def public_key(self) -> dh.DHPublicKey:
dh_cdata = _dh_params_dup(self._dh_cdata, self._backend)
pub_key = self._backend._ffi.new("BIGNUM **")
self._backend._lib.DH_get0_key(
self._dh_cdata, pub_key, self._backend._ffi.NULL
)
self._backend.openssl_assert(pub_key[0] != self._backend._ffi.NULL)
pub_key_dup = self._backend._lib.BN_dup(pub_key[0])
self._backend.openssl_assert(pub_key_dup != self._backend._ffi.NULL)
res = self._backend._lib.DH_set0_key(
dh_cdata, pub_key_dup, self._backend._ffi.NULL
)
self._backend.openssl_assert(res == 1)
evp_pkey = self._backend._dh_cdata_to_evp_pkey(dh_cdata)
return _DHPublicKey(self._backend, dh_cdata, evp_pkey)
def parameters(self) -> dh.DHParameters:
return _dh_cdata_to_parameters(self._dh_cdata, self._backend)
def private_bytes(
self,
encoding: serialization.Encoding,
format: serialization.PrivateFormat,
encryption_algorithm: serialization.KeySerializationEncryption,
) -> bytes:
if format is not serialization.PrivateFormat.PKCS8:
raise ValueError(
"DH private keys support only PKCS8 serialization"
)
if not self._backend._lib.Cryptography_HAS_EVP_PKEY_DHX:
q = self._backend._ffi.new("BIGNUM **")
self._backend._lib.DH_get0_pqg(
self._dh_cdata,
self._backend._ffi.NULL,
q,
self._backend._ffi.NULL,
)
if q[0] != self._backend._ffi.NULL:
raise UnsupportedAlgorithm(
"DH X9.42 serialization is not supported",
_Reasons.UNSUPPORTED_SERIALIZATION,
)
return self._backend._private_key_bytes(
encoding,
format,
encryption_algorithm,
self,
self._evp_pkey,
self._dh_cdata,
)
class _DHPublicKey(dh.DHPublicKey):
def __init__(self, backend, dh_cdata, evp_pkey):
self._backend = backend
self._dh_cdata = dh_cdata
self._evp_pkey = evp_pkey
self._key_size_bits = _get_dh_num_bits(self._backend, self._dh_cdata)
@property
def key_size(self) -> int:
return self._key_size_bits
def public_numbers(self) -> dh.DHPublicNumbers:
p = self._backend._ffi.new("BIGNUM **")
g = self._backend._ffi.new("BIGNUM **")
q = self._backend._ffi.new("BIGNUM **")
self._backend._lib.DH_get0_pqg(self._dh_cdata, p, q, g)
self._backend.openssl_assert(p[0] != self._backend._ffi.NULL)
self._backend.openssl_assert(g[0] != self._backend._ffi.NULL)
if q[0] == self._backend._ffi.NULL:
q_val = None
else:
q_val = self._backend._bn_to_int(q[0])
pub_key = self._backend._ffi.new("BIGNUM **")
self._backend._lib.DH_get0_key(
self._dh_cdata, pub_key, self._backend._ffi.NULL
)
self._backend.openssl_assert(pub_key[0] != self._backend._ffi.NULL)
return dh.DHPublicNumbers(
parameter_numbers=dh.DHParameterNumbers(
p=self._backend._bn_to_int(p[0]),
g=self._backend._bn_to_int(g[0]),
q=q_val,
),
y=self._backend._bn_to_int(pub_key[0]),
)
def parameters(self) -> dh.DHParameters:
return _dh_cdata_to_parameters(self._dh_cdata, self._backend)
def public_bytes(
self,
encoding: serialization.Encoding,
format: serialization.PublicFormat,
) -> bytes:
if format is not serialization.PublicFormat.SubjectPublicKeyInfo:
raise ValueError(
"DH public keys support only "
"SubjectPublicKeyInfo serialization"
)
if not self._backend._lib.Cryptography_HAS_EVP_PKEY_DHX:
q = self._backend._ffi.new("BIGNUM **")
self._backend._lib.DH_get0_pqg(
self._dh_cdata,
self._backend._ffi.NULL,
q,
self._backend._ffi.NULL,
)
if q[0] != self._backend._ffi.NULL:
raise UnsupportedAlgorithm(
"DH X9.42 serialization is not supported",
_Reasons.UNSUPPORTED_SERIALIZATION,
)
return self._backend._public_key_bytes(
encoding, format, self, self._evp_pkey, None
)
| en | 0.862627 | # This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. # In libressl DHparams_dup don't copy q # Invalid kex errors here in OpenSSL 3.0 because checks were moved # to EVP_PKEY_derive_set_peer # Invalid kex errors here in OpenSSL < 3 | 2.100029 | 2 |
brain/brain_libs/joint_model_fix/get_lu_pred.py | zuxfoucault/DoctorBot_demo | 0 | 6627977 | <filename>brain/brain_libs/joint_model_fix/get_lu_pred.py
# -*- coding: utf-8 -*-
"""
Get predicted intent and slot from user utterance.
"""
import tensorflow as tf
import sys
import os
import numpy as np
import jieba
import data_utils
import multi_task_model
DIR1 = "../brain/brain_libs/data_resource/"
DIR2 = "../"
DIR3 = "../joint_model/"
tf.app.flags.DEFINE_float("max_gradient_norm", 5.0,
"Clip gradients to this norm.")
tf.app.flags.DEFINE_integer("batch_size", 16,
"Batch size to use during training.")
tf.app.flags.DEFINE_integer("size", 128, "Size of each model layer.")
tf.app.flags.DEFINE_integer("word_embedding_size", 299, "Size of the word embedding")
tf.app.flags.DEFINE_integer("num_layers", 1, "Number of layers in the model.")
tf.app.flags.DEFINE_integer("in_vocab_size", 10696, "max vocab Size.")
tf.app.flags.DEFINE_integer("out_vocab_size", 10000, "max tag vocab Size.")
tf.app.flags.DEFINE_string("data_dir", DIR3+"data/hospital", "Data directory")
tf.app.flags.DEFINE_string("train_dir", DIR3+"model_tmp", "Training directory.")
tf.app.flags.DEFINE_boolean("use_attention", True,
"Use attention based RNN")
tf.app.flags.DEFINE_integer("max_sequence_length", 30,
"Max sequence length.")
tf.app.flags.DEFINE_float("dropout_keep_prob", 0.5,
"dropout keep cell input and output prob.")
tf.app.flags.DEFINE_boolean("bidirectional_rnn", True,
"Use birectional RNN")
tf.app.flags.DEFINE_string("task", "joint", "Options: joint; intent; tagging")
tf.app.flags.DEFINE_boolean("use_pretrained_word_emb", True,
"Use pretrained word embedding")
FLAGS = tf.app.flags.FLAGS
task = dict({'intent':0, 'tagging':0, 'joint':0})
if FLAGS.task == 'intent':
task['intent'] = 1
elif FLAGS.task == 'tagging':
task['tagging'] = 1
elif FLAGS.task == 'joint':
task['intent'] = 1
task['tagging'] = 1
task['joint'] = 1
_buckets = [(FLAGS.max_sequence_length, FLAGS.max_sequence_length)]
# Create vocabularies of the appropriate sizes.
vocab_path = os.path.join(FLAGS.data_dir, "in_vocab_%d.txt" % FLAGS.in_vocab_size)
tag_vocab_path = os.path.join(FLAGS.data_dir, "out_vocab_%d.txt" % FLAGS.out_vocab_size)
label_vocab_path = os.path.join(FLAGS.data_dir, "label.txt")
if FLAGS.use_pretrained_word_emb:
(in_seq_train, in_seq_dev, in_seq_test, vocab_path, embedding) = data_utils.prepare_pretrained_data(
FLAGS.data_dir, FLAGS.in_vocab_size, FLAGS.word_embedding_size, vocab_path)
vocab, rev_vocab = data_utils.initialize_vocabulary(vocab_path)
tag_vocab, rev_tag_vocab = data_utils.initialize_vocabulary(tag_vocab_path)
label_vocab, rev_label_vocab = data_utils.initialize_vocabulary(label_vocab_path)
DIR1 = "../brain/brain_libs/data_resource/"
DIR2 = "../"
jieba.load_userdict(DIR2+"data_resource/doctor_dict.txt")
jieba.load_userdict(DIR2+"data_resource/disease_dict.txt")
jieba.load_userdict(DIR2+"data_resource/division_dict.txt")
jieba.load_userdict(DIR2+"data_resource/week_dict.txt")
jieba.load_userdict(DIR2+"data_resource/other_dict.txt")
_buckets = [(FLAGS.max_sequence_length, FLAGS.max_sequence_length)]
bucket_id = 0
class LuModel(object):
def __init__(self):
def create_model(session, source_vocab_size, target_vocab_size, label_vocab_size):
"""Create model and initialize or load parameters in session."""
with tf.variable_scope("model", reuse=None):
model_test = multi_task_model.MultiTaskModel(
source_vocab_size, target_vocab_size, label_vocab_size, _buckets,
FLAGS.word_embedding_size, FLAGS.size, FLAGS.num_layers,
FLAGS.max_gradient_norm, FLAGS.batch_size,
dropout_keep_prob=FLAGS.dropout_keep_prob, use_lstm=True,
forward_only=True,
use_attention=FLAGS.use_attention,
bidirectional_rnn=FLAGS.bidirectional_rnn,
task=task)
ckpt = tf.train.get_checkpoint_state(FLAGS.train_dir)
if ckpt and tf.gfile.Exists(ckpt.model_checkpoint_path + ".meta"):
print("Reading model parameters from %s" % ckpt.model_checkpoint_path)
model_test.saver.restore(session, ckpt.model_checkpoint_path)
else:
print("Pre-trained model did not exist!")
return model_test
self.sess = tf.Session()
self.model_test = create_model(self.sess, len(vocab),
len(tag_vocab), len(label_vocab))
print('Applying Parameters:')
for k,v in FLAGS.__dict__['__flags'].items():
print('%s: %s' % (k, str(v)))
print("Preparing model in %s" % FLAGS.data_dir)
if not os.path.exists(FLAGS.data_dir):
print("%s not exist! Abort!" % FLAGS.data_dir)
exit
print("Max sequence length: %d." % _buckets[0][0])
print("Creating %d layers of %d units." % (FLAGS.num_layers, FLAGS.size))
print ("Creating model with source_vocab_size=%d, target_vocab_size=%d,\
and label_vocab_size=%d." % (len(vocab), len(tag_vocab), len(label_vocab)))
def semantic_frame(self, sentence):
seg_gen = list(jieba.cut(sentence, cut_all=False))
_sentence = " ".join(seg_gen)
# Get token-ids for the input sentence.
token_ids = data_utils.sentence_to_token_ids(
_sentence, vocab, data_utils.UNK_ID_dict['with_padding'])
encoder_inputs, tags, tag_weights, sequence_length, labels = self.model_test.get_one(
[[[token_ids, [], [0]]]], bucket_id, 0)
_, step_loss, tagging_logits, classification_logits = self.model_test.joint_step(
self.sess, encoder_inputs, tags, tag_weights, labels, sequence_length,
bucket_id, True)
intent_label = rev_label_vocab[np.argmax(classification_logits[0], 0)]
slot_list = [rev_tag_vocab[np.argmax(x)] for x in tagging_logits[:sequence_length[0]]]
slot_dictionary = {'intent': intent_label[1],
'slot': {'disease': '', 'division': '', 'doctor': '', 'time': ''}}
for index, item in enumerate(slot_list):
if item == 'b-disease':
slot_dictionary['slot']['disease'] = seg_gen[index]
elif item == 'b-division':
slot_dictionary['slot']['division'] = seg_gen[index]
elif item == 'b-doctor':
slot_dictionary['slot']['doctor'] = seg_gen[index]
elif item == 'b-time':
slot_dictionary['slot']['time'] = seg_gen[index]
return slot_dictionary
def get_lu_pred(self, sentence=None):
if sentence == None:
# Decode from standard input.
sys.stdout.write("> ")
sys.stdout.flush()
sentence = sys.stdin.readline()
try:
while sentence:
seg_gen = jieba.cut(sentence, cut_all=False)
_sentence = " ".join(seg_gen)
# Get token-ids for the input sentence.
token_ids = data_utils.sentence_to_token_ids(
_sentence, vocab, data_utils.UNK_ID_dict['with_padding'])
# Prepare one batch
encoder_inputs, tags, tag_weights, sequence_length, labels = self.model_test.get_one(
[[[token_ids, [], [0]]]], bucket_id, 0)
# Get prediction logits
_, step_loss, tagging_logits, classification_logits = self.model_test.joint_step(
self.sess, encoder_inputs, tags, tag_weights, labels, sequence_length,
bucket_id, True)
hyp_label = rev_label_vocab[np.argmax(classification_logits[0],0)]
print(hyp_label)
hyp_tags = [rev_tag_vocab[np.argmax(x)] for x in tagging_logits[:sequence_length[0]]]
print(hyp_tags)
print("> ", end="")
sys.stdout.flush()
sentence = sys.stdin.readline()
except KeyboardInterrupt:
print("KeyboardInterrupt")
self.sess.close()
else:
seg_gen = jieba.cut(sentence, cut_all=False)
_sentence = " ".join(seg_gen)
# Get token-ids for the input sentence.
token_ids = data_utils.sentence_to_token_ids(
_sentence, vocab, data_utils.UNK_ID_dict['with_padding'])
encoder_inputs, tags, tag_weights, sequence_length, labels = self.model_test.get_one(
[[[token_ids, [], [0]]]], bucket_id, 0)
_, step_loss, tagging_logits, classification_logits = self.model_test.joint_step(
self.sess, encoder_inputs, tags, tag_weights, labels, sequence_length,
bucket_id, True)
hyp_label = rev_label_vocab[np.argmax(classification_logits[0],0)]
hyp_tags = [rev_tag_vocab[np.argmax(x)] for x in tagging_logits[:sequence_length[0]]]
return hyp_label, hyp_tags
def main():
lu = LuModel()
lu.get_lu_pred()
if __name__ == '__main__':
main()
| <filename>brain/brain_libs/joint_model_fix/get_lu_pred.py
# -*- coding: utf-8 -*-
"""
Get predicted intent and slot from user utterance.
"""
import tensorflow as tf
import sys
import os
import numpy as np
import jieba
import data_utils
import multi_task_model
DIR1 = "../brain/brain_libs/data_resource/"
DIR2 = "../"
DIR3 = "../joint_model/"
tf.app.flags.DEFINE_float("max_gradient_norm", 5.0,
"Clip gradients to this norm.")
tf.app.flags.DEFINE_integer("batch_size", 16,
"Batch size to use during training.")
tf.app.flags.DEFINE_integer("size", 128, "Size of each model layer.")
tf.app.flags.DEFINE_integer("word_embedding_size", 299, "Size of the word embedding")
tf.app.flags.DEFINE_integer("num_layers", 1, "Number of layers in the model.")
tf.app.flags.DEFINE_integer("in_vocab_size", 10696, "max vocab Size.")
tf.app.flags.DEFINE_integer("out_vocab_size", 10000, "max tag vocab Size.")
tf.app.flags.DEFINE_string("data_dir", DIR3+"data/hospital", "Data directory")
tf.app.flags.DEFINE_string("train_dir", DIR3+"model_tmp", "Training directory.")
tf.app.flags.DEFINE_boolean("use_attention", True,
"Use attention based RNN")
tf.app.flags.DEFINE_integer("max_sequence_length", 30,
"Max sequence length.")
tf.app.flags.DEFINE_float("dropout_keep_prob", 0.5,
"dropout keep cell input and output prob.")
tf.app.flags.DEFINE_boolean("bidirectional_rnn", True,
"Use birectional RNN")
tf.app.flags.DEFINE_string("task", "joint", "Options: joint; intent; tagging")
tf.app.flags.DEFINE_boolean("use_pretrained_word_emb", True,
"Use pretrained word embedding")
FLAGS = tf.app.flags.FLAGS
task = dict({'intent':0, 'tagging':0, 'joint':0})
if FLAGS.task == 'intent':
task['intent'] = 1
elif FLAGS.task == 'tagging':
task['tagging'] = 1
elif FLAGS.task == 'joint':
task['intent'] = 1
task['tagging'] = 1
task['joint'] = 1
_buckets = [(FLAGS.max_sequence_length, FLAGS.max_sequence_length)]
# Create vocabularies of the appropriate sizes.
vocab_path = os.path.join(FLAGS.data_dir, "in_vocab_%d.txt" % FLAGS.in_vocab_size)
tag_vocab_path = os.path.join(FLAGS.data_dir, "out_vocab_%d.txt" % FLAGS.out_vocab_size)
label_vocab_path = os.path.join(FLAGS.data_dir, "label.txt")
if FLAGS.use_pretrained_word_emb:
(in_seq_train, in_seq_dev, in_seq_test, vocab_path, embedding) = data_utils.prepare_pretrained_data(
FLAGS.data_dir, FLAGS.in_vocab_size, FLAGS.word_embedding_size, vocab_path)
vocab, rev_vocab = data_utils.initialize_vocabulary(vocab_path)
tag_vocab, rev_tag_vocab = data_utils.initialize_vocabulary(tag_vocab_path)
label_vocab, rev_label_vocab = data_utils.initialize_vocabulary(label_vocab_path)
DIR1 = "../brain/brain_libs/data_resource/"
DIR2 = "../"
jieba.load_userdict(DIR2+"data_resource/doctor_dict.txt")
jieba.load_userdict(DIR2+"data_resource/disease_dict.txt")
jieba.load_userdict(DIR2+"data_resource/division_dict.txt")
jieba.load_userdict(DIR2+"data_resource/week_dict.txt")
jieba.load_userdict(DIR2+"data_resource/other_dict.txt")
_buckets = [(FLAGS.max_sequence_length, FLAGS.max_sequence_length)]
bucket_id = 0
class LuModel(object):
def __init__(self):
def create_model(session, source_vocab_size, target_vocab_size, label_vocab_size):
"""Create model and initialize or load parameters in session."""
with tf.variable_scope("model", reuse=None):
model_test = multi_task_model.MultiTaskModel(
source_vocab_size, target_vocab_size, label_vocab_size, _buckets,
FLAGS.word_embedding_size, FLAGS.size, FLAGS.num_layers,
FLAGS.max_gradient_norm, FLAGS.batch_size,
dropout_keep_prob=FLAGS.dropout_keep_prob, use_lstm=True,
forward_only=True,
use_attention=FLAGS.use_attention,
bidirectional_rnn=FLAGS.bidirectional_rnn,
task=task)
ckpt = tf.train.get_checkpoint_state(FLAGS.train_dir)
if ckpt and tf.gfile.Exists(ckpt.model_checkpoint_path + ".meta"):
print("Reading model parameters from %s" % ckpt.model_checkpoint_path)
model_test.saver.restore(session, ckpt.model_checkpoint_path)
else:
print("Pre-trained model did not exist!")
return model_test
self.sess = tf.Session()
self.model_test = create_model(self.sess, len(vocab),
len(tag_vocab), len(label_vocab))
print('Applying Parameters:')
for k,v in FLAGS.__dict__['__flags'].items():
print('%s: %s' % (k, str(v)))
print("Preparing model in %s" % FLAGS.data_dir)
if not os.path.exists(FLAGS.data_dir):
print("%s not exist! Abort!" % FLAGS.data_dir)
exit
print("Max sequence length: %d." % _buckets[0][0])
print("Creating %d layers of %d units." % (FLAGS.num_layers, FLAGS.size))
print ("Creating model with source_vocab_size=%d, target_vocab_size=%d,\
and label_vocab_size=%d." % (len(vocab), len(tag_vocab), len(label_vocab)))
def semantic_frame(self, sentence):
seg_gen = list(jieba.cut(sentence, cut_all=False))
_sentence = " ".join(seg_gen)
# Get token-ids for the input sentence.
token_ids = data_utils.sentence_to_token_ids(
_sentence, vocab, data_utils.UNK_ID_dict['with_padding'])
encoder_inputs, tags, tag_weights, sequence_length, labels = self.model_test.get_one(
[[[token_ids, [], [0]]]], bucket_id, 0)
_, step_loss, tagging_logits, classification_logits = self.model_test.joint_step(
self.sess, encoder_inputs, tags, tag_weights, labels, sequence_length,
bucket_id, True)
intent_label = rev_label_vocab[np.argmax(classification_logits[0], 0)]
slot_list = [rev_tag_vocab[np.argmax(x)] for x in tagging_logits[:sequence_length[0]]]
slot_dictionary = {'intent': intent_label[1],
'slot': {'disease': '', 'division': '', 'doctor': '', 'time': ''}}
for index, item in enumerate(slot_list):
if item == 'b-disease':
slot_dictionary['slot']['disease'] = seg_gen[index]
elif item == 'b-division':
slot_dictionary['slot']['division'] = seg_gen[index]
elif item == 'b-doctor':
slot_dictionary['slot']['doctor'] = seg_gen[index]
elif item == 'b-time':
slot_dictionary['slot']['time'] = seg_gen[index]
return slot_dictionary
def get_lu_pred(self, sentence=None):
if sentence == None:
# Decode from standard input.
sys.stdout.write("> ")
sys.stdout.flush()
sentence = sys.stdin.readline()
try:
while sentence:
seg_gen = jieba.cut(sentence, cut_all=False)
_sentence = " ".join(seg_gen)
# Get token-ids for the input sentence.
token_ids = data_utils.sentence_to_token_ids(
_sentence, vocab, data_utils.UNK_ID_dict['with_padding'])
# Prepare one batch
encoder_inputs, tags, tag_weights, sequence_length, labels = self.model_test.get_one(
[[[token_ids, [], [0]]]], bucket_id, 0)
# Get prediction logits
_, step_loss, tagging_logits, classification_logits = self.model_test.joint_step(
self.sess, encoder_inputs, tags, tag_weights, labels, sequence_length,
bucket_id, True)
hyp_label = rev_label_vocab[np.argmax(classification_logits[0],0)]
print(hyp_label)
hyp_tags = [rev_tag_vocab[np.argmax(x)] for x in tagging_logits[:sequence_length[0]]]
print(hyp_tags)
print("> ", end="")
sys.stdout.flush()
sentence = sys.stdin.readline()
except KeyboardInterrupt:
print("KeyboardInterrupt")
self.sess.close()
else:
seg_gen = jieba.cut(sentence, cut_all=False)
_sentence = " ".join(seg_gen)
# Get token-ids for the input sentence.
token_ids = data_utils.sentence_to_token_ids(
_sentence, vocab, data_utils.UNK_ID_dict['with_padding'])
encoder_inputs, tags, tag_weights, sequence_length, labels = self.model_test.get_one(
[[[token_ids, [], [0]]]], bucket_id, 0)
_, step_loss, tagging_logits, classification_logits = self.model_test.joint_step(
self.sess, encoder_inputs, tags, tag_weights, labels, sequence_length,
bucket_id, True)
hyp_label = rev_label_vocab[np.argmax(classification_logits[0],0)]
hyp_tags = [rev_tag_vocab[np.argmax(x)] for x in tagging_logits[:sequence_length[0]]]
return hyp_label, hyp_tags
def main():
lu = LuModel()
lu.get_lu_pred()
if __name__ == '__main__':
main()
| en | 0.661115 | # -*- coding: utf-8 -*- Get predicted intent and slot from user utterance. # Create vocabularies of the appropriate sizes. Create model and initialize or load parameters in session. # Get token-ids for the input sentence. # Decode from standard input. # Get token-ids for the input sentence. # Prepare one batch # Get prediction logits # Get token-ids for the input sentence. | 1.926158 | 2 |
setup.py | pymontecarlo/pypenelopetools | 3 | 6627978 | #!/usr/bin/env python
# Standard library modules.
import os
# Third party modules.
from setuptools import setup, find_packages
# Local modules.
import versioneer
# Globals and constants variables.
BASEDIR = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(BASEDIR, "README.md"), "r") as fp:
LONG_DESCRIPTION = fp.read()
PACKAGES = find_packages()
with open(os.path.join(BASEDIR, "requirements.txt"), "r") as fp:
INSTALL_REQUIRES = fp.read().splitlines()
EXTRAS_REQUIRE = {}
CMDCLASS = versioneer.get_cmdclass()
ENTRY_POINTS = {}
setup(
name="pyPENELOPEtools",
version=versioneer.get_version(),
url="https://github.com/pymontecarlo/pypenelopetools",
description="Python interface to facilitate the use of the Monte Carlo code PENELOPE and its main programs",
long_description=LONG_DESCRIPTION,
long_description_content_type="text/markdown",
author="<NAME>",
author_email="<EMAIL>",
license="Apache License, Version 2.0",
classifiers=[
"Development Status :: 4 - Beta",
"License :: OSI Approved :: Apache Software License",
"Natural Language :: English",
"Programming Language :: Python :: 3 :: Only",
"Operating System :: OS Independent",
"Topic :: Scientific/Engineering",
"Topic :: Scientific/Engineering :: Physics",
],
packages=PACKAGES,
install_requires=INSTALL_REQUIRES,
extras_require=EXTRAS_REQUIRE,
cmdclass=CMDCLASS,
entry_points=ENTRY_POINTS,
)
| #!/usr/bin/env python
# Standard library modules.
import os
# Third party modules.
from setuptools import setup, find_packages
# Local modules.
import versioneer
# Globals and constants variables.
BASEDIR = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(BASEDIR, "README.md"), "r") as fp:
LONG_DESCRIPTION = fp.read()
PACKAGES = find_packages()
with open(os.path.join(BASEDIR, "requirements.txt"), "r") as fp:
INSTALL_REQUIRES = fp.read().splitlines()
EXTRAS_REQUIRE = {}
CMDCLASS = versioneer.get_cmdclass()
ENTRY_POINTS = {}
setup(
name="pyPENELOPEtools",
version=versioneer.get_version(),
url="https://github.com/pymontecarlo/pypenelopetools",
description="Python interface to facilitate the use of the Monte Carlo code PENELOPE and its main programs",
long_description=LONG_DESCRIPTION,
long_description_content_type="text/markdown",
author="<NAME>",
author_email="<EMAIL>",
license="Apache License, Version 2.0",
classifiers=[
"Development Status :: 4 - Beta",
"License :: OSI Approved :: Apache Software License",
"Natural Language :: English",
"Programming Language :: Python :: 3 :: Only",
"Operating System :: OS Independent",
"Topic :: Scientific/Engineering",
"Topic :: Scientific/Engineering :: Physics",
],
packages=PACKAGES,
install_requires=INSTALL_REQUIRES,
extras_require=EXTRAS_REQUIRE,
cmdclass=CMDCLASS,
entry_points=ENTRY_POINTS,
)
| en | 0.389572 | #!/usr/bin/env python # Standard library modules. # Third party modules. # Local modules. # Globals and constants variables. | 1.511664 | 2 |
ec2api/tests/functional/api/test_vpn_gateways.py | vishnu-kumar/ec2-api | 0 | 6627979 | # Copyright 2014 OpenStack Foundation
# 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 botocore.exceptions
from ec2api.tests.functional import base
from ec2api.tests.functional import config
CONF = config.CONF
class VpnGatewayTest(base.EC2TestCase):
VPC_CIDR = '10.41.0.0/20'
vpc_id = None
@classmethod
@base.safe_setup
def setUpClass(cls):
super(VpnGatewayTest, cls).setUpClass()
if not base.TesterStateHolder().get_vpc_enabled():
raise cls.skipException('VPC is disabled')
data = cls.client.create_vpc(CidrBlock=cls.VPC_CIDR)
cls.vpc_id = data['Vpc']['VpcId']
cls.get_vpc_waiter().wait_available(cls.vpc_id)
cls.addResourceCleanUpStatic(cls.client.delete_vpc, VpcId=cls.vpc_id)
def test_create_delete_vpn_gateway(self):
data = self.client.create_vpn_gateway(
Type='ipsec.1', AvailabilityZone=CONF.aws.aws_zone)
vgw_id = data['VpnGateway']['VpnGatewayId']
vgw_clean = self.addResourceCleanUp(
self.client.delete_vpn_gateway, VpnGatewayId=vgw_id)
self.get_vpn_gateway_waiter().wait_available(vgw_id)
self.client.delete_vpn_gateway(VpnGatewayId=vgw_id)
self.cancelResourceCleanUp(vgw_clean)
self.get_vpn_gateway_waiter().wait_delete(vgw_id)
try:
data = self.client.describe_vpn_gateways(
VpnGatewayIds=[vgw_id])
self.assertEqual(1, len(data['VpnGateways']))
self.assertEqual('deleted', data['VpnGateways'][0]['State'])
except botocore.exceptions.ClientError as ex:
self.assertEqual('InvalidVpnGatewayID.NotFound',
ex.response['Error']['Code'])
def test_attach_detach_vpn_gateway(self):
data = self.client.create_vpn_gateway(
Type='ipsec.1', AvailabilityZone=CONF.aws.aws_zone)
vgw_id = data['VpnGateway']['VpnGatewayId']
self.addResourceCleanUp(self.client.delete_vpn_gateway,
VpnGatewayId=vgw_id)
self.get_vpn_gateway_waiter().wait_available(vgw_id)
data = self.client.attach_vpn_gateway(VpnGatewayId=vgw_id,
VpcId=self.vpc_id)
attach_clean = self.addResourceCleanUp(
self.client.detach_vpn_gateway,
VpnGatewayId=vgw_id, VpcId=self.vpc_id)
self.assertIn('VpcAttachment', data)
self.assertEqual(self.vpc_id, data['VpcAttachment']['VpcId'])
attach_waiter = self.get_vpn_gateway_attachment_waiter()
attach_waiter.wait_available(vgw_id, 'attached')
data = self.client.detach_vpn_gateway(VpnGatewayId=vgw_id,
VpcId=self.vpc_id)
self.cancelResourceCleanUp(attach_clean)
attach_waiter.wait_delete(vgw_id)
data = self.client.describe_vpn_gateways(VpnGatewayIds=[vgw_id])
self.assertEqual(
'detached',
(data['VpnGateways'][0]['VpcAttachments'] or
[{'State': 'detached'}])[0]['State'])
| # Copyright 2014 OpenStack Foundation
# 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 botocore.exceptions
from ec2api.tests.functional import base
from ec2api.tests.functional import config
CONF = config.CONF
class VpnGatewayTest(base.EC2TestCase):
VPC_CIDR = '10.41.0.0/20'
vpc_id = None
@classmethod
@base.safe_setup
def setUpClass(cls):
super(VpnGatewayTest, cls).setUpClass()
if not base.TesterStateHolder().get_vpc_enabled():
raise cls.skipException('VPC is disabled')
data = cls.client.create_vpc(CidrBlock=cls.VPC_CIDR)
cls.vpc_id = data['Vpc']['VpcId']
cls.get_vpc_waiter().wait_available(cls.vpc_id)
cls.addResourceCleanUpStatic(cls.client.delete_vpc, VpcId=cls.vpc_id)
def test_create_delete_vpn_gateway(self):
data = self.client.create_vpn_gateway(
Type='ipsec.1', AvailabilityZone=CONF.aws.aws_zone)
vgw_id = data['VpnGateway']['VpnGatewayId']
vgw_clean = self.addResourceCleanUp(
self.client.delete_vpn_gateway, VpnGatewayId=vgw_id)
self.get_vpn_gateway_waiter().wait_available(vgw_id)
self.client.delete_vpn_gateway(VpnGatewayId=vgw_id)
self.cancelResourceCleanUp(vgw_clean)
self.get_vpn_gateway_waiter().wait_delete(vgw_id)
try:
data = self.client.describe_vpn_gateways(
VpnGatewayIds=[vgw_id])
self.assertEqual(1, len(data['VpnGateways']))
self.assertEqual('deleted', data['VpnGateways'][0]['State'])
except botocore.exceptions.ClientError as ex:
self.assertEqual('InvalidVpnGatewayID.NotFound',
ex.response['Error']['Code'])
def test_attach_detach_vpn_gateway(self):
data = self.client.create_vpn_gateway(
Type='ipsec.1', AvailabilityZone=CONF.aws.aws_zone)
vgw_id = data['VpnGateway']['VpnGatewayId']
self.addResourceCleanUp(self.client.delete_vpn_gateway,
VpnGatewayId=vgw_id)
self.get_vpn_gateway_waiter().wait_available(vgw_id)
data = self.client.attach_vpn_gateway(VpnGatewayId=vgw_id,
VpcId=self.vpc_id)
attach_clean = self.addResourceCleanUp(
self.client.detach_vpn_gateway,
VpnGatewayId=vgw_id, VpcId=self.vpc_id)
self.assertIn('VpcAttachment', data)
self.assertEqual(self.vpc_id, data['VpcAttachment']['VpcId'])
attach_waiter = self.get_vpn_gateway_attachment_waiter()
attach_waiter.wait_available(vgw_id, 'attached')
data = self.client.detach_vpn_gateway(VpnGatewayId=vgw_id,
VpcId=self.vpc_id)
self.cancelResourceCleanUp(attach_clean)
attach_waiter.wait_delete(vgw_id)
data = self.client.describe_vpn_gateways(VpnGatewayIds=[vgw_id])
self.assertEqual(
'detached',
(data['VpnGateways'][0]['VpcAttachments'] or
[{'State': 'detached'}])[0]['State'])
| en | 0.845743 | # Copyright 2014 OpenStack Foundation # 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. | 1.785381 | 2 |
anaconda_project/requirements_registry/requirements/download.py | kathatherine/anaconda-project | 188 | 6627980 | <filename>anaconda_project/requirements_registry/requirements/download.py<gh_stars>100-1000
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2016, Anaconda, Inc. All rights reserved.
#
# Licensed under the terms of the BSD 3-Clause License.
# The full license is in the file LICENSE.txt, distributed with this software.
# -----------------------------------------------------------------------------
"""File download requirements."""
from __future__ import absolute_import, print_function
import os
from anaconda_project.requirements_registry.requirement import EnvVarRequirement
from anaconda_project.requirements_registry.network_util import urlparse
from anaconda_project.internal.py2_compat import is_string
_hash_algorithms = ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')
class DownloadRequirement(EnvVarRequirement):
"""A requirement for ``env_var`` to point to a downloaded file."""
@classmethod
def _parse(cls, varname, item, problems):
"""Parse an item from the downloads: section."""
url = None
filename = None
hash_algorithm = None
hash_value = None
unzip = None
description = None
if is_string(item):
url = item
elif isinstance(item, dict):
url = item.get('url', None)
if url is None:
problems.append("Download item {} doesn't contain a 'url' field.".format(varname))
return None
description = item.get('description', None)
if description is not None and not is_string(description):
problems.append("'description' field for download item {} is not a string".format(varname))
return None
for method in _hash_algorithms:
if method not in item:
continue
if hash_algorithm is not None:
problems.append("Multiple checksums for download {}: {} and {}.".format(
varname, hash_algorithm, method))
return None
else:
hash_value = item[method]
if is_string(hash_value):
hash_algorithm = method
else:
problems.append("Checksum value for {} should be a string not {}.".format(varname, hash_value))
return None
filename = item.get('filename', None)
unzip = item.get('unzip', None)
if unzip is not None and not isinstance(unzip, bool):
problems.append("Value of 'unzip' for download item {} should be a boolean, not {}.".format(
varname, unzip))
return None
if url is None or not is_string(url):
problems.append(("Download name {} should be followed by a URL string or a dictionary " +
"describing the download.").format(varname))
return None
if url == '':
problems.append("Download item {} has an empty 'url' field.".format(varname))
return None
# urlsplit doesn't seem to ever throw an exception, but it can
# return pretty nonsensical stuff on invalid urls, in particular
# an empty path is very possible
url_path = os.path.basename(urlparse.urlsplit(url).path)
url_path_is_zip = url_path.lower().endswith(".zip")
if filename is None:
if url_path != '':
filename = url_path
if url_path_is_zip:
if unzip is None:
# url is a zip and neither filename nor unzip specified, assume unzip
unzip = True
if unzip:
# unzip specified True, or we guessed True, and url ends in zip;
# take the .zip off the filename we invented based on the url.
filename = filename[:-4]
elif url_path_is_zip and unzip is None and not filename.lower().endswith(".zip"):
# URL is a zip, filename is not a zip, unzip was not specified, so assume
# we want to unzip
unzip = True
if filename is None:
filename = varname
if unzip is None:
unzip = False
return dict(env_var=varname,
url=url,
filename=filename,
hash_algorithm=hash_algorithm,
hash_value=hash_value,
unzip=unzip,
description=description)
def __init__(self,
registry,
env_var,
url,
filename,
hash_algorithm=None,
hash_value=None,
unzip=False,
description=None):
"""Extend init to accept url and hash parameters."""
options = None
if description is not None:
options = dict(description=description)
super(DownloadRequirement, self).__init__(registry=registry, env_var=env_var, options=options)
assert url is not None
assert filename is not None
assert len(url) > 0
assert len(filename) > 0
self.url = url
self.filename = filename
assert hash_algorithm is None or hash_algorithm in _hash_algorithms
self.hash_algorithm = hash_algorithm
self.hash_value = hash_value
self.unzip = unzip
@property
def description(self):
"""Override superclass to supply our description."""
return self._description("A downloaded file which is referenced by {}.".format(self.env_var))
@property
def ignore_patterns(self):
"""Override superclass with our ignore patterns."""
return set(['/' + self.filename, '/' + self.filename + ".part"])
def _why_not_provided(self, environ):
if self.env_var not in environ:
return self._unset_message()
filename = environ[self.env_var]
if not os.path.exists(filename):
return 'File not found: {}'.format(filename)
def check_status(self, environ, local_state_file, default_env_spec_name, overrides, latest_provide_result=None):
"""Override superclass to get our status."""
why_not_provided = self._why_not_provided(environ)
has_been_provided = why_not_provided is None
if has_been_provided:
status_description = ("File downloaded to {}".format(self._get_value_of_env_var(environ)))
else:
status_description = why_not_provided
return self._create_status(environ,
local_state_file,
default_env_spec_name,
overrides=overrides,
has_been_provided=has_been_provided,
status_description=status_description,
provider_class_name='DownloadProvider',
latest_provide_result=latest_provide_result)
| <filename>anaconda_project/requirements_registry/requirements/download.py<gh_stars>100-1000
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2016, Anaconda, Inc. All rights reserved.
#
# Licensed under the terms of the BSD 3-Clause License.
# The full license is in the file LICENSE.txt, distributed with this software.
# -----------------------------------------------------------------------------
"""File download requirements."""
from __future__ import absolute_import, print_function
import os
from anaconda_project.requirements_registry.requirement import EnvVarRequirement
from anaconda_project.requirements_registry.network_util import urlparse
from anaconda_project.internal.py2_compat import is_string
_hash_algorithms = ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')
class DownloadRequirement(EnvVarRequirement):
"""A requirement for ``env_var`` to point to a downloaded file."""
@classmethod
def _parse(cls, varname, item, problems):
"""Parse an item from the downloads: section."""
url = None
filename = None
hash_algorithm = None
hash_value = None
unzip = None
description = None
if is_string(item):
url = item
elif isinstance(item, dict):
url = item.get('url', None)
if url is None:
problems.append("Download item {} doesn't contain a 'url' field.".format(varname))
return None
description = item.get('description', None)
if description is not None and not is_string(description):
problems.append("'description' field for download item {} is not a string".format(varname))
return None
for method in _hash_algorithms:
if method not in item:
continue
if hash_algorithm is not None:
problems.append("Multiple checksums for download {}: {} and {}.".format(
varname, hash_algorithm, method))
return None
else:
hash_value = item[method]
if is_string(hash_value):
hash_algorithm = method
else:
problems.append("Checksum value for {} should be a string not {}.".format(varname, hash_value))
return None
filename = item.get('filename', None)
unzip = item.get('unzip', None)
if unzip is not None and not isinstance(unzip, bool):
problems.append("Value of 'unzip' for download item {} should be a boolean, not {}.".format(
varname, unzip))
return None
if url is None or not is_string(url):
problems.append(("Download name {} should be followed by a URL string or a dictionary " +
"describing the download.").format(varname))
return None
if url == '':
problems.append("Download item {} has an empty 'url' field.".format(varname))
return None
# urlsplit doesn't seem to ever throw an exception, but it can
# return pretty nonsensical stuff on invalid urls, in particular
# an empty path is very possible
url_path = os.path.basename(urlparse.urlsplit(url).path)
url_path_is_zip = url_path.lower().endswith(".zip")
if filename is None:
if url_path != '':
filename = url_path
if url_path_is_zip:
if unzip is None:
# url is a zip and neither filename nor unzip specified, assume unzip
unzip = True
if unzip:
# unzip specified True, or we guessed True, and url ends in zip;
# take the .zip off the filename we invented based on the url.
filename = filename[:-4]
elif url_path_is_zip and unzip is None and not filename.lower().endswith(".zip"):
# URL is a zip, filename is not a zip, unzip was not specified, so assume
# we want to unzip
unzip = True
if filename is None:
filename = varname
if unzip is None:
unzip = False
return dict(env_var=varname,
url=url,
filename=filename,
hash_algorithm=hash_algorithm,
hash_value=hash_value,
unzip=unzip,
description=description)
def __init__(self,
registry,
env_var,
url,
filename,
hash_algorithm=None,
hash_value=None,
unzip=False,
description=None):
"""Extend init to accept url and hash parameters."""
options = None
if description is not None:
options = dict(description=description)
super(DownloadRequirement, self).__init__(registry=registry, env_var=env_var, options=options)
assert url is not None
assert filename is not None
assert len(url) > 0
assert len(filename) > 0
self.url = url
self.filename = filename
assert hash_algorithm is None or hash_algorithm in _hash_algorithms
self.hash_algorithm = hash_algorithm
self.hash_value = hash_value
self.unzip = unzip
@property
def description(self):
"""Override superclass to supply our description."""
return self._description("A downloaded file which is referenced by {}.".format(self.env_var))
@property
def ignore_patterns(self):
"""Override superclass with our ignore patterns."""
return set(['/' + self.filename, '/' + self.filename + ".part"])
def _why_not_provided(self, environ):
if self.env_var not in environ:
return self._unset_message()
filename = environ[self.env_var]
if not os.path.exists(filename):
return 'File not found: {}'.format(filename)
def check_status(self, environ, local_state_file, default_env_spec_name, overrides, latest_provide_result=None):
"""Override superclass to get our status."""
why_not_provided = self._why_not_provided(environ)
has_been_provided = why_not_provided is None
if has_been_provided:
status_description = ("File downloaded to {}".format(self._get_value_of_env_var(environ)))
else:
status_description = why_not_provided
return self._create_status(environ,
local_state_file,
default_env_spec_name,
overrides=overrides,
has_been_provided=has_been_provided,
status_description=status_description,
provider_class_name='DownloadProvider',
latest_provide_result=latest_provide_result)
| en | 0.795427 | # -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) 2016, Anaconda, Inc. All rights reserved. # # Licensed under the terms of the BSD 3-Clause License. # The full license is in the file LICENSE.txt, distributed with this software. # ----------------------------------------------------------------------------- File download requirements. A requirement for ``env_var`` to point to a downloaded file. Parse an item from the downloads: section. # urlsplit doesn't seem to ever throw an exception, but it can # return pretty nonsensical stuff on invalid urls, in particular # an empty path is very possible # url is a zip and neither filename nor unzip specified, assume unzip # unzip specified True, or we guessed True, and url ends in zip; # take the .zip off the filename we invented based on the url. # URL is a zip, filename is not a zip, unzip was not specified, so assume # we want to unzip Extend init to accept url and hash parameters. Override superclass to supply our description. Override superclass with our ignore patterns. Override superclass to get our status. | 2.691685 | 3 |
.github/workflows/maturin_build_wheel.py | xkortex/blake3-py | 0 | 6627981 | <reponame>xkortex/blake3-py
#! /usr/bin/env python3
import os
import platform
import sys
from pathlib import Path
import subprocess
ROOT = Path(__file__).parent.parent.parent
# For macOS and Windows, we run Maturin against the Python interpreter that's
# been installed and configured for this CI run, i.e. the one that's running
# this script. (There are generally several versions installed by default, but
# that's not guaranteed.) For Linux, in order to get "manylinux" compatibility
# right, we need to run Maturin in a special Docker container. We hardcode
# paths to specific interpreter versions, based on where things are installed
# in this container. Our GitHub config has no effect on the the container, so
# we could build all the wheels in one job, but we stick to one-wheel-per-job
# for consistency.
if platform.system() == "Linux":
version_path_components = {
(3, 5): "cp35-cp35m",
(3, 6): "cp36-cp36m",
(3, 7): "cp37-cp37m",
(3, 8): "cp38-cp38",
# This list needs to be kept in sync with tag.yml.
}
version_component = version_path_components[sys.version_info[:2]]
interpreter_path = "/opt/python/" + version_component + "/bin/python"
# See https://github.com/PyO3/maturin#manylinux-and-auditwheel
command = [
"docker",
"run",
"--rm",
"-v",
os.getcwd() + ":/io",
"konstin2/maturin",
"build",
"--release",
"--no-sdist",
"--interpreter",
interpreter_path,
]
subprocess.run(command, check=True)
else:
command = [
"maturin",
"build",
"--release",
"--no-sdist",
"--interpreter",
sys.executable,
]
subprocess.run(command, check=True)
wheels = [x for x in (ROOT / "target" / "wheels").iterdir()]
if len(wheels) != 1:
raise RuntimeError("expected one wheel, found " + repr(wheels))
print("::set-output name=wheel_path::" + str(wheels[0]))
print("::set-output name=wheel_name::" + wheels[0].name)
| #! /usr/bin/env python3
import os
import platform
import sys
from pathlib import Path
import subprocess
ROOT = Path(__file__).parent.parent.parent
# For macOS and Windows, we run Maturin against the Python interpreter that's
# been installed and configured for this CI run, i.e. the one that's running
# this script. (There are generally several versions installed by default, but
# that's not guaranteed.) For Linux, in order to get "manylinux" compatibility
# right, we need to run Maturin in a special Docker container. We hardcode
# paths to specific interpreter versions, based on where things are installed
# in this container. Our GitHub config has no effect on the the container, so
# we could build all the wheels in one job, but we stick to one-wheel-per-job
# for consistency.
if platform.system() == "Linux":
version_path_components = {
(3, 5): "cp35-cp35m",
(3, 6): "cp36-cp36m",
(3, 7): "cp37-cp37m",
(3, 8): "cp38-cp38",
# This list needs to be kept in sync with tag.yml.
}
version_component = version_path_components[sys.version_info[:2]]
interpreter_path = "/opt/python/" + version_component + "/bin/python"
# See https://github.com/PyO3/maturin#manylinux-and-auditwheel
command = [
"docker",
"run",
"--rm",
"-v",
os.getcwd() + ":/io",
"konstin2/maturin",
"build",
"--release",
"--no-sdist",
"--interpreter",
interpreter_path,
]
subprocess.run(command, check=True)
else:
command = [
"maturin",
"build",
"--release",
"--no-sdist",
"--interpreter",
sys.executable,
]
subprocess.run(command, check=True)
wheels = [x for x in (ROOT / "target" / "wheels").iterdir()]
if len(wheels) != 1:
raise RuntimeError("expected one wheel, found " + repr(wheels))
print("::set-output name=wheel_path::" + str(wheels[0]))
print("::set-output name=wheel_name::" + wheels[0].name) | en | 0.914729 | #! /usr/bin/env python3 # For macOS and Windows, we run Maturin against the Python interpreter that's # been installed and configured for this CI run, i.e. the one that's running # this script. (There are generally several versions installed by default, but # that's not guaranteed.) For Linux, in order to get "manylinux" compatibility # right, we need to run Maturin in a special Docker container. We hardcode # paths to specific interpreter versions, based on where things are installed # in this container. Our GitHub config has no effect on the the container, so # we could build all the wheels in one job, but we stick to one-wheel-per-job # for consistency. # This list needs to be kept in sync with tag.yml. # See https://github.com/PyO3/maturin#manylinux-and-auditwheel | 2.277744 | 2 |
palettes/hues.py | maddisoj/wallgen | 0 | 6627982 | import imgen
import math
import random
# Generates colours whose hues are evenly distributed around the colour wheel.
# The saturation and lightness are the same for each colour with both being
# clamped to a subset to prevent murky colours.
class Palette(imgen.Palette):
def generate(self, **kwargs):
colors = []
lower = kwargs['at_least'] if 'at_least' in kwargs else 1
upper = kwargs['at_most'] if 'at_most' in kwargs else 10
amount = kwargs['exactly'] if 'exactly' in kwargs else random.randint(lower, upper)
step = 1 / amount
base = random.uniform(0.0, 1.0)
lightness = random.uniform(0.2, 0.8)
saturation = random.uniform(0.4, 0.8)
hues = [base + i * step for i in range(amount)]
for hue in hues:
if hue < 0.0 or hue > 1.0:
hue -= math.floor(hue)
colors.append(imgen.hsl2rgb(imgen.hsl(hue, saturation, lightness)))
return colors
| import imgen
import math
import random
# Generates colours whose hues are evenly distributed around the colour wheel.
# The saturation and lightness are the same for each colour with both being
# clamped to a subset to prevent murky colours.
class Palette(imgen.Palette):
def generate(self, **kwargs):
colors = []
lower = kwargs['at_least'] if 'at_least' in kwargs else 1
upper = kwargs['at_most'] if 'at_most' in kwargs else 10
amount = kwargs['exactly'] if 'exactly' in kwargs else random.randint(lower, upper)
step = 1 / amount
base = random.uniform(0.0, 1.0)
lightness = random.uniform(0.2, 0.8)
saturation = random.uniform(0.4, 0.8)
hues = [base + i * step for i in range(amount)]
for hue in hues:
if hue < 0.0 or hue > 1.0:
hue -= math.floor(hue)
colors.append(imgen.hsl2rgb(imgen.hsl(hue, saturation, lightness)))
return colors
| en | 0.94258 | # Generates colours whose hues are evenly distributed around the colour wheel. # The saturation and lightness are the same for each colour with both being # clamped to a subset to prevent murky colours. | 3.192552 | 3 |
src/user_auth_api/models.py | Adstefnum/mockexams | 0 | 6627983 | SUB_CHOICES = (
("ENG", "English"),
("MATH", "Mathematics"),
("PHY", "Physics"),
("GEO", "Geography"),
("BIO", "Biology"),
)
EXAM_TYPE = (
("UTME", "Jamb Examination"),
("POST-UTME", 'Post Jamb Examination'),
)
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.db import models
from django.utils import timezone
from django.core.validators import RegexValidator
import uuid
class UserManager(BaseUserManager):
def _create_user(
self,user_name,email, current_jamb_score,
phone_num,password,last_name,first_name, is_staff, is_superuser
):
if not email and phone_num and first_name and last_name and user_name:
raise ValueError('Users must have all specified fields')
now = timezone.now()
email = self.normalize_email(email)
user = self.model(
user_name=user_name,
email=email,
current_jamb_score = current_jamb_score,
phone_num=phone_num,
last_name=last_name,
first_name = first_name,
is_staff=is_staff,
is_active=True,
is_superuser=is_superuser,
last_login=now,
date_joined=now,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self,user_name,email, current_jamb_score,phone_num,password,last_name,first_name):
return self._create_user(
user_name,email, current_jamb_score,phone_num,password,
last_name,first_name, False, False
)
def create_superuser(self,user_name,email,phone_num,password,last_name,first_name):
user=self._create_user(user_name,email,0,phone_num,password,last_name,
first_name, True, True)
return user
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length=254, unique=True)
uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
user_name = models.CharField(max_length=254,null=False, blank=False, unique=True,default=None)
first_name = models.CharField(max_length=254, null=False, blank=False)
last_name = models.CharField(max_length=254,null=False, blank=False)
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
phone_num = models.CharField(validators=[phone_regex], max_length=17,null=False, blank=False, unique=True) # validators should be a list
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
last_login = models.DateTimeField(null=True, blank=True)
date_joined = models.DateTimeField(auto_now_add=True)
current_jamb_score = models.IntegerField(default=0)
USERNAME_FIELD = 'user_name'
EMAIL_FIELD = 'email'
REQUIRED_FIELDS = [
'email', 'phone_num', 'last_name', 'first_name'
]
objects = UserManager()
def get_absolute_url(self):
return "/users/%i/" % (self.uuid)
class userRecord(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE,default=None)
subject = models.CharField(max_length = 100,choices= SUB_CHOICES, default ="English")
exam_type = models.CharField(max_length = 100,choices= EXAM_TYPE,null=True)
score = models.IntegerField(default=0)
taken_at = models.DateTimeField(auto_now_add=True, blank=True)
| SUB_CHOICES = (
("ENG", "English"),
("MATH", "Mathematics"),
("PHY", "Physics"),
("GEO", "Geography"),
("BIO", "Biology"),
)
EXAM_TYPE = (
("UTME", "Jamb Examination"),
("POST-UTME", 'Post Jamb Examination'),
)
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.db import models
from django.utils import timezone
from django.core.validators import RegexValidator
import uuid
class UserManager(BaseUserManager):
def _create_user(
self,user_name,email, current_jamb_score,
phone_num,password,last_name,first_name, is_staff, is_superuser
):
if not email and phone_num and first_name and last_name and user_name:
raise ValueError('Users must have all specified fields')
now = timezone.now()
email = self.normalize_email(email)
user = self.model(
user_name=user_name,
email=email,
current_jamb_score = current_jamb_score,
phone_num=phone_num,
last_name=last_name,
first_name = first_name,
is_staff=is_staff,
is_active=True,
is_superuser=is_superuser,
last_login=now,
date_joined=now,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self,user_name,email, current_jamb_score,phone_num,password,last_name,first_name):
return self._create_user(
user_name,email, current_jamb_score,phone_num,password,
last_name,first_name, False, False
)
def create_superuser(self,user_name,email,phone_num,password,last_name,first_name):
user=self._create_user(user_name,email,0,phone_num,password,last_name,
first_name, True, True)
return user
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length=254, unique=True)
uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
user_name = models.CharField(max_length=254,null=False, blank=False, unique=True,default=None)
first_name = models.CharField(max_length=254, null=False, blank=False)
last_name = models.CharField(max_length=254,null=False, blank=False)
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
phone_num = models.CharField(validators=[phone_regex], max_length=17,null=False, blank=False, unique=True) # validators should be a list
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
last_login = models.DateTimeField(null=True, blank=True)
date_joined = models.DateTimeField(auto_now_add=True)
current_jamb_score = models.IntegerField(default=0)
USERNAME_FIELD = 'user_name'
EMAIL_FIELD = 'email'
REQUIRED_FIELDS = [
'email', 'phone_num', 'last_name', 'first_name'
]
objects = UserManager()
def get_absolute_url(self):
return "/users/%i/" % (self.uuid)
class userRecord(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE,default=None)
subject = models.CharField(max_length = 100,choices= SUB_CHOICES, default ="English")
exam_type = models.CharField(max_length = 100,choices= EXAM_TYPE,null=True)
score = models.IntegerField(default=0)
taken_at = models.DateTimeField(auto_now_add=True, blank=True)
| en | 0.541223 | # validators should be a list | 2.387641 | 2 |
look/views.py | scotthou94/myinstagram | 0 | 6627984 | from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from django.views.generic.edit import CreateView
from look.models import Follow
from look.models import Tweet
from django.contrib.auth.models import User
from stream_django.enrich import Enrich
from stream_django.feed_manager import feed_manager
from django.shortcuts import render_to_response, render, get_object_or_404, redirect
from django.conf import settings
from look.forms import TweetForm, FollowForm
enricher = Enrich()
def index(request):
if not request.user.is_authenticated():
return render(request, 'look/index.html')
if request.method == 'POST':
#create a form instance from post data.the authenticated user is passed only the POST`s text field is needed
form = TweetForm(
{
'user': request.user.pk,
'text': request.POST['text']
}
)
#validate the form
if form.is_valid():
#save a new Tweet object from the form data
form.save()
else: #for a GET request, create a blank form
form = TweetForm()
user = get_object_or_404(User, username=request.user.username)
feeds = feed_manager.get_user_feed(user.id)
activities = feeds.get(limit=25)['results']
activities = enricher.enrich_activities(activities)
context = {
'activities': activities,
'user': user,
'login_user': request.user,
'form': form
}
return render(request, 'look/user.html', context)
class TweetView(CreateView):
model = Tweet
fields = ['text']
def form_valid(self, form):
form.instance.user = self.request.user
return super(Tweet, self).form_valid(form)
def user(request, user_name):
if not request.user.is_authenticated():
return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
form = TweetForm()
user = get_object_or_404(User, username=user_name)
feeds = feed_manager.get_user_feed(user.id)
activities = feeds.get(limit=25)['results']
activities = enricher.enrich_activities(activities)
context = {
'activities': activities,
'user': user,
'login_user': request.user,
'form': form
}
return render(request, 'look/user.html', context)
def follow(request):
form = FollowForm(request.POST)
if form.is_valid():
follow = form.instance
follow.user = request.user
follow.save()
return redirect("/discover/")
def unfollow(request, target_id):
follow = Follow.objects.filter(user=request.user, target_id=target_id).first()
if follow is not None:
follow.delete()
return redirect("/discover/")
def discover(request):
users = User.objects.order_by('date_joined')[:50]
login_user = User.objects.get(username=request.user)
#generating the user list
following = []
for i in users:
if len(i.followers.filter(user=login_user.id)) == 0:
if i == request.user:
pass #user himself shouldn't appear
else:
following.append((i, False)) #not followed
else:
following.append((i, True)) #followed
context = {
'users': users,
'form': FollowForm,
'login_user': request.user,
'following': following
}
return render(request, 'look/discover.html', context)
#Timeline view
def timeline(request):
feed = feed_manager.get_news_feeds(reqeust.user.id)['flat']
activities = feed.get(limit=25)['results']
enricher.enrich_activities(activities)
context = {
'activities': activities
}
return render(request, 'timeline.html', context)
#hashtag view
def hashtag(request, hashtag):
feed = feed_manager.get_feed('hashtag', hashtag)
activities = feed.get(limit=25)['results']
enricher.enrich_activities(activities)
context = {
'activities': activities
}
return render(request, 'hashtag.html', context) | from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from django.views.generic.edit import CreateView
from look.models import Follow
from look.models import Tweet
from django.contrib.auth.models import User
from stream_django.enrich import Enrich
from stream_django.feed_manager import feed_manager
from django.shortcuts import render_to_response, render, get_object_or_404, redirect
from django.conf import settings
from look.forms import TweetForm, FollowForm
enricher = Enrich()
def index(request):
if not request.user.is_authenticated():
return render(request, 'look/index.html')
if request.method == 'POST':
#create a form instance from post data.the authenticated user is passed only the POST`s text field is needed
form = TweetForm(
{
'user': request.user.pk,
'text': request.POST['text']
}
)
#validate the form
if form.is_valid():
#save a new Tweet object from the form data
form.save()
else: #for a GET request, create a blank form
form = TweetForm()
user = get_object_or_404(User, username=request.user.username)
feeds = feed_manager.get_user_feed(user.id)
activities = feeds.get(limit=25)['results']
activities = enricher.enrich_activities(activities)
context = {
'activities': activities,
'user': user,
'login_user': request.user,
'form': form
}
return render(request, 'look/user.html', context)
class TweetView(CreateView):
model = Tweet
fields = ['text']
def form_valid(self, form):
form.instance.user = self.request.user
return super(Tweet, self).form_valid(form)
def user(request, user_name):
if not request.user.is_authenticated():
return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
form = TweetForm()
user = get_object_or_404(User, username=user_name)
feeds = feed_manager.get_user_feed(user.id)
activities = feeds.get(limit=25)['results']
activities = enricher.enrich_activities(activities)
context = {
'activities': activities,
'user': user,
'login_user': request.user,
'form': form
}
return render(request, 'look/user.html', context)
def follow(request):
form = FollowForm(request.POST)
if form.is_valid():
follow = form.instance
follow.user = request.user
follow.save()
return redirect("/discover/")
def unfollow(request, target_id):
follow = Follow.objects.filter(user=request.user, target_id=target_id).first()
if follow is not None:
follow.delete()
return redirect("/discover/")
def discover(request):
users = User.objects.order_by('date_joined')[:50]
login_user = User.objects.get(username=request.user)
#generating the user list
following = []
for i in users:
if len(i.followers.filter(user=login_user.id)) == 0:
if i == request.user:
pass #user himself shouldn't appear
else:
following.append((i, False)) #not followed
else:
following.append((i, True)) #followed
context = {
'users': users,
'form': FollowForm,
'login_user': request.user,
'following': following
}
return render(request, 'look/discover.html', context)
#Timeline view
def timeline(request):
feed = feed_manager.get_news_feeds(reqeust.user.id)['flat']
activities = feed.get(limit=25)['results']
enricher.enrich_activities(activities)
context = {
'activities': activities
}
return render(request, 'timeline.html', context)
#hashtag view
def hashtag(request, hashtag):
feed = feed_manager.get_feed('hashtag', hashtag)
activities = feed.get(limit=25)['results']
enricher.enrich_activities(activities)
context = {
'activities': activities
}
return render(request, 'hashtag.html', context) | en | 0.833393 | #create a form instance from post data.the authenticated user is passed only the POST`s text field is needed #validate the form #save a new Tweet object from the form data #for a GET request, create a blank form #generating the user list #user himself shouldn't appear #not followed #followed #Timeline view #hashtag view | 2.19524 | 2 |
admin/api/wsgi.py | MAHDTech/babylon | 21 | 6627985 | #!/usr/bin/env python3
import flask
import json
import kubernetes
import os
import pathlib
import random
import re
import redis
import string
from hotfix import HotfixKubeApiClient
def random_string(length):
return ''.join([random.choice(string.ascii_letters + string.digits) for n in range(length)])
application = flask.Flask('babylon-admin', static_url_path='/ui')
redis_connection = None
session_cache = {}
session_lifetime = int(os.environ.get('SESSION_LIFETIME', 600))
if 'REDIS_PASSWORD' in os.environ:
redis_connection = redis.StrictRedis(
host = os.environ.get('REDIS_SERVER', 'redis'),
port = int(os.environ.get('REDIS_PORT', 6379)),
password = <PASSWORD>('<PASSWORD>'),
charset = 'utf-8',
db = 0,
decode_responses = True,
)
if os.path.exists('/var/run/secrets/kubernetes.io/serviceaccount/namespace'):
kubernetes.config.load_incluster_config()
else:
kubernetes.config.load_kube_config()
custom_objects_api = kubernetes.client.CustomObjectsApi()
def openshift_auth_user():
user = custom_objects_api.get_cluster_custom_object(
'user.openshift.io', 'v1', 'users', '~'
)
return(user['metadata']['name'])
def proxy_user():
user = flask.request.headers.get('X-Forwarded-User')
# In development get user from authentication
if not user and os.environ.get('ENVIRONMENT') == 'development':
user = openshift_auth_user()
if not user:
flask.abort(401, description="No X-Forwarded-User header")
return user
def proxy_api_client(session):
api_client = HotfixKubeApiClient()
if os.environ.get('ENVIRONMENT') == 'development':
return api_client
api_client.default_headers['Impersonate-User'] = session['user']
for group in session['groups']:
api_client.default_headers.add('Impersonate-Group', group)
return api_client
def start_user_session(user):
user_groups = []
for group in custom_objects_api.list_cluster_custom_object(
'user.openshift.io', 'v1', 'groups'
).get('items', []):
if user in group.get('users', []):
user_groups.append(group['metadata']['name'])
session = {
'user': user,
'groups': user_groups
}
token = random_string(32)
if redis_connection:
redis_connection.setex(token, session_lifetime, json.dumps(session, separators=(',',':')))
else:
session_cache[token] = session
return token
def get_user_session(proxy_user):
authentication_header = flask.request.headers.get('Authentication')
if not authentication_header:
flask.abort(401, description='No Authentication header')
if not authentication_header.startswith('Bearer '):
flask.abort(401, description='Authentication header is not a bearer token')
token = authentication_header[7:]
if redis_connection:
session_json = redis_connection.get(token)
if not session_json:
flask.abort(401, description='Invalid bearer token, not found')
session = json.loads(session_json)
if session.get('user') != proxy_user:
flask.abort(401, description='Invalid bearer token, user mismatch')
return session
else:
session = session_cache.get(token)
if not session:
flask.abort(401, description='Invalid bearer token, no session for token')
elif session.get('user') != proxy_user:
flask.abort(401, description='Invalid bearer token, user mismatch')
return session
@application.route("/session")
def get_session():
user = proxy_user()
token = start_user_session(user)
return flask.jsonify({
"token": token,
"lifetime": session_lifetime,
})
@application.route("/api/<path:path>", methods=['GET', 'PUT', 'POST', 'PATCH', 'DELETE'])
@application.route("/apis/<path:path>", methods=['GET', 'PUT', 'POST', 'PATCH', 'DELETE'])
def apis_proxy(path):
user = proxy_user()
session = get_user_session(user)
api_client = proxy_api_client(session)
header_params = {}
if flask.request.headers.get('Accept'):
header_params['Accept'] = flask.request.headers['Accept']
if flask.request.content_type:
header_params['Content-Type'] = flask.request.content_type
try:
(data, status, headers) = api_client.call_api(
flask.request.path,
flask.request.method,
auth_settings = ['BearerToken'],
body = flask.request.json,
header_params = header_params,
query_params = [ (k, v) for k, v in flask.request.args.items() ],
response_type = 'object',
)
return flask.make_response(
json.dumps(data, separators=(',',':')),
status,
[(k, v) for k, v in headers.items() if k not in ('Content-Length', 'Transfer-Encoding')]
)
except kubernetes.client.rest.ApiException as e:
if e.body:
resp = flask.make_response(e.body, e.status)
resp.headers['Content-Type'] = 'application/json'
flask.abort(resp)
else:
flask.abort(flask.make_response(flask.jsonify({"reason": e.reason}), e.status))
@application.route('/')
def root_path():
return flask.redirect('/ui/')
@application.route('/ui/')
@application.route('/ui/r/<path:path>')
def ui_path(path=None):
return flask.send_file(application.static_folder + '/index.html')
if __name__ == "__main__":
application.run()
| #!/usr/bin/env python3
import flask
import json
import kubernetes
import os
import pathlib
import random
import re
import redis
import string
from hotfix import HotfixKubeApiClient
def random_string(length):
return ''.join([random.choice(string.ascii_letters + string.digits) for n in range(length)])
application = flask.Flask('babylon-admin', static_url_path='/ui')
redis_connection = None
session_cache = {}
session_lifetime = int(os.environ.get('SESSION_LIFETIME', 600))
if 'REDIS_PASSWORD' in os.environ:
redis_connection = redis.StrictRedis(
host = os.environ.get('REDIS_SERVER', 'redis'),
port = int(os.environ.get('REDIS_PORT', 6379)),
password = <PASSWORD>('<PASSWORD>'),
charset = 'utf-8',
db = 0,
decode_responses = True,
)
if os.path.exists('/var/run/secrets/kubernetes.io/serviceaccount/namespace'):
kubernetes.config.load_incluster_config()
else:
kubernetes.config.load_kube_config()
custom_objects_api = kubernetes.client.CustomObjectsApi()
def openshift_auth_user():
user = custom_objects_api.get_cluster_custom_object(
'user.openshift.io', 'v1', 'users', '~'
)
return(user['metadata']['name'])
def proxy_user():
user = flask.request.headers.get('X-Forwarded-User')
# In development get user from authentication
if not user and os.environ.get('ENVIRONMENT') == 'development':
user = openshift_auth_user()
if not user:
flask.abort(401, description="No X-Forwarded-User header")
return user
def proxy_api_client(session):
api_client = HotfixKubeApiClient()
if os.environ.get('ENVIRONMENT') == 'development':
return api_client
api_client.default_headers['Impersonate-User'] = session['user']
for group in session['groups']:
api_client.default_headers.add('Impersonate-Group', group)
return api_client
def start_user_session(user):
user_groups = []
for group in custom_objects_api.list_cluster_custom_object(
'user.openshift.io', 'v1', 'groups'
).get('items', []):
if user in group.get('users', []):
user_groups.append(group['metadata']['name'])
session = {
'user': user,
'groups': user_groups
}
token = random_string(32)
if redis_connection:
redis_connection.setex(token, session_lifetime, json.dumps(session, separators=(',',':')))
else:
session_cache[token] = session
return token
def get_user_session(proxy_user):
authentication_header = flask.request.headers.get('Authentication')
if not authentication_header:
flask.abort(401, description='No Authentication header')
if not authentication_header.startswith('Bearer '):
flask.abort(401, description='Authentication header is not a bearer token')
token = authentication_header[7:]
if redis_connection:
session_json = redis_connection.get(token)
if not session_json:
flask.abort(401, description='Invalid bearer token, not found')
session = json.loads(session_json)
if session.get('user') != proxy_user:
flask.abort(401, description='Invalid bearer token, user mismatch')
return session
else:
session = session_cache.get(token)
if not session:
flask.abort(401, description='Invalid bearer token, no session for token')
elif session.get('user') != proxy_user:
flask.abort(401, description='Invalid bearer token, user mismatch')
return session
@application.route("/session")
def get_session():
user = proxy_user()
token = start_user_session(user)
return flask.jsonify({
"token": token,
"lifetime": session_lifetime,
})
@application.route("/api/<path:path>", methods=['GET', 'PUT', 'POST', 'PATCH', 'DELETE'])
@application.route("/apis/<path:path>", methods=['GET', 'PUT', 'POST', 'PATCH', 'DELETE'])
def apis_proxy(path):
user = proxy_user()
session = get_user_session(user)
api_client = proxy_api_client(session)
header_params = {}
if flask.request.headers.get('Accept'):
header_params['Accept'] = flask.request.headers['Accept']
if flask.request.content_type:
header_params['Content-Type'] = flask.request.content_type
try:
(data, status, headers) = api_client.call_api(
flask.request.path,
flask.request.method,
auth_settings = ['BearerToken'],
body = flask.request.json,
header_params = header_params,
query_params = [ (k, v) for k, v in flask.request.args.items() ],
response_type = 'object',
)
return flask.make_response(
json.dumps(data, separators=(',',':')),
status,
[(k, v) for k, v in headers.items() if k not in ('Content-Length', 'Transfer-Encoding')]
)
except kubernetes.client.rest.ApiException as e:
if e.body:
resp = flask.make_response(e.body, e.status)
resp.headers['Content-Type'] = 'application/json'
flask.abort(resp)
else:
flask.abort(flask.make_response(flask.jsonify({"reason": e.reason}), e.status))
@application.route('/')
def root_path():
return flask.redirect('/ui/')
@application.route('/ui/')
@application.route('/ui/r/<path:path>')
def ui_path(path=None):
return flask.send_file(application.static_folder + '/index.html')
if __name__ == "__main__":
application.run()
| en | 0.654642 | #!/usr/bin/env python3 # In development get user from authentication | 2.124988 | 2 |
engine/game_object/tests/test_game_object.py | codehearts/pickles-fetch-quest | 3 | 6627986 | from ..game_object import GameObject
from unittest.mock import Mock
import unittest
class TestGameObject(unittest.TestCase):
"""Test functionality of a event-drive game objects."""
def setUp(self):
"""Defines the following properties for each test case:
* self.on_move: Listener mock for on_move.
* self.on_move_relative: Listener mock for on_move_relative.
* self.on_collider_enter: Listener mock for on_collider_enter.
* self.game_object: A GameObject at (1,2) with width 3 and height 4.
"""
self.on_collider_enter = Mock()
self.on_move_relative = Mock()
self.on_move = Mock()
self.physics = Mock()
self.game_object = GameObject(x=1, y=2, width=3, height=4)
self.game_object.add_listeners(
on_move=self.on_move,
on_move_relative=self.on_move_relative,
on_collider_enter=self.on_collider_enter)
def test_create_game_object(self):
"""Game objects are initialized with the given dimensions."""
self.assertEqual(1, self.game_object.x)
self.assertEqual(2, self.game_object.y)
self.assertEqual(3, self.game_object.width)
self.assertEqual(4, self.game_object.height)
def test_coordinates_are_read_only(self):
"""Coordinates are read-only."""
with self.assertRaises(AttributeError):
self.game_object.coordinates = (100, 200)
self.game_object.coordinates.x = 300
self.game_object.coordinates.y = 400
self.assertEqual(1, self.game_object.x)
self.assertEqual(2, self.game_object.y)
self.assertEqual(1, self.game_object.coordinates.x)
self.assertEqual(2, self.game_object.coordinates.y)
def test_set_x_dispatches_on_move(self):
"""Setting x coordinate triggers an on_move event."""
self.game_object.x = 100
self.assertEqual(100, self.game_object.x)
self.assertEqual(2, self.game_object.y)
self.assertEqual(3, self.game_object.width)
self.assertEqual(4, self.game_object.height)
self.on_move.assert_called_once_with((100, 2))
def test_set_x_dispatches_on_move_relative(self):
"""Setting x coordinate triggers an on_move_relative event."""
self.game_object.x = 100
self.assertEqual(100, self.game_object.x)
self.assertEqual(2, self.game_object.y)
self.assertEqual(3, self.game_object.width)
self.assertEqual(4, self.game_object.height)
self.on_move_relative.assert_called_once_with((99, 0))
def test_set_x_no_change_does_not_dispatch_events(self):
"""No event is fired when x value does not change."""
self.game_object.x = 1
self.assertEqual(1, self.game_object.x)
self.assertEqual(2, self.game_object.y)
self.assertEqual(3, self.game_object.width)
self.assertEqual(4, self.game_object.height)
self.on_move.assert_not_called()
self.on_move_relative.assert_not_called()
def test_set_y_dispatches_on_move(self):
"""Setting y coordinate triggers an on_move event."""
self.game_object.y = 100
self.assertEqual(1, self.game_object.x)
self.assertEqual(100, self.game_object.y)
self.assertEqual(3, self.game_object.width)
self.assertEqual(4, self.game_object.height)
self.on_move.assert_called_once_with((1, 100))
def test_set_y_dispatches_on_move_relative(self):
"""Setting y coordinate triggers an on_move_relative event."""
self.game_object.y = 100
self.assertEqual(1, self.game_object.x)
self.assertEqual(100, self.game_object.y)
self.assertEqual(3, self.game_object.width)
self.assertEqual(4, self.game_object.height)
self.on_move_relative.assert_called_once_with((0, 98))
def test_set_y_no_change_does_not_dispatch_events(self):
"""No event is fired when y value does not change."""
self.game_object.y = 2
self.assertEqual(1, self.game_object.x)
self.assertEqual(2, self.game_object.y)
self.assertEqual(3, self.game_object.width)
self.assertEqual(4, self.game_object.height)
self.on_move.assert_not_called()
self.on_move_relative.assert_not_called()
def test_set_position_dispatches_on_move(self):
"""Setting position dispatches an on_move event."""
self.game_object.set_position((100, 200))
self.assertEqual(100, self.game_object.x)
self.assertEqual(200, self.game_object.y)
self.assertEqual(3, self.game_object.width)
self.assertEqual(4, self.game_object.height)
self.on_move.assert_called_once_with((100, 200))
def test_set_position_dispatches_on_move_relative(self):
"""Setting position dispatches an on_move_relative event."""
self.game_object.set_position((100, 200))
self.assertEqual(100, self.game_object.x)
self.assertEqual(200, self.game_object.y)
self.assertEqual(3, self.game_object.width)
self.assertEqual(4, self.game_object.height)
self.on_move_relative.assert_called_once_with((99, 198))
def test_set_position_no_change_does_not_dispatch(self):
"""No event is fired when position does not change."""
self.game_object.set_position((1, 2))
self.assertEqual(1, self.game_object.x)
self.assertEqual(2, self.game_object.y)
self.assertEqual(3, self.game_object.width)
self.assertEqual(4, self.game_object.height)
self.on_move.assert_not_called()
self.on_move_relative.assert_not_called()
def test_move_by_dispatches_on_move(self):
"""Setting position relatively dispatches an on_move event."""
self.game_object.move_by((10, 20))
self.assertEqual(11, self.game_object.x)
self.assertEqual(22, self.game_object.y)
self.assertEqual(3, self.game_object.width)
self.assertEqual(4, self.game_object.height)
self.on_move.assert_called_once_with((11, 22))
def test_move_by_dispatches_on_move_relative(self):
"""Setting position relatively dispatches an on_move_relative event."""
self.game_object.move_by((10, 20))
self.assertEqual(11, self.game_object.x)
self.assertEqual(22, self.game_object.y)
self.assertEqual(3, self.game_object.width)
self.assertEqual(4, self.game_object.height)
self.on_move_relative.assert_called_once_with((10, 20))
def test_move_by_no_change_does_not_dispatch(self):
"""No event is fired when relative position does not change."""
self.game_object.move_by((0, 0))
self.assertEqual(1, self.game_object.x)
self.assertEqual(2, self.game_object.y)
self.assertEqual(3, self.game_object.width)
self.assertEqual(4, self.game_object.height)
self.on_move.assert_not_called()
self.on_move_relative.assert_not_called()
def test_update_game_object_does_nothing(self):
"""Updating a game object does nothing."""
self.game_object.update(1000)
self.assertEqual(1, self.game_object.x)
self.assertEqual(2, self.game_object.y)
self.assertEqual(3, self.game_object.width)
self.assertEqual(4, self.game_object.height)
def test_attachments_are_repositioned(self):
"""Objects are repositioned when attached to this one."""
attachment = Mock()
self.game_object.attach(attachment, (10, 20))
# This object was not repositioned
self.assertEqual(1, self.game_object.x)
self.assertEqual(2, self.game_object.y)
self.assertEqual(3, self.game_object.width)
self.assertEqual(4, self.game_object.height)
# The other object was repositioned
attachment.set_position.assert_called_once_with((11, 22))
def test_attachments_listen_for_movement(self):
"""Attachments are added as listeners for relative movement."""
attachment = Mock()
self.game_object.attach(attachment, (10, 20))
attachment.move_by.assert_not_called()
self.game_object.dispatch_event('on_move_relative', (1, 2))
attachment.move_by.assert_called_once_with((1, 2))
| from ..game_object import GameObject
from unittest.mock import Mock
import unittest
class TestGameObject(unittest.TestCase):
"""Test functionality of a event-drive game objects."""
def setUp(self):
"""Defines the following properties for each test case:
* self.on_move: Listener mock for on_move.
* self.on_move_relative: Listener mock for on_move_relative.
* self.on_collider_enter: Listener mock for on_collider_enter.
* self.game_object: A GameObject at (1,2) with width 3 and height 4.
"""
self.on_collider_enter = Mock()
self.on_move_relative = Mock()
self.on_move = Mock()
self.physics = Mock()
self.game_object = GameObject(x=1, y=2, width=3, height=4)
self.game_object.add_listeners(
on_move=self.on_move,
on_move_relative=self.on_move_relative,
on_collider_enter=self.on_collider_enter)
def test_create_game_object(self):
"""Game objects are initialized with the given dimensions."""
self.assertEqual(1, self.game_object.x)
self.assertEqual(2, self.game_object.y)
self.assertEqual(3, self.game_object.width)
self.assertEqual(4, self.game_object.height)
def test_coordinates_are_read_only(self):
"""Coordinates are read-only."""
with self.assertRaises(AttributeError):
self.game_object.coordinates = (100, 200)
self.game_object.coordinates.x = 300
self.game_object.coordinates.y = 400
self.assertEqual(1, self.game_object.x)
self.assertEqual(2, self.game_object.y)
self.assertEqual(1, self.game_object.coordinates.x)
self.assertEqual(2, self.game_object.coordinates.y)
def test_set_x_dispatches_on_move(self):
"""Setting x coordinate triggers an on_move event."""
self.game_object.x = 100
self.assertEqual(100, self.game_object.x)
self.assertEqual(2, self.game_object.y)
self.assertEqual(3, self.game_object.width)
self.assertEqual(4, self.game_object.height)
self.on_move.assert_called_once_with((100, 2))
def test_set_x_dispatches_on_move_relative(self):
"""Setting x coordinate triggers an on_move_relative event."""
self.game_object.x = 100
self.assertEqual(100, self.game_object.x)
self.assertEqual(2, self.game_object.y)
self.assertEqual(3, self.game_object.width)
self.assertEqual(4, self.game_object.height)
self.on_move_relative.assert_called_once_with((99, 0))
def test_set_x_no_change_does_not_dispatch_events(self):
"""No event is fired when x value does not change."""
self.game_object.x = 1
self.assertEqual(1, self.game_object.x)
self.assertEqual(2, self.game_object.y)
self.assertEqual(3, self.game_object.width)
self.assertEqual(4, self.game_object.height)
self.on_move.assert_not_called()
self.on_move_relative.assert_not_called()
def test_set_y_dispatches_on_move(self):
"""Setting y coordinate triggers an on_move event."""
self.game_object.y = 100
self.assertEqual(1, self.game_object.x)
self.assertEqual(100, self.game_object.y)
self.assertEqual(3, self.game_object.width)
self.assertEqual(4, self.game_object.height)
self.on_move.assert_called_once_with((1, 100))
def test_set_y_dispatches_on_move_relative(self):
"""Setting y coordinate triggers an on_move_relative event."""
self.game_object.y = 100
self.assertEqual(1, self.game_object.x)
self.assertEqual(100, self.game_object.y)
self.assertEqual(3, self.game_object.width)
self.assertEqual(4, self.game_object.height)
self.on_move_relative.assert_called_once_with((0, 98))
def test_set_y_no_change_does_not_dispatch_events(self):
"""No event is fired when y value does not change."""
self.game_object.y = 2
self.assertEqual(1, self.game_object.x)
self.assertEqual(2, self.game_object.y)
self.assertEqual(3, self.game_object.width)
self.assertEqual(4, self.game_object.height)
self.on_move.assert_not_called()
self.on_move_relative.assert_not_called()
def test_set_position_dispatches_on_move(self):
"""Setting position dispatches an on_move event."""
self.game_object.set_position((100, 200))
self.assertEqual(100, self.game_object.x)
self.assertEqual(200, self.game_object.y)
self.assertEqual(3, self.game_object.width)
self.assertEqual(4, self.game_object.height)
self.on_move.assert_called_once_with((100, 200))
def test_set_position_dispatches_on_move_relative(self):
"""Setting position dispatches an on_move_relative event."""
self.game_object.set_position((100, 200))
self.assertEqual(100, self.game_object.x)
self.assertEqual(200, self.game_object.y)
self.assertEqual(3, self.game_object.width)
self.assertEqual(4, self.game_object.height)
self.on_move_relative.assert_called_once_with((99, 198))
def test_set_position_no_change_does_not_dispatch(self):
"""No event is fired when position does not change."""
self.game_object.set_position((1, 2))
self.assertEqual(1, self.game_object.x)
self.assertEqual(2, self.game_object.y)
self.assertEqual(3, self.game_object.width)
self.assertEqual(4, self.game_object.height)
self.on_move.assert_not_called()
self.on_move_relative.assert_not_called()
def test_move_by_dispatches_on_move(self):
"""Setting position relatively dispatches an on_move event."""
self.game_object.move_by((10, 20))
self.assertEqual(11, self.game_object.x)
self.assertEqual(22, self.game_object.y)
self.assertEqual(3, self.game_object.width)
self.assertEqual(4, self.game_object.height)
self.on_move.assert_called_once_with((11, 22))
def test_move_by_dispatches_on_move_relative(self):
"""Setting position relatively dispatches an on_move_relative event."""
self.game_object.move_by((10, 20))
self.assertEqual(11, self.game_object.x)
self.assertEqual(22, self.game_object.y)
self.assertEqual(3, self.game_object.width)
self.assertEqual(4, self.game_object.height)
self.on_move_relative.assert_called_once_with((10, 20))
def test_move_by_no_change_does_not_dispatch(self):
"""No event is fired when relative position does not change."""
self.game_object.move_by((0, 0))
self.assertEqual(1, self.game_object.x)
self.assertEqual(2, self.game_object.y)
self.assertEqual(3, self.game_object.width)
self.assertEqual(4, self.game_object.height)
self.on_move.assert_not_called()
self.on_move_relative.assert_not_called()
def test_update_game_object_does_nothing(self):
"""Updating a game object does nothing."""
self.game_object.update(1000)
self.assertEqual(1, self.game_object.x)
self.assertEqual(2, self.game_object.y)
self.assertEqual(3, self.game_object.width)
self.assertEqual(4, self.game_object.height)
def test_attachments_are_repositioned(self):
"""Objects are repositioned when attached to this one."""
attachment = Mock()
self.game_object.attach(attachment, (10, 20))
# This object was not repositioned
self.assertEqual(1, self.game_object.x)
self.assertEqual(2, self.game_object.y)
self.assertEqual(3, self.game_object.width)
self.assertEqual(4, self.game_object.height)
# The other object was repositioned
attachment.set_position.assert_called_once_with((11, 22))
def test_attachments_listen_for_movement(self):
"""Attachments are added as listeners for relative movement."""
attachment = Mock()
self.game_object.attach(attachment, (10, 20))
attachment.move_by.assert_not_called()
self.game_object.dispatch_event('on_move_relative', (1, 2))
attachment.move_by.assert_called_once_with((1, 2))
| en | 0.814603 | Test functionality of a event-drive game objects. Defines the following properties for each test case: * self.on_move: Listener mock for on_move. * self.on_move_relative: Listener mock for on_move_relative. * self.on_collider_enter: Listener mock for on_collider_enter. * self.game_object: A GameObject at (1,2) with width 3 and height 4. Game objects are initialized with the given dimensions. Coordinates are read-only. Setting x coordinate triggers an on_move event. Setting x coordinate triggers an on_move_relative event. No event is fired when x value does not change. Setting y coordinate triggers an on_move event. Setting y coordinate triggers an on_move_relative event. No event is fired when y value does not change. Setting position dispatches an on_move event. Setting position dispatches an on_move_relative event. No event is fired when position does not change. Setting position relatively dispatches an on_move event. Setting position relatively dispatches an on_move_relative event. No event is fired when relative position does not change. Updating a game object does nothing. Objects are repositioned when attached to this one. # This object was not repositioned # The other object was repositioned Attachments are added as listeners for relative movement. | 3.559931 | 4 |
tensorflow/contrib/learn/python/learn/utils/input_fn_utils.py | tianyapiaozi/tensorflow | 848 | 6627987 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Utilities for creating input_fns (deprecated).
This module and all its submodules are deprecated. See
[contrib/learn/README.md](https://www.tensorflow.org/code/tensorflow/contrib/learn/README.md)
for migration instructions.
Contents of this file are moved to tensorflow/python/estimator/export.py.
InputFnOps is renamed to ServingInputReceiver.
build_parsing_serving_input_fn is renamed to
build_parsing_serving_input_receiver_fn.
build_default_serving_input_fn is renamed to
build_raw_serving_input_receiver_fn.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import parsing_ops
from tensorflow.python.util.deprecation import deprecated
class InputFnOps(collections.namedtuple('InputFnOps',
['features',
'labels',
'default_inputs'])):
"""A return type for an input_fn (deprecated).
THIS CLASS IS DEPRECATED. Please use tf.estimator.export.ServingInputReceiver
instead.
This return type is currently only supported for serving input_fn.
Training and eval input_fn should return a `(features, labels)` tuple.
The expected return values are:
features: A dict of string to `Tensor` or `SparseTensor`, specifying the
features to be passed to the model.
labels: A `Tensor`, `SparseTensor`, or a dict of string to `Tensor` or
`SparseTensor`, specifying labels for training or eval. For serving, set
`labels` to `None`.
default_inputs: a dict of string to `Tensor` or `SparseTensor`, specifying
the input placeholders (if any) that this input_fn expects to be fed.
Typically, this is used by a serving input_fn, which expects to be fed
serialized `tf.Example` protos.
"""
@deprecated(None, 'Please use '
'tf.estimator.export.build_parsing_serving_input_receiver_fn.')
def build_parsing_serving_input_fn(feature_spec, default_batch_size=None):
"""Build an input_fn appropriate for serving, expecting fed tf.Examples.
Creates an input_fn that expects a serialized tf.Example fed into a string
placeholder. The function parses the tf.Example according to the provided
feature_spec, and returns all parsed Tensors as features. This input_fn is
for use at serving time, so the labels return value is always None.
Args:
feature_spec: a dict of string to `VarLenFeature`/`FixedLenFeature`.
default_batch_size: the number of query examples expected per batch.
Leave unset for variable batch size (recommended).
Returns:
An input_fn suitable for use in serving.
"""
def input_fn():
"""An input_fn that expects a serialized tf.Example."""
serialized_tf_example = array_ops.placeholder(dtype=dtypes.string,
shape=[default_batch_size],
name='input_example_tensor')
inputs = {'examples': serialized_tf_example}
features = parsing_ops.parse_example(serialized_tf_example, feature_spec)
labels = None # these are not known in serving!
return InputFnOps(features, labels, inputs)
return input_fn
@deprecated(None, 'Please use '
'tf.estimator.export.build_raw_serving_input_receiver_fn.')
def build_default_serving_input_fn(features, default_batch_size=None):
"""Build an input_fn appropriate for serving, expecting feature Tensors.
Creates an input_fn that expects all features to be fed directly.
This input_fn is for use at serving time, so the labels return value is always
None.
Args:
features: a dict of string to `Tensor`.
default_batch_size: the number of query examples expected per batch.
Leave unset for variable batch size (recommended).
Returns:
An input_fn suitable for use in serving.
"""
def input_fn():
"""an input_fn that expects all features to be fed directly."""
features_placeholders = {}
for name, t in features.items():
shape_list = t.get_shape().as_list()
shape_list[0] = default_batch_size
shape = tensor_shape.TensorShape(shape_list)
features_placeholders[name] = array_ops.placeholder(
dtype=t.dtype, shape=shape, name=t.op.name)
labels = None # these are not known in serving!
return InputFnOps(features_placeholders, labels, features_placeholders)
return input_fn
| # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Utilities for creating input_fns (deprecated).
This module and all its submodules are deprecated. See
[contrib/learn/README.md](https://www.tensorflow.org/code/tensorflow/contrib/learn/README.md)
for migration instructions.
Contents of this file are moved to tensorflow/python/estimator/export.py.
InputFnOps is renamed to ServingInputReceiver.
build_parsing_serving_input_fn is renamed to
build_parsing_serving_input_receiver_fn.
build_default_serving_input_fn is renamed to
build_raw_serving_input_receiver_fn.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import parsing_ops
from tensorflow.python.util.deprecation import deprecated
class InputFnOps(collections.namedtuple('InputFnOps',
['features',
'labels',
'default_inputs'])):
"""A return type for an input_fn (deprecated).
THIS CLASS IS DEPRECATED. Please use tf.estimator.export.ServingInputReceiver
instead.
This return type is currently only supported for serving input_fn.
Training and eval input_fn should return a `(features, labels)` tuple.
The expected return values are:
features: A dict of string to `Tensor` or `SparseTensor`, specifying the
features to be passed to the model.
labels: A `Tensor`, `SparseTensor`, or a dict of string to `Tensor` or
`SparseTensor`, specifying labels for training or eval. For serving, set
`labels` to `None`.
default_inputs: a dict of string to `Tensor` or `SparseTensor`, specifying
the input placeholders (if any) that this input_fn expects to be fed.
Typically, this is used by a serving input_fn, which expects to be fed
serialized `tf.Example` protos.
"""
@deprecated(None, 'Please use '
'tf.estimator.export.build_parsing_serving_input_receiver_fn.')
def build_parsing_serving_input_fn(feature_spec, default_batch_size=None):
"""Build an input_fn appropriate for serving, expecting fed tf.Examples.
Creates an input_fn that expects a serialized tf.Example fed into a string
placeholder. The function parses the tf.Example according to the provided
feature_spec, and returns all parsed Tensors as features. This input_fn is
for use at serving time, so the labels return value is always None.
Args:
feature_spec: a dict of string to `VarLenFeature`/`FixedLenFeature`.
default_batch_size: the number of query examples expected per batch.
Leave unset for variable batch size (recommended).
Returns:
An input_fn suitable for use in serving.
"""
def input_fn():
"""An input_fn that expects a serialized tf.Example."""
serialized_tf_example = array_ops.placeholder(dtype=dtypes.string,
shape=[default_batch_size],
name='input_example_tensor')
inputs = {'examples': serialized_tf_example}
features = parsing_ops.parse_example(serialized_tf_example, feature_spec)
labels = None # these are not known in serving!
return InputFnOps(features, labels, inputs)
return input_fn
@deprecated(None, 'Please use '
'tf.estimator.export.build_raw_serving_input_receiver_fn.')
def build_default_serving_input_fn(features, default_batch_size=None):
"""Build an input_fn appropriate for serving, expecting feature Tensors.
Creates an input_fn that expects all features to be fed directly.
This input_fn is for use at serving time, so the labels return value is always
None.
Args:
features: a dict of string to `Tensor`.
default_batch_size: the number of query examples expected per batch.
Leave unset for variable batch size (recommended).
Returns:
An input_fn suitable for use in serving.
"""
def input_fn():
"""an input_fn that expects all features to be fed directly."""
features_placeholders = {}
for name, t in features.items():
shape_list = t.get_shape().as_list()
shape_list[0] = default_batch_size
shape = tensor_shape.TensorShape(shape_list)
features_placeholders[name] = array_ops.placeholder(
dtype=t.dtype, shape=shape, name=t.op.name)
labels = None # these are not known in serving!
return InputFnOps(features_placeholders, labels, features_placeholders)
return input_fn
| en | 0.76672 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== Utilities for creating input_fns (deprecated). This module and all its submodules are deprecated. See [contrib/learn/README.md](https://www.tensorflow.org/code/tensorflow/contrib/learn/README.md) for migration instructions. Contents of this file are moved to tensorflow/python/estimator/export.py. InputFnOps is renamed to ServingInputReceiver. build_parsing_serving_input_fn is renamed to build_parsing_serving_input_receiver_fn. build_default_serving_input_fn is renamed to build_raw_serving_input_receiver_fn. A return type for an input_fn (deprecated). THIS CLASS IS DEPRECATED. Please use tf.estimator.export.ServingInputReceiver instead. This return type is currently only supported for serving input_fn. Training and eval input_fn should return a `(features, labels)` tuple. The expected return values are: features: A dict of string to `Tensor` or `SparseTensor`, specifying the features to be passed to the model. labels: A `Tensor`, `SparseTensor`, or a dict of string to `Tensor` or `SparseTensor`, specifying labels for training or eval. For serving, set `labels` to `None`. default_inputs: a dict of string to `Tensor` or `SparseTensor`, specifying the input placeholders (if any) that this input_fn expects to be fed. Typically, this is used by a serving input_fn, which expects to be fed serialized `tf.Example` protos. Build an input_fn appropriate for serving, expecting fed tf.Examples. Creates an input_fn that expects a serialized tf.Example fed into a string placeholder. The function parses the tf.Example according to the provided feature_spec, and returns all parsed Tensors as features. This input_fn is for use at serving time, so the labels return value is always None. Args: feature_spec: a dict of string to `VarLenFeature`/`FixedLenFeature`. default_batch_size: the number of query examples expected per batch. Leave unset for variable batch size (recommended). Returns: An input_fn suitable for use in serving. An input_fn that expects a serialized tf.Example. # these are not known in serving! Build an input_fn appropriate for serving, expecting feature Tensors. Creates an input_fn that expects all features to be fed directly. This input_fn is for use at serving time, so the labels return value is always None. Args: features: a dict of string to `Tensor`. default_batch_size: the number of query examples expected per batch. Leave unset for variable batch size (recommended). Returns: An input_fn suitable for use in serving. an input_fn that expects all features to be fed directly. # these are not known in serving! | 1.413027 | 1 |
run.py | Kamnitsask/ssl_compact_clustering | 61 | 6627988 | #!/usr/bin/env python
# Copyright (c) 2018, <NAME>
#
# This program is free software; you can redistribute and/or modify
# it under the terms of the Apache License, Version 2.0. See the
# accompanying LICENSE file or read the terms at:
# http://www.apache.org/licenses/LICENSE-2.0
# To see the help and options, in command line try:
# python ./run.py -h
# Example usage from the command line:
# python ./run.py ./configs/mnist/cfg_mnist100.py -o ./output/ -dev 0
from __future__ import absolute_import, division, print_function
import os
import argparse
import sys
import logging
from cclp.frontend.logging.loggers import setup_loggers
from cclp.frontend.config_flags import TrainSessionNModelFlags, TrainerFlags
from cclp.routines import train
def setup_arg_parser() :
parser = argparse.ArgumentParser( prog='Compact Clustering via Label Propagation (CCLP)', formatter_class=argparse.RawTextHelpFormatter,
description= "This software accompanies the research presented in:\n"+\
"Kamnitsas et al, Semi-supervised learning via compact latent space clustering, ICML 2018.\n"+\
"We hope our work aids you in your endeavours.\n"+\
"For questions and feedback contact: <EMAIL>" )
# Required
parser.add_argument(dest='cfg_file', type=str, help="[REQUIRED] Path to config file.")
# Optional cfg that overrides values given in config file.
parser.add_argument("-o", dest='out_path', type=str, help="Path for output folder.")
parser.add_argument("-dev", dest='device', type=int, help="Which device to use. Give -1 to use CPU. Give number (0,1,2...) to use the correcpoding GPU.")
parser.add_argument("-load", dest='model_to_load', type=str, help="At the beginning of training, load model parameters from pretrained model.\n"+\
"Give \"self\" to load last checkpoint from own output dir, eg to continue training.\n"+\
"Else, give path to any pre-trained model.")
parser.add_argument("-pe", dest='plot_save_emb', type=int, help="Plot embedding of training batch (only works for 2D emb): 0=dont plot dont save. 1=save. 2=plot. 3=save and plot.")
# Optionals, cmd line only.
parser.add_argument("-ll", dest='cmd_loglevel', type=str, default="d", help="d=debug, i=info, etc. Default: [d]")
return parser
def override_file_cfg_with_cmd_cfg(cfg, cmd_args):
cfg['out_path'] = os.path.abspath( cmd_args.out_path if cmd_args.out_path is not None else cfg['out_path'] )
cfg['plot_save_emb'] = cmd_args.plot_save_emb if cmd_args.plot_save_emb is not None else cfg['plot_save_emb']
cfg['device'] = cmd_args.device if cmd_args.device is not None else cfg['device']
cfg['model_to_load'] = cmd_args.model_to_load if cmd_args.model_to_load is not None else cfg['model_to_load'] # if "self", it will change later in config_flags.py
if cfg['device'] is None:
raise ValueError('Invalid device given in file and cmd: %s' % cfg['device'])
def check_output_dir_ok( out_path, model_to_load ):
if os.path.exists(out_path) and model_to_load != "self":
user_input = None
try:
user_input = raw_input("The output directory exists already, and [-load] was NOT specified.\n"+\
"We may corrupt another session.\n" +\
"Output path given: "+str(out_path)+"\n"+\
"Are you sure you want to continue? [y/n] : ")
while user_input not in ['y','n']:
user_input = raw_input("Please specify 'y' or 'n': ")
except:
print("\nERROR:\tOutput directory already exists. Tried to ask for user input whether to continue, but failed."+\
"\n\tReason unknown (nohup? remote?)."+\
"\n\tSpecify other dir and retry."+\
"\n\tExiting."); exit(1)
if user_input == 'y':
pass
else:
print("Exiting as requested."); exit(0)
def create_session_folders(main_out_dir):
# Must be given absolute dir.
# Create only the main folder (and its parent if not existing).
parent_out_folder = os.path.abspath( os.path.join(main_out_dir, os.pardir) )
if not os.path.exists(parent_out_folder):
os.mkdir(parent_out_folder)
if not os.path.exists(main_out_dir):
os.mkdir(main_out_dir)
if __name__ == '__main__':
parser = setup_arg_parser()
args = parser.parse_args()
cfg_file = os.path.abspath( args.cfg_file )
cfg = {}
exec(open(cfg_file).read(), cfg) # Now the cfg is populated.
# Override file-config with command-line config if given.
override_file_cfg_with_cmd_cfg(cfg, args)
# Check whether output dir exists or not, and set it up
# check_output_dir_ok( out_path=cfg['out_path'], model_to_load=cfg['model_to_load'] )
create_session_folders( cfg['out_path'] )
# Setup logger
setup_loggers( cmd_loglevel=args.cmd_loglevel, logfile=os.path.join( cfg['out_path'], "logs") )
log = logging.getLogger('main') # created in loggers.py.
log.info("\n======================== Starting new session ==========================\n")
# Print command line args.
log.info("Command line arguments given: \n"+str(args))
# Setup cuda
if cfg['device'] == -1: # Set it up for CPU
os.environ["CUDA_VISIBLE_DEVICES"] = ""
else: # Goes to corresponding
os.environ["CUDA_VISIBLE_DEVICES"] = str(cfg['device'])
try:
if cfg['session_type'] == 'train':
sessionNModelFlags = TrainSessionNModelFlags(cfg)
trainerFlags = TrainerFlags(cfg)
log.info("================ PRINTING CONFIGURATION ====================")
sessionNModelFlags.print_params()
trainerFlags.print_params()
train.train( sessionNModelFlags=sessionNModelFlags, trainerFlags=trainerFlags )
else:
raise ValueError('Invalid session type: %s' % cfg['session_type'])
except Exception as e:
log.exception("Got exception during main process..!")
log.info("Process finished.")
logging.shutdown() # Closes all handlers everywhere.
| #!/usr/bin/env python
# Copyright (c) 2018, <NAME>
#
# This program is free software; you can redistribute and/or modify
# it under the terms of the Apache License, Version 2.0. See the
# accompanying LICENSE file or read the terms at:
# http://www.apache.org/licenses/LICENSE-2.0
# To see the help and options, in command line try:
# python ./run.py -h
# Example usage from the command line:
# python ./run.py ./configs/mnist/cfg_mnist100.py -o ./output/ -dev 0
from __future__ import absolute_import, division, print_function
import os
import argparse
import sys
import logging
from cclp.frontend.logging.loggers import setup_loggers
from cclp.frontend.config_flags import TrainSessionNModelFlags, TrainerFlags
from cclp.routines import train
def setup_arg_parser() :
parser = argparse.ArgumentParser( prog='Compact Clustering via Label Propagation (CCLP)', formatter_class=argparse.RawTextHelpFormatter,
description= "This software accompanies the research presented in:\n"+\
"Kamnitsas et al, Semi-supervised learning via compact latent space clustering, ICML 2018.\n"+\
"We hope our work aids you in your endeavours.\n"+\
"For questions and feedback contact: <EMAIL>" )
# Required
parser.add_argument(dest='cfg_file', type=str, help="[REQUIRED] Path to config file.")
# Optional cfg that overrides values given in config file.
parser.add_argument("-o", dest='out_path', type=str, help="Path for output folder.")
parser.add_argument("-dev", dest='device', type=int, help="Which device to use. Give -1 to use CPU. Give number (0,1,2...) to use the correcpoding GPU.")
parser.add_argument("-load", dest='model_to_load', type=str, help="At the beginning of training, load model parameters from pretrained model.\n"+\
"Give \"self\" to load last checkpoint from own output dir, eg to continue training.\n"+\
"Else, give path to any pre-trained model.")
parser.add_argument("-pe", dest='plot_save_emb', type=int, help="Plot embedding of training batch (only works for 2D emb): 0=dont plot dont save. 1=save. 2=plot. 3=save and plot.")
# Optionals, cmd line only.
parser.add_argument("-ll", dest='cmd_loglevel', type=str, default="d", help="d=debug, i=info, etc. Default: [d]")
return parser
def override_file_cfg_with_cmd_cfg(cfg, cmd_args):
cfg['out_path'] = os.path.abspath( cmd_args.out_path if cmd_args.out_path is not None else cfg['out_path'] )
cfg['plot_save_emb'] = cmd_args.plot_save_emb if cmd_args.plot_save_emb is not None else cfg['plot_save_emb']
cfg['device'] = cmd_args.device if cmd_args.device is not None else cfg['device']
cfg['model_to_load'] = cmd_args.model_to_load if cmd_args.model_to_load is not None else cfg['model_to_load'] # if "self", it will change later in config_flags.py
if cfg['device'] is None:
raise ValueError('Invalid device given in file and cmd: %s' % cfg['device'])
def check_output_dir_ok( out_path, model_to_load ):
if os.path.exists(out_path) and model_to_load != "self":
user_input = None
try:
user_input = raw_input("The output directory exists already, and [-load] was NOT specified.\n"+\
"We may corrupt another session.\n" +\
"Output path given: "+str(out_path)+"\n"+\
"Are you sure you want to continue? [y/n] : ")
while user_input not in ['y','n']:
user_input = raw_input("Please specify 'y' or 'n': ")
except:
print("\nERROR:\tOutput directory already exists. Tried to ask for user input whether to continue, but failed."+\
"\n\tReason unknown (nohup? remote?)."+\
"\n\tSpecify other dir and retry."+\
"\n\tExiting."); exit(1)
if user_input == 'y':
pass
else:
print("Exiting as requested."); exit(0)
def create_session_folders(main_out_dir):
# Must be given absolute dir.
# Create only the main folder (and its parent if not existing).
parent_out_folder = os.path.abspath( os.path.join(main_out_dir, os.pardir) )
if not os.path.exists(parent_out_folder):
os.mkdir(parent_out_folder)
if not os.path.exists(main_out_dir):
os.mkdir(main_out_dir)
if __name__ == '__main__':
parser = setup_arg_parser()
args = parser.parse_args()
cfg_file = os.path.abspath( args.cfg_file )
cfg = {}
exec(open(cfg_file).read(), cfg) # Now the cfg is populated.
# Override file-config with command-line config if given.
override_file_cfg_with_cmd_cfg(cfg, args)
# Check whether output dir exists or not, and set it up
# check_output_dir_ok( out_path=cfg['out_path'], model_to_load=cfg['model_to_load'] )
create_session_folders( cfg['out_path'] )
# Setup logger
setup_loggers( cmd_loglevel=args.cmd_loglevel, logfile=os.path.join( cfg['out_path'], "logs") )
log = logging.getLogger('main') # created in loggers.py.
log.info("\n======================== Starting new session ==========================\n")
# Print command line args.
log.info("Command line arguments given: \n"+str(args))
# Setup cuda
if cfg['device'] == -1: # Set it up for CPU
os.environ["CUDA_VISIBLE_DEVICES"] = ""
else: # Goes to corresponding
os.environ["CUDA_VISIBLE_DEVICES"] = str(cfg['device'])
try:
if cfg['session_type'] == 'train':
sessionNModelFlags = TrainSessionNModelFlags(cfg)
trainerFlags = TrainerFlags(cfg)
log.info("================ PRINTING CONFIGURATION ====================")
sessionNModelFlags.print_params()
trainerFlags.print_params()
train.train( sessionNModelFlags=sessionNModelFlags, trainerFlags=trainerFlags )
else:
raise ValueError('Invalid session type: %s' % cfg['session_type'])
except Exception as e:
log.exception("Got exception during main process..!")
log.info("Process finished.")
logging.shutdown() # Closes all handlers everywhere.
| en | 0.638399 | #!/usr/bin/env python # Copyright (c) 2018, <NAME> # # This program is free software; you can redistribute and/or modify # it under the terms of the Apache License, Version 2.0. See the # accompanying LICENSE file or read the terms at: # http://www.apache.org/licenses/LICENSE-2.0 # To see the help and options, in command line try: # python ./run.py -h # Example usage from the command line: # python ./run.py ./configs/mnist/cfg_mnist100.py -o ./output/ -dev 0 # Required # Optional cfg that overrides values given in config file. # Optionals, cmd line only. # if "self", it will change later in config_flags.py # Must be given absolute dir. # Create only the main folder (and its parent if not existing). # Now the cfg is populated. # Override file-config with command-line config if given. # Check whether output dir exists or not, and set it up # check_output_dir_ok( out_path=cfg['out_path'], model_to_load=cfg['model_to_load'] ) # Setup logger # created in loggers.py. # Print command line args. # Setup cuda # Set it up for CPU # Goes to corresponding # Closes all handlers everywhere. | 2.264035 | 2 |
src/core/mongo_manager.py | MihailButnaru/MongoIngestorS3 | 3 | 6627989 | # Copyright | 2019 | All rights reserved
# <NAME>
"""
Mongo manager will handle all the operations related to the mongo database
"""
class MongoManager():
"""
Mongo Manager handles the collections and documents from a collection
in a storage.
"""
def __init__(self, connection):
self._connection = connection
def get_data_collection(self):
"""
Data is collected and stored in a list from
mongo database, each collection is stored in a list
then in a dict.
Returns:
dict with all the data from the collections
"""
storage_documents = dict()
documents = []
for collection in self._get_collections():
for document in collection.find({}, {'_id': 0}):
documents.append(document)
storage_documents[collection.name] = documents
documents = []
return storage_documents
def _get_collections(self):
"""
Based on the configuration, table name a
list of collections from mongo database is returned.
"""
collections = self._connection.list_collection_names()
return [self._connection[collection] for collection in collections]
| # Copyright | 2019 | All rights reserved
# <NAME>
"""
Mongo manager will handle all the operations related to the mongo database
"""
class MongoManager():
"""
Mongo Manager handles the collections and documents from a collection
in a storage.
"""
def __init__(self, connection):
self._connection = connection
def get_data_collection(self):
"""
Data is collected and stored in a list from
mongo database, each collection is stored in a list
then in a dict.
Returns:
dict with all the data from the collections
"""
storage_documents = dict()
documents = []
for collection in self._get_collections():
for document in collection.find({}, {'_id': 0}):
documents.append(document)
storage_documents[collection.name] = documents
documents = []
return storage_documents
def _get_collections(self):
"""
Based on the configuration, table name a
list of collections from mongo database is returned.
"""
collections = self._connection.list_collection_names()
return [self._connection[collection] for collection in collections]
| en | 0.876934 | # Copyright | 2019 | All rights reserved # <NAME> Mongo manager will handle all the operations related to the mongo database Mongo Manager handles the collections and documents from a collection in a storage. Data is collected and stored in a list from mongo database, each collection is stored in a list then in a dict. Returns: dict with all the data from the collections Based on the configuration, table name a list of collections from mongo database is returned. | 3.371569 | 3 |
VowelConsonent.py | ethanwalsh98/ComputationalThinking | 0 | 6627990 | <filename>VowelConsonent.py<gh_stars>0
userInput = input("Enter your sentence: ")
vowels="AEIOUaeiou"
displayVowels=""
displayConsonants=""
for letter in userImput:
if letter in vowels:
displayVowels += letter
else:
displayConsonants = displayConsonants + letter
print("Vowels: " + displayVowels)
print("") | <filename>VowelConsonent.py<gh_stars>0
userInput = input("Enter your sentence: ")
vowels="AEIOUaeiou"
displayVowels=""
displayConsonants=""
for letter in userImput:
if letter in vowels:
displayVowels += letter
else:
displayConsonants = displayConsonants + letter
print("Vowels: " + displayVowels)
print("") | none | 1 | 3.905045 | 4 | |
dbms/tests/integration/test_storage_s3/test.py | sunadm/ClickHouse | 3 | 6627991 | <gh_stars>1-10
import json
import logging
import random
import pytest
from helpers.cluster import ClickHouseCluster, ClickHouseInstance
import helpers.client
logging.getLogger().setLevel(logging.INFO)
logging.getLogger().addHandler(logging.StreamHandler())
# Creates S3 bucket for tests and allows anonymous read-write access to it.
def prepare_s3_bucket(cluster):
minio_client = cluster.minio_client
if minio_client.bucket_exists(cluster.minio_bucket):
minio_client.remove_bucket(cluster.minio_bucket)
minio_client.make_bucket(cluster.minio_bucket)
# Allows read-write access for bucket without authorization.
bucket_read_write_policy = {"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {"AWS": "*"},
"Action": "s3:GetBucketLocation",
"Resource": "arn:aws:s3:::root"
},
{
"Sid": "",
"Effect": "Allow",
"Principal": {"AWS": "*"},
"Action": "s3:ListBucket",
"Resource": "arn:aws:s3:::root"
},
{
"Sid": "",
"Effect": "Allow",
"Principal": {"AWS": "*"},
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::root/*"
},
{
"Sid": "",
"Effect": "Allow",
"Principal": {"AWS": "*"},
"Action": "s3:PutObject",
"Resource": "arn:aws:s3:::root/*"
}
]}
minio_client.set_bucket_policy(cluster.minio_bucket, json.dumps(bucket_read_write_policy))
cluster.minio_restricted_bucket = "{}-with-auth".format(cluster.minio_bucket)
if minio_client.bucket_exists(cluster.minio_restricted_bucket):
minio_client.remove_bucket(cluster.minio_restricted_bucket)
minio_client.make_bucket(cluster.minio_restricted_bucket)
# Returns content of given S3 file as string.
def get_s3_file_content(cluster, bucket, filename):
# type: (ClickHouseCluster, str) -> str
data = cluster.minio_client.get_object(bucket, filename)
data_str = ""
for chunk in data.stream():
data_str += chunk
return data_str
# Returns nginx access log lines.
def get_nginx_access_logs():
handle = open("/nginx/access.log", "r")
data = handle.readlines()
handle.close()
return data
@pytest.fixture(scope="module")
def cluster():
try:
cluster = ClickHouseCluster(__file__)
cluster.add_instance("restricted_dummy", main_configs=["configs/config_for_test_remote_host_filter.xml"], with_minio=True)
cluster.add_instance("dummy", with_minio=True)
logging.info("Starting cluster...")
cluster.start()
logging.info("Cluster started")
prepare_s3_bucket(cluster)
logging.info("S3 bucket created")
yield cluster
finally:
cluster.shutdown()
def run_query(instance, query, stdin=None, settings=None):
# type: (ClickHouseInstance, str, object, dict) -> str
logging.info("Running query '{}'...".format(query))
result = instance.query(query, stdin=stdin, settings=settings)
logging.info("Query finished")
return result
# Test simple put.
@pytest.mark.parametrize("maybe_auth,positive", [
("", True),
("'minio','minio123',", True),
("'wrongid','wrongkey',", False)
])
def test_put(cluster, maybe_auth, positive):
# type: (ClickHouseCluster) -> None
bucket = cluster.minio_bucket if not maybe_auth else cluster.minio_restricted_bucket
instance = cluster.instances["dummy"] # type: ClickHouseInstance
table_format = "column1 UInt32, column2 UInt32, column3 UInt32"
values = "(1, 2, 3), (3, 2, 1), (78, 43, 45)"
values_csv = "1,2,3\n3,2,1\n78,43,45\n"
filename = "test.csv"
put_query = "insert into table function s3('http://{}:{}/{}/{}', {}'CSV', '{}') values {}".format(
cluster.minio_host, cluster.minio_port, bucket, filename, maybe_auth, table_format, values)
try:
run_query(instance, put_query)
except helpers.client.QueryRuntimeException:
if positive:
raise
else:
assert positive
assert values_csv == get_s3_file_content(cluster, bucket, filename)
# Test put values in CSV format.
@pytest.mark.parametrize("maybe_auth,positive", [
("", True),
("'minio','minio123',", True),
("'wrongid','wrongkey',", False)
])
def test_put_csv(cluster, maybe_auth, positive):
# type: (ClickHouseCluster) -> None
bucket = cluster.minio_bucket if not maybe_auth else cluster.minio_restricted_bucket
instance = cluster.instances["dummy"] # type: ClickHouseInstance
table_format = "column1 UInt32, column2 UInt32, column3 UInt32"
filename = "test.csv"
put_query = "insert into table function s3('http://{}:{}/{}/{}', {}'CSV', '{}') format CSV".format(
cluster.minio_host, cluster.minio_port, bucket, filename, maybe_auth, table_format)
csv_data = "8,9,16\n11,18,13\n22,14,2\n"
try:
run_query(instance, put_query, stdin=csv_data)
except helpers.client.QueryRuntimeException:
if positive:
raise
else:
assert positive
assert csv_data == get_s3_file_content(cluster, bucket, filename)
# Test put and get with S3 server redirect.
def test_put_get_with_redirect(cluster):
# type: (ClickHouseCluster) -> None
bucket = cluster.minio_bucket
instance = cluster.instances["dummy"] # type: ClickHouseInstance
table_format = "column1 UInt32, column2 UInt32, column3 UInt32"
values = "(1, 1, 1), (1, 1, 1), (11, 11, 11)"
values_csv = "1,1,1\n1,1,1\n11,11,11\n"
filename = "test.csv"
query = "insert into table function s3('http://{}:{}/{}/{}', 'CSV', '{}') values {}".format(
cluster.minio_redirect_host, cluster.minio_redirect_port, bucket, filename, table_format, values)
run_query(instance, query)
assert values_csv == get_s3_file_content(cluster, bucket, filename)
query = "select *, column1*column2*column3 from s3('http://{}:{}/{}/{}', 'CSV', '{}')".format(
cluster.minio_redirect_host, cluster.minio_redirect_port, bucket, filename, table_format)
stdout = run_query(instance, query)
assert list(map(str.split, stdout.splitlines())) == [
["1", "1", "1", "1"],
["1", "1", "1", "1"],
["11", "11", "11", "1331"],
]
def test_put_get_with_globs(cluster):
# type: (ClickHouseCluster) -> None
bucket = cluster.minio_bucket
instance = cluster.instances["dummy"] # type: ClickHouseInstance
table_format = "column1 UInt32, column2 UInt32, column3 UInt32"
max_path = ""
for i in range(10):
for j in range(10):
path = "{}_{}/{}.csv".format(i, random.choice(['a', 'b', 'c', 'd']), j)
max_path = max(path, max_path)
values = "({},{},{})".format(i, j, i+j)
query = "insert into table function s3('http://{}:{}/{}/{}', 'CSV', '{}') values {}".format(
cluster.minio_host, cluster.minio_port, bucket, path, table_format, values)
run_query(instance, query)
query = "select sum(column1), sum(column2), sum(column3), min(_file), max(_path) from s3('http://{}:{}/{}/*_{{a,b,c,d}}/%3f.csv', 'CSV', '{}')".format(
cluster.minio_redirect_host, cluster.minio_redirect_port, bucket, table_format)
assert run_query(instance, query).splitlines() == ["450\t450\t900\t0.csv\t{bucket}/{max_path}".format(bucket=bucket, max_path=max_path)]
# Test multipart put.
@pytest.mark.parametrize("maybe_auth,positive", [
("", True),
# ("'minio','minio123',",True), Redirect with credentials not working with nginx.
("'wrongid','wrongkey',", False)
])
def test_multipart_put(cluster, maybe_auth, positive):
# type: (ClickHouseCluster) -> None
bucket = cluster.minio_bucket if not maybe_auth else cluster.minio_restricted_bucket
instance = cluster.instances["dummy"] # type: ClickHouseInstance
table_format = "column1 UInt32, column2 UInt32, column3 UInt32"
# Minimum size of part is 5 Mb for Minio.
# See: https://github.com/minio/minio/blob/master/docs/minio-limits.md
min_part_size_bytes = 5 * 1024 * 1024
csv_size_bytes = int(min_part_size_bytes * 1.5) # To have 2 parts.
one_line_length = 6 # 3 digits, 2 commas, 1 line separator.
# Generate data having size more than one part
int_data = [[1, 2, 3] for i in range(csv_size_bytes / one_line_length)]
csv_data = "".join(["{},{},{}\n".format(x, y, z) for x, y, z in int_data])
assert len(csv_data) > min_part_size_bytes
filename = "test_multipart.csv"
put_query = "insert into table function s3('http://{}:{}/{}/{}', {}'CSV', '{}') format CSV".format(
cluster.minio_redirect_host, cluster.minio_redirect_port, bucket, filename, maybe_auth, table_format)
try:
run_query(instance, put_query, stdin=csv_data, settings={'s3_min_upload_part_size': min_part_size_bytes})
except helpers.client.QueryRuntimeException:
if positive:
raise
else:
assert positive
# Use Nginx access logs to count number of parts uploaded to Minio.
nginx_logs = get_nginx_access_logs()
uploaded_parts = filter(lambda log_line: log_line.find(filename) >= 0 and log_line.find("PUT") >= 0, nginx_logs)
assert len(uploaded_parts) > 1
assert csv_data == get_s3_file_content(cluster, bucket, filename)
def test_remote_host_filter(cluster):
instance = cluster.instances["restricted_dummy"]
format = "column1 UInt32, column2 UInt32, column3 UInt32"
query = "select *, column1*column2*column3 from s3('http://{}:{}/{}/test.csv', 'CSV', '{}')".format(
"invalid_host", cluster.minio_port, cluster.minio_bucket, format)
assert "not allowed in config.xml" in instance.query_and_get_error(query)
other_values = "(1, 1, 1), (1, 1, 1), (11, 11, 11)"
query = "insert into table function s3('http://{}:{}/{}/test.csv', 'CSV', '{}') values {}".format(
"invalid_host", cluster.minio_port, cluster.minio_bucket, format, other_values)
assert "not allowed in config.xml" in instance.query_and_get_error(query)
@pytest.mark.parametrize("s3_storage_args", [
"''", # 1 arguments
"'','','','','',''" # 6 arguments
])
def test_wrong_s3_syntax(cluster, s3_storage_args):
instance = cluster.instances["dummy"] # type: ClickHouseInstance
expected_err_msg = "Code: 42" # NUMBER_OF_ARGUMENTS_DOESNT_MATCH
query = "create table test_table_s3_syntax (id UInt32) ENGINE = S3({})".format(s3_storage_args)
assert expected_err_msg in instance.query_and_get_error(query)
| import json
import logging
import random
import pytest
from helpers.cluster import ClickHouseCluster, ClickHouseInstance
import helpers.client
logging.getLogger().setLevel(logging.INFO)
logging.getLogger().addHandler(logging.StreamHandler())
# Creates S3 bucket for tests and allows anonymous read-write access to it.
def prepare_s3_bucket(cluster):
minio_client = cluster.minio_client
if minio_client.bucket_exists(cluster.minio_bucket):
minio_client.remove_bucket(cluster.minio_bucket)
minio_client.make_bucket(cluster.minio_bucket)
# Allows read-write access for bucket without authorization.
bucket_read_write_policy = {"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {"AWS": "*"},
"Action": "s3:GetBucketLocation",
"Resource": "arn:aws:s3:::root"
},
{
"Sid": "",
"Effect": "Allow",
"Principal": {"AWS": "*"},
"Action": "s3:ListBucket",
"Resource": "arn:aws:s3:::root"
},
{
"Sid": "",
"Effect": "Allow",
"Principal": {"AWS": "*"},
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::root/*"
},
{
"Sid": "",
"Effect": "Allow",
"Principal": {"AWS": "*"},
"Action": "s3:PutObject",
"Resource": "arn:aws:s3:::root/*"
}
]}
minio_client.set_bucket_policy(cluster.minio_bucket, json.dumps(bucket_read_write_policy))
cluster.minio_restricted_bucket = "{}-with-auth".format(cluster.minio_bucket)
if minio_client.bucket_exists(cluster.minio_restricted_bucket):
minio_client.remove_bucket(cluster.minio_restricted_bucket)
minio_client.make_bucket(cluster.minio_restricted_bucket)
# Returns content of given S3 file as string.
def get_s3_file_content(cluster, bucket, filename):
# type: (ClickHouseCluster, str) -> str
data = cluster.minio_client.get_object(bucket, filename)
data_str = ""
for chunk in data.stream():
data_str += chunk
return data_str
# Returns nginx access log lines.
def get_nginx_access_logs():
handle = open("/nginx/access.log", "r")
data = handle.readlines()
handle.close()
return data
@pytest.fixture(scope="module")
def cluster():
try:
cluster = ClickHouseCluster(__file__)
cluster.add_instance("restricted_dummy", main_configs=["configs/config_for_test_remote_host_filter.xml"], with_minio=True)
cluster.add_instance("dummy", with_minio=True)
logging.info("Starting cluster...")
cluster.start()
logging.info("Cluster started")
prepare_s3_bucket(cluster)
logging.info("S3 bucket created")
yield cluster
finally:
cluster.shutdown()
def run_query(instance, query, stdin=None, settings=None):
# type: (ClickHouseInstance, str, object, dict) -> str
logging.info("Running query '{}'...".format(query))
result = instance.query(query, stdin=stdin, settings=settings)
logging.info("Query finished")
return result
# Test simple put.
@pytest.mark.parametrize("maybe_auth,positive", [
("", True),
("'minio','minio123',", True),
("'wrongid','wrongkey',", False)
])
def test_put(cluster, maybe_auth, positive):
# type: (ClickHouseCluster) -> None
bucket = cluster.minio_bucket if not maybe_auth else cluster.minio_restricted_bucket
instance = cluster.instances["dummy"] # type: ClickHouseInstance
table_format = "column1 UInt32, column2 UInt32, column3 UInt32"
values = "(1, 2, 3), (3, 2, 1), (78, 43, 45)"
values_csv = "1,2,3\n3,2,1\n78,43,45\n"
filename = "test.csv"
put_query = "insert into table function s3('http://{}:{}/{}/{}', {}'CSV', '{}') values {}".format(
cluster.minio_host, cluster.minio_port, bucket, filename, maybe_auth, table_format, values)
try:
run_query(instance, put_query)
except helpers.client.QueryRuntimeException:
if positive:
raise
else:
assert positive
assert values_csv == get_s3_file_content(cluster, bucket, filename)
# Test put values in CSV format.
@pytest.mark.parametrize("maybe_auth,positive", [
("", True),
("'minio','minio123',", True),
("'wrongid','wrongkey',", False)
])
def test_put_csv(cluster, maybe_auth, positive):
# type: (ClickHouseCluster) -> None
bucket = cluster.minio_bucket if not maybe_auth else cluster.minio_restricted_bucket
instance = cluster.instances["dummy"] # type: ClickHouseInstance
table_format = "column1 UInt32, column2 UInt32, column3 UInt32"
filename = "test.csv"
put_query = "insert into table function s3('http://{}:{}/{}/{}', {}'CSV', '{}') format CSV".format(
cluster.minio_host, cluster.minio_port, bucket, filename, maybe_auth, table_format)
csv_data = "8,9,16\n11,18,13\n22,14,2\n"
try:
run_query(instance, put_query, stdin=csv_data)
except helpers.client.QueryRuntimeException:
if positive:
raise
else:
assert positive
assert csv_data == get_s3_file_content(cluster, bucket, filename)
# Test put and get with S3 server redirect.
def test_put_get_with_redirect(cluster):
# type: (ClickHouseCluster) -> None
bucket = cluster.minio_bucket
instance = cluster.instances["dummy"] # type: ClickHouseInstance
table_format = "column1 UInt32, column2 UInt32, column3 UInt32"
values = "(1, 1, 1), (1, 1, 1), (11, 11, 11)"
values_csv = "1,1,1\n1,1,1\n11,11,11\n"
filename = "test.csv"
query = "insert into table function s3('http://{}:{}/{}/{}', 'CSV', '{}') values {}".format(
cluster.minio_redirect_host, cluster.minio_redirect_port, bucket, filename, table_format, values)
run_query(instance, query)
assert values_csv == get_s3_file_content(cluster, bucket, filename)
query = "select *, column1*column2*column3 from s3('http://{}:{}/{}/{}', 'CSV', '{}')".format(
cluster.minio_redirect_host, cluster.minio_redirect_port, bucket, filename, table_format)
stdout = run_query(instance, query)
assert list(map(str.split, stdout.splitlines())) == [
["1", "1", "1", "1"],
["1", "1", "1", "1"],
["11", "11", "11", "1331"],
]
def test_put_get_with_globs(cluster):
# type: (ClickHouseCluster) -> None
bucket = cluster.minio_bucket
instance = cluster.instances["dummy"] # type: ClickHouseInstance
table_format = "column1 UInt32, column2 UInt32, column3 UInt32"
max_path = ""
for i in range(10):
for j in range(10):
path = "{}_{}/{}.csv".format(i, random.choice(['a', 'b', 'c', 'd']), j)
max_path = max(path, max_path)
values = "({},{},{})".format(i, j, i+j)
query = "insert into table function s3('http://{}:{}/{}/{}', 'CSV', '{}') values {}".format(
cluster.minio_host, cluster.minio_port, bucket, path, table_format, values)
run_query(instance, query)
query = "select sum(column1), sum(column2), sum(column3), min(_file), max(_path) from s3('http://{}:{}/{}/*_{{a,b,c,d}}/%3f.csv', 'CSV', '{}')".format(
cluster.minio_redirect_host, cluster.minio_redirect_port, bucket, table_format)
assert run_query(instance, query).splitlines() == ["450\t450\t900\t0.csv\t{bucket}/{max_path}".format(bucket=bucket, max_path=max_path)]
# Test multipart put.
@pytest.mark.parametrize("maybe_auth,positive", [
("", True),
# ("'minio','minio123',",True), Redirect with credentials not working with nginx.
("'wrongid','wrongkey',", False)
])
def test_multipart_put(cluster, maybe_auth, positive):
# type: (ClickHouseCluster) -> None
bucket = cluster.minio_bucket if not maybe_auth else cluster.minio_restricted_bucket
instance = cluster.instances["dummy"] # type: ClickHouseInstance
table_format = "column1 UInt32, column2 UInt32, column3 UInt32"
# Minimum size of part is 5 Mb for Minio.
# See: https://github.com/minio/minio/blob/master/docs/minio-limits.md
min_part_size_bytes = 5 * 1024 * 1024
csv_size_bytes = int(min_part_size_bytes * 1.5) # To have 2 parts.
one_line_length = 6 # 3 digits, 2 commas, 1 line separator.
# Generate data having size more than one part
int_data = [[1, 2, 3] for i in range(csv_size_bytes / one_line_length)]
csv_data = "".join(["{},{},{}\n".format(x, y, z) for x, y, z in int_data])
assert len(csv_data) > min_part_size_bytes
filename = "test_multipart.csv"
put_query = "insert into table function s3('http://{}:{}/{}/{}', {}'CSV', '{}') format CSV".format(
cluster.minio_redirect_host, cluster.minio_redirect_port, bucket, filename, maybe_auth, table_format)
try:
run_query(instance, put_query, stdin=csv_data, settings={'s3_min_upload_part_size': min_part_size_bytes})
except helpers.client.QueryRuntimeException:
if positive:
raise
else:
assert positive
# Use Nginx access logs to count number of parts uploaded to Minio.
nginx_logs = get_nginx_access_logs()
uploaded_parts = filter(lambda log_line: log_line.find(filename) >= 0 and log_line.find("PUT") >= 0, nginx_logs)
assert len(uploaded_parts) > 1
assert csv_data == get_s3_file_content(cluster, bucket, filename)
def test_remote_host_filter(cluster):
instance = cluster.instances["restricted_dummy"]
format = "column1 UInt32, column2 UInt32, column3 UInt32"
query = "select *, column1*column2*column3 from s3('http://{}:{}/{}/test.csv', 'CSV', '{}')".format(
"invalid_host", cluster.minio_port, cluster.minio_bucket, format)
assert "not allowed in config.xml" in instance.query_and_get_error(query)
other_values = "(1, 1, 1), (1, 1, 1), (11, 11, 11)"
query = "insert into table function s3('http://{}:{}/{}/test.csv', 'CSV', '{}') values {}".format(
"invalid_host", cluster.minio_port, cluster.minio_bucket, format, other_values)
assert "not allowed in config.xml" in instance.query_and_get_error(query)
@pytest.mark.parametrize("s3_storage_args", [
"''", # 1 arguments
"'','','','','',''" # 6 arguments
])
def test_wrong_s3_syntax(cluster, s3_storage_args):
instance = cluster.instances["dummy"] # type: ClickHouseInstance
expected_err_msg = "Code: 42" # NUMBER_OF_ARGUMENTS_DOESNT_MATCH
query = "create table test_table_s3_syntax (id UInt32) ENGINE = S3({})".format(s3_storage_args)
assert expected_err_msg in instance.query_and_get_error(query) | en | 0.76105 | # Creates S3 bucket for tests and allows anonymous read-write access to it. # Allows read-write access for bucket without authorization. # Returns content of given S3 file as string. # type: (ClickHouseCluster, str) -> str # Returns nginx access log lines. # type: (ClickHouseInstance, str, object, dict) -> str # Test simple put. # type: (ClickHouseCluster) -> None # type: ClickHouseInstance # Test put values in CSV format. # type: (ClickHouseCluster) -> None # type: ClickHouseInstance # Test put and get with S3 server redirect. # type: (ClickHouseCluster) -> None # type: ClickHouseInstance # type: (ClickHouseCluster) -> None # type: ClickHouseInstance # Test multipart put. # ("'minio','minio123',",True), Redirect with credentials not working with nginx. # type: (ClickHouseCluster) -> None # type: ClickHouseInstance # Minimum size of part is 5 Mb for Minio. # See: https://github.com/minio/minio/blob/master/docs/minio-limits.md # To have 2 parts. # 3 digits, 2 commas, 1 line separator. # Generate data having size more than one part # Use Nginx access logs to count number of parts uploaded to Minio. # 1 arguments # 6 arguments # type: ClickHouseInstance # NUMBER_OF_ARGUMENTS_DOESNT_MATCH | 1.80993 | 2 |
faceswap/lib/image.py | huangjunxiong11/FaceMap | 2 | 6627992 | <reponame>huangjunxiong11/FaceMap<filename>faceswap/lib/image.py<gh_stars>1-10
#!/usr/bin python3
""" Utilities for working with images and videos """
import logging
import re
import subprocess
import os
import sys
from bisect import bisect
from concurrent import futures
from hashlib import sha1
import cv2
import imageio
import imageio_ffmpeg as im_ffm
import numpy as np
from tqdm import tqdm
from lib.multithreading import MultiThread
from lib.queue_manager import queue_manager, QueueEmpty
from lib.utils import convert_to_secs, FaceswapError, _video_extensions, get_image_paths
logger = logging.getLogger(__name__) # pylint:disable=invalid-name
# ################### #
# <<< IMAGE UTILS >>> #
# ################### #
# <<< IMAGE IO >>> #
class FfmpegReader(imageio.plugins.ffmpeg.FfmpegFormat.Reader):
""" Monkey patch imageio ffmpeg to use keyframes whilst seeking """
def __init__(self, format, request):
super().__init__(format, request)
self._frame_pts = None
self._keyframes = None
self.use_patch = False
def get_frame_info(self, frame_pts=None, keyframes=None):
""" Store the source video's keyframes in :attr:`_frame_info" for the current video for use
in :func:`initialize`.
Parameters
----------
frame_pts: list, optional
A list corresponding to the video frame count of the pts_time per frame. If this and
`keyframes` are provided, then analyzing the video is skipped and the values from the
given lists are used. Default: ``None``
keyframes: list, optional
A list containing the frame numbers of each key frame. if this and `frame_pts` are
provided, then analyzing the video is skipped and the values from the given lists are
used. Default: ``None``
"""
if frame_pts is not None and keyframes is not None:
logger.debug("Video meta information provided. Not analyzing video")
self._frame_pts = frame_pts
self._keyframes = keyframes
return len(frame_pts), dict(pts_time=self._frame_pts, keyframes=self._keyframes)
assert isinstance(self._filename, str), "Video path must be a string"
cmd = [im_ffm.get_ffmpeg_exe(),
"-hide_banner",
"-copyts",
"-i", self._filename,
"-vf", "showinfo",
"-start_number", "0",
"-an",
"-f", "null",
"-"]
logger.debug("FFMPEG Command: '%s'", " ".join(cmd))
process = subprocess.Popen(cmd,
stderr=subprocess.STDOUT,
stdout=subprocess.PIPE,
universal_newlines=True)
frame_pts = []
key_frames = []
last_update = 0
pbar = tqdm(desc="Analyzing Video",
leave=False,
total=int(self._meta["duration"]),
unit="secs")
while True:
output = process.stdout.readline().strip()
if output == "" and process.poll() is not None:
break
if "iskey" not in output:
continue
logger.trace("Keyframe line: %s", output)
line = re.split(r"\s+|:\s*", output)
pts_time = float(line[line.index("pts_time") + 1])
frame_no = int(line[line.index("n") + 1])
frame_pts.append(pts_time)
if "iskey:1" in output:
key_frames.append(frame_no)
logger.trace("pts_time: %s, frame_no: %s", pts_time, frame_no)
if int(pts_time) == last_update:
# Floating points make TQDM display poorly, so only update on full
# second increments
continue
pbar.update(int(pts_time) - last_update)
last_update = int(pts_time)
pbar.close()
return_code = process.poll()
frame_count = len(frame_pts)
logger.debug("Return code: %s, frame_pts: %s, keyframes: %s, frame_count: %s",
return_code, frame_pts, key_frames, frame_count)
self._frame_pts = frame_pts
self._keyframes = key_frames
return frame_count, dict(pts_time=self._frame_pts, keyframes=self._keyframes)
def _previous_keyframe_info(self, index=0):
""" Return the previous keyframe's pts_time and frame number """
prev_keyframe_idx = bisect(self._keyframes, index) - 1
prev_keyframe = self._keyframes[prev_keyframe_idx]
prev_pts_time = self._frame_pts[prev_keyframe]
logger.trace("keyframe pts_time: %s, keyframe: %s", prev_pts_time, prev_keyframe)
return prev_pts_time, prev_keyframe
def _initialize(self, index=0):
""" Replace ImageIO _initialize with a version that explictly uses keyframes.
Notes
-----
This introduces a minor change by seeking fast to the previous keyframe and then discarding
subsequent frames until the desired frame is reached. In testing, setting -ss flag either
prior to input, or both prior (fast) and after (slow) would not always bring back the
correct frame for all videos. Navigating to the previous keyframe then discarding frames
until the correct frame is reached appears to work well.
"""
# pylint: disable-all
if self._read_gen is not None:
self._read_gen.close()
iargs = []
oargs = []
skip_frames = 0
# Create input args
iargs += self._arg_input_params
if self.request._video:
iargs += ["-f", CAM_FORMAT] # noqa
if self._arg_pixelformat:
iargs += ["-pix_fmt", self._arg_pixelformat]
if self._arg_size:
iargs += ["-s", self._arg_size]
elif index > 0: # re-initialize / seek
# Note: only works if we initialized earlier, and now have meta. Some info here:
# https://trac.ffmpeg.org/wiki/Seeking
# There are two ways to seek, one before -i (input_params) and after (output_params).
# The former is fast, because it uses keyframes, the latter is slow but accurate.
# According to the article above, the fast method should also be accurate from ffmpeg
# version 2.1, however in version 4.1 our tests start failing again. Not sure why, but
# we can solve this by combining slow and fast.
# Further note: The old method would go back 10 seconds and then seek slow. This was
# still somewhat unresponsive and did not always land on the correct frame. This monkey
# patched version goes to the previous keyframe then discards frames until the correct
# frame is landed on.
if self.use_patch and self._frame_pts is None:
self.get_frame_info()
if self.use_patch:
keyframe_pts, keyframe = self._previous_keyframe_info(index)
seek_fast = keyframe_pts
skip_frames = index - keyframe
else:
starttime = index / self._meta["fps"]
seek_slow = min(10, starttime)
seek_fast = starttime - seek_slow
# We used to have this epsilon earlier, when we did not use
# the slow seek. I don't think we need it anymore.
# epsilon = -1 / self._meta["fps"] * 0.1
iargs += ["-ss", "%.06f" % (seek_fast)]
if not self.use_patch:
oargs += ["-ss", "%.06f" % (seek_slow)]
# Output args, for writing to pipe
if self._arg_size:
oargs += ["-s", self._arg_size]
if self.request.kwargs.get("fps", None):
fps = float(self.request.kwargs["fps"])
oargs += ["-r", "%.02f" % fps]
oargs += self._arg_output_params
# Get pixelformat and bytes per pixel
pix_fmt = self._pix_fmt
bpp = self._depth * self._bytes_per_channel
# Create generator
rf = self._ffmpeg_api.read_frames
self._read_gen = rf(
self._filename, pix_fmt, bpp, input_params=iargs, output_params=oargs
)
# Read meta data. This start the generator (and ffmpeg subprocess)
if self.request._video:
# With cameras, catch error and turn into IndexError
try:
meta = self._read_gen.__next__()
except IOError as err:
err_text = str(err)
if "darwin" in sys.platform:
if "Unknown input format: 'avfoundation'" in err_text:
err_text += (
"Try installing FFMPEG using "
"home brew to get a version with "
"support for cameras."
)
raise IndexError(
"No camera at {}.\n\n{}".format(self.request._video, err_text)
)
else:
self._meta.update(meta)
elif index == 0:
self._meta.update(self._read_gen.__next__())
else:
if self.use_patch:
frames_skipped = 0
while skip_frames != frames_skipped:
# Skip frames that are not the desired frame
_ = self._read_gen.__next__()
frames_skipped += 1
self._read_gen.__next__() # we already have meta data
imageio.plugins.ffmpeg.FfmpegFormat.Reader = FfmpegReader
def read_image(filename, raise_error=False, with_hash=False):
""" Read an image file from a file location.
Extends the functionality of :func:`cv2.imread()` by ensuring that an image was actually
loaded. Errors can be logged and ignored so that the process can continue on an image load
failure.
Parameters
----------
filename: str
Full path to the image to be loaded.
raise_error: bool, optional
If ``True`` then any failures (including the returned image being ``None``) will be
raised. If ``False`` then an error message will be logged, but the error will not be
raised. Default: ``False``
with_hash: bool, optional
If ``True`` then returns the image's sha1 hash with the image. Default: ``False``
Returns
-------
numpy.ndarray or tuple
If :attr:`with_hash` is ``False`` then returns a `numpy.ndarray` of the image in `BGR`
channel order. If :attr:`with_hash` is ``True`` then returns a `tuple` of (`numpy.ndarray`"
of the image in `BGR`, `str` of sha` hash of image)
Example
-------
>>> image_file = "/path/to/image.png"
>>> try:
>>> image = read_image(image_file, raise_error=True, with_hash=False)
>>> except:
>>> raise ValueError("There was an error")
"""
logger.trace("Requested image: '%s'", filename)
success = True
image = None
try:
image = cv2.imread(filename)
if image is None:
raise ValueError
except TypeError:
success = False
msg = "Error while reading image (TypeError): '{}'".format(filename)
logger.error(msg)
if raise_error:
raise Exception(msg)
except ValueError:
success = False
msg = ("Error while reading image. This is most likely caused by special characters in "
"the filename: '{}'".format(filename))
logger.error(msg)
if raise_error:
raise Exception(msg)
except Exception as err: # pylint:disable=broad-except
success = False
msg = "Failed to load image '{}'. Original Error: {}".format(filename, str(err))
logger.error(msg)
if raise_error:
raise Exception(msg)
logger.trace("Loaded image: '%s'. Success: %s", filename, success)
retval = (image, sha1(image).hexdigest()) if with_hash else image
return retval
def read_image_batch(filenames):
""" Load a batch of images from the given file locations.
Leverages multi-threading to load multiple images from disk at the same time leading to vastly
reduced image read times.
Parameters
----------
filenames: list
A list of ``str`` full paths to the images to be loaded.
Returns
-------
numpy.ndarray
The batch of images in `BGR` channel order returned in the order of :attr:`filenames`
Notes
-----
As the images are compiled into a batch, they must be all of the same dimensions.
Example
-------
>>> image_filenames = ["/path/to/image_1.png", "/path/to/image_2.png", "/path/to/image_3.png"]
>>> images = read_image_batch(image_filenames)
"""
logger.trace("Requested batch: '%s'", filenames)
executor = futures.ThreadPoolExecutor()
with executor:
images = {executor.submit(read_image, filename, raise_error=True): filename
for filename in filenames}
batch = [None for _ in range(len(filenames))]
# There is no guarantee that the same filename will not be passed through multiple times
# (and when shuffle is true this can definitely happen), so we can't just call
# filenames.index().
return_indices = {filename: [idx for idx, fname in enumerate(filenames)
if fname == filename]
for filename in set(filenames)}
for future in futures.as_completed(images):
batch[return_indices[images[future]].pop()] = future.result()
batch = np.array(batch)
logger.trace("Returning images: (filenames: %s, batch shape: %s)", filenames, batch.shape)
return batch
def read_image_hash(filename):
""" Return the `sha1` hash of an image saved on disk.
Parameters
----------
filename: str
Full path to the image to be loaded.
Returns
-------
str
The :func:`hashlib.hexdigest()` representation of the `sha1` hash of the given image.
Example
-------
>>> image_file = "/path/to/image.png"
>>> image_hash = read_image_hash(image_file)
"""
img = read_image(filename, raise_error=True)
image_hash = sha1(img).hexdigest()
logger.trace("filename: '%s', hash: %s", filename, image_hash)
return image_hash
def read_image_hash_batch(filenames):
""" Return the `sha` hash of a batch of images
Leverages multi-threading to load multiple images from disk at the same time
leading to vastly reduced image read times. Creates a generator to retrieve filenames
with their hashes as they are calculated.
Notes
-----
The order of returned values is non-deterministic so will most likely not be returned in the
same order as the filenames
Parameters
----------
filenames: list
A list of ``str`` full paths to the images to be loaded.
Yields
-------
tuple: (`filename`, :func:`hashlib.hexdigest()` representation of the `sha1` hash of the image)
Example
-------
>>> image_filenames = ["/path/to/image_1.png", "/path/to/image_2.png", "/path/to/image_3.png"]
>>> for filename, hash in read_image_hash_batch(image_filenames):
>>> <do something>
"""
logger.trace("Requested batch: '%s'", filenames)
executor = futures.ThreadPoolExecutor()
with executor:
logger.debug("Submitting %s items to executor", len(filenames))
read_hashes = {executor.submit(read_image_hash, filename): filename
for filename in filenames}
logger.debug("Succesfully submitted %s items to executor", len(filenames))
for future in futures.as_completed(read_hashes):
retval = (read_hashes[future], future.result())
logger.trace("Yielding: %s", retval)
yield retval
def encode_image_with_hash(image, extension):
""" Encode an image, and get the encoded image back with its `sha1` hash.
Parameters
----------
image: numpy.ndarray
The image to be encoded in `BGR` channel order.
extension: str
A compatible `cv2` image file extension that the final image is to be saved to.
Returns
-------
image_hash: str
The :func:`hashlib.hexdigest()` representation of the `sha1` hash of the encoded image
encoded_image: bytes
The image encoded into the correct file format
Example
-------
>>> image_file = "/path/to/image.png"
>>> image = read_image(image_file)
>>> image_hash, encoded_image = encode_image_with_hash(image, ".jpg")
"""
encoded_image = cv2.imencode(extension, image)[1]
image_hash = sha1(cv2.imdecode(encoded_image, cv2.IMREAD_UNCHANGED)).hexdigest()
return image_hash, encoded_image
def batch_convert_color(batch, colorspace):
""" Convert a batch of images from one color space to another.
Converts a batch of images by reshaping the batch prior to conversion rather than iterating
over the images. This leads to a significant speed up in the convert process.
Parameters
----------
batch: numpy.ndarray
A batch of images.
colorspace: str
The OpenCV Color Conversion Code suffix. For example for BGR to LAB this would be
``'BGR2LAB'``.
See https://docs.opencv.org/4.1.1/d8/d01/group__imgproc__color__conversions.html for a full
list of color codes.
Returns
-------
numpy.ndarray
The batch converted to the requested color space.
Example
-------
>>> images_bgr = numpy.array([image1, image2, image3])
>>> images_lab = batch_convert_color(images_bgr, "BGR2LAB")
Notes
-----
This function is only compatible for color space conversions that have the same image shape
for source and destination color spaces.
If you use :func:`batch_convert_color` with 8-bit images, the conversion will have some
information lost. For many cases, this will not be noticeable but it is recommended
to use 32-bit images in cases that need the full range of colors or that convert an image
before an operation and then convert back.
"""
logger.trace("Batch converting: (batch shape: %s, colorspace: %s)", batch.shape, colorspace)
original_shape = batch.shape
batch = batch.reshape((original_shape[0] * original_shape[1], *original_shape[2:]))
batch = cv2.cvtColor(batch, getattr(cv2, "COLOR_{}".format(colorspace)))
return batch.reshape(original_shape)
# ################### #
# <<< VIDEO UTILS >>> #
# ################### #
def count_frames(filename, fast=False):
""" Count the number of frames in a video file
There is no guaranteed accurate way to get a count of video frames without iterating through
a video and decoding every frame.
:func:`count_frames` can return an accurate count (albeit fairly slowly) or a possibly less
accurate count, depending on the :attr:`fast` parameter. A progress bar is displayed.
Parameters
----------
filename: str
Full path to the video to return the frame count from.
fast: bool, optional
Whether to count the frames without decoding them. This is significantly faster but
accuracy is not guaranteed. Default: ``False``.
Returns
-------
int:
The number of frames in the given video file.
Example
-------
>>> filename = "/path/to/video.mp4"
>>> frame_count = count_frames(filename)
"""
logger.debug("filename: %s, fast: %s", filename, fast)
assert isinstance(filename, str), "Video path must be a string"
cmd = [im_ffm.get_ffmpeg_exe(), "-i", filename, "-map", "0:v:0"]
if fast:
cmd.extend(["-c", "copy"])
cmd.extend(["-f", "null", "-"])
logger.debug("FFMPEG Command: '%s'", " ".join(cmd))
process = subprocess.Popen(cmd,
stderr=subprocess.STDOUT,
stdout=subprocess.PIPE,
universal_newlines=True)
pbar = None
duration = None
init_tqdm = False
update = 0
frames = 0
while True:
output = process.stdout.readline().strip()
if output == "" and process.poll() is not None:
break
if output.startswith("Duration:"):
logger.debug("Duration line: %s", output)
idx = output.find("Duration:") + len("Duration:")
duration = int(convert_to_secs(*output[idx:].split(",", 1)[0].strip().split(":")))
logger.debug("duration: %s", duration)
if output.startswith("frame="):
logger.debug("frame line: %s", output)
if not init_tqdm:
logger.debug("Initializing tqdm")
pbar = tqdm(desc="Analyzing Video", leave=False, total=duration, unit="secs")
init_tqdm = True
time_idx = output.find("time=") + len("time=")
frame_idx = output.find("frame=") + len("frame=")
frames = int(output[frame_idx:].strip().split(" ")[0].strip())
vid_time = int(convert_to_secs(*output[time_idx:].split(" ")[0].strip().split(":")))
logger.debug("frames: %s, vid_time: %s", frames, vid_time)
prev_update = update
update = vid_time
pbar.update(update - prev_update)
if pbar is not None:
pbar.close()
return_code = process.poll()
logger.debug("Return code: %s, frames: %s", return_code, frames)
return frames
class ImageIO():
""" Perform disk IO for images or videos in a background thread.
This is the parent thread for :class:`ImagesLoader` and :class:`ImagesSaver` and should not
be called directly.
Parameters
----------
path: str or list
The path to load or save images to/from. For loading this can be a folder which contains
images, video file or a list of image files. For saving this must be an existing folder.
queue_size: int
The amount of images to hold in the internal buffer.
args: tuple, optional
The arguments to be passed to the loader or saver thread. Default: ``None``
See Also
--------
lib.image.ImagesLoader : Background Image Loader inheriting from this class.
lib.image.ImagesSaver : Background Image Saver inheriting from this class.
"""
def __init__(self, path, queue_size, args=None):
logger.debug("Initializing %s: (path: %s, queue_size: %s, args: %s)",
self.__class__.__name__, path, queue_size, args)
self._args = tuple() if args is None else args
self._location = path
self._check_location_exists()
self._queue = queue_manager.get_queue(name=self.__class__.__name__, maxsize=queue_size)
self._thread = None
@property
def location(self):
""" str: The folder or video that was passed in as the :attr:`path` parameter. """
return self._location
def _check_location_exists(self):
""" Check whether the input location exists.
Raises
------
FaceswapError
If the given location does not exist
"""
if isinstance(self.location, str) and not os.path.exists(self.location):
raise FaceswapError("The location '{}' does not exist".format(self.location))
if isinstance(self.location, (list, tuple)) and not all(os.path.exists(location)
for location in self.location):
raise FaceswapError("Not all locations in the input list exist")
def _set_thread(self):
""" Set the background thread for the load and save iterators and launch it. """
logger.debug("Setting thread")
if self._thread is not None and self._thread.is_alive():
logger.debug("Thread pre-exists and is alive: %s", self._thread)
return
self._thread = MultiThread(self._process,
self._queue,
name=self.__class__.__name__,
thread_count=1)
logger.debug("Set thread: %s", self._thread)
self._thread.start()
def _process(self, queue):
""" Image IO process to be run in a thread. Override for loader/saver process.
Parameters
----------
queue: queue.Queue()
The ImageIO Queue
"""
raise NotImplementedError
def close(self):
""" Closes down and joins the internal threads """
logger.debug("Received Close")
if self._thread is not None:
self._thread.join()
self._thread = None
logger.debug("Closed")
class ImagesLoader(ImageIO):
""" Perform image loading from a folder of images or a video.
Images will be loaded and returned in the order that they appear in the folder, or in the video
to ensure deterministic ordering. Loading occurs in a background thread, caching 8 images at a
time so that other processes do not need to wait on disk reads.
See also :class:`ImageIO` for additional attributes.
Parameters
----------
path: str or list
The path to load images from. This can be a folder which contains images a video file or a
list of image files.
queue_size: int, optional
The amount of images to hold in the internal buffer. Default: 8.
fast_count: bool, optional
When loading from video, the video needs to be parsed frame by frame to get an accurate
count. This can be done quite quickly without guaranteed accuracy, or slower with
guaranteed accuracy. Set to ``True`` to count quickly, or ``False`` to count slower
but accurately. Default: ``True``.
skip_list: list, optional
Optional list of frame/image indices to not load. Any indices provided here will be skipped
when executing the :func:`load` function from the given location. Default: ``None``
count: int, optional
If the number of images that the loader will encounter is already known, it can be passed
in here to skip the image counting step, which can save time at launch. Set to ``None`` if
the count is not already known. Default: ``None``
Examples
--------
Loading from a video file:
>>> loader = ImagesLoader('/path/to/video.mp4')
>>> for filename, image in loader.load():
>>> <do processing>
"""
def __init__(self,
path,
queue_size=8,
fast_count=True,
skip_list=None,
count=None):
logger.debug("Initializing %s: (path: %s, queue_size: %s, fast_count: %s, skip_list: %s, "
"count: %s)", self.__class__.__name__, path, queue_size, fast_count,
skip_list, count)
super().__init__(path, queue_size=queue_size)
self._skip_list = set() if skip_list is None else set(skip_list)
self._is_video = self._check_for_video()
self._fps = self._get_fps()
self._count = None
self._file_list = None
self._get_count_and_filelist(fast_count, count)
@property
def count(self):
""" int: The number of images or video frames in the source location. This count includes
any files that will ultimately be skipped if a :attr:`skip_list` has been provided. See
also: :attr:`process_count`"""
return self._count
@property
def process_count(self):
""" int: The number of images or video frames to be processed (IE the total count less
items that are to be skipped from the :attr:`skip_list`)"""
return self._count - len(self._skip_list)
@property
def is_video(self):
""" bool: ``True`` if the input is a video, ``False`` if it is not """
return self._is_video
@property
def fps(self):
""" float: For an input folder of images, this will always return 25fps. If the input is a
video, then the fps of the video will be returned. """
return self._fps
@property
def file_list(self):
""" list: A full list of files in the source location. This includes any files that will
ultimately be skipped if a :attr:`skip_list` has been provided. If the input is a video
then this is a list of dummy filenames as corresponding to an alignments file """
return self._file_list
def add_skip_list(self, skip_list):
""" Add a skip list to this :class:`ImagesLoader`
Parameters
----------
skip_list: list
A list of indices corresponding to the frame indices that should be skipped by the
:func:`load` function.
"""
logger.debug(skip_list)
self._skip_list = set(skip_list)
def _check_for_video(self):
""" Check whether the input is a video
Returns
-------
bool: 'True' if input is a video 'False' if it is a folder.
Raises
------
FaceswapError
If the given location is a file and does not have a valid video extension.
"""
if os.path.isdir(self.location):
retval = False
elif os.path.splitext(self.location)[1].lower() in _video_extensions:
retval = True
else:
raise FaceswapError("The input file '{}' is not a valid video".format(self.location))
logger.debug("Input '%s' is_video: %s", self.location, retval)
return retval
def _get_fps(self):
""" Get the Frames per Second.
If the input is a folder of images than 25.0 will be returned, as it is not possible to
calculate the fps just from frames alone. For video files the correct FPS will be returned.
Returns
-------
float: The Frames per Second of the input sources
"""
if self._is_video:
reader = imageio.get_reader(self.location, "ffmpeg")
retval = reader.get_meta_data()["fps"]
reader.close()
else:
retval = 25.0
logger.debug(retval)
return retval
def _get_count_and_filelist(self, fast_count, count):
""" Set the count of images to be processed and set the file list
If the input is a video, a dummy file list is created for checking against an
alignments file, otherwise it will be a list of full filenames.
Parameters
----------
fast_count: bool
When loading from video, the video needs to be parsed frame by frame to get an accurate
count. This can be done quite quickly without guaranteed accuracy, or slower with
guaranteed accuracy. Set to ``True`` to count quickly, or ``False`` to count slower
but accurately.
count: int
The number of images that the loader will encounter if already known, otherwise
``None``
"""
if self._is_video:
self._count = int(count_frames(self.location,
fast=fast_count)) if count is None else count
self._file_list = [self._dummy_video_framename(i) for i in range(self.count)]
else:
if isinstance(self.location, (list, tuple)):
self._file_list = self.location
else:
self._file_list = get_image_paths(self.location)
self._count = len(self.file_list) if count is None else count
logger.debug("count: %s", self.count)
logger.trace("filelist: %s", self.file_list)
def _process(self, queue):
""" The load thread.
Loads from a folder of images or from a video and puts to a queue
Parameters
----------
queue: queue.Queue()
The ImageIO Queue
"""
iterator = self._from_video if self._is_video else self._from_folder
logger.debug("Load iterator: %s", iterator)
for retval in iterator():
filename, image = retval[:2]
if image is None or (not image.any() and image.ndim not in (2, 3)):
# All black frames will return not numpy.any() so check dims too
logger.warning("Unable to open image. Skipping: '%s'", filename)
continue
logger.trace("Putting to queue: %s", [v.shape if isinstance(v, np.ndarray) else v
for v in retval])
queue.put(retval)
logger.trace("Putting EOF")
queue.put("EOF")
def _from_video(self):
""" Generator for loading frames from a video
Yields
------
filename: str
The dummy filename of the loaded video frame.
image: numpy.ndarray
The loaded video frame.
"""
logger.debug("Loading frames from video: '%s'", self.location)
reader = imageio.get_reader(self.location, "ffmpeg")
for idx, frame in enumerate(reader):
if idx in self._skip_list:
logger.trace("Skipping frame %s due to skip list", idx)
continue
# Convert to BGR for cv2 compatibility
frame = frame[:, :, ::-1]
filename = self._dummy_video_framename(idx)
logger.trace("Loading video frame: '%s'", filename)
yield filename, frame
reader.close()
def _dummy_video_framename(self, index):
""" Return a dummy filename for video files
Parameters
----------
index: int
The index number for the frame in the video file
Notes
-----
Indexes start at 0, frame numbers start at 1, so index is incremented by 1
when creating the filename
Returns
-------
str: A dummied filename for a video frame """
vidname = os.path.splitext(os.path.basename(self.location))[0]
return "{}_{:06d}.png".format(vidname, index + 1)
def _from_folder(self):
""" Generator for loading images from a folder
Yields
------
filename: str
The filename of the loaded image.
image: numpy.ndarray
The loaded image.
"""
logger.debug("Loading frames from folder: '%s'", self.location)
for idx, filename in enumerate(self.file_list):
if idx in self._skip_list:
logger.trace("Skipping frame %s due to skip list")
continue
image_read = read_image(filename, raise_error=False, with_hash=False)
retval = filename, image_read
if retval[1] is None:
logger.warning("Frame not loaded: '%s'", filename)
continue
yield retval
def load(self):
""" Generator for loading images from the given :attr:`location`
If :class:`FacesLoader` is in use then the sha1 hash of the image is added as the final
item in the output `tuple`.
Yields
------
filename: str
The filename of the loaded image.
image: numpy.ndarray
The loaded image.
sha1_hash: str, (:class:`FacesLoader` only)
The sha1 hash of the loaded image. Only yielded if :class:`FacesLoader` is being
executed.
"""
logger.debug("Initializing Load Generator")
self._set_thread()
while True:
self._thread.check_and_raise_error()
try:
retval = self._queue.get(True, 1)
except QueueEmpty:
continue
if retval == "EOF":
logger.trace("Got EOF")
break
logger.trace("Yielding: %s", [v.shape if isinstance(v, np.ndarray) else v
for v in retval])
yield retval
logger.debug("Closing Load Generator")
self.close()
class FacesLoader(ImagesLoader):
""" Loads faces from a faces folder along with the face's hash.
Examples
--------
Loading faces with their sha1 hash:
>>> loader = FacesLoader('/path/to/faces/folder')
>>> for filename, face, sha1_hash in loader.load():
>>> <do processing>
"""
def __init__(self, path, skip_list=None, count=None):
logger.debug("Initializing %s: (path: %s, count: %s)", self.__class__.__name__,
path, count)
super().__init__(path, queue_size=8, skip_list=skip_list, count=count)
def _from_folder(self):
""" Generator for loading images from a folder
Faces will only ever be loaded from a folder, so this is the only function requiring
an override
Yields
------
filename: str
The filename of the loaded image.
image: numpy.ndarray
The loaded image.
sha1_hash: str
The sha1 hash of the loaded image.
"""
logger.debug("Loading images from folder: '%s'", self.location)
for idx, filename in enumerate(self.file_list):
if idx in self._skip_list:
logger.trace("Skipping face %s due to skip list")
continue
image_read = read_image(filename, raise_error=False, with_hash=True)
retval = filename, *image_read
if retval[1] is None:
logger.warning("Face not loaded: '%s'", filename)
continue
yield retval
class SingleFrameLoader(ImagesLoader):
""" Allows direct access to a frame by filename or frame index.
As we are interested in instant access to frames, there is no requirement to process in a
background thread, as either way we need to wait for the frame to load.
Parameters
----------
video_meta_data: dict, optional
Existing video meta information containing the pts_time and iskey flags for the given
video. Used in conjunction with single_frame_reader for faster seeks. Providing this means
that the video does not need to be scanned again. Set to ``None`` if the video is to be
scanned. Default: ``None``
"""
def __init__(self, path, video_meta_data=None):
logger.debug("Initializing %s: (path: %s, video_meta_data: %s)",
self.__class__.__name__, path, video_meta_data)
self._video_meta_data = dict() if video_meta_data is None else video_meta_data
self._reader = None
super().__init__(path, queue_size=1, fast_count=False)
@property
def video_meta_data(self):
""" dict: For videos contains the keys `frame_pts` holding a list of time stamps for each
frame and `keyframes` holding the frame index of each key frame.
Notes
-----
Only populated if the input is a video and single frame reader is being used, otherwise
returns ``None``.
"""
return self._video_meta_data
def _get_count_and_filelist(self, fast_count, count):
if self._is_video:
self._reader = imageio.get_reader(self.location, "ffmpeg")
self._reader.use_patch = True
count, video_meta_data = self._reader.get_frame_info(
frame_pts=self._video_meta_data.get("pts_time", None),
keyframes=self._video_meta_data.get("keyframes", None))
self._video_meta_data = video_meta_data
super()._get_count_and_filelist(fast_count, count)
def image_from_index(self, index):
""" Return a single image from :attr:`file_list` for the given index.
Parameters
----------
index: int
The index number (frame number) of the frame to retrieve. NB: The first frame is
index `0`
Returns
-------
filename: str
The filename of the returned image
image: :class:`numpy.ndarray`
The image for the given index
Notes
-----
Retrieving frames from video files can be slow as the whole video file needs to be
iterated to retrieve the requested frame. If a frame has already been retrieved, then
retrieving frames of a higher index will be quicker than retrieving frames of a lower
index, as iteration needs to start from the beginning again when navigating backwards.
We do not use a background thread for this task, as it is assumed that requesting an image
by index will be done when required.
"""
if self.is_video:
image = self._reader.get_data(index)[..., ::-1]
filename = self._dummy_video_framename(index)
else:
filename = self.file_list[index]
image = read_image(filename, raise_error=True)
filename = os.path.basename(filename)
logger.trace("index: %s, filename: %s image shape: %s", index, filename, image.shape)
return filename, image
class ImagesSaver(ImageIO):
""" Perform image saving to a destination folder.
Images are saved in a background ThreadPoolExecutor to allow for concurrent saving.
See also :class:`ImageIO` for additional attributes.
Parameters
----------
path: str
The folder to save images to. This must be an existing folder.
queue_size: int, optional
The amount of images to hold in the internal buffer. Default: 8.
as_bytes: bool, optional
``True`` if the image is already encoded to bytes, ``False`` if the image is a
:class:`numpy.ndarray`. Default: ``False``.
Examples
--------
>>> saver = ImagesSaver('/path/to/save/folder')
>>> for filename, image in <image_iterator>:
>>> saver.save(filename, image)
>>> saver.close()
"""
def __init__(self, path, queue_size=8, as_bytes=False):
logger.debug("Initializing %s: (path: %s, queue_size: %s, as_bytes: %s)",
self.__class__.__name__, path, queue_size, as_bytes)
super().__init__(path, queue_size=queue_size)
self._as_bytes = as_bytes
def _check_location_exists(self):
""" Check whether the output location exists and is a folder
Raises
------
FaceswapError
If the given location does not exist or the location is not a folder
"""
if not isinstance(self.location, str):
raise FaceswapError("The output location must be a string not a "
"{}".format(type(self.location)))
super()._check_location_exists()
if not os.path.isdir(self.location):
raise FaceswapError("The output location '{}' is not a folder".format(self.location))
def _process(self, queue):
""" Saves images from the save queue to the given :attr:`location` inside a thread.
Parameters
----------
queue: queue.Queue()
The ImageIO Queue
"""
executor = futures.ThreadPoolExecutor(thread_name_prefix=self.__class__.__name__)
while True:
item = queue.get()
if item == "EOF":
logger.debug("EOF received")
break
logger.trace("Submitting: '%s'", item[0])
executor.submit(self._save, *item)
executor.shutdown()
def _save(self, filename, image):
""" Save a single image inside a ThreadPoolExecutor
Parameters
----------
filename: str
The filename of the image to be saved. NB: Any folders passed in with the filename
will be stripped and replaced with :attr:`location`.
image: numpy.ndarray
The image to be saved
"""
filename = os.path.join(self.location, os.path.basename(filename))
try:
if self._as_bytes:
with open(filename, "wb") as out_file:
out_file.write(image)
else:
cv2.imwrite(filename, image)
logger.trace("Saved image: '%s'", filename)
except Exception as err: # pylint: disable=broad-except
logger.error("Failed to save image '%s'. Original Error: %s", filename, err)
def save(self, filename, image):
""" Save the given image in the background thread
Ensure that :func:`close` is called once all save operations are complete.
Parameters
----------
filename: str
The filename of the image to be saved
image: numpy.ndarray
The image to be saved
"""
self._set_thread()
logger.trace("Putting to save queue: '%s'", filename)
self._queue.put((filename, image))
def close(self):
""" Signal to the Save Threads that they should be closed and cleanly shutdown
the saver """
logger.debug("Putting EOF to save queue")
self._queue.put("EOF")
super().close()
| #!/usr/bin python3
""" Utilities for working with images and videos """
import logging
import re
import subprocess
import os
import sys
from bisect import bisect
from concurrent import futures
from hashlib import sha1
import cv2
import imageio
import imageio_ffmpeg as im_ffm
import numpy as np
from tqdm import tqdm
from lib.multithreading import MultiThread
from lib.queue_manager import queue_manager, QueueEmpty
from lib.utils import convert_to_secs, FaceswapError, _video_extensions, get_image_paths
logger = logging.getLogger(__name__) # pylint:disable=invalid-name
# ################### #
# <<< IMAGE UTILS >>> #
# ################### #
# <<< IMAGE IO >>> #
class FfmpegReader(imageio.plugins.ffmpeg.FfmpegFormat.Reader):
""" Monkey patch imageio ffmpeg to use keyframes whilst seeking """
def __init__(self, format, request):
super().__init__(format, request)
self._frame_pts = None
self._keyframes = None
self.use_patch = False
def get_frame_info(self, frame_pts=None, keyframes=None):
""" Store the source video's keyframes in :attr:`_frame_info" for the current video for use
in :func:`initialize`.
Parameters
----------
frame_pts: list, optional
A list corresponding to the video frame count of the pts_time per frame. If this and
`keyframes` are provided, then analyzing the video is skipped and the values from the
given lists are used. Default: ``None``
keyframes: list, optional
A list containing the frame numbers of each key frame. if this and `frame_pts` are
provided, then analyzing the video is skipped and the values from the given lists are
used. Default: ``None``
"""
if frame_pts is not None and keyframes is not None:
logger.debug("Video meta information provided. Not analyzing video")
self._frame_pts = frame_pts
self._keyframes = keyframes
return len(frame_pts), dict(pts_time=self._frame_pts, keyframes=self._keyframes)
assert isinstance(self._filename, str), "Video path must be a string"
cmd = [im_ffm.get_ffmpeg_exe(),
"-hide_banner",
"-copyts",
"-i", self._filename,
"-vf", "showinfo",
"-start_number", "0",
"-an",
"-f", "null",
"-"]
logger.debug("FFMPEG Command: '%s'", " ".join(cmd))
process = subprocess.Popen(cmd,
stderr=subprocess.STDOUT,
stdout=subprocess.PIPE,
universal_newlines=True)
frame_pts = []
key_frames = []
last_update = 0
pbar = tqdm(desc="Analyzing Video",
leave=False,
total=int(self._meta["duration"]),
unit="secs")
while True:
output = process.stdout.readline().strip()
if output == "" and process.poll() is not None:
break
if "iskey" not in output:
continue
logger.trace("Keyframe line: %s", output)
line = re.split(r"\s+|:\s*", output)
pts_time = float(line[line.index("pts_time") + 1])
frame_no = int(line[line.index("n") + 1])
frame_pts.append(pts_time)
if "iskey:1" in output:
key_frames.append(frame_no)
logger.trace("pts_time: %s, frame_no: %s", pts_time, frame_no)
if int(pts_time) == last_update:
# Floating points make TQDM display poorly, so only update on full
# second increments
continue
pbar.update(int(pts_time) - last_update)
last_update = int(pts_time)
pbar.close()
return_code = process.poll()
frame_count = len(frame_pts)
logger.debug("Return code: %s, frame_pts: %s, keyframes: %s, frame_count: %s",
return_code, frame_pts, key_frames, frame_count)
self._frame_pts = frame_pts
self._keyframes = key_frames
return frame_count, dict(pts_time=self._frame_pts, keyframes=self._keyframes)
def _previous_keyframe_info(self, index=0):
""" Return the previous keyframe's pts_time and frame number """
prev_keyframe_idx = bisect(self._keyframes, index) - 1
prev_keyframe = self._keyframes[prev_keyframe_idx]
prev_pts_time = self._frame_pts[prev_keyframe]
logger.trace("keyframe pts_time: %s, keyframe: %s", prev_pts_time, prev_keyframe)
return prev_pts_time, prev_keyframe
def _initialize(self, index=0):
""" Replace ImageIO _initialize with a version that explictly uses keyframes.
Notes
-----
This introduces a minor change by seeking fast to the previous keyframe and then discarding
subsequent frames until the desired frame is reached. In testing, setting -ss flag either
prior to input, or both prior (fast) and after (slow) would not always bring back the
correct frame for all videos. Navigating to the previous keyframe then discarding frames
until the correct frame is reached appears to work well.
"""
# pylint: disable-all
if self._read_gen is not None:
self._read_gen.close()
iargs = []
oargs = []
skip_frames = 0
# Create input args
iargs += self._arg_input_params
if self.request._video:
iargs += ["-f", CAM_FORMAT] # noqa
if self._arg_pixelformat:
iargs += ["-pix_fmt", self._arg_pixelformat]
if self._arg_size:
iargs += ["-s", self._arg_size]
elif index > 0: # re-initialize / seek
# Note: only works if we initialized earlier, and now have meta. Some info here:
# https://trac.ffmpeg.org/wiki/Seeking
# There are two ways to seek, one before -i (input_params) and after (output_params).
# The former is fast, because it uses keyframes, the latter is slow but accurate.
# According to the article above, the fast method should also be accurate from ffmpeg
# version 2.1, however in version 4.1 our tests start failing again. Not sure why, but
# we can solve this by combining slow and fast.
# Further note: The old method would go back 10 seconds and then seek slow. This was
# still somewhat unresponsive and did not always land on the correct frame. This monkey
# patched version goes to the previous keyframe then discards frames until the correct
# frame is landed on.
if self.use_patch and self._frame_pts is None:
self.get_frame_info()
if self.use_patch:
keyframe_pts, keyframe = self._previous_keyframe_info(index)
seek_fast = keyframe_pts
skip_frames = index - keyframe
else:
starttime = index / self._meta["fps"]
seek_slow = min(10, starttime)
seek_fast = starttime - seek_slow
# We used to have this epsilon earlier, when we did not use
# the slow seek. I don't think we need it anymore.
# epsilon = -1 / self._meta["fps"] * 0.1
iargs += ["-ss", "%.06f" % (seek_fast)]
if not self.use_patch:
oargs += ["-ss", "%.06f" % (seek_slow)]
# Output args, for writing to pipe
if self._arg_size:
oargs += ["-s", self._arg_size]
if self.request.kwargs.get("fps", None):
fps = float(self.request.kwargs["fps"])
oargs += ["-r", "%.02f" % fps]
oargs += self._arg_output_params
# Get pixelformat and bytes per pixel
pix_fmt = self._pix_fmt
bpp = self._depth * self._bytes_per_channel
# Create generator
rf = self._ffmpeg_api.read_frames
self._read_gen = rf(
self._filename, pix_fmt, bpp, input_params=iargs, output_params=oargs
)
# Read meta data. This start the generator (and ffmpeg subprocess)
if self.request._video:
# With cameras, catch error and turn into IndexError
try:
meta = self._read_gen.__next__()
except IOError as err:
err_text = str(err)
if "darwin" in sys.platform:
if "Unknown input format: 'avfoundation'" in err_text:
err_text += (
"Try installing FFMPEG using "
"home brew to get a version with "
"support for cameras."
)
raise IndexError(
"No camera at {}.\n\n{}".format(self.request._video, err_text)
)
else:
self._meta.update(meta)
elif index == 0:
self._meta.update(self._read_gen.__next__())
else:
if self.use_patch:
frames_skipped = 0
while skip_frames != frames_skipped:
# Skip frames that are not the desired frame
_ = self._read_gen.__next__()
frames_skipped += 1
self._read_gen.__next__() # we already have meta data
imageio.plugins.ffmpeg.FfmpegFormat.Reader = FfmpegReader
def read_image(filename, raise_error=False, with_hash=False):
""" Read an image file from a file location.
Extends the functionality of :func:`cv2.imread()` by ensuring that an image was actually
loaded. Errors can be logged and ignored so that the process can continue on an image load
failure.
Parameters
----------
filename: str
Full path to the image to be loaded.
raise_error: bool, optional
If ``True`` then any failures (including the returned image being ``None``) will be
raised. If ``False`` then an error message will be logged, but the error will not be
raised. Default: ``False``
with_hash: bool, optional
If ``True`` then returns the image's sha1 hash with the image. Default: ``False``
Returns
-------
numpy.ndarray or tuple
If :attr:`with_hash` is ``False`` then returns a `numpy.ndarray` of the image in `BGR`
channel order. If :attr:`with_hash` is ``True`` then returns a `tuple` of (`numpy.ndarray`"
of the image in `BGR`, `str` of sha` hash of image)
Example
-------
>>> image_file = "/path/to/image.png"
>>> try:
>>> image = read_image(image_file, raise_error=True, with_hash=False)
>>> except:
>>> raise ValueError("There was an error")
"""
logger.trace("Requested image: '%s'", filename)
success = True
image = None
try:
image = cv2.imread(filename)
if image is None:
raise ValueError
except TypeError:
success = False
msg = "Error while reading image (TypeError): '{}'".format(filename)
logger.error(msg)
if raise_error:
raise Exception(msg)
except ValueError:
success = False
msg = ("Error while reading image. This is most likely caused by special characters in "
"the filename: '{}'".format(filename))
logger.error(msg)
if raise_error:
raise Exception(msg)
except Exception as err: # pylint:disable=broad-except
success = False
msg = "Failed to load image '{}'. Original Error: {}".format(filename, str(err))
logger.error(msg)
if raise_error:
raise Exception(msg)
logger.trace("Loaded image: '%s'. Success: %s", filename, success)
retval = (image, sha1(image).hexdigest()) if with_hash else image
return retval
def read_image_batch(filenames):
""" Load a batch of images from the given file locations.
Leverages multi-threading to load multiple images from disk at the same time leading to vastly
reduced image read times.
Parameters
----------
filenames: list
A list of ``str`` full paths to the images to be loaded.
Returns
-------
numpy.ndarray
The batch of images in `BGR` channel order returned in the order of :attr:`filenames`
Notes
-----
As the images are compiled into a batch, they must be all of the same dimensions.
Example
-------
>>> image_filenames = ["/path/to/image_1.png", "/path/to/image_2.png", "/path/to/image_3.png"]
>>> images = read_image_batch(image_filenames)
"""
logger.trace("Requested batch: '%s'", filenames)
executor = futures.ThreadPoolExecutor()
with executor:
images = {executor.submit(read_image, filename, raise_error=True): filename
for filename in filenames}
batch = [None for _ in range(len(filenames))]
# There is no guarantee that the same filename will not be passed through multiple times
# (and when shuffle is true this can definitely happen), so we can't just call
# filenames.index().
return_indices = {filename: [idx for idx, fname in enumerate(filenames)
if fname == filename]
for filename in set(filenames)}
for future in futures.as_completed(images):
batch[return_indices[images[future]].pop()] = future.result()
batch = np.array(batch)
logger.trace("Returning images: (filenames: %s, batch shape: %s)", filenames, batch.shape)
return batch
def read_image_hash(filename):
""" Return the `sha1` hash of an image saved on disk.
Parameters
----------
filename: str
Full path to the image to be loaded.
Returns
-------
str
The :func:`hashlib.hexdigest()` representation of the `sha1` hash of the given image.
Example
-------
>>> image_file = "/path/to/image.png"
>>> image_hash = read_image_hash(image_file)
"""
img = read_image(filename, raise_error=True)
image_hash = sha1(img).hexdigest()
logger.trace("filename: '%s', hash: %s", filename, image_hash)
return image_hash
def read_image_hash_batch(filenames):
""" Return the `sha` hash of a batch of images
Leverages multi-threading to load multiple images from disk at the same time
leading to vastly reduced image read times. Creates a generator to retrieve filenames
with their hashes as they are calculated.
Notes
-----
The order of returned values is non-deterministic so will most likely not be returned in the
same order as the filenames
Parameters
----------
filenames: list
A list of ``str`` full paths to the images to be loaded.
Yields
-------
tuple: (`filename`, :func:`hashlib.hexdigest()` representation of the `sha1` hash of the image)
Example
-------
>>> image_filenames = ["/path/to/image_1.png", "/path/to/image_2.png", "/path/to/image_3.png"]
>>> for filename, hash in read_image_hash_batch(image_filenames):
>>> <do something>
"""
logger.trace("Requested batch: '%s'", filenames)
executor = futures.ThreadPoolExecutor()
with executor:
logger.debug("Submitting %s items to executor", len(filenames))
read_hashes = {executor.submit(read_image_hash, filename): filename
for filename in filenames}
logger.debug("Succesfully submitted %s items to executor", len(filenames))
for future in futures.as_completed(read_hashes):
retval = (read_hashes[future], future.result())
logger.trace("Yielding: %s", retval)
yield retval
def encode_image_with_hash(image, extension):
""" Encode an image, and get the encoded image back with its `sha1` hash.
Parameters
----------
image: numpy.ndarray
The image to be encoded in `BGR` channel order.
extension: str
A compatible `cv2` image file extension that the final image is to be saved to.
Returns
-------
image_hash: str
The :func:`hashlib.hexdigest()` representation of the `sha1` hash of the encoded image
encoded_image: bytes
The image encoded into the correct file format
Example
-------
>>> image_file = "/path/to/image.png"
>>> image = read_image(image_file)
>>> image_hash, encoded_image = encode_image_with_hash(image, ".jpg")
"""
encoded_image = cv2.imencode(extension, image)[1]
image_hash = sha1(cv2.imdecode(encoded_image, cv2.IMREAD_UNCHANGED)).hexdigest()
return image_hash, encoded_image
def batch_convert_color(batch, colorspace):
""" Convert a batch of images from one color space to another.
Converts a batch of images by reshaping the batch prior to conversion rather than iterating
over the images. This leads to a significant speed up in the convert process.
Parameters
----------
batch: numpy.ndarray
A batch of images.
colorspace: str
The OpenCV Color Conversion Code suffix. For example for BGR to LAB this would be
``'BGR2LAB'``.
See https://docs.opencv.org/4.1.1/d8/d01/group__imgproc__color__conversions.html for a full
list of color codes.
Returns
-------
numpy.ndarray
The batch converted to the requested color space.
Example
-------
>>> images_bgr = numpy.array([image1, image2, image3])
>>> images_lab = batch_convert_color(images_bgr, "BGR2LAB")
Notes
-----
This function is only compatible for color space conversions that have the same image shape
for source and destination color spaces.
If you use :func:`batch_convert_color` with 8-bit images, the conversion will have some
information lost. For many cases, this will not be noticeable but it is recommended
to use 32-bit images in cases that need the full range of colors or that convert an image
before an operation and then convert back.
"""
logger.trace("Batch converting: (batch shape: %s, colorspace: %s)", batch.shape, colorspace)
original_shape = batch.shape
batch = batch.reshape((original_shape[0] * original_shape[1], *original_shape[2:]))
batch = cv2.cvtColor(batch, getattr(cv2, "COLOR_{}".format(colorspace)))
return batch.reshape(original_shape)
# ################### #
# <<< VIDEO UTILS >>> #
# ################### #
def count_frames(filename, fast=False):
""" Count the number of frames in a video file
There is no guaranteed accurate way to get a count of video frames without iterating through
a video and decoding every frame.
:func:`count_frames` can return an accurate count (albeit fairly slowly) or a possibly less
accurate count, depending on the :attr:`fast` parameter. A progress bar is displayed.
Parameters
----------
filename: str
Full path to the video to return the frame count from.
fast: bool, optional
Whether to count the frames without decoding them. This is significantly faster but
accuracy is not guaranteed. Default: ``False``.
Returns
-------
int:
The number of frames in the given video file.
Example
-------
>>> filename = "/path/to/video.mp4"
>>> frame_count = count_frames(filename)
"""
logger.debug("filename: %s, fast: %s", filename, fast)
assert isinstance(filename, str), "Video path must be a string"
cmd = [im_ffm.get_ffmpeg_exe(), "-i", filename, "-map", "0:v:0"]
if fast:
cmd.extend(["-c", "copy"])
cmd.extend(["-f", "null", "-"])
logger.debug("FFMPEG Command: '%s'", " ".join(cmd))
process = subprocess.Popen(cmd,
stderr=subprocess.STDOUT,
stdout=subprocess.PIPE,
universal_newlines=True)
pbar = None
duration = None
init_tqdm = False
update = 0
frames = 0
while True:
output = process.stdout.readline().strip()
if output == "" and process.poll() is not None:
break
if output.startswith("Duration:"):
logger.debug("Duration line: %s", output)
idx = output.find("Duration:") + len("Duration:")
duration = int(convert_to_secs(*output[idx:].split(",", 1)[0].strip().split(":")))
logger.debug("duration: %s", duration)
if output.startswith("frame="):
logger.debug("frame line: %s", output)
if not init_tqdm:
logger.debug("Initializing tqdm")
pbar = tqdm(desc="Analyzing Video", leave=False, total=duration, unit="secs")
init_tqdm = True
time_idx = output.find("time=") + len("time=")
frame_idx = output.find("frame=") + len("frame=")
frames = int(output[frame_idx:].strip().split(" ")[0].strip())
vid_time = int(convert_to_secs(*output[time_idx:].split(" ")[0].strip().split(":")))
logger.debug("frames: %s, vid_time: %s", frames, vid_time)
prev_update = update
update = vid_time
pbar.update(update - prev_update)
if pbar is not None:
pbar.close()
return_code = process.poll()
logger.debug("Return code: %s, frames: %s", return_code, frames)
return frames
class ImageIO():
""" Perform disk IO for images or videos in a background thread.
This is the parent thread for :class:`ImagesLoader` and :class:`ImagesSaver` and should not
be called directly.
Parameters
----------
path: str or list
The path to load or save images to/from. For loading this can be a folder which contains
images, video file or a list of image files. For saving this must be an existing folder.
queue_size: int
The amount of images to hold in the internal buffer.
args: tuple, optional
The arguments to be passed to the loader or saver thread. Default: ``None``
See Also
--------
lib.image.ImagesLoader : Background Image Loader inheriting from this class.
lib.image.ImagesSaver : Background Image Saver inheriting from this class.
"""
def __init__(self, path, queue_size, args=None):
logger.debug("Initializing %s: (path: %s, queue_size: %s, args: %s)",
self.__class__.__name__, path, queue_size, args)
self._args = tuple() if args is None else args
self._location = path
self._check_location_exists()
self._queue = queue_manager.get_queue(name=self.__class__.__name__, maxsize=queue_size)
self._thread = None
@property
def location(self):
""" str: The folder or video that was passed in as the :attr:`path` parameter. """
return self._location
def _check_location_exists(self):
""" Check whether the input location exists.
Raises
------
FaceswapError
If the given location does not exist
"""
if isinstance(self.location, str) and not os.path.exists(self.location):
raise FaceswapError("The location '{}' does not exist".format(self.location))
if isinstance(self.location, (list, tuple)) and not all(os.path.exists(location)
for location in self.location):
raise FaceswapError("Not all locations in the input list exist")
def _set_thread(self):
""" Set the background thread for the load and save iterators and launch it. """
logger.debug("Setting thread")
if self._thread is not None and self._thread.is_alive():
logger.debug("Thread pre-exists and is alive: %s", self._thread)
return
self._thread = MultiThread(self._process,
self._queue,
name=self.__class__.__name__,
thread_count=1)
logger.debug("Set thread: %s", self._thread)
self._thread.start()
def _process(self, queue):
""" Image IO process to be run in a thread. Override for loader/saver process.
Parameters
----------
queue: queue.Queue()
The ImageIO Queue
"""
raise NotImplementedError
def close(self):
""" Closes down and joins the internal threads """
logger.debug("Received Close")
if self._thread is not None:
self._thread.join()
self._thread = None
logger.debug("Closed")
class ImagesLoader(ImageIO):
""" Perform image loading from a folder of images or a video.
Images will be loaded and returned in the order that they appear in the folder, or in the video
to ensure deterministic ordering. Loading occurs in a background thread, caching 8 images at a
time so that other processes do not need to wait on disk reads.
See also :class:`ImageIO` for additional attributes.
Parameters
----------
path: str or list
The path to load images from. This can be a folder which contains images a video file or a
list of image files.
queue_size: int, optional
The amount of images to hold in the internal buffer. Default: 8.
fast_count: bool, optional
When loading from video, the video needs to be parsed frame by frame to get an accurate
count. This can be done quite quickly without guaranteed accuracy, or slower with
guaranteed accuracy. Set to ``True`` to count quickly, or ``False`` to count slower
but accurately. Default: ``True``.
skip_list: list, optional
Optional list of frame/image indices to not load. Any indices provided here will be skipped
when executing the :func:`load` function from the given location. Default: ``None``
count: int, optional
If the number of images that the loader will encounter is already known, it can be passed
in here to skip the image counting step, which can save time at launch. Set to ``None`` if
the count is not already known. Default: ``None``
Examples
--------
Loading from a video file:
>>> loader = ImagesLoader('/path/to/video.mp4')
>>> for filename, image in loader.load():
>>> <do processing>
"""
def __init__(self,
path,
queue_size=8,
fast_count=True,
skip_list=None,
count=None):
logger.debug("Initializing %s: (path: %s, queue_size: %s, fast_count: %s, skip_list: %s, "
"count: %s)", self.__class__.__name__, path, queue_size, fast_count,
skip_list, count)
super().__init__(path, queue_size=queue_size)
self._skip_list = set() if skip_list is None else set(skip_list)
self._is_video = self._check_for_video()
self._fps = self._get_fps()
self._count = None
self._file_list = None
self._get_count_and_filelist(fast_count, count)
@property
def count(self):
""" int: The number of images or video frames in the source location. This count includes
any files that will ultimately be skipped if a :attr:`skip_list` has been provided. See
also: :attr:`process_count`"""
return self._count
@property
def process_count(self):
""" int: The number of images or video frames to be processed (IE the total count less
items that are to be skipped from the :attr:`skip_list`)"""
return self._count - len(self._skip_list)
@property
def is_video(self):
""" bool: ``True`` if the input is a video, ``False`` if it is not """
return self._is_video
@property
def fps(self):
""" float: For an input folder of images, this will always return 25fps. If the input is a
video, then the fps of the video will be returned. """
return self._fps
@property
def file_list(self):
""" list: A full list of files in the source location. This includes any files that will
ultimately be skipped if a :attr:`skip_list` has been provided. If the input is a video
then this is a list of dummy filenames as corresponding to an alignments file """
return self._file_list
def add_skip_list(self, skip_list):
""" Add a skip list to this :class:`ImagesLoader`
Parameters
----------
skip_list: list
A list of indices corresponding to the frame indices that should be skipped by the
:func:`load` function.
"""
logger.debug(skip_list)
self._skip_list = set(skip_list)
def _check_for_video(self):
""" Check whether the input is a video
Returns
-------
bool: 'True' if input is a video 'False' if it is a folder.
Raises
------
FaceswapError
If the given location is a file and does not have a valid video extension.
"""
if os.path.isdir(self.location):
retval = False
elif os.path.splitext(self.location)[1].lower() in _video_extensions:
retval = True
else:
raise FaceswapError("The input file '{}' is not a valid video".format(self.location))
logger.debug("Input '%s' is_video: %s", self.location, retval)
return retval
def _get_fps(self):
""" Get the Frames per Second.
If the input is a folder of images than 25.0 will be returned, as it is not possible to
calculate the fps just from frames alone. For video files the correct FPS will be returned.
Returns
-------
float: The Frames per Second of the input sources
"""
if self._is_video:
reader = imageio.get_reader(self.location, "ffmpeg")
retval = reader.get_meta_data()["fps"]
reader.close()
else:
retval = 25.0
logger.debug(retval)
return retval
def _get_count_and_filelist(self, fast_count, count):
""" Set the count of images to be processed and set the file list
If the input is a video, a dummy file list is created for checking against an
alignments file, otherwise it will be a list of full filenames.
Parameters
----------
fast_count: bool
When loading from video, the video needs to be parsed frame by frame to get an accurate
count. This can be done quite quickly without guaranteed accuracy, or slower with
guaranteed accuracy. Set to ``True`` to count quickly, or ``False`` to count slower
but accurately.
count: int
The number of images that the loader will encounter if already known, otherwise
``None``
"""
if self._is_video:
self._count = int(count_frames(self.location,
fast=fast_count)) if count is None else count
self._file_list = [self._dummy_video_framename(i) for i in range(self.count)]
else:
if isinstance(self.location, (list, tuple)):
self._file_list = self.location
else:
self._file_list = get_image_paths(self.location)
self._count = len(self.file_list) if count is None else count
logger.debug("count: %s", self.count)
logger.trace("filelist: %s", self.file_list)
def _process(self, queue):
""" The load thread.
Loads from a folder of images or from a video and puts to a queue
Parameters
----------
queue: queue.Queue()
The ImageIO Queue
"""
iterator = self._from_video if self._is_video else self._from_folder
logger.debug("Load iterator: %s", iterator)
for retval in iterator():
filename, image = retval[:2]
if image is None or (not image.any() and image.ndim not in (2, 3)):
# All black frames will return not numpy.any() so check dims too
logger.warning("Unable to open image. Skipping: '%s'", filename)
continue
logger.trace("Putting to queue: %s", [v.shape if isinstance(v, np.ndarray) else v
for v in retval])
queue.put(retval)
logger.trace("Putting EOF")
queue.put("EOF")
def _from_video(self):
""" Generator for loading frames from a video
Yields
------
filename: str
The dummy filename of the loaded video frame.
image: numpy.ndarray
The loaded video frame.
"""
logger.debug("Loading frames from video: '%s'", self.location)
reader = imageio.get_reader(self.location, "ffmpeg")
for idx, frame in enumerate(reader):
if idx in self._skip_list:
logger.trace("Skipping frame %s due to skip list", idx)
continue
# Convert to BGR for cv2 compatibility
frame = frame[:, :, ::-1]
filename = self._dummy_video_framename(idx)
logger.trace("Loading video frame: '%s'", filename)
yield filename, frame
reader.close()
def _dummy_video_framename(self, index):
""" Return a dummy filename for video files
Parameters
----------
index: int
The index number for the frame in the video file
Notes
-----
Indexes start at 0, frame numbers start at 1, so index is incremented by 1
when creating the filename
Returns
-------
str: A dummied filename for a video frame """
vidname = os.path.splitext(os.path.basename(self.location))[0]
return "{}_{:06d}.png".format(vidname, index + 1)
def _from_folder(self):
""" Generator for loading images from a folder
Yields
------
filename: str
The filename of the loaded image.
image: numpy.ndarray
The loaded image.
"""
logger.debug("Loading frames from folder: '%s'", self.location)
for idx, filename in enumerate(self.file_list):
if idx in self._skip_list:
logger.trace("Skipping frame %s due to skip list")
continue
image_read = read_image(filename, raise_error=False, with_hash=False)
retval = filename, image_read
if retval[1] is None:
logger.warning("Frame not loaded: '%s'", filename)
continue
yield retval
def load(self):
""" Generator for loading images from the given :attr:`location`
If :class:`FacesLoader` is in use then the sha1 hash of the image is added as the final
item in the output `tuple`.
Yields
------
filename: str
The filename of the loaded image.
image: numpy.ndarray
The loaded image.
sha1_hash: str, (:class:`FacesLoader` only)
The sha1 hash of the loaded image. Only yielded if :class:`FacesLoader` is being
executed.
"""
logger.debug("Initializing Load Generator")
self._set_thread()
while True:
self._thread.check_and_raise_error()
try:
retval = self._queue.get(True, 1)
except QueueEmpty:
continue
if retval == "EOF":
logger.trace("Got EOF")
break
logger.trace("Yielding: %s", [v.shape if isinstance(v, np.ndarray) else v
for v in retval])
yield retval
logger.debug("Closing Load Generator")
self.close()
class FacesLoader(ImagesLoader):
""" Loads faces from a faces folder along with the face's hash.
Examples
--------
Loading faces with their sha1 hash:
>>> loader = FacesLoader('/path/to/faces/folder')
>>> for filename, face, sha1_hash in loader.load():
>>> <do processing>
"""
def __init__(self, path, skip_list=None, count=None):
logger.debug("Initializing %s: (path: %s, count: %s)", self.__class__.__name__,
path, count)
super().__init__(path, queue_size=8, skip_list=skip_list, count=count)
def _from_folder(self):
""" Generator for loading images from a folder
Faces will only ever be loaded from a folder, so this is the only function requiring
an override
Yields
------
filename: str
The filename of the loaded image.
image: numpy.ndarray
The loaded image.
sha1_hash: str
The sha1 hash of the loaded image.
"""
logger.debug("Loading images from folder: '%s'", self.location)
for idx, filename in enumerate(self.file_list):
if idx in self._skip_list:
logger.trace("Skipping face %s due to skip list")
continue
image_read = read_image(filename, raise_error=False, with_hash=True)
retval = filename, *image_read
if retval[1] is None:
logger.warning("Face not loaded: '%s'", filename)
continue
yield retval
class SingleFrameLoader(ImagesLoader):
""" Allows direct access to a frame by filename or frame index.
As we are interested in instant access to frames, there is no requirement to process in a
background thread, as either way we need to wait for the frame to load.
Parameters
----------
video_meta_data: dict, optional
Existing video meta information containing the pts_time and iskey flags for the given
video. Used in conjunction with single_frame_reader for faster seeks. Providing this means
that the video does not need to be scanned again. Set to ``None`` if the video is to be
scanned. Default: ``None``
"""
def __init__(self, path, video_meta_data=None):
logger.debug("Initializing %s: (path: %s, video_meta_data: %s)",
self.__class__.__name__, path, video_meta_data)
self._video_meta_data = dict() if video_meta_data is None else video_meta_data
self._reader = None
super().__init__(path, queue_size=1, fast_count=False)
@property
def video_meta_data(self):
""" dict: For videos contains the keys `frame_pts` holding a list of time stamps for each
frame and `keyframes` holding the frame index of each key frame.
Notes
-----
Only populated if the input is a video and single frame reader is being used, otherwise
returns ``None``.
"""
return self._video_meta_data
def _get_count_and_filelist(self, fast_count, count):
if self._is_video:
self._reader = imageio.get_reader(self.location, "ffmpeg")
self._reader.use_patch = True
count, video_meta_data = self._reader.get_frame_info(
frame_pts=self._video_meta_data.get("pts_time", None),
keyframes=self._video_meta_data.get("keyframes", None))
self._video_meta_data = video_meta_data
super()._get_count_and_filelist(fast_count, count)
def image_from_index(self, index):
""" Return a single image from :attr:`file_list` for the given index.
Parameters
----------
index: int
The index number (frame number) of the frame to retrieve. NB: The first frame is
index `0`
Returns
-------
filename: str
The filename of the returned image
image: :class:`numpy.ndarray`
The image for the given index
Notes
-----
Retrieving frames from video files can be slow as the whole video file needs to be
iterated to retrieve the requested frame. If a frame has already been retrieved, then
retrieving frames of a higher index will be quicker than retrieving frames of a lower
index, as iteration needs to start from the beginning again when navigating backwards.
We do not use a background thread for this task, as it is assumed that requesting an image
by index will be done when required.
"""
if self.is_video:
image = self._reader.get_data(index)[..., ::-1]
filename = self._dummy_video_framename(index)
else:
filename = self.file_list[index]
image = read_image(filename, raise_error=True)
filename = os.path.basename(filename)
logger.trace("index: %s, filename: %s image shape: %s", index, filename, image.shape)
return filename, image
class ImagesSaver(ImageIO):
""" Perform image saving to a destination folder.
Images are saved in a background ThreadPoolExecutor to allow for concurrent saving.
See also :class:`ImageIO` for additional attributes.
Parameters
----------
path: str
The folder to save images to. This must be an existing folder.
queue_size: int, optional
The amount of images to hold in the internal buffer. Default: 8.
as_bytes: bool, optional
``True`` if the image is already encoded to bytes, ``False`` if the image is a
:class:`numpy.ndarray`. Default: ``False``.
Examples
--------
>>> saver = ImagesSaver('/path/to/save/folder')
>>> for filename, image in <image_iterator>:
>>> saver.save(filename, image)
>>> saver.close()
"""
def __init__(self, path, queue_size=8, as_bytes=False):
logger.debug("Initializing %s: (path: %s, queue_size: %s, as_bytes: %s)",
self.__class__.__name__, path, queue_size, as_bytes)
super().__init__(path, queue_size=queue_size)
self._as_bytes = as_bytes
def _check_location_exists(self):
""" Check whether the output location exists and is a folder
Raises
------
FaceswapError
If the given location does not exist or the location is not a folder
"""
if not isinstance(self.location, str):
raise FaceswapError("The output location must be a string not a "
"{}".format(type(self.location)))
super()._check_location_exists()
if not os.path.isdir(self.location):
raise FaceswapError("The output location '{}' is not a folder".format(self.location))
def _process(self, queue):
""" Saves images from the save queue to the given :attr:`location` inside a thread.
Parameters
----------
queue: queue.Queue()
The ImageIO Queue
"""
executor = futures.ThreadPoolExecutor(thread_name_prefix=self.__class__.__name__)
while True:
item = queue.get()
if item == "EOF":
logger.debug("EOF received")
break
logger.trace("Submitting: '%s'", item[0])
executor.submit(self._save, *item)
executor.shutdown()
def _save(self, filename, image):
""" Save a single image inside a ThreadPoolExecutor
Parameters
----------
filename: str
The filename of the image to be saved. NB: Any folders passed in with the filename
will be stripped and replaced with :attr:`location`.
image: numpy.ndarray
The image to be saved
"""
filename = os.path.join(self.location, os.path.basename(filename))
try:
if self._as_bytes:
with open(filename, "wb") as out_file:
out_file.write(image)
else:
cv2.imwrite(filename, image)
logger.trace("Saved image: '%s'", filename)
except Exception as err: # pylint: disable=broad-except
logger.error("Failed to save image '%s'. Original Error: %s", filename, err)
def save(self, filename, image):
""" Save the given image in the background thread
Ensure that :func:`close` is called once all save operations are complete.
Parameters
----------
filename: str
The filename of the image to be saved
image: numpy.ndarray
The image to be saved
"""
self._set_thread()
logger.trace("Putting to save queue: '%s'", filename)
self._queue.put((filename, image))
def close(self):
""" Signal to the Save Threads that they should be closed and cleanly shutdown
the saver """
logger.debug("Putting EOF to save queue")
self._queue.put("EOF")
super().close() | en | 0.796578 | #!/usr/bin python3 Utilities for working with images and videos # pylint:disable=invalid-name # ################### # # <<< IMAGE UTILS >>> # # ################### # # <<< IMAGE IO >>> # Monkey patch imageio ffmpeg to use keyframes whilst seeking Store the source video's keyframes in :attr:`_frame_info" for the current video for use in :func:`initialize`. Parameters ---------- frame_pts: list, optional A list corresponding to the video frame count of the pts_time per frame. If this and `keyframes` are provided, then analyzing the video is skipped and the values from the given lists are used. Default: ``None`` keyframes: list, optional A list containing the frame numbers of each key frame. if this and `frame_pts` are provided, then analyzing the video is skipped and the values from the given lists are used. Default: ``None`` # Floating points make TQDM display poorly, so only update on full # second increments Return the previous keyframe's pts_time and frame number Replace ImageIO _initialize with a version that explictly uses keyframes. Notes ----- This introduces a minor change by seeking fast to the previous keyframe and then discarding subsequent frames until the desired frame is reached. In testing, setting -ss flag either prior to input, or both prior (fast) and after (slow) would not always bring back the correct frame for all videos. Navigating to the previous keyframe then discarding frames until the correct frame is reached appears to work well. # pylint: disable-all # Create input args # noqa # re-initialize / seek # Note: only works if we initialized earlier, and now have meta. Some info here: # https://trac.ffmpeg.org/wiki/Seeking # There are two ways to seek, one before -i (input_params) and after (output_params). # The former is fast, because it uses keyframes, the latter is slow but accurate. # According to the article above, the fast method should also be accurate from ffmpeg # version 2.1, however in version 4.1 our tests start failing again. Not sure why, but # we can solve this by combining slow and fast. # Further note: The old method would go back 10 seconds and then seek slow. This was # still somewhat unresponsive and did not always land on the correct frame. This monkey # patched version goes to the previous keyframe then discards frames until the correct # frame is landed on. # We used to have this epsilon earlier, when we did not use # the slow seek. I don't think we need it anymore. # epsilon = -1 / self._meta["fps"] * 0.1 # Output args, for writing to pipe # Get pixelformat and bytes per pixel # Create generator # Read meta data. This start the generator (and ffmpeg subprocess) # With cameras, catch error and turn into IndexError # Skip frames that are not the desired frame # we already have meta data Read an image file from a file location. Extends the functionality of :func:`cv2.imread()` by ensuring that an image was actually loaded. Errors can be logged and ignored so that the process can continue on an image load failure. Parameters ---------- filename: str Full path to the image to be loaded. raise_error: bool, optional If ``True`` then any failures (including the returned image being ``None``) will be raised. If ``False`` then an error message will be logged, but the error will not be raised. Default: ``False`` with_hash: bool, optional If ``True`` then returns the image's sha1 hash with the image. Default: ``False`` Returns ------- numpy.ndarray or tuple If :attr:`with_hash` is ``False`` then returns a `numpy.ndarray` of the image in `BGR` channel order. If :attr:`with_hash` is ``True`` then returns a `tuple` of (`numpy.ndarray`" of the image in `BGR`, `str` of sha` hash of image) Example ------- >>> image_file = "/path/to/image.png" >>> try: >>> image = read_image(image_file, raise_error=True, with_hash=False) >>> except: >>> raise ValueError("There was an error") # pylint:disable=broad-except Load a batch of images from the given file locations. Leverages multi-threading to load multiple images from disk at the same time leading to vastly reduced image read times. Parameters ---------- filenames: list A list of ``str`` full paths to the images to be loaded. Returns ------- numpy.ndarray The batch of images in `BGR` channel order returned in the order of :attr:`filenames` Notes ----- As the images are compiled into a batch, they must be all of the same dimensions. Example ------- >>> image_filenames = ["/path/to/image_1.png", "/path/to/image_2.png", "/path/to/image_3.png"] >>> images = read_image_batch(image_filenames) # There is no guarantee that the same filename will not be passed through multiple times # (and when shuffle is true this can definitely happen), so we can't just call # filenames.index(). Return the `sha1` hash of an image saved on disk. Parameters ---------- filename: str Full path to the image to be loaded. Returns ------- str The :func:`hashlib.hexdigest()` representation of the `sha1` hash of the given image. Example ------- >>> image_file = "/path/to/image.png" >>> image_hash = read_image_hash(image_file) Return the `sha` hash of a batch of images Leverages multi-threading to load multiple images from disk at the same time leading to vastly reduced image read times. Creates a generator to retrieve filenames with their hashes as they are calculated. Notes ----- The order of returned values is non-deterministic so will most likely not be returned in the same order as the filenames Parameters ---------- filenames: list A list of ``str`` full paths to the images to be loaded. Yields ------- tuple: (`filename`, :func:`hashlib.hexdigest()` representation of the `sha1` hash of the image) Example ------- >>> image_filenames = ["/path/to/image_1.png", "/path/to/image_2.png", "/path/to/image_3.png"] >>> for filename, hash in read_image_hash_batch(image_filenames): >>> <do something> Encode an image, and get the encoded image back with its `sha1` hash. Parameters ---------- image: numpy.ndarray The image to be encoded in `BGR` channel order. extension: str A compatible `cv2` image file extension that the final image is to be saved to. Returns ------- image_hash: str The :func:`hashlib.hexdigest()` representation of the `sha1` hash of the encoded image encoded_image: bytes The image encoded into the correct file format Example ------- >>> image_file = "/path/to/image.png" >>> image = read_image(image_file) >>> image_hash, encoded_image = encode_image_with_hash(image, ".jpg") Convert a batch of images from one color space to another. Converts a batch of images by reshaping the batch prior to conversion rather than iterating over the images. This leads to a significant speed up in the convert process. Parameters ---------- batch: numpy.ndarray A batch of images. colorspace: str The OpenCV Color Conversion Code suffix. For example for BGR to LAB this would be ``'BGR2LAB'``. See https://docs.opencv.org/4.1.1/d8/d01/group__imgproc__color__conversions.html for a full list of color codes. Returns ------- numpy.ndarray The batch converted to the requested color space. Example ------- >>> images_bgr = numpy.array([image1, image2, image3]) >>> images_lab = batch_convert_color(images_bgr, "BGR2LAB") Notes ----- This function is only compatible for color space conversions that have the same image shape for source and destination color spaces. If you use :func:`batch_convert_color` with 8-bit images, the conversion will have some information lost. For many cases, this will not be noticeable but it is recommended to use 32-bit images in cases that need the full range of colors or that convert an image before an operation and then convert back. # ################### # # <<< VIDEO UTILS >>> # # ################### # Count the number of frames in a video file There is no guaranteed accurate way to get a count of video frames without iterating through a video and decoding every frame. :func:`count_frames` can return an accurate count (albeit fairly slowly) or a possibly less accurate count, depending on the :attr:`fast` parameter. A progress bar is displayed. Parameters ---------- filename: str Full path to the video to return the frame count from. fast: bool, optional Whether to count the frames without decoding them. This is significantly faster but accuracy is not guaranteed. Default: ``False``. Returns ------- int: The number of frames in the given video file. Example ------- >>> filename = "/path/to/video.mp4" >>> frame_count = count_frames(filename) Perform disk IO for images or videos in a background thread. This is the parent thread for :class:`ImagesLoader` and :class:`ImagesSaver` and should not be called directly. Parameters ---------- path: str or list The path to load or save images to/from. For loading this can be a folder which contains images, video file or a list of image files. For saving this must be an existing folder. queue_size: int The amount of images to hold in the internal buffer. args: tuple, optional The arguments to be passed to the loader or saver thread. Default: ``None`` See Also -------- lib.image.ImagesLoader : Background Image Loader inheriting from this class. lib.image.ImagesSaver : Background Image Saver inheriting from this class. str: The folder or video that was passed in as the :attr:`path` parameter. Check whether the input location exists. Raises ------ FaceswapError If the given location does not exist Set the background thread for the load and save iterators and launch it. Image IO process to be run in a thread. Override for loader/saver process. Parameters ---------- queue: queue.Queue() The ImageIO Queue Closes down and joins the internal threads Perform image loading from a folder of images or a video. Images will be loaded and returned in the order that they appear in the folder, or in the video to ensure deterministic ordering. Loading occurs in a background thread, caching 8 images at a time so that other processes do not need to wait on disk reads. See also :class:`ImageIO` for additional attributes. Parameters ---------- path: str or list The path to load images from. This can be a folder which contains images a video file or a list of image files. queue_size: int, optional The amount of images to hold in the internal buffer. Default: 8. fast_count: bool, optional When loading from video, the video needs to be parsed frame by frame to get an accurate count. This can be done quite quickly without guaranteed accuracy, or slower with guaranteed accuracy. Set to ``True`` to count quickly, or ``False`` to count slower but accurately. Default: ``True``. skip_list: list, optional Optional list of frame/image indices to not load. Any indices provided here will be skipped when executing the :func:`load` function from the given location. Default: ``None`` count: int, optional If the number of images that the loader will encounter is already known, it can be passed in here to skip the image counting step, which can save time at launch. Set to ``None`` if the count is not already known. Default: ``None`` Examples -------- Loading from a video file: >>> loader = ImagesLoader('/path/to/video.mp4') >>> for filename, image in loader.load(): >>> <do processing> int: The number of images or video frames in the source location. This count includes any files that will ultimately be skipped if a :attr:`skip_list` has been provided. See also: :attr:`process_count` int: The number of images or video frames to be processed (IE the total count less items that are to be skipped from the :attr:`skip_list`) bool: ``True`` if the input is a video, ``False`` if it is not float: For an input folder of images, this will always return 25fps. If the input is a video, then the fps of the video will be returned. list: A full list of files in the source location. This includes any files that will ultimately be skipped if a :attr:`skip_list` has been provided. If the input is a video then this is a list of dummy filenames as corresponding to an alignments file Add a skip list to this :class:`ImagesLoader` Parameters ---------- skip_list: list A list of indices corresponding to the frame indices that should be skipped by the :func:`load` function. Check whether the input is a video Returns ------- bool: 'True' if input is a video 'False' if it is a folder. Raises ------ FaceswapError If the given location is a file and does not have a valid video extension. Get the Frames per Second. If the input is a folder of images than 25.0 will be returned, as it is not possible to calculate the fps just from frames alone. For video files the correct FPS will be returned. Returns ------- float: The Frames per Second of the input sources Set the count of images to be processed and set the file list If the input is a video, a dummy file list is created for checking against an alignments file, otherwise it will be a list of full filenames. Parameters ---------- fast_count: bool When loading from video, the video needs to be parsed frame by frame to get an accurate count. This can be done quite quickly without guaranteed accuracy, or slower with guaranteed accuracy. Set to ``True`` to count quickly, or ``False`` to count slower but accurately. count: int The number of images that the loader will encounter if already known, otherwise ``None`` The load thread. Loads from a folder of images or from a video and puts to a queue Parameters ---------- queue: queue.Queue() The ImageIO Queue # All black frames will return not numpy.any() so check dims too Generator for loading frames from a video Yields ------ filename: str The dummy filename of the loaded video frame. image: numpy.ndarray The loaded video frame. # Convert to BGR for cv2 compatibility Return a dummy filename for video files Parameters ---------- index: int The index number for the frame in the video file Notes ----- Indexes start at 0, frame numbers start at 1, so index is incremented by 1 when creating the filename Returns ------- str: A dummied filename for a video frame Generator for loading images from a folder Yields ------ filename: str The filename of the loaded image. image: numpy.ndarray The loaded image. Generator for loading images from the given :attr:`location` If :class:`FacesLoader` is in use then the sha1 hash of the image is added as the final item in the output `tuple`. Yields ------ filename: str The filename of the loaded image. image: numpy.ndarray The loaded image. sha1_hash: str, (:class:`FacesLoader` only) The sha1 hash of the loaded image. Only yielded if :class:`FacesLoader` is being executed. Loads faces from a faces folder along with the face's hash. Examples -------- Loading faces with their sha1 hash: >>> loader = FacesLoader('/path/to/faces/folder') >>> for filename, face, sha1_hash in loader.load(): >>> <do processing> Generator for loading images from a folder Faces will only ever be loaded from a folder, so this is the only function requiring an override Yields ------ filename: str The filename of the loaded image. image: numpy.ndarray The loaded image. sha1_hash: str The sha1 hash of the loaded image. Allows direct access to a frame by filename or frame index. As we are interested in instant access to frames, there is no requirement to process in a background thread, as either way we need to wait for the frame to load. Parameters ---------- video_meta_data: dict, optional Existing video meta information containing the pts_time and iskey flags for the given video. Used in conjunction with single_frame_reader for faster seeks. Providing this means that the video does not need to be scanned again. Set to ``None`` if the video is to be scanned. Default: ``None`` dict: For videos contains the keys `frame_pts` holding a list of time stamps for each frame and `keyframes` holding the frame index of each key frame. Notes ----- Only populated if the input is a video and single frame reader is being used, otherwise returns ``None``. Return a single image from :attr:`file_list` for the given index. Parameters ---------- index: int The index number (frame number) of the frame to retrieve. NB: The first frame is index `0` Returns ------- filename: str The filename of the returned image image: :class:`numpy.ndarray` The image for the given index Notes ----- Retrieving frames from video files can be slow as the whole video file needs to be iterated to retrieve the requested frame. If a frame has already been retrieved, then retrieving frames of a higher index will be quicker than retrieving frames of a lower index, as iteration needs to start from the beginning again when navigating backwards. We do not use a background thread for this task, as it is assumed that requesting an image by index will be done when required. Perform image saving to a destination folder. Images are saved in a background ThreadPoolExecutor to allow for concurrent saving. See also :class:`ImageIO` for additional attributes. Parameters ---------- path: str The folder to save images to. This must be an existing folder. queue_size: int, optional The amount of images to hold in the internal buffer. Default: 8. as_bytes: bool, optional ``True`` if the image is already encoded to bytes, ``False`` if the image is a :class:`numpy.ndarray`. Default: ``False``. Examples -------- >>> saver = ImagesSaver('/path/to/save/folder') >>> for filename, image in <image_iterator>: >>> saver.save(filename, image) >>> saver.close() Check whether the output location exists and is a folder Raises ------ FaceswapError If the given location does not exist or the location is not a folder Saves images from the save queue to the given :attr:`location` inside a thread. Parameters ---------- queue: queue.Queue() The ImageIO Queue Save a single image inside a ThreadPoolExecutor Parameters ---------- filename: str The filename of the image to be saved. NB: Any folders passed in with the filename will be stripped and replaced with :attr:`location`. image: numpy.ndarray The image to be saved # pylint: disable=broad-except Save the given image in the background thread Ensure that :func:`close` is called once all save operations are complete. Parameters ---------- filename: str The filename of the image to be saved image: numpy.ndarray The image to be saved Signal to the Save Threads that they should be closed and cleanly shutdown the saver | 2.411046 | 2 |
src/AsmvarVarScore/modul/VariantRecalibratorArgumentCollection.py | bioinformatics-centre/AsmVar | 17 | 6627993 | <reponame>bioinformatics-centre/AsmVar<filename>src/AsmvarVarScore/modul/VariantRecalibratorArgumentCollection.py<gh_stars>10-100
"""
====================================
====================================
Author : <NAME>
Date : 2014-05-21 18:03:28
"""
class VariantRecalibratorArgumentCollection:
def __init__ (self):
self.NITER = 150
self.NINIT = 100
self.STD_THRESHOLD = 10.0
self.MIN_NUM_BAD_VARIANTS = 1000
self.MAX_NUM_TRAINING_DATA = 50000
self.TRAIN_SIZE_RATE = 0.6 # The ratio of Traing date set
self.CV_SIZE_RATE = 0.2 # The ratio of cross validation data set
self.TEST_SIZE_RATE = 0.2 # The ratio of test data set
self.MAX_GAUSSIANS = 6
self.POSITIVE_TO_NEGATIVE_RATE = 0.01 # The threshold that the positive training set -> negative
self.MAX_GAUSSIANS_FOR_NEGATIVE_MODEL = 4
| """
====================================
====================================
Author : <NAME>
Date : 2014-05-21 18:03:28
"""
class VariantRecalibratorArgumentCollection:
def __init__ (self):
self.NITER = 150
self.NINIT = 100
self.STD_THRESHOLD = 10.0
self.MIN_NUM_BAD_VARIANTS = 1000
self.MAX_NUM_TRAINING_DATA = 50000
self.TRAIN_SIZE_RATE = 0.6 # The ratio of Traing date set
self.CV_SIZE_RATE = 0.2 # The ratio of cross validation data set
self.TEST_SIZE_RATE = 0.2 # The ratio of test data set
self.MAX_GAUSSIANS = 6
self.POSITIVE_TO_NEGATIVE_RATE = 0.01 # The threshold that the positive training set -> negative
self.MAX_GAUSSIANS_FOR_NEGATIVE_MODEL = 4 | en | 0.702854 | ==================================== ==================================== Author : <NAME> Date : 2014-05-21 18:03:28 # The ratio of Traing date set # The ratio of cross validation data set # The ratio of test data set # The threshold that the positive training set -> negative | 2.546165 | 3 |
epgsearch/src/EPGSearchSetup.py | FoxyRabbit67/enigma2-plugins | 41 | 6627994 | <reponame>FoxyRabbit67/enigma2-plugins
# for localized messages
# GUI (Screens)
from Screens.Screen import Screen
from Components.ConfigList import ConfigListScreen
from Components.config import ConfigSelection, NoSave
# GUI (Summary)
from Screens.Setup import SetupSummary
from Screens.InfoBar import InfoBar
# GUI (Components)
from Components.ActionMap import ActionMap
from Components.Sources.StaticText import StaticText
# Configuration
from Components.config import config, getConfigListEntry
class EPGSearchSetup(Screen, ConfigListScreen):
skin = """<screen name="EPGSearchSetup" position="center,90" size="820,570">
<ePixmap pixmap="skin_default/buttons/red.png" position="10,5" size="200,40"/>
<ePixmap pixmap="skin_default/buttons/green.png" position="210,5" size="200,40"/>
<widget source="key_red" render="Label" position="10,5" size="200,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-2,-2"/>
<widget source="key_green" render="Label" position="210,5" size="200,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-2,-2"/>
<eLabel position="10,50" size="800,1" backgroundColor="grey"/>
<widget name="config" position="10,60" size="800,400" enableWrapAround="1" scrollbarMode="showOnDemand"/>
<eLabel position="10,470" size="800,1" backgroundColor="grey"/>
<widget source="help" render="Label" position="10,480" size="800,80" font="Regular;21" />
</screen>"""
def __init__(self, session):
Screen.__init__(self, session)
# Summary
self.setup_title = _("EPGSearch Setup")
self.onChangedEntry = []
#set config-values for search_scope-config
self.scopeChoices = self.getScopeChoices()
self.scopeChoices_default = self.getScopeChoicesDefault()
self.config_search_scope = NoSave( ConfigSelection(choices=self.scopeChoices, default=self.scopeChoices_default) )
self.list = []
self.buildConfig()
ConfigListScreen.__init__(self, self.list, session = session, on_change = self.changed)
def selectionChanged():
if self["config"].current:
self["config"].current[1].onDeselect(self.session)
self["config"].current = self["config"].getCurrent()
if self["config"].current:
self["config"].current[1].onSelect(self.session)
for x in self["config"].onSelectionChanged:
x()
self["config"].selectionChanged = selectionChanged
self["config"].onSelectionChanged.append(self.updateHelp)
# Initialize widgets
self["key_green"] = StaticText(_("OK"))
self["key_red"] = StaticText(_("Cancel"))
self["help"] = StaticText()
# Define Actions
self["actions"] = ActionMap(["SetupActions"],
{
"cancel": self.keyCancel,
"save": self.keySave,
}
)
# Trigger change
self.changed()
self.onLayoutFinish.append(self.setCustomTitle)
def buildConfig(self):
self.list.append( getConfigListEntry(_("Length of History"), config.plugins.epgsearch.history_length, _("Number of entries to retain in the search history at most. Set to 0 to disable history entirely.")) )
self.list.append( getConfigListEntry(_("Add search text to history when opening plugin"), config.plugins.epgsearch.add_history_onOpen , _("Enable to add search text to history when opening the plugin.")) )
self.list.append( getConfigListEntry(_("Search type"), config.plugins.epgsearch.search_type, _("Select \"exact match of title\" for a perfect match or \"partial match\" if you want to search for a part of the title or the description. Select \"Ask user\" to choose when searching.")) )
self.list.append( getConfigListEntry(_("Search scope"), self.config_search_scope, _("Search will return only matches from services in the selected bouquet.")) )
if self.config_search_scope.value != "all":
self.list.append( getConfigListEntry(_("Show events"), config.plugins.epgsearch.show_events, _("Show 'all', 'current', 'future' or 'current & future' events. This allows filtering matches by the event time.")) )
self.list.append( getConfigListEntry(_("Show Picons"), config.plugins.epgsearch.show_picon, _("Show the the picon of the channel instead of channelname. Use the picon path from the channelselection settings.")) )
if not config.plugins.epgsearch.show_picon.value:
self.list.append( getConfigListEntry(_("Show best matching channelname in screen title"), config.plugins.epgsearch.show_sname_in_title, _("Shows the best matching channelname in the screen title to have more space to display event name and short description.")) )
self.list.append( getConfigListEntry(_("Show short description"), config.plugins.epgsearch.show_shortdesc, _("Add the short description of the event to the search result.")) )
self.list.append(getConfigListEntry(_("BUTTONS"), ))
self.list.append( getConfigListEntry(_("Buttons for 'Search EPG'"), config.plugins.epgsearch.searchEPG_menu, _("Select the buttons, which show this menu item (on change GUI-restart is necessary).")) )
self.list.append( getConfigListEntry(_("Buttons for 'open EPGSearch search list'"), config.plugins.epgsearch.openSearchFilter_menu, _("Select the buttons, which show this menu item (on change GUI-restart is necessary).")) )
from EPGSearch import autoTimerAvailable
if autoTimerAvailable:
self.list.append( getConfigListEntry(_("Buttons for 'add search filter to EPGSearch'"), config.plugins.epgsearch.addSearchFilter_menu, _("Select the buttons, which show this menu item (on change GUI-restart is necessary).")) )
self.list.append( getConfigListEntry(_("Blue button function (search list)"), config.plugins.epgsearch.blue_function, _("Select the search list to show on blue button in the EPGSearch match list (default = text search history and search filter list).")) )
def getScopeChoicesDefault(self):
scopeChoices_default = "all"
for choice in self.scopeChoices:
if config.plugins.epgsearch.search_scope.value == choice[0]:
scopeChoices_default = config.plugins.epgsearch.search_scope.value
break
return scopeChoices_default
def getScopeChoices(self):
#set config-values for bouquet-config
config_scope_choices = [("all",_("all services")), ("current",_("current bouquet"))]
#get bouquetlist
infoBarInstance = InfoBar.instance
if infoBarInstance is not None:
bouquets = infoBarInstance.servicelist.getBouquetList()
for bouquet in bouquets:
config_scope_choices.append((bouquet[1].toString(),bouquet[0]))
return config_scope_choices
def keySave(self):
self.saveAll()
#config.plugins.epgsearch.search_current_bouquet.value = self.config_search_current_bouquet.value
config.plugins.epgsearch.search_scope.value = self.config_search_scope.value
config.plugins.epgsearch.save()
self.close()
def changeConfig(self):
self.list = []
self.buildConfig()
self["config"].setList(self.list)
def changed(self):
for x in self.onChangedEntry:
x()
current = self["config"].getCurrent()[1]
if (current == config.plugins.epgsearch.show_picon) or (current == self.config_search_scope):
self.changeConfig()
return
def setCustomTitle(self):
self.setTitle(_("EPGSearch Setup"))
def updateHelp(self):
cur = self["config"].getCurrent()
if cur:
self["help"].text = cur[2]
def getCurrentEntry(self):
return self["config"].getCurrent()[0]
def getCurrentValue(self):
return str(self["config"].getCurrent()[1].getText())
def createSummary(self):
return SetupSummary | # for localized messages
# GUI (Screens)
from Screens.Screen import Screen
from Components.ConfigList import ConfigListScreen
from Components.config import ConfigSelection, NoSave
# GUI (Summary)
from Screens.Setup import SetupSummary
from Screens.InfoBar import InfoBar
# GUI (Components)
from Components.ActionMap import ActionMap
from Components.Sources.StaticText import StaticText
# Configuration
from Components.config import config, getConfigListEntry
class EPGSearchSetup(Screen, ConfigListScreen):
skin = """<screen name="EPGSearchSetup" position="center,90" size="820,570">
<ePixmap pixmap="skin_default/buttons/red.png" position="10,5" size="200,40"/>
<ePixmap pixmap="skin_default/buttons/green.png" position="210,5" size="200,40"/>
<widget source="key_red" render="Label" position="10,5" size="200,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-2,-2"/>
<widget source="key_green" render="Label" position="210,5" size="200,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-2,-2"/>
<eLabel position="10,50" size="800,1" backgroundColor="grey"/>
<widget name="config" position="10,60" size="800,400" enableWrapAround="1" scrollbarMode="showOnDemand"/>
<eLabel position="10,470" size="800,1" backgroundColor="grey"/>
<widget source="help" render="Label" position="10,480" size="800,80" font="Regular;21" />
</screen>"""
def __init__(self, session):
Screen.__init__(self, session)
# Summary
self.setup_title = _("EPGSearch Setup")
self.onChangedEntry = []
#set config-values for search_scope-config
self.scopeChoices = self.getScopeChoices()
self.scopeChoices_default = self.getScopeChoicesDefault()
self.config_search_scope = NoSave( ConfigSelection(choices=self.scopeChoices, default=self.scopeChoices_default) )
self.list = []
self.buildConfig()
ConfigListScreen.__init__(self, self.list, session = session, on_change = self.changed)
def selectionChanged():
if self["config"].current:
self["config"].current[1].onDeselect(self.session)
self["config"].current = self["config"].getCurrent()
if self["config"].current:
self["config"].current[1].onSelect(self.session)
for x in self["config"].onSelectionChanged:
x()
self["config"].selectionChanged = selectionChanged
self["config"].onSelectionChanged.append(self.updateHelp)
# Initialize widgets
self["key_green"] = StaticText(_("OK"))
self["key_red"] = StaticText(_("Cancel"))
self["help"] = StaticText()
# Define Actions
self["actions"] = ActionMap(["SetupActions"],
{
"cancel": self.keyCancel,
"save": self.keySave,
}
)
# Trigger change
self.changed()
self.onLayoutFinish.append(self.setCustomTitle)
def buildConfig(self):
self.list.append( getConfigListEntry(_("Length of History"), config.plugins.epgsearch.history_length, _("Number of entries to retain in the search history at most. Set to 0 to disable history entirely.")) )
self.list.append( getConfigListEntry(_("Add search text to history when opening plugin"), config.plugins.epgsearch.add_history_onOpen , _("Enable to add search text to history when opening the plugin.")) )
self.list.append( getConfigListEntry(_("Search type"), config.plugins.epgsearch.search_type, _("Select \"exact match of title\" for a perfect match or \"partial match\" if you want to search for a part of the title or the description. Select \"Ask user\" to choose when searching.")) )
self.list.append( getConfigListEntry(_("Search scope"), self.config_search_scope, _("Search will return only matches from services in the selected bouquet.")) )
if self.config_search_scope.value != "all":
self.list.append( getConfigListEntry(_("Show events"), config.plugins.epgsearch.show_events, _("Show 'all', 'current', 'future' or 'current & future' events. This allows filtering matches by the event time.")) )
self.list.append( getConfigListEntry(_("Show Picons"), config.plugins.epgsearch.show_picon, _("Show the the picon of the channel instead of channelname. Use the picon path from the channelselection settings.")) )
if not config.plugins.epgsearch.show_picon.value:
self.list.append( getConfigListEntry(_("Show best matching channelname in screen title"), config.plugins.epgsearch.show_sname_in_title, _("Shows the best matching channelname in the screen title to have more space to display event name and short description.")) )
self.list.append( getConfigListEntry(_("Show short description"), config.plugins.epgsearch.show_shortdesc, _("Add the short description of the event to the search result.")) )
self.list.append(getConfigListEntry(_("BUTTONS"), ))
self.list.append( getConfigListEntry(_("Buttons for 'Search EPG'"), config.plugins.epgsearch.searchEPG_menu, _("Select the buttons, which show this menu item (on change GUI-restart is necessary).")) )
self.list.append( getConfigListEntry(_("Buttons for 'open EPGSearch search list'"), config.plugins.epgsearch.openSearchFilter_menu, _("Select the buttons, which show this menu item (on change GUI-restart is necessary).")) )
from EPGSearch import autoTimerAvailable
if autoTimerAvailable:
self.list.append( getConfigListEntry(_("Buttons for 'add search filter to EPGSearch'"), config.plugins.epgsearch.addSearchFilter_menu, _("Select the buttons, which show this menu item (on change GUI-restart is necessary).")) )
self.list.append( getConfigListEntry(_("Blue button function (search list)"), config.plugins.epgsearch.blue_function, _("Select the search list to show on blue button in the EPGSearch match list (default = text search history and search filter list).")) )
def getScopeChoicesDefault(self):
scopeChoices_default = "all"
for choice in self.scopeChoices:
if config.plugins.epgsearch.search_scope.value == choice[0]:
scopeChoices_default = config.plugins.epgsearch.search_scope.value
break
return scopeChoices_default
def getScopeChoices(self):
#set config-values for bouquet-config
config_scope_choices = [("all",_("all services")), ("current",_("current bouquet"))]
#get bouquetlist
infoBarInstance = InfoBar.instance
if infoBarInstance is not None:
bouquets = infoBarInstance.servicelist.getBouquetList()
for bouquet in bouquets:
config_scope_choices.append((bouquet[1].toString(),bouquet[0]))
return config_scope_choices
def keySave(self):
self.saveAll()
#config.plugins.epgsearch.search_current_bouquet.value = self.config_search_current_bouquet.value
config.plugins.epgsearch.search_scope.value = self.config_search_scope.value
config.plugins.epgsearch.save()
self.close()
def changeConfig(self):
self.list = []
self.buildConfig()
self["config"].setList(self.list)
def changed(self):
for x in self.onChangedEntry:
x()
current = self["config"].getCurrent()[1]
if (current == config.plugins.epgsearch.show_picon) or (current == self.config_search_scope):
self.changeConfig()
return
def setCustomTitle(self):
self.setTitle(_("EPGSearch Setup"))
def updateHelp(self):
cur = self["config"].getCurrent()
if cur:
self["help"].text = cur[2]
def getCurrentEntry(self):
return self["config"].getCurrent()[0]
def getCurrentValue(self):
return str(self["config"].getCurrent()[1].getText())
def createSummary(self):
return SetupSummary | en | 0.285984 | # for localized messages # GUI (Screens) # GUI (Summary) # GUI (Components) # Configuration <screen name="EPGSearchSetup" position="center,90" size="820,570"> <ePixmap pixmap="skin_default/buttons/red.png" position="10,5" size="200,40"/> <ePixmap pixmap="skin_default/buttons/green.png" position="210,5" size="200,40"/> <widget source="key_red" render="Label" position="10,5" size="200,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-2,-2"/> <widget source="key_green" render="Label" position="210,5" size="200,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-2,-2"/> <eLabel position="10,50" size="800,1" backgroundColor="grey"/> <widget name="config" position="10,60" size="800,400" enableWrapAround="1" scrollbarMode="showOnDemand"/> <eLabel position="10,470" size="800,1" backgroundColor="grey"/> <widget source="help" render="Label" position="10,480" size="800,80" font="Regular;21" /> </screen> # Summary #set config-values for search_scope-config # Initialize widgets # Define Actions # Trigger change #set config-values for bouquet-config #get bouquetlist #config.plugins.epgsearch.search_current_bouquet.value = self.config_search_current_bouquet.value | 2.085022 | 2 |
src/batou/secrets/encryption.py | wosc/batou | 1 | 6627995 | <reponame>wosc/batou
from batou import FileLockedError
from configupdater import ConfigUpdater
import fcntl
import glob
import io
import os
import shlex
import subprocess
import tempfile
# https://thraxil.org/users/anders/posts/2008/03/13/Subprocess-Hanging-PIPE-is-your-enemy/
NULL = tempfile.TemporaryFile()
NEW_FILE_TEMPLATE = """\
[batou]
members =
"""
class EncryptedFile(object):
"""Basic encryption methods - key management handled externally."""
lockfd = None
cleartext = None
GPG_BINARY_CANDIDATES = ["gpg", "gpg2"]
def __init__(self, encrypted_filename, write_lock=False, quiet=False):
"""Context manager that opens an encrypted file.
Use the read() and write() methods in the subordinate "with"
block to manipulate cleartext content. If the cleartext content
has been replaced, the encrypted file is updated.
`write_lock` must be set True if a modification of the file is
intended.
"""
self.encrypted_filename = encrypted_filename
self.write_lock = write_lock
self.quiet = quiet
self.recipients = []
def __enter__(self):
self._lock()
return self
def __exit__(self, _exc_type=None, _exc_value=None, _traceback=None):
self.lockfd.close()
def gpg(self):
with tempfile.TemporaryFile() as null:
for gpg in self.GPG_BINARY_CANDIDATES:
try:
subprocess.check_call([gpg, "--version"],
stdout=null,
stderr=null)
except (subprocess.CalledProcessError, OSError):
pass
else:
return gpg
raise RuntimeError("Could not find gpg binary."
" Is GPG installed? I tried looking for: {}".format(
", ".join("`{}`".format(x)
for x in self.GPG_BINARY_CANDIDATES)))
def read(self):
"""Read encrypted data into cleartext - if not not read already."""
if self.cleartext is None:
if os.path.exists(self.encrypted_filename):
self.cleartext = self._decrypt()
else:
self.cleartext = ''
return self.cleartext
def write(self):
"""Encrypt cleartext and write into destination file file. ."""
if not self.write_lock:
raise RuntimeError("write() needs a write lock")
self._encrypt(self.cleartext)
def _lock(self):
self.lockfd = open(self.encrypted_filename, self.write_lock and "a+"
or "r+")
try:
fcntl.lockf(
self.lockfd, fcntl.LOCK_EX | fcntl.LOCK_NB |
(fcntl.LOCK_EX if self.write_lock else fcntl.LOCK_SH))
except BlockingIOError:
raise FileLockedError(self.encrypted_filename)
def _decrypt(self):
args = [self.gpg()]
if self.quiet:
args += ['-q', '--no-tty', '--batch']
args += ['--decrypt', self.encrypted_filename]
return subprocess.check_output(args, stderr=NULL).decode("utf-8")
def _encrypt(self, data):
if not self.recipients:
raise ValueError('Need at least one recipient.')
os.rename(self.encrypted_filename, self.encrypted_filename + ".old")
args = [self.gpg(), '--encrypt']
for r in self.recipients:
args.extend(['-r', r.strip()])
args.extend(['-o', self.encrypted_filename])
try:
gpg = subprocess.Popen(args, stdin=subprocess.PIPE)
gpg.communicate(data.encode("utf-8"))
if gpg.returncode != 0:
raise RuntimeError("GPG returned non-zero exit code.")
except Exception:
os.rename(self.encrypted_filename + ".old",
self.encrypted_filename)
raise
else:
os.unlink(self.encrypted_filename + ".old")
class EncryptedConfigFile(object):
"""Wrap encrypted config files.
Manages keys based on the data in the configuration. Also allows
management of additional files with the same keys.
"""
def __init__(self,
encrypted_file,
subfile_pattern=None,
write_lock=False,
quiet=False):
self.subfile_pattern = subfile_pattern
self.write_lock = write_lock
self.quiet = quiet
self.files = {}
self.main_file = self.add_file(encrypted_file)
# Add all existing files to the session
if self.subfile_pattern:
for other_filename in glob.iglob(self.subfile_pattern):
self.add_file(other_filename)
def add_file(self, filename):
if filename not in self.files:
self.files[filename] = f = EncryptedFile(filename, self.write_lock,
self.quiet)
f.read()
return self.files[filename]
def __enter__(self):
self.main_file.__enter__()
return self
def __exit__(self, _exc_type=None, _exc_value=None, _traceback=None):
self.main_file.__exit__()
def read(self):
self.main_file.read()
if not self.main_file.cleartext:
self.main_file.cleartext = NEW_FILE_TEMPLATE
self.config = ConfigUpdater()
self.config.read_string(self.main_file.cleartext)
self.set_members(self.get_members())
def write(self):
s = io.StringIO()
self.config.write(s)
self.main_file.cleartext = s.getvalue()
for file in self.files.values():
file.recipients = self.get_members()
file.write()
def get_members(self):
if 'batou' not in self.config:
self.config.add_section('batou')
try:
members = self.config.get("batou", "members").value.split(",")
except Exception:
return []
members = [x.strip() for x in members]
members = [_f for _f in members if _f]
members.sort()
return members
def set_members(self, members):
# The whitespace here is exactly what
# "members = " looks like in the config file so we get
# proper indentation.
members = ",\n ".join(members)
self.config.set("batou", "members", members)
| from batou import FileLockedError
from configupdater import ConfigUpdater
import fcntl
import glob
import io
import os
import shlex
import subprocess
import tempfile
# https://thraxil.org/users/anders/posts/2008/03/13/Subprocess-Hanging-PIPE-is-your-enemy/
NULL = tempfile.TemporaryFile()
NEW_FILE_TEMPLATE = """\
[batou]
members =
"""
class EncryptedFile(object):
"""Basic encryption methods - key management handled externally."""
lockfd = None
cleartext = None
GPG_BINARY_CANDIDATES = ["gpg", "gpg2"]
def __init__(self, encrypted_filename, write_lock=False, quiet=False):
"""Context manager that opens an encrypted file.
Use the read() and write() methods in the subordinate "with"
block to manipulate cleartext content. If the cleartext content
has been replaced, the encrypted file is updated.
`write_lock` must be set True if a modification of the file is
intended.
"""
self.encrypted_filename = encrypted_filename
self.write_lock = write_lock
self.quiet = quiet
self.recipients = []
def __enter__(self):
self._lock()
return self
def __exit__(self, _exc_type=None, _exc_value=None, _traceback=None):
self.lockfd.close()
def gpg(self):
with tempfile.TemporaryFile() as null:
for gpg in self.GPG_BINARY_CANDIDATES:
try:
subprocess.check_call([gpg, "--version"],
stdout=null,
stderr=null)
except (subprocess.CalledProcessError, OSError):
pass
else:
return gpg
raise RuntimeError("Could not find gpg binary."
" Is GPG installed? I tried looking for: {}".format(
", ".join("`{}`".format(x)
for x in self.GPG_BINARY_CANDIDATES)))
def read(self):
"""Read encrypted data into cleartext - if not not read already."""
if self.cleartext is None:
if os.path.exists(self.encrypted_filename):
self.cleartext = self._decrypt()
else:
self.cleartext = ''
return self.cleartext
def write(self):
"""Encrypt cleartext and write into destination file file. ."""
if not self.write_lock:
raise RuntimeError("write() needs a write lock")
self._encrypt(self.cleartext)
def _lock(self):
self.lockfd = open(self.encrypted_filename, self.write_lock and "a+"
or "r+")
try:
fcntl.lockf(
self.lockfd, fcntl.LOCK_EX | fcntl.LOCK_NB |
(fcntl.LOCK_EX if self.write_lock else fcntl.LOCK_SH))
except BlockingIOError:
raise FileLockedError(self.encrypted_filename)
def _decrypt(self):
args = [self.gpg()]
if self.quiet:
args += ['-q', '--no-tty', '--batch']
args += ['--decrypt', self.encrypted_filename]
return subprocess.check_output(args, stderr=NULL).decode("utf-8")
def _encrypt(self, data):
if not self.recipients:
raise ValueError('Need at least one recipient.')
os.rename(self.encrypted_filename, self.encrypted_filename + ".old")
args = [self.gpg(), '--encrypt']
for r in self.recipients:
args.extend(['-r', r.strip()])
args.extend(['-o', self.encrypted_filename])
try:
gpg = subprocess.Popen(args, stdin=subprocess.PIPE)
gpg.communicate(data.encode("utf-8"))
if gpg.returncode != 0:
raise RuntimeError("GPG returned non-zero exit code.")
except Exception:
os.rename(self.encrypted_filename + ".old",
self.encrypted_filename)
raise
else:
os.unlink(self.encrypted_filename + ".old")
class EncryptedConfigFile(object):
"""Wrap encrypted config files.
Manages keys based on the data in the configuration. Also allows
management of additional files with the same keys.
"""
def __init__(self,
encrypted_file,
subfile_pattern=None,
write_lock=False,
quiet=False):
self.subfile_pattern = subfile_pattern
self.write_lock = write_lock
self.quiet = quiet
self.files = {}
self.main_file = self.add_file(encrypted_file)
# Add all existing files to the session
if self.subfile_pattern:
for other_filename in glob.iglob(self.subfile_pattern):
self.add_file(other_filename)
def add_file(self, filename):
if filename not in self.files:
self.files[filename] = f = EncryptedFile(filename, self.write_lock,
self.quiet)
f.read()
return self.files[filename]
def __enter__(self):
self.main_file.__enter__()
return self
def __exit__(self, _exc_type=None, _exc_value=None, _traceback=None):
self.main_file.__exit__()
def read(self):
self.main_file.read()
if not self.main_file.cleartext:
self.main_file.cleartext = NEW_FILE_TEMPLATE
self.config = ConfigUpdater()
self.config.read_string(self.main_file.cleartext)
self.set_members(self.get_members())
def write(self):
s = io.StringIO()
self.config.write(s)
self.main_file.cleartext = s.getvalue()
for file in self.files.values():
file.recipients = self.get_members()
file.write()
def get_members(self):
if 'batou' not in self.config:
self.config.add_section('batou')
try:
members = self.config.get("batou", "members").value.split(",")
except Exception:
return []
members = [x.strip() for x in members]
members = [_f for _f in members if _f]
members.sort()
return members
def set_members(self, members):
# The whitespace here is exactly what
# "members = " looks like in the config file so we get
# proper indentation.
members = ",\n ".join(members)
self.config.set("batou", "members", members) | en | 0.869548 | # https://thraxil.org/users/anders/posts/2008/03/13/Subprocess-Hanging-PIPE-is-your-enemy/ \ [batou] members = Basic encryption methods - key management handled externally. Context manager that opens an encrypted file. Use the read() and write() methods in the subordinate "with" block to manipulate cleartext content. If the cleartext content has been replaced, the encrypted file is updated. `write_lock` must be set True if a modification of the file is intended. Read encrypted data into cleartext - if not not read already. Encrypt cleartext and write into destination file file. . Wrap encrypted config files. Manages keys based on the data in the configuration. Also allows management of additional files with the same keys. # Add all existing files to the session # The whitespace here is exactly what # "members = " looks like in the config file so we get # proper indentation. | 2.618455 | 3 |
tests/app/billing/test_billing.py | cds-snc/notifier-api | 41 | 6627996 | <reponame>cds-snc/notifier-api
import json
from calendar import monthrange
from datetime import datetime, timedelta
import pytest
from freezegun import freeze_time
from app.billing.rest import update_free_sms_fragment_limit_data
from app.dao.annual_billing_dao import dao_get_free_sms_fragment_limit_for_year
from app.dao.date_util import (
get_current_financial_year_start_year,
get_month_start_and_end_date_in_utc,
)
from app.models import FactBilling
from tests import create_authorization_header
from tests.app.db import (
create_annual_billing,
create_ft_billing,
create_notification,
create_rate,
create_service,
create_template,
save_notification,
)
APR_2016_MONTH_START = datetime(2016, 3, 31, 23, 00, 00)
APR_2016_MONTH_END = datetime(2016, 4, 30, 22, 59, 59, 99999)
IN_MAY_2016 = datetime(2016, 5, 10, 23, 00, 00)
IN_JUN_2016 = datetime(2016, 6, 3, 23, 00, 00)
def _assert_dict_equals(actual, expected_dict):
assert actual == expected_dict
def test_create_update_free_sms_fragment_limit_invalid_schema(client, sample_service):
response = client.post(
"service/{}/billing/free-sms-fragment-limit".format(sample_service.id),
data={},
headers=[("Content-Type", "application/json"), create_authorization_header()],
)
json_resp = json.loads(response.get_data(as_text=True))
assert response.status_code == 400
assert "JSON" in json_resp["message"]
def test_create_free_sms_fragment_limit_current_year_updates_future_years(admin_request, sample_service):
current_year = get_current_financial_year_start_year()
future_billing = create_annual_billing(sample_service.id, 1, current_year + 1)
admin_request.post(
"billing.create_or_update_free_sms_fragment_limit",
service_id=sample_service.id,
_data={"free_sms_fragment_limit": 9999},
_expected_status=201,
)
current_billing = dao_get_free_sms_fragment_limit_for_year(sample_service.id, current_year)
assert future_billing.free_sms_fragment_limit == 9999
assert current_billing.financial_year_start == current_year
assert current_billing.free_sms_fragment_limit == 9999
@pytest.mark.parametrize("update_existing", [True, False])
def test_create_or_update_free_sms_fragment_limit_past_year_doenst_update_other_years(
admin_request, sample_service, update_existing
):
current_year = get_current_financial_year_start_year()
create_annual_billing(sample_service.id, 1, current_year)
if update_existing:
create_annual_billing(sample_service.id, 1, current_year - 1)
data = {"financial_year_start": current_year - 1, "free_sms_fragment_limit": 9999}
admin_request.post(
"billing.create_or_update_free_sms_fragment_limit",
service_id=sample_service.id,
_data=data,
_expected_status=201,
)
assert dao_get_free_sms_fragment_limit_for_year(sample_service.id, current_year - 1).free_sms_fragment_limit == 9999
assert dao_get_free_sms_fragment_limit_for_year(sample_service.id, current_year).free_sms_fragment_limit == 1
def test_create_free_sms_fragment_limit_updates_existing_year(admin_request, sample_service):
current_year = get_current_financial_year_start_year()
annual_billing = create_annual_billing(sample_service.id, 1, current_year)
admin_request.post(
"billing.create_or_update_free_sms_fragment_limit",
service_id=sample_service.id,
_data={"financial_year_start": current_year, "free_sms_fragment_limit": 2},
_expected_status=201,
)
assert annual_billing.free_sms_fragment_limit == 2
def test_get_free_sms_fragment_limit_current_year_creates_new_row(client, sample_service):
current_year = get_current_financial_year_start_year()
create_annual_billing(sample_service.id, 9999, current_year - 1)
response_get = client.get(
"service/{}/billing/free-sms-fragment-limit".format(sample_service.id),
headers=[("Content-Type", "application/json"), create_authorization_header()],
)
json_resp = json.loads(response_get.get_data(as_text=True))
assert response_get.status_code == 200
assert json_resp["financial_year_start"] == get_current_financial_year_start_year()
assert json_resp["free_sms_fragment_limit"] == 9999
def test_get_free_sms_fragment_limit_past_year_not_exist(client, sample_service):
current_year = get_current_financial_year_start_year()
create_annual_billing(sample_service.id, 9999, current_year - 1)
create_annual_billing(sample_service.id, 10000, current_year + 1)
annual_billing = dao_get_free_sms_fragment_limit_for_year(sample_service.id, current_year - 2)
assert annual_billing is None
res_get = client.get(
"service/{}/billing/free-sms-fragment-limit?financial_year_start={}".format(sample_service.id, current_year - 2),
headers=[("Content-Type", "application/json"), create_authorization_header()],
)
json_resp = json.loads(res_get.get_data(as_text=True))
assert res_get.status_code == 200
assert json_resp["financial_year_start"] == current_year - 1
assert json_resp["free_sms_fragment_limit"] == 9999
def test_get_free_sms_fragment_limit_future_year_not_exist(client, sample_service):
current_year = get_current_financial_year_start_year()
create_annual_billing(
sample_service.id,
free_sms_fragment_limit=9999,
financial_year_start=current_year - 1,
)
create_annual_billing(
sample_service.id,
free_sms_fragment_limit=10000,
financial_year_start=current_year + 1,
)
annual_billing = dao_get_free_sms_fragment_limit_for_year(sample_service.id, current_year + 2)
assert annual_billing is None
res_get = client.get(
"service/{}/billing/free-sms-fragment-limit?financial_year_start={}".format(sample_service.id, current_year + 2),
headers=[("Content-Type", "application/json"), create_authorization_header()],
)
json_resp = json.loads(res_get.get_data(as_text=True))
assert res_get.status_code == 200
assert json_resp["financial_year_start"] == current_year + 2
assert json_resp["free_sms_fragment_limit"] == 10000
def test_update_free_sms_fragment_limit_data(client, sample_service):
current_year = get_current_financial_year_start_year()
create_annual_billing(
sample_service.id,
free_sms_fragment_limit=250000,
financial_year_start=current_year - 1,
)
update_free_sms_fragment_limit_data(sample_service.id, 9999, current_year)
annual_billing = dao_get_free_sms_fragment_limit_for_year(sample_service.id, current_year)
assert annual_billing.free_sms_fragment_limit == 9999
@freeze_time("2018-04-21 14:00")
def test_get_yearly_usage_by_monthly_from_ft_billing_populates_deltas(client, notify_db_session):
service = create_service()
sms_template = create_template(service=service, template_type="sms")
create_rate(
start_date=datetime.utcnow() - timedelta(days=1),
value=0.158,
notification_type="sms",
)
save_notification(create_notification(template=sms_template, status="delivered"))
assert FactBilling.query.count() == 0
response = client.get(
"service/{}/billing/ft-monthly-usage?year=2018".format(service.id),
headers=[("Content-Type", "application/json"), create_authorization_header()],
)
assert response.status_code == 200
assert len(json.loads(response.get_data(as_text=True))) == 1
fact_billing = FactBilling.query.all()
assert len(fact_billing) == 1
assert fact_billing[0].notification_type == "sms"
def test_get_yearly_usage_by_monthly_from_ft_billing(client, notify_db_session):
service = create_service()
sms_template = create_template(service=service, template_type="sms")
email_template = create_template(service=service, template_type="email")
letter_template = create_template(service=service, template_type="letter")
for month in range(1, 13):
mon = str(month).zfill(2)
for day in range(1, monthrange(2016, month)[1] + 1):
d = str(day).zfill(2)
create_ft_billing(
utc_date="2016-{}-{}".format(mon, d),
service=service,
template=sms_template,
notification_type="sms",
billable_unit=1,
rate=0.162,
)
create_ft_billing(
utc_date="2016-{}-{}".format(mon, d),
service=service,
template=email_template,
notification_type="email",
rate=0,
)
create_ft_billing(
utc_date="2016-{}-{}".format(mon, d),
service=service,
template=letter_template,
notification_type="letter",
billable_unit=1,
rate=0.33,
postage="second",
)
response = client.get(
"service/{}/billing/ft-monthly-usage?year=2016".format(service.id),
headers=[("Content-Type", "application/json"), create_authorization_header()],
)
json_resp = json.loads(response.get_data(as_text=True))
ft_letters = [x for x in json_resp if x["notification_type"] == "letter"]
ft_sms = [x for x in json_resp if x["notification_type"] == "sms"]
ft_email = [x for x in json_resp if x["notification_type"] == "email"]
keys = [x.keys() for x in ft_sms][0]
expected_sms_april = {
"month": "April",
"notification_type": "sms",
"billing_units": 30,
"rate": 0.162,
"postage": "none",
}
expected_letter_april = {
"month": "April",
"notification_type": "letter",
"billing_units": 30,
"rate": 0.33,
"postage": "second",
}
for k in keys:
assert ft_sms[0][k] == expected_sms_april[k]
assert ft_letters[0][k] == expected_letter_april[k]
assert len(ft_email) == 0
def set_up_yearly_data():
service = create_service()
sms_template = create_template(service=service, template_type="sms")
email_template = create_template(service=service, template_type="email")
letter_template = create_template(service=service, template_type="letter")
for month in range(1, 13):
mon = str(month).zfill(2)
for day in range(1, monthrange(2016, month)[1] + 1):
d = str(day).zfill(2)
create_ft_billing(
utc_date="2016-{}-{}".format(mon, d),
service=service,
template=sms_template,
notification_type="sms",
rate=0.0162,
)
create_ft_billing(
utc_date="2016-{}-{}".format(mon, d),
service=service,
template=sms_template,
notification_type="sms",
rate_multiplier=2,
rate=0.0162,
)
create_ft_billing(
utc_date="2016-{}-{}".format(mon, d),
service=service,
template=email_template,
notification_type="email",
billable_unit=0,
rate=0,
)
create_ft_billing(
utc_date="2016-{}-{}".format(mon, d),
service=service,
template=letter_template,
notification_type="letter",
rate=0.33,
postage="second",
)
start_date, end_date = get_month_start_and_end_date_in_utc(datetime(2016, int(mon), 1))
return service
def test_get_yearly_billing_usage_summary_from_ft_billing_returns_400_if_missing_year(client, sample_service):
response = client.get(
"/service/{}/billing/ft-yearly-usage-summary".format(sample_service.id),
headers=[create_authorization_header()],
)
assert response.status_code == 400
assert json.loads(response.get_data(as_text=True)) == {
"message": "No valid year provided",
"result": "error",
}
def test_get_yearly_billing_usage_summary_from_ft_billing_returns_empty_list_if_no_billing_data(client, sample_service):
response = client.get(
"/service/{}/billing/ft-yearly-usage-summary?year=2016".format(sample_service.id),
headers=[create_authorization_header()],
)
assert response.status_code == 200
assert json.loads(response.get_data(as_text=True)) == []
def test_get_yearly_billing_usage_summary_from_ft_billing(client, notify_db_session):
service = set_up_yearly_data()
response = client.get(
"/service/{}/billing/ft-yearly-usage-summary?year=2016".format(service.id),
headers=[create_authorization_header()],
)
assert response.status_code == 200
json_response = json.loads(response.get_data(as_text=True))
assert len(json_response) == 3
assert json_response[0]["notification_type"] == "email"
assert json_response[0]["billing_units"] == 275
assert json_response[0]["rate"] == 0
assert json_response[0]["letter_total"] == 0
assert json_response[1]["notification_type"] == "letter"
assert json_response[1]["billing_units"] == 275
assert json_response[1]["rate"] == 0.33
assert json_response[1]["letter_total"] == 90.75
assert json_response[2]["notification_type"] == "sms"
assert json_response[2]["billing_units"] == 825
assert json_response[2]["rate"] == 0.0162
assert json_response[2]["letter_total"] == 0
def test_get_yearly_usage_by_monthly_from_ft_billing_all_cases(client, notify_db_session):
service = set_up_data_for_all_cases()
response = client.get(
"service/{}/billing/ft-monthly-usage?year=2018".format(service.id),
headers=[("Content-Type", "application/json"), create_authorization_header()],
)
assert response.status_code == 200
json_response = json.loads(response.get_data(as_text=True))
assert len(json_response) == 5
assert json_response[0]["month"] == "May"
assert json_response[0]["notification_type"] == "letter"
assert json_response[0]["rate"] == 0.33
assert json_response[0]["billing_units"] == 1
assert json_response[0]["postage"] == "second"
assert json_response[1]["month"] == "May"
assert json_response[1]["notification_type"] == "letter"
assert json_response[1]["rate"] == 0.36
assert json_response[1]["billing_units"] == 1
assert json_response[1]["postage"] == "second"
assert json_response[2]["month"] == "May"
assert json_response[2]["notification_type"] == "letter"
assert json_response[2]["rate"] == 0.39
assert json_response[2]["billing_units"] == 1
assert json_response[2]["postage"] == "first"
assert json_response[3]["month"] == "May"
assert json_response[3]["notification_type"] == "sms"
assert json_response[3]["rate"] == 0.0150
assert json_response[3]["billing_units"] == 4
assert json_response[3]["postage"] == "none"
assert json_response[4]["month"] == "May"
assert json_response[4]["notification_type"] == "sms"
assert json_response[4]["rate"] == 0.162
assert json_response[4]["billing_units"] == 5
assert json_response[4]["postage"] == "none"
def test_get_yearly_billing_usage_summary_from_ft_billing_all_cases(client, notify_db_session):
service = set_up_data_for_all_cases()
response = client.get(
"/service/{}/billing/ft-yearly-usage-summary?year=2018".format(service.id),
headers=[create_authorization_header()],
)
assert response.status_code == 200
json_response = json.loads(response.get_data(as_text=True))
assert len(json_response) == 6
assert json_response[0]["notification_type"] == "email"
assert json_response[0]["billing_units"] == 1
assert json_response[0]["rate"] == 0
assert json_response[0]["letter_total"] == 0
assert json_response[1]["notification_type"] == "letter"
assert json_response[1]["billing_units"] == 1
assert json_response[1]["rate"] == 0.33
assert json_response[1]["letter_total"] == 0.33
assert json_response[2]["notification_type"] == "letter"
assert json_response[2]["billing_units"] == 1
assert json_response[2]["rate"] == 0.36
assert json_response[2]["letter_total"] == 0.36
assert json_response[3]["notification_type"] == "letter"
assert json_response[3]["billing_units"] == 1
assert json_response[3]["rate"] == 0.39
assert json_response[3]["letter_total"] == 0.39
assert json_response[4]["notification_type"] == "sms"
assert json_response[4]["billing_units"] == 4
assert json_response[4]["rate"] == 0.0150
assert json_response[4]["letter_total"] == 0
assert json_response[5]["notification_type"] == "sms"
assert json_response[5]["billing_units"] == 5
assert json_response[5]["rate"] == 0.162
assert json_response[5]["letter_total"] == 0
def set_up_data_for_all_cases():
service = create_service()
sms_template = create_template(service=service, template_type="sms")
email_template = create_template(service=service, template_type="email")
letter_template = create_template(service=service, template_type="letter")
create_ft_billing(
utc_date="2018-05-16",
notification_type="sms",
template=sms_template,
service=service,
rate_multiplier=1,
international=False,
rate=0.162,
billable_unit=1,
notifications_sent=1,
)
create_ft_billing(
utc_date="2018-05-17",
notification_type="sms",
template=sms_template,
service=service,
rate_multiplier=2,
international=False,
rate=0.162,
billable_unit=2,
notifications_sent=1,
)
create_ft_billing(
utc_date="2018-05-16",
notification_type="sms",
template=sms_template,
service=service,
rate_multiplier=2,
international=False,
rate=0.0150,
billable_unit=2,
notifications_sent=1,
)
create_ft_billing(
utc_date="2018-05-16",
notification_type="email",
template=email_template,
service=service,
rate_multiplier=1,
international=False,
rate=0,
billable_unit=0,
notifications_sent=1,
)
create_ft_billing(
utc_date="2018-05-16",
notification_type="letter",
template=letter_template,
service=service,
rate_multiplier=1,
international=False,
rate=0.33,
billable_unit=1,
notifications_sent=1,
postage="second",
)
create_ft_billing(
utc_date="2018-05-17",
notification_type="letter",
template=letter_template,
service=service,
rate_multiplier=1,
international=False,
rate=0.36,
billable_unit=2,
notifications_sent=1,
postage="second",
)
create_ft_billing(
utc_date="2018-05-18",
notification_type="letter",
template=letter_template,
service=service,
rate_multiplier=1,
international=False,
rate=0.39,
billable_unit=3,
notifications_sent=1,
postage="first",
)
return service
| import json
from calendar import monthrange
from datetime import datetime, timedelta
import pytest
from freezegun import freeze_time
from app.billing.rest import update_free_sms_fragment_limit_data
from app.dao.annual_billing_dao import dao_get_free_sms_fragment_limit_for_year
from app.dao.date_util import (
get_current_financial_year_start_year,
get_month_start_and_end_date_in_utc,
)
from app.models import FactBilling
from tests import create_authorization_header
from tests.app.db import (
create_annual_billing,
create_ft_billing,
create_notification,
create_rate,
create_service,
create_template,
save_notification,
)
APR_2016_MONTH_START = datetime(2016, 3, 31, 23, 00, 00)
APR_2016_MONTH_END = datetime(2016, 4, 30, 22, 59, 59, 99999)
IN_MAY_2016 = datetime(2016, 5, 10, 23, 00, 00)
IN_JUN_2016 = datetime(2016, 6, 3, 23, 00, 00)
def _assert_dict_equals(actual, expected_dict):
assert actual == expected_dict
def test_create_update_free_sms_fragment_limit_invalid_schema(client, sample_service):
response = client.post(
"service/{}/billing/free-sms-fragment-limit".format(sample_service.id),
data={},
headers=[("Content-Type", "application/json"), create_authorization_header()],
)
json_resp = json.loads(response.get_data(as_text=True))
assert response.status_code == 400
assert "JSON" in json_resp["message"]
def test_create_free_sms_fragment_limit_current_year_updates_future_years(admin_request, sample_service):
current_year = get_current_financial_year_start_year()
future_billing = create_annual_billing(sample_service.id, 1, current_year + 1)
admin_request.post(
"billing.create_or_update_free_sms_fragment_limit",
service_id=sample_service.id,
_data={"free_sms_fragment_limit": 9999},
_expected_status=201,
)
current_billing = dao_get_free_sms_fragment_limit_for_year(sample_service.id, current_year)
assert future_billing.free_sms_fragment_limit == 9999
assert current_billing.financial_year_start == current_year
assert current_billing.free_sms_fragment_limit == 9999
@pytest.mark.parametrize("update_existing", [True, False])
def test_create_or_update_free_sms_fragment_limit_past_year_doenst_update_other_years(
admin_request, sample_service, update_existing
):
current_year = get_current_financial_year_start_year()
create_annual_billing(sample_service.id, 1, current_year)
if update_existing:
create_annual_billing(sample_service.id, 1, current_year - 1)
data = {"financial_year_start": current_year - 1, "free_sms_fragment_limit": 9999}
admin_request.post(
"billing.create_or_update_free_sms_fragment_limit",
service_id=sample_service.id,
_data=data,
_expected_status=201,
)
assert dao_get_free_sms_fragment_limit_for_year(sample_service.id, current_year - 1).free_sms_fragment_limit == 9999
assert dao_get_free_sms_fragment_limit_for_year(sample_service.id, current_year).free_sms_fragment_limit == 1
def test_create_free_sms_fragment_limit_updates_existing_year(admin_request, sample_service):
current_year = get_current_financial_year_start_year()
annual_billing = create_annual_billing(sample_service.id, 1, current_year)
admin_request.post(
"billing.create_or_update_free_sms_fragment_limit",
service_id=sample_service.id,
_data={"financial_year_start": current_year, "free_sms_fragment_limit": 2},
_expected_status=201,
)
assert annual_billing.free_sms_fragment_limit == 2
def test_get_free_sms_fragment_limit_current_year_creates_new_row(client, sample_service):
current_year = get_current_financial_year_start_year()
create_annual_billing(sample_service.id, 9999, current_year - 1)
response_get = client.get(
"service/{}/billing/free-sms-fragment-limit".format(sample_service.id),
headers=[("Content-Type", "application/json"), create_authorization_header()],
)
json_resp = json.loads(response_get.get_data(as_text=True))
assert response_get.status_code == 200
assert json_resp["financial_year_start"] == get_current_financial_year_start_year()
assert json_resp["free_sms_fragment_limit"] == 9999
def test_get_free_sms_fragment_limit_past_year_not_exist(client, sample_service):
current_year = get_current_financial_year_start_year()
create_annual_billing(sample_service.id, 9999, current_year - 1)
create_annual_billing(sample_service.id, 10000, current_year + 1)
annual_billing = dao_get_free_sms_fragment_limit_for_year(sample_service.id, current_year - 2)
assert annual_billing is None
res_get = client.get(
"service/{}/billing/free-sms-fragment-limit?financial_year_start={}".format(sample_service.id, current_year - 2),
headers=[("Content-Type", "application/json"), create_authorization_header()],
)
json_resp = json.loads(res_get.get_data(as_text=True))
assert res_get.status_code == 200
assert json_resp["financial_year_start"] == current_year - 1
assert json_resp["free_sms_fragment_limit"] == 9999
def test_get_free_sms_fragment_limit_future_year_not_exist(client, sample_service):
current_year = get_current_financial_year_start_year()
create_annual_billing(
sample_service.id,
free_sms_fragment_limit=9999,
financial_year_start=current_year - 1,
)
create_annual_billing(
sample_service.id,
free_sms_fragment_limit=10000,
financial_year_start=current_year + 1,
)
annual_billing = dao_get_free_sms_fragment_limit_for_year(sample_service.id, current_year + 2)
assert annual_billing is None
res_get = client.get(
"service/{}/billing/free-sms-fragment-limit?financial_year_start={}".format(sample_service.id, current_year + 2),
headers=[("Content-Type", "application/json"), create_authorization_header()],
)
json_resp = json.loads(res_get.get_data(as_text=True))
assert res_get.status_code == 200
assert json_resp["financial_year_start"] == current_year + 2
assert json_resp["free_sms_fragment_limit"] == 10000
def test_update_free_sms_fragment_limit_data(client, sample_service):
current_year = get_current_financial_year_start_year()
create_annual_billing(
sample_service.id,
free_sms_fragment_limit=250000,
financial_year_start=current_year - 1,
)
update_free_sms_fragment_limit_data(sample_service.id, 9999, current_year)
annual_billing = dao_get_free_sms_fragment_limit_for_year(sample_service.id, current_year)
assert annual_billing.free_sms_fragment_limit == 9999
@freeze_time("2018-04-21 14:00")
def test_get_yearly_usage_by_monthly_from_ft_billing_populates_deltas(client, notify_db_session):
service = create_service()
sms_template = create_template(service=service, template_type="sms")
create_rate(
start_date=datetime.utcnow() - timedelta(days=1),
value=0.158,
notification_type="sms",
)
save_notification(create_notification(template=sms_template, status="delivered"))
assert FactBilling.query.count() == 0
response = client.get(
"service/{}/billing/ft-monthly-usage?year=2018".format(service.id),
headers=[("Content-Type", "application/json"), create_authorization_header()],
)
assert response.status_code == 200
assert len(json.loads(response.get_data(as_text=True))) == 1
fact_billing = FactBilling.query.all()
assert len(fact_billing) == 1
assert fact_billing[0].notification_type == "sms"
def test_get_yearly_usage_by_monthly_from_ft_billing(client, notify_db_session):
service = create_service()
sms_template = create_template(service=service, template_type="sms")
email_template = create_template(service=service, template_type="email")
letter_template = create_template(service=service, template_type="letter")
for month in range(1, 13):
mon = str(month).zfill(2)
for day in range(1, monthrange(2016, month)[1] + 1):
d = str(day).zfill(2)
create_ft_billing(
utc_date="2016-{}-{}".format(mon, d),
service=service,
template=sms_template,
notification_type="sms",
billable_unit=1,
rate=0.162,
)
create_ft_billing(
utc_date="2016-{}-{}".format(mon, d),
service=service,
template=email_template,
notification_type="email",
rate=0,
)
create_ft_billing(
utc_date="2016-{}-{}".format(mon, d),
service=service,
template=letter_template,
notification_type="letter",
billable_unit=1,
rate=0.33,
postage="second",
)
response = client.get(
"service/{}/billing/ft-monthly-usage?year=2016".format(service.id),
headers=[("Content-Type", "application/json"), create_authorization_header()],
)
json_resp = json.loads(response.get_data(as_text=True))
ft_letters = [x for x in json_resp if x["notification_type"] == "letter"]
ft_sms = [x for x in json_resp if x["notification_type"] == "sms"]
ft_email = [x for x in json_resp if x["notification_type"] == "email"]
keys = [x.keys() for x in ft_sms][0]
expected_sms_april = {
"month": "April",
"notification_type": "sms",
"billing_units": 30,
"rate": 0.162,
"postage": "none",
}
expected_letter_april = {
"month": "April",
"notification_type": "letter",
"billing_units": 30,
"rate": 0.33,
"postage": "second",
}
for k in keys:
assert ft_sms[0][k] == expected_sms_april[k]
assert ft_letters[0][k] == expected_letter_april[k]
assert len(ft_email) == 0
def set_up_yearly_data():
service = create_service()
sms_template = create_template(service=service, template_type="sms")
email_template = create_template(service=service, template_type="email")
letter_template = create_template(service=service, template_type="letter")
for month in range(1, 13):
mon = str(month).zfill(2)
for day in range(1, monthrange(2016, month)[1] + 1):
d = str(day).zfill(2)
create_ft_billing(
utc_date="2016-{}-{}".format(mon, d),
service=service,
template=sms_template,
notification_type="sms",
rate=0.0162,
)
create_ft_billing(
utc_date="2016-{}-{}".format(mon, d),
service=service,
template=sms_template,
notification_type="sms",
rate_multiplier=2,
rate=0.0162,
)
create_ft_billing(
utc_date="2016-{}-{}".format(mon, d),
service=service,
template=email_template,
notification_type="email",
billable_unit=0,
rate=0,
)
create_ft_billing(
utc_date="2016-{}-{}".format(mon, d),
service=service,
template=letter_template,
notification_type="letter",
rate=0.33,
postage="second",
)
start_date, end_date = get_month_start_and_end_date_in_utc(datetime(2016, int(mon), 1))
return service
def test_get_yearly_billing_usage_summary_from_ft_billing_returns_400_if_missing_year(client, sample_service):
response = client.get(
"/service/{}/billing/ft-yearly-usage-summary".format(sample_service.id),
headers=[create_authorization_header()],
)
assert response.status_code == 400
assert json.loads(response.get_data(as_text=True)) == {
"message": "No valid year provided",
"result": "error",
}
def test_get_yearly_billing_usage_summary_from_ft_billing_returns_empty_list_if_no_billing_data(client, sample_service):
response = client.get(
"/service/{}/billing/ft-yearly-usage-summary?year=2016".format(sample_service.id),
headers=[create_authorization_header()],
)
assert response.status_code == 200
assert json.loads(response.get_data(as_text=True)) == []
def test_get_yearly_billing_usage_summary_from_ft_billing(client, notify_db_session):
service = set_up_yearly_data()
response = client.get(
"/service/{}/billing/ft-yearly-usage-summary?year=2016".format(service.id),
headers=[create_authorization_header()],
)
assert response.status_code == 200
json_response = json.loads(response.get_data(as_text=True))
assert len(json_response) == 3
assert json_response[0]["notification_type"] == "email"
assert json_response[0]["billing_units"] == 275
assert json_response[0]["rate"] == 0
assert json_response[0]["letter_total"] == 0
assert json_response[1]["notification_type"] == "letter"
assert json_response[1]["billing_units"] == 275
assert json_response[1]["rate"] == 0.33
assert json_response[1]["letter_total"] == 90.75
assert json_response[2]["notification_type"] == "sms"
assert json_response[2]["billing_units"] == 825
assert json_response[2]["rate"] == 0.0162
assert json_response[2]["letter_total"] == 0
def test_get_yearly_usage_by_monthly_from_ft_billing_all_cases(client, notify_db_session):
service = set_up_data_for_all_cases()
response = client.get(
"service/{}/billing/ft-monthly-usage?year=2018".format(service.id),
headers=[("Content-Type", "application/json"), create_authorization_header()],
)
assert response.status_code == 200
json_response = json.loads(response.get_data(as_text=True))
assert len(json_response) == 5
assert json_response[0]["month"] == "May"
assert json_response[0]["notification_type"] == "letter"
assert json_response[0]["rate"] == 0.33
assert json_response[0]["billing_units"] == 1
assert json_response[0]["postage"] == "second"
assert json_response[1]["month"] == "May"
assert json_response[1]["notification_type"] == "letter"
assert json_response[1]["rate"] == 0.36
assert json_response[1]["billing_units"] == 1
assert json_response[1]["postage"] == "second"
assert json_response[2]["month"] == "May"
assert json_response[2]["notification_type"] == "letter"
assert json_response[2]["rate"] == 0.39
assert json_response[2]["billing_units"] == 1
assert json_response[2]["postage"] == "first"
assert json_response[3]["month"] == "May"
assert json_response[3]["notification_type"] == "sms"
assert json_response[3]["rate"] == 0.0150
assert json_response[3]["billing_units"] == 4
assert json_response[3]["postage"] == "none"
assert json_response[4]["month"] == "May"
assert json_response[4]["notification_type"] == "sms"
assert json_response[4]["rate"] == 0.162
assert json_response[4]["billing_units"] == 5
assert json_response[4]["postage"] == "none"
def test_get_yearly_billing_usage_summary_from_ft_billing_all_cases(client, notify_db_session):
service = set_up_data_for_all_cases()
response = client.get(
"/service/{}/billing/ft-yearly-usage-summary?year=2018".format(service.id),
headers=[create_authorization_header()],
)
assert response.status_code == 200
json_response = json.loads(response.get_data(as_text=True))
assert len(json_response) == 6
assert json_response[0]["notification_type"] == "email"
assert json_response[0]["billing_units"] == 1
assert json_response[0]["rate"] == 0
assert json_response[0]["letter_total"] == 0
assert json_response[1]["notification_type"] == "letter"
assert json_response[1]["billing_units"] == 1
assert json_response[1]["rate"] == 0.33
assert json_response[1]["letter_total"] == 0.33
assert json_response[2]["notification_type"] == "letter"
assert json_response[2]["billing_units"] == 1
assert json_response[2]["rate"] == 0.36
assert json_response[2]["letter_total"] == 0.36
assert json_response[3]["notification_type"] == "letter"
assert json_response[3]["billing_units"] == 1
assert json_response[3]["rate"] == 0.39
assert json_response[3]["letter_total"] == 0.39
assert json_response[4]["notification_type"] == "sms"
assert json_response[4]["billing_units"] == 4
assert json_response[4]["rate"] == 0.0150
assert json_response[4]["letter_total"] == 0
assert json_response[5]["notification_type"] == "sms"
assert json_response[5]["billing_units"] == 5
assert json_response[5]["rate"] == 0.162
assert json_response[5]["letter_total"] == 0
def set_up_data_for_all_cases():
service = create_service()
sms_template = create_template(service=service, template_type="sms")
email_template = create_template(service=service, template_type="email")
letter_template = create_template(service=service, template_type="letter")
create_ft_billing(
utc_date="2018-05-16",
notification_type="sms",
template=sms_template,
service=service,
rate_multiplier=1,
international=False,
rate=0.162,
billable_unit=1,
notifications_sent=1,
)
create_ft_billing(
utc_date="2018-05-17",
notification_type="sms",
template=sms_template,
service=service,
rate_multiplier=2,
international=False,
rate=0.162,
billable_unit=2,
notifications_sent=1,
)
create_ft_billing(
utc_date="2018-05-16",
notification_type="sms",
template=sms_template,
service=service,
rate_multiplier=2,
international=False,
rate=0.0150,
billable_unit=2,
notifications_sent=1,
)
create_ft_billing(
utc_date="2018-05-16",
notification_type="email",
template=email_template,
service=service,
rate_multiplier=1,
international=False,
rate=0,
billable_unit=0,
notifications_sent=1,
)
create_ft_billing(
utc_date="2018-05-16",
notification_type="letter",
template=letter_template,
service=service,
rate_multiplier=1,
international=False,
rate=0.33,
billable_unit=1,
notifications_sent=1,
postage="second",
)
create_ft_billing(
utc_date="2018-05-17",
notification_type="letter",
template=letter_template,
service=service,
rate_multiplier=1,
international=False,
rate=0.36,
billable_unit=2,
notifications_sent=1,
postage="second",
)
create_ft_billing(
utc_date="2018-05-18",
notification_type="letter",
template=letter_template,
service=service,
rate_multiplier=1,
international=False,
rate=0.39,
billable_unit=3,
notifications_sent=1,
postage="first",
)
return service | none | 1 | 2.058361 | 2 | |
problems/ploppers2/executable.py | ShadowWei/Ytopt_fall19 | 0 | 6627997 | #!/usr/bin/env python
from __future__ import print_function
import re
import os
import sys
import time
import json
import math
import os
import argparse
import numpy as np
sys.path.insert(0, '/uufs/chpc.utah.edu/common/home/u1074259/ytopt/plopper')
from plopper import Plopper
from numpy import abs, cos, exp, mean, pi, prod, sin, sqrt, sum
seed = 12345
def create_parser():
'command line parser'
parser = argparse.ArgumentParser(add_help=True)
group = parser.add_argument_group('required arguments')
for id in range(0, 14):
parser.add_argument('--p%d'%id, action='store', dest='p%d'%id,
nargs='?', const=13, type=str, default='a',
help='parameter p%d value'%id)
return(parser)
parser = create_parser()
cmdline_args = parser.parse_args()
param_dict = vars(cmdline_args)
p0 = param_dict['p0'] #p0_dict
p1 = param_dict['p1'] #p1_dict
p2 = param_dict['p2'] #p2_dict
p3 = param_dict['p3'] #PF_dict
p4 = param_dict['p4'] #SI_dict
p5 = param_dict['p5'] #SC_dict
p6 = param_dict['p6'] #NT_dict
p7 = param_dict['p7'] #CO_dict
p8 = param_dict['p8'] #TL_dict
p9 = param_dict['p9'] #static or dynamic
p10 = param_dict['p10'] #1, 8, 16 Chunk Size?
p11 = param_dict['p11'] #1, 2, 4, 8, 14, 16, 28 NT?
p12 = param_dict['p12'] #1, 2, 3 Collapse
p13 = param_dict['p13'] #32, 64, 128, 256 thread limit?
x=[p0,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12,p13]
p0_dict = {'a': "None", 'b': "#pragma omp #p3", 'c': "#pragma omp target teams distribute #p #p"} #p0
p1_dict = {'a': "None", 'b': "#pragma omp #p3", 'c': "#pragma omp target teams distribute #p #p"} #p1
p2_dict = {'a': "None", 'b': "#pragma omp #p3", 'c': "#pragma omp target teams distribute #p #p"} #p2
PF_dict = {'a': "None", 'b': "parallel for #p4 #p5 #p6"} #p3
SI_dict = {'a': "None", 'b': "simd"} #p4
SC_dict = {'a': "None", 'b': "schedule(#p9, #p11)"} #p5
NT_dict = {'a': "None", 'b': "num_threads(#p11)"} #p6
CO_dict = {'a': "None", 'b': "collapse(#p12)"} #p7
TL_dict = {'a': "None", 'b': "thread_limit(#p13)"} #p8
#SI_dict = {'a': "None", 'b': "simd"} #p
#p0_dict = {'a': "None", 'b': "#pragma omp parallel for schedule(#p3, #p4) num_threads(#p5)", 'c': "#pragma omp parallel for schedule(#p3, #p4) collapse(#p6) num_threads(#p5)", 'd': "#pragma omp target teams distribute"}
#p1_dict = {'a': "None", 'b': "#pragma omp parallel for schedule(#p3, #p4) num_threads(#p5)", 'c': "#pragma omp parallel for schedule(#p3, #p4) collapse(#p6) num_threads(#p5)"}
#p2_dict = {'a': "None", 'b': "#pragma omp parallel for schedule(#p3, #p4) num_threads(#p5)", 'c': "#pragma omp simd"}
#p3_dict = {'a': "static", 'b': "dynamic"}
#p4_dict = {'a': "1", 'b': "8", 'c': "16"}
#p5_dict = {'a': "1", 'b': "2", 'c': "4", 'd': "8", 'e': "14", 'f': "16", 'g': "28"}
#p6_dict = {'a': "1", 'b': "2", 'c': "3"}
obj = Plopper()
def plopper_func(x):
#value = [p0_dict[x[0]], p1_dict[x[1]], p2_dict[x[2]], p3, p4, p5, p6, p7, PF_dict[x[8]], SI_dict[x[9]], SC_dict[x[10]], NT_dict[x[11]], CO_dict[x[12]], TL_dict[x[13]]]
value = [p0_dict[x[0]], p1_dict[x[1]], p2_dict[x[2]], PF_dict[x[3]], SC_dict[x[4]], SI_dict[x[5]], NT_dict[x[6]], CO_dict[x[7]], TL_dict[x[8]], p9, p10, p11, p12, p13]
params = ["LOOP1", "LOOP2", "LOOP3", "p3", "p4", "p5", "p6", "p7", "p8", "p9", "p10", "p11", "p12", "p13"]
result = obj.findRuntime(value, params)
return result
pval = plopper_func(x)
print('OUTPUT:%1.3f'%pval)
| #!/usr/bin/env python
from __future__ import print_function
import re
import os
import sys
import time
import json
import math
import os
import argparse
import numpy as np
sys.path.insert(0, '/uufs/chpc.utah.edu/common/home/u1074259/ytopt/plopper')
from plopper import Plopper
from numpy import abs, cos, exp, mean, pi, prod, sin, sqrt, sum
seed = 12345
def create_parser():
'command line parser'
parser = argparse.ArgumentParser(add_help=True)
group = parser.add_argument_group('required arguments')
for id in range(0, 14):
parser.add_argument('--p%d'%id, action='store', dest='p%d'%id,
nargs='?', const=13, type=str, default='a',
help='parameter p%d value'%id)
return(parser)
parser = create_parser()
cmdline_args = parser.parse_args()
param_dict = vars(cmdline_args)
p0 = param_dict['p0'] #p0_dict
p1 = param_dict['p1'] #p1_dict
p2 = param_dict['p2'] #p2_dict
p3 = param_dict['p3'] #PF_dict
p4 = param_dict['p4'] #SI_dict
p5 = param_dict['p5'] #SC_dict
p6 = param_dict['p6'] #NT_dict
p7 = param_dict['p7'] #CO_dict
p8 = param_dict['p8'] #TL_dict
p9 = param_dict['p9'] #static or dynamic
p10 = param_dict['p10'] #1, 8, 16 Chunk Size?
p11 = param_dict['p11'] #1, 2, 4, 8, 14, 16, 28 NT?
p12 = param_dict['p12'] #1, 2, 3 Collapse
p13 = param_dict['p13'] #32, 64, 128, 256 thread limit?
x=[p0,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12,p13]
p0_dict = {'a': "None", 'b': "#pragma omp #p3", 'c': "#pragma omp target teams distribute #p #p"} #p0
p1_dict = {'a': "None", 'b': "#pragma omp #p3", 'c': "#pragma omp target teams distribute #p #p"} #p1
p2_dict = {'a': "None", 'b': "#pragma omp #p3", 'c': "#pragma omp target teams distribute #p #p"} #p2
PF_dict = {'a': "None", 'b': "parallel for #p4 #p5 #p6"} #p3
SI_dict = {'a': "None", 'b': "simd"} #p4
SC_dict = {'a': "None", 'b': "schedule(#p9, #p11)"} #p5
NT_dict = {'a': "None", 'b': "num_threads(#p11)"} #p6
CO_dict = {'a': "None", 'b': "collapse(#p12)"} #p7
TL_dict = {'a': "None", 'b': "thread_limit(#p13)"} #p8
#SI_dict = {'a': "None", 'b': "simd"} #p
#p0_dict = {'a': "None", 'b': "#pragma omp parallel for schedule(#p3, #p4) num_threads(#p5)", 'c': "#pragma omp parallel for schedule(#p3, #p4) collapse(#p6) num_threads(#p5)", 'd': "#pragma omp target teams distribute"}
#p1_dict = {'a': "None", 'b': "#pragma omp parallel for schedule(#p3, #p4) num_threads(#p5)", 'c': "#pragma omp parallel for schedule(#p3, #p4) collapse(#p6) num_threads(#p5)"}
#p2_dict = {'a': "None", 'b': "#pragma omp parallel for schedule(#p3, #p4) num_threads(#p5)", 'c': "#pragma omp simd"}
#p3_dict = {'a': "static", 'b': "dynamic"}
#p4_dict = {'a': "1", 'b': "8", 'c': "16"}
#p5_dict = {'a': "1", 'b': "2", 'c': "4", 'd': "8", 'e': "14", 'f': "16", 'g': "28"}
#p6_dict = {'a': "1", 'b': "2", 'c': "3"}
obj = Plopper()
def plopper_func(x):
#value = [p0_dict[x[0]], p1_dict[x[1]], p2_dict[x[2]], p3, p4, p5, p6, p7, PF_dict[x[8]], SI_dict[x[9]], SC_dict[x[10]], NT_dict[x[11]], CO_dict[x[12]], TL_dict[x[13]]]
value = [p0_dict[x[0]], p1_dict[x[1]], p2_dict[x[2]], PF_dict[x[3]], SC_dict[x[4]], SI_dict[x[5]], NT_dict[x[6]], CO_dict[x[7]], TL_dict[x[8]], p9, p10, p11, p12, p13]
params = ["LOOP1", "LOOP2", "LOOP3", "p3", "p4", "p5", "p6", "p7", "p8", "p9", "p10", "p11", "p12", "p13"]
result = obj.findRuntime(value, params)
return result
pval = plopper_func(x)
print('OUTPUT:%1.3f'%pval)
| en | 0.283882 | #!/usr/bin/env python #p0_dict #p1_dict #p2_dict #PF_dict #SI_dict #SC_dict #NT_dict #CO_dict #TL_dict #static or dynamic #1, 8, 16 Chunk Size? #1, 2, 4, 8, 14, 16, 28 NT? #1, 2, 3 Collapse #32, 64, 128, 256 thread limit? #p3", 'c': "#pragma omp target teams distribute #p #p"} #p0 #p3", 'c': "#pragma omp target teams distribute #p #p"} #p1 #p3", 'c': "#pragma omp target teams distribute #p #p"} #p2 #p4 #p5 #p6"} #p3 #p4 #p9, #p11)"} #p5 #p11)"} #p6 #p12)"} #p7 #p13)"} #p8 #SI_dict = {'a': "None", 'b': "simd"} #p #p0_dict = {'a': "None", 'b': "#pragma omp parallel for schedule(#p3, #p4) num_threads(#p5)", 'c': "#pragma omp parallel for schedule(#p3, #p4) collapse(#p6) num_threads(#p5)", 'd': "#pragma omp target teams distribute"} #p1_dict = {'a': "None", 'b': "#pragma omp parallel for schedule(#p3, #p4) num_threads(#p5)", 'c': "#pragma omp parallel for schedule(#p3, #p4) collapse(#p6) num_threads(#p5)"} #p2_dict = {'a': "None", 'b': "#pragma omp parallel for schedule(#p3, #p4) num_threads(#p5)", 'c': "#pragma omp simd"} #p3_dict = {'a': "static", 'b': "dynamic"} #p4_dict = {'a': "1", 'b': "8", 'c': "16"} #p5_dict = {'a': "1", 'b': "2", 'c': "4", 'd': "8", 'e': "14", 'f': "16", 'g': "28"} #p6_dict = {'a': "1", 'b': "2", 'c': "3"} #value = [p0_dict[x[0]], p1_dict[x[1]], p2_dict[x[2]], p3, p4, p5, p6, p7, PF_dict[x[8]], SI_dict[x[9]], SC_dict[x[10]], NT_dict[x[11]], CO_dict[x[12]], TL_dict[x[13]]] | 2.351671 | 2 |
swift_undelete/tests/test_middleware.py | alexalv/swift_undelete | 0 | 6627998 | <filename>swift_undelete/tests/test_middleware.py
#!/usr/bin/env python
# Copyright (c) 2014 SwiftStack, Inc.
#
# 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 unittest
from swift.common import swob
from swift_undelete import middleware as md
class FakeApp(object):
def __init__(self):
self.responses = [] # fill in later
self._calls = []
def __call__(self, env, start_response):
req = swob.Request(env)
self._calls.append((
req.method, req.path,
# mutable dict; keep a copy so subsequent calls can't change it
swob.HeaderKeyDict(req.headers)))
if len(self.responses) > 1:
resp = self.responses.pop(0)
else:
resp = self.responses[0]
status = resp['status']
headers = resp.get('headers', [])
body_iter = resp.get('body_iter', [])
start_response(status, headers)
return body_iter
@property
def calls(self):
"""
Returns the calls received by this application as a list of
(method, path) pairs.
"""
return [x[:2] for x in self._calls]
@property
def call_headers(self):
"""
Returns the list of headers received by this application as it was
called
"""
return [x[2] for x in self._calls]
@property
def calls_with_headers(self):
"""
Returns the calls received by this application as a list of
(method, path, headers) tuples.
"""
return self._calls
class TestConfigParsing(unittest.TestCase):
def test_defaults(self):
app = FakeApp()
undelete = md.filter_factory({})(app)
self.assertEqual(undelete.trash_prefix, ".trash-")
self.assertEqual(undelete.trash_lifetime, 86400 * 90)
self.assertFalse(undelete.block_trash_deletes)
def test_non_defaults(self):
app = FakeApp()
undelete = md.filter_factory({
'trash_prefix': '.heap__',
'trash_lifetime': '31536000',
'block_trash_deletes': 'on',
})(app)
self.assertEqual(undelete.trash_prefix, ".heap__")
self.assertEqual(undelete.trash_lifetime, 31536000)
self.assertTrue(undelete.block_trash_deletes)
class MiddlewareTestCase(unittest.TestCase):
"""
Just a base class for other test cases. Some setup, some utility methods.
Nothing too exciting.
"""
def setUp(self):
self.app = FakeApp()
self.undelete = md.filter_factory({})(self.app)
def call_mware(self, req, expect_exception=False):
status = [None]
headers = [None]
def start_response(s, h, ei=None):
status[0] = s
headers[0] = h
body_iter = self.undelete(req.environ, start_response)
body = ''
caught_exc = None
try:
for chunk in body_iter:
body += chunk
except Exception as exc:
if expect_exception:
caught_exc = exc
else:
raise
headerdict = swob.HeaderKeyDict(headers[0])
if expect_exception:
return status[0], headerdict, body, caught_exc
else:
return status[0], headerdict, body
class TestPassthrough(MiddlewareTestCase):
def test_account_passthrough(self):
"""
Account requests are passed through unmodified.
"""
self.app.responses = [{'status': '200 OK'}]
req = swob.Request.blank('/v1/a')
req.method = 'DELETE'
status, _, _ = self.call_mware(req)
self.assertEqual(status, "200 OK")
self.assertEqual(self.app.calls, [('DELETE', '/v1/a')])
def test_container_passthrough(self):
"""
Container requests are passed through unmodified.
"""
self.app.responses = [{'status': '200 OK'}]
req = swob.Request.blank('/v1/a/c')
req.method = 'DELETE'
status, _, _ = self.call_mware(req)
self.assertEqual(status, "200 OK")
self.assertEqual(self.app.calls, [('DELETE', '/v1/a/c')])
class TestObjectDeletion(MiddlewareTestCase):
def test_deleting_nonexistent_object(self):
# If the object isn't there, ignore the 404 on COPY and pass the
# DELETE request through. It might be an expired object, in which case
# the object DELETE will actually get it out of the container listing
# and free up some space.
self.app.responses = [
# COPY request
{'status': '404 Not Found'},
# trash-versions container creation request
#
# Ideally we'd skip this stuff, but we can't tell the difference
# between object-not-found (404) and
# destination-container-not-found (also 404).
{'status': '202 Accepted'},
# trash container creation request
{'status': '202 Accepted'},
# second COPY attempt:
{'status': '404 Not Found'},
# DELETE request
{'status': '404 Not Found',
'headers': [('X-Exophagous', 'ungrassed')]}]
req = swob.Request.blank('/v1/a/elements/Cf')
req.method = 'DELETE'
status, headers, body = self.call_mware(req)
self.assertEqual(status, "404 Not Found")
self.assertEqual(headers.get('X-Exophagous'), 'ungrassed')
self.assertEqual(self.app.calls,
[('COPY', '/v1/a/elements/Cf'),
('PUT', '/v1/a/.trash-elements-versions'),
('PUT', '/v1/a/.trash-elements'),
('COPY', '/v1/a/elements/Cf'),
('DELETE', '/v1/a/elements/Cf')])
def test_copy_to_existing_trash_container(self):
self.undelete.trash_lifetime = 1997339
self.app.responses = [
# COPY request
{'status': '201 Created',
'headers': [('X-Sir-Not-Appearing-In-This-Response', 'yup')]},
# DELETE request
{'status': '204 No Content',
'headers': [('X-Decadation', 'coprose')]}]
req = swob.Request.blank('/v1/MY_account/cats/kittens.jpg')
req.method = 'DELETE'
status, headers, body = self.call_mware(req)
self.assertEqual(status, "204 No Content")
# the client gets whatever the DELETE coughed up
self.assertNotIn('X-Sir-Not-Appearing-In-This-Response', headers)
self.assertEqual(headers['X-Decadation'], 'coprose')
self.assertEqual(2, len(self.app.calls))
# First, we performed a COPY request to save the object into the trash.
method, path, headers = self.app.calls_with_headers[0]
self.assertEqual(method, 'COPY')
self.assertEqual(path, '/v1/MY_account/cats/kittens.jpg')
self.assertEqual(headers['Destination'], '.trash-cats/kittens.jpg')
self.assertEqual(headers['X-Delete-After'], str(1997339))
# Second, we actually perform the DELETE request (and send that
# response to the client unaltered)
method, path, headers = self.app.calls_with_headers[1]
self.assertEqual(method, 'DELETE')
self.assertEqual(path, '/v1/MY_account/cats/kittens.jpg')
def test_copy_to_existing_trash_container_no_expiration(self):
self.undelete.trash_lifetime = 0
self.app.responses = [
# COPY request
{'status': '201 Created'},
# DELETE request
{'status': '204 No Content'}]
req = swob.Request.blank('/v1/MY_account/cats/kittens.jpg')
req.method = 'DELETE'
status, headers, body = self.call_mware(req)
self.assertEqual(status, "204 No Content")
self.assertEqual(2, len(self.app.calls))
method, path, headers = self.app.calls_with_headers[0]
self.assertEqual(method, 'COPY')
self.assertEqual(path, '/v1/MY_account/cats/kittens.jpg')
self.assertNotIn('X-Delete-After', headers)
def test_copy_to_missing_trash_container(self):
self.app.responses = [
# first COPY attempt: trash container doesn't exist
{'status': '404 Not Found'},
# trash-versions container creation request
{'status': '201 Created'},
# trash container creation request
{'status': '201 Created'},
# second COPY attempt:
{'status': '404 Not Found'},
# DELETE request
{'status': '204 No Content'}]
req = swob.Request.blank('/v1/a/elements/Lv')
req.method = 'DELETE'
status, headers, body = self.call_mware(req)
self.assertEqual(status, "204 No Content")
self.assertEqual(self.app.calls,
[('COPY', '/v1/a/elements/Lv'),
('PUT', '/v1/a/.trash-elements-versions'),
('PUT', '/v1/a/.trash-elements'),
('COPY', '/v1/a/elements/Lv'),
('DELETE', '/v1/a/elements/Lv')])
def test_copy_error(self):
self.app.responses = [
# COPY attempt: some mysterious error with some headers
{'status': '503 Service Unavailable',
'headers': [('X-Scraggedness', 'Goclenian')],
'body_iter': ['dunno what happened boss']}]
req = swob.Request.blank('/v1/a/elements/Te')
req.method = 'DELETE'
status, headers, body = self.call_mware(req)
self.assertEqual(status, "503 Service Unavailable")
self.assertEqual(headers.get('X-Scraggedness'), 'Goclenian')
self.assertIn('what happened', body)
self.assertEqual(self.app.calls, [('COPY', '/v1/a/elements/Te')])
def test_copy_missing_trash_container_error_creating_vrs_container(self):
self.app.responses = [
# first COPY attempt: trash container doesn't exist
{'status': '404 Not Found'},
# trash-versions container creation request: failure!
{'status': '403 Forbidden',
'headers': [('X-Pupillidae', 'Barry')],
'body_iter': ['oh hell no']}]
req = swob.Request.blank('/v1/a/elements/U')
req.method = 'DELETE'
status, headers, body = self.call_mware(req)
self.assertEqual(status, "403 Forbidden")
self.assertEqual(headers.get('X-Pupillidae'), 'Barry')
self.assertIn('oh hell no', body)
self.assertEqual(self.app.calls,
[('COPY', '/v1/a/elements/U'),
('PUT', '/v1/a/.trash-elements-versions')])
def test_copy_missing_trash_container_error_creating_container(self):
self.app.responses = [
# first COPY attempt: trash container doesn't exist
{'status': '404 Not Found'},
# trash-versions container creation request
{'status': '201 Created'},
# trash container creation request: fails!
{'status': "418 I'm a teapot",
'headers': [('X-Body-Type', 'short and stout')],
'body_iter': ['here is my handle, here is my spout']}]
req = swob.Request.blank('/v1/a/elements/Mo')
req.method = 'DELETE'
status, headers, body = self.call_mware(req)
self.assertEqual(status, "418 I'm a teapot")
self.assertEqual(headers.get('X-Body-Type'), 'short and stout')
self.assertIn('spout', body)
self.assertEqual(self.app.calls,
[('COPY', '/v1/a/elements/Mo'),
('PUT', '/v1/a/.trash-elements-versions'),
('PUT', '/v1/a/.trash-elements')])
def test_delete_from_trash(self):
"""
Objects in trash containers don't get saved.
"""
self.app.responses = [{'status': '204 No Content'}]
req = swob.Request.blank('/v1/a/.trash-borkbork/bork')
req.method = 'DELETE'
status, headers, body = self.call_mware(req)
self.assertEqual(status, "204 No Content")
self.assertEqual(self.app.calls,
[('DELETE', '/v1/a/.trash-borkbork/bork')])
def test_delete_from_trash_blocked(self):
self.undelete.block_trash_deletes = True
req = swob.Request.blank('/v1/a/.trash-borkbork/bork')
req.method = 'DELETE'
status, headers, body = self.call_mware(req)
self.assertEqual(status, "405 Method Not Allowed")
self.assertEqual(self.app.calls, [])
| <filename>swift_undelete/tests/test_middleware.py
#!/usr/bin/env python
# Copyright (c) 2014 SwiftStack, Inc.
#
# 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 unittest
from swift.common import swob
from swift_undelete import middleware as md
class FakeApp(object):
def __init__(self):
self.responses = [] # fill in later
self._calls = []
def __call__(self, env, start_response):
req = swob.Request(env)
self._calls.append((
req.method, req.path,
# mutable dict; keep a copy so subsequent calls can't change it
swob.HeaderKeyDict(req.headers)))
if len(self.responses) > 1:
resp = self.responses.pop(0)
else:
resp = self.responses[0]
status = resp['status']
headers = resp.get('headers', [])
body_iter = resp.get('body_iter', [])
start_response(status, headers)
return body_iter
@property
def calls(self):
"""
Returns the calls received by this application as a list of
(method, path) pairs.
"""
return [x[:2] for x in self._calls]
@property
def call_headers(self):
"""
Returns the list of headers received by this application as it was
called
"""
return [x[2] for x in self._calls]
@property
def calls_with_headers(self):
"""
Returns the calls received by this application as a list of
(method, path, headers) tuples.
"""
return self._calls
class TestConfigParsing(unittest.TestCase):
def test_defaults(self):
app = FakeApp()
undelete = md.filter_factory({})(app)
self.assertEqual(undelete.trash_prefix, ".trash-")
self.assertEqual(undelete.trash_lifetime, 86400 * 90)
self.assertFalse(undelete.block_trash_deletes)
def test_non_defaults(self):
app = FakeApp()
undelete = md.filter_factory({
'trash_prefix': '.heap__',
'trash_lifetime': '31536000',
'block_trash_deletes': 'on',
})(app)
self.assertEqual(undelete.trash_prefix, ".heap__")
self.assertEqual(undelete.trash_lifetime, 31536000)
self.assertTrue(undelete.block_trash_deletes)
class MiddlewareTestCase(unittest.TestCase):
"""
Just a base class for other test cases. Some setup, some utility methods.
Nothing too exciting.
"""
def setUp(self):
self.app = FakeApp()
self.undelete = md.filter_factory({})(self.app)
def call_mware(self, req, expect_exception=False):
status = [None]
headers = [None]
def start_response(s, h, ei=None):
status[0] = s
headers[0] = h
body_iter = self.undelete(req.environ, start_response)
body = ''
caught_exc = None
try:
for chunk in body_iter:
body += chunk
except Exception as exc:
if expect_exception:
caught_exc = exc
else:
raise
headerdict = swob.HeaderKeyDict(headers[0])
if expect_exception:
return status[0], headerdict, body, caught_exc
else:
return status[0], headerdict, body
class TestPassthrough(MiddlewareTestCase):
def test_account_passthrough(self):
"""
Account requests are passed through unmodified.
"""
self.app.responses = [{'status': '200 OK'}]
req = swob.Request.blank('/v1/a')
req.method = 'DELETE'
status, _, _ = self.call_mware(req)
self.assertEqual(status, "200 OK")
self.assertEqual(self.app.calls, [('DELETE', '/v1/a')])
def test_container_passthrough(self):
"""
Container requests are passed through unmodified.
"""
self.app.responses = [{'status': '200 OK'}]
req = swob.Request.blank('/v1/a/c')
req.method = 'DELETE'
status, _, _ = self.call_mware(req)
self.assertEqual(status, "200 OK")
self.assertEqual(self.app.calls, [('DELETE', '/v1/a/c')])
class TestObjectDeletion(MiddlewareTestCase):
def test_deleting_nonexistent_object(self):
# If the object isn't there, ignore the 404 on COPY and pass the
# DELETE request through. It might be an expired object, in which case
# the object DELETE will actually get it out of the container listing
# and free up some space.
self.app.responses = [
# COPY request
{'status': '404 Not Found'},
# trash-versions container creation request
#
# Ideally we'd skip this stuff, but we can't tell the difference
# between object-not-found (404) and
# destination-container-not-found (also 404).
{'status': '202 Accepted'},
# trash container creation request
{'status': '202 Accepted'},
# second COPY attempt:
{'status': '404 Not Found'},
# DELETE request
{'status': '404 Not Found',
'headers': [('X-Exophagous', 'ungrassed')]}]
req = swob.Request.blank('/v1/a/elements/Cf')
req.method = 'DELETE'
status, headers, body = self.call_mware(req)
self.assertEqual(status, "404 Not Found")
self.assertEqual(headers.get('X-Exophagous'), 'ungrassed')
self.assertEqual(self.app.calls,
[('COPY', '/v1/a/elements/Cf'),
('PUT', '/v1/a/.trash-elements-versions'),
('PUT', '/v1/a/.trash-elements'),
('COPY', '/v1/a/elements/Cf'),
('DELETE', '/v1/a/elements/Cf')])
def test_copy_to_existing_trash_container(self):
self.undelete.trash_lifetime = 1997339
self.app.responses = [
# COPY request
{'status': '201 Created',
'headers': [('X-Sir-Not-Appearing-In-This-Response', 'yup')]},
# DELETE request
{'status': '204 No Content',
'headers': [('X-Decadation', 'coprose')]}]
req = swob.Request.blank('/v1/MY_account/cats/kittens.jpg')
req.method = 'DELETE'
status, headers, body = self.call_mware(req)
self.assertEqual(status, "204 No Content")
# the client gets whatever the DELETE coughed up
self.assertNotIn('X-Sir-Not-Appearing-In-This-Response', headers)
self.assertEqual(headers['X-Decadation'], 'coprose')
self.assertEqual(2, len(self.app.calls))
# First, we performed a COPY request to save the object into the trash.
method, path, headers = self.app.calls_with_headers[0]
self.assertEqual(method, 'COPY')
self.assertEqual(path, '/v1/MY_account/cats/kittens.jpg')
self.assertEqual(headers['Destination'], '.trash-cats/kittens.jpg')
self.assertEqual(headers['X-Delete-After'], str(1997339))
# Second, we actually perform the DELETE request (and send that
# response to the client unaltered)
method, path, headers = self.app.calls_with_headers[1]
self.assertEqual(method, 'DELETE')
self.assertEqual(path, '/v1/MY_account/cats/kittens.jpg')
def test_copy_to_existing_trash_container_no_expiration(self):
self.undelete.trash_lifetime = 0
self.app.responses = [
# COPY request
{'status': '201 Created'},
# DELETE request
{'status': '204 No Content'}]
req = swob.Request.blank('/v1/MY_account/cats/kittens.jpg')
req.method = 'DELETE'
status, headers, body = self.call_mware(req)
self.assertEqual(status, "204 No Content")
self.assertEqual(2, len(self.app.calls))
method, path, headers = self.app.calls_with_headers[0]
self.assertEqual(method, 'COPY')
self.assertEqual(path, '/v1/MY_account/cats/kittens.jpg')
self.assertNotIn('X-Delete-After', headers)
def test_copy_to_missing_trash_container(self):
self.app.responses = [
# first COPY attempt: trash container doesn't exist
{'status': '404 Not Found'},
# trash-versions container creation request
{'status': '201 Created'},
# trash container creation request
{'status': '201 Created'},
# second COPY attempt:
{'status': '404 Not Found'},
# DELETE request
{'status': '204 No Content'}]
req = swob.Request.blank('/v1/a/elements/Lv')
req.method = 'DELETE'
status, headers, body = self.call_mware(req)
self.assertEqual(status, "204 No Content")
self.assertEqual(self.app.calls,
[('COPY', '/v1/a/elements/Lv'),
('PUT', '/v1/a/.trash-elements-versions'),
('PUT', '/v1/a/.trash-elements'),
('COPY', '/v1/a/elements/Lv'),
('DELETE', '/v1/a/elements/Lv')])
def test_copy_error(self):
self.app.responses = [
# COPY attempt: some mysterious error with some headers
{'status': '503 Service Unavailable',
'headers': [('X-Scraggedness', 'Goclenian')],
'body_iter': ['dunno what happened boss']}]
req = swob.Request.blank('/v1/a/elements/Te')
req.method = 'DELETE'
status, headers, body = self.call_mware(req)
self.assertEqual(status, "503 Service Unavailable")
self.assertEqual(headers.get('X-Scraggedness'), 'Goclenian')
self.assertIn('what happened', body)
self.assertEqual(self.app.calls, [('COPY', '/v1/a/elements/Te')])
def test_copy_missing_trash_container_error_creating_vrs_container(self):
self.app.responses = [
# first COPY attempt: trash container doesn't exist
{'status': '404 Not Found'},
# trash-versions container creation request: failure!
{'status': '403 Forbidden',
'headers': [('X-Pupillidae', 'Barry')],
'body_iter': ['oh hell no']}]
req = swob.Request.blank('/v1/a/elements/U')
req.method = 'DELETE'
status, headers, body = self.call_mware(req)
self.assertEqual(status, "403 Forbidden")
self.assertEqual(headers.get('X-Pupillidae'), 'Barry')
self.assertIn('oh hell no', body)
self.assertEqual(self.app.calls,
[('COPY', '/v1/a/elements/U'),
('PUT', '/v1/a/.trash-elements-versions')])
def test_copy_missing_trash_container_error_creating_container(self):
self.app.responses = [
# first COPY attempt: trash container doesn't exist
{'status': '404 Not Found'},
# trash-versions container creation request
{'status': '201 Created'},
# trash container creation request: fails!
{'status': "418 I'm a teapot",
'headers': [('X-Body-Type', 'short and stout')],
'body_iter': ['here is my handle, here is my spout']}]
req = swob.Request.blank('/v1/a/elements/Mo')
req.method = 'DELETE'
status, headers, body = self.call_mware(req)
self.assertEqual(status, "418 I'm a teapot")
self.assertEqual(headers.get('X-Body-Type'), 'short and stout')
self.assertIn('spout', body)
self.assertEqual(self.app.calls,
[('COPY', '/v1/a/elements/Mo'),
('PUT', '/v1/a/.trash-elements-versions'),
('PUT', '/v1/a/.trash-elements')])
def test_delete_from_trash(self):
"""
Objects in trash containers don't get saved.
"""
self.app.responses = [{'status': '204 No Content'}]
req = swob.Request.blank('/v1/a/.trash-borkbork/bork')
req.method = 'DELETE'
status, headers, body = self.call_mware(req)
self.assertEqual(status, "204 No Content")
self.assertEqual(self.app.calls,
[('DELETE', '/v1/a/.trash-borkbork/bork')])
def test_delete_from_trash_blocked(self):
self.undelete.block_trash_deletes = True
req = swob.Request.blank('/v1/a/.trash-borkbork/bork')
req.method = 'DELETE'
status, headers, body = self.call_mware(req)
self.assertEqual(status, "405 Method Not Allowed")
self.assertEqual(self.app.calls, [])
| en | 0.897774 | #!/usr/bin/env python # Copyright (c) 2014 SwiftStack, Inc. # # 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. # fill in later # mutable dict; keep a copy so subsequent calls can't change it Returns the calls received by this application as a list of (method, path) pairs. Returns the list of headers received by this application as it was called Returns the calls received by this application as a list of (method, path, headers) tuples. Just a base class for other test cases. Some setup, some utility methods. Nothing too exciting. Account requests are passed through unmodified. Container requests are passed through unmodified. # If the object isn't there, ignore the 404 on COPY and pass the # DELETE request through. It might be an expired object, in which case # the object DELETE will actually get it out of the container listing # and free up some space. # COPY request # trash-versions container creation request # # Ideally we'd skip this stuff, but we can't tell the difference # between object-not-found (404) and # destination-container-not-found (also 404). # trash container creation request # second COPY attempt: # DELETE request # COPY request # DELETE request # the client gets whatever the DELETE coughed up # First, we performed a COPY request to save the object into the trash. # Second, we actually perform the DELETE request (and send that # response to the client unaltered) # COPY request # DELETE request # first COPY attempt: trash container doesn't exist # trash-versions container creation request # trash container creation request # second COPY attempt: # DELETE request # COPY attempt: some mysterious error with some headers # first COPY attempt: trash container doesn't exist # trash-versions container creation request: failure! # first COPY attempt: trash container doesn't exist # trash-versions container creation request # trash container creation request: fails! Objects in trash containers don't get saved. | 2.298631 | 2 |
tests/test_iou_box3d.py | janEbert/pytorch3d | 0 | 6627999 | <gh_stars>0
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import pickle
import random
import unittest
from typing import List, Tuple, Union
import torch
import torch.nn.functional as F
from common_testing import TestCaseMixin, get_random_cuda_device, get_tests_dir
from pytorch3d.io import save_obj
from pytorch3d.ops.iou_box3d import _box_planes, _box_triangles, box3d_overlap
from pytorch3d.transforms.rotation_conversions import random_rotation
OBJECTRON_TO_PYTORCH3D_FACE_IDX = [0, 4, 6, 2, 1, 5, 7, 3]
DATA_DIR = get_tests_dir() / "data"
DEBUG = False
EPS = 1e-5
UNIT_BOX = [
[0, 0, 0],
[1, 0, 0],
[1, 1, 0],
[0, 1, 0],
[0, 0, 1],
[1, 0, 1],
[1, 1, 1],
[0, 1, 1],
]
class TestIoU3D(TestCaseMixin, unittest.TestCase):
def setUp(self) -> None:
super().setUp()
torch.manual_seed(1)
@staticmethod
def create_box(xyz, whl):
x, y, z = xyz
w, h, le = whl
verts = torch.tensor(
[
[x - w / 2.0, y - h / 2.0, z - le / 2.0],
[x + w / 2.0, y - h / 2.0, z - le / 2.0],
[x + w / 2.0, y + h / 2.0, z - le / 2.0],
[x - w / 2.0, y + h / 2.0, z - le / 2.0],
[x - w / 2.0, y - h / 2.0, z + le / 2.0],
[x + w / 2.0, y - h / 2.0, z + le / 2.0],
[x + w / 2.0, y + h / 2.0, z + le / 2.0],
[x - w / 2.0, y + h / 2.0, z + le / 2.0],
],
device=xyz.device,
dtype=torch.float32,
)
return verts
@staticmethod
def _box3d_overlap_naive_batched(boxes1, boxes2):
"""
Wrapper around box3d_overlap_naive to support
batched input
"""
N = boxes1.shape[0]
M = boxes2.shape[0]
vols = torch.zeros((N, M), dtype=torch.float32, device=boxes1.device)
ious = torch.zeros((N, M), dtype=torch.float32, device=boxes1.device)
for n in range(N):
for m in range(M):
vol, iou = box3d_overlap_naive(boxes1[n], boxes2[m])
vols[n, m] = vol
ious[n, m] = iou
return vols, ious
@staticmethod
def _box3d_overlap_sampling_batched(boxes1, boxes2, num_samples: int):
"""
Wrapper around box3d_overlap_sampling to support
batched input
"""
N = boxes1.shape[0]
M = boxes2.shape[0]
ious = torch.zeros((N, M), dtype=torch.float32, device=boxes1.device)
for n in range(N):
for m in range(M):
iou = box3d_overlap_sampling(boxes1[n], boxes2[m])
ious[n, m] = iou
return ious
def _test_iou(self, overlap_fn, device):
box1 = torch.tensor(
UNIT_BOX,
dtype=torch.float32,
device=device,
)
# 1st test: same box, iou = 1.0
vol, iou = overlap_fn(box1[None], box1[None])
self.assertClose(vol, torch.tensor([[1.0]], device=vol.device, dtype=vol.dtype))
self.assertClose(iou, torch.tensor([[1.0]], device=vol.device, dtype=vol.dtype))
# 2nd test
dd = random.random()
box2 = box1 + torch.tensor([[0.0, dd, 0.0]], device=device)
vol, iou = overlap_fn(box1[None], box2[None])
self.assertClose(
vol, torch.tensor([[1 - dd]], device=vol.device, dtype=vol.dtype)
)
# symmetry
vol, iou = overlap_fn(box2[None], box1[None])
self.assertClose(
vol, torch.tensor([[1 - dd]], device=vol.device, dtype=vol.dtype)
)
# 3rd test
dd = random.random()
box2 = box1 + torch.tensor([[dd, 0.0, 0.0]], device=device)
vol, _ = overlap_fn(box1[None], box2[None])
self.assertClose(
vol, torch.tensor([[1 - dd]], device=vol.device, dtype=vol.dtype)
)
# symmetry
vol, _ = overlap_fn(box2[None], box1[None])
self.assertClose(
vol, torch.tensor([[1 - dd]], device=vol.device, dtype=vol.dtype)
)
# 4th test
ddx, ddy, ddz = random.random(), random.random(), random.random()
box2 = box1 + torch.tensor([[ddx, ddy, ddz]], device=device)
vol, _ = overlap_fn(box1[None], box2[None])
self.assertClose(
vol,
torch.tensor(
[[(1 - ddx) * (1 - ddy) * (1 - ddz)]],
device=vol.device,
dtype=vol.dtype,
),
)
# symmetry
vol, _ = overlap_fn(box2[None], box1[None])
self.assertClose(
vol,
torch.tensor(
[[(1 - ddx) * (1 - ddy) * (1 - ddz)]],
device=vol.device,
dtype=vol.dtype,
),
)
# Also check IoU is 1 when computing overlap with the same shifted box
vol, iou = overlap_fn(box2[None], box2[None])
self.assertClose(iou, torch.tensor([[1.0]], device=vol.device, dtype=vol.dtype))
# 5th test
ddx, ddy, ddz = random.random(), random.random(), random.random()
box2 = box1 + torch.tensor([[ddx, ddy, ddz]], device=device)
RR = random_rotation(dtype=torch.float32, device=device)
box1r = box1 @ RR.transpose(0, 1)
box2r = box2 @ RR.transpose(0, 1)
vol, _ = overlap_fn(box1r[None], box2r[None])
self.assertClose(
vol,
torch.tensor(
[[(1 - ddx) * (1 - ddy) * (1 - ddz)]],
device=vol.device,
dtype=vol.dtype,
),
)
# symmetry
vol, _ = overlap_fn(box2r[None], box1r[None])
self.assertClose(
vol,
torch.tensor(
[[(1 - ddx) * (1 - ddy) * (1 - ddz)]],
device=vol.device,
dtype=vol.dtype,
),
)
# 6th test
ddx, ddy, ddz = random.random(), random.random(), random.random()
box2 = box1 + torch.tensor([[ddx, ddy, ddz]], device=device)
RR = random_rotation(dtype=torch.float32, device=device)
TT = torch.rand((1, 3), dtype=torch.float32, device=device)
box1r = box1 @ RR.transpose(0, 1) + TT
box2r = box2 @ RR.transpose(0, 1) + TT
vol, _ = overlap_fn(box1r[None], box2r[None])
self.assertClose(
vol,
torch.tensor(
[[(1 - ddx) * (1 - ddy) * (1 - ddz)]],
device=vol.device,
dtype=vol.dtype,
),
atol=1e-7,
)
# symmetry
vol, _ = overlap_fn(box2r[None], box1r[None])
self.assertClose(
vol,
torch.tensor(
[[(1 - ddx) * (1 - ddy) * (1 - ddz)]],
device=vol.device,
dtype=vol.dtype,
),
atol=1e-7,
)
# 7th test: hand coded example and test with meshlab output
# Meshlab procedure to compute volumes of shapes
# 1. Load a shape, then Filters
# -> Remeshing, Simplification, Reconstruction -> Convex Hull
# 2. Select the convex hull shape (This is important!)
# 3. Then Filters -> Quality Measure and Computation -> Compute Geometric Measures
# 3. Check for "Mesh Volume" in the stdout
box1r = torch.tensor(
[
[3.1673, -2.2574, 0.4817],
[4.6470, 0.2223, 2.4197],
[5.2200, 1.1844, 0.7510],
[3.7403, -1.2953, -1.1869],
[-4.9316, 2.5724, 0.4856],
[-3.4519, 5.0521, 2.4235],
[-2.8789, 6.0142, 0.7549],
[-4.3586, 3.5345, -1.1831],
],
device=device,
)
box2r = torch.tensor(
[
[0.5623, 4.0647, 3.4334],
[3.3584, 4.3191, 1.1791],
[3.0724, -5.9235, -0.3315],
[0.2763, -6.1779, 1.9229],
[-2.0773, 4.6121, 0.2213],
[0.7188, 4.8665, -2.0331],
[0.4328, -5.3761, -3.5436],
[-2.3633, -5.6305, -1.2893],
],
device=device,
)
# from Meshlab:
vol_inters = 33.558529
vol_box1 = 65.899010
vol_box2 = 156.386719
iou_mesh = vol_inters / (vol_box1 + vol_box2 - vol_inters)
vol, iou = overlap_fn(box1r[None], box2r[None])
self.assertClose(vol, torch.tensor([[vol_inters]], device=device), atol=1e-1)
self.assertClose(iou, torch.tensor([[iou_mesh]], device=device), atol=1e-1)
# symmetry
vol, iou = overlap_fn(box2r[None], box1r[None])
self.assertClose(vol, torch.tensor([[vol_inters]], device=device), atol=1e-1)
self.assertClose(iou, torch.tensor([[iou_mesh]], device=device), atol=1e-1)
# 8th test: compare with sampling
# create box1
ctrs = torch.rand((2, 3), device=device)
whl = torch.rand((2, 3), device=device) * 10.0 + 1.0
# box8a & box8b
box8a = self.create_box(ctrs[0], whl[0])
box8b = self.create_box(ctrs[1], whl[1])
RR1 = random_rotation(dtype=torch.float32, device=device)
TT1 = torch.rand((1, 3), dtype=torch.float32, device=device)
RR2 = random_rotation(dtype=torch.float32, device=device)
TT2 = torch.rand((1, 3), dtype=torch.float32, device=device)
box1r = box8a @ RR1.transpose(0, 1) + TT1
box2r = box8b @ RR2.transpose(0, 1) + TT2
vol, iou = overlap_fn(box1r[None], box2r[None])
iou_sampling = self._box3d_overlap_sampling_batched(
box1r[None], box2r[None], num_samples=10000
)
self.assertClose(iou, iou_sampling, atol=1e-2)
# symmetry
vol, iou = overlap_fn(box2r[None], box1r[None])
self.assertClose(iou, iou_sampling, atol=1e-2)
# 9th test: non overlapping boxes, iou = 0.0
box2 = box1 + torch.tensor([[0.0, 100.0, 0.0]], device=device)
vol, iou = overlap_fn(box1[None], box2[None])
self.assertClose(vol, torch.tensor([[0.0]], device=vol.device, dtype=vol.dtype))
self.assertClose(iou, torch.tensor([[0.0]], device=vol.device, dtype=vol.dtype))
# symmetry
vol, iou = overlap_fn(box2[None], box1[None])
self.assertClose(vol, torch.tensor([[0.0]], device=vol.device, dtype=vol.dtype))
self.assertClose(iou, torch.tensor([[0.0]], device=vol.device, dtype=vol.dtype))
# 10th test: Non coplanar verts in a plane
box10 = box1 + torch.rand((8, 3), dtype=torch.float32, device=device)
msg = "Plane vertices are not coplanar"
with self.assertRaisesRegex(ValueError, msg):
overlap_fn(box10[None], box10[None])
# 11th test: Skewed bounding boxes but all verts are coplanar
box_skew_1 = torch.tensor(
[
[0, 0, 0],
[1, 0, 0],
[1, 1, 0],
[0, 1, 0],
[-2, -2, 2],
[2, -2, 2],
[2, 2, 2],
[-2, 2, 2],
],
dtype=torch.float32,
device=device,
)
box_skew_2 = torch.tensor(
[
[2.015995, 0.695233, 2.152806],
[2.832533, 0.663448, 1.576389],
[2.675445, -0.309592, 1.407520],
[1.858907, -0.277806, 1.983936],
[-0.413922, 3.161758, 2.044343],
[2.852230, 3.034615, -0.261321],
[2.223878, -0.857545, -0.936800],
[-1.042273, -0.730402, 1.368864],
],
dtype=torch.float32,
device=device,
)
vol1 = 14.000
vol2 = 14.000005
vol_inters = 5.431122
iou = vol_inters / (vol1 + vol2 - vol_inters)
vols, ious = overlap_fn(box_skew_1[None], box_skew_2[None])
self.assertClose(vols, torch.tensor([[vol_inters]], device=device), atol=1e-1)
self.assertClose(ious, torch.tensor([[iou]], device=device), atol=1e-1)
# symmetry
vols, ious = overlap_fn(box_skew_2[None], box_skew_1[None])
self.assertClose(vols, torch.tensor([[vol_inters]], device=device), atol=1e-1)
self.assertClose(ious, torch.tensor([[iou]], device=device), atol=1e-1)
# 12th test: Zero area bounding box (from GH issue #992)
box12a = torch.tensor(
[
[-1.0000, -1.0000, -0.5000],
[1.0000, -1.0000, -0.5000],
[1.0000, 1.0000, -0.5000],
[-1.0000, 1.0000, -0.5000],
[-1.0000, -1.0000, 0.5000],
[1.0000, -1.0000, 0.5000],
[1.0000, 1.0000, 0.5000],
[-1.0000, 1.0000, 0.5000],
],
device=device,
dtype=torch.float32,
)
box12b = torch.tensor(
[
[0.0, 0.0, 0.0],
[0.0, 0.0, 0.0],
[0.0, 0.0, 0.0],
[0.0, 0.0, 0.0],
[0.0, 0.0, 0.0],
[0.0, 0.0, 0.0],
[0.0, 0.0, 0.0],
[0.0, 0.0, 0.0],
],
device=device,
dtype=torch.float32,
)
msg = "Planes have zero areas"
with self.assertRaisesRegex(ValueError, msg):
overlap_fn(box12a[None], box12b[None])
# symmetry
with self.assertRaisesRegex(ValueError, msg):
overlap_fn(box12b[None], box12a[None])
# 13th test: From GH issue #992
# Zero area coplanar face after intersection
ctrs = torch.tensor([[0.0, 0.0, 0.0], [-1.0, 1.0, 0.0]])
whl = torch.tensor([[2.0, 2.0, 2.0], [2.0, 2, 2]])
box13a = TestIoU3D.create_box(ctrs[0], whl[0])
box13b = TestIoU3D.create_box(ctrs[1], whl[1])
vol, iou = overlap_fn(box13a[None], box13b[None])
self.assertClose(vol, torch.tensor([[2.0]], device=vol.device, dtype=vol.dtype))
# 14th test: From GH issue #992
# Random rotation, same boxes, iou should be 1.0
corners = (
torch.tensor(
[
[-1.0, -1.0, -1.0],
[1.0, -1.0, -1.0],
[1.0, 1.0, -1.0],
[-1.0, 1.0, -1.0],
[-1.0, -1.0, 1.0],
[1.0, -1.0, 1.0],
[1.0, 1.0, 1.0],
[-1.0, 1.0, 1.0],
],
device=device,
dtype=torch.float32,
)
* 0.5
)
yaw = torch.tensor(0.185)
Rot = torch.tensor(
[
[torch.cos(yaw), 0.0, torch.sin(yaw)],
[0.0, 1.0, 0.0],
[-torch.sin(yaw), 0.0, torch.cos(yaw)],
],
dtype=torch.float32,
device=device,
)
corners = (Rot.mm(corners.t())).t()
vol, iou = overlap_fn(corners[None], corners[None])
self.assertClose(
iou, torch.tensor([[1.0]], device=vol.device, dtype=vol.dtype), atol=1e-2
)
# 15th test: From GH issue #1082
box15a = torch.tensor(
[
[-2.5629019, 4.13995749, -1.76344576],
[1.92329434, 4.28127117, -1.86155124],
[1.86994571, 5.97489644, -1.86155124],
[-2.61625053, 5.83358276, -1.76344576],
[-2.53123587, 4.14095496, -0.31397536],
[1.95496037, 4.28226864, -0.41208084],
[1.90161174, 5.97589391, -0.41208084],
[-2.5845845, 5.83458023, -0.31397536],
],
device=device,
dtype=torch.float32,
)
box15b = torch.tensor(
[
[-2.6256125, 4.13036357, -1.82893437],
[1.87201008, 4.25296695, -1.82893437],
[1.82562476, 5.95458116, -1.82893437],
[-2.67199782, 5.83197777, -1.82893437],
[-2.6256125, 4.13036357, -0.40095884],
[1.87201008, 4.25296695, -0.40095884],
[1.82562476, 5.95458116, -0.40095884],
[-2.67199782, 5.83197777, -0.40095884],
],
device=device,
dtype=torch.float32,
)
vol, iou = overlap_fn(box15a[None], box15b[None])
self.assertClose(
iou, torch.tensor([[0.91]], device=vol.device, dtype=vol.dtype), atol=1e-2
)
def _test_real_boxes(self, overlap_fn, device):
data_filename = "./real_boxes.pkl"
with open(DATA_DIR / data_filename, "rb") as f:
example = pickle.load(f)
verts1 = torch.FloatTensor(example["verts1"])
verts2 = torch.FloatTensor(example["verts2"])
boxes = torch.stack((verts1, verts2)).to(device)
iou_expected = torch.eye(2).to(device)
vol, iou = overlap_fn(boxes, boxes)
self.assertClose(iou, iou_expected)
def test_iou_naive(self):
device = get_random_cuda_device()
self._test_iou(self._box3d_overlap_naive_batched, device)
self._test_compare_objectron(self._box3d_overlap_naive_batched, device)
self._test_real_boxes(self._box3d_overlap_naive_batched, device)
def test_iou_cpu(self):
device = torch.device("cpu")
self._test_iou(box3d_overlap, device)
self._test_compare_objectron(box3d_overlap, device)
self._test_real_boxes(box3d_overlap, device)
def test_iou_cuda(self):
device = torch.device("cuda:0")
self._test_iou(box3d_overlap, device)
self._test_compare_objectron(box3d_overlap, device)
self._test_real_boxes(box3d_overlap, device)
def _test_compare_objectron(self, overlap_fn, device):
# Load saved objectron data
data_filename = "./objectron_vols_ious.pt"
objectron_vals = torch.load(DATA_DIR / data_filename)
boxes1 = objectron_vals["boxes1"]
boxes2 = objectron_vals["boxes2"]
vols_objectron = objectron_vals["vols"]
ious_objectron = objectron_vals["ious"]
boxes1 = boxes1.to(device=device, dtype=torch.float32)
boxes2 = boxes2.to(device=device, dtype=torch.float32)
# Convert vertex orderings from Objectron to PyTorch3D convention
idx = torch.tensor(
OBJECTRON_TO_PYTORCH3D_FACE_IDX, dtype=torch.int64, device=device
)
boxes1 = boxes1.index_select(index=idx, dim=1)
boxes2 = boxes2.index_select(index=idx, dim=1)
# Run PyTorch3D version
vols, ious = overlap_fn(boxes1, boxes2)
# Check values match
self.assertClose(vols_objectron, vols.cpu())
self.assertClose(ious_objectron, ious.cpu())
def test_batched_errors(self):
N, M = 5, 10
boxes1 = torch.randn((N, 8, 3))
boxes2 = torch.randn((M, 10, 3))
with self.assertRaisesRegex(ValueError, "(8, 3)"):
box3d_overlap(boxes1, boxes2)
def test_box_volume(self):
device = torch.device("cuda:0")
box1 = torch.tensor(
[
[3.1673, -2.2574, 0.4817],
[4.6470, 0.2223, 2.4197],
[5.2200, 1.1844, 0.7510],
[3.7403, -1.2953, -1.1869],
[-4.9316, 2.5724, 0.4856],
[-3.4519, 5.0521, 2.4235],
[-2.8789, 6.0142, 0.7549],
[-4.3586, 3.5345, -1.1831],
],
dtype=torch.float32,
device=device,
)
box2 = torch.tensor(
[
[0.5623, 4.0647, 3.4334],
[3.3584, 4.3191, 1.1791],
[3.0724, -5.9235, -0.3315],
[0.2763, -6.1779, 1.9229],
[-2.0773, 4.6121, 0.2213],
[0.7188, 4.8665, -2.0331],
[0.4328, -5.3761, -3.5436],
[-2.3633, -5.6305, -1.2893],
],
dtype=torch.float32,
device=device,
)
box3 = torch.tensor(
[
[0, 0, 0],
[1, 0, 0],
[1, 1, 0],
[0, 1, 0],
[0, 0, 1],
[1, 0, 1],
[1, 1, 1],
[0, 1, 1],
],
dtype=torch.float32,
device=device,
)
RR = random_rotation(dtype=torch.float32, device=device)
TT = torch.rand((1, 3), dtype=torch.float32, device=device)
box4 = box3 @ RR.transpose(0, 1) + TT
self.assertClose(box_volume(box1).cpu(), torch.tensor(65.899010), atol=1e-3)
self.assertClose(box_volume(box2).cpu(), torch.tensor(156.386719), atol=1e-3)
self.assertClose(box_volume(box3).cpu(), torch.tensor(1.0), atol=1e-3)
self.assertClose(box_volume(box4).cpu(), torch.tensor(1.0), atol=1e-3)
def test_box_planar_dir(self):
device = torch.device("cuda:0")
box1 = torch.tensor(
UNIT_BOX,
dtype=torch.float32,
device=device,
)
n1 = torch.tensor(
[
[0.0, 0.0, 1.0],
[0.0, -1.0, 0.0],
[0.0, 1.0, 0.0],
[1.0, 0.0, 0.0],
[-1.0, 0.0, 0.0],
[0.0, 0.0, -1.0],
],
device=device,
dtype=torch.float32,
)
RR = random_rotation(dtype=torch.float32, device=device)
TT = torch.rand((1, 3), dtype=torch.float32, device=device)
box2 = box1 @ RR.transpose(0, 1) + TT
n2 = n1 @ RR.transpose(0, 1)
self.assertClose(box_planar_dir(box1), n1)
self.assertClose(box_planar_dir(box2), n2)
@staticmethod
def iou_naive(N: int, M: int, device="cpu"):
box = torch.tensor(
[UNIT_BOX],
dtype=torch.float32,
device=device,
)
boxes1 = box + torch.randn((N, 1, 3), device=device)
boxes2 = box + torch.randn((M, 1, 3), device=device)
def output():
vol, iou = TestIoU3D._box3d_overlap_naive_batched(boxes1, boxes2)
return output
@staticmethod
def iou(N: int, M: int, device="cpu"):
box = torch.tensor(
[UNIT_BOX],
dtype=torch.float32,
device=device,
)
boxes1 = box + torch.randn((N, 1, 3), device=device)
boxes2 = box + torch.randn((M, 1, 3), device=device)
def output():
vol, iou = box3d_overlap(boxes1, boxes2)
return output
@staticmethod
def iou_sampling(N: int, M: int, num_samples: int, device="cpu"):
box = torch.tensor(
[UNIT_BOX],
dtype=torch.float32,
device=device,
)
boxes1 = box + torch.randn((N, 1, 3), device=device)
boxes2 = box + torch.randn((M, 1, 3), device=device)
def output():
_ = TestIoU3D._box3d_overlap_sampling_batched(boxes1, boxes2, num_samples)
return output
# -------------------------------------------------- #
# NAIVE IMPLEMENTATION #
# -------------------------------------------------- #
"""
The main functions below are:
* box3d_overlap_naive: which computes the exact IoU of box1 and box2
* box3d_overlap_sampling: which computes an approximate IoU of box1 and box2
by sampling points within the boxes
Note that both implementations currently do not support batching.
"""
# -------------------------------------------------- #
# Throughout this implementation, we assume that boxes
# are defined by their 8 corners in the following order
#
# (4) +---------+. (5)
# | ` . | ` .
# | (0) +---+-----+ (1)
# | | | |
# (7) +-----+---+. (6)|
# ` . | ` . |
# (3) ` +---------+ (2)
#
# -------------------------------------------------- #
# -------------------------------------------------- #
# HELPER FUNCTIONS FOR EXACT SOLUTION #
# -------------------------------------------------- #
def get_tri_verts(box: torch.Tensor) -> torch.Tensor:
"""
Return the vertex coordinates forming the triangles of the box.
The computation here resembles the Meshes data structure.
But since we only want this tiny functionality, we abstract it out.
Args:
box: tensor of shape (8, 3)
Returns:
tri_verts: tensor of shape (12, 3, 3)
"""
device = box.device
faces = torch.tensor(_box_triangles, device=device, dtype=torch.int64) # (12, 3)
tri_verts = box[faces] # (12, 3, 3)
return tri_verts
def get_plane_verts(box: torch.Tensor) -> torch.Tensor:
"""
Return the vertex coordinates forming the planes of the box.
The computation here resembles the Meshes data structure.
But since we only want this tiny functionality, we abstract it out.
Args:
box: tensor of shape (8, 3)
Returns:
plane_verts: tensor of shape (6, 4, 3)
"""
device = box.device
faces = torch.tensor(_box_planes, device=device, dtype=torch.int64) # (6, 4)
plane_verts = box[faces] # (6, 4, 3)
return plane_verts
def box_planar_dir(box: torch.Tensor, eps: float = 1e-4) -> torch.Tensor:
"""
Finds the unit vector n which is perpendicular to each plane in the box
and points towards the inside of the box.
The planes are defined by `_box_planes`.
Since the shape is convex, we define the interior to be the direction
pointing to the center of the shape.
Args:
box: tensor of shape (8, 3) of the vertices of the 3D box
Returns:
n: tensor of shape (6,) of the unit vector orthogonal to the face pointing
towards the interior of the shape
"""
assert box.shape[0] == 8 and box.shape[1] == 3
# center point of each box
ctr = box.mean(0).view(1, 3)
verts = get_plane_verts(box) # (6, 4, 3)
v0, v1, v2, v3 = verts.unbind(1) # each v of shape (6, 3)
# We project the ctr on the plane defined by (v0, v1, v2, v3)
# We define e0 to be the edge connecting (v1, v0)
# We define e1 to be the edge connecting (v2, v0)
# And n is the cross product of e0, e1, either pointing "inside" or not.
e0 = F.normalize(v1 - v0, dim=-1)
e1 = F.normalize(v2 - v0, dim=-1)
n = F.normalize(torch.cross(e0, e1, dim=-1), dim=-1)
# Check all verts are coplanar
if not ((v3 - v0).unsqueeze(1).bmm(n.unsqueeze(2)).abs() < eps).all().item():
msg = "Plane vertices are not coplanar"
raise ValueError(msg)
# Check all faces have non zero area
area1 = torch.cross(v1 - v0, v2 - v0, dim=-1).norm(dim=-1) / 2
area2 = torch.cross(v3 - v0, v2 - v0, dim=-1).norm(dim=-1) / 2
if (area1 < eps).any().item() or (area2 < eps).any().item():
msg = "Planes have zero areas"
raise ValueError(msg)
# We can write: `ctr = v0 + a * e0 + b * e1 + c * n`, (1).
# With <e0, n> = 0 and <e1, n> = 0, where <.,.> refers to the dot product,
# since that e0 is orthogonal to n. Same for e1.
"""
# Below is how one would solve for (a, b, c)
# Solving for (a, b)
numF = verts.shape[0]
A = torch.ones((numF, 2, 2), dtype=torch.float32, device=device)
B = torch.ones((numF, 2), dtype=torch.float32, device=device)
A[:, 0, 1] = (e0 * e1).sum(-1)
A[:, 1, 0] = (e0 * e1).sum(-1)
B[:, 0] = ((ctr - v0) * e0).sum(-1)
B[:, 1] = ((ctr - v1) * e1).sum(-1)
ab = torch.linalg.solve(A, B) # (numF, 2)
a, b = ab.unbind(1)
# solving for c
c = ((ctr - v0 - a.view(numF, 1) * e0 - b.view(numF, 1) * e1) * n).sum(-1)
"""
# Since we know that <e0, n> = 0 and <e1, n> = 0 (e0 and e1 are orthogonal to n),
# the above solution is equivalent to
c = ((ctr - v0) * n).sum(-1)
# If c is negative, then we revert the direction of n such that n points "inside"
negc = c < 0.0
n[negc] *= -1.0
# c[negc] *= -1.0
# Now (a, b, c) is the solution to (1)
return n
def tri_verts_area(tri_verts: torch.Tensor) -> torch.Tensor:
"""
Computes the area of the triangle faces in tri_verts
Args:
tri_verts: tensor of shape (T, 3, 3)
Returns:
areas: the area of the triangles (T, 1)
"""
add_dim = False
if tri_verts.ndim == 2:
tri_verts = tri_verts.unsqueeze(0)
add_dim = True
v0, v1, v2 = tri_verts.unbind(1)
areas = torch.cross(v1 - v0, v2 - v0, dim=-1).norm(dim=-1) / 2.0
if add_dim:
areas = areas[0]
return areas
def box_volume(box: torch.Tensor) -> torch.Tensor:
"""
Computes the volume of each box in boxes.
The volume of each box is the sum of all the tetrahedrons
formed by the faces of the box. The face of the box is the base of
that tetrahedron and the center point of the box is the apex.
In other words, vol(box) = sum_i A_i * d_i / 3,
where A_i is the area of the i-th face and d_i is the
distance of the apex from the face.
We use the equivalent dot/cross product formulation.
Read https://en.wikipedia.org/wiki/Tetrahedron#Volume
Args:
box: tensor of shape (8, 3) containing the vertices
of the 3D box
Returns:
vols: the volume of the box
"""
assert box.shape[0] == 8 and box.shape[1] == 3
# Compute the center point of each box
ctr = box.mean(0).view(1, 1, 3)
# Extract the coordinates of the faces for each box
tri_verts = get_tri_verts(box)
# Set the origin of the coordinate system to coincide
# with the apex of the tetrahedron to simplify the volume calculation
# See https://en.wikipedia.org/wiki/Tetrahedron#Volume
tri_verts = tri_verts - ctr
# Compute the volume of each box using the dot/cross product formula
vols = torch.sum(
tri_verts[:, 0] * torch.cross(tri_verts[:, 1], tri_verts[:, 2], dim=-1),
dim=-1,
)
vols = (vols.abs() / 6.0).sum()
return vols
def coplanar_tri_faces(tri1: torch.Tensor, tri2: torch.Tensor, eps: float = EPS):
"""
Determines whether two triangle faces in 3D are coplanar
Args:
tri1: tensor of shape (3, 3) of the vertices of the 1st triangle
tri2: tensor of shape (3, 3) of the vertices of the 2nd triangle
Returns:
is_coplanar: bool
"""
v0, v1, v2 = tri1.unbind(0)
e0 = F.normalize(v1 - v0, dim=0)
e1 = F.normalize(v2 - v0, dim=0)
e2 = F.normalize(torch.cross(e0, e1), dim=0)
coplanar2 = torch.zeros((3,), dtype=torch.bool, device=tri1.device)
for i in range(3):
if (tri2[i] - v0).dot(e2).abs() < eps:
coplanar2[i] = 1
coplanar2 = coplanar2.all()
return coplanar2
def is_inside(
plane: torch.Tensor,
n: torch.Tensor,
points: torch.Tensor,
return_proj: bool = True,
eps: float = EPS,
):
"""
Computes whether point is "inside" the plane.
The definition of "inside" means that the point
has a positive component in the direction of the plane normal defined by n.
For example,
plane
|
| . (A)
|--> n
|
.(B) |
Point (A) is "inside" the plane, while point (B) is "outside" the plane.
Args:
plane: tensor of shape (4,3) of vertices of a box plane
n: tensor of shape (3,) of the unit "inside" direction on the plane
points: tensor of shape (P, 3) of coordinates of a point
return_proj: bool whether to return the projected point on the plane
Returns:
is_inside: bool of shape (P,) of whether point is inside
p_proj: tensor of shape (P, 3) of the projected point on plane
"""
device = plane.device
v0, v1, v2, v3 = plane
e0 = F.normalize(v1 - v0, dim=0)
e1 = F.normalize(v2 - v0, dim=0)
if not torch.allclose(e0.dot(n), torch.zeros((1,), device=device), atol=1e-6):
raise ValueError("Input n is not perpendicular to the plane")
if not torch.allclose(e1.dot(n), torch.zeros((1,), device=device), atol=1e-6):
raise ValueError("Input n is not perpendicular to the plane")
add_dim = False
if points.ndim == 1:
points = points.unsqueeze(0)
add_dim = True
assert points.shape[1] == 3
# Every point p can be written as p = v0 + a e0 + b e1 + c n
# If return_proj is True, we need to solve for (a, b)
p_proj = None
if return_proj:
# solving for (a, b)
A = torch.tensor(
[[1.0, e0.dot(e1)], [e0.dot(e1), 1.0]], dtype=torch.float32, device=device
)
B = torch.zeros((2, points.shape[0]), dtype=torch.float32, device=device)
B[0, :] = torch.sum((points - v0.view(1, 3)) * e0.view(1, 3), dim=-1)
B[1, :] = torch.sum((points - v0.view(1, 3)) * e1.view(1, 3), dim=-1)
ab = A.inverse() @ B # (2, P)
p_proj = v0.view(1, 3) + ab.transpose(0, 1) @ torch.stack((e0, e1), dim=0)
# solving for c
# c = (point - v0 - a * e0 - b * e1).dot(n)
c = torch.sum((points - v0.view(1, 3)) * n.view(1, 3), dim=-1)
ins = c > -eps
if add_dim:
assert p_proj.shape[0] == 1
p_proj = p_proj[0]
return ins, p_proj
def plane_edge_point_of_intersection(plane, n, p0, p1):
"""
Finds the point of intersection between a box plane and
a line segment connecting (p0, p1).
The plane is assumed to be infinite long.
Args:
plane: tensor of shape (4, 3) of the coordinates of the vertices defining the plane
n: tensor of shape (3,) of the unit direction perpendicular on the plane
(Note that we could compute n but since it's computed in the main
body of the function, we save time by feeding it in. For the purpose
of this function, it's not important that n points "inside" the shape.)
p0, p1: tensors of shape (3,), (3,)
Returns:
p: tensor of shape (3,) of the coordinates of the point of intersection
a: scalar such that p = p0 + a*(p1-p0)
"""
# The point of intersection can be parametrized
# p = p0 + a (p1 - p0) where a in [0, 1]
# We want to find a such that p is on plane
# <p - v0, n> = 0
v0, v1, v2, v3 = plane
a = -(p0 - v0).dot(n) / (p1 - p0).dot(n)
p = p0 + a * (p1 - p0)
return p, a
"""
The three following functions support clipping a triangle face by a plane.
They contain the following cases: (a) the triangle has one point "outside" the plane and
(b) the triangle has two points "outside" the plane.
This logic follows the logic of clipping triangles when they intersect the image plane while
rendering.
"""
def clip_tri_by_plane_oneout(
plane: torch.Tensor,
n: torch.Tensor,
vout: torch.Tensor,
vin1: torch.Tensor,
vin2: torch.Tensor,
eps: float = EPS,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Case (a).
Clips triangle by plane when vout is outside plane, and vin1, vin2, is inside
In this case, only one vertex of the triangle is outside the plane.
Clip the triangle into a quadrilateral, and then split into two triangles
Args:
plane: tensor of shape (4, 3) of the coordinates of the vertices forming the plane
n: tensor of shape (3,) of the unit "inside" direction of the plane
vout, vin1, vin2: tensors of shape (3,) of the points forming the triangle, where
vout is "outside" the plane and vin1, vin2 are "inside"
Returns:
verts: tensor of shape (4, 3) containing the new vertices formed after clipping the
original intersecting triangle (vout, vin1, vin2)
faces: tensor of shape (2, 3) defining the vertex indices forming the two new triangles
which are "inside" the plane formed after clipping
"""
device = plane.device
# point of intersection between plane and (vin1, vout)
pint1, a1 = plane_edge_point_of_intersection(plane, n, vin1, vout)
assert a1 >= -eps and a1 <= 1.0 + eps, a1
# point of intersection between plane and (vin2, vout)
pint2, a2 = plane_edge_point_of_intersection(plane, n, vin2, vout)
assert a2 >= -eps and a2 <= 1.0 + eps, a2
verts = torch.stack((vin1, pint1, pint2, vin2), dim=0) # 4x3
faces = torch.tensor(
[[0, 1, 2], [0, 2, 3]], dtype=torch.int64, device=device
) # 2x3
return verts, faces
def clip_tri_by_plane_twoout(
plane: torch.Tensor,
n: torch.Tensor,
vout1: torch.Tensor,
vout2: torch.Tensor,
vin: torch.Tensor,
eps: float = EPS,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Case (b).
Clips face by plane when vout1, vout2 are outside plane, and vin1 is inside
In this case, only one vertex of the triangle is inside the plane.
Args:
plane: tensor of shape (4, 3) of the coordinates of the vertices forming the plane
n: tensor of shape (3,) of the unit "inside" direction of the plane
vout1, vout2, vin: tensors of shape (3,) of the points forming the triangle, where
vin is "inside" the plane and vout1, vout2 are "outside"
Returns:
verts: tensor of shape (3, 3) containing the new vertices formed after clipping the
original intersectiong triangle (vout, vin1, vin2)
faces: tensor of shape (1, 3) defining the vertex indices forming
the single new triangle which is "inside" the plane formed after clipping
"""
device = plane.device
# point of intersection between plane and (vin, vout1)
pint1, a1 = plane_edge_point_of_intersection(plane, n, vin, vout1)
assert a1 >= -eps and a1 <= 1.0 + eps, a1
# point of intersection between plane and (vin, vout2)
pint2, a2 = plane_edge_point_of_intersection(plane, n, vin, vout2)
assert a2 >= -eps and a2 <= 1.0 + eps, a2
verts = torch.stack((vin, pint1, pint2), dim=0) # 3x3
faces = torch.tensor(
[
[0, 1, 2],
],
dtype=torch.int64,
device=device,
) # 1x3
return verts, faces
def clip_tri_by_plane(plane, n, tri_verts) -> Union[List, torch.Tensor]:
"""
Clip a trianglular face defined by tri_verts with a plane of inside "direction" n.
This function computes whether the triangle has one or two
or none points "outside" the plane.
Args:
plane: tensor of shape (4, 3) of the vertex coordinates of the plane
n: tensor of shape (3,) of the unit "inside" direction of the plane
tri_verts: tensor of shape (3, 3) of the vertex coordiantes of the the triangle faces
Returns:
tri_verts: tensor of shape (K, 3, 3) of the vertex coordinates of the triangles formed
after clipping. All K triangles are now "inside" the plane.
"""
v0, v1, v2 = tri_verts.unbind(0)
isin0, _ = is_inside(plane, n, v0)
isin1, _ = is_inside(plane, n, v1)
isin2, _ = is_inside(plane, n, v2)
if isin0 and isin1 and isin2:
# all in, no clipping, keep the old triangle face
return tri_verts.view(1, 3, 3)
elif (not isin0) and (not isin1) and (not isin2):
# all out, delete triangle
return []
else:
if isin0:
if isin1: # (isin0, isin1, not isin2)
verts, faces = clip_tri_by_plane_oneout(plane, n, v2, v0, v1)
return verts[faces]
elif isin2: # (isin0, not isin1, isin2)
verts, faces = clip_tri_by_plane_oneout(plane, n, v1, v0, v2)
return verts[faces]
else: # (isin0, not isin1, not isin2)
verts, faces = clip_tri_by_plane_twoout(plane, n, v1, v2, v0)
return verts[faces]
else:
if isin1 and isin2: # (not isin0, isin1, isin2)
verts, faces = clip_tri_by_plane_oneout(plane, n, v0, v1, v2)
return verts[faces]
elif isin1: # (not isin0, isin1, not isin2)
verts, faces = clip_tri_by_plane_twoout(plane, n, v0, v2, v1)
return verts[faces]
elif isin2: # (not isin0, not isin1, isin2)
verts, faces = clip_tri_by_plane_twoout(plane, n, v0, v1, v2)
return verts[faces]
# Should not be reached
return []
# -------------------------------------------------- #
# MAIN: BOX3D_OVERLAP #
# -------------------------------------------------- #
def box3d_overlap_naive(box1: torch.Tensor, box2: torch.Tensor):
"""
Computes the intersection of 3D boxes1 and boxes2.
Inputs boxes1, boxes2 are tensors of shape (8, 3) containing
the 8 corners of the boxes, as follows
(4) +---------+. (5)
| ` . | ` .
| (0) +---+-----+ (1)
| | | |
(7) +-----+---+. (6)|
` . | ` . |
(3) ` +---------+ (2)
Args:
box1: tensor of shape (8, 3) of the coordinates of the 1st box
box2: tensor of shape (8, 3) of the coordinates of the 2nd box
Returns:
vol: the volume of the intersecting convex shape
iou: the intersection over union which is simply
`iou = vol / (vol1 + vol2 - vol)`
"""
device = box1.device
# For boxes1 we compute the unit directions n1 corresponding to quad_faces
n1 = box_planar_dir(box1) # (6, 3)
# For boxes2 we compute the unit directions n2 corresponding to quad_faces
n2 = box_planar_dir(box2)
# We define triangle faces
vol1 = box_volume(box1)
vol2 = box_volume(box2)
tri_verts1 = get_tri_verts(box1) # (12, 3, 3)
plane_verts1 = get_plane_verts(box1) # (6, 4, 3)
tri_verts2 = get_tri_verts(box2) # (12, 3, 3)
plane_verts2 = get_plane_verts(box2) # (6, 4, 3)
num_planes = plane_verts1.shape[0] # (=6) based on our definition of planes
# Every triangle in box1 will be compared to each plane in box2.
# If the triangle is fully outside or fully inside, then it will remain as is
# If the triangle intersects with the (infinite) plane, it will be broken into
# subtriangles such that each subtriangle is either fully inside or outside the plane.
# Tris in Box1 -> Planes in Box2
for pidx in range(num_planes):
plane = plane_verts2[pidx]
nplane = n2[pidx]
tri_verts_updated = torch.zeros((0, 3, 3), dtype=torch.float32, device=device)
for i in range(tri_verts1.shape[0]):
tri = clip_tri_by_plane(plane, nplane, tri_verts1[i])
if len(tri) > 0:
tri_verts_updated = torch.cat((tri_verts_updated, tri), dim=0)
tri_verts1 = tri_verts_updated
# Tris in Box2 -> Planes in Box1
for pidx in range(num_planes):
plane = plane_verts1[pidx]
nplane = n1[pidx]
tri_verts_updated = torch.zeros((0, 3, 3), dtype=torch.float32, device=device)
for i in range(tri_verts2.shape[0]):
tri = clip_tri_by_plane(plane, nplane, tri_verts2[i])
if len(tri) > 0:
tri_verts_updated = torch.cat((tri_verts_updated, tri), dim=0)
tri_verts2 = tri_verts_updated
# remove triangles that are coplanar from the intersection as
# otherwise they would be doublecounting towards the volume
# this happens only if the original 3D boxes have common planes
# Since the resulting shape is convex and specifically composed of planar segments,
# each planar segment can belong either on box1 or box2 but not both.
# Without loss of generality, we assign shared planar segments to box1
keep2 = torch.ones((tri_verts2.shape[0],), device=device, dtype=torch.bool)
for i1 in range(tri_verts1.shape[0]):
for i2 in range(tri_verts2.shape[0]):
if (
coplanar_tri_faces(tri_verts1[i1], tri_verts2[i2])
and tri_verts_area(tri_verts1[i1]) > 1e-4
):
keep2[i2] = 0
keep2 = keep2.nonzero()[:, 0]
tri_verts2 = tri_verts2[keep2]
# intersecting shape
num_faces = tri_verts1.shape[0] + tri_verts2.shape[0]
num_verts = num_faces * 3 # V=F*3
overlap_faces = torch.arange(num_verts).view(num_faces, 3) # Fx3
overlap_tri_verts = torch.cat((tri_verts1, tri_verts2), dim=0) # Fx3x3
overlap_verts = overlap_tri_verts.view(num_verts, 3) # Vx3
# the volume of the convex hull defined by (overlap_verts, overlap_faces)
# can be defined as the sum of all the tetrahedrons formed where for each tetrahedron
# the base is the triangle and the apex is the center point of the convex hull
# See the math here: https://en.wikipedia.org/wiki/Tetrahedron#Volume
# we compute the center by computing the center point of each face
# and then averaging the face centers
ctr = overlap_tri_verts.mean(1).mean(0)
tetras = overlap_tri_verts - ctr.view(1, 1, 3)
vol = torch.sum(
tetras[:, 0] * torch.cross(tetras[:, 1], tetras[:, 2], dim=-1), dim=-1
)
vol = (vol.abs() / 6.0).sum()
iou = vol / (vol1 + vol2 - vol)
if DEBUG:
# save shapes
tri_faces = torch.tensor(_box_triangles, device=device, dtype=torch.int64)
save_obj("/tmp/output/shape1.obj", box1, tri_faces)
save_obj("/tmp/output/shape2.obj", box2, tri_faces)
if len(overlap_verts) > 0:
save_obj("/tmp/output/inters_shape.obj", overlap_verts, overlap_faces)
return vol, iou
# -------------------------------------------------- #
# HELPER FUNCTIONS FOR SAMPLING SOLUTION #
# -------------------------------------------------- #
def is_point_inside_box(box: torch.Tensor, points: torch.Tensor):
"""
Determines whether points are inside the boxes
Args:
box: tensor of shape (8, 3) of the corners of the boxes
points: tensor of shape (P, 3) of the points
Returns:
inside: bool tensor of shape (P,)
"""
device = box.device
P = points.shape[0]
n = box_planar_dir(box) # (6, 3)
box_planes = get_plane_verts(box) # (6, 4)
num_planes = box_planes.shape[0] # = 6
# a point p is inside the box if it "inside" all planes of the box
# so we run the checks
ins = torch.zeros((P, num_planes), device=device, dtype=torch.bool)
for i in range(num_planes):
is_in, _ = is_inside(box_planes[i], n[i], points, return_proj=False)
ins[:, i] = is_in
ins = ins.all(dim=1)
return ins
def sample_points_within_box(box: torch.Tensor, num_samples: int = 10):
"""
Sample points within a box defined by its 8 coordinates
Args:
box: tensor of shape (8, 3) of the box coordinates
num_samples: int defining the number of samples
Returns:
points: (num_samples, 3) of points inside the box
"""
assert box.shape[0] == 8 and box.shape[1] == 3
xyzmin = box.min(0).values.view(1, 3)
xyzmax = box.max(0).values.view(1, 3)
uvw = torch.rand((num_samples, 3), device=box.device)
points = uvw * (xyzmax - xyzmin) + xyzmin
# because the box is not axis aligned we need to check wether
# the points are within the box
num_points = 0
samples = []
while num_points < num_samples:
inside = is_point_inside_box(box, points)
samples.append(points[inside].view(-1, 3))
num_points += inside.sum()
samples = torch.cat(samples, dim=0)
return samples[1:num_samples]
# -------------------------------------------------- #
# MAIN: BOX3D_OVERLAP_SAMPLING #
# -------------------------------------------------- #
def box3d_overlap_sampling(
box1: torch.Tensor, box2: torch.Tensor, num_samples: int = 10000
):
"""
Computes the intersection of two boxes by sampling points
"""
vol1 = box_volume(box1)
vol2 = box_volume(box2)
points1 = sample_points_within_box(box1, num_samples=num_samples)
points2 = sample_points_within_box(box2, num_samples=num_samples)
isin21 = is_point_inside_box(box1, points2)
num21 = isin21.sum()
isin12 = is_point_inside_box(box2, points1)
num12 = isin12.sum()
assert num12 <= num_samples
assert num21 <= num_samples
inters = (vol1 * num12 + vol2 * num21) / 2.0
union = vol1 * num_samples + vol2 * num_samples - inters
return inters / union
| # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import pickle
import random
import unittest
from typing import List, Tuple, Union
import torch
import torch.nn.functional as F
from common_testing import TestCaseMixin, get_random_cuda_device, get_tests_dir
from pytorch3d.io import save_obj
from pytorch3d.ops.iou_box3d import _box_planes, _box_triangles, box3d_overlap
from pytorch3d.transforms.rotation_conversions import random_rotation
OBJECTRON_TO_PYTORCH3D_FACE_IDX = [0, 4, 6, 2, 1, 5, 7, 3]
DATA_DIR = get_tests_dir() / "data"
DEBUG = False
EPS = 1e-5
UNIT_BOX = [
[0, 0, 0],
[1, 0, 0],
[1, 1, 0],
[0, 1, 0],
[0, 0, 1],
[1, 0, 1],
[1, 1, 1],
[0, 1, 1],
]
class TestIoU3D(TestCaseMixin, unittest.TestCase):
def setUp(self) -> None:
super().setUp()
torch.manual_seed(1)
@staticmethod
def create_box(xyz, whl):
x, y, z = xyz
w, h, le = whl
verts = torch.tensor(
[
[x - w / 2.0, y - h / 2.0, z - le / 2.0],
[x + w / 2.0, y - h / 2.0, z - le / 2.0],
[x + w / 2.0, y + h / 2.0, z - le / 2.0],
[x - w / 2.0, y + h / 2.0, z - le / 2.0],
[x - w / 2.0, y - h / 2.0, z + le / 2.0],
[x + w / 2.0, y - h / 2.0, z + le / 2.0],
[x + w / 2.0, y + h / 2.0, z + le / 2.0],
[x - w / 2.0, y + h / 2.0, z + le / 2.0],
],
device=xyz.device,
dtype=torch.float32,
)
return verts
@staticmethod
def _box3d_overlap_naive_batched(boxes1, boxes2):
"""
Wrapper around box3d_overlap_naive to support
batched input
"""
N = boxes1.shape[0]
M = boxes2.shape[0]
vols = torch.zeros((N, M), dtype=torch.float32, device=boxes1.device)
ious = torch.zeros((N, M), dtype=torch.float32, device=boxes1.device)
for n in range(N):
for m in range(M):
vol, iou = box3d_overlap_naive(boxes1[n], boxes2[m])
vols[n, m] = vol
ious[n, m] = iou
return vols, ious
@staticmethod
def _box3d_overlap_sampling_batched(boxes1, boxes2, num_samples: int):
"""
Wrapper around box3d_overlap_sampling to support
batched input
"""
N = boxes1.shape[0]
M = boxes2.shape[0]
ious = torch.zeros((N, M), dtype=torch.float32, device=boxes1.device)
for n in range(N):
for m in range(M):
iou = box3d_overlap_sampling(boxes1[n], boxes2[m])
ious[n, m] = iou
return ious
def _test_iou(self, overlap_fn, device):
box1 = torch.tensor(
UNIT_BOX,
dtype=torch.float32,
device=device,
)
# 1st test: same box, iou = 1.0
vol, iou = overlap_fn(box1[None], box1[None])
self.assertClose(vol, torch.tensor([[1.0]], device=vol.device, dtype=vol.dtype))
self.assertClose(iou, torch.tensor([[1.0]], device=vol.device, dtype=vol.dtype))
# 2nd test
dd = random.random()
box2 = box1 + torch.tensor([[0.0, dd, 0.0]], device=device)
vol, iou = overlap_fn(box1[None], box2[None])
self.assertClose(
vol, torch.tensor([[1 - dd]], device=vol.device, dtype=vol.dtype)
)
# symmetry
vol, iou = overlap_fn(box2[None], box1[None])
self.assertClose(
vol, torch.tensor([[1 - dd]], device=vol.device, dtype=vol.dtype)
)
# 3rd test
dd = random.random()
box2 = box1 + torch.tensor([[dd, 0.0, 0.0]], device=device)
vol, _ = overlap_fn(box1[None], box2[None])
self.assertClose(
vol, torch.tensor([[1 - dd]], device=vol.device, dtype=vol.dtype)
)
# symmetry
vol, _ = overlap_fn(box2[None], box1[None])
self.assertClose(
vol, torch.tensor([[1 - dd]], device=vol.device, dtype=vol.dtype)
)
# 4th test
ddx, ddy, ddz = random.random(), random.random(), random.random()
box2 = box1 + torch.tensor([[ddx, ddy, ddz]], device=device)
vol, _ = overlap_fn(box1[None], box2[None])
self.assertClose(
vol,
torch.tensor(
[[(1 - ddx) * (1 - ddy) * (1 - ddz)]],
device=vol.device,
dtype=vol.dtype,
),
)
# symmetry
vol, _ = overlap_fn(box2[None], box1[None])
self.assertClose(
vol,
torch.tensor(
[[(1 - ddx) * (1 - ddy) * (1 - ddz)]],
device=vol.device,
dtype=vol.dtype,
),
)
# Also check IoU is 1 when computing overlap with the same shifted box
vol, iou = overlap_fn(box2[None], box2[None])
self.assertClose(iou, torch.tensor([[1.0]], device=vol.device, dtype=vol.dtype))
# 5th test
ddx, ddy, ddz = random.random(), random.random(), random.random()
box2 = box1 + torch.tensor([[ddx, ddy, ddz]], device=device)
RR = random_rotation(dtype=torch.float32, device=device)
box1r = box1 @ RR.transpose(0, 1)
box2r = box2 @ RR.transpose(0, 1)
vol, _ = overlap_fn(box1r[None], box2r[None])
self.assertClose(
vol,
torch.tensor(
[[(1 - ddx) * (1 - ddy) * (1 - ddz)]],
device=vol.device,
dtype=vol.dtype,
),
)
# symmetry
vol, _ = overlap_fn(box2r[None], box1r[None])
self.assertClose(
vol,
torch.tensor(
[[(1 - ddx) * (1 - ddy) * (1 - ddz)]],
device=vol.device,
dtype=vol.dtype,
),
)
# 6th test
ddx, ddy, ddz = random.random(), random.random(), random.random()
box2 = box1 + torch.tensor([[ddx, ddy, ddz]], device=device)
RR = random_rotation(dtype=torch.float32, device=device)
TT = torch.rand((1, 3), dtype=torch.float32, device=device)
box1r = box1 @ RR.transpose(0, 1) + TT
box2r = box2 @ RR.transpose(0, 1) + TT
vol, _ = overlap_fn(box1r[None], box2r[None])
self.assertClose(
vol,
torch.tensor(
[[(1 - ddx) * (1 - ddy) * (1 - ddz)]],
device=vol.device,
dtype=vol.dtype,
),
atol=1e-7,
)
# symmetry
vol, _ = overlap_fn(box2r[None], box1r[None])
self.assertClose(
vol,
torch.tensor(
[[(1 - ddx) * (1 - ddy) * (1 - ddz)]],
device=vol.device,
dtype=vol.dtype,
),
atol=1e-7,
)
# 7th test: hand coded example and test with meshlab output
# Meshlab procedure to compute volumes of shapes
# 1. Load a shape, then Filters
# -> Remeshing, Simplification, Reconstruction -> Convex Hull
# 2. Select the convex hull shape (This is important!)
# 3. Then Filters -> Quality Measure and Computation -> Compute Geometric Measures
# 3. Check for "Mesh Volume" in the stdout
box1r = torch.tensor(
[
[3.1673, -2.2574, 0.4817],
[4.6470, 0.2223, 2.4197],
[5.2200, 1.1844, 0.7510],
[3.7403, -1.2953, -1.1869],
[-4.9316, 2.5724, 0.4856],
[-3.4519, 5.0521, 2.4235],
[-2.8789, 6.0142, 0.7549],
[-4.3586, 3.5345, -1.1831],
],
device=device,
)
box2r = torch.tensor(
[
[0.5623, 4.0647, 3.4334],
[3.3584, 4.3191, 1.1791],
[3.0724, -5.9235, -0.3315],
[0.2763, -6.1779, 1.9229],
[-2.0773, 4.6121, 0.2213],
[0.7188, 4.8665, -2.0331],
[0.4328, -5.3761, -3.5436],
[-2.3633, -5.6305, -1.2893],
],
device=device,
)
# from Meshlab:
vol_inters = 33.558529
vol_box1 = 65.899010
vol_box2 = 156.386719
iou_mesh = vol_inters / (vol_box1 + vol_box2 - vol_inters)
vol, iou = overlap_fn(box1r[None], box2r[None])
self.assertClose(vol, torch.tensor([[vol_inters]], device=device), atol=1e-1)
self.assertClose(iou, torch.tensor([[iou_mesh]], device=device), atol=1e-1)
# symmetry
vol, iou = overlap_fn(box2r[None], box1r[None])
self.assertClose(vol, torch.tensor([[vol_inters]], device=device), atol=1e-1)
self.assertClose(iou, torch.tensor([[iou_mesh]], device=device), atol=1e-1)
# 8th test: compare with sampling
# create box1
ctrs = torch.rand((2, 3), device=device)
whl = torch.rand((2, 3), device=device) * 10.0 + 1.0
# box8a & box8b
box8a = self.create_box(ctrs[0], whl[0])
box8b = self.create_box(ctrs[1], whl[1])
RR1 = random_rotation(dtype=torch.float32, device=device)
TT1 = torch.rand((1, 3), dtype=torch.float32, device=device)
RR2 = random_rotation(dtype=torch.float32, device=device)
TT2 = torch.rand((1, 3), dtype=torch.float32, device=device)
box1r = box8a @ RR1.transpose(0, 1) + TT1
box2r = box8b @ RR2.transpose(0, 1) + TT2
vol, iou = overlap_fn(box1r[None], box2r[None])
iou_sampling = self._box3d_overlap_sampling_batched(
box1r[None], box2r[None], num_samples=10000
)
self.assertClose(iou, iou_sampling, atol=1e-2)
# symmetry
vol, iou = overlap_fn(box2r[None], box1r[None])
self.assertClose(iou, iou_sampling, atol=1e-2)
# 9th test: non overlapping boxes, iou = 0.0
box2 = box1 + torch.tensor([[0.0, 100.0, 0.0]], device=device)
vol, iou = overlap_fn(box1[None], box2[None])
self.assertClose(vol, torch.tensor([[0.0]], device=vol.device, dtype=vol.dtype))
self.assertClose(iou, torch.tensor([[0.0]], device=vol.device, dtype=vol.dtype))
# symmetry
vol, iou = overlap_fn(box2[None], box1[None])
self.assertClose(vol, torch.tensor([[0.0]], device=vol.device, dtype=vol.dtype))
self.assertClose(iou, torch.tensor([[0.0]], device=vol.device, dtype=vol.dtype))
# 10th test: Non coplanar verts in a plane
box10 = box1 + torch.rand((8, 3), dtype=torch.float32, device=device)
msg = "Plane vertices are not coplanar"
with self.assertRaisesRegex(ValueError, msg):
overlap_fn(box10[None], box10[None])
# 11th test: Skewed bounding boxes but all verts are coplanar
box_skew_1 = torch.tensor(
[
[0, 0, 0],
[1, 0, 0],
[1, 1, 0],
[0, 1, 0],
[-2, -2, 2],
[2, -2, 2],
[2, 2, 2],
[-2, 2, 2],
],
dtype=torch.float32,
device=device,
)
box_skew_2 = torch.tensor(
[
[2.015995, 0.695233, 2.152806],
[2.832533, 0.663448, 1.576389],
[2.675445, -0.309592, 1.407520],
[1.858907, -0.277806, 1.983936],
[-0.413922, 3.161758, 2.044343],
[2.852230, 3.034615, -0.261321],
[2.223878, -0.857545, -0.936800],
[-1.042273, -0.730402, 1.368864],
],
dtype=torch.float32,
device=device,
)
vol1 = 14.000
vol2 = 14.000005
vol_inters = 5.431122
iou = vol_inters / (vol1 + vol2 - vol_inters)
vols, ious = overlap_fn(box_skew_1[None], box_skew_2[None])
self.assertClose(vols, torch.tensor([[vol_inters]], device=device), atol=1e-1)
self.assertClose(ious, torch.tensor([[iou]], device=device), atol=1e-1)
# symmetry
vols, ious = overlap_fn(box_skew_2[None], box_skew_1[None])
self.assertClose(vols, torch.tensor([[vol_inters]], device=device), atol=1e-1)
self.assertClose(ious, torch.tensor([[iou]], device=device), atol=1e-1)
# 12th test: Zero area bounding box (from GH issue #992)
box12a = torch.tensor(
[
[-1.0000, -1.0000, -0.5000],
[1.0000, -1.0000, -0.5000],
[1.0000, 1.0000, -0.5000],
[-1.0000, 1.0000, -0.5000],
[-1.0000, -1.0000, 0.5000],
[1.0000, -1.0000, 0.5000],
[1.0000, 1.0000, 0.5000],
[-1.0000, 1.0000, 0.5000],
],
device=device,
dtype=torch.float32,
)
box12b = torch.tensor(
[
[0.0, 0.0, 0.0],
[0.0, 0.0, 0.0],
[0.0, 0.0, 0.0],
[0.0, 0.0, 0.0],
[0.0, 0.0, 0.0],
[0.0, 0.0, 0.0],
[0.0, 0.0, 0.0],
[0.0, 0.0, 0.0],
],
device=device,
dtype=torch.float32,
)
msg = "Planes have zero areas"
with self.assertRaisesRegex(ValueError, msg):
overlap_fn(box12a[None], box12b[None])
# symmetry
with self.assertRaisesRegex(ValueError, msg):
overlap_fn(box12b[None], box12a[None])
# 13th test: From GH issue #992
# Zero area coplanar face after intersection
ctrs = torch.tensor([[0.0, 0.0, 0.0], [-1.0, 1.0, 0.0]])
whl = torch.tensor([[2.0, 2.0, 2.0], [2.0, 2, 2]])
box13a = TestIoU3D.create_box(ctrs[0], whl[0])
box13b = TestIoU3D.create_box(ctrs[1], whl[1])
vol, iou = overlap_fn(box13a[None], box13b[None])
self.assertClose(vol, torch.tensor([[2.0]], device=vol.device, dtype=vol.dtype))
# 14th test: From GH issue #992
# Random rotation, same boxes, iou should be 1.0
corners = (
torch.tensor(
[
[-1.0, -1.0, -1.0],
[1.0, -1.0, -1.0],
[1.0, 1.0, -1.0],
[-1.0, 1.0, -1.0],
[-1.0, -1.0, 1.0],
[1.0, -1.0, 1.0],
[1.0, 1.0, 1.0],
[-1.0, 1.0, 1.0],
],
device=device,
dtype=torch.float32,
)
* 0.5
)
yaw = torch.tensor(0.185)
Rot = torch.tensor(
[
[torch.cos(yaw), 0.0, torch.sin(yaw)],
[0.0, 1.0, 0.0],
[-torch.sin(yaw), 0.0, torch.cos(yaw)],
],
dtype=torch.float32,
device=device,
)
corners = (Rot.mm(corners.t())).t()
vol, iou = overlap_fn(corners[None], corners[None])
self.assertClose(
iou, torch.tensor([[1.0]], device=vol.device, dtype=vol.dtype), atol=1e-2
)
# 15th test: From GH issue #1082
box15a = torch.tensor(
[
[-2.5629019, 4.13995749, -1.76344576],
[1.92329434, 4.28127117, -1.86155124],
[1.86994571, 5.97489644, -1.86155124],
[-2.61625053, 5.83358276, -1.76344576],
[-2.53123587, 4.14095496, -0.31397536],
[1.95496037, 4.28226864, -0.41208084],
[1.90161174, 5.97589391, -0.41208084],
[-2.5845845, 5.83458023, -0.31397536],
],
device=device,
dtype=torch.float32,
)
box15b = torch.tensor(
[
[-2.6256125, 4.13036357, -1.82893437],
[1.87201008, 4.25296695, -1.82893437],
[1.82562476, 5.95458116, -1.82893437],
[-2.67199782, 5.83197777, -1.82893437],
[-2.6256125, 4.13036357, -0.40095884],
[1.87201008, 4.25296695, -0.40095884],
[1.82562476, 5.95458116, -0.40095884],
[-2.67199782, 5.83197777, -0.40095884],
],
device=device,
dtype=torch.float32,
)
vol, iou = overlap_fn(box15a[None], box15b[None])
self.assertClose(
iou, torch.tensor([[0.91]], device=vol.device, dtype=vol.dtype), atol=1e-2
)
def _test_real_boxes(self, overlap_fn, device):
data_filename = "./real_boxes.pkl"
with open(DATA_DIR / data_filename, "rb") as f:
example = pickle.load(f)
verts1 = torch.FloatTensor(example["verts1"])
verts2 = torch.FloatTensor(example["verts2"])
boxes = torch.stack((verts1, verts2)).to(device)
iou_expected = torch.eye(2).to(device)
vol, iou = overlap_fn(boxes, boxes)
self.assertClose(iou, iou_expected)
def test_iou_naive(self):
device = get_random_cuda_device()
self._test_iou(self._box3d_overlap_naive_batched, device)
self._test_compare_objectron(self._box3d_overlap_naive_batched, device)
self._test_real_boxes(self._box3d_overlap_naive_batched, device)
def test_iou_cpu(self):
device = torch.device("cpu")
self._test_iou(box3d_overlap, device)
self._test_compare_objectron(box3d_overlap, device)
self._test_real_boxes(box3d_overlap, device)
def test_iou_cuda(self):
device = torch.device("cuda:0")
self._test_iou(box3d_overlap, device)
self._test_compare_objectron(box3d_overlap, device)
self._test_real_boxes(box3d_overlap, device)
def _test_compare_objectron(self, overlap_fn, device):
# Load saved objectron data
data_filename = "./objectron_vols_ious.pt"
objectron_vals = torch.load(DATA_DIR / data_filename)
boxes1 = objectron_vals["boxes1"]
boxes2 = objectron_vals["boxes2"]
vols_objectron = objectron_vals["vols"]
ious_objectron = objectron_vals["ious"]
boxes1 = boxes1.to(device=device, dtype=torch.float32)
boxes2 = boxes2.to(device=device, dtype=torch.float32)
# Convert vertex orderings from Objectron to PyTorch3D convention
idx = torch.tensor(
OBJECTRON_TO_PYTORCH3D_FACE_IDX, dtype=torch.int64, device=device
)
boxes1 = boxes1.index_select(index=idx, dim=1)
boxes2 = boxes2.index_select(index=idx, dim=1)
# Run PyTorch3D version
vols, ious = overlap_fn(boxes1, boxes2)
# Check values match
self.assertClose(vols_objectron, vols.cpu())
self.assertClose(ious_objectron, ious.cpu())
def test_batched_errors(self):
N, M = 5, 10
boxes1 = torch.randn((N, 8, 3))
boxes2 = torch.randn((M, 10, 3))
with self.assertRaisesRegex(ValueError, "(8, 3)"):
box3d_overlap(boxes1, boxes2)
def test_box_volume(self):
device = torch.device("cuda:0")
box1 = torch.tensor(
[
[3.1673, -2.2574, 0.4817],
[4.6470, 0.2223, 2.4197],
[5.2200, 1.1844, 0.7510],
[3.7403, -1.2953, -1.1869],
[-4.9316, 2.5724, 0.4856],
[-3.4519, 5.0521, 2.4235],
[-2.8789, 6.0142, 0.7549],
[-4.3586, 3.5345, -1.1831],
],
dtype=torch.float32,
device=device,
)
box2 = torch.tensor(
[
[0.5623, 4.0647, 3.4334],
[3.3584, 4.3191, 1.1791],
[3.0724, -5.9235, -0.3315],
[0.2763, -6.1779, 1.9229],
[-2.0773, 4.6121, 0.2213],
[0.7188, 4.8665, -2.0331],
[0.4328, -5.3761, -3.5436],
[-2.3633, -5.6305, -1.2893],
],
dtype=torch.float32,
device=device,
)
box3 = torch.tensor(
[
[0, 0, 0],
[1, 0, 0],
[1, 1, 0],
[0, 1, 0],
[0, 0, 1],
[1, 0, 1],
[1, 1, 1],
[0, 1, 1],
],
dtype=torch.float32,
device=device,
)
RR = random_rotation(dtype=torch.float32, device=device)
TT = torch.rand((1, 3), dtype=torch.float32, device=device)
box4 = box3 @ RR.transpose(0, 1) + TT
self.assertClose(box_volume(box1).cpu(), torch.tensor(65.899010), atol=1e-3)
self.assertClose(box_volume(box2).cpu(), torch.tensor(156.386719), atol=1e-3)
self.assertClose(box_volume(box3).cpu(), torch.tensor(1.0), atol=1e-3)
self.assertClose(box_volume(box4).cpu(), torch.tensor(1.0), atol=1e-3)
def test_box_planar_dir(self):
device = torch.device("cuda:0")
box1 = torch.tensor(
UNIT_BOX,
dtype=torch.float32,
device=device,
)
n1 = torch.tensor(
[
[0.0, 0.0, 1.0],
[0.0, -1.0, 0.0],
[0.0, 1.0, 0.0],
[1.0, 0.0, 0.0],
[-1.0, 0.0, 0.0],
[0.0, 0.0, -1.0],
],
device=device,
dtype=torch.float32,
)
RR = random_rotation(dtype=torch.float32, device=device)
TT = torch.rand((1, 3), dtype=torch.float32, device=device)
box2 = box1 @ RR.transpose(0, 1) + TT
n2 = n1 @ RR.transpose(0, 1)
self.assertClose(box_planar_dir(box1), n1)
self.assertClose(box_planar_dir(box2), n2)
@staticmethod
def iou_naive(N: int, M: int, device="cpu"):
box = torch.tensor(
[UNIT_BOX],
dtype=torch.float32,
device=device,
)
boxes1 = box + torch.randn((N, 1, 3), device=device)
boxes2 = box + torch.randn((M, 1, 3), device=device)
def output():
vol, iou = TestIoU3D._box3d_overlap_naive_batched(boxes1, boxes2)
return output
@staticmethod
def iou(N: int, M: int, device="cpu"):
box = torch.tensor(
[UNIT_BOX],
dtype=torch.float32,
device=device,
)
boxes1 = box + torch.randn((N, 1, 3), device=device)
boxes2 = box + torch.randn((M, 1, 3), device=device)
def output():
vol, iou = box3d_overlap(boxes1, boxes2)
return output
@staticmethod
def iou_sampling(N: int, M: int, num_samples: int, device="cpu"):
box = torch.tensor(
[UNIT_BOX],
dtype=torch.float32,
device=device,
)
boxes1 = box + torch.randn((N, 1, 3), device=device)
boxes2 = box + torch.randn((M, 1, 3), device=device)
def output():
_ = TestIoU3D._box3d_overlap_sampling_batched(boxes1, boxes2, num_samples)
return output
# -------------------------------------------------- #
# NAIVE IMPLEMENTATION #
# -------------------------------------------------- #
"""
The main functions below are:
* box3d_overlap_naive: which computes the exact IoU of box1 and box2
* box3d_overlap_sampling: which computes an approximate IoU of box1 and box2
by sampling points within the boxes
Note that both implementations currently do not support batching.
"""
# -------------------------------------------------- #
# Throughout this implementation, we assume that boxes
# are defined by their 8 corners in the following order
#
# (4) +---------+. (5)
# | ` . | ` .
# | (0) +---+-----+ (1)
# | | | |
# (7) +-----+---+. (6)|
# ` . | ` . |
# (3) ` +---------+ (2)
#
# -------------------------------------------------- #
# -------------------------------------------------- #
# HELPER FUNCTIONS FOR EXACT SOLUTION #
# -------------------------------------------------- #
def get_tri_verts(box: torch.Tensor) -> torch.Tensor:
"""
Return the vertex coordinates forming the triangles of the box.
The computation here resembles the Meshes data structure.
But since we only want this tiny functionality, we abstract it out.
Args:
box: tensor of shape (8, 3)
Returns:
tri_verts: tensor of shape (12, 3, 3)
"""
device = box.device
faces = torch.tensor(_box_triangles, device=device, dtype=torch.int64) # (12, 3)
tri_verts = box[faces] # (12, 3, 3)
return tri_verts
def get_plane_verts(box: torch.Tensor) -> torch.Tensor:
"""
Return the vertex coordinates forming the planes of the box.
The computation here resembles the Meshes data structure.
But since we only want this tiny functionality, we abstract it out.
Args:
box: tensor of shape (8, 3)
Returns:
plane_verts: tensor of shape (6, 4, 3)
"""
device = box.device
faces = torch.tensor(_box_planes, device=device, dtype=torch.int64) # (6, 4)
plane_verts = box[faces] # (6, 4, 3)
return plane_verts
def box_planar_dir(box: torch.Tensor, eps: float = 1e-4) -> torch.Tensor:
"""
Finds the unit vector n which is perpendicular to each plane in the box
and points towards the inside of the box.
The planes are defined by `_box_planes`.
Since the shape is convex, we define the interior to be the direction
pointing to the center of the shape.
Args:
box: tensor of shape (8, 3) of the vertices of the 3D box
Returns:
n: tensor of shape (6,) of the unit vector orthogonal to the face pointing
towards the interior of the shape
"""
assert box.shape[0] == 8 and box.shape[1] == 3
# center point of each box
ctr = box.mean(0).view(1, 3)
verts = get_plane_verts(box) # (6, 4, 3)
v0, v1, v2, v3 = verts.unbind(1) # each v of shape (6, 3)
# We project the ctr on the plane defined by (v0, v1, v2, v3)
# We define e0 to be the edge connecting (v1, v0)
# We define e1 to be the edge connecting (v2, v0)
# And n is the cross product of e0, e1, either pointing "inside" or not.
e0 = F.normalize(v1 - v0, dim=-1)
e1 = F.normalize(v2 - v0, dim=-1)
n = F.normalize(torch.cross(e0, e1, dim=-1), dim=-1)
# Check all verts are coplanar
if not ((v3 - v0).unsqueeze(1).bmm(n.unsqueeze(2)).abs() < eps).all().item():
msg = "Plane vertices are not coplanar"
raise ValueError(msg)
# Check all faces have non zero area
area1 = torch.cross(v1 - v0, v2 - v0, dim=-1).norm(dim=-1) / 2
area2 = torch.cross(v3 - v0, v2 - v0, dim=-1).norm(dim=-1) / 2
if (area1 < eps).any().item() or (area2 < eps).any().item():
msg = "Planes have zero areas"
raise ValueError(msg)
# We can write: `ctr = v0 + a * e0 + b * e1 + c * n`, (1).
# With <e0, n> = 0 and <e1, n> = 0, where <.,.> refers to the dot product,
# since that e0 is orthogonal to n. Same for e1.
"""
# Below is how one would solve for (a, b, c)
# Solving for (a, b)
numF = verts.shape[0]
A = torch.ones((numF, 2, 2), dtype=torch.float32, device=device)
B = torch.ones((numF, 2), dtype=torch.float32, device=device)
A[:, 0, 1] = (e0 * e1).sum(-1)
A[:, 1, 0] = (e0 * e1).sum(-1)
B[:, 0] = ((ctr - v0) * e0).sum(-1)
B[:, 1] = ((ctr - v1) * e1).sum(-1)
ab = torch.linalg.solve(A, B) # (numF, 2)
a, b = ab.unbind(1)
# solving for c
c = ((ctr - v0 - a.view(numF, 1) * e0 - b.view(numF, 1) * e1) * n).sum(-1)
"""
# Since we know that <e0, n> = 0 and <e1, n> = 0 (e0 and e1 are orthogonal to n),
# the above solution is equivalent to
c = ((ctr - v0) * n).sum(-1)
# If c is negative, then we revert the direction of n such that n points "inside"
negc = c < 0.0
n[negc] *= -1.0
# c[negc] *= -1.0
# Now (a, b, c) is the solution to (1)
return n
def tri_verts_area(tri_verts: torch.Tensor) -> torch.Tensor:
"""
Computes the area of the triangle faces in tri_verts
Args:
tri_verts: tensor of shape (T, 3, 3)
Returns:
areas: the area of the triangles (T, 1)
"""
add_dim = False
if tri_verts.ndim == 2:
tri_verts = tri_verts.unsqueeze(0)
add_dim = True
v0, v1, v2 = tri_verts.unbind(1)
areas = torch.cross(v1 - v0, v2 - v0, dim=-1).norm(dim=-1) / 2.0
if add_dim:
areas = areas[0]
return areas
def box_volume(box: torch.Tensor) -> torch.Tensor:
"""
Computes the volume of each box in boxes.
The volume of each box is the sum of all the tetrahedrons
formed by the faces of the box. The face of the box is the base of
that tetrahedron and the center point of the box is the apex.
In other words, vol(box) = sum_i A_i * d_i / 3,
where A_i is the area of the i-th face and d_i is the
distance of the apex from the face.
We use the equivalent dot/cross product formulation.
Read https://en.wikipedia.org/wiki/Tetrahedron#Volume
Args:
box: tensor of shape (8, 3) containing the vertices
of the 3D box
Returns:
vols: the volume of the box
"""
assert box.shape[0] == 8 and box.shape[1] == 3
# Compute the center point of each box
ctr = box.mean(0).view(1, 1, 3)
# Extract the coordinates of the faces for each box
tri_verts = get_tri_verts(box)
# Set the origin of the coordinate system to coincide
# with the apex of the tetrahedron to simplify the volume calculation
# See https://en.wikipedia.org/wiki/Tetrahedron#Volume
tri_verts = tri_verts - ctr
# Compute the volume of each box using the dot/cross product formula
vols = torch.sum(
tri_verts[:, 0] * torch.cross(tri_verts[:, 1], tri_verts[:, 2], dim=-1),
dim=-1,
)
vols = (vols.abs() / 6.0).sum()
return vols
def coplanar_tri_faces(tri1: torch.Tensor, tri2: torch.Tensor, eps: float = EPS):
"""
Determines whether two triangle faces in 3D are coplanar
Args:
tri1: tensor of shape (3, 3) of the vertices of the 1st triangle
tri2: tensor of shape (3, 3) of the vertices of the 2nd triangle
Returns:
is_coplanar: bool
"""
v0, v1, v2 = tri1.unbind(0)
e0 = F.normalize(v1 - v0, dim=0)
e1 = F.normalize(v2 - v0, dim=0)
e2 = F.normalize(torch.cross(e0, e1), dim=0)
coplanar2 = torch.zeros((3,), dtype=torch.bool, device=tri1.device)
for i in range(3):
if (tri2[i] - v0).dot(e2).abs() < eps:
coplanar2[i] = 1
coplanar2 = coplanar2.all()
return coplanar2
def is_inside(
plane: torch.Tensor,
n: torch.Tensor,
points: torch.Tensor,
return_proj: bool = True,
eps: float = EPS,
):
"""
Computes whether point is "inside" the plane.
The definition of "inside" means that the point
has a positive component in the direction of the plane normal defined by n.
For example,
plane
|
| . (A)
|--> n
|
.(B) |
Point (A) is "inside" the plane, while point (B) is "outside" the plane.
Args:
plane: tensor of shape (4,3) of vertices of a box plane
n: tensor of shape (3,) of the unit "inside" direction on the plane
points: tensor of shape (P, 3) of coordinates of a point
return_proj: bool whether to return the projected point on the plane
Returns:
is_inside: bool of shape (P,) of whether point is inside
p_proj: tensor of shape (P, 3) of the projected point on plane
"""
device = plane.device
v0, v1, v2, v3 = plane
e0 = F.normalize(v1 - v0, dim=0)
e1 = F.normalize(v2 - v0, dim=0)
if not torch.allclose(e0.dot(n), torch.zeros((1,), device=device), atol=1e-6):
raise ValueError("Input n is not perpendicular to the plane")
if not torch.allclose(e1.dot(n), torch.zeros((1,), device=device), atol=1e-6):
raise ValueError("Input n is not perpendicular to the plane")
add_dim = False
if points.ndim == 1:
points = points.unsqueeze(0)
add_dim = True
assert points.shape[1] == 3
# Every point p can be written as p = v0 + a e0 + b e1 + c n
# If return_proj is True, we need to solve for (a, b)
p_proj = None
if return_proj:
# solving for (a, b)
A = torch.tensor(
[[1.0, e0.dot(e1)], [e0.dot(e1), 1.0]], dtype=torch.float32, device=device
)
B = torch.zeros((2, points.shape[0]), dtype=torch.float32, device=device)
B[0, :] = torch.sum((points - v0.view(1, 3)) * e0.view(1, 3), dim=-1)
B[1, :] = torch.sum((points - v0.view(1, 3)) * e1.view(1, 3), dim=-1)
ab = A.inverse() @ B # (2, P)
p_proj = v0.view(1, 3) + ab.transpose(0, 1) @ torch.stack((e0, e1), dim=0)
# solving for c
# c = (point - v0 - a * e0 - b * e1).dot(n)
c = torch.sum((points - v0.view(1, 3)) * n.view(1, 3), dim=-1)
ins = c > -eps
if add_dim:
assert p_proj.shape[0] == 1
p_proj = p_proj[0]
return ins, p_proj
def plane_edge_point_of_intersection(plane, n, p0, p1):
"""
Finds the point of intersection between a box plane and
a line segment connecting (p0, p1).
The plane is assumed to be infinite long.
Args:
plane: tensor of shape (4, 3) of the coordinates of the vertices defining the plane
n: tensor of shape (3,) of the unit direction perpendicular on the plane
(Note that we could compute n but since it's computed in the main
body of the function, we save time by feeding it in. For the purpose
of this function, it's not important that n points "inside" the shape.)
p0, p1: tensors of shape (3,), (3,)
Returns:
p: tensor of shape (3,) of the coordinates of the point of intersection
a: scalar such that p = p0 + a*(p1-p0)
"""
# The point of intersection can be parametrized
# p = p0 + a (p1 - p0) where a in [0, 1]
# We want to find a such that p is on plane
# <p - v0, n> = 0
v0, v1, v2, v3 = plane
a = -(p0 - v0).dot(n) / (p1 - p0).dot(n)
p = p0 + a * (p1 - p0)
return p, a
"""
The three following functions support clipping a triangle face by a plane.
They contain the following cases: (a) the triangle has one point "outside" the plane and
(b) the triangle has two points "outside" the plane.
This logic follows the logic of clipping triangles when they intersect the image plane while
rendering.
"""
def clip_tri_by_plane_oneout(
plane: torch.Tensor,
n: torch.Tensor,
vout: torch.Tensor,
vin1: torch.Tensor,
vin2: torch.Tensor,
eps: float = EPS,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Case (a).
Clips triangle by plane when vout is outside plane, and vin1, vin2, is inside
In this case, only one vertex of the triangle is outside the plane.
Clip the triangle into a quadrilateral, and then split into two triangles
Args:
plane: tensor of shape (4, 3) of the coordinates of the vertices forming the plane
n: tensor of shape (3,) of the unit "inside" direction of the plane
vout, vin1, vin2: tensors of shape (3,) of the points forming the triangle, where
vout is "outside" the plane and vin1, vin2 are "inside"
Returns:
verts: tensor of shape (4, 3) containing the new vertices formed after clipping the
original intersecting triangle (vout, vin1, vin2)
faces: tensor of shape (2, 3) defining the vertex indices forming the two new triangles
which are "inside" the plane formed after clipping
"""
device = plane.device
# point of intersection between plane and (vin1, vout)
pint1, a1 = plane_edge_point_of_intersection(plane, n, vin1, vout)
assert a1 >= -eps and a1 <= 1.0 + eps, a1
# point of intersection between plane and (vin2, vout)
pint2, a2 = plane_edge_point_of_intersection(plane, n, vin2, vout)
assert a2 >= -eps and a2 <= 1.0 + eps, a2
verts = torch.stack((vin1, pint1, pint2, vin2), dim=0) # 4x3
faces = torch.tensor(
[[0, 1, 2], [0, 2, 3]], dtype=torch.int64, device=device
) # 2x3
return verts, faces
def clip_tri_by_plane_twoout(
plane: torch.Tensor,
n: torch.Tensor,
vout1: torch.Tensor,
vout2: torch.Tensor,
vin: torch.Tensor,
eps: float = EPS,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Case (b).
Clips face by plane when vout1, vout2 are outside plane, and vin1 is inside
In this case, only one vertex of the triangle is inside the plane.
Args:
plane: tensor of shape (4, 3) of the coordinates of the vertices forming the plane
n: tensor of shape (3,) of the unit "inside" direction of the plane
vout1, vout2, vin: tensors of shape (3,) of the points forming the triangle, where
vin is "inside" the plane and vout1, vout2 are "outside"
Returns:
verts: tensor of shape (3, 3) containing the new vertices formed after clipping the
original intersectiong triangle (vout, vin1, vin2)
faces: tensor of shape (1, 3) defining the vertex indices forming
the single new triangle which is "inside" the plane formed after clipping
"""
device = plane.device
# point of intersection between plane and (vin, vout1)
pint1, a1 = plane_edge_point_of_intersection(plane, n, vin, vout1)
assert a1 >= -eps and a1 <= 1.0 + eps, a1
# point of intersection between plane and (vin, vout2)
pint2, a2 = plane_edge_point_of_intersection(plane, n, vin, vout2)
assert a2 >= -eps and a2 <= 1.0 + eps, a2
verts = torch.stack((vin, pint1, pint2), dim=0) # 3x3
faces = torch.tensor(
[
[0, 1, 2],
],
dtype=torch.int64,
device=device,
) # 1x3
return verts, faces
def clip_tri_by_plane(plane, n, tri_verts) -> Union[List, torch.Tensor]:
"""
Clip a trianglular face defined by tri_verts with a plane of inside "direction" n.
This function computes whether the triangle has one or two
or none points "outside" the plane.
Args:
plane: tensor of shape (4, 3) of the vertex coordinates of the plane
n: tensor of shape (3,) of the unit "inside" direction of the plane
tri_verts: tensor of shape (3, 3) of the vertex coordiantes of the the triangle faces
Returns:
tri_verts: tensor of shape (K, 3, 3) of the vertex coordinates of the triangles formed
after clipping. All K triangles are now "inside" the plane.
"""
v0, v1, v2 = tri_verts.unbind(0)
isin0, _ = is_inside(plane, n, v0)
isin1, _ = is_inside(plane, n, v1)
isin2, _ = is_inside(plane, n, v2)
if isin0 and isin1 and isin2:
# all in, no clipping, keep the old triangle face
return tri_verts.view(1, 3, 3)
elif (not isin0) and (not isin1) and (not isin2):
# all out, delete triangle
return []
else:
if isin0:
if isin1: # (isin0, isin1, not isin2)
verts, faces = clip_tri_by_plane_oneout(plane, n, v2, v0, v1)
return verts[faces]
elif isin2: # (isin0, not isin1, isin2)
verts, faces = clip_tri_by_plane_oneout(plane, n, v1, v0, v2)
return verts[faces]
else: # (isin0, not isin1, not isin2)
verts, faces = clip_tri_by_plane_twoout(plane, n, v1, v2, v0)
return verts[faces]
else:
if isin1 and isin2: # (not isin0, isin1, isin2)
verts, faces = clip_tri_by_plane_oneout(plane, n, v0, v1, v2)
return verts[faces]
elif isin1: # (not isin0, isin1, not isin2)
verts, faces = clip_tri_by_plane_twoout(plane, n, v0, v2, v1)
return verts[faces]
elif isin2: # (not isin0, not isin1, isin2)
verts, faces = clip_tri_by_plane_twoout(plane, n, v0, v1, v2)
return verts[faces]
# Should not be reached
return []
# -------------------------------------------------- #
# MAIN: BOX3D_OVERLAP #
# -------------------------------------------------- #
def box3d_overlap_naive(box1: torch.Tensor, box2: torch.Tensor):
"""
Computes the intersection of 3D boxes1 and boxes2.
Inputs boxes1, boxes2 are tensors of shape (8, 3) containing
the 8 corners of the boxes, as follows
(4) +---------+. (5)
| ` . | ` .
| (0) +---+-----+ (1)
| | | |
(7) +-----+---+. (6)|
` . | ` . |
(3) ` +---------+ (2)
Args:
box1: tensor of shape (8, 3) of the coordinates of the 1st box
box2: tensor of shape (8, 3) of the coordinates of the 2nd box
Returns:
vol: the volume of the intersecting convex shape
iou: the intersection over union which is simply
`iou = vol / (vol1 + vol2 - vol)`
"""
device = box1.device
# For boxes1 we compute the unit directions n1 corresponding to quad_faces
n1 = box_planar_dir(box1) # (6, 3)
# For boxes2 we compute the unit directions n2 corresponding to quad_faces
n2 = box_planar_dir(box2)
# We define triangle faces
vol1 = box_volume(box1)
vol2 = box_volume(box2)
tri_verts1 = get_tri_verts(box1) # (12, 3, 3)
plane_verts1 = get_plane_verts(box1) # (6, 4, 3)
tri_verts2 = get_tri_verts(box2) # (12, 3, 3)
plane_verts2 = get_plane_verts(box2) # (6, 4, 3)
num_planes = plane_verts1.shape[0] # (=6) based on our definition of planes
# Every triangle in box1 will be compared to each plane in box2.
# If the triangle is fully outside or fully inside, then it will remain as is
# If the triangle intersects with the (infinite) plane, it will be broken into
# subtriangles such that each subtriangle is either fully inside or outside the plane.
# Tris in Box1 -> Planes in Box2
for pidx in range(num_planes):
plane = plane_verts2[pidx]
nplane = n2[pidx]
tri_verts_updated = torch.zeros((0, 3, 3), dtype=torch.float32, device=device)
for i in range(tri_verts1.shape[0]):
tri = clip_tri_by_plane(plane, nplane, tri_verts1[i])
if len(tri) > 0:
tri_verts_updated = torch.cat((tri_verts_updated, tri), dim=0)
tri_verts1 = tri_verts_updated
# Tris in Box2 -> Planes in Box1
for pidx in range(num_planes):
plane = plane_verts1[pidx]
nplane = n1[pidx]
tri_verts_updated = torch.zeros((0, 3, 3), dtype=torch.float32, device=device)
for i in range(tri_verts2.shape[0]):
tri = clip_tri_by_plane(plane, nplane, tri_verts2[i])
if len(tri) > 0:
tri_verts_updated = torch.cat((tri_verts_updated, tri), dim=0)
tri_verts2 = tri_verts_updated
# remove triangles that are coplanar from the intersection as
# otherwise they would be doublecounting towards the volume
# this happens only if the original 3D boxes have common planes
# Since the resulting shape is convex and specifically composed of planar segments,
# each planar segment can belong either on box1 or box2 but not both.
# Without loss of generality, we assign shared planar segments to box1
keep2 = torch.ones((tri_verts2.shape[0],), device=device, dtype=torch.bool)
for i1 in range(tri_verts1.shape[0]):
for i2 in range(tri_verts2.shape[0]):
if (
coplanar_tri_faces(tri_verts1[i1], tri_verts2[i2])
and tri_verts_area(tri_verts1[i1]) > 1e-4
):
keep2[i2] = 0
keep2 = keep2.nonzero()[:, 0]
tri_verts2 = tri_verts2[keep2]
# intersecting shape
num_faces = tri_verts1.shape[0] + tri_verts2.shape[0]
num_verts = num_faces * 3 # V=F*3
overlap_faces = torch.arange(num_verts).view(num_faces, 3) # Fx3
overlap_tri_verts = torch.cat((tri_verts1, tri_verts2), dim=0) # Fx3x3
overlap_verts = overlap_tri_verts.view(num_verts, 3) # Vx3
# the volume of the convex hull defined by (overlap_verts, overlap_faces)
# can be defined as the sum of all the tetrahedrons formed where for each tetrahedron
# the base is the triangle and the apex is the center point of the convex hull
# See the math here: https://en.wikipedia.org/wiki/Tetrahedron#Volume
# we compute the center by computing the center point of each face
# and then averaging the face centers
ctr = overlap_tri_verts.mean(1).mean(0)
tetras = overlap_tri_verts - ctr.view(1, 1, 3)
vol = torch.sum(
tetras[:, 0] * torch.cross(tetras[:, 1], tetras[:, 2], dim=-1), dim=-1
)
vol = (vol.abs() / 6.0).sum()
iou = vol / (vol1 + vol2 - vol)
if DEBUG:
# save shapes
tri_faces = torch.tensor(_box_triangles, device=device, dtype=torch.int64)
save_obj("/tmp/output/shape1.obj", box1, tri_faces)
save_obj("/tmp/output/shape2.obj", box2, tri_faces)
if len(overlap_verts) > 0:
save_obj("/tmp/output/inters_shape.obj", overlap_verts, overlap_faces)
return vol, iou
# -------------------------------------------------- #
# HELPER FUNCTIONS FOR SAMPLING SOLUTION #
# -------------------------------------------------- #
def is_point_inside_box(box: torch.Tensor, points: torch.Tensor):
"""
Determines whether points are inside the boxes
Args:
box: tensor of shape (8, 3) of the corners of the boxes
points: tensor of shape (P, 3) of the points
Returns:
inside: bool tensor of shape (P,)
"""
device = box.device
P = points.shape[0]
n = box_planar_dir(box) # (6, 3)
box_planes = get_plane_verts(box) # (6, 4)
num_planes = box_planes.shape[0] # = 6
# a point p is inside the box if it "inside" all planes of the box
# so we run the checks
ins = torch.zeros((P, num_planes), device=device, dtype=torch.bool)
for i in range(num_planes):
is_in, _ = is_inside(box_planes[i], n[i], points, return_proj=False)
ins[:, i] = is_in
ins = ins.all(dim=1)
return ins
def sample_points_within_box(box: torch.Tensor, num_samples: int = 10):
"""
Sample points within a box defined by its 8 coordinates
Args:
box: tensor of shape (8, 3) of the box coordinates
num_samples: int defining the number of samples
Returns:
points: (num_samples, 3) of points inside the box
"""
assert box.shape[0] == 8 and box.shape[1] == 3
xyzmin = box.min(0).values.view(1, 3)
xyzmax = box.max(0).values.view(1, 3)
uvw = torch.rand((num_samples, 3), device=box.device)
points = uvw * (xyzmax - xyzmin) + xyzmin
# because the box is not axis aligned we need to check wether
# the points are within the box
num_points = 0
samples = []
while num_points < num_samples:
inside = is_point_inside_box(box, points)
samples.append(points[inside].view(-1, 3))
num_points += inside.sum()
samples = torch.cat(samples, dim=0)
return samples[1:num_samples]
# -------------------------------------------------- #
# MAIN: BOX3D_OVERLAP_SAMPLING #
# -------------------------------------------------- #
def box3d_overlap_sampling(
box1: torch.Tensor, box2: torch.Tensor, num_samples: int = 10000
):
"""
Computes the intersection of two boxes by sampling points
"""
vol1 = box_volume(box1)
vol2 = box_volume(box2)
points1 = sample_points_within_box(box1, num_samples=num_samples)
points2 = sample_points_within_box(box2, num_samples=num_samples)
isin21 = is_point_inside_box(box1, points2)
num21 = isin21.sum()
isin12 = is_point_inside_box(box2, points1)
num12 = isin12.sum()
assert num12 <= num_samples
assert num21 <= num_samples
inters = (vol1 * num12 + vol2 * num21) / 2.0
union = vol1 * num_samples + vol2 * num_samples - inters
return inters / union | en | 0.837267 | # Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. Wrapper around box3d_overlap_naive to support batched input Wrapper around box3d_overlap_sampling to support batched input # 1st test: same box, iou = 1.0 # 2nd test # symmetry # 3rd test # symmetry # 4th test # symmetry # Also check IoU is 1 when computing overlap with the same shifted box # 5th test # symmetry # 6th test # symmetry # 7th test: hand coded example and test with meshlab output # Meshlab procedure to compute volumes of shapes # 1. Load a shape, then Filters # -> Remeshing, Simplification, Reconstruction -> Convex Hull # 2. Select the convex hull shape (This is important!) # 3. Then Filters -> Quality Measure and Computation -> Compute Geometric Measures # 3. Check for "Mesh Volume" in the stdout # from Meshlab: # symmetry # 8th test: compare with sampling # create box1 # box8a & box8b # symmetry # 9th test: non overlapping boxes, iou = 0.0 # symmetry # 10th test: Non coplanar verts in a plane # 11th test: Skewed bounding boxes but all verts are coplanar # symmetry # 12th test: Zero area bounding box (from GH issue #992) # symmetry # 13th test: From GH issue #992 # Zero area coplanar face after intersection # 14th test: From GH issue #992 # Random rotation, same boxes, iou should be 1.0 # 15th test: From GH issue #1082 # Load saved objectron data # Convert vertex orderings from Objectron to PyTorch3D convention # Run PyTorch3D version # Check values match # -------------------------------------------------- # # NAIVE IMPLEMENTATION # # -------------------------------------------------- # The main functions below are: * box3d_overlap_naive: which computes the exact IoU of box1 and box2 * box3d_overlap_sampling: which computes an approximate IoU of box1 and box2 by sampling points within the boxes Note that both implementations currently do not support batching. # -------------------------------------------------- # # Throughout this implementation, we assume that boxes # are defined by their 8 corners in the following order # # (4) +---------+. (5) # | ` . | ` . # | (0) +---+-----+ (1) # | | | | # (7) +-----+---+. (6)| # ` . | ` . | # (3) ` +---------+ (2) # # -------------------------------------------------- # # -------------------------------------------------- # # HELPER FUNCTIONS FOR EXACT SOLUTION # # -------------------------------------------------- # Return the vertex coordinates forming the triangles of the box. The computation here resembles the Meshes data structure. But since we only want this tiny functionality, we abstract it out. Args: box: tensor of shape (8, 3) Returns: tri_verts: tensor of shape (12, 3, 3) # (12, 3) # (12, 3, 3) Return the vertex coordinates forming the planes of the box. The computation here resembles the Meshes data structure. But since we only want this tiny functionality, we abstract it out. Args: box: tensor of shape (8, 3) Returns: plane_verts: tensor of shape (6, 4, 3) # (6, 4) # (6, 4, 3) Finds the unit vector n which is perpendicular to each plane in the box and points towards the inside of the box. The planes are defined by `_box_planes`. Since the shape is convex, we define the interior to be the direction pointing to the center of the shape. Args: box: tensor of shape (8, 3) of the vertices of the 3D box Returns: n: tensor of shape (6,) of the unit vector orthogonal to the face pointing towards the interior of the shape # center point of each box # (6, 4, 3) # each v of shape (6, 3) # We project the ctr on the plane defined by (v0, v1, v2, v3) # We define e0 to be the edge connecting (v1, v0) # We define e1 to be the edge connecting (v2, v0) # And n is the cross product of e0, e1, either pointing "inside" or not. # Check all verts are coplanar # Check all faces have non zero area # We can write: `ctr = v0 + a * e0 + b * e1 + c * n`, (1). # With <e0, n> = 0 and <e1, n> = 0, where <.,.> refers to the dot product, # since that e0 is orthogonal to n. Same for e1. # Below is how one would solve for (a, b, c) # Solving for (a, b) numF = verts.shape[0] A = torch.ones((numF, 2, 2), dtype=torch.float32, device=device) B = torch.ones((numF, 2), dtype=torch.float32, device=device) A[:, 0, 1] = (e0 * e1).sum(-1) A[:, 1, 0] = (e0 * e1).sum(-1) B[:, 0] = ((ctr - v0) * e0).sum(-1) B[:, 1] = ((ctr - v1) * e1).sum(-1) ab = torch.linalg.solve(A, B) # (numF, 2) a, b = ab.unbind(1) # solving for c c = ((ctr - v0 - a.view(numF, 1) * e0 - b.view(numF, 1) * e1) * n).sum(-1) # Since we know that <e0, n> = 0 and <e1, n> = 0 (e0 and e1 are orthogonal to n), # the above solution is equivalent to # If c is negative, then we revert the direction of n such that n points "inside" # c[negc] *= -1.0 # Now (a, b, c) is the solution to (1) Computes the area of the triangle faces in tri_verts Args: tri_verts: tensor of shape (T, 3, 3) Returns: areas: the area of the triangles (T, 1) Computes the volume of each box in boxes. The volume of each box is the sum of all the tetrahedrons formed by the faces of the box. The face of the box is the base of that tetrahedron and the center point of the box is the apex. In other words, vol(box) = sum_i A_i * d_i / 3, where A_i is the area of the i-th face and d_i is the distance of the apex from the face. We use the equivalent dot/cross product formulation. Read https://en.wikipedia.org/wiki/Tetrahedron#Volume Args: box: tensor of shape (8, 3) containing the vertices of the 3D box Returns: vols: the volume of the box # Compute the center point of each box # Extract the coordinates of the faces for each box # Set the origin of the coordinate system to coincide # with the apex of the tetrahedron to simplify the volume calculation # See https://en.wikipedia.org/wiki/Tetrahedron#Volume # Compute the volume of each box using the dot/cross product formula Determines whether two triangle faces in 3D are coplanar Args: tri1: tensor of shape (3, 3) of the vertices of the 1st triangle tri2: tensor of shape (3, 3) of the vertices of the 2nd triangle Returns: is_coplanar: bool Computes whether point is "inside" the plane. The definition of "inside" means that the point has a positive component in the direction of the plane normal defined by n. For example, plane | | . (A) |--> n | .(B) | Point (A) is "inside" the plane, while point (B) is "outside" the plane. Args: plane: tensor of shape (4,3) of vertices of a box plane n: tensor of shape (3,) of the unit "inside" direction on the plane points: tensor of shape (P, 3) of coordinates of a point return_proj: bool whether to return the projected point on the plane Returns: is_inside: bool of shape (P,) of whether point is inside p_proj: tensor of shape (P, 3) of the projected point on plane # Every point p can be written as p = v0 + a e0 + b e1 + c n # If return_proj is True, we need to solve for (a, b) # solving for (a, b) # (2, P) # solving for c # c = (point - v0 - a * e0 - b * e1).dot(n) Finds the point of intersection between a box plane and a line segment connecting (p0, p1). The plane is assumed to be infinite long. Args: plane: tensor of shape (4, 3) of the coordinates of the vertices defining the plane n: tensor of shape (3,) of the unit direction perpendicular on the plane (Note that we could compute n but since it's computed in the main body of the function, we save time by feeding it in. For the purpose of this function, it's not important that n points "inside" the shape.) p0, p1: tensors of shape (3,), (3,) Returns: p: tensor of shape (3,) of the coordinates of the point of intersection a: scalar such that p = p0 + a*(p1-p0) # The point of intersection can be parametrized # p = p0 + a (p1 - p0) where a in [0, 1] # We want to find a such that p is on plane # <p - v0, n> = 0 The three following functions support clipping a triangle face by a plane. They contain the following cases: (a) the triangle has one point "outside" the plane and (b) the triangle has two points "outside" the plane. This logic follows the logic of clipping triangles when they intersect the image plane while rendering. Case (a). Clips triangle by plane when vout is outside plane, and vin1, vin2, is inside In this case, only one vertex of the triangle is outside the plane. Clip the triangle into a quadrilateral, and then split into two triangles Args: plane: tensor of shape (4, 3) of the coordinates of the vertices forming the plane n: tensor of shape (3,) of the unit "inside" direction of the plane vout, vin1, vin2: tensors of shape (3,) of the points forming the triangle, where vout is "outside" the plane and vin1, vin2 are "inside" Returns: verts: tensor of shape (4, 3) containing the new vertices formed after clipping the original intersecting triangle (vout, vin1, vin2) faces: tensor of shape (2, 3) defining the vertex indices forming the two new triangles which are "inside" the plane formed after clipping # point of intersection between plane and (vin1, vout) # point of intersection between plane and (vin2, vout) # 4x3 # 2x3 Case (b). Clips face by plane when vout1, vout2 are outside plane, and vin1 is inside In this case, only one vertex of the triangle is inside the plane. Args: plane: tensor of shape (4, 3) of the coordinates of the vertices forming the plane n: tensor of shape (3,) of the unit "inside" direction of the plane vout1, vout2, vin: tensors of shape (3,) of the points forming the triangle, where vin is "inside" the plane and vout1, vout2 are "outside" Returns: verts: tensor of shape (3, 3) containing the new vertices formed after clipping the original intersectiong triangle (vout, vin1, vin2) faces: tensor of shape (1, 3) defining the vertex indices forming the single new triangle which is "inside" the plane formed after clipping # point of intersection between plane and (vin, vout1) # point of intersection between plane and (vin, vout2) # 3x3 # 1x3 Clip a trianglular face defined by tri_verts with a plane of inside "direction" n. This function computes whether the triangle has one or two or none points "outside" the plane. Args: plane: tensor of shape (4, 3) of the vertex coordinates of the plane n: tensor of shape (3,) of the unit "inside" direction of the plane tri_verts: tensor of shape (3, 3) of the vertex coordiantes of the the triangle faces Returns: tri_verts: tensor of shape (K, 3, 3) of the vertex coordinates of the triangles formed after clipping. All K triangles are now "inside" the plane. # all in, no clipping, keep the old triangle face # all out, delete triangle # (isin0, isin1, not isin2) # (isin0, not isin1, isin2) # (isin0, not isin1, not isin2) # (not isin0, isin1, isin2) # (not isin0, isin1, not isin2) # (not isin0, not isin1, isin2) # Should not be reached # -------------------------------------------------- # # MAIN: BOX3D_OVERLAP # # -------------------------------------------------- # Computes the intersection of 3D boxes1 and boxes2. Inputs boxes1, boxes2 are tensors of shape (8, 3) containing the 8 corners of the boxes, as follows (4) +---------+. (5) | ` . | ` . | (0) +---+-----+ (1) | | | | (7) +-----+---+. (6)| ` . | ` . | (3) ` +---------+ (2) Args: box1: tensor of shape (8, 3) of the coordinates of the 1st box box2: tensor of shape (8, 3) of the coordinates of the 2nd box Returns: vol: the volume of the intersecting convex shape iou: the intersection over union which is simply `iou = vol / (vol1 + vol2 - vol)` # For boxes1 we compute the unit directions n1 corresponding to quad_faces # (6, 3) # For boxes2 we compute the unit directions n2 corresponding to quad_faces # We define triangle faces # (12, 3, 3) # (6, 4, 3) # (12, 3, 3) # (6, 4, 3) # (=6) based on our definition of planes # Every triangle in box1 will be compared to each plane in box2. # If the triangle is fully outside or fully inside, then it will remain as is # If the triangle intersects with the (infinite) plane, it will be broken into # subtriangles such that each subtriangle is either fully inside or outside the plane. # Tris in Box1 -> Planes in Box2 # Tris in Box2 -> Planes in Box1 # remove triangles that are coplanar from the intersection as # otherwise they would be doublecounting towards the volume # this happens only if the original 3D boxes have common planes # Since the resulting shape is convex and specifically composed of planar segments, # each planar segment can belong either on box1 or box2 but not both. # Without loss of generality, we assign shared planar segments to box1 # intersecting shape # V=F*3 # Fx3 # Fx3x3 # Vx3 # the volume of the convex hull defined by (overlap_verts, overlap_faces) # can be defined as the sum of all the tetrahedrons formed where for each tetrahedron # the base is the triangle and the apex is the center point of the convex hull # See the math here: https://en.wikipedia.org/wiki/Tetrahedron#Volume # we compute the center by computing the center point of each face # and then averaging the face centers # save shapes # -------------------------------------------------- # # HELPER FUNCTIONS FOR SAMPLING SOLUTION # # -------------------------------------------------- # Determines whether points are inside the boxes Args: box: tensor of shape (8, 3) of the corners of the boxes points: tensor of shape (P, 3) of the points Returns: inside: bool tensor of shape (P,) # (6, 3) # (6, 4) # = 6 # a point p is inside the box if it "inside" all planes of the box # so we run the checks Sample points within a box defined by its 8 coordinates Args: box: tensor of shape (8, 3) of the box coordinates num_samples: int defining the number of samples Returns: points: (num_samples, 3) of points inside the box # because the box is not axis aligned we need to check wether # the points are within the box # -------------------------------------------------- # # MAIN: BOX3D_OVERLAP_SAMPLING # # -------------------------------------------------- # Computes the intersection of two boxes by sampling points | 1.717056 | 2 |
tests/tuples.py | fuzziqersoftware/nemesys | 9 | 6628000 | # a is iterable because its values are all the same type
a = (1, 2, 3, 4)
for x in a:
print(repr(x))
else:
print('done')
print('a[-4] is ' + repr(a[-4]))
print('a[-3] is ' + repr(a[-3]))
print('a[-2] is ' + repr(a[-2]))
print('a[-1] is ' + repr(a[-1]))
print('a[0] is ' + repr(a[0]))
print('a[1] is ' + repr(a[1]))
print('a[2] is ' + repr(a[2]))
print('a[3] is ' + repr(a[3]))
# b is also iterable
b = (0.1, 0.2, 0.3, 0.4)
for y in b:
print(repr(y))
else:
print('done')
print('b[-4] is ' + repr(b[-4]))
print('b[-3] is ' + repr(b[-3]))
print('b[-2] is ' + repr(b[-2]))
print('b[-1] is ' + repr(b[-1]))
print('b[0] is ' + repr(b[0]))
print('b[1] is ' + repr(b[1]))
print('b[2] is ' + repr(b[2]))
print('b[3] is ' + repr(b[3]))
# c is not iterable because it contains disparate types
c = ('c', 3, 5.6, True)
print('c[-4] is ' + repr(c[-4]))
print('c[-3] is ' + repr(c[-3]))
print('c[-2] is ' + repr(c[-2]))
print('c[-1] is ' + repr(c[-1]))
print('c[0] is ' + repr(c[0]))
print('c[1] is ' + repr(c[1]))
print('c[2] is ' + repr(c[2]))
print('c[3] is ' + repr(c[3]))
| # a is iterable because its values are all the same type
a = (1, 2, 3, 4)
for x in a:
print(repr(x))
else:
print('done')
print('a[-4] is ' + repr(a[-4]))
print('a[-3] is ' + repr(a[-3]))
print('a[-2] is ' + repr(a[-2]))
print('a[-1] is ' + repr(a[-1]))
print('a[0] is ' + repr(a[0]))
print('a[1] is ' + repr(a[1]))
print('a[2] is ' + repr(a[2]))
print('a[3] is ' + repr(a[3]))
# b is also iterable
b = (0.1, 0.2, 0.3, 0.4)
for y in b:
print(repr(y))
else:
print('done')
print('b[-4] is ' + repr(b[-4]))
print('b[-3] is ' + repr(b[-3]))
print('b[-2] is ' + repr(b[-2]))
print('b[-1] is ' + repr(b[-1]))
print('b[0] is ' + repr(b[0]))
print('b[1] is ' + repr(b[1]))
print('b[2] is ' + repr(b[2]))
print('b[3] is ' + repr(b[3]))
# c is not iterable because it contains disparate types
c = ('c', 3, 5.6, True)
print('c[-4] is ' + repr(c[-4]))
print('c[-3] is ' + repr(c[-3]))
print('c[-2] is ' + repr(c[-2]))
print('c[-1] is ' + repr(c[-1]))
print('c[0] is ' + repr(c[0]))
print('c[1] is ' + repr(c[1]))
print('c[2] is ' + repr(c[2]))
print('c[3] is ' + repr(c[3]))
| en | 0.948616 | # a is iterable because its values are all the same type # b is also iterable # c is not iterable because it contains disparate types | 4.171841 | 4 |
ckpt2np.py | ngocminhbui/resnet | 0 | 6628001 | import tensorflow as tf
import numpy as np
import argparse, os
if __name__ == '__main__':
print 'Example python ckpt2np.py model.ckpt-100.meta model.ckpt-100'
parser = argparse.ArgumentParser()
parser.add_argument('meta', help='meta file, (e.g. model.ckpt-100.meta)')
parser.add_argument('ckpt', help='checkpoint file, (e.g. model.ckpt-100 for tf 1.0, or model.ckpt-100.ckpt for older tf)')
parser.add_argument('save_pth', help='save path')
args = parser.parse_args()
sess = tf.Session()
new_saver = tf.train.import_meta_graph(args.meta)
new_saver.restore(sess, args.ckpt)
net = dict()
for var in tf.trainable_variables():
print 'rgb_stream/'+var.name
net['rgb_stream/'+var.name] = sess.run(var)
name = args.meta.split('.')[0]
np.save(args.save_pth, net)
| import tensorflow as tf
import numpy as np
import argparse, os
if __name__ == '__main__':
print 'Example python ckpt2np.py model.ckpt-100.meta model.ckpt-100'
parser = argparse.ArgumentParser()
parser.add_argument('meta', help='meta file, (e.g. model.ckpt-100.meta)')
parser.add_argument('ckpt', help='checkpoint file, (e.g. model.ckpt-100 for tf 1.0, or model.ckpt-100.ckpt for older tf)')
parser.add_argument('save_pth', help='save path')
args = parser.parse_args()
sess = tf.Session()
new_saver = tf.train.import_meta_graph(args.meta)
new_saver.restore(sess, args.ckpt)
net = dict()
for var in tf.trainable_variables():
print 'rgb_stream/'+var.name
net['rgb_stream/'+var.name] = sess.run(var)
name = args.meta.split('.')[0]
np.save(args.save_pth, net)
| none | 1 | 2.473381 | 2 | |
src/orion/benchmark/task/profet/model_utils.py | satyaog/orion | 0 | 6628002 | """ Options and utilities for training the profet meta-model from Emukit. """
import json
import pickle
import typing
import warnings
from abc import ABC
from copy import deepcopy
from dataclasses import dataclass
from logging import getLogger as get_logger
from pathlib import Path
from typing import Any, Callable, ClassVar, Optional, Tuple, Union
import numpy as np
_ERROR_MSG = (
"The `profet` extras needs to be installed in order to use the Profet tasks.\n"
"Error: {0}\n"
"Use `pip install orion[profet]` to install the profet extras."
)
try:
import GPy
import torch
from emukit.examples.profet.meta_benchmarks.architecture import (
get_default_architecture,
)
from emukit.examples.profet.meta_benchmarks.meta_forrester import (
get_architecture_forrester, # type: ignore
)
from emukit.examples.profet.train_meta_model import download_data
from GPy.models import BayesianGPLVM
from pybnn.bohamiann import Bohamiann
except ImportError as err:
warnings.warn(RuntimeWarning(_ERROR_MSG.format(err)))
# NOTE: Need to set some garbage dummy values, so that the documentation can be generated without
# actually having these values.
def get_default_architecture(
input_dimensionality: int, classification: bool = False, n_hidden: int = 500
) -> Any:
raise RuntimeError(_ERROR_MSG)
def get_architecture_forrester(input_dimensionality: int) -> Any:
raise RuntimeError(_ERROR_MSG)
logger = get_logger(__name__)
@dataclass
class MetaModelConfig(ABC):
"""Configuration options for the training of the Profet meta-model."""
benchmark: str
""" Name of the benchmark. """
# ---------- "Abstract"/required class attributes:
json_file_name: ClassVar[str]
""" Name of the json file that contains the data of this benchmark. """
get_architecture: ClassVar[
Callable[[int], "torch.nn.Module"]
] = get_default_architecture
""" Callable that takes the input dimensionality and returns the network to be trained. """
hidden_space: ClassVar[int]
""" Size of the hidden space for this benchmark. """
log_cost: ClassVar[bool]
""" Whether to apply `numpy.log` onto the raw data for the cost of each point. """
log_target: ClassVar[bool]
""" Whether to apply `numpy.log` onto the raw data for the `y` of each point. """
normalize_targets: ClassVar[bool]
""" Whether to normalize the targets (y), by default False. """
shapes: ClassVar[Tuple[Tuple[int, ...], Tuple[int, ...], Tuple[int, ...]]]
""" The shapes of the X, Y and C arrays of the dataset. """
y_min: ClassVar[float]
""" The minimum of the Y array. """
y_max: ClassVar[float]
""" The maximum of the Y array. """
c_min: ClassVar[float]
""" The minimum of the C array. """
c_max: ClassVar[float]
""" The maximum of the C array. """
# -----------
task_id: int = 0
""" Task index. """
seed: int = 123
""" Random seed. """
num_burnin_steps: int = 50000
""" (copied from `Bohamiann.train`): Number of burn-in steps to perform. This value is passed
to the given `optimizer` if it supports special burn-in specific behavior. Networks sampled
during burn-in are discarded.
"""
num_steps: int = 13_000
"""Value passed to the argument of the same name in `Bohamiann.train`.
(copied from `Bohamiann.train`):
Number of sampling steps to perform after burn-in is finished. In total,
`num_steps // keep_every` network weights will be sampled.
"""
mcmc_thining: int = 100
""" `keep_every` argument of `Bohamiann.train`.
(copied from `Bohamiann.train`):
Number of sampling steps (after burn-in) to perform before keeping a sample. In total,
`num_steps // keep_every` network weights will be sampled.
"""
lr: float = 1e-2
""" `lr` argument of `Bohamiann.train`. """
batch_size: int = 5
""" `batch_size` argument of `Bohamiann.train`. """
max_samples: Optional[int] = None
""" Maximum number of data samples to use when training the meta-model. This can be useful
if the dataset is large (e.g. FCNet task) and you don't have crazy amounts of memory.
"""
n_inducing_lvm: int = 50
""" Passed as the value for the "num_inducing" argument of `BayesianGPLVM` constructor.
(copied form `GPy.core.sparse_gp_mpi.SparseGP_MPI`):
Number of inducing points (optional, default 10. Ignored if Z is not None)
"""
max_iters: int = 10_000
"""Argument passed to the `optimize` method of the `BayesianGPLVM` instance that is used in the
call to `get_features`. Appears to be the number of training iterations to perform.
"""
n_samples_task: int = 500
""" Number of tasks to create in `get_training_data`."""
def get_task_network(self, input_path: Union[Path, str]) -> Tuple[Any, np.ndarray]:
"""Create, train and return a surrogate model for the given `benchmark`, `seed` and `task_id`.
Parameters
----------
input_path : Union[Path, str]
Data directory containing the json files.
Returns
-------
Tuple[Any, np.ndarray]
The surrogate model for the objective, as well as an array of sampled task features.
"""
rng = np.random.RandomState(seed=self.seed)
X, Y, C = self.load_data(input_path)
task_features_mean, task_features_std = self._get_features(
X=X,
Y=Y,
C=C,
display_messages=False,
)
X_train, Y_train, C_train = self._get_training_data(
X,
Y,
C,
task_features_mean=task_features_mean,
task_features_std=task_features_std,
)
objective_model, cost_model = self._get_meta_model(
X_train,
Y_train,
C_train,
with_cost=False,
)
net = self._create_task_network(objective_model, X_train.shape[1])
multiplier = rng.randn(self.hidden_space)
h = (
task_features_mean[self.task_id]
+ task_features_std[self.task_id] * multiplier
)
return net, h
def load_data(
self, input_path: Union[str, Path]
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Load the profet data for the given benchmark from the input directory.
When the input directory doesn't exist, attempts to download the data to create the input
directory.
Parameters
----------
input_path : Union[str, Path]
Input directory. Expects to find a json file for the given benchmark inside that directory.
Returns
-------
Tuple[np.ndarray, np.ndarray, np.ndarray]
X, Y, and C arrays.
"""
# file = Path(input_path) / NAMES[benchmark]
file = Path(input_path) / self.json_file_name
if not file.exists():
logger.info(f"File {file} doesn't exist, attempting to download data.")
download_data(input_path)
logger.info("Download finished.")
if not file.exists():
raise RuntimeError(
f"Download finished, but file {file} still doesn't exist!"
)
with open(file, "r") as f:
res = json.load(f)
X, Y, C = np.array(res["X"]), np.array(res["Y"]), np.array(res["C"])
if len(X.shape) == 1:
X = X[:, None]
return X, Y, C
def normalize_Y(
self, Y: np.ndarray, indexD: np.ndarray
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Normalize the Y array and return its mean and standard deviations.
Parameters
----------
Y : np.ndarray
Labels from the datasets.
indexD : np.ndarray
Task indices of corresponding labels Y.
Returns
-------
Tuple[np.ndarray, np.ndarray, np.ndarray]
Tuple containing the Y array, the mean array, and the std array.
"""
max_idx = np.max(indexD)
Y_mean = np.zeros(max_idx + 1)
Y_std = np.zeros(max_idx + 1)
for i in range(max_idx + 1):
Y_mean[i] = Y[indexD == i].mean()
Y_std[i] = Y[indexD == i].std() + 1e-8
Y[indexD == i] = (Y[indexD == i] - Y_mean[i]) / Y_std[i]
return Y, Y_mean[:, None], Y_std[:, None]
def _get_features(
self,
X: np.ndarray,
Y: np.ndarray,
C: np.ndarray,
display_messages: bool = True,
) -> Tuple[np.ndarray, np.ndarray]:
"""Generate features for the given task.
Parameters
----------
X : np.ndarray
Training examples
Y : np.ndarray
Training labels
C : np.ndarray
Training costs
display_messages : bool, optional
Whether to log messages to the console or not, by default True.
Returns
-------
Tuple[np.ndarray, np.ndarray]
The features mean and std arrays.
"""
n_tasks = Y.shape[0]
n_configs = X.shape[0]
index_task = np.repeat(np.arange(n_tasks), n_configs)
Y_norm, _, _ = self.normalize_Y(deepcopy(Y.flatten()), index_task)
# train the probabilistic encoder
kern = GPy.kern.Matern52(input_dim=self.hidden_space, ARD=True)
m_lvm = BayesianGPLVM(
Y_norm.reshape(n_tasks, n_configs),
input_dim=self.hidden_space,
kernel=kern,
num_inducing=self.n_inducing_lvm,
)
m_lvm.optimize(max_iters=self.max_iters, messages=display_messages)
ls = np.array(
[m_lvm.kern.lengthscale[i] for i in range(m_lvm.kern.lengthscale.shape[0])]
)
# generate data to train the multi-task model
task_features_mean = np.array(m_lvm.X.mean / ls)
task_features_std = np.array(np.sqrt(m_lvm.X.variance) / ls)
return task_features_mean, task_features_std
def _get_training_data(
self,
X: np.ndarray,
Y: np.ndarray,
C: np.ndarray,
task_features_mean: np.ndarray,
task_features_std: np.ndarray,
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Create training data by sampling a given number of tasks.
Parameters
----------
X : np.ndarray
Training examples
Y : np.ndarray
Training labels
C : np.ndarray
Training costs (NOTE: This isn't really used at the moment).
task_features_mean : np.ndarray
Mean of the model training weights.
task_features_std : np.ndarray
Std of the model training weights.
Returns
-------
Tuple[np.ndarray, np.ndarray, np.ndarray]
numpy arrays containing the X, Y, and C's for each task.
"""
n_tasks = Y.shape[0]
hidden_space = task_features_std.shape[1]
n_configs = X.shape[0]
X_train_list = []
Y_train_list = []
C_train_list = []
for i, xi in enumerate(X):
for idx in range(n_tasks):
for _ in range(self.n_samples_task):
multiplier = np.random.randn(hidden_space)
ht = task_features_mean[idx] + task_features_std[idx] * multiplier
x = np.concatenate((xi, ht), axis=0)
X_train_list.append(x)
Y_train_list.append(Y[idx, i])
C_train_list.append(C[idx, i])
X_train = np.array(X_train_list)
Y_train = np.array(Y_train_list)
C_train = np.array(C_train_list)
if self.log_cost:
C_train = np.log(C_train)
if self.log_target:
Y_train = np.log(Y_train)
return X_train, Y_train, C_train
def _get_meta_model(
self,
X_train: np.ndarray,
Y_train: np.ndarray,
C_train: np.ndarray,
with_cost: bool = False,
):
"""Create, train and return the objective model, and (optionally) a cost model for the data.
Parameters
----------
X_train : np.ndarray
Training samples.
Y_train : np.ndarray
Training objectives.
C_train : np.ndarray
Training costs.
with_cost : bool, optional
Whether to also create a surrogate model for the cost. Defaults to `False`.
Returns
-------
Tuple[Bohamiann, Optional[Bohamiann]]
Surrogate model for the objective, as well as another for the cost, if `with_cost` is
True, otherwise `None`.
"""
objective_model = Bohamiann(
get_network=type(self).get_architecture,
print_every_n_steps=1000,
normalize_output=self.normalize_targets,
)
logger.info("Training Bohamiann objective model.")
if self.max_samples is not None:
logger.info(
f"Limiting the dataset to a maximum of {self.max_samples} samples."
)
X_train = X_train[: self.max_samples, ...]
Y_train = Y_train[: self.max_samples, ...]
C_train = C_train[: self.max_samples, ...]
logger.debug(f"Shapes: {X_train.shape}, {Y_train.shape}")
logger.debug(f"config: {self}")
objective_model.train(
X_train,
Y_train,
num_steps=self.num_steps + self.num_burnin_steps,
num_burn_in_steps=self.num_burnin_steps,
keep_every=self.mcmc_thining,
lr=self.lr,
verbose=True,
batch_size=self.batch_size,
)
if with_cost:
cost_model = Bohamiann(
get_network=type(self).get_architecture, print_every_n_steps=1000
)
logger.info("Training Bohamiann cost model.")
cost_model.train(
X_train,
C_train,
num_steps=self.num_steps + self.num_burnin_steps,
num_burn_in_steps=self.num_burnin_steps,
keep_every=self.mcmc_thining,
lr=self.lr,
verbose=True,
batch_size=self.batch_size,
)
else:
cost_model = None
return objective_model, cost_model
def _create_task_network(self, model, size: int, idx: int = 0) -> "torch.nn.Module":
"""Retrieve a network with sampled weights for the given task id.
Parameters
----------
model : Bohamiann
"Base" Bohamiann model used to get a network and its weights.
size : int
Input dimensions for the generated network.
idx : int, optional
Task idx, by default 0
Returns
-------
nn.Module
A module with sampled weights.
"""
net = model.get_network(size)
# assert False, (type(self).get_architecture, net, self.shapes)
with torch.no_grad():
sampled_weights = model.sampled_weights[idx]
for parameter, sample in zip(net.parameters(), sampled_weights):
parameter.copy_(torch.from_numpy(sample))
return net
def load_task_network(
self,
checkpoint_file: Union[str, Path],
) -> Tuple[Any, np.ndarray]:
"""Load the result of the `get_task_network` function stored in the pickle file.
Parameters
----------
checkpoint_file : Union[str, Path]
Path to a pickle file. The file is expected to contain a serialized dictionary, with keys
"benchmark", "size", "network", and "h".
Returns
-------
Tuple[Any, np.ndarray]
The surrogate model for the objective, as well as an array of sampled task features.
"""
with open(checkpoint_file, "rb") as f:
state = pickle.load(f)
if state["benchmark"] != self.benchmark:
raise RuntimeError(
f"Trying to load model for benchmark {self.benchmark} from checkpoint that "
f"contains data from benchmark {state['benchmark']}."
)
network = type(self).get_architecture(input_dimensionality=state["size"])
network.load_state_dict(state["network"])
h = state["h"]
return network, h
def save_task_network(
self, checkpoint_file: Union[str, Path], network: Any, h: np.ndarray
) -> None:
"""Save the meta-model for the task at the given path.
Parameters
----------
checkpoint_file : Union[str, Path]
Path where the model should be saved
network : Any
The network
h : np.ndarray
The embedding vector
"""
checkpoint_file = Path(checkpoint_file)
state = dict(
benchmark=self.benchmark,
network=network.state_dict(),
size=list(network.parameters())[0].size()[1],
h=h.tolist(),
)
tmp_file = checkpoint_file.with_suffix(".tmp")
with open(tmp_file, "wb") as file:
pickle.dump(state, file, protocol=pickle.DEFAULT_PROTOCOL)
tmp_file.rename(checkpoint_file)
| """ Options and utilities for training the profet meta-model from Emukit. """
import json
import pickle
import typing
import warnings
from abc import ABC
from copy import deepcopy
from dataclasses import dataclass
from logging import getLogger as get_logger
from pathlib import Path
from typing import Any, Callable, ClassVar, Optional, Tuple, Union
import numpy as np
_ERROR_MSG = (
"The `profet` extras needs to be installed in order to use the Profet tasks.\n"
"Error: {0}\n"
"Use `pip install orion[profet]` to install the profet extras."
)
try:
import GPy
import torch
from emukit.examples.profet.meta_benchmarks.architecture import (
get_default_architecture,
)
from emukit.examples.profet.meta_benchmarks.meta_forrester import (
get_architecture_forrester, # type: ignore
)
from emukit.examples.profet.train_meta_model import download_data
from GPy.models import BayesianGPLVM
from pybnn.bohamiann import Bohamiann
except ImportError as err:
warnings.warn(RuntimeWarning(_ERROR_MSG.format(err)))
# NOTE: Need to set some garbage dummy values, so that the documentation can be generated without
# actually having these values.
def get_default_architecture(
input_dimensionality: int, classification: bool = False, n_hidden: int = 500
) -> Any:
raise RuntimeError(_ERROR_MSG)
def get_architecture_forrester(input_dimensionality: int) -> Any:
raise RuntimeError(_ERROR_MSG)
logger = get_logger(__name__)
@dataclass
class MetaModelConfig(ABC):
"""Configuration options for the training of the Profet meta-model."""
benchmark: str
""" Name of the benchmark. """
# ---------- "Abstract"/required class attributes:
json_file_name: ClassVar[str]
""" Name of the json file that contains the data of this benchmark. """
get_architecture: ClassVar[
Callable[[int], "torch.nn.Module"]
] = get_default_architecture
""" Callable that takes the input dimensionality and returns the network to be trained. """
hidden_space: ClassVar[int]
""" Size of the hidden space for this benchmark. """
log_cost: ClassVar[bool]
""" Whether to apply `numpy.log` onto the raw data for the cost of each point. """
log_target: ClassVar[bool]
""" Whether to apply `numpy.log` onto the raw data for the `y` of each point. """
normalize_targets: ClassVar[bool]
""" Whether to normalize the targets (y), by default False. """
shapes: ClassVar[Tuple[Tuple[int, ...], Tuple[int, ...], Tuple[int, ...]]]
""" The shapes of the X, Y and C arrays of the dataset. """
y_min: ClassVar[float]
""" The minimum of the Y array. """
y_max: ClassVar[float]
""" The maximum of the Y array. """
c_min: ClassVar[float]
""" The minimum of the C array. """
c_max: ClassVar[float]
""" The maximum of the C array. """
# -----------
task_id: int = 0
""" Task index. """
seed: int = 123
""" Random seed. """
num_burnin_steps: int = 50000
""" (copied from `Bohamiann.train`): Number of burn-in steps to perform. This value is passed
to the given `optimizer` if it supports special burn-in specific behavior. Networks sampled
during burn-in are discarded.
"""
num_steps: int = 13_000
"""Value passed to the argument of the same name in `Bohamiann.train`.
(copied from `Bohamiann.train`):
Number of sampling steps to perform after burn-in is finished. In total,
`num_steps // keep_every` network weights will be sampled.
"""
mcmc_thining: int = 100
""" `keep_every` argument of `Bohamiann.train`.
(copied from `Bohamiann.train`):
Number of sampling steps (after burn-in) to perform before keeping a sample. In total,
`num_steps // keep_every` network weights will be sampled.
"""
lr: float = 1e-2
""" `lr` argument of `Bohamiann.train`. """
batch_size: int = 5
""" `batch_size` argument of `Bohamiann.train`. """
max_samples: Optional[int] = None
""" Maximum number of data samples to use when training the meta-model. This can be useful
if the dataset is large (e.g. FCNet task) and you don't have crazy amounts of memory.
"""
n_inducing_lvm: int = 50
""" Passed as the value for the "num_inducing" argument of `BayesianGPLVM` constructor.
(copied form `GPy.core.sparse_gp_mpi.SparseGP_MPI`):
Number of inducing points (optional, default 10. Ignored if Z is not None)
"""
max_iters: int = 10_000
"""Argument passed to the `optimize` method of the `BayesianGPLVM` instance that is used in the
call to `get_features`. Appears to be the number of training iterations to perform.
"""
n_samples_task: int = 500
""" Number of tasks to create in `get_training_data`."""
def get_task_network(self, input_path: Union[Path, str]) -> Tuple[Any, np.ndarray]:
"""Create, train and return a surrogate model for the given `benchmark`, `seed` and `task_id`.
Parameters
----------
input_path : Union[Path, str]
Data directory containing the json files.
Returns
-------
Tuple[Any, np.ndarray]
The surrogate model for the objective, as well as an array of sampled task features.
"""
rng = np.random.RandomState(seed=self.seed)
X, Y, C = self.load_data(input_path)
task_features_mean, task_features_std = self._get_features(
X=X,
Y=Y,
C=C,
display_messages=False,
)
X_train, Y_train, C_train = self._get_training_data(
X,
Y,
C,
task_features_mean=task_features_mean,
task_features_std=task_features_std,
)
objective_model, cost_model = self._get_meta_model(
X_train,
Y_train,
C_train,
with_cost=False,
)
net = self._create_task_network(objective_model, X_train.shape[1])
multiplier = rng.randn(self.hidden_space)
h = (
task_features_mean[self.task_id]
+ task_features_std[self.task_id] * multiplier
)
return net, h
def load_data(
self, input_path: Union[str, Path]
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Load the profet data for the given benchmark from the input directory.
When the input directory doesn't exist, attempts to download the data to create the input
directory.
Parameters
----------
input_path : Union[str, Path]
Input directory. Expects to find a json file for the given benchmark inside that directory.
Returns
-------
Tuple[np.ndarray, np.ndarray, np.ndarray]
X, Y, and C arrays.
"""
# file = Path(input_path) / NAMES[benchmark]
file = Path(input_path) / self.json_file_name
if not file.exists():
logger.info(f"File {file} doesn't exist, attempting to download data.")
download_data(input_path)
logger.info("Download finished.")
if not file.exists():
raise RuntimeError(
f"Download finished, but file {file} still doesn't exist!"
)
with open(file, "r") as f:
res = json.load(f)
X, Y, C = np.array(res["X"]), np.array(res["Y"]), np.array(res["C"])
if len(X.shape) == 1:
X = X[:, None]
return X, Y, C
def normalize_Y(
self, Y: np.ndarray, indexD: np.ndarray
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Normalize the Y array and return its mean and standard deviations.
Parameters
----------
Y : np.ndarray
Labels from the datasets.
indexD : np.ndarray
Task indices of corresponding labels Y.
Returns
-------
Tuple[np.ndarray, np.ndarray, np.ndarray]
Tuple containing the Y array, the mean array, and the std array.
"""
max_idx = np.max(indexD)
Y_mean = np.zeros(max_idx + 1)
Y_std = np.zeros(max_idx + 1)
for i in range(max_idx + 1):
Y_mean[i] = Y[indexD == i].mean()
Y_std[i] = Y[indexD == i].std() + 1e-8
Y[indexD == i] = (Y[indexD == i] - Y_mean[i]) / Y_std[i]
return Y, Y_mean[:, None], Y_std[:, None]
def _get_features(
self,
X: np.ndarray,
Y: np.ndarray,
C: np.ndarray,
display_messages: bool = True,
) -> Tuple[np.ndarray, np.ndarray]:
"""Generate features for the given task.
Parameters
----------
X : np.ndarray
Training examples
Y : np.ndarray
Training labels
C : np.ndarray
Training costs
display_messages : bool, optional
Whether to log messages to the console or not, by default True.
Returns
-------
Tuple[np.ndarray, np.ndarray]
The features mean and std arrays.
"""
n_tasks = Y.shape[0]
n_configs = X.shape[0]
index_task = np.repeat(np.arange(n_tasks), n_configs)
Y_norm, _, _ = self.normalize_Y(deepcopy(Y.flatten()), index_task)
# train the probabilistic encoder
kern = GPy.kern.Matern52(input_dim=self.hidden_space, ARD=True)
m_lvm = BayesianGPLVM(
Y_norm.reshape(n_tasks, n_configs),
input_dim=self.hidden_space,
kernel=kern,
num_inducing=self.n_inducing_lvm,
)
m_lvm.optimize(max_iters=self.max_iters, messages=display_messages)
ls = np.array(
[m_lvm.kern.lengthscale[i] for i in range(m_lvm.kern.lengthscale.shape[0])]
)
# generate data to train the multi-task model
task_features_mean = np.array(m_lvm.X.mean / ls)
task_features_std = np.array(np.sqrt(m_lvm.X.variance) / ls)
return task_features_mean, task_features_std
def _get_training_data(
self,
X: np.ndarray,
Y: np.ndarray,
C: np.ndarray,
task_features_mean: np.ndarray,
task_features_std: np.ndarray,
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Create training data by sampling a given number of tasks.
Parameters
----------
X : np.ndarray
Training examples
Y : np.ndarray
Training labels
C : np.ndarray
Training costs (NOTE: This isn't really used at the moment).
task_features_mean : np.ndarray
Mean of the model training weights.
task_features_std : np.ndarray
Std of the model training weights.
Returns
-------
Tuple[np.ndarray, np.ndarray, np.ndarray]
numpy arrays containing the X, Y, and C's for each task.
"""
n_tasks = Y.shape[0]
hidden_space = task_features_std.shape[1]
n_configs = X.shape[0]
X_train_list = []
Y_train_list = []
C_train_list = []
for i, xi in enumerate(X):
for idx in range(n_tasks):
for _ in range(self.n_samples_task):
multiplier = np.random.randn(hidden_space)
ht = task_features_mean[idx] + task_features_std[idx] * multiplier
x = np.concatenate((xi, ht), axis=0)
X_train_list.append(x)
Y_train_list.append(Y[idx, i])
C_train_list.append(C[idx, i])
X_train = np.array(X_train_list)
Y_train = np.array(Y_train_list)
C_train = np.array(C_train_list)
if self.log_cost:
C_train = np.log(C_train)
if self.log_target:
Y_train = np.log(Y_train)
return X_train, Y_train, C_train
def _get_meta_model(
self,
X_train: np.ndarray,
Y_train: np.ndarray,
C_train: np.ndarray,
with_cost: bool = False,
):
"""Create, train and return the objective model, and (optionally) a cost model for the data.
Parameters
----------
X_train : np.ndarray
Training samples.
Y_train : np.ndarray
Training objectives.
C_train : np.ndarray
Training costs.
with_cost : bool, optional
Whether to also create a surrogate model for the cost. Defaults to `False`.
Returns
-------
Tuple[Bohamiann, Optional[Bohamiann]]
Surrogate model for the objective, as well as another for the cost, if `with_cost` is
True, otherwise `None`.
"""
objective_model = Bohamiann(
get_network=type(self).get_architecture,
print_every_n_steps=1000,
normalize_output=self.normalize_targets,
)
logger.info("Training Bohamiann objective model.")
if self.max_samples is not None:
logger.info(
f"Limiting the dataset to a maximum of {self.max_samples} samples."
)
X_train = X_train[: self.max_samples, ...]
Y_train = Y_train[: self.max_samples, ...]
C_train = C_train[: self.max_samples, ...]
logger.debug(f"Shapes: {X_train.shape}, {Y_train.shape}")
logger.debug(f"config: {self}")
objective_model.train(
X_train,
Y_train,
num_steps=self.num_steps + self.num_burnin_steps,
num_burn_in_steps=self.num_burnin_steps,
keep_every=self.mcmc_thining,
lr=self.lr,
verbose=True,
batch_size=self.batch_size,
)
if with_cost:
cost_model = Bohamiann(
get_network=type(self).get_architecture, print_every_n_steps=1000
)
logger.info("Training Bohamiann cost model.")
cost_model.train(
X_train,
C_train,
num_steps=self.num_steps + self.num_burnin_steps,
num_burn_in_steps=self.num_burnin_steps,
keep_every=self.mcmc_thining,
lr=self.lr,
verbose=True,
batch_size=self.batch_size,
)
else:
cost_model = None
return objective_model, cost_model
def _create_task_network(self, model, size: int, idx: int = 0) -> "torch.nn.Module":
"""Retrieve a network with sampled weights for the given task id.
Parameters
----------
model : Bohamiann
"Base" Bohamiann model used to get a network and its weights.
size : int
Input dimensions for the generated network.
idx : int, optional
Task idx, by default 0
Returns
-------
nn.Module
A module with sampled weights.
"""
net = model.get_network(size)
# assert False, (type(self).get_architecture, net, self.shapes)
with torch.no_grad():
sampled_weights = model.sampled_weights[idx]
for parameter, sample in zip(net.parameters(), sampled_weights):
parameter.copy_(torch.from_numpy(sample))
return net
def load_task_network(
self,
checkpoint_file: Union[str, Path],
) -> Tuple[Any, np.ndarray]:
"""Load the result of the `get_task_network` function stored in the pickle file.
Parameters
----------
checkpoint_file : Union[str, Path]
Path to a pickle file. The file is expected to contain a serialized dictionary, with keys
"benchmark", "size", "network", and "h".
Returns
-------
Tuple[Any, np.ndarray]
The surrogate model for the objective, as well as an array of sampled task features.
"""
with open(checkpoint_file, "rb") as f:
state = pickle.load(f)
if state["benchmark"] != self.benchmark:
raise RuntimeError(
f"Trying to load model for benchmark {self.benchmark} from checkpoint that "
f"contains data from benchmark {state['benchmark']}."
)
network = type(self).get_architecture(input_dimensionality=state["size"])
network.load_state_dict(state["network"])
h = state["h"]
return network, h
def save_task_network(
self, checkpoint_file: Union[str, Path], network: Any, h: np.ndarray
) -> None:
"""Save the meta-model for the task at the given path.
Parameters
----------
checkpoint_file : Union[str, Path]
Path where the model should be saved
network : Any
The network
h : np.ndarray
The embedding vector
"""
checkpoint_file = Path(checkpoint_file)
state = dict(
benchmark=self.benchmark,
network=network.state_dict(),
size=list(network.parameters())[0].size()[1],
h=h.tolist(),
)
tmp_file = checkpoint_file.with_suffix(".tmp")
with open(tmp_file, "wb") as file:
pickle.dump(state, file, protocol=pickle.DEFAULT_PROTOCOL)
tmp_file.rename(checkpoint_file)
| en | 0.738458 | Options and utilities for training the profet meta-model from Emukit. # type: ignore # NOTE: Need to set some garbage dummy values, so that the documentation can be generated without # actually having these values. Configuration options for the training of the Profet meta-model. Name of the benchmark. # ---------- "Abstract"/required class attributes: Name of the json file that contains the data of this benchmark. Callable that takes the input dimensionality and returns the network to be trained. Size of the hidden space for this benchmark. Whether to apply `numpy.log` onto the raw data for the cost of each point. Whether to apply `numpy.log` onto the raw data for the `y` of each point. Whether to normalize the targets (y), by default False. The shapes of the X, Y and C arrays of the dataset. The minimum of the Y array. The maximum of the Y array. The minimum of the C array. The maximum of the C array. # ----------- Task index. Random seed. (copied from `Bohamiann.train`): Number of burn-in steps to perform. This value is passed to the given `optimizer` if it supports special burn-in specific behavior. Networks sampled during burn-in are discarded. Value passed to the argument of the same name in `Bohamiann.train`. (copied from `Bohamiann.train`): Number of sampling steps to perform after burn-in is finished. In total, `num_steps // keep_every` network weights will be sampled. `keep_every` argument of `Bohamiann.train`. (copied from `Bohamiann.train`): Number of sampling steps (after burn-in) to perform before keeping a sample. In total, `num_steps // keep_every` network weights will be sampled. `lr` argument of `Bohamiann.train`. `batch_size` argument of `Bohamiann.train`. Maximum number of data samples to use when training the meta-model. This can be useful if the dataset is large (e.g. FCNet task) and you don't have crazy amounts of memory. Passed as the value for the "num_inducing" argument of `BayesianGPLVM` constructor. (copied form `GPy.core.sparse_gp_mpi.SparseGP_MPI`): Number of inducing points (optional, default 10. Ignored if Z is not None) Argument passed to the `optimize` method of the `BayesianGPLVM` instance that is used in the call to `get_features`. Appears to be the number of training iterations to perform. Number of tasks to create in `get_training_data`. Create, train and return a surrogate model for the given `benchmark`, `seed` and `task_id`. Parameters ---------- input_path : Union[Path, str] Data directory containing the json files. Returns ------- Tuple[Any, np.ndarray] The surrogate model for the objective, as well as an array of sampled task features. Load the profet data for the given benchmark from the input directory. When the input directory doesn't exist, attempts to download the data to create the input directory. Parameters ---------- input_path : Union[str, Path] Input directory. Expects to find a json file for the given benchmark inside that directory. Returns ------- Tuple[np.ndarray, np.ndarray, np.ndarray] X, Y, and C arrays. # file = Path(input_path) / NAMES[benchmark] Normalize the Y array and return its mean and standard deviations. Parameters ---------- Y : np.ndarray Labels from the datasets. indexD : np.ndarray Task indices of corresponding labels Y. Returns ------- Tuple[np.ndarray, np.ndarray, np.ndarray] Tuple containing the Y array, the mean array, and the std array. Generate features for the given task. Parameters ---------- X : np.ndarray Training examples Y : np.ndarray Training labels C : np.ndarray Training costs display_messages : bool, optional Whether to log messages to the console or not, by default True. Returns ------- Tuple[np.ndarray, np.ndarray] The features mean and std arrays. # train the probabilistic encoder # generate data to train the multi-task model Create training data by sampling a given number of tasks. Parameters ---------- X : np.ndarray Training examples Y : np.ndarray Training labels C : np.ndarray Training costs (NOTE: This isn't really used at the moment). task_features_mean : np.ndarray Mean of the model training weights. task_features_std : np.ndarray Std of the model training weights. Returns ------- Tuple[np.ndarray, np.ndarray, np.ndarray] numpy arrays containing the X, Y, and C's for each task. Create, train and return the objective model, and (optionally) a cost model for the data. Parameters ---------- X_train : np.ndarray Training samples. Y_train : np.ndarray Training objectives. C_train : np.ndarray Training costs. with_cost : bool, optional Whether to also create a surrogate model for the cost. Defaults to `False`. Returns ------- Tuple[Bohamiann, Optional[Bohamiann]] Surrogate model for the objective, as well as another for the cost, if `with_cost` is True, otherwise `None`. Retrieve a network with sampled weights for the given task id. Parameters ---------- model : Bohamiann "Base" Bohamiann model used to get a network and its weights. size : int Input dimensions for the generated network. idx : int, optional Task idx, by default 0 Returns ------- nn.Module A module with sampled weights. # assert False, (type(self).get_architecture, net, self.shapes) Load the result of the `get_task_network` function stored in the pickle file. Parameters ---------- checkpoint_file : Union[str, Path] Path to a pickle file. The file is expected to contain a serialized dictionary, with keys "benchmark", "size", "network", and "h". Returns ------- Tuple[Any, np.ndarray] The surrogate model for the objective, as well as an array of sampled task features. Save the meta-model for the task at the given path. Parameters ---------- checkpoint_file : Union[str, Path] Path where the model should be saved network : Any The network h : np.ndarray The embedding vector | 2.535363 | 3 |
python/python/repeated_word/test_repeated.py | iggy18/data-structures-and-algorithms | 0 | 6628003 | <filename>python/python/repeated_word/test_repeated.py<gh_stars>0
from repeated_word import strip_down, not_split, seen_word, which_word_is_repeated_first, repeated_word_dict
def test_strip_down():
assert strip_down
def test_not_split():
assert not_split
def test_seen_word():
assert seen_word
def test_which_word_is_repeated_first():
assert which_word_is_repeated_first
def test_strip_down_removes_special_chars():
x = "here, is! some... $tuff"
actual = strip_down(x)
expected = "here is some tuff"
assert actual == expected
def test_not_split_creates_array_from_input():
x = "here is some stuff"
actual = not_split(x)
expected = ["here", "is", "some", "stuff"]
assert actual == expected
def test_seen_word_returns_repeated_word():
x = "here is some some stuff"
y = not_split(x)
actual = seen_word(y)
expected = "some"
assert actual == expected
def test_which_word_is_repeated_first_returns_repeated_words_from_lengthy_input():
x = 'Once upon a time, there was a brave princess who... '
actual = which_word_is_repeated_first(x)
expected = "a"
assert actual == expected
def test_which_word_is_repeated_first_returns_repeated_words_from_lengthy_input_two():
x = 'It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair, we had everything before us, we had nothing before us, we were all going direct to Heaven, we were all going direct the other way – in short, the period was so far like the present period, that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only...'
actual = which_word_is_repeated_first(x)
expected = "it"
assert actual == expected
def test_which_word_is_repeated_first_returns_repeated_words_from_lengthy_input_three():
x = 'It was a queer, sultry summer, the summer they electrocuted the Rosenbergs, and I didn’t know what I was doing in New York...'
actual = which_word_is_repeated_first(x)
expected = "summer"
assert actual == expected
#function using built in methods and dictionary
def test_dict():
x = "Once upon a time, there was a brave princess who... "
actual = repeated_word_dict(x)
expected = "a"
assert actual == expected
| <filename>python/python/repeated_word/test_repeated.py<gh_stars>0
from repeated_word import strip_down, not_split, seen_word, which_word_is_repeated_first, repeated_word_dict
def test_strip_down():
assert strip_down
def test_not_split():
assert not_split
def test_seen_word():
assert seen_word
def test_which_word_is_repeated_first():
assert which_word_is_repeated_first
def test_strip_down_removes_special_chars():
x = "here, is! some... $tuff"
actual = strip_down(x)
expected = "here is some tuff"
assert actual == expected
def test_not_split_creates_array_from_input():
x = "here is some stuff"
actual = not_split(x)
expected = ["here", "is", "some", "stuff"]
assert actual == expected
def test_seen_word_returns_repeated_word():
x = "here is some some stuff"
y = not_split(x)
actual = seen_word(y)
expected = "some"
assert actual == expected
def test_which_word_is_repeated_first_returns_repeated_words_from_lengthy_input():
x = 'Once upon a time, there was a brave princess who... '
actual = which_word_is_repeated_first(x)
expected = "a"
assert actual == expected
def test_which_word_is_repeated_first_returns_repeated_words_from_lengthy_input_two():
x = 'It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair, we had everything before us, we had nothing before us, we were all going direct to Heaven, we were all going direct the other way – in short, the period was so far like the present period, that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only...'
actual = which_word_is_repeated_first(x)
expected = "it"
assert actual == expected
def test_which_word_is_repeated_first_returns_repeated_words_from_lengthy_input_three():
x = 'It was a queer, sultry summer, the summer they electrocuted the Rosenbergs, and I didn’t know what I was doing in New York...'
actual = which_word_is_repeated_first(x)
expected = "summer"
assert actual == expected
#function using built in methods and dictionary
def test_dict():
x = "Once upon a time, there was a brave princess who... "
actual = repeated_word_dict(x)
expected = "a"
assert actual == expected
| en | 0.823822 | #function using built in methods and dictionary | 3.611131 | 4 |
sc2_imitation_learning/agents/__init__.py | metataro/sc2_imitation_learning | 15 | 6628004 | <reponame>metataro/sc2_imitation_learning
import collections
from abc import ABC, abstractmethod
from typing import Tuple, Optional, Text
import sonnet as snt
import tensorflow as tf
import tree
from sonnet.src import types
from sc2_imitation_learning.environment.environment import ActionSpace, ObservationSpace
AgentOutput = collections.namedtuple('AgentOutput', ['logits', 'actions', 'values'])
class Agent(snt.RNNCore, ABC):
def __call__(self, prev_actions, env_outputs, core_state, unroll=False, teacher_actions=None) -> Tuple[AgentOutput, Tuple]:
if not unroll:
# Add time dimension.
prev_actions, env_outputs = tf.nest.map_structure(
lambda t: tf.expand_dims(t, 0), (prev_actions, env_outputs))
outputs, core_state = self._unroll(prev_actions, env_outputs, core_state, teacher_actions)
if not unroll:
# Remove time dimension.
outputs = tf.nest.map_structure(lambda t: None if t is None else tf.squeeze(t, 0), outputs)
return outputs, core_state
@abstractmethod
def _unroll(self, prev_actions, env_outputs, core_state, teacher_actions=None) -> Tuple[AgentOutput, Tuple]:
pass
def build_saved_agent(agent: Agent, observation_space: ObservationSpace, action_space: ActionSpace) -> tf.Module:
call_input_signature = [
tree.map_structure_with_path(
lambda path, s: tf.TensorSpec((None,) + s.shape, s.dtype, name='action/' + '/'.join(path)),
action_space.specs),
(
tf.TensorSpec((None,), dtype=tf.float32, name='reward'),
tf.TensorSpec((None,), dtype=tf.bool, name='done'),
tree.map_structure_with_path(
lambda path, s: tf.TensorSpec((None,) + s.shape, s.dtype, name='observation/' + '/'.join(path)),
observation_space.specs)
),
tree.map_structure(
lambda t: tf.TensorSpec((None,) + t.shape[1:], t.dtype, name='agent_state'), agent.initial_state(1))
]
initial_state_input_signature = [
tf.TensorSpec(shape=(), dtype=tf.int32, name='batch_size'),
]
class SavedAgent(tf.Module):
def __init__(self, agent: Agent, name=None):
super().__init__(name)
self._agent = agent
@tf.function(input_signature=call_input_signature)
def __call__(self, prev_action, env_outputs, agent_state):
return self._agent(prev_action, env_outputs, agent_state)
@tf.function(input_signature=initial_state_input_signature)
def initial_state(self, batch_size):
return self._agent.initial_state(batch_size)
return SavedAgent(agent)
| import collections
from abc import ABC, abstractmethod
from typing import Tuple, Optional, Text
import sonnet as snt
import tensorflow as tf
import tree
from sonnet.src import types
from sc2_imitation_learning.environment.environment import ActionSpace, ObservationSpace
AgentOutput = collections.namedtuple('AgentOutput', ['logits', 'actions', 'values'])
class Agent(snt.RNNCore, ABC):
def __call__(self, prev_actions, env_outputs, core_state, unroll=False, teacher_actions=None) -> Tuple[AgentOutput, Tuple]:
if not unroll:
# Add time dimension.
prev_actions, env_outputs = tf.nest.map_structure(
lambda t: tf.expand_dims(t, 0), (prev_actions, env_outputs))
outputs, core_state = self._unroll(prev_actions, env_outputs, core_state, teacher_actions)
if not unroll:
# Remove time dimension.
outputs = tf.nest.map_structure(lambda t: None if t is None else tf.squeeze(t, 0), outputs)
return outputs, core_state
@abstractmethod
def _unroll(self, prev_actions, env_outputs, core_state, teacher_actions=None) -> Tuple[AgentOutput, Tuple]:
pass
def build_saved_agent(agent: Agent, observation_space: ObservationSpace, action_space: ActionSpace) -> tf.Module:
call_input_signature = [
tree.map_structure_with_path(
lambda path, s: tf.TensorSpec((None,) + s.shape, s.dtype, name='action/' + '/'.join(path)),
action_space.specs),
(
tf.TensorSpec((None,), dtype=tf.float32, name='reward'),
tf.TensorSpec((None,), dtype=tf.bool, name='done'),
tree.map_structure_with_path(
lambda path, s: tf.TensorSpec((None,) + s.shape, s.dtype, name='observation/' + '/'.join(path)),
observation_space.specs)
),
tree.map_structure(
lambda t: tf.TensorSpec((None,) + t.shape[1:], t.dtype, name='agent_state'), agent.initial_state(1))
]
initial_state_input_signature = [
tf.TensorSpec(shape=(), dtype=tf.int32, name='batch_size'),
]
class SavedAgent(tf.Module):
def __init__(self, agent: Agent, name=None):
super().__init__(name)
self._agent = agent
@tf.function(input_signature=call_input_signature)
def __call__(self, prev_action, env_outputs, agent_state):
return self._agent(prev_action, env_outputs, agent_state)
@tf.function(input_signature=initial_state_input_signature)
def initial_state(self, batch_size):
return self._agent.initial_state(batch_size)
return SavedAgent(agent) | en | 0.636542 | # Add time dimension. # Remove time dimension. | 2.441078 | 2 |
lib/JumpScale/lib/ssh/disklayout/mount.py | rudecs/jumpscale_core7 | 0 | 6628005 | <reponame>rudecs/jumpscale_core7
from JumpScale import j
from fabric.api import settings
class MountError(Exception):
pass
class Mount(object):
def __init__(self, con, device, path=None, options=''):
self._con = con
self._device = device
self._path = path
self._autoClean = False
if self._path is None:
self._path = j.system.fs.getTmpDirPath()
self._autoClean = True
self._options = options
@property
def _mount(self):
return 'mount {options} {device} {path}'.format(
options='-o ' + self._options if self._options else '',
device=self._device,
path=self._path
)
@property
def _umount(self):
return 'umount {path}'.format(path=self._path)
@property
def path(self):
return self._path
def __enter__(self):
return self.mount()
def __exit__(self, type, value, traceback):
return self.umount()
def mount(self):
"""
Mount partition
"""
with settings(abort_exception=MountError):
self._con.dir_ensure(self.path, recursive=True)
self._con.run(self._mount)
return self
def umount(self):
"""
Umount partition
"""
with settings(abort_exception=MountError):
self._con.run(self._umount)
if self._autoClean:
self._con.dir_remove(self.path)
return self
| from JumpScale import j
from fabric.api import settings
class MountError(Exception):
pass
class Mount(object):
def __init__(self, con, device, path=None, options=''):
self._con = con
self._device = device
self._path = path
self._autoClean = False
if self._path is None:
self._path = j.system.fs.getTmpDirPath()
self._autoClean = True
self._options = options
@property
def _mount(self):
return 'mount {options} {device} {path}'.format(
options='-o ' + self._options if self._options else '',
device=self._device,
path=self._path
)
@property
def _umount(self):
return 'umount {path}'.format(path=self._path)
@property
def path(self):
return self._path
def __enter__(self):
return self.mount()
def __exit__(self, type, value, traceback):
return self.umount()
def mount(self):
"""
Mount partition
"""
with settings(abort_exception=MountError):
self._con.dir_ensure(self.path, recursive=True)
self._con.run(self._mount)
return self
def umount(self):
"""
Umount partition
"""
with settings(abort_exception=MountError):
self._con.run(self._umount)
if self._autoClean:
self._con.dir_remove(self.path)
return self | en | 0.75692 | Mount partition Umount partition | 2.292828 | 2 |
github_test.py | mitodl/release-script | 15 | 6628006 | <reponame>mitodl/release-script<filename>github_test.py
"""Tests for github functions"""
import json
import os
from urllib.parse import quote
import pytest
from constants import SCRIPT_DIR
from github import (
add_label,
create_pr,
delete_label,
get_labels,
get_org_and_repo,
get_pull_request,
github_auth_headers,
needs_review,
NEEDS_REVIEW_QUERY,
)
from test_constants import RELEASE_PR
pytestmark = pytest.mark.asyncio
async def test_needs_review(mocker):
"""Assert behavior of needs review"""
with open(
os.path.join(SCRIPT_DIR, "test_needs_review_response.json"),
"r",
encoding="utf-8",
) as f:
payload = json.load(f)
github_access_token = "token"
patched = mocker.async_patch("github.run_query", return_value=payload)
assert await needs_review(github_access_token) == [
(
"release-script",
"Add PR karma",
"https://github.com/mitodl/release-script/pull/88",
),
(
"release-script",
"Add codecov integration",
"https://github.com/mitodl/release-script/pull/85",
),
(
"release-script",
"Add repo name to certain doof messages",
"https://github.com/mitodl/release-script/pull/83",
),
(
"cookiecutter-djangoapp",
"Don't reference INSTALLED_APPS directly",
"https://github.com/mitodl/cookiecutter-djangoapp/pull/104",
),
(
"cookiecutter-djangoapp",
"Refactor docker-compose setup",
"https://github.com/mitodl/cookiecutter-djangoapp/pull/101",
),
(
"cookiecutter-djangoapp",
"Use application LOG_LEVEL environment variable for celery workers",
"https://github.com/mitodl/cookiecutter-djangoapp/pull/103",
),
(
"micromasters",
"Log failed send_automatic_email and update_percolate_memberships",
"https://github.com/mitodl/micromasters/pull/3707",
),
(
"open-discussions",
"split post display into two components",
"https://github.com/mitodl/open-discussions/pull/331",
),
(
"edx-platform",
"Exposed option to manage static asset imports for studio import",
"https://github.com/mitodl/edx-platform/pull/41",
),
]
patched.assert_called_once_with(
github_access_token=github_access_token,
query=NEEDS_REVIEW_QUERY,
)
async def test_create_pr(mocker):
"""create_pr should create a pr or raise an exception if the attempt failed"""
access_token = "github_access_token"
org = "abc"
repo = "xyz"
title = "title"
body = "body"
head = "head"
base = "base"
patched = mocker.async_patch("client_wrapper.ClientWrapper.post")
await create_pr(
github_access_token=access_token,
repo_url=f"https://github.com/{org}/{repo}.git",
title=title,
body=body,
head=head,
base=base,
)
endpoint = f"https://api.github.com/repos/{org}/{repo}/pulls"
patched.assert_called_once_with(
mocker.ANY,
endpoint,
headers={
"Authorization": f"Bearer {access_token}",
"Accept": "application/vnd.github.v3+json",
},
data=json.dumps(
{
"title": title,
"body": body,
"head": head,
"base": base,
}
),
)
async def test_github_auth_headers():
"""github_auth_headers should have appropriate headers for autentication"""
github_access_token = "access"
assert github_auth_headers(github_access_token) == {
"Authorization": f"Bearer {github_access_token}",
"Accept": "application/vnd.github.v3+json",
}
async def test_get_org_and_repo():
"""get_org_and_repo should get the GitHub organization and repo from the directory"""
for git_url in [
"<EMAIL>:mitodl/release-script.git",
"https://github.com/mitodl/release-script.git",
]:
assert get_org_and_repo(git_url) == ("mitodl", "release-script")
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
NEEDS_REVIEW_LABEL_JSON = {
"id": 324682350,
"node_id": "MDU6TGFiZWwzMjQ2ODIzNTA=",
"url": "https://api.github.com/repos/mitodl/release-script/labels/Needs%20review",
"name": "Needs review",
"color": "fef2c0",
"default": False,
"description": None,
}
TESTING_LABEL_JSON = {
"id": 2994207717,
"node_id": "MDU6TGFiZWwyOTk0MjA3NzE3",
"url": "https://api.github.com/repos/mitodl/release-script/labels/testing",
"name": "testing",
"color": "ededed",
"default": False,
"description": None,
}
async def test_get_labels(mocker):
"""get_labels should retrieve labels from github"""
response = mocker.Mock(
json=mocker.Mock(return_value=[NEEDS_REVIEW_LABEL_JSON, TESTING_LABEL_JSON])
)
patched = mocker.async_patch(
"client_wrapper.ClientWrapper.get", return_value=response
)
token = "token"
org = "mitodl"
repo = "release-script"
repo_url = f"<EMAIL>:{org}/{repo}.git"
pr_number = 1234
assert await get_labels(
github_access_token=token, repo_url=repo_url, pr_number=pr_number
) == [NEEDS_REVIEW_LABEL_JSON["name"], TESTING_LABEL_JSON["name"]]
patched.assert_called_once_with(
mocker.ANY,
f"https://api.github.com/repos/{org}/{repo}/issues/{pr_number}/labels",
headers=github_auth_headers(token),
)
response.raise_for_status.assert_called_once_with()
async def test_add_label(mocker):
"""add_label should add a new label on a pr"""
response = mocker.Mock()
patched = mocker.async_patch(
"client_wrapper.ClientWrapper.post", return_value=response
)
token = "token"
org = "mitodl"
repo = "release-script"
repo_url = f"<EMAIL>:{org}/{repo}.git"
pr_number = 1234
label = "new label"
await add_label(
github_access_token=token,
repo_url=repo_url,
pr_number=pr_number,
label=label,
)
patched.assert_called_once_with(
mocker.ANY,
f"https://api.github.com/repos/{org}/{repo}/issues/{pr_number}/labels",
json={"labels": [label]},
headers=github_auth_headers(token),
)
response.raise_for_status.assert_called_once_with()
@pytest.mark.parametrize(
"status, expected_raise_for_status", [[200, True], [400, True], [404, False]]
)
async def test_delete_label(mocker, status, expected_raise_for_status):
"""delete_label should remove a label from a pr"""
response = mocker.Mock(status_code=status)
patched = mocker.async_patch(
"client_wrapper.ClientWrapper.delete", return_value=response
)
token = "token"
org = "mitodl"
repo = "release-script"
repo_url = f"<EMAIL>:{org}/{repo}.git"
pr_number = 1234
label = "existing label"
await delete_label(
github_access_token=token,
repo_url=repo_url,
pr_number=pr_number,
label=label,
)
patched.assert_called_once_with(
mocker.ANY,
f"https://api.github.com/repos/{org}/{repo}/issues/{pr_number}/labels/{quote(label)}",
headers=github_auth_headers(token),
)
assert response.raise_for_status.called is expected_raise_for_status
@pytest.mark.parametrize("all_prs", [True, False])
@pytest.mark.parametrize("has_pr", [True, False])
async def test_get_pull_request(mocker, all_prs, has_pr):
"""get_pull_request should fetch a pull request from GitHub's API"""
org = "org"
repo = "repo"
access_token = "access"
branch = "release-candidate"
get_mock = mocker.async_patch(
"client_wrapper.ClientWrapper.get",
return_value=mocker.Mock(
json=mocker.Mock(return_value=[RELEASE_PR] if has_pr else [])
),
)
response = await get_pull_request(
github_access_token=access_token,
org=org,
repo=repo,
branch=branch,
all_prs=all_prs,
)
assert response == (RELEASE_PR if has_pr else None)
get_mock.return_value.raise_for_status.assert_called_once_with()
state = "all" if all_prs else "open"
get_mock.assert_called_once_with(
mocker.ANY,
f"https://api.github.com/repos/{org}/{repo}/pulls?state={state}&head={org}:{branch}&per_page=1",
headers=github_auth_headers(access_token),
)
| """Tests for github functions"""
import json
import os
from urllib.parse import quote
import pytest
from constants import SCRIPT_DIR
from github import (
add_label,
create_pr,
delete_label,
get_labels,
get_org_and_repo,
get_pull_request,
github_auth_headers,
needs_review,
NEEDS_REVIEW_QUERY,
)
from test_constants import RELEASE_PR
pytestmark = pytest.mark.asyncio
async def test_needs_review(mocker):
"""Assert behavior of needs review"""
with open(
os.path.join(SCRIPT_DIR, "test_needs_review_response.json"),
"r",
encoding="utf-8",
) as f:
payload = json.load(f)
github_access_token = "token"
patched = mocker.async_patch("github.run_query", return_value=payload)
assert await needs_review(github_access_token) == [
(
"release-script",
"Add PR karma",
"https://github.com/mitodl/release-script/pull/88",
),
(
"release-script",
"Add codecov integration",
"https://github.com/mitodl/release-script/pull/85",
),
(
"release-script",
"Add repo name to certain doof messages",
"https://github.com/mitodl/release-script/pull/83",
),
(
"cookiecutter-djangoapp",
"Don't reference INSTALLED_APPS directly",
"https://github.com/mitodl/cookiecutter-djangoapp/pull/104",
),
(
"cookiecutter-djangoapp",
"Refactor docker-compose setup",
"https://github.com/mitodl/cookiecutter-djangoapp/pull/101",
),
(
"cookiecutter-djangoapp",
"Use application LOG_LEVEL environment variable for celery workers",
"https://github.com/mitodl/cookiecutter-djangoapp/pull/103",
),
(
"micromasters",
"Log failed send_automatic_email and update_percolate_memberships",
"https://github.com/mitodl/micromasters/pull/3707",
),
(
"open-discussions",
"split post display into two components",
"https://github.com/mitodl/open-discussions/pull/331",
),
(
"edx-platform",
"Exposed option to manage static asset imports for studio import",
"https://github.com/mitodl/edx-platform/pull/41",
),
]
patched.assert_called_once_with(
github_access_token=github_access_token,
query=NEEDS_REVIEW_QUERY,
)
async def test_create_pr(mocker):
"""create_pr should create a pr or raise an exception if the attempt failed"""
access_token = "github_access_token"
org = "abc"
repo = "xyz"
title = "title"
body = "body"
head = "head"
base = "base"
patched = mocker.async_patch("client_wrapper.ClientWrapper.post")
await create_pr(
github_access_token=access_token,
repo_url=f"https://github.com/{org}/{repo}.git",
title=title,
body=body,
head=head,
base=base,
)
endpoint = f"https://api.github.com/repos/{org}/{repo}/pulls"
patched.assert_called_once_with(
mocker.ANY,
endpoint,
headers={
"Authorization": f"Bearer {access_token}",
"Accept": "application/vnd.github.v3+json",
},
data=json.dumps(
{
"title": title,
"body": body,
"head": head,
"base": base,
}
),
)
async def test_github_auth_headers():
"""github_auth_headers should have appropriate headers for autentication"""
github_access_token = "access"
assert github_auth_headers(github_access_token) == {
"Authorization": f"Bearer {github_access_token}",
"Accept": "application/vnd.github.v3+json",
}
async def test_get_org_and_repo():
"""get_org_and_repo should get the GitHub organization and repo from the directory"""
for git_url in [
"<EMAIL>:mitodl/release-script.git",
"https://github.com/mitodl/release-script.git",
]:
assert get_org_and_repo(git_url) == ("mitodl", "release-script")
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
NEEDS_REVIEW_LABEL_JSON = {
"id": 324682350,
"node_id": "MDU6TGFiZWwzMjQ2ODIzNTA=",
"url": "https://api.github.com/repos/mitodl/release-script/labels/Needs%20review",
"name": "Needs review",
"color": "fef2c0",
"default": False,
"description": None,
}
TESTING_LABEL_JSON = {
"id": 2994207717,
"node_id": "MDU6TGFiZWwyOTk0MjA3NzE3",
"url": "https://api.github.com/repos/mitodl/release-script/labels/testing",
"name": "testing",
"color": "ededed",
"default": False,
"description": None,
}
async def test_get_labels(mocker):
"""get_labels should retrieve labels from github"""
response = mocker.Mock(
json=mocker.Mock(return_value=[NEEDS_REVIEW_LABEL_JSON, TESTING_LABEL_JSON])
)
patched = mocker.async_patch(
"client_wrapper.ClientWrapper.get", return_value=response
)
token = "token"
org = "mitodl"
repo = "release-script"
repo_url = f"<EMAIL>:{org}/{repo}.git"
pr_number = 1234
assert await get_labels(
github_access_token=token, repo_url=repo_url, pr_number=pr_number
) == [NEEDS_REVIEW_LABEL_JSON["name"], TESTING_LABEL_JSON["name"]]
patched.assert_called_once_with(
mocker.ANY,
f"https://api.github.com/repos/{org}/{repo}/issues/{pr_number}/labels",
headers=github_auth_headers(token),
)
response.raise_for_status.assert_called_once_with()
async def test_add_label(mocker):
"""add_label should add a new label on a pr"""
response = mocker.Mock()
patched = mocker.async_patch(
"client_wrapper.ClientWrapper.post", return_value=response
)
token = "token"
org = "mitodl"
repo = "release-script"
repo_url = f"<EMAIL>:{org}/{repo}.git"
pr_number = 1234
label = "new label"
await add_label(
github_access_token=token,
repo_url=repo_url,
pr_number=pr_number,
label=label,
)
patched.assert_called_once_with(
mocker.ANY,
f"https://api.github.com/repos/{org}/{repo}/issues/{pr_number}/labels",
json={"labels": [label]},
headers=github_auth_headers(token),
)
response.raise_for_status.assert_called_once_with()
@pytest.mark.parametrize(
"status, expected_raise_for_status", [[200, True], [400, True], [404, False]]
)
async def test_delete_label(mocker, status, expected_raise_for_status):
"""delete_label should remove a label from a pr"""
response = mocker.Mock(status_code=status)
patched = mocker.async_patch(
"client_wrapper.ClientWrapper.delete", return_value=response
)
token = "token"
org = "mitodl"
repo = "release-script"
repo_url = f"<EMAIL>:{org}/{repo}.git"
pr_number = 1234
label = "existing label"
await delete_label(
github_access_token=token,
repo_url=repo_url,
pr_number=pr_number,
label=label,
)
patched.assert_called_once_with(
mocker.ANY,
f"https://api.github.com/repos/{org}/{repo}/issues/{pr_number}/labels/{quote(label)}",
headers=github_auth_headers(token),
)
assert response.raise_for_status.called is expected_raise_for_status
@pytest.mark.parametrize("all_prs", [True, False])
@pytest.mark.parametrize("has_pr", [True, False])
async def test_get_pull_request(mocker, all_prs, has_pr):
"""get_pull_request should fetch a pull request from GitHub's API"""
org = "org"
repo = "repo"
access_token = "access"
branch = "release-candidate"
get_mock = mocker.async_patch(
"client_wrapper.ClientWrapper.get",
return_value=mocker.Mock(
json=mocker.Mock(return_value=[RELEASE_PR] if has_pr else [])
),
)
response = await get_pull_request(
github_access_token=access_token,
org=org,
repo=repo,
branch=branch,
all_prs=all_prs,
)
assert response == (RELEASE_PR if has_pr else None)
get_mock.return_value.raise_for_status.assert_called_once_with()
state = "all" if all_prs else "open"
get_mock.assert_called_once_with(
mocker.ANY,
f"https://api.github.com/repos/{org}/{repo}/pulls?state={state}&head={org}:{branch}&per_page=1",
headers=github_auth_headers(access_token),
) | en | 0.746566 | Tests for github functions Assert behavior of needs review create_pr should create a pr or raise an exception if the attempt failed github_auth_headers should have appropriate headers for autentication get_org_and_repo should get the GitHub organization and repo from the directory get_labels should retrieve labels from github add_label should add a new label on a pr delete_label should remove a label from a pr get_pull_request should fetch a pull request from GitHub's API | 2.29133 | 2 |
pagesext/tests/__init__.py | dlancer/django-pages-cms-extensions | 1 | 6628007 | <filename>pagesext/tests/__init__.py
from pagesext.tests.test_pages import *
__test__ = {'pagesext.tests.TestPages': ['test_pages']}
| <filename>pagesext/tests/__init__.py
from pagesext.tests.test_pages import *
__test__ = {'pagesext.tests.TestPages': ['test_pages']}
| none | 1 | 1.394802 | 1 | |
animation_experimentation.py | tobyrcod/PiPet | 1 | 6628008 | from sense_hat import SenseHat
from time import sleep
import random
s = SenseHat()
default = True
p = (190, 174, 243)
b = (0,0,0)
w = (255, 255, 255)
yellow = (255, 255, 0)
blue = (0, 0, 255)
#prow = [p, p, p, p, p, p, p, p] #this does not work, when replace this with a whole row
#a pixel list must have 64 elements in it
#when creating designs, helps to draw it out by hand
default = [
p, p, p, p, p, p, p, p,
p, p, p, p, p, p, p, p,
p, b, p, p, p, p, b, p,
p, p, p, p, p, p, p, p,
p, p, b, p, p, b, p, p,
p, p, p, b, b, p, p, p,
p, p, p, p, p, p, p, p,
p, p, p, p, p, p, p, p
]
shock_high = [
p, p, p, p, p, p, p, p,
p, p, p, p, p, p, p, p,
p, b, p, p, p, p, b, p,
p, p, p, b, b, p, p, p,
p, p, p, b, b, p, p, p,
p, p, p, p, p, p, p, p,
p, p, p, p, p, p, p, p,
p, p, p, p, p, p, p, p
]
shock_low = [
p, p, p, p, p, p, p, p,
p, p, p, p, p, p, p, p,
p, p, p, p, p, p, p, p,
p, p, b, p, p, p, p, b,
p, p, p, p, b, b, p, p,
p, p, p, p, b, b, p, p,
p, p, p, p, p, p, p, p,
p, p, p, p, p, p, p, p
]
lsmile_eClosed = [
p, p, p, p, p, p, p, p,
p, p, p, p, p, p, p, p,
p, p, p, p, p, p, p, p,
p, p, p, p, p, p, p, p,
p, b, b, p, p, b, b, p,
p, p, p, p, p, p, p, p,
p, p, b, p, p, b, p, p,
p, p, p, b, b, p, p, p
]
hsmile_eClosed = [
p, p, p, p, p, p, p, p,
p, p, p, p, p, p, p, p,
p, p, p, p, p, p, p, p,
p, b, b, p, p, b, b, p,
p, p, p, p, p, p, p, p,
p, p, b, p, p, b, p, p,
p, p, p, b, b, p, p, p,
p, p, p, p, p, p, p, p
]
def smile_nod():
#s.clear(w)
s.set_pixels(hsmile_eClosed)
sleep(0.25)
for i in range(2):
s.set_pixels(lsmile_eClosed)
sleep(0.25)
s.set_pixels(hsmile_eClosed)
sleep(0.25)
def shock():
s.set_pixels(shock_low)
for i in range(2):
sleep(0.25)
s.flip_h()
def random():#may work in actual environment, as its a browser, may not import all things
while True:
rand_face = []
for i in range(64):
rand1 = random.randint(0, 255)
rand2 = random.randint(0, 255)
rand3 = random.randint(0, 255)
r_colour = (rand1, rand2, rand3)
#rand_face.append(rand)
s.set_pixels(rand_face)
sleep(0.5)
#s.show_message("Hello", text_colour = yellow, back_colour = blue)
s.set_pixels(default)
sleep(0.25)
default = False
print(random.randint(0,9))
if default == False:
#could do, if previous state == default, for more fluid animation
#could pass the previous display as a paramter
smile_nod()
sleep(0.25) #if you dont use this sleep funct, program may miss out the next line
#as there is no break, skips next line
shock()
random()
| from sense_hat import SenseHat
from time import sleep
import random
s = SenseHat()
default = True
p = (190, 174, 243)
b = (0,0,0)
w = (255, 255, 255)
yellow = (255, 255, 0)
blue = (0, 0, 255)
#prow = [p, p, p, p, p, p, p, p] #this does not work, when replace this with a whole row
#a pixel list must have 64 elements in it
#when creating designs, helps to draw it out by hand
default = [
p, p, p, p, p, p, p, p,
p, p, p, p, p, p, p, p,
p, b, p, p, p, p, b, p,
p, p, p, p, p, p, p, p,
p, p, b, p, p, b, p, p,
p, p, p, b, b, p, p, p,
p, p, p, p, p, p, p, p,
p, p, p, p, p, p, p, p
]
shock_high = [
p, p, p, p, p, p, p, p,
p, p, p, p, p, p, p, p,
p, b, p, p, p, p, b, p,
p, p, p, b, b, p, p, p,
p, p, p, b, b, p, p, p,
p, p, p, p, p, p, p, p,
p, p, p, p, p, p, p, p,
p, p, p, p, p, p, p, p
]
shock_low = [
p, p, p, p, p, p, p, p,
p, p, p, p, p, p, p, p,
p, p, p, p, p, p, p, p,
p, p, b, p, p, p, p, b,
p, p, p, p, b, b, p, p,
p, p, p, p, b, b, p, p,
p, p, p, p, p, p, p, p,
p, p, p, p, p, p, p, p
]
lsmile_eClosed = [
p, p, p, p, p, p, p, p,
p, p, p, p, p, p, p, p,
p, p, p, p, p, p, p, p,
p, p, p, p, p, p, p, p,
p, b, b, p, p, b, b, p,
p, p, p, p, p, p, p, p,
p, p, b, p, p, b, p, p,
p, p, p, b, b, p, p, p
]
hsmile_eClosed = [
p, p, p, p, p, p, p, p,
p, p, p, p, p, p, p, p,
p, p, p, p, p, p, p, p,
p, b, b, p, p, b, b, p,
p, p, p, p, p, p, p, p,
p, p, b, p, p, b, p, p,
p, p, p, b, b, p, p, p,
p, p, p, p, p, p, p, p
]
def smile_nod():
#s.clear(w)
s.set_pixels(hsmile_eClosed)
sleep(0.25)
for i in range(2):
s.set_pixels(lsmile_eClosed)
sleep(0.25)
s.set_pixels(hsmile_eClosed)
sleep(0.25)
def shock():
s.set_pixels(shock_low)
for i in range(2):
sleep(0.25)
s.flip_h()
def random():#may work in actual environment, as its a browser, may not import all things
while True:
rand_face = []
for i in range(64):
rand1 = random.randint(0, 255)
rand2 = random.randint(0, 255)
rand3 = random.randint(0, 255)
r_colour = (rand1, rand2, rand3)
#rand_face.append(rand)
s.set_pixels(rand_face)
sleep(0.5)
#s.show_message("Hello", text_colour = yellow, back_colour = blue)
s.set_pixels(default)
sleep(0.25)
default = False
print(random.randint(0,9))
if default == False:
#could do, if previous state == default, for more fluid animation
#could pass the previous display as a paramter
smile_nod()
sleep(0.25) #if you dont use this sleep funct, program may miss out the next line
#as there is no break, skips next line
shock()
random()
| en | 0.796885 | #prow = [p, p, p, p, p, p, p, p] #this does not work, when replace this with a whole row #a pixel list must have 64 elements in it #when creating designs, helps to draw it out by hand #s.clear(w) #may work in actual environment, as its a browser, may not import all things #rand_face.append(rand) #s.show_message("Hello", text_colour = yellow, back_colour = blue) #could do, if previous state == default, for more fluid animation #could pass the previous display as a paramter #if you dont use this sleep funct, program may miss out the next line #as there is no break, skips next line | 2.580833 | 3 |
arduino/portable/sketchbook/libraries/Adafruit_MQTT_Library/examples/mqtt_arbitrary_data/python_subscriber/subscriber.py | devshop2019/mixlyTest | 542 | 6628009 | <filename>arduino/portable/sketchbook/libraries/Adafruit_MQTT_Library/examples/mqtt_arbitrary_data/python_subscriber/subscriber.py
'''MQTT subscriber for Adafruit MQTT library mqtt_arbitrary_buffer example'''
import paho.mqtt.client as mqtt
import argparse
import struct
import array
import sys
return_str =[
"Connection successful",
"incorrect protocol version",
"invalid client identifier",
"server unavailable",
"bad username or password",
"not authorised"
]
args = None
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, rc):
"""callback function on connect. Subscribes or exits depending on outcome"""
print("MQTT: "),
print(return_str[rc])
if(rc > 1):
print("Connection refused - " + return_str[rc])
sys.exit(rc)
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
else:
print(return_str[rc])
client.subscribe(args.topic)
print("Subscribed to {}".format(args.topic))
def on_disconnect(client, userdata, rc):
"""Callback for disconnect"""
if rc != 0:
print("Unexpected disconnection.")
client.reconnect()
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
try:
pMsg = parseMsg(msg.payload)
print("Received char Array: \"{}\", val1: {}, val2: {}, val3: {}...".format(pMsg[0], pMsg[1], pMsg[2], pMsg[3]))
except Exception as err:
print err
def argBegin():
parser = argparse.ArgumentParser(description='MQTT subscriber for Adafruit MQTT library mqtt_arbitrary_buffer example')
parser.add_argument("--host", default="localhost", help='mqtt host to connect to. Defaults to localhost.')
parser.add_argument("-p", "--port", default=1883, help='network port to connect to. Defaults to 1883.')
parser.add_argument("-t", "--topic", nargs='*', default="/feeds/arb_packet", help="mqtt topic to subscribe to. May be repeated multiple times.")
parser.add_argument("-u", "--username", default="testPy", help="provide a username (requires MQTT 3.1 broker)")
parser.add_argument("-P", "--password", default="<PASSWORD>", help="provide a password (requires MQTT 3.1 broker)")
parser.add_argument("-k", "--keepalive", default=60, help="keep alive in seconds for this client. Defaults to 60.")
return parser.parse_args()
def parseMsg(payload):
"""Parses C struct from MQTT publisher Adafruit MQTT client to Python list"""
arr = array.array('B', payload) #convert python list to C-like array of unsigned char (B)
parsedStruct = struct.Struct('< 10s h L H') #define struct template (see below)
'''
Format of Struct from Adafruit MQTT client, Arduino, etc:
Adafruit MQTT client == Little endian (<)
Var NAME | C TYPE (python symbol) | size of member x bytes
-------------------------------------------------------------------
"charAry" | uchar (s) | 10s x 1 = 10 bytes
"val1" | int16 / short (h) | 1h x 2 = 2 bytes
"val2" | unsigned long (L) | 1L x 4 = 4 bytes
"val3" | uint16/unsigned short(H)| 1H x 2 = 2 bytes
------------------------------------------------------------------
Total packet size = | 18 bytes |
See Section 7.3.2 of Python struct module documentation for complete format list
https://docs.python.org/2/library/struct.html
'''
charAry, val1, val2, val3 = parsedStruct.unpack_from(arr) #convert byte array to formatted struct
charAry = charAry.rstrip(' \t\r\n\0') #remove trailing white space from buffer
return charAry, val1, val2, val3
def main():
"""Wait for incoming message published by Adafruit MQTT client"""
global args
args = argBegin()
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set(args.username, args.password)
client.connect(args.host, args.port, args.keepalive)
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()
if __name__ == '__main__':
sys.exit(main())
| <filename>arduino/portable/sketchbook/libraries/Adafruit_MQTT_Library/examples/mqtt_arbitrary_data/python_subscriber/subscriber.py
'''MQTT subscriber for Adafruit MQTT library mqtt_arbitrary_buffer example'''
import paho.mqtt.client as mqtt
import argparse
import struct
import array
import sys
return_str =[
"Connection successful",
"incorrect protocol version",
"invalid client identifier",
"server unavailable",
"bad username or password",
"not authorised"
]
args = None
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, rc):
"""callback function on connect. Subscribes or exits depending on outcome"""
print("MQTT: "),
print(return_str[rc])
if(rc > 1):
print("Connection refused - " + return_str[rc])
sys.exit(rc)
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
else:
print(return_str[rc])
client.subscribe(args.topic)
print("Subscribed to {}".format(args.topic))
def on_disconnect(client, userdata, rc):
"""Callback for disconnect"""
if rc != 0:
print("Unexpected disconnection.")
client.reconnect()
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
try:
pMsg = parseMsg(msg.payload)
print("Received char Array: \"{}\", val1: {}, val2: {}, val3: {}...".format(pMsg[0], pMsg[1], pMsg[2], pMsg[3]))
except Exception as err:
print err
def argBegin():
parser = argparse.ArgumentParser(description='MQTT subscriber for Adafruit MQTT library mqtt_arbitrary_buffer example')
parser.add_argument("--host", default="localhost", help='mqtt host to connect to. Defaults to localhost.')
parser.add_argument("-p", "--port", default=1883, help='network port to connect to. Defaults to 1883.')
parser.add_argument("-t", "--topic", nargs='*', default="/feeds/arb_packet", help="mqtt topic to subscribe to. May be repeated multiple times.")
parser.add_argument("-u", "--username", default="testPy", help="provide a username (requires MQTT 3.1 broker)")
parser.add_argument("-P", "--password", default="<PASSWORD>", help="provide a password (requires MQTT 3.1 broker)")
parser.add_argument("-k", "--keepalive", default=60, help="keep alive in seconds for this client. Defaults to 60.")
return parser.parse_args()
def parseMsg(payload):
"""Parses C struct from MQTT publisher Adafruit MQTT client to Python list"""
arr = array.array('B', payload) #convert python list to C-like array of unsigned char (B)
parsedStruct = struct.Struct('< 10s h L H') #define struct template (see below)
'''
Format of Struct from Adafruit MQTT client, Arduino, etc:
Adafruit MQTT client == Little endian (<)
Var NAME | C TYPE (python symbol) | size of member x bytes
-------------------------------------------------------------------
"charAry" | uchar (s) | 10s x 1 = 10 bytes
"val1" | int16 / short (h) | 1h x 2 = 2 bytes
"val2" | unsigned long (L) | 1L x 4 = 4 bytes
"val3" | uint16/unsigned short(H)| 1H x 2 = 2 bytes
------------------------------------------------------------------
Total packet size = | 18 bytes |
See Section 7.3.2 of Python struct module documentation for complete format list
https://docs.python.org/2/library/struct.html
'''
charAry, val1, val2, val3 = parsedStruct.unpack_from(arr) #convert byte array to formatted struct
charAry = charAry.rstrip(' \t\r\n\0') #remove trailing white space from buffer
return charAry, val1, val2, val3
def main():
"""Wait for incoming message published by Adafruit MQTT client"""
global args
args = argBegin()
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set(args.username, args.password)
client.connect(args.host, args.port, args.keepalive)
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()
if __name__ == '__main__':
sys.exit(main())
| en | 0.748585 | MQTT subscriber for Adafruit MQTT library mqtt_arbitrary_buffer example # The callback for when the client receives a CONNACK response from the server. callback function on connect. Subscribes or exits depending on outcome # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. Callback for disconnect # The callback for when a PUBLISH message is received from the server. Parses C struct from MQTT publisher Adafruit MQTT client to Python list #convert python list to C-like array of unsigned char (B) #define struct template (see below) Format of Struct from Adafruit MQTT client, Arduino, etc: Adafruit MQTT client == Little endian (<) Var NAME | C TYPE (python symbol) | size of member x bytes ------------------------------------------------------------------- "charAry" | uchar (s) | 10s x 1 = 10 bytes "val1" | int16 / short (h) | 1h x 2 = 2 bytes "val2" | unsigned long (L) | 1L x 4 = 4 bytes "val3" | uint16/unsigned short(H)| 1H x 2 = 2 bytes ------------------------------------------------------------------ Total packet size = | 18 bytes | See Section 7.3.2 of Python struct module documentation for complete format list https://docs.python.org/2/library/struct.html #convert byte array to formatted struct #remove trailing white space from buffer Wait for incoming message published by Adafruit MQTT client # Blocking call that processes network traffic, dispatches callbacks and # handles reconnecting. # Other loop*() functions are available that give a threaded interface and a # manual interface. | 2.860579 | 3 |
twig/compiler.py | vaporydev/twig | 16 | 6628010 | from pathlib import Path
from typing import Any, Dict
from ethpm.tools import builder as b
from ethpm.typing import Manifest
from twig.backends import VyperBackend
from twig.exceptions import CompilerError
from twig.utils.compiler import generate_contract_types, generate_inline_sources
class Compiler:
# todo solidity backend - start from solc output &/or source contracts
def __init__(self, sources_dir: Path, backend: VyperBackend) -> None:
self.sources_dir = sources_dir
self.backend = backend
self.output: Dict[str, Any] = None
def compile(self) -> None:
if self.output:
raise CompilerError(
"This instance of Compiler already contains compiler output."
)
self.output = self.backend.compile(self.sources_dir)
def get_contract_types(self) -> Dict[str, Any]:
if not self.output:
self.compile()
return generate_contract_types(self.output)
def get_source_tree(self) -> Dict[str, str]:
if not self.output:
self.compile()
return generate_inline_sources(self.output, self.sources_dir)
def get_simple_manifest(self, name: str, version: str) -> Manifest:
composed_contract_types = self.get_contract_types()
composed_inline_sources = self.get_source_tree()
manifest = b.build(
{},
b.package_name(name),
b.version(version),
b.manifest_version("2"),
*composed_inline_sources,
*composed_contract_types,
b.validate(),
)
return manifest
| from pathlib import Path
from typing import Any, Dict
from ethpm.tools import builder as b
from ethpm.typing import Manifest
from twig.backends import VyperBackend
from twig.exceptions import CompilerError
from twig.utils.compiler import generate_contract_types, generate_inline_sources
class Compiler:
# todo solidity backend - start from solc output &/or source contracts
def __init__(self, sources_dir: Path, backend: VyperBackend) -> None:
self.sources_dir = sources_dir
self.backend = backend
self.output: Dict[str, Any] = None
def compile(self) -> None:
if self.output:
raise CompilerError(
"This instance of Compiler already contains compiler output."
)
self.output = self.backend.compile(self.sources_dir)
def get_contract_types(self) -> Dict[str, Any]:
if not self.output:
self.compile()
return generate_contract_types(self.output)
def get_source_tree(self) -> Dict[str, str]:
if not self.output:
self.compile()
return generate_inline_sources(self.output, self.sources_dir)
def get_simple_manifest(self, name: str, version: str) -> Manifest:
composed_contract_types = self.get_contract_types()
composed_inline_sources = self.get_source_tree()
manifest = b.build(
{},
b.package_name(name),
b.version(version),
b.manifest_version("2"),
*composed_inline_sources,
*composed_contract_types,
b.validate(),
)
return manifest
| en | 0.539183 | # todo solidity backend - start from solc output &/or source contracts | 2.060652 | 2 |
kernel_two_sample_test.py | FabianHinder/drifting-data-in-continuous-time | 2 | 6628011 | <gh_stars>1-10
from __future__ import division
import numpy as np
from sys import stdout
from sklearn.metrics import pairwise_kernels
def MMD2u(K, m, n):
"""The MMD^2_u unbiased statistic.
"""
Kx = K[:m, :m]
Ky = K[m:, m:]
Kxy = K[:m, m:]
return 1.0 / (m * (m - 1.0)) * (Kx.sum() - Kx.diagonal().sum()) + \
1.0 / (n * (n - 1.0)) * (Ky.sum() - Ky.diagonal().sum()) - \
2.0 / (m * n) * Kxy.sum()
def compute_null_distribution(K, m, n, iterations=10000, verbose=False,
random_state=None, marker_interval=1000):
"""Compute the bootstrap null-distribution of MMD2u.
"""
if type(random_state) == type(np.random.RandomState()):
rng = random_state
else:
rng = np.random.RandomState(random_state)
mmd2u_null = np.zeros(iterations)
for i in range(iterations):
if verbose and (i % marker_interval) == 0:
print(i),
stdout.flush()
idx = rng.permutation(m+n)
K_i = K[idx, idx[:, None]]
mmd2u_null[i] = MMD2u(K_i, m, n)
if verbose:
print("")
return mmd2u_null
def compute_null_distribution_given_permutations(K, m, n, permutation,
iterations=None):
"""Compute the bootstrap null-distribution of MMD2u given
predefined permutations.
Note:: verbosity is removed to improve speed.
"""
if iterations is None:
iterations = len(permutation)
mmd2u_null = np.zeros(iterations)
for i in range(iterations):
idx = permutation[i]
K_i = K[idx, idx[:, None]]
mmd2u_null[i] = MMD2u(K_i, m, n)
return mmd2u_null
def kernel_two_sample_test(X, Y, kernel_function='rbf', iterations=500,
verbose=False, random_state=None, **kwargs):
"""Compute MMD^2_u, its null distribution and the p-value of the
kernel two-sample test.
Note that extra parameters captured by **kwargs will be passed to
pairwise_kernels() as kernel parameters. E.g. if
kernel_two_sample_test(..., kernel_function='rbf', gamma=0.1),
then this will result in getting the kernel through
kernel_function(metric='rbf', gamma=0.1).
"""
m = len(X)
n = len(Y)
XY = np.vstack([X, Y])
K = pairwise_kernels(XY, metric=kernel_function, **kwargs)
mmd2u = MMD2u(K, m, n)
if verbose:
print("MMD^2_u = %s" % mmd2u)
print("Computing the null distribution.")
mmd2u_null = compute_null_distribution(K, m, n, iterations,
verbose=verbose,
random_state=random_state)
p_value = max(1.0/iterations, (mmd2u_null > mmd2u).sum() /
float(iterations))
if verbose:
print("p-value ~= %s \t (resolution : %s)" % (p_value, 1.0/iterations))
return mmd2u, mmd2u_null, p_value
if __name__ == '__main__':
import matplotlib.pyplot as plt
from sklearn.metrics import pairwise_distances
np.random.seed(0)
m = 20
n = 20
d = 2
sigma2X = np.eye(d)
muX = np.zeros(d)
sigma2Y = np.eye(d)
muY = np.ones(d)
# muY = np.zeros(d)
iterations = 10000
X = np.random.multivariate_normal(mean=muX, cov=sigma2X, size=m)
Y = np.random.multivariate_normal(mean=muY, cov=sigma2Y, size=n)
if d == 2:
plt.figure()
plt.plot(X[:, 0], X[:, 1], 'bo')
plt.plot(Y[:, 0], Y[:, 1], 'rx')
sigma2 = np.median(pairwise_distances(X, Y, metric='euclidean'))**2
mmd2u, mmd2u_null, p_value = kernel_two_sample_test(X, Y,
kernel_function='rbf',
gamma=1.0/sigma2,
verbose=True)
# mmd2u, mmd2u_null, p_value = kernel_two_sample_test(X, Y,
# kernel_function='linear',
# verbose=True)
plt.figure()
prob, bins, patches = plt.hist(mmd2u_null, bins=50, normed=True)
plt.plot(mmd2u, prob.max()/30, 'w*', markersize=24, markeredgecolor='k',
markeredgewidth=2, label="$MMD^2_u = %s$" % mmd2u)
plt.xlabel('$MMD^2_u$')
plt.ylabel('$p(MMD^2_u)$')
plt.legend(numpoints=1)
plt.title('$MMD^2_u$: null-distribution and observed value. $p$-value=%s'
% p_value)
plt.show()
| from __future__ import division
import numpy as np
from sys import stdout
from sklearn.metrics import pairwise_kernels
def MMD2u(K, m, n):
"""The MMD^2_u unbiased statistic.
"""
Kx = K[:m, :m]
Ky = K[m:, m:]
Kxy = K[:m, m:]
return 1.0 / (m * (m - 1.0)) * (Kx.sum() - Kx.diagonal().sum()) + \
1.0 / (n * (n - 1.0)) * (Ky.sum() - Ky.diagonal().sum()) - \
2.0 / (m * n) * Kxy.sum()
def compute_null_distribution(K, m, n, iterations=10000, verbose=False,
random_state=None, marker_interval=1000):
"""Compute the bootstrap null-distribution of MMD2u.
"""
if type(random_state) == type(np.random.RandomState()):
rng = random_state
else:
rng = np.random.RandomState(random_state)
mmd2u_null = np.zeros(iterations)
for i in range(iterations):
if verbose and (i % marker_interval) == 0:
print(i),
stdout.flush()
idx = rng.permutation(m+n)
K_i = K[idx, idx[:, None]]
mmd2u_null[i] = MMD2u(K_i, m, n)
if verbose:
print("")
return mmd2u_null
def compute_null_distribution_given_permutations(K, m, n, permutation,
iterations=None):
"""Compute the bootstrap null-distribution of MMD2u given
predefined permutations.
Note:: verbosity is removed to improve speed.
"""
if iterations is None:
iterations = len(permutation)
mmd2u_null = np.zeros(iterations)
for i in range(iterations):
idx = permutation[i]
K_i = K[idx, idx[:, None]]
mmd2u_null[i] = MMD2u(K_i, m, n)
return mmd2u_null
def kernel_two_sample_test(X, Y, kernel_function='rbf', iterations=500,
verbose=False, random_state=None, **kwargs):
"""Compute MMD^2_u, its null distribution and the p-value of the
kernel two-sample test.
Note that extra parameters captured by **kwargs will be passed to
pairwise_kernels() as kernel parameters. E.g. if
kernel_two_sample_test(..., kernel_function='rbf', gamma=0.1),
then this will result in getting the kernel through
kernel_function(metric='rbf', gamma=0.1).
"""
m = len(X)
n = len(Y)
XY = np.vstack([X, Y])
K = pairwise_kernels(XY, metric=kernel_function, **kwargs)
mmd2u = MMD2u(K, m, n)
if verbose:
print("MMD^2_u = %s" % mmd2u)
print("Computing the null distribution.")
mmd2u_null = compute_null_distribution(K, m, n, iterations,
verbose=verbose,
random_state=random_state)
p_value = max(1.0/iterations, (mmd2u_null > mmd2u).sum() /
float(iterations))
if verbose:
print("p-value ~= %s \t (resolution : %s)" % (p_value, 1.0/iterations))
return mmd2u, mmd2u_null, p_value
if __name__ == '__main__':
import matplotlib.pyplot as plt
from sklearn.metrics import pairwise_distances
np.random.seed(0)
m = 20
n = 20
d = 2
sigma2X = np.eye(d)
muX = np.zeros(d)
sigma2Y = np.eye(d)
muY = np.ones(d)
# muY = np.zeros(d)
iterations = 10000
X = np.random.multivariate_normal(mean=muX, cov=sigma2X, size=m)
Y = np.random.multivariate_normal(mean=muY, cov=sigma2Y, size=n)
if d == 2:
plt.figure()
plt.plot(X[:, 0], X[:, 1], 'bo')
plt.plot(Y[:, 0], Y[:, 1], 'rx')
sigma2 = np.median(pairwise_distances(X, Y, metric='euclidean'))**2
mmd2u, mmd2u_null, p_value = kernel_two_sample_test(X, Y,
kernel_function='rbf',
gamma=1.0/sigma2,
verbose=True)
# mmd2u, mmd2u_null, p_value = kernel_two_sample_test(X, Y,
# kernel_function='linear',
# verbose=True)
plt.figure()
prob, bins, patches = plt.hist(mmd2u_null, bins=50, normed=True)
plt.plot(mmd2u, prob.max()/30, 'w*', markersize=24, markeredgecolor='k',
markeredgewidth=2, label="$MMD^2_u = %s$" % mmd2u)
plt.xlabel('$MMD^2_u$')
plt.ylabel('$p(MMD^2_u)$')
plt.legend(numpoints=1)
plt.title('$MMD^2_u$: null-distribution and observed value. $p$-value=%s'
% p_value)
plt.show() | en | 0.626115 | The MMD^2_u unbiased statistic. Compute the bootstrap null-distribution of MMD2u. Compute the bootstrap null-distribution of MMD2u given predefined permutations. Note:: verbosity is removed to improve speed. Compute MMD^2_u, its null distribution and the p-value of the kernel two-sample test. Note that extra parameters captured by **kwargs will be passed to pairwise_kernels() as kernel parameters. E.g. if kernel_two_sample_test(..., kernel_function='rbf', gamma=0.1), then this will result in getting the kernel through kernel_function(metric='rbf', gamma=0.1). # muY = np.zeros(d) # mmd2u, mmd2u_null, p_value = kernel_two_sample_test(X, Y, # kernel_function='linear', # verbose=True) | 2.758898 | 3 |
myapi/commons/errors/__init__.py | zobayer1/flask-tutorial | 4 | 6628012 | # -*- coding: utf-8 -*-
from enum import Enum
__all__ = ["Errors"]
class Errors(tuple, Enum):
"""Enums for error subtypes"""
SERVER_ERROR = (500001, "Something Went Wrong")
| # -*- coding: utf-8 -*-
from enum import Enum
__all__ = ["Errors"]
class Errors(tuple, Enum):
"""Enums for error subtypes"""
SERVER_ERROR = (500001, "Something Went Wrong")
| en | 0.591351 | # -*- coding: utf-8 -*- Enums for error subtypes | 2.81645 | 3 |
test/unit/common.py | isabella232/addonfactory-cloudconnect-library | 0 | 6628013 | <reponame>isabella232/addonfactory-cloudconnect-library
#
# Copyright 2021 Splunk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import os.path as op
PROJECT_ROOT = op.dirname(op.dirname(op.dirname(op.abspath(__file__))))
EXAMPLE_DIR = op.join(PROJECT_ROOT, "examples", "1.0")
TEST_DATA_DIR = op.join(PROJECT_ROOT, "test", "data")
CONFIGURATION_DIR = op.join(PROJECT_ROOT, "cloudconnectlib", "configuration")
SCHEMA_FILE = op.join(CONFIGURATION_DIR, "schema_1_0_0.json")
| #
# Copyright 2021 Splunk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import os.path as op
PROJECT_ROOT = op.dirname(op.dirname(op.dirname(op.abspath(__file__))))
EXAMPLE_DIR = op.join(PROJECT_ROOT, "examples", "1.0")
TEST_DATA_DIR = op.join(PROJECT_ROOT, "test", "data")
CONFIGURATION_DIR = op.join(PROJECT_ROOT, "cloudconnectlib", "configuration")
SCHEMA_FILE = op.join(CONFIGURATION_DIR, "schema_1_0_0.json") | en | 0.850714 | # # Copyright 2021 Splunk Inc. # # 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. # | 1.423485 | 1 |
app/database/add_primadonna.py | KindtAnton/Haldis | 0 | 6628014 | <filename>app/database/add_primadonna.py<gh_stars>0
"Script to add Primadonna to Haldis"
from app import db
from models import Location, Product
def add():
"Add Primadonna to the database"
addTA()
addAfhalen()
pizzasTA = {
"Peperoni": 750,
"Basis pizza (extra garneringen zie site)": 600,
"Parma": 750,
"Margharita": 600,
"Funghi": 715,
"Mamma mia": 715,
"Napoletana": 750,
"Exotic": 750,
"Siciliana": 750,
"Michelangelo": 750,
"Roma": 750,
"Torno": 750,
"Bolognese": 780,
"Hawai": 910,
"Cipolla": 910,
"Dolce vita": 910,
"Valentino": 910,
"Vegateriana": 1000,
"La donna": 1000,
"Tropical": 1000,
"Quattro Stagioni": 1000,
"Romana": 1000,
"Diabolo": 1000,
"Turkish": 1000,
"Cesar": 1000,
"Calzone": 1040,
"Calzone Vegetariana": 1040,
"Quattro Formaggi": 1040,
"Frutti di mare": 1040,
"Gerookte ham en rucola": 1040,
"Van de chef": 1170,
"Milano": 1170,
"Soronto": 1260,
"<NAME>": 1260,
"Pasta (zie site voor opties)": 900,
}
def addTA() -> None:
"Add Primadonna on takeaway.com to the database"
primadonna_takeaway = Location()
primadonna_takeaway.configure(
"Primadonna (takeaway laten bezorgen)",
"Overpoortstraat 46 9000 Gent",
"tel: 0475 40 13 00",
"https://www.takeaway.com/be-en/prima-donna",
)
db.session.add(primadonna_takeaway)
for pizza, price in pizzasTA.items():
entry = Product()
entry.configure(primadonna_takeaway, pizza, price)
db.session.add(entry)
pizzasAfhalen = {
"Peperoni": 575,
"Basis pizza (extra garneringen zie site)": 450,
"Parma": 575,
"Margharita": 450,
"Funghi": 550,
"Mamma mia": 550,
"Napoletana": 575,
"Exotic": 575,
"Siciliana": 575,
"Michelangelo": 575,
"Roma": 575,
"Torno": 575,
"Bolognese": 600,
"Hawai": 700,
"Cipolla": 700,
"Dolce vita": 700,
"Valentino": 700,
"Vegateriana": 770,
"La donna": 770,
"Tropical": 770,
"Quattro Stagioni": 770,
"Romana": 770,
"Diabolo": 770,
"Turkish": 770,
"Cesar": 770,
"Calzone": 800,
"Calzone Vegetariana": 800,
"Quattro Formaggi": 800,
"Frutti di mare": 800,
"Gerookte ham en rucola": 800,
"Van de chef": 900,
"Milano": 900,
"Soronto": 970,
"<NAME>": 970,
"Pasta (zie site voor opties)": 700,
}
def addAfhalen() -> None:
"Add Primadonna to takeaway to the database"
primadonna_afhalen = Location()
primadonna_afhalen.configure(
"Primadonna (bellen en afhalen)",
"Overpoortstraat 46 9000 Gent",
"tel: 0475 40 13 00",
"http://primadonnagent.be/Menu.html",
)
db.session.add(primadonna_afhalen)
for pizza, price in pizzasAfhalen.items():
entry = Product()
entry.configure(primadonna_afhalen, pizza, price)
db.session.add(entry)
| <filename>app/database/add_primadonna.py<gh_stars>0
"Script to add Primadonna to Haldis"
from app import db
from models import Location, Product
def add():
"Add Primadonna to the database"
addTA()
addAfhalen()
pizzasTA = {
"Peperoni": 750,
"Basis pizza (extra garneringen zie site)": 600,
"Parma": 750,
"Margharita": 600,
"Funghi": 715,
"Mamma mia": 715,
"Napoletana": 750,
"Exotic": 750,
"Siciliana": 750,
"Michelangelo": 750,
"Roma": 750,
"Torno": 750,
"Bolognese": 780,
"Hawai": 910,
"Cipolla": 910,
"Dolce vita": 910,
"Valentino": 910,
"Vegateriana": 1000,
"La donna": 1000,
"Tropical": 1000,
"Quattro Stagioni": 1000,
"Romana": 1000,
"Diabolo": 1000,
"Turkish": 1000,
"Cesar": 1000,
"Calzone": 1040,
"Calzone Vegetariana": 1040,
"Quattro Formaggi": 1040,
"Frutti di mare": 1040,
"Gerookte ham en rucola": 1040,
"Van de chef": 1170,
"Milano": 1170,
"Soronto": 1260,
"<NAME>": 1260,
"Pasta (zie site voor opties)": 900,
}
def addTA() -> None:
"Add Primadonna on takeaway.com to the database"
primadonna_takeaway = Location()
primadonna_takeaway.configure(
"Primadonna (takeaway laten bezorgen)",
"Overpoortstraat 46 9000 Gent",
"tel: 0475 40 13 00",
"https://www.takeaway.com/be-en/prima-donna",
)
db.session.add(primadonna_takeaway)
for pizza, price in pizzasTA.items():
entry = Product()
entry.configure(primadonna_takeaway, pizza, price)
db.session.add(entry)
pizzasAfhalen = {
"Peperoni": 575,
"Basis pizza (extra garneringen zie site)": 450,
"Parma": 575,
"Margharita": 450,
"Funghi": 550,
"Mamma mia": 550,
"Napoletana": 575,
"Exotic": 575,
"Siciliana": 575,
"Michelangelo": 575,
"Roma": 575,
"Torno": 575,
"Bolognese": 600,
"Hawai": 700,
"Cipolla": 700,
"Dolce vita": 700,
"Valentino": 700,
"Vegateriana": 770,
"La donna": 770,
"Tropical": 770,
"Quattro Stagioni": 770,
"Romana": 770,
"Diabolo": 770,
"Turkish": 770,
"Cesar": 770,
"Calzone": 800,
"Calzone Vegetariana": 800,
"Quattro Formaggi": 800,
"Frutti di mare": 800,
"Gerookte ham en rucola": 800,
"Van de chef": 900,
"Milano": 900,
"Soronto": 970,
"<NAME>": 970,
"Pasta (zie site voor opties)": 700,
}
def addAfhalen() -> None:
"Add Primadonna to takeaway to the database"
primadonna_afhalen = Location()
primadonna_afhalen.configure(
"Primadonna (bellen en afhalen)",
"Overpoortstraat 46 9000 Gent",
"tel: 0475 40 13 00",
"http://primadonnagent.be/Menu.html",
)
db.session.add(primadonna_afhalen)
for pizza, price in pizzasAfhalen.items():
entry = Product()
entry.configure(primadonna_afhalen, pizza, price)
db.session.add(entry)
| none | 1 | 2.478406 | 2 | |
Priority Queue/PriorityQueue-1-Worse.py | jweisz/iui22-code-translation | 0 | 6628015 | <gh_stars>0
class priority_queue:
"""
Python code to implement a priority - queue using an
ArrayList - based implementation of a binary heap
This class can be parameterized for any element class that supports the Comparable
interface on itself
A priority queue allows one to store comparable elements
and remove them in the order defined by the comparator
This implementation will remove the highest priority items first
Insertion and removal are O ( log n ) operations in terms of the number of items in the queue
"""
def __init__(self):
self.heap = []
def insert(self, item):
"""Insert an item into the priority queue
item - to be inserted
"""
index = self.heap.index(item)
self.heap.insert(index, item)
while index > 0:
parent_index = (index - 1) // 2
parent = self.heap.pop()
if parent < item:
self.heap.insert(parent_index, item)
self.heap.insert(index, parent)
index = parent_index
else:
break
return index
def remove(self):
""" Remove the highest priority item """
if len(self.heap) == 0:
return None
index = len(self.heap) - 1
element = self.heap[index]
self.heap[0] = self.heap[index]
self.heap.pop(index)
self.heapify(0, heap)
return None
def size(self):
""" Get the number of items in the priority queue """
return len(self.heap)
def peek(self):
""" Return the next element to be returned by remove without removing it from the priority queue """
if not self.heap.empty():
return self.heap.pop()
else:
return self.heap.pop()
def empty(self):
"""Is the Priority queue empty ?
: return : True if and only if the priority queue is empty"""
return self.heap.empty()
def enumerate(self):
""" Provide all the results in the priority queue in order """
saved_heap = copy.deepcopy(self.heap)
results = []
while not self.heap.empty():
results.append(self.remove())
self.heap = saved_heap
return [x for x in results if x["priority "] == 0]
def addAll(self, collection):
""" Add the elements of a collection to the priority queue """
for element in collection:
self.insert(element)
return collection
def _heapify(self, index, size):
"""Restore a section of the heap to maintain heap properties
index - the point in the heap to work on
If the indicated point does not have the proper relation to its descendants ,
their values are swapped and the descendant is then processed recursively"""
if self.heap:
left_index = (index * 2) + 1
right_index = (index * 2) + 2
parent = self.heap(pop)
max_index = self.heap.index(parent)
if left_index < left_index and self.heap[left_index] > parent:
max_index = left_index
if right_index < right_index and self.heap[right_index] > parent:
max_index = right_index
if max_index != self.heap.index(parent):
# swap them and recurse on the subtree rooted at min _ index heap [ index ]
self.heap[left_index] = self.heap[max_index]
self.heap[max_index] = parent
_siftup_max(self.heap, max_index)
| class priority_queue:
"""
Python code to implement a priority - queue using an
ArrayList - based implementation of a binary heap
This class can be parameterized for any element class that supports the Comparable
interface on itself
A priority queue allows one to store comparable elements
and remove them in the order defined by the comparator
This implementation will remove the highest priority items first
Insertion and removal are O ( log n ) operations in terms of the number of items in the queue
"""
def __init__(self):
self.heap = []
def insert(self, item):
"""Insert an item into the priority queue
item - to be inserted
"""
index = self.heap.index(item)
self.heap.insert(index, item)
while index > 0:
parent_index = (index - 1) // 2
parent = self.heap.pop()
if parent < item:
self.heap.insert(parent_index, item)
self.heap.insert(index, parent)
index = parent_index
else:
break
return index
def remove(self):
""" Remove the highest priority item """
if len(self.heap) == 0:
return None
index = len(self.heap) - 1
element = self.heap[index]
self.heap[0] = self.heap[index]
self.heap.pop(index)
self.heapify(0, heap)
return None
def size(self):
""" Get the number of items in the priority queue """
return len(self.heap)
def peek(self):
""" Return the next element to be returned by remove without removing it from the priority queue """
if not self.heap.empty():
return self.heap.pop()
else:
return self.heap.pop()
def empty(self):
"""Is the Priority queue empty ?
: return : True if and only if the priority queue is empty"""
return self.heap.empty()
def enumerate(self):
""" Provide all the results in the priority queue in order """
saved_heap = copy.deepcopy(self.heap)
results = []
while not self.heap.empty():
results.append(self.remove())
self.heap = saved_heap
return [x for x in results if x["priority "] == 0]
def addAll(self, collection):
""" Add the elements of a collection to the priority queue """
for element in collection:
self.insert(element)
return collection
def _heapify(self, index, size):
"""Restore a section of the heap to maintain heap properties
index - the point in the heap to work on
If the indicated point does not have the proper relation to its descendants ,
their values are swapped and the descendant is then processed recursively"""
if self.heap:
left_index = (index * 2) + 1
right_index = (index * 2) + 2
parent = self.heap(pop)
max_index = self.heap.index(parent)
if left_index < left_index and self.heap[left_index] > parent:
max_index = left_index
if right_index < right_index and self.heap[right_index] > parent:
max_index = right_index
if max_index != self.heap.index(parent):
# swap them and recurse on the subtree rooted at min _ index heap [ index ]
self.heap[left_index] = self.heap[max_index]
self.heap[max_index] = parent
_siftup_max(self.heap, max_index) | en | 0.829207 | Python code to implement a priority - queue using an ArrayList - based implementation of a binary heap This class can be parameterized for any element class that supports the Comparable interface on itself A priority queue allows one to store comparable elements and remove them in the order defined by the comparator This implementation will remove the highest priority items first Insertion and removal are O ( log n ) operations in terms of the number of items in the queue Insert an item into the priority queue item - to be inserted Remove the highest priority item Get the number of items in the priority queue Return the next element to be returned by remove without removing it from the priority queue Is the Priority queue empty ? : return : True if and only if the priority queue is empty Provide all the results in the priority queue in order Add the elements of a collection to the priority queue Restore a section of the heap to maintain heap properties index - the point in the heap to work on If the indicated point does not have the proper relation to its descendants , their values are swapped and the descendant is then processed recursively # swap them and recurse on the subtree rooted at min _ index heap [ index ] | 4.247565 | 4 |
onnx_tf/common/handler_helper.py | pluradj/onnx-tensorflow | 0 | 6628016 | <filename>onnx_tf/common/handler_helper.py<gh_stars>0
from onnx import defs
from onnx_tf.handlers.backend import * # noqa
from onnx_tf.handlers.backend_handler import BackendHandler
import onnx_tf.common as common
def get_all_backend_handlers(opset_dict):
""" Get a dict of all backend handler classes.
e.g. {'domain': {'Abs': Abs handler class}, ...}, }.
:param opset_dict: A dict of opset. e.g. {'domain': version, ...}
:return: Dict.
"""
handlers = {}
for handler in BackendHandler.__subclasses__():
handler.check_cls()
domain = handler.DOMAIN
version = opset_dict[domain] if domain in opset_dict else 1
handler.VERSION = version
since_version = 1
if defs.has(handler.ONNX_OP, domain=handler.DOMAIN):
try:
since_version = defs.get_schema(
handler.ONNX_OP,
domain=handler.DOMAIN,
max_inclusive_version=version).since_version
except RuntimeError:
common.logger.debug("Fail to get since_version of {} in domain `{}` "
"with max_inclusive_version={}. Set to 1.".format(
handler.ONNX_OP, handler.DOMAIN, version))
else:
common.logger.debug("Unknown op {} in domain `{}`.".format(
handler.ONNX_OP, handler.DOMAIN or "ai.onnx"))
handler.SINCE_VERSION = since_version
handlers.setdefault(domain, {})[handler.ONNX_OP] = handler
return handlers
def get_backend_coverage():
""" Get backend coverage for document.
:return: onnx_coverage: e.g. {'domain': {'ONNX_OP': [versions], ...}, ...}
"""
onnx_coverage = {}
experimental_op = set()
for handler in BackendHandler.__subclasses__():
handler.check_cls()
versions = handler.get_versions()
domain = handler.DOMAIN
if getattr(handler, "EXPERIMENTAL", False):
experimental_op.add(handler.ONNX_OP)
_update_coverage(onnx_coverage, domain, handler.ONNX_OP, versions)
return onnx_coverage, experimental_op
def _update_coverage(coverage, domain, key, versions):
domain_coverage = coverage.setdefault(domain, {})
vers = domain_coverage.get(key, [])
vers.extend(versions)
domain_coverage[key] = sorted(list(set(vers)))
def get_backend_partial_support_detail():
ps_dict = {}
opset_dict = dict([(defs.ONNX_DOMAIN, defs.onnx_opset_version())])
handlers = get_all_backend_handlers(opset_dict)[defs.ONNX_DOMAIN]
for op_name in handlers:
if handlers[op_name].PARTIAL_SUPPORT:
ps_dict[op_name] = handlers[op_name].PS_DESCRIPTION
return ps_dict
| <filename>onnx_tf/common/handler_helper.py<gh_stars>0
from onnx import defs
from onnx_tf.handlers.backend import * # noqa
from onnx_tf.handlers.backend_handler import BackendHandler
import onnx_tf.common as common
def get_all_backend_handlers(opset_dict):
""" Get a dict of all backend handler classes.
e.g. {'domain': {'Abs': Abs handler class}, ...}, }.
:param opset_dict: A dict of opset. e.g. {'domain': version, ...}
:return: Dict.
"""
handlers = {}
for handler in BackendHandler.__subclasses__():
handler.check_cls()
domain = handler.DOMAIN
version = opset_dict[domain] if domain in opset_dict else 1
handler.VERSION = version
since_version = 1
if defs.has(handler.ONNX_OP, domain=handler.DOMAIN):
try:
since_version = defs.get_schema(
handler.ONNX_OP,
domain=handler.DOMAIN,
max_inclusive_version=version).since_version
except RuntimeError:
common.logger.debug("Fail to get since_version of {} in domain `{}` "
"with max_inclusive_version={}. Set to 1.".format(
handler.ONNX_OP, handler.DOMAIN, version))
else:
common.logger.debug("Unknown op {} in domain `{}`.".format(
handler.ONNX_OP, handler.DOMAIN or "ai.onnx"))
handler.SINCE_VERSION = since_version
handlers.setdefault(domain, {})[handler.ONNX_OP] = handler
return handlers
def get_backend_coverage():
""" Get backend coverage for document.
:return: onnx_coverage: e.g. {'domain': {'ONNX_OP': [versions], ...}, ...}
"""
onnx_coverage = {}
experimental_op = set()
for handler in BackendHandler.__subclasses__():
handler.check_cls()
versions = handler.get_versions()
domain = handler.DOMAIN
if getattr(handler, "EXPERIMENTAL", False):
experimental_op.add(handler.ONNX_OP)
_update_coverage(onnx_coverage, domain, handler.ONNX_OP, versions)
return onnx_coverage, experimental_op
def _update_coverage(coverage, domain, key, versions):
domain_coverage = coverage.setdefault(domain, {})
vers = domain_coverage.get(key, [])
vers.extend(versions)
domain_coverage[key] = sorted(list(set(vers)))
def get_backend_partial_support_detail():
ps_dict = {}
opset_dict = dict([(defs.ONNX_DOMAIN, defs.onnx_opset_version())])
handlers = get_all_backend_handlers(opset_dict)[defs.ONNX_DOMAIN]
for op_name in handlers:
if handlers[op_name].PARTIAL_SUPPORT:
ps_dict[op_name] = handlers[op_name].PS_DESCRIPTION
return ps_dict
| en | 0.349576 | # noqa Get a dict of all backend handler classes. e.g. {'domain': {'Abs': Abs handler class}, ...}, }. :param opset_dict: A dict of opset. e.g. {'domain': version, ...} :return: Dict. Get backend coverage for document. :return: onnx_coverage: e.g. {'domain': {'ONNX_OP': [versions], ...}, ...} | 2.11494 | 2 |
pyforce/env/base.py | olemeyer/pyforce | 4 | 6628017 | import gym
import numpy as np
#Base class for all environment wrappers.
#Implements forwarding of all essential methods of the OpenAI Gyms (reset,step and render).
#Furthermore the original environment is kept and can be accessed from the wrapper.
class EnvWrapper(gym.Env):
def __init__(self,env):
self.env=env
self.action_space=env.action_space
self.observation_space=env.observation_space
def reset(self,*args,**kwargs):
return self.env.reset(*args,**kwargs)
def render(self,*args,**kwargs):
return self.env.render(*args,**kwargs)
def step(self,*args,**kwargs):
return self.env.step(*args,**kwargs) | import gym
import numpy as np
#Base class for all environment wrappers.
#Implements forwarding of all essential methods of the OpenAI Gyms (reset,step and render).
#Furthermore the original environment is kept and can be accessed from the wrapper.
class EnvWrapper(gym.Env):
def __init__(self,env):
self.env=env
self.action_space=env.action_space
self.observation_space=env.observation_space
def reset(self,*args,**kwargs):
return self.env.reset(*args,**kwargs)
def render(self,*args,**kwargs):
return self.env.render(*args,**kwargs)
def step(self,*args,**kwargs):
return self.env.step(*args,**kwargs) | en | 0.849707 | #Base class for all environment wrappers. #Implements forwarding of all essential methods of the OpenAI Gyms (reset,step and render). #Furthermore the original environment is kept and can be accessed from the wrapper. | 2.622342 | 3 |
skyportal/handlers/api/internal/source_views.py | Hallflower20/skyportal | 0 | 6628018 | <reponame>Hallflower20/skyportal<gh_stars>0
import datetime
from sqlalchemy import func, desc
from sqlalchemy.orm import joinedload
import tornado.web
from baselayer.app.access import auth_or_token
from ...base import BaseHandler
from ....models import DBSession, Obj, Source, SourceView
from .recent_sources import first_thumbnail_public_url
default_prefs = {'maxNumSources': 10, 'sinceDaysAgo': 7}
class SourceViewsHandler(BaseHandler):
@classmethod
def get_top_source_views_and_ids(self, current_user):
user_prefs = getattr(current_user, 'preferences', None) or {}
top_sources_prefs = user_prefs.get('topSources', {})
top_sources_prefs = {**default_prefs, **top_sources_prefs}
max_num_sources = int(top_sources_prefs['maxNumSources'])
since_days_ago = int(top_sources_prefs['sinceDaysAgo'])
cutoff_day = datetime.datetime.now() - datetime.timedelta(days=since_days_ago)
q = (
DBSession.query(
func.count(SourceView.obj_id).label('views'), SourceView.obj_id
)
.group_by(SourceView.obj_id)
.filter(
SourceView.obj_id.in_(
DBSession.query(Source.obj_id).filter(
Source.group_id.in_(
[g.id for g in current_user.accessible_groups]
)
)
)
)
.filter(SourceView.created_at >= cutoff_day)
.order_by(desc('views'))
.limit(max_num_sources)
)
return q.all()
@auth_or_token
def get(self):
query_results = SourceViewsHandler.get_top_source_views_and_ids(
self.current_user
)
sources = []
for view, obj_id in query_results:
s = Source.get_obj_if_owned_by( # Returns Source.obj
obj_id,
self.current_user,
options=[joinedload(Source.obj).joinedload(Obj.thumbnails)],
)
public_url = first_thumbnail_public_url(s.thumbnails)
sources.append(
{
'obj_id': s.id,
'views': view,
'ra': s.ra,
'dec': s.dec,
'public_url': public_url,
'classifications': s.classifications,
}
)
return self.success(data=sources)
@tornado.web.authenticated
def post(self, obj_id):
# Ensure user has access to source
Source.get_obj_if_owned_by(obj_id, self.current_user)
# This endpoint will only be hit by front-end, so this will never be a token
register_source_view(
obj_id=obj_id,
username_or_token_id=self.current_user.username,
is_token=False,
)
self.push_all(action="skyportal/FETCH_TOP_SOURCES")
return self.success()
def register_source_view(obj_id, username_or_token_id, is_token):
sv = SourceView(
obj_id=obj_id, username_or_token_id=username_or_token_id, is_token=is_token
)
DBSession.add(sv)
DBSession.commit()
| import datetime
from sqlalchemy import func, desc
from sqlalchemy.orm import joinedload
import tornado.web
from baselayer.app.access import auth_or_token
from ...base import BaseHandler
from ....models import DBSession, Obj, Source, SourceView
from .recent_sources import first_thumbnail_public_url
default_prefs = {'maxNumSources': 10, 'sinceDaysAgo': 7}
class SourceViewsHandler(BaseHandler):
@classmethod
def get_top_source_views_and_ids(self, current_user):
user_prefs = getattr(current_user, 'preferences', None) or {}
top_sources_prefs = user_prefs.get('topSources', {})
top_sources_prefs = {**default_prefs, **top_sources_prefs}
max_num_sources = int(top_sources_prefs['maxNumSources'])
since_days_ago = int(top_sources_prefs['sinceDaysAgo'])
cutoff_day = datetime.datetime.now() - datetime.timedelta(days=since_days_ago)
q = (
DBSession.query(
func.count(SourceView.obj_id).label('views'), SourceView.obj_id
)
.group_by(SourceView.obj_id)
.filter(
SourceView.obj_id.in_(
DBSession.query(Source.obj_id).filter(
Source.group_id.in_(
[g.id for g in current_user.accessible_groups]
)
)
)
)
.filter(SourceView.created_at >= cutoff_day)
.order_by(desc('views'))
.limit(max_num_sources)
)
return q.all()
@auth_or_token
def get(self):
query_results = SourceViewsHandler.get_top_source_views_and_ids(
self.current_user
)
sources = []
for view, obj_id in query_results:
s = Source.get_obj_if_owned_by( # Returns Source.obj
obj_id,
self.current_user,
options=[joinedload(Source.obj).joinedload(Obj.thumbnails)],
)
public_url = first_thumbnail_public_url(s.thumbnails)
sources.append(
{
'obj_id': s.id,
'views': view,
'ra': s.ra,
'dec': s.dec,
'public_url': public_url,
'classifications': s.classifications,
}
)
return self.success(data=sources)
@tornado.web.authenticated
def post(self, obj_id):
# Ensure user has access to source
Source.get_obj_if_owned_by(obj_id, self.current_user)
# This endpoint will only be hit by front-end, so this will never be a token
register_source_view(
obj_id=obj_id,
username_or_token_id=self.current_user.username,
is_token=False,
)
self.push_all(action="skyportal/FETCH_TOP_SOURCES")
return self.success()
def register_source_view(obj_id, username_or_token_id, is_token):
sv = SourceView(
obj_id=obj_id, username_or_token_id=username_or_token_id, is_token=is_token
)
DBSession.add(sv)
DBSession.commit() | en | 0.866966 | # Returns Source.obj # Ensure user has access to source # This endpoint will only be hit by front-end, so this will never be a token | 1.933365 | 2 |
ahc_tools/test/test_match.py | rdo-management/ahc-tools | 0 | 6628019 | <reponame>rdo-management/ahc-tools<filename>ahc_tools/test/test_match.py
# 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 mock
import os
from hardware import cmdb
from hardware import state
from oslo_config import cfg
from ahc_tools import exc
from ahc_tools import match
from ahc_tools.test import base
from ahc_tools import utils
CONF = cfg.CONF
def fake_load(obj, cfg_dir):
obj._cfg_dir = cfg_dir
obj._data = [('hw1', '*'), ]
class MatchBase(base.BaseTest):
def setUp(self):
super(MatchBase, self).setUp()
basedir = os.path.dirname(os.path.abspath(__file__))
CONF.set_override('configdir',
os.path.join(basedir, 'edeploy_conf'),
'edeploy')
self.uuid = '1a1a1a1a-2b2b-3c3c-4d4d-5e5e5e5e5e5e'
self.bmc_address = '1.2.3.4'
self.node = mock.Mock(driver='pxe_ipmitool',
driver_info={'ipmi_address': self.bmc_address},
properties={'cpu_arch': 'i386', 'local_gb': 40},
uuid=self.uuid,
power_state='power on',
provision_state='available',
extra={'on_discovery': 'true'},
instance_uuid=None,
maintenance=False)
self.facts = [
['network', 'eth0', 'serial', '99:99:99:99:99:99'],
['network', 'eth0', 'ipv4', '192.168.100.12']]
@mock.patch.object(utils, 'get_facts', autospec=True)
@mock.patch.object(state.State, 'load', fake_load)
@mock.patch.object(state.State, '_load_specs',
lambda o, n: [('network', '$iface', 'serial', '$mac'),
('network', '$iface', 'ipv4', '$ipv4')])
class TestMatch(MatchBase):
def setUp(self):
super(TestMatch, self).setUp()
def test_match(self, mock_facts):
mock_facts.return_value = self.facts
node_info = {}
match.match(self.node, node_info)
self.assertEqual('hw1', node_info['hardware']['profile'])
self.assertEqual('eth0', node_info['hardware']['iface'])
self.assertEqual('99:99:99:99:99:99', node_info['hardware']['mac'])
self.assertEqual('192.168.100.12', node_info['hardware']['ipv4'])
node_patches = match.get_update_patches(self.node, node_info)
self.assertEqual('/extra/configdrive_metadata',
node_patches[0]['path'])
self.assertEqual('hw1',
node_patches[0]['value']['hardware']['profile'])
self.assertEqual('/properties/capabilities',
node_patches[1]['path'])
self.assertEqual('profile:hw1',
node_patches[1]['value'])
@mock.patch.object(state.State, '__init__',
side_effect=Exception('boom'), autospec=True)
def test_load_failed(self, state_mock, mock_facts):
self.assertRaises(exc.LoadFailedError, match.match,
self.node, self.facts)
@mock.patch.object(state.State, 'find_match',
side_effect=Exception('boom'), autospec=True)
def test_no_match(self, find_mock, mock_facts):
self.assertRaises(exc.MatchFailedError, match.match, self.node, {})
def test_multiple_capabilities(self, mock_facts):
self.node.properties['capabilities'] = 'cat:meow,profile:robin'
node_info = {'hardware': {'profile': 'batman'}, 'edeploy_facts': []}
node_patches = match.get_update_patches(self.node, node_info)
self.assertIn('cat:meow', node_patches[1]['value'])
self.assertIn('profile:batman', node_patches[1]['value'])
# Assert the old profile is gone
self.assertNotIn('profile:robin', node_patches[1]['value'])
def test_no_data(self, mock_facts):
node_info = {}
self.assertEqual([], match.get_update_patches(self.node, node_info))
@mock.patch.object(cmdb, 'load_cmdb')
def test_raid_configuration_passed(self, mock_load_cmdb, mock_facts):
mock_load_cmdb.return_value = [
{'logical_disks': (
{'disk_type': 'hdd',
'interface_type': 'sas',
'is_root_volume': 'true',
'raid_level': '1+0',
'size_gb': 50,
'volume_name': 'root_volume'},
{'disk_type': 'hdd',
'interface_type': 'sas',
'number_of_physical_disks': 3,
'raid_level': '5',
'size_gb': 100,
'volume_name': 'data_volume'})}]
mock_facts.return_value = self.facts
node_info = {}
match.match(self.node, node_info)
self.assertIn('target_raid_configuration', node_info)
node_patches = match.get_update_patches(self.node, node_info)
self.assertEqual('/extra/target_raid_configuration',
node_patches[2]['path'])
@mock.patch.object(cmdb, 'load_cmdb')
def test_bios_configuration_passed(self, mock_load_cmdb, mock_facts):
mock_load_cmdb.return_value = [
{'bios_settings': {'ProcVirtualization': 'Disabled'}}]
mock_facts.return_value = self.facts
node_info = {}
match.match(self.node, node_info)
self.assertIn('bios_settings', node_info)
node_patches = match.get_update_patches(self.node, node_info)
self.assertEqual('/extra/bios_settings',
node_patches[2]['path'])
@mock.patch.object(match.cfg, 'ConfigParser', autospec=True)
@mock.patch.object(match, 'LOG')
@mock.patch.object(utils, 'get_ironic_client', autospec=True)
@mock.patch.object(match, '_restore_state', lambda: None)
class TestMain(MatchBase):
def setUp(self):
super(TestMain, self).setUp()
self.mock_client = mock.Mock()
self.mock_client.node.list.return_value = [self.node]
@mock.patch.object(match, '_copy_state', side_effect=Exception('boom'))
def test_copy_failed(self, mock_copy, mock_ic, mock_log, mock_cfg):
mock_ic.return_value = self.mock_client
self.assertRaises(SystemExit, match.main, args=[])
self.assertTrue(1, mock_log.error.call_count)
@mock.patch.object(match, 'match', autospec=True,
side_effect=exc.LoadFailedError('boom', '/etc/edeploy'))
@mock.patch.object(match, '_copy_state', lambda: None)
def test_load_failed(self, mock_match, mock_ic, mock_log, mock_cfg):
mock_ic.return_value = self.mock_client
self.assertRaises(SystemExit, match.main, args=[])
self.assertTrue(1, mock_log.error.call_count)
@mock.patch.object(match, 'get_update_patches', autospec=True)
@mock.patch.object(match, 'match', autospec=True,
side_effect=exc.MatchFailedError('boom', '1234567890'))
@mock.patch.object(match, '_copy_state', lambda: None)
def test_match_failed(self, mock_match, mock_update, mock_ic, mock_log,
mock_cfg):
mock_ic.return_value = self.mock_client
match.main(args=[])
self.assertEqual(2, mock_log.error.call_count)
self.assertFalse(mock_update.called)
@mock.patch.object(match, 'match', lambda x, y: None)
@mock.patch.object(match, 'get_update_patches', lambda x, y: None)
@mock.patch.object(match, '_copy_state', lambda: None)
def test_match_success(self, mock_ic, mock_log, mock_cfg):
mock_ic.return_value = self.mock_client
match.main(args=[])
self.assertFalse(mock_log.error.called)
@mock.patch.object(match, 'match', lambda x, y: None)
@mock.patch.object(match, 'get_update_patches', lambda x, y: None)
@mock.patch.object(match, '_copy_state', lambda: None)
def test_update_failed(self, mock_ic, mock_log, mock_cfg):
self.mock_client.node.update.side_effect = Exception('boom')
mock_ic.return_value = self.mock_client
match.main(args=[])
self.assertTrue(1, mock_log.error.call_count)
| # 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 mock
import os
from hardware import cmdb
from hardware import state
from oslo_config import cfg
from ahc_tools import exc
from ahc_tools import match
from ahc_tools.test import base
from ahc_tools import utils
CONF = cfg.CONF
def fake_load(obj, cfg_dir):
obj._cfg_dir = cfg_dir
obj._data = [('hw1', '*'), ]
class MatchBase(base.BaseTest):
def setUp(self):
super(MatchBase, self).setUp()
basedir = os.path.dirname(os.path.abspath(__file__))
CONF.set_override('configdir',
os.path.join(basedir, 'edeploy_conf'),
'edeploy')
self.uuid = '1a1a1a1a-2b2b-3c3c-4d4d-5e5e5e5e5e5e'
self.bmc_address = '1.2.3.4'
self.node = mock.Mock(driver='pxe_ipmitool',
driver_info={'ipmi_address': self.bmc_address},
properties={'cpu_arch': 'i386', 'local_gb': 40},
uuid=self.uuid,
power_state='power on',
provision_state='available',
extra={'on_discovery': 'true'},
instance_uuid=None,
maintenance=False)
self.facts = [
['network', 'eth0', 'serial', '99:99:99:99:99:99'],
['network', 'eth0', 'ipv4', '192.168.100.12']]
@mock.patch.object(utils, 'get_facts', autospec=True)
@mock.patch.object(state.State, 'load', fake_load)
@mock.patch.object(state.State, '_load_specs',
lambda o, n: [('network', '$iface', 'serial', '$mac'),
('network', '$iface', 'ipv4', '$ipv4')])
class TestMatch(MatchBase):
def setUp(self):
super(TestMatch, self).setUp()
def test_match(self, mock_facts):
mock_facts.return_value = self.facts
node_info = {}
match.match(self.node, node_info)
self.assertEqual('hw1', node_info['hardware']['profile'])
self.assertEqual('eth0', node_info['hardware']['iface'])
self.assertEqual('99:99:99:99:99:99', node_info['hardware']['mac'])
self.assertEqual('192.168.100.12', node_info['hardware']['ipv4'])
node_patches = match.get_update_patches(self.node, node_info)
self.assertEqual('/extra/configdrive_metadata',
node_patches[0]['path'])
self.assertEqual('hw1',
node_patches[0]['value']['hardware']['profile'])
self.assertEqual('/properties/capabilities',
node_patches[1]['path'])
self.assertEqual('profile:hw1',
node_patches[1]['value'])
@mock.patch.object(state.State, '__init__',
side_effect=Exception('boom'), autospec=True)
def test_load_failed(self, state_mock, mock_facts):
self.assertRaises(exc.LoadFailedError, match.match,
self.node, self.facts)
@mock.patch.object(state.State, 'find_match',
side_effect=Exception('boom'), autospec=True)
def test_no_match(self, find_mock, mock_facts):
self.assertRaises(exc.MatchFailedError, match.match, self.node, {})
def test_multiple_capabilities(self, mock_facts):
self.node.properties['capabilities'] = 'cat:meow,profile:robin'
node_info = {'hardware': {'profile': 'batman'}, 'edeploy_facts': []}
node_patches = match.get_update_patches(self.node, node_info)
self.assertIn('cat:meow', node_patches[1]['value'])
self.assertIn('profile:batman', node_patches[1]['value'])
# Assert the old profile is gone
self.assertNotIn('profile:robin', node_patches[1]['value'])
def test_no_data(self, mock_facts):
node_info = {}
self.assertEqual([], match.get_update_patches(self.node, node_info))
@mock.patch.object(cmdb, 'load_cmdb')
def test_raid_configuration_passed(self, mock_load_cmdb, mock_facts):
mock_load_cmdb.return_value = [
{'logical_disks': (
{'disk_type': 'hdd',
'interface_type': 'sas',
'is_root_volume': 'true',
'raid_level': '1+0',
'size_gb': 50,
'volume_name': 'root_volume'},
{'disk_type': 'hdd',
'interface_type': 'sas',
'number_of_physical_disks': 3,
'raid_level': '5',
'size_gb': 100,
'volume_name': 'data_volume'})}]
mock_facts.return_value = self.facts
node_info = {}
match.match(self.node, node_info)
self.assertIn('target_raid_configuration', node_info)
node_patches = match.get_update_patches(self.node, node_info)
self.assertEqual('/extra/target_raid_configuration',
node_patches[2]['path'])
@mock.patch.object(cmdb, 'load_cmdb')
def test_bios_configuration_passed(self, mock_load_cmdb, mock_facts):
mock_load_cmdb.return_value = [
{'bios_settings': {'ProcVirtualization': 'Disabled'}}]
mock_facts.return_value = self.facts
node_info = {}
match.match(self.node, node_info)
self.assertIn('bios_settings', node_info)
node_patches = match.get_update_patches(self.node, node_info)
self.assertEqual('/extra/bios_settings',
node_patches[2]['path'])
@mock.patch.object(match.cfg, 'ConfigParser', autospec=True)
@mock.patch.object(match, 'LOG')
@mock.patch.object(utils, 'get_ironic_client', autospec=True)
@mock.patch.object(match, '_restore_state', lambda: None)
class TestMain(MatchBase):
def setUp(self):
super(TestMain, self).setUp()
self.mock_client = mock.Mock()
self.mock_client.node.list.return_value = [self.node]
@mock.patch.object(match, '_copy_state', side_effect=Exception('boom'))
def test_copy_failed(self, mock_copy, mock_ic, mock_log, mock_cfg):
mock_ic.return_value = self.mock_client
self.assertRaises(SystemExit, match.main, args=[])
self.assertTrue(1, mock_log.error.call_count)
@mock.patch.object(match, 'match', autospec=True,
side_effect=exc.LoadFailedError('boom', '/etc/edeploy'))
@mock.patch.object(match, '_copy_state', lambda: None)
def test_load_failed(self, mock_match, mock_ic, mock_log, mock_cfg):
mock_ic.return_value = self.mock_client
self.assertRaises(SystemExit, match.main, args=[])
self.assertTrue(1, mock_log.error.call_count)
@mock.patch.object(match, 'get_update_patches', autospec=True)
@mock.patch.object(match, 'match', autospec=True,
side_effect=exc.MatchFailedError('boom', '1234567890'))
@mock.patch.object(match, '_copy_state', lambda: None)
def test_match_failed(self, mock_match, mock_update, mock_ic, mock_log,
mock_cfg):
mock_ic.return_value = self.mock_client
match.main(args=[])
self.assertEqual(2, mock_log.error.call_count)
self.assertFalse(mock_update.called)
@mock.patch.object(match, 'match', lambda x, y: None)
@mock.patch.object(match, 'get_update_patches', lambda x, y: None)
@mock.patch.object(match, '_copy_state', lambda: None)
def test_match_success(self, mock_ic, mock_log, mock_cfg):
mock_ic.return_value = self.mock_client
match.main(args=[])
self.assertFalse(mock_log.error.called)
@mock.patch.object(match, 'match', lambda x, y: None)
@mock.patch.object(match, 'get_update_patches', lambda x, y: None)
@mock.patch.object(match, '_copy_state', lambda: None)
def test_update_failed(self, mock_ic, mock_log, mock_cfg):
self.mock_client.node.update.side_effect = Exception('boom')
mock_ic.return_value = self.mock_client
match.main(args=[])
self.assertTrue(1, mock_log.error.call_count) | en | 0.860294 | # 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. # Assert the old profile is gone | 1.658686 | 2 |
tests/test_downloadermiddleware_robotstxt.py | wahello/scrapy | 3 | 6628020 | from unittest import mock
from twisted.internet import reactor, error
from twisted.internet.defer import Deferred, DeferredList, maybeDeferred
from twisted.python import failure
from twisted.trial import unittest
from scrapy.downloadermiddlewares.robotstxt import (RobotsTxtMiddleware,
logger as mw_module_logger)
from scrapy.exceptions import IgnoreRequest, NotConfigured
from scrapy.http import Request, Response, TextResponse
from scrapy.settings import Settings
from tests.test_robotstxt_interface import rerp_available, reppy_available
class RobotsTxtMiddlewareTest(unittest.TestCase):
def setUp(self):
self.crawler = mock.MagicMock()
self.crawler.settings = Settings()
self.crawler.engine.download = mock.MagicMock()
def tearDown(self):
del self.crawler
def test_robotstxt_settings(self):
self.crawler.settings = Settings()
self.crawler.settings.set('USER_AGENT', 'CustomAgent')
self.assertRaises(NotConfigured, RobotsTxtMiddleware, self.crawler)
def _get_successful_crawler(self):
crawler = self.crawler
crawler.settings.set('ROBOTSTXT_OBEY', True)
ROBOTS = u"""
User-Agent: *
Disallow: /admin/
Disallow: /static/
# taken from https://en.wikipedia.org/robots.txt
Disallow: /wiki/K%C3%A4ytt%C3%A4j%C3%A4:
Disallow: /wiki/Käyttäjä:
User-Agent: UnicödeBöt
Disallow: /some/randome/page.html
""".encode('utf-8')
response = TextResponse('http://site.local/robots.txt', body=ROBOTS)
def return_response(request, spider):
deferred = Deferred()
reactor.callFromThread(deferred.callback, response)
return deferred
crawler.engine.download.side_effect = return_response
return crawler
def test_robotstxt(self):
middleware = RobotsTxtMiddleware(self._get_successful_crawler())
return DeferredList([
self.assertNotIgnored(Request('http://site.local/allowed'), middleware),
self.assertIgnored(Request('http://site.local/admin/main'), middleware),
self.assertIgnored(Request('http://site.local/static/'), middleware),
self.assertIgnored(Request('http://site.local/wiki/K%C3%A4ytt%C3%A4j%C3%A4:'), middleware),
self.assertIgnored(Request(u'http://site.local/wiki/Käyttäjä:'), middleware)
], fireOnOneErrback=True)
def test_robotstxt_ready_parser(self):
middleware = RobotsTxtMiddleware(self._get_successful_crawler())
d = self.assertNotIgnored(Request('http://site.local/allowed'), middleware)
d.addCallback(lambda _: self.assertNotIgnored(Request('http://site.local/allowed'), middleware))
return d
def test_robotstxt_meta(self):
middleware = RobotsTxtMiddleware(self._get_successful_crawler())
meta = {'dont_obey_robotstxt': True}
return DeferredList([
self.assertNotIgnored(Request('http://site.local/allowed', meta=meta), middleware),
self.assertNotIgnored(Request('http://site.local/admin/main', meta=meta), middleware),
self.assertNotIgnored(Request('http://site.local/static/', meta=meta), middleware)
], fireOnOneErrback=True)
def _get_garbage_crawler(self):
crawler = self.crawler
crawler.settings.set('ROBOTSTXT_OBEY', True)
response = Response('http://site.local/robots.txt', body=b'GIF89a\xd3\x00\xfe\x00\xa2')
def return_response(request, spider):
deferred = Deferred()
reactor.callFromThread(deferred.callback, response)
return deferred
crawler.engine.download.side_effect = return_response
return crawler
def test_robotstxt_garbage(self):
# garbage response should be discarded, equal 'allow all'
middleware = RobotsTxtMiddleware(self._get_garbage_crawler())
deferred = DeferredList([
self.assertNotIgnored(Request('http://site.local'), middleware),
self.assertNotIgnored(Request('http://site.local/allowed'), middleware),
self.assertNotIgnored(Request('http://site.local/admin/main'), middleware),
self.assertNotIgnored(Request('http://site.local/static/'), middleware)
], fireOnOneErrback=True)
return deferred
def _get_emptybody_crawler(self):
crawler = self.crawler
crawler.settings.set('ROBOTSTXT_OBEY', True)
response = Response('http://site.local/robots.txt')
def return_response(request, spider):
deferred = Deferred()
reactor.callFromThread(deferred.callback, response)
return deferred
crawler.engine.download.side_effect = return_response
return crawler
def test_robotstxt_empty_response(self):
# empty response should equal 'allow all'
middleware = RobotsTxtMiddleware(self._get_emptybody_crawler())
return DeferredList([
self.assertNotIgnored(Request('http://site.local/allowed'), middleware),
self.assertNotIgnored(Request('http://site.local/admin/main'), middleware),
self.assertNotIgnored(Request('http://site.local/static/'), middleware)
], fireOnOneErrback=True)
def test_robotstxt_error(self):
self.crawler.settings.set('ROBOTSTXT_OBEY', True)
err = error.DNSLookupError('Robotstxt address not found')
def return_failure(request, spider):
deferred = Deferred()
reactor.callFromThread(deferred.errback, failure.Failure(err))
return deferred
self.crawler.engine.download.side_effect = return_failure
middleware = RobotsTxtMiddleware(self.crawler)
middleware._logerror = mock.MagicMock(side_effect=middleware._logerror)
deferred = middleware.process_request(Request('http://site.local'), None)
deferred.addCallback(lambda _: self.assertTrue(middleware._logerror.called))
return deferred
def test_robotstxt_immediate_error(self):
self.crawler.settings.set('ROBOTSTXT_OBEY', True)
err = error.DNSLookupError('Robotstxt address not found')
def immediate_failure(request, spider):
deferred = Deferred()
deferred.errback(failure.Failure(err))
return deferred
self.crawler.engine.download.side_effect = immediate_failure
middleware = RobotsTxtMiddleware(self.crawler)
return self.assertNotIgnored(Request('http://site.local'), middleware)
def test_ignore_robotstxt_request(self):
self.crawler.settings.set('ROBOTSTXT_OBEY', True)
def ignore_request(request, spider):
deferred = Deferred()
reactor.callFromThread(deferred.errback, failure.Failure(IgnoreRequest()))
return deferred
self.crawler.engine.download.side_effect = ignore_request
middleware = RobotsTxtMiddleware(self.crawler)
mw_module_logger.error = mock.MagicMock()
d = self.assertNotIgnored(Request('http://site.local/allowed'), middleware)
d.addCallback(lambda _: self.assertFalse(mw_module_logger.error.called))
return d
def test_robotstxt_user_agent_setting(self):
crawler = self._get_successful_crawler()
crawler.settings.set('ROBOTSTXT_USER_AGENT', 'Examplebot')
crawler.settings.set('USER_AGENT', 'Mozilla/5.0 (X11; Linux x86_64)')
middleware = RobotsTxtMiddleware(crawler)
rp = mock.MagicMock(return_value=True)
middleware.process_request_2(rp, Request('http://site.local/allowed'), None)
rp.allowed.assert_called_once_with('http://site.local/allowed', 'Examplebot')
def assertNotIgnored(self, request, middleware):
spider = None # not actually used
dfd = maybeDeferred(middleware.process_request, request, spider)
dfd.addCallback(self.assertIsNone)
return dfd
def assertIgnored(self, request, middleware):
spider = None # not actually used
return self.assertFailure(maybeDeferred(middleware.process_request, request, spider),
IgnoreRequest)
class RobotsTxtMiddlewareWithRerpTest(RobotsTxtMiddlewareTest):
if not rerp_available():
skip = "Rerp parser is not installed"
def setUp(self):
super(RobotsTxtMiddlewareWithRerpTest, self).setUp()
self.crawler.settings.set('ROBOTSTXT_PARSER', 'scrapy.robotstxt.RerpRobotParser')
class RobotsTxtMiddlewareWithReppyTest(RobotsTxtMiddlewareTest):
if not reppy_available():
skip = "Reppy parser is not installed"
def setUp(self):
super(RobotsTxtMiddlewareWithReppyTest, self).setUp()
self.crawler.settings.set('ROBOTSTXT_PARSER', 'scrapy.robotstxt.ReppyRobotParser')
| from unittest import mock
from twisted.internet import reactor, error
from twisted.internet.defer import Deferred, DeferredList, maybeDeferred
from twisted.python import failure
from twisted.trial import unittest
from scrapy.downloadermiddlewares.robotstxt import (RobotsTxtMiddleware,
logger as mw_module_logger)
from scrapy.exceptions import IgnoreRequest, NotConfigured
from scrapy.http import Request, Response, TextResponse
from scrapy.settings import Settings
from tests.test_robotstxt_interface import rerp_available, reppy_available
class RobotsTxtMiddlewareTest(unittest.TestCase):
def setUp(self):
self.crawler = mock.MagicMock()
self.crawler.settings = Settings()
self.crawler.engine.download = mock.MagicMock()
def tearDown(self):
del self.crawler
def test_robotstxt_settings(self):
self.crawler.settings = Settings()
self.crawler.settings.set('USER_AGENT', 'CustomAgent')
self.assertRaises(NotConfigured, RobotsTxtMiddleware, self.crawler)
def _get_successful_crawler(self):
crawler = self.crawler
crawler.settings.set('ROBOTSTXT_OBEY', True)
ROBOTS = u"""
User-Agent: *
Disallow: /admin/
Disallow: /static/
# taken from https://en.wikipedia.org/robots.txt
Disallow: /wiki/K%C3%A4ytt%C3%A4j%C3%A4:
Disallow: /wiki/Käyttäjä:
User-Agent: UnicödeBöt
Disallow: /some/randome/page.html
""".encode('utf-8')
response = TextResponse('http://site.local/robots.txt', body=ROBOTS)
def return_response(request, spider):
deferred = Deferred()
reactor.callFromThread(deferred.callback, response)
return deferred
crawler.engine.download.side_effect = return_response
return crawler
def test_robotstxt(self):
middleware = RobotsTxtMiddleware(self._get_successful_crawler())
return DeferredList([
self.assertNotIgnored(Request('http://site.local/allowed'), middleware),
self.assertIgnored(Request('http://site.local/admin/main'), middleware),
self.assertIgnored(Request('http://site.local/static/'), middleware),
self.assertIgnored(Request('http://site.local/wiki/K%C3%A4ytt%C3%A4j%C3%A4:'), middleware),
self.assertIgnored(Request(u'http://site.local/wiki/Käyttäjä:'), middleware)
], fireOnOneErrback=True)
def test_robotstxt_ready_parser(self):
middleware = RobotsTxtMiddleware(self._get_successful_crawler())
d = self.assertNotIgnored(Request('http://site.local/allowed'), middleware)
d.addCallback(lambda _: self.assertNotIgnored(Request('http://site.local/allowed'), middleware))
return d
def test_robotstxt_meta(self):
middleware = RobotsTxtMiddleware(self._get_successful_crawler())
meta = {'dont_obey_robotstxt': True}
return DeferredList([
self.assertNotIgnored(Request('http://site.local/allowed', meta=meta), middleware),
self.assertNotIgnored(Request('http://site.local/admin/main', meta=meta), middleware),
self.assertNotIgnored(Request('http://site.local/static/', meta=meta), middleware)
], fireOnOneErrback=True)
def _get_garbage_crawler(self):
crawler = self.crawler
crawler.settings.set('ROBOTSTXT_OBEY', True)
response = Response('http://site.local/robots.txt', body=b'GIF89a\xd3\x00\xfe\x00\xa2')
def return_response(request, spider):
deferred = Deferred()
reactor.callFromThread(deferred.callback, response)
return deferred
crawler.engine.download.side_effect = return_response
return crawler
def test_robotstxt_garbage(self):
# garbage response should be discarded, equal 'allow all'
middleware = RobotsTxtMiddleware(self._get_garbage_crawler())
deferred = DeferredList([
self.assertNotIgnored(Request('http://site.local'), middleware),
self.assertNotIgnored(Request('http://site.local/allowed'), middleware),
self.assertNotIgnored(Request('http://site.local/admin/main'), middleware),
self.assertNotIgnored(Request('http://site.local/static/'), middleware)
], fireOnOneErrback=True)
return deferred
def _get_emptybody_crawler(self):
crawler = self.crawler
crawler.settings.set('ROBOTSTXT_OBEY', True)
response = Response('http://site.local/robots.txt')
def return_response(request, spider):
deferred = Deferred()
reactor.callFromThread(deferred.callback, response)
return deferred
crawler.engine.download.side_effect = return_response
return crawler
def test_robotstxt_empty_response(self):
# empty response should equal 'allow all'
middleware = RobotsTxtMiddleware(self._get_emptybody_crawler())
return DeferredList([
self.assertNotIgnored(Request('http://site.local/allowed'), middleware),
self.assertNotIgnored(Request('http://site.local/admin/main'), middleware),
self.assertNotIgnored(Request('http://site.local/static/'), middleware)
], fireOnOneErrback=True)
def test_robotstxt_error(self):
self.crawler.settings.set('ROBOTSTXT_OBEY', True)
err = error.DNSLookupError('Robotstxt address not found')
def return_failure(request, spider):
deferred = Deferred()
reactor.callFromThread(deferred.errback, failure.Failure(err))
return deferred
self.crawler.engine.download.side_effect = return_failure
middleware = RobotsTxtMiddleware(self.crawler)
middleware._logerror = mock.MagicMock(side_effect=middleware._logerror)
deferred = middleware.process_request(Request('http://site.local'), None)
deferred.addCallback(lambda _: self.assertTrue(middleware._logerror.called))
return deferred
def test_robotstxt_immediate_error(self):
self.crawler.settings.set('ROBOTSTXT_OBEY', True)
err = error.DNSLookupError('Robotstxt address not found')
def immediate_failure(request, spider):
deferred = Deferred()
deferred.errback(failure.Failure(err))
return deferred
self.crawler.engine.download.side_effect = immediate_failure
middleware = RobotsTxtMiddleware(self.crawler)
return self.assertNotIgnored(Request('http://site.local'), middleware)
def test_ignore_robotstxt_request(self):
self.crawler.settings.set('ROBOTSTXT_OBEY', True)
def ignore_request(request, spider):
deferred = Deferred()
reactor.callFromThread(deferred.errback, failure.Failure(IgnoreRequest()))
return deferred
self.crawler.engine.download.side_effect = ignore_request
middleware = RobotsTxtMiddleware(self.crawler)
mw_module_logger.error = mock.MagicMock()
d = self.assertNotIgnored(Request('http://site.local/allowed'), middleware)
d.addCallback(lambda _: self.assertFalse(mw_module_logger.error.called))
return d
def test_robotstxt_user_agent_setting(self):
crawler = self._get_successful_crawler()
crawler.settings.set('ROBOTSTXT_USER_AGENT', 'Examplebot')
crawler.settings.set('USER_AGENT', 'Mozilla/5.0 (X11; Linux x86_64)')
middleware = RobotsTxtMiddleware(crawler)
rp = mock.MagicMock(return_value=True)
middleware.process_request_2(rp, Request('http://site.local/allowed'), None)
rp.allowed.assert_called_once_with('http://site.local/allowed', 'Examplebot')
def assertNotIgnored(self, request, middleware):
spider = None # not actually used
dfd = maybeDeferred(middleware.process_request, request, spider)
dfd.addCallback(self.assertIsNone)
return dfd
def assertIgnored(self, request, middleware):
spider = None # not actually used
return self.assertFailure(maybeDeferred(middleware.process_request, request, spider),
IgnoreRequest)
class RobotsTxtMiddlewareWithRerpTest(RobotsTxtMiddlewareTest):
if not rerp_available():
skip = "Rerp parser is not installed"
def setUp(self):
super(RobotsTxtMiddlewareWithRerpTest, self).setUp()
self.crawler.settings.set('ROBOTSTXT_PARSER', 'scrapy.robotstxt.RerpRobotParser')
class RobotsTxtMiddlewareWithReppyTest(RobotsTxtMiddlewareTest):
if not reppy_available():
skip = "Reppy parser is not installed"
def setUp(self):
super(RobotsTxtMiddlewareWithReppyTest, self).setUp()
self.crawler.settings.set('ROBOTSTXT_PARSER', 'scrapy.robotstxt.ReppyRobotParser')
| en | 0.434343 | User-Agent: * Disallow: /admin/ Disallow: /static/ # taken from https://en.wikipedia.org/robots.txt Disallow: /wiki/K%C3%A4ytt%C3%A4j%C3%A4: Disallow: /wiki/Käyttäjä: User-Agent: UnicödeBöt Disallow: /some/randome/page.html # garbage response should be discarded, equal 'allow all' # empty response should equal 'allow all' # not actually used # not actually used | 2.303633 | 2 |
setup.py | dvdotsenko/jsonrpc.py | 4 | 6628021 | from setuptools import setup, find_packages
version = '0.4.1'
long_description = """
JSON-RPC Parts is a library of composable components one would need to assemble a JSON-RPC server or client.
The parts provided are JSON-RPC message parser and serializer, a generic request handler collection, a WSGI-specific request handler and bits and pieces.
This JSON-RPC Parts collection supports both, JSON-RPC v.1.0 and v.2.0 including "batch" mode for v.2.0.
The parts are split into separate modules that can be used separately from this collection.
Since this collection is MIT-licensed, you are free grab a part of this code and use it in alsmost any.
"""
project_home = 'http://github.com/dvdotsenko/jsonrpc.py'
if __name__ == "__main__":
setup(
name='jsonrpcparts',
description='JSON-RPC client and server components',
long_description=long_description,
version=version,
author='<NAME>',
author_email='<EMAIL>',
url=project_home,
download_url=project_home+'/tarball/master',
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Topic :: Internet",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application"
],
keywords = ['JSON', 'jsonrpc', 'rpc', 'wsgi'],
license='MIT',
packages=find_packages(),
include_package_data=True,
install_requires=['requests']
)
# Next:
# python setup.py register
# python setup.py sdist upload
| from setuptools import setup, find_packages
version = '0.4.1'
long_description = """
JSON-RPC Parts is a library of composable components one would need to assemble a JSON-RPC server or client.
The parts provided are JSON-RPC message parser and serializer, a generic request handler collection, a WSGI-specific request handler and bits and pieces.
This JSON-RPC Parts collection supports both, JSON-RPC v.1.0 and v.2.0 including "batch" mode for v.2.0.
The parts are split into separate modules that can be used separately from this collection.
Since this collection is MIT-licensed, you are free grab a part of this code and use it in alsmost any.
"""
project_home = 'http://github.com/dvdotsenko/jsonrpc.py'
if __name__ == "__main__":
setup(
name='jsonrpcparts',
description='JSON-RPC client and server components',
long_description=long_description,
version=version,
author='<NAME>',
author_email='<EMAIL>',
url=project_home,
download_url=project_home+'/tarball/master',
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Topic :: Internet",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application"
],
keywords = ['JSON', 'jsonrpc', 'rpc', 'wsgi'],
license='MIT',
packages=find_packages(),
include_package_data=True,
install_requires=['requests']
)
# Next:
# python setup.py register
# python setup.py sdist upload
| en | 0.820115 | JSON-RPC Parts is a library of composable components one would need to assemble a JSON-RPC server or client. The parts provided are JSON-RPC message parser and serializer, a generic request handler collection, a WSGI-specific request handler and bits and pieces. This JSON-RPC Parts collection supports both, JSON-RPC v.1.0 and v.2.0 including "batch" mode for v.2.0. The parts are split into separate modules that can be used separately from this collection. Since this collection is MIT-licensed, you are free grab a part of this code and use it in alsmost any. # Next: # python setup.py register # python setup.py sdist upload | 1.557745 | 2 |
jechova.py | pyvec/jechova | 3 | 6628022 | <gh_stars>1-10
from argparse import ArgumentParser
import os
import sys
from operator import attrgetter
import arrow
from ics import Calendar
import requests
from slack import WebClient
# Only send a message when the number of remaining days is a key here.
# Values are emoji names; they should be more urgent for smaller numbers.
NOTIFY_WHEN_REMAINING_DAYS = {
3: 'panicmonster',
7: 'hourglass_flowing_sand',
14: 'eyes'
}
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument('--force', '-f', action='store_true')
parser.add_argument('--today', metavar='YYYY-MM-DD',
help="Override current date (for testing)")
parser.add_argument('channel')
parser.add_argument('pyvo_slug')
args = parser.parse_args()
if '/' in args.pyvo_slug:
raise ValueError(
"Meetup slug cannot contain slashes. See the README for usage."
)
response = requests.get(f'https://pyvo.cz/api/series/{args.pyvo_slug}.ics')
response.raise_for_status()
calendar = Calendar(response.text)
if args.today:
today = arrow.get(args.today)
else:
today = arrow.now('Europe/Prague')
event = min((e for e in calendar.events if e.begin > today),
key=attrgetter('begin'))
remaining_days = (event.begin - today).days
if not args.force and remaining_days not in NOTIFY_WHEN_REMAINING_DAYS:
print('Dní do dalšího srazu:', remaining_days)
print('Ozývám se, když zbývá:',
', '.join(map(str, NOTIFY_WHEN_REMAINING_DAYS)))
sys.exit()
for days, emoji in sorted(NOTIFY_WHEN_REMAINING_DAYS.items()):
if remaining_days <= days:
break
# nb. `emoji` keeps the value from the last iteration of this loop
if 'tentative-date' not in event.categories:
print("Zdá se, že příští sraz je naplánovaný!")
sys.exit()
channel = '#' + args.channel.lstrip('#')
client = WebClient(token=os.environ['SLACK_API_TOKEN'])
docs_url = "https://docs.pyvec.org/guides/meetup.html#informace-na-pyvo-cz"
web_url = f'https://pyvo.cz/{args.pyvo_slug}/'
if remaining_days < 0:
remaining_msg = 'Pyvo už bylo!'
elif remaining_days == 0:
remaining_msg = 'Pyvo je dnes!'
elif remaining_days == 1:
remaining_msg = 'Zbývá poslední den!'
elif remaining_days < 5:
remaining_msg = f'Zbývají {remaining_days} dny'
else:
remaining_msg = f'Zbývá {remaining_days} dní'
client.chat_postMessage(channel=channel, text=' '.join((
f'Máte téma? A mohla bych ho vidět? {remaining_msg} :{emoji}:\n',
'Pokud už tušíte, o čem Pyvo bude, přidejte to na pyvo.cz',
'přes odkaz _přidat informace o dalším srazu_ na',
f'<{web_url}|pyvo.cz/{args.pyvo_slug}>.\n',
'(Složitější případy řešte v <#C97Q9HHHT>)', # links to #pyvo channel
)))
| from argparse import ArgumentParser
import os
import sys
from operator import attrgetter
import arrow
from ics import Calendar
import requests
from slack import WebClient
# Only send a message when the number of remaining days is a key here.
# Values are emoji names; they should be more urgent for smaller numbers.
NOTIFY_WHEN_REMAINING_DAYS = {
3: 'panicmonster',
7: 'hourglass_flowing_sand',
14: 'eyes'
}
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument('--force', '-f', action='store_true')
parser.add_argument('--today', metavar='YYYY-MM-DD',
help="Override current date (for testing)")
parser.add_argument('channel')
parser.add_argument('pyvo_slug')
args = parser.parse_args()
if '/' in args.pyvo_slug:
raise ValueError(
"Meetup slug cannot contain slashes. See the README for usage."
)
response = requests.get(f'https://pyvo.cz/api/series/{args.pyvo_slug}.ics')
response.raise_for_status()
calendar = Calendar(response.text)
if args.today:
today = arrow.get(args.today)
else:
today = arrow.now('Europe/Prague')
event = min((e for e in calendar.events if e.begin > today),
key=attrgetter('begin'))
remaining_days = (event.begin - today).days
if not args.force and remaining_days not in NOTIFY_WHEN_REMAINING_DAYS:
print('Dní do dalšího srazu:', remaining_days)
print('Ozývám se, když zbývá:',
', '.join(map(str, NOTIFY_WHEN_REMAINING_DAYS)))
sys.exit()
for days, emoji in sorted(NOTIFY_WHEN_REMAINING_DAYS.items()):
if remaining_days <= days:
break
# nb. `emoji` keeps the value from the last iteration of this loop
if 'tentative-date' not in event.categories:
print("Zdá se, že příští sraz je naplánovaný!")
sys.exit()
channel = '#' + args.channel.lstrip('#')
client = WebClient(token=os.environ['SLACK_API_TOKEN'])
docs_url = "https://docs.pyvec.org/guides/meetup.html#informace-na-pyvo-cz"
web_url = f'https://pyvo.cz/{args.pyvo_slug}/'
if remaining_days < 0:
remaining_msg = 'Pyvo už bylo!'
elif remaining_days == 0:
remaining_msg = 'Pyvo je dnes!'
elif remaining_days == 1:
remaining_msg = 'Zbývá poslední den!'
elif remaining_days < 5:
remaining_msg = f'Zbývají {remaining_days} dny'
else:
remaining_msg = f'Zbývá {remaining_days} dní'
client.chat_postMessage(channel=channel, text=' '.join((
f'Máte téma? A mohla bych ho vidět? {remaining_msg} :{emoji}:\n',
'Pokud už tušíte, o čem Pyvo bude, přidejte to na pyvo.cz',
'přes odkaz _přidat informace o dalším srazu_ na',
f'<{web_url}|pyvo.cz/{args.pyvo_slug}>.\n',
'(Složitější případy řešte v <#C97Q9HHHT>)', # links to #pyvo channel
))) | en | 0.755785 | # Only send a message when the number of remaining days is a key here. # Values are emoji names; they should be more urgent for smaller numbers. # nb. `emoji` keeps the value from the last iteration of this loop #informace-na-pyvo-cz" #C97Q9HHHT>)', # links to #pyvo channel | 2.455244 | 2 |
d2scream/__init__.py | minervaclient/2scream | 2 | 6628023 | <filename>d2scream/__init__.py
from __future__ import absolute_import
from __future__ import unicode_literals
from . import login_shibboleth
from . import course_ids
from . import grades as grades_mod
from . import assign as assign_mod
class CourseActions():
def __init__(self,creds,ou):
self.creds = creds
self.ou = ou
def grades(self):
return grades_mod.dump(self.creds,self.ou)
def assignments(self):
return assign_mod.dump(self.creds,self.ou)
class Client():
def __init__(self,creds):
self.creds = creds
def courses(self):
return course_ids.dump(self.creds)
def grades(self,ou):
return grades_mod.dump(self.creds,ou)
def assignments(self,ou):
return assign_mod.dump(self.creds,ou)
def using(self,course):
return CourseActions(self.creds, course.ou)
def login(creds):
login_shibboleth.login(creds)
return Client(creds)
def login_saved():
from . import shib_credentials
return login(shib_credentials)
| <filename>d2scream/__init__.py
from __future__ import absolute_import
from __future__ import unicode_literals
from . import login_shibboleth
from . import course_ids
from . import grades as grades_mod
from . import assign as assign_mod
class CourseActions():
def __init__(self,creds,ou):
self.creds = creds
self.ou = ou
def grades(self):
return grades_mod.dump(self.creds,self.ou)
def assignments(self):
return assign_mod.dump(self.creds,self.ou)
class Client():
def __init__(self,creds):
self.creds = creds
def courses(self):
return course_ids.dump(self.creds)
def grades(self,ou):
return grades_mod.dump(self.creds,ou)
def assignments(self,ou):
return assign_mod.dump(self.creds,ou)
def using(self,course):
return CourseActions(self.creds, course.ou)
def login(creds):
login_shibboleth.login(creds)
return Client(creds)
def login_saved():
from . import shib_credentials
return login(shib_credentials)
| none | 1 | 2.337674 | 2 | |
airflow/plugins/operators/load_dimension.py | zqf1616/Udacity_project | 0 | 6628024 | from airflow.hooks.postgres_hook import PostgresHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
class LoadDimensionOperator(BaseOperator):
ui_color = '#80BD9E'
dimension_table_insert_sql = """
INSERT INTO {destination_table}
{insert_sql}
"""
# dimension_table_drop_sql = """
# DELETE FROM {destination_table}
# """
@apply_defaults
def __init__(self,
# Define your operators params (with defaults) here
# Example:
# conn_id = your-connection-name
redshift_conn_id="",
destination_table="",
insert_sql = "",
append_only = False,
*args, **kwargs):
self.redshift_conn_id = redshift_conn_id
self.destination_table = destination_table
self.insert_sql = insert_sql
self.append_only = append_only
super(LoadDimensionOperator, self).__init__(*args, **kwargs)
# Map params here
# Example:
# self.conn_id = conn_id
def execute(self, context):
#self.log.info('LoadDimensionOperator not implemented yet')
redshift = PostgresHook(postgres_conn_id=self.redshift_conn_id)
dimension_insert_sql = LoadFactOperator.dimension_table_insert_sql.format(
destination_table=self.destination_table,
insert_sql = self.insert_sql)
# dimension_drop_sql = LoadFactOperator.dimension_table_drop_sql.format(
# destination_table=self.destination_table)
if self.append_only == False:
#drop table
redshift.run("DELETE FROM {}".format(self.table))
redshift.run(dimension_insert_sql)
self.log.info('LoadDimensionOperator executed. append_only = False')
else:
redshift.run(dimension_insert_sql)
self.log.info('LoadDimensionOperator executed. append_only = True')
| from airflow.hooks.postgres_hook import PostgresHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
class LoadDimensionOperator(BaseOperator):
ui_color = '#80BD9E'
dimension_table_insert_sql = """
INSERT INTO {destination_table}
{insert_sql}
"""
# dimension_table_drop_sql = """
# DELETE FROM {destination_table}
# """
@apply_defaults
def __init__(self,
# Define your operators params (with defaults) here
# Example:
# conn_id = your-connection-name
redshift_conn_id="",
destination_table="",
insert_sql = "",
append_only = False,
*args, **kwargs):
self.redshift_conn_id = redshift_conn_id
self.destination_table = destination_table
self.insert_sql = insert_sql
self.append_only = append_only
super(LoadDimensionOperator, self).__init__(*args, **kwargs)
# Map params here
# Example:
# self.conn_id = conn_id
def execute(self, context):
#self.log.info('LoadDimensionOperator not implemented yet')
redshift = PostgresHook(postgres_conn_id=self.redshift_conn_id)
dimension_insert_sql = LoadFactOperator.dimension_table_insert_sql.format(
destination_table=self.destination_table,
insert_sql = self.insert_sql)
# dimension_drop_sql = LoadFactOperator.dimension_table_drop_sql.format(
# destination_table=self.destination_table)
if self.append_only == False:
#drop table
redshift.run("DELETE FROM {}".format(self.table))
redshift.run(dimension_insert_sql)
self.log.info('LoadDimensionOperator executed. append_only = False')
else:
redshift.run(dimension_insert_sql)
self.log.info('LoadDimensionOperator executed. append_only = True')
| en | 0.448775 | INSERT INTO {destination_table} {insert_sql} # dimension_table_drop_sql = """ # DELETE FROM {destination_table} # """ # Define your operators params (with defaults) here # Example: # conn_id = your-connection-name # Map params here # Example: # self.conn_id = conn_id #self.log.info('LoadDimensionOperator not implemented yet') # dimension_drop_sql = LoadFactOperator.dimension_table_drop_sql.format( # destination_table=self.destination_table) #drop table | 2.236456 | 2 |
shop/models.py | BranimirKoprivnjak/django-ecommerce | 0 | 6628025 | from django.db import models
from django.utils.text import slugify
from accounts.models import User
from django.shortcuts import reverse
from django.contrib.auth import get_user_model
from checkout.models import BillingAddress
User = get_user_model()
CATEGORY_CHOICES = [
#(item in db, human readable text)
('Jackets', 'Jackets'),
('Hoodies', 'Hoodies'),
('Tshirts', 'T-shirts'),
('Scarfs', 'Scarfs'),
('Bags', 'Bags')
]
class Item(models.Model):
title = models.CharField(max_length=100)
price = models.FloatField()
discount_price = models.FloatField(blank=True, null=True)
#if added after initial migrations, delete the initial migration log
slug = models.SlugField(allow_unicode=True, unique=True, blank=True)
#req: Pillow
image = models.ImageField(upload_to='static/simplewebshop/images')
category = models.CharField(choices=CATEGORY_CHOICES, max_length=10, blank=True)
description = models.TextField(blank=True)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super().save(*args, **kwargs)
#needed when clicking to see detail item page
def get_absolute_url(self):
return reverse('shop:single', kwargs={
'slug':self.slug
})
class OrderItem(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
ordered = models.BooleanField(default=False)
item = models.ForeignKey(Item, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
def __str__(self):
return f'{self.quantity} of {self.item.title}'
def get_final_price(self):
if self.item.discount_price:
return self.quantity * self.item.discount_price
return f'{(self.quantity * self.item.price):.2f}'
class Order(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
#will create cross reference table (join table) in db
items = models.ManyToManyField(OrderItem)
start_date = models.DateTimeField(auto_now_add=True)
ordered_date = models.DateTimeField()
ordered = models.BooleanField(default=False)
billing_address = models.ForeignKey(
BillingAddress, on_delete=models.SET_NULL, blank=True, null=True)
def __str__(self):
return self.user.username
def total(self):
total = 0
for order_item in self.items.all():
total += float(order_item.get_final_price())
return f'{total:.2f}'
| from django.db import models
from django.utils.text import slugify
from accounts.models import User
from django.shortcuts import reverse
from django.contrib.auth import get_user_model
from checkout.models import BillingAddress
User = get_user_model()
CATEGORY_CHOICES = [
#(item in db, human readable text)
('Jackets', 'Jackets'),
('Hoodies', 'Hoodies'),
('Tshirts', 'T-shirts'),
('Scarfs', 'Scarfs'),
('Bags', 'Bags')
]
class Item(models.Model):
title = models.CharField(max_length=100)
price = models.FloatField()
discount_price = models.FloatField(blank=True, null=True)
#if added after initial migrations, delete the initial migration log
slug = models.SlugField(allow_unicode=True, unique=True, blank=True)
#req: Pillow
image = models.ImageField(upload_to='static/simplewebshop/images')
category = models.CharField(choices=CATEGORY_CHOICES, max_length=10, blank=True)
description = models.TextField(blank=True)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super().save(*args, **kwargs)
#needed when clicking to see detail item page
def get_absolute_url(self):
return reverse('shop:single', kwargs={
'slug':self.slug
})
class OrderItem(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
ordered = models.BooleanField(default=False)
item = models.ForeignKey(Item, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
def __str__(self):
return f'{self.quantity} of {self.item.title}'
def get_final_price(self):
if self.item.discount_price:
return self.quantity * self.item.discount_price
return f'{(self.quantity * self.item.price):.2f}'
class Order(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
#will create cross reference table (join table) in db
items = models.ManyToManyField(OrderItem)
start_date = models.DateTimeField(auto_now_add=True)
ordered_date = models.DateTimeField()
ordered = models.BooleanField(default=False)
billing_address = models.ForeignKey(
BillingAddress, on_delete=models.SET_NULL, blank=True, null=True)
def __str__(self):
return self.user.username
def total(self):
total = 0
for order_item in self.items.all():
total += float(order_item.get_final_price())
return f'{total:.2f}'
| en | 0.732698 | #(item in db, human readable text) #if added after initial migrations, delete the initial migration log #req: Pillow #needed when clicking to see detail item page #will create cross reference table (join table) in db | 2.102943 | 2 |
space_manager/cabinets/serializers.py | yoojat/Space-Manager | 0 | 6628026 | from rest_framework import serializers
from space_manager.branches import serializers as branch_serializers
from space_manager.cabinets import serializers as cabinet_serializers
from . import models
from space_manager.branches import models as branch_models
from space_manager.users import serializers as user_serializers
class SimpleCabinetSerilaizer(serializers.ModelSerializer):
class Meta:
model = models.Cabinet
fields = ('cabinet_number', 'id')
class BriefCabinetSetSerializer(serializers.ModelSerializer):
branch = branch_serializers.BranchForMembershipSerializer()
class Meta:
model = models.CabinetSet
fields = (
'branch',
'id',
)
class CabinetSerializerForSelect(serializers.ModelSerializer):
cabinet_set = BriefCabinetSetSerializer()
user = user_serializers.UserSerializer()
class Meta:
model = models.Cabinet
fields = ('cabinet_number', 'xpos', 'ypos', 'id', 'start_date',
'cabinet_set', 'end_date', 'is_usable', 'is_clean', 'user')
class CabinetActionSerializer(serializers.ModelSerializer):
class Meta:
model = models.CabinetAction
fields = '__all__'
class CabinetHistorySerializer(serializers.ModelSerializer):
cabinet_action = CabinetActionSerializer()
class Meta:
model = models.CabinetHistory
fied = (
'cabinet',
'start_date',
'end_date',
'cabinet_action',
)
class CabinetMembershipSerializer(serializers.ModelSerializer):
cabinet_set = BriefCabinetSetSerializer()
class Meta:
model = models.Cabinet
fields = ('cabinet_number', 'cabinet_set')
class CabinetSetSerializer(serializers.ModelSerializer):
# cabinets = CabinetSerializerForSelect(many=True)
class Meta:
model = models.CabinetSet
fields = ('width', 'height', 'xpos', 'ypos', 'order', 'desc', 'branch',
'id', 'horizontal_num', 'vertical_num')
class CabinetSetDetailSerializer(serializers.ModelSerializer):
cabinets = cabinet_serializers.CabinetSerializerForSelect(many=True)
class Meta:
model = models.CabinetSet
fields = ('desc', 'id', 'horizontal_num', 'vertical_num', 'cabinets')
class BranchCabinetSetsSerializer(serializers.ModelSerializer):
cabinet_sets = CabinetSetSerializer(many=True)
class Meta:
model = branch_models.Branch
fields = ('lounge_img_cabinet', 'cabinet_sets', 'branch_name', 'id')
class InputCabinetSetSerializer(serializers.ModelSerializer):
class Meta:
model = models.CabinetSet
fields = (
'width',
'height',
'order',
'desc',
)
class InputCabinetSerializer(serializers.ModelSerializer):
class Meta:
model = models.Cabinet
fields = (
'cabinet_number',
'cabinet_set',
'xpos',
'ypos',
)
class HistorySerializer(serializers.ModelSerializer):
cabinet = CabinetSerializerForSelect()
cabinet_action = CabinetActionSerializer()
user = user_serializers.UserSerializer()
class Meta:
model = models.CabinetHistory
fields = ('id', 'user', 'cabinet', 'start_date', 'end_date',
'cabinet_action', 'created_at')
class InputCabLockSerializer(serializers.ModelSerializer):
class Meta:
model = models.CabinetLock
fields = (
'lock_number',
'lock_password',
'cabinet',
)
class CabinetSerializerForCablock(serializers.ModelSerializer):
class Meta:
model = models.Cabinet
fields = ('cabinet_number', )
class CabLockSerializer(serializers.ModelSerializer):
cabinet = CabinetSerializerForCablock()
class Meta:
model = models.CabinetLock
fields = (
'id',
'branch',
'lock_number',
'lock_password',
'cabinet',
)
class CabinetDetailSerializer(serializers.ModelSerializer):
cabinet_historys = HistorySerializer(many=True)
user = user_serializers.UserSerializer()
cabinet_lock = CabLockSerializer()
class Meta:
model = models.Cabinet
fields = ('id', 'cabinet_number', 'cabinet_set', 'xpos', 'ypos',
'updated_at', 'start_date', 'end_date', 'cabinet_historys',
'user', 'cabinet_lock')
| from rest_framework import serializers
from space_manager.branches import serializers as branch_serializers
from space_manager.cabinets import serializers as cabinet_serializers
from . import models
from space_manager.branches import models as branch_models
from space_manager.users import serializers as user_serializers
class SimpleCabinetSerilaizer(serializers.ModelSerializer):
class Meta:
model = models.Cabinet
fields = ('cabinet_number', 'id')
class BriefCabinetSetSerializer(serializers.ModelSerializer):
branch = branch_serializers.BranchForMembershipSerializer()
class Meta:
model = models.CabinetSet
fields = (
'branch',
'id',
)
class CabinetSerializerForSelect(serializers.ModelSerializer):
cabinet_set = BriefCabinetSetSerializer()
user = user_serializers.UserSerializer()
class Meta:
model = models.Cabinet
fields = ('cabinet_number', 'xpos', 'ypos', 'id', 'start_date',
'cabinet_set', 'end_date', 'is_usable', 'is_clean', 'user')
class CabinetActionSerializer(serializers.ModelSerializer):
class Meta:
model = models.CabinetAction
fields = '__all__'
class CabinetHistorySerializer(serializers.ModelSerializer):
cabinet_action = CabinetActionSerializer()
class Meta:
model = models.CabinetHistory
fied = (
'cabinet',
'start_date',
'end_date',
'cabinet_action',
)
class CabinetMembershipSerializer(serializers.ModelSerializer):
cabinet_set = BriefCabinetSetSerializer()
class Meta:
model = models.Cabinet
fields = ('cabinet_number', 'cabinet_set')
class CabinetSetSerializer(serializers.ModelSerializer):
# cabinets = CabinetSerializerForSelect(many=True)
class Meta:
model = models.CabinetSet
fields = ('width', 'height', 'xpos', 'ypos', 'order', 'desc', 'branch',
'id', 'horizontal_num', 'vertical_num')
class CabinetSetDetailSerializer(serializers.ModelSerializer):
cabinets = cabinet_serializers.CabinetSerializerForSelect(many=True)
class Meta:
model = models.CabinetSet
fields = ('desc', 'id', 'horizontal_num', 'vertical_num', 'cabinets')
class BranchCabinetSetsSerializer(serializers.ModelSerializer):
cabinet_sets = CabinetSetSerializer(many=True)
class Meta:
model = branch_models.Branch
fields = ('lounge_img_cabinet', 'cabinet_sets', 'branch_name', 'id')
class InputCabinetSetSerializer(serializers.ModelSerializer):
class Meta:
model = models.CabinetSet
fields = (
'width',
'height',
'order',
'desc',
)
class InputCabinetSerializer(serializers.ModelSerializer):
class Meta:
model = models.Cabinet
fields = (
'cabinet_number',
'cabinet_set',
'xpos',
'ypos',
)
class HistorySerializer(serializers.ModelSerializer):
cabinet = CabinetSerializerForSelect()
cabinet_action = CabinetActionSerializer()
user = user_serializers.UserSerializer()
class Meta:
model = models.CabinetHistory
fields = ('id', 'user', 'cabinet', 'start_date', 'end_date',
'cabinet_action', 'created_at')
class InputCabLockSerializer(serializers.ModelSerializer):
class Meta:
model = models.CabinetLock
fields = (
'lock_number',
'lock_password',
'cabinet',
)
class CabinetSerializerForCablock(serializers.ModelSerializer):
class Meta:
model = models.Cabinet
fields = ('cabinet_number', )
class CabLockSerializer(serializers.ModelSerializer):
cabinet = CabinetSerializerForCablock()
class Meta:
model = models.CabinetLock
fields = (
'id',
'branch',
'lock_number',
'lock_password',
'cabinet',
)
class CabinetDetailSerializer(serializers.ModelSerializer):
cabinet_historys = HistorySerializer(many=True)
user = user_serializers.UserSerializer()
cabinet_lock = CabLockSerializer()
class Meta:
model = models.Cabinet
fields = ('id', 'cabinet_number', 'cabinet_set', 'xpos', 'ypos',
'updated_at', 'start_date', 'end_date', 'cabinet_historys',
'user', 'cabinet_lock')
| en | 0.4759 | # cabinets = CabinetSerializerForSelect(many=True) | 1.991096 | 2 |
src/sima/simo/compensatortype.py | SINTEF/simapy | 0 | 6628027 | <filename>src/sima/simo/compensatortype.py
# Generated with CompensatorType
#
from enum import Enum
from enum import auto
class CompensatorType(Enum):
""""""
GENERIC = auto()
NOT_IMPLEMENTED = auto()
def label(self):
if self == CompensatorType.GENERIC:
return "Generic model"
if self == CompensatorType.NOT_IMPLEMENTED:
return "Not implemented" | <filename>src/sima/simo/compensatortype.py
# Generated with CompensatorType
#
from enum import Enum
from enum import auto
class CompensatorType(Enum):
""""""
GENERIC = auto()
NOT_IMPLEMENTED = auto()
def label(self):
if self == CompensatorType.GENERIC:
return "Generic model"
if self == CompensatorType.NOT_IMPLEMENTED:
return "Not implemented" | en | 0.889859 | # Generated with CompensatorType # | 2.649789 | 3 |
deepchem/molnet/load_function/kinase_datasets.py | cjgalvin/deepchem | 3 | 6628028 | """
KINASE dataset loader
"""
import os
import logging
import time
import numpy as np
import deepchem
from deepchem.molnet.load_function.kaggle_features import merck_descriptors
TRAIN_URL = "https://deepchemdata.s3-us-west-1.amazonaws.com/datasets/KINASE_training_disguised_combined_full.csv.gz"
VALID_UR = "https://deepchemdata.s3-us-west-1.amazonaws.com/datasets/KINASE_test1_disguised_combined_full.csv.gz"
TEST_URL = "https://deepchemdata.s3-us-west-1.amazonaws.com/datasets/KINASE_test2_disguised_combined_full.csv.gz"
TRAIN_FILENAME = "KINASE_training_disguised_combined_full.csv.gz"
VALID_FILENAME = "KINASE_test1_disguised_combined_full.csv.gz"
TEST_FILENAME = "KINASE_test2_disguised_combined_full.csv.gz"
logger = logging.getLogger(__name__)
def remove_missing_entries(dataset):
"""Remove missing entries.
Some of the datasets have missing entries that sneak in as zero'd out
feature vectors. Get rid of them.
"""
for i, (X, y, w, ids) in enumerate(dataset.itershards()):
available_rows = X.any(axis=1)
logger.info("Shard %d has %d missing entries." %
(i, np.count_nonzero(~available_rows)))
X = X[available_rows]
y = y[available_rows]
w = w[available_rows]
ids = ids[available_rows]
dataset.set_shard(i, X, y, w, ids)
def get_transformers(train_dataset):
"""Gets transformers applied to the dataset"""
#TODO: Check for this
transformers = list()
return transformers
def gen_kinase(KINASE_tasks,
train_dir,
valid_dir,
test_dir,
data_dir,
shard_size=2000):
time1 = time.time()
train_files = os.path.join(data_dir, TRAIN_FILENAME)
valid_files = os.path.join(data_dir, VALID_FILENAME)
test_files = os.path.join(data_dir, TEST_FILENAME)
# Download files if they don't exist
if not os.path.exists(train_files):
logger.info("Downloading training file...")
deepchem.utils.data_utils.download_url(url=TRAIN_URL, dest_dir=data_dir)
logger.info("Training file download complete.")
logger.info("Downloading validation file...")
deepchem.utils.data_utils.download_url(url=VALID_URL, dest_dir=data_dir)
logger.info("Validation file download complete.")
logger.info("Downloading test file...")
deepchem.utils.data_utils.download_url(url=TEST_URL, dest_dir=data_dir)
logger.info("Test file download complete")
# Featurize the KINASE dataset
logger.info("About to featurize KINASE dataset.")
featurizer = deepchem.feat.UserDefinedFeaturizer(merck_descriptors)
loader = deepchem.data.UserCSVLoader(
tasks=KINASE_tasks, id_field="Molecule", featurizer=featurizer)
logger.info("Featurizing train datasets...")
train_dataset = loader.featurize(
input_files=train_files, shard_size=shard_size)
logger.info("Featurizing validation datasets...")
valid_dataset = loader.featurize(
input_files=valid_files, shard_size=shard_size)
logger.info("Featurizing test datasets....")
test_dataset = loader.featurize(input_files=test_files, shard_size=shard_size)
logger.info("Remove missing entries from dataset")
remove_missing_entries(train_dataset)
remove_missing_entries(valid_dataset)
remove_missing_entries(test_dataset)
# Shuffle the training data
logger.info("Shuffling the training dataset")
train_dataset.sparse_shuffle()
# Apply transformations
logger.info("Transformating datasets with transformers")
transformers = get_transformers(train_dataset)
for transformer in transformers:
logger.info("Performing transformations with {}".format(
transformer.__class__.__name__))
logger.info("Transforming the training dataset...")
train_dataset = transformer.transform(train_dataset)
logger.info("Transforming the validation dataset...")
valid_dataset = transformer.transform(valid_dataset)
logger.info("Transforming the test dataset...")
test_dataset = transformer.transform(test_dataset)
logger.info("Transformations complete.")
logger.info("Moving datasets to corresponding directories")
train_dataset.move(train_dir)
logger.info("Train dataset moved.")
valid_dataset.move(valid_dir)
logger.info("Validation dataset moved.")
test_dataset.move(test_dir)
logger.info("Test dataset moved.")
time2 = time.time()
##### TIMING ######
logger.info("TIMING: KINASE fitting took %0.3f s" % (time2 - time1))
return train_dataset, valid_dataset, test_dataset
def load_kinase(shard_size=2000, featurizer=None, split=None, reload=True):
"""Loads Kinase datasets, does not do train/test split
The Kinase dataset is an in-house dataset from Merck that was first introduced in the following paper:
Ramsundar, Bharath, et al. "Is multitask deep learning practical for pharma?." Journal of chemical information and modeling 57.8 (2017): 2068-2076.
It contains 2500 Merck in-house compounds that were measured
for IC50 of inhibition on 99 protein kinases. Unlike most of
the other datasets featured in MoleculeNet, the Kinase
collection does not have structures for the compounds tested
since they were proprietary Merck compounds. However, the
collection does feature pre-computed descriptors for these
compounds.
Note that the original train/valid/test split from the source
data was preserved here, so this function doesn't allow for
alternate modes of splitting. Similarly, since the source data
came pre-featurized, it is not possible to apply alternative
featurizations.
Parameters
----------
shard_size: int, optional
Size of the DiskDataset shards to write on disk
featurizer: optional
Ignored since featurization pre-computed
split: optional
Ignored since split pre-computed
reload: bool, optional
Whether to automatically re-load from disk
"""
KINASE_tasks = [
'T_00013', 'T_00014', 'T_00015', 'T_00016', 'T_00017', 'T_00018',
'T_00019', 'T_00020', 'T_00021', 'T_00022', 'T_00023', 'T_00024',
'T_00025', 'T_00026', 'T_00027', 'T_00028', 'T_00029', 'T_00030',
'T_00031', 'T_00032', 'T_00033', 'T_00034', 'T_00035', 'T_00036',
'T_00037', 'T_00038', 'T_00039', 'T_00040', 'T_00041', 'T_00042',
'T_00043', 'T_00044', 'T_00045', 'T_00046', 'T_00047', 'T_00048',
'T_00049', 'T_00050', 'T_00051', 'T_00052', 'T_00053', 'T_00054',
'T_00055', 'T_00056', 'T_00057', 'T_00058', 'T_00059', 'T_00060',
'T_00061', 'T_00062', 'T_00063', 'T_00064', 'T_00065', 'T_00066',
'T_00067', 'T_00068', 'T_00069', 'T_00070', 'T_00071', 'T_00072',
'T_00073', 'T_00074', 'T_00075', 'T_00076', 'T_00077', 'T_00078',
'T_00079', 'T_00080', 'T_00081', 'T_00082', 'T_00083', 'T_00084',
'T_00085', 'T_00086', 'T_00087', 'T_00088', 'T_00089', 'T_00090',
'T_00091', 'T_00092', 'T_00093', 'T_00094', 'T_00095', 'T_00096',
'T_00097', 'T_00098', 'T_00099', 'T_00100', 'T_00101', 'T_00102',
'T_00103', 'T_00104', 'T_00105', 'T_00106', 'T_00107', 'T_00108',
'T_00109', 'T_00110', 'T_00111'
]
data_dir = deepchem.utils.data_utils.get_data_dir()
data_dir = os.path.join(data_dir, "kinase")
if not os.path.exists(data_dir):
os.mkdir(data_dir)
train_dir = os.path.join(data_dir, "train_dir")
valid_dir = os.path.join(data_dir, "valid_dir")
test_dir = os.path.join(data_dir, "test_dir")
if (os.path.exists(train_dir) and os.path.exists(valid_dir) and
os.path.exists(test_dir)):
logger.info("Reloading existing datasets")
train_dataset = deepchem.data.DiskDataset(train_dir)
valid_dataset = deepchem.data.DiskDataset(valid_dir)
test_dataset = deepchem.data.DiskDataset(test_dir)
else:
logger.info("Featurizing datasets")
train_dataset, valid_dataset, test_dataset = \
gen_kinase(KINASE_tasks=KINASE_tasks, train_dir=train_dir,
valid_dir=valid_dir, test_dir=test_dir, data_dir=data_dir,
shard_size=shard_size)
transformers = get_transformers(train_dataset)
return KINASE_tasks, (train_dataset, valid_dataset,
test_dataset), transformers
| """
KINASE dataset loader
"""
import os
import logging
import time
import numpy as np
import deepchem
from deepchem.molnet.load_function.kaggle_features import merck_descriptors
TRAIN_URL = "https://deepchemdata.s3-us-west-1.amazonaws.com/datasets/KINASE_training_disguised_combined_full.csv.gz"
VALID_UR = "https://deepchemdata.s3-us-west-1.amazonaws.com/datasets/KINASE_test1_disguised_combined_full.csv.gz"
TEST_URL = "https://deepchemdata.s3-us-west-1.amazonaws.com/datasets/KINASE_test2_disguised_combined_full.csv.gz"
TRAIN_FILENAME = "KINASE_training_disguised_combined_full.csv.gz"
VALID_FILENAME = "KINASE_test1_disguised_combined_full.csv.gz"
TEST_FILENAME = "KINASE_test2_disguised_combined_full.csv.gz"
logger = logging.getLogger(__name__)
def remove_missing_entries(dataset):
"""Remove missing entries.
Some of the datasets have missing entries that sneak in as zero'd out
feature vectors. Get rid of them.
"""
for i, (X, y, w, ids) in enumerate(dataset.itershards()):
available_rows = X.any(axis=1)
logger.info("Shard %d has %d missing entries." %
(i, np.count_nonzero(~available_rows)))
X = X[available_rows]
y = y[available_rows]
w = w[available_rows]
ids = ids[available_rows]
dataset.set_shard(i, X, y, w, ids)
def get_transformers(train_dataset):
"""Gets transformers applied to the dataset"""
#TODO: Check for this
transformers = list()
return transformers
def gen_kinase(KINASE_tasks,
train_dir,
valid_dir,
test_dir,
data_dir,
shard_size=2000):
time1 = time.time()
train_files = os.path.join(data_dir, TRAIN_FILENAME)
valid_files = os.path.join(data_dir, VALID_FILENAME)
test_files = os.path.join(data_dir, TEST_FILENAME)
# Download files if they don't exist
if not os.path.exists(train_files):
logger.info("Downloading training file...")
deepchem.utils.data_utils.download_url(url=TRAIN_URL, dest_dir=data_dir)
logger.info("Training file download complete.")
logger.info("Downloading validation file...")
deepchem.utils.data_utils.download_url(url=VALID_URL, dest_dir=data_dir)
logger.info("Validation file download complete.")
logger.info("Downloading test file...")
deepchem.utils.data_utils.download_url(url=TEST_URL, dest_dir=data_dir)
logger.info("Test file download complete")
# Featurize the KINASE dataset
logger.info("About to featurize KINASE dataset.")
featurizer = deepchem.feat.UserDefinedFeaturizer(merck_descriptors)
loader = deepchem.data.UserCSVLoader(
tasks=KINASE_tasks, id_field="Molecule", featurizer=featurizer)
logger.info("Featurizing train datasets...")
train_dataset = loader.featurize(
input_files=train_files, shard_size=shard_size)
logger.info("Featurizing validation datasets...")
valid_dataset = loader.featurize(
input_files=valid_files, shard_size=shard_size)
logger.info("Featurizing test datasets....")
test_dataset = loader.featurize(input_files=test_files, shard_size=shard_size)
logger.info("Remove missing entries from dataset")
remove_missing_entries(train_dataset)
remove_missing_entries(valid_dataset)
remove_missing_entries(test_dataset)
# Shuffle the training data
logger.info("Shuffling the training dataset")
train_dataset.sparse_shuffle()
# Apply transformations
logger.info("Transformating datasets with transformers")
transformers = get_transformers(train_dataset)
for transformer in transformers:
logger.info("Performing transformations with {}".format(
transformer.__class__.__name__))
logger.info("Transforming the training dataset...")
train_dataset = transformer.transform(train_dataset)
logger.info("Transforming the validation dataset...")
valid_dataset = transformer.transform(valid_dataset)
logger.info("Transforming the test dataset...")
test_dataset = transformer.transform(test_dataset)
logger.info("Transformations complete.")
logger.info("Moving datasets to corresponding directories")
train_dataset.move(train_dir)
logger.info("Train dataset moved.")
valid_dataset.move(valid_dir)
logger.info("Validation dataset moved.")
test_dataset.move(test_dir)
logger.info("Test dataset moved.")
time2 = time.time()
##### TIMING ######
logger.info("TIMING: KINASE fitting took %0.3f s" % (time2 - time1))
return train_dataset, valid_dataset, test_dataset
def load_kinase(shard_size=2000, featurizer=None, split=None, reload=True):
"""Loads Kinase datasets, does not do train/test split
The Kinase dataset is an in-house dataset from Merck that was first introduced in the following paper:
Ramsundar, Bharath, et al. "Is multitask deep learning practical for pharma?." Journal of chemical information and modeling 57.8 (2017): 2068-2076.
It contains 2500 Merck in-house compounds that were measured
for IC50 of inhibition on 99 protein kinases. Unlike most of
the other datasets featured in MoleculeNet, the Kinase
collection does not have structures for the compounds tested
since they were proprietary Merck compounds. However, the
collection does feature pre-computed descriptors for these
compounds.
Note that the original train/valid/test split from the source
data was preserved here, so this function doesn't allow for
alternate modes of splitting. Similarly, since the source data
came pre-featurized, it is not possible to apply alternative
featurizations.
Parameters
----------
shard_size: int, optional
Size of the DiskDataset shards to write on disk
featurizer: optional
Ignored since featurization pre-computed
split: optional
Ignored since split pre-computed
reload: bool, optional
Whether to automatically re-load from disk
"""
KINASE_tasks = [
'T_00013', 'T_00014', 'T_00015', 'T_00016', 'T_00017', 'T_00018',
'T_00019', 'T_00020', 'T_00021', 'T_00022', 'T_00023', 'T_00024',
'T_00025', 'T_00026', 'T_00027', 'T_00028', 'T_00029', 'T_00030',
'T_00031', 'T_00032', 'T_00033', 'T_00034', 'T_00035', 'T_00036',
'T_00037', 'T_00038', 'T_00039', 'T_00040', 'T_00041', 'T_00042',
'T_00043', 'T_00044', 'T_00045', 'T_00046', 'T_00047', 'T_00048',
'T_00049', 'T_00050', 'T_00051', 'T_00052', 'T_00053', 'T_00054',
'T_00055', 'T_00056', 'T_00057', 'T_00058', 'T_00059', 'T_00060',
'T_00061', 'T_00062', 'T_00063', 'T_00064', 'T_00065', 'T_00066',
'T_00067', 'T_00068', 'T_00069', 'T_00070', 'T_00071', 'T_00072',
'T_00073', 'T_00074', 'T_00075', 'T_00076', 'T_00077', 'T_00078',
'T_00079', 'T_00080', 'T_00081', 'T_00082', 'T_00083', 'T_00084',
'T_00085', 'T_00086', 'T_00087', 'T_00088', 'T_00089', 'T_00090',
'T_00091', 'T_00092', 'T_00093', 'T_00094', 'T_00095', 'T_00096',
'T_00097', 'T_00098', 'T_00099', 'T_00100', 'T_00101', 'T_00102',
'T_00103', 'T_00104', 'T_00105', 'T_00106', 'T_00107', 'T_00108',
'T_00109', 'T_00110', 'T_00111'
]
data_dir = deepchem.utils.data_utils.get_data_dir()
data_dir = os.path.join(data_dir, "kinase")
if not os.path.exists(data_dir):
os.mkdir(data_dir)
train_dir = os.path.join(data_dir, "train_dir")
valid_dir = os.path.join(data_dir, "valid_dir")
test_dir = os.path.join(data_dir, "test_dir")
if (os.path.exists(train_dir) and os.path.exists(valid_dir) and
os.path.exists(test_dir)):
logger.info("Reloading existing datasets")
train_dataset = deepchem.data.DiskDataset(train_dir)
valid_dataset = deepchem.data.DiskDataset(valid_dir)
test_dataset = deepchem.data.DiskDataset(test_dir)
else:
logger.info("Featurizing datasets")
train_dataset, valid_dataset, test_dataset = \
gen_kinase(KINASE_tasks=KINASE_tasks, train_dir=train_dir,
valid_dir=valid_dir, test_dir=test_dir, data_dir=data_dir,
shard_size=shard_size)
transformers = get_transformers(train_dataset)
return KINASE_tasks, (train_dataset, valid_dataset,
test_dataset), transformers
| en | 0.90836 | KINASE dataset loader Remove missing entries. Some of the datasets have missing entries that sneak in as zero'd out feature vectors. Get rid of them. Gets transformers applied to the dataset #TODO: Check for this # Download files if they don't exist # Featurize the KINASE dataset # Shuffle the training data # Apply transformations ##### TIMING ###### Loads Kinase datasets, does not do train/test split The Kinase dataset is an in-house dataset from Merck that was first introduced in the following paper: Ramsundar, Bharath, et al. "Is multitask deep learning practical for pharma?." Journal of chemical information and modeling 57.8 (2017): 2068-2076. It contains 2500 Merck in-house compounds that were measured for IC50 of inhibition on 99 protein kinases. Unlike most of the other datasets featured in MoleculeNet, the Kinase collection does not have structures for the compounds tested since they were proprietary Merck compounds. However, the collection does feature pre-computed descriptors for these compounds. Note that the original train/valid/test split from the source data was preserved here, so this function doesn't allow for alternate modes of splitting. Similarly, since the source data came pre-featurized, it is not possible to apply alternative featurizations. Parameters ---------- shard_size: int, optional Size of the DiskDataset shards to write on disk featurizer: optional Ignored since featurization pre-computed split: optional Ignored since split pre-computed reload: bool, optional Whether to automatically re-load from disk | 2.572999 | 3 |
pruebas/_soporte/arbol/fabric/python.py | dued/dued | 0 | 6628029 | "Artefactos de distribución de PyPI /etc."
from dued import artefacto, Coleccion
@artefacto(nombre="all", default=True)
def all_(c):
"Fabrica todos los paquetes de Python."
pass
@artefacto
def sdist(c):
"Construye tar.gz de estilo clásico."
pass
@artefacto
def wheel(c):
"Construye una distb. wheel (rueda)."
pass
| "Artefactos de distribución de PyPI /etc."
from dued import artefacto, Coleccion
@artefacto(nombre="all", default=True)
def all_(c):
"Fabrica todos los paquetes de Python."
pass
@artefacto
def sdist(c):
"Construye tar.gz de estilo clásico."
pass
@artefacto
def wheel(c):
"Construye una distb. wheel (rueda)."
pass
| none | 1 | 1.713826 | 2 | |
alipay/aop/api/domain/RefundPaidDetail.py | antopen/alipay-sdk-python-all | 213 | 6628030 | <gh_stars>100-1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.TuitionRefundRoyaltyInfo import TuitionRefundRoyaltyInfo
class RefundPaidDetail(object):
def __init__(self):
self._plan_id = None
self._refund_amount = None
self._refund_royalty_info_list = None
@property
def plan_id(self):
return self._plan_id
@plan_id.setter
def plan_id(self, value):
self._plan_id = value
@property
def refund_amount(self):
return self._refund_amount
@refund_amount.setter
def refund_amount(self, value):
self._refund_amount = value
@property
def refund_royalty_info_list(self):
return self._refund_royalty_info_list
@refund_royalty_info_list.setter
def refund_royalty_info_list(self, value):
if isinstance(value, list):
self._refund_royalty_info_list = list()
for i in value:
if isinstance(i, TuitionRefundRoyaltyInfo):
self._refund_royalty_info_list.append(i)
else:
self._refund_royalty_info_list.append(TuitionRefundRoyaltyInfo.from_alipay_dict(i))
def to_alipay_dict(self):
params = dict()
if self.plan_id:
if hasattr(self.plan_id, 'to_alipay_dict'):
params['plan_id'] = self.plan_id.to_alipay_dict()
else:
params['plan_id'] = self.plan_id
if self.refund_amount:
if hasattr(self.refund_amount, 'to_alipay_dict'):
params['refund_amount'] = self.refund_amount.to_alipay_dict()
else:
params['refund_amount'] = self.refund_amount
if self.refund_royalty_info_list:
if isinstance(self.refund_royalty_info_list, list):
for i in range(0, len(self.refund_royalty_info_list)):
element = self.refund_royalty_info_list[i]
if hasattr(element, 'to_alipay_dict'):
self.refund_royalty_info_list[i] = element.to_alipay_dict()
if hasattr(self.refund_royalty_info_list, 'to_alipay_dict'):
params['refund_royalty_info_list'] = self.refund_royalty_info_list.to_alipay_dict()
else:
params['refund_royalty_info_list'] = self.refund_royalty_info_list
return params
@staticmethod
def from_alipay_dict(d):
if not d:
return None
o = RefundPaidDetail()
if 'plan_id' in d:
o.plan_id = d['plan_id']
if 'refund_amount' in d:
o.refund_amount = d['refund_amount']
if 'refund_royalty_info_list' in d:
o.refund_royalty_info_list = d['refund_royalty_info_list']
return o
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.TuitionRefundRoyaltyInfo import TuitionRefundRoyaltyInfo
class RefundPaidDetail(object):
def __init__(self):
self._plan_id = None
self._refund_amount = None
self._refund_royalty_info_list = None
@property
def plan_id(self):
return self._plan_id
@plan_id.setter
def plan_id(self, value):
self._plan_id = value
@property
def refund_amount(self):
return self._refund_amount
@refund_amount.setter
def refund_amount(self, value):
self._refund_amount = value
@property
def refund_royalty_info_list(self):
return self._refund_royalty_info_list
@refund_royalty_info_list.setter
def refund_royalty_info_list(self, value):
if isinstance(value, list):
self._refund_royalty_info_list = list()
for i in value:
if isinstance(i, TuitionRefundRoyaltyInfo):
self._refund_royalty_info_list.append(i)
else:
self._refund_royalty_info_list.append(TuitionRefundRoyaltyInfo.from_alipay_dict(i))
def to_alipay_dict(self):
params = dict()
if self.plan_id:
if hasattr(self.plan_id, 'to_alipay_dict'):
params['plan_id'] = self.plan_id.to_alipay_dict()
else:
params['plan_id'] = self.plan_id
if self.refund_amount:
if hasattr(self.refund_amount, 'to_alipay_dict'):
params['refund_amount'] = self.refund_amount.to_alipay_dict()
else:
params['refund_amount'] = self.refund_amount
if self.refund_royalty_info_list:
if isinstance(self.refund_royalty_info_list, list):
for i in range(0, len(self.refund_royalty_info_list)):
element = self.refund_royalty_info_list[i]
if hasattr(element, 'to_alipay_dict'):
self.refund_royalty_info_list[i] = element.to_alipay_dict()
if hasattr(self.refund_royalty_info_list, 'to_alipay_dict'):
params['refund_royalty_info_list'] = self.refund_royalty_info_list.to_alipay_dict()
else:
params['refund_royalty_info_list'] = self.refund_royalty_info_list
return params
@staticmethod
def from_alipay_dict(d):
if not d:
return None
o = RefundPaidDetail()
if 'plan_id' in d:
o.plan_id = d['plan_id']
if 'refund_amount' in d:
o.refund_amount = d['refund_amount']
if 'refund_royalty_info_list' in d:
o.refund_royalty_info_list = d['refund_royalty_info_list']
return o | en | 0.352855 | #!/usr/bin/env python # -*- coding: utf-8 -*- | 2.212597 | 2 |
tensorflow_model_analysis/eval_saved_model/example_trainers/fixed_prediction_estimator_extra_fields.py | josephw-ml/model-analysis | 0 | 6628031 | # 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
#
# 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.
"""Exports a simple "fixed prediction" estimator using tf.Learn.
This model always predicts the value of the "prediction" feature.
The eval_input_receiver_fn also parses the "fixed_float", "fixed_string",
"fixed_int", and "var_float", "var_string", "var_int" features.
"""
import tensorflow as tf
from tensorflow_model_analysis.eval_saved_model import export
from tensorflow_model_analysis.eval_saved_model.example_trainers import util
from tensorflow.python.estimator.canned import metric_keys
from tensorflow.python.estimator.canned import prediction_keys
def simple_fixed_prediction_estimator_extra_fields(export_path,
eval_export_path,
include_metrics=True):
"""Exports a simple fixed prediction estimator that parses extra fields."""
def model_fn(features, labels, mode, config):
"""Model function for custom estimator."""
del config
predictions = features['prediction']
predictions_dict = {
prediction_keys.PredictionKeys.PREDICTIONS: predictions,
}
if mode == tf.estimator.ModeKeys.PREDICT:
return tf.estimator.EstimatorSpec(
mode=mode,
predictions=predictions_dict,
export_outputs={
tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY:
tf.estimator.export.RegressionOutput(predictions)
})
loss = tf.compat.v1.losses.mean_squared_error(predictions, labels)
train_op = tf.compat.v1.assign_add(tf.compat.v1.train.get_global_step(), 1)
eval_metric_ops = {}
if include_metrics:
eval_metric_ops[
metric_keys.MetricKeys.LOSS_MEAN] = tf.compat.v1.metrics.mean(loss)
return tf.estimator.EstimatorSpec(
mode=mode,
loss=loss,
train_op=train_op,
predictions=predictions_dict,
eval_metric_ops=eval_metric_ops)
def train_input_fn():
"""Train input function."""
return {
'prediction': tf.constant([[1.0], [2.0], [3.0], [4.0]]),
}, tf.constant([[1.0], [2.0], [3.0], [4.0]]),
feature_spec = {'prediction': tf.io.FixedLenFeature([1], dtype=tf.float32)}
eval_feature_spec = {
'prediction':
tf.io.FixedLenFeature([1], dtype=tf.float32),
'label':
tf.io.FixedLenFeature([1], dtype=tf.float32),
'fixed_float':
tf.io.FixedLenFeature([1], dtype=tf.float32, default_value=0.0),
'fixed_string':
tf.io.FixedLenFeature([1], dtype=tf.string, default_value=''),
'fixed_int':
tf.io.FixedLenFeature([1], dtype=tf.int64, default_value=0),
'var_float':
tf.io.VarLenFeature(dtype=tf.float32),
'var_string':
tf.io.VarLenFeature(dtype=tf.string),
'var_int':
tf.io.VarLenFeature(dtype=tf.int64),
}
estimator = tf.estimator.Estimator(model_fn=model_fn)
estimator.train(input_fn=train_input_fn, steps=1)
return util.export_model_and_eval_model(
estimator=estimator,
serving_input_receiver_fn=(
tf.estimator.export.build_parsing_serving_input_receiver_fn(
feature_spec)),
eval_input_receiver_fn=export.build_parsing_eval_input_receiver_fn(
eval_feature_spec, label_key='label'),
export_path=export_path,
eval_export_path=eval_export_path)
| # 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
#
# 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.
"""Exports a simple "fixed prediction" estimator using tf.Learn.
This model always predicts the value of the "prediction" feature.
The eval_input_receiver_fn also parses the "fixed_float", "fixed_string",
"fixed_int", and "var_float", "var_string", "var_int" features.
"""
import tensorflow as tf
from tensorflow_model_analysis.eval_saved_model import export
from tensorflow_model_analysis.eval_saved_model.example_trainers import util
from tensorflow.python.estimator.canned import metric_keys
from tensorflow.python.estimator.canned import prediction_keys
def simple_fixed_prediction_estimator_extra_fields(export_path,
eval_export_path,
include_metrics=True):
"""Exports a simple fixed prediction estimator that parses extra fields."""
def model_fn(features, labels, mode, config):
"""Model function for custom estimator."""
del config
predictions = features['prediction']
predictions_dict = {
prediction_keys.PredictionKeys.PREDICTIONS: predictions,
}
if mode == tf.estimator.ModeKeys.PREDICT:
return tf.estimator.EstimatorSpec(
mode=mode,
predictions=predictions_dict,
export_outputs={
tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY:
tf.estimator.export.RegressionOutput(predictions)
})
loss = tf.compat.v1.losses.mean_squared_error(predictions, labels)
train_op = tf.compat.v1.assign_add(tf.compat.v1.train.get_global_step(), 1)
eval_metric_ops = {}
if include_metrics:
eval_metric_ops[
metric_keys.MetricKeys.LOSS_MEAN] = tf.compat.v1.metrics.mean(loss)
return tf.estimator.EstimatorSpec(
mode=mode,
loss=loss,
train_op=train_op,
predictions=predictions_dict,
eval_metric_ops=eval_metric_ops)
def train_input_fn():
"""Train input function."""
return {
'prediction': tf.constant([[1.0], [2.0], [3.0], [4.0]]),
}, tf.constant([[1.0], [2.0], [3.0], [4.0]]),
feature_spec = {'prediction': tf.io.FixedLenFeature([1], dtype=tf.float32)}
eval_feature_spec = {
'prediction':
tf.io.FixedLenFeature([1], dtype=tf.float32),
'label':
tf.io.FixedLenFeature([1], dtype=tf.float32),
'fixed_float':
tf.io.FixedLenFeature([1], dtype=tf.float32, default_value=0.0),
'fixed_string':
tf.io.FixedLenFeature([1], dtype=tf.string, default_value=''),
'fixed_int':
tf.io.FixedLenFeature([1], dtype=tf.int64, default_value=0),
'var_float':
tf.io.VarLenFeature(dtype=tf.float32),
'var_string':
tf.io.VarLenFeature(dtype=tf.string),
'var_int':
tf.io.VarLenFeature(dtype=tf.int64),
}
estimator = tf.estimator.Estimator(model_fn=model_fn)
estimator.train(input_fn=train_input_fn, steps=1)
return util.export_model_and_eval_model(
estimator=estimator,
serving_input_receiver_fn=(
tf.estimator.export.build_parsing_serving_input_receiver_fn(
feature_spec)),
eval_input_receiver_fn=export.build_parsing_eval_input_receiver_fn(
eval_feature_spec, label_key='label'),
export_path=export_path,
eval_export_path=eval_export_path)
| en | 0.743686 | # 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 # # 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. Exports a simple "fixed prediction" estimator using tf.Learn. This model always predicts the value of the "prediction" feature. The eval_input_receiver_fn also parses the "fixed_float", "fixed_string", "fixed_int", and "var_float", "var_string", "var_int" features. Exports a simple fixed prediction estimator that parses extra fields. Model function for custom estimator. Train input function. | 2.194956 | 2 |
C2Server/app/setting.py | Master-cai/C2 | 2 | 6628032 | <filename>C2Server/app/setting.py
import os
BASE_DIR = os.path.dirname(os.path.dirname((os.path.abspath(__file__))))
TEMPLATE_FOLDER = os.path.join(BASE_DIR, 'templates')
class Config:
DEBUG = False
TESTING = False
SECRET_KEY = '<KEY>'
SQLALCHEMY_TRACK_MODIFICATIONS = False
def get_db_uri(dbconfig):
engine = dbconfig.get('ENGINE') or 'mysql'
driver = dbconfig.get('DRIVER') or 'pymysql'
user = dbconfig.get('USER') or 'root'
password = dbconfig.get('PASSWORD') or '<PASSWORD>'
host = dbconfig.get('HOST') or 'localhost'
port = dbconfig.get('PORT') or '3306'
name = dbconfig.get('NAME') or 'myWX'
return "{}+{}://{}:{}@{}:{}/{}".format(engine, driver, user, password, host, port, name)
class DevelopConfig(Config):
DEBUG = True
DATABASE = {
"ENGINE": "mysql",
"DRIVER": "pymysql",
"USER": "root",
"PASSWORD": "<PASSWORD>",
"HOST": "localhost",
"PORT": "3306",
"NAME": "myWX"
}
SQLALCHEMY_DATABASE_URI = get_db_uri(DATABASE)
class TestingConfig(Config):
TESTING = True
DATABASE = {
"ENGINE": "mysql",
"DRIVER": "pymysql",
"USER": "root",
"PASSWORD": "<PASSWORD>",
"HOST": "localhost",
"PORT": "3306",
"NAME": "myWX"
}
SQLALCHEMY_DATABASE_URI = get_db_uri(DATABASE)
class StagingConfig(Config):
DATABASE = {
"ENGINE": "mysql",
"DRIVER": "pymysql",
"USER": "root",
"PASSWORD": "<PASSWORD>",
"HOST": "localhost",
"PORT": "3306",
"NAME": "myWX"
}
SQLALCHEMY_DATABASE_URI = get_db_uri(DATABASE)
class ProductConfig(Config):
DATABASE = {
"ENGINE": "mysql",
"DRIVER": "pymysql",
"USER": "root",
"PASSWORD": "<PASSWORD>",
"HOST": "localhost",
"PORT": "3306",
"NAME": "myWX"
}
SQLALCHEMY_DATABASE_URI = get_db_uri(DATABASE)
envs = {
'develop': DevelopConfig,
'testing': TestingConfig,
'staging': StagingConfig,
'product': ProductConfig
}
| <filename>C2Server/app/setting.py
import os
BASE_DIR = os.path.dirname(os.path.dirname((os.path.abspath(__file__))))
TEMPLATE_FOLDER = os.path.join(BASE_DIR, 'templates')
class Config:
DEBUG = False
TESTING = False
SECRET_KEY = '<KEY>'
SQLALCHEMY_TRACK_MODIFICATIONS = False
def get_db_uri(dbconfig):
engine = dbconfig.get('ENGINE') or 'mysql'
driver = dbconfig.get('DRIVER') or 'pymysql'
user = dbconfig.get('USER') or 'root'
password = dbconfig.get('PASSWORD') or '<PASSWORD>'
host = dbconfig.get('HOST') or 'localhost'
port = dbconfig.get('PORT') or '3306'
name = dbconfig.get('NAME') or 'myWX'
return "{}+{}://{}:{}@{}:{}/{}".format(engine, driver, user, password, host, port, name)
class DevelopConfig(Config):
DEBUG = True
DATABASE = {
"ENGINE": "mysql",
"DRIVER": "pymysql",
"USER": "root",
"PASSWORD": "<PASSWORD>",
"HOST": "localhost",
"PORT": "3306",
"NAME": "myWX"
}
SQLALCHEMY_DATABASE_URI = get_db_uri(DATABASE)
class TestingConfig(Config):
TESTING = True
DATABASE = {
"ENGINE": "mysql",
"DRIVER": "pymysql",
"USER": "root",
"PASSWORD": "<PASSWORD>",
"HOST": "localhost",
"PORT": "3306",
"NAME": "myWX"
}
SQLALCHEMY_DATABASE_URI = get_db_uri(DATABASE)
class StagingConfig(Config):
DATABASE = {
"ENGINE": "mysql",
"DRIVER": "pymysql",
"USER": "root",
"PASSWORD": "<PASSWORD>",
"HOST": "localhost",
"PORT": "3306",
"NAME": "myWX"
}
SQLALCHEMY_DATABASE_URI = get_db_uri(DATABASE)
class ProductConfig(Config):
DATABASE = {
"ENGINE": "mysql",
"DRIVER": "pymysql",
"USER": "root",
"PASSWORD": "<PASSWORD>",
"HOST": "localhost",
"PORT": "3306",
"NAME": "myWX"
}
SQLALCHEMY_DATABASE_URI = get_db_uri(DATABASE)
envs = {
'develop': DevelopConfig,
'testing': TestingConfig,
'staging': StagingConfig,
'product': ProductConfig
}
| none | 1 | 2.290018 | 2 | |
tests/intensive/collections_tests.py | Bukkster/fiftyone | 3 | 6628033 | """
Sample collections tests.
All of these tests are designed to be run manually via::
pytest tests/intensive/collections_tests.py -s -k test_<name>
| Copyright 2017-2022, Voxel51, Inc.
| `voxel51.com <https://voxel51.com/>`_
|
"""
import random
import unittest
import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F
_ANIMALS = [
"bear",
"bird",
"cat",
"cow",
"dog",
"elephant",
"giraffe",
"horse",
"sheep",
"zebra",
]
def test_set_values():
dataset = foz.load_zoo_dataset("quickstart").clone()
with fo.ProgressBar() as pb:
for sample in pb(dataset):
sample["animal"] = fo.Classification(label=random.choice(_ANIMALS))
sample.save()
# Test simple fields
path = "animal.label"
path_upper = path + "_upper"
path_check = path + "_check"
values = dataset.values(path)
print(dataset.count_values(path))
values_upper = _to_upper(values)
dataset.set_values(path_upper, values_upper)
print(dataset.count_values(path_upper))
view = dataset.set_field(
path_check, F("label").upper() == F("label_upper")
)
print(view.count_values(path_check))
# Test array fields
path = "predictions.detections.label"
path_upper = path + "_upper"
path_check = path + "_check"
values = dataset.values(path)
print(dataset.count_values(path))
values_upper = _to_upper(values)
dataset.set_values(path_upper, values_upper)
print(dataset.count_values(path_upper))
view = dataset.set_field(
path_check, F("label").upper() == F("label_upper")
)
print(view.count_values(path_check))
def test_set_values_frames():
dataset = foz.load_zoo_dataset("quickstart-video").clone()
with fo.ProgressBar() as pb:
for sample in pb(dataset):
for frame in sample.frames.values():
frame["animal"] = fo.Classification(
label=random.choice(_ANIMALS)
)
sample.save()
# Test simple fields
path = "frames.animal.label"
path_upper = path + "_upper"
path_check = path + "_check"
values = dataset.values(path)
print(dataset.count_values(path))
values_upper = _to_upper(values)
dataset.set_values(path_upper, values_upper)
print(dataset.count_values(path_upper))
view = dataset.set_field(
path_check, F("label").upper() == F("label_upper")
)
print(view.count_values(path_check))
# Test array fields
path = "frames.detections.detections.label"
path_upper = path + "_upper"
path_check = path + "_check"
values = dataset.values(path)
print(dataset.count_values(path))
values_upper = _to_upper(values)
dataset.set_values(path_upper, values_upper)
print(dataset.count_values(path_upper))
view = dataset.set_field(
path_check, F("label").upper() == F("label_upper")
)
print(view.count_values(path_check))
def test_tag_samples():
dataset = foz.load_zoo_dataset("imagenet-sample").clone()
view = dataset.take(100)
view.tag_samples("test")
print(dataset.count_sample_tags())
view.untag_samples("test")
print(dataset.count_sample_tags())
def test_tag_classification():
dataset = foz.load_zoo_dataset("imagenet-sample").clone()
view = dataset.take(100)
view.tag_labels("test", "ground_truth")
print(dataset.count_label_tags("ground_truth"))
view.untag_labels("test", "ground_truth")
print(dataset.count_label_tags("ground_truth"))
def test_tag_detections():
dataset = foz.load_zoo_dataset("quickstart").clone()
print(dataset.count_label_tags("predictions"))
view = dataset.filter_labels("predictions", F("confidence") > 0.99)
view.tag_labels("test", "predictions")
print(dataset.count_label_tags("predictions"))
view.untag_labels("test", "predictions")
print(dataset.count_label_tags("predictions"))
def test_tag_detections_frames():
dataset = foz.load_zoo_dataset("quickstart-video").clone()
print(dataset.count_label_tags("frames.detections"))
view = dataset.filter_labels("frames.detections", F("index") == 1)
view.tag_labels("test", "frames.detections")
print(dataset.count_label_tags("frames.detections"))
view.untag_labels("test", "frames.detections")
print(dataset.count_label_tags("frames.detections"))
def _to_upper(values):
if isinstance(values, list):
return [_to_upper(v) for v in values]
return values.upper()
if __name__ == "__main__":
fo.config.show_progress_bars = True
unittest.main(verbosity=2)
| """
Sample collections tests.
All of these tests are designed to be run manually via::
pytest tests/intensive/collections_tests.py -s -k test_<name>
| Copyright 2017-2022, Voxel51, Inc.
| `voxel51.com <https://voxel51.com/>`_
|
"""
import random
import unittest
import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F
_ANIMALS = [
"bear",
"bird",
"cat",
"cow",
"dog",
"elephant",
"giraffe",
"horse",
"sheep",
"zebra",
]
def test_set_values():
dataset = foz.load_zoo_dataset("quickstart").clone()
with fo.ProgressBar() as pb:
for sample in pb(dataset):
sample["animal"] = fo.Classification(label=random.choice(_ANIMALS))
sample.save()
# Test simple fields
path = "animal.label"
path_upper = path + "_upper"
path_check = path + "_check"
values = dataset.values(path)
print(dataset.count_values(path))
values_upper = _to_upper(values)
dataset.set_values(path_upper, values_upper)
print(dataset.count_values(path_upper))
view = dataset.set_field(
path_check, F("label").upper() == F("label_upper")
)
print(view.count_values(path_check))
# Test array fields
path = "predictions.detections.label"
path_upper = path + "_upper"
path_check = path + "_check"
values = dataset.values(path)
print(dataset.count_values(path))
values_upper = _to_upper(values)
dataset.set_values(path_upper, values_upper)
print(dataset.count_values(path_upper))
view = dataset.set_field(
path_check, F("label").upper() == F("label_upper")
)
print(view.count_values(path_check))
def test_set_values_frames():
dataset = foz.load_zoo_dataset("quickstart-video").clone()
with fo.ProgressBar() as pb:
for sample in pb(dataset):
for frame in sample.frames.values():
frame["animal"] = fo.Classification(
label=random.choice(_ANIMALS)
)
sample.save()
# Test simple fields
path = "frames.animal.label"
path_upper = path + "_upper"
path_check = path + "_check"
values = dataset.values(path)
print(dataset.count_values(path))
values_upper = _to_upper(values)
dataset.set_values(path_upper, values_upper)
print(dataset.count_values(path_upper))
view = dataset.set_field(
path_check, F("label").upper() == F("label_upper")
)
print(view.count_values(path_check))
# Test array fields
path = "frames.detections.detections.label"
path_upper = path + "_upper"
path_check = path + "_check"
values = dataset.values(path)
print(dataset.count_values(path))
values_upper = _to_upper(values)
dataset.set_values(path_upper, values_upper)
print(dataset.count_values(path_upper))
view = dataset.set_field(
path_check, F("label").upper() == F("label_upper")
)
print(view.count_values(path_check))
def test_tag_samples():
dataset = foz.load_zoo_dataset("imagenet-sample").clone()
view = dataset.take(100)
view.tag_samples("test")
print(dataset.count_sample_tags())
view.untag_samples("test")
print(dataset.count_sample_tags())
def test_tag_classification():
dataset = foz.load_zoo_dataset("imagenet-sample").clone()
view = dataset.take(100)
view.tag_labels("test", "ground_truth")
print(dataset.count_label_tags("ground_truth"))
view.untag_labels("test", "ground_truth")
print(dataset.count_label_tags("ground_truth"))
def test_tag_detections():
dataset = foz.load_zoo_dataset("quickstart").clone()
print(dataset.count_label_tags("predictions"))
view = dataset.filter_labels("predictions", F("confidence") > 0.99)
view.tag_labels("test", "predictions")
print(dataset.count_label_tags("predictions"))
view.untag_labels("test", "predictions")
print(dataset.count_label_tags("predictions"))
def test_tag_detections_frames():
dataset = foz.load_zoo_dataset("quickstart-video").clone()
print(dataset.count_label_tags("frames.detections"))
view = dataset.filter_labels("frames.detections", F("index") == 1)
view.tag_labels("test", "frames.detections")
print(dataset.count_label_tags("frames.detections"))
view.untag_labels("test", "frames.detections")
print(dataset.count_label_tags("frames.detections"))
def _to_upper(values):
if isinstance(values, list):
return [_to_upper(v) for v in values]
return values.upper()
if __name__ == "__main__":
fo.config.show_progress_bars = True
unittest.main(verbosity=2)
| en | 0.618808 | Sample collections tests. All of these tests are designed to be run manually via:: pytest tests/intensive/collections_tests.py -s -k test_<name> | Copyright 2017-2022, Voxel51, Inc. | `voxel51.com <https://voxel51.com/>`_ | # Test simple fields # Test array fields # Test simple fields # Test array fields | 2.771027 | 3 |
autogp/util/util.py | Alwaysproblem/AutoGP | 1 | 6628034 | <gh_stars>1-10
from __future__ import division
import copy
import tensorflow as tf
def tri_vec_shape(N):
return [N * (N + 1) // 2]
def init_list(init, dims):
def empty_list(dims):
if not dims:
return None
else:
return [copy.deepcopy(empty_list(dims[1:])) for i in range(dims[0])]
def fill_list(dims, l):
if len(dims) == 1:
for i in range(dims[0]):
if callable(init):
l[i] = init()
else:
l[i] = init
else:
for i in range(dims[0]):
fill_list(dims[1:], l[i])
l = empty_list(dims)
fill_list(dims, l)
return l
def ceil_divide(dividend, divisor):
return (dividend + divisor - 1) / divisor
def log_cholesky_det(chol):
return 2 * tf.reduce_sum(tf.log(tf.diag_part(chol)))
def diag_mul(mat1, mat2):
return tf.reduce_sum(mat1 * tf.transpose(mat2), 1)
def logsumexp(vals, dim=None):
m = tf.reduce_max(vals, dim)
if dim is None:
return m + tf.log(tf.reduce_sum(tf.exp(vals - m), dim))
else:
return m + tf.log(tf.reduce_sum(tf.exp(vals - tf.expand_dims(m, dim)), dim))
def mat_square(mat):
return tf.matmul(mat, tf.transpose(mat))
def get_flags():
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_integer('batch_size', 100, 'Batch size. '
'Must divide evenly into the dataset sizes.')
flags.DEFINE_float('learning_rate', 0.001, 'Initial learning rate.')
flags.DEFINE_integer('n_epochs', 10000, 'Number of passes through the data')
flags.DEFINE_integer('n_inducing', 240, 'Number of inducing points')
flags.DEFINE_integer('display_step', 500, 'Display progress every FLAGS.display_step iterations')
flags.DEFINE_integer('mc_train', 100, 'Number of Monte Carlo samples used to compute stochastic gradients')
flags.DEFINE_integer('mc_test', 100, 'Number of Monte Carlo samples for predictions')
flags.DEFINE_string('optimizer', "adagrad", 'Optimizer')
flags.DEFINE_boolean('is_ard', True, 'Using ARD kernel or isotropic')
flags.DEFINE_float('lengthscale', 10, 'Initial lengthscale')
flags.DEFINE_integer('var_steps', 50, 'Number of times spent optimizing the variational objective.')
flags.DEFINE_integer('loocv_steps', 50, 'Number of times spent optimizing the LOOCV objective.')
flags.DEFINE_float('opt_growth', 0.0, 'Percentage to grow the number of each optimizations.')
flags.DEFINE_integer('num_components', 1, 'Number of mixture components on posterior')
flags.DEFINE_string('kernel', 'rbf', 'kernel')
flags.DEFINE_string('device_name', 'gpu0', 'Device name')
flags.DEFINE_integer('kernel_degree', 0, 'Degree of arccosine kernel')
flags.DEFINE_integer('kernel_depth', 1, 'Depth of arcosine kernel')
return FLAGS
| from __future__ import division
import copy
import tensorflow as tf
def tri_vec_shape(N):
return [N * (N + 1) // 2]
def init_list(init, dims):
def empty_list(dims):
if not dims:
return None
else:
return [copy.deepcopy(empty_list(dims[1:])) for i in range(dims[0])]
def fill_list(dims, l):
if len(dims) == 1:
for i in range(dims[0]):
if callable(init):
l[i] = init()
else:
l[i] = init
else:
for i in range(dims[0]):
fill_list(dims[1:], l[i])
l = empty_list(dims)
fill_list(dims, l)
return l
def ceil_divide(dividend, divisor):
return (dividend + divisor - 1) / divisor
def log_cholesky_det(chol):
return 2 * tf.reduce_sum(tf.log(tf.diag_part(chol)))
def diag_mul(mat1, mat2):
return tf.reduce_sum(mat1 * tf.transpose(mat2), 1)
def logsumexp(vals, dim=None):
m = tf.reduce_max(vals, dim)
if dim is None:
return m + tf.log(tf.reduce_sum(tf.exp(vals - m), dim))
else:
return m + tf.log(tf.reduce_sum(tf.exp(vals - tf.expand_dims(m, dim)), dim))
def mat_square(mat):
return tf.matmul(mat, tf.transpose(mat))
def get_flags():
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_integer('batch_size', 100, 'Batch size. '
'Must divide evenly into the dataset sizes.')
flags.DEFINE_float('learning_rate', 0.001, 'Initial learning rate.')
flags.DEFINE_integer('n_epochs', 10000, 'Number of passes through the data')
flags.DEFINE_integer('n_inducing', 240, 'Number of inducing points')
flags.DEFINE_integer('display_step', 500, 'Display progress every FLAGS.display_step iterations')
flags.DEFINE_integer('mc_train', 100, 'Number of Monte Carlo samples used to compute stochastic gradients')
flags.DEFINE_integer('mc_test', 100, 'Number of Monte Carlo samples for predictions')
flags.DEFINE_string('optimizer', "adagrad", 'Optimizer')
flags.DEFINE_boolean('is_ard', True, 'Using ARD kernel or isotropic')
flags.DEFINE_float('lengthscale', 10, 'Initial lengthscale')
flags.DEFINE_integer('var_steps', 50, 'Number of times spent optimizing the variational objective.')
flags.DEFINE_integer('loocv_steps', 50, 'Number of times spent optimizing the LOOCV objective.')
flags.DEFINE_float('opt_growth', 0.0, 'Percentage to grow the number of each optimizations.')
flags.DEFINE_integer('num_components', 1, 'Number of mixture components on posterior')
flags.DEFINE_string('kernel', 'rbf', 'kernel')
flags.DEFINE_string('device_name', 'gpu0', 'Device name')
flags.DEFINE_integer('kernel_degree', 0, 'Degree of arccosine kernel')
flags.DEFINE_integer('kernel_depth', 1, 'Depth of arcosine kernel')
return FLAGS | none | 1 | 2.312126 | 2 | |
tests/test_github_search.py | drusk/osstrends | 0 | 6628035 | <gh_stars>0
# Copyright (C) 2013 <NAME>
#
# 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.
__author__ = "<NAME> <<EMAIL>>"
import json
import unittest
from hamcrest import assert_that, equal_to, has_length, contains_inanyorder, none
import httpretty
from mock import Mock
from osstrends.github import GitHubSearcher, RateLimitException
from tests import testutil
class GitHubSearcherTest(unittest.TestCase):
def setUp(self):
self.searcher = GitHubSearcher()
@httpretty.activate
def test_search_users_by_location_in_single_call(self):
self.mock_uri("https://api.github.com/search/users",
testutil.read("victoria_search_page1.json"))
users = self.searcher.search_users_by_location("victoria")
assert_that(users, has_length(100))
@httpretty.activate
def test_search_repos_by_user(self):
self.mock_uri("https://api.github.com/users/drusk/repos",
testutil.read("user_repos.json"))
repos = self.searcher.search_repos_by_user("drusk")
assert_that(repos, has_length(16))
assert_that(repos, contains_inanyorder(
"MOP",
"scratch",
"fishcounter",
"config-files",
"WeightRep",
"drusk.github.com",
"algorithms",
"cadcVOFS",
"query-gateway",
"query-composer",
"pml",
"pml-applications",
"uvic-transcript-parser",
"archive",
"investment-tracker",
"drusk-gwt-oracle-example"
))
@httpretty.activate
def test_resolve_forked_repo_to_source(self):
self.mock_uri("https://api.github.com/repos/drusk/MOP",
testutil.read("repo_is_fork.json"))
owner, repo_name = self.searcher.resolve_repo_to_source("drusk", "MOP")
assert_that(owner, equal_to("ijiraq"))
assert_that(repo_name, equal_to("MOP"))
@httpretty.activate
def test_resolve_source_repo_to_source(self):
self.mock_uri("https://api.github.com/repos/drusk/algorithms",
testutil.read("repo_is_source.json"))
owner, repo_name = self.searcher.resolve_repo_to_source("drusk", "algorithms")
assert_that(owner, equal_to("drusk"))
assert_that(repo_name, equal_to("algorithms"))
@httpretty.activate
def test_get_repo_language_stats(self):
self.mock_uri("https://api.github.com/repos/drusk/algorithms/languages",
testutil.read("language_stats_algorithms.json"))
language_stats = self.searcher.get_repo_language_stats("drusk", "algorithms")
assert_that(language_stats, equal_to(
{
"Java": 150390,
"Python": 4713
}
))
@httpretty.activate
def test_get_user_language_stats(self):
self.searcher.search_repos_by_user = Mock(return_value=["algorithms", "pml"])
self.mock_uri("https://api.github.com/repos/drusk/algorithms/languages",
testutil.read("language_stats_algorithms.json"))
self.mock_uri("https://api.github.com/repos/drusk/pml/languages",
testutil.read("language_stats_pml.json"))
language_stats = self.searcher.get_user_language_stats("drusk")
assert_that(language_stats, equal_to(
{
"Java": 150390,
"Python": 273059,
"Shell": 5407
}
))
@httpretty.activate
def test_search_user(self):
self.mock_uri("https://api.github.com/users/drusk",
testutil.read("user_drusk.json"))
user = self.searcher.search_user("drusk")
assert_that(user["login"], equal_to("drusk"))
assert_that(user["name"], equal_to("<NAME>"))
assert_that(user["company"], none())
assert_that(user["location"], equal_to("Victoria, BC"))
assert_that(user["hireable"], equal_to(False))
assert_that(user["hireable"], equal_to(False))
assert_that(user["public_repos"], equal_to(16))
assert_that(user["followers"], equal_to(1))
assert_that(user["following"], equal_to(0))
@httpretty.activate
def test_rate_limit_exception_raised(self):
response = json.dumps({
"message": "API rate limit exceeded. See "
"http://developer.github.com/v3/#rate-limiting "
"for details."
})
self.mock_uri("https://api.github.com/users/drusk", response,
status=403, headers={"X-RateLimit-Remaining": 0,
"X-RateLimit-Reset": 1372700873})
try:
self.searcher.search_user("drusk")
self.fail("Should have raised RateLimitException.")
except RateLimitException as exception:
assert_that(exception.reset_time, equal_to(1372700873))
def mock_uri(self, uri, response_data, status=200, headers=None):
if headers is None:
headers = {"X-RateLimit-Remaining": 100,
"X-RateLimit-Reset": 123456789}
httpretty.register_uri(httpretty.GET,
uri,
responses=[
httpretty.Response(
body=response_data,
status=status,
adding_headers=headers
)
])
if __name__ == '__main__':
unittest.main()
| # Copyright (C) 2013 <NAME>
#
# 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.
__author__ = "<NAME> <<EMAIL>>"
import json
import unittest
from hamcrest import assert_that, equal_to, has_length, contains_inanyorder, none
import httpretty
from mock import Mock
from osstrends.github import GitHubSearcher, RateLimitException
from tests import testutil
class GitHubSearcherTest(unittest.TestCase):
def setUp(self):
self.searcher = GitHubSearcher()
@httpretty.activate
def test_search_users_by_location_in_single_call(self):
self.mock_uri("https://api.github.com/search/users",
testutil.read("victoria_search_page1.json"))
users = self.searcher.search_users_by_location("victoria")
assert_that(users, has_length(100))
@httpretty.activate
def test_search_repos_by_user(self):
self.mock_uri("https://api.github.com/users/drusk/repos",
testutil.read("user_repos.json"))
repos = self.searcher.search_repos_by_user("drusk")
assert_that(repos, has_length(16))
assert_that(repos, contains_inanyorder(
"MOP",
"scratch",
"fishcounter",
"config-files",
"WeightRep",
"drusk.github.com",
"algorithms",
"cadcVOFS",
"query-gateway",
"query-composer",
"pml",
"pml-applications",
"uvic-transcript-parser",
"archive",
"investment-tracker",
"drusk-gwt-oracle-example"
))
@httpretty.activate
def test_resolve_forked_repo_to_source(self):
self.mock_uri("https://api.github.com/repos/drusk/MOP",
testutil.read("repo_is_fork.json"))
owner, repo_name = self.searcher.resolve_repo_to_source("drusk", "MOP")
assert_that(owner, equal_to("ijiraq"))
assert_that(repo_name, equal_to("MOP"))
@httpretty.activate
def test_resolve_source_repo_to_source(self):
self.mock_uri("https://api.github.com/repos/drusk/algorithms",
testutil.read("repo_is_source.json"))
owner, repo_name = self.searcher.resolve_repo_to_source("drusk", "algorithms")
assert_that(owner, equal_to("drusk"))
assert_that(repo_name, equal_to("algorithms"))
@httpretty.activate
def test_get_repo_language_stats(self):
self.mock_uri("https://api.github.com/repos/drusk/algorithms/languages",
testutil.read("language_stats_algorithms.json"))
language_stats = self.searcher.get_repo_language_stats("drusk", "algorithms")
assert_that(language_stats, equal_to(
{
"Java": 150390,
"Python": 4713
}
))
@httpretty.activate
def test_get_user_language_stats(self):
self.searcher.search_repos_by_user = Mock(return_value=["algorithms", "pml"])
self.mock_uri("https://api.github.com/repos/drusk/algorithms/languages",
testutil.read("language_stats_algorithms.json"))
self.mock_uri("https://api.github.com/repos/drusk/pml/languages",
testutil.read("language_stats_pml.json"))
language_stats = self.searcher.get_user_language_stats("drusk")
assert_that(language_stats, equal_to(
{
"Java": 150390,
"Python": 273059,
"Shell": 5407
}
))
@httpretty.activate
def test_search_user(self):
self.mock_uri("https://api.github.com/users/drusk",
testutil.read("user_drusk.json"))
user = self.searcher.search_user("drusk")
assert_that(user["login"], equal_to("drusk"))
assert_that(user["name"], equal_to("<NAME>"))
assert_that(user["company"], none())
assert_that(user["location"], equal_to("Victoria, BC"))
assert_that(user["hireable"], equal_to(False))
assert_that(user["hireable"], equal_to(False))
assert_that(user["public_repos"], equal_to(16))
assert_that(user["followers"], equal_to(1))
assert_that(user["following"], equal_to(0))
@httpretty.activate
def test_rate_limit_exception_raised(self):
response = json.dumps({
"message": "API rate limit exceeded. See "
"http://developer.github.com/v3/#rate-limiting "
"for details."
})
self.mock_uri("https://api.github.com/users/drusk", response,
status=403, headers={"X-RateLimit-Remaining": 0,
"X-RateLimit-Reset": 1372700873})
try:
self.searcher.search_user("drusk")
self.fail("Should have raised RateLimitException.")
except RateLimitException as exception:
assert_that(exception.reset_time, equal_to(1372700873))
def mock_uri(self, uri, response_data, status=200, headers=None):
if headers is None:
headers = {"X-RateLimit-Remaining": 100,
"X-RateLimit-Reset": 123456789}
httpretty.register_uri(httpretty.GET,
uri,
responses=[
httpretty.Response(
body=response_data,
status=status,
adding_headers=headers
)
])
if __name__ == '__main__':
unittest.main() | en | 0.768919 | # Copyright (C) 2013 <NAME> # # 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. #rate-limiting " | 1.905173 | 2 |
src/huntsman/pocs/archive/archiver.py | JAAlvarado-Montes/huntsman-pocs | 0 | 6628036 | """ Code to facilitate delayed archiving of FITS files in the images directory """
import os
import time
import queue
import atexit
import shutil
from contextlib import suppress
from threading import Thread
from astropy import units as u
from panoptes.utils import get_quantity_value
from panoptes.utils.time import current_time
from panoptes.pocs.base import PanBase
VALID_EXTENSIONS = (".fits", ".fits.fz")
class Archiver(PanBase):
""" Class to watch the images directory for new files and move them to the archive directory
after enough time has passed.
"""
_valid_extensions = VALID_EXTENSIONS
def __init__(self, images_directory=None, archive_directory=None, delay_interval=None,
sleep_interval=None, status_interval=60, *args, **kwargs):
"""
Args:
images_directory (str): The images directory to archive. If None (default), uses
the directories.images config entry.
archive_directory (str): The archive directory. If None (default), uses
the directories.archive config entry.
delay_interval (u.Quantity): The minimum amount of time a file must spend in the
archive queue before it is archived. If None (default), uses the
archiver.delay_time config entry.
sleep_interval (u.Quantity): The amout of time to sleep in between checking for new
files to archive. Ideally this should be longer than delay_interval. If None
(default), uses the archiver.sleep_interval confing entry.
status_interval (float, optional): Sleep for this long between status reports. Default
60s.
*args, **kwargs: Parsed to PanBase initialiser.
"""
super().__init__(*args, **kwargs)
if images_directory is None:
images_directory = self.get_config("directories.images")
self.images_directory = str(images_directory)
if archive_directory is None:
archive_directory = self.get_config("directories.archive")
self.archive_directory = str(archive_directory)
self.logger.debug(f"Archive directory: {self.archive_directory}")
if delay_interval is None:
delay_interval = self.get_config("archiver.delay_interval")
self.delay_interval = get_quantity_value(delay_interval, u.minute) * u.minute
if sleep_interval is None:
sleep_interval = self.get_config("archiver.sleep_interval")
self.sleep_interval = get_quantity_value(sleep_interval, u.minute) * u.minute
self._status_interval = get_quantity_value(status_interval, u.second)
self._n_archived = 0
self._stop = False
self._archive_queue = queue.Queue()
self._status_thread = Thread(target=self._async_monitor_status)
self._watch_thread = Thread(target=self._async_watch_directory)
self._archive_thread = Thread(target=self._async_archive_files)
self._threads = [self._status_thread, self._watch_thread, self._archive_thread]
atexit.register(self.stop) # This gets called when python is quit
@property
def is_running(self):
return self.status["is_running"]
@property
def status(self):
""" Return a status dictionary.
Returns:
dict: The status dictionary.
"""
status = {"is_running": all([t.is_alive() for t in self._threads]),
"status_thread": self._status_thread.is_alive(),
"watch_thread": self._watch_thread.is_alive(),
"archive_thread": self._status_thread.is_alive(),
"queued": self._archive_queue.qsize(),
"archived": self._n_archived}
return status
def start(self):
""" Start archiving. """
self.logger.info("Starting archiving.")
self._stop = False
for thread in self._threads:
thread.start()
def stop(self, blocking=True):
""" Stop archiving.
Args:
blocking (bool, optional): If True (default), blocks until all threads have joined.
"""
self.logger.info("Stopping archiving.")
self._stop = True
if blocking:
for thread in self._threads:
with suppress(RuntimeError):
thread.join()
def _async_monitor_status(self):
""" Report the status on a regular interval. """
self.logger.debug("Starting status thread.")
while True:
if self._stop:
self.logger.debug("Stopping status thread.")
break
# Get the current status
status = self.status
self.logger.debug(f"Archiver status: {status}")
# Sleep before reporting status again
time.sleep(self._status_interval)
def _async_watch_directory(self):
""" Watch the images directory and add all valid files to the archive queue. """
self.logger.debug("Starting watch thread.")
while True:
if self._stop:
self.logger.debug("Stopping watch thread.")
break
# Loop over filenames and add them to the queue
# Duplicates are taken care of later on
for filename in self._get_filenames_to_archive():
self._archive_queue.put([current_time(), filename])
# Sleep before checking again
time.sleep(self.sleep_interval.to_value(u.second))
def _async_archive_files(self, sleep=10):
""" Archive files that have been in the queue longer than self.delay_interval.
Args:
sleep (float, optional): Sleep for this long while waiting for self.delay_interval to
expire. Default: 10s.
"""
while True:
if self._stop and self._archive_queue.empty():
self.logger.debug("Stopping archive thread.")
break
# Get the oldest file from the queue
try:
track_time, filename = self._archive_queue.get(block=True, timeout=sleep)
except queue.Empty:
continue
# Archive file when it is old enough
while current_time() - track_time < self.delay_interval:
time.sleep(sleep)
with suppress(FileNotFoundError):
self._archive_file(filename)
self._n_archived += 1
# Tell the queue we are done with this file
self._archive_queue.task_done()
def _get_filenames_to_archive(self):
""" Get valid filenames in the images directory to archive.
Returns:
list: The list of filenames to archive.
"""
filenames = []
# Get all the matching filenames in the images directory
for path, _, files in os.walk(self.images_directory):
for name in files:
if any([name.endswith(ext) for ext in self._valid_extensions]):
filenames.append(os.path.join(path, name))
return filenames
def _get_archive_filename(self, filename):
""" Get the archive filename from the original filename.
Args:
filename (str): The filename string.
Returns:
str: The archived file name.
"""
relpath = os.path.relpath(filename, self.images_directory)
return os.path.join(self.archive_directory, relpath)
def _archive_file(self, filename):
""" Archive the file.
Args:
filename (str): The filename string.
"""
if not os.path.exists(filename): # May have already been archived or deleted
self.logger.warning(f"Tried to archive {filename} but it does not exist.")
raise FileNotFoundError
# Get the archived filename
archive_filename = self._get_archive_filename(filename)
# Make sure the archive directory exists
os.makedirs(os.path.dirname(archive_filename), exist_ok=True)
# Move the file to the archive directory
self.logger.debug(f"Moving {filename} to {archive_filename}.")
shutil.move(filename, archive_filename)
| """ Code to facilitate delayed archiving of FITS files in the images directory """
import os
import time
import queue
import atexit
import shutil
from contextlib import suppress
from threading import Thread
from astropy import units as u
from panoptes.utils import get_quantity_value
from panoptes.utils.time import current_time
from panoptes.pocs.base import PanBase
VALID_EXTENSIONS = (".fits", ".fits.fz")
class Archiver(PanBase):
""" Class to watch the images directory for new files and move them to the archive directory
after enough time has passed.
"""
_valid_extensions = VALID_EXTENSIONS
def __init__(self, images_directory=None, archive_directory=None, delay_interval=None,
sleep_interval=None, status_interval=60, *args, **kwargs):
"""
Args:
images_directory (str): The images directory to archive. If None (default), uses
the directories.images config entry.
archive_directory (str): The archive directory. If None (default), uses
the directories.archive config entry.
delay_interval (u.Quantity): The minimum amount of time a file must spend in the
archive queue before it is archived. If None (default), uses the
archiver.delay_time config entry.
sleep_interval (u.Quantity): The amout of time to sleep in between checking for new
files to archive. Ideally this should be longer than delay_interval. If None
(default), uses the archiver.sleep_interval confing entry.
status_interval (float, optional): Sleep for this long between status reports. Default
60s.
*args, **kwargs: Parsed to PanBase initialiser.
"""
super().__init__(*args, **kwargs)
if images_directory is None:
images_directory = self.get_config("directories.images")
self.images_directory = str(images_directory)
if archive_directory is None:
archive_directory = self.get_config("directories.archive")
self.archive_directory = str(archive_directory)
self.logger.debug(f"Archive directory: {self.archive_directory}")
if delay_interval is None:
delay_interval = self.get_config("archiver.delay_interval")
self.delay_interval = get_quantity_value(delay_interval, u.minute) * u.minute
if sleep_interval is None:
sleep_interval = self.get_config("archiver.sleep_interval")
self.sleep_interval = get_quantity_value(sleep_interval, u.minute) * u.minute
self._status_interval = get_quantity_value(status_interval, u.second)
self._n_archived = 0
self._stop = False
self._archive_queue = queue.Queue()
self._status_thread = Thread(target=self._async_monitor_status)
self._watch_thread = Thread(target=self._async_watch_directory)
self._archive_thread = Thread(target=self._async_archive_files)
self._threads = [self._status_thread, self._watch_thread, self._archive_thread]
atexit.register(self.stop) # This gets called when python is quit
@property
def is_running(self):
return self.status["is_running"]
@property
def status(self):
""" Return a status dictionary.
Returns:
dict: The status dictionary.
"""
status = {"is_running": all([t.is_alive() for t in self._threads]),
"status_thread": self._status_thread.is_alive(),
"watch_thread": self._watch_thread.is_alive(),
"archive_thread": self._status_thread.is_alive(),
"queued": self._archive_queue.qsize(),
"archived": self._n_archived}
return status
def start(self):
""" Start archiving. """
self.logger.info("Starting archiving.")
self._stop = False
for thread in self._threads:
thread.start()
def stop(self, blocking=True):
""" Stop archiving.
Args:
blocking (bool, optional): If True (default), blocks until all threads have joined.
"""
self.logger.info("Stopping archiving.")
self._stop = True
if blocking:
for thread in self._threads:
with suppress(RuntimeError):
thread.join()
def _async_monitor_status(self):
""" Report the status on a regular interval. """
self.logger.debug("Starting status thread.")
while True:
if self._stop:
self.logger.debug("Stopping status thread.")
break
# Get the current status
status = self.status
self.logger.debug(f"Archiver status: {status}")
# Sleep before reporting status again
time.sleep(self._status_interval)
def _async_watch_directory(self):
""" Watch the images directory and add all valid files to the archive queue. """
self.logger.debug("Starting watch thread.")
while True:
if self._stop:
self.logger.debug("Stopping watch thread.")
break
# Loop over filenames and add them to the queue
# Duplicates are taken care of later on
for filename in self._get_filenames_to_archive():
self._archive_queue.put([current_time(), filename])
# Sleep before checking again
time.sleep(self.sleep_interval.to_value(u.second))
def _async_archive_files(self, sleep=10):
""" Archive files that have been in the queue longer than self.delay_interval.
Args:
sleep (float, optional): Sleep for this long while waiting for self.delay_interval to
expire. Default: 10s.
"""
while True:
if self._stop and self._archive_queue.empty():
self.logger.debug("Stopping archive thread.")
break
# Get the oldest file from the queue
try:
track_time, filename = self._archive_queue.get(block=True, timeout=sleep)
except queue.Empty:
continue
# Archive file when it is old enough
while current_time() - track_time < self.delay_interval:
time.sleep(sleep)
with suppress(FileNotFoundError):
self._archive_file(filename)
self._n_archived += 1
# Tell the queue we are done with this file
self._archive_queue.task_done()
def _get_filenames_to_archive(self):
""" Get valid filenames in the images directory to archive.
Returns:
list: The list of filenames to archive.
"""
filenames = []
# Get all the matching filenames in the images directory
for path, _, files in os.walk(self.images_directory):
for name in files:
if any([name.endswith(ext) for ext in self._valid_extensions]):
filenames.append(os.path.join(path, name))
return filenames
def _get_archive_filename(self, filename):
""" Get the archive filename from the original filename.
Args:
filename (str): The filename string.
Returns:
str: The archived file name.
"""
relpath = os.path.relpath(filename, self.images_directory)
return os.path.join(self.archive_directory, relpath)
def _archive_file(self, filename):
""" Archive the file.
Args:
filename (str): The filename string.
"""
if not os.path.exists(filename): # May have already been archived or deleted
self.logger.warning(f"Tried to archive {filename} but it does not exist.")
raise FileNotFoundError
# Get the archived filename
archive_filename = self._get_archive_filename(filename)
# Make sure the archive directory exists
os.makedirs(os.path.dirname(archive_filename), exist_ok=True)
# Move the file to the archive directory
self.logger.debug(f"Moving {filename} to {archive_filename}.")
shutil.move(filename, archive_filename)
| en | 0.805384 | Code to facilitate delayed archiving of FITS files in the images directory Class to watch the images directory for new files and move them to the archive directory after enough time has passed. Args: images_directory (str): The images directory to archive. If None (default), uses the directories.images config entry. archive_directory (str): The archive directory. If None (default), uses the directories.archive config entry. delay_interval (u.Quantity): The minimum amount of time a file must spend in the archive queue before it is archived. If None (default), uses the archiver.delay_time config entry. sleep_interval (u.Quantity): The amout of time to sleep in between checking for new files to archive. Ideally this should be longer than delay_interval. If None (default), uses the archiver.sleep_interval confing entry. status_interval (float, optional): Sleep for this long between status reports. Default 60s. *args, **kwargs: Parsed to PanBase initialiser. # This gets called when python is quit Return a status dictionary. Returns: dict: The status dictionary. Start archiving. Stop archiving. Args: blocking (bool, optional): If True (default), blocks until all threads have joined. Report the status on a regular interval. # Get the current status # Sleep before reporting status again Watch the images directory and add all valid files to the archive queue. # Loop over filenames and add them to the queue # Duplicates are taken care of later on # Sleep before checking again Archive files that have been in the queue longer than self.delay_interval. Args: sleep (float, optional): Sleep for this long while waiting for self.delay_interval to expire. Default: 10s. # Get the oldest file from the queue # Archive file when it is old enough # Tell the queue we are done with this file Get valid filenames in the images directory to archive. Returns: list: The list of filenames to archive. # Get all the matching filenames in the images directory Get the archive filename from the original filename. Args: filename (str): The filename string. Returns: str: The archived file name. Archive the file. Args: filename (str): The filename string. # May have already been archived or deleted # Get the archived filename # Make sure the archive directory exists # Move the file to the archive directory | 2.806269 | 3 |
CAIL2020/jesb/datagen/contract_test.py | ShenDezhou/CAIL | 71 | 6628037 | <filename>CAIL2020/jesb/datagen/contract_test.py
import os
import random
import re
import pandas
dic=[]
with open('amount_v1v2.dic', 'r', encoding='utf-8') as f:
lines = f.readlines()
dic.extend([l.strip() for l in lines])
print(len(dic))
regdic = []
for word in dic:
if '_' in word:
word = word.replace('_','[_\d]?',10)
r = re.compile(word)
else:
r = re.compile(word)
regdic.append(r)
def trigger(line):
for i in range(len(dic)):
if dic[i] in line:
return i, dic[i]
return None
def reg_trigger(line):
for i in range(len(regdic)):
if regdic[i].search(line):
return i, regdic[i], dic[i]
return None
FORMAL_DIGIT="零一二三四五六七八九十百千万亿兆"
LARGE_FORMAL_DIGIT="零壹贰叁肆伍陆柒捌玖拾佰仟萬億"
DIGIT_PAUSE=',\uFF0C'
DIGIT_SPLIT='.'
CARRY = "十百千万亿"
LARGE_CARRY = "拾佰仟萬億"
COMMON_UNIT='元'
UNIT='元角分'
math_digit="1234567890\uFF10\uFF11\uFF12\uFF13\uFF14\uFF15\uFF16\uFF17\uFF18\uFF19"
amount_len = (1, 5)
category_size = 400
chinese_dic = []
with open("chinese4049.txt",'r',encoding='utf-8') as f:
for line in f:
chinese_dic.append(line.strip())
def gen_amount(formal = 0):
len = random.randint(*amount_len)
if formal==0:
return "".join(random.sample(list(math_digit), len))
elif formal == 1:
return "".join(random.sample(list(FORMAL_DIGIT), len))
return "".join(random.sample(list(LARGE_FORMAL_DIGIT), len))
def gen_digit_amount(lenghth, comma=True, period=True):
index = 0
gen = ""
while index < lenghth:
gen += "".join(random.sample(list(math_digit), 3))
if comma:
gen += "".join(random.sample(list(DIGIT_PAUSE), 1))
index += 3
if period:
gen += "".join(random.sample(list(math_digit), 2))
return gen
def gen_with_rule(type = 0):
dice = random.random()
if dice < 0.3:
chars = random.randint(1, 3)
elif dice<0.6:
chars = random.randint(1, 6)
else:
chars = random.randint(1, 10)
index = 0
gen = ""
if type==0:
digit_type = random.randint(1, 4)
if digit_type ==0:
gen = gen_digit_amount(chars, comma=False, period=False)
elif digit_type ==1:
gen = gen_digit_amount(chars, comma=False, period=True)
elif digit_type == 2:
gen = gen_digit_amount(chars, comma=True, period=False)
else:
gen = gen_digit_amount(chars, comma=True, period=True)
else:
while index < chars:
if type==1:
gen += "".join(random.sample(list(FORMAL_DIGIT), 1))
gen += "".join(random.sample(list(CARRY), 1))
index+=2
elif type==2:
gen += "".join(random.sample(list(LARGE_FORMAL_DIGIT), 1))
gen += "".join(random.sample(list(LARGE_CARRY), 1))
index += 2
else:
if random.random() > 0.5:
gen += "".join(random.sample(list(math_digit), 3))
if random.random() > 0.1:
gen += "".join(random.sample(list(DIGIT_PAUSE), 1))
if random.random() > 0.5:
gen += "".join(random.sample(list(CARRY), 1))
else:
gen += "".join(random.sample(list(LARGE_CARRY), 1))
index += 4
else:
gen += "".join(random.sample(list(FORMAL_DIGIT), 1))
gen += "".join(random.sample(list(LARGE_FORMAL_DIGIT), 1))
index += 2
if random.random() < 0.1:
gen += "".join(random.sample(list(UNIT), 1))
elif random.random() < 0.9:
gen += COMMON_UNIT
else:
gen += " "
return gen
gen_amounts = []
gen_amounts.append('218399')
gen_amounts.append('贰拾壹万捌仟叁佰玖十九')
gen_amounts.append('31287')
gen_amounts.append('叁万壹仟贰佰捌拾柒')
gen_amounts.append('300000')
gen_amounts.append('叁拾万')
gen_amounts.append('280000')
gen_amounts.append('贰拾捌万')
gen_amounts.append('135998')
gen_amounts.append('拾叁万伍仟玖佰玖拾捌')
gen_amounts.append('75382')
gen_amounts.append('柒万伍仟叁佰捌拾贰')
gen_amounts.append('135998')
gen_amounts.append('柒万伍仟叁佰捌拾贰')
gen_amounts.append('1800000')
gen_amounts.append('壹佰捌拾万')
df = pandas.DataFrame(columns=["contract","indexes"])
# for dirpath, dnames, fnames in os.walk("txt/"):
# for file in fnames:
filename = 'testset.txt'
with open(filename, 'r', encoding='utf-8') as fr:
for line in fr:
buffer = []
buffer.append(line.strip())
# res = reg_trigger(line)
# if res:
# formald = gen_with_rule(type=random.randint(1,3))
# mathd = gen_with_rule(type=0)
#
# newline = res[1].sub(line, res[2] + formald + ("".join(random.sample(chinese_dic, random.randint(min(3, len(line)//3), len(line)//3))).replace("\n", "", 10 ** 10)) +mathd)
# buffer.append(newline.strip())
# else:
contracts = r"\n".join(buffer)
contracts = contracts.replace("\r\n", r"\n", 10 ** 10)
contracts = contracts.replace("\n", r"\n", 10 ** 10)
contracts = contracts.replace("{.underline}", "", 10 ** 10)
index_marks = []
for amount in gen_amounts:
start = contracts.find(amount)
end = start + len(amount)
if start>0:
index_marks.append((start,end))
if index_marks:
indexs =";".join( [str(k)+','+str(v) for (k,v) in index_marks] )
df = df.append({"contract":contracts,"indexes": indexs}, ignore_index=True)
df.to_csv("contract_amount_goldtest.csv", columns=["contract", "indexes"], index=False)
print('FIN') | <filename>CAIL2020/jesb/datagen/contract_test.py
import os
import random
import re
import pandas
dic=[]
with open('amount_v1v2.dic', 'r', encoding='utf-8') as f:
lines = f.readlines()
dic.extend([l.strip() for l in lines])
print(len(dic))
regdic = []
for word in dic:
if '_' in word:
word = word.replace('_','[_\d]?',10)
r = re.compile(word)
else:
r = re.compile(word)
regdic.append(r)
def trigger(line):
for i in range(len(dic)):
if dic[i] in line:
return i, dic[i]
return None
def reg_trigger(line):
for i in range(len(regdic)):
if regdic[i].search(line):
return i, regdic[i], dic[i]
return None
FORMAL_DIGIT="零一二三四五六七八九十百千万亿兆"
LARGE_FORMAL_DIGIT="零壹贰叁肆伍陆柒捌玖拾佰仟萬億"
DIGIT_PAUSE=',\uFF0C'
DIGIT_SPLIT='.'
CARRY = "十百千万亿"
LARGE_CARRY = "拾佰仟萬億"
COMMON_UNIT='元'
UNIT='元角分'
math_digit="1234567890\uFF10\uFF11\uFF12\uFF13\uFF14\uFF15\uFF16\uFF17\uFF18\uFF19"
amount_len = (1, 5)
category_size = 400
chinese_dic = []
with open("chinese4049.txt",'r',encoding='utf-8') as f:
for line in f:
chinese_dic.append(line.strip())
def gen_amount(formal = 0):
len = random.randint(*amount_len)
if formal==0:
return "".join(random.sample(list(math_digit), len))
elif formal == 1:
return "".join(random.sample(list(FORMAL_DIGIT), len))
return "".join(random.sample(list(LARGE_FORMAL_DIGIT), len))
def gen_digit_amount(lenghth, comma=True, period=True):
index = 0
gen = ""
while index < lenghth:
gen += "".join(random.sample(list(math_digit), 3))
if comma:
gen += "".join(random.sample(list(DIGIT_PAUSE), 1))
index += 3
if period:
gen += "".join(random.sample(list(math_digit), 2))
return gen
def gen_with_rule(type = 0):
dice = random.random()
if dice < 0.3:
chars = random.randint(1, 3)
elif dice<0.6:
chars = random.randint(1, 6)
else:
chars = random.randint(1, 10)
index = 0
gen = ""
if type==0:
digit_type = random.randint(1, 4)
if digit_type ==0:
gen = gen_digit_amount(chars, comma=False, period=False)
elif digit_type ==1:
gen = gen_digit_amount(chars, comma=False, period=True)
elif digit_type == 2:
gen = gen_digit_amount(chars, comma=True, period=False)
else:
gen = gen_digit_amount(chars, comma=True, period=True)
else:
while index < chars:
if type==1:
gen += "".join(random.sample(list(FORMAL_DIGIT), 1))
gen += "".join(random.sample(list(CARRY), 1))
index+=2
elif type==2:
gen += "".join(random.sample(list(LARGE_FORMAL_DIGIT), 1))
gen += "".join(random.sample(list(LARGE_CARRY), 1))
index += 2
else:
if random.random() > 0.5:
gen += "".join(random.sample(list(math_digit), 3))
if random.random() > 0.1:
gen += "".join(random.sample(list(DIGIT_PAUSE), 1))
if random.random() > 0.5:
gen += "".join(random.sample(list(CARRY), 1))
else:
gen += "".join(random.sample(list(LARGE_CARRY), 1))
index += 4
else:
gen += "".join(random.sample(list(FORMAL_DIGIT), 1))
gen += "".join(random.sample(list(LARGE_FORMAL_DIGIT), 1))
index += 2
if random.random() < 0.1:
gen += "".join(random.sample(list(UNIT), 1))
elif random.random() < 0.9:
gen += COMMON_UNIT
else:
gen += " "
return gen
gen_amounts = []
gen_amounts.append('218399')
gen_amounts.append('贰拾壹万捌仟叁佰玖十九')
gen_amounts.append('31287')
gen_amounts.append('叁万壹仟贰佰捌拾柒')
gen_amounts.append('300000')
gen_amounts.append('叁拾万')
gen_amounts.append('280000')
gen_amounts.append('贰拾捌万')
gen_amounts.append('135998')
gen_amounts.append('拾叁万伍仟玖佰玖拾捌')
gen_amounts.append('75382')
gen_amounts.append('柒万伍仟叁佰捌拾贰')
gen_amounts.append('135998')
gen_amounts.append('柒万伍仟叁佰捌拾贰')
gen_amounts.append('1800000')
gen_amounts.append('壹佰捌拾万')
df = pandas.DataFrame(columns=["contract","indexes"])
# for dirpath, dnames, fnames in os.walk("txt/"):
# for file in fnames:
filename = 'testset.txt'
with open(filename, 'r', encoding='utf-8') as fr:
for line in fr:
buffer = []
buffer.append(line.strip())
# res = reg_trigger(line)
# if res:
# formald = gen_with_rule(type=random.randint(1,3))
# mathd = gen_with_rule(type=0)
#
# newline = res[1].sub(line, res[2] + formald + ("".join(random.sample(chinese_dic, random.randint(min(3, len(line)//3), len(line)//3))).replace("\n", "", 10 ** 10)) +mathd)
# buffer.append(newline.strip())
# else:
contracts = r"\n".join(buffer)
contracts = contracts.replace("\r\n", r"\n", 10 ** 10)
contracts = contracts.replace("\n", r"\n", 10 ** 10)
contracts = contracts.replace("{.underline}", "", 10 ** 10)
index_marks = []
for amount in gen_amounts:
start = contracts.find(amount)
end = start + len(amount)
if start>0:
index_marks.append((start,end))
if index_marks:
indexs =";".join( [str(k)+','+str(v) for (k,v) in index_marks] )
df = df.append({"contract":contracts,"indexes": indexs}, ignore_index=True)
df.to_csv("contract_amount_goldtest.csv", columns=["contract", "indexes"], index=False)
print('FIN') | en | 0.322569 | # for dirpath, dnames, fnames in os.walk("txt/"): # for file in fnames: # res = reg_trigger(line) # if res: # formald = gen_with_rule(type=random.randint(1,3)) # mathd = gen_with_rule(type=0) # # newline = res[1].sub(line, res[2] + formald + ("".join(random.sample(chinese_dic, random.randint(min(3, len(line)//3), len(line)//3))).replace("\n", "", 10 ** 10)) +mathd) # buffer.append(newline.strip()) # else: | 2.359514 | 2 |
llvmpy/src/Bitcode/ReaderWriter.py | KennethNielsen/llvmpy | 140 | 6628038 | from binding import *
from ..namespace import llvm
from ..ADT.StringRef import StringRef
from ..Module import Module
from ..LLVMContext import LLVMContext
llvm.includes.add('llvm/Bitcode/ReaderWriter.h')
ParseBitCodeFile = llvm.CustomFunction('ParseBitCodeFile',
'llvm_ParseBitCodeFile',
PyObjectPtr, # returns Module*
cast(bytes, StringRef),
ref(LLVMContext),
PyObjectPtr, # file-like object
).require_only(2)
WriteBitcodeToFile = llvm.CustomFunction('WriteBitcodeToFile',
'llvm_WriteBitcodeToFile',
PyObjectPtr, # return None
ptr(Module),
PyObjectPtr, # file-like object
)
getBitcodeTargetTriple = llvm.CustomFunction('getBitcodeTargetTriple',
'llvm_getBitcodeTargetTriple',
PyObjectPtr, # return str
cast(str, StringRef),
ref(LLVMContext),
PyObjectPtr, # file-like object
).require_only(2)
| from binding import *
from ..namespace import llvm
from ..ADT.StringRef import StringRef
from ..Module import Module
from ..LLVMContext import LLVMContext
llvm.includes.add('llvm/Bitcode/ReaderWriter.h')
ParseBitCodeFile = llvm.CustomFunction('ParseBitCodeFile',
'llvm_ParseBitCodeFile',
PyObjectPtr, # returns Module*
cast(bytes, StringRef),
ref(LLVMContext),
PyObjectPtr, # file-like object
).require_only(2)
WriteBitcodeToFile = llvm.CustomFunction('WriteBitcodeToFile',
'llvm_WriteBitcodeToFile',
PyObjectPtr, # return None
ptr(Module),
PyObjectPtr, # file-like object
)
getBitcodeTargetTriple = llvm.CustomFunction('getBitcodeTargetTriple',
'llvm_getBitcodeTargetTriple',
PyObjectPtr, # return str
cast(str, StringRef),
ref(LLVMContext),
PyObjectPtr, # file-like object
).require_only(2)
| en | 0.330225 | # returns Module* # file-like object # return None # file-like object # return str # file-like object | 2.025917 | 2 |
tensorflow/lite/experimental/ruy/ruy_test_ext.bzl | PaulWang1905/tensorflow | 848 | 6628039 | <filename>tensorflow/lite/experimental/ruy/ruy_test_ext.bzl
"""
Allows to specialize the ruy BUILD to availability of external libraries
"""
def ruy_test_ext_defines():
return []
def ruy_test_ext_deps():
return []
| <filename>tensorflow/lite/experimental/ruy/ruy_test_ext.bzl
"""
Allows to specialize the ruy BUILD to availability of external libraries
"""
def ruy_test_ext_defines():
return []
def ruy_test_ext_deps():
return []
| en | 0.752198 | Allows to specialize the ruy BUILD to availability of external libraries | 1.218836 | 1 |
control/webapp/society.py | CHTJonas/control-panel | 0 | 6628040 | import re
from urllib.parse import urlparse
from werkzeug.exceptions import NotFound, Forbidden
from flask import Blueprint, render_template, request, redirect, url_for
from .utils import srcf_db_sess as sess
from .utils import parse_domain_name, create_job_maybe_email_and_redirect, find_mem_society
from . import utils
from srcf.controllib import jobs
from srcf.controllib.jobs import Job
from srcf.database import Domain
from srcf import domains
from . import utils, inspect_services
import string
bp = Blueprint("society", __name__)
def validate_soc_role_email(email):
if isinstance(email, str):
email = email.lower()
if not email:
return None
elif not utils.email_re.match(email):
return "This doesn't look like a valid email address."
elif email.endswith(("@srcf.net", "@srcf.ucam.org", "@hades.srcf.net")):
return "This should be an external email address, not one provided by the SRCF."
elif (email.endswith(("@cam.ac.uk", "@cantab.net", "@alumni.cam.ac.uk"))
or (email.endswith(("@hermes.cam.ac.uk",
"@universityofcambridgecloud.onmicrosoft.com"))
# check that this isn't a shared mailbox
and re.match(r'[0-9]$', '@'.join(email.split('@')[:-1]).split('+')[0]))):
return "This looks like a personal email address, which isn't suitable for a role email."
return None
@bp.route('/societies/<society>')
def home(society):
mem, soc = find_mem_society(society)
inspect_services.lookup_all(mem)
inspect_services.lookup_all(soc)
return render_template("society/home.html", member=mem, society=soc)
@bp.route("/societies/<society>/roleemail", methods=["GET", "POST"])
def update_role_email(society):
mem, soc = find_mem_society(society)
email = soc.role_email
error = None
if request.method == "POST":
email = request.form.get("email", "").strip() or None
if soc.role_email != email:
error = validate_soc_role_email(email)
elif email:
error = "That's the address we have already."
else:
error = "No address is currently set."
if request.method == "POST" and not error:
return create_job_maybe_email_and_redirect(
jobs.UpdateSocietyRoleEmail,
requesting_member=mem,
society=soc,
email=email
)
else:
return render_template("society/update_role_email.html", society=soc, email=email, error=error)
@bp.route("/societies/<society>/admins/add", methods=["GET", "POST"])
def add_admin(society):
mem, soc = find_mem_society(society)
crsid = ""
tgt = None
error = None
if request.method == "POST":
crsid = request.form.get("crsid", "").strip().lower()
try:
if not crsid:
raise ValueError("Please enter the new administrator's CRSid.")
try:
tgt = utils.get_member(crsid)
except KeyError:
if re.match("^[a-z]+[0-9]*$", crsid):
raise ValueError("{0} isn't a SRCF member; please ask them to join.".format(crsid))
else:
raise ValueError("{0} isn't a valid CRSid.".format(crsid))
if not tgt.member:
raise ValueError("{0} isn't a SRCF member; please ask them to join.".format(crsid))
if not tgt.user:
raise ValueError("{0} doesn't have an active SRCF account; please ask them to reactivate their account by going to the SRCF Control Panel.".format(crsid))
if tgt == mem:
raise ValueError("You are already an administrator.")
if tgt in soc.admins:
raise ValueError("{0} is already an administrator.".format(crsid))
except ValueError as e:
error = e.args[0]
if request.method == "POST" and not error:
return create_job_maybe_email_and_redirect(
jobs.ChangeSocietyAdmin,
requesting_member=mem,
society=soc,
target_member=tgt,
action="add"
)
else:
return render_template("society/add_admin.html", society=soc, crsid=crsid, error=error)
@bp.route("/societies/<society>/admins/<target_crsid>/remove", methods=["GET", "POST"])
def remove_admin(society, target_crsid):
mem, soc = find_mem_society(society)
try:
tgt = utils.get_member(target_crsid)
except KeyError:
raise NotFound
if tgt not in soc.admins:
raise NotFound
if request.method == "POST":
return create_job_maybe_email_and_redirect(
jobs.ChangeSocietyAdmin,
requesting_member=mem,
society=soc,
target_member=tgt,
action="remove"
)
else:
return render_template("society/remove_admin.html", member=mem, society=soc, target=tgt)
@bp.route("/societies/<society>/mailinglist", methods=["GET", "POST"])
def create_mailing_list(society):
mem, soc = find_mem_society(society)
listname = ""
error = None
if request.method == "POST":
listname = request.form.get("listname", "").strip()
if not listname:
error = "Please enter a list name."
elif re.search(r"[^a-z0-9_-]", listname):
error = "List names can only contain letters, numbers, hyphens and underscores."
else:
lists = inspect_services.lookup_mailinglists(society)
if "{}-{}".format(society, listname) in lists:
error = "This mailing list already exists."
if request.method == "POST" and not error:
return create_job_maybe_email_and_redirect(
jobs.CreateSocietyMailingList,
member=mem, society=soc, listname=listname
)
else:
return render_template("society/create_mailing_list.html", society=soc, listname=listname, error=error)
@bp.route("/societies/<society>/mailinglist/<listname>/password", methods=["GET", "POST"])
def reset_mailing_list_password(society, listname):
mem, soc = find_mem_society(society)
lists = inspect_services.lookup_mailinglists(society)
if listname not in lists:
raise NotFound
if request.method == "POST":
return create_job_maybe_email_and_redirect(
jobs.ResetSocietyMailingListPassword,
member=mem, society=soc, listname=listname
)
else:
return render_template("society/reset_mailing_list_password.html", member=mem, society=soc, listname=listname)
@bp.route("/societies/<society>/mysql/password", methods=["GET", "POST"], defaults={"type": "mysql"})
@bp.route("/societies/<society>/postgres/password", methods=["GET", "POST"], defaults={"type": "postgres"})
def reset_database_password(society, type):
mem, soc = find_mem_society(society)
if request.method == "POST":
cls = {"mysql": jobs.ResetMySQLSocietyPassword,
"postgres": jobs.ResetPostgresSocietyPassword}[type]
return create_job_maybe_email_and_redirect(cls, society=soc, member=mem)
else:
formatted_name = {"mysql": "MySQL",
"postgres": "PostgreSQL"}[type]
web_interface = {"mysql": "phpMyAdmin",
"postgres": "phpPgAdmin"}[type]
return render_template("society/reset_database_password.html", society=soc, member=mem, type=type, name=formatted_name, web_interface=web_interface)
@bp.route("/societies/<society>/mysql/create", methods=["GET", "POST"], defaults={"type": "mysql"})
@bp.route("/societies/<society>/postgres/create", methods=["GET", "POST"], defaults={"type": "postgres"})
def create_database(society, type):
mem, soc = find_mem_society(society)
if request.method == "POST":
cls = {"mysql": jobs.CreateMySQLSocietyDatabase,
"postgres": jobs.CreatePostgresSocietyDatabase}[type]
return create_job_maybe_email_and_redirect(cls, member=mem, society=soc)
else:
formatted_name = {"mysql": "MySQL",
"postgres": "PostgreSQL"}[type]
inspect = {"mysql": inspect_services.lookup_mysqluser,
"postgres": inspect_services.lookup_pguser}[type]
has_mem_user = inspect(mem.crsid)
has_soc_user = inspect(soc.society)
return render_template("society/create_database.html", society=soc, member=mem, type=type, name=formatted_name, mem_user=has_mem_user, soc_user=has_soc_user)
@bp.route("/societies/<society>/domains/add", methods=["GET", "POST"])
def add_vhost(society):
mem, soc = find_mem_society(society)
domain = ""
root = ""
errors = {}
if request.method == "POST":
domain = request.form.get("domain", "").strip()
root = request.form.get("root", "").strip()
if domain:
parsed = parse_domain_name(domain)
if domain != parsed:
domain = parsed
errors["domain"] = "We've corrected your input to just the domain name, submit again once you've checked it's correct."
elif "." not in domain:
errors["domain"] = "Please enter a fully-qualified domain name."
elif domain.endswith("." + soc.society + ".soc.srcf.net"):
pass
elif domain.endswith(".user.srcf.net") or domain.endswith(".soc.srcf.net"):
errors["domain"] = "SRCF domains can't be registered here."
elif sess.query(Domain).filter(Domain.domain == domain).count():
errors["domain"] = "This domain is already registered."
else:
errors["domain"] = "Please enter a domain or subdomain."
if request.form.get("edit") or errors:
return render_template("society/add_vhost.html", society=soc, member=mem, domain=domain, root=root, errors=errors)
elif not request.form.get("confirm"):
valid = {}
prefixed = "www.{}".format(domain)
for d in (domain, prefixed):
valid[d] = domains.verify(d)
good = all(v == (True, True) for v in valid.values())
return render_template("society/add_vhost_test.html", society=soc, member=mem, domain=domain, root=root, valid=valid, good=good)
else:
return create_job_maybe_email_and_redirect(
jobs.AddSocietyVhost, member=mem, society=soc,
domain=domain, root=root)
else:
return render_template("society/add_vhost.html", society=soc, member=mem, domain=domain, root=root, errors=errors)
@bp.route("/societies/<society>/domains/<domain>/changedocroot", methods=["GET", "POST"])
def change_vhost_docroot(society, domain):
mem, soc = find_mem_society(society)
errors = {}
try:
record = sess.query(Domain).filter(Domain.domain == domain, Domain.owner == soc.society)[0]
except IndexError:
raise NotFound
root = record.root.replace("public_html/", "") if record.root else ""
if request.method == "POST":
root = request.form.get("root", "").strip()
if any([ch in root for ch in string.whitespace + "\\" + "\"" + "\'"]) or ".." in root:
errors["root"] = "This document root is invalid."
try:
domain = parse_domain_name(domain)
except ValueError as e:
errors["domain"] = e.args[0]
if request.method == "POST" and not errors:
return create_job_maybe_email_and_redirect(
jobs.ChangeSocietyVhostDocroot, member=mem, society=soc,
domain=domain, root=root)
else:
return render_template("society/change_vhost_docroot.html", society=soc, member=mem, domain=domain, root=root, errors=errors)
@bp.route("/societies/<society>/domains/<domain>/remove", methods=["GET", "POST"])
def remove_vhost(society, domain):
mem, soc = find_mem_society(society)
try:
record = sess.query(Domain).filter(Domain.domain == domain)[0]
except IndexError:
raise NotFound
if not record.owner == soc.society:
raise Forbidden
if request.method == "POST":
return create_job_maybe_email_and_redirect(
jobs.RemoveSocietyVhost, member=mem, society=soc,
domain=domain)
else:
return render_template("society/remove_vhost.html", society=soc, member=mem, domain=domain)
| import re
from urllib.parse import urlparse
from werkzeug.exceptions import NotFound, Forbidden
from flask import Blueprint, render_template, request, redirect, url_for
from .utils import srcf_db_sess as sess
from .utils import parse_domain_name, create_job_maybe_email_and_redirect, find_mem_society
from . import utils
from srcf.controllib import jobs
from srcf.controllib.jobs import Job
from srcf.database import Domain
from srcf import domains
from . import utils, inspect_services
import string
bp = Blueprint("society", __name__)
def validate_soc_role_email(email):
if isinstance(email, str):
email = email.lower()
if not email:
return None
elif not utils.email_re.match(email):
return "This doesn't look like a valid email address."
elif email.endswith(("@srcf.net", "@srcf.ucam.org", "@hades.srcf.net")):
return "This should be an external email address, not one provided by the SRCF."
elif (email.endswith(("@cam.ac.uk", "@cantab.net", "@alumni.cam.ac.uk"))
or (email.endswith(("@hermes.cam.ac.uk",
"@universityofcambridgecloud.onmicrosoft.com"))
# check that this isn't a shared mailbox
and re.match(r'[0-9]$', '@'.join(email.split('@')[:-1]).split('+')[0]))):
return "This looks like a personal email address, which isn't suitable for a role email."
return None
@bp.route('/societies/<society>')
def home(society):
mem, soc = find_mem_society(society)
inspect_services.lookup_all(mem)
inspect_services.lookup_all(soc)
return render_template("society/home.html", member=mem, society=soc)
@bp.route("/societies/<society>/roleemail", methods=["GET", "POST"])
def update_role_email(society):
mem, soc = find_mem_society(society)
email = soc.role_email
error = None
if request.method == "POST":
email = request.form.get("email", "").strip() or None
if soc.role_email != email:
error = validate_soc_role_email(email)
elif email:
error = "That's the address we have already."
else:
error = "No address is currently set."
if request.method == "POST" and not error:
return create_job_maybe_email_and_redirect(
jobs.UpdateSocietyRoleEmail,
requesting_member=mem,
society=soc,
email=email
)
else:
return render_template("society/update_role_email.html", society=soc, email=email, error=error)
@bp.route("/societies/<society>/admins/add", methods=["GET", "POST"])
def add_admin(society):
mem, soc = find_mem_society(society)
crsid = ""
tgt = None
error = None
if request.method == "POST":
crsid = request.form.get("crsid", "").strip().lower()
try:
if not crsid:
raise ValueError("Please enter the new administrator's CRSid.")
try:
tgt = utils.get_member(crsid)
except KeyError:
if re.match("^[a-z]+[0-9]*$", crsid):
raise ValueError("{0} isn't a SRCF member; please ask them to join.".format(crsid))
else:
raise ValueError("{0} isn't a valid CRSid.".format(crsid))
if not tgt.member:
raise ValueError("{0} isn't a SRCF member; please ask them to join.".format(crsid))
if not tgt.user:
raise ValueError("{0} doesn't have an active SRCF account; please ask them to reactivate their account by going to the SRCF Control Panel.".format(crsid))
if tgt == mem:
raise ValueError("You are already an administrator.")
if tgt in soc.admins:
raise ValueError("{0} is already an administrator.".format(crsid))
except ValueError as e:
error = e.args[0]
if request.method == "POST" and not error:
return create_job_maybe_email_and_redirect(
jobs.ChangeSocietyAdmin,
requesting_member=mem,
society=soc,
target_member=tgt,
action="add"
)
else:
return render_template("society/add_admin.html", society=soc, crsid=crsid, error=error)
@bp.route("/societies/<society>/admins/<target_crsid>/remove", methods=["GET", "POST"])
def remove_admin(society, target_crsid):
mem, soc = find_mem_society(society)
try:
tgt = utils.get_member(target_crsid)
except KeyError:
raise NotFound
if tgt not in soc.admins:
raise NotFound
if request.method == "POST":
return create_job_maybe_email_and_redirect(
jobs.ChangeSocietyAdmin,
requesting_member=mem,
society=soc,
target_member=tgt,
action="remove"
)
else:
return render_template("society/remove_admin.html", member=mem, society=soc, target=tgt)
@bp.route("/societies/<society>/mailinglist", methods=["GET", "POST"])
def create_mailing_list(society):
mem, soc = find_mem_society(society)
listname = ""
error = None
if request.method == "POST":
listname = request.form.get("listname", "").strip()
if not listname:
error = "Please enter a list name."
elif re.search(r"[^a-z0-9_-]", listname):
error = "List names can only contain letters, numbers, hyphens and underscores."
else:
lists = inspect_services.lookup_mailinglists(society)
if "{}-{}".format(society, listname) in lists:
error = "This mailing list already exists."
if request.method == "POST" and not error:
return create_job_maybe_email_and_redirect(
jobs.CreateSocietyMailingList,
member=mem, society=soc, listname=listname
)
else:
return render_template("society/create_mailing_list.html", society=soc, listname=listname, error=error)
@bp.route("/societies/<society>/mailinglist/<listname>/password", methods=["GET", "POST"])
def reset_mailing_list_password(society, listname):
mem, soc = find_mem_society(society)
lists = inspect_services.lookup_mailinglists(society)
if listname not in lists:
raise NotFound
if request.method == "POST":
return create_job_maybe_email_and_redirect(
jobs.ResetSocietyMailingListPassword,
member=mem, society=soc, listname=listname
)
else:
return render_template("society/reset_mailing_list_password.html", member=mem, society=soc, listname=listname)
@bp.route("/societies/<society>/mysql/password", methods=["GET", "POST"], defaults={"type": "mysql"})
@bp.route("/societies/<society>/postgres/password", methods=["GET", "POST"], defaults={"type": "postgres"})
def reset_database_password(society, type):
mem, soc = find_mem_society(society)
if request.method == "POST":
cls = {"mysql": jobs.ResetMySQLSocietyPassword,
"postgres": jobs.ResetPostgresSocietyPassword}[type]
return create_job_maybe_email_and_redirect(cls, society=soc, member=mem)
else:
formatted_name = {"mysql": "MySQL",
"postgres": "PostgreSQL"}[type]
web_interface = {"mysql": "phpMyAdmin",
"postgres": "phpPgAdmin"}[type]
return render_template("society/reset_database_password.html", society=soc, member=mem, type=type, name=formatted_name, web_interface=web_interface)
@bp.route("/societies/<society>/mysql/create", methods=["GET", "POST"], defaults={"type": "mysql"})
@bp.route("/societies/<society>/postgres/create", methods=["GET", "POST"], defaults={"type": "postgres"})
def create_database(society, type):
mem, soc = find_mem_society(society)
if request.method == "POST":
cls = {"mysql": jobs.CreateMySQLSocietyDatabase,
"postgres": jobs.CreatePostgresSocietyDatabase}[type]
return create_job_maybe_email_and_redirect(cls, member=mem, society=soc)
else:
formatted_name = {"mysql": "MySQL",
"postgres": "PostgreSQL"}[type]
inspect = {"mysql": inspect_services.lookup_mysqluser,
"postgres": inspect_services.lookup_pguser}[type]
has_mem_user = inspect(mem.crsid)
has_soc_user = inspect(soc.society)
return render_template("society/create_database.html", society=soc, member=mem, type=type, name=formatted_name, mem_user=has_mem_user, soc_user=has_soc_user)
@bp.route("/societies/<society>/domains/add", methods=["GET", "POST"])
def add_vhost(society):
mem, soc = find_mem_society(society)
domain = ""
root = ""
errors = {}
if request.method == "POST":
domain = request.form.get("domain", "").strip()
root = request.form.get("root", "").strip()
if domain:
parsed = parse_domain_name(domain)
if domain != parsed:
domain = parsed
errors["domain"] = "We've corrected your input to just the domain name, submit again once you've checked it's correct."
elif "." not in domain:
errors["domain"] = "Please enter a fully-qualified domain name."
elif domain.endswith("." + soc.society + ".soc.srcf.net"):
pass
elif domain.endswith(".user.srcf.net") or domain.endswith(".soc.srcf.net"):
errors["domain"] = "SRCF domains can't be registered here."
elif sess.query(Domain).filter(Domain.domain == domain).count():
errors["domain"] = "This domain is already registered."
else:
errors["domain"] = "Please enter a domain or subdomain."
if request.form.get("edit") or errors:
return render_template("society/add_vhost.html", society=soc, member=mem, domain=domain, root=root, errors=errors)
elif not request.form.get("confirm"):
valid = {}
prefixed = "www.{}".format(domain)
for d in (domain, prefixed):
valid[d] = domains.verify(d)
good = all(v == (True, True) for v in valid.values())
return render_template("society/add_vhost_test.html", society=soc, member=mem, domain=domain, root=root, valid=valid, good=good)
else:
return create_job_maybe_email_and_redirect(
jobs.AddSocietyVhost, member=mem, society=soc,
domain=domain, root=root)
else:
return render_template("society/add_vhost.html", society=soc, member=mem, domain=domain, root=root, errors=errors)
@bp.route("/societies/<society>/domains/<domain>/changedocroot", methods=["GET", "POST"])
def change_vhost_docroot(society, domain):
mem, soc = find_mem_society(society)
errors = {}
try:
record = sess.query(Domain).filter(Domain.domain == domain, Domain.owner == soc.society)[0]
except IndexError:
raise NotFound
root = record.root.replace("public_html/", "") if record.root else ""
if request.method == "POST":
root = request.form.get("root", "").strip()
if any([ch in root for ch in string.whitespace + "\\" + "\"" + "\'"]) or ".." in root:
errors["root"] = "This document root is invalid."
try:
domain = parse_domain_name(domain)
except ValueError as e:
errors["domain"] = e.args[0]
if request.method == "POST" and not errors:
return create_job_maybe_email_and_redirect(
jobs.ChangeSocietyVhostDocroot, member=mem, society=soc,
domain=domain, root=root)
else:
return render_template("society/change_vhost_docroot.html", society=soc, member=mem, domain=domain, root=root, errors=errors)
@bp.route("/societies/<society>/domains/<domain>/remove", methods=["GET", "POST"])
def remove_vhost(society, domain):
mem, soc = find_mem_society(society)
try:
record = sess.query(Domain).filter(Domain.domain == domain)[0]
except IndexError:
raise NotFound
if not record.owner == soc.society:
raise Forbidden
if request.method == "POST":
return create_job_maybe_email_and_redirect(
jobs.RemoveSocietyVhost, member=mem, society=soc,
domain=domain)
else:
return render_template("society/remove_vhost.html", society=soc, member=mem, domain=domain)
| en | 0.983059 | # check that this isn't a shared mailbox | 2.292422 | 2 |
helm/dagster/schema/schema/charts/utils/kubernetes.py | kstennettlull/dagster | 0 | 6628041 | from enum import Enum
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Extra # pylint: disable=no-name-in-module
from .utils import BaseModel as BaseModelWithNullableRequiredFields
from .utils import SupportedKubernetes, create_definition_ref
class Annotations(BaseModel):
__root__: Dict[str, str]
class Config:
schema_extra = {
"$ref": create_definition_ref(
"io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta/properties/annotations"
)
}
class Labels(BaseModel):
class Config:
schema_extra = {
"$ref": create_definition_ref(
"io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta/properties/labels"
)
}
class PullPolicy(str, Enum):
ALWAYS = "Always"
IF_NOT_PRESENT = "IfNotPresent"
NEVER = "Never"
class Image(BaseModelWithNullableRequiredFields):
repository: str
tag: Optional[str]
pullPolicy: PullPolicy
@property
def name(self) -> str:
return f"{self.repository}:{self.tag}" if self.tag else self.repository
class ExternalImage(Image):
tag: str
class Service(BaseModel):
type: str
port: int
annotations: Optional[Annotations]
class Config:
extra = Extra.forbid
class NodeSelector(BaseModel):
__root__: Dict[str, str]
class Config:
schema_extra = {
"$ref": create_definition_ref("io.k8s.api.core.v1.PodSpec/properties/nodeSelector")
}
class Affinity(BaseModel):
__root__: Dict[str, Any]
class Config:
schema_extra = {"$ref": create_definition_ref("io.k8s.api.core.v1.Affinity")}
class Tolerations(BaseModel):
__root__: List[Dict[str, Any]]
class Config:
schema_extra = {
"$ref": create_definition_ref("io.k8s.api.core.v1.PodSpec/properties/tolerations")
}
class PodSecurityContext(BaseModel):
__root__: Dict[str, Any]
class Config:
schema_extra = {"$ref": create_definition_ref("io.k8s.api.core.v1.PodSecurityContext")}
class SecurityContext(BaseModel):
__root__: Dict[str, Any]
class Config:
schema_extra = {"$ref": create_definition_ref("io.k8s.api.core.v1.SecurityContext")}
class InitContainer(BaseModel):
class Config:
schema_extra = {"$ref": create_definition_ref("io.k8s.api.core.v1.Container")}
class Resources(BaseModel):
__root__: Dict[str, Any]
class Config:
schema_extra = {"$ref": create_definition_ref("io.k8s.api.core.v1.ResourceRequirements")}
class LivenessProbe(BaseModel):
class Config:
schema_extra = {"$ref": create_definition_ref("io.k8s.api.core.v1.Probe")}
class ReadinessProbe(BaseModel):
class Config:
schema_extra = {"$ref": create_definition_ref("io.k8s.api.core.v1.Probe")}
class StartupProbe(BaseModel):
enabled: bool = True
class Config:
schema_extra = {
"$ref": create_definition_ref("io.k8s.api.core.v1.Probe"),
}
class SecretRef(BaseModel):
class Config:
schema_extra = {"$ref": create_definition_ref("io.k8s.api.core.v1.LocalObjectReference")}
class SecretEnvSource(BaseModel):
class Config:
schema_extra = {"$ref": create_definition_ref("io.k8s.api.core.v1.SecretEnvSource")}
class ConfigMapEnvSource(BaseModel):
class Config:
schema_extra = {"$ref": create_definition_ref("io.k8s.api.core.v1.ConfigMapEnvSource")}
class VolumeMount(BaseModel):
class Config:
schema_extra = {"$ref": create_definition_ref("io.k8s.api.core.v1.VolumeMount")}
class Volume(BaseModel):
class Config:
schema_extra = {"$ref": create_definition_ref("io.k8s.api.core.v1.Volume")}
| from enum import Enum
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Extra # pylint: disable=no-name-in-module
from .utils import BaseModel as BaseModelWithNullableRequiredFields
from .utils import SupportedKubernetes, create_definition_ref
class Annotations(BaseModel):
__root__: Dict[str, str]
class Config:
schema_extra = {
"$ref": create_definition_ref(
"io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta/properties/annotations"
)
}
class Labels(BaseModel):
class Config:
schema_extra = {
"$ref": create_definition_ref(
"io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta/properties/labels"
)
}
class PullPolicy(str, Enum):
ALWAYS = "Always"
IF_NOT_PRESENT = "IfNotPresent"
NEVER = "Never"
class Image(BaseModelWithNullableRequiredFields):
repository: str
tag: Optional[str]
pullPolicy: PullPolicy
@property
def name(self) -> str:
return f"{self.repository}:{self.tag}" if self.tag else self.repository
class ExternalImage(Image):
tag: str
class Service(BaseModel):
type: str
port: int
annotations: Optional[Annotations]
class Config:
extra = Extra.forbid
class NodeSelector(BaseModel):
__root__: Dict[str, str]
class Config:
schema_extra = {
"$ref": create_definition_ref("io.k8s.api.core.v1.PodSpec/properties/nodeSelector")
}
class Affinity(BaseModel):
__root__: Dict[str, Any]
class Config:
schema_extra = {"$ref": create_definition_ref("io.k8s.api.core.v1.Affinity")}
class Tolerations(BaseModel):
__root__: List[Dict[str, Any]]
class Config:
schema_extra = {
"$ref": create_definition_ref("io.k8s.api.core.v1.PodSpec/properties/tolerations")
}
class PodSecurityContext(BaseModel):
__root__: Dict[str, Any]
class Config:
schema_extra = {"$ref": create_definition_ref("io.k8s.api.core.v1.PodSecurityContext")}
class SecurityContext(BaseModel):
__root__: Dict[str, Any]
class Config:
schema_extra = {"$ref": create_definition_ref("io.k8s.api.core.v1.SecurityContext")}
class InitContainer(BaseModel):
class Config:
schema_extra = {"$ref": create_definition_ref("io.k8s.api.core.v1.Container")}
class Resources(BaseModel):
__root__: Dict[str, Any]
class Config:
schema_extra = {"$ref": create_definition_ref("io.k8s.api.core.v1.ResourceRequirements")}
class LivenessProbe(BaseModel):
class Config:
schema_extra = {"$ref": create_definition_ref("io.k8s.api.core.v1.Probe")}
class ReadinessProbe(BaseModel):
class Config:
schema_extra = {"$ref": create_definition_ref("io.k8s.api.core.v1.Probe")}
class StartupProbe(BaseModel):
enabled: bool = True
class Config:
schema_extra = {
"$ref": create_definition_ref("io.k8s.api.core.v1.Probe"),
}
class SecretRef(BaseModel):
class Config:
schema_extra = {"$ref": create_definition_ref("io.k8s.api.core.v1.LocalObjectReference")}
class SecretEnvSource(BaseModel):
class Config:
schema_extra = {"$ref": create_definition_ref("io.k8s.api.core.v1.SecretEnvSource")}
class ConfigMapEnvSource(BaseModel):
class Config:
schema_extra = {"$ref": create_definition_ref("io.k8s.api.core.v1.ConfigMapEnvSource")}
class VolumeMount(BaseModel):
class Config:
schema_extra = {"$ref": create_definition_ref("io.k8s.api.core.v1.VolumeMount")}
class Volume(BaseModel):
class Config:
schema_extra = {"$ref": create_definition_ref("io.k8s.api.core.v1.Volume")}
| en | 0.264614 | # pylint: disable=no-name-in-module | 2.268896 | 2 |
setup.py | kennell/emojiflags | 2 | 6628042 | from setuptools import setup
setup(
name='flagz',
version='1.2.2',
py_modules=['flagz'],
author='<NAME>',
author_email='<EMAIL>',
license='MIT',
url='https://github.com/kennell/flagz',
)
| from setuptools import setup
setup(
name='flagz',
version='1.2.2',
py_modules=['flagz'],
author='<NAME>',
author_email='<EMAIL>',
license='MIT',
url='https://github.com/kennell/flagz',
)
| none | 1 | 1.074447 | 1 | |
robot/Car.py | toulouse-robot-race/turbot-simu | 5 | 6628043 | from robot.Config import STEERING_COEF
class Car:
def __init__(self, simulator, steering_handles, motors_handles, speed_controller, tachometer, gyro):
self.gyro = gyro
self.tachometer = tachometer
self.motors_handles = motors_handles
self.steering_handles = steering_handles
self.simulator = simulator
self.speedController = speed_controller
def tourne(self, steering_percent):
# Apply exponential
sign = 1 if steering_percent > 0 else -1
steering_percent = sign * (abs(steering_percent) ** 1.2) * 0.7 # TODO calibrate according to real robot
pos_steering = steering_percent * STEERING_COEF
self.simulator.set_target_pos(self.steering_handles[0], pos_steering)
self.simulator.set_target_pos(self.steering_handles[1], pos_steering)
def avance(self, speed):
self.speedController.set_speed_target(speed)
def get_tacho(self):
return self.tachometer.get_tacho()
def get_cap(self):
return self.gyro.get_cap()
def has_gyro_data(self):
return True
def setLed(self, etat):
pass
def getBoutonPoussoir(self):
return 1
def gpioCleanUp(self):
pass
| from robot.Config import STEERING_COEF
class Car:
def __init__(self, simulator, steering_handles, motors_handles, speed_controller, tachometer, gyro):
self.gyro = gyro
self.tachometer = tachometer
self.motors_handles = motors_handles
self.steering_handles = steering_handles
self.simulator = simulator
self.speedController = speed_controller
def tourne(self, steering_percent):
# Apply exponential
sign = 1 if steering_percent > 0 else -1
steering_percent = sign * (abs(steering_percent) ** 1.2) * 0.7 # TODO calibrate according to real robot
pos_steering = steering_percent * STEERING_COEF
self.simulator.set_target_pos(self.steering_handles[0], pos_steering)
self.simulator.set_target_pos(self.steering_handles[1], pos_steering)
def avance(self, speed):
self.speedController.set_speed_target(speed)
def get_tacho(self):
return self.tachometer.get_tacho()
def get_cap(self):
return self.gyro.get_cap()
def has_gyro_data(self):
return True
def setLed(self, etat):
pass
def getBoutonPoussoir(self):
return 1
def gpioCleanUp(self):
pass
| en | 0.671601 | # Apply exponential # TODO calibrate according to real robot | 2.729079 | 3 |
ACME/layer/Conv.py | mauriziokovacic/ACME | 3 | 6628044 | from .Layer import *
class Conv(Layer):
"""
A class representing a generic convolutional layer over 1D, 2D or 3D tensors
"""
def __init__(self, dim, *args, activation=None, batch_norm=None, pooling=None, **kwargs):
"""
Parameters
----------
dim : int
the dimension of the convolution. Accepted dims are 1, 2 or 3
*args : ...
the convolution layer arguments
activation : torch.nn.Module (optional)
the layer activation function (default is None)
batch_norm : torch.nn.Module (optional)
the layer batch normalization (default is None)
pooling : torch.nn.Module (optional)
the layer pooling (default is None)
**kwargs : ...
the convolution layer keyword arguments
"""
super(Conv, self).__init__(
eval('torch.nn.Conv'+str(dim)+'d(*args, **kwargs)'),
activation=activation,
batch_norm=batch_norm,
pooling=pooling,
dropout=None,
)
| from .Layer import *
class Conv(Layer):
"""
A class representing a generic convolutional layer over 1D, 2D or 3D tensors
"""
def __init__(self, dim, *args, activation=None, batch_norm=None, pooling=None, **kwargs):
"""
Parameters
----------
dim : int
the dimension of the convolution. Accepted dims are 1, 2 or 3
*args : ...
the convolution layer arguments
activation : torch.nn.Module (optional)
the layer activation function (default is None)
batch_norm : torch.nn.Module (optional)
the layer batch normalization (default is None)
pooling : torch.nn.Module (optional)
the layer pooling (default is None)
**kwargs : ...
the convolution layer keyword arguments
"""
super(Conv, self).__init__(
eval('torch.nn.Conv'+str(dim)+'d(*args, **kwargs)'),
activation=activation,
batch_norm=batch_norm,
pooling=pooling,
dropout=None,
)
| en | 0.345327 | A class representing a generic convolutional layer over 1D, 2D or 3D tensors Parameters ---------- dim : int the dimension of the convolution. Accepted dims are 1, 2 or 3 *args : ... the convolution layer arguments activation : torch.nn.Module (optional) the layer activation function (default is None) batch_norm : torch.nn.Module (optional) the layer batch normalization (default is None) pooling : torch.nn.Module (optional) the layer pooling (default is None) **kwargs : ... the convolution layer keyword arguments | 3.391433 | 3 |
views_query_planning/query_planning.py | prio-data/views_query_planning | 0 | 6628045 | import logging
from typing import Dict
import enum
from itertools import chain
import networkx as nx
from networkx.exception import NetworkXNoPath
from networkx.algorithms.shortest_paths import shortest_path
import sqlalchemy as sa
from . import exceptions, definitions
logger = logging.getLogger(__name__)
def class_partial(method,*args,**kwargs):
def undotted(instance):
return getattr(instance,method)(*args,**kwargs)
return undotted
class Direction(enum.Enum):
forwards = 1
backwards = 2
equal = 3
def join_network(tables:Dict[str,sa.Table])->nx.DiGraph:
"""
Creates a directed graph of the FK->Referent relationships present in a
list of tables. This graph can then be traversed to figure out how to
perform a join when retrieving data from this collection of tables.
"""
digraph = nx.DiGraph()
def get_fk_tables(fk):
return [tbl for tbl in tables.values() if fk.references(tbl)]
for table in tables.values():
for fk in table.foreign_keys:
try:
ref_table = get_fk_tables(fk)[-1]
except IndexError:
logger.debug("No table found for fk: %s",str(fk))
continue
digraph.add_edge(
table,
ref_table,
reference=fk.parent,
referent=fk.column
)
if {fk.parent} == set(table.primary_key):
digraph.add_edge(
ref_table,
table,
reference=fk.column,
referent=fk.parent,
)
logger.debug("Database is a digraph with %s nodes",len(digraph.nodes))
return digraph
def compose_join(network,loa_name,table_name,column_name,loa_index_columns,agg_fn="avg"):
"""
compose_join
Creates a list of operations that can be applied to a Query object, making
it retrieve data at a certain LOA
:param network: A networkx graph representing a database
:param loa_name: The name of the LOA to retrieve data at
:param table_name: The name of the table from which to retrieve the data
:param column_name: The name of the column to retrieve
:param agg_fn: If the retrieval op. needs to aggregate data, if will do so with this function
:returns: An iterator containing functions to be applied to a Query object
:raises QueryError: If table_name.column_name does not exist in the DB
:raises ConfigError: If the requested loa is not configured
"""
lookup = {tbl.name:tbl for tbl in network}
get_col_ref = lambda tbl,name: lookup[tbl].c[name]#.label(tbl+"_"+name)
loa_table = lookup[loa_name]
try:
column_ref = get_col_ref(table_name,column_name)
except KeyError as ke:
raise exceptions.QueryError(f"{table_name}.{column_name} not found") from ke
index_columns_ref = []
for idx_table_name,idx_column_name in loa_index_columns:
try:
index_columns_ref.append(get_col_ref(idx_table_name,idx_column_name))
except KeyError as ke:
raise exceptions.ConfigError(f"Index column for {loa_table}"
f" {idx_table_name}.{idx_column_name} not found")
all_columns = list(set(index_columns_ref+[column_ref]))
names = [c.table.name + "_" + c.name for c in all_columns]
aggregates = False
# Compute joins (+ agg)
join = []
joined = set()
for idx,c in enumerate(all_columns):
try:
path = shortest_path(network, loa_table, c.table)
except NetworkXNoPath:
try:
assert agg_fn in definitions.AGGREGATION_FUNCTIONS
except AssertionError:
raise exceptions.AggregationNameError(
f"Aggregation function {agg_fn} "
"is not available. "
"Available functions are: "
f"{', '.join(definitions.AGGREGATION_FUNCTIONS)}."
)
aggregates = True
path = shortest_path(network,c.table, loa_table)
path.reverse()
all_columns[idx] = getattr(sa.func,agg_fn)(c)
names[idx] = names[idx]+"_"+agg_fn
prev = loa_table
for table in path[1:]:
if table not in joined:
try:
con = network[prev][table]
join.append(class_partial("join",table,con["reference"]==con["referent"]))
except KeyError:
con = network[table][prev]
join.append(class_partial("join",table,con["referent"]==con["reference"]))
joined = joined.union({table})
else:
pass
prev = table
# Selects
all_columns = [col.label(name) for col,name in zip(all_columns,names)]
select = [class_partial("add_columns",col) for col in all_columns]
# Aggregation
if aggregates:
group_by = [class_partial("group_by",c) for c in index_columns_ref]
else:
group_by = []
logger.debug("%s selects",len(select))
logger.debug("%s joins",len(join))
logger.debug("%s groupbys",len(group_by))
return chain(select,[class_partial("select_from",loa_table)],join,group_by)
def query_with_ops(query,op_composer,*args,**kwargs):
for op in op_composer(*args,**kwargs):
query = op(query)
return query
| import logging
from typing import Dict
import enum
from itertools import chain
import networkx as nx
from networkx.exception import NetworkXNoPath
from networkx.algorithms.shortest_paths import shortest_path
import sqlalchemy as sa
from . import exceptions, definitions
logger = logging.getLogger(__name__)
def class_partial(method,*args,**kwargs):
def undotted(instance):
return getattr(instance,method)(*args,**kwargs)
return undotted
class Direction(enum.Enum):
forwards = 1
backwards = 2
equal = 3
def join_network(tables:Dict[str,sa.Table])->nx.DiGraph:
"""
Creates a directed graph of the FK->Referent relationships present in a
list of tables. This graph can then be traversed to figure out how to
perform a join when retrieving data from this collection of tables.
"""
digraph = nx.DiGraph()
def get_fk_tables(fk):
return [tbl for tbl in tables.values() if fk.references(tbl)]
for table in tables.values():
for fk in table.foreign_keys:
try:
ref_table = get_fk_tables(fk)[-1]
except IndexError:
logger.debug("No table found for fk: %s",str(fk))
continue
digraph.add_edge(
table,
ref_table,
reference=fk.parent,
referent=fk.column
)
if {fk.parent} == set(table.primary_key):
digraph.add_edge(
ref_table,
table,
reference=fk.column,
referent=fk.parent,
)
logger.debug("Database is a digraph with %s nodes",len(digraph.nodes))
return digraph
def compose_join(network,loa_name,table_name,column_name,loa_index_columns,agg_fn="avg"):
"""
compose_join
Creates a list of operations that can be applied to a Query object, making
it retrieve data at a certain LOA
:param network: A networkx graph representing a database
:param loa_name: The name of the LOA to retrieve data at
:param table_name: The name of the table from which to retrieve the data
:param column_name: The name of the column to retrieve
:param agg_fn: If the retrieval op. needs to aggregate data, if will do so with this function
:returns: An iterator containing functions to be applied to a Query object
:raises QueryError: If table_name.column_name does not exist in the DB
:raises ConfigError: If the requested loa is not configured
"""
lookup = {tbl.name:tbl for tbl in network}
get_col_ref = lambda tbl,name: lookup[tbl].c[name]#.label(tbl+"_"+name)
loa_table = lookup[loa_name]
try:
column_ref = get_col_ref(table_name,column_name)
except KeyError as ke:
raise exceptions.QueryError(f"{table_name}.{column_name} not found") from ke
index_columns_ref = []
for idx_table_name,idx_column_name in loa_index_columns:
try:
index_columns_ref.append(get_col_ref(idx_table_name,idx_column_name))
except KeyError as ke:
raise exceptions.ConfigError(f"Index column for {loa_table}"
f" {idx_table_name}.{idx_column_name} not found")
all_columns = list(set(index_columns_ref+[column_ref]))
names = [c.table.name + "_" + c.name for c in all_columns]
aggregates = False
# Compute joins (+ agg)
join = []
joined = set()
for idx,c in enumerate(all_columns):
try:
path = shortest_path(network, loa_table, c.table)
except NetworkXNoPath:
try:
assert agg_fn in definitions.AGGREGATION_FUNCTIONS
except AssertionError:
raise exceptions.AggregationNameError(
f"Aggregation function {agg_fn} "
"is not available. "
"Available functions are: "
f"{', '.join(definitions.AGGREGATION_FUNCTIONS)}."
)
aggregates = True
path = shortest_path(network,c.table, loa_table)
path.reverse()
all_columns[idx] = getattr(sa.func,agg_fn)(c)
names[idx] = names[idx]+"_"+agg_fn
prev = loa_table
for table in path[1:]:
if table not in joined:
try:
con = network[prev][table]
join.append(class_partial("join",table,con["reference"]==con["referent"]))
except KeyError:
con = network[table][prev]
join.append(class_partial("join",table,con["referent"]==con["reference"]))
joined = joined.union({table})
else:
pass
prev = table
# Selects
all_columns = [col.label(name) for col,name in zip(all_columns,names)]
select = [class_partial("add_columns",col) for col in all_columns]
# Aggregation
if aggregates:
group_by = [class_partial("group_by",c) for c in index_columns_ref]
else:
group_by = []
logger.debug("%s selects",len(select))
logger.debug("%s joins",len(join))
logger.debug("%s groupbys",len(group_by))
return chain(select,[class_partial("select_from",loa_table)],join,group_by)
def query_with_ops(query,op_composer,*args,**kwargs):
for op in op_composer(*args,**kwargs):
query = op(query)
return query
| en | 0.809522 | Creates a directed graph of the FK->Referent relationships present in a list of tables. This graph can then be traversed to figure out how to perform a join when retrieving data from this collection of tables. compose_join Creates a list of operations that can be applied to a Query object, making it retrieve data at a certain LOA :param network: A networkx graph representing a database :param loa_name: The name of the LOA to retrieve data at :param table_name: The name of the table from which to retrieve the data :param column_name: The name of the column to retrieve :param agg_fn: If the retrieval op. needs to aggregate data, if will do so with this function :returns: An iterator containing functions to be applied to a Query object :raises QueryError: If table_name.column_name does not exist in the DB :raises ConfigError: If the requested loa is not configured #.label(tbl+"_"+name) # Compute joins (+ agg) # Selects # Aggregation | 2.578346 | 3 |
script.module.placenta/lib/resources/lib/sources/en/filmxy.py | parser4life/tantrumrepo | 1 | 6628046 | <reponame>parser4life/tantrumrepo<filename>script.module.placenta/lib/resources/lib/sources/en/filmxy.py
# NEEDS FIXING
# -*- coding: UTF-8 -*-
#######################################################################
# ----------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42):
# @tantrumdev wrote this file. As long as you retain this notice you
# can do whatever you want with this stuff. If we meet some day, and you think
# this stuff is worth it, you can buy me a beer in return. - Muad'Dib
# ----------------------------------------------------------------------------
#######################################################################
# Addon Name: Placenta
# Addon id: plugin.video.placenta
# Addon Provider: MuadDib
import re,urllib,urlparse,json,base64
from resources.lib.modules import cleantitle
from resources.lib.modules import client
from resources.lib.modules import directstream
from resources.lib.modules import source_utils
class source:
def __init__(self):
self.priority = 1
self.language = ['en']
self.domains = ['filmxy.cc,filmxy.me']
self.base_link = 'http://www.filmxy.cc'
self.search_link = '%s/wp-json/wp/v2/posts?search=%s'
def movie(self, imdb, title, localtitle, aliases, year):
try:
url = {'imdb': imdb, 'title': title, 'year': year}
url = urllib.urlencode(url)
return url
except:
return
def sources(self, url, hostDict, hostprDict):
sources = []
try:
if url == None: return
urldata = urlparse.parse_qs(url)
urldata = dict((i, urldata[i][0]) for i in urldata)
title = urldata['title'].replace(':', ' ').replace('-', ' ').lower()
year = urldata['year']
search_id = title.lower()
start_url = self.search_link % (self.base_link, search_id.replace(' ','%20'))
headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'}
html = client.request(start_url,headers=headers)
Links = re.compile('"post","link":"(.+?)","title".+?"rendered":"(.+?)"',re.DOTALL).findall(html)
for link,name in Links:
link = link.replace('\\','')
name = name.replace('&', '')
if title.lower() in name.lower():
if year in name:
holder = client.request(link,headers=headers)
dpage = re.compile('id="main-down".+?href="(.+?)"',re.DOTALL).findall(holder)[0]
sources = self.scrape_results(dpage, title, year)
return sources
return sources
except:
return sources
def scrape_results(self,url,title,year):
sources = []
try:
headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'}
html = client.request(url,headers=headers)
block720 = re.compile('class="links_720p"(.+?)</ul>',re.DOTALL).findall(html)
Links720 = re.compile('href="(.+?)"',re.DOTALL).findall(str(block720))
for link in Links720:
host = link.split('//')[1].replace('www.','')
host = host.split('/')[0].lower()
if host not in ['upload.af', 'upload.mn', 'uploadx.org']:
sources.append({'source':host,'quality':'720p','language': 'en','url':link,'info':[],'direct':False,'debridonly':False})
block1080 = re.compile('class="links_1080p"(.+?)</ul>',re.DOTALL).findall(html)
Links1080 = re.compile('href="(.+?)"',re.DOTALL).findall(str(block1080))
for link in Links1080:
host = link.split('//')[1].replace('www.','')
host = host.split('/')[0].lower()
if host not in ['upload.af', 'upload.mn', 'uploadx.org']:
sources.append({'source':host,'quality':'1080p','language': 'en','url':link,'info':[],'direct':False,'debridonly':False})
return sources
except:
return sources
def resolve(self, url):
return url | # NEEDS FIXING
# -*- coding: UTF-8 -*-
#######################################################################
# ----------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42):
# @tantrumdev wrote this file. As long as you retain this notice you
# can do whatever you want with this stuff. If we meet some day, and you think
# this stuff is worth it, you can buy me a beer in return. - Muad'Dib
# ----------------------------------------------------------------------------
#######################################################################
# Addon Name: Placenta
# Addon id: plugin.video.placenta
# Addon Provider: MuadDib
import re,urllib,urlparse,json,base64
from resources.lib.modules import cleantitle
from resources.lib.modules import client
from resources.lib.modules import directstream
from resources.lib.modules import source_utils
class source:
def __init__(self):
self.priority = 1
self.language = ['en']
self.domains = ['filmxy.cc,filmxy.me']
self.base_link = 'http://www.filmxy.cc'
self.search_link = '%s/wp-json/wp/v2/posts?search=%s'
def movie(self, imdb, title, localtitle, aliases, year):
try:
url = {'imdb': imdb, 'title': title, 'year': year}
url = urllib.urlencode(url)
return url
except:
return
def sources(self, url, hostDict, hostprDict):
sources = []
try:
if url == None: return
urldata = urlparse.parse_qs(url)
urldata = dict((i, urldata[i][0]) for i in urldata)
title = urldata['title'].replace(':', ' ').replace('-', ' ').lower()
year = urldata['year']
search_id = title.lower()
start_url = self.search_link % (self.base_link, search_id.replace(' ','%20'))
headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'}
html = client.request(start_url,headers=headers)
Links = re.compile('"post","link":"(.+?)","title".+?"rendered":"(.+?)"',re.DOTALL).findall(html)
for link,name in Links:
link = link.replace('\\','')
name = name.replace('&', '')
if title.lower() in name.lower():
if year in name:
holder = client.request(link,headers=headers)
dpage = re.compile('id="main-down".+?href="(.+?)"',re.DOTALL).findall(holder)[0]
sources = self.scrape_results(dpage, title, year)
return sources
return sources
except:
return sources
def scrape_results(self,url,title,year):
sources = []
try:
headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'}
html = client.request(url,headers=headers)
block720 = re.compile('class="links_720p"(.+?)</ul>',re.DOTALL).findall(html)
Links720 = re.compile('href="(.+?)"',re.DOTALL).findall(str(block720))
for link in Links720:
host = link.split('//')[1].replace('www.','')
host = host.split('/')[0].lower()
if host not in ['upload.af', 'upload.mn', 'uploadx.org']:
sources.append({'source':host,'quality':'720p','language': 'en','url':link,'info':[],'direct':False,'debridonly':False})
block1080 = re.compile('class="links_1080p"(.+?)</ul>',re.DOTALL).findall(html)
Links1080 = re.compile('href="(.+?)"',re.DOTALL).findall(str(block1080))
for link in Links1080:
host = link.split('//')[1].replace('www.','')
host = host.split('/')[0].lower()
if host not in ['upload.af', 'upload.mn', 'uploadx.org']:
sources.append({'source':host,'quality':'1080p','language': 'en','url':link,'info':[],'direct':False,'debridonly':False})
return sources
except:
return sources
def resolve(self, url):
return url | en | 0.462615 | # NEEDS FIXING # -*- coding: UTF-8 -*- ####################################################################### # ---------------------------------------------------------------------------- # "THE BEER-WARE LICENSE" (Revision 42): # @tantrumdev wrote this file. As long as you retain this notice you # can do whatever you want with this stuff. If we meet some day, and you think # this stuff is worth it, you can buy me a beer in return. - Muad'Dib # ---------------------------------------------------------------------------- ####################################################################### # Addon Name: Placenta # Addon id: plugin.video.placenta # Addon Provider: MuadDib #038;', '') | 1.998252 | 2 |
problem_3_parenting_partnering.py | ahmdshrif/codeJam2020 | 0 | 6628047 | <filename>problem_3_parenting_partnering.py
#read inputs
num_of_cases = int(input())
def is_time_overlab (calender , time2):
St2 = time2[0]
Et2 = time2[1]
for i in range(St2,Et2):
if i in calender :
return True
return False
def add_to_clender(calender , time2):
St2 = time2[0]
Et2 = time2[1]
for i in range(St2,Et2):
calender.add(i)
for case in range(num_of_cases) :
num_of_activities = int(input())
activities = [[]for i in range(num_of_activities)]
for i in range(num_of_activities) :
activities[i] = list(map(int, (input()+" " + str(i)).strip().split()))
activities.sort()
# print(activities)
result = ["" for i in range(num_of_activities)]
J_calender = set()
C_calender = set()
IMPOSSIBLE = False
for i in range(num_of_activities):
if not(is_time_overlab(J_calender , activities[i])):
result[activities[i][2]] = "J"
add_to_clender(J_calender , activities[i])
elif not(is_time_overlab(C_calender , activities[i])):
add_to_clender(C_calender , activities[i])
result[activities[i][2]] = "C"
else :
IMPOSSIBLE = True
# result = "IMPOSSIBLE"
break
if IMPOSSIBLE :
print("Case #{}: {}".format(case+1, "IMPOSSIBLE" ), flush = True)
else:
print("Case #{}: {}".format(case+1, "".join(result) ), flush = True) | <filename>problem_3_parenting_partnering.py
#read inputs
num_of_cases = int(input())
def is_time_overlab (calender , time2):
St2 = time2[0]
Et2 = time2[1]
for i in range(St2,Et2):
if i in calender :
return True
return False
def add_to_clender(calender , time2):
St2 = time2[0]
Et2 = time2[1]
for i in range(St2,Et2):
calender.add(i)
for case in range(num_of_cases) :
num_of_activities = int(input())
activities = [[]for i in range(num_of_activities)]
for i in range(num_of_activities) :
activities[i] = list(map(int, (input()+" " + str(i)).strip().split()))
activities.sort()
# print(activities)
result = ["" for i in range(num_of_activities)]
J_calender = set()
C_calender = set()
IMPOSSIBLE = False
for i in range(num_of_activities):
if not(is_time_overlab(J_calender , activities[i])):
result[activities[i][2]] = "J"
add_to_clender(J_calender , activities[i])
elif not(is_time_overlab(C_calender , activities[i])):
add_to_clender(C_calender , activities[i])
result[activities[i][2]] = "C"
else :
IMPOSSIBLE = True
# result = "IMPOSSIBLE"
break
if IMPOSSIBLE :
print("Case #{}: {}".format(case+1, "IMPOSSIBLE" ), flush = True)
else:
print("Case #{}: {}".format(case+1, "".join(result) ), flush = True) | en | 0.572532 | #read inputs # print(activities) # result = "IMPOSSIBLE" #{}: {}".format(case+1, "IMPOSSIBLE" ), flush = True) #{}: {}".format(case+1, "".join(result) ), flush = True) | 3.620106 | 4 |
ritsukosay.py | d3suu/ritsukosay | 0 | 6628048 | #!/usr/bin/python3
import sys
# MIT License
#
# Copyright (c) 2021 <NAME>
#
# 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.
# ASCII art was made using https://asciiart.club/ and sketch from Groundwork of EVANGELION Vol. 1 or 2
ritsuko = """
»∞╓.⌐~─^ ª«▄ ▄e
]æ y. ═█º-▄
«Ö└7▀█ ╢ ▄ ▌▐ ▀
x" , ║ `⌐ ║ ║ ( ▀▒▄
∩ xº ╚"╤ ▐( ▌ ▌ ┤ ▐ `% ºº-─~⌐
x æV ▌ ▒⌠▐ █ ▌ b│ ╡ ╙ ¥«▄
┌█ Æ╓ █⌐▌∩╢ ▌▌ └ Ñ└ ∩ ▌ ""ⁿ«▄
╓T⌐ ▀┌ ▀£▌█▓╝▄ ██ ▐ ¥b ▐ ╣ b
╓╬∩ É▒Ö █┌╓╝ \ ▀▓ p ▓ └ ▓ ▄▄▄,. ¥
╣█ ▓└█▓ ▒ █ !═█* ╫ ▐ █▄ ▒(░ ╒ ▌ ▒Ö╖ Y
(▀.▀ .╗█ ╓.f (╫█Ñp▐ ▒▒ ▌▒ # .▒▌( ▌ ▌ ▌ k▐
▓▀ ▒╝▌┌█╒ ▐█-▓└ M▒█ M█. (▌ ┌ ╗▌ ⌐█ ▒ ▌ █
▀ █ ▌█▒∩ .⌐∞"ⁿ▀▄▄ ∩▒\▀ . ▓ Ñ ╒█ ▌█ ╓ p▌ ` ╙▒└╩▄
██▀▒▄#æ▒p╔█▒▄ ⁿ ▄⌐▓ █ Γ└ƒ▓ ▐ ▀ █ ║▒ p ▄▀╝N ▄
█▐ ▀╙ █▀████▄ ▐█"╙██▒▌╓─▀▓╝.─ ▒Y O ¼ ╙ ▒QU' █
▐ ⁿ"▓▀ ▀█▄ Ö δ ▀█▌▓█ ▌ 7 ╙ k \ ▐ p ▌
/ █ ╓██═( U∩▐█ █ ║█ └▄ % ∩y ▄└ ▒
▄⌐^" ▓▒─ª ▐ ██▀ ▓ ╢▄ ▐▄ \| µ ▐ ¥ ─
▄ █▌ ╣▀,╢█-╝▄ ▀▒ ( ▌ j
½╖ ▓º ║ /█▀██ ▒└▀█≥┐ Ö╕ └ { ▐
└⌐ ▀ .ÖQ"█╬▐∞¬╢ ╫ ▐▄ └ u k ▐py ╘▐
(▄ ╒ ▀ ▌- ▄█ ▐ ▌ k p φ ╘ ▓
▀█▒ └▄▄▄⌐▄" t ⌐ , ╙▄∩▒ ▀
▀ , « ╫█▄▄╧▌ ∩µ ╞ `▄ ╞ └ └▄ ▌
╒Ü▓▓▀▒ (¬ ⌐ ▐└ p ╙ ▒ ▐ ▐
─ Æ▒█▀ █ ╒█ B k ▐ ▀ ,╙ ▌╫
┘ ╓Ö ▀█▄╗██ ▐▐⌐▄ k ▄ h ▌ ╠ ▐█
╓ .,⌐- ▄∞Ö ╓7 ▓- █ │ ▒M ╘ ▌ ▐ Ñ ∩▓ █
╘▄ ~∞*^'"" ". / ╡ ▐▐ ∩ ═ b µ█ ▒ ▌ {▓ ▌
"╬▀ⁿ«▄▄▄ , Ö █ .▄ ─( . ▓▒▒ ╣ ▌ █▌▐ ▌
└. └º╖ 6 ⌐─^╫██▌╠██( ╬B .▓ ▒▓ ▒ █M █ ▀▒ ▌=
V ,~`W █ ▌█└╣█▐.▌ ╬│▓ └ p▌├ ▐ ▒▓▐ ▀
,^ .ª █ █▐∩ ▌▀ █ `▌ k╚ `Ñ
à─" .∞" █ └
⌐^Ü ,ⁿ ┌" █
«▄╣ ▄ / ▀
½╙,% ╫ # ⌐ ⌐▀█
b└⌐½ (⌐ ╒+ æ"▄ⁿ.▄▄∞▀ºº¬─╫
φ ▄∩ ▒ ▒ ∩ ▄O»æ▀T . ▒
U└╣ C ╙ ▄⌐e[åÑ*º" ¥
▓ ▌∩] .#æ╝^/ ▒
▄█ █a▌▀╙ ▌
▄∩▓█▌█#▌Ö ,─*#"º╙└└. .^*∞∞»▄\"\"\"\"\"^^*─▀««▄
"""
message = sys.argv[1:]
# Without arguments, print only Ritsuko
if len(message) == 0:
print(ritsuko)
quit()
# If message is longer than 40 characters, split it into lines
strMessage = " ".join(message)
newMessage = []
while len(strMessage) > 40:
x = 40
# From 40th character in strMessage, move back and check if character is space
while len(strMessage) != 0:
if " " not in strMessage:
newMessage.append(strMessage)
break
if strMessage[x] == " ":
# If it is, append it as new line, and remove this part from strMessage. Repeat.
newMessage.append(strMessage[:x])
strMessage = strMessage[x+1:]
break
else:
x -= 1
# If strMessage is shorter than 40 characters, just append it
newMessage.append(strMessage)
# Split Ritsuko
ritsukoSplit = ritsuko.splitlines()
# Print full
print(" " + "_"*42 + " " + ritsukoSplit[0])
print("/" + " "*42 + "\\" + ritsukoSplit[1])
a = 2
for strMessage in newMessage:
strLen = len(strMessage)
print("| " + strMessage + " "*(40-strLen) + " |" + ritsukoSplit[a])
a += 1
print("\\" + "_"*36 + " "*4 + "_"*2 + "/" + ritsukoSplit[a])
print(" "*37 + "\ |" + " "*3 + ritsukoSplit[a+1])
print(" "*37 + " \ |" + " "*3 + ritsukoSplit[a+2])
print(" "*37 + " \|" + " "*3 + ritsukoSplit[a+3])
# ^I think this code is bad, Magi would be straight up mad for executing something like this
# Print rest of Ritsuko
for line in ritsukoSplit[a+4:]:
print(" "*44 + line);
| #!/usr/bin/python3
import sys
# MIT License
#
# Copyright (c) 2021 <NAME>
#
# 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.
# ASCII art was made using https://asciiart.club/ and sketch from Groundwork of EVANGELION Vol. 1 or 2
ritsuko = """
»∞╓.⌐~─^ ª«▄ ▄e
]æ y. ═█º-▄
«Ö└7▀█ ╢ ▄ ▌▐ ▀
x" , ║ `⌐ ║ ║ ( ▀▒▄
∩ xº ╚"╤ ▐( ▌ ▌ ┤ ▐ `% ºº-─~⌐
x æV ▌ ▒⌠▐ █ ▌ b│ ╡ ╙ ¥«▄
┌█ Æ╓ █⌐▌∩╢ ▌▌ └ Ñ└ ∩ ▌ ""ⁿ«▄
╓T⌐ ▀┌ ▀£▌█▓╝▄ ██ ▐ ¥b ▐ ╣ b
╓╬∩ É▒Ö █┌╓╝ \ ▀▓ p ▓ └ ▓ ▄▄▄,. ¥
╣█ ▓└█▓ ▒ █ !═█* ╫ ▐ █▄ ▒(░ ╒ ▌ ▒Ö╖ Y
(▀.▀ .╗█ ╓.f (╫█Ñp▐ ▒▒ ▌▒ # .▒▌( ▌ ▌ ▌ k▐
▓▀ ▒╝▌┌█╒ ▐█-▓└ M▒█ M█. (▌ ┌ ╗▌ ⌐█ ▒ ▌ █
▀ █ ▌█▒∩ .⌐∞"ⁿ▀▄▄ ∩▒\▀ . ▓ Ñ ╒█ ▌█ ╓ p▌ ` ╙▒└╩▄
██▀▒▄#æ▒p╔█▒▄ ⁿ ▄⌐▓ █ Γ└ƒ▓ ▐ ▀ █ ║▒ p ▄▀╝N ▄
█▐ ▀╙ █▀████▄ ▐█"╙██▒▌╓─▀▓╝.─ ▒Y O ¼ ╙ ▒QU' █
▐ ⁿ"▓▀ ▀█▄ Ö δ ▀█▌▓█ ▌ 7 ╙ k \ ▐ p ▌
/ █ ╓██═( U∩▐█ █ ║█ └▄ % ∩y ▄└ ▒
▄⌐^" ▓▒─ª ▐ ██▀ ▓ ╢▄ ▐▄ \| µ ▐ ¥ ─
▄ █▌ ╣▀,╢█-╝▄ ▀▒ ( ▌ j
½╖ ▓º ║ /█▀██ ▒└▀█≥┐ Ö╕ └ { ▐
└⌐ ▀ .ÖQ"█╬▐∞¬╢ ╫ ▐▄ └ u k ▐py ╘▐
(▄ ╒ ▀ ▌- ▄█ ▐ ▌ k p φ ╘ ▓
▀█▒ └▄▄▄⌐▄" t ⌐ , ╙▄∩▒ ▀
▀ , « ╫█▄▄╧▌ ∩µ ╞ `▄ ╞ └ └▄ ▌
╒Ü▓▓▀▒ (¬ ⌐ ▐└ p ╙ ▒ ▐ ▐
─ Æ▒█▀ █ ╒█ B k ▐ ▀ ,╙ ▌╫
┘ ╓Ö ▀█▄╗██ ▐▐⌐▄ k ▄ h ▌ ╠ ▐█
╓ .,⌐- ▄∞Ö ╓7 ▓- █ │ ▒M ╘ ▌ ▐ Ñ ∩▓ █
╘▄ ~∞*^'"" ". / ╡ ▐▐ ∩ ═ b µ█ ▒ ▌ {▓ ▌
"╬▀ⁿ«▄▄▄ , Ö █ .▄ ─( . ▓▒▒ ╣ ▌ █▌▐ ▌
└. └º╖ 6 ⌐─^╫██▌╠██( ╬B .▓ ▒▓ ▒ █M █ ▀▒ ▌=
V ,~`W █ ▌█└╣█▐.▌ ╬│▓ └ p▌├ ▐ ▒▓▐ ▀
,^ .ª █ █▐∩ ▌▀ █ `▌ k╚ `Ñ
à─" .∞" █ └
⌐^Ü ,ⁿ ┌" █
«▄╣ ▄ / ▀
½╙,% ╫ # ⌐ ⌐▀█
b└⌐½ (⌐ ╒+ æ"▄ⁿ.▄▄∞▀ºº¬─╫
φ ▄∩ ▒ ▒ ∩ ▄O»æ▀T . ▒
U└╣ C ╙ ▄⌐e[åÑ*º" ¥
▓ ▌∩] .#æ╝^/ ▒
▄█ █a▌▀╙ ▌
▄∩▓█▌█#▌Ö ,─*#"º╙└└. .^*∞∞»▄\"\"\"\"\"^^*─▀««▄
"""
message = sys.argv[1:]
# Without arguments, print only Ritsuko
if len(message) == 0:
print(ritsuko)
quit()
# If message is longer than 40 characters, split it into lines
strMessage = " ".join(message)
newMessage = []
while len(strMessage) > 40:
x = 40
# From 40th character in strMessage, move back and check if character is space
while len(strMessage) != 0:
if " " not in strMessage:
newMessage.append(strMessage)
break
if strMessage[x] == " ":
# If it is, append it as new line, and remove this part from strMessage. Repeat.
newMessage.append(strMessage[:x])
strMessage = strMessage[x+1:]
break
else:
x -= 1
# If strMessage is shorter than 40 characters, just append it
newMessage.append(strMessage)
# Split Ritsuko
ritsukoSplit = ritsuko.splitlines()
# Print full
print(" " + "_"*42 + " " + ritsukoSplit[0])
print("/" + " "*42 + "\\" + ritsukoSplit[1])
a = 2
for strMessage in newMessage:
strLen = len(strMessage)
print("| " + strMessage + " "*(40-strLen) + " |" + ritsukoSplit[a])
a += 1
print("\\" + "_"*36 + " "*4 + "_"*2 + "/" + ritsukoSplit[a])
print(" "*37 + "\ |" + " "*3 + ritsukoSplit[a+1])
print(" "*37 + " \ |" + " "*3 + ritsukoSplit[a+2])
print(" "*37 + " \|" + " "*3 + ritsukoSplit[a+3])
# ^I think this code is bad, Magi would be straight up mad for executing something like this
# Print rest of Ritsuko
for line in ritsukoSplit[a+4:]:
print(" "*44 + line);
| en | 0.573729 | #!/usr/bin/python3 # MIT License # # Copyright (c) 2021 <NAME> # # 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. # ASCII art was made using https://asciiart.club/ and sketch from Groundwork of EVANGELION Vol. 1 or 2 »∞╓.⌐~─^ ª«▄ ▄e ]æ y. ═█º-▄ «Ö└7▀█ ╢ ▄ ▌▐ ▀ x" , ║ `⌐ ║ ║ ( ▀▒▄ ∩ xº ╚"╤ ▐( ▌ ▌ ┤ ▐ `% ºº-─~⌐ x æV ▌ ▒⌠▐ █ ▌ b│ ╡ ╙ ¥«▄ ┌█ Æ╓ █⌐▌∩╢ ▌▌ └ Ñ└ ∩ ▌ ""ⁿ«▄ ╓T⌐ ▀┌ ▀£▌█▓╝▄ ██ ▐ ¥b ▐ ╣ b ╓╬∩ É▒Ö █┌╓╝ \ ▀▓ p ▓ └ ▓ ▄▄▄,. ¥ ╣█ ▓└█▓ ▒ █ !═█* ╫ ▐ █▄ ▒(░ ╒ ▌ ▒Ö╖ Y (▀.▀ .╗█ ╓.f (╫█Ñp▐ ▒▒ ▌▒ # .▒▌( ▌ ▌ ▌ k▐ ▓▀ ▒╝▌┌█╒ ▐█-▓└ M▒█ M█. (▌ ┌ ╗▌ ⌐█ ▒ ▌ █ ▀ █ ▌█▒∩ .⌐∞"ⁿ▀▄▄ ∩▒\▀ . ▓ Ñ ╒█ ▌█ ╓ p▌ ` ╙▒└╩▄ ██▀▒▄#æ▒p╔█▒▄ ⁿ ▄⌐▓ █ Γ└ƒ▓ ▐ ▀ █ ║▒ p ▄▀╝N ▄ █▐ ▀╙ █▀████▄ ▐█"╙██▒▌╓─▀▓╝.─ ▒Y O ¼ ╙ ▒QU' █ ▐ ⁿ"▓▀ ▀█▄ Ö δ ▀█▌▓█ ▌ 7 ╙ k \ ▐ p ▌ / █ ╓██═( U∩▐█ █ ║█ └▄ % ∩y ▄└ ▒ ▄⌐^" ▓▒─ª ▐ ██▀ ▓ ╢▄ ▐▄ \| µ ▐ ¥ ─ ▄ █▌ ╣▀,╢█-╝▄ ▀▒ ( ▌ j ½╖ ▓º ║ /█▀██ ▒└▀█≥┐ Ö╕ └ { ▐ └⌐ ▀ .ÖQ"█╬▐∞¬╢ ╫ ▐▄ └ u k ▐py ╘▐ (▄ ╒ ▀ ▌- ▄█ ▐ ▌ k p φ ╘ ▓ ▀█▒ └▄▄▄⌐▄" t ⌐ , ╙▄∩▒ ▀ ▀ , « ╫█▄▄╧▌ ∩µ ╞ `▄ ╞ └ └▄ ▌ ╒Ü▓▓▀▒ (¬ ⌐ ▐└ p ╙ ▒ ▐ ▐ ─ Æ▒█▀ █ ╒█ B k ▐ ▀ ,╙ ▌╫ ┘ ╓Ö ▀█▄╗██ ▐▐⌐▄ k ▄ h ▌ ╠ ▐█ ╓ .,⌐- ▄∞Ö ╓7 ▓- █ │ ▒M ╘ ▌ ▐ Ñ ∩▓ █ ╘▄ ~∞*^'"" ". / ╡ ▐▐ ∩ ═ b µ█ ▒ ▌ {▓ ▌ "╬▀ⁿ«▄▄▄ , Ö █ .▄ ─( . ▓▒▒ ╣ ▌ █▌▐ ▌ └. └º╖ 6 ⌐─^╫██▌╠██( ╬B .▓ ▒▓ ▒ █M █ ▀▒ ▌= V ,~`W █ ▌█└╣█▐.▌ ╬│▓ └ p▌├ ▐ ▒▓▐ ▀ ,^ .ª █ █▐∩ ▌▀ █ `▌ k╚ `Ñ à─" .∞" █ └ ⌐^Ü ,ⁿ ┌" █ «▄╣ ▄ / ▀ ½╙,% ╫ # ⌐ ⌐▀█ b└⌐½ (⌐ ╒+ æ"▄ⁿ.▄▄∞▀ºº¬─╫ φ ▄∩ ▒ ▒ ∩ ▄O»æ▀T . ▒ U└╣ C ╙ ▄⌐e[åÑ*º" ¥ ▓ ▌∩] .#æ╝^/ ▒ ▄█ █a▌▀╙ ▌ ▄∩▓█▌█#▌Ö ,─*#"º╙└└. .^*∞∞»▄\"\"\"\"\"^^*─▀««▄ # Without arguments, print only Ritsuko # If message is longer than 40 characters, split it into lines # From 40th character in strMessage, move back and check if character is space # If it is, append it as new line, and remove this part from strMessage. Repeat. # If strMessage is shorter than 40 characters, just append it # Split Ritsuko # Print full # ^I think this code is bad, Magi would be straight up mad for executing something like this # Print rest of Ritsuko | 1.699924 | 2 |
anaconda_project/internal/cli/download_commands.py | kathatherine/anaconda-project | 188 | 6628049 | <gh_stars>100-1000
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2016, Anaconda, Inc. All rights reserved.
#
# Licensed under the terms of the BSD 3-Clause License.
# The full license is in the file LICENSE.txt, distributed with this software.
# -----------------------------------------------------------------------------
"""Commands related to the downloads section."""
from __future__ import absolute_import, print_function
import sys
from anaconda_project.internal.cli.project_load import load_project
from anaconda_project import project_ops
from anaconda_project.internal.cli import console_utils
from anaconda_project.prepare import prepare_without_interaction
from anaconda_project.provide import PROVIDE_MODE_CHECK
def add_download(project_dir, env_spec_name, filename_variable, download_url, filename, hash_algorithm, hash_value):
"""Add an item to the downloads section."""
project = load_project(project_dir)
if (hash_algorithm or hash_value) and not bool(hash_algorithm and hash_value):
print("Error: mutually dependant parameters: --hash-algorithm and --hash-value.", file=sys.stderr)
return 1
status = project_ops.add_download(project,
env_spec_name=env_spec_name,
env_var=filename_variable,
url=download_url,
filename=filename,
hash_algorithm=hash_algorithm,
hash_value=hash_value)
if status:
print(status.status_description)
print("Added %s to the project file." % download_url)
return 0
else:
console_utils.print_status_errors(status)
return 1
def remove_download(project_dir, env_spec_name, filename_variable):
"""Remove a download requirement from project and from file system."""
project = load_project(project_dir)
# we can remove a download even if prepare fails, so disable
# printing errors in the frontend.
with project.null_frontend():
result = prepare_without_interaction(project, env_spec_name=env_spec_name, mode=PROVIDE_MODE_CHECK)
status = project_ops.remove_download(project,
env_spec_name=env_spec_name,
env_var=filename_variable,
prepare_result=result)
if status:
print(status.status_description)
print("Removed {} from the project file.".format(filename_variable))
return 0
else:
console_utils.print_status_errors(status)
return 1
def list_downloads(project_dir, env_spec_name):
"""List the downloads present in project."""
project = load_project(project_dir)
if console_utils.print_project_problems(project):
return 1
if project.downloads(env_spec_name):
print("Downloads for project: {}\n".format(project_dir))
console_utils.print_names_and_descriptions(project.download_requirements(env_spec_name), name_attr='title')
else:
print("No downloads found in project.")
return 0
def main_add(args):
"""Start the download command and return exit status code."""
return add_download(args.directory, args.env_spec, args.filename_variable, args.download_url, args.filename,
args.hash_algorithm, args.hash_value)
def main_remove(args):
"""Start the remove download command and return exit status code."""
return remove_download(args.directory, args.env_spec, args.filename_variable)
def main_list(args):
"""Start the list download command and return exit status code."""
return list_downloads(args.directory, args.env_spec)
| # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2016, Anaconda, Inc. All rights reserved.
#
# Licensed under the terms of the BSD 3-Clause License.
# The full license is in the file LICENSE.txt, distributed with this software.
# -----------------------------------------------------------------------------
"""Commands related to the downloads section."""
from __future__ import absolute_import, print_function
import sys
from anaconda_project.internal.cli.project_load import load_project
from anaconda_project import project_ops
from anaconda_project.internal.cli import console_utils
from anaconda_project.prepare import prepare_without_interaction
from anaconda_project.provide import PROVIDE_MODE_CHECK
def add_download(project_dir, env_spec_name, filename_variable, download_url, filename, hash_algorithm, hash_value):
"""Add an item to the downloads section."""
project = load_project(project_dir)
if (hash_algorithm or hash_value) and not bool(hash_algorithm and hash_value):
print("Error: mutually dependant parameters: --hash-algorithm and --hash-value.", file=sys.stderr)
return 1
status = project_ops.add_download(project,
env_spec_name=env_spec_name,
env_var=filename_variable,
url=download_url,
filename=filename,
hash_algorithm=hash_algorithm,
hash_value=hash_value)
if status:
print(status.status_description)
print("Added %s to the project file." % download_url)
return 0
else:
console_utils.print_status_errors(status)
return 1
def remove_download(project_dir, env_spec_name, filename_variable):
"""Remove a download requirement from project and from file system."""
project = load_project(project_dir)
# we can remove a download even if prepare fails, so disable
# printing errors in the frontend.
with project.null_frontend():
result = prepare_without_interaction(project, env_spec_name=env_spec_name, mode=PROVIDE_MODE_CHECK)
status = project_ops.remove_download(project,
env_spec_name=env_spec_name,
env_var=filename_variable,
prepare_result=result)
if status:
print(status.status_description)
print("Removed {} from the project file.".format(filename_variable))
return 0
else:
console_utils.print_status_errors(status)
return 1
def list_downloads(project_dir, env_spec_name):
"""List the downloads present in project."""
project = load_project(project_dir)
if console_utils.print_project_problems(project):
return 1
if project.downloads(env_spec_name):
print("Downloads for project: {}\n".format(project_dir))
console_utils.print_names_and_descriptions(project.download_requirements(env_spec_name), name_attr='title')
else:
print("No downloads found in project.")
return 0
def main_add(args):
"""Start the download command and return exit status code."""
return add_download(args.directory, args.env_spec, args.filename_variable, args.download_url, args.filename,
args.hash_algorithm, args.hash_value)
def main_remove(args):
"""Start the remove download command and return exit status code."""
return remove_download(args.directory, args.env_spec, args.filename_variable)
def main_list(args):
"""Start the list download command and return exit status code."""
return list_downloads(args.directory, args.env_spec) | en | 0.731911 | # -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) 2016, Anaconda, Inc. All rights reserved. # # Licensed under the terms of the BSD 3-Clause License. # The full license is in the file LICENSE.txt, distributed with this software. # ----------------------------------------------------------------------------- Commands related to the downloads section. Add an item to the downloads section. Remove a download requirement from project and from file system. # we can remove a download even if prepare fails, so disable # printing errors in the frontend. List the downloads present in project. Start the download command and return exit status code. Start the remove download command and return exit status code. Start the list download command and return exit status code. | 1.961016 | 2 |
geotext/__init__.py | bbo2adwuff/geotext | 102 | 6628050 | <reponame>bbo2adwuff/geotext
# -*- coding: utf-8 -*-
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__version__ = '0.2.0'
from .geotext import GeoText | # -*- coding: utf-8 -*-
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__version__ = '0.2.0'
from .geotext import GeoText | en | 0.769321 | # -*- coding: utf-8 -*- | 1.148511 | 1 |