hexsha stringlengths 40 40 | size int64 2 1.02M | ext stringclasses 10
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 245 | max_stars_repo_name stringlengths 6 130 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 245 | max_issues_repo_name stringlengths 6 130 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 245 | max_forks_repo_name stringlengths 6 130 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 2 1.02M | avg_line_length float64 1 417k | max_line_length int64 1 987k | alphanum_fraction float64 0 1 | content_no_comment stringlengths 0 1.01M | is_comment_constant_removed bool 1
class | is_sharp_comment_removed bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f73138dea25be614ca8fc1cc6c899fbfc0321a36 | 6,537 | py | Python | car_client.py | wangbiao0327/car | 2632de357107beeb240b330f20ec5ac5fb568beb | [
"MIT"
] | 1 | 2018-12-18T10:58:34.000Z | 2018-12-18T10:58:34.000Z | car_client.py | wangbiao0327/car | 2632de357107beeb240b330f20ec5ac5fb568beb | [
"MIT"
] | null | null | null | car_client.py | wangbiao0327/car | 2632de357107beeb240b330f20ec5ac5fb568beb | [
"MIT"
] | null | null | null | """
此模块做停车管理系统的客户端
Author:Recall
Date: 2018-10-19
module: socket、multiprocessing、sys、os、time、signal
Email:
"""
from socket import *
from setting import *
from messageAff import user_message
from multiprocessing import Process
import sys,os,time,signal
class carClient(object):
def __init__(self):
self.sockfd = socket(AF_INET,SOCK_STREAM)
self.sockfd.connect(ADDR)
self.mes = user_message()
signal.signal(signal.SIGINT,self.dis_signal)
def dis_signal(self,sig,frame):
if sig == signal.SIGINT:
self.sockfd.send(b'quit')
sys.exit("强制退出")
elif sig == signal.SIGQUIT:
self.sockfd.send(b'quit')
def Get_email_verify_code(self,username,email):
'''
获取验证码
将用户名跟邮箱发送到服务器进行数值判断,并根据判断进行返回
返回值:verify_code or False
'''
data = 'select_email %s %s'% (username,email)
self.sockfd.send(data.encode())
aff = self.sockfd.recv(1024).decode()
if aff == 'ok':
auth_code = self.mes.my_email(email)
return auth_code
else:
return [False,"你输入的邮箱与注册的邮箱不一致"]
def Modify_password(self, username, password):
'''
此函数用来处理密码的修改
参数:用户名 密码
将用户密码发送到服务器,根据服务器信息确认处理
返回值:True or False
'''
data = "change_password %s %s" % (username,password)
self.sockfd.send(data.encode())
aff = self.sockfd.recv(1024).decode()
if aff == "ok":
return True
return False
def Modify_username(self,olduesrname,newusername):
'''
此函数用来修改用户名称
参数:旧用户名 新用户名
将新旧用户名发送到服务器,并根据服务器返回值进行返回
返回值:
成功:True
失败:
[False,"用户名早已被使用"]
[False,'修改用户名失败']
'''
data = 'change_username %s %s' % (olduesrname,newusername)
self.sockfd.send(data.encode())
aff = self.sockfd.recv(1024).decode()
if aff == "ok":
return True
elif aff == "nameisuser":
return [False,"用户名早已被使用"]
return [False,'修改用户名失败']
def Personal_information_display(self,username):
'''
此函数用来获取用户信息
参数:用户名
向服务器发送用户名,通过服务器返回值进行返回
'''
data = "select_user_message %s" % username
self.sockfd.send(data.encode())
aff = self.sockfd.recv(1024).decode()
user_list = aff.split(" ")
if user_list[0] == "ok":
return user_list[1:]
return [False,"未找到用户信息"]
def Personal_information_edit(self,username,phone_number):
'''
此函数用来修改用户信息
参数:用户名 联系方式
发送到服务器修改用户的联系方式
返回值:True or False
'''
data = "change_user_message %s %s" % (username,phone_number)
self.sockfd.send(data.encode())
aff = self.sockfd.recv(1024).decode()
if aff == "ok":
return True
return True
def Select_history_recording(self,username,aff=0):
'''
向服务器获取用户历史记录
参数:用户名 偏识标量
aff:偏识标量,假设用户有十五条历史记录,传入aff=2则返回结果为用户第11条至第15条的历史记录
返回历史记录,每次返回5条,不足五条或五条返回全部历史记录
返回值:
有历史记录:[True,[],[]....],每个小列表为一条记录
无历史记录:[False]
'''
data = "get_history_msg %s %d" % (username,aff)
self.sockfd.send(data.encode())
aff = self.sockfd.recv(4096).decode()
history_list =[True]
if aff != "error":
history_str = aff.split(" ")
for i in history_str:
record = i.split("##")
history_list.append(record)
return history_list
return [False]
def Login(self,username,password):
'''
此类函数用处理用户登录
参数:用户名 密码
返回值:
成功:True
失败:
[False,"用户名或密码错误"]
[False,"你已经在线,不能重复登录"]
获取用户账号和密码,并发送给服务器
'''
message = 'login %s %s' % (username, password)
self.sockfd.send(message.encode())
aff = self.sockfd.recv(1024).decode()
if aff == "ok":
return True
elif aff == "passerror":
return [False,"用户名或密码错误"]
elif aff == "online":
return [False,"你已经在线,不能重复登录"]
return [False, "用户名或密码错误"]
def Register(self, username,password,phone_number,car_factory,car_model,car_color,car_plate,email):
'''
此类方法用来处理用户注册功能
初步判断用户信息是否合法,并将信息发送给服务器进行处理
返回值:
成功:True
失败:
[False,"该用户名早已进行注册"]
[False,"该车牌号早已进行注册"]
'''
L = [username,password,phone_number,car_factory,car_model,car_color,car_plate,email]
data_list = ["regist"] + L
data = " ".join(data_list)
self.sockfd.send(data.encode())
aff = self.sockfd.recv(1024).decode()
if aff == 'ok':
return True
return [False,aff]
def User_quit(self,username):
'''
此函数在用户退出时修改用户的登录状态
参数:用户名
返回值:True or False
'''
data = 'quit %s' % username
self.sockfd.send(data.encode())
aff = self.sockfd.recv(1024).decode()
if aff == "ok":
return True
return False
def Select_weath_message(self,city):
"""
此函数用来获取天气信息
参数:城市名
返回值为列表:
成功:[True,{}],如:[True, {'wind_power': '<3级', 'min_temper': '17', 'wind_direction': '无持续风向', 'weather': '多云'}]
注意字典气温参数,夜间为最低气温min_temper,白天为最高气温max_temper
失败:[False]
"""
data = "select_weath_message %s" % city
self.sockfd.send(data.encode())
aff = self.sockfd.recv(1024).decode()
if aff != "error":
weath_list = aff.split(" ")
now_hour = time.localtime().tm_hour
if 6 <= now_hour <= 18:
dic = {
"weather":weath_list[0],
"wind_direction":weath_list[1],
"wind_power":weath_list[2],
"max_temper":weath_list[3]
}
else:
dic = {
"weather": weath_list[0],
"wind_direction": weath_list[1],
"wind_power": weath_list[2],
"min_temper": weath_list[3]
}
return [True,dic]
return [False]
def send_email(self, my_email):
self.mes.my_email(my_email)
if __name__ == "__main__":
client = carClient()
| 28.176724 | 120 | 0.528224 |
from socket import *
from setting import *
from messageAff import user_message
from multiprocessing import Process
import sys,os,time,signal
class carClient(object):
def __init__(self):
self.sockfd = socket(AF_INET,SOCK_STREAM)
self.sockfd.connect(ADDR)
self.mes = user_message()
signal.signal(signal.SIGINT,self.dis_signal)
def dis_signal(self,sig,frame):
if sig == signal.SIGINT:
self.sockfd.send(b'quit')
sys.exit("强制退出")
elif sig == signal.SIGQUIT:
self.sockfd.send(b'quit')
def Get_email_verify_code(self,username,email):
data = 'select_email %s %s'% (username,email)
self.sockfd.send(data.encode())
aff = self.sockfd.recv(1024).decode()
if aff == 'ok':
auth_code = self.mes.my_email(email)
return auth_code
else:
return [False,"你输入的邮箱与注册的邮箱不一致"]
def Modify_password(self, username, password):
data = "change_password %s %s" % (username,password)
self.sockfd.send(data.encode())
aff = self.sockfd.recv(1024).decode()
if aff == "ok":
return True
return False
def Modify_username(self,olduesrname,newusername):
data = 'change_username %s %s' % (olduesrname,newusername)
self.sockfd.send(data.encode())
aff = self.sockfd.recv(1024).decode()
if aff == "ok":
return True
elif aff == "nameisuser":
return [False,"用户名早已被使用"]
return [False,'修改用户名失败']
def Personal_information_display(self,username):
data = "select_user_message %s" % username
self.sockfd.send(data.encode())
aff = self.sockfd.recv(1024).decode()
user_list = aff.split(" ")
if user_list[0] == "ok":
return user_list[1:]
return [False,"未找到用户信息"]
def Personal_information_edit(self,username,phone_number):
data = "change_user_message %s %s" % (username,phone_number)
self.sockfd.send(data.encode())
aff = self.sockfd.recv(1024).decode()
if aff == "ok":
return True
return True
def Select_history_recording(self,username,aff=0):
data = "get_history_msg %s %d" % (username,aff)
self.sockfd.send(data.encode())
aff = self.sockfd.recv(4096).decode()
history_list =[True]
if aff != "error":
history_str = aff.split(" ")
for i in history_str:
record = i.split("##")
history_list.append(record)
return history_list
return [False]
def Login(self,username,password):
message = 'login %s %s' % (username, password)
self.sockfd.send(message.encode())
aff = self.sockfd.recv(1024).decode()
if aff == "ok":
return True
elif aff == "passerror":
return [False,"用户名或密码错误"]
elif aff == "online":
return [False,"你已经在线,不能重复登录"]
return [False, "用户名或密码错误"]
def Register(self, username,password,phone_number,car_factory,car_model,car_color,car_plate,email):
L = [username,password,phone_number,car_factory,car_model,car_color,car_plate,email]
data_list = ["regist"] + L
data = " ".join(data_list)
self.sockfd.send(data.encode())
aff = self.sockfd.recv(1024).decode()
if aff == 'ok':
return True
return [False,aff]
def User_quit(self,username):
data = 'quit %s' % username
self.sockfd.send(data.encode())
aff = self.sockfd.recv(1024).decode()
if aff == "ok":
return True
return False
def Select_weath_message(self,city):
data = "select_weath_message %s" % city
self.sockfd.send(data.encode())
aff = self.sockfd.recv(1024).decode()
if aff != "error":
weath_list = aff.split(" ")
now_hour = time.localtime().tm_hour
if 6 <= now_hour <= 18:
dic = {
"weather":weath_list[0],
"wind_direction":weath_list[1],
"wind_power":weath_list[2],
"max_temper":weath_list[3]
}
else:
dic = {
"weather": weath_list[0],
"wind_direction": weath_list[1],
"wind_power": weath_list[2],
"min_temper": weath_list[3]
}
return [True,dic]
return [False]
def send_email(self, my_email):
self.mes.my_email(my_email)
if __name__ == "__main__":
client = carClient()
| true | true |
f73138feb9a7f803855bf63268835f5d0728508e | 4,019 | py | Python | ubicacion/migrations/0004_auto_20180426_1619.py | jlopez0591/SIGIA | e857e2273daa43ab64fa78df254275af2dbcc2a5 | [
"MIT"
] | null | null | null | ubicacion/migrations/0004_auto_20180426_1619.py | jlopez0591/SIGIA | e857e2273daa43ab64fa78df254275af2dbcc2a5 | [
"MIT"
] | 7 | 2020-02-12T00:42:15.000Z | 2022-03-11T23:23:48.000Z | ubicacion/migrations/0004_auto_20180426_1619.py | jlopez0591/SIGIA | e857e2273daa43ab64fa78df254275af2dbcc2a5 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2018-04-26 21:19
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('ubicacion', '0003_auto_20180417_1603'),
]
operations = [
migrations.AddField(
model_name='carrera',
name='fecha_actualizacion',
field=models.DateField(auto_now=True),
),
migrations.AddField(
model_name='carrera',
name='fecha_creacion',
field=models.DateField(auto_now_add=True, default=django.utils.timezone.now),
preserve_default=False,
),
migrations.AddField(
model_name='carrerainstancia',
name='fecha_actualizacion',
field=models.DateField(auto_now=True),
),
migrations.AddField(
model_name='carrerainstancia',
name='fecha_creacion',
field=models.DateField(auto_now_add=True, default=django.utils.timezone.now),
preserve_default=False,
),
migrations.AddField(
model_name='departamento',
name='fecha_actualizacion',
field=models.DateField(auto_now=True),
),
migrations.AddField(
model_name='departamento',
name='fecha_creacion',
field=models.DateField(auto_now_add=True, default=django.utils.timezone.now),
preserve_default=False,
),
migrations.AddField(
model_name='departamentoinstancia',
name='fecha_actualizacion',
field=models.DateField(auto_now=True),
),
migrations.AddField(
model_name='departamentoinstancia',
name='fecha_creacion',
field=models.DateField(auto_now_add=True, default=django.utils.timezone.now),
preserve_default=False,
),
migrations.AddField(
model_name='escuela',
name='fecha_actualizacion',
field=models.DateField(auto_now=True),
),
migrations.AddField(
model_name='escuela',
name='fecha_creacion',
field=models.DateField(auto_now_add=True, default=django.utils.timezone.now),
preserve_default=False,
),
migrations.AddField(
model_name='escuelainstancia',
name='fecha_actualizacion',
field=models.DateField(auto_now=True),
),
migrations.AddField(
model_name='escuelainstancia',
name='fecha_creacion',
field=models.DateField(auto_now_add=True, default=django.utils.timezone.now),
preserve_default=False,
),
migrations.AddField(
model_name='facultad',
name='fecha_actualizacion',
field=models.DateField(auto_now=True),
),
migrations.AddField(
model_name='facultad',
name='fecha_creacion',
field=models.DateField(auto_now_add=True, default=django.utils.timezone.now),
preserve_default=False,
),
migrations.AddField(
model_name='facultadinstancia',
name='fecha_actualizacion',
field=models.DateField(auto_now=True),
),
migrations.AddField(
model_name='facultadinstancia',
name='fecha_creacion',
field=models.DateField(auto_now_add=True, default=django.utils.timezone.now),
preserve_default=False,
),
migrations.AddField(
model_name='sede',
name='fecha_actualizacion',
field=models.DateField(auto_now=True),
),
migrations.AddField(
model_name='sede',
name='fecha_creacion',
field=models.DateField(auto_now_add=True, default=django.utils.timezone.now),
preserve_default=False,
),
]
| 34.646552 | 89 | 0.591689 |
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('ubicacion', '0003_auto_20180417_1603'),
]
operations = [
migrations.AddField(
model_name='carrera',
name='fecha_actualizacion',
field=models.DateField(auto_now=True),
),
migrations.AddField(
model_name='carrera',
name='fecha_creacion',
field=models.DateField(auto_now_add=True, default=django.utils.timezone.now),
preserve_default=False,
),
migrations.AddField(
model_name='carrerainstancia',
name='fecha_actualizacion',
field=models.DateField(auto_now=True),
),
migrations.AddField(
model_name='carrerainstancia',
name='fecha_creacion',
field=models.DateField(auto_now_add=True, default=django.utils.timezone.now),
preserve_default=False,
),
migrations.AddField(
model_name='departamento',
name='fecha_actualizacion',
field=models.DateField(auto_now=True),
),
migrations.AddField(
model_name='departamento',
name='fecha_creacion',
field=models.DateField(auto_now_add=True, default=django.utils.timezone.now),
preserve_default=False,
),
migrations.AddField(
model_name='departamentoinstancia',
name='fecha_actualizacion',
field=models.DateField(auto_now=True),
),
migrations.AddField(
model_name='departamentoinstancia',
name='fecha_creacion',
field=models.DateField(auto_now_add=True, default=django.utils.timezone.now),
preserve_default=False,
),
migrations.AddField(
model_name='escuela',
name='fecha_actualizacion',
field=models.DateField(auto_now=True),
),
migrations.AddField(
model_name='escuela',
name='fecha_creacion',
field=models.DateField(auto_now_add=True, default=django.utils.timezone.now),
preserve_default=False,
),
migrations.AddField(
model_name='escuelainstancia',
name='fecha_actualizacion',
field=models.DateField(auto_now=True),
),
migrations.AddField(
model_name='escuelainstancia',
name='fecha_creacion',
field=models.DateField(auto_now_add=True, default=django.utils.timezone.now),
preserve_default=False,
),
migrations.AddField(
model_name='facultad',
name='fecha_actualizacion',
field=models.DateField(auto_now=True),
),
migrations.AddField(
model_name='facultad',
name='fecha_creacion',
field=models.DateField(auto_now_add=True, default=django.utils.timezone.now),
preserve_default=False,
),
migrations.AddField(
model_name='facultadinstancia',
name='fecha_actualizacion',
field=models.DateField(auto_now=True),
),
migrations.AddField(
model_name='facultadinstancia',
name='fecha_creacion',
field=models.DateField(auto_now_add=True, default=django.utils.timezone.now),
preserve_default=False,
),
migrations.AddField(
model_name='sede',
name='fecha_actualizacion',
field=models.DateField(auto_now=True),
),
migrations.AddField(
model_name='sede',
name='fecha_creacion',
field=models.DateField(auto_now_add=True, default=django.utils.timezone.now),
preserve_default=False,
),
]
| true | true |
f73139736d7eeb275bd78656e3b4701fb97eabe7 | 4,427 | py | Python | azure-mgmt-compute/azure/mgmt/compute/v2017_12_01/operations/usage_operations.py | JonathanGailliez/azure-sdk-for-python | f0f051bfd27f8ea512aea6fc0c3212ee9ee0029b | [
"MIT"
] | 1 | 2021-09-07T18:36:04.000Z | 2021-09-07T18:36:04.000Z | azure-mgmt-compute/azure/mgmt/compute/v2017_12_01/operations/usage_operations.py | JonathanGailliez/azure-sdk-for-python | f0f051bfd27f8ea512aea6fc0c3212ee9ee0029b | [
"MIT"
] | 2 | 2019-10-02T23:37:38.000Z | 2020-10-02T01:17:31.000Z | azure-mgmt-compute/azure/mgmt/compute/v2017_12_01/operations/usage_operations.py | JonathanGailliez/azure-sdk-for-python | f0f051bfd27f8ea512aea6fc0c3212ee9ee0029b | [
"MIT"
] | 1 | 2019-06-17T22:18:23.000Z | 2019-06-17T22:18:23.000Z | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
import uuid
from msrest.pipeline import ClientRawResponse
from msrestazure.azure_exceptions import CloudError
from .. import models
class UsageOperations(object):
"""UsageOperations operations.
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
:ivar api_version: Client Api Version. Constant value: "2017-12-01".
"""
models = models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self.api_version = "2017-12-01"
self.config = config
def list(
self, location, custom_headers=None, raw=False, **operation_config):
"""Gets, for the specified location, the current compute resource usage
information as well as the limits for compute resources under the
subscription.
:param location: The location for which resource usage is queried.
:type location: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: An iterator like instance of Usage
:rtype:
~azure.mgmt.compute.v2017_12_01.models.UsagePaged[~azure.mgmt.compute.v2017_12_01.models.Usage]
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
def internal_paging(next_link=None, raw=False):
if not next_link:
# Construct URL
url = self.list.metadata['url']
path_format_arguments = {
'location': self._serialize.url("location", location, 'str', pattern=r'^[-\w\._]+$'),
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
else:
url = next_link
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
return response
# Deserialize response
deserialized = models.UsagePaged(internal_paging, self._deserialize.dependencies)
if raw:
header_dict = {}
client_raw_response = models.UsagePaged(internal_paging, self._deserialize.dependencies, header_dict)
return client_raw_response
return deserialized
list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/usages'}
| 40.990741 | 144 | 0.630901 |
import uuid
from msrest.pipeline import ClientRawResponse
from msrestazure.azure_exceptions import CloudError
from .. import models
class UsageOperations(object):
models = models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self.api_version = "2017-12-01"
self.config = config
def list(
self, location, custom_headers=None, raw=False, **operation_config):
def internal_paging(next_link=None, raw=False):
if not next_link:
url = self.list.metadata['url']
path_format_arguments = {
'location': self._serialize.url("location", location, 'str', pattern=r'^[-\w\._]+$'),
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
else:
url = next_link
query_parameters = {}
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
return response
deserialized = models.UsagePaged(internal_paging, self._deserialize.dependencies)
if raw:
header_dict = {}
client_raw_response = models.UsagePaged(internal_paging, self._deserialize.dependencies, header_dict)
return client_raw_response
return deserialized
list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/usages'}
| true | true |
f7313beb6b36e0b6947bf44f357978b77188d33a | 4,841 | py | Python | radish/extensions/syslog_writer.py | tuxrosi/radish | b21fa751f8dfc4309451476151c810b44975babb | [
"MIT"
] | null | null | null | radish/extensions/syslog_writer.py | tuxrosi/radish | b21fa751f8dfc4309451476151c810b44975babb | [
"MIT"
] | null | null | null | radish/extensions/syslog_writer.py | tuxrosi/radish | b21fa751f8dfc4309451476151c810b44975babb | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""
This module provides an extension to write all features, scenarios and steps to the syslog.
"""
from __future__ import unicode_literals
from radish.terrain import world
from radish.feature import Feature
from radish.hookregistry import before, after
from radish.extensionregistry import extension
@extension
class SyslogWriter(object):
"""
Syslog Writer radish extension. This extension is only supported on
systems where the Python standard library supports the system logger
(syslog). For example, this extension works on UNIX and UNIX-like
systems (Linux), but will not work on Windows.
"""
OPTIONS = [
("--syslog", "log all of your features, scenarios, and steps to the syslog")
]
LOAD_IF = staticmethod(lambda config: config.syslog)
LOAD_PRIORITY = 40
def __init__(self):
# import syslog only if the extension got loaded
# but not if the module got loaded.
import syslog
before.all(self.syslog_writer_before_all)
before.each_feature(self.syslog_writer_before_each_feature)
before.each_scenario(self.syslog_writer_before_each_scenario)
before.each_step(self.syslog_writer_before_each_step)
after.all(self.syslog_writer_after_all)
after.each_feature(self.syslog_writer_after_each_feature)
after.each_scenario(self.syslog_writer_after_each_scenario)
after.each_step(self.syslog_writer_after_each_step)
def get_scenario_feature(self, scenario):
"""
Gets the scenarios feature
"""
if not isinstance(scenario.parent, Feature):
return scenario.parent.parent
return scenario.parent
def log(self, message):
"""
Logs the given message to the syslog
:param string message: the message to log
"""
import syslog
try:
if isinstance(message, unicode):
message = message.encode("utf8")
except Exception: # pylint: disable=broad-except
pass
finally:
syslog.syslog(syslog.LOG_INFO, message)
def syslog_writer_before_all(
self, features, marker
): # pylint: disable=unused-argument
"""
Opens the syslog
"""
import syslog
syslog.openlog(b"radish")
self.log("begin run {0}".format(marker))
def syslog_writer_after_all(
self, features, marker
): # pylint: disable=unused-argument
"""
Closes the syslog
"""
import syslog
self.log("end run {0}".format(marker))
syslog.closelog()
def syslog_writer_before_each_feature(self, feature):
"""
Writes the feature to the syslog
"""
self.log(
"begin feature {0}:{1} {2}".format(
world.config.marker, feature.id, feature.sentence
)
)
def syslog_writer_after_each_feature(self, feature):
"""
Writes the feature to the syslog
"""
self.log(
"end feature {0}:{1} {2}".format(
world.config.marker, feature.id, feature.sentence
)
)
def syslog_writer_before_each_scenario(self, scenario):
"""
Writes the scenario to the syslog
"""
self.log(
"begin scenario {0}:{1}.{2} {3}".format(
world.config.marker,
self.get_scenario_feature(scenario).id,
scenario.id,
scenario.sentence,
)
)
def syslog_writer_after_each_scenario(self, scenario):
"""
Writes the scenario to the syslog
"""
self.log(
"end scenario {0}:{1}.{2} {3}".format(
world.config.marker,
self.get_scenario_feature(scenario).id,
scenario.id,
scenario.sentence,
)
)
def syslog_writer_before_each_step(self, step):
"""
Writes the step to the syslog
"""
self.log(
"begin step {0}:{1}.{2}.{3} {4}".format(
world.config.marker,
self.get_scenario_feature(step.parent).id,
step.parent.id,
step.id,
step.sentence,
)
)
def syslog_writer_after_each_step(self, step):
"""
Writes the step to the syslog
"""
self.log(
"{0} step {1}:{2}.{3}.{4} {5}".format(
step.state,
world.config.marker,
self.get_scenario_feature(step.parent).id,
step.parent.id,
step.id,
step.sentence,
)
)
| 29.339394 | 95 | 0.567445 |
from __future__ import unicode_literals
from radish.terrain import world
from radish.feature import Feature
from radish.hookregistry import before, after
from radish.extensionregistry import extension
@extension
class SyslogWriter(object):
OPTIONS = [
("--syslog", "log all of your features, scenarios, and steps to the syslog")
]
LOAD_IF = staticmethod(lambda config: config.syslog)
LOAD_PRIORITY = 40
def __init__(self):
import syslog
before.all(self.syslog_writer_before_all)
before.each_feature(self.syslog_writer_before_each_feature)
before.each_scenario(self.syslog_writer_before_each_scenario)
before.each_step(self.syslog_writer_before_each_step)
after.all(self.syslog_writer_after_all)
after.each_feature(self.syslog_writer_after_each_feature)
after.each_scenario(self.syslog_writer_after_each_scenario)
after.each_step(self.syslog_writer_after_each_step)
def get_scenario_feature(self, scenario):
if not isinstance(scenario.parent, Feature):
return scenario.parent.parent
return scenario.parent
def log(self, message):
import syslog
try:
if isinstance(message, unicode):
message = message.encode("utf8")
except Exception:
pass
finally:
syslog.syslog(syslog.LOG_INFO, message)
def syslog_writer_before_all(
self, features, marker
):
import syslog
syslog.openlog(b"radish")
self.log("begin run {0}".format(marker))
def syslog_writer_after_all(
self, features, marker
):
import syslog
self.log("end run {0}".format(marker))
syslog.closelog()
def syslog_writer_before_each_feature(self, feature):
self.log(
"begin feature {0}:{1} {2}".format(
world.config.marker, feature.id, feature.sentence
)
)
def syslog_writer_after_each_feature(self, feature):
self.log(
"end feature {0}:{1} {2}".format(
world.config.marker, feature.id, feature.sentence
)
)
def syslog_writer_before_each_scenario(self, scenario):
self.log(
"begin scenario {0}:{1}.{2} {3}".format(
world.config.marker,
self.get_scenario_feature(scenario).id,
scenario.id,
scenario.sentence,
)
)
def syslog_writer_after_each_scenario(self, scenario):
self.log(
"end scenario {0}:{1}.{2} {3}".format(
world.config.marker,
self.get_scenario_feature(scenario).id,
scenario.id,
scenario.sentence,
)
)
def syslog_writer_before_each_step(self, step):
self.log(
"begin step {0}:{1}.{2}.{3} {4}".format(
world.config.marker,
self.get_scenario_feature(step.parent).id,
step.parent.id,
step.id,
step.sentence,
)
)
def syslog_writer_after_each_step(self, step):
self.log(
"{0} step {1}:{2}.{3}.{4} {5}".format(
step.state,
world.config.marker,
self.get_scenario_feature(step.parent).id,
step.parent.id,
step.id,
step.sentence,
)
)
| true | true |
f7313bfac29687bff5e8a360d2fdc2e1ee3e5a5f | 1,447 | py | Python | setup_guide/migrations/0005_auto_20180327_1341.py | uktrade/invest | 15b84c511839b46e81608fca9762d2df3f6df16c | [
"MIT"
] | 1 | 2019-01-18T03:50:46.000Z | 2019-01-18T03:50:46.000Z | setup_guide/migrations/0005_auto_20180327_1341.py | uktrade/invest | 15b84c511839b46e81608fca9762d2df3f6df16c | [
"MIT"
] | 50 | 2018-01-24T18:04:08.000Z | 2019-01-03T03:30:30.000Z | setup_guide/migrations/0005_auto_20180327_1341.py | uktrade/invest | 15b84c511839b46e81608fca9762d2df3f6df16c | [
"MIT"
] | 2 | 2018-02-12T15:20:52.000Z | 2019-01-18T03:51:52.000Z | # -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-03-27 13:41
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('setup_guide', '0004_auto_20180322_1443'),
]
operations = [
migrations.RenameField(
model_name='setupguidelandingpage',
old_name='heading_zh',
new_name='heading_zh_cn',
),
migrations.RenameField(
model_name='setupguidelandingpage',
old_name='lead_in_zh',
new_name='lead_in_zh_cn',
),
migrations.RenameField(
model_name='setupguidelandingpage',
old_name='sub_heading_zh',
new_name='sub_heading_zh_cn',
),
migrations.RenameField(
model_name='setupguidepage',
old_name='description_zh',
new_name='description_zh_cn',
),
migrations.RenameField(
model_name='setupguidepage',
old_name='heading_zh',
new_name='heading_zh_cn',
),
migrations.RenameField(
model_name='setupguidepage',
old_name='sub_heading_zh',
new_name='sub_heading_zh_cn',
),
migrations.RenameField(
model_name='setupguidepage',
old_name='subsections_zh',
new_name='subsections_zh_cn',
),
]
| 28.372549 | 51 | 0.580511 |
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('setup_guide', '0004_auto_20180322_1443'),
]
operations = [
migrations.RenameField(
model_name='setupguidelandingpage',
old_name='heading_zh',
new_name='heading_zh_cn',
),
migrations.RenameField(
model_name='setupguidelandingpage',
old_name='lead_in_zh',
new_name='lead_in_zh_cn',
),
migrations.RenameField(
model_name='setupguidelandingpage',
old_name='sub_heading_zh',
new_name='sub_heading_zh_cn',
),
migrations.RenameField(
model_name='setupguidepage',
old_name='description_zh',
new_name='description_zh_cn',
),
migrations.RenameField(
model_name='setupguidepage',
old_name='heading_zh',
new_name='heading_zh_cn',
),
migrations.RenameField(
model_name='setupguidepage',
old_name='sub_heading_zh',
new_name='sub_heading_zh_cn',
),
migrations.RenameField(
model_name='setupguidepage',
old_name='subsections_zh',
new_name='subsections_zh_cn',
),
]
| true | true |
f7313c2994502b974b95d44f22df74068b470940 | 81,610 | py | Python | dask/array/routines.py | leogao2/dask | 4e5dfe7463028a39a90e026c7fb9220969093ab3 | [
"BSD-3-Clause"
] | null | null | null | dask/array/routines.py | leogao2/dask | 4e5dfe7463028a39a90e026c7fb9220969093ab3 | [
"BSD-3-Clause"
] | null | null | null | dask/array/routines.py | leogao2/dask | 4e5dfe7463028a39a90e026c7fb9220969093ab3 | [
"BSD-3-Clause"
] | null | null | null | from __future__ import annotations
import math
import warnings
from collections.abc import Iterable
from functools import partial, reduce, wraps
from numbers import Integral, Real
import numpy as np
from tlz import concat, interleave, sliding_window
from dask.array import chunk
from dask.array.core import (
Array,
asanyarray,
asarray,
blockwise,
broadcast_arrays,
broadcast_shapes,
broadcast_to,
concatenate,
elemwise,
from_array,
implements,
is_scalar_for_elemwise,
map_blocks,
stack,
tensordot_lookup,
)
from dask.array.creation import arange, diag, empty, indices, tri
from dask.array.einsumfuncs import einsum # noqa
from dask.array.numpy_compat import _numpy_120
from dask.array.reductions import reduction
from dask.array.ufunc import multiply, sqrt
from dask.array.utils import (
array_safe,
asarray_safe,
meta_from_array,
safe_wraps,
validate_axis,
)
from dask.array.wrap import ones
from dask.base import is_dask_collection, tokenize
from dask.core import flatten
from dask.delayed import Delayed, unpack_collections
from dask.highlevelgraph import HighLevelGraph
from dask.utils import apply, derived_from, funcname, is_arraylike, is_cupy_type
# save built-in for histogram functions which use range as a kwarg.
_range = range
@derived_from(np)
def array(x, dtype=None, ndmin=None, *, like=None):
if not _numpy_120 and like is not None:
raise RuntimeError("The use of ``like`` required NumPy >= 1.20")
x = asarray(x, like=like)
while ndmin is not None and x.ndim < ndmin:
x = x[None, :]
if dtype is not None and x.dtype != dtype:
x = x.astype(dtype)
return x
@derived_from(np)
def result_type(*args):
args = [a if is_scalar_for_elemwise(a) else a.dtype for a in args]
return np.result_type(*args)
@derived_from(np)
def atleast_3d(*arys):
new_arys = []
for x in arys:
x = asanyarray(x)
if x.ndim == 0:
x = x[None, None, None]
elif x.ndim == 1:
x = x[None, :, None]
elif x.ndim == 2:
x = x[:, :, None]
new_arys.append(x)
if len(new_arys) == 1:
return new_arys[0]
else:
return new_arys
@derived_from(np)
def atleast_2d(*arys):
new_arys = []
for x in arys:
x = asanyarray(x)
if x.ndim == 0:
x = x[None, None]
elif x.ndim == 1:
x = x[None, :]
new_arys.append(x)
if len(new_arys) == 1:
return new_arys[0]
else:
return new_arys
@derived_from(np)
def atleast_1d(*arys):
new_arys = []
for x in arys:
x = asanyarray(x)
if x.ndim == 0:
x = x[None]
new_arys.append(x)
if len(new_arys) == 1:
return new_arys[0]
else:
return new_arys
@derived_from(np)
def vstack(tup, allow_unknown_chunksizes=False):
if isinstance(tup, Array):
raise NotImplementedError(
"``vstack`` expects a sequence of arrays as the first argument"
)
tup = tuple(atleast_2d(x) for x in tup)
return concatenate(tup, axis=0, allow_unknown_chunksizes=allow_unknown_chunksizes)
@derived_from(np)
def hstack(tup, allow_unknown_chunksizes=False):
if isinstance(tup, Array):
raise NotImplementedError(
"``hstack`` expects a sequence of arrays as the first argument"
)
if all(x.ndim == 1 for x in tup):
return concatenate(
tup, axis=0, allow_unknown_chunksizes=allow_unknown_chunksizes
)
else:
return concatenate(
tup, axis=1, allow_unknown_chunksizes=allow_unknown_chunksizes
)
@derived_from(np)
def dstack(tup, allow_unknown_chunksizes=False):
if isinstance(tup, Array):
raise NotImplementedError(
"``dstack`` expects a sequence of arrays as the first argument"
)
tup = tuple(atleast_3d(x) for x in tup)
return concatenate(tup, axis=2, allow_unknown_chunksizes=allow_unknown_chunksizes)
@derived_from(np)
def swapaxes(a, axis1, axis2):
if axis1 == axis2:
return a
if axis1 < 0:
axis1 = axis1 + a.ndim
if axis2 < 0:
axis2 = axis2 + a.ndim
ind = list(range(a.ndim))
out = list(ind)
out[axis1], out[axis2] = axis2, axis1
return blockwise(np.swapaxes, out, a, ind, axis1=axis1, axis2=axis2, dtype=a.dtype)
@derived_from(np)
def transpose(a, axes=None):
if axes:
if len(axes) != a.ndim:
raise ValueError("axes don't match array")
axes = tuple(d + a.ndim if d < 0 else d for d in axes)
else:
axes = tuple(range(a.ndim))[::-1]
return blockwise(
np.transpose, axes, a, tuple(range(a.ndim)), dtype=a.dtype, axes=axes
)
def flip(m, axis=None):
"""
Reverse element order along axis.
Parameters
----------
m : array_like
Input array.
axis : None or int or tuple of ints, optional
Axis or axes to reverse element order of. None will reverse all axes.
Returns
-------
dask.array.Array
The flipped array.
"""
m = asanyarray(m)
sl = m.ndim * [slice(None)]
if axis is None:
axis = range(m.ndim)
if not isinstance(axis, Iterable):
axis = (axis,)
try:
for ax in axis:
sl[ax] = slice(None, None, -1)
except IndexError as e:
raise ValueError(
f"`axis` of {str(axis)} invalid for {str(m.ndim)}-D array"
) from e
sl = tuple(sl)
return m[sl]
@derived_from(np)
def flipud(m):
return flip(m, 0)
@derived_from(np)
def fliplr(m):
return flip(m, 1)
@derived_from(np)
def rot90(m, k=1, axes=(0, 1)):
axes = tuple(axes)
if len(axes) != 2:
raise ValueError("len(axes) must be 2.")
m = asanyarray(m)
if axes[0] == axes[1] or np.absolute(axes[0] - axes[1]) == m.ndim:
raise ValueError("Axes must be different.")
if axes[0] >= m.ndim or axes[0] < -m.ndim or axes[1] >= m.ndim or axes[1] < -m.ndim:
raise ValueError(f"Axes={axes} out of range for array of ndim={m.ndim}.")
k %= 4
if k == 0:
return m[:]
if k == 2:
return flip(flip(m, axes[0]), axes[1])
axes_list = list(range(0, m.ndim))
(axes_list[axes[0]], axes_list[axes[1]]) = (axes_list[axes[1]], axes_list[axes[0]])
if k == 1:
return transpose(flip(m, axes[1]), axes_list)
else:
# k == 3
return flip(transpose(m, axes_list), axes[1])
def _tensordot(a, b, axes, is_sparse):
x = max([a, b], key=lambda x: x.__array_priority__)
tensordot = tensordot_lookup.dispatch(type(x))
x = tensordot(a, b, axes=axes)
if is_sparse and len(axes[0]) == 1:
return x
else:
ind = [slice(None, None)] * x.ndim
for a in sorted(axes[0]):
ind.insert(a, None)
x = x[tuple(ind)]
return x
def _tensordot_is_sparse(x):
is_sparse = "sparse" in str(type(x._meta))
if is_sparse:
# exclude pydata sparse arrays, no workaround required for these in tensordot
is_sparse = "sparse._coo.core.COO" not in str(type(x._meta))
return is_sparse
@derived_from(np)
def tensordot(lhs, rhs, axes=2):
if not isinstance(lhs, Array):
lhs = from_array(lhs)
if not isinstance(rhs, Array):
rhs = from_array(rhs)
if isinstance(axes, Iterable):
left_axes, right_axes = axes
else:
left_axes = tuple(range(lhs.ndim - axes, lhs.ndim))
right_axes = tuple(range(0, axes))
if isinstance(left_axes, Integral):
left_axes = (left_axes,)
if isinstance(right_axes, Integral):
right_axes = (right_axes,)
if isinstance(left_axes, list):
left_axes = tuple(left_axes)
if isinstance(right_axes, list):
right_axes = tuple(right_axes)
is_sparse = _tensordot_is_sparse(lhs) or _tensordot_is_sparse(rhs)
if is_sparse and len(left_axes) == 1:
concatenate = True
else:
concatenate = False
dt = np.promote_types(lhs.dtype, rhs.dtype)
left_index = list(range(lhs.ndim))
right_index = list(range(lhs.ndim, lhs.ndim + rhs.ndim))
out_index = left_index + right_index
adjust_chunks = {}
for l, r in zip(left_axes, right_axes):
out_index.remove(right_index[r])
right_index[r] = left_index[l]
if concatenate:
out_index.remove(left_index[l])
else:
adjust_chunks[left_index[l]] = lambda c: 1
intermediate = blockwise(
_tensordot,
out_index,
lhs,
left_index,
rhs,
right_index,
dtype=dt,
concatenate=concatenate,
adjust_chunks=adjust_chunks,
axes=(left_axes, right_axes),
is_sparse=is_sparse,
)
if concatenate:
return intermediate
else:
return intermediate.sum(axis=left_axes)
@derived_from(np)
def dot(a, b):
return tensordot(a, b, axes=((a.ndim - 1,), (b.ndim - 2,)))
@derived_from(np)
def vdot(a, b):
return dot(a.conj().ravel(), b.ravel())
def _chunk_sum(a, axis=None, dtype=None, keepdims=None):
# Caution: this is not your conventional array-sum: due
# to the special nature of the preceding blockwise con-
# traction, each chunk is expected to have exactly the
# same shape, with a size of 1 for the dimension given
# by `axis` (the reduction axis). This makes mere ele-
# ment-wise addition of the arrays possible. Besides,
# the output can be merely squeezed to lose the `axis`-
# dimension when keepdims = False
if type(a) is list:
out = reduce(partial(np.add, dtype=dtype), a)
else:
out = a
if keepdims:
return out
else:
return out.squeeze(axis[0])
def _sum_wo_cat(a, axis=None, dtype=None):
if dtype is None:
dtype = getattr(np.zeros(1, dtype=a.dtype).sum(), "dtype", object)
if a.shape[axis] == 1:
return a.squeeze(axis)
return reduction(
a, _chunk_sum, _chunk_sum, axis=axis, dtype=dtype, concatenate=False
)
def _matmul(a, b):
xp = np
if is_cupy_type(a):
# This branch appears to be unnecessary since cupy
# version 9.0. See the following link:
# https://github.com/dask/dask/pull/8423#discussion_r768291271
# But it remains here for backward-compatibility.
# Consider removing it in a future version of dask.
import cupy
xp = cupy
chunk = xp.matmul(a, b)
# Since we have performed the contraction via xp.matmul
# but blockwise expects all dimensions back (including
# the contraction-axis in the 2nd-to-last position of
# the output), we must then put it back in the expected
# the position ourselves:
return chunk[..., xp.newaxis, :]
@derived_from(np)
def matmul(a, b):
a = asanyarray(a)
b = asanyarray(b)
if a.ndim == 0 or b.ndim == 0:
raise ValueError("`matmul` does not support scalars.")
a_is_1d = False
if a.ndim == 1:
a_is_1d = True
a = a[np.newaxis, :]
b_is_1d = False
if b.ndim == 1:
b_is_1d = True
b = b[:, np.newaxis]
if a.ndim < b.ndim:
a = a[(b.ndim - a.ndim) * (np.newaxis,)]
elif a.ndim > b.ndim:
b = b[(a.ndim - b.ndim) * (np.newaxis,)]
# out_ind includes all dimensions to prevent contraction
# in the blockwise below. We set the last two dimensions
# of the output to the contraction axis and the 2nd
# (last) dimension of b in that order
out_ind = tuple(range(a.ndim + 1))
# lhs_ind includes `a`/LHS dimensions
lhs_ind = tuple(range(a.ndim))
# on `b`/RHS everything above 2nd dimension, is the same
# as `a`, -2 dimension is "contracted" with the last dimension
# of `a`, last dimension of `b` is `b` specific
rhs_ind = tuple(range(a.ndim - 2)) + (lhs_ind[-1], a.ndim)
out = blockwise(
_matmul,
out_ind,
a,
lhs_ind,
b,
rhs_ind,
adjust_chunks={lhs_ind[-1]: 1},
dtype=result_type(a, b),
concatenate=False,
)
# Because contraction + concatenate in blockwise leads to high
# memory footprints, we want to avoid them. Instead we will perform
# blockwise (without contraction) followed by reduction. More about
# this issue: https://github.com/dask/dask/issues/6874
# We will also perform the reduction without concatenation
out = _sum_wo_cat(out, axis=-2)
if a_is_1d:
out = out.squeeze(-2)
if b_is_1d:
out = out.squeeze(-1)
return out
@derived_from(np)
def outer(a, b):
a = a.flatten()
b = b.flatten()
dtype = np.outer(a.dtype.type(), b.dtype.type()).dtype
return blockwise(np.outer, "ij", a, "i", b, "j", dtype=dtype)
def _inner_apply_along_axis(arr, func1d, func1d_axis, func1d_args, func1d_kwargs):
return np.apply_along_axis(func1d, func1d_axis, arr, *func1d_args, **func1d_kwargs)
@derived_from(np)
def apply_along_axis(func1d, axis, arr, *args, dtype=None, shape=None, **kwargs):
"""
This is a blocked variant of :func:`numpy.apply_along_axis` implemented via
:func:`dask.array.map_blocks`
Notes
-----
If either of `dtype` or `shape` are not provided, Dask attempts to
determine them by calling `func1d` on a dummy array. This may produce
incorrect values for `dtype` or `shape`, so we recommend providing them.
"""
arr = asarray(arr)
# Verify that axis is valid and throw an error otherwise
axis = len(arr.shape[:axis])
# If necessary, infer dtype and shape of the output of func1d by calling it on test data.
if shape is None or dtype is None:
test_data = np.ones((1,), dtype=arr.dtype)
test_result = np.array(func1d(test_data, *args, **kwargs))
if shape is None:
shape = test_result.shape
if dtype is None:
dtype = test_result.dtype
# Rechunk so that func1d is applied over the full axis.
arr = arr.rechunk(
arr.chunks[:axis] + (arr.shape[axis : axis + 1],) + arr.chunks[axis + 1 :]
)
# Map func1d over the data to get the result
# Adds other axes as needed.
result = arr.map_blocks(
_inner_apply_along_axis,
name=funcname(func1d) + "-along-axis",
dtype=dtype,
chunks=(arr.chunks[:axis] + shape + arr.chunks[axis + 1 :]),
drop_axis=axis,
new_axis=list(range(axis, axis + len(shape), 1)),
func1d=func1d,
func1d_axis=axis,
func1d_args=args,
func1d_kwargs=kwargs,
)
return result
@derived_from(np)
def apply_over_axes(func, a, axes):
# Validate arguments
a = asarray(a)
try:
axes = tuple(axes)
except TypeError:
axes = (axes,)
sl = a.ndim * (slice(None),)
# Compute using `apply_along_axis`.
result = a
for i in axes:
result = apply_along_axis(func, i, result, 0)
# Restore original dimensionality or error.
if result.ndim == (a.ndim - 1):
result = result[sl[:i] + (None,)]
elif result.ndim != a.ndim:
raise ValueError(
"func must either preserve dimensionality of the input"
" or reduce it by one."
)
return result
@derived_from(np)
def ptp(a, axis=None):
return a.max(axis=axis) - a.min(axis=axis)
@derived_from(np)
def diff(a, n=1, axis=-1, prepend=None, append=None):
a = asarray(a)
n = int(n)
axis = int(axis)
if n == 0:
return a
if n < 0:
raise ValueError("order must be non-negative but got %d" % n)
combined = []
if prepend is not None:
prepend = asarray_safe(prepend, like=meta_from_array(a))
if prepend.ndim == 0:
shape = list(a.shape)
shape[axis] = 1
prepend = broadcast_to(prepend, tuple(shape))
combined.append(prepend)
combined.append(a)
if append is not None:
append = asarray_safe(append, like=meta_from_array(a))
if append.ndim == 0:
shape = list(a.shape)
shape[axis] = 1
append = np.broadcast_to(append, tuple(shape))
combined.append(append)
if len(combined) > 1:
a = concatenate(combined, axis)
sl_1 = a.ndim * [slice(None)]
sl_2 = a.ndim * [slice(None)]
sl_1[axis] = slice(1, None)
sl_2[axis] = slice(None, -1)
sl_1 = tuple(sl_1)
sl_2 = tuple(sl_2)
r = a
for i in range(n):
r = r[sl_1] - r[sl_2]
return r
@derived_from(np)
def ediff1d(ary, to_end=None, to_begin=None):
ary = asarray(ary)
aryf = ary.flatten()
r = aryf[1:] - aryf[:-1]
r = [r]
if to_begin is not None:
r = [asarray(to_begin).flatten()] + r
if to_end is not None:
r = r + [asarray(to_end).flatten()]
r = concatenate(r)
return r
def _gradient_kernel(x, block_id, coord, axis, array_locs, grad_kwargs):
"""
x: nd-array
array of one block
coord: 1d-array or scalar
coordinate along which the gradient is computed.
axis: int
axis along which the gradient is computed
array_locs:
actual location along axis. None if coordinate is scalar
grad_kwargs:
keyword to be passed to np.gradient
"""
block_loc = block_id[axis]
if array_locs is not None:
coord = coord[array_locs[0][block_loc] : array_locs[1][block_loc]]
grad = np.gradient(x, coord, axis=axis, **grad_kwargs)
return grad
@derived_from(np)
def gradient(f, *varargs, axis=None, **kwargs):
f = asarray(f)
kwargs["edge_order"] = math.ceil(kwargs.get("edge_order", 1))
if kwargs["edge_order"] > 2:
raise ValueError("edge_order must be less than or equal to 2.")
drop_result_list = False
if axis is None:
axis = tuple(range(f.ndim))
elif isinstance(axis, Integral):
drop_result_list = True
axis = (axis,)
axis = validate_axis(axis, f.ndim)
if len(axis) != len(set(axis)):
raise ValueError("duplicate axes not allowed")
axis = tuple(ax % f.ndim for ax in axis)
if varargs == ():
varargs = (1,)
if len(varargs) == 1:
varargs = len(axis) * varargs
if len(varargs) != len(axis):
raise TypeError(
"Spacing must either be a single scalar, or a scalar / 1d-array per axis"
)
if issubclass(f.dtype.type, (np.bool8, Integral)):
f = f.astype(float)
elif issubclass(f.dtype.type, Real) and f.dtype.itemsize < 4:
f = f.astype(float)
results = []
for i, ax in enumerate(axis):
for c in f.chunks[ax]:
if np.min(c) < kwargs["edge_order"] + 1:
raise ValueError(
"Chunk size must be larger than edge_order + 1. "
"Minimum chunk for axis {} is {}. Rechunk to "
"proceed.".format(ax, np.min(c))
)
if np.isscalar(varargs[i]):
array_locs = None
else:
if isinstance(varargs[i], Array):
raise NotImplementedError("dask array coordinated is not supported.")
# coordinate position for each block taking overlap into account
chunk = np.array(f.chunks[ax])
array_loc_stop = np.cumsum(chunk) + 1
array_loc_start = array_loc_stop - chunk - 2
array_loc_stop[-1] -= 1
array_loc_start[0] = 0
array_locs = (array_loc_start, array_loc_stop)
results.append(
f.map_overlap(
_gradient_kernel,
dtype=f.dtype,
depth={j: 1 if j == ax else 0 for j in range(f.ndim)},
boundary="none",
coord=varargs[i],
axis=ax,
array_locs=array_locs,
grad_kwargs=kwargs,
)
)
if drop_result_list:
results = results[0]
return results
def _bincount_agg(bincounts, dtype, **kwargs):
if not isinstance(bincounts, list):
return bincounts
n = max(map(len, bincounts))
out = np.zeros_like(bincounts[0], shape=n, dtype=dtype)
for b in bincounts:
out[: len(b)] += b
return out
@derived_from(np)
def bincount(x, weights=None, minlength=0, split_every=None):
if x.ndim != 1:
raise ValueError("Input array must be one dimensional. Try using x.ravel()")
if weights is not None:
if weights.chunks != x.chunks:
raise ValueError("Chunks of input array x and weights must match.")
token = tokenize(x, weights, minlength)
args = [x, "i"]
if weights is not None:
meta = array_safe(np.bincount([1], weights=[1]), like=meta_from_array(x))
args.extend([weights, "i"])
else:
meta = array_safe(np.bincount([]), like=meta_from_array(x))
if minlength == 0:
output_size = (np.nan,)
else:
output_size = (minlength,)
chunked_counts = blockwise(
partial(np.bincount, minlength=minlength), "i", *args, token=token, meta=meta
)
chunked_counts._chunks = (
output_size * len(chunked_counts.chunks[0]),
*chunked_counts.chunks[1:],
)
from dask.array.reductions import _tree_reduce
output = _tree_reduce(
chunked_counts,
aggregate=partial(_bincount_agg, dtype=meta.dtype),
axis=(0,),
keepdims=True,
dtype=meta.dtype,
split_every=split_every,
concatenate=False,
)
output._chunks = (output_size, *chunked_counts.chunks[1:])
output._meta = meta
return output
@derived_from(np)
def digitize(a, bins, right=False):
bins = asarray_safe(bins, like=meta_from_array(a))
dtype = np.digitize(asarray_safe([0], like=bins), bins, right=False).dtype
return a.map_blocks(np.digitize, dtype=dtype, bins=bins, right=right)
def _searchsorted_block(x, y, side):
res = np.searchsorted(x, y, side=side)
# 0 is only correct for the first block of a, but blockwise doesn't have a way
# of telling which block is being operated on (unlike map_blocks),
# so set all 0 values to a special value and set back at the end of searchsorted
res[res == 0] = -1
return res[np.newaxis, :]
@derived_from(np)
def searchsorted(a, v, side="left", sorter=None):
if a.ndim != 1:
raise ValueError("Input array a must be one dimensional")
if sorter is not None:
raise NotImplementedError(
"da.searchsorted with a sorter argument is not supported"
)
# call np.searchsorted for each pair of blocks in a and v
meta = np.searchsorted(a._meta, v._meta)
out = blockwise(
_searchsorted_block,
list(range(v.ndim + 1)),
a,
[0],
v,
list(range(1, v.ndim + 1)),
side,
None,
meta=meta,
adjust_chunks={0: 1}, # one row for each block in a
)
# add offsets to take account of the position of each block within the array a
a_chunk_sizes = array_safe((0, *a.chunks[0]), like=meta_from_array(a))
a_chunk_offsets = np.cumsum(a_chunk_sizes)[:-1]
a_chunk_offsets = a_chunk_offsets[(Ellipsis,) + v.ndim * (np.newaxis,)]
a_offsets = asarray(a_chunk_offsets, chunks=1)
out = where(out < 0, out, out + a_offsets)
# combine the results from each block (of a)
out = out.max(axis=0)
# fix up any -1 values
out[out == -1] = 0
return out
# TODO: dask linspace doesn't support delayed values
def _linspace_from_delayed(start, stop, num=50):
linspace_name = "linspace-" + tokenize(start, stop, num)
(start_ref, stop_ref, num_ref), deps = unpack_collections([start, stop, num])
if len(deps) == 0:
return np.linspace(start, stop, num=num)
linspace_dsk = {(linspace_name, 0): (np.linspace, start_ref, stop_ref, num_ref)}
linspace_graph = HighLevelGraph.from_collections(
linspace_name, linspace_dsk, dependencies=deps
)
chunks = ((np.nan,),) if is_dask_collection(num) else ((num,),)
return Array(linspace_graph, linspace_name, chunks, dtype=float)
def _block_hist(x, bins, range=None, weights=None):
return np.histogram(x, bins, range=range, weights=weights)[0][np.newaxis]
def histogram(a, bins=None, range=None, normed=False, weights=None, density=None):
"""
Blocked variant of :func:`numpy.histogram`.
Parameters
----------
a : dask.array.Array
Input data; the histogram is computed over the flattened
array. If the ``weights`` argument is used, the chunks of
``a`` are accessed to check chunking compatibility between
``a`` and ``weights``. If ``weights`` is ``None``, a
:py:class:`dask.dataframe.Series` object can be passed as
input data.
bins : int or sequence of scalars, optional
Either an iterable specifying the ``bins`` or the number of ``bins``
and a ``range`` argument is required as computing ``min`` and ``max``
over blocked arrays is an expensive operation that must be performed
explicitly.
If `bins` is an int, it defines the number of equal-width
bins in the given range (10, by default). If `bins` is a
sequence, it defines a monotonically increasing array of bin edges,
including the rightmost edge, allowing for non-uniform bin widths.
range : (float, float), optional
The lower and upper range of the bins. If not provided, range
is simply ``(a.min(), a.max())``. Values outside the range are
ignored. The first element of the range must be less than or
equal to the second. `range` affects the automatic bin
computation as well. While bin width is computed to be optimal
based on the actual data within `range`, the bin count will fill
the entire range including portions containing no data.
normed : bool, optional
This is equivalent to the ``density`` argument, but produces incorrect
results for unequal bin widths. It should not be used.
weights : dask.array.Array, optional
A dask.array.Array of weights, of the same block structure as ``a``. Each value in
``a`` only contributes its associated weight towards the bin count
(instead of 1). If ``density`` is True, the weights are
normalized, so that the integral of the density over the range
remains 1.
density : bool, optional
If ``False``, the result will contain the number of samples in
each bin. If ``True``, the result is the value of the
probability *density* function at the bin, normalized such that
the *integral* over the range is 1. Note that the sum of the
histogram values will not be equal to 1 unless bins of unity
width are chosen; it is not a probability *mass* function.
Overrides the ``normed`` keyword if given.
If ``density`` is True, ``bins`` cannot be a single-number delayed
value. It must be a concrete number, or a (possibly-delayed)
array/sequence of the bin edges.
Returns
-------
hist : dask Array
The values of the histogram. See `density` and `weights` for a
description of the possible semantics.
bin_edges : dask Array of dtype float
Return the bin edges ``(length(hist)+1)``.
Examples
--------
Using number of bins and range:
>>> import dask.array as da
>>> import numpy as np
>>> x = da.from_array(np.arange(10000), chunks=10)
>>> h, bins = da.histogram(x, bins=10, range=[0, 10000])
>>> bins
array([ 0., 1000., 2000., 3000., 4000., 5000., 6000., 7000.,
8000., 9000., 10000.])
>>> h.compute()
array([1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000])
Explicitly specifying the bins:
>>> h, bins = da.histogram(x, bins=np.array([0, 5000, 10000]))
>>> bins
array([ 0, 5000, 10000])
>>> h.compute()
array([5000, 5000])
"""
if isinstance(bins, Array):
scalar_bins = bins.ndim == 0
# ^ `np.ndim` is not implemented by Dask array.
elif isinstance(bins, Delayed):
scalar_bins = bins._length is None or bins._length == 1
else:
scalar_bins = np.ndim(bins) == 0
if bins is None or (scalar_bins and range is None):
raise ValueError(
"dask.array.histogram requires either specifying "
"bins as an iterable or specifying both a range and "
"the number of bins"
)
if weights is not None and weights.chunks != a.chunks:
raise ValueError("Input array and weights must have the same chunked structure")
if normed is not False:
raise ValueError(
"The normed= keyword argument has been deprecated. "
"Please use density instead. "
"See the numpy.histogram docstring for more information."
)
if density and scalar_bins and isinstance(bins, (Array, Delayed)):
raise NotImplementedError(
"When `density` is True, `bins` cannot be a scalar Dask object. "
"It must be a concrete number or a (possibly-delayed) array/sequence of bin edges."
)
for argname, val in [("bins", bins), ("range", range), ("weights", weights)]:
if not isinstance(bins, (Array, Delayed)) and is_dask_collection(bins):
raise TypeError(
"Dask types besides Array and Delayed are not supported "
"for `histogram`. For argument `{}`, got: {!r}".format(argname, val)
)
if range is not None:
try:
if len(range) != 2:
raise ValueError(
f"range must be a sequence or array of length 2, but got {len(range)} items"
)
if isinstance(range, (Array, np.ndarray)) and range.shape != (2,):
raise ValueError(
f"range must be a 1-dimensional array of two items, but got an array of shape {range.shape}"
)
except TypeError:
raise TypeError(
f"Expected a sequence or array for range, not {range}"
) from None
token = tokenize(a, bins, range, weights, density)
name = "histogram-sum-" + token
if scalar_bins:
bins = _linspace_from_delayed(range[0], range[1], bins + 1)
# ^ NOTE `range[1]` is safe because of the above check, and the initial check
# that range must not be None if `scalar_bins`
else:
if not isinstance(bins, (Array, np.ndarray)):
bins = asarray(bins)
if bins.ndim != 1:
raise ValueError(
f"bins must be a 1-dimensional array or sequence, got shape {bins.shape}"
)
(bins_ref, range_ref), deps = unpack_collections([bins, range])
# Map the histogram to all bins, forming a 2D array of histograms, stacked for each chunk
if weights is None:
dsk = {
(name, i, 0): (_block_hist, k, bins_ref, range_ref)
for i, k in enumerate(flatten(a.__dask_keys__()))
}
dtype = np.histogram([])[0].dtype
else:
a_keys = flatten(a.__dask_keys__())
w_keys = flatten(weights.__dask_keys__())
dsk = {
(name, i, 0): (_block_hist, k, bins_ref, range_ref, w)
for i, (k, w) in enumerate(zip(a_keys, w_keys))
}
dtype = weights.dtype
deps = (a,) + deps
if weights is not None:
deps += (weights,)
graph = HighLevelGraph.from_collections(name, dsk, dependencies=deps)
# Turn graph into a 2D Array of shape (nchunks, nbins)
nchunks = len(list(flatten(a.__dask_keys__())))
nbins = bins.size - 1 # since `bins` is 1D
chunks = ((1,) * nchunks, (nbins,))
mapped = Array(graph, name, chunks, dtype=dtype)
# Sum over chunks to get the final histogram
n = mapped.sum(axis=0)
# We need to replicate normed and density options from numpy
if density is not None:
if density:
db = asarray(np.diff(bins).astype(float), chunks=n.chunks)
return n / db / n.sum(), bins
else:
return n, bins
else:
return n, bins
def histogram2d(x, y, bins=10, range=None, normed=None, weights=None, density=None):
"""Blocked variant of :func:`numpy.histogram2d`.
Parameters
----------
x : dask.array.Array
An array containing the `x`-coordinates of the points to be
histogrammed.
y : dask.array.Array
An array containing the `y`-coordinates of the points to be
histogrammed.
bins : sequence of arrays describing bin edges, int, or sequence of ints
The bin specification. See the `bins` argument description for
:py:func:`histogramdd` for a complete description of all
possible bin configurations (this function is a 2D specific
version of histogramdd).
range : tuple of pairs, optional.
The leftmost and rightmost edges of the bins along each
dimension when integers are passed to `bins`; of the form:
((xmin, xmax), (ymin, ymax)).
normed : bool, optional
An alias for the density argument that behaves identically. To
avoid confusion with the broken argument in the `histogram`
function, `density` should be preferred.
weights : dask.array.Array, optional
An array of values weighing each sample in the input data. The
chunks of the weights must be identical to the chunking along
the 0th (row) axis of the data sample.
density : bool, optional
If False (the default) return the number of samples in each
bin. If True, the returned array represents the probability
density function at each bin.
Returns
-------
dask.array.Array
The values of the histogram.
dask.array.Array
The edges along the `x`-dimension.
dask.array.Array
The edges along the `y`-dimension.
See Also
--------
histogram
histogramdd
Examples
--------
>>> import dask.array as da
>>> x = da.array([2, 4, 2, 4, 2, 4])
>>> y = da.array([2, 2, 4, 4, 2, 4])
>>> bins = 2
>>> range = ((0, 6), (0, 6))
>>> h, xedges, yedges = da.histogram2d(x, y, bins=bins, range=range)
>>> h
dask.array<sum-aggregate, shape=(2, 2), dtype=float64, chunksize=(2, 2), chunktype=numpy.ndarray>
>>> xedges
dask.array<array, shape=(3,), dtype=float64, chunksize=(3,), chunktype=numpy.ndarray>
>>> h.compute()
array([[2., 1.],
[1., 2.]])
"""
counts, edges = histogramdd(
(x, y),
bins=bins,
range=range,
normed=normed,
weights=weights,
density=density,
)
return counts, edges[0], edges[1]
def _block_histogramdd_rect(sample, bins, range, weights):
"""Call numpy.histogramdd for a blocked/chunked calculation.
Slurps the result into an additional outer axis; this new axis
will be used to stack chunked calls of the numpy function and add
them together later.
Returns
-------
:py:object:`np.ndarray`
NumPy array with an additional outer dimension.
"""
return np.histogramdd(sample, bins, range=range, weights=weights)[0:1]
def _block_histogramdd_multiarg(*args):
"""Call numpy.histogramdd for a multi argument blocked/chunked calculation.
Slurps the result into an additional outer axis; this new axis
will be used to stack chunked calls of the numpy function and add
them together later.
The last three arguments _must be_ (bins, range, weights).
The difference between this function and
_block_histogramdd_rect is that here we expect the sample
to be composed of multiple arguments (multiple 1D arrays, each one
representing a coordinate), while _block_histogramdd_rect
expects a single rectangular (2D array where columns are
coordinates) sample.
"""
bins, range, weights = args[-3:]
sample = args[:-3]
return np.histogramdd(sample, bins=bins, range=range, weights=weights)[0:1]
def histogramdd(sample, bins, range=None, normed=None, weights=None, density=None):
"""Blocked variant of :func:`numpy.histogramdd`.
Chunking of the input data (``sample``) is only allowed along the
0th (row) axis (the axis corresponding to the total number of
samples). Data chunked along the 1st axis (column) axis is not
compatible with this function. If weights are used, they must be
chunked along the 0th axis identically to the input sample.
An example setup for a three dimensional histogram, where the
sample shape is ``(8, 3)`` and weights are shape ``(8,)``, sample
chunks would be ``((4, 4), (3,))`` and the weights chunks would be
``((4, 4),)`` a table of the structure:
+-------+-----------------------+-----------+
| | sample (8 x 3) | weights |
+=======+=====+=====+=====+=====+=====+=====+
| chunk | row | `x` | `y` | `z` | row | `w` |
+-------+-----+-----+-----+-----+-----+-----+
| | 0 | 5 | 6 | 6 | 0 | 0.5 |
| +-----+-----+-----+-----+-----+-----+
| | 1 | 8 | 9 | 2 | 1 | 0.8 |
| 0 +-----+-----+-----+-----+-----+-----+
| | 2 | 3 | 3 | 1 | 2 | 0.3 |
| +-----+-----+-----+-----+-----+-----+
| | 3 | 2 | 5 | 6 | 3 | 0.7 |
+-------+-----+-----+-----+-----+-----+-----+
| | 4 | 3 | 1 | 1 | 4 | 0.3 |
| +-----+-----+-----+-----+-----+-----+
| | 5 | 3 | 2 | 9 | 5 | 1.3 |
| 1 +-----+-----+-----+-----+-----+-----+
| | 6 | 8 | 1 | 5 | 6 | 0.8 |
| +-----+-----+-----+-----+-----+-----+
| | 7 | 3 | 5 | 3 | 7 | 0.7 |
+-------+-----+-----+-----+-----+-----+-----+
If the sample 0th dimension and weight 0th (row) dimension are
chunked differently, a ``ValueError`` will be raised. If
coordinate groupings ((x, y, z) trios) are separated by a chunk
boundry, then a ``ValueError`` will be raised. We suggest that you
rechunk your data if it is of that form.
The chunks property of the data (and optional weights) are used to
check for compatibility with the blocked algorithm (as described
above); therefore, you must call `to_dask_array` on a collection
from ``dask.dataframe``, i.e. :class:`dask.dataframe.Series` or
:class:`dask.dataframe.DataFrame`.
The function is also compatible with `x`, `y`, and `z` being
individual 1D arrays with equal chunking. In that case, the data
should be passed as a tuple: ``histogramdd((x, y, z), ...)``
Parameters
----------
sample : dask.array.Array (N, D) or sequence of dask.array.Array
Multidimensional data to be histogrammed.
Note the unusual interpretation of a sample when it is a
sequence of dask Arrays:
* When a (N, D) dask Array, each row is an entry in the sample
(coordinate in D dimensional space).
* When a sequence of dask Arrays, each element in the sequence
is the array of values for a single coordinate.
bins : sequence of arrays describing bin edges, int, or sequence of ints
The bin specification.
The possible binning configurations are:
* A sequence of arrays describing the monotonically increasing
bin edges along each dimension.
* A single int describing the total number of bins that will
be used in each dimension (this requires the ``range``
argument to be defined).
* A sequence of ints describing the total number of bins to be
used in each dimension (this requires the ``range`` argument
to be defined).
When bins are described by arrays, the rightmost edge is
included. Bins described by arrays also allows for non-uniform
bin widths.
range : sequence of pairs, optional
A sequence of length D, each a (min, max) tuple giving the
outer bin edges to be used if the edges are not given
explicitly in `bins`. If defined, this argument is required to
have an entry for each dimension. Unlike
:func:`numpy.histogramdd`, if `bins` does not define bin
edges, this argument is required (this function will not
automatically use the min and max of of the value in a given
dimension because the input data may be lazy in dask).
normed : bool, optional
An alias for the density argument that behaves identically. To
avoid confusion with the broken argument to `histogram`,
`density` should be preferred.
weights : dask.array.Array, optional
An array of values weighing each sample in the input data. The
chunks of the weights must be identical to the chunking along
the 0th (row) axis of the data sample.
density : bool, optional
If ``False`` (default), the returned array represents the
number of samples in each bin. If ``True``, the returned array
represents the probability density function at each bin.
See Also
--------
histogram
Returns
-------
dask.array.Array
The values of the histogram.
list(dask.array.Array)
Sequence of arrays representing the bin edges along each
dimension.
Examples
--------
Computing the histogram in 5 blocks using different bin edges
along each dimension:
>>> import dask.array as da
>>> x = da.random.uniform(0, 1, size=(1000, 3), chunks=(200, 3))
>>> edges = [
... np.linspace(0, 1, 5), # 4 bins in 1st dim
... np.linspace(0, 1, 6), # 5 in the 2nd
... np.linspace(0, 1, 4), # 3 in the 3rd
... ]
>>> h, edges = da.histogramdd(x, bins=edges)
>>> result = h.compute()
>>> result.shape
(4, 5, 3)
Defining the bins by total number and their ranges, along with
using weights:
>>> bins = (4, 5, 3)
>>> ranges = ((0, 1),) * 3 # expands to ((0, 1), (0, 1), (0, 1))
>>> w = da.random.uniform(0, 1, size=(1000,), chunks=x.chunksize[0])
>>> h, edges = da.histogramdd(x, bins=bins, range=ranges, weights=w)
>>> np.isclose(h.sum().compute(), w.sum().compute())
True
Using a sequence of 1D arrays as the input:
>>> x = da.array([2, 4, 2, 4, 2, 4])
>>> y = da.array([2, 2, 4, 4, 2, 4])
>>> z = da.array([4, 2, 4, 2, 4, 2])
>>> bins = ([0, 3, 6],) * 3
>>> h, edges = da.histogramdd((x, y, z), bins)
>>> h
dask.array<sum-aggregate, shape=(2, 2, 2), dtype=float64, chunksize=(2, 2, 2), chunktype=numpy.ndarray>
>>> edges[0]
dask.array<array, shape=(3,), dtype=int64, chunksize=(3,), chunktype=numpy.ndarray>
>>> h.compute()
array([[[0., 2.],
[0., 1.]],
<BLANKLINE>
[[1., 0.],
[2., 0.]]])
>>> edges[0].compute()
array([0, 3, 6])
>>> edges[1].compute()
array([0, 3, 6])
>>> edges[2].compute()
array([0, 3, 6])
"""
# logic used in numpy.histogramdd to handle normed/density.
if normed is None:
if density is None:
density = False
elif density is None:
# an explicit normed argument was passed, alias it to the new name
density = normed
else:
raise TypeError("Cannot specify both 'normed' and 'density'")
# check if any dask collections (dc) were passed to bins= or
# range= these are unsupported.
dc_bins = is_dask_collection(bins)
if isinstance(bins, (list, tuple)):
dc_bins = dc_bins or any([is_dask_collection(b) for b in bins])
dc_range = (
any([is_dask_collection(r) for r in range]) if range is not None else False
)
if dc_bins or dc_range:
raise NotImplementedError(
"Passing dask collections to bins=... or range=... is not supported."
)
# generate token and name for task
token = tokenize(sample, bins, range, weights, density)
name = f"histogramdd-sum-{token}"
# N == total number of samples
# D == total number of dimensions
if hasattr(sample, "shape"):
if len(sample.shape) != 2:
raise ValueError("Single array input to histogramdd should be columnar")
else:
_, D = sample.shape
n_chunks = sample.numblocks[0]
rectangular_sample = True
# Require data to be chunked along the first axis only.
if sample.shape[1:] != sample.chunksize[1:]:
raise ValueError("Input array can only be chunked along the 0th axis.")
elif isinstance(sample, (tuple, list)):
rectangular_sample = False
D = len(sample)
n_chunks = sample[0].numblocks[0]
for i in _range(1, D):
if sample[i].chunks != sample[0].chunks:
raise ValueError("All coordinate arrays must be chunked identically.")
else:
raise ValueError(
"Incompatible sample. Must be a 2D array or a sequence of 1D arrays."
)
# Require only Array or Delayed objects for bins, range, and weights.
for argname, val in [("bins", bins), ("range", range), ("weights", weights)]:
if not isinstance(bins, (Array, Delayed)) and is_dask_collection(bins):
raise TypeError(
"Dask types besides Array and Delayed are not supported "
"for `histogramdd`. For argument `{}`, got: {!r}".format(argname, val)
)
# Require that the chunking of the sample and weights are compatible.
if weights is not None:
if rectangular_sample and weights.chunks[0] != sample.chunks[0]:
raise ValueError(
"Input array and weights must have the same shape "
"and chunk structure along the first dimension."
)
elif not rectangular_sample and weights.numblocks[0] != n_chunks:
raise ValueError(
"Input arrays and weights must have the same shape "
"and chunk structure."
)
# if bins is a list, tuple, then make sure the length is the same
# as the number dimensions.
if isinstance(bins, (list, tuple)):
if len(bins) != D:
raise ValueError(
"The dimension of bins must be equal to the dimension of the sample."
)
# if range is defined, check that it's the right length and also a
# sequence of pairs.
if range is not None:
if len(range) != D:
raise ValueError(
"range argument requires one entry, a min max pair, per dimension."
)
if not all(len(r) == 2 for r in range):
raise ValueError("range argument should be a sequence of pairs")
# If bins is a single int, create a tuple of len `D` containing `bins`.
if isinstance(bins, int):
bins = (bins,) * D
# we will return the edges to mimic the NumPy API (we also use the
# edges later as a way to calculate the total number of bins).
if all(isinstance(b, int) for b in bins) and all(len(r) == 2 for r in range):
edges = [np.linspace(r[0], r[1], b + 1) for b, r in zip(bins, range)]
else:
edges = [np.asarray(b) for b in bins]
if rectangular_sample:
deps = (sample,)
else:
deps = tuple(sample)
if weights is not None:
w_keys = flatten(weights.__dask_keys__())
deps += (weights,)
dtype = weights.dtype
else:
w_keys = (None,) * n_chunks
dtype = np.histogramdd([])[0].dtype
# This tuple of zeros represents the chunk index along the columns
# (we only allow chunking along the rows).
column_zeros = tuple(0 for _ in _range(D))
# With dsk below, we will construct a (D + 1) dimensional array
# stacked for each chunk. For example, if the histogram is going
# to be 3 dimensions, this creates a stack of cubes (1 cube for
# each sample chunk) that will be collapsed into a final cube (the
# result). Depending on the input data, we can do this in two ways
#
# 1. The rectangular case: when the sample is a single 2D array
# where each column in the sample represents a coordinate of
# the sample).
#
# 2. The sequence-of-arrays case, when the sample is a tuple or
# list of arrays, with each array in that sequence representing
# the entirety of one coordinate of the complete sample.
if rectangular_sample:
sample_keys = flatten(sample.__dask_keys__())
dsk = {
(name, i, *column_zeros): (_block_histogramdd_rect, k, bins, range, w)
for i, (k, w) in enumerate(zip(sample_keys, w_keys))
}
else:
sample_keys = [
list(flatten(sample[i].__dask_keys__())) for i in _range(len(sample))
]
fused_on_chunk_keys = [
tuple(sample_keys[j][i] for j in _range(D)) for i in _range(n_chunks)
]
dsk = {
(name, i, *column_zeros): (
_block_histogramdd_multiarg,
*(*k, bins, range, w),
)
for i, (k, w) in enumerate(zip(fused_on_chunk_keys, w_keys))
}
graph = HighLevelGraph.from_collections(name, dsk, dependencies=deps)
all_nbins = tuple((b.size - 1,) for b in edges)
stacked_chunks = ((1,) * n_chunks, *all_nbins)
mapped = Array(graph, name, stacked_chunks, dtype=dtype)
# Finally, sum over chunks providing to get the final D
# dimensional result array.
n = mapped.sum(axis=0)
if density:
# compute array of values to divide by the bin width along
# each dimension.
width_divider = np.ones(n.shape)
for i in _range(D):
shape = np.ones(D, int)
shape[i] = width_divider.shape[i]
width_divider *= np.diff(edges[i]).reshape(shape)
width_divider = asarray(width_divider, chunks=n.chunks)
return n / width_divider / n.sum(), edges
return n, [asarray(entry) for entry in edges]
@derived_from(np)
def cov(m, y=None, rowvar=1, bias=0, ddof=None):
# This was copied almost verbatim from np.cov
# See numpy license at https://github.com/numpy/numpy/blob/master/LICENSE.txt
# or NUMPY_LICENSE.txt within this directory
if ddof is not None and ddof != int(ddof):
raise ValueError("ddof must be integer")
# Handles complex arrays too
m = asarray(m)
if y is None:
dtype = np.result_type(m, np.float64)
else:
y = asarray(y)
dtype = np.result_type(m, y, np.float64)
X = array(m, ndmin=2, dtype=dtype)
if X.shape[0] == 1:
rowvar = 1
if rowvar:
N = X.shape[1]
axis = 0
else:
N = X.shape[0]
axis = 1
# check ddof
if ddof is None:
if bias == 0:
ddof = 1
else:
ddof = 0
fact = float(N - ddof)
if fact <= 0:
warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning)
fact = 0.0
if y is not None:
y = array(y, ndmin=2, dtype=dtype)
X = concatenate((X, y), axis)
X = X - X.mean(axis=1 - axis, keepdims=True)
if not rowvar:
return (dot(X.T, X.conj()) / fact).squeeze()
else:
return (dot(X, X.T.conj()) / fact).squeeze()
@derived_from(np)
def corrcoef(x, y=None, rowvar=1):
c = cov(x, y, rowvar)
if c.shape == ():
return c / c
d = diag(c)
d = d.reshape((d.shape[0], 1))
sqr_d = sqrt(d)
return (c / sqr_d) / sqr_d.T
@implements(np.round, np.round_)
@derived_from(np)
def round(a, decimals=0):
return a.map_blocks(np.round, decimals=decimals, dtype=a.dtype)
@implements(np.ndim)
@derived_from(np)
def ndim(a):
return a.ndim
@implements(np.iscomplexobj)
@derived_from(np)
def iscomplexobj(x):
return issubclass(x.dtype.type, np.complexfloating)
def _unique_internal(ar, indices, counts, return_inverse=False):
"""
Helper/wrapper function for :func:`numpy.unique`.
Uses :func:`numpy.unique` to find the unique values for the array chunk.
Given this chunk may not represent the whole array, also take the
``indices`` and ``counts`` that are in 1-to-1 correspondence to ``ar``
and reduce them in the same fashion as ``ar`` is reduced. Namely sum
any counts that correspond to the same value and take the smallest
index that corresponds to the same value.
To handle the inverse mapping from the unique values to the original
array, simply return a NumPy array created with ``arange`` with enough
values to correspond 1-to-1 to the unique values. While there is more
work needed to be done to create the full inverse mapping for the
original array, this provides enough information to generate the
inverse mapping in Dask.
Given Dask likes to have one array returned from functions like
``blockwise``, some formatting is done to stuff all of the resulting arrays
into one big NumPy structured array. Dask is then able to handle this
object and can split it apart into the separate results on the Dask side,
which then can be passed back to this function in concatenated chunks for
further reduction or can be return to the user to perform other forms of
analysis.
By handling the problem in this way, it does not matter where a chunk
is in a larger array or how big it is. The chunk can still be computed
on the same way. Also it does not matter if the chunk is the result of
other chunks being run through this function multiple times. The end
result will still be just as accurate using this strategy.
"""
return_index = indices is not None
return_counts = counts is not None
u = np.unique(ar)
dt = [("values", u.dtype)]
if return_index:
dt.append(("indices", np.intp))
if return_inverse:
dt.append(("inverse", np.intp))
if return_counts:
dt.append(("counts", np.intp))
r = np.empty(u.shape, dtype=dt)
r["values"] = u
if return_inverse:
r["inverse"] = np.arange(len(r), dtype=np.intp)
if return_index or return_counts:
for i, v in enumerate(r["values"]):
m = ar == v
if return_index:
indices[m].min(keepdims=True, out=r["indices"][i : i + 1])
if return_counts:
counts[m].sum(keepdims=True, out=r["counts"][i : i + 1])
return r
def unique_no_structured_arr(
ar, return_index=False, return_inverse=False, return_counts=False
):
# A simplified version of `unique`, that allows computing unique for array
# types that don't support structured arrays (such as cupy.ndarray), but
# can only compute values at the moment.
if (
return_index is not False
or return_inverse is not False
or return_counts is not False
):
raise ValueError(
"dask.array.unique does not support `return_index`, `return_inverse` "
"or `return_counts` with array types that don't support structured "
"arrays."
)
ar = ar.ravel()
args = [ar, "i"]
meta = meta_from_array(ar)
out = blockwise(np.unique, "i", *args, meta=meta)
out._chunks = tuple((np.nan,) * len(c) for c in out.chunks)
out_parts = [out]
name = "unique-aggregate-" + out.name
dsk = {
(name, 0): (
(np.unique,)
+ tuple(
(np.concatenate, o.__dask_keys__())
if hasattr(o, "__dask_keys__")
else o
for o in out_parts
)
)
}
dependencies = [o for o in out_parts if hasattr(o, "__dask_keys__")]
graph = HighLevelGraph.from_collections(name, dsk, dependencies=dependencies)
chunks = ((np.nan,),)
out = Array(graph, name, chunks, meta=meta)
result = [out]
if len(result) == 1:
result = result[0]
else:
result = tuple(result)
return result
@derived_from(np)
def unique(ar, return_index=False, return_inverse=False, return_counts=False):
# Test whether the downstream library supports structured arrays. If the
# `np.empty_like` call raises a `TypeError`, the downstream library (e.g.,
# CuPy) doesn't support it. In that case we return the
# `unique_no_structured_arr` implementation, otherwise (e.g., NumPy) just
# continue as normal.
try:
meta = meta_from_array(ar)
np.empty_like(meta, dtype=[("a", int), ("b", float)])
except TypeError:
return unique_no_structured_arr(
ar,
return_index=return_index,
return_inverse=return_inverse,
return_counts=return_counts,
)
ar = ar.ravel()
# Run unique on each chunk and collect results in a Dask Array of
# unknown size.
args = [ar, "i"]
out_dtype = [("values", ar.dtype)]
if return_index:
args.extend([arange(ar.shape[0], dtype=np.intp, chunks=ar.chunks[0]), "i"])
out_dtype.append(("indices", np.intp))
else:
args.extend([None, None])
if return_counts:
args.extend([ones((ar.shape[0],), dtype=np.intp, chunks=ar.chunks[0]), "i"])
out_dtype.append(("counts", np.intp))
else:
args.extend([None, None])
out = blockwise(_unique_internal, "i", *args, dtype=out_dtype, return_inverse=False)
out._chunks = tuple((np.nan,) * len(c) for c in out.chunks)
# Take the results from the unique chunks and do the following.
#
# 1. Collect all results as arguments.
# 2. Concatenate each result into one big array.
# 3. Pass all results as arguments to the internal unique again.
#
# TODO: This should be replaced with a tree reduction using this strategy.
# xref: https://github.com/dask/dask/issues/2851
out_parts = [out["values"]]
if return_index:
out_parts.append(out["indices"])
else:
out_parts.append(None)
if return_counts:
out_parts.append(out["counts"])
else:
out_parts.append(None)
name = "unique-aggregate-" + out.name
dsk = {
(name, 0): (
(_unique_internal,)
+ tuple(
(np.concatenate, o.__dask_keys__())
if hasattr(o, "__dask_keys__")
else o
for o in out_parts
)
+ (return_inverse,)
)
}
out_dtype = [("values", ar.dtype)]
if return_index:
out_dtype.append(("indices", np.intp))
if return_inverse:
out_dtype.append(("inverse", np.intp))
if return_counts:
out_dtype.append(("counts", np.intp))
dependencies = [o for o in out_parts if hasattr(o, "__dask_keys__")]
graph = HighLevelGraph.from_collections(name, dsk, dependencies=dependencies)
chunks = ((np.nan,),)
out = Array(graph, name, chunks, out_dtype)
# Split out all results to return to the user.
result = [out["values"]]
if return_index:
result.append(out["indices"])
if return_inverse:
# Using the returned unique values and arange of unknown length, find
# each value matching a unique value and replace it with its
# corresponding index or `0`. There should be only one entry for this
# index in axis `1` (the one of unknown length). Reduce axis `1`
# through summing to get an array with known dimensionality and the
# mapping of the original values.
mtches = (ar[:, None] == out["values"][None, :]).astype(np.intp)
result.append((mtches * out["inverse"]).sum(axis=1))
if return_counts:
result.append(out["counts"])
if len(result) == 1:
result = result[0]
else:
result = tuple(result)
return result
def _isin_kernel(element, test_elements, assume_unique=False):
values = np.in1d(element.ravel(), test_elements, assume_unique=assume_unique)
return values.reshape(element.shape + (1,) * test_elements.ndim)
@safe_wraps(getattr(np, "isin", None))
def isin(element, test_elements, assume_unique=False, invert=False):
element = asarray(element)
test_elements = asarray(test_elements)
element_axes = tuple(range(element.ndim))
test_axes = tuple(i + element.ndim for i in range(test_elements.ndim))
mapped = blockwise(
_isin_kernel,
element_axes + test_axes,
element,
element_axes,
test_elements,
test_axes,
adjust_chunks={axis: lambda _: 1 for axis in test_axes},
dtype=bool,
assume_unique=assume_unique,
)
result = mapped.any(axis=test_axes)
if invert:
result = ~result
return result
@derived_from(np)
def roll(array, shift, axis=None):
result = array
if axis is None:
result = ravel(result)
if not isinstance(shift, Integral):
raise TypeError(
"Expect `shift` to be an instance of Integral when `axis` is None."
)
shift = (shift,)
axis = (0,)
else:
try:
len(shift)
except TypeError:
shift = (shift,)
try:
len(axis)
except TypeError:
axis = (axis,)
if len(shift) != len(axis):
raise ValueError("Must have the same number of shifts as axes.")
for i, s in zip(axis, shift):
s = -s
s %= result.shape[i]
sl1 = result.ndim * [slice(None)]
sl2 = result.ndim * [slice(None)]
sl1[i] = slice(s, None)
sl2[i] = slice(None, s)
sl1 = tuple(sl1)
sl2 = tuple(sl2)
result = concatenate([result[sl1], result[sl2]], axis=i)
result = result.reshape(array.shape)
# Ensure that the output is always a new array object
result = result.copy() if result is array else result
return result
@derived_from(np)
def shape(array):
return array.shape
@derived_from(np)
def union1d(ar1, ar2):
return unique(concatenate((ar1.ravel(), ar2.ravel())))
@derived_from(np)
def ravel(array_like):
return asanyarray(array_like).reshape((-1,))
@derived_from(np)
def expand_dims(a, axis):
if type(axis) not in (tuple, list):
axis = (axis,)
out_ndim = len(axis) + a.ndim
axis = validate_axis(axis, out_ndim)
shape_it = iter(a.shape)
shape = [1 if ax in axis else next(shape_it) for ax in range(out_ndim)]
return a.reshape(shape)
@derived_from(np)
def squeeze(a, axis=None):
if axis is None:
axis = tuple(i for i, d in enumerate(a.shape) if d == 1)
elif not isinstance(axis, tuple):
axis = (axis,)
if any(a.shape[i] != 1 for i in axis):
raise ValueError("cannot squeeze axis with size other than one")
axis = validate_axis(axis, a.ndim)
sl = tuple(0 if i in axis else slice(None) for i, s in enumerate(a.shape))
a = a[sl]
return a
@derived_from(np)
def compress(condition, a, axis=None):
if not is_arraylike(condition):
# Allow `condition` to be anything array-like, otherwise ensure `condition`
# is a numpy array.
condition = np.asarray(condition)
condition = condition.astype(bool)
a = asarray(a)
if condition.ndim != 1:
raise ValueError("Condition must be one dimensional")
if axis is None:
a = a.ravel()
axis = 0
axis = validate_axis(axis, a.ndim)
# Treat `condition` as filled with `False` (if it is too short)
a = a[
tuple(
slice(None, len(condition)) if i == axis else slice(None)
for i in range(a.ndim)
)
]
# Use `condition` to select along 1 dimension
a = a[tuple(condition if i == axis else slice(None) for i in range(a.ndim))]
return a
@derived_from(np)
def extract(condition, arr):
condition = asarray(condition).astype(bool)
arr = asarray(arr)
return compress(condition.ravel(), arr.ravel())
@derived_from(np)
def take(a, indices, axis=0):
axis = validate_axis(axis, a.ndim)
if isinstance(a, np.ndarray) and isinstance(indices, Array):
return _take_dask_array_from_numpy(a, indices, axis)
else:
return a[(slice(None),) * axis + (indices,)]
def _take_dask_array_from_numpy(a, indices, axis):
assert isinstance(a, np.ndarray)
assert isinstance(indices, Array)
return indices.map_blocks(
lambda block: np.take(a, block, axis), chunks=indices.chunks, dtype=a.dtype
)
@derived_from(np)
def around(x, decimals=0):
return map_blocks(partial(np.around, decimals=decimals), x, dtype=x.dtype)
def _asarray_isnull(values):
import pandas as pd
return np.asarray(pd.isnull(values))
def isnull(values):
"""pandas.isnull for dask arrays"""
# eagerly raise ImportError, if pandas isn't available
import pandas as pd # noqa
return elemwise(_asarray_isnull, values, dtype="bool")
def notnull(values):
"""pandas.notnull for dask arrays"""
return ~isnull(values)
@derived_from(np)
def isclose(arr1, arr2, rtol=1e-5, atol=1e-8, equal_nan=False):
func = partial(np.isclose, rtol=rtol, atol=atol, equal_nan=equal_nan)
return elemwise(func, arr1, arr2, dtype="bool")
@derived_from(np)
def allclose(arr1, arr2, rtol=1e-5, atol=1e-8, equal_nan=False):
return isclose(arr1, arr2, rtol=rtol, atol=atol, equal_nan=equal_nan).all()
def variadic_choose(a, *choices):
return np.choose(a, choices)
@derived_from(np)
def choose(a, choices):
return elemwise(variadic_choose, a, *choices)
def _isnonzero_vec(v):
return bool(np.count_nonzero(v))
_isnonzero_vec = np.vectorize(_isnonzero_vec, otypes=[bool])
def isnonzero(a):
if a.dtype.kind in {"U", "S"}:
# NumPy treats all-whitespace strings as falsy (like in `np.nonzero`).
# but not in `.astype(bool)`. To match the behavior of numpy at least until
# 1.19, we use `_isnonzero_vec`. When NumPy changes behavior, we should just
# use the try block below.
# https://github.com/numpy/numpy/issues/9875
return a.map_blocks(_isnonzero_vec, dtype=bool)
try:
np.zeros(tuple(), dtype=a.dtype).astype(bool)
except ValueError:
######################################################
# Handle special cases where conversion to bool does #
# not work correctly. #
# #
# xref: https://github.com/numpy/numpy/issues/9479 #
######################################################
return a.map_blocks(_isnonzero_vec, dtype=bool)
else:
return a.astype(bool)
@derived_from(np)
def argwhere(a):
a = asarray(a)
nz = isnonzero(a).flatten()
ind = indices(a.shape, dtype=np.intp, chunks=a.chunks)
if ind.ndim > 1:
ind = stack([ind[i].ravel() for i in range(len(ind))], axis=1)
ind = compress(nz, ind, axis=0)
return ind
@derived_from(np)
def where(condition, x=None, y=None):
if (x is None) != (y is None):
raise ValueError("either both or neither of x and y should be given")
if (x is None) and (y is None):
return nonzero(condition)
if np.isscalar(condition):
dtype = result_type(x, y)
x = asarray(x)
y = asarray(y)
shape = broadcast_shapes(x.shape, y.shape)
out = x if condition else y
return broadcast_to(out, shape).astype(dtype)
else:
return elemwise(np.where, condition, x, y)
@derived_from(np)
def count_nonzero(a, axis=None):
return isnonzero(asarray(a)).astype(np.intp).sum(axis=axis)
@derived_from(np)
def flatnonzero(a):
return argwhere(asarray(a).ravel())[:, 0]
@derived_from(np)
def nonzero(a):
ind = argwhere(a)
if ind.ndim > 1:
return tuple(ind[:, i] for i in range(ind.shape[1]))
else:
return (ind,)
def _unravel_index_kernel(indices, func_kwargs):
return np.stack(np.unravel_index(indices, **func_kwargs))
@derived_from(np)
def unravel_index(indices, shape, order="C"):
if shape and indices.size:
unraveled_indices = tuple(
indices.map_blocks(
_unravel_index_kernel,
dtype=np.intp,
chunks=(((len(shape),),) + indices.chunks),
new_axis=0,
func_kwargs={"shape": shape, "order": order},
)
)
else:
unraveled_indices = tuple(empty((0,), dtype=np.intp, chunks=1) for i in shape)
return unraveled_indices
@wraps(np.ravel_multi_index)
def ravel_multi_index(multi_index, dims, mode="raise", order="C"):
if np.isscalar(dims):
dims = (dims,)
if is_dask_collection(dims) or any(is_dask_collection(d) for d in dims):
raise NotImplementedError(
f"Dask types are not supported in the `dims` argument: {dims!r}"
)
if is_arraylike(multi_index):
index_stack = asarray(multi_index)
else:
multi_index_arrs = broadcast_arrays(*multi_index)
index_stack = stack(multi_index_arrs)
if not np.isnan(index_stack.shape).any() and len(index_stack) != len(dims):
raise ValueError(
f"parameter multi_index must be a sequence of length {len(dims)}"
)
if not np.issubdtype(index_stack.dtype, np.signedinteger):
raise TypeError("only int indices permitted")
return index_stack.map_blocks(
np.ravel_multi_index,
dtype=np.intp,
chunks=index_stack.chunks[1:],
drop_axis=0,
dims=dims,
mode=mode,
order=order,
)
def _int_piecewise(x, *condlist, **kwargs):
return np.piecewise(
x, list(condlist), kwargs["funclist"], *kwargs["func_args"], **kwargs["func_kw"]
)
@derived_from(np)
def piecewise(x, condlist, funclist, *args, **kw):
return map_blocks(
_int_piecewise,
x,
*condlist,
dtype=x.dtype,
name="piecewise",
funclist=funclist,
func_args=args,
func_kw=kw,
)
def _select(*args, **kwargs):
"""
This is a version of :func:`numpy.select` that acceptes an arbitrary number of arguments and
splits them in half to create ``condlist`` and ``choicelist`` params.
"""
split_at = len(args) // 2
condlist = args[:split_at]
choicelist = args[split_at:]
return np.select(condlist, choicelist, **kwargs)
@derived_from(np)
def select(condlist, choicelist, default=0):
# Making the same checks that np.select
# Check the size of condlist and choicelist are the same, or abort.
if len(condlist) != len(choicelist):
raise ValueError("list of cases must be same length as list of conditions")
if len(condlist) == 0:
raise ValueError("select with an empty condition list is not possible")
choicelist = [asarray(choice) for choice in choicelist]
try:
intermediate_dtype = result_type(*choicelist)
except TypeError as e:
msg = "Choicelist elements do not have a common dtype."
raise TypeError(msg) from e
blockwise_shape = tuple(range(choicelist[0].ndim))
condargs = [arg for elem in condlist for arg in (elem, blockwise_shape)]
choiceargs = [arg for elem in choicelist for arg in (elem, blockwise_shape)]
return blockwise(
_select,
blockwise_shape,
*condargs,
*choiceargs,
dtype=intermediate_dtype,
name="select",
default=default,
)
def _partition(total: int, divisor: int) -> tuple[tuple[int, ...], tuple[int, ...]]:
"""Given a total and a divisor, return two tuples: A tuple containing `divisor`
repeated the number of times it divides `total`, and length-1 or empty tuple
containing the remainder when `total` is divided by `divisor`. If `divisor` factors
`total`, i.e. if the remainder is 0, then `remainder` is empty.
"""
multiples = (divisor,) * (total // divisor)
remainder = (total % divisor,) if total % divisor else ()
return multiples, remainder
def aligned_coarsen_chunks(chunks: list[int], multiple: int) -> tuple[int, ...]:
"""
Returns a new chunking aligned with the coarsening multiple.
Any excess is at the end of the array.
Examples
--------
>>> aligned_coarsen_chunks(chunks=(1, 2, 3), multiple=4)
(4, 2)
>>> aligned_coarsen_chunks(chunks=(1, 20, 3, 4), multiple=4)
(4, 20, 4)
>>> aligned_coarsen_chunks(chunks=(20, 10, 15, 23, 24), multiple=10)
(20, 10, 20, 20, 20, 2)
"""
overflow = np.array(chunks) % multiple
excess = overflow.sum()
new_chunks = np.array(chunks) - overflow
# valid chunks are those that are already factorizable by `multiple`
chunk_validity = new_chunks == chunks
valid_inds, invalid_inds = np.where(chunk_validity)[0], np.where(~chunk_validity)[0]
# sort the invalid chunks by size (ascending), then concatenate the results of
# sorting the valid chunks by size (ascending)
chunk_modification_order = [
*invalid_inds[np.argsort(new_chunks[invalid_inds])],
*valid_inds[np.argsort(new_chunks[valid_inds])],
]
partitioned_excess, remainder = _partition(excess, multiple)
# add elements the partitioned excess to the smallest invalid chunks,
# then smallest valid chunks if needed.
for idx, extra in enumerate(partitioned_excess):
new_chunks[chunk_modification_order[idx]] += extra
# create excess chunk with remainder, if any remainder exists
new_chunks = np.array([*new_chunks, *remainder])
# remove 0-sized chunks
new_chunks = new_chunks[new_chunks > 0]
return tuple(new_chunks)
@wraps(chunk.coarsen)
def coarsen(reduction, x, axes, trim_excess=False, **kwargs):
if not trim_excess and not all(x.shape[i] % div == 0 for i, div in axes.items()):
msg = f"Coarsening factors {axes} do not align with array shape {x.shape}."
raise ValueError(msg)
if reduction.__module__.startswith("dask."):
reduction = getattr(np, reduction.__name__)
new_chunks = {}
for i, div in axes.items():
aligned = aligned_coarsen_chunks(x.chunks[i], div)
if aligned != x.chunks[i]:
new_chunks[i] = aligned
if new_chunks:
x = x.rechunk(new_chunks)
name = "coarsen-" + tokenize(reduction, x, axes, trim_excess)
dsk = {
(name,)
+ key[1:]: (apply, chunk.coarsen, [reduction, key, axes, trim_excess], kwargs)
for key in flatten(x.__dask_keys__())
}
chunks = tuple(
tuple(int(bd // axes.get(i, 1)) for bd in bds) for i, bds in enumerate(x.chunks)
)
meta = reduction(np.empty((1,) * x.ndim, dtype=x.dtype), **kwargs)
graph = HighLevelGraph.from_collections(name, dsk, dependencies=[x])
return Array(graph, name, chunks, meta=meta)
def split_at_breaks(array, breaks, axis=0):
"""Split an array into a list of arrays (using slices) at the given breaks
>>> split_at_breaks(np.arange(6), [3, 5])
[array([0, 1, 2]), array([3, 4]), array([5])]
"""
padded_breaks = concat([[None], breaks, [None]])
slices = [slice(i, j) for i, j in sliding_window(2, padded_breaks)]
preslice = (slice(None),) * axis
split_array = [array[preslice + (s,)] for s in slices]
return split_array
@derived_from(np)
def insert(arr, obj, values, axis):
# axis is a required argument here to avoid needing to deal with the numpy
# default case (which reshapes the array to make it flat)
axis = validate_axis(axis, arr.ndim)
if isinstance(obj, slice):
obj = np.arange(*obj.indices(arr.shape[axis]))
obj = np.asarray(obj)
scalar_obj = obj.ndim == 0
if scalar_obj:
obj = np.atleast_1d(obj)
obj = np.where(obj < 0, obj + arr.shape[axis], obj)
if (np.diff(obj) < 0).any():
raise NotImplementedError(
"da.insert only implemented for monotonic ``obj`` argument"
)
split_arr = split_at_breaks(arr, np.unique(obj), axis)
if getattr(values, "ndim", 0) == 0:
# we need to turn values into a dask array
name = "values-" + tokenize(values)
dtype = getattr(values, "dtype", type(values))
values = Array({(name,): values}, name, chunks=(), dtype=dtype)
values_shape = tuple(
len(obj) if axis == n else s for n, s in enumerate(arr.shape)
)
values = broadcast_to(values, values_shape)
elif scalar_obj:
values = values[(slice(None),) * axis + (None,)]
values_chunks = tuple(
values_bd if axis == n else arr_bd
for n, (arr_bd, values_bd) in enumerate(zip(arr.chunks, values.chunks))
)
values = values.rechunk(values_chunks)
counts = np.bincount(obj)[:-1]
values_breaks = np.cumsum(counts[counts > 0])
split_values = split_at_breaks(values, values_breaks, axis)
interleaved = list(interleave([split_arr, split_values]))
interleaved = [i for i in interleaved if i.nbytes]
return concatenate(interleaved, axis=axis)
@derived_from(np)
def delete(arr, obj, axis):
"""
NOTE: If ``obj`` is a dask array it is implicitly computed when this function
is called.
"""
# axis is a required argument here to avoid needing to deal with the numpy
# default case (which reshapes the array to make it flat)
axis = validate_axis(axis, arr.ndim)
if isinstance(obj, slice):
tmp = np.arange(*obj.indices(arr.shape[axis]))
obj = tmp[::-1] if obj.step and obj.step < 0 else tmp
else:
obj = np.asarray(obj)
obj = np.where(obj < 0, obj + arr.shape[axis], obj)
obj = np.unique(obj)
target_arr = split_at_breaks(arr, obj, axis)
target_arr = [
arr[
tuple(slice(1, None) if axis == n else slice(None) for n in range(arr.ndim))
]
if i != 0
else arr
for i, arr in enumerate(target_arr)
]
return concatenate(target_arr, axis=axis)
@derived_from(np)
def append(arr, values, axis=None):
# based on numpy.append
arr = asanyarray(arr)
if axis is None:
if arr.ndim != 1:
arr = arr.ravel()
values = ravel(asanyarray(values))
axis = arr.ndim - 1
return concatenate((arr, values), axis=axis)
def _average(a, axis=None, weights=None, returned=False, is_masked=False):
# This was minimally modified from numpy.average
# See numpy license at https://github.com/numpy/numpy/blob/master/LICENSE.txt
# or NUMPY_LICENSE.txt within this directory
# Wrapper used by da.average or da.ma.average.
a = asanyarray(a)
if weights is None:
avg = a.mean(axis)
scl = avg.dtype.type(a.size / avg.size)
else:
wgt = asanyarray(weights)
if issubclass(a.dtype.type, (np.integer, np.bool_)):
result_dtype = result_type(a.dtype, wgt.dtype, "f8")
else:
result_dtype = result_type(a.dtype, wgt.dtype)
# Sanity checks
if a.shape != wgt.shape:
if axis is None:
raise TypeError(
"Axis must be specified when shapes of a and weights differ."
)
if wgt.ndim != 1:
raise TypeError(
"1D weights expected when shapes of a and weights differ."
)
if wgt.shape[0] != a.shape[axis]:
raise ValueError(
"Length of weights not compatible with specified axis."
)
# setup wgt to broadcast along axis
wgt = broadcast_to(wgt, (a.ndim - 1) * (1,) + wgt.shape)
wgt = wgt.swapaxes(-1, axis)
if is_masked:
from dask.array.ma import getmaskarray
wgt = wgt * (~getmaskarray(a))
scl = wgt.sum(axis=axis, dtype=result_dtype)
avg = multiply(a, wgt, dtype=result_dtype).sum(axis) / scl
if returned:
if scl.shape != avg.shape:
scl = broadcast_to(scl, avg.shape).copy()
return avg, scl
else:
return avg
@derived_from(np)
def average(a, axis=None, weights=None, returned=False):
return _average(a, axis, weights, returned, is_masked=False)
@derived_from(np)
def tril(m, k=0):
m = asarray_safe(m, like=m)
mask = tri(
*m.shape[-2:],
k=k,
dtype=bool,
chunks=m.chunks[-2:],
like=meta_from_array(m) if _numpy_120 else None,
)
return where(mask, m, np.zeros_like(m, shape=(1,)))
@derived_from(np)
def triu(m, k=0):
m = asarray_safe(m, like=m)
mask = tri(
*m.shape[-2:],
k=k - 1,
dtype=bool,
chunks=m.chunks[-2:],
like=meta_from_array(m) if _numpy_120 else None,
)
return where(mask, np.zeros_like(m, shape=(1,)), m)
@derived_from(np)
def tril_indices(n, k=0, m=None, chunks="auto"):
return nonzero(tri(n, m, k=k, dtype=bool, chunks=chunks))
@derived_from(np)
def tril_indices_from(arr, k=0):
if arr.ndim != 2:
raise ValueError("input array must be 2-d")
return tril_indices(arr.shape[-2], k=k, m=arr.shape[-1], chunks=arr.chunks)
@derived_from(np)
def triu_indices(n, k=0, m=None, chunks="auto"):
return nonzero(~tri(n, m, k=k - 1, dtype=bool, chunks=chunks))
@derived_from(np)
def triu_indices_from(arr, k=0):
if arr.ndim != 2:
raise ValueError("input array must be 2-d")
return triu_indices(arr.shape[-2], k=k, m=arr.shape[-1], chunks=arr.chunks)
| 32.167915 | 112 | 0.609962 | from __future__ import annotations
import math
import warnings
from collections.abc import Iterable
from functools import partial, reduce, wraps
from numbers import Integral, Real
import numpy as np
from tlz import concat, interleave, sliding_window
from dask.array import chunk
from dask.array.core import (
Array,
asanyarray,
asarray,
blockwise,
broadcast_arrays,
broadcast_shapes,
broadcast_to,
concatenate,
elemwise,
from_array,
implements,
is_scalar_for_elemwise,
map_blocks,
stack,
tensordot_lookup,
)
from dask.array.creation import arange, diag, empty, indices, tri
from dask.array.einsumfuncs import einsum
from dask.array.numpy_compat import _numpy_120
from dask.array.reductions import reduction
from dask.array.ufunc import multiply, sqrt
from dask.array.utils import (
array_safe,
asarray_safe,
meta_from_array,
safe_wraps,
validate_axis,
)
from dask.array.wrap import ones
from dask.base import is_dask_collection, tokenize
from dask.core import flatten
from dask.delayed import Delayed, unpack_collections
from dask.highlevelgraph import HighLevelGraph
from dask.utils import apply, derived_from, funcname, is_arraylike, is_cupy_type
_range = range
@derived_from(np)
def array(x, dtype=None, ndmin=None, *, like=None):
if not _numpy_120 and like is not None:
raise RuntimeError("The use of ``like`` required NumPy >= 1.20")
x = asarray(x, like=like)
while ndmin is not None and x.ndim < ndmin:
x = x[None, :]
if dtype is not None and x.dtype != dtype:
x = x.astype(dtype)
return x
@derived_from(np)
def result_type(*args):
args = [a if is_scalar_for_elemwise(a) else a.dtype for a in args]
return np.result_type(*args)
@derived_from(np)
def atleast_3d(*arys):
new_arys = []
for x in arys:
x = asanyarray(x)
if x.ndim == 0:
x = x[None, None, None]
elif x.ndim == 1:
x = x[None, :, None]
elif x.ndim == 2:
x = x[:, :, None]
new_arys.append(x)
if len(new_arys) == 1:
return new_arys[0]
else:
return new_arys
@derived_from(np)
def atleast_2d(*arys):
new_arys = []
for x in arys:
x = asanyarray(x)
if x.ndim == 0:
x = x[None, None]
elif x.ndim == 1:
x = x[None, :]
new_arys.append(x)
if len(new_arys) == 1:
return new_arys[0]
else:
return new_arys
@derived_from(np)
def atleast_1d(*arys):
new_arys = []
for x in arys:
x = asanyarray(x)
if x.ndim == 0:
x = x[None]
new_arys.append(x)
if len(new_arys) == 1:
return new_arys[0]
else:
return new_arys
@derived_from(np)
def vstack(tup, allow_unknown_chunksizes=False):
if isinstance(tup, Array):
raise NotImplementedError(
"``vstack`` expects a sequence of arrays as the first argument"
)
tup = tuple(atleast_2d(x) for x in tup)
return concatenate(tup, axis=0, allow_unknown_chunksizes=allow_unknown_chunksizes)
@derived_from(np)
def hstack(tup, allow_unknown_chunksizes=False):
if isinstance(tup, Array):
raise NotImplementedError(
"``hstack`` expects a sequence of arrays as the first argument"
)
if all(x.ndim == 1 for x in tup):
return concatenate(
tup, axis=0, allow_unknown_chunksizes=allow_unknown_chunksizes
)
else:
return concatenate(
tup, axis=1, allow_unknown_chunksizes=allow_unknown_chunksizes
)
@derived_from(np)
def dstack(tup, allow_unknown_chunksizes=False):
if isinstance(tup, Array):
raise NotImplementedError(
"``dstack`` expects a sequence of arrays as the first argument"
)
tup = tuple(atleast_3d(x) for x in tup)
return concatenate(tup, axis=2, allow_unknown_chunksizes=allow_unknown_chunksizes)
@derived_from(np)
def swapaxes(a, axis1, axis2):
if axis1 == axis2:
return a
if axis1 < 0:
axis1 = axis1 + a.ndim
if axis2 < 0:
axis2 = axis2 + a.ndim
ind = list(range(a.ndim))
out = list(ind)
out[axis1], out[axis2] = axis2, axis1
return blockwise(np.swapaxes, out, a, ind, axis1=axis1, axis2=axis2, dtype=a.dtype)
@derived_from(np)
def transpose(a, axes=None):
if axes:
if len(axes) != a.ndim:
raise ValueError("axes don't match array")
axes = tuple(d + a.ndim if d < 0 else d for d in axes)
else:
axes = tuple(range(a.ndim))[::-1]
return blockwise(
np.transpose, axes, a, tuple(range(a.ndim)), dtype=a.dtype, axes=axes
)
def flip(m, axis=None):
m = asanyarray(m)
sl = m.ndim * [slice(None)]
if axis is None:
axis = range(m.ndim)
if not isinstance(axis, Iterable):
axis = (axis,)
try:
for ax in axis:
sl[ax] = slice(None, None, -1)
except IndexError as e:
raise ValueError(
f"`axis` of {str(axis)} invalid for {str(m.ndim)}-D array"
) from e
sl = tuple(sl)
return m[sl]
@derived_from(np)
def flipud(m):
return flip(m, 0)
@derived_from(np)
def fliplr(m):
return flip(m, 1)
@derived_from(np)
def rot90(m, k=1, axes=(0, 1)):
axes = tuple(axes)
if len(axes) != 2:
raise ValueError("len(axes) must be 2.")
m = asanyarray(m)
if axes[0] == axes[1] or np.absolute(axes[0] - axes[1]) == m.ndim:
raise ValueError("Axes must be different.")
if axes[0] >= m.ndim or axes[0] < -m.ndim or axes[1] >= m.ndim or axes[1] < -m.ndim:
raise ValueError(f"Axes={axes} out of range for array of ndim={m.ndim}.")
k %= 4
if k == 0:
return m[:]
if k == 2:
return flip(flip(m, axes[0]), axes[1])
axes_list = list(range(0, m.ndim))
(axes_list[axes[0]], axes_list[axes[1]]) = (axes_list[axes[1]], axes_list[axes[0]])
if k == 1:
return transpose(flip(m, axes[1]), axes_list)
else:
# k == 3
return flip(transpose(m, axes_list), axes[1])
def _tensordot(a, b, axes, is_sparse):
x = max([a, b], key=lambda x: x.__array_priority__)
tensordot = tensordot_lookup.dispatch(type(x))
x = tensordot(a, b, axes=axes)
if is_sparse and len(axes[0]) == 1:
return x
else:
ind = [slice(None, None)] * x.ndim
for a in sorted(axes[0]):
ind.insert(a, None)
x = x[tuple(ind)]
return x
def _tensordot_is_sparse(x):
is_sparse = "sparse" in str(type(x._meta))
if is_sparse:
# exclude pydata sparse arrays, no workaround required for these in tensordot
is_sparse = "sparse._coo.core.COO" not in str(type(x._meta))
return is_sparse
@derived_from(np)
def tensordot(lhs, rhs, axes=2):
if not isinstance(lhs, Array):
lhs = from_array(lhs)
if not isinstance(rhs, Array):
rhs = from_array(rhs)
if isinstance(axes, Iterable):
left_axes, right_axes = axes
else:
left_axes = tuple(range(lhs.ndim - axes, lhs.ndim))
right_axes = tuple(range(0, axes))
if isinstance(left_axes, Integral):
left_axes = (left_axes,)
if isinstance(right_axes, Integral):
right_axes = (right_axes,)
if isinstance(left_axes, list):
left_axes = tuple(left_axes)
if isinstance(right_axes, list):
right_axes = tuple(right_axes)
is_sparse = _tensordot_is_sparse(lhs) or _tensordot_is_sparse(rhs)
if is_sparse and len(left_axes) == 1:
concatenate = True
else:
concatenate = False
dt = np.promote_types(lhs.dtype, rhs.dtype)
left_index = list(range(lhs.ndim))
right_index = list(range(lhs.ndim, lhs.ndim + rhs.ndim))
out_index = left_index + right_index
adjust_chunks = {}
for l, r in zip(left_axes, right_axes):
out_index.remove(right_index[r])
right_index[r] = left_index[l]
if concatenate:
out_index.remove(left_index[l])
else:
adjust_chunks[left_index[l]] = lambda c: 1
intermediate = blockwise(
_tensordot,
out_index,
lhs,
left_index,
rhs,
right_index,
dtype=dt,
concatenate=concatenate,
adjust_chunks=adjust_chunks,
axes=(left_axes, right_axes),
is_sparse=is_sparse,
)
if concatenate:
return intermediate
else:
return intermediate.sum(axis=left_axes)
@derived_from(np)
def dot(a, b):
return tensordot(a, b, axes=((a.ndim - 1,), (b.ndim - 2,)))
@derived_from(np)
def vdot(a, b):
return dot(a.conj().ravel(), b.ravel())
def _chunk_sum(a, axis=None, dtype=None, keepdims=None):
# Caution: this is not your conventional array-sum: due
# to the special nature of the preceding blockwise con-
# traction, each chunk is expected to have exactly the
# same shape, with a size of 1 for the dimension given
# by `axis` (the reduction axis). This makes mere ele-
# ment-wise addition of the arrays possible. Besides,
# the output can be merely squeezed to lose the `axis`-
# dimension when keepdims = False
if type(a) is list:
out = reduce(partial(np.add, dtype=dtype), a)
else:
out = a
if keepdims:
return out
else:
return out.squeeze(axis[0])
def _sum_wo_cat(a, axis=None, dtype=None):
if dtype is None:
dtype = getattr(np.zeros(1, dtype=a.dtype).sum(), "dtype", object)
if a.shape[axis] == 1:
return a.squeeze(axis)
return reduction(
a, _chunk_sum, _chunk_sum, axis=axis, dtype=dtype, concatenate=False
)
def _matmul(a, b):
xp = np
if is_cupy_type(a):
# This branch appears to be unnecessary since cupy
# version 9.0. See the following link:
# https://github.com/dask/dask/pull/8423#discussion_r768291271
# But it remains here for backward-compatibility.
# Consider removing it in a future version of dask.
import cupy
xp = cupy
chunk = xp.matmul(a, b)
# Since we have performed the contraction via xp.matmul
# but blockwise expects all dimensions back (including
# the contraction-axis in the 2nd-to-last position of
# the output), we must then put it back in the expected
# the position ourselves:
return chunk[..., xp.newaxis, :]
@derived_from(np)
def matmul(a, b):
a = asanyarray(a)
b = asanyarray(b)
if a.ndim == 0 or b.ndim == 0:
raise ValueError("`matmul` does not support scalars.")
a_is_1d = False
if a.ndim == 1:
a_is_1d = True
a = a[np.newaxis, :]
b_is_1d = False
if b.ndim == 1:
b_is_1d = True
b = b[:, np.newaxis]
if a.ndim < b.ndim:
a = a[(b.ndim - a.ndim) * (np.newaxis,)]
elif a.ndim > b.ndim:
b = b[(a.ndim - b.ndim) * (np.newaxis,)]
# out_ind includes all dimensions to prevent contraction
# in the blockwise below. We set the last two dimensions
# of the output to the contraction axis and the 2nd
# (last) dimension of b in that order
out_ind = tuple(range(a.ndim + 1))
# lhs_ind includes `a`/LHS dimensions
lhs_ind = tuple(range(a.ndim))
# on `b`/RHS everything above 2nd dimension, is the same
# as `a`, -2 dimension is "contracted" with the last dimension
# of `a`, last dimension of `b` is `b` specific
rhs_ind = tuple(range(a.ndim - 2)) + (lhs_ind[-1], a.ndim)
out = blockwise(
_matmul,
out_ind,
a,
lhs_ind,
b,
rhs_ind,
adjust_chunks={lhs_ind[-1]: 1},
dtype=result_type(a, b),
concatenate=False,
)
# Because contraction + concatenate in blockwise leads to high
# memory footprints, we want to avoid them. Instead we will perform
# blockwise (without contraction) followed by reduction. More about
# this issue: https://github.com/dask/dask/issues/6874
# We will also perform the reduction without concatenation
out = _sum_wo_cat(out, axis=-2)
if a_is_1d:
out = out.squeeze(-2)
if b_is_1d:
out = out.squeeze(-1)
return out
@derived_from(np)
def outer(a, b):
a = a.flatten()
b = b.flatten()
dtype = np.outer(a.dtype.type(), b.dtype.type()).dtype
return blockwise(np.outer, "ij", a, "i", b, "j", dtype=dtype)
def _inner_apply_along_axis(arr, func1d, func1d_axis, func1d_args, func1d_kwargs):
return np.apply_along_axis(func1d, func1d_axis, arr, *func1d_args, **func1d_kwargs)
@derived_from(np)
def apply_along_axis(func1d, axis, arr, *args, dtype=None, shape=None, **kwargs):
arr = asarray(arr)
# Verify that axis is valid and throw an error otherwise
axis = len(arr.shape[:axis])
# If necessary, infer dtype and shape of the output of func1d by calling it on test data.
if shape is None or dtype is None:
test_data = np.ones((1,), dtype=arr.dtype)
test_result = np.array(func1d(test_data, *args, **kwargs))
if shape is None:
shape = test_result.shape
if dtype is None:
dtype = test_result.dtype
# Rechunk so that func1d is applied over the full axis.
arr = arr.rechunk(
arr.chunks[:axis] + (arr.shape[axis : axis + 1],) + arr.chunks[axis + 1 :]
)
# Map func1d over the data to get the result
# Adds other axes as needed.
result = arr.map_blocks(
_inner_apply_along_axis,
name=funcname(func1d) + "-along-axis",
dtype=dtype,
chunks=(arr.chunks[:axis] + shape + arr.chunks[axis + 1 :]),
drop_axis=axis,
new_axis=list(range(axis, axis + len(shape), 1)),
func1d=func1d,
func1d_axis=axis,
func1d_args=args,
func1d_kwargs=kwargs,
)
return result
@derived_from(np)
def apply_over_axes(func, a, axes):
# Validate arguments
a = asarray(a)
try:
axes = tuple(axes)
except TypeError:
axes = (axes,)
sl = a.ndim * (slice(None),)
# Compute using `apply_along_axis`.
result = a
for i in axes:
result = apply_along_axis(func, i, result, 0)
# Restore original dimensionality or error.
if result.ndim == (a.ndim - 1):
result = result[sl[:i] + (None,)]
elif result.ndim != a.ndim:
raise ValueError(
"func must either preserve dimensionality of the input"
" or reduce it by one."
)
return result
@derived_from(np)
def ptp(a, axis=None):
return a.max(axis=axis) - a.min(axis=axis)
@derived_from(np)
def diff(a, n=1, axis=-1, prepend=None, append=None):
a = asarray(a)
n = int(n)
axis = int(axis)
if n == 0:
return a
if n < 0:
raise ValueError("order must be non-negative but got %d" % n)
combined = []
if prepend is not None:
prepend = asarray_safe(prepend, like=meta_from_array(a))
if prepend.ndim == 0:
shape = list(a.shape)
shape[axis] = 1
prepend = broadcast_to(prepend, tuple(shape))
combined.append(prepend)
combined.append(a)
if append is not None:
append = asarray_safe(append, like=meta_from_array(a))
if append.ndim == 0:
shape = list(a.shape)
shape[axis] = 1
append = np.broadcast_to(append, tuple(shape))
combined.append(append)
if len(combined) > 1:
a = concatenate(combined, axis)
sl_1 = a.ndim * [slice(None)]
sl_2 = a.ndim * [slice(None)]
sl_1[axis] = slice(1, None)
sl_2[axis] = slice(None, -1)
sl_1 = tuple(sl_1)
sl_2 = tuple(sl_2)
r = a
for i in range(n):
r = r[sl_1] - r[sl_2]
return r
@derived_from(np)
def ediff1d(ary, to_end=None, to_begin=None):
ary = asarray(ary)
aryf = ary.flatten()
r = aryf[1:] - aryf[:-1]
r = [r]
if to_begin is not None:
r = [asarray(to_begin).flatten()] + r
if to_end is not None:
r = r + [asarray(to_end).flatten()]
r = concatenate(r)
return r
def _gradient_kernel(x, block_id, coord, axis, array_locs, grad_kwargs):
block_loc = block_id[axis]
if array_locs is not None:
coord = coord[array_locs[0][block_loc] : array_locs[1][block_loc]]
grad = np.gradient(x, coord, axis=axis, **grad_kwargs)
return grad
@derived_from(np)
def gradient(f, *varargs, axis=None, **kwargs):
f = asarray(f)
kwargs["edge_order"] = math.ceil(kwargs.get("edge_order", 1))
if kwargs["edge_order"] > 2:
raise ValueError("edge_order must be less than or equal to 2.")
drop_result_list = False
if axis is None:
axis = tuple(range(f.ndim))
elif isinstance(axis, Integral):
drop_result_list = True
axis = (axis,)
axis = validate_axis(axis, f.ndim)
if len(axis) != len(set(axis)):
raise ValueError("duplicate axes not allowed")
axis = tuple(ax % f.ndim for ax in axis)
if varargs == ():
varargs = (1,)
if len(varargs) == 1:
varargs = len(axis) * varargs
if len(varargs) != len(axis):
raise TypeError(
"Spacing must either be a single scalar, or a scalar / 1d-array per axis"
)
if issubclass(f.dtype.type, (np.bool8, Integral)):
f = f.astype(float)
elif issubclass(f.dtype.type, Real) and f.dtype.itemsize < 4:
f = f.astype(float)
results = []
for i, ax in enumerate(axis):
for c in f.chunks[ax]:
if np.min(c) < kwargs["edge_order"] + 1:
raise ValueError(
"Chunk size must be larger than edge_order + 1. "
"Minimum chunk for axis {} is {}. Rechunk to "
"proceed.".format(ax, np.min(c))
)
if np.isscalar(varargs[i]):
array_locs = None
else:
if isinstance(varargs[i], Array):
raise NotImplementedError("dask array coordinated is not supported.")
# coordinate position for each block taking overlap into account
chunk = np.array(f.chunks[ax])
array_loc_stop = np.cumsum(chunk) + 1
array_loc_start = array_loc_stop - chunk - 2
array_loc_stop[-1] -= 1
array_loc_start[0] = 0
array_locs = (array_loc_start, array_loc_stop)
results.append(
f.map_overlap(
_gradient_kernel,
dtype=f.dtype,
depth={j: 1 if j == ax else 0 for j in range(f.ndim)},
boundary="none",
coord=varargs[i],
axis=ax,
array_locs=array_locs,
grad_kwargs=kwargs,
)
)
if drop_result_list:
results = results[0]
return results
def _bincount_agg(bincounts, dtype, **kwargs):
if not isinstance(bincounts, list):
return bincounts
n = max(map(len, bincounts))
out = np.zeros_like(bincounts[0], shape=n, dtype=dtype)
for b in bincounts:
out[: len(b)] += b
return out
@derived_from(np)
def bincount(x, weights=None, minlength=0, split_every=None):
if x.ndim != 1:
raise ValueError("Input array must be one dimensional. Try using x.ravel()")
if weights is not None:
if weights.chunks != x.chunks:
raise ValueError("Chunks of input array x and weights must match.")
token = tokenize(x, weights, minlength)
args = [x, "i"]
if weights is not None:
meta = array_safe(np.bincount([1], weights=[1]), like=meta_from_array(x))
args.extend([weights, "i"])
else:
meta = array_safe(np.bincount([]), like=meta_from_array(x))
if minlength == 0:
output_size = (np.nan,)
else:
output_size = (minlength,)
chunked_counts = blockwise(
partial(np.bincount, minlength=minlength), "i", *args, token=token, meta=meta
)
chunked_counts._chunks = (
output_size * len(chunked_counts.chunks[0]),
*chunked_counts.chunks[1:],
)
from dask.array.reductions import _tree_reduce
output = _tree_reduce(
chunked_counts,
aggregate=partial(_bincount_agg, dtype=meta.dtype),
axis=(0,),
keepdims=True,
dtype=meta.dtype,
split_every=split_every,
concatenate=False,
)
output._chunks = (output_size, *chunked_counts.chunks[1:])
output._meta = meta
return output
@derived_from(np)
def digitize(a, bins, right=False):
bins = asarray_safe(bins, like=meta_from_array(a))
dtype = np.digitize(asarray_safe([0], like=bins), bins, right=False).dtype
return a.map_blocks(np.digitize, dtype=dtype, bins=bins, right=right)
def _searchsorted_block(x, y, side):
res = np.searchsorted(x, y, side=side)
# 0 is only correct for the first block of a, but blockwise doesn't have a way
res[res == 0] = -1
return res[np.newaxis, :]
@derived_from(np)
def searchsorted(a, v, side="left", sorter=None):
if a.ndim != 1:
raise ValueError("Input array a must be one dimensional")
if sorter is not None:
raise NotImplementedError(
"da.searchsorted with a sorter argument is not supported"
)
meta = np.searchsorted(a._meta, v._meta)
out = blockwise(
_searchsorted_block,
list(range(v.ndim + 1)),
a,
[0],
v,
list(range(1, v.ndim + 1)),
side,
None,
meta=meta,
adjust_chunks={0: 1},
)
a_chunk_sizes = array_safe((0, *a.chunks[0]), like=meta_from_array(a))
a_chunk_offsets = np.cumsum(a_chunk_sizes)[:-1]
a_chunk_offsets = a_chunk_offsets[(Ellipsis,) + v.ndim * (np.newaxis,)]
a_offsets = asarray(a_chunk_offsets, chunks=1)
out = where(out < 0, out, out + a_offsets)
out = out.max(axis=0)
out[out == -1] = 0
return out
def _linspace_from_delayed(start, stop, num=50):
linspace_name = "linspace-" + tokenize(start, stop, num)
(start_ref, stop_ref, num_ref), deps = unpack_collections([start, stop, num])
if len(deps) == 0:
return np.linspace(start, stop, num=num)
linspace_dsk = {(linspace_name, 0): (np.linspace, start_ref, stop_ref, num_ref)}
linspace_graph = HighLevelGraph.from_collections(
linspace_name, linspace_dsk, dependencies=deps
)
chunks = ((np.nan,),) if is_dask_collection(num) else ((num,),)
return Array(linspace_graph, linspace_name, chunks, dtype=float)
def _block_hist(x, bins, range=None, weights=None):
return np.histogram(x, bins, range=range, weights=weights)[0][np.newaxis]
def histogram(a, bins=None, range=None, normed=False, weights=None, density=None):
if isinstance(bins, Array):
scalar_bins = bins.ndim == 0
# ^ `np.ndim` is not implemented by Dask array.
elif isinstance(bins, Delayed):
scalar_bins = bins._length is None or bins._length == 1
else:
scalar_bins = np.ndim(bins) == 0
if bins is None or (scalar_bins and range is None):
raise ValueError(
"dask.array.histogram requires either specifying "
"bins as an iterable or specifying both a range and "
"the number of bins"
)
if weights is not None and weights.chunks != a.chunks:
raise ValueError("Input array and weights must have the same chunked structure")
if normed is not False:
raise ValueError(
"The normed= keyword argument has been deprecated. "
"Please use density instead. "
"See the numpy.histogram docstring for more information."
)
if density and scalar_bins and isinstance(bins, (Array, Delayed)):
raise NotImplementedError(
"When `density` is True, `bins` cannot be a scalar Dask object. "
"It must be a concrete number or a (possibly-delayed) array/sequence of bin edges."
)
for argname, val in [("bins", bins), ("range", range), ("weights", weights)]:
if not isinstance(bins, (Array, Delayed)) and is_dask_collection(bins):
raise TypeError(
"Dask types besides Array and Delayed are not supported "
"for `histogram`. For argument `{}`, got: {!r}".format(argname, val)
)
if range is not None:
try:
if len(range) != 2:
raise ValueError(
f"range must be a sequence or array of length 2, but got {len(range)} items"
)
if isinstance(range, (Array, np.ndarray)) and range.shape != (2,):
raise ValueError(
f"range must be a 1-dimensional array of two items, but got an array of shape {range.shape}"
)
except TypeError:
raise TypeError(
f"Expected a sequence or array for range, not {range}"
) from None
token = tokenize(a, bins, range, weights, density)
name = "histogram-sum-" + token
if scalar_bins:
bins = _linspace_from_delayed(range[0], range[1], bins + 1)
# ^ NOTE `range[1]` is safe because of the above check, and the initial check
# that range must not be None if `scalar_bins`
else:
if not isinstance(bins, (Array, np.ndarray)):
bins = asarray(bins)
if bins.ndim != 1:
raise ValueError(
f"bins must be a 1-dimensional array or sequence, got shape {bins.shape}"
)
(bins_ref, range_ref), deps = unpack_collections([bins, range])
# Map the histogram to all bins, forming a 2D array of histograms, stacked for each chunk
if weights is None:
dsk = {
(name, i, 0): (_block_hist, k, bins_ref, range_ref)
for i, k in enumerate(flatten(a.__dask_keys__()))
}
dtype = np.histogram([])[0].dtype
else:
a_keys = flatten(a.__dask_keys__())
w_keys = flatten(weights.__dask_keys__())
dsk = {
(name, i, 0): (_block_hist, k, bins_ref, range_ref, w)
for i, (k, w) in enumerate(zip(a_keys, w_keys))
}
dtype = weights.dtype
deps = (a,) + deps
if weights is not None:
deps += (weights,)
graph = HighLevelGraph.from_collections(name, dsk, dependencies=deps)
# Turn graph into a 2D Array of shape (nchunks, nbins)
nchunks = len(list(flatten(a.__dask_keys__())))
nbins = bins.size - 1 # since `bins` is 1D
chunks = ((1,) * nchunks, (nbins,))
mapped = Array(graph, name, chunks, dtype=dtype)
# Sum over chunks to get the final histogram
n = mapped.sum(axis=0)
# We need to replicate normed and density options from numpy
if density is not None:
if density:
db = asarray(np.diff(bins).astype(float), chunks=n.chunks)
return n / db / n.sum(), bins
else:
return n, bins
else:
return n, bins
def histogram2d(x, y, bins=10, range=None, normed=None, weights=None, density=None):
counts, edges = histogramdd(
(x, y),
bins=bins,
range=range,
normed=normed,
weights=weights,
density=density,
)
return counts, edges[0], edges[1]
def _block_histogramdd_rect(sample, bins, range, weights):
return np.histogramdd(sample, bins, range=range, weights=weights)[0:1]
def _block_histogramdd_multiarg(*args):
bins, range, weights = args[-3:]
sample = args[:-3]
return np.histogramdd(sample, bins=bins, range=range, weights=weights)[0:1]
def histogramdd(sample, bins, range=None, normed=None, weights=None, density=None):
# logic used in numpy.histogramdd to handle normed/density.
if normed is None:
if density is None:
density = False
elif density is None:
# an explicit normed argument was passed, alias it to the new name
density = normed
else:
raise TypeError("Cannot specify both 'normed' and 'density'")
# check if any dask collections (dc) were passed to bins= or
# range= these are unsupported.
dc_bins = is_dask_collection(bins)
if isinstance(bins, (list, tuple)):
dc_bins = dc_bins or any([is_dask_collection(b) for b in bins])
dc_range = (
any([is_dask_collection(r) for r in range]) if range is not None else False
)
if dc_bins or dc_range:
raise NotImplementedError(
"Passing dask collections to bins=... or range=... is not supported."
)
# generate token and name for task
token = tokenize(sample, bins, range, weights, density)
name = f"histogramdd-sum-{token}"
# N == total number of samples
# D == total number of dimensions
if hasattr(sample, "shape"):
if len(sample.shape) != 2:
raise ValueError("Single array input to histogramdd should be columnar")
else:
_, D = sample.shape
n_chunks = sample.numblocks[0]
rectangular_sample = True
# Require data to be chunked along the first axis only.
if sample.shape[1:] != sample.chunksize[1:]:
raise ValueError("Input array can only be chunked along the 0th axis.")
elif isinstance(sample, (tuple, list)):
rectangular_sample = False
D = len(sample)
n_chunks = sample[0].numblocks[0]
for i in _range(1, D):
if sample[i].chunks != sample[0].chunks:
raise ValueError("All coordinate arrays must be chunked identically.")
else:
raise ValueError(
"Incompatible sample. Must be a 2D array or a sequence of 1D arrays."
)
# Require only Array or Delayed objects for bins, range, and weights.
for argname, val in [("bins", bins), ("range", range), ("weights", weights)]:
if not isinstance(bins, (Array, Delayed)) and is_dask_collection(bins):
raise TypeError(
"Dask types besides Array and Delayed are not supported "
"for `histogramdd`. For argument `{}`, got: {!r}".format(argname, val)
)
# Require that the chunking of the sample and weights are compatible.
if weights is not None:
if rectangular_sample and weights.chunks[0] != sample.chunks[0]:
raise ValueError(
"Input array and weights must have the same shape "
"and chunk structure along the first dimension."
)
elif not rectangular_sample and weights.numblocks[0] != n_chunks:
raise ValueError(
"Input arrays and weights must have the same shape "
"and chunk structure."
)
# if bins is a list, tuple, then make sure the length is the same
# as the number dimensions.
if isinstance(bins, (list, tuple)):
if len(bins) != D:
raise ValueError(
"The dimension of bins must be equal to the dimension of the sample."
)
# if range is defined, check that it's the right length and also a
if range is not None:
if len(range) != D:
raise ValueError(
"range argument requires one entry, a min max pair, per dimension."
)
if not all(len(r) == 2 for r in range):
raise ValueError("range argument should be a sequence of pairs")
if isinstance(bins, int):
bins = (bins,) * D
if all(isinstance(b, int) for b in bins) and all(len(r) == 2 for r in range):
edges = [np.linspace(r[0], r[1], b + 1) for b, r in zip(bins, range)]
else:
edges = [np.asarray(b) for b in bins]
if rectangular_sample:
deps = (sample,)
else:
deps = tuple(sample)
if weights is not None:
w_keys = flatten(weights.__dask_keys__())
deps += (weights,)
dtype = weights.dtype
else:
w_keys = (None,) * n_chunks
dtype = np.histogramdd([])[0].dtype
column_zeros = tuple(0 for _ in _range(D))
if rectangular_sample:
sample_keys = flatten(sample.__dask_keys__())
dsk = {
(name, i, *column_zeros): (_block_histogramdd_rect, k, bins, range, w)
for i, (k, w) in enumerate(zip(sample_keys, w_keys))
}
else:
sample_keys = [
list(flatten(sample[i].__dask_keys__())) for i in _range(len(sample))
]
fused_on_chunk_keys = [
tuple(sample_keys[j][i] for j in _range(D)) for i in _range(n_chunks)
]
dsk = {
(name, i, *column_zeros): (
_block_histogramdd_multiarg,
*(*k, bins, range, w),
)
for i, (k, w) in enumerate(zip(fused_on_chunk_keys, w_keys))
}
graph = HighLevelGraph.from_collections(name, dsk, dependencies=deps)
all_nbins = tuple((b.size - 1,) for b in edges)
stacked_chunks = ((1,) * n_chunks, *all_nbins)
mapped = Array(graph, name, stacked_chunks, dtype=dtype)
n = mapped.sum(axis=0)
if density:
width_divider = np.ones(n.shape)
for i in _range(D):
shape = np.ones(D, int)
shape[i] = width_divider.shape[i]
width_divider *= np.diff(edges[i]).reshape(shape)
width_divider = asarray(width_divider, chunks=n.chunks)
return n / width_divider / n.sum(), edges
return n, [asarray(entry) for entry in edges]
@derived_from(np)
def cov(m, y=None, rowvar=1, bias=0, ddof=None):
if ddof is not None and ddof != int(ddof):
raise ValueError("ddof must be integer")
m = asarray(m)
if y is None:
dtype = np.result_type(m, np.float64)
else:
y = asarray(y)
dtype = np.result_type(m, y, np.float64)
X = array(m, ndmin=2, dtype=dtype)
if X.shape[0] == 1:
rowvar = 1
if rowvar:
N = X.shape[1]
axis = 0
else:
N = X.shape[0]
axis = 1
if ddof is None:
if bias == 0:
ddof = 1
else:
ddof = 0
fact = float(N - ddof)
if fact <= 0:
warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning)
fact = 0.0
if y is not None:
y = array(y, ndmin=2, dtype=dtype)
X = concatenate((X, y), axis)
X = X - X.mean(axis=1 - axis, keepdims=True)
if not rowvar:
return (dot(X.T, X.conj()) / fact).squeeze()
else:
return (dot(X, X.T.conj()) / fact).squeeze()
@derived_from(np)
def corrcoef(x, y=None, rowvar=1):
c = cov(x, y, rowvar)
if c.shape == ():
return c / c
d = diag(c)
d = d.reshape((d.shape[0], 1))
sqr_d = sqrt(d)
return (c / sqr_d) / sqr_d.T
@implements(np.round, np.round_)
@derived_from(np)
def round(a, decimals=0):
return a.map_blocks(np.round, decimals=decimals, dtype=a.dtype)
@implements(np.ndim)
@derived_from(np)
def ndim(a):
return a.ndim
@implements(np.iscomplexobj)
@derived_from(np)
def iscomplexobj(x):
return issubclass(x.dtype.type, np.complexfloating)
def _unique_internal(ar, indices, counts, return_inverse=False):
return_index = indices is not None
return_counts = counts is not None
u = np.unique(ar)
dt = [("values", u.dtype)]
if return_index:
dt.append(("indices", np.intp))
if return_inverse:
dt.append(("inverse", np.intp))
if return_counts:
dt.append(("counts", np.intp))
r = np.empty(u.shape, dtype=dt)
r["values"] = u
if return_inverse:
r["inverse"] = np.arange(len(r), dtype=np.intp)
if return_index or return_counts:
for i, v in enumerate(r["values"]):
m = ar == v
if return_index:
indices[m].min(keepdims=True, out=r["indices"][i : i + 1])
if return_counts:
counts[m].sum(keepdims=True, out=r["counts"][i : i + 1])
return r
def unique_no_structured_arr(
ar, return_index=False, return_inverse=False, return_counts=False
):
# can only compute values at the moment.
if (
return_index is not False
or return_inverse is not False
or return_counts is not False
):
raise ValueError(
"dask.array.unique does not support `return_index`, `return_inverse` "
"or `return_counts` with array types that don't support structured "
"arrays."
)
ar = ar.ravel()
args = [ar, "i"]
meta = meta_from_array(ar)
out = blockwise(np.unique, "i", *args, meta=meta)
out._chunks = tuple((np.nan,) * len(c) for c in out.chunks)
out_parts = [out]
name = "unique-aggregate-" + out.name
dsk = {
(name, 0): (
(np.unique,)
+ tuple(
(np.concatenate, o.__dask_keys__())
if hasattr(o, "__dask_keys__")
else o
for o in out_parts
)
)
}
dependencies = [o for o in out_parts if hasattr(o, "__dask_keys__")]
graph = HighLevelGraph.from_collections(name, dsk, dependencies=dependencies)
chunks = ((np.nan,),)
out = Array(graph, name, chunks, meta=meta)
result = [out]
if len(result) == 1:
result = result[0]
else:
result = tuple(result)
return result
@derived_from(np)
def unique(ar, return_index=False, return_inverse=False, return_counts=False):
# `unique_no_structured_arr` implementation, otherwise (e.g., NumPy) just
# continue as normal.
try:
meta = meta_from_array(ar)
np.empty_like(meta, dtype=[("a", int), ("b", float)])
except TypeError:
return unique_no_structured_arr(
ar,
return_index=return_index,
return_inverse=return_inverse,
return_counts=return_counts,
)
ar = ar.ravel()
# Run unique on each chunk and collect results in a Dask Array of
# unknown size.
args = [ar, "i"]
out_dtype = [("values", ar.dtype)]
if return_index:
args.extend([arange(ar.shape[0], dtype=np.intp, chunks=ar.chunks[0]), "i"])
out_dtype.append(("indices", np.intp))
else:
args.extend([None, None])
if return_counts:
args.extend([ones((ar.shape[0],), dtype=np.intp, chunks=ar.chunks[0]), "i"])
out_dtype.append(("counts", np.intp))
else:
args.extend([None, None])
out = blockwise(_unique_internal, "i", *args, dtype=out_dtype, return_inverse=False)
out._chunks = tuple((np.nan,) * len(c) for c in out.chunks)
# Take the results from the unique chunks and do the following.
#
# 1. Collect all results as arguments.
# 2. Concatenate each result into one big array.
# 3. Pass all results as arguments to the internal unique again.
#
# TODO: This should be replaced with a tree reduction using this strategy.
# xref: https://github.com/dask/dask/issues/2851
out_parts = [out["values"]]
if return_index:
out_parts.append(out["indices"])
else:
out_parts.append(None)
if return_counts:
out_parts.append(out["counts"])
else:
out_parts.append(None)
name = "unique-aggregate-" + out.name
dsk = {
(name, 0): (
(_unique_internal,)
+ tuple(
(np.concatenate, o.__dask_keys__())
if hasattr(o, "__dask_keys__")
else o
for o in out_parts
)
+ (return_inverse,)
)
}
out_dtype = [("values", ar.dtype)]
if return_index:
out_dtype.append(("indices", np.intp))
if return_inverse:
out_dtype.append(("inverse", np.intp))
if return_counts:
out_dtype.append(("counts", np.intp))
dependencies = [o for o in out_parts if hasattr(o, "__dask_keys__")]
graph = HighLevelGraph.from_collections(name, dsk, dependencies=dependencies)
chunks = ((np.nan,),)
out = Array(graph, name, chunks, out_dtype)
# Split out all results to return to the user.
result = [out["values"]]
if return_index:
result.append(out["indices"])
if return_inverse:
# Using the returned unique values and arange of unknown length, find
# each value matching a unique value and replace it with its
# corresponding index or `0`. There should be only one entry for this
# index in axis `1` (the one of unknown length). Reduce axis `1`
# through summing to get an array with known dimensionality and the
# mapping of the original values.
mtches = (ar[:, None] == out["values"][None, :]).astype(np.intp)
result.append((mtches * out["inverse"]).sum(axis=1))
if return_counts:
result.append(out["counts"])
if len(result) == 1:
result = result[0]
else:
result = tuple(result)
return result
def _isin_kernel(element, test_elements, assume_unique=False):
values = np.in1d(element.ravel(), test_elements, assume_unique=assume_unique)
return values.reshape(element.shape + (1,) * test_elements.ndim)
@safe_wraps(getattr(np, "isin", None))
def isin(element, test_elements, assume_unique=False, invert=False):
element = asarray(element)
test_elements = asarray(test_elements)
element_axes = tuple(range(element.ndim))
test_axes = tuple(i + element.ndim for i in range(test_elements.ndim))
mapped = blockwise(
_isin_kernel,
element_axes + test_axes,
element,
element_axes,
test_elements,
test_axes,
adjust_chunks={axis: lambda _: 1 for axis in test_axes},
dtype=bool,
assume_unique=assume_unique,
)
result = mapped.any(axis=test_axes)
if invert:
result = ~result
return result
@derived_from(np)
def roll(array, shift, axis=None):
result = array
if axis is None:
result = ravel(result)
if not isinstance(shift, Integral):
raise TypeError(
"Expect `shift` to be an instance of Integral when `axis` is None."
)
shift = (shift,)
axis = (0,)
else:
try:
len(shift)
except TypeError:
shift = (shift,)
try:
len(axis)
except TypeError:
axis = (axis,)
if len(shift) != len(axis):
raise ValueError("Must have the same number of shifts as axes.")
for i, s in zip(axis, shift):
s = -s
s %= result.shape[i]
sl1 = result.ndim * [slice(None)]
sl2 = result.ndim * [slice(None)]
sl1[i] = slice(s, None)
sl2[i] = slice(None, s)
sl1 = tuple(sl1)
sl2 = tuple(sl2)
result = concatenate([result[sl1], result[sl2]], axis=i)
result = result.reshape(array.shape)
# Ensure that the output is always a new array object
result = result.copy() if result is array else result
return result
@derived_from(np)
def shape(array):
return array.shape
@derived_from(np)
def union1d(ar1, ar2):
return unique(concatenate((ar1.ravel(), ar2.ravel())))
@derived_from(np)
def ravel(array_like):
return asanyarray(array_like).reshape((-1,))
@derived_from(np)
def expand_dims(a, axis):
if type(axis) not in (tuple, list):
axis = (axis,)
out_ndim = len(axis) + a.ndim
axis = validate_axis(axis, out_ndim)
shape_it = iter(a.shape)
shape = [1 if ax in axis else next(shape_it) for ax in range(out_ndim)]
return a.reshape(shape)
@derived_from(np)
def squeeze(a, axis=None):
if axis is None:
axis = tuple(i for i, d in enumerate(a.shape) if d == 1)
elif not isinstance(axis, tuple):
axis = (axis,)
if any(a.shape[i] != 1 for i in axis):
raise ValueError("cannot squeeze axis with size other than one")
axis = validate_axis(axis, a.ndim)
sl = tuple(0 if i in axis else slice(None) for i, s in enumerate(a.shape))
a = a[sl]
return a
@derived_from(np)
def compress(condition, a, axis=None):
if not is_arraylike(condition):
# Allow `condition` to be anything array-like, otherwise ensure `condition`
# is a numpy array.
condition = np.asarray(condition)
condition = condition.astype(bool)
a = asarray(a)
if condition.ndim != 1:
raise ValueError("Condition must be one dimensional")
if axis is None:
a = a.ravel()
axis = 0
axis = validate_axis(axis, a.ndim)
# Treat `condition` as filled with `False` (if it is too short)
a = a[
tuple(
slice(None, len(condition)) if i == axis else slice(None)
for i in range(a.ndim)
)
]
# Use `condition` to select along 1 dimension
a = a[tuple(condition if i == axis else slice(None) for i in range(a.ndim))]
return a
@derived_from(np)
def extract(condition, arr):
condition = asarray(condition).astype(bool)
arr = asarray(arr)
return compress(condition.ravel(), arr.ravel())
@derived_from(np)
def take(a, indices, axis=0):
axis = validate_axis(axis, a.ndim)
if isinstance(a, np.ndarray) and isinstance(indices, Array):
return _take_dask_array_from_numpy(a, indices, axis)
else:
return a[(slice(None),) * axis + (indices,)]
def _take_dask_array_from_numpy(a, indices, axis):
assert isinstance(a, np.ndarray)
assert isinstance(indices, Array)
return indices.map_blocks(
lambda block: np.take(a, block, axis), chunks=indices.chunks, dtype=a.dtype
)
@derived_from(np)
def around(x, decimals=0):
return map_blocks(partial(np.around, decimals=decimals), x, dtype=x.dtype)
def _asarray_isnull(values):
import pandas as pd
return np.asarray(pd.isnull(values))
def isnull(values):
# eagerly raise ImportError, if pandas isn't available
import pandas as pd
return elemwise(_asarray_isnull, values, dtype="bool")
def notnull(values):
return ~isnull(values)
@derived_from(np)
def isclose(arr1, arr2, rtol=1e-5, atol=1e-8, equal_nan=False):
func = partial(np.isclose, rtol=rtol, atol=atol, equal_nan=equal_nan)
return elemwise(func, arr1, arr2, dtype="bool")
@derived_from(np)
def allclose(arr1, arr2, rtol=1e-5, atol=1e-8, equal_nan=False):
return isclose(arr1, arr2, rtol=rtol, atol=atol, equal_nan=equal_nan).all()
def variadic_choose(a, *choices):
return np.choose(a, choices)
@derived_from(np)
def choose(a, choices):
return elemwise(variadic_choose, a, *choices)
def _isnonzero_vec(v):
return bool(np.count_nonzero(v))
_isnonzero_vec = np.vectorize(_isnonzero_vec, otypes=[bool])
def isnonzero(a):
if a.dtype.kind in {"U", "S"}:
return a.map_blocks(_isnonzero_vec, dtype=bool)
try:
np.zeros(tuple(), dtype=a.dtype).astype(bool)
except ValueError:
return index_stack.map_blocks(
np.ravel_multi_index,
dtype=np.intp,
chunks=index_stack.chunks[1:],
drop_axis=0,
dims=dims,
mode=mode,
order=order,
)
def _int_piecewise(x, *condlist, **kwargs):
return np.piecewise(
x, list(condlist), kwargs["funclist"], *kwargs["func_args"], **kwargs["func_kw"]
)
@derived_from(np)
def piecewise(x, condlist, funclist, *args, **kw):
return map_blocks(
_int_piecewise,
x,
*condlist,
dtype=x.dtype,
name="piecewise",
funclist=funclist,
func_args=args,
func_kw=kw,
)
def _select(*args, **kwargs):
split_at = len(args) // 2
condlist = args[:split_at]
choicelist = args[split_at:]
return np.select(condlist, choicelist, **kwargs)
@derived_from(np)
def select(condlist, choicelist, default=0):
if len(condlist) != len(choicelist):
raise ValueError("list of cases must be same length as list of conditions")
if len(condlist) == 0:
raise ValueError("select with an empty condition list is not possible")
choicelist = [asarray(choice) for choice in choicelist]
try:
intermediate_dtype = result_type(*choicelist)
except TypeError as e:
msg = "Choicelist elements do not have a common dtype."
raise TypeError(msg) from e
blockwise_shape = tuple(range(choicelist[0].ndim))
condargs = [arg for elem in condlist for arg in (elem, blockwise_shape)]
choiceargs = [arg for elem in choicelist for arg in (elem, blockwise_shape)]
return blockwise(
_select,
blockwise_shape,
*condargs,
*choiceargs,
dtype=intermediate_dtype,
name="select",
default=default,
)
def _partition(total: int, divisor: int) -> tuple[tuple[int, ...], tuple[int, ...]]:
multiples = (divisor,) * (total // divisor)
remainder = (total % divisor,) if total % divisor else ()
return multiples, remainder
def aligned_coarsen_chunks(chunks: list[int], multiple: int) -> tuple[int, ...]:
overflow = np.array(chunks) % multiple
excess = overflow.sum()
new_chunks = np.array(chunks) - overflow
chunk_validity = new_chunks == chunks
valid_inds, invalid_inds = np.where(chunk_validity)[0], np.where(~chunk_validity)[0]
chunk_modification_order = [
*invalid_inds[np.argsort(new_chunks[invalid_inds])],
*valid_inds[np.argsort(new_chunks[valid_inds])],
]
partitioned_excess, remainder = _partition(excess, multiple)
for idx, extra in enumerate(partitioned_excess):
new_chunks[chunk_modification_order[idx]] += extra
new_chunks = np.array([*new_chunks, *remainder])
new_chunks = new_chunks[new_chunks > 0]
return tuple(new_chunks)
@wraps(chunk.coarsen)
def coarsen(reduction, x, axes, trim_excess=False, **kwargs):
if not trim_excess and not all(x.shape[i] % div == 0 for i, div in axes.items()):
msg = f"Coarsening factors {axes} do not align with array shape {x.shape}."
raise ValueError(msg)
if reduction.__module__.startswith("dask."):
reduction = getattr(np, reduction.__name__)
new_chunks = {}
for i, div in axes.items():
aligned = aligned_coarsen_chunks(x.chunks[i], div)
if aligned != x.chunks[i]:
new_chunks[i] = aligned
if new_chunks:
x = x.rechunk(new_chunks)
name = "coarsen-" + tokenize(reduction, x, axes, trim_excess)
dsk = {
(name,)
+ key[1:]: (apply, chunk.coarsen, [reduction, key, axes, trim_excess], kwargs)
for key in flatten(x.__dask_keys__())
}
chunks = tuple(
tuple(int(bd // axes.get(i, 1)) for bd in bds) for i, bds in enumerate(x.chunks)
)
meta = reduction(np.empty((1,) * x.ndim, dtype=x.dtype), **kwargs)
graph = HighLevelGraph.from_collections(name, dsk, dependencies=[x])
return Array(graph, name, chunks, meta=meta)
def split_at_breaks(array, breaks, axis=0):
padded_breaks = concat([[None], breaks, [None]])
slices = [slice(i, j) for i, j in sliding_window(2, padded_breaks)]
preslice = (slice(None),) * axis
split_array = [array[preslice + (s,)] for s in slices]
return split_array
@derived_from(np)
def insert(arr, obj, values, axis):
axis = validate_axis(axis, arr.ndim)
if isinstance(obj, slice):
obj = np.arange(*obj.indices(arr.shape[axis]))
obj = np.asarray(obj)
scalar_obj = obj.ndim == 0
if scalar_obj:
obj = np.atleast_1d(obj)
obj = np.where(obj < 0, obj + arr.shape[axis], obj)
if (np.diff(obj) < 0).any():
raise NotImplementedError(
"da.insert only implemented for monotonic ``obj`` argument"
)
split_arr = split_at_breaks(arr, np.unique(obj), axis)
if getattr(values, "ndim", 0) == 0:
name = "values-" + tokenize(values)
dtype = getattr(values, "dtype", type(values))
values = Array({(name,): values}, name, chunks=(), dtype=dtype)
values_shape = tuple(
len(obj) if axis == n else s for n, s in enumerate(arr.shape)
)
values = broadcast_to(values, values_shape)
elif scalar_obj:
values = values[(slice(None),) * axis + (None,)]
values_chunks = tuple(
values_bd if axis == n else arr_bd
for n, (arr_bd, values_bd) in enumerate(zip(arr.chunks, values.chunks))
)
values = values.rechunk(values_chunks)
counts = np.bincount(obj)[:-1]
values_breaks = np.cumsum(counts[counts > 0])
split_values = split_at_breaks(values, values_breaks, axis)
interleaved = list(interleave([split_arr, split_values]))
interleaved = [i for i in interleaved if i.nbytes]
return concatenate(interleaved, axis=axis)
@derived_from(np)
def delete(arr, obj, axis):
axis = validate_axis(axis, arr.ndim)
if isinstance(obj, slice):
tmp = np.arange(*obj.indices(arr.shape[axis]))
obj = tmp[::-1] if obj.step and obj.step < 0 else tmp
else:
obj = np.asarray(obj)
obj = np.where(obj < 0, obj + arr.shape[axis], obj)
obj = np.unique(obj)
target_arr = split_at_breaks(arr, obj, axis)
target_arr = [
arr[
tuple(slice(1, None) if axis == n else slice(None) for n in range(arr.ndim))
]
if i != 0
else arr
for i, arr in enumerate(target_arr)
]
return concatenate(target_arr, axis=axis)
@derived_from(np)
def append(arr, values, axis=None):
arr = asanyarray(arr)
if axis is None:
if arr.ndim != 1:
arr = arr.ravel()
values = ravel(asanyarray(values))
axis = arr.ndim - 1
return concatenate((arr, values), axis=axis)
def _average(a, axis=None, weights=None, returned=False, is_masked=False):
a = asanyarray(a)
if weights is None:
avg = a.mean(axis)
scl = avg.dtype.type(a.size / avg.size)
else:
wgt = asanyarray(weights)
if issubclass(a.dtype.type, (np.integer, np.bool_)):
result_dtype = result_type(a.dtype, wgt.dtype, "f8")
else:
result_dtype = result_type(a.dtype, wgt.dtype)
if a.shape != wgt.shape:
if axis is None:
raise TypeError(
"Axis must be specified when shapes of a and weights differ."
)
if wgt.ndim != 1:
raise TypeError(
"1D weights expected when shapes of a and weights differ."
)
if wgt.shape[0] != a.shape[axis]:
raise ValueError(
"Length of weights not compatible with specified axis."
)
wgt = broadcast_to(wgt, (a.ndim - 1) * (1,) + wgt.shape)
wgt = wgt.swapaxes(-1, axis)
if is_masked:
from dask.array.ma import getmaskarray
wgt = wgt * (~getmaskarray(a))
scl = wgt.sum(axis=axis, dtype=result_dtype)
avg = multiply(a, wgt, dtype=result_dtype).sum(axis) / scl
if returned:
if scl.shape != avg.shape:
scl = broadcast_to(scl, avg.shape).copy()
return avg, scl
else:
return avg
@derived_from(np)
def average(a, axis=None, weights=None, returned=False):
return _average(a, axis, weights, returned, is_masked=False)
@derived_from(np)
def tril(m, k=0):
m = asarray_safe(m, like=m)
mask = tri(
*m.shape[-2:],
k=k,
dtype=bool,
chunks=m.chunks[-2:],
like=meta_from_array(m) if _numpy_120 else None,
)
return where(mask, m, np.zeros_like(m, shape=(1,)))
@derived_from(np)
def triu(m, k=0):
m = asarray_safe(m, like=m)
mask = tri(
*m.shape[-2:],
k=k - 1,
dtype=bool,
chunks=m.chunks[-2:],
like=meta_from_array(m) if _numpy_120 else None,
)
return where(mask, np.zeros_like(m, shape=(1,)), m)
@derived_from(np)
def tril_indices(n, k=0, m=None, chunks="auto"):
return nonzero(tri(n, m, k=k, dtype=bool, chunks=chunks))
@derived_from(np)
def tril_indices_from(arr, k=0):
if arr.ndim != 2:
raise ValueError("input array must be 2-d")
return tril_indices(arr.shape[-2], k=k, m=arr.shape[-1], chunks=arr.chunks)
@derived_from(np)
def triu_indices(n, k=0, m=None, chunks="auto"):
return nonzero(~tri(n, m, k=k - 1, dtype=bool, chunks=chunks))
@derived_from(np)
def triu_indices_from(arr, k=0):
if arr.ndim != 2:
raise ValueError("input array must be 2-d")
return triu_indices(arr.shape[-2], k=k, m=arr.shape[-1], chunks=arr.chunks)
| true | true |
f7313e3ab3e8fc56b748beb5452013bcc48f9018 | 1,982 | py | Python | lifegame.py | cuboktahedron/Rascon | 7f754434424c6a0b5f61c96c33c5d2c4acf04a4c | [
"MIT"
] | null | null | null | lifegame.py | cuboktahedron/Rascon | 7f754434424c6a0b5f61c96c33c5d2c4acf04a4c | [
"MIT"
] | null | null | null | lifegame.py | cuboktahedron/Rascon | 7f754434424c6a0b5f61c96c33c5d2c4acf04a4c | [
"MIT"
] | null | null | null | import copy
from datetime import datetime
class LifeGame:
def __init__(self, width, height):
self.__width = width
self.__height = height
self.__cells = [[False for x in range(0, width)] for y in range(0, height)]
self.__fps = 2
self._next_ts = datetime.now().timestamp()
def set(self, x, y, status):
self.__cells[y][x] = status
def get(self, x, y):
return self.__cells[y][x]
def next(self):
cur_ts = datetime.now().timestamp()
if cur_ts < self._next_ts:
return
self._next_ts = cur_ts + (1 / self.__fps)
nextCells = [[False for x in range(0, self.__width)] for y in range(0, self.__height)]
for x in range(0, self.__width):
for y in range(0, self.__height):
nextCells[y][x] = self.__next_cell(x, y)
self.__cells = nextCells
def __next_cell(self, x, y):
surroundCells = [
self.__is_alive(x - 1, y - 1),
self.__is_alive(x - 1, y + 0),
self.__is_alive(x - 1, y + 1),
self.__is_alive(x + 0, y - 1),
self.__is_alive(x + 0, y + 1),
self.__is_alive(x + 1, y - 1),
self.__is_alive(x + 1, y + 0),
self.__is_alive(x + 1, y + 1),
]
aliveCount = len(list(filter(lambda cell: cell, surroundCells)))
if self.__cells[y][x]:
return 2 <= aliveCount <= 3
else:
return aliveCount == 3
def __is_alive(self, x, y):
x = self.__width - 1 if x < 0 else x
x = 0 if x >= self.__width else x
y = self.__height -1 if y < 0 else y
y = 0 if y >= self.__height else y
return self.__cells[y][x]
def __is_outer(self, x, y):
return x < 0 or x >= self.__width or y < 0 or y >= self.__height
def get_cells(self):
return copy.deepcopy(self.__cells)
| 30.492308 | 95 | 0.519173 | import copy
from datetime import datetime
class LifeGame:
def __init__(self, width, height):
self.__width = width
self.__height = height
self.__cells = [[False for x in range(0, width)] for y in range(0, height)]
self.__fps = 2
self._next_ts = datetime.now().timestamp()
def set(self, x, y, status):
self.__cells[y][x] = status
def get(self, x, y):
return self.__cells[y][x]
def next(self):
cur_ts = datetime.now().timestamp()
if cur_ts < self._next_ts:
return
self._next_ts = cur_ts + (1 / self.__fps)
nextCells = [[False for x in range(0, self.__width)] for y in range(0, self.__height)]
for x in range(0, self.__width):
for y in range(0, self.__height):
nextCells[y][x] = self.__next_cell(x, y)
self.__cells = nextCells
def __next_cell(self, x, y):
surroundCells = [
self.__is_alive(x - 1, y - 1),
self.__is_alive(x - 1, y + 0),
self.__is_alive(x - 1, y + 1),
self.__is_alive(x + 0, y - 1),
self.__is_alive(x + 0, y + 1),
self.__is_alive(x + 1, y - 1),
self.__is_alive(x + 1, y + 0),
self.__is_alive(x + 1, y + 1),
]
aliveCount = len(list(filter(lambda cell: cell, surroundCells)))
if self.__cells[y][x]:
return 2 <= aliveCount <= 3
else:
return aliveCount == 3
def __is_alive(self, x, y):
x = self.__width - 1 if x < 0 else x
x = 0 if x >= self.__width else x
y = self.__height -1 if y < 0 else y
y = 0 if y >= self.__height else y
return self.__cells[y][x]
def __is_outer(self, x, y):
return x < 0 or x >= self.__width or y < 0 or y >= self.__height
def get_cells(self):
return copy.deepcopy(self.__cells)
| true | true |
f7313e94c331bb92c55fd8f8212ee3abca3087ee | 4,287 | py | Python | dockermon.py | CyberInt/dockermon | a8733b9395cb1b551971f17c31d7f4a8268bb969 | [
"MIT"
] | 10 | 2015-06-27T06:06:01.000Z | 2021-02-15T04:04:02.000Z | dockermon.py | CyberInt/dockermon | a8733b9395cb1b551971f17c31d7f4a8268bb969 | [
"MIT"
] | 2 | 2015-08-09T14:10:25.000Z | 2016-05-14T09:25:43.000Z | dockermon.py | CyberInt/dockermon | a8733b9395cb1b551971f17c31d7f4a8268bb969 | [
"MIT"
] | 7 | 2016-02-03T03:24:09.000Z | 2021-02-15T04:08:40.000Z | #!/usr/bin/env python
"""docker monitor using docker /events HTTP streaming API"""
from contextlib import closing
from functools import partial
from socket import socket, AF_UNIX
from subprocess import Popen, PIPE
from sys import stdout, version_info
import json
import shlex
if version_info[:2] < (3, 0):
from httplib import OK as HTTP_OK
from urlparse import urlparse
else:
from http.client import OK as HTTP_OK
from urllib.parse import urlparse
__version__ = '0.2.2'
bufsize = 1024
default_sock_url = 'ipc:///var/run/docker.sock'
class DockermonError(Exception):
pass
def read_http_header(sock):
"""Read HTTP header from socket, return header and rest of data."""
buf = []
hdr_end = '\r\n\r\n'
while True:
buf.append(sock.recv(bufsize).decode('utf-8'))
data = ''.join(buf)
i = data.find(hdr_end)
if i == -1:
continue
return data[:i], data[i + len(hdr_end):]
def header_status(header):
"""Parse HTTP status line, return status (int) and reason."""
status_line = header[:header.find('\r')]
# 'HTTP/1.1 200 OK' -> (200, 'OK')
fields = status_line.split(None, 2)
return int(fields[1]), fields[2]
def connect(url):
"""Connect to UNIX or TCP socket.
url can be either tcp://<host>:port or ipc://<path>
"""
url = urlparse(url)
if url.scheme == 'tcp':
sock = socket()
netloc = tuple(url.netloc.rsplit(':', 1))
hostname = socket.gethostname()
elif url.scheme == 'ipc':
sock = socket(AF_UNIX)
netloc = url.path
hostname = 'localhost'
else:
raise ValueError('unknown socket type: %s' % url.scheme)
sock.connect(netloc)
return sock, hostname
def watch(callback, url=default_sock_url):
"""Watch docker events. Will call callback with each new event (dict).
url can be either tcp://<host>:port or ipc://<path>
"""
sock, hostname = connect(url)
request = 'GET /events HTTP/1.1\nHost: %s\n\n' % hostname
request = request.encode('utf-8')
with closing(sock):
sock.sendall(request)
header, payload = read_http_header(sock)
status, reason = header_status(header)
if status != HTTP_OK:
raise DockermonError('bad HTTP status: %s %s' % (status, reason))
# Messages are \r\n<size in hex><JSON payload>\r\n
buf = [payload]
while True:
chunk = sock.recv(bufsize)
if not chunk:
raise EOFError('socket closed')
buf.append(chunk.decode('utf-8'))
data = ''.join(buf)
i = data.find('\r\n')
if i == -1:
continue
size = int(data[:i], 16)
start = i + 2 # Skip initial \r\n
if len(data) < start + size + 2:
continue
payload = data[start:start+size]
callback(json.loads(payload))
buf = [data[start+size+2:]] # Skip \r\n suffix
def print_callback(msg):
"""Print callback, prints message to stdout as JSON in one line."""
json.dump(msg, stdout)
stdout.write('\n')
stdout.flush()
def prog_callback(prog, msg):
"""Program callback, calls prog with message in stdin"""
pipe = Popen(prog, stdin=PIPE)
data = json.dumps(msg)
pipe.stdin.write(data.encode('utf-8'))
pipe.stdin.close()
if __name__ == '__main__':
from argparse import ArgumentParser
parser = ArgumentParser(description=__doc__)
parser.add_argument('--prog', default=None,
help='program to call (e.g. "jq --unbuffered .")')
parser.add_argument(
'--socket-url', default=default_sock_url,
help='socket url (ipc:///path/to/sock or tcp:///host:port)')
parser.add_argument(
'--version', help='print version and exit',
action='store_true', default=False)
args = parser.parse_args()
if args.version:
print('dockermon %s' % __version__)
raise SystemExit
if args.prog:
prog = shlex.split(args.prog)
callback = partial(prog_callback, prog)
else:
callback = print_callback
try:
watch(callback, args.socket_url)
except (KeyboardInterrupt, EOFError):
pass
| 28.203947 | 77 | 0.601586 |
from contextlib import closing
from functools import partial
from socket import socket, AF_UNIX
from subprocess import Popen, PIPE
from sys import stdout, version_info
import json
import shlex
if version_info[:2] < (3, 0):
from httplib import OK as HTTP_OK
from urlparse import urlparse
else:
from http.client import OK as HTTP_OK
from urllib.parse import urlparse
__version__ = '0.2.2'
bufsize = 1024
default_sock_url = 'ipc:///var/run/docker.sock'
class DockermonError(Exception):
pass
def read_http_header(sock):
buf = []
hdr_end = '\r\n\r\n'
while True:
buf.append(sock.recv(bufsize).decode('utf-8'))
data = ''.join(buf)
i = data.find(hdr_end)
if i == -1:
continue
return data[:i], data[i + len(hdr_end):]
def header_status(header):
status_line = header[:header.find('\r')]
fields = status_line.split(None, 2)
return int(fields[1]), fields[2]
def connect(url):
url = urlparse(url)
if url.scheme == 'tcp':
sock = socket()
netloc = tuple(url.netloc.rsplit(':', 1))
hostname = socket.gethostname()
elif url.scheme == 'ipc':
sock = socket(AF_UNIX)
netloc = url.path
hostname = 'localhost'
else:
raise ValueError('unknown socket type: %s' % url.scheme)
sock.connect(netloc)
return sock, hostname
def watch(callback, url=default_sock_url):
sock, hostname = connect(url)
request = 'GET /events HTTP/1.1\nHost: %s\n\n' % hostname
request = request.encode('utf-8')
with closing(sock):
sock.sendall(request)
header, payload = read_http_header(sock)
status, reason = header_status(header)
if status != HTTP_OK:
raise DockermonError('bad HTTP status: %s %s' % (status, reason))
buf = [payload]
while True:
chunk = sock.recv(bufsize)
if not chunk:
raise EOFError('socket closed')
buf.append(chunk.decode('utf-8'))
data = ''.join(buf)
i = data.find('\r\n')
if i == -1:
continue
size = int(data[:i], 16)
start = i + 2
if len(data) < start + size + 2:
continue
payload = data[start:start+size]
callback(json.loads(payload))
buf = [data[start+size+2:]]
def print_callback(msg):
json.dump(msg, stdout)
stdout.write('\n')
stdout.flush()
def prog_callback(prog, msg):
pipe = Popen(prog, stdin=PIPE)
data = json.dumps(msg)
pipe.stdin.write(data.encode('utf-8'))
pipe.stdin.close()
if __name__ == '__main__':
from argparse import ArgumentParser
parser = ArgumentParser(description=__doc__)
parser.add_argument('--prog', default=None,
help='program to call (e.g. "jq --unbuffered .")')
parser.add_argument(
'--socket-url', default=default_sock_url,
help='socket url (ipc:///path/to/sock or tcp:///host:port)')
parser.add_argument(
'--version', help='print version and exit',
action='store_true', default=False)
args = parser.parse_args()
if args.version:
print('dockermon %s' % __version__)
raise SystemExit
if args.prog:
prog = shlex.split(args.prog)
callback = partial(prog_callback, prog)
else:
callback = print_callback
try:
watch(callback, args.socket_url)
except (KeyboardInterrupt, EOFError):
pass
| true | true |
f7313f100d4294fe5183c05e8c3ad109ceb0c790 | 16,944 | py | Python | pandas/tests/indexes/ranges/test_range.py | mujtahidalam/pandas | 526468c8fe6fc5157aaf2fce327c5ab2a3350f49 | [
"PSF-2.0",
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"MIT",
"MIT-0",
"ECL-2.0",
"BSD-3-Clause"
] | 1 | 2021-06-17T12:54:33.000Z | 2021-06-17T12:54:33.000Z | pandas/tests/indexes/ranges/test_range.py | mujtahidalam/pandas | 526468c8fe6fc5157aaf2fce327c5ab2a3350f49 | [
"PSF-2.0",
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"MIT",
"MIT-0",
"ECL-2.0",
"BSD-3-Clause"
] | null | null | null | pandas/tests/indexes/ranges/test_range.py | mujtahidalam/pandas | 526468c8fe6fc5157aaf2fce327c5ab2a3350f49 | [
"PSF-2.0",
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"MIT",
"MIT-0",
"ECL-2.0",
"BSD-3-Clause"
] | null | null | null | import numpy as np
import pytest
from pandas.core.dtypes.common import ensure_platform_int
import pandas as pd
from pandas import (
Float64Index,
Index,
Int64Index,
RangeIndex,
)
import pandas._testing as tm
from pandas.tests.indexes.test_numeric import Numeric
# aliases to make some tests easier to read
RI = RangeIndex
I64 = Int64Index
F64 = Float64Index
OI = Index
class TestRangeIndex(Numeric):
_index_cls = RangeIndex
@pytest.fixture
def simple_index(self) -> Index:
return self._index_cls(start=0, stop=20, step=2)
@pytest.fixture(
params=[
RangeIndex(start=0, stop=20, step=2, name="foo"),
RangeIndex(start=18, stop=-1, step=-2, name="bar"),
],
ids=["index_inc", "index_dec"],
)
def index(self, request):
return request.param
def test_can_hold_identifiers(self, simple_index):
idx = simple_index
key = idx[0]
assert idx._can_hold_identifiers_and_holds_name(key) is False
def test_too_many_names(self, simple_index):
index = simple_index
with pytest.raises(ValueError, match="^Length"):
index.names = ["roger", "harold"]
@pytest.mark.parametrize(
"index, start, stop, step",
[
(RangeIndex(5), 0, 5, 1),
(RangeIndex(0, 5), 0, 5, 1),
(RangeIndex(5, step=2), 0, 5, 2),
(RangeIndex(1, 5, 2), 1, 5, 2),
],
)
def test_start_stop_step_attrs(self, index, start, stop, step):
# GH 25710
assert index.start == start
assert index.stop == stop
assert index.step == step
@pytest.mark.parametrize("attr_name", ["_start", "_stop", "_step"])
def test_deprecated_start_stop_step_attrs(self, attr_name, simple_index):
# GH 26581
idx = simple_index
with tm.assert_produces_warning(FutureWarning):
getattr(idx, attr_name)
def test_copy(self):
i = RangeIndex(5, name="Foo")
i_copy = i.copy()
assert i_copy is not i
assert i_copy.identical(i)
assert i_copy._range == range(0, 5, 1)
assert i_copy.name == "Foo"
def test_repr(self):
i = RangeIndex(5, name="Foo")
result = repr(i)
expected = "RangeIndex(start=0, stop=5, step=1, name='Foo')"
assert result == expected
result = eval(result)
tm.assert_index_equal(result, i, exact=True)
i = RangeIndex(5, 0, -1)
result = repr(i)
expected = "RangeIndex(start=5, stop=0, step=-1)"
assert result == expected
result = eval(result)
tm.assert_index_equal(result, i, exact=True)
def test_insert(self):
idx = RangeIndex(5, name="Foo")
result = idx[1:4]
# test 0th element
tm.assert_index_equal(idx[0:4], result.insert(0, idx[0]))
# GH 18295 (test missing)
expected = Float64Index([0, np.nan, 1, 2, 3, 4])
for na in [np.nan, None, pd.NA]:
result = RangeIndex(5).insert(1, na)
tm.assert_index_equal(result, expected)
result = RangeIndex(5).insert(1, pd.NaT)
expected = Index([0, pd.NaT, 1, 2, 3, 4], dtype=object)
tm.assert_index_equal(result, expected)
def test_delete(self):
idx = RangeIndex(5, name="Foo")
expected = idx[1:].astype(int)
result = idx.delete(0)
tm.assert_index_equal(result, expected)
assert result.name == expected.name
expected = idx[:-1].astype(int)
result = idx.delete(-1)
tm.assert_index_equal(result, expected)
assert result.name == expected.name
msg = "index 5 is out of bounds for axis 0 with size 5"
with pytest.raises((IndexError, ValueError), match=msg):
# either depending on numpy version
result = idx.delete(len(idx))
def test_view(self):
i = RangeIndex(0, name="Foo")
i_view = i.view()
assert i_view.name == "Foo"
i_view = i.view("i8")
tm.assert_numpy_array_equal(i.values, i_view)
i_view = i.view(RangeIndex)
tm.assert_index_equal(i, i_view)
def test_dtype(self, simple_index):
index = simple_index
assert index.dtype == np.int64
def test_cache(self):
# GH 26565, GH26617, GH35432
# This test checks whether _cache has been set.
# Calling RangeIndex._cache["_data"] creates an int64 array of the same length
# as the RangeIndex and stores it in _cache.
idx = RangeIndex(0, 100, 10)
assert idx._cache == {}
repr(idx)
assert idx._cache == {}
str(idx)
assert idx._cache == {}
idx.get_loc(20)
assert idx._cache == {}
90 in idx # True
assert idx._cache == {}
91 in idx # False
assert idx._cache == {}
idx.all()
assert idx._cache == {}
idx.any()
assert idx._cache == {}
for _ in idx:
pass
assert idx._cache == {}
idx.format()
assert idx._cache == {}
df = pd.DataFrame({"a": range(10)}, index=idx)
str(df)
assert idx._cache == {}
df.loc[50]
assert idx._cache == {}
with pytest.raises(KeyError, match="51"):
df.loc[51]
assert idx._cache == {}
df.loc[10:50]
assert idx._cache == {}
df.iloc[5:10]
assert idx._cache == {}
# idx._cache should contain a _data entry after call to idx._data
idx._data
assert isinstance(idx._data, np.ndarray)
assert idx._data is idx._data # check cached value is reused
assert len(idx._cache) == 1
expected = np.arange(0, 100, 10, dtype="int64")
tm.assert_numpy_array_equal(idx._cache["_data"], expected)
def test_is_monotonic(self):
index = RangeIndex(0, 20, 2)
assert index.is_monotonic is True
assert index.is_monotonic_increasing is True
assert index.is_monotonic_decreasing is False
assert index._is_strictly_monotonic_increasing is True
assert index._is_strictly_monotonic_decreasing is False
index = RangeIndex(4, 0, -1)
assert index.is_monotonic is False
assert index._is_strictly_monotonic_increasing is False
assert index.is_monotonic_decreasing is True
assert index._is_strictly_monotonic_decreasing is True
index = RangeIndex(1, 2)
assert index.is_monotonic is True
assert index.is_monotonic_increasing is True
assert index.is_monotonic_decreasing is True
assert index._is_strictly_monotonic_increasing is True
assert index._is_strictly_monotonic_decreasing is True
index = RangeIndex(2, 1)
assert index.is_monotonic is True
assert index.is_monotonic_increasing is True
assert index.is_monotonic_decreasing is True
assert index._is_strictly_monotonic_increasing is True
assert index._is_strictly_monotonic_decreasing is True
index = RangeIndex(1, 1)
assert index.is_monotonic is True
assert index.is_monotonic_increasing is True
assert index.is_monotonic_decreasing is True
assert index._is_strictly_monotonic_increasing is True
assert index._is_strictly_monotonic_decreasing is True
def test_equals_range(self):
equiv_pairs = [
(RangeIndex(0, 9, 2), RangeIndex(0, 10, 2)),
(RangeIndex(0), RangeIndex(1, -1, 3)),
(RangeIndex(1, 2, 3), RangeIndex(1, 3, 4)),
(RangeIndex(0, -9, -2), RangeIndex(0, -10, -2)),
]
for left, right in equiv_pairs:
assert left.equals(right)
assert right.equals(left)
def test_logical_compat(self, simple_index):
idx = simple_index
assert idx.all() == idx.values.all()
assert idx.any() == idx.values.any()
def test_identical(self, simple_index):
index = simple_index
i = Index(index.copy())
assert i.identical(index)
# we don't allow object dtype for RangeIndex
if isinstance(index, RangeIndex):
return
same_values_different_type = Index(i, dtype=object)
assert not i.identical(same_values_different_type)
i = index.copy(dtype=object)
i = i.rename("foo")
same_values = Index(i, dtype=object)
assert same_values.identical(index.copy(dtype=object))
assert not i.identical(index)
assert Index(same_values, name="foo", dtype=object).identical(i)
assert not index.copy(dtype=object).identical(index.copy(dtype="int64"))
def test_nbytes(self):
# memory savings vs int index
i = RangeIndex(0, 1000)
assert i.nbytes < i._int64index.nbytes / 10
# constant memory usage
i2 = RangeIndex(0, 10)
assert i.nbytes == i2.nbytes
@pytest.mark.parametrize(
"start,stop,step",
[
# can't
("foo", "bar", "baz"),
# shouldn't
("0", "1", "2"),
],
)
def test_cant_or_shouldnt_cast(self, start, stop, step):
msg = f"Wrong type {type(start)} for value {start}"
with pytest.raises(TypeError, match=msg):
RangeIndex(start, stop, step)
def test_view_index(self, simple_index):
index = simple_index
index.view(Index)
def test_prevent_casting(self, simple_index):
index = simple_index
result = index.astype("O")
assert result.dtype == np.object_
def test_repr_roundtrip(self, simple_index):
index = simple_index
tm.assert_index_equal(eval(repr(index)), index)
def test_slice_keep_name(self):
idx = RangeIndex(1, 2, name="asdf")
assert idx.name == idx[1:].name
def test_has_duplicates(self, index):
assert index.is_unique
assert not index.has_duplicates
def test_extended_gcd(self, simple_index):
index = simple_index
result = index._extended_gcd(6, 10)
assert result[0] == result[1] * 6 + result[2] * 10
assert 2 == result[0]
result = index._extended_gcd(10, 6)
assert 2 == result[1] * 10 + result[2] * 6
assert 2 == result[0]
def test_min_fitting_element(self):
result = RangeIndex(0, 20, 2)._min_fitting_element(1)
assert 2 == result
result = RangeIndex(1, 6)._min_fitting_element(1)
assert 1 == result
result = RangeIndex(18, -2, -2)._min_fitting_element(1)
assert 2 == result
result = RangeIndex(5, 0, -1)._min_fitting_element(1)
assert 1 == result
big_num = 500000000000000000000000
result = RangeIndex(5, big_num * 2, 1)._min_fitting_element(big_num)
assert big_num == result
def test_max_fitting_element(self):
result = RangeIndex(0, 20, 2)._max_fitting_element(17)
assert 16 == result
result = RangeIndex(1, 6)._max_fitting_element(4)
assert 4 == result
result = RangeIndex(18, -2, -2)._max_fitting_element(17)
assert 16 == result
result = RangeIndex(5, 0, -1)._max_fitting_element(4)
assert 4 == result
big_num = 500000000000000000000000
result = RangeIndex(5, big_num * 2, 1)._max_fitting_element(big_num)
assert big_num == result
def test_pickle_compat_construction(self):
# RangeIndex() is a valid constructor
pass
def test_slice_specialised(self, simple_index):
index = simple_index
index.name = "foo"
# scalar indexing
res = index[1]
expected = 2
assert res == expected
res = index[-1]
expected = 18
assert res == expected
# slicing
# slice value completion
index_slice = index[:]
expected = index
tm.assert_index_equal(index_slice, expected)
# positive slice values
index_slice = index[7:10:2]
expected = Index(np.array([14, 18]), name="foo")
tm.assert_index_equal(index_slice, expected)
# negative slice values
index_slice = index[-1:-5:-2]
expected = Index(np.array([18, 14]), name="foo")
tm.assert_index_equal(index_slice, expected)
# stop overshoot
index_slice = index[2:100:4]
expected = Index(np.array([4, 12]), name="foo")
tm.assert_index_equal(index_slice, expected)
# reverse
index_slice = index[::-1]
expected = Index(index.values[::-1], name="foo")
tm.assert_index_equal(index_slice, expected)
index_slice = index[-8::-1]
expected = Index(np.array([4, 2, 0]), name="foo")
tm.assert_index_equal(index_slice, expected)
index_slice = index[-40::-1]
expected = Index(np.array([], dtype=np.int64), name="foo")
tm.assert_index_equal(index_slice, expected)
index_slice = index[40::-1]
expected = Index(index.values[40::-1], name="foo")
tm.assert_index_equal(index_slice, expected)
index_slice = index[10::-1]
expected = Index(index.values[::-1], name="foo")
tm.assert_index_equal(index_slice, expected)
@pytest.mark.parametrize("step", set(range(-5, 6)) - {0})
def test_len_specialised(self, step):
# make sure that our len is the same as np.arange calc
start, stop = (0, 5) if step > 0 else (5, 0)
arr = np.arange(start, stop, step)
index = RangeIndex(start, stop, step)
assert len(index) == len(arr)
index = RangeIndex(stop, start, step)
assert len(index) == 0
@pytest.fixture(
params=[
([RI(1, 12, 5)], RI(1, 12, 5)),
([RI(0, 6, 4)], RI(0, 6, 4)),
([RI(1, 3), RI(3, 7)], RI(1, 7)),
([RI(1, 5, 2), RI(5, 6)], RI(1, 6, 2)),
([RI(1, 3, 2), RI(4, 7, 3)], RI(1, 7, 3)),
([RI(-4, 3, 2), RI(4, 7, 2)], RI(-4, 7, 2)),
([RI(-4, -8), RI(-8, -12)], RI(0, 0)),
([RI(-4, -8), RI(3, -4)], RI(0, 0)),
([RI(-4, -8), RI(3, 5)], RI(3, 5)),
([RI(-4, -2), RI(3, 5)], I64([-4, -3, 3, 4])),
([RI(-2), RI(3, 5)], RI(3, 5)),
([RI(2), RI(2)], I64([0, 1, 0, 1])),
([RI(2), RI(2, 5), RI(5, 8, 4)], RI(0, 6)),
([RI(2), RI(3, 5), RI(5, 8, 4)], I64([0, 1, 3, 4, 5])),
([RI(-2, 2), RI(2, 5), RI(5, 8, 4)], RI(-2, 6)),
([RI(3), I64([-1, 3, 15])], I64([0, 1, 2, -1, 3, 15])),
([RI(3), F64([-1, 3.1, 15.0])], F64([0, 1, 2, -1, 3.1, 15.0])),
([RI(3), OI(["a", None, 14])], OI([0, 1, 2, "a", None, 14])),
([RI(3, 1), OI(["a", None, 14])], OI(["a", None, 14])),
]
)
def appends(self, request):
"""Inputs and expected outputs for RangeIndex.append test"""
return request.param
def test_append(self, appends):
# GH16212
indices, expected = appends
result = indices[0].append(indices[1:])
tm.assert_index_equal(result, expected, exact=True)
if len(indices) == 2:
# Append single item rather than list
result2 = indices[0].append(indices[1])
tm.assert_index_equal(result2, expected, exact=True)
def test_engineless_lookup(self):
# GH 16685
# Standard lookup on RangeIndex should not require the engine to be
# created
idx = RangeIndex(2, 10, 3)
assert idx.get_loc(5) == 1
tm.assert_numpy_array_equal(
idx.get_indexer([2, 8]), ensure_platform_int(np.array([0, 2]))
)
with pytest.raises(KeyError, match="3"):
idx.get_loc(3)
assert "_engine" not in idx._cache
# Different types of scalars can be excluded immediately, no need to
# use the _engine
with pytest.raises(KeyError, match="'a'"):
idx.get_loc("a")
assert "_engine" not in idx._cache
def test_format_empty(self):
# GH35712
empty_idx = self._index_cls(0)
assert empty_idx.format() == []
assert empty_idx.format(name=True) == [""]
@pytest.mark.parametrize(
"RI",
[
RangeIndex(0, -1, -1),
RangeIndex(0, 1, 1),
RangeIndex(1, 3, 2),
RangeIndex(0, -1, -2),
RangeIndex(-3, -5, -2),
],
)
def test_append_len_one(self, RI):
# GH39401
result = RI.append([])
tm.assert_index_equal(result, RI, exact=True)
@pytest.mark.parametrize("base", [RangeIndex(0, 2), Index([0, 1])])
def test_isin_range(self, base):
# GH#41151
values = RangeIndex(0, 1)
result = base.isin(values)
expected = np.array([True, False])
tm.assert_numpy_array_equal(result, expected)
| 31.61194 | 86 | 0.578435 | import numpy as np
import pytest
from pandas.core.dtypes.common import ensure_platform_int
import pandas as pd
from pandas import (
Float64Index,
Index,
Int64Index,
RangeIndex,
)
import pandas._testing as tm
from pandas.tests.indexes.test_numeric import Numeric
RI = RangeIndex
I64 = Int64Index
F64 = Float64Index
OI = Index
class TestRangeIndex(Numeric):
_index_cls = RangeIndex
@pytest.fixture
def simple_index(self) -> Index:
return self._index_cls(start=0, stop=20, step=2)
@pytest.fixture(
params=[
RangeIndex(start=0, stop=20, step=2, name="foo"),
RangeIndex(start=18, stop=-1, step=-2, name="bar"),
],
ids=["index_inc", "index_dec"],
)
def index(self, request):
return request.param
def test_can_hold_identifiers(self, simple_index):
idx = simple_index
key = idx[0]
assert idx._can_hold_identifiers_and_holds_name(key) is False
def test_too_many_names(self, simple_index):
index = simple_index
with pytest.raises(ValueError, match="^Length"):
index.names = ["roger", "harold"]
@pytest.mark.parametrize(
"index, start, stop, step",
[
(RangeIndex(5), 0, 5, 1),
(RangeIndex(0, 5), 0, 5, 1),
(RangeIndex(5, step=2), 0, 5, 2),
(RangeIndex(1, 5, 2), 1, 5, 2),
],
)
def test_start_stop_step_attrs(self, index, start, stop, step):
assert index.start == start
assert index.stop == stop
assert index.step == step
@pytest.mark.parametrize("attr_name", ["_start", "_stop", "_step"])
def test_deprecated_start_stop_step_attrs(self, attr_name, simple_index):
idx = simple_index
with tm.assert_produces_warning(FutureWarning):
getattr(idx, attr_name)
def test_copy(self):
i = RangeIndex(5, name="Foo")
i_copy = i.copy()
assert i_copy is not i
assert i_copy.identical(i)
assert i_copy._range == range(0, 5, 1)
assert i_copy.name == "Foo"
def test_repr(self):
i = RangeIndex(5, name="Foo")
result = repr(i)
expected = "RangeIndex(start=0, stop=5, step=1, name='Foo')"
assert result == expected
result = eval(result)
tm.assert_index_equal(result, i, exact=True)
i = RangeIndex(5, 0, -1)
result = repr(i)
expected = "RangeIndex(start=5, stop=0, step=-1)"
assert result == expected
result = eval(result)
tm.assert_index_equal(result, i, exact=True)
def test_insert(self):
idx = RangeIndex(5, name="Foo")
result = idx[1:4]
tm.assert_index_equal(idx[0:4], result.insert(0, idx[0]))
expected = Float64Index([0, np.nan, 1, 2, 3, 4])
for na in [np.nan, None, pd.NA]:
result = RangeIndex(5).insert(1, na)
tm.assert_index_equal(result, expected)
result = RangeIndex(5).insert(1, pd.NaT)
expected = Index([0, pd.NaT, 1, 2, 3, 4], dtype=object)
tm.assert_index_equal(result, expected)
def test_delete(self):
idx = RangeIndex(5, name="Foo")
expected = idx[1:].astype(int)
result = idx.delete(0)
tm.assert_index_equal(result, expected)
assert result.name == expected.name
expected = idx[:-1].astype(int)
result = idx.delete(-1)
tm.assert_index_equal(result, expected)
assert result.name == expected.name
msg = "index 5 is out of bounds for axis 0 with size 5"
with pytest.raises((IndexError, ValueError), match=msg):
result = idx.delete(len(idx))
def test_view(self):
i = RangeIndex(0, name="Foo")
i_view = i.view()
assert i_view.name == "Foo"
i_view = i.view("i8")
tm.assert_numpy_array_equal(i.values, i_view)
i_view = i.view(RangeIndex)
tm.assert_index_equal(i, i_view)
def test_dtype(self, simple_index):
index = simple_index
assert index.dtype == np.int64
def test_cache(self):
idx = RangeIndex(0, 100, 10)
assert idx._cache == {}
repr(idx)
assert idx._cache == {}
str(idx)
assert idx._cache == {}
idx.get_loc(20)
assert idx._cache == {}
90 in idx
assert idx._cache == {}
91 in idx
assert idx._cache == {}
idx.all()
assert idx._cache == {}
idx.any()
assert idx._cache == {}
for _ in idx:
pass
assert idx._cache == {}
idx.format()
assert idx._cache == {}
df = pd.DataFrame({"a": range(10)}, index=idx)
str(df)
assert idx._cache == {}
df.loc[50]
assert idx._cache == {}
with pytest.raises(KeyError, match="51"):
df.loc[51]
assert idx._cache == {}
df.loc[10:50]
assert idx._cache == {}
df.iloc[5:10]
assert idx._cache == {}
idx._data
assert isinstance(idx._data, np.ndarray)
assert idx._data is idx._data
assert len(idx._cache) == 1
expected = np.arange(0, 100, 10, dtype="int64")
tm.assert_numpy_array_equal(idx._cache["_data"], expected)
def test_is_monotonic(self):
index = RangeIndex(0, 20, 2)
assert index.is_monotonic is True
assert index.is_monotonic_increasing is True
assert index.is_monotonic_decreasing is False
assert index._is_strictly_monotonic_increasing is True
assert index._is_strictly_monotonic_decreasing is False
index = RangeIndex(4, 0, -1)
assert index.is_monotonic is False
assert index._is_strictly_monotonic_increasing is False
assert index.is_monotonic_decreasing is True
assert index._is_strictly_monotonic_decreasing is True
index = RangeIndex(1, 2)
assert index.is_monotonic is True
assert index.is_monotonic_increasing is True
assert index.is_monotonic_decreasing is True
assert index._is_strictly_monotonic_increasing is True
assert index._is_strictly_monotonic_decreasing is True
index = RangeIndex(2, 1)
assert index.is_monotonic is True
assert index.is_monotonic_increasing is True
assert index.is_monotonic_decreasing is True
assert index._is_strictly_monotonic_increasing is True
assert index._is_strictly_monotonic_decreasing is True
index = RangeIndex(1, 1)
assert index.is_monotonic is True
assert index.is_monotonic_increasing is True
assert index.is_monotonic_decreasing is True
assert index._is_strictly_monotonic_increasing is True
assert index._is_strictly_monotonic_decreasing is True
def test_equals_range(self):
equiv_pairs = [
(RangeIndex(0, 9, 2), RangeIndex(0, 10, 2)),
(RangeIndex(0), RangeIndex(1, -1, 3)),
(RangeIndex(1, 2, 3), RangeIndex(1, 3, 4)),
(RangeIndex(0, -9, -2), RangeIndex(0, -10, -2)),
]
for left, right in equiv_pairs:
assert left.equals(right)
assert right.equals(left)
def test_logical_compat(self, simple_index):
idx = simple_index
assert idx.all() == idx.values.all()
assert idx.any() == idx.values.any()
def test_identical(self, simple_index):
index = simple_index
i = Index(index.copy())
assert i.identical(index)
if isinstance(index, RangeIndex):
return
same_values_different_type = Index(i, dtype=object)
assert not i.identical(same_values_different_type)
i = index.copy(dtype=object)
i = i.rename("foo")
same_values = Index(i, dtype=object)
assert same_values.identical(index.copy(dtype=object))
assert not i.identical(index)
assert Index(same_values, name="foo", dtype=object).identical(i)
assert not index.copy(dtype=object).identical(index.copy(dtype="int64"))
def test_nbytes(self):
# memory savings vs int index
i = RangeIndex(0, 1000)
assert i.nbytes < i._int64index.nbytes / 10
# constant memory usage
i2 = RangeIndex(0, 10)
assert i.nbytes == i2.nbytes
@pytest.mark.parametrize(
"start,stop,step",
[
# can't
("foo", "bar", "baz"),
("0", "1", "2"),
],
)
def test_cant_or_shouldnt_cast(self, start, stop, step):
msg = f"Wrong type {type(start)} for value {start}"
with pytest.raises(TypeError, match=msg):
RangeIndex(start, stop, step)
def test_view_index(self, simple_index):
index = simple_index
index.view(Index)
def test_prevent_casting(self, simple_index):
index = simple_index
result = index.astype("O")
assert result.dtype == np.object_
def test_repr_roundtrip(self, simple_index):
index = simple_index
tm.assert_index_equal(eval(repr(index)), index)
def test_slice_keep_name(self):
idx = RangeIndex(1, 2, name="asdf")
assert idx.name == idx[1:].name
def test_has_duplicates(self, index):
assert index.is_unique
assert not index.has_duplicates
def test_extended_gcd(self, simple_index):
index = simple_index
result = index._extended_gcd(6, 10)
assert result[0] == result[1] * 6 + result[2] * 10
assert 2 == result[0]
result = index._extended_gcd(10, 6)
assert 2 == result[1] * 10 + result[2] * 6
assert 2 == result[0]
def test_min_fitting_element(self):
result = RangeIndex(0, 20, 2)._min_fitting_element(1)
assert 2 == result
result = RangeIndex(1, 6)._min_fitting_element(1)
assert 1 == result
result = RangeIndex(18, -2, -2)._min_fitting_element(1)
assert 2 == result
result = RangeIndex(5, 0, -1)._min_fitting_element(1)
assert 1 == result
big_num = 500000000000000000000000
result = RangeIndex(5, big_num * 2, 1)._min_fitting_element(big_num)
assert big_num == result
def test_max_fitting_element(self):
result = RangeIndex(0, 20, 2)._max_fitting_element(17)
assert 16 == result
result = RangeIndex(1, 6)._max_fitting_element(4)
assert 4 == result
result = RangeIndex(18, -2, -2)._max_fitting_element(17)
assert 16 == result
result = RangeIndex(5, 0, -1)._max_fitting_element(4)
assert 4 == result
big_num = 500000000000000000000000
result = RangeIndex(5, big_num * 2, 1)._max_fitting_element(big_num)
assert big_num == result
def test_pickle_compat_construction(self):
# RangeIndex() is a valid constructor
pass
def test_slice_specialised(self, simple_index):
index = simple_index
index.name = "foo"
# scalar indexing
res = index[1]
expected = 2
assert res == expected
res = index[-1]
expected = 18
assert res == expected
# slicing
# slice value completion
index_slice = index[:]
expected = index
tm.assert_index_equal(index_slice, expected)
# positive slice values
index_slice = index[7:10:2]
expected = Index(np.array([14, 18]), name="foo")
tm.assert_index_equal(index_slice, expected)
# negative slice values
index_slice = index[-1:-5:-2]
expected = Index(np.array([18, 14]), name="foo")
tm.assert_index_equal(index_slice, expected)
# stop overshoot
index_slice = index[2:100:4]
expected = Index(np.array([4, 12]), name="foo")
tm.assert_index_equal(index_slice, expected)
# reverse
index_slice = index[::-1]
expected = Index(index.values[::-1], name="foo")
tm.assert_index_equal(index_slice, expected)
index_slice = index[-8::-1]
expected = Index(np.array([4, 2, 0]), name="foo")
tm.assert_index_equal(index_slice, expected)
index_slice = index[-40::-1]
expected = Index(np.array([], dtype=np.int64), name="foo")
tm.assert_index_equal(index_slice, expected)
index_slice = index[40::-1]
expected = Index(index.values[40::-1], name="foo")
tm.assert_index_equal(index_slice, expected)
index_slice = index[10::-1]
expected = Index(index.values[::-1], name="foo")
tm.assert_index_equal(index_slice, expected)
@pytest.mark.parametrize("step", set(range(-5, 6)) - {0})
def test_len_specialised(self, step):
# make sure that our len is the same as np.arange calc
start, stop = (0, 5) if step > 0 else (5, 0)
arr = np.arange(start, stop, step)
index = RangeIndex(start, stop, step)
assert len(index) == len(arr)
index = RangeIndex(stop, start, step)
assert len(index) == 0
@pytest.fixture(
params=[
([RI(1, 12, 5)], RI(1, 12, 5)),
([RI(0, 6, 4)], RI(0, 6, 4)),
([RI(1, 3), RI(3, 7)], RI(1, 7)),
([RI(1, 5, 2), RI(5, 6)], RI(1, 6, 2)),
([RI(1, 3, 2), RI(4, 7, 3)], RI(1, 7, 3)),
([RI(-4, 3, 2), RI(4, 7, 2)], RI(-4, 7, 2)),
([RI(-4, -8), RI(-8, -12)], RI(0, 0)),
([RI(-4, -8), RI(3, -4)], RI(0, 0)),
([RI(-4, -8), RI(3, 5)], RI(3, 5)),
([RI(-4, -2), RI(3, 5)], I64([-4, -3, 3, 4])),
([RI(-2), RI(3, 5)], RI(3, 5)),
([RI(2), RI(2)], I64([0, 1, 0, 1])),
([RI(2), RI(2, 5), RI(5, 8, 4)], RI(0, 6)),
([RI(2), RI(3, 5), RI(5, 8, 4)], I64([0, 1, 3, 4, 5])),
([RI(-2, 2), RI(2, 5), RI(5, 8, 4)], RI(-2, 6)),
([RI(3), I64([-1, 3, 15])], I64([0, 1, 2, -1, 3, 15])),
([RI(3), F64([-1, 3.1, 15.0])], F64([0, 1, 2, -1, 3.1, 15.0])),
([RI(3), OI(["a", None, 14])], OI([0, 1, 2, "a", None, 14])),
([RI(3, 1), OI(["a", None, 14])], OI(["a", None, 14])),
]
)
def appends(self, request):
return request.param
def test_append(self, appends):
# GH16212
indices, expected = appends
result = indices[0].append(indices[1:])
tm.assert_index_equal(result, expected, exact=True)
if len(indices) == 2:
# Append single item rather than list
result2 = indices[0].append(indices[1])
tm.assert_index_equal(result2, expected, exact=True)
def test_engineless_lookup(self):
# GH 16685
# Standard lookup on RangeIndex should not require the engine to be
# created
idx = RangeIndex(2, 10, 3)
assert idx.get_loc(5) == 1
tm.assert_numpy_array_equal(
idx.get_indexer([2, 8]), ensure_platform_int(np.array([0, 2]))
)
with pytest.raises(KeyError, match="3"):
idx.get_loc(3)
assert "_engine" not in idx._cache
# Different types of scalars can be excluded immediately, no need to
# use the _engine
with pytest.raises(KeyError, match="'a'"):
idx.get_loc("a")
assert "_engine" not in idx._cache
def test_format_empty(self):
# GH35712
empty_idx = self._index_cls(0)
assert empty_idx.format() == []
assert empty_idx.format(name=True) == [""]
@pytest.mark.parametrize(
"RI",
[
RangeIndex(0, -1, -1),
RangeIndex(0, 1, 1),
RangeIndex(1, 3, 2),
RangeIndex(0, -1, -2),
RangeIndex(-3, -5, -2),
],
)
def test_append_len_one(self, RI):
# GH39401
result = RI.append([])
tm.assert_index_equal(result, RI, exact=True)
@pytest.mark.parametrize("base", [RangeIndex(0, 2), Index([0, 1])])
def test_isin_range(self, base):
# GH#41151
values = RangeIndex(0, 1)
result = base.isin(values)
expected = np.array([True, False])
tm.assert_numpy_array_equal(result, expected)
| true | true |
f7313ff228df6f15c217111d85289fbb96c16a6e | 7,086 | py | Python | rpython/translator/backendopt/test/test_merge_if_blocks.py | nanjekyejoannah/pypy | e80079fe13c29eda7b2a6b4cd4557051f975a2d9 | [
"Apache-2.0",
"OpenSSL"
] | 381 | 2018-08-18T03:37:22.000Z | 2022-02-06T23:57:36.000Z | rpython/translator/backendopt/test/test_merge_if_blocks.py | nanjekyejoannah/pypy | e80079fe13c29eda7b2a6b4cd4557051f975a2d9 | [
"Apache-2.0",
"OpenSSL"
] | 16 | 2018-09-22T18:12:47.000Z | 2022-02-22T20:03:59.000Z | rpython/translator/backendopt/test/test_merge_if_blocks.py | nanjekyejoannah/pypy | e80079fe13c29eda7b2a6b4cd4557051f975a2d9 | [
"Apache-2.0",
"OpenSSL"
] | 55 | 2015-08-16T02:41:30.000Z | 2022-03-20T20:33:35.000Z | from rpython.translator.backendopt.merge_if_blocks import merge_if_blocks_once
from rpython.translator.backendopt.merge_if_blocks import merge_if_blocks
from rpython.translator.backendopt.all import backend_optimizations
from rpython.translator.translator import TranslationContext, graphof as tgraphof
from rpython.flowspace.model import Block, checkgraph
from rpython.translator.backendopt.removenoops import remove_same_as
from rpython.rtyper.llinterp import LLInterpreter
from rpython.rlib.rarithmetic import r_uint, r_ulonglong, r_longlong, r_int
from rpython.annotator.model import SomeChar, SomeUnicodeCodePoint
from rpython.rlib.objectmodel import CDefinedIntSymbolic
def do_test_merge(fn, testvalues):
t = TranslationContext()
a = t.buildannotator()
a.build_types(fn, [type(testvalues[0])])
rtyper = t.buildrtyper()
rtyper.specialize()
graph = tgraphof(t, fn)
assert len(list(graph.iterblocks())) == 4 #startblock, blocks, returnblock
remove_same_as(graph)
merge_if_blocks_once(graph)
assert len(graph.startblock.exits) == 4
assert len(list(graph.iterblocks())) == 2 #startblock, returnblock
interp = LLInterpreter(rtyper)
for i in testvalues:
expected = fn(i)
actual = interp.eval_graph(graph, [i])
assert actual == expected
def test_merge1():
def merge_int(n):
n += 1
if n == 1:
return 1
elif n == 2:
return 2
elif n == 3:
return 3
return 4
do_test_merge(merge_int, range(4))
do_test_merge(merge_int, [r_uint(i) for i in range(4)])
# this has been disabled:
#if r_longlong is not r_int:
# do_test_merge(merge_int, [r_longlong(i) for i in range(4)])
#do_test_merge(merge_int, [r_ulonglong(i) for i in range(4)])
def merge_chr(n):
c = chr(n + 1)
if c == 'a':
return 'a'
elif c == 'b':
return 'b'
elif c == 'c':
return 'c'
return 'd'
do_test_merge(merge_chr, range(96, 101))
def merge_uchr(n):
c = unichr(n + 1)
if c == u'a':
return u'a'
elif c == u'b':
return u'b'
elif c == u'c':
return u'c'
return u'd'
do_test_merge(merge_uchr, range(96, 101))
def test_merge_passonvars():
def merge(n, m):
if n == 1:
return m + 1
elif n == 2:
return m + 2
elif n == 3:
return m + 3
return m + 4
t = TranslationContext()
a = t.buildannotator()
a.build_types(merge, [int, int])
rtyper = t.buildrtyper()
rtyper.specialize()
graph = tgraphof(t, merge)
assert len(list(graph.iterblocks())) == 8
remove_same_as(graph)
merge_if_blocks_once(graph)
assert len(graph.startblock.exits) == 4
interp = LLInterpreter(rtyper)
for i in range(1, 5):
res = interp.eval_graph(graph, [i, 1])
assert res == i + 1
def test_merge_several():
def merge(n, m):
r = -1
if n == 0:
if m == 0:
r = 0
elif m == 1:
r = 1
else:
r = 2
elif n == 1:
r = 4
else:
r = 6
return r
t = TranslationContext()
a = t.buildannotator()
a.build_types(merge, [int, int])
rtyper = t.buildrtyper()
rtyper.specialize()
graph = tgraphof(t, merge)
remove_same_as(graph)
merge_if_blocks(graph)
assert len(graph.startblock.exits) == 3
assert len(list(graph.iterblocks())) == 3
interp = LLInterpreter(rtyper)
for m in range(3):
res = interp.eval_graph(graph, [0, m])
assert res == m
res = interp.eval_graph(graph, [1, 0])
assert res == 4
res = interp.eval_graph(graph, [2, 0])
assert res == 6
def test_merge_with_or():
def merge(n):
if n == 5:
return 4
elif n == 14 or n == 2:
return 16
else:
return 7
do_test_merge(merge, [5, 6, 14, 2, 3, 123])
def test_dont_merge():
def merge(n, m):
r = -1
if n == 0:
r += m
if n == 1:
r += 2 * m
else:
r += 6
return r
t = TranslationContext()
a = t.buildannotator()
a.build_types(merge, [int, int])
rtyper = t.buildrtyper()
rtyper.specialize()
graph = tgraphof(t, merge)
remove_same_as(graph)
blocknum = len(list(graph.iterblocks()))
merge_if_blocks(graph)
assert blocknum == len(list(graph.iterblocks()))
def test_two_constants():
def fn():
r = range(10, 37, 4)
r.reverse()
return r[0]
t = TranslationContext()
a = t.buildannotator()
a.build_types(fn, [])
rtyper = t.buildrtyper()
rtyper.specialize()
backend_optimizations(t, merge_if_blocks=True)
graph = tgraphof(t, fn)
blocknum = len(list(graph.iterblocks()))
merge_if_blocks(graph)
assert blocknum == len(list(graph.iterblocks()))
def test_same_cases():
def fn(x):
if x == 42:
r = 1
elif x == 42:
r = 2
else:
r = 3
return r
t = TranslationContext()
a = t.buildannotator()
a.build_types(fn, [int])
rtyper = t.buildrtyper()
rtyper.specialize()
backend_optimizations(t, merge_if_blocks=True)
graph = tgraphof(t, fn)
assert len(graph.startblock.exits) == 2
interp = LLInterpreter(rtyper)
for i in [42, 43]:
expected = fn(i)
actual = interp.eval_graph(graph, [i])
assert actual == expected
def test_replace_exitswitch_by_constant_bug():
class X:
pass
def constant9():
x = X()
x.n = 3
x.n = 9
return x.n
def fn():
n = constant9()
if n == 1: return 5
elif n == 2: return 6
elif n == 3: return 8
elif n == 4: return -123
elif n == 5: return 12973
else: return n
t = TranslationContext()
a = t.buildannotator()
a.build_types(fn, [])
rtyper = t.buildrtyper()
rtyper.specialize()
graph = t.graphs[0]
remove_same_as(graph)
merge_if_blocks_once(graph)
from rpython.translator.backendopt import malloc, inline
inline.auto_inlining(t, 20)
malloc.remove_mallocs(t, t.graphs)
from rpython.translator import simplify
simplify.join_blocks(graph)
def test_switch_on_symbolic():
symb1 = CDefinedIntSymbolic("1", 1)
symb2 = CDefinedIntSymbolic("2", 2)
symb3 = CDefinedIntSymbolic("3", 3)
def fn(x):
res = 0
if x == symb1:
res += x + 1
elif x == symb2:
res += x + 2
elif x == symb3:
res += x + 3
res += 1
return res
t = TranslationContext()
a = t.buildannotator()
a.build_types(fn, [int])
rtyper = t.buildrtyper()
rtyper.specialize()
graph = t.graphs[0]
remove_same_as(graph)
res = merge_if_blocks_once(graph)
assert not res
checkgraph(graph)
| 27.788235 | 81 | 0.576348 | from rpython.translator.backendopt.merge_if_blocks import merge_if_blocks_once
from rpython.translator.backendopt.merge_if_blocks import merge_if_blocks
from rpython.translator.backendopt.all import backend_optimizations
from rpython.translator.translator import TranslationContext, graphof as tgraphof
from rpython.flowspace.model import Block, checkgraph
from rpython.translator.backendopt.removenoops import remove_same_as
from rpython.rtyper.llinterp import LLInterpreter
from rpython.rlib.rarithmetic import r_uint, r_ulonglong, r_longlong, r_int
from rpython.annotator.model import SomeChar, SomeUnicodeCodePoint
from rpython.rlib.objectmodel import CDefinedIntSymbolic
def do_test_merge(fn, testvalues):
t = TranslationContext()
a = t.buildannotator()
a.build_types(fn, [type(testvalues[0])])
rtyper = t.buildrtyper()
rtyper.specialize()
graph = tgraphof(t, fn)
assert len(list(graph.iterblocks())) == 4
remove_same_as(graph)
merge_if_blocks_once(graph)
assert len(graph.startblock.exits) == 4
assert len(list(graph.iterblocks())) == 2
interp = LLInterpreter(rtyper)
for i in testvalues:
expected = fn(i)
actual = interp.eval_graph(graph, [i])
assert actual == expected
def test_merge1():
def merge_int(n):
n += 1
if n == 1:
return 1
elif n == 2:
return 2
elif n == 3:
return 3
return 4
do_test_merge(merge_int, range(4))
do_test_merge(merge_int, [r_uint(i) for i in range(4)])
def merge_chr(n):
c = chr(n + 1)
if c == 'a':
return 'a'
elif c == 'b':
return 'b'
elif c == 'c':
return 'c'
return 'd'
do_test_merge(merge_chr, range(96, 101))
def merge_uchr(n):
c = unichr(n + 1)
if c == u'a':
return u'a'
elif c == u'b':
return u'b'
elif c == u'c':
return u'c'
return u'd'
do_test_merge(merge_uchr, range(96, 101))
def test_merge_passonvars():
def merge(n, m):
if n == 1:
return m + 1
elif n == 2:
return m + 2
elif n == 3:
return m + 3
return m + 4
t = TranslationContext()
a = t.buildannotator()
a.build_types(merge, [int, int])
rtyper = t.buildrtyper()
rtyper.specialize()
graph = tgraphof(t, merge)
assert len(list(graph.iterblocks())) == 8
remove_same_as(graph)
merge_if_blocks_once(graph)
assert len(graph.startblock.exits) == 4
interp = LLInterpreter(rtyper)
for i in range(1, 5):
res = interp.eval_graph(graph, [i, 1])
assert res == i + 1
def test_merge_several():
def merge(n, m):
r = -1
if n == 0:
if m == 0:
r = 0
elif m == 1:
r = 1
else:
r = 2
elif n == 1:
r = 4
else:
r = 6
return r
t = TranslationContext()
a = t.buildannotator()
a.build_types(merge, [int, int])
rtyper = t.buildrtyper()
rtyper.specialize()
graph = tgraphof(t, merge)
remove_same_as(graph)
merge_if_blocks(graph)
assert len(graph.startblock.exits) == 3
assert len(list(graph.iterblocks())) == 3
interp = LLInterpreter(rtyper)
for m in range(3):
res = interp.eval_graph(graph, [0, m])
assert res == m
res = interp.eval_graph(graph, [1, 0])
assert res == 4
res = interp.eval_graph(graph, [2, 0])
assert res == 6
def test_merge_with_or():
def merge(n):
if n == 5:
return 4
elif n == 14 or n == 2:
return 16
else:
return 7
do_test_merge(merge, [5, 6, 14, 2, 3, 123])
def test_dont_merge():
def merge(n, m):
r = -1
if n == 0:
r += m
if n == 1:
r += 2 * m
else:
r += 6
return r
t = TranslationContext()
a = t.buildannotator()
a.build_types(merge, [int, int])
rtyper = t.buildrtyper()
rtyper.specialize()
graph = tgraphof(t, merge)
remove_same_as(graph)
blocknum = len(list(graph.iterblocks()))
merge_if_blocks(graph)
assert blocknum == len(list(graph.iterblocks()))
def test_two_constants():
def fn():
r = range(10, 37, 4)
r.reverse()
return r[0]
t = TranslationContext()
a = t.buildannotator()
a.build_types(fn, [])
rtyper = t.buildrtyper()
rtyper.specialize()
backend_optimizations(t, merge_if_blocks=True)
graph = tgraphof(t, fn)
blocknum = len(list(graph.iterblocks()))
merge_if_blocks(graph)
assert blocknum == len(list(graph.iterblocks()))
def test_same_cases():
def fn(x):
if x == 42:
r = 1
elif x == 42:
r = 2
else:
r = 3
return r
t = TranslationContext()
a = t.buildannotator()
a.build_types(fn, [int])
rtyper = t.buildrtyper()
rtyper.specialize()
backend_optimizations(t, merge_if_blocks=True)
graph = tgraphof(t, fn)
assert len(graph.startblock.exits) == 2
interp = LLInterpreter(rtyper)
for i in [42, 43]:
expected = fn(i)
actual = interp.eval_graph(graph, [i])
assert actual == expected
def test_replace_exitswitch_by_constant_bug():
class X:
pass
def constant9():
x = X()
x.n = 3
x.n = 9
return x.n
def fn():
n = constant9()
if n == 1: return 5
elif n == 2: return 6
elif n == 3: return 8
elif n == 4: return -123
elif n == 5: return 12973
else: return n
t = TranslationContext()
a = t.buildannotator()
a.build_types(fn, [])
rtyper = t.buildrtyper()
rtyper.specialize()
graph = t.graphs[0]
remove_same_as(graph)
merge_if_blocks_once(graph)
from rpython.translator.backendopt import malloc, inline
inline.auto_inlining(t, 20)
malloc.remove_mallocs(t, t.graphs)
from rpython.translator import simplify
simplify.join_blocks(graph)
def test_switch_on_symbolic():
symb1 = CDefinedIntSymbolic("1", 1)
symb2 = CDefinedIntSymbolic("2", 2)
symb3 = CDefinedIntSymbolic("3", 3)
def fn(x):
res = 0
if x == symb1:
res += x + 1
elif x == symb2:
res += x + 2
elif x == symb3:
res += x + 3
res += 1
return res
t = TranslationContext()
a = t.buildannotator()
a.build_types(fn, [int])
rtyper = t.buildrtyper()
rtyper.specialize()
graph = t.graphs[0]
remove_same_as(graph)
res = merge_if_blocks_once(graph)
assert not res
checkgraph(graph)
| true | true |
f7313ffd9372f0396f475d8a1a68661916b500ec | 796 | py | Python | leetcode/Algorithms/107.BinaryTreeLevelOrderTraversalII/Solution.py | liupangzi/codekata | 079373707601198f79fb6215b876a4cbcab32ee9 | [
"MIT"
] | 58 | 2017-04-30T12:59:37.000Z | 2020-08-05T14:23:57.000Z | leetcode/Algorithms/107.BinaryTreeLevelOrderTraversalII/Solution.py | liupangzi/codekata | 079373707601198f79fb6215b876a4cbcab32ee9 | [
"MIT"
] | null | null | null | leetcode/Algorithms/107.BinaryTreeLevelOrderTraversalII/Solution.py | liupangzi/codekata | 079373707601198f79fb6215b876a4cbcab32ee9 | [
"MIT"
] | 6 | 2018-01-20T18:35:09.000Z | 2020-07-22T14:20:27.000Z | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
result = [[]]
self.helper(result, root, 0)
result.reverse()
return result
def helper(self, result, root, level):
if len(result) == level:
result.append([root.val])
else:
result[level].append(root.val)
if root.left:
self.helper(result, root.left, level + 1)
if root.right:
self.helper(result, root.right, level + 1)
| 24.121212 | 54 | 0.520101 |
class Solution(object):
def levelOrderBottom(self, root):
if not root:
return []
result = [[]]
self.helper(result, root, 0)
result.reverse()
return result
def helper(self, result, root, level):
if len(result) == level:
result.append([root.val])
else:
result[level].append(root.val)
if root.left:
self.helper(result, root.left, level + 1)
if root.right:
self.helper(result, root.right, level + 1)
| true | true |
f7314057a11eff7d520a32457c96935f97b70271 | 24,185 | py | Python | backend/lib/sites/facebook.py | kavish-p/youtube-search-dashboard | 2810b0d098699f11086868f9d754e0cb6194d6ff | [
"MIT"
] | 1 | 2021-03-26T05:19:48.000Z | 2021-03-26T05:19:48.000Z | chat_downloader/sites/facebook.py | lbmaian/chat-replay-downloader | 0f1b1326eec9fb45031d7fd58e0a4a9dd2297d5d | [
"MIT"
] | null | null | null | chat_downloader/sites/facebook.py | lbmaian/chat-replay-downloader | 0f1b1326eec9fb45031d7fd58e0a4a9dd2297d5d | [
"MIT"
] | null | null | null | import json
from json.decoder import JSONDecodeError
import xml.etree.ElementTree as ET
import isodate
import re
from .common import (
Chat,
BaseChatDownloader,
Remapper as r
)
from requests.exceptions import RequestException
from ..utils import (
remove_prefixes,
multi_get,
try_get_first_value,
try_get,
seconds_to_time,
camel_case_split,
ensure_seconds,
attempts,
get_title_of_webpage,
log
)
class FacebookChatDownloader(BaseChatDownloader):
_FB_HOMEPAGE = 'https://www.facebook.com'
_FB_HEADERS = {
'Content-Type': 'application/x-www-form-urlencoded',
'Referer': _FB_HOMEPAGE,
'Accept-Language': 'en-US,en;',
}
_INITIAL_DATR_REGEX = r'_js_datr\",\"([^\"]+)'
_INITIAL_LSD_REGEX = r'<input.*?name=\"lsd\".*?value=\"([^\"]+)[^>]*>'
def __init__(self, **kwargs):
super().__init__(**kwargs)
# update headers for all subsequent FB requests
self.update_session_headers(self._FB_HEADERS)
initial_data = self._session_get(
self._FB_HOMEPAGE,
headers=self._FB_HEADERS, allow_redirects=False).text
datr = re.search(self._INITIAL_DATR_REGEX, initial_data)
if datr:
datr = datr.group(1)
else:
print('unable to get datr cookie')
raise Exception # TODO
sb = self.get_cookie_value('sb')
fr = self.get_cookie_value('fr')
# print('sb:', sb, flush=True)
# print('fr:', fr, flush=True)
# print('datr:', datr, flush=True)
lsd_info = re.search(self._INITIAL_LSD_REGEX, initial_data)
if not lsd_info:
print('no lsd info')
raise Exception # TODO
lsd = lsd_info.group(1)
# print('lsd:', lsd, flush=True)
request_headers = {
# TODO sb and fr unnecessary?
# wd=1122x969;
'Cookie': 'sb={}; fr={}; datr={};'.format(sb, fr, datr)
}
self.update_session_headers(request_headers)
self.data = {
# TODO need things like jazoest? (and other stuff from hidden elements/html)
'__a': 1, # TODO needed?
'lsd': lsd,
}
_NAME = 'facebook.com'
# Regex provided by youtube-dl
_VALID_URL = r'''(?x)
(?:
https?://
(?:[\w-]+\.)?(?:facebook\.com)/
(?:[^#]*?\#!/)?
(?:[^/]+/videos/(?:[^/]+/)?)
)
(?P<id>[0-9]+)
'''
_TESTS = [
]
_VIDEO_PAGE_TAHOE_TEMPLATE = _FB_HOMEPAGE + \
'/video/tahoe/async/{}/?chain=true&isvideo=true&payloadtype=primary'
def _parse_fb_json(self, response):
text_to_parse = remove_prefixes(response.text, 'for (;;);')
return json.loads(text_to_parse)
_VOD_COMMENTS_API = _FB_HOMEPAGE + '/videos/vodcomments/'
_GRAPH_API = _FB_HOMEPAGE + '/api/graphql/'
_VIDEO_URL_FORMAT = _FB_HOMEPAGE + '/video.php?v={}'
# _VIDEO_TITLE_REGEX = r'<meta\s+name=["\']description["\']\s+content=["\'](.*?)["\']\s*/>'
def _attempt_fb_retrieve(self, url, max_attempts, retry_timeout, fb_json=False, **post_kwargs):
for attempt_number in attempts(max_attempts):
try:
response = self._session_post(url, **post_kwargs)
if fb_json:
return self._parse_fb_json(response)
else:
return response.json()
except JSONDecodeError as e:
self.retry(attempt_number, max_attempts, e, retry_timeout,
text='Unable to parse JSON: `{}`'.format(response.text))
except RequestException as e:
self.retry(attempt_number, max_attempts, e, retry_timeout)
def _get_initial_info(self, video_id, params):
info = {}
max_attempts = params.get('max_attempts')
retry_timeout = params.get('retry_timeout')
# TODO remove duplication - many similar methods
json_data = self._attempt_fb_retrieve(
self._VIDEO_PAGE_TAHOE_TEMPLATE.format(video_id),
max_attempts,
retry_timeout,
True,
headers=self._FB_HEADERS, data=self.data
)
# print(json_data)
markup = multi_get(json_data, 'payload', 'video', 'markup', '__html')
video_markup = ET.fromstring(markup)
tags = [x.text for x in video_markup.findall(
'.//span[@class="_50f7"]')]
if len(tags) >= 2:
info['title'] = tags[0]
info['username'] = tags[1]
else:
video_page_url = self._VIDEO_URL_FORMAT.format(video_id)
for attempt_number in attempts(max_attempts):
try:
html = self._session_get(video_page_url).text
match = get_title_of_webpage(html)
if match:
title_info = match.split(' - ', 1)
if len(title_info) == 2:
info['username'] = title_info[0]
info['title'] = title_info[1]
break
except RequestException as e:
self.retry(attempt_number, max_attempts, e, retry_timeout)
instances = multi_get(json_data, 'jsmods', 'instances')
video_data = {}
for item in instances:
if try_get(item, lambda x: x[1][0]) == 'VideoConfig':
video_item = item[2][0]
if video_item.get('video_id'):
video_data = video_item['videoData'][0]
# print(video_data)
break
# print(video_data)
if not video_data:
print('unable to get video data')
raise Exception
dash_manifest = video_data.get('dash_manifest')
if dash_manifest: # when not live, this returns
dash_manifest_xml = ET.fromstring(dash_manifest)
info['duration'] = isodate.parse_duration(
dash_manifest_xml.attrib['mediaPresentationDuration']).total_seconds()
info['is_live'] = video_data['is_live_stream']
return info
@staticmethod
def _parse_feedback(feedback):
new_feedback = {}
edges = multi_get(feedback, 'top_reactions', 'edges')
if not edges:
return new_feedback
new_feedback['reaction_types'] = []
for edge in edges:
node = edge.get('node')
reaction_item = {
'key': node.get('key'),
'id': node.get('id'),
'name': node.get('reaction_type'),
'count': edge.get('reaction_count')
}
new_feedback['reaction_types'].append(reaction_item)
new_feedback['total_count'] = multi_get(feedback, 'reactors', 'count')
new_feedback['total_count_reduced'] = multi_get(
feedback, 'reactors', 'count_reduced')
return new_feedback
@staticmethod
def get_text(item):
return item.get('text') if item else None
@staticmethod
def parse_image(item):
return BaseChatDownloader.create_image(item.get('uri'), item.get('width'), item.get('height'))
@staticmethod
def get_uri(item):
return item.get('uri')
@staticmethod
def _parse_attachment_info(original_item):
item = {}
if isinstance(original_item, (list, tuple)) and len(original_item) > 0:
original_item = original_item[0]
if not original_item:
return item
for key in original_item:
BaseChatDownloader.remap(
item, FacebookChatDownloader._TARGET_MEDIA_REMAPPING, key, original_item[key])
# VideoTipJarPayment
quantity = item.get('quantity')
if quantity:
item['text'] = 'Sent {} Star{}'.format(
quantity, 's' if quantity != 1 else '')
# For photos:
blurred_image = item.pop('blurred_image', None)
massive_image = item.pop('massive_image', None)
if blurred_image and massive_image:
item['text'] = BaseChatDownloader.create_image(
blurred_image,
massive_image.get('width'),
massive_image.get('height')
)
# style_infos
donation_comment_text = item.pop('donation_comment_text', None)
if donation_comment_text:
entity = try_get(donation_comment_text,
lambda x: x['ranges'][0]['entity']) or {}
for key in entity:
BaseChatDownloader.remap(
item, FacebookChatDownloader._TARGET_MEDIA_REMAPPING, key, entity[key])
item['text'] = donation_comment_text.get('text')
# DEBUGGING
original_type_name = original_item.get('__typename')
if original_type_name not in FacebookChatDownloader._KNOWN_ATTACHMENT_TYPES:
print('debug')
print('unknown attachment type:', original_type_name)
print(original_item)
print(item)
input()
return item
@staticmethod
def _parse_target(media):
item = {}
return item
@staticmethod
def _parse_author_badges(item):
keys = (('badge_asset', 'small'), ('information_asset', 'colour'))
icons = list(map(lambda x: BaseChatDownloader.create_image(
FacebookChatDownloader._FB_HOMEPAGE + item.get(x[0]), 24, 24, x[1]), keys))
icons.append(BaseChatDownloader.create_image(
item.get('multiple_badge_asset'), 36, 36, 'large'))
return {
'title': item.get('text'),
'alternative_title': item.get('information_title'),
'description': item.get('information_description'),
'icons': icons,
# badge_asset
# multiple_badge_asset
# information_asset
'icon_name': item.get('identity_badge_type')
}
_ATTACHMENT_REMAPPING = {
'url': 'url', # facebook redirect url,
'source': r('source', get_text),
'title_with_entities': r('title', get_text),
'target': r('target', _parse_attachment_info),
'media': r('media', _parse_attachment_info),
'style_infos': r('style_infos', _parse_attachment_info),
'attachment_text': r('text', get_text),
}
_IGNORE_ATTACHMENT_KEYS = [
'tracking',
'action_links'
]
_KNOWN_ATTACHMENT_KEYS = set(
list(_ATTACHMENT_REMAPPING.keys()) + _IGNORE_ATTACHMENT_KEYS)
@staticmethod
def _parse_attachment_styles(item):
parsed = {}
attachment = multi_get(item, 'style_type_renderer', 'attachment')
if not attachment:
# TODO debug log
print('NO ATTACHMENT')
print(item)
return parsed
# set texts:
for key in attachment:
BaseChatDownloader.remap(
parsed, FacebookChatDownloader._ATTACHMENT_REMAPPING, key, attachment[key])
for key in ('target', 'media', 'style_infos'):
if parsed.get(key) == {}:
parsed.pop(key)
missing_keys = attachment.keys() - FacebookChatDownloader._KNOWN_ATTACHMENT_KEYS
if missing_keys:
print('MISSING ATTACHMENT KEYS:', missing_keys)
print(item)
print(parsed)
input()
return parsed
_TARGET_MEDIA_REMAPPING = {
'id': 'id',
'__typename': r('type', camel_case_split),
'fallback_image': r('image', parse_image),
'is_playable': 'is_playable',
'url': 'url',
'mobileUrl': 'mobile_url',
# Sticker
'pack': 'pack',
'label': 'label',
'image': r('image', parse_image),
# VideoTipJarPayment
'stars_image_on_star_quantity': 'icon',
'spark_quantity': 'quantity',
# Page
'name': 'name',
'category_name': 'category',
'address': 'address',
'overall_star_rating': 'overall_star_rating',
'profile_picture': r('profile_picture', get_uri),
# Photo
'accessibility_caption': 'accessibility_caption',
'blurred_image': r('blurred_image', get_uri),
'massive_image': 'massive_image',
# FundraiserForStoryDonationAttachmentStyleInfo
'donation_comment_text': 'donation_comment_text'
}
_KNOWN_ATTACHMENT_TYPES = [
'Sticker',
'VideoTipJarPayment',
'Page',
'Group',
'ProfilePicAttachmentMedia',
'User',
'Photo',
'ExternalUrl',
'GenericAttachmentMedia',
'ChatCommandResult',
'CommentMessageInfo',
'FundraiserForStoryDonationAttachmentStyleInfo'
]
_REMAPPING = {
'id': 'message_id',
'community_moderation_state': 'community_moderation_state',
# attachments
'author': 'author',
'feedback': r('reactions', _parse_feedback),
'created_time': r('timestamp', lambda x: x * 1000000),
'upvote_downvote_total': 'upvote_downvote_total',
'is_author_banned_by_content_owner': 'is_author_banned',
'is_author_original_poster': 'is_author_original_poster',
'is_author_bot': 'is_author_bot',
'is_author_non_coworker': 'is_author_non_coworker',
# if banned, ban_action?
'comment_parent': 'comment_parent',
'edit_history': r('number_of_edits', lambda x: x.get('count')),
'timestamp_in_video': 'time_in_seconds',
'written_while_video_was_live': 'written_while_video_was_live',
'translatability_for_viewer': r('message_dialect', lambda x: x.get('source_dialect_name')),
'url': 'message_url',
'body': r('message', get_text),
'identity_badges_web': r('author_badges', lambda x: list(map(FacebookChatDownloader._parse_author_badges, x))),
'attachments': r('attachments', lambda x: list(map(FacebookChatDownloader._parse_attachment_styles, x)))
}
_AUTHOR_REMAPPING = {
'id': 'id',
'name': 'name',
'__typename': r('type', camel_case_split),
'url': 'url',
'is_verified': 'is_verified',
'gender': r('gender', lambda x: x.lower()),
'short_name': 'short_name'
}
@ staticmethod
def _parse_live_stream_node(node):
# if info is None:
# info = {}
info = {}
for key in node:
BaseChatDownloader.remap(
info, FacebookChatDownloader._REMAPPING, key, node[key])
author_info = info.pop('author', {})
BaseChatDownloader.move_to_dict(info, 'author', create_when_empty=True)
for key in author_info:
BaseChatDownloader.remap(
info['author'], FacebookChatDownloader._AUTHOR_REMAPPING, key, author_info[key])
if 'profile_picture_depth_0' in author_info:
info['author']['images'] = []
for size in ((0, 32), (1, 24)):
url = multi_get(
author_info, 'profile_picture_depth_{}'.format(size[0]), 'uri')
info['author']['images'].append(
BaseChatDownloader.create_image(url, size[1], size[1]))
# author_badges = info.pop('author_badges', None)
# if author_badges:
# info['author']['badges'] = author_badges
in_reply_to = info.pop('comment_parent', None)
if isinstance(in_reply_to, dict) and in_reply_to:
info['in_reply_to'] = FacebookChatDownloader._parse_live_stream_node(
in_reply_to)
time_in_seconds = info.get('time_in_seconds')
if time_in_seconds is not None:
info['time_text'] = seconds_to_time(time_in_seconds)
message = info.get('message')
if message:
info['message'] = message
info['message_type'] = 'text_message'
else:
info.pop('message', None) # remove if empty
# remove the following if empty:
if info.get('reactions') == {}: # no reactions
info.pop('reactions')
if info.get('attachments') == []:
info.pop('attachments')
# print("AAAAAAAA")
# print(info.get('attachments'), node)
return info
def _get_live_chat_messages_by_video_id(self, video_id, params):
max_attempts = params.get('max_attempts')
retry_timeout = params.get('retry_timeout')
buffer_size = 25 # max num comments returned by api call
# cursor = ''
variables = {
'videoID': video_id
}
data = {
'variables': json.dumps(variables),
'doc_id': '4889623951078943', # specifies what API call this is?
# 'cursor' : cursor
# &first=12&after=<end_cursor>
}
data.update(self.data)
# p = (), params=p
first_try = True
last_ids = []
while True:
json_data = self._attempt_fb_retrieve(
self._GRAPH_API,
max_attempts,
retry_timeout,
headers=self._FB_HEADERS, data=data
)
feedback = multi_get(json_data, 'data', 'video', 'feedback') or {}
if not feedback:
print('no feedback') # TODO debug
print(json_data, flush=True)
continue
top_level_comments = multi_get(
json_data, 'data', 'video', 'feedback', 'top_level_comments')
edges = top_level_comments.get('edges')[::-1] # reverse order
errors = json_data.get('errors')
if errors:
# TODO will usually resume getting chat..
# maybe add timeout?
print('ERRORS DETECTED')
print(errors)
continue
# TODO - get pagination working
# page_info = top_level_comments.get('page_info')
# after = page_info.get('end_cursor')
num_to_add = 0
for edge in edges:
node = edge.get('node')
if not node:
# TODO debug
print('no node found in edge')
print(edge)
continue
comment_id = node.get('id')
# remove items that have already been parsed
if comment_id in last_ids:
# print('=', end='', flush=True)
continue
last_ids.append(comment_id)
last_ids = last_ids[-buffer_size:] # force x items
if not node:
# TODO debug
print('no node', edge)
continue
parsed_node = FacebookChatDownloader._parse_live_stream_node(
node)
# TODO determine whether to add or not
num_to_add += 1
yield parsed_node
# got 25 items, and this isn't the first one
if num_to_add >= buffer_size and not first_try:
log(
'warning',
'Messages may be coming in faster than requests are being made.'
)
if not top_level_comments:
print('err2')
print(json_data)
if first_try:
first_try = False
def _get_chat_replay_messages_by_video_id(self, video_id, max_duration, params):
max_attempts = params.get('max_attempts')
retry_timeout = params.get('retry_timeout')
# useful tool (convert curl to python request)
# https://curl.trillworks.com/
# timeout_duration = 10 # TODO make this modifiable
initial_request_params = (
('eft_id', video_id),
('target_ufi_instance_id', 'u_2_1'),
# ('should_backfill', 'false'), # used when seeking? - # TODO true on first try?
)
time_increment = 60 # Facebook gets messages by the minute
# TODO make this modifiable
start_time = ensure_seconds(
params.get('start_time'), 0)
end_time = ensure_seconds(
params.get('end_time'), float('inf'))
next_start_time = max(start_time, 0)
end_time = min(end_time, max_duration)
# print(next_start_time, end_time, type(next_start_time), type(end_time))
# return
# total = []
while True:
next_end_time = min(next_start_time + time_increment, end_time)
times = (('start_time', next_start_time),
('end_time', next_end_time))
# print(times, flush=True)
request_params = initial_request_params + times
json_data = self._attempt_fb_retrieve(
self._VOD_COMMENTS_API,
max_attempts,
retry_timeout,
True,
headers=self._FB_HEADERS, params=request_params, data=self.data
)
payloads = multi_get(json_data, 'payload', 'ufipayloads')
if not payloads:
continue
# TODO debug
# print('no comments between',next_start_time, next_end_time, flush=True)
# print('err1')
# print(json_data)
next_start_time = next_end_time
if next_start_time >= end_time:
print('end')
return
for payload in payloads:
time_offset = payload.get('timeoffset')
# print(test)
ufipayload = payload.get('ufipayload')
if not ufipayload:
print('no ufipayload', payload)
continue
# ['comments'][0]['body']['text']
comment = try_get(ufipayload, lambda x: x['comments'][0])
if not comment:
# TODO debug
continue
# pinned_comments = ufipayload.get('pinnedcomments')
profile = try_get_first_value(ufipayload['profiles'])
text = comment['body']['text'] # safe_convert_text()
temp = {
'author': {
'name': profile.get('name')
},
'time_in_seconds': time_offset,
'time_text': seconds_to_time(time_offset),
'message': text
}
yield temp
def get_chat_by_video_id(self, video_id, params):
initial_info = self._get_initial_info(video_id, params)
start_time = params.get('start_time')
end_time = params.get('end_time')
is_live = initial_info.get('is_live')
# if start or end time specified, use chat replay...
# The tool works for both active and finished live streams.
# if start/end time are specified, vods will be prioritised
# if is live stream and no start/end time specified
if is_live and not start_time and not end_time:
generator = self._get_live_chat_messages_by_video_id(
video_id, params)
else:
max_duration = initial_info.get('duration', float('inf'))
generator = self._get_chat_replay_messages_by_video_id(
video_id, max_duration, params)
return Chat(
generator,
title=initial_info.get('title'),
duration=initial_info.get('duration'),
is_live=is_live,
author=initial_info.get('author'),
)
def get_chat(self, **kwargs):
url = kwargs.get('url')
match = re.search(self._VALID_URL, url)
if match:
if match.group('id'): # normal youtube video
return self.get_chat_by_video_id(match.group('id'), kwargs)
else: # TODO add profile, etc.
pass
| 31.697248 | 119 | 0.557081 | import json
from json.decoder import JSONDecodeError
import xml.etree.ElementTree as ET
import isodate
import re
from .common import (
Chat,
BaseChatDownloader,
Remapper as r
)
from requests.exceptions import RequestException
from ..utils import (
remove_prefixes,
multi_get,
try_get_first_value,
try_get,
seconds_to_time,
camel_case_split,
ensure_seconds,
attempts,
get_title_of_webpage,
log
)
class FacebookChatDownloader(BaseChatDownloader):
_FB_HOMEPAGE = 'https://www.facebook.com'
_FB_HEADERS = {
'Content-Type': 'application/x-www-form-urlencoded',
'Referer': _FB_HOMEPAGE,
'Accept-Language': 'en-US,en;',
}
_INITIAL_DATR_REGEX = r'_js_datr\",\"([^\"]+)'
_INITIAL_LSD_REGEX = r'<input.*?name=\"lsd\".*?value=\"([^\"]+)[^>]*>'
def __init__(self, **kwargs):
super().__init__(**kwargs)
# update headers for all subsequent FB requests
self.update_session_headers(self._FB_HEADERS)
initial_data = self._session_get(
self._FB_HOMEPAGE,
headers=self._FB_HEADERS, allow_redirects=False).text
datr = re.search(self._INITIAL_DATR_REGEX, initial_data)
if datr:
datr = datr.group(1)
else:
print('unable to get datr cookie')
raise Exception # TODO
sb = self.get_cookie_value('sb')
fr = self.get_cookie_value('fr')
# print('sb:', sb, flush=True)
# print('fr:', fr, flush=True)
# print('datr:', datr, flush=True)
lsd_info = re.search(self._INITIAL_LSD_REGEX, initial_data)
if not lsd_info:
print('no lsd info')
raise Exception # TODO
lsd = lsd_info.group(1)
# print('lsd:', lsd, flush=True)
request_headers = {
# TODO sb and fr unnecessary?
# wd=1122x969;
'Cookie': 'sb={}; fr={}; datr={};'.format(sb, fr, datr)
}
self.update_session_headers(request_headers)
self.data = {
# TODO need things like jazoest? (and other stuff from hidden elements/html)
'__a': 1, # TODO needed?
'lsd': lsd,
}
_NAME = 'facebook.com'
# Regex provided by youtube-dl
_VALID_URL = r'''(?x)
(?:
https?://
(?:[\w-]+\.)?(?:facebook\.com)/
(?:[^#]*?\#!/)?
(?:[^/]+/videos/(?:[^/]+/)?)
)
(?P<id>[0-9]+)
'''
_TESTS = [
]
_VIDEO_PAGE_TAHOE_TEMPLATE = _FB_HOMEPAGE + \
'/video/tahoe/async/{}/?chain=true&isvideo=true&payloadtype=primary'
def _parse_fb_json(self, response):
text_to_parse = remove_prefixes(response.text, 'for (;;);')
return json.loads(text_to_parse)
_VOD_COMMENTS_API = _FB_HOMEPAGE + '/videos/vodcomments/'
_GRAPH_API = _FB_HOMEPAGE + '/api/graphql/'
_VIDEO_URL_FORMAT = _FB_HOMEPAGE + '/video.php?v={}'
# _VIDEO_TITLE_REGEX = r'<meta\s+name=["\']description["\']\s+content=["\'](.*?)["\']\s*/>'
def _attempt_fb_retrieve(self, url, max_attempts, retry_timeout, fb_json=False, **post_kwargs):
for attempt_number in attempts(max_attempts):
try:
response = self._session_post(url, **post_kwargs)
if fb_json:
return self._parse_fb_json(response)
else:
return response.json()
except JSONDecodeError as e:
self.retry(attempt_number, max_attempts, e, retry_timeout,
text='Unable to parse JSON: `{}`'.format(response.text))
except RequestException as e:
self.retry(attempt_number, max_attempts, e, retry_timeout)
def _get_initial_info(self, video_id, params):
info = {}
max_attempts = params.get('max_attempts')
retry_timeout = params.get('retry_timeout')
# TODO remove duplication - many similar methods
json_data = self._attempt_fb_retrieve(
self._VIDEO_PAGE_TAHOE_TEMPLATE.format(video_id),
max_attempts,
retry_timeout,
True,
headers=self._FB_HEADERS, data=self.data
)
# print(json_data)
markup = multi_get(json_data, 'payload', 'video', 'markup', '__html')
video_markup = ET.fromstring(markup)
tags = [x.text for x in video_markup.findall(
'.//span[@class="_50f7"]')]
if len(tags) >= 2:
info['title'] = tags[0]
info['username'] = tags[1]
else:
video_page_url = self._VIDEO_URL_FORMAT.format(video_id)
for attempt_number in attempts(max_attempts):
try:
html = self._session_get(video_page_url).text
match = get_title_of_webpage(html)
if match:
title_info = match.split(' - ', 1)
if len(title_info) == 2:
info['username'] = title_info[0]
info['title'] = title_info[1]
break
except RequestException as e:
self.retry(attempt_number, max_attempts, e, retry_timeout)
instances = multi_get(json_data, 'jsmods', 'instances')
video_data = {}
for item in instances:
if try_get(item, lambda x: x[1][0]) == 'VideoConfig':
video_item = item[2][0]
if video_item.get('video_id'):
video_data = video_item['videoData'][0]
# print(video_data)
break
# print(video_data)
if not video_data:
print('unable to get video data')
raise Exception
dash_manifest = video_data.get('dash_manifest')
if dash_manifest: # when not live, this returns
dash_manifest_xml = ET.fromstring(dash_manifest)
info['duration'] = isodate.parse_duration(
dash_manifest_xml.attrib['mediaPresentationDuration']).total_seconds()
info['is_live'] = video_data['is_live_stream']
return info
@staticmethod
def _parse_feedback(feedback):
new_feedback = {}
edges = multi_get(feedback, 'top_reactions', 'edges')
if not edges:
return new_feedback
new_feedback['reaction_types'] = []
for edge in edges:
node = edge.get('node')
reaction_item = {
'key': node.get('key'),
'id': node.get('id'),
'name': node.get('reaction_type'),
'count': edge.get('reaction_count')
}
new_feedback['reaction_types'].append(reaction_item)
new_feedback['total_count'] = multi_get(feedback, 'reactors', 'count')
new_feedback['total_count_reduced'] = multi_get(
feedback, 'reactors', 'count_reduced')
return new_feedback
@staticmethod
def get_text(item):
return item.get('text') if item else None
@staticmethod
def parse_image(item):
return BaseChatDownloader.create_image(item.get('uri'), item.get('width'), item.get('height'))
@staticmethod
def get_uri(item):
return item.get('uri')
@staticmethod
def _parse_attachment_info(original_item):
item = {}
if isinstance(original_item, (list, tuple)) and len(original_item) > 0:
original_item = original_item[0]
if not original_item:
return item
for key in original_item:
BaseChatDownloader.remap(
item, FacebookChatDownloader._TARGET_MEDIA_REMAPPING, key, original_item[key])
# VideoTipJarPayment
quantity = item.get('quantity')
if quantity:
item['text'] = 'Sent {} Star{}'.format(
quantity, 's' if quantity != 1 else '')
# For photos:
blurred_image = item.pop('blurred_image', None)
massive_image = item.pop('massive_image', None)
if blurred_image and massive_image:
item['text'] = BaseChatDownloader.create_image(
blurred_image,
massive_image.get('width'),
massive_image.get('height')
)
# style_infos
donation_comment_text = item.pop('donation_comment_text', None)
if donation_comment_text:
entity = try_get(donation_comment_text,
lambda x: x['ranges'][0]['entity']) or {}
for key in entity:
BaseChatDownloader.remap(
item, FacebookChatDownloader._TARGET_MEDIA_REMAPPING, key, entity[key])
item['text'] = donation_comment_text.get('text')
# DEBUGGING
original_type_name = original_item.get('__typename')
if original_type_name not in FacebookChatDownloader._KNOWN_ATTACHMENT_TYPES:
print('debug')
print('unknown attachment type:', original_type_name)
print(original_item)
print(item)
input()
return item
@staticmethod
def _parse_target(media):
item = {}
return item
@staticmethod
def _parse_author_badges(item):
keys = (('badge_asset', 'small'), ('information_asset', 'colour'))
icons = list(map(lambda x: BaseChatDownloader.create_image(
FacebookChatDownloader._FB_HOMEPAGE + item.get(x[0]), 24, 24, x[1]), keys))
icons.append(BaseChatDownloader.create_image(
item.get('multiple_badge_asset'), 36, 36, 'large'))
return {
'title': item.get('text'),
'alternative_title': item.get('information_title'),
'description': item.get('information_description'),
'icons': icons,
# badge_asset
# multiple_badge_asset
# information_asset
'icon_name': item.get('identity_badge_type')
}
_ATTACHMENT_REMAPPING = {
'url': 'url', # facebook redirect url,
'source': r('source', get_text),
'title_with_entities': r('title', get_text),
'target': r('target', _parse_attachment_info),
'media': r('media', _parse_attachment_info),
'style_infos': r('style_infos', _parse_attachment_info),
'attachment_text': r('text', get_text),
}
_IGNORE_ATTACHMENT_KEYS = [
'tracking',
'action_links'
]
_KNOWN_ATTACHMENT_KEYS = set(
list(_ATTACHMENT_REMAPPING.keys()) + _IGNORE_ATTACHMENT_KEYS)
@staticmethod
def _parse_attachment_styles(item):
parsed = {}
attachment = multi_get(item, 'style_type_renderer', 'attachment')
if not attachment:
# TODO debug log
print('NO ATTACHMENT')
print(item)
return parsed
# set texts:
for key in attachment:
BaseChatDownloader.remap(
parsed, FacebookChatDownloader._ATTACHMENT_REMAPPING, key, attachment[key])
for key in ('target', 'media', 'style_infos'):
if parsed.get(key) == {}:
parsed.pop(key)
missing_keys = attachment.keys() - FacebookChatDownloader._KNOWN_ATTACHMENT_KEYS
if missing_keys:
print('MISSING ATTACHMENT KEYS:', missing_keys)
print(item)
print(parsed)
input()
return parsed
_TARGET_MEDIA_REMAPPING = {
'id': 'id',
'__typename': r('type', camel_case_split),
'fallback_image': r('image', parse_image),
'is_playable': 'is_playable',
'url': 'url',
'mobileUrl': 'mobile_url',
# Sticker
'pack': 'pack',
'label': 'label',
'image': r('image', parse_image),
# VideoTipJarPayment
'stars_image_on_star_quantity': 'icon',
'spark_quantity': 'quantity',
# Page
'name': 'name',
'category_name': 'category',
'address': 'address',
'overall_star_rating': 'overall_star_rating',
'profile_picture': r('profile_picture', get_uri),
# Photo
'accessibility_caption': 'accessibility_caption',
'blurred_image': r('blurred_image', get_uri),
'massive_image': 'massive_image',
# FundraiserForStoryDonationAttachmentStyleInfo
'donation_comment_text': 'donation_comment_text'
}
_KNOWN_ATTACHMENT_TYPES = [
'Sticker',
'VideoTipJarPayment',
'Page',
'Group',
'ProfilePicAttachmentMedia',
'User',
'Photo',
'ExternalUrl',
'GenericAttachmentMedia',
'ChatCommandResult',
'CommentMessageInfo',
'FundraiserForStoryDonationAttachmentStyleInfo'
]
_REMAPPING = {
'id': 'message_id',
'community_moderation_state': 'community_moderation_state',
# attachments
'author': 'author',
'feedback': r('reactions', _parse_feedback),
'created_time': r('timestamp', lambda x: x * 1000000),
'upvote_downvote_total': 'upvote_downvote_total',
'is_author_banned_by_content_owner': 'is_author_banned',
'is_author_original_poster': 'is_author_original_poster',
'is_author_bot': 'is_author_bot',
'is_author_non_coworker': 'is_author_non_coworker',
# if banned, ban_action?
'comment_parent': 'comment_parent',
'edit_history': r('number_of_edits', lambda x: x.get('count')),
'timestamp_in_video': 'time_in_seconds',
'written_while_video_was_live': 'written_while_video_was_live',
'translatability_for_viewer': r('message_dialect', lambda x: x.get('source_dialect_name')),
'url': 'message_url',
'body': r('message', get_text),
'identity_badges_web': r('author_badges', lambda x: list(map(FacebookChatDownloader._parse_author_badges, x))),
'attachments': r('attachments', lambda x: list(map(FacebookChatDownloader._parse_attachment_styles, x)))
}
_AUTHOR_REMAPPING = {
'id': 'id',
'name': 'name',
'__typename': r('type', camel_case_split),
'url': 'url',
'is_verified': 'is_verified',
'gender': r('gender', lambda x: x.lower()),
'short_name': 'short_name'
}
@ staticmethod
def _parse_live_stream_node(node):
# if info is None:
# info = {}
info = {}
for key in node:
BaseChatDownloader.remap(
info, FacebookChatDownloader._REMAPPING, key, node[key])
author_info = info.pop('author', {})
BaseChatDownloader.move_to_dict(info, 'author', create_when_empty=True)
for key in author_info:
BaseChatDownloader.remap(
info['author'], FacebookChatDownloader._AUTHOR_REMAPPING, key, author_info[key])
if 'profile_picture_depth_0' in author_info:
info['author']['images'] = []
for size in ((0, 32), (1, 24)):
url = multi_get(
author_info, 'profile_picture_depth_{}'.format(size[0]), 'uri')
info['author']['images'].append(
BaseChatDownloader.create_image(url, size[1], size[1]))
# author_badges = info.pop('author_badges', None)
# if author_badges:
# info['author']['badges'] = author_badges
in_reply_to = info.pop('comment_parent', None)
if isinstance(in_reply_to, dict) and in_reply_to:
info['in_reply_to'] = FacebookChatDownloader._parse_live_stream_node(
in_reply_to)
time_in_seconds = info.get('time_in_seconds')
if time_in_seconds is not None:
info['time_text'] = seconds_to_time(time_in_seconds)
message = info.get('message')
if message:
info['message'] = message
info['message_type'] = 'text_message'
else:
info.pop('message', None) # remove if empty
# remove the following if empty:
if info.get('reactions') == {}: # no reactions
info.pop('reactions')
if info.get('attachments') == []:
info.pop('attachments')
# print("AAAAAAAA")
# print(info.get('attachments'), node)
return info
def _get_live_chat_messages_by_video_id(self, video_id, params):
max_attempts = params.get('max_attempts')
retry_timeout = params.get('retry_timeout')
buffer_size = 25 # max num comments returned by api call
# cursor = ''
variables = {
'videoID': video_id
}
data = {
'variables': json.dumps(variables),
'doc_id': '4889623951078943', # specifies what API call this is?
# 'cursor' : cursor
# &first=12&after=<end_cursor>
}
data.update(self.data)
# p = (), params=p
first_try = True
last_ids = []
while True:
json_data = self._attempt_fb_retrieve(
self._GRAPH_API,
max_attempts,
retry_timeout,
headers=self._FB_HEADERS, data=data
)
feedback = multi_get(json_data, 'data', 'video', 'feedback') or {}
if not feedback:
print('no feedback') # TODO debug
print(json_data, flush=True)
continue
top_level_comments = multi_get(
json_data, 'data', 'video', 'feedback', 'top_level_comments')
edges = top_level_comments.get('edges')[::-1] # reverse order
errors = json_data.get('errors')
if errors:
# TODO will usually resume getting chat..
# maybe add timeout?
print('ERRORS DETECTED')
print(errors)
continue
# TODO - get pagination working
# page_info = top_level_comments.get('page_info')
# after = page_info.get('end_cursor')
num_to_add = 0
for edge in edges:
node = edge.get('node')
if not node:
# TODO debug
print('no node found in edge')
print(edge)
continue
comment_id = node.get('id')
# remove items that have already been parsed
if comment_id in last_ids:
# print('=', end='', flush=True)
continue
last_ids.append(comment_id)
last_ids = last_ids[-buffer_size:] # force x items
if not node:
# TODO debug
print('no node', edge)
continue
parsed_node = FacebookChatDownloader._parse_live_stream_node(
node)
# TODO determine whether to add or not
num_to_add += 1
yield parsed_node
# got 25 items, and this isn't the first one
if num_to_add >= buffer_size and not first_try:
log(
'warning',
'Messages may be coming in faster than requests are being made.'
)
if not top_level_comments:
print('err2')
print(json_data)
if first_try:
first_try = False
def _get_chat_replay_messages_by_video_id(self, video_id, max_duration, params):
max_attempts = params.get('max_attempts')
retry_timeout = params.get('retry_timeout')
# useful tool (convert curl to python request)
# https://curl.trillworks.com/
# timeout_duration = 10 # TODO make this modifiable
initial_request_params = (
('eft_id', video_id),
('target_ufi_instance_id', 'u_2_1'),
# ('should_backfill', 'false'), # used when seeking? - # TODO true on first try?
)
time_increment = 60 # Facebook gets messages by the minute
# TODO make this modifiable
start_time = ensure_seconds(
params.get('start_time'), 0)
end_time = ensure_seconds(
params.get('end_time'), float('inf'))
next_start_time = max(start_time, 0)
end_time = min(end_time, max_duration)
# print(next_start_time, end_time, type(next_start_time), type(end_time))
# return
# total = []
while True:
next_end_time = min(next_start_time + time_increment, end_time)
times = (('start_time', next_start_time),
('end_time', next_end_time))
# print(times, flush=True)
request_params = initial_request_params + times
json_data = self._attempt_fb_retrieve(
self._VOD_COMMENTS_API,
max_attempts,
retry_timeout,
True,
headers=self._FB_HEADERS, params=request_params, data=self.data
)
payloads = multi_get(json_data, 'payload', 'ufipayloads')
if not payloads:
continue
# TODO debug
# print('no comments between',next_start_time, next_end_time, flush=True)
# print('err1')
# print(json_data)
next_start_time = next_end_time
if next_start_time >= end_time:
print('end')
return
for payload in payloads:
time_offset = payload.get('timeoffset')
# print(test)
ufipayload = payload.get('ufipayload')
if not ufipayload:
print('no ufipayload', payload)
continue
# ['comments'][0]['body']['text']
comment = try_get(ufipayload, lambda x: x['comments'][0])
if not comment:
# TODO debug
continue
# pinned_comments = ufipayload.get('pinnedcomments')
profile = try_get_first_value(ufipayload['profiles'])
text = comment['body']['text'] # safe_convert_text()
temp = {
'author': {
'name': profile.get('name')
},
'time_in_seconds': time_offset,
'time_text': seconds_to_time(time_offset),
'message': text
}
yield temp
def get_chat_by_video_id(self, video_id, params):
initial_info = self._get_initial_info(video_id, params)
start_time = params.get('start_time')
end_time = params.get('end_time')
is_live = initial_info.get('is_live')
# if start or end time specified, use chat replay...
# The tool works for both active and finished live streams.
# if start/end time are specified, vods will be prioritised
# if is live stream and no start/end time specified
if is_live and not start_time and not end_time:
generator = self._get_live_chat_messages_by_video_id(
video_id, params)
else:
max_duration = initial_info.get('duration', float('inf'))
generator = self._get_chat_replay_messages_by_video_id(
video_id, max_duration, params)
return Chat(
generator,
title=initial_info.get('title'),
duration=initial_info.get('duration'),
is_live=is_live,
author=initial_info.get('author'),
)
def get_chat(self, **kwargs):
url = kwargs.get('url')
match = re.search(self._VALID_URL, url)
if match:
if match.group('id'): # normal youtube video
return self.get_chat_by_video_id(match.group('id'), kwargs)
else: # TODO add profile, etc.
pass
| true | true |
f73140c2dd100d80311a5c5ccca1e3c3caf4075d | 3,746 | py | Python | postcode_validator_uk/rules.py | ioannavlahou/postcode-validator-uk | e43b2919a7d7e940ae072b24ab5d07587e8e3df8 | [
"MIT"
] | 4 | 2020-02-08T15:02:00.000Z | 2020-11-22T19:35:11.000Z | postcode_validator_uk/rules.py | ioannavlahou/postcode-validator-uk | e43b2919a7d7e940ae072b24ab5d07587e8e3df8 | [
"MIT"
] | 8 | 2021-06-23T12:36:40.000Z | 2021-12-21T11:26:27.000Z | postcode_validator_uk/rules.py | ioannavlahou/postcode-validator-uk | e43b2919a7d7e940ae072b24ab5d07587e8e3df8 | [
"MIT"
] | 2 | 2020-12-04T10:47:07.000Z | 2021-06-08T20:45:45.000Z | import re
from .exceptions import InvalidPostcode
class PostcodeRule:
attr_applied = None
applied_areas_regex = None
rule_regex = None
def __init__(self, postcode):
self.postcode = postcode
def validate(self):
postcode_attr_value = getattr(self.postcode, self.attr_applied, None)
if not postcode_attr_value:
raise AttributeError(f"This entity has not attr {self.attr_applied}")
if not self.applied_areas_regex.match(postcode_attr_value):
return
if not self.rule_regex.match(postcode_attr_value):
raise InvalidPostcode
class SingleDigitDistrict(PostcodeRule):
"""
Areas with only single-digit districts: BR, FY, HA, HD, HG, HR, HS, HX, JE, LD, SM, SR, WC, WN, ZE
(although WC is always subdivided by a further letter, e.g. WC1A)
"""
attr_applied = "outward"
applied_areas_regex = re.compile(r"^(BR|FY|HA|HD|HG|HR|HS|HX|JE|LD|SM|SR|WC|WN|ZE)")
rule_regex = re.compile(r"^(?!WC)[A-Z]{2}[0-9]$|^WC[0-9][A-Z]$")
class DoubleDigitDistrict(PostcodeRule):
"""Areas with only double-digit districts: AB, LL, SO"""
attr_applied = "outward"
applied_areas_regex = re.compile(r"^(AB|LL|SO)")
rule_regex = re.compile(r"^[A-Z]{2}[0-9]{2}$")
class ZeroOrTenDistrict(PostcodeRule):
"""
Areas with a district '0' (zero): BL, BS, CM, CR, FY, HA, PR, SL, SS
(BS is the only area to have both a district 0 and a district 10)
"""
attr_applied = "outward"
applied_areas_regex = re.compile(r"^[A-Z]{2}(0|10)$")
rule_regex = re.compile(r"^(BL|BS|CM|CR|FY|HA|PR|SL|SS)0$|^BS10$")
class CentralLondonDistrict(PostcodeRule):
"""
The following central London single-digit districts have been further divided by inserting a letter after
the digit and before the space: EC1–EC4 (but not EC50), SW1, W1, WC1, WC2 and parts of E1 (E1W),
N1 (N1C and N1P), NW1 (NW1W) and SE1 (SE1P).
"""
attr_applied = "outward"
applied_areas_regex = re.compile(r"^(EC[0-9]|E1|N1|NW1|SE1|SW1|W1|WC1|WC2)[A-Z]")
rule_regex = re.compile(
r"^EC[1-4][A-Z]?$|^E1[W]?$|^N1[C|P]?$|^NW1[W]?$|^SE1[P]?$|^SW1[A-Z]?$|^W1[A-Z]?$|^WC[1-2][A-Z]?$"
)
class FirstLetter(PostcodeRule):
"""The letters Q, V and X are not used in the first position."""
attr_applied = "outward"
applied_areas_regex = re.compile(r"^(Q|V|X)")
rule_regex = re.compile(r"^(?!Q|V|X).*")
class SecondLetter(PostcodeRule):
"""The letters I, J and Z are not used in the second position."""
attr_applied = "outward"
applied_areas_regex = re.compile(r"^[A-Z](I|J|Z)")
rule_regex = re.compile(r"^[A-Z](?!I|J|Z).*")
class ThirdLetter(PostcodeRule):
"""
The only letters to appear in the third position are A, B, C, D, E, F, G, H, J, K, P, S, T, U and W
when the structure starts with A9A.
"""
attr_applied = "outward"
applied_areas_regex = re.compile(r"^[A-Z][0-9][A-Z]$")
rule_regex = re.compile(r"^[A-Z][0-9](A|B|C|D|E|F|G|H|J|K|P|S|T|U|W)$")
class FourthLetter(PostcodeRule):
"""
The only letters to appear in the fourth position are A, B, E, H, M, N, P, R, V, W, X and Y
when the structure starts with AA9A.
"""
attr_applied = "outward"
applied_areas_regex = re.compile(r"^[A-Z]{2}[0-9][A-Z]$")
rule_regex = re.compile(r"^[A-Z]{2}[0-9](A|B|E|H|M|N|P|R|V|W|X|Y)$")
class LastTwoLetter(PostcodeRule):
"""
The final two letters do not use C, I, K, M, O or V, so as not to resemble digits
or each other when hand-written.
"""
attr_applied = "inward"
applied_areas_regex = re.compile(r"^[0-9][A-Z]{2}$")
rule_regex = re.compile(r"^[0-9][A|B|D|E|F|G|H|J|L|N|P|Q|R|S|T|U|W|X|Y|Z]{2}$")
| 32.017094 | 109 | 0.626535 | import re
from .exceptions import InvalidPostcode
class PostcodeRule:
attr_applied = None
applied_areas_regex = None
rule_regex = None
def __init__(self, postcode):
self.postcode = postcode
def validate(self):
postcode_attr_value = getattr(self.postcode, self.attr_applied, None)
if not postcode_attr_value:
raise AttributeError(f"This entity has not attr {self.attr_applied}")
if not self.applied_areas_regex.match(postcode_attr_value):
return
if not self.rule_regex.match(postcode_attr_value):
raise InvalidPostcode
class SingleDigitDistrict(PostcodeRule):
attr_applied = "outward"
applied_areas_regex = re.compile(r"^(BR|FY|HA|HD|HG|HR|HS|HX|JE|LD|SM|SR|WC|WN|ZE)")
rule_regex = re.compile(r"^(?!WC)[A-Z]{2}[0-9]$|^WC[0-9][A-Z]$")
class DoubleDigitDistrict(PostcodeRule):
attr_applied = "outward"
applied_areas_regex = re.compile(r"^(AB|LL|SO)")
rule_regex = re.compile(r"^[A-Z]{2}[0-9]{2}$")
class ZeroOrTenDistrict(PostcodeRule):
attr_applied = "outward"
applied_areas_regex = re.compile(r"^[A-Z]{2}(0|10)$")
rule_regex = re.compile(r"^(BL|BS|CM|CR|FY|HA|PR|SL|SS)0$|^BS10$")
class CentralLondonDistrict(PostcodeRule):
attr_applied = "outward"
applied_areas_regex = re.compile(r"^(EC[0-9]|E1|N1|NW1|SE1|SW1|W1|WC1|WC2)[A-Z]")
rule_regex = re.compile(
r"^EC[1-4][A-Z]?$|^E1[W]?$|^N1[C|P]?$|^NW1[W]?$|^SE1[P]?$|^SW1[A-Z]?$|^W1[A-Z]?$|^WC[1-2][A-Z]?$"
)
class FirstLetter(PostcodeRule):
attr_applied = "outward"
applied_areas_regex = re.compile(r"^(Q|V|X)")
rule_regex = re.compile(r"^(?!Q|V|X).*")
class SecondLetter(PostcodeRule):
attr_applied = "outward"
applied_areas_regex = re.compile(r"^[A-Z](I|J|Z)")
rule_regex = re.compile(r"^[A-Z](?!I|J|Z).*")
class ThirdLetter(PostcodeRule):
attr_applied = "outward"
applied_areas_regex = re.compile(r"^[A-Z][0-9][A-Z]$")
rule_regex = re.compile(r"^[A-Z][0-9](A|B|C|D|E|F|G|H|J|K|P|S|T|U|W)$")
class FourthLetter(PostcodeRule):
attr_applied = "outward"
applied_areas_regex = re.compile(r"^[A-Z]{2}[0-9][A-Z]$")
rule_regex = re.compile(r"^[A-Z]{2}[0-9](A|B|E|H|M|N|P|R|V|W|X|Y)$")
class LastTwoLetter(PostcodeRule):
attr_applied = "inward"
applied_areas_regex = re.compile(r"^[0-9][A-Z]{2}$")
rule_regex = re.compile(r"^[0-9][A|B|D|E|F|G|H|J|L|N|P|Q|R|S|T|U|W|X|Y|Z]{2}$")
| true | true |
f73140d48b7cc619133309d7e0b2c6781efb1c0a | 9,038 | py | Python | twentyfortyeight/strategy/nn/data.py | ggould256/twentyfortyeight | 7d2b88023077ba4c64b65617d493039c0a9998c3 | [
"MIT"
] | null | null | null | twentyfortyeight/strategy/nn/data.py | ggould256/twentyfortyeight | 7d2b88023077ba4c64b65617d493039c0a9998c3 | [
"MIT"
] | null | null | null | twentyfortyeight/strategy/nn/data.py | ggould256/twentyfortyeight | 7d2b88023077ba4c64b65617d493039c0a9998c3 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
"""Classes and functions related to dataset generation for learning Q
functions. Datasets in this sense are mappings from board positions
(represented as flattened arrays of tile numbers) to score values.
"""
import argparse
import sys
import numpy as np
from game.common import *
from game.board import Board
from game.game import Game
EXAMPLE_WIDTH = Board.vector_width()
MAX_BATCH_SIZE = 4096 # numpy arrays get slow to update beyond this size.
class Dataset(object):
"""A set of training data (held as matrices whose rows are examples) and a
column vector of the example scores.."""
def __init__(self):
"""Creates a new empty dataset."""
self._num_examples = 0
self._example_batches = [np.zeros((0, EXAMPLE_WIDTH))]
self._score_batches = [np.zeros((0, 1))]
def add_game(self, player_strategy, rnd, starting_game_position=None):
"""Runs a game with the given strategy and randomness source, then
enrolls the outcome in the dataset.
If @p starting_position is a Game object, start from that position.
Returns the number of examples (moves) added.
"""
states = np.zeros((1, EXAMPLE_WIDTH))
num_moves = 0
game = starting_game_position or Game(rnd=rnd)
running = True
while running:
intermediate_board, turn_outcome = (
game.do_turn_and_retrieve_intermediate(
player_strategy.get_move(game.board(), game.score())))
running = (turn_outcome != GAMEOVER)
num_moves += (turn_outcome != ILLEGAL)
if turn_outcome == OK:
states = np.append(states,
Board.as_vector(intermediate_board),
axis=0)
self._num_examples += 1
player_strategy.notify_outcome(game.board(), game.score())
scores = Dataset.evaluate_states(states, game.board(), game.score)
assert(len(states) == len(scores))
batch_size_so_far = self._example_batches[-1].shape[0]
if len(states) + batch_size_so_far > MAX_BATCH_SIZE:
self._example_batches.append(np.zeros((0, EXAMPLE_WIDTH)))
self._score_batches.append(np.zeros((0, 1)))
self._example_batches[-1] = \
np.append(self._example_batches[-1], states, axis=0)
self._score_batches[-1] = np.append(self._score_batches[-1], scores)
return len(states)
@staticmethod
def evaluate_states(states, end_board, end_score):
"""Associate a Q score with each state of the current game. There are
many possible designs here, ranging from applying the ultimate score or
highest attained tile to all of the states to scoring each state with
the number of moves remaining in its game. The correct function is
not obvious; the current implementation is moves-remaining."""
del end_board, end_score
return np.array(list(range(len(states), 0, -1)))
def add_n_examples(self, strategy, rnd, n,
starting_positions_dataset=None):
"""Runs games and adds them to the dataset until at least @p n
examples have been added. Returns the number of examples added.
If @p starting_positions_dataset is set, games will be started from
a randomly selected position from that dataset rather than from a
blank board."""
print("Adding", n, "examples to dataset.")
added = 0
while added < n:
starting_game = None
if starting_positions_dataset:
random_position = starting_positions_dataset.nth_example(
rnd.randint(0,
starting_positions_dataset.num_examples() - 1))
starting_game = Game(Board.from_vector(random_position))
if not starting_game.board().can_move():
continue
num_added = self.add_game(strategy, rnd, starting_game)
if (added // 10000) != ((num_added + added) // 10000):
print("Added %d so far..." % (num_added + added))
added += num_added
return added
def num_batches(self):
return len(self._example_batches)
def num_examples(self):
return self._num_examples
def example_batches(self):
return self._example_batches
def nth_example(self, n):
counter = n
for batch in self._example_batches:
size = batch.shape[0]
if counter < size:
return batch[counter, :]
else:
counter -= size
return None
def nth_score(self, n):
counter = n
for batch in self._score_batches:
size = batch.shape[0]
if counter < size:
return batch[counter]
else:
counter -= size
return None
def score_batches(self):
return self._score_batches
def collapse(self):
"""Collapses all of the batches down to a single, very large batch."""
self._score_batches = [np.concatenate(self._score_batches)]
self._example_batches = [np.concatenate(self._example_batches)]
def save(self, filename):
assert(filename.endswith(".npz"))
num_batches = len(self._example_batches)
examples_dict = {"examples_%s" % i: self._example_batches[i]
for i in range(num_batches)}
scores_dict = {"scores_%s" % i: self._score_batches[i]
for i in range(num_batches)}
unified_dict = {**examples_dict, **scores_dict}
with open(filename, "wb") as f:
np.savez(f, **unified_dict)
@staticmethod
def load(filename):
assert(filename.endswith(".npz"))
with open(filename, "rb") as f:
npz_data = np.load(f)
data = Dataset()
data._example_batches = []
data._score_batches = []
num_batches = len(npz_data.files) // 2
for i in range(num_batches):
data._example_batches.append(
npz_data["examples_%s" % i])
data._score_batches.append(
npz_data["scores_%s" % i])
data._num_examples = sum(array.shape[0]
for array in data._example_batches)
return data
def main(argv):
parser = argparse.ArgumentParser()
parser.add_argument('--num_examples', metavar='N', type=int,
help="Number of examples (at minimum) to generate")
parser.add_argument('--output_file', metavar='FILENAME', type=str,
help="npz file into which to write example data")
parser.add_argument('--strategy', metavar='FILE_OR_NAME', type=str,
help="name of strategy or filename of model",
default="random")
parser.add_argument('--starting_positions', metavar='FILENAME', type=str,
default=None,
help=("If set, start some or all games from positions"
"drawn from this dataset"))
parser.add_argument('--new_start_fraction', metavar='FRACTION', type=float,
default=1.,
help=("If --starting_positions is set, start this "
"fraction of games from a new game position"))
args = parser.parse_args(argv[1:])
import random
from strategy.basic import RandomStrategy, SpinnyStrategy
from strategy.nn.nn_strategy import ModelStrategy
if args.strategy == "spinny":
strategy = SpinnyStrategy()
elif args.strategy == "random":
strategy = RandomStrategy()
else:
strategy = ModelStrategy(args.strategy)
start_positions_dataset = None
if args.starting_positions:
start_positions_dataset = Dataset.load(args.starting_positions)
dataset = Dataset()
num_added = dataset.add_n_examples(
strategy, random, args.num_examples * args.new_start_fraction)
if args.new_start_fraction < 1:
assert start_positions_dataset, \
"--new_start_fraction requires --starting_positions"
num_added = dataset.add_n_examples(
strategy, random, args.num_examples * (1 - args.new_start_fraction),
starting_positions_dataset=start_positions_dataset)
print("Added", num_added, "examples")
print("saving...")
dataset.save(args.output_file)
print("...saved.")
print("checking output file validity...")
check_data = Dataset.load(args.output_file)
assert dataset.num_batches() == check_data.num_batches(), \
("original batch number %s does not equal output batch number %s"
% (dataset.num_batches(), check_data.num_batches()))
check_data.collapse()
print("...output is valid.")
if __name__ == '__main__':
main(sys.argv)
| 39.99115 | 80 | 0.610423 |
import argparse
import sys
import numpy as np
from game.common import *
from game.board import Board
from game.game import Game
EXAMPLE_WIDTH = Board.vector_width()
MAX_BATCH_SIZE = 4096
class Dataset(object):
def __init__(self):
self._num_examples = 0
self._example_batches = [np.zeros((0, EXAMPLE_WIDTH))]
self._score_batches = [np.zeros((0, 1))]
def add_game(self, player_strategy, rnd, starting_game_position=None):
states = np.zeros((1, EXAMPLE_WIDTH))
num_moves = 0
game = starting_game_position or Game(rnd=rnd)
running = True
while running:
intermediate_board, turn_outcome = (
game.do_turn_and_retrieve_intermediate(
player_strategy.get_move(game.board(), game.score())))
running = (turn_outcome != GAMEOVER)
num_moves += (turn_outcome != ILLEGAL)
if turn_outcome == OK:
states = np.append(states,
Board.as_vector(intermediate_board),
axis=0)
self._num_examples += 1
player_strategy.notify_outcome(game.board(), game.score())
scores = Dataset.evaluate_states(states, game.board(), game.score)
assert(len(states) == len(scores))
batch_size_so_far = self._example_batches[-1].shape[0]
if len(states) + batch_size_so_far > MAX_BATCH_SIZE:
self._example_batches.append(np.zeros((0, EXAMPLE_WIDTH)))
self._score_batches.append(np.zeros((0, 1)))
self._example_batches[-1] = \
np.append(self._example_batches[-1], states, axis=0)
self._score_batches[-1] = np.append(self._score_batches[-1], scores)
return len(states)
@staticmethod
def evaluate_states(states, end_board, end_score):
del end_board, end_score
return np.array(list(range(len(states), 0, -1)))
def add_n_examples(self, strategy, rnd, n,
starting_positions_dataset=None):
print("Adding", n, "examples to dataset.")
added = 0
while added < n:
starting_game = None
if starting_positions_dataset:
random_position = starting_positions_dataset.nth_example(
rnd.randint(0,
starting_positions_dataset.num_examples() - 1))
starting_game = Game(Board.from_vector(random_position))
if not starting_game.board().can_move():
continue
num_added = self.add_game(strategy, rnd, starting_game)
if (added // 10000) != ((num_added + added) // 10000):
print("Added %d so far..." % (num_added + added))
added += num_added
return added
def num_batches(self):
return len(self._example_batches)
def num_examples(self):
return self._num_examples
def example_batches(self):
return self._example_batches
def nth_example(self, n):
counter = n
for batch in self._example_batches:
size = batch.shape[0]
if counter < size:
return batch[counter, :]
else:
counter -= size
return None
def nth_score(self, n):
counter = n
for batch in self._score_batches:
size = batch.shape[0]
if counter < size:
return batch[counter]
else:
counter -= size
return None
def score_batches(self):
return self._score_batches
def collapse(self):
self._score_batches = [np.concatenate(self._score_batches)]
self._example_batches = [np.concatenate(self._example_batches)]
def save(self, filename):
assert(filename.endswith(".npz"))
num_batches = len(self._example_batches)
examples_dict = {"examples_%s" % i: self._example_batches[i]
for i in range(num_batches)}
scores_dict = {"scores_%s" % i: self._score_batches[i]
for i in range(num_batches)}
unified_dict = {**examples_dict, **scores_dict}
with open(filename, "wb") as f:
np.savez(f, **unified_dict)
@staticmethod
def load(filename):
assert(filename.endswith(".npz"))
with open(filename, "rb") as f:
npz_data = np.load(f)
data = Dataset()
data._example_batches = []
data._score_batches = []
num_batches = len(npz_data.files) // 2
for i in range(num_batches):
data._example_batches.append(
npz_data["examples_%s" % i])
data._score_batches.append(
npz_data["scores_%s" % i])
data._num_examples = sum(array.shape[0]
for array in data._example_batches)
return data
def main(argv):
parser = argparse.ArgumentParser()
parser.add_argument('--num_examples', metavar='N', type=int,
help="Number of examples (at minimum) to generate")
parser.add_argument('--output_file', metavar='FILENAME', type=str,
help="npz file into which to write example data")
parser.add_argument('--strategy', metavar='FILE_OR_NAME', type=str,
help="name of strategy or filename of model",
default="random")
parser.add_argument('--starting_positions', metavar='FILENAME', type=str,
default=None,
help=("If set, start some or all games from positions"
"drawn from this dataset"))
parser.add_argument('--new_start_fraction', metavar='FRACTION', type=float,
default=1.,
help=("If --starting_positions is set, start this "
"fraction of games from a new game position"))
args = parser.parse_args(argv[1:])
import random
from strategy.basic import RandomStrategy, SpinnyStrategy
from strategy.nn.nn_strategy import ModelStrategy
if args.strategy == "spinny":
strategy = SpinnyStrategy()
elif args.strategy == "random":
strategy = RandomStrategy()
else:
strategy = ModelStrategy(args.strategy)
start_positions_dataset = None
if args.starting_positions:
start_positions_dataset = Dataset.load(args.starting_positions)
dataset = Dataset()
num_added = dataset.add_n_examples(
strategy, random, args.num_examples * args.new_start_fraction)
if args.new_start_fraction < 1:
assert start_positions_dataset, \
"--new_start_fraction requires --starting_positions"
num_added = dataset.add_n_examples(
strategy, random, args.num_examples * (1 - args.new_start_fraction),
starting_positions_dataset=start_positions_dataset)
print("Added", num_added, "examples")
print("saving...")
dataset.save(args.output_file)
print("...saved.")
print("checking output file validity...")
check_data = Dataset.load(args.output_file)
assert dataset.num_batches() == check_data.num_batches(), \
("original batch number %s does not equal output batch number %s"
% (dataset.num_batches(), check_data.num_batches()))
check_data.collapse()
print("...output is valid.")
if __name__ == '__main__':
main(sys.argv)
| true | true |
f73142a29e58f8c444562a3781b8fbaa6e06ccc2 | 2,085 | py | Python | scout/server/blueprints/institutes/controllers.py | gmc-norr/scout | ea8eaaa079c63e4033af6216ec08da4a314f9b5c | [
"BSD-3-Clause"
] | null | null | null | scout/server/blueprints/institutes/controllers.py | gmc-norr/scout | ea8eaaa079c63e4033af6216ec08da4a314f9b5c | [
"BSD-3-Clause"
] | null | null | null | scout/server/blueprints/institutes/controllers.py | gmc-norr/scout | ea8eaaa079c63e4033af6216ec08da4a314f9b5c | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
import logging
LOG = logging.getLogger(__name__)
def institute(store, institute_id):
""" Process institute data.
Args:
store(adapter.MongoAdapter)
institute_id(str)
Returns
data(dict): includes institute obj and specific settings
"""
institute_obj = store.institute(institute_id)
users = store.users(institute_id)
data = {"institute": institute_obj, "users": users}
return data
def update_institute_settings(store, institute_obj, form):
""" Update institute settings with data collected from institute form
Args:
score(adapter.MongoAdapter)
institute_id(str)
form(dict)
Returns:
updated_institute(dict)
"""
sanger_recipients = []
sharing_institutes = []
phenotype_groups = []
group_abbreviations = []
cohorts = []
for email in form.getlist("sanger_emails"):
sanger_recipients.append(email.strip())
for inst in form.getlist("institutes"):
sharing_institutes.append(inst)
for pheno_group in form.getlist("pheno_groups"):
phenotype_groups.append(pheno_group.split(" ,")[0])
group_abbreviations.append(
pheno_group[pheno_group.find("( ") + 2 : pheno_group.find(" )")]
)
if form.get("hpo_term") and form.get("pheno_abbrev"):
phenotype_groups.append(form["hpo_term"].split(" |")[0])
group_abbreviations.append(form["pheno_abbrev"])
for cohort in form.getlist("cohorts"):
cohorts.append(cohort.strip())
updated_institute = store.update_institute(
internal_id=institute_obj["_id"],
sanger_recipients=sanger_recipients,
coverage_cutoff=int(form.get("coverage_cutoff")),
frequency_cutoff=float(form.get("frequency_cutoff")),
display_name=form.get("display_name"),
phenotype_groups=phenotype_groups,
group_abbreviations=group_abbreviations,
add_groups=False,
sharing_institutes=sharing_institutes,
cohorts=cohorts,
)
return updated_institute
| 27.8 | 76 | 0.664748 |
import logging
LOG = logging.getLogger(__name__)
def institute(store, institute_id):
institute_obj = store.institute(institute_id)
users = store.users(institute_id)
data = {"institute": institute_obj, "users": users}
return data
def update_institute_settings(store, institute_obj, form):
sanger_recipients = []
sharing_institutes = []
phenotype_groups = []
group_abbreviations = []
cohorts = []
for email in form.getlist("sanger_emails"):
sanger_recipients.append(email.strip())
for inst in form.getlist("institutes"):
sharing_institutes.append(inst)
for pheno_group in form.getlist("pheno_groups"):
phenotype_groups.append(pheno_group.split(" ,")[0])
group_abbreviations.append(
pheno_group[pheno_group.find("( ") + 2 : pheno_group.find(" )")]
)
if form.get("hpo_term") and form.get("pheno_abbrev"):
phenotype_groups.append(form["hpo_term"].split(" |")[0])
group_abbreviations.append(form["pheno_abbrev"])
for cohort in form.getlist("cohorts"):
cohorts.append(cohort.strip())
updated_institute = store.update_institute(
internal_id=institute_obj["_id"],
sanger_recipients=sanger_recipients,
coverage_cutoff=int(form.get("coverage_cutoff")),
frequency_cutoff=float(form.get("frequency_cutoff")),
display_name=form.get("display_name"),
phenotype_groups=phenotype_groups,
group_abbreviations=group_abbreviations,
add_groups=False,
sharing_institutes=sharing_institutes,
cohorts=cohorts,
)
return updated_institute
| true | true |
f731432c913f3ccfd7e302c02503a7537510ff9a | 2,720 | py | Python | pipenv/vendor/pythonfinder/models/windows.py | Enzime/pipenv | d4f710be4a39e09a82a5133b7b3a277ee9bfb13a | [
"MIT"
] | null | null | null | pipenv/vendor/pythonfinder/models/windows.py | Enzime/pipenv | d4f710be4a39e09a82a5133b7b3a277ee9bfb13a | [
"MIT"
] | null | null | null | pipenv/vendor/pythonfinder/models/windows.py | Enzime/pipenv | d4f710be4a39e09a82a5133b7b3a277ee9bfb13a | [
"MIT"
] | 1 | 2021-07-03T03:30:45.000Z | 2021-07-03T03:30:45.000Z | # -*- coding=utf-8 -*-
from __future__ import print_function, absolute_import
import attr
import operator
from collections import defaultdict
from . import BaseFinder
from .path import PathEntry
from .python import PythonVersion, VersionMap
from ..exceptions import InvalidPythonVersion
from ..utils import ensure_path
@attr.s
class WindowsFinder(BaseFinder):
paths = attr.ib(default=attr.Factory(list))
version_list = attr.ib(default=attr.Factory(list))
versions = attr.ib()
pythons = attr.ib()
def find_all_python_versions(
self, major=None, minor=None, patch=None, pre=None, dev=None, arch=None
):
version_matcher = operator.methodcaller(
"matches",
major=major,
minor=minor,
patch=patch,
pre=pre,
dev=dev,
arch=arch,
)
py_filter = filter(
None, filter(lambda c: version_matcher(c), self.version_list)
)
version_sort = operator.attrgetter("version_sort")
return [c.comes_from for c in sorted(py_filter, key=version_sort, reverse=True)]
def find_python_version(
self, major=None, minor=None, patch=None, pre=None, dev=None, arch=None
):
return next(
(
v
for v in self.find_all_python_versions(
major=major, minor=minor, patch=patch, pre=pre, dev=dev, arch=arch
)
),
None,
)
@versions.default
def get_versions(self):
versions = defaultdict(PathEntry)
from pythonfinder._vendor.pep514tools import environment as pep514env
env_versions = pep514env.findall()
path = None
for version_object in env_versions:
path = ensure_path(version_object.info.install_path.__getattr__(""))
try:
py_version = PythonVersion.from_windows_launcher(version_object)
except InvalidPythonVersion:
continue
self.version_list.append(py_version)
base_dir = PathEntry.create(
path,
is_root=True,
only_python=True,
pythons={py_version.comes_from.path: py_version},
)
versions[py_version.version_tuple[:5]] = base_dir
self.paths.append(base_dir)
return versions
@pythons.default
def get_pythons(self):
pythons = defaultdict()
for version in self.version_list:
_path = ensure_path(version.comes_from.path)
pythons[_path.as_posix()] = version.comes_from
return pythons
@classmethod
def create(cls):
return cls()
| 31.627907 | 88 | 0.608088 |
from __future__ import print_function, absolute_import
import attr
import operator
from collections import defaultdict
from . import BaseFinder
from .path import PathEntry
from .python import PythonVersion, VersionMap
from ..exceptions import InvalidPythonVersion
from ..utils import ensure_path
@attr.s
class WindowsFinder(BaseFinder):
paths = attr.ib(default=attr.Factory(list))
version_list = attr.ib(default=attr.Factory(list))
versions = attr.ib()
pythons = attr.ib()
def find_all_python_versions(
self, major=None, minor=None, patch=None, pre=None, dev=None, arch=None
):
version_matcher = operator.methodcaller(
"matches",
major=major,
minor=minor,
patch=patch,
pre=pre,
dev=dev,
arch=arch,
)
py_filter = filter(
None, filter(lambda c: version_matcher(c), self.version_list)
)
version_sort = operator.attrgetter("version_sort")
return [c.comes_from for c in sorted(py_filter, key=version_sort, reverse=True)]
def find_python_version(
self, major=None, minor=None, patch=None, pre=None, dev=None, arch=None
):
return next(
(
v
for v in self.find_all_python_versions(
major=major, minor=minor, patch=patch, pre=pre, dev=dev, arch=arch
)
),
None,
)
@versions.default
def get_versions(self):
versions = defaultdict(PathEntry)
from pythonfinder._vendor.pep514tools import environment as pep514env
env_versions = pep514env.findall()
path = None
for version_object in env_versions:
path = ensure_path(version_object.info.install_path.__getattr__(""))
try:
py_version = PythonVersion.from_windows_launcher(version_object)
except InvalidPythonVersion:
continue
self.version_list.append(py_version)
base_dir = PathEntry.create(
path,
is_root=True,
only_python=True,
pythons={py_version.comes_from.path: py_version},
)
versions[py_version.version_tuple[:5]] = base_dir
self.paths.append(base_dir)
return versions
@pythons.default
def get_pythons(self):
pythons = defaultdict()
for version in self.version_list:
_path = ensure_path(version.comes_from.path)
pythons[_path.as_posix()] = version.comes_from
return pythons
@classmethod
def create(cls):
return cls()
| true | true |
f73143b9c73994a32651383e17bb04174dee2b85 | 915 | py | Python | python/test/test_volume.py | adriangonz/seldon-deploy-sdk | c5504838630a87053387cec57ec2e1e7251971e2 | [
"Apache-2.0"
] | 6 | 2021-02-18T14:37:54.000Z | 2022-01-13T13:27:43.000Z | python/test/test_volume.py | adriangonz/seldon-deploy-sdk | c5504838630a87053387cec57ec2e1e7251971e2 | [
"Apache-2.0"
] | 14 | 2021-01-04T16:32:03.000Z | 2021-12-13T17:53:59.000Z | python/test/test_volume.py | adriangonz/seldon-deploy-sdk | c5504838630a87053387cec57ec2e1e7251971e2 | [
"Apache-2.0"
] | 7 | 2021-03-17T09:05:55.000Z | 2022-01-05T10:39:56.000Z | # coding: utf-8
"""
Seldon Deploy API
API to interact and manage the lifecycle of your machine learning models deployed through Seldon Deploy. # noqa: E501
OpenAPI spec version: v1alpha1
Contact: hello@seldon.io
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import seldon_deploy_sdk
from seldon_deploy_sdk.models.volume import Volume # noqa: E501
from seldon_deploy_sdk.rest import ApiException
class TestVolume(unittest.TestCase):
"""Volume unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testVolume(self):
"""Test Volume"""
# FIXME: construct object with mandatory attributes with example values
# model = seldon_deploy_sdk.models.volume.Volume() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
| 22.317073 | 122 | 0.700546 |
from __future__ import absolute_import
import unittest
import seldon_deploy_sdk
from seldon_deploy_sdk.models.volume import Volume
from seldon_deploy_sdk.rest import ApiException
class TestVolume(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def testVolume(self):
s
if __name__ == '__main__':
unittest.main()
| true | true |
f73143ec8bc29c71a9b4d763b26b580bba6673cb | 3,254 | py | Python | logging/cloud-client/snippets.py | alexhaines123/googlecloudsqlexamples | 06d9254ec77955c02f18cd79a57cdfbd64dbf8ea | [
"Apache-2.0"
] | 2 | 2017-09-23T04:23:46.000Z | 2021-06-11T01:23:06.000Z | logging/cloud-client/snippets.py | ryanmats/python-docs-samples | 183a6186cd059c7ba24ef324614bc5fee08bff08 | [
"Apache-2.0"
] | null | null | null | logging/cloud-client/snippets.py | ryanmats/python-docs-samples | 183a6186cd059c7ba24ef324614bc5fee08bff08 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This application demonstrates how to perform basic operations on logs and
log entries with Stackdriver Logging.
For more information, see the README.md under /logging and the
documentation at https://cloud.google.com/logging/docs.
"""
import argparse
from gcloud import logging
def write_entry(logger_name):
"""Writes log entries to the given logger."""
logging_client = logging.Client()
# This log can be found in the Cloud Logging console under 'Custom Logs'.
logger = logging_client.logger(logger_name)
# Make a simple text log
logger.log_text('Hello, world!')
# Simple text log with severity.
logger.log_text('Goodbye, world!', severity='ERROR')
# Struct log. The struct can be any JSON-serializable dictionary.
logger.log_struct({
'name': 'King Arthur',
'quest': 'Find the Holy Grail',
'favorite_color': 'Blue'
})
print('Wrote logs to {}.'.format(logger.name))
def list_entries(logger_name):
"""Lists the most recent entries for a given logger."""
logging_client = logging.Client()
logger = logging_client.logger(logger_name)
print('Listing entries for logger {}:'.format(logger.name))
entries = []
page_token = None
while True:
new_entries, page_token = logger.list_entries(page_token=page_token)
entries.extend(new_entries)
if not page_token:
break
for entry in entries:
timestamp = entry.timestamp.isoformat()
print('* {}: {}'.format
(timestamp, entry.payload))
def delete_logger(logger_name):
"""Deletes a logger and all its entries.
Note that a deletion can take several minutes to take effect.
"""
logging_client = logging.Client()
logger = logging_client.logger(logger_name)
logger.delete()
print('Deleted all logging entries for {}'.format(logger.name))
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument(
'logger_name', help='Logger name', default='example_log')
subparsers = parser.add_subparsers(dest='command')
subparsers.add_parser('list', help=list_entries.__doc__)
subparsers.add_parser('write', help=write_entry.__doc__)
subparsers.add_parser('delete', help=delete_logger.__doc__)
args = parser.parse_args()
if args.command == 'list':
list_entries(args.logger_name)
elif args.command == 'write':
write_entry(args.logger_name)
elif args.command == 'delete':
delete_logger(args.logger_name)
| 30.411215 | 77 | 0.69791 |
import argparse
from gcloud import logging
def write_entry(logger_name):
logging_client = logging.Client()
logger = logging_client.logger(logger_name)
logger.log_text('Hello, world!')
logger.log_text('Goodbye, world!', severity='ERROR')
logger.log_struct({
'name': 'King Arthur',
'quest': 'Find the Holy Grail',
'favorite_color': 'Blue'
})
print('Wrote logs to {}.'.format(logger.name))
def list_entries(logger_name):
logging_client = logging.Client()
logger = logging_client.logger(logger_name)
print('Listing entries for logger {}:'.format(logger.name))
entries = []
page_token = None
while True:
new_entries, page_token = logger.list_entries(page_token=page_token)
entries.extend(new_entries)
if not page_token:
break
for entry in entries:
timestamp = entry.timestamp.isoformat()
print('* {}: {}'.format
(timestamp, entry.payload))
def delete_logger(logger_name):
logging_client = logging.Client()
logger = logging_client.logger(logger_name)
logger.delete()
print('Deleted all logging entries for {}'.format(logger.name))
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument(
'logger_name', help='Logger name', default='example_log')
subparsers = parser.add_subparsers(dest='command')
subparsers.add_parser('list', help=list_entries.__doc__)
subparsers.add_parser('write', help=write_entry.__doc__)
subparsers.add_parser('delete', help=delete_logger.__doc__)
args = parser.parse_args()
if args.command == 'list':
list_entries(args.logger_name)
elif args.command == 'write':
write_entry(args.logger_name)
elif args.command == 'delete':
delete_logger(args.logger_name)
| true | true |
f73146cc31c2e9c1cdcb0e154acdd7af261b22a1 | 10,702 | py | Python | backbone/model_audio.py | rtu715/NAS-Bench-360 | d075006848c664371855c34082b0a00cda62be67 | [
"MIT"
] | 10 | 2021-06-15T17:48:34.000Z | 2022-02-23T18:34:28.000Z | backbone/model_audio.py | rtu715/NAS-Bench-360 | d075006848c664371855c34082b0a00cda62be67 | [
"MIT"
] | 1 | 2021-11-12T15:12:38.000Z | 2021-11-12T19:38:00.000Z | backbone/model_audio.py | rtu715/NAS-Bench-360 | d075006848c664371855c34082b0a00cda62be67 | [
"MIT"
] | 1 | 2021-11-15T04:07:17.000Z | 2021-11-15T04:07:17.000Z | '''
Determined model def example:
https://github.com/determined-ai/determined/tree/master/examples/computer_vision/cifar10_pytorch
'''
import tempfile
from typing import Any, Dict, Sequence, Tuple, Union, cast
from functools import partial
import os
import boto3
import numpy as np
from sklearn.metrics import average_precision_score
import torch
from torch import nn
from determined.pytorch import DataLoader, PyTorchTrial, PyTorchTrialContext, LRScheduler
from backbone_pt import Backbone_Pt, Backbone_Audio
import utils_pt
from data_utils.load_data import load_data
from data_utils.download_data import download_from_s3
from data_utils.audio_dataset import *
from data_utils.audio_dataset import _collate_fn, _collate_fn_eval
# Constants about the dataset here (need to modify)
TorchData = Union[Dict[str, torch.Tensor], Sequence[torch.Tensor], torch.Tensor]
def accuracy_rate(predictions: torch.Tensor, labels: torch.Tensor) -> float:
"""Return the accuracy rate based on dense predictions and sparse labels."""
assert len(predictions) == len(labels), "Predictions and labels must have the same length."
assert len(labels.shape) == 1, "Labels must be a column vector."
return ( # type: ignore
float((predictions.argmax(1) == labels.to(torch.long)).sum()) / predictions.shape[0]
)
class AttrDict(dict):
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
self.__dict__ = self
class BackboneTrial(PyTorchTrial):
def __init__(self, trial_context: PyTorchTrialContext) -> None:
self.context = trial_context
self.hparams = AttrDict(trial_context.get_hparams())
self.last_epoch = 0
self.download_directory = self.download_data_from_s3()
#self.results = {"loss": float("inf"), "top1_accuracy": 0, "top5_accuracy": 0, "test_loss": float("inf"),
# "test_top1_accuracy": 0, "test_top5_accuracy": 0}
dataset_hypers = {'sEMG': (7, 1), 'ninapro': (18, 1), 'cifar10': (10, 3),
'smnist': (10, 1), 'cifar100':(100, 3), 'scifar100': (100, 3),
'audio': (200, 1)}
n_classes, in_channels = dataset_hypers[self.hparams.task]
print('task: ', self.hparams.task, 'in_channels: ', in_channels, 'classes: ', n_classes)
# Changing our backbone
depth = list(map(int, self.hparams.backbone.split(',')))[0]
width = list(map(int, self.hparams.backbone.split(',')))[1]
#for audio, use multilabel loss
if self.hparams.task == 'audio':
# where is the weights file?
self.criterion = nn.BCEWithLogitsLoss().cuda()
self.backbone = Backbone_Audio(depth, n_classes, width,
dropRate=self.hparams.droprate, in_channels=in_channels)
else:
self.criterion = nn.CrossEntropyLoss().cuda()
self.backbone = Backbone_Pt(
depth,
n_classes,
width,
dropRate=self.hparams.droprate,
in_channels=in_channels,
)
total_params = sum(p.numel() for p in self.backbone.parameters() if p.requires_grad)/ 1e6
print('Parameter size in MB(backbone): ', total_params)
self.model = self.context.wrap_model(self.backbone)
self.last_eval = 0
'''
Definition of optimizer
'''
nesterov = self.hparams.nesterov if self.hparams.momentum else False
self.opt = self.context.wrap_optimizer(torch.optim.SGD(
self.model.parameters(),
lr=self.hparams.learning_rate,
momentum=self.hparams.momentum,
weight_decay=self.hparams.weight_decay,
nesterov=nesterov)
)
self.lr_scheduler = self.context.wrap_lr_scheduler(
lr_scheduler=torch.optim.lr_scheduler.LambdaLR(
self.opt,
lr_lambda=self.weight_sched,
last_epoch=self.hparams.start_epoch - 1
),
step_mode=LRScheduler.StepMode.STEP_EVERY_EPOCH,
)
def weight_sched(self, epoch) -> Any:
if self.hparams.epochs != 200:
return 0.2 ** (epoch >= int(0.3 * self.hparams.epochs)) * 0.2 ** (epoch > int(0.6 * self.hparams.epochs)) * 0.2 ** (epoch > int(0.8 * self.hparams.epochs))
#print('using original weight schedule')
return 0.2 ** (epoch >= 60) * 0.2 ** (epoch >= 120) * 0.2 ** (epoch >=160)
def download_data_from_s3(self):
'''Download data from s3 to store in temp directory'''
s3_bucket = self.context.get_data_config()["bucket"]
#download_directory = f"/tmp/data-rank{self.context.distributed.get_rank()}"
#download_directory = "/tmp/data"
download_directory = os.getcwd()
s3 = boto3.client("s3")
#os.makedirs(download_directory, exist_ok=True)
download_from_s3(s3_bucket, self.hparams.task, download_directory)
if self.hparams.train:
self.train_data, self.val_data, self.test_data = load_data(self.hparams.task, download_directory, True, self.hparams.permute)
self.build_test_data_loader(download_directory)
else:
self.train_data, _, self.val_data = load_data(self.hparams.task, download_directory, False, self.hparams.permute)
return download_directory
def build_training_data_loader(self) -> DataLoader:
trainset = self.train_data
print(len(trainset))
train_loader = DataLoader(trainset, num_workers=4, batch_size=self.context.get_per_slot_batch_size(),
shuffle=True, sampler=None, collate_fn=_collate_fn,
pin_memory=False, drop_last=True)
print(len(train_loader))
return train_loader
def build_validation_data_loader(self) -> DataLoader:
valset = self.val_data
print(len(valset))
return DataLoader(valset, sampler=None, num_workers=4,
collate_fn=_collate_fn_eval,
shuffle=False, batch_size=1,
pin_memory=False
)
def build_test_data_loader(self, download_directory):
testset = self.test_data
print(len(testset))
#self.test_loader = torch.utils.data.DataLoader(testset, batch_size=self.context.get_per_slot_batch_size(),
# shuffle=False, num_workers=2)
return
'''
Train and Evaluate Methods
'''
def train_batch(self, batch: TorchData, epoch_idx: int, batch_idx: int
) -> Dict[str, torch.Tensor]:
x_train, _, y_train = batch
self.model.train()
output = self.model(x_train)
loss = self.criterion(output, y_train)
self.context.backward(loss)
self.context.step_optimizer(self.opt)
return {
'loss': loss,
}
def evaluate_full_dataset(
self, data_loader: torch.utils.data.DataLoader,
) -> Dict[str, Any]:
if not self.hparams.train and self.hparams.task == 'audio':
return self.evaluate_audio_testset(self.val_data)
loss_avg = utils_pt.AverageMeter()
val_predictions = []
val_gts = []
with torch.no_grad():
for batch in data_loader:
batch = self.context.to_device(batch)
input, target = batch
n = input.size(0)
logits = self.model(input)
logits = logits.mean(0).unsqueeze(0)
loss = self.criterion(logits, target)
#top1, top5 = utils_pt.accuracy(logits, target, topk=(1, 5))
#acc_top1.update(top1.item(), n)
#acc_top5.update(top5.item(), n)
loss_avg.update(loss, n)
logits_sigmoid = torch.sigmoid(logits)
val_predictions.append(logits_sigmoid.detach().cpu().numpy()[0])
val_gts.append(target.detach().cpu().numpy()[0])
val_preds = np.asarray(val_predictions).astype('float32')
val_gts = np.asarray(val_gts).astype('int32')
map_value = average_precision_score(val_gts, val_preds, average="macro")
results = {
"loss": loss_avg.avg,
"val_mAP": map_value,
}
'''
if self.hparams.train:
test_acc_top1 = utils_pt.AverageMeter()
test_acc_top5 = utils_pt.AverageMeter()
test_loss = utils_pt.AverageMeter()
with torch.no_grad():
for batch in self.test_loader:
batch = self.context.to_device(batch)
input, target = batch
n = input.size(0)
logits = self.model(input)
loss = self.criterion(logits, target)
top1, top5 = utils_pt.accuracy(logits, target, topk=(1, 5))
test_acc_top1.update(top1.item(), n)
test_acc_top5.update(top5.item(), n)
test_loss.update(loss, n)
results2 = {
"test_loss": test_loss.avg,
"test_top1_accuracy": test_acc_top1.avg,
"test_top5_accuracy": test_acc_top5.avg,
}
results.update(results2)
'''
if self.hparams.task == 'audio' and self.last_eval % 20 == 0:
results.update(self.evaluate_audio_testset(self.test_data))
self.last_eval += 1
return results
def evaluate_audio_testset(self, testset) -> Dict[str, torch.Tensor]:
cnt = 0
test_predictions = []
test_gts = []
for ix in range(testset.len):
with torch.no_grad():
batch = testset[ix]
x, y = batch
x = x.cuda()
y_pred = self.model(x)
y_pred = y_pred.mean(0).unsqueeze(0)
sigmoid_preds = torch.sigmoid(y_pred)
test_predictions.append(sigmoid_preds.detach().cpu().numpy()[0])
test_gts.append(y.detach().cpu().numpy()[0]) # drop batch axis
test_predictions = np.asarray(test_predictions).astype('float32')
test_gts = np.asarray(test_gts).astype('int32')
stats = calculate_stats(test_predictions, test_gts)
mAP = np.mean([stat['AP'] for stat in stats])
mAUC = np.mean([stat['auc'] for stat in stats])
results = {
"test_mAUC": mAUC,
"test_mAP": mAP,
}
return results
| 37.289199 | 167 | 0.594749 | import tempfile
from typing import Any, Dict, Sequence, Tuple, Union, cast
from functools import partial
import os
import boto3
import numpy as np
from sklearn.metrics import average_precision_score
import torch
from torch import nn
from determined.pytorch import DataLoader, PyTorchTrial, PyTorchTrialContext, LRScheduler
from backbone_pt import Backbone_Pt, Backbone_Audio
import utils_pt
from data_utils.load_data import load_data
from data_utils.download_data import download_from_s3
from data_utils.audio_dataset import *
from data_utils.audio_dataset import _collate_fn, _collate_fn_eval
TorchData = Union[Dict[str, torch.Tensor], Sequence[torch.Tensor], torch.Tensor]
def accuracy_rate(predictions: torch.Tensor, labels: torch.Tensor) -> float:
assert len(predictions) == len(labels), "Predictions and labels must have the same length."
assert len(labels.shape) == 1, "Labels must be a column vector."
return (
float((predictions.argmax(1) == labels.to(torch.long)).sum()) / predictions.shape[0]
)
class AttrDict(dict):
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
self.__dict__ = self
class BackboneTrial(PyTorchTrial):
def __init__(self, trial_context: PyTorchTrialContext) -> None:
self.context = trial_context
self.hparams = AttrDict(trial_context.get_hparams())
self.last_epoch = 0
self.download_directory = self.download_data_from_s3()
dataset_hypers = {'sEMG': (7, 1), 'ninapro': (18, 1), 'cifar10': (10, 3),
'smnist': (10, 1), 'cifar100':(100, 3), 'scifar100': (100, 3),
'audio': (200, 1)}
n_classes, in_channels = dataset_hypers[self.hparams.task]
print('task: ', self.hparams.task, 'in_channels: ', in_channels, 'classes: ', n_classes)
depth = list(map(int, self.hparams.backbone.split(',')))[0]
width = list(map(int, self.hparams.backbone.split(',')))[1]
if self.hparams.task == 'audio':
self.criterion = nn.BCEWithLogitsLoss().cuda()
self.backbone = Backbone_Audio(depth, n_classes, width,
dropRate=self.hparams.droprate, in_channels=in_channels)
else:
self.criterion = nn.CrossEntropyLoss().cuda()
self.backbone = Backbone_Pt(
depth,
n_classes,
width,
dropRate=self.hparams.droprate,
in_channels=in_channels,
)
total_params = sum(p.numel() for p in self.backbone.parameters() if p.requires_grad)/ 1e6
print('Parameter size in MB(backbone): ', total_params)
self.model = self.context.wrap_model(self.backbone)
self.last_eval = 0
nesterov = self.hparams.nesterov if self.hparams.momentum else False
self.opt = self.context.wrap_optimizer(torch.optim.SGD(
self.model.parameters(),
lr=self.hparams.learning_rate,
momentum=self.hparams.momentum,
weight_decay=self.hparams.weight_decay,
nesterov=nesterov)
)
self.lr_scheduler = self.context.wrap_lr_scheduler(
lr_scheduler=torch.optim.lr_scheduler.LambdaLR(
self.opt,
lr_lambda=self.weight_sched,
last_epoch=self.hparams.start_epoch - 1
),
step_mode=LRScheduler.StepMode.STEP_EVERY_EPOCH,
)
def weight_sched(self, epoch) -> Any:
if self.hparams.epochs != 200:
return 0.2 ** (epoch >= int(0.3 * self.hparams.epochs)) * 0.2 ** (epoch > int(0.6 * self.hparams.epochs)) * 0.2 ** (epoch > int(0.8 * self.hparams.epochs))
return 0.2 ** (epoch >= 60) * 0.2 ** (epoch >= 120) * 0.2 ** (epoch >=160)
def download_data_from_s3(self):
s3_bucket = self.context.get_data_config()["bucket"]
download_directory = os.getcwd()
s3 = boto3.client("s3")
download_from_s3(s3_bucket, self.hparams.task, download_directory)
if self.hparams.train:
self.train_data, self.val_data, self.test_data = load_data(self.hparams.task, download_directory, True, self.hparams.permute)
self.build_test_data_loader(download_directory)
else:
self.train_data, _, self.val_data = load_data(self.hparams.task, download_directory, False, self.hparams.permute)
return download_directory
def build_training_data_loader(self) -> DataLoader:
trainset = self.train_data
print(len(trainset))
train_loader = DataLoader(trainset, num_workers=4, batch_size=self.context.get_per_slot_batch_size(),
shuffle=True, sampler=None, collate_fn=_collate_fn,
pin_memory=False, drop_last=True)
print(len(train_loader))
return train_loader
def build_validation_data_loader(self) -> DataLoader:
valset = self.val_data
print(len(valset))
return DataLoader(valset, sampler=None, num_workers=4,
collate_fn=_collate_fn_eval,
shuffle=False, batch_size=1,
pin_memory=False
)
def build_test_data_loader(self, download_directory):
testset = self.test_data
print(len(testset))
return
def train_batch(self, batch: TorchData, epoch_idx: int, batch_idx: int
) -> Dict[str, torch.Tensor]:
x_train, _, y_train = batch
self.model.train()
output = self.model(x_train)
loss = self.criterion(output, y_train)
self.context.backward(loss)
self.context.step_optimizer(self.opt)
return {
'loss': loss,
}
def evaluate_full_dataset(
self, data_loader: torch.utils.data.DataLoader,
) -> Dict[str, Any]:
if not self.hparams.train and self.hparams.task == 'audio':
return self.evaluate_audio_testset(self.val_data)
loss_avg = utils_pt.AverageMeter()
val_predictions = []
val_gts = []
with torch.no_grad():
for batch in data_loader:
batch = self.context.to_device(batch)
input, target = batch
n = input.size(0)
logits = self.model(input)
logits = logits.mean(0).unsqueeze(0)
loss = self.criterion(logits, target)
loss_avg.update(loss, n)
logits_sigmoid = torch.sigmoid(logits)
val_predictions.append(logits_sigmoid.detach().cpu().numpy()[0])
val_gts.append(target.detach().cpu().numpy()[0])
val_preds = np.asarray(val_predictions).astype('float32')
val_gts = np.asarray(val_gts).astype('int32')
map_value = average_precision_score(val_gts, val_preds, average="macro")
results = {
"loss": loss_avg.avg,
"val_mAP": map_value,
}
if self.hparams.task == 'audio' and self.last_eval % 20 == 0:
results.update(self.evaluate_audio_testset(self.test_data))
self.last_eval += 1
return results
def evaluate_audio_testset(self, testset) -> Dict[str, torch.Tensor]:
cnt = 0
test_predictions = []
test_gts = []
for ix in range(testset.len):
with torch.no_grad():
batch = testset[ix]
x, y = batch
x = x.cuda()
y_pred = self.model(x)
y_pred = y_pred.mean(0).unsqueeze(0)
sigmoid_preds = torch.sigmoid(y_pred)
test_predictions.append(sigmoid_preds.detach().cpu().numpy()[0])
test_gts.append(y.detach().cpu().numpy()[0])
test_predictions = np.asarray(test_predictions).astype('float32')
test_gts = np.asarray(test_gts).astype('int32')
stats = calculate_stats(test_predictions, test_gts)
mAP = np.mean([stat['AP'] for stat in stats])
mAUC = np.mean([stat['auc'] for stat in stats])
results = {
"test_mAUC": mAUC,
"test_mAP": mAP,
}
return results
| true | true |
f731498360202437e8db6137f9cfaad521cd7f82 | 5,286 | py | Python | music_extractor.py | reeechart/ricommender | c5cdf1cb9db27b9fc4a2553aee2b705b9ad0b95a | [
"MIT"
] | null | null | null | music_extractor.py | reeechart/ricommender | c5cdf1cb9db27b9fc4a2553aee2b705b9ad0b95a | [
"MIT"
] | null | null | null | music_extractor.py | reeechart/ricommender | c5cdf1cb9db27b9fc4a2553aee2b705b9ad0b95a | [
"MIT"
] | null | null | null | import csv
import eyed3
import librosa
import numpy as np
import sys
def load_editorial_metadata(audiofile):
'''Loads an audio file and extract its editorial metadata
Args:
audiofile (string): audio file to be extracted.
Returns:
title (string): title of the mp3 file
artist (string): artist/singer of the song in mp3 file
album (string): name of album of the mp3 file
'''
audio = eyed3.load(audiofile)
return audio.tag.title, audio.tag.artist, audio.tag.album
def get_reformatted_music_file_directory(file):
'''Returns a reformatted music file directory
Args:
file (string): audio file directory to be reformatted
Returns:
directory (string): reformatted music file directory
'''
splitted_dir = file.split('\\')
directory = '/'.join(splitted_dir[-2:])
return directory
def extract_music_content(directory):
'''Extracts mp3 metadata from a specified directory
Args:
directory (string): directory that contains the mp3 files
Returns:
metadata ([string]): list of mp3 metadata with a structure of
(file, title, artist, album, mfcc, zcr, tempo, chroma_stft)
'''
all_metadata = [['id', 'file', 'title', 'artist', 'album', 'mfcc', 'zcr', 'tempo', 'pitch', 'chroma', 'num_frames']]
files = librosa.util.find_files(directory, ext='mp3')
for idx, file in enumerate(files):
print('Extracting ', file, '...')
music_metadata = []
music_metadata.append(idx)
title, artist, album = load_editorial_metadata(file)
music_metadata.append(get_reformatted_music_file_directory(file))
music_metadata.append(title)
music_metadata.append(artist)
music_metadata.append(album)
wf, sr = librosa.load(file)
mfcc = librosa.feature.mfcc(y=wf, sr=sr)
music_metadata.append(np.mean(mfcc))
zcr = librosa.feature.zero_crossing_rate(y=wf)
music_metadata.append(np.mean(zcr))
tempo = librosa.beat.tempo(y=wf, sr=sr)
music_metadata.append(tempo[0])
# Get pitches array and its corresponding power (magnitude)
pitches, magnitudes = librosa.piptrack(y=wf, sr=sr)
# Select pitches with high energy (bigger than its median)
pitches = pitches[magnitudes > np.median(magnitudes)]
pitch = librosa.pitch_tuning(pitches)
music_metadata.append(pitch)
chroma_stft = librosa.feature.chroma_stft(y=wf, sr=sr)
music_metadata.append(np.mean(chroma_stft))
music_metadata.append(len(mfcc[0]))
all_metadata.append(music_metadata)
return all_metadata
def extract_music_frames(directory):
'''Extracts mp3 metadata by frame
Args:
directory (string): directory that contains mp3 files
Returns:
metadata ([string]): all frames metadata
'''
all_metadata = [['id', 'mean_thirteen_first_mfcc', 'zcr', 'max_chroma']]
files = librosa.util.find_files(directory, ext='mp3')
for idx, file in enumerate(files):
print('Extracting ', file, '...')
title, artist, _ = load_editorial_metadata(file)
wf, sr = librosa.load(file)
mfcc = librosa.feature.mfcc(y=wf, sr=sr)
mfcc = np.mean(mfcc[:13], axis=0) # take the first 13 mfcc values
zcr = librosa.feature.zero_crossing_rate(y=wf)
zcr = np.mean(zcr, axis=0)
chroma_stft = librosa.feature.chroma_stft(y=wf, sr=sr)
chroma_stft_max = np.argmax(chroma_stft, axis=0)
for i in range(len(mfcc)):
music_frame_metadata = []
music_frame_metadata.append(idx)
music_frame_metadata.append(mfcc[i])
music_frame_metadata.append(zcr[i])
music_frame_metadata.append(chroma_stft_max[i])
all_metadata.append(music_frame_metadata)
return all_metadata
def save_to_csv(data, csv_file):
'''Saves data (list) to a csv file
Args:
data ([object]): list of metadata to be saved
'''
print('Saving metadata to ', csv_file, '...')
with open(csv_file, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(data)
def exit_with_msg(msg):
'''Exit with a custom message
Args:
msg (string): exit message
'''
print(msg)
sys.exit()
def check_arguments(argv):
'''Check arguments when running the program
Args:
argv ([string]): list of arguments
'''
if (len(argv) != 4):
exit_with_msg('Need 4 arguments to continue')
else:
extraction_type = sys.argv[1]
music_folder = sys.argv[2]
csv_file = sys.argv[3]
return extraction_type, music_folder, csv_file
# Main program
if __name__ == '__main__':
extraction_type, music_folder, csv_file = check_arguments(sys.argv)
if (extraction_type == 'extract_music'):
metadata = extract_music_content(music_folder)
save_to_csv(metadata, csv_file)
elif (extraction_type == 'extract_music_frame'):
metadata = extract_music_frames(music_folder)
save_to_csv(metadata, csv_file)
else:
exit_with_msg('Extraction type invalid, please use only \'extract_music\' or \'extract_music_frame\'')
| 30.034091 | 120 | 0.64756 | import csv
import eyed3
import librosa
import numpy as np
import sys
def load_editorial_metadata(audiofile):
audio = eyed3.load(audiofile)
return audio.tag.title, audio.tag.artist, audio.tag.album
def get_reformatted_music_file_directory(file):
splitted_dir = file.split('\\')
directory = '/'.join(splitted_dir[-2:])
return directory
def extract_music_content(directory):
all_metadata = [['id', 'file', 'title', 'artist', 'album', 'mfcc', 'zcr', 'tempo', 'pitch', 'chroma', 'num_frames']]
files = librosa.util.find_files(directory, ext='mp3')
for idx, file in enumerate(files):
print('Extracting ', file, '...')
music_metadata = []
music_metadata.append(idx)
title, artist, album = load_editorial_metadata(file)
music_metadata.append(get_reformatted_music_file_directory(file))
music_metadata.append(title)
music_metadata.append(artist)
music_metadata.append(album)
wf, sr = librosa.load(file)
mfcc = librosa.feature.mfcc(y=wf, sr=sr)
music_metadata.append(np.mean(mfcc))
zcr = librosa.feature.zero_crossing_rate(y=wf)
music_metadata.append(np.mean(zcr))
tempo = librosa.beat.tempo(y=wf, sr=sr)
music_metadata.append(tempo[0])
pitches, magnitudes = librosa.piptrack(y=wf, sr=sr)
pitches = pitches[magnitudes > np.median(magnitudes)]
pitch = librosa.pitch_tuning(pitches)
music_metadata.append(pitch)
chroma_stft = librosa.feature.chroma_stft(y=wf, sr=sr)
music_metadata.append(np.mean(chroma_stft))
music_metadata.append(len(mfcc[0]))
all_metadata.append(music_metadata)
return all_metadata
def extract_music_frames(directory):
all_metadata = [['id', 'mean_thirteen_first_mfcc', 'zcr', 'max_chroma']]
files = librosa.util.find_files(directory, ext='mp3')
for idx, file in enumerate(files):
print('Extracting ', file, '...')
title, artist, _ = load_editorial_metadata(file)
wf, sr = librosa.load(file)
mfcc = librosa.feature.mfcc(y=wf, sr=sr)
mfcc = np.mean(mfcc[:13], axis=0)
zcr = librosa.feature.zero_crossing_rate(y=wf)
zcr = np.mean(zcr, axis=0)
chroma_stft = librosa.feature.chroma_stft(y=wf, sr=sr)
chroma_stft_max = np.argmax(chroma_stft, axis=0)
for i in range(len(mfcc)):
music_frame_metadata = []
music_frame_metadata.append(idx)
music_frame_metadata.append(mfcc[i])
music_frame_metadata.append(zcr[i])
music_frame_metadata.append(chroma_stft_max[i])
all_metadata.append(music_frame_metadata)
return all_metadata
def save_to_csv(data, csv_file):
print('Saving metadata to ', csv_file, '...')
with open(csv_file, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(data)
def exit_with_msg(msg):
print(msg)
sys.exit()
def check_arguments(argv):
if (len(argv) != 4):
exit_with_msg('Need 4 arguments to continue')
else:
extraction_type = sys.argv[1]
music_folder = sys.argv[2]
csv_file = sys.argv[3]
return extraction_type, music_folder, csv_file
if __name__ == '__main__':
extraction_type, music_folder, csv_file = check_arguments(sys.argv)
if (extraction_type == 'extract_music'):
metadata = extract_music_content(music_folder)
save_to_csv(metadata, csv_file)
elif (extraction_type == 'extract_music_frame'):
metadata = extract_music_frames(music_folder)
save_to_csv(metadata, csv_file)
else:
exit_with_msg('Extraction type invalid, please use only \'extract_music\' or \'extract_music_frame\'')
| true | true |
f73149a9f7e2ac7a2e62263f32e4418400e4b260 | 2,624 | py | Python | src/old_code/utils_old.py | basarane/model-based-rl | af7ba84c272054d1de0b8cf9cc91b571abe91c3d | [
"MIT"
] | null | null | null | src/old_code/utils_old.py | basarane/model-based-rl | af7ba84c272054d1de0b8cf9cc91b571abe91c3d | [
"MIT"
] | null | null | null | src/old_code/utils_old.py | basarane/model-based-rl | af7ba84c272054d1de0b8cf9cc91b571abe91c3d | [
"MIT"
] | null | null | null | import keras.backend as K
import numpy as np
from PIL import Image, ImageDraw
def get_activations(model, model_inputs, print_shape_only=False, layer_name=None):
print('----- activations -----')
activations = []
inp = model.input
model_multi_inputs_cond = True
if not isinstance(inp, list):
# only one input! let's wrap it in a list.
inp = [inp]
model_multi_inputs_cond = False
#from pprint import pprint
#pprint(vars(model.layers[3]))
for layer in model.layers:
print(layer.name, len(layer.outbound_nodes), len(layer.inbound_nodes))
for I in range(len(layer.inbound_nodes)):
o1 = layer.get_output_at(I)
print(o1.name, o1.shape)
outputs = [[layer.get_output_at(I) for I in range(len(layer.inbound_nodes))] for layer in model.layers if (layer.name == layer_name or layer_name is None)]
outputs = [item for sublist in outputs for item in sublist]
#outputs.extend([])
funcs = [K.function(inp + [K.learning_phase()], [out]) for out in outputs] # evaluation functions
if model_multi_inputs_cond:
list_inputs = []
list_inputs.extend(model_inputs)
list_inputs.append(0.)
else:
list_inputs = [model_inputs, 0.]
print("model_multi_inputs_cond", model_multi_inputs_cond, len(list_inputs))
# Learning phase. 0 = Test mode (no dropout or batch normalization)
# layer_outputs = [func([model_inputs, 0.])[0] for func in funcs]
layer_outputs = [func(list_inputs)[0] for func in funcs]
for layer_activations in layer_outputs:
activations.append(layer_activations)
if print_shape_only:
print(layer_activations.shape)
else:
print(layer_activations)
return activations
def toRGBImage(x):
im = Image.fromarray(x)
im = im.convert('RGB')
return np.array(im, dtype='uint8')
def prediction_to_image(prediction, meanImage):
predOutput = np.array(prediction)*255.0
predOutput = predOutput + meanImage
predOutput[predOutput<0] = 0
predOutput[predOutput>255] = 255
predOutput = np.array(predOutput, dtype="uint8")
predImage = np.squeeze(predOutput)
return predImage
def draw_reward(predImage, reward):
im = Image.fromarray(predImage)
draw = ImageDraw.Draw(im)
w = 100
x = 57
draw.rectangle([x,196,x+int(w*reward),208], "#fff", None)
draw.rectangle([x,196,x+w,208], None, "#f00")
predImage = np.array(im)
return predImage
def get_obs_input(lastFramesOrig, meanImage):
netin = np.array(lastFramesOrig, dtype='f')/255.0
netin = np.squeeze(netin)
netin = np.transpose(netin, (0,3,1,2))
netin = np.reshape(netin, (12, 210,160))
netin = netin - np.tile(np.transpose(meanImage/255.0, (2,0,1)), (4,1,1))
netin = np.reshape(netin, (1, 12, 210,160))
return netin
| 32 | 156 | 0.726372 | import keras.backend as K
import numpy as np
from PIL import Image, ImageDraw
def get_activations(model, model_inputs, print_shape_only=False, layer_name=None):
print('----- activations -----')
activations = []
inp = model.input
model_multi_inputs_cond = True
if not isinstance(inp, list):
inp = [inp]
model_multi_inputs_cond = False
#from pprint import pprint
#pprint(vars(model.layers[3]))
for layer in model.layers:
print(layer.name, len(layer.outbound_nodes), len(layer.inbound_nodes))
for I in range(len(layer.inbound_nodes)):
o1 = layer.get_output_at(I)
print(o1.name, o1.shape)
outputs = [[layer.get_output_at(I) for I in range(len(layer.inbound_nodes))] for layer in model.layers if (layer.name == layer_name or layer_name is None)]
outputs = [item for sublist in outputs for item in sublist]
#outputs.extend([])
funcs = [K.function(inp + [K.learning_phase()], [out]) for out in outputs] # evaluation functions
if model_multi_inputs_cond:
list_inputs = []
list_inputs.extend(model_inputs)
list_inputs.append(0.)
else:
list_inputs = [model_inputs, 0.]
print("model_multi_inputs_cond", model_multi_inputs_cond, len(list_inputs))
# Learning phase. 0 = Test mode (no dropout or batch normalization)
# layer_outputs = [func([model_inputs, 0.])[0] for func in funcs]
layer_outputs = [func(list_inputs)[0] for func in funcs]
for layer_activations in layer_outputs:
activations.append(layer_activations)
if print_shape_only:
print(layer_activations.shape)
else:
print(layer_activations)
return activations
def toRGBImage(x):
im = Image.fromarray(x)
im = im.convert('RGB')
return np.array(im, dtype='uint8')
def prediction_to_image(prediction, meanImage):
predOutput = np.array(prediction)*255.0
predOutput = predOutput + meanImage
predOutput[predOutput<0] = 0
predOutput[predOutput>255] = 255
predOutput = np.array(predOutput, dtype="uint8")
predImage = np.squeeze(predOutput)
return predImage
def draw_reward(predImage, reward):
im = Image.fromarray(predImage)
draw = ImageDraw.Draw(im)
w = 100
x = 57
draw.rectangle([x,196,x+int(w*reward),208], "#fff", None)
draw.rectangle([x,196,x+w,208], None, "#f00")
predImage = np.array(im)
return predImage
def get_obs_input(lastFramesOrig, meanImage):
netin = np.array(lastFramesOrig, dtype='f')/255.0
netin = np.squeeze(netin)
netin = np.transpose(netin, (0,3,1,2))
netin = np.reshape(netin, (12, 210,160))
netin = netin - np.tile(np.transpose(meanImage/255.0, (2,0,1)), (4,1,1))
netin = np.reshape(netin, (1, 12, 210,160))
return netin
| true | true |
f73149c06418dfdcc2ccc576f2c8e8c48e6bdbd1 | 1,157 | py | Python | saleor/graphql/page/schema.py | acabezasg/urpi-master | 7c9cd0fbe6d89dad70652482712ca38b21ba6f84 | [
"BSD-3-Clause"
] | 1 | 2019-04-15T09:37:26.000Z | 2019-04-15T09:37:26.000Z | saleor/graphql/page/schema.py | acabezasg/urpi-master | 7c9cd0fbe6d89dad70652482712ca38b21ba6f84 | [
"BSD-3-Clause"
] | 5 | 2021-03-09T16:22:37.000Z | 2022-02-10T19:10:03.000Z | saleor/graphql/page/schema.py | acabezasg/urpi-master | 7c9cd0fbe6d89dad70652482712ca38b21ba6f84 | [
"BSD-3-Clause"
] | 1 | 2020-12-26T10:25:37.000Z | 2020-12-26T10:25:37.000Z | import graphene
from ..core.fields import PrefetchingConnectionField
from ..descriptions import DESCRIPTIONS
from ..translations.mutations import PageTranslate
from .bulk_mutations import PageBulkDelete
from .mutations import PageCreate, PageDelete, PageUpdate
from .resolvers import resolve_page, resolve_pages
from .types import Page
class PageQueries(graphene.ObjectType):
page = graphene.Field(
Page, id=graphene.Argument(graphene.ID), slug=graphene.String(),
description='Lookup a page by ID or by slug.')
pages = PrefetchingConnectionField(
Page, query=graphene.String(
description=DESCRIPTIONS['page']),
description='List of the shop\'s pages.')
def resolve_page(self, info, id=None, slug=None):
return resolve_page(info, id, slug)
def resolve_pages(self, info, query=None, **kwargs):
return resolve_pages(info, query=query)
class PageMutations(graphene.ObjectType):
page_create = PageCreate.Field()
page_delete = PageDelete.Field()
page_bulk_delete = PageBulkDelete.Field()
page_update = PageUpdate.Field()
page_translate = PageTranslate.Field()
| 34.029412 | 72 | 0.736387 | import graphene
from ..core.fields import PrefetchingConnectionField
from ..descriptions import DESCRIPTIONS
from ..translations.mutations import PageTranslate
from .bulk_mutations import PageBulkDelete
from .mutations import PageCreate, PageDelete, PageUpdate
from .resolvers import resolve_page, resolve_pages
from .types import Page
class PageQueries(graphene.ObjectType):
page = graphene.Field(
Page, id=graphene.Argument(graphene.ID), slug=graphene.String(),
description='Lookup a page by ID or by slug.')
pages = PrefetchingConnectionField(
Page, query=graphene.String(
description=DESCRIPTIONS['page']),
description='List of the shop\'s pages.')
def resolve_page(self, info, id=None, slug=None):
return resolve_page(info, id, slug)
def resolve_pages(self, info, query=None, **kwargs):
return resolve_pages(info, query=query)
class PageMutations(graphene.ObjectType):
page_create = PageCreate.Field()
page_delete = PageDelete.Field()
page_bulk_delete = PageBulkDelete.Field()
page_update = PageUpdate.Field()
page_translate = PageTranslate.Field()
| true | true |
f73149da213043c623eaf8c02ac1225d022f99d9 | 69,506 | py | Python | server/datasets/tcga/constants.py | imwangtongxue-com/digital_slide_archive | 3c08432bf3ca192d8948cbe22a263c2259c542d5 | [
"Apache-2.0"
] | null | null | null | server/datasets/tcga/constants.py | imwangtongxue-com/digital_slide_archive | 3c08432bf3ca192d8948cbe22a263c2259c542d5 | [
"Apache-2.0"
] | null | null | null | server/datasets/tcga/constants.py | imwangtongxue-com/digital_slide_archive | 3c08432bf3ca192d8948cbe22a263c2259c542d5 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright Kitware 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.
###############################################################################
# flake8: noqa: E501
class TcgaCodes(object):
DISEASE_STUDIES = {
# 'Study Abbreviation': 'Study Name',
'LAML': 'Acute Myeloid Leukemia',
'ACC': 'Adrenocortical carcinoma',
'BLCA': 'Bladder Urothelial Carcinoma',
'LGG': 'Brain Lower Grade Glioma',
'BRCA': 'Breast invasive carcinoma',
'CESC': 'Cervical squamous cell carcinoma and endocervical adenocarcinoma',
'CHOL': 'Cholangiocarcinoma',
'LCML': 'Chronic Myelogenous Leukemia',
'COAD': 'Colon adenocarcinoma',
'CNTL': 'Controls',
'ESCA': 'Esophageal carcinoma ',
'FPPP': 'FFPE Pilot Phase II',
'GBM': 'Glioblastoma multiforme',
'HNSC': 'Head and Neck squamous cell carcinoma',
'KICH': 'Kidney Chromophobe',
'KIRC': 'Kidney renal clear cell carcinoma',
'KIRP': 'Kidney renal papillary cell carcinoma',
'LIHC': 'Liver hepatocellular carcinoma',
'LUAD': 'Lung adenocarcinoma',
'LUSC': 'Lung squamous cell carcinoma',
'DLBC': 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma',
'MESO': 'Mesothelioma',
'MISC': 'Miscellaneous',
'OV': 'Ovarian serous cystadenocarcinoma',
'PAAD': 'Pancreatic adenocarcinoma',
'PCPG': 'Pheochromocytoma and Paraganglioma',
'PRAD': 'Prostate adenocarcinoma',
'READ': 'Rectum adenocarcinoma',
'SARC': 'Sarcoma',
'SKCM': 'Skin Cutaneous Melanoma',
'STAD': 'Stomach adenocarcinoma',
'TGCT': 'Testicular Germ Cell Tumors',
'THYM': 'Thymoma',
'THCA': 'Thyroid carcinoma',
'UCS': 'Uterine Carcinosarcoma',
'UCEC': 'Uterine Corpus Endometrial Carcinoma',
'UVM': 'Uveal Melanoma',
}
REPOSITORY_TYPES = {
'bcr', # 'Biospecimen Core Resource'
'cgcc',
'gsc',
}
DATA_PROVIDERS = {
'biotab', # Clinical metadata, skip
'intgen.org',
'nationwidechildrens.org',
'genome.wustl.edu',
'supplemental' # unknown, appears under 'tumor/ov/bcr/', skip
}
DATA_TYPES = {
'bio', # XML format clinical metadata, skip
'biotab', # CSV format clinical metadata, skip
'pathology_reports', # PDF format pathology reports, skip
'diagnostic_images', # SVS format images, use
'tissue_images', # SVS format images, use
'minbio' # unknown, appears under 'tumor/gbm/bcr/intgen.org/', skip
}
SLIDE_LOCATION = {
'TS': 'Top Slide',
'MS': 'Middle Slide',
'BS': 'Bottom Slide',
'DX': 'Top Slide',
}
TISSUE_SOURCE_SITE = {
# 'TSS Code': ('Source Site', 'Study Name', 'BCR'),
'01': ('International Genomics Consortium', 'Ovarian serous cystadenocarcinoma', 'IGC'),
'02': ('MD Anderson Cancer Center', 'Glioblastoma multiforme', 'IGC'),
'04': ('Gynecologic Oncology Group', 'Ovarian serous cystadenocarcinoma', 'IGC'),
'05': ('Indivumed', 'Lung adenocarcinoma', 'IGC'),
'06': ('Henry Ford Hospital', 'Glioblastoma multiforme', 'IGC'),
'07': ('TGen', 'Cell Line Control', 'IGC'),
'08': ('UCSF', 'Glioblastoma multiforme', 'IGC'),
'09': ('UCSF', 'Ovarian serous cystadenocarcinoma', 'IGC'),
'10': ('MD Anderson Cancer Center', 'Ovarian serous cystadenocarcinoma', 'IGC'),
'11': ('MD Anderson Cancer Center', 'Lung squamous cell carcinoma', 'IGC'),
'12': ('Duke', 'Glioblastoma multiforme', 'IGC'),
'13': ('Memorial Sloan Kettering', 'Ovarian serous cystadenocarcinoma', 'IGC'),
'14': ('Emory University', 'Glioblastoma multiforme', 'IGC'),
'15': ('Mayo Clinic - Rochester', 'Glioblastoma multiforme', 'IGC'),
'16': ('Toronto Western Hospital', 'Glioblastoma multiforme', 'IGC'),
'17': ('Washington University', 'Lung adenocarcinoma', 'IGC'),
'18': ('Princess Margaret Hospital (Canada)', 'Lung squamous cell carcinoma', 'IGC'),
'19': ('Case Western', 'Glioblastoma multiforme', 'IGC'),
'1Z': ('Johns Hopkins', 'Thymoma', 'NCH'),
'20': ('Fox Chase Cancer Center', 'Ovarian serous cystadenocarcinoma', 'IGC'),
'21': ('Fox Chase Cancer Center', 'Lung squamous cell carcinoma', 'IGC'),
'22': ('Mayo Clinic - Rochester', 'Lung squamous cell carcinoma', 'IGC'),
'23': ('Cedars Sinai', 'Ovarian serous cystadenocarcinoma', 'IGC'),
'24': ('Washington University', 'Ovarian serous cystadenocarcinoma', 'IGC'),
'25': ('Mayo Clinic - Rochester', 'Ovarian serous cystadenocarcinoma', 'IGC'),
'26': ('University of Florida', 'Glioblastoma multiforme', 'IGC'),
'27': ('Milan - Italy, Fondazione IRCCS Instituto Neuroligico C. Besta', 'Glioblastoma multiforme', 'IGC'),
'28': ('Cedars Sinai', 'Glioblastoma multiforme', 'IGC'),
'29': ('Duke', 'Ovarian serous cystadenocarcinoma', 'IGC'),
'2A': ('Memorial Sloan Kettering Cancer Center', 'Prostate adenocarcinoma', 'NCH'),
'2E': ('University of Kansas Medical Center', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'2F': ('Erasmus MC', 'Bladder Urothelial Carcinoma', 'NCH'),
'2G': ('Erasmus MC', 'Testicular Germ Cell Tumors', 'NCH'),
'2H': ('Erasmus MC', 'Esophageal carcinoma ', 'NCH'),
'2J': ('Mayo Clinic', 'Pancreatic adenocarcinoma', 'NCH'),
'2K': ('Greenville Health System', 'Kidney renal papillary cell carcinoma', 'NCH'),
'2L': ('Technical University of Munich', 'Pancreatic adenocarcinoma', 'NCH'),
'2M': ('Technical University of Munich', 'Esophageal carcinoma ', 'NCH'),
'2N': ('Technical University of Munich', 'Stomach adenocarcinoma', 'NCH'),
'2P': ('University of California San Diego', 'Pancreatic adenocarcinoma', 'NCH'),
'2V': ('University of California San Diego', 'Liver hepatocellular carcinoma', 'NCH'),
'2W': ('University of New Mexico', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'2X': ('ABS IUPUI', 'Testicular Germ Cell Tumors', 'NCH'),
'2Y': ('Moffitt Cancer Center', 'Liver hepatocellular carcinoma', 'NCH'),
'2Z': ('Moffitt Cancer Center', 'Kidney renal papillary cell carcinoma', 'NCH'),
'30': ('Harvard', 'Ovarian serous cystadenocarcinoma', 'IGC'),
'31': ('Imperial College', 'Ovarian serous cystadenocarcinoma', 'IGC'),
'32': ('St. Joseph\'s Hospital (AZ)', 'Glioblastoma multiforme', 'IGC'),
'33': ('Johns Hopkins', 'Lung squamous cell carcinoma', 'IGC'),
'34': ('University of Pittsburgh', 'Lung squamous cell carcinoma', 'IGC'),
'35': ('Cureline', 'Lung adenocarcinoma', 'IGC'),
'36': ('BC Cancer Agency', 'Ovarian serous cystadenocarcinoma', 'IGC'),
'37': ('Cureline', 'Lung squamous cell carcinoma', 'IGC'),
'38': ('UNC', 'Lung adenocarcinoma', 'IGC'),
'39': ('MSKCC', 'Lung squamous cell carcinoma', 'IGC'),
'3A': ('Moffitt Cancer Center', 'Pancreatic adenocarcinoma', 'NCH'),
'3B': ('Moffitt Cancer Center', 'Sarcoma', 'NCH'),
'3C': ('Columbia University', 'Breast invasive carcinoma', 'NCH'),
'3E': ('Columbia University', 'Pancreatic adenocarcinoma', 'NCH'),
'3G': ('MD Anderson Cancer Center', 'Thymoma', 'NCH'),
'3H': ('MD Anderson Cancer Center', 'Mesothelioma', 'NCH'),
'3J': ('Carle Cancer Center', 'Breast invasive carcinoma', 'NCH'),
'3K': ('Boston Medical Center', 'Liver hepatocellular carcinoma', 'NCH'),
'3L': ('Albert Einstein Medical Center', 'Colon adenocarcinoma', 'NCH'),
'3M': ('University of Kansas Medical Center', 'Stomach adenocarcinoma', 'NCH'),
'3N': ('Greenville Health System', 'Skin Cutaneous Melanoma', 'NCH'),
'3P': ('Greenville Health System', 'Ovarian serous cystadenocarcinoma', 'NCH'),
'3Q': ('Greenville Health Systems', 'Thymoma', 'NCH'),
'3R': ('University of New Mexico', 'Sarcoma', 'NCH'),
'3S': ('University of New Mexico', 'Thymoma', 'NCH'),
'3T': ('Emory University', 'Thymoma', 'NCH'),
'3U': ('University of Chicago', 'Mesothelioma', 'NCH'),
'3W': ('University of California San Diego', 'Sarcoma', 'NCH'),
'3X': ('Alberta Health Services', 'Cholangiocarcinoma', 'NCH'),
'3Z': ('Mary Bird Perkins Cancer Center - Our Lady of the Lake', 'Kidney renal clear cell carcinoma', 'NCH'),
'41': ('Christiana Healthcare', 'Glioblastoma multiforme', 'IGC'),
'42': ('Christiana Healthcare', 'Ovarian serous cystadenocarcinoma', 'IGC'),
'43': ('Christiana Healthcare', 'Lung squamous cell carcinoma', 'IGC'),
'44': ('Christiana Healthcare', 'Lung adenocarcinoma', 'IGC'),
'46': ('St. Joseph\'s Medical Center (MD)', 'Lung squamous cell carcinoma', 'IGC'),
'49': ('Johns Hopkins', 'Lung adenocarcinoma', 'IGC'),
'4A': ('Mary Bird Perkins Cancer Center - Our Lady of the Lake', 'Kidney renal papillary cell carcinoma', 'NCH'),
'4B': ('Mary Bird Perkins Cancer Center - Our Lady of the Lake', 'Lung adenocarcinoma', 'NCH'),
'4C': ('Mary Bird Perkins Cancer Center - Our Lady of the Lake', 'Thyroid carcinoma', 'NCH'),
'4D': ('Molecular Response', 'Ovarian serous cystadenocarcinoma', 'NCH'),
'4E': ('Molecular Response', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'4G': ('Sapienza University of Rome', 'Cholangiocarcinoma', 'NCH'),
'4H': ('Proteogenex, Inc.', 'Breast invasive carcinoma', 'NCH'),
'4J': ('Proteogenex, Inc.', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'4K': ('Proteogenex, Inc.', 'Testicular Germ Cell Tumors', 'NCH'),
'4L': ('Proteogenex, Inc.', 'Prostate adenocarcinoma', 'NCH'),
'4N': ('Mary Bird Perkins Cancer Center - Our Lady of the Lake', 'Colon adenocarcinoma', 'NCH'),
'4P': ('Duke University', 'Head and Neck squamous cell carcinoma', 'NCH'),
'4Q': ('Duke University', 'Sarcoma', 'NCH'),
'4R': ('Duke University', 'Liver hepatocellular carcinoma', 'NCH'),
'4S': ('Duke University', 'Prostate adenocarcinoma', 'NCH'),
'4T': ('Duke University', 'Colon adenocarcinoma', 'NCH'),
'4V': ('Hospital Louis Pradel', 'Thymoma', 'NCH'),
'4W': ('University of Miami', 'Glioblastoma multiforme', 'NCH'),
'4X': ('Yale University', 'Thymoma', 'NCH'),
'4Y': ('Medical College of Wisconsin', 'Sarcoma', 'NCH'),
'4Z': ('Barretos Cancer Hospital', 'Bladder Urothelial Carcinoma', 'NCH'),
'50': ('University of Pittsburgh', 'Lung adenocarcinoma', 'IGC'),
'51': ('UNC', 'Lung squamous cell carcinoma', 'IGC'),
'52': ('University of Miami', 'Lung squamous cell carcinoma', 'IGC'),
'53': ('University of Miami', 'Lung adenocarcinoma', 'IGC'),
'55': ('International Genomics Consortium', 'Lung adenocarcinoma', 'IGC'),
'56': ('International Genomics Consortium', 'Lung squamous cell carcinoma', 'IGC'),
'57': ('International Genomics Consortium', 'Ovarian serous cystadenocarcinoma', 'IGC'),
'58': ('Thoraxklinik at University Hospital Heidelberg', 'Lung squamous cell carcinoma', 'IGC'),
'59': ('Roswell Park', 'Ovarian serous cystadenocarcinoma', 'IGC'),
'5A': ('Wake Forest University', 'Cholangiocarcinoma', 'NCH'),
'5B': ('Medical College of Wisconsin', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'5C': ('Cureline', 'Liver hepatocellular carcinoma', 'NCH'),
'5D': ('University of Miami', 'Sarcoma', 'NCH'),
'5F': ('Duke University', 'Thyroid carcinoma', 'NCH'),
'5G': ('Cleveland Clinic Foundation', 'Thymoma', 'NCH'),
'5H': ('Retina Consultants Houston', 'Uveal Melanoma', 'NCH'),
'5J': ('Cureline', 'Acute Myeloid Leukemia', 'NCH'),
'5K': ('St. Joseph\'s Hospital AZ', 'Thymoma', 'NCH'),
'5L': ('University of Sao Paulo', 'Breast invasive carcinoma', 'NCH'),
'5M': ('University of Sao Paulo', 'Colon adenocarcinoma', 'NCH'),
'5N': ('University Hospital Erlangen', 'Bladder Urothelial Carcinoma', 'NCH'),
'5P': ('University Hospital Erlangen', 'Kidney renal papillary cell carcinoma', 'NCH'),
'5Q': ('Proteogenex, Inc', 'Pancreatic adenocarcinoma', 'NCH'),
'5R': ('Proteogenex, Inc', 'Liver hepatocellular carcinoma', 'NCH'),
'5S': ('Holy Cross', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'5T': ('Holy Cross', 'Breast invasive carcinoma', 'NCH'),
'5U': ('Regina Elena National Cancer Institute', 'Thymoma', 'NCH'),
'5V': ('Roswell Park', 'Thymoma', 'NCH'),
'5W': ('University of Alabama', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'5X': ('University of Alabama', 'Ovarian serous cystadenocarcinoma', 'NCH'),
'60': ('Roswell Park', 'Lung squamous cell carcinoma', 'IGC'),
'61': ('University of Pittsburgh', 'Ovarian serous cystadenocarcinoma', 'IGC'),
'62': ('Thoraxklinik at University Hospital Heidelberg', 'Lung adenocarcinoma', 'IGC'),
'63': ('Ontario Institute for Cancer Research', 'Lung squamous cell carcinoma', 'IGC'),
'64': ('Fox Chase', 'Lung adenocarcinoma', 'IGC'),
'65': ('Roswell Park', 'Glioblastoma multiforme', 'IGC'),
'66': ('Indivumed', 'Lung squamous cell carcinoma', 'IGC'),
'67': ('St Joseph\'s Medical Center (MD)', 'Lung adenocarcinoma', 'IGC'),
'68': ('Washington University - Cleveland Clinic', 'Lung squamous cell carcinoma', 'IGC'),
'69': ('Washington University - Cleveland Clinic', 'Lung adenocarcinoma', 'IGC'),
'6A': ('University of Kansas', 'Lung squamous cell carcinoma', 'NCH'),
'6D': ('University of Oklahoma HSC', 'Kidney renal clear cell carcinoma', 'NCH'),
'6G': ('University of Sao Paulo', 'Rectum adenocarcinoma', 'NCH'),
'70': ('ILSBio', 'Lung squamous cell carcinoma', 'IGC'),
'71': ('ILSBio', 'Lung adenocarcinoma', 'IGC'),
'72': ('NCH', 'Ovarian serous cystadenocarcinoma', 'IGC'),
'73': ('Roswell Park', 'Lung adenocarcinoma', 'IGC'),
'74': ('Swedish Neurosciences', 'Glioblastoma multiforme', 'IGC'),
'75': ('Ontario Institute for Cancer Research (OICR)', 'Lung adenocarcinoma', 'IGC'),
'76': ('Thomas Jefferson University', 'Glioblastoma multiforme', 'IGC'),
'77': ('Prince Charles Hospital', 'Lung squamous cell carcinoma', 'IGC'),
'78': ('Prince Charles Hospital', 'Lung adenocarcinoma', 'IGC'),
'79': ('Ontario Institute for Cancer Research (OICR)/Ottawa', 'Lung squamous cell carcinoma', 'IGC'),
'80': ('Ontario Institute for Cancer Research (OICR)/Ottawa', 'Lung adenocarcinoma', 'IGC'),
'81': ('CHI-Penrose Colorado', 'Glioblastoma multiforme', 'IGC'),
'82': ('CHI-Penrose Colorado', 'Lung squamous cell carcinoma', 'IGC'),
'83': ('CHI-Penrose Colorado', 'Lung adenocarcinoma', 'IGC'),
'85': ('Asterand', 'Lung squamous cell carcinoma', 'IGC'),
'86': ('Asterand', 'Lung adenocarcinoma', 'IGC'),
'87': ('International Genomics Consortium', 'Glioblastoma multiforme', 'IGC'),
'90': ('ABS - IUPUI', 'Lung squamous cell carcinoma', 'IGC'),
'91': ('ABS - IUPUI', 'Lung adenocarcinoma', 'IGC'),
'92': ('Washington University - St. Louis', 'Lung squamous cell carcinoma', 'IGC'),
'93': ('Washington University - St. Louis', 'Lung adenocarcinoma', 'IGC'),
'94': ('Washington University - Emory', 'Lung squamous cell carcinoma', 'IGC'),
'95': ('Washington University - Emory', 'Lung adenocarcinoma', 'IGC'),
'96': ('Washington University - NYU', 'Lung squamous cell carcinoma', 'IGC'),
'97': ('Washington University - NYU', 'Lung adenocarcinoma', 'IGC'),
'98': ('Washington University - Alabama', 'Lung squamous cell carcinoma', 'IGC'),
'99': ('Washington University - Alabama', 'Lung adenocarcinoma', 'IGC'),
'A1': ('UCSF', 'Breast invasive carcinoma', 'NCH'),
'A2': ('Walter Reed', 'Breast invasive carcinoma', 'NCH'),
'A3': ('International Genomics Consortium', 'Kidney renal clear cell carcinoma', 'IGC'),
'A4': ('International Genomics Consortium', 'Kidney renal papillary cell carcinoma', 'IGC'),
'A5': ('Cedars Sinai', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'A6': ('Christiana Healthcare', 'Colon adenocarcinoma', 'IGC'),
'A7': ('Christiana Healthcare', 'Breast invasive carcinoma', 'NCH'),
'A8': ('Indivumed', 'Breast invasive carcinoma', 'NCH'),
'AA': ('Indivumed', 'Colon adenocarcinoma', 'IGC'),
'AB': ('Washington University', 'Acute Myeloid Leukemia', 'NCH'),
'AC': ('International Genomics Consortium', 'Breast invasive carcinoma', 'NCH'),
'AD': ('International Genomics Consortium', 'Colon adenocarcinoma', 'IGC'),
'AF': ('Christiana Healthcare', 'Rectum adenocarcinoma', 'IGC'),
'AG': ('Indivumed', 'Rectum adenocarcinoma', 'IGC'),
'AH': ('International Genomics Consortium', 'Rectum adenocarcinoma', 'IGC'),
'AJ': ('International Genomics Conosrtium', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'AK': ('Fox Chase', 'Kidney renal clear cell carcinoma', 'IGC'),
'AL': ('Fox Chase', 'Kidney renal papillary cell carcinoma', 'IGC'),
'AM': ('Cureline', 'Colon adenocarcinoma', 'IGC'),
'AN': ('Cureline', 'Breast invasive carcinoma', 'NCH'),
'AO': ('MSKCC', 'Breast invasive carcinoma', 'NCH'),
'AP': ('MSKCC', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'AQ': ('UNC ', 'Breast invasive carcinoma', 'NCH'),
'AR': ('Mayo', 'Breast invasive carcinoma', 'NCH'),
'AS': ('St. Joseph\'s Medical Center-(MD)', 'Kidney renal clear cell carcinoma', 'IGC'),
'AT': ('St. Joseph\'s Medical Center-(MD)', 'Kidney renal papillary cell carcinoma', 'IGC'),
'AU': ('St. Joseph\'s Medical Center-(MD)', 'Colon adenocarcinoma', 'IGC'),
'AV': ('NCH', 'Cell Line Control', 'NCH'),
'AW': ('Cureline', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'AX': ('Gynecologic Oncology Group', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'AY': ('UNC', 'Colon adenocarcinoma', 'IGC'),
'AZ': ('University of Pittsburgh', 'Colon adenocarcinoma', 'IGC'),
'B0': ('University of Pittsburgh', 'Kidney renal clear cell carcinoma', 'IGC'),
'B1': ('University of Pittsburgh', 'Kidney renal papillary cell carcinoma', 'IGC'),
'B2': ('Christiana Healthcare', 'Kidney renal clear cell carcinoma', 'IGC'),
'B3': ('Christiana Healthcare', 'Kidney renal papillary cell carcinoma', 'IGC'),
'B4': ('Cureline', 'Kidney renal clear cell carcinoma', 'IGC'),
'B5': ('Duke', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'B6': ('Duke', 'Breast invasive carcinoma', 'NCH'),
'B7': ('Cureline', 'Stomach adenocarcinoma', 'IGC'),
'B8': ('UNC', 'Kidney renal clear cell carcinoma', 'IGC'),
'B9': ('UNC', 'Kidney renal papillary cell carcinoma', 'IGC'),
'BA': ('UNC', 'Head and Neck squamous cell carcinoma', 'IGC'),
'BB': ('Johns Hopkins', 'Head and Neck squamous cell carcinoma', 'IGC'),
'BC': ('UNC', 'Liver hepatocellular carcinoma', 'NCH'),
'BD': ('University of Pittsburgh', 'Liver hepatocellular carcinoma', 'NCH'),
'BF': ('Cureline', 'Skin Cutaneous Melanoma', 'NCH'),
'BG': ('University of Pittsburgh', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'BH': ('University of Pittsburgh', 'Breast invasive carcinoma', 'NCH'),
'BI': ('University of Pittsburgh', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'BJ': ('University of Pittsburgh', 'Thyroid carcinoma', 'IGC'),
'BK': ('Christiana Healthcare', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'BL': ('Christiana Healthcare', 'Bladder Urothelial Carcinoma', 'NCH'),
'BM': ('UNC', 'Rectum adenocarcinoma', 'IGC'),
'BP': ('MSKCC', 'Kidney renal clear cell carcinoma', 'IGC'),
'BQ': ('MSKCC', 'Kidney renal papillary cell carcinoma', 'IGC'),
'BR': ('Asterand', 'Stomach adenocarcinoma', 'IGC'),
'BS': ('University of Hawaii', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'BT': ('University of Pittsburgh', 'Bladder Urothelial Carcinoma', 'NCH'),
'BW': ('St. Joseph\'s Medical Center-(MD)', 'Liver hepatocellular carcinoma', 'NCH'),
'C4': ('Indivumed', 'Bladder Urothelial Carcinoma', 'NCH'),
'C5': ('Medical College of Wisconsin', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'C8': ('ILSBio', 'Breast invasive carcinoma', 'NCH'),
'C9': ('ILSBio', 'Head and Neck squamous cell carcinoma', 'NCH'),
'CA': ('ILSBio', 'Colon adenocarcinoma', 'IGC'),
'CB': ('ILSBio', 'Kidney renal clear cell carcinoma', 'IGC'),
'CC': ('ILSBio', 'Liver hepatocellular carcinoma', 'NCH'),
'CD': ('ILSBio', 'Stomach adenocarcinoma', 'IGC'),
'CE': ('ILSBio', 'Thyroid carcinoma', 'IGC'),
'CF': ('ILSBio', 'Bladder Urothelial Carcinoma', 'NCH'),
'CG': ('Indivumed', 'Stomach adenocarcinoma', 'IGC'),
'CH': ('Indivumed', 'Prostate adenocarcinoma', 'IGC'),
'CI': ('University of Pittsburgh', 'Rectum adenocarcinoma', 'IGC'),
'CJ': ('MD Anderson Cancer Center', 'Kidney renal clear cell carcinoma', 'IGC'),
'CK': ('Harvard', 'Colon adenocarcinoma', 'IGC'),
'CL': ('Harvard', 'Rectum adenocarcinoma', 'IGC'),
'CM': ('MSKCC', 'Colon adenocarcinoma', 'IGC'),
'CN': ('University of Pittsburgh', 'Head and Neck squamous cell carcinoma', 'IGC'),
'CQ': ('University Health Network, Toronto', 'Head and Neck squamous cell carcinoma', 'IGC'),
'CR': ('Vanderbilt University', 'Head and Neck squamous cell carcinoma', 'IGC'),
'CS': ('Thomas Jefferson University', 'Brain Lower Grade Glioma', 'IGC'),
'CU': ('UNC', 'Bladder Urothelial Carcinoma', 'NCH'),
'CV': ('MD Anderson Cancer Center', 'Head and Neck squamous cell carcinoma', 'IGC'),
'CW': ('Mayo Clinic - Rochester', 'Kidney renal clear cell carcinoma', 'IGC'),
'CX': ('Medical College of Georgia', 'Head and Neck squamous cell carcinoma', 'IGC'),
'CZ': ('Harvard', 'Kidney renal clear cell carcinoma', 'IGC'),
'D1': ('Mayo Clinic', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'D3': ('MD Anderson', 'Skin Cutaneous Melanoma', 'NCH'),
'D5': ('Greater Poland Cancer Center', 'Colon adenocarcinoma', 'IGC'),
'D6': ('Greater Poland Cancer Center', 'Head and Neck squamous cell carcinoma', 'IGC'),
'D7': ('Greater Poland Cancer Center', 'Stomach adenocarcinoma', 'IGC'),
'D8': ('Greater Poland Cancer Center', 'Breast invasive carcinoma', 'NCH'),
'D9': ('Greater Poland Cancer Center', 'Skin Cutaneous Melanoma', 'NCH'),
'DA': ('Yale', 'Skin Cutaneous Melanoma', 'NCH'),
'DB': ('Mayo Clinic - Rochester', 'Brain Lower Grade Glioma', 'IGC'),
'DC': ('MSKCC', 'Rectum adenocarcinoma', 'IGC'),
'DD': ('Mayo Clinic - Rochester', 'Liver hepatocellular carcinoma', 'NCH'),
'DE': ('University of North Carolina', 'Thyroid carcinoma', 'NCH'),
'DF': ('Ontario Institute for Cancer Research', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'DG': ('Ontario Institute for Cancer Research', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'DH': ('University of Florida', 'Brain Lower Grade Glioma', 'IGC'),
'DI': ('MD Anderson', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'DJ': ('Memorial Sloan Kettering', 'Thyroid carcinoma', 'NCH'),
'DK': ('Memorial Sloan Kettering', 'Bladder Urothelial Carcinoma', 'NCH'),
'DM': ('University Of Michigan', 'Colon adenocarcinoma', 'NCH'),
'DO': ('Medical College of Georgia', 'Thyroid carcinoma', 'NCH'),
'DQ': ('University Of Michigan', 'Head and Neck squamous cell carcinoma', 'IGC'),
'DR': ('University of Hawaii', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'DS': ('Cedars Sinai', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'DT': ('ILSBio', 'Rectum adenocarcinoma', 'IGC'),
'DU': ('Henry Ford Hospital', 'Brain Lower Grade Glioma', 'IGC'),
'DV': ('NCI Urologic Oncology Branch', 'Kidney renal clear cell carcinoma', 'IGC'),
'DW': ('NCI Urologic Oncology Branch', 'Kidney renal papillary cell carcinoma', 'IGC'),
'DX': ('Memorial Sloan Kettering', 'Sarcoma', 'NCH'),
'DY': ('University Of Michigan', 'Rectum adenocarcinoma', 'NCH'),
'DZ': ('Mayo Clinic - Rochester', 'Kidney renal papillary cell carcinoma', 'IGC'),
'E1': ('Duke', 'Brain Lower Grade Glioma', 'IGC'),
'E2': ('Roswell Park', 'Breast invasive carcinoma', 'NCH'),
'E3': ('Roswell Park', 'Thyroid carcinoma', 'NCH'),
'E5': ('Roswell Park', 'Bladder Urothelial Carcinoma', 'NCH'),
'E6': ('Roswell Park', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'E7': ('Asterand', 'Bladder Urothelial Carcinoma', 'NCH'),
'E8': ('Asterand', 'Thyroid carcinoma', 'NCH'),
'E9': ('Asterand', 'Breast invasive carcinoma', 'NCH'),
'EA': ('Asterand', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'EB': ('Asterand', 'Skin Cutaneous Melanoma', 'NCH'),
'EC': ('Asterand', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'ED': ('Asterand', 'Liver hepatocellular carcinoma', 'NCH'),
'EE': ('University of Sydney', 'Skin Cutaneous Melanoma', 'NCH'),
'EF': ('Cureline', 'Rectum adenocarcinoma', 'IGC'),
'EI': ('Greater Poland Cancer Center', 'Rectum adenocarcinoma', 'IGC'),
'EJ': ('University of Pittsburgh', 'Prostate adenocarcinoma', 'IGC'),
'EK': ('Gynecologic Oncology Group', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'EL': ('MD Anderson', 'Thyroid carcinoma', 'NCH'),
'EM': ('University Health Network', 'Thyroid carcinoma', 'NCH'),
'EO': ('University Health Network', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'EP': ('Christiana Healthcare', 'Liver hepatocellular carcinoma', 'NCH'),
'EQ': ('Christiana Healthcare', 'Stomach adenocarcinoma', 'IGC'),
'ER': ('University of Pittsburgh', 'Skin Cutaneous Melanoma', 'NCH'),
'ES': ('University of Florida', 'Liver hepatocellular carcinoma', 'NCH'),
'ET': ('Johns Hopkins', 'Thyroid carcinoma', 'NCH'),
'EU': ('CHI-Penrose Colorado', 'Kidney renal clear cell carcinoma', 'IGC'),
'EV': ('CHI-Penrose Colorado', 'Kidney renal papillary cell carcinoma', 'IGC'),
'EW': ('University of Miami', 'Breast invasive carcinoma', 'NCH'),
'EX': ('University of North Carolina', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'EY': ('University of North Carolina', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'EZ': ('UNC', 'Brain Lower Grade Glioma', 'IGC'),
'F1': ('UNC', 'Stomach adenocarcinoma', 'IGC'),
'F2': ('UNC', 'Pancreatic adenocarcinoma', 'IGC'),
'F4': ('Asterand', 'Colon adenocarcinoma', 'IGC'),
'F5': ('Asterand', 'Rectum adenocarcinoma', 'IGC'),
'F6': ('Asterand', 'Brain Lower Grade Glioma', 'IGC'),
'F7': ('Asterand', 'Head and Neck squamous cell carcinoma', 'IGC'),
'F9': ('Asterand', 'Kidney renal papillary cell carcinoma', 'IGC'),
'FA': ('Asterand', 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'IGC'),
'FB': ('Asterand', 'Pancreatic adenocarcinoma', 'IGC'),
'FC': ('Asterand', 'Prostate adenocarcinoma', 'IGC'),
'FD': ('BLN - University Of Chicago', 'Bladder Urothelial Carcinoma', 'NCH'),
'FE': ('Ohio State University', 'Thyroid carcinoma', 'NCH'),
'FF': ('SingHealth', 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'IGC'),
'FG': ('Case Western', 'Brain Lower Grade Glioma', 'IGC'),
'FH': ('CHI-Penrose Colorado', 'Thyroid carcinoma', 'NCH'),
'FI': ('Washington University', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'FJ': ('BLN - Baylor', 'Bladder Urothelial Carcinoma', 'NCH'),
'FK': ('Johns Hopkins', 'Thyroid carcinoma', 'NCH'),
'FL': ('University of Hawaii - Normal Study', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'FM': ('International Genomics Consortium', 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'IGC'),
'FN': ('International Genomics Consortium', 'Brain Lower Grade Glioma', 'IGC'),
'FP': ('International Genomics Consortium', 'Stomach adenocarcinoma', 'IGC'),
'FQ': ('Johns Hopkins', 'Pancreatic adenocarcinoma', 'IGC'),
'FR': ('University of North Carolina', 'Skin Cutaneous Melanoma', 'NCH'),
'FS': ('Essen', 'Skin Cutaneous Melanoma', 'NCH'),
'FT': ('BLN - University of Miami', 'Bladder Urothelial Carcinoma', 'NCH'),
'FU': ('International Genomics Consortium', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'FV': ('International Genomics Consortium', 'Liver hepatocellular carcinoma', 'NCH'),
'FW': ('International Genomics Consortium', 'Skin Cutaneous Melanoma', 'NCH'),
'FX': ('International Genomics Consortium', 'Sarcoma', 'NCH'),
'FY': ('International Genomics Consortium', 'Thyroid carcinoma', 'NCH'),
'FZ': ('University of Pittsburgh', 'Pancreatic adenocarcinoma', 'IGC'),
'G2': ('MD Anderson', 'Bladder Urothelial Carcinoma', 'NCH'),
'G3': ('Alberta Health Services', 'Liver hepatocellular carcinoma', 'NCH'),
'G4': ('Roswell Park', 'Colon adenocarcinoma', 'IGC'),
'G5': ('Roswell Park', 'Rectum adenocarcinoma', 'IGC'),
'G6': ('Roswell Park', 'Kidney renal clear cell carcinoma', 'IGC'),
'G7': ('Roswell Park', 'Kidney renal papillary cell carcinoma', 'IGC'),
'G8': ('Roswell Park', 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'IGC'),
'G9': ('Roswell Park', 'Prostate adenocarcinoma', 'IGC'),
'GC': ('International Genomics Consortium', 'Bladder Urothelial Carcinoma', 'NCH'),
'GD': ('ABS - IUPUI', 'Bladder Urothelial Carcinoma', 'NCH'),
'GE': ('ABS - IUPUI', 'Thyroid carcinoma', 'NCH'),
'GF': ('ABS - IUPUI', 'Skin Cutaneous Melanoma', 'NCH'),
'GG': ('ABS - IUPUI', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'GH': ('ABS - IUPUI', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'GI': ('ABS - IUPUI', 'Breast invasive carcinoma', 'NCH'),
'GJ': ('ABS - IUPUI', 'Liver hepatocellular carcinoma', 'NCH'),
'GK': ('ABS - IUPUI', 'Kidney renal clear cell carcinoma', 'IGC'),
'GL': ('ABS - IUPUI', 'Kidney renal papillary cell carcinoma', 'IGC'),
'GM': ('MD Anderson', 'Breast invasive carcinoma', 'NCH'),
'GN': ('Roswell', 'Skin Cutaneous Melanoma', 'NCH'),
'GP': ('MD Anderson', 'Acute Myeloid Leukemia', 'NCH'),
'GR': ('University of Nebraska Medical Center (UNMC)', 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'IGC'),
'GS': ('Fundacio Clinic per a la Recerca Biomedica', 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'IGC'),
'GU': ('BLN - UT Southwestern Medical Center at Dallas', 'Bladder Urothelial Carcinoma', 'NCH'),
'GV': ('BLN - Cleveland Clinic', 'Bladder Urothelial Carcinoma', 'NCH'),
'GZ': ('BC Cancer Agency', 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'IGC'),
'H1': ('Medical College of Georgia', 'Stomach adenocarcinoma', 'IGC'),
'H2': ('Christiana Healthcare', 'Thyroid carcinoma', 'NCH'),
'H3': ('ABS - IUPUI', 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'IGC'),
'H4': ('Medical College of Georgia', 'Bladder Urothelial Carcinoma', 'NCH'),
'H5': ('Medical College of Georgia', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'H6': ('Christiana Healthcare', 'Pancreatic adenocarcinoma', 'IGC'),
'H7': ('ABS - IUPUI', 'Head and Neck squamous cell carcinoma', 'IGC'),
'H8': ('ABS - IUPUI', 'Pancreatic adenocarcinoma', 'IGC'),
'H9': ('ABS - IUPUI', 'Prostate adenocarcinoma', 'IGC'),
'HA': ('Alberta Health Services', 'Stomach adenocarcinoma', 'IGC'),
'HB': ('University of North Carolina', 'Sarcoma', 'NCH'),
'HC': ('International Genomics Consortium', 'Prostate adenocarcinoma', 'IGC'),
'HD': ('International Genomics Consortium', 'Head and Neck squamous cell carcinoma', 'IGC'),
'HE': ('Ontario Institute for Cancer Research (OICR)', 'Kidney renal papillary cell carcinoma', 'IGC'),
'HF': ('Ontario Institute for Cancer Research (OICR)', 'Stomach adenocarcinoma', 'IGC'),
'HG': ('Roswell Park', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'HH': ('Fox Chase', 'Stomach adenocarcinoma', 'IGC'),
'HI': ('Fox Chase', 'Prostate adenocarcinoma', 'IGC'),
'HJ': ('Fox Chase', 'Stomach adenocarcinoma', 'IGC'),
'HK': ('Fox Chase', 'Brain Lower Grade Glioma', 'IGC'),
'HL': ('Fox Chase', 'Head and Neck squamous cell carcinoma', 'IGC'),
'HM': ('Christiana Healthcare', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'HN': ('Ontario Institute for Cancer Research (OICR)', 'Breast invasive carcinoma', 'NCH'),
'HP': ('Ontario Institute for Cancer Research (OICR)', 'Liver hepatocellular carcinoma', 'NCH'),
'HQ': ('Ontario Institute for Cancer Research (OICR)', 'Bladder Urothelial Carcinoma', 'NCH'),
'HR': ('Ontario Institute for Cancer Research (OICR)', 'Skin Cutaneous Melanoma', 'NCH'),
'HS': ('Ontario Institute for Cancer Research (OICR)', 'Sarcoma', 'NCH'),
'HT': ('Case Western - St Joes', 'Brain Lower Grade Glioma', 'IGC'),
'HU': ('National Cancer Center Korea', 'Stomach adenocarcinoma', 'IGC'),
'HV': ('National Cancer Center Korea', 'Pancreatic adenocarcinoma', 'IGC'),
'HW': ('MSKCC', 'Brain Lower Grade Glioma', 'IGC'),
'HZ': ('International Genomics Consortium', 'Pancreatic adenocarcinoma', 'IGC'),
'IA': ('Cleveland Clinic', 'Kidney renal papillary cell carcinoma', 'IGC'),
'IB': ('Alberta Health Services', 'Pancreatic adenocarcinoma', 'IGC'),
'IC': ('University of Pittsburgh', 'Esophageal carcinoma ', 'NCH'),
'IE': ('ABS - IUPUI', 'Sarcoma', 'NCH'),
'IF': ('University of Texas MD Anderson Cancer Center', 'Sarcoma', 'NCH'),
'IG': ('Asterand', 'Esophageal carcinoma ', 'NCH'),
'IH': ('University of Miami', 'Skin Cutaneous Melanoma', 'NCH'),
'IJ': ('Christiana Healthcare', 'Acute Myeloid Leukemia', 'NCH'),
'IK': ('Christiana Healthcare', 'Brain Lower Grade Glioma', 'IGC'),
'IM': ('University of Miami', 'Thyroid carcinoma', 'NCH'),
'IN': ('University of Pittsburgh', 'Stomach adenocarcinoma', 'IGC'),
'IP': ('ABS - IUPUI', 'Stomach adenocarcinoma', 'IGC'),
'IQ': ('University of Miami', 'Head and Neck squamous cell carcinoma', 'IGC'),
'IR': ('Memorial Sloan Kettering', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'IS': ('Memorial Sloan Kettering', 'Sarcoma', 'NCH'),
'IW': ('Cedars Sinai', 'Sarcoma', 'NCH'),
'IZ': ('ABS - Lahey Clinic', 'Kidney renal papillary cell carcinoma', 'IGC'),
'J1': ('ABS - Lahey Clinic', 'Lung squamous cell carcinoma', 'IGC'),
'J2': ('ABS - Lahey Clinic', 'Lung adenocarcinoma', 'IGC'),
'J4': ('ABS - Lahey Clinic', 'Prostate adenocarcinoma', 'IGC'),
'J7': ('ILSBio', 'Kidney renal papillary cell carcinoma', 'IGC'),
'J8': ('Mayo Clinic', 'Thyroid carcinoma', 'NCH'),
'J9': ('Melbourne Health', 'Prostate adenocarcinoma', 'IGC'),
'JA': ('ABS - Research Metrics Pakistan', 'Head and Neck squamous cell carcinoma', 'IGC'),
'JL': ('ABS - Research Metrics Pakistan', 'Breast invasive carcinoma', 'NCH'),
'JU': ('BLN - Baylor', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'JV': ('BLN - Baylor', 'Sarcoma', 'NCH'),
'JW': ('BLN - Baylor', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'JX': ('Washington University', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'JY': ('University Health Network', 'Esophageal carcinoma ', 'NCH'),
'JZ': ('University of Rochester', 'Esophageal carcinoma ', 'NCH'),
'K1': ('University of Pittsburgh', 'Sarcoma', 'NCH'),
'K4': ('ABS - Lahey Clinic', 'Bladder Urothelial Carcinoma', 'NCH'),
'K6': ('ABS - Lahey Clinic', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'K7': ('ABS - Lahey Clinic', 'Liver hepatocellular carcinoma', 'NCH'),
'K8': ('ABS - Lahey Clinic', 'Skin Cutaneous Melanoma', 'NCH'),
'KA': ('ABS - Lahey Clinic', 'Esophageal carcinoma ', 'NCH'),
'KB': ('University Health Network, Toronto', 'Stomach adenocarcinoma', 'IGC'),
'KC': ('Cornell Medical College', 'Prostate adenocarcinoma', 'IGC'),
'KD': ('Mount Sinai School of Medicine', 'Sarcoma', 'NCH'),
'KE': ('Mount Sinai School of Medicine', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'KF': ('Christiana Healthcare', 'Sarcoma', 'NCH'),
'KG': ('Baylor Network', 'Pancreatic adenocarcinoma', 'IGC'),
'KH': ('Memorial Sloan Kettering', 'Esophageal carcinoma ', 'NCH'),
'KJ': ('University of Miami', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'KK': ('MD Anderson Cancer Center', 'Prostate adenocarcinoma', 'IGC'),
'KL': ('MSKCC', 'Kidney Chromophobe', 'IGC'),
'KM': ('NCI Urologic Oncology Branch', 'Kidney Chromophobe', 'IGC'),
'KN': ('Harvard', 'Kidney Chromophobe', 'IGC'),
'KO': ('MD Anderson Cancer Center', 'Kidney Chromophobe', 'IGC'),
'KP': ('British Columbia Cancer Agency', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'KQ': ('Cornell Medical College', 'Bladder Urothelial Carcinoma', 'NCH'),
'KR': ('University Of Michigan', 'Liver hepatocellular carcinoma', 'NCH'),
'KS': ('University Of Michigan', 'Thyroid carcinoma', 'NCH'),
'KT': ('Hartford', 'Brain Lower Grade Glioma', 'IGC'),
'KU': ('Hartford', 'Head and Neck squamous cell carcinoma', 'IGC'),
'KV': ('Hartford', 'Kidney renal papillary cell carcinoma', 'IGC'),
'KZ': ('Hartford', 'Stomach adenocarcinoma', 'IGC'),
'L1': ('Hartford', 'Pancreatic adenocarcinoma', 'IGC'),
'L3': ('Gundersen Lutheran Health System', 'Lung squamous cell carcinoma', 'IGC'),
'L4': ('Gundersen Lutheran Health System', 'Lung adenocarcinoma', 'IGC'),
'L5': ('University of Michigan', 'Esophageal carcinoma ', 'NCH'),
'L6': ('National Institutes of Health', 'Thyroid carcinoma', 'NCH'),
'L7': ('Christiana Care', 'Esophageal carcinoma ', 'NCH'),
'L8': ('University of Miami', 'Kidney renal papillary cell carcinoma', 'NCH'),
'L9': ('Candler', 'Lung adenocarcinoma', 'IGC'),
'LA': ('Candler', 'Lung squamous cell carcinoma', 'IGC'),
'LB': ('Candler', 'Pancreatic adenocarcinoma', 'IGC'),
'LC': ('Hartford Hospital', 'Bladder Urothelial Carcinoma', 'NCH'),
'LD': ('Hartford Hospital', 'Breast invasive carcinoma', 'NCH'),
'LG': ('Hartford Hospital', 'Liver hepatocellular carcinoma', 'NCH'),
'LH': ('Hartford Hospital', 'Skin Cutaneous Melanoma', 'NCH'),
'LI': ('Hartford Hospital', 'Sarcoma', 'NCH'),
'LK': ('University of Pittsburgh', 'Mesothelioma', 'NCH'),
'LL': ('Candler', 'Breast invasive carcinoma', 'NCH'),
'LN': ('ILSBIO', 'Esophageal carcinoma ', 'NCH'),
'LP': ('ILSBIO', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'LQ': ('Gundersen Lutheran Health System', 'Breast invasive carcinoma', 'NCH'),
'LS': ('Gundersen Lutheran Health System', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'LT': ('Gundersen Lutheran Health System', 'Bladder Urothelial Carcinoma', 'NCH'),
'M7': ('University of North Carolina', 'Prostate adenocarcinoma', 'NCH'),
'M8': ('Ontario Institute for Cancer Research (OICR)', 'Pancreatic adenocarcinoma', 'NCH'),
'M9': ('Ontario Institute for Cancer Research (OICR)', 'Esophageal carcinoma ', 'NCH'),
'MA': ('MD Anderson Cancer Center', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'MB': ('University of Minnesota', 'Sarcoma', 'NCH'),
'ME': ('University of Minnesota', 'Lung adenocarcinoma', 'NCH'),
'MF': ('University of Minnesota', 'Lung squamous cell carcinoma', 'NCH'),
'MG': ('BLN - Baylor', 'Prostate adenocarcinoma', 'NCH'),
'MH': ('BLN - Baylor', 'Kidney renal papillary cell carcinoma', 'NCH'),
'MI': ('BLN - Baylor', 'Liver hepatocellular carcinoma', 'NCH'),
'MJ': ('BLN - Baylor', 'Sarcoma', 'NCH'),
'MK': ('BLN - Baylor', 'Thyroid carcinoma', 'NCH'),
'ML': ('BLN - Baylor', 'Lung squamous cell carcinoma', 'NCH'),
'MM': ('BLN - Baylor', 'Kidney renal clear cell carcinoma', 'NCH'),
'MN': ('BLN - Baylor', 'Lung adenocarcinoma', 'NCH'),
'MO': ('ILSBio', 'Sarcoma', 'NCH'),
'MP': ('Washington University - Mayo Clinic', 'Lung adenocarcinoma', 'NCH'),
'MQ': ('Washington University - NYU', 'Mesothelioma', 'NCH'),
'MR': ('University of Minnesota', 'Liver hepatocellular carcinoma', 'NCH'),
'MS': ('University of Minnesota', 'Breast invasive carcinoma', 'NCH'),
'MT': ('University of Minnesota', 'Head and Neck squamous cell carcinoma', 'NCH'),
'MU': ('University of Minnesota', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'MV': ('University of Minnesota', 'Bladder Urothelial Carcinoma', 'NCH'),
'MW': ('University of Miami', 'Kidney renal clear cell carcinoma', 'NCH'),
'MX': ('MSKCC', 'Stomach adenocarcinoma', 'NCH'),
'MY': ('Montefiore Medical Center', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'MZ': ('Montefiore Medical Center', 'Head and Neck squamous cell carcinoma', 'NCH'),
'N1': ('Montefiore Medical Center', 'Sarcoma', 'NCH'),
'N5': ('MSKCC', 'Uterine Carcinosarcoma', 'NCH'),
'N6': ('University of Pittsburgh', 'Uterine Carcinosarcoma', 'NCH'),
'N7': ('Washington University', 'Uterine Carcinosarcoma', 'NCH'),
'N8': ('University of North Carolina', 'Uterine Carcinosarcoma', 'NCH'),
'N9': ('MD Anderson', 'Uterine Carcinosarcoma', 'NCH'),
'NA': ('Duke University', 'Uterine Carcinosarcoma', 'NCH'),
'NB': ('Washington University - CHUV', 'Lung adenocarcinoma', 'NCH'),
'NC': ('Washington University - CHUV', 'Lung squamous cell carcinoma', 'NCH'),
'ND': ('Cedars Sinai', 'Uterine Carcinosarcoma', 'NCH'),
'NF': ('Mayo Clinic - Rochester', 'Uterine Carcinosarcoma', 'NCH'),
'NG': ('Roswell Park', 'Uterine Carcinosarcoma', 'NCH'),
'NH': ('Candler', 'Colon adenocarcinoma', 'NCH'),
'NI': ('Roswell Park', 'Liver hepatocellular carcinoma', 'NCH'),
'NJ': ('Washington University - Rush University', 'Lung adenocarcinoma', 'NCH'),
'NK': ('Washington University - Rush University', 'Lung squamous cell carcinoma', 'NCH'),
'NM': ('Cambridge BioSource', 'Head and Neck squamous cell carcinoma', 'NCH'),
'NP': ('International Genomics Consortium', 'Kidney Chromophobe', 'NCH'),
'NQ': ('International Genomics Consortium', 'Mesothelioma', 'NCH'),
'NS': ('Gundersen Lutheran Health System', 'Skin Cutaneous Melanoma', 'NCH'),
'O1': ('Washington University - CALGB', 'Lung adenocarcinoma', 'NCH'),
'O2': ('Washington University - CALGB', 'Lung squamous cell carcinoma', 'NCH'),
'O8': ('Saint Mary\'s Health Care', 'Liver hepatocellular carcinoma', 'NCH'),
'O9': ('Saint Mary\'s Health Care', 'Kidney renal papillary cell carcinoma', 'NCH'),
'OC': ('Saint Mary\'s Health Care', 'Lung squamous cell carcinoma', 'NCH'),
'OD': ('Saint Mary\'s Health Care', 'Skin Cutaneous Melanoma', 'NCH'),
'OE': ('Saint Mary\'s Health Care', 'Pancreatic adenocarcinoma', 'NCH'),
'OJ': ('Saint Mary\'s Health Care', 'Thyroid carcinoma', 'NCH'),
'OK': ('Mount Sinai School of Medicine', 'Breast invasive carcinoma', 'NCH'),
'OL': ('University of Chicago', 'Breast invasive carcinoma', 'NCH'),
'OR': ('University of Michigan', 'Adrenocortical carcinoma', 'NCH'),
'OU': ('Roswell Park', 'Adrenocortical carcinoma', 'NCH'),
'OW': ('International Genomics Consortium', 'Miscellaneous', 'NCH'),
'OX': ('University of North Carolina', 'Glioblastoma multiforme', 'NCH'),
'OY': ('University of North Carolina', 'Ovarian serous cystadenocarcinoma', 'NCH'),
'P3': ('Fred Hutchinson', 'Head and Neck squamous cell carcinoma', 'NCH'),
'P4': ('MD Anderson Cancer Center', 'Kidney renal papillary cell carcinoma', 'NCH'),
'P5': ('Cureline', 'Brain Lower Grade Glioma', 'NCH'),
'P6': ('Translational Genomics Research Institute', 'Adrenocortical carcinoma', 'NCH'),
'P7': ('Translational Genomics Research Institute', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'P8': ('University of Pittsburgh', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'P9': ('University of Minnesota', 'Pancreatic adenocarcinoma', 'NCH'),
'PA': ('University of Minnesota', 'Adrenocortical carcinoma', 'NCH'),
'PB': ('University of Minnesota', 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'NCH'),
'PC': ('Fox Chase', 'Sarcoma', 'NCH'),
'PD': ('Fox Chase', 'Liver hepatocellular carcinoma', 'NCH'),
'PE': ('Fox Chase', 'Breast invasive carcinoma', 'NCH'),
'PG': ('Montefiore Medical Center', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'PH': ('Gundersen Lutheran', 'Acute Myeloid Leukemia', 'NCH'),
'PJ': ('Gundersen Lutheran', 'Kidney renal papillary cell carcinoma', 'NCH'),
'PK': ('University Health Network', 'Adrenocortical carcinoma', 'NCH'),
'PL': ('Institute of Human Virology Nigeria', 'Breast invasive carcinoma', 'NCH'),
'PN': ('Institute of Human Virology Nigeria', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'PQ': ('University of Colorado Denver', 'Bladder Urothelial Carcinoma', 'NCH'),
'PR': ('Roswell Park', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'PT': ('Maine Medical Center', 'Sarcoma', 'NCH'),
'PZ': ('ABS - Lahey Clinic', 'Pancreatic adenocarcinoma', 'NCH'),
'Q1': ('University of Oklahoma HSC', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'Q2': ('University of Oklahoma HSC', 'Kidney renal papillary cell carcinoma', 'NCH'),
'Q3': ('University of Oklahoma HSC', 'Pancreatic adenocarcinoma', 'NCH'),
'Q4': ('Emory University', 'Acute Myeloid Leukemia', 'NCH'),
'Q9': ('Emory University', 'Esophageal carcinoma ', 'NCH'),
'QA': ('Emory University', 'Liver hepatocellular carcinoma', 'NCH'),
'QB': ('Emory University', 'Skin Cutaneous Melanoma', 'NCH'),
'QC': ('Emory University', 'Sarcoma', 'NCH'),
'QD': ('Emory University', 'Thyroid carcinoma', 'NCH'),
'QF': ('BLN - Baylor', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'QG': ('BLN - Baylor', 'Colon adenocarcinoma', 'NCH'),
'QH': ('Fondazione-Besta', 'Brain Lower Grade Glioma', 'NCH'),
'QJ': ('Mount Sinai School of Medicine', 'Ovarian serous cystadenocarcinoma', 'NCH'),
'QK': ('Emory University - Winship Cancer Inst.', 'Head and Neck squamous cell carcinoma', 'NCH'),
'QL': ('University of Chicago', 'Colon adenocarcinoma', 'NCH'),
'QM': ('University of Oklahoma HSC', 'Uterine Carcinosarcoma', 'NCH'),
'QN': ('ILSBio', 'Uterine Carcinosarcoma', 'NCH'),
'QQ': ('Roswell Park', 'Sarcoma', 'NCH'),
'QR': ('National Institutes of Health', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'QS': ('Candler', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'QT': ('University of North Carolina', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'QU': ('Harvard Beth Israel', 'Prostate adenocarcinoma', 'NCH'),
'QV': ('Instituto Nacional de Cancerologia', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'QW': ('Instituto Nacional de Cancerologia', 'Stomach adenocarcinoma', 'NCH'),
'R1': ('CHI-Penrose Colorado', 'Colon adenocarcinoma', 'NCH'),
'R2': ('CHI-Penrose Colorado', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'R3': ('CHI-Penrose Colorado', 'Bladder Urothelial Carcinoma', 'NCH'),
'R5': ('MD Anderson Cancer Center', 'Stomach adenocarcinoma', 'NCH'),
'R6': ('MD Anderson Cancer Center', 'Esophageal carcinoma ', 'NCH'),
'R7': ('Gundersen Lutheran Health System', 'Head and Neck squamous cell carcinoma', 'NCH'),
'R8': ('MD Anderson', 'Brain Lower Grade Glioma', 'NCH'),
'R9': ('Candler', 'Ovarian serous cystadenocarcinoma', 'NCH'),
'RA': ('Candler', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'RB': ('Emory University', 'Pancreatic adenocarcinoma', 'NCH'),
'RC': ('University of Utah', 'Liver hepatocellular carcinoma', 'NCH'),
'RD': ('Peter MacCallum Cancer Center', 'Stomach adenocarcinoma', 'NCH'),
'RE': ('Peter MacCallum Cancer Center', 'Esophageal carcinoma ', 'NCH'),
'RG': ('Montefiore Medical Center', 'Liver hepatocellular carcinoma', 'NCH'),
'RH': ('BLN - Baylor', 'Head and Neck squamous cell carcinoma', 'NCH'),
'RL': ('St. Joseph\'s Hospital AZ', 'Pancreatic adenocarcinoma', 'NCH'),
'RM': ('St. Joseph\'s Hospital AZ', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'RN': ('St. Joseph\'s Hospital AZ', 'Sarcoma', 'NCH'),
'RP': ('St. Joseph\'s Hospital AZ', 'Skin Cutaneous Melanoma', 'NCH'),
'RQ': ('St. Joseph\'s Hospital AZ', 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'NCH'),
'RR': ('St. Joseph\'s Hospital AZ', 'Glioblastoma multiforme', 'NCH'),
'RS': ('Memorial Sloan Kettering Cancer Center', 'Head and Neck squamous cell carcinoma', 'NCH'),
'RT': ('Cleveland Clinic Foundation', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'RU': ('Northwestern University', 'Colon adenocarcinoma', 'NCH'),
'RV': ('Northwestern University', 'Pancreatic adenocarcinoma', 'NCH'),
'RW': ('Michigan University', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'RX': ('University of Minnesota', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'RY': ('University of California San Francisco', 'Brain Lower Grade Glioma', 'NCH'),
'RZ': ('Wills Eye Institute', 'Uveal Melanoma', 'NCH'),
'S2': ('Albert Einstein Medical Center', 'Lung adenocarcinoma', 'NCH'),
'S3': ('Albert Einstein Medical Center', 'Breast invasive carcinoma', 'NCH'),
'S4': ('University of Chicago', 'Pancreatic adenocarcinoma', 'NCH'),
'S5': ('University of Oklahoma HSC', 'Bladder Urothelial Carcinoma', 'NCH'),
'S6': ('Gundersen Lutheran Health System', 'Testicular Germ Cell Tumors', 'NCH'),
'S7': ('University Hospital Motol', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'S8': ('ABS - IUPUI', 'Esophageal carcinoma ', 'NCH'),
'S9': ('Dept of Neurosurgery at University of Heidelberg', 'Brain Lower Grade Glioma', 'NCH'),
'SA': ('ABS - IUPUI', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'SB': ('Baylor College of Medicine', 'Testicular Germ Cell Tumors', 'NCH'),
'SC': ('Memorial Sloan Kettering', 'Mesothelioma', 'NCH'),
'SD': ('MD Anderson', 'Pancreatic adenocarcinoma', 'NCH'),
'SE': ('Boston Medical Center', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'SG': ('Cleveland Clinic Foundation', 'Sarcoma', 'NCH'),
'SH': ('Papworth Hospital', 'Mesothelioma', 'NCH'),
'SI': ('Washington University St. Louis', 'Sarcoma', 'NCH'),
'SJ': ('Albert Einstein Medical Center', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'SK': ('St. Joseph\'s Hospital AZ', 'Colon adenocarcinoma', 'NCH'),
'SL': ('St. Joseph\'s Hospital AZ', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'SN': ('BLN - Baylor', 'Testicular Germ Cell Tumors', 'NCH'),
'SO': ('University of Minnesota', 'Testicular Germ Cell Tumors', 'NCH'),
'SP': ('University Health Network', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'SQ': ('International Genomics Consortium', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'SR': ('Tufts Medical Center', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'SS': ('Medical College of Georgia', 'Colon adenocarcinoma', 'NCH'),
'ST': ('Global Bioclinical-Moldova', 'Head and Neck squamous cell carcinoma', 'NCH'),
'SU': ('Global Bioclinical-Moldova', 'Prostate adenocarcinoma', 'NCH'),
'SW': ('Global Bioclinical-Moldova', 'Stomach adenocarcinoma', 'NCH'),
'SX': ('Mayo Clinic Arizona', 'Kidney renal papillary cell carcinoma', 'NCH'),
'SY': ('Mayo Clinic Arizona', 'Bladder Urothelial Carcinoma', 'NCH'),
'T1': ('St. Joseph\'s Hospital Arizona', 'Liver hepatocellular carcinoma', 'NCH'),
'T2': ('St. University of Colorado Denver', 'Head and Neck squamous cell carcinoma', 'NCH'),
'T3': ('Molecular Response', 'Head and Neck squamous cell carcinoma', 'NCH'),
'T6': ('Molecular Response', 'Lung adenocarcinoma', 'NCH'),
'T7': ('Molecular Response', 'Kidney renal clear cell carcinoma', 'NCH'),
'T9': ('Molecular Response', 'Colon adenocarcinoma', 'NCH'),
'TE': ('Global BioClinical - Georgia', 'Skin Cutaneous Melanoma', 'NCH'),
'TG': ('Global BioClinical - Georgia', 'Head and Neck squamous cell carcinoma', 'NCH'),
'TK': ('Global BioClinical - Georgia', 'Prostate adenocarcinoma', 'NCH'),
'TL': ('Global BioClinical - Georgia', 'Stomach adenocarcinoma', 'NCH'),
'TM': ('The University of New South Wales', 'Brain Lower Grade Glioma', 'NCH'),
'TN': ('Ohio State University', 'Head and Neck squamous cell carcinoma', 'NCH'),
'TP': ('Maine Medical Center', 'Prostate adenocarcinoma', 'NCH'),
'TQ': ('University of Sao Paulo', 'Brain Lower Grade Glioma', 'NCH'),
'TR': ('Global Bioclinical-Moldova', 'Skin Cutaneous Melanoma', 'NCH'),
'TS': ('University of Pennsylvania', 'Mesothelioma', 'NCH'),
'TT': ('University of Pennsylvania', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'TV': ('Wake Forest University', 'Breast invasive carcinoma', 'NCH'),
'UB': ('UCSF', 'Liver hepatocellular carcinoma', 'NCH'),
'UC': ('University of Washington', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'UD': ('University of Western Australia', 'Mesothelioma', 'NCH'),
'UE': ('Asterand', 'Sarcoma', 'NCH'),
'UF': ('Barretos Cancer Hospital', 'Head and Neck squamous cell carcinoma', 'NCH'),
'UJ': ('Boston Medical Center', 'Lung squamous cell carcinoma', 'NCH'),
'UL': ('Boston Medical Center', 'Breast invasive carcinoma', 'NCH'),
'UN': ('Boston Medical Center', 'Kidney renal papillary cell carcinoma', 'NCH'),
'UP': ('Boston Medical Center', 'Head and Neck squamous cell carcinoma', 'NCH'),
'UR': ('Boston Medical Center', 'Prostate adenocarcinoma', 'NCH'),
'US': ('Garvan Institute of Medical Research', 'Pancreatic adenocarcinoma', 'NCH'),
'UT': ('Asbestos Diseases Research Institute', 'Mesothelioma', 'NCH'),
'UU': ('Mary Bird Perkins Cancer Center - Our Lady of the Lake', 'Breast invasive carcinoma', 'NCH'),
'UV': ('Capital Biosciences', 'Liver hepatocellular carcinoma', 'NCH'),
'UW': ('University of North Carolina', 'Kidney Chromophobe', 'NCH'),
'UY': ('University of California San Francisco', 'Bladder Urothelial Carcinoma', 'NCH'),
'UZ': ('University of California San Francisco', 'Kidney renal papillary cell carcinoma', 'NCH'),
'V1': ('University of California San Francisco', 'Prostate adenocarcinoma', 'NCH'),
'V2': ('Cleveland Clinic Foundation', 'Prostate adenocarcinoma', 'NCH'),
'V3': ('Cleveland Clinic Foundation', 'Uveal Melanoma', 'NCH'),
'V4': ('Institut Curie', 'Uveal Melanoma', 'NCH'),
'V5': ('Duke University', 'Esophageal carcinoma ', 'NCH'),
'V6': ('Duke University', 'Stomach adenocarcinoma', 'NCH'),
'V7': ('Medical College of Georgia', 'Breast invasive carcinoma', 'NCH'),
'V8': ('Medical College of Georgia', 'Kidney renal clear cell carcinoma', 'NCH'),
'V9': ('Medical College of Georgia', 'Kidney renal papillary cell carcinoma', 'NCH'),
'VA': ('Alliance', 'Stomach adenocarcinoma', 'NCH'),
'VB': ('Global BioClinical - Georgia', 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'NCH'),
'VD': ('University of Liverpool', 'Uveal Melanoma', 'NCH'),
'VF': ('University of Pennsylvania', 'Testicular Germ Cell Tumors', 'NCH'),
'VG': ('Institute of Human Virology Nigeria', 'Ovarian serous cystadenocarcinoma', 'NCH'),
'VK': ('Institute of Human Virology Nigeria', 'Colon adenocarcinoma', 'NCH'),
'VL': ('Institute of Human Virology Nigeria', 'Rectum adenocarcinoma', 'NCH'),
'VM': ('Huntsman Cancer Institute', 'Brain Lower Grade Glioma', 'NCH'),
'VN': ('NCI Urologic Oncology Branch', 'Prostate adenocarcinoma', 'NCH'),
'VP': ('Washington University', 'Prostate adenocarcinoma', 'NCH'),
'VQ': ('Barretos Cancer Hospital', 'Stomach adenocarcinoma', 'NCH'),
'VR': ('Barretos Cancer Hospital', 'Esophageal carcinoma ', 'NCH'),
'VS': ('Barretos Cancer Hospital', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'VT': ('Vanderbilt', 'Sarcoma', 'NCH'),
'VV': ('John Wayne Cancer Center', 'Brain Lower Grade Glioma', 'NCH'),
'VW': ('Northwestern University', 'Brain Lower Grade Glioma', 'NCH'),
'VX': ('Northwestern University', 'Stomach adenocarcinoma', 'NCH'),
'VZ': ('Albert Einstein Medical Center', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'W2': ('Medical College of Wisconsin', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'W3': ('John Wayne Cancer Center', 'Skin Cutaneous Melanoma', 'NCH'),
'W4': ('University of North Carolina', 'Testicular Germ Cell Tumors', 'NCH'),
'W5': ('Mayo Clinic Rochester', 'Cholangiocarcinoma', 'NCH'),
'W6': ('UCSF', 'Cholangiocarcinoma', 'NCH'),
'W7': ('Garvan Institute of Medical Research', 'Cholangiocarcinoma', 'NCH'),
'W8': ('Greenville Health System', 'Breast invasive carcinoma', 'NCH'),
'W9': ('University of Kansas', 'Brain Lower Grade Glioma', 'NCH'),
'WA': ('University of Schleswig-Holstein', 'Head and Neck squamous cell carcinoma', 'NCH'),
'WB': ('Erasmus MC', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'WC': ('MD Anderson', 'Uveal Melanoma', 'NCH'),
'WD': ('Emory University', 'Cholangiocarcinoma', 'NCH'),
'WE': ('Norfolk and Norwich Hospital', 'Skin Cutaneous Melanoma', 'NCH'),
'WF': ('Greenville Health System', 'Pancreatic adenocarcinoma', 'NCH'),
'WG': ('Greenville Health System', 'Lung squamous cell carcinoma', 'NCH'),
'WH': ('Greenville Health System', 'Brain Lower Grade Glioma', 'NCH'),
'WJ': ('Greenville Health System', 'Liver hepatocellular carcinoma', 'NCH'),
'WK': ('Brigham and Women\'s Hospital', 'Sarcoma', 'NCH'),
'WL': ('University of Kansas', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'WM': ('University of Kansas', 'Kidney renal clear cell carcinoma', 'NCH'),
'WN': ('University of Kansas', 'Kidney renal papillary cell carcinoma', 'NCH'),
'WP': ('University of Kansas', 'Sarcoma', 'NCH'),
'WQ': ('University of Kansas', 'Liver hepatocellular carcinoma', 'NCH'),
'WR': ('University of Kansas', 'Ovarian serous cystadenocarcinoma', 'NCH'),
'WS': ('University of Kansas', 'Colon adenocarcinoma', 'NCH'),
'WT': ('University of Kansas', 'Breast invasive carcinoma', 'NCH'),
'WU': ('Wake Forest University', 'Colon adenocarcinoma', 'NCH'),
'WW': ('Wake Forest University', 'Prostate adenocarcinoma', 'NCH'),
'WX': ('Yale University', 'Liver hepatocellular carcinoma', 'NCH'),
'WY': ('Johns Hopkins', 'Brain Lower Grade Glioma', 'NCH'),
'WZ': ('International Genomics Consortium', 'Testicular Germ Cell Tumors', 'NCH'),
'X2': ('University of Washington', 'Sarcoma', 'NCH'),
'X3': ('Cleveland Clinic Foundation', 'Testicular Germ Cell Tumors', 'NCH'),
'X4': ('Institute for Medical Research', 'Prostate adenocarcinoma', 'NCH'),
'X5': ('Institute of Human Virology Nigeria', 'Bladder Urothelial Carcinoma', 'NCH'),
'X6': ('University of Iowa', 'Sarcoma', 'NCH'),
'X7': ('ABS IUPUI', 'Thymoma', 'NCH'),
'X8': ('St. Joseph\'s Hospital Arizona', 'Esophageal carcinoma ', 'NCH'),
'X9': ('University of California, Davis', 'Sarcoma', 'NCH'),
'XA': ('University of Minnesota', 'Prostate adenocarcinoma', 'NCH'),
'XB': ('Albert Einstein Medical Center', 'Esophageal carcinoma ', 'NCH'),
'XC': ('Albert Einstein Medical Center', 'Lung squamous cell carcinoma', 'NCH'),
'XD': ('Providence Portland Medical Center', 'Pancreatic adenocarcinoma', 'NCH'),
'XE': ('University of Southern California', 'Testicular Germ Cell Tumors', 'NCH'),
'XF': ('University of Southern California', 'Bladder Urothelial Carcinoma', 'NCH'),
'XG': ('BLN UT Southwestern Medical Center at Dallas', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'XH': ('BLN Baylor', 'Thymoma', 'NCH'),
'XJ': ('University of Kansas', 'Prostate adenocarcinoma', 'NCH'),
'XK': ('Mayo Clinic Arizona', 'Prostate adenocarcinoma', 'NCH'),
'XM': ('MSKCC', 'Thymoma', 'NCH'),
'XN': ('University of Sao Paulo', 'Pancreatic adenocarcinoma', 'NCH'),
'XP': ('University of Sao Paulo', 'Esophageal carcinoma ', 'NCH'),
'XQ': ('University of Sao Paulo', 'Prostate adenocarcinoma', 'NCH'),
'XR': ('University of Sao Paulo', 'Liver hepatocellular carcinoma', 'NCH'),
'XS': ('University of Sao Paulo', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'XT': ('Johns Hopkins', 'Mesothelioma', 'NCH'),
'XU': ('University Health Network', 'Thymoma', 'NCH'),
'XV': ('Capital Biosciences', 'Skin Cutaneous Melanoma', 'NCH'),
'XX': ('Spectrum Health', 'Breast invasive carcinoma', 'NCH'),
'XY': ('Spectrum Health', 'Testicular Germ Cell Tumors', 'NCH'),
'Y3': ('University of New Mexico', 'Acute Myeloid Leukemia', 'NCH'),
'Y5': ('University of Arizona', 'Sarcoma', 'NCH'),
'Y6': ('University of Arizona', 'Prostate adenocarcinoma', 'NCH'),
'Y8': ('Spectrum Health', 'Kidney renal papillary cell carcinoma', 'NCH'),
'YA': ('Spectrum Health', 'Liver hepatocellular carcinoma', 'NCH'),
'YB': ('Spectrum Health', 'Pancreatic adenocarcinoma', 'NCH'),
'YC': ('Spectrum Health', 'Bladder Urothelial Carcinoma', 'NCH'),
'YD': ('Spectrum Health', 'Skin Cutaneous Melanoma', 'NCH'),
'YF': ('University of Puerto Rico', 'Bladder Urothelial Carcinoma', 'NCH'),
'YG': ('University of Puerto Rico', 'Skin Cutaneous Melanoma', 'NCH'),
'YH': ('Stanford University', 'Pancreatic adenocarcinoma', 'NCH'),
'YJ': ('Stanford University', 'Prostate adenocarcinoma', 'NCH'),
'YL': ('PROCURE Biobank', 'Prostate adenocarcinoma', 'NCH'),
'YN': ('University of Arizona', 'Skin Cutaneous Melanoma', 'NCH'),
'YR': ('Barretos Cancer Hospital', 'Cholangiocarcinoma', 'NCH'),
'YS': ('Barretos Cancer Hospital', 'Mesothelioma', 'NCH'),
'YT': ('Barretos Cancer Hospital', 'Thymoma', 'NCH'),
'YU': ('Barretos Cancer Hospital', 'Testicular Germ Cell Tumors', 'NCH'),
'YV': ('MSKCC', 'Uveal Melanoma', 'NCH'),
'YW': ('Albert Einstein Medical Center', 'Sarcoma', 'NCH'),
'YX': ('Emory University', 'Stomach adenocarcinoma', 'NCH'),
'YY': ('Roswell Park', 'Pancreatic adenocarcinoma', 'NCH'),
'YZ': ('The Ohio State University', 'Uveal Melanoma', 'NCH'),
'Z2': ('IDI-IRCCS', 'Skin Cutaneous Melanoma', 'NCH'),
'Z3': ('UCLA', 'Sarcoma', 'NCH'),
'Z4': ('Cureline', 'Sarcoma', 'NCH'),
'Z5': ('Cureline', 'Pancreatic adenocarcinoma', 'NCH'),
'Z6': ('Cureline', 'Esophageal carcinoma ', 'NCH'),
'Z7': ('John Wayne Cancer Center', 'Breast invasive carcinoma', 'NCH'),
'Z8': ('John Wayne Cancer Center', 'Pancreatic adenocarcinoma', 'NCH'),
'ZA': ('Candler', 'Stomach adenocarcinoma', 'NCH'),
'ZB': ('Thoraxklinik', 'Thymoma', 'NCH'),
'ZC': ('University of Mannheim', 'Thymoma', 'NCH'),
'ZD': ('ILSbio', 'Cholangiocarcinoma', 'NCH'),
'ZE': ('Spectrum Health', 'Lung squamous cell carcinoma', 'NCH'),
'ZF': ('University of Sheffield', 'Bladder Urothelial Carcinoma', 'NCH'),
'ZG': ('University Medical Center Hamburg-Eppendorf', 'Prostate adenocarcinoma', 'NCH'),
'ZH': ('University of North Carolina', 'Cholangiocarcinoma', 'NCH'),
'ZJ': ('NCI HRE Branch', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'ZK': ('University of New Mexico', 'Cholangiocarcinoma', 'NCH'),
'ZL': ('Valley Hospital', 'Thymoma', 'NCH'),
'ZM': ('University of Ulm', 'Testicular Germ Cell Tumors', 'NCH'),
'ZN': ('Brigham and Women\'s Hospital Division of Thoracic Surgery', 'Mesothelioma', 'NCH'),
'ZP': ('Medical College of Wisconsin', 'Liver hepatocellular carcinoma', 'NCH'),
'ZQ': ('Tayside Tissue Bank', 'Stomach adenocarcinoma', 'NCH'),
'ZR': ('Tayside Tissue Bank', 'Esophageal carcinoma ', 'NCH'),
'ZS': ('Tayside Tissue Bank', 'Liver hepatocellular carcinoma', 'NCH'),
'ZT': ('International Genomics Consortium', 'Thymoma', 'NCH'),
'ZU': ('Spectrum Health', 'Cholangiocarcinoma', 'NCH'),
'ZW': ('University of Alabama', 'Pancreatic adenocarcinoma', 'NCH'),
'ZX': ('University of Alabama', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
}
SAMPLE_TYPE = {
# 'Code': ('Definition', 'Short Letter Code'),
'01': ('Primary solid Tumor', 'TP'),
'02': ('Recurrent Solid Tumor', 'TR'),
'03': ('Primary Blood Derived Cancer - Peripheral Blood', 'TB'),
'04': ('Recurrent Blood Derived Cancer - Bone Marrow', 'TRBM'),
'05': ('Additional - New Primary', 'TAP'),
'06': ('Metastatic', 'TM'),
'07': ('Additional Metastatic', 'TAM'),
'08': ('Human Tumor Original Cells', 'THOC'),
'09': ('Primary Blood Derived Cancer - Bone Marrow', 'TBM'),
'10': ('Blood Derived Normal', 'NB'),
'11': ('Solid Tissue Normal', 'NT'),
'12': ('Buccal Cell Normal', 'NBC'),
'13': ('EBV Immortalized Normal', 'NEBV'),
'14': ('Bone Marrow Normal', 'NBM'),
'20': ('Control Analyte', 'CELLC'),
'40': ('Recurrent Blood Derived Cancer - Peripheral Blood', 'TRB'),
'50': ('Cell Lines', 'CELL'),
'60': ('Primary Xenograft Tissue', 'XP'),
'61': ('Cell Line Derived Xenograft Tissue', 'XCL'),
}
| 73.087277 | 131 | 0.609473 |
amous cell carcinoma', 'IGC'),
'34': ('University of Pittsburgh', 'Lung squamous cell carcinoma', 'IGC'),
'35': ('Cureline', 'Lung adenocarcinoma', 'IGC'),
'36': ('BC Cancer Agency', 'Ovarian serous cystadenocarcinoma', 'IGC'),
'37': ('Cureline', 'Lung squamous cell carcinoma', 'IGC'),
'38': ('UNC', 'Lung adenocarcinoma', 'IGC'),
'39': ('MSKCC', 'Lung squamous cell carcinoma', 'IGC'),
'3A': ('Moffitt Cancer Center', 'Pancreatic adenocarcinoma', 'NCH'),
'3B': ('Moffitt Cancer Center', 'Sarcoma', 'NCH'),
'3C': ('Columbia University', 'Breast invasive carcinoma', 'NCH'),
'3E': ('Columbia University', 'Pancreatic adenocarcinoma', 'NCH'),
'3G': ('MD Anderson Cancer Center', 'Thymoma', 'NCH'),
'3H': ('MD Anderson Cancer Center', 'Mesothelioma', 'NCH'),
'3J': ('Carle Cancer Center', 'Breast invasive carcinoma', 'NCH'),
'3K': ('Boston Medical Center', 'Liver hepatocellular carcinoma', 'NCH'),
'3L': ('Albert Einstein Medical Center', 'Colon adenocarcinoma', 'NCH'),
'3M': ('University of Kansas Medical Center', 'Stomach adenocarcinoma', 'NCH'),
'3N': ('Greenville Health System', 'Skin Cutaneous Melanoma', 'NCH'),
'3P': ('Greenville Health System', 'Ovarian serous cystadenocarcinoma', 'NCH'),
'3Q': ('Greenville Health Systems', 'Thymoma', 'NCH'),
'3R': ('University of New Mexico', 'Sarcoma', 'NCH'),
'3S': ('University of New Mexico', 'Thymoma', 'NCH'),
'3T': ('Emory University', 'Thymoma', 'NCH'),
'3U': ('University of Chicago', 'Mesothelioma', 'NCH'),
'3W': ('University of California San Diego', 'Sarcoma', 'NCH'),
'3X': ('Alberta Health Services', 'Cholangiocarcinoma', 'NCH'),
'3Z': ('Mary Bird Perkins Cancer Center - Our Lady of the Lake', 'Kidney renal clear cell carcinoma', 'NCH'),
'41': ('Christiana Healthcare', 'Glioblastoma multiforme', 'IGC'),
'42': ('Christiana Healthcare', 'Ovarian serous cystadenocarcinoma', 'IGC'),
'43': ('Christiana Healthcare', 'Lung squamous cell carcinoma', 'IGC'),
'44': ('Christiana Healthcare', 'Lung adenocarcinoma', 'IGC'),
'46': ('St. Joseph\'s Medical Center (MD)', 'Lung squamous cell carcinoma', 'IGC'),
'49': ('Johns Hopkins', 'Lung adenocarcinoma', 'IGC'),
'4A': ('Mary Bird Perkins Cancer Center - Our Lady of the Lake', 'Kidney renal papillary cell carcinoma', 'NCH'),
'4B': ('Mary Bird Perkins Cancer Center - Our Lady of the Lake', 'Lung adenocarcinoma', 'NCH'),
'4C': ('Mary Bird Perkins Cancer Center - Our Lady of the Lake', 'Thyroid carcinoma', 'NCH'),
'4D': ('Molecular Response', 'Ovarian serous cystadenocarcinoma', 'NCH'),
'4E': ('Molecular Response', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'4G': ('Sapienza University of Rome', 'Cholangiocarcinoma', 'NCH'),
'4H': ('Proteogenex, Inc.', 'Breast invasive carcinoma', 'NCH'),
'4J': ('Proteogenex, Inc.', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'4K': ('Proteogenex, Inc.', 'Testicular Germ Cell Tumors', 'NCH'),
'4L': ('Proteogenex, Inc.', 'Prostate adenocarcinoma', 'NCH'),
'4N': ('Mary Bird Perkins Cancer Center - Our Lady of the Lake', 'Colon adenocarcinoma', 'NCH'),
'4P': ('Duke University', 'Head and Neck squamous cell carcinoma', 'NCH'),
'4Q': ('Duke University', 'Sarcoma', 'NCH'),
'4R': ('Duke University', 'Liver hepatocellular carcinoma', 'NCH'),
'4S': ('Duke University', 'Prostate adenocarcinoma', 'NCH'),
'4T': ('Duke University', 'Colon adenocarcinoma', 'NCH'),
'4V': ('Hospital Louis Pradel', 'Thymoma', 'NCH'),
'4W': ('University of Miami', 'Glioblastoma multiforme', 'NCH'),
'4X': ('Yale University', 'Thymoma', 'NCH'),
'4Y': ('Medical College of Wisconsin', 'Sarcoma', 'NCH'),
'4Z': ('Barretos Cancer Hospital', 'Bladder Urothelial Carcinoma', 'NCH'),
'50': ('University of Pittsburgh', 'Lung adenocarcinoma', 'IGC'),
'51': ('UNC', 'Lung squamous cell carcinoma', 'IGC'),
'52': ('University of Miami', 'Lung squamous cell carcinoma', 'IGC'),
'53': ('University of Miami', 'Lung adenocarcinoma', 'IGC'),
'55': ('International Genomics Consortium', 'Lung adenocarcinoma', 'IGC'),
'56': ('International Genomics Consortium', 'Lung squamous cell carcinoma', 'IGC'),
'57': ('International Genomics Consortium', 'Ovarian serous cystadenocarcinoma', 'IGC'),
'58': ('Thoraxklinik at University Hospital Heidelberg', 'Lung squamous cell carcinoma', 'IGC'),
'59': ('Roswell Park', 'Ovarian serous cystadenocarcinoma', 'IGC'),
'5A': ('Wake Forest University', 'Cholangiocarcinoma', 'NCH'),
'5B': ('Medical College of Wisconsin', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'5C': ('Cureline', 'Liver hepatocellular carcinoma', 'NCH'),
'5D': ('University of Miami', 'Sarcoma', 'NCH'),
'5F': ('Duke University', 'Thyroid carcinoma', 'NCH'),
'5G': ('Cleveland Clinic Foundation', 'Thymoma', 'NCH'),
'5H': ('Retina Consultants Houston', 'Uveal Melanoma', 'NCH'),
'5J': ('Cureline', 'Acute Myeloid Leukemia', 'NCH'),
'5K': ('St. Joseph\'s Hospital AZ', 'Thymoma', 'NCH'),
'5L': ('University of Sao Paulo', 'Breast invasive carcinoma', 'NCH'),
'5M': ('University of Sao Paulo', 'Colon adenocarcinoma', 'NCH'),
'5N': ('University Hospital Erlangen', 'Bladder Urothelial Carcinoma', 'NCH'),
'5P': ('University Hospital Erlangen', 'Kidney renal papillary cell carcinoma', 'NCH'),
'5Q': ('Proteogenex, Inc', 'Pancreatic adenocarcinoma', 'NCH'),
'5R': ('Proteogenex, Inc', 'Liver hepatocellular carcinoma', 'NCH'),
'5S': ('Holy Cross', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'5T': ('Holy Cross', 'Breast invasive carcinoma', 'NCH'),
'5U': ('Regina Elena National Cancer Institute', 'Thymoma', 'NCH'),
'5V': ('Roswell Park', 'Thymoma', 'NCH'),
'5W': ('University of Alabama', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'5X': ('University of Alabama', 'Ovarian serous cystadenocarcinoma', 'NCH'),
'60': ('Roswell Park', 'Lung squamous cell carcinoma', 'IGC'),
'61': ('University of Pittsburgh', 'Ovarian serous cystadenocarcinoma', 'IGC'),
'62': ('Thoraxklinik at University Hospital Heidelberg', 'Lung adenocarcinoma', 'IGC'),
'63': ('Ontario Institute for Cancer Research', 'Lung squamous cell carcinoma', 'IGC'),
'64': ('Fox Chase', 'Lung adenocarcinoma', 'IGC'),
'65': ('Roswell Park', 'Glioblastoma multiforme', 'IGC'),
'66': ('Indivumed', 'Lung squamous cell carcinoma', 'IGC'),
'67': ('St Joseph\'s Medical Center (MD)', 'Lung adenocarcinoma', 'IGC'),
'68': ('Washington University - Cleveland Clinic', 'Lung squamous cell carcinoma', 'IGC'),
'69': ('Washington University - Cleveland Clinic', 'Lung adenocarcinoma', 'IGC'),
'6A': ('University of Kansas', 'Lung squamous cell carcinoma', 'NCH'),
'6D': ('University of Oklahoma HSC', 'Kidney renal clear cell carcinoma', 'NCH'),
'6G': ('University of Sao Paulo', 'Rectum adenocarcinoma', 'NCH'),
'70': ('ILSBio', 'Lung squamous cell carcinoma', 'IGC'),
'71': ('ILSBio', 'Lung adenocarcinoma', 'IGC'),
'72': ('NCH', 'Ovarian serous cystadenocarcinoma', 'IGC'),
'73': ('Roswell Park', 'Lung adenocarcinoma', 'IGC'),
'74': ('Swedish Neurosciences', 'Glioblastoma multiforme', 'IGC'),
'75': ('Ontario Institute for Cancer Research (OICR)', 'Lung adenocarcinoma', 'IGC'),
'76': ('Thomas Jefferson University', 'Glioblastoma multiforme', 'IGC'),
'77': ('Prince Charles Hospital', 'Lung squamous cell carcinoma', 'IGC'),
'78': ('Prince Charles Hospital', 'Lung adenocarcinoma', 'IGC'),
'79': ('Ontario Institute for Cancer Research (OICR)/Ottawa', 'Lung squamous cell carcinoma', 'IGC'),
'80': ('Ontario Institute for Cancer Research (OICR)/Ottawa', 'Lung adenocarcinoma', 'IGC'),
'81': ('CHI-Penrose Colorado', 'Glioblastoma multiforme', 'IGC'),
'82': ('CHI-Penrose Colorado', 'Lung squamous cell carcinoma', 'IGC'),
'83': ('CHI-Penrose Colorado', 'Lung adenocarcinoma', 'IGC'),
'85': ('Asterand', 'Lung squamous cell carcinoma', 'IGC'),
'86': ('Asterand', 'Lung adenocarcinoma', 'IGC'),
'87': ('International Genomics Consortium', 'Glioblastoma multiforme', 'IGC'),
'90': ('ABS - IUPUI', 'Lung squamous cell carcinoma', 'IGC'),
'91': ('ABS - IUPUI', 'Lung adenocarcinoma', 'IGC'),
'92': ('Washington University - St. Louis', 'Lung squamous cell carcinoma', 'IGC'),
'93': ('Washington University - St. Louis', 'Lung adenocarcinoma', 'IGC'),
'94': ('Washington University - Emory', 'Lung squamous cell carcinoma', 'IGC'),
'95': ('Washington University - Emory', 'Lung adenocarcinoma', 'IGC'),
'96': ('Washington University - NYU', 'Lung squamous cell carcinoma', 'IGC'),
'97': ('Washington University - NYU', 'Lung adenocarcinoma', 'IGC'),
'98': ('Washington University - Alabama', 'Lung squamous cell carcinoma', 'IGC'),
'99': ('Washington University - Alabama', 'Lung adenocarcinoma', 'IGC'),
'A1': ('UCSF', 'Breast invasive carcinoma', 'NCH'),
'A2': ('Walter Reed', 'Breast invasive carcinoma', 'NCH'),
'A3': ('International Genomics Consortium', 'Kidney renal clear cell carcinoma', 'IGC'),
'A4': ('International Genomics Consortium', 'Kidney renal papillary cell carcinoma', 'IGC'),
'A5': ('Cedars Sinai', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'A6': ('Christiana Healthcare', 'Colon adenocarcinoma', 'IGC'),
'A7': ('Christiana Healthcare', 'Breast invasive carcinoma', 'NCH'),
'A8': ('Indivumed', 'Breast invasive carcinoma', 'NCH'),
'AA': ('Indivumed', 'Colon adenocarcinoma', 'IGC'),
'AB': ('Washington University', 'Acute Myeloid Leukemia', 'NCH'),
'AC': ('International Genomics Consortium', 'Breast invasive carcinoma', 'NCH'),
'AD': ('International Genomics Consortium', 'Colon adenocarcinoma', 'IGC'),
'AF': ('Christiana Healthcare', 'Rectum adenocarcinoma', 'IGC'),
'AG': ('Indivumed', 'Rectum adenocarcinoma', 'IGC'),
'AH': ('International Genomics Consortium', 'Rectum adenocarcinoma', 'IGC'),
'AJ': ('International Genomics Conosrtium', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'AK': ('Fox Chase', 'Kidney renal clear cell carcinoma', 'IGC'),
'AL': ('Fox Chase', 'Kidney renal papillary cell carcinoma', 'IGC'),
'AM': ('Cureline', 'Colon adenocarcinoma', 'IGC'),
'AN': ('Cureline', 'Breast invasive carcinoma', 'NCH'),
'AO': ('MSKCC', 'Breast invasive carcinoma', 'NCH'),
'AP': ('MSKCC', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'AQ': ('UNC ', 'Breast invasive carcinoma', 'NCH'),
'AR': ('Mayo', 'Breast invasive carcinoma', 'NCH'),
'AS': ('St. Joseph\'s Medical Center-(MD)', 'Kidney renal clear cell carcinoma', 'IGC'),
'AT': ('St. Joseph\'s Medical Center-(MD)', 'Kidney renal papillary cell carcinoma', 'IGC'),
'AU': ('St. Joseph\'s Medical Center-(MD)', 'Colon adenocarcinoma', 'IGC'),
'AV': ('NCH', 'Cell Line Control', 'NCH'),
'AW': ('Cureline', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'AX': ('Gynecologic Oncology Group', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'AY': ('UNC', 'Colon adenocarcinoma', 'IGC'),
'AZ': ('University of Pittsburgh', 'Colon adenocarcinoma', 'IGC'),
'B0': ('University of Pittsburgh', 'Kidney renal clear cell carcinoma', 'IGC'),
'B1': ('University of Pittsburgh', 'Kidney renal papillary cell carcinoma', 'IGC'),
'B2': ('Christiana Healthcare', 'Kidney renal clear cell carcinoma', 'IGC'),
'B3': ('Christiana Healthcare', 'Kidney renal papillary cell carcinoma', 'IGC'),
'B4': ('Cureline', 'Kidney renal clear cell carcinoma', 'IGC'),
'B5': ('Duke', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'B6': ('Duke', 'Breast invasive carcinoma', 'NCH'),
'B7': ('Cureline', 'Stomach adenocarcinoma', 'IGC'),
'B8': ('UNC', 'Kidney renal clear cell carcinoma', 'IGC'),
'B9': ('UNC', 'Kidney renal papillary cell carcinoma', 'IGC'),
'BA': ('UNC', 'Head and Neck squamous cell carcinoma', 'IGC'),
'BB': ('Johns Hopkins', 'Head and Neck squamous cell carcinoma', 'IGC'),
'BC': ('UNC', 'Liver hepatocellular carcinoma', 'NCH'),
'BD': ('University of Pittsburgh', 'Liver hepatocellular carcinoma', 'NCH'),
'BF': ('Cureline', 'Skin Cutaneous Melanoma', 'NCH'),
'BG': ('University of Pittsburgh', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'BH': ('University of Pittsburgh', 'Breast invasive carcinoma', 'NCH'),
'BI': ('University of Pittsburgh', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'BJ': ('University of Pittsburgh', 'Thyroid carcinoma', 'IGC'),
'BK': ('Christiana Healthcare', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'BL': ('Christiana Healthcare', 'Bladder Urothelial Carcinoma', 'NCH'),
'BM': ('UNC', 'Rectum adenocarcinoma', 'IGC'),
'BP': ('MSKCC', 'Kidney renal clear cell carcinoma', 'IGC'),
'BQ': ('MSKCC', 'Kidney renal papillary cell carcinoma', 'IGC'),
'BR': ('Asterand', 'Stomach adenocarcinoma', 'IGC'),
'BS': ('University of Hawaii', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'BT': ('University of Pittsburgh', 'Bladder Urothelial Carcinoma', 'NCH'),
'BW': ('St. Joseph\'s Medical Center-(MD)', 'Liver hepatocellular carcinoma', 'NCH'),
'C4': ('Indivumed', 'Bladder Urothelial Carcinoma', 'NCH'),
'C5': ('Medical College of Wisconsin', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'C8': ('ILSBio', 'Breast invasive carcinoma', 'NCH'),
'C9': ('ILSBio', 'Head and Neck squamous cell carcinoma', 'NCH'),
'CA': ('ILSBio', 'Colon adenocarcinoma', 'IGC'),
'CB': ('ILSBio', 'Kidney renal clear cell carcinoma', 'IGC'),
'CC': ('ILSBio', 'Liver hepatocellular carcinoma', 'NCH'),
'CD': ('ILSBio', 'Stomach adenocarcinoma', 'IGC'),
'CE': ('ILSBio', 'Thyroid carcinoma', 'IGC'),
'CF': ('ILSBio', 'Bladder Urothelial Carcinoma', 'NCH'),
'CG': ('Indivumed', 'Stomach adenocarcinoma', 'IGC'),
'CH': ('Indivumed', 'Prostate adenocarcinoma', 'IGC'),
'CI': ('University of Pittsburgh', 'Rectum adenocarcinoma', 'IGC'),
'CJ': ('MD Anderson Cancer Center', 'Kidney renal clear cell carcinoma', 'IGC'),
'CK': ('Harvard', 'Colon adenocarcinoma', 'IGC'),
'CL': ('Harvard', 'Rectum adenocarcinoma', 'IGC'),
'CM': ('MSKCC', 'Colon adenocarcinoma', 'IGC'),
'CN': ('University of Pittsburgh', 'Head and Neck squamous cell carcinoma', 'IGC'),
'CQ': ('University Health Network, Toronto', 'Head and Neck squamous cell carcinoma', 'IGC'),
'CR': ('Vanderbilt University', 'Head and Neck squamous cell carcinoma', 'IGC'),
'CS': ('Thomas Jefferson University', 'Brain Lower Grade Glioma', 'IGC'),
'CU': ('UNC', 'Bladder Urothelial Carcinoma', 'NCH'),
'CV': ('MD Anderson Cancer Center', 'Head and Neck squamous cell carcinoma', 'IGC'),
'CW': ('Mayo Clinic - Rochester', 'Kidney renal clear cell carcinoma', 'IGC'),
'CX': ('Medical College of Georgia', 'Head and Neck squamous cell carcinoma', 'IGC'),
'CZ': ('Harvard', 'Kidney renal clear cell carcinoma', 'IGC'),
'D1': ('Mayo Clinic', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'D3': ('MD Anderson', 'Skin Cutaneous Melanoma', 'NCH'),
'D5': ('Greater Poland Cancer Center', 'Colon adenocarcinoma', 'IGC'),
'D6': ('Greater Poland Cancer Center', 'Head and Neck squamous cell carcinoma', 'IGC'),
'D7': ('Greater Poland Cancer Center', 'Stomach adenocarcinoma', 'IGC'),
'D8': ('Greater Poland Cancer Center', 'Breast invasive carcinoma', 'NCH'),
'D9': ('Greater Poland Cancer Center', 'Skin Cutaneous Melanoma', 'NCH'),
'DA': ('Yale', 'Skin Cutaneous Melanoma', 'NCH'),
'DB': ('Mayo Clinic - Rochester', 'Brain Lower Grade Glioma', 'IGC'),
'DC': ('MSKCC', 'Rectum adenocarcinoma', 'IGC'),
'DD': ('Mayo Clinic - Rochester', 'Liver hepatocellular carcinoma', 'NCH'),
'DE': ('University of North Carolina', 'Thyroid carcinoma', 'NCH'),
'DF': ('Ontario Institute for Cancer Research', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'DG': ('Ontario Institute for Cancer Research', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'DH': ('University of Florida', 'Brain Lower Grade Glioma', 'IGC'),
'DI': ('MD Anderson', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'DJ': ('Memorial Sloan Kettering', 'Thyroid carcinoma', 'NCH'),
'DK': ('Memorial Sloan Kettering', 'Bladder Urothelial Carcinoma', 'NCH'),
'DM': ('University Of Michigan', 'Colon adenocarcinoma', 'NCH'),
'DO': ('Medical College of Georgia', 'Thyroid carcinoma', 'NCH'),
'DQ': ('University Of Michigan', 'Head and Neck squamous cell carcinoma', 'IGC'),
'DR': ('University of Hawaii', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'DS': ('Cedars Sinai', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'DT': ('ILSBio', 'Rectum adenocarcinoma', 'IGC'),
'DU': ('Henry Ford Hospital', 'Brain Lower Grade Glioma', 'IGC'),
'DV': ('NCI Urologic Oncology Branch', 'Kidney renal clear cell carcinoma', 'IGC'),
'DW': ('NCI Urologic Oncology Branch', 'Kidney renal papillary cell carcinoma', 'IGC'),
'DX': ('Memorial Sloan Kettering', 'Sarcoma', 'NCH'),
'DY': ('University Of Michigan', 'Rectum adenocarcinoma', 'NCH'),
'DZ': ('Mayo Clinic - Rochester', 'Kidney renal papillary cell carcinoma', 'IGC'),
'E1': ('Duke', 'Brain Lower Grade Glioma', 'IGC'),
'E2': ('Roswell Park', 'Breast invasive carcinoma', 'NCH'),
'E3': ('Roswell Park', 'Thyroid carcinoma', 'NCH'),
'E5': ('Roswell Park', 'Bladder Urothelial Carcinoma', 'NCH'),
'E6': ('Roswell Park', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'E7': ('Asterand', 'Bladder Urothelial Carcinoma', 'NCH'),
'E8': ('Asterand', 'Thyroid carcinoma', 'NCH'),
'E9': ('Asterand', 'Breast invasive carcinoma', 'NCH'),
'EA': ('Asterand', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'EB': ('Asterand', 'Skin Cutaneous Melanoma', 'NCH'),
'EC': ('Asterand', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'ED': ('Asterand', 'Liver hepatocellular carcinoma', 'NCH'),
'EE': ('University of Sydney', 'Skin Cutaneous Melanoma', 'NCH'),
'EF': ('Cureline', 'Rectum adenocarcinoma', 'IGC'),
'EI': ('Greater Poland Cancer Center', 'Rectum adenocarcinoma', 'IGC'),
'EJ': ('University of Pittsburgh', 'Prostate adenocarcinoma', 'IGC'),
'EK': ('Gynecologic Oncology Group', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'EL': ('MD Anderson', 'Thyroid carcinoma', 'NCH'),
'EM': ('University Health Network', 'Thyroid carcinoma', 'NCH'),
'EO': ('University Health Network', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'EP': ('Christiana Healthcare', 'Liver hepatocellular carcinoma', 'NCH'),
'EQ': ('Christiana Healthcare', 'Stomach adenocarcinoma', 'IGC'),
'ER': ('University of Pittsburgh', 'Skin Cutaneous Melanoma', 'NCH'),
'ES': ('University of Florida', 'Liver hepatocellular carcinoma', 'NCH'),
'ET': ('Johns Hopkins', 'Thyroid carcinoma', 'NCH'),
'EU': ('CHI-Penrose Colorado', 'Kidney renal clear cell carcinoma', 'IGC'),
'EV': ('CHI-Penrose Colorado', 'Kidney renal papillary cell carcinoma', 'IGC'),
'EW': ('University of Miami', 'Breast invasive carcinoma', 'NCH'),
'EX': ('University of North Carolina', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'EY': ('University of North Carolina', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'EZ': ('UNC', 'Brain Lower Grade Glioma', 'IGC'),
'F1': ('UNC', 'Stomach adenocarcinoma', 'IGC'),
'F2': ('UNC', 'Pancreatic adenocarcinoma', 'IGC'),
'F4': ('Asterand', 'Colon adenocarcinoma', 'IGC'),
'F5': ('Asterand', 'Rectum adenocarcinoma', 'IGC'),
'F6': ('Asterand', 'Brain Lower Grade Glioma', 'IGC'),
'F7': ('Asterand', 'Head and Neck squamous cell carcinoma', 'IGC'),
'F9': ('Asterand', 'Kidney renal papillary cell carcinoma', 'IGC'),
'FA': ('Asterand', 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'IGC'),
'FB': ('Asterand', 'Pancreatic adenocarcinoma', 'IGC'),
'FC': ('Asterand', 'Prostate adenocarcinoma', 'IGC'),
'FD': ('BLN - University Of Chicago', 'Bladder Urothelial Carcinoma', 'NCH'),
'FE': ('Ohio State University', 'Thyroid carcinoma', 'NCH'),
'FF': ('SingHealth', 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'IGC'),
'FG': ('Case Western', 'Brain Lower Grade Glioma', 'IGC'),
'FH': ('CHI-Penrose Colorado', 'Thyroid carcinoma', 'NCH'),
'FI': ('Washington University', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'FJ': ('BLN - Baylor', 'Bladder Urothelial Carcinoma', 'NCH'),
'FK': ('Johns Hopkins', 'Thyroid carcinoma', 'NCH'),
'FL': ('University of Hawaii - Normal Study', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'FM': ('International Genomics Consortium', 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'IGC'),
'FN': ('International Genomics Consortium', 'Brain Lower Grade Glioma', 'IGC'),
'FP': ('International Genomics Consortium', 'Stomach adenocarcinoma', 'IGC'),
'FQ': ('Johns Hopkins', 'Pancreatic adenocarcinoma', 'IGC'),
'FR': ('University of North Carolina', 'Skin Cutaneous Melanoma', 'NCH'),
'FS': ('Essen', 'Skin Cutaneous Melanoma', 'NCH'),
'FT': ('BLN - University of Miami', 'Bladder Urothelial Carcinoma', 'NCH'),
'FU': ('International Genomics Consortium', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'FV': ('International Genomics Consortium', 'Liver hepatocellular carcinoma', 'NCH'),
'FW': ('International Genomics Consortium', 'Skin Cutaneous Melanoma', 'NCH'),
'FX': ('International Genomics Consortium', 'Sarcoma', 'NCH'),
'FY': ('International Genomics Consortium', 'Thyroid carcinoma', 'NCH'),
'FZ': ('University of Pittsburgh', 'Pancreatic adenocarcinoma', 'IGC'),
'G2': ('MD Anderson', 'Bladder Urothelial Carcinoma', 'NCH'),
'G3': ('Alberta Health Services', 'Liver hepatocellular carcinoma', 'NCH'),
'G4': ('Roswell Park', 'Colon adenocarcinoma', 'IGC'),
'G5': ('Roswell Park', 'Rectum adenocarcinoma', 'IGC'),
'G6': ('Roswell Park', 'Kidney renal clear cell carcinoma', 'IGC'),
'G7': ('Roswell Park', 'Kidney renal papillary cell carcinoma', 'IGC'),
'G8': ('Roswell Park', 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'IGC'),
'G9': ('Roswell Park', 'Prostate adenocarcinoma', 'IGC'),
'GC': ('International Genomics Consortium', 'Bladder Urothelial Carcinoma', 'NCH'),
'GD': ('ABS - IUPUI', 'Bladder Urothelial Carcinoma', 'NCH'),
'GE': ('ABS - IUPUI', 'Thyroid carcinoma', 'NCH'),
'GF': ('ABS - IUPUI', 'Skin Cutaneous Melanoma', 'NCH'),
'GG': ('ABS - IUPUI', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'GH': ('ABS - IUPUI', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'GI': ('ABS - IUPUI', 'Breast invasive carcinoma', 'NCH'),
'GJ': ('ABS - IUPUI', 'Liver hepatocellular carcinoma', 'NCH'),
'GK': ('ABS - IUPUI', 'Kidney renal clear cell carcinoma', 'IGC'),
'GL': ('ABS - IUPUI', 'Kidney renal papillary cell carcinoma', 'IGC'),
'GM': ('MD Anderson', 'Breast invasive carcinoma', 'NCH'),
'GN': ('Roswell', 'Skin Cutaneous Melanoma', 'NCH'),
'GP': ('MD Anderson', 'Acute Myeloid Leukemia', 'NCH'),
'GR': ('University of Nebraska Medical Center (UNMC)', 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'IGC'),
'GS': ('Fundacio Clinic per a la Recerca Biomedica', 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'IGC'),
'GU': ('BLN - UT Southwestern Medical Center at Dallas', 'Bladder Urothelial Carcinoma', 'NCH'),
'GV': ('BLN - Cleveland Clinic', 'Bladder Urothelial Carcinoma', 'NCH'),
'GZ': ('BC Cancer Agency', 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'IGC'),
'H1': ('Medical College of Georgia', 'Stomach adenocarcinoma', 'IGC'),
'H2': ('Christiana Healthcare', 'Thyroid carcinoma', 'NCH'),
'H3': ('ABS - IUPUI', 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'IGC'),
'H4': ('Medical College of Georgia', 'Bladder Urothelial Carcinoma', 'NCH'),
'H5': ('Medical College of Georgia', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'H6': ('Christiana Healthcare', 'Pancreatic adenocarcinoma', 'IGC'),
'H7': ('ABS - IUPUI', 'Head and Neck squamous cell carcinoma', 'IGC'),
'H8': ('ABS - IUPUI', 'Pancreatic adenocarcinoma', 'IGC'),
'H9': ('ABS - IUPUI', 'Prostate adenocarcinoma', 'IGC'),
'HA': ('Alberta Health Services', 'Stomach adenocarcinoma', 'IGC'),
'HB': ('University of North Carolina', 'Sarcoma', 'NCH'),
'HC': ('International Genomics Consortium', 'Prostate adenocarcinoma', 'IGC'),
'HD': ('International Genomics Consortium', 'Head and Neck squamous cell carcinoma', 'IGC'),
'HE': ('Ontario Institute for Cancer Research (OICR)', 'Kidney renal papillary cell carcinoma', 'IGC'),
'HF': ('Ontario Institute for Cancer Research (OICR)', 'Stomach adenocarcinoma', 'IGC'),
'HG': ('Roswell Park', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'HH': ('Fox Chase', 'Stomach adenocarcinoma', 'IGC'),
'HI': ('Fox Chase', 'Prostate adenocarcinoma', 'IGC'),
'HJ': ('Fox Chase', 'Stomach adenocarcinoma', 'IGC'),
'HK': ('Fox Chase', 'Brain Lower Grade Glioma', 'IGC'),
'HL': ('Fox Chase', 'Head and Neck squamous cell carcinoma', 'IGC'),
'HM': ('Christiana Healthcare', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'HN': ('Ontario Institute for Cancer Research (OICR)', 'Breast invasive carcinoma', 'NCH'),
'HP': ('Ontario Institute for Cancer Research (OICR)', 'Liver hepatocellular carcinoma', 'NCH'),
'HQ': ('Ontario Institute for Cancer Research (OICR)', 'Bladder Urothelial Carcinoma', 'NCH'),
'HR': ('Ontario Institute for Cancer Research (OICR)', 'Skin Cutaneous Melanoma', 'NCH'),
'HS': ('Ontario Institute for Cancer Research (OICR)', 'Sarcoma', 'NCH'),
'HT': ('Case Western - St Joes', 'Brain Lower Grade Glioma', 'IGC'),
'HU': ('National Cancer Center Korea', 'Stomach adenocarcinoma', 'IGC'),
'HV': ('National Cancer Center Korea', 'Pancreatic adenocarcinoma', 'IGC'),
'HW': ('MSKCC', 'Brain Lower Grade Glioma', 'IGC'),
'HZ': ('International Genomics Consortium', 'Pancreatic adenocarcinoma', 'IGC'),
'IA': ('Cleveland Clinic', 'Kidney renal papillary cell carcinoma', 'IGC'),
'IB': ('Alberta Health Services', 'Pancreatic adenocarcinoma', 'IGC'),
'IC': ('University of Pittsburgh', 'Esophageal carcinoma ', 'NCH'),
'IE': ('ABS - IUPUI', 'Sarcoma', 'NCH'),
'IF': ('University of Texas MD Anderson Cancer Center', 'Sarcoma', 'NCH'),
'IG': ('Asterand', 'Esophageal carcinoma ', 'NCH'),
'IH': ('University of Miami', 'Skin Cutaneous Melanoma', 'NCH'),
'IJ': ('Christiana Healthcare', 'Acute Myeloid Leukemia', 'NCH'),
'IK': ('Christiana Healthcare', 'Brain Lower Grade Glioma', 'IGC'),
'IM': ('University of Miami', 'Thyroid carcinoma', 'NCH'),
'IN': ('University of Pittsburgh', 'Stomach adenocarcinoma', 'IGC'),
'IP': ('ABS - IUPUI', 'Stomach adenocarcinoma', 'IGC'),
'IQ': ('University of Miami', 'Head and Neck squamous cell carcinoma', 'IGC'),
'IR': ('Memorial Sloan Kettering', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'IS': ('Memorial Sloan Kettering', 'Sarcoma', 'NCH'),
'IW': ('Cedars Sinai', 'Sarcoma', 'NCH'),
'IZ': ('ABS - Lahey Clinic', 'Kidney renal papillary cell carcinoma', 'IGC'),
'J1': ('ABS - Lahey Clinic', 'Lung squamous cell carcinoma', 'IGC'),
'J2': ('ABS - Lahey Clinic', 'Lung adenocarcinoma', 'IGC'),
'J4': ('ABS - Lahey Clinic', 'Prostate adenocarcinoma', 'IGC'),
'J7': ('ILSBio', 'Kidney renal papillary cell carcinoma', 'IGC'),
'J8': ('Mayo Clinic', 'Thyroid carcinoma', 'NCH'),
'J9': ('Melbourne Health', 'Prostate adenocarcinoma', 'IGC'),
'JA': ('ABS - Research Metrics Pakistan', 'Head and Neck squamous cell carcinoma', 'IGC'),
'JL': ('ABS - Research Metrics Pakistan', 'Breast invasive carcinoma', 'NCH'),
'JU': ('BLN - Baylor', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'JV': ('BLN - Baylor', 'Sarcoma', 'NCH'),
'JW': ('BLN - Baylor', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'JX': ('Washington University', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'JY': ('University Health Network', 'Esophageal carcinoma ', 'NCH'),
'JZ': ('University of Rochester', 'Esophageal carcinoma ', 'NCH'),
'K1': ('University of Pittsburgh', 'Sarcoma', 'NCH'),
'K4': ('ABS - Lahey Clinic', 'Bladder Urothelial Carcinoma', 'NCH'),
'K6': ('ABS - Lahey Clinic', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'K7': ('ABS - Lahey Clinic', 'Liver hepatocellular carcinoma', 'NCH'),
'K8': ('ABS - Lahey Clinic', 'Skin Cutaneous Melanoma', 'NCH'),
'KA': ('ABS - Lahey Clinic', 'Esophageal carcinoma ', 'NCH'),
'KB': ('University Health Network, Toronto', 'Stomach adenocarcinoma', 'IGC'),
'KC': ('Cornell Medical College', 'Prostate adenocarcinoma', 'IGC'),
'KD': ('Mount Sinai School of Medicine', 'Sarcoma', 'NCH'),
'KE': ('Mount Sinai School of Medicine', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'KF': ('Christiana Healthcare', 'Sarcoma', 'NCH'),
'KG': ('Baylor Network', 'Pancreatic adenocarcinoma', 'IGC'),
'KH': ('Memorial Sloan Kettering', 'Esophageal carcinoma ', 'NCH'),
'KJ': ('University of Miami', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'KK': ('MD Anderson Cancer Center', 'Prostate adenocarcinoma', 'IGC'),
'KL': ('MSKCC', 'Kidney Chromophobe', 'IGC'),
'KM': ('NCI Urologic Oncology Branch', 'Kidney Chromophobe', 'IGC'),
'KN': ('Harvard', 'Kidney Chromophobe', 'IGC'),
'KO': ('MD Anderson Cancer Center', 'Kidney Chromophobe', 'IGC'),
'KP': ('British Columbia Cancer Agency', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'KQ': ('Cornell Medical College', 'Bladder Urothelial Carcinoma', 'NCH'),
'KR': ('University Of Michigan', 'Liver hepatocellular carcinoma', 'NCH'),
'KS': ('University Of Michigan', 'Thyroid carcinoma', 'NCH'),
'KT': ('Hartford', 'Brain Lower Grade Glioma', 'IGC'),
'KU': ('Hartford', 'Head and Neck squamous cell carcinoma', 'IGC'),
'KV': ('Hartford', 'Kidney renal papillary cell carcinoma', 'IGC'),
'KZ': ('Hartford', 'Stomach adenocarcinoma', 'IGC'),
'L1': ('Hartford', 'Pancreatic adenocarcinoma', 'IGC'),
'L3': ('Gundersen Lutheran Health System', 'Lung squamous cell carcinoma', 'IGC'),
'L4': ('Gundersen Lutheran Health System', 'Lung adenocarcinoma', 'IGC'),
'L5': ('University of Michigan', 'Esophageal carcinoma ', 'NCH'),
'L6': ('National Institutes of Health', 'Thyroid carcinoma', 'NCH'),
'L7': ('Christiana Care', 'Esophageal carcinoma ', 'NCH'),
'L8': ('University of Miami', 'Kidney renal papillary cell carcinoma', 'NCH'),
'L9': ('Candler', 'Lung adenocarcinoma', 'IGC'),
'LA': ('Candler', 'Lung squamous cell carcinoma', 'IGC'),
'LB': ('Candler', 'Pancreatic adenocarcinoma', 'IGC'),
'LC': ('Hartford Hospital', 'Bladder Urothelial Carcinoma', 'NCH'),
'LD': ('Hartford Hospital', 'Breast invasive carcinoma', 'NCH'),
'LG': ('Hartford Hospital', 'Liver hepatocellular carcinoma', 'NCH'),
'LH': ('Hartford Hospital', 'Skin Cutaneous Melanoma', 'NCH'),
'LI': ('Hartford Hospital', 'Sarcoma', 'NCH'),
'LK': ('University of Pittsburgh', 'Mesothelioma', 'NCH'),
'LL': ('Candler', 'Breast invasive carcinoma', 'NCH'),
'LN': ('ILSBIO', 'Esophageal carcinoma ', 'NCH'),
'LP': ('ILSBIO', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'LQ': ('Gundersen Lutheran Health System', 'Breast invasive carcinoma', 'NCH'),
'LS': ('Gundersen Lutheran Health System', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'LT': ('Gundersen Lutheran Health System', 'Bladder Urothelial Carcinoma', 'NCH'),
'M7': ('University of North Carolina', 'Prostate adenocarcinoma', 'NCH'),
'M8': ('Ontario Institute for Cancer Research (OICR)', 'Pancreatic adenocarcinoma', 'NCH'),
'M9': ('Ontario Institute for Cancer Research (OICR)', 'Esophageal carcinoma ', 'NCH'),
'MA': ('MD Anderson Cancer Center', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'MB': ('University of Minnesota', 'Sarcoma', 'NCH'),
'ME': ('University of Minnesota', 'Lung adenocarcinoma', 'NCH'),
'MF': ('University of Minnesota', 'Lung squamous cell carcinoma', 'NCH'),
'MG': ('BLN - Baylor', 'Prostate adenocarcinoma', 'NCH'),
'MH': ('BLN - Baylor', 'Kidney renal papillary cell carcinoma', 'NCH'),
'MI': ('BLN - Baylor', 'Liver hepatocellular carcinoma', 'NCH'),
'MJ': ('BLN - Baylor', 'Sarcoma', 'NCH'),
'MK': ('BLN - Baylor', 'Thyroid carcinoma', 'NCH'),
'ML': ('BLN - Baylor', 'Lung squamous cell carcinoma', 'NCH'),
'MM': ('BLN - Baylor', 'Kidney renal clear cell carcinoma', 'NCH'),
'MN': ('BLN - Baylor', 'Lung adenocarcinoma', 'NCH'),
'MO': ('ILSBio', 'Sarcoma', 'NCH'),
'MP': ('Washington University - Mayo Clinic', 'Lung adenocarcinoma', 'NCH'),
'MQ': ('Washington University - NYU', 'Mesothelioma', 'NCH'),
'MR': ('University of Minnesota', 'Liver hepatocellular carcinoma', 'NCH'),
'MS': ('University of Minnesota', 'Breast invasive carcinoma', 'NCH'),
'MT': ('University of Minnesota', 'Head and Neck squamous cell carcinoma', 'NCH'),
'MU': ('University of Minnesota', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'MV': ('University of Minnesota', 'Bladder Urothelial Carcinoma', 'NCH'),
'MW': ('University of Miami', 'Kidney renal clear cell carcinoma', 'NCH'),
'MX': ('MSKCC', 'Stomach adenocarcinoma', 'NCH'),
'MY': ('Montefiore Medical Center', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'MZ': ('Montefiore Medical Center', 'Head and Neck squamous cell carcinoma', 'NCH'),
'N1': ('Montefiore Medical Center', 'Sarcoma', 'NCH'),
'N5': ('MSKCC', 'Uterine Carcinosarcoma', 'NCH'),
'N6': ('University of Pittsburgh', 'Uterine Carcinosarcoma', 'NCH'),
'N7': ('Washington University', 'Uterine Carcinosarcoma', 'NCH'),
'N8': ('University of North Carolina', 'Uterine Carcinosarcoma', 'NCH'),
'N9': ('MD Anderson', 'Uterine Carcinosarcoma', 'NCH'),
'NA': ('Duke University', 'Uterine Carcinosarcoma', 'NCH'),
'NB': ('Washington University - CHUV', 'Lung adenocarcinoma', 'NCH'),
'NC': ('Washington University - CHUV', 'Lung squamous cell carcinoma', 'NCH'),
'ND': ('Cedars Sinai', 'Uterine Carcinosarcoma', 'NCH'),
'NF': ('Mayo Clinic - Rochester', 'Uterine Carcinosarcoma', 'NCH'),
'NG': ('Roswell Park', 'Uterine Carcinosarcoma', 'NCH'),
'NH': ('Candler', 'Colon adenocarcinoma', 'NCH'),
'NI': ('Roswell Park', 'Liver hepatocellular carcinoma', 'NCH'),
'NJ': ('Washington University - Rush University', 'Lung adenocarcinoma', 'NCH'),
'NK': ('Washington University - Rush University', 'Lung squamous cell carcinoma', 'NCH'),
'NM': ('Cambridge BioSource', 'Head and Neck squamous cell carcinoma', 'NCH'),
'NP': ('International Genomics Consortium', 'Kidney Chromophobe', 'NCH'),
'NQ': ('International Genomics Consortium', 'Mesothelioma', 'NCH'),
'NS': ('Gundersen Lutheran Health System', 'Skin Cutaneous Melanoma', 'NCH'),
'O1': ('Washington University - CALGB', 'Lung adenocarcinoma', 'NCH'),
'O2': ('Washington University - CALGB', 'Lung squamous cell carcinoma', 'NCH'),
'O8': ('Saint Mary\'s Health Care', 'Liver hepatocellular carcinoma', 'NCH'),
'O9': ('Saint Mary\'s Health Care', 'Kidney renal papillary cell carcinoma', 'NCH'),
'OC': ('Saint Mary\'s Health Care', 'Lung squamous cell carcinoma', 'NCH'),
'OD': ('Saint Mary\'s Health Care', 'Skin Cutaneous Melanoma', 'NCH'),
'OE': ('Saint Mary\'s Health Care', 'Pancreatic adenocarcinoma', 'NCH'),
'OJ': ('Saint Mary\'s Health Care', 'Thyroid carcinoma', 'NCH'),
'OK': ('Mount Sinai School of Medicine', 'Breast invasive carcinoma', 'NCH'),
'OL': ('University of Chicago', 'Breast invasive carcinoma', 'NCH'),
'OR': ('University of Michigan', 'Adrenocortical carcinoma', 'NCH'),
'OU': ('Roswell Park', 'Adrenocortical carcinoma', 'NCH'),
'OW': ('International Genomics Consortium', 'Miscellaneous', 'NCH'),
'OX': ('University of North Carolina', 'Glioblastoma multiforme', 'NCH'),
'OY': ('University of North Carolina', 'Ovarian serous cystadenocarcinoma', 'NCH'),
'P3': ('Fred Hutchinson', 'Head and Neck squamous cell carcinoma', 'NCH'),
'P4': ('MD Anderson Cancer Center', 'Kidney renal papillary cell carcinoma', 'NCH'),
'P5': ('Cureline', 'Brain Lower Grade Glioma', 'NCH'),
'P6': ('Translational Genomics Research Institute', 'Adrenocortical carcinoma', 'NCH'),
'P7': ('Translational Genomics Research Institute', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'P8': ('University of Pittsburgh', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'P9': ('University of Minnesota', 'Pancreatic adenocarcinoma', 'NCH'),
'PA': ('University of Minnesota', 'Adrenocortical carcinoma', 'NCH'),
'PB': ('University of Minnesota', 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'NCH'),
'PC': ('Fox Chase', 'Sarcoma', 'NCH'),
'PD': ('Fox Chase', 'Liver hepatocellular carcinoma', 'NCH'),
'PE': ('Fox Chase', 'Breast invasive carcinoma', 'NCH'),
'PG': ('Montefiore Medical Center', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'PH': ('Gundersen Lutheran', 'Acute Myeloid Leukemia', 'NCH'),
'PJ': ('Gundersen Lutheran', 'Kidney renal papillary cell carcinoma', 'NCH'),
'PK': ('University Health Network', 'Adrenocortical carcinoma', 'NCH'),
'PL': ('Institute of Human Virology Nigeria', 'Breast invasive carcinoma', 'NCH'),
'PN': ('Institute of Human Virology Nigeria', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'PQ': ('University of Colorado Denver', 'Bladder Urothelial Carcinoma', 'NCH'),
'PR': ('Roswell Park', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'PT': ('Maine Medical Center', 'Sarcoma', 'NCH'),
'PZ': ('ABS - Lahey Clinic', 'Pancreatic adenocarcinoma', 'NCH'),
'Q1': ('University of Oklahoma HSC', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'Q2': ('University of Oklahoma HSC', 'Kidney renal papillary cell carcinoma', 'NCH'),
'Q3': ('University of Oklahoma HSC', 'Pancreatic adenocarcinoma', 'NCH'),
'Q4': ('Emory University', 'Acute Myeloid Leukemia', 'NCH'),
'Q9': ('Emory University', 'Esophageal carcinoma ', 'NCH'),
'QA': ('Emory University', 'Liver hepatocellular carcinoma', 'NCH'),
'QB': ('Emory University', 'Skin Cutaneous Melanoma', 'NCH'),
'QC': ('Emory University', 'Sarcoma', 'NCH'),
'QD': ('Emory University', 'Thyroid carcinoma', 'NCH'),
'QF': ('BLN - Baylor', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'QG': ('BLN - Baylor', 'Colon adenocarcinoma', 'NCH'),
'QH': ('Fondazione-Besta', 'Brain Lower Grade Glioma', 'NCH'),
'QJ': ('Mount Sinai School of Medicine', 'Ovarian serous cystadenocarcinoma', 'NCH'),
'QK': ('Emory University - Winship Cancer Inst.', 'Head and Neck squamous cell carcinoma', 'NCH'),
'QL': ('University of Chicago', 'Colon adenocarcinoma', 'NCH'),
'QM': ('University of Oklahoma HSC', 'Uterine Carcinosarcoma', 'NCH'),
'QN': ('ILSBio', 'Uterine Carcinosarcoma', 'NCH'),
'QQ': ('Roswell Park', 'Sarcoma', 'NCH'),
'QR': ('National Institutes of Health', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'QS': ('Candler', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'QT': ('University of North Carolina', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'QU': ('Harvard Beth Israel', 'Prostate adenocarcinoma', 'NCH'),
'QV': ('Instituto Nacional de Cancerologia', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'QW': ('Instituto Nacional de Cancerologia', 'Stomach adenocarcinoma', 'NCH'),
'R1': ('CHI-Penrose Colorado', 'Colon adenocarcinoma', 'NCH'),
'R2': ('CHI-Penrose Colorado', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'R3': ('CHI-Penrose Colorado', 'Bladder Urothelial Carcinoma', 'NCH'),
'R5': ('MD Anderson Cancer Center', 'Stomach adenocarcinoma', 'NCH'),
'R6': ('MD Anderson Cancer Center', 'Esophageal carcinoma ', 'NCH'),
'R7': ('Gundersen Lutheran Health System', 'Head and Neck squamous cell carcinoma', 'NCH'),
'R8': ('MD Anderson', 'Brain Lower Grade Glioma', 'NCH'),
'R9': ('Candler', 'Ovarian serous cystadenocarcinoma', 'NCH'),
'RA': ('Candler', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'RB': ('Emory University', 'Pancreatic adenocarcinoma', 'NCH'),
'RC': ('University of Utah', 'Liver hepatocellular carcinoma', 'NCH'),
'RD': ('Peter MacCallum Cancer Center', 'Stomach adenocarcinoma', 'NCH'),
'RE': ('Peter MacCallum Cancer Center', 'Esophageal carcinoma ', 'NCH'),
'RG': ('Montefiore Medical Center', 'Liver hepatocellular carcinoma', 'NCH'),
'RH': ('BLN - Baylor', 'Head and Neck squamous cell carcinoma', 'NCH'),
'RL': ('St. Joseph\'s Hospital AZ', 'Pancreatic adenocarcinoma', 'NCH'),
'RM': ('St. Joseph\'s Hospital AZ', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'RN': ('St. Joseph\'s Hospital AZ', 'Sarcoma', 'NCH'),
'RP': ('St. Joseph\'s Hospital AZ', 'Skin Cutaneous Melanoma', 'NCH'),
'RQ': ('St. Joseph\'s Hospital AZ', 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'NCH'),
'RR': ('St. Joseph\'s Hospital AZ', 'Glioblastoma multiforme', 'NCH'),
'RS': ('Memorial Sloan Kettering Cancer Center', 'Head and Neck squamous cell carcinoma', 'NCH'),
'RT': ('Cleveland Clinic Foundation', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'RU': ('Northwestern University', 'Colon adenocarcinoma', 'NCH'),
'RV': ('Northwestern University', 'Pancreatic adenocarcinoma', 'NCH'),
'RW': ('Michigan University', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'RX': ('University of Minnesota', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'RY': ('University of California San Francisco', 'Brain Lower Grade Glioma', 'NCH'),
'RZ': ('Wills Eye Institute', 'Uveal Melanoma', 'NCH'),
'S2': ('Albert Einstein Medical Center', 'Lung adenocarcinoma', 'NCH'),
'S3': ('Albert Einstein Medical Center', 'Breast invasive carcinoma', 'NCH'),
'S4': ('University of Chicago', 'Pancreatic adenocarcinoma', 'NCH'),
'S5': ('University of Oklahoma HSC', 'Bladder Urothelial Carcinoma', 'NCH'),
'S6': ('Gundersen Lutheran Health System', 'Testicular Germ Cell Tumors', 'NCH'),
'S7': ('University Hospital Motol', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'S8': ('ABS - IUPUI', 'Esophageal carcinoma ', 'NCH'),
'S9': ('Dept of Neurosurgery at University of Heidelberg', 'Brain Lower Grade Glioma', 'NCH'),
'SA': ('ABS - IUPUI', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'SB': ('Baylor College of Medicine', 'Testicular Germ Cell Tumors', 'NCH'),
'SC': ('Memorial Sloan Kettering', 'Mesothelioma', 'NCH'),
'SD': ('MD Anderson', 'Pancreatic adenocarcinoma', 'NCH'),
'SE': ('Boston Medical Center', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'SG': ('Cleveland Clinic Foundation', 'Sarcoma', 'NCH'),
'SH': ('Papworth Hospital', 'Mesothelioma', 'NCH'),
'SI': ('Washington University St. Louis', 'Sarcoma', 'NCH'),
'SJ': ('Albert Einstein Medical Center', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'SK': ('St. Joseph\'s Hospital AZ', 'Colon adenocarcinoma', 'NCH'),
'SL': ('St. Joseph\'s Hospital AZ', 'Uterine Corpus Endometrial Carcinoma', 'NCH'),
'SN': ('BLN - Baylor', 'Testicular Germ Cell Tumors', 'NCH'),
'SO': ('University of Minnesota', 'Testicular Germ Cell Tumors', 'NCH'),
'SP': ('University Health Network', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'SQ': ('International Genomics Consortium', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'SR': ('Tufts Medical Center', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'SS': ('Medical College of Georgia', 'Colon adenocarcinoma', 'NCH'),
'ST': ('Global Bioclinical-Moldova', 'Head and Neck squamous cell carcinoma', 'NCH'),
'SU': ('Global Bioclinical-Moldova', 'Prostate adenocarcinoma', 'NCH'),
'SW': ('Global Bioclinical-Moldova', 'Stomach adenocarcinoma', 'NCH'),
'SX': ('Mayo Clinic Arizona', 'Kidney renal papillary cell carcinoma', 'NCH'),
'SY': ('Mayo Clinic Arizona', 'Bladder Urothelial Carcinoma', 'NCH'),
'T1': ('St. Joseph\'s Hospital Arizona', 'Liver hepatocellular carcinoma', 'NCH'),
'T2': ('St. University of Colorado Denver', 'Head and Neck squamous cell carcinoma', 'NCH'),
'T3': ('Molecular Response', 'Head and Neck squamous cell carcinoma', 'NCH'),
'T6': ('Molecular Response', 'Lung adenocarcinoma', 'NCH'),
'T7': ('Molecular Response', 'Kidney renal clear cell carcinoma', 'NCH'),
'T9': ('Molecular Response', 'Colon adenocarcinoma', 'NCH'),
'TE': ('Global BioClinical - Georgia', 'Skin Cutaneous Melanoma', 'NCH'),
'TG': ('Global BioClinical - Georgia', 'Head and Neck squamous cell carcinoma', 'NCH'),
'TK': ('Global BioClinical - Georgia', 'Prostate adenocarcinoma', 'NCH'),
'TL': ('Global BioClinical - Georgia', 'Stomach adenocarcinoma', 'NCH'),
'TM': ('The University of New South Wales', 'Brain Lower Grade Glioma', 'NCH'),
'TN': ('Ohio State University', 'Head and Neck squamous cell carcinoma', 'NCH'),
'TP': ('Maine Medical Center', 'Prostate adenocarcinoma', 'NCH'),
'TQ': ('University of Sao Paulo', 'Brain Lower Grade Glioma', 'NCH'),
'TR': ('Global Bioclinical-Moldova', 'Skin Cutaneous Melanoma', 'NCH'),
'TS': ('University of Pennsylvania', 'Mesothelioma', 'NCH'),
'TT': ('University of Pennsylvania', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'TV': ('Wake Forest University', 'Breast invasive carcinoma', 'NCH'),
'UB': ('UCSF', 'Liver hepatocellular carcinoma', 'NCH'),
'UC': ('University of Washington', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'UD': ('University of Western Australia', 'Mesothelioma', 'NCH'),
'UE': ('Asterand', 'Sarcoma', 'NCH'),
'UF': ('Barretos Cancer Hospital', 'Head and Neck squamous cell carcinoma', 'NCH'),
'UJ': ('Boston Medical Center', 'Lung squamous cell carcinoma', 'NCH'),
'UL': ('Boston Medical Center', 'Breast invasive carcinoma', 'NCH'),
'UN': ('Boston Medical Center', 'Kidney renal papillary cell carcinoma', 'NCH'),
'UP': ('Boston Medical Center', 'Head and Neck squamous cell carcinoma', 'NCH'),
'UR': ('Boston Medical Center', 'Prostate adenocarcinoma', 'NCH'),
'US': ('Garvan Institute of Medical Research', 'Pancreatic adenocarcinoma', 'NCH'),
'UT': ('Asbestos Diseases Research Institute', 'Mesothelioma', 'NCH'),
'UU': ('Mary Bird Perkins Cancer Center - Our Lady of the Lake', 'Breast invasive carcinoma', 'NCH'),
'UV': ('Capital Biosciences', 'Liver hepatocellular carcinoma', 'NCH'),
'UW': ('University of North Carolina', 'Kidney Chromophobe', 'NCH'),
'UY': ('University of California San Francisco', 'Bladder Urothelial Carcinoma', 'NCH'),
'UZ': ('University of California San Francisco', 'Kidney renal papillary cell carcinoma', 'NCH'),
'V1': ('University of California San Francisco', 'Prostate adenocarcinoma', 'NCH'),
'V2': ('Cleveland Clinic Foundation', 'Prostate adenocarcinoma', 'NCH'),
'V3': ('Cleveland Clinic Foundation', 'Uveal Melanoma', 'NCH'),
'V4': ('Institut Curie', 'Uveal Melanoma', 'NCH'),
'V5': ('Duke University', 'Esophageal carcinoma ', 'NCH'),
'V6': ('Duke University', 'Stomach adenocarcinoma', 'NCH'),
'V7': ('Medical College of Georgia', 'Breast invasive carcinoma', 'NCH'),
'V8': ('Medical College of Georgia', 'Kidney renal clear cell carcinoma', 'NCH'),
'V9': ('Medical College of Georgia', 'Kidney renal papillary cell carcinoma', 'NCH'),
'VA': ('Alliance', 'Stomach adenocarcinoma', 'NCH'),
'VB': ('Global BioClinical - Georgia', 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'NCH'),
'VD': ('University of Liverpool', 'Uveal Melanoma', 'NCH'),
'VF': ('University of Pennsylvania', 'Testicular Germ Cell Tumors', 'NCH'),
'VG': ('Institute of Human Virology Nigeria', 'Ovarian serous cystadenocarcinoma', 'NCH'),
'VK': ('Institute of Human Virology Nigeria', 'Colon adenocarcinoma', 'NCH'),
'VL': ('Institute of Human Virology Nigeria', 'Rectum adenocarcinoma', 'NCH'),
'VM': ('Huntsman Cancer Institute', 'Brain Lower Grade Glioma', 'NCH'),
'VN': ('NCI Urologic Oncology Branch', 'Prostate adenocarcinoma', 'NCH'),
'VP': ('Washington University', 'Prostate adenocarcinoma', 'NCH'),
'VQ': ('Barretos Cancer Hospital', 'Stomach adenocarcinoma', 'NCH'),
'VR': ('Barretos Cancer Hospital', 'Esophageal carcinoma ', 'NCH'),
'VS': ('Barretos Cancer Hospital', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'VT': ('Vanderbilt', 'Sarcoma', 'NCH'),
'VV': ('John Wayne Cancer Center', 'Brain Lower Grade Glioma', 'NCH'),
'VW': ('Northwestern University', 'Brain Lower Grade Glioma', 'NCH'),
'VX': ('Northwestern University', 'Stomach adenocarcinoma', 'NCH'),
'VZ': ('Albert Einstein Medical Center', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'W2': ('Medical College of Wisconsin', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'W3': ('John Wayne Cancer Center', 'Skin Cutaneous Melanoma', 'NCH'),
'W4': ('University of North Carolina', 'Testicular Germ Cell Tumors', 'NCH'),
'W5': ('Mayo Clinic Rochester', 'Cholangiocarcinoma', 'NCH'),
'W6': ('UCSF', 'Cholangiocarcinoma', 'NCH'),
'W7': ('Garvan Institute of Medical Research', 'Cholangiocarcinoma', 'NCH'),
'W8': ('Greenville Health System', 'Breast invasive carcinoma', 'NCH'),
'W9': ('University of Kansas', 'Brain Lower Grade Glioma', 'NCH'),
'WA': ('University of Schleswig-Holstein', 'Head and Neck squamous cell carcinoma', 'NCH'),
'WB': ('Erasmus MC', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'WC': ('MD Anderson', 'Uveal Melanoma', 'NCH'),
'WD': ('Emory University', 'Cholangiocarcinoma', 'NCH'),
'WE': ('Norfolk and Norwich Hospital', 'Skin Cutaneous Melanoma', 'NCH'),
'WF': ('Greenville Health System', 'Pancreatic adenocarcinoma', 'NCH'),
'WG': ('Greenville Health System', 'Lung squamous cell carcinoma', 'NCH'),
'WH': ('Greenville Health System', 'Brain Lower Grade Glioma', 'NCH'),
'WJ': ('Greenville Health System', 'Liver hepatocellular carcinoma', 'NCH'),
'WK': ('Brigham and Women\'s Hospital', 'Sarcoma', 'NCH'),
'WL': ('University of Kansas', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'WM': ('University of Kansas', 'Kidney renal clear cell carcinoma', 'NCH'),
'WN': ('University of Kansas', 'Kidney renal papillary cell carcinoma', 'NCH'),
'WP': ('University of Kansas', 'Sarcoma', 'NCH'),
'WQ': ('University of Kansas', 'Liver hepatocellular carcinoma', 'NCH'),
'WR': ('University of Kansas', 'Ovarian serous cystadenocarcinoma', 'NCH'),
'WS': ('University of Kansas', 'Colon adenocarcinoma', 'NCH'),
'WT': ('University of Kansas', 'Breast invasive carcinoma', 'NCH'),
'WU': ('Wake Forest University', 'Colon adenocarcinoma', 'NCH'),
'WW': ('Wake Forest University', 'Prostate adenocarcinoma', 'NCH'),
'WX': ('Yale University', 'Liver hepatocellular carcinoma', 'NCH'),
'WY': ('Johns Hopkins', 'Brain Lower Grade Glioma', 'NCH'),
'WZ': ('International Genomics Consortium', 'Testicular Germ Cell Tumors', 'NCH'),
'X2': ('University of Washington', 'Sarcoma', 'NCH'),
'X3': ('Cleveland Clinic Foundation', 'Testicular Germ Cell Tumors', 'NCH'),
'X4': ('Institute for Medical Research', 'Prostate adenocarcinoma', 'NCH'),
'X5': ('Institute of Human Virology Nigeria', 'Bladder Urothelial Carcinoma', 'NCH'),
'X6': ('University of Iowa', 'Sarcoma', 'NCH'),
'X7': ('ABS IUPUI', 'Thymoma', 'NCH'),
'X8': ('St. Joseph\'s Hospital Arizona', 'Esophageal carcinoma ', 'NCH'),
'X9': ('University of California, Davis', 'Sarcoma', 'NCH'),
'XA': ('University of Minnesota', 'Prostate adenocarcinoma', 'NCH'),
'XB': ('Albert Einstein Medical Center', 'Esophageal carcinoma ', 'NCH'),
'XC': ('Albert Einstein Medical Center', 'Lung squamous cell carcinoma', 'NCH'),
'XD': ('Providence Portland Medical Center', 'Pancreatic adenocarcinoma', 'NCH'),
'XE': ('University of Southern California', 'Testicular Germ Cell Tumors', 'NCH'),
'XF': ('University of Southern California', 'Bladder Urothelial Carcinoma', 'NCH'),
'XG': ('BLN UT Southwestern Medical Center at Dallas', 'Pheochromocytoma and Paraganglioma', 'NCH'),
'XH': ('BLN Baylor', 'Thymoma', 'NCH'),
'XJ': ('University of Kansas', 'Prostate adenocarcinoma', 'NCH'),
'XK': ('Mayo Clinic Arizona', 'Prostate adenocarcinoma', 'NCH'),
'XM': ('MSKCC', 'Thymoma', 'NCH'),
'XN': ('University of Sao Paulo', 'Pancreatic adenocarcinoma', 'NCH'),
'XP': ('University of Sao Paulo', 'Esophageal carcinoma ', 'NCH'),
'XQ': ('University of Sao Paulo', 'Prostate adenocarcinoma', 'NCH'),
'XR': ('University of Sao Paulo', 'Liver hepatocellular carcinoma', 'NCH'),
'XS': ('University of Sao Paulo', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'XT': ('Johns Hopkins', 'Mesothelioma', 'NCH'),
'XU': ('University Health Network', 'Thymoma', 'NCH'),
'XV': ('Capital Biosciences', 'Skin Cutaneous Melanoma', 'NCH'),
'XX': ('Spectrum Health', 'Breast invasive carcinoma', 'NCH'),
'XY': ('Spectrum Health', 'Testicular Germ Cell Tumors', 'NCH'),
'Y3': ('University of New Mexico', 'Acute Myeloid Leukemia', 'NCH'),
'Y5': ('University of Arizona', 'Sarcoma', 'NCH'),
'Y6': ('University of Arizona', 'Prostate adenocarcinoma', 'NCH'),
'Y8': ('Spectrum Health', 'Kidney renal papillary cell carcinoma', 'NCH'),
'YA': ('Spectrum Health', 'Liver hepatocellular carcinoma', 'NCH'),
'YB': ('Spectrum Health', 'Pancreatic adenocarcinoma', 'NCH'),
'YC': ('Spectrum Health', 'Bladder Urothelial Carcinoma', 'NCH'),
'YD': ('Spectrum Health', 'Skin Cutaneous Melanoma', 'NCH'),
'YF': ('University of Puerto Rico', 'Bladder Urothelial Carcinoma', 'NCH'),
'YG': ('University of Puerto Rico', 'Skin Cutaneous Melanoma', 'NCH'),
'YH': ('Stanford University', 'Pancreatic adenocarcinoma', 'NCH'),
'YJ': ('Stanford University', 'Prostate adenocarcinoma', 'NCH'),
'YL': ('PROCURE Biobank', 'Prostate adenocarcinoma', 'NCH'),
'YN': ('University of Arizona', 'Skin Cutaneous Melanoma', 'NCH'),
'YR': ('Barretos Cancer Hospital', 'Cholangiocarcinoma', 'NCH'),
'YS': ('Barretos Cancer Hospital', 'Mesothelioma', 'NCH'),
'YT': ('Barretos Cancer Hospital', 'Thymoma', 'NCH'),
'YU': ('Barretos Cancer Hospital', 'Testicular Germ Cell Tumors', 'NCH'),
'YV': ('MSKCC', 'Uveal Melanoma', 'NCH'),
'YW': ('Albert Einstein Medical Center', 'Sarcoma', 'NCH'),
'YX': ('Emory University', 'Stomach adenocarcinoma', 'NCH'),
'YY': ('Roswell Park', 'Pancreatic adenocarcinoma', 'NCH'),
'YZ': ('The Ohio State University', 'Uveal Melanoma', 'NCH'),
'Z2': ('IDI-IRCCS', 'Skin Cutaneous Melanoma', 'NCH'),
'Z3': ('UCLA', 'Sarcoma', 'NCH'),
'Z4': ('Cureline', 'Sarcoma', 'NCH'),
'Z5': ('Cureline', 'Pancreatic adenocarcinoma', 'NCH'),
'Z6': ('Cureline', 'Esophageal carcinoma ', 'NCH'),
'Z7': ('John Wayne Cancer Center', 'Breast invasive carcinoma', 'NCH'),
'Z8': ('John Wayne Cancer Center', 'Pancreatic adenocarcinoma', 'NCH'),
'ZA': ('Candler', 'Stomach adenocarcinoma', 'NCH'),
'ZB': ('Thoraxklinik', 'Thymoma', 'NCH'),
'ZC': ('University of Mannheim', 'Thymoma', 'NCH'),
'ZD': ('ILSbio', 'Cholangiocarcinoma', 'NCH'),
'ZE': ('Spectrum Health', 'Lung squamous cell carcinoma', 'NCH'),
'ZF': ('University of Sheffield', 'Bladder Urothelial Carcinoma', 'NCH'),
'ZG': ('University Medical Center Hamburg-Eppendorf', 'Prostate adenocarcinoma', 'NCH'),
'ZH': ('University of North Carolina', 'Cholangiocarcinoma', 'NCH'),
'ZJ': ('NCI HRE Branch', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
'ZK': ('University of New Mexico', 'Cholangiocarcinoma', 'NCH'),
'ZL': ('Valley Hospital', 'Thymoma', 'NCH'),
'ZM': ('University of Ulm', 'Testicular Germ Cell Tumors', 'NCH'),
'ZN': ('Brigham and Women\'s Hospital Division of Thoracic Surgery', 'Mesothelioma', 'NCH'),
'ZP': ('Medical College of Wisconsin', 'Liver hepatocellular carcinoma', 'NCH'),
'ZQ': ('Tayside Tissue Bank', 'Stomach adenocarcinoma', 'NCH'),
'ZR': ('Tayside Tissue Bank', 'Esophageal carcinoma ', 'NCH'),
'ZS': ('Tayside Tissue Bank', 'Liver hepatocellular carcinoma', 'NCH'),
'ZT': ('International Genomics Consortium', 'Thymoma', 'NCH'),
'ZU': ('Spectrum Health', 'Cholangiocarcinoma', 'NCH'),
'ZW': ('University of Alabama', 'Pancreatic adenocarcinoma', 'NCH'),
'ZX': ('University of Alabama', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'),
}
SAMPLE_TYPE = {
'01': ('Primary solid Tumor', 'TP'),
'02': ('Recurrent Solid Tumor', 'TR'),
'03': ('Primary Blood Derived Cancer - Peripheral Blood', 'TB'),
'04': ('Recurrent Blood Derived Cancer - Bone Marrow', 'TRBM'),
'05': ('Additional - New Primary', 'TAP'),
'06': ('Metastatic', 'TM'),
'07': ('Additional Metastatic', 'TAM'),
'08': ('Human Tumor Original Cells', 'THOC'),
'09': ('Primary Blood Derived Cancer - Bone Marrow', 'TBM'),
'10': ('Blood Derived Normal', 'NB'),
'11': ('Solid Tissue Normal', 'NT'),
'12': ('Buccal Cell Normal', 'NBC'),
'13': ('EBV Immortalized Normal', 'NEBV'),
'14': ('Bone Marrow Normal', 'NBM'),
'20': ('Control Analyte', 'CELLC'),
'40': ('Recurrent Blood Derived Cancer - Peripheral Blood', 'TRB'),
'50': ('Cell Lines', 'CELL'),
'60': ('Primary Xenograft Tissue', 'XP'),
'61': ('Cell Line Derived Xenograft Tissue', 'XCL'),
}
| true | true |
f7314a0e4e81b092e4ad4e0a58faca277e3f6357 | 482 | py | Python | measurements/read-ds18b20.py | jazik/raspberry-pi-cottage | c82885db7b265b96e7c1126a0f7af89602cd72d5 | [
"MIT"
] | null | null | null | measurements/read-ds18b20.py | jazik/raspberry-pi-cottage | c82885db7b265b96e7c1126a0f7af89602cd72d5 | [
"MIT"
] | null | null | null | measurements/read-ds18b20.py | jazik/raspberry-pi-cottage | c82885db7b265b96e7c1126a0f7af89602cd72d5 | [
"MIT"
] | null | null | null | #!/usr/bin/python
import sys
from w1thermsensor import W1ThermSensor
if len(sys.argv) == 2:
sensor_id = sys.argv[1]
else:
print('usage: sudo ' + sys.argv[0] + ' <sensor id>')
print('example: sudo ' + sys.argv[0] + ' 00000588806a - Read from an DS18B20 wiht id 00000588806a')
sys.exit(1)
sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, sensor_id)
temperature_in_celsius = sensor.get_temperature()
print('Temp={0:0.1f}*'.format(temperature_in_celsius))
| 28.352941 | 103 | 0.715768 |
import sys
from w1thermsensor import W1ThermSensor
if len(sys.argv) == 2:
sensor_id = sys.argv[1]
else:
print('usage: sudo ' + sys.argv[0] + ' <sensor id>')
print('example: sudo ' + sys.argv[0] + ' 00000588806a - Read from an DS18B20 wiht id 00000588806a')
sys.exit(1)
sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, sensor_id)
temperature_in_celsius = sensor.get_temperature()
print('Temp={0:0.1f}*'.format(temperature_in_celsius))
| true | true |
f7314b6028b09e35ddb4a9b228cfb6aadcb1d26a | 939 | py | Python | dwi_ml/models/utils/fisher_von_mises.py | EmmaRenauld/dwi_ml | f2f776199dd886509d15520aa68099a8c870a233 | [
"MIT"
] | null | null | null | dwi_ml/models/utils/fisher_von_mises.py | EmmaRenauld/dwi_ml | f2f776199dd886509d15520aa68099a8c870a233 | [
"MIT"
] | null | null | null | dwi_ml/models/utils/fisher_von_mises.py | EmmaRenauld/dwi_ml | f2f776199dd886509d15520aa68099a8c870a233 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
import numpy as np
import torch
"""
The complete formulas and explanations are available in our doc:
https://dwi-ml.readthedocs.io/en/latest/formulas.html
"""
def fisher_von_mises_log_prob_vector(mus, kappa, targets):
log_c = np.log(kappa) - np.log(2 * np.pi) - np.log(np.exp(kappa) -
np.exp(-kappa))
log_prob = log_c + (kappa * (mus * targets).sum(axis=-1))
return log_prob
def fisher_von_mises_log_prob(mus, kappa, targets, eps=1e-6):
log_2pi = np.log(2 * np.pi).astype(np.float32)
# Add an epsilon in case kappa is too small (i.e. a uniform
# distribution)
log_diff_exp_kappa = torch.log(torch.exp(kappa) - torch.exp(-kappa) + eps)
log_c = torch.log(kappa) - log_2pi - log_diff_exp_kappa
batch_dot_product = torch.sum(mus * targets, dim=1)
log_prob = log_c + (kappa * batch_dot_product)
return log_prob
| 29.34375 | 78 | 0.644302 |
import numpy as np
import torch
def fisher_von_mises_log_prob_vector(mus, kappa, targets):
log_c = np.log(kappa) - np.log(2 * np.pi) - np.log(np.exp(kappa) -
np.exp(-kappa))
log_prob = log_c + (kappa * (mus * targets).sum(axis=-1))
return log_prob
def fisher_von_mises_log_prob(mus, kappa, targets, eps=1e-6):
log_2pi = np.log(2 * np.pi).astype(np.float32)
log_diff_exp_kappa = torch.log(torch.exp(kappa) - torch.exp(-kappa) + eps)
log_c = torch.log(kappa) - log_2pi - log_diff_exp_kappa
batch_dot_product = torch.sum(mus * targets, dim=1)
log_prob = log_c + (kappa * batch_dot_product)
return log_prob
| true | true |
f7314ba8e10dd03e076c71b94e712ad4b4b62c44 | 664 | py | Python | docs/src/additional_responses/tutorial004.py | patrickmckenna/fastapi | 9c3c9b6e78768374868d690bc05918d58481e880 | [
"MIT"
] | 2 | 2020-11-01T00:04:05.000Z | 2021-07-21T06:32:20.000Z | docs/src/additional_responses/tutorial004.py | patrickmckenna/fastapi | 9c3c9b6e78768374868d690bc05918d58481e880 | [
"MIT"
] | 1 | 2019-11-02T22:03:59.000Z | 2019-11-02T22:03:59.000Z | docs/src/additional_responses/tutorial004.py | patrickmckenna/fastapi | 9c3c9b6e78768374868d690bc05918d58481e880 | [
"MIT"
] | 1 | 2020-12-19T18:01:20.000Z | 2020-12-19T18:01:20.000Z | from fastapi import FastAPI
from pydantic import BaseModel
from starlette.responses import FileResponse
class Item(BaseModel):
id: str
value: str
responses = {
404: {"description": "Item not found"},
302: {"description": "The item was moved"},
403: {"description": "Not enough privileges"},
}
app = FastAPI()
@app.get(
"/items/{item_id}",
response_model=Item,
responses={**responses, 200: {"content": {"image/png": {}}}},
)
async def read_item(item_id: str, img: bool = None):
if img:
return FileResponse("image.png", media_type="image/png")
else:
return {"id": "foo", "value": "there goes my hero"}
| 21.419355 | 65 | 0.637048 | from fastapi import FastAPI
from pydantic import BaseModel
from starlette.responses import FileResponse
class Item(BaseModel):
id: str
value: str
responses = {
404: {"description": "Item not found"},
302: {"description": "The item was moved"},
403: {"description": "Not enough privileges"},
}
app = FastAPI()
@app.get(
"/items/{item_id}",
response_model=Item,
responses={**responses, 200: {"content": {"image/png": {}}}},
)
async def read_item(item_id: str, img: bool = None):
if img:
return FileResponse("image.png", media_type="image/png")
else:
return {"id": "foo", "value": "there goes my hero"}
| true | true |
f7314be85e0d5c52d7bd7dba9f799e44ab8fed6b | 138 | py | Python | Fango/accounts/apps.py | Niemzok/fango | 37484a11e8bfffb0f6fe451b74501e0ad825b215 | [
"MIT"
] | null | null | null | Fango/accounts/apps.py | Niemzok/fango | 37484a11e8bfffb0f6fe451b74501e0ad825b215 | [
"MIT"
] | null | null | null | Fango/accounts/apps.py | Niemzok/fango | 37484a11e8bfffb0f6fe451b74501e0ad825b215 | [
"MIT"
] | null | null | null | from __future__ import unicode_literals
from django.apps import AppConfig
class AccountsConfig(AppConfig):
name = 'Fango.accounts'
| 17.25 | 39 | 0.797101 | from __future__ import unicode_literals
from django.apps import AppConfig
class AccountsConfig(AppConfig):
name = 'Fango.accounts'
| true | true |
f7314cf1f7f6c192548e293ee5dab1afb019d2fc | 13,083 | py | Python | examples/annotation.py | quattro/numpyro | b7b6e937297ea47c55760446134f84fc82936a9d | [
"Apache-2.0"
] | null | null | null | examples/annotation.py | quattro/numpyro | b7b6e937297ea47c55760446134f84fc82936a9d | [
"Apache-2.0"
] | null | null | null | examples/annotation.py | quattro/numpyro | b7b6e937297ea47c55760446134f84fc82936a9d | [
"Apache-2.0"
] | null | null | null | # Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
"""
Example: Bayesian Models of Annotation
======================================
In this example, we run MCMC for various crowdsourced annotation models in [1].
All models have discrete latent variables. Under the hood, we enumerate over
(marginalize out) those discrete latent sites in inference. Those models have different
complexity so they are great refererences for those who are new to Pyro/NumPyro
enumeration mechanism. We recommend readers compare the implementations with the
corresponding plate diagrams in [1] to see how concise a Pyro/NumPyro program is.
The interested readers can also refer to [3] for more explanation about enumeration.
The data is taken from Table 1 of reference [2].
Currently, this example does not include postprocessing steps to deal with "Label
Switching" issue (mentioned in section 6.2 of [1]).
**References:**
1. Paun, S., Carpenter, B., Chamberlain, J., Hovy, D., Kruschwitz, U.,
and Poesio, M. (2018). "Comparing bayesian models of annotation"
(https://www.aclweb.org/anthology/Q18-1040/)
2. Dawid, A. P., and Skene, A. M. (1979).
"Maximum likelihood estimation of observer error‐rates using the EM algorithm"
3. "Inference with Discrete Latent Variables"
(http://pyro.ai/examples/enumeration.html)
"""
import argparse
import os
import numpy as np
from jax import nn, random, vmap
import jax.numpy as jnp
import numpyro
from numpyro import handlers
from numpyro.contrib.indexing import Vindex
import numpyro.distributions as dist
from numpyro.infer import MCMC, NUTS, Predictive
from numpyro.infer.reparam import LocScaleReparam
def get_data():
"""
:return: a tuple of annotator indices and class indices. The first term has shape
`num_positions` whose entries take values from `0` to `num_annotators - 1`.
The second term has shape `num_items x num_positions` whose entries take values
from `0` to `num_classes - 1`.
"""
# NB: the first annotator assessed each item 3 times
positions = np.array([1, 1, 1, 2, 3, 4, 5])
annotations = np.array(
[
[1, 1, 1, 1, 1, 1, 1],
[3, 3, 3, 4, 3, 3, 4],
[1, 1, 2, 2, 1, 2, 2],
[2, 2, 2, 3, 1, 2, 1],
[2, 2, 2, 3, 2, 2, 2],
[2, 2, 2, 3, 3, 2, 2],
[1, 2, 2, 2, 1, 1, 1],
[3, 3, 3, 3, 4, 3, 3],
[2, 2, 2, 2, 2, 2, 3],
[2, 3, 2, 2, 2, 2, 3],
[4, 4, 4, 4, 4, 4, 4],
[2, 2, 2, 3, 3, 4, 3],
[1, 1, 1, 1, 1, 1, 1],
[2, 2, 2, 3, 2, 1, 2],
[1, 2, 1, 1, 1, 1, 1],
[1, 1, 1, 2, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[2, 2, 2, 2, 2, 2, 1],
[2, 2, 2, 1, 3, 2, 2],
[2, 2, 2, 2, 2, 2, 2],
[2, 2, 2, 2, 2, 2, 1],
[2, 2, 2, 3, 2, 2, 2],
[2, 2, 1, 2, 2, 2, 2],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[2, 3, 2, 2, 2, 2, 2],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 2, 1, 1, 2, 1],
[1, 1, 1, 1, 1, 1, 1],
[3, 3, 3, 3, 2, 3, 3],
[1, 1, 1, 1, 1, 1, 1],
[2, 2, 2, 2, 2, 2, 2],
[2, 2, 2, 3, 2, 3, 2],
[4, 3, 3, 4, 3, 4, 3],
[2, 2, 1, 2, 2, 3, 2],
[2, 3, 2, 3, 2, 3, 3],
[3, 3, 3, 3, 4, 3, 2],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[1, 2, 1, 2, 1, 1, 1],
[2, 3, 2, 2, 2, 2, 2],
[1, 2, 1, 1, 1, 1, 1],
[2, 2, 2, 2, 2, 2, 2],
]
)
# we minus 1 because in Python, the first index is 0
return positions - 1, annotations - 1
def multinomial(annotations):
"""
This model corresponds to the plate diagram in Figure 1 of reference [1].
"""
num_classes = int(np.max(annotations)) + 1
num_items, num_positions = annotations.shape
with numpyro.plate("class", num_classes):
zeta = numpyro.sample("zeta", dist.Dirichlet(jnp.ones(num_classes)))
pi = numpyro.sample("pi", dist.Dirichlet(jnp.ones(num_classes)))
with numpyro.plate("item", num_items, dim=-2):
c = numpyro.sample("c", dist.Categorical(pi))
with numpyro.plate("position", num_positions):
numpyro.sample("y", dist.Categorical(zeta[c]), obs=annotations)
def dawid_skene(positions, annotations):
"""
This model corresponds to the plate diagram in Figure 2 of reference [1].
"""
num_annotators = int(np.max(positions)) + 1
num_classes = int(np.max(annotations)) + 1
num_items, num_positions = annotations.shape
with numpyro.plate("annotator", num_annotators, dim=-2):
with numpyro.plate("class", num_classes):
beta = numpyro.sample("beta", dist.Dirichlet(jnp.ones(num_classes)))
pi = numpyro.sample("pi", dist.Dirichlet(jnp.ones(num_classes)))
with numpyro.plate("item", num_items, dim=-2):
c = numpyro.sample("c", dist.Categorical(pi))
# here we use Vindex to allow broadcasting for the second index `c`
# ref: http://num.pyro.ai/en/latest/utilities.html#numpyro.contrib.indexing.vindex
with numpyro.plate("position", num_positions):
numpyro.sample(
"y", dist.Categorical(Vindex(beta)[positions, c, :]), obs=annotations
)
def mace(positions, annotations):
"""
This model corresponds to the plate diagram in Figure 3 of reference [1].
"""
num_annotators = int(np.max(positions)) + 1
num_classes = int(np.max(annotations)) + 1
num_items, num_positions = annotations.shape
with numpyro.plate("annotator", num_annotators):
epsilon = numpyro.sample("epsilon", dist.Dirichlet(jnp.full(num_classes, 10)))
theta = numpyro.sample("theta", dist.Beta(0.5, 0.5))
with numpyro.plate("item", num_items, dim=-2):
# NB: using constant logits for discrete uniform prior
# (NumPyro does not have DiscreteUniform distribution yet)
c = numpyro.sample("c", dist.Categorical(logits=jnp.zeros(num_classes)))
with numpyro.plate("position", num_positions):
s = numpyro.sample("s", dist.Bernoulli(1 - theta[positions]))
probs = jnp.where(
s[..., None] == 0, nn.one_hot(c, num_classes), epsilon[positions]
)
numpyro.sample("y", dist.Categorical(probs), obs=annotations)
def hierarchical_dawid_skene(positions, annotations):
"""
This model corresponds to the plate diagram in Figure 4 of reference [1].
"""
num_annotators = int(np.max(positions)) + 1
num_classes = int(np.max(annotations)) + 1
num_items, num_positions = annotations.shape
with numpyro.plate("class", num_classes):
# NB: we define `beta` as the `logits` of `y` likelihood; but `logits` is
# invariant up to a constant, so we'll follow [1]: fix the last term of `beta`
# to 0 and only define hyperpriors for the first `num_classes - 1` terms.
zeta = numpyro.sample(
"zeta", dist.Normal(0, 1).expand([num_classes - 1]).to_event(1)
)
omega = numpyro.sample(
"Omega", dist.HalfNormal(1).expand([num_classes - 1]).to_event(1)
)
with numpyro.plate("annotator", num_annotators, dim=-2):
with numpyro.plate("class", num_classes):
# non-centered parameterization
with handlers.reparam(config={"beta": LocScaleReparam(0)}):
beta = numpyro.sample("beta", dist.Normal(zeta, omega).to_event(1))
# pad 0 to the last item
beta = jnp.pad(beta, [(0, 0)] * (jnp.ndim(beta) - 1) + [(0, 1)])
pi = numpyro.sample("pi", dist.Dirichlet(jnp.ones(num_classes)))
with numpyro.plate("item", num_items, dim=-2):
c = numpyro.sample("c", dist.Categorical(pi))
with numpyro.plate("position", num_positions):
logits = Vindex(beta)[positions, c, :]
numpyro.sample("y", dist.Categorical(logits=logits), obs=annotations)
def item_difficulty(annotations):
"""
This model corresponds to the plate diagram in Figure 5 of reference [1].
"""
num_classes = int(np.max(annotations)) + 1
num_items, num_positions = annotations.shape
with numpyro.plate("class", num_classes):
eta = numpyro.sample(
"eta", dist.Normal(0, 1).expand([num_classes - 1]).to_event(1)
)
chi = numpyro.sample(
"Chi", dist.HalfNormal(1).expand([num_classes - 1]).to_event(1)
)
pi = numpyro.sample("pi", dist.Dirichlet(jnp.ones(num_classes)))
with numpyro.plate("item", num_items, dim=-2):
c = numpyro.sample("c", dist.Categorical(pi))
with handlers.reparam(config={"theta": LocScaleReparam(0)}):
theta = numpyro.sample("theta", dist.Normal(eta[c], chi[c]).to_event(1))
theta = jnp.pad(theta, [(0, 0)] * (jnp.ndim(theta) - 1) + [(0, 1)])
with numpyro.plate("position", annotations.shape[-1]):
numpyro.sample("y", dist.Categorical(logits=theta), obs=annotations)
def logistic_random_effects(positions, annotations):
"""
This model corresponds to the plate diagram in Figure 5 of reference [1].
"""
num_annotators = int(np.max(positions)) + 1
num_classes = int(np.max(annotations)) + 1
num_items, num_positions = annotations.shape
with numpyro.plate("class", num_classes):
zeta = numpyro.sample(
"zeta", dist.Normal(0, 1).expand([num_classes - 1]).to_event(1)
)
omega = numpyro.sample(
"Omega", dist.HalfNormal(1).expand([num_classes - 1]).to_event(1)
)
chi = numpyro.sample(
"Chi", dist.HalfNormal(1).expand([num_classes - 1]).to_event(1)
)
with numpyro.plate("annotator", num_annotators, dim=-2):
with numpyro.plate("class", num_classes):
with handlers.reparam(config={"beta": LocScaleReparam(0)}):
beta = numpyro.sample("beta", dist.Normal(zeta, omega).to_event(1))
beta = jnp.pad(beta, [(0, 0)] * (jnp.ndim(beta) - 1) + [(0, 1)])
pi = numpyro.sample("pi", dist.Dirichlet(jnp.ones(num_classes)))
with numpyro.plate("item", num_items, dim=-2):
c = numpyro.sample("c", dist.Categorical(pi))
with handlers.reparam(config={"theta": LocScaleReparam(0)}):
theta = numpyro.sample("theta", dist.Normal(0, chi[c]).to_event(1))
theta = jnp.pad(theta, [(0, 0)] * (jnp.ndim(theta) - 1) + [(0, 1)])
with numpyro.plate("position", num_positions):
logits = Vindex(beta)[positions, c, :] - theta
numpyro.sample("y", dist.Categorical(logits=logits), obs=annotations)
NAME_TO_MODEL = {
"mn": multinomial,
"ds": dawid_skene,
"mace": mace,
"hds": hierarchical_dawid_skene,
"id": item_difficulty,
"lre": logistic_random_effects,
}
def main(args):
annotators, annotations = get_data()
model = NAME_TO_MODEL[args.model]
data = (
(annotations,)
if model in [multinomial, item_difficulty]
else (annotators, annotations)
)
mcmc = MCMC(
NUTS(model),
num_warmup=args.num_warmup,
num_samples=args.num_samples,
num_chains=args.num_chains,
progress_bar=False if "NUMPYRO_SPHINXBUILD" in os.environ else True,
)
mcmc.run(random.PRNGKey(0), *data)
mcmc.print_summary()
posterior_samples = mcmc.get_samples()
predictive = Predictive(model, posterior_samples, infer_discrete=True)
discrete_samples = predictive(random.PRNGKey(1), *data)
item_class = vmap(lambda x: jnp.bincount(x, length=4), in_axes=1)(
discrete_samples["c"].squeeze(-1)
)
print("Histogram of the predicted class of each item:")
row_format = "{:>10}" * 5
print(row_format.format("", *["c={}".format(i) for i in range(4)]))
for i, row in enumerate(item_class):
print(row_format.format(f"item[{i}]", *row))
if __name__ == "__main__":
assert numpyro.__version__.startswith("0.7.2")
parser = argparse.ArgumentParser(description="Bayesian Models of Annotation")
parser.add_argument("-n", "--num-samples", nargs="?", default=1000, type=int)
parser.add_argument("--num-warmup", nargs="?", default=1000, type=int)
parser.add_argument("--num-chains", nargs="?", default=1, type=int)
parser.add_argument(
"--model",
nargs="?",
default="ds",
help='one of "mn" (multinomial), "ds" (dawid_skene), "mace",'
' "hds" (hierarchical_dawid_skene),'
' "id" (item_difficulty), "lre" (logistic_random_effects)',
)
parser.add_argument("--device", default="cpu", type=str, help='use "cpu" or "gpu".')
args = parser.parse_args()
numpyro.set_platform(args.device)
numpyro.set_host_device_count(args.num_chains)
main(args)
| 37.38 | 90 | 0.591072 |
import argparse
import os
import numpy as np
from jax import nn, random, vmap
import jax.numpy as jnp
import numpyro
from numpyro import handlers
from numpyro.contrib.indexing import Vindex
import numpyro.distributions as dist
from numpyro.infer import MCMC, NUTS, Predictive
from numpyro.infer.reparam import LocScaleReparam
def get_data():
positions = np.array([1, 1, 1, 2, 3, 4, 5])
annotations = np.array(
[
[1, 1, 1, 1, 1, 1, 1],
[3, 3, 3, 4, 3, 3, 4],
[1, 1, 2, 2, 1, 2, 2],
[2, 2, 2, 3, 1, 2, 1],
[2, 2, 2, 3, 2, 2, 2],
[2, 2, 2, 3, 3, 2, 2],
[1, 2, 2, 2, 1, 1, 1],
[3, 3, 3, 3, 4, 3, 3],
[2, 2, 2, 2, 2, 2, 3],
[2, 3, 2, 2, 2, 2, 3],
[4, 4, 4, 4, 4, 4, 4],
[2, 2, 2, 3, 3, 4, 3],
[1, 1, 1, 1, 1, 1, 1],
[2, 2, 2, 3, 2, 1, 2],
[1, 2, 1, 1, 1, 1, 1],
[1, 1, 1, 2, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[2, 2, 2, 2, 2, 2, 1],
[2, 2, 2, 1, 3, 2, 2],
[2, 2, 2, 2, 2, 2, 2],
[2, 2, 2, 2, 2, 2, 1],
[2, 2, 2, 3, 2, 2, 2],
[2, 2, 1, 2, 2, 2, 2],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[2, 3, 2, 2, 2, 2, 2],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 2, 1, 1, 2, 1],
[1, 1, 1, 1, 1, 1, 1],
[3, 3, 3, 3, 2, 3, 3],
[1, 1, 1, 1, 1, 1, 1],
[2, 2, 2, 2, 2, 2, 2],
[2, 2, 2, 3, 2, 3, 2],
[4, 3, 3, 4, 3, 4, 3],
[2, 2, 1, 2, 2, 3, 2],
[2, 3, 2, 3, 2, 3, 3],
[3, 3, 3, 3, 4, 3, 2],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[1, 2, 1, 2, 1, 1, 1],
[2, 3, 2, 2, 2, 2, 2],
[1, 2, 1, 1, 1, 1, 1],
[2, 2, 2, 2, 2, 2, 2],
]
)
return positions - 1, annotations - 1
def multinomial(annotations):
num_classes = int(np.max(annotations)) + 1
num_items, num_positions = annotations.shape
with numpyro.plate("class", num_classes):
zeta = numpyro.sample("zeta", dist.Dirichlet(jnp.ones(num_classes)))
pi = numpyro.sample("pi", dist.Dirichlet(jnp.ones(num_classes)))
with numpyro.plate("item", num_items, dim=-2):
c = numpyro.sample("c", dist.Categorical(pi))
with numpyro.plate("position", num_positions):
numpyro.sample("y", dist.Categorical(zeta[c]), obs=annotations)
def dawid_skene(positions, annotations):
num_annotators = int(np.max(positions)) + 1
num_classes = int(np.max(annotations)) + 1
num_items, num_positions = annotations.shape
with numpyro.plate("annotator", num_annotators, dim=-2):
with numpyro.plate("class", num_classes):
beta = numpyro.sample("beta", dist.Dirichlet(jnp.ones(num_classes)))
pi = numpyro.sample("pi", dist.Dirichlet(jnp.ones(num_classes)))
with numpyro.plate("item", num_items, dim=-2):
c = numpyro.sample("c", dist.Categorical(pi))
ition", num_positions):
numpyro.sample(
"y", dist.Categorical(Vindex(beta)[positions, c, :]), obs=annotations
)
def mace(positions, annotations):
num_annotators = int(np.max(positions)) + 1
num_classes = int(np.max(annotations)) + 1
num_items, num_positions = annotations.shape
with numpyro.plate("annotator", num_annotators):
epsilon = numpyro.sample("epsilon", dist.Dirichlet(jnp.full(num_classes, 10)))
theta = numpyro.sample("theta", dist.Beta(0.5, 0.5))
with numpyro.plate("item", num_items, dim=-2):
c = numpyro.sample("c", dist.Categorical(logits=jnp.zeros(num_classes)))
with numpyro.plate("position", num_positions):
s = numpyro.sample("s", dist.Bernoulli(1 - theta[positions]))
probs = jnp.where(
s[..., None] == 0, nn.one_hot(c, num_classes), epsilon[positions]
)
numpyro.sample("y", dist.Categorical(probs), obs=annotations)
def hierarchical_dawid_skene(positions, annotations):
num_annotators = int(np.max(positions)) + 1
num_classes = int(np.max(annotations)) + 1
num_items, num_positions = annotations.shape
with numpyro.plate("class", num_classes):
# to 0 and only define hyperpriors for the first `num_classes - 1` terms.
zeta = numpyro.sample(
"zeta", dist.Normal(0, 1).expand([num_classes - 1]).to_event(1)
)
omega = numpyro.sample(
"Omega", dist.HalfNormal(1).expand([num_classes - 1]).to_event(1)
)
with numpyro.plate("annotator", num_annotators, dim=-2):
with numpyro.plate("class", num_classes):
# non-centered parameterization
with handlers.reparam(config={"beta": LocScaleReparam(0)}):
beta = numpyro.sample("beta", dist.Normal(zeta, omega).to_event(1))
# pad 0 to the last item
beta = jnp.pad(beta, [(0, 0)] * (jnp.ndim(beta) - 1) + [(0, 1)])
pi = numpyro.sample("pi", dist.Dirichlet(jnp.ones(num_classes)))
with numpyro.plate("item", num_items, dim=-2):
c = numpyro.sample("c", dist.Categorical(pi))
with numpyro.plate("position", num_positions):
logits = Vindex(beta)[positions, c, :]
numpyro.sample("y", dist.Categorical(logits=logits), obs=annotations)
def item_difficulty(annotations):
num_classes = int(np.max(annotations)) + 1
num_items, num_positions = annotations.shape
with numpyro.plate("class", num_classes):
eta = numpyro.sample(
"eta", dist.Normal(0, 1).expand([num_classes - 1]).to_event(1)
)
chi = numpyro.sample(
"Chi", dist.HalfNormal(1).expand([num_classes - 1]).to_event(1)
)
pi = numpyro.sample("pi", dist.Dirichlet(jnp.ones(num_classes)))
with numpyro.plate("item", num_items, dim=-2):
c = numpyro.sample("c", dist.Categorical(pi))
with handlers.reparam(config={"theta": LocScaleReparam(0)}):
theta = numpyro.sample("theta", dist.Normal(eta[c], chi[c]).to_event(1))
theta = jnp.pad(theta, [(0, 0)] * (jnp.ndim(theta) - 1) + [(0, 1)])
with numpyro.plate("position", annotations.shape[-1]):
numpyro.sample("y", dist.Categorical(logits=theta), obs=annotations)
def logistic_random_effects(positions, annotations):
num_annotators = int(np.max(positions)) + 1
num_classes = int(np.max(annotations)) + 1
num_items, num_positions = annotations.shape
with numpyro.plate("class", num_classes):
zeta = numpyro.sample(
"zeta", dist.Normal(0, 1).expand([num_classes - 1]).to_event(1)
)
omega = numpyro.sample(
"Omega", dist.HalfNormal(1).expand([num_classes - 1]).to_event(1)
)
chi = numpyro.sample(
"Chi", dist.HalfNormal(1).expand([num_classes - 1]).to_event(1)
)
with numpyro.plate("annotator", num_annotators, dim=-2):
with numpyro.plate("class", num_classes):
with handlers.reparam(config={"beta": LocScaleReparam(0)}):
beta = numpyro.sample("beta", dist.Normal(zeta, omega).to_event(1))
beta = jnp.pad(beta, [(0, 0)] * (jnp.ndim(beta) - 1) + [(0, 1)])
pi = numpyro.sample("pi", dist.Dirichlet(jnp.ones(num_classes)))
with numpyro.plate("item", num_items, dim=-2):
c = numpyro.sample("c", dist.Categorical(pi))
with handlers.reparam(config={"theta": LocScaleReparam(0)}):
theta = numpyro.sample("theta", dist.Normal(0, chi[c]).to_event(1))
theta = jnp.pad(theta, [(0, 0)] * (jnp.ndim(theta) - 1) + [(0, 1)])
with numpyro.plate("position", num_positions):
logits = Vindex(beta)[positions, c, :] - theta
numpyro.sample("y", dist.Categorical(logits=logits), obs=annotations)
NAME_TO_MODEL = {
"mn": multinomial,
"ds": dawid_skene,
"mace": mace,
"hds": hierarchical_dawid_skene,
"id": item_difficulty,
"lre": logistic_random_effects,
}
def main(args):
annotators, annotations = get_data()
model = NAME_TO_MODEL[args.model]
data = (
(annotations,)
if model in [multinomial, item_difficulty]
else (annotators, annotations)
)
mcmc = MCMC(
NUTS(model),
num_warmup=args.num_warmup,
num_samples=args.num_samples,
num_chains=args.num_chains,
progress_bar=False if "NUMPYRO_SPHINXBUILD" in os.environ else True,
)
mcmc.run(random.PRNGKey(0), *data)
mcmc.print_summary()
posterior_samples = mcmc.get_samples()
predictive = Predictive(model, posterior_samples, infer_discrete=True)
discrete_samples = predictive(random.PRNGKey(1), *data)
item_class = vmap(lambda x: jnp.bincount(x, length=4), in_axes=1)(
discrete_samples["c"].squeeze(-1)
)
print("Histogram of the predicted class of each item:")
row_format = "{:>10}" * 5
print(row_format.format("", *["c={}".format(i) for i in range(4)]))
for i, row in enumerate(item_class):
print(row_format.format(f"item[{i}]", *row))
if __name__ == "__main__":
assert numpyro.__version__.startswith("0.7.2")
parser = argparse.ArgumentParser(description="Bayesian Models of Annotation")
parser.add_argument("-n", "--num-samples", nargs="?", default=1000, type=int)
parser.add_argument("--num-warmup", nargs="?", default=1000, type=int)
parser.add_argument("--num-chains", nargs="?", default=1, type=int)
parser.add_argument(
"--model",
nargs="?",
default="ds",
help='one of "mn" (multinomial), "ds" (dawid_skene), "mace",'
' "hds" (hierarchical_dawid_skene),'
' "id" (item_difficulty), "lre" (logistic_random_effects)',
)
parser.add_argument("--device", default="cpu", type=str, help='use "cpu" or "gpu".')
args = parser.parse_args()
numpyro.set_platform(args.device)
numpyro.set_host_device_count(args.num_chains)
main(args)
| true | true |
f7314e8a496b92d9bd05e6902788e7b9a672b0dc | 11,218 | py | Python | plugins/sqlfluff-templater-dbt/test/templater_test.py | WittierDinosaur/sqlfluff | edc4a2c47cd4f0a5f53dbde36e50da19ec08dda7 | [
"MIT"
] | null | null | null | plugins/sqlfluff-templater-dbt/test/templater_test.py | WittierDinosaur/sqlfluff | edc4a2c47cd4f0a5f53dbde36e50da19ec08dda7 | [
"MIT"
] | null | null | null | plugins/sqlfluff-templater-dbt/test/templater_test.py | WittierDinosaur/sqlfluff | edc4a2c47cd4f0a5f53dbde36e50da19ec08dda7 | [
"MIT"
] | null | null | null | """Tests for the dbt templater."""
import glob
import os
import pytest
import logging
from pathlib import Path
from sqlfluff.core import FluffConfig, Lexer, Linter
from sqlfluff.core.errors import SQLTemplaterSkipFile
from test.fixtures.dbt.templater import ( # noqa: F401
DBT_FLUFF_CONFIG,
dbt_templater,
project_dir,
)
def test__templater_dbt_missing(dbt_templater, project_dir): # noqa: F811
"""Check that a nice error is returned when dbt module is missing."""
try:
import dbt # noqa: F401
pytest.skip(msg="dbt is installed")
except ModuleNotFoundError:
pass
with pytest.raises(ModuleNotFoundError, match=r"pip install sqlfluff\[dbt\]"):
dbt_templater.process(
in_str="",
fname=os.path.join(project_dir, "models/my_new_project/test.sql"),
config=FluffConfig(configs=DBT_FLUFF_CONFIG),
)
def test__templater_dbt_profiles_dir_expanded(dbt_templater): # noqa: F811
"""Check that the profiles_dir is expanded."""
dbt_templater.sqlfluff_config = FluffConfig(
configs={"templater": {"dbt": {"profiles_dir": "~/.dbt"}}}
)
profiles_dir = dbt_templater._get_profiles_dir()
# Normalise paths to control for OS variance
assert os.path.normpath(profiles_dir) == os.path.normpath(
os.path.expanduser("~/.dbt")
)
@pytest.mark.parametrize(
"fname",
[
# dbt_utils
"use_dbt_utils.sql",
# macro calling another macro
"macro_in_macro.sql",
# config.get(...)
"use_headers.sql",
# var(...)
"use_var.sql",
# {# {{ 1 + 2 }} #}
"templated_inside_comment.sql",
# {{ dbt_utils.last_day(
"last_day.sql",
],
)
def test__templater_dbt_templating_result(
project_dir, dbt_templater, fname # noqa: F811
):
"""Test that input sql file gets templated into output sql file."""
templated_file, _ = dbt_templater.process(
in_str="",
fname=os.path.join(project_dir, "models/my_new_project/", fname),
config=FluffConfig(configs=DBT_FLUFF_CONFIG),
)
assert (
str(templated_file)
== open("plugins/sqlfluff-templater-dbt/test/fixtures/dbt/" + fname).read()
)
@pytest.mark.parametrize(
"fnames_input, fnames_expected_sequence",
[
[
(
Path("models") / "depends_on_ephemeral" / "a.sql",
Path("models") / "depends_on_ephemeral" / "b.sql",
Path("models") / "depends_on_ephemeral" / "d.sql",
),
# c.sql is not present in the original list and should not appear here,
# even though b.sql depends on it. This test ensures that "out of scope"
# files, e.g. those ignored using ".sqlfluffignore" or in directories
# outside what was specified, are not inadvertently processed.
(
Path("models") / "depends_on_ephemeral" / "a.sql",
Path("models") / "depends_on_ephemeral" / "b.sql",
Path("models") / "depends_on_ephemeral" / "d.sql",
),
],
[
(
Path("models") / "depends_on_ephemeral" / "a.sql",
Path("models") / "depends_on_ephemeral" / "b.sql",
Path("models") / "depends_on_ephemeral" / "c.sql",
Path("models") / "depends_on_ephemeral" / "d.sql",
),
# c.sql should come before b.sql because b.sql depends on c.sql.
# It also comes first overall because ephemeral models come first.
(
Path("models") / "depends_on_ephemeral" / "c.sql",
Path("models") / "depends_on_ephemeral" / "a.sql",
Path("models") / "depends_on_ephemeral" / "b.sql",
Path("models") / "depends_on_ephemeral" / "d.sql",
),
],
],
)
def test__templater_dbt_sequence_files_ephemeral_dependency(
project_dir, dbt_templater, fnames_input, fnames_expected_sequence # noqa: F811
):
"""Test that dbt templater sequences files based on dependencies."""
result = dbt_templater.sequence_files(
[str(Path(project_dir) / fn) for fn in fnames_input],
config=FluffConfig(configs=DBT_FLUFF_CONFIG),
)
pd = Path(project_dir)
expected = [str(pd / fn) for fn in fnames_expected_sequence]
assert list(result) == expected
@pytest.mark.parametrize(
"raw_file,templated_file,result",
[
(
"select * from a",
"""
with dbt__CTE__INTERNAL_test as (
select * from a
)select count(*) from dbt__CTE__INTERNAL_test
""",
# The unwrapper should trim the ends.
[
("literal", slice(0, 15, None), slice(0, 15, None)),
],
)
],
)
def test__templater_dbt_slice_file_wrapped_test(
raw_file, templated_file, result, dbt_templater, caplog # noqa: F811
):
"""Test that wrapped queries are sliced safely using _check_for_wrapped()."""
with caplog.at_level(logging.DEBUG, logger="sqlfluff.templater"):
_, resp, _ = dbt_templater.slice_file(
raw_file,
templated_file,
)
assert resp == result
@pytest.mark.parametrize(
"fname",
[
"tests/test.sql",
"models/my_new_project/single_trailing_newline.sql",
"models/my_new_project/multiple_trailing_newline.sql",
],
)
def test__templater_dbt_templating_test_lex(
project_dir, dbt_templater, fname # noqa: F811
):
"""A test to demonstrate the lexer works on both dbt models (with any # of trailing newlines) and dbt tests."""
source_fpath = os.path.join(project_dir, fname)
with open(source_fpath, "r") as source_dbt_model:
source_dbt_sql = source_dbt_model.read()
n_trailing_newlines = len(source_dbt_sql) - len(source_dbt_sql.rstrip("\n"))
lexer = Lexer(config=FluffConfig(configs=DBT_FLUFF_CONFIG))
templated_file, _ = dbt_templater.process(
in_str="",
fname=os.path.join(project_dir, fname),
config=FluffConfig(configs=DBT_FLUFF_CONFIG),
)
tokens, lex_vs = lexer.lex(templated_file)
assert (
templated_file.source_str
== "select a\nfrom table_a" + "\n" * n_trailing_newlines
)
assert (
templated_file.templated_str
== "select a\nfrom table_a" + "\n" * n_trailing_newlines
)
def test__templater_dbt_skips_disabled_model(dbt_templater, project_dir): # noqa: F811
"""A disabled dbt model should be skipped."""
with pytest.raises(SQLTemplaterSkipFile, match=r"model was disabled"):
dbt_templater.process(
in_str="",
fname=os.path.join(project_dir, "models/my_new_project/disabled_model.sql"),
config=FluffConfig(configs=DBT_FLUFF_CONFIG),
)
@pytest.mark.parametrize(
"fname",
[
"use_var.sql",
"incremental.sql",
"single_trailing_newline.sql",
"L034_test.sql",
],
)
def test__dbt_templated_models_do_not_raise_lint_error(
project_dir, fname # noqa: F811
):
"""Test that templated dbt models do not raise a linting error."""
lntr = Linter(config=FluffConfig(configs=DBT_FLUFF_CONFIG))
lnt = lntr.lint_path(
path=os.path.join(project_dir, "models/my_new_project/", fname)
)
violations = lnt.check_tuples()
assert len(violations) == 0
@pytest.mark.parametrize(
"path", ["models/my_new_project/issue_1608.sql", "snapshots/issue_1771.sql"]
)
def test__dbt_templated_models_fix_does_not_corrupt_file(
project_dir, path # noqa: F811
):
"""Test fix for issue 1608. Previously "sqlfluff fix" corrupted the file."""
for fsp in glob.glob(os.path.join(project_dir, "snapshots", "*FIXED.sql")):
os.remove(fsp)
lntr = Linter(config=FluffConfig(configs=DBT_FLUFF_CONFIG))
lnt = lntr.lint_path(os.path.join(project_dir, path), fix=True)
try:
lnt.persist_changes(fixed_file_suffix="FIXED")
with open(os.path.join(project_dir, path + ".after")) as f:
comp_buff = f.read()
with open(os.path.join(project_dir, path.replace(".sql", "FIXED.sql"))) as f:
fixed_buff = f.read()
assert fixed_buff == comp_buff
finally:
for fsp in glob.glob(os.path.join(project_dir, "snapshots", "*FIXED.sql")):
os.remove(fsp)
def test__templater_dbt_templating_absolute_path(
project_dir, dbt_templater # noqa: F811
):
"""Test that absolute path of input path does not cause RuntimeError."""
try:
dbt_templater.process(
in_str="",
fname=os.path.abspath(
os.path.join(project_dir, "models/my_new_project/use_var.sql")
),
config=FluffConfig(configs=DBT_FLUFF_CONFIG),
)
except Exception as e:
pytest.fail(f"Unexpected RuntimeError: {e}")
@pytest.mark.parametrize(
"fname,exception_msg",
[
(
"compiler_error.sql",
"dbt compilation error on file 'models/my_new_project/compiler_error.sql', "
"Unexpected end of template. Jinja was looking for the following tags: 'endfor'",
),
("exception_connect_database.sql", "dbt tried to connect to the database"),
],
)
def test__templater_dbt_handle_exceptions(
project_dir, dbt_templater, fname, exception_msg # noqa: F811
):
"""Test that exceptions during compilation are returned as violation."""
from dbt.adapters.factory import get_adapter
src_fpath = "plugins/sqlfluff-templater-dbt/test/fixtures/dbt/error_models/" + fname
target_fpath = os.path.abspath(
os.path.join(project_dir, "models/my_new_project/", fname)
)
# We move the file that throws an error in and out of the project directory
# as dbt throws an error if a node fails to parse while computing the DAG
os.rename(src_fpath, target_fpath)
try:
_, violations = dbt_templater.process(
in_str="",
fname=target_fpath,
config=FluffConfig(configs=DBT_FLUFF_CONFIG),
)
finally:
get_adapter(dbt_templater.dbt_config).connections.release()
os.rename(target_fpath, src_fpath)
assert violations
# NB: Replace slashes to deal with different plaform paths being returned.
assert violations[0].desc().replace("\\", "/").startswith(exception_msg)
def test__project_dir_does_not_exist_error(dbt_templater, caplog): # noqa: F811
"""Test that an error is logged if the specified dbt project directory doesn't exist."""
dbt_templater.sqlfluff_config = FluffConfig(
configs={"templater": {"dbt": {"project_dir": "./non_existing_directory"}}}
)
logger = logging.getLogger("sqlfluff")
original_propagate_value = logger.propagate
try:
logger.propagate = True
with caplog.at_level(logging.ERROR, logger="sqlfluff.templater"):
dbt_project_dir = dbt_templater._get_project_dir()
assert (
f"dbt_project_dir: {dbt_project_dir} could not be accessed. Check it exists."
in caplog.text
)
finally:
logger.propagate = original_propagate_value
| 35.5 | 115 | 0.639151 |
import glob
import os
import pytest
import logging
from pathlib import Path
from sqlfluff.core import FluffConfig, Lexer, Linter
from sqlfluff.core.errors import SQLTemplaterSkipFile
from test.fixtures.dbt.templater import (
DBT_FLUFF_CONFIG,
dbt_templater,
project_dir,
)
def test__templater_dbt_missing(dbt_templater, project_dir):
try:
import dbt
pytest.skip(msg="dbt is installed")
except ModuleNotFoundError:
pass
with pytest.raises(ModuleNotFoundError, match=r"pip install sqlfluff\[dbt\]"):
dbt_templater.process(
in_str="",
fname=os.path.join(project_dir, "models/my_new_project/test.sql"),
config=FluffConfig(configs=DBT_FLUFF_CONFIG),
)
def test__templater_dbt_profiles_dir_expanded(dbt_templater):
dbt_templater.sqlfluff_config = FluffConfig(
configs={"templater": {"dbt": {"profiles_dir": "~/.dbt"}}}
)
profiles_dir = dbt_templater._get_profiles_dir()
assert os.path.normpath(profiles_dir) == os.path.normpath(
os.path.expanduser("~/.dbt")
)
@pytest.mark.parametrize(
"fname",
[
"use_dbt_utils.sql",
"macro_in_macro.sql",
"use_headers.sql",
"use_var.sql",
d_inside_comment.sql",
"last_day.sql",
],
)
def test__templater_dbt_templating_result(
project_dir, dbt_templater, fname
):
templated_file, _ = dbt_templater.process(
in_str="",
fname=os.path.join(project_dir, "models/my_new_project/", fname),
config=FluffConfig(configs=DBT_FLUFF_CONFIG),
)
assert (
str(templated_file)
== open("plugins/sqlfluff-templater-dbt/test/fixtures/dbt/" + fname).read()
)
@pytest.mark.parametrize(
"fnames_input, fnames_expected_sequence",
[
[
(
Path("models") / "depends_on_ephemeral" / "a.sql",
Path("models") / "depends_on_ephemeral" / "b.sql",
Path("models") / "depends_on_ephemeral" / "d.sql",
),
(
Path("models") / "depends_on_ephemeral" / "a.sql",
Path("models") / "depends_on_ephemeral" / "b.sql",
Path("models") / "depends_on_ephemeral" / "d.sql",
),
],
[
(
Path("models") / "depends_on_ephemeral" / "a.sql",
Path("models") / "depends_on_ephemeral" / "b.sql",
Path("models") / "depends_on_ephemeral" / "c.sql",
Path("models") / "depends_on_ephemeral" / "d.sql",
),
(
Path("models") / "depends_on_ephemeral" / "c.sql",
Path("models") / "depends_on_ephemeral" / "a.sql",
Path("models") / "depends_on_ephemeral" / "b.sql",
Path("models") / "depends_on_ephemeral" / "d.sql",
),
],
],
)
def test__templater_dbt_sequence_files_ephemeral_dependency(
project_dir, dbt_templater, fnames_input, fnames_expected_sequence
):
result = dbt_templater.sequence_files(
[str(Path(project_dir) / fn) for fn in fnames_input],
config=FluffConfig(configs=DBT_FLUFF_CONFIG),
)
pd = Path(project_dir)
expected = [str(pd / fn) for fn in fnames_expected_sequence]
assert list(result) == expected
@pytest.mark.parametrize(
"raw_file,templated_file,result",
[
(
"select * from a",
"""
with dbt__CTE__INTERNAL_test as (
select * from a
)select count(*) from dbt__CTE__INTERNAL_test
""",
[
("literal", slice(0, 15, None), slice(0, 15, None)),
],
)
],
)
def test__templater_dbt_slice_file_wrapped_test(
raw_file, templated_file, result, dbt_templater, caplog
):
with caplog.at_level(logging.DEBUG, logger="sqlfluff.templater"):
_, resp, _ = dbt_templater.slice_file(
raw_file,
templated_file,
)
assert resp == result
@pytest.mark.parametrize(
"fname",
[
"tests/test.sql",
"models/my_new_project/single_trailing_newline.sql",
"models/my_new_project/multiple_trailing_newline.sql",
],
)
def test__templater_dbt_templating_test_lex(
project_dir, dbt_templater, fname
):
source_fpath = os.path.join(project_dir, fname)
with open(source_fpath, "r") as source_dbt_model:
source_dbt_sql = source_dbt_model.read()
n_trailing_newlines = len(source_dbt_sql) - len(source_dbt_sql.rstrip("\n"))
lexer = Lexer(config=FluffConfig(configs=DBT_FLUFF_CONFIG))
templated_file, _ = dbt_templater.process(
in_str="",
fname=os.path.join(project_dir, fname),
config=FluffConfig(configs=DBT_FLUFF_CONFIG),
)
tokens, lex_vs = lexer.lex(templated_file)
assert (
templated_file.source_str
== "select a\nfrom table_a" + "\n" * n_trailing_newlines
)
assert (
templated_file.templated_str
== "select a\nfrom table_a" + "\n" * n_trailing_newlines
)
def test__templater_dbt_skips_disabled_model(dbt_templater, project_dir):
with pytest.raises(SQLTemplaterSkipFile, match=r"model was disabled"):
dbt_templater.process(
in_str="",
fname=os.path.join(project_dir, "models/my_new_project/disabled_model.sql"),
config=FluffConfig(configs=DBT_FLUFF_CONFIG),
)
@pytest.mark.parametrize(
"fname",
[
"use_var.sql",
"incremental.sql",
"single_trailing_newline.sql",
"L034_test.sql",
],
)
def test__dbt_templated_models_do_not_raise_lint_error(
project_dir, fname
):
lntr = Linter(config=FluffConfig(configs=DBT_FLUFF_CONFIG))
lnt = lntr.lint_path(
path=os.path.join(project_dir, "models/my_new_project/", fname)
)
violations = lnt.check_tuples()
assert len(violations) == 0
@pytest.mark.parametrize(
"path", ["models/my_new_project/issue_1608.sql", "snapshots/issue_1771.sql"]
)
def test__dbt_templated_models_fix_does_not_corrupt_file(
project_dir, path
):
for fsp in glob.glob(os.path.join(project_dir, "snapshots", "*FIXED.sql")):
os.remove(fsp)
lntr = Linter(config=FluffConfig(configs=DBT_FLUFF_CONFIG))
lnt = lntr.lint_path(os.path.join(project_dir, path), fix=True)
try:
lnt.persist_changes(fixed_file_suffix="FIXED")
with open(os.path.join(project_dir, path + ".after")) as f:
comp_buff = f.read()
with open(os.path.join(project_dir, path.replace(".sql", "FIXED.sql"))) as f:
fixed_buff = f.read()
assert fixed_buff == comp_buff
finally:
for fsp in glob.glob(os.path.join(project_dir, "snapshots", "*FIXED.sql")):
os.remove(fsp)
def test__templater_dbt_templating_absolute_path(
project_dir, dbt_templater
):
try:
dbt_templater.process(
in_str="",
fname=os.path.abspath(
os.path.join(project_dir, "models/my_new_project/use_var.sql")
),
config=FluffConfig(configs=DBT_FLUFF_CONFIG),
)
except Exception as e:
pytest.fail(f"Unexpected RuntimeError: {e}")
@pytest.mark.parametrize(
"fname,exception_msg",
[
(
"compiler_error.sql",
"dbt compilation error on file 'models/my_new_project/compiler_error.sql', "
"Unexpected end of template. Jinja was looking for the following tags: 'endfor'",
),
("exception_connect_database.sql", "dbt tried to connect to the database"),
],
)
def test__templater_dbt_handle_exceptions(
project_dir, dbt_templater, fname, exception_msg
):
from dbt.adapters.factory import get_adapter
src_fpath = "plugins/sqlfluff-templater-dbt/test/fixtures/dbt/error_models/" + fname
target_fpath = os.path.abspath(
os.path.join(project_dir, "models/my_new_project/", fname)
)
os.rename(src_fpath, target_fpath)
try:
_, violations = dbt_templater.process(
in_str="",
fname=target_fpath,
config=FluffConfig(configs=DBT_FLUFF_CONFIG),
)
finally:
get_adapter(dbt_templater.dbt_config).connections.release()
os.rename(target_fpath, src_fpath)
assert violations
assert violations[0].desc().replace("\\", "/").startswith(exception_msg)
def test__project_dir_does_not_exist_error(dbt_templater, caplog):
dbt_templater.sqlfluff_config = FluffConfig(
configs={"templater": {"dbt": {"project_dir": "./non_existing_directory"}}}
)
logger = logging.getLogger("sqlfluff")
original_propagate_value = logger.propagate
try:
logger.propagate = True
with caplog.at_level(logging.ERROR, logger="sqlfluff.templater"):
dbt_project_dir = dbt_templater._get_project_dir()
assert (
f"dbt_project_dir: {dbt_project_dir} could not be accessed. Check it exists."
in caplog.text
)
finally:
logger.propagate = original_propagate_value
| true | true |
f7314e8b65485bdd5e00c5546138536c89f6ad88 | 819 | py | Python | classy_config/_util.py | fisher60/classy-config | abc8016f9fef328b1410ede75833429b05e20e1a | [
"MIT"
] | 7 | 2022-01-04T20:24:53.000Z | 2022-02-21T19:31:57.000Z | classy_config/_util.py | fisher60/classy-config | abc8016f9fef328b1410ede75833429b05e20e1a | [
"MIT"
] | 13 | 2022-01-04T18:53:08.000Z | 2022-02-25T11:01:29.000Z | classy_config/_util.py | fisher60/classy-config | abc8016f9fef328b1410ede75833429b05e20e1a | [
"MIT"
] | 1 | 2022-02-14T22:06:11.000Z | 2022-02-14T22:06:11.000Z | from typing import Any, MutableMapping, Optional
def merge_dicts(a: MutableMapping[str, Any], b: MutableMapping[str, Any], path: Optional[list] = None) -> MutableMapping[str, Any]:
"""
Merge the keys and values of the two dicts.
:param a:
:param b:
:param path:
:return:
:raises ValueError: When both dicts assign the same key, with different values.
"""
if path is None:
path = []
for key in b:
if key not in a:
a[key] = b[key]
continue
if isinstance(a[key], dict) and isinstance(b[key], dict):
merge_dicts(a[key], b[key], path + [str(key)])
elif a[key] == b[key]:
pass # same leaf value
else:
raise ValueError(f"Conflict at {'.'.join(path + [str(key)])}")
return a
| 26.419355 | 131 | 0.566545 | from typing import Any, MutableMapping, Optional
def merge_dicts(a: MutableMapping[str, Any], b: MutableMapping[str, Any], path: Optional[list] = None) -> MutableMapping[str, Any]:
if path is None:
path = []
for key in b:
if key not in a:
a[key] = b[key]
continue
if isinstance(a[key], dict) and isinstance(b[key], dict):
merge_dicts(a[key], b[key], path + [str(key)])
elif a[key] == b[key]:
pass
else:
raise ValueError(f"Conflict at {'.'.join(path + [str(key)])}")
return a
| true | true |
f7314f70d97443e5927a361c54120beae4e4b7f5 | 9,594 | py | Python | cinder/common/config.py | rackerlabs/cinder | 4295ff0a64f781c3546f6c6e0816dbb8100133cb | [
"Apache-2.0"
] | null | null | null | cinder/common/config.py | rackerlabs/cinder | 4295ff0a64f781c3546f6c6e0816dbb8100133cb | [
"Apache-2.0"
] | null | null | null | cinder/common/config.py | rackerlabs/cinder | 4295ff0a64f781c3546f6c6e0816dbb8100133cb | [
"Apache-2.0"
] | null | null | null | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# Copyright 2012 Red Hat, Inc.
# Copyright 2013 NTT corp.
#
# 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.
"""Command-line flag library.
Emulates gflags by wrapping cfg.ConfigOpts.
The idea is to move fully to cfg eventually, and this wrapper is a
stepping stone.
"""
import socket
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import netutils
from cinder.i18n import _
CONF = cfg.CONF
logging.register_options(CONF)
core_opts = [
cfg.StrOpt('api_paste_config',
default="api-paste.ini",
help='File name for the paste.deploy config for cinder-api'),
cfg.StrOpt('state_path',
default='/var/lib/cinder',
deprecated_name='pybasedir',
help="Top-level directory for maintaining cinder's state"), ]
debug_opts = [
]
CONF.register_cli_opts(core_opts)
CONF.register_cli_opts(debug_opts)
global_opts = [
cfg.StrOpt('my_ip',
default=netutils.get_my_ipv4(),
help='IP address of this host'),
cfg.StrOpt('glance_host',
default='$my_ip',
help='Default glance host name or IP'),
cfg.IntOpt('glance_port',
default=9292,
min=1, max=65535,
help='Default glance port'),
cfg.ListOpt('glance_api_servers',
default=['$glance_host:$glance_port'],
help='A list of the glance API servers available to cinder '
'([hostname|ip]:port)'),
cfg.IntOpt('glance_api_version',
default=1,
help='Version of the glance API to use'),
cfg.IntOpt('glance_num_retries',
default=0,
help='Number retries when downloading an image from glance'),
cfg.BoolOpt('glance_api_insecure',
default=False,
help='Allow to perform insecure SSL (https) requests to '
'glance'),
cfg.BoolOpt('glance_api_ssl_compression',
default=False,
help='Enables or disables negotiation of SSL layer '
'compression. In some cases disabling compression '
'can improve data throughput, such as when high '
'network bandwidth is available and you use '
'compressed image formats like qcow2.'),
cfg.StrOpt('glance_ca_certificates_file',
help='Location of ca certificates file to use for glance '
'client requests.'),
cfg.IntOpt('glance_request_timeout',
default=None,
help='http/https timeout value for glance operations. If no '
'value (None) is supplied here, the glanceclient default '
'value is used.'),
cfg.StrOpt('scheduler_topic',
default='cinder-scheduler',
help='The topic that scheduler nodes listen on'),
cfg.StrOpt('volume_topic',
default='cinder-volume',
help='The topic that volume nodes listen on'),
cfg.StrOpt('backup_topic',
default='cinder-backup',
help='The topic that volume backup nodes listen on'),
cfg.BoolOpt('enable_v1_api',
default=True,
help=_("DEPRECATED: Deploy v1 of the Cinder API.")),
cfg.BoolOpt('enable_v2_api',
default=True,
help=_("Deploy v2 of the Cinder API.")),
cfg.BoolOpt('api_rate_limit',
default=True,
help='Enables or disables rate limit of the API.'),
cfg.ListOpt('osapi_volume_ext_list',
default=[],
help='Specify list of extensions to load when using osapi_'
'volume_extension option with cinder.api.contrib.'
'select_extensions'),
cfg.MultiStrOpt('osapi_volume_extension',
default=['cinder.api.contrib.standard_extensions'],
help='osapi volume extension to load'),
cfg.StrOpt('volume_manager',
default='cinder.volume.manager.VolumeManager',
help='Full class name for the Manager for volume'),
cfg.StrOpt('backup_manager',
default='cinder.backup.manager.BackupManager',
help='Full class name for the Manager for volume backup'),
cfg.StrOpt('scheduler_manager',
default='cinder.scheduler.manager.SchedulerManager',
help='Full class name for the Manager for scheduler'),
cfg.StrOpt('host',
default=socket.gethostname(),
help='Name of this node. This can be an opaque identifier. '
'It is not necessarily a host name, FQDN, or IP address.'),
# NOTE(vish): default to nova for compatibility with nova installs
cfg.StrOpt('storage_availability_zone',
default='nova',
help='Availability zone of this node'),
cfg.StrOpt('default_availability_zone',
default=None,
help='Default availability zone for new volumes. If not set, '
'the storage_availability_zone option value is used as '
'the default for new volumes.'),
cfg.BoolOpt('allow_availability_zone_fallback',
default=False,
help='If the requested Cinder availability zone is '
'unavailable, fall back to the value of '
'default_availability_zone, then '
'storage_availability_zone, instead of failing.'),
cfg.StrOpt('default_volume_type',
default=None,
help='Default volume type to use'),
cfg.StrOpt('volume_usage_audit_period',
default='month',
help='Time period for which to generate volume usages. '
'The options are hour, day, month, or year.'),
cfg.StrOpt('rootwrap_config',
default='/etc/cinder/rootwrap.conf',
help='Path to the rootwrap configuration file to use for '
'running commands as root'),
cfg.BoolOpt('monkey_patch',
default=False,
help='Enable monkey patching'),
cfg.ListOpt('monkey_patch_modules',
default=[],
help='List of modules/decorators to monkey patch'),
cfg.IntOpt('service_down_time',
default=60,
help='Maximum time since last check-in for a service to be '
'considered up'),
cfg.StrOpt('volume_api_class',
default='cinder.volume.api.API',
help='The full class name of the volume API class to use'),
cfg.StrOpt('backup_api_class',
default='cinder.backup.api.API',
help='The full class name of the volume backup API class'),
cfg.StrOpt('auth_strategy',
default='keystone',
choices=['noauth', 'keystone', 'deprecated'],
help='The strategy to use for auth. Supports noauth, keystone, '
'and deprecated.'),
cfg.ListOpt('enabled_backends',
default=None,
help='A list of backend names to use. These backend names '
'should be backed by a unique [CONFIG] group '
'with its options'),
cfg.BoolOpt('no_snapshot_gb_quota',
default=False,
help='Whether snapshots count against gigabyte quota'),
cfg.StrOpt('transfer_api_class',
default='cinder.transfer.api.API',
help='The full class name of the volume transfer API class'),
cfg.StrOpt('replication_api_class',
default='cinder.replication.api.API',
help='The full class name of the volume replication API class'),
cfg.StrOpt('consistencygroup_api_class',
default='cinder.consistencygroup.api.API',
help='The full class name of the consistencygroup API class'),
cfg.StrOpt('os_privileged_user_name',
default=None,
help='OpenStack privileged account username. Used for requests '
'to other services (such as Nova) that require an account '
'with special rights.'),
cfg.StrOpt('os_privileged_user_password',
default=None,
help='Password associated with the OpenStack privileged '
'account.',
secret=True),
cfg.StrOpt('os_privileged_user_tenant',
default=None,
help='Tenant name associated with the OpenStack privileged '
'account.'),
cfg.StrOpt('os_privileged_user_auth_url',
default=None,
help='Auth URL associated with the OpenStack privileged '
'account.'),
]
CONF.register_opts(global_opts)
| 43.808219 | 79 | 0.595164 |
import socket
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import netutils
from cinder.i18n import _
CONF = cfg.CONF
logging.register_options(CONF)
core_opts = [
cfg.StrOpt('api_paste_config',
default="api-paste.ini",
help='File name for the paste.deploy config for cinder-api'),
cfg.StrOpt('state_path',
default='/var/lib/cinder',
deprecated_name='pybasedir',
help="Top-level directory for maintaining cinder's state"), ]
debug_opts = [
]
CONF.register_cli_opts(core_opts)
CONF.register_cli_opts(debug_opts)
global_opts = [
cfg.StrOpt('my_ip',
default=netutils.get_my_ipv4(),
help='IP address of this host'),
cfg.StrOpt('glance_host',
default='$my_ip',
help='Default glance host name or IP'),
cfg.IntOpt('glance_port',
default=9292,
min=1, max=65535,
help='Default glance port'),
cfg.ListOpt('glance_api_servers',
default=['$glance_host:$glance_port'],
help='A list of the glance API servers available to cinder '
'([hostname|ip]:port)'),
cfg.IntOpt('glance_api_version',
default=1,
help='Version of the glance API to use'),
cfg.IntOpt('glance_num_retries',
default=0,
help='Number retries when downloading an image from glance'),
cfg.BoolOpt('glance_api_insecure',
default=False,
help='Allow to perform insecure SSL (https) requests to '
'glance'),
cfg.BoolOpt('glance_api_ssl_compression',
default=False,
help='Enables or disables negotiation of SSL layer '
'compression. In some cases disabling compression '
'can improve data throughput, such as when high '
'network bandwidth is available and you use '
'compressed image formats like qcow2.'),
cfg.StrOpt('glance_ca_certificates_file',
help='Location of ca certificates file to use for glance '
'client requests.'),
cfg.IntOpt('glance_request_timeout',
default=None,
help='http/https timeout value for glance operations. If no '
'value (None) is supplied here, the glanceclient default '
'value is used.'),
cfg.StrOpt('scheduler_topic',
default='cinder-scheduler',
help='The topic that scheduler nodes listen on'),
cfg.StrOpt('volume_topic',
default='cinder-volume',
help='The topic that volume nodes listen on'),
cfg.StrOpt('backup_topic',
default='cinder-backup',
help='The topic that volume backup nodes listen on'),
cfg.BoolOpt('enable_v1_api',
default=True,
help=_("DEPRECATED: Deploy v1 of the Cinder API.")),
cfg.BoolOpt('enable_v2_api',
default=True,
help=_("Deploy v2 of the Cinder API.")),
cfg.BoolOpt('api_rate_limit',
default=True,
help='Enables or disables rate limit of the API.'),
cfg.ListOpt('osapi_volume_ext_list',
default=[],
help='Specify list of extensions to load when using osapi_'
'volume_extension option with cinder.api.contrib.'
'select_extensions'),
cfg.MultiStrOpt('osapi_volume_extension',
default=['cinder.api.contrib.standard_extensions'],
help='osapi volume extension to load'),
cfg.StrOpt('volume_manager',
default='cinder.volume.manager.VolumeManager',
help='Full class name for the Manager for volume'),
cfg.StrOpt('backup_manager',
default='cinder.backup.manager.BackupManager',
help='Full class name for the Manager for volume backup'),
cfg.StrOpt('scheduler_manager',
default='cinder.scheduler.manager.SchedulerManager',
help='Full class name for the Manager for scheduler'),
cfg.StrOpt('host',
default=socket.gethostname(),
help='Name of this node. This can be an opaque identifier. '
'It is not necessarily a host name, FQDN, or IP address.'),
# NOTE(vish): default to nova for compatibility with nova installs
cfg.StrOpt('storage_availability_zone',
default='nova',
help='Availability zone of this node'),
cfg.StrOpt('default_availability_zone',
default=None,
help='Default availability zone for new volumes. If not set, '
'the storage_availability_zone option value is used as '
'the default for new volumes.'),
cfg.BoolOpt('allow_availability_zone_fallback',
default=False,
help='If the requested Cinder availability zone is '
'unavailable, fall back to the value of '
'default_availability_zone, then '
'storage_availability_zone, instead of failing.'),
cfg.StrOpt('default_volume_type',
default=None,
help='Default volume type to use'),
cfg.StrOpt('volume_usage_audit_period',
default='month',
help='Time period for which to generate volume usages. '
'The options are hour, day, month, or year.'),
cfg.StrOpt('rootwrap_config',
default='/etc/cinder/rootwrap.conf',
help='Path to the rootwrap configuration file to use for '
'running commands as root'),
cfg.BoolOpt('monkey_patch',
default=False,
help='Enable monkey patching'),
cfg.ListOpt('monkey_patch_modules',
default=[],
help='List of modules/decorators to monkey patch'),
cfg.IntOpt('service_down_time',
default=60,
help='Maximum time since last check-in for a service to be '
'considered up'),
cfg.StrOpt('volume_api_class',
default='cinder.volume.api.API',
help='The full class name of the volume API class to use'),
cfg.StrOpt('backup_api_class',
default='cinder.backup.api.API',
help='The full class name of the volume backup API class'),
cfg.StrOpt('auth_strategy',
default='keystone',
choices=['noauth', 'keystone', 'deprecated'],
help='The strategy to use for auth. Supports noauth, keystone, '
'and deprecated.'),
cfg.ListOpt('enabled_backends',
default=None,
help='A list of backend names to use. These backend names '
'should be backed by a unique [CONFIG] group '
'with its options'),
cfg.BoolOpt('no_snapshot_gb_quota',
default=False,
help='Whether snapshots count against gigabyte quota'),
cfg.StrOpt('transfer_api_class',
default='cinder.transfer.api.API',
help='The full class name of the volume transfer API class'),
cfg.StrOpt('replication_api_class',
default='cinder.replication.api.API',
help='The full class name of the volume replication API class'),
cfg.StrOpt('consistencygroup_api_class',
default='cinder.consistencygroup.api.API',
help='The full class name of the consistencygroup API class'),
cfg.StrOpt('os_privileged_user_name',
default=None,
help='OpenStack privileged account username. Used for requests '
'to other services (such as Nova) that require an account '
'with special rights.'),
cfg.StrOpt('os_privileged_user_password',
default=None,
help='Password associated with the OpenStack privileged '
'account.',
secret=True),
cfg.StrOpt('os_privileged_user_tenant',
default=None,
help='Tenant name associated with the OpenStack privileged '
'account.'),
cfg.StrOpt('os_privileged_user_auth_url',
default=None,
help='Auth URL associated with the OpenStack privileged '
'account.'),
]
CONF.register_opts(global_opts)
| true | true |
f7314f8b974c2b54dbcb6c11c5211b6c0d1d666e | 3,340 | py | Python | muranoclient/v1/services.py | mail2nsrajesh/python-muranoclient | 08411aa8d20993ac7c4a52b2aa0e73fb6fea4d40 | [
"Apache-2.0"
] | 27 | 2015-04-26T16:05:29.000Z | 2021-01-28T03:31:57.000Z | muranoclient/v1/services.py | mail2nsrajesh/python-muranoclient | 08411aa8d20993ac7c4a52b2aa0e73fb6fea4d40 | [
"Apache-2.0"
] | null | null | null | muranoclient/v1/services.py | mail2nsrajesh/python-muranoclient | 08411aa8d20993ac7c4a52b2aa0e73fb6fea4d40 | [
"Apache-2.0"
] | 14 | 2015-06-12T05:37:50.000Z | 2019-05-02T20:37:42.000Z | # Copyright (c) 2013 Mirantis, 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 functools
import posixpath
from muranoclient.common import base
def normalize_path(f):
@functools.wraps(f)
def f_normalize_path(*args, **kwargs):
path = args[2] if len(args) >= 3 else kwargs['path']
# path formally is just absolute unix path
if not posixpath.isabs(path):
raise ValueError("Parameter 'path' should start with '/'")
args = list(args)
if len(args) >= 3:
args[2] = args[2][1:]
else:
kwargs['path'] = kwargs['path'][1:]
return f(*args, **kwargs)
return f_normalize_path
class Service(base.Resource):
def __repr__(self):
return '<Service %s>' % self._info
def data(self, **kwargs):
return self.manager.data(self, **kwargs)
def _add_details(self, info):
if isinstance(info, dict):
for k, v in info.items():
setattr(self, k, v)
class ServiceManager(base.Manager):
resource_class = Service
def list(self, environment_id, session_id=None):
if session_id:
headers = {'X-Configuration-Session': session_id}
else:
headers = {}
return self._list("/v1/environments/{0}/services".
format(environment_id), headers=headers)
@normalize_path
def get(self, environment_id, path, session_id=None):
if session_id:
headers = {'X-Configuration-Session': session_id}
else:
headers = {}
return self._get('/v1/environments/{0}/services/{1}'.
format(environment_id, path), headers=headers)
@normalize_path
def post(self, environment_id, path, data, session_id):
headers = {'X-Configuration-Session': session_id}
result = self._create('/v1/environments/{0}/services/{1}'.
format(environment_id, path), data,
headers=headers, return_raw=True)
if isinstance(result, list):
return [self.resource_class(self, item) for item in result]
else:
return self.resource_class(self, result)
@normalize_path
def put(self, environment_id, path, data, session_id):
headers = {'X-Configuration-Session': session_id}
return self._update('/v1/environments/{0}/services/{1}'.
format(environment_id, path), data,
headers=headers)
@normalize_path
def delete(self, environment_id, path, session_id):
headers = {'X-Configuration-Session': session_id}
path = '/v1/environments/{0}/services/{1}'.format(environment_id, path)
return self._delete(path, headers=headers)
| 32.745098 | 79 | 0.613473 |
import functools
import posixpath
from muranoclient.common import base
def normalize_path(f):
@functools.wraps(f)
def f_normalize_path(*args, **kwargs):
path = args[2] if len(args) >= 3 else kwargs['path']
if not posixpath.isabs(path):
raise ValueError("Parameter 'path' should start with '/'")
args = list(args)
if len(args) >= 3:
args[2] = args[2][1:]
else:
kwargs['path'] = kwargs['path'][1:]
return f(*args, **kwargs)
return f_normalize_path
class Service(base.Resource):
def __repr__(self):
return '<Service %s>' % self._info
def data(self, **kwargs):
return self.manager.data(self, **kwargs)
def _add_details(self, info):
if isinstance(info, dict):
for k, v in info.items():
setattr(self, k, v)
class ServiceManager(base.Manager):
resource_class = Service
def list(self, environment_id, session_id=None):
if session_id:
headers = {'X-Configuration-Session': session_id}
else:
headers = {}
return self._list("/v1/environments/{0}/services".
format(environment_id), headers=headers)
@normalize_path
def get(self, environment_id, path, session_id=None):
if session_id:
headers = {'X-Configuration-Session': session_id}
else:
headers = {}
return self._get('/v1/environments/{0}/services/{1}'.
format(environment_id, path), headers=headers)
@normalize_path
def post(self, environment_id, path, data, session_id):
headers = {'X-Configuration-Session': session_id}
result = self._create('/v1/environments/{0}/services/{1}'.
format(environment_id, path), data,
headers=headers, return_raw=True)
if isinstance(result, list):
return [self.resource_class(self, item) for item in result]
else:
return self.resource_class(self, result)
@normalize_path
def put(self, environment_id, path, data, session_id):
headers = {'X-Configuration-Session': session_id}
return self._update('/v1/environments/{0}/services/{1}'.
format(environment_id, path), data,
headers=headers)
@normalize_path
def delete(self, environment_id, path, session_id):
headers = {'X-Configuration-Session': session_id}
path = '/v1/environments/{0}/services/{1}'.format(environment_id, path)
return self._delete(path, headers=headers)
| true | true |
f7314fe04d0a36817a1cc7e4b30f2ff6ab6dfec8 | 871 | py | Python | conflowgen/tests/domain_models/distribution_model_seeder/test_container_weight_distribution_seeder.py | bbargstaedt/conflowgen | b5b5c0e2df8a605d23ef467aaa3e88aa463a34ee | [
"MIT"
] | 5 | 2022-02-16T11:44:42.000Z | 2022-02-24T20:02:17.000Z | conflowgen/tests/domain_models/distribution_model_seeder/test_container_weight_distribution_seeder.py | bbargstaedt/conflowgen | b5b5c0e2df8a605d23ef467aaa3e88aa463a34ee | [
"MIT"
] | 90 | 2021-12-08T14:05:44.000Z | 2022-03-24T08:53:31.000Z | conflowgen/tests/domain_models/distribution_model_seeder/test_container_weight_distribution_seeder.py | bbargstaedt/conflowgen | b5b5c0e2df8a605d23ef467aaa3e88aa463a34ee | [
"MIT"
] | 5 | 2021-12-07T16:05:15.000Z | 2022-02-16T08:24:07.000Z | """
Check if container weights can be properly seeded.
"""
import unittest
from conflowgen.domain_models.distribution_models.container_weight_distribution import ContainerWeightDistribution
from conflowgen.domain_models.distribution_seeders import container_weight_distribution_seeder
from conflowgen.tests.substitute_peewee_database import setup_sqlite_in_memory_db
class TestContainerWeightDistributionSeeder(unittest.TestCase):
"""
The actual ModeOfTransportField behavior is implemented in peewee.
"""
def setUp(self) -> None:
"""Create container database in memory"""
sqlite_db = setup_sqlite_in_memory_db()
sqlite_db.create_tables([
ContainerWeightDistribution
])
def test_seeding(self):
"""This should just not throw any exception"""
container_weight_distribution_seeder.seed()
| 32.259259 | 114 | 0.766935 |
import unittest
from conflowgen.domain_models.distribution_models.container_weight_distribution import ContainerWeightDistribution
from conflowgen.domain_models.distribution_seeders import container_weight_distribution_seeder
from conflowgen.tests.substitute_peewee_database import setup_sqlite_in_memory_db
class TestContainerWeightDistributionSeeder(unittest.TestCase):
def setUp(self) -> None:
sqlite_db = setup_sqlite_in_memory_db()
sqlite_db.create_tables([
ContainerWeightDistribution
])
def test_seeding(self):
container_weight_distribution_seeder.seed()
| true | true |
f73150728d21634b3692b32fa17efb6464b8c3ef | 2,110 | py | Python | download_paper.py | xiangze/CSpaperTopicViewer | f98bfc3d8771b50448867b15b723ab6af8e6d321 | [
"WTFPL"
] | 1 | 2016-07-10T23:51:12.000Z | 2016-07-10T23:51:12.000Z | download_paper.py | xiangze/cvprpapers | f98bfc3d8771b50448867b15b723ab6af8e6d321 | [
"WTFPL"
] | null | null | null | download_paper.py | xiangze/cvprpapers | f98bfc3d8771b50448867b15b723ab6af8e6d321 | [
"WTFPL"
] | 1 | 2016-08-02T06:34:37.000Z | 2016-08-02T06:34:37.000Z | import httplib2
from bs4 import BeautifulSoup, SoupStrainer
import urllib.request, urllib.error
import os
import re
import sys
def get(url):
http = httplib2.Http(".cache", disable_ssl_certificate_validation=True)
status, response = http.request(url)
return response
def getlinks(url):
return BeautifulSoup(get(url),"html.parser", parseOnlyThese=SoupStrainer('a'))
def pdfname(file_url,save_folder):
start_index = file_url.rfind("/")+1
return save_folder+"/"+file_url[start_index:]
def savepdf(link,base_url,save_folder):
if link != "#" and link.endswith('pdf'):
outfilename=pdfname(link,save_folder)
if(not os.path.exists(outfilename)):
pdf = urllib.request.urlopen(base_url+link).read()
with open(outfilename, 'wb') as f:
f.write(pdf)
year=2016
conference="cvpr"
argc=len(sys.argv)
if(argc>1):
year=int(sys.argv[1])
if(argc>2):
conference=sys.argv[2]
save_folder=conference+str(year)
if(not os.path.exists(save_folder)):
os.mkdir(save_folder)
if(conference=="cvpr"):
base_url = 'https://openaccess.thecvf.com/'
url=base_url+'CVPR%d?day=all'%year
# print(get(url))
links=getlinks(url)
# print(links)
for link in links:
if link.has_key('href'):
savepdf(link['href'],base_url,save_folder)
elif(conference=="iccv"):
base_url = 'https://openaccess.thecvf.com/'
links=getlinks(base_url+'ICCV%d'%year)
for link in links:
if link.has_key('href'):
savepdf(link['href'],base_url,save_folder)
elif(conference=="nips"):
base_url = 'https://papers.nips.cc/'
links=getlinks(base_url)
for l in links:
if(len(re.findall(str(year),l.text))>0):
turl=l['href']
links_of_year=getlinks(base_url+turl)
print( len(links_of_year))
for l in links_of_year:
links_of_a_paper=getlinks(base_url+l['href'])
for link in links_of_a_paper:
if link.has_key('href'):
savepdf(link['href'],base_url,save_folder)
else:
print("not supperted conference :%s"%conference)
| 27.402597 | 83 | 0.658768 | import httplib2
from bs4 import BeautifulSoup, SoupStrainer
import urllib.request, urllib.error
import os
import re
import sys
def get(url):
http = httplib2.Http(".cache", disable_ssl_certificate_validation=True)
status, response = http.request(url)
return response
def getlinks(url):
return BeautifulSoup(get(url),"html.parser", parseOnlyThese=SoupStrainer('a'))
def pdfname(file_url,save_folder):
start_index = file_url.rfind("/")+1
return save_folder+"/"+file_url[start_index:]
def savepdf(link,base_url,save_folder):
if link != "#" and link.endswith('pdf'):
outfilename=pdfname(link,save_folder)
if(not os.path.exists(outfilename)):
pdf = urllib.request.urlopen(base_url+link).read()
with open(outfilename, 'wb') as f:
f.write(pdf)
year=2016
conference="cvpr"
argc=len(sys.argv)
if(argc>1):
year=int(sys.argv[1])
if(argc>2):
conference=sys.argv[2]
save_folder=conference+str(year)
if(not os.path.exists(save_folder)):
os.mkdir(save_folder)
if(conference=="cvpr"):
base_url = 'https://openaccess.thecvf.com/'
url=base_url+'CVPR%d?day=all'%year
links=getlinks(url)
for link in links:
if link.has_key('href'):
savepdf(link['href'],base_url,save_folder)
elif(conference=="iccv"):
base_url = 'https://openaccess.thecvf.com/'
links=getlinks(base_url+'ICCV%d'%year)
for link in links:
if link.has_key('href'):
savepdf(link['href'],base_url,save_folder)
elif(conference=="nips"):
base_url = 'https://papers.nips.cc/'
links=getlinks(base_url)
for l in links:
if(len(re.findall(str(year),l.text))>0):
turl=l['href']
links_of_year=getlinks(base_url+turl)
print( len(links_of_year))
for l in links_of_year:
links_of_a_paper=getlinks(base_url+l['href'])
for link in links_of_a_paper:
if link.has_key('href'):
savepdf(link['href'],base_url,save_folder)
else:
print("not supperted conference :%s"%conference)
| true | true |
f73150e76382b56bfc3f89148efd010e1fe93f98 | 1,332 | py | Python | utils/logquant_v1.py | listato/Logarithmic-Quantization-of-Parameters-in-Neural-Networks | dbc6a48ab5e0bf4361be459a45598523f2344371 | [
"MIT"
] | 1 | 2022-02-04T10:39:54.000Z | 2022-02-04T10:39:54.000Z | utils/logquant_v1.py | listato/Logarithmic-Quantization-of-Parameters-in-Neural-Networks | dbc6a48ab5e0bf4361be459a45598523f2344371 | [
"MIT"
] | null | null | null | utils/logquant_v1.py | listato/Logarithmic-Quantization-of-Parameters-in-Neural-Networks | dbc6a48ab5e0bf4361be459a45598523f2344371 | [
"MIT"
] | null | null | null | """
Author: CAI JINGYONG @ BeatCraft, Inc & Tokyo University of Agriculture and Technology
placeholder
input: numpy array
output: numpy array
"""
import numpy
class LogQuant:
def __init__(self,layer,bitwidth):
self.layer_data = layer
self.width = bitwidth
self.maxima = numpy.amax(layer)
self.minima = numpy.amin(layer)
self.fsr = self.maxima - self.minima
self.sign = numpy.sign(layer)
pass
def __clip(self, x):
# min = self.fsr-(2**self.width)
min = 4 - (2**self.width)
if(x <= min):
return 0
elif(x >= 4):
return 4 - 1
else:
return x
def __round(self,x):
bridge = numpy.sqrt(2)-1
decimalpart, intpart = numpy.modf(x)
if decimalpart >= bridge:
return numpy.ceil(x)
else:
return numpy.floor(x)
@property
def log_quantize(self):
round = numpy.vectorize(self.__round)
clip = numpy.vectorize(self.__clip)
# numpy.log2(0) -> -infinity == float("-inf") which will be used in clip method
return numpy.array(clip(round(numpy.log2(abs(self.layer_data)))),dtype=numpy.int8)
@property
def de_quantize(self):
x = numpy.power(2.0, self.log_quantized)
return x * self.sign
| 26.64 | 90 | 0.583333 | import numpy
class LogQuant:
def __init__(self,layer,bitwidth):
self.layer_data = layer
self.width = bitwidth
self.maxima = numpy.amax(layer)
self.minima = numpy.amin(layer)
self.fsr = self.maxima - self.minima
self.sign = numpy.sign(layer)
pass
def __clip(self, x):
min = 4 - (2**self.width)
if(x <= min):
return 0
elif(x >= 4):
return 4 - 1
else:
return x
def __round(self,x):
bridge = numpy.sqrt(2)-1
decimalpart, intpart = numpy.modf(x)
if decimalpart >= bridge:
return numpy.ceil(x)
else:
return numpy.floor(x)
@property
def log_quantize(self):
round = numpy.vectorize(self.__round)
clip = numpy.vectorize(self.__clip)
return numpy.array(clip(round(numpy.log2(abs(self.layer_data)))),dtype=numpy.int8)
@property
def de_quantize(self):
x = numpy.power(2.0, self.log_quantized)
return x * self.sign
| true | true |
f731514ce63880879d8950cd12e196a3a011a776 | 11,680 | py | Python | chives/util/merkle_set.py | zcomputerwiz/chives-light-wallet | b5f57f46bf4f804cc06a6e2bdf8cbde41bba2fe0 | [
"Apache-2.0"
] | null | null | null | chives/util/merkle_set.py | zcomputerwiz/chives-light-wallet | b5f57f46bf4f804cc06a6e2bdf8cbde41bba2fe0 | [
"Apache-2.0"
] | null | null | null | chives/util/merkle_set.py | zcomputerwiz/chives-light-wallet | b5f57f46bf4f804cc06a6e2bdf8cbde41bba2fe0 | [
"Apache-2.0"
] | 1 | 2022-03-20T16:19:04.000Z | 2022-03-20T16:19:04.000Z | from abc import ABCMeta, abstractmethod
from hashlib import sha256
from typing import Any, Dict, List, Tuple
from chives.types.blockchain_format.sized_bytes import bytes32
"""
A simple, confidence-inspiring Merkle Set standard
Advantages of this standard:
Low CPU requirements
Small proofs of inclusion/exclusion
Reasonably simple implementation
The main tricks in this standard are:
Skips repeated hashing of exactly two things even when they share prefix bits
Proofs support proving including/exclusion for a large number of values in
a single string. They're a serialization of a subset of the tree.
Proof format:
multiproof: subtree
subtree: middle or terminal or truncated or empty
middle: MIDDLE 1 subtree subtree
terminal: TERMINAL 1 hash 32
# If the sibling is empty truncated implies more than two children.
truncated: TRUNCATED 1 hash 32
empty: EMPTY 1
EMPTY: \x00
TERMINAL: \x01
MIDDLE: \x02
TRUNCATED: \x03
"""
EMPTY = bytes([0])
TERMINAL = bytes([1])
MIDDLE = bytes([2])
TRUNCATED = bytes([3])
BLANK = bytes32([0] * 32)
prehashed: Dict[bytes, Any] = {}
def init_prehashed():
for x in [EMPTY, TERMINAL, MIDDLE]:
for y in [EMPTY, TERMINAL, MIDDLE]:
prehashed[x + y] = sha256(bytes([0] * 30) + x + y)
init_prehashed()
def hashdown(mystr: bytes) -> bytes:
assert len(mystr) == 66
h = prehashed[bytes(mystr[0:1] + mystr[33:34])].copy()
h.update(mystr[1:33] + mystr[34:])
return h.digest()[:32]
def compress_root(mystr: bytes) -> bytes32:
assert len(mystr) == 33
if mystr[0:1] == MIDDLE:
return bytes32(mystr[1:])
if mystr[0:1] == EMPTY:
assert mystr[1:] == BLANK
return BLANK
return bytes32(sha256(mystr).digest()[:32])
def get_bit(mybytes: bytes, pos: int) -> int:
assert len(mybytes) == 32
return (mybytes[pos // 8] >> (7 - (pos % 8))) & 1
class Node(metaclass=ABCMeta):
hash: bytes
@abstractmethod
def get_hash(self) -> bytes:
pass
@abstractmethod
def is_empty(self) -> bool:
pass
@abstractmethod
def is_terminal(self) -> bool:
pass
@abstractmethod
def is_double(self) -> bool:
pass
@abstractmethod
def add(self, toadd: bytes, depth: int) -> "Node":
pass
@abstractmethod
def remove(self, toremove: bytes, depth: int):
pass
@abstractmethod
def is_included(self, tocheck: bytes, depth: int, p: List[bytes]) -> bool:
pass
@abstractmethod
def other_included(self, tocheck: bytes, depth: int, p: List[bytes], collapse: bool):
pass
@abstractmethod
def _audit(self, hashes: List[bytes], bits: List[int]):
pass
class MerkleSet:
root: Node
def __init__(self, root: Node = None):
if root is None:
self.root = _empty
else:
self.root = root
def get_root(self) -> bytes32:
return compress_root(self.root.get_hash())
def add_already_hashed(self, toadd: bytes):
self.root = self.root.add(toadd, 0)
def remove_already_hashed(self, toremove: bytes):
self.root = self.root.remove(toremove, 0)
def is_included_already_hashed(self, tocheck: bytes) -> Tuple[bool, bytes]:
proof: List = []
r = self.root.is_included(tocheck, 0, proof)
return r, b"".join(proof)
def _audit(self, hashes: List[bytes]):
newhashes: List = []
self.root._audit(newhashes, [])
assert newhashes == sorted(newhashes)
class EmptyNode(Node):
def __init__(self):
self.hash = BLANK
def get_hash(self) -> bytes:
return EMPTY + BLANK
def is_empty(self) -> bool:
return True
def is_terminal(self) -> bool:
return False
def is_double(self) -> bool:
raise SetError()
def add(self, toadd: bytes, depth: int) -> Node:
return TerminalNode(toadd)
def remove(self, toremove: bytes, depth: int) -> Node:
return self
def is_included(self, tocheck: bytes, depth: int, p: List[bytes]) -> bool:
p.append(EMPTY)
return False
def other_included(self, tocheck: bytes, depth: int, p: List[bytes], collapse: bool):
p.append(EMPTY)
def _audit(self, hashes: List[bytes], bits: List[int]):
pass
_empty = EmptyNode()
class TerminalNode(Node):
def __init__(self, hash: bytes, bits: List[int] = None):
assert len(hash) == 32
self.hash = hash
if bits is not None:
self._audit([], bits)
def get_hash(self) -> bytes:
return TERMINAL + self.hash
def is_empty(self) -> bool:
return False
def is_terminal(self) -> bool:
return True
def is_double(self) -> bool:
raise SetError()
def add(self, toadd: bytes, depth: int) -> Node:
if toadd == self.hash:
return self
if toadd > self.hash:
return self._make_middle([self, TerminalNode(toadd)], depth)
else:
return self._make_middle([TerminalNode(toadd), self], depth)
def _make_middle(self, children: Any, depth: int) -> Node:
cbits = [get_bit(child.hash, depth) for child in children]
if cbits[0] != cbits[1]:
return MiddleNode(children)
nextvals: List[Node] = [_empty, _empty]
nextvals[cbits[0] ^ 1] = _empty
nextvals[cbits[0]] = self._make_middle(children, depth + 1)
return MiddleNode(nextvals)
def remove(self, toremove: bytes, depth: int) -> Node:
if toremove == self.hash:
return _empty
return self
def is_included(self, tocheck: bytes, depth: int, p: List[bytes]) -> bool:
p.append(TERMINAL + self.hash)
return tocheck == self.hash
def other_included(self, tocheck: bytes, depth: int, p: List[bytes], collapse: bool):
p.append(TERMINAL + self.hash)
def _audit(self, hashes: List[bytes], bits: List[int]):
hashes.append(self.hash)
for pos, v in enumerate(bits):
assert get_bit(self.hash, pos) == v
class MiddleNode(Node):
def __init__(self, children: List[Node]):
self.children = children
if children[0].is_empty() and children[1].is_double():
self.hash = children[1].hash
elif children[1].is_empty() and children[0].is_double():
self.hash = children[0].hash
else:
if children[0].is_empty() and (children[1].is_empty() or children[1].is_terminal()):
raise SetError()
if children[1].is_empty() and children[0].is_terminal():
raise SetError
if children[0].is_terminal() and children[1].is_terminal() and children[0].hash >= children[1].hash:
raise SetError
self.hash = hashdown(children[0].get_hash() + children[1].get_hash())
def get_hash(self) -> bytes:
return MIDDLE + self.hash
def is_empty(self) -> bool:
return False
def is_terminal(self) -> bool:
return False
def is_double(self) -> bool:
if self.children[0].is_empty():
return self.children[1].is_double()
if self.children[1].is_empty():
return self.children[0].is_double()
return self.children[0].is_terminal() and self.children[1].is_terminal()
def add(self, toadd: bytes, depth: int) -> Node:
bit = get_bit(toadd, depth)
child = self.children[bit]
newchild = child.add(toadd, depth + 1)
if newchild is child:
return self
newvals = [x for x in self.children]
newvals[bit] = newchild
return MiddleNode(newvals)
def remove(self, toremove: bytes, depth: int) -> Node:
bit = get_bit(toremove, depth)
child = self.children[bit]
newchild = child.remove(toremove, depth + 1)
if newchild is child:
return self
otherchild = self.children[bit ^ 1]
if newchild.is_empty() and otherchild.is_terminal():
return otherchild
if newchild.is_terminal() and otherchild.is_empty():
return newchild
newvals = [x for x in self.children]
newvals[bit] = newchild
return MiddleNode(newvals)
def is_included(self, tocheck: bytes, depth: int, p: List[bytes]) -> bool:
p.append(MIDDLE)
if get_bit(tocheck, depth) == 0:
r = self.children[0].is_included(tocheck, depth + 1, p)
self.children[1].other_included(tocheck, depth + 1, p, not self.children[0].is_empty())
return r
else:
self.children[0].other_included(tocheck, depth + 1, p, not self.children[1].is_empty())
return self.children[1].is_included(tocheck, depth + 1, p)
def other_included(self, tocheck: bytes, depth: int, p: List[bytes], collapse: bool):
if collapse or not self.is_double():
p.append(TRUNCATED + self.hash)
else:
self.is_included(tocheck, depth, p)
def _audit(self, hashes: List[bytes], bits: List[int]):
self.children[0]._audit(hashes, bits + [0])
self.children[1]._audit(hashes, bits + [1])
class TruncatedNode(Node):
def __init__(self, hash: bytes):
self.hash = hash
def get_hash(self) -> bytes:
return MIDDLE + self.hash
def is_empty(self) -> bool:
return False
def is_terminal(self) -> bool:
return False
def is_double(self) -> bool:
return False
def add(self, toadd: bytes, depth: int) -> Node:
return self
def remove(self, toremove: bytes, depth: int) -> Node:
return self
def is_included(self, tocheck: bytes, depth: int, p: List[bytes]) -> bool:
raise SetError()
def other_included(self, tocheck: bytes, depth: int, p: List[bytes], collapse: bool):
p.append(TRUNCATED + self.hash)
def _audit(self, hashes: List[bytes], bits: List[int]):
pass
class SetError(Exception):
pass
def confirm_included(root: Node, val: bytes, proof: bytes32) -> bool:
return confirm_not_included_already_hashed(root, sha256(val).digest(), proof)
def confirm_included_already_hashed(root: Node, val: bytes, proof: bytes) -> bool:
return _confirm(root, val, proof, True)
def confirm_not_included(root: Node, val: bytes, proof: bytes32) -> bool:
return confirm_not_included_already_hashed(root, sha256(val).digest(), proof)
def confirm_not_included_already_hashed(root: Node, val: bytes, proof: bytes) -> bool:
return _confirm(root, val, proof, False)
def _confirm(root: Node, val: bytes, proof: bytes, expected: bool) -> bool:
try:
p = deserialize_proof(proof)
if p.get_root() != root:
return False
r, junk = p.is_included_already_hashed(val)
return r == expected
except SetError:
return False
def deserialize_proof(proof: bytes) -> MerkleSet:
try:
r, pos = _deserialize(proof, 0, [])
if pos != len(proof):
raise SetError()
return MerkleSet(r)
except IndexError:
raise SetError()
def _deserialize(proof: bytes, pos: int, bits: List[int]) -> Tuple[Node, int]:
t = proof[pos : pos + 1] # flake8: noqa
if t == EMPTY:
return _empty, pos + 1
if t == TERMINAL:
return TerminalNode(proof[pos + 1 : pos + 33], bits), pos + 33 # flake8: noqa
if t == TRUNCATED:
return TruncatedNode(proof[pos + 1 : pos + 33]), pos + 33 # flake8: noqa
if t != MIDDLE:
raise SetError()
v0, pos = _deserialize(proof, pos + 1, bits + [0])
v1, pos = _deserialize(proof, pos, bits + [1])
return MiddleNode([v0, v1]), pos
| 29.054726 | 112 | 0.617894 | from abc import ABCMeta, abstractmethod
from hashlib import sha256
from typing import Any, Dict, List, Tuple
from chives.types.blockchain_format.sized_bytes import bytes32
EMPTY = bytes([0])
TERMINAL = bytes([1])
MIDDLE = bytes([2])
TRUNCATED = bytes([3])
BLANK = bytes32([0] * 32)
prehashed: Dict[bytes, Any] = {}
def init_prehashed():
for x in [EMPTY, TERMINAL, MIDDLE]:
for y in [EMPTY, TERMINAL, MIDDLE]:
prehashed[x + y] = sha256(bytes([0] * 30) + x + y)
init_prehashed()
def hashdown(mystr: bytes) -> bytes:
assert len(mystr) == 66
h = prehashed[bytes(mystr[0:1] + mystr[33:34])].copy()
h.update(mystr[1:33] + mystr[34:])
return h.digest()[:32]
def compress_root(mystr: bytes) -> bytes32:
assert len(mystr) == 33
if mystr[0:1] == MIDDLE:
return bytes32(mystr[1:])
if mystr[0:1] == EMPTY:
assert mystr[1:] == BLANK
return BLANK
return bytes32(sha256(mystr).digest()[:32])
def get_bit(mybytes: bytes, pos: int) -> int:
assert len(mybytes) == 32
return (mybytes[pos // 8] >> (7 - (pos % 8))) & 1
class Node(metaclass=ABCMeta):
hash: bytes
@abstractmethod
def get_hash(self) -> bytes:
pass
@abstractmethod
def is_empty(self) -> bool:
pass
@abstractmethod
def is_terminal(self) -> bool:
pass
@abstractmethod
def is_double(self) -> bool:
pass
@abstractmethod
def add(self, toadd: bytes, depth: int) -> "Node":
pass
@abstractmethod
def remove(self, toremove: bytes, depth: int):
pass
@abstractmethod
def is_included(self, tocheck: bytes, depth: int, p: List[bytes]) -> bool:
pass
@abstractmethod
def other_included(self, tocheck: bytes, depth: int, p: List[bytes], collapse: bool):
pass
@abstractmethod
def _audit(self, hashes: List[bytes], bits: List[int]):
pass
class MerkleSet:
root: Node
def __init__(self, root: Node = None):
if root is None:
self.root = _empty
else:
self.root = root
def get_root(self) -> bytes32:
return compress_root(self.root.get_hash())
def add_already_hashed(self, toadd: bytes):
self.root = self.root.add(toadd, 0)
def remove_already_hashed(self, toremove: bytes):
self.root = self.root.remove(toremove, 0)
def is_included_already_hashed(self, tocheck: bytes) -> Tuple[bool, bytes]:
proof: List = []
r = self.root.is_included(tocheck, 0, proof)
return r, b"".join(proof)
def _audit(self, hashes: List[bytes]):
newhashes: List = []
self.root._audit(newhashes, [])
assert newhashes == sorted(newhashes)
class EmptyNode(Node):
def __init__(self):
self.hash = BLANK
def get_hash(self) -> bytes:
return EMPTY + BLANK
def is_empty(self) -> bool:
return True
def is_terminal(self) -> bool:
return False
def is_double(self) -> bool:
raise SetError()
def add(self, toadd: bytes, depth: int) -> Node:
return TerminalNode(toadd)
def remove(self, toremove: bytes, depth: int) -> Node:
return self
def is_included(self, tocheck: bytes, depth: int, p: List[bytes]) -> bool:
p.append(EMPTY)
return False
def other_included(self, tocheck: bytes, depth: int, p: List[bytes], collapse: bool):
p.append(EMPTY)
def _audit(self, hashes: List[bytes], bits: List[int]):
pass
_empty = EmptyNode()
class TerminalNode(Node):
def __init__(self, hash: bytes, bits: List[int] = None):
assert len(hash) == 32
self.hash = hash
if bits is not None:
self._audit([], bits)
def get_hash(self) -> bytes:
return TERMINAL + self.hash
def is_empty(self) -> bool:
return False
def is_terminal(self) -> bool:
return True
def is_double(self) -> bool:
raise SetError()
def add(self, toadd: bytes, depth: int) -> Node:
if toadd == self.hash:
return self
if toadd > self.hash:
return self._make_middle([self, TerminalNode(toadd)], depth)
else:
return self._make_middle([TerminalNode(toadd), self], depth)
def _make_middle(self, children: Any, depth: int) -> Node:
cbits = [get_bit(child.hash, depth) for child in children]
if cbits[0] != cbits[1]:
return MiddleNode(children)
nextvals: List[Node] = [_empty, _empty]
nextvals[cbits[0] ^ 1] = _empty
nextvals[cbits[0]] = self._make_middle(children, depth + 1)
return MiddleNode(nextvals)
def remove(self, toremove: bytes, depth: int) -> Node:
if toremove == self.hash:
return _empty
return self
def is_included(self, tocheck: bytes, depth: int, p: List[bytes]) -> bool:
p.append(TERMINAL + self.hash)
return tocheck == self.hash
def other_included(self, tocheck: bytes, depth: int, p: List[bytes], collapse: bool):
p.append(TERMINAL + self.hash)
def _audit(self, hashes: List[bytes], bits: List[int]):
hashes.append(self.hash)
for pos, v in enumerate(bits):
assert get_bit(self.hash, pos) == v
class MiddleNode(Node):
def __init__(self, children: List[Node]):
self.children = children
if children[0].is_empty() and children[1].is_double():
self.hash = children[1].hash
elif children[1].is_empty() and children[0].is_double():
self.hash = children[0].hash
else:
if children[0].is_empty() and (children[1].is_empty() or children[1].is_terminal()):
raise SetError()
if children[1].is_empty() and children[0].is_terminal():
raise SetError
if children[0].is_terminal() and children[1].is_terminal() and children[0].hash >= children[1].hash:
raise SetError
self.hash = hashdown(children[0].get_hash() + children[1].get_hash())
def get_hash(self) -> bytes:
return MIDDLE + self.hash
def is_empty(self) -> bool:
return False
def is_terminal(self) -> bool:
return False
def is_double(self) -> bool:
if self.children[0].is_empty():
return self.children[1].is_double()
if self.children[1].is_empty():
return self.children[0].is_double()
return self.children[0].is_terminal() and self.children[1].is_terminal()
def add(self, toadd: bytes, depth: int) -> Node:
bit = get_bit(toadd, depth)
child = self.children[bit]
newchild = child.add(toadd, depth + 1)
if newchild is child:
return self
newvals = [x for x in self.children]
newvals[bit] = newchild
return MiddleNode(newvals)
def remove(self, toremove: bytes, depth: int) -> Node:
bit = get_bit(toremove, depth)
child = self.children[bit]
newchild = child.remove(toremove, depth + 1)
if newchild is child:
return self
otherchild = self.children[bit ^ 1]
if newchild.is_empty() and otherchild.is_terminal():
return otherchild
if newchild.is_terminal() and otherchild.is_empty():
return newchild
newvals = [x for x in self.children]
newvals[bit] = newchild
return MiddleNode(newvals)
def is_included(self, tocheck: bytes, depth: int, p: List[bytes]) -> bool:
p.append(MIDDLE)
if get_bit(tocheck, depth) == 0:
r = self.children[0].is_included(tocheck, depth + 1, p)
self.children[1].other_included(tocheck, depth + 1, p, not self.children[0].is_empty())
return r
else:
self.children[0].other_included(tocheck, depth + 1, p, not self.children[1].is_empty())
return self.children[1].is_included(tocheck, depth + 1, p)
def other_included(self, tocheck: bytes, depth: int, p: List[bytes], collapse: bool):
if collapse or not self.is_double():
p.append(TRUNCATED + self.hash)
else:
self.is_included(tocheck, depth, p)
def _audit(self, hashes: List[bytes], bits: List[int]):
self.children[0]._audit(hashes, bits + [0])
self.children[1]._audit(hashes, bits + [1])
class TruncatedNode(Node):
def __init__(self, hash: bytes):
self.hash = hash
def get_hash(self) -> bytes:
return MIDDLE + self.hash
def is_empty(self) -> bool:
return False
def is_terminal(self) -> bool:
return False
def is_double(self) -> bool:
return False
def add(self, toadd: bytes, depth: int) -> Node:
return self
def remove(self, toremove: bytes, depth: int) -> Node:
return self
def is_included(self, tocheck: bytes, depth: int, p: List[bytes]) -> bool:
raise SetError()
def other_included(self, tocheck: bytes, depth: int, p: List[bytes], collapse: bool):
p.append(TRUNCATED + self.hash)
def _audit(self, hashes: List[bytes], bits: List[int]):
pass
class SetError(Exception):
pass
def confirm_included(root: Node, val: bytes, proof: bytes32) -> bool:
return confirm_not_included_already_hashed(root, sha256(val).digest(), proof)
def confirm_included_already_hashed(root: Node, val: bytes, proof: bytes) -> bool:
return _confirm(root, val, proof, True)
def confirm_not_included(root: Node, val: bytes, proof: bytes32) -> bool:
return confirm_not_included_already_hashed(root, sha256(val).digest(), proof)
def confirm_not_included_already_hashed(root: Node, val: bytes, proof: bytes) -> bool:
return _confirm(root, val, proof, False)
def _confirm(root: Node, val: bytes, proof: bytes, expected: bool) -> bool:
try:
p = deserialize_proof(proof)
if p.get_root() != root:
return False
r, junk = p.is_included_already_hashed(val)
return r == expected
except SetError:
return False
def deserialize_proof(proof: bytes) -> MerkleSet:
try:
r, pos = _deserialize(proof, 0, [])
if pos != len(proof):
raise SetError()
return MerkleSet(r)
except IndexError:
raise SetError()
def _deserialize(proof: bytes, pos: int, bits: List[int]) -> Tuple[Node, int]:
t = proof[pos : pos + 1]
if t == EMPTY:
return _empty, pos + 1
if t == TERMINAL:
return TerminalNode(proof[pos + 1 : pos + 33], bits), pos + 33
if t == TRUNCATED:
return TruncatedNode(proof[pos + 1 : pos + 33]), pos + 33
if t != MIDDLE:
raise SetError()
v0, pos = _deserialize(proof, pos + 1, bits + [0])
v1, pos = _deserialize(proof, pos, bits + [1])
return MiddleNode([v0, v1]), pos
| true | true |
f73151573f84138e26ebce007711c74837f84410 | 16,958 | py | Python | colour/characterisation/datasets/cameras/dslr/sensitivities.py | aurelienpierre/colour | 3ac45c12fbc0493e49ba4d4b2cb253df9fe14c47 | [
"BSD-3-Clause"
] | null | null | null | colour/characterisation/datasets/cameras/dslr/sensitivities.py | aurelienpierre/colour | 3ac45c12fbc0493e49ba4d4b2cb253df9fe14c47 | [
"BSD-3-Clause"
] | null | null | null | colour/characterisation/datasets/cameras/dslr/sensitivities.py | aurelienpierre/colour | 3ac45c12fbc0493e49ba4d4b2cb253df9fe14c47 | [
"BSD-3-Clause"
] | null | null | null | """
Sensitivities of *DSLR* Cameras
===============================
Defines the sensitivities of *DSLR* cameras.
Each *DSLR* camera data is in the form of a *dict* of
:class:`colour.characterisation.RGB_CameraSensitivities` classes as follows::
{
'name': RGB_CameraSensitivities,
...,
'name': RGB_CameraSensitivities
}
The following *DSLR* cameras are available:
- Nikon 5100 (NPL)
- Sigma SDMerill (NPL)
References
----------
- :cite:`Darrodi2015a` : Darrodi, M. M., Finlayson, G., Goodman, T., &
Mackiewicz, M. (2015). Reference data set for camera spectral sensitivity
estimation. Journal of the Optical Society of America A, 32(3), 381.
doi:10.1364/JOSAA.32.000381
"""
from __future__ import annotations
from functools import partial
from colour.characterisation import RGB_CameraSensitivities
from colour.hints import Dict
from colour.utilities import LazyCaseInsensitiveMapping
__author__ = "Colour Developers"
__copyright__ = "Copyright 2013 Colour Developers"
__license__ = "New BSD License - https://opensource.org/licenses/BSD-3-Clause"
__maintainer__ = "Colour Developers"
__email__ = "colour-developers@colour-science.org"
__status__ = "Production"
__all__ = [
"DATA_CAMERA_SENSITIVITIES_DSLR",
"MSDS_CAMERA_SENSITIVITIES_DSLR",
]
DATA_CAMERA_SENSITIVITIES_DSLR: Dict = {
"Nikon 5100 (NPL)": {
380.0: (
0.00156384299336578000,
0.00011500000000000000,
0.00180956039402335990,
),
385.0: (
0.00189691771384825000,
0.00152114360178015000,
0.00048982814544150399,
),
390.0: (
0.00000000000000000000,
0.00057430499183558695,
0.00087943069176996504,
),
395.0: (
0.00000000000000000000,
0.00000000000000000000,
0.00000000000000000000,
),
400.0: (
0.00000000000000000000,
0.00000000000000000000,
0.00153246068848051000,
),
405.0: (
0.00071776703300973298,
0.00119722386224553000,
0.00569805602282062030,
),
410.0: (
0.00292397466563330000,
0.00133571498448177000,
0.01660828769874150200,
),
415.0: (
0.01293626801713740000,
0.01319431696052810100,
0.07879120559214590500,
),
420.0: (
0.04959786481566520000,
0.06497102451249539600,
0.36171350364994898000,
),
425.0: (
0.07607250435970400200,
0.11510308718828900000,
0.65970462106512295000,
),
430.0: (
0.07658892708274399300,
0.13706582547087201000,
0.75534360010359503000,
),
435.0: (
0.06833381956036009600,
0.15242852584030600000,
0.81045312707380701000,
),
440.0: (
0.06131816189646559900,
0.16864005450745301000,
0.87494523362472998000,
),
445.0: (
0.05473314457789760200,
0.18329934605049600000,
0.92671273991178704000,
),
450.0: (
0.04886204743702320100,
0.19603263456229600000,
0.96314088025989897000,
),
455.0: (
0.04284591974257399800,
0.21733653278361301000,
0.98065048133510302000,
),
460.0: (
0.04022845332691499900,
0.25424357380995000000,
1.00000000000000000000,
),
465.0: (
0.04340795992263239700,
0.30864811930649899000,
0.99640467488711104000,
),
470.0: (
0.04762021431177430200,
0.37346871184252001000,
0.98896988650084305000,
),
475.0: (
0.05077188480559390000,
0.42915806139893697000,
0.95660139953157997000,
),
480.0: (
0.05280329597225499900,
0.45965432432137399000,
0.90495886986980800000,
),
485.0: (
0.05257122025495090300,
0.47106435446394301000,
0.83940927710351598000,
),
490.0: (
0.04789463902845950100,
0.48885616444524799000,
0.75146259578963404000,
),
495.0: (
0.04823994170483859900,
0.53715178104087602000,
0.66010202032260801000,
),
500.0: (
0.05022924089718029700,
0.61649118695883898000,
0.56706879193613802000,
),
505.0: (
0.05507649735001429700,
0.70700638759968903000,
0.47935094782603899000,
),
510.0: (
0.06370211901178619900,
0.80096424601366301000,
0.39406273870351299000,
),
515.0: (
0.08038951305895999900,
0.88137256686267296000,
0.31427061879449603000,
),
520.0: (
0.10038750399831201000,
0.93887792119838498000,
0.24981663439426000000,
),
525.0: (
0.11861314902313400000,
0.98446559576523596000,
0.20182351924718100000,
),
530.0: (
0.12360875120338000000,
1.00000000000000000000,
0.16163395085177601000,
),
535.0: (
0.10306249932787701000,
0.99084026557129701000,
0.13516143147333401000,
),
540.0: (
0.07634108360672720000,
0.96154626462922099000,
0.10998875716043301000,
),
545.0: (
0.05278086364640900000,
0.92814388346877297000,
0.08639435407789379500,
),
550.0: (
0.04118873831058649700,
0.88910231592076505000,
0.06525313059219839400,
),
555.0: (
0.03904385351931050100,
0.83494222924161199000,
0.04785595345227559900,
),
560.0: (
0.04254429440089119900,
0.77631807500187500000,
0.03413932303860940000,
),
565.0: (
0.06021313241068020100,
0.70731424532056497000,
0.02401990976851929900,
),
570.0: (
0.11179621705066800000,
0.63579620249170998000,
0.01976793598476750100,
),
575.0: (
0.26967059703276203000,
0.56551528450380395000,
0.01634844781073010000,
),
580.0: (
0.56450337990639099000,
0.49275517253522499000,
0.01381733937020259900,
),
585.0: (
0.85360126947261405000,
0.42475654159075799000,
0.01195294647966710000,
),
590.0: (
0.98103242181506201000,
0.35178931226078303000,
0.01000909395820090100,
),
595.0: (
1.00000000000000000000,
0.27817849879541801000,
0.00758776308929657970,
),
600.0: (
0.96307105371259005000,
0.21167353249961901000,
0.00645584463521649970,
),
605.0: (
0.90552061898043101000,
0.15671644549433000000,
0.00522978285684488030,
),
610.0: (
0.83427841652645296000,
0.11803962073050200000,
0.00365998459503786990,
),
615.0: (
0.76798733762510296000,
0.08885249534231440300,
0.00395538505488667040,
),
620.0: (
0.70366798041157996000,
0.07010184404853669900,
0.00396835221654468030,
),
625.0: (
0.63916484476123703000,
0.05690899470893220200,
0.00349138004486036990,
),
630.0: (
0.57081292173776299000,
0.04729879101895839700,
0.00404302103181797010,
),
635.0: (
0.49581796193158800000,
0.04119589002556579800,
0.00418929985295813000,
),
640.0: (
0.43833913452368101000,
0.03525207084991220000,
0.00554676856500057980,
),
645.0: (
0.38896992260406899000,
0.03069313144532450100,
0.00546423323547744030,
),
650.0: (
0.34295621205484700000,
0.02680396295683950100,
0.00597382847392098970,
),
655.0: (
0.29278541836293998000,
0.02352430119871520100,
0.00630906774763779000,
),
660.0: (
0.23770718073119301000,
0.02034633252474659900,
0.00610412697742267980,
),
665.0: (
0.16491386803178501000,
0.01545848325340879900,
0.00483655792375416000,
),
670.0: (
0.09128771706377150600,
0.00944075104617158980,
0.00302664794586984980,
),
675.0: (
0.04205615047283590300,
0.00508102204063505970,
0.00172169700987674990,
),
680.0: (
0.02058267877678380100,
0.00291019166901752010,
0.00078065128657817595,
),
685.0: (
0.01028680596369610000,
0.00162657557793382010,
0.00056963070848184102,
),
690.0: (
0.00540759846247261970,
0.00092251569139627796,
0.00027523296133938200,
),
695.0: (
0.00272409261591003000,
0.00049743349969026901,
0.00029672137857068598,
),
700.0: (
0.00127834798711079000,
0.00041215940263165701,
0.00024951192304202899,
),
705.0: (
0.00078123118374132301,
0.00031692634104666300,
8.5000000000000006e-05,
),
710.0: (
0.00047981421940270001,
0.00025621496960251102,
0.00041916895092770603,
),
715.0: (
0.00049133356428571098,
0.00000000000000000000,
0.00015331743444139899,
),
720.0: (
0.00017414897796340199,
0.00024353518865341200,
1.8300000000000001e-05,
),
725.0: (
0.00012017462571764001,
6.0200000000000000e-05,
0.00000000000000000000,
),
730.0: (
0.00000000000000000000,
0.00000000000000000000,
0.00033869381945204901,
),
735.0: (
6.1199999999999997e-05,
0.00000000000000000000,
0.00000000000000000000,
),
740.0: (
0.00000000000000000000,
0.00000000000000000000,
0.00000000000000000000,
),
745.0: (
0.00000000000000000000,
1.7099999999999999e-05,
0.00016527828734010200,
),
750.0: (
0.00031099754946016501,
5.2099999999999999e-05,
0.00017755262214537101,
),
755.0: (
0.00000000000000000000,
8.8499999999999996e-05,
0.00000000000000000000,
),
760.0: (
0.00000000000000000000,
0.00000000000000000000,
2.4300000000000001e-05,
),
765.0: (
0.00000000000000000000,
0.00000000000000000000,
6.1799999999999998e-05,
),
770.0: (
8.5599999999999994e-05,
0.00013799999999999999,
0.00026260703183506501,
),
775.0: (
0.00013831372865247499,
0.0001786501727059410,
0.00028050537004191899,
),
780.0: (
3.6199999999999999e-05,
4.2500000000000003e-05,
0.00000000000000000000,
),
},
"Sigma SDMerill (NPL)": {
400.0: (
0.00562107440608700020,
0.00632809751263116970,
0.16215942413307899000,
),
410.0: (
0.00650335624511722000,
0.00976180459591275040,
0.28549837804628603000,
),
420.0: (
0.07407911289140040000,
0.02527177008261050100,
0.39690431060902098000,
),
430.0: (
0.04302295946292879900,
0.08375118585311219800,
0.50831024317175599000,
),
440.0: (
0.03450952562247010200,
0.14370381974360999000,
0.62211847246948804000,
),
450.0: (
0.01889156723434350100,
0.18361168930882199000,
0.73742136245769496000,
),
460.0: (
0.00731107699680200000,
0.40909478009952999000,
0.94538036670138004000,
),
470.0: (
0.04549915123096019700,
0.51595564086176404000,
0.96441494770280400000,
),
480.0: (
0.05676752921111680200,
0.60120664662705503000,
1.00000000000000000000,
),
490.0: (
0.13419592065917799000,
0.67031679980136305000,
0.98598021188452500000,
),
500.0: (
0.16475268997837600000,
0.75258747153475802000,
0.98340266357529005000,
),
510.0: (
0.21712641978639199000,
0.84381384368944201000,
0.96969219567072595000,
),
520.0: (
0.30648343835824399000,
0.90151724558812696000,
0.94280817402079797000,
),
530.0: (
0.34984579614888500000,
0.91975030668767699000,
0.89664279918070899000,
),
540.0: (
0.44374258133259298000,
0.96799429052157804000,
0.88444590220041897000,
),
550.0: (
0.44488860528126301000,
0.95725231064041105000,
0.86791899071597101000,
),
560.0: (
0.47897575674702603000,
0.95204791860047400000,
0.83375679584908402000,
),
570.0: (
0.50950291481073895000,
0.97628014458399803000,
0.83204140240572999000,
),
580.0: (
0.59262909378530504000,
0.97258624388955806000,
0.80054956384778198000,
),
590.0: (
0.67383327560697603000,
1.00000000000000000000,
0.78289512474646505000,
),
600.0: (
0.71403771488106504000,
0.96948452757777404000,
0.73946953007191796000,
),
610.0: (
0.86000761311495100000,
0.95441319124850699000,
0.66718640174985699000,
),
620.0: (
0.89810302849565204000,
0.93335435890921303000,
0.62043627806816704000,
),
630.0: (
1.00000000000000000000,
0.92571406833636205000,
0.61116087876956704000,
),
640.0: (
0.99494213311245205000,
0.88486439541503403000,
0.55173556195710605000,
),
650.0: (
0.92085127736137995000,
0.76165184741615699000,
0.46538831744516401000,
),
660.0: (
0.18143311631425299000,
0.14052437057150499000,
0.07961907836720690000,
),
670.0: (
0.00630978795372749960,
0.00414367215817645990,
0.00059244446107236802,
),
680.0: (
0.00528874383171553000,
0.00183198958165669010,
0.00468563680483140980,
),
},
}
MSDS_CAMERA_SENSITIVITIES_DSLR = LazyCaseInsensitiveMapping(
{
"Nikon 5100 (NPL)": partial(
RGB_CameraSensitivities,
DATA_CAMERA_SENSITIVITIES_DSLR["Nikon 5100 (NPL)"],
name="Nikon 5100 (NPL)",
),
"Sigma SDMerill (NPL)": partial(
RGB_CameraSensitivities,
DATA_CAMERA_SENSITIVITIES_DSLR["Sigma SDMerill (NPL)"],
name="Sigma SDMerill (NPL)",
),
}
)
"""
Multi-spectral distributions of *DSLR* camera sensitivities.
References
----------
:cite:`Darrodi2015a`
"""
| 27.046252 | 78 | 0.513445 |
from __future__ import annotations
from functools import partial
from colour.characterisation import RGB_CameraSensitivities
from colour.hints import Dict
from colour.utilities import LazyCaseInsensitiveMapping
__author__ = "Colour Developers"
__copyright__ = "Copyright 2013 Colour Developers"
__license__ = "New BSD License - https://opensource.org/licenses/BSD-3-Clause"
__maintainer__ = "Colour Developers"
__email__ = "colour-developers@colour-science.org"
__status__ = "Production"
__all__ = [
"DATA_CAMERA_SENSITIVITIES_DSLR",
"MSDS_CAMERA_SENSITIVITIES_DSLR",
]
DATA_CAMERA_SENSITIVITIES_DSLR: Dict = {
"Nikon 5100 (NPL)": {
380.0: (
0.00156384299336578000,
0.00011500000000000000,
0.00180956039402335990,
),
385.0: (
0.00189691771384825000,
0.00152114360178015000,
0.00048982814544150399,
),
390.0: (
0.00000000000000000000,
0.00057430499183558695,
0.00087943069176996504,
),
395.0: (
0.00000000000000000000,
0.00000000000000000000,
0.00000000000000000000,
),
400.0: (
0.00000000000000000000,
0.00000000000000000000,
0.00153246068848051000,
),
405.0: (
0.00071776703300973298,
0.00119722386224553000,
0.00569805602282062030,
),
410.0: (
0.00292397466563330000,
0.00133571498448177000,
0.01660828769874150200,
),
415.0: (
0.01293626801713740000,
0.01319431696052810100,
0.07879120559214590500,
),
420.0: (
0.04959786481566520000,
0.06497102451249539600,
0.36171350364994898000,
),
425.0: (
0.07607250435970400200,
0.11510308718828900000,
0.65970462106512295000,
),
430.0: (
0.07658892708274399300,
0.13706582547087201000,
0.75534360010359503000,
),
435.0: (
0.06833381956036009600,
0.15242852584030600000,
0.81045312707380701000,
),
440.0: (
0.06131816189646559900,
0.16864005450745301000,
0.87494523362472998000,
),
445.0: (
0.05473314457789760200,
0.18329934605049600000,
0.92671273991178704000,
),
450.0: (
0.04886204743702320100,
0.19603263456229600000,
0.96314088025989897000,
),
455.0: (
0.04284591974257399800,
0.21733653278361301000,
0.98065048133510302000,
),
460.0: (
0.04022845332691499900,
0.25424357380995000000,
1.00000000000000000000,
),
465.0: (
0.04340795992263239700,
0.30864811930649899000,
0.99640467488711104000,
),
470.0: (
0.04762021431177430200,
0.37346871184252001000,
0.98896988650084305000,
),
475.0: (
0.05077188480559390000,
0.42915806139893697000,
0.95660139953157997000,
),
480.0: (
0.05280329597225499900,
0.45965432432137399000,
0.90495886986980800000,
),
485.0: (
0.05257122025495090300,
0.47106435446394301000,
0.83940927710351598000,
),
490.0: (
0.04789463902845950100,
0.48885616444524799000,
0.75146259578963404000,
),
495.0: (
0.04823994170483859900,
0.53715178104087602000,
0.66010202032260801000,
),
500.0: (
0.05022924089718029700,
0.61649118695883898000,
0.56706879193613802000,
),
505.0: (
0.05507649735001429700,
0.70700638759968903000,
0.47935094782603899000,
),
510.0: (
0.06370211901178619900,
0.80096424601366301000,
0.39406273870351299000,
),
515.0: (
0.08038951305895999900,
0.88137256686267296000,
0.31427061879449603000,
),
520.0: (
0.10038750399831201000,
0.93887792119838498000,
0.24981663439426000000,
),
525.0: (
0.11861314902313400000,
0.98446559576523596000,
0.20182351924718100000,
),
530.0: (
0.12360875120338000000,
1.00000000000000000000,
0.16163395085177601000,
),
535.0: (
0.10306249932787701000,
0.99084026557129701000,
0.13516143147333401000,
),
540.0: (
0.07634108360672720000,
0.96154626462922099000,
0.10998875716043301000,
),
545.0: (
0.05278086364640900000,
0.92814388346877297000,
0.08639435407789379500,
),
550.0: (
0.04118873831058649700,
0.88910231592076505000,
0.06525313059219839400,
),
555.0: (
0.03904385351931050100,
0.83494222924161199000,
0.04785595345227559900,
),
560.0: (
0.04254429440089119900,
0.77631807500187500000,
0.03413932303860940000,
),
565.0: (
0.06021313241068020100,
0.70731424532056497000,
0.02401990976851929900,
),
570.0: (
0.11179621705066800000,
0.63579620249170998000,
0.01976793598476750100,
),
575.0: (
0.26967059703276203000,
0.56551528450380395000,
0.01634844781073010000,
),
580.0: (
0.56450337990639099000,
0.49275517253522499000,
0.01381733937020259900,
),
585.0: (
0.85360126947261405000,
0.42475654159075799000,
0.01195294647966710000,
),
590.0: (
0.98103242181506201000,
0.35178931226078303000,
0.01000909395820090100,
),
595.0: (
1.00000000000000000000,
0.27817849879541801000,
0.00758776308929657970,
),
600.0: (
0.96307105371259005000,
0.21167353249961901000,
0.00645584463521649970,
),
605.0: (
0.90552061898043101000,
0.15671644549433000000,
0.00522978285684488030,
),
610.0: (
0.83427841652645296000,
0.11803962073050200000,
0.00365998459503786990,
),
615.0: (
0.76798733762510296000,
0.08885249534231440300,
0.00395538505488667040,
),
620.0: (
0.70366798041157996000,
0.07010184404853669900,
0.00396835221654468030,
),
625.0: (
0.63916484476123703000,
0.05690899470893220200,
0.00349138004486036990,
),
630.0: (
0.57081292173776299000,
0.04729879101895839700,
0.00404302103181797010,
),
635.0: (
0.49581796193158800000,
0.04119589002556579800,
0.00418929985295813000,
),
640.0: (
0.43833913452368101000,
0.03525207084991220000,
0.00554676856500057980,
),
645.0: (
0.38896992260406899000,
0.03069313144532450100,
0.00546423323547744030,
),
650.0: (
0.34295621205484700000,
0.02680396295683950100,
0.00597382847392098970,
),
655.0: (
0.29278541836293998000,
0.02352430119871520100,
0.00630906774763779000,
),
660.0: (
0.23770718073119301000,
0.02034633252474659900,
0.00610412697742267980,
),
665.0: (
0.16491386803178501000,
0.01545848325340879900,
0.00483655792375416000,
),
670.0: (
0.09128771706377150600,
0.00944075104617158980,
0.00302664794586984980,
),
675.0: (
0.04205615047283590300,
0.00508102204063505970,
0.00172169700987674990,
),
680.0: (
0.02058267877678380100,
0.00291019166901752010,
0.00078065128657817595,
),
685.0: (
0.01028680596369610000,
0.00162657557793382010,
0.00056963070848184102,
),
690.0: (
0.00540759846247261970,
0.00092251569139627796,
0.00027523296133938200,
),
695.0: (
0.00272409261591003000,
0.00049743349969026901,
0.00029672137857068598,
),
700.0: (
0.00127834798711079000,
0.00041215940263165701,
0.00024951192304202899,
),
705.0: (
0.00078123118374132301,
0.00031692634104666300,
8.5000000000000006e-05,
),
710.0: (
0.00047981421940270001,
0.00025621496960251102,
0.00041916895092770603,
),
715.0: (
0.00049133356428571098,
0.00000000000000000000,
0.00015331743444139899,
),
720.0: (
0.00017414897796340199,
0.00024353518865341200,
1.8300000000000001e-05,
),
725.0: (
0.00012017462571764001,
6.0200000000000000e-05,
0.00000000000000000000,
),
730.0: (
0.00000000000000000000,
0.00000000000000000000,
0.00033869381945204901,
),
735.0: (
6.1199999999999997e-05,
0.00000000000000000000,
0.00000000000000000000,
),
740.0: (
0.00000000000000000000,
0.00000000000000000000,
0.00000000000000000000,
),
745.0: (
0.00000000000000000000,
1.7099999999999999e-05,
0.00016527828734010200,
),
750.0: (
0.00031099754946016501,
5.2099999999999999e-05,
0.00017755262214537101,
),
755.0: (
0.00000000000000000000,
8.8499999999999996e-05,
0.00000000000000000000,
),
760.0: (
0.00000000000000000000,
0.00000000000000000000,
2.4300000000000001e-05,
),
765.0: (
0.00000000000000000000,
0.00000000000000000000,
6.1799999999999998e-05,
),
770.0: (
8.5599999999999994e-05,
0.00013799999999999999,
0.00026260703183506501,
),
775.0: (
0.00013831372865247499,
0.0001786501727059410,
0.00028050537004191899,
),
780.0: (
3.6199999999999999e-05,
4.2500000000000003e-05,
0.00000000000000000000,
),
},
"Sigma SDMerill (NPL)": {
400.0: (
0.00562107440608700020,
0.00632809751263116970,
0.16215942413307899000,
),
410.0: (
0.00650335624511722000,
0.00976180459591275040,
0.28549837804628603000,
),
420.0: (
0.07407911289140040000,
0.02527177008261050100,
0.39690431060902098000,
),
430.0: (
0.04302295946292879900,
0.08375118585311219800,
0.50831024317175599000,
),
440.0: (
0.03450952562247010200,
0.14370381974360999000,
0.62211847246948804000,
),
450.0: (
0.01889156723434350100,
0.18361168930882199000,
0.73742136245769496000,
),
460.0: (
0.00731107699680200000,
0.40909478009952999000,
0.94538036670138004000,
),
470.0: (
0.04549915123096019700,
0.51595564086176404000,
0.96441494770280400000,
),
480.0: (
0.05676752921111680200,
0.60120664662705503000,
1.00000000000000000000,
),
490.0: (
0.13419592065917799000,
0.67031679980136305000,
0.98598021188452500000,
),
500.0: (
0.16475268997837600000,
0.75258747153475802000,
0.98340266357529005000,
),
510.0: (
0.21712641978639199000,
0.84381384368944201000,
0.96969219567072595000,
),
520.0: (
0.30648343835824399000,
0.90151724558812696000,
0.94280817402079797000,
),
530.0: (
0.34984579614888500000,
0.91975030668767699000,
0.89664279918070899000,
),
540.0: (
0.44374258133259298000,
0.96799429052157804000,
0.88444590220041897000,
),
550.0: (
0.44488860528126301000,
0.95725231064041105000,
0.86791899071597101000,
),
560.0: (
0.47897575674702603000,
0.95204791860047400000,
0.83375679584908402000,
),
570.0: (
0.50950291481073895000,
0.97628014458399803000,
0.83204140240572999000,
),
580.0: (
0.59262909378530504000,
0.97258624388955806000,
0.80054956384778198000,
),
590.0: (
0.67383327560697603000,
1.00000000000000000000,
0.78289512474646505000,
),
600.0: (
0.71403771488106504000,
0.96948452757777404000,
0.73946953007191796000,
),
610.0: (
0.86000761311495100000,
0.95441319124850699000,
0.66718640174985699000,
),
620.0: (
0.89810302849565204000,
0.93335435890921303000,
0.62043627806816704000,
),
630.0: (
1.00000000000000000000,
0.92571406833636205000,
0.61116087876956704000,
),
640.0: (
0.99494213311245205000,
0.88486439541503403000,
0.55173556195710605000,
),
650.0: (
0.92085127736137995000,
0.76165184741615699000,
0.46538831744516401000,
),
660.0: (
0.18143311631425299000,
0.14052437057150499000,
0.07961907836720690000,
),
670.0: (
0.00630978795372749960,
0.00414367215817645990,
0.00059244446107236802,
),
680.0: (
0.00528874383171553000,
0.00183198958165669010,
0.00468563680483140980,
),
},
}
MSDS_CAMERA_SENSITIVITIES_DSLR = LazyCaseInsensitiveMapping(
{
"Nikon 5100 (NPL)": partial(
RGB_CameraSensitivities,
DATA_CAMERA_SENSITIVITIES_DSLR["Nikon 5100 (NPL)"],
name="Nikon 5100 (NPL)",
),
"Sigma SDMerill (NPL)": partial(
RGB_CameraSensitivities,
DATA_CAMERA_SENSITIVITIES_DSLR["Sigma SDMerill (NPL)"],
name="Sigma SDMerill (NPL)",
),
}
)
| true | true |
f731522e9661ea03a15b6c0891cbf1369590cc3e | 5,128 | py | Python | youtubeto/raindrop.py | Perlence/youtube-to | b0183719f3c40825f7fab520294bd55574fde581 | [
"BSD-3-Clause"
] | 1 | 2021-06-18T22:34:00.000Z | 2021-06-18T22:34:00.000Z | youtubeto/raindrop.py | Perlence/youtube-to | b0183719f3c40825f7fab520294bd55574fde581 | [
"BSD-3-Clause"
] | null | null | null | youtubeto/raindrop.py | Perlence/youtube-to | b0183719f3c40825f7fab520294bd55574fde581 | [
"BSD-3-Clause"
] | null | null | null | from __future__ import absolute_import
from gevent import monkey
monkey.patch_all(thread=False, select=False)
import json
import arrow
from apiclient.discovery import build
from gevent.pool import Pool
from httplib2 import Http
from logbook import Logger
from oauth2client import client
from . import config
logger = Logger('youtubeto.raindrop')
class Raindrop(object):
path = 'https://raindrop.io/api/'
def __init__(self, session_id=None):
self.session_id = session_id
def _request(self, uri, method='GET', body=None, headers=None, **kwargs):
uri = self.path + uri
if headers is None:
headers = {}
if body is not None:
body = json.dumps(body)
headers['Content-Type'] = 'application/json; charset=UTF-8'
if self.session_id is not None:
headers['Cookie'] = 'connect.sid=' + self.session_id
_, content = Http().request(uri, method, body, headers, **kwargs)
return json.loads(content)
def get(self, uri):
return self._request(uri, 'GET')
def create(self, uri, **params):
return self._request(uri, 'POST', params)
def delete(self, uri):
return self._request(uri, 'DELETE')
def update(self, uri, **params):
return self._request(uri, 'PUT', params)
def main():
if config.YOUTUBE_TOKEN_EXPIRY:
youtube_token_expiry = arrow.get(config.YOUTUBE_TOKEN_EXPIRY)
else:
youtube_token_expiry = None
if config.YOUTUBE_REFRESH_TOKEN:
creds = client.OAuth2Credentials(
config.YOUTUBE_ACCESS_TOKEN, config.YOUTUBE_CLIENT_ID,
config.YOUTUBE_CLIENT_SECRET, config.YOUTUBE_REFRESH_TOKEN,
youtube_token_expiry, config.YOUTUBE_TOKEN_URI,
config.YOUTUBE_USER_AGENT)
if youtube_token_expiry <= arrow.get():
creds.refresh(Http())
config.YOUTUBE_ACCESS_TOKEN = creds.access_token
config.YOUTUBE_TOKEN_EXPIRY = creds.token_expiry.isoformat()
config.save()
else:
import webbrowser
flow = client.OAuth2WebServerFlow(
config.YOUTUBE_CLIENT_ID,
config.YOUTUBE_CLIENT_SECRET,
config.YOUTUBE_SCOPE,
config.YOUTUBE_REDIRECT_URI)
webbrowser.open(flow.step1_get_authorize_url())
code = raw_input('Input code: ')
creds = flow.step2_exchange(code)
config.YOUTUBE_ACCESS_TOKEN = creds.access_token
config.YOUTUBE_CLIENT_ID = creds.client_id
config.YOUTUBE_CLIENT_SECRET = creds.client_secret
config.YOUTUBE_REFRESH_TOKEN = creds.refresh_token
config.YOUTUBE_TOKEN_EXPIRY = creds.token_expiry.isoformat()
config.YOUTUBE_TOKEN_URI = creds.token_uri
config.YOUTUBE_USER_AGENT = creds.user_agent
config.save()
http = authorized_http(creds)
youtube = build('youtube', 'v3', http=http())
if not config.RAINDROP_SESSION_ID:
import webbrowser
webbrowser.open('https://raindrop.io/account/signin')
config.RAINDROP_SESSION_ID = raw_input('Input session id: ')
config.save()
raindrop = Raindrop(config.RAINDROP_SESSION_ID)
playlists = youtube.playlists().list(part='snippet', mine=True).execute()
favorites = next((item for item in playlists['items']
if item['snippet']['title'] == 'Favorites'), None)
req = youtube.playlistItems().list(part='snippet',
playlistId=favorites['id'])
pool = Pool()
while req:
res = req.execute()
for item in res['items']:
pool.spawn(put_in_raindrop, youtube, http, raindrop, item)
pool.join()
req = youtube.playlistItems().list_next(req, res)
def authorized_http(creds):
return lambda: creds.authorize(Http())
def put_in_raindrop(youtube, http, raindrop, item):
logger.info('Adding bookmark for {snippet[title]}', **item)
collection_id = config.RAINDROP_COLLECTION_ID
req = youtube.videos().list(part='snippet',
id=item['snippet']['resourceId']['videoId'])
video = req.execute(http())['items'][0]
url = ('http://www.youtube.com/watch'
'?v={resourceId[videoId]}'
'&list={playlistId}'
.format(**item['snippet']))
title = u'{title} by {channelTitle}'.format(**video['snippet'])
result = raindrop.create(
'raindrop',
collectionId=collection_id,
cover=0,
coverEnabled=True,
drop=False,
excerpt=video['snippet']['description'],
haveScreenshot=False,
media=[{
'link': get_biggest_thumbnail(item),
'type': 'image'
}],
tags=[],
title=title,
url=url)
logger.info('Added bookmark for {snippet[title]}', **item)
def get_biggest_thumbnail(item):
for thumbnail in ('maxres', 'standard', 'high', 'medium', 'default'):
result = item['snippet']['thumbnails'].get(thumbnail)
if result is not None:
return result['url']
if __name__ == '__main__':
main()
| 33.736842 | 77 | 0.633385 | from __future__ import absolute_import
from gevent import monkey
monkey.patch_all(thread=False, select=False)
import json
import arrow
from apiclient.discovery import build
from gevent.pool import Pool
from httplib2 import Http
from logbook import Logger
from oauth2client import client
from . import config
logger = Logger('youtubeto.raindrop')
class Raindrop(object):
path = 'https://raindrop.io/api/'
def __init__(self, session_id=None):
self.session_id = session_id
def _request(self, uri, method='GET', body=None, headers=None, **kwargs):
uri = self.path + uri
if headers is None:
headers = {}
if body is not None:
body = json.dumps(body)
headers['Content-Type'] = 'application/json; charset=UTF-8'
if self.session_id is not None:
headers['Cookie'] = 'connect.sid=' + self.session_id
_, content = Http().request(uri, method, body, headers, **kwargs)
return json.loads(content)
def get(self, uri):
return self._request(uri, 'GET')
def create(self, uri, **params):
return self._request(uri, 'POST', params)
def delete(self, uri):
return self._request(uri, 'DELETE')
def update(self, uri, **params):
return self._request(uri, 'PUT', params)
def main():
if config.YOUTUBE_TOKEN_EXPIRY:
youtube_token_expiry = arrow.get(config.YOUTUBE_TOKEN_EXPIRY)
else:
youtube_token_expiry = None
if config.YOUTUBE_REFRESH_TOKEN:
creds = client.OAuth2Credentials(
config.YOUTUBE_ACCESS_TOKEN, config.YOUTUBE_CLIENT_ID,
config.YOUTUBE_CLIENT_SECRET, config.YOUTUBE_REFRESH_TOKEN,
youtube_token_expiry, config.YOUTUBE_TOKEN_URI,
config.YOUTUBE_USER_AGENT)
if youtube_token_expiry <= arrow.get():
creds.refresh(Http())
config.YOUTUBE_ACCESS_TOKEN = creds.access_token
config.YOUTUBE_TOKEN_EXPIRY = creds.token_expiry.isoformat()
config.save()
else:
import webbrowser
flow = client.OAuth2WebServerFlow(
config.YOUTUBE_CLIENT_ID,
config.YOUTUBE_CLIENT_SECRET,
config.YOUTUBE_SCOPE,
config.YOUTUBE_REDIRECT_URI)
webbrowser.open(flow.step1_get_authorize_url())
code = raw_input('Input code: ')
creds = flow.step2_exchange(code)
config.YOUTUBE_ACCESS_TOKEN = creds.access_token
config.YOUTUBE_CLIENT_ID = creds.client_id
config.YOUTUBE_CLIENT_SECRET = creds.client_secret
config.YOUTUBE_REFRESH_TOKEN = creds.refresh_token
config.YOUTUBE_TOKEN_EXPIRY = creds.token_expiry.isoformat()
config.YOUTUBE_TOKEN_URI = creds.token_uri
config.YOUTUBE_USER_AGENT = creds.user_agent
config.save()
http = authorized_http(creds)
youtube = build('youtube', 'v3', http=http())
if not config.RAINDROP_SESSION_ID:
import webbrowser
webbrowser.open('https://raindrop.io/account/signin')
config.RAINDROP_SESSION_ID = raw_input('Input session id: ')
config.save()
raindrop = Raindrop(config.RAINDROP_SESSION_ID)
playlists = youtube.playlists().list(part='snippet', mine=True).execute()
favorites = next((item for item in playlists['items']
if item['snippet']['title'] == 'Favorites'), None)
req = youtube.playlistItems().list(part='snippet',
playlistId=favorites['id'])
pool = Pool()
while req:
res = req.execute()
for item in res['items']:
pool.spawn(put_in_raindrop, youtube, http, raindrop, item)
pool.join()
req = youtube.playlistItems().list_next(req, res)
def authorized_http(creds):
return lambda: creds.authorize(Http())
def put_in_raindrop(youtube, http, raindrop, item):
logger.info('Adding bookmark for {snippet[title]}', **item)
collection_id = config.RAINDROP_COLLECTION_ID
req = youtube.videos().list(part='snippet',
id=item['snippet']['resourceId']['videoId'])
video = req.execute(http())['items'][0]
url = ('http://www.youtube.com/watch'
'?v={resourceId[videoId]}'
'&list={playlistId}'
.format(**item['snippet']))
title = u'{title} by {channelTitle}'.format(**video['snippet'])
result = raindrop.create(
'raindrop',
collectionId=collection_id,
cover=0,
coverEnabled=True,
drop=False,
excerpt=video['snippet']['description'],
haveScreenshot=False,
media=[{
'link': get_biggest_thumbnail(item),
'type': 'image'
}],
tags=[],
title=title,
url=url)
logger.info('Added bookmark for {snippet[title]}', **item)
def get_biggest_thumbnail(item):
for thumbnail in ('maxres', 'standard', 'high', 'medium', 'default'):
result = item['snippet']['thumbnails'].get(thumbnail)
if result is not None:
return result['url']
if __name__ == '__main__':
main()
| true | true |
f731523ad4d8e5ca45ea9d3c2e855ab60f507b2e | 31 | py | Python | nso_restconf/__init__.py | rtrjl/nso_restconf | f5b8aa1cd857bf79732273c51f8dc6df13df030f | [
"BSD-Source-Code"
] | 1 | 2022-02-04T13:44:49.000Z | 2022-02-04T13:44:49.000Z | nso_restconf/__init__.py | rtrjl/nso_restconf | f5b8aa1cd857bf79732273c51f8dc6df13df030f | [
"BSD-Source-Code"
] | null | null | null | nso_restconf/__init__.py | rtrjl/nso_restconf | f5b8aa1cd857bf79732273c51f8dc6df13df030f | [
"BSD-Source-Code"
] | null | null | null | from .restconf import RestConf
| 15.5 | 30 | 0.83871 | from .restconf import RestConf
| true | true |
f73152526fda44eeae7cc9b1ebdfc4befe32c01d | 13,312 | py | Python | tests/integration/cloud/helpers/cloud_test_base.py | HudsonWu/mysalt | 8ce2f66e0d0338157923f0ea0dab912a0f43e52e | [
"Apache-2.0"
] | null | null | null | tests/integration/cloud/helpers/cloud_test_base.py | HudsonWu/mysalt | 8ce2f66e0d0338157923f0ea0dab912a0f43e52e | [
"Apache-2.0"
] | null | null | null | tests/integration/cloud/helpers/cloud_test_base.py | HudsonWu/mysalt | 8ce2f66e0d0338157923f0ea0dab912a0f43e52e | [
"Apache-2.0"
] | null | null | null | """
Tests for the Openstack Cloud Provider
"""
import logging
import os
import shutil
from time import sleep
import salt.utils.verify
from salt.config import cloud_config, cloud_providers_config
from salt.ext.six.moves import range
from salt.utils.yaml import safe_load
from tests.support.case import ShellCase
from tests.support.helpers import expensiveTest, random_string
from tests.support.paths import FILES
from tests.support.runtests import RUNTIME_VARS
TIMEOUT = 500
log = logging.getLogger(__name__)
@expensiveTest
class CloudTest(ShellCase):
PROVIDER = ""
REQUIRED_PROVIDER_CONFIG_ITEMS = tuple()
__RE_RUN_DELAY = 30
__RE_TRIES = 12
@staticmethod
def clean_cloud_dir(tmp_dir):
"""
Clean the cloud.providers.d tmp directory
"""
# make sure old provider configs are deleted
if not os.path.isdir(tmp_dir):
return
for fname in os.listdir(tmp_dir):
os.remove(os.path.join(tmp_dir, fname))
def query_instances(self):
"""
Standardize the data returned from a salt-cloud --query
"""
return {
x.strip(": ")
for x in self.run_cloud("--query")
if x.lstrip().lower().startswith("cloud-test-")
}
def _instance_exists(self, instance_name=None, query=None):
"""
:param instance_name: The name of the instance to check for in salt-cloud.
For example this is may used when a test temporarily renames an instance
:param query: The result of a salt-cloud --query run outside of this function
"""
if not instance_name:
instance_name = self.instance_name
if not query:
query = self.query_instances()
log.debug('Checking for "{}" in {}'.format(instance_name, query))
if isinstance(query, set):
return instance_name in query
return any(instance_name == q.strip(": ") for q in query)
def assertInstanceExists(self, creation_ret=None, instance_name=None):
"""
:param instance_name: Override the checked instance name, otherwise the class default will be used.
:param creation_ret: The return value from the run_cloud() function that created the instance
"""
if not instance_name:
instance_name = self.instance_name
# If it exists but doesn't show up in the creation_ret, there was probably an error during creation
if creation_ret:
self.assertIn(
instance_name,
[i.strip(": ") for i in creation_ret],
"An error occured during instance creation: |\n\t{}\n\t|".format(
"\n\t".join(creation_ret)
),
)
else:
# Verify that the instance exists via query
query = self.query_instances()
for tries in range(self.__RE_TRIES):
if self._instance_exists(instance_name, query):
log.debug(
'Instance "{}" reported after {} seconds'.format(
instance_name, tries * self.__RE_RUN_DELAY
)
)
break
else:
sleep(self.__RE_RUN_DELAY)
query = self.query_instances()
# Assert that the last query was successful
self.assertTrue(
self._instance_exists(instance_name, query),
'Instance "{}" was not created successfully: {}'.format(
self.instance_name, ", ".join(query)
),
)
log.debug('Instance exists and was created: "{}"'.format(instance_name))
def assertDestroyInstance(self, instance_name=None, timeout=None):
if timeout is None:
timeout = TIMEOUT
if not instance_name:
instance_name = self.instance_name
log.debug('Deleting instance "{}"'.format(instance_name))
delete_str = self.run_cloud(
"-d {} --assume-yes --out=yaml".format(instance_name), timeout=timeout
)
if delete_str:
delete = safe_load("\n".join(delete_str))
self.assertIn(self.profile_str, delete)
self.assertIn(self.PROVIDER, delete[self.profile_str])
self.assertIn(instance_name, delete[self.profile_str][self.PROVIDER])
delete_status = delete[self.profile_str][self.PROVIDER][instance_name]
if isinstance(delete_status, str):
self.assertEqual(delete_status, "True")
return
elif isinstance(delete_status, dict):
current_state = delete_status.get("currentState")
if current_state:
if current_state.get("ACTION"):
self.assertIn(".delete", current_state.get("ACTION"))
return
else:
self.assertEqual(current_state.get("name"), "shutting-down")
return
# It's not clear from the delete string that deletion was successful, ask salt-cloud after a delay
query = self.query_instances()
# some instances take a while to report their destruction
for tries in range(6):
if self._instance_exists(query=query):
sleep(30)
log.debug(
'Instance "{}" still found in query after {} tries: {}'.format(
instance_name, tries, query
)
)
query = self.query_instances()
# The last query should have been successful
self.assertNotIn(instance_name, self.query_instances())
@property
def instance_name(self):
if not hasattr(self, "_instance_name"):
# Create the cloud instance name to be used throughout the tests
subclass = self.__class__.__name__.strip("Test")
# Use the first three letters of the subclass, fill with '-' if too short
self._instance_name = random_string(
"cloud-test-{:-<3}-".format(subclass[:3]), uppercase=False
).lower()
return self._instance_name
@property
def providers(self):
if not hasattr(self, "_providers"):
self._providers = self.run_cloud("--list-providers")
return self._providers
@property
def provider_config(self):
if not hasattr(self, "_provider_config"):
self._provider_config = cloud_providers_config(
os.path.join(
RUNTIME_VARS.TMP_CONF_DIR,
"cloud.providers.d",
self.PROVIDER + ".conf",
)
)
return self._provider_config[self.profile_str][self.PROVIDER]
@property
def config(self):
if not hasattr(self, "_config"):
self._config = cloud_config(
os.path.join(
RUNTIME_VARS.TMP_CONF_DIR,
"cloud.profiles.d",
self.PROVIDER + ".conf",
)
)
return self._config
@property
def profile_str(self):
return self.PROVIDER + "-config"
def add_profile_config(self, name, data, conf, new_profile):
"""
copy the current profile and add a new profile in the same file
"""
conf_path = os.path.join(RUNTIME_VARS.TMP_CONF_DIR, "cloud.profiles.d", conf)
with salt.utils.files.fopen(conf_path, "r") as fp:
conf = safe_load(fp)
conf[new_profile] = conf[name].copy()
conf[new_profile].update(data)
with salt.utils.files.fopen(conf_path, "w") as fp:
salt.utils.yaml.safe_dump(conf, fp)
def setUp(self):
"""
Sets up the test requirements. In child classes, define PROVIDER and REQUIRED_PROVIDER_CONFIG_ITEMS or this will fail
"""
super().setUp()
if not self.PROVIDER:
self.fail("A PROVIDER must be defined for this test")
# check if appropriate cloud provider and profile files are present
if self.profile_str + ":" not in self.providers:
self.skipTest(
"Configuration file for {0} was not found. Check {0}.conf files "
"in tests/integration/files/conf/cloud.*.d/ to run these tests.".format(
self.PROVIDER
)
)
missing_conf_item = []
for att in self.REQUIRED_PROVIDER_CONFIG_ITEMS:
if not self.provider_config.get(att):
missing_conf_item.append(att)
if missing_conf_item:
self.skipTest(
"Conf items are missing that must be provided to run these tests: {}".format(
", ".join(missing_conf_item)
)
+ "\nCheck tests/integration/files/conf/cloud.providers.d/{}.conf".format(
self.PROVIDER
)
)
def _alt_names(self):
"""
Check for an instances created alongside this test's instance that weren't cleaned up
"""
query = self.query_instances()
instances = set()
for q in query:
# Verify but this is a new name and not a shutting down ec2 instance
if q.startswith(self.instance_name) and not q.split("-")[-1].startswith(
"DEL"
):
instances.add(q)
log.debug(
'Adding "{}" to the set of instances that needs to be deleted'.format(
q
)
)
return instances
def _ensure_deletion(self, instance_name=None):
"""
Make sure that the instance absolutely gets deleted, but fail the test if it happens in the tearDown
:return True if an instance was deleted, False if no instance was deleted; and a message
"""
destroyed = False
if not instance_name:
instance_name = self.instance_name
if self._instance_exists(instance_name):
for tries in range(3):
try:
self.assertDestroyInstance(instance_name)
return (
False,
'The instance "{}" was deleted during the tearDown, not the test.'.format(
instance_name
),
)
except AssertionError as e:
log.error(
'Failed to delete instance "{}". Tries: {}\n{}'.format(
instance_name, tries, str(e)
)
)
if not self._instance_exists():
destroyed = True
break
else:
sleep(30)
if not destroyed:
# Destroying instances in the tearDown is a contingency, not the way things should work by default.
return (
False,
'The Instance "{}" was not deleted after multiple attempts'.format(
instance_name
),
)
return (
True,
'The instance "{}" cleaned up properly after the test'.format(
instance_name
),
)
def tearDown(self):
"""
Clean up after tests, If the instance still exists for any reason, delete it.
Instances should be destroyed before the tearDown, assertDestroyInstance() should be called exactly
one time in a test for each instance created. This is a failSafe and something went wrong
if the tearDown is where an instance is destroyed.
"""
success = True
fail_messages = []
alt_names = self._alt_names()
for instance in alt_names:
alt_destroyed, alt_destroy_message = self._ensure_deletion(instance)
if not alt_destroyed:
success = False
fail_messages.append(alt_destroy_message)
log.error(
'Failed to destroy instance "{}": {}'.format(
instance, alt_destroy_message
)
)
self.assertTrue(success, "\n".join(fail_messages))
self.assertFalse(
alt_names, "Cleanup should happen in the test, not the TearDown"
)
@classmethod
def tearDownClass(cls):
cls.clean_cloud_dir(cls.tmp_provider_dir)
@classmethod
def setUpClass(cls):
# clean up before setup
cls.tmp_provider_dir = os.path.join(
RUNTIME_VARS.TMP_CONF_DIR, "cloud.providers.d"
)
cls.clean_cloud_dir(cls.tmp_provider_dir)
# add the provider config for only the cloud we are testing
provider_file = cls.PROVIDER + ".conf"
shutil.copyfile(
os.path.join(
os.path.join(FILES, "conf", "cloud.providers.d"), provider_file
),
os.path.join(os.path.join(cls.tmp_provider_dir, provider_file)),
)
| 37.498592 | 126 | 0.558293 |
import logging
import os
import shutil
from time import sleep
import salt.utils.verify
from salt.config import cloud_config, cloud_providers_config
from salt.ext.six.moves import range
from salt.utils.yaml import safe_load
from tests.support.case import ShellCase
from tests.support.helpers import expensiveTest, random_string
from tests.support.paths import FILES
from tests.support.runtests import RUNTIME_VARS
TIMEOUT = 500
log = logging.getLogger(__name__)
@expensiveTest
class CloudTest(ShellCase):
PROVIDER = ""
REQUIRED_PROVIDER_CONFIG_ITEMS = tuple()
__RE_RUN_DELAY = 30
__RE_TRIES = 12
@staticmethod
def clean_cloud_dir(tmp_dir):
if not os.path.isdir(tmp_dir):
return
for fname in os.listdir(tmp_dir):
os.remove(os.path.join(tmp_dir, fname))
def query_instances(self):
return {
x.strip(": ")
for x in self.run_cloud("--query")
if x.lstrip().lower().startswith("cloud-test-")
}
def _instance_exists(self, instance_name=None, query=None):
if not instance_name:
instance_name = self.instance_name
if not query:
query = self.query_instances()
log.debug('Checking for "{}" in {}'.format(instance_name, query))
if isinstance(query, set):
return instance_name in query
return any(instance_name == q.strip(": ") for q in query)
def assertInstanceExists(self, creation_ret=None, instance_name=None):
if not instance_name:
instance_name = self.instance_name
if creation_ret:
self.assertIn(
instance_name,
[i.strip(": ") for i in creation_ret],
"An error occured during instance creation: |\n\t{}\n\t|".format(
"\n\t".join(creation_ret)
),
)
else:
# Verify that the instance exists via query
query = self.query_instances()
for tries in range(self.__RE_TRIES):
if self._instance_exists(instance_name, query):
log.debug(
'Instance "{}" reported after {} seconds'.format(
instance_name, tries * self.__RE_RUN_DELAY
)
)
break
else:
sleep(self.__RE_RUN_DELAY)
query = self.query_instances()
# Assert that the last query was successful
self.assertTrue(
self._instance_exists(instance_name, query),
'Instance "{}" was not created successfully: {}'.format(
self.instance_name, ", ".join(query)
),
)
log.debug('Instance exists and was created: "{}"'.format(instance_name))
def assertDestroyInstance(self, instance_name=None, timeout=None):
if timeout is None:
timeout = TIMEOUT
if not instance_name:
instance_name = self.instance_name
log.debug('Deleting instance "{}"'.format(instance_name))
delete_str = self.run_cloud(
"-d {} --assume-yes --out=yaml".format(instance_name), timeout=timeout
)
if delete_str:
delete = safe_load("\n".join(delete_str))
self.assertIn(self.profile_str, delete)
self.assertIn(self.PROVIDER, delete[self.profile_str])
self.assertIn(instance_name, delete[self.profile_str][self.PROVIDER])
delete_status = delete[self.profile_str][self.PROVIDER][instance_name]
if isinstance(delete_status, str):
self.assertEqual(delete_status, "True")
return
elif isinstance(delete_status, dict):
current_state = delete_status.get("currentState")
if current_state:
if current_state.get("ACTION"):
self.assertIn(".delete", current_state.get("ACTION"))
return
else:
self.assertEqual(current_state.get("name"), "shutting-down")
return
# It's not clear from the delete string that deletion was successful, ask salt-cloud after a delay
query = self.query_instances()
for tries in range(6):
if self._instance_exists(query=query):
sleep(30)
log.debug(
'Instance "{}" still found in query after {} tries: {}'.format(
instance_name, tries, query
)
)
query = self.query_instances()
self.assertNotIn(instance_name, self.query_instances())
@property
def instance_name(self):
if not hasattr(self, "_instance_name"):
subclass = self.__class__.__name__.strip("Test")
self._instance_name = random_string(
"cloud-test-{:-<3}-".format(subclass[:3]), uppercase=False
).lower()
return self._instance_name
@property
def providers(self):
if not hasattr(self, "_providers"):
self._providers = self.run_cloud("--list-providers")
return self._providers
@property
def provider_config(self):
if not hasattr(self, "_provider_config"):
self._provider_config = cloud_providers_config(
os.path.join(
RUNTIME_VARS.TMP_CONF_DIR,
"cloud.providers.d",
self.PROVIDER + ".conf",
)
)
return self._provider_config[self.profile_str][self.PROVIDER]
@property
def config(self):
if not hasattr(self, "_config"):
self._config = cloud_config(
os.path.join(
RUNTIME_VARS.TMP_CONF_DIR,
"cloud.profiles.d",
self.PROVIDER + ".conf",
)
)
return self._config
@property
def profile_str(self):
return self.PROVIDER + "-config"
def add_profile_config(self, name, data, conf, new_profile):
conf_path = os.path.join(RUNTIME_VARS.TMP_CONF_DIR, "cloud.profiles.d", conf)
with salt.utils.files.fopen(conf_path, "r") as fp:
conf = safe_load(fp)
conf[new_profile] = conf[name].copy()
conf[new_profile].update(data)
with salt.utils.files.fopen(conf_path, "w") as fp:
salt.utils.yaml.safe_dump(conf, fp)
def setUp(self):
super().setUp()
if not self.PROVIDER:
self.fail("A PROVIDER must be defined for this test")
if self.profile_str + ":" not in self.providers:
self.skipTest(
"Configuration file for {0} was not found. Check {0}.conf files "
"in tests/integration/files/conf/cloud.*.d/ to run these tests.".format(
self.PROVIDER
)
)
missing_conf_item = []
for att in self.REQUIRED_PROVIDER_CONFIG_ITEMS:
if not self.provider_config.get(att):
missing_conf_item.append(att)
if missing_conf_item:
self.skipTest(
"Conf items are missing that must be provided to run these tests: {}".format(
", ".join(missing_conf_item)
)
+ "\nCheck tests/integration/files/conf/cloud.providers.d/{}.conf".format(
self.PROVIDER
)
)
def _alt_names(self):
query = self.query_instances()
instances = set()
for q in query:
if q.startswith(self.instance_name) and not q.split("-")[-1].startswith(
"DEL"
):
instances.add(q)
log.debug(
'Adding "{}" to the set of instances that needs to be deleted'.format(
q
)
)
return instances
def _ensure_deletion(self, instance_name=None):
destroyed = False
if not instance_name:
instance_name = self.instance_name
if self._instance_exists(instance_name):
for tries in range(3):
try:
self.assertDestroyInstance(instance_name)
return (
False,
'The instance "{}" was deleted during the tearDown, not the test.'.format(
instance_name
),
)
except AssertionError as e:
log.error(
'Failed to delete instance "{}". Tries: {}\n{}'.format(
instance_name, tries, str(e)
)
)
if not self._instance_exists():
destroyed = True
break
else:
sleep(30)
if not destroyed:
return (
False,
'The Instance "{}" was not deleted after multiple attempts'.format(
instance_name
),
)
return (
True,
'The instance "{}" cleaned up properly after the test'.format(
instance_name
),
)
def tearDown(self):
success = True
fail_messages = []
alt_names = self._alt_names()
for instance in alt_names:
alt_destroyed, alt_destroy_message = self._ensure_deletion(instance)
if not alt_destroyed:
success = False
fail_messages.append(alt_destroy_message)
log.error(
'Failed to destroy instance "{}": {}'.format(
instance, alt_destroy_message
)
)
self.assertTrue(success, "\n".join(fail_messages))
self.assertFalse(
alt_names, "Cleanup should happen in the test, not the TearDown"
)
@classmethod
def tearDownClass(cls):
cls.clean_cloud_dir(cls.tmp_provider_dir)
@classmethod
def setUpClass(cls):
cls.tmp_provider_dir = os.path.join(
RUNTIME_VARS.TMP_CONF_DIR, "cloud.providers.d"
)
cls.clean_cloud_dir(cls.tmp_provider_dir)
provider_file = cls.PROVIDER + ".conf"
shutil.copyfile(
os.path.join(
os.path.join(FILES, "conf", "cloud.providers.d"), provider_file
),
os.path.join(os.path.join(cls.tmp_provider_dir, provider_file)),
)
| true | true |
f7315522e3755914ebfefcdfd231697126d0ee40 | 49,362 | py | Python | path-finding/yolo-v5/utils/datasets.py | sa-y-an/open-source-autonomous-vehicle-controller | 0cc415fb141d1b66ac45a7bf6b50add6814728fb | [
"MIT"
] | 3 | 2021-06-15T05:10:00.000Z | 2021-09-05T18:07:01.000Z | utils/datasets.py | z430/yolov5-mask-detection | b959a4fefa1d44d052436ff9129af386e15e0455 | [
"MIT"
] | 1 | 2021-06-07T21:05:14.000Z | 2021-06-07T21:05:14.000Z | utils/datasets.py | z430/yolov5-mask-detection | b959a4fefa1d44d052436ff9129af386e15e0455 | [
"MIT"
] | 9 | 2021-06-10T08:42:53.000Z | 2022-03-28T05:46:16.000Z | # Dataset utils and dataloaders
import glob
import hashlib
import json
import logging
import os
import random
import shutil
import time
from itertools import repeat
from multiprocessing.pool import ThreadPool, Pool
from pathlib import Path
from threading import Thread
import cv2
import math
import numpy as np
import torch
import torch.nn.functional as F
import yaml
from PIL import Image, ExifTags
from torch.utils.data import Dataset
from tqdm import tqdm
from utils.general import check_requirements, check_file, check_dataset, xywh2xyxy, xywhn2xyxy, xyxy2xywhn, \
xyn2xy, segment2box, segments2boxes, resample_segments, clean_str
from utils.metrics import bbox_ioa
from utils.torch_utils import torch_distributed_zero_first
# Parameters
help_url = 'https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data'
img_formats = ['bmp', 'jpg', 'jpeg', 'png', 'tif', 'tiff', 'dng', 'webp', 'mpo'] # acceptable image suffixes
vid_formats = ['mov', 'avi', 'mp4', 'mpg', 'mpeg', 'm4v', 'wmv', 'mkv'] # acceptable video suffixes
num_threads = min(8, os.cpu_count()) # number of multiprocessing threads
logger = logging.getLogger(__name__)
# Get orientation exif tag
for orientation in ExifTags.TAGS.keys():
if ExifTags.TAGS[orientation] == 'Orientation':
break
def get_hash(paths):
# Returns a single hash value of a list of paths (files or dirs)
size = sum(os.path.getsize(p) for p in paths if os.path.exists(p)) # sizes
h = hashlib.md5(str(size).encode()) # hash sizes
h.update(''.join(paths).encode()) # hash paths
return h.hexdigest() # return hash
def exif_size(img):
# Returns exif-corrected PIL size
s = img.size # (width, height)
try:
rotation = dict(img._getexif().items())[orientation]
if rotation == 6: # rotation 270
s = (s[1], s[0])
elif rotation == 8: # rotation 90
s = (s[1], s[0])
except:
pass
return s
def exif_transpose(image):
"""
Transpose a PIL image accordingly if it has an EXIF Orientation tag.
From https://github.com/python-pillow/Pillow/blob/master/src/PIL/ImageOps.py
:param image: The image to transpose.
:return: An image.
"""
exif = image.getexif()
orientation = exif.get(0x0112, 1) # default 1
if orientation > 1:
method = {2: Image.FLIP_LEFT_RIGHT,
3: Image.ROTATE_180,
4: Image.FLIP_TOP_BOTTOM,
5: Image.TRANSPOSE,
6: Image.ROTATE_270,
7: Image.TRANSVERSE,
8: Image.ROTATE_90,
}.get(orientation)
if method is not None:
image = image.transpose(method)
del exif[0x0112]
image.info["exif"] = exif.tobytes()
return image
def create_dataloader(path, imgsz, batch_size, stride, single_cls=False, hyp=None, augment=False, cache=False, pad=0.0,
rect=False, rank=-1, workers=8, image_weights=False, quad=False, prefix=''):
# Make sure only the first process in DDP process the dataset first, and the following others can use the cache
with torch_distributed_zero_first(rank):
dataset = LoadImagesAndLabels(path, imgsz, batch_size,
augment=augment, # augment images
hyp=hyp, # augmentation hyperparameters
rect=rect, # rectangular training
cache_images=cache,
single_cls=single_cls,
stride=int(stride),
pad=pad,
image_weights=image_weights,
prefix=prefix)
batch_size = min(batch_size, len(dataset))
nw = min([os.cpu_count(), batch_size if batch_size > 1 else 0, workers]) # number of workers
sampler = torch.utils.data.distributed.DistributedSampler(dataset) if rank != -1 else None
loader = torch.utils.data.DataLoader if image_weights else InfiniteDataLoader
# Use torch.utils.data.DataLoader() if dataset.properties will update during training else InfiniteDataLoader()
dataloader = loader(dataset,
batch_size=batch_size,
num_workers=nw,
sampler=sampler,
pin_memory=True,
collate_fn=LoadImagesAndLabels.collate_fn4 if quad else LoadImagesAndLabels.collate_fn)
return dataloader, dataset
class InfiniteDataLoader(torch.utils.data.dataloader.DataLoader):
""" Dataloader that reuses workers
Uses same syntax as vanilla DataLoader
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler))
self.iterator = super().__iter__()
def __len__(self):
return len(self.batch_sampler.sampler)
def __iter__(self):
for i in range(len(self)):
yield next(self.iterator)
class _RepeatSampler(object):
""" Sampler that repeats forever
Args:
sampler (Sampler)
"""
def __init__(self, sampler):
self.sampler = sampler
def __iter__(self):
while True:
yield from iter(self.sampler)
class LoadImages: # for inference
def __init__(self, path, img_size=640, stride=32):
p = str(Path(path).absolute()) # os-agnostic absolute path
if '*' in p:
files = sorted(glob.glob(p, recursive=True)) # glob
elif os.path.isdir(p):
files = sorted(glob.glob(os.path.join(p, '*.*'))) # dir
elif os.path.isfile(p):
files = [p] # files
else:
raise Exception(f'ERROR: {p} does not exist')
images = [x for x in files if x.split('.')[-1].lower() in img_formats]
videos = [x for x in files if x.split('.')[-1].lower() in vid_formats]
ni, nv = len(images), len(videos)
self.img_size = img_size
self.stride = stride
self.files = images + videos
self.nf = ni + nv # number of files
self.video_flag = [False] * ni + [True] * nv
self.mode = 'image'
if any(videos):
self.new_video(videos[0]) # new video
else:
self.cap = None
assert self.nf > 0, f'No images or videos found in {p}. ' \
f'Supported formats are:\nimages: {img_formats}\nvideos: {vid_formats}'
def __iter__(self):
self.count = 0
return self
def __next__(self):
if self.count == self.nf:
raise StopIteration
path = self.files[self.count]
if self.video_flag[self.count]:
# Read video
self.mode = 'video'
ret_val, img0 = self.cap.read()
if not ret_val:
self.count += 1
self.cap.release()
if self.count == self.nf: # last video
raise StopIteration
else:
path = self.files[self.count]
self.new_video(path)
ret_val, img0 = self.cap.read()
self.frame += 1
print(f'video {self.count + 1}/{self.nf} ({self.frame}/{self.frames}) {path}: ', end='')
else:
# Read image
self.count += 1
img0 = cv2.imread(path) # BGR
assert img0 is not None, 'Image Not Found ' + path
print(f'image {self.count}/{self.nf} {path}: ', end='')
# Padded resize
img = letterbox(img0, self.img_size, stride=self.stride)[0]
# Convert
img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB and HWC to CHW
img = np.ascontiguousarray(img)
return path, img, img0, self.cap
def new_video(self, path):
self.frame = 0
self.cap = cv2.VideoCapture(path)
self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
def __len__(self):
return self.nf # number of files
class LoadWebcam: # for inference
def __init__(self, pipe='0', img_size=640, stride=32):
self.img_size = img_size
self.stride = stride
self.pipe = eval(pipe) if pipe.isnumeric() else pipe
self.cap = cv2.VideoCapture(self.pipe) # video capture object
self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 3) # set buffer size
def __iter__(self):
self.count = -1
return self
def __next__(self):
self.count += 1
if cv2.waitKey(1) == ord('q'): # q to quit
self.cap.release()
cv2.destroyAllWindows()
raise StopIteration
# Read frame
ret_val, img0 = self.cap.read()
img0 = cv2.flip(img0, 1) # flip left-right
# Print
assert ret_val, f'Camera Error {self.pipe}'
img_path = 'webcam.jpg'
print(f'webcam {self.count}: ', end='')
# Padded resize
img = letterbox(img0, self.img_size, stride=self.stride)[0]
# Convert
img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB and HWC to CHW
img = np.ascontiguousarray(img)
return img_path, img, img0, None
def __len__(self):
return 0
class LoadStreams: # multiple IP or RTSP cameras
def __init__(self, sources='streams.txt', img_size=640, stride=32):
self.mode = 'stream'
self.img_size = img_size
self.stride = stride
if os.path.isfile(sources):
with open(sources, 'r') as f:
sources = [x.strip() for x in f.read().strip().splitlines() if len(x.strip())]
else:
sources = [sources]
n = len(sources)
self.imgs, self.fps, self.frames, self.threads = [None] * n, [0] * n, [0] * n, [None] * n
self.sources = [clean_str(x) for x in sources] # clean source names for later
for i, s in enumerate(sources): # index, source
# Start thread to read frames from video stream
print(f'{i + 1}/{n}: {s}... ', end='')
if 'youtube.com/' in s or 'youtu.be/' in s: # if source is YouTube video
check_requirements(('pafy', 'youtube_dl'))
import pafy
s = pafy.new(s).getbest(preftype="mp4").url # YouTube URL
s = eval(s) if s.isnumeric() else s # i.e. s = '0' local webcam
cap = cv2.VideoCapture(s)
assert cap.isOpened(), f'Failed to open {s}'
w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
self.fps[i] = max(cap.get(cv2.CAP_PROP_FPS) % 100, 0) or 30.0 # 30 FPS fallback
self.frames[i] = max(int(cap.get(cv2.CAP_PROP_FRAME_COUNT)), 0) or float('inf') # infinite stream fallback
_, self.imgs[i] = cap.read() # guarantee first frame
self.threads[i] = Thread(target=self.update, args=([i, cap]), daemon=True)
print(f" success ({self.frames[i]} frames {w}x{h} at {self.fps[i]:.2f} FPS)")
self.threads[i].start()
print('') # newline
# check for common shapes
s = np.stack([letterbox(x, self.img_size, stride=self.stride)[0].shape for x in self.imgs], 0) # shapes
self.rect = np.unique(s, axis=0).shape[0] == 1 # rect inference if all shapes equal
if not self.rect:
print('WARNING: Different stream shapes detected. For optimal performance supply similarly-shaped streams.')
def update(self, i, cap):
# Read stream `i` frames in daemon thread
n, f, read = 0, self.frames[i], 1 # frame number, frame array, inference every 'read' frame
while cap.isOpened() and n < f:
n += 1
# _, self.imgs[index] = cap.read()
cap.grab()
if n % read == 0:
success, im = cap.retrieve()
self.imgs[i] = im if success else self.imgs[i] * 0
time.sleep(1 / self.fps[i]) # wait time
def __iter__(self):
self.count = -1
return self
def __next__(self):
self.count += 1
if not all(x.is_alive() for x in self.threads) or cv2.waitKey(1) == ord('q'): # q to quit
cv2.destroyAllWindows()
raise StopIteration
# Letterbox
img0 = self.imgs.copy()
img = [letterbox(x, self.img_size, auto=self.rect, stride=self.stride)[0] for x in img0]
# Stack
img = np.stack(img, 0)
# Convert
img = img[:, :, :, ::-1].transpose(0, 3, 1, 2) # BGR to RGB and BHWC to BCHW
img = np.ascontiguousarray(img)
return self.sources, img, img0, None
def __len__(self):
return 0 # 1E12 frames = 32 streams at 30 FPS for 30 years
def img2label_paths(img_paths):
# Define label paths as a function of image paths
sa, sb = os.sep + 'images' + os.sep, os.sep + 'labels' + os.sep # /images/, /labels/ substrings
return [sb.join(x.rsplit(sa, 1)).rsplit('.', 1)[0] + '.txt' for x in img_paths]
class LoadImagesAndLabels(Dataset): # for training/testing
def __init__(self, path, img_size=640, batch_size=16, augment=False, hyp=None, rect=False, image_weights=False,
cache_images=False, single_cls=False, stride=32, pad=0.0, prefix=''):
self.img_size = img_size
self.augment = augment
self.hyp = hyp
self.image_weights = image_weights
self.rect = False if image_weights else rect
self.mosaic = self.augment and not self.rect # load 4 images at a time into a mosaic (only during training)
self.mosaic_border = [-img_size // 2, -img_size // 2]
self.stride = stride
self.path = path
try:
f = [] # image files
for p in path if isinstance(path, list) else [path]:
p = Path(p) # os-agnostic
if p.is_dir(): # dir
f += glob.glob(str(p / '**' / '*.*'), recursive=True)
# f = list(p.rglob('**/*.*')) # pathlib
elif p.is_file(): # file
with open(p, 'r') as t:
t = t.read().strip().splitlines()
parent = str(p.parent) + os.sep
f += [x.replace('./', parent) if x.startswith('./') else x for x in t] # local to global path
# f += [p.parent / x.lstrip(os.sep) for x in t] # local to global path (pathlib)
else:
raise Exception(f'{prefix}{p} does not exist')
self.img_files = sorted([x.replace('/', os.sep) for x in f if x.split('.')[-1].lower() in img_formats])
# self.img_files = sorted([x for x in f if x.suffix[1:].lower() in img_formats]) # pathlib
assert self.img_files, f'{prefix}No images found'
except Exception as e:
raise Exception(f'{prefix}Error loading data from {path}: {e}\nSee {help_url}')
# Check cache
self.label_files = img2label_paths(self.img_files) # labels
cache_path = (p if p.is_file() else Path(self.label_files[0]).parent).with_suffix('.cache') # cached labels
if cache_path.is_file():
cache, exists = torch.load(cache_path), True # load
if cache.get('version') != 0.3 or cache.get('hash') != get_hash(self.label_files + self.img_files):
cache, exists = self.cache_labels(cache_path, prefix), False # re-cache
else:
cache, exists = self.cache_labels(cache_path, prefix), False # cache
# Display cache
nf, nm, ne, nc, n = cache.pop('results') # found, missing, empty, corrupted, total
if exists:
d = f"Scanning '{cache_path}' images and labels... {nf} found, {nm} missing, {ne} empty, {nc} corrupted"
tqdm(None, desc=prefix + d, total=n, initial=n) # display cache results
if cache['msgs']:
logging.info('\n'.join(cache['msgs'])) # display warnings
assert nf > 0 or not augment, f'{prefix}No labels in {cache_path}. Can not train without labels. See {help_url}'
# Read cache
[cache.pop(k) for k in ('hash', 'version', 'msgs')] # remove items
labels, shapes, self.segments = zip(*cache.values())
self.labels = list(labels)
self.shapes = np.array(shapes, dtype=np.float64)
self.img_files = list(cache.keys()) # update
self.label_files = img2label_paths(cache.keys()) # update
if single_cls:
for x in self.labels:
x[:, 0] = 0
n = len(shapes) # number of images
bi = np.floor(np.arange(n) / batch_size).astype(np.int) # batch index
nb = bi[-1] + 1 # number of batches
self.batch = bi # batch index of image
self.n = n
self.indices = range(n)
# Rectangular Training
if self.rect:
# Sort by aspect ratio
s = self.shapes # wh
ar = s[:, 1] / s[:, 0] # aspect ratio
irect = ar.argsort()
self.img_files = [self.img_files[i] for i in irect]
self.label_files = [self.label_files[i] for i in irect]
self.labels = [self.labels[i] for i in irect]
self.shapes = s[irect] # wh
ar = ar[irect]
# Set training image shapes
shapes = [[1, 1]] * nb
for i in range(nb):
ari = ar[bi == i]
mini, maxi = ari.min(), ari.max()
if maxi < 1:
shapes[i] = [maxi, 1]
elif mini > 1:
shapes[i] = [1, 1 / mini]
self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(np.int) * stride
# Cache images into memory for faster training (WARNING: large datasets may exceed system RAM)
self.imgs = [None] * n
if cache_images:
gb = 0 # Gigabytes of cached images
self.img_hw0, self.img_hw = [None] * n, [None] * n
results = ThreadPool(num_threads).imap(lambda x: load_image(*x), zip(repeat(self), range(n)))
pbar = tqdm(enumerate(results), total=n)
for i, x in pbar:
self.imgs[i], self.img_hw0[i], self.img_hw[i] = x # img, hw_original, hw_resized = load_image(self, i)
gb += self.imgs[i].nbytes
pbar.desc = f'{prefix}Caching images ({gb / 1E9:.1f}GB)'
pbar.close()
def cache_labels(self, path=Path('./labels.cache'), prefix=''):
# Cache dataset labels, check images and read shapes
x = {} # dict
nm, nf, ne, nc, msgs = 0, 0, 0, 0, [] # number missing, found, empty, corrupt, messages
desc = f"{prefix}Scanning '{path.parent / path.stem}' images and labels..."
with Pool(num_threads) as pool:
pbar = tqdm(pool.imap_unordered(verify_image_label, zip(self.img_files, self.label_files, repeat(prefix))),
desc=desc, total=len(self.img_files))
for im_file, l, shape, segments, nm_f, nf_f, ne_f, nc_f, msg in pbar:
nm += nm_f
nf += nf_f
ne += ne_f
nc += nc_f
if im_file:
x[im_file] = [l, shape, segments]
if msg:
msgs.append(msg)
pbar.desc = f"{desc}{nf} found, {nm} missing, {ne} empty, {nc} corrupted"
pbar.close()
if msgs:
logging.info('\n'.join(msgs))
if nf == 0:
logging.info(f'{prefix}WARNING: No labels found in {path}. See {help_url}')
x['hash'] = get_hash(self.label_files + self.img_files)
x['results'] = nf, nm, ne, nc, len(self.img_files)
x['msgs'] = msgs # warnings
x['version'] = 0.3 # cache version
try:
torch.save(x, path) # save cache for next time
logging.info(f'{prefix}New cache created: {path}')
except Exception as e:
logging.info(f'{prefix}WARNING: Cache directory {path.parent} is not writeable: {e}') # path not writeable
return x
def __len__(self):
return len(self.img_files)
# def __iter__(self):
# self.count = -1
# print('ran dataset iter')
# #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF)
# return self
def __getitem__(self, index):
index = self.indices[index] # linear, shuffled, or image_weights
hyp = self.hyp
mosaic = self.mosaic and random.random() < hyp['mosaic']
if mosaic:
# Load mosaic
img, labels = load_mosaic(self, index)
shapes = None
# MixUp https://arxiv.org/pdf/1710.09412.pdf
if random.random() < hyp['mixup']:
img2, labels2 = load_mosaic(self, random.randint(0, self.n - 1))
r = np.random.beta(32.0, 32.0) # mixup ratio, alpha=beta=32.0
img = (img * r + img2 * (1 - r)).astype(np.uint8)
labels = np.concatenate((labels, labels2), 0)
else:
# Load image
img, (h0, w0), (h, w) = load_image(self, index)
# Letterbox
shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size # final letterboxed shape
img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment)
shapes = (h0, w0), ((h / h0, w / w0), pad) # for COCO mAP rescaling
labels = self.labels[index].copy()
if labels.size: # normalized xywh to pixel xyxy format
labels[:, 1:] = xywhn2xyxy(labels[:, 1:], ratio[0] * w, ratio[1] * h, padw=pad[0], padh=pad[1])
if self.augment:
# Augment imagespace
if not mosaic:
img, labels = random_perspective(img, labels,
degrees=hyp['degrees'],
translate=hyp['translate'],
scale=hyp['scale'],
shear=hyp['shear'],
perspective=hyp['perspective'])
# Augment colorspace
augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v'])
# Apply cutouts
# if random.random() < 0.9:
# labels = cutout(img, labels)
nL = len(labels) # number of labels
if nL:
labels[:, 1:5] = xyxy2xywhn(labels[:, 1:5], w=img.shape[1], h=img.shape[0]) # xyxy to xywh normalized
if self.augment:
# flip up-down
if random.random() < hyp['flipud']:
img = np.flipud(img)
if nL:
labels[:, 2] = 1 - labels[:, 2]
# flip left-right
if random.random() < hyp['fliplr']:
img = np.fliplr(img)
if nL:
labels[:, 1] = 1 - labels[:, 1]
labels_out = torch.zeros((nL, 6))
if nL:
labels_out[:, 1:] = torch.from_numpy(labels)
# Convert
img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3 x img_height x img_width
img = np.ascontiguousarray(img)
return torch.from_numpy(img), labels_out, self.img_files[index], shapes
@staticmethod
def collate_fn(batch):
img, label, path, shapes = zip(*batch) # transposed
for i, l in enumerate(label):
l[:, 0] = i # add target image index for build_targets()
return torch.stack(img, 0), torch.cat(label, 0), path, shapes
@staticmethod
def collate_fn4(batch):
img, label, path, shapes = zip(*batch) # transposed
n = len(shapes) // 4
img4, label4, path4, shapes4 = [], [], path[:n], shapes[:n]
ho = torch.tensor([[0., 0, 0, 1, 0, 0]])
wo = torch.tensor([[0., 0, 1, 0, 0, 0]])
s = torch.tensor([[1, 1, .5, .5, .5, .5]]) # scale
for i in range(n): # zidane torch.zeros(16,3,720,1280) # BCHW
i *= 4
if random.random() < 0.5:
im = F.interpolate(img[i].unsqueeze(0).float(), scale_factor=2., mode='bilinear', align_corners=False)[
0].type(img[i].type())
l = label[i]
else:
im = torch.cat((torch.cat((img[i], img[i + 1]), 1), torch.cat((img[i + 2], img[i + 3]), 1)), 2)
l = torch.cat((label[i], label[i + 1] + ho, label[i + 2] + wo, label[i + 3] + ho + wo), 0) * s
img4.append(im)
label4.append(l)
for i, l in enumerate(label4):
l[:, 0] = i # add target image index for build_targets()
return torch.stack(img4, 0), torch.cat(label4, 0), path4, shapes4
# Ancillary functions --------------------------------------------------------------------------------------------------
def load_image(self, index):
# loads 1 image from dataset, returns img, original hw, resized hw
img = self.imgs[index]
if img is None: # not cached
path = self.img_files[index]
img = cv2.imread(path) # BGR
assert img is not None, 'Image Not Found ' + path
h0, w0 = img.shape[:2] # orig hw
r = self.img_size / max(h0, w0) # ratio
if r != 1: # if sizes are not equal
img = cv2.resize(img, (int(w0 * r), int(h0 * r)),
interpolation=cv2.INTER_AREA if r < 1 and not self.augment else cv2.INTER_LINEAR)
return img, (h0, w0), img.shape[:2] # img, hw_original, hw_resized
else:
return self.imgs[index], self.img_hw0[index], self.img_hw[index] # img, hw_original, hw_resized
def augment_hsv(img, hgain=0.5, sgain=0.5, vgain=0.5):
if hgain or sgain or vgain:
r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains
hue, sat, val = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV))
dtype = img.dtype # uint8
x = np.arange(0, 256, dtype=r.dtype)
lut_hue = ((x * r[0]) % 180).astype(dtype)
lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)
lut_val = np.clip(x * r[2], 0, 255).astype(dtype)
img_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val)))
cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR, dst=img) # no return needed
def hist_equalize(img, clahe=True, bgr=False):
# Equalize histogram on BGR image 'img' with img.shape(n,m,3) and range 0-255
yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV if bgr else cv2.COLOR_RGB2YUV)
if clahe:
c = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
yuv[:, :, 0] = c.apply(yuv[:, :, 0])
else:
yuv[:, :, 0] = cv2.equalizeHist(yuv[:, :, 0]) # equalize Y channel histogram
return cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR if bgr else cv2.COLOR_YUV2RGB) # convert YUV image to RGB
def load_mosaic(self, index):
# loads images in a 4-mosaic
labels4, segments4 = [], []
s = self.img_size
yc, xc = [int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border] # mosaic center x, y
indices = [index] + random.choices(self.indices, k=3) # 3 additional image indices
for i, index in enumerate(indices):
# Load image
img, _, (h, w) = load_image(self, index)
# place img in img4
if i == 0: # top left
img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image)
x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image)
elif i == 1: # top right
x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc
x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h
elif i == 2: # bottom left
x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)
x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)
elif i == 3: # bottom right
x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)
x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)
img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
padw = x1a - x1b
padh = y1a - y1b
# Labels
labels, segments = self.labels[index].copy(), self.segments[index].copy()
if labels.size:
labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh) # normalized xywh to pixel xyxy format
segments = [xyn2xy(x, w, h, padw, padh) for x in segments]
labels4.append(labels)
segments4.extend(segments)
# Concat/clip labels
labels4 = np.concatenate(labels4, 0)
for x in (labels4[:, 1:], *segments4):
np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
# img4, labels4 = replicate(img4, labels4) # replicate
# Augment
img4, labels4, segments4 = copy_paste(img4, labels4, segments4, probability=self.hyp['copy_paste'])
img4, labels4 = random_perspective(img4, labels4, segments4,
degrees=self.hyp['degrees'],
translate=self.hyp['translate'],
scale=self.hyp['scale'],
shear=self.hyp['shear'],
perspective=self.hyp['perspective'],
border=self.mosaic_border) # border to remove
return img4, labels4
def load_mosaic9(self, index):
# loads images in a 9-mosaic
labels9, segments9 = [], []
s = self.img_size
indices = [index] + random.choices(self.indices, k=8) # 8 additional image indices
for i, index in enumerate(indices):
# Load image
img, _, (h, w) = load_image(self, index)
# place img in img9
if i == 0: # center
img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
h0, w0 = h, w
c = s, s, s + w, s + h # xmin, ymin, xmax, ymax (base) coordinates
elif i == 1: # top
c = s, s - h, s + w, s
elif i == 2: # top right
c = s + wp, s - h, s + wp + w, s
elif i == 3: # right
c = s + w0, s, s + w0 + w, s + h
elif i == 4: # bottom right
c = s + w0, s + hp, s + w0 + w, s + hp + h
elif i == 5: # bottom
c = s + w0 - w, s + h0, s + w0, s + h0 + h
elif i == 6: # bottom left
c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h
elif i == 7: # left
c = s - w, s + h0 - h, s, s + h0
elif i == 8: # top left
c = s - w, s + h0 - hp - h, s, s + h0 - hp
padx, pady = c[:2]
x1, y1, x2, y2 = [max(x, 0) for x in c] # allocate coords
# Labels
labels, segments = self.labels[index].copy(), self.segments[index].copy()
if labels.size:
labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padx, pady) # normalized xywh to pixel xyxy format
segments = [xyn2xy(x, w, h, padx, pady) for x in segments]
labels9.append(labels)
segments9.extend(segments)
# Image
img9[y1:y2, x1:x2] = img[y1 - pady:, x1 - padx:] # img9[ymin:ymax, xmin:xmax]
hp, wp = h, w # height, width previous
# Offset
yc, xc = [int(random.uniform(0, s)) for _ in self.mosaic_border] # mosaic center x, y
img9 = img9[yc:yc + 2 * s, xc:xc + 2 * s]
# Concat/clip labels
labels9 = np.concatenate(labels9, 0)
labels9[:, [1, 3]] -= xc
labels9[:, [2, 4]] -= yc
c = np.array([xc, yc]) # centers
segments9 = [x - c for x in segments9]
for x in (labels9[:, 1:], *segments9):
np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
# img9, labels9 = replicate(img9, labels9) # replicate
# Augment
img9, labels9 = random_perspective(img9, labels9, segments9,
degrees=self.hyp['degrees'],
translate=self.hyp['translate'],
scale=self.hyp['scale'],
shear=self.hyp['shear'],
perspective=self.hyp['perspective'],
border=self.mosaic_border) # border to remove
return img9, labels9
def replicate(img, labels):
# Replicate labels
h, w = img.shape[:2]
boxes = labels[:, 1:].astype(int)
x1, y1, x2, y2 = boxes.T
s = ((x2 - x1) + (y2 - y1)) / 2 # side length (pixels)
for i in s.argsort()[:round(s.size * 0.5)]: # smallest indices
x1b, y1b, x2b, y2b = boxes[i]
bh, bw = y2b - y1b, x2b - x1b
yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw)) # offset x, y
x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh]
img[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0)
return img, labels
def letterbox(img, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):
# Resize and pad image while meeting stride-multiple constraints
shape = img.shape[:2] # current shape [height, width]
if isinstance(new_shape, int):
new_shape = (new_shape, new_shape)
# Scale ratio (new / old)
r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
if not scaleup: # only scale down, do not scale up (for better test mAP)
r = min(r, 1.0)
# Compute padding
ratio = r, r # width, height ratios
new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
if auto: # minimum rectangle
dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding
elif scaleFill: # stretch
dw, dh = 0.0, 0.0
new_unpad = (new_shape[1], new_shape[0])
ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios
dw /= 2 # divide padding into 2 sides
dh /= 2
if shape[::-1] != new_unpad: # resize
img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)
top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border
return img, ratio, (dw, dh)
def random_perspective(img, targets=(), segments=(), degrees=10, translate=.1, scale=.1, shear=10, perspective=0.0,
border=(0, 0)):
# torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-10, 10))
# targets = [cls, xyxy]
height = img.shape[0] + border[0] * 2 # shape(h,w,c)
width = img.shape[1] + border[1] * 2
# Center
C = np.eye(3)
C[0, 2] = -img.shape[1] / 2 # x translation (pixels)
C[1, 2] = -img.shape[0] / 2 # y translation (pixels)
# Perspective
P = np.eye(3)
P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y)
P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x)
# Rotation and Scale
R = np.eye(3)
a = random.uniform(-degrees, degrees)
# a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations
s = random.uniform(1 - scale, 1 + scale)
# s = 2 ** random.uniform(-scale, scale)
R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)
# Shear
S = np.eye(3)
S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg)
S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg)
# Translation
T = np.eye(3)
T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width # x translation (pixels)
T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height # y translation (pixels)
# Combined rotation matrix
M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT
if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed
if perspective:
img = cv2.warpPerspective(img, M, dsize=(width, height), borderValue=(114, 114, 114))
else: # affine
img = cv2.warpAffine(img, M[:2], dsize=(width, height), borderValue=(114, 114, 114))
# Visualize
# import matplotlib.pyplot as plt
# ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel()
# ax[0].imshow(img[:, :, ::-1]) # base
# ax[1].imshow(img2[:, :, ::-1]) # warped
# Transform label coordinates
n = len(targets)
if n:
use_segments = any(x.any() for x in segments)
new = np.zeros((n, 4))
if use_segments: # warp segments
segments = resample_segments(segments) # upsample
for i, segment in enumerate(segments):
xy = np.ones((len(segment), 3))
xy[:, :2] = segment
xy = xy @ M.T # transform
xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2] # perspective rescale or affine
# clip
new[i] = segment2box(xy, width, height)
else: # warp boxes
xy = np.ones((n * 4, 3))
xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1
xy = xy @ M.T # transform
xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8) # perspective rescale or affine
# create new boxes
x = xy[:, [0, 2, 4, 6]]
y = xy[:, [1, 3, 5, 7]]
new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T
# clip
new[:, [0, 2]] = new[:, [0, 2]].clip(0, width)
new[:, [1, 3]] = new[:, [1, 3]].clip(0, height)
# filter candidates
i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01 if use_segments else 0.10)
targets = targets[i]
targets[:, 1:5] = new[i]
return img, targets
def copy_paste(img, labels, segments, probability=0.5):
# Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy)
n = len(segments)
if probability and n:
h, w, c = img.shape # height, width, channels
im_new = np.zeros(img.shape, np.uint8)
for j in random.sample(range(n), k=round(probability * n)):
l, s = labels[j], segments[j]
box = w - l[3], l[2], w - l[1], l[4]
ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area
if (ioa < 0.30).all(): # allow 30% obscuration of existing labels
labels = np.concatenate((labels, [[l[0], *box]]), 0)
segments.append(np.concatenate((w - s[:, 0:1], s[:, 1:2]), 1))
cv2.drawContours(im_new, [segments[j].astype(np.int32)], -1, (255, 255, 255), cv2.FILLED)
result = cv2.bitwise_and(src1=img, src2=im_new)
result = cv2.flip(result, 1) # augment segments (flip left-right)
i = result > 0 # pixels to replace
# i[:, :] = result.max(2).reshape(h, w, 1) # act over ch
img[i] = result[i] # cv2.imwrite('debug.jpg', img) # debug
return img, labels, segments
def box_candidates(box1, box2, wh_thr=2, ar_thr=20, area_thr=0.1, eps=1e-16): # box1(4,n), box2(4,n)
# Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio
w1, h1 = box1[2] - box1[0], box1[3] - box1[1]
w2, h2 = box2[2] - box2[0], box2[3] - box2[1]
ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio
return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr) # candidates
def cutout(image, labels):
# Applies image cutout augmentation https://arxiv.org/abs/1708.04552
h, w = image.shape[:2]
# create random masks
scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16 # image size fraction
for s in scales:
mask_h = random.randint(1, int(h * s))
mask_w = random.randint(1, int(w * s))
# box
xmin = max(0, random.randint(0, w) - mask_w // 2)
ymin = max(0, random.randint(0, h) - mask_h // 2)
xmax = min(w, xmin + mask_w)
ymax = min(h, ymin + mask_h)
# apply random color mask
image[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)]
# return unobscured labels
if len(labels) and s > 0.03:
box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32)
ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area
labels = labels[ioa < 0.60] # remove >60% obscured labels
return labels
def create_folder(path='./new'):
# Create folder
if os.path.exists(path):
shutil.rmtree(path) # delete output folder
os.makedirs(path) # make new output folder
def flatten_recursive(path='../datasets/coco128'):
# Flatten a recursive directory by bringing all files to top level
new_path = Path(path + '_flat')
create_folder(new_path)
for file in tqdm(glob.glob(str(Path(path)) + '/**/*.*', recursive=True)):
shutil.copyfile(file, new_path / Path(file).name)
def extract_boxes(path='../datasets/coco128'): # from utils.datasets import *; extract_boxes()
# Convert detection dataset into classification dataset, with one directory per class
path = Path(path) # images dir
shutil.rmtree(path / 'classifier') if (path / 'classifier').is_dir() else None # remove existing
files = list(path.rglob('*.*'))
n = len(files) # number of files
for im_file in tqdm(files, total=n):
if im_file.suffix[1:] in img_formats:
# image
im = cv2.imread(str(im_file))[..., ::-1] # BGR to RGB
h, w = im.shape[:2]
# labels
lb_file = Path(img2label_paths([str(im_file)])[0])
if Path(lb_file).exists():
with open(lb_file, 'r') as f:
lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32) # labels
for j, x in enumerate(lb):
c = int(x[0]) # class
f = (path / 'classifier') / f'{c}' / f'{path.stem}_{im_file.stem}_{j}.jpg' # new filename
if not f.parent.is_dir():
f.parent.mkdir(parents=True)
b = x[1:] * [w, h, w, h] # box
# b[2:] = b[2:].max() # rectangle to square
b[2:] = b[2:] * 1.2 + 3 # pad
b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int)
b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image
b[[1, 3]] = np.clip(b[[1, 3]], 0, h)
assert cv2.imwrite(str(f), im[b[1]:b[3], b[0]:b[2]]), f'box failure in {f}'
def autosplit(path='../datasets/coco128/images', weights=(0.9, 0.1, 0.0), annotated_only=False):
""" Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files
Usage: from utils.datasets import *; autosplit()
Arguments
path: Path to images directory
weights: Train, val, test weights (list, tuple)
annotated_only: Only use images with an annotated txt file
"""
path = Path(path) # images dir
files = sum([list(path.rglob(f"*.{img_ext}")) for img_ext in img_formats], []) # image files only
n = len(files) # number of files
random.seed(0) # for reproducibility
indices = random.choices([0, 1, 2], weights=weights, k=n) # assign each image to a split
txt = ['autosplit_train.txt', 'autosplit_val.txt', 'autosplit_test.txt'] # 3 txt files
[(path.parent / x).unlink(missing_ok=True) for x in txt] # remove existing
print(f'Autosplitting images from {path}' + ', using *.txt labeled images only' * annotated_only)
for i, img in tqdm(zip(indices, files), total=n):
if not annotated_only or Path(img2label_paths([str(img)])[0]).exists(): # check label
with open(path.parent / txt[i], 'a') as f:
f.write('./' + img.relative_to(path.parent).as_posix() + '\n') # add image to txt file
def verify_image_label(args):
# Verify one image-label pair
im_file, lb_file, prefix = args
nm, nf, ne, nc = 0, 0, 0, 0 # number missing, found, empty, corrupt
try:
# verify images
im = Image.open(im_file)
im.verify() # PIL verify
shape = exif_size(im) # image size
assert (shape[0] > 9) & (shape[1] > 9), f'image size {shape} <10 pixels'
assert im.format.lower() in img_formats, f'invalid image format {im.format}'
if im.format.lower() in ('jpg', 'jpeg'):
with open(im_file, 'rb') as f:
f.seek(-2, 2)
assert f.read() == b'\xff\xd9', 'corrupted JPEG'
# verify labels
segments = [] # instance segments
if os.path.isfile(lb_file):
nf = 1 # label found
with open(lb_file, 'r') as f:
l = [x.split() for x in f.read().strip().splitlines() if len(x)]
if any([len(x) > 8 for x in l]): # is segment
classes = np.array([x[0] for x in l], dtype=np.float32)
segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in l] # (cls, xy1...)
l = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1) # (cls, xywh)
l = np.array(l, dtype=np.float32)
if len(l):
assert l.shape[1] == 5, 'labels require 5 columns each'
assert (l >= 0).all(), 'negative labels'
assert (l[:, 1:] <= 1).all(), 'non-normalized or out of bounds coordinate labels'
assert np.unique(l, axis=0).shape[0] == l.shape[0], 'duplicate labels'
else:
ne = 1 # label empty
l = np.zeros((0, 5), dtype=np.float32)
else:
nm = 1 # label missing
l = np.zeros((0, 5), dtype=np.float32)
return im_file, l, shape, segments, nm, nf, ne, nc, ''
except Exception as e:
nc = 1
msg = f'{prefix}WARNING: Ignoring corrupted image and/or label {im_file}: {e}'
return [None, None, None, None, nm, nf, ne, nc, msg]
def dataset_stats(path='coco128.yaml', autodownload=False, verbose=False):
""" Return dataset statistics dictionary with images and instances counts per split per class
Usage: from utils.datasets import *; dataset_stats('coco128.yaml', verbose=True)
Arguments
path: Path to data.yaml
autodownload: Attempt to download dataset if not found locally
verbose: Print stats dictionary
"""
def round_labels(labels):
# Update labels to integer class and 6 decimal place floats
return [[int(c), *[round(x, 6) for x in points]] for c, *points in labels]
with open(check_file(path)) as f:
data = yaml.safe_load(f) # data dict
check_dataset(data, autodownload) # download dataset if missing
nc = data['nc'] # number of classes
stats = {'nc': nc, 'names': data['names']} # statistics dictionary
for split in 'train', 'val', 'test':
if data.get(split) is None:
stats[split] = None # i.e. no test set
continue
x = []
dataset = LoadImagesAndLabels(data[split], augment=False, rect=True) # load dataset
if split == 'train':
cache_path = Path(dataset.label_files[0]).parent.with_suffix('.cache') # *.cache path
for label in tqdm(dataset.labels, total=dataset.n, desc='Statistics'):
x.append(np.bincount(label[:, 0].astype(int), minlength=nc))
x = np.array(x) # shape(128x80)
stats[split] = {'instance_stats': {'total': int(x.sum()), 'per_class': x.sum(0).tolist()},
'image_stats': {'total': dataset.n, 'unlabelled': int(np.all(x == 0, 1).sum()),
'per_class': (x > 0).sum(0).tolist()},
'labels': [{str(Path(k).name): round_labels(v.tolist())} for k, v in
zip(dataset.img_files, dataset.labels)]}
# Save, print and return
with open(cache_path.with_suffix('.json'), 'w') as f:
json.dump(stats, f) # save stats *.json
if verbose:
print(json.dumps(stats, indent=2, sort_keys=False))
# print(yaml.dump([stats], sort_keys=False, default_flow_style=False))
return stats
| 42.590164 | 120 | 0.548803 |
import glob
import hashlib
import json
import logging
import os
import random
import shutil
import time
from itertools import repeat
from multiprocessing.pool import ThreadPool, Pool
from pathlib import Path
from threading import Thread
import cv2
import math
import numpy as np
import torch
import torch.nn.functional as F
import yaml
from PIL import Image, ExifTags
from torch.utils.data import Dataset
from tqdm import tqdm
from utils.general import check_requirements, check_file, check_dataset, xywh2xyxy, xywhn2xyxy, xyxy2xywhn, \
xyn2xy, segment2box, segments2boxes, resample_segments, clean_str
from utils.metrics import bbox_ioa
from utils.torch_utils import torch_distributed_zero_first
help_url = 'https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data'
img_formats = ['bmp', 'jpg', 'jpeg', 'png', 'tif', 'tiff', 'dng', 'webp', 'mpo']
vid_formats = ['mov', 'avi', 'mp4', 'mpg', 'mpeg', 'm4v', 'wmv', 'mkv']
num_threads = min(8, os.cpu_count())
logger = logging.getLogger(__name__)
for orientation in ExifTags.TAGS.keys():
if ExifTags.TAGS[orientation] == 'Orientation':
break
def get_hash(paths):
size = sum(os.path.getsize(p) for p in paths if os.path.exists(p))
h = hashlib.md5(str(size).encode())
h.update(''.join(paths).encode())
return h.hexdigest()
def exif_size(img):
s = img.size
try:
rotation = dict(img._getexif().items())[orientation]
if rotation == 6:
s = (s[1], s[0])
elif rotation == 8:
s = (s[1], s[0])
except:
pass
return s
def exif_transpose(image):
exif = image.getexif()
orientation = exif.get(0x0112, 1)
if orientation > 1:
method = {2: Image.FLIP_LEFT_RIGHT,
3: Image.ROTATE_180,
4: Image.FLIP_TOP_BOTTOM,
5: Image.TRANSPOSE,
6: Image.ROTATE_270,
7: Image.TRANSVERSE,
8: Image.ROTATE_90,
}.get(orientation)
if method is not None:
image = image.transpose(method)
del exif[0x0112]
image.info["exif"] = exif.tobytes()
return image
def create_dataloader(path, imgsz, batch_size, stride, single_cls=False, hyp=None, augment=False, cache=False, pad=0.0,
rect=False, rank=-1, workers=8, image_weights=False, quad=False, prefix=''):
with torch_distributed_zero_first(rank):
dataset = LoadImagesAndLabels(path, imgsz, batch_size,
augment=augment,
hyp=hyp,
rect=rect,
cache_images=cache,
single_cls=single_cls,
stride=int(stride),
pad=pad,
image_weights=image_weights,
prefix=prefix)
batch_size = min(batch_size, len(dataset))
nw = min([os.cpu_count(), batch_size if batch_size > 1 else 0, workers])
sampler = torch.utils.data.distributed.DistributedSampler(dataset) if rank != -1 else None
loader = torch.utils.data.DataLoader if image_weights else InfiniteDataLoader
dataloader = loader(dataset,
batch_size=batch_size,
num_workers=nw,
sampler=sampler,
pin_memory=True,
collate_fn=LoadImagesAndLabels.collate_fn4 if quad else LoadImagesAndLabels.collate_fn)
return dataloader, dataset
class InfiniteDataLoader(torch.utils.data.dataloader.DataLoader):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler))
self.iterator = super().__iter__()
def __len__(self):
return len(self.batch_sampler.sampler)
def __iter__(self):
for i in range(len(self)):
yield next(self.iterator)
class _RepeatSampler(object):
def __init__(self, sampler):
self.sampler = sampler
def __iter__(self):
while True:
yield from iter(self.sampler)
class LoadImages:
def __init__(self, path, img_size=640, stride=32):
p = str(Path(path).absolute())
if '*' in p:
files = sorted(glob.glob(p, recursive=True))
elif os.path.isdir(p):
files = sorted(glob.glob(os.path.join(p, '*.*')))
elif os.path.isfile(p):
files = [p]
else:
raise Exception(f'ERROR: {p} does not exist')
images = [x for x in files if x.split('.')[-1].lower() in img_formats]
videos = [x for x in files if x.split('.')[-1].lower() in vid_formats]
ni, nv = len(images), len(videos)
self.img_size = img_size
self.stride = stride
self.files = images + videos
self.nf = ni + nv
self.video_flag = [False] * ni + [True] * nv
self.mode = 'image'
if any(videos):
self.new_video(videos[0])
else:
self.cap = None
assert self.nf > 0, f'No images or videos found in {p}. ' \
f'Supported formats are:\nimages: {img_formats}\nvideos: {vid_formats}'
def __iter__(self):
self.count = 0
return self
def __next__(self):
if self.count == self.nf:
raise StopIteration
path = self.files[self.count]
if self.video_flag[self.count]:
self.mode = 'video'
ret_val, img0 = self.cap.read()
if not ret_val:
self.count += 1
self.cap.release()
if self.count == self.nf:
raise StopIteration
else:
path = self.files[self.count]
self.new_video(path)
ret_val, img0 = self.cap.read()
self.frame += 1
print(f'video {self.count + 1}/{self.nf} ({self.frame}/{self.frames}) {path}: ', end='')
else:
self.count += 1
img0 = cv2.imread(path)
assert img0 is not None, 'Image Not Found ' + path
print(f'image {self.count}/{self.nf} {path}: ', end='')
img = letterbox(img0, self.img_size, stride=self.stride)[0]
img = img[:, :, ::-1].transpose(2, 0, 1)
img = np.ascontiguousarray(img)
return path, img, img0, self.cap
def new_video(self, path):
self.frame = 0
self.cap = cv2.VideoCapture(path)
self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
def __len__(self):
return self.nf
class LoadWebcam:
def __init__(self, pipe='0', img_size=640, stride=32):
self.img_size = img_size
self.stride = stride
self.pipe = eval(pipe) if pipe.isnumeric() else pipe
self.cap = cv2.VideoCapture(self.pipe)
self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 3)
def __iter__(self):
self.count = -1
return self
def __next__(self):
self.count += 1
if cv2.waitKey(1) == ord('q'):
self.cap.release()
cv2.destroyAllWindows()
raise StopIteration
ret_val, img0 = self.cap.read()
img0 = cv2.flip(img0, 1)
assert ret_val, f'Camera Error {self.pipe}'
img_path = 'webcam.jpg'
print(f'webcam {self.count}: ', end='')
img = letterbox(img0, self.img_size, stride=self.stride)[0]
img = img[:, :, ::-1].transpose(2, 0, 1)
img = np.ascontiguousarray(img)
return img_path, img, img0, None
def __len__(self):
return 0
class LoadStreams:
def __init__(self, sources='streams.txt', img_size=640, stride=32):
self.mode = 'stream'
self.img_size = img_size
self.stride = stride
if os.path.isfile(sources):
with open(sources, 'r') as f:
sources = [x.strip() for x in f.read().strip().splitlines() if len(x.strip())]
else:
sources = [sources]
n = len(sources)
self.imgs, self.fps, self.frames, self.threads = [None] * n, [0] * n, [0] * n, [None] * n
self.sources = [clean_str(x) for x in sources]
for i, s in enumerate(sources):
print(f'{i + 1}/{n}: {s}... ', end='')
if 'youtube.com/' in s or 'youtu.be/' in s:
check_requirements(('pafy', 'youtube_dl'))
import pafy
s = pafy.new(s).getbest(preftype="mp4").url
s = eval(s) if s.isnumeric() else s
cap = cv2.VideoCapture(s)
assert cap.isOpened(), f'Failed to open {s}'
w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
self.fps[i] = max(cap.get(cv2.CAP_PROP_FPS) % 100, 0) or 30.0
self.frames[i] = max(int(cap.get(cv2.CAP_PROP_FRAME_COUNT)), 0) or float('inf')
_, self.imgs[i] = cap.read()
self.threads[i] = Thread(target=self.update, args=([i, cap]), daemon=True)
print(f" success ({self.frames[i]} frames {w}x{h} at {self.fps[i]:.2f} FPS)")
self.threads[i].start()
print('')
s = np.stack([letterbox(x, self.img_size, stride=self.stride)[0].shape for x in self.imgs], 0)
self.rect = np.unique(s, axis=0).shape[0] == 1
if not self.rect:
print('WARNING: Different stream shapes detected. For optimal performance supply similarly-shaped streams.')
def update(self, i, cap):
n, f, read = 0, self.frames[i], 1
while cap.isOpened() and n < f:
n += 1
cap.grab()
if n % read == 0:
success, im = cap.retrieve()
self.imgs[i] = im if success else self.imgs[i] * 0
time.sleep(1 / self.fps[i])
def __iter__(self):
self.count = -1
return self
def __next__(self):
self.count += 1
if not all(x.is_alive() for x in self.threads) or cv2.waitKey(1) == ord('q'):
cv2.destroyAllWindows()
raise StopIteration
img0 = self.imgs.copy()
img = [letterbox(x, self.img_size, auto=self.rect, stride=self.stride)[0] for x in img0]
img = np.stack(img, 0)
img = img[:, :, :, ::-1].transpose(0, 3, 1, 2)
img = np.ascontiguousarray(img)
return self.sources, img, img0, None
def __len__(self):
return 0
def img2label_paths(img_paths):
sa, sb = os.sep + 'images' + os.sep, os.sep + 'labels' + os.sep
return [sb.join(x.rsplit(sa, 1)).rsplit('.', 1)[0] + '.txt' for x in img_paths]
class LoadImagesAndLabels(Dataset):
def __init__(self, path, img_size=640, batch_size=16, augment=False, hyp=None, rect=False, image_weights=False,
cache_images=False, single_cls=False, stride=32, pad=0.0, prefix=''):
self.img_size = img_size
self.augment = augment
self.hyp = hyp
self.image_weights = image_weights
self.rect = False if image_weights else rect
self.mosaic = self.augment and not self.rect
self.mosaic_border = [-img_size // 2, -img_size // 2]
self.stride = stride
self.path = path
try:
f = []
for p in path if isinstance(path, list) else [path]:
p = Path(p)
if p.is_dir():
f += glob.glob(str(p / '**' / '*.*'), recursive=True)
elif p.is_file():
with open(p, 'r') as t:
t = t.read().strip().splitlines()
parent = str(p.parent) + os.sep
f += [x.replace('./', parent) if x.startswith('./') else x for x in t]
raise Exception(f'{prefix}{p} does not exist')
self.img_files = sorted([x.replace('/', os.sep) for x in f if x.split('.')[-1].lower() in img_formats])
assert self.img_files, f'{prefix}No images found'
except Exception as e:
raise Exception(f'{prefix}Error loading data from {path}: {e}\nSee {help_url}')
self.label_files = img2label_paths(self.img_files)
cache_path = (p if p.is_file() else Path(self.label_files[0]).parent).with_suffix('.cache')
if cache_path.is_file():
cache, exists = torch.load(cache_path), True
if cache.get('version') != 0.3 or cache.get('hash') != get_hash(self.label_files + self.img_files):
cache, exists = self.cache_labels(cache_path, prefix), False
else:
cache, exists = self.cache_labels(cache_path, prefix), False
nf, nm, ne, nc, n = cache.pop('results')
if exists:
d = f"Scanning '{cache_path}' images and labels... {nf} found, {nm} missing, {ne} empty, {nc} corrupted"
tqdm(None, desc=prefix + d, total=n, initial=n)
if cache['msgs']:
logging.info('\n'.join(cache['msgs']))
assert nf > 0 or not augment, f'{prefix}No labels in {cache_path}. Can not train without labels. See {help_url}'
[cache.pop(k) for k in ('hash', 'version', 'msgs')]
labels, shapes, self.segments = zip(*cache.values())
self.labels = list(labels)
self.shapes = np.array(shapes, dtype=np.float64)
self.img_files = list(cache.keys())
self.label_files = img2label_paths(cache.keys())
if single_cls:
for x in self.labels:
x[:, 0] = 0
n = len(shapes)
bi = np.floor(np.arange(n) / batch_size).astype(np.int)
nb = bi[-1] + 1
self.batch = bi
self.n = n
self.indices = range(n)
if self.rect:
s = self.shapes
ar = s[:, 1] / s[:, 0]
irect = ar.argsort()
self.img_files = [self.img_files[i] for i in irect]
self.label_files = [self.label_files[i] for i in irect]
self.labels = [self.labels[i] for i in irect]
self.shapes = s[irect]
ar = ar[irect]
shapes = [[1, 1]] * nb
for i in range(nb):
ari = ar[bi == i]
mini, maxi = ari.min(), ari.max()
if maxi < 1:
shapes[i] = [maxi, 1]
elif mini > 1:
shapes[i] = [1, 1 / mini]
self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(np.int) * stride
self.imgs = [None] * n
if cache_images:
gb = 0
self.img_hw0, self.img_hw = [None] * n, [None] * n
results = ThreadPool(num_threads).imap(lambda x: load_image(*x), zip(repeat(self), range(n)))
pbar = tqdm(enumerate(results), total=n)
for i, x in pbar:
self.imgs[i], self.img_hw0[i], self.img_hw[i] = x
gb += self.imgs[i].nbytes
pbar.desc = f'{prefix}Caching images ({gb / 1E9:.1f}GB)'
pbar.close()
def cache_labels(self, path=Path('./labels.cache'), prefix=''):
x = {}
nm, nf, ne, nc, msgs = 0, 0, 0, 0, []
desc = f"{prefix}Scanning '{path.parent / path.stem}' images and labels..."
with Pool(num_threads) as pool:
pbar = tqdm(pool.imap_unordered(verify_image_label, zip(self.img_files, self.label_files, repeat(prefix))),
desc=desc, total=len(self.img_files))
for im_file, l, shape, segments, nm_f, nf_f, ne_f, nc_f, msg in pbar:
nm += nm_f
nf += nf_f
ne += ne_f
nc += nc_f
if im_file:
x[im_file] = [l, shape, segments]
if msg:
msgs.append(msg)
pbar.desc = f"{desc}{nf} found, {nm} missing, {ne} empty, {nc} corrupted"
pbar.close()
if msgs:
logging.info('\n'.join(msgs))
if nf == 0:
logging.info(f'{prefix}WARNING: No labels found in {path}. See {help_url}')
x['hash'] = get_hash(self.label_files + self.img_files)
x['results'] = nf, nm, ne, nc, len(self.img_files)
x['msgs'] = msgs
x['version'] = 0.3
try:
torch.save(x, path)
logging.info(f'{prefix}New cache created: {path}')
except Exception as e:
logging.info(f'{prefix}WARNING: Cache directory {path.parent} is not writeable: {e}')
return x
def __len__(self):
return len(self.img_files)
self.hyp
mosaic = self.mosaic and random.random() < hyp['mosaic']
if mosaic:
img, labels = load_mosaic(self, index)
shapes = None
if random.random() < hyp['mixup']:
img2, labels2 = load_mosaic(self, random.randint(0, self.n - 1))
r = np.random.beta(32.0, 32.0)
img = (img * r + img2 * (1 - r)).astype(np.uint8)
labels = np.concatenate((labels, labels2), 0)
else:
img, (h0, w0), (h, w) = load_image(self, index)
shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size
img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment)
shapes = (h0, w0), ((h / h0, w / w0), pad)
labels = self.labels[index].copy()
if labels.size:
labels[:, 1:] = xywhn2xyxy(labels[:, 1:], ratio[0] * w, ratio[1] * h, padw=pad[0], padh=pad[1])
if self.augment:
if not mosaic:
img, labels = random_perspective(img, labels,
degrees=hyp['degrees'],
translate=hyp['translate'],
scale=hyp['scale'],
shear=hyp['shear'],
perspective=hyp['perspective'])
augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v'])
nL = len(labels)
if nL:
labels[:, 1:5] = xyxy2xywhn(labels[:, 1:5], w=img.shape[1], h=img.shape[0])
if self.augment:
if random.random() < hyp['flipud']:
img = np.flipud(img)
if nL:
labels[:, 2] = 1 - labels[:, 2]
if random.random() < hyp['fliplr']:
img = np.fliplr(img)
if nL:
labels[:, 1] = 1 - labels[:, 1]
labels_out = torch.zeros((nL, 6))
if nL:
labels_out[:, 1:] = torch.from_numpy(labels)
img = img[:, :, ::-1].transpose(2, 0, 1)
img = np.ascontiguousarray(img)
return torch.from_numpy(img), labels_out, self.img_files[index], shapes
@staticmethod
def collate_fn(batch):
img, label, path, shapes = zip(*batch)
for i, l in enumerate(label):
l[:, 0] = i
return torch.stack(img, 0), torch.cat(label, 0), path, shapes
@staticmethod
def collate_fn4(batch):
img, label, path, shapes = zip(*batch)
n = len(shapes) // 4
img4, label4, path4, shapes4 = [], [], path[:n], shapes[:n]
ho = torch.tensor([[0., 0, 0, 1, 0, 0]])
wo = torch.tensor([[0., 0, 1, 0, 0, 0]])
s = torch.tensor([[1, 1, .5, .5, .5, .5]])
for i in range(n): i *= 4
if random.random() < 0.5:
im = F.interpolate(img[i].unsqueeze(0).float(), scale_factor=2., mode='bilinear', align_corners=False)[
0].type(img[i].type())
l = label[i]
else:
im = torch.cat((torch.cat((img[i], img[i + 1]), 1), torch.cat((img[i + 2], img[i + 3]), 1)), 2)
l = torch.cat((label[i], label[i + 1] + ho, label[i + 2] + wo, label[i + 3] + ho + wo), 0) * s
img4.append(im)
label4.append(l)
for i, l in enumerate(label4):
l[:, 0] = i
return torch.stack(img4, 0), torch.cat(label4, 0), path4, shapes4
def load_image(self, index):
img = self.imgs[index]
if img is None:
path = self.img_files[index]
img = cv2.imread(path)
assert img is not None, 'Image Not Found ' + path
h0, w0 = img.shape[:2]
r = self.img_size / max(h0, w0)
if r != 1:
img = cv2.resize(img, (int(w0 * r), int(h0 * r)),
interpolation=cv2.INTER_AREA if r < 1 and not self.augment else cv2.INTER_LINEAR)
return img, (h0, w0), img.shape[:2]
else:
return self.imgs[index], self.img_hw0[index], self.img_hw[index]
def augment_hsv(img, hgain=0.5, sgain=0.5, vgain=0.5):
if hgain or sgain or vgain:
r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1
hue, sat, val = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV))
dtype = img.dtype
x = np.arange(0, 256, dtype=r.dtype)
lut_hue = ((x * r[0]) % 180).astype(dtype)
lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)
lut_val = np.clip(x * r[2], 0, 255).astype(dtype)
img_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val)))
cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR, dst=img)
def hist_equalize(img, clahe=True, bgr=False):
yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV if bgr else cv2.COLOR_RGB2YUV)
if clahe:
c = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
yuv[:, :, 0] = c.apply(yuv[:, :, 0])
else:
yuv[:, :, 0] = cv2.equalizeHist(yuv[:, :, 0])
return cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR if bgr else cv2.COLOR_YUV2RGB)
def load_mosaic(self, index):
labels4, segments4 = [], []
s = self.img_size
yc, xc = [int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border]
indices = [index] + random.choices(self.indices, k=3)
for i, index in enumerate(indices):
img, _, (h, w) = load_image(self, index)
if i == 0:
img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8)
x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc
x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h
elif i == 1:
x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc
x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h
elif i == 2:
x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)
x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)
elif i == 3:
x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)
x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)
img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b]
padw = x1a - x1b
padh = y1a - y1b
labels, segments = self.labels[index].copy(), self.segments[index].copy()
if labels.size:
labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh)
segments = [xyn2xy(x, w, h, padw, padh) for x in segments]
labels4.append(labels)
segments4.extend(segments)
labels4 = np.concatenate(labels4, 0)
for x in (labels4[:, 1:], *segments4):
np.clip(x, 0, 2 * s, out=x)
img4, labels4, segments4 = copy_paste(img4, labels4, segments4, probability=self.hyp['copy_paste'])
img4, labels4 = random_perspective(img4, labels4, segments4,
degrees=self.hyp['degrees'],
translate=self.hyp['translate'],
scale=self.hyp['scale'],
shear=self.hyp['shear'],
perspective=self.hyp['perspective'],
border=self.mosaic_border)
return img4, labels4
def load_mosaic9(self, index):
labels9, segments9 = [], []
s = self.img_size
indices = [index] + random.choices(self.indices, k=8)
for i, index in enumerate(indices):
img, _, (h, w) = load_image(self, index)
if i == 0:
img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8)
h0, w0 = h, w
c = s, s, s + w, s + h
elif i == 1:
c = s, s - h, s + w, s
elif i == 2:
c = s + wp, s - h, s + wp + w, s
elif i == 3:
c = s + w0, s, s + w0 + w, s + h
elif i == 4:
c = s + w0, s + hp, s + w0 + w, s + hp + h
elif i == 5:
c = s + w0 - w, s + h0, s + w0, s + h0 + h
elif i == 6:
c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h
elif i == 7:
c = s - w, s + h0 - h, s, s + h0
elif i == 8:
c = s - w, s + h0 - hp - h, s, s + h0 - hp
padx, pady = c[:2]
x1, y1, x2, y2 = [max(x, 0) for x in c]
labels, segments = self.labels[index].copy(), self.segments[index].copy()
if labels.size:
labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padx, pady)
segments = [xyn2xy(x, w, h, padx, pady) for x in segments]
labels9.append(labels)
segments9.extend(segments)
img9[y1:y2, x1:x2] = img[y1 - pady:, x1 - padx:]
hp, wp = h, w
yc, xc = [int(random.uniform(0, s)) for _ in self.mosaic_border]
img9 = img9[yc:yc + 2 * s, xc:xc + 2 * s]
labels9 = np.concatenate(labels9, 0)
labels9[:, [1, 3]] -= xc
labels9[:, [2, 4]] -= yc
c = np.array([xc, yc])
segments9 = [x - c for x in segments9]
for x in (labels9[:, 1:], *segments9):
np.clip(x, 0, 2 * s, out=x)
img9, labels9 = random_perspective(img9, labels9, segments9,
degrees=self.hyp['degrees'],
translate=self.hyp['translate'],
scale=self.hyp['scale'],
shear=self.hyp['shear'],
perspective=self.hyp['perspective'],
border=self.mosaic_border)
return img9, labels9
def replicate(img, labels):
h, w = img.shape[:2]
boxes = labels[:, 1:].astype(int)
x1, y1, x2, y2 = boxes.T
s = ((x2 - x1) + (y2 - y1)) / 2
for i in s.argsort()[:round(s.size * 0.5)]:
x1b, y1b, x2b, y2b = boxes[i]
bh, bw = y2b - y1b, x2b - x1b
yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw))
x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh]
img[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b]
labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0)
return img, labels
def letterbox(img, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):
shape = img.shape[:2]
if isinstance(new_shape, int):
new_shape = (new_shape, new_shape)
r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
if not scaleup:
r = min(r, 1.0)
ratio = r, r
new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1]
if auto:
dw, dh = np.mod(dw, stride), np.mod(dh, stride)
elif scaleFill:
dw, dh = 0.0, 0.0
new_unpad = (new_shape[1], new_shape[0])
ratio = new_shape[1] / shape[1], new_shape[0] / shape[0]
dw /= 2
dh /= 2
if shape[::-1] != new_unpad:
img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)
top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color)
return img, ratio, (dw, dh)
def random_perspective(img, targets=(), segments=(), degrees=10, translate=.1, scale=.1, shear=10, perspective=0.0,
border=(0, 0)):
height = img.shape[0] + border[0] * 2
width = img.shape[1] + border[1] * 2
C = np.eye(3)
C[0, 2] = -img.shape[1] / 2
C[1, 2] = -img.shape[0] / 2
P = np.eye(3)
P[2, 0] = random.uniform(-perspective, perspective)
P[2, 1] = random.uniform(-perspective, perspective)
R = np.eye(3)
a = random.uniform(-degrees, degrees)
cale)
R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)
S = np.eye(3)
S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180)
S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180)
T = np.eye(3)
T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width
T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height
M = T @ S @ R @ P @ C
if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any():
if perspective:
img = cv2.warpPerspective(img, M, dsize=(width, height), borderValue=(114, 114, 114))
else:
img = cv2.warpAffine(img, M[:2], dsize=(width, height), borderValue=(114, 114, 114))
n = len(targets)
if n:
use_segments = any(x.any() for x in segments)
new = np.zeros((n, 4))
if use_segments:
segments = resample_segments(segments)
for i, segment in enumerate(segments):
xy = np.ones((len(segment), 3))
xy[:, :2] = segment
xy = xy @ M.T
xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]
new[i] = segment2box(xy, width, height)
else:
xy = np.ones((n * 4, 3))
xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2)
xy = xy @ M.T
xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8)
x = xy[:, [0, 2, 4, 6]]
y = xy[:, [1, 3, 5, 7]]
new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T
new[:, [0, 2]] = new[:, [0, 2]].clip(0, width)
new[:, [1, 3]] = new[:, [1, 3]].clip(0, height)
i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01 if use_segments else 0.10)
targets = targets[i]
targets[:, 1:5] = new[i]
return img, targets
def copy_paste(img, labels, segments, probability=0.5):
n = len(segments)
if probability and n:
h, w, c = img.shape
im_new = np.zeros(img.shape, np.uint8)
for j in random.sample(range(n), k=round(probability * n)):
l, s = labels[j], segments[j]
box = w - l[3], l[2], w - l[1], l[4]
ioa = bbox_ioa(box, labels[:, 1:5])
if (ioa < 0.30).all():
labels = np.concatenate((labels, [[l[0], *box]]), 0)
segments.append(np.concatenate((w - s[:, 0:1], s[:, 1:2]), 1))
cv2.drawContours(im_new, [segments[j].astype(np.int32)], -1, (255, 255, 255), cv2.FILLED)
result = cv2.bitwise_and(src1=img, src2=im_new)
result = cv2.flip(result, 1)
i = result > 0
i] = result[i] eturn img, labels, segments
def box_candidates(box1, box2, wh_thr=2, ar_thr=20, area_thr=0.1, eps=1e-16):
w1, h1 = box1[2] - box1[0], box1[3] - box1[1]
w2, h2 = box2[2] - box2[0], box2[3] - box2[1]
ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps))
return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr)
def cutout(image, labels):
h, w = image.shape[:2]
scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16
for s in scales:
mask_h = random.randint(1, int(h * s))
mask_w = random.randint(1, int(w * s))
xmin = max(0, random.randint(0, w) - mask_w // 2)
ymin = max(0, random.randint(0, h) - mask_h // 2)
xmax = min(w, xmin + mask_w)
ymax = min(h, ymin + mask_h)
image[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)]
if len(labels) and s > 0.03:
box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32)
ioa = bbox_ioa(box, labels[:, 1:5])
labels = labels[ioa < 0.60]
return labels
def create_folder(path='./new'):
if os.path.exists(path):
shutil.rmtree(path)
os.makedirs(path)
def flatten_recursive(path='../datasets/coco128'):
new_path = Path(path + '_flat')
create_folder(new_path)
for file in tqdm(glob.glob(str(Path(path)) + '/**/*.*', recursive=True)):
shutil.copyfile(file, new_path / Path(file).name)
def extract_boxes(path='../datasets/coco128'):
path = Path(path)
shutil.rmtree(path / 'classifier') if (path / 'classifier').is_dir() else None
files = list(path.rglob('*.*'))
n = len(files)
for im_file in tqdm(files, total=n):
if im_file.suffix[1:] in img_formats:
im = cv2.imread(str(im_file))[..., ::-1]
h, w = im.shape[:2]
lb_file = Path(img2label_paths([str(im_file)])[0])
if Path(lb_file).exists():
with open(lb_file, 'r') as f:
lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32)
for j, x in enumerate(lb):
c = int(x[0])
f = (path / 'classifier') / f'{c}' / f'{path.stem}_{im_file.stem}_{j}.jpg'
if not f.parent.is_dir():
f.parent.mkdir(parents=True)
b = x[1:] * [w, h, w, h]
b[2:] = b[2:] * 1.2 + 3
b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int)
b[[0, 2]] = np.clip(b[[0, 2]], 0, w)
b[[1, 3]] = np.clip(b[[1, 3]], 0, h)
assert cv2.imwrite(str(f), im[b[1]:b[3], b[0]:b[2]]), f'box failure in {f}'
def autosplit(path='../datasets/coco128/images', weights=(0.9, 0.1, 0.0), annotated_only=False):
path = Path(path)
files = sum([list(path.rglob(f"*.{img_ext}")) for img_ext in img_formats], [])
n = len(files)
random.seed(0)
indices = random.choices([0, 1, 2], weights=weights, k=n)
txt = ['autosplit_train.txt', 'autosplit_val.txt', 'autosplit_test.txt']
[(path.parent / x).unlink(missing_ok=True) for x in txt]
print(f'Autosplitting images from {path}' + ', using *.txt labeled images only' * annotated_only)
for i, img in tqdm(zip(indices, files), total=n):
if not annotated_only or Path(img2label_paths([str(img)])[0]).exists():
with open(path.parent / txt[i], 'a') as f:
f.write('./' + img.relative_to(path.parent).as_posix() + '\n')
def verify_image_label(args):
im_file, lb_file, prefix = args
nm, nf, ne, nc = 0, 0, 0, 0
try:
im = Image.open(im_file)
im.verify()
shape = exif_size(im)
assert (shape[0] > 9) & (shape[1] > 9), f'image size {shape} <10 pixels'
assert im.format.lower() in img_formats, f'invalid image format {im.format}'
if im.format.lower() in ('jpg', 'jpeg'):
with open(im_file, 'rb') as f:
f.seek(-2, 2)
assert f.read() == b'\xff\xd9', 'corrupted JPEG'
segments = []
if os.path.isfile(lb_file):
nf = 1
with open(lb_file, 'r') as f:
l = [x.split() for x in f.read().strip().splitlines() if len(x)]
if any([len(x) > 8 for x in l]):
classes = np.array([x[0] for x in l], dtype=np.float32)
segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in l]
l = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1)
l = np.array(l, dtype=np.float32)
if len(l):
assert l.shape[1] == 5, 'labels require 5 columns each'
assert (l >= 0).all(), 'negative labels'
assert (l[:, 1:] <= 1).all(), 'non-normalized or out of bounds coordinate labels'
assert np.unique(l, axis=0).shape[0] == l.shape[0], 'duplicate labels'
else:
ne = 1
l = np.zeros((0, 5), dtype=np.float32)
else:
nm = 1
l = np.zeros((0, 5), dtype=np.float32)
return im_file, l, shape, segments, nm, nf, ne, nc, ''
except Exception as e:
nc = 1
msg = f'{prefix}WARNING: Ignoring corrupted image and/or label {im_file}: {e}'
return [None, None, None, None, nm, nf, ne, nc, msg]
def dataset_stats(path='coco128.yaml', autodownload=False, verbose=False):
def round_labels(labels):
return [[int(c), *[round(x, 6) for x in points]] for c, *points in labels]
with open(check_file(path)) as f:
data = yaml.safe_load(f)
check_dataset(data, autodownload)
nc = data['nc']
stats = {'nc': nc, 'names': data['names']}
for split in 'train', 'val', 'test':
if data.get(split) is None:
stats[split] = None
continue
x = []
dataset = LoadImagesAndLabels(data[split], augment=False, rect=True)
if split == 'train':
cache_path = Path(dataset.label_files[0]).parent.with_suffix('.cache')
for label in tqdm(dataset.labels, total=dataset.n, desc='Statistics'):
x.append(np.bincount(label[:, 0].astype(int), minlength=nc))
x = np.array(x)
stats[split] = {'instance_stats': {'total': int(x.sum()), 'per_class': x.sum(0).tolist()},
'image_stats': {'total': dataset.n, 'unlabelled': int(np.all(x == 0, 1).sum()),
'per_class': (x > 0).sum(0).tolist()},
'labels': [{str(Path(k).name): round_labels(v.tolist())} for k, v in
zip(dataset.img_files, dataset.labels)]}
with open(cache_path.with_suffix('.json'), 'w') as f:
json.dump(stats, f)
if verbose:
print(json.dumps(stats, indent=2, sort_keys=False))
return stats
| true | true |
f7315650becb2c94bec9837ddd60b3d1e3e2b7d1 | 2,007 | py | Python | extra/face.py | Leyan529/ImageClassificationPL | a4be75f4525828100d8d278e46ff5dccd829af1a | [
"MIT"
] | null | null | null | extra/face.py | Leyan529/ImageClassificationPL | a4be75f4525828100d8d278e46ff5dccd829af1a | [
"MIT"
] | null | null | null | extra/face.py | Leyan529/ImageClassificationPL | a4be75f4525828100d8d278e46ff5dccd829af1a | [
"MIT"
] | null | null | null | import torch
import matplotlib.image as img
import cv2
import dlib
from imutils.face_utils import *
import numpy as np
# image = img.imread("extra//test.jpg")
# image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR) # opencvImage
dlib_path = 'extra//shape_predictor_68_face_landmarks.dat'
def get_face(img):
global detector, landmark_predictor
# 宣告臉部偵測器,以及載入預訓練的臉部特徵點模型
detector = dlib.get_frontal_face_detector()
landmark_predictor = dlib.shape_predictor(dlib_path)
# 產生臉部識別
face_rects = detector(img, 1)
for i, d in enumerate(face_rects):
# 讀取框左上右下座標
x1 = d.left()
y1 = d.top()
x2 = d.right()
y2 = d.bottom()
# 根據此座標範圍讀取臉部特徵點
shape = landmark_predictor(img, d)
# 將特徵點轉為numpy
shape = shape_to_np(shape) # (68,2)
# 透過dlib挖取臉孔部分,將臉孔圖片縮放至256*256的大小,並存放於pickle檔中
# 人臉圖像部分呢。很簡單,只要根據畫框的位置切取即可crop_img = img[y1:y2, x1:x2, :]
crop_img = img[y1:y2, x1:x2, :]
try:
resize_img = cv2.resize(crop_img, (512, 512))
# cv2.imshow("OpenCV",resize_img)
# cv2.waitKey()
return resize_img
except:
return np.array([0])
return np.array([0])
def predict_image(logger, image, model):
try:
face = get_face(image) # predict target
face = torch.tensor(face, dtype=torch.float32)/255 # normalize
face = face.permute(2, 0, 1).unsqueeze(0).cuda()
# model = torch.load('run\SCUT\pre_googlenet\experiment_6\pre_googlenet.pkl')
# model.load_state_dict(torch.load('run\SCUT\pre_googlenet\experiment_6\checkpoint.pth.tar')['state_dict'])
outputs = model(face) # [bsz, c, h, w]
_, predicted = torch.max(outputs.data, 1)
score = int(predicted.item()) * 20
# logger.info("Predict Score : {}".format(score))
return score
except Exception as e:
# print(e)
return 0 | 35.210526 | 116 | 0.605879 | import torch
import matplotlib.image as img
import cv2
import dlib
from imutils.face_utils import *
import numpy as np
extra//shape_predictor_68_face_landmarks.dat'
def get_face(img):
global detector, landmark_predictor
detector = dlib.get_frontal_face_detector()
landmark_predictor = dlib.shape_predictor(dlib_path)
face_rects = detector(img, 1)
for i, d in enumerate(face_rects):
x1 = d.left()
y1 = d.top()
x2 = d.right()
y2 = d.bottom()
shape = landmark_predictor(img, d)
shape = shape_to_np(shape)
crop_img = img[y1:y2, x1:x2, :]
try:
resize_img = cv2.resize(crop_img, (512, 512))
return resize_img
except:
return np.array([0])
return np.array([0])
def predict_image(logger, image, model):
try:
face = get_face(image)
face = torch.tensor(face, dtype=torch.float32)/255
face = face.permute(2, 0, 1).unsqueeze(0).cuda()
outputs = model(face)
_, predicted = torch.max(outputs.data, 1)
score = int(predicted.item()) * 20
return score
except Exception as e:
return 0 | true | true |
f731574329fa3890c3eac2e8b58b5c9c180f7338 | 1,636 | py | Python | src/Filtering/BinaryMathematicalMorphology/DilateABinaryImage/Code.py | justbennet/ITKExamples | cde3b1bfb396042050c399b4bae59c338cf646f2 | [
"Apache-2.0"
] | null | null | null | src/Filtering/BinaryMathematicalMorphology/DilateABinaryImage/Code.py | justbennet/ITKExamples | cde3b1bfb396042050c399b4bae59c338cf646f2 | [
"Apache-2.0"
] | null | null | null | src/Filtering/BinaryMathematicalMorphology/DilateABinaryImage/Code.py | justbennet/ITKExamples | cde3b1bfb396042050c399b4bae59c338cf646f2 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
# Copyright NumFOCUS
#
# 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.txt
#
# 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 sys
import itk
if len(sys.argv) != 4:
print("Usage: " + sys.argv[0] + " <inputImage> <outputImage> <radius>")
sys.exit(1)
inputImage = sys.argv[1]
outputImage = sys.argv[2]
radiusValue = int(sys.argv[3])
PixelType = itk.UC
Dimension = 2
ImageType = itk.Image[PixelType, Dimension]
ReaderType = itk.ImageFileReader[ImageType]
reader = ReaderType.New()
reader.SetFileName(inputImage)
StructuringElementType = itk.FlatStructuringElement[Dimension]
structuringElement = StructuringElementType.Ball(radiusValue)
DilateFilterType = itk.BinaryDilateImageFilter[ImageType,
ImageType,
StructuringElementType]
dilateFilter = DilateFilterType.New()
dilateFilter.SetInput(reader.GetOutput())
dilateFilter.SetKernel(structuringElement)
dilateFilter.SetForegroundValue(255)
WriterType = itk.ImageFileWriter[ImageType]
writer = WriterType.New()
writer.SetFileName(outputImage)
writer.SetInput(dilateFilter.GetOutput())
writer.Update()
| 30.296296 | 75 | 0.732274 |
import sys
import itk
if len(sys.argv) != 4:
print("Usage: " + sys.argv[0] + " <inputImage> <outputImage> <radius>")
sys.exit(1)
inputImage = sys.argv[1]
outputImage = sys.argv[2]
radiusValue = int(sys.argv[3])
PixelType = itk.UC
Dimension = 2
ImageType = itk.Image[PixelType, Dimension]
ReaderType = itk.ImageFileReader[ImageType]
reader = ReaderType.New()
reader.SetFileName(inputImage)
StructuringElementType = itk.FlatStructuringElement[Dimension]
structuringElement = StructuringElementType.Ball(radiusValue)
DilateFilterType = itk.BinaryDilateImageFilter[ImageType,
ImageType,
StructuringElementType]
dilateFilter = DilateFilterType.New()
dilateFilter.SetInput(reader.GetOutput())
dilateFilter.SetKernel(structuringElement)
dilateFilter.SetForegroundValue(255)
WriterType = itk.ImageFileWriter[ImageType]
writer = WriterType.New()
writer.SetFileName(outputImage)
writer.SetInput(dilateFilter.GetOutput())
writer.Update()
| true | true |
f731577f3eb816602726166e59d42f01b5f4b241 | 9,919 | py | Python | src/sasctl/utils/cli.py | brtieu/python-sasctl | 1eed427c39faaddda78dec4806f12f3f8964890e | [
"Apache-2.0"
] | 30 | 2019-07-12T00:18:21.000Z | 2022-03-18T08:36:35.000Z | src/sasctl/utils/cli.py | brtieu/python-sasctl | 1eed427c39faaddda78dec4806f12f3f8964890e | [
"Apache-2.0"
] | 89 | 2019-07-12T20:46:46.000Z | 2022-03-29T16:16:46.000Z | src/sasctl/utils/cli.py | brtieu/python-sasctl | 1eed427c39faaddda78dec4806f12f3f8964890e | [
"Apache-2.0"
] | 41 | 2019-07-11T15:08:55.000Z | 2022-01-10T05:30:50.000Z | #!/usr/bin/env python
# encoding: utf-8
#
# Copyright © 2019, SAS Institute Inc., Cary, NC, USA. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import argparse
import inspect
import json
import logging
import os
import pkgutil
import warnings
from collections import namedtuple, defaultdict
from importlib import import_module
from pprint import pprint
ArgInfo = namedtuple('ArgInfo', ['name', 'type', 'required', 'default', 'doc'])
def sasctl_command(name, subname=None):
"""Decorator that tags the function as being usable from the command line.
Parameters
----------
name : str
the name of the command that will be shown on the command line.
subname : str
the name of the service that the command will be listed under
Returns
-------
function
Examples
--------
Define a command called 'cmd' not associated with a service
>>> @sasctl_command('cmd')
>>> def func():
...
Define a command called 'cmd' associated with the 'svc' service
>>> @sasctl_command('svc', 'cmd')
>>> def func():
...
Define a command and allow it's name and service to be auto-assigned
>>> @sasctl_command
>>> def func():
...
"""
def decorator(func):
if isinstance(name, str):
if isinstance(subname, str):
command_name = subname
service_name = name
else:
command_name = name
service_name = subname
else:
command_name = func.__name__
if any(
command_name.startswith(x)
for x in ['list_', 'update_', 'get_', 'create_', 'delete_']
):
parts = command_name.split('_')
command_name = parts[0]
service_name = parts[-1]
else:
service_name = subname
def parse_args():
"""Retrieve argument metadata from function signature and docstring."""
arg_spec = inspect.getargspec(func)
defaults = list(arg_spec.defaults) if arg_spec.defaults is not None else []
required = [True] * (len(arg_spec.args) - len(defaults)) + [False] * len(
defaults
)
defaults = [None] * (len(arg_spec.args) - len(defaults)) + defaults
types = []
help_doc = []
doc = inspect.getdoc(func)
if doc and doc.find('Parameters\n'):
doc_lines = doc[doc.find('Parameters\n') :].splitlines()
doc_lines.pop(0) # First line is "Parameters"
if doc_lines and doc_lines[0].startswith('---'):
doc_lines.pop(
0
) # Discard ----------- line under "Parameters" heading
while doc_lines:
var = doc_lines.pop(0)
if var.startswith('Returns') or var.strip() == '':
break
if ':' in var:
types.append(var.split(':')[-1].strip())
else:
types.append('str')
if doc_lines and doc_lines[0].startswith(' '):
help_doc.append(doc_lines.pop(0).strip())
else:
help_doc.append('')
else:
types = ['str'] * len(arg_spec.args)
help_doc = [None] * len(arg_spec.args)
return [
ArgInfo(n, t, r, d, o)
for n, t, r, d, o in zip(
arg_spec.args, types, required, defaults, help_doc
)
]
func._cli_command = command_name
func._cli_service = service_name
func._cli_arguments = parse_args
return func
if callable(name):
# allow direct decoration without arguments
return decorator(name)
return decorator
def _find_services(module='sasctl'):
"""Recursively find all functions in all modules that have been decorated as CLI commands."""
m = __import__(module, fromlist=['']) # returns a module
def find_recurse(module, services):
for obj in dir(module):
obj = getattr(module, obj)
source_module = getattr(obj, '__module__', type(obj).__module__)
# Module-level functions that are tagged as commands
if hasattr(obj, '_cli_command') and hasattr(obj, '_cli_service'):
services[obj._cli_service][obj._cli_command] = obj
# Check methods on service classes
elif source_module.startswith('sasctl._services'):
for atr in dir(obj):
atr = getattr(obj, atr)
if hasattr(atr, '_cli_command') and hasattr(atr, '_cli_service'):
services[atr._cli_service][atr._cli_command] = atr
# recurse into submodules
submodules = pkgutil.iter_modules(getattr(module, '__path__', []))
for submodule in submodules:
# ModuleInfo returned py 3.6 has .name
# Tuple of (module_loader, name, ispkg) returned by older versions
submodule_name = getattr(submodule, 'name', submodule[1])
# TODO: Temporary until pzmm fully merged with sasctl
if submodule_name == 'pzmm':
continue
submodule = import_module('.' + submodule_name, package=module.__name__)
# if hasattr(submodule, 'name'):
# # ModuleInfo returned py 3.6
# submodule = import_module('.' + submodule.name, package=module.__name__)
# else:
# # Tuple of (module_loader, name, ispkg) returned by older versions
# submodule = import_module('.' + submodule[1], package=module.__name__)
services = find_recurse(submodule, services)
return services
services = find_recurse(m, defaultdict(dict))
return services
def _get_func_description(func):
description = getattr(func, '__doc__', '')
lines = description.split('\n')
if lines:
return lines[0]
def _build_parser(services):
from sasctl import __version__
# TODO: Set command docstring
# Create standard, top-level arguments
parser = argparse.ArgumentParser(
prog='sasctl', description='sasctl interacts with a SAS Viya environment.'
)
parser.add_argument(
'-k', '--insecure', action='store_true', help='skip SSL verification'
)
parser.add_argument(
'-f', '--format', choices=['json'], default='json', help='output format'
)
parser.add_argument('-v', '--verbose', action='count')
parser.add_argument(
'--version', action='version', version='%(prog)s ' + __version__
)
subparsers = parser.add_subparsers(title='service', dest='service')
subparsers.required = True
for service, commands in services.items():
service_parser = subparsers.add_parser(service)
service_subparser = service_parser.add_subparsers(
title='command', dest='command'
)
service_subparser.required = True
# Add the command and arguments for each command
for command in commands:
func = services[service][command]
cmd_parser = service_subparser.add_parser(
command, help=_get_func_description(func)
)
for arg in func._cli_arguments():
if arg.name in ('self', 'cls'):
continue
if arg.required:
cmd_parser.add_argument(arg.name, help=arg.doc)
else:
cmd_parser.add_argument(
'--' + arg.name,
required=arg.required,
default=arg.default,
help=arg.doc,
)
return parser
def main(args=None):
"""Main entry point when executed as a command line utility."""
from sasctl import Session, current_session
# Find all services and associated commands
services = _find_services()
parser = _build_parser(services)
args = parser.parse_args(args)
if args.verbose is None or args.verbose == 0:
lvl = logging.WARNING
elif args.verbose == 1:
lvl = logging.INFO
else:
lvl = logging.DEBUG
handler = logging.StreamHandler()
handler.setLevel(lvl)
logging.getLogger('sasctl.core').addHandler(handler)
logging.getLogger('sasctl.core').setLevel(lvl)
warnings.simplefilter('ignore')
func = services[args.service][args.command]
kwargs = vars(args).copy()
# Remove args that shouldn't be passed to the underlying command
for k in ['command', 'service', 'insecure', 'verbose', 'format']:
kwargs.pop(k, None)
username = os.environ.get('SASCTL_USER_NAME')
password = os.environ.get('SASCTL_PASSWORD')
server = os.environ.get('SASCTL_SERVER_NAME')
if server is None:
parser.error(
"Hostname must be specified in the 'SASCTL_SERVER_NAME' environment variable."
)
verify_ssl = not args.insecure
try:
# current_session() should never be set when executing from the
# command line but it allows us to provide a pre-created session
# during testing
with current_session() or Session(
server, username, password, verify_ssl=verify_ssl
):
result = func(**kwargs)
if isinstance(result, list):
pprint([str(x) for x in result])
elif isinstance(result, dict) and args.format == 'json':
print(json.dumps(result, indent=2))
else:
pprint(result)
except RuntimeError as e:
parser.error(e)
| 32.521311 | 97 | 0.569311 |
import argparse
import inspect
import json
import logging
import os
import pkgutil
import warnings
from collections import namedtuple, defaultdict
from importlib import import_module
from pprint import pprint
ArgInfo = namedtuple('ArgInfo', ['name', 'type', 'required', 'default', 'doc'])
def sasctl_command(name, subname=None):
def decorator(func):
if isinstance(name, str):
if isinstance(subname, str):
command_name = subname
service_name = name
else:
command_name = name
service_name = subname
else:
command_name = func.__name__
if any(
command_name.startswith(x)
for x in ['list_', 'update_', 'get_', 'create_', 'delete_']
):
parts = command_name.split('_')
command_name = parts[0]
service_name = parts[-1]
else:
service_name = subname
def parse_args():
arg_spec = inspect.getargspec(func)
defaults = list(arg_spec.defaults) if arg_spec.defaults is not None else []
required = [True] * (len(arg_spec.args) - len(defaults)) + [False] * len(
defaults
)
defaults = [None] * (len(arg_spec.args) - len(defaults)) + defaults
types = []
help_doc = []
doc = inspect.getdoc(func)
if doc and doc.find('Parameters\n'):
doc_lines = doc[doc.find('Parameters\n') :].splitlines()
doc_lines.pop(0)
if doc_lines and doc_lines[0].startswith('---'):
doc_lines.pop(
0
)
while doc_lines:
var = doc_lines.pop(0)
if var.startswith('Returns') or var.strip() == '':
break
if ':' in var:
types.append(var.split(':')[-1].strip())
else:
types.append('str')
if doc_lines and doc_lines[0].startswith(' '):
help_doc.append(doc_lines.pop(0).strip())
else:
help_doc.append('')
else:
types = ['str'] * len(arg_spec.args)
help_doc = [None] * len(arg_spec.args)
return [
ArgInfo(n, t, r, d, o)
for n, t, r, d, o in zip(
arg_spec.args, types, required, defaults, help_doc
)
]
func._cli_command = command_name
func._cli_service = service_name
func._cli_arguments = parse_args
return func
if callable(name):
return decorator(name)
return decorator
def _find_services(module='sasctl'):
m = __import__(module, fromlist=[''])
def find_recurse(module, services):
for obj in dir(module):
obj = getattr(module, obj)
source_module = getattr(obj, '__module__', type(obj).__module__)
if hasattr(obj, '_cli_command') and hasattr(obj, '_cli_service'):
services[obj._cli_service][obj._cli_command] = obj
elif source_module.startswith('sasctl._services'):
for atr in dir(obj):
atr = getattr(obj, atr)
if hasattr(atr, '_cli_command') and hasattr(atr, '_cli_service'):
services[atr._cli_service][atr._cli_command] = atr
submodules = pkgutil.iter_modules(getattr(module, '__path__', []))
for submodule in submodules:
submodule_name = getattr(submodule, 'name', submodule[1])
if submodule_name == 'pzmm':
continue
submodule = import_module('.' + submodule_name, package=module.__name__)
ces)
return services
services = find_recurse(m, defaultdict(dict))
return services
def _get_func_description(func):
description = getattr(func, '__doc__', '')
lines = description.split('\n')
if lines:
return lines[0]
def _build_parser(services):
from sasctl import __version__
parser = argparse.ArgumentParser(
prog='sasctl', description='sasctl interacts with a SAS Viya environment.'
)
parser.add_argument(
'-k', '--insecure', action='store_true', help='skip SSL verification'
)
parser.add_argument(
'-f', '--format', choices=['json'], default='json', help='output format'
)
parser.add_argument('-v', '--verbose', action='count')
parser.add_argument(
'--version', action='version', version='%(prog)s ' + __version__
)
subparsers = parser.add_subparsers(title='service', dest='service')
subparsers.required = True
for service, commands in services.items():
service_parser = subparsers.add_parser(service)
service_subparser = service_parser.add_subparsers(
title='command', dest='command'
)
service_subparser.required = True
for command in commands:
func = services[service][command]
cmd_parser = service_subparser.add_parser(
command, help=_get_func_description(func)
)
for arg in func._cli_arguments():
if arg.name in ('self', 'cls'):
continue
if arg.required:
cmd_parser.add_argument(arg.name, help=arg.doc)
else:
cmd_parser.add_argument(
'--' + arg.name,
required=arg.required,
default=arg.default,
help=arg.doc,
)
return parser
def main(args=None):
from sasctl import Session, current_session
services = _find_services()
parser = _build_parser(services)
args = parser.parse_args(args)
if args.verbose is None or args.verbose == 0:
lvl = logging.WARNING
elif args.verbose == 1:
lvl = logging.INFO
else:
lvl = logging.DEBUG
handler = logging.StreamHandler()
handler.setLevel(lvl)
logging.getLogger('sasctl.core').addHandler(handler)
logging.getLogger('sasctl.core').setLevel(lvl)
warnings.simplefilter('ignore')
func = services[args.service][args.command]
kwargs = vars(args).copy()
for k in ['command', 'service', 'insecure', 'verbose', 'format']:
kwargs.pop(k, None)
username = os.environ.get('SASCTL_USER_NAME')
password = os.environ.get('SASCTL_PASSWORD')
server = os.environ.get('SASCTL_SERVER_NAME')
if server is None:
parser.error(
"Hostname must be specified in the 'SASCTL_SERVER_NAME' environment variable."
)
verify_ssl = not args.insecure
try:
# current_session() should never be set when executing from the
# command line but it allows us to provide a pre-created session
# during testing
with current_session() or Session(
server, username, password, verify_ssl=verify_ssl
):
result = func(**kwargs)
if isinstance(result, list):
pprint([str(x) for x in result])
elif isinstance(result, dict) and args.format == 'json':
print(json.dumps(result, indent=2))
else:
pprint(result)
except RuntimeError as e:
parser.error(e)
| true | true |
f731586ef1b81b7d4f26fef5e91e60a95e44ab32 | 28 | py | Python | purectypes/struct_value.py | aguinet/purectypes | e1db225ba865468b1f0d2fe017a7291da41acbfd | [
"Apache-2.0"
] | 19 | 2020-02-22T12:29:39.000Z | 2021-10-02T02:36:01.000Z | purectypes/struct_value.py | aguinet/purectypes | e1db225ba865468b1f0d2fe017a7291da41acbfd | [
"Apache-2.0"
] | null | null | null | purectypes/struct_value.py | aguinet/purectypes | e1db225ba865468b1f0d2fe017a7291da41acbfd | [
"Apache-2.0"
] | 2 | 2020-02-22T12:29:46.000Z | 2020-10-11T18:48:53.000Z | class StructValue:
pass
| 9.333333 | 18 | 0.714286 | class StructValue:
pass
| true | true |
f731592f46955b17ebfec9140599ba5b56cb5dab | 33,850 | py | Python | mlflow/pyfunc/__init__.py | washcycle/mlflow | 5a60ab34a4cecfe0b9636f6df77c087faa8b6959 | [
"Apache-2.0"
] | 3 | 2018-10-16T16:34:46.000Z | 2020-01-08T09:34:34.000Z | mlflow/pyfunc/__init__.py | washcycle/mlflow | 5a60ab34a4cecfe0b9636f6df77c087faa8b6959 | [
"Apache-2.0"
] | null | null | null | mlflow/pyfunc/__init__.py | washcycle/mlflow | 5a60ab34a4cecfe0b9636f6df77c087faa8b6959 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
"""
The ``mlflow.pyfunc`` module defines a generic :ref:`filesystem format <pyfunc-filesystem-format>`
for Python models and provides utilities for saving to and loading from this format. The format is
self contained in the sense that it includes all necessary information for anyone to load it and
use it. Dependencies are either stored directly with the model or referenced via a Conda
environment.
The ``mlflow.pyfunc`` module also defines utilities for creating custom ``pyfunc`` models
using frameworks and inference logic that may not be natively included in MLflow. See
:ref:`pyfunc-create-custom`.
.. _pyfunc-filesystem-format:
*****************
Filesystem format
*****************
The Pyfunc format is defined as a directory structure containing all required data, code, and
configuration::
./dst-path/
./MLmodel: configuration
<code>: code packaged with the model (specified in the MLmodel file)
<data>: data packaged with the model (specified in the MLmodel file)
<env>: Conda environment definition (specified in the MLmodel file)
The directory structure may contain additional contents that can be referenced by the ``MLmodel``
configuration.
.. _pyfunc-model-config:
MLModel configuration
#####################
A Python model contains an ``MLmodel`` file in **python_function** format in its root with the
following parameters:
- loader_module [required]:
Python module that can load the model. Expected as module identifier
e.g. ``mlflow.sklearn``, it will be imported using ``importlib.import_module``.
The imported module must contain a function with the following signature::
_load_pyfunc(path: string) -> <pyfunc model>
The path argument is specified by the ``data`` parameter and may refer to a file or
directory.
- code [optional]:
Relative path to a directory containing the code packaged with this model.
All files and directories inside this directory are added to the Python path
prior to importing the model loader.
- data [optional]:
Relative path to a file or directory containing model data.
The path is passed to the model loader.
- env [optional]:
Relative path to an exported Conda environment. If present this environment
should be activated prior to running the model.
- Optionally, any additional parameters necessary for interpreting the serialized model in
``pyfunc`` format.
.. rubric:: Example
>>> tree example/sklearn_iris/mlruns/run1/outputs/linear-lr
::
├── MLmodel
├── code
│ ├── sklearn_iris.py
│
├── data
│ └── model.pkl
└── mlflow_env.yml
>>> cat example/sklearn_iris/mlruns/run1/outputs/linear-lr/MLmodel
::
python_function:
code: code
data: data/model.pkl
loader_module: mlflow.sklearn
env: mlflow_env.yml
main: sklearn_iris
.. _pyfunc-inference-api:
*************
Inference API
*************
The convention for pyfunc models is to have a ``predict`` method or function with the following
signature::
predict(model_input: pandas.DataFrame) -> [numpy.ndarray | pandas.Series | pandas.DataFrame]
This convention is relied on by other MLflow components.
.. _pyfunc-create-custom:
******************************
Creating custom Pyfunc models
******************************
MLflow's persistence modules provide convenience functions for creating models with the
``pyfunc`` flavor in a variety of machine learning frameworks (scikit-learn, Keras, Pytorch, and
more); however, they do not cover every use case. For example, you may want to create an MLflow
model with the ``pyfunc`` flavor using a framework that MLflow does not natively support.
Alternatively, you may want to build an MLflow model that executes custom logic when evaluating
queries, such as preprocessing and postprocessing routines. Therefore, ``mlflow.pyfunc``
provides utilities for creating ``pyfunc`` models from arbitrary code and model data.
The :meth:`save_model()` and :meth:`log_model()` methods are designed to support multiple workflows
for creating custom ``pyfunc`` models that incorporate custom inference logic and artifacts
that the logic may require.
An `artifact` is a file or directory, such as a serialized model or a CSV. For example, a
serialized TensorFlow graph is an artifact. An MLflow model directory is also an artifact.
.. _pyfunc-create-custom-workflows:
Workflows
#########
:meth:`save_model()` and :meth:`log_model()` support the following workflows:
1. Programmatically defining a new MLflow model, including its attributes and artifacts.
Given a set of artifact URIs, :meth:`save_model()` and :meth:`log_model()` can
automatically download artifacts from their URIs and create an MLflow model directory.
In this case, you must define a Python class which inherits from :class:`~PythonModel`,
defining ``predict()`` and, optionally, ``load_context()``. An instance of this class is
specified via the ``python_model`` parameter; it is automatically serialized and deserialized
as a Python class, including all of its attributes.
2. Interpreting pre-existing data as an MLflow model.
If you already have a directory containing model data, :meth:`save_model()` and
:meth:`log_model()` can import the data as an MLflow model. The ``data_path`` parameter
specifies the local filesystem path to the directory containing model data.
In this case, you must provide a Python module, called a `loader module`. The
loader module defines a ``_load_pyfunc()`` method that performs the following tasks:
- Load data from the specified ``data_path``. For example, this process may include
deserializing pickled Python objects or models or parsing CSV files.
- Construct and return a pyfunc-compatible model wrapper. As in the first
use case, this wrapper must define a ``predict()`` method that is used to evaluate
queries. ``predict()`` must adhere to the :ref:`pyfunc-inference-api`.
The ``loader_module`` parameter specifies the name of your loader module.
For an example loader module implementation, refer to the `loader module
implementation in mlflow.keras <https://github.com/mlflow/mlflow/blob/
74d75109aaf2975f5026104d6125bb30f4e3f744/mlflow/keras.py#L157-L187>`_.
.. _pyfunc-create-custom-selecting-workflow:
Which workflow is right for my use case?
########################################
We consider the first workflow to be more user-friendly and generally recommend it for the
following reasons:
- It automatically resolves and collects specified model artifacts.
- It automatically serializes and deserializes the ``python_model`` instance and all of
its attributes, reducing the amount of user logic that is required to load the model
- You can create Models using logic that is defined in the ``__main__`` scope. This allows
custom models to be constructed in interactive environments, such as notebooks and the Python
REPL.
You may prefer the second, lower-level workflow for the following reasons:
- Inference logic is always persisted as code, rather than a Python object. This makes logic
easier to inspect and modify later.
- If you have already collected all of your model data in a single location, the second
workflow allows it to be saved in MLflow format directly, without enumerating constituent
artifacts.
"""
import importlib
import logging
import numpy as np
import os
import pandas
import shutil
from copy import deepcopy
import mlflow
import mlflow.pyfunc.model
import mlflow.pyfunc.utils
from mlflow.models import Model
from mlflow.pyfunc.model import PythonModel, PythonModelContext, get_default_conda_env
from mlflow.tracking.artifact_utils import _download_artifact_from_uri
from mlflow.utils import PYTHON_VERSION, deprecated, get_major_minor_py_version
from mlflow.utils.file_utils import TempDir, _copy_file_or_tree
from mlflow.utils.model_utils import _get_flavor_configuration
from mlflow.exceptions import MlflowException
from mlflow.protos.databricks_pb2 import INVALID_PARAMETER_VALUE, RESOURCE_ALREADY_EXISTS
FLAVOR_NAME = "python_function"
MAIN = "loader_module"
CODE = "code"
DATA = "data"
ENV = "env"
PY_VERSION = "python_version"
_logger = logging.getLogger(__name__)
def add_to_model(model, loader_module, data=None, code=None, env=None, **kwargs):
"""
Add a ``pyfunc`` spec to the model configuration.
Defines ``pyfunc`` configuration schema. Caller can use this to create a valid ``pyfunc`` model
flavor out of an existing directory structure. For example, other model flavors can use this to
specify how to use their output as a ``pyfunc``.
NOTE:
All paths are relative to the exported model root directory.
:param model: Existing model.
:param loader_module: The module to be used to load the model.
:param data: Path to the model data.
:param code: Path to the code dependencies.
:param env: Conda environment.
:param kwargs: Additional key-value pairs to include in the ``pyfunc`` flavor specification.
Values must be YAML-serializable.
:return: Updated model configuration.
"""
parms = deepcopy(kwargs)
parms[MAIN] = loader_module
parms[PY_VERSION] = PYTHON_VERSION
if code:
parms[CODE] = code
if data:
parms[DATA] = data
if env:
parms[ENV] = env
return model.add_flavor(FLAVOR_NAME, **parms)
def _load_model_env(path):
"""
Get ENV file string from a model configuration stored in Python Function format.
Returned value is a model-relative path to a Conda Environment file,
or None if none was specified at model save time
"""
return _get_flavor_configuration(model_path=path, flavor_name=FLAVOR_NAME).get(ENV, None)
def load_model(model_uri, suppress_warnings=False):
"""
Load a model stored in Python function format.
:param model_uri: The location, in URI format, of the MLflow model. For example:
- ``/Users/me/path/to/local/model``
- ``relative/path/to/local/model``
- ``s3://my_bucket/path/to/model``
- ``runs:/<mlflow_run_id>/run-relative/path/to/model``
For more information about supported URI schemes, see
`Referencing Artifacts <https://www.mlflow.org/docs/latest/tracking.html#
artifact-locations>`_.
:param suppress_warnings: If ``True``, non-fatal warning messages associated with the model
loading process will be suppressed. If ``False``, these warning
messages will be emitted.
"""
return load_pyfunc(model_uri, suppress_warnings)
@deprecated("pyfunc.load_model", 1.0)
def load_pyfunc(model_uri, suppress_warnings=False):
"""
Load a model stored in Python function format.
:param model_uri: The location, in URI format, of the MLflow model. For example:
- ``/Users/me/path/to/local/model``
- ``relative/path/to/local/model``
- ``s3://my_bucket/path/to/model``
- ``runs:/<mlflow_run_id>/run-relative/path/to/model``
For more information about supported URI schemes, see
`Referencing Artifacts <https://www.mlflow.org/docs/latest/tracking.html#
artifact-locations>`_.
:param suppress_warnings: If ``True``, non-fatal warning messages associated with the model
loading process will be suppressed. If ``False``, these warning
messages will be emitted.
"""
local_model_path = _download_artifact_from_uri(artifact_uri=model_uri)
conf = _get_flavor_configuration(model_path=local_model_path, flavor_name=FLAVOR_NAME)
model_py_version = conf.get(PY_VERSION)
if not suppress_warnings:
_warn_potentially_incompatible_py_version_if_necessary(model_py_version=model_py_version)
if CODE in conf and conf[CODE]:
code_path = os.path.join(local_model_path, conf[CODE])
mlflow.pyfunc.utils._add_code_to_system_path(code_path=code_path)
data_path = os.path.join(local_model_path, conf[DATA]) if (DATA in conf) else local_model_path
return importlib.import_module(conf[MAIN])._load_pyfunc(data_path)
def _warn_potentially_incompatible_py_version_if_necessary(model_py_version=None):
"""
Compares the version of Python that was used to save a given model with the version
of Python that is currently running. If a major or minor version difference is detected,
logs an appropriate warning.
"""
if model_py_version is None:
_logger.warning(
"The specified model does not have a specified Python version. It may be"
" incompatible with the version of Python that is currently running: Python %s",
PYTHON_VERSION)
elif get_major_minor_py_version(model_py_version) != get_major_minor_py_version(PYTHON_VERSION):
_logger.warning(
"The version of Python that the model was saved in, `Python %s`, differs"
" from the version of Python that is currently running, `Python %s`,"
" and may be incompatible",
model_py_version, PYTHON_VERSION)
def spark_udf(spark, model_uri, result_type="double"):
"""
A Spark UDF that can be used to invoke the Python function formatted model.
Parameters passed to the UDF are forwarded to the model as a DataFrame where the names are
ordinals (0, 1, ...).
The predictions are filtered to contain only the columns that can be represented as the
``result_type``. If the ``result_type`` is string or array of strings, all predictions are
converted to string. If the result type is not an array type, the left most column with
matching type is returned.
>>> predict = mlflow.pyfunc.spark_udf(spark, "/my/local/model")
>>> df.withColumn("prediction", predict("name", "age")).show()
:param spark: A SparkSession object.
:param model_uri: The location, in URI format, of the MLflow model with the
:py:mod:`mlflow.pyfunc` flavor. For example:
- ``/Users/me/path/to/local/model``
- ``relative/path/to/local/model``
- ``s3://my_bucket/path/to/model``
- ``runs:/<mlflow_run_id>/run-relative/path/to/model``
For more information about supported URI schemes, see
`Referencing Artifacts <https://www.mlflow.org/docs/latest/tracking.html#
artifact-locations>`_.
:param result_type: the return type of the user-defined function. The value can be either a
:class:`pyspark.sql.types.DataType` object or a DDL-formatted type string. Only a primitive
type or an array ``pyspark.sql.types.ArrayType`` of primitive type are allowed.
The following classes of result type are supported:
- "int" or ``pyspark.sql.types.IntegerType``: The leftmost integer that can fit in an
``int32`` or an exception if there is none.
- "long" or ``pyspark.sql.types.LongType``: The leftmost long integer that can fit in an
``int64`` or an exception if there is none.
- ``ArrayType(IntegerType|LongType)``: All integer columns that can fit into the requested
size.
- "float" or ``pyspark.sql.types.FloatType``: The leftmost numeric result cast to
``float32`` or an exception if there is none.
- "double" or ``pyspark.sql.types.DoubleType``: The leftmost numeric result cast to
``double`` or an exception if there is none.
- ``ArrayType(FloatType|DoubleType)``: All numeric columns cast to the requested type or
an exception if there are no numeric columns.
- "string" or ``pyspark.sql.types.StringType``: The leftmost column converted to ``string``.
- ``ArrayType(StringType)``: All columns converted to ``string``.
:return: Spark UDF that applies the model's ``predict`` method to the data and returns a
type specified by ``result_type``, which by default is a double.
"""
# Scope Spark import to this method so users don't need pyspark to use non-Spark-related
# functionality.
from mlflow.pyfunc.spark_model_cache import SparkModelCache
from pyspark.sql.functions import pandas_udf
from pyspark.sql.types import _parse_datatype_string
from pyspark.sql.types import ArrayType, DataType
from pyspark.sql.types import DoubleType, IntegerType, FloatType, LongType, StringType
if not isinstance(result_type, DataType):
result_type = _parse_datatype_string(result_type)
elem_type = result_type
if isinstance(elem_type, ArrayType):
elem_type = elem_type.elementType
supported_types = [IntegerType, LongType, FloatType, DoubleType, StringType]
if not any([isinstance(elem_type, x) for x in supported_types]):
raise MlflowException(
message="Invalid result_type '{}'. Result type can only be one of or an array of one "
"of the following types types: {}".format(str(elem_type), str(supported_types)),
error_code=INVALID_PARAMETER_VALUE)
local_model_path = _download_artifact_from_uri(artifact_uri=model_uri)
archive_path = SparkModelCache.add_local_model(spark, local_model_path)
def predict(*args):
model = SparkModelCache.get_or_load(archive_path)
schema = {str(i): arg for i, arg in enumerate(args)}
# Explicitly pass order of columns to avoid lexicographic ordering (i.e., 10 < 2)
columns = [str(i) for i, _ in enumerate(args)]
pdf = pandas.DataFrame(schema, columns=columns)
result = model.predict(pdf)
if not isinstance(result, pandas.DataFrame):
result = pandas.DataFrame(data=result)
elif type(elem_type) == IntegerType:
result = result.select_dtypes([np.byte, np.ubyte, np.short, np.ushort,
np.int32]).astype(np.int32)
elif type(elem_type) == LongType:
result = result.select_dtypes([np.byte, np.ubyte, np.short, np.ushort, np.int, np.long])
elif type(elem_type) == FloatType:
result = result.select_dtypes(include=(np.number,)).astype(np.float32)
elif type(elem_type) == DoubleType:
result = result.select_dtypes(include=(np.number,)).astype(np.float64)
if len(result.columns) == 0:
raise MlflowException(
message="The the model did not produce any values compatible with the requested "
"type '{}'. Consider requesting udf with StringType or "
"Arraytype(StringType).".format(str(elem_type)),
error_code=INVALID_PARAMETER_VALUE)
if type(elem_type) == StringType:
result = result.applymap(str)
if type(result_type) == ArrayType:
return pandas.Series([row[1].values for row in result.iterrows()])
else:
return result[result.columns[0]]
return pandas_udf(predict, result_type)
def save_model(path, loader_module=None, data_path=None, code_path=None, conda_env=None,
mlflow_model=Model(), python_model=None, artifacts=None, **kwargs):
"""
save_model(path, loader_module=None, data_path=None, code_path=None, conda_env=None,\
mlflow_model=Model(), python_model=None, artifacts=None)
Save a Pyfunc model with custom inference logic and optional data dependencies to a path on the
local filesystem.
For information about the workflows that this method supports, please see :ref:`"workflows for
creating custom pyfunc models" <pyfunc-create-custom-workflows>` and
:ref:`"which workflow is right for my use case?" <pyfunc-create-custom-selecting-workflow>`.
Note that the parameters for the first workflow: ``loader_module``, ``data_path`` and the
parameters for the second workflow: ``python_model``, ``artifacts``, cannot be
specified together.
:param path: The path to which to save the Python model.
:param loader_module: The name of the Python module that is used to load the model
from ``data_path``. This module must define a method with the prototype
``_load_pyfunc(data_path)``. If not ``None``, this module and its
dependencies must be included in one of the following locations:
- The MLflow library.
- Package(s) listed in the model's Conda environment, specified by
the ``conda_env`` parameter.
- One or more of the files specified by the ``code_path`` parameter.
:param data_path: Path to a file or directory containing model data.
:param code_path: A list of local filesystem paths to Python file dependencies (or directories
containing file dependencies). These files are *prepended* to the system
path before the model is loaded.
:param conda_env: Either a dictionary representation of a Conda environment or the path to a
Conda environment yaml file. This decribes the environment this model should
be run in. If ``python_model`` is not ``None``, the Conda environment must
at least specify the dependencies contained in
:func:`get_default_conda_env()`. If ``None``, the default
:func:`get_default_conda_env()` environment is added to the
model. The following is an *example* dictionary representation of a Conda
environment::
{
'name': 'mlflow-env',
'channels': ['defaults'],
'dependencies': [
'python=3.7.0',
'cloudpickle==0.5.8'
]
}
:param mlflow_model: :py:mod:`mlflow.models.Model` configuration to which to add the
**python_function** flavor.
:param python_model: An instance of a subclass of :class:`~PythonModel`. This class is
serialized using the CloudPickle library. Any dependencies of the class
should be included in one of the following locations:
- The MLflow library.
- Package(s) listed in the model's Conda environment, specified by
the ``conda_env`` parameter.
- One or more of the files specified by the ``code_path`` parameter.
Note: If the class is imported from another module, as opposed to being
defined in the ``__main__`` scope, the defining module should also be
included in one of the listed locations.
:param artifacts: A dictionary containing ``<name, artifact_uri>`` entries. Remote artifact URIs
are resolved to absolute filesystem paths, producing a dictionary of
``<name, absolute_path>`` entries. ``python_model`` can reference these
resolved entries as the ``artifacts`` property of the ``context`` parameter
in :func:`PythonModel.load_context() <mlflow.pyfunc.PythonModel.load_context>`
and :func:`PythonModel.predict() <mlflow.pyfunc.PythonModel.predict>`.
For example, consider the following ``artifacts`` dictionary::
{
"my_file": "s3://my-bucket/path/to/my/file"
}
In this case, the ``"my_file"`` artifact is downloaded from S3. The
``python_model`` can then refer to ``"my_file"`` as an absolute filesystem
path via ``context.artifacts["my_file"]``.
If ``None``, no artifacts are added to the model.
"""
mlflow_model = kwargs.pop('model', mlflow_model)
if len(kwargs) > 0:
raise TypeError("save_model() got unexpected keyword arguments: {}".format(kwargs))
first_argument_set = {
"loader_module": loader_module,
"data_path": data_path,
}
second_argument_set = {
"artifacts": artifacts,
"python_model": python_model,
}
first_argument_set_specified = any([item is not None for item in first_argument_set.values()])
second_argument_set_specified = any([item is not None for item in second_argument_set.values()])
if first_argument_set_specified and second_argument_set_specified:
raise MlflowException(
message=(
"The following sets of parameters cannot be specified together: {first_set_keys}"
" and {second_set_keys}. All parameters in one set must be `None`. Instead, found"
" the following values: {first_set_entries} and {second_set_entries}".format(
first_set_keys=first_argument_set.keys(),
second_set_keys=second_argument_set.keys(),
first_set_entries=first_argument_set,
second_set_entries=second_argument_set)),
error_code=INVALID_PARAMETER_VALUE)
elif (loader_module is None) and (python_model is None):
raise MlflowException(
message="Either `loader_module` or `python_model` must be specified!",
error_code=INVALID_PARAMETER_VALUE)
if first_argument_set_specified:
return _save_model_with_loader_module_and_data_path(
path=path, loader_module=loader_module, data_path=data_path,
code_paths=code_path, conda_env=conda_env, mlflow_model=mlflow_model)
elif second_argument_set_specified:
return mlflow.pyfunc.model._save_model_with_class_artifacts_params(
path=path, python_model=python_model, artifacts=artifacts, conda_env=conda_env,
code_paths=code_path, mlflow_model=mlflow_model)
def log_model(artifact_path, loader_module=None, data_path=None, code_path=None, conda_env=None,
python_model=None, artifacts=None):
"""
Log a Pyfunc model with custom inference logic and optional data dependencies as an MLflow
artifact for the current run.
For information about the workflows that this method supports, see :ref:`Workflows for
creating custom pyfunc models <pyfunc-create-custom-workflows>` and
:ref:`Which workflow is right for my use case? <pyfunc-create-custom-selecting-workflow>`.
You cannot specify the parameters for the first workflow: ``loader_module``, ``data_path``
and the parameters for the second workflow: ``python_model``, ``artifacts`` together.
:param artifact_path: The run-relative artifact path to which to log the Python model.
:param loader_module: The name of the Python module that is used to load the model
from ``data_path``. This module must define a method with the prototype
``_load_pyfunc(data_path)``. If not ``None``, this module and its
dependencies must be included in one of the following locations:
- The MLflow library.
- Package(s) listed in the model's Conda environment, specified by
the ``conda_env`` parameter.
- One or more of the files specified by the ``code_path`` parameter.
:param data_path: Path to a file or directory containing model data.
:param code_path: A list of local filesystem paths to Python file dependencies (or directories
containing file dependencies). These files are *prepended* to the system
path before the model is loaded.
:param conda_env: Either a dictionary representation of a Conda environment or the path to a
Conda environment yaml file. This decribes the environment this model should
be run in. If ``python_model`` is not ``None``, the Conda environment must
at least specify the dependencies contained in
:func:`get_default_conda_env()`. If `None`, the default
:func:`get_default_conda_env()` environment is added to the
model. The following is an *example* dictionary representation of a Conda
environment::
{
'name': 'mlflow-env',
'channels': ['defaults'],
'dependencies': [
'python=3.7.0',
'cloudpickle==0.5.8'
]
}
:param python_model: An instance of a subclass of :class:`~PythonModel`. This class is
serialized using the CloudPickle library. Any dependencies of the class
should be included in one of the following locations:
- The MLflow library.
- Package(s) listed in the model's Conda environment, specified by
the ``conda_env`` parameter.
- One or more of the files specified by the ``code_path`` parameter.
Note: If the class is imported from another module, as opposed to being
defined in the ``__main__`` scope, the defining module should also be
included in one of the listed locations.
:param artifacts: A dictionary containing ``<name, artifact_uri>`` entries. Remote artifact URIs
are resolved to absolute filesystem paths, producing a dictionary of
``<name, absolute_path>`` entries. ``python_model`` can reference these
resolved entries as the ``artifacts`` property of the ``context`` parameter
in :func:`PythonModel.load_context() <mlflow.pyfunc.PythonModel.load_context>`
and :func:`PythonModel.predict() <mlflow.pyfunc.PythonModel.predict>`.
For example, consider the following ``artifacts`` dictionary::
{
"my_file": "s3://my-bucket/path/to/my/file"
}
In this case, the ``"my_file"`` artifact is downloaded from S3. The
``python_model`` can then refer to ``"my_file"`` as an absolute filesystem
path via ``context.artifacts["my_file"]``.
If ``None``, no artifacts are added to the model.
"""
return Model.log(artifact_path=artifact_path,
flavor=mlflow.pyfunc,
loader_module=loader_module,
data_path=data_path,
code_path=code_path,
python_model=python_model,
artifacts=artifacts,
conda_env=conda_env)
def _save_model_with_loader_module_and_data_path(path, loader_module, data_path=None,
code_paths=None, conda_env=None,
mlflow_model=Model()):
"""
Export model as a generic Python function model.
:param path: The path to which to save the Python model.
:param loader_module: The name of the Python module that is used to load the model
from ``data_path``. This module must define a method with the prototype
``_load_pyfunc(data_path)``.
:param data_path: Path to a file or directory containing model data.
:param code_paths: A list of local filesystem paths to Python file dependencies (or directories
containing file dependencies). These files are *prepended* to the system
path before the model is loaded.
:param conda_env: Either a dictionary representation of a Conda environment or the path to a
Conda environment yaml file. If provided, this decribes the environment
this model should be run in.
:return: Model configuration containing model info.
"""
if os.path.exists(path):
raise MlflowException(
message="Path '{}' already exists".format(path),
error_code=RESOURCE_ALREADY_EXISTS)
os.makedirs(path)
code = None
data = None
env = None
if data_path is not None:
model_file = _copy_file_or_tree(src=data_path, dst=path, dst_dir="data")
data = model_file
if code_paths is not None:
for code_path in code_paths:
_copy_file_or_tree(src=code_path, dst=path, dst_dir="code")
code = "code"
if conda_env is not None:
shutil.copy(src=conda_env, dst=os.path.join(path, "mlflow_env.yml"))
env = "mlflow_env.yml"
mlflow.pyfunc.add_to_model(
mlflow_model, loader_module=loader_module, code=code, data=data, env=env)
mlflow_model.save(os.path.join(path, 'MLmodel'))
return mlflow_model
loader_template = """
import importlib
import os
import sys
def load_pyfunc():
{update_path}return importlib.import_module('{main}')._load_pyfunc('{data_path}')
"""
| 46.883657 | 100 | 0.65288 |
import importlib
import logging
import numpy as np
import os
import pandas
import shutil
from copy import deepcopy
import mlflow
import mlflow.pyfunc.model
import mlflow.pyfunc.utils
from mlflow.models import Model
from mlflow.pyfunc.model import PythonModel, PythonModelContext, get_default_conda_env
from mlflow.tracking.artifact_utils import _download_artifact_from_uri
from mlflow.utils import PYTHON_VERSION, deprecated, get_major_minor_py_version
from mlflow.utils.file_utils import TempDir, _copy_file_or_tree
from mlflow.utils.model_utils import _get_flavor_configuration
from mlflow.exceptions import MlflowException
from mlflow.protos.databricks_pb2 import INVALID_PARAMETER_VALUE, RESOURCE_ALREADY_EXISTS
FLAVOR_NAME = "python_function"
MAIN = "loader_module"
CODE = "code"
DATA = "data"
ENV = "env"
PY_VERSION = "python_version"
_logger = logging.getLogger(__name__)
def add_to_model(model, loader_module, data=None, code=None, env=None, **kwargs):
parms = deepcopy(kwargs)
parms[MAIN] = loader_module
parms[PY_VERSION] = PYTHON_VERSION
if code:
parms[CODE] = code
if data:
parms[DATA] = data
if env:
parms[ENV] = env
return model.add_flavor(FLAVOR_NAME, **parms)
def _load_model_env(path):
return _get_flavor_configuration(model_path=path, flavor_name=FLAVOR_NAME).get(ENV, None)
def load_model(model_uri, suppress_warnings=False):
return load_pyfunc(model_uri, suppress_warnings)
@deprecated("pyfunc.load_model", 1.0)
def load_pyfunc(model_uri, suppress_warnings=False):
local_model_path = _download_artifact_from_uri(artifact_uri=model_uri)
conf = _get_flavor_configuration(model_path=local_model_path, flavor_name=FLAVOR_NAME)
model_py_version = conf.get(PY_VERSION)
if not suppress_warnings:
_warn_potentially_incompatible_py_version_if_necessary(model_py_version=model_py_version)
if CODE in conf and conf[CODE]:
code_path = os.path.join(local_model_path, conf[CODE])
mlflow.pyfunc.utils._add_code_to_system_path(code_path=code_path)
data_path = os.path.join(local_model_path, conf[DATA]) if (DATA in conf) else local_model_path
return importlib.import_module(conf[MAIN])._load_pyfunc(data_path)
def _warn_potentially_incompatible_py_version_if_necessary(model_py_version=None):
if model_py_version is None:
_logger.warning(
"The specified model does not have a specified Python version. It may be"
" incompatible with the version of Python that is currently running: Python %s",
PYTHON_VERSION)
elif get_major_minor_py_version(model_py_version) != get_major_minor_py_version(PYTHON_VERSION):
_logger.warning(
"The version of Python that the model was saved in, `Python %s`, differs"
" from the version of Python that is currently running, `Python %s`,"
" and may be incompatible",
model_py_version, PYTHON_VERSION)
def spark_udf(spark, model_uri, result_type="double"):
# functionality.
from mlflow.pyfunc.spark_model_cache import SparkModelCache
from pyspark.sql.functions import pandas_udf
from pyspark.sql.types import _parse_datatype_string
from pyspark.sql.types import ArrayType, DataType
from pyspark.sql.types import DoubleType, IntegerType, FloatType, LongType, StringType
if not isinstance(result_type, DataType):
result_type = _parse_datatype_string(result_type)
elem_type = result_type
if isinstance(elem_type, ArrayType):
elem_type = elem_type.elementType
supported_types = [IntegerType, LongType, FloatType, DoubleType, StringType]
if not any([isinstance(elem_type, x) for x in supported_types]):
raise MlflowException(
message="Invalid result_type '{}'. Result type can only be one of or an array of one "
"of the following types types: {}".format(str(elem_type), str(supported_types)),
error_code=INVALID_PARAMETER_VALUE)
local_model_path = _download_artifact_from_uri(artifact_uri=model_uri)
archive_path = SparkModelCache.add_local_model(spark, local_model_path)
def predict(*args):
model = SparkModelCache.get_or_load(archive_path)
schema = {str(i): arg for i, arg in enumerate(args)}
# Explicitly pass order of columns to avoid lexicographic ordering (i.e., 10 < 2)
columns = [str(i) for i, _ in enumerate(args)]
pdf = pandas.DataFrame(schema, columns=columns)
result = model.predict(pdf)
if not isinstance(result, pandas.DataFrame):
result = pandas.DataFrame(data=result)
elif type(elem_type) == IntegerType:
result = result.select_dtypes([np.byte, np.ubyte, np.short, np.ushort,
np.int32]).astype(np.int32)
elif type(elem_type) == LongType:
result = result.select_dtypes([np.byte, np.ubyte, np.short, np.ushort, np.int, np.long])
elif type(elem_type) == FloatType:
result = result.select_dtypes(include=(np.number,)).astype(np.float32)
elif type(elem_type) == DoubleType:
result = result.select_dtypes(include=(np.number,)).astype(np.float64)
if len(result.columns) == 0:
raise MlflowException(
message="The the model did not produce any values compatible with the requested "
"type '{}'. Consider requesting udf with StringType or "
"Arraytype(StringType).".format(str(elem_type)),
error_code=INVALID_PARAMETER_VALUE)
if type(elem_type) == StringType:
result = result.applymap(str)
if type(result_type) == ArrayType:
return pandas.Series([row[1].values for row in result.iterrows()])
else:
return result[result.columns[0]]
return pandas_udf(predict, result_type)
def save_model(path, loader_module=None, data_path=None, code_path=None, conda_env=None,
mlflow_model=Model(), python_model=None, artifacts=None, **kwargs):
mlflow_model = kwargs.pop('model', mlflow_model)
if len(kwargs) > 0:
raise TypeError("save_model() got unexpected keyword arguments: {}".format(kwargs))
first_argument_set = {
"loader_module": loader_module,
"data_path": data_path,
}
second_argument_set = {
"artifacts": artifacts,
"python_model": python_model,
}
first_argument_set_specified = any([item is not None for item in first_argument_set.values()])
second_argument_set_specified = any([item is not None for item in second_argument_set.values()])
if first_argument_set_specified and second_argument_set_specified:
raise MlflowException(
message=(
"The following sets of parameters cannot be specified together: {first_set_keys}"
" and {second_set_keys}. All parameters in one set must be `None`. Instead, found"
" the following values: {first_set_entries} and {second_set_entries}".format(
first_set_keys=first_argument_set.keys(),
second_set_keys=second_argument_set.keys(),
first_set_entries=first_argument_set,
second_set_entries=second_argument_set)),
error_code=INVALID_PARAMETER_VALUE)
elif (loader_module is None) and (python_model is None):
raise MlflowException(
message="Either `loader_module` or `python_model` must be specified!",
error_code=INVALID_PARAMETER_VALUE)
if first_argument_set_specified:
return _save_model_with_loader_module_and_data_path(
path=path, loader_module=loader_module, data_path=data_path,
code_paths=code_path, conda_env=conda_env, mlflow_model=mlflow_model)
elif second_argument_set_specified:
return mlflow.pyfunc.model._save_model_with_class_artifacts_params(
path=path, python_model=python_model, artifacts=artifacts, conda_env=conda_env,
code_paths=code_path, mlflow_model=mlflow_model)
def log_model(artifact_path, loader_module=None, data_path=None, code_path=None, conda_env=None,
python_model=None, artifacts=None):
return Model.log(artifact_path=artifact_path,
flavor=mlflow.pyfunc,
loader_module=loader_module,
data_path=data_path,
code_path=code_path,
python_model=python_model,
artifacts=artifacts,
conda_env=conda_env)
def _save_model_with_loader_module_and_data_path(path, loader_module, data_path=None,
code_paths=None, conda_env=None,
mlflow_model=Model()):
if os.path.exists(path):
raise MlflowException(
message="Path '{}' already exists".format(path),
error_code=RESOURCE_ALREADY_EXISTS)
os.makedirs(path)
code = None
data = None
env = None
if data_path is not None:
model_file = _copy_file_or_tree(src=data_path, dst=path, dst_dir="data")
data = model_file
if code_paths is not None:
for code_path in code_paths:
_copy_file_or_tree(src=code_path, dst=path, dst_dir="code")
code = "code"
if conda_env is not None:
shutil.copy(src=conda_env, dst=os.path.join(path, "mlflow_env.yml"))
env = "mlflow_env.yml"
mlflow.pyfunc.add_to_model(
mlflow_model, loader_module=loader_module, code=code, data=data, env=env)
mlflow_model.save(os.path.join(path, 'MLmodel'))
return mlflow_model
loader_template = """
import importlib
import os
import sys
def load_pyfunc():
{update_path}return importlib.import_module('{main}')._load_pyfunc('{data_path}')
"""
| true | true |
f7315a0806862ec68601ee3196af37bdc53af7a3 | 3,235 | py | Python | pypureclient/flasharray/FA_2_5/models/certificate_signing_request_response.py | Flav-STOR-WL/py-pure-client | 03b889c997d90380ac5d6380ca5d5432792d3e89 | [
"BSD-2-Clause"
] | 14 | 2018-12-07T18:30:27.000Z | 2022-02-22T09:12:33.000Z | pypureclient/flasharray/FA_2_5/models/certificate_signing_request_response.py | Flav-STOR-WL/py-pure-client | 03b889c997d90380ac5d6380ca5d5432792d3e89 | [
"BSD-2-Clause"
] | 28 | 2019-09-17T21:03:52.000Z | 2022-03-29T22:07:35.000Z | pypureclient/flasharray/FA_2_5/models/certificate_signing_request_response.py | Flav-STOR-WL/py-pure-client | 03b889c997d90380ac5d6380ca5d5432792d3e89 | [
"BSD-2-Clause"
] | 15 | 2020-06-11T15:50:08.000Z | 2022-03-21T09:27:25.000Z | # coding: utf-8
"""
FlashArray REST API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 2.5
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re
import six
import typing
from ....properties import Property
if typing.TYPE_CHECKING:
from pypureclient.flasharray.FA_2_5 import models
class CertificateSigningRequestResponse(object):
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'items': 'list[CertificateSigningRequest]'
}
attribute_map = {
'items': 'items'
}
required_args = {
}
def __init__(
self,
items=None, # type: List[models.CertificateSigningRequest]
):
"""
Keyword args:
items (list[CertificateSigningRequest])
"""
if items is not None:
self.items = items
def __setattr__(self, key, value):
if key not in self.attribute_map:
raise KeyError("Invalid key `{}` for `CertificateSigningRequestResponse`".format(key))
self.__dict__[key] = value
def __getattribute__(self, item):
value = object.__getattribute__(self, item)
if isinstance(value, Property):
raise AttributeError
else:
return value
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
if hasattr(self, attr):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(CertificateSigningRequestResponse, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, CertificateSigningRequestResponse):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| 28.883929 | 105 | 0.559505 |
import pprint
import re
import six
import typing
from ....properties import Property
if typing.TYPE_CHECKING:
from pypureclient.flasharray.FA_2_5 import models
class CertificateSigningRequestResponse(object):
swagger_types = {
'items': 'list[CertificateSigningRequest]'
}
attribute_map = {
'items': 'items'
}
required_args = {
}
def __init__(
self,
items=None,
):
if items is not None:
self.items = items
def __setattr__(self, key, value):
if key not in self.attribute_map:
raise KeyError("Invalid key `{}` for `CertificateSigningRequestResponse`".format(key))
self.__dict__[key] = value
def __getattribute__(self, item):
value = object.__getattribute__(self, item)
if isinstance(value, Property):
raise AttributeError
else:
return value
def to_dict(self):
result = {}
for attr, _ in six.iteritems(self.swagger_types):
if hasattr(self, attr):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(CertificateSigningRequestResponse, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
return pprint.pformat(self.to_dict())
def __repr__(self):
return self.to_str()
def __eq__(self, other):
if not isinstance(other, CertificateSigningRequestResponse):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
| true | true |
f7315a1e62e3e9a93eec26f0b1922799b57e4925 | 6,815 | py | Python | resources.py | vermeulendivan/qgis-pipelineplanner | b0d0c05626401b874a193fe358eec6146a204fff | [
"MIT"
] | null | null | null | resources.py | vermeulendivan/qgis-pipelineplanner | b0d0c05626401b874a193fe358eec6146a204fff | [
"MIT"
] | null | null | null | resources.py | vermeulendivan/qgis-pipelineplanner | b0d0c05626401b874a193fe358eec6146a204fff | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# Resource object code
#
# Created by: The Resource Compiler for PyQt5 (Qt v5.15.2)
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore
qt_resource_data = b"\
\x00\x00\x04\xa5\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x18\x00\x00\x00\x18\x08\x02\x00\x00\x00\x6f\x15\xaa\xaf\
\x00\x00\x00\x01\x73\x52\x47\x42\x00\xae\xce\x1c\xe9\x00\x00\x00\
\x04\x67\x41\x4d\x41\x00\x00\xb1\x8f\x0b\xfc\x61\x05\x00\x00\x00\
\x09\x70\x48\x59\x73\x00\x00\x0e\xc3\x00\x00\x0e\xc3\x01\xc7\x6f\
\xa8\x64\x00\x00\x04\x3a\x49\x44\x41\x54\x38\x4f\x75\x54\x4d\x6c\
\x1b\x45\x14\xde\x99\x59\xaf\x77\x37\xf6\xfa\x67\xe3\xfc\x37\x4e\
\xdb\x38\x71\xd4\xa2\x26\x8d\x15\x01\x25\x50\x21\x90\x80\x94\x22\
\x50\x85\x84\xf8\xb9\x14\x2e\x88\x6b\x6f\x08\x71\xe4\xcc\x95\x1e\
\xb9\x00\xe2\xc0\x21\x91\x88\xe0\xc0\x6f\xd5\x9f\x10\x08\x24\x4d\
\x71\x12\x8c\x9d\x1f\x37\xfe\x8f\x7f\xd6\xde\x5d\xef\xf0\x66\xd7\
\x4e\xd2\x24\x3c\x7d\x7e\xfe\xe6\xcd\x9b\x99\xf7\x66\xe7\x3d\xf4\
\xee\xcd\x87\xdc\x31\x41\x08\x51\x4a\x5b\x83\xb6\x80\xb1\xc5\x4e\
\x12\x0c\xd3\xc7\x05\x26\x5a\xec\x90\x38\x0b\x40\xf6\xa9\x43\x40\
\x03\x60\xa3\x16\x7b\x14\xf4\x10\x8e\x0c\x21\x52\xa6\x31\x86\x4d\
\x98\x76\x96\xfc\xdf\x46\x4c\x30\x66\xf1\x82\x3a\x4c\xda\xda\xb1\
\xb0\x7f\x1b\x1c\x30\xf8\x1d\x03\x01\x80\x27\x05\xe2\x22\x56\xc0\
\x5d\xf7\xf1\x55\x82\x2d\x8c\xed\x10\x08\xd8\x6d\xf0\x14\xb8\x0d\
\x84\xde\xff\x3c\x03\x11\xb2\x5c\xb9\xc3\x77\x09\x16\x36\x1c\xf1\
\xd5\xf3\xcb\xb3\xb7\x7f\x9a\xcf\x66\x33\x3d\xfd\xe1\xfe\xd8\x6b\
\xfc\xe0\x25\x0e\xb1\xac\x1c\x81\xf0\x1d\x21\x53\xd7\x6e\xb0\x5c\
\x20\xed\x76\xb6\x10\x89\x43\xc6\x54\x23\xbb\xf8\xe5\xad\xb5\xd2\
\xc0\xd3\xd7\x83\x82\x46\xd5\xd1\x95\xef\x6e\x7a\x04\x4b\xea\x3b\
\xcf\xe2\x6a\x39\xb7\x40\x1e\xbf\x76\xa3\xba\x1d\x2f\xaf\xdd\x31\
\x77\xe3\x8d\xc2\xa6\x4b\x09\x11\xc1\x0d\x3b\x89\xc8\xb8\x20\x6e\
\x7c\xbb\x52\x3e\x3b\xfd\xa6\x20\x2b\x21\xba\xe3\x1a\xb9\x12\x1c\
\x9e\xfa\x6b\xee\x53\xb5\xbb\x5f\x54\xc3\x70\x38\x66\x5b\x38\xa7\
\x22\x6c\x54\x0b\xb5\x74\x82\x77\x89\x1e\x91\xb8\xab\x49\xf3\x9f\
\x5f\x7a\x45\x3d\xe0\x6e\x0e\x07\xf4\x1f\x7e\xbd\x35\x18\x7b\xd9\
\xb9\x35\xf6\xa5\x30\xe7\xeb\x8b\x84\xa7\xdf\xc9\x2e\x7e\xcd\x59\
\x26\xb1\x37\xc2\x70\x8f\x8e\x9e\x54\x0a\x97\x2f\x86\x87\xd4\xa6\
\x80\x0d\x2c\x78\xdc\x54\xf3\xee\x3d\x38\x6d\x25\x55\x7d\xd3\xd0\
\xb9\x71\xef\xde\x98\x5c\x39\x23\xd5\x09\x35\x82\x82\x25\xf3\x5c\
\x78\xf2\x25\xf8\x40\xe5\xc4\x42\x23\x93\x34\x8b\x69\x4b\xaf\xd9\
\x1f\x10\x91\xf1\xd8\x93\x9a\x56\xee\x52\x88\x22\xd4\x2d\x4e\x28\
\x6c\xfd\xb1\x9d\x29\xf1\x84\x56\x8a\xe9\xfb\xcb\x4b\xc8\xac\x62\
\xa3\x24\x59\xe5\x52\x6e\x53\xd2\x8b\x11\x55\x1a\x10\x0d\xa3\x5e\
\xc2\x5a\xa1\xc7\x2b\xd5\x1f\xae\x15\xd6\x17\xb1\x1c\x14\x3c\x7e\
\xf4\xd4\xcc\x75\x49\x12\x89\x59\x10\x5c\x44\x19\x7a\x76\xe3\xee\
\x17\xb2\xbf\x27\x3a\x12\x11\x50\x23\xf1\x6f\xd2\x32\xaa\xc9\x64\
\xca\x34\xf4\xde\xfe\x53\x6e\x51\xf6\x07\x42\xb2\xc7\xcf\x51\x53\
\xea\x50\x46\xcf\x3d\xd1\x28\x6f\xaf\xef\x54\xca\xa6\xa0\xc6\x66\
\x48\xef\xe0\xd9\xc4\x46\x3c\x95\x88\xbb\xdc\x72\xa8\x37\x22\xba\
\xac\xe5\xfb\xeb\xe5\x9a\xde\xa8\x15\xe1\xfd\xa6\x52\x5b\x5a\xad\
\xaa\x35\x2c\x35\x18\xec\x1e\x1c\xf3\xfa\x3b\xe1\xb2\x8c\x86\x06\
\xd9\x99\x14\x69\xd5\xbc\xe0\x96\x75\xdd\x8a\xf6\xfb\xc9\xf4\xd5\
\xf7\xca\xc5\x82\x3f\x10\x98\x88\x5d\x1a\x9f\x98\x0c\xf5\x0e\xfd\
\x76\xef\xe7\xca\x5e\xae\xb2\x57\xec\xf4\xcb\xe9\x9c\xa6\x19\x96\
\x41\x85\xa9\xd8\xc4\xed\xc5\xf8\x46\x62\x2b\x57\xac\xbd\x7a\xf5\
\x85\x3b\x0b\xbf\x17\xca\xf5\xdd\xf4\xa6\x4e\x45\xd3\xa4\xb5\x7c\
\x8a\xc7\xc1\x33\xd1\x8b\x42\xb7\xd2\x9c\xb9\xf2\x3c\xe6\x9a\x4b\
\x4b\x5b\x13\xe3\xe7\x75\xc3\xd0\x6a\xb5\x6c\x76\xb3\xa7\xa7\x33\
\x93\x17\x9b\x4d\x8b\xe7\x79\xad\x5a\x84\x67\x2a\xf0\x56\x40\x91\
\x57\x56\xd7\x38\x9c\x94\x50\xad\xdb\x0a\xd5\x9b\xb5\xbd\xf4\x2a\
\x79\xf1\x83\x4f\x1a\xe9\xd5\x48\x34\xaa\xaa\x41\x77\xb0\xef\xde\
\x96\x29\x76\x85\x3b\x3a\x07\x7c\x5d\x7d\x16\x12\x2a\x3b\x7f\x47\
\xa2\xe7\x02\xc1\x60\x40\x91\x20\x17\x9f\xe2\x7d\xfb\x8d\xd7\x67\
\xe7\xbe\xa9\x68\x3a\xa6\x0d\x8f\x0c\xcf\x6e\x98\x5a\x0d\x53\xdb\
\x45\x1f\xce\xe7\x39\x4a\x11\x6d\xc2\xe3\x66\xc5\xd3\xae\x16\xe7\
\xe9\x2f\xcd\x7e\x96\xbe\x3b\x77\xe1\xf2\x2b\x5e\x62\x78\x4e\x3d\
\xe6\xa3\xd5\x3f\x97\x16\x74\x29\x64\xe5\x13\xd9\x74\x6a\x70\xec\
\x19\x57\x47\x97\x32\x36\xc9\x4b\x02\xfa\x68\x3e\x67\x2f\x39\x41\
\xe0\xc9\x82\x64\xe2\x0b\x6b\x3f\x7e\x65\x94\x76\x79\x97\xe0\x0e\
\x9d\x1e\x7d\xee\x2d\x8f\xda\xc7\x65\x1e\x34\xeb\xba\xd0\xd1\x4d\
\x3b\x7c\x54\x12\x99\xf3\xc7\xdf\xe7\xda\x15\x7a\x82\x80\x99\x4d\
\x22\xce\x6a\x9a\x50\x06\xd0\x2f\x8e\xfa\xb6\x07\xf0\x1d\xed\x86\
\xc0\xea\x00\xf4\x23\x40\x36\x60\x16\x34\x71\x11\xd6\x58\x0e\xec\
\xac\x05\x1c\xd4\x39\x5b\xde\x92\x03\x66\x0b\x6b\x5a\xc4\x21\x4e\
\xe7\x62\x86\x16\x01\x3b\xc1\xc8\x86\x43\xec\x23\x9c\x9a\x3c\xf0\
\x6a\x01\x84\xf5\x36\x1b\x4e\x9f\xe3\x08\x41\x0e\x5a\x3e\x87\xa6\
\x18\xda\xac\xdd\xf4\x6c\x10\xb6\x0c\x40\x89\x73\x8c\x3d\x3c\xe2\
\xd3\xbe\x81\xb6\x1b\x8f\x39\x06\x02\x40\xfb\x80\x09\x76\x38\x84\
\xed\xd8\xed\x44\xf6\xb5\xbd\x04\xb9\x6c\xbb\x33\xcb\x13\xf4\x1f\
\x7b\xd5\xbe\x4b\xfc\x0a\xbc\x91\x00\x00\x00\x00\x49\x45\x4e\x44\
\xae\x42\x60\x82\
"
qt_resource_name = b"\
\x00\x07\
\x07\x3b\xe0\xb3\
\x00\x70\
\x00\x6c\x00\x75\x00\x67\x00\x69\x00\x6e\x00\x73\
\x00\x10\
\x0f\x65\x03\xa2\
\x00\x70\
\x00\x69\x00\x70\x00\x65\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x70\x00\x6c\x00\x61\x00\x6e\x00\x6e\x00\x65\x00\x72\
\x00\x08\
\x0a\x61\x5a\xa7\
\x00\x69\
\x00\x63\x00\x6f\x00\x6e\x00\x2e\x00\x70\x00\x6e\x00\x67\
"
qt_resource_struct_v1 = b"\
\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x01\
\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x02\
\x00\x00\x00\x14\x00\x02\x00\x00\x00\x01\x00\x00\x00\x03\
\x00\x00\x00\x3a\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\
"
qt_resource_struct_v2 = b"\
\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x01\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x02\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x00\x14\x00\x02\x00\x00\x00\x01\x00\x00\x00\x03\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x00\x3a\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\
\x00\x00\x01\x7a\x2e\x14\x2c\xa2\
"
qt_version = [int(v) for v in QtCore.qVersion().split('.')]
if qt_version < [5, 8, 0]:
rcc_version = 1
qt_resource_struct = qt_resource_struct_v1
else:
rcc_version = 2
qt_resource_struct = qt_resource_struct_v2
def qInitResources():
QtCore.qRegisterResourceData(rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data)
def qCleanupResources():
QtCore.qUnregisterResourceData(rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data)
qInitResources()
| 49.028777 | 122 | 0.711812 |
from PyQt5 import QtCore
qt_resource_data = b"\
\x00\x00\x04\xa5\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x18\x00\x00\x00\x18\x08\x02\x00\x00\x00\x6f\x15\xaa\xaf\
\x00\x00\x00\x01\x73\x52\x47\x42\x00\xae\xce\x1c\xe9\x00\x00\x00\
\x04\x67\x41\x4d\x41\x00\x00\xb1\x8f\x0b\xfc\x61\x05\x00\x00\x00\
\x09\x70\x48\x59\x73\x00\x00\x0e\xc3\x00\x00\x0e\xc3\x01\xc7\x6f\
\xa8\x64\x00\x00\x04\x3a\x49\x44\x41\x54\x38\x4f\x75\x54\x4d\x6c\
\x1b\x45\x14\xde\x99\x59\xaf\x77\x37\xf6\xfa\x67\xe3\xfc\x37\x4e\
\xdb\x38\x71\xd4\xa2\x26\x8d\x15\x01\x25\x50\x21\x90\x80\x94\x22\
\x50\x85\x84\xf8\xb9\x14\x2e\x88\x6b\x6f\x08\x71\xe4\xcc\x95\x1e\
\xb9\x00\xe2\xc0\x21\x91\x88\xe0\xc0\x6f\xd5\x9f\x10\x08\x24\x4d\
\x71\x12\x8c\x9d\x1f\x37\xfe\x8f\x7f\xd6\xde\x5d\xef\xf0\x66\xd7\
\x4e\xd2\x24\x3c\x7d\x7e\xfe\xe6\xcd\x9b\x99\xf7\x66\xe7\x3d\xf4\
\xee\xcd\x87\xdc\x31\x41\x08\x51\x4a\x5b\x83\xb6\x80\xb1\xc5\x4e\
\x12\x0c\xd3\xc7\x05\x26\x5a\xec\x90\x38\x0b\x40\xf6\xa9\x43\x40\
\x03\x60\xa3\x16\x7b\x14\xf4\x10\x8e\x0c\x21\x52\xa6\x31\x86\x4d\
\x98\x76\x96\xfc\xdf\x46\x4c\x30\x66\xf1\x82\x3a\x4c\xda\xda\xb1\
\xb0\x7f\x1b\x1c\x30\xf8\x1d\x03\x01\x80\x27\x05\xe2\x22\x56\xc0\
\x5d\xf7\xf1\x55\x82\x2d\x8c\xed\x10\x08\xd8\x6d\xf0\x14\xb8\x0d\
\x84\xde\xff\x3c\x03\x11\xb2\x5c\xb9\xc3\x77\x09\x16\x36\x1c\xf1\
\xd5\xf3\xcb\xb3\xb7\x7f\x9a\xcf\x66\x33\x3d\xfd\xe1\xfe\xd8\x6b\
\xfc\xe0\x25\x0e\xb1\xac\x1c\x81\xf0\x1d\x21\x53\xd7\x6e\xb0\x5c\
\x20\xed\x76\xb6\x10\x89\x43\xc6\x54\x23\xbb\xf8\xe5\xad\xb5\xd2\
\xc0\xd3\xd7\x83\x82\x46\xd5\xd1\x95\xef\x6e\x7a\x04\x4b\xea\x3b\
\xcf\xe2\x6a\x39\xb7\x40\x1e\xbf\x76\xa3\xba\x1d\x2f\xaf\xdd\x31\
\x77\xe3\x8d\xc2\xa6\x4b\x09\x11\xc1\x0d\x3b\x89\xc8\xb8\x20\x6e\
\x7c\xbb\x52\x3e\x3b\xfd\xa6\x20\x2b\x21\xba\xe3\x1a\xb9\x12\x1c\
\x9e\xfa\x6b\xee\x53\xb5\xbb\x5f\x54\xc3\x70\x38\x66\x5b\x38\xa7\
\x22\x6c\x54\x0b\xb5\x74\x82\x77\x89\x1e\x91\xb8\xab\x49\xf3\x9f\
\x5f\x7a\x45\x3d\xe0\x6e\x0e\x07\xf4\x1f\x7e\xbd\x35\x18\x7b\xd9\
\xb9\x35\xf6\xa5\x30\xe7\xeb\x8b\x84\xa7\xdf\xc9\x2e\x7e\xcd\x59\
\x26\xb1\x37\xc2\x70\x8f\x8e\x9e\x54\x0a\x97\x2f\x86\x87\xd4\xa6\
\x80\x0d\x2c\x78\xdc\x54\xf3\xee\x3d\x38\x6d\x25\x55\x7d\xd3\xd0\
\xb9\x71\xef\xde\x98\x5c\x39\x23\xd5\x09\x35\x82\x82\x25\xf3\x5c\
\x78\xf2\x25\xf8\x40\xe5\xc4\x42\x23\x93\x34\x8b\x69\x4b\xaf\xd9\
\x1f\x10\x91\xf1\xd8\x93\x9a\x56\xee\x52\x88\x22\xd4\x2d\x4e\x28\
\x6c\xfd\xb1\x9d\x29\xf1\x84\x56\x8a\xe9\xfb\xcb\x4b\xc8\xac\x62\
\xa3\x24\x59\xe5\x52\x6e\x53\xd2\x8b\x11\x55\x1a\x10\x0d\xa3\x5e\
\xc2\x5a\xa1\xc7\x2b\xd5\x1f\xae\x15\xd6\x17\xb1\x1c\x14\x3c\x7e\
\xf4\xd4\xcc\x75\x49\x12\x89\x59\x10\x5c\x44\x19\x7a\x76\xe3\xee\
\x17\xb2\xbf\x27\x3a\x12\x11\x50\x23\xf1\x6f\xd2\x32\xaa\xc9\x64\
\xca\x34\xf4\xde\xfe\x53\x6e\x51\xf6\x07\x42\xb2\xc7\xcf\x51\x53\
\xea\x50\x46\xcf\x3d\xd1\x28\x6f\xaf\xef\x54\xca\xa6\xa0\xc6\x66\
\x48\xef\xe0\xd9\xc4\x46\x3c\x95\x88\xbb\xdc\x72\xa8\x37\x22\xba\
\xac\xe5\xfb\xeb\xe5\x9a\xde\xa8\x15\xe1\xfd\xa6\x52\x5b\x5a\xad\
\xaa\x35\x2c\x35\x18\xec\x1e\x1c\xf3\xfa\x3b\xe1\xb2\x8c\x86\x06\
\xd9\x99\x14\x69\xd5\xbc\xe0\x96\x75\xdd\x8a\xf6\xfb\xc9\xf4\xd5\
\xf7\xca\xc5\x82\x3f\x10\x98\x88\x5d\x1a\x9f\x98\x0c\xf5\x0e\xfd\
\x76\xef\xe7\xca\x5e\xae\xb2\x57\xec\xf4\xcb\xe9\x9c\xa6\x19\x96\
\x41\x85\xa9\xd8\xc4\xed\xc5\xf8\x46\x62\x2b\x57\xac\xbd\x7a\xf5\
\x85\x3b\x0b\xbf\x17\xca\xf5\xdd\xf4\xa6\x4e\x45\xd3\xa4\xb5\x7c\
\x8a\xc7\xc1\x33\xd1\x8b\x42\xb7\xd2\x9c\xb9\xf2\x3c\xe6\x9a\x4b\
\x4b\x5b\x13\xe3\xe7\x75\xc3\xd0\x6a\xb5\x6c\x76\xb3\xa7\xa7\x33\
\x93\x17\x9b\x4d\x8b\xe7\x79\xad\x5a\x84\x67\x2a\xf0\x56\x40\x91\
\x57\x56\xd7\x38\x9c\x94\x50\xad\xdb\x0a\xd5\x9b\xb5\xbd\xf4\x2a\
\x79\xf1\x83\x4f\x1a\xe9\xd5\x48\x34\xaa\xaa\x41\x77\xb0\xef\xde\
\x96\x29\x76\x85\x3b\x3a\x07\x7c\x5d\x7d\x16\x12\x2a\x3b\x7f\x47\
\xa2\xe7\x02\xc1\x60\x40\x91\x20\x17\x9f\xe2\x7d\xfb\x8d\xd7\x67\
\xe7\xbe\xa9\x68\x3a\xa6\x0d\x8f\x0c\xcf\x6e\x98\x5a\x0d\x53\xdb\
\x45\x1f\xce\xe7\x39\x4a\x11\x6d\xc2\xe3\x66\xc5\xd3\xae\x16\xe7\
\xe9\x2f\xcd\x7e\x96\xbe\x3b\x77\xe1\xf2\x2b\x5e\x62\x78\x4e\x3d\
\xe6\xa3\xd5\x3f\x97\x16\x74\x29\x64\xe5\x13\xd9\x74\x6a\x70\xec\
\x19\x57\x47\x97\x32\x36\xc9\x4b\x02\xfa\x68\x3e\x67\x2f\x39\x41\
\xe0\xc9\x82\x64\xe2\x0b\x6b\x3f\x7e\x65\x94\x76\x79\x97\xe0\x0e\
\x9d\x1e\x7d\xee\x2d\x8f\xda\xc7\x65\x1e\x34\xeb\xba\xd0\xd1\x4d\
\x3b\x7c\x54\x12\x99\xf3\xc7\xdf\xe7\xda\x15\x7a\x82\x80\x99\x4d\
\x22\xce\x6a\x9a\x50\x06\xd0\x2f\x8e\xfa\xb6\x07\xf0\x1d\xed\x86\
\xc0\xea\x00\xf4\x23\x40\x36\x60\x16\x34\x71\x11\xd6\x58\x0e\xec\
\xac\x05\x1c\xd4\x39\x5b\xde\x92\x03\x66\x0b\x6b\x5a\xc4\x21\x4e\
\xe7\x62\x86\x16\x01\x3b\xc1\xc8\x86\x43\xec\x23\x9c\x9a\x3c\xf0\
\x6a\x01\x84\xf5\x36\x1b\x4e\x9f\xe3\x08\x41\x0e\x5a\x3e\x87\xa6\
\x18\xda\xac\xdd\xf4\x6c\x10\xb6\x0c\x40\x89\x73\x8c\x3d\x3c\xe2\
\xd3\xbe\x81\xb6\x1b\x8f\x39\x06\x02\x40\xfb\x80\x09\x76\x38\x84\
\xed\xd8\xed\x44\xf6\xb5\xbd\x04\xb9\x6c\xbb\x33\xcb\x13\xf4\x1f\
\x7b\xd5\xbe\x4b\xfc\x0a\xbc\x91\x00\x00\x00\x00\x49\x45\x4e\x44\
\xae\x42\x60\x82\
"
qt_resource_name = b"\
\x00\x07\
\x07\x3b\xe0\xb3\
\x00\x70\
\x00\x6c\x00\x75\x00\x67\x00\x69\x00\x6e\x00\x73\
\x00\x10\
\x0f\x65\x03\xa2\
\x00\x70\
\x00\x69\x00\x70\x00\x65\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x70\x00\x6c\x00\x61\x00\x6e\x00\x6e\x00\x65\x00\x72\
\x00\x08\
\x0a\x61\x5a\xa7\
\x00\x69\
\x00\x63\x00\x6f\x00\x6e\x00\x2e\x00\x70\x00\x6e\x00\x67\
"
qt_resource_struct_v1 = b"\
\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x01\
\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x02\
\x00\x00\x00\x14\x00\x02\x00\x00\x00\x01\x00\x00\x00\x03\
\x00\x00\x00\x3a\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\
"
qt_resource_struct_v2 = b"\
\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x01\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x02\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x00\x14\x00\x02\x00\x00\x00\x01\x00\x00\x00\x03\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x00\x3a\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\
\x00\x00\x01\x7a\x2e\x14\x2c\xa2\
"
qt_version = [int(v) for v in QtCore.qVersion().split('.')]
if qt_version < [5, 8, 0]:
rcc_version = 1
qt_resource_struct = qt_resource_struct_v1
else:
rcc_version = 2
qt_resource_struct = qt_resource_struct_v2
def qInitResources():
QtCore.qRegisterResourceData(rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data)
def qCleanupResources():
QtCore.qUnregisterResourceData(rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data)
qInitResources()
| true | true |
f7315ba8d23659f4ee2ea63c31b028bd2c878b21 | 182 | py | Python | problem0153.py | kmarcini/Project-Euler-Python | d644e8e1ec4fac70a9ab407ad5e1f0a75547c8d3 | [
"BSD-3-Clause"
] | null | null | null | problem0153.py | kmarcini/Project-Euler-Python | d644e8e1ec4fac70a9ab407ad5e1f0a75547c8d3 | [
"BSD-3-Clause"
] | null | null | null | problem0153.py | kmarcini/Project-Euler-Python | d644e8e1ec4fac70a9ab407ad5e1f0a75547c8d3 | [
"BSD-3-Clause"
] | null | null | null | ###########################
#
# #153 Investigating Gaussian Integers - Project Euler
# https://projecteuler.net/problem=153
#
# Code by Kevin Marciniak
#
###########################
| 20.222222 | 54 | 0.516484 | true | true | |
f7315e9ebfe36931ca1757fcf4e6d4f8dd4ad184 | 2,810 | py | Python | .history/src/modules/test_plot/test_plot_20190927183934.py | mattzakh/mattplotlib | 5e9bc779d8c1b7074549615ab6790a9f7163cd59 | [
"MIT"
] | null | null | null | .history/src/modules/test_plot/test_plot_20190927183934.py | mattzakh/mattplotlib | 5e9bc779d8c1b7074549615ab6790a9f7163cd59 | [
"MIT"
] | 5 | 2020-03-24T17:44:10.000Z | 2021-08-23T20:22:20.000Z | .history/src/modules/test_plot/test_plot_20190927183934.py | mattzakh/mattplotlib | 5e9bc779d8c1b7074549615ab6790a9f7163cd59 | [
"MIT"
] | null | null | null | import numpy as np
import matplotlib.pyplot as plt
# plt.style.use('../notebooks/test.mplstyle')
import seaborn as sns
from logs import logDecorator as lD
import jsonref, pprint
config = jsonref.load(open('../config/config.json'))
logBase = config['logging']['logBase'] + '.modules.test_plot.test_plot'
@lD.log(logBase + '.doSomething')
def doSomething(logger):
'''print a line
This function simply prints a single line
Parameters
----------
logger : {logging.Logger}
The logger used for logging error information
'''
with plt.style.context('../notebooks/test.mplstyle'):
w = 7.2
fig = plt.figure(figsize=(w, w/1.6)) #, edgecolor='k', linewidth=2)
ax = {}
ax[0] = plt.axes([0.10, 0.10, 0.35, 0.30])
ax[1] = plt.axes([0.55, 0.10, 0.35, 0.30])
ax[2] = plt.axes([0.10, 0.57, 0.35, 0.30])
ax[3] = plt.axes([0.55, 0.57, 0.35, 0.30])
[ax[0].plot([1,2,3],np.random.randint([1,2,3],[10,9,8], size=3), marker='', label=f'line {i}') for i in range(4)]
[ax[1].plot([1,2,3],np.random.randint([1,2,3],[10,9,8], size=3), linestyle='', label=f'marker {i}') for i in range(4)]
params = ((10, 10), (4, 12), (50, 12), (6, 55))
for a, b in params:
values = np.random.beta(a, b, size=10000)
ax[2].hist(values, histtype="stepfilled", bins=30,
alpha=0.2, density=True)
mean, cov = [0, 2], [(1, .5), (.5, 1)]
x, y = np.random.multivariate_normal(mean, cov, size=50).T
# ax[3] = sns.kdeplot(x, linestyle='-', marker='', label='hist')#, marker='')
fig.suptitle('Times New Roman')
[ax[i].set_title(f'ax{i} Title') for i in range(4)]
[ax[i].set_xlabel(f'ax{i} xlabel') for i in range(4)]
[ax[i].set_ylabel(f'ax{i} ylabel') for i in range(4)]
[ax[i].legend(loc='upper right') for i in range(4)]
ax[3].set_xlabel(r'ax3 $a_i \sin(2\pi fx_i)$ label');
plt.savefig('test.svg')
return
@lD.log(logBase + '.main')
def main(logger, resultsDict):
'''main function for module1
This function finishes all the tasks for the
main function. This is a way in which a
particular module is going to be executed.
Parameters
----------
logger : {logging.Logger}
The logger used for logging error information
resultsDict: {dict}
A dintionary containing information about the
command line arguments. These can be used for
overwriting command line arguments as needed.
'''
print('='*30)
print('Main function of module 1')
print('='*30)
print('We get a copy of the result dictionary over here ...')
doSomething()
print('Getting out of Module 1')
print('-'*30)
return
| 30.543478 | 126 | 0.580071 | import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from logs import logDecorator as lD
import jsonref, pprint
config = jsonref.load(open('../config/config.json'))
logBase = config['logging']['logBase'] + '.modules.test_plot.test_plot'
@lD.log(logBase + '.doSomething')
def doSomething(logger):
with plt.style.context('../notebooks/test.mplstyle'):
w = 7.2
fig = plt.figure(figsize=(w, w/1.6))
ax = {}
ax[0] = plt.axes([0.10, 0.10, 0.35, 0.30])
ax[1] = plt.axes([0.55, 0.10, 0.35, 0.30])
ax[2] = plt.axes([0.10, 0.57, 0.35, 0.30])
ax[3] = plt.axes([0.55, 0.57, 0.35, 0.30])
[ax[0].plot([1,2,3],np.random.randint([1,2,3],[10,9,8], size=3), marker='', label=f'line {i}') for i in range(4)]
[ax[1].plot([1,2,3],np.random.randint([1,2,3],[10,9,8], size=3), linestyle='', label=f'marker {i}') for i in range(4)]
params = ((10, 10), (4, 12), (50, 12), (6, 55))
for a, b in params:
values = np.random.beta(a, b, size=10000)
ax[2].hist(values, histtype="stepfilled", bins=30,
alpha=0.2, density=True)
mean, cov = [0, 2], [(1, .5), (.5, 1)]
x, y = np.random.multivariate_normal(mean, cov, size=50).T
.suptitle('Times New Roman')
[ax[i].set_title(f'ax{i} Title') for i in range(4)]
[ax[i].set_xlabel(f'ax{i} xlabel') for i in range(4)]
[ax[i].set_ylabel(f'ax{i} ylabel') for i in range(4)]
[ax[i].legend(loc='upper right') for i in range(4)]
ax[3].set_xlabel(r'ax3 $a_i \sin(2\pi fx_i)$ label');
plt.savefig('test.svg')
return
@lD.log(logBase + '.main')
def main(logger, resultsDict):
print('='*30)
print('Main function of module 1')
print('='*30)
print('We get a copy of the result dictionary over here ...')
doSomething()
print('Getting out of Module 1')
print('-'*30)
return
| true | true |
f7315faf3403c57b71fcb4aae306f4d130e43b2b | 666 | py | Python | algorithms/python/21.py | scream7/leetcode | 1fe0f5df3ca0019a4d99979cc663993d2492272d | [
"Apache-2.0"
] | null | null | null | algorithms/python/21.py | scream7/leetcode | 1fe0f5df3ca0019a4d99979cc663993d2492272d | [
"Apache-2.0"
] | null | null | null | algorithms/python/21.py | scream7/leetcode | 1fe0f5df3ca0019a4d99979cc663993d2492272d | [
"Apache-2.0"
] | null | null | null | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy = ListNode(0)
cur = dummy
while l1 and l2:
if l1.val <= l2.val:
cur.next = l1
l1 = l1.next
elif l2.val < l1.val:
cur.next = l2
l2 = l2.next
cur = cur.next
cur.next = l1 if l1 is not None else l2
return dummy.next
| 25.615385 | 47 | 0.472973 |
class Solution(object):
def mergeTwoLists(self, l1, l2):
dummy = ListNode(0)
cur = dummy
while l1 and l2:
if l1.val <= l2.val:
cur.next = l1
l1 = l1.next
elif l2.val < l1.val:
cur.next = l2
l2 = l2.next
cur = cur.next
cur.next = l1 if l1 is not None else l2
return dummy.next
| true | true |
f7316132008490fabdc6c23eaeae95ebcafde9b9 | 2,856 | py | Python | setup.py | vikrammodh0111/vectorai | 0ca0adf1599639035603af8158477972b0902784 | [
"Apache-2.0"
] | null | null | null | setup.py | vikrammodh0111/vectorai | 0ca0adf1599639035603af8158477972b0902784 | [
"Apache-2.0"
] | null | null | null | setup.py | vikrammodh0111/vectorai | 0ca0adf1599639035603af8158477972b0902784 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import os
core_req = ["requests", "numpy", "pandas", "appdirs>=1.4.4", "tqdm>=4.27.0", "plotly>=4.0.0"]
extras_req = {
"dev" : ["twine", "black", "pytest", "pytest-cov"],
"test" : ["pytest", "pytest-cov"],
"docs" : ["sphinx-rtd-theme>=0.5.0", "nbsphinx>=0.7.1"]
}
extras_req["all"] = [p for r in extras_req.values() for p in r]
if 'IS_VECTORAI_NIGHTLY' in os.environ.keys():
from datetime import datetime
name = 'vectorai-nightly'
version = '0.2.2' + '.' + datetime.today().date().__str__().replace('-', '.')
else:
name = 'vectorai'
version = '0.2.2'
setup(
name=name,
version=version,
author="OnSearch Pty Ltd",
author_email="dev@vctr.ai",
description="A Python framework for building vector based applications. Encode, query and analyse data using vectors.",
long_description=open("README.md", "r", encoding="utf-8").read(),
long_description_content_type="text/markdown",
keywords="vector, embeddings, machinelearning, ai, artificialintelligence, nlp, tensorflow, pytorch, nearestneighbors, search, analytics, clustering, dimensionalityreduction",
url="https://github.com/vector-ai/vectorai",
license="Apache",
packages=find_packages(exclude=["tests*"]),
python_requires=">=3",
install_requires=core_req,
extras_require=extras_req,
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Intended Audience :: Education",
"Intended Audience :: Science/Research",
"Intended Audience :: Information Technology",
"Intended Audience :: Financial and Insurance Industry",
"Intended Audience :: Healthcare Industry",
"Intended Audience :: Manufacturing",
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: Implementation :: PyPy",
"Topic :: Database",
"Topic :: Internet :: WWW/HTTP :: Indexing/Search",
"Topic :: Multimedia :: Sound/Audio :: Conversion",
"Topic :: Multimedia :: Video :: Conversion",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
"Topic :: Scientific/Engineering :: Image Recognition",
"Topic :: Scientific/Engineering :: Information Analysis",
"Topic :: Scientific/Engineering :: Visualization",
"Topic :: Software Development :: Libraries :: Application Frameworks",
],
)
| 42.626866 | 179 | 0.640056 |
from setuptools import setup, find_packages
import os
core_req = ["requests", "numpy", "pandas", "appdirs>=1.4.4", "tqdm>=4.27.0", "plotly>=4.0.0"]
extras_req = {
"dev" : ["twine", "black", "pytest", "pytest-cov"],
"test" : ["pytest", "pytest-cov"],
"docs" : ["sphinx-rtd-theme>=0.5.0", "nbsphinx>=0.7.1"]
}
extras_req["all"] = [p for r in extras_req.values() for p in r]
if 'IS_VECTORAI_NIGHTLY' in os.environ.keys():
from datetime import datetime
name = 'vectorai-nightly'
version = '0.2.2' + '.' + datetime.today().date().__str__().replace('-', '.')
else:
name = 'vectorai'
version = '0.2.2'
setup(
name=name,
version=version,
author="OnSearch Pty Ltd",
author_email="dev@vctr.ai",
description="A Python framework for building vector based applications. Encode, query and analyse data using vectors.",
long_description=open("README.md", "r", encoding="utf-8").read(),
long_description_content_type="text/markdown",
keywords="vector, embeddings, machinelearning, ai, artificialintelligence, nlp, tensorflow, pytorch, nearestneighbors, search, analytics, clustering, dimensionalityreduction",
url="https://github.com/vector-ai/vectorai",
license="Apache",
packages=find_packages(exclude=["tests*"]),
python_requires=">=3",
install_requires=core_req,
extras_require=extras_req,
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Intended Audience :: Education",
"Intended Audience :: Science/Research",
"Intended Audience :: Information Technology",
"Intended Audience :: Financial and Insurance Industry",
"Intended Audience :: Healthcare Industry",
"Intended Audience :: Manufacturing",
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: Implementation :: PyPy",
"Topic :: Database",
"Topic :: Internet :: WWW/HTTP :: Indexing/Search",
"Topic :: Multimedia :: Sound/Audio :: Conversion",
"Topic :: Multimedia :: Video :: Conversion",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
"Topic :: Scientific/Engineering :: Image Recognition",
"Topic :: Scientific/Engineering :: Information Analysis",
"Topic :: Scientific/Engineering :: Visualization",
"Topic :: Software Development :: Libraries :: Application Frameworks",
],
)
| true | true |
f7316298bcfb66abd224d102bd05d708bceccc59 | 647 | py | Python | SAMparser.py | camaclean/bella | c80c012cda05bc15b69db7fd54424823f75b5a21 | [
"BSD-3-Clause-LBNL"
] | 36 | 2018-11-07T14:21:20.000Z | 2020-07-21T03:52:20.000Z | SAMparser.py | camaclean/bella | c80c012cda05bc15b69db7fd54424823f75b5a21 | [
"BSD-3-Clause-LBNL"
] | 5 | 2018-11-09T11:03:36.000Z | 2019-09-10T18:39:39.000Z | SAMparser.py | camaclean/bella | c80c012cda05bc15b69db7fd54424823f75b5a21 | [
"BSD-3-Clause-LBNL"
] | 6 | 2019-05-21T01:15:02.000Z | 2020-06-17T16:34:36.000Z | from simplesam import Reader, Writer
import inspect
import sys, os, fileinput, string
in_file = open(sys.argv[1], 'r')
in_sam = Reader(in_file)
out_file = open('full_ecoli_mapped_q10_truth.txt', 'w')
# out_sam = Writer(out_file)
x = next(in_sam)
try:
while(x.qname != ''):
#if(x.reverse):
# out_file.write("+" + " ")
#else:
# out_file.write("-" + " ")
out_file.write(x.rname + " ")
out_file.write(x.qname + " ")
out_file.write(str(x.pos) + " ")
out_file.write(str(x.pos + len(x.seq)) + "\n")
#print str(type(x))
x = next(in_sam)
except:
print("Long read alignment ground truth generated")
in_file.close()
out_file.close() | 23.107143 | 55 | 0.650696 | from simplesam import Reader, Writer
import inspect
import sys, os, fileinput, string
in_file = open(sys.argv[1], 'r')
in_sam = Reader(in_file)
out_file = open('full_ecoli_mapped_q10_truth.txt', 'w')
x = next(in_sam)
try:
while(x.qname != ''):
out_file.write(x.rname + " ")
out_file.write(x.qname + " ")
out_file.write(str(x.pos) + " ")
out_file.write(str(x.pos + len(x.seq)) + "\n")
x = next(in_sam)
except:
print("Long read alignment ground truth generated")
in_file.close()
out_file.close() | true | true |
f73162a75addcf3c375f9aa1bcc038bdb5b9598e | 16,255 | py | Python | XBNet/main.py | tusharsarkar3/XBNet | 01e385f1c0a446eb38f4dd59ee9c510170bf096b | [
"MIT"
] | 167 | 2021-06-03T18:45:12.000Z | 2022-03-30T10:50:35.000Z | XBNet/main.py | tusharsarkar3/XBNet | 01e385f1c0a446eb38f4dd59ee9c510170bf096b | [
"MIT"
] | 13 | 2021-06-12T04:11:16.000Z | 2022-03-18T15:56:36.000Z | XBNet/main.py | tusharsarkar3/XBNet | 01e385f1c0a446eb38f4dd59ee9c510170bf096b | [
"MIT"
] | 27 | 2021-06-11T08:44:05.000Z | 2022-02-26T11:54:43.000Z | from kivymd.app import MDApp
from kivy.uix.widget import Widget
from kivy.uix.actionbar import ActionBar
from kivy.uix.scrollview import ScrollView
from kivy.uix.boxlayout import BoxLayout
from kivymd.theming import ThemableBehavior
from kivymd.uix.list import OneLineListItem, MDList, TwoLineListItem, ThreeLineListItem
from kivymd.uix.list import MDList
from kivymd.uix.textfield import MDTextField
from kivy.uix.button import Button
from kivy.lang import Builder
from kivymd.toast import toast
from kivy.uix.screenmanager import Screen, ScreenManager
import time
from kivy.core.window import Window
from kivymd.uix.label import MDLabel
from kivy.uix.modalview import ModalView
from kivymd.uix.filemanager import MDFileManager
from kivymd.theming import ThemeManager
import requests
from kivy.uix.popup import Popup
import os
from xgboost import XGBClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
from lightgbm import LGBMClassifier
import torch
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from XBNet.training_utils import training,predict
from XBNet.models import XBNETClassifier
from XBNet.run import run_XBNET
from os import environ
import pickle
def suppress_qt_warnings():
environ["QT_DEVICE_PIXEL_RATIO"] = "0"
environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1"
environ["QT_SCREEN_SCALE_FACTORS"] = "1"
environ["QT_SCALE_FACTOR"] = "1"
Login_Page = """
ScreenManager:
LoginPage
ModelDetails
FileManage
<LoginPage>:
name:"Login"
MDFloatLayout:
Image:
id: imageView
source: 'Untitled.png'
allow_stretch: True
halign: 'center'
pos_hint: {"center_x":0.23, "center_y":0.5}
MDRoundFlatIconButton:
id: filemanage
text: "Select Dataset"
icon: "folder"
pos_hint: {'center_x': .77, 'center_y': .85}
on_release: root.manager.current = "File"
MDTextField:
id: modelname
hint_text:"Enter the model name: "
pos_hint:{"center_x":0.77,"center_y":0.7}
current_hint_text_color:0,0,0,1
size_hint_x:0.4
required: True
MDTextField:
id: layers
hint_text:"Enter number of layers(For XBNet or NN): "
pos_hint:{"center_x":0.77,"center_y":0.55}
current_hint_text_color:0,0,0,1
size_hint_x:0.4
MDTextField:
id: target
hint_text:"Enter name of target feature: "
pos_hint:{"center_x":0.77,"center_y":0.40}
current_hint_text_color:0,0,0,1
size_hint_x:0.4
required: True
MDRaisedButton:
text:"Build model"
pos_hint:{"center_x":0.77,"center_y":0.25}
size_hint_x:0.3
on_release: root.manager.current = "Model"
on_press: app.get_model(modelname.text,target.text,layers.text)
theme_text_color:"Custom"
text_color:0,0,0,1
<ModelDetails>:
name:"Model"
MDFloatLayout:
Image:
id: imageView
source: 'Untitled.png'
allow_stretch: True
halign: 'center'
pos_hint: {"center_x":0.23, "center_y":0.5}
MDRaisedButton:
text:"Train"
pos_hint:{"center_x":0.63,"center_y":0.15}
size_hint_x:0.2
# on_release: root.manager.current = "Model"
on_press: app.get_layers()
theme_text_color:"Custom"
text_color:0,0,0,1
MDRaisedButton:
text:"Predict"
pos_hint:{"center_x":0.88,"center_y":0.15}
size_hint_x:0.2
# on_release: root.manager.current = "Model"
on_press: app.predict()
theme_text_color:"Custom"
text_color:0,0,0,1
<FileManage>:
name:"File"
BoxLayout:
FileChooserListView:
canvas.before:
Color:
rgb: 0.1, 0.2, 0.5
Rectangle:
pos: self.pos
size: self.size
on_selection: app.get_path(*args)
"""
class LoginPage(Screen):
pass
class ModelDetails(Screen):
pass
class CustomDropDown(BoxLayout):
pass
class FileManage(Screen):
pass
sm = ScreenManager()
sm.add_widget(LoginPage(name="Login"))
sm.add_widget(ModelDetails(name="Model"))
sm.add_widget(FileManage(name="File"))
class XBNetGUI(MDApp):
def __init__(self):
super(XBNetGUI, self).__init__()
self.predict_phase = False
class ContentNavigationDrawer(BoxLayout):
pass
class DrawerList(ThemableBehavior, MDList):
pass
def build(self):
self.theme_cls.primary_palette = "Blue"
login_page = Builder.load_string(Login_Page)
return login_page
def get_layers(self):
self.layers_dims = []
if self.model == "xbnet" or self.model == "neural network":
for i,j in self.fields.items():
self.layers_dims.append(int(j.text))
print(j.text)
elif (self.model == "xgboost" or self.model == "randomforest"
or self.model == "decision tree" or self.model == "lightgbm"):
for i,j in self.fields.items():
try:
self.layers_dims.append(int(j.text))
except:
self.layers_dims.append(float(j.text))
self.train()
def process_input(self):
suppress_qt_warnings()
column_to_predict = self.target
data = pd.read_csv(self.file_selected)
n_df = len(data)
label_encoded = {}
imputations = {}
for i in data.columns:
imputations[i] = data[i].mode()
if data[i].isnull().sum() / n_df >= 0.15:
data.drop(i, axis=1, inplace=True)
elif data[i].isnull().sum() / n_df < 0.15 and data[i].isnull().sum() / n_df > 0:
data[i].fillna(data[i].mode(), inplace=True)
imputations[i] = data[i].mode()
columns_object = list(data.dtypes[data.dtypes == object].index)
for i in columns_object:
if i != column_to_predict:
if data[i].nunique() / n_df < 0.4:
le = LabelEncoder()
data[i] = le.fit_transform(data[i])
label_encoded[i] = le
else:
data.drop(i, axis=1, inplace=True)
x_data = data.drop(column_to_predict, axis=1).to_numpy()
self.columns_finally_used = data.drop(column_to_predict, axis=1).columns
y_data = data[column_to_predict].to_numpy()
self.label_y = False
if y_data.dtype == object:
self.label_y = True
self.y_label_encoder = LabelEncoder()
y_data = self.y_label_encoder.fit_transform(y_data)
self.label_encoded = label_encoded
self.imputations = imputations
toast("Number of features are: " + str(x_data.shape[1]) +
" classes are: "+ str(len(np.unique(y_data))),duration=5)
self.x_data = x_data
self.y_data = y_data
def train(self):
X_train, X_test, y_train, y_test = train_test_split(self.x_data, self.y_data,
test_size=0.3, random_state=0)
if self.model == "xbnet" or self.model =="neural network":
print(self.layers_dims)
m = self.model
model = XBNETClassifier( X_train, y_train, self.layers,
input_through_cmd=True, inputs_for_gui=self.layers_dims,
num_layers_boosted=self.n_layers_boosted
)
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
self.model, self.acc, self.lo, self.val_ac, self.val_lo = run_XBNET(X_train, X_test, y_train, y_test, model, criterion, optimizer, 32, 10)
model.save(m+"_testAccuracy_" +str(max(self.val_ac))[:4] +"_trainAccuracy_" +
str(max(self.acc))[:4]+ ".pt",)
toast("Test Accuracy is: " +str(max(self.val_ac))[:4] +" and Training Accuracy is: " +
str(max(self.acc))[:4] + " and model is saved.",duration= 10)
elif (self.model == "xgboost" or self.model == "randomforest"
or self.model == "decision tree" or self.model == "lightgbm"):
if self.model == "xgboost":
self.model_tree = XGBClassifier(n_estimators=self.layers_dims[0],
max_depth=self.layers_dims[1],
learning_rate= self.layers_dims[2],
subsample= self.layers_dims[3],
colsample_bylevel = self.layers_dims[4],
random_state=0,n_jobs=-1,
)
self.model_tree.fit(X_train, y_train,eval_metric="mlogloss")
training_acc = self.model_tree.score(X_train, y_train)
testing_acc = self.model_tree.score(X_test,y_test)
elif self.model == "randomforest":
self.model_tree = RandomForestClassifier(n_estimators=self.layers_dims[0],
max_depth=self.layers_dims[1],
random_state=0,n_jobs=-1)
self.model_tree.fit(X_train, y_train)
training_acc = self.model_tree.score(X_train, y_train)
testing_acc = self.model_tree.score(X_test,y_test)
elif self.model == "decision tree":
self.model_tree = DecisionTreeClassifier(max_depth=self.layers_dims[1],random_state=0)
self.model_tree.fit(X_train, y_train)
training_acc = self.model_tree.score(X_train, y_train)
testing_acc = self.model_tree.score(X_test,y_test)
elif self.model == "lightgbm":
self.model_tree = LGBMClassifier(n_estimators=self.layers_dims[0],
max_depth=self.layers_dims[1],
learning_rate= self.layers_dims[2],
subsample= self.layers_dims[3],
colsample_bylevel = self.layers_dims[4],
random_state=0,n_jobs=-1,)
self.model_tree.fit(X_train, y_train,eval_metric="mlogloss")
training_acc = self.model_tree.score(X_train, y_train)
testing_acc = self.model_tree.score(X_test,y_test)
toast(text="Training and Testing accuracies are "+str(training_acc*100)
+" "+str(testing_acc*100) + " respectively and model is stored",duration=7)
with open(self.model+"_testAccuracy_" +str(testing_acc)[:4] +"_trainAccuracy_" +
str(training_acc)[:4]+ ".pkl", 'wb') as outfile:
pickle.dump(self.model_tree,outfile)
def predict(self):
self.predict_phase = True
self.root.current = "File"
def predict_results(self):
df = pd.read_csv(self.file_selected)
data = df[self.columns_finally_used]
for i in data.columns:
if data[i].isnull().sum() > 0:
data[i].fillna(self.imputations[i], inplace=True)
if i in self.label_encoded.keys():
data[i] = self.label_encoded[i].transform(data[i])
if (self.model == "xgboost" or self.model == "randomforest"
or self.model == "decision tree" or self.model == "lightgbm"):
predictions = self.model_tree.predict(data.to_numpy())
else:
predictions = predict(self.model, data.to_numpy())
if self.label_y == True:
df[self.target] = self.y_label_encoder.inverse_transform(predictions)
else:
df[self.target] = predictions
df.to_csv("Predicted_Results.csv",index=False)
toast(text="Predicted_Results.csv in this directory has the results",
duration = 10)
def get_model(self,model,target,layers):
self.model = model.lower()
if len(layers) > 0:
self.layers = int(layers)
self.target = target
if self.model.lower() == "xbnet":
self.n_layers_boosted = 1
self.net_model()
elif (self.model == "xgboost" or self.model == "randomforest"
or self.model == "decision tree" or self.model == "lightgbm"):
self.tree_model()
elif self.model.lower() == "neural network":
self.n_layers_boosted = 0
self.net_model()
self.process_input()
def net_model(self):
layout = self.root.get_screen('Model')
gap = 1/(2*self.layers+2)
counter = 1
self.fields = {}
for i in range(self.layers):
lab1 = MDTextField(hint_text="Enter input dimensions of layer "+ str(i+1) +":",
pos_hint={"center_x":0.77,"center_y":1-gap*(counter)},
size_hint_x=.4, current_hint_text_color=[0,0,0,1] )
counter+=1
lab2 = MDTextField(hint_text="Enter output dimensions of layer "+ str(i+1) +":",
pos_hint={"center_x":0.77,"center_y":1-gap*(counter)},
size_hint_x=.4, current_hint_text_color=[0,0,0,1] )
counter +=1
layout.add_widget(lab1)
layout.add_widget(lab2)
self.fields["input_"+str(i+1)] = lab1
self.fields["output_" + str(i+1)] = lab2
def tree_model(self):
layout = self.root.get_screen('Model')
self.fields = {}
lab1 = MDTextField(hint_text="Enter number of estimators: ",
pos_hint={"center_x":0.77,"center_y":0.85},
size_hint_x=.4, current_hint_text_color=[0,0,0,1] )
lab2 = MDTextField(hint_text="Enter depth of trees[default:6](Typical 3-10): ",
pos_hint={"center_x":0.77,"center_y":0.7},
size_hint_x=.4, current_hint_text_color=[0,0,0,1] )
lab3 = MDTextField(hint_text="Enter learning rate forr XGBoost(eta)[default:0.3]: ",
pos_hint={"center_x":0.77,"center_y":0.55},
size_hint_x=.4, current_hint_text_color=[0,0,0,1] )
lab4 = MDTextField(hint_text="Enter size of subsample[default:1](Typical 0.5-1): ",
pos_hint={"center_x":0.77,"center_y":0.4},
size_hint_x=.4, current_hint_text_color=[0,0,0,1] )
lab5 = MDTextField(hint_text="Enter size of colsample_bytree[default:1](Typical 0.5-1): ",
pos_hint={"center_x":0.77,"center_y":0.25},
size_hint_x=.4, current_hint_text_color=[0,0,0,1] )
layout.add_widget(lab1)
layout.add_widget(lab2)
layout.add_widget(lab3)
layout.add_widget(lab4)
layout.add_widget(lab5)
self.fields["no_trees"] = lab1
self.fields["depth"] = lab2
self.fields["learning_rate"] = lab3
self.fields["subsample"] = lab4
self.fields["colsample_bytree"] = lab5
def get_path(self,*args):
print(args)
self.file_selected = args[1][0]
print(self.file_selected)
if self.predict_phase:
self.root.current = "Model"
print("hellooo")
self.predict_results()
else:
self.root.current = "Login"
if __name__ == "__main__":
XBNetGUI().run() | 40.235149 | 150 | 0.562781 | from kivymd.app import MDApp
from kivy.uix.widget import Widget
from kivy.uix.actionbar import ActionBar
from kivy.uix.scrollview import ScrollView
from kivy.uix.boxlayout import BoxLayout
from kivymd.theming import ThemableBehavior
from kivymd.uix.list import OneLineListItem, MDList, TwoLineListItem, ThreeLineListItem
from kivymd.uix.list import MDList
from kivymd.uix.textfield import MDTextField
from kivy.uix.button import Button
from kivy.lang import Builder
from kivymd.toast import toast
from kivy.uix.screenmanager import Screen, ScreenManager
import time
from kivy.core.window import Window
from kivymd.uix.label import MDLabel
from kivy.uix.modalview import ModalView
from kivymd.uix.filemanager import MDFileManager
from kivymd.theming import ThemeManager
import requests
from kivy.uix.popup import Popup
import os
from xgboost import XGBClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
from lightgbm import LGBMClassifier
import torch
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from XBNet.training_utils import training,predict
from XBNet.models import XBNETClassifier
from XBNet.run import run_XBNET
from os import environ
import pickle
def suppress_qt_warnings():
environ["QT_DEVICE_PIXEL_RATIO"] = "0"
environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1"
environ["QT_SCREEN_SCALE_FACTORS"] = "1"
environ["QT_SCALE_FACTOR"] = "1"
Login_Page = """
ScreenManager:
LoginPage
ModelDetails
FileManage
<LoginPage>:
name:"Login"
MDFloatLayout:
Image:
id: imageView
source: 'Untitled.png'
allow_stretch: True
halign: 'center'
pos_hint: {"center_x":0.23, "center_y":0.5}
MDRoundFlatIconButton:
id: filemanage
text: "Select Dataset"
icon: "folder"
pos_hint: {'center_x': .77, 'center_y': .85}
on_release: root.manager.current = "File"
MDTextField:
id: modelname
hint_text:"Enter the model name: "
pos_hint:{"center_x":0.77,"center_y":0.7}
current_hint_text_color:0,0,0,1
size_hint_x:0.4
required: True
MDTextField:
id: layers
hint_text:"Enter number of layers(For XBNet or NN): "
pos_hint:{"center_x":0.77,"center_y":0.55}
current_hint_text_color:0,0,0,1
size_hint_x:0.4
MDTextField:
id: target
hint_text:"Enter name of target feature: "
pos_hint:{"center_x":0.77,"center_y":0.40}
current_hint_text_color:0,0,0,1
size_hint_x:0.4
required: True
MDRaisedButton:
text:"Build model"
pos_hint:{"center_x":0.77,"center_y":0.25}
size_hint_x:0.3
on_release: root.manager.current = "Model"
on_press: app.get_model(modelname.text,target.text,layers.text)
theme_text_color:"Custom"
text_color:0,0,0,1
<ModelDetails>:
name:"Model"
MDFloatLayout:
Image:
id: imageView
source: 'Untitled.png'
allow_stretch: True
halign: 'center'
pos_hint: {"center_x":0.23, "center_y":0.5}
MDRaisedButton:
text:"Train"
pos_hint:{"center_x":0.63,"center_y":0.15}
size_hint_x:0.2
# on_release: root.manager.current = "Model"
on_press: app.get_layers()
theme_text_color:"Custom"
text_color:0,0,0,1
MDRaisedButton:
text:"Predict"
pos_hint:{"center_x":0.88,"center_y":0.15}
size_hint_x:0.2
# on_release: root.manager.current = "Model"
on_press: app.predict()
theme_text_color:"Custom"
text_color:0,0,0,1
<FileManage>:
name:"File"
BoxLayout:
FileChooserListView:
canvas.before:
Color:
rgb: 0.1, 0.2, 0.5
Rectangle:
pos: self.pos
size: self.size
on_selection: app.get_path(*args)
"""
class LoginPage(Screen):
pass
class ModelDetails(Screen):
pass
class CustomDropDown(BoxLayout):
pass
class FileManage(Screen):
pass
sm = ScreenManager()
sm.add_widget(LoginPage(name="Login"))
sm.add_widget(ModelDetails(name="Model"))
sm.add_widget(FileManage(name="File"))
class XBNetGUI(MDApp):
def __init__(self):
super(XBNetGUI, self).__init__()
self.predict_phase = False
class ContentNavigationDrawer(BoxLayout):
pass
class DrawerList(ThemableBehavior, MDList):
pass
def build(self):
self.theme_cls.primary_palette = "Blue"
login_page = Builder.load_string(Login_Page)
return login_page
def get_layers(self):
self.layers_dims = []
if self.model == "xbnet" or self.model == "neural network":
for i,j in self.fields.items():
self.layers_dims.append(int(j.text))
print(j.text)
elif (self.model == "xgboost" or self.model == "randomforest"
or self.model == "decision tree" or self.model == "lightgbm"):
for i,j in self.fields.items():
try:
self.layers_dims.append(int(j.text))
except:
self.layers_dims.append(float(j.text))
self.train()
def process_input(self):
suppress_qt_warnings()
column_to_predict = self.target
data = pd.read_csv(self.file_selected)
n_df = len(data)
label_encoded = {}
imputations = {}
for i in data.columns:
imputations[i] = data[i].mode()
if data[i].isnull().sum() / n_df >= 0.15:
data.drop(i, axis=1, inplace=True)
elif data[i].isnull().sum() / n_df < 0.15 and data[i].isnull().sum() / n_df > 0:
data[i].fillna(data[i].mode(), inplace=True)
imputations[i] = data[i].mode()
columns_object = list(data.dtypes[data.dtypes == object].index)
for i in columns_object:
if i != column_to_predict:
if data[i].nunique() / n_df < 0.4:
le = LabelEncoder()
data[i] = le.fit_transform(data[i])
label_encoded[i] = le
else:
data.drop(i, axis=1, inplace=True)
x_data = data.drop(column_to_predict, axis=1).to_numpy()
self.columns_finally_used = data.drop(column_to_predict, axis=1).columns
y_data = data[column_to_predict].to_numpy()
self.label_y = False
if y_data.dtype == object:
self.label_y = True
self.y_label_encoder = LabelEncoder()
y_data = self.y_label_encoder.fit_transform(y_data)
self.label_encoded = label_encoded
self.imputations = imputations
toast("Number of features are: " + str(x_data.shape[1]) +
" classes are: "+ str(len(np.unique(y_data))),duration=5)
self.x_data = x_data
self.y_data = y_data
def train(self):
X_train, X_test, y_train, y_test = train_test_split(self.x_data, self.y_data,
test_size=0.3, random_state=0)
if self.model == "xbnet" or self.model =="neural network":
print(self.layers_dims)
m = self.model
model = XBNETClassifier( X_train, y_train, self.layers,
input_through_cmd=True, inputs_for_gui=self.layers_dims,
num_layers_boosted=self.n_layers_boosted
)
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
self.model, self.acc, self.lo, self.val_ac, self.val_lo = run_XBNET(X_train, X_test, y_train, y_test, model, criterion, optimizer, 32, 10)
model.save(m+"_testAccuracy_" +str(max(self.val_ac))[:4] +"_trainAccuracy_" +
str(max(self.acc))[:4]+ ".pt",)
toast("Test Accuracy is: " +str(max(self.val_ac))[:4] +" and Training Accuracy is: " +
str(max(self.acc))[:4] + " and model is saved.",duration= 10)
elif (self.model == "xgboost" or self.model == "randomforest"
or self.model == "decision tree" or self.model == "lightgbm"):
if self.model == "xgboost":
self.model_tree = XGBClassifier(n_estimators=self.layers_dims[0],
max_depth=self.layers_dims[1],
learning_rate= self.layers_dims[2],
subsample= self.layers_dims[3],
colsample_bylevel = self.layers_dims[4],
random_state=0,n_jobs=-1,
)
self.model_tree.fit(X_train, y_train,eval_metric="mlogloss")
training_acc = self.model_tree.score(X_train, y_train)
testing_acc = self.model_tree.score(X_test,y_test)
elif self.model == "randomforest":
self.model_tree = RandomForestClassifier(n_estimators=self.layers_dims[0],
max_depth=self.layers_dims[1],
random_state=0,n_jobs=-1)
self.model_tree.fit(X_train, y_train)
training_acc = self.model_tree.score(X_train, y_train)
testing_acc = self.model_tree.score(X_test,y_test)
elif self.model == "decision tree":
self.model_tree = DecisionTreeClassifier(max_depth=self.layers_dims[1],random_state=0)
self.model_tree.fit(X_train, y_train)
training_acc = self.model_tree.score(X_train, y_train)
testing_acc = self.model_tree.score(X_test,y_test)
elif self.model == "lightgbm":
self.model_tree = LGBMClassifier(n_estimators=self.layers_dims[0],
max_depth=self.layers_dims[1],
learning_rate= self.layers_dims[2],
subsample= self.layers_dims[3],
colsample_bylevel = self.layers_dims[4],
random_state=0,n_jobs=-1,)
self.model_tree.fit(X_train, y_train,eval_metric="mlogloss")
training_acc = self.model_tree.score(X_train, y_train)
testing_acc = self.model_tree.score(X_test,y_test)
toast(text="Training and Testing accuracies are "+str(training_acc*100)
+" "+str(testing_acc*100) + " respectively and model is stored",duration=7)
with open(self.model+"_testAccuracy_" +str(testing_acc)[:4] +"_trainAccuracy_" +
str(training_acc)[:4]+ ".pkl", 'wb') as outfile:
pickle.dump(self.model_tree,outfile)
def predict(self):
self.predict_phase = True
self.root.current = "File"
def predict_results(self):
df = pd.read_csv(self.file_selected)
data = df[self.columns_finally_used]
for i in data.columns:
if data[i].isnull().sum() > 0:
data[i].fillna(self.imputations[i], inplace=True)
if i in self.label_encoded.keys():
data[i] = self.label_encoded[i].transform(data[i])
if (self.model == "xgboost" or self.model == "randomforest"
or self.model == "decision tree" or self.model == "lightgbm"):
predictions = self.model_tree.predict(data.to_numpy())
else:
predictions = predict(self.model, data.to_numpy())
if self.label_y == True:
df[self.target] = self.y_label_encoder.inverse_transform(predictions)
else:
df[self.target] = predictions
df.to_csv("Predicted_Results.csv",index=False)
toast(text="Predicted_Results.csv in this directory has the results",
duration = 10)
def get_model(self,model,target,layers):
self.model = model.lower()
if len(layers) > 0:
self.layers = int(layers)
self.target = target
if self.model.lower() == "xbnet":
self.n_layers_boosted = 1
self.net_model()
elif (self.model == "xgboost" or self.model == "randomforest"
or self.model == "decision tree" or self.model == "lightgbm"):
self.tree_model()
elif self.model.lower() == "neural network":
self.n_layers_boosted = 0
self.net_model()
self.process_input()
def net_model(self):
layout = self.root.get_screen('Model')
gap = 1/(2*self.layers+2)
counter = 1
self.fields = {}
for i in range(self.layers):
lab1 = MDTextField(hint_text="Enter input dimensions of layer "+ str(i+1) +":",
pos_hint={"center_x":0.77,"center_y":1-gap*(counter)},
size_hint_x=.4, current_hint_text_color=[0,0,0,1] )
counter+=1
lab2 = MDTextField(hint_text="Enter output dimensions of layer "+ str(i+1) +":",
pos_hint={"center_x":0.77,"center_y":1-gap*(counter)},
size_hint_x=.4, current_hint_text_color=[0,0,0,1] )
counter +=1
layout.add_widget(lab1)
layout.add_widget(lab2)
self.fields["input_"+str(i+1)] = lab1
self.fields["output_" + str(i+1)] = lab2
def tree_model(self):
layout = self.root.get_screen('Model')
self.fields = {}
lab1 = MDTextField(hint_text="Enter number of estimators: ",
pos_hint={"center_x":0.77,"center_y":0.85},
size_hint_x=.4, current_hint_text_color=[0,0,0,1] )
lab2 = MDTextField(hint_text="Enter depth of trees[default:6](Typical 3-10): ",
pos_hint={"center_x":0.77,"center_y":0.7},
size_hint_x=.4, current_hint_text_color=[0,0,0,1] )
lab3 = MDTextField(hint_text="Enter learning rate forr XGBoost(eta)[default:0.3]: ",
pos_hint={"center_x":0.77,"center_y":0.55},
size_hint_x=.4, current_hint_text_color=[0,0,0,1] )
lab4 = MDTextField(hint_text="Enter size of subsample[default:1](Typical 0.5-1): ",
pos_hint={"center_x":0.77,"center_y":0.4},
size_hint_x=.4, current_hint_text_color=[0,0,0,1] )
lab5 = MDTextField(hint_text="Enter size of colsample_bytree[default:1](Typical 0.5-1): ",
pos_hint={"center_x":0.77,"center_y":0.25},
size_hint_x=.4, current_hint_text_color=[0,0,0,1] )
layout.add_widget(lab1)
layout.add_widget(lab2)
layout.add_widget(lab3)
layout.add_widget(lab4)
layout.add_widget(lab5)
self.fields["no_trees"] = lab1
self.fields["depth"] = lab2
self.fields["learning_rate"] = lab3
self.fields["subsample"] = lab4
self.fields["colsample_bytree"] = lab5
def get_path(self,*args):
print(args)
self.file_selected = args[1][0]
print(self.file_selected)
if self.predict_phase:
self.root.current = "Model"
print("hellooo")
self.predict_results()
else:
self.root.current = "Login"
if __name__ == "__main__":
XBNetGUI().run() | true | true |
f7316351492d58d868c0577a2c53428d4e7bd48c | 815 | py | Python | apiapp/views.py | cansati/api-project | 9760025d84e91997ee9d3e141263e903ec95d6df | [
"MIT"
] | null | null | null | apiapp/views.py | cansati/api-project | 9760025d84e91997ee9d3e141263e903ec95d6df | [
"MIT"
] | null | null | null | apiapp/views.py | cansati/api-project | 9760025d84e91997ee9d3e141263e903ec95d6df | [
"MIT"
] | null | null | null | from rest_framework import viewsets
from . import serializers, models, permissions
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework import filters
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.settings import api_settings
class UserModelViewSet(viewsets.ModelViewSet):
serializer_class = serializers.ModelSerializer
queryset = models.UserProfile.objects.all()
authentication_classes = (TokenAuthentication,)
permission_classes = (permissions.UpdateOwnProfile, IsAuthenticated)
filter_backends = (filters.SearchFilter,)
search_fields = ['id', 'name', 'surname', 'email']
class LoginViewSet(ObtainAuthToken):
renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES
| 42.894737 | 72 | 0.825767 | from rest_framework import viewsets
from . import serializers, models, permissions
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework import filters
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.settings import api_settings
class UserModelViewSet(viewsets.ModelViewSet):
serializer_class = serializers.ModelSerializer
queryset = models.UserProfile.objects.all()
authentication_classes = (TokenAuthentication,)
permission_classes = (permissions.UpdateOwnProfile, IsAuthenticated)
filter_backends = (filters.SearchFilter,)
search_fields = ['id', 'name', 'surname', 'email']
class LoginViewSet(ObtainAuthToken):
renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES
| true | true |
f73163bebf2ce9fdff591feac06da38b26c56b96 | 851 | py | Python | ooobuild/dyn/sdb/definition_content.py | Amourspirit/ooo_uno_tmpl | 64e0c86fd68f24794acc22d63d8d32ae05dd12b8 | [
"Apache-2.0"
] | null | null | null | ooobuild/dyn/sdb/definition_content.py | Amourspirit/ooo_uno_tmpl | 64e0c86fd68f24794acc22d63d8d32ae05dd12b8 | [
"Apache-2.0"
] | null | null | null | ooobuild/dyn/sdb/definition_content.py | Amourspirit/ooo_uno_tmpl | 64e0c86fd68f24794acc22d63d8d32ae05dd12b8 | [
"Apache-2.0"
] | null | null | null | # coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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.
#
# Service Class
# this is a auto generated file generated by Cheetah
# Libre Office Version: 7.3
# Namespace: com.sun.star.sdb
from ...lo.sdb.definition_content import DefinitionContent as DefinitionContent
__all__ = ['DefinitionContent']
| 32.730769 | 79 | 0.760282 |
from ...lo.sdb.definition_content import DefinitionContent as DefinitionContent
__all__ = ['DefinitionContent']
| true | true |
f731655548ca300269d3b7f542881d9a8eb93c2a | 4,830 | py | Python | src/pykeen/models/unimodal/trans_e.py | DJRavinszkha/pykeen | d79fe39f83bc2831137f22be6421b37568694cf4 | [
"MIT"
] | null | null | null | src/pykeen/models/unimodal/trans_e.py | DJRavinszkha/pykeen | d79fe39f83bc2831137f22be6421b37568694cf4 | [
"MIT"
] | null | null | null | src/pykeen/models/unimodal/trans_e.py | DJRavinszkha/pykeen | d79fe39f83bc2831137f22be6421b37568694cf4 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""TransE."""
from typing import Any, ClassVar, Mapping, Optional
import torch
import torch.autograd
from torch.nn import functional
from ..base import EntityRelationEmbeddingModel
from ...constants import DEFAULT_EMBEDDING_HPO_EMBEDDING_DIM_RANGE
from ...losses import Loss
from ...nn.emb import EmbeddingSpecification
from ...nn.init import xavier_uniform_, xavier_uniform_norm_
from ...regularizers import Regularizer
from ...triples import TriplesFactory
from ...typing import Constrainer, DeviceHint, Hint, Initializer
__all__ = [
'TransE',
]
class TransE(EntityRelationEmbeddingModel):
r"""An implementation of TransE [bordes2013]_.
TransE models relations as a translation from head to tail entities in :math:`\textbf{e}`:
.. math::
\textbf{e}_h + \textbf{e}_r \approx \textbf{e}_t
This equation is rearranged and the :math:`l_p` norm is applied to create the TransE interaction function.
.. math::
f(h, r, t) = - \|\textbf{e}_h + \textbf{e}_r - \textbf{e}_t\|_{p}
While this formulation is computationally efficient, it inherently cannot model one-to-many, many-to-one, and
many-to-many relationships. For triples :math:`(h,r,t_1), (h,r,t_2) \in \mathcal{K}` where :math:`t_1 \neq t_2`,
the model adapts the embeddings in order to ensure :math:`\textbf{e}_h + \textbf{e}_r \approx \textbf{e}_{t_1}`
and :math:`\textbf{e}_h + \textbf{e}_r \approx \textbf{e}_{t_2}` which results in
:math:`\textbf{e}_{t_1} \approx \textbf{e}_{t_2}`.
---
citation:
author: Bordes
year: 2013
link: http://papers.nips.cc/paper/5071-translating-embeddings-for-modeling-multi-relational-data.pdf
"""
#: The default strategy for optimizing the model's hyper-parameters
hpo_default: ClassVar[Mapping[str, Any]] = dict(
embedding_dim=DEFAULT_EMBEDDING_HPO_EMBEDDING_DIM_RANGE,
scoring_fct_norm=dict(type=int, low=1, high=2),
)
def __init__(
self,
triples_factory: TriplesFactory,
embedding_dim: int = 50,
scoring_fct_norm: int = 1,
loss: Optional[Loss] = None,
preferred_device: DeviceHint = None,
random_seed: Optional[int] = None,
regularizer: Optional[Regularizer] = None,
entity_initializer: Hint[Initializer] = xavier_uniform_,
entity_constrainer: Hint[Constrainer] = functional.normalize,
relation_initializer: Hint[Initializer] = xavier_uniform_norm_,
) -> None:
r"""Initialize TransE.
:param embedding_dim: The entity embedding dimension $d$. Is usually $d \in [50, 300]$.
:param scoring_fct_norm: The :math:`l_p` norm applied in the interaction function. Is usually ``1`` or ``2.``.
.. seealso::
- OpenKE `implementation of TransE <https://github.com/thunlp/OpenKE/blob/OpenKE-PyTorch/models/TransE.py>`_
"""
super().__init__(
triples_factory=triples_factory,
loss=loss,
preferred_device=preferred_device,
random_seed=random_seed,
regularizer=regularizer,
entity_representations=EmbeddingSpecification(
embedding_dim=embedding_dim,
initializer=entity_initializer,
constrainer=entity_constrainer,
),
relation_representations=EmbeddingSpecification(
embedding_dim=embedding_dim,
initializer=relation_initializer,
),
)
self.scoring_fct_norm = scoring_fct_norm
def score_hrt(self, hrt_batch: torch.LongTensor) -> torch.FloatTensor: # noqa: D102
# Get embeddings
h = self.entity_embeddings(indices=hrt_batch[:, 0])
r = self.relation_embeddings(indices=hrt_batch[:, 1])
t = self.entity_embeddings(indices=hrt_batch[:, 2])
# TODO: Use torch.dist
return -torch.norm(h + r - t, dim=-1, p=self.scoring_fct_norm, keepdim=True)
def score_t(self, hr_batch: torch.LongTensor) -> torch.FloatTensor: # noqa: D102
# Get embeddings
h = self.entity_embeddings(indices=hr_batch[:, 0])
r = self.relation_embeddings(indices=hr_batch[:, 1])
t = self.entity_embeddings(indices=None)
# TODO: Use torch.cdist
return -torch.norm(h[:, None, :] + r[:, None, :] - t[None, :, :], dim=-1, p=self.scoring_fct_norm)
def score_h(self, rt_batch: torch.LongTensor) -> torch.FloatTensor: # noqa: D102
# Get embeddings
h = self.entity_embeddings(indices=None)
r = self.relation_embeddings(indices=rt_batch[:, 0])
t = self.entity_embeddings(indices=rt_batch[:, 1])
# TODO: Use torch.cdist
return -torch.norm(h[None, :, :] + r[:, None, :] - t[:, None, :], dim=-1, p=self.scoring_fct_norm)
| 38.951613 | 119 | 0.654658 |
from typing import Any, ClassVar, Mapping, Optional
import torch
import torch.autograd
from torch.nn import functional
from ..base import EntityRelationEmbeddingModel
from ...constants import DEFAULT_EMBEDDING_HPO_EMBEDDING_DIM_RANGE
from ...losses import Loss
from ...nn.emb import EmbeddingSpecification
from ...nn.init import xavier_uniform_, xavier_uniform_norm_
from ...regularizers import Regularizer
from ...triples import TriplesFactory
from ...typing import Constrainer, DeviceHint, Hint, Initializer
__all__ = [
'TransE',
]
class TransE(EntityRelationEmbeddingModel):
hpo_default: ClassVar[Mapping[str, Any]] = dict(
embedding_dim=DEFAULT_EMBEDDING_HPO_EMBEDDING_DIM_RANGE,
scoring_fct_norm=dict(type=int, low=1, high=2),
)
def __init__(
self,
triples_factory: TriplesFactory,
embedding_dim: int = 50,
scoring_fct_norm: int = 1,
loss: Optional[Loss] = None,
preferred_device: DeviceHint = None,
random_seed: Optional[int] = None,
regularizer: Optional[Regularizer] = None,
entity_initializer: Hint[Initializer] = xavier_uniform_,
entity_constrainer: Hint[Constrainer] = functional.normalize,
relation_initializer: Hint[Initializer] = xavier_uniform_norm_,
) -> None:
super().__init__(
triples_factory=triples_factory,
loss=loss,
preferred_device=preferred_device,
random_seed=random_seed,
regularizer=regularizer,
entity_representations=EmbeddingSpecification(
embedding_dim=embedding_dim,
initializer=entity_initializer,
constrainer=entity_constrainer,
),
relation_representations=EmbeddingSpecification(
embedding_dim=embedding_dim,
initializer=relation_initializer,
),
)
self.scoring_fct_norm = scoring_fct_norm
def score_hrt(self, hrt_batch: torch.LongTensor) -> torch.FloatTensor: # noqa: D102
# Get embeddings
h = self.entity_embeddings(indices=hrt_batch[:, 0])
r = self.relation_embeddings(indices=hrt_batch[:, 1])
t = self.entity_embeddings(indices=hrt_batch[:, 2])
# TODO: Use torch.dist
return -torch.norm(h + r - t, dim=-1, p=self.scoring_fct_norm, keepdim=True)
def score_t(self, hr_batch: torch.LongTensor) -> torch.FloatTensor: # noqa: D102
# Get embeddings
h = self.entity_embeddings(indices=hr_batch[:, 0])
r = self.relation_embeddings(indices=hr_batch[:, 1])
t = self.entity_embeddings(indices=None)
# TODO: Use torch.cdist
return -torch.norm(h[:, None, :] + r[:, None, :] - t[None, :, :], dim=-1, p=self.scoring_fct_norm)
def score_h(self, rt_batch: torch.LongTensor) -> torch.FloatTensor: # noqa: D102
# Get embeddings
h = self.entity_embeddings(indices=None)
r = self.relation_embeddings(indices=rt_batch[:, 0])
t = self.entity_embeddings(indices=rt_batch[:, 1])
# TODO: Use torch.cdist
return -torch.norm(h[None, :, :] + r[:, None, :] - t[:, None, :], dim=-1, p=self.scoring_fct_norm)
| true | true |
f73165f0c8a4ee6043789cf0356dafa3edf3bfa8 | 1,392 | py | Python | main.py | tejasvicsr1/Jumble-Solver | 12980394f6f0b7a5a580a56389559266f3825d6a | [
"MIT"
] | null | null | null | main.py | tejasvicsr1/Jumble-Solver | 12980394f6f0b7a5a580a56389559266f3825d6a | [
"MIT"
] | null | null | null | main.py | tejasvicsr1/Jumble-Solver | 12980394f6f0b7a5a580a56389559266f3825d6a | [
"MIT"
] | null | null | null | # Python code to unscramble a jumbled word using the Enchant dictionary(US) and itertools in Python.
from itertools import permutations
import enchant
word_list = enchant.Dict("en_US")
# Taking the input word and converting it into lowercase words.
word = input("Enter the letters: ")
word = word.lower()
word_length = len(word)
# A function to print the unjumbled words according to the length of the word.
def output_fnc(length):
temp = []
for word in ans:
if len(word) == length:
temp.append(word)
if len(temp) != 0:
print("Words of length " + str(length) + " are:")
for temps in temp:
print(temps)
else:
print("No words of length " + str(length))
# Variables to store the final correct words and to store all the possible permutations.
ans = []
perms = []
# Finding and adding all the permutations to the list.
for i in range(1, word_length + 1):
for p in permutations(word, i):
striing = ''
len_p = len(p)
for letter in range(0, len_p):
striing += p[letter]
perms.append(striing)
# Removing duplicates.
perms = list(set(perms))
# Checking if the permutation created is an actual English(US) word.
for perm in perms:
if word_list.check(perm):
ans.append(perm)
#Printing the final results.
for j in range(2, word_length + 1):
output_fnc(j)
| 28.408163 | 101 | 0.655891 |
from itertools import permutations
import enchant
word_list = enchant.Dict("en_US")
word = input("Enter the letters: ")
word = word.lower()
word_length = len(word)
def output_fnc(length):
temp = []
for word in ans:
if len(word) == length:
temp.append(word)
if len(temp) != 0:
print("Words of length " + str(length) + " are:")
for temps in temp:
print(temps)
else:
print("No words of length " + str(length))
ans = []
perms = []
for i in range(1, word_length + 1):
for p in permutations(word, i):
striing = ''
len_p = len(p)
for letter in range(0, len_p):
striing += p[letter]
perms.append(striing)
perms = list(set(perms))
for perm in perms:
if word_list.check(perm):
ans.append(perm)
for j in range(2, word_length + 1):
output_fnc(j)
| true | true |
f731664d01602fc4bc98d2d3a1dca73625c63b84 | 14,176 | py | Python | file-access/static/usr/bin/setup-users-and-groups.py | aisbergg/dockerfiles | 3cf24d2667a75d6eda8b8fb7df835b97c6a13348 | [
"MIT"
] | 1 | 2019-10-23T06:54:06.000Z | 2019-10-23T06:54:06.000Z | file-access/static/usr/bin/setup-users-and-groups.py | aisbergg/dockerfiles | 3cf24d2667a75d6eda8b8fb7df835b97c6a13348 | [
"MIT"
] | null | null | null | file-access/static/usr/bin/setup-users-and-groups.py | aisbergg/dockerfiles | 3cf24d2667a75d6eda8b8fb7df835b97c6a13348 | [
"MIT"
] | null | null | null | import argparse
import crypt
import json
import os
import pwd
import random
import re
import string
import subprocess
import sys
import traceback
from itertools import product
import yaml
class ACL:
@staticmethod
def get_file_acl(path):
if not os.path.exists(path):
raise IOError("The directory or file '{0}' does not exist".format(path))
cmd_result = execute_command(['getfacl', '-p', path])
if cmd_result['returncode'] != 0:
raise Exception("Failed to get ACL of file or directory '{0}': {1}".format(path, cmd_result['output']))
raw_acl = cmd_result['output'].splitlines()
owner = re.match(r'# owner: (.+)', raw_acl[1]).group(1)
group = re.match(r'# group: (.+)', raw_acl[2]).group(1)
acl = {'users': [], 'groups': [], 'other': None}
for a in raw_acl[3:]:
match_acl = re.match(r'user::([rwx-]+)', a)
if match_acl:
acl['users'].append({'name': '', 'permissions': match_acl.group(1)})
# explicitly add owner (e.g. webserver), so sub directories created
# by different user will still be readable by the original owner
acl['owner'] = {'name': owner, 'permissions': match_acl.group(1)}
continue
match_acl = re.match(r'user:([^:]+):([rwx-]+)', a)
if match_acl:
acl['users'].append({'name': match_acl.group(1), 'permissions': match_acl.group(2)})
continue
match_acl = re.match(r'group::([rwx-]+)', a)
if match_acl:
acl['groups'].append({'name': '', 'permissions': match_acl.group(1)})
acl['group'] = {'name': group, 'permissions': match_acl.group(1)}
continue
match_acl = re.match(r'group:([^:]+):([rwx-]+)', a)
if match_acl:
acl['groups'].append({'name': match_acl.group(1), 'permissions': match_acl.group(2)})
continue
match_acl = re.match(r'other::([rwx-]+)', a)
if match_acl:
acl['other'] = match_acl.group(1)
continue
return acl
@staticmethod
def file_acl_differs(path, new_acl):
old_acl = ACL.get_file_acl(path)
return json.dumps(old_acl, sort_keys=True) != json.dumps(new_acl, sort_keys=True)
@staticmethod
def set_file_acl(path, new_acl, force=False):
def format_acl_spec(prefix, name, permissions):
acl_spec = list()
acl_spec.append("{0}:{1}:{2}".format(prefix, name, permissions))
if os.path.isdir(path):
acl_spec.append("d:{0}:{1}:{2}".format(prefix, name, permissions))
return ','.join(acl_spec)
old_acl = ACL.get_file_acl(path)
if force or json.dumps(old_acl, sort_keys=True) != json.dumps(new_acl, sort_keys=True):
print("Setting ACLs of '{0}...".format(path))
# modify ACLs
setfacl_cmd = ['setfacl', '-R', '-m']
acl_spec = list()
for uacl in new_acl['users']:
acl_spec.append(format_acl_spec('u', uacl['name'], uacl['permissions']))
# explicitly add owner (e.g. webserver), so sub directories created
# by different user will still be readable by the original owner
acl_spec.append(format_acl_spec('u', new_acl['owner']['name'], new_acl['owner']['permissions']))
for gacl in new_acl['groups']:
acl_spec.append(format_acl_spec('g', gacl['name'], gacl['permissions']))
acl_spec.append(format_acl_spec('g', new_acl['group']['name'], new_acl['group']['permissions']))
acl_spec.append(format_acl_spec('o', '', new_acl['other']))
setfacl_cmd.append(','.join(acl_spec))
setfacl_cmd.append(path)
cmd_result = execute_command(setfacl_cmd)
if cmd_result['returncode'] != 0:
raise Exception("Failed to set ACL of file or directory '{0}': {1}".format(path, cmd_result['output']))
# remove ACLs
setfacl_cmd = ['setfacl', '-R', '-x']
acl_spec = list()
users_to_remove = list(
set([x['name'] for x in old_acl['users']]) - set([x['name'] for x in new_acl['users']]))
groups_to_remove = list(
set([x['name'] for x in old_acl['groups']]) - set([x['name'] for x in new_acl['groups']]))
for u in users_to_remove:
acl_spec.append(format_acl_spec('u', u, ''))
for g in groups_to_remove:
acl_spec.append(format_acl_spec('g', g, ''))
if acl_spec:
setfacl_cmd.append(','.join(acl_spec))
setfacl_cmd.append(path)
cmd_result = execute_command(setfacl_cmd)
if cmd_result['returncode'] != 0:
raise Exception(
"Failed to remove ACL from file or directory '{0}': {1}".format(path, cmd_result['output']))
def get_arg(config, arg, dtype, default=None, required=False):
if required and not arg in config:
raise ValueError("Missing key '{0}'".format(arg))
if not arg in config:
return default
if type(config[arg]) is not dtype:
raise ValueError("'{0}' must be of type '{1}', got '{2}'".format(arg, str(dtype), str(config[arg])))
return config[arg]
def execute_command(cmd):
try:
return {'returncode': 0,
'output': subprocess.check_output(cmd, stderr=subprocess.STDOUT, universal_newlines=True)}
except subprocess.CalledProcessError as e:
return {'returncode': e.returncode, 'output': e.output}
def recursive_chown(path, uid, gid):
os.chown(path, uid, gid)
for item in os.listdir(path):
itempath = os.path.join(path, item)
if os.path.isfile(itempath):
os.chown(itempath, uid, gid)
elif os.path.isdir(itempath):
os.chown(itempath, uid, gid)
recursive_chown(itempath, uid, gid)
def main():
# parse arguments
parser = argparse.ArgumentParser(
prog='setup-users-and-groups',
description='According to a configuration file this script creates Linux users/groups and grants permissions on resources.',
add_help=True)
parser.add_argument('-f', '--force', dest='force',
action='store_true', default=False, help="Force the setting the ACLs.")
parser.add_argument('-c', '--create-dir', dest='create_dir',
action='store_true', default=False, help="Create a directory for a path that does not exists.")
parser.add_argument('configuration_file', help="File that defines what to do.")
args = parser.parse_args(sys.argv[1:])
try:
# load configuration either from file or from stdin
if args.configuration_file == '-':
inp = sys.stdin.read()
config = yaml.load(inp) or dict()
else:
if not os.path.exists(args.configuration_file):
raise IOError("The configuration file '{0}' does not exist".format(args.configuration_file))
with open(file=args.configuration_file, mode='r', encoding='utf8') as f:
config = yaml.load(f.read())
# parse arguments
groups = get_arg(config, "groups", dict, dict())
users = get_arg(config, "users", dict, dict())
defaults = get_arg(config, "defaults", dict, None) or dict()
defaults = {
'owner_permissions': get_arg(defaults, "owner_permissions", str, None),
'owner_group_permissions': get_arg(defaults, "owner_group_permissions", str, None),
'user_permissions': get_arg(defaults, "user_permissions", str, 'rwx'),
'group_permissions': get_arg(defaults, "group_permissions", str, 'rwx'),
}
acls = dict()
# create groups
for group, gdef in groups.items():
if type(gdef) != dict:
raise ValueError("The group definition of '{0}' must be of type dict".format(group))
gid = get_arg(gdef, 'gid', int, None)
permissions = get_arg(gdef, 'permissions', list, list())
# add group if it doesn't already exists
if execute_command(['getent', 'group', group])['returncode'] == 0:
print("Group '{0}' already exists, skipping...".format(group))
else:
print("Creating group '{0}'...".format(group))
groupadd_cmd = ['groupadd']
if gid:
groupadd_cmd += ['-g', str(gid)]
groupadd_cmd.append(group)
cmd_result = execute_command(groupadd_cmd)
if cmd_result['returncode'] != 0:
raise Exception("Failed to create group '{0}': {1}".format(group, cmd_result['output']))
# parse permissions
for perm in permissions:
path = get_arg(perm, "path", str, None, required=True)
if not os.path.exists(path):
if args.create_dir:
os.makedirs(path, 0o750);
else:
raise IOError("The directory or file '{0}' does not exist".format(path))
path_permissions = get_arg(perm, 'permissions', str, defaults['group_permissions'])
new_acl = {'name': group, 'permissions': path_permissions}
if path in acls:
acls[path]['groups'].append(new_acl)
else:
user_group_default = {'name': '', 'permissions': defaults['group_permissions']}
acls[path] = {'users': [user_group_default], 'groups': [user_group_default, new_acl],
'other': '---'}
# create users
for user, udef in users.items():
if type(udef) != dict:
raise ValueError("The user definition of '{0}' must be of type dict".format(user))
uid = get_arg(udef, 'uid', int, None)
groups = get_arg(udef, 'groups', list, None)
home = get_arg(udef, 'home', str, None)
random_string = ''.join(
random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(64))
hashed_password = crypt.crypt(get_arg(udef, 'password', str, random_string),
crypt.mksalt(crypt.METHOD_SHA512))
ssh_public_key = get_arg(udef, 'ssh_public_key', str, '')
permissions = get_arg(udef, 'permissions', list, list())
# add user if it doesn't already exists
if execute_command(['getent', 'passwd', user])['returncode'] == 0:
print("User '{0}' already exists, skipping...".format(user))
else:
print("Creating user '{0}'...".format(user))
useradd_cmd = ['useradd', '-m', '-p', hashed_password, '-U', '-s', '/bin/bash']
if uid:
useradd_cmd += ['-u', str(uid)]
if groups:
useradd_cmd += ['-G', ','.join(groups)]
if home:
useradd_cmd += ['-d', home]
useradd_cmd.append(user)
cmd_result = execute_command(useradd_cmd)
if cmd_result['returncode'] != 0:
raise Exception("Failed to create user '{0}': {1}".format(user, cmd_result['output']))
# set SSH public key
user_info = pwd.getpwnam(user)
ak_file = os.path.join(user_info.pw_dir, '.ssh/authorized_keys')
authorized_key_string = "## !!! DO NOT EDIT THIS FILE !!!\n## This file is generated automatically. Any changes will eventually be lost.\n## If you like to add a SSH Public Key contact your administrator.\n" + ssh_public_key
os.makedirs(os.path.dirname(ak_file), 0o750, True)
with open(file=ak_file, mode='w', encoding='utf8') as f:
f.write(authorized_key_string)
os.chmod(ak_file, 0o400)
recursive_chown(user_info.pw_dir, user_info.pw_uid, user_info.pw_gid)
# parse permissions
for perm in permissions:
path = get_arg(perm, "path", str, None, required=True)
if not os.path.exists(path):
if args.create_dir:
os.makedirs(path, 0o750)
else:
raise IOError("The directory or file '{0}' does not exist".format(path))
path_permissions = get_arg(perm, 'permissions', str, defaults['user_permissions'])
new_acl = {'name': user, 'permissions': path_permissions}
if path in acls:
acls[path]['users'].append(new_acl)
else:
user_group_default = {'name': '', 'permissions': defaults['user_permissions']}
acls[path] = {'users': [user_group_default, new_acl], 'groups': [user_group_default],
'other': '---'}
# set ACLs
paths = list(acls.keys())
paths.sort()
# find prefix paths and append permissions, otherwise longer paths will overwrite the shorter paths permissions
for p1, p2 in product(paths, paths):
if p1 != p2 and p2.startswith(p1):
acls[p2]['users'] += acls[p1]['users']
acls[p2]['groups'] += acls[p1]['groups']
for path in paths:
old_acl = ACL.get_file_acl(path)
acls[path]['owner'] = {'name': old_acl['owner']['name'], 'permissions': defaults['owner_permissions'] or old_acl['owner']['permissions']}
acls[path]['group'] = {'name': old_acl['group']['name'], 'permissions': defaults['owner_group_permissions'] or old_acl['group']['permissions']}
ACL.set_file_acl(path, acls[path], args.force)
except Exception as e:
sys.stderr.write(str(e) + '\n\n')
traceback.print_exc(5)
exit(1)
if __name__ == '__main__':
main()
| 46.175896 | 236 | 0.55862 | import argparse
import crypt
import json
import os
import pwd
import random
import re
import string
import subprocess
import sys
import traceback
from itertools import product
import yaml
class ACL:
@staticmethod
def get_file_acl(path):
if not os.path.exists(path):
raise IOError("The directory or file '{0}' does not exist".format(path))
cmd_result = execute_command(['getfacl', '-p', path])
if cmd_result['returncode'] != 0:
raise Exception("Failed to get ACL of file or directory '{0}': {1}".format(path, cmd_result['output']))
raw_acl = cmd_result['output'].splitlines()
owner = re.match(r'# owner: (.+)', raw_acl[1]).group(1)
group = re.match(r'# group: (.+)', raw_acl[2]).group(1)
acl = {'users': [], 'groups': [], 'other': None}
for a in raw_acl[3:]:
match_acl = re.match(r'user::([rwx-]+)', a)
if match_acl:
acl['users'].append({'name': '', 'permissions': match_acl.group(1)})
acl['owner'] = {'name': owner, 'permissions': match_acl.group(1)}
continue
match_acl = re.match(r'user:([^:]+):([rwx-]+)', a)
if match_acl:
acl['users'].append({'name': match_acl.group(1), 'permissions': match_acl.group(2)})
continue
match_acl = re.match(r'group::([rwx-]+)', a)
if match_acl:
acl['groups'].append({'name': '', 'permissions': match_acl.group(1)})
acl['group'] = {'name': group, 'permissions': match_acl.group(1)}
continue
match_acl = re.match(r'group:([^:]+):([rwx-]+)', a)
if match_acl:
acl['groups'].append({'name': match_acl.group(1), 'permissions': match_acl.group(2)})
continue
match_acl = re.match(r'other::([rwx-]+)', a)
if match_acl:
acl['other'] = match_acl.group(1)
continue
return acl
@staticmethod
def file_acl_differs(path, new_acl):
old_acl = ACL.get_file_acl(path)
return json.dumps(old_acl, sort_keys=True) != json.dumps(new_acl, sort_keys=True)
@staticmethod
def set_file_acl(path, new_acl, force=False):
def format_acl_spec(prefix, name, permissions):
acl_spec = list()
acl_spec.append("{0}:{1}:{2}".format(prefix, name, permissions))
if os.path.isdir(path):
acl_spec.append("d:{0}:{1}:{2}".format(prefix, name, permissions))
return ','.join(acl_spec)
old_acl = ACL.get_file_acl(path)
if force or json.dumps(old_acl, sort_keys=True) != json.dumps(new_acl, sort_keys=True):
print("Setting ACLs of '{0}...".format(path))
# modify ACLs
setfacl_cmd = ['setfacl', '-R', '-m']
acl_spec = list()
for uacl in new_acl['users']:
acl_spec.append(format_acl_spec('u', uacl['name'], uacl['permissions']))
# explicitly add owner (e.g. webserver), so sub directories created
# by different user will still be readable by the original owner
acl_spec.append(format_acl_spec('u', new_acl['owner']['name'], new_acl['owner']['permissions']))
for gacl in new_acl['groups']:
acl_spec.append(format_acl_spec('g', gacl['name'], gacl['permissions']))
acl_spec.append(format_acl_spec('g', new_acl['group']['name'], new_acl['group']['permissions']))
acl_spec.append(format_acl_spec('o', '', new_acl['other']))
setfacl_cmd.append(','.join(acl_spec))
setfacl_cmd.append(path)
cmd_result = execute_command(setfacl_cmd)
if cmd_result['returncode'] != 0:
raise Exception("Failed to set ACL of file or directory '{0}': {1}".format(path, cmd_result['output']))
# remove ACLs
setfacl_cmd = ['setfacl', '-R', '-x']
acl_spec = list()
users_to_remove = list(
set([x['name'] for x in old_acl['users']]) - set([x['name'] for x in new_acl['users']]))
groups_to_remove = list(
set([x['name'] for x in old_acl['groups']]) - set([x['name'] for x in new_acl['groups']]))
for u in users_to_remove:
acl_spec.append(format_acl_spec('u', u, ''))
for g in groups_to_remove:
acl_spec.append(format_acl_spec('g', g, ''))
if acl_spec:
setfacl_cmd.append(','.join(acl_spec))
setfacl_cmd.append(path)
cmd_result = execute_command(setfacl_cmd)
if cmd_result['returncode'] != 0:
raise Exception(
"Failed to remove ACL from file or directory '{0}': {1}".format(path, cmd_result['output']))
def get_arg(config, arg, dtype, default=None, required=False):
if required and not arg in config:
raise ValueError("Missing key '{0}'".format(arg))
if not arg in config:
return default
if type(config[arg]) is not dtype:
raise ValueError("'{0}' must be of type '{1}', got '{2}'".format(arg, str(dtype), str(config[arg])))
return config[arg]
def execute_command(cmd):
try:
return {'returncode': 0,
'output': subprocess.check_output(cmd, stderr=subprocess.STDOUT, universal_newlines=True)}
except subprocess.CalledProcessError as e:
return {'returncode': e.returncode, 'output': e.output}
def recursive_chown(path, uid, gid):
os.chown(path, uid, gid)
for item in os.listdir(path):
itempath = os.path.join(path, item)
if os.path.isfile(itempath):
os.chown(itempath, uid, gid)
elif os.path.isdir(itempath):
os.chown(itempath, uid, gid)
recursive_chown(itempath, uid, gid)
def main():
# parse arguments
parser = argparse.ArgumentParser(
prog='setup-users-and-groups',
description='According to a configuration file this script creates Linux users/groups and grants permissions on resources.',
add_help=True)
parser.add_argument('-f', '--force', dest='force',
action='store_true', default=False, help="Force the setting the ACLs.")
parser.add_argument('-c', '--create-dir', dest='create_dir',
action='store_true', default=False, help="Create a directory for a path that does not exists.")
parser.add_argument('configuration_file', help="File that defines what to do.")
args = parser.parse_args(sys.argv[1:])
try:
# load configuration either from file or from stdin
if args.configuration_file == '-':
inp = sys.stdin.read()
config = yaml.load(inp) or dict()
else:
if not os.path.exists(args.configuration_file):
raise IOError("The configuration file '{0}' does not exist".format(args.configuration_file))
with open(file=args.configuration_file, mode='r', encoding='utf8') as f:
config = yaml.load(f.read())
# parse arguments
groups = get_arg(config, "groups", dict, dict())
users = get_arg(config, "users", dict, dict())
defaults = get_arg(config, "defaults", dict, None) or dict()
defaults = {
'owner_permissions': get_arg(defaults, "owner_permissions", str, None),
'owner_group_permissions': get_arg(defaults, "owner_group_permissions", str, None),
'user_permissions': get_arg(defaults, "user_permissions", str, 'rwx'),
'group_permissions': get_arg(defaults, "group_permissions", str, 'rwx'),
}
acls = dict()
# create groups
for group, gdef in groups.items():
if type(gdef) != dict:
raise ValueError("The group definition of '{0}' must be of type dict".format(group))
gid = get_arg(gdef, 'gid', int, None)
permissions = get_arg(gdef, 'permissions', list, list())
# add group if it doesn't already exists
if execute_command(['getent', 'group', group])['returncode'] == 0:
print("Group '{0}' already exists, skipping...".format(group))
else:
print("Creating group '{0}'...".format(group))
groupadd_cmd = ['groupadd']
if gid:
groupadd_cmd += ['-g', str(gid)]
groupadd_cmd.append(group)
cmd_result = execute_command(groupadd_cmd)
if cmd_result['returncode'] != 0:
raise Exception("Failed to create group '{0}': {1}".format(group, cmd_result['output']))
for perm in permissions:
path = get_arg(perm, "path", str, None, required=True)
if not os.path.exists(path):
if args.create_dir:
os.makedirs(path, 0o750);
else:
raise IOError("The directory or file '{0}' does not exist".format(path))
path_permissions = get_arg(perm, 'permissions', str, defaults['group_permissions'])
new_acl = {'name': group, 'permissions': path_permissions}
if path in acls:
acls[path]['groups'].append(new_acl)
else:
user_group_default = {'name': '', 'permissions': defaults['group_permissions']}
acls[path] = {'users': [user_group_default], 'groups': [user_group_default, new_acl],
'other': '---'}
for user, udef in users.items():
if type(udef) != dict:
raise ValueError("The user definition of '{0}' must be of type dict".format(user))
uid = get_arg(udef, 'uid', int, None)
groups = get_arg(udef, 'groups', list, None)
home = get_arg(udef, 'home', str, None)
random_string = ''.join(
random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(64))
hashed_password = crypt.crypt(get_arg(udef, 'password', str, random_string),
crypt.mksalt(crypt.METHOD_SHA512))
ssh_public_key = get_arg(udef, 'ssh_public_key', str, '')
permissions = get_arg(udef, 'permissions', list, list())
if execute_command(['getent', 'passwd', user])['returncode'] == 0:
print("User '{0}' already exists, skipping...".format(user))
else:
print("Creating user '{0}'...".format(user))
useradd_cmd = ['useradd', '-m', '-p', hashed_password, '-U', '-s', '/bin/bash']
if uid:
useradd_cmd += ['-u', str(uid)]
if groups:
useradd_cmd += ['-G', ','.join(groups)]
if home:
useradd_cmd += ['-d', home]
useradd_cmd.append(user)
cmd_result = execute_command(useradd_cmd)
if cmd_result['returncode'] != 0:
raise Exception("Failed to create user '{0}': {1}".format(user, cmd_result['output']))
# set SSH public key
user_info = pwd.getpwnam(user)
ak_file = os.path.join(user_info.pw_dir, '.ssh/authorized_keys')
authorized_key_string = "## !!! DO NOT EDIT THIS FILE !!!\n## This file is generated automatically. Any changes will eventually be lost.\n## If you like to add a SSH Public Key contact your administrator.\n" + ssh_public_key
os.makedirs(os.path.dirname(ak_file), 0o750, True)
with open(file=ak_file, mode='w', encoding='utf8') as f:
f.write(authorized_key_string)
os.chmod(ak_file, 0o400)
recursive_chown(user_info.pw_dir, user_info.pw_uid, user_info.pw_gid)
# parse permissions
for perm in permissions:
path = get_arg(perm, "path", str, None, required=True)
if not os.path.exists(path):
if args.create_dir:
os.makedirs(path, 0o750)
else:
raise IOError("The directory or file '{0}' does not exist".format(path))
path_permissions = get_arg(perm, 'permissions', str, defaults['user_permissions'])
new_acl = {'name': user, 'permissions': path_permissions}
if path in acls:
acls[path]['users'].append(new_acl)
else:
user_group_default = {'name': '', 'permissions': defaults['user_permissions']}
acls[path] = {'users': [user_group_default, new_acl], 'groups': [user_group_default],
'other': '---'}
# set ACLs
paths = list(acls.keys())
paths.sort()
# find prefix paths and append permissions, otherwise longer paths will overwrite the shorter paths permissions
for p1, p2 in product(paths, paths):
if p1 != p2 and p2.startswith(p1):
acls[p2]['users'] += acls[p1]['users']
acls[p2]['groups'] += acls[p1]['groups']
for path in paths:
old_acl = ACL.get_file_acl(path)
acls[path]['owner'] = {'name': old_acl['owner']['name'], 'permissions': defaults['owner_permissions'] or old_acl['owner']['permissions']}
acls[path]['group'] = {'name': old_acl['group']['name'], 'permissions': defaults['owner_group_permissions'] or old_acl['group']['permissions']}
ACL.set_file_acl(path, acls[path], args.force)
except Exception as e:
sys.stderr.write(str(e) + '\n\n')
traceback.print_exc(5)
exit(1)
if __name__ == '__main__':
main()
| true | true |
f73167cc38566b53bef2f4ba63993e95af6bb2c0 | 3,587 | py | Python | brian2/only.py | awillats/brian2 | e1107ed0cc4a7d6c69c1e2634b675ba09edfd9fc | [
"BSD-2-Clause"
] | 1 | 2021-06-10T15:28:51.000Z | 2021-06-10T15:28:51.000Z | brian2/only.py | awillats/brian2 | e1107ed0cc4a7d6c69c1e2634b675ba09edfd9fc | [
"BSD-2-Clause"
] | null | null | null | brian2/only.py | awillats/brian2 | e1107ed0cc4a7d6c69c1e2634b675ba09edfd9fc | [
"BSD-2-Clause"
] | null | null | null | '''
A dummy package to allow wildcard import from brian2 without also importing
the pylab (numpy + matplotlib) namespace.
Usage: ``from brian2.only import *``
'''
# To minimize the problems with imports, import the packages in a sensible
# order
# The units and utils package does not depend on any other Brian package and
# should be imported first
from brian2.units import *
from brian2.utils import *
from brian2.core.tracking import *
from brian2.core.names import *
from brian2.core.spikesource import *
# The following packages only depend on something in the above set
from brian2.core.variables import linked_var
from brian2.core.functions import *
from brian2.core.preferences import *
from brian2.core.clocks import *
from brian2.equations import *
# The base class only depends on the above sets
from brian2.core.base import *
# The rest...
from brian2.core.network import *
from brian2.core.magic import *
from brian2.core.operations import *
from brian2.stateupdaters import *
from brian2.codegen import *
from brian2.core.namespace import *
from brian2.groups import *
from brian2.groups.subgroup import *
from brian2.synapses import *
from brian2.monitors import *
from brian2.importexport import *
from brian2.input import *
from brian2.spatialneuron import *
from brian2.devices import set_device, get_device, device, all_devices, seed
import brian2.devices.cpp_standalone as _cpp_standalone
# preferences
import brian2.core.core_preferences as _core_preferences
prefs.load_preferences()
prefs.do_validation()
prefs._backup()
set_device(all_devices['runtime'])
def restore_initial_state():
'''
Restores internal Brian variables to the state they are in when Brian is imported
Resets ``defaultclock.dt = 0.1*ms``,
`BrianGlobalPreferences._restore` preferences, and set
`BrianObject._scope_current_key` back to 0.
'''
import gc
prefs._restore()
BrianObject._scope_current_key = 0
defaultclock.dt = 0.1*ms
gc.collect()
# make the test suite available via brian2.test()
from brian2.tests import run as test
from brian2.units import __all__ as _all_units
__all__ = [
'get_logger', 'BrianLogger', 'std_silent',
'Trackable',
'Nameable',
'SpikeSource',
'linked_var',
'DEFAULT_FUNCTIONS', 'Function', 'implementation', 'declare_types',
'PreferenceError', 'BrianPreference', 'prefs', 'brian_prefs',
'Clock', 'defaultclock',
'Equations', 'Expression', 'Statements',
'BrianObject',
'BrianObjectException',
'Network', 'profiling_summary', 'scheduling_summary',
'MagicNetwork', 'magic_network',
'MagicError',
'run', 'stop', 'collect', 'store', 'restore',
'start_scope',
'NetworkOperation', 'network_operation',
'StateUpdateMethod',
'linear', 'exact', 'independent',
'milstein', 'heun', 'euler', 'rk2', 'rk4', 'ExplicitStateUpdater',
'exponential_euler',
'gsl_rk2', 'gsl_rk4', 'gsl_rkf45', 'gsl_rkck', 'gsl_rk8pd',
'NumpyCodeObject', 'CythonCodeObject',
'get_local_namespace', 'DEFAULT_FUNCTIONS', 'DEFAULT_UNITS',
'DEFAULT_CONSTANTS',
'CodeRunner', 'Group', 'VariableOwner', 'NeuronGroup',
'Subgroup',
'Synapses',
'SpikeMonitor', 'EventMonitor', 'StateMonitor',
'PopulationRateMonitor',
'ImportExport',
'BinomialFunction', 'PoissonGroup', 'PoissonInput',
'SpikeGeneratorGroup', 'TimedArray',
'Morphology', 'Soma', 'Cylinder', 'Section', 'SpatialNeuron',
'set_device', 'get_device', 'device', 'all_devices', 'seed',
'restore_initial_state',
'test'
]
__all__.extend(_all_units)
| 31.191304 | 85 | 0.726234 |
from brian2.units import *
from brian2.utils import *
from brian2.core.tracking import *
from brian2.core.names import *
from brian2.core.spikesource import *
from brian2.core.variables import linked_var
from brian2.core.functions import *
from brian2.core.preferences import *
from brian2.core.clocks import *
from brian2.equations import *
from brian2.core.base import *
from brian2.core.network import *
from brian2.core.magic import *
from brian2.core.operations import *
from brian2.stateupdaters import *
from brian2.codegen import *
from brian2.core.namespace import *
from brian2.groups import *
from brian2.groups.subgroup import *
from brian2.synapses import *
from brian2.monitors import *
from brian2.importexport import *
from brian2.input import *
from brian2.spatialneuron import *
from brian2.devices import set_device, get_device, device, all_devices, seed
import brian2.devices.cpp_standalone as _cpp_standalone
import brian2.core.core_preferences as _core_preferences
prefs.load_preferences()
prefs.do_validation()
prefs._backup()
set_device(all_devices['runtime'])
def restore_initial_state():
import gc
prefs._restore()
BrianObject._scope_current_key = 0
defaultclock.dt = 0.1*ms
gc.collect()
from brian2.tests import run as test
from brian2.units import __all__ as _all_units
__all__ = [
'get_logger', 'BrianLogger', 'std_silent',
'Trackable',
'Nameable',
'SpikeSource',
'linked_var',
'DEFAULT_FUNCTIONS', 'Function', 'implementation', 'declare_types',
'PreferenceError', 'BrianPreference', 'prefs', 'brian_prefs',
'Clock', 'defaultclock',
'Equations', 'Expression', 'Statements',
'BrianObject',
'BrianObjectException',
'Network', 'profiling_summary', 'scheduling_summary',
'MagicNetwork', 'magic_network',
'MagicError',
'run', 'stop', 'collect', 'store', 'restore',
'start_scope',
'NetworkOperation', 'network_operation',
'StateUpdateMethod',
'linear', 'exact', 'independent',
'milstein', 'heun', 'euler', 'rk2', 'rk4', 'ExplicitStateUpdater',
'exponential_euler',
'gsl_rk2', 'gsl_rk4', 'gsl_rkf45', 'gsl_rkck', 'gsl_rk8pd',
'NumpyCodeObject', 'CythonCodeObject',
'get_local_namespace', 'DEFAULT_FUNCTIONS', 'DEFAULT_UNITS',
'DEFAULT_CONSTANTS',
'CodeRunner', 'Group', 'VariableOwner', 'NeuronGroup',
'Subgroup',
'Synapses',
'SpikeMonitor', 'EventMonitor', 'StateMonitor',
'PopulationRateMonitor',
'ImportExport',
'BinomialFunction', 'PoissonGroup', 'PoissonInput',
'SpikeGeneratorGroup', 'TimedArray',
'Morphology', 'Soma', 'Cylinder', 'Section', 'SpatialNeuron',
'set_device', 'get_device', 'device', 'all_devices', 'seed',
'restore_initial_state',
'test'
]
__all__.extend(_all_units)
| true | true |
f73168e6d9bed2cc8b08603295293be0c8f914d9 | 5,134 | py | Python | test/test_keytool_parse.py | cccs-rs/assemblyline-v4-service | ed53dedaa6f3c4e3850defd9f68b0d57407153bf | [
"MIT"
] | 6 | 2020-06-30T13:54:44.000Z | 2021-05-28T19:36:32.000Z | test/test_keytool_parse.py | cccs-rs/assemblyline-v4-service | ed53dedaa6f3c4e3850defd9f68b0d57407153bf | [
"MIT"
] | 17 | 2020-06-19T03:02:21.000Z | 2022-03-01T18:19:07.000Z | test/test_keytool_parse.py | cccs-rs/assemblyline-v4-service | ed53dedaa6f3c4e3850defd9f68b0d57407153bf | [
"MIT"
] | 8 | 2020-04-30T16:11:52.000Z | 2021-07-16T12:11:40.000Z | import pytest
class TestKeytoolParse:
@staticmethod
@pytest.mark.parametrize("printcert, correct_certs",
[
('Owner: CN=ca, OU=ca, O=ca, L=ca, ST=ca, C=CA\nIssuer: CN=root, OU=root, O=root, L=root, ST=root, C=CA\nSerial number: 5f822698\nValid from: Wed Apr 14 13:40:13 EDT 2021 until: Tue Jul 13 13:40:13 EDT 2021\nCertificate fingerprints:\n SHA1: 59:7C:A0:72:5D:98:9F:61:B9:9F:29:20:C8:73:60:9C:0E:02:EB:DF\n SHA256: AE:56:E7:5E:49:F2:1B:4B:FF:7A:76:12:6E:72:84:1C:6B:D3:E7:FA:D9:84:43:53:C7:24:A9:2F:3E:12:63:7F\nSignature algorithm name: SHA256withDSA\nSubject Public Key Algorithm: 2048-bit DSA key\nVersion: 3\n\nExtensions:\n\n#1: ObjectId: 2.5.29.35 Criticality=false\nAuthorityKeyIdentifier [\nKeyIdentifier [\n0000: 9D 76 79 BA 97 17 06 07 75 A6 5C E1 E6 98 09 F0 .vy.....u.\.....\n0010: D8 42 F6 C1 .B..\n]\n]\n\n#2: ObjectId: 2.5.29.19 Criticality=false\nBasicConstraints:[\n CA:true\n PathLen:0\n]\n\n#3: ObjectId: 2.5.29.14 Criticality=false\nSubjectKeyIdentifier [\nKeyIdentifier [\n0000: C2 BF E5 BF 85 2B ED 82 D2 F1 49 89 06 5B 5E 90 .....+....I..[^.\n0010: 64 FC C3 16 d...\n]\n]\n', [{'Owner': 'CN=ca, OU=ca, O=ca, L=ca, ST=ca, C=CA', 'Issuer': 'CN=root, OU=root, O=root, L=root, ST=root, C=CA', 'Country': 'CA', 'ValidFrom': 'Wed Apr 14 13:40:13 EDT 2021', 'ValidTo': 'Tue Jul 13 13:40:13 EDT 2021'}]),
('Certificate[1]:\nOwner: CN=server, OU=server, O=server, L=server, ST=server, C=CA\nIssuer: CN=ca, OU=ca, O=ca, L=ca, ST=ca, C=CA\nSerial number: 4e2d045a\nValid from: Wed Apr 14 13:42:22 EDT 2021 until: Tue Jul 13 13:42:22 EDT 2021\nCertificate fingerprints:\n SHA1: 0B:BE:A7:40:20:F4:F0:DE:D1:C8:99:26:32:A8:33:7A:EB:E8:87:70\n SHA256: 83:C1:8D:49:A4:98:3F:73:66:97:63:78:4C:E5:70:BF:0C:A2:71:4A:58:CE:B0:4E:65:87:39:F0:06:1F:7F:2C\nSignature algorithm name: SHA256withDSA\nSubject Public Key Algorithm: 2048-bit DSA key\nVersion: 3\n\nExtensions:\n\n#1: ObjectId: 2.5.29.35 Criticality=false\nAuthorityKeyIdentifier [\nKeyIdentifier [\n0000: C2 BF E5 BF 85 2B ED 82 D2 F1 49 89 06 5B 5E 90 .....+....I..[^.\n0010: 64 FC C3 16 d...\n]\n]\n\n#2: ObjectId: 2.5.29.15 Criticality=true\nKeyUsage [\n DigitalSignature\n Key_Encipherment\n]\n\n#3: ObjectId: 2.5.29.14 Criticality=false\nSubjectKeyIdentifier [\nKeyIdentifier [\n0000: 9B 06 D8 13 2E 6F 2F 62 85 66 42 A9 AC 86 2E A8 .....o/b.fB.....\n0010: 25 89 AB FC %...\n]\n]\n\n\nCertificate[2]:\nOwner: CN=ca, OU=ca, O=ca, L=ca, ST=ca, C=CA\nIssuer: CN=root, OU=root, O=root, L=root, ST=root, C=CA\nSerial number: 5f822698\nValid from: Wed Apr 14 13:40:13 EDT 2021 until: Tue Jul 13 13:40:13 EDT 2021\nCertificate fingerprints:\n SHA1: 59:7C:A0:72:5D:98:9F:61:B9:9F:29:20:C8:73:60:9C:0E:02:EB:DF\n SHA256: AE:56:E7:5E:49:F2:1B:4B:FF:7A:76:12:6E:72:84:1C:6B:D3:E7:FA:D9:84:43:53:C7:24:A9:2F:3E:12:63:7F\nSignature algorithm name: SHA256withDSA\nSubject Public Key Algorithm: 2048-bit DSA key\nVersion: 3\n\nExtensions:\n\n#1: ObjectId: 2.5.29.35 Criticality=false\nAuthorityKeyIdentifier [\nKeyIdentifier [\n0000: 9D 76 79 BA 97 17 06 07 75 A6 5C E1 E6 98 09 F0 .vy.....u.\.....\n0010: D8 42 F6 C1 .B..\n]\n]\n\n#2: ObjectId: 2.5.29.19 Criticality=false\nBasicConstraints:[\n CA:true\n PathLen:0\n]\n\n#3: ObjectId: 2.5.29.14 Criticality=false\nSubjectKeyIdentifier [\nKeyIdentifier [\n0000: C2 BF E5 BF 85 2B ED 82 D2 F1 49 89 06 5B 5E 90 .....+....I..[^.\n0010: 64 FC C3 16 d...\n]\n]\n', [{'Owner': 'CN=server, OU=server, O=server, L=server, ST=server, C=CA', 'Issuer': 'CN=ca, OU=ca, O=ca, L=ca, ST=ca, C=CA', 'Country': 'CA', 'ValidFrom': 'Wed Apr 14 13:42:22 EDT 2021', 'ValidTo': 'Tue Jul 13 13:42:22 EDT 2021'}, {'Owner': 'CN=ca, OU=ca, O=ca, L=ca, ST=ca, C=CA', 'Issuer': 'CN=root, OU=root, O=root, L=root, ST=root, C=CA', 'Country': 'CA', 'ValidFrom': 'Wed Apr 14 13:40:13 EDT 2021', 'ValidTo': 'Tue Jul 13 13:40:13 EDT 2021'}]),
]
)
def test_certificate_chain_from_printcert(printcert, correct_certs):
"""
This function tests that a printcert output is properly parsed by certificate_chain_from_printcert.
The certificates used come from running the commands in section 'Generate Certificates for an SSL Server'
in the keytool docs: https://docs.oracle.com/javase/8/docs/technotes/tools/windows/keytool.html
"""
from assemblyline_v4_service.common.keytool_parse import certificate_chain_from_printcert
certs = certificate_chain_from_printcert(printcert)
assert len(certs) == len(correct_certs)
for cert, correct in zip(certs, correct_certs):
assert cert.country == correct['Country']
assert cert.issuer == correct['Issuer']
assert cert.owner == correct['Owner']
assert cert.valid_from == correct['ValidFrom']
assert cert.valid_to == correct['ValidTo'] | 190.148148 | 2,706 | 0.639462 | import pytest
class TestKeytoolParse:
@staticmethod
@pytest.mark.parametrize("printcert, correct_certs",
[
('Owner: CN=ca, OU=ca, O=ca, L=ca, ST=ca, C=CA\nIssuer: CN=root, OU=root, O=root, L=root, ST=root, C=CA\nSerial number: 5f822698\nValid from: Wed Apr 14 13:40:13 EDT 2021 until: Tue Jul 13 13:40:13 EDT 2021\nCertificate fingerprints:\n SHA1: 59:7C:A0:72:5D:98:9F:61:B9:9F:29:20:C8:73:60:9C:0E:02:EB:DF\n SHA256: AE:56:E7:5E:49:F2:1B:4B:FF:7A:76:12:6E:72:84:1C:6B:D3:E7:FA:D9:84:43:53:C7:24:A9:2F:3E:12:63:7F\nSignature algorithm name: SHA256withDSA\nSubject Public Key Algorithm: 2048-bit DSA key\nVersion: 3\n\nExtensions:\n\n#1: ObjectId: 2.5.29.35 Criticality=false\nAuthorityKeyIdentifier [\nKeyIdentifier [\n0000: 9D 76 79 BA 97 17 06 07 75 A6 5C E1 E6 98 09 F0 .vy.....u.\.....\n0010: D8 42 F6 C1 .B..\n]\n]\n\n#2: ObjectId: 2.5.29.19 Criticality=false\nBasicConstraints:[\n CA:true\n PathLen:0\n]\n\n#3: ObjectId: 2.5.29.14 Criticality=false\nSubjectKeyIdentifier [\nKeyIdentifier [\n0000: C2 BF E5 BF 85 2B ED 82 D2 F1 49 89 06 5B 5E 90 .....+....I..[^.\n0010: 64 FC C3 16 d...\n]\n]\n', [{'Owner': 'CN=ca, OU=ca, O=ca, L=ca, ST=ca, C=CA', 'Issuer': 'CN=root, OU=root, O=root, L=root, ST=root, C=CA', 'Country': 'CA', 'ValidFrom': 'Wed Apr 14 13:40:13 EDT 2021', 'ValidTo': 'Tue Jul 13 13:40:13 EDT 2021'}]),
('Certificate[1]:\nOwner: CN=server, OU=server, O=server, L=server, ST=server, C=CA\nIssuer: CN=ca, OU=ca, O=ca, L=ca, ST=ca, C=CA\nSerial number: 4e2d045a\nValid from: Wed Apr 14 13:42:22 EDT 2021 until: Tue Jul 13 13:42:22 EDT 2021\nCertificate fingerprints:\n SHA1: 0B:BE:A7:40:20:F4:F0:DE:D1:C8:99:26:32:A8:33:7A:EB:E8:87:70\n SHA256: 83:C1:8D:49:A4:98:3F:73:66:97:63:78:4C:E5:70:BF:0C:A2:71:4A:58:CE:B0:4E:65:87:39:F0:06:1F:7F:2C\nSignature algorithm name: SHA256withDSA\nSubject Public Key Algorithm: 2048-bit DSA key\nVersion: 3\n\nExtensions:\n\n#1: ObjectId: 2.5.29.35 Criticality=false\nAuthorityKeyIdentifier [\nKeyIdentifier [\n0000: C2 BF E5 BF 85 2B ED 82 D2 F1 49 89 06 5B 5E 90 .....+....I..[^.\n0010: 64 FC C3 16 d...\n]\n]\n\n#2: ObjectId: 2.5.29.15 Criticality=true\nKeyUsage [\n DigitalSignature\n Key_Encipherment\n]\n\n#3: ObjectId: 2.5.29.14 Criticality=false\nSubjectKeyIdentifier [\nKeyIdentifier [\n0000: 9B 06 D8 13 2E 6F 2F 62 85 66 42 A9 AC 86 2E A8 .....o/b.fB.....\n0010: 25 89 AB FC %...\n]\n]\n\n\nCertificate[2]:\nOwner: CN=ca, OU=ca, O=ca, L=ca, ST=ca, C=CA\nIssuer: CN=root, OU=root, O=root, L=root, ST=root, C=CA\nSerial number: 5f822698\nValid from: Wed Apr 14 13:40:13 EDT 2021 until: Tue Jul 13 13:40:13 EDT 2021\nCertificate fingerprints:\n SHA1: 59:7C:A0:72:5D:98:9F:61:B9:9F:29:20:C8:73:60:9C:0E:02:EB:DF\n SHA256: AE:56:E7:5E:49:F2:1B:4B:FF:7A:76:12:6E:72:84:1C:6B:D3:E7:FA:D9:84:43:53:C7:24:A9:2F:3E:12:63:7F\nSignature algorithm name: SHA256withDSA\nSubject Public Key Algorithm: 2048-bit DSA key\nVersion: 3\n\nExtensions:\n\n#1: ObjectId: 2.5.29.35 Criticality=false\nAuthorityKeyIdentifier [\nKeyIdentifier [\n0000: 9D 76 79 BA 97 17 06 07 75 A6 5C E1 E6 98 09 F0 .vy.....u.\.....\n0010: D8 42 F6 C1 .B..\n]\n]\n\n#2: ObjectId: 2.5.29.19 Criticality=false\nBasicConstraints:[\n CA:true\n PathLen:0\n]\n\n#3: ObjectId: 2.5.29.14 Criticality=false\nSubjectKeyIdentifier [\nKeyIdentifier [\n0000: C2 BF E5 BF 85 2B ED 82 D2 F1 49 89 06 5B 5E 90 .....+....I..[^.\n0010: 64 FC C3 16 d...\n]\n]\n', [{'Owner': 'CN=server, OU=server, O=server, L=server, ST=server, C=CA', 'Issuer': 'CN=ca, OU=ca, O=ca, L=ca, ST=ca, C=CA', 'Country': 'CA', 'ValidFrom': 'Wed Apr 14 13:42:22 EDT 2021', 'ValidTo': 'Tue Jul 13 13:42:22 EDT 2021'}, {'Owner': 'CN=ca, OU=ca, O=ca, L=ca, ST=ca, C=CA', 'Issuer': 'CN=root, OU=root, O=root, L=root, ST=root, C=CA', 'Country': 'CA', 'ValidFrom': 'Wed Apr 14 13:40:13 EDT 2021', 'ValidTo': 'Tue Jul 13 13:40:13 EDT 2021'}]),
]
)
def test_certificate_chain_from_printcert(printcert, correct_certs):
from assemblyline_v4_service.common.keytool_parse import certificate_chain_from_printcert
certs = certificate_chain_from_printcert(printcert)
assert len(certs) == len(correct_certs)
for cert, correct in zip(certs, correct_certs):
assert cert.country == correct['Country']
assert cert.issuer == correct['Issuer']
assert cert.owner == correct['Owner']
assert cert.valid_from == correct['ValidFrom']
assert cert.valid_to == correct['ValidTo'] | true | true |
f7316970b0437dcd982b168d5fcd16d064c8cb16 | 8,044 | py | Python | tempest/api/identity/admin/v3/test_domain_configuration.py | mail2nsrajesh/tempest | 1a3b3dc50b418d3a15839830d7d1ff88c8c76cff | [
"Apache-2.0"
] | null | null | null | tempest/api/identity/admin/v3/test_domain_configuration.py | mail2nsrajesh/tempest | 1a3b3dc50b418d3a15839830d7d1ff88c8c76cff | [
"Apache-2.0"
] | null | null | null | tempest/api/identity/admin/v3/test_domain_configuration.py | mail2nsrajesh/tempest | 1a3b3dc50b418d3a15839830d7d1ff88c8c76cff | [
"Apache-2.0"
] | 5 | 2016-06-24T20:03:52.000Z | 2020-02-05T10:14:54.000Z | # Copyright 2017 AT&T Corporation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.api.identity import base
from tempest.lib.common.utils import data_utils
from tempest.lib.common.utils import test_utils
from tempest.lib import decorators
from tempest.lib import exceptions as lib_exc
class DomainConfigurationTestJSON(base.BaseIdentityV3AdminTest):
custom_config = {
"identity": {
"driver": "ldap"
},
"ldap": {
"url": "ldap://myldap.com:389/",
"user_tree_dn": "ou=Users,dc=my_new_root,dc=org"
}
}
@classmethod
def setup_clients(cls):
super(DomainConfigurationTestJSON, cls).setup_clients()
cls.client = cls.domain_config_client
@classmethod
def resource_setup(cls):
super(DomainConfigurationTestJSON, cls).resource_setup()
cls.group = cls.groups_client.create_group(
name=data_utils.rand_name('group'),
description=data_utils.rand_name('group-desc'))['group']
@classmethod
def resource_cleanup(cls):
cls.groups_client.delete_group(cls.group['id'])
super(DomainConfigurationTestJSON, cls).resource_cleanup()
def _create_domain_and_config(self, config):
domain = self.setup_test_domain()
config = self.client.create_domain_config(domain['id'], **config)[
'config']
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.client.delete_domain_config, domain['id'])
return domain, config
@decorators.idempotent_id('11a02bf0-6f94-4380-b3b0-c8dc18fc0d22')
def test_show_default_group_config_and_options(self):
# The API supports only the identity and ldap groups. For the ldap
# group, a valid value is url or user_tree_dn. For the identity group,
# a valid value is driver.
# Check that the default config has the identity and ldap groups.
config = self.client.show_default_config_settings()['config']
self.assertIsInstance(config, dict)
self.assertIn('identity', config)
self.assertIn('ldap', config)
# Check that the identity group is correct.
identity_config = self.client.show_default_group_config('identity')[
'config']
self.assertIsInstance(identity_config, dict)
self.assertIn('identity', identity_config)
self.assertIn('driver', identity_config['identity'])
self.assertIn('list_limit', identity_config['identity'])
# Show each option for the default domain and identity group.
for config_opt_name in ['driver', 'list_limit']:
retrieved_config_opt = self.client.show_default_group_option(
'identity', config_opt_name)['config']
self.assertIn(config_opt_name, retrieved_config_opt)
# Check that the ldap group is correct.
ldap_config = self.client.show_default_group_config('ldap')['config']
self.assertIsInstance(ldap_config, dict)
self.assertIn('ldap', ldap_config)
# Several valid options exist for ldap group.
valid_options = ldap_config['ldap'].keys()
# Show each option for the default domain and ldap group.
for config_opt_name in valid_options:
retrieved_config_opt = self.client.show_default_group_option(
'ldap', config_opt_name)['config']
self.assertIn(config_opt_name, retrieved_config_opt)
@decorators.idempotent_id('9e3ff13c-f597-4f01-9377-d6c06c2a1477')
def test_create_domain_config_and_show_config_groups_and_options(self):
domain, created_config = self._create_domain_and_config(
self.custom_config)
# Check that the entire configuration is correct.
self.assertEqual(self.custom_config, created_config)
# Check that each configuration group is correct.
for group_name in self.custom_config.keys():
group_cfg = self.client.show_domain_group_config(
domain['id'], group_name)['config']
self.assertIn(group_name, group_cfg)
self.assertEqual(self.custom_config[group_name],
group_cfg[group_name])
# Check that each configuration option is correct.
for opt_name in self.custom_config[group_name].keys():
group_opt = self.client.show_domain_group_option_config(
domain['id'], group_name, opt_name)['config']
self.assertIn(opt_name, group_opt)
self.assertEqual(self.custom_config[group_name][opt_name],
group_opt[opt_name])
@decorators.idempotent_id('7161023e-5dd0-4612-9da0-1bac6ac30b63')
def test_create_update_and_delete_domain_config(self):
domain, created_config = self._create_domain_and_config(
self.custom_config)
new_config = created_config
new_config['ldap']['url'] = data_utils.rand_url()
# Check that the altered configuration is reflected in updated_config.
updated_config = self.client.update_domain_config(
domain['id'], **new_config)['config']
self.assertEqual(new_config, updated_config)
# Check that showing the domain config shows the altered configuration.
retrieved_config = self.client.show_domain_config(domain['id'])[
'config']
self.assertEqual(new_config, retrieved_config)
# Check that deleting a configuration works.
self.client.delete_domain_config(domain['id'])
self.assertRaises(lib_exc.NotFound, self.client.show_domain_config,
domain['id'])
@decorators.idempotent_id('c7510fa2-6661-4170-9c6b-4783a80651e9')
def test_create_update_and_delete_domain_config_groups_and_opts(self):
domain, _ = self._create_domain_and_config(self.custom_config)
# Check that updating configuration groups work.
new_driver = data_utils.rand_name('driver')
new_limit = data_utils.rand_int_id(0, 100)
new_group_config = {'identity': {'driver': new_driver,
'list_limit': new_limit}}
updated_config = self.client.update_domain_group_config(
domain['id'], 'identity', **new_group_config)['config']
self.assertEqual(new_driver, updated_config['identity']['driver'])
self.assertEqual(new_limit, updated_config['identity']['list_limit'])
# Check that updating individual configuration group options work.
new_driver = data_utils.rand_name('driver')
updated_config = self.client.update_domain_group_option_config(
domain['id'], 'identity', 'driver', driver=new_driver)['config']
self.assertEqual(new_driver, updated_config['identity']['driver'])
# Check that deleting individual configuration group options work.
self.client.delete_domain_group_option_config(
domain['id'], 'identity', 'driver')
self.assertRaises(lib_exc.NotFound,
self.client.show_domain_group_option_config,
domain['id'], 'identity', 'driver')
# Check that deleting configuration groups work.
self.client.delete_domain_group_config(domain['id'], 'identity')
self.assertRaises(lib_exc.NotFound,
self.client.show_domain_group_config,
domain['id'], 'identity')
| 43.481081 | 79 | 0.669443 |
from tempest.api.identity import base
from tempest.lib.common.utils import data_utils
from tempest.lib.common.utils import test_utils
from tempest.lib import decorators
from tempest.lib import exceptions as lib_exc
class DomainConfigurationTestJSON(base.BaseIdentityV3AdminTest):
custom_config = {
"identity": {
"driver": "ldap"
},
"ldap": {
"url": "ldap://myldap.com:389/",
"user_tree_dn": "ou=Users,dc=my_new_root,dc=org"
}
}
@classmethod
def setup_clients(cls):
super(DomainConfigurationTestJSON, cls).setup_clients()
cls.client = cls.domain_config_client
@classmethod
def resource_setup(cls):
super(DomainConfigurationTestJSON, cls).resource_setup()
cls.group = cls.groups_client.create_group(
name=data_utils.rand_name('group'),
description=data_utils.rand_name('group-desc'))['group']
@classmethod
def resource_cleanup(cls):
cls.groups_client.delete_group(cls.group['id'])
super(DomainConfigurationTestJSON, cls).resource_cleanup()
def _create_domain_and_config(self, config):
domain = self.setup_test_domain()
config = self.client.create_domain_config(domain['id'], **config)[
'config']
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.client.delete_domain_config, domain['id'])
return domain, config
@decorators.idempotent_id('11a02bf0-6f94-4380-b3b0-c8dc18fc0d22')
def test_show_default_group_config_and_options(self):
config = self.client.show_default_config_settings()['config']
self.assertIsInstance(config, dict)
self.assertIn('identity', config)
self.assertIn('ldap', config)
identity_config = self.client.show_default_group_config('identity')[
'config']
self.assertIsInstance(identity_config, dict)
self.assertIn('identity', identity_config)
self.assertIn('driver', identity_config['identity'])
self.assertIn('list_limit', identity_config['identity'])
for config_opt_name in ['driver', 'list_limit']:
retrieved_config_opt = self.client.show_default_group_option(
'identity', config_opt_name)['config']
self.assertIn(config_opt_name, retrieved_config_opt)
ldap_config = self.client.show_default_group_config('ldap')['config']
self.assertIsInstance(ldap_config, dict)
self.assertIn('ldap', ldap_config)
valid_options = ldap_config['ldap'].keys()
for config_opt_name in valid_options:
retrieved_config_opt = self.client.show_default_group_option(
'ldap', config_opt_name)['config']
self.assertIn(config_opt_name, retrieved_config_opt)
@decorators.idempotent_id('9e3ff13c-f597-4f01-9377-d6c06c2a1477')
def test_create_domain_config_and_show_config_groups_and_options(self):
domain, created_config = self._create_domain_and_config(
self.custom_config)
self.assertEqual(self.custom_config, created_config)
for group_name in self.custom_config.keys():
group_cfg = self.client.show_domain_group_config(
domain['id'], group_name)['config']
self.assertIn(group_name, group_cfg)
self.assertEqual(self.custom_config[group_name],
group_cfg[group_name])
for opt_name in self.custom_config[group_name].keys():
group_opt = self.client.show_domain_group_option_config(
domain['id'], group_name, opt_name)['config']
self.assertIn(opt_name, group_opt)
self.assertEqual(self.custom_config[group_name][opt_name],
group_opt[opt_name])
@decorators.idempotent_id('7161023e-5dd0-4612-9da0-1bac6ac30b63')
def test_create_update_and_delete_domain_config(self):
domain, created_config = self._create_domain_and_config(
self.custom_config)
new_config = created_config
new_config['ldap']['url'] = data_utils.rand_url()
updated_config = self.client.update_domain_config(
domain['id'], **new_config)['config']
self.assertEqual(new_config, updated_config)
retrieved_config = self.client.show_domain_config(domain['id'])[
'config']
self.assertEqual(new_config, retrieved_config)
self.client.delete_domain_config(domain['id'])
self.assertRaises(lib_exc.NotFound, self.client.show_domain_config,
domain['id'])
@decorators.idempotent_id('c7510fa2-6661-4170-9c6b-4783a80651e9')
def test_create_update_and_delete_domain_config_groups_and_opts(self):
domain, _ = self._create_domain_and_config(self.custom_config)
new_driver = data_utils.rand_name('driver')
new_limit = data_utils.rand_int_id(0, 100)
new_group_config = {'identity': {'driver': new_driver,
'list_limit': new_limit}}
updated_config = self.client.update_domain_group_config(
domain['id'], 'identity', **new_group_config)['config']
self.assertEqual(new_driver, updated_config['identity']['driver'])
self.assertEqual(new_limit, updated_config['identity']['list_limit'])
new_driver = data_utils.rand_name('driver')
updated_config = self.client.update_domain_group_option_config(
domain['id'], 'identity', 'driver', driver=new_driver)['config']
self.assertEqual(new_driver, updated_config['identity']['driver'])
self.client.delete_domain_group_option_config(
domain['id'], 'identity', 'driver')
self.assertRaises(lib_exc.NotFound,
self.client.show_domain_group_option_config,
domain['id'], 'identity', 'driver')
self.client.delete_domain_group_config(domain['id'], 'identity')
self.assertRaises(lib_exc.NotFound,
self.client.show_domain_group_config,
domain['id'], 'identity')
| true | true |
f731698f7c8a52b2ad20a1732001853d221b636d | 9,161 | py | Python | metalibm_core/code_generation/code_function.py | metalibm/metalibm-clone | d04839e58950a156b79b763b9f45cb874e21ebfe | [
"MIT"
] | null | null | null | metalibm_core/code_generation/code_function.py | metalibm/metalibm-clone | d04839e58950a156b79b763b9f45cb874e21ebfe | [
"MIT"
] | null | null | null | metalibm_core/code_generation/code_function.py | metalibm/metalibm-clone | d04839e58950a156b79b763b9f45cb874e21ebfe | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
###############################################################################
# This file is part of metalibm (https://github.com/kalray/metalibm)
###############################################################################
# MIT License
#
# Copyright (c) 2018 Kalray
#
# 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.
###############################################################################
# created: Feb 1st, 2016
# last-modified: Mar 7th, 2018
#
# author(s): Nicolas Brunie (nicolas.brunie@kalray.eu)
###############################################################################
from ..core.ml_operations import Variable, FunctionObject, FunctionType
from .code_object import NestedCode
from .generator_utility import FunctionOperator, FO_Arg
from .code_constant import *
class CodeFunction(object):
""" function code object """
def __init__(self, name, arg_list=None, output_format=None, code_object=None, language=C_Code, attributes=None):
""" code function initialization """
self.arg_list = arg_list if arg_list else []
arg_list_precision = [arg.get_precision() for arg in self.arg_list]
self.function_type = FunctionType(name, arg_list_precision, output_format, attributes)
self.code_object = code_object
self.function_object = None
self.function_operator = None
self.language = language
@property
def name(self):
return self.function_type.name
@property
def output_format(self):
return self.function_type.output_format
@property
def attributes(self):
return self.function_type.attributes
def get_name(self):
return self.name
def add_input_variable(self, name, vartype, **kw):
""" declares a new Variable with name @p name and format @p vartype
and registers it as an input variable """
input_var = Variable(name, precision = vartype, **kw)
self.arg_list.append(input_var)
# WARNING: self.function_type.arg_list_precision is not updated
return input_var
def register_new_input_variable(self, new_input):
self.arg_list.append(new_input)
# WARNING: self.function_type.arg_list_precision is not updated
def get_arg_list(self):
return self.arg_list
def clear_arg_list(self):
self.arg_list = []
def get_function_object(self):
# if None, build it
if self.function_object is None:
self.function_object = self.build_function_object()
return self.function_object
def build_function_object(self):
arg_list_precision = [arg.get_precision() for arg in self.arg_list]
return FunctionObject(self.name, arg_list_precision, self.output_format, self.get_function_operator(), self.attributes)
def get_function_operator(self):
return self.build_function_operator()
def build_function_operator(self):
function_arg_map = {}
for i in range(len(self.arg_list)):
function_arg_map[i] = FO_Arg(i)
return FunctionOperator(self.name, arg_map = function_arg_map)
## retrieve format of the result(s) returned by the function
# @return ML_Format object
def get_output_format(self):
return self.output_format
## define a new at for the function return value(s)
# @param new_output_format ML_Format object indicated which format is returned by the function
def set_output_format(self, new_output_format):
self.function_type.output_format = new_output_format
def add_attribute(self, attribute):
assert not attribute in self.attributes
self.attributes.append(attribute)
def get_attributes_dec(self, language=C_Code):
""" generate function attribute string """
if self.attributes:
return " ".join(self.attributes)
return ""
def get_LLVM_definition(self, final=True, language=LLVM_IR_Code):
# TODO: support attributes and metadata
arg_format_list = ", ".join("%s %s" % (inp.get_precision().get_name(language = language), inp.get_tag()) for inp in self.arg_list)
return "define %s @%s(%s)" % (self.output_format.get_name(language = language), self.name, arg_format_list)
def update_arg_list_precisions(self):
self.function_type.arg_list_precision = [arg.precision for arg in self.arg_list]
def get_declaration(self, code_generator, final=True, language=None, named_arg_list=False, is_definition=False):
"""
:param self:
:param for_definition: indicate if the declaration is a definition prolog or a true declaration
:type for_definition: bool
"""
self.update_arg_list_precisions()
language = self.language if language is None else language
if is_definition:
return code_generator.get_function_definition(self.function_type, final, language, arg_list=(self.arg_list if named_arg_list else None))
else:
# pure declaration
return code_generator.get_function_declaration(self.function_type, final, language, arg_list=(self.arg_list if named_arg_list else None))
#self.name, self.output_format, self.arg_list, final, language
#)
## define function implementation
# @param scheme ML_Operation object to be defined as function implementation
def set_scheme(self, scheme):
self.scheme = scheme
## @return function implementation (ML_Operation DAG)
def get_scheme(self):
return self.scheme
def get_definition(self, code_generator, language, folded = True, static_cst = False):
code_object = NestedCode(code_generator, static_cst = static_cst)
code_object << self.get_declaration(code_generator, final=False, language=language, named_arg_list=True, is_definition=True)
code_object.open_level()
code_generator.generate_expr(code_object, self.scheme, folded = folded, initial = True, language = language)
code_object.close_level()
return code_object
def add_definition(self, code_generator, language, code_object, folded = True, static_cst = False):
code_object << self.get_declaration(code_generator, final=False, language=language, named_arg_list=True, is_definition=True)
code_object.open_level()
code_generator.generate_expr(code_object, self.scheme, folded = folded, initial = True, language = language)
code_object.close_level()
return code_object
def add_declaration(self, code_generator, language, code_object):
code_object << self.get_declaration(code_generator, final=True, language=language) +"\n"
return code_object
class FunctionGroup(object):
""" group of multiple functions """
def __init__(self, core_function_list=None, sub_function_list=None):
self.core_function_list = [] if not(core_function_list) else core_function_list
self.sub_function_list = [] if not(sub_function_list) else sub_function_list
def add_sub_function(self, sub_function):
self.sub_function_list.append(sub_function)
def add_core_function(self, sub_function):
self.core_function_list.append(sub_function)
def apply_to_core_functions(self, routine):
for fct in self.core_function_list:
routine(self, fct)
def apply_to_sub_functions(self, routine):
for fct in self.sub_function_list:
routine(self, fct)
def apply_to_all_functions(self, routine):
self.apply_to_sub_functions(routine)
self.apply_to_core_functions(routine)
return self
def merge_with_group(self, subgroup, demote_sub_core=True):
""" Merge two FunctionGroup-s together (if demote_sub_core
is set, the argument core and sub function list are merged
into self sub function list, it unset core list are merged
together and sub list are merged together """
for sub_fct in subgroup.sub_function_list:
self.add_sub_function(sub_fct)
for sub_fct in subgroup.core_function_list:
if demote_sub_core:
self.add_sub_function(sub_fct)
else:
self.add_core_function(sub_fct)
return self
def get_code_function_by_name(self, function_name):
for fct in self.core_function_list + self.sub_function_list:
if fct.name == function_name:
return fct
return None
| 41.640909 | 145 | 0.709966 | true | true | |
f7316a0076d2b4bf5804f2d9d837fa670e1f56a2 | 5,487 | py | Python | classic_tetris_project_django/settings.py | professor-l/classic-tetris-project | d171ab40c06b87ee945dce058babf2ed23dd3b88 | [
"MIT"
] | 17 | 2019-11-23T12:56:06.000Z | 2022-02-05T21:48:00.000Z | classic_tetris_project_django/settings.py | professor-l/classic-tetris-project | d171ab40c06b87ee945dce058babf2ed23dd3b88 | [
"MIT"
] | 43 | 2019-10-03T20:16:11.000Z | 2022-03-12T00:24:52.000Z | classic_tetris_project_django/settings.py | professor-l/classic-tetris-project | d171ab40c06b87ee945dce058babf2ed23dd3b88 | [
"MIT"
] | 17 | 2020-02-09T01:55:01.000Z | 2021-11-12T21:16:50.000Z | """
Django settings for classic_tetris_project_django project.
Generated by 'django-admin startproject' using Django 2.2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import environ
import django
import os
ENV = environ.Env(
SECRET_KEY=(str, 'd0$j=wune9kn70srt1lt!g3a8fim7ug#j@x8+zmy0gi_mv7&dk'),
DEBUG=(bool, True),
DATABASE_URL=(str, 'sqlite:///db.sqlite3'),
CACHE_URL=(str, 'rediscache://'),
BASE_URL=(str, 'http://dev.monthlytetris.info:8000'),
DISCORD_USER_ID_WHITELIST=(list, []),
DISCORD_CHANNEL_MESSAGES=(bool, False),
ROLLBAR_ENABLED=(bool, False),
ROLLBAR_TOKEN=(str, ''),
)
environ.Env.read_env('.env')
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BASE_URL = ENV('BASE_URL')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ENV('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = ENV('DEBUG')
ALLOWED_HOSTS = [
'ctm.gg',
'monthlytetris.info',
'monthlytetris.com',
]
if DEBUG:
ALLOWED_HOSTS.append('*')
# Application definition
INSTALLED_APPS = [
'classic_tetris_project.apps.ClassicTetrisProjectConfig',
'dal',
'dal_select2',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.humanize',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'django.contrib.redirects',
'django_extensions',
'django_object_actions',
'markdownx',
'adminsortable2',
'colorfield',
'webpack_loader',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
'rollbar.contrib.django.middleware.RollbarNotifierMiddleware',
]
ROOT_URLCONF = 'classic_tetris_project_django.urls'
LOGIN_URL = '/oauth/login/'
FORM_RENDERER = 'django.forms.renderers.TemplatesSetting'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, "classic_tetris_project", "templates"),
os.path.join(BASE_DIR, "classic_tetris_project", "private", "templates"),
os.path.join(django.__path__[0], "forms", "templates"),
],
'APP_DIRS': True,
'OPTIONS': {
'builtins': [
'classic_tetris_project.private.templatetags',
],
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'classic_tetris_project.private.context_processors.session_processor',
],
},
},
]
WSGI_APPLICATION = 'classic_tetris_project_django.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
**ENV.db(),
"ATOMIC_REQUESTS": True,
}
}
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
}
}
SITE_ID = 1
SHELL_PLUS_PRINT_SQL = True
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Expires after 180 days
SESSION_COOKIE_AGE = 180 * 24 * 60 * 60
MARKDOWNX_MARKDOWN_EXTENSIONS = [
'markdown.extensions.extra',
]
STATIC_URL = '/static/'
STATIC_ROOT = '/var/www/tetris/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'bundles/',
'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'),
}
}
ROLLBAR = {
'access_token': ENV('ROLLBAR_TOKEN'),
'environment': 'development' if DEBUG else 'production',
'root': BASE_DIR,
'enabled': ENV('ROLLBAR_ENABLED'),
}
import rollbar
rollbar.init(**ROLLBAR)
CELERY_BROKER_URL = 'redis://127.0.0.1:6379/1',
| 26.253589 | 91 | 0.67906 |
import environ
import django
import os
ENV = environ.Env(
SECRET_KEY=(str, 'd0$j=wune9kn70srt1lt!g3a8fim7ug#j@x8+zmy0gi_mv7&dk'),
DEBUG=(bool, True),
DATABASE_URL=(str, 'sqlite:///db.sqlite3'),
CACHE_URL=(str, 'rediscache://'),
BASE_URL=(str, 'http://dev.monthlytetris.info:8000'),
DISCORD_USER_ID_WHITELIST=(list, []),
DISCORD_CHANNEL_MESSAGES=(bool, False),
ROLLBAR_ENABLED=(bool, False),
ROLLBAR_TOKEN=(str, ''),
)
environ.Env.read_env('.env')
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BASE_URL = ENV('BASE_URL')
SECRET_KEY = ENV('SECRET_KEY')
DEBUG = ENV('DEBUG')
ALLOWED_HOSTS = [
'ctm.gg',
'monthlytetris.info',
'monthlytetris.com',
]
if DEBUG:
ALLOWED_HOSTS.append('*')
# Application definition
INSTALLED_APPS = [
'classic_tetris_project.apps.ClassicTetrisProjectConfig',
'dal',
'dal_select2',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.humanize',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'django.contrib.redirects',
'django_extensions',
'django_object_actions',
'markdownx',
'adminsortable2',
'colorfield',
'webpack_loader',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
'rollbar.contrib.django.middleware.RollbarNotifierMiddleware',
]
ROOT_URLCONF = 'classic_tetris_project_django.urls'
LOGIN_URL = '/oauth/login/'
FORM_RENDERER = 'django.forms.renderers.TemplatesSetting'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, "classic_tetris_project", "templates"),
os.path.join(BASE_DIR, "classic_tetris_project", "private", "templates"),
os.path.join(django.__path__[0], "forms", "templates"),
],
'APP_DIRS': True,
'OPTIONS': {
'builtins': [
'classic_tetris_project.private.templatetags',
],
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'classic_tetris_project.private.context_processors.session_processor',
],
},
},
]
WSGI_APPLICATION = 'classic_tetris_project_django.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
**ENV.db(),
"ATOMIC_REQUESTS": True,
}
}
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
}
}
SITE_ID = 1
SHELL_PLUS_PRINT_SQL = True
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Expires after 180 days
SESSION_COOKIE_AGE = 180 * 24 * 60 * 60
MARKDOWNX_MARKDOWN_EXTENSIONS = [
'markdown.extensions.extra',
]
STATIC_URL = '/static/'
STATIC_ROOT = '/var/www/tetris/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'bundles/',
'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'),
}
}
ROLLBAR = {
'access_token': ENV('ROLLBAR_TOKEN'),
'environment': 'development' if DEBUG else 'production',
'root': BASE_DIR,
'enabled': ENV('ROLLBAR_ENABLED'),
}
import rollbar
rollbar.init(**ROLLBAR)
CELERY_BROKER_URL = 'redis://127.0.0.1:6379/1',
| true | true |
f7316a594c1c8ddc04649d2c3866818979f193b5 | 12,132 | py | Python | python/modprop/core/modules_core.py | Humhu/modprop | 0cff8240d5e1522f620de8004c22a74491a0c9fb | [
"AFL-3.0"
] | 1 | 2017-11-10T00:54:53.000Z | 2017-11-10T00:54:53.000Z | python/modprop/core/modules_core.py | Humhu/modprop | 0cff8240d5e1522f620de8004c22a74491a0c9fb | [
"AFL-3.0"
] | null | null | null | python/modprop/core/modules_core.py | Humhu/modprop | 0cff8240d5e1522f620de8004c22a74491a0c9fb | [
"AFL-3.0"
] | null | null | null | """This module contains base classes and types for creating new Modules and using module trees.
"""
import abc
from collections import deque
import numpy as np
class ModuleBase(object):
"""The base interface for all modules. Modules must inherit from this interface.
"""
__metaclass__ = abc.ABCMeta
def __init__(self):
self._inputs = []
self._outputs = []
def register_inputs(self, *args):
"""Registers inputs to this module.
Parameters
----------
inputs : Variable number of inputs to register.
"""
for arg in args:
if not isinstance(arg, InputPort):
raise ValueError('All inputs must be InputPort type')
self._inputs.append(arg)
def register_outputs(self, *args):
"""Registers outputs to this module.
Parameters
----------
outputs : Variable number of outputs to register.
"""
for arg in args:
if not isinstance(arg, OutputPort):
raise ValueError('All outputs must be OutputPort type')
self._outputs.append(arg)
def foreprop_ready(self):
"""Returns if the module is ready to forward-propagate.
Default implementation returns true when all inputs are ready and
not all outputs are set.
Returns
-------
ready : Boolean denoting if the module is ready to foreprop
"""
return all(self._inputs) and not all(self._outputs)
@abc.abstractmethod
def foreprop(self):
"""Perform forward-propagation for this module.
Returns
-------
ready : The aggregated return list from all forepropped output ports.
"""
return []
def backprop_ready(self):
"""Returns if the module is ready to backward-propagate.
Typically this is when all outputs have received all backprops.
Default implementation checks to see if all outputs are ready to backprop.
Returns
-------
ready : Boolean denoting if the module is ready to backprop
"""
return all([o.backprop_ready() for o in self._outputs])
@abc.abstractmethod
def backprop(self):
"""Perform backward-propagation for this module.
Returns
-------
ready : The aggregated return list from all backpropped input ports.
"""
return []
def is_invalid(self):
"""Returns if the module is fully invalidated.
Typically this is when all ports are invalidated.
Default implementation checks to see if all ports are invalidated.
Returns
-------
invalid : Boolean denoting if this module is fully invalid
"""
return not any(self._inputs) and not any(self._outputs)
def invalidate(self):
"""Invalidate this modules' inputs and outputs.
Default implementation first checks to see if the module is already invalid.
If it is not, it calls invalidate on all inputs and outputs.
Returns
-------
ready : List of modules to invalidate next.
"""
if self.is_invalid():
return []
ready = []
for i in self._inputs:
ready += i.invalidate()
for o in self._outputs:
ready += o.invalidate()
return ready
# TODO Ways to unregister port connections
class InputPort(object):
"""An input to a module. Ideally instantiated as a member of the module.
Parameters
----------
module : The owning module. Must implement the ModuleBase interface.
"""
def __init__(self, module):
if not isinstance(module, ModuleBase):
raise ValueError('module must implement ModuleBase')
self._module = module
self._value = None
self._source = None
def __nonzero__(self):
"""Override of Python boolean test operator to return if the port has a value.
Returns
-------
ready : Boolean denoting if the port has a valid value.
"""
return self._value is not None
def invalidate(self):
"""Invalidate this input port and propagate to the module and source.
Returns
-------
valid : List of modules to invalidate next.
"""
# If we're already invalidated, there's nothing for us to do here
if not self:
return []
self._value = None
valid = []
# If the owning module is not invalid, return it
if not self._module.is_invalid():
valid.append(self._module)
# Propagate invalidation to source
if self._source is not None:
valid += self._source.invalidate()
return valid
def foreprop(self, v):
"""Set this port's value and forward-propagate.
Typically only called by OutputPorts.
Parameters
----------
v : The value to set the port to.
Returns
-------
ready : List of modules to foreprop next.
"""
self._value = v
if self._module.foreprop_ready():
return [self._module]
else:
return []
def backprop(self, do_dx):
"""Give this port a backpropagation accumulator to pass on.
Typically called by the owning module.
Parameters
----------
do_dx : Numpy 2D array Jacobian[i,j] of tree outputs[i] w.r.t. this input port elements[j].
Returns
-------
ready : List of modules to backprop next.
"""
if self._source is not None:
return self._source.backprop(do_dx)
else:
return []
def register_source(self, src):
"""Register an OutputPort source for this port.
Parameters
----------
src : OutputPort to take as the source of this port.
"""
if not isinstance(src, OutputPort):
raise ValueError('src must be OutputPort')
self._source = src
@property
def value(self):
return self._value
class OutputPort(object):
"""An output from a module. Typically instantiated as a module member.
Parameters
----------
module : The owning module. Must implement the ModuleBase interface.
"""
def __init__(self, module):
if not isinstance(module, ModuleBase):
raise ValueError('module must implement ModuleBase')
self._module = module
self._backprop_acc = None
self._num_backs = 0
self._value = None
self._consumers = []
def __nonzero__(self):
"""Override of Python boolean test operator to return whether this port has a value.
"""
return self.value is not None
@property
def num_consumers(self):
"""Return the number of registered consumers.
"""
return len(self._consumers)
@property
def value(self):
return self._value
def register_consumer(self, con):
"""Register an InputPort consumer to this port.
"""
if not isinstance(con, InputPort):
raise ValueError('Consumer must be InputPort')
self._consumers.append(con)
def invalidate(self):
"""Invalidate this port and propagate.
Returns
-------
valid : List of modules to invalidate next
"""
# If we're already invalid, there's nothing to do
if not self:
return []
self._backprop_acc = None
self._num_backs = 0
self._value = None
valid = []
if not self._module.is_invalid():
valid.append(self._module)
for con in self._consumers:
valid += con.invalidate()
return valid
def foreprop(self, v):
"""Perform forward-propagation through this output.
Typically called by the owning module.
Parameters
----------
v : The value to set this port to.
Returns
-------
ready : List of modules to foreprop next.
"""
self._value = v
ready = []
for con in self._consumers:
ready += con.foreprop(self._value)
return ready
def backprop(self, do_dx):
"""Perform backward-propagation through this output.
Typically called by a connected InputPort.
Only propagates when data from all registered consumers is received.
Parameters
----------
do_dx : Numpy 2D array Jacobian[i,j] of tree outputs[i] w.r.t. this input port elements[j]
Returns
-------
ready : List of modules to backprop next
"""
if do_dx is None:
raise RuntimeError('OutputPort received None backprop value.')
do_dx.tick_descent()
if self._backprop_acc is None:
self._backprop_acc = do_dx
else:
self._backprop_acc += do_dx
self._num_backs += 1
# Check for backprop errors
if self._num_backs > len(self._consumers):
errstr = 'Received %d backprops for %d consumers!' % (self._num_backs, len(self._consumers))
raise RuntimeError(errstr)
# If we've heard from every consumer and our module is ready
if self.backprop_ready() and self._module.backprop_ready():
return [self._module]
else:
return []
def backprop_ready(self):
"""Returns if this port has heard from all its consumers.
"""
return self._num_backs == self.num_consumers
def chain_backprop(self, dy_dx=None):
"""Returns a copy of this port's backprop accumulator right-multiplied by the
given gradient. If the port has not received a backprop, returns None.
"""
if self._backprop_acc is None:
return None
#raise RuntimeError('Cannot chain backprop! Port has not received do_dx.')
out_acc = self._backprop_acc.copy()
if dy_dx is not None:
out_acc = out_acc * dy_dx
return out_acc
@property
def backprop_accumulator(self):
"""Returns the port's backprop accumulator.
"""
return self._backprop_acc
@property
def backprop_value(self):
if self._backprop_acc is None:
return 0
else:
return self._backprop_acc.retrieve()
def link_ports(in_port, out_port):
"""Join an input and output port together.
Parameters
----------
in_port : InputPort to join
out_port : OutputPort to join
"""
if not isinstance(in_port, InputPort):
raise ValueError('in_port must be an InputPort.')
if not isinstance(out_port, OutputPort):
raise ValueError('out_port must be an OutputPort.')
in_port.register_source(out_port)
out_port.register_consumer(in_port)
# @profile
def iterative_operation(init_module, op):
# TODO Allow taking list of initial modules
"""Iteratively perform an operation on a module tree.
This function should be used instead of recursive calls, which do not scale
to deep trees very well.
Parameters
----------
init_module : Module to begin iteration on
op : Function that takes a module and returns a list of modules to operate on next
"""
to_prop = deque()
to_prop.append(init_module)
while len(to_prop) > 0:
current = to_prop.popleft()
ready_children = op(current)
for c in ready_children:
to_prop.append(c)
def iterative_foreprop(init_module):
"""Iterative forward-pass propagation on a module tree.
"""
op = lambda x: x.foreprop()
iterative_operation(init_module, op)
def iterative_backprop(init_module):
"""Iterative backward-pass propagation on a module tree.
"""
op = lambda x: x.backprop()
iterative_operation(init_module, op)
def iterative_invalidate(init_module):
"""Iterative invalidation on a module tree.
"""
op = lambda x: x.invalidate()
iterative_operation(init_module, op)
| 28.817102 | 104 | 0.60089 | import abc
from collections import deque
import numpy as np
class ModuleBase(object):
__metaclass__ = abc.ABCMeta
def __init__(self):
self._inputs = []
self._outputs = []
def register_inputs(self, *args):
for arg in args:
if not isinstance(arg, InputPort):
raise ValueError('All inputs must be InputPort type')
self._inputs.append(arg)
def register_outputs(self, *args):
for arg in args:
if not isinstance(arg, OutputPort):
raise ValueError('All outputs must be OutputPort type')
self._outputs.append(arg)
def foreprop_ready(self):
return all(self._inputs) and not all(self._outputs)
@abc.abstractmethod
def foreprop(self):
return []
def backprop_ready(self):
return all([o.backprop_ready() for o in self._outputs])
@abc.abstractmethod
def backprop(self):
return []
def is_invalid(self):
return not any(self._inputs) and not any(self._outputs)
def invalidate(self):
if self.is_invalid():
return []
ready = []
for i in self._inputs:
ready += i.invalidate()
for o in self._outputs:
ready += o.invalidate()
return ready
class InputPort(object):
def __init__(self, module):
if not isinstance(module, ModuleBase):
raise ValueError('module must implement ModuleBase')
self._module = module
self._value = None
self._source = None
def __nonzero__(self):
return self._value is not None
def invalidate(self):
if not self:
return []
self._value = None
valid = []
if not self._module.is_invalid():
valid.append(self._module)
if self._source is not None:
valid += self._source.invalidate()
return valid
def foreprop(self, v):
self._value = v
if self._module.foreprop_ready():
return [self._module]
else:
return []
def backprop(self, do_dx):
if self._source is not None:
return self._source.backprop(do_dx)
else:
return []
def register_source(self, src):
if not isinstance(src, OutputPort):
raise ValueError('src must be OutputPort')
self._source = src
@property
def value(self):
return self._value
class OutputPort(object):
def __init__(self, module):
if not isinstance(module, ModuleBase):
raise ValueError('module must implement ModuleBase')
self._module = module
self._backprop_acc = None
self._num_backs = 0
self._value = None
self._consumers = []
def __nonzero__(self):
return self.value is not None
@property
def num_consumers(self):
return len(self._consumers)
@property
def value(self):
return self._value
def register_consumer(self, con):
if not isinstance(con, InputPort):
raise ValueError('Consumer must be InputPort')
self._consumers.append(con)
def invalidate(self):
if not self:
return []
self._backprop_acc = None
self._num_backs = 0
self._value = None
valid = []
if not self._module.is_invalid():
valid.append(self._module)
for con in self._consumers:
valid += con.invalidate()
return valid
def foreprop(self, v):
self._value = v
ready = []
for con in self._consumers:
ready += con.foreprop(self._value)
return ready
def backprop(self, do_dx):
if do_dx is None:
raise RuntimeError('OutputPort received None backprop value.')
do_dx.tick_descent()
if self._backprop_acc is None:
self._backprop_acc = do_dx
else:
self._backprop_acc += do_dx
self._num_backs += 1
if self._num_backs > len(self._consumers):
errstr = 'Received %d backprops for %d consumers!' % (self._num_backs, len(self._consumers))
raise RuntimeError(errstr)
if self.backprop_ready() and self._module.backprop_ready():
return [self._module]
else:
return []
def backprop_ready(self):
return self._num_backs == self.num_consumers
def chain_backprop(self, dy_dx=None):
if self._backprop_acc is None:
return None
#raise RuntimeError('Cannot chain backprop! Port has not received do_dx.')
out_acc = self._backprop_acc.copy()
if dy_dx is not None:
out_acc = out_acc * dy_dx
return out_acc
@property
def backprop_accumulator(self):
return self._backprop_acc
@property
def backprop_value(self):
if self._backprop_acc is None:
return 0
else:
return self._backprop_acc.retrieve()
def link_ports(in_port, out_port):
if not isinstance(in_port, InputPort):
raise ValueError('in_port must be an InputPort.')
if not isinstance(out_port, OutputPort):
raise ValueError('out_port must be an OutputPort.')
in_port.register_source(out_port)
out_port.register_consumer(in_port)
# @profile
def iterative_operation(init_module, op):
# TODO Allow taking list of initial modules
to_prop = deque()
to_prop.append(init_module)
while len(to_prop) > 0:
current = to_prop.popleft()
ready_children = op(current)
for c in ready_children:
to_prop.append(c)
def iterative_foreprop(init_module):
op = lambda x: x.foreprop()
iterative_operation(init_module, op)
def iterative_backprop(init_module):
op = lambda x: x.backprop()
iterative_operation(init_module, op)
def iterative_invalidate(init_module):
op = lambda x: x.invalidate()
iterative_operation(init_module, op)
| true | true |
f7316ace9299b1066e1b315ba165fdf6fd372280 | 1,042 | py | Python | recipes/mojo.py | azunite/chrome_build | fed8b4e9c12aa9a0e33680e223b6327a65b2c268 | [
"BSD-3-Clause"
] | 10 | 2016-06-15T06:27:53.000Z | 2019-08-29T05:44:28.000Z | recipes/mojo.py | azunite/chrome_build | fed8b4e9c12aa9a0e33680e223b6327a65b2c268 | [
"BSD-3-Clause"
] | null | null | null | recipes/mojo.py | azunite/chrome_build | fed8b4e9c12aa9a0e33680e223b6327a65b2c268 | [
"BSD-3-Clause"
] | 19 | 2016-03-25T08:12:35.000Z | 2022-02-14T06:05:26.000Z | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import sys
import recipe_util # pylint: disable=F0401
# This class doesn't need an __init__ method, so we disable the warning
# pylint: disable=W0232
class Mojo(recipe_util.Recipe):
"""Basic Recipe class for Mojo."""
@staticmethod
def fetch_spec(props):
url = 'https://github.com/domokit/mojo.git'
solution = {
'name' :'src',
'url' : url,
'deps_file': 'DEPS',
'managed' : False,
'custom_deps': {},
'safesync_url': '',
}
spec = {
'solutions': [solution],
}
if props.get('target_os'):
spec['target_os'] = props['target_os'].split(',')
return {
'type': 'gclient_git',
'gclient_git_spec': spec,
}
@staticmethod
def expected_root(_props):
return 'src'
def main(argv=None):
return Mojo().handle_args(argv)
if __name__ == '__main__':
sys.exit(main(sys.argv))
| 22.170213 | 72 | 0.627639 |
import sys
import recipe_util
# pylint: disable=W0232
class Mojo(recipe_util.Recipe):
@staticmethod
def fetch_spec(props):
url = 'https://github.com/domokit/mojo.git'
solution = {
'name' :'src',
'url' : url,
'deps_file': 'DEPS',
'managed' : False,
'custom_deps': {},
'safesync_url': '',
}
spec = {
'solutions': [solution],
}
if props.get('target_os'):
spec['target_os'] = props['target_os'].split(',')
return {
'type': 'gclient_git',
'gclient_git_spec': spec,
}
@staticmethod
def expected_root(_props):
return 'src'
def main(argv=None):
return Mojo().handle_args(argv)
if __name__ == '__main__':
sys.exit(main(sys.argv))
| true | true |
f7316bd69a4ba467eed53268684ee4aaaa448a25 | 2,259 | py | Python | mmaction/models/builder.py | jiaoml1996/mmaction2 | cff4a9e196dfc7b7b0e842ab44f2a7f2573a2c7c | [
"Apache-2.0"
] | 1 | 2021-01-07T05:03:16.000Z | 2021-01-07T05:03:16.000Z | mmaction/models/builder.py | xumingze0308/mmaction2 | 777546f27f8f5a3c83e10d966e2149be2fc9fa31 | [
"Apache-2.0"
] | null | null | null | mmaction/models/builder.py | xumingze0308/mmaction2 | 777546f27f8f5a3c83e10d966e2149be2fc9fa31 | [
"Apache-2.0"
] | null | null | null | import warnings
import torch.nn as nn
from mmcv.utils import Registry, build_from_cfg
from .registry import BACKBONES, HEADS, LOCALIZERS, LOSSES, NECKS, RECOGNIZERS
try:
from mmdet.models.builder import DETECTORS, build_detector
except (ImportError, ModuleNotFoundError):
warnings.warn('Please install mmdet to use DETECTORS, build_detector')
# Define an empty registry and building func, so that can import
DETECTORS = Registry('detector')
def build_detector(cfg, train_cfg, test_cfg):
pass
def build(cfg, registry, default_args=None):
"""Build a module.
Args:
cfg (dict, list[dict]): The config of modules, it is either a dict
or a list of configs.
registry (:obj:`Registry`): A registry the module belongs to.
default_args (dict, optional): Default arguments to build the module.
Defaults to None.
Returns:
nn.Module: A built nn module.
"""
if isinstance(cfg, list):
modules = [
build_from_cfg(cfg_, registry, default_args) for cfg_ in cfg
]
return nn.Sequential(*modules)
return build_from_cfg(cfg, registry, default_args)
def build_backbone(cfg):
"""Build backbone."""
return build(cfg, BACKBONES)
def build_head(cfg):
"""Build head."""
return build(cfg, HEADS)
def build_recognizer(cfg, train_cfg=None, test_cfg=None):
"""Build recognizer."""
return build(cfg, RECOGNIZERS,
dict(train_cfg=train_cfg, test_cfg=test_cfg))
def build_loss(cfg):
"""Build loss."""
return build(cfg, LOSSES)
def build_localizer(cfg):
"""Build localizer."""
return build(cfg, LOCALIZERS)
def build_model(cfg, train_cfg=None, test_cfg=None):
"""Build model."""
args = cfg.copy()
obj_type = args.pop('type')
if obj_type in LOCALIZERS:
return build_localizer(cfg)
if obj_type in RECOGNIZERS:
return build_recognizer(cfg, train_cfg, test_cfg)
if obj_type in DETECTORS:
return build_detector(cfg, train_cfg, test_cfg)
raise ValueError(f'{obj_type} is not registered in '
'LOCALIZERS, RECOGNIZERS or DETECTORS')
def build_neck(cfg):
"""Build neck."""
return build(cfg, NECKS)
| 26.267442 | 78 | 0.666224 | import warnings
import torch.nn as nn
from mmcv.utils import Registry, build_from_cfg
from .registry import BACKBONES, HEADS, LOCALIZERS, LOSSES, NECKS, RECOGNIZERS
try:
from mmdet.models.builder import DETECTORS, build_detector
except (ImportError, ModuleNotFoundError):
warnings.warn('Please install mmdet to use DETECTORS, build_detector')
DETECTORS = Registry('detector')
def build_detector(cfg, train_cfg, test_cfg):
pass
def build(cfg, registry, default_args=None):
if isinstance(cfg, list):
modules = [
build_from_cfg(cfg_, registry, default_args) for cfg_ in cfg
]
return nn.Sequential(*modules)
return build_from_cfg(cfg, registry, default_args)
def build_backbone(cfg):
return build(cfg, BACKBONES)
def build_head(cfg):
return build(cfg, HEADS)
def build_recognizer(cfg, train_cfg=None, test_cfg=None):
return build(cfg, RECOGNIZERS,
dict(train_cfg=train_cfg, test_cfg=test_cfg))
def build_loss(cfg):
return build(cfg, LOSSES)
def build_localizer(cfg):
return build(cfg, LOCALIZERS)
def build_model(cfg, train_cfg=None, test_cfg=None):
args = cfg.copy()
obj_type = args.pop('type')
if obj_type in LOCALIZERS:
return build_localizer(cfg)
if obj_type in RECOGNIZERS:
return build_recognizer(cfg, train_cfg, test_cfg)
if obj_type in DETECTORS:
return build_detector(cfg, train_cfg, test_cfg)
raise ValueError(f'{obj_type} is not registered in '
'LOCALIZERS, RECOGNIZERS or DETECTORS')
def build_neck(cfg):
return build(cfg, NECKS)
| true | true |
f7316c5bc4aa4105269362035d277cc55ecd7b85 | 3,975 | py | Python | MyResumes/MyResumes/MyResumes/settings.py | githubError/MessyRepository | 2380ed13c167c5c6174f0e71c8dfc634318cda4f | [
"MIT"
] | 2 | 2018-03-12T08:01:47.000Z | 2018-03-12T08:06:14.000Z | MyResumes/MyResumes/MyResumes/settings.py | githubError/MessyRepository | 2380ed13c167c5c6174f0e71c8dfc634318cda4f | [
"MIT"
] | null | null | null | MyResumes/MyResumes/MyResumes/settings.py | githubError/MessyRepository | 2380ed13c167c5c6174f0e71c8dfc634318cda4f | [
"MIT"
] | 1 | 2019-11-06T15:58:05.000Z | 2019-11-06T15:58:05.000Z | """
Django settings for MyResumes project.
Generated by 'django-admin startproject' using Django 2.0.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'lqpjra6xa@pm96&$y1xri(uau#vk2&)7b1hi6$k&v=zvne*o)%'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'Resumes.apps.ResumesConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
CORS_ORIGIN_WHITELIST = (
'127.0.0.1:8000',
)
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'MyResumes.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'MyResumes.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME' : 'myresumes',
'USER' : 'root',
'PASSWORD' : 'root',
'HOST' : '140.143.249.103',
'PORT' : '5432',
}
}
# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# email
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.163.com'
EMAIL_PORT = 465
EMAIL_HOST_USER = 'githuberror@163.com'
EMAIL_HOST_PASSWORD = 'cpf9401'
DEFAULT_CHARSET = 'utf-8'
EMAIL_USE_TLS = False
EMAIL_USE_SSL = True
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static')
STATICFILES_DIRS = (
('css',os.path.join(STATIC_ROOT,'css').replace('\\','/') ),
('js',os.path.join(STATIC_ROOT,'js').replace('\\','/') ),
('images',os.path.join(STATIC_ROOT,'images').replace('\\','/') ),
('upload',os.path.join(STATIC_ROOT,'upload').replace('\\','/') ),
) | 25 | 91 | 0.683522 |
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'lqpjra6xa@pm96&$y1xri(uau#vk2&)7b1hi6$k&v=zvne*o)%'
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'Resumes.apps.ResumesConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
CORS_ORIGIN_WHITELIST = (
'127.0.0.1:8000',
)
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'MyResumes.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'MyResumes.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME' : 'myresumes',
'USER' : 'root',
'PASSWORD' : 'root',
'HOST' : '140.143.249.103',
'PORT' : '5432',
}
}
# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# email
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.163.com'
EMAIL_PORT = 465
EMAIL_HOST_USER = 'githuberror@163.com'
EMAIL_HOST_PASSWORD = 'cpf9401'
DEFAULT_CHARSET = 'utf-8'
EMAIL_USE_TLS = False
EMAIL_USE_SSL = True
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static')
STATICFILES_DIRS = (
('css',os.path.join(STATIC_ROOT,'css').replace('\\','/') ),
('js',os.path.join(STATIC_ROOT,'js').replace('\\','/') ),
('images',os.path.join(STATIC_ROOT,'images').replace('\\','/') ),
('upload',os.path.join(STATIC_ROOT,'upload').replace('\\','/') ),
) | true | true |
f7316c7ddaccd1a7c79dfb5e3ac9e15377fd1b26 | 4,228 | py | Python | test_tile/test_tile_magma.py | zbelateche/ee272_cgra | 4cf2e3cf4a4bdf585d87a9209a5bf252666bc6a2 | [
"BSD-3-Clause"
] | 1 | 2020-07-23T02:57:12.000Z | 2020-07-23T02:57:12.000Z | test_tile/test_tile_magma.py | zbelateche/ee272_cgra | 4cf2e3cf4a4bdf585d87a9209a5bf252666bc6a2 | [
"BSD-3-Clause"
] | null | null | null | test_tile/test_tile_magma.py | zbelateche/ee272_cgra | 4cf2e3cf4a4bdf585d87a9209a5bf252666bc6a2 | [
"BSD-3-Clause"
] | 1 | 2021-04-27T23:13:43.000Z | 2021-04-27T23:13:43.000Z | from common.dummy_core_magma import DummyCore
from bit_vector import BitVector
from tile.tile_magma import Tile
from common.testers import BasicTester
import tempfile
from fault.random import random_bv
def check_all_config(tester,
tile_circ,
tile,
data_written,
inputs_applied):
for addr in data_written:
tester.config_read(addr)
expected_data = data_written[addr]
tester.expect(tile_circ.read_config_data, expected_data)
def test_tile():
core = DummyCore()
tile = Tile(core)
tile_circ = tile.circuit()
# No functional model for tile yet, so we have to use the
# standard fault tester for now
tester = BasicTester(tile_circ, tile_circ.clk, tile_circ.reset)
# assign the tile a random ID for configuration
tile_id = random_bv(16)
tester.poke(tile_circ.tile_id, tile_id)
tester.reset()
# Connect random vals to all tile inputs
inputs_applied = {}
for side_in in (tile_circ.north.I, tile_circ.south.I,
tile_circ.east.I, tile_circ.west.I):
for i in range(len(side_in.layer1)):
port = side_in.layer1[i]
rand_input = random_bv(1)
inputs_applied[port] = rand_input
tester.poke(port, rand_input)
for j in range(len(side_in.layer16)):
port = side_in.layer16[j]
rand_input = random_bv(16)
inputs_applied[port] = rand_input
tester.poke(port, rand_input)
# Write to all configuration registers in the tile
# This test should be applicapable to any tile, regardless
# of the core it's using
data_written = {}
for i, feat in enumerate(tile.features()):
feat_addr = BitVector(i, 8)
for reg in feat.registers.values():
reg_addr = BitVector(reg.addr, 8)
upper_config_addr = BitVector.concat(reg_addr, feat_addr)
config_addr = BitVector.concat(upper_config_addr, tile_id)
# Ensure the register is wide enough to contain the random value
rand_data = random_bv(reg.width)
# Further restrict random config data values based on feature
# Only 0-3 valid for SB config_data
if (feat == tile.sb):
if((reg_addr % 2) == 0):
rand_data = rand_data % 4
# Only 0-1 valid for SB regs
else:
rand_data = rand_data % 2
# Only 0-9 valid for CB config_data
elif (feat in tile.cbs):
rand_data = rand_data % 10
# Make sure we pass 32 bits of config data to configure
config_data = BitVector(rand_data, 32)
tester.configure(config_addr, config_data)
# Keep track of data written so we know what to expect to read back
data_written[config_addr] = config_data
# Now, read back all the configuration we just wrote
for addr in data_written:
tester.config_read(addr)
expected_data = data_written[addr]
tester.expect(tile_circ.read_config_data, expected_data)
feat_addr = addr[16:24]
reg_addr = addr[24:32]
check_all_config(tester,
tile_circ,
tile,
data_written,
inputs_applied)
# Try writing to tile with wrong tile id
for config_addr in data_written:
new_tile_id = config_addr[0:16] + 1
upper_config_addr = config_addr[16:32]
new_config_addr = BitVector.concat(upper_config_addr, new_tile_id)
random_data = random_bv(32)
tester.configure(new_config_addr, random_data)
# Read all the config back again to make sure nothing changed
check_all_config(tester,
tile_circ,
tile,
data_written,
inputs_applied)
with tempfile.TemporaryDirectory() as tempdir:
tester.compile_and_run(target="verilator",
magma_output="coreir-verilog",
directory=tempdir,
flags=["-Wno-fatal"])
| 38.436364 | 79 | 0.602176 | from common.dummy_core_magma import DummyCore
from bit_vector import BitVector
from tile.tile_magma import Tile
from common.testers import BasicTester
import tempfile
from fault.random import random_bv
def check_all_config(tester,
tile_circ,
tile,
data_written,
inputs_applied):
for addr in data_written:
tester.config_read(addr)
expected_data = data_written[addr]
tester.expect(tile_circ.read_config_data, expected_data)
def test_tile():
core = DummyCore()
tile = Tile(core)
tile_circ = tile.circuit()
tester = BasicTester(tile_circ, tile_circ.clk, tile_circ.reset)
tile_id = random_bv(16)
tester.poke(tile_circ.tile_id, tile_id)
tester.reset()
inputs_applied = {}
for side_in in (tile_circ.north.I, tile_circ.south.I,
tile_circ.east.I, tile_circ.west.I):
for i in range(len(side_in.layer1)):
port = side_in.layer1[i]
rand_input = random_bv(1)
inputs_applied[port] = rand_input
tester.poke(port, rand_input)
for j in range(len(side_in.layer16)):
port = side_in.layer16[j]
rand_input = random_bv(16)
inputs_applied[port] = rand_input
tester.poke(port, rand_input)
data_written = {}
for i, feat in enumerate(tile.features()):
feat_addr = BitVector(i, 8)
for reg in feat.registers.values():
reg_addr = BitVector(reg.addr, 8)
upper_config_addr = BitVector.concat(reg_addr, feat_addr)
config_addr = BitVector.concat(upper_config_addr, tile_id)
# Ensure the register is wide enough to contain the random value
rand_data = random_bv(reg.width)
# Further restrict random config data values based on feature
# Only 0-3 valid for SB config_data
if (feat == tile.sb):
if((reg_addr % 2) == 0):
rand_data = rand_data % 4
# Only 0-1 valid for SB regs
else:
rand_data = rand_data % 2
# Only 0-9 valid for CB config_data
elif (feat in tile.cbs):
rand_data = rand_data % 10
# Make sure we pass 32 bits of config data to configure
config_data = BitVector(rand_data, 32)
tester.configure(config_addr, config_data)
# Keep track of data written so we know what to expect to read back
data_written[config_addr] = config_data
# Now, read back all the configuration we just wrote
for addr in data_written:
tester.config_read(addr)
expected_data = data_written[addr]
tester.expect(tile_circ.read_config_data, expected_data)
feat_addr = addr[16:24]
reg_addr = addr[24:32]
check_all_config(tester,
tile_circ,
tile,
data_written,
inputs_applied)
# Try writing to tile with wrong tile id
for config_addr in data_written:
new_tile_id = config_addr[0:16] + 1
upper_config_addr = config_addr[16:32]
new_config_addr = BitVector.concat(upper_config_addr, new_tile_id)
random_data = random_bv(32)
tester.configure(new_config_addr, random_data)
# Read all the config back again to make sure nothing changed
check_all_config(tester,
tile_circ,
tile,
data_written,
inputs_applied)
with tempfile.TemporaryDirectory() as tempdir:
tester.compile_and_run(target="verilator",
magma_output="coreir-verilog",
directory=tempdir,
flags=["-Wno-fatal"])
| true | true |
f7316cf7b3b3e6fbabab8a174cf2ecb75444019b | 4,820 | py | Python | docs/conf.py | aladinoster/prjits_01_v2i | b6b3f96899d56c583c87098ea53ef008a8cb4365 | [
"MIT"
] | null | null | null | docs/conf.py | aladinoster/prjits_01_v2i | b6b3f96899d56c583c87098ea53ef008a8cb4365 | [
"MIT"
] | null | null | null | docs/conf.py | aladinoster/prjits_01_v2i | b6b3f96899d56c583c87098ea53ef008a8cb4365 | [
"MIT"
] | 1 | 2020-10-20T09:37:48.000Z | 2020-10-20T09:37:48.000Z | #!/usr/bin/env python
#
# connectv2x documentation build configuration file, created by
# sphinx-quickstart on Fri Jun 9 13:47:02 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another
# directory, add these directories to sys.path here. If the directory is
# relative to the documentation root, use os.path.abspath to make it
# absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
import connectv2x
# -- General configuration ---------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'connectv2x'
copyright = "2019, Andres Ladino"
author = "Andres Ladino"
# The version info for the project you're documenting, acts as replacement
# for |version| and |release|, also used in various other places throughout
# the built documents.
#
# The short X.Y version.
version = connectv2x.__version__
# The full version, including alpha/beta/rc tags.
release = connectv2x.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output -------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a
# theme further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# -- Options for HTMLHelp output ---------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'connectv2xdoc'
# -- Options for LaTeX output ------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass
# [howto, manual, or own class]).
latex_documents = [
(master_doc, 'connectv2x.tex',
'connectv2x Documentation',
'Andres Ladino', 'manual'),
]
# -- Options for manual page output ------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'connectv2x',
'connectv2x Documentation',
[author], 1)
]
# -- Options for Texinfo output ----------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'connectv2x',
'connectv2x Documentation',
author,
'connectv2x',
'One line description of project.',
'Miscellaneous'),
]
| 29.570552 | 77 | 0.686722 |
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
import connectv2x
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = 'connectv2x'
copyright = "2019, Andres Ladino"
author = "Andres Ladino"
# for |version| and |release|, also used in various other places throughout
# the built documents.
#
# The short X.Y version.
version = connectv2x.__version__
# The full version, including alpha/beta/rc tags.
release = connectv2x.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output -------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a
# theme further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# -- Options for HTMLHelp output ---------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'connectv2xdoc'
# -- Options for LaTeX output ------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass
# [howto, manual, or own class]).
latex_documents = [
(master_doc, 'connectv2x.tex',
'connectv2x Documentation',
'Andres Ladino', 'manual'),
]
# -- Options for manual page output ------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'connectv2x',
'connectv2x Documentation',
[author], 1)
]
# -- Options for Texinfo output ----------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'connectv2x',
'connectv2x Documentation',
author,
'connectv2x',
'One line description of project.',
'Miscellaneous'),
]
| true | true |
f7316dfaeb40184095a7f7a53a6f4baaf2fb85dd | 4,081 | py | Python | vcx/wrappers/python3/tests/test_wallet.py | absltkaos/indy-sdk | bc14c5b514dc1c76ce62dd7f6bf804120bf69f5e | [
"Apache-2.0"
] | 5 | 2018-04-09T12:26:28.000Z | 2019-06-12T01:45:30.000Z | vcx/wrappers/python3/tests/test_wallet.py | absltkaos/indy-sdk | bc14c5b514dc1c76ce62dd7f6bf804120bf69f5e | [
"Apache-2.0"
] | 9 | 2019-01-22T22:31:54.000Z | 2019-04-11T21:45:09.000Z | vcx/wrappers/python3/tests/test_wallet.py | absltkaos/indy-sdk | bc14c5b514dc1c76ce62dd7f6bf804120bf69f5e | [
"Apache-2.0"
] | 19 | 2018-04-25T16:08:43.000Z | 2022-01-11T10:18:38.000Z | import pytest
from vcx.error import VcxError, ErrorCode
from vcx.api.wallet import *
import json
TYPE = "record type"
EMPTY_TYPE = ""
ID = "123"
EMPTY_ID = ""
VALUE = "record value"
VALUE_NEW = "RecordValueNew"
EMPTY_VALUE = ""
TAGS = "{\"tagName1\":\"str1\",\"tagName2\":\"5\",\"tagName3\":\"12\"}"
OPTIONS = json.dumps({"retrieveType": True, "retrieveValue": True, "retrieveTags": True})
TAGS_EMPTY = ""
TAGS_EMPTY_JSON = "{}"
TAGS_MALFORMED_JSON = "{\"e\":}"
QUERY_JSON = {"tagName1": "str1"}
SEARCHED_RECORD = {
"id": "RecordId",
"type": None,
"value": "RecordValue",
"tags": TAGS
}
@pytest.mark.asyncio
@pytest.mark.usefixtures('vcx_init_test_mode')
async def test_get_token_info():
info = await Wallet.get_token_info(0)
assert info
@pytest.mark.asyncio
@pytest.mark.usefixtures('vcx_init_test_mode')
async def test_send_tokens():
receipt = await Wallet.send_tokens(0,1,"address")
assert receipt
@pytest.mark.asyncio
@pytest.mark.usefixtures('vcx_init_test_mode')
async def test_create_payment_address():
address = await Wallet.create_payment_address()
assert address
@pytest.mark.asyncio
@pytest.mark.usefixtures('vcx_init_test_mode')
async def test_create_payment_address_with_seed():
address = await Wallet.create_payment_address("0000000000000000000000WHATEVER00")
assert address
@pytest.mark.asyncio
@pytest.mark.usefixtures('vcx_init_test_mode')
async def test_validate_payment_address():
await Wallet.validate_payment_address('sov:1:1234')
@pytest.mark.asyncio
@pytest.mark.usefixtures('vcx_init_test_mode')
async def test_wallet_storage():
await Wallet.add_record(TYPE, ID, VALUE, TAGS)
await Wallet.update_record_value(TYPE, ID, VALUE_NEW)
await Wallet.update_record_tags(TYPE, ID, TAGS_EMPTY_JSON)
await Wallet.add_record_tags(TYPE, ID, TAGS)
await Wallet.delete_record_tags(TYPE, ID, ['one', 'two'])
await Wallet.delete_record(TYPE, ID)
record = {
"id": ID,
"type": TYPE,
"value": VALUE,
"tags": None,
}
assert (json.loads(await Wallet.get_record(TYPE, ID, OPTIONS)) == record)
@pytest.mark.asyncio
async def test_wallet_search():
search_handle = await Wallet.open_search(TYPE, QUERY_JSON, None)
assert (search_handle == 1)
searched_record = await Wallet.search_next_records(search_handle, 1)
assert (json.loads(searched_record) == SEARCHED_RECORD)
await Wallet.close_search(search_handle)
with pytest.raises(VcxError) as e:
await Wallet.export("/tmp/output.wallet", "backupKey")
@pytest.mark.asyncio
async def test_import_wallet_failures(vcx_init_test_mode, cleanup):
with pytest.raises(VcxError) as e:
await Wallet.import_wallet('Invalid Json')
assert ErrorCode.InvalidJson == e.value.error_code
cleanup(True)
config = {'wallet_name': '', 'wallet_key': '', 'exported_wallet_path': '', 'backup_key': ''}
with pytest.raises(VcxError) as e:
await Wallet.import_wallet(json.dumps(config))
assert ErrorCode.IOError == e.value.error_code
cleanup(True)
config = {'wallet_key': '', 'exported_wallet_path': '', 'backup_key': ''}
with pytest.raises(VcxError) as e:
await Wallet.import_wallet(json.dumps(config))
assert ErrorCode.MissingWalletName == e.value.error_code
cleanup(True)
config = {'wallet_name': '', 'exported_wallet_path': '', 'backup_key': ''}
with pytest.raises(VcxError) as e:
await Wallet.import_wallet(json.dumps(config))
assert ErrorCode.MissingWalletKey == e.value.error_code
cleanup(True)
config = {'wallet_name': '', 'wallet_key': '', 'backup_key': ''}
with pytest.raises(VcxError) as e:
await Wallet.import_wallet(json.dumps(config))
assert ErrorCode.MissingExportedWalletPath == e.value.error_code
cleanup(True)
config = {'wallet_name': '', 'wallet_key': '', 'exported_wallet_path': ''}
with pytest.raises(VcxError) as e:
await Wallet.import_wallet(json.dumps(config))
assert ErrorCode.MissingBackupKey == e.value.error_code
cleanup(True)
| 31.392308 | 96 | 0.708895 | import pytest
from vcx.error import VcxError, ErrorCode
from vcx.api.wallet import *
import json
TYPE = "record type"
EMPTY_TYPE = ""
ID = "123"
EMPTY_ID = ""
VALUE = "record value"
VALUE_NEW = "RecordValueNew"
EMPTY_VALUE = ""
TAGS = "{\"tagName1\":\"str1\",\"tagName2\":\"5\",\"tagName3\":\"12\"}"
OPTIONS = json.dumps({"retrieveType": True, "retrieveValue": True, "retrieveTags": True})
TAGS_EMPTY = ""
TAGS_EMPTY_JSON = "{}"
TAGS_MALFORMED_JSON = "{\"e\":}"
QUERY_JSON = {"tagName1": "str1"}
SEARCHED_RECORD = {
"id": "RecordId",
"type": None,
"value": "RecordValue",
"tags": TAGS
}
@pytest.mark.asyncio
@pytest.mark.usefixtures('vcx_init_test_mode')
async def test_get_token_info():
info = await Wallet.get_token_info(0)
assert info
@pytest.mark.asyncio
@pytest.mark.usefixtures('vcx_init_test_mode')
async def test_send_tokens():
receipt = await Wallet.send_tokens(0,1,"address")
assert receipt
@pytest.mark.asyncio
@pytest.mark.usefixtures('vcx_init_test_mode')
async def test_create_payment_address():
address = await Wallet.create_payment_address()
assert address
@pytest.mark.asyncio
@pytest.mark.usefixtures('vcx_init_test_mode')
async def test_create_payment_address_with_seed():
address = await Wallet.create_payment_address("0000000000000000000000WHATEVER00")
assert address
@pytest.mark.asyncio
@pytest.mark.usefixtures('vcx_init_test_mode')
async def test_validate_payment_address():
await Wallet.validate_payment_address('sov:1:1234')
@pytest.mark.asyncio
@pytest.mark.usefixtures('vcx_init_test_mode')
async def test_wallet_storage():
await Wallet.add_record(TYPE, ID, VALUE, TAGS)
await Wallet.update_record_value(TYPE, ID, VALUE_NEW)
await Wallet.update_record_tags(TYPE, ID, TAGS_EMPTY_JSON)
await Wallet.add_record_tags(TYPE, ID, TAGS)
await Wallet.delete_record_tags(TYPE, ID, ['one', 'two'])
await Wallet.delete_record(TYPE, ID)
record = {
"id": ID,
"type": TYPE,
"value": VALUE,
"tags": None,
}
assert (json.loads(await Wallet.get_record(TYPE, ID, OPTIONS)) == record)
@pytest.mark.asyncio
async def test_wallet_search():
search_handle = await Wallet.open_search(TYPE, QUERY_JSON, None)
assert (search_handle == 1)
searched_record = await Wallet.search_next_records(search_handle, 1)
assert (json.loads(searched_record) == SEARCHED_RECORD)
await Wallet.close_search(search_handle)
with pytest.raises(VcxError) as e:
await Wallet.export("/tmp/output.wallet", "backupKey")
@pytest.mark.asyncio
async def test_import_wallet_failures(vcx_init_test_mode, cleanup):
with pytest.raises(VcxError) as e:
await Wallet.import_wallet('Invalid Json')
assert ErrorCode.InvalidJson == e.value.error_code
cleanup(True)
config = {'wallet_name': '', 'wallet_key': '', 'exported_wallet_path': '', 'backup_key': ''}
with pytest.raises(VcxError) as e:
await Wallet.import_wallet(json.dumps(config))
assert ErrorCode.IOError == e.value.error_code
cleanup(True)
config = {'wallet_key': '', 'exported_wallet_path': '', 'backup_key': ''}
with pytest.raises(VcxError) as e:
await Wallet.import_wallet(json.dumps(config))
assert ErrorCode.MissingWalletName == e.value.error_code
cleanup(True)
config = {'wallet_name': '', 'exported_wallet_path': '', 'backup_key': ''}
with pytest.raises(VcxError) as e:
await Wallet.import_wallet(json.dumps(config))
assert ErrorCode.MissingWalletKey == e.value.error_code
cleanup(True)
config = {'wallet_name': '', 'wallet_key': '', 'backup_key': ''}
with pytest.raises(VcxError) as e:
await Wallet.import_wallet(json.dumps(config))
assert ErrorCode.MissingExportedWalletPath == e.value.error_code
cleanup(True)
config = {'wallet_name': '', 'wallet_key': '', 'exported_wallet_path': ''}
with pytest.raises(VcxError) as e:
await Wallet.import_wallet(json.dumps(config))
assert ErrorCode.MissingBackupKey == e.value.error_code
cleanup(True)
| true | true |
f73170c66a28ee836b140a20bd40414c0d6d7122 | 13,527 | py | Python | micropsi_server/usermanagement.py | joschabach/micropsi2 | 74a2642d20da9da1d64acc5e4c11aeabee192a27 | [
"MIT"
] | 119 | 2015-01-23T11:24:58.000Z | 2022-03-13T08:00:50.000Z | micropsi_server/usermanagement.py | Chediak/micropsi2 | 74a2642d20da9da1d64acc5e4c11aeabee192a27 | [
"MIT"
] | 9 | 2015-02-18T20:44:58.000Z | 2021-09-17T14:38:05.000Z | micropsi_server/usermanagement.py | Chediak/micropsi2 | 74a2642d20da9da1d64acc5e4c11aeabee192a27 | [
"MIT"
] | 34 | 2015-04-01T20:48:49.000Z | 2022-03-13T08:02:00.000Z | """
Very simple user management for the MicroPsi service
The user manager takes care of users, sessions and user roles.
Users without a password set can login with an arbitrary password, so make sure that users do not set empty passwords
if this concerns you.
When new users are created, they are given a role and stored along with their hashed password. Because we do not store
the password itself, it cannot be retrieved if it is lost. Instead, set a new password.
Users, including the admin user, must be logged in to receive a valid session token. The session token is valid until
the user logs off, or until it expires. To prevent expiration, it may be refreshed during each user interaction.
To check the permissions of a given user, you may use get_permissions_for_session_token. In return, the user manager
will return the rights matrix of the associated user, if the user is logged in, or the rights of a guest it the session
token does not correspond to an open session.
At the moment, persistence is achieved with a simple file, into which user and session data is dumped in json format.
Example usage:
>>> um = UserManager()
>>> um.create_user("eliza", "qwerty", "World Creator") # new user "eliza" with password "querty" as "World Creator"
>>> print um.list_users["eliza"]
{'is_active': False, 'role': 'World Creator'}
>>> elizas_token = um.start_session("eliza", "querty") # log in eliza (give this token to her)
>>> print um.list_users["eliza"]
{'is_active': True, 'role': 'World Creator'}
>>> print um.get_permissions(elizas_token)
set(['manage worlds', 'manage nodenets'])
>>> um.set_user_role('eliza', 'Administrator')
>>> print um.get_permissions(elizas_token)
Set(['manage users', 'manage worlds', 'manage nodenets'])
>>> um.end_session(elizas_token) # log off eliza
>>> print um.get_permissions(elizas_token)
{}
"""
__author__ = 'joscha'
__date__ = '11.05.12'
import json
import hashlib
import os
import datetime
import threading
import time
import uuid
import logging
import micropsi_core.tools
from configuration import config as cfg
ADMIN_USER = "admin" # default name of the admin user
DEFAULT_ROLE = "Restricted" # new users can create and edit nodenets, but not create worlds
IDLE_TIME_BEFORE_SESSION_EXPIRES = 360000 # after 100h idle time, expire the user session (but not the calculation)
TIME_INTERVAL_BETWEEN_EXPIRATION_CHECKS = 3600 # check every hour if we should log out users
USER_ROLES = { # sets of strings; each represents a permission.
"Administrator": {"manage users","manage worlds","manage nodenets", "manage server",
"create admin", "create restricted", "create full"},
"Full": {"manage worlds","manage nodenets", "manage server", "create full", "create restricted"},
"Restricted": {"manage nodenets", "create restricted"},
"Guest": {"create restricted"}
}
class UserManager(object):
"""The user manager creates, deletes and authenticates users.
It should be a singleton, because all user managers would use the same resources for maintaining persistence.
Attributes:
users: a dictionary of user_ids to user objects (containing session tokens, access role and hashed passwords)
sessions: a dictionary of active sessions for faster reference
user_file: the handle for the user data file
"""
def __init__(self, userfile_path=None):
"""initialize user management.
If no user data are found, a new resource file is created.
Parameters:
resource_path (optional): a path to store user data permanently.
"""
self.users = None
self.sessions = {}
# set up persistence
if userfile_path is None:
userfile_path = cfg['paths']['usermanager_path']
os.makedirs(os.path.dirname(userfile_path), exist_ok=True)
self.user_file_name = userfile_path # todo: make this work without a file system
try:
with open(self.user_file_name) as file:
self.users = json.load(file)
except ValueError:
logging.getLogger('system').warn("Invalid user data")
except IOError:
logging.getLogger('system').info("No readable userdata file, attempting to create one.")
if not self.users:
self.users = {}
# set up sessions
for name in self.users:
# compatibility for files before multi-session-feature
if "session_token" in self.users[name] and "sessions" not in self.users[name]:
self.users[name]["sessions"] = {
self.users[name]["session_token"]: {"expires": self.users[name]["session_expires"]}
}
for token in self.users[name]["sessions"]:
self.sessions[token] = name
# set up session cleanup
def _session_expiration():
while True:
self.check_for_expired_user_sessions()
time.sleep(TIME_INTERVAL_BETWEEN_EXPIRATION_CHECKS)
session_expiration_daemon = threading.Thread(target=_session_expiration)
session_expiration_daemon.daemon = True
session_expiration_daemon.start()
def __del__(self):
"""shut down user management"""
self.save_users()
def create_user(self, user_id, password="", role = DEFAULT_ROLE, uid = None):
"""create a new user.
Returns False if the creation was not successful.
Arguments:
user_id: a non-empty string which must be unique, used for display and urls
password: an arbitrary string
role: a string corresponding to a user role (such as "Administrator", or "Restricted")
uid: a string that acts as a unique, immutable handle (so we can store resources for this user)
"""
if user_id and user_id not in self.users:
self.users[user_id] = {
"uid": uid or user_id,
"hashed_password": hashlib.md5(password.encode('utf-8')).hexdigest(),
"role": role,
"sessions": {}
}
self.save_users()
return True
else:
return False
def save_users(self):
"""stores the user data to a file"""
with open(self.user_file_name, mode='w+') as file:
json.dump(self.users, file, indent=4)
def list_users(self):
"""returns a dictionary with all users currently known to the user manager for display purposes"""
return dict((name, {
"role": self.users[name]["role"],
"is_active": True if self.users[name]["sessions"] else False})
for name in self.users)
def set_user_id(self, user_id_old, user_id_new):
"""returns the new username if the user has been renamed successfully, the old username if the new one was
already in use, and None if the old username did not exist"""
if user_id_old in self.users:
if user_id_new not in self.users:
self.users[user_id_new] = self.users[user_id_old]
del self.users[user_id_old]
self.save_users()
return user_id_new
else:
return user_id_old
return None
def set_user_role(self, user_id, role):
"""sets the role, and thereby the permissions of a user, returns False if user does not exist"""
if user_id in self.users:
self.users[user_id]["role"] = role
self.save_users()
return True
return False
def set_user_password(self, user_id, password):
"""sets the password of a user, returns False if user does not exist"""
if user_id in self.users:
self.users[user_id]["hashed_password"] = hashlib.md5(password.encode('utf-8')).hexdigest()
self.save_users()
return True
return False
def delete_user(self, user_id):
"""deletes the specified user, returns True if successful"""
if user_id in self.users:
# if the user is still active, kill the session
for token in list(self.users[user_id]["sessions"].keys()):
self.end_session(token)
del self.users[user_id]
self.save_users()
return True
return False
def start_session(self, user_id, password=None, keep_logged_in_forever=True):
"""authenticates the specified user, returns session token if successful, or None if not.
Arguments:
user_id: a string that must be the id of an existing user
password (optional): checked against the stored password
keep_logged_in_forever (optional): if True, the session will not expire unless manually logging off
"""
if password is None or self.test_password(user_id, password):
session_token = str(uuid.UUID(bytes=os.urandom(16)))
self.users[user_id]["sessions"][session_token] = {
"expires": not keep_logged_in_forever
}
self.sessions[session_token] = user_id
if keep_logged_in_forever:
self.save_users()
else:
self.refresh_session(session_token)
return session_token
return None
def switch_user_for_session_token(self, user_id, session_token):
"""Ends the current session associated with the token, starts a new session for the supplied user,
and associates the same token to it. Used for allowing admins to take on the identity of a user, so they
can edit resources with the user credentials.
Returns True if successful, False if not.
Arguments:
user_id: a string that must be the id of an existing user
token: a valid session token
"""
if session_token in self.sessions and user_id in self.users:
current_user = self.sessions[session_token]
if current_user in self.users:
session = self.users[current_user]["sessions"][session_token]
del self.users[current_user]["sessions"][session_token]
self.users[user_id]["sessions"].update({
session_token: session
})
self.sessions[session_token] = user_id
self.refresh_session(session_token)
self.save_users()
return True
return False
def test_password(self, user_id, password):
"""returns True if the user is known and the password matches, False otherwise"""
if user_id in self.users:
if self.users[user_id]["hashed_password"] == hashlib.md5(password.encode('utf-8')).hexdigest():
return True
return False
def end_session(self, session_token):
"""ends the session associated with the given token"""
if session_token in self.sessions:
user_id = self.sessions[session_token]
del self.sessions[session_token]
if user_id in self.users:
del self.users[user_id]["sessions"][session_token]
def end_all_sessions(self):
"""useful during a reset of the runtime, because all open user sessions will persist during shutdown"""
sessions = self.sessions.copy()
for session_token in sessions:
self.end_session(session_token)
def refresh_session(self, session_token):
"""resets the idle time until a currently active session expires to some point in the future"""
if session_token in self.sessions:
user_id = self.sessions[session_token]
if self.users[user_id]["sessions"][session_token]["expires"]:
self.users[user_id]["sessions"][session_token]["expires"] = (datetime.datetime.now() + datetime.timedelta(
seconds=IDLE_TIME_BEFORE_SESSION_EXPIRES)).isoformat()
def check_for_expired_user_sessions(self):
"""removes all user sessions that have been idle for too long"""
change_flag = False
now = datetime.datetime.now().isoformat()
sessions = self.sessions.copy()
for session_token in sessions:
user_id = self.sessions[session_token]
expires = self.users[user_id]["sessions"][session_token]["expires"]
if expires and expires < now:
self.end_session(session_token)
change_flag = True
if change_flag:
self.save_users()
def get_permissions_for_session_token(self, session_token):
"""returns a set of permissions corresponding to the role of the user associated with the session;
if no session with that token exists, the Guest role permissions are returned.
Example usage:
if "create nodenets" in usermanager.get_permissions(my_session): ...
"""
if session_token in self.sessions:
user_id = self.sessions[session_token]
if user_id in self.users:
role = self.users[user_id]["role"]
if role in USER_ROLES:
return USER_ROLES[role]
return USER_ROLES["Guest"]
def get_user_id_for_session_token(self, session_token):
"""returns the id of the user associated with the session token, or 'Guest', if the token is invalid"""
if session_token in self.sessions:
return self.sessions[session_token]
else:
return "Guest"
| 42.537736 | 122 | 0.645524 |
__author__ = 'joscha'
__date__ = '11.05.12'
import json
import hashlib
import os
import datetime
import threading
import time
import uuid
import logging
import micropsi_core.tools
from configuration import config as cfg
ADMIN_USER = "admin"
DEFAULT_ROLE = "Restricted"
IDLE_TIME_BEFORE_SESSION_EXPIRES = 360000
TIME_INTERVAL_BETWEEN_EXPIRATION_CHECKS = 3600
USER_ROLES = {
"Administrator": {"manage users","manage worlds","manage nodenets", "manage server",
"create admin", "create restricted", "create full"},
"Full": {"manage worlds","manage nodenets", "manage server", "create full", "create restricted"},
"Restricted": {"manage nodenets", "create restricted"},
"Guest": {"create restricted"}
}
class UserManager(object):
def __init__(self, userfile_path=None):
self.users = None
self.sessions = {}
if userfile_path is None:
userfile_path = cfg['paths']['usermanager_path']
os.makedirs(os.path.dirname(userfile_path), exist_ok=True)
self.user_file_name = userfile_path
try:
with open(self.user_file_name) as file:
self.users = json.load(file)
except ValueError:
logging.getLogger('system').warn("Invalid user data")
except IOError:
logging.getLogger('system').info("No readable userdata file, attempting to create one.")
if not self.users:
self.users = {}
for name in self.users:
if "session_token" in self.users[name] and "sessions" not in self.users[name]:
self.users[name]["sessions"] = {
self.users[name]["session_token"]: {"expires": self.users[name]["session_expires"]}
}
for token in self.users[name]["sessions"]:
self.sessions[token] = name
def _session_expiration():
while True:
self.check_for_expired_user_sessions()
time.sleep(TIME_INTERVAL_BETWEEN_EXPIRATION_CHECKS)
session_expiration_daemon = threading.Thread(target=_session_expiration)
session_expiration_daemon.daemon = True
session_expiration_daemon.start()
def __del__(self):
self.save_users()
def create_user(self, user_id, password="", role = DEFAULT_ROLE, uid = None):
if user_id and user_id not in self.users:
self.users[user_id] = {
"uid": uid or user_id,
"hashed_password": hashlib.md5(password.encode('utf-8')).hexdigest(),
"role": role,
"sessions": {}
}
self.save_users()
return True
else:
return False
def save_users(self):
with open(self.user_file_name, mode='w+') as file:
json.dump(self.users, file, indent=4)
def list_users(self):
return dict((name, {
"role": self.users[name]["role"],
"is_active": True if self.users[name]["sessions"] else False})
for name in self.users)
def set_user_id(self, user_id_old, user_id_new):
if user_id_old in self.users:
if user_id_new not in self.users:
self.users[user_id_new] = self.users[user_id_old]
del self.users[user_id_old]
self.save_users()
return user_id_new
else:
return user_id_old
return None
def set_user_role(self, user_id, role):
if user_id in self.users:
self.users[user_id]["role"] = role
self.save_users()
return True
return False
def set_user_password(self, user_id, password):
if user_id in self.users:
self.users[user_id]["hashed_password"] = hashlib.md5(password.encode('utf-8')).hexdigest()
self.save_users()
return True
return False
def delete_user(self, user_id):
if user_id in self.users:
for token in list(self.users[user_id]["sessions"].keys()):
self.end_session(token)
del self.users[user_id]
self.save_users()
return True
return False
def start_session(self, user_id, password=None, keep_logged_in_forever=True):
if password is None or self.test_password(user_id, password):
session_token = str(uuid.UUID(bytes=os.urandom(16)))
self.users[user_id]["sessions"][session_token] = {
"expires": not keep_logged_in_forever
}
self.sessions[session_token] = user_id
if keep_logged_in_forever:
self.save_users()
else:
self.refresh_session(session_token)
return session_token
return None
def switch_user_for_session_token(self, user_id, session_token):
if session_token in self.sessions and user_id in self.users:
current_user = self.sessions[session_token]
if current_user in self.users:
session = self.users[current_user]["sessions"][session_token]
del self.users[current_user]["sessions"][session_token]
self.users[user_id]["sessions"].update({
session_token: session
})
self.sessions[session_token] = user_id
self.refresh_session(session_token)
self.save_users()
return True
return False
def test_password(self, user_id, password):
if user_id in self.users:
if self.users[user_id]["hashed_password"] == hashlib.md5(password.encode('utf-8')).hexdigest():
return True
return False
def end_session(self, session_token):
if session_token in self.sessions:
user_id = self.sessions[session_token]
del self.sessions[session_token]
if user_id in self.users:
del self.users[user_id]["sessions"][session_token]
def end_all_sessions(self):
sessions = self.sessions.copy()
for session_token in sessions:
self.end_session(session_token)
def refresh_session(self, session_token):
if session_token in self.sessions:
user_id = self.sessions[session_token]
if self.users[user_id]["sessions"][session_token]["expires"]:
self.users[user_id]["sessions"][session_token]["expires"] = (datetime.datetime.now() + datetime.timedelta(
seconds=IDLE_TIME_BEFORE_SESSION_EXPIRES)).isoformat()
def check_for_expired_user_sessions(self):
change_flag = False
now = datetime.datetime.now().isoformat()
sessions = self.sessions.copy()
for session_token in sessions:
user_id = self.sessions[session_token]
expires = self.users[user_id]["sessions"][session_token]["expires"]
if expires and expires < now:
self.end_session(session_token)
change_flag = True
if change_flag:
self.save_users()
def get_permissions_for_session_token(self, session_token):
if session_token in self.sessions:
user_id = self.sessions[session_token]
if user_id in self.users:
role = self.users[user_id]["role"]
if role in USER_ROLES:
return USER_ROLES[role]
return USER_ROLES["Guest"]
def get_user_id_for_session_token(self, session_token):
if session_token in self.sessions:
return self.sessions[session_token]
else:
return "Guest"
| true | true |
f731716e66ce6ce28fd803a90df2d90dd154013a | 1,402 | py | Python | iop_data_flow/footfall/01_footfall_clip.py | IaaC/MACT21.22_Digital_tools_Big_Data_part_2 | f0c50a5f7ac147f6e9753545767d2d9998075ebb | [
"Apache-2.0"
] | 1 | 2022-02-18T14:35:34.000Z | 2022-02-18T14:35:34.000Z | iop_data_flow/footfall/01_footfall_clip.py | IaaC/MACT21.22_Digital_tools_Big_Data_part_2 | f0c50a5f7ac147f6e9753545767d2d9998075ebb | [
"Apache-2.0"
] | null | null | null | iop_data_flow/footfall/01_footfall_clip.py | IaaC/MACT21.22_Digital_tools_Big_Data_part_2 | f0c50a5f7ac147f6e9753545767d2d9998075ebb | [
"Apache-2.0"
] | 1 | 2022-02-18T14:35:40.000Z | 2022-02-18T14:35:40.000Z | import os
import pandas as pd
import geopandas as gpd
## Config
# Number of rows to read
nrows = 1000
#nrows = 1000000
#nrows = None
# Output file path
day_num = 1
input_csv_filepath = f'../../data/footfall/footfall_20210217/day{day_num}Bcntrakingotherdays.csv'
# Clip mask file path
#clip_mask_filepath = '../../data/studio/clip_area/clip_darea.shp'
clip_mask_filepath = '../../data/footfall/aoi_glories.geojson'
# Output file path
output_file = f'ff-day{day_num}-clipped.shp'
output_folder = '../../data/studio/footfall/01_clipped/'
## Run
# Load csv all spain footfall
print(f"Load csv footfall : {input_csv_filepath}")
df = pd.read_csv(input_csv_filepath,
delimiter='|',
nrows=nrows)
# Convert it to geopandas
gdf = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df.LONGITUDE, df.LATITUDE), crs='epsg:4326')
print(f"Footfall all: {len(gdf)} points")
# Load clip mask
mask_gdf = gpd.read_file(clip_mask_filepath)
mask_gdf = mask_gdf[mask_gdf['geometry'].notnull()]
# Clip it to district
gdf = gpd.clip(gdf, mask_gdf)
print(f"Footfall clipped district: {len(gdf)} points")
# Create output directory if it doesn't exist
if not os.path.exists(output_folder):
os.mkdir(output_folder)
output_fullpath = os.path.join(output_folder, output_file)
# Save clipped points
gdf.to_file(output_fullpath)
print(f"Saved shp footfall district: {output_fullpath}") | 26.961538 | 99 | 0.736091 | import os
import pandas as pd
import geopandas as gpd
= 1000
day_num = 1
input_csv_filepath = f'../../data/footfall/footfall_20210217/day{day_num}Bcntrakingotherdays.csv'
clip_mask_filepath = '../../data/footfall/aoi_glories.geojson'
output_file = f'ff-day{day_num}-clipped.shp'
output_folder = '../../data/studio/footfall/01_clipped/'
int(f"Load csv footfall : {input_csv_filepath}")
df = pd.read_csv(input_csv_filepath,
delimiter='|',
nrows=nrows)
gdf = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df.LONGITUDE, df.LATITUDE), crs='epsg:4326')
print(f"Footfall all: {len(gdf)} points")
mask_gdf = gpd.read_file(clip_mask_filepath)
mask_gdf = mask_gdf[mask_gdf['geometry'].notnull()]
gdf = gpd.clip(gdf, mask_gdf)
print(f"Footfall clipped district: {len(gdf)} points")
if not os.path.exists(output_folder):
os.mkdir(output_folder)
output_fullpath = os.path.join(output_folder, output_file)
# Save clipped points
gdf.to_file(output_fullpath)
print(f"Saved shp footfall district: {output_fullpath}") | true | true |
f731716eb335aa711c9fca62072e00fad94f8a35 | 4,633 | py | Python | sis-api/swagger_server/models/address.py | maxbilbow/7054CEM-sis | 1c5067c9afc38e340fcce046048f8ae21d267365 | [
"MIT"
] | null | null | null | sis-api/swagger_server/models/address.py | maxbilbow/7054CEM-sis | 1c5067c9afc38e340fcce046048f8ae21d267365 | [
"MIT"
] | null | null | null | sis-api/swagger_server/models/address.py | maxbilbow/7054CEM-sis | 1c5067c9afc38e340fcce046048f8ae21d267365 | [
"MIT"
] | null | null | null | # coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from swagger_server.models.base_model_ import Model
from swagger_server import util
class Address(Model):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, id: int=None, number_or_name: str=None, street: str=None, town: str=None, county: str=None, postcode: str=None): # noqa: E501
"""Address - a model defined in Swagger
:param id: The id of this Address. # noqa: E501
:type id: int
:param number_or_name: The number_or_name of this Address. # noqa: E501
:type number_or_name: str
:param street: The street of this Address. # noqa: E501
:type street: str
:param town: The town of this Address. # noqa: E501
:type town: str
:param county: The county of this Address. # noqa: E501
:type county: str
:param postcode: The postcode of this Address. # noqa: E501
:type postcode: str
"""
self.swagger_types = {
'id': int,
'number_or_name': str,
'street': str,
'town': str,
'county': str,
'postcode': str
}
self.attribute_map = {
'id': 'id',
'number_or_name': 'number_or_name',
'street': 'street',
'town': 'town',
'county': 'county',
'postcode': 'postcode'
}
self._id = id
self._number_or_name = number_or_name
self._street = street
self._town = town
self._county = county
self._postcode = postcode
@classmethod
def from_dict(cls, dikt) -> 'Address':
"""Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The Address of this Address. # noqa: E501
:rtype: Address
"""
return util.deserialize_model(dikt, cls)
@property
def id(self) -> int:
"""Gets the id of this Address.
:return: The id of this Address.
:rtype: int
"""
return self._id
@id.setter
def id(self, id: int):
"""Sets the id of this Address.
:param id: The id of this Address.
:type id: int
"""
self._id = id
@property
def number_or_name(self) -> str:
"""Gets the number_or_name of this Address.
:return: The number_or_name of this Address.
:rtype: str
"""
return self._number_or_name
@number_or_name.setter
def number_or_name(self, number_or_name: str):
"""Sets the number_or_name of this Address.
:param number_or_name: The number_or_name of this Address.
:type number_or_name: str
"""
self._number_or_name = number_or_name
@property
def street(self) -> str:
"""Gets the street of this Address.
:return: The street of this Address.
:rtype: str
"""
return self._street
@street.setter
def street(self, street: str):
"""Sets the street of this Address.
:param street: The street of this Address.
:type street: str
"""
self._street = street
@property
def town(self) -> str:
"""Gets the town of this Address.
:return: The town of this Address.
:rtype: str
"""
return self._town
@town.setter
def town(self, town: str):
"""Sets the town of this Address.
:param town: The town of this Address.
:type town: str
"""
self._town = town
@property
def county(self) -> str:
"""Gets the county of this Address.
:return: The county of this Address.
:rtype: str
"""
return self._county
@county.setter
def county(self, county: str):
"""Sets the county of this Address.
:param county: The county of this Address.
:type county: str
"""
self._county = county
@property
def postcode(self) -> str:
"""Gets the postcode of this Address.
:return: The postcode of this Address.
:rtype: str
"""
return self._postcode
@postcode.setter
def postcode(self, postcode: str):
"""Sets the postcode of this Address.
:param postcode: The postcode of this Address.
:type postcode: str
"""
self._postcode = postcode
| 24.005181 | 149 | 0.564429 |
from __future__ import absolute_import
from datetime import date, datetime
from typing import List, Dict
from swagger_server.models.base_model_ import Model
from swagger_server import util
class Address(Model):
def __init__(self, id: int=None, number_or_name: str=None, street: str=None, town: str=None, county: str=None, postcode: str=None):
self.swagger_types = {
'id': int,
'number_or_name': str,
'street': str,
'town': str,
'county': str,
'postcode': str
}
self.attribute_map = {
'id': 'id',
'number_or_name': 'number_or_name',
'street': 'street',
'town': 'town',
'county': 'county',
'postcode': 'postcode'
}
self._id = id
self._number_or_name = number_or_name
self._street = street
self._town = town
self._county = county
self._postcode = postcode
@classmethod
def from_dict(cls, dikt) -> 'Address':
return util.deserialize_model(dikt, cls)
@property
def id(self) -> int:
return self._id
@id.setter
def id(self, id: int):
self._id = id
@property
def number_or_name(self) -> str:
return self._number_or_name
@number_or_name.setter
def number_or_name(self, number_or_name: str):
self._number_or_name = number_or_name
@property
def street(self) -> str:
return self._street
@street.setter
def street(self, street: str):
self._street = street
@property
def town(self) -> str:
return self._town
@town.setter
def town(self, town: str):
self._town = town
@property
def county(self) -> str:
return self._county
@county.setter
def county(self, county: str):
self._county = county
@property
def postcode(self) -> str:
return self._postcode
@postcode.setter
def postcode(self, postcode: str):
self._postcode = postcode
| true | true |
f73171a82a9e8efd02676c00bb3724b2c05b4702 | 673 | py | Python | atlasbrief/mainsite/migrations/0002_auto_20180124_1611.py | joshr2020/Atlas-Brief | 4471102a7a4b5bf549ef044d7d7de939438011dd | [
"MIT"
] | 1 | 2018-08-20T19:02:00.000Z | 2018-08-20T19:02:00.000Z | atlasbrief/mainsite/migrations/0002_auto_20180124_1611.py | joshr2020/Atlas-Brief | 4471102a7a4b5bf549ef044d7d7de939438011dd | [
"MIT"
] | null | null | null | atlasbrief/mainsite/migrations/0002_auto_20180124_1611.py | joshr2020/Atlas-Brief | 4471102a7a4b5bf549ef044d7d7de939438011dd | [
"MIT"
] | null | null | null | # Generated by Django 2.0.1 on 2018-01-24 21:11
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('mainsite', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='brief',
name='sources',
),
migrations.RemoveField(
model_name='tag',
name='kind',
),
migrations.AddField(
model_name='country',
name='tag',
field=models.OneToOneField(default=None, on_delete=django.db.models.deletion.CASCADE, to='mainsite.Tag'),
),
]
| 24.035714 | 117 | 0.576523 |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('mainsite', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='brief',
name='sources',
),
migrations.RemoveField(
model_name='tag',
name='kind',
),
migrations.AddField(
model_name='country',
name='tag',
field=models.OneToOneField(default=None, on_delete=django.db.models.deletion.CASCADE, to='mainsite.Tag'),
),
]
| true | true |
f73172073a5b7aa03cf878398739be9ce4b17eb0 | 9,088 | py | Python | src/ploomber/io/_commander.py | aadityasinha-dotcom/ploomber | ddbdb63bf7e92d4c48073893b5f54a5f59383291 | [
"Apache-2.0"
] | null | null | null | src/ploomber/io/_commander.py | aadityasinha-dotcom/ploomber | ddbdb63bf7e92d4c48073893b5f54a5f59383291 | [
"Apache-2.0"
] | null | null | null | src/ploomber/io/_commander.py | aadityasinha-dotcom/ploomber | ddbdb63bf7e92d4c48073893b5f54a5f59383291 | [
"Apache-2.0"
] | null | null | null | import os
import sys
import subprocess
import shutil
from pathlib import Path, PurePosixPath
from click import ClickException
from jinja2 import Environment, PackageLoader, StrictUndefined
from ploomber.io import TerminalWriter
def to_pascal_case(name):
return ''.join([w.capitalize() for w in name.split('_')])
def _delete(dst):
dst = Path(dst)
if dst.is_file():
dst.unlink()
if dst.is_dir():
shutil.rmtree(dst)
class CommanderException(ClickException):
"""
Exception raised when the workflow cannot proceed and require a fix
from the user. It is a subclass of ClickException, which signals the CLI
to hide the traceback
"""
pass
class CommanderStop(Exception):
"""
An exception that stops the execution of a commander without raising
an exception
"""
pass
class Commander:
"""Manage script workflows
"""
def __init__(self,
workspace=None,
templates_path=None,
environment_kwargs=None):
self.tw = TerminalWriter()
self.workspace = None if not workspace else Path(workspace).resolve()
self._to_delete = []
self._warnings = []
self._wd = Path('.').resolve()
if templates_path:
self._env = Environment(loader=PackageLoader(*templates_path),
undefined=StrictUndefined,
**(environment_kwargs or {}))
self._env.filters['to_pascal_case'] = to_pascal_case
else:
self._env = None
def run(self,
*cmd,
description=None,
capture_output=False,
expected_output=None,
error_message=None,
hint=None,
show_cmd=True):
"""Execute a command in a subprocess
Parameters
----------
*cmd
Command to execute
description: str, default=None
Label to display before executing the command
capture_output: bool, default=False
Captures output, otherwise prints to standard output and standard
error
expected_output: str, default=None
Raises a RuntimeError if the output is different than this value.
Only valid when capture_output=True
error_message: str, default=None
Error to display when expected_output does not match. If None,
a generic message is shown
hint: str, default=None
An optional string to show when at the end of the error when
the expected_output does not match. Used to hint the user how
to fix the problem
show_cmd : bool, default=True
Whether to display the command next to the description
(and error message if it fails) or not. Only valid when
description is not None
"""
cmd_str = ' '.join(cmd)
if expected_output is not None and not capture_output:
raise RuntimeError('capture_output must be True when '
'expected_output is not None')
if description:
header = f'{description}: {cmd_str}' if show_cmd else description
self.tw.sep('=', header, blue=True)
error = None
# py 3.6 compatibility: cannot use subprocess.run directly
# because the check_output arg was included until version 3.7
if not capture_output:
try:
result = subprocess.check_call(cmd)
except Exception as e:
error = e
# capture outpuut
else:
try:
result = subprocess.check_output(cmd)
except Exception as e:
error = e
else:
result = result.decode(sys.stdout.encoding)
if expected_output is not None:
error = result != expected_output
if error:
lines = []
if error_message:
line_first = error_message
else:
if show_cmd:
cmd_str = ' '.join(cmd)
line_first = ('An error occurred when executing '
f'command: {cmd_str}')
else:
line_first = 'An error occurred.'
lines.append(line_first)
if not capture_output:
lines.append(f'Original error message: {error}')
if hint:
lines.append(f'Hint: {hint}.')
raise CommanderException('\n'.join(lines))
else:
return result
def __enter__(self):
if self.workspace and not Path(self.workspace).exists():
Path(self.workspace).mkdir()
return self
def __exit__(self, exc_type, exc_value, traceback):
# move to the original working directory
os.chdir(self._wd)
self.rm(*self._to_delete)
supress = isinstance(exc_value, CommanderStop)
if supress:
self.info(str(exc_value))
self._warn_show()
return supress
def rm(self, *args):
"""Deletes all files/directories
Examples
--------
>>> cmdr.rm('file', 'directory') # doctest: +SKIP
"""
for f in args:
_delete(f)
def rm_on_exit(self, path):
"""Removes file upon exit
Examples
--------
>>> cmdr.rm_on_exit('some_temporary_file') # doctest: +SKIP
"""
self._to_delete.append(Path(path).resolve())
def copy_template(self, path, **render_kwargs):
"""Copy template to the workspace
Parameters
----------
path : str
Path to template (relative to templates path)
**render_kwargs
Keyword arguments passed to the template
Examples
--------
>>> # copies template in {templates-path}/directory/template.yaml
>>> # to {workspace}/template.yaml
>>> cmdr.copy_template('directory/template.yaml') # doctest: +SKIP
"""
dst = Path(self.workspace, PurePosixPath(path).name)
# This message is no longer valid since this is only called
# when there is no env yet
if dst.exists():
self.success(f'Using existing {path!s}...')
else:
self.info(f'Adding {dst!s}...')
dst.parent.mkdir(exist_ok=True, parents=True)
content = self._env.get_template(str(path)).render(**render_kwargs)
dst.write_text(content)
def cd(self, dir_):
"""Change current working directory
"""
os.chdir(dir_)
def cp(self, src):
"""
Copies a file or directory to the workspace, replacing it if necessary.
Deleted on exit.
Notes
-----
Used mainly for preparing Dockerfiles since they can only
copy from the current working directory
Examples
--------
>>> # copies dir/file to {workspace}/file
>>> cmdr.cp('dir/file') # doctest: +SKIP
"""
path = Path(src)
if not path.exists():
raise CommanderException(
f'Missing {src} file. Add it and try again.')
# convert to absolute to ensure we delete the right file on __exit__
dst = Path(self.workspace, path.name).resolve()
self._to_delete.append(dst)
_delete(dst)
if path.is_file():
shutil.copy(src, dst)
else:
shutil.copytree(src, dst)
def append_inline(self, line, dst):
"""Append line to a file
Parameters
----------
line : str
Line to append
dst : str
File to append (can be outside the workspace)
Examples
--------
>>> cmdr.append_inline('*.csv', '.gitignore') # doctest: +SKIP
"""
if not Path(dst).exists():
Path(dst).touch()
original = Path(dst).read_text()
Path(dst).write_text(original + '\n' + line + '\n')
def print(self, line):
"""Print message (no color)
"""
self.tw.write(f'{line}\n')
def success(self, line=None):
"""Print success message (green)
"""
self.tw.sep('=', line, green=True)
def info(self, line=None):
"""Print information message (blue)
"""
self.tw.sep('=', line, blue=True)
def warn(self, line=None):
"""Print warning (yellow)
"""
self.tw.sep('=', line, yellow=True)
def warn_on_exit(self, line):
"""Append a warning message to be displayed on exit
"""
self._warnings.append(line)
def _warn_show(self):
"""Display accumulated warning messages (added via .warn_on_exit)
"""
if self._warnings:
self.tw.sep('=', 'Warnings', yellow=True)
self.tw.write('\n\n'.join(self._warnings) + '\n')
self.tw.sep('=', yellow=True)
| 28.4 | 79 | 0.554027 | import os
import sys
import subprocess
import shutil
from pathlib import Path, PurePosixPath
from click import ClickException
from jinja2 import Environment, PackageLoader, StrictUndefined
from ploomber.io import TerminalWriter
def to_pascal_case(name):
return ''.join([w.capitalize() for w in name.split('_')])
def _delete(dst):
dst = Path(dst)
if dst.is_file():
dst.unlink()
if dst.is_dir():
shutil.rmtree(dst)
class CommanderException(ClickException):
pass
class CommanderStop(Exception):
pass
class Commander:
def __init__(self,
workspace=None,
templates_path=None,
environment_kwargs=None):
self.tw = TerminalWriter()
self.workspace = None if not workspace else Path(workspace).resolve()
self._to_delete = []
self._warnings = []
self._wd = Path('.').resolve()
if templates_path:
self._env = Environment(loader=PackageLoader(*templates_path),
undefined=StrictUndefined,
**(environment_kwargs or {}))
self._env.filters['to_pascal_case'] = to_pascal_case
else:
self._env = None
def run(self,
*cmd,
description=None,
capture_output=False,
expected_output=None,
error_message=None,
hint=None,
show_cmd=True):
cmd_str = ' '.join(cmd)
if expected_output is not None and not capture_output:
raise RuntimeError('capture_output must be True when '
'expected_output is not None')
if description:
header = f'{description}: {cmd_str}' if show_cmd else description
self.tw.sep('=', header, blue=True)
error = None
if not capture_output:
try:
result = subprocess.check_call(cmd)
except Exception as e:
error = e
else:
try:
result = subprocess.check_output(cmd)
except Exception as e:
error = e
else:
result = result.decode(sys.stdout.encoding)
if expected_output is not None:
error = result != expected_output
if error:
lines = []
if error_message:
line_first = error_message
else:
if show_cmd:
cmd_str = ' '.join(cmd)
line_first = ('An error occurred when executing '
f'command: {cmd_str}')
else:
line_first = 'An error occurred.'
lines.append(line_first)
if not capture_output:
lines.append(f'Original error message: {error}')
if hint:
lines.append(f'Hint: {hint}.')
raise CommanderException('\n'.join(lines))
else:
return result
def __enter__(self):
if self.workspace and not Path(self.workspace).exists():
Path(self.workspace).mkdir()
return self
def __exit__(self, exc_type, exc_value, traceback):
os.chdir(self._wd)
self.rm(*self._to_delete)
supress = isinstance(exc_value, CommanderStop)
if supress:
self.info(str(exc_value))
self._warn_show()
return supress
def rm(self, *args):
for f in args:
_delete(f)
def rm_on_exit(self, path):
self._to_delete.append(Path(path).resolve())
def copy_template(self, path, **render_kwargs):
dst = Path(self.workspace, PurePosixPath(path).name)
if dst.exists():
self.success(f'Using existing {path!s}...')
else:
self.info(f'Adding {dst!s}...')
dst.parent.mkdir(exist_ok=True, parents=True)
content = self._env.get_template(str(path)).render(**render_kwargs)
dst.write_text(content)
def cd(self, dir_):
os.chdir(dir_)
def cp(self, src):
path = Path(src)
if not path.exists():
raise CommanderException(
f'Missing {src} file. Add it and try again.')
dst = Path(self.workspace, path.name).resolve()
self._to_delete.append(dst)
_delete(dst)
if path.is_file():
shutil.copy(src, dst)
else:
shutil.copytree(src, dst)
def append_inline(self, line, dst):
if not Path(dst).exists():
Path(dst).touch()
original = Path(dst).read_text()
Path(dst).write_text(original + '\n' + line + '\n')
def print(self, line):
self.tw.write(f'{line}\n')
def success(self, line=None):
self.tw.sep('=', line, green=True)
def info(self, line=None):
self.tw.sep('=', line, blue=True)
def warn(self, line=None):
self.tw.sep('=', line, yellow=True)
def warn_on_exit(self, line):
self._warnings.append(line)
def _warn_show(self):
if self._warnings:
self.tw.sep('=', 'Warnings', yellow=True)
self.tw.write('\n\n'.join(self._warnings) + '\n')
self.tw.sep('=', yellow=True)
| true | true |
f73173b0bf6552c411247cc25c457802bd9b31e5 | 15,273 | py | Python | zerogercrnn/experiments/ast_level/metrics.py | zerogerc/rnn-autocomplete | 39dc8dd7c431cb8ac9e15016388ec823771388e4 | [
"Apache-2.0"
] | 7 | 2019-02-27T09:48:39.000Z | 2021-11-30T19:01:01.000Z | zerogercrnn/experiments/ast_level/metrics.py | ZeRoGerc/rnn-autocomplete | 39dc8dd7c431cb8ac9e15016388ec823771388e4 | [
"Apache-2.0"
] | null | null | null | zerogercrnn/experiments/ast_level/metrics.py | ZeRoGerc/rnn-autocomplete | 39dc8dd7c431cb8ac9e15016388ec823771388e4 | [
"Apache-2.0"
] | null | null | null | import json
import os
import numpy as np
import torch
from zerogercrnn.lib.constants import EMPTY_TOKEN_ID, UNKNOWN_TOKEN_ID
from zerogercrnn.experiments.ast_level.utils import read_non_terminals
from zerogercrnn.lib.constants import EMPTY_TOKEN_ID, UNKNOWN_TOKEN_ID, EOF_TOKEN
from zerogercrnn.lib.metrics import Metrics, BaseAccuracyMetrics, IndexedAccuracyMetrics, MaxPredictionAccuracyMetrics, TopKAccuracy
class NonTerminalsMetricsWrapper(Metrics):
"""Metrics that extract non-terminals from target and pass non-terminals tensor to base metrics."""
def __init__(self, base: Metrics):
super().__init__()
self.base = base
def drop_state(self):
self.base.drop_state()
def report(self, prediction_target):
prediction, target = prediction_target
self.base.report((prediction, target.non_terminals))
def get_current_value(self, should_print=False):
return self.base.get_current_value(should_print)
def decrease_hits(self, number):
self.base.decrease_hits(number)
class SingleNonTerminalAccuracyMetrics(Metrics):
"""Metrics that show accuracies per non-terminal. It should not be used for plotting, but to
print results on console during model evaluation."""
def __init__(self, non_terminals_file, results_dir=None, group=False, dim=2):
"""
:param non_terminals_file: file with json of non-terminals
:param results_dir: where to save json with accuracies per non-terminal
:param dim: dimension to run max function on for predicted values
"""
super().__init__()
print('SingleNonTerminalAccuracyMetrics created!')
self.non_terminals = read_non_terminals(non_terminals_file)
self.non_terminals_number = len(self.non_terminals)
self.results_dir = results_dir
self.group = group
self.dim = dim
self.accuracies = [IndexedAccuracyMetrics(label='ERROR') for _ in self.non_terminals]
def drop_state(self):
for accuracy in self.accuracies:
accuracy.drop_state()
def report(self, data):
prediction, target = data
if self.dim is None:
predicted = prediction
else:
_, predicted = torch.max(prediction, dim=self.dim)
predicted = predicted.view(-1)
target = target.non_terminals.view(-1)
for cur in range(len(self.non_terminals)):
indices = (target == cur).nonzero().squeeze()
self.accuracies[cur].report(predicted, target, indices)
def get_current_value(self, should_print=False):
result = []
for cur in range(len(self.non_terminals)):
cur_accuracy = self.accuracies[cur].get_current_value(should_print=False)
result.append(cur_accuracy)
# if should_print:
# print('Accuracy on {} is {}'.format(self.non_terminals[cur], cur_accuracy))
self.save_to_file(result)
return 0 # this metrics if only for printing
def save_to_file(self, result):
if self.results_dir is not None:
if self.group:
nt, res = self.get_grouped_result()
else:
nt, res = self.non_terminals, result
with open(os.path.join(self.results_dir, 'nt_acc.txt'), mode='w') as f:
f.write(json.dumps(nt))
f.write('\n')
f.write(json.dumps(res))
def get_grouped_result(self):
"""Calc accuracies ignoring last two bits of information."""
nt = set()
hits = {}
misses = {}
for i in range(len(self.non_terminals)):
base = self.non_terminals[i]
if self.non_terminals[i] != EOF_TOKEN:
base = base[:-2] # remove last two bits
nt.add(base)
if base not in hits:
hits[base] = 0
if base not in misses:
misses[base] = 0
hits[base] += self.accuracies[i].metrics.hits
misses[base] += self.accuracies[i].metrics.misses
nt = sorted(list(nt))
result = []
nt.remove('Program')
nt.remove('AssignmentPattern')
for cur in nt:
if hits[cur] + misses[cur] == 0:
result.append(0)
else:
result.append(float(hits[cur]) / (hits[cur] + misses[cur]))
return nt, result
class TerminalAccuracyMetrics(Metrics):
def __init__(self, dim=2):
super().__init__()
self.dim = dim
self.general_accuracy = BaseAccuracyMetrics()
self.empty_accuracy = IndexedAccuracyMetrics(
label='Accuracy on terminals that ground truth is <empty>'
)
self.non_empty_accuracy = IndexedAccuracyMetrics(
label='Accuracy on terminals that ground truth is not <empty>'
)
self.ground_not_unk_accuracy = IndexedAccuracyMetrics(
label='Accuracy on terminals that ground truth is not <unk> (and ground truth is not <empty>)'
)
self.model_not_unk_accuracy = IndexedAccuracyMetrics(
label='Accuracy on terminals that model predicted to non <unk> (and ground truth is not <empty>)'
)
def drop_state(self):
self.general_accuracy.drop_state()
self.empty_accuracy.drop_state()
self.non_empty_accuracy.drop_state()
self.ground_not_unk_accuracy.drop_state()
self.model_not_unk_accuracy.drop_state()
def report(self, prediction_target):
prediction, target = prediction_target
_, predicted = torch.max(prediction, dim=self.dim)
predicted = predicted.view(-1)
target = target.view(-1)
self.general_accuracy.report((predicted, target))
if not self.is_train:
empty_indexes = torch.nonzero(target == 0).squeeze()
self.empty_accuracy.report(predicted, target, empty_indexes)
non_empty_indexes = torch.nonzero(target - EMPTY_TOKEN_ID).squeeze()
self.non_empty_accuracy.report(predicted, target, non_empty_indexes)
predicted = torch.index_select(predicted, 0, non_empty_indexes)
target = torch.index_select(target, 0, non_empty_indexes)
ground_not_unk_indexes = torch.nonzero(target - UNKNOWN_TOKEN_ID).squeeze()
self.ground_not_unk_accuracy.report(predicted, target, ground_not_unk_indexes)
model_not_unk_indexes = torch.nonzero(predicted - UNKNOWN_TOKEN_ID).squeeze()
self.model_not_unk_accuracy.report(predicted, target, model_not_unk_indexes)
def get_current_value(self, should_print=False):
general_accuracy = self.general_accuracy.get_current_value(should_print=should_print)
if (not self.is_train) and should_print:
self.empty_accuracy.get_current_value(should_print=True)
self.non_empty_accuracy.get_current_value(should_print=True)
self.ground_not_unk_accuracy.get_current_value(should_print=True)
self.model_not_unk_accuracy.get_current_value(should_print=True)
return general_accuracy
class NonTerminalTerminalAccuracyMetrics(Metrics):
def __init__(self):
super().__init__()
self.nt_accuracy = MaxPredictionAccuracyMetrics()
self.t_accuracy = MaxPredictionAccuracyMetrics()
def drop_state(self):
self.nt_accuracy.drop_state()
self.t_accuracy.drop_state()
def report(self, data):
nt_prediction, t_prediction, nt_target, t_target = data
self.nt_accuracy.report((nt_prediction, nt_target))
self.t_accuracy.report((t_prediction, t_target))
def get_current_value(self, should_print=False):
nt_value = self.nt_accuracy.get_current_value(should_print=False)
t_value = self.t_accuracy.get_current_value(should_print=False)
if should_print:
print('Non terminals accuracy: {}'.format(nt_value))
print('Terminals accuracy: {}'.format(t_value))
return nt_value, t_value
class LayeredNodeDepthsAttentionMetrics(Metrics):
"""Metrics that is able to visualize attention coefficient per node depths"""
def __init__(self):
super().__init__()
self.per_depth_attention_sum = np.zeros((50, 50))
self.per_depth_reports = np.zeros((50))
def drop_state(self):
pass
def report(self, node_depths, attention_coefficients):
for i in range(50):
index = torch.nonzero((node_depths == i))
if index.size()[0] == 0:
continue
selected_attention = torch.index_select(attention_coefficients, dim=0, index=index.squeeze())
selected_attention = selected_attention.squeeze(2)
to_report = torch.sum(selected_attention, dim=0).cpu().numpy()
self.per_depth_attention_sum[i] += to_report
self.per_depth_reports[i] += index.size()[0]
def get_current_value(self, should_print=False):
for i in range(50):
if abs(self.per_depth_reports[i]) > 1e-6:
self.per_depth_attention_sum[i] /= self.per_depth_reports[i]
np.save('eval/temp/attention/per_depth_matrix', self.per_depth_attention_sum)
return 0 # this metrics is only for saving results to file.
class PerNtAttentionMetrics(Metrics):
def __init__(self):
super().__init__()
def report(self, current_input, attention_coefficients):
nt_ids = torch.argmax(current_input, dim=-1)
# for i in range(97): # TODO: check
# index = torch.nonzero((nt_ids == i))
# if index.size()[0] == 0:
# continue
# selected_attention = torch.index_select(attention_coefficients, dim=0, index=index.squeeze())
# selected_attention = selected_attention.squeeze(2)
# to_report = torch.sum(selected_attention, dim=0).cpu().numpy()
# self.per_depth_attention_sum[i] += to_report
# self.per_depth_reports[i] += index.size()[0]
def drop_state(self):
pass
def get_current_value(self, should_print=False):
pass
class EmptyNonEmptyWrapper(Metrics):
def __init__(self, non_emp_base: Metrics, with_emp_base:Metrics):
super().__init__()
self.non_emp_base = non_emp_base
self.with_emp_base = with_emp_base
def drop_state(self):
self.non_emp_base.drop_state()
self.with_emp_base.drop_state()
def report(self, prediction_target):
prediction, target = prediction_target
prediction = prediction.view(-1)
target = target.view(-1)
self.with_emp_base.report((prediction, target))
non_emp_indices = (target != EMPTY_TOKEN_ID).nonzero().squeeze()
prediction = torch.index_select(prediction, 0, non_emp_indices)
target = torch.index_select(target, 0, non_emp_indices)
self.non_emp_base.report((prediction, target))
def get_current_value(self, should_print=False):
print('Non Empty')
self.non_emp_base.get_current_value(should_print=should_print)
print('With Empty')
self.with_emp_base.get_current_value(should_print=should_print)
class EmptyNonEmptyTerminalTopKAccuracyWrapper(Metrics):
def __init__(self):
super().__init__()
self.non_emp_base = TopKAccuracy(k=5)
self.with_emp_base = TopKAccuracy(k=5)
def drop_state(self):
self.non_emp_base.drop_state()
self.with_emp_base.drop_state()
def report(self, prediction_target):
prediction, target = prediction_target
prediction = prediction.view(-1, prediction.size()[-1])
target = target.view(-1)
self.with_emp_base.report((prediction, target))
non_emp_indices = (target != EMPTY_TOKEN_ID).nonzero().squeeze()
prediction = torch.index_select(prediction, 0, non_emp_indices)
target = torch.index_select(target, 0, non_emp_indices)
self.non_emp_base.report((prediction, target))
def get_current_value(self, should_print=False):
print('Non Empty')
self.non_emp_base.get_current_value(should_print=should_print)
print('With Empty')
self.with_emp_base.get_current_value(should_print=should_print)
# class AggregatedTerminalTopKMetrics(Metrics):
#
# def __init__(self, k):
# super().__init__()
# self.k = k
# self.common = BaseAccuracyMetrics()
# self.target_non_unk = Top
# self.prediction_non_unk = IndexedAccuracyMetrics('Prediction not unk')
#
# def drop_state(self):
# self.common.drop_state()
# self.target_non_unk.drop_state()
# self.prediction_non_unk.drop_state()
#
# def report(self, prediction_target):
# prediction, target = prediction_target
# prediction = prediction.view(-1)
# target = target.view(-1)
#
# self.common.report((prediction, target))
#
# pred_non_unk_indices = (prediction != UNKNOWN_TOKEN_ID).nonzero().squeeze()
# target_non_unk_indices = (target != UNKNOWN_TOKEN_ID).nonzero().squeeze()
#
# self.prediction_non_unk.report(prediction, target, pred_non_unk_indices)
# self.target_non_unk.report(prediction, target, target_non_unk_indices)
#
# def get_current_value(self, should_print=False):
# print('P(hat(t) == t) = {}'.format(self.common.get_current_value(False)))
# print('P(hat(t) == t && hat(t) != unk) = {}'.format(self.prediction_non_unk.metrics.hits / (self.common.hits + self.common.misses)))
# print('P(hat(t) == t | t != unk) = {}'.format(self.target_non_unk.get_current_value(False)))
# print('P(hat(t) == t | hat(t) != unk) = {}'.format(self.prediction_non_unk.get_current_value(False)))
class AggregatedTerminalMetrics(Metrics):
def __init__(self):
super().__init__()
self.common = BaseAccuracyMetrics()
self.target_non_unk = IndexedAccuracyMetrics('Target not unk')
self.prediction_non_unk = IndexedAccuracyMetrics('Prediction not unk')
def drop_state(self):
self.common.drop_state()
self.target_non_unk.drop_state()
self.prediction_non_unk.drop_state()
def report(self, prediction_target):
prediction, target = prediction_target
prediction = prediction.view(-1)
target = target.view(-1)
self.common.report((prediction, target))
pred_non_unk_indices = (prediction != UNKNOWN_TOKEN_ID).nonzero().squeeze()
target_non_unk_indices = (target != UNKNOWN_TOKEN_ID).nonzero().squeeze()
self.prediction_non_unk.report(prediction, target, pred_non_unk_indices)
self.target_non_unk.report(prediction, target, target_non_unk_indices)
def get_current_value(self, should_print=False):
print('P(hat(t) == t) = {}'.format(self.common.get_current_value(False)))
print('P(hat(t) == t && hat(t) != unk) = {}'.format(self.prediction_non_unk.metrics.hits / (self.common.hits + self.common.misses)))
print('P(hat(t) == t | t != unk) = {}'.format(self.target_non_unk.get_current_value(False)))
print('P(hat(t) == t | hat(t) != unk) = {}'.format(self.prediction_non_unk.get_current_value(False)))
| 38.568182 | 142 | 0.659726 | import json
import os
import numpy as np
import torch
from zerogercrnn.lib.constants import EMPTY_TOKEN_ID, UNKNOWN_TOKEN_ID
from zerogercrnn.experiments.ast_level.utils import read_non_terminals
from zerogercrnn.lib.constants import EMPTY_TOKEN_ID, UNKNOWN_TOKEN_ID, EOF_TOKEN
from zerogercrnn.lib.metrics import Metrics, BaseAccuracyMetrics, IndexedAccuracyMetrics, MaxPredictionAccuracyMetrics, TopKAccuracy
class NonTerminalsMetricsWrapper(Metrics):
def __init__(self, base: Metrics):
super().__init__()
self.base = base
def drop_state(self):
self.base.drop_state()
def report(self, prediction_target):
prediction, target = prediction_target
self.base.report((prediction, target.non_terminals))
def get_current_value(self, should_print=False):
return self.base.get_current_value(should_print)
def decrease_hits(self, number):
self.base.decrease_hits(number)
class SingleNonTerminalAccuracyMetrics(Metrics):
def __init__(self, non_terminals_file, results_dir=None, group=False, dim=2):
super().__init__()
print('SingleNonTerminalAccuracyMetrics created!')
self.non_terminals = read_non_terminals(non_terminals_file)
self.non_terminals_number = len(self.non_terminals)
self.results_dir = results_dir
self.group = group
self.dim = dim
self.accuracies = [IndexedAccuracyMetrics(label='ERROR') for _ in self.non_terminals]
def drop_state(self):
for accuracy in self.accuracies:
accuracy.drop_state()
def report(self, data):
prediction, target = data
if self.dim is None:
predicted = prediction
else:
_, predicted = torch.max(prediction, dim=self.dim)
predicted = predicted.view(-1)
target = target.non_terminals.view(-1)
for cur in range(len(self.non_terminals)):
indices = (target == cur).nonzero().squeeze()
self.accuracies[cur].report(predicted, target, indices)
def get_current_value(self, should_print=False):
result = []
for cur in range(len(self.non_terminals)):
cur_accuracy = self.accuracies[cur].get_current_value(should_print=False)
result.append(cur_accuracy)
self.save_to_file(result)
return 0
def save_to_file(self, result):
if self.results_dir is not None:
if self.group:
nt, res = self.get_grouped_result()
else:
nt, res = self.non_terminals, result
with open(os.path.join(self.results_dir, 'nt_acc.txt'), mode='w') as f:
f.write(json.dumps(nt))
f.write('\n')
f.write(json.dumps(res))
def get_grouped_result(self):
nt = set()
hits = {}
misses = {}
for i in range(len(self.non_terminals)):
base = self.non_terminals[i]
if self.non_terminals[i] != EOF_TOKEN:
base = base[:-2]
nt.add(base)
if base not in hits:
hits[base] = 0
if base not in misses:
misses[base] = 0
hits[base] += self.accuracies[i].metrics.hits
misses[base] += self.accuracies[i].metrics.misses
nt = sorted(list(nt))
result = []
nt.remove('Program')
nt.remove('AssignmentPattern')
for cur in nt:
if hits[cur] + misses[cur] == 0:
result.append(0)
else:
result.append(float(hits[cur]) / (hits[cur] + misses[cur]))
return nt, result
class TerminalAccuracyMetrics(Metrics):
def __init__(self, dim=2):
super().__init__()
self.dim = dim
self.general_accuracy = BaseAccuracyMetrics()
self.empty_accuracy = IndexedAccuracyMetrics(
label='Accuracy on terminals that ground truth is <empty>'
)
self.non_empty_accuracy = IndexedAccuracyMetrics(
label='Accuracy on terminals that ground truth is not <empty>'
)
self.ground_not_unk_accuracy = IndexedAccuracyMetrics(
label='Accuracy on terminals that ground truth is not <unk> (and ground truth is not <empty>)'
)
self.model_not_unk_accuracy = IndexedAccuracyMetrics(
label='Accuracy on terminals that model predicted to non <unk> (and ground truth is not <empty>)'
)
def drop_state(self):
self.general_accuracy.drop_state()
self.empty_accuracy.drop_state()
self.non_empty_accuracy.drop_state()
self.ground_not_unk_accuracy.drop_state()
self.model_not_unk_accuracy.drop_state()
def report(self, prediction_target):
prediction, target = prediction_target
_, predicted = torch.max(prediction, dim=self.dim)
predicted = predicted.view(-1)
target = target.view(-1)
self.general_accuracy.report((predicted, target))
if not self.is_train:
empty_indexes = torch.nonzero(target == 0).squeeze()
self.empty_accuracy.report(predicted, target, empty_indexes)
non_empty_indexes = torch.nonzero(target - EMPTY_TOKEN_ID).squeeze()
self.non_empty_accuracy.report(predicted, target, non_empty_indexes)
predicted = torch.index_select(predicted, 0, non_empty_indexes)
target = torch.index_select(target, 0, non_empty_indexes)
ground_not_unk_indexes = torch.nonzero(target - UNKNOWN_TOKEN_ID).squeeze()
self.ground_not_unk_accuracy.report(predicted, target, ground_not_unk_indexes)
model_not_unk_indexes = torch.nonzero(predicted - UNKNOWN_TOKEN_ID).squeeze()
self.model_not_unk_accuracy.report(predicted, target, model_not_unk_indexes)
def get_current_value(self, should_print=False):
general_accuracy = self.general_accuracy.get_current_value(should_print=should_print)
if (not self.is_train) and should_print:
self.empty_accuracy.get_current_value(should_print=True)
self.non_empty_accuracy.get_current_value(should_print=True)
self.ground_not_unk_accuracy.get_current_value(should_print=True)
self.model_not_unk_accuracy.get_current_value(should_print=True)
return general_accuracy
class NonTerminalTerminalAccuracyMetrics(Metrics):
def __init__(self):
super().__init__()
self.nt_accuracy = MaxPredictionAccuracyMetrics()
self.t_accuracy = MaxPredictionAccuracyMetrics()
def drop_state(self):
self.nt_accuracy.drop_state()
self.t_accuracy.drop_state()
def report(self, data):
nt_prediction, t_prediction, nt_target, t_target = data
self.nt_accuracy.report((nt_prediction, nt_target))
self.t_accuracy.report((t_prediction, t_target))
def get_current_value(self, should_print=False):
nt_value = self.nt_accuracy.get_current_value(should_print=False)
t_value = self.t_accuracy.get_current_value(should_print=False)
if should_print:
print('Non terminals accuracy: {}'.format(nt_value))
print('Terminals accuracy: {}'.format(t_value))
return nt_value, t_value
class LayeredNodeDepthsAttentionMetrics(Metrics):
def __init__(self):
super().__init__()
self.per_depth_attention_sum = np.zeros((50, 50))
self.per_depth_reports = np.zeros((50))
def drop_state(self):
pass
def report(self, node_depths, attention_coefficients):
for i in range(50):
index = torch.nonzero((node_depths == i))
if index.size()[0] == 0:
continue
selected_attention = torch.index_select(attention_coefficients, dim=0, index=index.squeeze())
selected_attention = selected_attention.squeeze(2)
to_report = torch.sum(selected_attention, dim=0).cpu().numpy()
self.per_depth_attention_sum[i] += to_report
self.per_depth_reports[i] += index.size()[0]
def get_current_value(self, should_print=False):
for i in range(50):
if abs(self.per_depth_reports[i]) > 1e-6:
self.per_depth_attention_sum[i] /= self.per_depth_reports[i]
np.save('eval/temp/attention/per_depth_matrix', self.per_depth_attention_sum)
return 0
class PerNtAttentionMetrics(Metrics):
def __init__(self):
super().__init__()
def report(self, current_input, attention_coefficients):
nt_ids = torch.argmax(current_input, dim=-1)
def drop_state(self):
pass
def get_current_value(self, should_print=False):
pass
class EmptyNonEmptyWrapper(Metrics):
def __init__(self, non_emp_base: Metrics, with_emp_base:Metrics):
super().__init__()
self.non_emp_base = non_emp_base
self.with_emp_base = with_emp_base
def drop_state(self):
self.non_emp_base.drop_state()
self.with_emp_base.drop_state()
def report(self, prediction_target):
prediction, target = prediction_target
prediction = prediction.view(-1)
target = target.view(-1)
self.with_emp_base.report((prediction, target))
non_emp_indices = (target != EMPTY_TOKEN_ID).nonzero().squeeze()
prediction = torch.index_select(prediction, 0, non_emp_indices)
target = torch.index_select(target, 0, non_emp_indices)
self.non_emp_base.report((prediction, target))
def get_current_value(self, should_print=False):
print('Non Empty')
self.non_emp_base.get_current_value(should_print=should_print)
print('With Empty')
self.with_emp_base.get_current_value(should_print=should_print)
class EmptyNonEmptyTerminalTopKAccuracyWrapper(Metrics):
def __init__(self):
super().__init__()
self.non_emp_base = TopKAccuracy(k=5)
self.with_emp_base = TopKAccuracy(k=5)
def drop_state(self):
self.non_emp_base.drop_state()
self.with_emp_base.drop_state()
def report(self, prediction_target):
prediction, target = prediction_target
prediction = prediction.view(-1, prediction.size()[-1])
target = target.view(-1)
self.with_emp_base.report((prediction, target))
non_emp_indices = (target != EMPTY_TOKEN_ID).nonzero().squeeze()
prediction = torch.index_select(prediction, 0, non_emp_indices)
target = torch.index_select(target, 0, non_emp_indices)
self.non_emp_base.report((prediction, target))
def get_current_value(self, should_print=False):
print('Non Empty')
self.non_emp_base.get_current_value(should_print=should_print)
print('With Empty')
self.with_emp_base.get_current_value(should_print=should_print)
class AggregatedTerminalMetrics(Metrics):
def __init__(self):
super().__init__()
self.common = BaseAccuracyMetrics()
self.target_non_unk = IndexedAccuracyMetrics('Target not unk')
self.prediction_non_unk = IndexedAccuracyMetrics('Prediction not unk')
def drop_state(self):
self.common.drop_state()
self.target_non_unk.drop_state()
self.prediction_non_unk.drop_state()
def report(self, prediction_target):
prediction, target = prediction_target
prediction = prediction.view(-1)
target = target.view(-1)
self.common.report((prediction, target))
pred_non_unk_indices = (prediction != UNKNOWN_TOKEN_ID).nonzero().squeeze()
target_non_unk_indices = (target != UNKNOWN_TOKEN_ID).nonzero().squeeze()
self.prediction_non_unk.report(prediction, target, pred_non_unk_indices)
self.target_non_unk.report(prediction, target, target_non_unk_indices)
def get_current_value(self, should_print=False):
print('P(hat(t) == t) = {}'.format(self.common.get_current_value(False)))
print('P(hat(t) == t && hat(t) != unk) = {}'.format(self.prediction_non_unk.metrics.hits / (self.common.hits + self.common.misses)))
print('P(hat(t) == t | t != unk) = {}'.format(self.target_non_unk.get_current_value(False)))
print('P(hat(t) == t | hat(t) != unk) = {}'.format(self.prediction_non_unk.get_current_value(False)))
| true | true |
f731744360c85355f37d6f3b7a8789da418a6261 | 544 | py | Python | LeetCode/Algorithms/Easy/PascalsTriangle/PascalsTriangle.py | roshan11160/Competitive-Programming-Solutions | 2d9cfe901c23a2b7344c410b7368eb02f7fa6e7e | [
"MIT"
] | 40 | 2020-07-25T19:35:37.000Z | 2022-01-28T02:57:02.000Z | LeetCode/Algorithms/Easy/PascalsTriangle/PascalsTriangle.py | afrozchakure/Hackerrank-Problem-Solutions | 014155d841e08cb1f7609c23335576dc9b29cef3 | [
"MIT"
] | 34 | 2020-10-10T17:59:46.000Z | 2021-10-05T18:29:25.000Z | LeetCode/Algorithms/Easy/PascalsTriangle/PascalsTriangle.py | afrozchakure/Hackerrank-Problem-Solutions | 014155d841e08cb1f7609c23335576dc9b29cef3 | [
"MIT"
] | 24 | 2020-05-03T08:11:53.000Z | 2021-10-04T03:23:20.000Z | class Solution:
def generate(self, numRows: int) -> List[List[int]]:
result = [[1]]
for i in range(1, numRows):
temp1 = result[-1] + [0]
temp2 = [0] + result[-1]
result.append([temp1[i] + temp2[i] for i in range(len(temp1))])
return result[:numRows]
# Time Complexity - O(n**2)\
# Space Complexity - O(n)
"""
explanation: Any row can be constructed using the offset sum of the previous row. Example:
1 3 3 1 0
+ 0 1 3 3 1
= 1 4 6 4 1
"""
| 25.904762 | 90 | 0.523897 | class Solution:
def generate(self, numRows: int) -> List[List[int]]:
result = [[1]]
for i in range(1, numRows):
temp1 = result[-1] + [0]
temp2 = [0] + result[-1]
result.append([temp1[i] + temp2[i] for i in range(len(temp1))])
return result[:numRows]
| true | true |
f7317480ca6a2ca583ccb6170587b803d919d1a4 | 2,591 | py | Python | framework/auth/decorators.py | alexschiller/osf.io | 4122d4be152c6189142c2ebb19cfdee09c77035d | [
"Apache-2.0"
] | null | null | null | framework/auth/decorators.py | alexschiller/osf.io | 4122d4be152c6189142c2ebb19cfdee09c77035d | [
"Apache-2.0"
] | null | null | null | framework/auth/decorators.py | alexschiller/osf.io | 4122d4be152c6189142c2ebb19cfdee09c77035d | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
import time
import httplib
import functools
from flask import request
from framework.auth import cas
from framework.auth import signing
from framework.flask import redirect
from framework.exceptions import HTTPError
from .core import Auth
from .core import User
def collect_auth(func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
kwargs['auth'] = Auth.from_kwargs(request.args.to_dict(), kwargs)
return func(*args, **kwargs)
return wrapped
def must_be_confirmed(func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
user = User.load(kwargs['uid'])
if user is not None:
if user.is_confirmed:
return func(*args, **kwargs)
else:
raise HTTPError(httplib.BAD_REQUEST, data={
'message_short': 'Account not yet confirmed',
'message_long': 'The profile page could not be displayed as the user has not confirmed the account.'
})
else:
raise HTTPError(httplib.NOT_FOUND)
return wrapped
def must_be_logged_in(func):
"""Require that user be logged in. Modifies kwargs to include the current
user.
"""
@functools.wraps(func)
def wrapped(*args, **kwargs):
kwargs['auth'] = Auth.from_kwargs(request.args.to_dict(), kwargs)
if kwargs['auth'].logged_in:
return func(*args, **kwargs)
else:
return redirect(cas.get_login_url(request.url))
return wrapped
def must_be_signed(func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
if request.method in ('GET', 'DELETE'):
data = request.args
else:
data = request.get_json()
try:
sig = data['signature']
payload = signing.unserialize_payload(data['payload'])
exp_time = payload['time']
except (KeyError, ValueError):
raise HTTPError(httplib.BAD_REQUEST, data={
'message_short': 'Invalid payload',
'message_long': 'The request payload could not be deserialized.'
})
if not signing.default_signer.verify_payload(sig, payload):
raise HTTPError(httplib.UNAUTHORIZED)
if time.time() > exp_time:
raise HTTPError(httplib.BAD_REQUEST, data={
'message_short': 'Expired',
'message_long': 'Signature has expired.'
})
kwargs['payload'] = payload
return func(*args, **kwargs)
return wrapped
| 27.56383 | 120 | 0.603242 |
import time
import httplib
import functools
from flask import request
from framework.auth import cas
from framework.auth import signing
from framework.flask import redirect
from framework.exceptions import HTTPError
from .core import Auth
from .core import User
def collect_auth(func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
kwargs['auth'] = Auth.from_kwargs(request.args.to_dict(), kwargs)
return func(*args, **kwargs)
return wrapped
def must_be_confirmed(func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
user = User.load(kwargs['uid'])
if user is not None:
if user.is_confirmed:
return func(*args, **kwargs)
else:
raise HTTPError(httplib.BAD_REQUEST, data={
'message_short': 'Account not yet confirmed',
'message_long': 'The profile page could not be displayed as the user has not confirmed the account.'
})
else:
raise HTTPError(httplib.NOT_FOUND)
return wrapped
def must_be_logged_in(func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
kwargs['auth'] = Auth.from_kwargs(request.args.to_dict(), kwargs)
if kwargs['auth'].logged_in:
return func(*args, **kwargs)
else:
return redirect(cas.get_login_url(request.url))
return wrapped
def must_be_signed(func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
if request.method in ('GET', 'DELETE'):
data = request.args
else:
data = request.get_json()
try:
sig = data['signature']
payload = signing.unserialize_payload(data['payload'])
exp_time = payload['time']
except (KeyError, ValueError):
raise HTTPError(httplib.BAD_REQUEST, data={
'message_short': 'Invalid payload',
'message_long': 'The request payload could not be deserialized.'
})
if not signing.default_signer.verify_payload(sig, payload):
raise HTTPError(httplib.UNAUTHORIZED)
if time.time() > exp_time:
raise HTTPError(httplib.BAD_REQUEST, data={
'message_short': 'Expired',
'message_long': 'Signature has expired.'
})
kwargs['payload'] = payload
return func(*args, **kwargs)
return wrapped
| true | true |
f731751fa69ae18a6c65a0e7b8a660da710c2f8f | 663 | py | Python | model.py | SMMousaviSP/Sudoku-Solver | 13ab46585aaa1c8072ace58f0eee6df7388f684e | [
"MIT"
] | 26 | 2020-01-25T16:51:01.000Z | 2021-08-02T10:34:49.000Z | model.py | SMMousaviSP/Sudoku-Solver | 13ab46585aaa1c8072ace58f0eee6df7388f684e | [
"MIT"
] | 1 | 2021-04-26T09:03:39.000Z | 2021-04-26T09:03:39.000Z | model.py | SMMousaviSP/Sudoku-Solver | 13ab46585aaa1c8072ace58f0eee6df7388f684e | [
"MIT"
] | 21 | 2020-01-27T08:14:20.000Z | 2021-11-23T07:51:46.000Z | import keras
from keras.layers import Activation
from keras.layers import Conv2D, BatchNormalization, Dense, Flatten, Reshape
def get_model():
model = keras.models.Sequential()
model.add(Conv2D(64, kernel_size=(3,3), activation='relu', padding='same', input_shape=(9,9,1)))
model.add(BatchNormalization())
model.add(Conv2D(64, kernel_size=(3,3), activation='relu', padding='same'))
model.add(BatchNormalization())
model.add(Conv2D(128, kernel_size=(1,1), activation='relu', padding='same'))
model.add(Flatten())
model.add(Dense(81*9))
model.add(Reshape((-1, 9)))
model.add(Activation('softmax'))
return model
| 31.571429 | 100 | 0.689291 | import keras
from keras.layers import Activation
from keras.layers import Conv2D, BatchNormalization, Dense, Flatten, Reshape
def get_model():
model = keras.models.Sequential()
model.add(Conv2D(64, kernel_size=(3,3), activation='relu', padding='same', input_shape=(9,9,1)))
model.add(BatchNormalization())
model.add(Conv2D(64, kernel_size=(3,3), activation='relu', padding='same'))
model.add(BatchNormalization())
model.add(Conv2D(128, kernel_size=(1,1), activation='relu', padding='same'))
model.add(Flatten())
model.add(Dense(81*9))
model.add(Reshape((-1, 9)))
model.add(Activation('softmax'))
return model
| true | true |
f73175349ae72496647a8ded5362832c8f303bf2 | 45,377 | py | Python | exp/cips3d_inversion/models/generator_v2.py | PeterouZh/CIPS-3D | 9b8bfa0fb23f642af042e150ccd70408f9d137c6 | [
"MIT"
] | 308 | 2021-10-19T17:29:14.000Z | 2022-03-31T11:54:45.000Z | exp/cips3d_inversion/models/generator_v2.py | PeterouZh/CIPS-3D | 9b8bfa0fb23f642af042e150ccd70408f9d137c6 | [
"MIT"
] | 28 | 2021-10-31T22:49:00.000Z | 2022-03-25T05:49:47.000Z | exp/cips3d_inversion/models/generator_v2.py | PeterouZh/CIPS-3D | 9b8bfa0fb23f642af042e150ccd70408f9d137c6 | [
"MIT"
] | 44 | 2021-10-21T10:08:23.000Z | 2022-03-16T10:05:08.000Z | from itertools import chain
import math
import logging
import collections
from collections import OrderedDict
import tqdm
import random
import time
from einops import rearrange, repeat
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.cuda.amp import autocast
from tl2.proj.fvcore import MODEL_REGISTRY, build_model
# from tl2.proj.stylegan2_ada import persistence
from tl2.launch.launch_utils import global_cfg
from tl2.proj.pytorch.pytorch_hook import VerboseModel
from tl2.proj.pytorch import torch_utils
from tl2.proj.pytorch import torch_utils, init_func
from tl2 import tl2_utils
from tl2.proj.pytorch.examples.nerf import cam_params
from tl2.proj.pytorch.examples.nerf import volume_rendering
from tl2.proj.pytorch.examples.networks import nerf_net
from tl2.proj.pytorch.examples.networks import multi_head_mapping
from tl2.proj.pytorch.examples.networks import cips_net
from exp.pigan import pigan_utils
from exp.dev.nerf_inr.models.generator_nerf_inr import INRNetwork
from exp.dev.nerf_inr.models.generator_nerf_inr import GeneratorNerfINR as GeneratorNerfINR_base
from exp.comm import comm_utils
from exp.comm.models import nerf_network
from exp.comm.models import inr_network
from exp.comm.models import film_layer
from exp.comm.models import mod_conv_fc
# from exp.cips3d.models import multi_head_mapping
class SkipLayer(nn.Module):
def __init__(self, ):
super(SkipLayer, self).__init__()
def forward(self, x0, x1):
# out = (x0 + x1) / math.pi
out = (x0 + x1)
return out
class SinAct(nn.Module):
def __init__(self, ):
super(SinAct, self).__init__()
def forward(self, x):
return torch.sin(x)
class LinearSinAct(nn.Module):
def __init__(self,
in_features,
out_features):
super(LinearSinAct, self).__init__()
self.linear = nn.Linear(in_features=in_features, out_features=out_features)
self.sin = SinAct()
pass
def forward(self, x, *args, **kwargs):
x = self.linear(x)
x = self.sin(x)
return x
class FiLMLayer(nn.Module):
def __init__(self,
in_dim,
out_dim,
style_dim,
use_style_fc=True,
which_linear=nn.Linear,
**kwargs):
super(FiLMLayer, self).__init__()
self.in_dim = in_dim
self.out_dim = out_dim
self.style_dim = style_dim
self.use_style_fc = use_style_fc
self.linear = which_linear(in_dim, out_dim)
# self.linear.apply(film_layer.frequency_init(25))
# self.gain_scale = film_layer.LinearScale(scale=15, bias=30)
self.gain_scale = nn.Identity()
# Prepare gain and bias layers
if use_style_fc:
self.gain_fc = which_linear(style_dim, out_dim)
self.bias_fc = which_linear(style_dim, out_dim)
# self.gain_fc.weight.data.mul_(0.25)
# self.bias_fc.weight.data.mul_(0.25)
else:
self.style_dim = out_dim * 2
self.sin = SinAct()
self.lrelu = nn.LeakyReLU(0.2, inplace=True)
# self.register_buffer('stored_mean', torch.zeros(output_size))
# self.register_buffer('stored_var', torch.ones(output_size))
pass
def forward(self,
x,
style):
"""
:param x: (b, c) or (b, n, c)
:param style: (b, c)
:return:
"""
if self.use_style_fc:
gain = self.gain_fc(style)
gain = self.gain_scale(gain)
bias = self.bias_fc(style)
else:
style = rearrange(style, "b (n c) -> b n c", n=2)
gain, bias = style.unbind(dim=1)
gain = self.gain_scale(gain)
if x.dim() == 3:
gain = rearrange(gain, "b c -> b 1 c")
bias = rearrange(bias, "b c -> b 1 c")
elif x.dim() == 2:
pass
else:
assert 0
x = self.linear(x)
x = x * torch.rsqrt(torch.mean(x ** 2, dim=-1, keepdim=True) + 1e-8)
# out = self.sin(gain * x + bias)
out = self.lrelu((gain + 1.) * x + bias)
return out
def __repr__(self):
s = f'{self.__class__.__name__}(' \
f'in_dim={self.in_dim}, ' \
f'out_dim={self.out_dim}, ' \
f'style_dim={self.style_dim}, ' \
f'use_style_fc={self.use_style_fc}, ' \
f')'
return s
class INRNetwork_Skip(nn.Module):
def __repr__(self): return f"{self.__class__.__name__}({self.repr})"
def __init__(self,
input_dim,
style_dim,
hidden_layers,
dim_scale=1,
rgb_dim=3,
device=None,
name_prefix='inr',
**kwargs):
"""
:param z_dim:
:param hidden_dim:
:param rgb_dim:
:param device:
:param kwargs:
"""
super().__init__()
self.repr = f"input_dim={input_dim}, " \
f"style_dim={style_dim}, " \
f"hidden_layers={hidden_layers}, " \
f"dim_scale={dim_scale}, "
self.device = device
self.rgb_dim = rgb_dim
self.hidden_layers = hidden_layers
self.name_prefix = name_prefix
self.channels = {
0: int(512 * dim_scale), # 4
1: int(512 * dim_scale), # 8
2: int(512 * dim_scale), # 16
3: int(512 * dim_scale), # 32
4: int(512 * dim_scale), # 64
5: int(128 * dim_scale), # 128
6: int(64 * dim_scale), # 256
7: int(32 * dim_scale), # 512
8: int(16 * dim_scale), # 1024
}
self.style_dim_dict = {}
_out_dim = input_dim
self.network = nn.ModuleList()
self.to_rbgs = nn.ModuleList()
for i in range(hidden_layers):
_in_dim = _out_dim
_out_dim = self.channels[i]
_layer = film_layer.FiLMLayer(in_dim=_in_dim,
out_dim=_out_dim,
style_dim=style_dim)
self.network.append(_layer)
self.style_dim_dict[f'{name_prefix}_w{i}_0'] = _layer.style_dim
_layer = film_layer.FiLMLayer(in_dim=_out_dim,
out_dim=_out_dim,
style_dim=style_dim)
self.network.append(_layer)
self.style_dim_dict[f'{name_prefix}_w{i}_1'] = _layer.style_dim
to_rgb = inr_network.ToRGB(in_dim=_out_dim, dim_rgb=3)
self.to_rbgs.append(to_rgb)
self.tanh = nn.Sequential(
# nn.Linear(hidden_dim, rgb_dim),
nn.Tanh()
)
# self.to_rbg.apply(frequency_init(25))
torch_utils.print_number_params(
{
'network': self.network,
'to_rbgs': self.to_rbgs,
'inr_net': self
})
logging.getLogger('tl').info(self)
pass
def forward(self,
input,
style_dict,
**kwargs):
"""
:param input: points xyz, (b, num_points, 3)
:param style_dict:
:param ray_directions: (b, num_points, 3)
:param kwargs:
:return:
- out: (b, num_points, 4), rgb(3) + sigma(1)
"""
x = input
rgb = 0
for index in range(self.hidden_layers):
_layer = self.network[index * 2]
style = style_dict[f'{self.name_prefix}_w{index}_0']
if global_cfg.tl_debug:
VerboseModel.forward_verbose(_layer,
inputs_args=(x, style),
name_prefix=f"{self.name_prefix}.network.{index}.0.")
x = _layer(x, style)
_layer = self.network[index * 2 + 1]
style = style_dict[f'{self.name_prefix}_w{index}_1']
if global_cfg.tl_debug:
VerboseModel.forward_verbose(_layer,
inputs_args=(x, style),
name_prefix=f"{self.name_prefix}.network.{index}.1.")
x = _layer(x, style)
if global_cfg.tl_debug:
VerboseModel.forward_verbose(self.to_rbgs[index],
inputs_args=(x, rgb),
name_prefix=f'to_rgb.{index}')
rgb = self.to_rbgs[index](x, skip=rgb)
# if global_cfg.tl_debug:
# VerboseModel.forward_verbose(self.to_rbg,
# inputs_args=(x, ),
# name_prefix='to_rgb.')
# out = self.to_rbg(x)
if global_cfg.tl_debug:
VerboseModel.forward_verbose(self.tanh,
inputs_args=(rgb, ),
name_prefix='tanh.')
out = self.tanh(rgb)
return out
class ModSinLayer(nn.Module):
def __repr__(self): return f"{self.__class__.__name__}({self.repr})"
def __init__(self,
in_dim,
use_style_fc=False,
style_dim=None,
which_linear=nn.Linear,
spectral_norm=False,
eps=1e-5,
freq=1,
phase=0,
**kwargs):
super(ModSinLayer, self).__init__()
self.repr = f"in_dim={in_dim}, use_style_fc={use_style_fc}, style_dim={style_dim}, " \
f"freq={freq}, phase={phase}"
self.in_dim = in_dim
self.use_style_fc = use_style_fc
self.style_dim = style_dim
self.freq = freq
self.phase = phase
self.spectral_norm = spectral_norm
# Prepare gain and bias layers
if use_style_fc:
self.gain_fc = which_linear(style_dim, in_dim)
self.bias_fc = which_linear(style_dim, in_dim)
if spectral_norm:
self.gain_fc = nn.utils.spectral_norm(self.gain_fc)
self.bias_fc = nn.utils.spectral_norm(self.bias_fc)
else:
self.style_dim = in_dim * 2
self.eps = eps
self.lrelu = nn.LeakyReLU(0.2, inplace=True)
# self.register_buffer('stored_mean', torch.zeros(output_size))
# self.register_buffer('stored_var', torch.ones(output_size))
pass
def forward(self,
x,
style):
"""
Calculate class-conditional gains and biases.
:param x: (b, c) or (b, n, c)
:param style: (b, c)
:return:
"""
assert style.shape[-1] == self.style_dim
if self.use_style_fc:
gain = self.gain_fc(style) + 1.
bias = self.bias_fc(style)
else:
style = rearrange(style, "b (n c) -> b n c", n=2)
gain, bias = style.unbind(dim=1)
gain = gain + 1.
if x.dim() == 3:
gain = rearrange(gain, "b c -> b 1 c")
bias = rearrange(bias, "b c -> b 1 c")
elif x.dim() == 2:
pass
else:
assert 0
# x = torch.sin(self.freq * x + self.phase)
# out = x * gain + bias
x = x * torch.rsqrt(torch.mean(x ** 2, dim=-1, keepdim=True) + 1e-8)
x = x * gain + bias
out = self.lrelu(x)
return out
class ModSinLayer_NoBias(nn.Module):
def __repr__(self): return f"{self.__class__.__name__}({self.repr})"
def __init__(self,
in_dim,
use_style_fc=False,
style_dim=None,
which_linear=nn.Linear,
spectral_norm=False,
eps=1e-5,
freq=1,
phase=0,
**kwargs):
super(ModSinLayer_NoBias, self).__init__()
self.repr = f"in_dim={in_dim}, use_style_fc={use_style_fc}, style_dim={style_dim}, " \
f"freq={freq}, phase={phase}"
self.in_dim = in_dim
self.use_style_fc = use_style_fc
self.style_dim = style_dim
self.freq = freq
self.phase = phase
self.spectral_norm = spectral_norm
# Prepare gain and bias layers
if use_style_fc:
self.gain_fc = which_linear(style_dim, in_dim)
# self.bias_fc = which_linear(style_dim, in_dim)
if spectral_norm:
self.gain_fc = nn.utils.spectral_norm(self.gain_fc)
# self.bias_fc = nn.utils.spectral_norm(self.bias_fc)
else:
self.style_dim = in_dim * 2
self.eps = eps
pass
def forward(self,
x,
style):
"""
Calculate class-conditional gains and biases.
:param x: (b, c) or (b, n, c)
:param style: (b, c)
:return:
"""
assert style.shape[-1] == self.style_dim
if self.use_style_fc:
gain = self.gain_fc(style) + 1.
else:
style = rearrange(style, "b (n c) -> b n c", n=2)
gain, bias = style.unbind(dim=1)
gain = gain + 1.
if x.dim() == 3:
gain = rearrange(gain, "b c -> b 1 c")
elif x.dim() == 2:
pass
else:
assert 0
x = torch.sin(self.freq * x + self.phase)
# out = x * gain + bias
out = x * gain
return out
class SinBlock(nn.Module):
def __init__(self,
in_dim,
out_dim,
style_dim,
name_prefix,
):
super().__init__()
self.in_dim = in_dim
self.out_dim = out_dim
self.style_dim = style_dim
self.name_prefix = name_prefix
self.style_dim_dict = {}
# self.mod1 = mod_conv_fc.Modulated_FC_Conv(in_channel=in_dim,
# out_channel=out_dim,
# style_dim=style_dim,
# use_style_fc=True,
# scale=1.,
# # scale=None,
# )
self.mod1 = mod_conv_fc.SinStyleMod(in_channel=in_dim,
out_channel=out_dim,
style_dim=style_dim,
use_style_fc=True,
)
self.style_dim_dict[f'{name_prefix}_0'] = self.mod1.style_dim
self.act1 = nn.LeakyReLU(0.2, inplace=True)
# self.mod2 = mod_conv_fc.Modulated_FC_Conv(in_channel=out_dim,
# out_channel=out_dim,
# style_dim=style_dim,
# use_style_fc=True,
# scale=1.,
# # scale=None,
# )
self.mod2 = mod_conv_fc.SinStyleMod(in_channel=out_dim,
out_channel=out_dim,
style_dim=style_dim,
use_style_fc=True,
)
self.style_dim_dict[f'{name_prefix}_1'] = self.mod2.style_dim
self.act2 = nn.LeakyReLU(0.2, inplace=True)
# self.linear1 = nn.Linear(in_dim, out_dim)
# self.mod1 = ModSinLayer(in_dim=out_dim, use_style_fc=True, style_dim=style_dim)
# self.style_dim_dict[f'{name_prefix}_0'] = self.mod1.style_dim
# self.linear2 = nn.Linear(out_dim, out_dim)
# self.mod2 = ModSinLayer(in_dim=out_dim, use_style_fc=True, style_dim=style_dim)
# self.style_dim_dict[f'{name_prefix}_1'] = self.mod2.style_dim
self.skip = SkipLayer()
pass
def forward(self,
x,
style_dict,
skip=False):
x_orig = x
style = style_dict[f'{self.name_prefix}_0']
x = self.mod1(x, style)
x = self.act1(x)
style = style_dict[f'{self.name_prefix}_1']
x = self.mod2(x, style)
out = self.act2(x)
# x = self.linear1(x)
# style = style_dict[f'{self.name_prefix}_0']
# x = self.mod1(x, style)
# x = self.linear2(x)
# style = style_dict[f'{self.name_prefix}_1']
# out = self.mod2(x, style)
if skip and out.shape[-1] == x_orig.shape[-1]:
# out = (out + x_orig) / 1.41421
out = self.skip(out, x_orig)
return out
def __repr__(self):
repr = f"{self.__class__.__name__}(in_dim={self.in_dim}, " \
f"out_dim={self.out_dim}, " \
f"style_dim={self.style_dim})"
return repr
class ToRGB(nn.Module):
def __init__(self,
in_dim,
dim_rgb=3,
use_equal_fc=False):
super().__init__()
self.in_dim = in_dim
self.dim_rgb = dim_rgb
if use_equal_fc:
self.linear = mod_conv_fc.EqualLinear(in_dim, dim_rgb, scale=1.)
else:
self.linear = nn.Linear(in_dim, dim_rgb)
pass
def forward(self,
input,
skip=None):
out = self.linear(input)
if skip is not None:
out = out + skip
return out
@MODEL_REGISTRY.register(name_prefix=__name__)
# class Generator_Diffcam(GeneratorNerfINR_base):
class Generator_Diffcam(nn.Module):
def __repr__(self):
return tl2_utils.get_class_repr(self)
def __init__(self,
nerf_cfg,
mapping_shape_cfg,
mapping_app_cfg,
inr_cfg,
mapping_inr_cfg,
shape_block_end_index=None,
app_block_end_index=None,
inr_block_end_index=None,
device='cuda',
**kwargs):
super(Generator_Diffcam, self).__init__()
self.repr_str = tl2_utils.dict2string(dict_obj={
'nerf_cfg': nerf_cfg,
'mapping_shape_cfg': mapping_shape_cfg,
'mapping_app_cfg': mapping_app_cfg,
'inr_cfg': inr_cfg,
'mapping_inr_cfg': mapping_inr_cfg,
'shape_block_end_index': shape_block_end_index,
'app_block_end_index': app_block_end_index,
'inr_block_end_index': inr_block_end_index,
})
self.device = device
self.inr_block_end_index = inr_block_end_index
self.module_name_list = []
# nerf_net
self.nerf_net = nerf_net.NeRFNetwork_SIREN_skip(
shape_block_end_index=shape_block_end_index,
app_block_end_index=app_block_end_index,
**nerf_cfg)
self.module_name_list.append('nerf_net')
# mapping shape
self.mapping_shape = multi_head_mapping.MultiHeadMappingNetwork(**{
**mapping_shape_cfg,
'head_dim_dict': self.nerf_net.style_dim_dict_shape
})
self.module_name_list.append('mapping_shape')
# mapping appearance
self.mapping_app = multi_head_mapping.MultiHeadMappingNetwork(**{
**mapping_app_cfg,
'head_dim_dict': self.nerf_net.style_dim_dict_app
})
self.module_name_list.append('mapping_app')
_in_dim = nerf_cfg.app_net_cfg.out_dim
# inr_net
self.inr_net = cips_net.CIPSNet(**{
**inr_cfg,
"input_dim": _in_dim,
'add_out_layer': True,
})
self.module_name_list.append('inr_net')
self.mapping_inr = multi_head_mapping.MultiHeadMappingNetwork(**{
**mapping_inr_cfg,
'head_dim_dict': self.inr_net.style_dim_dict
})
self.module_name_list.append('mapping_inr')
self.aux_to_rbg = nn.Sequential(
nn.Linear(_in_dim, 3),
nn.Tanh()
)
self.aux_to_rbg.apply(nerf_network.frequency_init(25))
self.module_name_list.append('aux_to_rbg')
logger = logging.getLogger('tl')
models_dict = {}
for name in self.module_name_list:
models_dict[name] = getattr(self, name)
models_dict['G'] = self
torch_utils.print_number_params(models_dict=models_dict, logger=logger)
logger.info(self)
pass
def forward(self,
zs,
rays_o,
rays_d,
nerf_kwargs={},
psi=1,
return_aux_img=False,
grad_points=None,
forward_points=None, # disable gradients
**kwargs):
"""
Generates images from a noise vector, rendering parameters, and camera distribution.
Uses the hierarchical sampling scheme described in NeRF.
:param zs: {k: (b, z_dim), ...}
:param rays_o: (b, h, w, 3) in world space
:param rays_d: (b, h, w, 3) in world space
:return:
- pixels: (b, 3, h, w)
- pitch_yaw: (b, 2)
"""
# mapping network
style_dict = self.mapping_network(**zs)
if psi < 1:
avg_styles = self.generate_avg_frequencies(device=self.device)
style_dict = self.get_truncated_freq_phase(
raw_style_dict=style_dict, avg_style_dict=avg_styles, raw_lambda=psi)
b, h, w, c = rays_o.shape
rays_o = rearrange(rays_o, "b h w c -> b (h w) c")
rays_d = rearrange(rays_d, "b h w c -> b (h w) c")
if grad_points is not None and grad_points < h * w:
imgs, ret_maps = self.part_grad_forward(
rays_o=rays_o,
rays_d=rays_d,
style_dict=style_dict,
nerf_kwargs=nerf_kwargs,
return_aux_img=return_aux_img,
grad_points=grad_points)
else:
imgs, ret_maps = self.whole_grad_forward(
rays_o=rays_o,
rays_d=rays_d,
style_dict=style_dict,
nerf_kwargs=nerf_kwargs,
return_aux_img=return_aux_img,
forward_points=forward_points)
imgs = rearrange(imgs, "b (h w) c -> b c h w", h=h, w=w)
ret_imgs = {}
for name, v_map in ret_maps.items():
if v_map.dim() == 3:
v_map = rearrange(v_map, "b (h w) c -> b c h w", h=h, w=w)
elif v_map.dim() == 2:
v_map = rearrange(v_map, "b (h w) -> b h w", h=h, w=w)
ret_imgs[name] = v_map
return imgs, ret_imgs
def get_rays_axis_angle(self,
R,
t,
fx,
fy,
H: int,
W: int,
N_rays: int = -1):
"""
:param R: (b, 3)
:param t: (b, 3)
:param fx:
:param fy:
:param H:
:param W:
:param N_rays:
:return
- rays_o: (b, H, W, 3)
- rays_d: (b, H, W, 3)
- select_inds: (b, H, W)
"""
rays_o, rays_d, select_inds = cam_params.get_rays(
rot=R,
trans=t,
focal_x=fx,
focal_y=fy,
H=H,
W=W,
N_rays=N_rays,
flatten=False)
return rays_o, rays_d, select_inds
def get_batch_style_dict(self, b, style_dict):
ret_style_dict = {}
for name, style in style_dict.items():
ret_style_dict[name] = style[[b]]
return ret_style_dict
def whole_grad_forward(self,
rays_o,
rays_d,
style_dict,
nerf_kwargs,
return_aux_img=True,
forward_points=None,
**kwargs):
if forward_points is not None and forward_points < rays_o.shape[1]: # no gradients
# stage forward
with torch.no_grad():
batch_size = rays_o.shape[0]
num_points = rays_o.shape[1]
near = nerf_kwargs['near']
far = nerf_kwargs['far']
N_samples = nerf_kwargs['N_samples']
perturb = self.training
z_vals, points = volume_rendering.ray_sample_points(rays_o=rays_o,
rays_d=rays_d,
near=near,
far=far,
N_samples=N_samples,
perturb=perturb)
batch_image_ddict = collections.defaultdict(list)
for b in range(batch_size):
image_ddict = collections.defaultdict(list)
head = 0
while head < num_points:
tail = head + forward_points
cur_style_dict = self.get_batch_style_dict(b=b, style_dict=style_dict)
cur_inr_img, cur_ret_maps = self.points_forward(
rays_o=rays_o[[b], head:tail], # (b, hxw, 3)
rays_d=rays_d[[b], head:tail], # (b, hxw, 3)
points=points[[b], head:tail], # (b, hxw, Nsamples, 3)
z_vals=z_vals[[b], head:tail], # (b, hxw, Nsamples)
style_dict=cur_style_dict,
nerf_kwargs=nerf_kwargs,
return_aux_img=return_aux_img)
image_ddict['inr_img'].append(cur_inr_img)
for k, v in cur_ret_maps.items():
image_ddict[k].append(v)
head += forward_points
for k, v in image_ddict.items():
one_image = torch.cat(v, dim=1)
batch_image_ddict[k].append(one_image)
ret_maps = {}
for k, v in batch_image_ddict.items():
ret_maps[k] = torch.cat(v, dim=0)
imgs = ret_maps.pop('inr_img')
else:
near = nerf_kwargs['near']
far = nerf_kwargs['far']
N_samples = nerf_kwargs['N_samples']
perturb = self.training
z_vals, points = volume_rendering.ray_sample_points(rays_o=rays_o,
rays_d=rays_d,
near=near,
far=far,
N_samples=N_samples,
perturb=perturb)
# transformed_points = rearrange(transformed_points, "b (h w s) c -> b (h w) s c", h=img_size, s=num_steps)
# transformed_ray_directions_expanded = rearrange(transformed_ray_directions_expanded,
# "b (h w s) c -> b (h w) s c", h=img_size, s=num_steps)
imgs, ret_maps = self.points_forward(
rays_o=rays_o,
rays_d=rays_d,
points=points,
z_vals=z_vals,
style_dict=style_dict,
nerf_kwargs=nerf_kwargs,
return_aux_img=return_aux_img)
return imgs, ret_maps
def part_grad_forward(self,
rays_o,
rays_d,
style_dict,
nerf_kwargs,
return_aux_img,
grad_points):
near = nerf_kwargs['near']
far = nerf_kwargs['far']
N_samples = nerf_kwargs['N_samples']
perturb = self.training
# z_vals: (b, hxw, Nsamples), points: (b, hxw, Nsamples, 3)
z_vals, points = volume_rendering.ray_sample_points(rays_o=rays_o, # (b, hxw, 3)
rays_d=rays_d, # (b, hxw, 3)
near=near,
far=far,
N_samples=N_samples,
perturb=perturb)
# transformed_points = rearrange(transformed_points, "b (h w s) c -> b (h w) s c", h=img_size, s=num_steps)
# transformed_ray_directions_expanded = rearrange(transformed_ray_directions_expanded,
# "b (h w s) c -> b (h w) s c", h=img_size, s=num_steps)
batch_size = rays_o.shape[0]
num_points = rays_o.shape[1]
device = self.device
assert num_points > grad_points
idx_grad, idx_no_grad = torch_utils.batch_random_split_indices(bs=batch_size,
num_points=num_points,
grad_points=grad_points,
device=device)
# rand_idx = torch.randperm(num_points, device=device)
# idx_grad = rand_idx[:grad_points]
# idx_no_grad = rand_idx[grad_points:]
inr_img_grad, ret_maps_grad = self.points_forward(
rays_o=rays_o,
rays_d=rays_d,
points=points,
z_vals=z_vals,
style_dict=style_dict,
nerf_kwargs=nerf_kwargs,
return_aux_img=return_aux_img,
idx_grad=idx_grad)
with torch.no_grad():
inr_img_no_grad, ret_maps_no_grad = self.points_forward(
rays_o=rays_o,
rays_d=rays_d,
points=points,
z_vals=z_vals,
style_dict=style_dict,
nerf_kwargs=nerf_kwargs,
return_aux_img=return_aux_img,
idx_grad=idx_no_grad)
imgs = comm_utils.batch_scatter_points(idx_grad=idx_grad,
points_grad=inr_img_grad,
idx_no_grad=idx_no_grad,
points_no_grad=inr_img_no_grad,
num_points=num_points)
ret_maps = {}
for k in ret_maps_grad.keys():
comp_map = comm_utils.batch_scatter_points(idx_grad=idx_grad,
points_grad=ret_maps_grad[k],
idx_no_grad=idx_no_grad,
points_no_grad=ret_maps_no_grad[k],
num_points=num_points)
ret_maps[k] = comp_map
return imgs, ret_maps
def points_forward(self,
rays_o,
rays_d,
points,
z_vals,
style_dict,
nerf_kwargs,
return_aux_img,
idx_grad=None,
**kwargs):
"""
:param rays_o: (b, hxw, 3)
:param rays_d: (b, hxw, 3)
:param points: (b, hxw, Nsamples, 3)
:param z_vals: (b, hxw, Nsamples)
:param style_dict:
:param nerf_kwargs:
:param return_aux_img:
:param idx_grad: (b, N_grad, )
:param kwargs:
:return:
"""
device = points.device
viewdirs = volume_rendering.get_viewdirs(rays_d=rays_d)
# viewdirs = viewdirs[..., None, :].expand_as(points)
N_samples = nerf_kwargs['N_samples']
if idx_grad is not None:
rays_o = comm_utils.batch_gather_points(points=rays_o, idx_grad=idx_grad)
rays_d = comm_utils.batch_gather_points(points=rays_d, idx_grad=idx_grad)
points = comm_utils.batch_gather_points(points=points, idx_grad=idx_grad)
z_vals = comm_utils.batch_gather_points(points=z_vals, idx_grad=idx_grad)
points = rearrange(points, "b Nrays Nsamples c -> b (Nrays Nsamples) c")
coarse_viewdirs = repeat(viewdirs, "b Nrays c -> b (Nrays Nsamples) c", Nsamples=N_samples)
# Model prediction on course points
coarse_output = self.nerf_net(
x=points, # b (Nrays Nsamples) c
ray_directions=coarse_viewdirs, # b (Nrays Nsamples) c
style_dict=style_dict)
coarse_output = rearrange(
coarse_output, "b (Nrays Nsamples) rgb_sigma -> b Nrays Nsamples rgb_sigma", Nsamples=N_samples)
# Re-sample fine points alont camera rays, as described in NeRF
if nerf_kwargs['N_importance'] > 0:
with torch.no_grad():
raw_sigma = coarse_output[..., -1]
perturb = self.training
fine_z_vals, fine_points = volume_rendering.get_fine_points(
z_vals=z_vals,
rays_o=rays_o,
rays_d=rays_d,
raw_sigma=raw_sigma,
N_importance=nerf_kwargs['N_importance'],
perturb=perturb,
raw_noise_std=nerf_kwargs['raw_noise_std'],
eps=nerf_kwargs['eps'])
# Model prediction on re-sampled find points
fine_points = rearrange(fine_points, "b Nrays Nsamples c -> b (Nrays Nsamples) c")
fine_viewdirs = repeat(viewdirs, "b Nrays c -> b (Nrays Nsamples) c", Nsamples=nerf_kwargs['N_importance'])
fine_output = self.nerf_net(
x=fine_points, # b (Nrays Nsamples) c
ray_directions=fine_viewdirs, # b (Nrays Nsamples) c
style_dict=style_dict)
fine_output = rearrange(
fine_output, "b (Nrays Nsamples) rgb_sigma -> b Nrays Nsamples rgb_sigma", Nsamples=nerf_kwargs['N_importance'])
# Combine course and fine points
DIM_SAMPLES = 2
all_z_vals = torch.cat([fine_z_vals, z_vals], dim=DIM_SAMPLES) # (b, N_rays, N_samples)
_, indices = torch.sort(all_z_vals, dim=DIM_SAMPLES) # (b, N_rays, N_samples)
# gather z_vals
all_z_vals = torch.gather(all_z_vals, DIM_SAMPLES, indices) # (b, N_rays, N_samples)
# (b, N_rays, N_samples, rgb_sigma)
all_outputs = torch.cat([fine_output, coarse_output], dim=DIM_SAMPLES)
view_shape = [*indices.shape, *(len(all_outputs.shape) - len(indices.shape)) * [1]]
all_outputs = torch.gather(all_outputs, DIM_SAMPLES, indices.view(view_shape).expand_as(all_outputs))
else:
all_outputs = coarse_output
all_z_vals = z_vals
# Create images with NeRF
all_raw_rgb = all_outputs[..., :-1]
all_raw_sigma = all_outputs[..., -1]
pixels_fea, ret_maps = volume_rendering.ray_integration(raw_rgb=all_raw_rgb,
raw_sigma=all_raw_sigma,
z_vals=all_z_vals,
rays_d=rays_d,
raw_noise_std=nerf_kwargs['raw_noise_std'],
eps=nerf_kwargs['eps'])
# inr_net
inr_img = self.inr_net(pixels_fea, style_dict, block_end_index=self.inr_block_end_index)
if return_aux_img:
# aux rgb_branch
aux_img = self.aux_to_rbg(pixels_fea)
ret_maps['aux_img'] = aux_img
return inr_img, ret_maps
def z_sampler(self,
shape,
device,
dist='gaussian'):
if dist == 'gaussian':
z = torch.randn(shape, device=device)
elif dist == 'uniform':
z = torch.rand(shape, device=device) * 2 - 1
return z
def get_zs(self,
b,
batch_split=1):
z_shape = self.z_sampler(shape=(b, self.mapping_shape.z_dim), device=self.device)
z_app = self.z_sampler(shape=(b, self.mapping_app.z_dim), device=self.device)
z_inr = self.z_sampler(shape=(b, self.mapping_inr.z_dim), device=self.device)
if batch_split > 1:
zs_list = []
z_shape_list = z_shape.split(b // batch_split)
z_app_list = z_app.split(b // batch_split)
z_inr_list = z_inr.split(b // batch_split)
for z_shape_, z_app_, z_inr_ in zip(z_shape_list, z_app_list, z_inr_list):
zs_ = {
'z_shape': z_shape_,
'z_app': z_app_,
'z_inr': z_inr_,
}
zs_list.append(zs_)
return zs_list
else:
zs = {
'z_shape': z_shape,
'z_app': z_app,
'z_inr': z_inr,
}
return zs
def mapping_network(self,
z_shape,
z_app,
z_inr):
if global_cfg.tl_debug:
VerboseModel.forward_verbose(self.mapping_shape,
inputs_args=(z_shape,),
submodels=['base_net'],
name_prefix='mapping_shape.')
VerboseModel.forward_verbose(self.mapping_app,
inputs_args=(z_app,),
submodels=['base_net'],
name_prefix='mapping_app.')
VerboseModel.forward_verbose(self.mapping_inr,
inputs_args=(z_inr,),
submodels=['base_net', ],
input_padding=50,
name_prefix='mapping_inr.')
style_dict = {}
style_dict.update(self.mapping_shape(z_shape))
style_dict.update(self.mapping_app(z_app))
style_dict.update(self.mapping_inr(z_inr))
return style_dict
def get_truncated_freq_phase(self,
raw_style_dict,
avg_style_dict,
raw_lambda):
truncated_style_dict = {}
for name, avg_style in avg_style_dict.items():
raw_style = raw_style_dict[name]
truncated_style = avg_style + raw_lambda * (raw_style - avg_style)
truncated_style_dict[name] = truncated_style
return truncated_style_dict
def generate_avg_frequencies(self,
num_samples=10000,
device='cuda'):
"""Calculates average frequencies and phase shifts"""
# z = torch.randn((num_samples, self.z_dim), device=device)
zs = self.get_zs(num_samples)
with torch.no_grad():
style_dict = self.mapping_network(**zs)
avg_styles = {}
for name, style in style_dict.items():
avg_styles[name] = style.mean(0, keepdim=True)
# self.avg_styles = avg_styles
return avg_styles
def staged_forward(self, *args, **kwargs):
raise NotImplementedError
def set_device(self, device):
pass
def forward_camera_pos_and_lookup(self,
zs,
img_size,
fov,
ray_start,
ray_end,
num_steps,
h_stddev,
v_stddev,
h_mean,
v_mean,
hierarchical_sample,
camera_pos,
camera_lookup,
psi=1,
sample_dist=None,
lock_view_dependence=False,
clamp_mode='relu',
nerf_noise=0.,
white_back=False,
last_back=False,
return_aux_img=False,
grad_points=None,
forward_points=None,
**kwargs):
"""
Generates images from a noise vector, rendering parameters, and camera distribution.
Uses the hierarchical sampling scheme described in NeRF.
:param z: (b, z_dim)
:param img_size:
:param fov: face: 12
:param ray_start: face: 0.88
:param ray_end: face: 1.12
:param num_steps: face: 12
:param h_stddev: face: 0.3
:param v_stddev: face: 0.155
:param h_mean: face: pi/2
:param v_mean: face: pi/2
:param hierarchical_sample: face: true
:param camera_pos: (b, 3)
:param camera_lookup: (b, 3)
:param psi: [0, 1]
:param sample_dist: mode for sample_camera_positions, face: 'gaussian'
:param lock_view_dependence: face: false
:param clamp_mode: face: 'relu'
:param nerf_noise:
:param last_back: face: false
:param white_back: face: false
:param kwargs:
:return:
- pixels: (b, 3, h, w)
- pitch_yaw: (b, 2)
"""
# mapping network
if global_cfg.tl_debug:
VerboseModel.forward_verbose(self.mapping_network_nerf,
inputs_args=(zs['z_nerf'],),
submodels=['base_net'],
name_prefix='mapping_nerf.')
VerboseModel.forward_verbose(self.mapping_network_inr,
inputs_args=(zs['z_inr'],),
submodels=['base_net', ],
input_padding=50,
name_prefix='mapping_inr.')
style_dict = self.mapping_network(**zs)
if psi < 1:
avg_styles = self.generate_avg_frequencies(device=self.device)
style_dict = self.get_truncated_freq_phase(
raw_style_dict=style_dict, avg_style_dict=avg_styles, raw_lambda=psi)
if grad_points is not None and grad_points < img_size ** 2:
imgs, pitch_yaw = self.part_grad_forward(
style_dict=style_dict,
img_size=img_size,
fov=fov,
ray_start=ray_start,
ray_end=ray_end,
num_steps=num_steps,
h_stddev=h_stddev,
v_stddev=v_stddev,
h_mean=h_mean,
v_mean=v_mean,
hierarchical_sample=hierarchical_sample,
sample_dist=sample_dist,
lock_view_dependence=lock_view_dependence,
clamp_mode=clamp_mode,
nerf_noise=nerf_noise,
white_back=white_back,
last_back=last_back,
return_aux_img=return_aux_img,
grad_points=grad_points,
camera_pos=camera_pos,
camera_lookup=camera_lookup,
)
return imgs, pitch_yaw
else:
imgs, pitch_yaw = self.whole_grad_forward(
style_dict=style_dict,
img_size=img_size,
fov=fov,
ray_start=ray_start,
ray_end=ray_end,
num_steps=num_steps,
h_stddev=h_stddev,
v_stddev=v_stddev,
h_mean=h_mean,
v_mean=v_mean,
hierarchical_sample=hierarchical_sample,
sample_dist=sample_dist,
lock_view_dependence=lock_view_dependence,
clamp_mode=clamp_mode,
nerf_noise=nerf_noise,
white_back=white_back,
last_back=last_back,
return_aux_img=return_aux_img,
forward_points=forward_points,
camera_pos=camera_pos,
camera_lookup=camera_lookup,
)
return imgs, pitch_yaw
@MODEL_REGISTRY.register(name_prefix=__name__)
class GeneratorNerfINR_freeze_NeRF(Generator_Diffcam):
def load_nerf_ema(self, G_ema):
ret = self.nerf_net.load_state_dict(G_ema.nerf_net.state_dict())
ret = self.mapping_network_nerf.load_state_dict(G_ema.mapping_network_nerf.state_dict())
ret = self.aux_to_rbg.load_state_dict(G_ema.aux_to_rbg.state_dict())
ret = self.mapping_network_inr.load_state_dict(G_ema.mapping_network_inr.state_dict())
ret = self.nerf_rgb_mapping.load_state_dict(G_ema.nerf_rgb_mapping.state_dict())
pass
def mapping_network(self,
z_nerf,
z_inr):
style_dict = {}
with torch.no_grad():
style_dict.update(self.mapping_network_nerf(z_nerf))
style_dict.update(self.mapping_network_inr(z_inr))
style_dict['nerf_rgb'] = self.nerf_rgb_mapping(style_dict['nerf_rgb'])
return style_dict
def points_forward(self,
style_dict,
transformed_points,
transformed_ray_directions_expanded,
num_steps,
hierarchical_sample,
z_vals,
clamp_mode,
nerf_noise,
transformed_ray_origins,
transformed_ray_directions,
white_back,
last_back,
return_aux_img,
idx_grad=None,
):
"""
:param style_dict:
:param transformed_points: (b, n, s, 3)
:param transformed_ray_directions_expanded: (b, n, s, 3)
:param num_steps: sampled points along a ray
:param hierarchical_sample:
:param z_vals: (b, n, s, 1)
:param clamp_mode: 'relu'
:param nerf_noise:
:param transformed_ray_origins: (b, n, 3)
:param transformed_ray_directions: (b, n, 3)
:param white_back:
:param last_back:
:return:
"""
device = transformed_points.device
if idx_grad is not None:
transformed_points = comm_utils.gather_points(points=transformed_points, idx_grad=idx_grad)
transformed_ray_directions_expanded = comm_utils.gather_points(
points=transformed_ray_directions_expanded, idx_grad=idx_grad)
z_vals = comm_utils.gather_points(points=z_vals, idx_grad=idx_grad)
transformed_ray_origins = comm_utils.gather_points(points=transformed_ray_origins, idx_grad=idx_grad)
transformed_ray_directions = comm_utils.gather_points(points=transformed_ray_directions, idx_grad=idx_grad)
transformed_points = rearrange(transformed_points, "b n s c -> b (n s) c")
transformed_ray_directions_expanded = rearrange(transformed_ray_directions_expanded, "b n s c -> b (n s) c")
# Model prediction on course points
with torch.no_grad():
coarse_output = self.nerf_net(
x=transformed_points, # (b, n x s, 3)
style_dict=style_dict,
ray_directions=transformed_ray_directions_expanded,
)
coarse_output = rearrange(coarse_output, "b (n s) rgb_sigma -> b n s rgb_sigma", s=num_steps)
# Re-sample fine points alont camera rays, as described in NeRF
if hierarchical_sample:
fine_points, fine_z_vals = self.get_fine_points_and_direction(
coarse_output=coarse_output,
z_vals=z_vals,
dim_rgb=self.nerf_net.rgb_dim,
clamp_mode=clamp_mode,
nerf_noise=nerf_noise,
num_steps=num_steps,
transformed_ray_origins=transformed_ray_origins,
transformed_ray_directions=transformed_ray_directions
)
# Model prediction on re-sampled find points
with torch.no_grad():
fine_output = self.nerf_net(
x=fine_points, # (b, n x s, 3)
style_dict=style_dict,
ray_directions=transformed_ray_directions_expanded, # (b, n x s, 3)
)
fine_output = rearrange(fine_output, "b (n s) rgb_sigma -> b n s rgb_sigma", s=num_steps)
# Combine course and fine points
all_outputs = torch.cat([fine_output, coarse_output], dim=-2) # (b, n, s, dim_rgb_sigma)
all_z_vals = torch.cat([fine_z_vals, z_vals], dim=-2) # (b, n, s, 1)
_, indices = torch.sort(all_z_vals, dim=-2) # (b, n, s, 1)
all_z_vals = torch.gather(all_z_vals, -2, indices) # (b, n, s, 1)
# (b, n, s, dim_rgb_sigma)
all_outputs = torch.gather(all_outputs, -2, indices.expand(-1, -1, -1, all_outputs.shape[-1]))
else:
all_outputs = coarse_output
all_z_vals = z_vals
# Create images with NeRF
pixels_fea, depth, weights = pigan_utils.fancy_integration(
rgb_sigma=all_outputs,
z_vals=all_z_vals,
device=device,
dim_rgb=self.nerf_net.rgb_dim,
white_back=white_back,
last_back=last_back,
clamp_mode=clamp_mode,
noise_std=nerf_noise)
inr_img = self.inr_net(pixels_fea, style_dict)
if return_aux_img:
# aux rgb_branch
with torch.no_grad():
aux_img = self.aux_to_rbg(pixels_fea)
else:
aux_img = None
return inr_img, aux_img
| 32.668826 | 120 | 0.571721 | from itertools import chain
import math
import logging
import collections
from collections import OrderedDict
import tqdm
import random
import time
from einops import rearrange, repeat
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.cuda.amp import autocast
from tl2.proj.fvcore import MODEL_REGISTRY, build_model
from tl2.launch.launch_utils import global_cfg
from tl2.proj.pytorch.pytorch_hook import VerboseModel
from tl2.proj.pytorch import torch_utils
from tl2.proj.pytorch import torch_utils, init_func
from tl2 import tl2_utils
from tl2.proj.pytorch.examples.nerf import cam_params
from tl2.proj.pytorch.examples.nerf import volume_rendering
from tl2.proj.pytorch.examples.networks import nerf_net
from tl2.proj.pytorch.examples.networks import multi_head_mapping
from tl2.proj.pytorch.examples.networks import cips_net
from exp.pigan import pigan_utils
from exp.dev.nerf_inr.models.generator_nerf_inr import INRNetwork
from exp.dev.nerf_inr.models.generator_nerf_inr import GeneratorNerfINR as GeneratorNerfINR_base
from exp.comm import comm_utils
from exp.comm.models import nerf_network
from exp.comm.models import inr_network
from exp.comm.models import film_layer
from exp.comm.models import mod_conv_fc
class SkipLayer(nn.Module):
def __init__(self, ):
super(SkipLayer, self).__init__()
def forward(self, x0, x1):
out = (x0 + x1)
return out
class SinAct(nn.Module):
def __init__(self, ):
super(SinAct, self).__init__()
def forward(self, x):
return torch.sin(x)
class LinearSinAct(nn.Module):
def __init__(self,
in_features,
out_features):
super(LinearSinAct, self).__init__()
self.linear = nn.Linear(in_features=in_features, out_features=out_features)
self.sin = SinAct()
pass
def forward(self, x, *args, **kwargs):
x = self.linear(x)
x = self.sin(x)
return x
class FiLMLayer(nn.Module):
def __init__(self,
in_dim,
out_dim,
style_dim,
use_style_fc=True,
which_linear=nn.Linear,
**kwargs):
super(FiLMLayer, self).__init__()
self.in_dim = in_dim
self.out_dim = out_dim
self.style_dim = style_dim
self.use_style_fc = use_style_fc
self.linear = which_linear(in_dim, out_dim)
self.gain_scale = nn.Identity()
if use_style_fc:
self.gain_fc = which_linear(style_dim, out_dim)
self.bias_fc = which_linear(style_dim, out_dim)
else:
self.style_dim = out_dim * 2
self.sin = SinAct()
self.lrelu = nn.LeakyReLU(0.2, inplace=True)
pass
def forward(self,
x,
style):
if self.use_style_fc:
gain = self.gain_fc(style)
gain = self.gain_scale(gain)
bias = self.bias_fc(style)
else:
style = rearrange(style, "b (n c) -> b n c", n=2)
gain, bias = style.unbind(dim=1)
gain = self.gain_scale(gain)
if x.dim() == 3:
gain = rearrange(gain, "b c -> b 1 c")
bias = rearrange(bias, "b c -> b 1 c")
elif x.dim() == 2:
pass
else:
assert 0
x = self.linear(x)
x = x * torch.rsqrt(torch.mean(x ** 2, dim=-1, keepdim=True) + 1e-8)
out = self.lrelu((gain + 1.) * x + bias)
return out
def __repr__(self):
s = f'{self.__class__.__name__}(' \
f'in_dim={self.in_dim}, ' \
f'out_dim={self.out_dim}, ' \
f'style_dim={self.style_dim}, ' \
f'use_style_fc={self.use_style_fc}, ' \
f')'
return s
class INRNetwork_Skip(nn.Module):
def __repr__(self): return f"{self.__class__.__name__}({self.repr})"
def __init__(self,
input_dim,
style_dim,
hidden_layers,
dim_scale=1,
rgb_dim=3,
device=None,
name_prefix='inr',
**kwargs):
super().__init__()
self.repr = f"input_dim={input_dim}, " \
f"style_dim={style_dim}, " \
f"hidden_layers={hidden_layers}, " \
f"dim_scale={dim_scale}, "
self.device = device
self.rgb_dim = rgb_dim
self.hidden_layers = hidden_layers
self.name_prefix = name_prefix
self.channels = {
0: int(512 * dim_scale),
1: int(512 * dim_scale),
2: int(512 * dim_scale),
3: int(512 * dim_scale),
4: int(512 * dim_scale),
5: int(128 * dim_scale),
6: int(64 * dim_scale),
7: int(32 * dim_scale),
8: int(16 * dim_scale),
}
self.style_dim_dict = {}
_out_dim = input_dim
self.network = nn.ModuleList()
self.to_rbgs = nn.ModuleList()
for i in range(hidden_layers):
_in_dim = _out_dim
_out_dim = self.channels[i]
_layer = film_layer.FiLMLayer(in_dim=_in_dim,
out_dim=_out_dim,
style_dim=style_dim)
self.network.append(_layer)
self.style_dim_dict[f'{name_prefix}_w{i}_0'] = _layer.style_dim
_layer = film_layer.FiLMLayer(in_dim=_out_dim,
out_dim=_out_dim,
style_dim=style_dim)
self.network.append(_layer)
self.style_dim_dict[f'{name_prefix}_w{i}_1'] = _layer.style_dim
to_rgb = inr_network.ToRGB(in_dim=_out_dim, dim_rgb=3)
self.to_rbgs.append(to_rgb)
self.tanh = nn.Sequential(
nn.Tanh()
)
torch_utils.print_number_params(
{
'network': self.network,
'to_rbgs': self.to_rbgs,
'inr_net': self
})
logging.getLogger('tl').info(self)
pass
def forward(self,
input,
style_dict,
**kwargs):
x = input
rgb = 0
for index in range(self.hidden_layers):
_layer = self.network[index * 2]
style = style_dict[f'{self.name_prefix}_w{index}_0']
if global_cfg.tl_debug:
VerboseModel.forward_verbose(_layer,
inputs_args=(x, style),
name_prefix=f"{self.name_prefix}.network.{index}.0.")
x = _layer(x, style)
_layer = self.network[index * 2 + 1]
style = style_dict[f'{self.name_prefix}_w{index}_1']
if global_cfg.tl_debug:
VerboseModel.forward_verbose(_layer,
inputs_args=(x, style),
name_prefix=f"{self.name_prefix}.network.{index}.1.")
x = _layer(x, style)
if global_cfg.tl_debug:
VerboseModel.forward_verbose(self.to_rbgs[index],
inputs_args=(x, rgb),
name_prefix=f'to_rgb.{index}')
rgb = self.to_rbgs[index](x, skip=rgb)
if global_cfg.tl_debug:
VerboseModel.forward_verbose(self.tanh,
inputs_args=(rgb, ),
name_prefix='tanh.')
out = self.tanh(rgb)
return out
class ModSinLayer(nn.Module):
def __repr__(self): return f"{self.__class__.__name__}({self.repr})"
def __init__(self,
in_dim,
use_style_fc=False,
style_dim=None,
which_linear=nn.Linear,
spectral_norm=False,
eps=1e-5,
freq=1,
phase=0,
**kwargs):
super(ModSinLayer, self).__init__()
self.repr = f"in_dim={in_dim}, use_style_fc={use_style_fc}, style_dim={style_dim}, " \
f"freq={freq}, phase={phase}"
self.in_dim = in_dim
self.use_style_fc = use_style_fc
self.style_dim = style_dim
self.freq = freq
self.phase = phase
self.spectral_norm = spectral_norm
if use_style_fc:
self.gain_fc = which_linear(style_dim, in_dim)
self.bias_fc = which_linear(style_dim, in_dim)
if spectral_norm:
self.gain_fc = nn.utils.spectral_norm(self.gain_fc)
self.bias_fc = nn.utils.spectral_norm(self.bias_fc)
else:
self.style_dim = in_dim * 2
self.eps = eps
self.lrelu = nn.LeakyReLU(0.2, inplace=True)
pass
def forward(self,
x,
style):
assert style.shape[-1] == self.style_dim
if self.use_style_fc:
gain = self.gain_fc(style) + 1.
bias = self.bias_fc(style)
else:
style = rearrange(style, "b (n c) -> b n c", n=2)
gain, bias = style.unbind(dim=1)
gain = gain + 1.
if x.dim() == 3:
gain = rearrange(gain, "b c -> b 1 c")
bias = rearrange(bias, "b c -> b 1 c")
elif x.dim() == 2:
pass
else:
assert 0
x = x * torch.rsqrt(torch.mean(x ** 2, dim=-1, keepdim=True) + 1e-8)
x = x * gain + bias
out = self.lrelu(x)
return out
class ModSinLayer_NoBias(nn.Module):
def __repr__(self): return f"{self.__class__.__name__}({self.repr})"
def __init__(self,
in_dim,
use_style_fc=False,
style_dim=None,
which_linear=nn.Linear,
spectral_norm=False,
eps=1e-5,
freq=1,
phase=0,
**kwargs):
super(ModSinLayer_NoBias, self).__init__()
self.repr = f"in_dim={in_dim}, use_style_fc={use_style_fc}, style_dim={style_dim}, " \
f"freq={freq}, phase={phase}"
self.in_dim = in_dim
self.use_style_fc = use_style_fc
self.style_dim = style_dim
self.freq = freq
self.phase = phase
self.spectral_norm = spectral_norm
if use_style_fc:
self.gain_fc = which_linear(style_dim, in_dim)
if spectral_norm:
self.gain_fc = nn.utils.spectral_norm(self.gain_fc)
else:
self.style_dim = in_dim * 2
self.eps = eps
pass
def forward(self,
x,
style):
assert style.shape[-1] == self.style_dim
if self.use_style_fc:
gain = self.gain_fc(style) + 1.
else:
style = rearrange(style, "b (n c) -> b n c", n=2)
gain, bias = style.unbind(dim=1)
gain = gain + 1.
if x.dim() == 3:
gain = rearrange(gain, "b c -> b 1 c")
elif x.dim() == 2:
pass
else:
assert 0
x = torch.sin(self.freq * x + self.phase)
out = x * gain
return out
class SinBlock(nn.Module):
def __init__(self,
in_dim,
out_dim,
style_dim,
name_prefix,
):
super().__init__()
self.in_dim = in_dim
self.out_dim = out_dim
self.style_dim = style_dim
self.name_prefix = name_prefix
self.style_dim_dict = {}
f.mod1 = mod_conv_fc.SinStyleMod(in_channel=in_dim,
out_channel=out_dim,
style_dim=style_dim,
use_style_fc=True,
)
self.style_dim_dict[f'{name_prefix}_0'] = self.mod1.style_dim
self.act1 = nn.LeakyReLU(0.2, inplace=True)
f.mod2 = mod_conv_fc.SinStyleMod(in_channel=out_dim,
out_channel=out_dim,
style_dim=style_dim,
use_style_fc=True,
)
self.style_dim_dict[f'{name_prefix}_1'] = self.mod2.style_dim
self.act2 = nn.LeakyReLU(0.2, inplace=True)
self.skip = SkipLayer()
pass
def forward(self,
x,
style_dict,
skip=False):
x_orig = x
style = style_dict[f'{self.name_prefix}_0']
x = self.mod1(x, style)
x = self.act1(x)
style = style_dict[f'{self.name_prefix}_1']
x = self.mod2(x, style)
out = self.act2(x)
if skip and out.shape[-1] == x_orig.shape[-1]:
out = self.skip(out, x_orig)
return out
def __repr__(self):
repr = f"{self.__class__.__name__}(in_dim={self.in_dim}, " \
f"out_dim={self.out_dim}, " \
f"style_dim={self.style_dim})"
return repr
class ToRGB(nn.Module):
def __init__(self,
in_dim,
dim_rgb=3,
use_equal_fc=False):
super().__init__()
self.in_dim = in_dim
self.dim_rgb = dim_rgb
if use_equal_fc:
self.linear = mod_conv_fc.EqualLinear(in_dim, dim_rgb, scale=1.)
else:
self.linear = nn.Linear(in_dim, dim_rgb)
pass
def forward(self,
input,
skip=None):
out = self.linear(input)
if skip is not None:
out = out + skip
return out
@MODEL_REGISTRY.register(name_prefix=__name__)
class Generator_Diffcam(nn.Module):
def __repr__(self):
return tl2_utils.get_class_repr(self)
def __init__(self,
nerf_cfg,
mapping_shape_cfg,
mapping_app_cfg,
inr_cfg,
mapping_inr_cfg,
shape_block_end_index=None,
app_block_end_index=None,
inr_block_end_index=None,
device='cuda',
**kwargs):
super(Generator_Diffcam, self).__init__()
self.repr_str = tl2_utils.dict2string(dict_obj={
'nerf_cfg': nerf_cfg,
'mapping_shape_cfg': mapping_shape_cfg,
'mapping_app_cfg': mapping_app_cfg,
'inr_cfg': inr_cfg,
'mapping_inr_cfg': mapping_inr_cfg,
'shape_block_end_index': shape_block_end_index,
'app_block_end_index': app_block_end_index,
'inr_block_end_index': inr_block_end_index,
})
self.device = device
self.inr_block_end_index = inr_block_end_index
self.module_name_list = []
self.nerf_net = nerf_net.NeRFNetwork_SIREN_skip(
shape_block_end_index=shape_block_end_index,
app_block_end_index=app_block_end_index,
**nerf_cfg)
self.module_name_list.append('nerf_net')
self.mapping_shape = multi_head_mapping.MultiHeadMappingNetwork(**{
**mapping_shape_cfg,
'head_dim_dict': self.nerf_net.style_dim_dict_shape
})
self.module_name_list.append('mapping_shape')
self.mapping_app = multi_head_mapping.MultiHeadMappingNetwork(**{
**mapping_app_cfg,
'head_dim_dict': self.nerf_net.style_dim_dict_app
})
self.module_name_list.append('mapping_app')
_in_dim = nerf_cfg.app_net_cfg.out_dim
self.inr_net = cips_net.CIPSNet(**{
**inr_cfg,
"input_dim": _in_dim,
'add_out_layer': True,
})
self.module_name_list.append('inr_net')
self.mapping_inr = multi_head_mapping.MultiHeadMappingNetwork(**{
**mapping_inr_cfg,
'head_dim_dict': self.inr_net.style_dim_dict
})
self.module_name_list.append('mapping_inr')
self.aux_to_rbg = nn.Sequential(
nn.Linear(_in_dim, 3),
nn.Tanh()
)
self.aux_to_rbg.apply(nerf_network.frequency_init(25))
self.module_name_list.append('aux_to_rbg')
logger = logging.getLogger('tl')
models_dict = {}
for name in self.module_name_list:
models_dict[name] = getattr(self, name)
models_dict['G'] = self
torch_utils.print_number_params(models_dict=models_dict, logger=logger)
logger.info(self)
pass
def forward(self,
zs,
rays_o,
rays_d,
nerf_kwargs={},
psi=1,
return_aux_img=False,
grad_points=None,
forward_points=None,
**kwargs):
style_dict = self.mapping_network(**zs)
if psi < 1:
avg_styles = self.generate_avg_frequencies(device=self.device)
style_dict = self.get_truncated_freq_phase(
raw_style_dict=style_dict, avg_style_dict=avg_styles, raw_lambda=psi)
b, h, w, c = rays_o.shape
rays_o = rearrange(rays_o, "b h w c -> b (h w) c")
rays_d = rearrange(rays_d, "b h w c -> b (h w) c")
if grad_points is not None and grad_points < h * w:
imgs, ret_maps = self.part_grad_forward(
rays_o=rays_o,
rays_d=rays_d,
style_dict=style_dict,
nerf_kwargs=nerf_kwargs,
return_aux_img=return_aux_img,
grad_points=grad_points)
else:
imgs, ret_maps = self.whole_grad_forward(
rays_o=rays_o,
rays_d=rays_d,
style_dict=style_dict,
nerf_kwargs=nerf_kwargs,
return_aux_img=return_aux_img,
forward_points=forward_points)
imgs = rearrange(imgs, "b (h w) c -> b c h w", h=h, w=w)
ret_imgs = {}
for name, v_map in ret_maps.items():
if v_map.dim() == 3:
v_map = rearrange(v_map, "b (h w) c -> b c h w", h=h, w=w)
elif v_map.dim() == 2:
v_map = rearrange(v_map, "b (h w) -> b h w", h=h, w=w)
ret_imgs[name] = v_map
return imgs, ret_imgs
def get_rays_axis_angle(self,
R,
t,
fx,
fy,
H: int,
W: int,
N_rays: int = -1):
rays_o, rays_d, select_inds = cam_params.get_rays(
rot=R,
trans=t,
focal_x=fx,
focal_y=fy,
H=H,
W=W,
N_rays=N_rays,
flatten=False)
return rays_o, rays_d, select_inds
def get_batch_style_dict(self, b, style_dict):
ret_style_dict = {}
for name, style in style_dict.items():
ret_style_dict[name] = style[[b]]
return ret_style_dict
def whole_grad_forward(self,
rays_o,
rays_d,
style_dict,
nerf_kwargs,
return_aux_img=True,
forward_points=None,
**kwargs):
if forward_points is not None and forward_points < rays_o.shape[1]:
with torch.no_grad():
batch_size = rays_o.shape[0]
num_points = rays_o.shape[1]
near = nerf_kwargs['near']
far = nerf_kwargs['far']
N_samples = nerf_kwargs['N_samples']
perturb = self.training
z_vals, points = volume_rendering.ray_sample_points(rays_o=rays_o,
rays_d=rays_d,
near=near,
far=far,
N_samples=N_samples,
perturb=perturb)
batch_image_ddict = collections.defaultdict(list)
for b in range(batch_size):
image_ddict = collections.defaultdict(list)
head = 0
while head < num_points:
tail = head + forward_points
cur_style_dict = self.get_batch_style_dict(b=b, style_dict=style_dict)
cur_inr_img, cur_ret_maps = self.points_forward(
rays_o=rays_o[[b], head:tail],
rays_d=rays_d[[b], head:tail],
points=points[[b], head:tail],
z_vals=z_vals[[b], head:tail],
style_dict=cur_style_dict,
nerf_kwargs=nerf_kwargs,
return_aux_img=return_aux_img)
image_ddict['inr_img'].append(cur_inr_img)
for k, v in cur_ret_maps.items():
image_ddict[k].append(v)
head += forward_points
for k, v in image_ddict.items():
one_image = torch.cat(v, dim=1)
batch_image_ddict[k].append(one_image)
ret_maps = {}
for k, v in batch_image_ddict.items():
ret_maps[k] = torch.cat(v, dim=0)
imgs = ret_maps.pop('inr_img')
else:
near = nerf_kwargs['near']
far = nerf_kwargs['far']
N_samples = nerf_kwargs['N_samples']
perturb = self.training
z_vals, points = volume_rendering.ray_sample_points(rays_o=rays_o,
rays_d=rays_d,
near=near,
far=far,
N_samples=N_samples,
perturb=perturb)
imgs, ret_maps = self.points_forward(
rays_o=rays_o,
rays_d=rays_d,
points=points,
z_vals=z_vals,
style_dict=style_dict,
nerf_kwargs=nerf_kwargs,
return_aux_img=return_aux_img)
return imgs, ret_maps
def part_grad_forward(self,
rays_o,
rays_d,
style_dict,
nerf_kwargs,
return_aux_img,
grad_points):
near = nerf_kwargs['near']
far = nerf_kwargs['far']
N_samples = nerf_kwargs['N_samples']
perturb = self.training
z_vals, points = volume_rendering.ray_sample_points(rays_o=rays_o,
rays_d=rays_d,
near=near,
far=far,
N_samples=N_samples,
perturb=perturb)
batch_size = rays_o.shape[0]
num_points = rays_o.shape[1]
device = self.device
assert num_points > grad_points
idx_grad, idx_no_grad = torch_utils.batch_random_split_indices(bs=batch_size,
num_points=num_points,
grad_points=grad_points,
device=device)
inr_img_grad, ret_maps_grad = self.points_forward(
rays_o=rays_o,
rays_d=rays_d,
points=points,
z_vals=z_vals,
style_dict=style_dict,
nerf_kwargs=nerf_kwargs,
return_aux_img=return_aux_img,
idx_grad=idx_grad)
with torch.no_grad():
inr_img_no_grad, ret_maps_no_grad = self.points_forward(
rays_o=rays_o,
rays_d=rays_d,
points=points,
z_vals=z_vals,
style_dict=style_dict,
nerf_kwargs=nerf_kwargs,
return_aux_img=return_aux_img,
idx_grad=idx_no_grad)
imgs = comm_utils.batch_scatter_points(idx_grad=idx_grad,
points_grad=inr_img_grad,
idx_no_grad=idx_no_grad,
points_no_grad=inr_img_no_grad,
num_points=num_points)
ret_maps = {}
for k in ret_maps_grad.keys():
comp_map = comm_utils.batch_scatter_points(idx_grad=idx_grad,
points_grad=ret_maps_grad[k],
idx_no_grad=idx_no_grad,
points_no_grad=ret_maps_no_grad[k],
num_points=num_points)
ret_maps[k] = comp_map
return imgs, ret_maps
def points_forward(self,
rays_o,
rays_d,
points,
z_vals,
style_dict,
nerf_kwargs,
return_aux_img,
idx_grad=None,
**kwargs):
device = points.device
viewdirs = volume_rendering.get_viewdirs(rays_d=rays_d)
N_samples = nerf_kwargs['N_samples']
if idx_grad is not None:
rays_o = comm_utils.batch_gather_points(points=rays_o, idx_grad=idx_grad)
rays_d = comm_utils.batch_gather_points(points=rays_d, idx_grad=idx_grad)
points = comm_utils.batch_gather_points(points=points, idx_grad=idx_grad)
z_vals = comm_utils.batch_gather_points(points=z_vals, idx_grad=idx_grad)
points = rearrange(points, "b Nrays Nsamples c -> b (Nrays Nsamples) c")
coarse_viewdirs = repeat(viewdirs, "b Nrays c -> b (Nrays Nsamples) c", Nsamples=N_samples)
coarse_output = self.nerf_net(
x=points,
ray_directions=coarse_viewdirs,
style_dict=style_dict)
coarse_output = rearrange(
coarse_output, "b (Nrays Nsamples) rgb_sigma -> b Nrays Nsamples rgb_sigma", Nsamples=N_samples)
if nerf_kwargs['N_importance'] > 0:
with torch.no_grad():
raw_sigma = coarse_output[..., -1]
perturb = self.training
fine_z_vals, fine_points = volume_rendering.get_fine_points(
z_vals=z_vals,
rays_o=rays_o,
rays_d=rays_d,
raw_sigma=raw_sigma,
N_importance=nerf_kwargs['N_importance'],
perturb=perturb,
raw_noise_std=nerf_kwargs['raw_noise_std'],
eps=nerf_kwargs['eps'])
fine_points = rearrange(fine_points, "b Nrays Nsamples c -> b (Nrays Nsamples) c")
fine_viewdirs = repeat(viewdirs, "b Nrays c -> b (Nrays Nsamples) c", Nsamples=nerf_kwargs['N_importance'])
fine_output = self.nerf_net(
x=fine_points,
ray_directions=fine_viewdirs,
style_dict=style_dict)
fine_output = rearrange(
fine_output, "b (Nrays Nsamples) rgb_sigma -> b Nrays Nsamples rgb_sigma", Nsamples=nerf_kwargs['N_importance'])
DIM_SAMPLES = 2
all_z_vals = torch.cat([fine_z_vals, z_vals], dim=DIM_SAMPLES)
_, indices = torch.sort(all_z_vals, dim=DIM_SAMPLES)
all_z_vals = torch.gather(all_z_vals, DIM_SAMPLES, indices)
all_outputs = torch.cat([fine_output, coarse_output], dim=DIM_SAMPLES)
view_shape = [*indices.shape, *(len(all_outputs.shape) - len(indices.shape)) * [1]]
all_outputs = torch.gather(all_outputs, DIM_SAMPLES, indices.view(view_shape).expand_as(all_outputs))
else:
all_outputs = coarse_output
all_z_vals = z_vals
all_raw_rgb = all_outputs[..., :-1]
all_raw_sigma = all_outputs[..., -1]
pixels_fea, ret_maps = volume_rendering.ray_integration(raw_rgb=all_raw_rgb,
raw_sigma=all_raw_sigma,
z_vals=all_z_vals,
rays_d=rays_d,
raw_noise_std=nerf_kwargs['raw_noise_std'],
eps=nerf_kwargs['eps'])
inr_img = self.inr_net(pixels_fea, style_dict, block_end_index=self.inr_block_end_index)
if return_aux_img:
aux_img = self.aux_to_rbg(pixels_fea)
ret_maps['aux_img'] = aux_img
return inr_img, ret_maps
def z_sampler(self,
shape,
device,
dist='gaussian'):
if dist == 'gaussian':
z = torch.randn(shape, device=device)
elif dist == 'uniform':
z = torch.rand(shape, device=device) * 2 - 1
return z
def get_zs(self,
b,
batch_split=1):
z_shape = self.z_sampler(shape=(b, self.mapping_shape.z_dim), device=self.device)
z_app = self.z_sampler(shape=(b, self.mapping_app.z_dim), device=self.device)
z_inr = self.z_sampler(shape=(b, self.mapping_inr.z_dim), device=self.device)
if batch_split > 1:
zs_list = []
z_shape_list = z_shape.split(b // batch_split)
z_app_list = z_app.split(b // batch_split)
z_inr_list = z_inr.split(b // batch_split)
for z_shape_, z_app_, z_inr_ in zip(z_shape_list, z_app_list, z_inr_list):
zs_ = {
'z_shape': z_shape_,
'z_app': z_app_,
'z_inr': z_inr_,
}
zs_list.append(zs_)
return zs_list
else:
zs = {
'z_shape': z_shape,
'z_app': z_app,
'z_inr': z_inr,
}
return zs
def mapping_network(self,
z_shape,
z_app,
z_inr):
if global_cfg.tl_debug:
VerboseModel.forward_verbose(self.mapping_shape,
inputs_args=(z_shape,),
submodels=['base_net'],
name_prefix='mapping_shape.')
VerboseModel.forward_verbose(self.mapping_app,
inputs_args=(z_app,),
submodels=['base_net'],
name_prefix='mapping_app.')
VerboseModel.forward_verbose(self.mapping_inr,
inputs_args=(z_inr,),
submodels=['base_net', ],
input_padding=50,
name_prefix='mapping_inr.')
style_dict = {}
style_dict.update(self.mapping_shape(z_shape))
style_dict.update(self.mapping_app(z_app))
style_dict.update(self.mapping_inr(z_inr))
return style_dict
def get_truncated_freq_phase(self,
raw_style_dict,
avg_style_dict,
raw_lambda):
truncated_style_dict = {}
for name, avg_style in avg_style_dict.items():
raw_style = raw_style_dict[name]
truncated_style = avg_style + raw_lambda * (raw_style - avg_style)
truncated_style_dict[name] = truncated_style
return truncated_style_dict
def generate_avg_frequencies(self,
num_samples=10000,
device='cuda'):
zs = self.get_zs(num_samples)
with torch.no_grad():
style_dict = self.mapping_network(**zs)
avg_styles = {}
for name, style in style_dict.items():
avg_styles[name] = style.mean(0, keepdim=True)
return avg_styles
def staged_forward(self, *args, **kwargs):
raise NotImplementedError
def set_device(self, device):
pass
def forward_camera_pos_and_lookup(self,
zs,
img_size,
fov,
ray_start,
ray_end,
num_steps,
h_stddev,
v_stddev,
h_mean,
v_mean,
hierarchical_sample,
camera_pos,
camera_lookup,
psi=1,
sample_dist=None,
lock_view_dependence=False,
clamp_mode='relu',
nerf_noise=0.,
white_back=False,
last_back=False,
return_aux_img=False,
grad_points=None,
forward_points=None,
**kwargs):
if global_cfg.tl_debug:
VerboseModel.forward_verbose(self.mapping_network_nerf,
inputs_args=(zs['z_nerf'],),
submodels=['base_net'],
name_prefix='mapping_nerf.')
VerboseModel.forward_verbose(self.mapping_network_inr,
inputs_args=(zs['z_inr'],),
submodels=['base_net', ],
input_padding=50,
name_prefix='mapping_inr.')
style_dict = self.mapping_network(**zs)
if psi < 1:
avg_styles = self.generate_avg_frequencies(device=self.device)
style_dict = self.get_truncated_freq_phase(
raw_style_dict=style_dict, avg_style_dict=avg_styles, raw_lambda=psi)
if grad_points is not None and grad_points < img_size ** 2:
imgs, pitch_yaw = self.part_grad_forward(
style_dict=style_dict,
img_size=img_size,
fov=fov,
ray_start=ray_start,
ray_end=ray_end,
num_steps=num_steps,
h_stddev=h_stddev,
v_stddev=v_stddev,
h_mean=h_mean,
v_mean=v_mean,
hierarchical_sample=hierarchical_sample,
sample_dist=sample_dist,
lock_view_dependence=lock_view_dependence,
clamp_mode=clamp_mode,
nerf_noise=nerf_noise,
white_back=white_back,
last_back=last_back,
return_aux_img=return_aux_img,
grad_points=grad_points,
camera_pos=camera_pos,
camera_lookup=camera_lookup,
)
return imgs, pitch_yaw
else:
imgs, pitch_yaw = self.whole_grad_forward(
style_dict=style_dict,
img_size=img_size,
fov=fov,
ray_start=ray_start,
ray_end=ray_end,
num_steps=num_steps,
h_stddev=h_stddev,
v_stddev=v_stddev,
h_mean=h_mean,
v_mean=v_mean,
hierarchical_sample=hierarchical_sample,
sample_dist=sample_dist,
lock_view_dependence=lock_view_dependence,
clamp_mode=clamp_mode,
nerf_noise=nerf_noise,
white_back=white_back,
last_back=last_back,
return_aux_img=return_aux_img,
forward_points=forward_points,
camera_pos=camera_pos,
camera_lookup=camera_lookup,
)
return imgs, pitch_yaw
@MODEL_REGISTRY.register(name_prefix=__name__)
class GeneratorNerfINR_freeze_NeRF(Generator_Diffcam):
def load_nerf_ema(self, G_ema):
ret = self.nerf_net.load_state_dict(G_ema.nerf_net.state_dict())
ret = self.mapping_network_nerf.load_state_dict(G_ema.mapping_network_nerf.state_dict())
ret = self.aux_to_rbg.load_state_dict(G_ema.aux_to_rbg.state_dict())
ret = self.mapping_network_inr.load_state_dict(G_ema.mapping_network_inr.state_dict())
ret = self.nerf_rgb_mapping.load_state_dict(G_ema.nerf_rgb_mapping.state_dict())
pass
def mapping_network(self,
z_nerf,
z_inr):
style_dict = {}
with torch.no_grad():
style_dict.update(self.mapping_network_nerf(z_nerf))
style_dict.update(self.mapping_network_inr(z_inr))
style_dict['nerf_rgb'] = self.nerf_rgb_mapping(style_dict['nerf_rgb'])
return style_dict
def points_forward(self,
style_dict,
transformed_points,
transformed_ray_directions_expanded,
num_steps,
hierarchical_sample,
z_vals,
clamp_mode,
nerf_noise,
transformed_ray_origins,
transformed_ray_directions,
white_back,
last_back,
return_aux_img,
idx_grad=None,
):
device = transformed_points.device
if idx_grad is not None:
transformed_points = comm_utils.gather_points(points=transformed_points, idx_grad=idx_grad)
transformed_ray_directions_expanded = comm_utils.gather_points(
points=transformed_ray_directions_expanded, idx_grad=idx_grad)
z_vals = comm_utils.gather_points(points=z_vals, idx_grad=idx_grad)
transformed_ray_origins = comm_utils.gather_points(points=transformed_ray_origins, idx_grad=idx_grad)
transformed_ray_directions = comm_utils.gather_points(points=transformed_ray_directions, idx_grad=idx_grad)
transformed_points = rearrange(transformed_points, "b n s c -> b (n s) c")
transformed_ray_directions_expanded = rearrange(transformed_ray_directions_expanded, "b n s c -> b (n s) c")
with torch.no_grad():
coarse_output = self.nerf_net(
x=transformed_points,
style_dict=style_dict,
ray_directions=transformed_ray_directions_expanded,
)
coarse_output = rearrange(coarse_output, "b (n s) rgb_sigma -> b n s rgb_sigma", s=num_steps)
if hierarchical_sample:
fine_points, fine_z_vals = self.get_fine_points_and_direction(
coarse_output=coarse_output,
z_vals=z_vals,
dim_rgb=self.nerf_net.rgb_dim,
clamp_mode=clamp_mode,
nerf_noise=nerf_noise,
num_steps=num_steps,
transformed_ray_origins=transformed_ray_origins,
transformed_ray_directions=transformed_ray_directions
)
with torch.no_grad():
fine_output = self.nerf_net(
x=fine_points,
style_dict=style_dict,
ray_directions=transformed_ray_directions_expanded,
)
fine_output = rearrange(fine_output, "b (n s) rgb_sigma -> b n s rgb_sigma", s=num_steps)
all_outputs = torch.cat([fine_output, coarse_output], dim=-2)
all_z_vals = torch.cat([fine_z_vals, z_vals], dim=-2)
_, indices = torch.sort(all_z_vals, dim=-2)
all_z_vals = torch.gather(all_z_vals, -2, indices)
all_outputs = torch.gather(all_outputs, -2, indices.expand(-1, -1, -1, all_outputs.shape[-1]))
else:
all_outputs = coarse_output
all_z_vals = z_vals
pixels_fea, depth, weights = pigan_utils.fancy_integration(
rgb_sigma=all_outputs,
z_vals=all_z_vals,
device=device,
dim_rgb=self.nerf_net.rgb_dim,
white_back=white_back,
last_back=last_back,
clamp_mode=clamp_mode,
noise_std=nerf_noise)
inr_img = self.inr_net(pixels_fea, style_dict)
if return_aux_img:
with torch.no_grad():
aux_img = self.aux_to_rbg(pixels_fea)
else:
aux_img = None
return inr_img, aux_img
| true | true |
f73176b9df2d9d3e6551836091e9a8f8bdc64a68 | 9,041 | py | Python | src/pyrobot/habitat/base.py | cihuang123/pyrobot | fe620097e31d11453b5ea7ac15e40f5f5721b29a | [
"MIT"
] | 2,150 | 2019-06-12T20:55:41.000Z | 2022-03-21T07:14:51.000Z | src/pyrobot/habitat/base.py | cihuang123/pyrobot | fe620097e31d11453b5ea7ac15e40f5f5721b29a | [
"MIT"
] | 124 | 2019-06-22T17:12:27.000Z | 2022-02-26T11:43:13.000Z | src/pyrobot/habitat/base.py | cihuang123/pyrobot | fe620097e31d11453b5ea7ac15e40f5f5721b29a | [
"MIT"
] | 329 | 2019-06-13T03:03:54.000Z | 2022-03-30T07:04:55.000Z | import numpy as np
import math
import pyrobot.utils.util as prutil
import rospy
import habitat_sim.agent as habAgent
import habitat_sim.utils as habUtils
from habitat_sim.agent.controls import ActuationSpec
import habitat_sim.errors
import quaternion
from tf.transformations import euler_from_quaternion, euler_from_matrix
class LoCoBotBase(object):
"""docstring for SimpleBase"""
def __init__(self, configs, simulator):
self.configs = configs
self.sim = simulator.sim
self.agent = self.sim.get_agent(self.configs.COMMON.SIMULATOR.DEFAULT_AGENT_ID)
self.transform = None
self.init_state = self.get_full_state()
def execute_action(self, action_name, actuation):
# actions = "turn_right" or "turn_left" or "move_forward"
# returns a bool showing if collided or not
return self._act(action_name, actuation)
def get_full_state(self):
# Returns habitat_sim.agent.AgentState
return self.agent.get_state()
def _rot_matrix(self, habitat_quat):
quat_list = [habitat_quat.x, habitat_quat.y, habitat_quat.z, habitat_quat.w]
return prutil.quat_to_rot_mat(quat_list)
def get_state(self, state_type="odom"):
# Returns (x, y, yaw)
assert state_type == "odom", "Error: Only Odom state is available"
cur_state = self.get_full_state()
init_rotation = self._rot_matrix(self.init_state.rotation)
# true position here refers to the relative position from
# where `self.init_state` is treated as origin
true_position = cur_state.position - self.init_state.position
true_position = np.matmul(init_rotation.transpose(), true_position, dtype=np.float64)
cur_rotation = self._rot_matrix(cur_state.rotation)
cur_rotation = np.matmul(init_rotation.transpose(), cur_rotation, dtype=np.float64)
(r, pitch, yaw) = euler_from_matrix(cur_rotation, axes="sxzy")
# Habitat has y perpendicular to map where as ROS has z perpendicular
# to the map. Where as x is same.
# Here ROS_X = -1 * habitat_z and ROS_Y = -1*habitat_x
return (-1 * true_position[2], -1 * true_position[0], yaw)
def stop(self):
raise NotImplementedError("Veclocity control is not supported in Habitat-Sim!!")
def set_vel(self, fwd_speed, turn_speed, exe_time=1):
raise NotImplementedError("Veclocity control is not supported in Habitat-Sim!!")
def go_to_relative(
self, xyt_position, use_map=False, close_loop=False, smooth=False
):
"""
Moves the robot to the robot to given
goal state relative to its initial pose.
:param xyt_position: The relative goal state of the form (x,y,t)
:param use_map: When set to "True", ensures that controler is
using only free space on the map to move the robot.
:param close_loop: When set to "True", ensures that controler is
operating in open loop by
taking account of odometry.
:param smooth: When set to "True", ensures that the motion
leading to the goal is a smooth one.
:type xyt_position: list
:type use_map: bool
:type close_loop: bool
:type smooth: bool
:return: True if successful; False otherwise (timeout, etc.)
:rtype: bool
"""
try:
if use_map:
raise NotImplementedError(
"Using map feature is not yet supported for Habitat-Sim"
)
if close_loop:
raise NotImplementedError(
"Closed-loop postion control is not supported in Habitat-Sim!"
)
if smooth:
raise NotImplementedError(
"Smooth position control feature is not yet for Habitat-Sim"
)
except Exception as error:
print(error)
return False
(cur_x, cur_y, cur_yaw) = self.get_state()
abs_yaw = cur_yaw + xyt_position[2]
return self._go_to_relative_pose(xyt_position[0], xyt_position[1], abs_yaw)
def go_to_absolute(
self, xyt_position, use_map=False, close_loop=False, smooth=False
):
"""
Moves the robot to the robot to given goal state in the world frame.
:param xyt_position: The goal state of the form (x,y,t)
in the world (map) frame.
:param use_map: When set to "True", ensures that controler is using
only free space on the map to move the robot.
:param close_loop: When set to "True", ensures that controler is
operating in open loop by
taking account of odometry.
:param smooth: When set to "True", ensures that the motion
leading to the goal is a smooth one.
:type xyt_position: list
:type use_map: bool
:type close_loop: bool
:type smooth: bool
:return: True if successful; False otherwise (timeout, etc.)
:rtype: bool
"""
try:
if use_map:
raise NotImplementedError(
"Using map feature is not yet supported for Habitat-Sim"
)
if close_loop:
raise NotImplementedError(
"Closed-loop postion control is not supported in Habitat-Sim!"
)
if smooth:
raise NotImplementedError(
"Smooth position control feature is not yet for Habitat-Sim"
)
except Exception as error:
print(error)
return False
(cur_x, cur_y, cur_yaw) = self.get_state()
rel_X = xyt_position[0] - cur_x
rel_Y = xyt_position[1] - cur_y
abs_yaw = xyt_position[2]
# convert rel_X & rel_Y from global frame to current frame
R = np.array([[np.cos(cur_yaw), np.sin(cur_yaw)],
[-np.sin(cur_yaw), np.cos(cur_yaw)]])
rel_x, rel_y = np.matmul(R, np.array([rel_X, rel_Y]).reshape(-1,1))
return self._go_to_relative_pose(rel_x[0], rel_y[0], abs_yaw)
def _act(self, action_name, actuation):
"""Take the action specified by action_id
:param action_id: ID of the action. Retreives the action from
`agent_config.action_space <AgentConfiguration.action_space>`
:return: Whether or not the action taken resulted in a collision
"""
did_collide = False
act_spec = ActuationSpec(actuation)
did_collide = self.agent.controls.action(
self.agent.scene_node, action_name, act_spec, apply_filter=True
)
return did_collide
def _go_to_relative_pose(self, rel_x, rel_y, abs_yaw):
# clip relative movements beyond 10 micrometer precision
# this is done to improve determinism, as habitat-sim doesn't
# seem to precisely move the robot beyond sub milimeter precision anyways
if abs(rel_x) < 1e-5:
rel_x = 0
if abs(rel_y) < 1e-5:
rel_y = 0
if math.sqrt(rel_x ** 2 + rel_y ** 2) > 0.0:
# rotate to point to (x, y) point
action_name = "turn_left"
if rel_y < 0.0:
action_name = "turn_right"
v1 = np.asarray([1, 0], dtype=np.float64)
v2 = np.asarray([rel_x, rel_y], dtype=np.float64)
cosine_angle = np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2))
angle = np.arccos(cosine_angle)
did_collide = self._act(action_name, math.degrees(angle))
if did_collide:
print("Error: Collision accured while 1st rotating!")
return False
# move to (x,y) point
did_collide = self._act("move_forward", math.sqrt(rel_x ** 2 + rel_y ** 2))
if did_collide:
print("Error: Collision accured while moving straight!")
return False
# rotate to match the final yaw!
(cur_x, cur_y, cur_yaw) = self.get_state()
rel_yaw = abs_yaw - cur_yaw
# clip to micro-degree precision to preserve determinism
if abs(rel_yaw) < 1e-4:
rel_yaw = 0
action_name = "turn_left"
if rel_yaw < 0.0:
action_name = "turn_right"
rel_yaw *= -1
did_collide = self._act(action_name, math.degrees(rel_yaw))
if did_collide:
print("Error: Collision accured while rotating!")
return False
return True
def track_trajectory(self, states, controls, close_loop):
"""
State trajectory that the robot should track.
:param states: sequence of (x,y,t) states that the robot should track.
:param controls: optionally specify control sequence as well.
:param close_loop: whether to close loop on the
computed control sequence or not.
:type states: list
:type controls: list
:type close_loop: bool
:return: True if successful; False otherwise (timeout, etc.)
:rtype: bool
"""
raise NotImplementedError
| 36.603239 | 93 | 0.623825 | import numpy as np
import math
import pyrobot.utils.util as prutil
import rospy
import habitat_sim.agent as habAgent
import habitat_sim.utils as habUtils
from habitat_sim.agent.controls import ActuationSpec
import habitat_sim.errors
import quaternion
from tf.transformations import euler_from_quaternion, euler_from_matrix
class LoCoBotBase(object):
def __init__(self, configs, simulator):
self.configs = configs
self.sim = simulator.sim
self.agent = self.sim.get_agent(self.configs.COMMON.SIMULATOR.DEFAULT_AGENT_ID)
self.transform = None
self.init_state = self.get_full_state()
def execute_action(self, action_name, actuation):
return self._act(action_name, actuation)
def get_full_state(self):
return self.agent.get_state()
def _rot_matrix(self, habitat_quat):
quat_list = [habitat_quat.x, habitat_quat.y, habitat_quat.z, habitat_quat.w]
return prutil.quat_to_rot_mat(quat_list)
def get_state(self, state_type="odom"):
assert state_type == "odom", "Error: Only Odom state is available"
cur_state = self.get_full_state()
init_rotation = self._rot_matrix(self.init_state.rotation)
true_position = cur_state.position - self.init_state.position
true_position = np.matmul(init_rotation.transpose(), true_position, dtype=np.float64)
cur_rotation = self._rot_matrix(cur_state.rotation)
cur_rotation = np.matmul(init_rotation.transpose(), cur_rotation, dtype=np.float64)
(r, pitch, yaw) = euler_from_matrix(cur_rotation, axes="sxzy")
return (-1 * true_position[2], -1 * true_position[0], yaw)
def stop(self):
raise NotImplementedError("Veclocity control is not supported in Habitat-Sim!!")
def set_vel(self, fwd_speed, turn_speed, exe_time=1):
raise NotImplementedError("Veclocity control is not supported in Habitat-Sim!!")
def go_to_relative(
self, xyt_position, use_map=False, close_loop=False, smooth=False
):
try:
if use_map:
raise NotImplementedError(
"Using map feature is not yet supported for Habitat-Sim"
)
if close_loop:
raise NotImplementedError(
"Closed-loop postion control is not supported in Habitat-Sim!"
)
if smooth:
raise NotImplementedError(
"Smooth position control feature is not yet for Habitat-Sim"
)
except Exception as error:
print(error)
return False
(cur_x, cur_y, cur_yaw) = self.get_state()
abs_yaw = cur_yaw + xyt_position[2]
return self._go_to_relative_pose(xyt_position[0], xyt_position[1], abs_yaw)
def go_to_absolute(
self, xyt_position, use_map=False, close_loop=False, smooth=False
):
try:
if use_map:
raise NotImplementedError(
"Using map feature is not yet supported for Habitat-Sim"
)
if close_loop:
raise NotImplementedError(
"Closed-loop postion control is not supported in Habitat-Sim!"
)
if smooth:
raise NotImplementedError(
"Smooth position control feature is not yet for Habitat-Sim"
)
except Exception as error:
print(error)
return False
(cur_x, cur_y, cur_yaw) = self.get_state()
rel_X = xyt_position[0] - cur_x
rel_Y = xyt_position[1] - cur_y
abs_yaw = xyt_position[2]
R = np.array([[np.cos(cur_yaw), np.sin(cur_yaw)],
[-np.sin(cur_yaw), np.cos(cur_yaw)]])
rel_x, rel_y = np.matmul(R, np.array([rel_X, rel_Y]).reshape(-1,1))
return self._go_to_relative_pose(rel_x[0], rel_y[0], abs_yaw)
def _act(self, action_name, actuation):
did_collide = False
act_spec = ActuationSpec(actuation)
did_collide = self.agent.controls.action(
self.agent.scene_node, action_name, act_spec, apply_filter=True
)
return did_collide
def _go_to_relative_pose(self, rel_x, rel_y, abs_yaw):
# seem to precisely move the robot beyond sub milimeter precision anyways
if abs(rel_x) < 1e-5:
rel_x = 0
if abs(rel_y) < 1e-5:
rel_y = 0
if math.sqrt(rel_x ** 2 + rel_y ** 2) > 0.0:
# rotate to point to (x, y) point
action_name = "turn_left"
if rel_y < 0.0:
action_name = "turn_right"
v1 = np.asarray([1, 0], dtype=np.float64)
v2 = np.asarray([rel_x, rel_y], dtype=np.float64)
cosine_angle = np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2))
angle = np.arccos(cosine_angle)
did_collide = self._act(action_name, math.degrees(angle))
if did_collide:
print("Error: Collision accured while 1st rotating!")
return False
# move to (x,y) point
did_collide = self._act("move_forward", math.sqrt(rel_x ** 2 + rel_y ** 2))
if did_collide:
print("Error: Collision accured while moving straight!")
return False
# rotate to match the final yaw!
(cur_x, cur_y, cur_yaw) = self.get_state()
rel_yaw = abs_yaw - cur_yaw
# clip to micro-degree precision to preserve determinism
if abs(rel_yaw) < 1e-4:
rel_yaw = 0
action_name = "turn_left"
if rel_yaw < 0.0:
action_name = "turn_right"
rel_yaw *= -1
did_collide = self._act(action_name, math.degrees(rel_yaw))
if did_collide:
print("Error: Collision accured while rotating!")
return False
return True
def track_trajectory(self, states, controls, close_loop):
raise NotImplementedError
| true | true |
f73176e6fa8ce3c0edc651c2858ea483ba4fd4a1 | 5,318 | py | Python | fritzconnection/fritzhosts.py | deisi/fritzconnection | b5c14515e1c8e2652b06b6316a7f3913df942841 | [
"MIT"
] | 2 | 2016-11-14T18:58:56.000Z | 2021-03-12T10:15:03.000Z | fritzconnection/fritzhosts.py | deisi/fritzconnection | b5c14515e1c8e2652b06b6316a7f3913df942841 | [
"MIT"
] | 2 | 2015-12-09T20:12:08.000Z | 2016-11-02T15:03:19.000Z | fritzconnection/fritzhosts.py | deisi/fritzconnection | b5c14515e1c8e2652b06b6316a7f3913df942841 | [
"MIT"
] | 7 | 2016-10-02T18:37:20.000Z | 2021-09-14T21:29:28.000Z | # -*- coding: utf-8 -*-
__version__ = '0.4.6'
import argparse
from . import fritzconnection
SERVICE = 'Hosts'
# version-access:
def get_version():
return __version__
class FritzHosts(object):
def __init__(self,
fc=None,
address=fritzconnection.FRITZ_IP_ADDRESS,
port=fritzconnection.FRITZ_TCP_PORT,
user=fritzconnection.FRITZ_USERNAME,
password=''):
super(FritzHosts, self).__init__()
if fc is None:
fc = fritzconnection.FritzConnection(address, port, user, password)
self.fc = fc
def action(self, actionname, **kwargs):
return self.fc.call_action(SERVICE, actionname, **kwargs)
@property
def modelname(self):
return self.fc.modelname
@property
def host_numbers(self):
result = self.action('GetHostNumberOfEntries')
return result['NewHostNumberOfEntries']
def get_generic_host_entry(self, index):
result = self.action('GetGenericHostEntry', NewIndex=index)
return result
def get_specific_host_entry(self, mac_address):
result = self.action('GetSpecificHostEntry', NewMACAddress=mac_address)
return result
def get_hosts_info(self):
"""
Returns a list of dicts with information about the known hosts.
The dict-keys are: 'ip', 'name', 'mac', 'status'
"""
result = []
index = 0
while index < self.host_numbers:
host = self.get_generic_host_entry(index)
result.append({
'ip': host['NewIPAddress'],
'name': host['NewHostName'],
'mac': host['NewMACAddress'],
'status': host['NewActive']})
index += 1
return result
# ---------------------------------------------------------
# terminal-output:
# ---------------------------------------------------------
def _print_header(fh):
print('\nFritzHosts:')
print('{:<20}{}'.format('version:', get_version()))
print('{:<20}{}'.format('model:', fh.modelname))
print('{:<20}{}'.format('ip:', fh.fc.address))
def print_hosts(fh):
print('\nList of registered hosts:\n')
print('{:>3}: {:<15} {:<26} {:<17} {}\n'.format(
'n', 'ip', 'name', 'mac', 'status'))
hosts = fh.get_hosts_info()
for index, host in enumerate(hosts):
if host['status'] == '1':
status = 'active'
else:
status = '-'
print('{:>3}: {:<15} {:<26} {:<17} {}'.format(
index,
host['ip'],
host['name'],
host['mac'],
status,
)
)
print('\n')
def _print_detail(fh, detail):
mac_address = detail[0]
print('\n{:<23}{}\n'.format('Details for host:', mac_address))
info = fh.get_specific_host_entry(mac_address)
for key, value in info.items():
print('{:<23}: {}'.format(key, value))
print('\n')
def _print_nums(fh):
print('{:<20}{}\n'.format('Number of hosts:', fh.host_numbers))
# ---------------------------------------------------------
# cli-section:
# ---------------------------------------------------------
def _get_cli_arguments():
parser = argparse.ArgumentParser(description='FritzBox Hosts')
parser.add_argument('-i', '--ip-address',
nargs='?', default=fritzconnection.FRITZ_IP_ADDRESS,
dest='address',
help='ip-address of the FritzBox to connect to. '
'Default: %s' % fritzconnection.FRITZ_IP_ADDRESS)
parser.add_argument('--port',
nargs='?', default=fritzconnection.FRITZ_TCP_PORT,
dest='port',
help='port of the FritzBox to connect to. '
'Default: %s' % fritzconnection.FRITZ_TCP_PORT)
parser.add_argument('-u', '--username',
nargs=1, default=fritzconnection.FRITZ_USERNAME,
help='Fritzbox authentication username')
parser.add_argument('-p', '--password',
nargs=1, default='',
help='Fritzbox authentication password')
parser.add_argument('-a', '--all',
action='store_true',
help='Show all hosts '
'(default if no other options given)')
parser.add_argument('-n', '--nums',
action='store_true',
help='Show number of known hosts')
parser.add_argument('-d', '--detail',
nargs=1, default='',
help='Show information about a specific host '
'(DETAIL: MAC Address)')
args = parser.parse_args()
return args
def _print_status(arguments):
fh = FritzHosts(address=arguments.address,
port=arguments.port,
user=arguments.username,
password=arguments.password)
_print_header(fh)
if arguments.detail:
_print_detail(fh, arguments.detail)
elif arguments.nums:
_print_nums(fh)
else:
print_hosts(fh)
if __name__ == '__main__':
_print_status(_get_cli_arguments())
| 32.036145 | 79 | 0.520496 |
__version__ = '0.4.6'
import argparse
from . import fritzconnection
SERVICE = 'Hosts'
def get_version():
return __version__
class FritzHosts(object):
def __init__(self,
fc=None,
address=fritzconnection.FRITZ_IP_ADDRESS,
port=fritzconnection.FRITZ_TCP_PORT,
user=fritzconnection.FRITZ_USERNAME,
password=''):
super(FritzHosts, self).__init__()
if fc is None:
fc = fritzconnection.FritzConnection(address, port, user, password)
self.fc = fc
def action(self, actionname, **kwargs):
return self.fc.call_action(SERVICE, actionname, **kwargs)
@property
def modelname(self):
return self.fc.modelname
@property
def host_numbers(self):
result = self.action('GetHostNumberOfEntries')
return result['NewHostNumberOfEntries']
def get_generic_host_entry(self, index):
result = self.action('GetGenericHostEntry', NewIndex=index)
return result
def get_specific_host_entry(self, mac_address):
result = self.action('GetSpecificHostEntry', NewMACAddress=mac_address)
return result
def get_hosts_info(self):
result = []
index = 0
while index < self.host_numbers:
host = self.get_generic_host_entry(index)
result.append({
'ip': host['NewIPAddress'],
'name': host['NewHostName'],
'mac': host['NewMACAddress'],
'status': host['NewActive']})
index += 1
return result
def _print_header(fh):
print('\nFritzHosts:')
print('{:<20}{}'.format('version:', get_version()))
print('{:<20}{}'.format('model:', fh.modelname))
print('{:<20}{}'.format('ip:', fh.fc.address))
def print_hosts(fh):
print('\nList of registered hosts:\n')
print('{:>3}: {:<15} {:<26} {:<17} {}\n'.format(
'n', 'ip', 'name', 'mac', 'status'))
hosts = fh.get_hosts_info()
for index, host in enumerate(hosts):
if host['status'] == '1':
status = 'active'
else:
status = '-'
print('{:>3}: {:<15} {:<26} {:<17} {}'.format(
index,
host['ip'],
host['name'],
host['mac'],
status,
)
)
print('\n')
def _print_detail(fh, detail):
mac_address = detail[0]
print('\n{:<23}{}\n'.format('Details for host:', mac_address))
info = fh.get_specific_host_entry(mac_address)
for key, value in info.items():
print('{:<23}: {}'.format(key, value))
print('\n')
def _print_nums(fh):
print('{:<20}{}\n'.format('Number of hosts:', fh.host_numbers))
def _get_cli_arguments():
parser = argparse.ArgumentParser(description='FritzBox Hosts')
parser.add_argument('-i', '--ip-address',
nargs='?', default=fritzconnection.FRITZ_IP_ADDRESS,
dest='address',
help='ip-address of the FritzBox to connect to. '
'Default: %s' % fritzconnection.FRITZ_IP_ADDRESS)
parser.add_argument('--port',
nargs='?', default=fritzconnection.FRITZ_TCP_PORT,
dest='port',
help='port of the FritzBox to connect to. '
'Default: %s' % fritzconnection.FRITZ_TCP_PORT)
parser.add_argument('-u', '--username',
nargs=1, default=fritzconnection.FRITZ_USERNAME,
help='Fritzbox authentication username')
parser.add_argument('-p', '--password',
nargs=1, default='',
help='Fritzbox authentication password')
parser.add_argument('-a', '--all',
action='store_true',
help='Show all hosts '
'(default if no other options given)')
parser.add_argument('-n', '--nums',
action='store_true',
help='Show number of known hosts')
parser.add_argument('-d', '--detail',
nargs=1, default='',
help='Show information about a specific host '
'(DETAIL: MAC Address)')
args = parser.parse_args()
return args
def _print_status(arguments):
fh = FritzHosts(address=arguments.address,
port=arguments.port,
user=arguments.username,
password=arguments.password)
_print_header(fh)
if arguments.detail:
_print_detail(fh, arguments.detail)
elif arguments.nums:
_print_nums(fh)
else:
print_hosts(fh)
if __name__ == '__main__':
_print_status(_get_cli_arguments())
| true | true |
f731785fe68dc453314df05fd73e25b0eaf40c95 | 7,738 | py | Python | pygments/lexers/rust.py | beasleyr-vmw/pygments | bd166a3bb5452efd3a37a52d4847cae96d3d45e2 | [
"BSD-2-Clause"
] | 6,989 | 2017-07-18T06:23:18.000Z | 2022-03-31T15:58:36.000Z | pygments/lexers/rust.py | beasleyr-vmw/pygments | bd166a3bb5452efd3a37a52d4847cae96d3d45e2 | [
"BSD-2-Clause"
] | 1,978 | 2017-07-18T09:17:58.000Z | 2022-03-31T14:28:43.000Z | pygments/lexers/rust.py | beasleyr-vmw/pygments | bd166a3bb5452efd3a37a52d4847cae96d3d45e2 | [
"BSD-2-Clause"
] | 1,228 | 2017-07-18T09:03:13.000Z | 2022-03-29T05:57:40.000Z | # -*- coding: utf-8 -*-
"""
pygments.lexers.rust
~~~~~~~~~~~~~~~~~~~~
Lexers for the Rust language.
:copyright: Copyright 2006-2019 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.lexer import RegexLexer, include, bygroups, words, default
from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
Number, Punctuation, Whitespace
__all__ = ['RustLexer']
class RustLexer(RegexLexer):
"""
Lexer for the Rust programming language (version 1.10).
.. versionadded:: 1.6
"""
name = 'Rust'
filenames = ['*.rs', '*.rs.in']
aliases = ['rust', 'rs']
mimetypes = ['text/rust']
keyword_types = (
words(('u8', 'u16', 'u32', 'u64', 'i8', 'i16', 'i32', 'i64',
'i128', 'u128', 'usize', 'isize', 'f32', 'f64', 'str', 'bool'),
suffix=r'\b'),
Keyword.Type)
builtin_types = (words((
# Reexported core operators
'Copy', 'Send', 'Sized', 'Sync',
'Drop', 'Fn', 'FnMut', 'FnOnce',
# Reexported types and traits
'Box',
'ToOwned',
'Clone',
'PartialEq', 'PartialOrd', 'Eq', 'Ord',
'AsRef', 'AsMut', 'Into', 'From',
'Default',
'Iterator', 'Extend', 'IntoIterator',
'DoubleEndedIterator', 'ExactSizeIterator',
'Option',
'Some', 'None',
'Result',
'Ok', 'Err',
'SliceConcatExt',
'String', 'ToString',
'Vec'), suffix=r'\b'),
Name.Builtin)
tokens = {
'root': [
# rust allows a file to start with a shebang, but if the first line
# starts with #![ then it's not a shebang but a crate attribute.
(r'#![^[\r\n].*$', Comment.Preproc),
default('base'),
],
'base': [
# Whitespace and Comments
(r'\n', Whitespace),
(r'\s+', Whitespace),
(r'//!.*?\n', String.Doc),
(r'///(\n|[^/].*?\n)', String.Doc),
(r'//(.*?)\n', Comment.Single),
(r'/\*\*(\n|[^/*])', String.Doc, 'doccomment'),
(r'/\*!', String.Doc, 'doccomment'),
(r'/\*', Comment.Multiline, 'comment'),
# Macro parameters
(r"""\$([a-zA-Z_]\w*|\(,?|\),?|,?)""", Comment.Preproc),
# Keywords
(words((
'as', 'async', 'await', 'box', 'const', 'crate', 'else',
'extern', 'for', 'if', 'impl', 'in', 'loop', 'match', 'move',
'mut', 'pub', 'ref', 'return', 'static', 'super', 'trait',
'try', 'unsafe', 'use', 'where', 'while'), suffix=r'\b'),
Keyword),
(words(('abstract', 'alignof', 'become', 'do', 'final', 'macro',
'offsetof', 'override', 'priv', 'proc', 'pure', 'sizeof',
'typeof', 'unsized', 'virtual', 'yield'), suffix=r'\b'),
Keyword.Reserved),
(r'(true|false)\b', Keyword.Constant),
(r'mod\b', Keyword, 'modname'),
(r'let\b', Keyword.Declaration),
(r'fn\b', Keyword, 'funcname'),
(r'(struct|enum|type|union)\b', Keyword, 'typename'),
(r'(default)(\s+)(type|fn)\b', bygroups(Keyword, Text, Keyword)),
keyword_types,
(r'self\b', Name.Builtin.Pseudo),
# Prelude (taken from Rust's src/libstd/prelude.rs)
builtin_types,
# Path seperators, so types don't catch them.
(r'::\b', Text),
# Types in positions.
(r'(?::|->)', Text, 'typename'),
# Labels
(r'(break|continue)(\s*)(\'[A-Za-z_]\w*)?',
bygroups(Keyword, Text.Whitespace, Name.Label)),
# Character Literal
(r"""'(\\['"\\nrt]|\\x[0-7][0-9a-fA-F]|\\0"""
r"""|\\u\{[0-9a-fA-F]{1,6}\}|.)'""",
String.Char),
(r"""b'(\\['"\\nrt]|\\x[0-9a-fA-F]{2}|\\0"""
r"""|\\u\{[0-9a-fA-F]{1,6}\}|.)'""",
String.Char),
# Binary Literal
(r'0b[01_]+', Number.Bin, 'number_lit'),
# Octal Literal
(r'0o[0-7_]+', Number.Oct, 'number_lit'),
# Hexadecimal Literal
(r'0[xX][0-9a-fA-F_]+', Number.Hex, 'number_lit'),
# Decimal Literal
(r'[0-9][0-9_]*(\.[0-9_]+[eE][+\-]?[0-9_]+|'
r'\.[0-9_]*(?!\.)|[eE][+\-]?[0-9_]+)', Number.Float,
'number_lit'),
(r'[0-9][0-9_]*', Number.Integer, 'number_lit'),
# String Literal
(r'b"', String, 'bytestring'),
(r'"', String, 'string'),
(r'b?r(#*)".*?"\1', String),
# Lifetime
(r"""'static""", Name.Builtin),
(r"""'[a-zA-Z_]\w*""", Name.Attribute),
# Operators and Punctuation
(r'[{}()\[\],.;]', Punctuation),
(r'[+\-*/%&|<>^!~@=:?]', Operator),
# Identifier
(r'[a-zA-Z_]\w*', Name),
# Attributes
(r'#!?\[', Comment.Preproc, 'attribute['),
# Macros
(r'([A-Za-z_]\w*)(!)(\s*)([A-Za-z_]\w*)?(\s*)(\{)',
bygroups(Comment.Preproc, Punctuation, Whitespace, Name,
Whitespace, Punctuation), 'macro{'),
(r'([A-Za-z_]\w*)(!)(\s*)([A-Za-z_]\w*)?(\()',
bygroups(Comment.Preproc, Punctuation, Whitespace, Name,
Punctuation), 'macro('),
],
'comment': [
(r'[^*/]+', Comment.Multiline),
(r'/\*', Comment.Multiline, '#push'),
(r'\*/', Comment.Multiline, '#pop'),
(r'[*/]', Comment.Multiline),
],
'doccomment': [
(r'[^*/]+', String.Doc),
(r'/\*', String.Doc, '#push'),
(r'\*/', String.Doc, '#pop'),
(r'[*/]', String.Doc),
],
'modname': [
(r'\s+', Text),
(r'[a-zA-Z_]\w*', Name.Namespace, '#pop'),
default('#pop'),
],
'funcname': [
(r'\s+', Text),
(r'[a-zA-Z_]\w*', Name.Function, '#pop'),
default('#pop'),
],
'typename': [
(r'\s+', Text),
(r'&', Keyword.Pseudo),
builtin_types,
keyword_types,
(r'[a-zA-Z_]\w*', Name.Class, '#pop'),
default('#pop'),
],
'number_lit': [
(r'[ui](8|16|32|64|size)', Keyword, '#pop'),
(r'f(32|64)', Keyword, '#pop'),
default('#pop'),
],
'string': [
(r'"', String, '#pop'),
(r"""\\['"\\nrt]|\\x[0-7][0-9a-fA-F]|\\0"""
r"""|\\u\{[0-9a-fA-F]{1,6}\}""", String.Escape),
(r'[^\\"]+', String),
(r'\\', String),
],
'bytestring': [
(r"""\\x[89a-fA-F][0-9a-fA-F]""", String.Escape),
include('string'),
],
'macro{': [
(r'\{', Operator, '#push'),
(r'\}', Operator, '#pop'),
],
'macro(': [
(r'\(', Operator, '#push'),
(r'\)', Operator, '#pop'),
],
'attribute_common': [
(r'"', String, 'string'),
(r'\[', Comment.Preproc, 'attribute['),
(r'\(', Comment.Preproc, 'attribute('),
],
'attribute[': [
include('attribute_common'),
(r'\];?', Comment.Preproc, '#pop'),
(r'[^"\]]+', Comment.Preproc),
],
'attribute(': [
include('attribute_common'),
(r'\);?', Comment.Preproc, '#pop'),
(r'[^")]+', Comment.Preproc),
],
}
| 35.013575 | 79 | 0.415094 |
from pygments.lexer import RegexLexer, include, bygroups, words, default
from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
Number, Punctuation, Whitespace
__all__ = ['RustLexer']
class RustLexer(RegexLexer):
name = 'Rust'
filenames = ['*.rs', '*.rs.in']
aliases = ['rust', 'rs']
mimetypes = ['text/rust']
keyword_types = (
words(('u8', 'u16', 'u32', 'u64', 'i8', 'i16', 'i32', 'i64',
'i128', 'u128', 'usize', 'isize', 'f32', 'f64', 'str', 'bool'),
suffix=r'\b'),
Keyword.Type)
builtin_types = (words((
'Copy', 'Send', 'Sized', 'Sync',
'Drop', 'Fn', 'FnMut', 'FnOnce',
'Box',
'ToOwned',
'Clone',
'PartialEq', 'PartialOrd', 'Eq', 'Ord',
'AsRef', 'AsMut', 'Into', 'From',
'Default',
'Iterator', 'Extend', 'IntoIterator',
'DoubleEndedIterator', 'ExactSizeIterator',
'Option',
'Some', 'None',
'Result',
'Ok', 'Err',
'SliceConcatExt',
'String', 'ToString',
'Vec'), suffix=r'\b'),
Name.Builtin)
tokens = {
'root': [
],
'base': [
# Whitespace and Comments
(r'\n', Whitespace),
(r'\s+', Whitespace),
(r'//!.*?\n', String.Doc),
(r'///(\n|[^/].*?\n)', String.Doc),
(r'//(.*?)\n', Comment.Single),
(r'/\*\*(\n|[^/*])', String.Doc, 'doccomment'),
(r'/\*!', String.Doc, 'doccomment'),
(r'/\*', Comment.Multiline, 'comment'),
# Macro parameters
(r"""\$([a-zA-Z_]\w*|\(,?|\),?|,?)""", Comment.Preproc),
# Keywords
(words((
'as', 'async', 'await', 'box', 'const', 'crate', 'else',
'extern', 'for', 'if', 'impl', 'in', 'loop', 'match', 'move',
'mut', 'pub', 'ref', 'return', 'static', 'super', 'trait',
'try', 'unsafe', 'use', 'where', 'while'), suffix=r'\b'),
Keyword),
(words(('abstract', 'alignof', 'become', 'do', 'final', 'macro',
'offsetof', 'override', 'priv', 'proc', 'pure', 'sizeof',
'typeof', 'unsized', 'virtual', 'yield'), suffix=r'\b'),
Keyword.Reserved),
(r'(true|false)\b', Keyword.Constant),
(r'mod\b', Keyword, 'modname'),
(r'let\b', Keyword.Declaration),
(r'fn\b', Keyword, 'funcname'),
(r'(struct|enum|type|union)\b', Keyword, 'typename'),
(r'(default)(\s+)(type|fn)\b', bygroups(Keyword, Text, Keyword)),
keyword_types,
(r'self\b', Name.Builtin.Pseudo),
# Prelude (taken from Rust's src/libstd/prelude.rs)
builtin_types,
(r'::\b', Text),
# Types in positions.
(r'(?::|->)', Text, 'typename'),
# Labels
(r'(break|continue)(\s*)(\'[A-Za-z_]\w*)?',
bygroups(Keyword, Text.Whitespace, Name.Label)),
(r"""'(\\['"\\nrt]|\\x[0-7][0-9a-fA-F]|\\0"""
r"""|\\u\{[0-9a-fA-F]{1,6}\}|.)'""",
String.Char),
(r"""b'(\\['"\\nrt]|\\x[0-9a-fA-F]{2}|\\0"""
r"""|\\u\{[0-9a-fA-F]{1,6}\}|.)'""",
String.Char),
(r'0b[01_]+', Number.Bin, 'number_lit'),
(r'0o[0-7_]+', Number.Oct, 'number_lit'),
(r'0[xX][0-9a-fA-F_]+', Number.Hex, 'number_lit'),
(r'[0-9][0-9_]*(\.[0-9_]+[eE][+\-]?[0-9_]+|'
r'\.[0-9_]*(?!\.)|[eE][+\-]?[0-9_]+)', Number.Float,
'number_lit'),
(r'[0-9][0-9_]*', Number.Integer, 'number_lit'),
(r'b"', String, 'bytestring'),
(r'"', String, 'string'),
(r'b?r(#*)".*?"\1', String),
(r"""'static""", Name.Builtin),
(r"""'[a-zA-Z_]\w*""", Name.Attribute),
(r'[{}()\[\],.;]', Punctuation),
(r'[+\-*/%&|<>^!~@=:?]', Operator),
(r'[a-zA-Z_]\w*', Name),
(r'#!?\[', Comment.Preproc, 'attribute['),
(r'([A-Za-z_]\w*)(!)(\s*)([A-Za-z_]\w*)?(\s*)(\{)',
bygroups(Comment.Preproc, Punctuation, Whitespace, Name,
Whitespace, Punctuation), 'macro{'),
(r'([A-Za-z_]\w*)(!)(\s*)([A-Za-z_]\w*)?(\()',
bygroups(Comment.Preproc, Punctuation, Whitespace, Name,
Punctuation), 'macro('),
],
'comment': [
(r'[^*/]+', Comment.Multiline),
(r'/\*', Comment.Multiline, '#push'),
(r'\*/', Comment.Multiline, '#pop'),
(r'[*/]', Comment.Multiline),
],
'doccomment': [
(r'[^*/]+', String.Doc),
(r'/\*', String.Doc, '#push'),
(r'\*/', String.Doc, '#pop'),
(r'[*/]', String.Doc),
],
'modname': [
(r'\s+', Text),
(r'[a-zA-Z_]\w*', Name.Namespace, '#pop'),
default('#pop'),
],
'funcname': [
(r'\s+', Text),
(r'[a-zA-Z_]\w*', Name.Function, '#pop'),
default('#pop'),
],
'typename': [
(r'\s+', Text),
(r'&', Keyword.Pseudo),
builtin_types,
keyword_types,
(r'[a-zA-Z_]\w*', Name.Class, '#pop'),
default('#pop'),
],
'number_lit': [
(r'[ui](8|16|32|64|size)', Keyword, '#pop'),
(r'f(32|64)', Keyword, '#pop'),
default('#pop'),
],
'string': [
(r'"', String, '#pop'),
(r"""\\['"\\nrt]|\\x[0-7][0-9a-fA-F]|\\0"""
r"""|\\u\{[0-9a-fA-F]{1,6}\}""", String.Escape),
(r'[^\\"]+', String),
(r'\\', String),
],
'bytestring': [
(r"""\\x[89a-fA-F][0-9a-fA-F]""", String.Escape),
include('string'),
],
'macro{': [
(r'\{', Operator, '#push'),
(r'\}', Operator, '#pop'),
],
'macro(': [
(r'\(', Operator, '#push'),
(r'\)', Operator, '#pop'),
],
'attribute_common': [
(r'"', String, 'string'),
(r'\[', Comment.Preproc, 'attribute['),
(r'\(', Comment.Preproc, 'attribute('),
],
'attribute[': [
include('attribute_common'),
(r'\];?', Comment.Preproc, '
(r'[^"\]]+', Comment.Preproc),
],
'attribute(': [
include('attribute_common'),
(r'\);?', Comment.Preproc, '#pop'),
(r'[^")]+', Comment.Preproc),
],
}
| true | true |
f731786dd9a6f98ebccbad8bbac311e06ceed81d | 200 | py | Python | apps/users/utils.py | Yunloop/RoadBlog | d27504096cf00357c8f18737721b9b117b0203d9 | [
"MIT"
] | 1 | 2019-09-18T10:51:55.000Z | 2019-09-18T10:51:55.000Z | apps/users/utils.py | Yunloop/road | d27504096cf00357c8f18737721b9b117b0203d9 | [
"MIT"
] | 9 | 2020-06-05T23:14:20.000Z | 2022-02-10T11:36:14.000Z | apps/users/utils.py | Yunloop/road | d27504096cf00357c8f18737721b9b117b0203d9 | [
"MIT"
] | null | null | null | def jwt_response_payload_handler(token, user=None, request=None):
"""
重写获取jwt载荷数据方法
"""
return {
'token': token,
'id': user.id,
'username': user.username
}
| 20 | 65 | 0.56 | def jwt_response_payload_handler(token, user=None, request=None):
return {
'token': token,
'id': user.id,
'username': user.username
}
| true | true |
f73179932da21703dc52d5ead50dafad85c3d14a | 11,369 | py | Python | pydantic_sqlite/_core.py | Phil997/pydantic_sqlite | d52d0f42045c90b47a8e6987ec60dd071444f427 | [
"MIT"
] | 3 | 2022-01-11T06:02:45.000Z | 2022-02-07T06:07:29.000Z | pydantic_sqlite/_core.py | Phil997/pydantic_sqlite | d52d0f42045c90b47a8e6987ec60dd071444f427 | [
"MIT"
] | null | null | null | pydantic_sqlite/_core.py | Phil997/pydantic_sqlite | d52d0f42045c90b47a8e6987ec60dd071444f427 | [
"MIT"
] | null | null | null | import importlib
import inspect
import json
import os
import sqlite3
import tempfile
import typing
from shutil import copyfile
from typing import Any, Generator, List, Union
from pydantic import BaseModel, root_validator
from pydantic.fields import ModelField
from sqlite_utils import Database as _Database
from typing_inspect import is_literal_type, is_union_type
from ._misc import iterable_in_type_repr
SPECIALTYPE = [
typing.Any,
typing.Literal,
typing.Union]
class TableBaseModel(BaseModel):
table: str
moduleclass: typing.Any
modulename: str
pks: List[str]
@root_validator(pre=True)
def extract_modulename(cls, values):
v = values['moduleclass']
values.update(
{'modulename': str(v).split("<class '")[1].split("'>")[0]})
return values
def data(self):
return dict(
table=self.table,
modulename=self.modulename,
pks=self.pks)
class DataBase():
def __init__(self, **kwargs):
self._basemodels = {}
self._db = _Database(memory=True)
def __call__(self, tablename) -> Generator[BaseModel, None, None]:
"""returns a Generator for all values in the Table. The returned values are subclasses of pydantic.BaseModel"""
try:
basemodel = self._basemodels[tablename]
foreign_refs = {key.column: key.other_table for key in self._db[tablename].foreign_keys}
except KeyError:
raise KeyError(f"can not find Table: {tablename} in Database") from None
for row in self._db[tablename].rows:
yield self._build_basemodel_from_dict(basemodel, row, foreign_refs)
def _special_conversion(self, field_value: Any) -> Union[bool, Any]:
def special_possible(obj_class):
try:
if not hasattr(obj_class.SQConfig, 'convert'):
return False
return True if obj_class.SQConfig.special_insert else False
except AttributeError:
return False
if isinstance(field_value, List):
if len(field_value) == 0:
return False
if not special_possible(obj_class := field_value[0].__class__):
return False
if not all(isinstance(value, type(field_value[0])) for value in field_value):
raise ValueError(f"not all values in the List are from the same type: '{field_value}'")
return [obj_class.SQConfig.convert(value) for value in field_value]
else:
if not special_possible(obj_class := field_value.__class__):
return False
return obj_class.SQConfig.convert(field_value)
def add(self, tablename: str, value: BaseModel, foreign_tables={}, update_nested_models=True, pk: str = "uuid") -> None:
"""adds a new value to the table tablename"""
# unkown Tablename -> means new Table -> update the table_basemodel_ref list
if tablename not in self._basemodels:
self._basemodels_add_model(table=tablename, moduleclass=value.__class__, pks=[pk])
# check whether the value matches the basemodels in the table
if not self._basemodels[tablename].moduleclass == type(value):
raise ValueError(
f"Can not add type '{type(value)}' to the table '{tablename}', which contains values of type '{self._basemodels[tablename].moduleclass}'")
# create dict for writing to the Table
data_for_save = value.dict() if not hasattr(value, "sqlite_repr") else value.sqlite_repr
foreign_keys = []
for field_name, field in value.__fields__.items():
field_value = getattr(value, field_name)
if res := self._special_conversion(field_value): # Special Insert with SQConfig.convert
data_for_save[field_name] = res
elif field.type_ in SPECIALTYPE or typing.get_origin(field.type_):
# typing._SpecialForm: Any, NoReturn, ClassVar, Union, Optional
# typing.get_origin(field.type_) -> e.g. Literal
data_for_save[field_name] = self._typing_conversion(field, field_value)
elif issubclass(field.type_, BaseModel): # nested BaseModels in this value
# the value has got a field which is of type BaseModel, so this filed must be in a foreign table
# if the field is already in the Table it continues, but if is it not in the table it will add this to the table
# !recursive call to self.add
if field_name not in foreign_tables.keys():
keys = list(foreign_tables.keys())
raise KeyError(f"detect field of Type BaseModel, but can not find '{field_name}' in foreign_tables (Keys: {keys})") from None
else:
foreign_table_name = foreign_tables[field_name]
if foreign_table_name not in self._db.table_names():
raise KeyError(f"Can not add a value, which has a foreign Key '{foreign_tables}' to a Table '{foreign_table_name}' which does not exists")
nested_obj_ids = self._upsert_value_in_foreign_table(field_value, foreign_table_name, update_nested_models)
data_for_save[field_name] = nested_obj_ids
foreign_keys.append((field_name, foreign_table_name, pk)) # ignore=True
self._db[tablename].upsert(data_for_save, pk=pk, foreign_keys=foreign_keys)
def uuid_in_table(self, tablename: str, uuid: str) -> bool:
"""checks if the given uuid is used as a primary key in the table"""
hits = [row for row in self._db[tablename].rows_where("uuid = ?", [uuid])]
if len(hits) > 1:
raise Exception("uuid is two times in table") # TODO choice correct exceptiontype
return False if not hits else True
def value_in_table(self, tablename: str, value: BaseModel) -> bool:
"""checks if the given value is in the table"""
return self.uuid_in_table(tablename, value.uuid)
def value_from_table(self, tablename: str, uuid: str) -> typing.Any:
"""searchs the Objekt with the given uuid in the table and returns it. Returns a subclass of type pydantic.BaseModel"""
hits = [row for row in self._db[tablename].rows_where("uuid = ?", [uuid])]
if len(hits) > 1:
raise Exception("uuid is two times in table") # TODO choice correct exceptiontype
model = self._basemodels[tablename]
foreign_refs = {key.column: key.other_table for key in self._db[tablename].foreign_keys}
return None if not hits else self._build_basemodel_from_dict(model, hits[0], foreign_refs=foreign_refs)
def values_in_table(self, tablename) -> int:
"""returns the number of values in the Table"""
return self._db[tablename].count
def load(self, filename: str) -> None:
"""loads all data from the given file and adds them to the in-memory database"""
if not os.path.isfile(filename):
raise FileNotFoundError(f"Can not load {filename}")
file_db = sqlite3.connect(filename)
query = "".join(line for line in file_db.iterdump())
self._db.conn.executescript(query)
file_db.close()
for model in self._db["__basemodels__"].rows:
classname = model['modulename'].split('.')[-1]
modulename = '.'.join(model['modulename'].split('.')[:-1])
my_module = importlib.import_module(modulename)
self._basemodels_add_model(
table=model['table'],
moduleclass=getattr(my_module, classname),
pks=json.loads(model['pks']))
def save(self, filename: str) -> None:
"""saves alle values from the in_memory database to a file"""
if not filename.endswith(".db"):
filename += ".db"
tmp_dir = tempfile.mkdtemp()
name = filename.split(os.path.sep)[-1]
tmp_name = tmp_dir + os.path.sep + name
backup = tmp_dir + os.path.sep + "_backup.db"
if os.path.isfile(filename):
copyfile(filename, backup)
try:
file_db = sqlite3.connect(tmp_name)
query = "".join(line for line in self._db.conn.iterdump())
file_db.executescript(query)
file_db.close()
copyfile(tmp_name, filename)
except Exception:
print(f"saved the backup file under '{backup}'")
def _basemodels_add_model(self, **kwargs):
model = TableBaseModel(**kwargs)
self._basemodels.update({kwargs['table']: model})
self._db["__basemodels__"].upsert(model.data(), pk="modulename")
def _build_basemodel_from_dict(self, basemodel: TableBaseModel, row: dict, foreign_refs: dict):
# returns a subclass object of type BaseModel which is build out of class basemodel.moduleclass and the data out of the dict
members = inspect.getmembers(basemodel.moduleclass, lambda a: not(inspect.isroutine(a)))
field_models = next(line[1] for line in members if '__fields__' in line)
d = {}
for field_name, field_value in row.items():
type_repr = field_models[field_name].__str__().split(' ')[1] # 'type=Any'
if field_name in foreign_refs.keys(): # the column contains another subclass of BaseModel
if not iterable_in_type_repr(type_repr):
data = self.value_from_table(foreign_refs[field_name], field_value)
else:
data = [self.value_from_table(foreign_refs[field_name], val) for val in json.loads(field_value)]
else:
data = field_value if not iterable_in_type_repr(type_repr) else json.loads(field_value)
d.update({field_name: data})
return basemodel.moduleclass(**d)
def _upsert_value_in_foreign_table(self, field_value, foreign_table_name, update_nested_models) -> Union[str, List[str]]:
# The nested BaseModel will be inserted or upserted to the foreign table if it is not contained there,
# or the update_nested_models parameter is True. If the value is Iterable (e.g. List) all values in the
# List will be be inserted or upserted. The function returns the ids of the values
# The foreign keys of this table are needed to add the nested basemodel object.
foreign_refs = {key.column: key.other_table for key in self._db.table(foreign_table_name).foreign_keys}
def add_nested_model(value):
if not self.value_in_table(foreign_table_name, value) or update_nested_models:
self.add(foreign_table_name, value, foreign_tables=foreign_refs)
return value.uuid
if not isinstance(field_value, List):
return add_nested_model(field_value)
else:
return [add_nested_model(element) for element in field_value]
def _typing_conversion(self, field: ModelField, field_value: typing) -> typing.Any:
if field.type_ == typing.Any:
return field_value
elif is_union_type(field.type_):
return str(field_value)
elif is_literal_type(field.type_):
return str(field_value)
else:
raise NotImplementedError(f"type {field.type_} is not supported yet")
| 46.215447 | 158 | 0.648078 | import importlib
import inspect
import json
import os
import sqlite3
import tempfile
import typing
from shutil import copyfile
from typing import Any, Generator, List, Union
from pydantic import BaseModel, root_validator
from pydantic.fields import ModelField
from sqlite_utils import Database as _Database
from typing_inspect import is_literal_type, is_union_type
from ._misc import iterable_in_type_repr
SPECIALTYPE = [
typing.Any,
typing.Literal,
typing.Union]
class TableBaseModel(BaseModel):
table: str
moduleclass: typing.Any
modulename: str
pks: List[str]
@root_validator(pre=True)
def extract_modulename(cls, values):
v = values['moduleclass']
values.update(
{'modulename': str(v).split("<class '")[1].split("'>")[0]})
return values
def data(self):
return dict(
table=self.table,
modulename=self.modulename,
pks=self.pks)
class DataBase():
def __init__(self, **kwargs):
self._basemodels = {}
self._db = _Database(memory=True)
def __call__(self, tablename) -> Generator[BaseModel, None, None]:
try:
basemodel = self._basemodels[tablename]
foreign_refs = {key.column: key.other_table for key in self._db[tablename].foreign_keys}
except KeyError:
raise KeyError(f"can not find Table: {tablename} in Database") from None
for row in self._db[tablename].rows:
yield self._build_basemodel_from_dict(basemodel, row, foreign_refs)
def _special_conversion(self, field_value: Any) -> Union[bool, Any]:
def special_possible(obj_class):
try:
if not hasattr(obj_class.SQConfig, 'convert'):
return False
return True if obj_class.SQConfig.special_insert else False
except AttributeError:
return False
if isinstance(field_value, List):
if len(field_value) == 0:
return False
if not special_possible(obj_class := field_value[0].__class__):
return False
if not all(isinstance(value, type(field_value[0])) for value in field_value):
raise ValueError(f"not all values in the List are from the same type: '{field_value}'")
return [obj_class.SQConfig.convert(value) for value in field_value]
else:
if not special_possible(obj_class := field_value.__class__):
return False
return obj_class.SQConfig.convert(field_value)
def add(self, tablename: str, value: BaseModel, foreign_tables={}, update_nested_models=True, pk: str = "uuid") -> None:
if tablename not in self._basemodels:
self._basemodels_add_model(table=tablename, moduleclass=value.__class__, pks=[pk])
if not self._basemodels[tablename].moduleclass == type(value):
raise ValueError(
f"Can not add type '{type(value)}' to the table '{tablename}', which contains values of type '{self._basemodels[tablename].moduleclass}'")
data_for_save = value.dict() if not hasattr(value, "sqlite_repr") else value.sqlite_repr
foreign_keys = []
for field_name, field in value.__fields__.items():
field_value = getattr(value, field_name)
if res := self._special_conversion(field_value):
data_for_save[field_name] = res
elif field.type_ in SPECIALTYPE or typing.get_origin(field.type_):
data_for_save[field_name] = self._typing_conversion(field, field_value)
elif issubclass(field.type_, BaseModel):
if field_name not in foreign_tables.keys():
keys = list(foreign_tables.keys())
raise KeyError(f"detect field of Type BaseModel, but can not find '{field_name}' in foreign_tables (Keys: {keys})") from None
else:
foreign_table_name = foreign_tables[field_name]
if foreign_table_name not in self._db.table_names():
raise KeyError(f"Can not add a value, which has a foreign Key '{foreign_tables}' to a Table '{foreign_table_name}' which does not exists")
nested_obj_ids = self._upsert_value_in_foreign_table(field_value, foreign_table_name, update_nested_models)
data_for_save[field_name] = nested_obj_ids
foreign_keys.append((field_name, foreign_table_name, pk))
self._db[tablename].upsert(data_for_save, pk=pk, foreign_keys=foreign_keys)
def uuid_in_table(self, tablename: str, uuid: str) -> bool:
hits = [row for row in self._db[tablename].rows_where("uuid = ?", [uuid])]
if len(hits) > 1:
raise Exception("uuid is two times in table")
return False if not hits else True
def value_in_table(self, tablename: str, value: BaseModel) -> bool:
return self.uuid_in_table(tablename, value.uuid)
def value_from_table(self, tablename: str, uuid: str) -> typing.Any:
hits = [row for row in self._db[tablename].rows_where("uuid = ?", [uuid])]
if len(hits) > 1:
raise Exception("uuid is two times in table")
model = self._basemodels[tablename]
foreign_refs = {key.column: key.other_table for key in self._db[tablename].foreign_keys}
return None if not hits else self._build_basemodel_from_dict(model, hits[0], foreign_refs=foreign_refs)
def values_in_table(self, tablename) -> int:
return self._db[tablename].count
def load(self, filename: str) -> None:
if not os.path.isfile(filename):
raise FileNotFoundError(f"Can not load {filename}")
file_db = sqlite3.connect(filename)
query = "".join(line for line in file_db.iterdump())
self._db.conn.executescript(query)
file_db.close()
for model in self._db["__basemodels__"].rows:
classname = model['modulename'].split('.')[-1]
modulename = '.'.join(model['modulename'].split('.')[:-1])
my_module = importlib.import_module(modulename)
self._basemodels_add_model(
table=model['table'],
moduleclass=getattr(my_module, classname),
pks=json.loads(model['pks']))
def save(self, filename: str) -> None:
if not filename.endswith(".db"):
filename += ".db"
tmp_dir = tempfile.mkdtemp()
name = filename.split(os.path.sep)[-1]
tmp_name = tmp_dir + os.path.sep + name
backup = tmp_dir + os.path.sep + "_backup.db"
if os.path.isfile(filename):
copyfile(filename, backup)
try:
file_db = sqlite3.connect(tmp_name)
query = "".join(line for line in self._db.conn.iterdump())
file_db.executescript(query)
file_db.close()
copyfile(tmp_name, filename)
except Exception:
print(f"saved the backup file under '{backup}'")
def _basemodels_add_model(self, **kwargs):
model = TableBaseModel(**kwargs)
self._basemodels.update({kwargs['table']: model})
self._db["__basemodels__"].upsert(model.data(), pk="modulename")
def _build_basemodel_from_dict(self, basemodel: TableBaseModel, row: dict, foreign_refs: dict):
members = inspect.getmembers(basemodel.moduleclass, lambda a: not(inspect.isroutine(a)))
field_models = next(line[1] for line in members if '__fields__' in line)
d = {}
for field_name, field_value in row.items():
type_repr = field_models[field_name].__str__().split(' ')[1]
if field_name in foreign_refs.keys():
if not iterable_in_type_repr(type_repr):
data = self.value_from_table(foreign_refs[field_name], field_value)
else:
data = [self.value_from_table(foreign_refs[field_name], val) for val in json.loads(field_value)]
else:
data = field_value if not iterable_in_type_repr(type_repr) else json.loads(field_value)
d.update({field_name: data})
return basemodel.moduleclass(**d)
def _upsert_value_in_foreign_table(self, field_value, foreign_table_name, update_nested_models) -> Union[str, List[str]]:
foreign_refs = {key.column: key.other_table for key in self._db.table(foreign_table_name).foreign_keys}
def add_nested_model(value):
if not self.value_in_table(foreign_table_name, value) or update_nested_models:
self.add(foreign_table_name, value, foreign_tables=foreign_refs)
return value.uuid
if not isinstance(field_value, List):
return add_nested_model(field_value)
else:
return [add_nested_model(element) for element in field_value]
def _typing_conversion(self, field: ModelField, field_value: typing) -> typing.Any:
if field.type_ == typing.Any:
return field_value
elif is_union_type(field.type_):
return str(field_value)
elif is_literal_type(field.type_):
return str(field_value)
else:
raise NotImplementedError(f"type {field.type_} is not supported yet")
| true | true |
f7317ac183acdc3fef988d0b36002f1c1f9db05e | 7,610 | py | Python | env/lib/python3.6/site-packages/nibabel/tests/test_filename_parser.py | Raniac/NEURO-LEARN | 3c3acc55de8ba741e673063378e6cbaf10b64c7a | [
"Apache-2.0"
] | 8 | 2019-05-29T09:38:30.000Z | 2021-01-20T03:36:59.000Z | env/lib/python3.6/site-packages/nibabel/tests/test_filename_parser.py | Raniac/neurolearn_dev | 3c3acc55de8ba741e673063378e6cbaf10b64c7a | [
"Apache-2.0"
] | 12 | 2021-03-09T03:01:16.000Z | 2022-03-11T23:59:36.000Z | env/lib/python3.6/site-packages/nibabel/tests/test_filename_parser.py | Raniac/NEURO-LEARN | 3c3acc55de8ba741e673063378e6cbaf10b64c7a | [
"Apache-2.0"
] | 1 | 2020-07-17T12:49:49.000Z | 2020-07-17T12:49:49.000Z | # emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the NiBabel package for the
# copyright and license terms.
#
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
''' Tests for filename container '''
from ..filename_parser import (types_filenames, TypesFilenamesError,
parse_filename, splitext_addext)
from nose.tools import (assert_equal, assert_true, assert_false,
assert_raises)
def test_filenames():
types_exts = (('image', '.img'), ('header', '.hdr'))
for t_fname in ('test.img', 'test.hdr', 'test', 'test.'):
tfns = types_filenames(t_fname, types_exts)
assert_equal(tfns,
{'image': 'test.img',
'header': 'test.hdr'})
# enforcing extensions raises an error for bad extension
assert_raises(TypesFilenamesError,
types_filenames,
'test.funny',
types_exts)
# If not enforcing extensions, it does the best job it can,
# assuming the passed filename is for the first type (in this case
# 'image')
tfns = types_filenames('test.funny', types_exts,
enforce_extensions=False)
assert_equal(tfns,
{'header': 'test.hdr',
'image': 'test.funny'})
# .gz and .bz2 suffixes to extensions, by default, are removed
# before extension checking etc, and then put back onto every
# returned filename.
tfns = types_filenames('test.img.gz', types_exts)
assert_equal(tfns,
{'header': 'test.hdr.gz',
'image': 'test.img.gz'})
tfns = types_filenames('test.img.bz2', types_exts)
assert_equal(tfns,
{'header': 'test.hdr.bz2',
'image': 'test.img.bz2'})
# of course, if we don't know about e.g. gz, and enforce_extensions
# is on, we get an errror
assert_raises(TypesFilenamesError,
types_filenames,
'test.img.gz',
types_exts, ())
# if we don't know about .gz extension, and not enforcing, then we
# get something a bit odd
tfns = types_filenames('test.img.gz', types_exts,
trailing_suffixes=(),
enforce_extensions=False)
assert_equal(tfns,
{'header': 'test.img.hdr',
'image': 'test.img.gz'})
# the suffixes we remove and replaces can be any suffixes.
tfns = types_filenames('test.img.bzr', types_exts, ('.bzr',))
assert_equal(tfns,
{'header': 'test.hdr.bzr',
'image': 'test.img.bzr'})
# If we specifically pass the remove / replace suffixes, then we
# don't remove / replace the .gz and .bz2, unless they are passed
# specifically.
tfns = types_filenames('test.img.bzr', types_exts,
trailing_suffixes=('.bzr',),
enforce_extensions=False)
assert_equal(tfns,
{'header': 'test.hdr.bzr',
'image': 'test.img.bzr'})
# but, just .gz or .bz2 as extension gives an error, if enforcing is on
assert_raises(TypesFilenamesError,
types_filenames,
'test.gz',
types_exts)
assert_raises(TypesFilenamesError,
types_filenames,
'test.bz2',
types_exts)
# if enforcing is off, it tries to work out what the other files
# should be assuming the passed filename is of the first input type
tfns = types_filenames('test.gz', types_exts,
enforce_extensions=False)
assert_equal(tfns,
{'image': 'test.gz',
'header': 'test.hdr.gz'})
# case (in)sensitivity, and effect of uppercase, lowercase
tfns = types_filenames('test.IMG', types_exts)
assert_equal(tfns,
{'image': 'test.IMG',
'header': 'test.HDR'})
tfns = types_filenames('test.img',
(('image', '.IMG'), ('header', '.HDR')))
assert_equal(tfns,
{'header': 'test.hdr',
'image': 'test.img'})
tfns = types_filenames('test.IMG.Gz', types_exts)
assert_equal(tfns,
{'image': 'test.IMG.Gz',
'header': 'test.HDR.Gz'})
def test_parse_filename():
types_exts = (('t1', 'ext1'), ('t2', 'ext2'))
exp_in_outs = (
(('/path/fname.funny', ()),
('/path/fname', '.funny', None, None)),
(('/path/fnameext2', ()),
('/path/fname', 'ext2', None, 't2')),
(('/path/fnameext2', ('.gz',)),
('/path/fname', 'ext2', None, 't2')),
(('/path/fnameext2.gz', ('.gz',)),
('/path/fname', 'ext2', '.gz', 't2'))
)
for inps, exps in exp_in_outs:
pth, sufs = inps
res = parse_filename(pth, types_exts, sufs)
assert_equal(res, exps)
upth = pth.upper()
uexps = (exps[0].upper(), exps[1].upper(),
exps[2].upper() if exps[2] else None,
exps[3])
res = parse_filename(upth, types_exts, sufs)
assert_equal(res, uexps)
# test case sensitivity
res = parse_filename('/path/fnameext2.GZ',
types_exts,
('.gz',), False) # case insensitive again
assert_equal(res, ('/path/fname', 'ext2', '.GZ', 't2'))
res = parse_filename('/path/fnameext2.GZ',
types_exts,
('.gz',), True) # case sensitive
assert_equal(res, ('/path/fnameext2', '.GZ', None, None))
res = parse_filename('/path/fnameEXT2.gz',
types_exts,
('.gz',), False) # case insensitive
assert_equal(res, ('/path/fname', 'EXT2', '.gz', 't2'))
res = parse_filename('/path/fnameEXT2.gz',
types_exts,
('.gz',), True) # case sensitive
assert_equal(res, ('/path/fnameEXT2', '', '.gz', None))
def test_splitext_addext():
res = splitext_addext('fname.ext.gz')
assert_equal(res, ('fname', '.ext', '.gz'))
res = splitext_addext('fname.ext')
assert_equal(res, ('fname', '.ext', ''))
res = splitext_addext('fname.ext.foo', ('.foo', '.bar'))
assert_equal(res, ('fname', '.ext', '.foo'))
res = splitext_addext('fname.ext.FOO', ('.foo', '.bar'))
assert_equal(res, ('fname', '.ext', '.FOO'))
# case sensitive
res = splitext_addext('fname.ext.FOO', ('.foo', '.bar'), True)
assert_equal(res, ('fname.ext', '.FOO', ''))
# edge cases
res = splitext_addext('.nii')
assert_equal(res, ('', '.nii', ''))
res = splitext_addext('...nii')
assert_equal(res, ('..', '.nii', ''))
res = splitext_addext('.')
assert_equal(res, ('.', '', ''))
res = splitext_addext('..')
assert_equal(res, ('..', '', ''))
res = splitext_addext('...')
assert_equal(res, ('...', '', ''))
| 43.988439 | 79 | 0.49724 |
.upper(), exps[1].upper(),
exps[2].upper() if exps[2] else None,
exps[3])
res = parse_filename(upth, types_exts, sufs)
assert_equal(res, uexps)
# test case sensitivity
res = parse_filename('/path/fnameext2.GZ',
types_exts,
('.gz',), False) # case insensitive again
assert_equal(res, ('/path/fname', 'ext2', '.GZ', 't2'))
res = parse_filename('/path/fnameext2.GZ',
types_exts,
('.gz',), True) # case sensitive
assert_equal(res, ('/path/fnameext2', '.GZ', None, None))
res = parse_filename('/path/fnameEXT2.gz',
types_exts,
('.gz',), False) # case insensitive
assert_equal(res, ('/path/fname', 'EXT2', '.gz', 't2'))
res = parse_filename('/path/fnameEXT2.gz',
types_exts,
('.gz',), True) # case sensitive
assert_equal(res, ('/path/fnameEXT2', '', '.gz', None))
def test_splitext_addext():
res = splitext_addext('fname.ext.gz')
assert_equal(res, ('fname', '.ext', '.gz'))
res = splitext_addext('fname.ext')
assert_equal(res, ('fname', '.ext', ''))
res = splitext_addext('fname.ext.foo', ('.foo', '.bar'))
assert_equal(res, ('fname', '.ext', '.foo'))
res = splitext_addext('fname.ext.FOO', ('.foo', '.bar'))
assert_equal(res, ('fname', '.ext', '.FOO'))
# case sensitive
res = splitext_addext('fname.ext.FOO', ('.foo', '.bar'), True)
assert_equal(res, ('fname.ext', '.FOO', ''))
# edge cases
res = splitext_addext('.nii')
assert_equal(res, ('', '.nii', ''))
res = splitext_addext('...nii')
assert_equal(res, ('..', '.nii', ''))
res = splitext_addext('.')
assert_equal(res, ('.', '', ''))
res = splitext_addext('..')
assert_equal(res, ('..', '', ''))
res = splitext_addext('...')
assert_equal(res, ('...', '', ''))
| true | true |
f7317b0eda9c7facface10dbec8642b54e7fc9d2 | 2,521 | py | Python | polling_stations/apps/data_collection/management/commands/import_tower_hamlets.py | chris48s/UK-Polling-Stations | 4742b527dae94f0276d35c80460837be743b7d17 | [
"BSD-3-Clause"
] | null | null | null | polling_stations/apps/data_collection/management/commands/import_tower_hamlets.py | chris48s/UK-Polling-Stations | 4742b527dae94f0276d35c80460837be743b7d17 | [
"BSD-3-Clause"
] | null | null | null | polling_stations/apps/data_collection/management/commands/import_tower_hamlets.py | chris48s/UK-Polling-Stations | 4742b527dae94f0276d35c80460837be743b7d17 | [
"BSD-3-Clause"
] | null | null | null | """
Import Tower Hamlets
"""
from time import sleep
from django.contrib.gis.geos import Point
from data_collection.management.commands import BaseCsvStationsCsvAddressesImporter
from data_finder.helpers import geocode, geocode_point_only, PostcodeError
from addressbase.models import Address
class Command(BaseCsvStationsCsvAddressesImporter):
"""
Imports the Polling Station data from Tower Hamlets Council
"""
council_id = 'E09000030'
addresses_name = '2016/Polling Stations with Addresses.csv'
stations_name = '2016/Polling Stations with Addresses.csv'
csv_delimiter = ','
elections = [
'ref.2016-06-23'
]
def get_station_hash(self, record):
return "-".join([
record.station_na,
record.code,
record.polling_na,
])
def station_record_to_dict(self, record):
if not record.polling_na:
return
# format address
address = record.station_na
while "\n\n" in address:
address = address.replace("\n\n", "\n").strip()
postcode = " ".join(address.split(' ')[-2:]).strip().split('\n')[-1]
location = None
if float(record.polling_station_x) and float(record.polling_station_y):
if "Shapla Primary School" in address:
location = Point(
-0.066990,
51.510020,
srid=4326
)
else:
location = Point(
float(record.polling_station_x),
float(record.polling_station_y),
srid=27700)
else:
# no points supplied, so attempt to attach them by geocoding
try:
location_data = geocode_point_only(postcode)
except PostcodeError:
pass
if location_data:
location = Point(
location_data['wgs84_lon'],
location_data['wgs84_lat'],
srid=4326)
return {
'internal_council_id': record.code,
'postcode' : postcode,
'address' : address,
'location' : location
}
def address_record_to_dict(self, record):
return {
'address' : record.fulladdress.strip(),
'postcode' : record.postcode.strip(),
'polling_station_id': record.code
}
| 31.5125 | 83 | 0.548195 | from time import sleep
from django.contrib.gis.geos import Point
from data_collection.management.commands import BaseCsvStationsCsvAddressesImporter
from data_finder.helpers import geocode, geocode_point_only, PostcodeError
from addressbase.models import Address
class Command(BaseCsvStationsCsvAddressesImporter):
council_id = 'E09000030'
addresses_name = '2016/Polling Stations with Addresses.csv'
stations_name = '2016/Polling Stations with Addresses.csv'
csv_delimiter = ','
elections = [
'ref.2016-06-23'
]
def get_station_hash(self, record):
return "-".join([
record.station_na,
record.code,
record.polling_na,
])
def station_record_to_dict(self, record):
if not record.polling_na:
return
address = record.station_na
while "\n\n" in address:
address = address.replace("\n\n", "\n").strip()
postcode = " ".join(address.split(' ')[-2:]).strip().split('\n')[-1]
location = None
if float(record.polling_station_x) and float(record.polling_station_y):
if "Shapla Primary School" in address:
location = Point(
-0.066990,
51.510020,
srid=4326
)
else:
location = Point(
float(record.polling_station_x),
float(record.polling_station_y),
srid=27700)
else:
try:
location_data = geocode_point_only(postcode)
except PostcodeError:
pass
if location_data:
location = Point(
location_data['wgs84_lon'],
location_data['wgs84_lat'],
srid=4326)
return {
'internal_council_id': record.code,
'postcode' : postcode,
'address' : address,
'location' : location
}
def address_record_to_dict(self, record):
return {
'address' : record.fulladdress.strip(),
'postcode' : record.postcode.strip(),
'polling_station_id': record.code
}
| true | true |
f7317c3b8b64c75edaf8033692d2b70b5b070677 | 10,874 | py | Python | test/shake_test.py | arkottke/MapIO | dd6e347dce2d65b7bd4c489a03d8883d0e4210fc | [
"CC0-1.0"
] | null | null | null | test/shake_test.py | arkottke/MapIO | dd6e347dce2d65b7bd4c489a03d8883d0e4210fc | [
"CC0-1.0"
] | null | null | null | test/shake_test.py | arkottke/MapIO | dd6e347dce2d65b7bd4c489a03d8883d0e4210fc | [
"CC0-1.0"
] | 1 | 2019-11-09T16:05:37.000Z | 2019-11-09T16:05:37.000Z | #!/usr/bin/env python
#python 3 compatibility
from __future__ import print_function
#stdlib imports
from xml.dom import minidom
from datetime import datetime
from collections import OrderedDict
import re
import sys
import tempfile
import time
import shutil
if sys.version_info.major == 2:
import StringIO
else:
from io import StringIO
import os.path
#hack the path so that I can debug these functions if I need to
homedir = os.path.dirname(os.path.abspath(__file__)) #where is this script?
mapiodir = os.path.abspath(os.path.join(homedir,'..'))
sys.path.insert(0,mapiodir) #put this at the front of the system path, ignoring any installed mapio stuff
#third party
from mapio.shake import ShakeGrid
from mapio.gridbase import Grid
from mapio.multiple import MultiGrid
from mapio.dataset import DataSetException
from mapio.grid2d import Grid2D
from mapio.geodict import GeoDict
import numpy as np
def test_modify():
print('Testing ShakeGrid interpolate() method...')
geodict = GeoDict({'xmin':0.5,'xmax':6.5,'ymin':1.5,'ymax':6.5,'dx':1.0,'dy':1.0,'ny':6,'nx':7})
data = np.arange(14,56).reshape(6,7)
layers = OrderedDict()
layers['pga'] = data
shakeDict = {'event_id':'usabcd1234',
'shakemap_id':'usabcd1234',
'shakemap_version':1,
'code_version':'4.0',
'process_timestamp':datetime.utcnow(),
'shakemap_originator':'us',
'map_status':'RELEASED',
'shakemap_event_type':'ACTUAL'}
eventDict = {'event_id':'usabcd1234',
'magnitude':7.6,
'depth':1.4,
'lat':2.0,
'lon':2.0,
'event_timestamp':datetime.utcnow(),
'event_network':'us',
'event_description':'sample event'}
uncDict = {'pga':(0.0,0)}
shake = ShakeGrid(layers,geodict,eventDict,shakeDict,uncDict)
rdata = np.random.rand(data.shape[0],data.shape[1])
shake.setLayer('pga',rdata)
newdata = shake.getLayer('pga').getData()
np.testing.assert_almost_equal(rdata,newdata)
def test_interpolate():
print('Testing ShakeGrid interpolate() method...')
geodict = GeoDict({'xmin':0.5,'xmax':6.5,'ymin':1.5,'ymax':6.5,'dx':1.0,'dy':1.0,'ny':6,'nx':7})
data = np.arange(14,56).reshape(6,7)
layers = OrderedDict()
layers['pga'] = data
shakeDict = {'event_id':'usabcd1234',
'shakemap_id':'usabcd1234',
'shakemap_version':1,
'code_version':'4.0',
'process_timestamp':datetime.utcnow(),
'shakemap_originator':'us',
'map_status':'RELEASED',
'shakemap_event_type':'ACTUAL'}
eventDict = {'event_id':'usabcd1234',
'magnitude':7.6,
'depth':1.4,
'lat':2.0,
'lon':2.0,
'event_timestamp':datetime.utcnow(),
'event_network':'us',
'event_description':'sample event'}
uncDict = {'pga':(0.0,0)}
shake = ShakeGrid(layers,geodict,eventDict,shakeDict,uncDict)
sampledict = GeoDict({'xmin':3.0,'xmax':4.0,
'ymin':3.0,'ymax':4.0,
'dx':1.0,'dy':1.0,
'ny':2,'nx':2})
shake2 = shake.interpolateToGrid(sampledict,method='linear')
output = np.array([[34.,35.],[41.,42.]])
np.testing.assert_almost_equal(output,shake2.getLayer('pga').getData())
print('Passed test of ShakeGrid interpolate() method.')
def test_read():
xmlfile = os.path.join(homedir,'data','northridge.xml')
tdir = tempfile.mkdtemp()
testfile = os.path.join(tdir,'test.xml')
try:
shakegrid = ShakeGrid.load(xmlfile,adjust='res')
t1 = time.time()
shakegrid.save(testfile)
t2 = time.time()
print('Saving shakemap took %.2f seconds' % (t2-t1))
except Exception as error:
print('Failed to read grid.xml format file "%s". Error "%s".' % (xmlfile,str(error)))
assert 0 == 1
finally:
if os.path.isdir(tdir):
shutil.rmtree(tdir)
def test_save():
tdir = tempfile.mkdtemp()
testfile = os.path.join(tdir,'test.xml')
try:
print('Testing save/read functionality for shakemap grids...')
pga = np.arange(0,16,dtype=np.float32).reshape(4,4)
pgv = np.arange(1,17,dtype=np.float32).reshape(4,4)
mmi = np.arange(2,18,dtype=np.float32).reshape(4,4)
geodict = GeoDict({'xmin':0.5,'xmax':3.5,
'ymin':0.5,'ymax':3.5,
'dx':1.0,'dy':1.0,
'ny':4,'nx':4})
layers = OrderedDict()
layers['pga'] = pga
layers['pgv'] = pgv
layers['mmi'] = mmi
shakeDict = {'event_id':'usabcd1234',
'shakemap_id':'usabcd1234',
'shakemap_version':1,
'code_version':'4.0',
'process_timestamp':datetime.utcnow(),
'shakemap_originator':'us',
'map_status':'RELEASED',
'shakemap_event_type':'ACTUAL'}
eventDict = {'event_id':'usabcd1234',
'magnitude':7.6,
'depth':1.4,
'lat':2.0,
'lon':2.0,
'event_timestamp':datetime.utcnow(),
'event_network':'us',
'event_description':'sample event'}
uncDict = {'pga':(0.0,0),
'pgv':(0.0,0),
'mmi':(0.0,0)}
shake = ShakeGrid(layers,geodict,eventDict,shakeDict,uncDict)
print('Testing save/read functionality...')
shake.save(testfile,version=3)
shake2 = ShakeGrid.load(testfile)
for layer in ['pga','pgv','mmi']:
tdata = shake2.getLayer(layer).getData()
np.testing.assert_almost_equal(tdata,layers[layer])
print('Passed save/read functionality for shakemap grids.')
print('Testing getFileGeoDict method...')
fgeodict = ShakeGrid.getFileGeoDict(testfile)
print('Passed save/read functionality for shakemap grids.')
print('Testing loading with bounds (no resampling or padding)...')
sampledict = GeoDict({'xmin':-0.5,'xmax':3.5,
'ymin':-0.5,'ymax':3.5,
'dx':1.0,'dy':1.0,
'ny':5,'nx':5})
shake3 = ShakeGrid.load(testfile,samplegeodict=sampledict,
resample=False,doPadding=False,padValue=np.nan)
tdata = shake3.getLayer('pga').getData()
np.testing.assert_almost_equal(tdata,layers['pga'])
print('Passed loading with bounds (no resampling or padding)...')
print('Testing loading shakemap with padding, no resampling...')
newdict = GeoDict({'xmin':-0.5,'xmax':4.5,
'ymin':-0.5,'ymax':4.5,
'dx':1.0,'dy':1.0,
'ny':6,'nx':6})
shake4 = ShakeGrid.load(testfile,samplegeodict=newdict,
resample=False,doPadding=True,padValue=np.nan)
output = np.array([[np.nan,np.nan,np.nan,np.nan,np.nan,np.nan],
[np.nan,0.0,1.0,2.0,3.0,np.nan],
[np.nan,4.0,5.0,6.0,7.0,np.nan],
[np.nan,8.0,9.0,10.0,11.0,np.nan],
[np.nan,12.0,13.0,14.0,15.0,np.nan],
[np.nan,np.nan,np.nan,np.nan,np.nan,np.nan]])
tdata = shake4.getLayer('pga').getData()
np.testing.assert_almost_equal(tdata,output)
print('Passed loading shakemap with padding, no resampling...')
#make a bigger grid
pga = np.arange(0,36,dtype=np.float32).reshape(6,6)
pgv = np.arange(1,37,dtype=np.float32).reshape(6,6)
mmi = np.arange(2,38,dtype=np.float32).reshape(6,6)
layers = OrderedDict()
layers['pga'] = pga
layers['pgv'] = pgv
layers['mmi'] = mmi
geodict = GeoDict({'xmin':0.5,'xmax':5.5,
'ymin':0.5,'ymax':5.5,
'dx':1.0,'dy':1.0,
'ny':6,'nx':6})
shake = ShakeGrid(layers,geodict,eventDict,shakeDict,uncDict)
shake.save(testfile,version=3)
print('Testing resampling, no padding...')
littledict = GeoDict({'xmin':2.0,'xmax':4.0,
'ymin':2.0,'ymax':4.0,
'dx':1.0,'dy':1.0,
'ny':3,'nx':3})
shake5 = ShakeGrid.load(testfile,samplegeodict=littledict,resample=True,doPadding=False,padValue=np.nan)
output = np.array([[10.5,11.5,12.5],
[16.5,17.5,18.5],
[22.5,23.5,24.5]])
tdata = shake5.getLayer('pga').getData()
np.testing.assert_almost_equal(tdata,output)
print('Passed resampling, no padding...')
print('Testing resampling and padding...')
pga = np.arange(0,16,dtype=np.float32).reshape(4,4)
pgv = np.arange(1,17,dtype=np.float32).reshape(4,4)
mmi = np.arange(2,18,dtype=np.float32).reshape(4,4)
geodict = GeoDict({'xmin':0.5,'ymax':3.5,
'ymin':0.5,'xmax':3.5,
'dx':1.0,'dy':1.0,
'ny':4,'nx':4})
layers = OrderedDict()
layers['pga'] = pga
layers['pgv'] = pgv
layers['mmi'] = mmi
shake = ShakeGrid(layers,geodict,eventDict,shakeDict,uncDict)
shake.save(testfile,version=3)
bigdict = GeoDict({'xmin':0.0,'xmax':4.0,
'ymin':0.0,'ymax':4.0,
'dx':1.0,'dy':1.0,
'ny':5,'nx':5})
shake6 = ShakeGrid.load(testfile,samplegeodict=bigdict,resample=True,doPadding=True,padValue=np.nan)
tdata = shake6.getLayer('pga').getData()
output = np.array([[np.nan,np.nan,np.nan,np.nan,np.nan],
[np.nan,2.5,3.5,4.5,np.nan],
[np.nan,6.5,7.5,8.5,np.nan],
[np.nan,10.5,11.5,12.5,np.nan],
[np.nan,np.nan,np.nan,np.nan,np.nan]])
np.testing.assert_almost_equal(tdata,output)
print('Passed resampling and padding...')
except Exception as error:
print('Failed to read grid.xml format file "%s". Error "%s".' % (xmlfile,str(error)))
assert 0 == 1
finally:
if os.path.isdir(tdir):
shutil.rmtree(tdir)
if __name__ == '__main__':
test_modify()
test_interpolate()
test_read()
test_save()
| 41.503817 | 112 | 0.532279 |
from __future__ import print_function
from xml.dom import minidom
from datetime import datetime
from collections import OrderedDict
import re
import sys
import tempfile
import time
import shutil
if sys.version_info.major == 2:
import StringIO
else:
from io import StringIO
import os.path
homedir = os.path.dirname(os.path.abspath(__file__))
mapiodir = os.path.abspath(os.path.join(homedir,'..'))
sys.path.insert(0,mapiodir)
from mapio.shake import ShakeGrid
from mapio.gridbase import Grid
from mapio.multiple import MultiGrid
from mapio.dataset import DataSetException
from mapio.grid2d import Grid2D
from mapio.geodict import GeoDict
import numpy as np
def test_modify():
print('Testing ShakeGrid interpolate() method...')
geodict = GeoDict({'xmin':0.5,'xmax':6.5,'ymin':1.5,'ymax':6.5,'dx':1.0,'dy':1.0,'ny':6,'nx':7})
data = np.arange(14,56).reshape(6,7)
layers = OrderedDict()
layers['pga'] = data
shakeDict = {'event_id':'usabcd1234',
'shakemap_id':'usabcd1234',
'shakemap_version':1,
'code_version':'4.0',
'process_timestamp':datetime.utcnow(),
'shakemap_originator':'us',
'map_status':'RELEASED',
'shakemap_event_type':'ACTUAL'}
eventDict = {'event_id':'usabcd1234',
'magnitude':7.6,
'depth':1.4,
'lat':2.0,
'lon':2.0,
'event_timestamp':datetime.utcnow(),
'event_network':'us',
'event_description':'sample event'}
uncDict = {'pga':(0.0,0)}
shake = ShakeGrid(layers,geodict,eventDict,shakeDict,uncDict)
rdata = np.random.rand(data.shape[0],data.shape[1])
shake.setLayer('pga',rdata)
newdata = shake.getLayer('pga').getData()
np.testing.assert_almost_equal(rdata,newdata)
def test_interpolate():
print('Testing ShakeGrid interpolate() method...')
geodict = GeoDict({'xmin':0.5,'xmax':6.5,'ymin':1.5,'ymax':6.5,'dx':1.0,'dy':1.0,'ny':6,'nx':7})
data = np.arange(14,56).reshape(6,7)
layers = OrderedDict()
layers['pga'] = data
shakeDict = {'event_id':'usabcd1234',
'shakemap_id':'usabcd1234',
'shakemap_version':1,
'code_version':'4.0',
'process_timestamp':datetime.utcnow(),
'shakemap_originator':'us',
'map_status':'RELEASED',
'shakemap_event_type':'ACTUAL'}
eventDict = {'event_id':'usabcd1234',
'magnitude':7.6,
'depth':1.4,
'lat':2.0,
'lon':2.0,
'event_timestamp':datetime.utcnow(),
'event_network':'us',
'event_description':'sample event'}
uncDict = {'pga':(0.0,0)}
shake = ShakeGrid(layers,geodict,eventDict,shakeDict,uncDict)
sampledict = GeoDict({'xmin':3.0,'xmax':4.0,
'ymin':3.0,'ymax':4.0,
'dx':1.0,'dy':1.0,
'ny':2,'nx':2})
shake2 = shake.interpolateToGrid(sampledict,method='linear')
output = np.array([[34.,35.],[41.,42.]])
np.testing.assert_almost_equal(output,shake2.getLayer('pga').getData())
print('Passed test of ShakeGrid interpolate() method.')
def test_read():
xmlfile = os.path.join(homedir,'data','northridge.xml')
tdir = tempfile.mkdtemp()
testfile = os.path.join(tdir,'test.xml')
try:
shakegrid = ShakeGrid.load(xmlfile,adjust='res')
t1 = time.time()
shakegrid.save(testfile)
t2 = time.time()
print('Saving shakemap took %.2f seconds' % (t2-t1))
except Exception as error:
print('Failed to read grid.xml format file "%s". Error "%s".' % (xmlfile,str(error)))
assert 0 == 1
finally:
if os.path.isdir(tdir):
shutil.rmtree(tdir)
def test_save():
tdir = tempfile.mkdtemp()
testfile = os.path.join(tdir,'test.xml')
try:
print('Testing save/read functionality for shakemap grids...')
pga = np.arange(0,16,dtype=np.float32).reshape(4,4)
pgv = np.arange(1,17,dtype=np.float32).reshape(4,4)
mmi = np.arange(2,18,dtype=np.float32).reshape(4,4)
geodict = GeoDict({'xmin':0.5,'xmax':3.5,
'ymin':0.5,'ymax':3.5,
'dx':1.0,'dy':1.0,
'ny':4,'nx':4})
layers = OrderedDict()
layers['pga'] = pga
layers['pgv'] = pgv
layers['mmi'] = mmi
shakeDict = {'event_id':'usabcd1234',
'shakemap_id':'usabcd1234',
'shakemap_version':1,
'code_version':'4.0',
'process_timestamp':datetime.utcnow(),
'shakemap_originator':'us',
'map_status':'RELEASED',
'shakemap_event_type':'ACTUAL'}
eventDict = {'event_id':'usabcd1234',
'magnitude':7.6,
'depth':1.4,
'lat':2.0,
'lon':2.0,
'event_timestamp':datetime.utcnow(),
'event_network':'us',
'event_description':'sample event'}
uncDict = {'pga':(0.0,0),
'pgv':(0.0,0),
'mmi':(0.0,0)}
shake = ShakeGrid(layers,geodict,eventDict,shakeDict,uncDict)
print('Testing save/read functionality...')
shake.save(testfile,version=3)
shake2 = ShakeGrid.load(testfile)
for layer in ['pga','pgv','mmi']:
tdata = shake2.getLayer(layer).getData()
np.testing.assert_almost_equal(tdata,layers[layer])
print('Passed save/read functionality for shakemap grids.')
print('Testing getFileGeoDict method...')
fgeodict = ShakeGrid.getFileGeoDict(testfile)
print('Passed save/read functionality for shakemap grids.')
print('Testing loading with bounds (no resampling or padding)...')
sampledict = GeoDict({'xmin':-0.5,'xmax':3.5,
'ymin':-0.5,'ymax':3.5,
'dx':1.0,'dy':1.0,
'ny':5,'nx':5})
shake3 = ShakeGrid.load(testfile,samplegeodict=sampledict,
resample=False,doPadding=False,padValue=np.nan)
tdata = shake3.getLayer('pga').getData()
np.testing.assert_almost_equal(tdata,layers['pga'])
print('Passed loading with bounds (no resampling or padding)...')
print('Testing loading shakemap with padding, no resampling...')
newdict = GeoDict({'xmin':-0.5,'xmax':4.5,
'ymin':-0.5,'ymax':4.5,
'dx':1.0,'dy':1.0,
'ny':6,'nx':6})
shake4 = ShakeGrid.load(testfile,samplegeodict=newdict,
resample=False,doPadding=True,padValue=np.nan)
output = np.array([[np.nan,np.nan,np.nan,np.nan,np.nan,np.nan],
[np.nan,0.0,1.0,2.0,3.0,np.nan],
[np.nan,4.0,5.0,6.0,7.0,np.nan],
[np.nan,8.0,9.0,10.0,11.0,np.nan],
[np.nan,12.0,13.0,14.0,15.0,np.nan],
[np.nan,np.nan,np.nan,np.nan,np.nan,np.nan]])
tdata = shake4.getLayer('pga').getData()
np.testing.assert_almost_equal(tdata,output)
print('Passed loading shakemap with padding, no resampling...')
pga = np.arange(0,36,dtype=np.float32).reshape(6,6)
pgv = np.arange(1,37,dtype=np.float32).reshape(6,6)
mmi = np.arange(2,38,dtype=np.float32).reshape(6,6)
layers = OrderedDict()
layers['pga'] = pga
layers['pgv'] = pgv
layers['mmi'] = mmi
geodict = GeoDict({'xmin':0.5,'xmax':5.5,
'ymin':0.5,'ymax':5.5,
'dx':1.0,'dy':1.0,
'ny':6,'nx':6})
shake = ShakeGrid(layers,geodict,eventDict,shakeDict,uncDict)
shake.save(testfile,version=3)
print('Testing resampling, no padding...')
littledict = GeoDict({'xmin':2.0,'xmax':4.0,
'ymin':2.0,'ymax':4.0,
'dx':1.0,'dy':1.0,
'ny':3,'nx':3})
shake5 = ShakeGrid.load(testfile,samplegeodict=littledict,resample=True,doPadding=False,padValue=np.nan)
output = np.array([[10.5,11.5,12.5],
[16.5,17.5,18.5],
[22.5,23.5,24.5]])
tdata = shake5.getLayer('pga').getData()
np.testing.assert_almost_equal(tdata,output)
print('Passed resampling, no padding...')
print('Testing resampling and padding...')
pga = np.arange(0,16,dtype=np.float32).reshape(4,4)
pgv = np.arange(1,17,dtype=np.float32).reshape(4,4)
mmi = np.arange(2,18,dtype=np.float32).reshape(4,4)
geodict = GeoDict({'xmin':0.5,'ymax':3.5,
'ymin':0.5,'xmax':3.5,
'dx':1.0,'dy':1.0,
'ny':4,'nx':4})
layers = OrderedDict()
layers['pga'] = pga
layers['pgv'] = pgv
layers['mmi'] = mmi
shake = ShakeGrid(layers,geodict,eventDict,shakeDict,uncDict)
shake.save(testfile,version=3)
bigdict = GeoDict({'xmin':0.0,'xmax':4.0,
'ymin':0.0,'ymax':4.0,
'dx':1.0,'dy':1.0,
'ny':5,'nx':5})
shake6 = ShakeGrid.load(testfile,samplegeodict=bigdict,resample=True,doPadding=True,padValue=np.nan)
tdata = shake6.getLayer('pga').getData()
output = np.array([[np.nan,np.nan,np.nan,np.nan,np.nan],
[np.nan,2.5,3.5,4.5,np.nan],
[np.nan,6.5,7.5,8.5,np.nan],
[np.nan,10.5,11.5,12.5,np.nan],
[np.nan,np.nan,np.nan,np.nan,np.nan]])
np.testing.assert_almost_equal(tdata,output)
print('Passed resampling and padding...')
except Exception as error:
print('Failed to read grid.xml format file "%s". Error "%s".' % (xmlfile,str(error)))
assert 0 == 1
finally:
if os.path.isdir(tdir):
shutil.rmtree(tdir)
if __name__ == '__main__':
test_modify()
test_interpolate()
test_read()
test_save()
| true | true |
f7317c790976f2907b99356b3b5fdcac78c33a12 | 1,014 | py | Python | python/tests/integration/postgres/test_postgres_results.py | Vjrx/airship-drydock | 315fb9864e6d55a66d5266f76c160be55d22c98b | [
"Apache-2.0"
] | 14 | 2017-03-07T17:00:22.000Z | 2021-04-02T14:15:04.000Z | python/tests/integration/postgres/test_postgres_results.py | Vjrx/airship-drydock | 315fb9864e6d55a66d5266f76c160be55d22c98b | [
"Apache-2.0"
] | 82 | 2017-02-16T16:54:18.000Z | 2018-06-04T13:40:32.000Z | python/tests/integration/postgres/test_postgres_results.py | Vjrx/airship-drydock | 315fb9864e6d55a66d5266f76c160be55d22c98b | [
"Apache-2.0"
] | 16 | 2017-02-14T19:47:00.000Z | 2018-04-26T10:13:05.000Z | import pytest
from drydock_provisioner import objects
class TestPostgres(object):
def test_result_message_insert(self, populateddb, drydock_state):
"""Test that a result message for a task can be added."""
msg1 = objects.TaskStatusMessage('Error 1', True, 'node', 'node1')
msg2 = objects.TaskStatusMessage('Status 1', False, 'node', 'node1')
result = drydock_state.post_result_message(populateddb.task_id, msg1)
assert result
result = drydock_state.post_result_message(populateddb.task_id, msg2)
assert result
task = drydock_state.get_task(populateddb.task_id)
assert task.result.error_count == 1
assert len(task.result.message_list) == 2
@pytest.fixture(scope='function')
def populateddb(self, blank_state):
"""Add dummy task to test against."""
task = objects.Task(
action='prepare_site', design_ref='http://test.com/design')
blank_state.post_task(task)
return task
| 31.6875 | 77 | 0.675542 | import pytest
from drydock_provisioner import objects
class TestPostgres(object):
def test_result_message_insert(self, populateddb, drydock_state):
msg1 = objects.TaskStatusMessage('Error 1', True, 'node', 'node1')
msg2 = objects.TaskStatusMessage('Status 1', False, 'node', 'node1')
result = drydock_state.post_result_message(populateddb.task_id, msg1)
assert result
result = drydock_state.post_result_message(populateddb.task_id, msg2)
assert result
task = drydock_state.get_task(populateddb.task_id)
assert task.result.error_count == 1
assert len(task.result.message_list) == 2
@pytest.fixture(scope='function')
def populateddb(self, blank_state):
task = objects.Task(
action='prepare_site', design_ref='http://test.com/design')
blank_state.post_task(task)
return task
| true | true |
f7317c8199b599b34a14ce19dda9e2ac6e37c688 | 42,329 | py | Python | modin/pandas/test/dataframe/test_map_metadata.py | palash247/modin | 3f1e275b67a760f09db6944600c4b7f5e601cbde | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | modin/pandas/test/dataframe/test_map_metadata.py | palash247/modin | 3f1e275b67a760f09db6944600c4b7f5e601cbde | [
"ECL-2.0",
"Apache-2.0"
] | 46 | 2020-08-28T09:12:51.000Z | 2021-04-20T00:01:04.000Z | modin/pandas/test/dataframe/test_map_metadata.py | monocilindro/modin | ffea4ee2d3556dc48c05dac7abb54b62c66f3153 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | # Licensed to Modin Development Team under one or more contributor license agreements.
# See the NOTICE file distributed with this work for additional information regarding
# copyright ownership. The Modin Development Team licenses this file to you 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 pytest
import numpy as np
import pandas
from pandas.testing import assert_index_equal
import matplotlib
import modin.pandas as pd
from modin.utils import get_current_backend
from modin.pandas.test.utils import (
random_state,
RAND_LOW,
RAND_HIGH,
df_equals,
df_is_empty,
arg_keys,
name_contains,
test_data,
test_data_values,
test_data_keys,
test_data_with_duplicates_values,
test_data_with_duplicates_keys,
numeric_dfs,
test_func_keys,
test_func_values,
indices_keys,
indices_values,
axis_keys,
axis_values,
bool_arg_keys,
bool_arg_values,
int_arg_keys,
int_arg_values,
eval_general,
create_test_dfs,
)
from modin.config import NPartitions
NPartitions.put(4)
# Force matplotlib to not use any Xwindows backend.
matplotlib.use("Agg")
def eval_insert(modin_df, pandas_df, **kwargs):
if "col" in kwargs and "column" not in kwargs:
kwargs["column"] = kwargs.pop("col")
_kwargs = {"loc": 0, "column": "New column"}
_kwargs.update(kwargs)
eval_general(
modin_df,
pandas_df,
operation=lambda df, **kwargs: df.insert(**kwargs),
**_kwargs,
)
def test_indexing():
modin_df = pd.DataFrame(
dict(a=[1, 2, 3], b=[4, 5, 6], c=[7, 8, 9]), index=["a", "b", "c"]
)
pandas_df = pandas.DataFrame(
dict(a=[1, 2, 3], b=[4, 5, 6], c=[7, 8, 9]), index=["a", "b", "c"]
)
modin_result = modin_df
pandas_result = pandas_df
df_equals(modin_result, pandas_result)
modin_result = modin_df["b"]
pandas_result = pandas_df["b"]
df_equals(modin_result, pandas_result)
modin_result = modin_df[["b"]]
pandas_result = pandas_df[["b"]]
df_equals(modin_result, pandas_result)
modin_result = modin_df[["b", "a"]]
pandas_result = pandas_df[["b", "a"]]
df_equals(modin_result, pandas_result)
modin_result = modin_df.loc["b"]
pandas_result = pandas_df.loc["b"]
df_equals(modin_result, pandas_result)
modin_result = modin_df.loc[["b"]]
pandas_result = pandas_df.loc[["b"]]
df_equals(modin_result, pandas_result)
modin_result = modin_df.loc[["b", "a"]]
pandas_result = pandas_df.loc[["b", "a"]]
df_equals(modin_result, pandas_result)
modin_result = modin_df.loc[["b", "a"], ["a", "c"]]
pandas_result = pandas_df.loc[["b", "a"], ["a", "c"]]
df_equals(modin_result, pandas_result)
modin_result = modin_df.loc[:, ["a", "c"]]
pandas_result = pandas_df.loc[:, ["a", "c"]]
df_equals(modin_result, pandas_result)
modin_result = modin_df.loc[:, ["c"]]
pandas_result = pandas_df.loc[:, ["c"]]
df_equals(modin_result, pandas_result)
modin_result = modin_df.loc[[]]
pandas_result = pandas_df.loc[[]]
df_equals(modin_result, pandas_result)
def test_empty_df():
df = pd.DataFrame(index=["a", "b"])
df_is_empty(df)
assert_index_equal(df.index, pd.Index(["a", "b"]))
assert len(df.columns) == 0
df = pd.DataFrame(columns=["a", "b"])
df_is_empty(df)
assert len(df.index) == 0
assert_index_equal(df.columns, pd.Index(["a", "b"]))
df = pd.DataFrame()
df_is_empty(df)
assert len(df.index) == 0
assert len(df.columns) == 0
df = pd.DataFrame(index=["a", "b"])
df_is_empty(df)
assert_index_equal(df.index, pd.Index(["a", "b"]))
assert len(df.columns) == 0
df = pd.DataFrame(columns=["a", "b"])
df_is_empty(df)
assert len(df.index) == 0
assert_index_equal(df.columns, pd.Index(["a", "b"]))
df = pd.DataFrame()
df_is_empty(df)
assert len(df.index) == 0
assert len(df.columns) == 0
df = pd.DataFrame()
pd_df = pandas.DataFrame()
df["a"] = [1, 2, 3, 4, 5]
pd_df["a"] = [1, 2, 3, 4, 5]
df_equals(df, pd_df)
df = pd.DataFrame()
pd_df = pandas.DataFrame()
df["a"] = list("ABCDEF")
pd_df["a"] = list("ABCDEF")
df_equals(df, pd_df)
df = pd.DataFrame()
pd_df = pandas.DataFrame()
df["a"] = pd.Series([1, 2, 3, 4, 5])
pd_df["a"] = pandas.Series([1, 2, 3, 4, 5])
df_equals(df, pd_df)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_abs(request, data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
try:
pandas_result = pandas_df.abs()
except Exception as e:
with pytest.raises(type(e)):
modin_df.abs()
else:
modin_result = modin_df.abs()
df_equals(modin_result, pandas_result)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_add_prefix(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
test_prefix = "TEST"
new_modin_df = modin_df.add_prefix(test_prefix)
new_pandas_df = pandas_df.add_prefix(test_prefix)
df_equals(new_modin_df.columns, new_pandas_df.columns)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
@pytest.mark.parametrize("testfunc", test_func_values, ids=test_func_keys)
def test_applymap(request, data, testfunc):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
with pytest.raises(ValueError):
x = 2
modin_df.applymap(x)
try:
pandas_result = pandas_df.applymap(testfunc)
except Exception as e:
with pytest.raises(type(e)):
modin_df.applymap(testfunc)
else:
modin_result = modin_df.applymap(testfunc)
df_equals(modin_result, pandas_result)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
@pytest.mark.parametrize("testfunc", test_func_values, ids=test_func_keys)
def test_applymap_numeric(request, data, testfunc):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
if name_contains(request.node.name, numeric_dfs):
try:
pandas_result = pandas_df.applymap(testfunc)
except Exception as e:
with pytest.raises(type(e)):
modin_df.applymap(testfunc)
else:
modin_result = modin_df.applymap(testfunc)
df_equals(modin_result, pandas_result)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_add_suffix(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
test_suffix = "TEST"
new_modin_df = modin_df.add_suffix(test_suffix)
new_pandas_df = pandas_df.add_suffix(test_suffix)
df_equals(new_modin_df.columns, new_pandas_df.columns)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_at(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
key1 = modin_df.columns[0]
# Scaler
df_equals(modin_df.at[0, key1], pandas_df.at[0, key1])
# Series
df_equals(modin_df.loc[0].at[key1], pandas_df.loc[0].at[key1])
# Write Item
modin_df_copy = modin_df.copy()
pandas_df_copy = pandas_df.copy()
modin_df_copy.at[1, key1] = modin_df.at[0, key1]
pandas_df_copy.at[1, key1] = pandas_df.at[0, key1]
df_equals(modin_df_copy, pandas_df_copy)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_axes(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
for modin_axis, pd_axis in zip(modin_df.axes, pandas_df.axes):
assert np.array_equal(modin_axis, pd_axis)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_copy(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data) # noqa F841
# pandas_df is unused but there so there won't be confusing list comprehension
# stuff in the pytest.mark.parametrize
new_modin_df = modin_df.copy()
assert new_modin_df is not modin_df
if get_current_backend() != "BaseOnPython":
assert np.array_equal(
new_modin_df._query_compiler._modin_frame._partitions,
modin_df._query_compiler._modin_frame._partitions,
)
assert new_modin_df is not modin_df
df_equals(new_modin_df, modin_df)
# Shallow copy tests
modin_df = pd.DataFrame(data)
modin_df_cp = modin_df.copy(False)
modin_df[modin_df.columns[0]] = 0
df_equals(modin_df, modin_df_cp)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_dtypes(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
df_equals(modin_df.dtypes, pandas_df.dtypes)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
@pytest.mark.parametrize("key", indices_values, ids=indices_keys)
def test_get(data, key):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
df_equals(modin_df.get(key), pandas_df.get(key))
df_equals(
modin_df.get(key, default="default"), pandas_df.get(key, default="default")
)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
@pytest.mark.parametrize(
"dummy_na", bool_arg_values, ids=arg_keys("dummy_na", bool_arg_keys)
)
@pytest.mark.parametrize(
"drop_first", bool_arg_values, ids=arg_keys("drop_first", bool_arg_keys)
)
def test_get_dummies(request, data, dummy_na, drop_first):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
try:
pandas_result = pandas.get_dummies(
pandas_df, dummy_na=dummy_na, drop_first=drop_first
)
except Exception as e:
with pytest.raises(type(e)):
pd.get_dummies(modin_df, dummy_na=dummy_na, drop_first=drop_first)
else:
modin_result = pd.get_dummies(
modin_df, dummy_na=dummy_na, drop_first=drop_first
)
df_equals(modin_result, pandas_result)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_isna(data):
pandas_df = pandas.DataFrame(data)
modin_df = pd.DataFrame(data)
pandas_result = pandas_df.isna()
modin_result = modin_df.isna()
df_equals(modin_result, pandas_result)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_isnull(data):
pandas_df = pandas.DataFrame(data)
modin_df = pd.DataFrame(data)
pandas_result = pandas_df.isnull()
modin_result = modin_df.isnull()
df_equals(modin_result, pandas_result)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_append(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
data_to_append = {"append_a": 2, "append_b": 1000}
ignore_idx_values = [True, False]
for ignore in ignore_idx_values:
try:
pandas_result = pandas_df.append(data_to_append, ignore_index=ignore)
except Exception as e:
with pytest.raises(type(e)):
modin_df.append(data_to_append, ignore_index=ignore)
else:
modin_result = modin_df.append(data_to_append, ignore_index=ignore)
df_equals(modin_result, pandas_result)
try:
pandas_result = pandas_df.append(pandas_df.iloc[-1])
except Exception as e:
with pytest.raises(type(e)):
modin_df.append(modin_df.iloc[-1])
else:
modin_result = modin_df.append(modin_df.iloc[-1])
df_equals(modin_result, pandas_result)
try:
pandas_result = pandas_df.append(list(pandas_df.iloc[-1]))
except Exception as e:
with pytest.raises(type(e)):
modin_df.append(list(modin_df.iloc[-1]))
else:
modin_result = modin_df.append(list(modin_df.iloc[-1]))
# Pandas has bug where sort=False is ignored
# (https://github.com/pandas-dev/pandas/issues/35092), but Modin
# now does the right thing, so for now manually sort to workaround
# this. Once the Pandas bug is fixed and Modin upgrades to that
# Pandas release, this sort will cause the test to fail, and the
# next three lines should be deleted.
if get_current_backend() != "BaseOnPython":
assert list(modin_result.columns) == list(modin_df.columns) + [0]
modin_result = modin_result[[0] + sorted(modin_df.columns)]
df_equals(modin_result, pandas_result)
verify_integrity_values = [True, False]
for verify_integrity in verify_integrity_values:
try:
pandas_result = pandas_df.append(
[pandas_df, pandas_df], verify_integrity=verify_integrity
)
except Exception as e:
with pytest.raises(type(e)):
modin_df.append([modin_df, modin_df], verify_integrity=verify_integrity)
else:
modin_result = modin_df.append(
[modin_df, modin_df], verify_integrity=verify_integrity
)
df_equals(modin_result, pandas_result)
try:
pandas_result = pandas_df.append(
pandas_df, verify_integrity=verify_integrity
)
except Exception as e:
with pytest.raises(type(e)):
modin_df.append(modin_df, verify_integrity=verify_integrity)
else:
modin_result = modin_df.append(modin_df, verify_integrity=verify_integrity)
df_equals(modin_result, pandas_result)
def test_astype():
td = pandas.DataFrame(test_data["int_data"])[["col1", "index", "col3", "col4"]]
modin_df = pd.DataFrame(td.values, index=td.index, columns=td.columns)
expected_df = pandas.DataFrame(td.values, index=td.index, columns=td.columns)
modin_df_casted = modin_df.astype(np.int32)
expected_df_casted = expected_df.astype(np.int32)
df_equals(modin_df_casted, expected_df_casted)
modin_df_casted = modin_df.astype(np.float64)
expected_df_casted = expected_df.astype(np.float64)
df_equals(modin_df_casted, expected_df_casted)
modin_df_casted = modin_df.astype(str)
expected_df_casted = expected_df.astype(str)
df_equals(modin_df_casted, expected_df_casted)
modin_df_casted = modin_df.astype("category")
expected_df_casted = expected_df.astype("category")
df_equals(modin_df_casted, expected_df_casted)
dtype_dict = {"col1": np.int32, "index": np.int64, "col3": str}
modin_df_casted = modin_df.astype(dtype_dict)
expected_df_casted = expected_df.astype(dtype_dict)
df_equals(modin_df_casted, expected_df_casted)
# Ignore lint because this is testing bad input
bad_dtype_dict = {"index": np.int32, "index": np.int64, "index": str} # noqa F601
modin_df_casted = modin_df.astype(bad_dtype_dict)
expected_df_casted = expected_df.astype(bad_dtype_dict)
df_equals(modin_df_casted, expected_df_casted)
modin_df = pd.DataFrame(index=["row1"], columns=["col1"])
modin_df["col1"]["row1"] = 11
modin_df_casted = modin_df.astype(int)
expected_df = pandas.DataFrame(index=["row1"], columns=["col1"])
expected_df["col1"]["row1"] = 11
expected_df_casted = expected_df.astype(int)
df_equals(modin_df_casted, expected_df_casted)
with pytest.raises(KeyError):
modin_df.astype({"not_exists": np.uint8})
def test_astype_category():
modin_df = pd.DataFrame(
{"col1": ["A", "A", "B", "B", "A"], "col2": [1, 2, 3, 4, 5]}
)
pandas_df = pandas.DataFrame(
{"col1": ["A", "A", "B", "B", "A"], "col2": [1, 2, 3, 4, 5]}
)
modin_result = modin_df.astype({"col1": "category"})
pandas_result = pandas_df.astype({"col1": "category"})
df_equals(modin_result, pandas_result)
assert modin_result.dtypes.equals(pandas_result.dtypes)
modin_result = modin_df.astype("category")
pandas_result = pandas_df.astype("category")
df_equals(modin_result, pandas_result)
assert modin_result.dtypes.equals(pandas_result.dtypes)
def test_astype_category_large():
series_length = 10_000
modin_df = pd.DataFrame(
{
"col1": ["str{0}".format(i) for i in range(0, series_length)],
"col2": [i for i in range(0, series_length)],
}
)
pandas_df = pandas.DataFrame(
{
"col1": ["str{0}".format(i) for i in range(0, series_length)],
"col2": [i for i in range(0, series_length)],
}
)
modin_result = modin_df.astype({"col1": "category"})
pandas_result = pandas_df.astype({"col1": "category"})
df_equals(modin_result, pandas_result)
assert modin_result.dtypes.equals(pandas_result.dtypes)
modin_result = modin_df.astype("category")
pandas_result = pandas_df.astype("category")
df_equals(modin_result, pandas_result)
assert modin_result.dtypes.equals(pandas_result.dtypes)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
@pytest.mark.parametrize("axis", axis_values, ids=axis_keys)
def test_clip(request, data, axis):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
if name_contains(request.node.name, numeric_dfs):
ind_len = (
len(modin_df.index)
if not pandas.DataFrame()._get_axis_number(axis)
else len(modin_df.columns)
)
# set bounds
lower, upper = np.sort(random_state.random_integers(RAND_LOW, RAND_HIGH, 2))
lower_list = random_state.random_integers(RAND_LOW, RAND_HIGH, ind_len)
upper_list = random_state.random_integers(RAND_LOW, RAND_HIGH, ind_len)
# test only upper scalar bound
modin_result = modin_df.clip(None, upper, axis=axis)
pandas_result = pandas_df.clip(None, upper, axis=axis)
df_equals(modin_result, pandas_result)
# test lower and upper scalar bound
modin_result = modin_df.clip(lower, upper, axis=axis)
pandas_result = pandas_df.clip(lower, upper, axis=axis)
df_equals(modin_result, pandas_result)
# test lower and upper list bound on each column
modin_result = modin_df.clip(lower_list, upper_list, axis=axis)
pandas_result = pandas_df.clip(lower_list, upper_list, axis=axis)
df_equals(modin_result, pandas_result)
# test only upper list bound on each column
modin_result = modin_df.clip(np.nan, upper_list, axis=axis)
pandas_result = pandas_df.clip(np.nan, upper_list, axis=axis)
df_equals(modin_result, pandas_result)
with pytest.raises(ValueError):
modin_df.clip(lower=[1, 2, 3], axis=None)
def test_drop():
frame_data = {"A": [1, 2, 3, 4], "B": [0, 1, 2, 3]}
simple = pandas.DataFrame(frame_data)
modin_simple = pd.DataFrame(frame_data)
df_equals(modin_simple.drop("A", axis=1), simple[["B"]])
df_equals(modin_simple.drop(["A", "B"], axis="columns"), simple[[]])
df_equals(modin_simple.drop([0, 1, 3], axis=0), simple.loc[[2], :])
df_equals(modin_simple.drop([0, 3], axis="index"), simple.loc[[1, 2], :])
pytest.raises(ValueError, modin_simple.drop, 5)
pytest.raises(ValueError, modin_simple.drop, "C", 1)
pytest.raises(ValueError, modin_simple.drop, [1, 5])
pytest.raises(ValueError, modin_simple.drop, ["A", "C"], 1)
# errors = 'ignore'
df_equals(modin_simple.drop(5, errors="ignore"), simple)
df_equals(modin_simple.drop([0, 5], errors="ignore"), simple.loc[[1, 2, 3], :])
df_equals(modin_simple.drop("C", axis=1, errors="ignore"), simple)
df_equals(modin_simple.drop(["A", "C"], axis=1, errors="ignore"), simple[["B"]])
# non-unique
nu_df = pandas.DataFrame(
zip(range(3), range(-3, 1), list("abc")), columns=["a", "a", "b"]
)
modin_nu_df = pd.DataFrame(nu_df)
df_equals(modin_nu_df.drop("a", axis=1), nu_df[["b"]])
df_equals(modin_nu_df.drop("b", axis="columns"), nu_df["a"])
df_equals(modin_nu_df.drop([]), nu_df)
nu_df = nu_df.set_index(pandas.Index(["X", "Y", "X"]))
nu_df.columns = list("abc")
modin_nu_df = pd.DataFrame(nu_df)
df_equals(modin_nu_df.drop("X", axis="rows"), nu_df.loc[["Y"], :])
df_equals(modin_nu_df.drop(["X", "Y"], axis=0), nu_df.loc[[], :])
# inplace cache issue
frame_data = random_state.randn(10, 3)
df = pandas.DataFrame(frame_data, columns=list("abc"))
modin_df = pd.DataFrame(frame_data, columns=list("abc"))
expected = df[~(df.b > 0)]
modin_df.drop(labels=df[df.b > 0].index, inplace=True)
df_equals(modin_df, expected)
midx = pd.MultiIndex(
levels=[["lama", "cow", "falcon"], ["speed", "weight", "length"]],
codes=[[0, 0, 0, 1, 1, 1, 2, 2, 2], [0, 1, 2, 0, 1, 2, 0, 1, 2]],
)
df = pd.DataFrame(
index=midx,
columns=["big", "small"],
data=[
[45, 30],
[200, 100],
[1.5, 1],
[30, 20],
[250, 150],
[1.5, 0.8],
[320, 250],
[1, 0.8],
[0.3, 0.2],
],
)
with pytest.warns(UserWarning):
df.drop(index="length", level=1)
def test_drop_api_equivalence():
# equivalence of the labels/axis and index/columns API's
frame_data = [[1, 2, 3], [3, 4, 5], [5, 6, 7]]
modin_df = pd.DataFrame(frame_data, index=["a", "b", "c"], columns=["d", "e", "f"])
modin_df1 = modin_df.drop("a")
modin_df2 = modin_df.drop(index="a")
df_equals(modin_df1, modin_df2)
modin_df1 = modin_df.drop("d", 1)
modin_df2 = modin_df.drop(columns="d")
df_equals(modin_df1, modin_df2)
modin_df1 = modin_df.drop(labels="e", axis=1)
modin_df2 = modin_df.drop(columns="e")
df_equals(modin_df1, modin_df2)
modin_df1 = modin_df.drop(["a"], axis=0)
modin_df2 = modin_df.drop(index=["a"])
df_equals(modin_df1, modin_df2)
modin_df1 = modin_df.drop(["a"], axis=0).drop(["d"], axis=1)
modin_df2 = modin_df.drop(index=["a"], columns=["d"])
df_equals(modin_df1, modin_df2)
with pytest.raises(ValueError):
modin_df.drop(labels="a", index="b")
with pytest.raises(ValueError):
modin_df.drop(labels="a", columns="b")
with pytest.raises(ValueError):
modin_df.drop(axis=1)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_drop_transpose(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
modin_result = modin_df.T.drop(columns=[0, 1, 2])
pandas_result = pandas_df.T.drop(columns=[0, 1, 2])
df_equals(modin_result, pandas_result)
modin_result = modin_df.T.drop(index=["col3", "col1"])
pandas_result = pandas_df.T.drop(index=["col3", "col1"])
df_equals(modin_result, pandas_result)
modin_result = modin_df.T.drop(columns=[0, 1, 2], index=["col3", "col1"])
pandas_result = pandas_df.T.drop(columns=[0, 1, 2], index=["col3", "col1"])
df_equals(modin_result, pandas_result)
def test_droplevel():
df = (
pd.DataFrame([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
.set_index([0, 1])
.rename_axis(["a", "b"])
)
df.columns = pd.MultiIndex.from_tuples(
[("c", "e"), ("d", "f")], names=["level_1", "level_2"]
)
df.droplevel("a")
df.droplevel("level_2", axis=1)
@pytest.mark.parametrize(
"data", test_data_with_duplicates_values, ids=test_data_with_duplicates_keys
)
@pytest.mark.parametrize(
"keep", ["last", "first", False], ids=["last", "first", "False"]
)
@pytest.mark.parametrize(
"subset",
[None, "col1", "name", ("col1", "col3"), ["col1", "col3", "col7"]],
ids=["None", "string", "name", "tuple", "list"],
)
def test_drop_duplicates(data, keep, subset):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
try:
pandas_df.drop_duplicates(keep=keep, inplace=False, subset=subset)
except Exception as e:
with pytest.raises(type(e)):
modin_df.drop_duplicates(keep=keep, inplace=False, subset=subset)
else:
df_equals(
pandas_df.drop_duplicates(keep=keep, inplace=False, subset=subset),
modin_df.drop_duplicates(keep=keep, inplace=False, subset=subset),
)
try:
pandas_results = pandas_df.drop_duplicates(
keep=keep, inplace=True, subset=subset
)
except Exception as e:
with pytest.raises(type(e)):
modin_df.drop_duplicates(keep=keep, inplace=True, subset=subset)
else:
modin_results = modin_df.drop_duplicates(keep=keep, inplace=True, subset=subset)
df_equals(modin_results, pandas_results)
def test_drop_duplicates_with_missing_index_values():
data = {
"columns": ["value", "time", "id"],
"index": [
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
20,
21,
22,
23,
24,
25,
26,
27,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41,
],
"data": [
["3", 1279213398000.0, 88.0],
["3", 1279204682000.0, 88.0],
["0", 1245772835000.0, 448.0],
["0", 1270564258000.0, 32.0],
["0", 1267106669000.0, 118.0],
["7", 1300621123000.0, 5.0],
["0", 1251130752000.0, 957.0],
["0", 1311683506000.0, 62.0],
["9", 1283692698000.0, 89.0],
["9", 1270234253000.0, 64.0],
["0", 1285088818000.0, 50.0],
["0", 1218212725000.0, 695.0],
["2", 1383933968000.0, 348.0],
["0", 1368227625000.0, 257.0],
["1", 1454514093000.0, 446.0],
["1", 1428497427000.0, 134.0],
["1", 1459184936000.0, 568.0],
["1", 1502293302000.0, 599.0],
["1", 1491833358000.0, 829.0],
["1", 1485431534000.0, 806.0],
["8", 1351800505000.0, 101.0],
["0", 1357247721000.0, 916.0],
["0", 1335804423000.0, 370.0],
["24", 1327547726000.0, 720.0],
["0", 1332334140000.0, 415.0],
["0", 1309543100000.0, 30.0],
["18", 1309541141000.0, 30.0],
["0", 1298979435000.0, 48.0],
["14", 1276098160000.0, 59.0],
["0", 1233936302000.0, 109.0],
],
}
pandas_df = pandas.DataFrame(
data["data"], index=data["index"], columns=data["columns"]
)
modin_df = pd.DataFrame(data["data"], index=data["index"], columns=data["columns"])
modin_result = modin_df.sort_values(["id", "time"]).drop_duplicates(["id"])
pandas_result = pandas_df.sort_values(["id", "time"]).drop_duplicates(["id"])
df_equals(modin_result, pandas_result)
def test_drop_duplicates_after_sort():
data = [
{"value": 1, "time": 2},
{"value": 1, "time": 1},
{"value": 2, "time": 1},
{"value": 2, "time": 2},
]
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
modin_result = modin_df.sort_values(["value", "time"]).drop_duplicates(["value"])
pandas_result = pandas_df.sort_values(["value", "time"]).drop_duplicates(["value"])
df_equals(modin_result, pandas_result)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
@pytest.mark.parametrize("axis", axis_values, ids=axis_keys)
@pytest.mark.parametrize("how", ["any", "all"], ids=["any", "all"])
def test_dropna(data, axis, how):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
with pytest.raises(ValueError):
modin_df.dropna(axis=axis, how="invalid")
with pytest.raises(TypeError):
modin_df.dropna(axis=axis, how=None, thresh=None)
with pytest.raises(KeyError):
modin_df.dropna(axis=axis, subset=["NotExists"], how=how)
modin_result = modin_df.dropna(axis=axis, how=how)
pandas_result = pandas_df.dropna(axis=axis, how=how)
df_equals(modin_result, pandas_result)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_dropna_inplace(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
pandas_result = pandas_df.dropna()
modin_df.dropna(inplace=True)
df_equals(modin_df, pandas_result)
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
pandas_df.dropna(thresh=2, inplace=True)
modin_df.dropna(thresh=2, inplace=True)
df_equals(modin_df, pandas_df)
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
pandas_df.dropna(axis=1, how="any", inplace=True)
modin_df.dropna(axis=1, how="any", inplace=True)
df_equals(modin_df, pandas_df)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_dropna_multiple_axes(data):
modin_df = pd.DataFrame(data)
with pytest.raises(TypeError):
modin_df.dropna(how="all", axis=[0, 1])
with pytest.raises(TypeError):
modin_df.dropna(how="all", axis=(0, 1))
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_dropna_subset(request, data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
if "empty_data" not in request.node.name:
column_subset = modin_df.columns[0:2]
df_equals(
modin_df.dropna(how="all", subset=column_subset),
pandas_df.dropna(how="all", subset=column_subset),
)
df_equals(
modin_df.dropna(how="any", subset=column_subset),
pandas_df.dropna(how="any", subset=column_subset),
)
row_subset = modin_df.index[0:2]
df_equals(
modin_df.dropna(how="all", axis=1, subset=row_subset),
pandas_df.dropna(how="all", axis=1, subset=row_subset),
)
df_equals(
modin_df.dropna(how="any", axis=1, subset=row_subset),
pandas_df.dropna(how="any", axis=1, subset=row_subset),
)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
@pytest.mark.parametrize("axis,subset", [(0, list("EF")), (1, [4, 5])])
def test_dropna_subset_error(data, axis, subset):
eval_general(*create_test_dfs(data), lambda df: df.dropna(axis=axis, subset=subset))
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
@pytest.mark.parametrize("astype", ["category", "int32", "float"])
def test_insert_dtypes(data, astype):
modin_df, pandas_df = pd.DataFrame(data), pandas.DataFrame(data)
# categories with NaN works incorrect for now
if astype == "category" and pandas_df.iloc[:, 0].isnull().any():
return
eval_insert(
modin_df,
pandas_df,
col="TypeSaver",
value=lambda df: df.iloc[:, 0].astype(astype),
)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
@pytest.mark.parametrize("loc", int_arg_values, ids=arg_keys("loc", int_arg_keys))
def test_insert_loc(data, loc):
modin_df, pandas_df = pd.DataFrame(data), pandas.DataFrame(data)
value = modin_df.iloc[:, 0]
eval_insert(modin_df, pandas_df, loc=loc, value=value)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_insert(data):
modin_df, pandas_df = pd.DataFrame(data), pandas.DataFrame(data)
eval_insert(
modin_df, pandas_df, col="Duplicate", value=lambda df: df[df.columns[0]]
)
eval_insert(modin_df, pandas_df, col="Scalar", value=100)
eval_insert(
pd.DataFrame(columns=list("ab")),
pandas.DataFrame(columns=list("ab")),
col=lambda df: df.columns[0],
value=lambda df: df[df.columns[0]],
)
eval_insert(
pd.DataFrame(index=modin_df.index),
pandas.DataFrame(index=pandas_df.index),
col=lambda df: df.columns[0],
value=lambda df: df[df.columns[0]],
)
eval_insert(
modin_df,
pandas_df,
col="DataFrame insert",
value=lambda df: df[[df.columns[0]]],
)
eval_insert(
modin_df,
pandas_df,
col="Different indices",
value=lambda df: df[[df.columns[0]]].set_index(df.index[::-1]),
)
# Bad inserts
eval_insert(modin_df, pandas_df, col="Bad Column", value=lambda df: df)
eval_insert(
modin_df,
pandas_df,
col="Too Short",
value=lambda df: list(df[df.columns[0]])[:-1],
)
eval_insert(
modin_df,
pandas_df,
col=lambda df: df.columns[0],
value=lambda df: df[df.columns[0]],
)
eval_insert(
modin_df,
pandas_df,
loc=lambda df: len(df.columns) + 100,
col="Bad Loc",
value=100,
)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_ndim(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
assert modin_df.ndim == pandas_df.ndim
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_notna(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
df_equals(modin_df.notna(), pandas_df.notna())
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_notnull(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
df_equals(modin_df.notnull(), pandas_df.notnull())
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_round(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
df_equals(modin_df.round(), pandas_df.round())
df_equals(modin_df.round(1), pandas_df.round(1))
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
@pytest.mark.parametrize("axis", axis_values, ids=axis_keys)
def test_set_axis(data, axis):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
x = pandas.DataFrame()._get_axis_number(axis)
index = modin_df.columns if x else modin_df.index
labels = ["{0}_{1}".format(index[i], i) for i in range(modin_df.shape[x])]
modin_result = modin_df.set_axis(labels, axis=axis, inplace=False)
pandas_result = pandas_df.set_axis(labels, axis=axis, inplace=False)
df_equals(modin_result, pandas_result)
modin_df_copy = modin_df.copy()
modin_df.set_axis(labels, axis=axis, inplace=True)
# Check that the copy and original are different
try:
df_equals(modin_df, modin_df_copy)
except AssertionError:
assert True
else:
assert False
pandas_df.set_axis(labels, axis=axis, inplace=True)
df_equals(modin_df, pandas_df)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
@pytest.mark.parametrize("drop", bool_arg_values, ids=arg_keys("drop", bool_arg_keys))
@pytest.mark.parametrize(
"append", bool_arg_values, ids=arg_keys("append", bool_arg_keys)
)
def test_set_index(request, data, drop, append):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
if "empty_data" not in request.node.name:
key = modin_df.columns[0]
modin_result = modin_df.set_index(key, drop=drop, append=append, inplace=False)
pandas_result = pandas_df.set_index(
key, drop=drop, append=append, inplace=False
)
df_equals(modin_result, pandas_result)
modin_df_copy = modin_df.copy()
modin_df.set_index(key, drop=drop, append=append, inplace=True)
# Check that the copy and original are different
try:
df_equals(modin_df, modin_df_copy)
except AssertionError:
assert True
else:
assert False
pandas_df.set_index(key, drop=drop, append=append, inplace=True)
df_equals(modin_df, pandas_df)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_shape(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
assert modin_df.shape == pandas_df.shape
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_size(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
assert modin_df.size == pandas_df.size
def test_squeeze():
frame_data = {
"col1": [0, 1, 2, 3],
"col2": [4, 5, 6, 7],
"col3": [8, 9, 10, 11],
"col4": [12, 13, 14, 15],
"col5": [0, 0, 0, 0],
}
frame_data_2 = {"col1": [0, 1, 2, 3]}
frame_data_3 = {
"col1": [0],
"col2": [4],
"col3": [8],
"col4": [12],
"col5": [0],
}
frame_data_4 = {"col1": [2]}
frame_data_5 = {"col1": ["string"]}
# Different data for different cases
pandas_df = pandas.DataFrame(frame_data).squeeze()
modin_df = pd.DataFrame(frame_data).squeeze()
df_equals(modin_df, pandas_df)
pandas_df_2 = pandas.DataFrame(frame_data_2).squeeze()
modin_df_2 = pd.DataFrame(frame_data_2).squeeze()
df_equals(modin_df_2, pandas_df_2)
pandas_df_3 = pandas.DataFrame(frame_data_3).squeeze()
modin_df_3 = pd.DataFrame(frame_data_3).squeeze()
df_equals(modin_df_3, pandas_df_3)
pandas_df_4 = pandas.DataFrame(frame_data_4).squeeze()
modin_df_4 = pd.DataFrame(frame_data_4).squeeze()
df_equals(modin_df_4, pandas_df_4)
pandas_df_5 = pandas.DataFrame(frame_data_5).squeeze()
modin_df_5 = pd.DataFrame(frame_data_5).squeeze()
df_equals(modin_df_5, pandas_df_5)
data = [
[
pd.Timestamp("2019-01-02"),
pd.Timestamp("2019-01-03"),
pd.Timestamp("2019-01-04"),
pd.Timestamp("2019-01-05"),
],
[1, 1, 1, 2],
]
df = pd.DataFrame(data, index=["date", "value"]).T
pf = pandas.DataFrame(data, index=["date", "value"]).T
df.set_index("date", inplace=True)
pf.set_index("date", inplace=True)
df_equals(df.iloc[0], pf.iloc[0])
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_transpose(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
df_equals(modin_df.T, pandas_df.T)
df_equals(modin_df.transpose(), pandas_df.transpose())
# Test for map across full axis for select indices
df_equals(modin_df.T.dropna(), pandas_df.T.dropna())
# Test for map across full axis
df_equals(modin_df.T.nunique(), pandas_df.T.nunique())
# Test for map across blocks
df_equals(modin_df.T.notna(), pandas_df.T.notna())
@pytest.mark.parametrize(
"data, other_data",
[
({"A": [1, 2, 3], "B": [400, 500, 600]}, {"B": [4, 5, 6], "C": [7, 8, 9]}),
(
{"A": ["a", "b", "c"], "B": ["x", "y", "z"]},
{"B": ["d", "e", "f", "g", "h", "i"]},
),
({"A": [1, 2, 3], "B": [400, 500, 600]}, {"B": [4, np.nan, 6]}),
],
)
def test_update(data, other_data):
modin_df, pandas_df = pd.DataFrame(data), pandas.DataFrame(data)
other_modin_df, other_pandas_df = (
pd.DataFrame(other_data),
pandas.DataFrame(other_data),
)
modin_df.update(other_modin_df)
pandas_df.update(other_pandas_df)
df_equals(modin_df, pandas_df)
with pytest.raises(ValueError):
modin_df.update(other_modin_df, errors="raise")
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test___neg__(request, data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
try:
pandas_result = pandas_df.__neg__()
except Exception as e:
with pytest.raises(type(e)):
modin_df.__neg__()
else:
modin_result = modin_df.__neg__()
df_equals(modin_result, pandas_result)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test___invert__(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
try:
pandas_result = ~pandas_df
except Exception as e:
with pytest.raises(type(e)):
repr(~modin_df)
else:
modin_result = ~modin_df
df_equals(modin_result, pandas_result)
def test___hash__():
data = test_data_values[0]
with pytest.warns(UserWarning):
try:
pd.DataFrame(data).__hash__()
except TypeError:
pass
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test___delitem__(request, data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
if "empty_data" not in request.node.name:
key = pandas_df.columns[0]
modin_df = modin_df.copy()
pandas_df = pandas_df.copy()
modin_df.__delitem__(key)
pandas_df.__delitem__(key)
df_equals(modin_df, pandas_df)
# Issue 2027
last_label = pandas_df.iloc[:, -1].name
modin_df.__delitem__(last_label)
pandas_df.__delitem__(last_label)
df_equals(modin_df, pandas_df)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test___nonzero__(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data) # noqa F841
with pytest.raises(ValueError):
# Always raises ValueError
modin_df.__nonzero__()
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test___abs__(request, data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
try:
pandas_result = abs(pandas_df)
except Exception as e:
with pytest.raises(type(e)):
abs(modin_df)
else:
modin_result = abs(modin_df)
df_equals(modin_result, pandas_result)
def test___round__():
data = test_data_values[0]
with pytest.warns(UserWarning):
pd.DataFrame(data).__round__()
| 32.585835 | 88 | 0.644924 |
import pytest
import numpy as np
import pandas
from pandas.testing import assert_index_equal
import matplotlib
import modin.pandas as pd
from modin.utils import get_current_backend
from modin.pandas.test.utils import (
random_state,
RAND_LOW,
RAND_HIGH,
df_equals,
df_is_empty,
arg_keys,
name_contains,
test_data,
test_data_values,
test_data_keys,
test_data_with_duplicates_values,
test_data_with_duplicates_keys,
numeric_dfs,
test_func_keys,
test_func_values,
indices_keys,
indices_values,
axis_keys,
axis_values,
bool_arg_keys,
bool_arg_values,
int_arg_keys,
int_arg_values,
eval_general,
create_test_dfs,
)
from modin.config import NPartitions
NPartitions.put(4)
matplotlib.use("Agg")
def eval_insert(modin_df, pandas_df, **kwargs):
if "col" in kwargs and "column" not in kwargs:
kwargs["column"] = kwargs.pop("col")
_kwargs = {"loc": 0, "column": "New column"}
_kwargs.update(kwargs)
eval_general(
modin_df,
pandas_df,
operation=lambda df, **kwargs: df.insert(**kwargs),
**_kwargs,
)
def test_indexing():
modin_df = pd.DataFrame(
dict(a=[1, 2, 3], b=[4, 5, 6], c=[7, 8, 9]), index=["a", "b", "c"]
)
pandas_df = pandas.DataFrame(
dict(a=[1, 2, 3], b=[4, 5, 6], c=[7, 8, 9]), index=["a", "b", "c"]
)
modin_result = modin_df
pandas_result = pandas_df
df_equals(modin_result, pandas_result)
modin_result = modin_df["b"]
pandas_result = pandas_df["b"]
df_equals(modin_result, pandas_result)
modin_result = modin_df[["b"]]
pandas_result = pandas_df[["b"]]
df_equals(modin_result, pandas_result)
modin_result = modin_df[["b", "a"]]
pandas_result = pandas_df[["b", "a"]]
df_equals(modin_result, pandas_result)
modin_result = modin_df.loc["b"]
pandas_result = pandas_df.loc["b"]
df_equals(modin_result, pandas_result)
modin_result = modin_df.loc[["b"]]
pandas_result = pandas_df.loc[["b"]]
df_equals(modin_result, pandas_result)
modin_result = modin_df.loc[["b", "a"]]
pandas_result = pandas_df.loc[["b", "a"]]
df_equals(modin_result, pandas_result)
modin_result = modin_df.loc[["b", "a"], ["a", "c"]]
pandas_result = pandas_df.loc[["b", "a"], ["a", "c"]]
df_equals(modin_result, pandas_result)
modin_result = modin_df.loc[:, ["a", "c"]]
pandas_result = pandas_df.loc[:, ["a", "c"]]
df_equals(modin_result, pandas_result)
modin_result = modin_df.loc[:, ["c"]]
pandas_result = pandas_df.loc[:, ["c"]]
df_equals(modin_result, pandas_result)
modin_result = modin_df.loc[[]]
pandas_result = pandas_df.loc[[]]
df_equals(modin_result, pandas_result)
def test_empty_df():
df = pd.DataFrame(index=["a", "b"])
df_is_empty(df)
assert_index_equal(df.index, pd.Index(["a", "b"]))
assert len(df.columns) == 0
df = pd.DataFrame(columns=["a", "b"])
df_is_empty(df)
assert len(df.index) == 0
assert_index_equal(df.columns, pd.Index(["a", "b"]))
df = pd.DataFrame()
df_is_empty(df)
assert len(df.index) == 0
assert len(df.columns) == 0
df = pd.DataFrame(index=["a", "b"])
df_is_empty(df)
assert_index_equal(df.index, pd.Index(["a", "b"]))
assert len(df.columns) == 0
df = pd.DataFrame(columns=["a", "b"])
df_is_empty(df)
assert len(df.index) == 0
assert_index_equal(df.columns, pd.Index(["a", "b"]))
df = pd.DataFrame()
df_is_empty(df)
assert len(df.index) == 0
assert len(df.columns) == 0
df = pd.DataFrame()
pd_df = pandas.DataFrame()
df["a"] = [1, 2, 3, 4, 5]
pd_df["a"] = [1, 2, 3, 4, 5]
df_equals(df, pd_df)
df = pd.DataFrame()
pd_df = pandas.DataFrame()
df["a"] = list("ABCDEF")
pd_df["a"] = list("ABCDEF")
df_equals(df, pd_df)
df = pd.DataFrame()
pd_df = pandas.DataFrame()
df["a"] = pd.Series([1, 2, 3, 4, 5])
pd_df["a"] = pandas.Series([1, 2, 3, 4, 5])
df_equals(df, pd_df)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_abs(request, data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
try:
pandas_result = pandas_df.abs()
except Exception as e:
with pytest.raises(type(e)):
modin_df.abs()
else:
modin_result = modin_df.abs()
df_equals(modin_result, pandas_result)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_add_prefix(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
test_prefix = "TEST"
new_modin_df = modin_df.add_prefix(test_prefix)
new_pandas_df = pandas_df.add_prefix(test_prefix)
df_equals(new_modin_df.columns, new_pandas_df.columns)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
@pytest.mark.parametrize("testfunc", test_func_values, ids=test_func_keys)
def test_applymap(request, data, testfunc):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
with pytest.raises(ValueError):
x = 2
modin_df.applymap(x)
try:
pandas_result = pandas_df.applymap(testfunc)
except Exception as e:
with pytest.raises(type(e)):
modin_df.applymap(testfunc)
else:
modin_result = modin_df.applymap(testfunc)
df_equals(modin_result, pandas_result)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
@pytest.mark.parametrize("testfunc", test_func_values, ids=test_func_keys)
def test_applymap_numeric(request, data, testfunc):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
if name_contains(request.node.name, numeric_dfs):
try:
pandas_result = pandas_df.applymap(testfunc)
except Exception as e:
with pytest.raises(type(e)):
modin_df.applymap(testfunc)
else:
modin_result = modin_df.applymap(testfunc)
df_equals(modin_result, pandas_result)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_add_suffix(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
test_suffix = "TEST"
new_modin_df = modin_df.add_suffix(test_suffix)
new_pandas_df = pandas_df.add_suffix(test_suffix)
df_equals(new_modin_df.columns, new_pandas_df.columns)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_at(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
key1 = modin_df.columns[0]
df_equals(modin_df.at[0, key1], pandas_df.at[0, key1])
df_equals(modin_df.loc[0].at[key1], pandas_df.loc[0].at[key1])
modin_df_copy = modin_df.copy()
pandas_df_copy = pandas_df.copy()
modin_df_copy.at[1, key1] = modin_df.at[0, key1]
pandas_df_copy.at[1, key1] = pandas_df.at[0, key1]
df_equals(modin_df_copy, pandas_df_copy)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_axes(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
for modin_axis, pd_axis in zip(modin_df.axes, pandas_df.axes):
assert np.array_equal(modin_axis, pd_axis)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_copy(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
# stuff in the pytest.mark.parametrize
new_modin_df = modin_df.copy()
assert new_modin_df is not modin_df
if get_current_backend() != "BaseOnPython":
assert np.array_equal(
new_modin_df._query_compiler._modin_frame._partitions,
modin_df._query_compiler._modin_frame._partitions,
)
assert new_modin_df is not modin_df
df_equals(new_modin_df, modin_df)
# Shallow copy tests
modin_df = pd.DataFrame(data)
modin_df_cp = modin_df.copy(False)
modin_df[modin_df.columns[0]] = 0
df_equals(modin_df, modin_df_cp)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_dtypes(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
df_equals(modin_df.dtypes, pandas_df.dtypes)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
@pytest.mark.parametrize("key", indices_values, ids=indices_keys)
def test_get(data, key):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
df_equals(modin_df.get(key), pandas_df.get(key))
df_equals(
modin_df.get(key, default="default"), pandas_df.get(key, default="default")
)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
@pytest.mark.parametrize(
"dummy_na", bool_arg_values, ids=arg_keys("dummy_na", bool_arg_keys)
)
@pytest.mark.parametrize(
"drop_first", bool_arg_values, ids=arg_keys("drop_first", bool_arg_keys)
)
def test_get_dummies(request, data, dummy_na, drop_first):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
try:
pandas_result = pandas.get_dummies(
pandas_df, dummy_na=dummy_na, drop_first=drop_first
)
except Exception as e:
with pytest.raises(type(e)):
pd.get_dummies(modin_df, dummy_na=dummy_na, drop_first=drop_first)
else:
modin_result = pd.get_dummies(
modin_df, dummy_na=dummy_na, drop_first=drop_first
)
df_equals(modin_result, pandas_result)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_isna(data):
pandas_df = pandas.DataFrame(data)
modin_df = pd.DataFrame(data)
pandas_result = pandas_df.isna()
modin_result = modin_df.isna()
df_equals(modin_result, pandas_result)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_isnull(data):
pandas_df = pandas.DataFrame(data)
modin_df = pd.DataFrame(data)
pandas_result = pandas_df.isnull()
modin_result = modin_df.isnull()
df_equals(modin_result, pandas_result)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_append(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
data_to_append = {"append_a": 2, "append_b": 1000}
ignore_idx_values = [True, False]
for ignore in ignore_idx_values:
try:
pandas_result = pandas_df.append(data_to_append, ignore_index=ignore)
except Exception as e:
with pytest.raises(type(e)):
modin_df.append(data_to_append, ignore_index=ignore)
else:
modin_result = modin_df.append(data_to_append, ignore_index=ignore)
df_equals(modin_result, pandas_result)
try:
pandas_result = pandas_df.append(pandas_df.iloc[-1])
except Exception as e:
with pytest.raises(type(e)):
modin_df.append(modin_df.iloc[-1])
else:
modin_result = modin_df.append(modin_df.iloc[-1])
df_equals(modin_result, pandas_result)
try:
pandas_result = pandas_df.append(list(pandas_df.iloc[-1]))
except Exception as e:
with pytest.raises(type(e)):
modin_df.append(list(modin_df.iloc[-1]))
else:
modin_result = modin_df.append(list(modin_df.iloc[-1]))
# Pandas has bug where sort=False is ignored
# (https://github.com/pandas-dev/pandas/issues/35092), but Modin
# now does the right thing, so for now manually sort to workaround
# this. Once the Pandas bug is fixed and Modin upgrades to that
# Pandas release, this sort will cause the test to fail, and the
# next three lines should be deleted.
if get_current_backend() != "BaseOnPython":
assert list(modin_result.columns) == list(modin_df.columns) + [0]
modin_result = modin_result[[0] + sorted(modin_df.columns)]
df_equals(modin_result, pandas_result)
verify_integrity_values = [True, False]
for verify_integrity in verify_integrity_values:
try:
pandas_result = pandas_df.append(
[pandas_df, pandas_df], verify_integrity=verify_integrity
)
except Exception as e:
with pytest.raises(type(e)):
modin_df.append([modin_df, modin_df], verify_integrity=verify_integrity)
else:
modin_result = modin_df.append(
[modin_df, modin_df], verify_integrity=verify_integrity
)
df_equals(modin_result, pandas_result)
try:
pandas_result = pandas_df.append(
pandas_df, verify_integrity=verify_integrity
)
except Exception as e:
with pytest.raises(type(e)):
modin_df.append(modin_df, verify_integrity=verify_integrity)
else:
modin_result = modin_df.append(modin_df, verify_integrity=verify_integrity)
df_equals(modin_result, pandas_result)
def test_astype():
td = pandas.DataFrame(test_data["int_data"])[["col1", "index", "col3", "col4"]]
modin_df = pd.DataFrame(td.values, index=td.index, columns=td.columns)
expected_df = pandas.DataFrame(td.values, index=td.index, columns=td.columns)
modin_df_casted = modin_df.astype(np.int32)
expected_df_casted = expected_df.astype(np.int32)
df_equals(modin_df_casted, expected_df_casted)
modin_df_casted = modin_df.astype(np.float64)
expected_df_casted = expected_df.astype(np.float64)
df_equals(modin_df_casted, expected_df_casted)
modin_df_casted = modin_df.astype(str)
expected_df_casted = expected_df.astype(str)
df_equals(modin_df_casted, expected_df_casted)
modin_df_casted = modin_df.astype("category")
expected_df_casted = expected_df.astype("category")
df_equals(modin_df_casted, expected_df_casted)
dtype_dict = {"col1": np.int32, "index": np.int64, "col3": str}
modin_df_casted = modin_df.astype(dtype_dict)
expected_df_casted = expected_df.astype(dtype_dict)
df_equals(modin_df_casted, expected_df_casted)
# Ignore lint because this is testing bad input
bad_dtype_dict = {"index": np.int32, "index": np.int64, "index": str} # noqa F601
modin_df_casted = modin_df.astype(bad_dtype_dict)
expected_df_casted = expected_df.astype(bad_dtype_dict)
df_equals(modin_df_casted, expected_df_casted)
modin_df = pd.DataFrame(index=["row1"], columns=["col1"])
modin_df["col1"]["row1"] = 11
modin_df_casted = modin_df.astype(int)
expected_df = pandas.DataFrame(index=["row1"], columns=["col1"])
expected_df["col1"]["row1"] = 11
expected_df_casted = expected_df.astype(int)
df_equals(modin_df_casted, expected_df_casted)
with pytest.raises(KeyError):
modin_df.astype({"not_exists": np.uint8})
def test_astype_category():
modin_df = pd.DataFrame(
{"col1": ["A", "A", "B", "B", "A"], "col2": [1, 2, 3, 4, 5]}
)
pandas_df = pandas.DataFrame(
{"col1": ["A", "A", "B", "B", "A"], "col2": [1, 2, 3, 4, 5]}
)
modin_result = modin_df.astype({"col1": "category"})
pandas_result = pandas_df.astype({"col1": "category"})
df_equals(modin_result, pandas_result)
assert modin_result.dtypes.equals(pandas_result.dtypes)
modin_result = modin_df.astype("category")
pandas_result = pandas_df.astype("category")
df_equals(modin_result, pandas_result)
assert modin_result.dtypes.equals(pandas_result.dtypes)
def test_astype_category_large():
series_length = 10_000
modin_df = pd.DataFrame(
{
"col1": ["str{0}".format(i) for i in range(0, series_length)],
"col2": [i for i in range(0, series_length)],
}
)
pandas_df = pandas.DataFrame(
{
"col1": ["str{0}".format(i) for i in range(0, series_length)],
"col2": [i for i in range(0, series_length)],
}
)
modin_result = modin_df.astype({"col1": "category"})
pandas_result = pandas_df.astype({"col1": "category"})
df_equals(modin_result, pandas_result)
assert modin_result.dtypes.equals(pandas_result.dtypes)
modin_result = modin_df.astype("category")
pandas_result = pandas_df.astype("category")
df_equals(modin_result, pandas_result)
assert modin_result.dtypes.equals(pandas_result.dtypes)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
@pytest.mark.parametrize("axis", axis_values, ids=axis_keys)
def test_clip(request, data, axis):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
if name_contains(request.node.name, numeric_dfs):
ind_len = (
len(modin_df.index)
if not pandas.DataFrame()._get_axis_number(axis)
else len(modin_df.columns)
)
# set bounds
lower, upper = np.sort(random_state.random_integers(RAND_LOW, RAND_HIGH, 2))
lower_list = random_state.random_integers(RAND_LOW, RAND_HIGH, ind_len)
upper_list = random_state.random_integers(RAND_LOW, RAND_HIGH, ind_len)
# test only upper scalar bound
modin_result = modin_df.clip(None, upper, axis=axis)
pandas_result = pandas_df.clip(None, upper, axis=axis)
df_equals(modin_result, pandas_result)
# test lower and upper scalar bound
modin_result = modin_df.clip(lower, upper, axis=axis)
pandas_result = pandas_df.clip(lower, upper, axis=axis)
df_equals(modin_result, pandas_result)
# test lower and upper list bound on each column
modin_result = modin_df.clip(lower_list, upper_list, axis=axis)
pandas_result = pandas_df.clip(lower_list, upper_list, axis=axis)
df_equals(modin_result, pandas_result)
# test only upper list bound on each column
modin_result = modin_df.clip(np.nan, upper_list, axis=axis)
pandas_result = pandas_df.clip(np.nan, upper_list, axis=axis)
df_equals(modin_result, pandas_result)
with pytest.raises(ValueError):
modin_df.clip(lower=[1, 2, 3], axis=None)
def test_drop():
frame_data = {"A": [1, 2, 3, 4], "B": [0, 1, 2, 3]}
simple = pandas.DataFrame(frame_data)
modin_simple = pd.DataFrame(frame_data)
df_equals(modin_simple.drop("A", axis=1), simple[["B"]])
df_equals(modin_simple.drop(["A", "B"], axis="columns"), simple[[]])
df_equals(modin_simple.drop([0, 1, 3], axis=0), simple.loc[[2], :])
df_equals(modin_simple.drop([0, 3], axis="index"), simple.loc[[1, 2], :])
pytest.raises(ValueError, modin_simple.drop, 5)
pytest.raises(ValueError, modin_simple.drop, "C", 1)
pytest.raises(ValueError, modin_simple.drop, [1, 5])
pytest.raises(ValueError, modin_simple.drop, ["A", "C"], 1)
# errors = 'ignore'
df_equals(modin_simple.drop(5, errors="ignore"), simple)
df_equals(modin_simple.drop([0, 5], errors="ignore"), simple.loc[[1, 2, 3], :])
df_equals(modin_simple.drop("C", axis=1, errors="ignore"), simple)
df_equals(modin_simple.drop(["A", "C"], axis=1, errors="ignore"), simple[["B"]])
# non-unique
nu_df = pandas.DataFrame(
zip(range(3), range(-3, 1), list("abc")), columns=["a", "a", "b"]
)
modin_nu_df = pd.DataFrame(nu_df)
df_equals(modin_nu_df.drop("a", axis=1), nu_df[["b"]])
df_equals(modin_nu_df.drop("b", axis="columns"), nu_df["a"])
df_equals(modin_nu_df.drop([]), nu_df)
nu_df = nu_df.set_index(pandas.Index(["X", "Y", "X"]))
nu_df.columns = list("abc")
modin_nu_df = pd.DataFrame(nu_df)
df_equals(modin_nu_df.drop("X", axis="rows"), nu_df.loc[["Y"], :])
df_equals(modin_nu_df.drop(["X", "Y"], axis=0), nu_df.loc[[], :])
# inplace cache issue
frame_data = random_state.randn(10, 3)
df = pandas.DataFrame(frame_data, columns=list("abc"))
modin_df = pd.DataFrame(frame_data, columns=list("abc"))
expected = df[~(df.b > 0)]
modin_df.drop(labels=df[df.b > 0].index, inplace=True)
df_equals(modin_df, expected)
midx = pd.MultiIndex(
levels=[["lama", "cow", "falcon"], ["speed", "weight", "length"]],
codes=[[0, 0, 0, 1, 1, 1, 2, 2, 2], [0, 1, 2, 0, 1, 2, 0, 1, 2]],
)
df = pd.DataFrame(
index=midx,
columns=["big", "small"],
data=[
[45, 30],
[200, 100],
[1.5, 1],
[30, 20],
[250, 150],
[1.5, 0.8],
[320, 250],
[1, 0.8],
[0.3, 0.2],
],
)
with pytest.warns(UserWarning):
df.drop(index="length", level=1)
def test_drop_api_equivalence():
# equivalence of the labels/axis and index/columns API's
frame_data = [[1, 2, 3], [3, 4, 5], [5, 6, 7]]
modin_df = pd.DataFrame(frame_data, index=["a", "b", "c"], columns=["d", "e", "f"])
modin_df1 = modin_df.drop("a")
modin_df2 = modin_df.drop(index="a")
df_equals(modin_df1, modin_df2)
modin_df1 = modin_df.drop("d", 1)
modin_df2 = modin_df.drop(columns="d")
df_equals(modin_df1, modin_df2)
modin_df1 = modin_df.drop(labels="e", axis=1)
modin_df2 = modin_df.drop(columns="e")
df_equals(modin_df1, modin_df2)
modin_df1 = modin_df.drop(["a"], axis=0)
modin_df2 = modin_df.drop(index=["a"])
df_equals(modin_df1, modin_df2)
modin_df1 = modin_df.drop(["a"], axis=0).drop(["d"], axis=1)
modin_df2 = modin_df.drop(index=["a"], columns=["d"])
df_equals(modin_df1, modin_df2)
with pytest.raises(ValueError):
modin_df.drop(labels="a", index="b")
with pytest.raises(ValueError):
modin_df.drop(labels="a", columns="b")
with pytest.raises(ValueError):
modin_df.drop(axis=1)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_drop_transpose(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
modin_result = modin_df.T.drop(columns=[0, 1, 2])
pandas_result = pandas_df.T.drop(columns=[0, 1, 2])
df_equals(modin_result, pandas_result)
modin_result = modin_df.T.drop(index=["col3", "col1"])
pandas_result = pandas_df.T.drop(index=["col3", "col1"])
df_equals(modin_result, pandas_result)
modin_result = modin_df.T.drop(columns=[0, 1, 2], index=["col3", "col1"])
pandas_result = pandas_df.T.drop(columns=[0, 1, 2], index=["col3", "col1"])
df_equals(modin_result, pandas_result)
def test_droplevel():
df = (
pd.DataFrame([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
.set_index([0, 1])
.rename_axis(["a", "b"])
)
df.columns = pd.MultiIndex.from_tuples(
[("c", "e"), ("d", "f")], names=["level_1", "level_2"]
)
df.droplevel("a")
df.droplevel("level_2", axis=1)
@pytest.mark.parametrize(
"data", test_data_with_duplicates_values, ids=test_data_with_duplicates_keys
)
@pytest.mark.parametrize(
"keep", ["last", "first", False], ids=["last", "first", "False"]
)
@pytest.mark.parametrize(
"subset",
[None, "col1", "name", ("col1", "col3"), ["col1", "col3", "col7"]],
ids=["None", "string", "name", "tuple", "list"],
)
def test_drop_duplicates(data, keep, subset):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
try:
pandas_df.drop_duplicates(keep=keep, inplace=False, subset=subset)
except Exception as e:
with pytest.raises(type(e)):
modin_df.drop_duplicates(keep=keep, inplace=False, subset=subset)
else:
df_equals(
pandas_df.drop_duplicates(keep=keep, inplace=False, subset=subset),
modin_df.drop_duplicates(keep=keep, inplace=False, subset=subset),
)
try:
pandas_results = pandas_df.drop_duplicates(
keep=keep, inplace=True, subset=subset
)
except Exception as e:
with pytest.raises(type(e)):
modin_df.drop_duplicates(keep=keep, inplace=True, subset=subset)
else:
modin_results = modin_df.drop_duplicates(keep=keep, inplace=True, subset=subset)
df_equals(modin_results, pandas_results)
def test_drop_duplicates_with_missing_index_values():
data = {
"columns": ["value", "time", "id"],
"index": [
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
20,
21,
22,
23,
24,
25,
26,
27,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41,
],
"data": [
["3", 1279213398000.0, 88.0],
["3", 1279204682000.0, 88.0],
["0", 1245772835000.0, 448.0],
["0", 1270564258000.0, 32.0],
["0", 1267106669000.0, 118.0],
["7", 1300621123000.0, 5.0],
["0", 1251130752000.0, 957.0],
["0", 1311683506000.0, 62.0],
["9", 1283692698000.0, 89.0],
["9", 1270234253000.0, 64.0],
["0", 1285088818000.0, 50.0],
["0", 1218212725000.0, 695.0],
["2", 1383933968000.0, 348.0],
["0", 1368227625000.0, 257.0],
["1", 1454514093000.0, 446.0],
["1", 1428497427000.0, 134.0],
["1", 1459184936000.0, 568.0],
["1", 1502293302000.0, 599.0],
["1", 1491833358000.0, 829.0],
["1", 1485431534000.0, 806.0],
["8", 1351800505000.0, 101.0],
["0", 1357247721000.0, 916.0],
["0", 1335804423000.0, 370.0],
["24", 1327547726000.0, 720.0],
["0", 1332334140000.0, 415.0],
["0", 1309543100000.0, 30.0],
["18", 1309541141000.0, 30.0],
["0", 1298979435000.0, 48.0],
["14", 1276098160000.0, 59.0],
["0", 1233936302000.0, 109.0],
],
}
pandas_df = pandas.DataFrame(
data["data"], index=data["index"], columns=data["columns"]
)
modin_df = pd.DataFrame(data["data"], index=data["index"], columns=data["columns"])
modin_result = modin_df.sort_values(["id", "time"]).drop_duplicates(["id"])
pandas_result = pandas_df.sort_values(["id", "time"]).drop_duplicates(["id"])
df_equals(modin_result, pandas_result)
def test_drop_duplicates_after_sort():
data = [
{"value": 1, "time": 2},
{"value": 1, "time": 1},
{"value": 2, "time": 1},
{"value": 2, "time": 2},
]
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
modin_result = modin_df.sort_values(["value", "time"]).drop_duplicates(["value"])
pandas_result = pandas_df.sort_values(["value", "time"]).drop_duplicates(["value"])
df_equals(modin_result, pandas_result)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
@pytest.mark.parametrize("axis", axis_values, ids=axis_keys)
@pytest.mark.parametrize("how", ["any", "all"], ids=["any", "all"])
def test_dropna(data, axis, how):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
with pytest.raises(ValueError):
modin_df.dropna(axis=axis, how="invalid")
with pytest.raises(TypeError):
modin_df.dropna(axis=axis, how=None, thresh=None)
with pytest.raises(KeyError):
modin_df.dropna(axis=axis, subset=["NotExists"], how=how)
modin_result = modin_df.dropna(axis=axis, how=how)
pandas_result = pandas_df.dropna(axis=axis, how=how)
df_equals(modin_result, pandas_result)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_dropna_inplace(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
pandas_result = pandas_df.dropna()
modin_df.dropna(inplace=True)
df_equals(modin_df, pandas_result)
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
pandas_df.dropna(thresh=2, inplace=True)
modin_df.dropna(thresh=2, inplace=True)
df_equals(modin_df, pandas_df)
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
pandas_df.dropna(axis=1, how="any", inplace=True)
modin_df.dropna(axis=1, how="any", inplace=True)
df_equals(modin_df, pandas_df)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_dropna_multiple_axes(data):
modin_df = pd.DataFrame(data)
with pytest.raises(TypeError):
modin_df.dropna(how="all", axis=[0, 1])
with pytest.raises(TypeError):
modin_df.dropna(how="all", axis=(0, 1))
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_dropna_subset(request, data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
if "empty_data" not in request.node.name:
column_subset = modin_df.columns[0:2]
df_equals(
modin_df.dropna(how="all", subset=column_subset),
pandas_df.dropna(how="all", subset=column_subset),
)
df_equals(
modin_df.dropna(how="any", subset=column_subset),
pandas_df.dropna(how="any", subset=column_subset),
)
row_subset = modin_df.index[0:2]
df_equals(
modin_df.dropna(how="all", axis=1, subset=row_subset),
pandas_df.dropna(how="all", axis=1, subset=row_subset),
)
df_equals(
modin_df.dropna(how="any", axis=1, subset=row_subset),
pandas_df.dropna(how="any", axis=1, subset=row_subset),
)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
@pytest.mark.parametrize("axis,subset", [(0, list("EF")), (1, [4, 5])])
def test_dropna_subset_error(data, axis, subset):
eval_general(*create_test_dfs(data), lambda df: df.dropna(axis=axis, subset=subset))
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
@pytest.mark.parametrize("astype", ["category", "int32", "float"])
def test_insert_dtypes(data, astype):
modin_df, pandas_df = pd.DataFrame(data), pandas.DataFrame(data)
if astype == "category" and pandas_df.iloc[:, 0].isnull().any():
return
eval_insert(
modin_df,
pandas_df,
col="TypeSaver",
value=lambda df: df.iloc[:, 0].astype(astype),
)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
@pytest.mark.parametrize("loc", int_arg_values, ids=arg_keys("loc", int_arg_keys))
def test_insert_loc(data, loc):
modin_df, pandas_df = pd.DataFrame(data), pandas.DataFrame(data)
value = modin_df.iloc[:, 0]
eval_insert(modin_df, pandas_df, loc=loc, value=value)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_insert(data):
modin_df, pandas_df = pd.DataFrame(data), pandas.DataFrame(data)
eval_insert(
modin_df, pandas_df, col="Duplicate", value=lambda df: df[df.columns[0]]
)
eval_insert(modin_df, pandas_df, col="Scalar", value=100)
eval_insert(
pd.DataFrame(columns=list("ab")),
pandas.DataFrame(columns=list("ab")),
col=lambda df: df.columns[0],
value=lambda df: df[df.columns[0]],
)
eval_insert(
pd.DataFrame(index=modin_df.index),
pandas.DataFrame(index=pandas_df.index),
col=lambda df: df.columns[0],
value=lambda df: df[df.columns[0]],
)
eval_insert(
modin_df,
pandas_df,
col="DataFrame insert",
value=lambda df: df[[df.columns[0]]],
)
eval_insert(
modin_df,
pandas_df,
col="Different indices",
value=lambda df: df[[df.columns[0]]].set_index(df.index[::-1]),
)
eval_insert(modin_df, pandas_df, col="Bad Column", value=lambda df: df)
eval_insert(
modin_df,
pandas_df,
col="Too Short",
value=lambda df: list(df[df.columns[0]])[:-1],
)
eval_insert(
modin_df,
pandas_df,
col=lambda df: df.columns[0],
value=lambda df: df[df.columns[0]],
)
eval_insert(
modin_df,
pandas_df,
loc=lambda df: len(df.columns) + 100,
col="Bad Loc",
value=100,
)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_ndim(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
assert modin_df.ndim == pandas_df.ndim
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_notna(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
df_equals(modin_df.notna(), pandas_df.notna())
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_notnull(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
df_equals(modin_df.notnull(), pandas_df.notnull())
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_round(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
df_equals(modin_df.round(), pandas_df.round())
df_equals(modin_df.round(1), pandas_df.round(1))
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
@pytest.mark.parametrize("axis", axis_values, ids=axis_keys)
def test_set_axis(data, axis):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
x = pandas.DataFrame()._get_axis_number(axis)
index = modin_df.columns if x else modin_df.index
labels = ["{0}_{1}".format(index[i], i) for i in range(modin_df.shape[x])]
modin_result = modin_df.set_axis(labels, axis=axis, inplace=False)
pandas_result = pandas_df.set_axis(labels, axis=axis, inplace=False)
df_equals(modin_result, pandas_result)
modin_df_copy = modin_df.copy()
modin_df.set_axis(labels, axis=axis, inplace=True)
try:
df_equals(modin_df, modin_df_copy)
except AssertionError:
assert True
else:
assert False
pandas_df.set_axis(labels, axis=axis, inplace=True)
df_equals(modin_df, pandas_df)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
@pytest.mark.parametrize("drop", bool_arg_values, ids=arg_keys("drop", bool_arg_keys))
@pytest.mark.parametrize(
"append", bool_arg_values, ids=arg_keys("append", bool_arg_keys)
)
def test_set_index(request, data, drop, append):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
if "empty_data" not in request.node.name:
key = modin_df.columns[0]
modin_result = modin_df.set_index(key, drop=drop, append=append, inplace=False)
pandas_result = pandas_df.set_index(
key, drop=drop, append=append, inplace=False
)
df_equals(modin_result, pandas_result)
modin_df_copy = modin_df.copy()
modin_df.set_index(key, drop=drop, append=append, inplace=True)
try:
df_equals(modin_df, modin_df_copy)
except AssertionError:
assert True
else:
assert False
pandas_df.set_index(key, drop=drop, append=append, inplace=True)
df_equals(modin_df, pandas_df)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_shape(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
assert modin_df.shape == pandas_df.shape
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_size(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
assert modin_df.size == pandas_df.size
def test_squeeze():
frame_data = {
"col1": [0, 1, 2, 3],
"col2": [4, 5, 6, 7],
"col3": [8, 9, 10, 11],
"col4": [12, 13, 14, 15],
"col5": [0, 0, 0, 0],
}
frame_data_2 = {"col1": [0, 1, 2, 3]}
frame_data_3 = {
"col1": [0],
"col2": [4],
"col3": [8],
"col4": [12],
"col5": [0],
}
frame_data_4 = {"col1": [2]}
frame_data_5 = {"col1": ["string"]}
pandas_df = pandas.DataFrame(frame_data).squeeze()
modin_df = pd.DataFrame(frame_data).squeeze()
df_equals(modin_df, pandas_df)
pandas_df_2 = pandas.DataFrame(frame_data_2).squeeze()
modin_df_2 = pd.DataFrame(frame_data_2).squeeze()
df_equals(modin_df_2, pandas_df_2)
pandas_df_3 = pandas.DataFrame(frame_data_3).squeeze()
modin_df_3 = pd.DataFrame(frame_data_3).squeeze()
df_equals(modin_df_3, pandas_df_3)
pandas_df_4 = pandas.DataFrame(frame_data_4).squeeze()
modin_df_4 = pd.DataFrame(frame_data_4).squeeze()
df_equals(modin_df_4, pandas_df_4)
pandas_df_5 = pandas.DataFrame(frame_data_5).squeeze()
modin_df_5 = pd.DataFrame(frame_data_5).squeeze()
df_equals(modin_df_5, pandas_df_5)
data = [
[
pd.Timestamp("2019-01-02"),
pd.Timestamp("2019-01-03"),
pd.Timestamp("2019-01-04"),
pd.Timestamp("2019-01-05"),
],
[1, 1, 1, 2],
]
df = pd.DataFrame(data, index=["date", "value"]).T
pf = pandas.DataFrame(data, index=["date", "value"]).T
df.set_index("date", inplace=True)
pf.set_index("date", inplace=True)
df_equals(df.iloc[0], pf.iloc[0])
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_transpose(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
df_equals(modin_df.T, pandas_df.T)
df_equals(modin_df.transpose(), pandas_df.transpose())
df_equals(modin_df.T.dropna(), pandas_df.T.dropna())
df_equals(modin_df.T.nunique(), pandas_df.T.nunique())
df_equals(modin_df.T.notna(), pandas_df.T.notna())
@pytest.mark.parametrize(
"data, other_data",
[
({"A": [1, 2, 3], "B": [400, 500, 600]}, {"B": [4, 5, 6], "C": [7, 8, 9]}),
(
{"A": ["a", "b", "c"], "B": ["x", "y", "z"]},
{"B": ["d", "e", "f", "g", "h", "i"]},
),
({"A": [1, 2, 3], "B": [400, 500, 600]}, {"B": [4, np.nan, 6]}),
],
)
def test_update(data, other_data):
modin_df, pandas_df = pd.DataFrame(data), pandas.DataFrame(data)
other_modin_df, other_pandas_df = (
pd.DataFrame(other_data),
pandas.DataFrame(other_data),
)
modin_df.update(other_modin_df)
pandas_df.update(other_pandas_df)
df_equals(modin_df, pandas_df)
with pytest.raises(ValueError):
modin_df.update(other_modin_df, errors="raise")
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test___neg__(request, data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
try:
pandas_result = pandas_df.__neg__()
except Exception as e:
with pytest.raises(type(e)):
modin_df.__neg__()
else:
modin_result = modin_df.__neg__()
df_equals(modin_result, pandas_result)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test___invert__(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
try:
pandas_result = ~pandas_df
except Exception as e:
with pytest.raises(type(e)):
repr(~modin_df)
else:
modin_result = ~modin_df
df_equals(modin_result, pandas_result)
def test___hash__():
data = test_data_values[0]
with pytest.warns(UserWarning):
try:
pd.DataFrame(data).__hash__()
except TypeError:
pass
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test___delitem__(request, data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
if "empty_data" not in request.node.name:
key = pandas_df.columns[0]
modin_df = modin_df.copy()
pandas_df = pandas_df.copy()
modin_df.__delitem__(key)
pandas_df.__delitem__(key)
df_equals(modin_df, pandas_df)
last_label = pandas_df.iloc[:, -1].name
modin_df.__delitem__(last_label)
pandas_df.__delitem__(last_label)
df_equals(modin_df, pandas_df)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test___nonzero__(data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
with pytest.raises(ValueError):
modin_df.__nonzero__()
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test___abs__(request, data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
try:
pandas_result = abs(pandas_df)
except Exception as e:
with pytest.raises(type(e)):
abs(modin_df)
else:
modin_result = abs(modin_df)
df_equals(modin_result, pandas_result)
def test___round__():
data = test_data_values[0]
with pytest.warns(UserWarning):
pd.DataFrame(data).__round__()
| true | true |
f7317cf731b0cf356e1cea4ede7915e02f90b539 | 7,087 | py | Python | litex_boards/targets/alveo_u250.py | quiatvn/litex-boards | 70c32a978fb588b3144a9e3cf9a63562f5505b7f | [
"BSD-2-Clause"
] | null | null | null | litex_boards/targets/alveo_u250.py | quiatvn/litex-boards | 70c32a978fb588b3144a9e3cf9a63562f5505b7f | [
"BSD-2-Clause"
] | null | null | null | litex_boards/targets/alveo_u250.py | quiatvn/litex-boards | 70c32a978fb588b3144a9e3cf9a63562f5505b7f | [
"BSD-2-Clause"
] | null | null | null | #!/usr/bin/env python3
#
# This file is part of LiteX-Boards.
#
# Copyright (c) 2020 Fei Gao <feig@princeton.edu>
# Copyright (c) 2020 Florent Kermarrec <florent@enjoy-digital.fr>
# Copyright (c) 2020 David Shah <dave@ds0.me>
# SPDX-License-Identifier: BSD-2-Clause
import argparse, os
from migen import *
from litex_boards.platforms import alveo_u250
from litex.soc.cores.clock import *
from litex.soc.integration.soc_core import *
from litex.soc.integration.soc_sdram import *
from litex.soc.integration.builder import *
from litex.soc.cores.led import LedChaser
from litedram.modules import MTA18ASF2G72PZ
from litedram.phy import usddrphy
from litepcie.phy.usppciephy import USPPCIEPHY
from litepcie.core import LitePCIeEndpoint, LitePCIeMSI
from litepcie.frontend.dma import LitePCIeDMA
from litepcie.frontend.wishbone import LitePCIeWishboneBridge
from litepcie.software import generate_litepcie_software
# CRG ----------------------------------------------------------------------------------------------
class _CRG(Module):
def __init__(self, platform, sys_clk_freq):
self.clock_domains.cd_sys = ClockDomain()
self.clock_domains.cd_sys4x = ClockDomain(reset_less=True)
self.clock_domains.cd_pll4x = ClockDomain(reset_less=True)
self.clock_domains.cd_clk500 = ClockDomain()
# # #
self.submodules.pll = pll = USMMCM(speedgrade=-2)
self.comb += pll.reset.eq(0) # FIXME
pll.register_clkin(platform.request("clk300", 0), 300e6)
pll.create_clkout(self.cd_pll4x, sys_clk_freq*4, buf=None, with_reset=False)
pll.create_clkout(self.cd_clk500, 500e6, with_reset=False)
self.specials += [
Instance("BUFGCE_DIV", name="main_bufgce_div",
p_BUFGCE_DIVIDE=4,
i_CE=1, i_I=self.cd_pll4x.clk, o_O=self.cd_sys.clk),
Instance("BUFGCE", name="main_bufgce",
i_CE=1, i_I=self.cd_pll4x.clk, o_O=self.cd_sys4x.clk),
AsyncResetSynchronizer(self.cd_clk500, ~pll.locked),
]
self.submodules.idelayctrl = USIDELAYCTRL(cd_ref=self.cd_clk500, cd_sys=self.cd_sys)
# BaseSoC ------------------------------------------------------------------------------------------
class BaseSoC(SoCCore):
def __init__(self, sys_clk_freq=int(125e6), with_pcie=False, **kwargs):
platform = alveo_u250.Platform()
# SoCCore ----------------------------------------------------------------------------------
SoCCore.__init__(self, platform, sys_clk_freq,
ident = "LiteX SoC on Alveo U250",
ident_version = True,
**kwargs)
# CRG --------------------------------------------------------------------------------------
self.submodules.crg = _CRG(platform, sys_clk_freq)
# DDR4 SDRAM -------------------------------------------------------------------------------
if not self.integrated_main_ram_size:
self.submodules.ddrphy = usddrphy.USPDDRPHY(platform.request("ddram"),
memtype = "DDR4",
sys_clk_freq = sys_clk_freq,
iodelay_clk_freq = 500e6,
cmd_latency = 1,
is_rdimm = True)
self.add_csr("ddrphy")
self.add_sdram("sdram",
phy = self.ddrphy,
module = MTA18ASF2G72PZ(sys_clk_freq, "1:4"),
origin = self.mem_map["main_ram"],
size = kwargs.get("max_sdram_size", 0x40000000),
l2_cache_size = kwargs.get("l2_size", 8192),
l2_cache_min_data_width = kwargs.get("min_l2_data_width", 128),
l2_cache_reverse = True
)
# Firmware RAM (To ease initial LiteDRAM calibration support) ------------------------------
self.add_ram("firmware_ram", 0x20000000, 0x8000)
# PCIe -------------------------------------------------------------------------------------
if with_pcie:
# PHY
self.submodules.pcie_phy = USPPCIEPHY(platform, platform.request("pcie_x4"),
data_width = 128,
bar0_size = 0x20000)
#self.pcie_phy.add_timing_constraints(platform) # FIXME
platform.add_false_path_constraints(self.crg.cd_sys.clk, self.pcie_phy.cd_pcie.clk)
self.add_csr("pcie_phy")
# Endpoint
self.submodules.pcie_endpoint = LitePCIeEndpoint(self.pcie_phy, max_pending_requests=8)
# Wishbone bridge
self.submodules.pcie_bridge = LitePCIeWishboneBridge(self.pcie_endpoint,
base_address = self.mem_map["csr"])
self.add_wb_master(self.pcie_bridge.wishbone)
# DMA0
self.submodules.pcie_dma0 = LitePCIeDMA(self.pcie_phy, self.pcie_endpoint,
with_buffering = True, buffering_depth=1024,
with_loopback = True)
self.add_csr("pcie_dma0")
self.add_constant("DMA_CHANNELS", 1)
# MSI
self.submodules.pcie_msi = LitePCIeMSI()
self.add_csr("pcie_msi")
self.comb += self.pcie_msi.source.connect(self.pcie_phy.msi)
self.interrupts = {
"PCIE_DMA0_WRITER": self.pcie_dma0.writer.irq,
"PCIE_DMA0_READER": self.pcie_dma0.reader.irq,
}
for i, (k, v) in enumerate(sorted(self.interrupts.items())):
self.comb += self.pcie_msi.irqs[i].eq(v)
self.add_constant(k + "_INTERRUPT", i)
# Leds -------------------------------------------------------------------------------------
self.submodules.leds = LedChaser(
pads = platform.request_all("user_led"),
sys_clk_freq = sys_clk_freq)
self.add_csr("leds")
# Build --------------------------------------------------------------------------------------------
def main():
parser = argparse.ArgumentParser(description="LiteX SoC on Alveo U250")
parser.add_argument("--build", action="store_true", help="Build bitstream")
parser.add_argument("--with-pcie", action="store_true", help="Enable PCIe support")
parser.add_argument("--driver", action="store_true", help="Generate PCIe driver")
parser.add_argument("--load", action="store_true", help="Load bitstream")
builder_args(parser)
soc_sdram_args(parser)
args = parser.parse_args()
# Enforce arguments
args.csr_data_width = 32
soc = BaseSoC(with_pcie=args.with_pcie, **soc_sdram_argdict(args))
builder = Builder(soc, **builder_argdict(args))
builder.build(run=args.build)
if args.driver:
generate_litepcie_software(soc, os.path.join(builder.output_dir, "driver"))
if args.load:
prog = soc.platform.create_programmer()
prog.load_bitstream(os.path.join(builder.gateware_dir, soc.build_name + ".bit"))
if __name__ == "__main__":
main()
| 41.934911 | 100 | 0.56272 |
import argparse, os
from migen import *
from litex_boards.platforms import alveo_u250
from litex.soc.cores.clock import *
from litex.soc.integration.soc_core import *
from litex.soc.integration.soc_sdram import *
from litex.soc.integration.builder import *
from litex.soc.cores.led import LedChaser
from litedram.modules import MTA18ASF2G72PZ
from litedram.phy import usddrphy
from litepcie.phy.usppciephy import USPPCIEPHY
from litepcie.core import LitePCIeEndpoint, LitePCIeMSI
from litepcie.frontend.dma import LitePCIeDMA
from litepcie.frontend.wishbone import LitePCIeWishboneBridge
from litepcie.software import generate_litepcie_software
class _CRG(Module):
def __init__(self, platform, sys_clk_freq):
self.clock_domains.cd_sys = ClockDomain()
self.clock_domains.cd_sys4x = ClockDomain(reset_less=True)
self.clock_domains.cd_pll4x = ClockDomain(reset_less=True)
self.clock_domains.cd_clk500 = ClockDomain()
self.submodules.pll = pll = USMMCM(speedgrade=-2)
self.comb += pll.reset.eq(0)
pll.register_clkin(platform.request("clk300", 0), 300e6)
pll.create_clkout(self.cd_pll4x, sys_clk_freq*4, buf=None, with_reset=False)
pll.create_clkout(self.cd_clk500, 500e6, with_reset=False)
self.specials += [
Instance("BUFGCE_DIV", name="main_bufgce_div",
p_BUFGCE_DIVIDE=4,
i_CE=1, i_I=self.cd_pll4x.clk, o_O=self.cd_sys.clk),
Instance("BUFGCE", name="main_bufgce",
i_CE=1, i_I=self.cd_pll4x.clk, o_O=self.cd_sys4x.clk),
AsyncResetSynchronizer(self.cd_clk500, ~pll.locked),
]
self.submodules.idelayctrl = USIDELAYCTRL(cd_ref=self.cd_clk500, cd_sys=self.cd_sys)
class BaseSoC(SoCCore):
def __init__(self, sys_clk_freq=int(125e6), with_pcie=False, **kwargs):
platform = alveo_u250.Platform()
SoCCore.__init__(self, platform, sys_clk_freq,
ident = "LiteX SoC on Alveo U250",
ident_version = True,
**kwargs)
self.submodules.crg = _CRG(platform, sys_clk_freq)
if not self.integrated_main_ram_size:
self.submodules.ddrphy = usddrphy.USPDDRPHY(platform.request("ddram"),
memtype = "DDR4",
sys_clk_freq = sys_clk_freq,
iodelay_clk_freq = 500e6,
cmd_latency = 1,
is_rdimm = True)
self.add_csr("ddrphy")
self.add_sdram("sdram",
phy = self.ddrphy,
module = MTA18ASF2G72PZ(sys_clk_freq, "1:4"),
origin = self.mem_map["main_ram"],
size = kwargs.get("max_sdram_size", 0x40000000),
l2_cache_size = kwargs.get("l2_size", 8192),
l2_cache_min_data_width = kwargs.get("min_l2_data_width", 128),
l2_cache_reverse = True
)
self.add_ram("firmware_ram", 0x20000000, 0x8000)
if with_pcie:
self.submodules.pcie_phy = USPPCIEPHY(platform, platform.request("pcie_x4"),
data_width = 128,
bar0_size = 0x20000)
platform.add_false_path_constraints(self.crg.cd_sys.clk, self.pcie_phy.cd_pcie.clk)
self.add_csr("pcie_phy")
self.submodules.pcie_endpoint = LitePCIeEndpoint(self.pcie_phy, max_pending_requests=8)
self.submodules.pcie_bridge = LitePCIeWishboneBridge(self.pcie_endpoint,
base_address = self.mem_map["csr"])
self.add_wb_master(self.pcie_bridge.wishbone)
self.submodules.pcie_dma0 = LitePCIeDMA(self.pcie_phy, self.pcie_endpoint,
with_buffering = True, buffering_depth=1024,
with_loopback = True)
self.add_csr("pcie_dma0")
self.add_constant("DMA_CHANNELS", 1)
self.submodules.pcie_msi = LitePCIeMSI()
self.add_csr("pcie_msi")
self.comb += self.pcie_msi.source.connect(self.pcie_phy.msi)
self.interrupts = {
"PCIE_DMA0_WRITER": self.pcie_dma0.writer.irq,
"PCIE_DMA0_READER": self.pcie_dma0.reader.irq,
}
for i, (k, v) in enumerate(sorted(self.interrupts.items())):
self.comb += self.pcie_msi.irqs[i].eq(v)
self.add_constant(k + "_INTERRUPT", i)
self.submodules.leds = LedChaser(
pads = platform.request_all("user_led"),
sys_clk_freq = sys_clk_freq)
self.add_csr("leds")
def main():
parser = argparse.ArgumentParser(description="LiteX SoC on Alveo U250")
parser.add_argument("--build", action="store_true", help="Build bitstream")
parser.add_argument("--with-pcie", action="store_true", help="Enable PCIe support")
parser.add_argument("--driver", action="store_true", help="Generate PCIe driver")
parser.add_argument("--load", action="store_true", help="Load bitstream")
builder_args(parser)
soc_sdram_args(parser)
args = parser.parse_args()
args.csr_data_width = 32
soc = BaseSoC(with_pcie=args.with_pcie, **soc_sdram_argdict(args))
builder = Builder(soc, **builder_argdict(args))
builder.build(run=args.build)
if args.driver:
generate_litepcie_software(soc, os.path.join(builder.output_dir, "driver"))
if args.load:
prog = soc.platform.create_programmer()
prog.load_bitstream(os.path.join(builder.gateware_dir, soc.build_name + ".bit"))
if __name__ == "__main__":
main()
| true | true |
f7317da5336aa017fc94a0299d3bac8f2c5c34b4 | 7,740 | py | Python | facebook_insights/metrics.py | jaylynch/django-facebook-insights | b10f1662f2f346bea19bc84629a8079257c9d710 | [
"MIT"
] | null | null | null | facebook_insights/metrics.py | jaylynch/django-facebook-insights | b10f1662f2f346bea19bc84629a8079257c9d710 | [
"MIT"
] | null | null | null | facebook_insights/metrics.py | jaylynch/django-facebook-insights | b10f1662f2f346bea19bc84629a8079257c9d710 | [
"MIT"
] | 1 | 2019-05-30T06:23:47.000Z | 2019-05-30T06:23:47.000Z | """Tools to fetch and extract Facebook Insights metrics.
>>> graph_id = '1234567890'
>>> metrics = ['page_impressions', 'page_engaged_users']
>>> page_metrics = fetch_metrics(graph_id, metrics)
>>> page_impressions = page_metrics['page_impressions']
>>> page_impressions.values
{'day': [
{'end_time': '2016-11-15T08:00:00+0000', 'value': 0},
{'end_time': '2016-11-16T08:00:00+0000', 'value': 1},
{'end_time': '2016-11-17T08:00:00+0000', 'value': 2},
],
'week': [
{'end_time': '2016-11-15T08:00:00+0000', 'value': 10},
{'end_time': '2016-11-16T08:00:00+0000', 'value': 11},
{'end_time': '2016-11-17T08:00:00+0000', 'value': 12},
],
'days_28': [
{'end_time': '2016-11-15T08:00:00+0000', 'value': 100},
{'end_time': '2016-11-16T08:00:00+0000', 'value': 101},
{'end_time': '2016-11-17T08:00:00+0000', 'value': 102},
]
}
>>> page_impressions.get_value('day')
{'end_time': '2016-11-17T08:00:00+0000', 'value': 2}
>>> page_impressions.get_value('day', extract=True)
2
>>> page_impressions.get_value('week', index=0)
{'end_time': '2016-11-15T08:00:00+0000', 'value': 10}
>>> page_impressions.get_value('week', index=0, extract=True)
10
>>> get_all_values()
{'day': {'end_time': '2016-11-17T08:00:00+0000', 'value': 2},
'week': {'end_time': '2016-11-17T08:00:00+0000', 'value': 12},
'days_28': {'end_time': '2016-11-17T08:00:00+0000', 'value': 102}}
>>> get_all_values(extract=True)
{'day': 2, 'week': 12, 'days_28': 102}
>>> get_all_values(index=0, extract=True)
{'day': 0, 'week': 10, 'days_28': 100}
"""
import json
from django.conf import settings
from facebook import GraphAPI, GraphAPIError
from facebook_insights.exceptions import EmptyData, MetricsNotSpecified
__all__ = ['fetch_metrics', 'Metric']
access_token = settings.FACEBOOK_INSIGHTS_ACCESS_TOKEN
api_version = getattr(settings, 'FACEBOOK_INSIGHTS_API_VERSION', None)
graph_api = GraphAPI(access_token=access_token, version=api_version)
def fetch_metrics(graph_id, metrics, token=None):
"""Fetch Facebook Insights metrics for an object with a given id.
Parameters
----------
graph_id : str
The Facebook ID of a Graph API object.
metrics : iterable of str
The object's metrics to fetch (e.g. 'page_engaged_users').
token: str
A Facebook Graph API access token
Returns
-------
dict
A dictionary of mappings between metric names and instances
of class 'Metric'.
"""
if not metrics:
raise MetricsNotSpecified('Specify metrics you want to fetch.')
batch = []
for metric in metrics:
request_data = {
'method': 'GET',
'relative_url': '{}/insights/{}/'.format(graph_id, metric)
}
batch.append(request_data)
# ##TODON'T##
global graph_api
if token and (token != graph_api.access_token):
graph_api = GraphAPI(access_token=token, version=api_version)
batch_response = graph_api.put_object(
parent_object='/',
connection_name='',
batch=json.dumps(batch),
)
extracted_metrics = {}
for response in batch_response:
body = json.loads(response['body'])
# (nevimov/2016-11-09): Currently facebook-sdk is not
# able to catch errors in responses to batch requests, so
# we have to take care of those ourselves.
if 'error' in body:
raise GraphAPIError(body)
data = body['data']
if not data:
# We need a better middle ground for this but just
# raising exceptions doesn't work when some of a
# set can legitimately be empty
continue
# raise EmptyData
rearranged_values = {}
for datum in data:
name = datum['name']
period = datum['period']
rearranged_values[period] = datum['values']
extracted_metrics[name] = Metric(name, rearranged_values)
return extracted_metrics
class Metric(object):
"""A Facebook Insights metric.
Parameters
----------
name : str
The name of a metric (e.g. 'post_impressions' or 'page_engaged_users').
values : dict of list of dict
Values to associate with the metric. Must be a dictionary of mappings
between periods ('day', 'week', 'days_28', 'lifetime') and lists of
their respective values, for example:
# The format typical for post metrics
{'lifetime': [{'value': 1000}]}
# The format typical for page metrics
{'day': [
{'end_time': '2016-11-15T08:00:00+0000', 'value': 0},
{'end_time': '2016-11-16T08:00:00+0000', 'value': 1},
{'end_time': '2016-11-17T08:00:00+0000', 'value': 2},
],
'week': [
{'end_time': '2016-11-15T08:00:00+0000', 'value': 10},
{'end_time': '2016-11-16T08:00:00+0000', 'value': 11},
{'end_time': '2016-11-17T08:00:00+0000', 'value': 12},
],
'days_28': [
{'end_time': '2016-11-15T08:00:00+0000', 'value': 100},
{'end_time': '2016-11-16T08:00:00+0000', 'value': 101},
{'end_time': '2016-11-17T08:00:00+0000', 'value': 102},
]}
Attributes
----------
name : str
The name of the metric.
values : list of dict of list
The values associated with the metric.
"""
def __init__(self, name, values):
self.name = name
self.values = values
def get_value(self, period=None, index=-1, extract=False):
"""Get the metric's value for a given period.
Parameters
----------
period: {None, 'day', 'week', 'days_28', 'lifetime'}
A period for which you want to get the value.
Can be omitted for metrics available only for one period
(e.g. all the post_impressions_* metrics).
index : int
For many metrics (e.g. most of page metrics) Facebook sends
values for 3 consecutive days. By default this method returns
the last value. If you want to get a previous value, pass
`index` in range from 0 to 2 (or from -1 to -3).
extract : bool
By default the return value is a dictionary containing key
'value' (most of page metrics also have 'end_time').
If `extract` is True, then simply the value associated with
this key is returned.
Returns
-------
The return value can be either:
* dictionary containing one key, 'value' (most of post metrics)
* dictionary containing two keys, 'value' and 'end_time'
(most of page metrics)
Pass `extract=True`, if you don't care about the 'end_time' and
need only the value.
"""
values = self.values
if not period:
if len(values) == 1:
period = list(values.keys())[0]
else:
raise TypeError(
"Can't get a period. Argument 'period' can be omitted "
"only for metrics that have one period."
)
value = values[period][index]
if extract:
return value['value']
return value
def get_all_values(self, index=-1, extract=False):
"""Get values for all periods.
Parameters
----------
Arguments `index` and `extract` have the same meaning as for
get_value().
Returns
-------
dict
A mapping of periods to values.
"""
all_values = {}
for period in self.values:
all_values[period] = self.get_value(period, index, extract)
return all_values
| 34.247788 | 79 | 0.589922 | import json
from django.conf import settings
from facebook import GraphAPI, GraphAPIError
from facebook_insights.exceptions import EmptyData, MetricsNotSpecified
__all__ = ['fetch_metrics', 'Metric']
access_token = settings.FACEBOOK_INSIGHTS_ACCESS_TOKEN
api_version = getattr(settings, 'FACEBOOK_INSIGHTS_API_VERSION', None)
graph_api = GraphAPI(access_token=access_token, version=api_version)
def fetch_metrics(graph_id, metrics, token=None):
if not metrics:
raise MetricsNotSpecified('Specify metrics you want to fetch.')
batch = []
for metric in metrics:
request_data = {
'method': 'GET',
'relative_url': '{}/insights/{}/'.format(graph_id, metric)
}
batch.append(request_data)
if token and (token != graph_api.access_token):
graph_api = GraphAPI(access_token=token, version=api_version)
batch_response = graph_api.put_object(
parent_object='/',
connection_name='',
batch=json.dumps(batch),
)
extracted_metrics = {}
for response in batch_response:
body = json.loads(response['body'])
# (nevimov/2016-11-09): Currently facebook-sdk is not
# able to catch errors in responses to batch requests, so
# we have to take care of those ourselves.
if 'error' in body:
raise GraphAPIError(body)
data = body['data']
if not data:
# We need a better middle ground for this but just
# raising exceptions doesn't work when some of a
continue
rearranged_values = {}
for datum in data:
name = datum['name']
period = datum['period']
rearranged_values[period] = datum['values']
extracted_metrics[name] = Metric(name, rearranged_values)
return extracted_metrics
class Metric(object):
def __init__(self, name, values):
self.name = name
self.values = values
def get_value(self, period=None, index=-1, extract=False):
values = self.values
if not period:
if len(values) == 1:
period = list(values.keys())[0]
else:
raise TypeError(
"Can't get a period. Argument 'period' can be omitted "
"only for metrics that have one period."
)
value = values[period][index]
if extract:
return value['value']
return value
def get_all_values(self, index=-1, extract=False):
all_values = {}
for period in self.values:
all_values[period] = self.get_value(period, index, extract)
return all_values
| true | true |
f7317e2c185510c822951fefebfbee8e10479664 | 38,094 | py | Python | t3f/riemannian.py | aiboyko/t3f | 0361b80f36a06eb5aa5d536650eef9e006289139 | [
"MIT"
] | null | null | null | t3f/riemannian.py | aiboyko/t3f | 0361b80f36a06eb5aa5d536650eef9e006289139 | [
"MIT"
] | null | null | null | t3f/riemannian.py | aiboyko/t3f | 0361b80f36a06eb5aa5d536650eef9e006289139 | [
"MIT"
] | null | null | null | import tensorflow.compat.v1 as tf
from t3f.tensor_train import TensorTrain
from t3f.tensor_train_batch import TensorTrainBatch
from t3f import shapes
from t3f import decompositions
def project_sum(what, where, weights=None):
"""Project sum of `what` TTs on the tangent space of `where` TT.
project_sum(what, x) = P_x(what)
project_sum(batch_what, x) = P_x(\sum_i batch_what[i])
project_sum(batch_what, x, weights) = P_x(\sum_j weights[j] * batch_what[j])
This function implements the algorithm from the paper [1], theorem 3.1.
[1] C. Lubich, I. Oseledets and B. Vandereycken, Time integration of
Tensor Trains.
Args:
what: TensorTrain or TensorTrainBatch. In the case of batch returns
projection of the sum of elements in the batch.
where: TensorTrain, TT-tensor or TT-matrix on which tangent space to project
weights: python list or tf.Tensor of numbers or None, weights of the sum
Returns:
a TensorTrain with the TT-ranks equal 2 * tangent_space_tens.get_tt_ranks()
Complexity:
O(d r_where^3 m) for orthogonalizing the TT-cores of where
+O(batch_size d r_what r_where n (r_what + r_where))
d is the number of TT-cores (what.ndims());
r_what is the largest TT-rank of what max(what.get_tt_rank())
r_where is the largest TT-rank of where
n is the size of the axis dimension of what and where e.g.
for a tensor of size 4 x 4 x 4, n is 4;
for a 9 x 64 matrix of raw shape (3, 3, 3) x (4, 4, 4) n is 12
"""
# Always work with batch of TT objects for simplicity.
what = shapes.expand_batch_dim(what)
if weights is not None:
weights = tf.convert_to_tensor(weights, dtype=where.dtype)
if not isinstance(where, TensorTrain):
raise ValueError('The first argument should be a TensorTrain object, got '
'"%s".' % where)
if where.get_raw_shape() != what.get_raw_shape():
raise ValueError('The shapes of the tensor we want to project and of the '
'tensor on which tangent space we want to project should '
'match, got %s and %s.' %
(where.get_raw_shape(),
what.get_raw_shape()))
dtypes_compatible = (where.dtype.is_compatible_with(what.dtype) or
what.dtype.is_compatible_with(where.dtype))
if not dtypes_compatible:
raise ValueError('Dtypes of the arguments should coincide, got %s and %s.' %
(where.dtype,
what.dtype))
left_tangent_space_tens = decompositions.orthogonalize_tt_cores(
where)
right_tangent_space_tens = decompositions.orthogonalize_tt_cores(
left_tangent_space_tens, left_to_right=False)
ndims = where.ndims()
dtype = where.dtype
raw_shape = shapes.lazy_raw_shape(where)
batch_size = shapes.lazy_batch_size(what)
right_tangent_tt_ranks = shapes.lazy_tt_ranks(right_tangent_space_tens)
left_tangent_tt_ranks = shapes.lazy_tt_ranks(left_tangent_space_tens)
# For einsum notation.
mode_str = 'ij' if where.is_tt_matrix() else 'i'
right_rank_dim = where.right_tt_rank_dim
left_rank_dim = where.left_tt_rank_dim
if weights is not None:
weights_shape = weights.get_shape()
output_is_batch = len(weights_shape) > 1 and weights_shape[1] > 1
else:
output_is_batch = False
output_batch_str = 'o' if output_is_batch else ''
if output_is_batch:
right_rank_dim += 1
left_rank_dim += 1
output_batch_size = weights.get_shape()[1].value
# Prepare rhs vectors.
# rhs[core_idx] is of size
# batch_size x tensor_tt_ranks[core_idx] x tangent_tt_ranks[core_idx]
rhs = [None] * (ndims + 1)
rhs[ndims] = tf.ones((batch_size, 1, 1), dtype=dtype)
for core_idx in range(ndims - 1, 0, -1):
tens_core = what.tt_cores[core_idx]
right_tang_core = right_tangent_space_tens.tt_cores[core_idx]
einsum_str = 'sa{0}b,sbd,c{0}d->sac'.format(mode_str)
rhs[core_idx] = tf.einsum(einsum_str, tens_core, rhs[core_idx + 1],
right_tang_core)
# Prepare lhs vectors.
# lhs[core_idx] is of size
# batch_size x tangent_tt_ranks[core_idx] x tensor_tt_ranks[core_idx]
lhs = [None] * (ndims + 1)
lhs[0] = tf.ones((batch_size, 1, 1), dtype=dtype)
for core_idx in range(ndims - 1):
tens_core = what.tt_cores[core_idx]
left_tang_core = left_tangent_space_tens.tt_cores[core_idx]
einsum_str = 'sab,a{0}c,sb{0}d->scd'.format(mode_str)
lhs[core_idx + 1] = tf.einsum(einsum_str, lhs[core_idx], left_tang_core,
tens_core)
# Left to right sweep.
res_cores_list = []
for core_idx in range(ndims):
tens_core = what.tt_cores[core_idx]
left_tang_core = left_tangent_space_tens.tt_cores[core_idx]
right_tang_core = right_tangent_space_tens.tt_cores[core_idx]
if core_idx < ndims - 1:
einsum_str = 'sab,sb{0}c->sa{0}c'.format(mode_str)
proj_core = tf.einsum(einsum_str, lhs[core_idx], tens_core)
einsum_str = 'a{0}b,sbc->sa{0}c'.format(mode_str)
proj_core -= tf.einsum(einsum_str, left_tang_core, lhs[core_idx + 1])
if weights is None:
einsum_str = 'sa{0}b,sbc->a{0}c'.format(mode_str)
proj_core = tf.einsum(einsum_str, proj_core, rhs[core_idx + 1])
else:
einsum_str = 'sa{0}b,sbc->sa{0}c'.format(mode_str, output_batch_str)
proj_core_s = tf.einsum(einsum_str, proj_core, rhs[core_idx + 1])
einsum_str = 's{1},sa{0}c->{1}a{0}c'.format(mode_str, output_batch_str)
proj_core = tf.einsum(einsum_str, weights, proj_core_s)
if core_idx == ndims - 1:
if weights is None:
einsum_str = 'sab,sb{0}c->a{0}c'.format(mode_str)
proj_core = tf.einsum(einsum_str, lhs[core_idx], tens_core)
else:
einsum_str = 'sab,sb{0}c->sa{0}c'.format(mode_str, output_batch_str)
proj_core_s = tf.einsum(einsum_str, lhs[core_idx], tens_core)
einsum_str = 's{1},sa{0}c->{1}a{0}c'.format(mode_str, output_batch_str)
proj_core = tf.einsum(einsum_str, weights, proj_core_s)
if output_is_batch:
# Add batch dimension of size output_batch_size to left_tang_core and
# right_tang_core
extended_left_tang_core = tf.expand_dims(left_tang_core, 0)
extended_right_tang_core = tf.expand_dims(right_tang_core, 0)
if where.is_tt_matrix():
extended_left_tang_core = tf.tile(extended_left_tang_core,
[output_batch_size, 1, 1, 1, 1])
extended_right_tang_core = tf.tile(extended_right_tang_core,
[output_batch_size, 1, 1, 1, 1])
else:
extended_left_tang_core = tf.tile(extended_left_tang_core,
[output_batch_size, 1, 1, 1])
extended_right_tang_core = tf.tile(extended_right_tang_core,
[output_batch_size, 1, 1, 1])
else:
extended_left_tang_core = left_tang_core
extended_right_tang_core = right_tang_core
if core_idx == 0:
res_core = tf.concat((proj_core, extended_left_tang_core),
axis=right_rank_dim)
elif core_idx == ndims - 1:
res_core = tf.concat((extended_right_tang_core, proj_core), axis=left_rank_dim)
else:
rank_1 = right_tangent_tt_ranks[core_idx]
rank_2 = left_tangent_tt_ranks[core_idx + 1]
if where.is_tt_matrix():
mode_size_n = raw_shape[0][core_idx]
mode_size_m = raw_shape[1][core_idx]
shape = [rank_1, mode_size_n, mode_size_m, rank_2]
else:
mode_size = raw_shape[0][core_idx]
shape = [rank_1, mode_size, rank_2]
if output_is_batch:
shape = [output_batch_size] + shape
zeros = tf.zeros(shape, dtype)
upper = tf.concat((extended_right_tang_core, zeros), axis=right_rank_dim)
lower = tf.concat((proj_core, extended_left_tang_core),
axis=right_rank_dim)
res_core = tf.concat((upper, lower), axis=left_rank_dim)
res_cores_list.append(res_core)
# TODO: TT-ranks.
if output_is_batch:
res = TensorTrainBatch(res_cores_list, where.get_raw_shape(),
batch_size=output_batch_size)
else:
res = TensorTrain(res_cores_list, where.get_raw_shape())
res.projection_on = where
return res
def project(what, where):
"""Project `what` TTs on the tangent space of `where` TT.
project(what, x) = P_x(what)
project(batch_what, x) = batch(P_x(batch_what[0]), ..., P_x(batch_what[N]))
This function implements the algorithm from the paper [1], theorem 3.1.
[1] C. Lubich, I. Oseledets and B. Vandereycken, Time integration of
Tensor Trains.
Args:
what: TensorTrain or TensorTrainBatch. In the case of batch returns
batch with projection of each individual tensor.
where: TensorTrain, TT-tensor or TT-matrix on which tangent space to project
Returns:
a TensorTrain with the TT-ranks equal 2 * tangent_space_tens.get_tt_ranks()
Complexity:
O(d r_where^3 m) for orthogonalizing the TT-cores of where
+O(batch_size d r_what r_where n (r_what + r_where))
d is the number of TT-cores (what.ndims());
r_what is the largest TT-rank of what max(what.get_tt_rank())
r_where is the largest TT-rank of where
n is the size of the axis dimension of what and where e.g.
for a tensor of size 4 x 4 x 4, n is 4;
for a 9 x 64 matrix of raw shape (3, 3, 3) x (4, 4, 4) n is 12
"""
if not isinstance(where, TensorTrain):
raise ValueError('The first argument should be a TensorTrain object, got '
'"%s".' % where)
if where.get_raw_shape() != what.get_raw_shape():
raise ValueError('The shapes of the tensor we want to project and of the '
'tensor on which tangent space we want to project should '
'match, got %s and %s.' %
(where.get_raw_shape(),
what.get_raw_shape()))
dtypes_compatible = (where.dtype.is_compatible_with(what.dtype) or
what.dtype.is_compatible_with(where.dtype))
if not dtypes_compatible:
raise ValueError('Dtypes of the arguments should coincide, got %s and %s.' %
(where.dtype,
what.dtype))
left_tangent_space_tens = decompositions.orthogonalize_tt_cores(
where)
right_tangent_space_tens = decompositions.orthogonalize_tt_cores(
left_tangent_space_tens, left_to_right=False)
ndims = where.ndims()
dtype = where.dtype
raw_shape = shapes.lazy_raw_shape(where)
right_tangent_tt_ranks = shapes.lazy_tt_ranks(right_tangent_space_tens)
left_tangent_tt_ranks = shapes.lazy_tt_ranks(left_tangent_space_tens)
# For einsum notation.
mode_str = 'ij' if where.is_tt_matrix() else 'i'
right_rank_dim = what.right_tt_rank_dim
left_rank_dim = what.left_tt_rank_dim
output_is_batch = isinstance(what, TensorTrainBatch)
if output_is_batch:
output_batch_size = what.batch_size
# Always work with batch of TT objects for simplicity.
what = shapes.expand_batch_dim(what)
batch_size = shapes.lazy_batch_size(what)
# Prepare rhs vectors.
# rhs[core_idx] is of size
# batch_size x tensor_tt_ranks[core_idx] x tangent_tt_ranks[core_idx]
rhs = [None] * (ndims + 1)
rhs[ndims] = tf.ones((batch_size, 1, 1), dtype=dtype)
for core_idx in range(ndims - 1, 0, -1):
tens_core = what.tt_cores[core_idx]
right_tang_core = right_tangent_space_tens.tt_cores[core_idx]
einsum_str = 'sa{0}b,sbd,c{0}d->sac'.format(mode_str)
rhs[core_idx] = tf.einsum(einsum_str, tens_core, rhs[core_idx + 1],
right_tang_core)
# Prepare lhs vectors.
# lhs[core_idx] is of size
# batch_size x tangent_tt_ranks[core_idx] x tensor_tt_ranks[core_idx]
lhs = [None] * (ndims + 1)
lhs[0] = tf.ones((batch_size, 1, 1), dtype=dtype)
for core_idx in range(ndims - 1):
tens_core = what.tt_cores[core_idx]
left_tang_core = left_tangent_space_tens.tt_cores[core_idx]
einsum_str = 'sab,a{0}c,sb{0}d->scd'.format(mode_str)
lhs[core_idx + 1] = tf.einsum(einsum_str, lhs[core_idx], left_tang_core,
tens_core)
# Left to right sweep.
res_cores_list = []
for core_idx in range(ndims):
tens_core = what.tt_cores[core_idx]
left_tang_core = left_tangent_space_tens.tt_cores[core_idx]
right_tang_core = right_tangent_space_tens.tt_cores[core_idx]
if core_idx < ndims - 1:
einsum_str = 'sab,sb{0}c->sa{0}c'.format(mode_str)
proj_core = tf.einsum(einsum_str, lhs[core_idx], tens_core)
einsum_str = 'a{0}b,sbc->sa{0}c'.format(mode_str)
proj_core -= tf.einsum(einsum_str, left_tang_core, lhs[core_idx + 1])
if output_is_batch:
einsum_str = 'sa{0}b,sbc->sa{0}c'.format(mode_str)
else:
einsum_str = 'sa{0}b,sbc->a{0}c'.format(mode_str)
proj_core = tf.einsum(einsum_str, proj_core, rhs[core_idx + 1])
if core_idx == ndims - 1:
if output_is_batch:
einsum_str = 'sab,sb{0}c->sa{0}c'.format(mode_str)
else:
einsum_str = 'sab,sb{0}c->a{0}c'.format(mode_str)
proj_core = tf.einsum(einsum_str, lhs[core_idx], tens_core)
if output_is_batch:
# Add batch dimension of size output_batch_size to left_tang_core and
# right_tang_core
extended_left_tang_core = tf.expand_dims(left_tang_core, 0)
extended_right_tang_core = tf.expand_dims(right_tang_core, 0)
if where.is_tt_matrix():
extended_left_tang_core = tf.tile(extended_left_tang_core,
[output_batch_size, 1, 1, 1, 1])
extended_right_tang_core = tf.tile(extended_right_tang_core,
[output_batch_size, 1, 1, 1, 1])
else:
extended_left_tang_core = tf.tile(extended_left_tang_core,
[output_batch_size, 1, 1, 1])
extended_right_tang_core = tf.tile(extended_right_tang_core,
[output_batch_size, 1, 1, 1])
else:
extended_left_tang_core = left_tang_core
extended_right_tang_core = right_tang_core
if core_idx == 0:
res_core = tf.concat((proj_core, extended_left_tang_core),
axis=right_rank_dim)
elif core_idx == ndims - 1:
res_core = tf.concat((extended_right_tang_core, proj_core), axis=left_rank_dim)
else:
rank_1 = right_tangent_tt_ranks[core_idx]
rank_2 = left_tangent_tt_ranks[core_idx + 1]
if where.is_tt_matrix():
mode_size_n = raw_shape[0][core_idx]
mode_size_m = raw_shape[1][core_idx]
shape = [rank_1, mode_size_n, mode_size_m, rank_2]
else:
mode_size = raw_shape[0][core_idx]
shape = [rank_1, mode_size, rank_2]
if output_is_batch:
shape = [output_batch_size] + shape
zeros = tf.zeros(shape, dtype)
upper = tf.concat((extended_right_tang_core, zeros), axis=right_rank_dim)
lower = tf.concat((proj_core, extended_left_tang_core),
axis=right_rank_dim)
res_core = tf.concat((upper, lower), axis=left_rank_dim)
res_cores_list.append(res_core)
# TODO: TT-ranks.
if output_is_batch:
res = TensorTrainBatch(res_cores_list, where.get_raw_shape(),
batch_size=output_batch_size)
else:
res = TensorTrain(res_cores_list, where.get_raw_shape())
res.projection_on = where
return res
def project_matmul(what, where, matrix):
"""Project `matrix` * `what` TTs on the tangent space of `where` TT.
project(what, x) = P_x(what)
project(batch_what, x) = batch(P_x(batch_what[0]), ..., P_x(batch_what[N]))
This function implements the algorithm from the paper [1], theorem 3.1.
[1] C. Lubich, I. Oseledets and B. Vandereycken, Time integration of
Tensor Trains.
Args:
what: TensorTrain or TensorTrainBatch. In the case of batch returns
batch with projection of each individual tensor.
where: TensorTrain, TT-tensor or TT-matrix on which tangent space to project
matrix: TensorTrain, TT-matrix to multiply by what
Returns:
a TensorTrain with the TT-ranks equal 2 * tangent_space_tens.get_tt_ranks()
Complexity:
O(d r_where^3 m) for orthogonalizing the TT-cores of where
+O(batch_size d R r_what r_where (n r_what + n m R + m r_where))
d is the number of TT-cores (what.ndims());
r_what is the largest TT-rank of what max(what.get_tt_rank())
r_where is the largest TT-rank of where
matrix is of TT-rank R and of raw-shape (m, m, ..., m) x (n, n, ..., n).
"""
if not isinstance(where, TensorTrain):
raise ValueError('The first argument should be a TensorTrain object, got '
'"%s".' % where)
if where.get_raw_shape() != what.get_raw_shape():
raise ValueError('The shapes of the tensor we want to project and of the '
'tensor on which tangent space we want to project should '
'match, got %s and %s.' %
(where.get_raw_shape(),
what.get_raw_shape()))
dtypes_compatible = (where.dtype.is_compatible_with(what.dtype) or
what.dtype.is_compatible_with(where.dtype))
if not dtypes_compatible:
raise ValueError('Dtypes of the arguments should coincide, got %s and %s.' %
(where.dtype,
what.dtype))
left_tangent_space_tens = decompositions.orthogonalize_tt_cores(
where)
right_tangent_space_tens = decompositions.orthogonalize_tt_cores(
left_tangent_space_tens, left_to_right=False)
ndims = where.ndims()
dtype = where.dtype
raw_shape = shapes.lazy_raw_shape(where)
batch_size = shapes.lazy_batch_size(what)
right_tangent_tt_ranks = shapes.lazy_tt_ranks(right_tangent_space_tens)
left_tangent_tt_ranks = shapes.lazy_tt_ranks(left_tangent_space_tens)
# For einsum notation.
right_rank_dim = what.right_tt_rank_dim
left_rank_dim = what.left_tt_rank_dim
output_is_batch = isinstance(what, TensorTrainBatch)
if output_is_batch:
output_batch_size = what.batch_size
# Always work with batch of TT objects for simplicity.
what = shapes.expand_batch_dim(what)
# Prepare rhs vectors.
# rhs[core_idx] is of size
# batch_size x tensor_tt_ranks[core_idx] x matrix_tt_ranks[core_idx] x tangent_tt_ranks[core_idx]
rhs = [None] * (ndims + 1)
rhs[ndims] = tf.ones((batch_size, 1, 1, 1), dtype=dtype)
for core_idx in range(ndims - 1, 0, -1):
tens_core = what.tt_cores[core_idx]
right_tang_core = right_tangent_space_tens.tt_cores[core_idx]
matrix_core = matrix.tt_cores[core_idx]
rhs[core_idx] = tf.einsum('bije,cikf,sdef,sajkd->sabc', matrix_core,
right_tang_core, rhs[core_idx + 1], tens_core)
# Prepare lhs vectors.
# lhs[core_idx] is of size
# batch_size x tangent_tt_ranks[core_idx] x matrix_tt_ranks[core_idx] x tensor_tt_ranks[core_idx]
lhs = [None] * (ndims + 1)
lhs[0] = tf.ones((batch_size, 1, 1, 1), dtype=dtype)
for core_idx in range(ndims - 1):
tens_core = what.tt_cores[core_idx]
left_tang_core = left_tangent_space_tens.tt_cores[core_idx]
matrix_core = matrix.tt_cores[core_idx]
# TODO: brutforce order of indices in lhs??
lhs[core_idx + 1] = tf.einsum('bije,aikd,sabc,scjkf->sdef', matrix_core,
left_tang_core, lhs[core_idx], tens_core)
# Left to right sweep.
res_cores_list = []
for core_idx in range(ndims):
tens_core = what.tt_cores[core_idx]
matrix_core = matrix.tt_cores[core_idx]
left_tang_core = left_tangent_space_tens.tt_cores[core_idx]
right_tang_core = right_tangent_space_tens.tt_cores[core_idx]
if core_idx < ndims - 1:
proj_core = tf.einsum('scjke,sabc,bijd->saikde', tens_core,
lhs[core_idx], matrix_core)
proj_core -= tf.einsum('aikb,sbcd->saikcd', left_tang_core,
lhs[core_idx + 1])
proj_core = tf.einsum('saikcb,sbcd->saikd', proj_core, rhs[core_idx + 1])
if core_idx == ndims - 1:
# d and e dimensions take 1 value, since its the last rank.
# To make the result shape (?, ?, ?, 1), we are summing d and leaving e,
# but we could have done the opposite -- sum e and leave d.
proj_core = tf.einsum('sabc,bijd,scjke->saike', lhs[core_idx], matrix_core,
tens_core)
if output_is_batch:
# Add batch dimension of size output_batch_size to left_tang_core and
# right_tang_core
extended_left_tang_core = tf.expand_dims(left_tang_core, 0)
extended_right_tang_core = tf.expand_dims(right_tang_core, 0)
extended_left_tang_core = tf.tile(extended_left_tang_core,
[output_batch_size, 1, 1, 1, 1])
extended_right_tang_core = tf.tile(extended_right_tang_core,
[output_batch_size, 1, 1, 1, 1])
else:
extended_left_tang_core = left_tang_core
extended_right_tang_core = right_tang_core
if core_idx == 0:
res_core = tf.concat((proj_core, extended_left_tang_core),
axis=right_rank_dim)
elif core_idx == ndims - 1:
res_core = tf.concat((extended_right_tang_core, proj_core),
axis=left_rank_dim)
else:
rank_1 = right_tangent_tt_ranks[core_idx]
rank_2 = left_tangent_tt_ranks[core_idx + 1]
mode_size_n = raw_shape[0][core_idx]
mode_size_m = raw_shape[1][core_idx]
shape = [rank_1, mode_size_n, mode_size_m, rank_2]
if output_is_batch:
shape = [output_batch_size] + shape
zeros = tf.zeros(shape, dtype)
upper = tf.concat((extended_right_tang_core, zeros),
axis=right_rank_dim)
lower = tf.concat((proj_core, extended_left_tang_core),
axis=right_rank_dim)
res_core = tf.concat((upper, lower), axis=left_rank_dim)
res_cores_list.append(res_core)
# TODO: TT-ranks.
if output_is_batch:
res = TensorTrainBatch(res_cores_list, where.get_raw_shape(),
batch_size=output_batch_size)
else:
res = TensorTrain(res_cores_list, where.get_raw_shape())
res.projection_on = where
return res
def pairwise_flat_inner_projected(projected_tt_vectors_1,
projected_tt_vectors_2):
"""Scalar products between two batches of TTs from the same tangent space.
res[i, j] = t3f.flat_inner(projected_tt_vectors_1[i], projected_tt_vectors_1[j]).
pairwise_flat_inner_projected(projected_tt_vectors_1, projected_tt_vectors_2)
is equivalent to
pairwise_flat_inner(projected_tt_vectors_1, projected_tt_vectors_2)
, but works only on objects from the same tangent space and is much faster
than general pairwise_flat_inner.
Args:
projected_tt_vectors_1: TensorTrainBatch of tensors projected on the same
tangent space as projected_tt_vectors_2.
projected_tt_vectors_2: TensorTrainBatch.
Returns:
tf.tensor with the scalar product matrix.
Complexity:
O(batch_size^2 d r^2 n), where
d is the number of TT-cores (projected_tt_vectors_1.ndims());
r is the largest TT-rank max(projected_tt_vectors_1.get_tt_rank())
(i.e. 2 * {the TT-rank of the object we projected vectors onto}.
and n is the size of the axis dimension, e.g.
for a tensor of size 4 x 4 x 4, n is 4;
for a 9 x 64 matrix of raw shape (3, 3, 3) x (4, 4, 4) n is 12.
"""
if not hasattr(projected_tt_vectors_1, 'projection_on') or \
not hasattr(projected_tt_vectors_2, 'projection_on'):
raise ValueError('Both arguments should be projections on the tangent '
'space of some other TT-object. All projection* functions '
'leave .projection_on field in the resulting TT-object '
'which is not present in the arguments you\'ve provided')
if projected_tt_vectors_1.projection_on != projected_tt_vectors_2.projection_on:
raise ValueError('Both arguments should be projections on the tangent '
'space of the same TT-object. The provided arguments are '
'projections on different TT-objects (%s and %s). Or at '
'least the pointers are different.' %
(projected_tt_vectors_1.projection_on,
projected_tt_vectors_2.projection_on))
# Always work with batches of objects for simplicity.
projected_tt_vectors_1 = shapes.expand_batch_dim(projected_tt_vectors_1)
projected_tt_vectors_2 = shapes.expand_batch_dim(projected_tt_vectors_2)
ndims = projected_tt_vectors_1.ndims()
tt_ranks = shapes.lazy_tt_ranks(projected_tt_vectors_1)
if projected_tt_vectors_1.is_tt_matrix():
right_size = tt_ranks[1] // 2
curr_core_1 = projected_tt_vectors_1.tt_cores[0]
curr_core_2 = projected_tt_vectors_2.tt_cores[0]
curr_du_1 = curr_core_1[:, :, :, :, :right_size]
curr_du_2 = curr_core_2[:, :, :, :, :right_size]
res = tf.einsum('paijb,qaijb->pq', curr_du_1, curr_du_2)
for core_idx in range(1, ndims):
left_size = tt_ranks[core_idx] // 2
right_size = tt_ranks[core_idx + 1] // 2
curr_core_1 = projected_tt_vectors_1.tt_cores[core_idx]
curr_core_2 = projected_tt_vectors_2.tt_cores[core_idx]
curr_du_1 = curr_core_1[:, left_size:, :, :, :right_size]
curr_du_2 = curr_core_2[:, left_size:, :, :, :right_size]
res += tf.einsum('paijb,qaijb->pq', curr_du_1, curr_du_2)
left_size = tt_ranks[-2] // 2
curr_core_1 = projected_tt_vectors_1.tt_cores[-1]
curr_core_2 = projected_tt_vectors_2.tt_cores[-1]
curr_du_1 = curr_core_1[:, left_size:, :, :, :]
curr_du_2 = curr_core_2[:, left_size:, :, :, :]
res += tf.einsum('paijb,qaijb->pq', curr_du_1, curr_du_2)
else:
# Working with TT-tensor, not TT-matrix.
right_size = tt_ranks[1] // 2
curr_core_1 = projected_tt_vectors_1.tt_cores[0]
curr_core_2 = projected_tt_vectors_2.tt_cores[0]
curr_du_1 = curr_core_1[:, :, :, :right_size]
curr_du_2 = curr_core_2[:, :, :, :right_size]
res = tf.einsum('paib,qaib->pq', curr_du_1, curr_du_2)
for core_idx in range(1, ndims):
left_size = tt_ranks[core_idx] // 2
right_size = tt_ranks[core_idx + 1] // 2
curr_core_1 = projected_tt_vectors_1.tt_cores[core_idx]
curr_core_2 = projected_tt_vectors_2.tt_cores[core_idx]
curr_du_1 = curr_core_1[:, left_size:, :, :right_size]
curr_du_2 = curr_core_2[:, left_size:, :, :right_size]
res += tf.einsum('paib,qaib->pq', curr_du_1, curr_du_2)
left_size = tt_ranks[-2] // 2
curr_core_1 = projected_tt_vectors_1.tt_cores[-1]
curr_core_2 = projected_tt_vectors_2.tt_cores[-1]
curr_du_1 = curr_core_1[:, left_size:, :, :]
curr_du_2 = curr_core_2[:, left_size:, :, :]
res += tf.einsum('paib,qaib->pq', curr_du_1, curr_du_2)
return res
def add_n_projected(tt_objects, coef=None):
"""Adds all input TT-objects that are projections on the same tangent space.
add_projected((a, b)) is equivalent add(a, b) for a and b that are from the
same tangent space, but doesn't increase the TT-ranks.
Args:
tt_objects: a list of TT-objects that are projections on the same tangent
space.
coef: a list of numbers or anything else convertable to tf.Tensor.
If provided, computes weighted sum. The size of this array should be
len(tt_objects) x tt_objects[0].batch_size
Returns:
TT-objects representing the sum of the tt_objects (weighted sum if coef is
provided). The TT-rank of the result equals to the TT-ranks of the arguments.
"""
for tt in tt_objects:
if not hasattr(tt, 'projection_on'):
raise ValueError('Both arguments should be projections on the tangent '
'space of some other TT-object. All projection* functions '
'leave .projection_on field in the resulting TT-object '
'which is not present in the argument you\'ve provided.')
projection_on = tt_objects[0].projection_on
for tt in tt_objects[1:]:
if tt.projection_on != projection_on:
raise ValueError('All tt_objects should be projections on the tangent '
'space of the same TT-object. The provided arguments are '
'projections on different TT-objects (%s and %s). Or at '
'least the pointers are different.' % (tt.projection_on,
projection_on))
if coef is not None:
coef = tf.convert_to_tensor(coef, dtype=tt_objects[0].dtype)
if coef.get_shape().ndims > 1:
# In batch case we will need to multiply each core by this coefficients
# along the first axis. To do it need to reshape the coefs to match
# the TT-cores number of dimensions.
some_core = tt_objects[0].tt_cores[0]
dim_array = [1] * (some_core.get_shape().ndims + 1)
dim_array[0] = coef.get_shape()[0].value
dim_array[1] = coef.get_shape()[1].value
coef = tf.reshape(coef, dim_array)
ndims = tt_objects[0].ndims()
tt_ranks = shapes.lazy_tt_ranks(tt_objects[0])
left_rank_dim = tt_objects[0].left_tt_rank_dim
right_rank_dim = tt_objects[0].right_tt_rank_dim
res_cores = []
def slice_tt_core(tt_core, left_idx, right_idx):
num_tt_core_dims = len(tt_core.get_shape())
idx = [slice(None)] * num_tt_core_dims
idx[left_rank_dim] = left_idx
idx[right_rank_dim] = right_idx
return tt_core[idx]
right_half_rank = tt_ranks[1] // 2
left_chunks = []
for obj_idx, tt in enumerate(tt_objects):
curr_core = slice_tt_core(tt.tt_cores[0], slice(None),
slice(0, right_half_rank))
if coef is not None:
curr_core *= coef[obj_idx]
left_chunks.append(curr_core)
left_part = tf.add_n(left_chunks)
first_obj_core = tt_objects[0].tt_cores[0]
right_part = slice_tt_core(first_obj_core, slice(None),
slice(right_half_rank, None))
first_core = tf.concat((left_part, right_part), axis=right_rank_dim)
res_cores.append(first_core)
for core_idx in range(1, ndims - 1):
first_obj_core = tt_objects[0].tt_cores[core_idx]
left_half_rank = tt_ranks[core_idx] // 2
right_half_rank = tt_ranks[core_idx + 1] // 2
upper_part = slice_tt_core(tt.tt_cores[core_idx], slice(0, left_half_rank),
slice(None))
lower_right_part = slice_tt_core(first_obj_core,
slice(left_half_rank, None),
slice(right_half_rank, None))
lower_left_chunks = []
for obj_idx, tt in enumerate(tt_objects):
curr_core = slice_tt_core(tt.tt_cores[core_idx],
slice(left_half_rank, None),
slice(0, right_half_rank))
if coef is not None:
curr_core *= coef[obj_idx]
lower_left_chunks.append(curr_core)
lower_left_part = tf.add_n(lower_left_chunks)
lower_part = tf.concat((lower_left_part, lower_right_part),
axis=right_rank_dim)
curr_core = tf.concat((upper_part, lower_part), axis=left_rank_dim)
res_cores.append(curr_core)
left_half_rank = tt_ranks[ndims - 1] // 2
upper_part = slice_tt_core(tt.tt_cores[-1], slice(0, left_half_rank),
slice(None))
lower_chunks = []
for obj_idx, tt in enumerate(tt_objects):
curr_core = slice_tt_core(tt.tt_cores[-1], slice(left_half_rank, None),
slice(None))
if coef is not None:
curr_core *= coef[obj_idx]
lower_chunks.append(curr_core)
lower_part = tf.add_n(lower_chunks)
last_core = tf.concat((upper_part, lower_part), axis=left_rank_dim)
res_cores.append(last_core)
raw_shape = tt_objects[0].get_raw_shape()
static_tt_ranks = tt_objects[0].get_tt_ranks()
if isinstance(tt_objects[0], TensorTrain):
res = TensorTrain(res_cores, raw_shape, static_tt_ranks)
elif isinstance(tt_objects[0], TensorTrainBatch):
res = TensorTrainBatch(res_cores, raw_shape, static_tt_ranks,
tt_objects[0].batch_size)
# Maintain the projection_on property.
res.projection_on = tt_objects[0].projection_on
return res
def tangent_space_to_deltas(tt, name='t3f_tangent_space_to_deltas'):
"""Convert an element of the tangent space to deltas representation.
Tangent space elements (outputs of t3f.project) look like:
dP1 V2 ... Vd + U1 dP2 V3 ... Vd + ... + U1 ... Ud-1 dPd.
This function takes as input an element of the tangent space and converts
it to the list of deltas [dP1, ..., dPd].
Args:
tt: `TensorTrain` or `TensorTrainBatch` that is a result of t3f.project,
t3f.project_matmul, or other similar functions.
name: string, name of the Op.
Returns:
A list of delta-cores (tf.Tensors).
"""
if not hasattr(tt, 'projection_on') or tt.projection_on is None:
raise ValueError('tt argument is supposed to be a projection, but it '
'lacks projection_on field')
num_dims = tt.ndims()
left_tt_rank_dim = tt.left_tt_rank_dim
right_tt_rank_dim = tt.right_tt_rank_dim
deltas = [None] * num_dims
tt_ranks = shapes.lazy_tt_ranks(tt)
for i in range(1, num_dims - 1):
if int(tt_ranks[i] / 2) != tt_ranks[i] / 2:
raise ValueError('tt argument is supposed to be a projection, but its '
'ranks are not even.')
with tf.name_scope(name, values=tt.tt_cores):
for i in range(1, num_dims - 1):
r1, r2 = tt_ranks[i], tt_ranks[i + 1]
curr_core = tt.tt_cores[i]
slc = [slice(None)] * len(curr_core.shape)
slc[left_tt_rank_dim] = slice(int(r1 / 2), None)
slc[right_tt_rank_dim] = slice(0, int(r2 / 2))
deltas[i] = curr_core[slc]
slc = [slice(None)] * len(tt.tt_cores[0].shape)
slc[right_tt_rank_dim] = slice(0, int(tt_ranks[1] / 2))
deltas[0] = tt.tt_cores[0][slc]
slc = [slice(None)] * len(tt.tt_cores[0].shape)
slc[left_tt_rank_dim] = slice(int(tt_ranks[-2] / 2), None)
deltas[num_dims - 1] = tt.tt_cores[num_dims - 1][slc]
return deltas
def deltas_to_tangent_space(deltas, tt, left=None, right=None,
name='t3f_deltas_to_tangent_space'):
"""Converts deltas representation of tangent space vector to TT object.
Takes as input a list of [dP1, ..., dPd] and returns
dP1 V2 ... Vd + U1 dP2 V3 ... Vd + ... + U1 ... Ud-1 dPd.
This function is hard to use correctly because deltas should abey the
so called gauge conditions. If the don't, the function will silently return
incorrect result. This is why this function is not imported in __init__.
Args:
deltas: a list of deltas (essentially TT-cores) obeying the gauge
conditions.
tt: `TensorTrain` object on which the tangent space tensor represented by
delta is projected.
left: t3f.orthogonilize_tt_cores(tt). If you have it already compute, you
may pass it as argument to avoid recomputing.
right: t3f.orthogonilize_tt_cores(left, left_to_right=False). If you have
it already compute, you may pass it as argument to avoid recomputing.
name: string, name of the Op.
Returns:
`TensorTrain` object constructed from deltas, that is from the tangent
space at point `tt`.
"""
cores = []
dtype = tt.dtype
num_dims = tt.ndims()
# TODO: add cache instead of mannually pasisng precomputed stuff?
input_tensors = list(tt.tt_cores) + list(deltas)
if left is not None:
input_tensors += list(left.tt_cores)
if right is not None:
input_tensors += list(right.tt_cores)
with tf.name_scope(name, values=input_tensors):
if left is None:
left = decompositions.orthogonalize_tt_cores(tt)
if right is None:
right = decompositions.orthogonalize_tt_cores(left, left_to_right=False)
left_tangent_tt_ranks = shapes.lazy_tt_ranks(left)
right_tangent_tt_ranks = shapes.lazy_tt_ranks(left)
raw_shape = shapes.lazy_raw_shape(left)
right_rank_dim = left.right_tt_rank_dim
left_rank_dim = left.left_tt_rank_dim
is_batch_case = len(deltas[0].shape) > len(tt.tt_cores[0].shape)
if is_batch_case:
right_rank_dim += 1
left_rank_dim += 1
batch_size = deltas[0].shape.as_list()[0]
for i in range(num_dims):
left_tt_core = left.tt_cores[i]
right_tt_core = right.tt_cores[i]
if is_batch_case:
tile = [1] * len(left_tt_core.shape)
tile = [batch_size] + tile
left_tt_core = tf.tile(left_tt_core[None, ...], tile)
right_tt_core = tf.tile(right_tt_core[None, ...], tile)
if i == 0:
tangent_core = tf.concat((deltas[i], left_tt_core),
axis=right_rank_dim)
elif i == num_dims - 1:
tangent_core = tf.concat((right_tt_core, deltas[i]),
axis=left_rank_dim)
else:
rank_1 = right_tangent_tt_ranks[i]
rank_2 = left_tangent_tt_ranks[i + 1]
if tt.is_tt_matrix():
mode_size_n = raw_shape[0][i]
mode_size_m = raw_shape[1][i]
shape = [rank_1, mode_size_n, mode_size_m, rank_2]
else:
mode_size_n = raw_shape[0][i]
shape = [rank_1, mode_size_n, rank_2]
if is_batch_case:
shape = [batch_size] + shape
zeros = tf.zeros(shape, dtype=dtype)
upper = tf.concat((right_tt_core, zeros), axis=right_rank_dim)
lower = tf.concat((deltas[i], left_tt_core), axis=right_rank_dim)
tangent_core = tf.concat((upper, lower), axis=left_rank_dim)
cores.append(tangent_core)
if is_batch_case:
tangent = TensorTrainBatch(cores, batch_size=batch_size)
else:
tangent = TensorTrain(cores)
tangent.projection_on = tt
return tangent
| 42.898649 | 101 | 0.664908 | import tensorflow.compat.v1 as tf
from t3f.tensor_train import TensorTrain
from t3f.tensor_train_batch import TensorTrainBatch
from t3f import shapes
from t3f import decompositions
def project_sum(what, where, weights=None):
what = shapes.expand_batch_dim(what)
if weights is not None:
weights = tf.convert_to_tensor(weights, dtype=where.dtype)
if not isinstance(where, TensorTrain):
raise ValueError('The first argument should be a TensorTrain object, got '
'"%s".' % where)
if where.get_raw_shape() != what.get_raw_shape():
raise ValueError('The shapes of the tensor we want to project and of the '
'tensor on which tangent space we want to project should '
'match, got %s and %s.' %
(where.get_raw_shape(),
what.get_raw_shape()))
dtypes_compatible = (where.dtype.is_compatible_with(what.dtype) or
what.dtype.is_compatible_with(where.dtype))
if not dtypes_compatible:
raise ValueError('Dtypes of the arguments should coincide, got %s and %s.' %
(where.dtype,
what.dtype))
left_tangent_space_tens = decompositions.orthogonalize_tt_cores(
where)
right_tangent_space_tens = decompositions.orthogonalize_tt_cores(
left_tangent_space_tens, left_to_right=False)
ndims = where.ndims()
dtype = where.dtype
raw_shape = shapes.lazy_raw_shape(where)
batch_size = shapes.lazy_batch_size(what)
right_tangent_tt_ranks = shapes.lazy_tt_ranks(right_tangent_space_tens)
left_tangent_tt_ranks = shapes.lazy_tt_ranks(left_tangent_space_tens)
mode_str = 'ij' if where.is_tt_matrix() else 'i'
right_rank_dim = where.right_tt_rank_dim
left_rank_dim = where.left_tt_rank_dim
if weights is not None:
weights_shape = weights.get_shape()
output_is_batch = len(weights_shape) > 1 and weights_shape[1] > 1
else:
output_is_batch = False
output_batch_str = 'o' if output_is_batch else ''
if output_is_batch:
right_rank_dim += 1
left_rank_dim += 1
output_batch_size = weights.get_shape()[1].value
rhs = [None] * (ndims + 1)
rhs[ndims] = tf.ones((batch_size, 1, 1), dtype=dtype)
for core_idx in range(ndims - 1, 0, -1):
tens_core = what.tt_cores[core_idx]
right_tang_core = right_tangent_space_tens.tt_cores[core_idx]
einsum_str = 'sa{0}b,sbd,c{0}d->sac'.format(mode_str)
rhs[core_idx] = tf.einsum(einsum_str, tens_core, rhs[core_idx + 1],
right_tang_core)
lhs = [None] * (ndims + 1)
lhs[0] = tf.ones((batch_size, 1, 1), dtype=dtype)
for core_idx in range(ndims - 1):
tens_core = what.tt_cores[core_idx]
left_tang_core = left_tangent_space_tens.tt_cores[core_idx]
einsum_str = 'sab,a{0}c,sb{0}d->scd'.format(mode_str)
lhs[core_idx + 1] = tf.einsum(einsum_str, lhs[core_idx], left_tang_core,
tens_core)
res_cores_list = []
for core_idx in range(ndims):
tens_core = what.tt_cores[core_idx]
left_tang_core = left_tangent_space_tens.tt_cores[core_idx]
right_tang_core = right_tangent_space_tens.tt_cores[core_idx]
if core_idx < ndims - 1:
einsum_str = 'sab,sb{0}c->sa{0}c'.format(mode_str)
proj_core = tf.einsum(einsum_str, lhs[core_idx], tens_core)
einsum_str = 'a{0}b,sbc->sa{0}c'.format(mode_str)
proj_core -= tf.einsum(einsum_str, left_tang_core, lhs[core_idx + 1])
if weights is None:
einsum_str = 'sa{0}b,sbc->a{0}c'.format(mode_str)
proj_core = tf.einsum(einsum_str, proj_core, rhs[core_idx + 1])
else:
einsum_str = 'sa{0}b,sbc->sa{0}c'.format(mode_str, output_batch_str)
proj_core_s = tf.einsum(einsum_str, proj_core, rhs[core_idx + 1])
einsum_str = 's{1},sa{0}c->{1}a{0}c'.format(mode_str, output_batch_str)
proj_core = tf.einsum(einsum_str, weights, proj_core_s)
if core_idx == ndims - 1:
if weights is None:
einsum_str = 'sab,sb{0}c->a{0}c'.format(mode_str)
proj_core = tf.einsum(einsum_str, lhs[core_idx], tens_core)
else:
einsum_str = 'sab,sb{0}c->sa{0}c'.format(mode_str, output_batch_str)
proj_core_s = tf.einsum(einsum_str, lhs[core_idx], tens_core)
einsum_str = 's{1},sa{0}c->{1}a{0}c'.format(mode_str, output_batch_str)
proj_core = tf.einsum(einsum_str, weights, proj_core_s)
if output_is_batch:
extended_left_tang_core = tf.expand_dims(left_tang_core, 0)
extended_right_tang_core = tf.expand_dims(right_tang_core, 0)
if where.is_tt_matrix():
extended_left_tang_core = tf.tile(extended_left_tang_core,
[output_batch_size, 1, 1, 1, 1])
extended_right_tang_core = tf.tile(extended_right_tang_core,
[output_batch_size, 1, 1, 1, 1])
else:
extended_left_tang_core = tf.tile(extended_left_tang_core,
[output_batch_size, 1, 1, 1])
extended_right_tang_core = tf.tile(extended_right_tang_core,
[output_batch_size, 1, 1, 1])
else:
extended_left_tang_core = left_tang_core
extended_right_tang_core = right_tang_core
if core_idx == 0:
res_core = tf.concat((proj_core, extended_left_tang_core),
axis=right_rank_dim)
elif core_idx == ndims - 1:
res_core = tf.concat((extended_right_tang_core, proj_core), axis=left_rank_dim)
else:
rank_1 = right_tangent_tt_ranks[core_idx]
rank_2 = left_tangent_tt_ranks[core_idx + 1]
if where.is_tt_matrix():
mode_size_n = raw_shape[0][core_idx]
mode_size_m = raw_shape[1][core_idx]
shape = [rank_1, mode_size_n, mode_size_m, rank_2]
else:
mode_size = raw_shape[0][core_idx]
shape = [rank_1, mode_size, rank_2]
if output_is_batch:
shape = [output_batch_size] + shape
zeros = tf.zeros(shape, dtype)
upper = tf.concat((extended_right_tang_core, zeros), axis=right_rank_dim)
lower = tf.concat((proj_core, extended_left_tang_core),
axis=right_rank_dim)
res_core = tf.concat((upper, lower), axis=left_rank_dim)
res_cores_list.append(res_core)
if output_is_batch:
res = TensorTrainBatch(res_cores_list, where.get_raw_shape(),
batch_size=output_batch_size)
else:
res = TensorTrain(res_cores_list, where.get_raw_shape())
res.projection_on = where
return res
def project(what, where):
if not isinstance(where, TensorTrain):
raise ValueError('The first argument should be a TensorTrain object, got '
'"%s".' % where)
if where.get_raw_shape() != what.get_raw_shape():
raise ValueError('The shapes of the tensor we want to project and of the '
'tensor on which tangent space we want to project should '
'match, got %s and %s.' %
(where.get_raw_shape(),
what.get_raw_shape()))
dtypes_compatible = (where.dtype.is_compatible_with(what.dtype) or
what.dtype.is_compatible_with(where.dtype))
if not dtypes_compatible:
raise ValueError('Dtypes of the arguments should coincide, got %s and %s.' %
(where.dtype,
what.dtype))
left_tangent_space_tens = decompositions.orthogonalize_tt_cores(
where)
right_tangent_space_tens = decompositions.orthogonalize_tt_cores(
left_tangent_space_tens, left_to_right=False)
ndims = where.ndims()
dtype = where.dtype
raw_shape = shapes.lazy_raw_shape(where)
right_tangent_tt_ranks = shapes.lazy_tt_ranks(right_tangent_space_tens)
left_tangent_tt_ranks = shapes.lazy_tt_ranks(left_tangent_space_tens)
mode_str = 'ij' if where.is_tt_matrix() else 'i'
right_rank_dim = what.right_tt_rank_dim
left_rank_dim = what.left_tt_rank_dim
output_is_batch = isinstance(what, TensorTrainBatch)
if output_is_batch:
output_batch_size = what.batch_size
what = shapes.expand_batch_dim(what)
batch_size = shapes.lazy_batch_size(what)
rhs = [None] * (ndims + 1)
rhs[ndims] = tf.ones((batch_size, 1, 1), dtype=dtype)
for core_idx in range(ndims - 1, 0, -1):
tens_core = what.tt_cores[core_idx]
right_tang_core = right_tangent_space_tens.tt_cores[core_idx]
einsum_str = 'sa{0}b,sbd,c{0}d->sac'.format(mode_str)
rhs[core_idx] = tf.einsum(einsum_str, tens_core, rhs[core_idx + 1],
right_tang_core)
lhs = [None] * (ndims + 1)
lhs[0] = tf.ones((batch_size, 1, 1), dtype=dtype)
for core_idx in range(ndims - 1):
tens_core = what.tt_cores[core_idx]
left_tang_core = left_tangent_space_tens.tt_cores[core_idx]
einsum_str = 'sab,a{0}c,sb{0}d->scd'.format(mode_str)
lhs[core_idx + 1] = tf.einsum(einsum_str, lhs[core_idx], left_tang_core,
tens_core)
res_cores_list = []
for core_idx in range(ndims):
tens_core = what.tt_cores[core_idx]
left_tang_core = left_tangent_space_tens.tt_cores[core_idx]
right_tang_core = right_tangent_space_tens.tt_cores[core_idx]
if core_idx < ndims - 1:
einsum_str = 'sab,sb{0}c->sa{0}c'.format(mode_str)
proj_core = tf.einsum(einsum_str, lhs[core_idx], tens_core)
einsum_str = 'a{0}b,sbc->sa{0}c'.format(mode_str)
proj_core -= tf.einsum(einsum_str, left_tang_core, lhs[core_idx + 1])
if output_is_batch:
einsum_str = 'sa{0}b,sbc->sa{0}c'.format(mode_str)
else:
einsum_str = 'sa{0}b,sbc->a{0}c'.format(mode_str)
proj_core = tf.einsum(einsum_str, proj_core, rhs[core_idx + 1])
if core_idx == ndims - 1:
if output_is_batch:
einsum_str = 'sab,sb{0}c->sa{0}c'.format(mode_str)
else:
einsum_str = 'sab,sb{0}c->a{0}c'.format(mode_str)
proj_core = tf.einsum(einsum_str, lhs[core_idx], tens_core)
if output_is_batch:
extended_left_tang_core = tf.expand_dims(left_tang_core, 0)
extended_right_tang_core = tf.expand_dims(right_tang_core, 0)
if where.is_tt_matrix():
extended_left_tang_core = tf.tile(extended_left_tang_core,
[output_batch_size, 1, 1, 1, 1])
extended_right_tang_core = tf.tile(extended_right_tang_core,
[output_batch_size, 1, 1, 1, 1])
else:
extended_left_tang_core = tf.tile(extended_left_tang_core,
[output_batch_size, 1, 1, 1])
extended_right_tang_core = tf.tile(extended_right_tang_core,
[output_batch_size, 1, 1, 1])
else:
extended_left_tang_core = left_tang_core
extended_right_tang_core = right_tang_core
if core_idx == 0:
res_core = tf.concat((proj_core, extended_left_tang_core),
axis=right_rank_dim)
elif core_idx == ndims - 1:
res_core = tf.concat((extended_right_tang_core, proj_core), axis=left_rank_dim)
else:
rank_1 = right_tangent_tt_ranks[core_idx]
rank_2 = left_tangent_tt_ranks[core_idx + 1]
if where.is_tt_matrix():
mode_size_n = raw_shape[0][core_idx]
mode_size_m = raw_shape[1][core_idx]
shape = [rank_1, mode_size_n, mode_size_m, rank_2]
else:
mode_size = raw_shape[0][core_idx]
shape = [rank_1, mode_size, rank_2]
if output_is_batch:
shape = [output_batch_size] + shape
zeros = tf.zeros(shape, dtype)
upper = tf.concat((extended_right_tang_core, zeros), axis=right_rank_dim)
lower = tf.concat((proj_core, extended_left_tang_core),
axis=right_rank_dim)
res_core = tf.concat((upper, lower), axis=left_rank_dim)
res_cores_list.append(res_core)
if output_is_batch:
res = TensorTrainBatch(res_cores_list, where.get_raw_shape(),
batch_size=output_batch_size)
else:
res = TensorTrain(res_cores_list, where.get_raw_shape())
res.projection_on = where
return res
def project_matmul(what, where, matrix):
if not isinstance(where, TensorTrain):
raise ValueError('The first argument should be a TensorTrain object, got '
'"%s".' % where)
if where.get_raw_shape() != what.get_raw_shape():
raise ValueError('The shapes of the tensor we want to project and of the '
'tensor on which tangent space we want to project should '
'match, got %s and %s.' %
(where.get_raw_shape(),
what.get_raw_shape()))
dtypes_compatible = (where.dtype.is_compatible_with(what.dtype) or
what.dtype.is_compatible_with(where.dtype))
if not dtypes_compatible:
raise ValueError('Dtypes of the arguments should coincide, got %s and %s.' %
(where.dtype,
what.dtype))
left_tangent_space_tens = decompositions.orthogonalize_tt_cores(
where)
right_tangent_space_tens = decompositions.orthogonalize_tt_cores(
left_tangent_space_tens, left_to_right=False)
ndims = where.ndims()
dtype = where.dtype
raw_shape = shapes.lazy_raw_shape(where)
batch_size = shapes.lazy_batch_size(what)
right_tangent_tt_ranks = shapes.lazy_tt_ranks(right_tangent_space_tens)
left_tangent_tt_ranks = shapes.lazy_tt_ranks(left_tangent_space_tens)
right_rank_dim = what.right_tt_rank_dim
left_rank_dim = what.left_tt_rank_dim
output_is_batch = isinstance(what, TensorTrainBatch)
if output_is_batch:
output_batch_size = what.batch_size
what = shapes.expand_batch_dim(what)
rhs = [None] * (ndims + 1)
rhs[ndims] = tf.ones((batch_size, 1, 1, 1), dtype=dtype)
for core_idx in range(ndims - 1, 0, -1):
tens_core = what.tt_cores[core_idx]
right_tang_core = right_tangent_space_tens.tt_cores[core_idx]
matrix_core = matrix.tt_cores[core_idx]
rhs[core_idx] = tf.einsum('bije,cikf,sdef,sajkd->sabc', matrix_core,
right_tang_core, rhs[core_idx + 1], tens_core)
lhs = [None] * (ndims + 1)
lhs[0] = tf.ones((batch_size, 1, 1, 1), dtype=dtype)
for core_idx in range(ndims - 1):
tens_core = what.tt_cores[core_idx]
left_tang_core = left_tangent_space_tens.tt_cores[core_idx]
matrix_core = matrix.tt_cores[core_idx]
lhs[core_idx + 1] = tf.einsum('bije,aikd,sabc,scjkf->sdef', matrix_core,
left_tang_core, lhs[core_idx], tens_core)
res_cores_list = []
for core_idx in range(ndims):
tens_core = what.tt_cores[core_idx]
matrix_core = matrix.tt_cores[core_idx]
left_tang_core = left_tangent_space_tens.tt_cores[core_idx]
right_tang_core = right_tangent_space_tens.tt_cores[core_idx]
if core_idx < ndims - 1:
proj_core = tf.einsum('scjke,sabc,bijd->saikde', tens_core,
lhs[core_idx], matrix_core)
proj_core -= tf.einsum('aikb,sbcd->saikcd', left_tang_core,
lhs[core_idx + 1])
proj_core = tf.einsum('saikcb,sbcd->saikd', proj_core, rhs[core_idx + 1])
if core_idx == ndims - 1:
proj_core = tf.einsum('sabc,bijd,scjke->saike', lhs[core_idx], matrix_core,
tens_core)
if output_is_batch:
extended_left_tang_core = tf.expand_dims(left_tang_core, 0)
extended_right_tang_core = tf.expand_dims(right_tang_core, 0)
extended_left_tang_core = tf.tile(extended_left_tang_core,
[output_batch_size, 1, 1, 1, 1])
extended_right_tang_core = tf.tile(extended_right_tang_core,
[output_batch_size, 1, 1, 1, 1])
else:
extended_left_tang_core = left_tang_core
extended_right_tang_core = right_tang_core
if core_idx == 0:
res_core = tf.concat((proj_core, extended_left_tang_core),
axis=right_rank_dim)
elif core_idx == ndims - 1:
res_core = tf.concat((extended_right_tang_core, proj_core),
axis=left_rank_dim)
else:
rank_1 = right_tangent_tt_ranks[core_idx]
rank_2 = left_tangent_tt_ranks[core_idx + 1]
mode_size_n = raw_shape[0][core_idx]
mode_size_m = raw_shape[1][core_idx]
shape = [rank_1, mode_size_n, mode_size_m, rank_2]
if output_is_batch:
shape = [output_batch_size] + shape
zeros = tf.zeros(shape, dtype)
upper = tf.concat((extended_right_tang_core, zeros),
axis=right_rank_dim)
lower = tf.concat((proj_core, extended_left_tang_core),
axis=right_rank_dim)
res_core = tf.concat((upper, lower), axis=left_rank_dim)
res_cores_list.append(res_core)
if output_is_batch:
res = TensorTrainBatch(res_cores_list, where.get_raw_shape(),
batch_size=output_batch_size)
else:
res = TensorTrain(res_cores_list, where.get_raw_shape())
res.projection_on = where
return res
def pairwise_flat_inner_projected(projected_tt_vectors_1,
projected_tt_vectors_2):
if not hasattr(projected_tt_vectors_1, 'projection_on') or \
not hasattr(projected_tt_vectors_2, 'projection_on'):
raise ValueError('Both arguments should be projections on the tangent '
'space of some other TT-object. All projection* functions '
'leave .projection_on field in the resulting TT-object '
'which is not present in the arguments you\'ve provided')
if projected_tt_vectors_1.projection_on != projected_tt_vectors_2.projection_on:
raise ValueError('Both arguments should be projections on the tangent '
'space of the same TT-object. The provided arguments are '
'projections on different TT-objects (%s and %s). Or at '
'least the pointers are different.' %
(projected_tt_vectors_1.projection_on,
projected_tt_vectors_2.projection_on))
# Always work with batches of objects for simplicity.
projected_tt_vectors_1 = shapes.expand_batch_dim(projected_tt_vectors_1)
projected_tt_vectors_2 = shapes.expand_batch_dim(projected_tt_vectors_2)
ndims = projected_tt_vectors_1.ndims()
tt_ranks = shapes.lazy_tt_ranks(projected_tt_vectors_1)
if projected_tt_vectors_1.is_tt_matrix():
right_size = tt_ranks[1] // 2
curr_core_1 = projected_tt_vectors_1.tt_cores[0]
curr_core_2 = projected_tt_vectors_2.tt_cores[0]
curr_du_1 = curr_core_1[:, :, :, :, :right_size]
curr_du_2 = curr_core_2[:, :, :, :, :right_size]
res = tf.einsum('paijb,qaijb->pq', curr_du_1, curr_du_2)
for core_idx in range(1, ndims):
left_size = tt_ranks[core_idx] // 2
right_size = tt_ranks[core_idx + 1] // 2
curr_core_1 = projected_tt_vectors_1.tt_cores[core_idx]
curr_core_2 = projected_tt_vectors_2.tt_cores[core_idx]
curr_du_1 = curr_core_1[:, left_size:, :, :, :right_size]
curr_du_2 = curr_core_2[:, left_size:, :, :, :right_size]
res += tf.einsum('paijb,qaijb->pq', curr_du_1, curr_du_2)
left_size = tt_ranks[-2] // 2
curr_core_1 = projected_tt_vectors_1.tt_cores[-1]
curr_core_2 = projected_tt_vectors_2.tt_cores[-1]
curr_du_1 = curr_core_1[:, left_size:, :, :, :]
curr_du_2 = curr_core_2[:, left_size:, :, :, :]
res += tf.einsum('paijb,qaijb->pq', curr_du_1, curr_du_2)
else:
# Working with TT-tensor, not TT-matrix.
right_size = tt_ranks[1] // 2
curr_core_1 = projected_tt_vectors_1.tt_cores[0]
curr_core_2 = projected_tt_vectors_2.tt_cores[0]
curr_du_1 = curr_core_1[:, :, :, :right_size]
curr_du_2 = curr_core_2[:, :, :, :right_size]
res = tf.einsum('paib,qaib->pq', curr_du_1, curr_du_2)
for core_idx in range(1, ndims):
left_size = tt_ranks[core_idx] // 2
right_size = tt_ranks[core_idx + 1] // 2
curr_core_1 = projected_tt_vectors_1.tt_cores[core_idx]
curr_core_2 = projected_tt_vectors_2.tt_cores[core_idx]
curr_du_1 = curr_core_1[:, left_size:, :, :right_size]
curr_du_2 = curr_core_2[:, left_size:, :, :right_size]
res += tf.einsum('paib,qaib->pq', curr_du_1, curr_du_2)
left_size = tt_ranks[-2] // 2
curr_core_1 = projected_tt_vectors_1.tt_cores[-1]
curr_core_2 = projected_tt_vectors_2.tt_cores[-1]
curr_du_1 = curr_core_1[:, left_size:, :, :]
curr_du_2 = curr_core_2[:, left_size:, :, :]
res += tf.einsum('paib,qaib->pq', curr_du_1, curr_du_2)
return res
def add_n_projected(tt_objects, coef=None):
for tt in tt_objects:
if not hasattr(tt, 'projection_on'):
raise ValueError('Both arguments should be projections on the tangent '
'space of some other TT-object. All projection* functions '
'leave .projection_on field in the resulting TT-object '
'which is not present in the argument you\'ve provided.')
projection_on = tt_objects[0].projection_on
for tt in tt_objects[1:]:
if tt.projection_on != projection_on:
raise ValueError('All tt_objects should be projections on the tangent '
'space of the same TT-object. The provided arguments are '
'projections on different TT-objects (%s and %s). Or at '
'least the pointers are different.' % (tt.projection_on,
projection_on))
if coef is not None:
coef = tf.convert_to_tensor(coef, dtype=tt_objects[0].dtype)
if coef.get_shape().ndims > 1:
some_core = tt_objects[0].tt_cores[0]
dim_array = [1] * (some_core.get_shape().ndims + 1)
dim_array[0] = coef.get_shape()[0].value
dim_array[1] = coef.get_shape()[1].value
coef = tf.reshape(coef, dim_array)
ndims = tt_objects[0].ndims()
tt_ranks = shapes.lazy_tt_ranks(tt_objects[0])
left_rank_dim = tt_objects[0].left_tt_rank_dim
right_rank_dim = tt_objects[0].right_tt_rank_dim
res_cores = []
def slice_tt_core(tt_core, left_idx, right_idx):
num_tt_core_dims = len(tt_core.get_shape())
idx = [slice(None)] * num_tt_core_dims
idx[left_rank_dim] = left_idx
idx[right_rank_dim] = right_idx
return tt_core[idx]
right_half_rank = tt_ranks[1] // 2
left_chunks = []
for obj_idx, tt in enumerate(tt_objects):
curr_core = slice_tt_core(tt.tt_cores[0], slice(None),
slice(0, right_half_rank))
if coef is not None:
curr_core *= coef[obj_idx]
left_chunks.append(curr_core)
left_part = tf.add_n(left_chunks)
first_obj_core = tt_objects[0].tt_cores[0]
right_part = slice_tt_core(first_obj_core, slice(None),
slice(right_half_rank, None))
first_core = tf.concat((left_part, right_part), axis=right_rank_dim)
res_cores.append(first_core)
for core_idx in range(1, ndims - 1):
first_obj_core = tt_objects[0].tt_cores[core_idx]
left_half_rank = tt_ranks[core_idx] // 2
right_half_rank = tt_ranks[core_idx + 1] // 2
upper_part = slice_tt_core(tt.tt_cores[core_idx], slice(0, left_half_rank),
slice(None))
lower_right_part = slice_tt_core(first_obj_core,
slice(left_half_rank, None),
slice(right_half_rank, None))
lower_left_chunks = []
for obj_idx, tt in enumerate(tt_objects):
curr_core = slice_tt_core(tt.tt_cores[core_idx],
slice(left_half_rank, None),
slice(0, right_half_rank))
if coef is not None:
curr_core *= coef[obj_idx]
lower_left_chunks.append(curr_core)
lower_left_part = tf.add_n(lower_left_chunks)
lower_part = tf.concat((lower_left_part, lower_right_part),
axis=right_rank_dim)
curr_core = tf.concat((upper_part, lower_part), axis=left_rank_dim)
res_cores.append(curr_core)
left_half_rank = tt_ranks[ndims - 1] // 2
upper_part = slice_tt_core(tt.tt_cores[-1], slice(0, left_half_rank),
slice(None))
lower_chunks = []
for obj_idx, tt in enumerate(tt_objects):
curr_core = slice_tt_core(tt.tt_cores[-1], slice(left_half_rank, None),
slice(None))
if coef is not None:
curr_core *= coef[obj_idx]
lower_chunks.append(curr_core)
lower_part = tf.add_n(lower_chunks)
last_core = tf.concat((upper_part, lower_part), axis=left_rank_dim)
res_cores.append(last_core)
raw_shape = tt_objects[0].get_raw_shape()
static_tt_ranks = tt_objects[0].get_tt_ranks()
if isinstance(tt_objects[0], TensorTrain):
res = TensorTrain(res_cores, raw_shape, static_tt_ranks)
elif isinstance(tt_objects[0], TensorTrainBatch):
res = TensorTrainBatch(res_cores, raw_shape, static_tt_ranks,
tt_objects[0].batch_size)
res.projection_on = tt_objects[0].projection_on
return res
def tangent_space_to_deltas(tt, name='t3f_tangent_space_to_deltas'):
if not hasattr(tt, 'projection_on') or tt.projection_on is None:
raise ValueError('tt argument is supposed to be a projection, but it '
'lacks projection_on field')
num_dims = tt.ndims()
left_tt_rank_dim = tt.left_tt_rank_dim
right_tt_rank_dim = tt.right_tt_rank_dim
deltas = [None] * num_dims
tt_ranks = shapes.lazy_tt_ranks(tt)
for i in range(1, num_dims - 1):
if int(tt_ranks[i] / 2) != tt_ranks[i] / 2:
raise ValueError('tt argument is supposed to be a projection, but its '
'ranks are not even.')
with tf.name_scope(name, values=tt.tt_cores):
for i in range(1, num_dims - 1):
r1, r2 = tt_ranks[i], tt_ranks[i + 1]
curr_core = tt.tt_cores[i]
slc = [slice(None)] * len(curr_core.shape)
slc[left_tt_rank_dim] = slice(int(r1 / 2), None)
slc[right_tt_rank_dim] = slice(0, int(r2 / 2))
deltas[i] = curr_core[slc]
slc = [slice(None)] * len(tt.tt_cores[0].shape)
slc[right_tt_rank_dim] = slice(0, int(tt_ranks[1] / 2))
deltas[0] = tt.tt_cores[0][slc]
slc = [slice(None)] * len(tt.tt_cores[0].shape)
slc[left_tt_rank_dim] = slice(int(tt_ranks[-2] / 2), None)
deltas[num_dims - 1] = tt.tt_cores[num_dims - 1][slc]
return deltas
def deltas_to_tangent_space(deltas, tt, left=None, right=None,
name='t3f_deltas_to_tangent_space'):
cores = []
dtype = tt.dtype
num_dims = tt.ndims()
input_tensors = list(tt.tt_cores) + list(deltas)
if left is not None:
input_tensors += list(left.tt_cores)
if right is not None:
input_tensors += list(right.tt_cores)
with tf.name_scope(name, values=input_tensors):
if left is None:
left = decompositions.orthogonalize_tt_cores(tt)
if right is None:
right = decompositions.orthogonalize_tt_cores(left, left_to_right=False)
left_tangent_tt_ranks = shapes.lazy_tt_ranks(left)
right_tangent_tt_ranks = shapes.lazy_tt_ranks(left)
raw_shape = shapes.lazy_raw_shape(left)
right_rank_dim = left.right_tt_rank_dim
left_rank_dim = left.left_tt_rank_dim
is_batch_case = len(deltas[0].shape) > len(tt.tt_cores[0].shape)
if is_batch_case:
right_rank_dim += 1
left_rank_dim += 1
batch_size = deltas[0].shape.as_list()[0]
for i in range(num_dims):
left_tt_core = left.tt_cores[i]
right_tt_core = right.tt_cores[i]
if is_batch_case:
tile = [1] * len(left_tt_core.shape)
tile = [batch_size] + tile
left_tt_core = tf.tile(left_tt_core[None, ...], tile)
right_tt_core = tf.tile(right_tt_core[None, ...], tile)
if i == 0:
tangent_core = tf.concat((deltas[i], left_tt_core),
axis=right_rank_dim)
elif i == num_dims - 1:
tangent_core = tf.concat((right_tt_core, deltas[i]),
axis=left_rank_dim)
else:
rank_1 = right_tangent_tt_ranks[i]
rank_2 = left_tangent_tt_ranks[i + 1]
if tt.is_tt_matrix():
mode_size_n = raw_shape[0][i]
mode_size_m = raw_shape[1][i]
shape = [rank_1, mode_size_n, mode_size_m, rank_2]
else:
mode_size_n = raw_shape[0][i]
shape = [rank_1, mode_size_n, rank_2]
if is_batch_case:
shape = [batch_size] + shape
zeros = tf.zeros(shape, dtype=dtype)
upper = tf.concat((right_tt_core, zeros), axis=right_rank_dim)
lower = tf.concat((deltas[i], left_tt_core), axis=right_rank_dim)
tangent_core = tf.concat((upper, lower), axis=left_rank_dim)
cores.append(tangent_core)
if is_batch_case:
tangent = TensorTrainBatch(cores, batch_size=batch_size)
else:
tangent = TensorTrain(cores)
tangent.projection_on = tt
return tangent
| true | true |
f7317ee14c32df99d8957b13095c5f0979815548 | 11,872 | py | Python | intake_esm/cat.py | agstephens/intake-esm | 25ead83497d025c37a80abdbefee9b286934308b | [
"Apache-2.0"
] | null | null | null | intake_esm/cat.py | agstephens/intake-esm | 25ead83497d025c37a80abdbefee9b286934308b | [
"Apache-2.0"
] | null | null | null | intake_esm/cat.py | agstephens/intake-esm | 25ead83497d025c37a80abdbefee9b286934308b | [
"Apache-2.0"
] | null | null | null | import enum
import json
import os
import pathlib
import typing
import fsspec
import pandas as pd
import pydantic
import tlz
from ._search import search, search_apply_require_all_on
class AggregationType(str, enum.Enum):
join_new = 'join_new'
join_existing = 'join_existing'
union = 'union'
class Config:
validate_all = True
validate_assignment = True
class DataFormat(str, enum.Enum):
netcdf = 'netcdf'
zarr = 'zarr'
class Config:
validate_all = True
validate_assignment = True
class Attribute(pydantic.BaseModel):
column_name: pydantic.StrictStr
vocabulary: pydantic.StrictStr = ''
class Config:
validate_all = True
validate_assignment = True
class Assets(pydantic.BaseModel):
column_name: pydantic.StrictStr
format: DataFormat
format_column_name: typing.Optional[pydantic.StrictStr]
class Config:
validate_all = True
validate_assignment = True
@pydantic.root_validator
def _validate_data_format(cls, values):
data_format, format_column_name = values.get('format'), values.get('format_column_name')
if data_format is not None and format_column_name is not None:
raise ValueError('Cannot set both format and format_column_name')
return values
class Aggregation(pydantic.BaseModel):
type: AggregationType
attribute_name: pydantic.StrictStr
options: typing.Optional[typing.Dict] = {}
class Config:
validate_all = True
validate_assignment = True
class AggregationControl(pydantic.BaseModel):
variable_column_name: pydantic.StrictStr
groupby_attrs: typing.List[pydantic.StrictStr]
aggregations: typing.List[Aggregation] = []
class Config:
validate_all = True
validate_assignment = True
class ESMCatalogModel(pydantic.BaseModel):
"""
Pydantic model for the ESM data catalog defined in https://git.io/JBWoW
"""
esmcat_version: pydantic.StrictStr
id: str
attributes: typing.List[Attribute]
assets: Assets
aggregation_control: AggregationControl
catalog_dict: typing.Optional[typing.List[typing.Dict]] = None
catalog_file: pydantic.StrictStr = None
description: pydantic.StrictStr = None
title: pydantic.StrictStr = None
_df: typing.Optional[typing.Any] = pydantic.PrivateAttr()
class Config:
validate_all = True
validate_assignment = True
@pydantic.root_validator
def validate_catalog(cls, values):
catalog_dict, catalog_file = values.get('catalog_dict'), values.get('catalog_file')
if catalog_dict is not None and catalog_file is not None:
raise ValueError('catalog_dict and catalog_file cannot be set at the same time')
return values
@classmethod
def from_dict(cls, data: typing.Dict) -> 'ESMCatalogModel':
esmcat = data['esmcat']
df = data['df']
cat = cls.parse_obj(esmcat)
cat._df = df
return cat
def save(self, name: str, *, directory: str = None, catalog_type: str = 'dict') -> None:
"""
Save the catalog to a file.
Parameters
-----------
name: str
The name of the file to save the catalog to.
directory: str
The directory to save the catalog to. If None, use the current directory
catalog_type: str
The type of catalog to save. Whether to save the catalog table as a dictionary
in the JSON file or as a separate CSV file. Valid options are 'dict' and 'file'.
Notes
-----
Large catalogs can result in large JSON files. To keep the JSON file size manageable, call with
`catalog_type='file'` to save catalog as a separate CSV file.
"""
if catalog_type not in {'file', 'dict'}:
raise ValueError(
f'catalog_type must be either "dict" or "file". Received catalog_type={catalog_type}'
)
csv_file_name = pathlib.Path(f'{name}.csv.gz')
json_file_name = pathlib.Path(f'{name}.json')
if directory:
directory = pathlib.Path(directory)
directory.mkdir(parents=True, exist_ok=True)
csv_file_name = directory / csv_file_name
json_file_name = directory / json_file_name
data = self.dict().copy()
for key in {'catalog_dict', 'catalog_file'}:
data.pop(key, None)
data['id'] = name
if catalog_type == 'file':
data['catalog_file'] = str(csv_file_name)
self.df.to_csv(csv_file_name, compression='gzip', index=False)
else:
data['catalog_dict'] = self.df.to_dict(orient='records')
with open(json_file_name, 'w') as outfile:
json.dump(data, outfile, indent=2)
print(f'Successfully wrote ESM collection json file to: {json_file_name}')
@classmethod
def load(
cls,
json_file: typing.Union[str, pydantic.FilePath, pydantic.AnyUrl],
storage_options: typing.Dict[str, typing.Any] = None,
read_csv_kwargs: typing.Dict[str, typing.Any] = None,
) -> 'ESMCatalogModel':
"""
Loads the catalog from a file
"""
storage_options = storage_options if storage_options is not None else {}
read_csv_kwargs = read_csv_kwargs or {}
_mapper = fsspec.get_mapper(json_file, **storage_options)
with fsspec.open(json_file, **storage_options) as fobj:
cat = cls.parse_raw(fobj.read())
if cat.catalog_file:
if _mapper.fs.exists(cat.catalog_file):
csv_path = cat.catalog_file
else:
csv_path = f'{os.path.dirname(_mapper.root)}/{cat.catalog_file}'
cat.catalog_file = csv_path
df = pd.read_csv(
cat.catalog_file,
storage_options=storage_options,
**read_csv_kwargs,
)
else:
df = pd.DataFrame(cat.catalog_dict)
cat._df = df
cat._cast_agg_columns_with_iterables()
return cat
@property
def columns_with_iterables(self) -> typing.Set[str]:
"""Return a set of columns that have iterables."""
if self._df.empty:
return set()
has_iterables = (
self._df.sample(20, replace=True)
.applymap(type)
.isin([list, tuple, set])
.any()
.to_dict()
)
return {column for column, check in has_iterables.items() if check}
@property
def has_multiple_variable_assets(self) -> bool:
"""Return True if the catalog has multiple variable assets."""
return self.aggregation_control.variable_column_name in self.columns_with_iterables
@property
def df(self) -> pd.DataFrame:
"""Return the dataframe."""
return self._df
@df.setter
def df(self, value: pd.DataFrame) -> None:
self._df = value
def _cast_agg_columns_with_iterables(self) -> None:
"""Cast all agg_columns with iterables to tuple values so as
to avoid hashing issues (e.g. TypeError: unhashable type: 'list')
"""
columns = list(
self.columns_with_iterables.intersection(
set(map(lambda agg: agg.attribute_name, self.aggregation_control.aggregations))
)
)
if columns:
self._df[columns] = self._df[columns].apply(tuple)
@property
def grouped(self) -> typing.Union[pd.core.groupby.DataFrameGroupBy, pd.DataFrame]:
if self.aggregation_control.groupby_attrs and set(
self.aggregation_control.groupby_attrs
) != set(self.df.columns):
return self.df.groupby(self.aggregation_control.groupby_attrs)
return self.df
def _construct_group_keys(
self, sep: str = '.'
) -> typing.Dict[str, typing.Union[str, typing.Tuple[str]]]:
grouped = self.grouped
if isinstance(grouped, pd.core.groupby.generic.DataFrameGroupBy):
internal_keys = grouped.groups.keys()
public_keys = map(
lambda key: key if isinstance(key, str) else sep.join(str(value) for value in key),
internal_keys,
)
else:
internal_keys = grouped.index
public_keys = (
grouped[grouped.columns.tolist()]
.apply(lambda row: sep.join(str(v) for v in row), axis=1)
.tolist()
)
return dict(zip(public_keys, internal_keys))
def _unique(self) -> typing.Dict:
def _find_unique(series):
values = series.dropna()
if series.name in self.columns_with_iterables:
values = tlz.concat(values)
return list(tlz.unique(values))
data = self.df[self.df.columns]
if data.empty:
return {col: [] for col in self.df.columns}
else:
return data.apply(_find_unique, result_type='reduce').to_dict()
def unique(self) -> pd.Series:
return pd.Series(self._unique())
def nunique(self) -> pd.Series:
return pd.Series(tlz.valmap(len, self._unique()))
def search(
self,
*,
query: typing.Union['QueryModel', typing.Dict[str, typing.Any]],
require_all_on: typing.Union[str, typing.List[str]] = None,
) -> 'ESMCatalogModel':
"""
Search for entries in the catalog.
Parameters
----------
query: dict, optional
A dictionary of query parameters to execute against the dataframe.
require_all_on : list, str, optional
A dataframe column or a list of dataframe columns across
which all entries must satisfy the query criteria.
If None, return entries that fulfill any of the criteria specified
in the query, by default None.
"""
if not isinstance(query, QueryModel):
_query = QueryModel(
query=query, require_all_on=require_all_on, columns=self.df.columns.tolist()
)
else:
_query = query
results = search(
df=self.df, query=_query.query, columns_with_iterables=self.columns_with_iterables
)
if _query.require_all_on is not None and not results.empty:
results = search_apply_require_all_on(
df=results, query=_query.query, require_all_on=_query.require_all_on
)
return results
class QueryModel(pydantic.BaseModel):
query: typing.Dict[pydantic.StrictStr, typing.Union[typing.Any, typing.List[typing.Any]]]
columns: typing.List[str]
require_all_on: typing.Union[str, typing.List[typing.Any]] = None
class Config:
validate_all = True
validate_assignment = True
@pydantic.root_validator(pre=False)
def validate_query(cls, values):
query = values.get('query', {})
columns = values.get('columns')
require_all_on = values.get('require_all_on', [])
if query:
for key in query:
if key not in columns:
raise ValueError(f'Column {key} not in columns {columns}')
if isinstance(require_all_on, str):
values['require_all_on'] = [require_all_on]
if require_all_on is not None:
for key in values['require_all_on']:
if key not in columns:
raise ValueError(f'Column {key} not in columns {columns}')
_query = query.copy()
for key, value in _query.items():
if isinstance(value, (str, int, float, bool)):
_query[key] = [value]
values['query'] = _query
return values
| 33.254902 | 103 | 0.614976 | import enum
import json
import os
import pathlib
import typing
import fsspec
import pandas as pd
import pydantic
import tlz
from ._search import search, search_apply_require_all_on
class AggregationType(str, enum.Enum):
join_new = 'join_new'
join_existing = 'join_existing'
union = 'union'
class Config:
validate_all = True
validate_assignment = True
class DataFormat(str, enum.Enum):
netcdf = 'netcdf'
zarr = 'zarr'
class Config:
validate_all = True
validate_assignment = True
class Attribute(pydantic.BaseModel):
column_name: pydantic.StrictStr
vocabulary: pydantic.StrictStr = ''
class Config:
validate_all = True
validate_assignment = True
class Assets(pydantic.BaseModel):
column_name: pydantic.StrictStr
format: DataFormat
format_column_name: typing.Optional[pydantic.StrictStr]
class Config:
validate_all = True
validate_assignment = True
@pydantic.root_validator
def _validate_data_format(cls, values):
data_format, format_column_name = values.get('format'), values.get('format_column_name')
if data_format is not None and format_column_name is not None:
raise ValueError('Cannot set both format and format_column_name')
return values
class Aggregation(pydantic.BaseModel):
type: AggregationType
attribute_name: pydantic.StrictStr
options: typing.Optional[typing.Dict] = {}
class Config:
validate_all = True
validate_assignment = True
class AggregationControl(pydantic.BaseModel):
variable_column_name: pydantic.StrictStr
groupby_attrs: typing.List[pydantic.StrictStr]
aggregations: typing.List[Aggregation] = []
class Config:
validate_all = True
validate_assignment = True
class ESMCatalogModel(pydantic.BaseModel):
esmcat_version: pydantic.StrictStr
id: str
attributes: typing.List[Attribute]
assets: Assets
aggregation_control: AggregationControl
catalog_dict: typing.Optional[typing.List[typing.Dict]] = None
catalog_file: pydantic.StrictStr = None
description: pydantic.StrictStr = None
title: pydantic.StrictStr = None
_df: typing.Optional[typing.Any] = pydantic.PrivateAttr()
class Config:
validate_all = True
validate_assignment = True
@pydantic.root_validator
def validate_catalog(cls, values):
catalog_dict, catalog_file = values.get('catalog_dict'), values.get('catalog_file')
if catalog_dict is not None and catalog_file is not None:
raise ValueError('catalog_dict and catalog_file cannot be set at the same time')
return values
@classmethod
def from_dict(cls, data: typing.Dict) -> 'ESMCatalogModel':
esmcat = data['esmcat']
df = data['df']
cat = cls.parse_obj(esmcat)
cat._df = df
return cat
def save(self, name: str, *, directory: str = None, catalog_type: str = 'dict') -> None:
if catalog_type not in {'file', 'dict'}:
raise ValueError(
f'catalog_type must be either "dict" or "file". Received catalog_type={catalog_type}'
)
csv_file_name = pathlib.Path(f'{name}.csv.gz')
json_file_name = pathlib.Path(f'{name}.json')
if directory:
directory = pathlib.Path(directory)
directory.mkdir(parents=True, exist_ok=True)
csv_file_name = directory / csv_file_name
json_file_name = directory / json_file_name
data = self.dict().copy()
for key in {'catalog_dict', 'catalog_file'}:
data.pop(key, None)
data['id'] = name
if catalog_type == 'file':
data['catalog_file'] = str(csv_file_name)
self.df.to_csv(csv_file_name, compression='gzip', index=False)
else:
data['catalog_dict'] = self.df.to_dict(orient='records')
with open(json_file_name, 'w') as outfile:
json.dump(data, outfile, indent=2)
print(f'Successfully wrote ESM collection json file to: {json_file_name}')
@classmethod
def load(
cls,
json_file: typing.Union[str, pydantic.FilePath, pydantic.AnyUrl],
storage_options: typing.Dict[str, typing.Any] = None,
read_csv_kwargs: typing.Dict[str, typing.Any] = None,
) -> 'ESMCatalogModel':
storage_options = storage_options if storage_options is not None else {}
read_csv_kwargs = read_csv_kwargs or {}
_mapper = fsspec.get_mapper(json_file, **storage_options)
with fsspec.open(json_file, **storage_options) as fobj:
cat = cls.parse_raw(fobj.read())
if cat.catalog_file:
if _mapper.fs.exists(cat.catalog_file):
csv_path = cat.catalog_file
else:
csv_path = f'{os.path.dirname(_mapper.root)}/{cat.catalog_file}'
cat.catalog_file = csv_path
df = pd.read_csv(
cat.catalog_file,
storage_options=storage_options,
**read_csv_kwargs,
)
else:
df = pd.DataFrame(cat.catalog_dict)
cat._df = df
cat._cast_agg_columns_with_iterables()
return cat
@property
def columns_with_iterables(self) -> typing.Set[str]:
if self._df.empty:
return set()
has_iterables = (
self._df.sample(20, replace=True)
.applymap(type)
.isin([list, tuple, set])
.any()
.to_dict()
)
return {column for column, check in has_iterables.items() if check}
@property
def has_multiple_variable_assets(self) -> bool:
return self.aggregation_control.variable_column_name in self.columns_with_iterables
@property
def df(self) -> pd.DataFrame:
return self._df
@df.setter
def df(self, value: pd.DataFrame) -> None:
self._df = value
def _cast_agg_columns_with_iterables(self) -> None:
columns = list(
self.columns_with_iterables.intersection(
set(map(lambda agg: agg.attribute_name, self.aggregation_control.aggregations))
)
)
if columns:
self._df[columns] = self._df[columns].apply(tuple)
@property
def grouped(self) -> typing.Union[pd.core.groupby.DataFrameGroupBy, pd.DataFrame]:
if self.aggregation_control.groupby_attrs and set(
self.aggregation_control.groupby_attrs
) != set(self.df.columns):
return self.df.groupby(self.aggregation_control.groupby_attrs)
return self.df
def _construct_group_keys(
self, sep: str = '.'
) -> typing.Dict[str, typing.Union[str, typing.Tuple[str]]]:
grouped = self.grouped
if isinstance(grouped, pd.core.groupby.generic.DataFrameGroupBy):
internal_keys = grouped.groups.keys()
public_keys = map(
lambda key: key if isinstance(key, str) else sep.join(str(value) for value in key),
internal_keys,
)
else:
internal_keys = grouped.index
public_keys = (
grouped[grouped.columns.tolist()]
.apply(lambda row: sep.join(str(v) for v in row), axis=1)
.tolist()
)
return dict(zip(public_keys, internal_keys))
def _unique(self) -> typing.Dict:
def _find_unique(series):
values = series.dropna()
if series.name in self.columns_with_iterables:
values = tlz.concat(values)
return list(tlz.unique(values))
data = self.df[self.df.columns]
if data.empty:
return {col: [] for col in self.df.columns}
else:
return data.apply(_find_unique, result_type='reduce').to_dict()
def unique(self) -> pd.Series:
return pd.Series(self._unique())
def nunique(self) -> pd.Series:
return pd.Series(tlz.valmap(len, self._unique()))
def search(
self,
*,
query: typing.Union['QueryModel', typing.Dict[str, typing.Any]],
require_all_on: typing.Union[str, typing.List[str]] = None,
) -> 'ESMCatalogModel':
if not isinstance(query, QueryModel):
_query = QueryModel(
query=query, require_all_on=require_all_on, columns=self.df.columns.tolist()
)
else:
_query = query
results = search(
df=self.df, query=_query.query, columns_with_iterables=self.columns_with_iterables
)
if _query.require_all_on is not None and not results.empty:
results = search_apply_require_all_on(
df=results, query=_query.query, require_all_on=_query.require_all_on
)
return results
class QueryModel(pydantic.BaseModel):
query: typing.Dict[pydantic.StrictStr, typing.Union[typing.Any, typing.List[typing.Any]]]
columns: typing.List[str]
require_all_on: typing.Union[str, typing.List[typing.Any]] = None
class Config:
validate_all = True
validate_assignment = True
@pydantic.root_validator(pre=False)
def validate_query(cls, values):
query = values.get('query', {})
columns = values.get('columns')
require_all_on = values.get('require_all_on', [])
if query:
for key in query:
if key not in columns:
raise ValueError(f'Column {key} not in columns {columns}')
if isinstance(require_all_on, str):
values['require_all_on'] = [require_all_on]
if require_all_on is not None:
for key in values['require_all_on']:
if key not in columns:
raise ValueError(f'Column {key} not in columns {columns}')
_query = query.copy()
for key, value in _query.items():
if isinstance(value, (str, int, float, bool)):
_query[key] = [value]
values['query'] = _query
return values
| true | true |
f7317f9433b31ade91e5efd2feb76b31b2af0dcf | 228 | py | Python | adc/tth.py | udoprog/python-adc | 6e3775a6fddd0c4a12211a237e2ae5f62a79fd31 | [
"BSD-3-Clause"
] | 1 | 2015-02-01T15:05:16.000Z | 2015-02-01T15:05:16.000Z | adc/tth.py | udoprog/python-adc | 6e3775a6fddd0c4a12211a237e2ae5f62a79fd31 | [
"BSD-3-Clause"
] | null | null | null | adc/tth.py | udoprog/python-adc | 6e3775a6fddd0c4a12211a237e2ae5f62a79fd31 | [
"BSD-3-Clause"
] | null | null | null | from merkletree import MerkleTree
from .hashing import TigerHash
class TigerTree(MerkleTree):
segment = 1024;
hashsize = TigerHash.size;
@classmethod
def _hash(klass, *chunks):
return TigerHash.digest(*chunks);
| 19 | 37 | 0.741228 | from merkletree import MerkleTree
from .hashing import TigerHash
class TigerTree(MerkleTree):
segment = 1024;
hashsize = TigerHash.size;
@classmethod
def _hash(klass, *chunks):
return TigerHash.digest(*chunks);
| true | true |
f7318003a4d1f4c23a5fc12ba056718d045c25e6 | 3,232 | py | Python | dataflows/processors/parallelize.py | cschloer/dataflows | 78a683b5d202512c06021ff6be8ac7f60ef1cd9b | [
"MIT"
] | null | null | null | dataflows/processors/parallelize.py | cschloer/dataflows | 78a683b5d202512c06021ff6be8ac7f60ef1cd9b | [
"MIT"
] | null | null | null | dataflows/processors/parallelize.py | cschloer/dataflows | 78a683b5d202512c06021ff6be8ac7f60ef1cd9b | [
"MIT"
] | null | null | null | import itertools
import os
import multiprocessing as mp
import threading
import queue
from ..helpers import ResourceMatcher
from .. import PackageWrapper, ResourceWrapper
def init_mp(num_processors, row_func, q_in, q_internal):
q_out = mp.Queue()
processes = [mp.Process(target=work, args=(q_in, q_out, row_func)) for _ in range(num_processors)]
for process in processes:
process.start()
t_fetch = threading.Thread(target=fetcher, args=(q_out, q_internal, num_processors))
t_fetch.start()
return (processes, t_fetch)
def fini_mp(processes, t_fetch):
for process in processes:
try:
process.join(timeout=10)
except Exception:
try:
process.kill()
except Exception:
pass
finally:
process.close()
t_fetch.join()
def producer(res, q_in, q_internal, num_processors, predicate):
try:
for row in res:
if predicate(row):
q_in.put(row)
else:
q_internal.put(row)
for _ in range(num_processors):
q_in.put(None)
except Exception:
q_internal.put(None)
return 1
return 0
def fetcher(q_out, q_internal, num_processors):
expected_nones = num_processors
while True:
row = q_out.get()
if row is None:
expected_nones -= 1
if expected_nones == 0:
q_internal.put(None)
break
continue
q_internal.put(row)
def work(q_in: mp.Queue, q_out: mp.Queue, row_func):
pid = os.getpid()
try:
while True:
row = q_in.get()
if row is None:
break
try:
row_func(row)
except Exception as e:
print(pid, 'FAILED TO RUN row_func {}\n'.format(e))
pass
q_out.put(row)
except Exception:
pass
finally:
q_out.put(None)
def fork(res, row_func, num_processors, predicate):
predicate = predicate or (lambda x: True)
for row in res:
if predicate(row):
res = itertools.chain([row], res)
q_in = mp.Queue()
q_internal = queue.Queue()
t_prod = threading.Thread(target=producer, args=(res, q_in, q_internal, num_processors, predicate))
t_prod.start()
processes, t_fetch = init_mp(num_processors, row_func, q_in, q_internal)
while True:
row = q_internal.get()
if row is None:
break
yield row
t_prod.join()
fini_mp(processes, t_fetch)
else:
yield row
def parallelize(row_func, num_processors=None, resources=None, predicate=None):
num_processors = num_processors or 2*os.cpu_count()
def func(package: PackageWrapper):
yield package.pkg
matcher = ResourceMatcher(resources, package.pkg)
res: ResourceWrapper
for res in package:
if matcher.match(res.res.name):
yield fork(res, row_func, num_processors, predicate)
else:
yield res
return func
| 26.933333 | 111 | 0.569926 | import itertools
import os
import multiprocessing as mp
import threading
import queue
from ..helpers import ResourceMatcher
from .. import PackageWrapper, ResourceWrapper
def init_mp(num_processors, row_func, q_in, q_internal):
q_out = mp.Queue()
processes = [mp.Process(target=work, args=(q_in, q_out, row_func)) for _ in range(num_processors)]
for process in processes:
process.start()
t_fetch = threading.Thread(target=fetcher, args=(q_out, q_internal, num_processors))
t_fetch.start()
return (processes, t_fetch)
def fini_mp(processes, t_fetch):
for process in processes:
try:
process.join(timeout=10)
except Exception:
try:
process.kill()
except Exception:
pass
finally:
process.close()
t_fetch.join()
def producer(res, q_in, q_internal, num_processors, predicate):
try:
for row in res:
if predicate(row):
q_in.put(row)
else:
q_internal.put(row)
for _ in range(num_processors):
q_in.put(None)
except Exception:
q_internal.put(None)
return 1
return 0
def fetcher(q_out, q_internal, num_processors):
expected_nones = num_processors
while True:
row = q_out.get()
if row is None:
expected_nones -= 1
if expected_nones == 0:
q_internal.put(None)
break
continue
q_internal.put(row)
def work(q_in: mp.Queue, q_out: mp.Queue, row_func):
pid = os.getpid()
try:
while True:
row = q_in.get()
if row is None:
break
try:
row_func(row)
except Exception as e:
print(pid, 'FAILED TO RUN row_func {}\n'.format(e))
pass
q_out.put(row)
except Exception:
pass
finally:
q_out.put(None)
def fork(res, row_func, num_processors, predicate):
predicate = predicate or (lambda x: True)
for row in res:
if predicate(row):
res = itertools.chain([row], res)
q_in = mp.Queue()
q_internal = queue.Queue()
t_prod = threading.Thread(target=producer, args=(res, q_in, q_internal, num_processors, predicate))
t_prod.start()
processes, t_fetch = init_mp(num_processors, row_func, q_in, q_internal)
while True:
row = q_internal.get()
if row is None:
break
yield row
t_prod.join()
fini_mp(processes, t_fetch)
else:
yield row
def parallelize(row_func, num_processors=None, resources=None, predicate=None):
num_processors = num_processors or 2*os.cpu_count()
def func(package: PackageWrapper):
yield package.pkg
matcher = ResourceMatcher(resources, package.pkg)
res: ResourceWrapper
for res in package:
if matcher.match(res.res.name):
yield fork(res, row_func, num_processors, predicate)
else:
yield res
return func
| true | true |
f73180d03d5ce10b4c3dc13aefb29b163648e360 | 3,306 | py | Python | data/p2DJ/New/program/qiskit/simulator/startQiskit336.py | UCLA-SEAL/QDiff | d968cbc47fe926b7f88b4adf10490f1edd6f8819 | [
"BSD-3-Clause"
] | null | null | null | data/p2DJ/New/program/qiskit/simulator/startQiskit336.py | UCLA-SEAL/QDiff | d968cbc47fe926b7f88b4adf10490f1edd6f8819 | [
"BSD-3-Clause"
] | null | null | null | data/p2DJ/New/program/qiskit/simulator/startQiskit336.py | UCLA-SEAL/QDiff | d968cbc47fe926b7f88b4adf10490f1edd6f8819 | [
"BSD-3-Clause"
] | null | null | null | # qubit number=2
# total number=18
import cirq
import qiskit
from qiskit import IBMQ
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer, execute, transpile
from pprint import pprint
from qiskit.test.mock import FakeVigo
from math import log2,floor, sqrt, pi
import numpy as np
import networkx as nx
def build_oracle(n: int, f) -> QuantumCircuit:
# implement the oracle O_f^\pm
# NOTE: use U1 gate (P gate) with \lambda = 180 ==> CZ gate
# or multi_control_Z_gate (issue #127)
controls = QuantumRegister(n, "ofc")
target = QuantumRegister(1, "oft")
oracle = QuantumCircuit(controls, target, name="Of")
for i in range(2 ** n):
rep = np.binary_repr(i, n)
if f(rep) == "1":
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
oracle.mct(controls, target[0], None, mode='noancilla')
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
# oracle.barrier()
# oracle.draw('mpl', filename='circuit/deutsch-oracle.png')
return oracle
def make_circuit(n:int,f) -> QuantumCircuit:
# circuit begin
input_qubit = QuantumRegister(n, "qc")
target = QuantumRegister(1, "qt")
prog = QuantumCircuit(input_qubit, target)
# inverse last one (can be omitted if using O_f^\pm)
prog.x(target)
# apply H to get superposition
for i in range(n):
prog.h(input_qubit[i])
prog.h(input_qubit[1]) # number=1
prog.h(target)
prog.barrier()
# apply oracle O_f
oracle = build_oracle(n, f)
prog.append(
oracle.to_gate(),
[input_qubit[i] for i in range(n)] + [target])
# apply H back (QFT on Z_2^n)
for i in range(n):
prog.h(input_qubit[i])
prog.barrier()
# measure
#for i in range(n):
# prog.measure(input_qubit[i], classicals[i])
prog.y(input_qubit[1]) # number=2
prog.y(input_qubit[1]) # number=4
prog.y(input_qubit[1]) # number=3
prog.rx(2.0860175219836226,input_qubit[1]) # number=7
prog.x(input_qubit[0]) # number=5
prog.x(input_qubit[0]) # number=6
prog.h(input_qubit[0]) # number=10
prog.cz(input_qubit[1],input_qubit[0]) # number=11
prog.h(input_qubit[0]) # number=12
prog.h(input_qubit[0]) # number=13
prog.cz(input_qubit[1],input_qubit[0]) # number=14
prog.h(input_qubit[0]) # number=15
prog.x(input_qubit[1]) # number=16
prog.x(input_qubit[1]) # number=17
# circuit end
return prog
if __name__ == '__main__':
n = 2
f = lambda rep: rep[-1]
# f = lambda rep: "1" if rep[0:2] == "01" or rep[0:2] == "10" else "0"
# f = lambda rep: "0"
prog = make_circuit(n, f)
sample_shot =2800
backend = BasicAer.get_backend('qasm_simulator')
circuit1 = transpile(prog,FakeVigo())
circuit1.x(qubit=3)
circuit1.x(qubit=3)
circuit1.measure_all()
prog = circuit1
info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()
writefile = open("../data/startQiskit336.csv","w")
print(info,file=writefile)
print("results end", file=writefile)
print(circuit1.depth(),file=writefile)
print(circuit1,file=writefile)
writefile.close()
| 28.747826 | 82 | 0.625227 |
import cirq
import qiskit
from qiskit import IBMQ
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer, execute, transpile
from pprint import pprint
from qiskit.test.mock import FakeVigo
from math import log2,floor, sqrt, pi
import numpy as np
import networkx as nx
def build_oracle(n: int, f) -> QuantumCircuit:
controls = QuantumRegister(n, "ofc")
target = QuantumRegister(1, "oft")
oracle = QuantumCircuit(controls, target, name="Of")
for i in range(2 ** n):
rep = np.binary_repr(i, n)
if f(rep) == "1":
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
oracle.mct(controls, target[0], None, mode='noancilla')
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
return oracle
def make_circuit(n:int,f) -> QuantumCircuit:
input_qubit = QuantumRegister(n, "qc")
target = QuantumRegister(1, "qt")
prog = QuantumCircuit(input_qubit, target)
prog.x(target)
for i in range(n):
prog.h(input_qubit[i])
prog.h(input_qubit[1])
prog.h(target)
prog.barrier()
oracle = build_oracle(n, f)
prog.append(
oracle.to_gate(),
[input_qubit[i] for i in range(n)] + [target])
for i in range(n):
prog.h(input_qubit[i])
prog.barrier()
prog.y(input_qubit[1])
prog.y(input_qubit[1])
prog.y(input_qubit[1])
prog.rx(2.0860175219836226,input_qubit[1])
prog.x(input_qubit[0])
prog.x(input_qubit[0])
prog.h(input_qubit[0])
prog.cz(input_qubit[1],input_qubit[0])
prog.h(input_qubit[0])
prog.h(input_qubit[0])
prog.cz(input_qubit[1],input_qubit[0])
prog.h(input_qubit[0])
prog.x(input_qubit[1])
prog.x(input_qubit[1])
return prog
if __name__ == '__main__':
n = 2
f = lambda rep: rep[-1]
prog = make_circuit(n, f)
sample_shot =2800
backend = BasicAer.get_backend('qasm_simulator')
circuit1 = transpile(prog,FakeVigo())
circuit1.x(qubit=3)
circuit1.x(qubit=3)
circuit1.measure_all()
prog = circuit1
info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()
writefile = open("../data/startQiskit336.csv","w")
print(info,file=writefile)
print("results end", file=writefile)
print(circuit1.depth(),file=writefile)
print(circuit1,file=writefile)
writefile.close()
| true | true |
f73180ffb7b8ac7ff84ef16f39b5d76cd4a45949 | 255 | py | Python | tests/urls.py | srijwalzartek/django-slick-reporting | aed9262a3dd83aa28e141301a4b3bf7041be7748 | [
"BSD-3-Clause"
] | null | null | null | tests/urls.py | srijwalzartek/django-slick-reporting | aed9262a3dd83aa28e141301a4b3bf7041be7748 | [
"BSD-3-Clause"
] | null | null | null | tests/urls.py | srijwalzartek/django-slick-reporting | aed9262a3dd83aa28e141301a4b3bf7041be7748 | [
"BSD-3-Clause"
] | null | null | null | from django.urls import path
from . import views
urlpatterns = [
path('report1/', views.MonthlyProductSales.as_view(), name='report1'),
path('product_crosstab_client/', views.ProductClientSalesMatrix.as_view(), name='product_crosstab_client'),
]
| 31.875 | 111 | 0.756863 | from django.urls import path
from . import views
urlpatterns = [
path('report1/', views.MonthlyProductSales.as_view(), name='report1'),
path('product_crosstab_client/', views.ProductClientSalesMatrix.as_view(), name='product_crosstab_client'),
]
| true | true |
f7318134d4c39845139626c088e97f1dd313f92c | 4,575 | py | Python | minecraft_dynmap_timemachine/dynmap.py | paul-eff/minecraft-dynmap-timemachine | ee902fe6600023a3de2d3b71969738016914a03a | [
"MIT"
] | 61 | 2015-05-22T17:30:09.000Z | 2022-02-26T20:22:15.000Z | minecraft_dynmap_timemachine/dynmap.py | paul-eff/minecraft-dynmap-timemachine | ee902fe6600023a3de2d3b71969738016914a03a | [
"MIT"
] | 10 | 2017-07-18T18:34:42.000Z | 2022-03-09T01:49:13.000Z | minecraft_dynmap_timemachine/dynmap.py | paul-eff/minecraft-dynmap-timemachine | ee902fe6600023a3de2d3b71969738016914a03a | [
"MIT"
] | 18 | 2017-12-28T10:44:54.000Z | 2022-02-26T01:33:05.000Z | # import urllib
import json
import time
import math
import re
from . import simple_downloader
class MapException(Exception):
def __init__(self, map_obj, *args, **kwargs):
super(MapException, self).__init__(*args, **kwargs)
self.map = map_obj
class DynMap(object):
def __init__(self, url):
# super(DynMap, self).__init__(*args, **kwargs)
self.url = url.rstrip('/')
#self._server_addres = server_addres
#self._cache_dir = cache_dir
self._config = None
self._config_urls = None
self._worlds = {}
#self.urls # force init dynmap urls from server or from property
self._init()
def _init(self):
for c in self.config['worlds']:
# print(c)
w = World(c)
self._worlds[w.name] = w
def _download_config(self):
"""configuration of all worlds and their maps"""
rel_path = self.urls['configuration'].replace('{timestamp}', str(int(time.time())))
return simple_downloader.download(self.url + '/' + rel_path)
def _download_config_urls(self):
"""DynMap configuration"""
return simple_downloader.download(self.url + '/' + 'standalone/config.js')
@staticmethod
def parse_config_urls_string(jsonlike_str):
m = re.search('url \: (.+)};', jsonlike_str, re.DOTALL)
#return json.loads(m.group(1))
pattern = r"([a-zA-Z_][a-zA-Z_0-9]*)\s*\:"
repl = lambda match: '"{}":'.format(match.group(1))
json_str = re.sub(pattern, repl, m.group(1))
#print json_str
return json.loads(json_str.replace('\'', '"'))
@property
def urls(self):
if not self._config_urls:
# if self._config_urls_json:
# self._config_urls = json.loads(self._config_urls_json)
# else:
self._config_urls = self.parse_config_urls_string(self._download_config_urls())
# self._config_urls_json = json.dumps(self._config_urls)
#self.save()
return self._config_urls
@property
def config(self):
if not self._config:
# if self._config_json:
# self._config = json.loads(self._config_json)
# else:
self._config = json.loads(self._download_config())
# self._config_json = json.dumps(self._config)
return self._config
@property
def worlds(self):
return self._worlds
class World(object):
def __init__(self, world_config):
self._config = world_config
self._maps = {}
self._init()
def _init(self):
for c in self._config['maps']:
m = Map(c, self.name)
self._maps[m.name] = m
@property
def name(self):
return self._config['name']
@property
def title(self):
return self._config['title']
@property
def maps(self):
return self._maps
class Map(object):
# PERSPECTIVES = ['iso_SE_30_hires', 'iso_SE_30_lowres', 'iso_SE_60_hires', 'iso_SE_60_lowres', 'iso_S_90_hires', 'iso_S_90_lowres']
# SHADERS = ['stdtexture', 'cave']
def __init__(self, map_config, world):
self._config = map_config
self._world = world
# if not Map.is_known_perspective(self.perspective):
# raise MapException(self, 'Unknown perspective "%s"' % self.perspective)
# if not Map.is_known_shader(self.shader):
# raise MapException(self, 'Unknown shader "%s"' % self.shader)
# @staticmethod
# def is_known_perspective(type_name):
# return type_name in Map.PERSPECTIVES
#
# @staticmethod
# def is_known_shader(shader_name):
# return shader_name in Map.SHADERS
def image_url(self, t_loc):
zoom = t_loc.zoom
chunk_x = math.floor(t_loc.x / 32.0)
chunk_y = math.floor(t_loc.y / 32.0)
dashes = ('' if zoom == 0 else ('z' * zoom) + '_')
image_url = '/tiles/%s/%s/%d_%d/%s%d_%d.png' % (self._world, self.prefix, chunk_x, chunk_y, dashes, t_loc.x, t_loc.y)
return image_url
@property
def perspective(self):
return self._config['perspective']
@property
def shader(self):
return self._config['shader']
@property
def name(self):
return self._config['name']
@property
def title(self):
return self._config['title']
@property
def worldtomap(self):
return self._config['worldtomap']
@property
def prefix(self):
return self._config['prefix'] | 28.773585 | 136 | 0.599344 |
import json
import time
import math
import re
from . import simple_downloader
class MapException(Exception):
def __init__(self, map_obj, *args, **kwargs):
super(MapException, self).__init__(*args, **kwargs)
self.map = map_obj
class DynMap(object):
def __init__(self, url):
self.url = url.rstrip('/')
self._config = None
self._config_urls = None
self._worlds = {}
or c in self.config['worlds']:
w = World(c)
self._worlds[w.name] = w
def _download_config(self):
rel_path = self.urls['configuration'].replace('{timestamp}', str(int(time.time())))
return simple_downloader.download(self.url + '/' + rel_path)
def _download_config_urls(self):
return simple_downloader.download(self.url + '/' + 'standalone/config.js')
@staticmethod
def parse_config_urls_string(jsonlike_str):
m = re.search('url \: (.+)};', jsonlike_str, re.DOTALL)
pattern = r"([a-zA-Z_][a-zA-Z_0-9]*)\s*\:"
repl = lambda match: '"{}":'.format(match.group(1))
json_str = re.sub(pattern, repl, m.group(1))
return json.loads(json_str.replace('\'', '"'))
@property
def urls(self):
if not self._config_urls:
# if self._config_urls_json:
# self._config_urls = json.loads(self._config_urls_json)
# else:
self._config_urls = self.parse_config_urls_string(self._download_config_urls())
# self._config_urls_json = json.dumps(self._config_urls)
#self.save()
return self._config_urls
@property
def config(self):
if not self._config:
# if self._config_json:
# self._config = json.loads(self._config_json)
# else:
self._config = json.loads(self._download_config())
# self._config_json = json.dumps(self._config)
return self._config
@property
def worlds(self):
return self._worlds
class World(object):
def __init__(self, world_config):
self._config = world_config
self._maps = {}
self._init()
def _init(self):
for c in self._config['maps']:
m = Map(c, self.name)
self._maps[m.name] = m
@property
def name(self):
return self._config['name']
@property
def title(self):
return self._config['title']
@property
def maps(self):
return self._maps
class Map(object):
# PERSPECTIVES = ['iso_SE_30_hires', 'iso_SE_30_lowres', 'iso_SE_60_hires', 'iso_SE_60_lowres', 'iso_S_90_hires', 'iso_S_90_lowres']
# SHADERS = ['stdtexture', 'cave']
def __init__(self, map_config, world):
self._config = map_config
self._world = world
# if not Map.is_known_perspective(self.perspective):
# raise MapException(self, 'Unknown perspective "%s"' % self.perspective)
# if not Map.is_known_shader(self.shader):
# raise MapException(self, 'Unknown shader "%s"' % self.shader)
# @staticmethod
# def is_known_perspective(type_name):
# return type_name in Map.PERSPECTIVES
#
# @staticmethod
# def is_known_shader(shader_name):
# return shader_name in Map.SHADERS
def image_url(self, t_loc):
zoom = t_loc.zoom
chunk_x = math.floor(t_loc.x / 32.0)
chunk_y = math.floor(t_loc.y / 32.0)
dashes = ('' if zoom == 0 else ('z' * zoom) + '_')
image_url = '/tiles/%s/%s/%d_%d/%s%d_%d.png' % (self._world, self.prefix, chunk_x, chunk_y, dashes, t_loc.x, t_loc.y)
return image_url
@property
def perspective(self):
return self._config['perspective']
@property
def shader(self):
return self._config['shader']
@property
def name(self):
return self._config['name']
@property
def title(self):
return self._config['title']
@property
def worldtomap(self):
return self._config['worldtomap']
@property
def prefix(self):
return self._config['prefix'] | true | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.