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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1c2e3e29450951f7817fa320c3125f8a88f35010 | 733 | py | Python | codes/MIGraph/Encoders/CompoundEncoder.py | KentaroKutsukake/Integrating-multiple-materials-science-projects | a6f09583718fc00431a3ce67d5fc6f026646f91c | [
"MIT"
] | 5 | 2020-07-31T01:35:49.000Z | 2021-07-30T13:05:48.000Z | codes/MIGraph/Encoders/CompoundEncoder.py | KentaroKutsukake/Integrating-multiple-materials-science-projects | a6f09583718fc00431a3ce67d5fc6f026646f91c | [
"MIT"
] | null | null | null | codes/MIGraph/Encoders/CompoundEncoder.py | KentaroKutsukake/Integrating-multiple-materials-science-projects | a6f09583718fc00431a3ce67d5fc6f026646f91c | [
"MIT"
] | 2 | 2020-10-21T19:17:06.000Z | 2021-05-17T10:38:41.000Z |
"""
Compound encoder
this class returns vector information of a target smiles
"""
import numpy as np
from Config import Config
CF=Config()
categoryEmbed=CF.categoryEmbed
#compound encoder class
class CompEncoder:
def __init__(self,CompDat,num):
"""
CompDat: CompDatabase class
num: =CF.ID_COMPOUNDS (=3)
"""
self.CompDat=CompDat
self.num=num
#get embetting vector
def getEVector(self,string):
"""
input: SMILES
return :embedding vector
"""
num=self.num
res=self.CompDat.getCompDesc(string)
num=categoryEmbed(np.array([num])).array
return np.concatenate([num,res],1).reshape(-1)
| 20.942857 | 56 | 0.608458 |
import numpy as np
from Config import Config
CF=Config()
categoryEmbed=CF.categoryEmbed
class CompEncoder:
def __init__(self,CompDat,num):
self.CompDat=CompDat
self.num=num
def getEVector(self,string):
num=self.num
res=self.CompDat.getCompDesc(string)
num=categoryEmbed(np.array([num])).array
return np.concatenate([num,res],1).reshape(-1)
| true | true |
1c2e3e3aee69136d4d47437ed81e6f8478aef8ce | 670 | py | Python | tests/python/test_cuda_internals.py | gaoxinge/taichi | 86d403f071b8505858763d4712b37cd71b89db91 | [
"MIT"
] | 1 | 2020-11-10T07:17:01.000Z | 2020-11-10T07:17:01.000Z | tests/python/test_cuda_internals.py | gaoxinge/taichi | 86d403f071b8505858763d4712b37cd71b89db91 | [
"MIT"
] | 1 | 2020-08-24T05:18:43.000Z | 2020-08-24T05:18:43.000Z | tests/python/test_cuda_internals.py | gaoxinge/taichi | 86d403f071b8505858763d4712b37cd71b89db91 | [
"MIT"
] | null | null | null | from taichi.lang import impl
import taichi as ti
from tests import test_utils
# TODO: these are not really tests...
@test_utils.test(arch=ti.cuda)
def test_do_nothing():
@ti.kernel
def test():
for i in range(10):
impl.call_internal("do_nothing")
test()
@test_utils.test(arch=ti.cuda)
def test_active_mask():
@ti.kernel
def test():
for i in range(48):
if i % 2 == 0:
impl.call_internal("test_active_mask")
test()
@test_utils.test(arch=ti.cuda)
def test_shfl_down():
@ti.kernel
def test():
for i in range(32):
impl.call_internal("test_shfl")
test()
| 17.631579 | 54 | 0.602985 | from taichi.lang import impl
import taichi as ti
from tests import test_utils
@test_utils.test(arch=ti.cuda)
def test_do_nothing():
@ti.kernel
def test():
for i in range(10):
impl.call_internal("do_nothing")
test()
@test_utils.test(arch=ti.cuda)
def test_active_mask():
@ti.kernel
def test():
for i in range(48):
if i % 2 == 0:
impl.call_internal("test_active_mask")
test()
@test_utils.test(arch=ti.cuda)
def test_shfl_down():
@ti.kernel
def test():
for i in range(32):
impl.call_internal("test_shfl")
test()
| true | true |
1c2e3e50d1e8a86414fb26a4710c822625cf9f44 | 4,769 | py | Python | bwt.py | broestls/pycuda-bw-test | 0ac9a377363bb99bc1b9e5dd42bbdd0bd6d697c3 | [
"MIT"
] | null | null | null | bwt.py | broestls/pycuda-bw-test | 0ac9a377363bb99bc1b9e5dd42bbdd0bd6d697c3 | [
"MIT"
] | null | null | null | bwt.py | broestls/pycuda-bw-test | 0ac9a377363bb99bc1b9e5dd42bbdd0bd6d697c3 | [
"MIT"
] | null | null | null | import numpy as np
import pycuda.driver as cuda
from pycuda.compiler import SourceModule
from pycuda.tools import make_default_context, clear_context_caches
import glob
import sys
import os
from datetime import datetime
import ctypes
import atexit
import argparse
import subprocess
import psutil
import itertools
from signal import signal, SIGINT
from sys import exit
from multiprocessing import Process, Value, set_start_method, Pool, cpu_count, current_process
from codetiming import Timer
from utils import calc_bws, calc_gbs
global cuda_devices
parser = argparse.ArgumentParser(description="A program for simulating load on GPU memory and system bus")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--single', type=int, help="Run with a N constant size array")
group.add_argument('--batch', action='store_true')
group.add_argument('--hwinfo', type=int, help="Gets info for CUDA device with ID")
parser.add_argument('-d', '--num_devices', type=int, help="Number of CUDA devices to use")
parser.add_argument('-i', '--iterations', type=int, default=1, help="number of iterations to run")
parser.add_argument('-w', '--workers', type=int, default=4, help="number of workers to spawn")
parser.add_argument('-e', '--elements', type=int, default=4, help="number of numpy arrays to work on")
parser.add_argument('--debug', action='store_true')
parser.add_argument('-n', '--name', type=str, help='name to use for the run')
args = parser.parse_args()
def get_hw_info(device_id):
device = cuda.Device(device_id)
return "device_id: {}, bus_id: {}, name: {}, cuda_version: {}".format(device_id, device.pci_bus_id(), device.name(), cuda.get_version())
def handler(signal_received, frame):
print('Shutting down...')
exit(0)
def np_to_hmem(src, dest):
source = src.ctypes.data_as(ctypes.POINTER(ctypes.c_float))
destination = dest.ctypes.data_as(ctypes.POINTER(ctypes.c_float))
size = src.size * ctypes.sizeof(ctypes.c_float)
ctypes.memmove(source,destination,size)
def load_single_array(mb_size):
return np.random.randn(int(mb_size * (10**6)/4)).astype(np.float32)
def transfer_data(size):
t1 = Timer(name="total_memcpy_time", logger=None)
t1.start()
cuda.init()
device = cuda.Device(0)
context = device.make_context()
dev_id = context.get_device().pci_bus_id()
np_array = np.random.randn(int(size * (10**6)/4)).astype(np.float32)
np_return = np.empty_like(np_array)
mem_gpu = cuda.mem_alloc(np_array.nbytes)
mem_host = cuda.register_host_memory(np_array)
np_to_hmem(np_array,mem_host)
t2 = Timer(name="hmem_to_dmem", logger=None)
t2.start()
cuda.memcpy_htod(mem_gpu, mem_host)
t2.stop()
t3 = Timer(name="dmem_to_hmem", logger=None)
t3.start()
return_data = np.empty_like(np_array)
cuda.memcpy_dtoh(mem_host, mem_gpu)
t3.stop()
mem_host.base.unregister()
mem_gpu.free()
context.pop()
context = None
clear_context_caches()
t1.stop()
if(args.debug):
print("{},{},{},{},{},{},{},{}".format('htod-'+args.name+'-debug',args.single,format(t2.last, '.4f'),calc_gbs(size,t2.last),psutil.Process().cpu_num(),psutil.Process().pid,dev_id,current_process().name))
print("{},{},{},{},{},{},{},{}".format('dtoh-'+args.name+'-debug',args.single,format(t3.last, '.4f'),calc_gbs(size,t3.last),psutil.Process().cpu_num(),psutil.Process().pid,dev_id,current_process().name))
return {'total_time':t1.last, 'htod': calc_gbs(size,t2.last), 'htod_time':t2.last, 'dtoh': calc_gbs(size,t3.last), 'dtoh_time':t3.last}
def devices_to_workers():
cuda.init()
global cuda_devices
available_devices = args.num_cuda_devices
for i in range(args.workers):
cuda_devices[i] = 0
if __name__ == "__main__":
signal(SIGINT, handler)
set_start_method('fork')
np_list = [args.single for x in range(args.elements)]
pool = Pool(processes=args.workers)
for i in range(args.iterations):
total_size = args.single * args.elements
res = pool.map(transfer_data, np_list)
hotd_bandwidth = sum([float(x['htod']) for x in res])/args.elements
dtoh_bandwidth = sum([float(x['dtoh']) for x in res])/args.elements
total_time = sum([float(x['total_time']) for x in res])
htod_time = sum([float(x['htod_time']) for x in res])
dtoh_time = sum([float(x['dtoh_time']) for x in res])
print("{},{},{},{},{},{},{},{},{},{}".format(args.name,args.single,format(total_time, '.4f'),format(hotd_bandwidth, '.4f'),format(htod_time, '.4f'),format(dtoh_bandwidth, '.4f'),format(dtoh_time, '.4f'),args.workers,'epoch-'+str(i),datetime.now().strftime("%H:%M:%S:%f")))
if args.hwinfo != None:
print(get_hw_info(args.hwinfo)) | 43.354545 | 280 | 0.695743 | import numpy as np
import pycuda.driver as cuda
from pycuda.compiler import SourceModule
from pycuda.tools import make_default_context, clear_context_caches
import glob
import sys
import os
from datetime import datetime
import ctypes
import atexit
import argparse
import subprocess
import psutil
import itertools
from signal import signal, SIGINT
from sys import exit
from multiprocessing import Process, Value, set_start_method, Pool, cpu_count, current_process
from codetiming import Timer
from utils import calc_bws, calc_gbs
global cuda_devices
parser = argparse.ArgumentParser(description="A program for simulating load on GPU memory and system bus")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--single', type=int, help="Run with a N constant size array")
group.add_argument('--batch', action='store_true')
group.add_argument('--hwinfo', type=int, help="Gets info for CUDA device with ID")
parser.add_argument('-d', '--num_devices', type=int, help="Number of CUDA devices to use")
parser.add_argument('-i', '--iterations', type=int, default=1, help="number of iterations to run")
parser.add_argument('-w', '--workers', type=int, default=4, help="number of workers to spawn")
parser.add_argument('-e', '--elements', type=int, default=4, help="number of numpy arrays to work on")
parser.add_argument('--debug', action='store_true')
parser.add_argument('-n', '--name', type=str, help='name to use for the run')
args = parser.parse_args()
def get_hw_info(device_id):
device = cuda.Device(device_id)
return "device_id: {}, bus_id: {}, name: {}, cuda_version: {}".format(device_id, device.pci_bus_id(), device.name(), cuda.get_version())
def handler(signal_received, frame):
print('Shutting down...')
exit(0)
def np_to_hmem(src, dest):
source = src.ctypes.data_as(ctypes.POINTER(ctypes.c_float))
destination = dest.ctypes.data_as(ctypes.POINTER(ctypes.c_float))
size = src.size * ctypes.sizeof(ctypes.c_float)
ctypes.memmove(source,destination,size)
def load_single_array(mb_size):
return np.random.randn(int(mb_size * (10**6)/4)).astype(np.float32)
def transfer_data(size):
t1 = Timer(name="total_memcpy_time", logger=None)
t1.start()
cuda.init()
device = cuda.Device(0)
context = device.make_context()
dev_id = context.get_device().pci_bus_id()
np_array = np.random.randn(int(size * (10**6)/4)).astype(np.float32)
np_return = np.empty_like(np_array)
mem_gpu = cuda.mem_alloc(np_array.nbytes)
mem_host = cuda.register_host_memory(np_array)
np_to_hmem(np_array,mem_host)
t2 = Timer(name="hmem_to_dmem", logger=None)
t2.start()
cuda.memcpy_htod(mem_gpu, mem_host)
t2.stop()
t3 = Timer(name="dmem_to_hmem", logger=None)
t3.start()
return_data = np.empty_like(np_array)
cuda.memcpy_dtoh(mem_host, mem_gpu)
t3.stop()
mem_host.base.unregister()
mem_gpu.free()
context.pop()
context = None
clear_context_caches()
t1.stop()
if(args.debug):
print("{},{},{},{},{},{},{},{}".format('htod-'+args.name+'-debug',args.single,format(t2.last, '.4f'),calc_gbs(size,t2.last),psutil.Process().cpu_num(),psutil.Process().pid,dev_id,current_process().name))
print("{},{},{},{},{},{},{},{}".format('dtoh-'+args.name+'-debug',args.single,format(t3.last, '.4f'),calc_gbs(size,t3.last),psutil.Process().cpu_num(),psutil.Process().pid,dev_id,current_process().name))
return {'total_time':t1.last, 'htod': calc_gbs(size,t2.last), 'htod_time':t2.last, 'dtoh': calc_gbs(size,t3.last), 'dtoh_time':t3.last}
def devices_to_workers():
cuda.init()
global cuda_devices
available_devices = args.num_cuda_devices
for i in range(args.workers):
cuda_devices[i] = 0
if __name__ == "__main__":
signal(SIGINT, handler)
set_start_method('fork')
np_list = [args.single for x in range(args.elements)]
pool = Pool(processes=args.workers)
for i in range(args.iterations):
total_size = args.single * args.elements
res = pool.map(transfer_data, np_list)
hotd_bandwidth = sum([float(x['htod']) for x in res])/args.elements
dtoh_bandwidth = sum([float(x['dtoh']) for x in res])/args.elements
total_time = sum([float(x['total_time']) for x in res])
htod_time = sum([float(x['htod_time']) for x in res])
dtoh_time = sum([float(x['dtoh_time']) for x in res])
print("{},{},{},{},{},{},{},{},{},{}".format(args.name,args.single,format(total_time, '.4f'),format(hotd_bandwidth, '.4f'),format(htod_time, '.4f'),format(dtoh_bandwidth, '.4f'),format(dtoh_time, '.4f'),args.workers,'epoch-'+str(i),datetime.now().strftime("%H:%M:%S:%f")))
if args.hwinfo != None:
print(get_hw_info(args.hwinfo)) | true | true |
1c2e3f6cda81575e2f211c0c19990a5adcb75fb9 | 2,608 | py | Python | src/third_party/wiredtiger/test/suite/test_upgrade.py | hgGeorg/mongo | b5bea92504b2612f433b55e7b901f9ae276d11ec | [
"Apache-2.0"
] | 1 | 2020-01-01T06:16:58.000Z | 2020-01-01T06:16:58.000Z | src/third_party/wiredtiger/test/suite/test_upgrade.py | Man1029/CMONGO | c40380caa14e05509f46993aa8b8da966b09b0b5 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/third_party/wiredtiger/test/suite/test_upgrade.py | Man1029/CMONGO | c40380caa14e05509f46993aa8b8da966b09b0b5 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
#
# Public Domain 2014-2016 MongoDB, Inc.
# Public Domain 2008-2014 WiredTiger, Inc.
#
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compiled
# binary, for any purpose, commercial or non-commercial, and by any
# means.
#
# In jurisdictions that recognize copyright laws, the author or authors
# of this software dedicate any and all copyright interest in the
# software to the public domain. We make this dedication for the benefit
# of the public at large and to the detriment of our heirs and
# successors. We intend this dedication to be an overt act of
# relinquishment in perpetuity of all present and future rights to this
# software under copyright law.
#
# 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
import os, time
import wiredtiger, wttest
from helper import complex_populate, simple_populate
from wtscenario import make_scenarios
# test_upgrade.py
# session level upgrade operation
class test_upgrade(wttest.WiredTigerTestCase):
name = 'test_upgrade'
scenarios = make_scenarios([
('file', dict(uri='file:')),
('table', dict(uri='table:'))
])
# Populate an object, then upgrade it.
def upgrade(self, populate, with_cursor):
uri = self.uri + self.name
populate(self, uri, 'key_format=S', 10)
# Open cursors should cause failure.
if with_cursor:
cursor = self.session.open_cursor(uri, None, None)
self.assertRaises(wiredtiger.WiredTigerError,
lambda: self.session.drop(uri, None))
cursor.close()
self.session.upgrade(uri, None)
self.session.drop(uri)
# Test upgrade of an object.
def test_upgrade(self):
# Simple file or table object.
self.upgrade(simple_populate, False)
self.upgrade(simple_populate, True)
# A complex, multi-file table object.
if self.uri == "table:":
self.upgrade(complex_populate, False)
self.upgrade(complex_populate, True)
if __name__ == '__main__':
wttest.run()
| 36.222222 | 73 | 0.705521 |
import os, time
import wiredtiger, wttest
from helper import complex_populate, simple_populate
from wtscenario import make_scenarios
class test_upgrade(wttest.WiredTigerTestCase):
name = 'test_upgrade'
scenarios = make_scenarios([
('file', dict(uri='file:')),
('table', dict(uri='table:'))
])
def upgrade(self, populate, with_cursor):
uri = self.uri + self.name
populate(self, uri, 'key_format=S', 10)
if with_cursor:
cursor = self.session.open_cursor(uri, None, None)
self.assertRaises(wiredtiger.WiredTigerError,
lambda: self.session.drop(uri, None))
cursor.close()
self.session.upgrade(uri, None)
self.session.drop(uri)
def test_upgrade(self):
self.upgrade(simple_populate, False)
self.upgrade(simple_populate, True)
if self.uri == "table:":
self.upgrade(complex_populate, False)
self.upgrade(complex_populate, True)
if __name__ == '__main__':
wttest.run()
| true | true |
1c2e3fb6bad79b1aacdb5023df3f230ddeafaff8 | 863 | py | Python | tests/conftest.py | radarlabs/radar-python | 5b9a61bda3e405565eb16d76b120cc27f7a2a7b3 | [
"MIT"
] | 8 | 2020-03-16T18:14:49.000Z | 2021-01-26T20:27:54.000Z | tests/conftest.py | radarlabs/radar-python | 5b9a61bda3e405565eb16d76b120cc27f7a2a7b3 | [
"MIT"
] | 1 | 2020-03-21T19:54:49.000Z | 2020-03-21T19:54:49.000Z | tests/conftest.py | radarlabs/radar-python | 5b9a61bda3e405565eb16d76b120cc27f7a2a7b3 | [
"MIT"
] | 3 | 2020-07-02T00:31:26.000Z | 2020-08-26T08:20:35.000Z | import os
import json
import pytest
from radar import RadarClient
MOCK_DATA_PATH = "tests/mock_data/{file_name}"
class TestHelpers:
def load_mock_data(file_name):
json_path = MOCK_DATA_PATH.format(file_name=file_name)
with open(json_path) as f:
return json.load(f)
@pytest.fixture(scope="module")
def radar():
radar = RadarClient(secret_key="sk_test_123", pub_key="pk_test_123")
return radar
@pytest.fixture(scope="module")
def geofence_json():
return TestHelpers.load_mock_data("geofence.json")
@pytest.fixture(scope="module")
def user_json():
return TestHelpers.load_mock_data("user.json")
@pytest.fixture(scope="module")
def event_json():
return TestHelpers.load_mock_data("event.json")
@pytest.fixture(scope="module")
def context_json():
return TestHelpers.load_mock_data("context.json")
| 20.547619 | 72 | 0.73117 | import os
import json
import pytest
from radar import RadarClient
MOCK_DATA_PATH = "tests/mock_data/{file_name}"
class TestHelpers:
def load_mock_data(file_name):
json_path = MOCK_DATA_PATH.format(file_name=file_name)
with open(json_path) as f:
return json.load(f)
@pytest.fixture(scope="module")
def radar():
radar = RadarClient(secret_key="sk_test_123", pub_key="pk_test_123")
return radar
@pytest.fixture(scope="module")
def geofence_json():
return TestHelpers.load_mock_data("geofence.json")
@pytest.fixture(scope="module")
def user_json():
return TestHelpers.load_mock_data("user.json")
@pytest.fixture(scope="module")
def event_json():
return TestHelpers.load_mock_data("event.json")
@pytest.fixture(scope="module")
def context_json():
return TestHelpers.load_mock_data("context.json")
| true | true |
1c2e403be24638bc95e9583ee92456a7ed4bf692 | 487 | py | Python | src/CELERY/wsgi.py | terean-dspd/django-celery-celerybeat-ubuntu-deamon-example | 162a8d50ba03146137225d029f6102efcf53aaf2 | [
"MIT"
] | 1 | 2018-02-03T18:24:48.000Z | 2018-02-03T18:24:48.000Z | src/CELERY/wsgi.py | terean-dspd/django-celery-celerybeat-ubuntu-deamon-example | 162a8d50ba03146137225d029f6102efcf53aaf2 | [
"MIT"
] | null | null | null | src/CELERY/wsgi.py | terean-dspd/django-celery-celerybeat-ubuntu-deamon-example | 162a8d50ba03146137225d029f6102efcf53aaf2 | [
"MIT"
] | null | null | null | """
WSGI config for CELERY project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/
"""
import os
import sys
path = '/home/dennis/myproject/src'
if path not in sys.path:
sys.path.append(path)
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CELERY.settings")
application = get_wsgi_application()
| 23.190476 | 78 | 0.770021 |
import os
import sys
path = '/home/dennis/myproject/src'
if path not in sys.path:
sys.path.append(path)
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CELERY.settings")
application = get_wsgi_application()
| true | true |
1c2e405d8358df0c72f1ce7fb8b607ea11f4d86b | 747 | py | Python | src/profiles/migrations/0008_document.py | MisaelMvM/bookAnalytics-ACC-Project | 954eb47f19c5fd83abbc46a6224dc588dbd20887 | [
"MIT"
] | null | null | null | src/profiles/migrations/0008_document.py | MisaelMvM/bookAnalytics-ACC-Project | 954eb47f19c5fd83abbc46a6224dc588dbd20887 | [
"MIT"
] | null | null | null | src/profiles/migrations/0008_document.py | MisaelMvM/bookAnalytics-ACC-Project | 954eb47f19c5fd83abbc46a6224dc588dbd20887 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-05-14 20:33
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('profiles', '0007_auto_20170513_2020'),
]
operations = [
migrations.CreateModel(
name='Document',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('description', models.CharField(blank=True, max_length=255)),
('document', models.FileField(upload_to='documents/')),
('uploaded_at', models.DateTimeField(auto_now_add=True)),
],
),
]
| 29.88 | 114 | 0.603748 |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('profiles', '0007_auto_20170513_2020'),
]
operations = [
migrations.CreateModel(
name='Document',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('description', models.CharField(blank=True, max_length=255)),
('document', models.FileField(upload_to='documents/')),
('uploaded_at', models.DateTimeField(auto_now_add=True)),
],
),
]
| true | true |
1c2e40e328bf407c26f76e9787a116626dbf5a00 | 932 | py | Python | docs/build/html/xas/xas_ft-5.py | marcoalsina/araucaria | 78039106ae27d3fdef9265503c33f33992199d8e | [
"BSD-2-Clause"
] | 8 | 2021-07-11T22:54:21.000Z | 2022-02-16T20:22:25.000Z | docs/build/html/xas/xas_ft-5.py | marcoalsina/araucaria | 78039106ae27d3fdef9265503c33f33992199d8e | [
"BSD-2-Clause"
] | null | null | null | docs/build/html/xas/xas_ft-5.py | marcoalsina/araucaria | 78039106ae27d3fdef9265503c33f33992199d8e | [
"BSD-2-Clause"
] | null | null | null | from numpy import arange, sin, pi
from scipy.fftpack import fftfreq
from araucaria.xas import ftwindow, xftf_kwin, xftr_kwin
nfft = 2048 # number of points for FFT
ks = 0.05 # delta k (angstrom^-1)
f1 = 0.5 # freq1 (angstrom)
k = arange(0, 10, ks)
wink = ftwindow(k, x_range=(0,10), dx1=0.5, win='sine')
chi = 0.5*sin(2*pi*k*f1)
chir = xftf_kwin(wink*chi, nfft=nfft, kstep=ks)
freq = fftfreq(nfft, ks)[:nfft//2]
chiq = xftr_kwin(chir, nfft=nfft, kstep=ks)[:len(k)]
print(chiq.dtype)
# complex128
# plotting reverse FFT signal
import matplotlib.pyplot as plt
from araucaria.plot import fig_xas_template
fig, ax = fig_xas_template(panels='re', fig_pars={'kweight':0})
line = ax[0].plot(freq, abs(chir))
xlim = ax[0].set_xlim(0,2)
xlab = ax[0].set_xlabel('$R/\pi$ [$\AA$]')
line = ax[1].plot(k, chiq)
text = ax[1].set_xlabel(r'$q(\AA^{-1})$')
text = ax[1].set_ylabel(r'$\chi(q)$')
fig.tight_layout()
plt.show(block=False)
| 33.285714 | 63 | 0.680258 | from numpy import arange, sin, pi
from scipy.fftpack import fftfreq
from araucaria.xas import ftwindow, xftf_kwin, xftr_kwin
nfft = 2048
ks = 0.05
f1 = 0.5
k = arange(0, 10, ks)
wink = ftwindow(k, x_range=(0,10), dx1=0.5, win='sine')
chi = 0.5*sin(2*pi*k*f1)
chir = xftf_kwin(wink*chi, nfft=nfft, kstep=ks)
freq = fftfreq(nfft, ks)[:nfft//2]
chiq = xftr_kwin(chir, nfft=nfft, kstep=ks)[:len(k)]
print(chiq.dtype)
import matplotlib.pyplot as plt
from araucaria.plot import fig_xas_template
fig, ax = fig_xas_template(panels='re', fig_pars={'kweight':0})
line = ax[0].plot(freq, abs(chir))
xlim = ax[0].set_xlim(0,2)
xlab = ax[0].set_xlabel('$R/\pi$ [$\AA$]')
line = ax[1].plot(k, chiq)
text = ax[1].set_xlabel(r'$q(\AA^{-1})$')
text = ax[1].set_ylabel(r'$\chi(q)$')
fig.tight_layout()
plt.show(block=False)
| true | true |
1c2e40f354a326634308047ef393dea19c9186a2 | 7,291 | py | Python | kolibri/core/analytics/measurements.py | priyanka-choubey/kolibri | 4070dc158634ab47c6e127768f0aed7548c0a182 | [
"MIT"
] | 2 | 2021-05-13T10:20:46.000Z | 2021-11-15T12:31:03.000Z | kolibri/core/analytics/measurements.py | priyanka-choubey/kolibri | 4070dc158634ab47c6e127768f0aed7548c0a182 | [
"MIT"
] | 3 | 2021-03-10T08:57:45.000Z | 2021-09-02T07:03:34.000Z | kolibri/core/analytics/measurements.py | priyanka-choubey/kolibri | 4070dc158634ab47c6e127768f0aed7548c0a182 | [
"MIT"
] | 1 | 2019-12-04T12:26:16.000Z | 2019-12-04T12:26:16.000Z | import time
from collections import namedtuple
from datetime import timedelta
import requests
from django.contrib.sessions.models import Session
from django.db import connection
from django.db.models import Count
from django.db.models import Sum
from django.db.utils import OperationalError
from django.utils import timezone
from kolibri.core.analytics import SUPPORTED_OS
from kolibri.core.content.models import ChannelMetadata
from kolibri.core.logger.models import ContentSessionLog
from kolibri.core.logger.models import UserSessionLog
from kolibri.utils.server import NotRunning
from kolibri.utils.server import PID_FILE
try:
import kolibri.utils.pskolibri as psutil
except NotImplementedError:
# This module can't work on this OS
psutil = None
def get_db_info():
"""
Returns information about the sessions and users the current
Kolibri server has in use
"""
# Users information
active_sessions = "unknown"
active_users = active_users_minute = None
try:
connection.ensure_connection()
# Sessions active in the last 10 minutes (includes guest accesses):
active_sessions = str(
Session.objects.filter(expire_date__gte=timezone.now()).count()
)
last_ten_minutes = timezone.now() - timedelta(minutes=10)
last_minute = timezone.now() - timedelta(minutes=1)
# Active logged users:
active_users = str(
UserSessionLog.objects.filter(
last_interaction_timestamp__gte=last_ten_minutes
).count()
)
# Logged users with activity in the last minute:
active_users_minute = str(
UserSessionLog.objects.filter(
last_interaction_timestamp__gte=last_minute
).count()
)
except OperationalError:
print("Database unavailable, impossible to retrieve users and sessions info")
return (active_sessions, active_users, active_users_minute)
def get_channels_usage_info():
"""
Scan the channels Kolibri has installed, getting information on how many times
their resources have been accessed and how long they have been used
:returns: List containing namedtuples, with each channel: id, name, accesses and time spent
"""
channels_info = []
ChannelsInfo = namedtuple("ChannelsInfo", "id name accesses time_spent")
try:
connection.ensure_connection()
channels = ChannelMetadata.objects.values("id", "name")
channel_stats = ContentSessionLog.objects.values("channel_id").annotate(
time_spent=Sum("time_spent"), total=Count("channel_id")
)
for channel in channels:
stats = channel_stats.filter(channel_id=channel["id"])
if stats:
channels_info.append(
ChannelsInfo(
id=channel["id"],
name=channel["name"],
accesses=str(stats[0]["total"]),
time_spent="{:.2f} s".format(stats[0]["time_spent"]),
)
)
else:
channels_info.append(
ChannelsInfo(
id=channel["id"],
name=channel["name"],
accesses="0",
time_spent="0.00 s",
)
)
except OperationalError:
print("Database unavailable, impossible to retrieve channels usage info")
return channels_info
def get_requests_info():
"""
Returns timing information on some Kolibri pages that can be hit without credentials
:returns: tuple of strings containing time in seconds when requesting
- Kolibri homepage
- Kolibri recommended channels
- Kolibri channels list
"""
def format_url(url, base_url):
formatted = "{base_url}{url}&contentCacheKey={cache}".format(
base_url=base_url, url=url, cache=time.time()
)
return formatted
_, port = get_kolibri_process_info()
if port:
base_url = "http://localhost:{}".format(port)
homepage_time = "{:.2f} s".format(
requests.get(base_url).elapsed.total_seconds()
)
recommended_url = format_url(
"/api/content/contentnode_slim/popular/?user_kind=learner", base_url
)
recommended_time = "{:.2f} s".format(
requests.get(recommended_url).elapsed.total_seconds()
)
channels_url = format_url("/api/content/channel/?available=true", base_url)
channels_time = "{:.2f} s".format(
requests.get(channels_url).elapsed.total_seconds()
)
else:
homepage_time = recommended_time = channels_time = None
return (homepage_time, recommended_time, channels_time)
def get_machine_info():
"""
Gets information on the memory, cpu and processes in the server
:returns: tuple of strings containing cpu percentage, used memory, free memory and number of active processes
"""
if not SUPPORTED_OS:
return (None, None, None, None)
used_cpu = str(psutil.cpu_percent())
used_memory = str(psutil.virtual_memory().used / pow(2, 20)) # In Megabytes
total_memory = str(psutil.virtual_memory().total / pow(2, 20)) # In Megabytes
total_processes = str(len(psutil.pids()))
return (used_cpu, used_memory, total_memory, total_processes)
def get_kolibri_process_info():
"""
Return information on the Kolibri process running in the machine
:returns: tuple of integers containing PID and TCP Port of
the running (if any) Kolibri server in this same machine
"""
kolibri_pid = None
kolibri_port = None
try:
with open(PID_FILE, "r") as f:
kolibri_pid = int(f.readline())
kolibri_port = int(f.readline())
except IOError:
pass # Kolibri PID file does not exist
except ValueError:
pass # corrupted Kolibri PID file
return (kolibri_pid, kolibri_port)
def get_kolibri_process_cmd():
"""
Retrieve from the OS the command line executed to run Kolibri server
:returns: tuple with command line and its arguments
"""
if not SUPPORTED_OS:
return None
kolibri_pid, _ = get_kolibri_process_info()
try:
kolibri_proc = psutil.Process(kolibri_pid)
except psutil.NoSuchProcess:
# Kolibri server is not running
raise NotRunning(0)
return kolibri_proc.cmdline()
def get_kolibri_use(development=False):
"""
Gets information on the memory and cpu usage of the current Kolibri process
:returns: tuple of strings containing cpu percentage and virtual memory used (in Mb)
"""
if not SUPPORTED_OS:
return (None, None)
kolibri_mem = kolibri_cpu = "None"
kolibri_pid, _ = get_kolibri_process_info()
if kolibri_pid:
try:
kolibri_proc = psutil.Process(kolibri_pid)
kolibri_mem = str(kolibri_proc.memory_info().rss / pow(2, 20))
kolibri_cpu = str(kolibri_proc.cpu_percent())
except psutil.NoSuchProcess:
# Kolibri server is not running
raise NotRunning(0)
return (kolibri_cpu, kolibri_mem)
| 34.885167 | 113 | 0.645728 | import time
from collections import namedtuple
from datetime import timedelta
import requests
from django.contrib.sessions.models import Session
from django.db import connection
from django.db.models import Count
from django.db.models import Sum
from django.db.utils import OperationalError
from django.utils import timezone
from kolibri.core.analytics import SUPPORTED_OS
from kolibri.core.content.models import ChannelMetadata
from kolibri.core.logger.models import ContentSessionLog
from kolibri.core.logger.models import UserSessionLog
from kolibri.utils.server import NotRunning
from kolibri.utils.server import PID_FILE
try:
import kolibri.utils.pskolibri as psutil
except NotImplementedError:
psutil = None
def get_db_info():
# Users information
active_sessions = "unknown"
active_users = active_users_minute = None
try:
connection.ensure_connection()
# Sessions active in the last 10 minutes (includes guest accesses):
active_sessions = str(
Session.objects.filter(expire_date__gte=timezone.now()).count()
)
last_ten_minutes = timezone.now() - timedelta(minutes=10)
last_minute = timezone.now() - timedelta(minutes=1)
# Active logged users:
active_users = str(
UserSessionLog.objects.filter(
last_interaction_timestamp__gte=last_ten_minutes
).count()
)
# Logged users with activity in the last minute:
active_users_minute = str(
UserSessionLog.objects.filter(
last_interaction_timestamp__gte=last_minute
).count()
)
except OperationalError:
print("Database unavailable, impossible to retrieve users and sessions info")
return (active_sessions, active_users, active_users_minute)
def get_channels_usage_info():
channels_info = []
ChannelsInfo = namedtuple("ChannelsInfo", "id name accesses time_spent")
try:
connection.ensure_connection()
channels = ChannelMetadata.objects.values("id", "name")
channel_stats = ContentSessionLog.objects.values("channel_id").annotate(
time_spent=Sum("time_spent"), total=Count("channel_id")
)
for channel in channels:
stats = channel_stats.filter(channel_id=channel["id"])
if stats:
channels_info.append(
ChannelsInfo(
id=channel["id"],
name=channel["name"],
accesses=str(stats[0]["total"]),
time_spent="{:.2f} s".format(stats[0]["time_spent"]),
)
)
else:
channels_info.append(
ChannelsInfo(
id=channel["id"],
name=channel["name"],
accesses="0",
time_spent="0.00 s",
)
)
except OperationalError:
print("Database unavailable, impossible to retrieve channels usage info")
return channels_info
def get_requests_info():
def format_url(url, base_url):
formatted = "{base_url}{url}&contentCacheKey={cache}".format(
base_url=base_url, url=url, cache=time.time()
)
return formatted
_, port = get_kolibri_process_info()
if port:
base_url = "http://localhost:{}".format(port)
homepage_time = "{:.2f} s".format(
requests.get(base_url).elapsed.total_seconds()
)
recommended_url = format_url(
"/api/content/contentnode_slim/popular/?user_kind=learner", base_url
)
recommended_time = "{:.2f} s".format(
requests.get(recommended_url).elapsed.total_seconds()
)
channels_url = format_url("/api/content/channel/?available=true", base_url)
channels_time = "{:.2f} s".format(
requests.get(channels_url).elapsed.total_seconds()
)
else:
homepage_time = recommended_time = channels_time = None
return (homepage_time, recommended_time, channels_time)
def get_machine_info():
if not SUPPORTED_OS:
return (None, None, None, None)
used_cpu = str(psutil.cpu_percent())
used_memory = str(psutil.virtual_memory().used / pow(2, 20)) # In Megabytes
total_memory = str(psutil.virtual_memory().total / pow(2, 20)) # In Megabytes
total_processes = str(len(psutil.pids()))
return (used_cpu, used_memory, total_memory, total_processes)
def get_kolibri_process_info():
kolibri_pid = None
kolibri_port = None
try:
with open(PID_FILE, "r") as f:
kolibri_pid = int(f.readline())
kolibri_port = int(f.readline())
except IOError:
pass # Kolibri PID file does not exist
except ValueError:
pass # corrupted Kolibri PID file
return (kolibri_pid, kolibri_port)
def get_kolibri_process_cmd():
if not SUPPORTED_OS:
return None
kolibri_pid, _ = get_kolibri_process_info()
try:
kolibri_proc = psutil.Process(kolibri_pid)
except psutil.NoSuchProcess:
# Kolibri server is not running
raise NotRunning(0)
return kolibri_proc.cmdline()
def get_kolibri_use(development=False):
if not SUPPORTED_OS:
return (None, None)
kolibri_mem = kolibri_cpu = "None"
kolibri_pid, _ = get_kolibri_process_info()
if kolibri_pid:
try:
kolibri_proc = psutil.Process(kolibri_pid)
kolibri_mem = str(kolibri_proc.memory_info().rss / pow(2, 20))
kolibri_cpu = str(kolibri_proc.cpu_percent())
except psutil.NoSuchProcess:
# Kolibri server is not running
raise NotRunning(0)
return (kolibri_cpu, kolibri_mem)
| true | true |
1c2e4108dea4f61e84c54e7da24a415af6455d96 | 15,581 | py | Python | model/metric.py | bhadreshpsavani/TAPER-EHR | ab938749756fcaaef52a7002a074421f483e3562 | [
"MIT"
] | 12 | 2020-04-10T02:24:20.000Z | 2021-11-09T22:52:24.000Z | model/metric.py | bhadreshpsavani/TAPER-EHR | ab938749756fcaaef52a7002a074421f483e3562 | [
"MIT"
] | 7 | 2020-05-03T10:03:29.000Z | 2022-02-09T23:38:21.000Z | model/metric.py | bhadreshpsavani/TAPER-EHR | ab938749756fcaaef52a7002a074421f483e3562 | [
"MIT"
] | 10 | 2020-06-14T09:37:35.000Z | 2022-02-04T22:21:16.000Z | import torch
from sklearn.metrics import roc_auc_score, average_precision_score, roc_curve, auc, roc_curve, precision_recall_curve
def roc_auc(output,target):
# temporary place holders..
# these will be run at the end of the epoch once all probabilities are obtained..
# refer to pr_auc_1
#output = output.detach().cpu().numpy()
#target = target.cpu().numpy()
#if (torch.sum(target) == 0 or torch.sum(target) == len(target)):
# return 1.0
#return roc_auc_score(target, output)
return 1.0
def pr_auc(output, target):
# temporary place holders.
# these will be run at the end of the epoch once all probabilities are obtained..
# refer to pr_auc_1
#output = output.detach().cpu().numpy()
#target = target.cpu().numpy()
#if (torch.sum(target) == 0 or torch.sum(target) == len(target)):
# return 1.0
#return average_precision_score(target, output)
return 1.0
def roc_auc_1(output,target):
# evaluate after eac
fpr, tpr, thresholds = roc_curve(target, output)
area = auc(fpr, tpr)
return area #roc_auc_score(target, output)
def pr_auc_1(output, target):
precision, recall, _ = precision_recall_curve(target, output)
area = auc(recall, precision)
return area #average_precision_score(target, output)
def accuracy(output, target):
with torch.no_grad():
output = torch.squeeze(output)
target = torch.squeeze(target)
pred = torch.argmax(output, dim=1)
assert pred.shape[0] == len(target)
correct = 0
correct += torch.sum(pred == target).item()
return correct / len(target)
def accuracy2(output, target, t=0):
with torch.no_grad():
if (len(target.shape) == 1):
target = torch.unsqueeze(target, 1)
if (len(output.shape) == 1):
output = torch.unsqueeze(output, 1)
pred = output >= 0.5#torch.argmax(output, dim=1)
pred = pred.long()
assert pred.shape[0] == len(target)
correct = 0
correct += torch.sum(pred == target).item()
return correct / len(target)
def my_metric2(output, target, k=3):
with torch.no_grad():
pred = torch.topk(output, k, dim=1)[1]
assert pred.shape[0] == len(target)
correct = 0
for i in range(k):
correct += torch.sum(pred[:, i] == target).item()
return correct / len(target)
def recall_k(output, target, mask, k=10, window=1):
bsz = output.shape[0]
idx = torch.arange(0, bsz, device=output.device)
mask = mask.squeeze()
for i in range(window):
mi = mask[i + 1:] * mask[:-i - 1]
mi = torch.nn.functional.pad(mi, (1 + i, 1 + i))
target_mask = torch.masked_select(idx, tm)
input_mask = torch.masked_select(idx, im)
#ii = ii.long()
output = output[input_mask, :]
output = output.float()
target = target[target_mask, :]
target = target.float()
_, tk = torch.topk(output, k)
tt = torch.gather(target, 1, tk)
r = torch.mean(torch.sum(tt, dim=1) / (torch.sum(target, dim=1) + 1e-7))
if r != r:
r = 0
return r
def recall_10_diag(output, target, mask, k=10, window=1):
bsz = output.shape[0]
idx = torch.arange(0, bsz, device=output.device)
mask = mask.squeeze()
output = output[:, :232]
target = target[:, :232]
for i in range(window):
mi = mask[i + 1:] * mask[:-i - 1]
mi = torch.nn.functional.pad(mi, (1 + i, 1 + i))
tm = mi[:-i - 1]
im = mi[i + 1:]
target_mask = torch.masked_select(idx, tm)
input_mask = torch.masked_select(idx, im)
#ii = ii.long()
output = output[input_mask, :]
output = output.float()
target = target[target_mask, :]
target = target.float()
_, tk = torch.topk(output, k)
tt = torch.gather(target, 1, tk)
r = torch.mean(torch.sum(tt, dim=1) / (torch.sum(target, dim=1) + 1e-7))
if r != r:
r = 0
return r
def recall_20_diag(output, target, mask, k=20, window=1):
bsz = output.shape[0]
idx = torch.arange(0, bsz, device=output.device)
mask = mask.squeeze()
output = output[:, :232]
target = target[:, :232]
for i in range(window):
mi = mask[i + 1:] * mask[:-i - 1]
mi = torch.nn.functional.pad(mi, (1 + i, 1 + i))
tm = mi[:-i - 1]
im = mi[i + 1:]
target_mask = torch.masked_select(idx, tm)
input_mask = torch.masked_select(idx, im)
#ii = ii.long()
output = output[input_mask, :]
output = output.float()
target = target[target_mask, :]
target = target.float()
_, tk = torch.topk(output, k)
tt = torch.gather(target, 1, tk)
r = torch.mean(torch.sum(tt, dim=1) / (torch.sum(target, dim=1) + 1e-7))
if r != r:
r = 0
return r
def recall_30_diag(output, target, mask, k=30, window=1):
bsz = output.shape[0]
idx = torch.arange(0, bsz, device=output.device)
mask = mask.squeeze()
output = output[:, :232]
target = target[:, :232]
for i in range(window):
mi = mask[i + 1:] * mask[:-i - 1]
mi = torch.nn.functional.pad(mi, (1 + i, 1 + i))
tm = mi[:-i - 1]
im = mi[i + 1:]
target_mask = torch.masked_select(idx, tm)
input_mask = torch.masked_select(idx, im)
#ii = ii.long()
output = output[input_mask, :]
output = output.float()
target = target[target_mask, :]
target = target.float()
_, tk = torch.topk(output, k)
tt = torch.gather(target, 1, tk)
r = torch.mean(torch.sum(tt, dim=1) / (torch.sum(target, dim=1) + 1e-7))
if r != r:
r = 0
return r
def recall_40_diag(output, target, mask, k=40, window=1):
bsz = output.shape[0]
idx = torch.arange(0, bsz, device=output.device)
mask = mask.squeeze()
output = output[:, :232]
target = target[:, :232]
for i in range(window):
mi = mask[i + 1:] * mask[:-i - 1]
mi = torch.nn.functional.pad(mi, (1 + i, 1 + i))
tm = mi[:-i - 1]
im = mi[i + 1:]
target_mask = torch.masked_select(idx, tm)
input_mask = torch.masked_select(idx, im)
#ii = ii.long()
output = output[input_mask, :]
output = output.float()
target = target[target_mask, :]
target = target.float()
_, tk = torch.topk(output, k)
tt = torch.gather(target, 1, tk)
r = torch.mean(torch.sum(tt, dim=1) / (torch.sum(target, dim=1) + 1e-7))
if r != r:
r = 0
return r
def recall_10_proc(output, target, mask, k=10, window=1):
bsz = output.shape[0]
idx = torch.arange(0, bsz, device=output.device)
mask = mask.squeeze()
output = output[:, 232:]
target = target[:, 232:]
for i in range(window):
mi = mask[i + 1:] * mask[:-i - 1]
mi = torch.nn.functional.pad(mi, (1 + i, 1 + i))
tm = mi[:-i - 1]
im = mi[i + 1:]
target_mask = torch.masked_select(idx, tm)
input_mask = torch.masked_select(idx, im)
#ii = ii.long()
output = output[input_mask, :]
output = output.float()
target = target[target_mask, :]
target = target.float()
_, tk = torch.topk(output, k)
tt = torch.gather(target, 1, tk)
r = torch.mean(torch.sum(tt, dim=1) / (torch.sum(target, dim=1) + 1e-7))
if r != r:
r = 0
return r
def recall_20_proc(output, target, mask, k=20, window=1):
bsz = output.shape[0]
idx = torch.arange(0, bsz, device=output.device)
mask = mask.squeeze()
output = output[:, 232:]
target = target[:, 232:]
for i in range(window):
mi = mask[i + 1:] * mask[:-i - 1]
mi = torch.nn.functional.pad(mi, (1 + i, 1 + i))
tm = mi[:-i - 1]
im = mi[i + 1:]
target_mask = torch.masked_select(idx, tm)
input_mask = torch.masked_select(idx, im)
#ii = ii.long()
output = output[input_mask, :]
output = output.float()
target = target[target_mask, :]
target = target.float()
_, tk = torch.topk(output, k)
tt = torch.gather(target, 1, tk)
r = torch.mean(torch.sum(tt, dim=1) / (torch.sum(target, dim=1) + 1e-7))
if r != r:
r = 0
return r
def recall_30_proc(output, target, mask, k=30, window=1):
bsz = output.shape[0]
idx = torch.arange(0, bsz, device=output.device)
mask = mask.squeeze()
output = output[:, 232:]
target = target[:, 232:]
for i in range(window):
mi = mask[i + 1:] * mask[:-i - 1]
mi = torch.nn.functional.pad(mi, (1 + i, 1 + i))
tm = mi[:-i - 1]
im = mi[i + 1:]
target_mask = torch.masked_select(idx, tm)
input_mask = torch.masked_select(idx, im)
#ii = ii.long()
output = output[input_mask, :]
output = output.float()
target = target[target_mask, :]
target = target.float()
_, tk = torch.topk(output, k)
tt = torch.gather(target, 1, tk)
r = torch.mean(torch.sum(tt, dim=1) / (torch.sum(target, dim=1) + 1e-7))
if r != r:
r = 0
return r
def recall_40_proc(output, target, mask, k=40, window=1):
bsz = output.shape[0]
idx = torch.arange(0, bsz, device=output.device)
mask = mask.squeeze()
output = output[:, 232:]
target = target[:, 232:]
for i in range(window):
mi = mask[i + 1:] * mask[:-i - 1]
mi = torch.nn.functional.pad(mi, (1 + i, 1 + i))
tm = mi[:-i - 1]
im = mi[i + 1:]
target_mask = torch.masked_select(idx, tm)
input_mask = torch.masked_select(idx, im)
#ii = ii.long()
output = output[input_mask, :]
output = output.float()
target = target[target_mask, :]
target = target.float()
_, tk = torch.topk(output, k)
tt = torch.gather(target, 1, tk)
r = torch.mean(torch.sum(tt, dim=1) / (torch.sum(target, dim=1) + 1e-7))
if r != r:
r = 0
return r
def recall_10(output, target, mask, k=10, window=1):
bsz = output.shape[0]
idx = torch.arange(0, bsz, device=output.device)
mask = mask.squeeze()
for i in range(window):
mi = mask[i + 1:] * mask[:-i - 1]
mi = torch.nn.functional.pad(mi, (1 + i, 1 + i))
tm = mi[:-i - 1]
im = mi[i + 1:]
target_mask = torch.masked_select(idx, tm)
input_mask = torch.masked_select(idx, im)
#ii = ii.long()
output = output[input_mask, :]
output = output.float()
target = target[target_mask, :]
target = target.float()
_, tk = torch.topk(output, k)
tt = torch.gather(target, 1, tk)
r = torch.mean(torch.sum(tt, dim=1) / (torch.sum(target, dim=1) + 1e-7))
if r != r:
r = 0
return r
def recall_20(output, target, mask, k=20, window=1):
bsz = output.shape[0]
idx = torch.arange(0, bsz, device=output.device)
mask = mask.squeeze()
for i in range(window):
mi = mask[i + 1:] * mask[:-i - 1]
mi = torch.nn.functional.pad(mi, (1 + i, 1 + i))
tm = mi[:-i - 1]
im = mi[i + 1:]
target_mask = torch.masked_select(idx, tm)
input_mask = torch.masked_select(idx, im)
#ii = ii.long()
output = output[input_mask, :]
output = output.float()
target = target[target_mask, :]
target = target.float()
_, tk = torch.topk(output, k)
tt = torch.gather(target, 1, tk)
r = torch.mean(torch.sum(tt, dim=1) / (torch.sum(target, dim=1) + 1e-7))
if r != r:
r = 0
return r
def recall_30(output, target, mask, k=30, window=1):
bsz = output.shape[0]
idx = torch.arange(0, bsz, device=output.device)
mask = mask.squeeze()
for i in range(window):
mi = mask[i + 1:] * mask[:-i - 1]
mi = torch.nn.functional.pad(mi, (1 + i, 1 + i))
tm = mi[:-i - 1]
im = mi[i + 1:]
target_mask = torch.masked_select(idx, tm)
input_mask = torch.masked_select(idx, im)
#ii = ii.long()
output = output[input_mask, :]
output = output.float()
target = target[target_mask, :]
target = target.float()
_, tk = torch.topk(output, k)
tt = torch.gather(target, 1, tk)
r = torch.mean(torch.sum(tt, dim=1) / (torch.sum(target, dim=1) + 1e-7))
if r != r:
r = 0
return r
def recall_40(output, target, mask, k=40, window=1):
bsz = output.shape[0]
idx = torch.arange(0, bsz, device=output.device)
mask = mask.squeeze()
for i in range(window):
mi = mask[i + 1:] * mask[:-i - 1]
mi = torch.nn.functional.pad(mi, (1 + i, 1 + i))
tm = mi[:-i - 1]
im = mi[i + 1:]
target_mask = torch.masked_select(idx, tm)
input_mask = torch.masked_select(idx, im)
#ii = ii.long()
output = output[input_mask, :]
output = output.float()
target = target[target_mask, :]
target = target.float()
_, tk = torch.topk(output, k)
tt = torch.gather(target, 1, tk)
r = torch.mean(torch.sum(tt, dim=1) / (torch.sum(target, dim=1) + 1e-7))
if r != r:
r = 0
return r
def recall_50(output, target, mask, k=50, window=1):
bsz = output.shape[0]
idx = torch.arange(0, bsz, device=output.device)
mask = mask.squeeze()
for i in range(window):
mi = mask[i + 1:] * mask[:-i - 1]
mi = torch.nn.functional.pad(mi, (1 + i, 1 + i))
tm = mi[:-i - 1]
im = mi[i + 1:]
target_mask = torch.masked_select(idx, tm)
input_mask = torch.masked_select(idx, im)
#ii = ii.long()
output = output[input_mask, :]
output = output.float()
target = target[target_mask, :]
target = target.float()
_, tk = torch.topk(output, k)
tt = torch.gather(target, 1, tk)
r = torch.mean(torch.sum(tt, dim=1) / (torch.sum(target, dim=1) + 1e-7))
if r != r:
r = 0
return r
def specificity(output, target, t=0.5):
with torch.no_grad():
preds = output > t#torch.argmax(output, dim=1)
preds = preds.long()
num_true_0s = torch.sum((target == 0) & (preds == target), dtype=torch.float).item()
num_false_1s = torch.sum((target == 0) & (preds != target), dtype=torch.float).item()
if (num_false_1s == 0):
return 1
s = num_true_0s / (num_true_0s + num_false_1s)
if (s != s):
s = 1
return s
def sensitivity(output, target, t=0.5):
with torch.no_grad():
preds = output > t#torch.argmax(output, dim=1)
preds = preds.long()
num_true_1s = torch.sum((preds == target) & (preds == 1), dtype=torch.float)
num_false_1s = torch.sum((preds != target) & (preds == 1), dtype=torch.float)
s = num_true_1s / (num_true_1s + num_false_1s)
if (s != s):
s = 1
return s
def precision(output, target, t=0.5):
with torch.no_grad():
preds = output > t
preds = preds.long()
num_true_1s = torch.sum((preds == target) & (preds == 1), dtype=torch.float)
num_false_0s = torch.sum((preds != target) & (preds == 0), dtype=torch.float)
s = num_true_1s / (num_true_1s + num_false_0s)
if (s != s):
s = 1
return s
| 30.611002 | 117 | 0.546627 | import torch
from sklearn.metrics import roc_auc_score, average_precision_score, roc_curve, auc, roc_curve, precision_recall_curve
def roc_auc(output,target):
return 1.0
def pr_auc(output, target):
return 1.0
def roc_auc_1(output,target):
fpr, tpr, thresholds = roc_curve(target, output)
area = auc(fpr, tpr)
return area
def pr_auc_1(output, target):
precision, recall, _ = precision_recall_curve(target, output)
area = auc(recall, precision)
return area
def accuracy(output, target):
with torch.no_grad():
output = torch.squeeze(output)
target = torch.squeeze(target)
pred = torch.argmax(output, dim=1)
assert pred.shape[0] == len(target)
correct = 0
correct += torch.sum(pred == target).item()
return correct / len(target)
def accuracy2(output, target, t=0):
with torch.no_grad():
if (len(target.shape) == 1):
target = torch.unsqueeze(target, 1)
if (len(output.shape) == 1):
output = torch.unsqueeze(output, 1)
pred = output >= 0.5
pred = pred.long()
assert pred.shape[0] == len(target)
correct = 0
correct += torch.sum(pred == target).item()
return correct / len(target)
def my_metric2(output, target, k=3):
with torch.no_grad():
pred = torch.topk(output, k, dim=1)[1]
assert pred.shape[0] == len(target)
correct = 0
for i in range(k):
correct += torch.sum(pred[:, i] == target).item()
return correct / len(target)
def recall_k(output, target, mask, k=10, window=1):
bsz = output.shape[0]
idx = torch.arange(0, bsz, device=output.device)
mask = mask.squeeze()
for i in range(window):
mi = mask[i + 1:] * mask[:-i - 1]
mi = torch.nn.functional.pad(mi, (1 + i, 1 + i))
target_mask = torch.masked_select(idx, tm)
input_mask = torch.masked_select(idx, im)
output = output[input_mask, :]
output = output.float()
target = target[target_mask, :]
target = target.float()
_, tk = torch.topk(output, k)
tt = torch.gather(target, 1, tk)
r = torch.mean(torch.sum(tt, dim=1) / (torch.sum(target, dim=1) + 1e-7))
if r != r:
r = 0
return r
def recall_10_diag(output, target, mask, k=10, window=1):
bsz = output.shape[0]
idx = torch.arange(0, bsz, device=output.device)
mask = mask.squeeze()
output = output[:, :232]
target = target[:, :232]
for i in range(window):
mi = mask[i + 1:] * mask[:-i - 1]
mi = torch.nn.functional.pad(mi, (1 + i, 1 + i))
tm = mi[:-i - 1]
im = mi[i + 1:]
target_mask = torch.masked_select(idx, tm)
input_mask = torch.masked_select(idx, im)
output = output[input_mask, :]
output = output.float()
target = target[target_mask, :]
target = target.float()
_, tk = torch.topk(output, k)
tt = torch.gather(target, 1, tk)
r = torch.mean(torch.sum(tt, dim=1) / (torch.sum(target, dim=1) + 1e-7))
if r != r:
r = 0
return r
def recall_20_diag(output, target, mask, k=20, window=1):
bsz = output.shape[0]
idx = torch.arange(0, bsz, device=output.device)
mask = mask.squeeze()
output = output[:, :232]
target = target[:, :232]
for i in range(window):
mi = mask[i + 1:] * mask[:-i - 1]
mi = torch.nn.functional.pad(mi, (1 + i, 1 + i))
tm = mi[:-i - 1]
im = mi[i + 1:]
target_mask = torch.masked_select(idx, tm)
input_mask = torch.masked_select(idx, im)
output = output[input_mask, :]
output = output.float()
target = target[target_mask, :]
target = target.float()
_, tk = torch.topk(output, k)
tt = torch.gather(target, 1, tk)
r = torch.mean(torch.sum(tt, dim=1) / (torch.sum(target, dim=1) + 1e-7))
if r != r:
r = 0
return r
def recall_30_diag(output, target, mask, k=30, window=1):
bsz = output.shape[0]
idx = torch.arange(0, bsz, device=output.device)
mask = mask.squeeze()
output = output[:, :232]
target = target[:, :232]
for i in range(window):
mi = mask[i + 1:] * mask[:-i - 1]
mi = torch.nn.functional.pad(mi, (1 + i, 1 + i))
tm = mi[:-i - 1]
im = mi[i + 1:]
target_mask = torch.masked_select(idx, tm)
input_mask = torch.masked_select(idx, im)
output = output[input_mask, :]
output = output.float()
target = target[target_mask, :]
target = target.float()
_, tk = torch.topk(output, k)
tt = torch.gather(target, 1, tk)
r = torch.mean(torch.sum(tt, dim=1) / (torch.sum(target, dim=1) + 1e-7))
if r != r:
r = 0
return r
def recall_40_diag(output, target, mask, k=40, window=1):
bsz = output.shape[0]
idx = torch.arange(0, bsz, device=output.device)
mask = mask.squeeze()
output = output[:, :232]
target = target[:, :232]
for i in range(window):
mi = mask[i + 1:] * mask[:-i - 1]
mi = torch.nn.functional.pad(mi, (1 + i, 1 + i))
tm = mi[:-i - 1]
im = mi[i + 1:]
target_mask = torch.masked_select(idx, tm)
input_mask = torch.masked_select(idx, im)
output = output[input_mask, :]
output = output.float()
target = target[target_mask, :]
target = target.float()
_, tk = torch.topk(output, k)
tt = torch.gather(target, 1, tk)
r = torch.mean(torch.sum(tt, dim=1) / (torch.sum(target, dim=1) + 1e-7))
if r != r:
r = 0
return r
def recall_10_proc(output, target, mask, k=10, window=1):
bsz = output.shape[0]
idx = torch.arange(0, bsz, device=output.device)
mask = mask.squeeze()
output = output[:, 232:]
target = target[:, 232:]
for i in range(window):
mi = mask[i + 1:] * mask[:-i - 1]
mi = torch.nn.functional.pad(mi, (1 + i, 1 + i))
tm = mi[:-i - 1]
im = mi[i + 1:]
target_mask = torch.masked_select(idx, tm)
input_mask = torch.masked_select(idx, im)
output = output[input_mask, :]
output = output.float()
target = target[target_mask, :]
target = target.float()
_, tk = torch.topk(output, k)
tt = torch.gather(target, 1, tk)
r = torch.mean(torch.sum(tt, dim=1) / (torch.sum(target, dim=1) + 1e-7))
if r != r:
r = 0
return r
def recall_20_proc(output, target, mask, k=20, window=1):
bsz = output.shape[0]
idx = torch.arange(0, bsz, device=output.device)
mask = mask.squeeze()
output = output[:, 232:]
target = target[:, 232:]
for i in range(window):
mi = mask[i + 1:] * mask[:-i - 1]
mi = torch.nn.functional.pad(mi, (1 + i, 1 + i))
tm = mi[:-i - 1]
im = mi[i + 1:]
target_mask = torch.masked_select(idx, tm)
input_mask = torch.masked_select(idx, im)
output = output[input_mask, :]
output = output.float()
target = target[target_mask, :]
target = target.float()
_, tk = torch.topk(output, k)
tt = torch.gather(target, 1, tk)
r = torch.mean(torch.sum(tt, dim=1) / (torch.sum(target, dim=1) + 1e-7))
if r != r:
r = 0
return r
def recall_30_proc(output, target, mask, k=30, window=1):
bsz = output.shape[0]
idx = torch.arange(0, bsz, device=output.device)
mask = mask.squeeze()
output = output[:, 232:]
target = target[:, 232:]
for i in range(window):
mi = mask[i + 1:] * mask[:-i - 1]
mi = torch.nn.functional.pad(mi, (1 + i, 1 + i))
tm = mi[:-i - 1]
im = mi[i + 1:]
target_mask = torch.masked_select(idx, tm)
input_mask = torch.masked_select(idx, im)
output = output[input_mask, :]
output = output.float()
target = target[target_mask, :]
target = target.float()
_, tk = torch.topk(output, k)
tt = torch.gather(target, 1, tk)
r = torch.mean(torch.sum(tt, dim=1) / (torch.sum(target, dim=1) + 1e-7))
if r != r:
r = 0
return r
def recall_40_proc(output, target, mask, k=40, window=1):
bsz = output.shape[0]
idx = torch.arange(0, bsz, device=output.device)
mask = mask.squeeze()
output = output[:, 232:]
target = target[:, 232:]
for i in range(window):
mi = mask[i + 1:] * mask[:-i - 1]
mi = torch.nn.functional.pad(mi, (1 + i, 1 + i))
tm = mi[:-i - 1]
im = mi[i + 1:]
target_mask = torch.masked_select(idx, tm)
input_mask = torch.masked_select(idx, im)
output = output[input_mask, :]
output = output.float()
target = target[target_mask, :]
target = target.float()
_, tk = torch.topk(output, k)
tt = torch.gather(target, 1, tk)
r = torch.mean(torch.sum(tt, dim=1) / (torch.sum(target, dim=1) + 1e-7))
if r != r:
r = 0
return r
def recall_10(output, target, mask, k=10, window=1):
bsz = output.shape[0]
idx = torch.arange(0, bsz, device=output.device)
mask = mask.squeeze()
for i in range(window):
mi = mask[i + 1:] * mask[:-i - 1]
mi = torch.nn.functional.pad(mi, (1 + i, 1 + i))
tm = mi[:-i - 1]
im = mi[i + 1:]
target_mask = torch.masked_select(idx, tm)
input_mask = torch.masked_select(idx, im)
output = output[input_mask, :]
output = output.float()
target = target[target_mask, :]
target = target.float()
_, tk = torch.topk(output, k)
tt = torch.gather(target, 1, tk)
r = torch.mean(torch.sum(tt, dim=1) / (torch.sum(target, dim=1) + 1e-7))
if r != r:
r = 0
return r
def recall_20(output, target, mask, k=20, window=1):
bsz = output.shape[0]
idx = torch.arange(0, bsz, device=output.device)
mask = mask.squeeze()
for i in range(window):
mi = mask[i + 1:] * mask[:-i - 1]
mi = torch.nn.functional.pad(mi, (1 + i, 1 + i))
tm = mi[:-i - 1]
im = mi[i + 1:]
target_mask = torch.masked_select(idx, tm)
input_mask = torch.masked_select(idx, im)
output = output[input_mask, :]
output = output.float()
target = target[target_mask, :]
target = target.float()
_, tk = torch.topk(output, k)
tt = torch.gather(target, 1, tk)
r = torch.mean(torch.sum(tt, dim=1) / (torch.sum(target, dim=1) + 1e-7))
if r != r:
r = 0
return r
def recall_30(output, target, mask, k=30, window=1):
bsz = output.shape[0]
idx = torch.arange(0, bsz, device=output.device)
mask = mask.squeeze()
for i in range(window):
mi = mask[i + 1:] * mask[:-i - 1]
mi = torch.nn.functional.pad(mi, (1 + i, 1 + i))
tm = mi[:-i - 1]
im = mi[i + 1:]
target_mask = torch.masked_select(idx, tm)
input_mask = torch.masked_select(idx, im)
output = output[input_mask, :]
output = output.float()
target = target[target_mask, :]
target = target.float()
_, tk = torch.topk(output, k)
tt = torch.gather(target, 1, tk)
r = torch.mean(torch.sum(tt, dim=1) / (torch.sum(target, dim=1) + 1e-7))
if r != r:
r = 0
return r
def recall_40(output, target, mask, k=40, window=1):
bsz = output.shape[0]
idx = torch.arange(0, bsz, device=output.device)
mask = mask.squeeze()
for i in range(window):
mi = mask[i + 1:] * mask[:-i - 1]
mi = torch.nn.functional.pad(mi, (1 + i, 1 + i))
tm = mi[:-i - 1]
im = mi[i + 1:]
target_mask = torch.masked_select(idx, tm)
input_mask = torch.masked_select(idx, im)
output = output[input_mask, :]
output = output.float()
target = target[target_mask, :]
target = target.float()
_, tk = torch.topk(output, k)
tt = torch.gather(target, 1, tk)
r = torch.mean(torch.sum(tt, dim=1) / (torch.sum(target, dim=1) + 1e-7))
if r != r:
r = 0
return r
def recall_50(output, target, mask, k=50, window=1):
bsz = output.shape[0]
idx = torch.arange(0, bsz, device=output.device)
mask = mask.squeeze()
for i in range(window):
mi = mask[i + 1:] * mask[:-i - 1]
mi = torch.nn.functional.pad(mi, (1 + i, 1 + i))
tm = mi[:-i - 1]
im = mi[i + 1:]
target_mask = torch.masked_select(idx, tm)
input_mask = torch.masked_select(idx, im)
output = output[input_mask, :]
output = output.float()
target = target[target_mask, :]
target = target.float()
_, tk = torch.topk(output, k)
tt = torch.gather(target, 1, tk)
r = torch.mean(torch.sum(tt, dim=1) / (torch.sum(target, dim=1) + 1e-7))
if r != r:
r = 0
return r
def specificity(output, target, t=0.5):
with torch.no_grad():
preds = output > t
preds = preds.long()
num_true_0s = torch.sum((target == 0) & (preds == target), dtype=torch.float).item()
num_false_1s = torch.sum((target == 0) & (preds != target), dtype=torch.float).item()
if (num_false_1s == 0):
return 1
s = num_true_0s / (num_true_0s + num_false_1s)
if (s != s):
s = 1
return s
def sensitivity(output, target, t=0.5):
with torch.no_grad():
preds = output > t
preds = preds.long()
num_true_1s = torch.sum((preds == target) & (preds == 1), dtype=torch.float)
num_false_1s = torch.sum((preds != target) & (preds == 1), dtype=torch.float)
s = num_true_1s / (num_true_1s + num_false_1s)
if (s != s):
s = 1
return s
def precision(output, target, t=0.5):
with torch.no_grad():
preds = output > t
preds = preds.long()
num_true_1s = torch.sum((preds == target) & (preds == 1), dtype=torch.float)
num_false_0s = torch.sum((preds != target) & (preds == 0), dtype=torch.float)
s = num_true_1s / (num_true_1s + num_false_0s)
if (s != s):
s = 1
return s
| true | true |
1c2e41dd856bb7d1bb94896fc537c0a340c99cdb | 1,800 | py | Python | marrow/mailer/transport/ses.py | digiturtle/mailer | 3b718f415a4a955ba0fdb7e7ae135c0ab1f9d900 | [
"MIT"
] | 1 | 2019-02-13T12:40:30.000Z | 2019-02-13T12:40:30.000Z | marrow/mailer/transport/ses.py | digiturtle/mailer | 3b718f415a4a955ba0fdb7e7ae135c0ab1f9d900 | [
"MIT"
] | 1 | 2021-03-24T13:02:56.000Z | 2021-03-24T16:27:14.000Z | marrow/mailer/transport/ses.py | LexMachinaInc/mailer | 5b144797a412f4816ecc25f237a6ebc0737f6897 | [
"MIT"
] | 1 | 2018-03-29T19:11:45.000Z | 2018-03-29T19:11:45.000Z | # encoding: utf-8
try:
import boto.ses
from boto.ses import SESConnection
except ImportError:
raise ImportError("You must install the boto package to deliver mail via Amazon SES.")
__all__ = ['AmazonTransport']
log = __import__('logging').getLogger(__name__)
class AmazonTransport(object): # pragma: no cover
__slots__ = ('ephemeral', 'config', 'region', 'connection')
def __init__(self, config):
# Give our configuration aliases their proper names.
config['aws_access_key_id'] = config.pop('id')
config['aws_secret_access_key'] = config.pop('key')
self.region = config.pop('region', "us-east-1")
config.pop('use') #boto throws an error if we leave this in the next line
self.config = config # All other configuration directives are passed to connect_to_region.
self.connection = None
def startup(self):
self.connection = boto.ses.connect_to_region(self.region, **self.config)
def deliver(self, message):
try:
destinations = [r.encode(encoding='utf-8') for r in message.recipients]
response = self.connection.send_raw_email(str(message), message.author.encode(), destinations)
return (
response['SendRawEmailResponse']['SendRawEmailResult']['MessageId'],
response['SendRawEmailResponse']['ResponseMetadata']['RequestId']
)
except SESConnection.ResponseError:
raise # TODO: Raise appropriate internal exception.
# ['status', 'reason', 'body', 'request_id', 'error_code', 'error_message']
def shutdown(self):
if self.connection:
self.connection.close()
self.connection = None
| 34.615385 | 106 | 0.628333 |
try:
import boto.ses
from boto.ses import SESConnection
except ImportError:
raise ImportError("You must install the boto package to deliver mail via Amazon SES.")
__all__ = ['AmazonTransport']
log = __import__('logging').getLogger(__name__)
class AmazonTransport(object):
__slots__ = ('ephemeral', 'config', 'region', 'connection')
def __init__(self, config):
config['aws_access_key_id'] = config.pop('id')
config['aws_secret_access_key'] = config.pop('key')
self.region = config.pop('region', "us-east-1")
config.pop('use')
self.config = config
self.connection = None
def startup(self):
self.connection = boto.ses.connect_to_region(self.region, **self.config)
def deliver(self, message):
try:
destinations = [r.encode(encoding='utf-8') for r in message.recipients]
response = self.connection.send_raw_email(str(message), message.author.encode(), destinations)
return (
response['SendRawEmailResponse']['SendRawEmailResult']['MessageId'],
response['SendRawEmailResponse']['ResponseMetadata']['RequestId']
)
except SESConnection.ResponseError:
raise
def shutdown(self):
if self.connection:
self.connection.close()
self.connection = None
| true | true |
1c2e425b2fdcf310e1a53834ab48adeaac7c57cc | 388 | py | Python | datamodel_code_generator/model/pydantic/dataclass.py | adaamz/datamodel-code-generator | 3b34573f35f8d420e4668a85047c757fd1da7754 | [
"MIT"
] | 891 | 2019-07-23T04:23:32.000Z | 2022-03-31T13:36:33.000Z | datamodel_code_generator/model/pydantic/dataclass.py | adaamz/datamodel-code-generator | 3b34573f35f8d420e4668a85047c757fd1da7754 | [
"MIT"
] | 663 | 2019-07-23T09:50:26.000Z | 2022-03-29T01:56:55.000Z | datamodel_code_generator/model/pydantic/dataclass.py | adaamz/datamodel-code-generator | 3b34573f35f8d420e4668a85047c757fd1da7754 | [
"MIT"
] | 108 | 2019-07-23T08:50:37.000Z | 2022-03-09T10:50:22.000Z | from typing import ClassVar, Tuple
from datamodel_code_generator.imports import Import
from datamodel_code_generator.model import DataModel
from datamodel_code_generator.model.pydantic.imports import IMPORT_DATACLASS
class DataClass(DataModel):
TEMPLATE_FILE_PATH: ClassVar[str] = 'pydantic/dataclass.jinja2'
DEFAULT_IMPORTS: ClassVar[Tuple[Import, ...]] = (IMPORT_DATACLASS,)
| 35.272727 | 76 | 0.822165 | from typing import ClassVar, Tuple
from datamodel_code_generator.imports import Import
from datamodel_code_generator.model import DataModel
from datamodel_code_generator.model.pydantic.imports import IMPORT_DATACLASS
class DataClass(DataModel):
TEMPLATE_FILE_PATH: ClassVar[str] = 'pydantic/dataclass.jinja2'
DEFAULT_IMPORTS: ClassVar[Tuple[Import, ...]] = (IMPORT_DATACLASS,)
| true | true |
1c2e4387f8d476e9d7aadd89fb94f15969de13b9 | 769 | py | Python | supreme/lib/klt/setup.py | KirillDZR/supreme | c296722599363bd0cbcce6877bd9de9b066cb74b | [
"BSD-3-Clause"
] | 95 | 2015-01-17T09:48:20.000Z | 2021-11-07T16:02:38.000Z | supreme/lib/klt/setup.py | KirillDZR/supreme | c296722599363bd0cbcce6877bd9de9b066cb74b | [
"BSD-3-Clause"
] | 4 | 2015-10-23T15:13:34.000Z | 2019-09-23T22:47:10.000Z | supreme/lib/klt/setup.py | KirillDZR/supreme | c296722599363bd0cbcce6877bd9de9b066cb74b | [
"BSD-3-Clause"
] | 34 | 2015-02-22T20:54:40.000Z | 2022-02-27T13:39:32.000Z | from supreme._build import CExtension
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs
config = Configuration('klt', parent_package, top_path)
config.ext_modules.append(CExtension('libklt_',
['convolve.c', 'error.c', 'pnmio.c',
'pyramid.c', 'selectGoodFeatures.c',
'storeFeatures.c', 'trackFeatures.c',
'klt.c', 'klt_util.c',
'writeFeatures.c'],
path=config.local_path))
config.add_data_dir('tests')
return config
| 40.473684 | 79 | 0.50065 | from supreme._build import CExtension
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs
config = Configuration('klt', parent_package, top_path)
config.ext_modules.append(CExtension('libklt_',
['convolve.c', 'error.c', 'pnmio.c',
'pyramid.c', 'selectGoodFeatures.c',
'storeFeatures.c', 'trackFeatures.c',
'klt.c', 'klt_util.c',
'writeFeatures.c'],
path=config.local_path))
config.add_data_dir('tests')
return config
| true | true |
1c2e4421cbf7299f4b6ac2145e779f62caffe157 | 939 | py | Python | data/test/python/1c2e4421cbf7299f4b6ac2145e779f62caffe157SecurityService.py | harshp8l/deep-learning-lang-detection | 2a54293181c1c2b1a2b840ddee4d4d80177efb33 | [
"MIT"
] | 84 | 2017-10-25T15:49:21.000Z | 2021-11-28T21:25:54.000Z | data/test/python/1c2e4421cbf7299f4b6ac2145e779f62caffe157SecurityService.py | vassalos/deep-learning-lang-detection | cbb00b3e81bed3a64553f9c6aa6138b2511e544e | [
"MIT"
] | 5 | 2018-03-29T11:50:46.000Z | 2021-04-26T13:33:18.000Z | data/test/python/1c2e4421cbf7299f4b6ac2145e779f62caffe157SecurityService.py | vassalos/deep-learning-lang-detection | cbb00b3e81bed3a64553f9c6aa6138b2511e544e | [
"MIT"
] | 24 | 2017-11-22T08:31:00.000Z | 2022-03-27T01:22:31.000Z | # _*_ coding:utf-8 _*_
from web.broker.Brokers import Broker
__author__ = 'Administrator'
class SecurityService(object):
def __init__(self):
pass
'''杀毒'''
def antivirus(self, hostKey, path):
broker = Broker.getBroker(hostKey)
return broker.antivirus(path)
'''取消ip限制'''
def ipOpen(self, hostKey, ip):
broker = Broker.getBroker(hostKey)
broker.unLimit(ip)
'''ip限制'''
def ipClose(self, hostKey, ip):
broker = Broker.getBroker(hostKey)
broker.Limit(ip)
'''开放端口'''
def portOpen(self, hostKey, port):
broker = Broker.getBroker(hostKey)
broker.openPort(port)
'''关闭端口'''
def portClose(self, hostKey, port):
broker = Broker.getBroker(hostKey)
broker.closePort(port)
'''获取iptable列表'''
def iptables(self, hostKey, port):
broker = Broker.getBroker(hostKey)
broker.closePort(port)
| 20.413043 | 42 | 0.610224 |
from web.broker.Brokers import Broker
__author__ = 'Administrator'
class SecurityService(object):
def __init__(self):
pass
def antivirus(self, hostKey, path):
broker = Broker.getBroker(hostKey)
return broker.antivirus(path)
def ipOpen(self, hostKey, ip):
broker = Broker.getBroker(hostKey)
broker.unLimit(ip)
def ipClose(self, hostKey, ip):
broker = Broker.getBroker(hostKey)
broker.Limit(ip)
def portOpen(self, hostKey, port):
broker = Broker.getBroker(hostKey)
broker.openPort(port)
def portClose(self, hostKey, port):
broker = Broker.getBroker(hostKey)
broker.closePort(port)
def iptables(self, hostKey, port):
broker = Broker.getBroker(hostKey)
broker.closePort(port)
| true | true |
1c2e4429e2fc1fc28a8adeeca84d861f861b453c | 8,192 | py | Python | sudoku.py | bryanlimy/samurai-sudoku-solver | 2b3e1f0dfe2c1cf352df375633ca70981d7968bf | [
"MIT"
] | 7 | 2017-07-23T13:19:31.000Z | 2021-11-14T11:08:27.000Z | sudoku.py | bryanlimy/samurai-sudoku-solver | 2b3e1f0dfe2c1cf352df375633ca70981d7968bf | [
"MIT"
] | null | null | null | sudoku.py | bryanlimy/samurai-sudoku-solver | 2b3e1f0dfe2c1cf352df375633ca70981d7968bf | [
"MIT"
] | 2 | 2019-03-14T21:07:55.000Z | 2021-09-18T14:47:52.000Z | ## Solve Every Sudoku Puzzle
## See http://norvig.com/sudoku.html
## Throughout this program we have:
## r is a row, e.g. 'A'
## c is a column, e.g. '3'
## s is a square, e.g. 'A3'
## d is a digit, e.g. '9'
## u is a unit, e.g. ['A1','B1','C1','D1','E1','F1','G1','H1','I1']
## grid is a grid,e.g. 81 non-blank chars, e.g. starting with '.18...7...
## values is a dict of possible values, e.g. {'A1':'12349', 'A2':'8', ...}
def cross(A, B):
"Cross product of elements in A and elements in B."
return [a+b for a in A for b in B]
digits = '123456789'
rows = 'ABCDEFGHI'
cols = digits
squares = cross(rows, cols)
unitlist = ([cross(rows, c) for c in cols] +
[cross(r, cols) for r in rows] +
[cross(rs, cs) for rs in ('ABC','DEF','GHI') for cs in ('123','456','789')])
units = dict((s, [u for u in unitlist if s in u])
for s in squares)
peers = dict((s, set(sum(units[s],[]))-set([s]))
for s in squares)
################ Unit Tests ################
def test():
"A set of tests that must pass."
assert len(squares) == 81
assert len(unitlist) == 27
assert all(len(units[s]) == 3 for s in squares)
assert all(len(peers[s]) == 20 for s in squares)
assert units['C2'] == [['A2', 'B2', 'C2', 'D2', 'E2', 'F2', 'G2', 'H2', 'I2'],
['C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9'],
['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3']]
assert peers['C2'] == set(['A2', 'B2', 'D2', 'E2', 'F2', 'G2', 'H2', 'I2',
'C1', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9',
'A1', 'A3', 'B1', 'B3'])
print('All tests pass.')
################ Parse a Grid ################
def parse_grid(grid):
"""Convert grid to a dict of possible values, {square: digits}, or
return False if a contradiction is detected."""
## To start, every square can be any digit; then assign values from the grid.
values = dict((s, digits) for s in squares)
for s,d in grid_values(grid).items():
if d in digits and not assign(values, s, d):
return False ## (Fail if we can't assign d to square s.)
return values
def grid_values(grid):
"Convert grid into a dict of {square: char} with '0' or '.' for empties."
chars = [c for c in grid if c in digits or c in '0.']
assert len(chars) == 81
return dict(zip(squares, chars))
################ Constraint Propagation ################
def assign(values, s, d):
"""Eliminate all the other values (except d) from values[s] and propagate.
Return values, except return False if a contradiction is detected."""
other_values = values[s].replace(d, '')
if all(eliminate(values, s, d2) for d2 in other_values):
return values
else:
return False
def eliminate(values, s, d):
"""Eliminate d from values[s]; propagate when values or places <= 2.
Return values, except return False if a contradiction is detected."""
if d not in values[s]:
return values ## Already eliminated
values[s] = values[s].replace(d,'')
## (1) If a square s is reduced to one value d2, then eliminate d2 from the peers.
if len(values[s]) == 0:
return False ## Contradiction: removed last value
elif len(values[s]) == 1:
d2 = values[s]
if not all(eliminate(values, s2, d2) for s2 in peers[s]):
return False
## (2) If a unit u is reduced to only one place for a value d, then put it there.
for u in units[s]:
dplaces = [s for s in u if d in values[s]]
if len(dplaces) == 0:
return False ## Contradiction: no place for this value
elif len(dplaces) == 1:
# d can only be in one place in unit; assign it there
if not assign(values, dplaces[0], d):
return False
return values
################ Display as 2-D grid ################
def display(values):
"Display these values as a 2-D grid."
width = 1+max(len(values[s]) for s in squares)
line = '+'.join(['-'*(width*3)]*3)
for r in rows:
print(''.join(values[r+c].center(width)+('|' if c in '36' else '') for c in cols))
if r in 'CF': print(line)
print()
################ Search ################
def solve(grid): return search(parse_grid(grid))
def search(values):
"Using depth-first search and propagation, try all possible values."
if values is False:
return False ## Failed earlier
if all(len(values[s]) == 1 for s in squares):
return values ## Solved!
## Chose the unfilled square s with the fewest possibilities
n,s = min((len(values[s]), s) for s in squares if len(values[s]) > 1)
return some(search(assign(values.copy(), s, d))
for d in values[s])
################ Utilities ################
def some(seq):
"Return some element of seq that is true."
for e in seq:
if e: return e
return False
def from_file(filename, sep='\n'):
"Parse a file into a list of strings, separated by sep."
return file(filename).read().strip().split(sep)
def shuffled(seq):
"Return a randomly shuffled copy of the input sequence."
seq = list(seq)
random.shuffle(seq)
return seq
################ System test ################
import time, random
def solve_all(grids, name='', showif=0.0):
"""Attempt to solve a sequence of grids. Report results.
When showif is a number of seconds, display puzzles that take longer.
When showif is None, don't display any puzzles."""
def time_solve(grid):
start = time.clock()
values = solve(grid)
t = time.clock()-start
## Display puzzles that take long enough
if showif is not None and t > showif:
display(grid_values(grid))
if values: display(values)
print('(%.2f seconds)\n' % t)
return (t, solved(values))
times, results = zip(*[time_solve(grid) for grid in grids])
N = len(grids)
if N > 1:
print("Solved %d of %d %s puzzles (avg %.2f secs (%d Hz), max %.2f secs)." % (sum(results), N, name, sum(times)/N, N/sum(times), max(times)))
def solved(values):
"A puzzle is solved if each unit is a permutation of the digits 1 to 9."
def unitsolved(unit): return set(values[s] for s in unit) == set(digits)
return values is not False and all(unitsolved(unit) for unit in unitlist)
def random_puzzle(N=17):
"""Make a random puzzle with N or more assignments. Restart on contradictions.
Note the resulting puzzle is not guaranteed to be solvable, but empirically
about 99.8% of them are solvable. Some have multiple solutions."""
values = dict((s, digits) for s in squares)
for s in shuffled(squares):
if not assign(values, s, random.choice(values[s])):
break
ds = [values[s] for s in squares if len(values[s]) == 1]
if len(ds) >= N and len(set(ds)) >= 8:
return ''.join(values[s] if len(values[s])==1 else '.' for s in squares)
return random_puzzle(N) ## Give up and make a new puzzle
grid1 = '003020600900305001001806400008102900700000008006708200002609500800203009005010300'
grid2 = '4.....8.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......'
hard1 = '.....6....59.....82....8....45........3........6..3.54...325..6..................'
if __name__ == '__main__':
test()
solve_all(from_file("easy50.txt", '========'), "easy", None)
solve_all(from_file("top95.txt"), "hard", None)
solve_all(from_file("hardest.txt"), "hardest", None)
solve_all([random_puzzle() for _ in range(99)], "random", 100.0)
## References used:
## http://www.scanraid.com/BasicStrategies.htm
## http://www.sudokudragon.com/sudokustrategy.htm
## http://www.krazydad.com/blog/2005/09/29/an-index-of-sudoku-strategies/
## http://www2.warwick.ac.uk/fac/sci/moac/currentstudents/peter_cock/python/sudoku/ | 41.165829 | 150 | 0.561768 | ss(rs, cs) for rs in ('ABC','DEF','GHI') for cs in ('123','456','789')])
units = dict((s, [u for u in unitlist if s in u])
for s in squares)
peers = dict((s, set(sum(units[s],[]))-set([s]))
for s in squares)
################ Unit Tests ################
def test():
assert len(squares) == 81
assert len(unitlist) == 27
assert all(len(units[s]) == 3 for s in squares)
assert all(len(peers[s]) == 20 for s in squares)
assert units['C2'] == [['A2', 'B2', 'C2', 'D2', 'E2', 'F2', 'G2', 'H2', 'I2'],
['C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9'],
['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3']]
assert peers['C2'] == set(['A2', 'B2', 'D2', 'E2', 'F2', 'G2', 'H2', 'I2',
'C1', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9',
'A1', 'A3', 'B1', 'B3'])
print('All tests pass.')
################ Parse a Grid ################
def parse_grid(grid):
## To start, every square can be any digit; then assign values from the grid.
values = dict((s, digits) for s in squares)
for s,d in grid_values(grid).items():
if d in digits and not assign(values, s, d):
return False ## (Fail if we can't assign d to square s.)
return values
def grid_values(grid):
chars = [c for c in grid if c in digits or c in '0.']
assert len(chars) == 81
return dict(zip(squares, chars))
| true | true |
1c2e447c8ebd033d153d63b0073ddd1fecc39a3c | 52,937 | py | Python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_04_01/operations/_p2_svpn_gateways_operations.py | beltr0n/azure-sdk-for-python | 2f7fb8bee881b0fc0386a0ad5385755ceedd0453 | [
"MIT"
] | 2 | 2021-03-24T06:26:11.000Z | 2021-04-18T15:55:59.000Z | sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_04_01/operations/_p2_svpn_gateways_operations.py | beltr0n/azure-sdk-for-python | 2f7fb8bee881b0fc0386a0ad5385755ceedd0453 | [
"MIT"
] | 4 | 2019-04-17T17:57:49.000Z | 2020-04-24T21:11:22.000Z | sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_04_01/operations/_p2_svpn_gateways_operations.py | beltr0n/azure-sdk-for-python | 2f7fb8bee881b0fc0386a0ad5385755ceedd0453 | [
"MIT"
] | 2 | 2021-05-23T16:46:31.000Z | 2021-05-26T23:51:09.000Z | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRequest, HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
class P2SVpnGatewaysOperations(object):
"""P2SVpnGatewaysOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.network.v2020_04_01.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def get(
self,
resource_group_name, # type: str
gateway_name, # type: str
**kwargs # type: Any
):
# type: (...) -> "_models.P2SVpnGateway"
"""Retrieves the details of a virtual wan p2s vpn gateway.
:param resource_group_name: The resource group name of the P2SVpnGateway.
:type resource_group_name: str
:param gateway_name: The name of the gateway.
:type gateway_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: P2SVpnGateway, or the result of cls(response)
:rtype: ~azure.mgmt.network.v2020_04_01.models.P2SVpnGateway
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.P2SVpnGateway"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-04-01"
accept = "application/json"
# Construct URL
url = self.get.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('P2SVpnGateway', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}'} # type: ignore
def _create_or_update_initial(
self,
resource_group_name, # type: str
gateway_name, # type: str
p2_s_vpn_gateway_parameters, # type: "_models.P2SVpnGateway"
**kwargs # type: Any
):
# type: (...) -> "_models.P2SVpnGateway"
cls = kwargs.pop('cls', None) # type: ClsType["_models.P2SVpnGateway"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-04-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self._create_or_update_initial.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(p2_s_vpn_gateway_parameters, 'P2SVpnGateway')
body_content_kwargs['content'] = body_content
request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('P2SVpnGateway', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('P2SVpnGateway', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}'} # type: ignore
def begin_create_or_update(
self,
resource_group_name, # type: str
gateway_name, # type: str
p2_s_vpn_gateway_parameters, # type: "_models.P2SVpnGateway"
**kwargs # type: Any
):
# type: (...) -> LROPoller["_models.P2SVpnGateway"]
"""Creates a virtual wan p2s vpn gateway if it doesn't exist else updates the existing gateway.
:param resource_group_name: The resource group name of the P2SVpnGateway.
:type resource_group_name: str
:param gateway_name: The name of the gateway.
:type gateway_name: str
:param p2_s_vpn_gateway_parameters: Parameters supplied to create or Update a virtual wan p2s
vpn gateway.
:type p2_s_vpn_gateway_parameters: ~azure.mgmt.network.v2020_04_01.models.P2SVpnGateway
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of LROPoller that returns either P2SVpnGateway or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.network.v2020_04_01.models.P2SVpnGateway]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.P2SVpnGateway"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_or_update_initial(
resource_group_name=resource_group_name,
gateway_name=gateway_name,
p2_s_vpn_gateway_parameters=p2_s_vpn_gateway_parameters,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('P2SVpnGateway', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
}
if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}'} # type: ignore
def update_tags(
self,
resource_group_name, # type: str
gateway_name, # type: str
p2_s_vpn_gateway_parameters, # type: "_models.TagsObject"
**kwargs # type: Any
):
# type: (...) -> "_models.P2SVpnGateway"
"""Updates virtual wan p2s vpn gateway tags.
:param resource_group_name: The resource group name of the P2SVpnGateway.
:type resource_group_name: str
:param gateway_name: The name of the gateway.
:type gateway_name: str
:param p2_s_vpn_gateway_parameters: Parameters supplied to update a virtual wan p2s vpn gateway
tags.
:type p2_s_vpn_gateway_parameters: ~azure.mgmt.network.v2020_04_01.models.TagsObject
:keyword callable cls: A custom type or function that will be passed the direct response
:return: P2SVpnGateway, or the result of cls(response)
:rtype: ~azure.mgmt.network.v2020_04_01.models.P2SVpnGateway
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.P2SVpnGateway"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-04-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self.update_tags.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(p2_s_vpn_gateway_parameters, 'TagsObject')
body_content_kwargs['content'] = body_content
request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('P2SVpnGateway', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
update_tags.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}'} # type: ignore
def _delete_initial(
self,
resource_group_name, # type: str
gateway_name, # type: str
**kwargs # type: Any
):
# type: (...) -> None
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-04-01"
accept = "application/json"
# Construct URL
url = self._delete_initial.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.delete(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}'} # type: ignore
def begin_delete(
self,
resource_group_name, # type: str
gateway_name, # type: str
**kwargs # type: Any
):
# type: (...) -> LROPoller[None]
"""Deletes a virtual wan p2s vpn gateway.
:param resource_group_name: The resource group name of the P2SVpnGateway.
:type resource_group_name: str
:param gateway_name: The name of the gateway.
:type gateway_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType[None]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial(
resource_group_name=resource_group_name,
gateway_name=gateway_name,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
if cls:
return cls(pipeline_response, None, {})
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
}
if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}'} # type: ignore
def list_by_resource_group(
self,
resource_group_name, # type: str
**kwargs # type: Any
):
# type: (...) -> Iterable["_models.ListP2SVpnGatewaysResult"]
"""Lists all the P2SVpnGateways in a resource group.
:param resource_group_name: The resource group name of the P2SVpnGateway.
:type resource_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ListP2SVpnGatewaysResult or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.network.v2020_04_01.models.ListP2SVpnGatewaysResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ListP2SVpnGatewaysResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-04-01"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list_by_resource_group.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
def extract_data(pipeline_response):
deserialized = self._deserialize('ListP2SVpnGatewaysResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways'} # type: ignore
def list(
self,
**kwargs # type: Any
):
# type: (...) -> Iterable["_models.ListP2SVpnGatewaysResult"]
"""Lists all the P2SVpnGateways in a subscription.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ListP2SVpnGatewaysResult or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.network.v2020_04_01.models.ListP2SVpnGatewaysResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ListP2SVpnGatewaysResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-04-01"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list.metadata['url'] # type: ignore
path_format_arguments = {
'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 = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
def extract_data(pipeline_response):
deserialized = self._deserialize('ListP2SVpnGatewaysResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/p2svpnGateways'} # type: ignore
def _generate_vpn_profile_initial(
self,
resource_group_name, # type: str
gateway_name, # type: str
parameters, # type: "_models.P2SVpnProfileParameters"
**kwargs # type: Any
):
# type: (...) -> Optional["_models.VpnProfileResponse"]
cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.VpnProfileResponse"]]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-04-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self._generate_vpn_profile_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'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 = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(parameters, 'P2SVpnProfileParameters')
body_content_kwargs['content'] = body_content
request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('VpnProfileResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_generate_vpn_profile_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}/generatevpnprofile'} # type: ignore
def begin_generate_vpn_profile(
self,
resource_group_name, # type: str
gateway_name, # type: str
parameters, # type: "_models.P2SVpnProfileParameters"
**kwargs # type: Any
):
# type: (...) -> LROPoller["_models.VpnProfileResponse"]
"""Generates VPN profile for P2S client of the P2SVpnGateway in the specified resource group.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param gateway_name: The name of the P2SVpnGateway.
:type gateway_name: str
:param parameters: Parameters supplied to the generate P2SVpnGateway VPN client package
operation.
:type parameters: ~azure.mgmt.network.v2020_04_01.models.P2SVpnProfileParameters
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of LROPoller that returns either VpnProfileResponse or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.network.v2020_04_01.models.VpnProfileResponse]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.VpnProfileResponse"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = self._generate_vpn_profile_initial(
resource_group_name=resource_group_name,
gateway_name=gateway_name,
parameters=parameters,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('VpnProfileResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_generate_vpn_profile.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}/generatevpnprofile'} # type: ignore
def _get_p2_s_vpn_connection_health_initial(
self,
resource_group_name, # type: str
gateway_name, # type: str
**kwargs # type: Any
):
# type: (...) -> Optional["_models.P2SVpnGateway"]
cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.P2SVpnGateway"]]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-04-01"
accept = "application/json"
# Construct URL
url = self._get_p2_s_vpn_connection_health_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'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 = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.post(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('P2SVpnGateway', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_get_p2_s_vpn_connection_health_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}/getP2sVpnConnectionHealth'} # type: ignore
def begin_get_p2_s_vpn_connection_health(
self,
resource_group_name, # type: str
gateway_name, # type: str
**kwargs # type: Any
):
# type: (...) -> LROPoller["_models.P2SVpnGateway"]
"""Gets the connection health of P2S clients of the virtual wan P2SVpnGateway in the specified
resource group.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param gateway_name: The name of the P2SVpnGateway.
:type gateway_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of LROPoller that returns either P2SVpnGateway or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.network.v2020_04_01.models.P2SVpnGateway]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.P2SVpnGateway"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = self._get_p2_s_vpn_connection_health_initial(
resource_group_name=resource_group_name,
gateway_name=gateway_name,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('P2SVpnGateway', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_get_p2_s_vpn_connection_health.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}/getP2sVpnConnectionHealth'} # type: ignore
def _get_p2_s_vpn_connection_health_detailed_initial(
self,
resource_group_name, # type: str
gateway_name, # type: str
request, # type: "_models.P2SVpnConnectionHealthRequest"
**kwargs # type: Any
):
# type: (...) -> Optional["_models.P2SVpnConnectionHealth"]
cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.P2SVpnConnectionHealth"]]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-04-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self._get_p2_s_vpn_connection_health_detailed_initial.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(request, 'P2SVpnConnectionHealthRequest')
body_content_kwargs['content'] = body_content
request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('P2SVpnConnectionHealth', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_get_p2_s_vpn_connection_health_detailed_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}/getP2sVpnConnectionHealthDetailed'} # type: ignore
def begin_get_p2_s_vpn_connection_health_detailed(
self,
resource_group_name, # type: str
gateway_name, # type: str
request, # type: "_models.P2SVpnConnectionHealthRequest"
**kwargs # type: Any
):
# type: (...) -> LROPoller["_models.P2SVpnConnectionHealth"]
"""Gets the sas url to get the connection health detail of P2S clients of the virtual wan
P2SVpnGateway in the specified resource group.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param gateway_name: The name of the P2SVpnGateway.
:type gateway_name: str
:param request: Request parameters supplied to get p2s vpn connections detailed health.
:type request: ~azure.mgmt.network.v2020_04_01.models.P2SVpnConnectionHealthRequest
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of LROPoller that returns either P2SVpnConnectionHealth or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.network.v2020_04_01.models.P2SVpnConnectionHealth]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.P2SVpnConnectionHealth"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = self._get_p2_s_vpn_connection_health_detailed_initial(
resource_group_name=resource_group_name,
gateway_name=gateway_name,
request=request,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('P2SVpnConnectionHealth', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
}
if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_get_p2_s_vpn_connection_health_detailed.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}/getP2sVpnConnectionHealthDetailed'} # type: ignore
def _disconnect_p2_s_vpn_connections_initial(
self,
resource_group_name, # type: str
p2_s_vpn_gateway_name, # type: str
request, # type: "_models.P2SVpnConnectionRequest"
**kwargs # type: Any
):
# type: (...) -> None
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-04-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self._disconnect_p2_s_vpn_connections_initial.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'p2sVpnGatewayName': self._serialize.url("p2_s_vpn_gateway_name", p2_s_vpn_gateway_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(request, 'P2SVpnConnectionRequest')
body_content_kwargs['content'] = body_content
request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_disconnect_p2_s_vpn_connections_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{p2sVpnGatewayName}/disconnectP2sVpnConnections'} # type: ignore
def begin_disconnect_p2_s_vpn_connections(
self,
resource_group_name, # type: str
p2_s_vpn_gateway_name, # type: str
request, # type: "_models.P2SVpnConnectionRequest"
**kwargs # type: Any
):
# type: (...) -> LROPoller[None]
"""Disconnect P2S vpn connections of the virtual wan P2SVpnGateway in the specified resource
group.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param p2_s_vpn_gateway_name: The name of the P2S Vpn Gateway.
:type p2_s_vpn_gateway_name: str
:param request: The parameters are supplied to disconnect p2s vpn connections.
:type request: ~azure.mgmt.network.v2020_04_01.models.P2SVpnConnectionRequest
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType[None]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = self._disconnect_p2_s_vpn_connections_initial(
resource_group_name=resource_group_name,
p2_s_vpn_gateway_name=p2_s_vpn_gateway_name,
request=request,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
if cls:
return cls(pipeline_response, None, {})
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'p2sVpnGatewayName': self._serialize.url("p2_s_vpn_gateway_name", p2_s_vpn_gateway_name, 'str'),
}
if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_disconnect_p2_s_vpn_connections.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{p2sVpnGatewayName}/disconnectP2sVpnConnections'} # type: ignore
| 50.272555 | 248 | 0.66768 |
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRequest, HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
if TYPE_CHECKING:
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
class P2SVpnGatewaysOperations(object):
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def get(
self,
resource_group_name,
gateway_name,
**kwargs
):
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-04-01"
accept = "application/json"
url = self.get.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
header_parameters = {}
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('P2SVpnGateway', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}'}
def _create_or_update_initial(
self,
resource_group_name,
gateway_name,
p2_s_vpn_gateway_parameters,
**kwargs
):
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-04-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
url = self._create_or_update_initial.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
header_parameters = {}
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {}
body_content = self._serialize.body(p2_s_vpn_gateway_parameters, 'P2SVpnGateway')
body_content_kwargs['content'] = body_content
request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('P2SVpnGateway', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('P2SVpnGateway', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}'}
def begin_create_or_update(
self,
resource_group_name,
gateway_name,
p2_s_vpn_gateway_parameters,
**kwargs
):
polling = kwargs.pop('polling', True)
cls = kwargs.pop('cls', None)
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None)
if cont_token is None:
raw_result = self._create_or_update_initial(
resource_group_name=resource_group_name,
gateway_name=gateway_name,
p2_s_vpn_gateway_parameters=p2_s_vpn_gateway_parameters,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('P2SVpnGateway', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
}
if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}'}
def update_tags(
self,
resource_group_name,
gateway_name,
p2_s_vpn_gateway_parameters,
**kwargs
):
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-04-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
url = self.update_tags.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
header_parameters = {}
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {}
body_content = self._serialize.body(p2_s_vpn_gateway_parameters, 'TagsObject')
body_content_kwargs['content'] = body_content
request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('P2SVpnGateway', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
update_tags.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}'}
def _delete_initial(
self,
resource_group_name,
gateway_name,
**kwargs
):
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-04-01"
accept = "application/json"
url = self._delete_initial.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
header_parameters = {}
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.delete(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}'}
def begin_delete(
self,
resource_group_name,
gateway_name,
**kwargs
):
polling = kwargs.pop('polling', True)
cls = kwargs.pop('cls', None)
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None)
if cont_token is None:
raw_result = self._delete_initial(
resource_group_name=resource_group_name,
gateway_name=gateway_name,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
if cls:
return cls(pipeline_response, None, {})
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
}
if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}'}
def list_by_resource_group(
self,
resource_group_name,
**kwargs
):
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-04-01"
accept = "application/json"
def prepare_request(next_link=None):
header_parameters = {}
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
url = self.list_by_resource_group.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {}
request = self._client.get(url, query_parameters, header_parameters)
return request
def extract_data(pipeline_response):
deserialized = self._deserialize('ListP2SVpnGatewaysResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways'}
def list(
self,
**kwargs
):
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-04-01"
accept = "application/json"
def prepare_request(next_link=None):
header_parameters = {}
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
url = self.list.metadata['url']
path_format_arguments = {
'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("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {}
request = self._client.get(url, query_parameters, header_parameters)
return request
def extract_data(pipeline_response):
deserialized = self._deserialize('ListP2SVpnGatewaysResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/p2svpnGateways'}
def _generate_vpn_profile_initial(
self,
resource_group_name,
gateway_name,
parameters,
**kwargs
):
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-04-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
url = self._generate_vpn_profile_initial.metadata['url']
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'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("api_version", api_version, 'str')
header_parameters = {}
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {}
body_content = self._serialize.body(parameters, 'P2SVpnProfileParameters')
body_content_kwargs['content'] = body_content
request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('VpnProfileResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_generate_vpn_profile_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}/generatevpnprofile'}
def begin_generate_vpn_profile(
self,
resource_group_name,
gateway_name,
parameters,
**kwargs
):
polling = kwargs.pop('polling', True)
cls = kwargs.pop('cls', None)
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None)
if cont_token is None:
raw_result = self._generate_vpn_profile_initial(
resource_group_name=resource_group_name,
gateway_name=gateway_name,
parameters=parameters,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('VpnProfileResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_generate_vpn_profile.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}/generatevpnprofile'}
def _get_p2_s_vpn_connection_health_initial(
self,
resource_group_name,
gateway_name,
**kwargs
):
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-04-01"
accept = "application/json"
url = self._get_p2_s_vpn_connection_health_initial.metadata['url']
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'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("api_version", api_version, 'str')
header_parameters = {}
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.post(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('P2SVpnGateway', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_get_p2_s_vpn_connection_health_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}/getP2sVpnConnectionHealth'}
def begin_get_p2_s_vpn_connection_health(
self,
resource_group_name,
gateway_name,
**kwargs
):
polling = kwargs.pop('polling', True)
cls = kwargs.pop('cls', None)
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None)
if cont_token is None:
raw_result = self._get_p2_s_vpn_connection_health_initial(
resource_group_name=resource_group_name,
gateway_name=gateway_name,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('P2SVpnGateway', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_get_p2_s_vpn_connection_health.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}/getP2sVpnConnectionHealth'}
def _get_p2_s_vpn_connection_health_detailed_initial(
self,
resource_group_name,
gateway_name,
request,
**kwargs
):
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-04-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
url = self._get_p2_s_vpn_connection_health_detailed_initial.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
header_parameters = {}
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {}
body_content = self._serialize.body(request, 'P2SVpnConnectionHealthRequest')
body_content_kwargs['content'] = body_content
request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('P2SVpnConnectionHealth', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_get_p2_s_vpn_connection_health_detailed_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}/getP2sVpnConnectionHealthDetailed'}
def begin_get_p2_s_vpn_connection_health_detailed(
self,
resource_group_name,
gateway_name,
request,
**kwargs
):
polling = kwargs.pop('polling', True)
cls = kwargs.pop('cls', None)
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None)
if cont_token is None:
raw_result = self._get_p2_s_vpn_connection_health_detailed_initial(
resource_group_name=resource_group_name,
gateway_name=gateway_name,
request=request,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('P2SVpnConnectionHealth', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
}
if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_get_p2_s_vpn_connection_health_detailed.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}/getP2sVpnConnectionHealthDetailed'}
def _disconnect_p2_s_vpn_connections_initial(
self,
resource_group_name,
p2_s_vpn_gateway_name,
request,
**kwargs
):
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-04-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
url = self._disconnect_p2_s_vpn_connections_initial.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'p2sVpnGatewayName': self._serialize.url("p2_s_vpn_gateway_name", p2_s_vpn_gateway_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
header_parameters = {}
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {}
body_content = self._serialize.body(request, 'P2SVpnConnectionRequest')
body_content_kwargs['content'] = body_content
request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_disconnect_p2_s_vpn_connections_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{p2sVpnGatewayName}/disconnectP2sVpnConnections'}
def begin_disconnect_p2_s_vpn_connections(
self,
resource_group_name,
p2_s_vpn_gateway_name,
request,
**kwargs
):
polling = kwargs.pop('polling', True)
cls = kwargs.pop('cls', None)
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None)
if cont_token is None:
raw_result = self._disconnect_p2_s_vpn_connections_initial(
resource_group_name=resource_group_name,
p2_s_vpn_gateway_name=p2_s_vpn_gateway_name,
request=request,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
if cls:
return cls(pipeline_response, None, {})
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'p2sVpnGatewayName': self._serialize.url("p2_s_vpn_gateway_name", p2_s_vpn_gateway_name, 'str'),
}
if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_disconnect_p2_s_vpn_connections.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{p2sVpnGatewayName}/disconnectP2sVpnConnections'}
| true | true |
1c2e44acca47cb034eaa829d2aea0746a82c253c | 271 | py | Python | tz_detect/utils.py | dkirkham/django-tz-detect | ec3c66a967e2518adf070bfd42a9076471f1bc2a | [
"MIT"
] | null | null | null | tz_detect/utils.py | dkirkham/django-tz-detect | ec3c66a967e2518adf070bfd42a9076471f1bc2a | [
"MIT"
] | null | null | null | tz_detect/utils.py | dkirkham/django-tz-detect | ec3c66a967e2518adf070bfd42a9076471f1bc2a | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
def convert_header_name(django_header):
"""Converts header name from django settings to real header name.
For example:
'HTTP_CUSTOM_CSRF' -> 'custom-csrf'
"""
return django_header.lower().replace('_', '-').split('http-')[-1]
| 27.1 | 69 | 0.645756 |
def convert_header_name(django_header):
return django_header.lower().replace('_', '-').split('http-')[-1]
| true | true |
1c2e44c4a90f8779ad9a447ea28d87f5a7458299 | 3,107 | py | Python | cannabis/protocols/timelord_protocol.py | CannabisChain/cannabis-blockchain | 6a1dc045cdcca45d0ffdcbdebe805c49f04b3faf | [
"Apache-2.0"
] | 12 | 2021-07-24T14:50:56.000Z | 2022-02-09T04:28:28.000Z | cannabis/protocols/timelord_protocol.py | CannabisChain/cannabis-blockchain | 6a1dc045cdcca45d0ffdcbdebe805c49f04b3faf | [
"Apache-2.0"
] | 27 | 2021-07-23T15:16:41.000Z | 2022-03-22T10:11:23.000Z | cannabis/protocols/timelord_protocol.py | CannabisChain/cannabis-blockchain | 6a1dc045cdcca45d0ffdcbdebe805c49f04b3faf | [
"Apache-2.0"
] | 7 | 2021-07-23T15:48:54.000Z | 2022-01-20T20:03:51.000Z | from dataclasses import dataclass
from typing import List, Optional, Tuple
from cannabis.types.blockchain_format.foliage import Foliage
from cannabis.types.blockchain_format.reward_chain_block import RewardChainBlock, RewardChainBlockUnfinished
from cannabis.types.blockchain_format.sized_bytes import bytes32
from cannabis.types.blockchain_format.sub_epoch_summary import SubEpochSummary
from cannabis.types.blockchain_format.vdf import VDFInfo, VDFProof
from cannabis.types.end_of_slot_bundle import EndOfSubSlotBundle
from cannabis.util.ints import uint8, uint32, uint64, uint128
from cannabis.util.streamable import Streamable, streamable
"""
Protocol between timelord and full node.
Note: When changing this file, also change protocol_message_types.py, and the protocol version in shared_protocol.py
"""
@dataclass(frozen=True)
@streamable
class NewPeakTimelord(Streamable):
reward_chain_block: RewardChainBlock
difficulty: uint64
deficit: uint8
sub_slot_iters: uint64 # SSi in the slot where NewPeak has been infused
sub_epoch_summary: Optional[
SubEpochSummary
] # If NewPeak is the last slot in epoch, the next slot should include this
previous_reward_challenges: List[Tuple[bytes32, uint128]]
last_challenge_sb_or_eos_total_iters: uint128
passes_ses_height_but_not_yet_included: bool
@dataclass(frozen=True)
@streamable
class NewUnfinishedBlockTimelord(Streamable):
reward_chain_block: RewardChainBlockUnfinished # Reward chain trunk data
difficulty: uint64
sub_slot_iters: uint64 # SSi in the slot where block is infused
foliage: Foliage # Reward chain foliage data
sub_epoch_summary: Optional[SubEpochSummary] # If this is the last slot in epoch, the next slot should include this
# This is the last thing infused in the reward chain before this signage point.
# The challenge that the SP reward chain VDF is based off of, or in the case of sp index 0, the previous infusion
rc_prev: bytes32
@dataclass(frozen=True)
@streamable
class NewInfusionPointVDF(Streamable):
unfinished_reward_hash: bytes32
challenge_chain_ip_vdf: VDFInfo
challenge_chain_ip_proof: VDFProof
reward_chain_ip_vdf: VDFInfo
reward_chain_ip_proof: VDFProof
infused_challenge_chain_ip_vdf: Optional[VDFInfo]
infused_challenge_chain_ip_proof: Optional[VDFProof]
@dataclass(frozen=True)
@streamable
class NewSignagePointVDF(Streamable):
index_from_challenge: uint8
challenge_chain_sp_vdf: VDFInfo
challenge_chain_sp_proof: VDFProof
reward_chain_sp_vdf: VDFInfo
reward_chain_sp_proof: VDFProof
@dataclass(frozen=True)
@streamable
class NewEndOfSubSlotVDF(Streamable):
end_of_sub_slot_bundle: EndOfSubSlotBundle
@dataclass(frozen=True)
@streamable
class RequestCompactProofOfTime(Streamable):
new_proof_of_time: VDFInfo
header_hash: bytes32
height: uint32
field_vdf: uint8
@dataclass(frozen=True)
@streamable
class RespondCompactProofOfTime(Streamable):
vdf_info: VDFInfo
vdf_proof: VDFProof
header_hash: bytes32
height: uint32
field_vdf: uint8
| 33.771739 | 120 | 0.801738 | from dataclasses import dataclass
from typing import List, Optional, Tuple
from cannabis.types.blockchain_format.foliage import Foliage
from cannabis.types.blockchain_format.reward_chain_block import RewardChainBlock, RewardChainBlockUnfinished
from cannabis.types.blockchain_format.sized_bytes import bytes32
from cannabis.types.blockchain_format.sub_epoch_summary import SubEpochSummary
from cannabis.types.blockchain_format.vdf import VDFInfo, VDFProof
from cannabis.types.end_of_slot_bundle import EndOfSubSlotBundle
from cannabis.util.ints import uint8, uint32, uint64, uint128
from cannabis.util.streamable import Streamable, streamable
@dataclass(frozen=True)
@streamable
class NewPeakTimelord(Streamable):
reward_chain_block: RewardChainBlock
difficulty: uint64
deficit: uint8
sub_slot_iters: uint64
sub_epoch_summary: Optional[
SubEpochSummary
]
previous_reward_challenges: List[Tuple[bytes32, uint128]]
last_challenge_sb_or_eos_total_iters: uint128
passes_ses_height_but_not_yet_included: bool
@dataclass(frozen=True)
@streamable
class NewUnfinishedBlockTimelord(Streamable):
reward_chain_block: RewardChainBlockUnfinished
difficulty: uint64
sub_slot_iters: uint64
foliage: Foliage
sub_epoch_summary: Optional[SubEpochSummary]
rc_prev: bytes32
@dataclass(frozen=True)
@streamable
class NewInfusionPointVDF(Streamable):
unfinished_reward_hash: bytes32
challenge_chain_ip_vdf: VDFInfo
challenge_chain_ip_proof: VDFProof
reward_chain_ip_vdf: VDFInfo
reward_chain_ip_proof: VDFProof
infused_challenge_chain_ip_vdf: Optional[VDFInfo]
infused_challenge_chain_ip_proof: Optional[VDFProof]
@dataclass(frozen=True)
@streamable
class NewSignagePointVDF(Streamable):
index_from_challenge: uint8
challenge_chain_sp_vdf: VDFInfo
challenge_chain_sp_proof: VDFProof
reward_chain_sp_vdf: VDFInfo
reward_chain_sp_proof: VDFProof
@dataclass(frozen=True)
@streamable
class NewEndOfSubSlotVDF(Streamable):
end_of_sub_slot_bundle: EndOfSubSlotBundle
@dataclass(frozen=True)
@streamable
class RequestCompactProofOfTime(Streamable):
new_proof_of_time: VDFInfo
header_hash: bytes32
height: uint32
field_vdf: uint8
@dataclass(frozen=True)
@streamable
class RespondCompactProofOfTime(Streamable):
vdf_info: VDFInfo
vdf_proof: VDFProof
header_hash: bytes32
height: uint32
field_vdf: uint8
| true | true |
1c2e460373f0cb1f36cd06f1a55dcf13a8557ea3 | 4,052 | py | Python | src/batch_runner/net_eval_batch.py | haleqiu/TLIO | d4fea31517fb8db662dc14c388a792217b172e64 | [
"BSD-3-Clause"
] | 127 | 2020-06-15T18:16:09.000Z | 2022-03-28T08:57:18.000Z | src/batch_runner/net_eval_batch.py | ori-drs/tlio | 259247bea2e10bf47922071d235b7f80d7685e61 | [
"BSD-3-Clause"
] | 12 | 2020-10-01T14:38:04.000Z | 2022-03-14T10:11:11.000Z | src/batch_runner/net_eval_batch.py | ori-drs/tlio | 259247bea2e10bf47922071d235b7f80d7685e61 | [
"BSD-3-Clause"
] | 38 | 2020-06-15T18:46:41.000Z | 2022-03-06T09:33:58.000Z | import argparse
import json
import os
import os.path as osp
import subprocess as sp
from pathlib import Path
from utils.logging import logging
homedir = Path.home()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
# ----------------------- io params -----------------------
io_groups = parser.add_argument_group("io")
io_groups.add_argument(
"--root_dir",
type=str,
default=f"{homedir}/vo_output",
help="Path to dataset directory",
)
io_groups.add_argument(
"--data_list",
type=str,
default=f"{homedir}/vo_output/split/golden/golden_test.txt",
)
io_groups.add_argument(
"--model_globbing",
type=str,
default="../models/200hz/1s-1s*/checkpoint_*.pt",
help="Globbing expression for model selection",
)
io_groups.add_argument(
"--out_dir",
type=str,
default=f"./all_output/",
help="Path to dataset directory",
)
parser.add_argument("--sample_freq", type=float, default=5.0)
parser.add_argument("--perturbation_analysis", action="store_true")
args = parser.parse_args()
all_models = list(Path.cwd().glob(args.model_globbing))
logging.info(f"Found {len(all_models)} models")
logging.info(f"Found {all_models}")
for m in all_models:
base_folder = Path(m).parent
logging.info(base_folder)
name_run = str(Path(m).parents[1].name) + "-" + str(Path(m).parents[0].name)
if not osp.exists(f"./{args.out_dir}/{name_run}/"):
os.mkdir(f"./{args.out_dir}/{name_run}/")
with open(str(base_folder) + "/parameters.json", "r") as f:
conf = json.load(f)
print(conf)
if args.perturbation_analysis:
accel_bias_ptrb_range = [
0,
0.1,
0.2,
0.3,
0.4,
0.5,
0,
0,
0,
0,
0,
0,
0,
0,
0,
]
gyro_bias_ptrb_range = [
0,
0,
0,
0,
0,
0,
0.025,
0.05,
0.075,
0.1,
0,
0,
0,
0,
0,
]
grav_ptrb_range = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 6, 8, 10]
else:
accel_bias_ptrb_range = [0]
gyro_bias_ptrb_range = [0]
grav_ptrb_range = [0]
n_trials = len(grav_ptrb_range)
for trial in range(n_trials):
command = [
"python3",
"main_net.py",
"--mode",
"eval",
"--test_list",
f"{args.data_list}",
"--root_dir",
f"{args.root_dir}",
"--model_path",
f"{m}",
"--out_dir",
f"./{args.out_dir}/{name_run}/",
"--imu_freq",
f'{conf["imu_freq"]}',
"--past_time",
f'{conf["past_time"]}',
"--window_time",
f'{conf["window_time"]}',
"--future_time",
f'{conf["future_time"]}',
"--sample_freq",
f"{args.sample_freq}",
"--do_bias_shift",
"--accel_bias_range",
f"{accel_bias_ptrb_range[trial]}",
"--gyro_bias_range",
f"{gyro_bias_ptrb_range[trial]}",
"--perturb_gravity",
"--perturb_gravity_theta_range",
f"{grav_ptrb_range[trial]}",
]
logging.info(" ".join(command))
try:
sp.run(command)
except Exception as e:
logging.error(e)
continue
| 28.942857 | 84 | 0.439289 | import argparse
import json
import os
import os.path as osp
import subprocess as sp
from pathlib import Path
from utils.logging import logging
homedir = Path.home()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
io_groups = parser.add_argument_group("io")
io_groups.add_argument(
"--root_dir",
type=str,
default=f"{homedir}/vo_output",
help="Path to dataset directory",
)
io_groups.add_argument(
"--data_list",
type=str,
default=f"{homedir}/vo_output/split/golden/golden_test.txt",
)
io_groups.add_argument(
"--model_globbing",
type=str,
default="../models/200hz/1s-1s*/checkpoint_*.pt",
help="Globbing expression for model selection",
)
io_groups.add_argument(
"--out_dir",
type=str,
default=f"./all_output/",
help="Path to dataset directory",
)
parser.add_argument("--sample_freq", type=float, default=5.0)
parser.add_argument("--perturbation_analysis", action="store_true")
args = parser.parse_args()
all_models = list(Path.cwd().glob(args.model_globbing))
logging.info(f"Found {len(all_models)} models")
logging.info(f"Found {all_models}")
for m in all_models:
base_folder = Path(m).parent
logging.info(base_folder)
name_run = str(Path(m).parents[1].name) + "-" + str(Path(m).parents[0].name)
if not osp.exists(f"./{args.out_dir}/{name_run}/"):
os.mkdir(f"./{args.out_dir}/{name_run}/")
with open(str(base_folder) + "/parameters.json", "r") as f:
conf = json.load(f)
print(conf)
if args.perturbation_analysis:
accel_bias_ptrb_range = [
0,
0.1,
0.2,
0.3,
0.4,
0.5,
0,
0,
0,
0,
0,
0,
0,
0,
0,
]
gyro_bias_ptrb_range = [
0,
0,
0,
0,
0,
0,
0.025,
0.05,
0.075,
0.1,
0,
0,
0,
0,
0,
]
grav_ptrb_range = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 6, 8, 10]
else:
accel_bias_ptrb_range = [0]
gyro_bias_ptrb_range = [0]
grav_ptrb_range = [0]
n_trials = len(grav_ptrb_range)
for trial in range(n_trials):
command = [
"python3",
"main_net.py",
"--mode",
"eval",
"--test_list",
f"{args.data_list}",
"--root_dir",
f"{args.root_dir}",
"--model_path",
f"{m}",
"--out_dir",
f"./{args.out_dir}/{name_run}/",
"--imu_freq",
f'{conf["imu_freq"]}',
"--past_time",
f'{conf["past_time"]}',
"--window_time",
f'{conf["window_time"]}',
"--future_time",
f'{conf["future_time"]}',
"--sample_freq",
f"{args.sample_freq}",
"--do_bias_shift",
"--accel_bias_range",
f"{accel_bias_ptrb_range[trial]}",
"--gyro_bias_range",
f"{gyro_bias_ptrb_range[trial]}",
"--perturb_gravity",
"--perturb_gravity_theta_range",
f"{grav_ptrb_range[trial]}",
]
logging.info(" ".join(command))
try:
sp.run(command)
except Exception as e:
logging.error(e)
continue
| true | true |
1c2e467cd4fc6eaf6552db91bf2a99fe684155dc | 2,670 | py | Python | bingo/Base/MuPlusLambdaEA.py | tylertownsend/bingo | 0aeebe03df71a632f833c56ceb9c697dddbe78fc | [
"Apache-2.0"
] | null | null | null | bingo/Base/MuPlusLambdaEA.py | tylertownsend/bingo | 0aeebe03df71a632f833c56ceb9c697dddbe78fc | [
"Apache-2.0"
] | null | null | null | bingo/Base/MuPlusLambdaEA.py | tylertownsend/bingo | 0aeebe03df71a632f833c56ceb9c697dddbe78fc | [
"Apache-2.0"
] | null | null | null | """The "Mu + Lambda"
This module defines the basis of the "mu plus lambda"
evolutionary algorithm in bingo analyses. The next generation
is evaluated and selected from both the parent and offspring
populations.
"""
from .EvolutionaryAlgorithm import EvolutionaryAlgorithm
from .VarOr import VarOr
class MuPlusLambda(EvolutionaryAlgorithm):
"""The algorithm used to perform generational steps.
A class for the "mu plus lambda" evolutionary algorithm in bingo.
Parameters
----------
evaluation : Evaluation
The evaluation algorithm that sets the fitness on the population.
selection : Selection
Selection instance to perform selection on a population
crossover : Crossover
The algorithm that performs crossover during variation.
mutation : Mutation
The algorithm that performs mutation during variation.
crossover_probability : float
Probability that crossover will occur on an
individual.
mutation_probability : float
Probability that mutation will occur on an
individual.
number_offspring : int
The number of offspring produced from variation.
Attributes
----------
variation : VarOr
VarOr variation to perform variation on a population
evaluation : Evaluation
Evaluation instance to perform evaluation on a population
selection : Selection
Selection instance to perform selection on a population
"""
def __init__(self, evaluation, selection, crossover, mutation,
crossover_probability, mutation_probability,
number_offspring):
super().__init__(variation=VarOr(crossover, mutation,
crossover_probability,
mutation_probability),
evaluation=evaluation,
selection=selection)
self._number_offspring = number_offspring
def generational_step(self, population):
"""Performs selection on individuals.
Parameters
----------
population : list of Chromosome
The population at the start of the generational step
Returns
-------
list of Chromosome :
The next generation of the population
"""
offspring = self.variation(population, self._number_offspring)
self.evaluation(population + offspring)
return self.selection(population + offspring, len(population))
| 37.605634 | 74 | 0.623596 | from .EvolutionaryAlgorithm import EvolutionaryAlgorithm
from .VarOr import VarOr
class MuPlusLambda(EvolutionaryAlgorithm):
def __init__(self, evaluation, selection, crossover, mutation,
crossover_probability, mutation_probability,
number_offspring):
super().__init__(variation=VarOr(crossover, mutation,
crossover_probability,
mutation_probability),
evaluation=evaluation,
selection=selection)
self._number_offspring = number_offspring
def generational_step(self, population):
offspring = self.variation(population, self._number_offspring)
self.evaluation(population + offspring)
return self.selection(population + offspring, len(population))
| true | true |
1c2e4716e42cad5bc4c78a3108ee05cc872214b3 | 21,852 | py | Python | neurox/interpretation/utils.py | davidarps/NeuroX | 591cabce7a317d2a1ff2b07e6a3b277250815454 | [
"BSD-3-Clause"
] | null | null | null | neurox/interpretation/utils.py | davidarps/NeuroX | 591cabce7a317d2a1ff2b07e6a3b277250815454 | [
"BSD-3-Clause"
] | null | null | null | neurox/interpretation/utils.py | davidarps/NeuroX | 591cabce7a317d2a1ff2b07e6a3b277250815454 | [
"BSD-3-Clause"
] | null | null | null | import math
import numpy as np
from imblearn.under_sampling import RandomUnderSampler
def isnotebook():
"""
Utility function to detect if the code being run is within a jupyter
notebook. Useful to change progress indicators for example.
Returns
-------
isnotebook : bool
True if the function is being called inside a notebook, False otherwise.
"""
try:
shell = get_ipython().__class__.__name__
if shell == "ZMQInteractiveShell":
return True # Jupyter notebook or qtconsole
elif shell == "TerminalInteractiveShell":
return False # Terminal running IPython
else:
return False # Other type (?)
except NameError:
return False # Probably standard Python interpreter
def get_progress_bar():
"""
Utility function to get a progress bar depending on the environment the code
is running in. A normal text-based progress bar is returned in normal
shells, and a notebook widget-based progress bar is returned in jupyter
notebooks.
Returns
-------
progressbar : function
The appropriate progressbar from the tqdm library.
"""
if isnotebook():
from tqdm import tqdm_notebook as progressbar
else:
from tqdm import tqdm as progressbar
return progressbar
def batch_generator(X, y, batch_size=32):
"""
Generator function to generate batches of data for training/evaluation.
This function takes two tensors representing the activations and labels
respectively, and yields batches of parallel data. The last batch may
contain fewer than ``batch_size`` elements.
Parameters
----------
X : numpy.ndarray
Numpy Matrix of size [``NUM_TOKENS`` x ``NUM_NEURONS``]. Usually the
output of ``interpretation.utils.create_tensors``
y : numpy.ndarray
Numpy Vector of size [``NUM_TOKENS``] with class labels for each input
token. For classification, 0-indexed class labels for each input token
are expected. For regression, a real value per input token is expected.
Usually the output of ``interpretation.utils.create_tensors``
batch_size : int, optional
Number of samples to return in each call. Defaults to 32.
Yields
------
X_batch : numpy.ndarray
Numpy Matrix of size [``batch_size`` x ``NUM_NEURONS``]. The final batch
may have fewer elements than the requested ``batch_size``
y_batch : numpy.ndarray
Numpy Vector of size [``batch_size``]. The final batch may have fewer
elements than the requested ``batch_size``
"""
start_idx = 0
while start_idx < X.shape[0]:
yield X[start_idx : start_idx + batch_size], y[
start_idx : start_idx + batch_size
]
start_idx = start_idx + batch_size
def tok2idx(tokens):
"""
Utility function to generate unique indices for a set of tokens.
Parameters
----------
tokens : list of lists
List of sentences, where each sentence is a list of tokens. Usually
returned from ``data.loader.load_data``
Returns
-------
tok2idx_mapping : dict
A dictionary with tokens as keys and a unique index for each token as
values
"""
uniq_tokens = set().union(*tokens)
return {p: idx for idx, p in enumerate(uniq_tokens)}
def idx2tok(srcidx):
"""
Utility function to an inverse mapping from a ``tok2idx`` mapping.
Parameters
----------
tok2idx_mapping : dict
Token to index mapping, usually the output for
``interpretation.utils.tok2idx``.
Returns
-------
idx2tok : dict
A dictionary with unique indices as keys and their associated tokens as
values
"""
return {v: k for k, v in srcidx.items()}
def count_target_words(tokens):
"""
Utility function to count the total number of tokens in a dataset.
Parameters
----------
tokens : list of lists
List of sentences, where each sentence is a list of tokens. Usually
returned from ``data.loader.load_data``
Returns
-------
count : int
Total number of tokens in the given ``tokens`` structure
"""
return sum([len(t) for t in tokens["target"]])
def create_tensors(
tokens, activations, task_specific_tag, mappings=None, task_type="classification", binarized_tag = None, balance_data = False, dtype=None
):
"""
Method to pre-process loaded datasets into tensors that can be used to train
probes and perform analyis on. The input tokens are represented as list of
sentences, where each sentence is a list of tokens. Each token also has
an associated label. All tokens from all sentences are flattened into one
dimension in the returned tensors. The returned tensors will thus have
``total_num_tokens`` rows.
Parameters
----------
tokens : list of lists
List of sentences, where each sentence is a list of tokens. Usually
returned from ``data.loader.load_data``
activations : list of numpy.ndarray
List of *sentence representations*, where each *sentence representation*
is a numpy matrix of shape
``[num tokens in sentence x concatenated representation size]``. Usually
retured from ``data.loader.load_activations``
task_specific_tag : str
Label to assign tokens with unseen labels. This is particularly useful
if some labels are never seen during train, but are present in the dev
or test set. This is usually set to the majority class in the task.
mappings : list of dicts
List of four python dicts: ``label2idx``, ``idx2label``, ``src2idx`` and
``idx2src`` for classification tasks. List of two dicts ``src2idx`` and
``idx2src`` for regression tasks. Each dict represents either the
mapping from class labels to indices and source tokens to indices or
vice versa. Usually returned from a previous call to ``create_tensors``.
task_type : str
Either "classification" or "regression", indicate the kind of task that
is being probed.
binarized_tag : str, optional
Tag/Label to create binary data. All other labels in the dataset are changed
to OTHER. Defaults to None in which case the data labels are processed as-is.
balance_data : bool, optional
Whether the incoming data should be balanced. Data is balanced using
utils.balance_binary_class_data for binary data and utils.balance_multi_class_data
for multi-class data using undersampling. Defaults to False.
dtype : str, optional
None if the dtype of the activation tensor should be the same dtype as in the activations input
e.g. 'float16' or 'float32' to enforce half-precision or full-precision floats
Returns
-------
X : numpy.ndarray
Numpy Matrix of size [``NUM_TOKENS`` x ``NUM_NEURONS``]
y : numpy.ndarray
Numpy vector of size [``NUM_TOKENS``]
mappings : list of dicts
List of four python dicts: ``label2idx``, ``idx2label``, ``src2idx`` and
``idx2src`` for classification tasks. List of two dicts ``src2idx`` and
``idx2src`` for regression tasks. Each dict represents either the
mapping from class labels to indices and source tokens to indices or
vice versa.
Notes
-----
- ``mappings`` should be created exactly once, and should be reused for subsequent calls
- For example, ``mappings`` can be created on train data, and the passed during the call for dev and test data.
"""
assert (
task_type == "classification" or task_type == "regression"
), "Invalid model type"
num_tokens = count_target_words(tokens)
print("Number of tokens: ", num_tokens)
num_neurons = activations[0].shape[1]
source_tokens = tokens["source"]
target_tokens = tokens["target"]
####### creating pos and source to index and reverse
if mappings is not None:
if task_type == "classification":
label2idx, idx2label, src2idx, idx2src = mappings
else:
src2idx, idx2src = mappings
else:
if task_type == "classification":
if binarized_tag:
label2idx = {binarized_tag: 1, "OTHER": 0}
idx2label = {1: binarized_tag, 0: "OTHER"}
else:
label2idx = tok2idx(target_tokens)
idx2label = idx2tok(label2idx)
src2idx = tok2idx(source_tokens)
idx2src = idx2tok(src2idx)
print("length of source dictionary: ", len(src2idx))
if task_type == "classification":
print("length of target dictionary: ", len(label2idx))
if dtype==None:
dtype=activations[0].dtype
X = np.zeros((num_tokens, num_neurons), dtype=dtype)
if task_type=="classification":
y = np.zeros((num_tokens,), dtype=np.int)
else:
y = np.zeros((num_tokens,), dtype=np.float32)
example_set = set()
idx = 0
for instance_idx, instance in enumerate(target_tokens):
for token_idx, _ in enumerate(instance):
if idx < num_tokens:
X[idx] = activations[instance_idx][token_idx, :]
example_set.add(source_tokens[instance_idx][token_idx])
if task_type == "classification":
current_target_token = target_tokens[instance_idx][token_idx]
if binarized_tag and current_target_token != binarized_tag:
current_target_token = "OTHER"
if (
mappings is not None
and current_target_token not in label2idx
):
y[idx] = label2idx[task_specific_tag]
else:
y[idx] = label2idx[current_target_token]
elif task_type == "regression":
y[idx] = float(target_tokens[instance_idx][token_idx])
idx += 1
print(idx)
print("Total instances: %d" % (num_tokens))
print(list(example_set)[:20])
print ("Number of samples: ", X.shape[0])
if balance_data:
print ("Balancing data ... ")
if binarized_tag:
X, y = balance_binary_class_data(X, y)
else:
X, y = balance_multi_class_data(X, y)
print ("Number of samples after balancing: ", X.shape[0])
labels, freqs = np.unique(y, return_counts=True)
print ("Stats: Labels with their frequencies in the final set")
for idx, label in enumerate(labels):
print (idx2label[label], freqs[idx])
if task_type == "classification":
return X, y, (label2idx, idx2label, src2idx, idx2src)
return X, y, (src2idx, idx2src)
################################## Statictics ##################################
def print_overall_stats(all_results):
"""
Method to pretty print overall results.
.. warning::
This method was primarily written to process results from internal
scripts and pipelines.
Parameters
----------
all_results : dict
Dictionary containing the probe, overall scores, scores from selected
neurons, neuron ordering and neuron selections at various percentages
"""
probe = all_results["probe"]
weights = list(probe.parameters())[0].data.cpu()
num_neurons = weights.numpy().shape[1]
print(
"Overall accuracy: %0.02f%%"
% (100 * all_results["original_accs"]["__OVERALL__"])
)
print("")
print("Global results")
print("10% Neurons")
print(
"\tKeep Top accuracy: %0.02f%%"
% (100 * all_results["global_results"]["10%"]["keep_top_accs"]["__OVERALL__"])
)
print(
"\tKeep Random accuracy: %0.02f%%"
% (
100
* all_results["global_results"]["10%"]["keep_random_accs"]["__OVERALL__"]
)
)
print(
"\tKeep Bottom accuracy: %0.02f%%"
% (
100
* all_results["global_results"]["10%"]["keep_bottom_accs"]["__OVERALL__"]
)
)
print("15% Neurons")
print(
"\tKeep Top accuracy: %0.02f%%"
% (100 * all_results["global_results"]["15%"]["keep_top_accs"]["__OVERALL__"])
)
print(
"\tKeep Random accuracy: %0.02f%%"
% (
100
* all_results["global_results"]["15%"]["keep_random_accs"]["__OVERALL__"]
)
)
print(
"\tKeep Bottom accuracy: %0.02f%%"
% (
100
* all_results["global_results"]["15%"]["keep_bottom_accs"]["__OVERALL__"]
)
)
print("20% Neurons")
print(
"\tKeep Top accuracy: %0.02f%%"
% (100 * all_results["global_results"]["20%"]["keep_top_accs"]["__OVERALL__"])
)
print(
"\tKeep Random accuracy: %0.02f%%"
% (
100
* all_results["global_results"]["20%"]["keep_random_accs"]["__OVERALL__"]
)
)
print(
"\tKeep Bottom accuracy: %0.02f%%"
% (
100
* all_results["global_results"]["20%"]["keep_bottom_accs"]["__OVERALL__"]
)
)
print("")
print("Full order of neurons:")
print(all_results["global_results"]["ordering"])
print("--------------------")
print("")
print("Local results")
for idx, percentage in enumerate(all_results["local_results"]["percentages"]):
print("Weight Mass percentage: %d%%" % (percentage * 100))
_, top_neurons, top_neurons_per_tag = all_results["local_results"][
"local_top_neurons"
][idx]
print(
"Percentage of all neurons: %0.0f%%"
% (100 * len(top_neurons) / num_neurons)
)
print("Top Neurons:", sorted(top_neurons))
print("")
print("Top neurons per tag:")
for tag in top_neurons_per_tag:
print("\t" + tag + ":", sorted(top_neurons_per_tag[tag]))
print("")
def print_machine_stats(all_results):
"""
Method to print overall results in tsv format.
.. warning::
This method was primarily written to process results from internal
scripts and pipelines.
Parameters
----------
all_results : dict
Dictionary containing the probe, overall scores, scores from selected
neurons, neuron ordering and neuron selections at various percentages
"""
probe = all_results["probe"]
weights = list(probe.parameters())[0].data.cpu()
num_neurons = weights.numpy().shape[1]
print("Filtering out:")
print(
"%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%s"
% (
100 * all_results["original_accs"]["__OVERALL__"],
100 * all_results["global_results"]["10%"]["keep_top_accs"]["__OVERALL__"],
100
* all_results["global_results"]["10%"]["keep_random_accs"]["__OVERALL__"],
100
* all_results["global_results"]["10%"]["keep_bottom_accs"]["__OVERALL__"],
100 * all_results["global_results"]["15%"]["keep_top_accs"]["__OVERALL__"],
100
* all_results["global_results"]["15%"]["keep_random_accs"]["__OVERALL__"],
100
* all_results["global_results"]["15%"]["keep_bottom_accs"]["__OVERALL__"],
100 * all_results["global_results"]["20%"]["keep_top_accs"]["__OVERALL__"],
100
* all_results["global_results"]["20%"]["keep_random_accs"]["__OVERALL__"],
100
* all_results["global_results"]["20%"]["keep_bottom_accs"]["__OVERALL__"],
str(all_results["global_results"]["ordering"][:300]),
)
)
print("\nZero out:")
print(
"%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f"
% (
100 * all_results["original_accs"]["__OVERALL__"],
100
* all_results["global_results"]["10%"]["zero_out_top_accs"]["__OVERALL__"],
100
* all_results["global_results"]["10%"]["zero_out_random_accs"][
"__OVERALL__"
],
100
* all_results["global_results"]["10%"]["zero_out_bottom_accs"][
"__OVERALL__"
],
100
* all_results["global_results"]["15%"]["zero_out_top_accs"]["__OVERALL__"],
100
* all_results["global_results"]["15%"]["zero_out_random_accs"][
"__OVERALL__"
],
100
* all_results["global_results"]["15%"]["zero_out_bottom_accs"][
"__OVERALL__"
],
100
* all_results["global_results"]["20%"]["zero_out_top_accs"]["__OVERALL__"],
100
* all_results["global_results"]["20%"]["zero_out_random_accs"][
"__OVERALL__"
],
100
* all_results["global_results"]["20%"]["zero_out_bottom_accs"][
"__OVERALL__"
],
)
)
for idx, percentage in enumerate(all_results["local_results"]["percentages"]):
print("\nLocal %d%%:" % (percentage * 100))
top_neurons = all_results["local_results"]["local_top_neurons"][idx][1]
top_neurons_per_tag = all_results["local_results"]["local_top_neurons"][idx][2]
top_neurons_per_tag_list = {k: list(v) for k, v in top_neurons_per_tag.items()}
print(
"%0.2f%%\t%s\t%s"
% (
100 * len(top_neurons) / num_neurons,
str(sorted(top_neurons)),
str(top_neurons_per_tag_list),
)
)
################################ Data Balancing ################################
def balance_binary_class_data(X, y):
"""
Method to balance binary class data.
.. note::
The majority class is under-sampled randomly to match the minority class
in it's size.
Parameters
----------
X : numpy.ndarray
Numpy Matrix of size [``NUM_TOKENS`` x ``NUM_NEURONS``]. Usually
returned from ``interpretation.utils.create_tensors``
y : numpy.ndarray
Numpy vector of size [``NUM_TOKENS``]. Usually returned from
``interpretation.utils.create_tensors``
Returns
-------
X_balanced : numpy.ndarray
Numpy matrix of size [``NUM_BALANCED_TOKENS`` x ``NUM_NEURONS``]
y_balanced : numpy.ndarray
Numpy vector of size [``NUM_BALANCED_TOKENS``]
"""
rus = RandomUnderSampler()
X_res, y_res = rus.fit_resample(X, y)
return X_res, y_res
def balance_multi_class_data(X, y, num_required_instances=None):
"""
Method to balance multi class data.
.. note::
All classes are under-sampled randomly to match the minority class in
their size. If ``num_required_instances`` is provided, all classes are
sampled proportionally so that the total number of selected examples is
approximately ``num_required_instances`` (because of rounding proportions).
Parameters
----------
X : numpy.ndarray
Numpy Matrix of size [``NUM_TOKENS`` x ``NUM_NEURONS``]. Usually
returned from ``interpretation.utils.create_tensors``
y : numpy.ndarray
Numpy vector of size [``NUM_TOKENS``]. Usually returned from
``interpretation.utils.create_tensors``
num_required_instances : int, optional
Total number of required instances. All classes are sampled
proportionally.
Returns
-------
X_balanced : numpy.ndarray
Numpy matrix of size [``NUM_BALANCED_TOKENS`` x ``NUM_NEURONS``]
y_balanced : numpy.ndarray
Numpy vector of size [``NUM_BALANCED_TOKENS``]
"""
if num_required_instances:
total = y.shape[0]
unique, counts = np.unique(y, return_counts=True)
class_counts = dict(zip(unique, counts))
num_instances_per_class = {
key: math.ceil(count / total * num_required_instances)
for key, count in class_counts.items()
}
print(num_instances_per_class)
rus = RandomUnderSampler(sampling_strategy=num_instances_per_class)
else:
rus = RandomUnderSampler()
X_res, y_res = rus.fit_resample(X, y)
return X_res, y_res
def load_probe(probe_path):
"""
Loads a probe and its associated mappings from probe_path
.. warning::
This method is currently not implemented.
Parameters
----------
probe_path : str
Path to a pkl object saved by interpretation.utils.save_probe
Returns
-------
probe : interpretation.linear_probe.LinearProbe
Trained probe model
mappings : list of dicts
List of four python dicts: ``label2idx``, ``idx2label``, ``src2idx`` and
``idx2src`` for classification tasks. List of two dicts ``src2idx`` and
``idx2src`` for regression tasks. Each dict represents either the
mapping from class labels to indices and source tokens to indices or
vice versa.
"""
pass
def save_probe(probe_path, probe, mappings):
"""
Saves a model and its associated mappings as a pkl object at probe_path
.. warning::
This method is currently not implemented.
Parameters
----------
probe_path : str
Path to save a pkl object
probe : interpretation.linear_probe.LinearProbe
Trained probe model
mappings : list of dicts
List of four python dicts: ``label2idx``, ``idx2label``, ``src2idx`` and
``idx2src`` for classification tasks. List of two dicts ``src2idx`` and
``idx2src`` for regression tasks. Each dict represents either the
mapping from class labels to indices and source tokens to indices or
vice versa.
"""
pass | 34.9632 | 141 | 0.610608 | import math
import numpy as np
from imblearn.under_sampling import RandomUnderSampler
def isnotebook():
try:
shell = get_ipython().__class__.__name__
if shell == "ZMQInteractiveShell":
return True
elif shell == "TerminalInteractiveShell":
return False
else:
return False
except NameError:
return False
def get_progress_bar():
if isnotebook():
from tqdm import tqdm_notebook as progressbar
else:
from tqdm import tqdm as progressbar
return progressbar
def batch_generator(X, y, batch_size=32):
start_idx = 0
while start_idx < X.shape[0]:
yield X[start_idx : start_idx + batch_size], y[
start_idx : start_idx + batch_size
]
start_idx = start_idx + batch_size
def tok2idx(tokens):
uniq_tokens = set().union(*tokens)
return {p: idx for idx, p in enumerate(uniq_tokens)}
def idx2tok(srcidx):
return {v: k for k, v in srcidx.items()}
def count_target_words(tokens):
return sum([len(t) for t in tokens["target"]])
def create_tensors(
tokens, activations, task_specific_tag, mappings=None, task_type="classification", binarized_tag = None, balance_data = False, dtype=None
):
assert (
task_type == "classification" or task_type == "regression"
), "Invalid model type"
num_tokens = count_target_words(tokens)
print("Number of tokens: ", num_tokens)
num_neurons = activations[0].shape[1]
source_tokens = tokens["source"]
target_tokens = tokens["target"]
label2idx = {binarized_tag: 1, "OTHER": 0}
idx2label = {1: binarized_tag, 0: "OTHER"}
else:
label2idx = tok2idx(target_tokens)
idx2label = idx2tok(label2idx)
src2idx = tok2idx(source_tokens)
idx2src = idx2tok(src2idx)
print("length of source dictionary: ", len(src2idx))
if task_type == "classification":
print("length of target dictionary: ", len(label2idx))
if dtype==None:
dtype=activations[0].dtype
X = np.zeros((num_tokens, num_neurons), dtype=dtype)
if task_type=="classification":
y = np.zeros((num_tokens,), dtype=np.int)
else:
y = np.zeros((num_tokens,), dtype=np.float32)
example_set = set()
idx = 0
for instance_idx, instance in enumerate(target_tokens):
for token_idx, _ in enumerate(instance):
if idx < num_tokens:
X[idx] = activations[instance_idx][token_idx, :]
example_set.add(source_tokens[instance_idx][token_idx])
if task_type == "classification":
current_target_token = target_tokens[instance_idx][token_idx]
if binarized_tag and current_target_token != binarized_tag:
current_target_token = "OTHER"
if (
mappings is not None
and current_target_token not in label2idx
):
y[idx] = label2idx[task_specific_tag]
else:
y[idx] = label2idx[current_target_token]
elif task_type == "regression":
y[idx] = float(target_tokens[instance_idx][token_idx])
idx += 1
print(idx)
print("Total instances: %d" % (num_tokens))
print(list(example_set)[:20])
print ("Number of samples: ", X.shape[0])
if balance_data:
print ("Balancing data ... ")
if binarized_tag:
X, y = balance_binary_class_data(X, y)
else:
X, y = balance_multi_class_data(X, y)
print ("Number of samples after balancing: ", X.shape[0])
labels, freqs = np.unique(y, return_counts=True)
print ("Stats: Labels with their frequencies in the final set")
for idx, label in enumerate(labels):
print (idx2label[label], freqs[idx])
if task_type == "classification":
return X, y, (label2idx, idx2label, src2idx, idx2src)
return X, y, (src2idx, idx2src)
print("\t" + tag + ":", sorted(top_neurons_per_tag[tag]))
print("")
def print_machine_stats(all_results):
probe = all_results["probe"]
weights = list(probe.parameters())[0].data.cpu()
num_neurons = weights.numpy().shape[1]
print("Filtering out:")
print(
"%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%s"
% (
100 * all_results["original_accs"]["__OVERALL__"],
100 * all_results["global_results"]["10%"]["keep_top_accs"]["__OVERALL__"],
100
* all_results["global_results"]["10%"]["keep_random_accs"]["__OVERALL__"],
100
* all_results["global_results"]["10%"]["keep_bottom_accs"]["__OVERALL__"],
100 * all_results["global_results"]["15%"]["keep_top_accs"]["__OVERALL__"],
100
* all_results["global_results"]["15%"]["keep_random_accs"]["__OVERALL__"],
100
* all_results["global_results"]["15%"]["keep_bottom_accs"]["__OVERALL__"],
100 * all_results["global_results"]["20%"]["keep_top_accs"]["__OVERALL__"],
100
* all_results["global_results"]["20%"]["keep_random_accs"]["__OVERALL__"],
100
* all_results["global_results"]["20%"]["keep_bottom_accs"]["__OVERALL__"],
str(all_results["global_results"]["ordering"][:300]),
)
)
print("\nZero out:")
print(
"%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f"
% (
100 * all_results["original_accs"]["__OVERALL__"],
100
* all_results["global_results"]["10%"]["zero_out_top_accs"]["__OVERALL__"],
100
* all_results["global_results"]["10%"]["zero_out_random_accs"][
"__OVERALL__"
],
100
* all_results["global_results"]["10%"]["zero_out_bottom_accs"][
"__OVERALL__"
],
100
* all_results["global_results"]["15%"]["zero_out_top_accs"]["__OVERALL__"],
100
* all_results["global_results"]["15%"]["zero_out_random_accs"][
"__OVERALL__"
],
100
* all_results["global_results"]["15%"]["zero_out_bottom_accs"][
"__OVERALL__"
],
100
* all_results["global_results"]["20%"]["zero_out_top_accs"]["__OVERALL__"],
100
* all_results["global_results"]["20%"]["zero_out_random_accs"][
"__OVERALL__"
],
100
* all_results["global_results"]["20%"]["zero_out_bottom_accs"][
"__OVERALL__"
],
)
)
for idx, percentage in enumerate(all_results["local_results"]["percentages"]):
print("\nLocal %d%%:" % (percentage * 100))
top_neurons = all_results["local_results"]["local_top_neurons"][idx][1]
top_neurons_per_tag = all_results["local_results"]["local_top_neurons"][idx][2]
top_neurons_per_tag_list = {k: list(v) for k, v in top_neurons_per_tag.items()}
print(
"%0.2f%%\t%s\t%s"
% (
100 * len(top_neurons) / num_neurons,
str(sorted(top_neurons)),
str(top_neurons_per_tag_list),
)
)
| true | true |
1c2e478bdfe0ea24a0b1714571dfbbe8815e468a | 6,584 | py | Python | share/common/utils/restcall.py | onap/multicloud-openstack | d0e41eb1b1a1cb79365836da728908ed26253db4 | [
"CC-BY-4.0"
] | 4 | 2018-10-24T15:20:14.000Z | 2020-03-09T06:29:11.000Z | share/common/utils/restcall.py | onap/multicloud-openstack | d0e41eb1b1a1cb79365836da728908ed26253db4 | [
"CC-BY-4.0"
] | null | null | null | share/common/utils/restcall.py | onap/multicloud-openstack | d0e41eb1b1a1cb79365836da728908ed26253db4 | [
"CC-BY-4.0"
] | 2 | 2020-08-03T13:45:44.000Z | 2021-09-15T21:10:26.000Z | # Copyright (c) 2017-2018 Wind River Systems, 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.
import six
import base64
import codecs
import json
import traceback
import sys
import logging
from six.moves import urllib
import httplib2
import uuid
from rest_framework import status
from django.conf import settings
from common.utils import aai_cache
rest_no_auth, rest_oneway_auth, rest_bothway_auth = 0, 1, 2
HTTP_200_OK, HTTP_201_CREATED = '200', '201'
HTTP_204_NO_CONTENT, HTTP_202_ACCEPTED = '204', '202'
status_ok_list = [HTTP_200_OK, HTTP_201_CREATED,
HTTP_204_NO_CONTENT, HTTP_202_ACCEPTED]
HTTP_404_NOTFOUND, HTTP_403_FORBIDDEN = '404', '403'
HTTP_401_UNAUTHORIZED, HTTP_400_BADREQUEST = '401', '400'
MAX_RETRY_TIME = 3
logger = logging.getLogger(__name__)
def _call_req(base_url, user, passwd, auth_type,
resource, method, extra_headers='', content=''):
callid = str(uuid.uuid1())
ret = None
resp_status = None
try:
full_url = _combine_url(base_url, resource)
headers = {
'content-type': 'application/json',
'accept': 'application/json'
}
if extra_headers:
headers.update(extra_headers)
# if user:
# headers['Authorization'] = \
# 'Basic ' + str(codecs.encode('%s:%s' % (user, passwd), "ascii"))
if user:
tmpauthsource = '%s:%s' % (user, passwd)
if six.PY3:
tmpauthsource = tmpauthsource.encode('utf-8')
headers['Authorization'] = 'Basic ' + \
base64.b64encode(tmpauthsource).decode('utf-8')
logger.info("Making rest call with method, uri, header = %s, %s, %s" %
(method.upper(), full_url, headers))
if content:
logger.debug("with content = %s" % content)
ca_certs = None
for retry_times in range(MAX_RETRY_TIME):
http = httplib2.Http(
ca_certs=ca_certs,
disable_ssl_certificate_validation=(auth_type == rest_no_auth))
http.follow_all_redirects = True
try:
resp, resp_content = http.request(full_url,
method=method.upper(),
body=content,
headers=headers)
resp_status, resp_body = \
resp['status'], codecs.decode(
resp_content, 'UTF-8') if resp_content else None
if resp_status in status_ok_list:
ret = [0, resp_body, resp_status]
else:
ret = [1, resp_body, resp_status]
break
except Exception as ex:
if 'httplib.ResponseNotReady' in str(sys.exc_info()):
logger.debug("retry_times=%d", retry_times)
logger.error(traceback.format_exc())
ret = [1, "Unable to connect to %s" % full_url, resp_status]
continue
raise ex
logger.info("Rest call finished with status = %s", resp_status)
logger.debug("with response content = %s" % resp_body)
except urllib.error.URLError as err:
logger.error("status=%s, error message=%s" % (resp_status, str(err)))
ret = [2, str(err), resp_status]
except Exception:
logger.error(traceback.format_exc())
logger.error("[%s]ret=%s" % (callid, str(sys.exc_info())))
if not resp_status:
resp_status = status.HTTP_500_INTERNAL_SERVER_ERROR
ret = [3, str(sys.exc_info()), resp_status]
except:
logger.error(traceback.format_exc())
if not resp_status:
resp_status = status.HTTP_500_INTERNAL_SERVER_ERROR
ret = [4, str(sys.exc_info()), resp_status]
return ret
def req_by_msb(resource, method, content=''):
base_url = "%s://%s:%s/" % (
settings.MSB_SERVICE_PROTOCOL, settings.MSB_SERVICE_ADDR, settings.MSB_SERVICE_PORT)
return _call_req(base_url, "", "", rest_no_auth,
resource, method, "", content)
def req_to_vim(base_url, resource, method, extra_headers='', content=''):
return _call_req(base_url, "", "", rest_no_auth,
resource, method, extra_headers, content)
def req_to_aai(resource, method, content='', appid=settings.MULTICLOUD_APP_ID, nocache=False):
tmp_trasaction_id = '9003' #str(uuid.uuid1())
headers = {
'X-FromAppId': appid,
'X-TransactionId': tmp_trasaction_id,
'content-type': 'application/json',
'accept': 'application/json'
}
# hook to flush cache
if method.upper() in ["PUT", "POST", "PATCH", "DELETE"]:
aai_cache.flush_cache_by_url(resource)
elif method.upper() in ["GET"]:
if not nocache:
content = aai_cache.get_cache_by_url(resource)
# logger.debug("cached resource: %s, %s" % (resource, content))
if content:
return content
else:
# flush possible cached data blindly
aai_cache.flush_cache_by_url(resource)
ret, resp_body, resp_status = _call_req(
settings.AAI_BASE_URL, settings.AAI_USERNAME, settings.AAI_PASSWORD, rest_no_auth,
resource, method, content=json.dumps(content), extra_headers=headers)
if method.upper() in ["GET"] and ret == 0 and not nocache:
# aai_cache.set_cache_by_url(resource, [ret, resp_body, resp_status])
aai_cache.set_cache_by_url(resource, (ret, resp_body, resp_status))
return [ret, resp_body, resp_status]
def _combine_url(base_url, resource):
full_url = None
if not resource:
return base_url
if base_url.endswith('/') and resource.startswith('/'):
full_url = base_url[:-1] + resource
elif base_url.endswith('/') and not resource.startswith('/'):
full_url = base_url + resource
elif not base_url.endswith('/') and resource.startswith('/'):
full_url = base_url + resource
else:
full_url = base_url + '/' + resource
return full_url
| 36.782123 | 94 | 0.609356 |
import six
import base64
import codecs
import json
import traceback
import sys
import logging
from six.moves import urllib
import httplib2
import uuid
from rest_framework import status
from django.conf import settings
from common.utils import aai_cache
rest_no_auth, rest_oneway_auth, rest_bothway_auth = 0, 1, 2
HTTP_200_OK, HTTP_201_CREATED = '200', '201'
HTTP_204_NO_CONTENT, HTTP_202_ACCEPTED = '204', '202'
status_ok_list = [HTTP_200_OK, HTTP_201_CREATED,
HTTP_204_NO_CONTENT, HTTP_202_ACCEPTED]
HTTP_404_NOTFOUND, HTTP_403_FORBIDDEN = '404', '403'
HTTP_401_UNAUTHORIZED, HTTP_400_BADREQUEST = '401', '400'
MAX_RETRY_TIME = 3
logger = logging.getLogger(__name__)
def _call_req(base_url, user, passwd, auth_type,
resource, method, extra_headers='', content=''):
callid = str(uuid.uuid1())
ret = None
resp_status = None
try:
full_url = _combine_url(base_url, resource)
headers = {
'content-type': 'application/json',
'accept': 'application/json'
}
if extra_headers:
headers.update(extra_headers)
if user:
tmpauthsource = '%s:%s' % (user, passwd)
if six.PY3:
tmpauthsource = tmpauthsource.encode('utf-8')
headers['Authorization'] = 'Basic ' + \
base64.b64encode(tmpauthsource).decode('utf-8')
logger.info("Making rest call with method, uri, header = %s, %s, %s" %
(method.upper(), full_url, headers))
if content:
logger.debug("with content = %s" % content)
ca_certs = None
for retry_times in range(MAX_RETRY_TIME):
http = httplib2.Http(
ca_certs=ca_certs,
disable_ssl_certificate_validation=(auth_type == rest_no_auth))
http.follow_all_redirects = True
try:
resp, resp_content = http.request(full_url,
method=method.upper(),
body=content,
headers=headers)
resp_status, resp_body = \
resp['status'], codecs.decode(
resp_content, 'UTF-8') if resp_content else None
if resp_status in status_ok_list:
ret = [0, resp_body, resp_status]
else:
ret = [1, resp_body, resp_status]
break
except Exception as ex:
if 'httplib.ResponseNotReady' in str(sys.exc_info()):
logger.debug("retry_times=%d", retry_times)
logger.error(traceback.format_exc())
ret = [1, "Unable to connect to %s" % full_url, resp_status]
continue
raise ex
logger.info("Rest call finished with status = %s", resp_status)
logger.debug("with response content = %s" % resp_body)
except urllib.error.URLError as err:
logger.error("status=%s, error message=%s" % (resp_status, str(err)))
ret = [2, str(err), resp_status]
except Exception:
logger.error(traceback.format_exc())
logger.error("[%s]ret=%s" % (callid, str(sys.exc_info())))
if not resp_status:
resp_status = status.HTTP_500_INTERNAL_SERVER_ERROR
ret = [3, str(sys.exc_info()), resp_status]
except:
logger.error(traceback.format_exc())
if not resp_status:
resp_status = status.HTTP_500_INTERNAL_SERVER_ERROR
ret = [4, str(sys.exc_info()), resp_status]
return ret
def req_by_msb(resource, method, content=''):
base_url = "%s://%s:%s/" % (
settings.MSB_SERVICE_PROTOCOL, settings.MSB_SERVICE_ADDR, settings.MSB_SERVICE_PORT)
return _call_req(base_url, "", "", rest_no_auth,
resource, method, "", content)
def req_to_vim(base_url, resource, method, extra_headers='', content=''):
return _call_req(base_url, "", "", rest_no_auth,
resource, method, extra_headers, content)
def req_to_aai(resource, method, content='', appid=settings.MULTICLOUD_APP_ID, nocache=False):
tmp_trasaction_id = '9003'
headers = {
'X-FromAppId': appid,
'X-TransactionId': tmp_trasaction_id,
'content-type': 'application/json',
'accept': 'application/json'
}
if method.upper() in ["PUT", "POST", "PATCH", "DELETE"]:
aai_cache.flush_cache_by_url(resource)
elif method.upper() in ["GET"]:
if not nocache:
content = aai_cache.get_cache_by_url(resource)
if content:
return content
else:
aai_cache.flush_cache_by_url(resource)
ret, resp_body, resp_status = _call_req(
settings.AAI_BASE_URL, settings.AAI_USERNAME, settings.AAI_PASSWORD, rest_no_auth,
resource, method, content=json.dumps(content), extra_headers=headers)
if method.upper() in ["GET"] and ret == 0 and not nocache:
aai_cache.set_cache_by_url(resource, (ret, resp_body, resp_status))
return [ret, resp_body, resp_status]
def _combine_url(base_url, resource):
full_url = None
if not resource:
return base_url
if base_url.endswith('/') and resource.startswith('/'):
full_url = base_url[:-1] + resource
elif base_url.endswith('/') and not resource.startswith('/'):
full_url = base_url + resource
elif not base_url.endswith('/') and resource.startswith('/'):
full_url = base_url + resource
else:
full_url = base_url + '/' + resource
return full_url
| true | true |
1c2e47c00a8520777c086214fe06e3a52f73817f | 21,859 | py | Python | readtwice/models/trivia_qa/preprocess_lib.py | shaun95/google-research | d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5 | [
"Apache-2.0"
] | 1 | 2022-03-13T21:48:52.000Z | 2022-03-13T21:48:52.000Z | readtwice/models/trivia_qa/preprocess_lib.py | shaun95/google-research | d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5 | [
"Apache-2.0"
] | null | null | null | readtwice/models/trivia_qa/preprocess_lib.py | shaun95/google-research | d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5 | [
"Apache-2.0"
] | 1 | 2022-03-30T07:20:29.000Z | 2022-03-30T07:20:29.000Z | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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.
"""Preprocessing for TriviaQA data."""
import json
import os
import re
import string
from typing import Any, Iterator, List, Optional, Set, Text, Tuple
import apache_beam as beam
from apache_beam import metrics
import dataclasses
import nltk
import tensorflow.compat.v1 as tf
from readtwice.data_utils import beam_utils
from readtwice.data_utils import data_utils
from readtwice.data_utils import tokenization
from readtwice.models.trivia_qa import evaluation
METRICS_NAMESPACE = 'read_it_twice.trivia_qa'
@dataclasses.dataclass(frozen=True)
class Question(object):
id: int
question_id: Text
value: Text
@dataclasses.dataclass(frozen=True)
class EvidenceInfo(object):
id: Text
source: Text
title: Text
@dataclasses.dataclass(frozen=True)
class Evidence(object):
info: EvidenceInfo
text: Text
@dataclasses.dataclass(frozen=True)
class Answer(object):
"""Class represents answer for the question."""
value: Text
aliases: List[Text]
normalized_aliases: List[Text]
def _alias_answer(self, answer, include=None):
alias = answer.replace('_', ' ').lower()
exclude = set(string.punctuation + ''.join(['‘', '’', '´', '`']))
include = include or []
alias = ''.join(
c if c not in exclude or c in include else ' ' for c in alias)
return ' '.join(alias.split()).strip()
def make_answer_set(self):
"""Apply less aggressive normalization to the answer aliases."""
answers = []
for alias in [self.value] + self.aliases:
answers.append(self._alias_answer(alias))
answers.append(self._alias_answer(alias, [',', '.']))
answers.append(self._alias_answer(alias, ['-']))
answers.append(self._alias_answer(alias, [',', '.', '-']))
answers.append(self._alias_answer(alias, string.punctuation))
answers = set(answers + self.normalized_aliases)
# Filter out empty or all-whitespace strings
answers = {answer for answer in answers if answer.strip()}
return answers
@dataclasses.dataclass(frozen=True)
class QuestionAnswer(object):
"""Single record in TriviaQA dataset."""
question: Question
evidence_info: List[EvidenceInfo]
answer: Optional[Answer] = None
@classmethod
def from_dict(cls, idx, datum):
"""Create `QuestionAnswer` object from a dictionary."""
question = Question(
id=idx, question_id=datum['QuestionId'], value=datum['Question'])
if 'Answer' in datum:
answer = Answer(
value=datum['Answer']['Value'],
aliases=datum['Answer']['Aliases'],
normalized_aliases=datum['Answer']['NormalizedAliases'])
else:
answer = None
evidence_info = []
for key in ['EntityPages', 'SearchResults']:
for document in datum.get(key, []):
evidence_info.append(
EvidenceInfo(
id=document['Filename'], title=document['Title'], source=key))
return cls(question=question, evidence_info=evidence_info, answer=answer)
class EnhancedJSONEncoder(json.JSONEncoder):
def default(self, o):
if dataclasses.is_dataclass(o):
return dataclasses.asdict(o)
return super().default(o)
@dataclasses.dataclass
class QuestionAnswerEvidence(object):
question: Question
evidence: List[Evidence]
answer: Optional[Answer] = None
def to_json(self):
return json.dumps(self, cls=EnhancedJSONEncoder)
@dataclasses.dataclass
class FilteredAnnotation(object):
question: Question
answer: Answer
annotation: Text
sentence: Text
def __str__(self):
return '%s\t%s\t%s\t%s' % (
self.question.question_id, self.answer.value, self.annotation,
self.sentence.replace(tokenization.SPIECE_UNDERLINE, ' '))
class MakeExampleOutput(object):
SUCCESS = None
SUCCESS_FILTERED_ANNOTATIONS = 'success_filtered_annotations'
NO_ANSWER = 'no_answer'
NO_ANSWER_TOKENIZED = 'no_answer_tokenized'
NO_ANSWER_TOKENIZED_FILTERED_ANNOTATIONS = 'no_answer_tokenized_filtered_annotations'
TOO_MANY_ANSWERS = 'too_many_answers'
def read_question_answer_json(json_path):
with tf.io.gfile.GFile(json_path) as f:
data = json.load(f)['Data']
# Note that document IDs start from 1. We keep 0 as an ID of an empty document
return [
QuestionAnswer.from_dict(idx + 1, datum) for idx, datum in enumerate(data)
]
class ReadEvidence(beam.DoFn):
"""Read evidence from Wikipedia and/or Web files."""
def __init__(self, wikipedia_dir, web_dir):
self.wikipedia_dir = wikipedia_dir
self.web_dir = web_dir
def process(
self,
question_answer):
evidence = []
for info in question_answer.evidence_info:
if info.source == 'EntityPages':
evidence_path = os.path.join(self.wikipedia_dir, info.id)
elif info.source == 'SearchResult':
evidence_path = os.path.join(self.web_dir, info.id)
else:
raise ValueError(f'Unknown evidence source: {info.source}.')
with tf.io.gfile.GFile(evidence_path, 'rb') as f:
text = f.read().decode('utf-8')
evidence.append(Evidence(info=info, text=text))
if not evidence:
raise ValueError('Question %s does not have evidence.' %
str(question_answer))
metrics.Metrics.counter(METRICS_NAMESPACE, 'ReadEvidence.questions').inc()
metrics.Metrics.distribution(METRICS_NAMESPACE,
'ReadEvidence.num_evidence').update(
len(evidence))
yield QuestionAnswerEvidence(
question=question_answer.question,
evidence=evidence,
answer=question_answer.answer)
# TODO(urikz): Potentially, we should filter out all intersecting
# annotations and try to pick only, for example, the largest ones
def find_answer_annotations(
text, answer_set):
"""Find answer annotations."""
annotations = []
for answer in answer_set:
# We use regex matching to search for the answer for two reasons:
# (1) We want to ignore case (so `flags=re.IGNORECASE`)
# (2) We want to the space and the hyphen to be treated as the same token.
# Sometimes the answer is "TSR 2", but the actual text contains only "TSR-2"
#
# Note that we have to espace -- `re.escape(answer)` -- because the answer
# can contain parentheses, etc.
# Finally, to accommodate (2) we replace spaces ('\\ ' due to escaping)
# with a group '[ -]'.
answer_regex = re.compile(
re.escape(answer).replace('\\ ', '[ -]'), flags=re.IGNORECASE)
for match in re.finditer(answer_regex, text):
if not answer.strip() or match.end() == 0:
raise ValueError('Invalid answer string "%s" from answer set %s' %
(answer, str(answer_set)))
annotations.append(
data_utils.Annotation(
begin=match.start(), end=match.end() - 1, text=match.group(0)))
return sorted(annotations)
class MakeExamples(beam.DoFn):
"""Function to make tf.train.Examples."""
def __init__(self, spm_model_path, num_blocks_per_example,
block_overlap_length, block_length,
max_num_annotations_per_block, padding_token_id,
cls_token_id, sep_token_id, generate_answers,
nltk_data_path):
self.spm_model_path = spm_model_path
self.num_blocks_per_example = num_blocks_per_example
self.block_overlap_length = block_overlap_length
self.block_length = block_length
self.max_num_annotations_per_block = max_num_annotations_per_block
self.padding_token_id = padding_token_id
self.cls_token_id = cls_token_id
self.sep_token_id = sep_token_id
self.generate_answers = generate_answers
self.nltk_data_path = nltk_data_path
nltk.data.path.append(self.nltk_data_path)
def setup(self):
nltk.data.path.append(self.nltk_data_path)
self.tokenizer = tokenization.FullTokenizer(
spm_model_file=self.spm_model_path)
self.nltk_tokenizer = nltk.TreebankWordTokenizer()
self.nltk_pos_types = {'PERSON', 'ORGANIZATION', 'FACILITY', 'GPE', 'GSP'}
def process(
self, question_answer_evidence):
metrics.Metrics.counter(METRICS_NAMESPACE, 'num_questions').inc()
if self.generate_answers:
answer_set = question_answer_evidence.answer.make_answer_set()
sentences = []
for sentence in self._split_into_sentences(
question_answer_evidence.evidence):
sentence_obj = self._annotate_entities(sentence)
metrics.Metrics.counter(METRICS_NAMESPACE, 'nltk_entities').inc(
sentence_obj.num_annotations(1))
if self.generate_answers:
annotations = find_answer_annotations(sentence_obj.text, answer_set)
sentence_obj.annotations.extend(annotations)
sentences.append(sentence_obj)
big_document = data_utils.BertDocument(
sentences=sentences, document_id=question_answer_evidence.question.id)
metrics.Metrics.distribution(METRICS_NAMESPACE,
'doc_length_per_question').update(
big_document.num_characters())
if self.generate_answers:
num_annotations = big_document.num_annotations(0)
metrics.Metrics.distribution(
METRICS_NAMESPACE,
'num_annotations_per_question').update(num_annotations)
if num_annotations == 0:
metrics.Metrics.counter(
METRICS_NAMESPACE,
'make_example_status.answer_span_not_found').inc()
yield beam.pvalue.TaggedOutput(MakeExampleOutput.NO_ANSWER,
question_answer_evidence.to_json())
return
tokenized_big_document = data_utils.tokenize_document_for_bert(
big_document, self.tokenizer)
metrics.Metrics.distribution(METRICS_NAMESPACE,
'tokenized_doc_length_per_question').update(
tokenized_big_document.num_tokens())
tokenized_question = self._tokenize_question(
question_answer_evidence.question.value)
metrics.Metrics.distribution(METRICS_NAMESPACE, 'question_length').update(
len(tokenized_question))
filtered_annotations = []
if self.generate_answers:
for i, sentence in enumerate(tokenized_big_document.sentences):
(should_update, annotations,
current_filtered_annotations) = self._verify_annotations(
sentence.annotations, answer_set)
if should_update:
tokenized_big_document.sentences[i].annotations = annotations
# pylint: disable=g-complex-comprehension
filtered_annotations.extend([
FilteredAnnotation(
question=question_answer_evidence.question,
answer=question_answer_evidence.answer,
annotation=annotation,
sentence=''.join(sentence.tokens))
for annotation in current_filtered_annotations
])
metrics.Metrics.counter(METRICS_NAMESPACE,
'num_filtered_annotations').inc(
len(current_filtered_annotations))
num_annotations = tokenized_big_document.num_annotations(0)
metrics.Metrics.distribution(
METRICS_NAMESPACE,
'num_annotations_tokenized_per_question').update(num_annotations)
if num_annotations == 0:
metrics.Metrics.counter(
METRICS_NAMESPACE,
'make_example_status.answer_not_found_tokenized').inc()
yield beam.pvalue.TaggedOutput(MakeExampleOutput.NO_ANSWER_TOKENIZED,
question_answer_evidence.to_json())
yield beam.pvalue.TaggedOutput(
MakeExampleOutput.NO_ANSWER_TOKENIZED_FILTERED_ANNOTATIONS,
filtered_annotations)
return
else:
approx_num_blocks = (
tokenized_big_document.num_tokens() /
(self.block_length - self.block_overlap_length -
len(tokenized_question)))
if num_annotations > self.max_num_annotations_per_block * approx_num_blocks:
metrics.Metrics.counter(METRICS_NAMESPACE,
'num_questions_with_too_many_answers').inc()
yield beam.pvalue.TaggedOutput(MakeExampleOutput.TOO_MANY_ANSWERS,
question_answer_evidence.to_json())
yield beam.pvalue.TaggedOutput(
MakeExampleOutput.SUCCESS_FILTERED_ANNOTATIONS,
filtered_annotations)
tokenized_documents = data_utils.split_tokenized_documents(
tokenized_big_document,
max_tokens=self._get_max_tokens_per_raw_doc(len(tokenized_question)),
max_sentences=None)
metrics.Metrics.distribution(METRICS_NAMESPACE,
'num_examples_per_question').update(
len(tokenized_documents))
if len(tokenized_documents) > 1:
metrics.Metrics.counter(METRICS_NAMESPACE, 'num_too_large_evidence').inc()
for tokenized_document in tokenized_documents:
if self.generate_answers and tokenized_document.num_annotations(0) == 0:
metrics.Metrics.counter(
METRICS_NAMESPACE,
'make_example_status.answer_not_found_splitted').inc()
continue
metrics.Metrics.counter(METRICS_NAMESPACE, 'num_examples').inc()
yield tokenized_document.to_tf_strided_large_example(
overlap_length=self.block_overlap_length,
block_length=self.block_length,
padding_token_id=self.padding_token_id,
prefix_token_ids=tokenized_question,
max_num_annotations=self.max_num_annotations_per_block)
metrics.Metrics.counter(METRICS_NAMESPACE,
'make_example_status.success').inc()
def _split_into_sentences(self, evidences):
for evidence in evidences:
for line in evidence.text.strip().split('\n'):
line_stripped = line.strip()
if line_stripped:
yield line_stripped
def _annotate_entities(self, text):
spans = list(self.nltk_tokenizer.span_tokenize(text))
tokens = [text[b:e] for (b, e) in spans]
annotations = []
trees = nltk.ne_chunk(nltk.pos_tag(tokens))
start_index = 0
for tree in trees:
if hasattr(tree, 'label'):
children = [text for text, pos in tree]
end_index = start_index + len(children)
if tree.label() in self.nltk_pos_types:
begin, _ = spans[start_index]
_, end = spans[end_index - 1]
surface_form = ' '.join(children)
# There are edge cases when these are not equal.
# For example, Diminish'd != Diminish 'd
# assert text[begin:end] == surface_form, text
surface_form = text[begin:end]
annotations.append(
data_utils.Annotation(
begin=begin, end=end - 1, text=surface_form, label=1, type=1))
start_index = end_index
else:
start_index += 1
annotations.sort(key=lambda a: (a.begin, a.end))
sentence = data_utils.Sentence(text=text, annotations=annotations)
sentence.strip_whitespaces()
return sentence
def _verify_annotations(
self, annotations, answer_set
):
should_update = False
new_annotations = []
filtered_annotations = set()
for annotation in annotations:
if (annotation.type == 0 and
evaluation.normalize_answer(annotation.text) not in answer_set):
filtered_annotations.add(annotation.text)
should_update = True
else:
new_annotations.append(annotation)
return should_update, new_annotations, filtered_annotations
def _get_max_tokens_per_raw_doc(self, question_len):
"""Computes the maximal number of tokens per single document."""
# The document will be split into several overlapping blocks --
# see TokenizedBertDocument.to_tf_strided_large_example for details.
# The first block will contain (`block_length` - `question_len`) tokens
# Other blocks will contain fewer tokens because of the overlap --
# (`block_length` - `question_len` - `block_overlap_length`) tokens.
# Finally, `num_blocks_per_example` blocks will in total
# have the following number of tokens:
# (`block_length` - `question_len`) + (`num_blocks_per_example` - 1) *
# (`block_length` - `question_len` - `block_overlap_length`) tokens =
# = `num_blocks_per_example` * (`block_length` - `question_len`)
# - (`num_blocks_per_example` - 1) * `block_overlap_length`
return self.num_blocks_per_example * (self.block_length - question_len) - (
self.num_blocks_per_example - 1) * self.block_overlap_length
def _tokenize_question(self, question):
tokens = self.tokenizer.tokenize(question)
token_ids = self.tokenizer.convert_tokens_to_ids(tokens)
return [self.cls_token_id] + token_ids + [self.sep_token_id]
def write_to_file_fn(output_prefix, filename):
return beam.io.WriteToText(
os.path.join(output_prefix + '.' + filename),
append_trailing_newlines=True,
shard_name_template='', # To force unsharded output.
)
def get_pipeline(input_file, wikipedia_dir, web_dir,
spm_model_path, num_blocks_per_example,
block_overlap_length, block_length,
max_num_annotations_per_block, padding_token_id,
cls_token_id, sep_token_id, generate_answers,
nltk_data_path, output_prefix,
output_num_shards):
"""Makes a Beam pipeline."""
def pipeline(root):
question_answers = read_question_answer_json(input_file)
question_answers = (
root | 'CreateQuestionAnswers' >> beam.Create(question_answers))
outputs = (
question_answers
| 'ReadEvidence' >> beam.ParDo(
ReadEvidence(wikipedia_dir=wikipedia_dir, web_dir=web_dir))
| 'ShuffleBeforeMakeExamples' >> beam.Reshuffle()
| 'MakeExamples' >> beam.ParDo(
MakeExamples(
spm_model_path=spm_model_path,
num_blocks_per_example=num_blocks_per_example,
block_overlap_length=block_overlap_length,
block_length=block_length,
max_num_annotations_per_block=max_num_annotations_per_block,
padding_token_id=padding_token_id,
cls_token_id=cls_token_id,
sep_token_id=sep_token_id,
generate_answers=generate_answers,
nltk_data_path=nltk_data_path)).with_outputs())
if generate_answers:
# Write failure cases, when no answer was found
_ = (
outputs[MakeExampleOutput.NO_ANSWER]
|
'WriteNoAnswer' >> write_to_file_fn(output_prefix, 'no_answer.jsonl'))
_ = (
outputs[MakeExampleOutput.NO_ANSWER_TOKENIZED]
| 'WriteNoAnswerTokenized' >> write_to_file_fn(
output_prefix, 'no_answer_tokenized.jsonl'))
# Write annotations that have been filtered out after tokenization
_ = (
outputs[MakeExampleOutput.SUCCESS_FILTERED_ANNOTATIONS]
| 'FlattenSuccessFilteredAnnotations' >> beam.FlatMap(lambda x: x)
| 'WriteSuccessFilteredAnnotations' >> write_to_file_fn(
output_prefix, 'success.filtered_annotations.txt'))
_ = (
outputs[MakeExampleOutput.NO_ANSWER_TOKENIZED_FILTERED_ANNOTATIONS]
| 'FlattenNoAnswerTokenizedFilteredAnnotations' >>
beam.FlatMap(lambda x: x)
| 'WriteNoAnswerTokenizedFilteredAnnotations' >> write_to_file_fn(
output_prefix, 'no_answer_tokenized.filtered_annotations.txt'))
# Write cases where the too many answer spans were found
_ = (
outputs[MakeExampleOutput.TOO_MANY_ANSWERS]
| 'WriteTooManyAnswers' >> write_to_file_fn(output_prefix,
'too_many_answers.jsonl'))
max_tokens = num_blocks_per_example * block_length
max_num_annotations = num_blocks_per_example * max_num_annotations_per_block
example_packer = beam_utils.PriorityExamplePacker(
priority_feature='token_ids',
max_lengths=dict(
token_ids=max_tokens,
is_continuation=max_tokens,
block_ids=num_blocks_per_example,
answer_annotation_begins=max_num_annotations,
answer_annotation_ends=max_num_annotations,
answer_annotation_labels=max_num_annotations,
entity_annotation_begins=max_num_annotations,
entity_annotation_ends=max_num_annotations,
entity_annotation_labels=max_num_annotations,
prefix_length=num_blocks_per_example),
breakpoint_features=dict(),
cumulative_features=[],
min_packing_fraction=1.0,
max_cache_len=num_blocks_per_example)
_ = (
outputs[MakeExampleOutput.SUCCESS]
| 'ShuffleBeforePacking' >> beam.Reshuffle()
| 'PackExamples' >> beam_utils.PackExamples(example_packer)
| 'ShuffleAfterPacking' >> beam.Reshuffle()
| 'WriteTfExamples' >> beam.io.WriteToTFRecord(
os.path.join(output_prefix + '.tfrecord'),
coder=beam.coders.ProtoCoder(tf.train.Example),
num_shards=output_num_shards))
return pipeline
| 38.964349 | 87 | 0.679308 |
import json
import os
import re
import string
from typing import Any, Iterator, List, Optional, Set, Text, Tuple
import apache_beam as beam
from apache_beam import metrics
import dataclasses
import nltk
import tensorflow.compat.v1 as tf
from readtwice.data_utils import beam_utils
from readtwice.data_utils import data_utils
from readtwice.data_utils import tokenization
from readtwice.models.trivia_qa import evaluation
METRICS_NAMESPACE = 'read_it_twice.trivia_qa'
@dataclasses.dataclass(frozen=True)
class Question(object):
id: int
question_id: Text
value: Text
@dataclasses.dataclass(frozen=True)
class EvidenceInfo(object):
id: Text
source: Text
title: Text
@dataclasses.dataclass(frozen=True)
class Evidence(object):
info: EvidenceInfo
text: Text
@dataclasses.dataclass(frozen=True)
class Answer(object):
value: Text
aliases: List[Text]
normalized_aliases: List[Text]
def _alias_answer(self, answer, include=None):
alias = answer.replace('_', ' ').lower()
exclude = set(string.punctuation + ''.join(['‘', '’', '´', '`']))
include = include or []
alias = ''.join(
c if c not in exclude or c in include else ' ' for c in alias)
return ' '.join(alias.split()).strip()
def make_answer_set(self):
answers = []
for alias in [self.value] + self.aliases:
answers.append(self._alias_answer(alias))
answers.append(self._alias_answer(alias, [',', '.']))
answers.append(self._alias_answer(alias, ['-']))
answers.append(self._alias_answer(alias, [',', '.', '-']))
answers.append(self._alias_answer(alias, string.punctuation))
answers = set(answers + self.normalized_aliases)
answers = {answer for answer in answers if answer.strip()}
return answers
@dataclasses.dataclass(frozen=True)
class QuestionAnswer(object):
question: Question
evidence_info: List[EvidenceInfo]
answer: Optional[Answer] = None
@classmethod
def from_dict(cls, idx, datum):
question = Question(
id=idx, question_id=datum['QuestionId'], value=datum['Question'])
if 'Answer' in datum:
answer = Answer(
value=datum['Answer']['Value'],
aliases=datum['Answer']['Aliases'],
normalized_aliases=datum['Answer']['NormalizedAliases'])
else:
answer = None
evidence_info = []
for key in ['EntityPages', 'SearchResults']:
for document in datum.get(key, []):
evidence_info.append(
EvidenceInfo(
id=document['Filename'], title=document['Title'], source=key))
return cls(question=question, evidence_info=evidence_info, answer=answer)
class EnhancedJSONEncoder(json.JSONEncoder):
def default(self, o):
if dataclasses.is_dataclass(o):
return dataclasses.asdict(o)
return super().default(o)
@dataclasses.dataclass
class QuestionAnswerEvidence(object):
question: Question
evidence: List[Evidence]
answer: Optional[Answer] = None
def to_json(self):
return json.dumps(self, cls=EnhancedJSONEncoder)
@dataclasses.dataclass
class FilteredAnnotation(object):
question: Question
answer: Answer
annotation: Text
sentence: Text
def __str__(self):
return '%s\t%s\t%s\t%s' % (
self.question.question_id, self.answer.value, self.annotation,
self.sentence.replace(tokenization.SPIECE_UNDERLINE, ' '))
class MakeExampleOutput(object):
SUCCESS = None
SUCCESS_FILTERED_ANNOTATIONS = 'success_filtered_annotations'
NO_ANSWER = 'no_answer'
NO_ANSWER_TOKENIZED = 'no_answer_tokenized'
NO_ANSWER_TOKENIZED_FILTERED_ANNOTATIONS = 'no_answer_tokenized_filtered_annotations'
TOO_MANY_ANSWERS = 'too_many_answers'
def read_question_answer_json(json_path):
with tf.io.gfile.GFile(json_path) as f:
data = json.load(f)['Data']
return [
QuestionAnswer.from_dict(idx + 1, datum) for idx, datum in enumerate(data)
]
class ReadEvidence(beam.DoFn):
def __init__(self, wikipedia_dir, web_dir):
self.wikipedia_dir = wikipedia_dir
self.web_dir = web_dir
def process(
self,
question_answer):
evidence = []
for info in question_answer.evidence_info:
if info.source == 'EntityPages':
evidence_path = os.path.join(self.wikipedia_dir, info.id)
elif info.source == 'SearchResult':
evidence_path = os.path.join(self.web_dir, info.id)
else:
raise ValueError(f'Unknown evidence source: {info.source}.')
with tf.io.gfile.GFile(evidence_path, 'rb') as f:
text = f.read().decode('utf-8')
evidence.append(Evidence(info=info, text=text))
if not evidence:
raise ValueError('Question %s does not have evidence.' %
str(question_answer))
metrics.Metrics.counter(METRICS_NAMESPACE, 'ReadEvidence.questions').inc()
metrics.Metrics.distribution(METRICS_NAMESPACE,
'ReadEvidence.num_evidence').update(
len(evidence))
yield QuestionAnswerEvidence(
question=question_answer.question,
evidence=evidence,
answer=question_answer.answer)
def find_answer_annotations(
text, answer_set):
annotations = []
for answer in answer_set:
answer_regex = re.compile(
re.escape(answer).replace('\\ ', '[ -]'), flags=re.IGNORECASE)
for match in re.finditer(answer_regex, text):
if not answer.strip() or match.end() == 0:
raise ValueError('Invalid answer string "%s" from answer set %s' %
(answer, str(answer_set)))
annotations.append(
data_utils.Annotation(
begin=match.start(), end=match.end() - 1, text=match.group(0)))
return sorted(annotations)
class MakeExamples(beam.DoFn):
def __init__(self, spm_model_path, num_blocks_per_example,
block_overlap_length, block_length,
max_num_annotations_per_block, padding_token_id,
cls_token_id, sep_token_id, generate_answers,
nltk_data_path):
self.spm_model_path = spm_model_path
self.num_blocks_per_example = num_blocks_per_example
self.block_overlap_length = block_overlap_length
self.block_length = block_length
self.max_num_annotations_per_block = max_num_annotations_per_block
self.padding_token_id = padding_token_id
self.cls_token_id = cls_token_id
self.sep_token_id = sep_token_id
self.generate_answers = generate_answers
self.nltk_data_path = nltk_data_path
nltk.data.path.append(self.nltk_data_path)
def setup(self):
nltk.data.path.append(self.nltk_data_path)
self.tokenizer = tokenization.FullTokenizer(
spm_model_file=self.spm_model_path)
self.nltk_tokenizer = nltk.TreebankWordTokenizer()
self.nltk_pos_types = {'PERSON', 'ORGANIZATION', 'FACILITY', 'GPE', 'GSP'}
def process(
self, question_answer_evidence):
metrics.Metrics.counter(METRICS_NAMESPACE, 'num_questions').inc()
if self.generate_answers:
answer_set = question_answer_evidence.answer.make_answer_set()
sentences = []
for sentence in self._split_into_sentences(
question_answer_evidence.evidence):
sentence_obj = self._annotate_entities(sentence)
metrics.Metrics.counter(METRICS_NAMESPACE, 'nltk_entities').inc(
sentence_obj.num_annotations(1))
if self.generate_answers:
annotations = find_answer_annotations(sentence_obj.text, answer_set)
sentence_obj.annotations.extend(annotations)
sentences.append(sentence_obj)
big_document = data_utils.BertDocument(
sentences=sentences, document_id=question_answer_evidence.question.id)
metrics.Metrics.distribution(METRICS_NAMESPACE,
'doc_length_per_question').update(
big_document.num_characters())
if self.generate_answers:
num_annotations = big_document.num_annotations(0)
metrics.Metrics.distribution(
METRICS_NAMESPACE,
'num_annotations_per_question').update(num_annotations)
if num_annotations == 0:
metrics.Metrics.counter(
METRICS_NAMESPACE,
'make_example_status.answer_span_not_found').inc()
yield beam.pvalue.TaggedOutput(MakeExampleOutput.NO_ANSWER,
question_answer_evidence.to_json())
return
tokenized_big_document = data_utils.tokenize_document_for_bert(
big_document, self.tokenizer)
metrics.Metrics.distribution(METRICS_NAMESPACE,
'tokenized_doc_length_per_question').update(
tokenized_big_document.num_tokens())
tokenized_question = self._tokenize_question(
question_answer_evidence.question.value)
metrics.Metrics.distribution(METRICS_NAMESPACE, 'question_length').update(
len(tokenized_question))
filtered_annotations = []
if self.generate_answers:
for i, sentence in enumerate(tokenized_big_document.sentences):
(should_update, annotations,
current_filtered_annotations) = self._verify_annotations(
sentence.annotations, answer_set)
if should_update:
tokenized_big_document.sentences[i].annotations = annotations
filtered_annotations.extend([
FilteredAnnotation(
question=question_answer_evidence.question,
answer=question_answer_evidence.answer,
annotation=annotation,
sentence=''.join(sentence.tokens))
for annotation in current_filtered_annotations
])
metrics.Metrics.counter(METRICS_NAMESPACE,
'num_filtered_annotations').inc(
len(current_filtered_annotations))
num_annotations = tokenized_big_document.num_annotations(0)
metrics.Metrics.distribution(
METRICS_NAMESPACE,
'num_annotations_tokenized_per_question').update(num_annotations)
if num_annotations == 0:
metrics.Metrics.counter(
METRICS_NAMESPACE,
'make_example_status.answer_not_found_tokenized').inc()
yield beam.pvalue.TaggedOutput(MakeExampleOutput.NO_ANSWER_TOKENIZED,
question_answer_evidence.to_json())
yield beam.pvalue.TaggedOutput(
MakeExampleOutput.NO_ANSWER_TOKENIZED_FILTERED_ANNOTATIONS,
filtered_annotations)
return
else:
approx_num_blocks = (
tokenized_big_document.num_tokens() /
(self.block_length - self.block_overlap_length -
len(tokenized_question)))
if num_annotations > self.max_num_annotations_per_block * approx_num_blocks:
metrics.Metrics.counter(METRICS_NAMESPACE,
'num_questions_with_too_many_answers').inc()
yield beam.pvalue.TaggedOutput(MakeExampleOutput.TOO_MANY_ANSWERS,
question_answer_evidence.to_json())
yield beam.pvalue.TaggedOutput(
MakeExampleOutput.SUCCESS_FILTERED_ANNOTATIONS,
filtered_annotations)
tokenized_documents = data_utils.split_tokenized_documents(
tokenized_big_document,
max_tokens=self._get_max_tokens_per_raw_doc(len(tokenized_question)),
max_sentences=None)
metrics.Metrics.distribution(METRICS_NAMESPACE,
'num_examples_per_question').update(
len(tokenized_documents))
if len(tokenized_documents) > 1:
metrics.Metrics.counter(METRICS_NAMESPACE, 'num_too_large_evidence').inc()
for tokenized_document in tokenized_documents:
if self.generate_answers and tokenized_document.num_annotations(0) == 0:
metrics.Metrics.counter(
METRICS_NAMESPACE,
'make_example_status.answer_not_found_splitted').inc()
continue
metrics.Metrics.counter(METRICS_NAMESPACE, 'num_examples').inc()
yield tokenized_document.to_tf_strided_large_example(
overlap_length=self.block_overlap_length,
block_length=self.block_length,
padding_token_id=self.padding_token_id,
prefix_token_ids=tokenized_question,
max_num_annotations=self.max_num_annotations_per_block)
metrics.Metrics.counter(METRICS_NAMESPACE,
'make_example_status.success').inc()
def _split_into_sentences(self, evidences):
for evidence in evidences:
for line in evidence.text.strip().split('\n'):
line_stripped = line.strip()
if line_stripped:
yield line_stripped
def _annotate_entities(self, text):
spans = list(self.nltk_tokenizer.span_tokenize(text))
tokens = [text[b:e] for (b, e) in spans]
annotations = []
trees = nltk.ne_chunk(nltk.pos_tag(tokens))
start_index = 0
for tree in trees:
if hasattr(tree, 'label'):
children = [text for text, pos in tree]
end_index = start_index + len(children)
if tree.label() in self.nltk_pos_types:
begin, _ = spans[start_index]
_, end = spans[end_index - 1]
surface_form = ' '.join(children)
surface_form = text[begin:end]
annotations.append(
data_utils.Annotation(
begin=begin, end=end - 1, text=surface_form, label=1, type=1))
start_index = end_index
else:
start_index += 1
annotations.sort(key=lambda a: (a.begin, a.end))
sentence = data_utils.Sentence(text=text, annotations=annotations)
sentence.strip_whitespaces()
return sentence
def _verify_annotations(
self, annotations, answer_set
):
should_update = False
new_annotations = []
filtered_annotations = set()
for annotation in annotations:
if (annotation.type == 0 and
evaluation.normalize_answer(annotation.text) not in answer_set):
filtered_annotations.add(annotation.text)
should_update = True
else:
new_annotations.append(annotation)
return should_update, new_annotations, filtered_annotations
def _get_max_tokens_per_raw_doc(self, question_len):
return self.num_blocks_per_example * (self.block_length - question_len) - (
self.num_blocks_per_example - 1) * self.block_overlap_length
def _tokenize_question(self, question):
tokens = self.tokenizer.tokenize(question)
token_ids = self.tokenizer.convert_tokens_to_ids(tokens)
return [self.cls_token_id] + token_ids + [self.sep_token_id]
def write_to_file_fn(output_prefix, filename):
return beam.io.WriteToText(
os.path.join(output_prefix + '.' + filename),
append_trailing_newlines=True,
shard_name_template='',
)
def get_pipeline(input_file, wikipedia_dir, web_dir,
spm_model_path, num_blocks_per_example,
block_overlap_length, block_length,
max_num_annotations_per_block, padding_token_id,
cls_token_id, sep_token_id, generate_answers,
nltk_data_path, output_prefix,
output_num_shards):
def pipeline(root):
question_answers = read_question_answer_json(input_file)
question_answers = (
root | 'CreateQuestionAnswers' >> beam.Create(question_answers))
outputs = (
question_answers
| 'ReadEvidence' >> beam.ParDo(
ReadEvidence(wikipedia_dir=wikipedia_dir, web_dir=web_dir))
| 'ShuffleBeforeMakeExamples' >> beam.Reshuffle()
| 'MakeExamples' >> beam.ParDo(
MakeExamples(
spm_model_path=spm_model_path,
num_blocks_per_example=num_blocks_per_example,
block_overlap_length=block_overlap_length,
block_length=block_length,
max_num_annotations_per_block=max_num_annotations_per_block,
padding_token_id=padding_token_id,
cls_token_id=cls_token_id,
sep_token_id=sep_token_id,
generate_answers=generate_answers,
nltk_data_path=nltk_data_path)).with_outputs())
if generate_answers:
_ = (
outputs[MakeExampleOutput.NO_ANSWER]
|
'WriteNoAnswer' >> write_to_file_fn(output_prefix, 'no_answer.jsonl'))
_ = (
outputs[MakeExampleOutput.NO_ANSWER_TOKENIZED]
| 'WriteNoAnswerTokenized' >> write_to_file_fn(
output_prefix, 'no_answer_tokenized.jsonl'))
_ = (
outputs[MakeExampleOutput.SUCCESS_FILTERED_ANNOTATIONS]
| 'FlattenSuccessFilteredAnnotations' >> beam.FlatMap(lambda x: x)
| 'WriteSuccessFilteredAnnotations' >> write_to_file_fn(
output_prefix, 'success.filtered_annotations.txt'))
_ = (
outputs[MakeExampleOutput.NO_ANSWER_TOKENIZED_FILTERED_ANNOTATIONS]
| 'FlattenNoAnswerTokenizedFilteredAnnotations' >>
beam.FlatMap(lambda x: x)
| 'WriteNoAnswerTokenizedFilteredAnnotations' >> write_to_file_fn(
output_prefix, 'no_answer_tokenized.filtered_annotations.txt'))
_ = (
outputs[MakeExampleOutput.TOO_MANY_ANSWERS]
| 'WriteTooManyAnswers' >> write_to_file_fn(output_prefix,
'too_many_answers.jsonl'))
max_tokens = num_blocks_per_example * block_length
max_num_annotations = num_blocks_per_example * max_num_annotations_per_block
example_packer = beam_utils.PriorityExamplePacker(
priority_feature='token_ids',
max_lengths=dict(
token_ids=max_tokens,
is_continuation=max_tokens,
block_ids=num_blocks_per_example,
answer_annotation_begins=max_num_annotations,
answer_annotation_ends=max_num_annotations,
answer_annotation_labels=max_num_annotations,
entity_annotation_begins=max_num_annotations,
entity_annotation_ends=max_num_annotations,
entity_annotation_labels=max_num_annotations,
prefix_length=num_blocks_per_example),
breakpoint_features=dict(),
cumulative_features=[],
min_packing_fraction=1.0,
max_cache_len=num_blocks_per_example)
_ = (
outputs[MakeExampleOutput.SUCCESS]
| 'ShuffleBeforePacking' >> beam.Reshuffle()
| 'PackExamples' >> beam_utils.PackExamples(example_packer)
| 'ShuffleAfterPacking' >> beam.Reshuffle()
| 'WriteTfExamples' >> beam.io.WriteToTFRecord(
os.path.join(output_prefix + '.tfrecord'),
coder=beam.coders.ProtoCoder(tf.train.Example),
num_shards=output_num_shards))
return pipeline
| true | true |
1c2e47c636c1783dcf57665f6534a758cd499e93 | 520 | py | Python | Dependencies/gyp-master/test/win/gyptest-midl-includedirs.py | knight666/exlibris | b21b46e0c84e5c4f81f8048022cda88e7bb3dca2 | [
"MIT"
] | null | null | null | Dependencies/gyp-master/test/win/gyptest-midl-includedirs.py | knight666/exlibris | b21b46e0c84e5c4f81f8048022cda88e7bb3dca2 | [
"MIT"
] | null | null | null | Dependencies/gyp-master/test/win/gyptest-midl-includedirs.py | knight666/exlibris | b21b46e0c84e5c4f81f8048022cda88e7bb3dca2 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# Copyright (c) 2014 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verify that 'midl_include_dirs' is handled.
"""
import TestGyp
import sys
if sys.platform == 'win32':
test = TestGyp.TestGyp(formats=['msvs', 'ninja'])
CHDIR = 'idl-includedirs'
test.run_gyp('idl-includedirs.gyp', chdir=CHDIR)
test.build('idl-includedirs.gyp', test.ALL, chdir=CHDIR)
test.pass_test()
| 23.636364 | 73 | 0.682692 |
import TestGyp
import sys
if sys.platform == 'win32':
test = TestGyp.TestGyp(formats=['msvs', 'ninja'])
CHDIR = 'idl-includedirs'
test.run_gyp('idl-includedirs.gyp', chdir=CHDIR)
test.build('idl-includedirs.gyp', test.ALL, chdir=CHDIR)
test.pass_test()
| true | true |
1c2e490b3e72e07c39bc7fa5d700e8208b53f383 | 6,264 | py | Python | server.py | itssathya/techathon-product-development | 4c0a4e79e194837628996a6b00cc1d97c7442fb3 | [
"MIT"
] | null | null | null | server.py | itssathya/techathon-product-development | 4c0a4e79e194837628996a6b00cc1d97c7442fb3 | [
"MIT"
] | null | null | null | server.py | itssathya/techathon-product-development | 4c0a4e79e194837628996a6b00cc1d97c7442fb3 | [
"MIT"
] | null | null | null | from flask import Flask, render_template,request,redirect,url_for,flash,session,g
from dbCode import loginVerify,addUser,studentPopulateClasses,ownerPopulateClasses,retrieveClassData,addClass,joinClassroom,allUsers,deleteUserDB,findClass
from examDB import createTestDB,createAssignmentDB
app = Flask(__name__)
app.secret_key = 'somesecretkeythatonlyishouldknow'
UPLOAD_FOLDER = './uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
@app.before_request
def before_request():
g.user = None
if('user_id' in session):
g.user = 'user_id'
@app.route('/login',methods=['GET','POST'])
def login():
if request.method == 'GET':
return render_template('login.html',message="")
elif request.method == 'POST':
session.pop('user_id',None)
print("SumbissionLogDebug")
user=request.form['user']
pwd=request.form['pwd']
token=loginVerify(user,pwd)
if(token[0]==0):
return render_template('login.html',message="Invalid password")
elif(token[0]==-1):
return render_template('login.html',message="User does not exist")
else:
session['user_id']=token[1]
session['user_name']=token[0]
session['user_role']=token[2]
print(session['user_role'])
return redirect(url_for('dashboard'))
@app.route('/signup',methods=['GET','POST'])
def signup():
if request.method == 'GET':
return render_template('signup.html')
elif request.method == 'POST':
name=request.form['fname']
email=request.form['email']
phone=request.form['phone']
pwd=request.form['pwd']
role=request.form["role"]
addUser(name,email,phone,pwd,role)
return redirect(url_for('login'))
@app.route('/dashboard',methods=['GET','POST'])
def dashboard():
if not g.user:
return redirect(url_for('login'))
if request.method == 'GET':
if(session['user_role']=="3"):
classes=studentPopulateClasses(session['user_id'])
return render_template('studentDashboard.html',classes=classes)
elif(session['user_role']=="2"):
classes=ownerPopulateClasses(session['user_id'])
return render_template('ownerDashboard.html',classes=classes)
elif(session['user_role']=="1"):
return render_template('adminDashboard.html')
@app.route('/logout',methods=['GET','POST'])
def logout():
session.pop('user_id',None)
return redirect(url_for('login'))
@app.route('/classStream',methods=['GET','POST'])
def classStream():
if not g.user:
return redirect(url_for('login'))
if request.method == 'POST':
classid=request.form['goclass']
print(classid)
if(session['user_role']=="3"):
classes=retrieveClassData(classid)
classdata=findClass(classid)
print("Student")
return render_template('studentClassStream.html',classes=classes,classdata=classdata)
elif(session['user_role']=="2"):
classes=retrieveClassData(classid)
classdata=findClass(classid)
classes=retrieveClassData(classid)
return render_template('ownerClassStream.html',classes=classes,classdata=classdata)
@app.route('/ownerClasses',methods=['GET','POST'])
def ownerClasses():
if not g.user:
return redirect(url_for('login'))
if request.method == 'GET':
return render_template('ownerClasses.html')
@app.route('/newClass',methods=['GET','POST'])
def newClass():
if not g.user:
return redirect(url_for('login'))
if request.method == 'GET':
return render_template('newClass.html')
elif request.method == 'POST':
className = request.form['classname']
addClass(className,session['user_id'])
return redirect(url_for('dashboard'))
@app.route('/joinClass',methods=['GET','POST'])
def joinClass():
if not g.user:
return redirect(url_for('login'))
if request.method == 'GET':
return render_template('joinClass.html')
elif request.method == 'POST':
classid = request.form['classname']
joinClassroom(classid,session['user_id'])
return redirect(url_for('dashboard'))
@app.route('/deleteUser',methods=['GET','POST'])
def deleteUser():
if not g.user:
return redirect(url_for('login'))
if request.method == 'GET':
users=allUsers()
return render_template('deleteUser.html',users=users)
elif request.method == 'POST':
userid = request.form['user']
deleteUserDB(userid)
return redirect(url_for('deleteUser'))
@app.route('/upload/',methods = ['GET','POST'])
def upload_file():
if not g.user:
return redirect(url_for('login'))
if request.method =='POST':
file = request.files['file']
if file:
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))
return hello()
return render_template('file_upload.html')
@app.route('/createAssignment',methods=['GET','POST'])
def createTest():
if request.method == 'GET':
return render_template('createAssignment.html')
if request.method == 'POST':
testname = request.form['testname']
due = request.form['dateandtime']
testQuestions = request.form.getlist('questions[]')
questionOption1 = request.form.getlist('option1[]')
questionOption2 = request.form.getlist('option2[]')
questionOption3 = request.form.getlist('option3[]')
questionOption4 = request.form.getlist('option4[]')
ans = request.form.getlist('ans[]')
createAssignmentDB(session['user_id'],due,testname,testQuestions,questionOption1,questionOption2,questionOption3,questionOption4,ans)
return redirect(url_for('dashboard'))
@app.route('/testTrial',methods=['GET','POST'])
def testTrial():
if request.method == 'GET':
return render_template('test.html')
elif request.method == 'POST':
datatrials=request.form.getlist('name[]')
print(datatrials)
return redirect(url_for('login'))
if __name__ == '__main__':
app.run(debug=True,host='192.168.0.77')
| 35.794286 | 155 | 0.64288 | from flask import Flask, render_template,request,redirect,url_for,flash,session,g
from dbCode import loginVerify,addUser,studentPopulateClasses,ownerPopulateClasses,retrieveClassData,addClass,joinClassroom,allUsers,deleteUserDB,findClass
from examDB import createTestDB,createAssignmentDB
app = Flask(__name__)
app.secret_key = 'somesecretkeythatonlyishouldknow'
UPLOAD_FOLDER = './uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
@app.before_request
def before_request():
g.user = None
if('user_id' in session):
g.user = 'user_id'
@app.route('/login',methods=['GET','POST'])
def login():
if request.method == 'GET':
return render_template('login.html',message="")
elif request.method == 'POST':
session.pop('user_id',None)
print("SumbissionLogDebug")
user=request.form['user']
pwd=request.form['pwd']
token=loginVerify(user,pwd)
if(token[0]==0):
return render_template('login.html',message="Invalid password")
elif(token[0]==-1):
return render_template('login.html',message="User does not exist")
else:
session['user_id']=token[1]
session['user_name']=token[0]
session['user_role']=token[2]
print(session['user_role'])
return redirect(url_for('dashboard'))
@app.route('/signup',methods=['GET','POST'])
def signup():
if request.method == 'GET':
return render_template('signup.html')
elif request.method == 'POST':
name=request.form['fname']
email=request.form['email']
phone=request.form['phone']
pwd=request.form['pwd']
role=request.form["role"]
addUser(name,email,phone,pwd,role)
return redirect(url_for('login'))
@app.route('/dashboard',methods=['GET','POST'])
def dashboard():
if not g.user:
return redirect(url_for('login'))
if request.method == 'GET':
if(session['user_role']=="3"):
classes=studentPopulateClasses(session['user_id'])
return render_template('studentDashboard.html',classes=classes)
elif(session['user_role']=="2"):
classes=ownerPopulateClasses(session['user_id'])
return render_template('ownerDashboard.html',classes=classes)
elif(session['user_role']=="1"):
return render_template('adminDashboard.html')
@app.route('/logout',methods=['GET','POST'])
def logout():
session.pop('user_id',None)
return redirect(url_for('login'))
@app.route('/classStream',methods=['GET','POST'])
def classStream():
if not g.user:
return redirect(url_for('login'))
if request.method == 'POST':
classid=request.form['goclass']
print(classid)
if(session['user_role']=="3"):
classes=retrieveClassData(classid)
classdata=findClass(classid)
print("Student")
return render_template('studentClassStream.html',classes=classes,classdata=classdata)
elif(session['user_role']=="2"):
classes=retrieveClassData(classid)
classdata=findClass(classid)
classes=retrieveClassData(classid)
return render_template('ownerClassStream.html',classes=classes,classdata=classdata)
@app.route('/ownerClasses',methods=['GET','POST'])
def ownerClasses():
if not g.user:
return redirect(url_for('login'))
if request.method == 'GET':
return render_template('ownerClasses.html')
@app.route('/newClass',methods=['GET','POST'])
def newClass():
if not g.user:
return redirect(url_for('login'))
if request.method == 'GET':
return render_template('newClass.html')
elif request.method == 'POST':
className = request.form['classname']
addClass(className,session['user_id'])
return redirect(url_for('dashboard'))
@app.route('/joinClass',methods=['GET','POST'])
def joinClass():
if not g.user:
return redirect(url_for('login'))
if request.method == 'GET':
return render_template('joinClass.html')
elif request.method == 'POST':
classid = request.form['classname']
joinClassroom(classid,session['user_id'])
return redirect(url_for('dashboard'))
@app.route('/deleteUser',methods=['GET','POST'])
def deleteUser():
if not g.user:
return redirect(url_for('login'))
if request.method == 'GET':
users=allUsers()
return render_template('deleteUser.html',users=users)
elif request.method == 'POST':
userid = request.form['user']
deleteUserDB(userid)
return redirect(url_for('deleteUser'))
@app.route('/upload/',methods = ['GET','POST'])
def upload_file():
if not g.user:
return redirect(url_for('login'))
if request.method =='POST':
file = request.files['file']
if file:
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))
return hello()
return render_template('file_upload.html')
@app.route('/createAssignment',methods=['GET','POST'])
def createTest():
if request.method == 'GET':
return render_template('createAssignment.html')
if request.method == 'POST':
testname = request.form['testname']
due = request.form['dateandtime']
testQuestions = request.form.getlist('questions[]')
questionOption1 = request.form.getlist('option1[]')
questionOption2 = request.form.getlist('option2[]')
questionOption3 = request.form.getlist('option3[]')
questionOption4 = request.form.getlist('option4[]')
ans = request.form.getlist('ans[]')
createAssignmentDB(session['user_id'],due,testname,testQuestions,questionOption1,questionOption2,questionOption3,questionOption4,ans)
return redirect(url_for('dashboard'))
@app.route('/testTrial',methods=['GET','POST'])
def testTrial():
if request.method == 'GET':
return render_template('test.html')
elif request.method == 'POST':
datatrials=request.form.getlist('name[]')
print(datatrials)
return redirect(url_for('login'))
if __name__ == '__main__':
app.run(debug=True,host='192.168.0.77')
| true | true |
1c2e4918ba1a3933f30f85a9410175d9db93dd40 | 16,898 | py | Python | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/tests/test_nrt.py | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 8 | 2019-10-07T16:33:47.000Z | 2020-12-07T03:59:58.000Z | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/tests/test_nrt.py | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 1 | 2017-12-21T23:31:59.000Z | 2017-12-29T16:56:05.000Z | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/tests/test_nrt.py | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 5 | 2020-08-27T20:44:18.000Z | 2021-08-21T22:54:11.000Z | from __future__ import absolute_import, division, print_function
import math
import os
import sys
import re
import numpy as np
from numba import unittest_support as unittest
from numba import njit
from numba.compiler import compile_isolated, Flags, types
from numba.runtime import rtsys
from numba.runtime import nrtopt
from .support import MemoryLeakMixin, TestCase
enable_nrt_flags = Flags()
enable_nrt_flags.set("nrt")
class Dummy(object):
alive = 0
def __init__(self):
type(self).alive += 1
def __del__(self):
type(self).alive -= 1
class TestNrtMemInfo(unittest.TestCase):
"""
Unitest for core MemInfo functionality
"""
def setUp(self):
# Reset the Dummy class
Dummy.alive = 0
def test_meminfo_refct_1(self):
d = Dummy()
self.assertEqual(Dummy.alive, 1)
addr = 0xdeadcafe # some made up location
mi = rtsys.meminfo_new(addr, d)
self.assertEqual(mi.refcount, 1)
del d
self.assertEqual(Dummy.alive, 1)
mi.acquire()
self.assertEqual(mi.refcount, 2)
self.assertEqual(Dummy.alive, 1)
mi.release()
self.assertEqual(mi.refcount, 1)
del mi
self.assertEqual(Dummy.alive, 0)
def test_meminfo_refct_2(self):
d = Dummy()
self.assertEqual(Dummy.alive, 1)
addr = 0xdeadcafe # some made up location
mi = rtsys.meminfo_new(addr, d)
self.assertEqual(mi.refcount, 1)
del d
self.assertEqual(Dummy.alive, 1)
for ct in range(100):
mi.acquire()
self.assertEqual(mi.refcount, 1 + 100)
self.assertEqual(Dummy.alive, 1)
for _ in range(100):
mi.release()
self.assertEqual(mi.refcount, 1)
del mi
self.assertEqual(Dummy.alive, 0)
@unittest.skipIf(sys.version_info < (3,), "memoryview not supported")
def test_fake_memoryview(self):
d = Dummy()
self.assertEqual(Dummy.alive, 1)
addr = 0xdeadcafe # some made up location
mi = rtsys.meminfo_new(addr, d)
self.assertEqual(mi.refcount, 1)
mview = memoryview(mi)
self.assertEqual(mi.refcount, 1)
self.assertEqual(addr, mi.data)
self.assertFalse(mview.readonly)
self.assertIs(mi, mview.obj)
self.assertTrue(mview.c_contiguous)
self.assertEqual(mview.itemsize, 1)
self.assertEqual(mview.ndim, 1)
del d
del mi
self.assertEqual(Dummy.alive, 1)
del mview
self.assertEqual(Dummy.alive, 0)
@unittest.skipIf(sys.version_info < (3,), "memoryview not supported")
def test_memoryview(self):
from ctypes import c_uint32, c_void_p, POINTER, cast
dtype = np.dtype(np.uint32)
bytesize = dtype.itemsize * 10
mi = rtsys.meminfo_alloc(bytesize, safe=True)
addr = mi.data
c_arr = cast(c_void_p(mi.data), POINTER(c_uint32 * 10))
# Check 0xCB-filling
for i in range(10):
self.assertEqual(c_arr.contents[i], 0xcbcbcbcb)
# Init array with ctypes
for i in range(10):
c_arr.contents[i] = i + 1
mview = memoryview(mi)
self.assertEqual(mview.nbytes, bytesize)
self.assertFalse(mview.readonly)
self.assertIs(mi, mview.obj)
self.assertTrue(mview.c_contiguous)
self.assertEqual(mview.itemsize, 1)
self.assertEqual(mview.ndim, 1)
del mi
arr = np.ndarray(dtype=dtype, shape=mview.nbytes // dtype.itemsize,
buffer=mview)
del mview
# Modify array with NumPy
np.testing.assert_equal(np.arange(arr.size) + 1, arr)
arr += 1
# Check value reflected in ctypes
for i in range(10):
self.assertEqual(c_arr.contents[i], i + 2)
self.assertEqual(arr.ctypes.data, addr)
del arr
# At this point the memory is zero filled
# We can't check this deterministically because the memory could be
# consumed by another thread.
def test_buffer(self):
from ctypes import c_uint32, c_void_p, POINTER, cast
dtype = np.dtype(np.uint32)
bytesize = dtype.itemsize * 10
mi = rtsys.meminfo_alloc(bytesize, safe=True)
self.assertEqual(mi.refcount, 1)
addr = mi.data
c_arr = cast(c_void_p(addr), POINTER(c_uint32 * 10))
# Check 0xCB-filling
for i in range(10):
self.assertEqual(c_arr.contents[i], 0xcbcbcbcb)
# Init array with ctypes
for i in range(10):
c_arr.contents[i] = i + 1
arr = np.ndarray(dtype=dtype, shape=bytesize // dtype.itemsize,
buffer=mi)
self.assertEqual(mi.refcount, 1)
del mi
# Modify array with NumPy
np.testing.assert_equal(np.arange(arr.size) + 1, arr)
arr += 1
# Check value reflected in ctypes
for i in range(10):
self.assertEqual(c_arr.contents[i], i + 2)
self.assertEqual(arr.ctypes.data, addr)
del arr
# At this point the memory is zero filled
# We can't check this deterministically because the memory could be
# consumed by another thread.
@unittest.skipUnless(sys.version_info >= (3, 4),
"need Python 3.4+ for the tracemalloc module")
class TestTracemalloc(unittest.TestCase):
"""
Test NRT-allocated memory can be tracked by tracemalloc.
"""
def measure_memory_diff(self, func):
import tracemalloc
tracemalloc.start()
try:
before = tracemalloc.take_snapshot()
# Keep the result and only delete it after taking a snapshot
res = func()
after = tracemalloc.take_snapshot()
del res
return after.compare_to(before, 'lineno')
finally:
tracemalloc.stop()
def test_snapshot(self):
N = 1000000
dtype = np.int8
@njit
def alloc_nrt_memory():
"""
Allocate and return a large array.
"""
return np.empty(N, dtype)
def keep_memory():
return alloc_nrt_memory()
def release_memory():
alloc_nrt_memory()
alloc_lineno = keep_memory.__code__.co_firstlineno + 1
# Warmup JIT
alloc_nrt_memory()
# The large NRT-allocated array should appear topmost in the diff
diff = self.measure_memory_diff(keep_memory)
stat = diff[0]
# There is a slight overhead, so the allocated size won't exactly be N
self.assertGreaterEqual(stat.size, N)
self.assertLess(stat.size, N * 1.01)
frame = stat.traceback[0]
self.assertEqual(os.path.basename(frame.filename), "test_nrt.py")
self.assertEqual(frame.lineno, alloc_lineno)
# If NRT memory is released before taking a snapshot, it shouldn't
# appear.
diff = self.measure_memory_diff(release_memory)
stat = diff[0]
# Something else appears, but nothing the magnitude of N
self.assertLess(stat.size, N * 0.01)
class TestNRTIssue(MemoryLeakMixin, TestCase):
def test_issue_with_refct_op_pruning(self):
"""
GitHub Issue #1244 https://github.com/numba/numba/issues/1244
"""
@njit
def calculate_2D_vector_mag(vector):
x, y = vector
return math.sqrt(x ** 2 + y ** 2)
@njit
def normalize_2D_vector(vector):
normalized_vector = np.empty(2, dtype=np.float64)
mag = calculate_2D_vector_mag(vector)
x, y = vector
normalized_vector[0] = x / mag
normalized_vector[1] = y / mag
return normalized_vector
@njit
def normalize_vectors(num_vectors, vectors):
normalized_vectors = np.empty((num_vectors, 2), dtype=np.float64)
for i in range(num_vectors):
vector = vectors[i]
normalized_vector = normalize_2D_vector(vector)
normalized_vectors[i, 0] = normalized_vector[0]
normalized_vectors[i, 1] = normalized_vector[1]
return normalized_vectors
num_vectors = 10
test_vectors = np.random.random((num_vectors, 2))
got = normalize_vectors(num_vectors, test_vectors)
expected = normalize_vectors.py_func(num_vectors, test_vectors)
np.testing.assert_almost_equal(expected, got)
def test_incref_after_cast(self):
# Issue #1427: when casting a value before returning it, the
# cast result should be incref'ed, not the original value.
def f():
return 0.0, np.zeros(1, dtype=np.int32)
# Note the return type isn't the same as the tuple type above:
# the first element is a complex rather than a float.
cres = compile_isolated(f, (),
types.Tuple((types.complex128,
types.Array(types.int32, 1, 'C')
))
)
z, arr = cres.entry_point()
self.assertPreciseEqual(z, 0j)
self.assertPreciseEqual(arr, np.zeros(1, dtype=np.int32))
def test_refct_pruning_issue_1511(self):
@njit
def f():
a = np.ones(10, dtype=np.float64)
b = np.ones(10, dtype=np.float64)
return a, b[:]
a, b = f()
np.testing.assert_equal(a, b)
np.testing.assert_equal(a, np.ones(10, dtype=np.float64))
def test_refct_pruning_issue_1526(self):
@njit
def udt(image, x, y):
next_loc = np.where(image == 1)
if len(next_loc[0]) == 0:
y_offset = 1
x_offset = 1
else:
y_offset = next_loc[0][0]
x_offset = next_loc[1][0]
next_loc_x = (x - 1) + x_offset
next_loc_y = (y - 1) + y_offset
return next_loc_x, next_loc_y
a = np.array([[1, 0, 1, 0, 1, 0, 0, 1, 0, 0]])
expect = udt.py_func(a, 1, 6)
got = udt(a, 1, 6)
self.assertEqual(expect, got)
class TestRefCtPruning(unittest.TestCase):
sample_llvm_ir = '''
define i32 @"MyFunction"(i8** noalias nocapture %retptr, { i8*, i32 }** noalias nocapture %excinfo, i8* noalias nocapture readnone %env, double %arg.vt.0, double %arg.vt.1, double %arg.vt.2, double %arg.vt.3, double %arg.bounds.0, double %arg.bounds.1, double %arg.bounds.2, double %arg.bounds.3, i8* %arg.xs.0, i8* nocapture readnone %arg.xs.1, i64 %arg.xs.2, i64 %arg.xs.3, double* nocapture readonly %arg.xs.4, i64 %arg.xs.5.0, i64 %arg.xs.6.0, i8* %arg.ys.0, i8* nocapture readnone %arg.ys.1, i64 %arg.ys.2, i64 %arg.ys.3, double* nocapture readonly %arg.ys.4, i64 %arg.ys.5.0, i64 %arg.ys.6.0, i8* %arg.aggs_and_cols.0.0, i8* nocapture readnone %arg.aggs_and_cols.0.1, i64 %arg.aggs_and_cols.0.2, i64 %arg.aggs_and_cols.0.3, i32* nocapture %arg.aggs_and_cols.0.4, i64 %arg.aggs_and_cols.0.5.0, i64 %arg.aggs_and_cols.0.5.1, i64 %arg.aggs_and_cols.0.6.0, i64 %arg.aggs_and_cols.0.6.1) local_unnamed_addr {
entry:
tail call void @NRT_incref(i8* %arg.xs.0)
tail call void @NRT_incref(i8* %arg.ys.0)
tail call void @NRT_incref(i8* %arg.aggs_and_cols.0.0)
%.251 = icmp sgt i64 %arg.xs.5.0, 0
br i1 %.251, label %B42.preheader, label %B160
B42.preheader: ; preds = %entry
%0 = add i64 %arg.xs.5.0, 1
br label %B42
B42: ; preds = %B40.backedge, %B42.preheader
%lsr.iv3 = phi i64 [ %lsr.iv.next, %B40.backedge ], [ %0, %B42.preheader ]
%lsr.iv1 = phi double* [ %scevgep2, %B40.backedge ], [ %arg.xs.4, %B42.preheader ]
%lsr.iv = phi double* [ %scevgep, %B40.backedge ], [ %arg.ys.4, %B42.preheader ]
%.381 = load double, double* %lsr.iv1, align 8
%.420 = load double, double* %lsr.iv, align 8
%.458 = fcmp ole double %.381, %arg.bounds.1
%not..432 = fcmp oge double %.381, %arg.bounds.0
%"$phi82.1.1" = and i1 %.458, %not..432
br i1 %"$phi82.1.1", label %B84, label %B40.backedge
B84: ; preds = %B42
%.513 = fcmp ole double %.420, %arg.bounds.3
%not..487 = fcmp oge double %.420, %arg.bounds.2
%"$phi106.1.1" = and i1 %.513, %not..487
br i1 %"$phi106.1.1", label %B108.endif.endif.endif, label %B40.backedge
B160: ; preds = %B40.backedge, %entry
tail call void @NRT_decref(i8* %arg.ys.0)
tail call void @NRT_decref(i8* %arg.xs.0)
tail call void @NRT_decref(i8* %arg.aggs_and_cols.0.0)
store i8* null, i8** %retptr, align 8
ret i32 0
B108.endif.endif.endif: ; preds = %B84
%.575 = fmul double %.381, %arg.vt.0
%.583 = fadd double %.575, %arg.vt.1
%.590 = fptosi double %.583 to i64
%.630 = fmul double %.420, %arg.vt.2
%.638 = fadd double %.630, %arg.vt.3
%.645 = fptosi double %.638 to i64
tail call void @NRT_incref(i8* %arg.aggs_and_cols.0.0) ; GONE 1
tail call void @NRT_decref(i8* null) ; GONE 2
tail call void @NRT_incref(i8* %arg.aggs_and_cols.0.0), !noalias !0 ; GONE 3
%.62.i.i = icmp slt i64 %.645, 0
%.63.i.i = select i1 %.62.i.i, i64 %arg.aggs_and_cols.0.5.0, i64 0
%.64.i.i = add i64 %.63.i.i, %.645
%.65.i.i = icmp slt i64 %.590, 0
%.66.i.i = select i1 %.65.i.i, i64 %arg.aggs_and_cols.0.5.1, i64 0
%.67.i.i = add i64 %.66.i.i, %.590
%.84.i.i = mul i64 %.64.i.i, %arg.aggs_and_cols.0.5.1
%.87.i.i = add i64 %.67.i.i, %.84.i.i
%.88.i.i = getelementptr i32, i32* %arg.aggs_and_cols.0.4, i64 %.87.i.i
%.89.i.i = load i32, i32* %.88.i.i, align 4, !noalias !3
%.99.i.i = add i32 %.89.i.i, 1
store i32 %.99.i.i, i32* %.88.i.i, align 4, !noalias !3
tail call void @NRT_decref(i8* %arg.aggs_and_cols.0.0), !noalias !0 ; GONE 4
tail call void @NRT_decref(i8* %arg.aggs_and_cols.0.0) ; GONE 5
br label %B40.backedge
B40.backedge: ; preds = %B108.endif.endif.endif, %B84, %B42
%scevgep = getelementptr double, double* %lsr.iv, i64 1
%scevgep2 = getelementptr double, double* %lsr.iv1, i64 1
%lsr.iv.next = add i64 %lsr.iv3, -1
%.294 = icmp sgt i64 %lsr.iv.next, 1
br i1 %.294, label %B42, label %B160
}
'''
def test_refct_pruning_op_recognize(self):
input_ir = self.sample_llvm_ir
input_lines = list(input_ir.splitlines())
before_increfs = [ln for ln in input_lines if 'NRT_incref' in ln]
before_decrefs = [ln for ln in input_lines if 'NRT_decref' in ln]
# prune
output_ir = nrtopt._remove_redundant_nrt_refct(input_ir)
output_lines = list(output_ir.splitlines())
after_increfs = [ln for ln in output_lines if 'NRT_incref' in ln]
after_decrefs = [ln for ln in output_lines if 'NRT_decref' in ln]
# check
self.assertNotEqual(before_increfs, after_increfs)
self.assertNotEqual(before_decrefs, after_decrefs)
pruned_increfs = set(before_increfs) - set(after_increfs)
pruned_decrefs = set(before_decrefs) - set(after_decrefs)
# the symm difference == or-combined
combined = pruned_increfs | pruned_decrefs
self.assertEqual(combined, pruned_increfs ^ pruned_decrefs)
pruned_lines = '\n'.join(combined)
# all GONE lines are pruned
for i in [1, 2, 3, 4, 5]:
gone = '; GONE {}'.format(i)
self.assertIn(gone, pruned_lines)
# no other lines
self.assertEqual(len(list(pruned_lines.splitlines())), len(combined))
def test_refct_pruning_with_branches(self):
'''testcase from #2350'''
@njit
def _append_non_na(x, y, agg, field):
if not np.isnan(field):
agg[y, x] += 1
@njit
def _append(x, y, agg, field):
if not np.isnan(field):
if np.isnan(agg[y, x]):
agg[y, x] = field
else:
agg[y, x] += field
@njit
def append(x, y, agg, field):
_append_non_na(x, y, agg, field)
_append(x, y, agg, field)
# Disable python wrapper to avoid detecting necessary
# refcount inside it
@njit(no_cpython_wrapper=True)
def extend(arr, field):
for i in range(arr.shape[0]):
for j in range(arr.shape[1]):
append(j, i, arr, field)
# Compile
extend.compile("(f4[:,::1], f4)")
# Test there are no reference count operations
llvmir = str(extend.inspect_llvm(extend.signatures[0]))
refops = list(re.finditer(r'(NRT_incref|NRT_decref)\([^\)]+\)', llvmir))
self.assertEqual(len(refops), 0)
if __name__ == '__main__':
unittest.main()
| 35.351464 | 909 | 0.59439 | from __future__ import absolute_import, division, print_function
import math
import os
import sys
import re
import numpy as np
from numba import unittest_support as unittest
from numba import njit
from numba.compiler import compile_isolated, Flags, types
from numba.runtime import rtsys
from numba.runtime import nrtopt
from .support import MemoryLeakMixin, TestCase
enable_nrt_flags = Flags()
enable_nrt_flags.set("nrt")
class Dummy(object):
alive = 0
def __init__(self):
type(self).alive += 1
def __del__(self):
type(self).alive -= 1
class TestNrtMemInfo(unittest.TestCase):
def setUp(self):
Dummy.alive = 0
def test_meminfo_refct_1(self):
d = Dummy()
self.assertEqual(Dummy.alive, 1)
addr = 0xdeadcafe
mi = rtsys.meminfo_new(addr, d)
self.assertEqual(mi.refcount, 1)
del d
self.assertEqual(Dummy.alive, 1)
mi.acquire()
self.assertEqual(mi.refcount, 2)
self.assertEqual(Dummy.alive, 1)
mi.release()
self.assertEqual(mi.refcount, 1)
del mi
self.assertEqual(Dummy.alive, 0)
def test_meminfo_refct_2(self):
d = Dummy()
self.assertEqual(Dummy.alive, 1)
addr = 0xdeadcafe
mi = rtsys.meminfo_new(addr, d)
self.assertEqual(mi.refcount, 1)
del d
self.assertEqual(Dummy.alive, 1)
for ct in range(100):
mi.acquire()
self.assertEqual(mi.refcount, 1 + 100)
self.assertEqual(Dummy.alive, 1)
for _ in range(100):
mi.release()
self.assertEqual(mi.refcount, 1)
del mi
self.assertEqual(Dummy.alive, 0)
@unittest.skipIf(sys.version_info < (3,), "memoryview not supported")
def test_fake_memoryview(self):
d = Dummy()
self.assertEqual(Dummy.alive, 1)
addr = 0xdeadcafe
mi = rtsys.meminfo_new(addr, d)
self.assertEqual(mi.refcount, 1)
mview = memoryview(mi)
self.assertEqual(mi.refcount, 1)
self.assertEqual(addr, mi.data)
self.assertFalse(mview.readonly)
self.assertIs(mi, mview.obj)
self.assertTrue(mview.c_contiguous)
self.assertEqual(mview.itemsize, 1)
self.assertEqual(mview.ndim, 1)
del d
del mi
self.assertEqual(Dummy.alive, 1)
del mview
self.assertEqual(Dummy.alive, 0)
@unittest.skipIf(sys.version_info < (3,), "memoryview not supported")
def test_memoryview(self):
from ctypes import c_uint32, c_void_p, POINTER, cast
dtype = np.dtype(np.uint32)
bytesize = dtype.itemsize * 10
mi = rtsys.meminfo_alloc(bytesize, safe=True)
addr = mi.data
c_arr = cast(c_void_p(mi.data), POINTER(c_uint32 * 10))
for i in range(10):
self.assertEqual(c_arr.contents[i], 0xcbcbcbcb)
for i in range(10):
c_arr.contents[i] = i + 1
mview = memoryview(mi)
self.assertEqual(mview.nbytes, bytesize)
self.assertFalse(mview.readonly)
self.assertIs(mi, mview.obj)
self.assertTrue(mview.c_contiguous)
self.assertEqual(mview.itemsize, 1)
self.assertEqual(mview.ndim, 1)
del mi
arr = np.ndarray(dtype=dtype, shape=mview.nbytes // dtype.itemsize,
buffer=mview)
del mview
np.testing.assert_equal(np.arange(arr.size) + 1, arr)
arr += 1
for i in range(10):
self.assertEqual(c_arr.contents[i], i + 2)
self.assertEqual(arr.ctypes.data, addr)
del arr
# consumed by another thread.
def test_buffer(self):
from ctypes import c_uint32, c_void_p, POINTER, cast
dtype = np.dtype(np.uint32)
bytesize = dtype.itemsize * 10
mi = rtsys.meminfo_alloc(bytesize, safe=True)
self.assertEqual(mi.refcount, 1)
addr = mi.data
c_arr = cast(c_void_p(addr), POINTER(c_uint32 * 10))
# Check 0xCB-filling
for i in range(10):
self.assertEqual(c_arr.contents[i], 0xcbcbcbcb)
# Init array with ctypes
for i in range(10):
c_arr.contents[i] = i + 1
arr = np.ndarray(dtype=dtype, shape=bytesize // dtype.itemsize,
buffer=mi)
self.assertEqual(mi.refcount, 1)
del mi
# Modify array with NumPy
np.testing.assert_equal(np.arange(arr.size) + 1, arr)
arr += 1
# Check value reflected in ctypes
for i in range(10):
self.assertEqual(c_arr.contents[i], i + 2)
self.assertEqual(arr.ctypes.data, addr)
del arr
# At this point the memory is zero filled
# We can't check this deterministically because the memory could be
@unittest.skipUnless(sys.version_info >= (3, 4),
"need Python 3.4+ for the tracemalloc module")
class TestTracemalloc(unittest.TestCase):
def measure_memory_diff(self, func):
import tracemalloc
tracemalloc.start()
try:
before = tracemalloc.take_snapshot()
res = func()
after = tracemalloc.take_snapshot()
del res
return after.compare_to(before, 'lineno')
finally:
tracemalloc.stop()
def test_snapshot(self):
N = 1000000
dtype = np.int8
@njit
def alloc_nrt_memory():
return np.empty(N, dtype)
def keep_memory():
return alloc_nrt_memory()
def release_memory():
alloc_nrt_memory()
alloc_lineno = keep_memory.__code__.co_firstlineno + 1
alloc_nrt_memory()
diff = self.measure_memory_diff(keep_memory)
stat = diff[0]
self.assertGreaterEqual(stat.size, N)
self.assertLess(stat.size, N * 1.01)
frame = stat.traceback[0]
self.assertEqual(os.path.basename(frame.filename), "test_nrt.py")
self.assertEqual(frame.lineno, alloc_lineno)
# If NRT memory is released before taking a snapshot, it shouldn't
diff = self.measure_memory_diff(release_memory)
stat = diff[0]
self.assertLess(stat.size, N * 0.01)
class TestNRTIssue(MemoryLeakMixin, TestCase):
def test_issue_with_refct_op_pruning(self):
@njit
def calculate_2D_vector_mag(vector):
x, y = vector
return math.sqrt(x ** 2 + y ** 2)
@njit
def normalize_2D_vector(vector):
normalized_vector = np.empty(2, dtype=np.float64)
mag = calculate_2D_vector_mag(vector)
x, y = vector
normalized_vector[0] = x / mag
normalized_vector[1] = y / mag
return normalized_vector
@njit
def normalize_vectors(num_vectors, vectors):
normalized_vectors = np.empty((num_vectors, 2), dtype=np.float64)
for i in range(num_vectors):
vector = vectors[i]
normalized_vector = normalize_2D_vector(vector)
normalized_vectors[i, 0] = normalized_vector[0]
normalized_vectors[i, 1] = normalized_vector[1]
return normalized_vectors
num_vectors = 10
test_vectors = np.random.random((num_vectors, 2))
got = normalize_vectors(num_vectors, test_vectors)
expected = normalize_vectors.py_func(num_vectors, test_vectors)
np.testing.assert_almost_equal(expected, got)
def test_incref_after_cast(self):
p.zeros(1, dtype=np.int32)
# Note the return type isn't the same as the tuple type above:
cres = compile_isolated(f, (),
types.Tuple((types.complex128,
types.Array(types.int32, 1, 'C')
))
)
z, arr = cres.entry_point()
self.assertPreciseEqual(z, 0j)
self.assertPreciseEqual(arr, np.zeros(1, dtype=np.int32))
def test_refct_pruning_issue_1511(self):
@njit
def f():
a = np.ones(10, dtype=np.float64)
b = np.ones(10, dtype=np.float64)
return a, b[:]
a, b = f()
np.testing.assert_equal(a, b)
np.testing.assert_equal(a, np.ones(10, dtype=np.float64))
def test_refct_pruning_issue_1526(self):
@njit
def udt(image, x, y):
next_loc = np.where(image == 1)
if len(next_loc[0]) == 0:
y_offset = 1
x_offset = 1
else:
y_offset = next_loc[0][0]
x_offset = next_loc[1][0]
next_loc_x = (x - 1) + x_offset
next_loc_y = (y - 1) + y_offset
return next_loc_x, next_loc_y
a = np.array([[1, 0, 1, 0, 1, 0, 0, 1, 0, 0]])
expect = udt.py_func(a, 1, 6)
got = udt(a, 1, 6)
self.assertEqual(expect, got)
class TestRefCtPruning(unittest.TestCase):
sample_llvm_ir = '''
define i32 @"MyFunction"(i8** noalias nocapture %retptr, { i8*, i32 }** noalias nocapture %excinfo, i8* noalias nocapture readnone %env, double %arg.vt.0, double %arg.vt.1, double %arg.vt.2, double %arg.vt.3, double %arg.bounds.0, double %arg.bounds.1, double %arg.bounds.2, double %arg.bounds.3, i8* %arg.xs.0, i8* nocapture readnone %arg.xs.1, i64 %arg.xs.2, i64 %arg.xs.3, double* nocapture readonly %arg.xs.4, i64 %arg.xs.5.0, i64 %arg.xs.6.0, i8* %arg.ys.0, i8* nocapture readnone %arg.ys.1, i64 %arg.ys.2, i64 %arg.ys.3, double* nocapture readonly %arg.ys.4, i64 %arg.ys.5.0, i64 %arg.ys.6.0, i8* %arg.aggs_and_cols.0.0, i8* nocapture readnone %arg.aggs_and_cols.0.1, i64 %arg.aggs_and_cols.0.2, i64 %arg.aggs_and_cols.0.3, i32* nocapture %arg.aggs_and_cols.0.4, i64 %arg.aggs_and_cols.0.5.0, i64 %arg.aggs_and_cols.0.5.1, i64 %arg.aggs_and_cols.0.6.0, i64 %arg.aggs_and_cols.0.6.1) local_unnamed_addr {
entry:
tail call void @NRT_incref(i8* %arg.xs.0)
tail call void @NRT_incref(i8* %arg.ys.0)
tail call void @NRT_incref(i8* %arg.aggs_and_cols.0.0)
%.251 = icmp sgt i64 %arg.xs.5.0, 0
br i1 %.251, label %B42.preheader, label %B160
B42.preheader: ; preds = %entry
%0 = add i64 %arg.xs.5.0, 1
br label %B42
B42: ; preds = %B40.backedge, %B42.preheader
%lsr.iv3 = phi i64 [ %lsr.iv.next, %B40.backedge ], [ %0, %B42.preheader ]
%lsr.iv1 = phi double* [ %scevgep2, %B40.backedge ], [ %arg.xs.4, %B42.preheader ]
%lsr.iv = phi double* [ %scevgep, %B40.backedge ], [ %arg.ys.4, %B42.preheader ]
%.381 = load double, double* %lsr.iv1, align 8
%.420 = load double, double* %lsr.iv, align 8
%.458 = fcmp ole double %.381, %arg.bounds.1
%not..432 = fcmp oge double %.381, %arg.bounds.0
%"$phi82.1.1" = and i1 %.458, %not..432
br i1 %"$phi82.1.1", label %B84, label %B40.backedge
B84: ; preds = %B42
%.513 = fcmp ole double %.420, %arg.bounds.3
%not..487 = fcmp oge double %.420, %arg.bounds.2
%"$phi106.1.1" = and i1 %.513, %not..487
br i1 %"$phi106.1.1", label %B108.endif.endif.endif, label %B40.backedge
B160: ; preds = %B40.backedge, %entry
tail call void @NRT_decref(i8* %arg.ys.0)
tail call void @NRT_decref(i8* %arg.xs.0)
tail call void @NRT_decref(i8* %arg.aggs_and_cols.0.0)
store i8* null, i8** %retptr, align 8
ret i32 0
B108.endif.endif.endif: ; preds = %B84
%.575 = fmul double %.381, %arg.vt.0
%.583 = fadd double %.575, %arg.vt.1
%.590 = fptosi double %.583 to i64
%.630 = fmul double %.420, %arg.vt.2
%.638 = fadd double %.630, %arg.vt.3
%.645 = fptosi double %.638 to i64
tail call void @NRT_incref(i8* %arg.aggs_and_cols.0.0) ; GONE 1
tail call void @NRT_decref(i8* null) ; GONE 2
tail call void @NRT_incref(i8* %arg.aggs_and_cols.0.0), !noalias !0 ; GONE 3
%.62.i.i = icmp slt i64 %.645, 0
%.63.i.i = select i1 %.62.i.i, i64 %arg.aggs_and_cols.0.5.0, i64 0
%.64.i.i = add i64 %.63.i.i, %.645
%.65.i.i = icmp slt i64 %.590, 0
%.66.i.i = select i1 %.65.i.i, i64 %arg.aggs_and_cols.0.5.1, i64 0
%.67.i.i = add i64 %.66.i.i, %.590
%.84.i.i = mul i64 %.64.i.i, %arg.aggs_and_cols.0.5.1
%.87.i.i = add i64 %.67.i.i, %.84.i.i
%.88.i.i = getelementptr i32, i32* %arg.aggs_and_cols.0.4, i64 %.87.i.i
%.89.i.i = load i32, i32* %.88.i.i, align 4, !noalias !3
%.99.i.i = add i32 %.89.i.i, 1
store i32 %.99.i.i, i32* %.88.i.i, align 4, !noalias !3
tail call void @NRT_decref(i8* %arg.aggs_and_cols.0.0), !noalias !0 ; GONE 4
tail call void @NRT_decref(i8* %arg.aggs_and_cols.0.0) ; GONE 5
br label %B40.backedge
B40.backedge: ; preds = %B108.endif.endif.endif, %B84, %B42
%scevgep = getelementptr double, double* %lsr.iv, i64 1
%scevgep2 = getelementptr double, double* %lsr.iv1, i64 1
%lsr.iv.next = add i64 %lsr.iv3, -1
%.294 = icmp sgt i64 %lsr.iv.next, 1
br i1 %.294, label %B42, label %B160
}
'''
def test_refct_pruning_op_recognize(self):
input_ir = self.sample_llvm_ir
input_lines = list(input_ir.splitlines())
before_increfs = [ln for ln in input_lines if 'NRT_incref' in ln]
before_decrefs = [ln for ln in input_lines if 'NRT_decref' in ln]
output_ir = nrtopt._remove_redundant_nrt_refct(input_ir)
output_lines = list(output_ir.splitlines())
after_increfs = [ln for ln in output_lines if 'NRT_incref' in ln]
after_decrefs = [ln for ln in output_lines if 'NRT_decref' in ln]
self.assertNotEqual(before_increfs, after_increfs)
self.assertNotEqual(before_decrefs, after_decrefs)
pruned_increfs = set(before_increfs) - set(after_increfs)
pruned_decrefs = set(before_decrefs) - set(after_decrefs)
combined = pruned_increfs | pruned_decrefs
self.assertEqual(combined, pruned_increfs ^ pruned_decrefs)
pruned_lines = '\n'.join(combined)
for i in [1, 2, 3, 4, 5]:
gone = '; GONE {}'.format(i)
self.assertIn(gone, pruned_lines)
self.assertEqual(len(list(pruned_lines.splitlines())), len(combined))
def test_refct_pruning_with_branches(self):
@njit
def _append_non_na(x, y, agg, field):
if not np.isnan(field):
agg[y, x] += 1
@njit
def _append(x, y, agg, field):
if not np.isnan(field):
if np.isnan(agg[y, x]):
agg[y, x] = field
else:
agg[y, x] += field
@njit
def append(x, y, agg, field):
_append_non_na(x, y, agg, field)
_append(x, y, agg, field)
@njit(no_cpython_wrapper=True)
def extend(arr, field):
for i in range(arr.shape[0]):
for j in range(arr.shape[1]):
append(j, i, arr, field)
extend.compile("(f4[:,::1], f4)")
llvmir = str(extend.inspect_llvm(extend.signatures[0]))
refops = list(re.finditer(r'(NRT_incref|NRT_decref)\([^\)]+\)', llvmir))
self.assertEqual(len(refops), 0)
if __name__ == '__main__':
unittest.main()
| true | true |
1c2e4c0a10f3cb8b077049e6c82ff994b4f0e5e5 | 15,130 | py | Python | rliable/library.py | DennisSoemers/rliable | 9f4c97d59196b70518f1ee3ba6d4f03a302c3241 | [
"Apache-2.0"
] | 361 | 2021-08-20T00:45:20.000Z | 2022-03-31T15:59:54.000Z | rliable/library.py | DennisSoemers/rliable | 9f4c97d59196b70518f1ee3ba6d4f03a302c3241 | [
"Apache-2.0"
] | 7 | 2021-09-04T00:37:39.000Z | 2022-01-31T19:21:45.000Z | rliable/library.py | DennisSoemers/rliable | 9f4c97d59196b70518f1ee3ba6d4f03a302c3241 | [
"Apache-2.0"
] | 22 | 2021-08-31T22:09:22.000Z | 2022-03-10T01:21:36.000Z | # coding=utf-8
# Copyright 2021 The Rliable Authors.
# 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.
"""Main library functions for interval estimates and performance profiles."""
from typing import Callable, Dict, List, Optional, Tuple, Union, Mapping
from absl import logging
import arch.bootstrap as arch_bs
import numpy as np
from numpy import random
Float = Union[float, np.float32, np.float64]
####################### Stratified Bootstrap #######################
class StratifiedBootstrap(arch_bs.IIDBootstrap):
"""Bootstrap using stratified resampling.
Supports numpy arrays. Data returned has the same type as the input data.
Data entered using keyword arguments is directly accessibly as an attribute.
To ensure a reproducible bootstrap, you must set the `random_state`
attribute after the bootstrap has been created. See the example below.
Note that `random_state` is a reserved keyword and any variable
passed using this keyword must be an instance of `RandomState`.
Examples
--------
Data can be accessed in a number of ways. Positional data is retained in
the same order as it was entered when the bootstrap was initialized.
Keyword data is available both as an attribute or using a dictionary syntax
on kw_data.
>>> from rliable.library import StratifiedBootstrap
>>> from numpy.random import standard_normal
>>> x = standard_normal((5, 50))
>>> bs = StratifiedBootstrap(x)
>>> for data in bs.bootstrap(100):
... bs_x = data[0][0]
>>> bs.conf_int(np.mean, method='percentile', reps=50000) # 95% CIs for mean
Set the random_state if reproducibility is required.
>>> from numpy.random import RandomState
>>> rs = RandomState(1234)
>>> bs = StratifiedBootstrap(x, random_state=rs)
See also: `arch.bootstrap.IIDBootstrap`
Attributes:
data: tuple, Two-element tuple with the pos_data in the first position and
kw_data in the second (pos_data, kw_data). Derived from `IIDBootstrap`.
pos_data: tuple, Tuple containing the positional arguments (in the order
entered). Derived from `IIDBootstrap`.
kw_data: dict, Dictionary containing the keyword arguments. Derived from
`IIDBootstrap`.
"""
_name = 'Stratified Bootstrap'
def __init__(
self,
*args: np.ndarray,
random_state: Optional[random.RandomState] = None,
task_bootstrap: bool = False,
**kwargs: np.ndarray,
) -> None:
"""Initializes StratifiedBootstrap.
Args:
*args: Positional arguments to bootstrap. Typically used for the
performance on a suite of tasks with multiple runs/episodes. The inputs
are assumed to be of the shape `(num_runs, num_tasks, ..)`.
random_state: If specified, ensures reproducibility in uncertainty
estimates.
task_bootstrap: Whether to perform bootstrapping (a) over runs or (b) over
both runs and tasks. Defaults to False which corresponds to (a). (a)
captures the statistical uncertainty in the aggregate performance if the
experiment is repeated using a different set of runs (e.g., changing
seeds) on the same set of tasks. (b) captures the sensitivity of the
aggregate performance to a given task and provides the performance
estimate if we had used a larger unknown population of tasks.
**kwargs: Keyword arguments, passed directly to `IIDBootstrap`.
"""
super().__init__(*args, random_state=random_state, **kwargs)
self._args_shape = args[0].shape
self._num_tasks = self._args_shape[1]
self._parameters = [self._num_tasks, task_bootstrap]
self._task_bootstrap = task_bootstrap
self._strata_indices = self._get_strata_indices()
def _get_strata_indices(self) -> List[np.ndarray]:
"""Samples partial indices for bootstrap resamples.
Returns:
A list of arrays of size N x 1 x 1 x .., 1 x M x 1 x ..,
1 x 1 x L x .. and so on, where the `args_shape` is `N x M x L x ..`.
"""
ogrid_indices = tuple(slice(x) for x in (0, *self._args_shape[1:]))
strata_indices = np.ogrid[ogrid_indices]
return strata_indices[1:]
def update_indices(self,) -> Tuple[np.ndarray, ...]:
"""Selects the indices to sample from the bootstrap distribution."""
# `self._num_items` corresponds to the number of runs
indices = np.random.choice(self._num_items, self._args_shape, replace=True)
if self._task_bootstrap:
task_indices = np.random.choice(
self._num_tasks, self._strata_indices[0].shape, replace=True)
return (indices, task_indices, *self._strata_indices[1:])
return (indices, *self._strata_indices)
class StratifiedIndependentBootstrap(arch_bs.IndependentSamplesBootstrap):
"""Stratified Bootstrap where each input is independently resampled.
This bootstrap is useful for computing CIs for metrics which take multiple
score arrays, possibly with different number of runs, as input, such as
average probability of improvement. See also: `StratifiedBootstrap` and
`arch_bs.IndependentSamplesBootstrap`.
Attributes:
data: tuple, Two-element tuple with the pos_data in the first position and
kw_data in the second (pos_data, kw_data). Derived from
`IndependentSamplesBootstrap`.
pos_data: tuple, Tuple containing the positional arguments (in the order
entered). Derived from `IndependentSamplesBootstrap`.
kw_data: dict, Dictionary containing the keyword arguments. Derived from
`IndependentSamplesBootstrap`.
"""
def __init__(
self,
*args: np.ndarray,
random_state: Optional[random.RandomState] = None,
**kwargs: np.ndarray,
) -> None:
"""Initializes StratifiedIndependentSamplesBootstrap.
Args:
*args: Positional arguments to bootstrap. Typically used for the
performance on a suite of tasks with multiple runs/episodes. The inputs
are assumed to be of the shape `(num_runs, num_tasks, ..)`.
random_state: If specified, ensures reproducibility in uncertainty
estimates.
**kwargs: Keyword arguments, passed directly to `IIDBootstrap`.
"""
super().__init__(*args, random_state=random_state, **kwargs)
self._args_shapes = [arg.shape for arg in args]
self._kwargs_shapes = {key: val.shape for key, val in self._kwargs.items()}
self._args_strata_indices = [
self._get_strata_indices(arg_shape) for arg_shape in self._args_shapes
]
self._kwargs_strata_indices = {
key: self._get_strata_indices(kwarg_shape)
for key, kwarg_shape in self._kwargs_shapes.items()
}
def _get_strata_indices(
self, array_shape: Tuple[int, ...]) -> List[np.ndarray]:
"""Samples partial indices for bootstrap resamples.
Args:
array_shape: Shape of array for which strata indices are created.
Returns:
A list of arrays of size N x 1 x 1 x .., 1 x M x 1 x ..,
1 x 1 x L x .. and so on, where the `array_shape` is `N x M x L x ..`.
"""
ogrid_indices = tuple(slice(x) for x in (0, *array_shape[1:]))
strata_indices = np.ogrid[ogrid_indices]
return strata_indices[1:]
def _get_indices(self, num_runs: int, array_shape: Tuple[int, ...],
strata_indices: List[np.ndarray]) -> Tuple[np.ndarray, ...]:
"""Helper function for updating bootstrap indices."""
indices = np.random.choice(num_runs, array_shape, replace=True)
return (indices, *strata_indices)
def update_indices(
self,
) -> Tuple[List[Tuple[np.ndarray, ...]], Dict[str, Tuple[np.ndarray, ...]]]:
"""Update independent sampling indices for the next bootstrap iteration."""
pos_indices = [
self._get_indices(self._num_arg_items[i], self._args_shapes[i],
self._args_strata_indices[i])
for i in range(self._num_args)
]
kw_indices = {}
for key in self._kwargs:
kw_indices[key] = self._get_indices(self._num_kw_items[key],
self._kwargs_shapes[key],
self._kwargs_strata_indices[key])
return pos_indices, kw_indices
####################### Interval Estimates #######################
def get_interval_estimates(
score_dict: Union[Mapping[str, np.ndarray], Mapping[str, List[np.ndarray]]],
func: Callable[..., np.ndarray],
method: str = 'percentile',
task_bootstrap: bool = False,
reps: int = 50000,
confidence_interval_size: Float = 0.95,
random_state: Optional[random.RandomState] = None,
) -> Tuple[Dict[str, np.ndarray], Dict[str, np.ndarray]]:
"""Computes interval estimates via stratified bootstrap confidence intervals.
Args:
score_dict: A dictionary of scores for each method where scores are arranged
as a matrix of the shape (`num_runs` x `num_tasks` x ..). For example, the
scores could be 2D matrix containing final scores of the algorithm or a 3D
matrix containing evaluation scores at multiple points during training.
func: Function that computes the aggregate performance, which outputs a 1D
numpy array. See Notes for requirements. For example, if computing
estimates for interquartile mean across all runs, pass the function as
`lambda x: np.array([metrics.aggregate_IQM])`.
method: One of `basic`, `percentile`, `bc` (identical to `debiased`,
`bias-corrected’), or ‘bca`.
task_bootstrap: Whether to perform bootstrapping over tasks in addition to
runs. Defaults to False. See `StratifiedBoostrap` for more details.
reps: Number of bootstrap replications.
confidence_interval_size: Coverage of confidence interval. Defaults to 95%.
random_state: If specified, ensures reproducibility in uncertainty
estimates.
Returns:
point_estimates: A dictionary of point estimates obtained by applying `func`
on score data corresponding to each key in `data_dict`.
interval_estimates: Confidence intervals~(CIs) for point estimates. Default
is to return 95% CIs. Returns a np array of size (2 x ..) where the first
row contains the lower bounds while the second row contains the upper
bound of the 95% CIs.
Notes:
When there are no extra keyword arguments, the function is called
.. code:: python
func(*args, **kwargs)
where args and kwargs are the bootstrap version of the data provided
when setting up the bootstrap. When extra keyword arguments are used,
these are appended to kwargs before calling func.
The bootstraps are:
* 'basic' - Basic confidence using the estimated parameter and
difference between the estimated parameter and the bootstrap
parameters.
* 'percentile' - Direct use of bootstrap percentiles.
* 'bc' - Bias corrected using estimate bootstrap bias correction.
* 'bca' - Bias corrected and accelerated, adding acceleration parameter
to 'bc' method.
"""
interval_estimates, point_estimates = {}, {}
for key, scores in score_dict.items():
logging.info('Calculating estimates for %s ...', key)
if isinstance(scores, np.ndarray):
stratified_bs = StratifiedBootstrap(
scores, task_bootstrap=task_bootstrap, random_state=random_state)
point_estimates[key] = func(scores)
else:
# Pass arrays as separate arguments, `task_bootstrap` is not supported
stratified_bs = StratifiedIndependentBootstrap(
*scores,
random_state=random_state)
point_estimates[key] = func(*scores)
interval_estimates[key] = stratified_bs.conf_int(
func, reps=reps, size=confidence_interval_size, method=method)
return point_estimates, interval_estimates
####################### Performance Profiles #######################
def run_score_deviation(scores: np.ndarray, tau: Float) -> Float:
"""Evaluates how many `scores` are above `tau` averaged across all runs."""
return np.mean(scores > tau)
def mean_score_deviation(scores: np.ndarray, tau: Float) -> Float:
"""Evaluates how many average task `scores` are above `tau`."""
return np.mean(np.mean(scores, axis=0) > tau)
score_distributions = np.vectorize(run_score_deviation, excluded=[0])
average_score_distributions = np.vectorize(mean_score_deviation, excluded=[0])
def create_performance_profile(
score_dict: Mapping[str, np.ndarray],
tau_list: Union[List[Float], np.ndarray],
use_score_distribution: bool = True,
custom_profile_func: Optional[Callable[..., np.ndarray]] = None,
method: str = 'percentile',
task_bootstrap: bool = False,
reps: int = 2000,
confidence_interval_size: Float = 0.95
) -> Tuple[Dict[str, np.ndarray], Dict[str, np.ndarray]]:
"""Function for calculating performance profiles.
Args:
score_dict: A dictionary of scores for each method where scores are arranged
as a matrix of the shape (`num_runs` x `num_tasks` x ..).
tau_list: List or 1D numpy array of threshold values on which the profile is
evaluated.
use_score_distribution: Whether to report score distributions or average
score distributions. Defaults to score distributions for smaller
uncertainty in reported results with unbiased profiles.
custom_profile_func: Custom performance profile function. Can be used to
compute performance profiles other than score distributions.
method: Bootstrap method for `StratifiedBootstrap`, defaults to percentile.
task_bootstrap: Whether to perform bootstrapping over tasks in addition to
runs. Defaults to False. See `StratifiedBoostrap` for more details.
reps: Number of bootstrap replications.
confidence_interval_size: Coverage of confidence interval. Defaults to 95%.
Returns:
profiles: A dictionary of performance profiles for each key in `score_dict`.
Each profile is a 1D np array of same size as `tau_list`.
profile_cis: The 95% confidence intervals of profiles evaluated at
all threshdolds in `tau_list`.
"""
if custom_profile_func is None:
def profile_function(scores):
if use_score_distribution:
# Performance profile for scores across all tasks and runs
return score_distributions(scores, tau_list)
# Performance profile for task scores averaged across runs
return average_score_distributions(scores, tau_list)
else:
profile_function = lambda scores: custom_profile_func(scores, tau_list)
profiles, profile_cis = get_interval_estimates(
score_dict,
func=profile_function,
task_bootstrap=task_bootstrap,
method=method,
reps=reps,
confidence_interval_size=confidence_interval_size)
return profiles, profile_cis
| 42.619718 | 80 | 0.706345 |
from typing import Callable, Dict, List, Optional, Tuple, Union, Mapping
from absl import logging
import arch.bootstrap as arch_bs
import numpy as np
from numpy import random
Float = Union[float, np.float32, np.float64]
args_shapes = {key: val.shape for key, val in self._kwargs.items()}
self._args_strata_indices = [
self._get_strata_indices(arg_shape) for arg_shape in self._args_shapes
]
self._kwargs_strata_indices = {
key: self._get_strata_indices(kwarg_shape)
for key, kwarg_shape in self._kwargs_shapes.items()
}
def _get_strata_indices(
self, array_shape: Tuple[int, ...]) -> List[np.ndarray]:
ogrid_indices = tuple(slice(x) for x in (0, *array_shape[1:]))
strata_indices = np.ogrid[ogrid_indices]
return strata_indices[1:]
def _get_indices(self, num_runs: int, array_shape: Tuple[int, ...],
strata_indices: List[np.ndarray]) -> Tuple[np.ndarray, ...]:
indices = np.random.choice(num_runs, array_shape, replace=True)
return (indices, *strata_indices)
def update_indices(
self,
) -> Tuple[List[Tuple[np.ndarray, ...]], Dict[str, Tuple[np.ndarray, ...]]]:
pos_indices = [
self._get_indices(self._num_arg_items[i], self._args_shapes[i],
self._args_strata_indices[i])
for i in range(self._num_args)
]
kw_indices = {}
for key in self._kwargs:
kw_indices[key] = self._get_indices(self._num_kw_items[key],
self._kwargs_shapes[key],
self._kwargs_strata_indices[key])
return pos_indices, kw_indices
| true | true |
1c2e4c6f4061b20735d75dc5ba9f1d42d8f45267 | 3,535 | py | Python | zvt/tag/tags/cycle_tag.py | KtineXu/zvt | 3c1fdbb1c579225a59567ff211001f3c2c16a915 | [
"MIT"
] | null | null | null | zvt/tag/tags/cycle_tag.py | KtineXu/zvt | 3c1fdbb1c579225a59567ff211001f3c2c16a915 | [
"MIT"
] | null | null | null | zvt/tag/tags/cycle_tag.py | KtineXu/zvt | 3c1fdbb1c579225a59567ff211001f3c2c16a915 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
from enum import Enum
from zvt.domain import Stock, BlockStock, Block
from zvt.tag.dataset.stock_tags import StockTags
from zvt.tag.tag import StockTagger
class CycleTag(Enum):
# 强周期
strong_cycle = 'strong_cycle'
# 弱周期
weak_cycle = 'weak_cycle'
# 非周期,受周期影响不大,比如消费,医药
non_cycle = 'non_cycle'
# 这里用的是东财的行业分类
# 数据来源
# Block.record_data(provider='eastmoney')
# Block.query_data(provider='eastmoney', filters=[Block.category==industry])
# BlockStock.record_data(provider='eastmoney')
# 这不是一个严格的分类,好像也不需要太严格
cycle_map_industry = {
CycleTag.strong_cycle: ['有色金属', '水泥建材', '化工行业', '输配电气', '化纤行业',
'钢铁行业', '煤炭采选', '化肥行业', '贵金属', '船舶制造',
'房地产', '石油行业', '港口水运', '材料行业', '工程建设',
'包装材料', '券商信托', '机械行业', '金属制品', '塑胶制品',
'环保工程', '玻璃陶瓷'],
CycleTag.weak_cycle: ['电力行业', '民航机场', '家电行业', '旅游酒店', '银行',
'保险', '高速公路', '电子信息', '通讯行业', '多元金融',
'电子元件', '国际贸易', '珠宝首饰', '交运物流', '航天航空',
'交运设备', '汽车行业', '专用设备', '园林工程', '造纸印刷',
'安防设备', '装修装饰', '木业家具'],
CycleTag.non_cycle: ['食品饮料', '酿酒行业', '医疗行业', '医药制造', '文教休闲',
'软件服务', '商业百货', '文化传媒', '农牧饲渔', '公用事业',
'纺织服装', '综合行业', '仪器仪表', '电信运营', '工艺商品',
'农药兽药']
}
def get_cycle_tag(industry_name):
for cycle_tag in cycle_map_industry:
if industry_name in cycle_map_industry.get(cycle_tag):
return cycle_tag.name
class CycleTagger(StockTagger):
def tag(self, timestamp):
stock_df = Stock.query_data(filters=[Stock.list_date <= timestamp], index='entity_id')
block_df = Block.query_data(provider='eastmoney', filters=[Block.category == 'industry'], index='entity_id')
block_ids = block_df.index.tolist()
block_stock_df = BlockStock.query_data(provider='eastmoney',
entity_ids=block_ids,
filters=[BlockStock.stock_id.in_(stock_df.index.tolist())],
index='stock_id')
block_stock_df['cycle_tag'] = block_stock_df['name'].apply(lambda name: get_cycle_tag(name))
strong_cycle_stocks = block_stock_df[block_stock_df.cycle_tag == 'strong_cycle']['stock_id']
weak_cycle_stocks = block_stock_df[block_stock_df.cycle_tag == 'weak_cycle']['stock_id']
non_cycle_stocks = block_stock_df[block_stock_df.cycle_tag == 'non_cycle']['stock_id']
strong_cycle_domains = self.get_tag_domains(entity_ids=strong_cycle_stocks, timestamp=timestamp,
cycle_tag=CycleTag.strong_cycle.value)
weak_cycle_domains = self.get_tag_domains(entity_ids=weak_cycle_stocks, timestamp=timestamp,
cycle_tag=CycleTag.weak_cycle.value)
non_cycle_domains = self.get_tag_domains(entity_ids=non_cycle_stocks, timestamp=timestamp,
cycle_tag=CycleTag.non_cycle.value)
self.session.add_all(strong_cycle_domains)
self.session.add_all(weak_cycle_domains)
self.session.add_all(non_cycle_domains)
self.session.commit()
if __name__ == '__main__':
CycleTagger().run()
print(StockTags.query_data(start_timestamp='2021-08-31', filters=[StockTags.cycle_tag != None]))
| 44.746835 | 116 | 0.584724 |
from enum import Enum
from zvt.domain import Stock, BlockStock, Block
from zvt.tag.dataset.stock_tags import StockTags
from zvt.tag.tag import StockTagger
class CycleTag(Enum):
strong_cycle = 'strong_cycle'
weak_cycle = 'weak_cycle'
non_cycle = 'non_cycle'
cycle_map_industry = {
CycleTag.strong_cycle: ['有色金属', '水泥建材', '化工行业', '输配电气', '化纤行业',
'钢铁行业', '煤炭采选', '化肥行业', '贵金属', '船舶制造',
'房地产', '石油行业', '港口水运', '材料行业', '工程建设',
'包装材料', '券商信托', '机械行业', '金属制品', '塑胶制品',
'环保工程', '玻璃陶瓷'],
CycleTag.weak_cycle: ['电力行业', '民航机场', '家电行业', '旅游酒店', '银行',
'保险', '高速公路', '电子信息', '通讯行业', '多元金融',
'电子元件', '国际贸易', '珠宝首饰', '交运物流', '航天航空',
'交运设备', '汽车行业', '专用设备', '园林工程', '造纸印刷',
'安防设备', '装修装饰', '木业家具'],
CycleTag.non_cycle: ['食品饮料', '酿酒行业', '医疗行业', '医药制造', '文教休闲',
'软件服务', '商业百货', '文化传媒', '农牧饲渔', '公用事业',
'纺织服装', '综合行业', '仪器仪表', '电信运营', '工艺商品',
'农药兽药']
}
def get_cycle_tag(industry_name):
for cycle_tag in cycle_map_industry:
if industry_name in cycle_map_industry.get(cycle_tag):
return cycle_tag.name
class CycleTagger(StockTagger):
def tag(self, timestamp):
stock_df = Stock.query_data(filters=[Stock.list_date <= timestamp], index='entity_id')
block_df = Block.query_data(provider='eastmoney', filters=[Block.category == 'industry'], index='entity_id')
block_ids = block_df.index.tolist()
block_stock_df = BlockStock.query_data(provider='eastmoney',
entity_ids=block_ids,
filters=[BlockStock.stock_id.in_(stock_df.index.tolist())],
index='stock_id')
block_stock_df['cycle_tag'] = block_stock_df['name'].apply(lambda name: get_cycle_tag(name))
strong_cycle_stocks = block_stock_df[block_stock_df.cycle_tag == 'strong_cycle']['stock_id']
weak_cycle_stocks = block_stock_df[block_stock_df.cycle_tag == 'weak_cycle']['stock_id']
non_cycle_stocks = block_stock_df[block_stock_df.cycle_tag == 'non_cycle']['stock_id']
strong_cycle_domains = self.get_tag_domains(entity_ids=strong_cycle_stocks, timestamp=timestamp,
cycle_tag=CycleTag.strong_cycle.value)
weak_cycle_domains = self.get_tag_domains(entity_ids=weak_cycle_stocks, timestamp=timestamp,
cycle_tag=CycleTag.weak_cycle.value)
non_cycle_domains = self.get_tag_domains(entity_ids=non_cycle_stocks, timestamp=timestamp,
cycle_tag=CycleTag.non_cycle.value)
self.session.add_all(strong_cycle_domains)
self.session.add_all(weak_cycle_domains)
self.session.add_all(non_cycle_domains)
self.session.commit()
if __name__ == '__main__':
CycleTagger().run()
print(StockTags.query_data(start_timestamp='2021-08-31', filters=[StockTags.cycle_tag != None]))
| true | true |
1c2e4c7dbc3b5f88af53b55c65475ce89c3a4685 | 11,268 | py | Python | venv/Lib/site-packages/gevent/lock.py | asanka9/Quession-Discussion-App-Socket.Io-NLP | 95a49a8afa572dc3908a0bade45e424c3751f191 | [
"Apache-2.0"
] | 6 | 2020-08-04T13:12:42.000Z | 2020-08-16T13:26:19.000Z | venv/Lib/site-packages/gevent/lock.py | asanka9/Quession-Discussion-App-Socket.Io-NLP | 95a49a8afa572dc3908a0bade45e424c3751f191 | [
"Apache-2.0"
] | null | null | null | venv/Lib/site-packages/gevent/lock.py | asanka9/Quession-Discussion-App-Socket.Io-NLP | 95a49a8afa572dc3908a0bade45e424c3751f191 | [
"Apache-2.0"
] | null | null | null | # Copyright (c) 2009-2012 Denis Bilenko. See LICENSE for details.
"""
Locking primitives.
These include semaphores with arbitrary bounds (:class:`Semaphore` and
its safer subclass :class:`BoundedSemaphore`) and a semaphore with
infinite bounds (:class:`DummySemaphore`), along with a reentrant lock
(:class:`RLock`) with the same API as :class:`threading.RLock`.
"""
from __future__ import absolute_import
from gevent.hub import getcurrent
from gevent._compat import PURE_PYTHON
from gevent._compat import PY2
# This is the one exception to the rule of where to
# import Semaphore, obviously
from gevent import monkey
from gevent._semaphore import Semaphore
from gevent._semaphore import BoundedSemaphore
__all__ = [
'Semaphore',
'BoundedSemaphore',
'DummySemaphore',
'RLock',
]
# On PyPy, we don't compile the Semaphore class with Cython. Under
# Cython, each individual method holds the GIL for its entire
# duration, ensuring that no other thread can interrupt us in an
# unsafe state (only when we _wait do we call back into Python and
# allow switching threads; this is broken down into the
# _drop_lock_for_switch_out and _acquire_lock_for_switch_in methods).
# Simulate that here through the use of a manual lock. (We use a
# separate lock for each semaphore to allow sys.settrace functions to
# use locks *other* than the one being traced.) This, of course, must
# also hold for PURE_PYTHON mode when no optional C extensions are
# used.
_allocate_lock, _get_ident = monkey.get_original(
('_thread', 'thread'),
('allocate_lock', 'get_ident')
)
class _OwnedLock(object):
__slots__ = (
'_owner',
'_block',
'_locking',
'_count',
)
# Don't allow re-entry to these functions in a single thread, as can
# happen if a sys.settrace is used.
#
# This is essentially a variant of the (pure-Python) RLock from the
# standard library.
def __init__(self):
self._owner = None
self._block = _allocate_lock()
self._locking = {}
self._count = 0
def __begin(self):
# Return (me, count) if we should proceed, otherwise return
# None. The function should exit in that case.
# In either case, it must call __end.
me = _get_ident()
try:
count = self._locking[me]
except KeyError:
count = self._locking[me] = 1
else:
count = self._locking[me] = count + 1
return (me, count) if not count else (None, None)
def __end(self, me, count):
if me is None:
return
count = count - 1
if not count:
del self._locking[me]
else:
self._locking[me] = count
def __enter__(self):
me, lock_count = self.__begin()
try:
if me is None:
return
if self._owner == me:
self._count += 1
return
self._block.acquire()
self._owner = me
self._count = 1
finally:
self.__end(me, lock_count)
def __exit__(self, t, v, tb):
self.release()
acquire = __enter__
def release(self):
me, lock_count = self.__begin()
try:
if me is None:
return
self._count = count = self._count - 1
if not count:
self._owner = None
self._block.release()
finally:
self.__end(me, lock_count)
class _AtomicSemaphoreMixin(object):
# Behaves as though the GIL was held for the duration of acquire, wait,
# and release, just as if we were in Cython.
#
# acquire, wait, and release all acquire the lock on entry and release it
# on exit. acquire and wait can call _wait, which must release it on entry
# and re-acquire it for them on exit.
#
# Note that this does *NOT*, in-and-of itself, make semaphores safe to use from multiple threads
__slots__ = ()
def __init__(self, *args, **kwargs):
self._lock_lock = _OwnedLock() # pylint:disable=assigning-non-slot
super(_AtomicSemaphoreMixin, self).__init__(*args, **kwargs)
def _acquire_lock_for_switch_in(self):
self._lock_lock.acquire()
def _drop_lock_for_switch_out(self):
self._lock_lock.release()
def _notify_links(self, arrived_while_waiting):
with self._lock_lock:
return super(_AtomicSemaphoreMixin, self)._notify_links(arrived_while_waiting)
def release(self):
with self._lock_lock:
return super(_AtomicSemaphoreMixin, self).release()
def acquire(self, blocking=True, timeout=None):
with self._lock_lock:
return super(_AtomicSemaphoreMixin, self).acquire(blocking, timeout)
_py3k_acquire = acquire
def wait(self, timeout=None):
with self._lock_lock:
return super(_AtomicSemaphoreMixin, self).wait(timeout)
class _AtomicSemaphore(_AtomicSemaphoreMixin, Semaphore):
__doc__ = Semaphore.__doc__
__slots__ = (
'_lock_lock',
)
class _AtomicBoundedSemaphore(_AtomicSemaphoreMixin, BoundedSemaphore):
__doc__ = BoundedSemaphore.__doc__
__slots__ = (
'_lock_lock',
)
def release(self): # pylint:disable=useless-super-delegation
# This method is duplicated here so that it can get
# properly documented.
return super(_AtomicBoundedSemaphore, self).release()
def _fixup_docstrings():
for c in _AtomicSemaphore, _AtomicBoundedSemaphore:
b = c.__mro__[2]
assert b.__name__.endswith('Semaphore') and 'Atomic' not in b.__name__
assert c.__doc__ == b.__doc__
for m in 'acquire', 'release', 'wait':
c_meth = getattr(c, m)
if PY2:
c_meth = c_meth.__func__
b_meth = getattr(b, m)
c_meth.__doc__ = b_meth.__doc__
_fixup_docstrings()
del _fixup_docstrings
if PURE_PYTHON:
Semaphore = _AtomicSemaphore
Semaphore.__name__ = 'Semaphore'
BoundedSemaphore = _AtomicBoundedSemaphore
BoundedSemaphore.__name__ = 'BoundedSemaphore'
class DummySemaphore(object):
"""
DummySemaphore(value=None) -> DummySemaphore
An object with the same API as :class:`Semaphore`,
initialized with "infinite" initial value. None of its
methods ever block.
This can be used to parameterize on whether or not to actually
guard access to a potentially limited resource. If the resource is
actually limited, such as a fixed-size thread pool, use a real
:class:`Semaphore`, but if the resource is unbounded, use an
instance of this class. In that way none of the supporting code
needs to change.
Similarly, it can be used to parameterize on whether or not to
enforce mutual exclusion to some underlying object. If the
underlying object is known to be thread-safe itself mutual
exclusion is not needed and a ``DummySemaphore`` can be used, but
if that's not true, use a real ``Semaphore``.
"""
# Internally this is used for exactly the purpose described in the
# documentation. gevent.pool.Pool uses it instead of a Semaphore
# when the pool size is unlimited, and
# gevent.fileobject.FileObjectThread takes a parameter that
# determines whether it should lock around IO to the underlying
# file object.
def __init__(self, value=None):
"""
.. versionchanged:: 1.1rc3
Accept and ignore a *value* argument for compatibility with Semaphore.
"""
def __str__(self):
return '<%s>' % self.__class__.__name__
def locked(self):
"""A DummySemaphore is never locked so this always returns False."""
return False
def ready(self):
"""A DummySemaphore is never locked so this always returns True."""
return True
def release(self):
"""Releasing a dummy semaphore does nothing."""
def rawlink(self, callback):
# XXX should still work and notify?
pass
def unlink(self, callback):
pass
def wait(self, timeout=None): # pylint:disable=unused-argument
"""Waiting for a DummySemaphore returns immediately."""
return 1
def acquire(self, blocking=True, timeout=None):
"""
A DummySemaphore can always be acquired immediately so this always
returns True and ignores its arguments.
.. versionchanged:: 1.1a1
Always return *true*.
"""
# pylint:disable=unused-argument
return True
def __enter__(self):
pass
def __exit__(self, typ, val, tb):
pass
class RLock(object):
"""
A mutex that can be acquired more than once by the same greenlet.
A mutex can only be locked by one greenlet at a time. A single greenlet
can `acquire` the mutex as many times as desired, though. Each call to
`acquire` must be paired with a matching call to `release`.
It is an error for a greenlet that has not acquired the mutex
to release it.
Instances are context managers.
"""
__slots__ = (
'_block',
'_owner',
'_count',
'__weakref__',
)
def __init__(self, hub=None):
"""
.. versionchanged:: 20.5.1
Add the ``hub`` argument.
"""
self._block = Semaphore(1, hub)
self._owner = None
self._count = 0
def __repr__(self):
return "<%s at 0x%x _block=%s _count=%r _owner=%r)>" % (
self.__class__.__name__,
id(self),
self._block,
self._count,
self._owner)
def acquire(self, blocking=True, timeout=None):
"""
Acquire the mutex, blocking if *blocking* is true, for up to
*timeout* seconds.
.. versionchanged:: 1.5a4
Added the *timeout* parameter.
:return: A boolean indicating whether the mutex was acquired.
"""
me = getcurrent()
if self._owner is me:
self._count = self._count + 1
return 1
rc = self._block.acquire(blocking, timeout)
if rc:
self._owner = me
self._count = 1
return rc
def __enter__(self):
return self.acquire()
def release(self):
"""
Release the mutex.
Only the greenlet that originally acquired the mutex can
release it.
"""
if self._owner is not getcurrent():
raise RuntimeError("cannot release un-acquired lock")
self._count = count = self._count - 1
if not count:
self._owner = None
self._block.release()
def __exit__(self, typ, value, tb):
self.release()
# Internal methods used by condition variables
def _acquire_restore(self, count_owner):
count, owner = count_owner
self._block.acquire()
self._count = count
self._owner = owner
def _release_save(self):
count = self._count
self._count = 0
owner = self._owner
self._owner = None
self._block.release()
return (count, owner)
def _is_owned(self):
return self._owner is getcurrent()
| 29.888594 | 100 | 0.631434 |
from __future__ import absolute_import
from gevent.hub import getcurrent
from gevent._compat import PURE_PYTHON
from gevent._compat import PY2
from gevent import monkey
from gevent._semaphore import Semaphore
from gevent._semaphore import BoundedSemaphore
__all__ = [
'Semaphore',
'BoundedSemaphore',
'DummySemaphore',
'RLock',
]
# Cython, each individual method holds the GIL for its entire
# duration, ensuring that no other thread can interrupt us in an
# unsafe state (only when we _wait do we call back into Python and
# allow switching threads; this is broken down into the
# _drop_lock_for_switch_out and _acquire_lock_for_switch_in methods).
# Simulate that here through the use of a manual lock. (We use a
# separate lock for each semaphore to allow sys.settrace functions to
# use locks *other* than the one being traced.) This, of course, must
# also hold for PURE_PYTHON mode when no optional C extensions are
# used.
_allocate_lock, _get_ident = monkey.get_original(
('_thread', 'thread'),
('allocate_lock', 'get_ident')
)
class _OwnedLock(object):
__slots__ = (
'_owner',
'_block',
'_locking',
'_count',
)
# Don't allow re-entry to these functions in a single thread, as can
def __init__(self):
self._owner = None
self._block = _allocate_lock()
self._locking = {}
self._count = 0
def __begin(self):
me = _get_ident()
try:
count = self._locking[me]
except KeyError:
count = self._locking[me] = 1
else:
count = self._locking[me] = count + 1
return (me, count) if not count else (None, None)
def __end(self, me, count):
if me is None:
return
count = count - 1
if not count:
del self._locking[me]
else:
self._locking[me] = count
def __enter__(self):
me, lock_count = self.__begin()
try:
if me is None:
return
if self._owner == me:
self._count += 1
return
self._block.acquire()
self._owner = me
self._count = 1
finally:
self.__end(me, lock_count)
def __exit__(self, t, v, tb):
self.release()
acquire = __enter__
def release(self):
me, lock_count = self.__begin()
try:
if me is None:
return
self._count = count = self._count - 1
if not count:
self._owner = None
self._block.release()
finally:
self.__end(me, lock_count)
class _AtomicSemaphoreMixin(object):
__slots__ = ()
def __init__(self, *args, **kwargs):
self._lock_lock = _OwnedLock()
super(_AtomicSemaphoreMixin, self).__init__(*args, **kwargs)
def _acquire_lock_for_switch_in(self):
self._lock_lock.acquire()
def _drop_lock_for_switch_out(self):
self._lock_lock.release()
def _notify_links(self, arrived_while_waiting):
with self._lock_lock:
return super(_AtomicSemaphoreMixin, self)._notify_links(arrived_while_waiting)
def release(self):
with self._lock_lock:
return super(_AtomicSemaphoreMixin, self).release()
def acquire(self, blocking=True, timeout=None):
with self._lock_lock:
return super(_AtomicSemaphoreMixin, self).acquire(blocking, timeout)
_py3k_acquire = acquire
def wait(self, timeout=None):
with self._lock_lock:
return super(_AtomicSemaphoreMixin, self).wait(timeout)
class _AtomicSemaphore(_AtomicSemaphoreMixin, Semaphore):
__doc__ = Semaphore.__doc__
__slots__ = (
'_lock_lock',
)
class _AtomicBoundedSemaphore(_AtomicSemaphoreMixin, BoundedSemaphore):
__doc__ = BoundedSemaphore.__doc__
__slots__ = (
'_lock_lock',
)
def release(self):
return super(_AtomicBoundedSemaphore, self).release()
def _fixup_docstrings():
for c in _AtomicSemaphore, _AtomicBoundedSemaphore:
b = c.__mro__[2]
assert b.__name__.endswith('Semaphore') and 'Atomic' not in b.__name__
assert c.__doc__ == b.__doc__
for m in 'acquire', 'release', 'wait':
c_meth = getattr(c, m)
if PY2:
c_meth = c_meth.__func__
b_meth = getattr(b, m)
c_meth.__doc__ = b_meth.__doc__
_fixup_docstrings()
del _fixup_docstrings
if PURE_PYTHON:
Semaphore = _AtomicSemaphore
Semaphore.__name__ = 'Semaphore'
BoundedSemaphore = _AtomicBoundedSemaphore
BoundedSemaphore.__name__ = 'BoundedSemaphore'
class DummySemaphore(object):
def __init__(self, value=None):
def __str__(self):
return '<%s>' % self.__class__.__name__
def locked(self):
return False
def ready(self):
return True
def release(self):
def rawlink(self, callback):
pass
def unlink(self, callback):
pass
def wait(self, timeout=None):
return 1
def acquire(self, blocking=True, timeout=None):
return True
def __enter__(self):
pass
def __exit__(self, typ, val, tb):
pass
class RLock(object):
__slots__ = (
'_block',
'_owner',
'_count',
'__weakref__',
)
def __init__(self, hub=None):
self._block = Semaphore(1, hub)
self._owner = None
self._count = 0
def __repr__(self):
return "<%s at 0x%x _block=%s _count=%r _owner=%r)>" % (
self.__class__.__name__,
id(self),
self._block,
self._count,
self._owner)
def acquire(self, blocking=True, timeout=None):
me = getcurrent()
if self._owner is me:
self._count = self._count + 1
return 1
rc = self._block.acquire(blocking, timeout)
if rc:
self._owner = me
self._count = 1
return rc
def __enter__(self):
return self.acquire()
def release(self):
if self._owner is not getcurrent():
raise RuntimeError("cannot release un-acquired lock")
self._count = count = self._count - 1
if not count:
self._owner = None
self._block.release()
def __exit__(self, typ, value, tb):
self.release()
def _acquire_restore(self, count_owner):
count, owner = count_owner
self._block.acquire()
self._count = count
self._owner = owner
def _release_save(self):
count = self._count
self._count = 0
owner = self._owner
self._owner = None
self._block.release()
return (count, owner)
def _is_owned(self):
return self._owner is getcurrent()
| true | true |
1c2e4db653cb665625fad9379f5532990b041c03 | 65,422 | py | Python | watertap3/watertap3/wt_units/ion_exchange.py | NREL/WaterTAP3 | 74b83dbd189784ccfddac4bc5d27002190473619 | [
"BSD-3-Clause"
] | null | null | null | watertap3/watertap3/wt_units/ion_exchange.py | NREL/WaterTAP3 | 74b83dbd189784ccfddac4bc5d27002190473619 | [
"BSD-3-Clause"
] | 34 | 2021-06-25T17:54:12.000Z | 2021-06-25T17:54:27.000Z | watertap3/watertap3/wt_units/ion_exchange.py | NREL/WaterTAP3 | 74b83dbd189784ccfddac4bc5d27002190473619 | [
"BSD-3-Clause"
] | 4 | 2021-06-25T18:32:31.000Z | 2022-03-24T20:24:18.000Z | import pandas as pd
from pyomo.environ import *
from pyomo.environ import units as pyunits
from pyomo.repn.plugins.baron_writer import NonNegativeReals
from watertap3.utils import financials
from watertap3.wt_units.wt_unit import WT3UnitProcess
## REFERENCE: ADD REFERENCE HERE
module_name = 'ion_exchange'
basis_year = 2016 # 2016 is costing year for EPA component costing data
tpec_or_tic = 'TIC'
class UnitProcess(WT3UnitProcess):
def fixed_cap(self, unit_params):
'''
Docstrings go here.
:return:
'''
time = self.flowsheet().config.time
self.total_ix_cap = Var(time,
initialize=25,
domain=NonNegativeReals,
doc='Total ion exchange FCI [$MM]')
self.cap_per_column = Var(time,
initialize=1,
domain=NonNegativeReals,
doc='Capital per column [$MM]')
self.column_total_cap = Var(time,
initialize=1,
domain=NonNegativeReals,
doc='Total column capital [$MM]')
self.resin_unit_cap = Var(time,
initialize=4000,
domain=NonNegativeReals,
doc='Resin cap per m3 [$/m3]')
self.resin_cap = Var(time,
initialize=1E4,
domain=NonNegativeReals,
doc='Resin capital [$MM]')
self.regen_pump_cap = Var(time,
initialize=100,
domain=NonNegativeReals,
doc='Pump capital for regen cycle [$MM]')
self.bw_pump_cap = Var(time,
initialize=100,
domain=NonNegativeReals,
doc='Pump capital for backwash cycle [$MM]')
self.rinse_pump_cap = Var(time,
initialize=100,
domain=NonNegativeReals,
doc='Pump capital for rinse cycle [$MM]')
self.boost_pump_cap = Var(time,
initialize=100,
domain=NonNegativeReals,
doc='Pump capital for booster pump [#MM]')
if self.pv_material == 'carbon_w_stainless_internals':
self.cap_per_column_constr = Constraint(expr=self.cap_per_column[self.t] ==
(16504 * self.column_vol[self.t] ** 0.43) * 1E-6)
if self.pv_material == 'carbon_w_plastic_internals':
self.cap_per_column_constr = Constraint(expr=self.cap_per_column[self.t] ==
(9120 * self.column_vol[self.t] ** 0.49) * 1E-6)
if self.pv_material == 'fiberglass':
self.cap_per_column_constr = Constraint(expr=self.cap_per_column[self.t] ==
(5637 * self.column_vol[self.t] ** 0.9) * 1E-6)
self.col_total_cap_constr = Constraint(expr=self.column_total_cap[self.t] == self.cap_per_column[self.t] * (self.num_columns[self.t] + 1))
self.resin_unit_cap.fix(self.resin_dict[self.resin_type])
self.resin_cap_constr = Constraint(expr=self.resin_cap[self.t] == ((self.resin_vol[self.t] + self.resin_per_column[self.t]) * self.resin_unit_cap[self.t]) * 1E-6) # include an additional resin vol per column to account for the extra column
self.regen_pump_cap_constr = Constraint(expr=self.regen_pump_cap[self.t] == (-24.257 * self.regen_flow[self.t] ** 2 + 2803.7 * self.regen_flow[self.t] + 7495.7) *
(self.num_columns[self.t] + 1) * 1E-6) # assumes centrifugal pump and 1 pump per column
self.bw_pump_cap_constr = Constraint(expr=self.bw_pump_cap[self.t] == (-24.257 * self.bw_flow[self.t] ** 2 + 2803.7 * self.bw_flow[self.t] + 7495.7) *
(self.num_columns[self.t] + 1) * 1E-6) # assumes centrifugal pump and 1 pump per column
self.rinse_pump_cap_constr = Constraint(expr=self.rinse_pump_cap[self.t] == (-24.257 * self.rinse_flow[self.t] ** 2 + 2803.7 * self.rinse_flow[self.t] + 7495.7) *
(self.num_columns[self.t] + 1) * 1E-6) # assumes centrifugal pump and 1 pump per column
self.flow_per_col_m3_min = pyunits.convert(self.flow_per_column[self.t], to_units=pyunits.m ** 3 / pyunits.min)
self.boost_pump_cap_constr = Constraint(expr=self.boost_pump_cap[self.t] == (-24.257 * self.flow_per_col_m3_min ** 2 + 2803.7 * self.flow_per_col_m3_min + 7495.7) *
(self.num_columns[self.t] + 1) * 1E-6) # assumes centrifugal pump and 1 pump per column
self.total_ix_cap_constr = Constraint(expr=self.total_ix_cap[self.t] ==
self.column_total_cap[self.t] + self.resin_cap[self.t] + self.regen_pump_cap[self.t] + self.bw_pump_cap[self.t] + self.rinse_pump_cap[self.t] + self.boost_pump_cap[self.t])
return self.total_ix_cap[self.t] * self.tpec_tic
def elect(self):
'''
Electricity intensity for ion exchange
:return:
'''
time = self.flowsheet().config.time
self.main_pump_ei = Var(time,
initialize=4E-6,
domain=NonNegativeReals,
doc='Electricity intensity for main pump [kWh/m3]')
self.regen_pump_ei = Var(time,
initialize=4E-6,
domain=NonNegativeReals,
doc='Electricity intensity for regen pump [kWh/m3]')
self.bw_pump_ei = Var(time,
initialize=4E-6,
domain=NonNegativeReals,
doc='Electricity intensity for backwash pump [kWh/m3]')
self.rinse_pump_ei = Var(time,
initialize=4E-6,
domain=NonNegativeReals,
doc='Electricity intensity for rinse pump [kWh/m3]')
self.total_pump_ei = Var(time,
initialize=4E-5,
domain=NonNegativeReals,
doc='Total pumping electricity intensity [kWh/m3]')
flow_out_m3_hr = pyunits.convert(self.flow_vol_out[self.t], to_units=pyunits.m ** 3 / pyunits.hr)
flow_waste_m3_hr = pyunits.convert(self.flow_vol_waste[self.t], to_units=pyunits.m ** 3 / pyunits.hr)
self.main_pump_ei_constr = Constraint(expr=self.main_pump_ei[self.t] == ((1000 * 9.81 * self.pressure_drop[self.t] * 0.703249) / (3.6E6 * 0.7)) / flow_out_m3_hr)
self.regen_pump_ei_constr = Constraint(expr=self.regen_pump_ei[self.t] == ((1000 * 9.81) / (3.6E6 * 0.7)) / flow_waste_m3_hr)
self.bw_pump_ei_constr = Constraint(expr=self.bw_pump_ei[self.t] == ((1000 * 9.81) / (3.6E6 * 0.7)) / flow_waste_m3_hr)
self.rinse_pump_ei_constr = Constraint(expr=self.rinse_pump_ei[self.t] == ((1000 * 9.81) / (3.6E6 * 0.7)) / flow_waste_m3_hr)
self.total_pump_ei_constr = Constraint(expr=self.total_pump_ei[self.t] == self.main_pump_ei[self.t] + self.regen_pump_ei[self.t] + self.bw_pump_ei[self.t] + self.rinse_pump_ei[self.t])
return self.total_pump_ei[self.t] * self.tpec_tic
def sba(self, unit_params):
'''
Function for Strong-Base Anion Exchange Model
:param unit_params:
:return:
'''
time = self.flowsheet().config.time
### REGEN VARIABLES
self.regen_dose = Var(time,
initialize=300,
domain=NonNegativeReals,
units=pyunits.kg / pyunits.m ** 3,
bounds=(80, 500),
doc='NaCl dose required for regeneration [kg/m3]')
self.regen_rate = Var(time,
initialize=4,
domain=NonNegativeReals,
bounds=(2, 5),
doc='Regeneration rate [BV/hr]')
self.regen_density = Var(time,
initialize=1000,
domain=NonNegativeReals,
units=pyunits.kg / pyunits.m ** 3,
bounds=(990, 1200),
doc='Density of NaCl regen solution [kg/m3]')
self.regen_ww = Var(time,
initialize=0.1,
domain=NonNegativeReals,
bounds=(0.015, 0.26),
doc='Strength of NaCl solution w/w [kg NaCl/kg soln]')
self.regen_conc = Var(time,
initialize=110,
domain=NonNegativeReals,
units=pyunits.kg / pyunits.m ** 3,
doc='Concentration of regen solution [kg/m3]')
self.regen_vol = Var(time,
initialize=2,
domain=NonNegativeReals,
doc='m3 of regen solution per m3 resin')
self.regen_soln_per_column = Var(time,
initialize=50,
domain=NonNegativeReals,
units=pyunits.m ** 3,
doc='Regen solution used per column [m3/column]')
self.regen_soln_per_column_annual = Var(time,
initialize=1E3,
domain=NonNegativeReals,
units=pyunits.m ** 3 / pyunits.year,
doc='Annual regen used per column [m3/year]')
self.regen_soln_annual = Var(time,
initialize=1E5,
domain=NonNegativeReals,
units=pyunits.m ** 3 / pyunits.year,
doc='Total volume regen solution used [m3/year]')
self.regen_time_per_column = Var(time,
initialize=5,
domain=NonNegativeReals,
units=pyunits.min,
doc='Regen time per column [min]')
self.regen_flow = Var(time,
initialize=10,
domain=NonNegativeReals,
units=pyunits.m ** 3 / pyunits.min,
doc='Regeneration flow rate [m3/min]')
self.num_regen_per_column_annual = Var(time,
initialize=200,
domain=NonNegativeReals,
doc='Number of regen cycles per year')
self.salt_per_regen_per_column = Var(time,
initialize=5E3,
domain=NonNegativeReals,
doc='Number of regen cycles per year')
self.salt_per_column_annual = Var(time,
initialize=1E5,
domain=NonNegativeReals,
units=pyunits.kg / pyunits.year,
doc='Mass of salt per column per year [kg/yr]')
self.salt_total_annual = Var(time,
initialize=1E6,
domain=NonNegativeReals,
units=pyunits.kg / pyunits.year,
doc='Mass of salt per year [kg/yr]')
self.salt_dose = Var(time,
initialize=0.1,
domain=NonNegativeReals,
units=pyunits.kg / pyunits.m ** 3,
doc='Salt dose for system [kg/m3]')
self.total_regen_time = Var(time,
initialize=30,
units=pyunits.min,
domain=NonNegativeReals,
doc='Total regeneration cycle time [min]')
self.regen_dose.fix(300)
try:
self.regen_ww.fix(unit_params['regen_ww'])
except KeyError:
self.regen_ww.fix(0.1)
### BACKWASH VARIABLES
self.bw_rate = Var(time,
initialize=6,
domain=NonNegativeReals,
units=pyunits.m / pyunits.hour,
bounds=(4.5, 8),
doc='Backwash rate [m/hr]')
self.bw_time = Var(time,
initialize=6,
domain=NonNegativeReals,
units=pyunits.minute,
bounds=(4, 20),
doc='Backwash time [min]')
self.bw_flow = Var(time,
initialize=5,
domain=NonNegativeReals,
units=pyunits.m ** 3 / pyunits.minute,
doc='Backwash flow rate [m3/min]')
self.bed_expansion = Var(time,
initialize=0.5,
domain=NonNegativeReals,
units=pyunits.dimensionless,
bounds=(0.4, 0.8),
doc='Resin bed expansion during backwash [%]')
self.bed_expansion_h = Var(time,
# initialize=0.5,
domain=NonNegativeReals,
units=pyunits.m,
bounds=(0.5, 3),
doc='Resin bed expansion during backwash [m]')
# self.bw_time.fix(6)
self.bw_time.fix(12)
### RINSE VARIABLES
self.rinse_bv = Var(time,
initialize=5,
domain=NonNegativeReals,
bounds=(2, 10),
doc='Number of bed volumes for rinse step [BV]')
self.rinse_vol_per_column = Var(time,
initialize=150,
domain=NonNegativeReals,
units=pyunits.m ** 3,
doc='Rinse volume per column [m3/col]')
self.rinse_vol_per_column_annual = Var(time,
initialize=5E3,
domain=NonNegativeReals,
units=pyunits.m ** 3 / pyunits.year,
doc='Rinse volume per column [m3/yr]')
self.rinse_time_per_column = Var(time,
initialize=4,
domain=NonNegativeReals,
units=pyunits.min,
doc='Rinse time per column [min]')
self.rinse_flow = Var(time,
initialize=2,
domain=NonNegativeReals,
units=pyunits.m ** 3 / pyunits.min,
doc='Rinse step flow rate [m3/min]')
self.rinse_bv.fix(5)
### RESIN AND FLOW VARIABLES
ix_df = self.ix_df = pd.read_csv('data/ix_sba.csv', index_col='constituent')
self.cons = [c for c in self.config.property_package.component_list if c in ix_df.index]
ix_df = self.ix_df = ix_df.loc[self.cons].copy()
self.sep_factor_dict = ix_df.to_dict()['sep_factor']
self.meq_conv_dict = ix_df.to_dict()['meq']
try:
self.target = unit_params['target']
except:
self.cons_df = self.source_df.loc[[c for c in self.cons if c != 'chloride']].copy()
self.cons_df['meq_L'] = [(self.cons_df.loc[c].value * 1E3) / self.meq_conv_dict[c] for c in self.cons if c != 'chloride']
self.target = self.cons_df.meq_L.idxmax()
for k, v in self.sep_factor_dict.items():
if v > self.sep_factor_dict[self.target]:
self.sep_factor_dict[k] = 0.99 * self.sep_factor_dict[self.target]
self.sep_factor = Param(self.cons,
initialize=self.sep_factor_dict)
self.meq_conv = Param(self.cons,
initialize=self.meq_conv_dict)
self.target_removal = Var(time,
initialize=1,
domain=NonNegativeReals,
bounds=(0.0001, 1),
doc='Removal fraction for target compound')
self.sfr = Var(time,
initialize=30,
domain=NonNegativeReals,
bounds=(6, 50),
doc='Service flow rate [BV/hr]')
self.loading_rate = Var(time,
initialize=20,
domain=NonNegativeReals,
bounds=(10, 40),
units=pyunits.m / pyunits.hr,
doc='Column loading rate (superficial velocity) [m/hr]')
self.cycle_time = Var(time,
initialize=100,
domain=NonNegativeReals,
units=pyunits.hr,
doc='Service cycle time [hr]')
self.ebct = Var(time,
initialize=1.1,
domain=NonNegativeReals,
units=pyunits.min,
doc='Empty Bed Contact Time [min]')
self.mg_L = Var(time,
self.cons,
initialize=1,
domain=NonNegativeReals,
doc='Influent concentration in mg/L')
self.meq_L = Var(time,
self.cons,
initialize=0.1,
domain=NonNegativeReals,
doc='Influent concentration in meq/L')
self.mass_in = Var(time,
self.cons,
initialize=200,
domain=NonNegativeReals,
doc='Influent mass [eq]')
self.mass_removed = Var(time,
self.cons,
initialize=10,
domain=NonNegativeReals,
doc='Mass removed [eq]')
self.frac_removed = Var(time,
self.cons,
initialize=0.8,
domain=NonNegativeReals,
doc='Fraction removed [%]')
self.denom_resin = Var(time,
initialize=1,
domain=NonNegativeReals)
self.denom_aq = Var(time,
initialize=1,
domain=NonNegativeReals)
self.resin_conc = Var(time,
self.cons,
initialize=0.1,
domain=NonNegativeReals,
doc='Resin phase concentration of each ion [eq/L resin]')
self.max_vol_treated = Var(time,
initialize=5E3,
domain=NonNegativeReals,
bounds=(100, 1E6),
units=pyunits.L / pyunits.L,
doc='Max volume of water treated before breakthrough [L water/L resin]')
self.resin_capacity = Var(time,
initialize=1.2,
domain=NonNegativeReals,
bounds=(0.9, 1.5),
doc='Resin capacity [eq/L]')
self.resin_vol = Var(time,
# initialize=100,
domain=NonNegativeReals,
units=pyunits.m ** 3,
doc='Resin volume needed [m3]')
self.resin_area = Var(time,
initialize=100,
domain=NonNegativeReals,
units=pyunits.m ** 2,
doc='Resin cross-sectional area needed [m2]')
self.resin_depth = Var(time,
initialize=1.5,
domain=NonNegativeReals,
bounds=(0.75, 3),
units=pyunits.m,
doc='Resin bed depth [m]')
self.resin_depth_to_column_diam_ratio = Var(time,
initialize=1,
domain=NonNegativeReals,
bounds=(0.6, 1.6),
units=pyunits.dimensionless,
doc='Ratio of resin depth to column height')
self.resin_per_column = Var(time,
initialize=15,
domain=NonNegativeReals,
units=pyunits.m ** 3,
doc='Resin per column [m3]')
self.resin_loss_frac_annual = Var(time,
initialize=0.045,
domain=NonNegativeReals,
bounds=(3.75, 5.25),
doc='Fraction of resin replaced per year [%]')
self.resin_loss_annual = Var(time,
initialize=20,
domain=NonNegativeReals,
units=pyunits.m ** 3,
doc='Resin replaced per year [m3]')
#### COLUMN VARIABLES
self.column_h = Var(time,
initialize=2,
domain=NonNegativeReals,
units=pyunits.m,
bounds=(1, 16),
doc='Column height [m]')
self.column_diam = Var(time,
initialize=2,
domain=NonNegativeReals,
units=pyunits.m,
bounds=(1, 4),
doc='Column diameter [m]')
self.column_area = Var(time,
initialize=15,
domain=NonNegativeReals,
units=pyunits.m ** 2,
doc='Column cross-sectional area [m2]')
if self.pv_material == 'fiberglass':
self.column_vol = Var(time,
initialize=2,
domain=NonNegativeReals,
bounds=(0.5, 4),
units=pyunits.m ** 3,
doc='Column volume [m3]')
else:
self.column_vol = Var(time,
initialize=35,
domain=NonNegativeReals,
bounds=(0.5, 25),
units=pyunits.m ** 3,
doc='Column volume [m3]')
self.num_columns = Var(time,
initialize=2,
domain=NonNegativeReals,
bounds=(1, 1E5),
units=pyunits.dimensionless,
doc='Number of columns in parallel')
self.underdrain_h = Var(time,
initialize=0.5,
domain=NonNegativeReals,
units=pyunits.m,
doc='Underdrain height [m]')
self.distributor_h = Var(time,
initialize=1,
domain=NonNegativeReals,
units=pyunits.m,
doc='Distributor height [m]')
self.flow_per_column = Var(time,
initialize=250,
domain=NonNegativeReals,
units=pyunits.m ** 3 / pyunits.hr,
doc='Flow per column [m3/hr]')
self.pressure_drop = Var(time,
initialize=14,
domain=NonNegativeReals,
units=pyunits.psi,
bounds=(0, 25),
doc='Pressure drop across column [psi]')
self.resin_capacity.fix(1.2)
# self.resin_capacity.fix(0.9435)
# self.sfr.fix(30)
self.loading_rate.fix(20)
self.underdrain_h.fix(0.5)
self.distributor_h.fix(1)
self.resin_loss_frac_annual.fix(0.045)
# self.column_diam.fix(3)
try:
self.target_removal = unit_params['target_removal']
except KeyError:
self.target_removal.fix(1)
flow_out_m3_hr = pyunits.convert(self.flow_vol_out[self.t], to_units=pyunits.m ** 3 / pyunits.hr)
flow_out_m3_yr = pyunits.convert(self.flow_vol_out[self.t], to_units=pyunits.m ** 3 / pyunits.year)
flow_out_L_hr = pyunits.convert(self.flow_vol_out[self.t], to_units=pyunits.L / pyunits.hr)
############################# CONSTRAINTS START
#### RESIN AND PERFORMANCE CONSTRAINTS
self.mg_L_constr = ConstraintList()
self.meq_L_constr = ConstraintList()
self.resin_conc_constr = ConstraintList()
self.mass_in_constr = ConstraintList()
self.mass_removed_constr = ConstraintList()
self.frac_removed_constr = ConstraintList()
for c in self.cons:
self.mg_L_constr.add(self.mg_L[self.t, c] == (self.conc_mass_in[self.t, c] * 1E3))
self.meq_L_constr.add(self.meq_L[self.t, c] == self.mg_L[self.t, c] / self.meq_conv[c])
self.resin_conc_constr.add(self.resin_conc[self.t, c] == (self.resin_capacity[self.t] * self.sep_factor[c] * self.meq_L[self.t, c]) /
self.denom_resin[self.t])
self.mass_in_constr.add(self.mass_in[self.t, c] == self.meq_L[self.t, c] * flow_out_m3_hr * self.cycle_time[self.t] * 1E-3)
self.mass_removed_constr.add(self.mass_removed[self.t, c] == (self.resin_conc[self.t, c] / self.max_vol_treated[self.t]) * flow_out_m3_hr * self.cycle_time[self.t])
self.frac_removed_constr.add(self.frac_removed[self.t, c] == 0.99 * (self.mass_removed[self.t, c] / self.mass_in[self.t, c]))
self.denom_resin_constr = Constraint(expr=self.denom_resin[self.t] == sum(self.meq_L[self.t, c] * self.sep_factor[c] for c in self.cons))
self.denom_aq_constr = Constraint(expr=self.denom_aq[self.t] == sum(self.resin_conc[self.t, c] / self.sep_factor[c] for c in self.cons))
self.max_vol_treated_constr = Constraint(expr=self.max_vol_treated[self.t] == (self.resin_conc[self.t, self.target] * 1E3) /
(self.meq_L[self.t, self.target] * self.target_removal[self.t]))
self.resin_vol_constr = Constraint(expr=self.resin_vol[self.t] == flow_out_m3_hr / self.sfr[self.t])
resin_vol_L = pyunits.convert(self.resin_vol[self.t], to_units=pyunits.L)
self.resin_depth_to_column_diam_ratio_constr = Constraint(expr=self.resin_depth_to_column_diam_ratio[self.t] == self.resin_depth[self.t] / self.column_diam[self.t])
self.resin_loss_annual_constr = Constraint(expr=self.resin_loss_annual[self.t] == self.resin_vol[self.t] * self.resin_loss_frac_annual[self.t])
self.cycle_time_constr = Constraint(expr=self.cycle_time[self.t] == (self.max_vol_treated[self.t] * resin_vol_L) / flow_out_L_hr)
self.resin_area_constr = Constraint(expr=self.resin_area[self.t] == self.resin_vol[self.t] / self.resin_depth[self.t])
self.column_area_constr = Constraint(expr=self.column_area[self.t] == 3.141592 * (self.column_diam[self.t] / 2) ** 2)
self.num_columns_constr = Constraint(expr=self.num_columns[self.t] == self.resin_area[self.t] / self.column_area[self.t])
self.flow_per_col_constr = Constraint(expr=self.flow_per_column[self.t] == flow_out_m3_hr / self.num_columns[self.t])
self.resin_per_col_constr = Constraint(expr=self.resin_per_column[self.t] == self.resin_vol[self.t] / self.num_columns[self.t])
self.loading_rate_constr1 = Constraint(expr=self.loading_rate[self.t] == self.flow_per_column[self.t] / self.column_area[self.t])
self.loading_rate_constr2 = Constraint(expr=self.loading_rate[self.t] == self.sfr[self.t] * self.resin_depth[self.t])
self.pressure_drop_constr = Constraint(expr=self.pressure_drop[self.t] == (8.28E-04 * self.loading_rate[self.t] ** 2 + 0.173 * self.loading_rate[self.t] + 0.609) * self.resin_depth[self.t]) # Curve for 20C temperatuer
self.column_h_constr = Constraint(expr=self.column_h[self.t] == self.resin_depth[self.t] + self.bed_expansion_h[self.t] + self.distributor_h[self.t] + self.underdrain_h[self.t])
self.column_vol_constr = Constraint(expr=self.column_vol[self.t] == 3.14159 * (self.column_diam[self.t] / 2) ** 2 * self.column_h[self.t])
self.ebct_constr = Constraint(expr=self.ebct[self.t] == (self.resin_depth[self.t] / self.loading_rate[self.t]) * 60)
#### REGEN CONSTRAINTS
self.regen_density_constr = Constraint(expr=self.regen_density[self.t] == 994.34 + 761.65 * self.regen_ww[self.t]) # kg Nacl / m3 resin
self.regen_conc_constr = Constraint(expr=self.regen_conc[self.t] == self.regen_ww[self.t] * self.regen_density[self.t])
self.regen_vol_constr = Constraint(expr=self.regen_vol[self.t] == self.regen_dose[self.t] / self.regen_conc[self.t]) # m3 regen soln / m3 resin
self.num_regen_per_column_annual_constr = Constraint(expr=self.num_regen_per_column_annual[self.t] == 8760 / self.cycle_time[self.t]) # numerator is hours per year
self.salt_per_regen_per_column_constr = Constraint(expr=self.salt_per_regen_per_column[self.t] == self.resin_per_column[self.t] * self.regen_dose[self.t])
self.salt_per_col_annual_constr = Constraint(expr=self.salt_per_column_annual[self.t] == self.num_regen_per_column_annual[self.t] * self.salt_per_regen_per_column[self.t]) # kg / year per column
self.salt_total_annual_constr = Constraint(expr=self.salt_total_annual[self.t] == self.salt_per_column_annual[self.t] * self.num_columns[self.t]) # kg / year
self.salt_dose_constr = Constraint(expr=self.salt_dose[self.t] == self.salt_total_annual[self.t] / flow_out_m3_yr)
self.regen_soln_per_col_constr = Constraint(expr=self.regen_soln_per_column[self.t] == self.resin_per_column[self.t] * self.regen_vol[self.t])
self.regen_soln_per_col_annual_constr = Constraint(expr=self.regen_soln_per_column_annual[self.t] == self.regen_soln_per_column[self.t] * self.num_regen_per_column_annual[self.t])
self.regen_soln_annual_constr = Constraint(expr=self.regen_soln_annual[self.t] == self.regen_soln_per_column_annual[self.t] * self.num_columns[self.t])
self.regen_time_per_col_constr = Constraint(expr=self.regen_time_per_column[self.t] == self.ebct[self.t] * self.regen_vol[self.t])
self.total_regen_time_constr = Constraint(expr=self.total_regen_time[self.t] == self.regen_time_per_column[self.t] + self.rinse_time_per_column[self.t] + self.bw_time[self.t])
self.regen_flow_constr = Constraint(expr=self.regen_flow[self.t] == self.column_vol[self.t] / self.regen_time_per_column[self.t])
##### BW CONSTRAINTS
self.bed_exp_constr = Constraint(expr=self.bed_expansion[self.t] == -1.35E-3 * self.bw_rate[self.t] ** 2 + 1.02E-1 * self.bw_rate[self.t] - 1.23E-2)
self.bed_exp_h_constr = Constraint(expr=self.bed_expansion_h[self.t] == self.resin_depth[self.t] * self.bed_expansion[self.t])
self.bw_flow_constr = Constraint(expr=self.bw_flow[self.t] == self.column_vol[self.t] / self.bw_time[self.t])
##### RINSE CONSTRAINTS
self.rinse_vol_per_column_constr = Constraint(expr=self.rinse_vol_per_column[self.t] == self.resin_per_column[self.t] * self.rinse_bv[self.t])
self.rinse_vol_per_col_annual_constr = Constraint(expr=self.rinse_vol_per_column_annual[self.t] == self.rinse_vol_per_column[self.t] * self.num_regen_per_column_annual[self.t])
self.rinse_time_per_col_constr = Constraint(expr=self.rinse_time_per_column[self.t] == self.ebct[self.t] * self.rinse_bv[self.t])
self.rinse_flow_constr = Constraint(expr=self.rinse_flow[self.t] == self.column_vol[self.t] / self.rinse_time_per_column[self.t])
##### WATER RECOVERY, CHEM DICT, AND CONSTITUENT REMOVAL
self.wr_constr = Constraint(expr=self.water_recovery[self.t] == 1 - (self.total_regen_time[self.t] / ((self.cycle_time[self.t] * 60) + self.total_regen_time[self.t])))
self.chem_dict = {
'Sodium_Chloride': self.salt_dose[self.t]
}
self.del_component(self.component_removal_equation)
self.ix_component_removal = ConstraintList()
for c in self.config.property_package.component_list:
if c in self.cons:
self.ix_component_removal.add(self.frac_removed[self.t, c] * self.flow_vol_in[self.t] * self.conc_mass_in[self.t, c] ==
self.flow_vol_waste[self.t] * self.conc_mass_waste[self.t, c])
else:
self.ix_component_removal.add(self.removal_fraction[self.t, c] * self.flow_vol_in[self.t] * self.conc_mass_in[self.t, c] ==
self.flow_vol_waste[self.t] * self.conc_mass_waste[self.t, c])
def sac(self, unit_params):
'''
Function for Strong-Acid Cation Exchange Model
:param unit_params:
:return:
'''
### REGEN VARIABLES
time = self.flowsheet().config.time
### REGEN VARIABLES
self.regen_dose = Var(time,
initialize=300,
domain=NonNegativeReals,
units=pyunits.kg / pyunits.m ** 3,
bounds=(80, 500),\
doc='NaCl dose required for regeneration [kg/m3]')
self.regen_rate = Var(time,
initialize=4,
domain=NonNegativeReals,
bounds=(2, 5),
doc='Regeneration rate [BV/hr]')
self.regen_density = Var(time,
initialize=1000,
domain=NonNegativeReals,
units=pyunits.kg / pyunits.m ** 3,
bounds=(990, 1200),
doc='Density of NaCl regen solution [kg/m3]')
self.regen_ww = Var(time,
initialize=0.1,
domain=NonNegativeReals,
bounds=(0.015, 0.26),
doc='Strength of NaCl solution w/w [kg NaCl/kg soln]')
self.regen_conc = Var(time,
initialize=110,
domain=NonNegativeReals,
units=pyunits.kg / pyunits.m ** 3,
doc='Concentration of regen solution [kg/m3]')
self.regen_vol = Var(time,
initialize=2,
domain=NonNegativeReals,
doc='m3 of regen solution per m3 resin')
self.regen_soln_per_column = Var(time,
initialize=50,
domain=NonNegativeReals,
units=pyunits.m ** 3,
doc='Regen solution used per column [m3/column]')
self.regen_soln_per_column_annual = Var(time,
initialize=1E3,
domain=NonNegativeReals,
units=pyunits.m ** 3 / pyunits.year,
doc='Annual regen used per column [m3/year]')
self.regen_soln_annual = Var(time,
initialize=1E5,
domain=NonNegativeReals,
units=pyunits.m ** 3 / pyunits.year,
doc='Total volume regen solution used [m3/year]')
self.regen_time_per_column = Var(time,
initialize=5,
domain=NonNegativeReals,
units=pyunits.min,
doc='Regen time per column [min]')
self.regen_flow = Var(time,
initialize=10,
domain=NonNegativeReals,
units=pyunits.m ** 3 / pyunits.min,
doc='Regeneration flow rate [m3/min]')
self.num_regen_per_column_annual = Var(time,
initialize=200,
domain=NonNegativeReals,
doc='Number of regen cycles per year')
self.salt_per_regen_per_column = Var(time,
initialize=5E3,
domain=NonNegativeReals,
doc='Number of regen cycles per year')
self.salt_per_column_annual = Var(time,
initialize=1E5,
domain=NonNegativeReals,
units=pyunits.kg / pyunits.year,
doc='Mass of salt per column per year [kg/yr]')
self.salt_total_annual = Var(time,
initialize=1E6,
domain=NonNegativeReals,
units=pyunits.kg / pyunits.year,
doc='Mass of salt per year [kg/yr]')
self.salt_dose = Var(time,
initialize=0.1,
domain=NonNegativeReals,
units=pyunits.kg / pyunits.m ** 3,
doc='Salt dose for system [kg/m3]')
self.total_regen_time = Var(time,
initialize=30,
units=pyunits.min,
domain=NonNegativeReals,
doc='Total regeneration cycle time [min]')
self.regen_dose.fix(300)
try:
self.regen_ww.fix(unit_params['regen_ww'])
except KeyError:
self.regen_ww.fix(0.1)
### BACKWASH VARIABLES
self.bw_rate = Var(time,
initialize=5,
domain=NonNegativeReals,
units=pyunits.m / pyunits.hour,
bounds=(4.5, 6.5),
doc='Backwash rate [m/hr]')
self.bw_time = Var(time,
initialize=6,
domain=NonNegativeReals,
units=pyunits.minute,
bounds=(4, 15),
doc='Backwash time [min]')
self.bw_flow = Var(time,
initialize=5,
domain=NonNegativeReals,
units=pyunits.m ** 3 / pyunits.minute,
doc='Backwash flow rate [m3/min]')
self.bed_expansion = Var(time,
initialize=0.5,
domain=NonNegativeReals,
units=pyunits.dimensionless,
bounds=(0.4, 0.6),
doc='Resin bed expansion during backwash [%]')
self.bed_expansion_h = Var(time,
# initialize=0.5,
domain=NonNegativeReals,
units=pyunits.m,
bounds=(0.1, 3),
doc='Resin bed expansion during backwash [m]')
self.bw_time.fix(6)
### RINSE VARIABLES
self.rinse_bv = Var(time,
initialize=5,
domain=NonNegativeReals,
bounds=(2, 5),
doc='Number of bed volumes for rinse step [BV]')
self.rinse_vol_per_column = Var(time,
initialize=150,
domain=NonNegativeReals,
units=pyunits.m ** 3,
doc='Rinse volume per column [m3/col]')
self.rinse_vol_per_column_annual = Var(time,
initialize=5E3,
domain=NonNegativeReals,
units=pyunits.m ** 3 / pyunits.year,
doc='Rinse volume per column [m3/yr]')
self.rinse_time_per_column = Var(time,
initialize=4,
domain=NonNegativeReals,
units=pyunits.min,
doc='Rinse time per column [min]')
self.rinse_flow = Var(time,
initialize=2,
domain=NonNegativeReals,
units=pyunits.m ** 3 / pyunits.min,
doc='Rinse step flow rate [m3/min]')
self.rinse_bv.fix(3)
### RESIN AND FLOW VARIABLES
ix_df = self.ix_df = pd.read_csv('data/ix_sac.csv', index_col='constituent')
self.cons = [c for c in self.config.property_package.component_list if c in ix_df.index]
ix_df = self.ix_df = ix_df.loc[self.cons].copy()
self.sep_factor_dict = ix_df.to_dict()['sep_factor']
self.meq_conv_dict = ix_df.to_dict()['meq']
try:
self.target = unit_params['target']
except KeyError:
self.cons_df = self.source_df.loc[[c for c in self.cons if c != 'sodium']].copy()
self.cons_df['meq_L'] = [(self.cons_df.loc[c].value * 1E3) / self.meq_conv_dict[c] for c in self.cons if c != 'sodium']
self.target = self.cons_df.meq_L.idxmax()
for k, v in self.sep_factor_dict.items():
if v > self.sep_factor_dict[self.target]:
self.sep_factor_dict[k] = 0.99 * self.sep_factor_dict[self.target]
self.sep_factor = Param(self.cons,
initialize=self.sep_factor_dict)
self.meq_conv = Param(self.cons,
initialize=self.meq_conv_dict)
self.target_removal = Var(time,
initialize=1,
domain=NonNegativeReals,
bounds=(0.0001, 1),
doc='Removal fraction for target compound')
self.sfr = Var(time,
initialize=30,
domain=NonNegativeReals,
bounds=(6, 50),
doc='Service flow rate [BV/hr]')
self.loading_rate = Var(time,
initialize=20,
domain=NonNegativeReals,
bounds=(10, 40),
units=pyunits.m / pyunits.hr,
doc='Column loading rate (superficial velocity) [m/hr]')
self.cycle_time = Var(time,
initialize=100,
domain=NonNegativeReals,
units=pyunits.hr,
doc='Service cycle time [hr]')
self.ebct = Var(time,
initialize=1.1,
domain=NonNegativeReals,
units=pyunits.min,
doc='Empty Bed Contact Time [min]')
self.mg_L = Var(time,
self.cons,
initialize=1,
domain=NonNegativeReals,
doc='Influent concentration in mg/L')
self.meq_L = Var(time,
self.cons,
initialize=0.1,
domain=NonNegativeReals,
doc='Influent concentration in meq/L')
self.mass_in = Var(time,
self.cons,
initialize=200,
domain=NonNegativeReals,
doc='Influent mass [eq]')
self.mass_removed = Var(time,
self.cons,
initialize=10,
domain=NonNegativeReals,
doc='Mass removed [eq]')
self.frac_removed = Var(time,
self.cons,
initialize=0.8,
domain=NonNegativeReals,
doc='Fraction removed [%]')
self.denom_resin = Var(time,
initialize=1,
domain=NonNegativeReals)
self.denom_aq = Var(time,
initialize=1,
domain=NonNegativeReals)
self.resin_conc = Var(time,
self.cons,
initialize=0.1,
domain=NonNegativeReals,
doc='Resin phase concentration of each ion [eq/L resin]')
self.max_vol_treated = Var(time,
initialize=5E3,
domain=NonNegativeReals,
bounds=(100, 1E6),
units=pyunits.L / pyunits.L,
doc='Max volume of water treated before breakthrough [L water/L resin]')
self.resin_capacity = Var(time,
initialize=1.7,
domain=NonNegativeReals,
bounds=(1.6, 2.2),
doc='Resin capacity [eq/L]')
self.resin_vol = Var(time,
# initialize=100,
domain=NonNegativeReals,
units=pyunits.m ** 3,
doc='Resin volume needed [m3]')
self.resin_area = Var(time,
initialize=100,
domain=NonNegativeReals,
units=pyunits.m ** 2,
doc='Resin cross-sectional area needed [m2]')
self.resin_depth = Var(time,
initialize=1.5,
domain=NonNegativeReals,
bounds=(0.75, 3),
units=pyunits.m,
doc='Resin bed depth [m]')
self.resin_depth_to_column_diam_ratio = Var(time,
initialize=1,
domain=NonNegativeReals,
bounds=(0.6, 1.6),
units=pyunits.dimensionless,
doc='Ratio of resin depth to column height')
self.resin_per_column = Var(time,
initialize=15,
domain=NonNegativeReals,
units=pyunits.m ** 3,
doc='Resin per column [m3]')
self.resin_loss_frac_annual = Var(time,
initialize=0.045,
domain=NonNegativeReals,
bounds=(3.75, 5.25),
doc='Fraction of resin replaced per year [%]')
self.resin_loss_annual = Var(time,
initialize=20,
domain=NonNegativeReals,
units=pyunits.m ** 3,
doc='Resin replaced per year [m3]')
#### COLUMN VARIABLES
self.column_h = Var(time,
initialize=2,
domain=NonNegativeReals,
units=pyunits.m,
bounds=(1, 16),
doc='Column height [m]')
self.column_diam = Var(time,
initialize=2,
domain=NonNegativeReals,
units=pyunits.m,
bounds=(1, 4),
doc='Column diameter [m]')
self.column_area = Var(time,
initialize=15,
domain=NonNegativeReals,
units=pyunits.m ** 2,
doc='Column cross-sectional area [m2]')
if self.pv_material == 'fiberglass':
self.column_vol = Var(time,
initialize=2,
domain=NonNegativeReals,
bounds=(0.5, 4),
units=pyunits.m ** 3,
doc='Column volume [m3]')
else:
self.column_vol = Var(time,
initialize=35,
domain=NonNegativeReals,
bounds=(0.5, 25),
units=pyunits.m ** 3,
doc='Column volume [m3]')
self.num_columns = Var(time,
initialize=2,
domain=NonNegativeReals,
bounds=(1, 1E5),
units=pyunits.dimensionless,
doc='Number of columns in parallel')
self.underdrain_h = Var(time,
initialize=0.5,
domain=NonNegativeReals,
units=pyunits.m,
doc='Underdrain height [m]')
self.distributor_h = Var(time,
initialize=1,
domain=NonNegativeReals,
units=pyunits.m,
doc='Distributor height [m]')
self.flow_per_column = Var(time,
initialize=250,
domain=NonNegativeReals,
units=pyunits.m ** 3 / pyunits.hr,
doc='Flow per column [m3/hr]')
self.pressure_drop = Var(time,
initialize=14,
domain=NonNegativeReals,
units=pyunits.psi,
bounds=(0, 25),
doc='Pressure drop across column [psi]')
self.resin_capacity.fix(1.7)
# self.sfr.fix(30)
self.loading_rate.fix(20)
self.underdrain_h.fix(0.5)
self.distributor_h.fix(1)
self.resin_loss_frac_annual.fix(0.045)
# self.column_diam.fix(2.5)
try:
self.target_removal = unit_params['target_removal']
except KeyError:
self.target_removal.fix(1)
flow_out_m3_hr = pyunits.convert(self.flow_vol_out[self.t], to_units=pyunits.m ** 3 / pyunits.hr)
flow_out_m3_yr = pyunits.convert(self.flow_vol_out[self.t], to_units=pyunits.m ** 3 / pyunits.year)
flow_out_L_hr = pyunits.convert(self.flow_vol_out[self.t], to_units=pyunits.L / pyunits.hr)
############################# CONSTRAINTS START
#### RESIN AND PERFORMANCE CONSTRAINTS
self.mg_L_constr = ConstraintList()
self.meq_L_constr = ConstraintList()
self.resin_conc_constr = ConstraintList()
self.mass_in_constr = ConstraintList()
self.mass_removed_constr = ConstraintList()
self.frac_removed_constr = ConstraintList()
for c in self.cons:
self.mg_L_constr.add(self.mg_L[self.t, c] == (self.conc_mass_in[self.t, c] * 1E3))
self.meq_L_constr.add(self.meq_L[self.t, c] == self.mg_L[self.t, c] / self.meq_conv[c])
self.resin_conc_constr.add(self.resin_conc[self.t, c] == (self.resin_capacity[self.t] * self.sep_factor[c] * self.meq_L[self.t, c]) /
self.denom_resin[self.t])
self.mass_in_constr.add(self.mass_in[self.t, c] == self.meq_L[self.t, c] * flow_out_m3_hr * self.cycle_time[self.t] * 1E-3)
self.mass_removed_constr.add(self.mass_removed[self.t, c] == (self.resin_conc[self.t, c] / self.max_vol_treated[self.t]) * flow_out_m3_hr * self.cycle_time[self.t])
self.frac_removed_constr.add(self.frac_removed[self.t, c] == 0.99 * (self.mass_removed[self.t, c] / self.mass_in[self.t, c]))
self.denom_resin_constr = Constraint(expr=self.denom_resin[self.t] == sum(self.meq_L[self.t, c] * self.sep_factor[c] for c in self.cons))
self.denom_aq_constr = Constraint(expr=self.denom_aq[self.t] == sum(self.resin_conc[self.t, c] / self.sep_factor[c] for c in self.cons))
self.max_vol_treated_constr = Constraint(expr=self.max_vol_treated[self.t] == (self.resin_conc[self.t, self.target] * 1E3) /
(self.meq_L[self.t, self.target] * self.target_removal[self.t]))
self.resin_vol_constr = Constraint(expr=self.resin_vol[self.t] == flow_out_m3_hr / self.sfr[self.t])
resin_vol_L = pyunits.convert(self.resin_vol[self.t], to_units=pyunits.L)
self.resin_depth_to_column_diam_ratio_constr = Constraint(expr=self.resin_depth_to_column_diam_ratio[self.t] == self.resin_depth[self.t] / self.column_diam[self.t])
self.resin_loss_annual_constr = Constraint(expr=self.resin_loss_annual[self.t] == self.resin_vol[self.t] * self.resin_loss_frac_annual[self.t])
self.cycle_time_constr = Constraint(expr=self.cycle_time[self.t] == (self.max_vol_treated[self.t] * resin_vol_L) / flow_out_L_hr)
self.resin_area_constr = Constraint(expr=self.resin_area[self.t] == self.resin_vol[self.t] / self.resin_depth[self.t])
self.column_area_constr = Constraint(expr=self.column_area[self.t] == 3.141592 * (self.column_diam[self.t] / 2) ** 2)
self.num_columns_constr = Constraint(expr=self.num_columns[self.t] == self.resin_area[self.t] / self.column_area[self.t])
self.flow_per_col_constr = Constraint(expr=self.flow_per_column[self.t] == flow_out_m3_hr / self.num_columns[self.t])
self.resin_per_col_constr = Constraint(expr=self.resin_per_column[self.t] == self.resin_vol[self.t] / self.num_columns[self.t])
self.loading_rate_constr1 = Constraint(expr=self.loading_rate[self.t] == self.flow_per_column[self.t] / self.column_area[self.t])
self.loading_rate_constr2 = Constraint(expr=self.loading_rate[self.t] == self.sfr[self.t] * self.resin_depth[self.t])
self.pressure_drop_constr = Constraint(expr=self.pressure_drop[self.t] == (8.28E-04 * self.loading_rate[self.t] ** 2 + 0.173 * self.loading_rate[self.t] + 0.609) * self.resin_depth[self.t]) # Curve for 20C temperatuer
self.column_h_constr = Constraint(expr=self.column_h[self.t] == self.resin_depth[self.t] + self.bed_expansion_h[self.t] + self.distributor_h[self.t] + self.underdrain_h[self.t])
self.column_vol_constr = Constraint(expr=self.column_vol[self.t] == 3.14159 * (self.column_diam[self.t] / 2) ** 2 * self.column_h[self.t])
self.ebct_constr = Constraint(expr=self.ebct[self.t] == (self.resin_depth[self.t] / self.loading_rate[self.t]) * 60)
#### REGEN CONSTRAINTS
self.regen_density_constr = Constraint(expr=self.regen_density[self.t] == 994.34 + 761.65 * self.regen_ww[self.t]) # kg Nacl / m3 resin
self.regen_conc_constr = Constraint(expr=self.regen_conc[self.t] == self.regen_ww[self.t] * self.regen_density[self.t])
self.regen_vol_constr = Constraint(expr=self.regen_vol[self.t] == self.regen_dose[self.t] / self.regen_conc[self.t]) # m3 regen soln / m3 resin
self.num_regen_per_column_annual_constr = Constraint(expr=self.num_regen_per_column_annual[self.t] == 8760 / self.cycle_time[self.t]) # numerator is hours per year
self.salt_per_regen_per_column_constr = Constraint(expr=self.salt_per_regen_per_column[self.t] == self.resin_per_column[self.t] * self.regen_dose[self.t])
self.salt_per_col_annual_constr = Constraint(expr=self.salt_per_column_annual[self.t] == self.num_regen_per_column_annual[self.t] * self.salt_per_regen_per_column[self.t]) # kg / year per column
self.salt_total_annual_constr = Constraint(expr=self.salt_total_annual[self.t] == self.salt_per_column_annual[self.t] * self.num_columns[self.t]) # kg / year
self.salt_dose_constr = Constraint(expr=self.salt_dose[self.t] == self.salt_total_annual[self.t] / flow_out_m3_yr)
self.regen_soln_per_col_constr = Constraint(expr=self.regen_soln_per_column[self.t] == self.resin_per_column[self.t] * self.regen_vol[self.t])
self.regen_soln_per_col_annual_constr = Constraint(expr=self.regen_soln_per_column_annual[self.t] == self.regen_soln_per_column[self.t] * self.num_regen_per_column_annual[self.t])
self.regen_soln_annual_constr = Constraint(expr=self.regen_soln_annual[self.t] == self.regen_soln_per_column_annual[self.t] * self.num_columns[self.t])
self.regen_time_per_col_constr = Constraint(expr=self.regen_time_per_column[self.t] == self.ebct[self.t] * self.regen_vol[self.t])
self.total_regen_time_constr = Constraint(expr=self.total_regen_time[self.t] == self.regen_time_per_column[self.t] + self.rinse_time_per_column[self.t] + self.bw_time[self.t])
self.regen_flow_constr = Constraint(expr=self.regen_flow[self.t] == self.column_vol[self.t] / self.regen_time_per_column[self.t])
##### BW CONSTRAINTS
self.bed_exp_constr = Constraint(expr=self.bed_expansion[self.t] == -1.35E-3 * self.bw_rate[self.t] ** 2 + 1.02E-1 * self.bw_rate[self.t] - 1.23E-2)
self.bed_exp_h_constr = Constraint(expr=self.bed_expansion_h[self.t] == self.resin_depth[self.t] * self.bed_expansion[self.t])
self.bw_flow_constr = Constraint(expr=self.bw_flow[self.t] == self.column_vol[self.t] / self.bw_time[self.t])
##### RINSE CONSTRAINTS
self.rinse_vol_per_column_constr = Constraint(expr=self.rinse_vol_per_column[self.t] == self.resin_per_column[self.t] * self.rinse_bv[self.t])
self.rinse_vol_per_col_annual_constr = Constraint(expr=self.rinse_vol_per_column_annual[self.t] == self.rinse_vol_per_column[self.t] * self.num_regen_per_column_annual[self.t])
self.rinse_time_per_col_constr = Constraint(expr=self.rinse_time_per_column[self.t] == self.ebct[self.t] * self.rinse_bv[self.t])
self.rinse_flow_constr = Constraint(expr=self.rinse_flow[self.t] == self.column_vol[self.t] / self.rinse_time_per_column[self.t])
##### WATER RECOVERY, CHEM DICT, AND CONSTITUENT REMOVAL
self.wr_constr = Constraint(expr=self.water_recovery[self.t] == 1 - (self.total_regen_time[self.t] / ((self.cycle_time[self.t] * 60) + self.total_regen_time[self.t])))
self.chem_dict = {
'Sodium_Chloride': self.salt_dose[self.t]
}
self.del_component(self.component_removal_equation)
self.ix_component_removal = ConstraintList()
for c in self.config.property_package.component_list:
if c in self.cons:
self.ix_component_removal.add(self.frac_removed[self.t, c] * self.flow_vol_in[self.t] * self.conc_mass_in[self.t, c] ==
self.flow_vol_waste[self.t] * self.conc_mass_waste[self.t, c])
else:
self.ix_component_removal.add(self.removal_fraction[self.t, c] * self.flow_vol_in[self.t] * self.conc_mass_in[self.t, c] ==
self.flow_vol_waste[self.t] * self.conc_mass_waste[self.t, c])
def get_costing(self, unit_params=None, year=None):
'''
Initialize the unit in WaterTAP3.
'''
financials.create_costing_block(self, basis_year, tpec_or_tic)
time = self.flowsheet().config.time
self.t = time.first()
self.units_meta = self.config.property_package.get_metadata().get_derived_units
self.mode = unit_params['mode']
self.source_df = self.parent_block().source_df
self.parent_block().has_ix = True
try:
self.pv_material = unit_params['pv_material']
except KeyError:
self.pv_material = 'carbon_w_plastic_internals'
if self.mode == 'sac':
self.resin_dict = {
'polystyrenic_macro': 3680,
'polystyrenic_gel': 6240,
} # cost of resin per m3, adapted to $/m3 from EPA models
try:
self.resin_type = unit_params['resin_type']
except KeyError:
self.resin_type = 'polystyrenic_macro'
self.sac(unit_params)
if self.mode == 'sba':
self.resin_dict = {
'styrenic_gel_1': 5214,
'styrenic_gel_2': 6116,
'styrenic_macro_1': 7298,
'styrenic_macro_2': 7810,
'polyacrylic': 8658,
'nitrate': 6116
} # cost of resin per m3, adapted to $/m3 from EPA models
try:
self.resin_type = unit_params['resin_type']
except KeyError:
self.resin_type = 'styrenic_gel_1'
self.sba(unit_params)
self.costing.fixed_cap_inv_unadjusted = Expression(expr=self.fixed_cap(unit_params),
doc='Unadjusted fixed capital investment')
self.electricity = Expression(expr=self.elect(),
doc='Electricity intensity [kwh/m3]')
self.costing.other_var_cost = (self.resin_unit_cap[self.t] * self.resin_loss_annual[self.t]) * 1E-6
financials.get_complete_costing(self.costing) | 49.300678 | 248 | 0.493978 | import pandas as pd
from pyomo.environ import *
from pyomo.environ import units as pyunits
from pyomo.repn.plugins.baron_writer import NonNegativeReals
from watertap3.utils import financials
from watertap3.wt_units.wt_unit import WT3UnitProcess
basis_year = 2016
tpec_or_tic = 'TIC'
class UnitProcess(WT3UnitProcess):
def fixed_cap(self, unit_params):
time = self.flowsheet().config.time
self.total_ix_cap = Var(time,
initialize=25,
domain=NonNegativeReals,
doc='Total ion exchange FCI [$MM]')
self.cap_per_column = Var(time,
initialize=1,
domain=NonNegativeReals,
doc='Capital per column [$MM]')
self.column_total_cap = Var(time,
initialize=1,
domain=NonNegativeReals,
doc='Total column capital [$MM]')
self.resin_unit_cap = Var(time,
initialize=4000,
domain=NonNegativeReals,
doc='Resin cap per m3 [$/m3]')
self.resin_cap = Var(time,
initialize=1E4,
domain=NonNegativeReals,
doc='Resin capital [$MM]')
self.regen_pump_cap = Var(time,
initialize=100,
domain=NonNegativeReals,
doc='Pump capital for regen cycle [$MM]')
self.bw_pump_cap = Var(time,
initialize=100,
domain=NonNegativeReals,
doc='Pump capital for backwash cycle [$MM]')
self.rinse_pump_cap = Var(time,
initialize=100,
domain=NonNegativeReals,
doc='Pump capital for rinse cycle [$MM]')
self.boost_pump_cap = Var(time,
initialize=100,
domain=NonNegativeReals,
doc='Pump capital for booster pump [#MM]')
if self.pv_material == 'carbon_w_stainless_internals':
self.cap_per_column_constr = Constraint(expr=self.cap_per_column[self.t] ==
(16504 * self.column_vol[self.t] ** 0.43) * 1E-6)
if self.pv_material == 'carbon_w_plastic_internals':
self.cap_per_column_constr = Constraint(expr=self.cap_per_column[self.t] ==
(9120 * self.column_vol[self.t] ** 0.49) * 1E-6)
if self.pv_material == 'fiberglass':
self.cap_per_column_constr = Constraint(expr=self.cap_per_column[self.t] ==
(5637 * self.column_vol[self.t] ** 0.9) * 1E-6)
self.col_total_cap_constr = Constraint(expr=self.column_total_cap[self.t] == self.cap_per_column[self.t] * (self.num_columns[self.t] + 1))
self.resin_unit_cap.fix(self.resin_dict[self.resin_type])
self.resin_cap_constr = Constraint(expr=self.resin_cap[self.t] == ((self.resin_vol[self.t] + self.resin_per_column[self.t]) * self.resin_unit_cap[self.t]) * 1E-6)
self.regen_pump_cap_constr = Constraint(expr=self.regen_pump_cap[self.t] == (-24.257 * self.regen_flow[self.t] ** 2 + 2803.7 * self.regen_flow[self.t] + 7495.7) *
(self.num_columns[self.t] + 1) * 1E-6)
self.bw_pump_cap_constr = Constraint(expr=self.bw_pump_cap[self.t] == (-24.257 * self.bw_flow[self.t] ** 2 + 2803.7 * self.bw_flow[self.t] + 7495.7) *
(self.num_columns[self.t] + 1) * 1E-6)
self.rinse_pump_cap_constr = Constraint(expr=self.rinse_pump_cap[self.t] == (-24.257 * self.rinse_flow[self.t] ** 2 + 2803.7 * self.rinse_flow[self.t] + 7495.7) *
(self.num_columns[self.t] + 1) * 1E-6)
self.flow_per_col_m3_min = pyunits.convert(self.flow_per_column[self.t], to_units=pyunits.m ** 3 / pyunits.min)
self.boost_pump_cap_constr = Constraint(expr=self.boost_pump_cap[self.t] == (-24.257 * self.flow_per_col_m3_min ** 2 + 2803.7 * self.flow_per_col_m3_min + 7495.7) *
(self.num_columns[self.t] + 1) * 1E-6)
self.total_ix_cap_constr = Constraint(expr=self.total_ix_cap[self.t] ==
self.column_total_cap[self.t] + self.resin_cap[self.t] + self.regen_pump_cap[self.t] + self.bw_pump_cap[self.t] + self.rinse_pump_cap[self.t] + self.boost_pump_cap[self.t])
return self.total_ix_cap[self.t] * self.tpec_tic
def elect(self):
time = self.flowsheet().config.time
self.main_pump_ei = Var(time,
initialize=4E-6,
domain=NonNegativeReals,
doc='Electricity intensity for main pump [kWh/m3]')
self.regen_pump_ei = Var(time,
initialize=4E-6,
domain=NonNegativeReals,
doc='Electricity intensity for regen pump [kWh/m3]')
self.bw_pump_ei = Var(time,
initialize=4E-6,
domain=NonNegativeReals,
doc='Electricity intensity for backwash pump [kWh/m3]')
self.rinse_pump_ei = Var(time,
initialize=4E-6,
domain=NonNegativeReals,
doc='Electricity intensity for rinse pump [kWh/m3]')
self.total_pump_ei = Var(time,
initialize=4E-5,
domain=NonNegativeReals,
doc='Total pumping electricity intensity [kWh/m3]')
flow_out_m3_hr = pyunits.convert(self.flow_vol_out[self.t], to_units=pyunits.m ** 3 / pyunits.hr)
flow_waste_m3_hr = pyunits.convert(self.flow_vol_waste[self.t], to_units=pyunits.m ** 3 / pyunits.hr)
self.main_pump_ei_constr = Constraint(expr=self.main_pump_ei[self.t] == ((1000 * 9.81 * self.pressure_drop[self.t] * 0.703249) / (3.6E6 * 0.7)) / flow_out_m3_hr)
self.regen_pump_ei_constr = Constraint(expr=self.regen_pump_ei[self.t] == ((1000 * 9.81) / (3.6E6 * 0.7)) / flow_waste_m3_hr)
self.bw_pump_ei_constr = Constraint(expr=self.bw_pump_ei[self.t] == ((1000 * 9.81) / (3.6E6 * 0.7)) / flow_waste_m3_hr)
self.rinse_pump_ei_constr = Constraint(expr=self.rinse_pump_ei[self.t] == ((1000 * 9.81) / (3.6E6 * 0.7)) / flow_waste_m3_hr)
self.total_pump_ei_constr = Constraint(expr=self.total_pump_ei[self.t] == self.main_pump_ei[self.t] + self.regen_pump_ei[self.t] + self.bw_pump_ei[self.t] + self.rinse_pump_ei[self.t])
return self.total_pump_ei[self.t] * self.tpec_tic
def sba(self, unit_params):
time = self.flowsheet().config.time
e,
initialize=300,
domain=NonNegativeReals,
units=pyunits.kg / pyunits.m ** 3,
bounds=(80, 500),
doc='NaCl dose required for regeneration [kg/m3]')
self.regen_rate = Var(time,
initialize=4,
domain=NonNegativeReals,
bounds=(2, 5),
doc='Regeneration rate [BV/hr]')
self.regen_density = Var(time,
initialize=1000,
domain=NonNegativeReals,
units=pyunits.kg / pyunits.m ** 3,
bounds=(990, 1200),
doc='Density of NaCl regen solution [kg/m3]')
self.regen_ww = Var(time,
initialize=0.1,
domain=NonNegativeReals,
bounds=(0.015, 0.26),
doc='Strength of NaCl solution w/w [kg NaCl/kg soln]')
self.regen_conc = Var(time,
initialize=110,
domain=NonNegativeReals,
units=pyunits.kg / pyunits.m ** 3,
doc='Concentration of regen solution [kg/m3]')
self.regen_vol = Var(time,
initialize=2,
domain=NonNegativeReals,
doc='m3 of regen solution per m3 resin')
self.regen_soln_per_column = Var(time,
initialize=50,
domain=NonNegativeReals,
units=pyunits.m ** 3,
doc='Regen solution used per column [m3/column]')
self.regen_soln_per_column_annual = Var(time,
initialize=1E3,
domain=NonNegativeReals,
units=pyunits.m ** 3 / pyunits.year,
doc='Annual regen used per column [m3/year]')
self.regen_soln_annual = Var(time,
initialize=1E5,
domain=NonNegativeReals,
units=pyunits.m ** 3 / pyunits.year,
doc='Total volume regen solution used [m3/year]')
self.regen_time_per_column = Var(time,
initialize=5,
domain=NonNegativeReals,
units=pyunits.min,
doc='Regen time per column [min]')
self.regen_flow = Var(time,
initialize=10,
domain=NonNegativeReals,
units=pyunits.m ** 3 / pyunits.min,
doc='Regeneration flow rate [m3/min]')
self.num_regen_per_column_annual = Var(time,
initialize=200,
domain=NonNegativeReals,
doc='Number of regen cycles per year')
self.salt_per_regen_per_column = Var(time,
initialize=5E3,
domain=NonNegativeReals,
doc='Number of regen cycles per year')
self.salt_per_column_annual = Var(time,
initialize=1E5,
domain=NonNegativeReals,
units=pyunits.kg / pyunits.year,
doc='Mass of salt per column per year [kg/yr]')
self.salt_total_annual = Var(time,
initialize=1E6,
domain=NonNegativeReals,
units=pyunits.kg / pyunits.year,
doc='Mass of salt per year [kg/yr]')
self.salt_dose = Var(time,
initialize=0.1,
domain=NonNegativeReals,
units=pyunits.kg / pyunits.m ** 3,
doc='Salt dose for system [kg/m3]')
self.total_regen_time = Var(time,
initialize=30,
units=pyunits.min,
domain=NonNegativeReals,
doc='Total regeneration cycle time [min]')
self.regen_dose.fix(300)
try:
self.regen_ww.fix(unit_params['regen_ww'])
except KeyError:
self.regen_ww.fix(0.1)
initialize=6,
domain=NonNegativeReals,
units=pyunits.m / pyunits.hour,
bounds=(4.5, 8),
doc='Backwash rate [m/hr]')
self.bw_time = Var(time,
initialize=6,
domain=NonNegativeReals,
units=pyunits.minute,
bounds=(4, 20),
doc='Backwash time [min]')
self.bw_flow = Var(time,
initialize=5,
domain=NonNegativeReals,
units=pyunits.m ** 3 / pyunits.minute,
doc='Backwash flow rate [m3/min]')
self.bed_expansion = Var(time,
initialize=0.5,
domain=NonNegativeReals,
units=pyunits.dimensionless,
bounds=(0.4, 0.8),
doc='Resin bed expansion during backwash [%]')
self.bed_expansion_h = Var(time,
domain=NonNegativeReals,
units=pyunits.m,
bounds=(0.5, 3),
doc='Resin bed expansion during backwash [m]')
self.bw_time.fix(12)
initialize=5,
domain=NonNegativeReals,
bounds=(2, 10),
doc='Number of bed volumes for rinse step [BV]')
self.rinse_vol_per_column = Var(time,
initialize=150,
domain=NonNegativeReals,
units=pyunits.m ** 3,
doc='Rinse volume per column [m3/col]')
self.rinse_vol_per_column_annual = Var(time,
initialize=5E3,
domain=NonNegativeReals,
units=pyunits.m ** 3 / pyunits.year,
doc='Rinse volume per column [m3/yr]')
self.rinse_time_per_column = Var(time,
initialize=4,
domain=NonNegativeReals,
units=pyunits.min,
doc='Rinse time per column [min]')
self.rinse_flow = Var(time,
initialize=2,
domain=NonNegativeReals,
units=pyunits.m ** 3 / pyunits.min,
doc='Rinse step flow rate [m3/min]')
self.rinse_bv.fix(5)
ba.csv', index_col='constituent')
self.cons = [c for c in self.config.property_package.component_list if c in ix_df.index]
ix_df = self.ix_df = ix_df.loc[self.cons].copy()
self.sep_factor_dict = ix_df.to_dict()['sep_factor']
self.meq_conv_dict = ix_df.to_dict()['meq']
try:
self.target = unit_params['target']
except:
self.cons_df = self.source_df.loc[[c for c in self.cons if c != 'chloride']].copy()
self.cons_df['meq_L'] = [(self.cons_df.loc[c].value * 1E3) / self.meq_conv_dict[c] for c in self.cons if c != 'chloride']
self.target = self.cons_df.meq_L.idxmax()
for k, v in self.sep_factor_dict.items():
if v > self.sep_factor_dict[self.target]:
self.sep_factor_dict[k] = 0.99 * self.sep_factor_dict[self.target]
self.sep_factor = Param(self.cons,
initialize=self.sep_factor_dict)
self.meq_conv = Param(self.cons,
initialize=self.meq_conv_dict)
self.target_removal = Var(time,
initialize=1,
domain=NonNegativeReals,
bounds=(0.0001, 1),
doc='Removal fraction for target compound')
self.sfr = Var(time,
initialize=30,
domain=NonNegativeReals,
bounds=(6, 50),
doc='Service flow rate [BV/hr]')
self.loading_rate = Var(time,
initialize=20,
domain=NonNegativeReals,
bounds=(10, 40),
units=pyunits.m / pyunits.hr,
doc='Column loading rate (superficial velocity) [m/hr]')
self.cycle_time = Var(time,
initialize=100,
domain=NonNegativeReals,
units=pyunits.hr,
doc='Service cycle time [hr]')
self.ebct = Var(time,
initialize=1.1,
domain=NonNegativeReals,
units=pyunits.min,
doc='Empty Bed Contact Time [min]')
self.mg_L = Var(time,
self.cons,
initialize=1,
domain=NonNegativeReals,
doc='Influent concentration in mg/L')
self.meq_L = Var(time,
self.cons,
initialize=0.1,
domain=NonNegativeReals,
doc='Influent concentration in meq/L')
self.mass_in = Var(time,
self.cons,
initialize=200,
domain=NonNegativeReals,
doc='Influent mass [eq]')
self.mass_removed = Var(time,
self.cons,
initialize=10,
domain=NonNegativeReals,
doc='Mass removed [eq]')
self.frac_removed = Var(time,
self.cons,
initialize=0.8,
domain=NonNegativeReals,
doc='Fraction removed [%]')
self.denom_resin = Var(time,
initialize=1,
domain=NonNegativeReals)
self.denom_aq = Var(time,
initialize=1,
domain=NonNegativeReals)
self.resin_conc = Var(time,
self.cons,
initialize=0.1,
domain=NonNegativeReals,
doc='Resin phase concentration of each ion [eq/L resin]')
self.max_vol_treated = Var(time,
initialize=5E3,
domain=NonNegativeReals,
bounds=(100, 1E6),
units=pyunits.L / pyunits.L,
doc='Max volume of water treated before breakthrough [L water/L resin]')
self.resin_capacity = Var(time,
initialize=1.2,
domain=NonNegativeReals,
bounds=(0.9, 1.5),
doc='Resin capacity [eq/L]')
self.resin_vol = Var(time,
domain=NonNegativeReals,
units=pyunits.m ** 3,
doc='Resin volume needed [m3]')
self.resin_area = Var(time,
initialize=100,
domain=NonNegativeReals,
units=pyunits.m ** 2,
doc='Resin cross-sectional area needed [m2]')
self.resin_depth = Var(time,
initialize=1.5,
domain=NonNegativeReals,
bounds=(0.75, 3),
units=pyunits.m,
doc='Resin bed depth [m]')
self.resin_depth_to_column_diam_ratio = Var(time,
initialize=1,
domain=NonNegativeReals,
bounds=(0.6, 1.6),
units=pyunits.dimensionless,
doc='Ratio of resin depth to column height')
self.resin_per_column = Var(time,
initialize=15,
domain=NonNegativeReals,
units=pyunits.m ** 3,
doc='Resin per column [m3]')
self.resin_loss_frac_annual = Var(time,
initialize=0.045,
domain=NonNegativeReals,
bounds=(3.75, 5.25),
doc='Fraction of resin replaced per year [%]')
self.resin_loss_annual = Var(time,
initialize=20,
domain=NonNegativeReals,
units=pyunits.m ** 3,
doc='Resin replaced per year [m3]')
initialize=2,
domain=NonNegativeReals,
units=pyunits.m,
bounds=(1, 16),
doc='Column height [m]')
self.column_diam = Var(time,
initialize=2,
domain=NonNegativeReals,
units=pyunits.m,
bounds=(1, 4),
doc='Column diameter [m]')
self.column_area = Var(time,
initialize=15,
domain=NonNegativeReals,
units=pyunits.m ** 2,
doc='Column cross-sectional area [m2]')
if self.pv_material == 'fiberglass':
self.column_vol = Var(time,
initialize=2,
domain=NonNegativeReals,
bounds=(0.5, 4),
units=pyunits.m ** 3,
doc='Column volume [m3]')
else:
self.column_vol = Var(time,
initialize=35,
domain=NonNegativeReals,
bounds=(0.5, 25),
units=pyunits.m ** 3,
doc='Column volume [m3]')
self.num_columns = Var(time,
initialize=2,
domain=NonNegativeReals,
bounds=(1, 1E5),
units=pyunits.dimensionless,
doc='Number of columns in parallel')
self.underdrain_h = Var(time,
initialize=0.5,
domain=NonNegativeReals,
units=pyunits.m,
doc='Underdrain height [m]')
self.distributor_h = Var(time,
initialize=1,
domain=NonNegativeReals,
units=pyunits.m,
doc='Distributor height [m]')
self.flow_per_column = Var(time,
initialize=250,
domain=NonNegativeReals,
units=pyunits.m ** 3 / pyunits.hr,
doc='Flow per column [m3/hr]')
self.pressure_drop = Var(time,
initialize=14,
domain=NonNegativeReals,
units=pyunits.psi,
bounds=(0, 25),
doc='Pressure drop across column [psi]')
self.resin_capacity.fix(1.2)
self.loading_rate.fix(20)
self.underdrain_h.fix(0.5)
self.distributor_h.fix(1)
self.resin_loss_frac_annual.fix(0.045)
try:
self.target_removal = unit_params['target_removal']
except KeyError:
self.target_removal.fix(1)
flow_out_m3_hr = pyunits.convert(self.flow_vol_out[self.t], to_units=pyunits.m ** 3 / pyunits.hr)
flow_out_m3_yr = pyunits.convert(self.flow_vol_out[self.t], to_units=pyunits.m ** 3 / pyunits.year)
flow_out_L_hr = pyunits.convert(self.flow_vol_out[self.t], to_units=pyunits.L / pyunits.hr)
_hr * self.cycle_time[self.t])
self.frac_removed_constr.add(self.frac_removed[self.t, c] == 0.99 * (self.mass_removed[self.t, c] / self.mass_in[self.t, c]))
self.denom_resin_constr = Constraint(expr=self.denom_resin[self.t] == sum(self.meq_L[self.t, c] * self.sep_factor[c] for c in self.cons))
self.denom_aq_constr = Constraint(expr=self.denom_aq[self.t] == sum(self.resin_conc[self.t, c] / self.sep_factor[c] for c in self.cons))
self.max_vol_treated_constr = Constraint(expr=self.max_vol_treated[self.t] == (self.resin_conc[self.t, self.target] * 1E3) /
(self.meq_L[self.t, self.target] * self.target_removal[self.t]))
self.resin_vol_constr = Constraint(expr=self.resin_vol[self.t] == flow_out_m3_hr / self.sfr[self.t])
resin_vol_L = pyunits.convert(self.resin_vol[self.t], to_units=pyunits.L)
self.resin_depth_to_column_diam_ratio_constr = Constraint(expr=self.resin_depth_to_column_diam_ratio[self.t] == self.resin_depth[self.t] / self.column_diam[self.t])
self.resin_loss_annual_constr = Constraint(expr=self.resin_loss_annual[self.t] == self.resin_vol[self.t] * self.resin_loss_frac_annual[self.t])
self.cycle_time_constr = Constraint(expr=self.cycle_time[self.t] == (self.max_vol_treated[self.t] * resin_vol_L) / flow_out_L_hr)
self.resin_area_constr = Constraint(expr=self.resin_area[self.t] == self.resin_vol[self.t] / self.resin_depth[self.t])
self.column_area_constr = Constraint(expr=self.column_area[self.t] == 3.141592 * (self.column_diam[self.t] / 2) ** 2)
self.num_columns_constr = Constraint(expr=self.num_columns[self.t] == self.resin_area[self.t] / self.column_area[self.t])
self.flow_per_col_constr = Constraint(expr=self.flow_per_column[self.t] == flow_out_m3_hr / self.num_columns[self.t])
self.resin_per_col_constr = Constraint(expr=self.resin_per_column[self.t] == self.resin_vol[self.t] / self.num_columns[self.t])
self.loading_rate_constr1 = Constraint(expr=self.loading_rate[self.t] == self.flow_per_column[self.t] / self.column_area[self.t])
self.loading_rate_constr2 = Constraint(expr=self.loading_rate[self.t] == self.sfr[self.t] * self.resin_depth[self.t])
self.pressure_drop_constr = Constraint(expr=self.pressure_drop[self.t] == (8.28E-04 * self.loading_rate[self.t] ** 2 + 0.173 * self.loading_rate[self.t] + 0.609) * self.resin_depth[self.t])
self.column_h_constr = Constraint(expr=self.column_h[self.t] == self.resin_depth[self.t] + self.bed_expansion_h[self.t] + self.distributor_h[self.t] + self.underdrain_h[self.t])
self.column_vol_constr = Constraint(expr=self.column_vol[self.t] == 3.14159 * (self.column_diam[self.t] / 2) ** 2 * self.column_h[self.t])
self.ebct_constr = Constraint(expr=self.ebct[self.t] == (self.resin_depth[self.t] / self.loading_rate[self.t]) * 60)
egen_density[self.t] == 994.34 + 761.65 * self.regen_ww[self.t])
self.regen_conc_constr = Constraint(expr=self.regen_conc[self.t] == self.regen_ww[self.t] * self.regen_density[self.t])
self.regen_vol_constr = Constraint(expr=self.regen_vol[self.t] == self.regen_dose[self.t] / self.regen_conc[self.t])
self.num_regen_per_column_annual_constr = Constraint(expr=self.num_regen_per_column_annual[self.t] == 8760 / self.cycle_time[self.t])
self.salt_per_regen_per_column_constr = Constraint(expr=self.salt_per_regen_per_column[self.t] == self.resin_per_column[self.t] * self.regen_dose[self.t])
self.salt_per_col_annual_constr = Constraint(expr=self.salt_per_column_annual[self.t] == self.num_regen_per_column_annual[self.t] * self.salt_per_regen_per_column[self.t])
self.salt_total_annual_constr = Constraint(expr=self.salt_total_annual[self.t] == self.salt_per_column_annual[self.t] * self.num_columns[self.t])
self.salt_dose_constr = Constraint(expr=self.salt_dose[self.t] == self.salt_total_annual[self.t] / flow_out_m3_yr)
self.regen_soln_per_col_constr = Constraint(expr=self.regen_soln_per_column[self.t] == self.resin_per_column[self.t] * self.regen_vol[self.t])
self.regen_soln_per_col_annual_constr = Constraint(expr=self.regen_soln_per_column_annual[self.t] == self.regen_soln_per_column[self.t] * self.num_regen_per_column_annual[self.t])
self.regen_soln_annual_constr = Constraint(expr=self.regen_soln_annual[self.t] == self.regen_soln_per_column_annual[self.t] * self.num_columns[self.t])
self.regen_time_per_col_constr = Constraint(expr=self.regen_time_per_column[self.t] == self.ebct[self.t] * self.regen_vol[self.t])
self.total_regen_time_constr = Constraint(expr=self.total_regen_time[self.t] == self.regen_time_per_column[self.t] + self.rinse_time_per_column[self.t] + self.bw_time[self.t])
self.regen_flow_constr = Constraint(expr=self.regen_flow[self.t] == self.column_vol[self.t] / self.regen_time_per_column[self.t])
f.t] == -1.35E-3 * self.bw_rate[self.t] ** 2 + 1.02E-1 * self.bw_rate[self.t] - 1.23E-2)
self.bed_exp_h_constr = Constraint(expr=self.bed_expansion_h[self.t] == self.resin_depth[self.t] * self.bed_expansion[self.t])
self.bw_flow_constr = Constraint(expr=self.bw_flow[self.t] == self.column_vol[self.t] / self.bw_time[self.t])
lumn[self.t] == self.resin_per_column[self.t] * self.rinse_bv[self.t])
self.rinse_vol_per_col_annual_constr = Constraint(expr=self.rinse_vol_per_column_annual[self.t] == self.rinse_vol_per_column[self.t] * self.num_regen_per_column_annual[self.t])
self.rinse_time_per_col_constr = Constraint(expr=self.rinse_time_per_column[self.t] == self.ebct[self.t] * self.rinse_bv[self.t])
self.rinse_flow_constr = Constraint(expr=self.rinse_flow[self.t] == self.column_vol[self.t] / self.rinse_time_per_column[self.t])
'Sodium_Chloride': self.salt_dose[self.t]
}
self.del_component(self.component_removal_equation)
self.ix_component_removal = ConstraintList()
for c in self.config.property_package.component_list:
if c in self.cons:
self.ix_component_removal.add(self.frac_removed[self.t, c] * self.flow_vol_in[self.t] * self.conc_mass_in[self.t, c] ==
self.flow_vol_waste[self.t] * self.conc_mass_waste[self.t, c])
else:
self.ix_component_removal.add(self.removal_fraction[self.t, c] * self.flow_vol_in[self.t] * self.conc_mass_in[self.t, c] ==
self.flow_vol_waste[self.t] * self.conc_mass_waste[self.t, c])
def sac(self, unit_params):
onfig.time
e,
initialize=300,
domain=NonNegativeReals,
units=pyunits.kg / pyunits.m ** 3,
bounds=(80, 500),\
doc='NaCl dose required for regeneration [kg/m3]')
self.regen_rate = Var(time,
initialize=4,
domain=NonNegativeReals,
bounds=(2, 5),
doc='Regeneration rate [BV/hr]')
self.regen_density = Var(time,
initialize=1000,
domain=NonNegativeReals,
units=pyunits.kg / pyunits.m ** 3,
bounds=(990, 1200),
doc='Density of NaCl regen solution [kg/m3]')
self.regen_ww = Var(time,
initialize=0.1,
domain=NonNegativeReals,
bounds=(0.015, 0.26),
doc='Strength of NaCl solution w/w [kg NaCl/kg soln]')
self.regen_conc = Var(time,
initialize=110,
domain=NonNegativeReals,
units=pyunits.kg / pyunits.m ** 3,
doc='Concentration of regen solution [kg/m3]')
self.regen_vol = Var(time,
initialize=2,
domain=NonNegativeReals,
doc='m3 of regen solution per m3 resin')
self.regen_soln_per_column = Var(time,
initialize=50,
domain=NonNegativeReals,
units=pyunits.m ** 3,
doc='Regen solution used per column [m3/column]')
self.regen_soln_per_column_annual = Var(time,
initialize=1E3,
domain=NonNegativeReals,
units=pyunits.m ** 3 / pyunits.year,
doc='Annual regen used per column [m3/year]')
self.regen_soln_annual = Var(time,
initialize=1E5,
domain=NonNegativeReals,
units=pyunits.m ** 3 / pyunits.year,
doc='Total volume regen solution used [m3/year]')
self.regen_time_per_column = Var(time,
initialize=5,
domain=NonNegativeReals,
units=pyunits.min,
doc='Regen time per column [min]')
self.regen_flow = Var(time,
initialize=10,
domain=NonNegativeReals,
units=pyunits.m ** 3 / pyunits.min,
doc='Regeneration flow rate [m3/min]')
self.num_regen_per_column_annual = Var(time,
initialize=200,
domain=NonNegativeReals,
doc='Number of regen cycles per year')
self.salt_per_regen_per_column = Var(time,
initialize=5E3,
domain=NonNegativeReals,
doc='Number of regen cycles per year')
self.salt_per_column_annual = Var(time,
initialize=1E5,
domain=NonNegativeReals,
units=pyunits.kg / pyunits.year,
doc='Mass of salt per column per year [kg/yr]')
self.salt_total_annual = Var(time,
initialize=1E6,
domain=NonNegativeReals,
units=pyunits.kg / pyunits.year,
doc='Mass of salt per year [kg/yr]')
self.salt_dose = Var(time,
initialize=0.1,
domain=NonNegativeReals,
units=pyunits.kg / pyunits.m ** 3,
doc='Salt dose for system [kg/m3]')
self.total_regen_time = Var(time,
initialize=30,
units=pyunits.min,
domain=NonNegativeReals,
doc='Total regeneration cycle time [min]')
self.regen_dose.fix(300)
try:
self.regen_ww.fix(unit_params['regen_ww'])
except KeyError:
self.regen_ww.fix(0.1)
initialize=5,
domain=NonNegativeReals,
units=pyunits.m / pyunits.hour,
bounds=(4.5, 6.5),
doc='Backwash rate [m/hr]')
self.bw_time = Var(time,
initialize=6,
domain=NonNegativeReals,
units=pyunits.minute,
bounds=(4, 15),
doc='Backwash time [min]')
self.bw_flow = Var(time,
initialize=5,
domain=NonNegativeReals,
units=pyunits.m ** 3 / pyunits.minute,
doc='Backwash flow rate [m3/min]')
self.bed_expansion = Var(time,
initialize=0.5,
domain=NonNegativeReals,
units=pyunits.dimensionless,
bounds=(0.4, 0.6),
doc='Resin bed expansion during backwash [%]')
self.bed_expansion_h = Var(time,
domain=NonNegativeReals,
units=pyunits.m,
bounds=(0.1, 3),
doc='Resin bed expansion during backwash [m]')
self.bw_time.fix(6)
initialize=5,
domain=NonNegativeReals,
bounds=(2, 5),
doc='Number of bed volumes for rinse step [BV]')
self.rinse_vol_per_column = Var(time,
initialize=150,
domain=NonNegativeReals,
units=pyunits.m ** 3,
doc='Rinse volume per column [m3/col]')
self.rinse_vol_per_column_annual = Var(time,
initialize=5E3,
domain=NonNegativeReals,
units=pyunits.m ** 3 / pyunits.year,
doc='Rinse volume per column [m3/yr]')
self.rinse_time_per_column = Var(time,
initialize=4,
domain=NonNegativeReals,
units=pyunits.min,
doc='Rinse time per column [min]')
self.rinse_flow = Var(time,
initialize=2,
domain=NonNegativeReals,
units=pyunits.m ** 3 / pyunits.min,
doc='Rinse step flow rate [m3/min]')
self.rinse_bv.fix(3)
ac.csv', index_col='constituent')
self.cons = [c for c in self.config.property_package.component_list if c in ix_df.index]
ix_df = self.ix_df = ix_df.loc[self.cons].copy()
self.sep_factor_dict = ix_df.to_dict()['sep_factor']
self.meq_conv_dict = ix_df.to_dict()['meq']
try:
self.target = unit_params['target']
except KeyError:
self.cons_df = self.source_df.loc[[c for c in self.cons if c != 'sodium']].copy()
self.cons_df['meq_L'] = [(self.cons_df.loc[c].value * 1E3) / self.meq_conv_dict[c] for c in self.cons if c != 'sodium']
self.target = self.cons_df.meq_L.idxmax()
for k, v in self.sep_factor_dict.items():
if v > self.sep_factor_dict[self.target]:
self.sep_factor_dict[k] = 0.99 * self.sep_factor_dict[self.target]
self.sep_factor = Param(self.cons,
initialize=self.sep_factor_dict)
self.meq_conv = Param(self.cons,
initialize=self.meq_conv_dict)
self.target_removal = Var(time,
initialize=1,
domain=NonNegativeReals,
bounds=(0.0001, 1),
doc='Removal fraction for target compound')
self.sfr = Var(time,
initialize=30,
domain=NonNegativeReals,
bounds=(6, 50),
doc='Service flow rate [BV/hr]')
self.loading_rate = Var(time,
initialize=20,
domain=NonNegativeReals,
bounds=(10, 40),
units=pyunits.m / pyunits.hr,
doc='Column loading rate (superficial velocity) [m/hr]')
self.cycle_time = Var(time,
initialize=100,
domain=NonNegativeReals,
units=pyunits.hr,
doc='Service cycle time [hr]')
self.ebct = Var(time,
initialize=1.1,
domain=NonNegativeReals,
units=pyunits.min,
doc='Empty Bed Contact Time [min]')
self.mg_L = Var(time,
self.cons,
initialize=1,
domain=NonNegativeReals,
doc='Influent concentration in mg/L')
self.meq_L = Var(time,
self.cons,
initialize=0.1,
domain=NonNegativeReals,
doc='Influent concentration in meq/L')
self.mass_in = Var(time,
self.cons,
initialize=200,
domain=NonNegativeReals,
doc='Influent mass [eq]')
self.mass_removed = Var(time,
self.cons,
initialize=10,
domain=NonNegativeReals,
doc='Mass removed [eq]')
self.frac_removed = Var(time,
self.cons,
initialize=0.8,
domain=NonNegativeReals,
doc='Fraction removed [%]')
self.denom_resin = Var(time,
initialize=1,
domain=NonNegativeReals)
self.denom_aq = Var(time,
initialize=1,
domain=NonNegativeReals)
self.resin_conc = Var(time,
self.cons,
initialize=0.1,
domain=NonNegativeReals,
doc='Resin phase concentration of each ion [eq/L resin]')
self.max_vol_treated = Var(time,
initialize=5E3,
domain=NonNegativeReals,
bounds=(100, 1E6),
units=pyunits.L / pyunits.L,
doc='Max volume of water treated before breakthrough [L water/L resin]')
self.resin_capacity = Var(time,
initialize=1.7,
domain=NonNegativeReals,
bounds=(1.6, 2.2),
doc='Resin capacity [eq/L]')
self.resin_vol = Var(time,
domain=NonNegativeReals,
units=pyunits.m ** 3,
doc='Resin volume needed [m3]')
self.resin_area = Var(time,
initialize=100,
domain=NonNegativeReals,
units=pyunits.m ** 2,
doc='Resin cross-sectional area needed [m2]')
self.resin_depth = Var(time,
initialize=1.5,
domain=NonNegativeReals,
bounds=(0.75, 3),
units=pyunits.m,
doc='Resin bed depth [m]')
self.resin_depth_to_column_diam_ratio = Var(time,
initialize=1,
domain=NonNegativeReals,
bounds=(0.6, 1.6),
units=pyunits.dimensionless,
doc='Ratio of resin depth to column height')
self.resin_per_column = Var(time,
initialize=15,
domain=NonNegativeReals,
units=pyunits.m ** 3,
doc='Resin per column [m3]')
self.resin_loss_frac_annual = Var(time,
initialize=0.045,
domain=NonNegativeReals,
bounds=(3.75, 5.25),
doc='Fraction of resin replaced per year [%]')
self.resin_loss_annual = Var(time,
initialize=20,
domain=NonNegativeReals,
units=pyunits.m ** 3,
doc='Resin replaced per year [m3]')
initialize=2,
domain=NonNegativeReals,
units=pyunits.m,
bounds=(1, 16),
doc='Column height [m]')
self.column_diam = Var(time,
initialize=2,
domain=NonNegativeReals,
units=pyunits.m,
bounds=(1, 4),
doc='Column diameter [m]')
self.column_area = Var(time,
initialize=15,
domain=NonNegativeReals,
units=pyunits.m ** 2,
doc='Column cross-sectional area [m2]')
if self.pv_material == 'fiberglass':
self.column_vol = Var(time,
initialize=2,
domain=NonNegativeReals,
bounds=(0.5, 4),
units=pyunits.m ** 3,
doc='Column volume [m3]')
else:
self.column_vol = Var(time,
initialize=35,
domain=NonNegativeReals,
bounds=(0.5, 25),
units=pyunits.m ** 3,
doc='Column volume [m3]')
self.num_columns = Var(time,
initialize=2,
domain=NonNegativeReals,
bounds=(1, 1E5),
units=pyunits.dimensionless,
doc='Number of columns in parallel')
self.underdrain_h = Var(time,
initialize=0.5,
domain=NonNegativeReals,
units=pyunits.m,
doc='Underdrain height [m]')
self.distributor_h = Var(time,
initialize=1,
domain=NonNegativeReals,
units=pyunits.m,
doc='Distributor height [m]')
self.flow_per_column = Var(time,
initialize=250,
domain=NonNegativeReals,
units=pyunits.m ** 3 / pyunits.hr,
doc='Flow per column [m3/hr]')
self.pressure_drop = Var(time,
initialize=14,
domain=NonNegativeReals,
units=pyunits.psi,
bounds=(0, 25),
doc='Pressure drop across column [psi]')
self.resin_capacity.fix(1.7)
self.loading_rate.fix(20)
self.underdrain_h.fix(0.5)
self.distributor_h.fix(1)
self.resin_loss_frac_annual.fix(0.045)
try:
self.target_removal = unit_params['target_removal']
except KeyError:
self.target_removal.fix(1)
flow_out_m3_hr = pyunits.convert(self.flow_vol_out[self.t], to_units=pyunits.m ** 3 / pyunits.hr)
flow_out_m3_yr = pyunits.convert(self.flow_vol_out[self.t], to_units=pyunits.m ** 3 / pyunits.year)
flow_out_L_hr = pyunits.convert(self.flow_vol_out[self.t], to_units=pyunits.L / pyunits.hr)
_hr * self.cycle_time[self.t])
self.frac_removed_constr.add(self.frac_removed[self.t, c] == 0.99 * (self.mass_removed[self.t, c] / self.mass_in[self.t, c]))
self.denom_resin_constr = Constraint(expr=self.denom_resin[self.t] == sum(self.meq_L[self.t, c] * self.sep_factor[c] for c in self.cons))
self.denom_aq_constr = Constraint(expr=self.denom_aq[self.t] == sum(self.resin_conc[self.t, c] / self.sep_factor[c] for c in self.cons))
self.max_vol_treated_constr = Constraint(expr=self.max_vol_treated[self.t] == (self.resin_conc[self.t, self.target] * 1E3) /
(self.meq_L[self.t, self.target] * self.target_removal[self.t]))
self.resin_vol_constr = Constraint(expr=self.resin_vol[self.t] == flow_out_m3_hr / self.sfr[self.t])
resin_vol_L = pyunits.convert(self.resin_vol[self.t], to_units=pyunits.L)
self.resin_depth_to_column_diam_ratio_constr = Constraint(expr=self.resin_depth_to_column_diam_ratio[self.t] == self.resin_depth[self.t] / self.column_diam[self.t])
self.resin_loss_annual_constr = Constraint(expr=self.resin_loss_annual[self.t] == self.resin_vol[self.t] * self.resin_loss_frac_annual[self.t])
self.cycle_time_constr = Constraint(expr=self.cycle_time[self.t] == (self.max_vol_treated[self.t] * resin_vol_L) / flow_out_L_hr)
self.resin_area_constr = Constraint(expr=self.resin_area[self.t] == self.resin_vol[self.t] / self.resin_depth[self.t])
self.column_area_constr = Constraint(expr=self.column_area[self.t] == 3.141592 * (self.column_diam[self.t] / 2) ** 2)
self.num_columns_constr = Constraint(expr=self.num_columns[self.t] == self.resin_area[self.t] / self.column_area[self.t])
self.flow_per_col_constr = Constraint(expr=self.flow_per_column[self.t] == flow_out_m3_hr / self.num_columns[self.t])
self.resin_per_col_constr = Constraint(expr=self.resin_per_column[self.t] == self.resin_vol[self.t] / self.num_columns[self.t])
self.loading_rate_constr1 = Constraint(expr=self.loading_rate[self.t] == self.flow_per_column[self.t] / self.column_area[self.t])
self.loading_rate_constr2 = Constraint(expr=self.loading_rate[self.t] == self.sfr[self.t] * self.resin_depth[self.t])
self.pressure_drop_constr = Constraint(expr=self.pressure_drop[self.t] == (8.28E-04 * self.loading_rate[self.t] ** 2 + 0.173 * self.loading_rate[self.t] + 0.609) * self.resin_depth[self.t])
self.column_h_constr = Constraint(expr=self.column_h[self.t] == self.resin_depth[self.t] + self.bed_expansion_h[self.t] + self.distributor_h[self.t] + self.underdrain_h[self.t])
self.column_vol_constr = Constraint(expr=self.column_vol[self.t] == 3.14159 * (self.column_diam[self.t] / 2) ** 2 * self.column_h[self.t])
self.ebct_constr = Constraint(expr=self.ebct[self.t] == (self.resin_depth[self.t] / self.loading_rate[self.t]) * 60)
egen_density[self.t] == 994.34 + 761.65 * self.regen_ww[self.t])
self.regen_conc_constr = Constraint(expr=self.regen_conc[self.t] == self.regen_ww[self.t] * self.regen_density[self.t])
self.regen_vol_constr = Constraint(expr=self.regen_vol[self.t] == self.regen_dose[self.t] / self.regen_conc[self.t])
self.num_regen_per_column_annual_constr = Constraint(expr=self.num_regen_per_column_annual[self.t] == 8760 / self.cycle_time[self.t])
self.salt_per_regen_per_column_constr = Constraint(expr=self.salt_per_regen_per_column[self.t] == self.resin_per_column[self.t] * self.regen_dose[self.t])
self.salt_per_col_annual_constr = Constraint(expr=self.salt_per_column_annual[self.t] == self.num_regen_per_column_annual[self.t] * self.salt_per_regen_per_column[self.t])
self.salt_total_annual_constr = Constraint(expr=self.salt_total_annual[self.t] == self.salt_per_column_annual[self.t] * self.num_columns[self.t])
self.salt_dose_constr = Constraint(expr=self.salt_dose[self.t] == self.salt_total_annual[self.t] / flow_out_m3_yr)
self.regen_soln_per_col_constr = Constraint(expr=self.regen_soln_per_column[self.t] == self.resin_per_column[self.t] * self.regen_vol[self.t])
self.regen_soln_per_col_annual_constr = Constraint(expr=self.regen_soln_per_column_annual[self.t] == self.regen_soln_per_column[self.t] * self.num_regen_per_column_annual[self.t])
self.regen_soln_annual_constr = Constraint(expr=self.regen_soln_annual[self.t] == self.regen_soln_per_column_annual[self.t] * self.num_columns[self.t])
self.regen_time_per_col_constr = Constraint(expr=self.regen_time_per_column[self.t] == self.ebct[self.t] * self.regen_vol[self.t])
self.total_regen_time_constr = Constraint(expr=self.total_regen_time[self.t] == self.regen_time_per_column[self.t] + self.rinse_time_per_column[self.t] + self.bw_time[self.t])
self.regen_flow_constr = Constraint(expr=self.regen_flow[self.t] == self.column_vol[self.t] / self.regen_time_per_column[self.t])
f.t] == -1.35E-3 * self.bw_rate[self.t] ** 2 + 1.02E-1 * self.bw_rate[self.t] - 1.23E-2)
self.bed_exp_h_constr = Constraint(expr=self.bed_expansion_h[self.t] == self.resin_depth[self.t] * self.bed_expansion[self.t])
self.bw_flow_constr = Constraint(expr=self.bw_flow[self.t] == self.column_vol[self.t] / self.bw_time[self.t])
lumn[self.t] == self.resin_per_column[self.t] * self.rinse_bv[self.t])
self.rinse_vol_per_col_annual_constr = Constraint(expr=self.rinse_vol_per_column_annual[self.t] == self.rinse_vol_per_column[self.t] * self.num_regen_per_column_annual[self.t])
self.rinse_time_per_col_constr = Constraint(expr=self.rinse_time_per_column[self.t] == self.ebct[self.t] * self.rinse_bv[self.t])
self.rinse_flow_constr = Constraint(expr=self.rinse_flow[self.t] == self.column_vol[self.t] / self.rinse_time_per_column[self.t])
'Sodium_Chloride': self.salt_dose[self.t]
}
self.del_component(self.component_removal_equation)
self.ix_component_removal = ConstraintList()
for c in self.config.property_package.component_list:
if c in self.cons:
self.ix_component_removal.add(self.frac_removed[self.t, c] * self.flow_vol_in[self.t] * self.conc_mass_in[self.t, c] ==
self.flow_vol_waste[self.t] * self.conc_mass_waste[self.t, c])
else:
self.ix_component_removal.add(self.removal_fraction[self.t, c] * self.flow_vol_in[self.t] * self.conc_mass_in[self.t, c] ==
self.flow_vol_waste[self.t] * self.conc_mass_waste[self.t, c])
def get_costing(self, unit_params=None, year=None):
financials.create_costing_block(self, basis_year, tpec_or_tic)
time = self.flowsheet().config.time
self.t = time.first()
self.units_meta = self.config.property_package.get_metadata().get_derived_units
self.mode = unit_params['mode']
self.source_df = self.parent_block().source_df
self.parent_block().has_ix = True
try:
self.pv_material = unit_params['pv_material']
except KeyError:
self.pv_material = 'carbon_w_plastic_internals'
if self.mode == 'sac':
self.resin_dict = {
'polystyrenic_macro': 3680,
'polystyrenic_gel': 6240,
}
try:
self.resin_type = unit_params['resin_type']
except KeyError:
self.resin_type = 'polystyrenic_macro'
self.sac(unit_params)
if self.mode == 'sba':
self.resin_dict = {
'styrenic_gel_1': 5214,
'styrenic_gel_2': 6116,
'styrenic_macro_1': 7298,
'styrenic_macro_2': 7810,
'polyacrylic': 8658,
'nitrate': 6116
}
try:
self.resin_type = unit_params['resin_type']
except KeyError:
self.resin_type = 'styrenic_gel_1'
self.sba(unit_params)
self.costing.fixed_cap_inv_unadjusted = Expression(expr=self.fixed_cap(unit_params),
doc='Unadjusted fixed capital investment')
self.electricity = Expression(expr=self.elect(),
doc='Electricity intensity [kwh/m3]')
self.costing.other_var_cost = (self.resin_unit_cap[self.t] * self.resin_loss_annual[self.t]) * 1E-6
financials.get_complete_costing(self.costing) | true | true |
1c2e4e8ccd6bde2732204fcd388857bed85a4f35 | 1,147 | py | Python | tests/test_film.py | kiniadit/swapit-wrapper | 46ba13683f77b53575b3f10398288791ad863426 | [
"MIT"
] | null | null | null | tests/test_film.py | kiniadit/swapit-wrapper | 46ba13683f77b53575b3f10398288791ad863426 | [
"MIT"
] | null | null | null | tests/test_film.py | kiniadit/swapit-wrapper | 46ba13683f77b53575b3f10398288791ad863426 | [
"MIT"
] | null | null | null | import responses
from swapi_wrapper import Film, make_url
@responses.activate
def test_film_get(film_data):
responses.add(responses.GET, film_data['url'], json=film_data)
assert Film.resource_url == 'https://swapi.co/api/films/'
film = Film.get(1)
assert isinstance(film, Film)
assert film.title == 'A New Hope'
@responses.activate
def test_film_get_returns_none_on_error():
responses.add(responses.GET, make_url(
Film.resource_url, '99'), status=404)
assert Film.get(99) is None
def test_film_attributes(film):
str_attributes = 'title opening_crawl director release_date url'
int_attributes = 'episode_id'
list_attributes = 'producers characters planets starships vehicles species'
for attrib in str_attributes.split():
value = getattr(film, attrib)
assert isinstance(value, str)
assert isinstance(film.episode_id, int)
for attrib in list_attributes.split():
value = getattr(film, attrib)
assert isinstance(value, list)
def test_film_producers(film):
assert 'Gary Kurtz' in film.producers
assert 'Rick McCallum' in film.producers
| 26.674419 | 79 | 0.718396 | import responses
from swapi_wrapper import Film, make_url
@responses.activate
def test_film_get(film_data):
responses.add(responses.GET, film_data['url'], json=film_data)
assert Film.resource_url == 'https://swapi.co/api/films/'
film = Film.get(1)
assert isinstance(film, Film)
assert film.title == 'A New Hope'
@responses.activate
def test_film_get_returns_none_on_error():
responses.add(responses.GET, make_url(
Film.resource_url, '99'), status=404)
assert Film.get(99) is None
def test_film_attributes(film):
str_attributes = 'title opening_crawl director release_date url'
int_attributes = 'episode_id'
list_attributes = 'producers characters planets starships vehicles species'
for attrib in str_attributes.split():
value = getattr(film, attrib)
assert isinstance(value, str)
assert isinstance(film.episode_id, int)
for attrib in list_attributes.split():
value = getattr(film, attrib)
assert isinstance(value, list)
def test_film_producers(film):
assert 'Gary Kurtz' in film.producers
assert 'Rick McCallum' in film.producers
| true | true |
1c2e4f25610415e051c3646eb03b6dfb4efe06d5 | 235 | py | Python | atividade2/RetornarVerticesAdjacentes.py | mateus2810/atividadesIa | 0ffc816c962889fb9e0b9635692d616e46a0d0c5 | [
"Apache-2.0"
] | null | null | null | atividade2/RetornarVerticesAdjacentes.py | mateus2810/atividadesIa | 0ffc816c962889fb9e0b9635692d616e46a0d0c5 | [
"Apache-2.0"
] | null | null | null | atividade2/RetornarVerticesAdjacentes.py | mateus2810/atividadesIa | 0ffc816c962889fb9e0b9635692d616e46a0d0c5 | [
"Apache-2.0"
] | null | null | null | #Questão 7 - Retornar os vertes adjacentes
import numpy as np
matrixIa = [[0,5,0,0,15,2], [5,0,0,9,22,4], [0,0,0,13,1,0], [9,0,12,0,0,6], [15,22,1,0,0,0], [2,4,0,6,0,0]]
#Mostrar os vertes adjacentes ]
print(np.matrix(matrixIa))
| 26.111111 | 107 | 0.617021 |
import numpy as np
matrixIa = [[0,5,0,0,15,2], [5,0,0,9,22,4], [0,0,0,13,1,0], [9,0,12,0,0,6], [15,22,1,0,0,0], [2,4,0,6,0,0]]
print(np.matrix(matrixIa))
| true | true |
1c2e5066f3b9c3767bdcfbe8c26f9f81315452be | 372 | py | Python | app/core/migrations/0002_user_is_staff.py | EdgarGGamartgo/recipe-app-api | e1749710b61bd1478527cc6d0415f335b914eb70 | [
"MIT"
] | null | null | null | app/core/migrations/0002_user_is_staff.py | EdgarGGamartgo/recipe-app-api | e1749710b61bd1478527cc6d0415f335b914eb70 | [
"MIT"
] | null | null | null | app/core/migrations/0002_user_is_staff.py | EdgarGGamartgo/recipe-app-api | e1749710b61bd1478527cc6d0415f335b914eb70 | [
"MIT"
] | null | null | null | # Generated by Django 3.0.8 on 2020-07-28 02:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='user',
name='is_staff',
field=models.BooleanField(default=True),
),
]
| 19.578947 | 52 | 0.583333 |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='user',
name='is_staff',
field=models.BooleanField(default=True),
),
]
| true | true |
1c2e50d3f6208bc987f1ae48612865cc8e89d195 | 5,112 | py | Python | pelayanan/views.py | diaksizz/Adisatya | 1b20e523aede6ab3e8effb1ca63adf72016a6839 | [
"MIT"
] | null | null | null | pelayanan/views.py | diaksizz/Adisatya | 1b20e523aede6ab3e8effb1ca63adf72016a6839 | [
"MIT"
] | 7 | 2021-03-30T14:04:35.000Z | 2022-01-13T03:07:50.000Z | pelayanan/views.py | diaksizz/Adisatya | 1b20e523aede6ab3e8effb1ca63adf72016a6839 | [
"MIT"
] | null | null | null | from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from aitc_service.views import *
from aitc_service.forms import *
from .forms import *
from .models import *
from .filters import PelayananFilter
# Create your views here.
###############Pengaduan########################################################
@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def pelayanan(request):
pengaduan = Pengaduans.objects.all()
client = Client.objects.all()
kategori_penanganan = request.GET.get('kategori_penanganan')
# pengaduans = pengaduan.order_set.all()
myFilter = PelayananFilter()
form = PelayananForm()
formup = EditStatusForm()
if request.method == 'POST':
form = PelayananForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, 'Data Berhasil Ditambahkan')
return redirect('pelayanan')
context = {'pengaduan':pengaduan, 'client':client, 'myFilter':myFilter, 'act':'pelayanan', 'form':form, 'formup':formup}
return render(request, 'pelayanan.html', context)
@login_required(login_url='login')
def updateStatus(request):
formup = EditStatusForm()
if request.method =='POST':
formup = EditStatusForm(request.POST)
if formup.is_valid():
idk = formup.cleaned_data['pk']
kategori_penanganan = formup.cleaned_data['kategori_penanganan']
Pengaduans.objects.filter(id=idk).update(kategori_penanganan=kategori_penanganan)
return redirect('pelayanan')
@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def filterpelayanan(request):
pelayananfilter = FilterForm()
if request.method == 'GET':
pelayananfilter = FilterForm(request.GET)
if pelayananfilter.is_valid():
kategori = pelayananfilter.cleaned_data['kategori_penanganan']
pelayanan = Pengaduans.objects.filter(kategori_penanganan=kategori)
context = {'pelayananfilter':pelayananfilter, 'kategori':kategori, 'act':'pelayanan'}
return render(request, 'pelayanan.html', context)
# @login_required(login_url='login')
# @allowed_users(allowed_roles=['admin'])
# def tambahpelayanan(request):
# form = PelayananForm()
# if request.method == 'POST':
# form = PelayananForm(request.POST)
# if form.is_valid():
# form.save()
# messages.success(request, 'Data Berhasil Ditambahkan')
# return redirect('pelayanan')
#
# context = {'form':form, 'act':'pelayanan'}
# return render(request, 'tambah_pelayanan.html', context)
@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def editstatus(request, pk):
pengaduan = Pengaduans.objects.get(id=pk)
form = StatusForm(instance=pengaduan)
if request.method == 'POST':
form = StatusForm(request.POST, instance=pengaduan)
if form.is_valid():
form.save()
messages.success(request, 'Data Berhasil Diubah')
return redirect('pelayanan')
context = {'form':form, 'pengaduan':pengaduan, 'act':'pelayanan'}
return render(request, 'edit_status.html', context)
@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def detailpelayanan(request, pk):
pengaduan = Pengaduans.objects.get(id=pk)
# respon = Respons.objects.get(id=pk)
form = PelayananForm(instance=pengaduan)
if request.method == 'POST':
form = PelayananForm(request.POST, instance=pengaduan)
if form.is_valid():
form.save()
messages.success(request, 'Data Berhasil Diubah')
return redirect('detailpelayanan')
context = {'pengaduan':pengaduan, 'form':form, 'act':'pelayanan'}
return render(request, 'detail_pelayanan.html', context)
@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def deletepelayanan(request, pk):
pengaduan = Pengaduans.objects.get(id=pk)
form = DeletePelayananForm()
if request.method == 'POST':
pengaduan.delete()
messages.success(request, 'Data Berhasil Dihapus')
return redirect('pelayanan')
@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def pelayanandel(request, pk):
pengaduan = Pengaduans.objects.get(id=pk)
if request.method == 'POST':
pengaduan.delete()
messages.success(request, 'Data Berhasil Dihapus')
return redirect('pelayanan')
context = {'item':pengaduan, 'act':'pelayanan'}
return render(request, 'del_pelayanan.html', context)
###############Dashboard########################################################
@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def detaildaftar(request, pk):
pengaduan = Pengaduans.objects.get(id=pk)
# respon = Respon.objects.get(id=pk)
form = PelayananForm(instance=pengaduan)
context = {'form':form, 'pengaduan':pengaduan, 'act':'dashboard'}
return render(request, 'detail_daftar.html', context)
| 35.748252 | 124 | 0.676839 | from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from aitc_service.views import *
from aitc_service.forms import *
from .forms import *
from .models import *
from .filters import PelayananFilter
if form.is_valid():
form.save()
messages.success(request, 'Data Berhasil Diubah')
return redirect('detailpelayanan')
context = {'pengaduan':pengaduan, 'form':form, 'act':'pelayanan'}
return render(request, 'detail_pelayanan.html', context)
@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def deletepelayanan(request, pk):
pengaduan = Pengaduans.objects.get(id=pk)
form = DeletePelayananForm()
if request.method == 'POST':
pengaduan.delete()
messages.success(request, 'Data Berhasil Dihapus')
return redirect('pelayanan')
@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def pelayanandel(request, pk):
pengaduan = Pengaduans.objects.get(id=pk)
if request.method == 'POST':
pengaduan.delete()
messages.success(request, 'Data Berhasil Dihapus')
return redirect('pelayanan')
context = {'item':pengaduan, 'act':'pelayanan'}
return render(request, 'del_pelayanan.html', context)
| true | true |
1c2e511591999b44847ebd94d2fabef97267fc38 | 1,510 | py | Python | local/lib/python3.6/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/pgagent/tests/tests_pgagent_get.py | sahilsdei/django_ecommerce | edc2513e41aca178d1ccae14ebaa6c7b1d709e73 | [
"MIT"
] | null | null | null | local/lib/python3.6/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/pgagent/tests/tests_pgagent_get.py | sahilsdei/django_ecommerce | edc2513e41aca178d1ccae14ebaa6c7b1d709e73 | [
"MIT"
] | null | null | null | local/lib/python3.6/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/pgagent/tests/tests_pgagent_get.py | sahilsdei/django_ecommerce | edc2513e41aca178d1ccae14ebaa6c7b1d709e73 | [
"MIT"
] | null | null | null | ##########################################################################
#
# pgAdmin 4 - PostgreSQL Tools
#
# Copyright (C) 2013 - 2018, The pgAdmin Development Team
# This software is released under the PostgreSQL Licence
#
##########################################################################
import uuid
from pgadmin.utils.route import BaseTestGenerator
from regression.python_test_utils import test_utils as utils
from . import utils as pgagent_utils
class PgAgentGetTestCase(BaseTestGenerator):
"""This class will test the get pgAgent job API"""
scenarios = [
('Get pgAgent job', dict(url='/browser/pga_job/obj/'))
]
def setUp(self):
flag, msg = pgagent_utils.is_valid_server_to_run_pgagent(self)
if not flag:
self.skipTest(msg)
flag, msg = pgagent_utils.is_pgagent_installed_on_server(self)
if not flag:
self.skipTest(msg)
name = "test_job_get%s" % str(uuid.uuid4())[1:8]
self.job_id = pgagent_utils.create_pgagent_job(self, name)
def runTest(self):
"""This function will get pgAgent job"""
response = self.tester.get(
'{0}{1}/{2}/{3}'.format(
self.url, str(utils.SERVER_GROUP), str(self.server_id),
str(self.job_id)
),
content_type='html/json'
)
self.assertEquals(response.status_code, 200)
def tearDown(self):
"""Clean up code"""
pgagent_utils.delete_pgagent_job(self)
| 32.826087 | 74 | 0.576159 | true | true | |
1c2e513ed9092fe958702b468646efc642b43f91 | 183 | py | Python | tests/datasets/test_ncbi.py | iwasakishuto/Keras-Imitation | 8ac0cd7c8912d49d13b19a0182ad534c0781fbfe | [
"MIT"
] | 4 | 2020-04-25T08:50:36.000Z | 2020-04-26T04:49:16.000Z | tests/datasets/test_ncbi.py | iwasakishuto/Keras-Imitation | 8ac0cd7c8912d49d13b19a0182ad534c0781fbfe | [
"MIT"
] | null | null | null | tests/datasets/test_ncbi.py | iwasakishuto/Keras-Imitation | 8ac0cd7c8912d49d13b19a0182ad534c0781fbfe | [
"MIT"
] | null | null | null | # coding: utf-8
from kerasy.datasets import ncbi
def test_get_seq():
# SARS coronavirus, complete genome
sequence = ncbi.getSeq("NC_004718")
assert sequence is not None
| 20.333333 | 39 | 0.721311 |
from kerasy.datasets import ncbi
def test_get_seq():
sequence = ncbi.getSeq("NC_004718")
assert sequence is not None
| true | true |
1c2e51d9a46484396d7bb44c506394b105fd35ba | 433 | py | Python | examples/nodes.py | hamersaw/stippy | ad341eab764c4a4162e90afba2e80bdb25e8e25d | [
"MIT"
] | null | null | null | examples/nodes.py | hamersaw/stippy | ad341eab764c4a4162e90afba2e80bdb25e8e25d | [
"MIT"
] | null | null | null | examples/nodes.py | hamersaw/stippy | ad341eab764c4a4162e90afba2e80bdb25e8e25d | [
"MIT"
] | null | null | null | #!/bin/python3
import os
import sys
# import realative 'stippy' python project
script_dir = os.path.dirname(os.path.realpath(__file__))
sys.path.append(script_dir + '/../')
import stippy
if __name__ == '__main__':
host_addr = '127.0.0.1:15606'
# print nodes
print('-----NODES-----')
nodes = stippy.list_nodes(host_addr)
for node in nodes:
print(str(node.id) + ' ' + node.rpcAddr + ' ' + node.xferAddr)
| 24.055556 | 70 | 0.646651 |
import os
import sys
script_dir = os.path.dirname(os.path.realpath(__file__))
sys.path.append(script_dir + '/../')
import stippy
if __name__ == '__main__':
host_addr = '127.0.0.1:15606'
print('-----NODES-----')
nodes = stippy.list_nodes(host_addr)
for node in nodes:
print(str(node.id) + ' ' + node.rpcAddr + ' ' + node.xferAddr)
| true | true |
1c2e52342ca11109dc41f59d2289fc2c9c8ac5bb | 18,480 | py | Python | dimod/utilities.py | wbernoudy/dimod | c39677b4a743574dc795bc140dce703abd61087b | [
"Apache-2.0"
] | null | null | null | dimod/utilities.py | wbernoudy/dimod | c39677b4a743574dc795bc140dce703abd61087b | [
"Apache-2.0"
] | null | null | null | dimod/utilities.py | wbernoudy/dimod | c39677b4a743574dc795bc140dce703abd61087b | [
"Apache-2.0"
] | null | null | null | # Copyright 2018 D-Wave Systems 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 copy
import os
import itertools
from functools import reduce
import numpy as np
__all__ = ['ising_energy',
'qubo_energy',
'ising_to_qubo',
'qubo_to_ising',
'child_structure_dfs',
'get_include',
]
def ising_energy(sample, h, J, offset=0.0):
"""Calculate the energy for the specified sample of an Ising model.
Energy of a sample for a binary quadratic model is defined as a sum, offset
by the constant energy offset associated with the model, of
the sample multipled by the linear bias of the variable and
all its interactions. For an Ising model,
.. math::
E(\mathbf{s}) = \sum_v h_v s_v + \sum_{u,v} J_{u,v} s_u s_v + c
where :math:`s_v` is the sample, :math:`h_v` is the linear bias, :math:`J_{u,v}`
the quadratic bias (interactions), and :math:`c` the energy offset.
Args:
sample (dict[variable, spin]):
Sample for a binary quadratic model as a dict of form {v: spin, ...},
where keys are variables of the model and values are spins (either -1 or 1).
h (dict[variable, bias]):
Linear biases as a dict of the form {v: bias, ...}, where keys are variables of
the model and values are biases.
J (dict[(variable, variable), bias]):
Quadratic biases as a dict of the form {(u, v): bias, ...}, where keys
are 2-tuples of variables of the model and values are quadratic biases
associated with the pair of variables (the interaction).
offset (numeric, optional, default=0):
Constant offset to be applied to the energy. Default 0.
Returns:
float: The induced energy.
Notes:
No input checking is performed.
Examples:
This example calculates the energy of a sample representing two down spins for
an Ising model of two variables that have positive biases of value 1 and
are positively coupled with an interaction of value 1.
>>> sample = {1: -1, 2: -1}
>>> h = {1: 1, 2: 1}
>>> J = {(1, 2): 1}
>>> dimod.ising_energy(sample, h, J, 0.5)
-0.5
References
----------
`Ising model on Wikipedia <https://en.wikipedia.org/wiki/Ising_model>`_
"""
# add the contribution from the linear biases
for v in h:
offset += h[v] * sample[v]
# add the contribution from the quadratic biases
for v0, v1 in J:
offset += J[(v0, v1)] * sample[v0] * sample[v1]
return offset
def qubo_energy(sample, Q, offset=0.0):
"""Calculate the energy for the specified sample of a QUBO model.
Energy of a sample for a binary quadratic model is defined as a sum, offset
by the constant energy offset associated with the model, of
the sample multipled by the linear bias of the variable and
all its interactions. For a quadratic unconstrained binary optimization (QUBO)
model,
.. math::
E(\mathbf{x}) = \sum_{u,v} Q_{u,v} x_u x_v + c
where :math:`x_v` is the sample, :math:`Q_{u,v}`
a matrix of biases, and :math:`c` the energy offset.
Args:
sample (dict[variable, spin]):
Sample for a binary quadratic model as a dict of form {v: bin, ...},
where keys are variables of the model and values are binary (either 0 or 1).
Q (dict[(variable, variable), coefficient]):
QUBO coefficients in a dict of form {(u, v): coefficient, ...}, where keys
are 2-tuples of variables of the model and values are biases
associated with the pair of variables. Tuples (u, v) represent interactions
and (v, v) linear biases.
offset (numeric, optional, default=0):
Constant offset to be applied to the energy. Default 0.
Returns:
float: The induced energy.
Notes:
No input checking is performed.
Examples:
This example calculates the energy of a sample representing two zeros for
a QUBO model of two variables that have positive biases of value 1 and
are positively coupled with an interaction of value 1.
>>> sample = {1: 0, 2: 0}
>>> Q = {(1, 1): 1, (2, 2): 1, (1, 2): 1}
>>> dimod.qubo_energy(sample, Q, 0.5)
0.5
References
----------
`QUBO model on Wikipedia <https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization>`_
"""
for v0, v1 in Q:
offset += sample[v0] * sample[v1] * Q[(v0, v1)]
return offset
def ising_to_qubo(h, J, offset=0.0):
"""Convert an Ising problem to a QUBO problem.
Map an Ising model defined on spins (variables with {-1, +1} values) to quadratic
unconstrained binary optimization (QUBO) formulation :math:`x' Q x` defined over
binary variables (0 or 1 values), where the linear term is contained along the diagonal of Q.
Return matrix Q that defines the model as well as the offset in energy between the two
problem formulations:
.. math::
s' J s + h' s = offset + x' Q x
See :meth:`~dimod.utilities.qubo_to_ising` for the inverse function.
Args:
h (dict[variable, bias]):
Linear biases as a dict of the form {v: bias, ...}, where keys are variables of
the model and values are biases.
J (dict[(variable, variable), bias]):
Quadratic biases as a dict of the form {(u, v): bias, ...}, where keys
are 2-tuples of variables of the model and values are quadratic biases
associated with the pair of variables (the interaction).
offset (numeric, optional, default=0):
Constant offset to be applied to the energy. Default 0.
Returns:
(dict, float): A 2-tuple containing:
dict: QUBO coefficients.
float: New energy offset.
Examples:
This example converts an Ising problem of two variables that have positive
biases of value 1 and are positively coupled with an interaction of value 1
to a QUBO problem and prints the resulting energy offset.
>>> h = {1: 1, 2: 1}
>>> J = {(1, 2): 1}
>>> dimod.ising_to_qubo(h, J, 0.5)[1]
-0.5
"""
# the linear biases are the easiest
q = {(v, v): 2. * bias for v, bias in h.items()}
# next the quadratic biases
for (u, v), bias in J.items():
if bias == 0.0:
continue
q[(u, v)] = 4. * bias
q[(u, u)] = q.setdefault((u, u), 0) - 2. * bias
q[(v, v)] = q.setdefault((v, v), 0) - 2. * bias
# finally calculate the offset
offset += sum(J.values()) - sum(h.values())
return q, offset
def qubo_to_ising(Q, offset=0.0):
"""Convert a QUBO problem to an Ising problem.
Map a quadratic unconstrained binary optimization (QUBO) problem :math:`x' Q x`
defined over binary variables (0 or 1 values), where the linear term is contained along
the diagonal of Q, to an Ising model defined on spins (variables with {-1, +1} values).
Return h and J that define the Ising model as well as the offset in energy
between the two problem formulations:
.. math::
x' Q x = offset + s' J s + h' s
See :meth:`~dimod.utilities.ising_to_qubo` for the inverse function.
Args:
Q (dict[(variable, variable), coefficient]):
QUBO coefficients in a dict of form {(u, v): coefficient, ...}, where keys
are 2-tuples of variables of the model and values are biases
associated with the pair of variables. Tuples (u, v) represent interactions
and (v, v) linear biases.
offset (numeric, optional, default=0):
Constant offset to be applied to the energy. Default 0.
Returns:
(dict, dict, float): A 3-tuple containing:
dict: Linear coefficients of the Ising problem.
dict: Quadratic coefficients of the Ising problem.
float: New energy offset.
Examples:
This example converts a QUBO problem of two variables that have positive
biases of value 1 and are positively coupled with an interaction of value 1
to an Ising problem, and shows the new energy offset.
>>> Q = {(1, 1): 1, (2, 2): 1, (1, 2): 1}
>>> dimod.qubo_to_ising(Q, 0.5)[2]
1.75
"""
h = {}
J = {}
linear_offset = 0.0
quadratic_offset = 0.0
for (u, v), bias in Q.items():
if u == v:
if u in h:
h[u] += .5 * bias
else:
h[u] = .5 * bias
linear_offset += bias
else:
if bias != 0.0:
J[(u, v)] = .25 * bias
if u in h:
h[u] += .25 * bias
else:
h[u] = .25 * bias
if v in h:
h[v] += .25 * bias
else:
h[v] = .25 * bias
quadratic_offset += bias
offset += .5 * linear_offset + .25 * quadratic_offset
return h, J, offset
def resolve_label_conflict(mapping, existing, old_labels=None, new_labels=None):
"""Resolve a self-labeling conflict by creating an intermediate labeling.
Args:
mapping (dict):
A dict mapping the current variable labels to new ones.
existing (set-like):
The existing labels.
old_labels (set, optional, default=None):
The keys of mapping. Can be passed in for performance reasons. These are not checked.
new_labels (set, optional, default=None):
The values of mapping. Can be passed in for performance reasons. These are not checked.
Returns:
tuple: A 2-tuple containing:
dict: A map from the keys of mapping to an intermediate labeling
dict: A map from the intermediate labeling to the values of mapping.
"""
if old_labels is None:
old_labels = set(mapping)
if new_labels is None:
new_labels = set(mapping.values())
# counter will be used to generate the intermediate labels, as an easy optimization
# we start the counter with a high number because often variables are labeled by
# integers starting from 0
counter = itertools.count(2 * len(mapping))
old_to_intermediate = {}
intermediate_to_new = {}
for old, new in mapping.items():
if old == new:
# we can remove self-labels
continue
if old in new_labels or new in old_labels:
# try to get a new unique label
lbl = next(counter)
while lbl in new_labels or lbl in old_labels or lbl in existing:
lbl = next(counter)
# add it to the mapping
old_to_intermediate[old] = lbl
intermediate_to_new[lbl] = new
else:
old_to_intermediate[old] = new
# don't need to add it to intermediate_to_new because it is a self-label
return old_to_intermediate, intermediate_to_new
def iter_safe_relabels(mapping, existing):
"""Iterator over "safe" intermediate relabelings.
Args:
mapping (dict):
A map from old labels to new.
existing (set):
A container of existing labels.
Yields:
dict: A "safe" relabelling.
"""
# put the new labels into a set for fast lookup, also ensures that the
# values are valid labels
try:
new_labels = set(mapping.values())
except TypeError:
raise ValueError("mapping targets must be hashable objects")
old_labels = mapping.keys()
for v in new_labels:
if v in existing and v not in old_labels:
msg = ("A variable cannot be relabeled {!r} without also "
"relabeling the existing variable of the same name")
raise ValueError(msg.format(v))
if any(v in new_labels for v in old_labels):
yield from resolve_label_conflict(mapping, existing, old_labels, new_labels)
else:
yield mapping
def child_structure_dfs(sampler, seen=None):
"""Return the structure of a composed sampler using a depth-first search on its
children.
Args:
sampler (:obj:`.Sampler`):
:class:`.Structured` or composed sampler with at least
one structured child.
seen (set, optional, default=False):
IDs of already checked child samplers.
Returns:
:class:`~collections.namedtuple`: A named tuple of the form
`Structure(nodelist, edgelist, adjacency)`, where the 3-tuple values
are the :attr:`.Structured.nodelist`, :attr:`.Structured.edgelist`
and :attr:`.Structured.adjacency` attributes of the first structured
sampler found.
Raises:
ValueError: If no structured sampler is found.
Examples:
>>> sampler = dimod.TrackingComposite(
... dimod.StructureComposite(
... dimod.ExactSolver(), [0, 1], [(0, 1)]))
>>> print(dimod.child_structure_dfs(sampler).nodelist)
[0, 1]
"""
seen = set() if seen is None else seen
if sampler not in seen:
try:
return sampler.structure
except AttributeError:
# hasattr just tries to access anyway...
pass
seen.add(sampler)
for child in getattr(sampler, 'children', ()): # getattr handles samplers
if child in seen:
continue
try:
return child_structure_dfs(child, seen=seen)
except ValueError:
# tree has no child samplers
pass
raise ValueError("no structured sampler found")
def get_include():
"""Return the directory with dimod's header files."""
return os.path.join(os.path.dirname(__file__), 'include')
def _astypearrays(arrays, requirements, min_itemsize, allowed_types):
# allowed types can only be numeric for now, see comment below
# todo: allow unsafe with warning controlled by kwarg?
# We need to get the dtype, and as far as I can tell the only way to do
# it for array-like is to actually cast to a numpy array
arrays = [np.asarray(arr) for arr in arrays]
# get the dtype we can promote to
dtype = reduce(np.promote_types, (arr.dtype for arr in arrays))
if not any(np.issubdtype(dtype, type_) for type_ in allowed_types):
# put together an appropriate error message
descriptors = []
if np.floating in allowed_types:
descriptors.append('floating')
if np.integer in allowed_types:
descriptors.append('integer')
elif np.unsignedinteger in allowed_types:
if np.signedinteger in allowed_types:
descriptors.append('integer')
else:
descriptors.append('unsigned integer')
elif np.signedinteger in allowed_types:
descriptors.append('signed integer')
raise TypeError(
"Cannot safely cast arrays to {} (given {})".format(
', '.join(descriptors),
', '.join(arr.dtype.name for arr in arrays)))
if min_itemsize is not None:
if min_itemsize >= 1:
size = str(2**int(np.ceil(np.log2(min_itemsize))))
else:
size = '1'
if np.issubdtype(dtype, np.unsignedinteger):
kind = 'u'
elif np.issubdtype(dtype, np.signedinteger):
kind = 'i'
elif np.issubdtype(dtype, np.floating):
kind = 'f'
else:
# we could instead read this from the type string, but it's kind of
# pandora's box, because there's also structured arrays, complex,
# etc. For now, let's just restrict to numeric.
raise RuntimeError("unexpected dtype")
dtype = np.promote_types(dtype, kind+size)
arrays = tuple(np.require(arr, dtype=dtype, requirements=requirements)
for arr in arrays)
if len(arrays) > 1:
return arrays
else:
return arrays[0]
# Not a public function (yet)
def asintegerarrays(*arrays, requirements=None, min_itemsize=None):
"""Cast the given array(s) to the same integer type.
Not a public function.
This is useful when calling cython functions.
Args:
*arrays (array-like): At least one array-like.
requirements (str/list[str], optional): See :func:`numpy.require`.
min_itemsize (int, optional):
The minimum itemsize (in bytes) for the output arrays.
Returns:
Numpy array(s) satisfying the above requirements. They will all have
the same dtype.
"""
# empty arrays are a problem because numy defaults them to float, so let's
# do a tiny bit of prechecking
arrays = [arr if len(arr) else np.asarray(arr, dtype=np.int8)
for arr in arrays]
if not arrays:
raise TypeError('asintegerarrays() takes at least 1 array (0 given)')
return _astypearrays(arrays, requirements, min_itemsize, [np.integer])
# Not a public function (yet)
def asnumericarrays(*arrays, requirements=None, min_itemsize=None):
"""Cast the given array(s) to the same floating type.
Not a public function.
This is useful when calling cython functions.
Args:
*arrays (array-like): At least one array-like.
requirements (str/list[str], optional): See :func:`numpy.require`.
min_itemsize (int, optional):
The minimum itemsize (in bytes) for the output arrays.
Returns:
Numpy array(s) satisfying the above requirements. They will all have
the same dtype.
"""
if not arrays:
raise TypeError('asnumericarrays() takes at least 1 array (0 given)')
return _astypearrays(arrays, requirements, min_itemsize,
[np.integer, np.floating])
| 32.824156 | 106 | 0.613582 |
import copy
import os
import itertools
from functools import reduce
import numpy as np
__all__ = ['ising_energy',
'qubo_energy',
'ising_to_qubo',
'qubo_to_ising',
'child_structure_dfs',
'get_include',
]
def ising_energy(sample, h, J, offset=0.0):
for v in h:
offset += h[v] * sample[v]
for v0, v1 in J:
offset += J[(v0, v1)] * sample[v0] * sample[v1]
return offset
def qubo_energy(sample, Q, offset=0.0):
for v0, v1 in Q:
offset += sample[v0] * sample[v1] * Q[(v0, v1)]
return offset
def ising_to_qubo(h, J, offset=0.0):
q = {(v, v): 2. * bias for v, bias in h.items()}
for (u, v), bias in J.items():
if bias == 0.0:
continue
q[(u, v)] = 4. * bias
q[(u, u)] = q.setdefault((u, u), 0) - 2. * bias
q[(v, v)] = q.setdefault((v, v), 0) - 2. * bias
offset += sum(J.values()) - sum(h.values())
return q, offset
def qubo_to_ising(Q, offset=0.0):
h = {}
J = {}
linear_offset = 0.0
quadratic_offset = 0.0
for (u, v), bias in Q.items():
if u == v:
if u in h:
h[u] += .5 * bias
else:
h[u] = .5 * bias
linear_offset += bias
else:
if bias != 0.0:
J[(u, v)] = .25 * bias
if u in h:
h[u] += .25 * bias
else:
h[u] = .25 * bias
if v in h:
h[v] += .25 * bias
else:
h[v] = .25 * bias
quadratic_offset += bias
offset += .5 * linear_offset + .25 * quadratic_offset
return h, J, offset
def resolve_label_conflict(mapping, existing, old_labels=None, new_labels=None):
if old_labels is None:
old_labels = set(mapping)
if new_labels is None:
new_labels = set(mapping.values())
counter = itertools.count(2 * len(mapping))
old_to_intermediate = {}
intermediate_to_new = {}
for old, new in mapping.items():
if old == new:
continue
if old in new_labels or new in old_labels:
lbl = next(counter)
while lbl in new_labels or lbl in old_labels or lbl in existing:
lbl = next(counter)
old_to_intermediate[old] = lbl
intermediate_to_new[lbl] = new
else:
old_to_intermediate[old] = new
return old_to_intermediate, intermediate_to_new
def iter_safe_relabels(mapping, existing):
# put the new labels into a set for fast lookup, also ensures that the
# values are valid labels
try:
new_labels = set(mapping.values())
except TypeError:
raise ValueError("mapping targets must be hashable objects")
old_labels = mapping.keys()
for v in new_labels:
if v in existing and v not in old_labels:
msg = ("A variable cannot be relabeled {!r} without also "
"relabeling the existing variable of the same name")
raise ValueError(msg.format(v))
if any(v in new_labels for v in old_labels):
yield from resolve_label_conflict(mapping, existing, old_labels, new_labels)
else:
yield mapping
def child_structure_dfs(sampler, seen=None):
seen = set() if seen is None else seen
if sampler not in seen:
try:
return sampler.structure
except AttributeError:
# hasattr just tries to access anyway...
pass
seen.add(sampler)
for child in getattr(sampler, 'children', ()): # getattr handles samplers
if child in seen:
continue
try:
return child_structure_dfs(child, seen=seen)
except ValueError:
# tree has no child samplers
pass
raise ValueError("no structured sampler found")
def get_include():
return os.path.join(os.path.dirname(__file__), 'include')
def _astypearrays(arrays, requirements, min_itemsize, allowed_types):
# allowed types can only be numeric for now, see comment below
# todo: allow unsafe with warning controlled by kwarg?
# We need to get the dtype, and as far as I can tell the only way to do
# it for array-like is to actually cast to a numpy array
arrays = [np.asarray(arr) for arr in arrays]
# get the dtype we can promote to
dtype = reduce(np.promote_types, (arr.dtype for arr in arrays))
if not any(np.issubdtype(dtype, type_) for type_ in allowed_types):
# put together an appropriate error message
descriptors = []
if np.floating in allowed_types:
descriptors.append('floating')
if np.integer in allowed_types:
descriptors.append('integer')
elif np.unsignedinteger in allowed_types:
if np.signedinteger in allowed_types:
descriptors.append('integer')
else:
descriptors.append('unsigned integer')
elif np.signedinteger in allowed_types:
descriptors.append('signed integer')
raise TypeError(
"Cannot safely cast arrays to {} (given {})".format(
', '.join(descriptors),
', '.join(arr.dtype.name for arr in arrays)))
if min_itemsize is not None:
if min_itemsize >= 1:
size = str(2**int(np.ceil(np.log2(min_itemsize))))
else:
size = '1'
if np.issubdtype(dtype, np.unsignedinteger):
kind = 'u'
elif np.issubdtype(dtype, np.signedinteger):
kind = 'i'
elif np.issubdtype(dtype, np.floating):
kind = 'f'
else:
# we could instead read this from the type string, but it's kind of
raise RuntimeError("unexpected dtype")
dtype = np.promote_types(dtype, kind+size)
arrays = tuple(np.require(arr, dtype=dtype, requirements=requirements)
for arr in arrays)
if len(arrays) > 1:
return arrays
else:
return arrays[0]
# Not a public function (yet)
def asintegerarrays(*arrays, requirements=None, min_itemsize=None):
# empty arrays are a problem because numy defaults them to float, so let's
arrays = [arr if len(arr) else np.asarray(arr, dtype=np.int8)
for arr in arrays]
if not arrays:
raise TypeError('asintegerarrays() takes at least 1 array (0 given)')
return _astypearrays(arrays, requirements, min_itemsize, [np.integer])
def asnumericarrays(*arrays, requirements=None, min_itemsize=None):
if not arrays:
raise TypeError('asnumericarrays() takes at least 1 array (0 given)')
return _astypearrays(arrays, requirements, min_itemsize,
[np.integer, np.floating])
| true | true |
1c2e52715e112ad281fe0514e66107bb8805dd44 | 6,571 | py | Python | third_party/a2c_ppo_acktr/algo/ppo.py | jyf588/SimGAN | 23283d7b5629f1653567b2437bb28aac1cc17169 | [
"Apache-2.0"
] | 30 | 2021-06-16T23:28:58.000Z | 2022-03-23T17:20:58.000Z | third_party/a2c_ppo_acktr/algo/ppo.py | jyf588/SimGAN | 23283d7b5629f1653567b2437bb28aac1cc17169 | [
"Apache-2.0"
] | 1 | 2021-06-25T09:21:29.000Z | 2021-08-11T23:14:14.000Z | third_party/a2c_ppo_acktr/algo/ppo.py | jyf588/SimGAN | 23283d7b5629f1653567b2437bb28aac1cc17169 | [
"Apache-2.0"
] | 8 | 2021-06-19T12:51:50.000Z | 2021-12-23T08:31:10.000Z | # MIT License
#
# Copyright (c) 2017 Ilya Kostrikov
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import torch
import torch.nn as nn
import torch.optim as optim
from my_pybullet_envs.utils import mirror_obsact_batch
class PPO():
def __init__(self,
actor_critic,
clip_param,
ppo_epoch,
num_mini_batch,
value_loss_coef,
entropy_coef,
symmetry_coef=0,
lr=None,
eps=None,
max_grad_norm=None,
use_clipped_value_loss=True,
mirror_obs=None,
mirror_act=None):
self.actor_critic = actor_critic
self.clip_param = clip_param
self.ppo_epoch = ppo_epoch
self.num_mini_batch = num_mini_batch
self.value_loss_coef = value_loss_coef
self.entropy_coef = entropy_coef
self.max_grad_norm = max_grad_norm
self.use_clipped_value_loss = use_clipped_value_loss
self.optimizer = optim.Adam(actor_critic.parameters(), lr=lr, eps=eps)
self.symmetry_coef = symmetry_coef
self.mirror_obs = mirror_obs
self.mirror_act = mirror_act
self.is_cuda = next(actor_critic.parameters()).is_cuda
def update(self, rollouts):
advantages = rollouts.returns[:-1] - rollouts.value_preds[:-1]
advantages = (advantages - advantages.mean()) / (
advantages.std() + 1e-5)
value_loss_epoch = 0
action_loss_epoch = 0
dist_entropy_epoch = 0
for e in range(self.ppo_epoch):
if self.actor_critic.is_recurrent:
data_generator = rollouts.recurrent_generator(
advantages, self.num_mini_batch)
else:
data_generator = rollouts.feed_forward_generator(
advantages, self.num_mini_batch)
for sample in data_generator:
obs_batch, recurrent_hidden_states_batch, actions_batch, \
value_preds_batch, return_batch, masks_batch, old_action_log_probs_batch, \
adv_targ, *_ = sample
# Reshape to do in a single forward pass for all steps
values, action_log_probs, dist_entropy, _ = self.actor_critic.evaluate_actions(
obs_batch, recurrent_hidden_states_batch, masks_batch,
actions_batch)
ratio = torch.exp(action_log_probs -
old_action_log_probs_batch)
surr1 = ratio * adv_targ
surr2 = torch.clamp(ratio, 1.0 - self.clip_param,
1.0 + self.clip_param) * adv_targ
action_loss = -torch.min(surr1, surr2).mean()
if self.use_clipped_value_loss:
value_pred_clipped = value_preds_batch + \
(values - value_preds_batch).clamp(-self.clip_param, self.clip_param)
value_losses = (values - return_batch).pow(2)
value_losses_clipped = (
value_pred_clipped - return_batch).pow(2)
value_loss = 0.5 * torch.max(value_losses,
value_losses_clipped).mean()
else:
value_loss = 0.5 * (return_batch - values).pow(2).mean()
# https://github.com/UBCMOCCA/SymmetricRL/blob/master/algorithms/ppo.py#L86
if self.mirror_obs and self.symmetry_coef > 0:
act_mean = self.actor_critic.act(
obs_batch,
recurrent_hidden_states_batch,
masks_batch,
deterministic=True,
)[1]
# pi - Ma(pi(Ms))
# <=> Ma(pi) - pi(Ms)
mirror_act_mean = mirror_obsact_batch(act_mean, self.is_cuda,
self.mirror_act, augment=False)
mirror_obs_batch = mirror_obsact_batch(obs_batch, self.is_cuda,
self.mirror_obs, augment=False)
act_mirror_mean = self.actor_critic.act(
mirror_obs_batch,
recurrent_hidden_states_batch,
masks_batch,
deterministic=True
)[1]
symmetry_loss = (mirror_act_mean - act_mirror_mean).pow(2).mean()
else:
symmetry_loss = 0
self.optimizer.zero_grad()
(value_loss * self.value_loss_coef
+ action_loss
- dist_entropy * self.entropy_coef
+ symmetry_loss * self.symmetry_coef).backward()
nn.utils.clip_grad_norm_(self.actor_critic.parameters(),
self.max_grad_norm)
self.optimizer.step()
value_loss_epoch += value_loss.item()
action_loss_epoch += action_loss.item()
dist_entropy_epoch += dist_entropy.item()
num_updates = self.ppo_epoch * self.num_mini_batch
value_loss_epoch /= num_updates
action_loss_epoch /= num_updates
dist_entropy_epoch /= num_updates
return value_loss_epoch, action_loss_epoch, dist_entropy_epoch
| 41.588608 | 110 | 0.575559 |
import torch
import torch.nn as nn
import torch.optim as optim
from my_pybullet_envs.utils import mirror_obsact_batch
class PPO():
def __init__(self,
actor_critic,
clip_param,
ppo_epoch,
num_mini_batch,
value_loss_coef,
entropy_coef,
symmetry_coef=0,
lr=None,
eps=None,
max_grad_norm=None,
use_clipped_value_loss=True,
mirror_obs=None,
mirror_act=None):
self.actor_critic = actor_critic
self.clip_param = clip_param
self.ppo_epoch = ppo_epoch
self.num_mini_batch = num_mini_batch
self.value_loss_coef = value_loss_coef
self.entropy_coef = entropy_coef
self.max_grad_norm = max_grad_norm
self.use_clipped_value_loss = use_clipped_value_loss
self.optimizer = optim.Adam(actor_critic.parameters(), lr=lr, eps=eps)
self.symmetry_coef = symmetry_coef
self.mirror_obs = mirror_obs
self.mirror_act = mirror_act
self.is_cuda = next(actor_critic.parameters()).is_cuda
def update(self, rollouts):
advantages = rollouts.returns[:-1] - rollouts.value_preds[:-1]
advantages = (advantages - advantages.mean()) / (
advantages.std() + 1e-5)
value_loss_epoch = 0
action_loss_epoch = 0
dist_entropy_epoch = 0
for e in range(self.ppo_epoch):
if self.actor_critic.is_recurrent:
data_generator = rollouts.recurrent_generator(
advantages, self.num_mini_batch)
else:
data_generator = rollouts.feed_forward_generator(
advantages, self.num_mini_batch)
for sample in data_generator:
obs_batch, recurrent_hidden_states_batch, actions_batch, \
value_preds_batch, return_batch, masks_batch, old_action_log_probs_batch, \
adv_targ, *_ = sample
values, action_log_probs, dist_entropy, _ = self.actor_critic.evaluate_actions(
obs_batch, recurrent_hidden_states_batch, masks_batch,
actions_batch)
ratio = torch.exp(action_log_probs -
old_action_log_probs_batch)
surr1 = ratio * adv_targ
surr2 = torch.clamp(ratio, 1.0 - self.clip_param,
1.0 + self.clip_param) * adv_targ
action_loss = -torch.min(surr1, surr2).mean()
if self.use_clipped_value_loss:
value_pred_clipped = value_preds_batch + \
(values - value_preds_batch).clamp(-self.clip_param, self.clip_param)
value_losses = (values - return_batch).pow(2)
value_losses_clipped = (
value_pred_clipped - return_batch).pow(2)
value_loss = 0.5 * torch.max(value_losses,
value_losses_clipped).mean()
else:
value_loss = 0.5 * (return_batch - values).pow(2).mean()
if self.mirror_obs and self.symmetry_coef > 0:
act_mean = self.actor_critic.act(
obs_batch,
recurrent_hidden_states_batch,
masks_batch,
deterministic=True,
)[1]
mirror_act_mean = mirror_obsact_batch(act_mean, self.is_cuda,
self.mirror_act, augment=False)
mirror_obs_batch = mirror_obsact_batch(obs_batch, self.is_cuda,
self.mirror_obs, augment=False)
act_mirror_mean = self.actor_critic.act(
mirror_obs_batch,
recurrent_hidden_states_batch,
masks_batch,
deterministic=True
)[1]
symmetry_loss = (mirror_act_mean - act_mirror_mean).pow(2).mean()
else:
symmetry_loss = 0
self.optimizer.zero_grad()
(value_loss * self.value_loss_coef
+ action_loss
- dist_entropy * self.entropy_coef
+ symmetry_loss * self.symmetry_coef).backward()
nn.utils.clip_grad_norm_(self.actor_critic.parameters(),
self.max_grad_norm)
self.optimizer.step()
value_loss_epoch += value_loss.item()
action_loss_epoch += action_loss.item()
dist_entropy_epoch += dist_entropy.item()
num_updates = self.ppo_epoch * self.num_mini_batch
value_loss_epoch /= num_updates
action_loss_epoch /= num_updates
dist_entropy_epoch /= num_updates
return value_loss_epoch, action_loss_epoch, dist_entropy_epoch
| true | true |
1c2e52deeec86ee00757fa67e77d28c322c9ffd1 | 3,829 | py | Python | scripts/simulate.py | kblondal/RMG-Py | ee14e35321c1dc3cd1900c6d2ebb27931d1bb542 | [
"MIT"
] | 1 | 2020-03-17T13:16:51.000Z | 2020-03-17T13:16:51.000Z | scripts/simulate.py | kblondal/RMG-Py | ee14e35321c1dc3cd1900c6d2ebb27931d1bb542 | [
"MIT"
] | null | null | null | scripts/simulate.py | kblondal/RMG-Py | ee14e35321c1dc3cd1900c6d2ebb27931d1bb542 | [
"MIT"
] | 1 | 2018-10-03T19:36:40.000Z | 2018-10-03T19:36:40.000Z | #!/usr/bin/env python3
###############################################################################
# #
# RMG - Reaction Mechanism Generator #
# #
# Copyright (c) 2002-2019 Prof. William H. Green (whgreen@mit.edu), #
# Prof. Richard H. West (r.west@neu.edu) and the RMG Team (rmg_dev@mit.edu) #
# #
# 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. #
# #
###############################################################################
"""
This script runs a stand-alone simulation (including sensitivity analysis if
specified in the input file) on an RMG job.
"""
import argparse
import os.path
from rmgpy.tools.simulate import run_simulation
################################################################################
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('input', metavar='INPUT', type=str, nargs=1,
help='RMG input file')
parser.add_argument('chemkin', metavar='CHEMKIN', type=str, nargs=1,
help='Chemkin file')
parser.add_argument('dictionary', metavar='DICTIONARY', type=str, nargs=1,
help='RMG dictionary file')
parser.add_argument('--no-dlim', dest='dlim', action='store_false',
help='Turn off diffusion-limited rates for LiquidReactor')
parser.add_argument('-f', '--foreign', dest='checkDuplicates', action='store_true',
help='Not an RMG generated Chemkin file (will be checked for duplicates)')
args = parser.parse_args()
input_file = os.path.abspath(args.input[0])
chemkin_file = os.path.abspath(args.chemkin[0])
dict_file = os.path.abspath(args.dictionary[0])
dflag = args.dlim
check_duplicates = args.checkDuplicates
return input_file, chemkin_file, dict_file, dflag, check_duplicates
def main():
input_file, chemkin_file, dict_file, dflag, check_duplicates = parse_arguments()
run_simulation(input_file, chemkin_file, dict_file, diffusion_limited=dflag, check_duplicates=check_duplicates)
################################################################################
if __name__ == '__main__':
main()
| 50.381579 | 115 | 0.532254 | true | true | |
1c2e5356a51e4433e91dfeaa4e7b0fc62446dccd | 400 | py | Python | projeto_cliente/cliente/migrations/0003_auto_20210615_2006.py | LeandroMelloo/curso_completo_api_rest_django_framework | c56771a2103ac755e68984b2b1b78f591c1d4b5a | [
"Apache-2.0"
] | null | null | null | projeto_cliente/cliente/migrations/0003_auto_20210615_2006.py | LeandroMelloo/curso_completo_api_rest_django_framework | c56771a2103ac755e68984b2b1b78f591c1d4b5a | [
"Apache-2.0"
] | null | null | null | projeto_cliente/cliente/migrations/0003_auto_20210615_2006.py | LeandroMelloo/curso_completo_api_rest_django_framework | c56771a2103ac755e68984b2b1b78f591c1d4b5a | [
"Apache-2.0"
] | null | null | null | # Generated by Django 3.0.8 on 2021-06-15 23:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cliente', '0002_auto_20210615_1759'),
]
operations = [
migrations.AlterField(
model_name='cliente',
name='email',
field=models.EmailField(max_length=30, unique=True),
),
]
| 21.052632 | 64 | 0.605 |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cliente', '0002_auto_20210615_1759'),
]
operations = [
migrations.AlterField(
model_name='cliente',
name='email',
field=models.EmailField(max_length=30, unique=True),
),
]
| true | true |
1c2e53c1762cf1429f24b1c0b740c323994335fd | 342 | py | Python | backend/models/profiles.py | jimbunny/AdminSystem | d9a42e2d8608cb0d9bc88f4c1945da48fb8cc925 | [
"MIT"
] | null | null | null | backend/models/profiles.py | jimbunny/AdminSystem | d9a42e2d8608cb0d9bc88f4c1945da48fb8cc925 | [
"MIT"
] | null | null | null | backend/models/profiles.py | jimbunny/AdminSystem | d9a42e2d8608cb0d9bc88f4c1945da48fb8cc925 | [
"MIT"
] | 1 | 2021-09-20T10:53:40.000Z | 2021-09-20T10:53:40.000Z | #!/usr/bin/env python
#-*- coding:utf-8 -*-
# author:jingtongyu
# datetime:2020/6/7 10:14 下午
# software: PyCharm
from . import db
from .base import BaseModel
class ProfilesModel(db.Model, BaseModel):
"""
示例模型类
"""
__tablename__ = 'profiles'
nickname = db.Column(db.String(32))
signature = db.Column(db.String(32))
| 18 | 41 | 0.654971 |
from . import db
from .base import BaseModel
class ProfilesModel(db.Model, BaseModel):
__tablename__ = 'profiles'
nickname = db.Column(db.String(32))
signature = db.Column(db.String(32))
| true | true |
1c2e54a1a5dfb8670a48456dadbf819fd0df054a | 4,909 | py | Python | tests/components/homematicip_cloud/test_config_flow.py | dauden1184/home-assistant | f4c6d389b77d0efa86644e76604eaea5d21abdb5 | [
"Apache-2.0"
] | 7 | 2018-08-03T10:15:36.000Z | 2019-03-25T13:31:55.000Z | tests/components/homematicip_cloud/test_config_flow.py | dauden1184/home-assistant | f4c6d389b77d0efa86644e76604eaea5d21abdb5 | [
"Apache-2.0"
] | 6 | 2021-02-08T20:25:50.000Z | 2022-03-11T23:27:53.000Z | tests/components/homematicip_cloud/test_config_flow.py | dauden1184/home-assistant | f4c6d389b77d0efa86644e76604eaea5d21abdb5 | [
"Apache-2.0"
] | 3 | 2018-09-14T07:34:09.000Z | 2018-09-29T12:57:10.000Z | """Tests for HomematicIP Cloud config flow."""
from unittest.mock import patch
from homeassistant.components.homematicip_cloud import hap as hmipc
from homeassistant.components.homematicip_cloud import config_flow, const
from tests.common import MockConfigEntry, mock_coro
async def test_flow_works(hass):
"""Test config flow works."""
config = {
const.HMIPC_HAPID: 'ABC123',
const.HMIPC_PIN: '123',
const.HMIPC_NAME: 'hmip',
}
flow = config_flow.HomematicipCloudFlowHandler()
flow.hass = hass
hap = hmipc.HomematicipAuth(hass, config)
with patch.object(hap, 'get_auth', return_value=mock_coro()), \
patch.object(hmipc.HomematicipAuth, 'async_checkbutton',
return_value=mock_coro(True)), \
patch.object(hmipc.HomematicipAuth, 'async_register',
return_value=mock_coro(True)):
hap.authtoken = 'ABC'
result = await flow.async_step_init(user_input=config)
assert hap.authtoken == 'ABC'
assert result['type'] == 'create_entry'
async def test_flow_init_connection_error(hass):
"""Test config flow with accesspoint connection error."""
config = {
const.HMIPC_HAPID: 'ABC123',
const.HMIPC_PIN: '123',
const.HMIPC_NAME: 'hmip',
}
flow = config_flow.HomematicipCloudFlowHandler()
flow.hass = hass
with patch.object(hmipc.HomematicipAuth, 'async_setup',
return_value=mock_coro(False)):
result = await flow.async_step_init(user_input=config)
assert result['type'] == 'form'
async def test_flow_link_connection_error(hass):
"""Test config flow client registration connection error."""
config = {
const.HMIPC_HAPID: 'ABC123',
const.HMIPC_PIN: '123',
const.HMIPC_NAME: 'hmip',
}
flow = config_flow.HomematicipCloudFlowHandler()
flow.hass = hass
with patch.object(hmipc.HomematicipAuth, 'async_setup',
return_value=mock_coro(True)), \
patch.object(hmipc.HomematicipAuth, 'async_checkbutton',
return_value=mock_coro(True)), \
patch.object(hmipc.HomematicipAuth, 'async_register',
return_value=mock_coro(False)):
result = await flow.async_step_init(user_input=config)
assert result['type'] == 'abort'
async def test_flow_link_press_button(hass):
"""Test config flow ask for pressing the blue button."""
config = {
const.HMIPC_HAPID: 'ABC123',
const.HMIPC_PIN: '123',
const.HMIPC_NAME: 'hmip',
}
flow = config_flow.HomematicipCloudFlowHandler()
flow.hass = hass
with patch.object(hmipc.HomematicipAuth, 'async_setup',
return_value=mock_coro(True)), \
patch.object(hmipc.HomematicipAuth, 'async_checkbutton',
return_value=mock_coro(False)):
result = await flow.async_step_init(user_input=config)
assert result['type'] == 'form'
assert result['errors'] == {'base': 'press_the_button'}
async def test_init_flow_show_form(hass):
"""Test config flow shows up with a form."""
flow = config_flow.HomematicipCloudFlowHandler()
flow.hass = hass
result = await flow.async_step_init(user_input=None)
assert result['type'] == 'form'
async def test_init_already_configured(hass):
"""Test accesspoint is already configured."""
MockConfigEntry(domain=const.DOMAIN, data={
const.HMIPC_HAPID: 'ABC123',
}).add_to_hass(hass)
config = {
const.HMIPC_HAPID: 'ABC123',
const.HMIPC_PIN: '123',
const.HMIPC_NAME: 'hmip',
}
flow = config_flow.HomematicipCloudFlowHandler()
flow.hass = hass
result = await flow.async_step_init(user_input=config)
assert result['type'] == 'abort'
async def test_import_config(hass):
"""Test importing a host with an existing config file."""
flow = config_flow.HomematicipCloudFlowHandler()
flow.hass = hass
result = await flow.async_step_import({
hmipc.HMIPC_HAPID: 'ABC123',
hmipc.HMIPC_AUTHTOKEN: '123',
hmipc.HMIPC_NAME: 'hmip'
})
assert result['type'] == 'create_entry'
assert result['title'] == 'ABC123'
assert result['data'] == {
hmipc.HMIPC_HAPID: 'ABC123',
hmipc.HMIPC_AUTHTOKEN: '123',
hmipc.HMIPC_NAME: 'hmip'
}
async def test_import_existing_config(hass):
"""Test abort of an existing accesspoint from config."""
flow = config_flow.HomematicipCloudFlowHandler()
flow.hass = hass
MockConfigEntry(domain=const.DOMAIN, data={
hmipc.HMIPC_HAPID: 'ABC123',
}).add_to_hass(hass)
result = await flow.async_step_import({
hmipc.HMIPC_HAPID: 'ABC123',
hmipc.HMIPC_AUTHTOKEN: '123',
hmipc.HMIPC_NAME: 'hmip'
})
assert result['type'] == 'abort'
| 32.509934 | 73 | 0.652475 | from unittest.mock import patch
from homeassistant.components.homematicip_cloud import hap as hmipc
from homeassistant.components.homematicip_cloud import config_flow, const
from tests.common import MockConfigEntry, mock_coro
async def test_flow_works(hass):
config = {
const.HMIPC_HAPID: 'ABC123',
const.HMIPC_PIN: '123',
const.HMIPC_NAME: 'hmip',
}
flow = config_flow.HomematicipCloudFlowHandler()
flow.hass = hass
hap = hmipc.HomematicipAuth(hass, config)
with patch.object(hap, 'get_auth', return_value=mock_coro()), \
patch.object(hmipc.HomematicipAuth, 'async_checkbutton',
return_value=mock_coro(True)), \
patch.object(hmipc.HomematicipAuth, 'async_register',
return_value=mock_coro(True)):
hap.authtoken = 'ABC'
result = await flow.async_step_init(user_input=config)
assert hap.authtoken == 'ABC'
assert result['type'] == 'create_entry'
async def test_flow_init_connection_error(hass):
config = {
const.HMIPC_HAPID: 'ABC123',
const.HMIPC_PIN: '123',
const.HMIPC_NAME: 'hmip',
}
flow = config_flow.HomematicipCloudFlowHandler()
flow.hass = hass
with patch.object(hmipc.HomematicipAuth, 'async_setup',
return_value=mock_coro(False)):
result = await flow.async_step_init(user_input=config)
assert result['type'] == 'form'
async def test_flow_link_connection_error(hass):
config = {
const.HMIPC_HAPID: 'ABC123',
const.HMIPC_PIN: '123',
const.HMIPC_NAME: 'hmip',
}
flow = config_flow.HomematicipCloudFlowHandler()
flow.hass = hass
with patch.object(hmipc.HomematicipAuth, 'async_setup',
return_value=mock_coro(True)), \
patch.object(hmipc.HomematicipAuth, 'async_checkbutton',
return_value=mock_coro(True)), \
patch.object(hmipc.HomematicipAuth, 'async_register',
return_value=mock_coro(False)):
result = await flow.async_step_init(user_input=config)
assert result['type'] == 'abort'
async def test_flow_link_press_button(hass):
config = {
const.HMIPC_HAPID: 'ABC123',
const.HMIPC_PIN: '123',
const.HMIPC_NAME: 'hmip',
}
flow = config_flow.HomematicipCloudFlowHandler()
flow.hass = hass
with patch.object(hmipc.HomematicipAuth, 'async_setup',
return_value=mock_coro(True)), \
patch.object(hmipc.HomematicipAuth, 'async_checkbutton',
return_value=mock_coro(False)):
result = await flow.async_step_init(user_input=config)
assert result['type'] == 'form'
assert result['errors'] == {'base': 'press_the_button'}
async def test_init_flow_show_form(hass):
flow = config_flow.HomematicipCloudFlowHandler()
flow.hass = hass
result = await flow.async_step_init(user_input=None)
assert result['type'] == 'form'
async def test_init_already_configured(hass):
MockConfigEntry(domain=const.DOMAIN, data={
const.HMIPC_HAPID: 'ABC123',
}).add_to_hass(hass)
config = {
const.HMIPC_HAPID: 'ABC123',
const.HMIPC_PIN: '123',
const.HMIPC_NAME: 'hmip',
}
flow = config_flow.HomematicipCloudFlowHandler()
flow.hass = hass
result = await flow.async_step_init(user_input=config)
assert result['type'] == 'abort'
async def test_import_config(hass):
flow = config_flow.HomematicipCloudFlowHandler()
flow.hass = hass
result = await flow.async_step_import({
hmipc.HMIPC_HAPID: 'ABC123',
hmipc.HMIPC_AUTHTOKEN: '123',
hmipc.HMIPC_NAME: 'hmip'
})
assert result['type'] == 'create_entry'
assert result['title'] == 'ABC123'
assert result['data'] == {
hmipc.HMIPC_HAPID: 'ABC123',
hmipc.HMIPC_AUTHTOKEN: '123',
hmipc.HMIPC_NAME: 'hmip'
}
async def test_import_existing_config(hass):
flow = config_flow.HomematicipCloudFlowHandler()
flow.hass = hass
MockConfigEntry(domain=const.DOMAIN, data={
hmipc.HMIPC_HAPID: 'ABC123',
}).add_to_hass(hass)
result = await flow.async_step_import({
hmipc.HMIPC_HAPID: 'ABC123',
hmipc.HMIPC_AUTHTOKEN: '123',
hmipc.HMIPC_NAME: 'hmip'
})
assert result['type'] == 'abort'
| true | true |
1c2e563df760ccb6ee133e043950867149d7c623 | 335 | py | Python | NyaaPy/__init__.py | jennisu/NyaaPy | 98bdda06c9e104da93ba4882b54eae22864a3844 | [
"MIT"
] | null | null | null | NyaaPy/__init__.py | jennisu/NyaaPy | 98bdda06c9e104da93ba4882b54eae22864a3844 | [
"MIT"
] | null | null | null | NyaaPy/__init__.py | jennisu/NyaaPy | 98bdda06c9e104da93ba4882b54eae22864a3844 | [
"MIT"
] | null | null | null | # Info about the module
__version__ = '0.6.0'
__author__ = 'Juanjo Salvador'
__email__ = 'juanjosalvador@netc.eu'
__url__ = 'http://juanjosalvador.me'
__copyright__ = '2017 Juanjo Salvador'
__license__ = 'MIT license'
from NyaaPy.nyaa import Nyaa
from NyaaPy.pantsu import Pantsu
from NyaaPy.sukebei import SukebeiNyaa, SukebeiPantsu
| 27.916667 | 53 | 0.785075 |
__version__ = '0.6.0'
__author__ = 'Juanjo Salvador'
__email__ = 'juanjosalvador@netc.eu'
__url__ = 'http://juanjosalvador.me'
__copyright__ = '2017 Juanjo Salvador'
__license__ = 'MIT license'
from NyaaPy.nyaa import Nyaa
from NyaaPy.pantsu import Pantsu
from NyaaPy.sukebei import SukebeiNyaa, SukebeiPantsu
| true | true |
1c2e57e31ee9856cdbed3b2440d6bec2260be61a | 42,956 | py | Python | zerver/tests/test_home.py | rohanj-02/zulip | fc0488fdb1b83bffea4a300656d7bb7f5e6ab581 | [
"Apache-2.0"
] | null | null | null | zerver/tests/test_home.py | rohanj-02/zulip | fc0488fdb1b83bffea4a300656d7bb7f5e6ab581 | [
"Apache-2.0"
] | null | null | null | zerver/tests/test_home.py | rohanj-02/zulip | fc0488fdb1b83bffea4a300656d7bb7f5e6ab581 | [
"Apache-2.0"
] | null | null | null | import calendar
import urllib
from datetime import timedelta
from typing import Any
from unittest.mock import patch
import orjson
from django.conf import settings
from django.http import HttpResponse
from django.utils.timezone import now as timezone_now
from corporate.models import Customer, CustomerPlan
from zerver.lib.actions import do_change_logo_source, do_create_user
from zerver.lib.events import add_realm_logo_fields
from zerver.lib.home import get_furthest_read_time
from zerver.lib.soft_deactivation import do_soft_deactivate_users
from zerver.lib.test_classes import ZulipTestCase
from zerver.lib.test_helpers import get_user_messages, queries_captured
from zerver.lib.users import compute_show_invites_and_add_streams
from zerver.models import (
DefaultStream,
Realm,
UserActivity,
UserProfile,
flush_per_request_caches,
get_realm,
get_stream,
get_system_bot,
get_user,
)
from zerver.views.home import compute_navbar_logo_url
from zerver.worker.queue_processors import UserActivityWorker
logger_string = "zulip.soft_deactivation"
class HomeTest(ZulipTestCase):
# Keep this list sorted!!!
expected_page_params_keys = [
"alert_words",
"available_notification_sounds",
"avatar_source",
"avatar_url",
"avatar_url_medium",
"bot_types",
"can_create_streams",
"can_subscribe_other_users",
"color_scheme",
"cross_realm_bots",
"custom_profile_field_types",
"custom_profile_fields",
"debug_mode",
"default_language",
"default_language_name",
"delivery_email",
"demote_inactive_streams",
"dense_mode",
"desktop_icon_count_display",
"development_environment",
"email",
"emojiset",
"emojiset_choices",
"enable_desktop_notifications",
"enable_digest_emails",
"enable_login_emails",
"enable_offline_email_notifications",
"enable_offline_push_notifications",
"enable_online_push_notifications",
"enable_sounds",
"enable_stream_audible_notifications",
"enable_stream_desktop_notifications",
"enable_stream_email_notifications",
"enable_stream_push_notifications",
"enter_sends",
"first_in_realm",
"fluid_layout_width",
"full_name",
"furthest_read_time",
"has_mobile_devices",
"has_zoom_token",
"high_contrast_mode",
"hotspots",
"initial_servertime",
"insecure_desktop_app",
"is_admin",
"is_guest",
"is_owner",
"is_web_public_visitor",
"jitsi_server_url",
"language_list",
"language_list_dbl_col",
"last_event_id",
"left_side_userlist",
"login_page",
"max_avatar_file_size_mib",
"max_file_upload_size_mib",
"max_icon_file_size",
"max_logo_file_size",
"max_message_id",
"message_content_in_email_notifications",
"muted_topics",
"narrow",
"narrow_stream",
"needs_tutorial",
"never_subscribed",
"no_event_queue",
"notification_sound",
"password_min_guesses",
"password_min_length",
"pm_content_in_desktop_notifications",
"poll_timeout",
"presence_enabled",
"presences",
"prompt_for_invites",
"queue_id",
"realm_add_emoji_by_admins_only",
"realm_allow_community_topic_editing",
"realm_allow_edit_history",
"realm_allow_message_deleting",
"realm_allow_message_editing",
"realm_authentication_methods",
"realm_available_video_chat_providers",
"realm_avatar_changes_disabled",
"realm_bot_creation_policy",
"realm_bot_domain",
"realm_bots",
"realm_community_topic_editing_limit_seconds",
"realm_create_stream_policy",
"realm_default_code_block_language",
"realm_default_external_accounts",
"realm_default_language",
"realm_default_stream_groups",
"realm_default_streams",
"realm_default_twenty_four_hour_time",
"realm_description",
"realm_digest_emails_enabled",
"realm_digest_weekday",
"realm_disallow_disposable_email_addresses",
"realm_domains",
"realm_email_address_visibility",
"realm_email_auth_enabled",
"realm_email_changes_disabled",
"realm_emails_restricted_to_domains",
"realm_embedded_bots",
"realm_emoji",
"realm_filters",
"realm_icon_source",
"realm_icon_url",
"realm_incoming_webhook_bots",
"realm_inline_image_preview",
"realm_inline_url_embed_preview",
"realm_invite_by_admins_only",
"realm_invite_required",
"realm_invite_to_stream_policy",
"realm_is_zephyr_mirror_realm",
"realm_logo_source",
"realm_logo_url",
"realm_mandatory_topics",
"realm_message_content_allowed_in_email_notifications",
"realm_message_content_delete_limit_seconds",
"realm_message_content_edit_limit_seconds",
"realm_message_retention_days",
"realm_name",
"realm_name_changes_disabled",
"realm_name_in_notifications",
"realm_night_logo_source",
"realm_night_logo_url",
"realm_non_active_users",
"realm_notifications_stream_id",
"realm_password_auth_enabled",
"realm_plan_type",
"realm_presence_disabled",
"realm_private_message_policy",
"realm_push_notifications_enabled",
"realm_send_welcome_emails",
"realm_signup_notifications_stream_id",
"realm_upload_quota",
"realm_uri",
"realm_user_group_edit_policy",
"realm_user_groups",
"realm_users",
"realm_video_chat_provider",
"realm_waiting_period_threshold",
"realm_wildcard_mention_policy",
"recent_private_conversations",
"root_domain_uri",
"save_stacktraces",
"search_pills_enabled",
"server_avatar_changes_disabled",
"server_generation",
"server_inline_image_preview",
"server_inline_url_embed_preview",
"server_name_changes_disabled",
"settings_send_digest_emails",
"starred_message_counts",
"starred_messages",
"stop_words",
"stream_description_max_length",
"stream_name_max_length",
"subscriptions",
"test_suite",
"timezone",
"translate_emoticons",
"translation_data",
"twenty_four_hour_time",
"two_fa_enabled",
"two_fa_enabled_user",
"unread_msgs",
"unsubscribed",
"upgrade_text_for_wide_organization_logo",
"user_id",
"user_status",
"warn_no_email",
"webpack_public_path",
"wildcard_mentions_notify",
"zulip_feature_level",
"zulip_plan_is_not_limited",
"zulip_version",
]
def test_home(self) -> None:
# Keep this list sorted!!!
html_bits = [
"Compose your message here...",
"Exclude messages with topic",
"Keyboard shortcuts",
"Loading...",
"Manage streams",
"Narrow to topic",
"Next message",
"Search streams",
# Verify that the app styles get included
"app-stubentry.js",
"data-params",
]
self.login("hamlet")
# Create bot for realm_bots testing. Must be done before fetching home_page.
bot_info = {
"full_name": "The Bot of Hamlet",
"short_name": "hambot",
}
self.client_post("/json/bots", bot_info)
# Verify succeeds once logged-in
flush_per_request_caches()
with queries_captured() as queries:
with patch("zerver.lib.cache.cache_set") as cache_mock:
result = self._get_home_page(stream="Denmark")
self.check_rendered_logged_in_app(result)
self.assertEqual(
set(result["Cache-Control"].split(", ")), {"must-revalidate", "no-store", "no-cache"}
)
self.assert_length(queries, 39)
self.assert_length(cache_mock.call_args_list, 5)
html = result.content.decode("utf-8")
for html_bit in html_bits:
if html_bit not in html:
raise AssertionError(f"{html_bit} not in result")
page_params = self._get_page_params(result)
actual_keys = sorted(str(k) for k in page_params.keys())
self.assertEqual(actual_keys, self.expected_page_params_keys)
# TODO: Inspect the page_params data further.
# print(orjson.dumps(page_params, option=orjson.OPT_INDENT_2).decode())
realm_bots_expected_keys = [
"api_key",
"avatar_url",
"bot_type",
"default_all_public_streams",
"default_events_register_stream",
"default_sending_stream",
"email",
"full_name",
"is_active",
"owner_id",
"services",
"user_id",
]
realm_bots_actual_keys = sorted(str(key) for key in page_params["realm_bots"][0].keys())
self.assertEqual(realm_bots_actual_keys, realm_bots_expected_keys)
def test_logged_out_home(self) -> None:
result = self.client_get("/")
self.assertEqual(result.status_code, 200)
page_params = self._get_page_params(result)
actual_keys = sorted(str(k) for k in page_params.keys())
removed_keys = [
"last_event_id",
"narrow",
"narrow_stream",
]
expected_keys = [i for i in self.expected_page_params_keys if i not in removed_keys]
self.assertEqual(actual_keys, expected_keys)
def test_home_under_2fa_without_otp_device(self) -> None:
with self.settings(TWO_FACTOR_AUTHENTICATION_ENABLED=True):
self.login("iago")
result = self._get_home_page()
# Should be successful because otp device is not configured.
self.check_rendered_logged_in_app(result)
def test_home_under_2fa_with_otp_device(self) -> None:
with self.settings(TWO_FACTOR_AUTHENTICATION_ENABLED=True):
user_profile = self.example_user("iago")
self.create_default_device(user_profile)
self.login_user(user_profile)
result = self._get_home_page()
# User should not log in because otp device is configured but
# 2fa login function was not called.
self.assertEqual(result.status_code, 302)
self.login_2fa(user_profile)
result = self._get_home_page()
# Should be successful after calling 2fa login function.
self.check_rendered_logged_in_app(result)
def test_num_queries_for_realm_admin(self) -> None:
# Verify number of queries for Realm admin isn't much higher than for normal users.
self.login("iago")
flush_per_request_caches()
with queries_captured() as queries:
with patch("zerver.lib.cache.cache_set") as cache_mock:
result = self._get_home_page()
self.check_rendered_logged_in_app(result)
self.assert_length(cache_mock.call_args_list, 6)
self.assert_length(queries, 36)
def test_num_queries_with_streams(self) -> None:
main_user = self.example_user("hamlet")
other_user = self.example_user("cordelia")
realm_id = main_user.realm_id
self.login_user(main_user)
# Try to make page-load do extra work for various subscribed
# streams.
for i in range(10):
stream_name = "test_stream_" + str(i)
stream = self.make_stream(stream_name)
DefaultStream.objects.create(
realm_id=realm_id,
stream_id=stream.id,
)
for user in [main_user, other_user]:
self.subscribe(user, stream_name)
# Simulate hitting the page the first time to avoid some noise
# related to initial logins.
self._get_home_page()
# Then for the second page load, measure the number of queries.
flush_per_request_caches()
with queries_captured() as queries2:
result = self._get_home_page()
self.assert_length(queries2, 34)
# Do a sanity check that our new streams were in the payload.
html = result.content.decode("utf-8")
self.assertIn("test_stream_7", html)
def _get_home_page(self, **kwargs: Any) -> HttpResponse:
with patch("zerver.lib.events.request_event_queue", return_value=42), patch(
"zerver.lib.events.get_user_events", return_value=[]
):
result = self.client_get("/", dict(**kwargs))
return result
def _sanity_check(self, result: HttpResponse) -> None:
"""
Use this for tests that are geared toward specific edge cases, but
which still want the home page to load properly.
"""
html = result.content.decode("utf-8")
if "Compose your message" not in html:
raise AssertionError("Home page probably did not load.")
def test_terms_of_service(self) -> None:
user = self.example_user("hamlet")
self.login_user(user)
for user_tos_version in [None, "1.1", "2.0.3.4"]:
user.tos_version = user_tos_version
user.save()
with self.settings(TERMS_OF_SERVICE="whatever"), self.settings(TOS_VERSION="99.99"):
result = self.client_get("/", dict(stream="Denmark"))
html = result.content.decode("utf-8")
self.assertIn("Accept the new Terms of Service", html)
def test_banned_desktop_app_versions(self) -> None:
user = self.example_user("hamlet")
self.login_user(user)
result = self.client_get("/", HTTP_USER_AGENT="ZulipElectron/2.3.82")
html = result.content.decode("utf-8")
self.assertIn("You are using old version of the Zulip desktop", html)
def test_unsupported_browser(self) -> None:
user = self.example_user("hamlet")
self.login_user(user)
# currently we don't support IE, so some of IE's user agents are added.
unsupported_user_agents = [
"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2)",
"Mozilla/5.0 (Windows NT 10.0; Trident/7.0; rv:11.0) like Gecko",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)",
]
for user_agent in unsupported_user_agents:
result = self.client_get("/", HTTP_USER_AGENT=user_agent)
html = result.content.decode("utf-8")
self.assertIn("Internet Explorer is not supported by Zulip.", html)
def test_terms_of_service_first_time_template(self) -> None:
user = self.example_user("hamlet")
self.login_user(user)
user.tos_version = None
user.save()
with self.settings(FIRST_TIME_TOS_TEMPLATE="hello.html"), self.settings(
TOS_VERSION="99.99"
):
result = self.client_post("/accounts/accept_terms/")
self.assertEqual(result.status_code, 200)
self.assert_in_response("I agree to the", result)
self.assert_in_response("Chat for distributed teams", result)
def test_accept_terms_of_service(self) -> None:
self.login("hamlet")
result = self.client_post("/accounts/accept_terms/")
self.assertEqual(result.status_code, 200)
self.assert_in_response("I agree to the", result)
result = self.client_post("/accounts/accept_terms/", {"terms": True})
self.assertEqual(result.status_code, 302)
self.assertEqual(result["Location"], "/")
def test_bad_narrow(self) -> None:
self.login("hamlet")
with self.assertLogs(level="WARNING") as m:
result = self._get_home_page(stream="Invalid Stream")
self.assertEqual(m.output, ["WARNING:root:Invalid narrow requested, ignoring"])
self._sanity_check(result)
def test_topic_narrow(self) -> None:
self.login("hamlet")
result = self._get_home_page(stream="Denmark", topic="lunch")
self._sanity_check(result)
html = result.content.decode("utf-8")
self.assertIn("lunch", html)
self.assertEqual(
set(result["Cache-Control"].split(", ")), {"must-revalidate", "no-store", "no-cache"}
)
def test_notifications_stream(self) -> None:
realm = get_realm("zulip")
realm.notifications_stream_id = get_stream("Denmark", realm).id
realm.save()
self.login("hamlet")
result = self._get_home_page()
page_params = self._get_page_params(result)
self.assertEqual(
page_params["realm_notifications_stream_id"], get_stream("Denmark", realm).id
)
def create_bot(self, owner: UserProfile, bot_email: str, bot_name: str) -> UserProfile:
user = do_create_user(
email=bot_email,
password="123",
realm=owner.realm,
full_name=bot_name,
bot_type=UserProfile.DEFAULT_BOT,
bot_owner=owner,
)
return user
def create_non_active_user(self, realm: Realm, email: str, name: str) -> UserProfile:
user = do_create_user(
email=email,
password="123",
realm=realm,
full_name=name,
)
# Doing a full-stack deactivation would be expensive here,
# and we really only need to flip the flag to get a valid
# test.
user.is_active = False
user.save()
return user
def test_signup_notifications_stream(self) -> None:
realm = get_realm("zulip")
realm.signup_notifications_stream = get_stream("Denmark", realm)
realm.save()
self.login("hamlet")
result = self._get_home_page()
page_params = self._get_page_params(result)
self.assertEqual(
page_params["realm_signup_notifications_stream_id"], get_stream("Denmark", realm).id
)
def test_people(self) -> None:
hamlet = self.example_user("hamlet")
realm = get_realm("zulip")
self.login_user(hamlet)
bots = {}
for i in range(3):
bots[i] = self.create_bot(
owner=hamlet,
bot_email=f"bot-{i}@zulip.com",
bot_name=f"Bot {i}",
)
for i in range(3):
defunct_user = self.create_non_active_user(
realm=realm,
email=f"defunct-{i}@zulip.com",
name=f"Defunct User {i}",
)
result = self._get_home_page()
page_params = self._get_page_params(result)
"""
We send three lists of users. The first two below are disjoint
lists of users, and the records we send for them have identical
structure.
The realm_bots bucket is somewhat redundant, since all bots will
be in one of the first two buckets. They do include fields, however,
that normal users don't care about, such as default_sending_stream.
"""
buckets = [
"realm_users",
"realm_non_active_users",
"realm_bots",
]
for field in buckets:
users = page_params[field]
self.assertTrue(len(users) >= 3, field)
for rec in users:
self.assertEqual(rec["user_id"], get_user(rec["email"], realm).id)
if field == "realm_bots":
self.assertNotIn("is_bot", rec)
self.assertIn("is_active", rec)
self.assertIn("owner_id", rec)
else:
self.assertIn("is_bot", rec)
self.assertNotIn("is_active", rec)
active_ids = {p["user_id"] for p in page_params["realm_users"]}
non_active_ids = {p["user_id"] for p in page_params["realm_non_active_users"]}
bot_ids = {p["user_id"] for p in page_params["realm_bots"]}
self.assertIn(hamlet.id, active_ids)
self.assertIn(defunct_user.id, non_active_ids)
# Bots can show up in multiple buckets.
self.assertIn(bots[2].id, bot_ids)
self.assertIn(bots[2].id, active_ids)
# Make sure nobody got mis-bucketed.
self.assertNotIn(hamlet.id, non_active_ids)
self.assertNotIn(defunct_user.id, active_ids)
cross_bots = page_params["cross_realm_bots"]
self.assertEqual(len(cross_bots), 3)
cross_bots.sort(key=lambda d: d["email"])
for cross_bot in cross_bots:
# These are either nondeterministic or boring
del cross_bot["timezone"]
del cross_bot["avatar_url"]
del cross_bot["date_joined"]
notification_bot = self.notification_bot()
email_gateway_bot = get_system_bot(settings.EMAIL_GATEWAY_BOT)
welcome_bot = get_system_bot(settings.WELCOME_BOT)
by_email = lambda d: d["email"]
self.assertEqual(
sorted(cross_bots, key=by_email),
sorted(
[
dict(
avatar_version=email_gateway_bot.avatar_version,
bot_owner_id=None,
bot_type=1,
email=email_gateway_bot.email,
user_id=email_gateway_bot.id,
full_name=email_gateway_bot.full_name,
is_active=True,
is_bot=True,
is_admin=False,
is_owner=False,
is_cross_realm_bot=True,
is_guest=False,
),
dict(
avatar_version=email_gateway_bot.avatar_version,
bot_owner_id=None,
bot_type=1,
email=notification_bot.email,
user_id=notification_bot.id,
full_name=notification_bot.full_name,
is_active=True,
is_bot=True,
is_admin=False,
is_owner=False,
is_cross_realm_bot=True,
is_guest=False,
),
dict(
avatar_version=email_gateway_bot.avatar_version,
bot_owner_id=None,
bot_type=1,
email=welcome_bot.email,
user_id=welcome_bot.id,
full_name=welcome_bot.full_name,
is_active=True,
is_bot=True,
is_admin=False,
is_owner=False,
is_cross_realm_bot=True,
is_guest=False,
),
],
key=by_email,
),
)
def test_new_stream(self) -> None:
user_profile = self.example_user("hamlet")
stream_name = "New stream"
self.subscribe(user_profile, stream_name)
self.login_user(user_profile)
result = self._get_home_page(stream=stream_name)
page_params = self._get_page_params(result)
self.assertEqual(page_params["narrow_stream"], stream_name)
self.assertEqual(page_params["narrow"], [dict(operator="stream", operand=stream_name)])
self.assertEqual(page_params["max_message_id"], -1)
def test_invites_by_admins_only(self) -> None:
user_profile = self.example_user("hamlet")
realm = user_profile.realm
realm.invite_by_admins_only = True
realm.save()
self.login_user(user_profile)
self.assertFalse(user_profile.is_realm_admin)
result = self._get_home_page()
html = result.content.decode("utf-8")
self.assertNotIn("Invite more users", html)
user_profile.role = UserProfile.ROLE_REALM_ADMINISTRATOR
user_profile.save()
result = self._get_home_page()
html = result.content.decode("utf-8")
self.assertIn("Invite more users", html)
def test_show_invites_for_guest_users(self) -> None:
user_profile = self.example_user("polonius")
realm = user_profile.realm
realm.invite_by_admins_only = False
realm.save()
self.login_user(user_profile)
self.assertFalse(user_profile.is_realm_admin)
self.assertFalse(get_realm("zulip").invite_by_admins_only)
result = self._get_home_page()
html = result.content.decode("utf-8")
self.assertNotIn("Invite more users", html)
def test_show_billing(self) -> None:
customer = Customer.objects.create(realm=get_realm("zulip"), stripe_customer_id="cus_id")
user = self.example_user("desdemona")
# realm owner, but no CustomerPlan -> no billing link
user.role = UserProfile.ROLE_REALM_OWNER
user.save(update_fields=["role"])
self.login_user(user)
result_html = self._get_home_page().content.decode("utf-8")
self.assertNotIn("Billing", result_html)
# realm owner, with inactive CustomerPlan -> show billing link
CustomerPlan.objects.create(
customer=customer,
billing_cycle_anchor=timezone_now(),
billing_schedule=CustomerPlan.ANNUAL,
next_invoice_date=timezone_now(),
tier=CustomerPlan.STANDARD,
status=CustomerPlan.ENDED,
)
result_html = self._get_home_page().content.decode("utf-8")
self.assertIn("Billing", result_html)
# realm admin, with CustomerPlan -> no billing link
user.role = UserProfile.ROLE_REALM_ADMINISTRATOR
user.save(update_fields=["role"])
result_html = self._get_home_page().content.decode("utf-8")
self.assertNotIn("Billing", result_html)
# billing admin, with CustomerPlan -> show billing link
user.role = UserProfile.ROLE_MEMBER
user.is_billing_admin = True
user.save(update_fields=["role", "is_billing_admin"])
result_html = self._get_home_page().content.decode("utf-8")
self.assertIn("Billing", result_html)
# member, with CustomerPlan -> no billing link
user.is_billing_admin = False
user.save(update_fields=["is_billing_admin"])
result_html = self._get_home_page().content.decode("utf-8")
self.assertNotIn("Billing", result_html)
# guest, with CustomerPlan -> no billing link
user.role = UserProfile.ROLE_GUEST
user.save(update_fields=["role"])
result_html = self._get_home_page().content.decode("utf-8")
self.assertNotIn("Billing", result_html)
# billing admin, but no CustomerPlan -> no billing link
user.role = UserProfile.ROLE_MEMBER
user.is_billing_admin = True
user.save(update_fields=["role", "is_billing_admin"])
CustomerPlan.objects.all().delete()
result_html = self._get_home_page().content.decode("utf-8")
self.assertNotIn("Billing", result_html)
# billing admin, with sponsorship pending -> show billing link
customer.sponsorship_pending = True
customer.save(update_fields=["sponsorship_pending"])
result_html = self._get_home_page().content.decode("utf-8")
self.assertIn("Billing", result_html)
# billing admin, no customer object -> make sure it doesn't crash
customer.delete()
result = self._get_home_page()
self.check_rendered_logged_in_app(result)
def test_show_plans(self) -> None:
realm = get_realm("zulip")
# Don't show plans to guest users
self.login("polonius")
realm.plan_type = Realm.LIMITED
realm.save(update_fields=["plan_type"])
result_html = self._get_home_page().content.decode("utf-8")
self.assertNotIn("Plans", result_html)
# Show plans link to all other users if plan_type is LIMITED
self.login("hamlet")
result_html = self._get_home_page().content.decode("utf-8")
self.assertIn("Plans", result_html)
# Show plans link to no one, including admins, if SELF_HOSTED or STANDARD
realm.plan_type = Realm.SELF_HOSTED
realm.save(update_fields=["plan_type"])
result_html = self._get_home_page().content.decode("utf-8")
self.assertNotIn("Plans", result_html)
realm.plan_type = Realm.STANDARD
realm.save(update_fields=["plan_type"])
result_html = self._get_home_page().content.decode("utf-8")
self.assertNotIn("Plans", result_html)
def test_desktop_home(self) -> None:
self.login("hamlet")
result = self.client_get("/desktop_home")
self.assertEqual(result.status_code, 301)
self.assertTrue(result["Location"].endswith("/desktop_home/"))
result = self.client_get("/desktop_home/")
self.assertEqual(result.status_code, 302)
path = urllib.parse.urlparse(result["Location"]).path
self.assertEqual(path, "/")
def test_compute_navbar_logo_url(self) -> None:
user_profile = self.example_user("hamlet")
page_params = {"color_scheme": user_profile.COLOR_SCHEME_NIGHT}
add_realm_logo_fields(page_params, user_profile.realm)
self.assertEqual(
compute_navbar_logo_url(page_params), "/static/images/logo/zulip-org-logo.svg?version=0"
)
page_params = {"color_scheme": user_profile.COLOR_SCHEME_LIGHT}
add_realm_logo_fields(page_params, user_profile.realm)
self.assertEqual(
compute_navbar_logo_url(page_params), "/static/images/logo/zulip-org-logo.svg?version=0"
)
do_change_logo_source(
user_profile.realm, Realm.LOGO_UPLOADED, night=False, acting_user=user_profile
)
page_params = {"color_scheme": user_profile.COLOR_SCHEME_NIGHT}
add_realm_logo_fields(page_params, user_profile.realm)
self.assertEqual(
compute_navbar_logo_url(page_params),
f"/user_avatars/{user_profile.realm_id}/realm/logo.png?version=2",
)
page_params = {"color_scheme": user_profile.COLOR_SCHEME_LIGHT}
add_realm_logo_fields(page_params, user_profile.realm)
self.assertEqual(
compute_navbar_logo_url(page_params),
f"/user_avatars/{user_profile.realm_id}/realm/logo.png?version=2",
)
do_change_logo_source(
user_profile.realm, Realm.LOGO_UPLOADED, night=True, acting_user=user_profile
)
page_params = {"color_scheme": user_profile.COLOR_SCHEME_NIGHT}
add_realm_logo_fields(page_params, user_profile.realm)
self.assertEqual(
compute_navbar_logo_url(page_params),
f"/user_avatars/{user_profile.realm_id}/realm/night_logo.png?version=2",
)
page_params = {"color_scheme": user_profile.COLOR_SCHEME_LIGHT}
add_realm_logo_fields(page_params, user_profile.realm)
self.assertEqual(
compute_navbar_logo_url(page_params),
f"/user_avatars/{user_profile.realm_id}/realm/logo.png?version=2",
)
# This configuration isn't super supported in the UI and is a
# weird choice, but we have a test for it anyway.
do_change_logo_source(
user_profile.realm, Realm.LOGO_DEFAULT, night=False, acting_user=user_profile
)
page_params = {"color_scheme": user_profile.COLOR_SCHEME_NIGHT}
add_realm_logo_fields(page_params, user_profile.realm)
self.assertEqual(
compute_navbar_logo_url(page_params),
f"/user_avatars/{user_profile.realm_id}/realm/night_logo.png?version=2",
)
page_params = {"color_scheme": user_profile.COLOR_SCHEME_LIGHT}
add_realm_logo_fields(page_params, user_profile.realm)
self.assertEqual(
compute_navbar_logo_url(page_params), "/static/images/logo/zulip-org-logo.svg?version=0"
)
def test_generate_204(self) -> None:
self.login("hamlet")
result = self.client_get("/api/v1/generate_204")
self.assertEqual(result.status_code, 204)
def test_furthest_read_time(self) -> None:
msg_id = self.send_test_message("hello!", sender_name="iago")
hamlet = self.example_user("hamlet")
self.login_user(hamlet)
self.client_post(
"/json/messages/flags",
{"messages": orjson.dumps([msg_id]).decode(), "op": "add", "flag": "read"},
)
# Manually process the UserActivity
now = timezone_now()
activity_time = calendar.timegm(now.timetuple())
user_activity_event = {
"user_profile_id": hamlet.id,
"client": "test-client",
"query": "update_message_flags",
"time": activity_time,
}
yesterday = now - timedelta(days=1)
activity_time_2 = calendar.timegm(yesterday.timetuple())
user_activity_event_2 = {
"user_profile_id": hamlet.id,
"client": "test-client-2",
"query": "update_message_flags",
"time": activity_time_2,
}
UserActivityWorker().consume_batch([user_activity_event, user_activity_event_2])
# verify furthest_read_time is last activity time, irrespective of client
furthest_read_time = get_furthest_read_time(hamlet)
self.assertGreaterEqual(furthest_read_time, activity_time)
# Check when user has no activity
UserActivity.objects.filter(user_profile=hamlet).delete()
furthest_read_time = get_furthest_read_time(hamlet)
self.assertIsNone(furthest_read_time)
# Check no user profile handling
furthest_read_time = get_furthest_read_time(None)
self.assertIsNotNone(furthest_read_time)
def test_subdomain_homepage(self) -> None:
self.login("hamlet")
with self.settings(ROOT_DOMAIN_LANDING_PAGE=True):
with patch("zerver.views.home.get_subdomain", return_value=""):
result = self._get_home_page()
self.assertEqual(result.status_code, 200)
self.assert_in_response("Chat for distributed teams", result)
with patch("zerver.views.home.get_subdomain", return_value="subdomain"):
result = self._get_home_page()
self._sanity_check(result)
def send_test_message(
self,
content: str,
sender_name: str = "iago",
stream_name: str = "Denmark",
topic_name: str = "foo",
) -> int:
sender = self.example_user(sender_name)
return self.send_stream_message(sender, stream_name, content=content, topic_name=topic_name)
def soft_activate_and_get_unread_count(
self, stream: str = "Denmark", topic: str = "foo"
) -> int:
stream_narrow = self._get_home_page(stream=stream, topic=topic)
page_params = self._get_page_params(stream_narrow)
return page_params["unread_msgs"]["count"]
def test_unread_count_user_soft_deactivation(self) -> None:
# In this test we make sure if a soft deactivated user had unread
# messages before deactivation they remain same way after activation.
long_term_idle_user = self.example_user("hamlet")
self.login_user(long_term_idle_user)
message = "Test Message 1"
self.send_test_message(message)
with queries_captured() as queries:
self.assertEqual(self.soft_activate_and_get_unread_count(), 1)
query_count = len(queries)
user_msg_list = get_user_messages(long_term_idle_user)
self.assertEqual(user_msg_list[-1].content, message)
self.logout()
with self.assertLogs(logger_string, level="INFO") as info_log:
do_soft_deactivate_users([long_term_idle_user])
self.assertEqual(
info_log.output,
[
f"INFO:{logger_string}:Soft deactivated user {long_term_idle_user.id}",
f"INFO:{logger_string}:Soft-deactivated batch of 1 users; 0 remain to process",
],
)
self.login_user(long_term_idle_user)
message = "Test Message 2"
self.send_test_message(message)
idle_user_msg_list = get_user_messages(long_term_idle_user)
self.assertNotEqual(idle_user_msg_list[-1].content, message)
with queries_captured() as queries:
self.assertEqual(self.soft_activate_and_get_unread_count(), 2)
# Test here for query count to be at least 5 greater than previous count
# This will assure indirectly that add_missing_messages() was called.
self.assertGreaterEqual(len(queries) - query_count, 5)
idle_user_msg_list = get_user_messages(long_term_idle_user)
self.assertEqual(idle_user_msg_list[-1].content, message)
def test_multiple_user_soft_deactivations(self) -> None:
long_term_idle_user = self.example_user("hamlet")
# We are sending this message to ensure that long_term_idle_user has
# at least one UserMessage row.
self.send_test_message("Testing", sender_name="hamlet")
with self.assertLogs(logger_string, level="INFO") as info_log:
do_soft_deactivate_users([long_term_idle_user])
self.assertEqual(
info_log.output,
[
f"INFO:{logger_string}:Soft deactivated user {long_term_idle_user.id}",
f"INFO:{logger_string}:Soft-deactivated batch of 1 users; 0 remain to process",
],
)
message = "Test Message 1"
self.send_test_message(message)
self.login_user(long_term_idle_user)
with queries_captured() as queries:
self.assertEqual(self.soft_activate_and_get_unread_count(), 2)
query_count = len(queries)
long_term_idle_user.refresh_from_db()
self.assertFalse(long_term_idle_user.long_term_idle)
idle_user_msg_list = get_user_messages(long_term_idle_user)
self.assertEqual(idle_user_msg_list[-1].content, message)
message = "Test Message 2"
self.send_test_message(message)
with queries_captured() as queries:
self.assertEqual(self.soft_activate_and_get_unread_count(), 3)
# Test here for query count to be at least 5 less than previous count.
# This will assure add_missing_messages() isn't repeatedly called.
self.assertGreaterEqual(query_count - len(queries), 5)
idle_user_msg_list = get_user_messages(long_term_idle_user)
self.assertEqual(idle_user_msg_list[-1].content, message)
self.logout()
with self.assertLogs(logger_string, level="INFO") as info_log:
do_soft_deactivate_users([long_term_idle_user])
self.assertEqual(
info_log.output,
[
f"INFO:{logger_string}:Soft deactivated user {long_term_idle_user.id}",
f"INFO:{logger_string}:Soft-deactivated batch of 1 users; 0 remain to process",
],
)
message = "Test Message 3"
self.send_test_message(message)
self.login_user(long_term_idle_user)
with queries_captured() as queries:
self.assertEqual(self.soft_activate_and_get_unread_count(), 4)
query_count = len(queries)
long_term_idle_user.refresh_from_db()
self.assertFalse(long_term_idle_user.long_term_idle)
idle_user_msg_list = get_user_messages(long_term_idle_user)
self.assertEqual(idle_user_msg_list[-1].content, message)
message = "Test Message 4"
self.send_test_message(message)
with queries_captured() as queries:
self.assertEqual(self.soft_activate_and_get_unread_count(), 5)
self.assertGreaterEqual(query_count - len(queries), 5)
idle_user_msg_list = get_user_messages(long_term_idle_user)
self.assertEqual(idle_user_msg_list[-1].content, message)
self.logout()
def test_url_language(self) -> None:
user = self.example_user("hamlet")
user.default_language = "es"
user.save()
self.login_user(user)
result = self._get_home_page()
self.check_rendered_logged_in_app(result)
with patch("zerver.lib.events.request_event_queue", return_value=42), patch(
"zerver.lib.events.get_user_events", return_value=[]
):
result = self.client_get("/de/")
page_params = self._get_page_params(result)
self.assertEqual(page_params["default_language"], "es")
# TODO: Verify that the actual language we're using in the
# translation data is German.
def test_translation_data(self) -> None:
user = self.example_user("hamlet")
user.default_language = "es"
user.save()
self.login_user(user)
result = self._get_home_page()
self.check_rendered_logged_in_app(result)
page_params = self._get_page_params(result)
self.assertEqual(page_params["default_language"], "es")
def test_compute_show_invites_and_add_streams_admin(self) -> None:
user = self.example_user("iago")
realm = user.realm
realm.invite_by_admins_only = True
realm.save()
show_invites, show_add_streams = compute_show_invites_and_add_streams(user)
self.assertEqual(show_invites, True)
self.assertEqual(show_add_streams, True)
def test_compute_show_invites_and_add_streams_require_admin(self) -> None:
user = self.example_user("hamlet")
realm = user.realm
realm.invite_by_admins_only = True
realm.save()
show_invites, show_add_streams = compute_show_invites_and_add_streams(user)
self.assertEqual(show_invites, False)
self.assertEqual(show_add_streams, True)
def test_compute_show_invites_and_add_streams_guest(self) -> None:
user = self.example_user("polonius")
show_invites, show_add_streams = compute_show_invites_and_add_streams(user)
self.assertEqual(show_invites, False)
self.assertEqual(show_add_streams, False)
def test_compute_show_invites_and_add_streams_unauthenticated(self) -> None:
show_invites, show_add_streams = compute_show_invites_and_add_streams(None)
self.assertEqual(show_invites, False)
self.assertEqual(show_add_streams, False)
| 38.803975 | 100 | 0.634184 | import calendar
import urllib
from datetime import timedelta
from typing import Any
from unittest.mock import patch
import orjson
from django.conf import settings
from django.http import HttpResponse
from django.utils.timezone import now as timezone_now
from corporate.models import Customer, CustomerPlan
from zerver.lib.actions import do_change_logo_source, do_create_user
from zerver.lib.events import add_realm_logo_fields
from zerver.lib.home import get_furthest_read_time
from zerver.lib.soft_deactivation import do_soft_deactivate_users
from zerver.lib.test_classes import ZulipTestCase
from zerver.lib.test_helpers import get_user_messages, queries_captured
from zerver.lib.users import compute_show_invites_and_add_streams
from zerver.models import (
DefaultStream,
Realm,
UserActivity,
UserProfile,
flush_per_request_caches,
get_realm,
get_stream,
get_system_bot,
get_user,
)
from zerver.views.home import compute_navbar_logo_url
from zerver.worker.queue_processors import UserActivityWorker
logger_string = "zulip.soft_deactivation"
class HomeTest(ZulipTestCase):
expected_page_params_keys = [
"alert_words",
"available_notification_sounds",
"avatar_source",
"avatar_url",
"avatar_url_medium",
"bot_types",
"can_create_streams",
"can_subscribe_other_users",
"color_scheme",
"cross_realm_bots",
"custom_profile_field_types",
"custom_profile_fields",
"debug_mode",
"default_language",
"default_language_name",
"delivery_email",
"demote_inactive_streams",
"dense_mode",
"desktop_icon_count_display",
"development_environment",
"email",
"emojiset",
"emojiset_choices",
"enable_desktop_notifications",
"enable_digest_emails",
"enable_login_emails",
"enable_offline_email_notifications",
"enable_offline_push_notifications",
"enable_online_push_notifications",
"enable_sounds",
"enable_stream_audible_notifications",
"enable_stream_desktop_notifications",
"enable_stream_email_notifications",
"enable_stream_push_notifications",
"enter_sends",
"first_in_realm",
"fluid_layout_width",
"full_name",
"furthest_read_time",
"has_mobile_devices",
"has_zoom_token",
"high_contrast_mode",
"hotspots",
"initial_servertime",
"insecure_desktop_app",
"is_admin",
"is_guest",
"is_owner",
"is_web_public_visitor",
"jitsi_server_url",
"language_list",
"language_list_dbl_col",
"last_event_id",
"left_side_userlist",
"login_page",
"max_avatar_file_size_mib",
"max_file_upload_size_mib",
"max_icon_file_size",
"max_logo_file_size",
"max_message_id",
"message_content_in_email_notifications",
"muted_topics",
"narrow",
"narrow_stream",
"needs_tutorial",
"never_subscribed",
"no_event_queue",
"notification_sound",
"password_min_guesses",
"password_min_length",
"pm_content_in_desktop_notifications",
"poll_timeout",
"presence_enabled",
"presences",
"prompt_for_invites",
"queue_id",
"realm_add_emoji_by_admins_only",
"realm_allow_community_topic_editing",
"realm_allow_edit_history",
"realm_allow_message_deleting",
"realm_allow_message_editing",
"realm_authentication_methods",
"realm_available_video_chat_providers",
"realm_avatar_changes_disabled",
"realm_bot_creation_policy",
"realm_bot_domain",
"realm_bots",
"realm_community_topic_editing_limit_seconds",
"realm_create_stream_policy",
"realm_default_code_block_language",
"realm_default_external_accounts",
"realm_default_language",
"realm_default_stream_groups",
"realm_default_streams",
"realm_default_twenty_four_hour_time",
"realm_description",
"realm_digest_emails_enabled",
"realm_digest_weekday",
"realm_disallow_disposable_email_addresses",
"realm_domains",
"realm_email_address_visibility",
"realm_email_auth_enabled",
"realm_email_changes_disabled",
"realm_emails_restricted_to_domains",
"realm_embedded_bots",
"realm_emoji",
"realm_filters",
"realm_icon_source",
"realm_icon_url",
"realm_incoming_webhook_bots",
"realm_inline_image_preview",
"realm_inline_url_embed_preview",
"realm_invite_by_admins_only",
"realm_invite_required",
"realm_invite_to_stream_policy",
"realm_is_zephyr_mirror_realm",
"realm_logo_source",
"realm_logo_url",
"realm_mandatory_topics",
"realm_message_content_allowed_in_email_notifications",
"realm_message_content_delete_limit_seconds",
"realm_message_content_edit_limit_seconds",
"realm_message_retention_days",
"realm_name",
"realm_name_changes_disabled",
"realm_name_in_notifications",
"realm_night_logo_source",
"realm_night_logo_url",
"realm_non_active_users",
"realm_notifications_stream_id",
"realm_password_auth_enabled",
"realm_plan_type",
"realm_presence_disabled",
"realm_private_message_policy",
"realm_push_notifications_enabled",
"realm_send_welcome_emails",
"realm_signup_notifications_stream_id",
"realm_upload_quota",
"realm_uri",
"realm_user_group_edit_policy",
"realm_user_groups",
"realm_users",
"realm_video_chat_provider",
"realm_waiting_period_threshold",
"realm_wildcard_mention_policy",
"recent_private_conversations",
"root_domain_uri",
"save_stacktraces",
"search_pills_enabled",
"server_avatar_changes_disabled",
"server_generation",
"server_inline_image_preview",
"server_inline_url_embed_preview",
"server_name_changes_disabled",
"settings_send_digest_emails",
"starred_message_counts",
"starred_messages",
"stop_words",
"stream_description_max_length",
"stream_name_max_length",
"subscriptions",
"test_suite",
"timezone",
"translate_emoticons",
"translation_data",
"twenty_four_hour_time",
"two_fa_enabled",
"two_fa_enabled_user",
"unread_msgs",
"unsubscribed",
"upgrade_text_for_wide_organization_logo",
"user_id",
"user_status",
"warn_no_email",
"webpack_public_path",
"wildcard_mentions_notify",
"zulip_feature_level",
"zulip_plan_is_not_limited",
"zulip_version",
]
def test_home(self) -> None:
html_bits = [
"Compose your message here...",
"Exclude messages with topic",
"Keyboard shortcuts",
"Loading...",
"Manage streams",
"Narrow to topic",
"Next message",
"Search streams",
"app-stubentry.js",
"data-params",
]
self.login("hamlet")
bot_info = {
"full_name": "The Bot of Hamlet",
"short_name": "hambot",
}
self.client_post("/json/bots", bot_info)
flush_per_request_caches()
with queries_captured() as queries:
with patch("zerver.lib.cache.cache_set") as cache_mock:
result = self._get_home_page(stream="Denmark")
self.check_rendered_logged_in_app(result)
self.assertEqual(
set(result["Cache-Control"].split(", ")), {"must-revalidate", "no-store", "no-cache"}
)
self.assert_length(queries, 39)
self.assert_length(cache_mock.call_args_list, 5)
html = result.content.decode("utf-8")
for html_bit in html_bits:
if html_bit not in html:
raise AssertionError(f"{html_bit} not in result")
page_params = self._get_page_params(result)
actual_keys = sorted(str(k) for k in page_params.keys())
self.assertEqual(actual_keys, self.expected_page_params_keys)
realm_bots_expected_keys = [
"api_key",
"avatar_url",
"bot_type",
"default_all_public_streams",
"default_events_register_stream",
"default_sending_stream",
"email",
"full_name",
"is_active",
"owner_id",
"services",
"user_id",
]
realm_bots_actual_keys = sorted(str(key) for key in page_params["realm_bots"][0].keys())
self.assertEqual(realm_bots_actual_keys, realm_bots_expected_keys)
def test_logged_out_home(self) -> None:
result = self.client_get("/")
self.assertEqual(result.status_code, 200)
page_params = self._get_page_params(result)
actual_keys = sorted(str(k) for k in page_params.keys())
removed_keys = [
"last_event_id",
"narrow",
"narrow_stream",
]
expected_keys = [i for i in self.expected_page_params_keys if i not in removed_keys]
self.assertEqual(actual_keys, expected_keys)
def test_home_under_2fa_without_otp_device(self) -> None:
with self.settings(TWO_FACTOR_AUTHENTICATION_ENABLED=True):
self.login("iago")
result = self._get_home_page()
self.check_rendered_logged_in_app(result)
def test_home_under_2fa_with_otp_device(self) -> None:
with self.settings(TWO_FACTOR_AUTHENTICATION_ENABLED=True):
user_profile = self.example_user("iago")
self.create_default_device(user_profile)
self.login_user(user_profile)
result = self._get_home_page()
self.assertEqual(result.status_code, 302)
self.login_2fa(user_profile)
result = self._get_home_page()
self.check_rendered_logged_in_app(result)
def test_num_queries_for_realm_admin(self) -> None:
self.login("iago")
flush_per_request_caches()
with queries_captured() as queries:
with patch("zerver.lib.cache.cache_set") as cache_mock:
result = self._get_home_page()
self.check_rendered_logged_in_app(result)
self.assert_length(cache_mock.call_args_list, 6)
self.assert_length(queries, 36)
def test_num_queries_with_streams(self) -> None:
main_user = self.example_user("hamlet")
other_user = self.example_user("cordelia")
realm_id = main_user.realm_id
self.login_user(main_user)
# Try to make page-load do extra work for various subscribed
# streams.
for i in range(10):
stream_name = "test_stream_" + str(i)
stream = self.make_stream(stream_name)
DefaultStream.objects.create(
realm_id=realm_id,
stream_id=stream.id,
)
for user in [main_user, other_user]:
self.subscribe(user, stream_name)
# Simulate hitting the page the first time to avoid some noise
# related to initial logins.
self._get_home_page()
# Then for the second page load, measure the number of queries.
flush_per_request_caches()
with queries_captured() as queries2:
result = self._get_home_page()
self.assert_length(queries2, 34)
# Do a sanity check that our new streams were in the payload.
html = result.content.decode("utf-8")
self.assertIn("test_stream_7", html)
def _get_home_page(self, **kwargs: Any) -> HttpResponse:
with patch("zerver.lib.events.request_event_queue", return_value=42), patch(
"zerver.lib.events.get_user_events", return_value=[]
):
result = self.client_get("/", dict(**kwargs))
return result
def _sanity_check(self, result: HttpResponse) -> None:
html = result.content.decode("utf-8")
if "Compose your message" not in html:
raise AssertionError("Home page probably did not load.")
def test_terms_of_service(self) -> None:
user = self.example_user("hamlet")
self.login_user(user)
for user_tos_version in [None, "1.1", "2.0.3.4"]:
user.tos_version = user_tos_version
user.save()
with self.settings(TERMS_OF_SERVICE="whatever"), self.settings(TOS_VERSION="99.99"):
result = self.client_get("/", dict(stream="Denmark"))
html = result.content.decode("utf-8")
self.assertIn("Accept the new Terms of Service", html)
def test_banned_desktop_app_versions(self) -> None:
user = self.example_user("hamlet")
self.login_user(user)
result = self.client_get("/", HTTP_USER_AGENT="ZulipElectron/2.3.82")
html = result.content.decode("utf-8")
self.assertIn("You are using old version of the Zulip desktop", html)
def test_unsupported_browser(self) -> None:
user = self.example_user("hamlet")
self.login_user(user)
# currently we don't support IE, so some of IE's user agents are added.
unsupported_user_agents = [
"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2)",
"Mozilla/5.0 (Windows NT 10.0; Trident/7.0; rv:11.0) like Gecko",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)",
]
for user_agent in unsupported_user_agents:
result = self.client_get("/", HTTP_USER_AGENT=user_agent)
html = result.content.decode("utf-8")
self.assertIn("Internet Explorer is not supported by Zulip.", html)
def test_terms_of_service_first_time_template(self) -> None:
user = self.example_user("hamlet")
self.login_user(user)
user.tos_version = None
user.save()
with self.settings(FIRST_TIME_TOS_TEMPLATE="hello.html"), self.settings(
TOS_VERSION="99.99"
):
result = self.client_post("/accounts/accept_terms/")
self.assertEqual(result.status_code, 200)
self.assert_in_response("I agree to the", result)
self.assert_in_response("Chat for distributed teams", result)
def test_accept_terms_of_service(self) -> None:
self.login("hamlet")
result = self.client_post("/accounts/accept_terms/")
self.assertEqual(result.status_code, 200)
self.assert_in_response("I agree to the", result)
result = self.client_post("/accounts/accept_terms/", {"terms": True})
self.assertEqual(result.status_code, 302)
self.assertEqual(result["Location"], "/")
def test_bad_narrow(self) -> None:
self.login("hamlet")
with self.assertLogs(level="WARNING") as m:
result = self._get_home_page(stream="Invalid Stream")
self.assertEqual(m.output, ["WARNING:root:Invalid narrow requested, ignoring"])
self._sanity_check(result)
def test_topic_narrow(self) -> None:
self.login("hamlet")
result = self._get_home_page(stream="Denmark", topic="lunch")
self._sanity_check(result)
html = result.content.decode("utf-8")
self.assertIn("lunch", html)
self.assertEqual(
set(result["Cache-Control"].split(", ")), {"must-revalidate", "no-store", "no-cache"}
)
def test_notifications_stream(self) -> None:
realm = get_realm("zulip")
realm.notifications_stream_id = get_stream("Denmark", realm).id
realm.save()
self.login("hamlet")
result = self._get_home_page()
page_params = self._get_page_params(result)
self.assertEqual(
page_params["realm_notifications_stream_id"], get_stream("Denmark", realm).id
)
def create_bot(self, owner: UserProfile, bot_email: str, bot_name: str) -> UserProfile:
user = do_create_user(
email=bot_email,
password="123",
realm=owner.realm,
full_name=bot_name,
bot_type=UserProfile.DEFAULT_BOT,
bot_owner=owner,
)
return user
def create_non_active_user(self, realm: Realm, email: str, name: str) -> UserProfile:
user = do_create_user(
email=email,
password="123",
realm=realm,
full_name=name,
)
# Doing a full-stack deactivation would be expensive here,
# and we really only need to flip the flag to get a valid
# test.
user.is_active = False
user.save()
return user
def test_signup_notifications_stream(self) -> None:
realm = get_realm("zulip")
realm.signup_notifications_stream = get_stream("Denmark", realm)
realm.save()
self.login("hamlet")
result = self._get_home_page()
page_params = self._get_page_params(result)
self.assertEqual(
page_params["realm_signup_notifications_stream_id"], get_stream("Denmark", realm).id
)
def test_people(self) -> None:
hamlet = self.example_user("hamlet")
realm = get_realm("zulip")
self.login_user(hamlet)
bots = {}
for i in range(3):
bots[i] = self.create_bot(
owner=hamlet,
bot_email=f"bot-{i}@zulip.com",
bot_name=f"Bot {i}",
)
for i in range(3):
defunct_user = self.create_non_active_user(
realm=realm,
email=f"defunct-{i}@zulip.com",
name=f"Defunct User {i}",
)
result = self._get_home_page()
page_params = self._get_page_params(result)
buckets = [
"realm_users",
"realm_non_active_users",
"realm_bots",
]
for field in buckets:
users = page_params[field]
self.assertTrue(len(users) >= 3, field)
for rec in users:
self.assertEqual(rec["user_id"], get_user(rec["email"], realm).id)
if field == "realm_bots":
self.assertNotIn("is_bot", rec)
self.assertIn("is_active", rec)
self.assertIn("owner_id", rec)
else:
self.assertIn("is_bot", rec)
self.assertNotIn("is_active", rec)
active_ids = {p["user_id"] for p in page_params["realm_users"]}
non_active_ids = {p["user_id"] for p in page_params["realm_non_active_users"]}
bot_ids = {p["user_id"] for p in page_params["realm_bots"]}
self.assertIn(hamlet.id, active_ids)
self.assertIn(defunct_user.id, non_active_ids)
# Bots can show up in multiple buckets.
self.assertIn(bots[2].id, bot_ids)
self.assertIn(bots[2].id, active_ids)
# Make sure nobody got mis-bucketed.
self.assertNotIn(hamlet.id, non_active_ids)
self.assertNotIn(defunct_user.id, active_ids)
cross_bots = page_params["cross_realm_bots"]
self.assertEqual(len(cross_bots), 3)
cross_bots.sort(key=lambda d: d["email"])
for cross_bot in cross_bots:
# These are either nondeterministic or boring
del cross_bot["timezone"]
del cross_bot["avatar_url"]
del cross_bot["date_joined"]
notification_bot = self.notification_bot()
email_gateway_bot = get_system_bot(settings.EMAIL_GATEWAY_BOT)
welcome_bot = get_system_bot(settings.WELCOME_BOT)
by_email = lambda d: d["email"]
self.assertEqual(
sorted(cross_bots, key=by_email),
sorted(
[
dict(
avatar_version=email_gateway_bot.avatar_version,
bot_owner_id=None,
bot_type=1,
email=email_gateway_bot.email,
user_id=email_gateway_bot.id,
full_name=email_gateway_bot.full_name,
is_active=True,
is_bot=True,
is_admin=False,
is_owner=False,
is_cross_realm_bot=True,
is_guest=False,
),
dict(
avatar_version=email_gateway_bot.avatar_version,
bot_owner_id=None,
bot_type=1,
email=notification_bot.email,
user_id=notification_bot.id,
full_name=notification_bot.full_name,
is_active=True,
is_bot=True,
is_admin=False,
is_owner=False,
is_cross_realm_bot=True,
is_guest=False,
),
dict(
avatar_version=email_gateway_bot.avatar_version,
bot_owner_id=None,
bot_type=1,
email=welcome_bot.email,
user_id=welcome_bot.id,
full_name=welcome_bot.full_name,
is_active=True,
is_bot=True,
is_admin=False,
is_owner=False,
is_cross_realm_bot=True,
is_guest=False,
),
],
key=by_email,
),
)
def test_new_stream(self) -> None:
user_profile = self.example_user("hamlet")
stream_name = "New stream"
self.subscribe(user_profile, stream_name)
self.login_user(user_profile)
result = self._get_home_page(stream=stream_name)
page_params = self._get_page_params(result)
self.assertEqual(page_params["narrow_stream"], stream_name)
self.assertEqual(page_params["narrow"], [dict(operator="stream", operand=stream_name)])
self.assertEqual(page_params["max_message_id"], -1)
def test_invites_by_admins_only(self) -> None:
user_profile = self.example_user("hamlet")
realm = user_profile.realm
realm.invite_by_admins_only = True
realm.save()
self.login_user(user_profile)
self.assertFalse(user_profile.is_realm_admin)
result = self._get_home_page()
html = result.content.decode("utf-8")
self.assertNotIn("Invite more users", html)
user_profile.role = UserProfile.ROLE_REALM_ADMINISTRATOR
user_profile.save()
result = self._get_home_page()
html = result.content.decode("utf-8")
self.assertIn("Invite more users", html)
def test_show_invites_for_guest_users(self) -> None:
user_profile = self.example_user("polonius")
realm = user_profile.realm
realm.invite_by_admins_only = False
realm.save()
self.login_user(user_profile)
self.assertFalse(user_profile.is_realm_admin)
self.assertFalse(get_realm("zulip").invite_by_admins_only)
result = self._get_home_page()
html = result.content.decode("utf-8")
self.assertNotIn("Invite more users", html)
def test_show_billing(self) -> None:
customer = Customer.objects.create(realm=get_realm("zulip"), stripe_customer_id="cus_id")
user = self.example_user("desdemona")
# realm owner, but no CustomerPlan -> no billing link
user.role = UserProfile.ROLE_REALM_OWNER
user.save(update_fields=["role"])
self.login_user(user)
result_html = self._get_home_page().content.decode("utf-8")
self.assertNotIn("Billing", result_html)
# realm owner, with inactive CustomerPlan -> show billing link
CustomerPlan.objects.create(
customer=customer,
billing_cycle_anchor=timezone_now(),
billing_schedule=CustomerPlan.ANNUAL,
next_invoice_date=timezone_now(),
tier=CustomerPlan.STANDARD,
status=CustomerPlan.ENDED,
)
result_html = self._get_home_page().content.decode("utf-8")
self.assertIn("Billing", result_html)
# realm admin, with CustomerPlan -> no billing link
user.role = UserProfile.ROLE_REALM_ADMINISTRATOR
user.save(update_fields=["role"])
result_html = self._get_home_page().content.decode("utf-8")
self.assertNotIn("Billing", result_html)
# billing admin, with CustomerPlan -> show billing link
user.role = UserProfile.ROLE_MEMBER
user.is_billing_admin = True
user.save(update_fields=["role", "is_billing_admin"])
result_html = self._get_home_page().content.decode("utf-8")
self.assertIn("Billing", result_html)
# member, with CustomerPlan -> no billing link
user.is_billing_admin = False
user.save(update_fields=["is_billing_admin"])
result_html = self._get_home_page().content.decode("utf-8")
self.assertNotIn("Billing", result_html)
# guest, with CustomerPlan -> no billing link
user.role = UserProfile.ROLE_GUEST
user.save(update_fields=["role"])
result_html = self._get_home_page().content.decode("utf-8")
self.assertNotIn("Billing", result_html)
# billing admin, but no CustomerPlan -> no billing link
user.role = UserProfile.ROLE_MEMBER
user.is_billing_admin = True
user.save(update_fields=["role", "is_billing_admin"])
CustomerPlan.objects.all().delete()
result_html = self._get_home_page().content.decode("utf-8")
self.assertNotIn("Billing", result_html)
# billing admin, with sponsorship pending -> show billing link
customer.sponsorship_pending = True
customer.save(update_fields=["sponsorship_pending"])
result_html = self._get_home_page().content.decode("utf-8")
self.assertIn("Billing", result_html)
# billing admin, no customer object -> make sure it doesn't crash
customer.delete()
result = self._get_home_page()
self.check_rendered_logged_in_app(result)
def test_show_plans(self) -> None:
realm = get_realm("zulip")
self.login("polonius")
realm.plan_type = Realm.LIMITED
realm.save(update_fields=["plan_type"])
result_html = self._get_home_page().content.decode("utf-8")
self.assertNotIn("Plans", result_html)
# Show plans link to all other users if plan_type is LIMITED
self.login("hamlet")
result_html = self._get_home_page().content.decode("utf-8")
self.assertIn("Plans", result_html)
# Show plans link to no one, including admins, if SELF_HOSTED or STANDARD
realm.plan_type = Realm.SELF_HOSTED
realm.save(update_fields=["plan_type"])
result_html = self._get_home_page().content.decode("utf-8")
self.assertNotIn("Plans", result_html)
realm.plan_type = Realm.STANDARD
realm.save(update_fields=["plan_type"])
result_html = self._get_home_page().content.decode("utf-8")
self.assertNotIn("Plans", result_html)
def test_desktop_home(self) -> None:
self.login("hamlet")
result = self.client_get("/desktop_home")
self.assertEqual(result.status_code, 301)
self.assertTrue(result["Location"].endswith("/desktop_home/"))
result = self.client_get("/desktop_home/")
self.assertEqual(result.status_code, 302)
path = urllib.parse.urlparse(result["Location"]).path
self.assertEqual(path, "/")
def test_compute_navbar_logo_url(self) -> None:
user_profile = self.example_user("hamlet")
page_params = {"color_scheme": user_profile.COLOR_SCHEME_NIGHT}
add_realm_logo_fields(page_params, user_profile.realm)
self.assertEqual(
compute_navbar_logo_url(page_params), "/static/images/logo/zulip-org-logo.svg?version=0"
)
page_params = {"color_scheme": user_profile.COLOR_SCHEME_LIGHT}
add_realm_logo_fields(page_params, user_profile.realm)
self.assertEqual(
compute_navbar_logo_url(page_params), "/static/images/logo/zulip-org-logo.svg?version=0"
)
do_change_logo_source(
user_profile.realm, Realm.LOGO_UPLOADED, night=False, acting_user=user_profile
)
page_params = {"color_scheme": user_profile.COLOR_SCHEME_NIGHT}
add_realm_logo_fields(page_params, user_profile.realm)
self.assertEqual(
compute_navbar_logo_url(page_params),
f"/user_avatars/{user_profile.realm_id}/realm/logo.png?version=2",
)
page_params = {"color_scheme": user_profile.COLOR_SCHEME_LIGHT}
add_realm_logo_fields(page_params, user_profile.realm)
self.assertEqual(
compute_navbar_logo_url(page_params),
f"/user_avatars/{user_profile.realm_id}/realm/logo.png?version=2",
)
do_change_logo_source(
user_profile.realm, Realm.LOGO_UPLOADED, night=True, acting_user=user_profile
)
page_params = {"color_scheme": user_profile.COLOR_SCHEME_NIGHT}
add_realm_logo_fields(page_params, user_profile.realm)
self.assertEqual(
compute_navbar_logo_url(page_params),
f"/user_avatars/{user_profile.realm_id}/realm/night_logo.png?version=2",
)
page_params = {"color_scheme": user_profile.COLOR_SCHEME_LIGHT}
add_realm_logo_fields(page_params, user_profile.realm)
self.assertEqual(
compute_navbar_logo_url(page_params),
f"/user_avatars/{user_profile.realm_id}/realm/logo.png?version=2",
)
# This configuration isn't super supported in the UI and is a
do_change_logo_source(
user_profile.realm, Realm.LOGO_DEFAULT, night=False, acting_user=user_profile
)
page_params = {"color_scheme": user_profile.COLOR_SCHEME_NIGHT}
add_realm_logo_fields(page_params, user_profile.realm)
self.assertEqual(
compute_navbar_logo_url(page_params),
f"/user_avatars/{user_profile.realm_id}/realm/night_logo.png?version=2",
)
page_params = {"color_scheme": user_profile.COLOR_SCHEME_LIGHT}
add_realm_logo_fields(page_params, user_profile.realm)
self.assertEqual(
compute_navbar_logo_url(page_params), "/static/images/logo/zulip-org-logo.svg?version=0"
)
def test_generate_204(self) -> None:
self.login("hamlet")
result = self.client_get("/api/v1/generate_204")
self.assertEqual(result.status_code, 204)
def test_furthest_read_time(self) -> None:
msg_id = self.send_test_message("hello!", sender_name="iago")
hamlet = self.example_user("hamlet")
self.login_user(hamlet)
self.client_post(
"/json/messages/flags",
{"messages": orjson.dumps([msg_id]).decode(), "op": "add", "flag": "read"},
)
now = timezone_now()
activity_time = calendar.timegm(now.timetuple())
user_activity_event = {
"user_profile_id": hamlet.id,
"client": "test-client",
"query": "update_message_flags",
"time": activity_time,
}
yesterday = now - timedelta(days=1)
activity_time_2 = calendar.timegm(yesterday.timetuple())
user_activity_event_2 = {
"user_profile_id": hamlet.id,
"client": "test-client-2",
"query": "update_message_flags",
"time": activity_time_2,
}
UserActivityWorker().consume_batch([user_activity_event, user_activity_event_2])
furthest_read_time = get_furthest_read_time(hamlet)
self.assertGreaterEqual(furthest_read_time, activity_time)
UserActivity.objects.filter(user_profile=hamlet).delete()
furthest_read_time = get_furthest_read_time(hamlet)
self.assertIsNone(furthest_read_time)
furthest_read_time = get_furthest_read_time(None)
self.assertIsNotNone(furthest_read_time)
def test_subdomain_homepage(self) -> None:
self.login("hamlet")
with self.settings(ROOT_DOMAIN_LANDING_PAGE=True):
with patch("zerver.views.home.get_subdomain", return_value=""):
result = self._get_home_page()
self.assertEqual(result.status_code, 200)
self.assert_in_response("Chat for distributed teams", result)
with patch("zerver.views.home.get_subdomain", return_value="subdomain"):
result = self._get_home_page()
self._sanity_check(result)
def send_test_message(
self,
content: str,
sender_name: str = "iago",
stream_name: str = "Denmark",
topic_name: str = "foo",
) -> int:
sender = self.example_user(sender_name)
return self.send_stream_message(sender, stream_name, content=content, topic_name=topic_name)
def soft_activate_and_get_unread_count(
self, stream: str = "Denmark", topic: str = "foo"
) -> int:
stream_narrow = self._get_home_page(stream=stream, topic=topic)
page_params = self._get_page_params(stream_narrow)
return page_params["unread_msgs"]["count"]
def test_unread_count_user_soft_deactivation(self) -> None:
long_term_idle_user = self.example_user("hamlet")
self.login_user(long_term_idle_user)
message = "Test Message 1"
self.send_test_message(message)
with queries_captured() as queries:
self.assertEqual(self.soft_activate_and_get_unread_count(), 1)
query_count = len(queries)
user_msg_list = get_user_messages(long_term_idle_user)
self.assertEqual(user_msg_list[-1].content, message)
self.logout()
with self.assertLogs(logger_string, level="INFO") as info_log:
do_soft_deactivate_users([long_term_idle_user])
self.assertEqual(
info_log.output,
[
f"INFO:{logger_string}:Soft deactivated user {long_term_idle_user.id}",
f"INFO:{logger_string}:Soft-deactivated batch of 1 users; 0 remain to process",
],
)
self.login_user(long_term_idle_user)
message = "Test Message 2"
self.send_test_message(message)
idle_user_msg_list = get_user_messages(long_term_idle_user)
self.assertNotEqual(idle_user_msg_list[-1].content, message)
with queries_captured() as queries:
self.assertEqual(self.soft_activate_and_get_unread_count(), 2)
self.assertGreaterEqual(len(queries) - query_count, 5)
idle_user_msg_list = get_user_messages(long_term_idle_user)
self.assertEqual(idle_user_msg_list[-1].content, message)
def test_multiple_user_soft_deactivations(self) -> None:
long_term_idle_user = self.example_user("hamlet")
self.send_test_message("Testing", sender_name="hamlet")
with self.assertLogs(logger_string, level="INFO") as info_log:
do_soft_deactivate_users([long_term_idle_user])
self.assertEqual(
info_log.output,
[
f"INFO:{logger_string}:Soft deactivated user {long_term_idle_user.id}",
f"INFO:{logger_string}:Soft-deactivated batch of 1 users; 0 remain to process",
],
)
message = "Test Message 1"
self.send_test_message(message)
self.login_user(long_term_idle_user)
with queries_captured() as queries:
self.assertEqual(self.soft_activate_and_get_unread_count(), 2)
query_count = len(queries)
long_term_idle_user.refresh_from_db()
self.assertFalse(long_term_idle_user.long_term_idle)
idle_user_msg_list = get_user_messages(long_term_idle_user)
self.assertEqual(idle_user_msg_list[-1].content, message)
message = "Test Message 2"
self.send_test_message(message)
with queries_captured() as queries:
self.assertEqual(self.soft_activate_and_get_unread_count(), 3)
self.assertGreaterEqual(query_count - len(queries), 5)
idle_user_msg_list = get_user_messages(long_term_idle_user)
self.assertEqual(idle_user_msg_list[-1].content, message)
self.logout()
with self.assertLogs(logger_string, level="INFO") as info_log:
do_soft_deactivate_users([long_term_idle_user])
self.assertEqual(
info_log.output,
[
f"INFO:{logger_string}:Soft deactivated user {long_term_idle_user.id}",
f"INFO:{logger_string}:Soft-deactivated batch of 1 users; 0 remain to process",
],
)
message = "Test Message 3"
self.send_test_message(message)
self.login_user(long_term_idle_user)
with queries_captured() as queries:
self.assertEqual(self.soft_activate_and_get_unread_count(), 4)
query_count = len(queries)
long_term_idle_user.refresh_from_db()
self.assertFalse(long_term_idle_user.long_term_idle)
idle_user_msg_list = get_user_messages(long_term_idle_user)
self.assertEqual(idle_user_msg_list[-1].content, message)
message = "Test Message 4"
self.send_test_message(message)
with queries_captured() as queries:
self.assertEqual(self.soft_activate_and_get_unread_count(), 5)
self.assertGreaterEqual(query_count - len(queries), 5)
idle_user_msg_list = get_user_messages(long_term_idle_user)
self.assertEqual(idle_user_msg_list[-1].content, message)
self.logout()
def test_url_language(self) -> None:
user = self.example_user("hamlet")
user.default_language = "es"
user.save()
self.login_user(user)
result = self._get_home_page()
self.check_rendered_logged_in_app(result)
with patch("zerver.lib.events.request_event_queue", return_value=42), patch(
"zerver.lib.events.get_user_events", return_value=[]
):
result = self.client_get("/de/")
page_params = self._get_page_params(result)
self.assertEqual(page_params["default_language"], "es")
# TODO: Verify that the actual language we're using in the
def test_translation_data(self) -> None:
user = self.example_user("hamlet")
user.default_language = "es"
user.save()
self.login_user(user)
result = self._get_home_page()
self.check_rendered_logged_in_app(result)
page_params = self._get_page_params(result)
self.assertEqual(page_params["default_language"], "es")
def test_compute_show_invites_and_add_streams_admin(self) -> None:
user = self.example_user("iago")
realm = user.realm
realm.invite_by_admins_only = True
realm.save()
show_invites, show_add_streams = compute_show_invites_and_add_streams(user)
self.assertEqual(show_invites, True)
self.assertEqual(show_add_streams, True)
def test_compute_show_invites_and_add_streams_require_admin(self) -> None:
user = self.example_user("hamlet")
realm = user.realm
realm.invite_by_admins_only = True
realm.save()
show_invites, show_add_streams = compute_show_invites_and_add_streams(user)
self.assertEqual(show_invites, False)
self.assertEqual(show_add_streams, True)
def test_compute_show_invites_and_add_streams_guest(self) -> None:
user = self.example_user("polonius")
show_invites, show_add_streams = compute_show_invites_and_add_streams(user)
self.assertEqual(show_invites, False)
self.assertEqual(show_add_streams, False)
def test_compute_show_invites_and_add_streams_unauthenticated(self) -> None:
show_invites, show_add_streams = compute_show_invites_and_add_streams(None)
self.assertEqual(show_invites, False)
self.assertEqual(show_add_streams, False)
| true | true |
1c2e57eb478b88cc278197b05dd422c8b7eec2cb | 2,421 | py | Python | src/ZPublisher/interfaces.py | tseaver/Zope-RFA | 08634f39b0f8b56403a2a9daaa6ee4479ef0c625 | [
"ZPL-2.1"
] | 2 | 2015-12-21T10:34:56.000Z | 2017-09-24T11:07:58.000Z | src/ZPublisher/interfaces.py | MatthewWilkes/Zope | 740f934fc9409ae0062e8f0cd6dcfd8b2df00376 | [
"ZPL-2.1"
] | null | null | null | src/ZPublisher/interfaces.py | MatthewWilkes/Zope | 740f934fc9409ae0062e8f0cd6dcfd8b2df00376 | [
"ZPL-2.1"
] | null | null | null | from zope.interface import Interface, Attribute
#############################################################################
# Publication events
# These are events notified in 'ZPublisher.Publish.publish'.
class IPubEvent(Interface):
'''Base class for publication events.
Publication events are notified in 'ZPublisher.Publish.publish' to
inform about publications (aka requests) and their fate.
'''
request = Attribute('The request being affected')
class IPubStart(IPubEvent):
'''Event notified at the beginning of 'ZPublisher.Publish.publish'.'''
class IPubEnd(IPubEvent):
'''Event notified after request processing.
Note that a retried request ends before the retrial, the retrial
itself is considered a new event.
'''
class IPubSuccess(IPubEnd):
'''A successful request processing.'''
class IPubFailure(IPubEnd):
'''A failed request processing.
Note: If a subscriber to 'IPubSuccess' raises an exception,
then 'IPubFailure' may be notified in addtion to 'IPubSuccess'.
'''
exc_info = Attribute('''The exception info as returned by 'sys.exc_info()'.''')
retry = Attribute('Whether the request will be retried')
class IPubAfterTraversal(IPubEvent):
"""notified after traversal and an (optional) authentication."""
class IPubBeforeCommit(IPubEvent):
"""notified immediately before the transaction commit (i.e. after the main
request processing is finished).
"""
class IPubBeforeAbort(IPubEvent):
"""notified immediately before the transaction abort (i.e. after the main
request processing is finished, and there was an error).
"""
exc_info = Attribute('''The exception info as returned by 'sys.exc_info()'.''')
retry = Attribute('Whether the request will be retried')
class IPubBeforeStreaming(Interface):
"""Event fired just before a streaming response is initiated, i.e. when
something calls response.write() for the first time. Note that this is
carries a reference to the *response*, not the request.
"""
response = Attribute(u"The current HTTP response")
# Exceptions
class UseTraversalDefault(Exception):
"""Indicate default traversal in ``__bobo_traverse__``
This exception can be raised by '__bobo_traverse__' implementations to
indicate that it has no special casing for the given name and that standard
traversal logic should be applied.
"""
| 33.164384 | 83 | 0.701776 | from zope.interface import Interface, Attribute
| true | true |
1c2e5941f1479ba49f53eb4c158724816054820e | 3,858 | py | Python | linkedin_jobs_scraper/utils/chrome_driver.py | magahet/py-linkedin-jobs-scraper | f0d69053455e68bd8a74ab2d79ab2c27b5e3f7d4 | [
"MIT"
] | 85 | 2020-10-21T04:09:23.000Z | 2022-03-23T00:29:33.000Z | linkedin_jobs_scraper/utils/chrome_driver.py | magahet/py-linkedin-jobs-scraper | f0d69053455e68bd8a74ab2d79ab2c27b5e3f7d4 | [
"MIT"
] | 24 | 2020-11-18T10:10:32.000Z | 2022-03-19T17:30:25.000Z | linkedin_jobs_scraper/utils/chrome_driver.py | magahet/py-linkedin-jobs-scraper | f0d69053455e68bd8a74ab2d79ab2c27b5e3f7d4 | [
"MIT"
] | 23 | 2020-11-18T09:31:13.000Z | 2022-03-25T03:50:52.000Z | import urllib3
import json
from selenium import webdriver
from selenium.webdriver.common.proxy import Proxy, ProxyType
from selenium.webdriver.chrome.options import Options
from linkedin_jobs_scraper.utils.logger import debug
def get_default_driver_options(width=1472, height=828, headless=True) -> Options:
"""
Generate default Chrome driver options
:param width: int
:param height: int
:param headless: bool
:return: Options
"""
chrome_options = Options()
chrome_options.headless = headless
chrome_options.page_load_strategy = 'normal'
chrome_options.add_argument("--enable-automation"),
chrome_options.add_argument("--start-maximized"),
chrome_options.add_argument(f"--window-size={width},{height}"),
chrome_options.add_argument("--lang=en-GB"),
chrome_options.add_argument("--no-sandbox"),
chrome_options.add_argument("--disable-setuid-sandbox"),
chrome_options.add_argument("--disable-dev-shm-usage"),
chrome_options.add_argument("--disable-gpu"),
chrome_options.add_argument("--disable-accelerated-2d-canvas"),
# chrome_options.add_argument("--proxy-server='direct://"),
# chrome_options.add_argument("--proxy-bypass-list=*"),
chrome_options.add_argument("--allow-running-insecure-content"),
chrome_options.add_argument("--disable-web-security"),
chrome_options.add_argument("--disable-client-side-phishing-detection"),
chrome_options.add_argument("--disable-notifications"),
chrome_options.add_argument("--mute-audio"),
chrome_options.add_argument("--ignore-certificate-errors"),
# Disable downloads
chrome_options.add_experimental_option(
'prefs', {
'safebrowsing.enabled': 'false',
'download.prompt_for_download': False,
'download.default_directory': '/dev/null',
'download_restrictions': 3,
'profile.default_content_setting_values.notifications': 2,
}
)
return chrome_options
def get_driver_proxy_capabilities(proxy: str):
"""
Use a single proxy directly from the browser
:param proxy:
:return:
"""
proxy = Proxy()
proxy.proxy_type = ProxyType.MANUAL
proxy.http_proxy = proxy
proxy.ssl_proxy = proxy
proxy.ftp_proxy = proxy
proxy.auto_detect = False
capabilities = webdriver.DesiredCapabilities.CHROME.copy()
proxy.add_to_capabilities(capabilities)
return capabilities
def build_driver(executable_path: str = None, options: Options = None, headless=True, timeout=20) -> webdriver:
"""
Build Chrome driver instance
:param executable_path: str
:param options: Options
:param headless: bool
:param timeout: int
:return: webdriver
"""
kwargs = {}
if executable_path is not None:
kwargs['executable_path'] = executable_path
kwargs['options'] = options if options is not None else get_default_driver_options(headless=headless)
# kwargs['desired_capabilities'] = get_driver_proxy_capabilities('http://localhost:8888')
driver = webdriver.Chrome(**kwargs)
driver.set_page_load_timeout(timeout)
return driver
def get_debugger_url(driver: webdriver) -> str:
"""
Get Chrome debugger url
:param driver: webdriver
:return: str
"""
chrome_debugger_url = f"http://{driver.capabilities['goog:chromeOptions']['debuggerAddress']}"
debug('Chrome Debugger Url', chrome_debugger_url)
return chrome_debugger_url
def get_websocket_debugger_url(driver: webdriver) -> str:
"""
Get Chrome websocket debugger url
:param driver: webdriver
:return: str
"""
chrome_debugger_url = get_debugger_url(driver)
http = urllib3.PoolManager()
response = json.loads(http.request('GET', chrome_debugger_url + '/json').data.decode())
return response[0]['webSocketDebuggerUrl']
| 32.420168 | 111 | 0.708657 | import urllib3
import json
from selenium import webdriver
from selenium.webdriver.common.proxy import Proxy, ProxyType
from selenium.webdriver.chrome.options import Options
from linkedin_jobs_scraper.utils.logger import debug
def get_default_driver_options(width=1472, height=828, headless=True) -> Options:
chrome_options = Options()
chrome_options.headless = headless
chrome_options.page_load_strategy = 'normal'
chrome_options.add_argument("--enable-automation"),
chrome_options.add_argument("--start-maximized"),
chrome_options.add_argument(f"--window-size={width},{height}"),
chrome_options.add_argument("--lang=en-GB"),
chrome_options.add_argument("--no-sandbox"),
chrome_options.add_argument("--disable-setuid-sandbox"),
chrome_options.add_argument("--disable-dev-shm-usage"),
chrome_options.add_argument("--disable-gpu"),
chrome_options.add_argument("--disable-accelerated-2d-canvas"),
# chrome_options.add_argument("--proxy-bypass-list=*"),
chrome_options.add_argument("--allow-running-insecure-content"),
chrome_options.add_argument("--disable-web-security"),
chrome_options.add_argument("--disable-client-side-phishing-detection"),
chrome_options.add_argument("--disable-notifications"),
chrome_options.add_argument("--mute-audio"),
chrome_options.add_argument("--ignore-certificate-errors"),
# Disable downloads
chrome_options.add_experimental_option(
'prefs', {
'safebrowsing.enabled': 'false',
'download.prompt_for_download': False,
'download.default_directory': '/dev/null',
'download_restrictions': 3,
'profile.default_content_setting_values.notifications': 2,
}
)
return chrome_options
def get_driver_proxy_capabilities(proxy: str):
proxy = Proxy()
proxy.proxy_type = ProxyType.MANUAL
proxy.http_proxy = proxy
proxy.ssl_proxy = proxy
proxy.ftp_proxy = proxy
proxy.auto_detect = False
capabilities = webdriver.DesiredCapabilities.CHROME.copy()
proxy.add_to_capabilities(capabilities)
return capabilities
def build_driver(executable_path: str = None, options: Options = None, headless=True, timeout=20) -> webdriver:
kwargs = {}
if executable_path is not None:
kwargs['executable_path'] = executable_path
kwargs['options'] = options if options is not None else get_default_driver_options(headless=headless)
# kwargs['desired_capabilities'] = get_driver_proxy_capabilities('http://localhost:8888')
driver = webdriver.Chrome(**kwargs)
driver.set_page_load_timeout(timeout)
return driver
def get_debugger_url(driver: webdriver) -> str:
chrome_debugger_url = f"http://{driver.capabilities['goog:chromeOptions']['debuggerAddress']}"
debug('Chrome Debugger Url', chrome_debugger_url)
return chrome_debugger_url
def get_websocket_debugger_url(driver: webdriver) -> str:
chrome_debugger_url = get_debugger_url(driver)
http = urllib3.PoolManager()
response = json.loads(http.request('GET', chrome_debugger_url + '/json').data.decode())
return response[0]['webSocketDebuggerUrl']
| true | true |
1c2e59e65ce3964676a548c7c0827f760fd7b88b | 1,176 | py | Python | clean.py | braedynl/DasCrazy | 02a3e41631929eaf402116d25299ec252f6fee2f | [
"MIT"
] | 1 | 2021-07-26T05:46:17.000Z | 2021-07-26T05:46:17.000Z | clean.py | braedynl/DasCrazy | 02a3e41631929eaf402116d25299ec252f6fee2f | [
"MIT"
] | null | null | null | clean.py | braedynl/DasCrazy | 02a3e41631929eaf402116d25299ec252f6fee2f | [
"MIT"
] | null | null | null | import pandas as pd
from util import load
def main(raw_filename: str, clean_filename: str) -> None:
raw_data = load(raw_filename)
clean_data = pd.DataFrame(columns=raw_data.columns)
# First chat message to signal a "das crazy" moment
indicator_row = None
for _, row in raw_data.iterrows():
message = row["message"].lower()
if "crazy" in message:
# Filters other users messaging at (roughly) the same time, i.e., discards
# all messages containing the word "crazy" within a 30 second interval
# The user can alternatively be myself, as I will notate "x2" if there were
# two back-to-back crazy moments (I've never witnessed more than two)
if (
(indicator_row is None)
or (row["user"] == "braedynl_" and "x2" in message)
or (row["sent"] - indicator_row["sent"]).total_seconds() > 30
):
indicator_row = row
clean_data = clean_data.append(row, ignore_index=True)
clean_data.to_csv(f"data/{clean_filename}.csv", index=False)
if __name__ == "__main__":
main("raw", "clean")
| 31.783784 | 87 | 0.610544 | import pandas as pd
from util import load
def main(raw_filename: str, clean_filename: str) -> None:
raw_data = load(raw_filename)
clean_data = pd.DataFrame(columns=raw_data.columns)
indicator_row = None
for _, row in raw_data.iterrows():
message = row["message"].lower()
if "crazy" in message:
if (
(indicator_row is None)
or (row["user"] == "braedynl_" and "x2" in message)
or (row["sent"] - indicator_row["sent"]).total_seconds() > 30
):
indicator_row = row
clean_data = clean_data.append(row, ignore_index=True)
clean_data.to_csv(f"data/{clean_filename}.csv", index=False)
if __name__ == "__main__":
main("raw", "clean")
| true | true |
1c2e5aa505ad967025a5ad570c9e300b8bc1dfaf | 5,096 | py | Python | xarray/tests/test_coding.py | jhamman/xarray-test-docs | c54123772817875678ec7ad769e6d4d6612aeb92 | [
"Apache-2.0"
] | 2,257 | 2016-01-06T01:52:47.000Z | 2022-03-30T10:36:31.000Z | xarray/tests/test_coding.py | jhamman/xarray-test-docs | c54123772817875678ec7ad769e6d4d6612aeb92 | [
"Apache-2.0"
] | 4,934 | 2016-01-05T00:06:37.000Z | 2022-03-31T23:57:36.000Z | xarray/tests/test_coding.py | jhamman/xarray-test-docs | c54123772817875678ec7ad769e6d4d6612aeb92 | [
"Apache-2.0"
] | 925 | 2016-01-07T12:18:45.000Z | 2022-03-28T07:42:09.000Z | from contextlib import suppress
import numpy as np
import pandas as pd
import pytest
import xarray as xr
from xarray.coding import variables
from xarray.conventions import decode_cf_variable, encode_cf_variable
from . import assert_allclose, assert_equal, assert_identical, requires_dask
with suppress(ImportError):
import dask.array as da
def test_CFMaskCoder_decode() -> None:
original = xr.Variable(("x",), [0, -1, 1], {"_FillValue": -1})
expected = xr.Variable(("x",), [0, np.nan, 1])
coder = variables.CFMaskCoder()
encoded = coder.decode(original)
assert_identical(expected, encoded)
encoding_with_dtype = {
"dtype": np.dtype("float64"),
"_FillValue": np.float32(1e20),
"missing_value": np.float64(1e20),
}
encoding_without_dtype = {
"_FillValue": np.float32(1e20),
"missing_value": np.float64(1e20),
}
CFMASKCODER_ENCODE_DTYPE_CONFLICT_TESTS = {
"numeric-with-dtype": ([0.0, -1.0, 1.0], encoding_with_dtype),
"numeric-without-dtype": ([0.0, -1.0, 1.0], encoding_without_dtype),
"times-with-dtype": (pd.date_range("2000", periods=3), encoding_with_dtype),
}
@pytest.mark.parametrize(
("data", "encoding"),
CFMASKCODER_ENCODE_DTYPE_CONFLICT_TESTS.values(),
ids=list(CFMASKCODER_ENCODE_DTYPE_CONFLICT_TESTS.keys()),
)
def test_CFMaskCoder_encode_missing_fill_values_conflict(data, encoding) -> None:
original = xr.Variable(("x",), data, encoding=encoding)
encoded = encode_cf_variable(original)
assert encoded.dtype == encoded.attrs["missing_value"].dtype
assert encoded.dtype == encoded.attrs["_FillValue"].dtype
with pytest.warns(variables.SerializationWarning):
roundtripped = decode_cf_variable("foo", encoded)
assert_identical(roundtripped, original)
def test_CFMaskCoder_missing_value() -> None:
expected = xr.DataArray(
np.array([[26915, 27755, -9999, 27705], [25595, -9999, 28315, -9999]]),
dims=["npts", "ntimes"],
name="tmpk",
)
expected.attrs["missing_value"] = -9999
decoded = xr.decode_cf(expected.to_dataset())
encoded, _ = xr.conventions.cf_encoder(decoded, decoded.attrs)
assert_equal(encoded["tmpk"], expected.variable)
decoded.tmpk.encoding["_FillValue"] = -9940
with pytest.raises(ValueError):
encoded, _ = xr.conventions.cf_encoder(decoded, decoded.attrs)
@requires_dask
def test_CFMaskCoder_decode_dask() -> None:
original = xr.Variable(("x",), [0, -1, 1], {"_FillValue": -1}).chunk()
expected = xr.Variable(("x",), [0, np.nan, 1])
coder = variables.CFMaskCoder()
encoded = coder.decode(original)
assert isinstance(encoded.data, da.Array)
assert_identical(expected, encoded)
# TODO(shoyer): port other fill-value tests
# TODO(shoyer): parameterize when we have more coders
def test_coder_roundtrip() -> None:
original = xr.Variable(("x",), [0.0, np.nan, 1.0])
coder = variables.CFMaskCoder()
roundtripped = coder.decode(coder.encode(original))
assert_identical(original, roundtripped)
@pytest.mark.parametrize("dtype", "u1 u2 i1 i2 f2 f4".split())
def test_scaling_converts_to_float32(dtype) -> None:
original = xr.Variable(
("x",), np.arange(10, dtype=dtype), encoding=dict(scale_factor=10)
)
coder = variables.CFScaleOffsetCoder()
encoded = coder.encode(original)
assert encoded.dtype == np.float32
roundtripped = coder.decode(encoded)
assert_identical(original, roundtripped)
assert roundtripped.dtype == np.float32
@pytest.mark.parametrize("scale_factor", (10, [10]))
@pytest.mark.parametrize("add_offset", (0.1, [0.1]))
def test_scaling_offset_as_list(scale_factor, add_offset) -> None:
# test for #4631
encoding = dict(scale_factor=scale_factor, add_offset=add_offset)
original = xr.Variable(("x",), np.arange(10.0), encoding=encoding)
coder = variables.CFScaleOffsetCoder()
encoded = coder.encode(original)
roundtripped = coder.decode(encoded)
assert_allclose(original, roundtripped)
@pytest.mark.parametrize("bits", [1, 2, 4, 8])
def test_decode_unsigned_from_signed(bits) -> None:
unsigned_dtype = np.dtype(f"u{bits}")
signed_dtype = np.dtype(f"i{bits}")
original_values = np.array([np.iinfo(unsigned_dtype).max], dtype=unsigned_dtype)
encoded = xr.Variable(
("x",), original_values.astype(signed_dtype), attrs={"_Unsigned": "true"}
)
coder = variables.UnsignedIntegerCoder()
decoded = coder.decode(encoded)
assert decoded.dtype == unsigned_dtype
assert decoded.values == original_values
@pytest.mark.parametrize("bits", [1, 2, 4, 8])
def test_decode_signed_from_unsigned(bits) -> None:
unsigned_dtype = np.dtype(f"u{bits}")
signed_dtype = np.dtype(f"i{bits}")
original_values = np.array([-1], dtype=signed_dtype)
encoded = xr.Variable(
("x",), original_values.astype(unsigned_dtype), attrs={"_Unsigned": "false"}
)
coder = variables.UnsignedIntegerCoder()
decoded = coder.decode(encoded)
assert decoded.dtype == signed_dtype
assert decoded.values == original_values
| 34.432432 | 84 | 0.701334 | from contextlib import suppress
import numpy as np
import pandas as pd
import pytest
import xarray as xr
from xarray.coding import variables
from xarray.conventions import decode_cf_variable, encode_cf_variable
from . import assert_allclose, assert_equal, assert_identical, requires_dask
with suppress(ImportError):
import dask.array as da
def test_CFMaskCoder_decode() -> None:
original = xr.Variable(("x",), [0, -1, 1], {"_FillValue": -1})
expected = xr.Variable(("x",), [0, np.nan, 1])
coder = variables.CFMaskCoder()
encoded = coder.decode(original)
assert_identical(expected, encoded)
encoding_with_dtype = {
"dtype": np.dtype("float64"),
"_FillValue": np.float32(1e20),
"missing_value": np.float64(1e20),
}
encoding_without_dtype = {
"_FillValue": np.float32(1e20),
"missing_value": np.float64(1e20),
}
CFMASKCODER_ENCODE_DTYPE_CONFLICT_TESTS = {
"numeric-with-dtype": ([0.0, -1.0, 1.0], encoding_with_dtype),
"numeric-without-dtype": ([0.0, -1.0, 1.0], encoding_without_dtype),
"times-with-dtype": (pd.date_range("2000", periods=3), encoding_with_dtype),
}
@pytest.mark.parametrize(
("data", "encoding"),
CFMASKCODER_ENCODE_DTYPE_CONFLICT_TESTS.values(),
ids=list(CFMASKCODER_ENCODE_DTYPE_CONFLICT_TESTS.keys()),
)
def test_CFMaskCoder_encode_missing_fill_values_conflict(data, encoding) -> None:
original = xr.Variable(("x",), data, encoding=encoding)
encoded = encode_cf_variable(original)
assert encoded.dtype == encoded.attrs["missing_value"].dtype
assert encoded.dtype == encoded.attrs["_FillValue"].dtype
with pytest.warns(variables.SerializationWarning):
roundtripped = decode_cf_variable("foo", encoded)
assert_identical(roundtripped, original)
def test_CFMaskCoder_missing_value() -> None:
expected = xr.DataArray(
np.array([[26915, 27755, -9999, 27705], [25595, -9999, 28315, -9999]]),
dims=["npts", "ntimes"],
name="tmpk",
)
expected.attrs["missing_value"] = -9999
decoded = xr.decode_cf(expected.to_dataset())
encoded, _ = xr.conventions.cf_encoder(decoded, decoded.attrs)
assert_equal(encoded["tmpk"], expected.variable)
decoded.tmpk.encoding["_FillValue"] = -9940
with pytest.raises(ValueError):
encoded, _ = xr.conventions.cf_encoder(decoded, decoded.attrs)
@requires_dask
def test_CFMaskCoder_decode_dask() -> None:
original = xr.Variable(("x",), [0, -1, 1], {"_FillValue": -1}).chunk()
expected = xr.Variable(("x",), [0, np.nan, 1])
coder = variables.CFMaskCoder()
encoded = coder.decode(original)
assert isinstance(encoded.data, da.Array)
assert_identical(expected, encoded)
def test_coder_roundtrip() -> None:
original = xr.Variable(("x",), [0.0, np.nan, 1.0])
coder = variables.CFMaskCoder()
roundtripped = coder.decode(coder.encode(original))
assert_identical(original, roundtripped)
@pytest.mark.parametrize("dtype", "u1 u2 i1 i2 f2 f4".split())
def test_scaling_converts_to_float32(dtype) -> None:
original = xr.Variable(
("x",), np.arange(10, dtype=dtype), encoding=dict(scale_factor=10)
)
coder = variables.CFScaleOffsetCoder()
encoded = coder.encode(original)
assert encoded.dtype == np.float32
roundtripped = coder.decode(encoded)
assert_identical(original, roundtripped)
assert roundtripped.dtype == np.float32
@pytest.mark.parametrize("scale_factor", (10, [10]))
@pytest.mark.parametrize("add_offset", (0.1, [0.1]))
def test_scaling_offset_as_list(scale_factor, add_offset) -> None:
encoding = dict(scale_factor=scale_factor, add_offset=add_offset)
original = xr.Variable(("x",), np.arange(10.0), encoding=encoding)
coder = variables.CFScaleOffsetCoder()
encoded = coder.encode(original)
roundtripped = coder.decode(encoded)
assert_allclose(original, roundtripped)
@pytest.mark.parametrize("bits", [1, 2, 4, 8])
def test_decode_unsigned_from_signed(bits) -> None:
unsigned_dtype = np.dtype(f"u{bits}")
signed_dtype = np.dtype(f"i{bits}")
original_values = np.array([np.iinfo(unsigned_dtype).max], dtype=unsigned_dtype)
encoded = xr.Variable(
("x",), original_values.astype(signed_dtype), attrs={"_Unsigned": "true"}
)
coder = variables.UnsignedIntegerCoder()
decoded = coder.decode(encoded)
assert decoded.dtype == unsigned_dtype
assert decoded.values == original_values
@pytest.mark.parametrize("bits", [1, 2, 4, 8])
def test_decode_signed_from_unsigned(bits) -> None:
unsigned_dtype = np.dtype(f"u{bits}")
signed_dtype = np.dtype(f"i{bits}")
original_values = np.array([-1], dtype=signed_dtype)
encoded = xr.Variable(
("x",), original_values.astype(unsigned_dtype), attrs={"_Unsigned": "false"}
)
coder = variables.UnsignedIntegerCoder()
decoded = coder.decode(encoded)
assert decoded.dtype == signed_dtype
assert decoded.values == original_values
| true | true |
1c2e5aafe3ab159eff123db0b0e741b4a314b731 | 1,966 | py | Python | internal/notes/builtin-SAVE/packages/r-rmpfr/package.py | HPCToolkit/hpctest | 5ff4455582bf39e75530a31badcf6142081b386b | [
"BSD-3-Clause"
] | 1 | 2019-01-17T20:07:19.000Z | 2019-01-17T20:07:19.000Z | internal/notes/builtin-SAVE/packages/r-rmpfr/package.py | HPCToolkit/hpctest | 5ff4455582bf39e75530a31badcf6142081b386b | [
"BSD-3-Clause"
] | null | null | null | internal/notes/builtin-SAVE/packages/r-rmpfr/package.py | HPCToolkit/hpctest | 5ff4455582bf39e75530a31badcf6142081b386b | [
"BSD-3-Clause"
] | 2 | 2019-08-06T18:13:57.000Z | 2021-11-05T18:19:49.000Z | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class RRmpfr(RPackage):
"""Arithmetic (via S4 classes and methods) for arbitrary precision
floating point numbers, including transcendental ("special")
functions. To this end, Rmpfr interfaces to the LGPL'ed MPFR
(Multiple Precision Floating-Point Reliable) Library which itself
is based on the GMP (GNU Multiple Precision) Library."""
homepage = "http://rmpfr.r-forge.r-project.org"
url = "https://cran.r-project.org/src/contrib/Rmpfr_0.6-1.tar.gz"
list_url = "https://cran.r-project.org/src/contrib/Archive/Rmpfr"
version('0.6-1', '55d4ec257bd2a9233bafee9e444d0265')
depends_on('r-gmp@0.5-8:', type=('build', 'run'))
depends_on('mpfr@3.0.0:')
| 45.72093 | 78 | 0.677518 | true | true | |
1c2e5af9ef58185b398507efc2256af2097a2184 | 587 | py | Python | card_utils/games/poker/__init__.py | cdrappi/card_utils | dd12d3be22774cf35d7a6ce6b5f05ff6ee527929 | [
"MIT"
] | null | null | null | card_utils/games/poker/__init__.py | cdrappi/card_utils | dd12d3be22774cf35d7a6ce6b5f05ff6ee527929 | [
"MIT"
] | null | null | null | card_utils/games/poker/__init__.py | cdrappi/card_utils | dd12d3be22774cf35d7a6ce6b5f05ff6ee527929 | [
"MIT"
] | null | null | null | """ poker specific constants """
broadway_ranks = {'T', 'J', 'Q', 'K', 'A'}
STRAIGHT_FLUSH = 'straight flush'
QUADS = 'four of a kind'
FULL_HOUSE = 'full house'
FLUSH = 'flush'
STRAIGHT = 'straight'
THREE_OF_A_KIND = 'three of a kind'
TWO_PAIR = 'two pair'
ONE_PAIR = 'one pair'
HIGH_CARD = 'high card'
hand_order = {
HIGH_CARD: 0,
ONE_PAIR: 1,
TWO_PAIR: 2,
THREE_OF_A_KIND: 3,
STRAIGHT: 4,
FLUSH: 5,
FULL_HOUSE: 6,
QUADS: 7,
STRAIGHT_FLUSH: 8
}
inverse_hand_order = {
int_order: str_order
for str_order, int_order in hand_order.items()
}
| 18.935484 | 50 | 0.643952 |
broadway_ranks = {'T', 'J', 'Q', 'K', 'A'}
STRAIGHT_FLUSH = 'straight flush'
QUADS = 'four of a kind'
FULL_HOUSE = 'full house'
FLUSH = 'flush'
STRAIGHT = 'straight'
THREE_OF_A_KIND = 'three of a kind'
TWO_PAIR = 'two pair'
ONE_PAIR = 'one pair'
HIGH_CARD = 'high card'
hand_order = {
HIGH_CARD: 0,
ONE_PAIR: 1,
TWO_PAIR: 2,
THREE_OF_A_KIND: 3,
STRAIGHT: 4,
FLUSH: 5,
FULL_HOUSE: 6,
QUADS: 7,
STRAIGHT_FLUSH: 8
}
inverse_hand_order = {
int_order: str_order
for str_order, int_order in hand_order.items()
}
| true | true |
1c2e5b04acf80c8fcbf410c24c15edcad6285238 | 20,265 | py | Python | dashboard/dashboard/common/utils.py | ncalexan/catapult | d21a98f0ee0bc0394eb93922d0b274fd6ac281d5 | [
"BSD-3-Clause"
] | null | null | null | dashboard/dashboard/common/utils.py | ncalexan/catapult | d21a98f0ee0bc0394eb93922d0b274fd6ac281d5 | [
"BSD-3-Clause"
] | null | null | null | dashboard/dashboard/common/utils.py | ncalexan/catapult | d21a98f0ee0bc0394eb93922d0b274fd6ac281d5 | [
"BSD-3-Clause"
] | 1 | 2019-04-21T23:48:15.000Z | 2019-04-21T23:48:15.000Z | # Copyright 2015 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.
"""General functions which are useful throughout this project."""
import json
import logging
import os
import re
import time
import urllib
from apiclient import discovery
from apiclient import errors
from google.appengine.api import app_identity
from google.appengine.api import memcache
from google.appengine.api import oauth
from google.appengine.api import urlfetch
from google.appengine.api import urlfetch_errors
from google.appengine.api import users
from google.appengine.ext import ndb
import httplib2
from oauth2client import client
from dashboard.common import stored_object
SHERIFF_DOMAINS_KEY = 'sheriff_domains_key'
IP_WHITELIST_KEY = 'ip_whitelist'
SERVICE_ACCOUNT_KEY = 'service_account'
EMAIL_SCOPE = 'https://www.googleapis.com/auth/userinfo.email'
_PROJECT_ID_KEY = 'project_id'
_DEFAULT_CUSTOM_METRIC_VAL = 1
OAUTH_SCOPES = (
'https://www.googleapis.com/auth/userinfo.email',
)
OAUTH_ENDPOINTS = ['/api/', '/add_histograms']
_AUTOROLL_DOMAINS = (
'chops-service-accounts.iam.gserviceaccount.com',
'skia-corp.google.com.iam.gserviceaccount.com',
'skia-public.iam.gserviceaccount.com',
)
def IsDevAppserver():
return app_identity.get_application_id() == 'None'
def _GetNowRfc3339():
"""Returns the current time formatted per RFC 3339."""
return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
def GetEmail():
"""Returns email address of the current user.
Uses OAuth2 for /api/ requests, otherwise cookies.
Returns:
The email address as a string or None if there is no user logged in.
Raises:
OAuthRequestError: The request was not a valid OAuth request.
OAuthServiceFailureError: An unknown error occurred.
"""
request_uri = os.environ.get('REQUEST_URI', '')
if any(request_uri.startswith(e) for e in OAUTH_ENDPOINTS):
# Prevent a CSRF whereby a malicious site posts an api request without an
# Authorization header (so oauth.get_current_user() is None), but while the
# user is signed in, so their cookies would make users.get_current_user()
# return a non-None user.
if 'HTTP_AUTHORIZATION' not in os.environ:
# The user is not signed in. Avoid raising OAuthRequestError.
return None
user = oauth.get_current_user(OAUTH_SCOPES)
else:
user = users.get_current_user()
return user.email() if user else None
def TickMonitoringCustomMetric(metric_name):
"""Increments the stackdriver custom metric with the given name.
This is used for cron job monitoring; if these metrics stop being received
an alert mail is sent. For more information on custom metrics, see
https://cloud.google.com/monitoring/custom-metrics/using-custom-metrics
Args:
metric_name: The name of the metric being monitored.
"""
credentials = client.GoogleCredentials.get_application_default()
monitoring = discovery.build(
'monitoring', 'v3', credentials=credentials)
now = _GetNowRfc3339()
project_id = stored_object.Get(_PROJECT_ID_KEY)
points = [{
'interval': {
'startTime': now,
'endTime': now,
},
'value': {
'int64Value': _DEFAULT_CUSTOM_METRIC_VAL,
},
}]
write_request = monitoring.projects().timeSeries().create(
name='projects/%s' %project_id,
body={'timeSeries': [{
'metric': {
'type': 'custom.googleapis.com/%s' % metric_name,
},
'points': points
}]})
write_request.execute()
def TestPath(key):
"""Returns the test path for a TestMetadata from an ndb.Key.
A "test path" is just a convenient string representation of an ndb.Key.
Each test path corresponds to one ndb.Key, which can be used to get an
entity.
Args:
key: An ndb.Key where all IDs are string IDs.
Returns:
A test path string.
"""
if key.kind() == 'Test':
# The Test key looks like ('Master', 'name', 'Bot', 'name', 'Test' 'name'..)
# Pull out every other entry and join with '/' to form the path.
return '/'.join(key.flat()[1::2])
assert key.kind() == 'TestMetadata' or key.kind() == 'TestContainer'
return key.id()
def TestSuiteName(test_key):
"""Returns the test suite name for a given TestMetadata key."""
assert test_key.kind() == 'TestMetadata'
parts = test_key.id().split('/')
return parts[2]
def TestKey(test_path):
"""Returns the ndb.Key that corresponds to a test path."""
if test_path is None:
return None
path_parts = test_path.split('/')
if path_parts is None:
return None
if len(path_parts) < 3:
key_list = [('Master', path_parts[0])]
if len(path_parts) > 1:
key_list += [('Bot', path_parts[1])]
return ndb.Key(pairs=key_list)
return ndb.Key('TestMetadata', test_path)
def TestMetadataKey(key_or_string):
"""Convert the given (Test or TestMetadata) key or test_path string to a
TestMetadata key.
We are in the process of converting from Test entities to TestMetadata.
Unfortunately, we haver trillions of Row entities which have a parent_test
property set to a Test, and it's not possible to migrate them all. So we
use the Test key in Row queries, and convert between the old and new format.
Note that the Test entities which the keys refer to may be deleted; the
queries over keys still work.
"""
if key_or_string is None:
return None
if isinstance(key_or_string, basestring):
return ndb.Key('TestMetadata', key_or_string)
if key_or_string.kind() == 'TestMetadata':
return key_or_string
if key_or_string.kind() == 'Test':
return ndb.Key('TestMetadata', TestPath(key_or_string))
def OldStyleTestKey(key_or_string):
"""Get the key for the old style Test entity corresponding to this key or
test_path.
We are in the process of converting from Test entities to TestMetadata.
Unfortunately, we haver trillions of Row entities which have a parent_test
property set to a Test, and it's not possible to migrate them all. So we
use the Test key in Row queries, and convert between the old and new format.
Note that the Test entities which the keys refer to may be deleted; the
queries over keys still work.
"""
if key_or_string is None:
return None
elif isinstance(key_or_string, ndb.Key) and key_or_string.kind() == 'Test':
return key_or_string
if (isinstance(key_or_string, ndb.Key) and
key_or_string.kind() == 'TestMetadata'):
key_or_string = key_or_string.id()
assert isinstance(key_or_string, basestring)
path_parts = key_or_string.split('/')
key_parts = ['Master', path_parts[0], 'Bot', path_parts[1]]
for part in path_parts[2:]:
key_parts += ['Test', part]
return ndb.Key(*key_parts)
def MostSpecificMatchingPattern(test, pattern_data_tuples):
"""Takes a test and a list of (pattern, data) tuples and returns the data
for the pattern which most closely matches the test. It does this by
ordering the matching patterns, and choosing the one with the most specific
top level match.
For example, if there was a test Master/Bot/Foo/Bar, then:
*/*/*/Bar would match more closely than */*/*/*
*/*/*/Bar would match more closely than */*/*/Bar.*
*/*/*/Bar.* would match more closely than */*/*/*
"""
matching_patterns = []
for p, v in pattern_data_tuples:
if not TestMatchesPattern(test, p):
continue
matching_patterns.append([p, v])
if not matching_patterns:
return None
if isinstance(test, ndb.Key):
test_path = TestPath(test)
else:
test_path = test.test_path
test_path_parts = test_path.split('/')
# This ensures the ordering puts the closest match at index 0
def CmpPatterns(a, b):
a_parts = a[0].split('/')
b_parts = b[0].split('/')
for a_part, b_part, test_part in reversed(
zip(a_parts, b_parts, test_path_parts)):
# We favour a specific match over a partial match, and a partial
# match over a catch-all * match.
if a_part == b_part:
continue
if a_part == test_part:
return -1
if b_part == test_part:
return 1
if a_part != '*':
return -1
if b_part != '*':
return 1
return 0
matching_patterns.sort(cmp=CmpPatterns)
return matching_patterns[0][1]
def TestMatchesPattern(test, pattern):
"""Checks whether a test matches a test path pattern.
Args:
test: A TestMetadata entity or a TestMetadata key.
pattern: A test path which can include wildcard characters (*).
Returns:
True if it matches, False otherwise.
"""
if not test:
return False
if isinstance(test, ndb.Key):
test_path = TestPath(test)
else:
test_path = test.test_path
test_path_parts = test_path.split('/')
pattern_parts = pattern.split('/')
if len(test_path_parts) != len(pattern_parts):
return False
for test_path_part, pattern_part in zip(test_path_parts, pattern_parts):
if not _MatchesPatternPart(pattern_part, test_path_part):
return False
return True
def _MatchesPatternPart(pattern_part, test_path_part):
"""Checks whether a pattern (possibly with a *) matches the given string.
Args:
pattern_part: A string which may contain a wildcard (*).
test_path_part: Another string.
Returns:
True if it matches, False otherwise.
"""
if pattern_part == '*' or pattern_part == test_path_part:
return True
if '*' not in pattern_part:
return False
# Escape any other special non-alphanumeric characters.
pattern_part = re.escape(pattern_part)
# There are not supposed to be any other asterisk characters, so all
# occurrences of backslash-asterisk can now be replaced with dot-asterisk.
re_pattern = re.compile('^' + pattern_part.replace('\\*', '.*') + '$')
return re_pattern.match(test_path_part)
def TimestampMilliseconds(datetime):
"""Returns the number of milliseconds since the epoch."""
return int(time.mktime(datetime.timetuple()) * 1000)
def GetTestContainerKey(test):
"""Gets the TestContainer key for the given TestMetadata.
Args:
test: Either a TestMetadata entity or its ndb.Key.
Returns:
ndb.Key('TestContainer', test path)
"""
test_path = None
if isinstance(test, ndb.Key):
test_path = TestPath(test)
else:
test_path = test.test_path
return ndb.Key('TestContainer', test_path)
def GetMulti(keys):
"""Gets a list of entities from a list of keys.
If this user is logged in, this is the same as ndb.get_multi. However, if the
user is logged out and any of the data is internal only, an AssertionError
will be raised.
Args:
keys: A list of ndb entity keys.
Returns:
A list of entities, but no internal_only ones if the user is not logged in.
"""
if IsInternalUser():
return ndb.get_multi(keys)
# Not logged in. Check each key individually.
entities = []
for key in keys:
try:
entities.append(key.get())
except AssertionError:
continue
return entities
def MinimumAlertRange(alerts):
"""Returns the intersection of the revision ranges for a set of alerts.
Args:
alerts: An iterable of Alerts.
Returns:
A pair (start, end) if there is a valid minimum range,
or None if the ranges are not overlapping.
"""
ranges = [(a.start_revision, a.end_revision) for a in alerts if a]
return MinimumRange(ranges)
def MinimumRange(ranges):
"""Returns the intersection of the given ranges, or None."""
if not ranges:
return None
starts, ends = zip(*ranges)
start, end = (max(starts), min(ends))
if start > end:
return None
return start, end
def IsInternalUser():
"""Checks whether the user should be able to see internal-only data."""
if IsDevAppserver():
return True
email = GetEmail()
if not email:
return False
cached = GetCachedIsInternalUser(email)
if cached is not None:
return cached
is_internal_user = IsGroupMember(identity=email, group='chromeperf-access')
SetCachedIsInternalUser(email, is_internal_user)
return is_internal_user
def GetCachedIsInternalUser(email):
return memcache.get(_IsInternalUserCacheKey(email))
def SetCachedIsInternalUser(email, value):
memcache.add(_IsInternalUserCacheKey(email), value, time=60*60*24)
def _IsInternalUserCacheKey(email):
return 'is_internal_user_%s' % email
def IsGroupMember(identity, group):
"""Checks if a user is a group member of using chrome-infra-auth.appspot.com.
Args:
identity: User email address.
group: Group name.
Returns:
True if confirmed to be a member, False otherwise.
"""
cached = GetCachedIsGroupMember(identity, group)
if cached is not None:
return cached
try:
discovery_url = ('https://chrome-infra-auth.appspot.com'
'/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest')
service = discovery.build(
'auth', 'v1', discoveryServiceUrl=discovery_url,
http=ServiceAccountHttp())
request = service.membership(identity=identity, group=group)
response = request.execute()
is_member = response['is_member']
SetCachedIsGroupMember(identity, group, is_member)
return is_member
except (errors.HttpError, KeyError, AttributeError) as e:
logging.error('Failed to check membership of %s: %s', identity, e)
return False
def GetCachedIsGroupMember(identity, group):
return memcache.get(_IsGroupMemberCacheKey(identity, group))
def SetCachedIsGroupMember(identity, group, value):
memcache.add(_IsGroupMemberCacheKey(identity, group), value, time=60*60*24)
def _IsGroupMemberCacheKey(identity, group):
return 'is_group_member_%s_%s' % (identity, group)
def ServiceAccountHttp(scope=EMAIL_SCOPE, timeout=None):
"""Returns the Credentials of the service account if available."""
account_details = stored_object.Get(SERVICE_ACCOUNT_KEY)
if not account_details:
raise KeyError('Service account credentials not found.')
assert scope, "ServiceAccountHttp scope must not be None."
client.logger.setLevel(logging.WARNING)
credentials = client.SignedJwtAssertionCredentials(
service_account_name=account_details['client_email'],
private_key=account_details['private_key'],
scope=scope)
http = httplib2.Http(timeout=timeout)
credentials.authorize(http)
return http
def IsValidSheriffUser():
"""Checks whether the user should be allowed to triage alerts."""
email = GetEmail()
if not email:
return False
sheriff_domains = stored_object.Get(SHERIFF_DOMAINS_KEY)
domain_matched = sheriff_domains and any(
email.endswith('@' + domain) for domain in sheriff_domains)
return domain_matched or IsTryjobUser()
def IsTryjobUser():
email = GetEmail()
return bool(email) and IsGroupMember(
identity=email, group='project-chromium-tryjob-access')
def GetIpWhitelist():
"""Returns a list of IP address strings in the whitelist."""
return stored_object.Get(IP_WHITELIST_KEY)
def BisectConfigPythonString(config):
"""Turns a bisect config dict into a properly formatted Python string.
Args:
config: A bisect config dict (see start_try_job.GetBisectConfig)
Returns:
A config string suitable to store in a TryJob entity.
"""
return 'config = %s\n' % json.dumps(
config, sort_keys=True, indent=2, separators=(',', ': '))
def GetRequestId():
"""Returns the request log ID which can be used to find a specific log."""
return os.environ.get('REQUEST_LOG_ID')
def Validate(expected, actual):
"""Generic validator for expected keys, values, and types.
Values are also considered equal if |actual| can be converted to |expected|'s
type. For instance:
_Validate([3], '3') # Returns True.
See utils_test.py for more examples.
Args:
expected: Either a list of expected values or a dictionary of expected
keys and type. A dictionary can contain a list of expected values.
actual: A value.
"""
def IsValidType(expected, actual):
if isinstance(expected, type) and not isinstance(actual, expected):
try:
expected(actual)
except ValueError:
return False
return True
def IsInList(expected, actual):
for value in expected:
try:
if type(value)(actual) == value:
return True
except ValueError:
pass
return False
if not expected:
return
expected_type = type(expected)
actual_type = type(actual)
if expected_type is list:
if not IsInList(expected, actual):
raise ValueError('Invalid value. Expected one of the following: '
'%s. Actual: %s.' % (','.join(expected), actual))
elif expected_type is dict:
if actual_type is not dict:
raise ValueError('Invalid type. Expected: %s. Actual: %s.'
% (expected_type, actual_type))
missing = set(expected.keys()) - set(actual.keys())
if missing:
raise ValueError('Missing the following properties: %s'
% ','.join(missing))
for key in expected:
Validate(expected[key], actual[key])
elif not IsValidType(expected, actual):
raise ValueError('Invalid type. Expected: %s. Actual: %s.' %
(expected, actual_type))
def FetchURL(request_url, skip_status_code=False):
"""Wrapper around URL fetch service to make request.
Args:
request_url: URL of request.
skip_status_code: Skips return code check when True, default is False.
Returns:
Response object return by URL fetch, otherwise None when there's an error.
"""
logging.info('URL being fetched: ' + request_url)
try:
response = urlfetch.fetch(request_url)
except urlfetch_errors.DeadlineExceededError:
logging.error('Deadline exceeded error checking %s', request_url)
return None
except urlfetch_errors.DownloadError as err:
# DownloadError is raised to indicate a non-specific failure when there
# was not a 4xx or 5xx status code.
logging.error('DownloadError: %r', err)
return None
if skip_status_code:
return response
elif response.status_code != 200:
logging.error(
'ERROR %s checking %s', response.status_code, request_url)
return None
return response
def GetBuildDetailsFromStdioLink(stdio_link):
no_details = (None, None, None, None, None)
m = re.match(r'\[(.+?)\]\((.+?)\)', stdio_link)
if not m:
# This wasn't the markdown-style link we were expecting.
return no_details
_, link = m.groups()
m = re.match(
r'(https{0,1}://.*/([^\/]*)/builders/)'
r'([^\/]+)/builds/(\d+)/steps/([^\/]+)', link)
if not m:
# This wasn't a buildbot formatted link.
return no_details
base_url, master, bot, buildnumber, step = m.groups()
bot = urllib.unquote(bot)
return base_url, master, bot, buildnumber, step
def GetStdioLinkFromRow(row):
"""Returns the markdown-style buildbot stdio link.
Due to crbug.com/690630, many row entities have this set to "a_a_stdio_uri"
instead of "a_stdio_uri".
"""
return(getattr(row, 'a_stdio_uri', None) or
getattr(row, 'a_a_stdio_uri', None))
def GetBuildbotStatusPageUriFromStdioLink(stdio_link):
base_url, _, bot, buildnumber, _ = GetBuildDetailsFromStdioLink(
stdio_link)
if not base_url:
# Can't parse status page
return None
return '%s%s/builds/%s' % (base_url, urllib.quote(bot), buildnumber)
def GetLogdogLogUriFromStdioLink(stdio_link):
base_url, master, bot, buildnumber, step = GetBuildDetailsFromStdioLink(
stdio_link)
if not base_url:
# Can't parse status page
return None
bot = re.sub(r'[ \(\)]', '_', bot)
s_param = urllib.quote('chrome/bb/%s/%s/%s/+/recipes/steps/%s/0/stdout' % (
master, bot, buildnumber, step), safe='')
return 'https://luci-logdog.appspot.com/v/?s=%s' % s_param
def GetRowKey(testmetadata_key, revision):
test_container_key = GetTestContainerKey(testmetadata_key)
return ndb.Key('Row', revision, parent=test_container_key)
def GetSheriffForAutorollCommit(author, message):
if author.split('@')[-1] not in _AUTOROLL_DOMAINS:
# Not an autoroll.
return None
# This is an autoroll. The sheriff should be the first person on TBR list.
m = re.search(r'TBR=([^,^\s]*)', message)
if not m:
return None
return m.group(1)
| 30.986239 | 80 | 0.702048 |
import json
import logging
import os
import re
import time
import urllib
from apiclient import discovery
from apiclient import errors
from google.appengine.api import app_identity
from google.appengine.api import memcache
from google.appengine.api import oauth
from google.appengine.api import urlfetch
from google.appengine.api import urlfetch_errors
from google.appengine.api import users
from google.appengine.ext import ndb
import httplib2
from oauth2client import client
from dashboard.common import stored_object
SHERIFF_DOMAINS_KEY = 'sheriff_domains_key'
IP_WHITELIST_KEY = 'ip_whitelist'
SERVICE_ACCOUNT_KEY = 'service_account'
EMAIL_SCOPE = 'https://www.googleapis.com/auth/userinfo.email'
_PROJECT_ID_KEY = 'project_id'
_DEFAULT_CUSTOM_METRIC_VAL = 1
OAUTH_SCOPES = (
'https://www.googleapis.com/auth/userinfo.email',
)
OAUTH_ENDPOINTS = ['/api/', '/add_histograms']
_AUTOROLL_DOMAINS = (
'chops-service-accounts.iam.gserviceaccount.com',
'skia-corp.google.com.iam.gserviceaccount.com',
'skia-public.iam.gserviceaccount.com',
)
def IsDevAppserver():
return app_identity.get_application_id() == 'None'
def _GetNowRfc3339():
return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
def GetEmail():
request_uri = os.environ.get('REQUEST_URI', '')
if any(request_uri.startswith(e) for e in OAUTH_ENDPOINTS):
if 'HTTP_AUTHORIZATION' not in os.environ:
return None
user = oauth.get_current_user(OAUTH_SCOPES)
else:
user = users.get_current_user()
return user.email() if user else None
def TickMonitoringCustomMetric(metric_name):
credentials = client.GoogleCredentials.get_application_default()
monitoring = discovery.build(
'monitoring', 'v3', credentials=credentials)
now = _GetNowRfc3339()
project_id = stored_object.Get(_PROJECT_ID_KEY)
points = [{
'interval': {
'startTime': now,
'endTime': now,
},
'value': {
'int64Value': _DEFAULT_CUSTOM_METRIC_VAL,
},
}]
write_request = monitoring.projects().timeSeries().create(
name='projects/%s' %project_id,
body={'timeSeries': [{
'metric': {
'type': 'custom.googleapis.com/%s' % metric_name,
},
'points': points
}]})
write_request.execute()
def TestPath(key):
if key.kind() == 'Test':
return '/'.join(key.flat()[1::2])
assert key.kind() == 'TestMetadata' or key.kind() == 'TestContainer'
return key.id()
def TestSuiteName(test_key):
assert test_key.kind() == 'TestMetadata'
parts = test_key.id().split('/')
return parts[2]
def TestKey(test_path):
if test_path is None:
return None
path_parts = test_path.split('/')
if path_parts is None:
return None
if len(path_parts) < 3:
key_list = [('Master', path_parts[0])]
if len(path_parts) > 1:
key_list += [('Bot', path_parts[1])]
return ndb.Key(pairs=key_list)
return ndb.Key('TestMetadata', test_path)
def TestMetadataKey(key_or_string):
if key_or_string is None:
return None
if isinstance(key_or_string, basestring):
return ndb.Key('TestMetadata', key_or_string)
if key_or_string.kind() == 'TestMetadata':
return key_or_string
if key_or_string.kind() == 'Test':
return ndb.Key('TestMetadata', TestPath(key_or_string))
def OldStyleTestKey(key_or_string):
if key_or_string is None:
return None
elif isinstance(key_or_string, ndb.Key) and key_or_string.kind() == 'Test':
return key_or_string
if (isinstance(key_or_string, ndb.Key) and
key_or_string.kind() == 'TestMetadata'):
key_or_string = key_or_string.id()
assert isinstance(key_or_string, basestring)
path_parts = key_or_string.split('/')
key_parts = ['Master', path_parts[0], 'Bot', path_parts[1]]
for part in path_parts[2:]:
key_parts += ['Test', part]
return ndb.Key(*key_parts)
def MostSpecificMatchingPattern(test, pattern_data_tuples):
matching_patterns = []
for p, v in pattern_data_tuples:
if not TestMatchesPattern(test, p):
continue
matching_patterns.append([p, v])
if not matching_patterns:
return None
if isinstance(test, ndb.Key):
test_path = TestPath(test)
else:
test_path = test.test_path
test_path_parts = test_path.split('/')
def CmpPatterns(a, b):
a_parts = a[0].split('/')
b_parts = b[0].split('/')
for a_part, b_part, test_part in reversed(
zip(a_parts, b_parts, test_path_parts)):
if a_part == b_part:
continue
if a_part == test_part:
return -1
if b_part == test_part:
return 1
if a_part != '*':
return -1
if b_part != '*':
return 1
return 0
matching_patterns.sort(cmp=CmpPatterns)
return matching_patterns[0][1]
def TestMatchesPattern(test, pattern):
if not test:
return False
if isinstance(test, ndb.Key):
test_path = TestPath(test)
else:
test_path = test.test_path
test_path_parts = test_path.split('/')
pattern_parts = pattern.split('/')
if len(test_path_parts) != len(pattern_parts):
return False
for test_path_part, pattern_part in zip(test_path_parts, pattern_parts):
if not _MatchesPatternPart(pattern_part, test_path_part):
return False
return True
def _MatchesPatternPart(pattern_part, test_path_part):
if pattern_part == '*' or pattern_part == test_path_part:
return True
if '*' not in pattern_part:
return False
pattern_part = re.escape(pattern_part)
re_pattern = re.compile('^' + pattern_part.replace('\\*', '.*') + '$')
return re_pattern.match(test_path_part)
def TimestampMilliseconds(datetime):
return int(time.mktime(datetime.timetuple()) * 1000)
def GetTestContainerKey(test):
test_path = None
if isinstance(test, ndb.Key):
test_path = TestPath(test)
else:
test_path = test.test_path
return ndb.Key('TestContainer', test_path)
def GetMulti(keys):
if IsInternalUser():
return ndb.get_multi(keys)
entities = []
for key in keys:
try:
entities.append(key.get())
except AssertionError:
continue
return entities
def MinimumAlertRange(alerts):
ranges = [(a.start_revision, a.end_revision) for a in alerts if a]
return MinimumRange(ranges)
def MinimumRange(ranges):
if not ranges:
return None
starts, ends = zip(*ranges)
start, end = (max(starts), min(ends))
if start > end:
return None
return start, end
def IsInternalUser():
if IsDevAppserver():
return True
email = GetEmail()
if not email:
return False
cached = GetCachedIsInternalUser(email)
if cached is not None:
return cached
is_internal_user = IsGroupMember(identity=email, group='chromeperf-access')
SetCachedIsInternalUser(email, is_internal_user)
return is_internal_user
def GetCachedIsInternalUser(email):
return memcache.get(_IsInternalUserCacheKey(email))
def SetCachedIsInternalUser(email, value):
memcache.add(_IsInternalUserCacheKey(email), value, time=60*60*24)
def _IsInternalUserCacheKey(email):
return 'is_internal_user_%s' % email
def IsGroupMember(identity, group):
cached = GetCachedIsGroupMember(identity, group)
if cached is not None:
return cached
try:
discovery_url = ('https://chrome-infra-auth.appspot.com'
'/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest')
service = discovery.build(
'auth', 'v1', discoveryServiceUrl=discovery_url,
http=ServiceAccountHttp())
request = service.membership(identity=identity, group=group)
response = request.execute()
is_member = response['is_member']
SetCachedIsGroupMember(identity, group, is_member)
return is_member
except (errors.HttpError, KeyError, AttributeError) as e:
logging.error('Failed to check membership of %s: %s', identity, e)
return False
def GetCachedIsGroupMember(identity, group):
return memcache.get(_IsGroupMemberCacheKey(identity, group))
def SetCachedIsGroupMember(identity, group, value):
memcache.add(_IsGroupMemberCacheKey(identity, group), value, time=60*60*24)
def _IsGroupMemberCacheKey(identity, group):
return 'is_group_member_%s_%s' % (identity, group)
def ServiceAccountHttp(scope=EMAIL_SCOPE, timeout=None):
account_details = stored_object.Get(SERVICE_ACCOUNT_KEY)
if not account_details:
raise KeyError('Service account credentials not found.')
assert scope, "ServiceAccountHttp scope must not be None."
client.logger.setLevel(logging.WARNING)
credentials = client.SignedJwtAssertionCredentials(
service_account_name=account_details['client_email'],
private_key=account_details['private_key'],
scope=scope)
http = httplib2.Http(timeout=timeout)
credentials.authorize(http)
return http
def IsValidSheriffUser():
email = GetEmail()
if not email:
return False
sheriff_domains = stored_object.Get(SHERIFF_DOMAINS_KEY)
domain_matched = sheriff_domains and any(
email.endswith('@' + domain) for domain in sheriff_domains)
return domain_matched or IsTryjobUser()
def IsTryjobUser():
email = GetEmail()
return bool(email) and IsGroupMember(
identity=email, group='project-chromium-tryjob-access')
def GetIpWhitelist():
return stored_object.Get(IP_WHITELIST_KEY)
def BisectConfigPythonString(config):
return 'config = %s\n' % json.dumps(
config, sort_keys=True, indent=2, separators=(',', ': '))
def GetRequestId():
return os.environ.get('REQUEST_LOG_ID')
def Validate(expected, actual):
def IsValidType(expected, actual):
if isinstance(expected, type) and not isinstance(actual, expected):
try:
expected(actual)
except ValueError:
return False
return True
def IsInList(expected, actual):
for value in expected:
try:
if type(value)(actual) == value:
return True
except ValueError:
pass
return False
if not expected:
return
expected_type = type(expected)
actual_type = type(actual)
if expected_type is list:
if not IsInList(expected, actual):
raise ValueError('Invalid value. Expected one of the following: '
'%s. Actual: %s.' % (','.join(expected), actual))
elif expected_type is dict:
if actual_type is not dict:
raise ValueError('Invalid type. Expected: %s. Actual: %s.'
% (expected_type, actual_type))
missing = set(expected.keys()) - set(actual.keys())
if missing:
raise ValueError('Missing the following properties: %s'
% ','.join(missing))
for key in expected:
Validate(expected[key], actual[key])
elif not IsValidType(expected, actual):
raise ValueError('Invalid type. Expected: %s. Actual: %s.' %
(expected, actual_type))
def FetchURL(request_url, skip_status_code=False):
logging.info('URL being fetched: ' + request_url)
try:
response = urlfetch.fetch(request_url)
except urlfetch_errors.DeadlineExceededError:
logging.error('Deadline exceeded error checking %s', request_url)
return None
except urlfetch_errors.DownloadError as err:
logging.error('DownloadError: %r', err)
return None
if skip_status_code:
return response
elif response.status_code != 200:
logging.error(
'ERROR %s checking %s', response.status_code, request_url)
return None
return response
def GetBuildDetailsFromStdioLink(stdio_link):
no_details = (None, None, None, None, None)
m = re.match(r'\[(.+?)\]\((.+?)\)', stdio_link)
if not m:
return no_details
_, link = m.groups()
m = re.match(
r'(https{0,1}://.*/([^\/]*)/builders/)'
r'([^\/]+)/builds/(\d+)/steps/([^\/]+)', link)
if not m:
# This wasn't a buildbot formatted link.
return no_details
base_url, master, bot, buildnumber, step = m.groups()
bot = urllib.unquote(bot)
return base_url, master, bot, buildnumber, step
def GetStdioLinkFromRow(row):
return(getattr(row, 'a_stdio_uri', None) or
getattr(row, 'a_a_stdio_uri', None))
def GetBuildbotStatusPageUriFromStdioLink(stdio_link):
base_url, _, bot, buildnumber, _ = GetBuildDetailsFromStdioLink(
stdio_link)
if not base_url:
return None
return '%s%s/builds/%s' % (base_url, urllib.quote(bot), buildnumber)
def GetLogdogLogUriFromStdioLink(stdio_link):
base_url, master, bot, buildnumber, step = GetBuildDetailsFromStdioLink(
stdio_link)
if not base_url:
# Can't parse status page
return None
bot = re.sub(r'[ \(\)]', '_', bot)
s_param = urllib.quote('chrome/bb/%s/%s/%s/+/recipes/steps/%s/0/stdout' % (
master, bot, buildnumber, step), safe='')
return 'https://luci-logdog.appspot.com/v/?s=%s' % s_param
def GetRowKey(testmetadata_key, revision):
test_container_key = GetTestContainerKey(testmetadata_key)
return ndb.Key('Row', revision, parent=test_container_key)
def GetSheriffForAutorollCommit(author, message):
if author.split('@')[-1] not in _AUTOROLL_DOMAINS:
return None
m = re.search(r'TBR=([^,^\s]*)', message)
if not m:
return None
return m.group(1)
| true | true |
1c2e5da54ed921047d2d2dc98db94232bc973fcc | 1,992 | py | Python | packages/Python/lldbsuite/test/commands/expression/import-std-module/stack/TestStack.py | xiaobai/swift-lldb | 9238527ce430e6837108a16d2a91b147551fb83c | [
"Apache-2.0"
] | 765 | 2015-12-03T16:44:59.000Z | 2022-03-07T12:41:10.000Z | packages/Python/lldbsuite/test/commands/expression/import-std-module/stack/TestStack.py | xiaobai/swift-lldb | 9238527ce430e6837108a16d2a91b147551fb83c | [
"Apache-2.0"
] | 1,815 | 2015-12-11T23:56:05.000Z | 2020-01-10T19:28:43.000Z | packages/Python/lldbsuite/test/commands/expression/import-std-module/stack/TestStack.py | xiaobai/swift-lldb | 9238527ce430e6837108a16d2a91b147551fb83c | [
"Apache-2.0"
] | 284 | 2015-12-03T16:47:25.000Z | 2022-03-12T05:39:48.000Z | """
Tests std::stack functionality.
"""
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class TestStack(TestBase):
mydir = TestBase.compute_mydir(__file__)
# FIXME: This should work on more setups, so remove these
# skipIf's in the future.
@add_test_categories(["libc++"])
@skipIf(compiler=no_match("clang"))
@skipIf(oslist=no_match(["linux"]))
@skipIf(debug_info=no_match(["dwarf"]))
def test(self):
self.build()
lldbutil.run_to_source_breakpoint(self,
"// Set break point at this line.", lldb.SBFileSpec("main.cpp"))
self.runCmd("settings set target.import-std-module true")
# Test std::stack functionality with a std::deque.
self.expect("expr s_deque.pop()")
self.expect("expr s_deque.push({4})")
self.expect("expr (size_t)s_deque.size()", substrs=['(size_t) $0 = 3'])
self.expect("expr (int)s_deque.top().i", substrs=['(int) $1 = 4'])
self.expect("expr s_deque.emplace(5)")
self.expect("expr (int)s_deque.top().i", substrs=['(int) $2 = 5'])
# Test std::stack functionality with a std::vector.
self.expect("expr s_vector.pop()")
self.expect("expr s_vector.push({4})")
self.expect("expr (size_t)s_vector.size()", substrs=['(size_t) $3 = 3'])
self.expect("expr (int)s_vector.top().i", substrs=['(int) $4 = 4'])
self.expect("expr s_vector.emplace(5)")
self.expect("expr (int)s_vector.top().i", substrs=['(int) $5 = 5'])
# Test std::stack functionality with a std::list.
self.expect("expr s_list.pop()")
self.expect("expr s_list.push({4})")
self.expect("expr (size_t)s_list.size()", substrs=['(size_t) $6 = 3'])
self.expect("expr (int)s_list.top().i", substrs=['(int) $7 = 4'])
self.expect("expr s_list.emplace(5)")
self.expect("expr (int)s_list.top().i", substrs=['(int) $8 = 5'])
| 39.84 | 80 | 0.611446 |
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class TestStack(TestBase):
mydir = TestBase.compute_mydir(__file__)
@add_test_categories(["libc++"])
@skipIf(compiler=no_match("clang"))
@skipIf(oslist=no_match(["linux"]))
@skipIf(debug_info=no_match(["dwarf"]))
def test(self):
self.build()
lldbutil.run_to_source_breakpoint(self,
"// Set break point at this line.", lldb.SBFileSpec("main.cpp"))
self.runCmd("settings set target.import-std-module true")
# Test std::stack functionality with a std::deque.
self.expect("expr s_deque.pop()")
self.expect("expr s_deque.push({4})")
self.expect("expr (size_t)s_deque.size()", substrs=['(size_t) $0 = 3'])
self.expect("expr (int)s_deque.top().i", substrs=['(int) $1 = 4'])
self.expect("expr s_deque.emplace(5)")
self.expect("expr (int)s_deque.top().i", substrs=['(int) $2 = 5'])
# Test std::stack functionality with a std::vector.
self.expect("expr s_vector.pop()")
self.expect("expr s_vector.push({4})")
self.expect("expr (size_t)s_vector.size()", substrs=['(size_t) $3 = 3'])
self.expect("expr (int)s_vector.top().i", substrs=['(int) $4 = 4'])
self.expect("expr s_vector.emplace(5)")
self.expect("expr (int)s_vector.top().i", substrs=['(int) $5 = 5'])
# Test std::stack functionality with a std::list.
self.expect("expr s_list.pop()")
self.expect("expr s_list.push({4})")
self.expect("expr (size_t)s_list.size()", substrs=['(size_t) $6 = 3'])
self.expect("expr (int)s_list.top().i", substrs=['(int) $7 = 4'])
self.expect("expr s_list.emplace(5)")
self.expect("expr (int)s_list.top().i", substrs=['(int) $8 = 5'])
| true | true |
1c2e5dc72d3bbd38b07704a9269c71b9217a32ae | 8,929 | py | Python | RE/grb2fig.py | reic/groupLearning-Python-100-Days | 91746e6ee3acf2dbf0e9d324f6c6ce3cb91ed131 | [
"MIT"
] | 4 | 2020-05-21T06:50:52.000Z | 2020-09-07T05:39:24.000Z | RE/grb2fig.py | reic/groupLearning-Python-100-Days | 91746e6ee3acf2dbf0e9d324f6c6ce3cb91ed131 | [
"MIT"
] | 1 | 2020-05-24T07:26:56.000Z | 2020-05-25T00:06:02.000Z | RE/grb2fig.py | reic/groupLearning-Python-100-Days | 91746e6ee3acf2dbf0e9d324f6c6ce3cb91ed131 | [
"MIT"
] | 1 | 2020-11-05T13:03:42.000Z | 2020-11-05T13:03:42.000Z | import pandas as pd
import os
import numpy as np
import matplotlib.pyplot as plt
import concurrent.futures
def grb_aggr(files, grb_xlsFileName):
dft = []
for file in files:
dft.append(pd.read_excel(file))
df = pd.concat(dft, ignore_index=True)
# 輸出合併檔
df.to_excel(grb_xlsFileName, index=False)
return df
def year_fig(df, category, grb_figdata, figout=0):
dft = pd.DataFrame(pd.pivot_table(df, index=category, values=[
'本期經費(千元)'], aggfunc={'本期經費(千元)': ["sum", "count"]}).to_records())
dft.rename(columns={"('本期經費(千元)', 'count')": "件數",
"('本期經費(千元)', 'sum')": "經費(千元)"}, inplace=True)
if isinstance(category, list):
index_name = category[0]
df2 = dft.pivot_table(index=index_name, columns="計畫年度", values=[
"件數", "經費(千元)"], fill_value=0)
# df2.columns.name = None
df2 = df2.reset_index()
df2.to_excel(
"{}/{}_件數_經費.xlsx".format(grb_figdata, category))
df2.to_excel(
"{}/{}_件數_經費.xlsx".format(grb_figdata, category))
return
dft.to_excel("{}/{}_件數_經費.xlsx".format(grb_figdata, category), index=False)
if figout:
year_fig2(dft[category], dft["件數"], category, "件數")
year_fig2(dft[category], dft["經費(千元)"], category, "經費(千元)")
def data_count(df, category):
dft = pd.DataFrame(pd.pivot_table(df, index=category, values=[
'本期經費(千元)'], aggfunc={'本期經費(千元)': ["sum", "count"]}).to_records())
dft.rename(columns={"('本期經費(千元)', 'count')": "件數",
"('本期經費(千元)', 'sum')": "經費(千元)"}, inplace=True)
return dft
def year_fig2(xdata, ydata, xlab, ylab, grb_figdata):
plt.rcParams['font.sans-serif'] = ['Microsoft JhengHei']
plt.plot(xdata, ydata)
plt.xlabel(xlab, fontsize=14)
plt.ylabel(ylab, fontsize=14)
plt.savefig("{}/{}_{}.png".format(grb_figdata, xlab, ylab))
plt.show()
def columnlinechart(writer, sheet_name, maxrow):
workbook = writer.book
worksheet = writer.sheets[sheet_name]
# Create a chart object.
chart = workbook.add_chart({'type': 'column'})
# Configure the series of the chart from the dataframe data.
chart.add_series({'name': f"={sheet_name}!C1", 'values': f"={sheet_name}!$C$2:$C${maxrow}",
"categories": f"={sheet_name}!$A$2:$A${maxrow}",
'fill': {'color': '#808080'}, 'data_labels': {'value': True}, 'gap': 15})
# 'type': 'column' 即為圖表類別為 line chart
line_chart = workbook.add_chart({'type': 'line'})
line_chart.add_series({'name': f"={sheet_name}!B1", "categories": f"={sheet_name}!$A$2:$A${maxrow}", 'values': f"={sheet_name}!$B$2:$B${maxrow}", 'data_labels': {'value': True, "position": "above"},
'y2_axis': True, "marker": {"type": "circle", "size": "9", "fill": {"color": "white"}}}) # 'y2_axis': 表示是否增加 secondary y-axis
chart.combine(line_chart) # 將兩張圖 (bar chart & line chart) 組合在一起
chart.set_legend({'position': 'top'}) # legend 位置於圖表下方
chart.set_x_axis({'major_gridlines': {'visible': False}})
chart.set_y_axis({'major_gridlines': {'visible': False}})
# Turn off chart legend. It is on by default in Excel.
# chart.set_legend({'position': 'none'})
chart.set_size({'width': 800, 'height': 500})
# Insert the chart into the worksheet.
worksheet.insert_chart('F2', chart)
def barchart(writer, sheet_name, maxrow, maxcolumn):
workbook = writer.book
worksheet = writer.sheets[sheet_name]
# Create a chart object.
chart = workbook.add_chart({'type': 'bar', 'subtype': 'percent_stacked'})
for itm in range(1, maxcolumn):
colname = chr(65+itm)
chart.add_series({"name": f"='{sheet_name}'!${colname}$1",
'categories': f"='{sheet_name}'!$A$2:$A${maxrow}",
"values": f"='{sheet_name}'!${colname}$2:${colname}${maxrow}"
})
chart.set_legend({'position': 'top'}) # legend 位置於圖表下方
chart.set_style(13)
chart.set_y_axis({'major_gridlines': {'visible': False}})
chart.set_x_axis({'major_gridlines': {'visible': False}})
chart.set_size({'width': 800, 'height': 500})
worksheet.insert_chart("F2", chart)
def piechart(writer, sheet_name, maxrow):
workbook = writer.book
worksheet = writer.sheets[sheet_name]
chart = workbook.add_chart({"type": "pie"})
chart.add_series({'categories': f"='{sheet_name}'!$A$2:$A${maxrow}",
"values": f"='{sheet_name}'!$C$2:$C${maxrow}",
'data_labels': {'category': True, 'percentage': True},
})
chart.set_legend({'position': 'left'}) # legend 位置於圖表下方
chart.set_style(13)
chart.set_size({'width': 800, 'height': 500})
worksheet.insert_chart("F2", chart)
def yeardiv(dfyears, period):
# dfyears 為 df["year"].values 的值
years = list(set(dfyears))
start = min(years)
grouplabel = [f"{itm}~{itm+period-1}" for itm in years[::period]]
groupyear = []
for itm in dfyears:
groupyear.append(grouplabel[(itm-start)//period])
return groupyear
def checkdict(context, wordDict):
if context in wordDict:
wordDict[context] += 1
else:
wordDict[context] = 1
def main(grb_dir):
print(grb_dir)
grb_xlsFileName = f"{grb_dir[:6]}_grb.xlsx"
outputfilename = f"{grb_dir[:6]}_output.xlsx"
# 取得下載 xlsx 所有檔案名稱
files = ["{}/{}".format(grb_dir, i) for i in os.listdir(grb_dir)]
# 執行 xslx 合併檔案
df = grb_aggr(files, grb_xlsFileName)
# df = pd.read_excel("D:/grb.xlsx")
# 資料處理的工作
# 僅取出 國科會、科技部的計畫
filterlist = ["行政院國家科學委員會", "科技部"]
df1 = df[df["計畫主管機關"].isin(filterlist)][['計畫中文名稱', '執行單位名稱', '計畫年度', '計畫主管機關', '研究性質', '研究領域', '本期期間(起)', '本期期間(訖)', '本期經費(千元)',
'計畫主持人', '共同/協同主持人', '中文關鍵詞', '英文關鍵詞']]
# 研究領域,僅取出第一個研究領域 分析
df1["主研究領域"] = [itm[0] for itm in df1["研究領域"].str.split(";").values]
# 執行機構名稱的清理
df1["執行單位_new"] = [str(itm[1]).replace("台灣", "臺灣") for itm in df1["執行單位名稱"].str.extract(
r'(國立|.*法人|行政院)?(.*大學|.*學院|.*研究院|.*學會|.*學校|原子能委員會|食品工業發展研究所|國家同步輻射研究中心|林業試驗所|中醫藥研究所)').values]
# 輸出整理過的檔案
df1.to_excel("{}_整理.xlsx".format(
grb_xlsFileName[:grb_xlsFileName.rfind(".")]), index=False)
with pd.ExcelWriter(outputfilename, engine='xlsxwriter') as writer:
tmp = data_count(df1, "計畫年度")
maxrow = len(tmp)+1
tmp.to_excel(writer, sheet_name="計畫年度", index=False)
columnlinechart(writer, "計畫年度", maxrow)
tmp = data_count(df, ["研究性質", "計畫年度"])
mask = tmp["研究性質"] == "其他"
tmp[~mask].to_excel(writer, sheet_name="研究性質with年度", index=False)
tmp = data_count(df1, ["研究性質", "計畫年度"])
mask = tmp["研究性質"] == "其他"
tmp = tmp[~mask]
tmp.to_excel(writer, sheet_name="MOST 研究性質with年度", index=False)
for j in [4, 3, 2]:
yearlen = len(set(tmp["計畫年度"].values))
if yearlen % j == 0:
divdat = yearlen//j
break
groupyear = yeardiv(tmp["計畫年度"].values, divdat)
tmp["計畫年度"] = groupyear
tmp = pd.DataFrame(pd.pivot_table(tmp, index="研究性質",
values="經費(千元)", columns=["計畫年度"]).to_records())
sindex = tmp.index.to_list()
sindex[0] = 4
tmp.index = sindex
tmp.sort_index(inplace=True)
tmp.to_excel(writer, sheet_name="MOST 研究性質 with 年度區間", index=False)
maxrow = len(tmp)+1
maxcolumn = len(tmp.columns)
barchart(writer, "MOST 研究性質 with 年度區間", maxrow, maxcolumn)
tmp = data_count(df1, "主研究領域")
tmp.sort_values("經費(千元)", ascending=False, inplace=True)
maxrow = len(tmp)+1
tmp.to_excel(writer, "主研究領域", index=False)
if maxrow > 13:
maxrow = 13
piechart(writer, "主研究領域", maxrow)
sheetname = "執行單位_new"
tmp = data_count(df1, sheetname)
tmp.sort_values("經費(千元)", ascending=False, inplace=True)
maxrow = len(tmp)+1
tmp.to_excel(writer, sheet_name=sheetname, index=False)
if maxrow > 25:
maxrow = 25
piechart(writer, sheetname, maxrow)
if __name__ == "__main__":
# 定義區
# 設定工作目錄
working_dir = "d:/tmp"
txt_data = "txt"
os.chdir(working_dir)
grb_dirs = ["solarcell", "hydrogen",
"storeenergy", 'sysintegrate', 'windturbine']
# # 做圖用的 xlsx 分檔的輸出位置
grb_figdata = "data2fig"
# # 建立 xlsx 輸出檔的存放目錄
try:
os.mkdir(txt_data)
except FileExistsError:
print("%s 的目標已存在" % txt_data)
try:
os.mkdir(grb_figdata)
except FileExistsError:
print("%s 的目標已存在" % grb_figdata)
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
executor.map(main, grb_dirs)
| 37.834746 | 202 | 0.586628 | import pandas as pd
import os
import numpy as np
import matplotlib.pyplot as plt
import concurrent.futures
def grb_aggr(files, grb_xlsFileName):
dft = []
for file in files:
dft.append(pd.read_excel(file))
df = pd.concat(dft, ignore_index=True)
df.to_excel(grb_xlsFileName, index=False)
return df
def year_fig(df, category, grb_figdata, figout=0):
dft = pd.DataFrame(pd.pivot_table(df, index=category, values=[
'本期經費(千元)'], aggfunc={'本期經費(千元)': ["sum", "count"]}).to_records())
dft.rename(columns={"('本期經費(千元)', 'count')": "件數",
"('本期經費(千元)', 'sum')": "經費(千元)"}, inplace=True)
if isinstance(category, list):
index_name = category[0]
df2 = dft.pivot_table(index=index_name, columns="計畫年度", values=[
"件數", "經費(千元)"], fill_value=0)
df2 = df2.reset_index()
df2.to_excel(
"{}/{}_件數_經費.xlsx".format(grb_figdata, category))
df2.to_excel(
"{}/{}_件數_經費.xlsx".format(grb_figdata, category))
return
dft.to_excel("{}/{}_件數_經費.xlsx".format(grb_figdata, category), index=False)
if figout:
year_fig2(dft[category], dft["件數"], category, "件數")
year_fig2(dft[category], dft["經費(千元)"], category, "經費(千元)")
def data_count(df, category):
dft = pd.DataFrame(pd.pivot_table(df, index=category, values=[
'本期經費(千元)'], aggfunc={'本期經費(千元)': ["sum", "count"]}).to_records())
dft.rename(columns={"('本期經費(千元)', 'count')": "件數",
"('本期經費(千元)', 'sum')": "經費(千元)"}, inplace=True)
return dft
def year_fig2(xdata, ydata, xlab, ylab, grb_figdata):
plt.rcParams['font.sans-serif'] = ['Microsoft JhengHei']
plt.plot(xdata, ydata)
plt.xlabel(xlab, fontsize=14)
plt.ylabel(ylab, fontsize=14)
plt.savefig("{}/{}_{}.png".format(grb_figdata, xlab, ylab))
plt.show()
def columnlinechart(writer, sheet_name, maxrow):
workbook = writer.book
worksheet = writer.sheets[sheet_name]
chart = workbook.add_chart({'type': 'column'})
chart.add_series({'name': f"={sheet_name}!C1", 'values': f"={sheet_name}!$C$2:$C${maxrow}",
"categories": f"={sheet_name}!$A$2:$A${maxrow}",
'fill': {'color': '#808080'}, 'data_labels': {'value': True}, 'gap': 15})
line_chart = workbook.add_chart({'type': 'line'})
line_chart.add_series({'name': f"={sheet_name}!B1", "categories": f"={sheet_name}!$A$2:$A${maxrow}", 'values': f"={sheet_name}!$B$2:$B${maxrow}", 'data_labels': {'value': True, "position": "above"},
'y2_axis': True, "marker": {"type": "circle", "size": "9", "fill": {"color": "white"}}})
chart.combine(line_chart)
chart.set_legend({'position': 'top'})
chart.set_x_axis({'major_gridlines': {'visible': False}})
chart.set_y_axis({'major_gridlines': {'visible': False}})
chart.set_size({'width': 800, 'height': 500})
worksheet.insert_chart('F2', chart)
def barchart(writer, sheet_name, maxrow, maxcolumn):
workbook = writer.book
worksheet = writer.sheets[sheet_name]
chart = workbook.add_chart({'type': 'bar', 'subtype': 'percent_stacked'})
for itm in range(1, maxcolumn):
colname = chr(65+itm)
chart.add_series({"name": f"='{sheet_name}'!${colname}$1",
'categories': f"='{sheet_name}'!$A$2:$A${maxrow}",
"values": f"='{sheet_name}'!${colname}$2:${colname}${maxrow}"
})
chart.set_legend({'position': 'top'})
chart.set_style(13)
chart.set_y_axis({'major_gridlines': {'visible': False}})
chart.set_x_axis({'major_gridlines': {'visible': False}})
chart.set_size({'width': 800, 'height': 500})
worksheet.insert_chart("F2", chart)
def piechart(writer, sheet_name, maxrow):
workbook = writer.book
worksheet = writer.sheets[sheet_name]
chart = workbook.add_chart({"type": "pie"})
chart.add_series({'categories': f"='{sheet_name}'!$A$2:$A${maxrow}",
"values": f"='{sheet_name}'!$C$2:$C${maxrow}",
'data_labels': {'category': True, 'percentage': True},
})
chart.set_legend({'position': 'left'})
chart.set_style(13)
chart.set_size({'width': 800, 'height': 500})
worksheet.insert_chart("F2", chart)
def yeardiv(dfyears, period):
years = list(set(dfyears))
start = min(years)
grouplabel = [f"{itm}~{itm+period-1}" for itm in years[::period]]
groupyear = []
for itm in dfyears:
groupyear.append(grouplabel[(itm-start)//period])
return groupyear
def checkdict(context, wordDict):
if context in wordDict:
wordDict[context] += 1
else:
wordDict[context] = 1
def main(grb_dir):
print(grb_dir)
grb_xlsFileName = f"{grb_dir[:6]}_grb.xlsx"
outputfilename = f"{grb_dir[:6]}_output.xlsx"
files = ["{}/{}".format(grb_dir, i) for i in os.listdir(grb_dir)]
df = grb_aggr(files, grb_xlsFileName)
filterlist = ["行政院國家科學委員會", "科技部"]
df1 = df[df["計畫主管機關"].isin(filterlist)][['計畫中文名稱', '執行單位名稱', '計畫年度', '計畫主管機關', '研究性質', '研究領域', '本期期間(起)', '本期期間(訖)', '本期經費(千元)',
'計畫主持人', '共同/協同主持人', '中文關鍵詞', '英文關鍵詞']]
df1["主研究領域"] = [itm[0] for itm in df1["研究領域"].str.split(";").values]
df1["執行單位_new"] = [str(itm[1]).replace("台灣", "臺灣") for itm in df1["執行單位名稱"].str.extract(
r'(國立|.*法人|行政院)?(.*大學|.*學院|.*研究院|.*學會|.*學校|原子能委員會|食品工業發展研究所|國家同步輻射研究中心|林業試驗所|中醫藥研究所)').values]
df1.to_excel("{}_整理.xlsx".format(
grb_xlsFileName[:grb_xlsFileName.rfind(".")]), index=False)
with pd.ExcelWriter(outputfilename, engine='xlsxwriter') as writer:
tmp = data_count(df1, "計畫年度")
maxrow = len(tmp)+1
tmp.to_excel(writer, sheet_name="計畫年度", index=False)
columnlinechart(writer, "計畫年度", maxrow)
tmp = data_count(df, ["研究性質", "計畫年度"])
mask = tmp["研究性質"] == "其他"
tmp[~mask].to_excel(writer, sheet_name="研究性質with年度", index=False)
tmp = data_count(df1, ["研究性質", "計畫年度"])
mask = tmp["研究性質"] == "其他"
tmp = tmp[~mask]
tmp.to_excel(writer, sheet_name="MOST 研究性質with年度", index=False)
for j in [4, 3, 2]:
yearlen = len(set(tmp["計畫年度"].values))
if yearlen % j == 0:
divdat = yearlen//j
break
groupyear = yeardiv(tmp["計畫年度"].values, divdat)
tmp["計畫年度"] = groupyear
tmp = pd.DataFrame(pd.pivot_table(tmp, index="研究性質",
values="經費(千元)", columns=["計畫年度"]).to_records())
sindex = tmp.index.to_list()
sindex[0] = 4
tmp.index = sindex
tmp.sort_index(inplace=True)
tmp.to_excel(writer, sheet_name="MOST 研究性質 with 年度區間", index=False)
maxrow = len(tmp)+1
maxcolumn = len(tmp.columns)
barchart(writer, "MOST 研究性質 with 年度區間", maxrow, maxcolumn)
tmp = data_count(df1, "主研究領域")
tmp.sort_values("經費(千元)", ascending=False, inplace=True)
maxrow = len(tmp)+1
tmp.to_excel(writer, "主研究領域", index=False)
if maxrow > 13:
maxrow = 13
piechart(writer, "主研究領域", maxrow)
sheetname = "執行單位_new"
tmp = data_count(df1, sheetname)
tmp.sort_values("經費(千元)", ascending=False, inplace=True)
maxrow = len(tmp)+1
tmp.to_excel(writer, sheet_name=sheetname, index=False)
if maxrow > 25:
maxrow = 25
piechart(writer, sheetname, maxrow)
if __name__ == "__main__":
working_dir = "d:/tmp"
txt_data = "txt"
os.chdir(working_dir)
grb_dirs = ["solarcell", "hydrogen",
"storeenergy", 'sysintegrate', 'windturbine']
"data2fig"
os.mkdir(txt_data)
except FileExistsError:
print("%s 的目標已存在" % txt_data)
try:
os.mkdir(grb_figdata)
except FileExistsError:
print("%s 的目標已存在" % grb_figdata)
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
executor.map(main, grb_dirs)
| true | true |
1c2e5de7d7bc7f5f29dee40434b610461ea5fa0b | 8,903 | py | Python | ludwig/serve.py | majacQ/ludwig | 237d832b85d224ef6d1ea53eface5479449caba3 | [
"Apache-2.0"
] | null | null | null | ludwig/serve.py | majacQ/ludwig | 237d832b85d224ef6d1ea53eface5479449caba3 | [
"Apache-2.0"
] | null | null | null | ludwig/serve.py | majacQ/ludwig | 237d832b85d224ef6d1ea53eface5479449caba3 | [
"Apache-2.0"
] | null | null | null | #! /usr/bin/env python
# coding=utf-8
# Copyright (c) 2019 Uber Technologies, 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 argparse
import json
import logging
import os
import sys
import tempfile
import pandas as pd
from imageio import imread
from ludwig.api import LudwigModel
from ludwig.constants import COLUMN, AUDIO
from ludwig.contrib import contrib_command, contrib_import
from ludwig.globals import LUDWIG_VERSION
from ludwig.utils.print_utils import logging_level_registry, print_ludwig
logger = logging.getLogger(__name__)
try:
import uvicorn
from fastapi import FastAPI
from starlette.datastructures import UploadFile
from starlette.middleware import Middleware
from starlette.middleware.cors import CORSMiddleware
from starlette.requests import Request
from starlette.responses import JSONResponse
except ImportError as e:
logger.error(e)
logger.error(
' fastapi and other serving dependencies cannot be loaded'
'and may have not been installed. '
'In order to install all serving dependencies run '
'pip install ludwig[serve]'
)
sys.exit(-1)
ALL_FEATURES_PRESENT_ERROR = {"error": "entry must contain all input features"}
COULD_NOT_RUN_INFERENCE_ERROR = {
"error": "Unexpected Error: could not run inference on model"}
def server(model, allowed_origins=None):
middleware = [
Middleware(CORSMiddleware, allow_origins=allowed_origins)
] if allowed_origins else None
app = FastAPI(middleware=middleware)
input_features = {
f[COLUMN] for f in model.config['input_features']
}
@app.get('/')
def check_health():
return JSONResponse({"message": "Ludwig server is up"})
@app.post('/predict')
async def predict(request: Request):
try:
form = await request.form()
entry, files = convert_input(
form,
model.model.input_features
)
except Exception:
logger.exception("Failed to parse predict form")
return JSONResponse(COULD_NOT_RUN_INFERENCE_ERROR,
status_code=500)
try:
if (entry.keys() & input_features) != input_features:
return JSONResponse(ALL_FEATURES_PRESENT_ERROR,
status_code=400)
try:
resp, _ = model.predict(
dataset=[entry], data_format=dict
)
resp = resp.to_dict('records')[0]
return JSONResponse(resp)
except Exception as exc:
logger.exception("Failed to run predict: {}".format(exc))
return JSONResponse(COULD_NOT_RUN_INFERENCE_ERROR,
status_code=500)
finally:
for f in files:
os.remove(f.name)
@app.post('/batch_predict')
async def batch_predict(request: Request):
try:
form = await request.form()
data, files = convert_batch_input(
form,
model.model.input_features
)
data_df = pd.DataFrame.from_records(data['data'],
index=data.get('index'),
columns=data['columns'])
except Exception:
logger.exception("Failed to parse batch_predict form")
return JSONResponse(COULD_NOT_RUN_INFERENCE_ERROR,
status_code=500)
if (set(data_df.columns) & input_features) != input_features:
return JSONResponse(ALL_FEATURES_PRESENT_ERROR,
status_code=400)
try:
resp, _ = model.predict(dataset=data_df)
resp = resp.to_dict('split')
return JSONResponse(resp)
except Exception:
logger.exception("Failed to run batch_predict: {}")
return JSONResponse(COULD_NOT_RUN_INFERENCE_ERROR,
status_code=500)
return app
def _write_file(v, files):
# Convert UploadFile to a NamedTemporaryFile to ensure it's on the disk
suffix = os.path.splitext(v.filename)[1]
named_file = tempfile.NamedTemporaryFile(
delete=False, suffix=suffix)
files.append(named_file)
named_file.write(v.file.read())
named_file.close()
return named_file.name
def _read_image_buffer(v):
# get image format type, e.g., 'jpg', 'png', etc.
image_type_suffix = os.path.splitext(v.filename)[1][1:]
# read in file buffer to obtain ndarray of image
return imread(v.file.read(), image_type_suffix)
def convert_input(form, input_features):
"""Returns a new input and a list of files to be cleaned up"""
new_input = {}
files = []
for k, v in form.multi_items():
if type(v) == UploadFile:
# check if audio or image file
if input_features[k].type == AUDIO:
new_input[k] = _write_file(v, files)
else:
new_input[k] = _read_image_buffer(v)
else:
new_input[k] = v
return new_input, files
def convert_batch_input(form, input_features):
"""Returns a new input and a list of files to be cleaned up"""
file_index = {}
files = []
for k, v in form.multi_items():
if type(v) == UploadFile:
file_index[v.filename] = v
data = json.loads(form['dataset'])
for row in data['data']:
for i in range(len(row)):
if row[i] in file_index:
feature_name = data['columns'][i]
if input_features[feature_name].type == AUDIO:
row[i] = _write_file(file_index[row[i]], files)
else:
row[i] = _read_image_buffer(file_index[row[i]])
return data, files
def run_server(
model_path: str,
host: str,
port: int,
allowed_origins: list,
) -> None:
"""
Loads a pre-trained model and serve it on an http server.
# Inputs
:param model_path: (str) filepath to pre-trained model.
:param host: (str, default: `0.0.0.0`) host ip address for the server to use.
:param port: (int, default: `8000`) port number for the server to use.
:param allowed_origins: (list) list of origins allowed to make cross-origin requests.
# Return
:return: (`None`)
"""
model = LudwigModel.load(model_path)
app = server(model, allowed_origins)
uvicorn.run(app, host=host, port=port)
def cli(sys_argv):
parser = argparse.ArgumentParser(
description='This script serves a pretrained model',
prog='ludwig serve',
usage='%(prog)s [options]'
)
# ----------------
# Model parameters
# ----------------
parser.add_argument(
'-m',
'--model_path',
help='model to load',
required=True
)
parser.add_argument(
'-l',
'--logging_level',
default='info',
help='the level of logging to use',
choices=['critical', 'error', 'warning', 'info', 'debug', 'notset']
)
# ----------------
# Server parameters
# ----------------
parser.add_argument(
'-p',
'--port',
help='port for server (default: 8000)',
default=8000,
type=int,
)
parser.add_argument(
'-H',
'--host',
help='host for server (default: 0.0.0.0)',
default='0.0.0.0'
)
parser.add_argument(
'-ao',
'--allowed_origins',
nargs='*',
help='A list of origins that should be permitted to make cross-origin requests. '
'Use "*" to allow any origin. See https://www.starlette.io/middleware/#corsmiddleware.',
)
args = parser.parse_args(sys_argv)
args.logging_level = logging_level_registry[args.logging_level]
logging.getLogger('ludwig').setLevel(
args.logging_level
)
global logger
logger = logging.getLogger('ludwig.serve')
print_ludwig('Serve', LUDWIG_VERSION)
run_server(args.model_path, args.host, args.port, args.allowed_origins)
if __name__ == '__main__':
contrib_import()
contrib_command("serve", *sys.argv)
cli(sys.argv[1:])
| 31.129371 | 101 | 0.599124 |
import argparse
import json
import logging
import os
import sys
import tempfile
import pandas as pd
from imageio import imread
from ludwig.api import LudwigModel
from ludwig.constants import COLUMN, AUDIO
from ludwig.contrib import contrib_command, contrib_import
from ludwig.globals import LUDWIG_VERSION
from ludwig.utils.print_utils import logging_level_registry, print_ludwig
logger = logging.getLogger(__name__)
try:
import uvicorn
from fastapi import FastAPI
from starlette.datastructures import UploadFile
from starlette.middleware import Middleware
from starlette.middleware.cors import CORSMiddleware
from starlette.requests import Request
from starlette.responses import JSONResponse
except ImportError as e:
logger.error(e)
logger.error(
' fastapi and other serving dependencies cannot be loaded'
'and may have not been installed. '
'In order to install all serving dependencies run '
'pip install ludwig[serve]'
)
sys.exit(-1)
ALL_FEATURES_PRESENT_ERROR = {"error": "entry must contain all input features"}
COULD_NOT_RUN_INFERENCE_ERROR = {
"error": "Unexpected Error: could not run inference on model"}
def server(model, allowed_origins=None):
middleware = [
Middleware(CORSMiddleware, allow_origins=allowed_origins)
] if allowed_origins else None
app = FastAPI(middleware=middleware)
input_features = {
f[COLUMN] for f in model.config['input_features']
}
@app.get('/')
def check_health():
return JSONResponse({"message": "Ludwig server is up"})
@app.post('/predict')
async def predict(request: Request):
try:
form = await request.form()
entry, files = convert_input(
form,
model.model.input_features
)
except Exception:
logger.exception("Failed to parse predict form")
return JSONResponse(COULD_NOT_RUN_INFERENCE_ERROR,
status_code=500)
try:
if (entry.keys() & input_features) != input_features:
return JSONResponse(ALL_FEATURES_PRESENT_ERROR,
status_code=400)
try:
resp, _ = model.predict(
dataset=[entry], data_format=dict
)
resp = resp.to_dict('records')[0]
return JSONResponse(resp)
except Exception as exc:
logger.exception("Failed to run predict: {}".format(exc))
return JSONResponse(COULD_NOT_RUN_INFERENCE_ERROR,
status_code=500)
finally:
for f in files:
os.remove(f.name)
@app.post('/batch_predict')
async def batch_predict(request: Request):
try:
form = await request.form()
data, files = convert_batch_input(
form,
model.model.input_features
)
data_df = pd.DataFrame.from_records(data['data'],
index=data.get('index'),
columns=data['columns'])
except Exception:
logger.exception("Failed to parse batch_predict form")
return JSONResponse(COULD_NOT_RUN_INFERENCE_ERROR,
status_code=500)
if (set(data_df.columns) & input_features) != input_features:
return JSONResponse(ALL_FEATURES_PRESENT_ERROR,
status_code=400)
try:
resp, _ = model.predict(dataset=data_df)
resp = resp.to_dict('split')
return JSONResponse(resp)
except Exception:
logger.exception("Failed to run batch_predict: {}")
return JSONResponse(COULD_NOT_RUN_INFERENCE_ERROR,
status_code=500)
return app
def _write_file(v, files):
suffix = os.path.splitext(v.filename)[1]
named_file = tempfile.NamedTemporaryFile(
delete=False, suffix=suffix)
files.append(named_file)
named_file.write(v.file.read())
named_file.close()
return named_file.name
def _read_image_buffer(v):
# get image format type, e.g., 'jpg', 'png', etc.
image_type_suffix = os.path.splitext(v.filename)[1][1:]
# read in file buffer to obtain ndarray of image
return imread(v.file.read(), image_type_suffix)
def convert_input(form, input_features):
new_input = {}
files = []
for k, v in form.multi_items():
if type(v) == UploadFile:
# check if audio or image file
if input_features[k].type == AUDIO:
new_input[k] = _write_file(v, files)
else:
new_input[k] = _read_image_buffer(v)
else:
new_input[k] = v
return new_input, files
def convert_batch_input(form, input_features):
file_index = {}
files = []
for k, v in form.multi_items():
if type(v) == UploadFile:
file_index[v.filename] = v
data = json.loads(form['dataset'])
for row in data['data']:
for i in range(len(row)):
if row[i] in file_index:
feature_name = data['columns'][i]
if input_features[feature_name].type == AUDIO:
row[i] = _write_file(file_index[row[i]], files)
else:
row[i] = _read_image_buffer(file_index[row[i]])
return data, files
def run_server(
model_path: str,
host: str,
port: int,
allowed_origins: list,
) -> None:
model = LudwigModel.load(model_path)
app = server(model, allowed_origins)
uvicorn.run(app, host=host, port=port)
def cli(sys_argv):
parser = argparse.ArgumentParser(
description='This script serves a pretrained model',
prog='ludwig serve',
usage='%(prog)s [options]'
)
# ----------------
# Model parameters
# ----------------
parser.add_argument(
'-m',
'--model_path',
help='model to load',
required=True
)
parser.add_argument(
'-l',
'--logging_level',
default='info',
help='the level of logging to use',
choices=['critical', 'error', 'warning', 'info', 'debug', 'notset']
)
# ----------------
# Server parameters
# ----------------
parser.add_argument(
'-p',
'--port',
help='port for server (default: 8000)',
default=8000,
type=int,
)
parser.add_argument(
'-H',
'--host',
help='host for server (default: 0.0.0.0)',
default='0.0.0.0'
)
parser.add_argument(
'-ao',
'--allowed_origins',
nargs='*',
help='A list of origins that should be permitted to make cross-origin requests. '
'Use "*" to allow any origin. See https://www.starlette.io/middleware/
)
args = parser.parse_args(sys_argv)
args.logging_level = logging_level_registry[args.logging_level]
logging.getLogger('ludwig').setLevel(
args.logging_level
)
global logger
logger = logging.getLogger('ludwig.serve')
print_ludwig('Serve', LUDWIG_VERSION)
run_server(args.model_path, args.host, args.port, args.allowed_origins)
if __name__ == '__main__':
contrib_import()
contrib_command("serve", *sys.argv)
cli(sys.argv[1:])
| true | true |
1c2e5e21c0f2b7137d89603c9202cf6fefca9953 | 1,837 | py | Python | server/main/management/commands/fix_permissions.py | coll-gate/collgate | 8c2ff1c59adda2bf318040f588c05263317a2812 | [
"MIT"
] | 2 | 2017-07-04T16:19:09.000Z | 2019-08-16T04:54:47.000Z | server/main/management/commands/fix_permissions.py | coll-gate/collgate | 8c2ff1c59adda2bf318040f588c05263317a2812 | [
"MIT"
] | null | null | null | server/main/management/commands/fix_permissions.py | coll-gate/collgate | 8c2ff1c59adda2bf318040f588c05263317a2812 | [
"MIT"
] | 1 | 2018-04-13T08:28:09.000Z | 2018-04-13T08:28:09.000Z | # -*- coding: utf-8; -*-
#
# @file fix_permissions.py
# @brief
# @author Frédéric SCHERMA (INRA UMR1095)
# @date 2016-09-01
# @copyright Copyright (c) 2016 INRA/CIRAD
# @license MIT (see LICENSE file)
# @details
"""Add permissions for proxy model.
This is needed because of the bug https://code.djangoproject.com/ticket/11154
in Django (as of 1.6, it's not fixed).
When a permission is created for a proxy model, it actually creates if for it's
base model app_label (eg: for "article" instead of "about", for the About proxy
model).
What we need, however, is that the permission be created for the proxy model
itself, in order to have the proper entries displayed in the admin.
"""
from __future__ import unicode_literals, absolute_import, division
import sys
from django.contrib.auth.management import _get_all_permissions
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.core.management.base import BaseCommand
from django.apps import apps
from django.utils.encoding import smart_text
class Command(BaseCommand):
help = "Fix permissions for proxy models."
def handle(self, *args, **options):
for model in apps.get_models():
opts = model._meta
ctype, created = ContentType.objects.get_or_create(
app_label=opts.app_label,
model=opts.object_name.lower(),
defaults={'name': smart_text(opts.verbose_name_raw)})
for codename, name in _get_all_permissions(opts, ctype):
p, created = Permission.objects.get_or_create(
codename=codename,
content_type=ctype,
defaults={'name': name})
if created:
sys.stdout.write('Adding permission {}\n'.format(p))
| 35.326923 | 79 | 0.684812 |
from __future__ import unicode_literals, absolute_import, division
import sys
from django.contrib.auth.management import _get_all_permissions
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.core.management.base import BaseCommand
from django.apps import apps
from django.utils.encoding import smart_text
class Command(BaseCommand):
help = "Fix permissions for proxy models."
def handle(self, *args, **options):
for model in apps.get_models():
opts = model._meta
ctype, created = ContentType.objects.get_or_create(
app_label=opts.app_label,
model=opts.object_name.lower(),
defaults={'name': smart_text(opts.verbose_name_raw)})
for codename, name in _get_all_permissions(opts, ctype):
p, created = Permission.objects.get_or_create(
codename=codename,
content_type=ctype,
defaults={'name': name})
if created:
sys.stdout.write('Adding permission {}\n'.format(p))
| true | true |
1c2e5e917fc2f3c6f9a285d882f2ed99ff462e22 | 7,277 | py | Python | scripts_dql/script17.py | lbaiao/sys-simulator-2 | 94f00d43309fe7b56dac5099bd4024695ba317b6 | [
"MIT"
] | 1 | 2020-06-14T13:50:28.000Z | 2020-06-14T13:50:28.000Z | scripts_dql/script17.py | lbaiao/sys-simulator-2 | 94f00d43309fe7b56dac5099bd4024695ba317b6 | [
"MIT"
] | null | null | null | scripts_dql/script17.py | lbaiao/sys-simulator-2 | 94f00d43309fe7b56dac5099bd4024695ba317b6 | [
"MIT"
] | null | null | null | # Same as script 15, but there are only 5 actions options, hence the DQN has a smaller output layer.
import sys
import os
lucas_path = os.environ['LUCAS_PATH']
sys.path.insert(1, lucas_path)
from general import general as gen
from devices.devices import node, base_station, mobile_user, d2d_user, d2d_node_type
from pathloss import pathloss
from plots.plots import plot_positions, plot_spectral_effs
from q_learning.environments.completeEnvironment import CompleteEnvironment
from dqn.agents.dqnAgent import ExternalDQNAgent
from dqn.externalDQNFramework import ExternalDQNFramework
from dqn.replayMemory import ReplayMemory
from dqn.dqn import DQN
from q_learning.q_table import DistributedQTable
from q_learning import rewards
from parameters.parameters import EnvironmentParameters, TrainingParameters, DQNAgentParameters, LearningParameters
from typing import List
from matplotlib import pyplot as plt
import torch
import math
import numpy as np
import os
import pickle
n_mues = 1 # number of mues
n_d2d = 2 # number of d2d pairs
n_rb = n_mues # number of RBs
bs_radius = 500 # bs radius in m
rb_bandwidth = 180*1e3 # rb bandwidth in Hz
d2d_pair_distance = 50 # d2d pair distance in m
p_max = 23 # max tx power in dBm
noise_power = -116 # noise power per RB in dBm
bs_gain = 17 # macro bs antenna gain in dBi
user_gain = 4 # user antenna gain in dBi
sinr_threshold_train = 6 # mue sinr threshold in dB for training
sinr_threshold_mue = 6 # true mue sinr threshold in dB
mue_margin = .5e4
# conversions from dB to pow
p_max = p_max - 30
p_max = gen.db_to_power(p_max)
noise_power = noise_power - 30
noise_power = gen.db_to_power(noise_power)
bs_gain = gen.db_to_power(bs_gain)
user_gain = gen.db_to_power(user_gain)
sinr_threshold_train = gen.db_to_power(sinr_threshold_train)
# q-learning parameters
STEPS_PER_EPISODE = 25
EPSILON_MIN = 0.05
# MAX_NUM_STEPS = 50
# EPSILON_DECAY = 0.4045*1e-4 # super long training
# EPSILON_DECAY = 0.809*1e-4 # long training
# EPSILON_DECAY = 0.809*1e-4 # medium training
EPSILON_DECAY = 3.35*1e-4 # medium training
# EPSILON_DECAY = 8.09*1e-4 # short training
# MAX_NUM_EPISODES = 40000 # super long training
# MAX_NUM_EPISODES = 20000 # long training
MAX_NUM_EPISODES = 480 # medium training
# MAX_NUM_EPISODES = 480 # medium training
# MAX_NUM_EPISODES = 2000 # short training
ALPHA = 0.05 # Learning rate
GAMMA = 0.98 # Discount factor
# C = 8000 # C constant for the improved reward function
C = 80 # C constant for the improved reward function
TARGET_UPDATE = 10
MAX_NUMBER_OF_AGENTS = 20
# more parameters
env_params = EnvironmentParameters(rb_bandwidth, d2d_pair_distance, p_max, noise_power, bs_gain, user_gain, sinr_threshold_train,
n_mues, n_d2d, n_rb, bs_radius, c_param=C, mue_margin=mue_margin)
train_params = TrainingParameters(MAX_NUM_EPISODES, STEPS_PER_EPISODE)
agent_params = DQNAgentParameters(EPSILON_MIN, EPSILON_DECAY, 1, 512, GAMMA)
ext_framework = ExternalDQNFramework(agent_params)
# actions = [i*p_max/10/1000 for i in range(21)] # worst
# actions = [i*0.80*p_max/10/1000 for i in range(21)] # best histogram
reward_function = rewards.dis_reward_tensor
# environment = CompleteEnvironment(env_params, reward_function, early_stop=1e-6, tolerance=10)
environment = CompleteEnvironment(env_params, reward_function)
# training function
# TODO: colocar agente e d2d_device na mesma classe? fazer propriedade d2d_device no agente?
def train(framework: ExternalDQNFramework, env: CompleteEnvironment, params: TrainingParameters, agent_params: DQNAgentParameters, max_d2d: int):
best_reward = float('-inf')
device = torch.device('cuda')
mue_spectral_eff_bag = list()
d2d_spectral_eff_bag = list()
aux_range = range(max_d2d)[1:]
epsilon = agent_params.start_epsilon
for episode in range(params.max_episodes):
# TODO: atualmente redistribuo os usuarios aleatoriamente a cada episodio. Isto é o melhor há se fazer?
# Simular deslocamento dos usuários?
actions = [i*0.82*p_max/5/1000 for i in range(5)] # best result
n_agents = np.random.choice(aux_range)
agents = [ExternalDQNAgent(agent_params, actions) for i in range(n_agents)] # 1 agent per d2d tx
counts = np.zeros(len(agents))
awaits = list()
await_steps = [2,3,4]
for a in agents:
awaits.append(np.random.choice(await_steps))
a.set_action(torch.tensor(0).long().cuda(), a.actions[0])
a.set_epsilon(epsilon)
env.build_scenario(agents)
done = False
obs = [env.get_state(a) for a in agents]
total_reward = 0.0
i = 0
bag = list()
while not done:
if i >= params.steps_per_episode:
break
else:
actions = torch.zeros([len(agents)], device=device)
for j, agent in enumerate(agents):
if counts[j] < awaits[j]:
counts[j] += 1
else:
agent.get_action(framework, obs[j])
actions[j] = agent.action_index
counts[j] = 0
awaits[j] = np.random.choice(await_steps)
next_obs, rewards, done = env.step(agents)
i += 1
for j, agent in enumerate(agents):
framework.replay_memory.push(obs[j], actions[j], next_obs[j], rewards[j])
framework.learn()
obs = next_obs
total_reward += torch.sum(rewards)
bag.append(total_reward.item())
obs = next_obs
if episode % TARGET_UPDATE == 0:
framework.target_net.load_state_dict(framework.policy_net.state_dict())
if total_reward > best_reward:
best_reward = total_reward
print("Episode#:{} sum reward:{} best_sum_reward:{} eps:{}".format(episode,
total_reward, best_reward, agents[0].epsilon))
# some statistics
mue_spectral_eff_bag.append(env.mue_spectral_eff) # mue spectral eff
d2d_spectral_eff_bag.append(env.d2d_spectral_eff/env.params.n_d2d) # average d2d spectral eff
epsilon = agents[0].epsilon
# Return the trained policy
return mue_spectral_eff_bag, d2d_spectral_eff_bag
# SCRIPT EXEC
# training
mue_spectral_effs, d2d_spectral_effs = train(ext_framework, environment, train_params, agent_params, MAX_NUMBER_OF_AGENTS)
spectral_effs = zip(mue_spectral_effs, d2d_spectral_effs)
cwd = os.getcwd()
filename = gen.path_leaf(__file__)
filename = filename.split('.')[0]
filename_model = filename
filename = f'{lucas_path}/data/{filename}.pickle'
torch.save(ext_framework.policy_net.state_dict(), f'{lucas_path}/models/{filename_model}.pt')
with open(filename, 'wb') as f:
pickle.dump(spectral_effs, f)
plt.figure(1)
plt.plot(mue_spectral_effs, '.', label='MUEs')
plt.plot(d2d_spectral_effs, '.', label='D2Ds')
plt.xlabel('Iteration')
plt.ylabel('Average Spectral Efficiencies')
plt.legend()
plt.show()
| 39.983516 | 149 | 0.682699 |
import sys
import os
lucas_path = os.environ['LUCAS_PATH']
sys.path.insert(1, lucas_path)
from general import general as gen
from devices.devices import node, base_station, mobile_user, d2d_user, d2d_node_type
from pathloss import pathloss
from plots.plots import plot_positions, plot_spectral_effs
from q_learning.environments.completeEnvironment import CompleteEnvironment
from dqn.agents.dqnAgent import ExternalDQNAgent
from dqn.externalDQNFramework import ExternalDQNFramework
from dqn.replayMemory import ReplayMemory
from dqn.dqn import DQN
from q_learning.q_table import DistributedQTable
from q_learning import rewards
from parameters.parameters import EnvironmentParameters, TrainingParameters, DQNAgentParameters, LearningParameters
from typing import List
from matplotlib import pyplot as plt
import torch
import math
import numpy as np
import os
import pickle
n_mues = 1
n_d2d = 2
n_rb = n_mues
bs_radius = 500
rb_bandwidth = 180*1e3
d2d_pair_distance = 50
p_max = 23
noise_power = -116
bs_gain = 17
user_gain = 4
sinr_threshold_train = 6
sinr_threshold_mue = 6
mue_margin = .5e4
p_max = p_max - 30
p_max = gen.db_to_power(p_max)
noise_power = noise_power - 30
noise_power = gen.db_to_power(noise_power)
bs_gain = gen.db_to_power(bs_gain)
user_gain = gen.db_to_power(user_gain)
sinr_threshold_train = gen.db_to_power(sinr_threshold_train)
STEPS_PER_EPISODE = 25
EPSILON_MIN = 0.05
ters(rb_bandwidth, d2d_pair_distance, p_max, noise_power, bs_gain, user_gain, sinr_threshold_train,
n_mues, n_d2d, n_rb, bs_radius, c_param=C, mue_margin=mue_margin)
train_params = TrainingParameters(MAX_NUM_EPISODES, STEPS_PER_EPISODE)
agent_params = DQNAgentParameters(EPSILON_MIN, EPSILON_DECAY, 1, 512, GAMMA)
ext_framework = ExternalDQNFramework(agent_params)
ards.dis_reward_tensor
environment = CompleteEnvironment(env_params, reward_function)
def train(framework: ExternalDQNFramework, env: CompleteEnvironment, params: TrainingParameters, agent_params: DQNAgentParameters, max_d2d: int):
best_reward = float('-inf')
device = torch.device('cuda')
mue_spectral_eff_bag = list()
d2d_spectral_eff_bag = list()
aux_range = range(max_d2d)[1:]
epsilon = agent_params.start_epsilon
for episode in range(params.max_episodes):
actions = [i*0.82*p_max/5/1000 for i in range(5)]
n_agents = np.random.choice(aux_range)
agents = [ExternalDQNAgent(agent_params, actions) for i in range(n_agents)]
counts = np.zeros(len(agents))
awaits = list()
await_steps = [2,3,4]
for a in agents:
awaits.append(np.random.choice(await_steps))
a.set_action(torch.tensor(0).long().cuda(), a.actions[0])
a.set_epsilon(epsilon)
env.build_scenario(agents)
done = False
obs = [env.get_state(a) for a in agents]
total_reward = 0.0
i = 0
bag = list()
while not done:
if i >= params.steps_per_episode:
break
else:
actions = torch.zeros([len(agents)], device=device)
for j, agent in enumerate(agents):
if counts[j] < awaits[j]:
counts[j] += 1
else:
agent.get_action(framework, obs[j])
actions[j] = agent.action_index
counts[j] = 0
awaits[j] = np.random.choice(await_steps)
next_obs, rewards, done = env.step(agents)
i += 1
for j, agent in enumerate(agents):
framework.replay_memory.push(obs[j], actions[j], next_obs[j], rewards[j])
framework.learn()
obs = next_obs
total_reward += torch.sum(rewards)
bag.append(total_reward.item())
obs = next_obs
if episode % TARGET_UPDATE == 0:
framework.target_net.load_state_dict(framework.policy_net.state_dict())
if total_reward > best_reward:
best_reward = total_reward
print("Episode#:{} sum reward:{} best_sum_reward:{} eps:{}".format(episode,
total_reward, best_reward, agents[0].epsilon))
mue_spectral_eff_bag.append(env.mue_spectral_eff)
d2d_spectral_eff_bag.append(env.d2d_spectral_eff/env.params.n_d2d)
epsilon = agents[0].epsilon
return mue_spectral_eff_bag, d2d_spectral_eff_bag
mue_spectral_effs, d2d_spectral_effs = train(ext_framework, environment, train_params, agent_params, MAX_NUMBER_OF_AGENTS)
spectral_effs = zip(mue_spectral_effs, d2d_spectral_effs)
cwd = os.getcwd()
filename = gen.path_leaf(__file__)
filename = filename.split('.')[0]
filename_model = filename
filename = f'{lucas_path}/data/{filename}.pickle'
torch.save(ext_framework.policy_net.state_dict(), f'{lucas_path}/models/{filename_model}.pt')
with open(filename, 'wb') as f:
pickle.dump(spectral_effs, f)
plt.figure(1)
plt.plot(mue_spectral_effs, '.', label='MUEs')
plt.plot(d2d_spectral_effs, '.', label='D2Ds')
plt.xlabel('Iteration')
plt.ylabel('Average Spectral Efficiencies')
plt.legend()
plt.show()
| true | true |
1c2e5eaa434e78501ffc85e65c2a4f21a98ed90f | 2,009 | py | Python | tests/test_pyvmomi_tasks.py | NavyaPalle/vlab_inf_common | 2a220e5543c168f364adf3ab2677bcfd52e5beb3 | [
"Apache-2.0"
] | 1 | 2019-04-10T16:17:27.000Z | 2019-04-10T16:17:27.000Z | tests/test_pyvmomi_tasks.py | NavyaPalle/vlab_inf_common | 2a220e5543c168f364adf3ab2677bcfd52e5beb3 | [
"Apache-2.0"
] | 3 | 2019-03-28T17:39:36.000Z | 2019-05-22T17:08:35.000Z | tests/test_pyvmomi_tasks.py | NavyaPalle/vlab_inf_common | 2a220e5543c168f364adf3ab2677bcfd52e5beb3 | [
"Apache-2.0"
] | 1 | 2020-08-27T11:48:33.000Z | 2020-08-27T11:48:33.000Z | # -*- coding: UTF-8 -*-
"""Unittests for the vlab_inf_common.vmware.tasks module"""
import unittest
from unittest.mock import patch, MagicMock
import vlab_inf_common.vmware.tasks as task_lib
class TestConsumeTask(unittest.TestCase):
"""A set of test cases for the ``consume_task`` function"""
@patch.object(task_lib, 'time')
def test_happy_path(self, fake_time):
"""``consume_task`` - Works as expected when there are no issues"""
fake_task = MagicMock()
fake_task.info.error = None
fake_task.info.result = 'woot'
result = task_lib.consume_task(fake_task, timeout=2)
expected = 'woot'
self.assertEqual(result, expected)
@patch.object(task_lib, 'time')
def test_timeout(self, fake_time):
"""``consume_task`` raises RuntimeError if the task does not complete within the timeout"""
fake_task = MagicMock()
fake_task.info.completeTime = None
fake_task.info.error = None
fake_task.info.result = 'woot'
with self.assertRaises(RuntimeError):
task_lib.consume_task(fake_task, timeout=2)
@patch.object(task_lib, 'time')
def test_error(self, fake_time):
"""``consume_task`` - raises RuntimeError if the task complete with an error"""
fake_task = MagicMock()
fake_task.info.error.msg = 'someError'
fake_task.info.result = 'woot'
with self.assertRaises(RuntimeError):
task_lib.consume_task(fake_task, timeout=2)
@patch.object(task_lib, 'time')
def test_blocks(self, fake_time):
"""``consume_task`` - Blocks until the task is complete"""
fake_task = MagicMock()
fake_task.info.error = None
fake_task.info.result = 'woot'
fake_task.info.completeTime.side_effect = [None, 'someTimestamp']
result = task_lib.consume_task(fake_task, timeout=5)
expected = 'woot'
self.assertEqual(result, expected)
if __name__ == '__main__':
unittest.main()
| 33.483333 | 99 | 0.658537 |
import unittest
from unittest.mock import patch, MagicMock
import vlab_inf_common.vmware.tasks as task_lib
class TestConsumeTask(unittest.TestCase):
@patch.object(task_lib, 'time')
def test_happy_path(self, fake_time):
fake_task = MagicMock()
fake_task.info.error = None
fake_task.info.result = 'woot'
result = task_lib.consume_task(fake_task, timeout=2)
expected = 'woot'
self.assertEqual(result, expected)
@patch.object(task_lib, 'time')
def test_timeout(self, fake_time):
fake_task = MagicMock()
fake_task.info.completeTime = None
fake_task.info.error = None
fake_task.info.result = 'woot'
with self.assertRaises(RuntimeError):
task_lib.consume_task(fake_task, timeout=2)
@patch.object(task_lib, 'time')
def test_error(self, fake_time):
fake_task = MagicMock()
fake_task.info.error.msg = 'someError'
fake_task.info.result = 'woot'
with self.assertRaises(RuntimeError):
task_lib.consume_task(fake_task, timeout=2)
@patch.object(task_lib, 'time')
def test_blocks(self, fake_time):
fake_task = MagicMock()
fake_task.info.error = None
fake_task.info.result = 'woot'
fake_task.info.completeTime.side_effect = [None, 'someTimestamp']
result = task_lib.consume_task(fake_task, timeout=5)
expected = 'woot'
self.assertEqual(result, expected)
if __name__ == '__main__':
unittest.main()
| true | true |
1c2e5f1a6f2675d5bde9f8ba22a467e54251eb41 | 1,279 | py | Python | Module02/Guess_the_Primer.py | biomed-bioinformatics-bootcamp/bmes-t580-2019-coursework-Nathan-Ona | e09f761f837ba7c6c2bfa223a9ed9e987b6260be | [
"MIT"
] | null | null | null | Module02/Guess_the_Primer.py | biomed-bioinformatics-bootcamp/bmes-t580-2019-coursework-Nathan-Ona | e09f761f837ba7c6c2bfa223a9ed9e987b6260be | [
"MIT"
] | null | null | null | Module02/Guess_the_Primer.py | biomed-bioinformatics-bootcamp/bmes-t580-2019-coursework-Nathan-Ona | e09f761f837ba7c6c2bfa223a9ed9e987b6260be | [
"MIT"
] | null | null | null | # imports the random module that allows for the generation of random values
import random
# Creates divider for program
print('---------------------------')
print(' GUESS THE PRIMER! ')
print('---------------------------')
print()
# Generates random DNA sequence
DNA_goal = random.choice('ACGT')
DNA_goal += random.choice('ACGT')
DNA_goal += random.choice('ACGT')
DNA_goal += random.choice('ACGT')
DNA_goal += random.choice('ACGT')
X = 2
# asks user for their name and welcomes the use
user_name = input('What is your name?')
print('Hello ' + user_name)
# temporary value to enter the while loop for the game to start
user_guess = 'QWERT'
# checks if the guess value is less than the chosen random number
while user_guess != DNA_goal:
# asks use for their guess at the random 5 base pair primer
user_guess = input('please enter a 5 base pair primer ')
# checks if the user guess is equal to the random base primer, otherwise outputs that the user guess
# was correct
misses = 0
for i in range(len(user_guess)):
if user_guess[i] != DNA_goal[i]:
misses += 1
if misses > 0:
print('Sorry, your guessed %i bases wrong. Play Again?' % misses)
else:
print('Good job' + user_name + ', your guessed the Primer!') | 38.757576 | 104 | 0.659109 |
import random
print('---------------------------')
print(' GUESS THE PRIMER! ')
print('---------------------------')
print()
DNA_goal = random.choice('ACGT')
DNA_goal += random.choice('ACGT')
DNA_goal += random.choice('ACGT')
DNA_goal += random.choice('ACGT')
DNA_goal += random.choice('ACGT')
X = 2
user_name = input('What is your name?')
print('Hello ' + user_name)
user_guess = 'QWERT'
while user_guess != DNA_goal:
user_guess = input('please enter a 5 base pair primer ')
misses = 0
for i in range(len(user_guess)):
if user_guess[i] != DNA_goal[i]:
misses += 1
if misses > 0:
print('Sorry, your guessed %i bases wrong. Play Again?' % misses)
else:
print('Good job' + user_name + ', your guessed the Primer!') | true | true |
1c2e5ff93c9e3a3ea5ad94041810c30dd27d4bfd | 686 | py | Python | src/healthcare/azext_healthcare/_client_factory.py | feiskyer/azure-cli-extensions | a5e1d20c15031ef11c0e388993ea4e86603b33bb | [
"MIT"
] | null | null | null | src/healthcare/azext_healthcare/_client_factory.py | feiskyer/azure-cli-extensions | a5e1d20c15031ef11c0e388993ea4e86603b33bb | [
"MIT"
] | null | null | null | src/healthcare/azext_healthcare/_client_factory.py | feiskyer/azure-cli-extensions | a5e1d20c15031ef11c0e388993ea4e86603b33bb | [
"MIT"
] | null | null | null | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
def cf_healthcare(cli_ctx, *_):
from azure.cli.core.commands.client_factory import get_mgmt_service_client
from .vendored_sdks.healthcareapis import HealthcareApisManagementClient
return get_mgmt_service_client(cli_ctx, HealthcareApisManagementClient)
def cf_services(cli_ctx, *_):
return cf_healthcare(cli_ctx).services
| 45.733333 | 94 | 0.587464 |
def cf_healthcare(cli_ctx, *_):
from azure.cli.core.commands.client_factory import get_mgmt_service_client
from .vendored_sdks.healthcareapis import HealthcareApisManagementClient
return get_mgmt_service_client(cli_ctx, HealthcareApisManagementClient)
def cf_services(cli_ctx, *_):
return cf_healthcare(cli_ctx).services
| true | true |
1c2e60291d6a6365d4e7b03e7f1fb39162c03e54 | 8,957 | py | Python | odoo/addons/base/tests/test_search.py | jjiege/odoo | fd5b8ad387c1881f349d125cbd56433f4d49398f | [
"MIT"
] | null | null | null | odoo/addons/base/tests/test_search.py | jjiege/odoo | fd5b8ad387c1881f349d125cbd56433f4d49398f | [
"MIT"
] | null | null | null | odoo/addons/base/tests/test_search.py | jjiege/odoo | fd5b8ad387c1881f349d125cbd56433f4d49398f | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests.common import TransactionCase
class test_search(TransactionCase):
def test_00_search_order(self):
# Create 6 partners with a given name, and a given creation order to
# ensure the order of their ID. Some are set as inactive to verify they
# are by default excluded from the searches and to provide a second
# `order` argument.
Partner = self.env['res.partner']
c = Partner.create({'name': 'test_search_order_C'})
d = Partner.create({'name': 'test_search_order_D', 'active': False})
a = Partner.create({'name': 'test_search_order_A'})
b = Partner.create({'name': 'test_search_order_B'})
ab = Partner.create({'name': 'test_search_order_AB'})
e = Partner.create({'name': 'test_search_order_E', 'active': False})
# The tests.
# The basic searches should exclude records that have active = False.
# The order of the returned ids should be given by the `order`
# parameter of search().
name_asc = Partner.search([('name', 'like', 'test_search_order%')], order="name asc")
self.assertEqual([a, ab, b, c], list(name_asc), "Search with 'NAME ASC' order failed.")
name_desc = Partner.search([('name', 'like', 'test_search_order%')], order="name desc")
self.assertEqual([c, b, ab, a], list(name_desc), "Search with 'NAME DESC' order failed.")
id_asc = Partner.search([('name', 'like', 'test_search_order%')], order="id asc")
self.assertEqual([c, a, b, ab], list(id_asc), "Search with 'ID ASC' order failed.")
id_desc = Partner.search([('name', 'like', 'test_search_order%')], order="id desc")
self.assertEqual([ab, b, a, c], list(id_desc), "Search with 'ID DESC' order failed.")
# The inactive records shouldn't be excluded as soon as a condition on
# that field is present in the domain. The `order` parameter of
# search() should support any legal coma-separated values.
active_asc_id_asc = Partner.search([('name', 'like', 'test_search_order%'), '|', ('active', '=', True), ('active', '=', False)], order="active asc, id asc")
self.assertEqual([d, e, c, a, b, ab], list(active_asc_id_asc), "Search with 'ACTIVE ASC, ID ASC' order failed.")
active_desc_id_asc = Partner.search([('name', 'like', 'test_search_order%'), '|', ('active', '=', True), ('active', '=', False)], order="active desc, id asc")
self.assertEqual([c, a, b, ab, d, e], list(active_desc_id_asc), "Search with 'ACTIVE DESC, ID ASC' order failed.")
active_asc_id_desc = Partner.search([('name', 'like', 'test_search_order%'), '|', ('active', '=', True), ('active', '=', False)], order="active asc, id desc")
self.assertEqual([e, d, ab, b, a, c], list(active_asc_id_desc), "Search with 'ACTIVE ASC, ID DESC' order failed.")
active_desc_id_desc = Partner.search([('name', 'like', 'test_search_order%'), '|', ('active', '=', True), ('active', '=', False)], order="active desc, id desc")
self.assertEqual([ab, b, a, c, e, d], list(active_desc_id_desc), "Search with 'ACTIVE DESC, ID DESC' order failed.")
id_asc_active_asc = Partner.search([('name', 'like', 'test_search_order%'), '|', ('active', '=', True), ('active', '=', False)], order="id asc, active asc")
self.assertEqual([c, d, a, b, ab, e], list(id_asc_active_asc), "Search with 'ID ASC, ACTIVE ASC' order failed.")
id_asc_active_desc = Partner.search([('name', 'like', 'test_search_order%'), '|', ('active', '=', True), ('active', '=', False)], order="id asc, active desc")
self.assertEqual([c, d, a, b, ab, e], list(id_asc_active_desc), "Search with 'ID ASC, ACTIVE DESC' order failed.")
id_desc_active_asc = Partner.search([('name', 'like', 'test_search_order%'), '|', ('active', '=', True), ('active', '=', False)], order="id desc, active asc")
self.assertEqual([e, ab, b, a, d, c], list(id_desc_active_asc), "Search with 'ID DESC, ACTIVE ASC' order failed.")
id_desc_active_desc = Partner.search([('name', 'like', 'test_search_order%'), '|', ('active', '=', True), ('active', '=', False)], order="id desc, active desc")
self.assertEqual([e, ab, b, a, d, c], list(id_desc_active_desc), "Search with 'ID DESC, ACTIVE DESC' order failed.")
def test_10_inherits_m2order(self):
Users = self.env['res.users']
# Find Employee group
group_employee = self.env.ref('base.group_user')
# Get country/state data
country_be = self.env.ref('base.be')
country_us = self.env.ref('base.us')
states_us = country_us.state_ids[:2]
# Create test users
u = Users.create({'name': '__search', 'login': '__search', 'groups_id': [(6, 0, [group_employee.id])]})
a = Users.create({'name': '__test_A', 'login': '__test_A', 'country_id': country_be.id, 'state_id': country_be.id})
b = Users.create({'name': '__test_B', 'login': '__a_test_B', 'country_id': country_us.id, 'state_id': states_us[1].id})
c = Users.create({'name': '__test_B', 'login': '__z_test_B', 'country_id': country_us.id, 'state_id': states_us[0].id})
# Search as search user
Users = Users.sudo(u)
# Do: search on res.users, order on a field on res.partner to try inherits'd fields, then res.users
expected_ids = [u.id, a.id, c.id, b.id]
user_ids = Users.search([('id', 'in', expected_ids)], order='name asc, login desc').ids
self.assertEqual(user_ids, expected_ids, 'search on res_users did not provide expected ids or expected order')
# Do: order on many2one and inherits'd fields
expected_ids = [c.id, b.id, a.id, u.id]
user_ids = Users.search([('id', 'in', expected_ids)], order='state_id asc, country_id desc, name asc, login desc').ids
self.assertEqual(user_ids, expected_ids, 'search on res_users did not provide expected ids or expected order')
# Do: order on many2one and inherits'd fields
expected_ids = [u.id, b.id, c.id, a.id]
user_ids = Users.search([('id', 'in', expected_ids)], order='country_id desc, state_id desc, name asc, login desc').ids
self.assertEqual(user_ids, expected_ids, 'search on res_users did not provide expected ids or expected order')
# Do: order on many2one, but not by specifying in order parameter of search, but by overriding _order of res_users
self.patch_order('res.users', 'country_id desc, name asc, login desc')
expected_ids = [u.id, c.id, b.id, a.id]
user_ids = Users.search([('id', 'in', expected_ids)]).ids
self.assertEqual(user_ids, expected_ids, 'search on res_users did not provide expected ids or expected order')
def test_11_indirect_inherits_m2o_order(self):
Cron = self.env['ir.cron']
Users = self.env['res.users']
user_ids = {}
cron_ids = {}
for u in 'BAC':
user_ids[u] = Users.create({'name': u, 'login': u}).id
cron_ids[u] = Cron.create({'name': u, 'model_id': self.env.ref('base.model_res_partner').id, 'user_id': user_ids[u]}).id
ids = Cron.search([('id', 'in', list(cron_ids.values()))], order='user_id').ids
expected_ids = [cron_ids[l] for l in 'ABC']
self.assertEqual(ids, expected_ids)
def test_12_m2o_order_loop_self(self):
Cats = self.env['ir.module.category']
cat_ids = {}
def create(name, **kw):
cat_ids[name] = Cats.create(dict(kw, name=name)).id
self.patch_order('ir.module.category', 'parent_id desc, name')
create('A')
create('B', parent_id=cat_ids['A'])
create('C', parent_id=cat_ids['A'])
create('D')
create('E', parent_id=cat_ids['D'])
create('F', parent_id=cat_ids['D'])
expected_ids = [cat_ids[x] for x in 'ADEFBC']
found_ids = Cats.search([('id', 'in', list(cat_ids.values()))]).ids
self.assertEqual(found_ids, expected_ids)
def test_13_m2o_order_loop_multi(self):
Users = self.env['res.users']
# will sort by login desc of the creator, then by name
self.patch_order('res.partner', 'create_uid, name')
self.patch_order('res.users', 'partner_id, login desc')
kw = dict(groups_id=[(6, 0, [self.ref('base.group_system'),
self.ref('base.group_partner_manager')])])
u1 = Users.create(dict(name='Q', login='m', **kw)).id
u2 = Users.sudo(user=u1).create(dict(name='B', login='f', **kw)).id
u3 = Users.create(dict(name='C', login='c', **kw)).id
u4 = Users.sudo(user=u2).create(dict(name='D', login='z', **kw)).id
expected_ids = [u2, u4, u3, u1]
found_ids = Users.search([('id', 'in', expected_ids)]).ids
self.assertEqual(found_ids, expected_ids)
| 59.317881 | 168 | 0.620074 |
from odoo.tests.common import TransactionCase
class test_search(TransactionCase):
def test_00_search_order(self):
Partner = self.env['res.partner']
c = Partner.create({'name': 'test_search_order_C'})
d = Partner.create({'name': 'test_search_order_D', 'active': False})
a = Partner.create({'name': 'test_search_order_A'})
b = Partner.create({'name': 'test_search_order_B'})
ab = Partner.create({'name': 'test_search_order_AB'})
e = Partner.create({'name': 'test_search_order_E', 'active': False})
name_asc = Partner.search([('name', 'like', 'test_search_order%')], order="name asc")
self.assertEqual([a, ab, b, c], list(name_asc), "Search with 'NAME ASC' order failed.")
name_desc = Partner.search([('name', 'like', 'test_search_order%')], order="name desc")
self.assertEqual([c, b, ab, a], list(name_desc), "Search with 'NAME DESC' order failed.")
id_asc = Partner.search([('name', 'like', 'test_search_order%')], order="id asc")
self.assertEqual([c, a, b, ab], list(id_asc), "Search with 'ID ASC' order failed.")
id_desc = Partner.search([('name', 'like', 'test_search_order%')], order="id desc")
self.assertEqual([ab, b, a, c], list(id_desc), "Search with 'ID DESC' order failed.")
# that field is present in the domain. The `order` parameter of
# search() should support any legal coma-separated values.
active_asc_id_asc = Partner.search([('name', 'like', 'test_search_order%'), '|', ('active', '=', True), ('active', '=', False)], order="active asc, id asc")
self.assertEqual([d, e, c, a, b, ab], list(active_asc_id_asc), "Search with 'ACTIVE ASC, ID ASC' order failed.")
active_desc_id_asc = Partner.search([('name', 'like', 'test_search_order%'), '|', ('active', '=', True), ('active', '=', False)], order="active desc, id asc")
self.assertEqual([c, a, b, ab, d, e], list(active_desc_id_asc), "Search with 'ACTIVE DESC, ID ASC' order failed.")
active_asc_id_desc = Partner.search([('name', 'like', 'test_search_order%'), '|', ('active', '=', True), ('active', '=', False)], order="active asc, id desc")
self.assertEqual([e, d, ab, b, a, c], list(active_asc_id_desc), "Search with 'ACTIVE ASC, ID DESC' order failed.")
active_desc_id_desc = Partner.search([('name', 'like', 'test_search_order%'), '|', ('active', '=', True), ('active', '=', False)], order="active desc, id desc")
self.assertEqual([ab, b, a, c, e, d], list(active_desc_id_desc), "Search with 'ACTIVE DESC, ID DESC' order failed.")
id_asc_active_asc = Partner.search([('name', 'like', 'test_search_order%'), '|', ('active', '=', True), ('active', '=', False)], order="id asc, active asc")
self.assertEqual([c, d, a, b, ab, e], list(id_asc_active_asc), "Search with 'ID ASC, ACTIVE ASC' order failed.")
id_asc_active_desc = Partner.search([('name', 'like', 'test_search_order%'), '|', ('active', '=', True), ('active', '=', False)], order="id asc, active desc")
self.assertEqual([c, d, a, b, ab, e], list(id_asc_active_desc), "Search with 'ID ASC, ACTIVE DESC' order failed.")
id_desc_active_asc = Partner.search([('name', 'like', 'test_search_order%'), '|', ('active', '=', True), ('active', '=', False)], order="id desc, active asc")
self.assertEqual([e, ab, b, a, d, c], list(id_desc_active_asc), "Search with 'ID DESC, ACTIVE ASC' order failed.")
id_desc_active_desc = Partner.search([('name', 'like', 'test_search_order%'), '|', ('active', '=', True), ('active', '=', False)], order="id desc, active desc")
self.assertEqual([e, ab, b, a, d, c], list(id_desc_active_desc), "Search with 'ID DESC, ACTIVE DESC' order failed.")
def test_10_inherits_m2order(self):
Users = self.env['res.users']
# Find Employee group
group_employee = self.env.ref('base.group_user')
# Get country/state data
country_be = self.env.ref('base.be')
country_us = self.env.ref('base.us')
states_us = country_us.state_ids[:2]
# Create test users
u = Users.create({'name': '__search', 'login': '__search', 'groups_id': [(6, 0, [group_employee.id])]})
a = Users.create({'name': '__test_A', 'login': '__test_A', 'country_id': country_be.id, 'state_id': country_be.id})
b = Users.create({'name': '__test_B', 'login': '__a_test_B', 'country_id': country_us.id, 'state_id': states_us[1].id})
c = Users.create({'name': '__test_B', 'login': '__z_test_B', 'country_id': country_us.id, 'state_id': states_us[0].id})
# Search as search user
Users = Users.sudo(u)
# Do: search on res.users, order on a field on res.partner to try inherits'd fields, then res.users
expected_ids = [u.id, a.id, c.id, b.id]
user_ids = Users.search([('id', 'in', expected_ids)], order='name asc, login desc').ids
self.assertEqual(user_ids, expected_ids, 'search on res_users did not provide expected ids or expected order')
expected_ids = [c.id, b.id, a.id, u.id]
user_ids = Users.search([('id', 'in', expected_ids)], order='state_id asc, country_id desc, name asc, login desc').ids
self.assertEqual(user_ids, expected_ids, 'search on res_users did not provide expected ids or expected order')
# Do: order on many2one and inherits'd fields
expected_ids = [u.id, b.id, c.id, a.id]
user_ids = Users.search([('id', 'in', expected_ids)], order='country_id desc, state_id desc, name asc, login desc').ids
self.assertEqual(user_ids, expected_ids, 'search on res_users did not provide expected ids or expected order')
self.patch_order('res.users', 'country_id desc, name asc, login desc')
expected_ids = [u.id, c.id, b.id, a.id]
user_ids = Users.search([('id', 'in', expected_ids)]).ids
self.assertEqual(user_ids, expected_ids, 'search on res_users did not provide expected ids or expected order')
def test_11_indirect_inherits_m2o_order(self):
Cron = self.env['ir.cron']
Users = self.env['res.users']
user_ids = {}
cron_ids = {}
for u in 'BAC':
user_ids[u] = Users.create({'name': u, 'login': u}).id
cron_ids[u] = Cron.create({'name': u, 'model_id': self.env.ref('base.model_res_partner').id, 'user_id': user_ids[u]}).id
ids = Cron.search([('id', 'in', list(cron_ids.values()))], order='user_id').ids
expected_ids = [cron_ids[l] for l in 'ABC']
self.assertEqual(ids, expected_ids)
def test_12_m2o_order_loop_self(self):
Cats = self.env['ir.module.category']
cat_ids = {}
def create(name, **kw):
cat_ids[name] = Cats.create(dict(kw, name=name)).id
self.patch_order('ir.module.category', 'parent_id desc, name')
create('A')
create('B', parent_id=cat_ids['A'])
create('C', parent_id=cat_ids['A'])
create('D')
create('E', parent_id=cat_ids['D'])
create('F', parent_id=cat_ids['D'])
expected_ids = [cat_ids[x] for x in 'ADEFBC']
found_ids = Cats.search([('id', 'in', list(cat_ids.values()))]).ids
self.assertEqual(found_ids, expected_ids)
def test_13_m2o_order_loop_multi(self):
Users = self.env['res.users']
self.patch_order('res.partner', 'create_uid, name')
self.patch_order('res.users', 'partner_id, login desc')
kw = dict(groups_id=[(6, 0, [self.ref('base.group_system'),
self.ref('base.group_partner_manager')])])
u1 = Users.create(dict(name='Q', login='m', **kw)).id
u2 = Users.sudo(user=u1).create(dict(name='B', login='f', **kw)).id
u3 = Users.create(dict(name='C', login='c', **kw)).id
u4 = Users.sudo(user=u2).create(dict(name='D', login='z', **kw)).id
expected_ids = [u2, u4, u3, u1]
found_ids = Users.search([('id', 'in', expected_ids)]).ids
self.assertEqual(found_ids, expected_ids)
| true | true |
1c2e603e05c399fbbfce0c3827f887ed09dab251 | 2,178 | py | Python | dp/188.py | fimh/dsa-py | 383c9e9a36304a63668449043b1217aede93dd1e | [
"MIT"
] | 1 | 2019-12-17T09:23:51.000Z | 2019-12-17T09:23:51.000Z | dp/188.py | fimh/dsa-py | 383c9e9a36304a63668449043b1217aede93dd1e | [
"MIT"
] | null | null | null | dp/188.py | fimh/dsa-py | 383c9e9a36304a63668449043b1217aede93dd1e | [
"MIT"
] | null | null | null | """
Question: Best Time to Buy and Sell Stock IV
Difficulty: Hard
Link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/
Ref: https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iv/
You are given an integer array prices where prices[i] is the price of a given stock on the ith day, and an integer k.
Find the maximum profit you can achieve. You may complete at most k transactions.
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Example 1:
Input: k = 2, prices = [2,4,1]
Output: 2
Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.
Example 2:
Input: k = 2, prices = [3,2,6,5,0,3]
Output: 7
Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
Constraints:
0 <= k <= 100
0 <= prices.length <= 1000
0 <= prices[i] <= 1000
"""
from typing import List
class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
"""
DP approach
state: dp[i][k][j]
i: ith day, range - [0, n-1]
k: transaction times, range - [0, k]
j: hold shares, range - [0, 1]
Note that, k + 1 when buying one share
"""
if len(prices) <= 1:
return 0
times = k # Two transactions at most
dp = [[[0 for _ in range(2)] for _ in range(times + 1)] for _ in range(len(prices))]
for k in range(times + 1):
dp[0][k][1] = -prices[0]
res = dp[0][0][0]
for ii in range(1, len(prices)):
for kk in range(1, times + 1):
dp[ii][kk][0] = max(dp[ii - 1][kk][0], dp[ii - 1][kk][1] + prices[ii]) # Sell one share
dp[ii][kk][1] = max(dp[ii - 1][kk][1], dp[ii - 1][kk - 1][0] - prices[ii]) # Buy one share
if dp[ii][kk][0] > res:
res = dp[ii][kk][0]
return res
if __name__ == '__main__':
test_k = 1
test_prices = [3, 2, 6, 5, 0, 3]
ret = Solution().maxProfit(test_k, test_prices)
print(ret)
| 29.835616 | 165 | 0.566575 | from typing import List
class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
if len(prices) <= 1:
return 0
times = k
dp = [[[0 for _ in range(2)] for _ in range(times + 1)] for _ in range(len(prices))]
for k in range(times + 1):
dp[0][k][1] = -prices[0]
res = dp[0][0][0]
for ii in range(1, len(prices)):
for kk in range(1, times + 1):
dp[ii][kk][0] = max(dp[ii - 1][kk][0], dp[ii - 1][kk][1] + prices[ii])
dp[ii][kk][1] = max(dp[ii - 1][kk][1], dp[ii - 1][kk - 1][0] - prices[ii])
if dp[ii][kk][0] > res:
res = dp[ii][kk][0]
return res
if __name__ == '__main__':
test_k = 1
test_prices = [3, 2, 6, 5, 0, 3]
ret = Solution().maxProfit(test_k, test_prices)
print(ret)
| true | true |
1c2e603f21f291adba5b57dfc58e8f9764fba114 | 11,169 | py | Python | Sklearn_scipy_numpy/source/sklearn/feature_extraction/tests/test_image.py | Con-Mi/lambda-packs | b23a8464abdd88050b83310e1d0e99c54dac28ab | [
"MIT"
] | 1 | 2019-06-27T12:09:44.000Z | 2019-06-27T12:09:44.000Z | Sklearn_scipy_numpy/source/sklearn/feature_extraction/tests/test_image.py | Con-Mi/lambda-packs | b23a8464abdd88050b83310e1d0e99c54dac28ab | [
"MIT"
] | null | null | null | Sklearn_scipy_numpy/source/sklearn/feature_extraction/tests/test_image.py | Con-Mi/lambda-packs | b23a8464abdd88050b83310e1d0e99c54dac28ab | [
"MIT"
] | null | null | null | # Authors: Emmanuelle Gouillart <emmanuelle.gouillart@normalesup.org>
# Gael Varoquaux <gael.varoquaux@normalesup.org>
# License: BSD 3 clause
import numpy as np
import scipy as sp
from scipy import ndimage
from scipy import misc
from nose.tools import assert_equal, assert_true
from numpy.testing import assert_raises
from sklearn.feature_extraction.image import (
img_to_graph, grid_to_graph, extract_patches_2d,
reconstruct_from_patches_2d, PatchExtractor, extract_patches)
from sklearn.utils.graph import connected_components
from sklearn.utils.testing import SkipTest
from sklearn.utils.fixes import sp_version
if sp_version < (0, 12):
raise SkipTest("Skipping because SciPy version earlier than 0.12.0 and "
"thus does not include the scipy.misc.face() image.")
def test_img_to_graph():
x, y = np.mgrid[:4, :4] - 10
grad_x = img_to_graph(x)
grad_y = img_to_graph(y)
assert_equal(grad_x.nnz, grad_y.nnz)
# Negative elements are the diagonal: the elements of the original
# image. Positive elements are the values of the gradient, they
# should all be equal on grad_x and grad_y
np.testing.assert_array_equal(grad_x.data[grad_x.data > 0],
grad_y.data[grad_y.data > 0])
def test_grid_to_graph():
#Checking that the function works with graphs containing no edges
size = 2
roi_size = 1
# Generating two convex parts with one vertex
# Thus, edges will be empty in _to_graph
mask = np.zeros((size, size), dtype=np.bool)
mask[0:roi_size, 0:roi_size] = True
mask[-roi_size:, -roi_size:] = True
mask = mask.reshape(size ** 2)
A = grid_to_graph(n_x=size, n_y=size, mask=mask, return_as=np.ndarray)
assert_true(connected_components(A)[0] == 2)
# Checking that the function works whatever the type of mask is
mask = np.ones((size, size), dtype=np.int16)
A = grid_to_graph(n_x=size, n_y=size, n_z=size, mask=mask)
assert_true(connected_components(A)[0] == 1)
# Checking dtype of the graph
mask = np.ones((size, size))
A = grid_to_graph(n_x=size, n_y=size, n_z=size, mask=mask, dtype=np.bool)
assert_true(A.dtype == np.bool)
A = grid_to_graph(n_x=size, n_y=size, n_z=size, mask=mask, dtype=np.int)
assert_true(A.dtype == np.int)
A = grid_to_graph(n_x=size, n_y=size, n_z=size, mask=mask, dtype=np.float)
assert_true(A.dtype == np.float)
def test_connect_regions():
try:
face = sp.face(gray=True)
except AttributeError:
# Newer versions of scipy have face in misc
from scipy import misc
face = misc.face(gray=True)
for thr in (50, 150):
mask = face > thr
graph = img_to_graph(face, mask)
assert_equal(ndimage.label(mask)[1], connected_components(graph)[0])
def test_connect_regions_with_grid():
try:
face = sp.face(gray=True)
except AttributeError:
# Newer versions of scipy have face in misc
from scipy import misc
face = misc.face(gray=True)
mask = face > 50
graph = grid_to_graph(*face.shape, mask=mask)
assert_equal(ndimage.label(mask)[1], connected_components(graph)[0])
mask = face > 150
graph = grid_to_graph(*face.shape, mask=mask, dtype=None)
assert_equal(ndimage.label(mask)[1], connected_components(graph)[0])
def _downsampled_face():
try:
face = sp.face(gray=True)
except AttributeError:
# Newer versions of scipy have face in misc
from scipy import misc
face = misc.face(gray=True)
face = face.astype(np.float32)
face = (face[::2, ::2] + face[1::2, ::2] + face[::2, 1::2]
+ face[1::2, 1::2])
face = (face[::2, ::2] + face[1::2, ::2] + face[::2, 1::2]
+ face[1::2, 1::2])
face = face.astype(np.float32)
face /= 16.0
return face
def _orange_face(face=None):
face = _downsampled_face() if face is None else face
face_color = np.zeros(face.shape + (3,))
face_color[:, :, 0] = 256 - face
face_color[:, :, 1] = 256 - face / 2
face_color[:, :, 2] = 256 - face / 4
return face_color
def _make_images(face=None):
face = _downsampled_face() if face is None else face
# make a collection of faces
images = np.zeros((3,) + face.shape)
images[0] = face
images[1] = face + 1
images[2] = face + 2
return images
downsampled_face = _downsampled_face()
orange_face = _orange_face(downsampled_face)
face_collection = _make_images(downsampled_face)
def test_extract_patches_all():
face = downsampled_face
i_h, i_w = face.shape
p_h, p_w = 16, 16
expected_n_patches = (i_h - p_h + 1) * (i_w - p_w + 1)
patches = extract_patches_2d(face, (p_h, p_w))
assert_equal(patches.shape, (expected_n_patches, p_h, p_w))
def test_extract_patches_all_color():
face = orange_face
i_h, i_w = face.shape[:2]
p_h, p_w = 16, 16
expected_n_patches = (i_h - p_h + 1) * (i_w - p_w + 1)
patches = extract_patches_2d(face, (p_h, p_w))
assert_equal(patches.shape, (expected_n_patches, p_h, p_w, 3))
def test_extract_patches_all_rect():
face = downsampled_face
face = face[:, 32:97]
i_h, i_w = face.shape
p_h, p_w = 16, 12
expected_n_patches = (i_h - p_h + 1) * (i_w - p_w + 1)
patches = extract_patches_2d(face, (p_h, p_w))
assert_equal(patches.shape, (expected_n_patches, p_h, p_w))
def test_extract_patches_max_patches():
face = downsampled_face
i_h, i_w = face.shape
p_h, p_w = 16, 16
patches = extract_patches_2d(face, (p_h, p_w), max_patches=100)
assert_equal(patches.shape, (100, p_h, p_w))
expected_n_patches = int(0.5 * (i_h - p_h + 1) * (i_w - p_w + 1))
patches = extract_patches_2d(face, (p_h, p_w), max_patches=0.5)
assert_equal(patches.shape, (expected_n_patches, p_h, p_w))
assert_raises(ValueError, extract_patches_2d, face, (p_h, p_w),
max_patches=2.0)
assert_raises(ValueError, extract_patches_2d, face, (p_h, p_w),
max_patches=-1.0)
def test_reconstruct_patches_perfect():
face = downsampled_face
p_h, p_w = 16, 16
patches = extract_patches_2d(face, (p_h, p_w))
face_reconstructed = reconstruct_from_patches_2d(patches, face.shape)
np.testing.assert_array_equal(face, face_reconstructed)
def test_reconstruct_patches_perfect_color():
face = orange_face
p_h, p_w = 16, 16
patches = extract_patches_2d(face, (p_h, p_w))
face_reconstructed = reconstruct_from_patches_2d(patches, face.shape)
np.testing.assert_array_equal(face, face_reconstructed)
def test_patch_extractor_fit():
faces = face_collection
extr = PatchExtractor(patch_size=(8, 8), max_patches=100, random_state=0)
assert_true(extr == extr.fit(faces))
def test_patch_extractor_max_patches():
faces = face_collection
i_h, i_w = faces.shape[1:3]
p_h, p_w = 8, 8
max_patches = 100
expected_n_patches = len(faces) * max_patches
extr = PatchExtractor(patch_size=(p_h, p_w), max_patches=max_patches,
random_state=0)
patches = extr.transform(faces)
assert_true(patches.shape == (expected_n_patches, p_h, p_w))
max_patches = 0.5
expected_n_patches = len(faces) * int((i_h - p_h + 1) * (i_w - p_w + 1)
* max_patches)
extr = PatchExtractor(patch_size=(p_h, p_w), max_patches=max_patches,
random_state=0)
patches = extr.transform(faces)
assert_true(patches.shape == (expected_n_patches, p_h, p_w))
def test_patch_extractor_max_patches_default():
faces = face_collection
extr = PatchExtractor(max_patches=100, random_state=0)
patches = extr.transform(faces)
assert_equal(patches.shape, (len(faces) * 100, 19, 25))
def test_patch_extractor_all_patches():
faces = face_collection
i_h, i_w = faces.shape[1:3]
p_h, p_w = 8, 8
expected_n_patches = len(faces) * (i_h - p_h + 1) * (i_w - p_w + 1)
extr = PatchExtractor(patch_size=(p_h, p_w), random_state=0)
patches = extr.transform(faces)
assert_true(patches.shape == (expected_n_patches, p_h, p_w))
def test_patch_extractor_color():
faces = _make_images(orange_face)
i_h, i_w = faces.shape[1:3]
p_h, p_w = 8, 8
expected_n_patches = len(faces) * (i_h - p_h + 1) * (i_w - p_w + 1)
extr = PatchExtractor(patch_size=(p_h, p_w), random_state=0)
patches = extr.transform(faces)
assert_true(patches.shape == (expected_n_patches, p_h, p_w, 3))
def test_extract_patches_strided():
image_shapes_1D = [(10,), (10,), (11,), (10,)]
patch_sizes_1D = [(1,), (2,), (3,), (8,)]
patch_steps_1D = [(1,), (1,), (4,), (2,)]
expected_views_1D = [(10,), (9,), (3,), (2,)]
last_patch_1D = [(10,), (8,), (8,), (2,)]
image_shapes_2D = [(10, 20), (10, 20), (10, 20), (11, 20)]
patch_sizes_2D = [(2, 2), (10, 10), (10, 11), (6, 6)]
patch_steps_2D = [(5, 5), (3, 10), (3, 4), (4, 2)]
expected_views_2D = [(2, 4), (1, 2), (1, 3), (2, 8)]
last_patch_2D = [(5, 15), (0, 10), (0, 8), (4, 14)]
image_shapes_3D = [(5, 4, 3), (3, 3, 3), (7, 8, 9), (7, 8, 9)]
patch_sizes_3D = [(2, 2, 3), (2, 2, 2), (1, 7, 3), (1, 3, 3)]
patch_steps_3D = [(1, 2, 10), (1, 1, 1), (2, 1, 3), (3, 3, 4)]
expected_views_3D = [(4, 2, 1), (2, 2, 2), (4, 2, 3), (3, 2, 2)]
last_patch_3D = [(3, 2, 0), (1, 1, 1), (6, 1, 6), (6, 3, 4)]
image_shapes = image_shapes_1D + image_shapes_2D + image_shapes_3D
patch_sizes = patch_sizes_1D + patch_sizes_2D + patch_sizes_3D
patch_steps = patch_steps_1D + patch_steps_2D + patch_steps_3D
expected_views = expected_views_1D + expected_views_2D + expected_views_3D
last_patches = last_patch_1D + last_patch_2D + last_patch_3D
for (image_shape, patch_size, patch_step, expected_view,
last_patch) in zip(image_shapes, patch_sizes, patch_steps,
expected_views, last_patches):
image = np.arange(np.prod(image_shape)).reshape(image_shape)
patches = extract_patches(image, patch_shape=patch_size,
extraction_step=patch_step)
ndim = len(image_shape)
assert_true(patches.shape[:ndim] == expected_view)
last_patch_slices = [slice(i, i + j, None) for i, j in
zip(last_patch, patch_size)]
assert_true((patches[[slice(-1, None, None)] * ndim] ==
image[last_patch_slices].squeeze()).all())
def test_extract_patches_square():
# test same patch size for all dimensions
face = downsampled_face
i_h, i_w = face.shape
p = 8
expected_n_patches = ((i_h - p + 1), (i_w - p + 1))
patches = extract_patches(face, patch_shape=p)
assert_true(patches.shape == (expected_n_patches[0], expected_n_patches[1],
p, p))
def test_width_patch():
# width and height of the patch should be less than the image
x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
assert_raises(ValueError, extract_patches_2d, x, (4, 1))
assert_raises(ValueError, extract_patches_2d, x, (1, 4))
| 35.683706 | 79 | 0.64491 |
import numpy as np
import scipy as sp
from scipy import ndimage
from scipy import misc
from nose.tools import assert_equal, assert_true
from numpy.testing import assert_raises
from sklearn.feature_extraction.image import (
img_to_graph, grid_to_graph, extract_patches_2d,
reconstruct_from_patches_2d, PatchExtractor, extract_patches)
from sklearn.utils.graph import connected_components
from sklearn.utils.testing import SkipTest
from sklearn.utils.fixes import sp_version
if sp_version < (0, 12):
raise SkipTest("Skipping because SciPy version earlier than 0.12.0 and "
"thus does not include the scipy.misc.face() image.")
def test_img_to_graph():
x, y = np.mgrid[:4, :4] - 10
grad_x = img_to_graph(x)
grad_y = img_to_graph(y)
assert_equal(grad_x.nnz, grad_y.nnz)
np.testing.assert_array_equal(grad_x.data[grad_x.data > 0],
grad_y.data[grad_y.data > 0])
def test_grid_to_graph():
size = 2
roi_size = 1
mask = np.zeros((size, size), dtype=np.bool)
mask[0:roi_size, 0:roi_size] = True
mask[-roi_size:, -roi_size:] = True
mask = mask.reshape(size ** 2)
A = grid_to_graph(n_x=size, n_y=size, mask=mask, return_as=np.ndarray)
assert_true(connected_components(A)[0] == 2)
mask = np.ones((size, size), dtype=np.int16)
A = grid_to_graph(n_x=size, n_y=size, n_z=size, mask=mask)
assert_true(connected_components(A)[0] == 1)
mask = np.ones((size, size))
A = grid_to_graph(n_x=size, n_y=size, n_z=size, mask=mask, dtype=np.bool)
assert_true(A.dtype == np.bool)
A = grid_to_graph(n_x=size, n_y=size, n_z=size, mask=mask, dtype=np.int)
assert_true(A.dtype == np.int)
A = grid_to_graph(n_x=size, n_y=size, n_z=size, mask=mask, dtype=np.float)
assert_true(A.dtype == np.float)
def test_connect_regions():
try:
face = sp.face(gray=True)
except AttributeError:
from scipy import misc
face = misc.face(gray=True)
for thr in (50, 150):
mask = face > thr
graph = img_to_graph(face, mask)
assert_equal(ndimage.label(mask)[1], connected_components(graph)[0])
def test_connect_regions_with_grid():
try:
face = sp.face(gray=True)
except AttributeError:
from scipy import misc
face = misc.face(gray=True)
mask = face > 50
graph = grid_to_graph(*face.shape, mask=mask)
assert_equal(ndimage.label(mask)[1], connected_components(graph)[0])
mask = face > 150
graph = grid_to_graph(*face.shape, mask=mask, dtype=None)
assert_equal(ndimage.label(mask)[1], connected_components(graph)[0])
def _downsampled_face():
try:
face = sp.face(gray=True)
except AttributeError:
from scipy import misc
face = misc.face(gray=True)
face = face.astype(np.float32)
face = (face[::2, ::2] + face[1::2, ::2] + face[::2, 1::2]
+ face[1::2, 1::2])
face = (face[::2, ::2] + face[1::2, ::2] + face[::2, 1::2]
+ face[1::2, 1::2])
face = face.astype(np.float32)
face /= 16.0
return face
def _orange_face(face=None):
face = _downsampled_face() if face is None else face
face_color = np.zeros(face.shape + (3,))
face_color[:, :, 0] = 256 - face
face_color[:, :, 1] = 256 - face / 2
face_color[:, :, 2] = 256 - face / 4
return face_color
def _make_images(face=None):
face = _downsampled_face() if face is None else face
images = np.zeros((3,) + face.shape)
images[0] = face
images[1] = face + 1
images[2] = face + 2
return images
downsampled_face = _downsampled_face()
orange_face = _orange_face(downsampled_face)
face_collection = _make_images(downsampled_face)
def test_extract_patches_all():
face = downsampled_face
i_h, i_w = face.shape
p_h, p_w = 16, 16
expected_n_patches = (i_h - p_h + 1) * (i_w - p_w + 1)
patches = extract_patches_2d(face, (p_h, p_w))
assert_equal(patches.shape, (expected_n_patches, p_h, p_w))
def test_extract_patches_all_color():
face = orange_face
i_h, i_w = face.shape[:2]
p_h, p_w = 16, 16
expected_n_patches = (i_h - p_h + 1) * (i_w - p_w + 1)
patches = extract_patches_2d(face, (p_h, p_w))
assert_equal(patches.shape, (expected_n_patches, p_h, p_w, 3))
def test_extract_patches_all_rect():
face = downsampled_face
face = face[:, 32:97]
i_h, i_w = face.shape
p_h, p_w = 16, 12
expected_n_patches = (i_h - p_h + 1) * (i_w - p_w + 1)
patches = extract_patches_2d(face, (p_h, p_w))
assert_equal(patches.shape, (expected_n_patches, p_h, p_w))
def test_extract_patches_max_patches():
face = downsampled_face
i_h, i_w = face.shape
p_h, p_w = 16, 16
patches = extract_patches_2d(face, (p_h, p_w), max_patches=100)
assert_equal(patches.shape, (100, p_h, p_w))
expected_n_patches = int(0.5 * (i_h - p_h + 1) * (i_w - p_w + 1))
patches = extract_patches_2d(face, (p_h, p_w), max_patches=0.5)
assert_equal(patches.shape, (expected_n_patches, p_h, p_w))
assert_raises(ValueError, extract_patches_2d, face, (p_h, p_w),
max_patches=2.0)
assert_raises(ValueError, extract_patches_2d, face, (p_h, p_w),
max_patches=-1.0)
def test_reconstruct_patches_perfect():
face = downsampled_face
p_h, p_w = 16, 16
patches = extract_patches_2d(face, (p_h, p_w))
face_reconstructed = reconstruct_from_patches_2d(patches, face.shape)
np.testing.assert_array_equal(face, face_reconstructed)
def test_reconstruct_patches_perfect_color():
face = orange_face
p_h, p_w = 16, 16
patches = extract_patches_2d(face, (p_h, p_w))
face_reconstructed = reconstruct_from_patches_2d(patches, face.shape)
np.testing.assert_array_equal(face, face_reconstructed)
def test_patch_extractor_fit():
faces = face_collection
extr = PatchExtractor(patch_size=(8, 8), max_patches=100, random_state=0)
assert_true(extr == extr.fit(faces))
def test_patch_extractor_max_patches():
faces = face_collection
i_h, i_w = faces.shape[1:3]
p_h, p_w = 8, 8
max_patches = 100
expected_n_patches = len(faces) * max_patches
extr = PatchExtractor(patch_size=(p_h, p_w), max_patches=max_patches,
random_state=0)
patches = extr.transform(faces)
assert_true(patches.shape == (expected_n_patches, p_h, p_w))
max_patches = 0.5
expected_n_patches = len(faces) * int((i_h - p_h + 1) * (i_w - p_w + 1)
* max_patches)
extr = PatchExtractor(patch_size=(p_h, p_w), max_patches=max_patches,
random_state=0)
patches = extr.transform(faces)
assert_true(patches.shape == (expected_n_patches, p_h, p_w))
def test_patch_extractor_max_patches_default():
faces = face_collection
extr = PatchExtractor(max_patches=100, random_state=0)
patches = extr.transform(faces)
assert_equal(patches.shape, (len(faces) * 100, 19, 25))
def test_patch_extractor_all_patches():
faces = face_collection
i_h, i_w = faces.shape[1:3]
p_h, p_w = 8, 8
expected_n_patches = len(faces) * (i_h - p_h + 1) * (i_w - p_w + 1)
extr = PatchExtractor(patch_size=(p_h, p_w), random_state=0)
patches = extr.transform(faces)
assert_true(patches.shape == (expected_n_patches, p_h, p_w))
def test_patch_extractor_color():
faces = _make_images(orange_face)
i_h, i_w = faces.shape[1:3]
p_h, p_w = 8, 8
expected_n_patches = len(faces) * (i_h - p_h + 1) * (i_w - p_w + 1)
extr = PatchExtractor(patch_size=(p_h, p_w), random_state=0)
patches = extr.transform(faces)
assert_true(patches.shape == (expected_n_patches, p_h, p_w, 3))
def test_extract_patches_strided():
image_shapes_1D = [(10,), (10,), (11,), (10,)]
patch_sizes_1D = [(1,), (2,), (3,), (8,)]
patch_steps_1D = [(1,), (1,), (4,), (2,)]
expected_views_1D = [(10,), (9,), (3,), (2,)]
last_patch_1D = [(10,), (8,), (8,), (2,)]
image_shapes_2D = [(10, 20), (10, 20), (10, 20), (11, 20)]
patch_sizes_2D = [(2, 2), (10, 10), (10, 11), (6, 6)]
patch_steps_2D = [(5, 5), (3, 10), (3, 4), (4, 2)]
expected_views_2D = [(2, 4), (1, 2), (1, 3), (2, 8)]
last_patch_2D = [(5, 15), (0, 10), (0, 8), (4, 14)]
image_shapes_3D = [(5, 4, 3), (3, 3, 3), (7, 8, 9), (7, 8, 9)]
patch_sizes_3D = [(2, 2, 3), (2, 2, 2), (1, 7, 3), (1, 3, 3)]
patch_steps_3D = [(1, 2, 10), (1, 1, 1), (2, 1, 3), (3, 3, 4)]
expected_views_3D = [(4, 2, 1), (2, 2, 2), (4, 2, 3), (3, 2, 2)]
last_patch_3D = [(3, 2, 0), (1, 1, 1), (6, 1, 6), (6, 3, 4)]
image_shapes = image_shapes_1D + image_shapes_2D + image_shapes_3D
patch_sizes = patch_sizes_1D + patch_sizes_2D + patch_sizes_3D
patch_steps = patch_steps_1D + patch_steps_2D + patch_steps_3D
expected_views = expected_views_1D + expected_views_2D + expected_views_3D
last_patches = last_patch_1D + last_patch_2D + last_patch_3D
for (image_shape, patch_size, patch_step, expected_view,
last_patch) in zip(image_shapes, patch_sizes, patch_steps,
expected_views, last_patches):
image = np.arange(np.prod(image_shape)).reshape(image_shape)
patches = extract_patches(image, patch_shape=patch_size,
extraction_step=patch_step)
ndim = len(image_shape)
assert_true(patches.shape[:ndim] == expected_view)
last_patch_slices = [slice(i, i + j, None) for i, j in
zip(last_patch, patch_size)]
assert_true((patches[[slice(-1, None, None)] * ndim] ==
image[last_patch_slices].squeeze()).all())
def test_extract_patches_square():
face = downsampled_face
i_h, i_w = face.shape
p = 8
expected_n_patches = ((i_h - p + 1), (i_w - p + 1))
patches = extract_patches(face, patch_shape=p)
assert_true(patches.shape == (expected_n_patches[0], expected_n_patches[1],
p, p))
def test_width_patch():
x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
assert_raises(ValueError, extract_patches_2d, x, (4, 1))
assert_raises(ValueError, extract_patches_2d, x, (1, 4))
| true | true |
1c2e603f860b366c183495d66f427a52370e54a5 | 8,379 | py | Python | pippin/snana_fit.py | skuhl99/Pippin | 3cbf4feed71a380eecd57a42b972f9723ae1abd1 | [
"MIT"
] | null | null | null | pippin/snana_fit.py | skuhl99/Pippin | 3cbf4feed71a380eecd57a42b972f9723ae1abd1 | [
"MIT"
] | null | null | null | pippin/snana_fit.py | skuhl99/Pippin | 3cbf4feed71a380eecd57a42b972f9723ae1abd1 | [
"MIT"
] | null | null | null | import inspect
import os
import logging
import shutil
import subprocess
import time
import pandas as pd
from pippin.base import ConfigBasedExecutable
from pippin.config import chown_dir, mkdirs
from pippin.dataprep import DataPrep
from pippin.snana_sim import SNANASimulation
from pippin.task import Task
class SNANALightCurveFit(ConfigBasedExecutable):
def __init__(self, name, output_dir, sim_task, config, global_config):
self.data_dir = os.path.dirname(inspect.stack()[0][1]) + "/data_files/"
self.config = config
self.global_config = global_config
base = config["BASE"]
fitopts = config.get("FITOPTS", "empty.fitopts")
self.base_file = self.data_dir + base
self.fitopts_file = self.data_dir + fitopts
super().__init__(name, output_dir, self.base_file, "= ", dependencies=[sim_task])
self.sim_task = sim_task
self.sim_version = sim_task.output["genversion"]
self.config_path = self.output_dir + "/" + self.sim_version + ".nml"
self.lc_output_dir = f"{self.output_dir}/output"
self.fitres_dir = f"{self.lc_output_dir}/{self.sim_version}"
self.set_num_jobs(int(config.get("NUM_JOBS", 100)))
self.logging_file = self.config_path.replace(".nml", ".nml_log")
self.done_file = f"{self.output_dir}/FINISHED.DONE"
secondary_log = f"{self.lc_output_dir}/SPLIT_JOBS_LCFIT/MERGELOGS/MERGE2.LOG"
self.log_files = [self.logging_file, secondary_log]
self.output["fitres_dir"] = self.fitres_dir
self.output["nml_file"] = self.config_path
self.output["genversion"] = self.sim_version
self.output["sim_name"] = sim_task.output["name"]
self.output["lc_output_dir"] = self.lc_output_dir
def get_sim_dependency(self):
for t in self.dependencies:
if isinstance(t, SNANASimulation) or isinstance(t, DataPrep):
return t.output
return None
def print_stats(self):
folders = [f for f in os.listdir(self.lc_output_dir) if f.startswith("PIP_") and os.path.isdir(self.lc_output_dir + "/" + f)]
for f in folders:
path = os.path.join(self.lc_output_dir, f)
data = pd.read_csv(os.path.join(path, "FITOPT000.FITRES.gz"), sep='\s+', comment="#", compression="infer")
counts = data.groupby("TYPE").size()
self.logger.info("Types: " + (" ".join([f"{k}:{v}" for k, v in zip(counts.index, counts.values)])))
def set_snlcinp(self, name, value):
""" Ensures the property name value pair is set in the SNLCINP section.
Parameters
----------
name : str
The name of the property. Case insensitive, will be cast to upper.
value : object
The value to use. Object will be cast to string. For strings, include single quotes.
"""
self.set_property(name, value, section_start="&SNLCINP", section_end="&END")
def set_fitinp(self, name, value):
""" Ensures the property name value pair is set in the FITINP section.
Parameters
----------
name : str
The name of the property. Case insensitive, will be cast to upper.
value : object
The value to use. Object will be cast to string. For strings, include single quotes.
"""
self.set_property(name, value, section_start="&FITINP", section_end="&END")
def write_nml(self, force_refresh):
self.logger.debug(f"Loading fitopts file from {self.fitopts_file}")
with open(self.fitopts_file, "r") as f:
self.fitopts = list(f.read().splitlines())
self.logger.info(f"Loaded {len(self.fitopts)} fitopts file from {self.fitopts_file}")
# Parse config, first SNLCINP and then FITINP
for key, value in self.config.get("SNLCINP", {}).items():
self.set_snlcinp(key, value)
for key, value in self.config.get("FITINP", {}).items():
self.set_fitinp(key, value)
self.set_property("VERSION", self.sim_version + "*", assignment=": ", section_end="&SNLCINP") # TODO FIX THIS, DOUBLE VERSION KEY
self.set_property("OUTDIR", self.lc_output_dir, assignment=": ", section_end="&SNLCINP")
if isinstance(self.sim_task, DataPrep):
self.set_snlcinp("PRIVATE_DATA_PATH", f"'{self.sim_task.output['data_path']}'")
self.set_snlcinp("VERSION_PHOTOMETRY", f"'{self.sim_task.output['genversion']}'")
# We want to do our hashing check here
string_to_hash = self.fitopts + self.base
# with open(os.path.abspath(inspect.stack()[0][1]), "r") as f:
# string_to_hash += f.read()
new_hash = self.get_hash_from_string("".join(string_to_hash))
old_hash = self.get_old_hash()
regenerate = force_refresh or (old_hash is None or old_hash != new_hash)
if regenerate:
self.logger.info(f"Running Light curve fit. Removing output_dir")
shutil.rmtree(self.output_dir, ignore_errors=True)
mkdirs(self.output_dir)
# Write main file
with open(self.config_path, "w") as f:
f.writelines(map(lambda s: s + '\n', string_to_hash))
self.logger.info(f"NML file written to {self.config_path}")
self.save_new_hash(new_hash)
chown_dir(self.output_dir)
else:
self.logger.info("Hash check passed, not rerunning")
return regenerate, new_hash
def _run(self, force_refresh):
regenerate, new_hash = self.write_nml(force_refresh)
if not regenerate:
return True
self.logger.info(f"Light curve fitting outputting to {self.logging_file}")
with open(self.logging_file, "w") as f:
subprocess.run(["split_and_fit.pl", self.config_path, "NOPROMPT"], stdout=f, stderr=subprocess.STDOUT, cwd=self.output_dir)
return True
def _check_completion(self, squeue):
# Check for errors
for file in self.log_files:
if os.path.exists(file):
with open(file, "r") as f:
output_error = False
for line in f.read().splitlines():
if ("ERROR" in line or ("ABORT" in line and " 0 " not in line)) and not output_error:
self.logger.error(f"Fatal error in light curve fitting. See {file} for details.")
output_error = True
if output_error:
self.logger.info(f"Excerpt: {line}")
if output_error:
return Task.FINISHED_FAILURE
# Check for existence of SPLIT_JOBS_LCFIT.tar.gz to see if job is done
if os.path.exists(self.done_file):
self.logger.info("Light curve done file found")
logging_file2 = self.logging_file.replace("_log", "_log2")
if not os.path.exists(logging_file2):
self.logger.info("Tarball found, fitting complete, cleaning up the directory")
try:
with open(logging_file2, "w") as f:
subprocess.run(["split_and_fit.pl", "CLEANMASK", "4", "NOPROMPT"], stdout=f, stderr=subprocess.STDOUT, cwd=self.output_dir, check=True)
time.sleep(2)
except subprocess.CalledProcessError as e:
self.logger.warning(f"split_and_fit.pl has a return code of {e.returncode}. This may or may not be an issue.")
chown_dir(self.output_dir)
self.print_stats()
self.output["fitres_file"] = os.path.abspath(os.path.join(self.fitres_dir, "FITOPT000.FITRES.gz")) # TODO: Ask rick if there
return Task.FINISHED_SUCCESS
return 0
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG, format="[%(levelname)7s |%(funcName)20s] %(message)s")
config = {"BASE": "des.nml", }
s = SNANALightCurveFit("../output/test", "testv", config, {})
s.set_snlcinp("CUTWIN_NBAND_THRESH", 1000)
s.set_snlcinp("HELLO", "'human'")
s.set_fitinp("FITWIN_PROB", "0.05, 1.01")
s.set_fitinp("GOODBYE", -1)
s.set_property("BATCH_INFO", "sbatch $SBATCH_TEMPLATES/SBATCH_sandyb.TEMPLATE 96", assignment=": ")
s.delete_property("GOODBYE")
s.write_nml()
| 45.538043 | 159 | 0.622151 | import inspect
import os
import logging
import shutil
import subprocess
import time
import pandas as pd
from pippin.base import ConfigBasedExecutable
from pippin.config import chown_dir, mkdirs
from pippin.dataprep import DataPrep
from pippin.snana_sim import SNANASimulation
from pippin.task import Task
class SNANALightCurveFit(ConfigBasedExecutable):
def __init__(self, name, output_dir, sim_task, config, global_config):
self.data_dir = os.path.dirname(inspect.stack()[0][1]) + "/data_files/"
self.config = config
self.global_config = global_config
base = config["BASE"]
fitopts = config.get("FITOPTS", "empty.fitopts")
self.base_file = self.data_dir + base
self.fitopts_file = self.data_dir + fitopts
super().__init__(name, output_dir, self.base_file, "= ", dependencies=[sim_task])
self.sim_task = sim_task
self.sim_version = sim_task.output["genversion"]
self.config_path = self.output_dir + "/" + self.sim_version + ".nml"
self.lc_output_dir = f"{self.output_dir}/output"
self.fitres_dir = f"{self.lc_output_dir}/{self.sim_version}"
self.set_num_jobs(int(config.get("NUM_JOBS", 100)))
self.logging_file = self.config_path.replace(".nml", ".nml_log")
self.done_file = f"{self.output_dir}/FINISHED.DONE"
secondary_log = f"{self.lc_output_dir}/SPLIT_JOBS_LCFIT/MERGELOGS/MERGE2.LOG"
self.log_files = [self.logging_file, secondary_log]
self.output["fitres_dir"] = self.fitres_dir
self.output["nml_file"] = self.config_path
self.output["genversion"] = self.sim_version
self.output["sim_name"] = sim_task.output["name"]
self.output["lc_output_dir"] = self.lc_output_dir
def get_sim_dependency(self):
for t in self.dependencies:
if isinstance(t, SNANASimulation) or isinstance(t, DataPrep):
return t.output
return None
def print_stats(self):
folders = [f for f in os.listdir(self.lc_output_dir) if f.startswith("PIP_") and os.path.isdir(self.lc_output_dir + "/" + f)]
for f in folders:
path = os.path.join(self.lc_output_dir, f)
data = pd.read_csv(os.path.join(path, "FITOPT000.FITRES.gz"), sep='\s+', comment="#", compression="infer")
counts = data.groupby("TYPE").size()
self.logger.info("Types: " + (" ".join([f"{k}:{v}" for k, v in zip(counts.index, counts.values)])))
def set_snlcinp(self, name, value):
self.set_property(name, value, section_start="&SNLCINP", section_end="&END")
def set_fitinp(self, name, value):
self.set_property(name, value, section_start="&FITINP", section_end="&END")
def write_nml(self, force_refresh):
self.logger.debug(f"Loading fitopts file from {self.fitopts_file}")
with open(self.fitopts_file, "r") as f:
self.fitopts = list(f.read().splitlines())
self.logger.info(f"Loaded {len(self.fitopts)} fitopts file from {self.fitopts_file}")
for key, value in self.config.get("SNLCINP", {}).items():
self.set_snlcinp(key, value)
for key, value in self.config.get("FITINP", {}).items():
self.set_fitinp(key, value)
self.set_property("VERSION", self.sim_version + "*", assignment=": ", section_end="&SNLCINP")
self.set_property("OUTDIR", self.lc_output_dir, assignment=": ", section_end="&SNLCINP")
if isinstance(self.sim_task, DataPrep):
self.set_snlcinp("PRIVATE_DATA_PATH", f"'{self.sim_task.output['data_path']}'")
self.set_snlcinp("VERSION_PHOTOMETRY", f"'{self.sim_task.output['genversion']}'")
string_to_hash = self.fitopts + self.base
new_hash = self.get_hash_from_string("".join(string_to_hash))
old_hash = self.get_old_hash()
regenerate = force_refresh or (old_hash is None or old_hash != new_hash)
if regenerate:
self.logger.info(f"Running Light curve fit. Removing output_dir")
shutil.rmtree(self.output_dir, ignore_errors=True)
mkdirs(self.output_dir)
with open(self.config_path, "w") as f:
f.writelines(map(lambda s: s + '\n', string_to_hash))
self.logger.info(f"NML file written to {self.config_path}")
self.save_new_hash(new_hash)
chown_dir(self.output_dir)
else:
self.logger.info("Hash check passed, not rerunning")
return regenerate, new_hash
def _run(self, force_refresh):
regenerate, new_hash = self.write_nml(force_refresh)
if not regenerate:
return True
self.logger.info(f"Light curve fitting outputting to {self.logging_file}")
with open(self.logging_file, "w") as f:
subprocess.run(["split_and_fit.pl", self.config_path, "NOPROMPT"], stdout=f, stderr=subprocess.STDOUT, cwd=self.output_dir)
return True
def _check_completion(self, squeue):
for file in self.log_files:
if os.path.exists(file):
with open(file, "r") as f:
output_error = False
for line in f.read().splitlines():
if ("ERROR" in line or ("ABORT" in line and " 0 " not in line)) and not output_error:
self.logger.error(f"Fatal error in light curve fitting. See {file} for details.")
output_error = True
if output_error:
self.logger.info(f"Excerpt: {line}")
if output_error:
return Task.FINISHED_FAILURE
if os.path.exists(self.done_file):
self.logger.info("Light curve done file found")
logging_file2 = self.logging_file.replace("_log", "_log2")
if not os.path.exists(logging_file2):
self.logger.info("Tarball found, fitting complete, cleaning up the directory")
try:
with open(logging_file2, "w") as f:
subprocess.run(["split_and_fit.pl", "CLEANMASK", "4", "NOPROMPT"], stdout=f, stderr=subprocess.STDOUT, cwd=self.output_dir, check=True)
time.sleep(2)
except subprocess.CalledProcessError as e:
self.logger.warning(f"split_and_fit.pl has a return code of {e.returncode}. This may or may not be an issue.")
chown_dir(self.output_dir)
self.print_stats()
self.output["fitres_file"] = os.path.abspath(os.path.join(self.fitres_dir, "FITOPT000.FITRES.gz"))
return Task.FINISHED_SUCCESS
return 0
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG, format="[%(levelname)7s |%(funcName)20s] %(message)s")
config = {"BASE": "des.nml", }
s = SNANALightCurveFit("../output/test", "testv", config, {})
s.set_snlcinp("CUTWIN_NBAND_THRESH", 1000)
s.set_snlcinp("HELLO", "'human'")
s.set_fitinp("FITWIN_PROB", "0.05, 1.01")
s.set_fitinp("GOODBYE", -1)
s.set_property("BATCH_INFO", "sbatch $SBATCH_TEMPLATES/SBATCH_sandyb.TEMPLATE 96", assignment=": ")
s.delete_property("GOODBYE")
s.write_nml()
| true | true |
1c2e60cc093706b62834ad86a94e249ff1421971 | 1,095 | py | Python | raythena/utils/logging.py | dougbenjamin/ray | 6f01cb1af4eb2fdd3c32fb3ebf21bb6405c4b540 | [
"Apache-2.0"
] | 3 | 2019-10-08T22:56:35.000Z | 2021-07-21T23:31:48.000Z | raythena/utils/logging.py | dougbenjamin/ray | 6f01cb1af4eb2fdd3c32fb3ebf21bb6405c4b540 | [
"Apache-2.0"
] | 4 | 2020-07-07T12:30:08.000Z | 2020-09-25T14:18:38.000Z | raythena/utils/logging.py | dougbenjamin/ray | 6f01cb1af4eb2fdd3c32fb3ebf21bb6405c4b540 | [
"Apache-2.0"
] | 5 | 2020-07-06T12:10:36.000Z | 2022-03-09T22:25:25.000Z | import logging
import os
import sys
from raythena.utils.config import Config
def configure_logger(config: Config, file_logging: bool = True) -> None:
"""
Configure the logging format and handlers.
Args:
config: application config
file_logging: if True, write logs to 'config.logging.logfile' in addition to stdout
Returns:
None
"""
if config.logging['level'].lower() == 'debug':
log_level = logging.DEBUG
else:
log_level = config.logging['level'].upper()
handlers = list()
ch = logging.StreamHandler(sys.stdout)
handlers.append(ch)
if file_logging:
logdir = os.path.expandvars(config.ray.get('workdir', os.getcwd()))
if not os.path.isdir(logdir):
logdir = os.getcwd()
log_file = os.path.join(logdir, config.logging['logfile'])
fh = logging.FileHandler(log_file, mode='w')
handlers.append(fh)
logging.basicConfig(
format="{levelname} | {message}",
style='{',
level=logging.getLevelName(log_level),
handlers=handlers)
| 27.375 | 91 | 0.632877 | import logging
import os
import sys
from raythena.utils.config import Config
def configure_logger(config: Config, file_logging: bool = True) -> None:
if config.logging['level'].lower() == 'debug':
log_level = logging.DEBUG
else:
log_level = config.logging['level'].upper()
handlers = list()
ch = logging.StreamHandler(sys.stdout)
handlers.append(ch)
if file_logging:
logdir = os.path.expandvars(config.ray.get('workdir', os.getcwd()))
if not os.path.isdir(logdir):
logdir = os.getcwd()
log_file = os.path.join(logdir, config.logging['logfile'])
fh = logging.FileHandler(log_file, mode='w')
handlers.append(fh)
logging.basicConfig(
format="{levelname} | {message}",
style='{',
level=logging.getLevelName(log_level),
handlers=handlers)
| true | true |
1c2e6185f1083da1c3e89b821714bfff2b3c1517 | 28,916 | py | Python | scipy/special/tests/test_data.py | HumHongeKamyaab/scipy | ce61e02e912d15ea28b37ea036334b9ba266ebb5 | [
"BSD-3-Clause"
] | null | null | null | scipy/special/tests/test_data.py | HumHongeKamyaab/scipy | ce61e02e912d15ea28b37ea036334b9ba266ebb5 | [
"BSD-3-Clause"
] | null | null | null | scipy/special/tests/test_data.py | HumHongeKamyaab/scipy | ce61e02e912d15ea28b37ea036334b9ba266ebb5 | [
"BSD-3-Clause"
] | null | null | null | import os
import numpy as np
from numpy import arccosh, arcsinh, arctanh
from numpy.testing import suppress_warnings
import pytest
from scipy.special import (
lpn, lpmn, lpmv, lqn, lqmn, sph_harm, eval_legendre, eval_hermite,
eval_laguerre, eval_genlaguerre, binom, cbrt, expm1, log1p, zeta,
jn, jv, jvp, yn, yv, yvp, iv, ivp, kn, kv, kvp,
gamma, gammaln, gammainc, gammaincc, gammaincinv, gammainccinv, digamma,
beta, betainc, betaincinv, poch,
ellipe, ellipeinc, ellipk, ellipkm1, ellipkinc, ellipj,
elliprc, elliprd, elliprf, elliprg, elliprj,
erf, erfc, erfinv, erfcinv, exp1, expi, expn,
bdtrik, btdtr, btdtri, btdtria, btdtrib, chndtr, gdtr, gdtrc, gdtrix, gdtrib,
nbdtrik, pdtrik, owens_t,
mathieu_a, mathieu_b, mathieu_cem, mathieu_sem, mathieu_modcem1,
mathieu_modsem1, mathieu_modcem2, mathieu_modsem2,
ellip_harm, ellip_harm_2, spherical_jn, spherical_yn,
)
from scipy.integrate import IntegrationWarning
from scipy.special._testutils import FuncData
DATASETS_BOOST = np.load(os.path.join(os.path.dirname(__file__),
"data", "boost.npz"))
DATASETS_GSL = np.load(os.path.join(os.path.dirname(__file__),
"data", "gsl.npz"))
DATASETS_LOCAL = np.load(os.path.join(os.path.dirname(__file__),
"data", "local.npz"))
def data(func, dataname, *a, **kw):
kw.setdefault('dataname', dataname)
return FuncData(func, DATASETS_BOOST[dataname], *a, **kw)
def data_gsl(func, dataname, *a, **kw):
kw.setdefault('dataname', dataname)
return FuncData(func, DATASETS_GSL[dataname], *a, **kw)
def data_local(func, dataname, *a, **kw):
kw.setdefault('dataname', dataname)
return FuncData(func, DATASETS_LOCAL[dataname], *a, **kw)
def ellipk_(k):
return ellipk(k*k)
def ellipkinc_(f, k):
return ellipkinc(f, k*k)
def ellipe_(k):
return ellipe(k*k)
def ellipeinc_(f, k):
return ellipeinc(f, k*k)
def ellipj_(k):
return ellipj(k*k)
def zeta_(x):
return zeta(x, 1.)
def assoc_legendre_p_boost_(nu, mu, x):
# the boost test data is for integer orders only
return lpmv(mu, nu.astype(int), x)
def legendre_p_via_assoc_(nu, x):
return lpmv(0, nu, x)
def lpn_(n, x):
return lpn(n.astype('l'), x)[0][-1]
def lqn_(n, x):
return lqn(n.astype('l'), x)[0][-1]
def legendre_p_via_lpmn(n, x):
return lpmn(0, n, x)[0][0,-1]
def legendre_q_via_lqmn(n, x):
return lqmn(0, n, x)[0][0,-1]
def mathieu_ce_rad(m, q, x):
return mathieu_cem(m, q, x*180/np.pi)[0]
def mathieu_se_rad(m, q, x):
return mathieu_sem(m, q, x*180/np.pi)[0]
def mathieu_mc1_scaled(m, q, x):
# GSL follows a different normalization.
# We follow Abramowitz & Stegun, they apparently something else.
return mathieu_modcem1(m, q, x)[0] * np.sqrt(np.pi/2)
def mathieu_ms1_scaled(m, q, x):
return mathieu_modsem1(m, q, x)[0] * np.sqrt(np.pi/2)
def mathieu_mc2_scaled(m, q, x):
return mathieu_modcem2(m, q, x)[0] * np.sqrt(np.pi/2)
def mathieu_ms2_scaled(m, q, x):
return mathieu_modsem2(m, q, x)[0] * np.sqrt(np.pi/2)
def eval_legendre_ld(n, x):
return eval_legendre(n.astype('l'), x)
def eval_legendre_dd(n, x):
return eval_legendre(n.astype('d'), x)
def eval_hermite_ld(n, x):
return eval_hermite(n.astype('l'), x)
def eval_laguerre_ld(n, x):
return eval_laguerre(n.astype('l'), x)
def eval_laguerre_dd(n, x):
return eval_laguerre(n.astype('d'), x)
def eval_genlaguerre_ldd(n, a, x):
return eval_genlaguerre(n.astype('l'), a, x)
def eval_genlaguerre_ddd(n, a, x):
return eval_genlaguerre(n.astype('d'), a, x)
def bdtrik_comp(y, n, p):
return bdtrik(1-y, n, p)
def btdtri_comp(a, b, p):
return btdtri(a, b, 1-p)
def btdtria_comp(p, b, x):
return btdtria(1-p, b, x)
def btdtrib_comp(a, p, x):
return btdtrib(a, 1-p, x)
def gdtr_(p, x):
return gdtr(1.0, p, x)
def gdtrc_(p, x):
return gdtrc(1.0, p, x)
def gdtrix_(b, p):
return gdtrix(1.0, b, p)
def gdtrix_comp(b, p):
return gdtrix(1.0, b, 1-p)
def gdtrib_(p, x):
return gdtrib(1.0, p, x)
def gdtrib_comp(p, x):
return gdtrib(1.0, 1-p, x)
def nbdtrik_comp(y, n, p):
return nbdtrik(1-y, n, p)
def pdtrik_comp(p, m):
return pdtrik(1-p, m)
def poch_(z, m):
return 1.0 / poch(z, m)
def poch_minus(z, m):
return 1.0 / poch(z, -m)
def spherical_jn_(n, x):
return spherical_jn(n.astype('l'), x)
def spherical_yn_(n, x):
return spherical_yn(n.astype('l'), x)
def sph_harm_(m, n, theta, phi):
y = sph_harm(m, n, theta, phi)
return (y.real, y.imag)
def cexpm1(x, y):
z = expm1(x + 1j*y)
return z.real, z.imag
def clog1p(x, y):
z = log1p(x + 1j*y)
return z.real, z.imag
BOOST_TESTS = [
data(arccosh, 'acosh_data_ipp-acosh_data', 0, 1, rtol=5e-13),
data(arccosh, 'acosh_data_ipp-acosh_data', 0j, 1, rtol=5e-13),
data(arcsinh, 'asinh_data_ipp-asinh_data', 0, 1, rtol=1e-11),
data(arcsinh, 'asinh_data_ipp-asinh_data', 0j, 1, rtol=1e-11),
data(arctanh, 'atanh_data_ipp-atanh_data', 0, 1, rtol=1e-11),
data(arctanh, 'atanh_data_ipp-atanh_data', 0j, 1, rtol=1e-11),
data(assoc_legendre_p_boost_, 'assoc_legendre_p_ipp-assoc_legendre_p', (0,1,2), 3, rtol=1e-11),
data(legendre_p_via_assoc_, 'legendre_p_ipp-legendre_p', (0,1), 2, rtol=1e-11),
data(legendre_p_via_assoc_, 'legendre_p_large_ipp-legendre_p_large', (0,1), 2, rtol=9.6e-14),
data(legendre_p_via_lpmn, 'legendre_p_ipp-legendre_p', (0,1), 2, rtol=5e-14, vectorized=False),
data(legendre_p_via_lpmn, 'legendre_p_large_ipp-legendre_p_large', (0,1), 2, rtol=9.6e-14, vectorized=False),
data(lpn_, 'legendre_p_ipp-legendre_p', (0,1), 2, rtol=5e-14, vectorized=False),
data(lpn_, 'legendre_p_large_ipp-legendre_p_large', (0,1), 2, rtol=3e-13, vectorized=False),
data(eval_legendre_ld, 'legendre_p_ipp-legendre_p', (0,1), 2, rtol=6e-14),
data(eval_legendre_ld, 'legendre_p_large_ipp-legendre_p_large', (0,1), 2, rtol=2e-13),
data(eval_legendre_dd, 'legendre_p_ipp-legendre_p', (0,1), 2, rtol=2e-14),
data(eval_legendre_dd, 'legendre_p_large_ipp-legendre_p_large', (0,1), 2, rtol=2e-13),
data(lqn_, 'legendre_p_ipp-legendre_p', (0,1), 3, rtol=2e-14, vectorized=False),
data(lqn_, 'legendre_p_large_ipp-legendre_p_large', (0,1), 3, rtol=2e-12, vectorized=False),
data(legendre_q_via_lqmn, 'legendre_p_ipp-legendre_p', (0,1), 3, rtol=2e-14, vectorized=False),
data(legendre_q_via_lqmn, 'legendre_p_large_ipp-legendre_p_large', (0,1), 3, rtol=2e-12, vectorized=False),
data(beta, 'beta_exp_data_ipp-beta_exp_data', (0,1), 2, rtol=1e-13),
data(beta, 'beta_exp_data_ipp-beta_exp_data', (0,1), 2, rtol=1e-13),
data(beta, 'beta_med_data_ipp-beta_med_data', (0,1), 2, rtol=5e-13),
data(betainc, 'ibeta_small_data_ipp-ibeta_small_data', (0,1,2), 5, rtol=6e-15),
data(betainc, 'ibeta_data_ipp-ibeta_data', (0,1,2), 5, rtol=5e-13),
data(betainc, 'ibeta_int_data_ipp-ibeta_int_data', (0,1,2), 5, rtol=2e-14),
data(betainc, 'ibeta_large_data_ipp-ibeta_large_data', (0,1,2), 5, rtol=4e-10),
data(betaincinv, 'ibeta_inv_data_ipp-ibeta_inv_data', (0,1,2), 3, rtol=1e-5),
data(btdtr, 'ibeta_small_data_ipp-ibeta_small_data', (0,1,2), 5, rtol=6e-15),
data(btdtr, 'ibeta_data_ipp-ibeta_data', (0,1,2), 5, rtol=4e-13),
data(btdtr, 'ibeta_int_data_ipp-ibeta_int_data', (0,1,2), 5, rtol=2e-14),
data(btdtr, 'ibeta_large_data_ipp-ibeta_large_data', (0,1,2), 5, rtol=4e-10),
data(btdtri, 'ibeta_inv_data_ipp-ibeta_inv_data', (0,1,2), 3, rtol=1e-5),
data(btdtri_comp, 'ibeta_inv_data_ipp-ibeta_inv_data', (0,1,2), 4, rtol=8e-7),
data(btdtria, 'ibeta_inva_data_ipp-ibeta_inva_data', (2,0,1), 3, rtol=5e-9),
data(btdtria_comp, 'ibeta_inva_data_ipp-ibeta_inva_data', (2,0,1), 4, rtol=5e-9),
data(btdtrib, 'ibeta_inva_data_ipp-ibeta_inva_data', (0,2,1), 5, rtol=5e-9),
data(btdtrib_comp, 'ibeta_inva_data_ipp-ibeta_inva_data', (0,2,1), 6, rtol=5e-9),
data(binom, 'binomial_data_ipp-binomial_data', (0,1), 2, rtol=1e-13),
data(binom, 'binomial_large_data_ipp-binomial_large_data', (0,1), 2, rtol=5e-13),
data(bdtrik, 'binomial_quantile_ipp-binomial_quantile_data', (2,0,1), 3, rtol=5e-9),
data(bdtrik_comp, 'binomial_quantile_ipp-binomial_quantile_data', (2,0,1), 4, rtol=5e-9),
data(nbdtrik, 'negative_binomial_quantile_ipp-negative_binomial_quantile_data', (2,0,1), 3, rtol=4e-9),
data(nbdtrik_comp, 'negative_binomial_quantile_ipp-negative_binomial_quantile_data', (2,0,1), 4, rtol=4e-9),
data(pdtrik, 'poisson_quantile_ipp-poisson_quantile_data', (1,0), 2, rtol=3e-9),
data(pdtrik_comp, 'poisson_quantile_ipp-poisson_quantile_data', (1,0), 3, rtol=4e-9),
data(cbrt, 'cbrt_data_ipp-cbrt_data', 1, 0),
data(digamma, 'digamma_data_ipp-digamma_data', 0, 1),
data(digamma, 'digamma_data_ipp-digamma_data', 0j, 1),
data(digamma, 'digamma_neg_data_ipp-digamma_neg_data', 0, 1, rtol=2e-13),
data(digamma, 'digamma_neg_data_ipp-digamma_neg_data', 0j, 1, rtol=1e-13),
data(digamma, 'digamma_root_data_ipp-digamma_root_data', 0, 1, rtol=1e-15),
data(digamma, 'digamma_root_data_ipp-digamma_root_data', 0j, 1, rtol=1e-15),
data(digamma, 'digamma_small_data_ipp-digamma_small_data', 0, 1, rtol=1e-15),
data(digamma, 'digamma_small_data_ipp-digamma_small_data', 0j, 1, rtol=1e-14),
data(ellipk_, 'ellint_k_data_ipp-ellint_k_data', 0, 1),
data(ellipkinc_, 'ellint_f_data_ipp-ellint_f_data', (0,1), 2, rtol=1e-14),
data(ellipe_, 'ellint_e_data_ipp-ellint_e_data', 0, 1),
data(ellipeinc_, 'ellint_e2_data_ipp-ellint_e2_data', (0,1), 2, rtol=1e-14),
data(erf, 'erf_data_ipp-erf_data', 0, 1),
data(erf, 'erf_data_ipp-erf_data', 0j, 1, rtol=1e-13),
data(erfc, 'erf_data_ipp-erf_data', 0, 2, rtol=6e-15),
data(erf, 'erf_large_data_ipp-erf_large_data', 0, 1),
data(erf, 'erf_large_data_ipp-erf_large_data', 0j, 1),
data(erfc, 'erf_large_data_ipp-erf_large_data', 0, 2, rtol=4e-14),
data(erf, 'erf_small_data_ipp-erf_small_data', 0, 1),
data(erf, 'erf_small_data_ipp-erf_small_data', 0j, 1, rtol=1e-13),
data(erfc, 'erf_small_data_ipp-erf_small_data', 0, 2),
data(erfinv, 'erf_inv_data_ipp-erf_inv_data', 0, 1),
data(erfcinv, 'erfc_inv_data_ipp-erfc_inv_data', 0, 1),
data(erfcinv, 'erfc_inv_big_data_ipp-erfc_inv_big_data', 0, 1, param_filter=(lambda s: s > 0)),
data(exp1, 'expint_1_data_ipp-expint_1_data', 1, 2, rtol=1e-13),
data(exp1, 'expint_1_data_ipp-expint_1_data', 1j, 2, rtol=5e-9),
data(expi, 'expinti_data_ipp-expinti_data', 0, 1, rtol=1e-13),
data(expi, 'expinti_data_double_ipp-expinti_data_double', 0, 1, rtol=1e-13),
data(expi, 'expinti_data_long_ipp-expinti_data_long', 0, 1),
data(expn, 'expint_small_data_ipp-expint_small_data', (0,1), 2),
data(expn, 'expint_data_ipp-expint_data', (0,1), 2, rtol=1e-14),
data(gamma, 'test_gamma_data_ipp-near_0', 0, 1),
data(gamma, 'test_gamma_data_ipp-near_1', 0, 1),
data(gamma, 'test_gamma_data_ipp-near_2', 0, 1),
data(gamma, 'test_gamma_data_ipp-near_m10', 0, 1),
data(gamma, 'test_gamma_data_ipp-near_m55', 0, 1, rtol=7e-12),
data(gamma, 'test_gamma_data_ipp-factorials', 0, 1, rtol=4e-14),
data(gamma, 'test_gamma_data_ipp-near_0', 0j, 1, rtol=2e-9),
data(gamma, 'test_gamma_data_ipp-near_1', 0j, 1, rtol=2e-9),
data(gamma, 'test_gamma_data_ipp-near_2', 0j, 1, rtol=2e-9),
data(gamma, 'test_gamma_data_ipp-near_m10', 0j, 1, rtol=2e-9),
data(gamma, 'test_gamma_data_ipp-near_m55', 0j, 1, rtol=2e-9),
data(gamma, 'test_gamma_data_ipp-factorials', 0j, 1, rtol=2e-13),
data(gammaln, 'test_gamma_data_ipp-near_0', 0, 2, rtol=5e-11),
data(gammaln, 'test_gamma_data_ipp-near_1', 0, 2, rtol=5e-11),
data(gammaln, 'test_gamma_data_ipp-near_2', 0, 2, rtol=2e-10),
data(gammaln, 'test_gamma_data_ipp-near_m10', 0, 2, rtol=5e-11),
data(gammaln, 'test_gamma_data_ipp-near_m55', 0, 2, rtol=5e-11),
data(gammaln, 'test_gamma_data_ipp-factorials', 0, 2),
data(gammainc, 'igamma_small_data_ipp-igamma_small_data', (0,1), 5, rtol=5e-15),
data(gammainc, 'igamma_med_data_ipp-igamma_med_data', (0,1), 5, rtol=2e-13),
data(gammainc, 'igamma_int_data_ipp-igamma_int_data', (0,1), 5, rtol=2e-13),
data(gammainc, 'igamma_big_data_ipp-igamma_big_data', (0,1), 5, rtol=1e-12),
data(gdtr_, 'igamma_small_data_ipp-igamma_small_data', (0,1), 5, rtol=1e-13),
data(gdtr_, 'igamma_med_data_ipp-igamma_med_data', (0,1), 5, rtol=2e-13),
data(gdtr_, 'igamma_int_data_ipp-igamma_int_data', (0,1), 5, rtol=2e-13),
data(gdtr_, 'igamma_big_data_ipp-igamma_big_data', (0,1), 5, rtol=2e-9),
data(gammaincc, 'igamma_small_data_ipp-igamma_small_data', (0,1), 3, rtol=1e-13),
data(gammaincc, 'igamma_med_data_ipp-igamma_med_data', (0,1), 3, rtol=2e-13),
data(gammaincc, 'igamma_int_data_ipp-igamma_int_data', (0,1), 3, rtol=4e-14),
data(gammaincc, 'igamma_big_data_ipp-igamma_big_data', (0,1), 3, rtol=1e-11),
data(gdtrc_, 'igamma_small_data_ipp-igamma_small_data', (0,1), 3, rtol=1e-13),
data(gdtrc_, 'igamma_med_data_ipp-igamma_med_data', (0,1), 3, rtol=2e-13),
data(gdtrc_, 'igamma_int_data_ipp-igamma_int_data', (0,1), 3, rtol=4e-14),
data(gdtrc_, 'igamma_big_data_ipp-igamma_big_data', (0,1), 3, rtol=1e-11),
data(gdtrib_, 'igamma_inva_data_ipp-igamma_inva_data', (1,0), 2, rtol=5e-9),
data(gdtrib_comp, 'igamma_inva_data_ipp-igamma_inva_data', (1,0), 3, rtol=5e-9),
data(poch_, 'tgamma_delta_ratio_data_ipp-tgamma_delta_ratio_data', (0,1), 2, rtol=2e-13),
data(poch_, 'tgamma_delta_ratio_int_ipp-tgamma_delta_ratio_int', (0,1), 2,),
data(poch_, 'tgamma_delta_ratio_int2_ipp-tgamma_delta_ratio_int2', (0,1), 2,),
data(poch_minus, 'tgamma_delta_ratio_data_ipp-tgamma_delta_ratio_data', (0,1), 3, rtol=2e-13),
data(poch_minus, 'tgamma_delta_ratio_int_ipp-tgamma_delta_ratio_int', (0,1), 3),
data(poch_minus, 'tgamma_delta_ratio_int2_ipp-tgamma_delta_ratio_int2', (0,1), 3),
data(eval_hermite_ld, 'hermite_ipp-hermite', (0,1), 2, rtol=2e-14),
data(eval_laguerre_ld, 'laguerre2_ipp-laguerre2', (0,1), 2, rtol=7e-12),
data(eval_laguerre_dd, 'laguerre2_ipp-laguerre2', (0,1), 2, knownfailure='hyp2f1 insufficiently accurate.'),
data(eval_genlaguerre_ldd, 'laguerre3_ipp-laguerre3', (0,1,2), 3, rtol=2e-13),
data(eval_genlaguerre_ddd, 'laguerre3_ipp-laguerre3', (0,1,2), 3, knownfailure='hyp2f1 insufficiently accurate.'),
data(log1p, 'log1p_expm1_data_ipp-log1p_expm1_data', 0, 1),
data(expm1, 'log1p_expm1_data_ipp-log1p_expm1_data', 0, 2),
data(iv, 'bessel_i_data_ipp-bessel_i_data', (0,1), 2, rtol=1e-12),
data(iv, 'bessel_i_data_ipp-bessel_i_data', (0,1j), 2, rtol=2e-10, atol=1e-306),
data(iv, 'bessel_i_int_data_ipp-bessel_i_int_data', (0,1), 2, rtol=1e-9),
data(iv, 'bessel_i_int_data_ipp-bessel_i_int_data', (0,1j), 2, rtol=2e-10),
data(ivp, 'bessel_i_prime_int_data_ipp-bessel_i_prime_int_data', (0,1), 2, rtol=1.2e-13),
data(ivp, 'bessel_i_prime_int_data_ipp-bessel_i_prime_int_data', (0,1j), 2, rtol=1.2e-13, atol=1e-300),
data(jn, 'bessel_j_int_data_ipp-bessel_j_int_data', (0,1), 2, rtol=1e-12),
data(jn, 'bessel_j_int_data_ipp-bessel_j_int_data', (0,1j), 2, rtol=1e-12),
data(jn, 'bessel_j_large_data_ipp-bessel_j_large_data', (0,1), 2, rtol=6e-11),
data(jn, 'bessel_j_large_data_ipp-bessel_j_large_data', (0,1j), 2, rtol=6e-11),
data(jv, 'bessel_j_int_data_ipp-bessel_j_int_data', (0,1), 2, rtol=1e-12),
data(jv, 'bessel_j_int_data_ipp-bessel_j_int_data', (0,1j), 2, rtol=1e-12),
data(jv, 'bessel_j_data_ipp-bessel_j_data', (0,1), 2, rtol=1e-12),
data(jv, 'bessel_j_data_ipp-bessel_j_data', (0,1j), 2, rtol=1e-12),
data(jvp, 'bessel_j_prime_int_data_ipp-bessel_j_prime_int_data', (0,1), 2, rtol=1e-13),
data(jvp, 'bessel_j_prime_int_data_ipp-bessel_j_prime_int_data', (0,1j), 2, rtol=1e-13),
data(jvp, 'bessel_j_prime_large_data_ipp-bessel_j_prime_large_data', (0,1), 2, rtol=1e-11),
data(jvp, 'bessel_j_prime_large_data_ipp-bessel_j_prime_large_data', (0,1j), 2, rtol=1e-11),
data(kn, 'bessel_k_int_data_ipp-bessel_k_int_data', (0,1), 2, rtol=1e-12),
data(kv, 'bessel_k_int_data_ipp-bessel_k_int_data', (0,1), 2, rtol=1e-12),
data(kv, 'bessel_k_int_data_ipp-bessel_k_int_data', (0,1j), 2, rtol=1e-12),
data(kv, 'bessel_k_data_ipp-bessel_k_data', (0,1), 2, rtol=1e-12),
data(kv, 'bessel_k_data_ipp-bessel_k_data', (0,1j), 2, rtol=1e-12),
data(kvp, 'bessel_k_prime_int_data_ipp-bessel_k_prime_int_data', (0,1), 2, rtol=3e-14),
data(kvp, 'bessel_k_prime_int_data_ipp-bessel_k_prime_int_data', (0,1j), 2, rtol=3e-14),
data(kvp, 'bessel_k_prime_data_ipp-bessel_k_prime_data', (0,1), 2, rtol=7e-14),
data(kvp, 'bessel_k_prime_data_ipp-bessel_k_prime_data', (0,1j), 2, rtol=7e-14),
data(yn, 'bessel_y01_data_ipp-bessel_y01_data', (0,1), 2, rtol=1e-12),
data(yn, 'bessel_yn_data_ipp-bessel_yn_data', (0,1), 2, rtol=1e-12),
data(yv, 'bessel_yn_data_ipp-bessel_yn_data', (0,1), 2, rtol=1e-12),
data(yv, 'bessel_yn_data_ipp-bessel_yn_data', (0,1j), 2, rtol=1e-12),
data(yv, 'bessel_yv_data_ipp-bessel_yv_data', (0,1), 2, rtol=1e-10),
data(yv, 'bessel_yv_data_ipp-bessel_yv_data', (0,1j), 2, rtol=1e-10),
data(yvp, 'bessel_yv_prime_data_ipp-bessel_yv_prime_data', (0, 1), 2, rtol=4e-9),
data(yvp, 'bessel_yv_prime_data_ipp-bessel_yv_prime_data', (0, 1j), 2, rtol=4e-9),
data(zeta_, 'zeta_data_ipp-zeta_data', 0, 1, param_filter=(lambda s: s > 1)),
data(zeta_, 'zeta_neg_data_ipp-zeta_neg_data', 0, 1, param_filter=(lambda s: s > 1)),
data(zeta_, 'zeta_1_up_data_ipp-zeta_1_up_data', 0, 1, param_filter=(lambda s: s > 1)),
data(zeta_, 'zeta_1_below_data_ipp-zeta_1_below_data', 0, 1, param_filter=(lambda s: s > 1)),
data(gammaincinv, 'gamma_inv_small_data_ipp-gamma_inv_small_data', (0,1), 2, rtol=1e-11),
data(gammaincinv, 'gamma_inv_data_ipp-gamma_inv_data', (0,1), 2, rtol=1e-14),
data(gammaincinv, 'gamma_inv_big_data_ipp-gamma_inv_big_data', (0,1), 2, rtol=1e-11),
data(gammainccinv, 'gamma_inv_small_data_ipp-gamma_inv_small_data', (0,1), 3, rtol=1e-12),
data(gammainccinv, 'gamma_inv_data_ipp-gamma_inv_data', (0,1), 3, rtol=1e-14),
data(gammainccinv, 'gamma_inv_big_data_ipp-gamma_inv_big_data', (0,1), 3, rtol=1e-14),
data(gdtrix_, 'gamma_inv_small_data_ipp-gamma_inv_small_data', (0,1), 2, rtol=3e-13, knownfailure='gdtrix unflow some points'),
data(gdtrix_, 'gamma_inv_data_ipp-gamma_inv_data', (0,1), 2, rtol=3e-15),
data(gdtrix_, 'gamma_inv_big_data_ipp-gamma_inv_big_data', (0,1), 2),
data(gdtrix_comp, 'gamma_inv_small_data_ipp-gamma_inv_small_data', (0,1), 2, knownfailure='gdtrix bad some points'),
data(gdtrix_comp, 'gamma_inv_data_ipp-gamma_inv_data', (0,1), 3, rtol=6e-15),
data(gdtrix_comp, 'gamma_inv_big_data_ipp-gamma_inv_big_data', (0,1), 3),
data(chndtr, 'nccs_ipp-nccs', (2,0,1), 3, rtol=3e-5),
data(chndtr, 'nccs_big_ipp-nccs_big', (2,0,1), 3, rtol=5e-4, knownfailure='chndtr inaccurate some points'),
data(sph_harm_, 'spherical_harmonic_ipp-spherical_harmonic', (1,0,3,2), (4,5), rtol=5e-11,
param_filter=(lambda p: np.ones(p.shape, '?'),
lambda p: np.ones(p.shape, '?'),
lambda p: np.logical_and(p < 2*np.pi, p >= 0),
lambda p: np.logical_and(p < np.pi, p >= 0))),
data(spherical_jn_, 'sph_bessel_data_ipp-sph_bessel_data', (0,1), 2, rtol=1e-13),
data(spherical_yn_, 'sph_neumann_data_ipp-sph_neumann_data', (0,1), 2, rtol=8e-15),
data(owens_t, 'owens_t_ipp-owens_t', (0, 1), 2, rtol=5e-14),
data(owens_t, 'owens_t_large_data_ipp-owens_t_large_data', (0, 1), 2, rtol=8e-12),
# -- test data exists in boost but is not used in scipy --
# ibeta_derivative_data_ipp/ibeta_derivative_data.txt
# ibeta_derivative_int_data_ipp/ibeta_derivative_int_data.txt
# ibeta_derivative_large_data_ipp/ibeta_derivative_large_data.txt
# ibeta_derivative_small_data_ipp/ibeta_derivative_small_data.txt
# bessel_y01_prime_data_ipp/bessel_y01_prime_data.txt
# bessel_yn_prime_data_ipp/bessel_yn_prime_data.txt
# sph_bessel_prime_data_ipp/sph_bessel_prime_data.txt
# sph_neumann_prime_data_ipp/sph_neumann_prime_data.txt
# ellint_d2_data_ipp/ellint_d2_data.txt
# ellint_d_data_ipp/ellint_d_data.txt
# ellint_pi2_data_ipp/ellint_pi2_data.txt
# ellint_pi3_data_ipp/ellint_pi3_data.txt
# ellint_pi3_large_data_ipp/ellint_pi3_large_data.txt
data(elliprc, 'ellint_rc_data_ipp-ellint_rc_data', (0, 1), 2,
rtol=5e-16),
data(elliprd, 'ellint_rd_data_ipp-ellint_rd_data', (0, 1, 2), 3,
rtol=5e-16),
data(elliprd, 'ellint_rd_0xy_ipp-ellint_rd_0xy', (0, 1, 2), 3,
rtol=5e-16),
data(elliprd, 'ellint_rd_0yy_ipp-ellint_rd_0yy', (0, 1, 2), 3,
rtol=5e-16),
data(elliprd, 'ellint_rd_xxx_ipp-ellint_rd_xxx', (0, 1, 2), 3,
rtol=5e-16),
# Some of the following rtol for elliprd may be larger than 5e-16 to
# work around some hard cases in the Boost test where we get slightly
# larger error than the ideal bound when the x (==y) input is close to
# zero.
# Also the accuracy on 32-bit buids with g++ may suffer from excess
# loss of precision; see GCC bugzilla 323
# https://gcc.gnu.org/bugzilla/show_bug.cgi?id=323
data(elliprd, 'ellint_rd_xxz_ipp-ellint_rd_xxz', (0, 1, 2), 3,
rtol=6.5e-16),
data(elliprd, 'ellint_rd_xyy_ipp-ellint_rd_xyy', (0, 1, 2), 3,
rtol=6e-16),
data(elliprf, 'ellint_rf_data_ipp-ellint_rf_data', (0, 1, 2), 3,
rtol=5e-16),
data(elliprf, 'ellint_rf_xxx_ipp-ellint_rf_xxx', (0, 1, 2), 3,
rtol=5e-16),
data(elliprf, 'ellint_rf_xyy_ipp-ellint_rf_xyy', (0, 1, 2), 3,
rtol=5e-16),
data(elliprf, 'ellint_rf_xy0_ipp-ellint_rf_xy0', (0, 1, 2), 3,
rtol=5e-16),
data(elliprf, 'ellint_rf_0yy_ipp-ellint_rf_0yy', (0, 1, 2), 3,
rtol=5e-16),
# The accuracy of R_G is primarily limited by R_D that is used
# internally. It is generally worse than R_D. Notice that we increased
# the rtol for R_G here. The cases with duplicate arguments are
# slightly less likely to be unbalanced (at least two arguments are
# already balanced) so the error bound is slightly better. Again,
# precision with g++ 32-bit is even worse.
data(elliprg, 'ellint_rg_ipp-ellint_rg', (0, 1, 2), 3,
rtol=8.0e-16),
data(elliprg, 'ellint_rg_xxx_ipp-ellint_rg_xxx', (0, 1, 2), 3,
rtol=6e-16),
data(elliprg, 'ellint_rg_xyy_ipp-ellint_rg_xyy', (0, 1, 2), 3,
rtol=7.5e-16),
data(elliprg, 'ellint_rg_xy0_ipp-ellint_rg_xy0', (0, 1, 2), 3,
rtol=5e-16),
data(elliprg, 'ellint_rg_00x_ipp-ellint_rg_00x', (0, 1, 2), 3,
rtol=5e-16),
data(elliprj, 'ellint_rj_data_ipp-ellint_rj_data', (0, 1, 2, 3), 4,
rtol=5e-16, atol=1e-25,
param_filter=(lambda s: s <= 5e-26,)),
# ellint_rc_data_ipp/ellint_rc_data.txt
# ellint_rd_0xy_ipp/ellint_rd_0xy.txt
# ellint_rd_0yy_ipp/ellint_rd_0yy.txt
# ellint_rd_data_ipp/ellint_rd_data.txt
# ellint_rd_xxx_ipp/ellint_rd_xxx.txt
# ellint_rd_xxz_ipp/ellint_rd_xxz.txt
# ellint_rd_xyy_ipp/ellint_rd_xyy.txt
# ellint_rf_0yy_ipp/ellint_rf_0yy.txt
# ellint_rf_data_ipp/ellint_rf_data.txt
# ellint_rf_xxx_ipp/ellint_rf_xxx.txt
# ellint_rf_xy0_ipp/ellint_rf_xy0.txt
# ellint_rf_xyy_ipp/ellint_rf_xyy.txt
# ellint_rg_00x_ipp/ellint_rg_00x.txt
# ellint_rg_ipp/ellint_rg.txt
# ellint_rg_xxx_ipp/ellint_rg_xxx.txt
# ellint_rg_xy0_ipp/ellint_rg_xy0.txt
# ellint_rg_xyy_ipp/ellint_rg_xyy.txt
# ellint_rj_data_ipp/ellint_rj_data.txt
# ellint_rj_e2_ipp/ellint_rj_e2.txt
# ellint_rj_e3_ipp/ellint_rj_e3.txt
# ellint_rj_e4_ipp/ellint_rj_e4.txt
# ellint_rj_zp_ipp/ellint_rj_zp.txt
# jacobi_elliptic_ipp/jacobi_elliptic.txt
# jacobi_elliptic_small_ipp/jacobi_elliptic_small.txt
# jacobi_large_phi_ipp/jacobi_large_phi.txt
# jacobi_near_1_ipp/jacobi_near_1.txt
# jacobi_zeta_big_phi_ipp/jacobi_zeta_big_phi.txt
# jacobi_zeta_data_ipp/jacobi_zeta_data.txt
# heuman_lambda_data_ipp/heuman_lambda_data.txt
# hypergeometric_0F2_ipp/hypergeometric_0F2.txt
# hypergeometric_1F1_big_ipp/hypergeometric_1F1_big.txt
# hypergeometric_1F1_ipp/hypergeometric_1F1.txt
# hypergeometric_1F1_small_random_ipp/hypergeometric_1F1_small_random.txt
# hypergeometric_1F2_ipp/hypergeometric_1F2.txt
# hypergeometric_1f1_large_regularized_ipp/hypergeometric_1f1_large_regularized.txt
# hypergeometric_1f1_log_large_unsolved_ipp/hypergeometric_1f1_log_large_unsolved.txt
# hypergeometric_2F0_half_ipp/hypergeometric_2F0_half.txt
# hypergeometric_2F0_integer_a2_ipp/hypergeometric_2F0_integer_a2.txt
# hypergeometric_2F0_ipp/hypergeometric_2F0.txt
# hypergeometric_2F0_large_z_ipp/hypergeometric_2F0_large_z.txt
# hypergeometric_2F1_ipp/hypergeometric_2F1.txt
# hypergeometric_2F2_ipp/hypergeometric_2F2.txt
# ncbeta_big_ipp/ncbeta_big.txt
# nct_small_delta_ipp/nct_small_delta.txt
# nct_asym_ipp/nct_asym.txt
# ncbeta_ipp/ncbeta.txt
# powm1_data_ipp/powm1_big_data.txt
# powm1_sqrtp1m1_test_hpp/sqrtp1m1_data.txt
# sinc_data_ipp/sinc_data.txt
# test_gamma_data_ipp/gammap1m1_data.txt
# tgamma_ratio_data_ipp/tgamma_ratio_data.txt
# trig_data_ipp/trig_data.txt
# trig_data2_ipp/trig_data2.txt
]
@pytest.mark.parametrize('test', BOOST_TESTS, ids=repr)
def test_boost(test):
_test_factory(test)
GSL_TESTS = [
data_gsl(mathieu_a, 'mathieu_ab', (0, 1), 2, rtol=1e-13, atol=1e-13),
data_gsl(mathieu_b, 'mathieu_ab', (0, 1), 3, rtol=1e-13, atol=1e-13),
# Also the GSL output has limited accuracy...
data_gsl(mathieu_ce_rad, 'mathieu_ce_se', (0, 1, 2), 3, rtol=1e-7, atol=1e-13),
data_gsl(mathieu_se_rad, 'mathieu_ce_se', (0, 1, 2), 4, rtol=1e-7, atol=1e-13),
data_gsl(mathieu_mc1_scaled, 'mathieu_mc_ms', (0, 1, 2), 3, rtol=1e-7, atol=1e-13),
data_gsl(mathieu_ms1_scaled, 'mathieu_mc_ms', (0, 1, 2), 4, rtol=1e-7, atol=1e-13),
data_gsl(mathieu_mc2_scaled, 'mathieu_mc_ms', (0, 1, 2), 5, rtol=1e-7, atol=1e-13),
data_gsl(mathieu_ms2_scaled, 'mathieu_mc_ms', (0, 1, 2), 6, rtol=1e-7, atol=1e-13),
]
@pytest.mark.parametrize('test', GSL_TESTS, ids=repr)
def test_gsl(test):
_test_factory(test)
LOCAL_TESTS = [
data_local(ellipkinc, 'ellipkinc_neg_m', (0, 1), 2),
data_local(ellipkm1, 'ellipkm1', 0, 1),
data_local(ellipeinc, 'ellipeinc_neg_m', (0, 1), 2),
data_local(clog1p, 'log1p_expm1_complex', (0,1), (2,3), rtol=1e-14),
data_local(cexpm1, 'log1p_expm1_complex', (0,1), (4,5), rtol=1e-14),
data_local(gammainc, 'gammainc', (0, 1), 2, rtol=1e-12),
data_local(gammaincc, 'gammaincc', (0, 1), 2, rtol=1e-11),
data_local(ellip_harm_2, 'ellip',(0, 1, 2, 3, 4), 6, rtol=1e-10, atol=1e-13),
data_local(ellip_harm, 'ellip',(0, 1, 2, 3, 4), 5, rtol=1e-10, atol=1e-13),
]
@pytest.mark.parametrize('test', LOCAL_TESTS, ids=repr)
def test_local(test):
_test_factory(test)
def _test_factory(test, dtype=np.double):
"""Boost test"""
with suppress_warnings() as sup:
sup.filter(IntegrationWarning, "The occurrence of roundoff error is detected")
with np.errstate(all='ignore'):
test.check(dtype=dtype)
| 46.118022 | 135 | 0.664857 | import os
import numpy as np
from numpy import arccosh, arcsinh, arctanh
from numpy.testing import suppress_warnings
import pytest
from scipy.special import (
lpn, lpmn, lpmv, lqn, lqmn, sph_harm, eval_legendre, eval_hermite,
eval_laguerre, eval_genlaguerre, binom, cbrt, expm1, log1p, zeta,
jn, jv, jvp, yn, yv, yvp, iv, ivp, kn, kv, kvp,
gamma, gammaln, gammainc, gammaincc, gammaincinv, gammainccinv, digamma,
beta, betainc, betaincinv, poch,
ellipe, ellipeinc, ellipk, ellipkm1, ellipkinc, ellipj,
elliprc, elliprd, elliprf, elliprg, elliprj,
erf, erfc, erfinv, erfcinv, exp1, expi, expn,
bdtrik, btdtr, btdtri, btdtria, btdtrib, chndtr, gdtr, gdtrc, gdtrix, gdtrib,
nbdtrik, pdtrik, owens_t,
mathieu_a, mathieu_b, mathieu_cem, mathieu_sem, mathieu_modcem1,
mathieu_modsem1, mathieu_modcem2, mathieu_modsem2,
ellip_harm, ellip_harm_2, spherical_jn, spherical_yn,
)
from scipy.integrate import IntegrationWarning
from scipy.special._testutils import FuncData
DATASETS_BOOST = np.load(os.path.join(os.path.dirname(__file__),
"data", "boost.npz"))
DATASETS_GSL = np.load(os.path.join(os.path.dirname(__file__),
"data", "gsl.npz"))
DATASETS_LOCAL = np.load(os.path.join(os.path.dirname(__file__),
"data", "local.npz"))
def data(func, dataname, *a, **kw):
kw.setdefault('dataname', dataname)
return FuncData(func, DATASETS_BOOST[dataname], *a, **kw)
def data_gsl(func, dataname, *a, **kw):
kw.setdefault('dataname', dataname)
return FuncData(func, DATASETS_GSL[dataname], *a, **kw)
def data_local(func, dataname, *a, **kw):
kw.setdefault('dataname', dataname)
return FuncData(func, DATASETS_LOCAL[dataname], *a, **kw)
def ellipk_(k):
return ellipk(k*k)
def ellipkinc_(f, k):
return ellipkinc(f, k*k)
def ellipe_(k):
return ellipe(k*k)
def ellipeinc_(f, k):
return ellipeinc(f, k*k)
def ellipj_(k):
return ellipj(k*k)
def zeta_(x):
return zeta(x, 1.)
def assoc_legendre_p_boost_(nu, mu, x):
return lpmv(mu, nu.astype(int), x)
def legendre_p_via_assoc_(nu, x):
return lpmv(0, nu, x)
def lpn_(n, x):
return lpn(n.astype('l'), x)[0][-1]
def lqn_(n, x):
return lqn(n.astype('l'), x)[0][-1]
def legendre_p_via_lpmn(n, x):
return lpmn(0, n, x)[0][0,-1]
def legendre_q_via_lqmn(n, x):
return lqmn(0, n, x)[0][0,-1]
def mathieu_ce_rad(m, q, x):
return mathieu_cem(m, q, x*180/np.pi)[0]
def mathieu_se_rad(m, q, x):
return mathieu_sem(m, q, x*180/np.pi)[0]
def mathieu_mc1_scaled(m, q, x):
return mathieu_modcem1(m, q, x)[0] * np.sqrt(np.pi/2)
def mathieu_ms1_scaled(m, q, x):
return mathieu_modsem1(m, q, x)[0] * np.sqrt(np.pi/2)
def mathieu_mc2_scaled(m, q, x):
return mathieu_modcem2(m, q, x)[0] * np.sqrt(np.pi/2)
def mathieu_ms2_scaled(m, q, x):
return mathieu_modsem2(m, q, x)[0] * np.sqrt(np.pi/2)
def eval_legendre_ld(n, x):
return eval_legendre(n.astype('l'), x)
def eval_legendre_dd(n, x):
return eval_legendre(n.astype('d'), x)
def eval_hermite_ld(n, x):
return eval_hermite(n.astype('l'), x)
def eval_laguerre_ld(n, x):
return eval_laguerre(n.astype('l'), x)
def eval_laguerre_dd(n, x):
return eval_laguerre(n.astype('d'), x)
def eval_genlaguerre_ldd(n, a, x):
return eval_genlaguerre(n.astype('l'), a, x)
def eval_genlaguerre_ddd(n, a, x):
return eval_genlaguerre(n.astype('d'), a, x)
def bdtrik_comp(y, n, p):
return bdtrik(1-y, n, p)
def btdtri_comp(a, b, p):
return btdtri(a, b, 1-p)
def btdtria_comp(p, b, x):
return btdtria(1-p, b, x)
def btdtrib_comp(a, p, x):
return btdtrib(a, 1-p, x)
def gdtr_(p, x):
return gdtr(1.0, p, x)
def gdtrc_(p, x):
return gdtrc(1.0, p, x)
def gdtrix_(b, p):
return gdtrix(1.0, b, p)
def gdtrix_comp(b, p):
return gdtrix(1.0, b, 1-p)
def gdtrib_(p, x):
return gdtrib(1.0, p, x)
def gdtrib_comp(p, x):
return gdtrib(1.0, 1-p, x)
def nbdtrik_comp(y, n, p):
return nbdtrik(1-y, n, p)
def pdtrik_comp(p, m):
return pdtrik(1-p, m)
def poch_(z, m):
return 1.0 / poch(z, m)
def poch_minus(z, m):
return 1.0 / poch(z, -m)
def spherical_jn_(n, x):
return spherical_jn(n.astype('l'), x)
def spherical_yn_(n, x):
return spherical_yn(n.astype('l'), x)
def sph_harm_(m, n, theta, phi):
y = sph_harm(m, n, theta, phi)
return (y.real, y.imag)
def cexpm1(x, y):
z = expm1(x + 1j*y)
return z.real, z.imag
def clog1p(x, y):
z = log1p(x + 1j*y)
return z.real, z.imag
BOOST_TESTS = [
data(arccosh, 'acosh_data_ipp-acosh_data', 0, 1, rtol=5e-13),
data(arccosh, 'acosh_data_ipp-acosh_data', 0j, 1, rtol=5e-13),
data(arcsinh, 'asinh_data_ipp-asinh_data', 0, 1, rtol=1e-11),
data(arcsinh, 'asinh_data_ipp-asinh_data', 0j, 1, rtol=1e-11),
data(arctanh, 'atanh_data_ipp-atanh_data', 0, 1, rtol=1e-11),
data(arctanh, 'atanh_data_ipp-atanh_data', 0j, 1, rtol=1e-11),
data(assoc_legendre_p_boost_, 'assoc_legendre_p_ipp-assoc_legendre_p', (0,1,2), 3, rtol=1e-11),
data(legendre_p_via_assoc_, 'legendre_p_ipp-legendre_p', (0,1), 2, rtol=1e-11),
data(legendre_p_via_assoc_, 'legendre_p_large_ipp-legendre_p_large', (0,1), 2, rtol=9.6e-14),
data(legendre_p_via_lpmn, 'legendre_p_ipp-legendre_p', (0,1), 2, rtol=5e-14, vectorized=False),
data(legendre_p_via_lpmn, 'legendre_p_large_ipp-legendre_p_large', (0,1), 2, rtol=9.6e-14, vectorized=False),
data(lpn_, 'legendre_p_ipp-legendre_p', (0,1), 2, rtol=5e-14, vectorized=False),
data(lpn_, 'legendre_p_large_ipp-legendre_p_large', (0,1), 2, rtol=3e-13, vectorized=False),
data(eval_legendre_ld, 'legendre_p_ipp-legendre_p', (0,1), 2, rtol=6e-14),
data(eval_legendre_ld, 'legendre_p_large_ipp-legendre_p_large', (0,1), 2, rtol=2e-13),
data(eval_legendre_dd, 'legendre_p_ipp-legendre_p', (0,1), 2, rtol=2e-14),
data(eval_legendre_dd, 'legendre_p_large_ipp-legendre_p_large', (0,1), 2, rtol=2e-13),
data(lqn_, 'legendre_p_ipp-legendre_p', (0,1), 3, rtol=2e-14, vectorized=False),
data(lqn_, 'legendre_p_large_ipp-legendre_p_large', (0,1), 3, rtol=2e-12, vectorized=False),
data(legendre_q_via_lqmn, 'legendre_p_ipp-legendre_p', (0,1), 3, rtol=2e-14, vectorized=False),
data(legendre_q_via_lqmn, 'legendre_p_large_ipp-legendre_p_large', (0,1), 3, rtol=2e-12, vectorized=False),
data(beta, 'beta_exp_data_ipp-beta_exp_data', (0,1), 2, rtol=1e-13),
data(beta, 'beta_exp_data_ipp-beta_exp_data', (0,1), 2, rtol=1e-13),
data(beta, 'beta_med_data_ipp-beta_med_data', (0,1), 2, rtol=5e-13),
data(betainc, 'ibeta_small_data_ipp-ibeta_small_data', (0,1,2), 5, rtol=6e-15),
data(betainc, 'ibeta_data_ipp-ibeta_data', (0,1,2), 5, rtol=5e-13),
data(betainc, 'ibeta_int_data_ipp-ibeta_int_data', (0,1,2), 5, rtol=2e-14),
data(betainc, 'ibeta_large_data_ipp-ibeta_large_data', (0,1,2), 5, rtol=4e-10),
data(betaincinv, 'ibeta_inv_data_ipp-ibeta_inv_data', (0,1,2), 3, rtol=1e-5),
data(btdtr, 'ibeta_small_data_ipp-ibeta_small_data', (0,1,2), 5, rtol=6e-15),
data(btdtr, 'ibeta_data_ipp-ibeta_data', (0,1,2), 5, rtol=4e-13),
data(btdtr, 'ibeta_int_data_ipp-ibeta_int_data', (0,1,2), 5, rtol=2e-14),
data(btdtr, 'ibeta_large_data_ipp-ibeta_large_data', (0,1,2), 5, rtol=4e-10),
data(btdtri, 'ibeta_inv_data_ipp-ibeta_inv_data', (0,1,2), 3, rtol=1e-5),
data(btdtri_comp, 'ibeta_inv_data_ipp-ibeta_inv_data', (0,1,2), 4, rtol=8e-7),
data(btdtria, 'ibeta_inva_data_ipp-ibeta_inva_data', (2,0,1), 3, rtol=5e-9),
data(btdtria_comp, 'ibeta_inva_data_ipp-ibeta_inva_data', (2,0,1), 4, rtol=5e-9),
data(btdtrib, 'ibeta_inva_data_ipp-ibeta_inva_data', (0,2,1), 5, rtol=5e-9),
data(btdtrib_comp, 'ibeta_inva_data_ipp-ibeta_inva_data', (0,2,1), 6, rtol=5e-9),
data(binom, 'binomial_data_ipp-binomial_data', (0,1), 2, rtol=1e-13),
data(binom, 'binomial_large_data_ipp-binomial_large_data', (0,1), 2, rtol=5e-13),
data(bdtrik, 'binomial_quantile_ipp-binomial_quantile_data', (2,0,1), 3, rtol=5e-9),
data(bdtrik_comp, 'binomial_quantile_ipp-binomial_quantile_data', (2,0,1), 4, rtol=5e-9),
data(nbdtrik, 'negative_binomial_quantile_ipp-negative_binomial_quantile_data', (2,0,1), 3, rtol=4e-9),
data(nbdtrik_comp, 'negative_binomial_quantile_ipp-negative_binomial_quantile_data', (2,0,1), 4, rtol=4e-9),
data(pdtrik, 'poisson_quantile_ipp-poisson_quantile_data', (1,0), 2, rtol=3e-9),
data(pdtrik_comp, 'poisson_quantile_ipp-poisson_quantile_data', (1,0), 3, rtol=4e-9),
data(cbrt, 'cbrt_data_ipp-cbrt_data', 1, 0),
data(digamma, 'digamma_data_ipp-digamma_data', 0, 1),
data(digamma, 'digamma_data_ipp-digamma_data', 0j, 1),
data(digamma, 'digamma_neg_data_ipp-digamma_neg_data', 0, 1, rtol=2e-13),
data(digamma, 'digamma_neg_data_ipp-digamma_neg_data', 0j, 1, rtol=1e-13),
data(digamma, 'digamma_root_data_ipp-digamma_root_data', 0, 1, rtol=1e-15),
data(digamma, 'digamma_root_data_ipp-digamma_root_data', 0j, 1, rtol=1e-15),
data(digamma, 'digamma_small_data_ipp-digamma_small_data', 0, 1, rtol=1e-15),
data(digamma, 'digamma_small_data_ipp-digamma_small_data', 0j, 1, rtol=1e-14),
data(ellipk_, 'ellint_k_data_ipp-ellint_k_data', 0, 1),
data(ellipkinc_, 'ellint_f_data_ipp-ellint_f_data', (0,1), 2, rtol=1e-14),
data(ellipe_, 'ellint_e_data_ipp-ellint_e_data', 0, 1),
data(ellipeinc_, 'ellint_e2_data_ipp-ellint_e2_data', (0,1), 2, rtol=1e-14),
data(erf, 'erf_data_ipp-erf_data', 0, 1),
data(erf, 'erf_data_ipp-erf_data', 0j, 1, rtol=1e-13),
data(erfc, 'erf_data_ipp-erf_data', 0, 2, rtol=6e-15),
data(erf, 'erf_large_data_ipp-erf_large_data', 0, 1),
data(erf, 'erf_large_data_ipp-erf_large_data', 0j, 1),
data(erfc, 'erf_large_data_ipp-erf_large_data', 0, 2, rtol=4e-14),
data(erf, 'erf_small_data_ipp-erf_small_data', 0, 1),
data(erf, 'erf_small_data_ipp-erf_small_data', 0j, 1, rtol=1e-13),
data(erfc, 'erf_small_data_ipp-erf_small_data', 0, 2),
data(erfinv, 'erf_inv_data_ipp-erf_inv_data', 0, 1),
data(erfcinv, 'erfc_inv_data_ipp-erfc_inv_data', 0, 1),
data(erfcinv, 'erfc_inv_big_data_ipp-erfc_inv_big_data', 0, 1, param_filter=(lambda s: s > 0)),
data(exp1, 'expint_1_data_ipp-expint_1_data', 1, 2, rtol=1e-13),
data(exp1, 'expint_1_data_ipp-expint_1_data', 1j, 2, rtol=5e-9),
data(expi, 'expinti_data_ipp-expinti_data', 0, 1, rtol=1e-13),
data(expi, 'expinti_data_double_ipp-expinti_data_double', 0, 1, rtol=1e-13),
data(expi, 'expinti_data_long_ipp-expinti_data_long', 0, 1),
data(expn, 'expint_small_data_ipp-expint_small_data', (0,1), 2),
data(expn, 'expint_data_ipp-expint_data', (0,1), 2, rtol=1e-14),
data(gamma, 'test_gamma_data_ipp-near_0', 0, 1),
data(gamma, 'test_gamma_data_ipp-near_1', 0, 1),
data(gamma, 'test_gamma_data_ipp-near_2', 0, 1),
data(gamma, 'test_gamma_data_ipp-near_m10', 0, 1),
data(gamma, 'test_gamma_data_ipp-near_m55', 0, 1, rtol=7e-12),
data(gamma, 'test_gamma_data_ipp-factorials', 0, 1, rtol=4e-14),
data(gamma, 'test_gamma_data_ipp-near_0', 0j, 1, rtol=2e-9),
data(gamma, 'test_gamma_data_ipp-near_1', 0j, 1, rtol=2e-9),
data(gamma, 'test_gamma_data_ipp-near_2', 0j, 1, rtol=2e-9),
data(gamma, 'test_gamma_data_ipp-near_m10', 0j, 1, rtol=2e-9),
data(gamma, 'test_gamma_data_ipp-near_m55', 0j, 1, rtol=2e-9),
data(gamma, 'test_gamma_data_ipp-factorials', 0j, 1, rtol=2e-13),
data(gammaln, 'test_gamma_data_ipp-near_0', 0, 2, rtol=5e-11),
data(gammaln, 'test_gamma_data_ipp-near_1', 0, 2, rtol=5e-11),
data(gammaln, 'test_gamma_data_ipp-near_2', 0, 2, rtol=2e-10),
data(gammaln, 'test_gamma_data_ipp-near_m10', 0, 2, rtol=5e-11),
data(gammaln, 'test_gamma_data_ipp-near_m55', 0, 2, rtol=5e-11),
data(gammaln, 'test_gamma_data_ipp-factorials', 0, 2),
data(gammainc, 'igamma_small_data_ipp-igamma_small_data', (0,1), 5, rtol=5e-15),
data(gammainc, 'igamma_med_data_ipp-igamma_med_data', (0,1), 5, rtol=2e-13),
data(gammainc, 'igamma_int_data_ipp-igamma_int_data', (0,1), 5, rtol=2e-13),
data(gammainc, 'igamma_big_data_ipp-igamma_big_data', (0,1), 5, rtol=1e-12),
data(gdtr_, 'igamma_small_data_ipp-igamma_small_data', (0,1), 5, rtol=1e-13),
data(gdtr_, 'igamma_med_data_ipp-igamma_med_data', (0,1), 5, rtol=2e-13),
data(gdtr_, 'igamma_int_data_ipp-igamma_int_data', (0,1), 5, rtol=2e-13),
data(gdtr_, 'igamma_big_data_ipp-igamma_big_data', (0,1), 5, rtol=2e-9),
data(gammaincc, 'igamma_small_data_ipp-igamma_small_data', (0,1), 3, rtol=1e-13),
data(gammaincc, 'igamma_med_data_ipp-igamma_med_data', (0,1), 3, rtol=2e-13),
data(gammaincc, 'igamma_int_data_ipp-igamma_int_data', (0,1), 3, rtol=4e-14),
data(gammaincc, 'igamma_big_data_ipp-igamma_big_data', (0,1), 3, rtol=1e-11),
data(gdtrc_, 'igamma_small_data_ipp-igamma_small_data', (0,1), 3, rtol=1e-13),
data(gdtrc_, 'igamma_med_data_ipp-igamma_med_data', (0,1), 3, rtol=2e-13),
data(gdtrc_, 'igamma_int_data_ipp-igamma_int_data', (0,1), 3, rtol=4e-14),
data(gdtrc_, 'igamma_big_data_ipp-igamma_big_data', (0,1), 3, rtol=1e-11),
data(gdtrib_, 'igamma_inva_data_ipp-igamma_inva_data', (1,0), 2, rtol=5e-9),
data(gdtrib_comp, 'igamma_inva_data_ipp-igamma_inva_data', (1,0), 3, rtol=5e-9),
data(poch_, 'tgamma_delta_ratio_data_ipp-tgamma_delta_ratio_data', (0,1), 2, rtol=2e-13),
data(poch_, 'tgamma_delta_ratio_int_ipp-tgamma_delta_ratio_int', (0,1), 2,),
data(poch_, 'tgamma_delta_ratio_int2_ipp-tgamma_delta_ratio_int2', (0,1), 2,),
data(poch_minus, 'tgamma_delta_ratio_data_ipp-tgamma_delta_ratio_data', (0,1), 3, rtol=2e-13),
data(poch_minus, 'tgamma_delta_ratio_int_ipp-tgamma_delta_ratio_int', (0,1), 3),
data(poch_minus, 'tgamma_delta_ratio_int2_ipp-tgamma_delta_ratio_int2', (0,1), 3),
data(eval_hermite_ld, 'hermite_ipp-hermite', (0,1), 2, rtol=2e-14),
data(eval_laguerre_ld, 'laguerre2_ipp-laguerre2', (0,1), 2, rtol=7e-12),
data(eval_laguerre_dd, 'laguerre2_ipp-laguerre2', (0,1), 2, knownfailure='hyp2f1 insufficiently accurate.'),
data(eval_genlaguerre_ldd, 'laguerre3_ipp-laguerre3', (0,1,2), 3, rtol=2e-13),
data(eval_genlaguerre_ddd, 'laguerre3_ipp-laguerre3', (0,1,2), 3, knownfailure='hyp2f1 insufficiently accurate.'),
data(log1p, 'log1p_expm1_data_ipp-log1p_expm1_data', 0, 1),
data(expm1, 'log1p_expm1_data_ipp-log1p_expm1_data', 0, 2),
data(iv, 'bessel_i_data_ipp-bessel_i_data', (0,1), 2, rtol=1e-12),
data(iv, 'bessel_i_data_ipp-bessel_i_data', (0,1j), 2, rtol=2e-10, atol=1e-306),
data(iv, 'bessel_i_int_data_ipp-bessel_i_int_data', (0,1), 2, rtol=1e-9),
data(iv, 'bessel_i_int_data_ipp-bessel_i_int_data', (0,1j), 2, rtol=2e-10),
data(ivp, 'bessel_i_prime_int_data_ipp-bessel_i_prime_int_data', (0,1), 2, rtol=1.2e-13),
data(ivp, 'bessel_i_prime_int_data_ipp-bessel_i_prime_int_data', (0,1j), 2, rtol=1.2e-13, atol=1e-300),
data(jn, 'bessel_j_int_data_ipp-bessel_j_int_data', (0,1), 2, rtol=1e-12),
data(jn, 'bessel_j_int_data_ipp-bessel_j_int_data', (0,1j), 2, rtol=1e-12),
data(jn, 'bessel_j_large_data_ipp-bessel_j_large_data', (0,1), 2, rtol=6e-11),
data(jn, 'bessel_j_large_data_ipp-bessel_j_large_data', (0,1j), 2, rtol=6e-11),
data(jv, 'bessel_j_int_data_ipp-bessel_j_int_data', (0,1), 2, rtol=1e-12),
data(jv, 'bessel_j_int_data_ipp-bessel_j_int_data', (0,1j), 2, rtol=1e-12),
data(jv, 'bessel_j_data_ipp-bessel_j_data', (0,1), 2, rtol=1e-12),
data(jv, 'bessel_j_data_ipp-bessel_j_data', (0,1j), 2, rtol=1e-12),
data(jvp, 'bessel_j_prime_int_data_ipp-bessel_j_prime_int_data', (0,1), 2, rtol=1e-13),
data(jvp, 'bessel_j_prime_int_data_ipp-bessel_j_prime_int_data', (0,1j), 2, rtol=1e-13),
data(jvp, 'bessel_j_prime_large_data_ipp-bessel_j_prime_large_data', (0,1), 2, rtol=1e-11),
data(jvp, 'bessel_j_prime_large_data_ipp-bessel_j_prime_large_data', (0,1j), 2, rtol=1e-11),
data(kn, 'bessel_k_int_data_ipp-bessel_k_int_data', (0,1), 2, rtol=1e-12),
data(kv, 'bessel_k_int_data_ipp-bessel_k_int_data', (0,1), 2, rtol=1e-12),
data(kv, 'bessel_k_int_data_ipp-bessel_k_int_data', (0,1j), 2, rtol=1e-12),
data(kv, 'bessel_k_data_ipp-bessel_k_data', (0,1), 2, rtol=1e-12),
data(kv, 'bessel_k_data_ipp-bessel_k_data', (0,1j), 2, rtol=1e-12),
data(kvp, 'bessel_k_prime_int_data_ipp-bessel_k_prime_int_data', (0,1), 2, rtol=3e-14),
data(kvp, 'bessel_k_prime_int_data_ipp-bessel_k_prime_int_data', (0,1j), 2, rtol=3e-14),
data(kvp, 'bessel_k_prime_data_ipp-bessel_k_prime_data', (0,1), 2, rtol=7e-14),
data(kvp, 'bessel_k_prime_data_ipp-bessel_k_prime_data', (0,1j), 2, rtol=7e-14),
data(yn, 'bessel_y01_data_ipp-bessel_y01_data', (0,1), 2, rtol=1e-12),
data(yn, 'bessel_yn_data_ipp-bessel_yn_data', (0,1), 2, rtol=1e-12),
data(yv, 'bessel_yn_data_ipp-bessel_yn_data', (0,1), 2, rtol=1e-12),
data(yv, 'bessel_yn_data_ipp-bessel_yn_data', (0,1j), 2, rtol=1e-12),
data(yv, 'bessel_yv_data_ipp-bessel_yv_data', (0,1), 2, rtol=1e-10),
data(yv, 'bessel_yv_data_ipp-bessel_yv_data', (0,1j), 2, rtol=1e-10),
data(yvp, 'bessel_yv_prime_data_ipp-bessel_yv_prime_data', (0, 1), 2, rtol=4e-9),
data(yvp, 'bessel_yv_prime_data_ipp-bessel_yv_prime_data', (0, 1j), 2, rtol=4e-9),
data(zeta_, 'zeta_data_ipp-zeta_data', 0, 1, param_filter=(lambda s: s > 1)),
data(zeta_, 'zeta_neg_data_ipp-zeta_neg_data', 0, 1, param_filter=(lambda s: s > 1)),
data(zeta_, 'zeta_1_up_data_ipp-zeta_1_up_data', 0, 1, param_filter=(lambda s: s > 1)),
data(zeta_, 'zeta_1_below_data_ipp-zeta_1_below_data', 0, 1, param_filter=(lambda s: s > 1)),
data(gammaincinv, 'gamma_inv_small_data_ipp-gamma_inv_small_data', (0,1), 2, rtol=1e-11),
data(gammaincinv, 'gamma_inv_data_ipp-gamma_inv_data', (0,1), 2, rtol=1e-14),
data(gammaincinv, 'gamma_inv_big_data_ipp-gamma_inv_big_data', (0,1), 2, rtol=1e-11),
data(gammainccinv, 'gamma_inv_small_data_ipp-gamma_inv_small_data', (0,1), 3, rtol=1e-12),
data(gammainccinv, 'gamma_inv_data_ipp-gamma_inv_data', (0,1), 3, rtol=1e-14),
data(gammainccinv, 'gamma_inv_big_data_ipp-gamma_inv_big_data', (0,1), 3, rtol=1e-14),
data(gdtrix_, 'gamma_inv_small_data_ipp-gamma_inv_small_data', (0,1), 2, rtol=3e-13, knownfailure='gdtrix unflow some points'),
data(gdtrix_, 'gamma_inv_data_ipp-gamma_inv_data', (0,1), 2, rtol=3e-15),
data(gdtrix_, 'gamma_inv_big_data_ipp-gamma_inv_big_data', (0,1), 2),
data(gdtrix_comp, 'gamma_inv_small_data_ipp-gamma_inv_small_data', (0,1), 2, knownfailure='gdtrix bad some points'),
data(gdtrix_comp, 'gamma_inv_data_ipp-gamma_inv_data', (0,1), 3, rtol=6e-15),
data(gdtrix_comp, 'gamma_inv_big_data_ipp-gamma_inv_big_data', (0,1), 3),
data(chndtr, 'nccs_ipp-nccs', (2,0,1), 3, rtol=3e-5),
data(chndtr, 'nccs_big_ipp-nccs_big', (2,0,1), 3, rtol=5e-4, knownfailure='chndtr inaccurate some points'),
data(sph_harm_, 'spherical_harmonic_ipp-spherical_harmonic', (1,0,3,2), (4,5), rtol=5e-11,
param_filter=(lambda p: np.ones(p.shape, '?'),
lambda p: np.ones(p.shape, '?'),
lambda p: np.logical_and(p < 2*np.pi, p >= 0),
lambda p: np.logical_and(p < np.pi, p >= 0))),
data(spherical_jn_, 'sph_bessel_data_ipp-sph_bessel_data', (0,1), 2, rtol=1e-13),
data(spherical_yn_, 'sph_neumann_data_ipp-sph_neumann_data', (0,1), 2, rtol=8e-15),
data(owens_t, 'owens_t_ipp-owens_t', (0, 1), 2, rtol=5e-14),
data(owens_t, 'owens_t_large_data_ipp-owens_t_large_data', (0, 1), 2, rtol=8e-12),
data(elliprc, 'ellint_rc_data_ipp-ellint_rc_data', (0, 1), 2,
rtol=5e-16),
data(elliprd, 'ellint_rd_data_ipp-ellint_rd_data', (0, 1, 2), 3,
rtol=5e-16),
data(elliprd, 'ellint_rd_0xy_ipp-ellint_rd_0xy', (0, 1, 2), 3,
rtol=5e-16),
data(elliprd, 'ellint_rd_0yy_ipp-ellint_rd_0yy', (0, 1, 2), 3,
rtol=5e-16),
data(elliprd, 'ellint_rd_xxx_ipp-ellint_rd_xxx', (0, 1, 2), 3,
rtol=5e-16),
data(elliprd, 'ellint_rd_xxz_ipp-ellint_rd_xxz', (0, 1, 2), 3,
rtol=6.5e-16),
data(elliprd, 'ellint_rd_xyy_ipp-ellint_rd_xyy', (0, 1, 2), 3,
rtol=6e-16),
data(elliprf, 'ellint_rf_data_ipp-ellint_rf_data', (0, 1, 2), 3,
rtol=5e-16),
data(elliprf, 'ellint_rf_xxx_ipp-ellint_rf_xxx', (0, 1, 2), 3,
rtol=5e-16),
data(elliprf, 'ellint_rf_xyy_ipp-ellint_rf_xyy', (0, 1, 2), 3,
rtol=5e-16),
data(elliprf, 'ellint_rf_xy0_ipp-ellint_rf_xy0', (0, 1, 2), 3,
rtol=5e-16),
data(elliprf, 'ellint_rf_0yy_ipp-ellint_rf_0yy', (0, 1, 2), 3,
rtol=5e-16),
data(elliprg, 'ellint_rg_ipp-ellint_rg', (0, 1, 2), 3,
rtol=8.0e-16),
data(elliprg, 'ellint_rg_xxx_ipp-ellint_rg_xxx', (0, 1, 2), 3,
rtol=6e-16),
data(elliprg, 'ellint_rg_xyy_ipp-ellint_rg_xyy', (0, 1, 2), 3,
rtol=7.5e-16),
data(elliprg, 'ellint_rg_xy0_ipp-ellint_rg_xy0', (0, 1, 2), 3,
rtol=5e-16),
data(elliprg, 'ellint_rg_00x_ipp-ellint_rg_00x', (0, 1, 2), 3,
rtol=5e-16),
data(elliprj, 'ellint_rj_data_ipp-ellint_rj_data', (0, 1, 2, 3), 4,
rtol=5e-16, atol=1e-25,
param_filter=(lambda s: s <= 5e-26,)),
]
@pytest.mark.parametrize('test', BOOST_TESTS, ids=repr)
def test_boost(test):
_test_factory(test)
GSL_TESTS = [
data_gsl(mathieu_a, 'mathieu_ab', (0, 1), 2, rtol=1e-13, atol=1e-13),
data_gsl(mathieu_b, 'mathieu_ab', (0, 1), 3, rtol=1e-13, atol=1e-13),
data_gsl(mathieu_ce_rad, 'mathieu_ce_se', (0, 1, 2), 3, rtol=1e-7, atol=1e-13),
data_gsl(mathieu_se_rad, 'mathieu_ce_se', (0, 1, 2), 4, rtol=1e-7, atol=1e-13),
data_gsl(mathieu_mc1_scaled, 'mathieu_mc_ms', (0, 1, 2), 3, rtol=1e-7, atol=1e-13),
data_gsl(mathieu_ms1_scaled, 'mathieu_mc_ms', (0, 1, 2), 4, rtol=1e-7, atol=1e-13),
data_gsl(mathieu_mc2_scaled, 'mathieu_mc_ms', (0, 1, 2), 5, rtol=1e-7, atol=1e-13),
data_gsl(mathieu_ms2_scaled, 'mathieu_mc_ms', (0, 1, 2), 6, rtol=1e-7, atol=1e-13),
]
@pytest.mark.parametrize('test', GSL_TESTS, ids=repr)
def test_gsl(test):
_test_factory(test)
LOCAL_TESTS = [
data_local(ellipkinc, 'ellipkinc_neg_m', (0, 1), 2),
data_local(ellipkm1, 'ellipkm1', 0, 1),
data_local(ellipeinc, 'ellipeinc_neg_m', (0, 1), 2),
data_local(clog1p, 'log1p_expm1_complex', (0,1), (2,3), rtol=1e-14),
data_local(cexpm1, 'log1p_expm1_complex', (0,1), (4,5), rtol=1e-14),
data_local(gammainc, 'gammainc', (0, 1), 2, rtol=1e-12),
data_local(gammaincc, 'gammaincc', (0, 1), 2, rtol=1e-11),
data_local(ellip_harm_2, 'ellip',(0, 1, 2, 3, 4), 6, rtol=1e-10, atol=1e-13),
data_local(ellip_harm, 'ellip',(0, 1, 2, 3, 4), 5, rtol=1e-10, atol=1e-13),
]
@pytest.mark.parametrize('test', LOCAL_TESTS, ids=repr)
def test_local(test):
_test_factory(test)
def _test_factory(test, dtype=np.double):
with suppress_warnings() as sup:
sup.filter(IntegrationWarning, "The occurrence of roundoff error is detected")
with np.errstate(all='ignore'):
test.check(dtype=dtype)
| true | true |
1c2e62b0fc97c13f9605dc60ea7eadd17f276dde | 483 | py | Python | prep_ons_nuts_gva.py | aeturrell/uk-economy-app | 915272d9843f5bf4ad6ace1d5353e7ae58a7b6be | [
"MIT"
] | null | null | null | prep_ons_nuts_gva.py | aeturrell/uk-economy-app | 915272d9843f5bf4ad6ace1d5353e7ae58a7b6be | [
"MIT"
] | null | null | null | prep_ons_nuts_gva.py | aeturrell/uk-economy-app | 915272d9843f5bf4ad6ace1d5353e7ae58a7b6be | [
"MIT"
] | null | null | null | import pandas as pd
import os
fname = "regionalgrossvalueaddedbalancedbyindustryallnutslevelregions.xlsx"
df = pd.read_excel(os.path.join('scratch', fname),
sheet_name='Table1b',
skiprows=0)
df.columns = df.iloc[0, :]
df = df.iloc[1:, :]
df = df[df['SIC07 code'] == 'Total']
df = df.rename(columns={df.columns[0]: 'NUTS1',
df.columns[-1]: str(df.columns[-1])[:4]})
df.to_csv(os.path.join('data', 'nuts1_gva_2016.csv'))
| 32.2 | 75 | 0.610766 | import pandas as pd
import os
fname = "regionalgrossvalueaddedbalancedbyindustryallnutslevelregions.xlsx"
df = pd.read_excel(os.path.join('scratch', fname),
sheet_name='Table1b',
skiprows=0)
df.columns = df.iloc[0, :]
df = df.iloc[1:, :]
df = df[df['SIC07 code'] == 'Total']
df = df.rename(columns={df.columns[0]: 'NUTS1',
df.columns[-1]: str(df.columns[-1])[:4]})
df.to_csv(os.path.join('data', 'nuts1_gva_2016.csv'))
| true | true |
1c2e649ff99586fff51de52322950e772745dde5 | 3,165 | py | Python | tests/operators/vector/test_smooth_l1_loss_grad_001.py | laekov/akg | 5316b8cb2340bbf71bdc724dc9d81513a67b3104 | [
"Apache-2.0"
] | 1 | 2020-08-31T02:43:43.000Z | 2020-08-31T02:43:43.000Z | tests/operators/vector/test_smooth_l1_loss_grad_001.py | laekov/akg | 5316b8cb2340bbf71bdc724dc9d81513a67b3104 | [
"Apache-2.0"
] | null | null | null | tests/operators/vector/test_smooth_l1_loss_grad_001.py | laekov/akg | 5316b8cb2340bbf71bdc724dc9d81513a67b3104 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Huawei Technologies Co., Ltd
#
# 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 datetime
import os
from base import TestBase
import pytest
from test_run.smooth_l1_loss_grad_run import smooth_l1_loss_grad_run
############################################################
# TestCase= class: put to tests/*/
############################################################
class TestCase(TestBase):
def setup(self):
case_name = "test_smooth_l1_loss_grad"
case_path = os.getcwd()
# params init
self.params_init(case_name, case_path)
self.caseresult = True
self._log.info("============= {0} Setup case============".format(self.casename))
kernel = smooth_l1_loss_grad_run
kernel_name = "smooth_l1_loss_grad"
self.testarg = [
## testflag,opfuncname,testRunArgs, dimArgs
]
self.testarg_cloud = [
## testflag,opfuncname,testRunArgs, dimArgs
("test_smooth_l1_loss_grad_05_fp32", kernel, ((1, 16, 4), "float16")),
]
self.testarg_rpc_cloud = [
## testflag,opfuncname,testRunArgs, dimArgs
("test_smooth_l1_loss_grad_01_fp16", kernel, ((8, 4718, 4), "float16")),
("test_smooth_l1_loss_grad_02_fp32", kernel, ((8, 4718, 4), "float32")),
("test_smooth_l1_loss_grad_03_fp16", kernel, ((8, 8732, 4), "float16")),
("test_smooth_l1_loss_grad_04_fp16", kernel, ((8, 8732, 4), "float32")),
# ("test_smooth_l1_loss_grad_05_fp16_pad", kernel, ((8, 8732, '4,16'), "float16")), # multicore wrong
("test_smooth_l1_loss_grad_06_fp16", kernel, ((32, 8732, 4), "float16")),
("test_smooth_l1_loss_grad_07_fp16", kernel, ((32, 8732, 4), "float32")),
]
return
@pytest.mark.rpc_mini
@pytest.mark.level0
@pytest.mark.env_onecard
@pytest.mark.platform_x86_ascend_training
def test_run(self):
"""
run case.#
:return:
"""
self.common_run(self.testarg)
@pytest.mark.aicmodel
@pytest.mark.env_onecard
@pytest.mark.platform_x86_ascend_training
def test_run_cloud(self):
"""
run case.#
:return:
"""
self.common_run(self.testarg_cloud)
@pytest.mark.rpc_cloud
@pytest.mark.env_onecard
@pytest.mark.platform_x86_ascend_training
def test_run_rpc_cloud(self):
self.common_run(self.testarg_rpc_cloud)
def teardown(self):
"""
clean environment
:return:
"""
self._log.info("============= {0} Teardown============".format(self.casename))
return
| 34.032258 | 114 | 0.612006 |
import datetime
import os
from base import TestBase
import pytest
from test_run.smooth_l1_loss_grad_run import smooth_l1_loss_grad_run
| true | true |
1c2e6507af08539c77c856e95f6d4852bc06d2f2 | 9,590 | py | Python | tests/test_integration.py | repo-helper/formate | 45e4b4fe29af144db714ea90c92cf6e7035ae301 | [
"MIT"
] | 1 | 2022-03-19T07:39:58.000Z | 2022-03-19T07:39:58.000Z | tests/test_integration.py | repo-helper/formate | 45e4b4fe29af144db714ea90c92cf6e7035ae301 | [
"MIT"
] | 14 | 2021-01-25T23:10:04.000Z | 2021-06-29T19:55:38.000Z | tests/test_integration.py | repo-helper/formate | 45e4b4fe29af144db714ea90c92cf6e7035ae301 | [
"MIT"
] | null | null | null | # stdlib
import re
from typing import Union, no_type_check
# 3rd party
import click
import pytest
from _pytest.capture import CaptureResult
from coincidence.regressions import AdvancedDataRegressionFixture, AdvancedFileRegressionFixture
from coincidence.selectors import max_version, min_version, not_pypy, only_pypy
from consolekit.terminal_colours import strip_ansi
from consolekit.testing import CliRunner, Result
from domdf_python_tools.paths import PathPlus, in_directory
# this package
from formate import Reformatter, reformat_file
from formate.__main__ import main
from formate.config import load_toml
path_sub = re.compile(rf" .*/pytest-of-.*/pytest-\d+")
@no_type_check
def check_out(
result: Union[Result, CaptureResult[str]],
advanced_data_regression: AdvancedDataRegressionFixture,
):
if hasattr(result, "stdout"):
stdout = result.stdout
else:
stdout = result.out
if hasattr(result, "stderr"):
stderr = result.stderr
else:
stderr = result.err
data_dict = {
"out": strip_ansi(path_sub.sub(" ...", stdout)).split('\n'),
"err": strip_ansi(path_sub.sub(" ...", stderr)).split('\n'),
}
advanced_data_regression.check(data_dict)
@pytest.fixture()
def demo_environment(tmp_pathplus):
example_formate_toml = PathPlus(__file__).parent / "example_formate.toml"
(tmp_pathplus / "formate.toml").write_text(example_formate_toml.read_text())
code = [
"class F:",
"\tfrom collections import (",
"Iterable,",
"\tCounter,",
"\t\t)",
'',
"\tdef foo(self):",
"\t\tpass",
'',
"print('hello world')",
r"assert t.uname == '\udce4\udcf6\udcfc'",
]
(tmp_pathplus / "code.py").write_lines(code, trailing_whitespace=True)
@pytest.fixture()
def demo_pyproject_environment(demo_environment, tmp_pathplus):
example_formate_toml = PathPlus(__file__).parent / "example_pyproject.toml"
(tmp_pathplus / "pyproject.toml").write_text(example_formate_toml.read_text())
def test_integration(
tmp_pathplus: PathPlus,
advanced_file_regression: AdvancedFileRegressionFixture,
capsys,
advanced_data_regression: AdvancedDataRegressionFixture,
demo_environment,
):
config = load_toml(tmp_pathplus / "formate.toml")
st = (tmp_pathplus / "code.py").stat()
assert st == st
assert reformat_file(tmp_pathplus / "code.py", config) == 1
advanced_file_regression.check_file(tmp_pathplus / "code.py")
check_out(capsys.readouterr(), advanced_data_regression)
# mtime should have changed
new_st = (tmp_pathplus / "code.py").stat()
assert new_st.st_mtime != st.st_mtime
assert new_st != st
# Calling a second time shouldn't change anything
assert reformat_file(tmp_pathplus / "code.py", config) == 0
advanced_file_regression.check_file(tmp_pathplus / "code.py")
# mtime should be the same
assert (tmp_pathplus / "code.py").stat().st_mtime == new_st.st_mtime
def test_integration_pyproject(
tmp_pathplus: PathPlus,
advanced_file_regression: AdvancedFileRegressionFixture,
capsys,
advanced_data_regression: AdvancedDataRegressionFixture,
demo_pyproject_environment,
):
config = load_toml(tmp_pathplus / "pyproject.toml")
assert reformat_file(tmp_pathplus / "code.py", config) == 1
advanced_file_regression.check_file(tmp_pathplus / "code.py")
check_out(capsys.readouterr(), advanced_data_regression)
# Calling a second time shouldn't change anything
assert reformat_file(tmp_pathplus / "code.py", config) == 0
advanced_file_regression.check_file(tmp_pathplus / "code.py")
def test_reformatter_class(
tmp_pathplus: PathPlus,
advanced_file_regression: AdvancedFileRegressionFixture,
capsys,
advanced_data_regression: AdvancedDataRegressionFixture,
demo_environment,
):
config = load_toml(tmp_pathplus / "formate.toml")
r = Reformatter(tmp_pathplus / "code.py", config)
with pytest.raises(ValueError, match=r"'Reformatter.run\(\)' must be called first!"):
r.to_string()
with pytest.raises(ValueError, match=r"'Reformatter.run\(\)' must be called first!"):
r.to_file()
with pytest.raises(ValueError, match=r"'Reformatter.run\(\)' must be called first!"):
r.get_diff()
st = (tmp_pathplus / "code.py").stat()
assert st == st
assert r.run() == 1
r.to_file()
advanced_file_regression.check_file(tmp_pathplus / "code.py")
advanced_file_regression.check(r.to_string(), extension="._py_")
captured = capsys.readouterr()
assert not captured.out
assert not captured.err
# mtime should have changed
new_st = (tmp_pathplus / "code.py").stat()
assert new_st.st_mtime != st.st_mtime
assert new_st != st
# Calling a second time shouldn't change anything
r = Reformatter(tmp_pathplus / "code.py", config)
assert r.run() == 0
r.to_file()
advanced_file_regression.check_file(tmp_pathplus / "code.py")
def test_cli(
tmp_pathplus: PathPlus,
advanced_file_regression: AdvancedFileRegressionFixture,
advanced_data_regression: AdvancedDataRegressionFixture,
demo_environment,
):
result: Result
st = (tmp_pathplus / "code.py").stat()
assert st == st
with in_directory(tmp_pathplus):
runner = CliRunner(mix_stderr=False)
result = runner.invoke(
main,
args=["code.py", "--no-colour", "--diff", "--verbose"],
)
assert result.exit_code == 1
advanced_file_regression.check_file(tmp_pathplus / "code.py")
check_out(result, advanced_data_regression)
# mtime should have changed
new_st = (tmp_pathplus / "code.py").stat()
assert new_st.st_mtime != st.st_mtime
assert new_st != st
# Calling a second time shouldn't change anything
with in_directory(tmp_pathplus):
runner = CliRunner(mix_stderr=False)
result = runner.invoke(main, args=["code.py"])
assert result.exit_code == 0
# mtime should be the same
assert (tmp_pathplus / "code.py").stat().st_mtime == new_st.st_mtime
def test_cli_verbose_verbose(
tmp_pathplus: PathPlus,
advanced_file_regression: AdvancedFileRegressionFixture,
advanced_data_regression: AdvancedDataRegressionFixture,
demo_environment,
):
result: Result
with in_directory(tmp_pathplus):
runner = CliRunner(mix_stderr=False)
result = runner.invoke(
main,
args=["code.py", "--no-colour", "--diff", "--verbose", "-v"],
)
assert result.exit_code == 1
advanced_file_regression.check_file(tmp_pathplus / "code.py")
# Calling a second time shouldn't change anything
with in_directory(tmp_pathplus):
runner = CliRunner(mix_stderr=False)
result = runner.invoke(
main,
args=["code.py", "code.c", "--no-colour", "--diff", "--verbose", "-v"],
)
assert result.exit_code == 0
check_out(result, advanced_data_regression)
@max_version("3.9.9", reason="Output differs on Python 3.10+")
@not_pypy("Output differs on PyPy")
def test_cli_syntax_error(
tmp_pathplus: PathPlus,
advanced_data_regression: AdvancedDataRegressionFixture,
demo_environment,
):
code = [
"class F:",
"\tfrom collections import (",
"Iterable,",
"\tCounter,",
"\t\t)",
'',
"\tdef foo(self):",
"\t\tpass",
'',
"print('hello world'",
]
(tmp_pathplus / "code.py").write_lines(code, trailing_whitespace=True)
with in_directory(tmp_pathplus):
runner = CliRunner(mix_stderr=False)
result: Result = runner.invoke(main, args=["code.py", "--no-colour", "--verbose"])
assert result.exit_code == 126
check_out(result, advanced_data_regression)
@only_pypy("Output differs on PyPy")
def test_cli_syntax_error_pypy(
tmp_pathplus: PathPlus,
advanced_data_regression: AdvancedDataRegressionFixture,
demo_environment,
):
code = [
"class F:",
"\tfrom collections import (",
"Iterable,",
"\tCounter,",
"\t\t)",
'',
"\tdef foo(self):",
"\t\tpass",
'',
"print('hello world'",
]
(tmp_pathplus / "code.py").write_lines(code, trailing_whitespace=True)
with in_directory(tmp_pathplus):
runner = CliRunner(mix_stderr=False)
result: Result = runner.invoke(main, args=["code.py", "--no-colour", "--verbose"])
assert result.exit_code == 126
check_out(result, advanced_data_regression)
@min_version("3.10", reason="Output differs on Python 3.10+")
def test_cli_syntax_error_py310(
tmp_pathplus: PathPlus,
advanced_data_regression: AdvancedDataRegressionFixture,
demo_environment,
):
code = [
"class F:",
"\tfrom collections import (",
"Iterable,",
"\tCounter,",
"\t\t)",
'',
"\tdef foo(self):",
"\t\tpass",
'',
"print('hello world'",
]
(tmp_pathplus / "code.py").write_lines(code, trailing_whitespace=True)
with in_directory(tmp_pathplus):
runner = CliRunner(mix_stderr=False)
result: Result = runner.invoke(main, args=["code.py", "--no-colour", "--verbose"])
assert result.exit_code == 126
check_out(result, advanced_data_regression)
@pytest.mark.skipif(click.__version__.split('.')[0] != '7', reason="Output differs on Click 8")
def test_cli_no_config(
tmp_pathplus: PathPlus,
advanced_data_regression: AdvancedDataRegressionFixture,
):
result: Result
with in_directory(tmp_pathplus):
runner = CliRunner(mix_stderr=False)
result = runner.invoke(main, args=["--no-colour", "--verbose"])
assert result.exit_code == 2
check_out(result, advanced_data_regression)
@pytest.mark.skipif(click.__version__.split('.')[0] == '7', reason="Output differs on Click 8")
def test_cli_no_config_click8(
tmp_pathplus: PathPlus,
advanced_data_regression: AdvancedDataRegressionFixture,
):
result: Result
with in_directory(tmp_pathplus):
runner = CliRunner(mix_stderr=False)
result = runner.invoke(main, args=["--no-colour", "--verbose"])
assert result.exit_code == 2
check_out(result, advanced_data_regression)
| 25.710456 | 96 | 0.727216 |
import re
from typing import Union, no_type_check
import click
import pytest
from _pytest.capture import CaptureResult
from coincidence.regressions import AdvancedDataRegressionFixture, AdvancedFileRegressionFixture
from coincidence.selectors import max_version, min_version, not_pypy, only_pypy
from consolekit.terminal_colours import strip_ansi
from consolekit.testing import CliRunner, Result
from domdf_python_tools.paths import PathPlus, in_directory
from formate import Reformatter, reformat_file
from formate.__main__ import main
from formate.config import load_toml
path_sub = re.compile(rf" .*/pytest-of-.*/pytest-\d+")
@no_type_check
def check_out(
result: Union[Result, CaptureResult[str]],
advanced_data_regression: AdvancedDataRegressionFixture,
):
if hasattr(result, "stdout"):
stdout = result.stdout
else:
stdout = result.out
if hasattr(result, "stderr"):
stderr = result.stderr
else:
stderr = result.err
data_dict = {
"out": strip_ansi(path_sub.sub(" ...", stdout)).split('\n'),
"err": strip_ansi(path_sub.sub(" ...", stderr)).split('\n'),
}
advanced_data_regression.check(data_dict)
@pytest.fixture()
def demo_environment(tmp_pathplus):
example_formate_toml = PathPlus(__file__).parent / "example_formate.toml"
(tmp_pathplus / "formate.toml").write_text(example_formate_toml.read_text())
code = [
"class F:",
"\tfrom collections import (",
"Iterable,",
"\tCounter,",
"\t\t)",
'',
"\tdef foo(self):",
"\t\tpass",
'',
"print('hello world')",
r"assert t.uname == '\udce4\udcf6\udcfc'",
]
(tmp_pathplus / "code.py").write_lines(code, trailing_whitespace=True)
@pytest.fixture()
def demo_pyproject_environment(demo_environment, tmp_pathplus):
example_formate_toml = PathPlus(__file__).parent / "example_pyproject.toml"
(tmp_pathplus / "pyproject.toml").write_text(example_formate_toml.read_text())
def test_integration(
tmp_pathplus: PathPlus,
advanced_file_regression: AdvancedFileRegressionFixture,
capsys,
advanced_data_regression: AdvancedDataRegressionFixture,
demo_environment,
):
config = load_toml(tmp_pathplus / "formate.toml")
st = (tmp_pathplus / "code.py").stat()
assert st == st
assert reformat_file(tmp_pathplus / "code.py", config) == 1
advanced_file_regression.check_file(tmp_pathplus / "code.py")
check_out(capsys.readouterr(), advanced_data_regression)
new_st = (tmp_pathplus / "code.py").stat()
assert new_st.st_mtime != st.st_mtime
assert new_st != st
assert reformat_file(tmp_pathplus / "code.py", config) == 0
advanced_file_regression.check_file(tmp_pathplus / "code.py")
# mtime should be the same
assert (tmp_pathplus / "code.py").stat().st_mtime == new_st.st_mtime
def test_integration_pyproject(
tmp_pathplus: PathPlus,
advanced_file_regression: AdvancedFileRegressionFixture,
capsys,
advanced_data_regression: AdvancedDataRegressionFixture,
demo_pyproject_environment,
):
config = load_toml(tmp_pathplus / "pyproject.toml")
assert reformat_file(tmp_pathplus / "code.py", config) == 1
advanced_file_regression.check_file(tmp_pathplus / "code.py")
check_out(capsys.readouterr(), advanced_data_regression)
# Calling a second time shouldn't change anything
assert reformat_file(tmp_pathplus / "code.py", config) == 0
advanced_file_regression.check_file(tmp_pathplus / "code.py")
def test_reformatter_class(
tmp_pathplus: PathPlus,
advanced_file_regression: AdvancedFileRegressionFixture,
capsys,
advanced_data_regression: AdvancedDataRegressionFixture,
demo_environment,
):
config = load_toml(tmp_pathplus / "formate.toml")
r = Reformatter(tmp_pathplus / "code.py", config)
with pytest.raises(ValueError, match=r"'Reformatter.run\(\)' must be called first!"):
r.to_string()
with pytest.raises(ValueError, match=r"'Reformatter.run\(\)' must be called first!"):
r.to_file()
with pytest.raises(ValueError, match=r"'Reformatter.run\(\)' must be called first!"):
r.get_diff()
st = (tmp_pathplus / "code.py").stat()
assert st == st
assert r.run() == 1
r.to_file()
advanced_file_regression.check_file(tmp_pathplus / "code.py")
advanced_file_regression.check(r.to_string(), extension="._py_")
captured = capsys.readouterr()
assert not captured.out
assert not captured.err
new_st = (tmp_pathplus / "code.py").stat()
assert new_st.st_mtime != st.st_mtime
assert new_st != st
r = Reformatter(tmp_pathplus / "code.py", config)
assert r.run() == 0
r.to_file()
advanced_file_regression.check_file(tmp_pathplus / "code.py")
def test_cli(
tmp_pathplus: PathPlus,
advanced_file_regression: AdvancedFileRegressionFixture,
advanced_data_regression: AdvancedDataRegressionFixture,
demo_environment,
):
result: Result
st = (tmp_pathplus / "code.py").stat()
assert st == st
with in_directory(tmp_pathplus):
runner = CliRunner(mix_stderr=False)
result = runner.invoke(
main,
args=["code.py", "--no-colour", "--diff", "--verbose"],
)
assert result.exit_code == 1
advanced_file_regression.check_file(tmp_pathplus / "code.py")
check_out(result, advanced_data_regression)
# mtime should have changed
new_st = (tmp_pathplus / "code.py").stat()
assert new_st.st_mtime != st.st_mtime
assert new_st != st
# Calling a second time shouldn't change anything
with in_directory(tmp_pathplus):
runner = CliRunner(mix_stderr=False)
result = runner.invoke(main, args=["code.py"])
assert result.exit_code == 0
assert (tmp_pathplus / "code.py").stat().st_mtime == new_st.st_mtime
def test_cli_verbose_verbose(
tmp_pathplus: PathPlus,
advanced_file_regression: AdvancedFileRegressionFixture,
advanced_data_regression: AdvancedDataRegressionFixture,
demo_environment,
):
result: Result
with in_directory(tmp_pathplus):
runner = CliRunner(mix_stderr=False)
result = runner.invoke(
main,
args=["code.py", "--no-colour", "--diff", "--verbose", "-v"],
)
assert result.exit_code == 1
advanced_file_regression.check_file(tmp_pathplus / "code.py")
with in_directory(tmp_pathplus):
runner = CliRunner(mix_stderr=False)
result = runner.invoke(
main,
args=["code.py", "code.c", "--no-colour", "--diff", "--verbose", "-v"],
)
assert result.exit_code == 0
check_out(result, advanced_data_regression)
@max_version("3.9.9", reason="Output differs on Python 3.10+")
@not_pypy("Output differs on PyPy")
def test_cli_syntax_error(
tmp_pathplus: PathPlus,
advanced_data_regression: AdvancedDataRegressionFixture,
demo_environment,
):
code = [
"class F:",
"\tfrom collections import (",
"Iterable,",
"\tCounter,",
"\t\t)",
'',
"\tdef foo(self):",
"\t\tpass",
'',
"print('hello world'",
]
(tmp_pathplus / "code.py").write_lines(code, trailing_whitespace=True)
with in_directory(tmp_pathplus):
runner = CliRunner(mix_stderr=False)
result: Result = runner.invoke(main, args=["code.py", "--no-colour", "--verbose"])
assert result.exit_code == 126
check_out(result, advanced_data_regression)
@only_pypy("Output differs on PyPy")
def test_cli_syntax_error_pypy(
tmp_pathplus: PathPlus,
advanced_data_regression: AdvancedDataRegressionFixture,
demo_environment,
):
code = [
"class F:",
"\tfrom collections import (",
"Iterable,",
"\tCounter,",
"\t\t)",
'',
"\tdef foo(self):",
"\t\tpass",
'',
"print('hello world'",
]
(tmp_pathplus / "code.py").write_lines(code, trailing_whitespace=True)
with in_directory(tmp_pathplus):
runner = CliRunner(mix_stderr=False)
result: Result = runner.invoke(main, args=["code.py", "--no-colour", "--verbose"])
assert result.exit_code == 126
check_out(result, advanced_data_regression)
@min_version("3.10", reason="Output differs on Python 3.10+")
def test_cli_syntax_error_py310(
tmp_pathplus: PathPlus,
advanced_data_regression: AdvancedDataRegressionFixture,
demo_environment,
):
code = [
"class F:",
"\tfrom collections import (",
"Iterable,",
"\tCounter,",
"\t\t)",
'',
"\tdef foo(self):",
"\t\tpass",
'',
"print('hello world'",
]
(tmp_pathplus / "code.py").write_lines(code, trailing_whitespace=True)
with in_directory(tmp_pathplus):
runner = CliRunner(mix_stderr=False)
result: Result = runner.invoke(main, args=["code.py", "--no-colour", "--verbose"])
assert result.exit_code == 126
check_out(result, advanced_data_regression)
@pytest.mark.skipif(click.__version__.split('.')[0] != '7', reason="Output differs on Click 8")
def test_cli_no_config(
tmp_pathplus: PathPlus,
advanced_data_regression: AdvancedDataRegressionFixture,
):
result: Result
with in_directory(tmp_pathplus):
runner = CliRunner(mix_stderr=False)
result = runner.invoke(main, args=["--no-colour", "--verbose"])
assert result.exit_code == 2
check_out(result, advanced_data_regression)
@pytest.mark.skipif(click.__version__.split('.')[0] == '7', reason="Output differs on Click 8")
def test_cli_no_config_click8(
tmp_pathplus: PathPlus,
advanced_data_regression: AdvancedDataRegressionFixture,
):
result: Result
with in_directory(tmp_pathplus):
runner = CliRunner(mix_stderr=False)
result = runner.invoke(main, args=["--no-colour", "--verbose"])
assert result.exit_code == 2
check_out(result, advanced_data_regression)
| true | true |
1c2e65d33801a4fa744793960df341bf946c28ad | 32 | py | Python | {{cookiecutter.package_name}}/{{cookiecutter.package_name}}/__init__.py | simongarisch/cookiecutter_streamlit | 2ef3dafdbc5505b601a0f8aee8fcbf8d0cdbf537 | [
"MIT"
] | 5 | 2020-08-26T03:43:24.000Z | 2021-11-08T10:45:27.000Z | {{cookiecutter.package_name}}/{{cookiecutter.package_name}}/__init__.py | simongarisch/cookiecutter_streamlit | 2ef3dafdbc5505b601a0f8aee8fcbf8d0cdbf537 | [
"MIT"
] | 1 | 2020-08-26T03:42:37.000Z | 2020-08-26T03:42:37.000Z | {{cookiecutter.package_name}}/{{cookiecutter.package_name}}/__init__.py | simongarisch/cookiecutter_streamlit | 2ef3dafdbc5505b601a0f8aee8fcbf8d0cdbf537 | [
"MIT"
] | null | null | null | from . import app # noqa: F401
| 16 | 31 | 0.65625 | from . import app
| true | true |
1c2e67114bdb46bf67592b33e2fdbd16e1e9438f | 5,933 | py | Python | tensorflow/python/ops/math_grad_test.py | connectthefuture/tensorflow | 93812423fcd5878aa2c1d0b68dc0496980c8519d | [
"Apache-2.0"
] | 1 | 2016-12-12T09:46:14.000Z | 2016-12-12T09:46:14.000Z | tensorflow/python/ops/math_grad_test.py | connectthefuture/tensorflow | 93812423fcd5878aa2c1d0b68dc0496980c8519d | [
"Apache-2.0"
] | null | null | null | tensorflow/python/ops/math_grad_test.py | connectthefuture/tensorflow | 93812423fcd5878aa2c1d0b68dc0496980c8519d | [
"Apache-2.0"
] | 1 | 2019-11-04T11:58:30.000Z | 2019-11-04T11:58:30.000Z | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for Python ops defined in math_grad.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
class SquaredDifferenceOpTest(tf.test.TestCase):
def _testGrad(self, left_shape, right_shape):
if len(left_shape) > len(right_shape):
output_shape = left_shape
else:
output_shape = right_shape
l = np.random.randn(*left_shape)
r = np.random.randn(*right_shape)
with self.test_session(use_gpu=True):
left_tensor = tf.constant(l, shape=left_shape)
right_tensor = tf.constant(r, shape=right_shape)
output = tf.squared_difference(left_tensor, right_tensor)
left_err = tf.test.compute_gradient_error(left_tensor,
left_shape,
output,
output_shape,
x_init_value=l)
right_err = tf.test.compute_gradient_error(right_tensor,
right_shape,
output,
output_shape,
x_init_value=r)
self.assertLess(left_err, 1e-10)
self.assertLess(right_err, 1e-10)
def testGrad(self):
self._testGrad([1, 2, 3, 2], [3, 2])
self._testGrad([2, 4], [3, 2, 4])
class AbsOpTest(tf.test.TestCase):
def _biasedRandN(self, shape, bias=0.1, sigma=1.0):
"""Returns samples from a normal distribution shifted `bias` away from 0."""
value = np.random.randn(*shape) * sigma
return value + np.sign(value) * bias
def _testGrad(self, shape, dtype=None, max_error=None, bias=None, sigma=None):
np.random.seed(7)
if dtype in (tf.complex64, tf.complex128):
value = tf.complex(self._biasedRandN(shape, bias=bias, sigma=sigma),
self._biasedRandN(shape, bias=bias, sigma=sigma))
else:
value = tf.convert_to_tensor(self._biasedRandN(shape, bias=bias),
dtype=dtype)
with self.test_session(use_gpu=True):
if dtype in (tf.complex64, tf.complex128):
output = tf.complex_abs(value)
else:
output = tf.abs(value)
error = tf.test.compute_gradient_error(
value, shape, output, output.get_shape().as_list())
self.assertLess(error, max_error)
def testComplexAbs(self):
# Bias random test values away from zero to avoid numeric instabilities.
self._testGrad([3, 3], dtype=tf.float32, max_error=2e-5, bias=0.1,
sigma=1.0)
self._testGrad([3, 3], dtype=tf.complex64, max_error=2e-5, bias=0.1,
sigma=1.0)
# Ensure stability near the pole at zero.
self._testGrad([3, 3], dtype=tf.float32, max_error=100.0, bias=0.0,
sigma=0.1)
self._testGrad([3, 3], dtype=tf.complex64, max_error=100.0, bias=0.0,
sigma=0.1)
class MinOrMaxGradientTest(tf.test.TestCase):
def testMinGradient(self):
inputs = tf.constant([1.0], dtype=tf.float32)
outputs = tf.reduce_min(tf.concat_v2([inputs, inputs], 0))
with self.test_session():
error = tf.test.compute_gradient_error(inputs, [1], outputs, [])
self.assertLess(error, 1e-4)
def testMaxGradient(self):
inputs = tf.constant([1.0], dtype=tf.float32)
outputs = tf.reduce_max(tf.concat_v2([inputs, inputs], 0))
with self.test_session():
error = tf.test.compute_gradient_error(inputs, [1], outputs, [])
self.assertLess(error, 1e-4)
class SegmentMinOrMaxGradientTest(tf.test.TestCase):
def testSegmentMinGradient(self):
data = tf.constant([1.0, 2.0, 3.0], dtype=tf.float32)
segment_ids = tf.constant([0, 0, 1], dtype=tf.int64)
segment_min = tf.segment_min(data, segment_ids)
with self.test_session():
error = tf.test.compute_gradient_error(data, [3], segment_min, [2])
self.assertLess(error, 1e-4)
def testSegmentMaxGradient(self):
data = tf.constant([1.0, 2.0, 3.0], dtype=tf.float32)
segment_ids = tf.constant([0, 0, 1], dtype=tf.int64)
segment_max = tf.segment_max(data, segment_ids)
with self.test_session():
error = tf.test.compute_gradient_error(data, [3], segment_max, [2])
self.assertLess(error, 1e-4)
def testSegmentMinGradientWithTies(self):
inputs = tf.constant([1.0], dtype=tf.float32)
data = tf.concat_v2([inputs, inputs], 0)
segment_ids = tf.constant([0, 0], dtype=tf.int64)
segment_min = tf.segment_min(data, segment_ids)
with self.test_session():
error = tf.test.compute_gradient_error(inputs, [1], segment_min, [1])
self.assertLess(error, 1e-4)
def testSegmentMaxGradientWithTies(self):
inputs = tf.constant([1.0], dtype=tf.float32)
data = tf.concat_v2([inputs, inputs], 0)
segment_ids = tf.constant([0, 0], dtype=tf.int64)
segment_max = tf.segment_max(data, segment_ids)
with self.test_session():
error = tf.test.compute_gradient_error(inputs, [1], segment_max, [1])
self.assertLess(error, 1e-4)
if __name__ == "__main__":
tf.test.main()
| 38.777778 | 80 | 0.629698 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
class SquaredDifferenceOpTest(tf.test.TestCase):
def _testGrad(self, left_shape, right_shape):
if len(left_shape) > len(right_shape):
output_shape = left_shape
else:
output_shape = right_shape
l = np.random.randn(*left_shape)
r = np.random.randn(*right_shape)
with self.test_session(use_gpu=True):
left_tensor = tf.constant(l, shape=left_shape)
right_tensor = tf.constant(r, shape=right_shape)
output = tf.squared_difference(left_tensor, right_tensor)
left_err = tf.test.compute_gradient_error(left_tensor,
left_shape,
output,
output_shape,
x_init_value=l)
right_err = tf.test.compute_gradient_error(right_tensor,
right_shape,
output,
output_shape,
x_init_value=r)
self.assertLess(left_err, 1e-10)
self.assertLess(right_err, 1e-10)
def testGrad(self):
self._testGrad([1, 2, 3, 2], [3, 2])
self._testGrad([2, 4], [3, 2, 4])
class AbsOpTest(tf.test.TestCase):
def _biasedRandN(self, shape, bias=0.1, sigma=1.0):
value = np.random.randn(*shape) * sigma
return value + np.sign(value) * bias
def _testGrad(self, shape, dtype=None, max_error=None, bias=None, sigma=None):
np.random.seed(7)
if dtype in (tf.complex64, tf.complex128):
value = tf.complex(self._biasedRandN(shape, bias=bias, sigma=sigma),
self._biasedRandN(shape, bias=bias, sigma=sigma))
else:
value = tf.convert_to_tensor(self._biasedRandN(shape, bias=bias),
dtype=dtype)
with self.test_session(use_gpu=True):
if dtype in (tf.complex64, tf.complex128):
output = tf.complex_abs(value)
else:
output = tf.abs(value)
error = tf.test.compute_gradient_error(
value, shape, output, output.get_shape().as_list())
self.assertLess(error, max_error)
def testComplexAbs(self):
self._testGrad([3, 3], dtype=tf.float32, max_error=2e-5, bias=0.1,
sigma=1.0)
self._testGrad([3, 3], dtype=tf.complex64, max_error=2e-5, bias=0.1,
sigma=1.0)
self._testGrad([3, 3], dtype=tf.float32, max_error=100.0, bias=0.0,
sigma=0.1)
self._testGrad([3, 3], dtype=tf.complex64, max_error=100.0, bias=0.0,
sigma=0.1)
class MinOrMaxGradientTest(tf.test.TestCase):
def testMinGradient(self):
inputs = tf.constant([1.0], dtype=tf.float32)
outputs = tf.reduce_min(tf.concat_v2([inputs, inputs], 0))
with self.test_session():
error = tf.test.compute_gradient_error(inputs, [1], outputs, [])
self.assertLess(error, 1e-4)
def testMaxGradient(self):
inputs = tf.constant([1.0], dtype=tf.float32)
outputs = tf.reduce_max(tf.concat_v2([inputs, inputs], 0))
with self.test_session():
error = tf.test.compute_gradient_error(inputs, [1], outputs, [])
self.assertLess(error, 1e-4)
class SegmentMinOrMaxGradientTest(tf.test.TestCase):
def testSegmentMinGradient(self):
data = tf.constant([1.0, 2.0, 3.0], dtype=tf.float32)
segment_ids = tf.constant([0, 0, 1], dtype=tf.int64)
segment_min = tf.segment_min(data, segment_ids)
with self.test_session():
error = tf.test.compute_gradient_error(data, [3], segment_min, [2])
self.assertLess(error, 1e-4)
def testSegmentMaxGradient(self):
data = tf.constant([1.0, 2.0, 3.0], dtype=tf.float32)
segment_ids = tf.constant([0, 0, 1], dtype=tf.int64)
segment_max = tf.segment_max(data, segment_ids)
with self.test_session():
error = tf.test.compute_gradient_error(data, [3], segment_max, [2])
self.assertLess(error, 1e-4)
def testSegmentMinGradientWithTies(self):
inputs = tf.constant([1.0], dtype=tf.float32)
data = tf.concat_v2([inputs, inputs], 0)
segment_ids = tf.constant([0, 0], dtype=tf.int64)
segment_min = tf.segment_min(data, segment_ids)
with self.test_session():
error = tf.test.compute_gradient_error(inputs, [1], segment_min, [1])
self.assertLess(error, 1e-4)
def testSegmentMaxGradientWithTies(self):
inputs = tf.constant([1.0], dtype=tf.float32)
data = tf.concat_v2([inputs, inputs], 0)
segment_ids = tf.constant([0, 0], dtype=tf.int64)
segment_max = tf.segment_max(data, segment_ids)
with self.test_session():
error = tf.test.compute_gradient_error(inputs, [1], segment_max, [1])
self.assertLess(error, 1e-4)
if __name__ == "__main__":
tf.test.main()
| true | true |
1c2e67b756b49f212be2f8f1f244e49bdf436db0 | 10,309 | py | Python | rllib/algorithms/maml/maml.py | Gekho457/ray | bed660b085fa9949bca71160addfc0a69931c64b | [
"Apache-2.0"
] | null | null | null | rllib/algorithms/maml/maml.py | Gekho457/ray | bed660b085fa9949bca71160addfc0a69931c64b | [
"Apache-2.0"
] | null | null | null | rllib/algorithms/maml/maml.py | Gekho457/ray | bed660b085fa9949bca71160addfc0a69931c64b | [
"Apache-2.0"
] | null | null | null | import logging
import numpy as np
from typing import Type
from ray.rllib.utils.sgd import standardized
from ray.rllib.agents import with_common_config
from ray.rllib.agents.trainer import Trainer
from ray.rllib.evaluation.metrics import get_learner_stats
from ray.rllib.evaluation.worker_set import WorkerSet
from ray.rllib.execution.common import (
STEPS_SAMPLED_COUNTER,
STEPS_TRAINED_COUNTER,
STEPS_TRAINED_THIS_ITER_COUNTER,
_get_shared_metrics,
)
from ray.rllib.policy.policy import Policy
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.execution.metric_ops import CollectMetrics
from ray.rllib.evaluation.metrics import collect_metrics
from ray.rllib.utils.annotations import override
from ray.rllib.utils.deprecation import DEPRECATED_VALUE
from ray.rllib.utils.metrics.learner_info import LEARNER_INFO
from ray.rllib.utils.typing import TrainerConfigDict
from ray.util.iter import from_actors, LocalIterator
logger = logging.getLogger(__name__)
# fmt: off
# __sphinx_doc_begin__
DEFAULT_CONFIG = with_common_config({
# If true, use the Generalized Advantage Estimator (GAE)
# with a value function, see https://arxiv.org/pdf/1506.02438.pdf.
"use_gae": True,
# GAE(lambda) parameter
"lambda": 1.0,
# Initial coefficient for KL divergence
"kl_coeff": 0.0005,
# Size of batches collected from each worker
"rollout_fragment_length": 200,
# Do create an actual env on the local worker (worker-idx=0).
"create_env_on_driver": True,
# Stepsize of SGD
"lr": 1e-3,
"model": {
# Share layers for value function.
"vf_share_layers": False,
},
# Coefficient of the value function loss
"vf_loss_coeff": 0.5,
# Coefficient of the entropy regularizer
"entropy_coeff": 0.0,
# PPO clip parameter
"clip_param": 0.3,
# Clip param for the value function. Note that this is sensitive to the
# scale of the rewards. If your expected V is large, increase this.
"vf_clip_param": 10.0,
# If specified, clip the global norm of gradients by this amount
"grad_clip": None,
# Target value for KL divergence
"kl_target": 0.01,
# Whether to rollout "complete_episodes" or "truncate_episodes"
"batch_mode": "complete_episodes",
# Which observation filter to apply to the observation
"observation_filter": "NoFilter",
# Number of Inner adaptation steps for the MAML algorithm
"inner_adaptation_steps": 1,
# Number of MAML steps per meta-update iteration (PPO steps)
"maml_optimizer_steps": 5,
# Inner Adaptation Step size
"inner_lr": 0.1,
# Use Meta Env Template
"use_meta_env": True,
# Deprecated keys:
# Share layers for value function. If you set this to True, it's important
# to tune vf_loss_coeff.
# Use config.model.vf_share_layers instead.
"vf_share_layers": DEPRECATED_VALUE,
# Use `execution_plan` instead of `training_iteration`.
"_disable_execution_plan_api": False,
})
# __sphinx_doc_end__
# fmt: on
# @mluo: TODO
def set_worker_tasks(workers, use_meta_env):
if use_meta_env:
n_tasks = len(workers.remote_workers())
tasks = workers.local_worker().foreach_env(lambda x: x)[0].sample_tasks(n_tasks)
for i, worker in enumerate(workers.remote_workers()):
worker.foreach_env.remote(lambda env: env.set_task(tasks[i]))
class MetaUpdate:
def __init__(self, workers, maml_steps, metric_gen, use_meta_env):
self.workers = workers
self.maml_optimizer_steps = maml_steps
self.metric_gen = metric_gen
self.use_meta_env = use_meta_env
def __call__(self, data_tuple):
# Metaupdate Step
samples = data_tuple[0]
adapt_metrics_dict = data_tuple[1]
# Metric Updating
metrics = _get_shared_metrics()
metrics.counters[STEPS_SAMPLED_COUNTER] += samples.count
fetches = None
for i in range(self.maml_optimizer_steps):
fetches = self.workers.local_worker().learn_on_batch(samples)
learner_stats = get_learner_stats(fetches)
# Sync workers with meta policy
self.workers.sync_weights()
# Set worker tasks
set_worker_tasks(self.workers, self.use_meta_env)
# Update KLS
def update(pi, pi_id):
assert "inner_kl" not in learner_stats, (
"inner_kl should be nested under policy id key",
learner_stats,
)
if pi_id in learner_stats:
assert "inner_kl" in learner_stats[pi_id], (learner_stats, pi_id)
pi.update_kls(learner_stats[pi_id]["inner_kl"])
else:
logger.warning("No data for {}, not updating kl".format(pi_id))
self.workers.local_worker().foreach_policy_to_train(update)
# Modify Reporting Metrics
metrics = _get_shared_metrics()
metrics.info[LEARNER_INFO] = fetches
metrics.counters[STEPS_TRAINED_THIS_ITER_COUNTER] = samples.count
metrics.counters[STEPS_TRAINED_COUNTER] += samples.count
res = self.metric_gen.__call__(None)
res.update(adapt_metrics_dict)
return res
def post_process_metrics(adapt_iter, workers, metrics):
# Obtain Current Dataset Metrics and filter out
name = "_adapt_" + str(adapt_iter) if adapt_iter > 0 else ""
# Only workers are collecting data
res = collect_metrics(remote_workers=workers.remote_workers())
metrics["episode_reward_max" + str(name)] = res["episode_reward_max"]
metrics["episode_reward_mean" + str(name)] = res["episode_reward_mean"]
metrics["episode_reward_min" + str(name)] = res["episode_reward_min"]
return metrics
def inner_adaptation(workers, samples):
# Each worker performs one gradient descent
for i, e in enumerate(workers.remote_workers()):
e.learn_on_batch.remote(samples[i])
class MAMLTrainer(Trainer):
@classmethod
@override(Trainer)
def get_default_config(cls) -> TrainerConfigDict:
return DEFAULT_CONFIG
@override(Trainer)
def validate_config(self, config: TrainerConfigDict) -> None:
# Call super's validation method.
super().validate_config(config)
if config["num_gpus"] > 1:
raise ValueError("`num_gpus` > 1 not yet supported for MAML!")
if config["inner_adaptation_steps"] <= 0:
raise ValueError("Inner Adaptation Steps must be >=1!")
if config["maml_optimizer_steps"] <= 0:
raise ValueError("PPO steps for meta-update needs to be >=0!")
if config["entropy_coeff"] < 0:
raise ValueError("`entropy_coeff` must be >=0.0!")
if config["batch_mode"] != "complete_episodes":
raise ValueError("`batch_mode`=truncate_episodes not supported!")
if config["num_workers"] <= 0:
raise ValueError("Must have at least 1 worker/task!")
if config["create_env_on_driver"] is False:
raise ValueError(
"Must have an actual Env created on the driver "
"(local) worker! Set `create_env_on_driver` to True."
)
@override(Trainer)
def get_default_policy_class(self, config: TrainerConfigDict) -> Type[Policy]:
if config["framework"] == "torch":
from ray.rllib.algorithms.maml.maml_torch_policy import MAMLTorchPolicy
return MAMLTorchPolicy
elif config["framework"] == "tf":
from ray.rllib.algorithms.maml.maml_tf_policy import MAMLDynamicTFPolicy
return MAMLDynamicTFPolicy
else:
from ray.rllib.algorithms.maml.maml_tf_policy import MAMLEagerTFPolicy
return MAMLEagerTFPolicy
@staticmethod
@override(Trainer)
def execution_plan(
workers: WorkerSet, config: TrainerConfigDict, **kwargs
) -> LocalIterator[dict]:
assert (
len(kwargs) == 0
), "MAML execution_plan does NOT take any additional parameters"
# Sync workers with meta policy
workers.sync_weights()
# Samples and sets worker tasks
use_meta_env = config["use_meta_env"]
set_worker_tasks(workers, use_meta_env)
# Metric Collector
metric_collect = CollectMetrics(
workers,
min_history=config["metrics_num_episodes_for_smoothing"],
timeout_seconds=config["metrics_episode_collection_timeout_s"],
)
# Iterator for Inner Adaptation Data gathering (from pre->post
# adaptation)
inner_steps = config["inner_adaptation_steps"]
def inner_adaptation_steps(itr):
buf = []
split = []
metrics = {}
for samples in itr:
# Processing Samples (Standardize Advantages)
split_lst = []
for sample in samples:
sample["advantages"] = standardized(sample["advantages"])
split_lst.append(sample.count)
buf.extend(samples)
split.append(split_lst)
adapt_iter = len(split) - 1
metrics = post_process_metrics(adapt_iter, workers, metrics)
if len(split) > inner_steps:
out = SampleBatch.concat_samples(buf)
out["split"] = np.array(split)
buf = []
split = []
# Reporting Adaptation Rew Diff
ep_rew_pre = metrics["episode_reward_mean"]
ep_rew_post = metrics[
"episode_reward_mean_adapt_" + str(inner_steps)
]
metrics["adaptation_delta"] = ep_rew_post - ep_rew_pre
yield out, metrics
metrics = {}
else:
inner_adaptation(workers, samples)
rollouts = from_actors(workers.remote_workers())
rollouts = rollouts.batch_across_shards()
rollouts = rollouts.transform(inner_adaptation_steps)
# Metaupdate Step
train_op = rollouts.for_each(
MetaUpdate(
workers, config["maml_optimizer_steps"], metric_collect, use_meta_env
)
)
return train_op
| 36.299296 | 88 | 0.652052 | import logging
import numpy as np
from typing import Type
from ray.rllib.utils.sgd import standardized
from ray.rllib.agents import with_common_config
from ray.rllib.agents.trainer import Trainer
from ray.rllib.evaluation.metrics import get_learner_stats
from ray.rllib.evaluation.worker_set import WorkerSet
from ray.rllib.execution.common import (
STEPS_SAMPLED_COUNTER,
STEPS_TRAINED_COUNTER,
STEPS_TRAINED_THIS_ITER_COUNTER,
_get_shared_metrics,
)
from ray.rllib.policy.policy import Policy
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.execution.metric_ops import CollectMetrics
from ray.rllib.evaluation.metrics import collect_metrics
from ray.rllib.utils.annotations import override
from ray.rllib.utils.deprecation import DEPRECATED_VALUE
from ray.rllib.utils.metrics.learner_info import LEARNER_INFO
from ray.rllib.utils.typing import TrainerConfigDict
from ray.util.iter import from_actors, LocalIterator
logger = logging.getLogger(__name__)
DEFAULT_CONFIG = with_common_config({
"use_gae": True,
"lambda": 1.0,
"kl_coeff": 0.0005,
"rollout_fragment_length": 200,
"create_env_on_driver": True,
"lr": 1e-3,
"model": {
"vf_share_layers": False,
},
"vf_loss_coeff": 0.5,
"entropy_coeff": 0.0,
"clip_param": 0.3,
"vf_clip_param": 10.0,
"grad_clip": None,
"kl_target": 0.01,
"batch_mode": "complete_episodes",
"observation_filter": "NoFilter",
"inner_adaptation_steps": 1,
"maml_optimizer_steps": 5,
"inner_lr": 0.1,
"use_meta_env": True,
# to tune vf_loss_coeff.
# Use config.model.vf_share_layers instead.
"vf_share_layers": DEPRECATED_VALUE,
# Use `execution_plan` instead of `training_iteration`.
"_disable_execution_plan_api": False,
})
# __sphinx_doc_end__
# fmt: on
# @mluo: TODO
def set_worker_tasks(workers, use_meta_env):
if use_meta_env:
n_tasks = len(workers.remote_workers())
tasks = workers.local_worker().foreach_env(lambda x: x)[0].sample_tasks(n_tasks)
for i, worker in enumerate(workers.remote_workers()):
worker.foreach_env.remote(lambda env: env.set_task(tasks[i]))
class MetaUpdate:
def __init__(self, workers, maml_steps, metric_gen, use_meta_env):
self.workers = workers
self.maml_optimizer_steps = maml_steps
self.metric_gen = metric_gen
self.use_meta_env = use_meta_env
def __call__(self, data_tuple):
# Metaupdate Step
samples = data_tuple[0]
adapt_metrics_dict = data_tuple[1]
# Metric Updating
metrics = _get_shared_metrics()
metrics.counters[STEPS_SAMPLED_COUNTER] += samples.count
fetches = None
for i in range(self.maml_optimizer_steps):
fetches = self.workers.local_worker().learn_on_batch(samples)
learner_stats = get_learner_stats(fetches)
# Sync workers with meta policy
self.workers.sync_weights()
# Set worker tasks
set_worker_tasks(self.workers, self.use_meta_env)
# Update KLS
def update(pi, pi_id):
assert "inner_kl" not in learner_stats, (
"inner_kl should be nested under policy id key",
learner_stats,
)
if pi_id in learner_stats:
assert "inner_kl" in learner_stats[pi_id], (learner_stats, pi_id)
pi.update_kls(learner_stats[pi_id]["inner_kl"])
else:
logger.warning("No data for {}, not updating kl".format(pi_id))
self.workers.local_worker().foreach_policy_to_train(update)
# Modify Reporting Metrics
metrics = _get_shared_metrics()
metrics.info[LEARNER_INFO] = fetches
metrics.counters[STEPS_TRAINED_THIS_ITER_COUNTER] = samples.count
metrics.counters[STEPS_TRAINED_COUNTER] += samples.count
res = self.metric_gen.__call__(None)
res.update(adapt_metrics_dict)
return res
def post_process_metrics(adapt_iter, workers, metrics):
# Obtain Current Dataset Metrics and filter out
name = "_adapt_" + str(adapt_iter) if adapt_iter > 0 else ""
# Only workers are collecting data
res = collect_metrics(remote_workers=workers.remote_workers())
metrics["episode_reward_max" + str(name)] = res["episode_reward_max"]
metrics["episode_reward_mean" + str(name)] = res["episode_reward_mean"]
metrics["episode_reward_min" + str(name)] = res["episode_reward_min"]
return metrics
def inner_adaptation(workers, samples):
# Each worker performs one gradient descent
for i, e in enumerate(workers.remote_workers()):
e.learn_on_batch.remote(samples[i])
class MAMLTrainer(Trainer):
@classmethod
@override(Trainer)
def get_default_config(cls) -> TrainerConfigDict:
return DEFAULT_CONFIG
@override(Trainer)
def validate_config(self, config: TrainerConfigDict) -> None:
# Call super's validation method.
super().validate_config(config)
if config["num_gpus"] > 1:
raise ValueError("`num_gpus` > 1 not yet supported for MAML!")
if config["inner_adaptation_steps"] <= 0:
raise ValueError("Inner Adaptation Steps must be >=1!")
if config["maml_optimizer_steps"] <= 0:
raise ValueError("PPO steps for meta-update needs to be >=0!")
if config["entropy_coeff"] < 0:
raise ValueError("`entropy_coeff` must be >=0.0!")
if config["batch_mode"] != "complete_episodes":
raise ValueError("`batch_mode`=truncate_episodes not supported!")
if config["num_workers"] <= 0:
raise ValueError("Must have at least 1 worker/task!")
if config["create_env_on_driver"] is False:
raise ValueError(
"Must have an actual Env created on the driver "
"(local) worker! Set `create_env_on_driver` to True."
)
@override(Trainer)
def get_default_policy_class(self, config: TrainerConfigDict) -> Type[Policy]:
if config["framework"] == "torch":
from ray.rllib.algorithms.maml.maml_torch_policy import MAMLTorchPolicy
return MAMLTorchPolicy
elif config["framework"] == "tf":
from ray.rllib.algorithms.maml.maml_tf_policy import MAMLDynamicTFPolicy
return MAMLDynamicTFPolicy
else:
from ray.rllib.algorithms.maml.maml_tf_policy import MAMLEagerTFPolicy
return MAMLEagerTFPolicy
@staticmethod
@override(Trainer)
def execution_plan(
workers: WorkerSet, config: TrainerConfigDict, **kwargs
) -> LocalIterator[dict]:
assert (
len(kwargs) == 0
), "MAML execution_plan does NOT take any additional parameters"
workers.sync_weights()
use_meta_env = config["use_meta_env"]
set_worker_tasks(workers, use_meta_env)
metric_collect = CollectMetrics(
workers,
min_history=config["metrics_num_episodes_for_smoothing"],
timeout_seconds=config["metrics_episode_collection_timeout_s"],
)
inner_steps = config["inner_adaptation_steps"]
def inner_adaptation_steps(itr):
buf = []
split = []
metrics = {}
for samples in itr:
split_lst = []
for sample in samples:
sample["advantages"] = standardized(sample["advantages"])
split_lst.append(sample.count)
buf.extend(samples)
split.append(split_lst)
adapt_iter = len(split) - 1
metrics = post_process_metrics(adapt_iter, workers, metrics)
if len(split) > inner_steps:
out = SampleBatch.concat_samples(buf)
out["split"] = np.array(split)
buf = []
split = []
ep_rew_pre = metrics["episode_reward_mean"]
ep_rew_post = metrics[
"episode_reward_mean_adapt_" + str(inner_steps)
]
metrics["adaptation_delta"] = ep_rew_post - ep_rew_pre
yield out, metrics
metrics = {}
else:
inner_adaptation(workers, samples)
rollouts = from_actors(workers.remote_workers())
rollouts = rollouts.batch_across_shards()
rollouts = rollouts.transform(inner_adaptation_steps)
train_op = rollouts.for_each(
MetaUpdate(
workers, config["maml_optimizer_steps"], metric_collect, use_meta_env
)
)
return train_op
| true | true |
1c2e67d0008f1ba063945db94e9b653a9657eba1 | 1,805 | py | Python | pelenet/experiments/nestcomparison.py | sagacitysite/pelene | e8d4112264acb44954c52053b4e3f9d63b46bdd6 | [
"MIT"
] | 10 | 2021-02-09T16:42:37.000Z | 2022-01-10T07:37:00.000Z | pelenet/experiments/nestcomparison.py | sagacitysite/pelene | e8d4112264acb44954c52053b4e3f9d63b46bdd6 | [
"MIT"
] | null | null | null | pelenet/experiments/nestcomparison.py | sagacitysite/pelene | e8d4112264acb44954c52053b4e3f9d63b46bdd6 | [
"MIT"
] | 3 | 2021-02-10T18:12:31.000Z | 2021-09-13T07:40:01.000Z | # Loihi modules
import nxsdk.api.n2a as nx
# Official modules
import numpy as np
import logging
from copy import deepcopy
import os
# Pelenet modules
from ..system import System
from ..system.datalog import Datalog
from ..parameters import Parameters
from ..utils import Utils
from ..plots import Plot
from .readout import ReadoutExperiment
from ..network import ReservoirNetwork
"""
@desc: Class for comparing anisotropic nest simulation with anisotropic loihi simulation
"""
class NestComparison(ReadoutExperiment):
"""
@desc: Initiates the experiment
"""
def __init__(self):
super().__init__()
"""
@desc: Overwrite parameters for this experiment
"""
def updateParameters(self):
# Update patameters from parent
p = super().updateParameters()
return {
# Parameters from parent
**p,
# Experiment
'trials': 1,
'stepsPerTrial': 500,
# Input
'isClusterInput': True,
# Network
'refractoryDelay': 2, # Sparse activity (high values) vs. dense activity (low values)
'compartmentVoltageDecay': 400, #400, #500, # Slows down / speeds up
'compartmentCurrentDecay': 380, #425, #500 # Variability (higher values) vs. Stability (lower values)
'thresholdMant': 1000, # Slower spread (high values) va. faster spread (low values)
# Probes
'isExSpikeProbe': True,
'isOutSpikeProbe': False
}
# 400, 380, 1000
# 500, 400, 900 -> equal firing rate
# 400, 375, 1000 -> equal firing rate
# 300, 400, 1000 -> equal firing rate
# lower threshold and higher decays looks good! (e.g. 600, 600, 800) -> influence on performance?
| 29.590164 | 114 | 0.623823 |
import nxsdk.api.n2a as nx
import numpy as np
import logging
from copy import deepcopy
import os
from ..system import System
from ..system.datalog import Datalog
from ..parameters import Parameters
from ..utils import Utils
from ..plots import Plot
from .readout import ReadoutExperiment
from ..network import ReservoirNetwork
class NestComparison(ReadoutExperiment):
def __init__(self):
super().__init__()
def updateParameters(self):
p = super().updateParameters()
return {
**p,
'trials': 1,
'stepsPerTrial': 500,
'isClusterInput': True,
'refractoryDelay': 2,
'compartmentVoltageDecay': 400, }
| true | true |
1c2e69214588e0c2a8ef0926fa72d22d8951e59d | 39,094 | py | Python | cmake/tribits/ci_support/cdash_analyze_and_report.py | jschueller/seacas | 14c34ae08b757cba43a3a03ec0f129c8a168a9d3 | [
"Python-2.0",
"Zlib",
"BSD-2-Clause",
"MIT",
"NetCDF",
"BSL-1.0",
"X11",
"BSD-3-Clause"
] | 82 | 2016-02-04T18:38:25.000Z | 2022-03-29T03:01:49.000Z | cmake/tribits/ci_support/cdash_analyze_and_report.py | jschueller/seacas | 14c34ae08b757cba43a3a03ec0f129c8a168a9d3 | [
"Python-2.0",
"Zlib",
"BSD-2-Clause",
"MIT",
"NetCDF",
"BSL-1.0",
"X11",
"BSD-3-Clause"
] | 206 | 2015-11-20T01:57:47.000Z | 2022-03-31T21:12:04.000Z | cmake/tribits/ci_support/cdash_analyze_and_report.py | jschueller/seacas | 14c34ae08b757cba43a3a03ec0f129c8a168a9d3 | [
"Python-2.0",
"Zlib",
"BSD-2-Clause",
"MIT",
"NetCDF",
"BSL-1.0",
"X11",
"BSD-3-Clause"
] | 68 | 2016-01-13T22:46:51.000Z | 2022-03-31T06:25:05.000Z | #!/usr/bin/env python
# @HEADER
# ************************************************************************
#
# TriBITS: Tribal Build, Integrate, and Test System
# Copyright 2013 Sandia Corporation
#
# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
# the U.S. Government retains certain rights in this software.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the Corporation nor the names of the
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# ************************************************************************
# @HEADER
import sys
import pprint
import datetime
from FindGeneralScriptSupport import *
from GeneralScriptSupport import *
import CDashQueryAnalyzeReport as CDQAR
import cdash_build_testing_date as CBTD
from gitdist import addOptionParserChoiceOption
#
# Help message
#
usageHelp = r"""cdash_analyze_and_report.py [options]
This script takes in CDash URL information and other data as command-line
arguments and then analyzes it to look for missing expected builds, failed
tests, and various types of other failures and then reports the findings as an
HTML file written to disk and/or an HTML-formatted email sent to one or more
email addresses. (Other types of output can be produced as well in different
files.)
If all of the expected builds are found (and all of them have test results)
and there are no other failures found, then the script returns 0. Otherwise
the script returns non-zero. Therefore, this script can be used to drive
automated workflows by examining data on CDash.
"""
#
# Helper functions
#
def injectCmndLineOptionsInParser(clp, gitoliteRootDefault=""):
clp.add_option(
"--date", dest="date", type="string", default='yesterday',
help="Date for the testing day <YYYY-MM-DD> or special values 'today'"+\
" or 'yesterday'. [default 'yesterday']" )
clp.add_option(
"--cdash-project-testing-day-start-time", dest="cdashProjectTestingDayStartTime",
type="string", default="00:00",
help="The CDash project testing day build star time in UTC in format '<hh>:<mm>'."+\
" [default = '00:00']" )
clp.add_option(
"--cdash-project-name", dest="cdashProjectName", type="string", default="",
help="CDash project name (e.g. 'Trilinos'). [REQUIRED]" )
clp.add_option(
"--build-set-name", dest="buildSetName", type="string", default="",
help="Name for the set of builds, (e.g. 'Trilinos Nightly Builds)."+\
" This used in the email summary line and in the HTML file body"+\
" to identify the set of builds and tests being examined."+\
" [REQUIRED]" )
clp.add_option(
"--cdash-site-url", dest="cdashSiteUrl", type="string", default="",
help="Base CDash site (e.g. 'https://testing.sandia.gov/cdash')."+\
" [REQUIRED]" )
clp.add_option(
"--cdash-builds-filters", dest="cdashBuildsFilters", type="string",
default="",
help="Partial URL fragment for index.php making of the filters for"+\
" the set of builds (e.g. 'filtercount=1&showfilters=1&field1=groupname&compare1=61&value1=ATDM')."+\
" [REQUIRED]" )
clp.add_option(
"--cdash-nonpassed-tests-filters", dest="cdashNonpassedTestsFilters", type="string",
default="",
help="Partial URL fragment for queryTests.php making of the filters for"+\
" the set of non-passing tests matching this set of builds (e.g."+\
" 'filtercombine=and&filtercount=1&showfilters=1&filtercombine=and&field1=groupname&compare1=61&value1=ATDM')."+\
" This set of filter fields may also filter out extra nonpassing tests"+\
" such for known random system failures to avoid flooding the output. In this"+\
" case, one should also set --require-test-history-match-nonpassing-tests=off."+\
" [REQUIRED]" )
clp.add_option(
"--expected-builds-file", dest="expectedBuildsFile", type="string",
default="",
help="Path to a CSV file that lists the expected builds. Each of these builds"+\
" must have unique 'site' and 'buildname' field pairs or an error will be"+\
" raised and the tool will abort. A list of files is also allowed that are"+\
" separated with ',' as <file1>,<file2>,... [default = '']" )
clp.add_option(
"--tests-with-issue-trackers-file", dest="testsWithIssueTrackersFile",
type="string", default="",
help="Path to CSV file that lists tests with issue trackers (and other data)."+\
" Each of these tests must have a unique 'site', 'buildName', and 'testname'"+\
" sets or an error will be raised and the tool will abort. [default = '']" )
addOptionParserChoiceOption(
"--filter-out-builds-and-tests-not-matching-expected-builds",
"filterOutBuildsAndTestsNotMatchingExpectedBuildsStr",
("on", "off"), 1,
"Filter out build and test data not matching input list of expected builds."+\
" If set to 'on', this will filter out build and test data downloaded"+\
" from CDash that does not match the list of expected builds provided in"+\
" --expected-builds-file=<csv-file>. This will also filter out any tests"+\
" with issue trackers listed in"+\
" --tests-with-issue-trackers-file=<csv-file>.",
clp )
cdashQueriesCacheDir_default=os.getcwd()
clp.add_option(
"--cdash-queries-cache-dir", dest="cdashQueriesCacheDir", type="string",
default=cdashQueriesCacheDir_default,
help="Cache CDash query data this directory." \
+" [default = '"+cdashQueriesCacheDir_default+"']" )
clp.add_option(
"--cdash-base-cache-files-prefix", dest="cdashBaseCacheFilesPrefix", type="string",
default="",
help="Prefix given to the base-level cache files outside of the test_history/"+\
" directory. This is to allow multiple invocations of this script to share"+\
" the same base cache directory and share the test_history/ in case there are"+\
" overrlapping sets of tests where the test history cache could be reused."+\
" [default is derived from the --build-set-name=<build_set_name> argument where"+\
" spaces and punctuation in <build_set_name> are replaced with '_']" )
addOptionParserChoiceOption(
"--use-cached-cdash-data", "useCachedCDashDataStr",
("on", "off"), 1,
"Use data downloaded from CDash already cached. Note that this only"+\
" impacts the reuse of base-level cache files and does not impact the usage"+\
" of test history cache in the <cacheDir>/test_history/ directory."+\
" If a test history file for a given testing day exists under the test_history/"+\
" directory it is used unconditionally.",
clp )
testHistoryDaysDefault= 30
clp.add_option(
"--limit-test-history-days", dest="testHistoryDays",
default=testHistoryDaysDefault, type="int",
help="Number of days to go back in history for each test."+\
" [default = '"+str(testHistoryDaysDefault)+"']" )
limitTableRows = 10
clp.add_option(
"--limit-table-rows", dest="limitTableRows", type="int",
default=limitTableRows,
help="Limit to the number of rows displayed in many of"+\
" the tables. This impacts tables like 'twoif' and 'twoinr'"+\
" that could have thousands of entries for some projects."+\
" This limits the number of tests for which detailed test history"+\
" is downloaded from CDash and is therefore important to ensure the"+\
" tool does not take too long to execute. However, this does NOT"+\
" limit the number of rows in many other tables that should be bounded like"+\
" any of the tables related to the builds or the list of tests with"+\
" issue trackers. (The number of those should never be extremely high.)"+\
" [default '"+str(limitTableRows)+"']" )
addOptionParserChoiceOption(
"--require-test-history-match-nonpassing-tests",
"requireTestHistoryMatchNonpassingTestsStr",
("on", "off"), 0,
"Require that the status for each tracked test listed in the tests with issue"\
+" trackers CSV file match the status of that test returned from the test history"\
+" returned from CDash. In general, these should match up but these may not if extra"\
+" filter criteria has been added to the list on nonpassing tests in the"\
+" --cdash-nonpassed-tests-filters=<filters> set of filters (such as to filter out"\
+" a large number of random system failures). In this case, an error will be"\
+" returned by default and the script will crash. But this can be relaxed by"\
+" setting this to 'off' which will result in these tracked tests being listed in"\
+" the 'twim' table but typically with status 'Failed'.",
clp )
addOptionParserChoiceOption(
"--print-details", "printDetailsStr",
("on", "off"), 1,
"Print more info like the CDash URLs for downloaded data and the cache"+\
" file names.",
clp )
addOptionParserChoiceOption(
"--list-unexpected-builds",
"listUnexpectedBuildsStr",
("on", "off"), 1,
"List unexpected builds downloaded from CDash (i.e. not matching an expected build)'.",
clp )
clp.add_option(
"--write-unexpected-builds-to-file",
dest="writeUnexpectedBuildsToFile", type="string", default="",
help="Write a CSV file with a list of unexpected builds 'bu'." \
+" This is to make it easy to add new entires to the file read by" \
+" the option --expected-builds-file=<csv-file>. [default = '']" )
clp.add_option(
"--write-failing-tests-without-issue-trackers-to-file",
dest="writeFailingTestsWithoutIssueTrackersToFile", type="string", default="",
help="Write a CSV file with a list of tests with issue trackers failed 'twif'." \
+" This is to make it easy to add new entires to the file read by" \
+" the option --tests-with-issue-trackers-file=<csv-file>. [default = '']" )
clp.add_option(
"--write-test-data-to-file",
dest="writeTestDataToFile", type="string", default="",
help="Write pretty-printed Python list of dictionaries for tests" \
+" with issue trackers. This includes the history of the tests for" \
+" --limit-test-history-days=<days> of history. This contains all of the" \
+" information that appears in the generated summary tables for tests with" \
+" associated issue trackers. [default = '']" )
clp.add_option(
"--write-email-to-file", dest="writeEmailToFile", type="string", default="",
help="Write the body of the HTML email to this file. [default = '']" )
clp.add_option(
"--email-from-address=", dest="emailFromAddress", type="string", default="",
help="Address reported in the sent email. [default '']" )
clp.add_option(
"--send-email-to=", dest="sendEmailTo", type="string", default="",
help="Send email to 'address1, address2, ...'. [default '']" )
addOptionParserChoiceOption(
"--email-without-soft-hyphens",
"emailWithoutSoftHyphensStr",
("on", "off"), 1,
"Remove soft hyphens from emails.",
clp )
def validateAndConvertCmndLineOptions(inOptions):
if inOptions.date == "":
print("Error, can't have empty --date, must pass in --date=YYYY-MM-DD"+\
" or special values --date=today or --date=yesterday!")
sys.exit(1)
else:
dateTimeObj = CDQAR.convertInputDateArgToYYYYMMDD(
inOptions.cdashProjectTestingDayStartTime,
inOptions.date)
inOptions.date = CBTD.getDateStrFromDateTime(dateTimeObj)
# ToDo: Assert more of the options to make sure they are correct!
def setExtraCmndLineOptionsAfterParse(inOptions_inout):
setattr(inOptions_inout, 'filterOutBuildsAndTestsNotMatchingExpectedBuilds',
inOptions_inout.filterOutBuildsAndTestsNotMatchingExpectedBuildsStr == "on")
setattr(inOptions_inout, 'useCachedCDashData',
inOptions_inout.useCachedCDashDataStr == "on")
setattr(inOptions_inout, 'requireTestHistoryMatchNonpassingTests',
inOptions_inout.requireTestHistoryMatchNonpassingTestsStr == "on")
setattr(inOptions_inout, 'printDetails',
inOptions_inout.printDetailsStr == "on")
setattr(inOptions_inout, 'listUnexpectedBuilds',
inOptions_inout.listUnexpectedBuildsStr == "on")
if inOptions_inout.cdashBaseCacheFilesPrefix == "":
inOptions_inout.cdashBaseCacheFilesPrefix = \
CDQAR.getFileNameStrFromText(inOptions_inout.buildSetName)+"_"
setattr(inOptions_inout, 'emailWithoutSoftHyphens',
inOptions_inout.emailWithoutSoftHyphensStr == "on")
def getCmndLineOptions():
from optparse import OptionParser
clp = OptionParser(usage=usageHelp)
injectCmndLineOptionsInParser(clp)
(options, args) = clp.parse_args()
validateAndConvertCmndLineOptions(options)
setExtraCmndLineOptionsAfterParse(options)
return options
def fwdCmndLineOptions(inOptions, lt=""):
io = inOptions
cmndLineOpts = \
" --date='"+io.date+"'"+lt+\
" --cdash-project-testing-day-start-time='"+io.cdashProjectTestingDayStartTime+"'"+lt+\
" --cdash-project-name='"+io.cdashProjectName+"'"+lt+\
" --build-set-name='"+io.buildSetName+"'"+lt+\
" --cdash-site-url='"+io.cdashSiteUrl+"'"+lt+\
" --cdash-builds-filters='"+io.cdashBuildsFilters+"'"+lt+\
" --cdash-nonpassed-tests-filters='"+io.cdashNonpassedTestsFilters+"'"+lt+\
" --expected-builds-file='"+io.expectedBuildsFile+"'"+lt+\
" --tests-with-issue-trackers-file='"+io.testsWithIssueTrackersFile+"'"+lt+\
" --filter-out-builds-and-tests-not-matching-expected-builds='"+\
io.filterOutBuildsAndTestsNotMatchingExpectedBuildsStr+"'"+lt+\
" --cdash-queries-cache-dir='"+io.cdashQueriesCacheDir+"'"+lt+\
" --cdash-base-cache-files-prefix='"+io.cdashBaseCacheFilesPrefix+"'"+lt+\
" --use-cached-cdash-data='"+io.useCachedCDashDataStr+"'"+lt+\
" --limit-test-history-days='"+str(io.testHistoryDays)+"'"+lt+\
" --limit-table-rows='"+str(io.limitTableRows)+"'"+lt+\
" --require-test-history-match-nonpassing-tests='"+io.requireTestHistoryMatchNonpassingTestsStr+"'"+lt+\
" --print-details='"+io.printDetailsStr+"'"+lt+\
" --list-unexpected-builds='"+io.listUnexpectedBuildsStr+"'"+lt+\
" --write-unexpected-builds-to-fileo='"+io.writeUnexpectedBuildsToFile+"'"+lt+\
" --write-failing-tests-without-issue-trackers-to-file='"+io.writeFailingTestsWithoutIssueTrackersToFile+"'"+lt+\
" --write-test-data-to-file='"+io.writeTestDataToFile+"'"+lt+\
" --write-email-to-file='"+io.writeEmailToFile+"'"+lt+\
" --email-from-address='"+io.emailFromAddress+"'"+lt+\
" --send-email-to='"+io.sendEmailTo+"'"+lt+\
" --email-without-soft-hyphens='"+io.emailWithoutSoftHyphensStr+"'"+lt
return cmndLineOpts
def echoCmndLineOptions(inOptions):
print(fwdCmndLineOptions(inOptions, " \\\n"))
def echoCmndLine(inOptions):
print("")
print("**************************************************************************")
print("cdash_analyze_and_report.py \\")
echoCmndLineOptions(inOptions)
# Strategy class that can get test history for a list of tests and set them in
# the test dicts taking input from the cdash_analyze_and_report.py commandline
# arguments.
#
class AddTestHistoryStrategy(object):
def __init__(self, inOptions, testHistoryCacheDir):
self.inOptions = inOptions
self.testHistoryCacheDir = testHistoryCacheDir
def getTestHistory(self, testLOD):
sio = self.inOptions
CDQAR.foreachTransform(
testLOD,
CDQAR.AddTestHistoryToTestDictFunctor(
cdashUrl=sio.cdashSiteUrl,
projectName=sio.cdashProjectName,
date=sio.date,
testingDayStartTimeUtc=sio.cdashProjectTestingDayStartTime,
daysOfHistory=sio.testHistoryDays,
testCacheDir=self.testHistoryCacheDir,
useCachedCDashData=sio.useCachedCDashData,
alwaysUseCacheFileIfExists=True,
verbose=True,
printDetails=sio.printDetails,
requireMatchTestTopTestHistory=sio.requireTestHistoryMatchNonpassingTests,
)
)
#
# Run the script
#
if __name__ == '__main__':
#
# Get commandline options
#
inOptions = getCmndLineOptions()
echoCmndLine(inOptions)
cacheDirAndBaseFilePrefix = \
inOptions.cdashQueriesCacheDir+"/"+inOptions.cdashBaseCacheFilesPrefix
#
# A) Define common data, etc
#
tcd = CDQAR.TableColumnData
pp = pprint.PrettyPrinter(indent=2)
groupSiteBuildNameSortOrder = ['group', 'site', 'buildname']
#
# B) Sound off
#
print("***")
print("*** Query and analyze CDash results for "+inOptions.buildSetName+\
" for testing day "+inOptions.date)
print("***")
#
# C) Create beginning of email body (that does not require getting any data off CDash)
#
# Aggregation of vars that get updated in this main() body and by functions
# called.
cdashReportData = CDQAR.CDashReportData()
cdashReportData.htmlEmailBodyTop += \
"<h2>Build and Test results for "+inOptions.buildSetName \
+" on "+inOptions.date+"</h2>\n\n"
#
# D) Read data files, get data off of CDash, do analysis, and construct HTML
# body parts
#
try:
# Beginning of top full bulid and tests CDash links paragraph
cdashReportData.htmlEmailBodyTop += "<p>\n"
#
# D.1) Read data from input files, set up cache directories
#
# Assert this data is correct and abort if there is an error before we run
# expensive CDash queries!
#
# Get list of expected builds from input CSV file
expectedBuildsLOD = CDQAR.getExpectedBuildsListOfDictsFromCsvFileArg(
inOptions.expectedBuildsFile)
print("\nNum expected builds = "+str(len(expectedBuildsLOD)))
# Create a SearchableListOfDict object to help look up expected builds
# given a build dict by key/value pairs 'group', 'site', and 'buildname'
# (requires unique builds with these key/value pairs)
expectedBuildsSLOD = CDQAR.createSearchableListOfBuilds(expectedBuildsLOD)
# Create a SearchableListOfDicts that will look up an expected build given
# just a test dict fields ['site', 'buildName']. (The list of tests with
# issue trackers does not have 'group' since cdash/queryTests.php does not
# give the 'group' associated with each test. Also, note that we need
# this special SearchableListOfDicts since the Build Name key name
# different for a cdash/queryTests.php test dict 'buildName' and a
# cdash/index.php build dict 'buildname'.)
testsToExpectedBuildsSLOD = \
CDQAR.createTestToBuildSearchableListOfDicts(expectedBuildsLOD)
# ToDo: Put in try/except to print about error in duplicate rows in the
# list of expected builds.
# Get list of tests with issue trackers from the input CSV file
if inOptions.testsWithIssueTrackersFile:
fullTestsWithIssueTrackersLOD = CDQAR.getTestsWtihIssueTrackersListFromCsvFile(
inOptions.testsWithIssueTrackersFile)
else:
fullTestsWithIssueTrackersLOD = []
print("\nNum tests with issue trackers read from CSV file = "+\
str(len(fullTestsWithIssueTrackersLOD)))
if inOptions.filterOutBuildsAndTestsNotMatchingExpectedBuilds:
(testsWithIssueTrackersLOD, testsWithIssueTrackersNotExpectedLOD) = \
CDQAR.splitTestsOnMatchExpectedBuilds(fullTestsWithIssueTrackersLOD,
testsToExpectedBuildsSLOD)
print("Num tests with issue trackers matching expected builds = "+\
str(len(testsWithIssueTrackersLOD)))
else:
testsWithIssueTrackersLOD = fullTestsWithIssueTrackersLOD
print("Num tests with issue trackers = "+\
str(len(testsWithIssueTrackersLOD)))
# Get a SearchableListOfDicts for the tests with issue trackers to allow
# them to be looked up based on matching ['site', 'buildName', 'testname']
# key/value pairs.
testsWithIssueTrackersSLOD = \
CDQAR.createSearchableListOfTests(testsWithIssueTrackersLOD)
# ToDo: Put in try/except to print about error in duplicate rows in the
# list of tests with issue trackers.
# Get a functor that will return True if a passed-in test dict matches a
# test with an issue tracker for the test key/value pairs ['site',
# 'buildName', and 'testname'].
testsWithIssueTrackerMatchFunctor = \
CDQAR.MatchDictKeysValuesFunctor(testsWithIssueTrackersSLOD)
# Assert that the list of tests with issue trackers matches the list of
# expected builds
(allTestsMatch, errMsg) = CDQAR.doTestsWithIssueTrackersMatchExpectedBuilds(
testsWithIssueTrackersLOD, testsToExpectedBuildsSLOD)
if not allTestsMatch:
raise Exception(errMsg)
# Test history cache dir
testHistoryCacheDir = inOptions.cdashQueriesCacheDir+"/test_history"
if not os.path.exists(testHistoryCacheDir):
print("\nCreating new test cache directory '"+testHistoryCacheDir+"'")
os.mkdir(testHistoryCacheDir)
#
# D.2) Get top-level lists of build and nonpassing tests off CDash
#
#
# D.2.a) Get list of dicts of builds off cdash/index.phpp
#
cdashIndexBuildsBrowserUrl = CDQAR.getCDashIndexBrowserUrl(
inOptions.cdashSiteUrl, inOptions.cdashProjectName, inOptions.date,
inOptions.cdashBuildsFilters)
print("\nCDash builds browser URL:\n\n "+cdashIndexBuildsBrowserUrl+"\n")
cdashIndexBuildsQueryUrl = CDQAR.getCDashIndexQueryUrl(
inOptions.cdashSiteUrl,
inOptions.cdashProjectName,
inOptions.date,
inOptions.cdashBuildsFilters )
fullCDashIndexBuildsJsonCacheFile = \
cacheDirAndBaseFilePrefix+"fullCDashIndexBuilds.json"
fullBuildsLOD = CDQAR.downloadBuildsOffCDashAndFlatten(
cdashIndexBuildsQueryUrl,
fullCDashIndexBuildsJsonCacheFile,
inOptions.useCachedCDashData )
print("\nNum builds downloaded from CDash = "+str(len(fullBuildsLOD)))
(buildsExpectedLOD, buildsUnexpectedLOD) = \
CDQAR.splitTestsOnMatchExpectedBuilds(fullBuildsLOD, expectedBuildsSLOD)
if inOptions.filterOutBuildsAndTestsNotMatchingExpectedBuilds:
print("Num builds matching expected builds = "+str(len(buildsExpectedLOD)))
buildsLOD = buildsExpectedLOD
else:
buildsLOD = fullBuildsLOD
if inOptions.listUnexpectedBuilds:
print("Num builds unexpected = "+str(len(buildsUnexpectedLOD)))
print("Num builds = "+str(len(buildsLOD)))
# HTML line "Builds on CDash"
cdashReportData.htmlEmailBodyTop += \
"<a href=\""+cdashIndexBuildsBrowserUrl+"\">"+\
"Builds on CDash</a> (num/expected="+\
str(len(buildsLOD))+"/"+str(len(expectedBuildsLOD))+")<br>\n"
# Create a SearchableListOfDict object to help look up builds given a
# build dict by key/value pairs 'group', 'site', and 'buildname' (requires
# unique builds with these key/value pairs)
buildsSLOD = CDQAR.createSearchableListOfBuilds(buildsLOD)
# ToDo: Add try/except to report duplicate builds in case this raises an
# exception.
#
# D.2.b) Get list of dicts of all nonpassing tests off
# cdash/queryTests.php
#
cdashNonpassingTestsBrowserUrl = CDQAR.getCDashQueryTestsBrowserUrl(
inOptions.cdashSiteUrl, inOptions.cdashProjectName, inOptions.date,
inOptions.cdashNonpassedTestsFilters)
print("\nGetting list of nonpassing tests from CDash ...\n")
print("\nCDash nonpassing tests browser URL:\n\n"+\
" "+cdashNonpassingTestsBrowserUrl+"\n")
cdashNonpassingTestsQueryUrl = CDQAR.getCDashQueryTestsQueryUrl(
inOptions.cdashSiteUrl, inOptions.cdashProjectName, inOptions.date,
inOptions.cdashNonpassedTestsFilters)
cdashNonpassingTestsQueryJsonCacheFile = \
cacheDirAndBaseFilePrefix+"fullCDashNonpassingTests.json"
fullNonpassingTestsLOD = CDQAR.downloadTestsOffCDashQueryTestsAndFlatten(
cdashNonpassingTestsQueryUrl, cdashNonpassingTestsQueryJsonCacheFile,
inOptions.useCachedCDashData )
print("\nNum nonpassing tests direct from CDash query = "+\
str(len(fullNonpassingTestsLOD)))
if inOptions.filterOutBuildsAndTestsNotMatchingExpectedBuilds:
(nonpassingTestsLOD, nonpassingTestsNotExpectedLOD) = \
CDQAR.splitTestsOnMatchExpectedBuilds(fullNonpassingTestsLOD,
testsToExpectedBuildsSLOD)
print("Num nonpassing tests matching expected builds = "+\
str(len(nonpassingTestsLOD)))
else:
nonpassingTestsLOD = fullNonpassingTestsLOD
print("Num nonpassing tests = "+\
str(len(nonpassingTestsLOD)))
# HTML line "Nonpassing Tests on CDash"
cdashReportData.htmlEmailBodyTop += \
"<a href=\""+cdashNonpassingTestsBrowserUrl+"\">"+\
"Non-passing Tests on CDash</a> (num="+str(len(nonpassingTestsLOD))+")<br>\n"
# End of full build and test link paragraph and start the next paragraph
# for the summary of failures and other tables
cdashReportData.htmlEmailBodyTop += \
"</p>\n\n"+\
"<p>\n"
# Create a SearchableListOfDicts object for looking up a nonpassing test
# given the test dict fields 'site', 'buildName', and 'testname'.
nonpassingTestsSLOD = CDQAR.createSearchableListOfTests(
nonpassingTestsLOD, removeExactDuplicateElements=True,
checkDictsAreSame_in=CDQAR.checkCDashTestDictsAreSame )
# NOTE: Above we add the option to remove exact duplicate tests since
# cdash/queryTests.php can return duplicate tests (i.e. all test dict
# fields are the same except and has the same buildid but could have
# different testids!)
# ToDo: Add try/except for above code in order to report duplicate tests
# where the buildid (and other fields) not match.
print("Num nonpassing tests after removing duplicate tests = "+\
str(len(nonpassingTestsLOD)))
# Create a functor to to see if a test dict matches one of the nonpassing
# tests downloaded from cdash/queryTests.php.
nonpassingTestsMatchFunctor = \
CDQAR.MatchDictKeysValuesFunctor(nonpassingTestsSLOD)
#
# D.3) Partition the varous list of tests into different sets that will
# be displayed in different tables.
#
# Add issue tracker info for all nonpassing tests (including adding empty
# issue tracker fields for tests that don't have issue trackers)
CDQAR.foreachTransform( nonpassingTestsLOD,
CDQAR.AddIssueTrackerInfoToTestDictFunctor(testsWithIssueTrackersSLOD))
# Split the list of nonpassing tests into those with and without issue
# trackers
(nonpassingTestsWithIssueTrackersLOD,nonpassingTestsWithoutIssueTrackersLOD)=\
CDQAR.splitListOnMatch(nonpassingTestsLOD, testsWithIssueTrackerMatchFunctor)
print("Num nonpassing tests without issue trackers = "+\
str(len(nonpassingTestsWithoutIssueTrackersLOD)))
print("Num nonpassing tests with issue trackers = "+\
str(len(nonpassingTestsWithIssueTrackersLOD)))
# Split the list nonpassing tests without issue trackers into 'twoif' and
# 'twoinp'
(twoifLOD, twoinrLOD) = CDQAR.splitListOnMatch(
nonpassingTestsWithoutIssueTrackersLOD, CDQAR.isTestFailed)
print("Num nonpassing tests without issue trackers Failed = "+str(len(twoifLOD)))
print("Num nonpassing tests without issue trackers Not Run = "+str(len(twoinrLOD)))
# Split the list nonpassing tests with issue trackers into 'twif' and
# 'twinp'
(twifLOD, twinrLOD) = CDQAR.splitListOnMatch(
nonpassingTestsWithIssueTrackersLOD, CDQAR.isTestFailed)
print("Num nonpassing tests with issue trackers Failed = "+str(len(twifLOD)))
print("Num nonpassing tests with issue trackers Not Run = "+str(len(twinrLOD)))
# Get list of tests with issue trackers that are not in the list of
# nonpassing tests (and therefore these are passing or missing)
testsWithIssueTrackersGrossPassingOrMissingLOD = CDQAR.getFilteredList(
testsWithIssueTrackersSLOD,
CDQAR.NotMatchFunctor(nonpassingTestsMatchFunctor) )
print("Num tests with issue trackers gross passing or missing = "+\
str(len(testsWithIssueTrackersGrossPassingOrMissingLOD)))
#
# D.4) Process and tabulate lists of builds
#
buildsetReporter = CDQAR.SingleBuildsetReporter(cdashReportData)
#
# 'bm'
#
print("\nSearch for any missing expected builds ...\n")
missingExpectedBuildsLOD = CDQAR.getMissingExpectedBuildsList(
buildsSLOD, expectedBuildsLOD)
buildsetReporter.reportSingleBuildset("Builds Missing", "bm",
missingExpectedBuildsLOD,
buildsetGlobalPass=False,
buildsetColor=CDQAR.cdashColorFailed(),
buildsetColDataList=[
tcd("Group", 'group'),
tcd("Site", 'site'),
tcd("Build Name", 'buildname'),
tcd("Missing Status", 'status'),
],
)
#
# 'cf'
#
print("\nSearch for any builds with configure failures ...\n")
buildsWithConfigureFailuresLOD = \
CDQAR.getFilteredList(buildsSLOD, CDQAR.buildHasConfigureFailures)
buildsetReporter.reportSingleBuildset("Builds with Configure Failures", "cf",
buildsWithConfigureFailuresLOD,
buildsetGlobalPass=False,
buildsetColor=CDQAR.cdashColorFailed(),
)
#
# 'bf'
#
print("\nSearch for any builds with compilation (build) failures ...\n")
buildsWithBuildFailuresLOD = \
CDQAR.getFilteredList(buildsSLOD, CDQAR.buildHasBuildFailures)
buildsetReporter.reportSingleBuildset("Builds with Build Failures", "bf",
buildsWithBuildFailuresLOD,
buildsetGlobalPass=False,
buildsetColor=CDQAR.cdashColorFailed(),
)
#
# 'bu'
#
if inOptions.listUnexpectedBuilds:
buildsetReporter.reportSingleBuildset("Builds Unexpected", "bu",
buildsUnexpectedLOD,
buildsetGlobalPass=True,
buildsetColor=None,
)
#
# D.5) Analyaize and report the different sets of tests
#
#
# D.5.a) Final processing of lists of tests and splitting into the
# different tests sets to report
#
# Object to make it easy to process the different test sets
addTestHistoryStrategy = AddTestHistoryStrategy(inOptions, testHistoryCacheDir)
testsetReporter = CDQAR.SingleTestsetReporter(cdashReportData,
addTestHistoryStrategy=addTestHistoryStrategy)
# Special functor to look up missing expected build given a test dict
testsToMissingExpectedBuildsSLOD = \
CDQAR.createTestToBuildSearchableListOfDicts(missingExpectedBuildsLOD)
# Functor for matching an missing expected build given a test dict
testMatchesMissingExpectedBuildsFunctor = CDQAR.MatchDictKeysValuesFunctor(
testsToMissingExpectedBuildsSLOD)
# Get list of tests with issue trackers that are not in the list of
# nonpassing tests and don't match expected builds (and therefore will be
# included in the sets 'twip' and 'twim').
( testsWithIssueTrackersMatchingMissingExpectedBuildsLOD,
testsWithIssueTrackersPassingOrMissingLOD ) \
= \
CDQAR.splitListOnMatch( testsWithIssueTrackersGrossPassingOrMissingLOD,
testMatchesMissingExpectedBuildsFunctor )
print("\nNum tests with issue trackers passing or missing matching"+\
" posted builds = "+str(len(testsWithIssueTrackersPassingOrMissingLOD)))
print("\nTests with issue trackers missing that match"+\
" missing expected builds: num="+\
str(len(testsWithIssueTrackersMatchingMissingExpectedBuildsLOD)))
if len(testsWithIssueTrackersMatchingMissingExpectedBuildsLOD) > 0:
for testDict in testsWithIssueTrackersMatchingMissingExpectedBuildsLOD:
print(" "+sorted_dict_str(testDict))
print("\nNOTE: The above tests will NOT be listed in the set 'twim'!")
# Get test history for all of the tests with issue trackers that are not
# passing or missing. These will either be tests that are passing today
# (and therefore have history) or they will be tests that are missing.
# (But don't get test history or list out tests with issue trackers that
# match missing expected builds that did not submit any test data today.)
twipLOD = []
twimLOD = []
if testsWithIssueTrackersPassingOrMissingLOD:
print("\nGetting test history for tests with issue trackers"+\
" passing or missing: num="+str(len(testsWithIssueTrackersPassingOrMissingLOD)))
CDQAR.foreachTransform(
testsWithIssueTrackersPassingOrMissingLOD,
CDQAR.AddTestHistoryToTestDictFunctor(
inOptions.cdashSiteUrl,
inOptions.cdashProjectName,
inOptions.date,
inOptions.cdashProjectTestingDayStartTime,
inOptions.testHistoryDays,
testHistoryCacheDir,
useCachedCDashData=inOptions.useCachedCDashData,
alwaysUseCacheFileIfExists=True,
verbose=True,
printDetails=inOptions.printDetails,
requireMatchTestTopTestHistory=inOptions.requireTestHistoryMatchNonpassingTests,
)
)
# Split into lists for 'twip' and 'twim'
(twipLOD, twimLOD) = CDQAR.splitListOnMatch(
testsWithIssueTrackersPassingOrMissingLOD, CDQAR.isTestPassed )
print("\nNum tests with issue trackers Passed = "+str(len(twipLOD)))
print("Num tests with issue trackers Missing = "+str(len(twimLOD)))
#
# D.5.b) Report the different sets of tests
#
# NOTE: The order of these is chosen so those that require action of the
# person doing the triaging are sorted to the top.
#
testsetReporter.reportSingleTestset(
CDQAR.getStandardTestsetTypeInfo('twoif'),
len(twoifLOD), twoifLOD,
limitTableRows=inOptions.limitTableRows,
getTestHistory=True,
)
testsetReporter.reportSingleTestset(
CDQAR.getStandardTestsetTypeInfo('twoinr'),
len(twoinrLOD), twoinrLOD,
limitTableRows=inOptions.limitTableRows,
getTestHistory=True,
)
testsetReporter.reportSingleTestset(
CDQAR.getStandardTestsetTypeInfo('twip'),
len(twipLOD), twipLOD,
limitTableRows=None,
getTestHistory=False, # Already got it above!
)
testsetReporter.reportSingleTestset(
CDQAR.getStandardTestsetTypeInfo('twim', ""),
len(twimLOD), twimLOD,
limitTableRows=None,
getTestHistory=False, # Already got it above!
)
testsetReporter.reportSingleTestset(
CDQAR.getStandardTestsetTypeInfo('twif', ""),
len(twifLOD), twifLOD,
limitTableRows=None,
getTestHistory=True,
)
testsetReporter.reportSingleTestset(
CDQAR.getStandardTestsetTypeInfo('twinr', ""),
len(twinrLOD), twinrLOD,
limitTableRows=None,
getTestHistory=True,
)
#
# D.6) Write out list of unexpected builds to CSV file
#
if inOptions.writeUnexpectedBuildsToFile:
unexpectedBuildsCsvFileName = inOptions.writeUnexpectedBuildsToFile
print("\nWriting list of unexpected builds to file "\
+unexpectedBuildsCsvFileName+" ...")
CDQAR.writeExpectedBuildsListOfDictsToCsvFile(buildsUnexpectedLOD,
unexpectedBuildsCsvFileName)
#
# D.7) Write out list twiof to CSV file
#
if inOptions.writeFailingTestsWithoutIssueTrackersToFile:
twoifCsvFileName = inOptions.writeFailingTestsWithoutIssueTrackersToFile
print("\nWriting list of 'twiof' to file "+twoifCsvFileName+" ...")
CDQAR.writeTestsListOfDictsToCsvFile(twoifLOD, twoifCsvFileName)
#
# D.8) Write out test data to CSV file
#
if inOptions.writeTestDataToFile:
testDataFileName = inOptions.writeTestDataToFile
print("\nWriting out gathered test data to file "+testDataFileName+" ...")
testDataLOD = twipLOD + twimLOD + twifLOD + twinrLOD
CDQAR.foreachTransform(testDataLOD,
CDQAR.AddCDashTestingDayFunctor(inOptions.date))
# ToDo: Add the first inOptions.limitTableRows elements of twiofLOD and twoinrLOD?
CDQAR.pprintPythonDataToFile(testDataLOD, testDataFileName)
except Exception:
# Traceback!
print("")
sys.stdout.flush()
traceback.print_exc()
# Report the error
cdashReportData.htmlEmailBodyBottom += "\n<pre><code>\n"+\
traceback.format_exc()+"\n</code></pre>\n"
print("\nError, could not compute the analysis due to"+\
" above error so return failed!")
cdashReportData.globalPass = False
cdashReportData.summaryLineDataNumbersList.append("SCRIPT CRASHED")
#
# E) Put together final email summary line
#
summaryLine = CDQAR.getOverallCDashReportSummaryLine(cdashReportData,
inOptions.buildSetName, inOptions.date)
#
# F) Finish off HTML body guts and define overall HTML body style
#
# Finish off the top paragraph of the summary lines
cdashReportData.htmlEmailBodyTop += \
"</p>\n"
#
# G) Write HTML body file and/or send HTML email(s)
#
defaultPageStyle = CDQAR.getDefaultHtmlPageStyleStr()
if inOptions.writeEmailToFile:
print("\nWriting HTML file '"+inOptions.writeEmailToFile+"' ...")
fullCDashHtmlReportPageStr = CDQAR.getFullCDashHtmlReportPageStr(cdashReportData,
pageTitle=summaryLine, pageStyle=defaultPageStyle)
with open(inOptions.writeEmailToFile, 'w') as outFile:
outFile.write(fullCDashHtmlReportPageStr)
if inOptions.sendEmailTo:
htmlEmailBodyStr = CDQAR.getFullCDashHtmlReportPageStr(cdashReportData,
pageStyle=defaultPageStyle)
for emailAddress in inOptions.sendEmailTo.split(','):
emailAddress = emailAddress.strip()
print("\nSending email to '"+emailAddress+"' ...")
msg=CDQAR.createHtmlMimeEmail(
inOptions.emailFromAddress, emailAddress, summaryLine, "",
htmlEmailBodyStr, inOptions.emailWithoutSoftHyphens)
CDQAR.sendMineEmail(msg)
#
# H) Return final global pass/fail
#
print("\n"+summaryLine+"\n")
if cdashReportData.globalPass:
sys.exit(0)
else:
sys.exit(1)
| 39.211635 | 119 | 0.709521 |
import sys
import pprint
import datetime
from FindGeneralScriptSupport import *
from GeneralScriptSupport import *
import CDashQueryAnalyzeReport as CDQAR
import cdash_build_testing_date as CBTD
from gitdist import addOptionParserChoiceOption
usageHelp = r"""cdash_analyze_and_report.py [options]
This script takes in CDash URL information and other data as command-line
arguments and then analyzes it to look for missing expected builds, failed
tests, and various types of other failures and then reports the findings as an
HTML file written to disk and/or an HTML-formatted email sent to one or more
email addresses. (Other types of output can be produced as well in different
files.)
If all of the expected builds are found (and all of them have test results)
and there are no other failures found, then the script returns 0. Otherwise
the script returns non-zero. Therefore, this script can be used to drive
automated workflows by examining data on CDash.
"""
def injectCmndLineOptionsInParser(clp, gitoliteRootDefault=""):
clp.add_option(
"--date", dest="date", type="string", default='yesterday',
help="Date for the testing day <YYYY-MM-DD> or special values 'today'"+\
" or 'yesterday'. [default 'yesterday']" )
clp.add_option(
"--cdash-project-testing-day-start-time", dest="cdashProjectTestingDayStartTime",
type="string", default="00:00",
help="The CDash project testing day build star time in UTC in format '<hh>:<mm>'."+\
" [default = '00:00']" )
clp.add_option(
"--cdash-project-name", dest="cdashProjectName", type="string", default="",
help="CDash project name (e.g. 'Trilinos'). [REQUIRED]" )
clp.add_option(
"--build-set-name", dest="buildSetName", type="string", default="",
help="Name for the set of builds, (e.g. 'Trilinos Nightly Builds)."+\
" This used in the email summary line and in the HTML file body"+\
" to identify the set of builds and tests being examined."+\
" [REQUIRED]" )
clp.add_option(
"--cdash-site-url", dest="cdashSiteUrl", type="string", default="",
help="Base CDash site (e.g. 'https://testing.sandia.gov/cdash')."+\
" [REQUIRED]" )
clp.add_option(
"--cdash-builds-filters", dest="cdashBuildsFilters", type="string",
default="",
help="Partial URL fragment for index.php making of the filters for"+\
" the set of builds (e.g. 'filtercount=1&showfilters=1&field1=groupname&compare1=61&value1=ATDM')."+\
" [REQUIRED]" )
clp.add_option(
"--cdash-nonpassed-tests-filters", dest="cdashNonpassedTestsFilters", type="string",
default="",
help="Partial URL fragment for queryTests.php making of the filters for"+\
" the set of non-passing tests matching this set of builds (e.g."+\
" 'filtercombine=and&filtercount=1&showfilters=1&filtercombine=and&field1=groupname&compare1=61&value1=ATDM')."+\
" This set of filter fields may also filter out extra nonpassing tests"+\
" such for known random system failures to avoid flooding the output. In this"+\
" case, one should also set --require-test-history-match-nonpassing-tests=off."+\
" [REQUIRED]" )
clp.add_option(
"--expected-builds-file", dest="expectedBuildsFile", type="string",
default="",
help="Path to a CSV file that lists the expected builds. Each of these builds"+\
" must have unique 'site' and 'buildname' field pairs or an error will be"+\
" raised and the tool will abort. A list of files is also allowed that are"+\
" separated with ',' as <file1>,<file2>,... [default = '']" )
clp.add_option(
"--tests-with-issue-trackers-file", dest="testsWithIssueTrackersFile",
type="string", default="",
help="Path to CSV file that lists tests with issue trackers (and other data)."+\
" Each of these tests must have a unique 'site', 'buildName', and 'testname'"+\
" sets or an error will be raised and the tool will abort. [default = '']" )
addOptionParserChoiceOption(
"--filter-out-builds-and-tests-not-matching-expected-builds",
"filterOutBuildsAndTestsNotMatchingExpectedBuildsStr",
("on", "off"), 1,
"Filter out build and test data not matching input list of expected builds."+\
" If set to 'on', this will filter out build and test data downloaded"+\
" from CDash that does not match the list of expected builds provided in"+\
" --expected-builds-file=<csv-file>. This will also filter out any tests"+\
" with issue trackers listed in"+\
" --tests-with-issue-trackers-file=<csv-file>.",
clp )
cdashQueriesCacheDir_default=os.getcwd()
clp.add_option(
"--cdash-queries-cache-dir", dest="cdashQueriesCacheDir", type="string",
default=cdashQueriesCacheDir_default,
help="Cache CDash query data this directory." \
+" [default = '"+cdashQueriesCacheDir_default+"']" )
clp.add_option(
"--cdash-base-cache-files-prefix", dest="cdashBaseCacheFilesPrefix", type="string",
default="",
help="Prefix given to the base-level cache files outside of the test_history/"+\
" directory. This is to allow multiple invocations of this script to share"+\
" the same base cache directory and share the test_history/ in case there are"+\
" overrlapping sets of tests where the test history cache could be reused."+\
" [default is derived from the --build-set-name=<build_set_name> argument where"+\
" spaces and punctuation in <build_set_name> are replaced with '_']" )
addOptionParserChoiceOption(
"--use-cached-cdash-data", "useCachedCDashDataStr",
("on", "off"), 1,
"Use data downloaded from CDash already cached. Note that this only"+\
" impacts the reuse of base-level cache files and does not impact the usage"+\
" of test history cache in the <cacheDir>/test_history/ directory."+\
" If a test history file for a given testing day exists under the test_history/"+\
" directory it is used unconditionally.",
clp )
testHistoryDaysDefault= 30
clp.add_option(
"--limit-test-history-days", dest="testHistoryDays",
default=testHistoryDaysDefault, type="int",
help="Number of days to go back in history for each test."+\
" [default = '"+str(testHistoryDaysDefault)+"']" )
limitTableRows = 10
clp.add_option(
"--limit-table-rows", dest="limitTableRows", type="int",
default=limitTableRows,
help="Limit to the number of rows displayed in many of"+\
" the tables. This impacts tables like 'twoif' and 'twoinr'"+\
" that could have thousands of entries for some projects."+\
" This limits the number of tests for which detailed test history"+\
" is downloaded from CDash and is therefore important to ensure the"+\
" tool does not take too long to execute. However, this does NOT"+\
" limit the number of rows in many other tables that should be bounded like"+\
" any of the tables related to the builds or the list of tests with"+\
" issue trackers. (The number of those should never be extremely high.)"+\
" [default '"+str(limitTableRows)+"']" )
addOptionParserChoiceOption(
"--require-test-history-match-nonpassing-tests",
"requireTestHistoryMatchNonpassingTestsStr",
("on", "off"), 0,
"Require that the status for each tracked test listed in the tests with issue"\
+" trackers CSV file match the status of that test returned from the test history"\
+" returned from CDash. In general, these should match up but these may not if extra"\
+" filter criteria has been added to the list on nonpassing tests in the"\
+" --cdash-nonpassed-tests-filters=<filters> set of filters (such as to filter out"\
+" a large number of random system failures). In this case, an error will be"\
+" returned by default and the script will crash. But this can be relaxed by"\
+" setting this to 'off' which will result in these tracked tests being listed in"\
+" the 'twim' table but typically with status 'Failed'.",
clp )
addOptionParserChoiceOption(
"--print-details", "printDetailsStr",
("on", "off"), 1,
"Print more info like the CDash URLs for downloaded data and the cache"+\
" file names.",
clp )
addOptionParserChoiceOption(
"--list-unexpected-builds",
"listUnexpectedBuildsStr",
("on", "off"), 1,
"List unexpected builds downloaded from CDash (i.e. not matching an expected build)'.",
clp )
clp.add_option(
"--write-unexpected-builds-to-file",
dest="writeUnexpectedBuildsToFile", type="string", default="",
help="Write a CSV file with a list of unexpected builds 'bu'." \
+" This is to make it easy to add new entires to the file read by" \
+" the option --expected-builds-file=<csv-file>. [default = '']" )
clp.add_option(
"--write-failing-tests-without-issue-trackers-to-file",
dest="writeFailingTestsWithoutIssueTrackersToFile", type="string", default="",
help="Write a CSV file with a list of tests with issue trackers failed 'twif'." \
+" This is to make it easy to add new entires to the file read by" \
+" the option --tests-with-issue-trackers-file=<csv-file>. [default = '']" )
clp.add_option(
"--write-test-data-to-file",
dest="writeTestDataToFile", type="string", default="",
help="Write pretty-printed Python list of dictionaries for tests" \
+" with issue trackers. This includes the history of the tests for" \
+" --limit-test-history-days=<days> of history. This contains all of the" \
+" information that appears in the generated summary tables for tests with" \
+" associated issue trackers. [default = '']" )
clp.add_option(
"--write-email-to-file", dest="writeEmailToFile", type="string", default="",
help="Write the body of the HTML email to this file. [default = '']" )
clp.add_option(
"--email-from-address=", dest="emailFromAddress", type="string", default="",
help="Address reported in the sent email. [default '']" )
clp.add_option(
"--send-email-to=", dest="sendEmailTo", type="string", default="",
help="Send email to 'address1, address2, ...'. [default '']" )
addOptionParserChoiceOption(
"--email-without-soft-hyphens",
"emailWithoutSoftHyphensStr",
("on", "off"), 1,
"Remove soft hyphens from emails.",
clp )
def validateAndConvertCmndLineOptions(inOptions):
if inOptions.date == "":
print("Error, can't have empty --date, must pass in --date=YYYY-MM-DD"+\
" or special values --date=today or --date=yesterday!")
sys.exit(1)
else:
dateTimeObj = CDQAR.convertInputDateArgToYYYYMMDD(
inOptions.cdashProjectTestingDayStartTime,
inOptions.date)
inOptions.date = CBTD.getDateStrFromDateTime(dateTimeObj)
# ToDo: Assert more of the options to make sure they are correct!
def setExtraCmndLineOptionsAfterParse(inOptions_inout):
setattr(inOptions_inout, 'filterOutBuildsAndTestsNotMatchingExpectedBuilds',
inOptions_inout.filterOutBuildsAndTestsNotMatchingExpectedBuildsStr == "on")
setattr(inOptions_inout, 'useCachedCDashData',
inOptions_inout.useCachedCDashDataStr == "on")
setattr(inOptions_inout, 'requireTestHistoryMatchNonpassingTests',
inOptions_inout.requireTestHistoryMatchNonpassingTestsStr == "on")
setattr(inOptions_inout, 'printDetails',
inOptions_inout.printDetailsStr == "on")
setattr(inOptions_inout, 'listUnexpectedBuilds',
inOptions_inout.listUnexpectedBuildsStr == "on")
if inOptions_inout.cdashBaseCacheFilesPrefix == "":
inOptions_inout.cdashBaseCacheFilesPrefix = \
CDQAR.getFileNameStrFromText(inOptions_inout.buildSetName)+"_"
setattr(inOptions_inout, 'emailWithoutSoftHyphens',
inOptions_inout.emailWithoutSoftHyphensStr == "on")
def getCmndLineOptions():
from optparse import OptionParser
clp = OptionParser(usage=usageHelp)
injectCmndLineOptionsInParser(clp)
(options, args) = clp.parse_args()
validateAndConvertCmndLineOptions(options)
setExtraCmndLineOptionsAfterParse(options)
return options
def fwdCmndLineOptions(inOptions, lt=""):
io = inOptions
cmndLineOpts = \
" --date='"+io.date+"'"+lt+\
" --cdash-project-testing-day-start-time='"+io.cdashProjectTestingDayStartTime+"'"+lt+\
" --cdash-project-name='"+io.cdashProjectName+"'"+lt+\
" --build-set-name='"+io.buildSetName+"'"+lt+\
" --cdash-site-url='"+io.cdashSiteUrl+"'"+lt+\
" --cdash-builds-filters='"+io.cdashBuildsFilters+"'"+lt+\
" --cdash-nonpassed-tests-filters='"+io.cdashNonpassedTestsFilters+"'"+lt+\
" --expected-builds-file='"+io.expectedBuildsFile+"'"+lt+\
" --tests-with-issue-trackers-file='"+io.testsWithIssueTrackersFile+"'"+lt+\
" --filter-out-builds-and-tests-not-matching-expected-builds='"+\
io.filterOutBuildsAndTestsNotMatchingExpectedBuildsStr+"'"+lt+\
" --cdash-queries-cache-dir='"+io.cdashQueriesCacheDir+"'"+lt+\
" --cdash-base-cache-files-prefix='"+io.cdashBaseCacheFilesPrefix+"'"+lt+\
" --use-cached-cdash-data='"+io.useCachedCDashDataStr+"'"+lt+\
" --limit-test-history-days='"+str(io.testHistoryDays)+"'"+lt+\
" --limit-table-rows='"+str(io.limitTableRows)+"'"+lt+\
" --require-test-history-match-nonpassing-tests='"+io.requireTestHistoryMatchNonpassingTestsStr+"'"+lt+\
" --print-details='"+io.printDetailsStr+"'"+lt+\
" --list-unexpected-builds='"+io.listUnexpectedBuildsStr+"'"+lt+\
" --write-unexpected-builds-to-fileo='"+io.writeUnexpectedBuildsToFile+"'"+lt+\
" --write-failing-tests-without-issue-trackers-to-file='"+io.writeFailingTestsWithoutIssueTrackersToFile+"'"+lt+\
" --write-test-data-to-file='"+io.writeTestDataToFile+"'"+lt+\
" --write-email-to-file='"+io.writeEmailToFile+"'"+lt+\
" --email-from-address='"+io.emailFromAddress+"'"+lt+\
" --send-email-to='"+io.sendEmailTo+"'"+lt+\
" --email-without-soft-hyphens='"+io.emailWithoutSoftHyphensStr+"'"+lt
return cmndLineOpts
def echoCmndLineOptions(inOptions):
print(fwdCmndLineOptions(inOptions, " \\\n"))
def echoCmndLine(inOptions):
print("")
print("**************************************************************************")
print("cdash_analyze_and_report.py \\")
echoCmndLineOptions(inOptions)
# Strategy class that can get test history for a list of tests and set them in
# the test dicts taking input from the cdash_analyze_and_report.py commandline
# arguments.
#
class AddTestHistoryStrategy(object):
def __init__(self, inOptions, testHistoryCacheDir):
self.inOptions = inOptions
self.testHistoryCacheDir = testHistoryCacheDir
def getTestHistory(self, testLOD):
sio = self.inOptions
CDQAR.foreachTransform(
testLOD,
CDQAR.AddTestHistoryToTestDictFunctor(
cdashUrl=sio.cdashSiteUrl,
projectName=sio.cdashProjectName,
date=sio.date,
testingDayStartTimeUtc=sio.cdashProjectTestingDayStartTime,
daysOfHistory=sio.testHistoryDays,
testCacheDir=self.testHistoryCacheDir,
useCachedCDashData=sio.useCachedCDashData,
alwaysUseCacheFileIfExists=True,
verbose=True,
printDetails=sio.printDetails,
requireMatchTestTopTestHistory=sio.requireTestHistoryMatchNonpassingTests,
)
)
#
# Run the script
#
if __name__ == '__main__':
#
# Get commandline options
#
inOptions = getCmndLineOptions()
echoCmndLine(inOptions)
cacheDirAndBaseFilePrefix = \
inOptions.cdashQueriesCacheDir+"/"+inOptions.cdashBaseCacheFilesPrefix
#
# A) Define common data, etc
#
tcd = CDQAR.TableColumnData
pp = pprint.PrettyPrinter(indent=2)
groupSiteBuildNameSortOrder = ['group', 'site', 'buildname']
#
# B) Sound off
#
print("***")
print("*** Query and analyze CDash results for "+inOptions.buildSetName+\
" for testing day "+inOptions.date)
print("***")
#
# C) Create beginning of email body (that does not require getting any data off CDash)
#
# Aggregation of vars that get updated in this main() body and by functions
# called.
cdashReportData = CDQAR.CDashReportData()
cdashReportData.htmlEmailBodyTop += \
"<h2>Build and Test results for "+inOptions.buildSetName \
+" on "+inOptions.date+"</h2>\n\n"
#
# D) Read data files, get data off of CDash, do analysis, and construct HTML
# body parts
#
try:
# Beginning of top full bulid and tests CDash links paragraph
cdashReportData.htmlEmailBodyTop += "<p>\n"
#
# D.1) Read data from input files, set up cache directories
#
# Assert this data is correct and abort if there is an error before we run
# expensive CDash queries!
#
# Get list of expected builds from input CSV file
expectedBuildsLOD = CDQAR.getExpectedBuildsListOfDictsFromCsvFileArg(
inOptions.expectedBuildsFile)
print("\nNum expected builds = "+str(len(expectedBuildsLOD)))
# Create a SearchableListOfDict object to help look up expected builds
# given a build dict by key/value pairs 'group', 'site', and 'buildname'
# (requires unique builds with these key/value pairs)
expectedBuildsSLOD = CDQAR.createSearchableListOfBuilds(expectedBuildsLOD)
# Create a SearchableListOfDicts that will look up an expected build given
# just a test dict fields ['site', 'buildName']. (The list of tests with
# issue trackers does not have 'group' since cdash/queryTests.php does not
# give the 'group' associated with each test. Also, note that we need
# this special SearchableListOfDicts since the Build Name key name
# different for a cdash/queryTests.php test dict 'buildName' and a
# cdash/index.php build dict 'buildname'.)
testsToExpectedBuildsSLOD = \
CDQAR.createTestToBuildSearchableListOfDicts(expectedBuildsLOD)
# ToDo: Put in try/except to print about error in duplicate rows in the
# list of expected builds.
# Get list of tests with issue trackers from the input CSV file
if inOptions.testsWithIssueTrackersFile:
fullTestsWithIssueTrackersLOD = CDQAR.getTestsWtihIssueTrackersListFromCsvFile(
inOptions.testsWithIssueTrackersFile)
else:
fullTestsWithIssueTrackersLOD = []
print("\nNum tests with issue trackers read from CSV file = "+\
str(len(fullTestsWithIssueTrackersLOD)))
if inOptions.filterOutBuildsAndTestsNotMatchingExpectedBuilds:
(testsWithIssueTrackersLOD, testsWithIssueTrackersNotExpectedLOD) = \
CDQAR.splitTestsOnMatchExpectedBuilds(fullTestsWithIssueTrackersLOD,
testsToExpectedBuildsSLOD)
print("Num tests with issue trackers matching expected builds = "+\
str(len(testsWithIssueTrackersLOD)))
else:
testsWithIssueTrackersLOD = fullTestsWithIssueTrackersLOD
print("Num tests with issue trackers = "+\
str(len(testsWithIssueTrackersLOD)))
# Get a SearchableListOfDicts for the tests with issue trackers to allow
# them to be looked up based on matching ['site', 'buildName', 'testname']
# key/value pairs.
testsWithIssueTrackersSLOD = \
CDQAR.createSearchableListOfTests(testsWithIssueTrackersLOD)
# ToDo: Put in try/except to print about error in duplicate rows in the
# list of tests with issue trackers.
# Get a functor that will return True if a passed-in test dict matches a
# test with an issue tracker for the test key/value pairs ['site',
# 'buildName', and 'testname'].
testsWithIssueTrackerMatchFunctor = \
CDQAR.MatchDictKeysValuesFunctor(testsWithIssueTrackersSLOD)
# Assert that the list of tests with issue trackers matches the list of
# expected builds
(allTestsMatch, errMsg) = CDQAR.doTestsWithIssueTrackersMatchExpectedBuilds(
testsWithIssueTrackersLOD, testsToExpectedBuildsSLOD)
if not allTestsMatch:
raise Exception(errMsg)
# Test history cache dir
testHistoryCacheDir = inOptions.cdashQueriesCacheDir+"/test_history"
if not os.path.exists(testHistoryCacheDir):
print("\nCreating new test cache directory '"+testHistoryCacheDir+"'")
os.mkdir(testHistoryCacheDir)
#
# D.2) Get top-level lists of build and nonpassing tests off CDash
#
#
# D.2.a) Get list of dicts of builds off cdash/index.phpp
#
cdashIndexBuildsBrowserUrl = CDQAR.getCDashIndexBrowserUrl(
inOptions.cdashSiteUrl, inOptions.cdashProjectName, inOptions.date,
inOptions.cdashBuildsFilters)
print("\nCDash builds browser URL:\n\n "+cdashIndexBuildsBrowserUrl+"\n")
cdashIndexBuildsQueryUrl = CDQAR.getCDashIndexQueryUrl(
inOptions.cdashSiteUrl,
inOptions.cdashProjectName,
inOptions.date,
inOptions.cdashBuildsFilters )
fullCDashIndexBuildsJsonCacheFile = \
cacheDirAndBaseFilePrefix+"fullCDashIndexBuilds.json"
fullBuildsLOD = CDQAR.downloadBuildsOffCDashAndFlatten(
cdashIndexBuildsQueryUrl,
fullCDashIndexBuildsJsonCacheFile,
inOptions.useCachedCDashData )
print("\nNum builds downloaded from CDash = "+str(len(fullBuildsLOD)))
(buildsExpectedLOD, buildsUnexpectedLOD) = \
CDQAR.splitTestsOnMatchExpectedBuilds(fullBuildsLOD, expectedBuildsSLOD)
if inOptions.filterOutBuildsAndTestsNotMatchingExpectedBuilds:
print("Num builds matching expected builds = "+str(len(buildsExpectedLOD)))
buildsLOD = buildsExpectedLOD
else:
buildsLOD = fullBuildsLOD
if inOptions.listUnexpectedBuilds:
print("Num builds unexpected = "+str(len(buildsUnexpectedLOD)))
print("Num builds = "+str(len(buildsLOD)))
# HTML line "Builds on CDash"
cdashReportData.htmlEmailBodyTop += \
"<a href=\""+cdashIndexBuildsBrowserUrl+"\">"+\
"Builds on CDash</a> (num/expected="+\
str(len(buildsLOD))+"/"+str(len(expectedBuildsLOD))+")<br>\n"
# Create a SearchableListOfDict object to help look up builds given a
# build dict by key/value pairs 'group', 'site', and 'buildname' (requires
# unique builds with these key/value pairs)
buildsSLOD = CDQAR.createSearchableListOfBuilds(buildsLOD)
# ToDo: Add try/except to report duplicate builds in case this raises an
# exception.
#
# D.2.b) Get list of dicts of all nonpassing tests off
# cdash/queryTests.php
#
cdashNonpassingTestsBrowserUrl = CDQAR.getCDashQueryTestsBrowserUrl(
inOptions.cdashSiteUrl, inOptions.cdashProjectName, inOptions.date,
inOptions.cdashNonpassedTestsFilters)
print("\nGetting list of nonpassing tests from CDash ...\n")
print("\nCDash nonpassing tests browser URL:\n\n"+\
" "+cdashNonpassingTestsBrowserUrl+"\n")
cdashNonpassingTestsQueryUrl = CDQAR.getCDashQueryTestsQueryUrl(
inOptions.cdashSiteUrl, inOptions.cdashProjectName, inOptions.date,
inOptions.cdashNonpassedTestsFilters)
cdashNonpassingTestsQueryJsonCacheFile = \
cacheDirAndBaseFilePrefix+"fullCDashNonpassingTests.json"
fullNonpassingTestsLOD = CDQAR.downloadTestsOffCDashQueryTestsAndFlatten(
cdashNonpassingTestsQueryUrl, cdashNonpassingTestsQueryJsonCacheFile,
inOptions.useCachedCDashData )
print("\nNum nonpassing tests direct from CDash query = "+\
str(len(fullNonpassingTestsLOD)))
if inOptions.filterOutBuildsAndTestsNotMatchingExpectedBuilds:
(nonpassingTestsLOD, nonpassingTestsNotExpectedLOD) = \
CDQAR.splitTestsOnMatchExpectedBuilds(fullNonpassingTestsLOD,
testsToExpectedBuildsSLOD)
print("Num nonpassing tests matching expected builds = "+\
str(len(nonpassingTestsLOD)))
else:
nonpassingTestsLOD = fullNonpassingTestsLOD
print("Num nonpassing tests = "+\
str(len(nonpassingTestsLOD)))
# HTML line "Nonpassing Tests on CDash"
cdashReportData.htmlEmailBodyTop += \
"<a href=\""+cdashNonpassingTestsBrowserUrl+"\">"+\
"Non-passing Tests on CDash</a> (num="+str(len(nonpassingTestsLOD))+")<br>\n"
# End of full build and test link paragraph and start the next paragraph
# for the summary of failures and other tables
cdashReportData.htmlEmailBodyTop += \
"</p>\n\n"+\
"<p>\n"
# Create a SearchableListOfDicts object for looking up a nonpassing test
# given the test dict fields 'site', 'buildName', and 'testname'.
nonpassingTestsSLOD = CDQAR.createSearchableListOfTests(
nonpassingTestsLOD, removeExactDuplicateElements=True,
checkDictsAreSame_in=CDQAR.checkCDashTestDictsAreSame )
# NOTE: Above we add the option to remove exact duplicate tests since
# cdash/queryTests.php can return duplicate tests (i.e. all test dict
# fields are the same except and has the same buildid but could have
# different testids!)
# ToDo: Add try/except for above code in order to report duplicate tests
# where the buildid (and other fields) not match.
print("Num nonpassing tests after removing duplicate tests = "+\
str(len(nonpassingTestsLOD)))
# Create a functor to to see if a test dict matches one of the nonpassing
# tests downloaded from cdash/queryTests.php.
nonpassingTestsMatchFunctor = \
CDQAR.MatchDictKeysValuesFunctor(nonpassingTestsSLOD)
#
# D.3) Partition the varous list of tests into different sets that will
# be displayed in different tables.
#
# Add issue tracker info for all nonpassing tests (including adding empty
# issue tracker fields for tests that don't have issue trackers)
CDQAR.foreachTransform( nonpassingTestsLOD,
CDQAR.AddIssueTrackerInfoToTestDictFunctor(testsWithIssueTrackersSLOD))
(nonpassingTestsWithIssueTrackersLOD,nonpassingTestsWithoutIssueTrackersLOD)=\
CDQAR.splitListOnMatch(nonpassingTestsLOD, testsWithIssueTrackerMatchFunctor)
print("Num nonpassing tests without issue trackers = "+\
str(len(nonpassingTestsWithoutIssueTrackersLOD)))
print("Num nonpassing tests with issue trackers = "+\
str(len(nonpassingTestsWithIssueTrackersLOD)))
(twoifLOD, twoinrLOD) = CDQAR.splitListOnMatch(
nonpassingTestsWithoutIssueTrackersLOD, CDQAR.isTestFailed)
print("Num nonpassing tests without issue trackers Failed = "+str(len(twoifLOD)))
print("Num nonpassing tests without issue trackers Not Run = "+str(len(twoinrLOD)))
(twifLOD, twinrLOD) = CDQAR.splitListOnMatch(
nonpassingTestsWithIssueTrackersLOD, CDQAR.isTestFailed)
print("Num nonpassing tests with issue trackers Failed = "+str(len(twifLOD)))
print("Num nonpassing tests with issue trackers Not Run = "+str(len(twinrLOD)))
testsWithIssueTrackersGrossPassingOrMissingLOD = CDQAR.getFilteredList(
testsWithIssueTrackersSLOD,
CDQAR.NotMatchFunctor(nonpassingTestsMatchFunctor) )
print("Num tests with issue trackers gross passing or missing = "+\
str(len(testsWithIssueTrackersGrossPassingOrMissingLOD)))
buildsetReporter = CDQAR.SingleBuildsetReporter(cdashReportData)
print("\nSearch for any missing expected builds ...\n")
missingExpectedBuildsLOD = CDQAR.getMissingExpectedBuildsList(
buildsSLOD, expectedBuildsLOD)
buildsetReporter.reportSingleBuildset("Builds Missing", "bm",
missingExpectedBuildsLOD,
buildsetGlobalPass=False,
buildsetColor=CDQAR.cdashColorFailed(),
buildsetColDataList=[
tcd("Group", 'group'),
tcd("Site", 'site'),
tcd("Build Name", 'buildname'),
tcd("Missing Status", 'status'),
],
)
print("\nSearch for any builds with configure failures ...\n")
buildsWithConfigureFailuresLOD = \
CDQAR.getFilteredList(buildsSLOD, CDQAR.buildHasConfigureFailures)
buildsetReporter.reportSingleBuildset("Builds with Configure Failures", "cf",
buildsWithConfigureFailuresLOD,
buildsetGlobalPass=False,
buildsetColor=CDQAR.cdashColorFailed(),
)
print("\nSearch for any builds with compilation (build) failures ...\n")
buildsWithBuildFailuresLOD = \
CDQAR.getFilteredList(buildsSLOD, CDQAR.buildHasBuildFailures)
buildsetReporter.reportSingleBuildset("Builds with Build Failures", "bf",
buildsWithBuildFailuresLOD,
buildsetGlobalPass=False,
buildsetColor=CDQAR.cdashColorFailed(),
)
if inOptions.listUnexpectedBuilds:
buildsetReporter.reportSingleBuildset("Builds Unexpected", "bu",
buildsUnexpectedLOD,
buildsetGlobalPass=True,
buildsetColor=None,
)
addTestHistoryStrategy = AddTestHistoryStrategy(inOptions, testHistoryCacheDir)
testsetReporter = CDQAR.SingleTestsetReporter(cdashReportData,
addTestHistoryStrategy=addTestHistoryStrategy)
testsToMissingExpectedBuildsSLOD = \
CDQAR.createTestToBuildSearchableListOfDicts(missingExpectedBuildsLOD)
testMatchesMissingExpectedBuildsFunctor = CDQAR.MatchDictKeysValuesFunctor(
testsToMissingExpectedBuildsSLOD)
# included in the sets 'twip' and 'twim').
( testsWithIssueTrackersMatchingMissingExpectedBuildsLOD,
testsWithIssueTrackersPassingOrMissingLOD ) \
= \
CDQAR.splitListOnMatch( testsWithIssueTrackersGrossPassingOrMissingLOD,
testMatchesMissingExpectedBuildsFunctor )
print("\nNum tests with issue trackers passing or missing matching"+\
" posted builds = "+str(len(testsWithIssueTrackersPassingOrMissingLOD)))
print("\nTests with issue trackers missing that match"+\
" missing expected builds: num="+\
str(len(testsWithIssueTrackersMatchingMissingExpectedBuildsLOD)))
if len(testsWithIssueTrackersMatchingMissingExpectedBuildsLOD) > 0:
for testDict in testsWithIssueTrackersMatchingMissingExpectedBuildsLOD:
print(" "+sorted_dict_str(testDict))
print("\nNOTE: The above tests will NOT be listed in the set 'twim'!")
# Get test history for all of the tests with issue trackers that are not
# passing or missing. These will either be tests that are passing today
# (and therefore have history) or they will be tests that are missing.
# (But don't get test history or list out tests with issue trackers that
twipLOD = []
twimLOD = []
if testsWithIssueTrackersPassingOrMissingLOD:
print("\nGetting test history for tests with issue trackers"+\
" passing or missing: num="+str(len(testsWithIssueTrackersPassingOrMissingLOD)))
CDQAR.foreachTransform(
testsWithIssueTrackersPassingOrMissingLOD,
CDQAR.AddTestHistoryToTestDictFunctor(
inOptions.cdashSiteUrl,
inOptions.cdashProjectName,
inOptions.date,
inOptions.cdashProjectTestingDayStartTime,
inOptions.testHistoryDays,
testHistoryCacheDir,
useCachedCDashData=inOptions.useCachedCDashData,
alwaysUseCacheFileIfExists=True,
verbose=True,
printDetails=inOptions.printDetails,
requireMatchTestTopTestHistory=inOptions.requireTestHistoryMatchNonpassingTests,
)
)
(twipLOD, twimLOD) = CDQAR.splitListOnMatch(
testsWithIssueTrackersPassingOrMissingLOD, CDQAR.isTestPassed )
print("\nNum tests with issue trackers Passed = "+str(len(twipLOD)))
print("Num tests with issue trackers Missing = "+str(len(twimLOD)))
testsetReporter.reportSingleTestset(
CDQAR.getStandardTestsetTypeInfo('twoif'),
len(twoifLOD), twoifLOD,
limitTableRows=inOptions.limitTableRows,
getTestHistory=True,
)
testsetReporter.reportSingleTestset(
CDQAR.getStandardTestsetTypeInfo('twoinr'),
len(twoinrLOD), twoinrLOD,
limitTableRows=inOptions.limitTableRows,
getTestHistory=True,
)
testsetReporter.reportSingleTestset(
CDQAR.getStandardTestsetTypeInfo('twip'),
len(twipLOD), twipLOD,
limitTableRows=None,
getTestHistory=False,
)
testsetReporter.reportSingleTestset(
CDQAR.getStandardTestsetTypeInfo('twim', ""),
len(twimLOD), twimLOD,
limitTableRows=None,
getTestHistory=False,
)
testsetReporter.reportSingleTestset(
CDQAR.getStandardTestsetTypeInfo('twif', ""),
len(twifLOD), twifLOD,
limitTableRows=None,
getTestHistory=True,
)
testsetReporter.reportSingleTestset(
CDQAR.getStandardTestsetTypeInfo('twinr', ""),
len(twinrLOD), twinrLOD,
limitTableRows=None,
getTestHistory=True,
)
if inOptions.writeUnexpectedBuildsToFile:
unexpectedBuildsCsvFileName = inOptions.writeUnexpectedBuildsToFile
print("\nWriting list of unexpected builds to file "\
+unexpectedBuildsCsvFileName+" ...")
CDQAR.writeExpectedBuildsListOfDictsToCsvFile(buildsUnexpectedLOD,
unexpectedBuildsCsvFileName)
if inOptions.writeFailingTestsWithoutIssueTrackersToFile:
twoifCsvFileName = inOptions.writeFailingTestsWithoutIssueTrackersToFile
print("\nWriting list of 'twiof' to file "+twoifCsvFileName+" ...")
CDQAR.writeTestsListOfDictsToCsvFile(twoifLOD, twoifCsvFileName)
if inOptions.writeTestDataToFile:
testDataFileName = inOptions.writeTestDataToFile
print("\nWriting out gathered test data to file "+testDataFileName+" ...")
testDataLOD = twipLOD + twimLOD + twifLOD + twinrLOD
CDQAR.foreachTransform(testDataLOD,
CDQAR.AddCDashTestingDayFunctor(inOptions.date))
CDQAR.pprintPythonDataToFile(testDataLOD, testDataFileName)
except Exception:
print("")
sys.stdout.flush()
traceback.print_exc()
cdashReportData.htmlEmailBodyBottom += "\n<pre><code>\n"+\
traceback.format_exc()+"\n</code></pre>\n"
print("\nError, could not compute the analysis due to"+\
" above error so return failed!")
cdashReportData.globalPass = False
cdashReportData.summaryLineDataNumbersList.append("SCRIPT CRASHED")
summaryLine = CDQAR.getOverallCDashReportSummaryLine(cdashReportData,
inOptions.buildSetName, inOptions.date)
cdashReportData.htmlEmailBodyTop += \
"</p>\n"
defaultPageStyle = CDQAR.getDefaultHtmlPageStyleStr()
if inOptions.writeEmailToFile:
print("\nWriting HTML file '"+inOptions.writeEmailToFile+"' ...")
fullCDashHtmlReportPageStr = CDQAR.getFullCDashHtmlReportPageStr(cdashReportData,
pageTitle=summaryLine, pageStyle=defaultPageStyle)
with open(inOptions.writeEmailToFile, 'w') as outFile:
outFile.write(fullCDashHtmlReportPageStr)
if inOptions.sendEmailTo:
htmlEmailBodyStr = CDQAR.getFullCDashHtmlReportPageStr(cdashReportData,
pageStyle=defaultPageStyle)
for emailAddress in inOptions.sendEmailTo.split(','):
emailAddress = emailAddress.strip()
print("\nSending email to '"+emailAddress+"' ...")
msg=CDQAR.createHtmlMimeEmail(
inOptions.emailFromAddress, emailAddress, summaryLine, "",
htmlEmailBodyStr, inOptions.emailWithoutSoftHyphens)
CDQAR.sendMineEmail(msg)
print("\n"+summaryLine+"\n")
if cdashReportData.globalPass:
sys.exit(0)
else:
sys.exit(1)
| true | true |
1c2e6992c079c51b2cb74c6f2314e9a5c7023d15 | 2,904 | py | Python | linkedin-automation/index.py | tusharnankani/Social-Scheduler | 24975ed280047946359ee29052ab315e701aa6c1 | [
"MIT"
] | 16 | 2020-08-10T11:35:30.000Z | 2022-02-15T20:38:19.000Z | linkedin-automation/index.py | tusharnankani/Social-Scheduler | 24975ed280047946359ee29052ab315e701aa6c1 | [
"MIT"
] | 73 | 2020-08-01T23:27:13.000Z | 2020-11-03T05:21:22.000Z | linkedin-automation/index.py | tusharnankani/Social-Scheduler | 24975ed280047946359ee29052ab315e701aa6c1 | [
"MIT"
] | 50 | 2020-08-10T14:14:51.000Z | 2021-12-18T08:33:39.000Z | import os,random,sys,time
#from urllib.parse import urlparse
from selenium import webdriver
from bs4 import BeautifulSoup
import requests
browser = webdriver.Chrome('./driver/chromedriver.exe')
browser.get('https://www.linkedin.com/uas/login')
file=open('./config.txt')
lines=file.readlines()
username=lines[0]
password=lines[1]
elementID = browser.find_element_by_id('username')
elementID.send_keys(username)
elementID =browser.find_element_by_id('password')
elementID.send_keys(password)
elementID.submit()
content=requests.get('https://www.linkedin.com/in/rohan-devaki')
soup = BeautifulSoup(content.text, 'html.parser')
visitingProfileID='/in/rohan-devaki'
fullLink='https://www.linkedin.com/'+ visitingProfileID
browser.get(fullLink)
visitedProfiles = []
profilesQueued=[]
def getNewProfileIDs(soup,profilesQueued):
profilesID=[]
pav= soup.find('section',{'class':'artdeco-card ember-view'})
all_links=pav.findAll('a',{'class':'pv-browsemap-section__member ember-view'})
for link in all_links:
userID=link.get('href')
if(userID not in profilesQueued) and (userID not in visitedProfiles):
profilesID.append(userID)
return profilesID
profilesQueued=getNewProfileIDs(BeautifulSoup(browser.page_source), profilesQueued)
while profilesQueued:
try:
visitingProfileID=profilesQueued.pop()
visitedProfiles.append(visitingProfileID)
fullLink='https://www.linkedin.com' + visitingProfileID
browser.get(fullLink)
browser.find_element_by_class_name('artdeco-button__text').click()
browser.find_element_by_class_name('mr1').click()
customMessage = "Hello,This is social-sheduler,We would like to connect with you"
elementID=browser.find_element_by_id('custom-message')
elementID.send_keys(customMessage)
browser.find_element_by_class_name('ml1').click()
#add the id to visitedUsersFile
with open('visitedUsers.txt','a') as visitedUsersFile:
visitedUsersFile.write(str(visitingProfileID)+ '\n')
visitedUsersFile.close()
#get noe profiles ID
soup=BeautifulSoup(browser.page_source)
try:
profilesQueued.extend(getNewProfileIDs(soup,profilesQueued))
except:
print('Continue')
#pause
time.sleep(random.uniform(5,15)) #otherwise,sleep to make sure that it is not automated process
if(len(visitedProfiles)%50==0):
print('Visited Profiles:',len(visitedProfiles))
if(len(profilesQueued)>10000):
with open('profilesQueued.txt','a') as visitedUsersFile:
visitedUsersFile.write(str(visitingProfileID)+'\n')
visitedUsersFile.close()
print('100,000 Done!!!')
break;
except:
print('error') | 33 | 103 | 0.681474 | import os,random,sys,time
from selenium import webdriver
from bs4 import BeautifulSoup
import requests
browser = webdriver.Chrome('./driver/chromedriver.exe')
browser.get('https://www.linkedin.com/uas/login')
file=open('./config.txt')
lines=file.readlines()
username=lines[0]
password=lines[1]
elementID = browser.find_element_by_id('username')
elementID.send_keys(username)
elementID =browser.find_element_by_id('password')
elementID.send_keys(password)
elementID.submit()
content=requests.get('https://www.linkedin.com/in/rohan-devaki')
soup = BeautifulSoup(content.text, 'html.parser')
visitingProfileID='/in/rohan-devaki'
fullLink='https://www.linkedin.com/'+ visitingProfileID
browser.get(fullLink)
visitedProfiles = []
profilesQueued=[]
def getNewProfileIDs(soup,profilesQueued):
profilesID=[]
pav= soup.find('section',{'class':'artdeco-card ember-view'})
all_links=pav.findAll('a',{'class':'pv-browsemap-section__member ember-view'})
for link in all_links:
userID=link.get('href')
if(userID not in profilesQueued) and (userID not in visitedProfiles):
profilesID.append(userID)
return profilesID
profilesQueued=getNewProfileIDs(BeautifulSoup(browser.page_source), profilesQueued)
while profilesQueued:
try:
visitingProfileID=profilesQueued.pop()
visitedProfiles.append(visitingProfileID)
fullLink='https://www.linkedin.com' + visitingProfileID
browser.get(fullLink)
browser.find_element_by_class_name('artdeco-button__text').click()
browser.find_element_by_class_name('mr1').click()
customMessage = "Hello,This is social-sheduler,We would like to connect with you"
elementID=browser.find_element_by_id('custom-message')
elementID.send_keys(customMessage)
browser.find_element_by_class_name('ml1').click()
with open('visitedUsers.txt','a') as visitedUsersFile:
visitedUsersFile.write(str(visitingProfileID)+ '\n')
visitedUsersFile.close()
soup=BeautifulSoup(browser.page_source)
try:
profilesQueued.extend(getNewProfileIDs(soup,profilesQueued))
except:
print('Continue')
time.sleep(random.uniform(5,15))
if(len(visitedProfiles)%50==0):
print('Visited Profiles:',len(visitedProfiles))
if(len(profilesQueued)>10000):
with open('profilesQueued.txt','a') as visitedUsersFile:
visitedUsersFile.write(str(visitingProfileID)+'\n')
visitedUsersFile.close()
print('100,000 Done!!!')
break;
except:
print('error') | true | true |
1c2e6a7ca5d9a4aed44dd6bb4ca4cb9a9faf31d0 | 204 | py | Python | Source_Code/Python/testing6.py | fenglwh/instruments | 7886158d1ed97fe6bfe372a55f4fca107e834311 | [
"MIT"
] | null | null | null | Source_Code/Python/testing6.py | fenglwh/instruments | 7886158d1ed97fe6bfe372a55f4fca107e834311 | [
"MIT"
] | 3 | 2018-09-21T00:57:21.000Z | 2018-09-21T01:49:40.000Z | Source_Code/Python/testing6.py | fenglwh/instruments | 7886158d1ed97fe6bfe372a55f4fca107e834311 | [
"MIT"
] | null | null | null | import visa
rs=visa.ResourceManager()
instrument=rs.open_resource("GPIB::20::INSTR")
print('init ok')
instrument.write('CONF:WLAN:SIGN1:CONN:CCODe:CCC?')
print(instrument.read())
instrument.write('*GTL') | 25.5 | 51 | 0.759804 | import visa
rs=visa.ResourceManager()
instrument=rs.open_resource("GPIB::20::INSTR")
print('init ok')
instrument.write('CONF:WLAN:SIGN1:CONN:CCODe:CCC?')
print(instrument.read())
instrument.write('*GTL') | true | true |
1c2e6d289f4ec58a738045f39a1e1dabf66fac88 | 1,614 | py | Python | tests/test_hashcrypto.py | janbrohl/hashcrypto | ba32a7f43992e25a4b199f7f427fc48f3f237353 | [
"BSD-3-Clause"
] | 1 | 2017-03-19T09:13:00.000Z | 2017-03-19T09:13:00.000Z | tests/test_hashcrypto.py | janbrohl/hashcrypto | ba32a7f43992e25a4b199f7f427fc48f3f237353 | [
"BSD-3-Clause"
] | 1 | 2018-05-12T10:36:53.000Z | 2018-05-12T10:36:53.000Z | tests/test_hashcrypto.py | janbrohl/hashcrypto | ba32a7f43992e25a4b199f7f427fc48f3f237353 | [
"BSD-3-Clause"
] | null | null | null | from __future__ import print_function, unicode_literals
import unittest
import hashcrypto
import io
def notrandom(n,start=0):
return bytearray(0xff&i for i in range(start,start+n))
class TestCipherModes(unittest.TestCase):
def setUp(self):
self.inbytes=notrandom(1000)
self.key=notrandom(20)
def roundtrip_stream(self,cls):
infile=io.BytesIO(self.inbytes)
cryptfile=io.BytesIO()
outfile=io.BytesIO()
crypt=cls(self.key)
crypt.encrypt_stream(infile,cryptfile)
cryptfile.seek(0)
crypt.decrypt_stream(cryptfile,outfile)
self.assertEqual(infile.getvalue(),outfile.getvalue())
def roundtrip_file(self,cls):
infile=io.BytesIO(self.inbytes)
cryptfile=io.BytesIO()
outfile=io.BytesIO()
crypt=cls(self.key)
crypt.encrypt_file(infile,cryptfile)
cryptfile.seek(0)
hashcrypto.decrypt_file(cryptfile,outfile,self.key)
self.assertEqual(infile.getvalue(),outfile.getvalue())
def test_CTR_roundtrip_stream(self):
self.roundtrip_stream(hashcrypto.CTR)
def test_CFB_roundtrip_stream(self):
self.roundtrip_stream(hashcrypto.CFB)
def test_OFB_roundtrip_stream(self):
self.roundtrip_stream(hashcrypto.OFB)
def test_CTR_roundtrip_file(self):
self.roundtrip_file(hashcrypto.CTR)
def test_CFB_roundtrip_file(self):
self.roundtrip_file(hashcrypto.CFB)
def test_OFB_roundtrip_file(self):
self.roundtrip_file(hashcrypto.OFB)
if __name__ == '__main__':
unittest.main()
| 28.821429 | 62 | 0.687113 | from __future__ import print_function, unicode_literals
import unittest
import hashcrypto
import io
def notrandom(n,start=0):
return bytearray(0xff&i for i in range(start,start+n))
class TestCipherModes(unittest.TestCase):
def setUp(self):
self.inbytes=notrandom(1000)
self.key=notrandom(20)
def roundtrip_stream(self,cls):
infile=io.BytesIO(self.inbytes)
cryptfile=io.BytesIO()
outfile=io.BytesIO()
crypt=cls(self.key)
crypt.encrypt_stream(infile,cryptfile)
cryptfile.seek(0)
crypt.decrypt_stream(cryptfile,outfile)
self.assertEqual(infile.getvalue(),outfile.getvalue())
def roundtrip_file(self,cls):
infile=io.BytesIO(self.inbytes)
cryptfile=io.BytesIO()
outfile=io.BytesIO()
crypt=cls(self.key)
crypt.encrypt_file(infile,cryptfile)
cryptfile.seek(0)
hashcrypto.decrypt_file(cryptfile,outfile,self.key)
self.assertEqual(infile.getvalue(),outfile.getvalue())
def test_CTR_roundtrip_stream(self):
self.roundtrip_stream(hashcrypto.CTR)
def test_CFB_roundtrip_stream(self):
self.roundtrip_stream(hashcrypto.CFB)
def test_OFB_roundtrip_stream(self):
self.roundtrip_stream(hashcrypto.OFB)
def test_CTR_roundtrip_file(self):
self.roundtrip_file(hashcrypto.CTR)
def test_CFB_roundtrip_file(self):
self.roundtrip_file(hashcrypto.CFB)
def test_OFB_roundtrip_file(self):
self.roundtrip_file(hashcrypto.OFB)
if __name__ == '__main__':
unittest.main()
| true | true |
1c2e6df6c8dac011078fe392b64fca0a921b7ab0 | 2,515 | py | Python | src/ukw_tools/extern/video_annotations.py | Maddonix/ukw_tools | faaef987d06b232a32745fb497ed705f73f07aa3 | [
"MIT"
] | null | null | null | src/ukw_tools/extern/video_annotations.py | Maddonix/ukw_tools | faaef987d06b232a32745fb497ed705f73f07aa3 | [
"MIT"
] | null | null | null | src/ukw_tools/extern/video_annotations.py | Maddonix/ukw_tools | faaef987d06b232a32745fb497ed705f73f07aa3 | [
"MIT"
] | null | null | null | from bson import ObjectId
from ..classes.video_segmentation import VideoSegmentation
def convert_extern_annotation(annotation):
# video_segmentation = {}
annotation_by_label = {}
label_annotation_index = {}
dates = [_.date for _ in annotation]
max_date = max(dates)
# create a dict with all labels and the corresponding annotation index
for i, _annotation in enumerate(annotation):
for value in _annotation.flanks:
if not value.name in label_annotation_index:
label_annotation_index[value.name] = []
label_annotation_index[value.name].append(i)
# select the most recent annotation for each label
for key in label_annotation_index.keys():
label_annotation_index[key] = list(set(label_annotation_index[key]))
indices = label_annotation_index[key]
selected_dates = [dates[i] for i in indices]
max_date_index = selected_dates.index(max(selected_dates))
selected_index = indices[max_date_index]
selected_annotation = annotation[selected_index]
annotation_by_label[key] = selected_annotation
# filter all flanks, so that only flanks of the corresponding label are in the dict entry
flanks = []
for key in annotation_by_label.keys():
_annotation = annotation_by_label[key]
annotator_id = _annotation.extern_annotator_id
date = _annotation.date
values = _annotation.flanks
values = [_ for _ in values if _.name == key]
values = [_.to_intern(
source = "video_web_annotation",
annotator_id = annotator_id,
date = date
) for _ in values]
flanks.extend(values)
flanks.sort(key=lambda x: x.start)
return flanks, max_date
def flanks_to_annotation_segments(flanks):
segments = {}
for flank in flanks:
name = flank.name
if name == "body":
continue
if not name in segments:
segments[name] = []
if flank.value == True:
segments[name].append([flank.start, flank.stop])
return segments
def extern_to_intern_video_annotation(examination_id: ObjectId, annotation):
flanks, max_date = convert_extern_annotation(annotation)
segments = flanks_to_annotation_segments(flanks)
segmentation_dict = {
"examination_id": examination_id,
"annotation_segments": segments
}
segmentation = VideoSegmentation(**segmentation_dict)
return segmentation | 35.928571 | 93 | 0.675149 | from bson import ObjectId
from ..classes.video_segmentation import VideoSegmentation
def convert_extern_annotation(annotation):
annotation_by_label = {}
label_annotation_index = {}
dates = [_.date for _ in annotation]
max_date = max(dates)
for i, _annotation in enumerate(annotation):
for value in _annotation.flanks:
if not value.name in label_annotation_index:
label_annotation_index[value.name] = []
label_annotation_index[value.name].append(i)
for key in label_annotation_index.keys():
label_annotation_index[key] = list(set(label_annotation_index[key]))
indices = label_annotation_index[key]
selected_dates = [dates[i] for i in indices]
max_date_index = selected_dates.index(max(selected_dates))
selected_index = indices[max_date_index]
selected_annotation = annotation[selected_index]
annotation_by_label[key] = selected_annotation
flanks = []
for key in annotation_by_label.keys():
_annotation = annotation_by_label[key]
annotator_id = _annotation.extern_annotator_id
date = _annotation.date
values = _annotation.flanks
values = [_ for _ in values if _.name == key]
values = [_.to_intern(
source = "video_web_annotation",
annotator_id = annotator_id,
date = date
) for _ in values]
flanks.extend(values)
flanks.sort(key=lambda x: x.start)
return flanks, max_date
def flanks_to_annotation_segments(flanks):
segments = {}
for flank in flanks:
name = flank.name
if name == "body":
continue
if not name in segments:
segments[name] = []
if flank.value == True:
segments[name].append([flank.start, flank.stop])
return segments
def extern_to_intern_video_annotation(examination_id: ObjectId, annotation):
flanks, max_date = convert_extern_annotation(annotation)
segments = flanks_to_annotation_segments(flanks)
segmentation_dict = {
"examination_id": examination_id,
"annotation_segments": segments
}
segmentation = VideoSegmentation(**segmentation_dict)
return segmentation | true | true |
1c2e6e24b71793733105f5765e661a2c5fcb9aa6 | 4,102 | py | Python | azure/mgmt/storage/v2015_06_15/operations/usage_operations.py | EnjoyLifeFund/py36pkgs | 0ac677fbbfa7b6d8c527fe2c759ba05117b07fd2 | [
"MIT",
"BSD-2-Clause",
"BSD-3-Clause"
] | 1 | 2022-01-25T22:52:58.000Z | 2022-01-25T22:52:58.000Z | azure/mgmt/storage/v2015_06_15/operations/usage_operations.py | EnjoyLifeFund/Debian_py36_packages | 1985d4c73fabd5f08f54b922e73a9306e09c77a5 | [
"BSD-3-Clause",
"BSD-2-Clause",
"MIT"
] | null | null | null | azure/mgmt/storage/v2015_06_15/operations/usage_operations.py | EnjoyLifeFund/Debian_py36_packages | 1985d4c73fabd5f08f54b922e73a9306e09c77a5 | [
"BSD-3-Clause",
"BSD-2-Clause",
"MIT"
] | null | null | null | # 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 objec model deserializer.
:ivar api_version: Client Api Version. Constant value: "2015-06-15".
"""
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self.api_version = "2015-06-15"
self.config = config
def list(
self, custom_headers=None, raw=False, **operation_config):
"""Lists the current usage count and the limit for the resources under the
subscription.
: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 :class:`Usage
<azure.mgmt.storage.v2015_06_15.models.Usage>`
:rtype: :class:`UsagePaged
<azure.mgmt.storage.v2015_06_15.models.UsagePaged>`
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
def internal_paging(next_link=None, raw=False):
if not next_link:
# Construct URL
url = '/subscriptions/{subscriptionId}/providers/Microsoft.Storage/usages'
path_format_arguments = {
'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['Content-Type'] = 'application/json; charset=utf-8'
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)
response = self._client.send(
request, header_parameters, **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
| 39.825243 | 144 | 0.626524 |
import uuid
from msrest.pipeline import ClientRawResponse
from msrestazure.azure_exceptions import CloudError
from .. import models
class UsageOperations(object):
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self.api_version = "2015-06-15"
self.config = config
def list(
self, custom_headers=None, raw=False, **operation_config):
def internal_paging(next_link=None, raw=False):
if not next_link:
url = '/subscriptions/{subscriptionId}/providers/Microsoft.Storage/usages'
path_format_arguments = {
'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['Content-Type'] = 'application/json; charset=utf-8'
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)
response = self._client.send(
request, header_parameters, **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
| true | true |
1c2e6e50911c13e2d434c53394dcaf827b8110e0 | 1,145 | py | Python | constant/DaemonConstant.py | handsomezhou/PyDemo | 47bf4a87caba6307ffad557bf7abcbd978604469 | [
"Apache-2.0"
] | null | null | null | constant/DaemonConstant.py | handsomezhou/PyDemo | 47bf4a87caba6307ffad557bf7abcbd978604469 | [
"Apache-2.0"
] | null | null | null | constant/DaemonConstant.py | handsomezhou/PyDemo | 47bf4a87caba6307ffad557bf7abcbd978604469 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
# @Time : 2021/5/25
# @Author : handsomezhou
from util import TimeUtil
PY_DEMO_DAEMON_CHECK_INTERVAL_TIME_SEC = int(15)
PY_DEMO_CHECK_INTERVAL_TIME_SEC = int(20)
#PyDemo心跳时间更新最小间隔时间秒
PY_DEMO_HEARTBEAT_TIME_UPDATE_MIN_INTERVAL_TIME_SEC=int(30)
#PyDemo心跳时间更新最小间隔时间毫秒
PY_DEMO_HEARTBEAT_TIME_UPDATE_MIN_INTERVAL_TIME_MS=TimeUtil.sec2ms(PY_DEMO_HEARTBEAT_TIME_UPDATE_MIN_INTERVAL_TIME_SEC)
#PyDemo心跳时间更新最大间隔时间秒
PY_DEMO_HEARTBEAT_TIME_UPDATE_MAX_INTERVAL_TIME_SEC=int(120)
#PyDemo心跳时间更新最大间隔时间毫秒
PY_DEMO_HEARTBEAT_TIME_UPDATE_MAX_INTERVAL_TIME_MS=TimeUtil.sec2ms(PY_DEMO_HEARTBEAT_TIME_UPDATE_MAX_INTERVAL_TIME_SEC)
#PyDemo守护进程心跳时间更新最小间隔时间秒
PY_DEMO_DAEMON_HEARTBEAT_TIME_UPDATE_MIN_INTERVAL_TIME_SEC=int(30)
#PyDemo守护进程心跳时间更新最小间隔时间毫秒
PY_DEMO_DAEMON_HEARTBEAT_TIME_UPDATE_MIN_INTERVAL_TIME_MS=TimeUtil.sec2ms(PY_DEMO_DAEMON_HEARTBEAT_TIME_UPDATE_MIN_INTERVAL_TIME_SEC)
#PyDemo守护进程心跳时间更新最大间隔时间秒
PY_DEMO_DAEMON_HEARTBEAT_TIME_UPDATE_MAX_INTERVAL_TIME_SEC=int(120)
#PyDemo守护进程心跳时间更新最大间隔时间毫秒
PY_DEMO_DAEMON_HEARTBEAT_TIME_UPDATE_MAX_INTERVAL_TIME_MS=TimeUtil.sec2ms(PY_DEMO_DAEMON_HEARTBEAT_TIME_UPDATE_MAX_INTERVAL_TIME_SEC)
| 38.166667 | 133 | 0.908297 |
from util import TimeUtil
PY_DEMO_DAEMON_CHECK_INTERVAL_TIME_SEC = int(15)
PY_DEMO_CHECK_INTERVAL_TIME_SEC = int(20)
PY_DEMO_HEARTBEAT_TIME_UPDATE_MIN_INTERVAL_TIME_SEC=int(30)
PY_DEMO_HEARTBEAT_TIME_UPDATE_MIN_INTERVAL_TIME_MS=TimeUtil.sec2ms(PY_DEMO_HEARTBEAT_TIME_UPDATE_MIN_INTERVAL_TIME_SEC)
PY_DEMO_HEARTBEAT_TIME_UPDATE_MAX_INTERVAL_TIME_SEC=int(120)
PY_DEMO_HEARTBEAT_TIME_UPDATE_MAX_INTERVAL_TIME_MS=TimeUtil.sec2ms(PY_DEMO_HEARTBEAT_TIME_UPDATE_MAX_INTERVAL_TIME_SEC)
PY_DEMO_DAEMON_HEARTBEAT_TIME_UPDATE_MIN_INTERVAL_TIME_SEC=int(30)
PY_DEMO_DAEMON_HEARTBEAT_TIME_UPDATE_MIN_INTERVAL_TIME_MS=TimeUtil.sec2ms(PY_DEMO_DAEMON_HEARTBEAT_TIME_UPDATE_MIN_INTERVAL_TIME_SEC)
PY_DEMO_DAEMON_HEARTBEAT_TIME_UPDATE_MAX_INTERVAL_TIME_SEC=int(120)
PY_DEMO_DAEMON_HEARTBEAT_TIME_UPDATE_MAX_INTERVAL_TIME_MS=TimeUtil.sec2ms(PY_DEMO_DAEMON_HEARTBEAT_TIME_UPDATE_MAX_INTERVAL_TIME_SEC)
| true | true |
1c2e6ebb189720cacb8e35400a05b9d29c27f0fd | 2,925 | py | Python | bin/fix_requests/fix_request_4208.py | PRIMAVERA-H2020/pre-proc | 0c47636cbe32a13a9544f3e5ce9f4c778dc55078 | [
"BSD-3-Clause"
] | null | null | null | bin/fix_requests/fix_request_4208.py | PRIMAVERA-H2020/pre-proc | 0c47636cbe32a13a9544f3e5ce9f4c778dc55078 | [
"BSD-3-Clause"
] | null | null | null | bin/fix_requests/fix_request_4208.py | PRIMAVERA-H2020/pre-proc | 0c47636cbe32a13a9544f3e5ce9f4c778dc55078 | [
"BSD-3-Clause"
] | null | null | null | #!/usr/bin/env python
"""
fix_request_4208.py
EC-Earth-Consortium.*.highresSST-present.r1i1p1f1.6hrPlev.wap4
Set the cell_methods "area: time: mean"
"""
import argparse
import logging.config
import sys
import django
django.setup()
from pre_proc_app.models import DataRequest, FileFix
__version__ = '0.1.0b1'
DEFAULT_LOG_LEVEL = logging.WARNING
DEFAULT_LOG_FORMAT = '%(levelname)s: %(message)s'
logger = logging.getLogger(__name__)
def parse_args():
"""
Parse command-line arguments
"""
parser = argparse.ArgumentParser(description='Add pre-processing rules.')
parser.add_argument('-l', '--log-level', help='set logging level to one '
'of debug, info, warn (the '
'default), or error')
parser.add_argument('--version', action='version',
version='%(prog)s {}'.format(__version__))
args = parser.parse_args()
return args
def main():
"""
Main entry point
"""
data_reqs = DataRequest.objects.filter(
institution_id__name='EC-Earth-Consortium',
experiment_id__name='highresSST-present',
variant_label='r1i1p1f1',
table_id='6hrPlev',
cmor_name='wap4'
)
fixes = [
FileFix.objects.get(name='CellMethodsAreaTimeMeanAdd')
]
# This next line could be done more quickly by:
# further_info_url_fix.datarequest_set.add(*data_reqs)
# but sqlite3 gives an error of:
# django.db.utils.OperationalError: too many SQL variables
for data_req in data_reqs:
for fix in fixes:
data_req.fixes.add(fix)
num_data_reqs = data_reqs.count()
for fix in fixes:
logger.debug('FileFix {} added to {} data requests.'.
format(fix.name, num_data_reqs))
if __name__ == "__main__":
cmd_args = parse_args()
# determine the log level
if cmd_args.log_level:
try:
log_level = getattr(logging, cmd_args.log_level.upper())
except AttributeError:
logger.setLevel(logging.WARNING)
logger.error('log-level must be one of: debug, info, warn or error')
sys.exit(1)
else:
log_level = DEFAULT_LOG_LEVEL
# configure the logger
logging.config.dictConfig({
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': DEFAULT_LOG_FORMAT,
},
},
'handlers': {
'default': {
'level': log_level,
'class': 'logging.StreamHandler',
'formatter': 'standard'
},
},
'loggers': {
'': {
'handlers': ['default'],
'level': log_level,
'propagate': True
}
}
})
# run the code
main()
| 25.884956 | 80 | 0.571282 |
import argparse
import logging.config
import sys
import django
django.setup()
from pre_proc_app.models import DataRequest, FileFix
__version__ = '0.1.0b1'
DEFAULT_LOG_LEVEL = logging.WARNING
DEFAULT_LOG_FORMAT = '%(levelname)s: %(message)s'
logger = logging.getLogger(__name__)
def parse_args():
parser = argparse.ArgumentParser(description='Add pre-processing rules.')
parser.add_argument('-l', '--log-level', help='set logging level to one '
'of debug, info, warn (the '
'default), or error')
parser.add_argument('--version', action='version',
version='%(prog)s {}'.format(__version__))
args = parser.parse_args()
return args
def main():
data_reqs = DataRequest.objects.filter(
institution_id__name='EC-Earth-Consortium',
experiment_id__name='highresSST-present',
variant_label='r1i1p1f1',
table_id='6hrPlev',
cmor_name='wap4'
)
fixes = [
FileFix.objects.get(name='CellMethodsAreaTimeMeanAdd')
]
for data_req in data_reqs:
for fix in fixes:
data_req.fixes.add(fix)
num_data_reqs = data_reqs.count()
for fix in fixes:
logger.debug('FileFix {} added to {} data requests.'.
format(fix.name, num_data_reqs))
if __name__ == "__main__":
cmd_args = parse_args()
if cmd_args.log_level:
try:
log_level = getattr(logging, cmd_args.log_level.upper())
except AttributeError:
logger.setLevel(logging.WARNING)
logger.error('log-level must be one of: debug, info, warn or error')
sys.exit(1)
else:
log_level = DEFAULT_LOG_LEVEL
logging.config.dictConfig({
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': DEFAULT_LOG_FORMAT,
},
},
'handlers': {
'default': {
'level': log_level,
'class': 'logging.StreamHandler',
'formatter': 'standard'
},
},
'loggers': {
'': {
'handlers': ['default'],
'level': log_level,
'propagate': True
}
}
})
main()
| true | true |
1c2e6f90232b3e315ce68699f89badcb1998a267 | 4,622 | py | Python | wagtail/admin/menu.py | wlcrs/wagtail | 8afbc6c3eccef9eb0f09ed56c54cd36779451882 | [
"BSD-3-Clause"
] | 3 | 2019-05-14T13:43:08.000Z | 2021-11-09T11:27:18.000Z | wagtail/admin/menu.py | wlcrs/wagtail | 8afbc6c3eccef9eb0f09ed56c54cd36779451882 | [
"BSD-3-Clause"
] | 4 | 2021-03-19T00:33:36.000Z | 2022-03-11T23:47:17.000Z | wagtail/admin/menu.py | wlcrs/wagtail | 8afbc6c3eccef9eb0f09ed56c54cd36779451882 | [
"BSD-3-Clause"
] | 1 | 2021-08-13T15:38:43.000Z | 2021-08-13T15:38:43.000Z | from django.forms import Media, MediaDefiningClass
from django.forms.utils import flatatt
from django.template.loader import render_to_string
from django.templatetags.static import static
from django.utils.safestring import mark_safe
from django.utils.text import slugify
from wagtail.core import hooks
class MenuItem(metaclass=MediaDefiningClass):
template = 'wagtailadmin/shared/menu_item.html'
def __init__(self, label, url, name=None, classnames='', attrs=None, order=1000):
self.label = label
self.url = url
self.classnames = classnames
self.name = (name or slugify(str(label)))
self.order = order
if attrs:
self.attr_string = flatatt(attrs)
else:
self.attr_string = ""
def is_shown(self, request):
"""
Whether this menu item should be shown for the given request; permission
checks etc should go here. By default, menu items are shown all the time
"""
return True
def is_active(self, request):
return request.path.startswith(str(self.url))
def get_context(self, request):
"""Defines context for the template, overridable to use more data"""
return {
'name': self.name,
'url': self.url,
'classnames': self.classnames,
'attr_string': self.attr_string,
'label': self.label,
'active': self.is_active(request)
}
def render_html(self, request):
context = self.get_context(request)
return render_to_string(self.template, context, request=request)
class Menu:
def __init__(self, register_hook_name, construct_hook_name=None):
self.register_hook_name = register_hook_name
self.construct_hook_name = construct_hook_name
# _registered_menu_items will be populated on first access to the
# registered_menu_items property. We can't populate it in __init__ because
# we can't rely on all hooks modules to have been imported at the point that
# we create the admin_menu and settings_menu instances
self._registered_menu_items = None
@property
def registered_menu_items(self):
if self._registered_menu_items is None:
self._registered_menu_items = [fn() for fn in hooks.get_hooks(self.register_hook_name)]
return self._registered_menu_items
def menu_items_for_request(self, request):
return [item for item in self.registered_menu_items if item.is_shown(request)]
def active_menu_items(self, request):
return [item for item in self.menu_items_for_request(request) if item.is_active(request)]
@property
def media(self):
media = Media()
for item in self.registered_menu_items:
media += item.media
return media
def render_html(self, request):
menu_items = self.menu_items_for_request(request)
# provide a hook for modifying the menu, if construct_hook_name has been set
if self.construct_hook_name:
for fn in hooks.get_hooks(self.construct_hook_name):
fn(request, menu_items)
rendered_menu_items = []
for item in sorted(menu_items, key=lambda i: i.order):
try:
rendered_menu_items.append(item.render_html(request))
except TypeError:
# fallback for older render_html methods that don't accept a request arg
rendered_menu_items.append(item.render_html(request))
return mark_safe(''.join(rendered_menu_items))
class SubmenuMenuItem(MenuItem):
template = 'wagtailadmin/shared/menu_submenu_item.html'
"""A MenuItem which wraps an inner Menu object"""
def __init__(self, label, menu, **kwargs):
self.menu = menu
super().__init__(label, '#', **kwargs)
@property
def media(self):
return Media(js=[static('wagtailadmin/js/submenu.js')]) + self.menu.media
def is_shown(self, request):
# show the submenu if one or more of its children is shown
return bool(self.menu.menu_items_for_request(request))
def is_active(self, request):
return bool(self.menu.active_menu_items(request))
def get_context(self, request):
context = super().get_context(request)
context['menu_html'] = self.menu.render_html(request)
context['request'] = request
return context
admin_menu = Menu(register_hook_name='register_admin_menu_item', construct_hook_name='construct_main_menu')
settings_menu = Menu(register_hook_name='register_settings_menu_item')
| 36.109375 | 107 | 0.676763 | from django.forms import Media, MediaDefiningClass
from django.forms.utils import flatatt
from django.template.loader import render_to_string
from django.templatetags.static import static
from django.utils.safestring import mark_safe
from django.utils.text import slugify
from wagtail.core import hooks
class MenuItem(metaclass=MediaDefiningClass):
template = 'wagtailadmin/shared/menu_item.html'
def __init__(self, label, url, name=None, classnames='', attrs=None, order=1000):
self.label = label
self.url = url
self.classnames = classnames
self.name = (name or slugify(str(label)))
self.order = order
if attrs:
self.attr_string = flatatt(attrs)
else:
self.attr_string = ""
def is_shown(self, request):
return True
def is_active(self, request):
return request.path.startswith(str(self.url))
def get_context(self, request):
return {
'name': self.name,
'url': self.url,
'classnames': self.classnames,
'attr_string': self.attr_string,
'label': self.label,
'active': self.is_active(request)
}
def render_html(self, request):
context = self.get_context(request)
return render_to_string(self.template, context, request=request)
class Menu:
def __init__(self, register_hook_name, construct_hook_name=None):
self.register_hook_name = register_hook_name
self.construct_hook_name = construct_hook_name
# we can't rely on all hooks modules to have been imported at the point that
self._registered_menu_items = None
@property
def registered_menu_items(self):
if self._registered_menu_items is None:
self._registered_menu_items = [fn() for fn in hooks.get_hooks(self.register_hook_name)]
return self._registered_menu_items
def menu_items_for_request(self, request):
return [item for item in self.registered_menu_items if item.is_shown(request)]
def active_menu_items(self, request):
return [item for item in self.menu_items_for_request(request) if item.is_active(request)]
@property
def media(self):
media = Media()
for item in self.registered_menu_items:
media += item.media
return media
def render_html(self, request):
menu_items = self.menu_items_for_request(request)
if self.construct_hook_name:
for fn in hooks.get_hooks(self.construct_hook_name):
fn(request, menu_items)
rendered_menu_items = []
for item in sorted(menu_items, key=lambda i: i.order):
try:
rendered_menu_items.append(item.render_html(request))
except TypeError:
rendered_menu_items.append(item.render_html(request))
return mark_safe(''.join(rendered_menu_items))
class SubmenuMenuItem(MenuItem):
template = 'wagtailadmin/shared/menu_submenu_item.html'
def __init__(self, label, menu, **kwargs):
self.menu = menu
super().__init__(label, '
@property
def media(self):
return Media(js=[static('wagtailadmin/js/submenu.js')]) + self.menu.media
def is_shown(self, request):
# show the submenu if one or more of its children is shown
return bool(self.menu.menu_items_for_request(request))
def is_active(self, request):
return bool(self.menu.active_menu_items(request))
def get_context(self, request):
context = super().get_context(request)
context['menu_html'] = self.menu.render_html(request)
context['request'] = request
return context
admin_menu = Menu(register_hook_name='register_admin_menu_item', construct_hook_name='construct_main_menu')
settings_menu = Menu(register_hook_name='register_settings_menu_item')
| true | true |
1c2e6fcef6dc4f8cf45a1ffb8f2bd2bb9f47c2d7 | 1,157 | py | Python | dashlib/mnb_makevote.py | chaeplin/dash-mnb | edf965f590de57c4b3ed5136dc46961f2673e41c | [
"MIT"
] | 18 | 2017-02-20T19:38:52.000Z | 2021-03-24T23:39:47.000Z | dashlib/mnb_makevote.py | chaeplin/dash-mnb | edf965f590de57c4b3ed5136dc46961f2673e41c | [
"MIT"
] | 3 | 2017-03-10T15:32:34.000Z | 2017-12-12T10:58:14.000Z | dashlib/mnb_makevote.py | chaeplin/dash-mnb | edf965f590de57c4b3ed5136dc46961f2673e41c | [
"MIT"
] | 5 | 2017-03-10T22:37:06.000Z | 2020-10-22T20:35:26.000Z | import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '.'))
import time
import random
from dash_utils import *
from mnb_misc import *
from mnb_signing import *
def make_vote(
alias,
proposal_hash,
vote,
mnconfig):
print('%s : %s : %s ' % (alias, vote, proposal_hash))
sig_time = int(time.time()) + random.randint(-1800, 1800)
collateral_txidtxidn = mnconfig['collateral_txidtxidn']
if vote == 'yes':
voteno = '1'
elif vote == 'no':
voteno = '2'
elif vote == 'abstain':
voteno = '3'
serialize_for_sig = collateral_txidtxidn + '|' \
+ proposal_hash + '|' \
+ '1' + '|' \
+ voteno + '|' \
+ str(sig_time)
sig = signmessage_ecdsa_no_encoding(
serialize_for_sig,
mnconfig['masternode_privkey'])
work = {
"alias": mnconfig['alias'],
"collateral_txid": mnconfig['collateral_txid'],
"collateral_txidn": mnconfig['collateral_txidn'],
"proposal_hash": proposal_hash,
"vote": vote,
"sig_time": sig_time,
"sig": sig
}
return work
| 21.830189 | 61 | 0.575627 | import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '.'))
import time
import random
from dash_utils import *
from mnb_misc import *
from mnb_signing import *
def make_vote(
alias,
proposal_hash,
vote,
mnconfig):
print('%s : %s : %s ' % (alias, vote, proposal_hash))
sig_time = int(time.time()) + random.randint(-1800, 1800)
collateral_txidtxidn = mnconfig['collateral_txidtxidn']
if vote == 'yes':
voteno = '1'
elif vote == 'no':
voteno = '2'
elif vote == 'abstain':
voteno = '3'
serialize_for_sig = collateral_txidtxidn + '|' \
+ proposal_hash + '|' \
+ '1' + '|' \
+ voteno + '|' \
+ str(sig_time)
sig = signmessage_ecdsa_no_encoding(
serialize_for_sig,
mnconfig['masternode_privkey'])
work = {
"alias": mnconfig['alias'],
"collateral_txid": mnconfig['collateral_txid'],
"collateral_txidn": mnconfig['collateral_txidn'],
"proposal_hash": proposal_hash,
"vote": vote,
"sig_time": sig_time,
"sig": sig
}
return work
| true | true |
1c2e711a531de4bb38415cef5b318c047f0e40ef | 539 | py | Python | cc_vary_header/records/mappings/__init__.py | equadon/cookiecutter-instance-vary-header | 6a774f6eceb5bdef07245433eae6702f4306d1ba | [
"MIT"
] | null | null | null | cc_vary_header/records/mappings/__init__.py | equadon/cookiecutter-instance-vary-header | 6a774f6eceb5bdef07245433eae6702f4306d1ba | [
"MIT"
] | null | null | null | cc_vary_header/records/mappings/__init__.py | equadon/cookiecutter-instance-vary-header | 6a774f6eceb5bdef07245433eae6702f4306d1ba | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
#
# Copyright (C) 2019 CERN.
#
# CC Vary Header is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Mappings.
Mappings define how records and their fields will be indexed in Elasticsearch.
The provided record-v1.0.0.json file is an example of how to index records
in Elasticsearch. You need to provide one mapping per major version of
Elasticsearch you want to support.
"""
from __future__ import absolute_import, print_function
| 31.705882 | 78 | 0.764378 |
from __future__ import absolute_import, print_function
| true | true |
1c2e717c8a47d6c7d51f81414765e9b73312c608 | 940 | py | Python | boa_test/example/demo/IteratorTest.py | mixbee/neo-boa | da7366c26c7b8e60afb9ac27439a1da37b0be355 | [
"MIT"
] | 4 | 2018-08-22T03:30:34.000Z | 2019-04-16T10:54:08.000Z | boa_test/example/demo/IteratorTest.py | mixbee/neo-boa | da7366c26c7b8e60afb9ac27439a1da37b0be355 | [
"MIT"
] | 3 | 2018-09-03T09:19:26.000Z | 2019-01-24T00:06:29.000Z | boa_test/example/demo/IteratorTest.py | mixbee/neo-boa | da7366c26c7b8e60afb9ac27439a1da37b0be355 | [
"MIT"
] | 12 | 2018-07-19T06:36:44.000Z | 2019-05-13T05:45:58.000Z | from boa.interop.Neo.Iterator import *
def Main(testNum):
items = {
'a': 1,
'c': 4,
'f': 13
}
vals = IterCreate(items)
if testNum == 1:
while IterNext(vals):
print("next!")
print("ok done")
return True
if testNum == 2:
count = 0
while next(vals):
count += 1
return count
if testNum == 3:
i = iter(items)
keys = []
while next(i):
keys.append(i.Key)
return keys
if testNum == 4:
i = iter(items)
values = []
while next(i):
values.append(i.Value)
return values
if testNum == 5:
count = 0
while vals.Next():
count += 1
return count
if testNum == 6:
keys = []
while vals.Keys.next():
keys.append(vals.Value)
return keys
return False
| 15.932203 | 38 | 0.446809 | from boa.interop.Neo.Iterator import *
def Main(testNum):
items = {
'a': 1,
'c': 4,
'f': 13
}
vals = IterCreate(items)
if testNum == 1:
while IterNext(vals):
print("next!")
print("ok done")
return True
if testNum == 2:
count = 0
while next(vals):
count += 1
return count
if testNum == 3:
i = iter(items)
keys = []
while next(i):
keys.append(i.Key)
return keys
if testNum == 4:
i = iter(items)
values = []
while next(i):
values.append(i.Value)
return values
if testNum == 5:
count = 0
while vals.Next():
count += 1
return count
if testNum == 6:
keys = []
while vals.Keys.next():
keys.append(vals.Value)
return keys
return False
| true | true |
1c2e74341ab2c5299f6ccdc750677bace94844cc | 874 | py | Python | InvenTree/stock/migrations/0057_stock_location_item_owner.py | carlos-riquelme/InvenTree | 724dd2a9c82e4c10e14bd6aba8f48553b183fef9 | [
"MIT"
] | 656 | 2017-03-29T22:06:14.000Z | 2022-03-30T11:23:52.000Z | InvenTree/stock/migrations/0057_stock_location_item_owner.py | carlos-riquelme/InvenTree | 724dd2a9c82e4c10e14bd6aba8f48553b183fef9 | [
"MIT"
] | 1,545 | 2017-04-10T23:26:04.000Z | 2022-03-31T18:32:10.000Z | InvenTree/stock/migrations/0057_stock_location_item_owner.py | fablabbcn/InvenTree | 1d7ea7716cc96c6ffd151c822b01cd1fb5dcfecd | [
"MIT"
] | 196 | 2017-03-28T03:06:21.000Z | 2022-03-28T11:53:29.000Z | # Generated by Django 3.0.7 on 2021-01-11 21:54
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('users', '0005_owner_model'),
('stock', '0056_stockitem_expiry_date'),
]
operations = [
migrations.AddField(
model_name='stockitem',
name='owner',
field=models.ForeignKey(blank=True, help_text='Select Owner', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='stock_items', to='users.Owner'),
),
migrations.AddField(
model_name='stocklocation',
name='owner',
field=models.ForeignKey(blank=True, help_text='Select Owner', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='stock_locations', to='users.Owner'),
),
]
| 33.615385 | 181 | 0.648741 |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('users', '0005_owner_model'),
('stock', '0056_stockitem_expiry_date'),
]
operations = [
migrations.AddField(
model_name='stockitem',
name='owner',
field=models.ForeignKey(blank=True, help_text='Select Owner', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='stock_items', to='users.Owner'),
),
migrations.AddField(
model_name='stocklocation',
name='owner',
field=models.ForeignKey(blank=True, help_text='Select Owner', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='stock_locations', to='users.Owner'),
),
]
| true | true |
1c2e79341d86580e2a9ea356f0068245887be687 | 7,871 | py | Python | tf2_gnn/data/jsonl_graph_dataset.py | dahburj/tf2-gnn | ac6247c44957b35a478de4bbe13c0c96e82f0ba1 | [
"MIT"
] | null | null | null | tf2_gnn/data/jsonl_graph_dataset.py | dahburj/tf2-gnn | ac6247c44957b35a478de4bbe13c0c96e82f0ba1 | [
"MIT"
] | null | null | null | tf2_gnn/data/jsonl_graph_dataset.py | dahburj/tf2-gnn | ac6247c44957b35a478de4bbe13c0c96e82f0ba1 | [
"MIT"
] | 1 | 2021-04-22T12:46:26.000Z | 2021-04-22T12:46:26.000Z | """General dataset class for datasets stored as JSONLines files."""
import logging
from typing import Any, Dict, Iterator, List, Optional, Tuple, Set
import numpy as np
from dpu_utils.utils import RichPath
from .graph_dataset import DataFold, GraphDataset, GraphSampleType, GraphSample
logger = logging.getLogger(__name__)
class JsonLGraphDataset(GraphDataset[GraphSampleType]):
"""
General class representing pre-split datasets in JSONLines format.
Concretely, this class expects the following:
* In the data directory, files "train.jsonl.gz", "valid.jsonl.gz" and
"test.jsonl.gz" are used to store the train/valid/test datasets.
* Each of the files is gzipped text file in which each line is a valid
JSON dictionary with a "graph" key, which in turn points to a
dictionary with keys
- "node_features" (list of numerical initial node labels)
- "adjacency_lists" (list of list of directed edge pairs)
"""
@classmethod
def get_default_hyperparameters(cls) -> Dict[str, Any]:
super_hypers = super().get_default_hyperparameters()
this_hypers = {
"num_fwd_edge_types": 3,
"add_self_loop_edges": True,
"tie_fwd_bkwd_edges": True,
}
super_hypers.update(this_hypers)
return super_hypers
def __init__(
self, params: Dict[str, Any], metadata: Optional[Dict[str, Any]] = None,
):
super().__init__(params, metadata=metadata)
self._params = params
self._num_fwd_edge_types = params["num_fwd_edge_types"]
if params["tie_fwd_bkwd_edges"]:
self._num_edge_types = self._num_fwd_edge_types
else:
self._num_edge_types = 2 * self._num_fwd_edge_types
self._num_edge_types += int(params["add_self_loop_edges"])
self._node_feature_shape: Optional[Tuple[int]] = None
self._loaded_data: Dict[DataFold, List[GraphSampleType]] = {}
@property
def num_edge_types(self) -> int:
return self._num_edge_types
@property
def node_feature_shape(self) -> Tuple:
"""Return the shape of the node features."""
if self._node_feature_shape is None:
some_data_fold = next(iter(self._loaded_data.values()))
self._node_feature_shape = (len(some_data_fold[0].node_features[0]),)
return self._node_feature_shape
def load_metadata(self, path: RichPath) -> None:
"""Load the metadata for a dataset (such as vocabularies, names of properties, ...)
from a path on disk.
Note: Implementors needing to act on metadata information before loading any actual data
should override this method.
"""
if self.metadata == {}:
metadata_path = path.join("metadata.pkl.gz")
if metadata_path.exists():
logger.info(f"Loading metadata from {metadata_path}")
self._metadata = metadata_path.read_by_file_suffix()
else:
logger.warning("Using metadata passed to constructor, not metadata stored with data.")
def load_data(self, path: RichPath, folds_to_load: Optional[Set[DataFold]] = None) -> None:
"""Load the data from disk."""
logger.info(f"Starting to load data from {path}.")
self.load_metadata(path)
# If we haven't defined what folds to load, load all:
if folds_to_load is None:
folds_to_load = {DataFold.TRAIN, DataFold.VALIDATION, DataFold.TEST}
if DataFold.TRAIN in folds_to_load:
self._loaded_data[DataFold.TRAIN] = self.__load_data(path.join("train.jsonl.gz"))
logger.debug("Done loading training data.")
if DataFold.VALIDATION in folds_to_load:
self._loaded_data[DataFold.VALIDATION] = self.__load_data(path.join("valid.jsonl.gz"))
logger.debug("Done loading validation data.")
if DataFold.TEST in folds_to_load:
self._loaded_data[DataFold.TEST] = self.__load_data(path.join("test.jsonl.gz"))
logger.debug("Done loading test data.")
def load_data_from_list(
self, datapoints: List[Dict[str, Any]], target_fold: DataFold = DataFold.TEST
):
if target_fold not in self._loaded_data:
self._loaded_data[target_fold] = []
for datapoint in datapoints:
self._loaded_data[target_fold].append(self._process_raw_datapoint(datapoint))
def __load_data(self, data_file: RichPath) -> List[GraphSampleType]:
return [
self._process_raw_datapoint(datapoint) for datapoint in data_file.read_by_file_suffix()
]
def _process_raw_datapoint(self, datapoint: Dict[str, Any]) -> GraphSampleType:
node_features = datapoint["graph"]["node_features"]
type_to_adj_list, type_to_num_incoming_edges = self._process_raw_adjacency_lists(
raw_adjacency_lists=datapoint["graph"]["adjacency_lists"],
num_nodes=len(node_features),
)
return GraphSample(
adjacency_lists=type_to_adj_list,
type_to_node_to_num_inedges=type_to_num_incoming_edges,
node_features=node_features,
)
def _process_raw_adjacency_lists(
self, raw_adjacency_lists: List[List[Tuple]], num_nodes: int
) -> Tuple[List, np.ndarray]:
type_to_adj_list = [
[] for _ in range(self._num_fwd_edge_types + int(self.params["add_self_loop_edges"]))
] # type: List[List[Tuple[int, int]]]
type_to_num_incoming_edges = np.zeros(shape=(self.num_edge_types, num_nodes))
for raw_edge_type, edges in enumerate(raw_adjacency_lists):
if self.params["add_self_loop_edges"]:
fwd_edge_type = raw_edge_type + 1 # 0 will be the self-loop type
else:
fwd_edge_type = raw_edge_type # Make edges start from 0
for src, dest in edges:
type_to_adj_list[fwd_edge_type].append((src, dest))
type_to_num_incoming_edges[fwd_edge_type, dest] += 1
if self.params["tie_fwd_bkwd_edges"]:
type_to_adj_list[fwd_edge_type].append((dest, src))
type_to_num_incoming_edges[fwd_edge_type, src] += 1
if self.params["add_self_loop_edges"]:
# Add self-loop edges (idx 0, which isn't used in the data):
for node in range(num_nodes):
type_to_num_incoming_edges[0, node] = 1
type_to_adj_list[0].append((node, node))
# Add backward edges as an additional edge type that goes backwards:
if not (self.params["tie_fwd_bkwd_edges"]):
# for (edge_type, adj_list) in enumerate(type_to_adj_list):
num_edge_types_in_adj_lists = len(type_to_adj_list)
for edge_type in range(num_edge_types_in_adj_lists):
adj_list = type_to_adj_list[edge_type]
# Don't add self loops again!
if edge_type == 0 and self.params["add_self_loop_edges"]:
continue
bkwd_edge_type = len(type_to_adj_list)
type_to_adj_list.append([(y, x) for (x, y) in adj_list])
for (x, y) in adj_list:
type_to_num_incoming_edges[bkwd_edge_type][y] += 1
# Convert the adjacency lists to numpy arrays.
type_to_adj_list = [
np.array(adj_list, dtype=np.int32)
if len(adj_list) > 0
else np.zeros(shape=(0, 2), dtype=np.int32)
for adj_list in type_to_adj_list
]
return type_to_adj_list, type_to_num_incoming_edges
def _graph_iterator(self, data_fold: DataFold) -> Iterator[GraphSampleType]:
if data_fold == DataFold.TRAIN:
np.random.shuffle(self._loaded_data[data_fold])
return iter(self._loaded_data[data_fold])
| 44.721591 | 99 | 0.650362 | import logging
from typing import Any, Dict, Iterator, List, Optional, Tuple, Set
import numpy as np
from dpu_utils.utils import RichPath
from .graph_dataset import DataFold, GraphDataset, GraphSampleType, GraphSample
logger = logging.getLogger(__name__)
class JsonLGraphDataset(GraphDataset[GraphSampleType]):
@classmethod
def get_default_hyperparameters(cls) -> Dict[str, Any]:
super_hypers = super().get_default_hyperparameters()
this_hypers = {
"num_fwd_edge_types": 3,
"add_self_loop_edges": True,
"tie_fwd_bkwd_edges": True,
}
super_hypers.update(this_hypers)
return super_hypers
def __init__(
self, params: Dict[str, Any], metadata: Optional[Dict[str, Any]] = None,
):
super().__init__(params, metadata=metadata)
self._params = params
self._num_fwd_edge_types = params["num_fwd_edge_types"]
if params["tie_fwd_bkwd_edges"]:
self._num_edge_types = self._num_fwd_edge_types
else:
self._num_edge_types = 2 * self._num_fwd_edge_types
self._num_edge_types += int(params["add_self_loop_edges"])
self._node_feature_shape: Optional[Tuple[int]] = None
self._loaded_data: Dict[DataFold, List[GraphSampleType]] = {}
@property
def num_edge_types(self) -> int:
return self._num_edge_types
@property
def node_feature_shape(self) -> Tuple:
if self._node_feature_shape is None:
some_data_fold = next(iter(self._loaded_data.values()))
self._node_feature_shape = (len(some_data_fold[0].node_features[0]),)
return self._node_feature_shape
def load_metadata(self, path: RichPath) -> None:
if self.metadata == {}:
metadata_path = path.join("metadata.pkl.gz")
if metadata_path.exists():
logger.info(f"Loading metadata from {metadata_path}")
self._metadata = metadata_path.read_by_file_suffix()
else:
logger.warning("Using metadata passed to constructor, not metadata stored with data.")
def load_data(self, path: RichPath, folds_to_load: Optional[Set[DataFold]] = None) -> None:
logger.info(f"Starting to load data from {path}.")
self.load_metadata(path)
if folds_to_load is None:
folds_to_load = {DataFold.TRAIN, DataFold.VALIDATION, DataFold.TEST}
if DataFold.TRAIN in folds_to_load:
self._loaded_data[DataFold.TRAIN] = self.__load_data(path.join("train.jsonl.gz"))
logger.debug("Done loading training data.")
if DataFold.VALIDATION in folds_to_load:
self._loaded_data[DataFold.VALIDATION] = self.__load_data(path.join("valid.jsonl.gz"))
logger.debug("Done loading validation data.")
if DataFold.TEST in folds_to_load:
self._loaded_data[DataFold.TEST] = self.__load_data(path.join("test.jsonl.gz"))
logger.debug("Done loading test data.")
def load_data_from_list(
self, datapoints: List[Dict[str, Any]], target_fold: DataFold = DataFold.TEST
):
if target_fold not in self._loaded_data:
self._loaded_data[target_fold] = []
for datapoint in datapoints:
self._loaded_data[target_fold].append(self._process_raw_datapoint(datapoint))
def __load_data(self, data_file: RichPath) -> List[GraphSampleType]:
return [
self._process_raw_datapoint(datapoint) for datapoint in data_file.read_by_file_suffix()
]
def _process_raw_datapoint(self, datapoint: Dict[str, Any]) -> GraphSampleType:
node_features = datapoint["graph"]["node_features"]
type_to_adj_list, type_to_num_incoming_edges = self._process_raw_adjacency_lists(
raw_adjacency_lists=datapoint["graph"]["adjacency_lists"],
num_nodes=len(node_features),
)
return GraphSample(
adjacency_lists=type_to_adj_list,
type_to_node_to_num_inedges=type_to_num_incoming_edges,
node_features=node_features,
)
def _process_raw_adjacency_lists(
self, raw_adjacency_lists: List[List[Tuple]], num_nodes: int
) -> Tuple[List, np.ndarray]:
type_to_adj_list = [
[] for _ in range(self._num_fwd_edge_types + int(self.params["add_self_loop_edges"]))
] # type: List[List[Tuple[int, int]]]
type_to_num_incoming_edges = np.zeros(shape=(self.num_edge_types, num_nodes))
for raw_edge_type, edges in enumerate(raw_adjacency_lists):
if self.params["add_self_loop_edges"]:
fwd_edge_type = raw_edge_type + 1 # 0 will be the self-loop type
else:
fwd_edge_type = raw_edge_type # Make edges start from 0
for src, dest in edges:
type_to_adj_list[fwd_edge_type].append((src, dest))
type_to_num_incoming_edges[fwd_edge_type, dest] += 1
if self.params["tie_fwd_bkwd_edges"]:
type_to_adj_list[fwd_edge_type].append((dest, src))
type_to_num_incoming_edges[fwd_edge_type, src] += 1
if self.params["add_self_loop_edges"]:
# Add self-loop edges (idx 0, which isn't used in the data):
for node in range(num_nodes):
type_to_num_incoming_edges[0, node] = 1
type_to_adj_list[0].append((node, node))
if not (self.params["tie_fwd_bkwd_edges"]):
num_edge_types_in_adj_lists = len(type_to_adj_list)
for edge_type in range(num_edge_types_in_adj_lists):
adj_list = type_to_adj_list[edge_type]
if edge_type == 0 and self.params["add_self_loop_edges"]:
continue
bkwd_edge_type = len(type_to_adj_list)
type_to_adj_list.append([(y, x) for (x, y) in adj_list])
for (x, y) in adj_list:
type_to_num_incoming_edges[bkwd_edge_type][y] += 1
# Convert the adjacency lists to numpy arrays.
type_to_adj_list = [
np.array(adj_list, dtype=np.int32)
if len(adj_list) > 0
else np.zeros(shape=(0, 2), dtype=np.int32)
for adj_list in type_to_adj_list
]
return type_to_adj_list, type_to_num_incoming_edges
def _graph_iterator(self, data_fold: DataFold) -> Iterator[GraphSampleType]:
if data_fold == DataFold.TRAIN:
np.random.shuffle(self._loaded_data[data_fold])
return iter(self._loaded_data[data_fold])
| true | true |
1c2e797e399706d5a8b5cbb79669143ef784f79c | 1,117 | py | Python | setup.py | ragnarok22/ptb-django-cookiecutter | 4a06df669052ec24fcca47c01c50bc20fc0a8561 | [
"BSD-3-Clause"
] | 18 | 2021-06-23T07:41:26.000Z | 2022-02-04T07:56:39.000Z | setup.py | ragnarok22/ptb-django-cookiecutter | 4a06df669052ec24fcca47c01c50bc20fc0a8561 | [
"BSD-3-Clause"
] | 5 | 2021-07-11T03:24:58.000Z | 2021-11-01T20:17:38.000Z | setup.py | ragnarok22/ptb-django-cookiecutter | 4a06df669052ec24fcca47c01c50bc20fc0a8561 | [
"BSD-3-Clause"
] | 7 | 2021-08-10T20:36:03.000Z | 2021-12-13T18:35:57.000Z | # !/usr/bin/env python
from distutils.core import setup
setup(
name='ptb-django-cookiecutter',
packages=[],
version='0.1.1',
description='A simple cookiecutter to create Python Telegram bot, wrapped with Django.',
author='Carlos Lugones',
license='MIT',
author_email='contact@lugodev.com',
url='https://github.com/lugodev/ptb-django-cookiecutter',
keywords=['cookiecutter', 'template', 'package', ],
python_requires='>=3.8',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development',
],
)
| 36.032258 | 92 | 0.617726 |
from distutils.core import setup
setup(
name='ptb-django-cookiecutter',
packages=[],
version='0.1.1',
description='A simple cookiecutter to create Python Telegram bot, wrapped with Django.',
author='Carlos Lugones',
license='MIT',
author_email='contact@lugodev.com',
url='https://github.com/lugodev/ptb-django-cookiecutter',
keywords=['cookiecutter', 'template', 'package', ],
python_requires='>=3.8',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development',
],
)
| true | true |
1c2e79ee0b9008d2c20846f2ec4ec284300d3e86 | 539 | py | Python | website2.0/website/urls.py | mrava87/EAGE_Hackatoon_2017 | 68fbe6922f191e6b15827e47b37f931eaaca3104 | [
"MIT"
] | 13 | 2017-06-17T17:49:40.000Z | 2021-07-30T17:20:24.000Z | website2.0/website/urls.py | mrava87/EAGE_Hackatoon_2017 | 68fbe6922f191e6b15827e47b37f931eaaca3104 | [
"MIT"
] | 1 | 2017-05-31T16:43:37.000Z | 2017-06-01T10:53:48.000Z | website2.0/website/urls.py | mrava87/EAGE_Hackatoon_2017 | 68fbe6922f191e6b15827e47b37f931eaaca3104 | [
"MIT"
] | 3 | 2017-05-31T16:37:59.000Z | 2017-10-04T16:19:13.000Z | from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'website.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^$', include('mainapp.urls')),
url(r'^upload-', include('mainapp.urls')),
url(r'^admin/', include(admin.site.urls)),
)
urlpatterns += patterns('',(
r'^media/(?P<path>.*)$',
'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}
),)
| 28.368421 | 52 | 0.627087 | from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
urlpatterns = patterns('',
url(r'^$', include('mainapp.urls')),
url(r'^upload-', include('mainapp.urls')),
url(r'^admin/', include(admin.site.urls)),
)
urlpatterns += patterns('',(
r'^media/(?P<path>.*)$',
'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}
),)
| true | true |
1c2e7a1c8137d6dc414e3592f39f7bf82cd596df | 3,409 | py | Python | settings.py | TheLortex/rust-mcts | 10d0700cef7df7059b7cbacc609d173580203fa9 | [
"MIT"
] | 3 | 2020-10-24T03:25:16.000Z | 2021-06-30T05:36:58.000Z | settings.py | TheLortex/rust-mcts | 10d0700cef7df7059b7cbacc609d173580203fa9 | [
"MIT"
] | null | null | null | settings.py | TheLortex/rust-mcts | 10d0700cef7df7059b7cbacc609d173580203fa9 | [
"MIT"
] | 1 | 2021-03-27T09:13:31.000Z | 2021-03-27T09:13:31.000Z |
def dir_name(config, method):
if config.game.kind == "Breakthrough":
return "{}-breakthrough-{}".format(method, config.game.size)
elif config.game.kind == "Gym":
return "{}-gym-{}".format(method, config.game.name)
else:
print("Unknown game in config file.")
exit(-1)
def get_board_shape(config):
if config.game.kind == "Breakthrough":
return (config.game.history, config.game.size, config.game.size, 3)
elif config.game.kind == "Gym":
if config.game.name == "Breakout-v0":
return (config.game.history, 96, 96, 3)
else:
print("Gym not implemented for this game.")
exit(-1)
else:
print("Unknown game in config file.")
exit(-1)
def get_action_shape(config):
if config.game.kind == "Breakthrough":
return (config.game.size, config.game.size, 3)
elif config.game.kind == "Gym":
if config.game.name == "Breakout-v0":
return (4,)
else:
print("Gym not implemented for this game.")
exit(-1)
else:
print("Unknown game in config file.")
exit(-1)
import numpy as np
# scalar to categorical transformation.
def value_to_support(v, support_size):
# invertible transformation
scaled = np.sign(v) * ((np.sqrt(np.abs(v)+1)-1)) + 0.001*v
# clamp to support
clamped = np.clip(scaled, -support_size, support_size)
v1 = np.floor(clamped)
p1 = 1 - (clamped - v1)
v2 = v1 + 1
p2 = 1 - p1
result = np.zeros(shape=(support_size*2+1,))
result[int(v1) + support_size] = p1
if int(v2) + support_size < support_size*2+1:
result[int(v2) + support_size] = p2
return result
from tensorflow.keras import losses
def mu_loss_unrolled_cce(config):
def loss(y_true, y_pred):
policy_loss = 0.
for i in range(config.mu.unroll_steps):
policy_loss += losses.categorical_crossentropy(
y_true[:, i], y_pred[:, i]) / config.mu.unroll_steps
return policy_loss
return loss
def get_support_shape(x):
return (x or 0)*2+1
"""
## GAME SETTINGS, make sure this is coherent with the generator and evaluator
GAME = "breakthrough"
if GAME == "breakthrough":
BT_K = 5
HISTORY_LENGTH = 2
BOARD_SHAPE = (HISTORY_LENGTH, BT_K, BT_K, 3)
ACTION_PLANES = 3
ACTION_SHAPE = (BT_K, BT_K, ACTION_PLANES)
HIDDEN_PLANES = 16
HIDDEN_SHAPE = (BT_K, BT_K, HIDDEN_PLANES)
SUPPORT_SIZE = 1
elif GAME == "atari":
HISTORY_LENGTH = 8
BOARD_SHAPE = (HISTORY_LENGTH, 96, 96, 3)
ACTION_PLANES = 4 # breakout
ACTION_SHAPE = (ACTION_PLANES, )
HIDDEN_PLANES = 16
HIDDEN_SHAPE = (6, 6, HIDDEN_PLANES)
SUPPORT_SIZE = 300
SUPPORT_SHAPE = 2*SUPPORT_SIZE+1
# MUZERO SPECIFIC
N_UNROLL_STEPS = 5
N_TD_STEPS = 300
DISCOUNT = 0.997
WEIGHT_DECAY = 1e-4
REPLAY_BUFFER_SIZE = 5000 # SAVE THE LAST 5k GAMES
EPOCH_SIZE = 5*REPLAY_BUFFER_SIZE
BATCH_SIZE = 512
N_EPOCH = 50000
SAVE_REPLAY_BUFFER_FREQ = 64 # backup replay buffer every _ games
CHECKPOINT_FREQ = 5*EPOCH_SIZE # save model
EVALUATION_FREQ = 5*EPOCH_SIZE # evaluate model
""" | 30.711712 | 119 | 0.592549 |
def dir_name(config, method):
if config.game.kind == "Breakthrough":
return "{}-breakthrough-{}".format(method, config.game.size)
elif config.game.kind == "Gym":
return "{}-gym-{}".format(method, config.game.name)
else:
print("Unknown game in config file.")
exit(-1)
def get_board_shape(config):
if config.game.kind == "Breakthrough":
return (config.game.history, config.game.size, config.game.size, 3)
elif config.game.kind == "Gym":
if config.game.name == "Breakout-v0":
return (config.game.history, 96, 96, 3)
else:
print("Gym not implemented for this game.")
exit(-1)
else:
print("Unknown game in config file.")
exit(-1)
def get_action_shape(config):
if config.game.kind == "Breakthrough":
return (config.game.size, config.game.size, 3)
elif config.game.kind == "Gym":
if config.game.name == "Breakout-v0":
return (4,)
else:
print("Gym not implemented for this game.")
exit(-1)
else:
print("Unknown game in config file.")
exit(-1)
import numpy as np
def value_to_support(v, support_size):
scaled = np.sign(v) * ((np.sqrt(np.abs(v)+1)-1)) + 0.001*v
clamped = np.clip(scaled, -support_size, support_size)
v1 = np.floor(clamped)
p1 = 1 - (clamped - v1)
v2 = v1 + 1
p2 = 1 - p1
result = np.zeros(shape=(support_size*2+1,))
result[int(v1) + support_size] = p1
if int(v2) + support_size < support_size*2+1:
result[int(v2) + support_size] = p2
return result
from tensorflow.keras import losses
def mu_loss_unrolled_cce(config):
def loss(y_true, y_pred):
policy_loss = 0.
for i in range(config.mu.unroll_steps):
policy_loss += losses.categorical_crossentropy(
y_true[:, i], y_pred[:, i]) / config.mu.unroll_steps
return policy_loss
return loss
def get_support_shape(x):
return (x or 0)*2+1 | true | true |
1c2e7aa04b523bbaa95397b7ab53e8cdc6334804 | 3,722 | py | Python | timm/scheduler/scheduler_factory.py | RobbieEarle/pytorch-image-models | a43fafef8ca62a6347832d71ade045ae86b8a96f | [
"Apache-2.0"
] | null | null | null | timm/scheduler/scheduler_factory.py | RobbieEarle/pytorch-image-models | a43fafef8ca62a6347832d71ade045ae86b8a96f | [
"Apache-2.0"
] | null | null | null | timm/scheduler/scheduler_factory.py | RobbieEarle/pytorch-image-models | a43fafef8ca62a6347832d71ade045ae86b8a96f | [
"Apache-2.0"
] | 1 | 2021-01-07T15:04:35.000Z | 2021-01-07T15:04:35.000Z | """ Scheduler Factory
Hacked together by / Copyright 2020 Ross Wightman
"""
from .cosine_lr import CosineLRScheduler
from .tanh_lr import TanhLRScheduler
from .step_lr import StepLRScheduler
from .plateau_lr import PlateauLRScheduler
from torch.optim.lr_scheduler import OneCycleLR
import math
def create_scheduler(args, optimizer, dataset_train):
num_epochs = args.epochs
if getattr(args, 'lr_noise', None) is not None:
lr_noise = getattr(args, 'lr_noise')
if isinstance(lr_noise, (list, tuple)):
noise_range = [n * num_epochs for n in lr_noise]
if len(noise_range) == 1:
noise_range = noise_range[0]
else:
noise_range = lr_noise * num_epochs
else:
noise_range = None
lr_scheduler = None
if args.sched == 'onecycle':
lr_scheduler = OneCycleLR(optimizer,
max_lr=args.lr,
epochs=num_epochs,
steps_per_epoch=int(math.floor(len(dataset_train) / args.batch_size)),
cycle_momentum=False
)
if args.sched == 'cosine':
lr_scheduler = CosineLRScheduler(
optimizer,
t_initial=num_epochs,
t_mul=getattr(args, 'lr_cycle_mul', 1.),
lr_min=args.min_lr,
decay_rate=args.decay_rate,
warmup_lr_init=args.warmup_lr,
warmup_t=args.warmup_epochs,
cycle_limit=getattr(args, 'lr_cycle_limit', 1),
t_in_epochs=True,
noise_range_t=noise_range,
noise_pct=getattr(args, 'lr_noise_pct', 0.67),
noise_std=getattr(args, 'lr_noise_std', 1.),
noise_seed=getattr(args, 'seed', 42),
)
num_epochs = lr_scheduler.get_cycle_length() + args.cooldown_epochs
elif args.sched == 'tanh':
lr_scheduler = TanhLRScheduler(
optimizer,
t_initial=num_epochs,
t_mul=getattr(args, 'lr_cycle_mul', 1.),
lr_min=args.min_lr,
warmup_lr_init=args.warmup_lr,
warmup_t=args.warmup_epochs,
cycle_limit=getattr(args, 'lr_cycle_limit', 1),
t_in_epochs=True,
noise_range_t=noise_range,
noise_pct=getattr(args, 'lr_noise_pct', 0.67),
noise_std=getattr(args, 'lr_noise_std', 1.),
noise_seed=getattr(args, 'seed', 42),
)
num_epochs = lr_scheduler.get_cycle_length() + args.cooldown_epochs
elif args.sched == 'step':
lr_scheduler = StepLRScheduler(
optimizer,
decay_t=args.decay_epochs,
decay_rate=args.decay_rate,
warmup_lr_init=args.warmup_lr,
warmup_t=args.warmup_epochs,
noise_range_t=noise_range,
noise_pct=getattr(args, 'lr_noise_pct', 0.67),
noise_std=getattr(args, 'lr_noise_std', 1.),
noise_seed=getattr(args, 'seed', 42),
)
elif args.sched == 'plateau':
mode = 'min' if 'loss' in getattr(args, 'eval_metric', '') else 'max'
lr_scheduler = PlateauLRScheduler(
optimizer,
decay_rate=args.decay_rate,
patience_t=args.patience_epochs,
lr_min=args.min_lr,
mode=mode,
warmup_lr_init=args.warmup_lr,
warmup_t=args.warmup_epochs,
cooldown_t=0,
noise_range_t=noise_range,
noise_pct=getattr(args, 'lr_noise_pct', 0.67),
noise_std=getattr(args, 'lr_noise_std', 1.),
noise_seed=getattr(args, 'seed', 42),
)
return lr_scheduler, num_epochs
| 37.59596 | 104 | 0.585975 | from .cosine_lr import CosineLRScheduler
from .tanh_lr import TanhLRScheduler
from .step_lr import StepLRScheduler
from .plateau_lr import PlateauLRScheduler
from torch.optim.lr_scheduler import OneCycleLR
import math
def create_scheduler(args, optimizer, dataset_train):
num_epochs = args.epochs
if getattr(args, 'lr_noise', None) is not None:
lr_noise = getattr(args, 'lr_noise')
if isinstance(lr_noise, (list, tuple)):
noise_range = [n * num_epochs for n in lr_noise]
if len(noise_range) == 1:
noise_range = noise_range[0]
else:
noise_range = lr_noise * num_epochs
else:
noise_range = None
lr_scheduler = None
if args.sched == 'onecycle':
lr_scheduler = OneCycleLR(optimizer,
max_lr=args.lr,
epochs=num_epochs,
steps_per_epoch=int(math.floor(len(dataset_train) / args.batch_size)),
cycle_momentum=False
)
if args.sched == 'cosine':
lr_scheduler = CosineLRScheduler(
optimizer,
t_initial=num_epochs,
t_mul=getattr(args, 'lr_cycle_mul', 1.),
lr_min=args.min_lr,
decay_rate=args.decay_rate,
warmup_lr_init=args.warmup_lr,
warmup_t=args.warmup_epochs,
cycle_limit=getattr(args, 'lr_cycle_limit', 1),
t_in_epochs=True,
noise_range_t=noise_range,
noise_pct=getattr(args, 'lr_noise_pct', 0.67),
noise_std=getattr(args, 'lr_noise_std', 1.),
noise_seed=getattr(args, 'seed', 42),
)
num_epochs = lr_scheduler.get_cycle_length() + args.cooldown_epochs
elif args.sched == 'tanh':
lr_scheduler = TanhLRScheduler(
optimizer,
t_initial=num_epochs,
t_mul=getattr(args, 'lr_cycle_mul', 1.),
lr_min=args.min_lr,
warmup_lr_init=args.warmup_lr,
warmup_t=args.warmup_epochs,
cycle_limit=getattr(args, 'lr_cycle_limit', 1),
t_in_epochs=True,
noise_range_t=noise_range,
noise_pct=getattr(args, 'lr_noise_pct', 0.67),
noise_std=getattr(args, 'lr_noise_std', 1.),
noise_seed=getattr(args, 'seed', 42),
)
num_epochs = lr_scheduler.get_cycle_length() + args.cooldown_epochs
elif args.sched == 'step':
lr_scheduler = StepLRScheduler(
optimizer,
decay_t=args.decay_epochs,
decay_rate=args.decay_rate,
warmup_lr_init=args.warmup_lr,
warmup_t=args.warmup_epochs,
noise_range_t=noise_range,
noise_pct=getattr(args, 'lr_noise_pct', 0.67),
noise_std=getattr(args, 'lr_noise_std', 1.),
noise_seed=getattr(args, 'seed', 42),
)
elif args.sched == 'plateau':
mode = 'min' if 'loss' in getattr(args, 'eval_metric', '') else 'max'
lr_scheduler = PlateauLRScheduler(
optimizer,
decay_rate=args.decay_rate,
patience_t=args.patience_epochs,
lr_min=args.min_lr,
mode=mode,
warmup_lr_init=args.warmup_lr,
warmup_t=args.warmup_epochs,
cooldown_t=0,
noise_range_t=noise_range,
noise_pct=getattr(args, 'lr_noise_pct', 0.67),
noise_std=getattr(args, 'lr_noise_std', 1.),
noise_seed=getattr(args, 'seed', 42),
)
return lr_scheduler, num_epochs
| true | true |
1c2e7ba7d4fe1255704b12f9560527ef0aa657fb | 2,139 | py | Python | aesara/compile/compilelock.py | hs2361/aesara | 16f98e4fd69db92e0c2cde9dd97a0d005235deea | [
"BSD-3-Clause"
] | null | null | null | aesara/compile/compilelock.py | hs2361/aesara | 16f98e4fd69db92e0c2cde9dd97a0d005235deea | [
"BSD-3-Clause"
] | null | null | null | aesara/compile/compilelock.py | hs2361/aesara | 16f98e4fd69db92e0c2cde9dd97a0d005235deea | [
"BSD-3-Clause"
] | null | null | null | """
Locking mechanism to ensure no two compilations occur simultaneously
in the same compilation directory (which can cause crashes).
"""
import os
import threading
import typing
from contextlib import contextmanager
import filelock
from aesara.configdefaults import config
__all__ = [
"force_unlock",
"lock_ctx",
]
class ThreadFileLocks(threading.local):
def __init__(self):
self._locks = {}
local_mem = ThreadFileLocks()
def force_unlock(lock_dir: os.PathLike):
"""Forces the release of the lock on a specific directory.
Parameters
----------
lock_dir : os.PathLike
Path to a directory that was locked with `lock_ctx`.
"""
fl = filelock.FileLock(os.path.join(lock_dir, ".lock"))
fl.release(force=True)
dir_key = f"{lock_dir}-{os.getpid()}"
if dir_key in local_mem._locks:
del local_mem._locks[dir_key]
@contextmanager
def lock_ctx(lock_dir: os.PathLike = None, *, timeout: typing.Optional[float] = -1):
"""Context manager that wraps around FileLock and SoftFileLock from filelock package.
Parameters
----------
lock_dir : str
A directory for which to acquire the lock.
Defaults to the config.compiledir.
timeout : float
Timeout in seconds for waiting in lock acquisition.
Defaults to config.compile__timeout.
"""
if lock_dir is None:
lock_dir = config.compiledir
if timeout == -1:
timeout = config.compile__timeout
elif not (timeout is None or timeout > 0):
raise ValueError(f"Timeout parameter must be None or positive. Got {timeout}.")
# locks are kept in a dictionary to account for changing compiledirs
dir_key = f"{lock_dir}-{os.getpid()}"
if dir_key not in local_mem._locks:
local_mem._locks[dir_key] = True
fl = filelock.FileLock(os.path.join(lock_dir, ".lock"))
fl.acquire(timeout=timeout)
try:
yield
finally:
if fl.is_locked:
fl.release()
if dir_key in local_mem._locks:
del local_mem._locks[dir_key]
else:
yield
| 25.771084 | 89 | 0.654511 | import os
import threading
import typing
from contextlib import contextmanager
import filelock
from aesara.configdefaults import config
__all__ = [
"force_unlock",
"lock_ctx",
]
class ThreadFileLocks(threading.local):
def __init__(self):
self._locks = {}
local_mem = ThreadFileLocks()
def force_unlock(lock_dir: os.PathLike):
fl = filelock.FileLock(os.path.join(lock_dir, ".lock"))
fl.release(force=True)
dir_key = f"{lock_dir}-{os.getpid()}"
if dir_key in local_mem._locks:
del local_mem._locks[dir_key]
@contextmanager
def lock_ctx(lock_dir: os.PathLike = None, *, timeout: typing.Optional[float] = -1):
if lock_dir is None:
lock_dir = config.compiledir
if timeout == -1:
timeout = config.compile__timeout
elif not (timeout is None or timeout > 0):
raise ValueError(f"Timeout parameter must be None or positive. Got {timeout}.")
dir_key = f"{lock_dir}-{os.getpid()}"
if dir_key not in local_mem._locks:
local_mem._locks[dir_key] = True
fl = filelock.FileLock(os.path.join(lock_dir, ".lock"))
fl.acquire(timeout=timeout)
try:
yield
finally:
if fl.is_locked:
fl.release()
if dir_key in local_mem._locks:
del local_mem._locks[dir_key]
else:
yield
| true | true |
1c2e7e382fe94223338339592e2ee6790d0d70e6 | 3,486 | py | Python | homeassistant/components/camera/verisure.py | adolfoeliazat/voidhomecontrol | 6d733253811c553912e46e24debec818b28b0688 | [
"Apache-2.0"
] | 1 | 2020-08-14T15:01:33.000Z | 2020-08-14T15:01:33.000Z | homeassistant/components/camera/verisure.py | adolfoeliazat/voidhomecontrol | 6d733253811c553912e46e24debec818b28b0688 | [
"Apache-2.0"
] | null | null | null | homeassistant/components/camera/verisure.py | adolfoeliazat/voidhomecontrol | 6d733253811c553912e46e24debec818b28b0688 | [
"Apache-2.0"
] | 1 | 2020-08-26T20:54:14.000Z | 2020-08-26T20:54:14.000Z | """
Camera that loads a picture from a local file.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/camera.verisure/
"""
import errno
import logging
import os
from homeassistant.components.camera import Camera
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
from homeassistant.components.verisure import HUB as hub
from homeassistant.components.verisure import CONF_SMARTCAM
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the Verisure Camera."""
if not int(hub.config.get(CONF_SMARTCAM, 1)):
return False
directory_path = hass.config.config_dir
if not os.access(directory_path, os.R_OK):
_LOGGER.error("file path %s is not readable", directory_path)
return False
hub.update_smartcam()
smartcams = []
smartcams.extend([
VerisureSmartcam(hass, value.deviceLabel, directory_path)
for value in hub.smartcam_status.values()])
add_devices(smartcams)
class VerisureSmartcam(Camera):
"""Representation of a Verisure camera."""
def __init__(self, hass, device_id, directory_path):
"""Initialize Verisure File Camera component."""
super().__init__()
self._device_id = device_id
self._directory_path = directory_path
self._image = None
self._image_id = None
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP,
self.delete_image)
def camera_image(self):
"""Return image response."""
self.check_imagelist()
if not self._image:
_LOGGER.debug("No image to display")
return
_LOGGER.debug("Trying to open %s", self._image)
with open(self._image, 'rb') as file:
return file.read()
def check_imagelist(self):
"""Check the contents of the image list."""
hub.update_smartcam_imagelist()
if (self._device_id not in hub.smartcam_dict or
not hub.smartcam_dict[self._device_id]):
return
images = hub.smartcam_dict[self._device_id]
new_image_id = images[0]
_LOGGER.debug("self._device_id=%s, self._images=%s, "
"self._new_image_id=%s", self._device_id,
images, new_image_id)
if (new_image_id == '-1' or
self._image_id == new_image_id):
_LOGGER.debug("The image is the same, or loading image_id")
return
_LOGGER.debug("Download new image %s", new_image_id)
hub.my_pages.smartcam.download_image(
self._device_id, new_image_id, self._directory_path)
_LOGGER.debug("Old image_id=%s", self._image_id)
self.delete_image(self)
self._image_id = new_image_id
self._image = os.path.join(
self._directory_path, '{}{}'.format(self._image_id, '.jpg'))
def delete_image(self, event):
"""Delete an old image."""
remove_image = os.path.join(
self._directory_path, '{}{}'.format(self._image_id, '.jpg'))
try:
os.remove(remove_image)
_LOGGER.debug("Deleting old image %s", remove_image)
except OSError as error:
if error.errno != errno.ENOENT:
raise
@property
def name(self):
"""Return the name of this camera."""
return hub.smartcam_status[self._device_id].location
| 35.212121 | 74 | 0.64257 | import errno
import logging
import os
from homeassistant.components.camera import Camera
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
from homeassistant.components.verisure import HUB as hub
from homeassistant.components.verisure import CONF_SMARTCAM
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_devices, discovery_info=None):
if not int(hub.config.get(CONF_SMARTCAM, 1)):
return False
directory_path = hass.config.config_dir
if not os.access(directory_path, os.R_OK):
_LOGGER.error("file path %s is not readable", directory_path)
return False
hub.update_smartcam()
smartcams = []
smartcams.extend([
VerisureSmartcam(hass, value.deviceLabel, directory_path)
for value in hub.smartcam_status.values()])
add_devices(smartcams)
class VerisureSmartcam(Camera):
def __init__(self, hass, device_id, directory_path):
super().__init__()
self._device_id = device_id
self._directory_path = directory_path
self._image = None
self._image_id = None
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP,
self.delete_image)
def camera_image(self):
self.check_imagelist()
if not self._image:
_LOGGER.debug("No image to display")
return
_LOGGER.debug("Trying to open %s", self._image)
with open(self._image, 'rb') as file:
return file.read()
def check_imagelist(self):
hub.update_smartcam_imagelist()
if (self._device_id not in hub.smartcam_dict or
not hub.smartcam_dict[self._device_id]):
return
images = hub.smartcam_dict[self._device_id]
new_image_id = images[0]
_LOGGER.debug("self._device_id=%s, self._images=%s, "
"self._new_image_id=%s", self._device_id,
images, new_image_id)
if (new_image_id == '-1' or
self._image_id == new_image_id):
_LOGGER.debug("The image is the same, or loading image_id")
return
_LOGGER.debug("Download new image %s", new_image_id)
hub.my_pages.smartcam.download_image(
self._device_id, new_image_id, self._directory_path)
_LOGGER.debug("Old image_id=%s", self._image_id)
self.delete_image(self)
self._image_id = new_image_id
self._image = os.path.join(
self._directory_path, '{}{}'.format(self._image_id, '.jpg'))
def delete_image(self, event):
remove_image = os.path.join(
self._directory_path, '{}{}'.format(self._image_id, '.jpg'))
try:
os.remove(remove_image)
_LOGGER.debug("Deleting old image %s", remove_image)
except OSError as error:
if error.errno != errno.ENOENT:
raise
@property
def name(self):
return hub.smartcam_status[self._device_id].location
| true | true |
1c2e7e3bd7241c6969ca5f5b6f23ddc6d82a0548 | 201 | py | Python | matplotlib/plot()/plot1.py | programmer1017/python | 3dce528be121ced032157c9d800b4770989889bf | [
"MIT"
] | null | null | null | matplotlib/plot()/plot1.py | programmer1017/python | 3dce528be121ced032157c9d800b4770989889bf | [
"MIT"
] | null | null | null | matplotlib/plot()/plot1.py | programmer1017/python | 3dce528be121ced032157c9d800b4770989889bf | [
"MIT"
] | null | null | null | import matplotlib.pyplot as plt
plt.plot([2, 3, 5, 10])
# plot: 점을 찍는다 .[2, 3, 4, 10]은 y좌표로 간주된다.
# 또한 여기서 x좌표는 따로 지정하지 않았기 때문에 자동으로 각각 [0, 1, 2, 3]으로 간주되어 그래프가 그려진다.
plt.show()
# show: 창에 그래프를 띄운다. | 22.333333 | 68 | 0.631841 | import matplotlib.pyplot as plt
plt.plot([2, 3, 5, 10])
plt.show()
| true | true |
1c2e7eccd1f9668a71a63ddb467c7d69dbc9acc0 | 2,447 | py | Python | src/git_portfolio/use_cases/git_use_case.py | admdev8/git-portfolio | 4269923bac2d31c9058b76bb6facfdadd4045603 | [
"MIT"
] | 1 | 2020-10-19T13:11:32.000Z | 2020-10-19T13:11:32.000Z | src/git_portfolio/use_cases/git_use_case.py | admdev8/git-portfolio | 4269923bac2d31c9058b76bb6facfdadd4045603 | [
"MIT"
] | 179 | 2020-12-15T06:37:58.000Z | 2022-03-31T08:06:51.000Z | src/git_portfolio/use_cases/git_use_case.py | admdev8/git-portfolio | 4269923bac2d31c9058b76bb6facfdadd4045603 | [
"MIT"
] | null | null | null | """Local git use case."""
import os
import pathlib
import subprocess # noqa: S404
from typing import List
from typing import Tuple
from typing import Union
import git_portfolio.response_objects as res
class GitUseCase:
"""Execution of git use case."""
def __init__(self) -> None:
"""Constructor."""
self.err_output = self._check_git_install()
@staticmethod
def _check_git_install() -> str:
try:
popen = subprocess.Popen( # noqa: S603, S607
"git", stdout=subprocess.DEVNULL, stderr=subprocess.PIPE
)
popen.communicate()
except FileNotFoundError:
return "This command requires Git executable installed and on system path."
return ""
def execute(
self, git_selected_repos: List[str], command: str, args: Tuple[str]
) -> Union[res.ResponseFailure, res.ResponseSuccess]:
"""Batch `git` command.
Args:
git_selected_repos: list of configured repo names.
command: supported: checkout.
args (Tuple[str]): command arguments.
Returns:
str: output.
str: error output.
"""
if self.err_output:
return res.ResponseFailure.build_system_error(self.err_output)
output = ""
cwd = pathlib.Path().absolute()
for repo_name in git_selected_repos:
folder_name = repo_name.split("/")[1]
output += f"{folder_name}: "
try:
popen = subprocess.Popen( # noqa: S603, S607
["git", command, *args],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=os.path.join(cwd, folder_name),
)
stdout, error = popen.communicate()
# case of commands that outputs nothing on success such as `git add .`
if not stdout and not error:
output += "success.\n"
else:
if stdout:
stdout_str = stdout.decode("utf-8")
output += f"{stdout_str}"
if error:
error_str = error.decode("utf-8")
output += f"{error_str}"
except FileNotFoundError as fnf_error:
output += f"{fnf_error}\n"
return res.ResponseSuccess(output)
| 33.986111 | 87 | 0.541479 | import os
import pathlib
import subprocess
from typing import List
from typing import Tuple
from typing import Union
import git_portfolio.response_objects as res
class GitUseCase:
def __init__(self) -> None:
self.err_output = self._check_git_install()
@staticmethod
def _check_git_install() -> str:
try:
popen = subprocess.Popen(
"git", stdout=subprocess.DEVNULL, stderr=subprocess.PIPE
)
popen.communicate()
except FileNotFoundError:
return "This command requires Git executable installed and on system path."
return ""
def execute(
self, git_selected_repos: List[str], command: str, args: Tuple[str]
) -> Union[res.ResponseFailure, res.ResponseSuccess]:
if self.err_output:
return res.ResponseFailure.build_system_error(self.err_output)
output = ""
cwd = pathlib.Path().absolute()
for repo_name in git_selected_repos:
folder_name = repo_name.split("/")[1]
output += f"{folder_name}: "
try:
popen = subprocess.Popen(
["git", command, *args],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=os.path.join(cwd, folder_name),
)
stdout, error = popen.communicate()
if not stdout and not error:
output += "success.\n"
else:
if stdout:
stdout_str = stdout.decode("utf-8")
output += f"{stdout_str}"
if error:
error_str = error.decode("utf-8")
output += f"{error_str}"
except FileNotFoundError as fnf_error:
output += f"{fnf_error}\n"
return res.ResponseSuccess(output)
| true | true |
1c2e7fe6679d6cec764138b6a3d8661cf7766095 | 2,645 | py | Python | UVa Online Judge/v3/397.py | mjenrungrot/algorithm | e0e8174eb133ba20931c2c7f5c67732e4cb2b703 | [
"MIT"
] | 1 | 2021-12-08T08:58:43.000Z | 2021-12-08T08:58:43.000Z | UVa Online Judge/v3/397.py | mjenrungrot/algorithm | e0e8174eb133ba20931c2c7f5c67732e4cb2b703 | [
"MIT"
] | null | null | null | UVa Online Judge/v3/397.py | mjenrungrot/algorithm | e0e8174eb133ba20931c2c7f5c67732e4cb2b703 | [
"MIT"
] | null | null | null | # =============================================================================
# Author: Teerapat Jenrungrot - https://github.com/mjenrungrot/
# FileName: 397.py
# Description: UVa Online Judge - 397
# =============================================================================
def parse_number(x, offset):
output = ""
curr = offset
while curr < len(x):
if x[curr] == " ":
curr += 1
continue
if len(output) == 0 and x[curr] in "-+":
output += x[curr]
curr += 1
elif x[curr].isdigit():
output += x[curr]
curr += 1
else:
break
return str(int(output)), curr
def parse_operand(x, offset):
output = ""
curr = offset
while curr < len(x):
if x[curr] == " ":
curr += 1
continue
output += x[curr]
curr += 1
break
return output, curr
newline = False
while True:
try:
line = input()
except EOFError:
break
if newline:
print("")
newline = True
eqs, var = line.split("=")
# Parsing
parsed_eqs = []
curr = 0
x, curr = parse_number(eqs, curr)
parsed_eqs.append(x)
while curr < len(eqs):
if eqs[curr] == " ":
curr += 1
continue
x, curr = parse_operand(eqs, curr)
parsed_eqs.append(x)
x, curr = parse_number(eqs, curr)
parsed_eqs.append(x)
# Run
while True:
print("{} = {}".format(" ".join(parsed_eqs), var))
if len(parsed_eqs) == 1:
break
# check * /
passed = False
for i, token in enumerate(parsed_eqs):
if token in "*/":
lhs = int(parsed_eqs[i - 1])
rhs = int(parsed_eqs[i + 1])
if token == "*":
val = str(lhs * rhs)
else:
val = str(lhs // rhs)
del parsed_eqs[i - 1 : i + 2]
parsed_eqs.insert(i - 1, val)
passed = True
break
if passed:
continue
# check + -
for i, token in enumerate(parsed_eqs):
if token in "+-":
lhs = int(parsed_eqs[i - 1])
rhs = int(parsed_eqs[i + 1])
if token == "+":
val = str(lhs + rhs)
else:
val = str(lhs - rhs)
del parsed_eqs[i - 1 : i + 2]
parsed_eqs.insert(i - 1, val)
passed = True
break
| 23.201754 | 79 | 0.404537 |
def parse_number(x, offset):
output = ""
curr = offset
while curr < len(x):
if x[curr] == " ":
curr += 1
continue
if len(output) == 0 and x[curr] in "-+":
output += x[curr]
curr += 1
elif x[curr].isdigit():
output += x[curr]
curr += 1
else:
break
return str(int(output)), curr
def parse_operand(x, offset):
output = ""
curr = offset
while curr < len(x):
if x[curr] == " ":
curr += 1
continue
output += x[curr]
curr += 1
break
return output, curr
newline = False
while True:
try:
line = input()
except EOFError:
break
if newline:
print("")
newline = True
eqs, var = line.split("=")
parsed_eqs = []
curr = 0
x, curr = parse_number(eqs, curr)
parsed_eqs.append(x)
while curr < len(eqs):
if eqs[curr] == " ":
curr += 1
continue
x, curr = parse_operand(eqs, curr)
parsed_eqs.append(x)
x, curr = parse_number(eqs, curr)
parsed_eqs.append(x)
while True:
print("{} = {}".format(" ".join(parsed_eqs), var))
if len(parsed_eqs) == 1:
break
passed = False
for i, token in enumerate(parsed_eqs):
if token in "*/":
lhs = int(parsed_eqs[i - 1])
rhs = int(parsed_eqs[i + 1])
if token == "*":
val = str(lhs * rhs)
else:
val = str(lhs // rhs)
del parsed_eqs[i - 1 : i + 2]
parsed_eqs.insert(i - 1, val)
passed = True
break
if passed:
continue
for i, token in enumerate(parsed_eqs):
if token in "+-":
lhs = int(parsed_eqs[i - 1])
rhs = int(parsed_eqs[i + 1])
if token == "+":
val = str(lhs + rhs)
else:
val = str(lhs - rhs)
del parsed_eqs[i - 1 : i + 2]
parsed_eqs.insert(i - 1, val)
passed = True
break
| true | true |
1c2e81898fee54dc6d2391d56188977c7058f6de | 873 | py | Python | String/AlgoExpert/Medium/10_minimum-characters-for-words.py | sounak95/100_days_of_code | 50fbf088ce6ab2137aa216a30e3b3f828b278a22 | [
"Apache-2.0"
] | null | null | null | String/AlgoExpert/Medium/10_minimum-characters-for-words.py | sounak95/100_days_of_code | 50fbf088ce6ab2137aa216a30e3b3f828b278a22 | [
"Apache-2.0"
] | null | null | null | String/AlgoExpert/Medium/10_minimum-characters-for-words.py | sounak95/100_days_of_code | 50fbf088ce6ab2137aa216a30e3b3f828b278a22 | [
"Apache-2.0"
] | null | null | null |
def countCharFreq(string):
charFreq={}
for ch in string:
if ch in charFreq:
charFreq[ch]+=1
else:
charFreq[ch]=1
return charFreq
def updateMaxFreq(charFreq, maxCharFreq):
for ch in charFreq:
if ch in maxCharFreq:
maxCharFreq[ch]= max(charFreq[ch], maxCharFreq[ch])
else:
maxCharFreq[ch]=charFreq[ch]
def convertDictToList(dict):
l1=[]
for ch in dict:
freq= dict[ch]
for _ in range(freq):
l1.append(ch)
return l1
def minimumCharactersForWords(words):
# Write your code here.
maxCharFreq={}
for word in words:
charFreq=countCharFreq(word)
updateMaxFreq(charFreq, maxCharFreq)
return convertDictToList(maxCharFreq)
print(minimumCharactersForWords(["this", "that", "did", "deed", "them!", "a"])) | 20.302326 | 79 | 0.60252 |
def countCharFreq(string):
charFreq={}
for ch in string:
if ch in charFreq:
charFreq[ch]+=1
else:
charFreq[ch]=1
return charFreq
def updateMaxFreq(charFreq, maxCharFreq):
for ch in charFreq:
if ch in maxCharFreq:
maxCharFreq[ch]= max(charFreq[ch], maxCharFreq[ch])
else:
maxCharFreq[ch]=charFreq[ch]
def convertDictToList(dict):
l1=[]
for ch in dict:
freq= dict[ch]
for _ in range(freq):
l1.append(ch)
return l1
def minimumCharactersForWords(words):
maxCharFreq={}
for word in words:
charFreq=countCharFreq(word)
updateMaxFreq(charFreq, maxCharFreq)
return convertDictToList(maxCharFreq)
print(minimumCharactersForWords(["this", "that", "did", "deed", "them!", "a"])) | true | true |
1c2e829f76a0ecd0a9354921fb8cf2b2cf7783c3 | 447 | py | Python | tools/python/boutiques/tests/test_pprint.py | jerdra/boutiques | f6ee252fd1332ec686dc76dc12e52a0d69c685c3 | [
"MIT"
] | null | null | null | tools/python/boutiques/tests/test_pprint.py | jerdra/boutiques | f6ee252fd1332ec686dc76dc12e52a0d69c685c3 | [
"MIT"
] | null | null | null | tools/python/boutiques/tests/test_pprint.py | jerdra/boutiques | f6ee252fd1332ec686dc76dc12e52a0d69c685c3 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
import os
import os.path as op
from unittest import TestCase
from boutiques import __file__ as bfile
from six import string_types
import boutiques as bosh
class TestPPrint(TestCase):
def test_doesntcrash(self):
fil = op.join(op.split(bfile)[0],
'schema/examples/test_pretty_print.json')
prettystring = bosh.prettyprint(fil)
assert(isinstance(prettystring, string_types))
| 24.833333 | 63 | 0.711409 |
import os
import os.path as op
from unittest import TestCase
from boutiques import __file__ as bfile
from six import string_types
import boutiques as bosh
class TestPPrint(TestCase):
def test_doesntcrash(self):
fil = op.join(op.split(bfile)[0],
'schema/examples/test_pretty_print.json')
prettystring = bosh.prettyprint(fil)
assert(isinstance(prettystring, string_types))
| true | true |
1c2e8320ab12fd5dfaf27f520054c3b13732220f | 919 | py | Python | funcional.py | ludimila/LearnFunctionalPython | 80275371d1c6cee5a17ab98e1c36242ffeb4644c | [
"MIT"
] | null | null | null | funcional.py | ludimila/LearnFunctionalPython | 80275371d1c6cee5a17ab98e1c36242ffeb4644c | [
"MIT"
] | null | null | null | funcional.py | ludimila/LearnFunctionalPython | 80275371d1c6cee5a17ab98e1c36242ffeb4644c | [
"MIT"
] | null | null | null | #open
#filter tirar linhas em branco - filter
#map
#map remove new lines
#lower
#map remove punctuation
from functools import partial
from string import punctuation
from re import sub
from collections import Counter
#from multprocessing.dummy import Pool
def pipe(*funcs):
def inner(arg):
result = arg
for func in funcs:
result = func(result)
return result
return inner
remove_blank_lines = partial(filter,lambda x: x != '\n')
remove_new_lines = partial(map, lambda x: str.strip(x, '\n'))
lower = partial(map, str.lower)
remove_punctuation = partial(map, lambda x: sub(r'[.\,?!\-\();]','',x))
join = partial(str.join,' ☾ ')
split = partial(str.split, sep = ' ')
parse = pipe(open)
parse = pipe (open, remove_blank_lines, lower, remove_punctuation,join, split)
count_parse = pipe(parse, Counter)
xpto = count_parse('vaimalandra.txt')
print(' '.join(xpto))
| 20.886364 | 78 | 0.681175 |
from functools import partial
from string import punctuation
from re import sub
from collections import Counter
def pipe(*funcs):
def inner(arg):
result = arg
for func in funcs:
result = func(result)
return result
return inner
remove_blank_lines = partial(filter,lambda x: x != '\n')
remove_new_lines = partial(map, lambda x: str.strip(x, '\n'))
lower = partial(map, str.lower)
remove_punctuation = partial(map, lambda x: sub(r'[.\,?!\-\();]','',x))
join = partial(str.join,' ☾ ')
split = partial(str.split, sep = ' ')
parse = pipe(open)
parse = pipe (open, remove_blank_lines, lower, remove_punctuation,join, split)
count_parse = pipe(parse, Counter)
xpto = count_parse('vaimalandra.txt')
print(' '.join(xpto))
| true | true |
1c2e8380043de9ea543efb9b099a5d397f7be960 | 4,030 | py | Python | onnx/backend/test/case/node/bitshift.py | How-Wang/onnx | c940fa3fea84948e46603cab2f86467291443beb | [
"Apache-2.0"
] | 1 | 2022-02-04T07:45:14.000Z | 2022-02-04T07:45:14.000Z | onnx/backend/test/case/node/bitshift.py | How-Wang/onnx | c940fa3fea84948e46603cab2f86467291443beb | [
"Apache-2.0"
] | null | null | null | onnx/backend/test/case/node/bitshift.py | How-Wang/onnx | c940fa3fea84948e46603cab2f86467291443beb | [
"Apache-2.0"
] | null | null | null | # SPDX-License-Identifier: Apache-2.0
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np # type: ignore
import onnx
from ..base import Base
from . import expect
class BitShift(Base):
@staticmethod
def export_right_unit8() -> None:
node = onnx.helper.make_node(
'BitShift',
inputs=['x', 'y'],
outputs=['z'],
direction="RIGHT"
)
x = np.array([16, 4, 1]).astype(np.uint8)
y = np.array([1, 2, 3]).astype(np.uint8)
z = x >> y # expected output [8, 1, 0]
expect(node, inputs=[x, y], outputs=[z],
name='test_bitshift_right_uint8')
@staticmethod
def export_right_unit16() -> None:
node = onnx.helper.make_node(
'BitShift',
inputs=['x', 'y'],
outputs=['z'],
direction="RIGHT"
)
x = np.array([16, 4, 1]).astype(np.uint16)
y = np.array([1, 2, 3]).astype(np.uint16)
z = x >> y # expected output [8, 1, 0]
expect(node, inputs=[x, y], outputs=[z],
name='test_bitshift_right_uint16')
@staticmethod
def export_right_unit32() -> None:
node = onnx.helper.make_node(
'BitShift',
inputs=['x', 'y'],
outputs=['z'],
direction="RIGHT"
)
x = np.array([16, 4, 1]).astype(np.uint32)
y = np.array([1, 2, 3]).astype(np.uint32)
z = x >> y # expected output [8, 1, 0]
expect(node, inputs=[x, y], outputs=[z],
name='test_bitshift_right_uint32')
@staticmethod
def export_right_unit64() -> None:
node = onnx.helper.make_node(
'BitShift',
inputs=['x', 'y'],
outputs=['z'],
direction="RIGHT"
)
x = np.array([16, 4, 1]).astype(np.uint64)
y = np.array([1, 2, 3]).astype(np.uint64)
z = x >> y # expected output [8, 1, 0]
expect(node, inputs=[x, y], outputs=[z],
name='test_bitshift_right_uint64')
@staticmethod
def export_left_unit8() -> None:
node = onnx.helper.make_node(
'BitShift',
inputs=['x', 'y'],
outputs=['z'],
direction="LEFT"
)
x = np.array([16, 4, 1]).astype(np.uint8)
y = np.array([1, 2, 3]).astype(np.uint8)
z = x << y # expected output [32, 16, 8]
expect(node, inputs=[x, y], outputs=[z],
name='test_bitshift_left_uint8')
@staticmethod
def export_left_unit16() -> None:
node = onnx.helper.make_node(
'BitShift',
inputs=['x', 'y'],
outputs=['z'],
direction="LEFT"
)
x = np.array([16, 4, 1]).astype(np.uint16)
y = np.array([1, 2, 3]).astype(np.uint16)
z = x << y # expected output [32, 16, 8]
expect(node, inputs=[x, y], outputs=[z],
name='test_bitshift_left_uint16')
@staticmethod
def export_left_unit32() -> None:
node = onnx.helper.make_node(
'BitShift',
inputs=['x', 'y'],
outputs=['z'],
direction="LEFT"
)
x = np.array([16, 4, 1]).astype(np.uint32)
y = np.array([1, 2, 3]).astype(np.uint32)
z = x << y # expected output [32, 16, 8]
expect(node, inputs=[x, y], outputs=[z],
name='test_bitshift_left_uint32')
@staticmethod
def export_left_unit64() -> None:
node = onnx.helper.make_node(
'BitShift',
inputs=['x', 'y'],
outputs=['z'],
direction="LEFT"
)
x = np.array([16, 4, 1]).astype(np.uint64)
y = np.array([1, 2, 3]).astype(np.uint64)
z = x << y # expected output [32, 16, 8]
expect(node, inputs=[x, y], outputs=[z],
name='test_bitshift_left_uint64')
| 29.632353 | 50 | 0.507196 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
import onnx
from ..base import Base
from . import expect
class BitShift(Base):
@staticmethod
def export_right_unit8() -> None:
node = onnx.helper.make_node(
'BitShift',
inputs=['x', 'y'],
outputs=['z'],
direction="RIGHT"
)
x = np.array([16, 4, 1]).astype(np.uint8)
y = np.array([1, 2, 3]).astype(np.uint8)
z = x >> y
expect(node, inputs=[x, y], outputs=[z],
name='test_bitshift_right_uint8')
@staticmethod
def export_right_unit16() -> None:
node = onnx.helper.make_node(
'BitShift',
inputs=['x', 'y'],
outputs=['z'],
direction="RIGHT"
)
x = np.array([16, 4, 1]).astype(np.uint16)
y = np.array([1, 2, 3]).astype(np.uint16)
z = x >> y
expect(node, inputs=[x, y], outputs=[z],
name='test_bitshift_right_uint16')
@staticmethod
def export_right_unit32() -> None:
node = onnx.helper.make_node(
'BitShift',
inputs=['x', 'y'],
outputs=['z'],
direction="RIGHT"
)
x = np.array([16, 4, 1]).astype(np.uint32)
y = np.array([1, 2, 3]).astype(np.uint32)
z = x >> y
expect(node, inputs=[x, y], outputs=[z],
name='test_bitshift_right_uint32')
@staticmethod
def export_right_unit64() -> None:
node = onnx.helper.make_node(
'BitShift',
inputs=['x', 'y'],
outputs=['z'],
direction="RIGHT"
)
x = np.array([16, 4, 1]).astype(np.uint64)
y = np.array([1, 2, 3]).astype(np.uint64)
z = x >> y
expect(node, inputs=[x, y], outputs=[z],
name='test_bitshift_right_uint64')
@staticmethod
def export_left_unit8() -> None:
node = onnx.helper.make_node(
'BitShift',
inputs=['x', 'y'],
outputs=['z'],
direction="LEFT"
)
x = np.array([16, 4, 1]).astype(np.uint8)
y = np.array([1, 2, 3]).astype(np.uint8)
z = x << y
expect(node, inputs=[x, y], outputs=[z],
name='test_bitshift_left_uint8')
@staticmethod
def export_left_unit16() -> None:
node = onnx.helper.make_node(
'BitShift',
inputs=['x', 'y'],
outputs=['z'],
direction="LEFT"
)
x = np.array([16, 4, 1]).astype(np.uint16)
y = np.array([1, 2, 3]).astype(np.uint16)
z = x << y
expect(node, inputs=[x, y], outputs=[z],
name='test_bitshift_left_uint16')
@staticmethod
def export_left_unit32() -> None:
node = onnx.helper.make_node(
'BitShift',
inputs=['x', 'y'],
outputs=['z'],
direction="LEFT"
)
x = np.array([16, 4, 1]).astype(np.uint32)
y = np.array([1, 2, 3]).astype(np.uint32)
z = x << y
expect(node, inputs=[x, y], outputs=[z],
name='test_bitshift_left_uint32')
@staticmethod
def export_left_unit64() -> None:
node = onnx.helper.make_node(
'BitShift',
inputs=['x', 'y'],
outputs=['z'],
direction="LEFT"
)
x = np.array([16, 4, 1]).astype(np.uint64)
y = np.array([1, 2, 3]).astype(np.uint64)
z = x << y
expect(node, inputs=[x, y], outputs=[z],
name='test_bitshift_left_uint64')
| true | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.