hexsha stringlengths 40 40 | size int64 4 996k | ext stringclasses 8
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 4 996k | avg_line_length float64 1.33 58.2k | max_line_length int64 2 323k | alphanum_fraction float64 0 0.97 | content_no_comment stringlengths 0 946k | is_comment_constant_removed bool 2
classes | is_sharp_comment_removed bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f7f92036ba670d7510d7a2dcce65254cc45e98b5 | 392 | py | Python | solutions/pe00009.py | Derick7/projectEulerSolutions | 586c5bd4d29885906aa469f27113c7ebbb0b0050 | [
"MIT"
] | null | null | null | solutions/pe00009.py | Derick7/projectEulerSolutions | 586c5bd4d29885906aa469f27113c7ebbb0b0050 | [
"MIT"
] | null | null | null | solutions/pe00009.py | Derick7/projectEulerSolutions | 586c5bd4d29885906aa469f27113c7ebbb0b0050 | [
"MIT"
] | null | null | null | def sqrt(n):
return int(n**0.5)
abcSum = 1000
abcPdt = 0
searchRange = [x for x in range(abcSum/2,0,-1)]
for i in searchRange:
for j in [x for x in searchRange if x<i]:
k = 1000 - (i + j)
if k in searchRange and k<j:
if (i**2) == ((j**2)+(k**2)):
abcPdt = i*j*k
print str(i) +" "+ str(j) +" "+ str(k)
print abcPdt
| 21.777778 | 60 | 0.477041 | def sqrt(n):
return int(n**0.5)
abcSum = 1000
abcPdt = 0
searchRange = [x for x in range(abcSum/2,0,-1)]
for i in searchRange:
for j in [x for x in searchRange if x<i]:
k = 1000 - (i + j)
if k in searchRange and k<j:
if (i**2) == ((j**2)+(k**2)):
abcPdt = i*j*k
print str(i) +" "+ str(j) +" "+ str(k)
print abcPdt
| false | true |
f7f921a6b4db6cf121eee3a94fa22d3e6bc9143c | 574 | py | Python | saleor/graphql/order/tests/benchmark/fixtures.py | hereischen/saleor | 26bd271ac32312a415b0c5e1987e92fe939b3cb5 | [
"CC-BY-4.0"
] | null | null | null | saleor/graphql/order/tests/benchmark/fixtures.py | hereischen/saleor | 26bd271ac32312a415b0c5e1987e92fe939b3cb5 | [
"CC-BY-4.0"
] | null | null | null | saleor/graphql/order/tests/benchmark/fixtures.py | hereischen/saleor | 26bd271ac32312a415b0c5e1987e92fe939b3cb5 | [
"CC-BY-4.0"
] | null | null | null | import uuid
import pytest
from prices import Money, TaxedMoney
from .....order.models import Order
@pytest.fixture
def orders_for_benchmarks(channel_USD, address, customer_user):
orders = [
Order(
token=str(uuid.uuid4()),
channel=channel_USD,
billing_address=address.get_copy(),
shipping_address=address.get_copy(),
user=customer_user,
total=TaxedMoney(net=Money(i, "USD"), gross=Money(i, "USD")),
)
for i in range(10)
]
return Order.objects.bulk_create(orders)
| 24.956522 | 73 | 0.627178 | import uuid
import pytest
from prices import Money, TaxedMoney
from .....order.models import Order
@pytest.fixture
def orders_for_benchmarks(channel_USD, address, customer_user):
orders = [
Order(
token=str(uuid.uuid4()),
channel=channel_USD,
billing_address=address.get_copy(),
shipping_address=address.get_copy(),
user=customer_user,
total=TaxedMoney(net=Money(i, "USD"), gross=Money(i, "USD")),
)
for i in range(10)
]
return Order.objects.bulk_create(orders)
| true | true |
f7f922da71d5b0b3cd3455181465feb7dfb1351d | 3,511 | py | Python | scripts/test-omw-cili-db.py | sehqlr/OMW | 008bd8a96c7bd054b7284a407dc8e12167ec8832 | [
"MIT"
] | 33 | 2016-08-18T02:42:16.000Z | 2021-07-07T02:38:55.000Z | scripts/test-omw-cili-db.py | sehqlr/OMW | 008bd8a96c7bd054b7284a407dc8e12167ec8832 | [
"MIT"
] | 82 | 2016-12-05T11:40:41.000Z | 2021-03-17T08:44:40.000Z | scripts/test-omw-cili-db.py | sehqlr/OMW | 008bd8a96c7bd054b7284a407dc8e12167ec8832 | [
"MIT"
] | 12 | 2016-08-01T01:54:06.000Z | 2020-10-03T09:48:48.000Z | import sqlite3
import sys, time
dbfile = "omw.db"
con = sqlite3.connect(dbfile)
curs = con.cursor()
print("\nYou should be testing over an empty table!")
print("Failure to comply will result in foreverness... \n")
commandlist = [
("""PRAGMA foreign_keys = 1;""",
"""Activating foreign key constraints"""),
("""INSERT INTO active_user (user_id)
VALUES ('test-user-deleter');""",
"""Inserting active user"""),
# TESTING kind TABLE
("""INSERT INTO kind (kind, u)
VALUES ('kind1', 'test-user');""",
"""Inserting in kind table"""),
("""UPDATE kind
SET kind = 'kind2', u='test-user2'
WHERE kind = 'kind1';""",
"""Updating in kind table"""),
# TESTING status TABLE
("""INSERT INTO status (status, u)
VALUES ('status1', 'test-user');""",
"""Inserting in status table"""),
("""UPDATE status
SET status = 'status2', u='test-user2'
WHERE status = 'status1';""",
"""Updating in status table"""),
# TESTING proj TABLE
("""INSERT INTO proj (code, u)
VALUES ('ntutest', 'test-user');""",
"""Inserting in proj table"""),
("""UPDATE proj
SET code = 'ntutest2', u='test-user2'
WHERE code = 'ntutest';""",
"""Updating in proj table"""),
# TESTING scr TABLE
("""INSERT INTO src (proj_id, version, u)
VALUES (1, '3.0', 'test-user');""",
"""Inserting in src table"""),
("""UPDATE src
SET version = '3.2', u='test-user2'
WHERE version = '3.0';""",
"""Updating in src table"""),
# TESTING scr_meta TABLE
("""INSERT INTO src_meta (src_id, attr, val, u)
VALUES (1, 'attr-test','val-test', 'test-user');""",
"""Inserting in src_meta table"""),
("""UPDATE src_meta
SET attr = 'attr-test2', u='test-user2' WHERE attr = 'attr-test';""",
"""Updating in src_meta table"""),
("""DELETE FROM src_meta WHERE attr = 'attr-test2' limit 5;""",
"""Deleting from src_meta table"""),
# TESTING ili TABLE
("""INSERT INTO ili (kind_id, def, status_id, origin_src_id, src_key, u)
VALUES (1, 'def-test', 1, 1, 'src-key-test', 'test-user');""",
"""Inserting in ili table"""),
("""INSERT INTO ili (kind_id, def, status_id, origin_src_id, src_key, u)
VALUES (1, 'def2-test', 1, 1, 'src-key2-test', 'test-user');""",
"""Inserting in ili table"""),
("""UPDATE ili
SET superseded_by_id = 2, u='test-user2' WHERE id = 1;""",
"""Updating in ili table"""),
# TESTING ili_com TABLE
("""INSERT INTO ili_com (ili_id, com, u)
VALUES (1, 'commentary-test', 'test-user');""",
"""Inserting in ili_com table"""),
("""UPDATE ili_com
SET com = 'updated-commentary-test', u='test-user2' WHERE id = 1;""",
"""Updating in ili_com table"""),
# DELETING THINGS IN THE RIGHT ORDER
("""DELETE FROM ili_com;""",
"""Deleting from ili_com table"""),
("""DELETE FROM ili;""",
"""Deleting from ili table"""),
("""DELETE FROM kind;""",
"""Deleting from kind table"""),
("""DELETE FROM status;""",
"""Deleting from status table"""),
("""DELETE FROM src;""",
"""Deleting from src table"""),
("""DELETE FROM proj;""",
"""Deleting from proj table"""),
("""DELETE FROM active_user;""",
"""Deleting active user""")
]
failedcommands = []
for command in commandlist:
try:
time.sleep(0.5)
curs.execute(command[0])
print("PASSED: {} ".format(command[1]))
except:
failedcommands.append(command[0])
print("FAILED: <<<< {} >>>> !!!".format(command[1]))
if failedcommands == []:
print("")
print("Congratulations, it seems everything went well!")
con.commit()
con.close()
| 24.552448 | 73 | 0.603817 | import sqlite3
import sys, time
dbfile = "omw.db"
con = sqlite3.connect(dbfile)
curs = con.cursor()
print("\nYou should be testing over an empty table!")
print("Failure to comply will result in foreverness... \n")
commandlist = [
("""PRAGMA foreign_keys = 1;""",
"""Activating foreign key constraints"""),
("""INSERT INTO active_user (user_id)
VALUES ('test-user-deleter');""",
"""Inserting active user"""),
("""INSERT INTO kind (kind, u)
VALUES ('kind1', 'test-user');""",
"""Inserting in kind table"""),
("""UPDATE kind
SET kind = 'kind2', u='test-user2'
WHERE kind = 'kind1';""",
"""Updating in kind table"""),
("""INSERT INTO status (status, u)
VALUES ('status1', 'test-user');""",
"""Inserting in status table"""),
("""UPDATE status
SET status = 'status2', u='test-user2'
WHERE status = 'status1';""",
"""Updating in status table"""),
("""INSERT INTO proj (code, u)
VALUES ('ntutest', 'test-user');""",
"""Inserting in proj table"""),
("""UPDATE proj
SET code = 'ntutest2', u='test-user2'
WHERE code = 'ntutest';""",
"""Updating in proj table"""),
("""INSERT INTO src (proj_id, version, u)
VALUES (1, '3.0', 'test-user');""",
"""Inserting in src table"""),
("""UPDATE src
SET version = '3.2', u='test-user2'
WHERE version = '3.0';""",
"""Updating in src table"""),
("""INSERT INTO src_meta (src_id, attr, val, u)
VALUES (1, 'attr-test','val-test', 'test-user');""",
"""Inserting in src_meta table"""),
("""UPDATE src_meta
SET attr = 'attr-test2', u='test-user2' WHERE attr = 'attr-test';""",
"""Updating in src_meta table"""),
("""DELETE FROM src_meta WHERE attr = 'attr-test2' limit 5;""",
"""Deleting from src_meta table"""),
("""INSERT INTO ili (kind_id, def, status_id, origin_src_id, src_key, u)
VALUES (1, 'def-test', 1, 1, 'src-key-test', 'test-user');""",
"""Inserting in ili table"""),
("""INSERT INTO ili (kind_id, def, status_id, origin_src_id, src_key, u)
VALUES (1, 'def2-test', 1, 1, 'src-key2-test', 'test-user');""",
"""Inserting in ili table"""),
("""UPDATE ili
SET superseded_by_id = 2, u='test-user2' WHERE id = 1;""",
"""Updating in ili table"""),
("""INSERT INTO ili_com (ili_id, com, u)
VALUES (1, 'commentary-test', 'test-user');""",
"""Inserting in ili_com table"""),
("""UPDATE ili_com
SET com = 'updated-commentary-test', u='test-user2' WHERE id = 1;""",
"""Updating in ili_com table"""),
("""DELETE FROM ili_com;""",
"""Deleting from ili_com table"""),
("""DELETE FROM ili;""",
"""Deleting from ili table"""),
("""DELETE FROM kind;""",
"""Deleting from kind table"""),
("""DELETE FROM status;""",
"""Deleting from status table"""),
("""DELETE FROM src;""",
"""Deleting from src table"""),
("""DELETE FROM proj;""",
"""Deleting from proj table"""),
("""DELETE FROM active_user;""",
"""Deleting active user""")
]
failedcommands = []
for command in commandlist:
try:
time.sleep(0.5)
curs.execute(command[0])
print("PASSED: {} ".format(command[1]))
except:
failedcommands.append(command[0])
print("FAILED: <<<< {} >>>> !!!".format(command[1]))
if failedcommands == []:
print("")
print("Congratulations, it seems everything went well!")
con.commit()
con.close()
| true | true |
f7f9233d897360bac62ea4d7b7be7ffcec670b27 | 22,498 | py | Python | photutils/psf/tests/test_photometry.py | fdeugenio/photutils | 33c8b15cbbda85dc11c86a73217422dcb61398b7 | [
"BSD-3-Clause"
] | null | null | null | photutils/psf/tests/test_photometry.py | fdeugenio/photutils | 33c8b15cbbda85dc11c86a73217422dcb61398b7 | [
"BSD-3-Clause"
] | null | null | null | photutils/psf/tests/test_photometry.py | fdeugenio/photutils | 33c8b15cbbda85dc11c86a73217422dcb61398b7 | [
"BSD-3-Clause"
] | null | null | null | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
import numpy as np
from numpy.testing import assert_allclose, assert_array_equal, assert_equal
from astropy.convolution.utils import discretize_model
from astropy.modeling import Parameter, Fittable2DModel
from astropy.modeling.fitting import LevMarLSQFitter
from astropy.modeling.models import Gaussian2D, Moffat2D
from astropy.stats import gaussian_sigma_to_fwhm, SigmaClip
from astropy.table import Table
from astropy.tests.helper import catch_warnings
from astropy.utils.exceptions import AstropyUserWarning
from ..groupstars import DAOGroup
from ..models import IntegratedGaussianPRF
from ..photometry import (DAOPhotPSFPhotometry, BasicPSFPhotometry,
IterativelySubtractedPSFPhotometry)
from ..sandbox import DiscretePRF
from ..utils import prepare_psf_model
from ...background import StdBackgroundRMS, MMMBackground
from ...datasets import make_gaussian_prf_sources_image, make_noise_image
from ...detection import DAOStarFinder
try:
import scipy # noqa
HAS_SCIPY = True
except ImportError:
HAS_SCIPY = False
def make_psf_photometry_objs(std=1, sigma_psf=1):
"""
Produces baseline photometry objects which are then
modified as-needed in specific tests below
"""
daofind = DAOStarFinder(threshold=5.0*std,
fwhm=sigma_psf*gaussian_sigma_to_fwhm)
daogroup = DAOGroup(1.5*sigma_psf*gaussian_sigma_to_fwhm)
threshold = 5. * std
fwhm = sigma_psf * gaussian_sigma_to_fwhm
crit_separation = 1.5 * sigma_psf * gaussian_sigma_to_fwhm
daofind = DAOStarFinder(threshold=threshold, fwhm=fwhm)
daogroup = DAOGroup(crit_separation)
mode_bkg = MMMBackground()
psf_model = IntegratedGaussianPRF(sigma=sigma_psf)
fitter = LevMarLSQFitter()
basic_phot_obj = BasicPSFPhotometry(finder=daofind,
group_maker=daogroup,
bkg_estimator=mode_bkg,
psf_model=psf_model,
fitter=fitter,
fitshape=(11, 11))
iter_phot_obj = IterativelySubtractedPSFPhotometry(finder=daofind,
group_maker=daogroup,
bkg_estimator=mode_bkg,
psf_model=psf_model,
fitter=fitter, niters=1,
fitshape=(11, 11))
dao_phot_obj = DAOPhotPSFPhotometry(crit_separation=crit_separation,
threshold=threshold, fwhm=fwhm,
psf_model=psf_model, fitshape=(11, 11),
niters=1)
return (basic_phot_obj, iter_phot_obj, dao_phot_obj)
sigma_psfs = []
# A group of two overlapped stars and an isolated one
sigma_psfs.append(2)
sources1 = Table()
sources1['flux'] = [800, 1000, 1200]
sources1['x_0'] = [13, 18, 25]
sources1['y_0'] = [16, 16, 25]
sources1['sigma'] = [sigma_psfs[-1]] * 3
sources1['theta'] = [0] * 3
sources1['id'] = [1, 2, 3]
sources1['group_id'] = [1, 1, 2]
# one single group with four stars.
sigma_psfs.append(2)
sources2 = Table()
sources2['flux'] = [700, 800, 700, 800]
sources2['x_0'] = [12, 17, 12, 17]
sources2['y_0'] = [15, 15, 20, 20]
sources2['sigma'] = [sigma_psfs[-1]] * 4
sources2['theta'] = [0] * 4
sources2['id'] = [1, 2, 3, 4]
sources2['group_id'] = [1, 1, 1, 1]
# one faint star and one brither companion
# although they are in the same group, the detection algorithm
# is not able to detect the fainter star, hence photometry should
# be performed with niters > 1 or niters=None
sigma_psfs.append(2)
sources3 = Table()
sources3['flux'] = [10000, 1000]
sources3['x_0'] = [18, 13]
sources3['y_0'] = [17, 19]
sources3['sigma'] = [sigma_psfs[-1]] * 2
sources3['theta'] = [0] * 2
sources3['id'] = [1] * 2
sources3['group_id'] = [1] * 2
sources3['iter_detected'] = [1, 2]
@pytest.mark.skipif('not HAS_SCIPY')
@pytest.mark.parametrize("sigma_psf, sources", [(sigma_psfs[2], sources3)])
def test_psf_photometry_niters(sigma_psf, sources):
img_shape = (32, 32)
# generate image with read-out noise (Gaussian) and
# background noise (Poisson)
image = (make_gaussian_prf_sources_image(img_shape, sources) +
make_noise_image(img_shape, type='poisson', mean=6.,
random_state=1) +
make_noise_image(img_shape, type='gaussian', mean=0.,
stddev=2., random_state=1))
cp_image = image.copy()
sigma_clip = SigmaClip(sigma=3.)
bkgrms = StdBackgroundRMS(sigma_clip)
std = bkgrms(image)
phot_obj = make_psf_photometry_objs(std, sigma_psf)[1:3]
for iter_phot_obj in phot_obj:
iter_phot_obj.niters = None
result_tab = iter_phot_obj(image)
residual_image = iter_phot_obj.get_residual_image()
assert (result_tab['x_0_unc'] < 1.96 * sigma_psf /
np.sqrt(sources['flux'])).all()
assert (result_tab['y_0_unc'] < 1.96 * sigma_psf /
np.sqrt(sources['flux'])).all()
assert (result_tab['flux_unc'] < 1.96 *
np.sqrt(sources['flux'])).all()
assert_allclose(result_tab['x_fit'], sources['x_0'], rtol=1e-1)
assert_allclose(result_tab['y_fit'], sources['y_0'], rtol=1e-1)
assert_allclose(result_tab['flux_fit'], sources['flux'], rtol=1e-1)
assert_array_equal(result_tab['id'], sources['id'])
assert_array_equal(result_tab['group_id'], sources['group_id'])
assert_array_equal(result_tab['iter_detected'],
sources['iter_detected'])
assert_allclose(np.mean(residual_image), 0.0, atol=1e1)
# make sure image is note overwritten
assert_array_equal(cp_image, image)
@pytest.mark.skipif('not HAS_SCIPY')
@pytest.mark.parametrize("sigma_psf, sources",
[(sigma_psfs[0], sources1),
(sigma_psfs[1], sources2),
# these ensure that the test *fails* if the model
# PSFs are the wrong shape
pytest.param(sigma_psfs[0]/1.2, sources1,
marks=pytest.mark.xfail()),
pytest.param(sigma_psfs[1]*1.2, sources2,
marks=pytest.mark.xfail())])
def test_psf_photometry_oneiter(sigma_psf, sources):
"""
Tests in an image with a group of two overlapped stars and an
isolated one.
"""
img_shape = (32, 32)
# generate image with read-out noise (Gaussian) and
# background noise (Poisson)
image = (make_gaussian_prf_sources_image(img_shape, sources) +
make_noise_image(img_shape, type='poisson', mean=6.,
random_state=1) +
make_noise_image(img_shape, type='gaussian', mean=0.,
stddev=2., random_state=1))
cp_image = image.copy()
sigma_clip = SigmaClip(sigma=3.)
bkgrms = StdBackgroundRMS(sigma_clip)
std = bkgrms(image)
phot_objs = make_psf_photometry_objs(std, sigma_psf)
for phot_proc in phot_objs:
result_tab = phot_proc(image)
residual_image = phot_proc.get_residual_image()
assert (result_tab['x_0_unc'] < 1.96 * sigma_psf /
np.sqrt(sources['flux'])).all()
assert (result_tab['y_0_unc'] < 1.96 * sigma_psf /
np.sqrt(sources['flux'])).all()
assert (result_tab['flux_unc'] < 1.96 *
np.sqrt(sources['flux'])).all()
assert_allclose(result_tab['x_fit'], sources['x_0'], rtol=1e-1)
assert_allclose(result_tab['y_fit'], sources['y_0'], rtol=1e-1)
assert_allclose(result_tab['flux_fit'], sources['flux'], rtol=1e-1)
assert_array_equal(result_tab['id'], sources['id'])
assert_array_equal(result_tab['group_id'], sources['group_id'])
assert_allclose(np.mean(residual_image), 0.0, atol=1e1)
# test fixed photometry
phot_proc.psf_model.x_0.fixed = True
phot_proc.psf_model.y_0.fixed = True
pos = Table(names=['x_0', 'y_0'], data=[sources['x_0'],
sources['y_0']])
cp_pos = pos.copy()
result_tab = phot_proc(image, pos)
residual_image = phot_proc.get_residual_image()
assert 'x_0_unc' not in result_tab.colnames
assert 'y_0_unc' not in result_tab.colnames
assert (result_tab['flux_unc'] < 1.96 *
np.sqrt(sources['flux'])).all()
assert_array_equal(result_tab['x_fit'], sources['x_0'])
assert_array_equal(result_tab['y_fit'], sources['y_0'])
assert_allclose(result_tab['flux_fit'], sources['flux'], rtol=1e-1)
assert_array_equal(result_tab['id'], sources['id'])
assert_array_equal(result_tab['group_id'], sources['group_id'])
assert_allclose(np.mean(residual_image), 0.0, atol=1e1)
# make sure image is not overwritten
assert_array_equal(cp_image, image)
# make sure initial guess table is not modified
assert_array_equal(cp_pos, pos)
# resets fixed positions
phot_proc.psf_model.x_0.fixed = False
phot_proc.psf_model.y_0.fixed = False
@pytest.mark.skipif('not HAS_SCIPY')
def test_niters_errors():
iter_phot_obj = make_psf_photometry_objs()[1]
# tests that niters is set to an integer even if the user inputs
# a float
iter_phot_obj.niters = 1.1
assert_equal(iter_phot_obj.niters, 1)
# test that a ValueError is raised if niters <= 0
with pytest.raises(ValueError):
iter_phot_obj.niters = 0
# test that it's OK to set niters to None
iter_phot_obj.niters = None
@pytest.mark.skipif('not HAS_SCIPY')
def test_fitshape_errors():
basic_phot_obj = make_psf_photometry_objs()[0]
# first make sure setting to a scalar does the right thing (and makes
# no errors)
basic_phot_obj.fitshape = 11
assert np.all(basic_phot_obj.fitshape == (11, 11))
# test that a ValuError is raised if fitshape has even components
with pytest.raises(ValueError):
basic_phot_obj.fitshape = (2, 2)
with pytest.raises(ValueError):
basic_phot_obj.fitshape = 2
# test that a ValueError is raised if fitshape has non positive
# components
with pytest.raises(ValueError):
basic_phot_obj.fitshape = (-1, 0)
# test that a ValueError is raised if fitshape has more than two
# dimensions
with pytest.raises(ValueError):
basic_phot_obj.fitshape = (3, 3, 3)
@pytest.mark.skipif('not HAS_SCIPY')
def test_aperture_radius_errors():
basic_phot_obj = make_psf_photometry_objs()[0]
# test that aperture_radius was set to None by default
assert_equal(basic_phot_obj.aperture_radius, None)
# test that a ValueError is raised if aperture_radius is non positive
with pytest.raises(ValueError):
basic_phot_obj.aperture_radius = -3
@pytest.mark.skipif('not HAS_SCIPY')
def test_finder_errors():
iter_phot_obj = make_psf_photometry_objs()[1]
with pytest.raises(ValueError):
iter_phot_obj.finder = None
with pytest.raises(ValueError):
iter_phot_obj = IterativelySubtractedPSFPhotometry(
finder=None, group_maker=DAOGroup(1),
bkg_estimator=MMMBackground(),
psf_model=IntegratedGaussianPRF(1), fitshape=(11, 11))
@pytest.mark.skipif('not HAS_SCIPY')
def test_finder_positions_warning():
basic_phot_obj = make_psf_photometry_objs(sigma_psf=2)[0]
positions = Table()
positions['x_0'] = [12.8, 18.2, 25.3]
positions['y_0'] = [15.7, 16.5, 25.1]
image = (make_gaussian_prf_sources_image((32, 32), sources1) +
make_noise_image((32, 32), type='poisson', mean=6.,
random_state=1))
with catch_warnings(AstropyUserWarning):
result_tab = basic_phot_obj(image=image, init_guesses=positions)
assert_array_equal(result_tab['x_0'], positions['x_0'])
assert_array_equal(result_tab['y_0'], positions['y_0'])
assert_allclose(result_tab['x_fit'], positions['x_0'], rtol=1e-1)
assert_allclose(result_tab['y_fit'], positions['y_0'], rtol=1e-1)
with pytest.raises(ValueError):
basic_phot_obj.finder = None
result_tab = basic_phot_obj(image=image)
@pytest.mark.skipif('not HAS_SCIPY')
def test_aperture_radius():
img_shape = (32, 32)
# generate image with read-out noise (Gaussian) and
# background noise (Poisson)
image = (make_gaussian_prf_sources_image(img_shape, sources1) +
make_noise_image(img_shape, type='poisson', mean=6.,
random_state=1) +
make_noise_image(img_shape, type='gaussian', mean=0.,
stddev=2., random_state=1))
basic_phot_obj = make_psf_photometry_objs()[0]
# test that aperture radius is properly set whenever the PSF model has
# a `fwhm` attribute
class PSFModelWithFWHM(Fittable2DModel):
x_0 = Parameter(default=1)
y_0 = Parameter(default=1)
flux = Parameter(default=1)
fwhm = Parameter(default=5)
def __init__(self, fwhm=fwhm.default):
super().__init__(fwhm=fwhm)
def evaluate(self, x, y, x_0, y_0, flux, fwhm):
return flux / (fwhm * (x - x_0)**2 * (y - y_0)**2)
psf_model = PSFModelWithFWHM()
basic_phot_obj.psf_model = psf_model
basic_phot_obj(image)
assert_equal(basic_phot_obj.aperture_radius, psf_model.fwhm.value)
PARS_TO_SET_0 = {'x_0': 'x_0', 'y_0': 'y_0', 'flux_0': 'flux'}
PARS_TO_OUTPUT_0 = {'x_fit': 'x_0', 'y_fit': 'y_0', 'flux_fit': 'flux'}
PARS_TO_SET_1 = PARS_TO_SET_0.copy()
PARS_TO_SET_1['sigma_0'] = 'sigma'
PARS_TO_OUTPUT_1 = PARS_TO_OUTPUT_0.copy()
PARS_TO_OUTPUT_1['sigma_fit'] = 'sigma'
@pytest.mark.parametrize("actual_pars_to_set, actual_pars_to_output,"
"is_sigma_fixed", [(PARS_TO_SET_0, PARS_TO_OUTPUT_0,
True),
(PARS_TO_SET_1, PARS_TO_OUTPUT_1,
False)])
@pytest.mark.skipif('not HAS_SCIPY')
def test_define_fit_param_names(actual_pars_to_set, actual_pars_to_output,
is_sigma_fixed):
psf_model = IntegratedGaussianPRF()
psf_model.sigma.fixed = is_sigma_fixed
basic_phot_obj = make_psf_photometry_objs()[0]
basic_phot_obj.psf_model = psf_model
basic_phot_obj._define_fit_param_names()
assert_equal(basic_phot_obj._pars_to_set, actual_pars_to_set)
assert_equal(basic_phot_obj._pars_to_output, actual_pars_to_output)
# tests previously written to psf_photometry
PSF_SIZE = 11
GAUSSIAN_WIDTH = 1.
IMAGE_SIZE = 101
# Position and FLUXES of test sources
INTAB = Table([[50., 23, 12, 86], [50., 83, 80, 84],
[np.pi * 10, 3.654, 20., 80 / np.sqrt(3)]],
names=['x_0', 'y_0', 'flux_0'])
# Create test psf
psf_model = Gaussian2D(1. / (2 * np.pi * GAUSSIAN_WIDTH ** 2), PSF_SIZE // 2,
PSF_SIZE // 2, GAUSSIAN_WIDTH, GAUSSIAN_WIDTH)
test_psf = discretize_model(psf_model, (0, PSF_SIZE), (0, PSF_SIZE),
mode='oversample')
# Set up grid for test image
image = np.zeros((IMAGE_SIZE, IMAGE_SIZE))
# Add sources to test image
for x, y, flux in INTAB:
model = Gaussian2D(flux / (2 * np.pi * GAUSSIAN_WIDTH ** 2),
x, y, GAUSSIAN_WIDTH, GAUSSIAN_WIDTH)
image += discretize_model(model, (0, IMAGE_SIZE), (0, IMAGE_SIZE),
mode='oversample')
# Some tests require an image with wider sources.
WIDE_GAUSSIAN_WIDTH = 3.
WIDE_INTAB = Table([[50, 23.2], [50.5, 1], [10, 20]],
names=['x_0', 'y_0', 'flux_0'])
wide_image = np.zeros((IMAGE_SIZE, IMAGE_SIZE))
# Add sources to test image
for x, y, flux in WIDE_INTAB:
model = Gaussian2D(flux / (2 * np.pi * WIDE_GAUSSIAN_WIDTH ** 2),
x, y, WIDE_GAUSSIAN_WIDTH, WIDE_GAUSSIAN_WIDTH)
wide_image += discretize_model(model, (0, IMAGE_SIZE), (0, IMAGE_SIZE),
mode='oversample')
@pytest.mark.skipif('not HAS_SCIPY')
def test_psf_photometry_discrete():
""" Test psf_photometry with discrete PRF model. """
prf = DiscretePRF(test_psf, subsampling=1)
basic_phot = BasicPSFPhotometry(group_maker=DAOGroup(2),
bkg_estimator=None, psf_model=prf,
fitshape=7)
f = basic_phot(image=image, init_guesses=INTAB)
for n in ['x', 'y', 'flux']:
assert_allclose(f[n + '_0'], f[n + '_fit'], rtol=1e-6)
@pytest.mark.skipif('not HAS_SCIPY')
def test_tune_coordinates():
"""
Test psf_photometry with discrete PRF model and coordinates that need
to be adjusted in the fit.
"""
prf = DiscretePRF(test_psf, subsampling=1)
prf.x_0.fixed = False
prf.y_0.fixed = False
# Shift all sources by 0.3 pixels
intab = INTAB.copy()
intab['x_0'] += 0.3
basic_phot = BasicPSFPhotometry(group_maker=DAOGroup(2),
bkg_estimator=None, psf_model=prf,
fitshape=7)
f = basic_phot(image=image, init_guesses=intab)
for n in ['x', 'y', 'flux']:
assert_allclose(f[n + '_0'], f[n + '_fit'], rtol=1e-3)
@pytest.mark.skipif('not HAS_SCIPY')
def test_psf_boundary():
"""
Test psf_photometry with discrete PRF model at the boundary of the data.
"""
prf = DiscretePRF(test_psf, subsampling=1)
basic_phot = BasicPSFPhotometry(group_maker=DAOGroup(2),
bkg_estimator=None, psf_model=prf,
fitshape=7, aperture_radius=5.5)
intab = Table(data=[[1], [1]], names=['x_0', 'y_0'])
f = basic_phot(image=image, init_guesses=intab)
assert_allclose(f['flux_fit'], 0, atol=1e-8)
@pytest.mark.skipif('not HAS_SCIPY')
def test_aperture_radius_value_error():
"""
Test psf_photometry with discrete PRF model at the boundary of the data.
"""
prf = DiscretePRF(test_psf, subsampling=1)
basic_phot = BasicPSFPhotometry(group_maker=DAOGroup(2),
bkg_estimator=None, psf_model=prf,
fitshape=7)
intab = Table(data=[[1], [1]], names=['x_0', 'y_0'])
with pytest.raises(ValueError) as err:
basic_phot(image=image, init_guesses=intab)
assert 'aperture_radius is None' in str(err.value)
@pytest.mark.skipif('not HAS_SCIPY')
def test_psf_boundary_gaussian():
"""
Test psf_photometry with discrete PRF model at the boundary of the data.
"""
psf = IntegratedGaussianPRF(GAUSSIAN_WIDTH)
basic_phot = BasicPSFPhotometry(group_maker=DAOGroup(2),
bkg_estimator=None, psf_model=psf,
fitshape=7)
intab = Table(data=[[1], [1]], names=['x_0', 'y_0'])
f = basic_phot(image=image, init_guesses=intab)
assert_allclose(f['flux_fit'], 0, atol=1e-8)
@pytest.mark.skipif('not HAS_SCIPY')
def test_psf_photometry_gaussian():
"""
Test psf_photometry with Gaussian PSF model.
"""
psf = IntegratedGaussianPRF(sigma=GAUSSIAN_WIDTH)
basic_phot = BasicPSFPhotometry(group_maker=DAOGroup(2),
bkg_estimator=None, psf_model=psf,
fitshape=7)
f = basic_phot(image=image, init_guesses=INTAB)
for n in ['x', 'y', 'flux']:
assert_allclose(f[n + '_0'], f[n + '_fit'], rtol=1e-3)
@pytest.mark.skipif('not HAS_SCIPY')
@pytest.mark.parametrize("renormalize_psf", (True, False))
def test_psf_photometry_gaussian2(renormalize_psf):
"""
Test psf_photometry with Gaussian PSF model from Astropy.
"""
psf = Gaussian2D(1. / (2 * np.pi * GAUSSIAN_WIDTH ** 2), PSF_SIZE // 2,
PSF_SIZE // 2, GAUSSIAN_WIDTH, GAUSSIAN_WIDTH)
psf = prepare_psf_model(psf, xname='x_mean', yname='y_mean',
renormalize_psf=renormalize_psf)
basic_phot = BasicPSFPhotometry(group_maker=DAOGroup(2),
bkg_estimator=None, psf_model=psf,
fitshape=7)
f = basic_phot(image=image, init_guesses=INTAB)
for n in ['x', 'y']:
assert_allclose(f[n + '_0'], f[n + '_fit'], rtol=1e-1)
assert_allclose(f['flux_0'], f['flux_fit'], rtol=1e-1)
@pytest.mark.skipif('not HAS_SCIPY')
def test_psf_photometry_moffat():
"""
Test psf_photometry with Moffat PSF model from Astropy.
"""
psf = Moffat2D(1. / (2 * np.pi * GAUSSIAN_WIDTH ** 2), PSF_SIZE // 2,
PSF_SIZE // 2, 1, 1)
psf = prepare_psf_model(psf, xname='x_0', yname='y_0',
renormalize_psf=False)
basic_phot = BasicPSFPhotometry(group_maker=DAOGroup(2),
bkg_estimator=None, psf_model=psf,
fitshape=7)
f = basic_phot(image=image, init_guesses=INTAB)
f.pprint(max_width=-1)
for n in ['x', 'y']:
assert_allclose(f[n + '_0'], f[n + '_fit'], rtol=1e-3)
# image was created with a gaussian, so flux won't match exactly
assert_allclose(f['flux_0'], f['flux_fit'], rtol=1e-1)
@pytest.mark.skipif('not HAS_SCIPY')
def test_psf_fitting_data_on_edge():
"""
No mask is input explicitly here, but source 2 is so close to the
edge that the subarray that's extracted gets a mask internally.
"""
psf_guess = IntegratedGaussianPRF(flux=1, sigma=WIDE_GAUSSIAN_WIDTH)
psf_guess.flux.fixed = psf_guess.x_0.fixed = psf_guess.y_0.fixed = False
basic_phot = BasicPSFPhotometry(group_maker=DAOGroup(2),
bkg_estimator=None, psf_model=psf_guess,
fitshape=7)
outtab = basic_phot(image=wide_image, init_guesses=WIDE_INTAB)
for n in ['x', 'y', 'flux']:
assert_allclose(outtab[n + '_0'], outtab[n + '_fit'],
rtol=0.05, atol=0.1)
| 37.496667 | 79 | 0.622189 |
import pytest
import numpy as np
from numpy.testing import assert_allclose, assert_array_equal, assert_equal
from astropy.convolution.utils import discretize_model
from astropy.modeling import Parameter, Fittable2DModel
from astropy.modeling.fitting import LevMarLSQFitter
from astropy.modeling.models import Gaussian2D, Moffat2D
from astropy.stats import gaussian_sigma_to_fwhm, SigmaClip
from astropy.table import Table
from astropy.tests.helper import catch_warnings
from astropy.utils.exceptions import AstropyUserWarning
from ..groupstars import DAOGroup
from ..models import IntegratedGaussianPRF
from ..photometry import (DAOPhotPSFPhotometry, BasicPSFPhotometry,
IterativelySubtractedPSFPhotometry)
from ..sandbox import DiscretePRF
from ..utils import prepare_psf_model
from ...background import StdBackgroundRMS, MMMBackground
from ...datasets import make_gaussian_prf_sources_image, make_noise_image
from ...detection import DAOStarFinder
try:
import scipy
HAS_SCIPY = True
except ImportError:
HAS_SCIPY = False
def make_psf_photometry_objs(std=1, sigma_psf=1):
daofind = DAOStarFinder(threshold=5.0*std,
fwhm=sigma_psf*gaussian_sigma_to_fwhm)
daogroup = DAOGroup(1.5*sigma_psf*gaussian_sigma_to_fwhm)
threshold = 5. * std
fwhm = sigma_psf * gaussian_sigma_to_fwhm
crit_separation = 1.5 * sigma_psf * gaussian_sigma_to_fwhm
daofind = DAOStarFinder(threshold=threshold, fwhm=fwhm)
daogroup = DAOGroup(crit_separation)
mode_bkg = MMMBackground()
psf_model = IntegratedGaussianPRF(sigma=sigma_psf)
fitter = LevMarLSQFitter()
basic_phot_obj = BasicPSFPhotometry(finder=daofind,
group_maker=daogroup,
bkg_estimator=mode_bkg,
psf_model=psf_model,
fitter=fitter,
fitshape=(11, 11))
iter_phot_obj = IterativelySubtractedPSFPhotometry(finder=daofind,
group_maker=daogroup,
bkg_estimator=mode_bkg,
psf_model=psf_model,
fitter=fitter, niters=1,
fitshape=(11, 11))
dao_phot_obj = DAOPhotPSFPhotometry(crit_separation=crit_separation,
threshold=threshold, fwhm=fwhm,
psf_model=psf_model, fitshape=(11, 11),
niters=1)
return (basic_phot_obj, iter_phot_obj, dao_phot_obj)
sigma_psfs = []
sigma_psfs.append(2)
sources1 = Table()
sources1['flux'] = [800, 1000, 1200]
sources1['x_0'] = [13, 18, 25]
sources1['y_0'] = [16, 16, 25]
sources1['sigma'] = [sigma_psfs[-1]] * 3
sources1['theta'] = [0] * 3
sources1['id'] = [1, 2, 3]
sources1['group_id'] = [1, 1, 2]
sigma_psfs.append(2)
sources2 = Table()
sources2['flux'] = [700, 800, 700, 800]
sources2['x_0'] = [12, 17, 12, 17]
sources2['y_0'] = [15, 15, 20, 20]
sources2['sigma'] = [sigma_psfs[-1]] * 4
sources2['theta'] = [0] * 4
sources2['id'] = [1, 2, 3, 4]
sources2['group_id'] = [1, 1, 1, 1]
sigma_psfs.append(2)
sources3 = Table()
sources3['flux'] = [10000, 1000]
sources3['x_0'] = [18, 13]
sources3['y_0'] = [17, 19]
sources3['sigma'] = [sigma_psfs[-1]] * 2
sources3['theta'] = [0] * 2
sources3['id'] = [1] * 2
sources3['group_id'] = [1] * 2
sources3['iter_detected'] = [1, 2]
@pytest.mark.skipif('not HAS_SCIPY')
@pytest.mark.parametrize("sigma_psf, sources", [(sigma_psfs[2], sources3)])
def test_psf_photometry_niters(sigma_psf, sources):
img_shape = (32, 32)
image = (make_gaussian_prf_sources_image(img_shape, sources) +
make_noise_image(img_shape, type='poisson', mean=6.,
random_state=1) +
make_noise_image(img_shape, type='gaussian', mean=0.,
stddev=2., random_state=1))
cp_image = image.copy()
sigma_clip = SigmaClip(sigma=3.)
bkgrms = StdBackgroundRMS(sigma_clip)
std = bkgrms(image)
phot_obj = make_psf_photometry_objs(std, sigma_psf)[1:3]
for iter_phot_obj in phot_obj:
iter_phot_obj.niters = None
result_tab = iter_phot_obj(image)
residual_image = iter_phot_obj.get_residual_image()
assert (result_tab['x_0_unc'] < 1.96 * sigma_psf /
np.sqrt(sources['flux'])).all()
assert (result_tab['y_0_unc'] < 1.96 * sigma_psf /
np.sqrt(sources['flux'])).all()
assert (result_tab['flux_unc'] < 1.96 *
np.sqrt(sources['flux'])).all()
assert_allclose(result_tab['x_fit'], sources['x_0'], rtol=1e-1)
assert_allclose(result_tab['y_fit'], sources['y_0'], rtol=1e-1)
assert_allclose(result_tab['flux_fit'], sources['flux'], rtol=1e-1)
assert_array_equal(result_tab['id'], sources['id'])
assert_array_equal(result_tab['group_id'], sources['group_id'])
assert_array_equal(result_tab['iter_detected'],
sources['iter_detected'])
assert_allclose(np.mean(residual_image), 0.0, atol=1e1)
assert_array_equal(cp_image, image)
@pytest.mark.skipif('not HAS_SCIPY')
@pytest.mark.parametrize("sigma_psf, sources",
[(sigma_psfs[0], sources1),
(sigma_psfs[1], sources2),
pytest.param(sigma_psfs[0]/1.2, sources1,
marks=pytest.mark.xfail()),
pytest.param(sigma_psfs[1]*1.2, sources2,
marks=pytest.mark.xfail())])
def test_psf_photometry_oneiter(sigma_psf, sources):
img_shape = (32, 32)
image = (make_gaussian_prf_sources_image(img_shape, sources) +
make_noise_image(img_shape, type='poisson', mean=6.,
random_state=1) +
make_noise_image(img_shape, type='gaussian', mean=0.,
stddev=2., random_state=1))
cp_image = image.copy()
sigma_clip = SigmaClip(sigma=3.)
bkgrms = StdBackgroundRMS(sigma_clip)
std = bkgrms(image)
phot_objs = make_psf_photometry_objs(std, sigma_psf)
for phot_proc in phot_objs:
result_tab = phot_proc(image)
residual_image = phot_proc.get_residual_image()
assert (result_tab['x_0_unc'] < 1.96 * sigma_psf /
np.sqrt(sources['flux'])).all()
assert (result_tab['y_0_unc'] < 1.96 * sigma_psf /
np.sqrt(sources['flux'])).all()
assert (result_tab['flux_unc'] < 1.96 *
np.sqrt(sources['flux'])).all()
assert_allclose(result_tab['x_fit'], sources['x_0'], rtol=1e-1)
assert_allclose(result_tab['y_fit'], sources['y_0'], rtol=1e-1)
assert_allclose(result_tab['flux_fit'], sources['flux'], rtol=1e-1)
assert_array_equal(result_tab['id'], sources['id'])
assert_array_equal(result_tab['group_id'], sources['group_id'])
assert_allclose(np.mean(residual_image), 0.0, atol=1e1)
phot_proc.psf_model.x_0.fixed = True
phot_proc.psf_model.y_0.fixed = True
pos = Table(names=['x_0', 'y_0'], data=[sources['x_0'],
sources['y_0']])
cp_pos = pos.copy()
result_tab = phot_proc(image, pos)
residual_image = phot_proc.get_residual_image()
assert 'x_0_unc' not in result_tab.colnames
assert 'y_0_unc' not in result_tab.colnames
assert (result_tab['flux_unc'] < 1.96 *
np.sqrt(sources['flux'])).all()
assert_array_equal(result_tab['x_fit'], sources['x_0'])
assert_array_equal(result_tab['y_fit'], sources['y_0'])
assert_allclose(result_tab['flux_fit'], sources['flux'], rtol=1e-1)
assert_array_equal(result_tab['id'], sources['id'])
assert_array_equal(result_tab['group_id'], sources['group_id'])
assert_allclose(np.mean(residual_image), 0.0, atol=1e1)
assert_array_equal(cp_image, image)
assert_array_equal(cp_pos, pos)
phot_proc.psf_model.x_0.fixed = False
phot_proc.psf_model.y_0.fixed = False
@pytest.mark.skipif('not HAS_SCIPY')
def test_niters_errors():
iter_phot_obj = make_psf_photometry_objs()[1]
iter_phot_obj.niters = 1.1
assert_equal(iter_phot_obj.niters, 1)
with pytest.raises(ValueError):
iter_phot_obj.niters = 0
iter_phot_obj.niters = None
@pytest.mark.skipif('not HAS_SCIPY')
def test_fitshape_errors():
basic_phot_obj = make_psf_photometry_objs()[0]
# first make sure setting to a scalar does the right thing (and makes
# no errors)
basic_phot_obj.fitshape = 11
assert np.all(basic_phot_obj.fitshape == (11, 11))
# test that a ValuError is raised if fitshape has even components
with pytest.raises(ValueError):
basic_phot_obj.fitshape = (2, 2)
with pytest.raises(ValueError):
basic_phot_obj.fitshape = 2
# test that a ValueError is raised if fitshape has non positive
# components
with pytest.raises(ValueError):
basic_phot_obj.fitshape = (-1, 0)
# test that a ValueError is raised if fitshape has more than two
# dimensions
with pytest.raises(ValueError):
basic_phot_obj.fitshape = (3, 3, 3)
@pytest.mark.skipif('not HAS_SCIPY')
def test_aperture_radius_errors():
basic_phot_obj = make_psf_photometry_objs()[0]
# test that aperture_radius was set to None by default
assert_equal(basic_phot_obj.aperture_radius, None)
# test that a ValueError is raised if aperture_radius is non positive
with pytest.raises(ValueError):
basic_phot_obj.aperture_radius = -3
@pytest.mark.skipif('not HAS_SCIPY')
def test_finder_errors():
iter_phot_obj = make_psf_photometry_objs()[1]
with pytest.raises(ValueError):
iter_phot_obj.finder = None
with pytest.raises(ValueError):
iter_phot_obj = IterativelySubtractedPSFPhotometry(
finder=None, group_maker=DAOGroup(1),
bkg_estimator=MMMBackground(),
psf_model=IntegratedGaussianPRF(1), fitshape=(11, 11))
@pytest.mark.skipif('not HAS_SCIPY')
def test_finder_positions_warning():
basic_phot_obj = make_psf_photometry_objs(sigma_psf=2)[0]
positions = Table()
positions['x_0'] = [12.8, 18.2, 25.3]
positions['y_0'] = [15.7, 16.5, 25.1]
image = (make_gaussian_prf_sources_image((32, 32), sources1) +
make_noise_image((32, 32), type='poisson', mean=6.,
random_state=1))
with catch_warnings(AstropyUserWarning):
result_tab = basic_phot_obj(image=image, init_guesses=positions)
assert_array_equal(result_tab['x_0'], positions['x_0'])
assert_array_equal(result_tab['y_0'], positions['y_0'])
assert_allclose(result_tab['x_fit'], positions['x_0'], rtol=1e-1)
assert_allclose(result_tab['y_fit'], positions['y_0'], rtol=1e-1)
with pytest.raises(ValueError):
basic_phot_obj.finder = None
result_tab = basic_phot_obj(image=image)
@pytest.mark.skipif('not HAS_SCIPY')
def test_aperture_radius():
img_shape = (32, 32)
# generate image with read-out noise (Gaussian) and
# background noise (Poisson)
image = (make_gaussian_prf_sources_image(img_shape, sources1) +
make_noise_image(img_shape, type='poisson', mean=6.,
random_state=1) +
make_noise_image(img_shape, type='gaussian', mean=0.,
stddev=2., random_state=1))
basic_phot_obj = make_psf_photometry_objs()[0]
# test that aperture radius is properly set whenever the PSF model has
# a `fwhm` attribute
class PSFModelWithFWHM(Fittable2DModel):
x_0 = Parameter(default=1)
y_0 = Parameter(default=1)
flux = Parameter(default=1)
fwhm = Parameter(default=5)
def __init__(self, fwhm=fwhm.default):
super().__init__(fwhm=fwhm)
def evaluate(self, x, y, x_0, y_0, flux, fwhm):
return flux / (fwhm * (x - x_0)**2 * (y - y_0)**2)
psf_model = PSFModelWithFWHM()
basic_phot_obj.psf_model = psf_model
basic_phot_obj(image)
assert_equal(basic_phot_obj.aperture_radius, psf_model.fwhm.value)
PARS_TO_SET_0 = {'x_0': 'x_0', 'y_0': 'y_0', 'flux_0': 'flux'}
PARS_TO_OUTPUT_0 = {'x_fit': 'x_0', 'y_fit': 'y_0', 'flux_fit': 'flux'}
PARS_TO_SET_1 = PARS_TO_SET_0.copy()
PARS_TO_SET_1['sigma_0'] = 'sigma'
PARS_TO_OUTPUT_1 = PARS_TO_OUTPUT_0.copy()
PARS_TO_OUTPUT_1['sigma_fit'] = 'sigma'
@pytest.mark.parametrize("actual_pars_to_set, actual_pars_to_output,"
"is_sigma_fixed", [(PARS_TO_SET_0, PARS_TO_OUTPUT_0,
True),
(PARS_TO_SET_1, PARS_TO_OUTPUT_1,
False)])
@pytest.mark.skipif('not HAS_SCIPY')
def test_define_fit_param_names(actual_pars_to_set, actual_pars_to_output,
is_sigma_fixed):
psf_model = IntegratedGaussianPRF()
psf_model.sigma.fixed = is_sigma_fixed
basic_phot_obj = make_psf_photometry_objs()[0]
basic_phot_obj.psf_model = psf_model
basic_phot_obj._define_fit_param_names()
assert_equal(basic_phot_obj._pars_to_set, actual_pars_to_set)
assert_equal(basic_phot_obj._pars_to_output, actual_pars_to_output)
# tests previously written to psf_photometry
PSF_SIZE = 11
GAUSSIAN_WIDTH = 1.
IMAGE_SIZE = 101
# Position and FLUXES of test sources
INTAB = Table([[50., 23, 12, 86], [50., 83, 80, 84],
[np.pi * 10, 3.654, 20., 80 / np.sqrt(3)]],
names=['x_0', 'y_0', 'flux_0'])
# Create test psf
psf_model = Gaussian2D(1. / (2 * np.pi * GAUSSIAN_WIDTH ** 2), PSF_SIZE // 2,
PSF_SIZE // 2, GAUSSIAN_WIDTH, GAUSSIAN_WIDTH)
test_psf = discretize_model(psf_model, (0, PSF_SIZE), (0, PSF_SIZE),
mode='oversample')
# Set up grid for test image
image = np.zeros((IMAGE_SIZE, IMAGE_SIZE))
# Add sources to test image
for x, y, flux in INTAB:
model = Gaussian2D(flux / (2 * np.pi * GAUSSIAN_WIDTH ** 2),
x, y, GAUSSIAN_WIDTH, GAUSSIAN_WIDTH)
image += discretize_model(model, (0, IMAGE_SIZE), (0, IMAGE_SIZE),
mode='oversample')
# Some tests require an image with wider sources.
WIDE_GAUSSIAN_WIDTH = 3.
WIDE_INTAB = Table([[50, 23.2], [50.5, 1], [10, 20]],
names=['x_0', 'y_0', 'flux_0'])
wide_image = np.zeros((IMAGE_SIZE, IMAGE_SIZE))
# Add sources to test image
for x, y, flux in WIDE_INTAB:
model = Gaussian2D(flux / (2 * np.pi * WIDE_GAUSSIAN_WIDTH ** 2),
x, y, WIDE_GAUSSIAN_WIDTH, WIDE_GAUSSIAN_WIDTH)
wide_image += discretize_model(model, (0, IMAGE_SIZE), (0, IMAGE_SIZE),
mode='oversample')
@pytest.mark.skipif('not HAS_SCIPY')
def test_psf_photometry_discrete():
prf = DiscretePRF(test_psf, subsampling=1)
basic_phot = BasicPSFPhotometry(group_maker=DAOGroup(2),
bkg_estimator=None, psf_model=prf,
fitshape=7)
f = basic_phot(image=image, init_guesses=INTAB)
for n in ['x', 'y', 'flux']:
assert_allclose(f[n + '_0'], f[n + '_fit'], rtol=1e-6)
@pytest.mark.skipif('not HAS_SCIPY')
def test_tune_coordinates():
prf = DiscretePRF(test_psf, subsampling=1)
prf.x_0.fixed = False
prf.y_0.fixed = False
# Shift all sources by 0.3 pixels
intab = INTAB.copy()
intab['x_0'] += 0.3
basic_phot = BasicPSFPhotometry(group_maker=DAOGroup(2),
bkg_estimator=None, psf_model=prf,
fitshape=7)
f = basic_phot(image=image, init_guesses=intab)
for n in ['x', 'y', 'flux']:
assert_allclose(f[n + '_0'], f[n + '_fit'], rtol=1e-3)
@pytest.mark.skipif('not HAS_SCIPY')
def test_psf_boundary():
prf = DiscretePRF(test_psf, subsampling=1)
basic_phot = BasicPSFPhotometry(group_maker=DAOGroup(2),
bkg_estimator=None, psf_model=prf,
fitshape=7, aperture_radius=5.5)
intab = Table(data=[[1], [1]], names=['x_0', 'y_0'])
f = basic_phot(image=image, init_guesses=intab)
assert_allclose(f['flux_fit'], 0, atol=1e-8)
@pytest.mark.skipif('not HAS_SCIPY')
def test_aperture_radius_value_error():
prf = DiscretePRF(test_psf, subsampling=1)
basic_phot = BasicPSFPhotometry(group_maker=DAOGroup(2),
bkg_estimator=None, psf_model=prf,
fitshape=7)
intab = Table(data=[[1], [1]], names=['x_0', 'y_0'])
with pytest.raises(ValueError) as err:
basic_phot(image=image, init_guesses=intab)
assert 'aperture_radius is None' in str(err.value)
@pytest.mark.skipif('not HAS_SCIPY')
def test_psf_boundary_gaussian():
psf = IntegratedGaussianPRF(GAUSSIAN_WIDTH)
basic_phot = BasicPSFPhotometry(group_maker=DAOGroup(2),
bkg_estimator=None, psf_model=psf,
fitshape=7)
intab = Table(data=[[1], [1]], names=['x_0', 'y_0'])
f = basic_phot(image=image, init_guesses=intab)
assert_allclose(f['flux_fit'], 0, atol=1e-8)
@pytest.mark.skipif('not HAS_SCIPY')
def test_psf_photometry_gaussian():
psf = IntegratedGaussianPRF(sigma=GAUSSIAN_WIDTH)
basic_phot = BasicPSFPhotometry(group_maker=DAOGroup(2),
bkg_estimator=None, psf_model=psf,
fitshape=7)
f = basic_phot(image=image, init_guesses=INTAB)
for n in ['x', 'y', 'flux']:
assert_allclose(f[n + '_0'], f[n + '_fit'], rtol=1e-3)
@pytest.mark.skipif('not HAS_SCIPY')
@pytest.mark.parametrize("renormalize_psf", (True, False))
def test_psf_photometry_gaussian2(renormalize_psf):
psf = Gaussian2D(1. / (2 * np.pi * GAUSSIAN_WIDTH ** 2), PSF_SIZE // 2,
PSF_SIZE // 2, GAUSSIAN_WIDTH, GAUSSIAN_WIDTH)
psf = prepare_psf_model(psf, xname='x_mean', yname='y_mean',
renormalize_psf=renormalize_psf)
basic_phot = BasicPSFPhotometry(group_maker=DAOGroup(2),
bkg_estimator=None, psf_model=psf,
fitshape=7)
f = basic_phot(image=image, init_guesses=INTAB)
for n in ['x', 'y']:
assert_allclose(f[n + '_0'], f[n + '_fit'], rtol=1e-1)
assert_allclose(f['flux_0'], f['flux_fit'], rtol=1e-1)
@pytest.mark.skipif('not HAS_SCIPY')
def test_psf_photometry_moffat():
psf = Moffat2D(1. / (2 * np.pi * GAUSSIAN_WIDTH ** 2), PSF_SIZE // 2,
PSF_SIZE // 2, 1, 1)
psf = prepare_psf_model(psf, xname='x_0', yname='y_0',
renormalize_psf=False)
basic_phot = BasicPSFPhotometry(group_maker=DAOGroup(2),
bkg_estimator=None, psf_model=psf,
fitshape=7)
f = basic_phot(image=image, init_guesses=INTAB)
f.pprint(max_width=-1)
for n in ['x', 'y']:
assert_allclose(f[n + '_0'], f[n + '_fit'], rtol=1e-3)
# image was created with a gaussian, so flux won't match exactly
assert_allclose(f['flux_0'], f['flux_fit'], rtol=1e-1)
@pytest.mark.skipif('not HAS_SCIPY')
def test_psf_fitting_data_on_edge():
psf_guess = IntegratedGaussianPRF(flux=1, sigma=WIDE_GAUSSIAN_WIDTH)
psf_guess.flux.fixed = psf_guess.x_0.fixed = psf_guess.y_0.fixed = False
basic_phot = BasicPSFPhotometry(group_maker=DAOGroup(2),
bkg_estimator=None, psf_model=psf_guess,
fitshape=7)
outtab = basic_phot(image=wide_image, init_guesses=WIDE_INTAB)
for n in ['x', 'y', 'flux']:
assert_allclose(outtab[n + '_0'], outtab[n + '_fit'],
rtol=0.05, atol=0.1)
| true | true |
f7f923ba2aef1be38b7b79a65357cb7ea026281c | 16,018 | py | Python | tests/contrib/gp/test_models.py | gavincangan/pyro | d9115a6da7edd7e3fecd6b89a850cc137d7e7e9a | [
"MIT"
] | null | null | null | tests/contrib/gp/test_models.py | gavincangan/pyro | d9115a6da7edd7e3fecd6b89a850cc137d7e7e9a | [
"MIT"
] | 4 | 2019-01-31T17:54:03.000Z | 2019-02-07T07:09:51.000Z | tests/contrib/gp/test_models.py | gavincangan/pyro | d9115a6da7edd7e3fecd6b89a850cc137d7e7e9a | [
"MIT"
] | null | null | null | from __future__ import absolute_import, division, print_function
import logging
from collections import defaultdict, namedtuple
import pytest
import torch
import pyro.distributions as dist
from pyro.contrib.gp.kernels import Cosine, Matern32, RBF, WhiteNoise
from pyro.contrib.gp.likelihoods import Gaussian
from pyro.contrib.gp.models import (GPLVM, GPRegression, SparseGPRegression,
VariationalGP, VariationalSparseGP)
from pyro.contrib.gp.util import train
from pyro.infer.mcmc.hmc import HMC
from pyro.infer.mcmc.mcmc import MCMC
from tests.common import assert_equal
logger = logging.getLogger(__name__)
T = namedtuple("TestGPModel", ["model_class", "X", "y", "kernel", "likelihood"])
X = torch.tensor([[1., 5., 3.], [4., 3., 7.]])
y1D = torch.tensor([2., 1.])
y2D = torch.tensor([[1., 2.], [3., 3.], [1., 4.], [-1., 1.]])
noise = torch.tensor(1e-7)
def _kernel():
return RBF(input_dim=3, variance=torch.tensor(3.), lengthscale=torch.tensor(2.))
def _likelihood():
return Gaussian(torch.tensor(1e-7))
def _TEST_CASES():
TEST_CASES = [
T(
GPRegression,
X, y1D, _kernel(), noise
),
T(
GPRegression,
X, y2D, _kernel(), noise
),
T(
SparseGPRegression,
X, y1D, _kernel(), noise
),
T(
SparseGPRegression,
X, y2D, _kernel(), noise
),
T(
VariationalGP,
X, y1D, _kernel(), _likelihood()
),
T(
VariationalGP,
X, y2D, _kernel(), _likelihood()
),
T(
VariationalSparseGP,
X, y1D, _kernel(), _likelihood()
),
T(
VariationalSparseGP,
X, y2D, _kernel(), _likelihood()
),
]
return TEST_CASES
TEST_IDS = [t[0].__name__ + "_y{}D".format(str(t[2].dim()))
for t in _TEST_CASES()]
@pytest.mark.parametrize("model_class, X, y, kernel, likelihood", _TEST_CASES(), ids=TEST_IDS)
def test_model(model_class, X, y, kernel, likelihood):
if model_class is SparseGPRegression or model_class is VariationalSparseGP:
gp = model_class(X, None, kernel, X, likelihood)
else:
gp = model_class(X, None, kernel, likelihood)
loc, var = gp.model()
if model_class is VariationalGP or model_class is VariationalSparseGP:
assert_equal(loc.norm().item(), 0)
assert_equal(var, torch.ones(var.shape[-1]).expand(var.shape))
else:
assert_equal(loc.norm().item(), 0)
assert_equal(var, kernel(X).diag())
@pytest.mark.parametrize("model_class, X, y, kernel, likelihood", _TEST_CASES(), ids=TEST_IDS)
def test_forward(model_class, X, y, kernel, likelihood):
if model_class is SparseGPRegression or model_class is VariationalSparseGP:
gp = model_class(X, y, kernel, X, likelihood)
else:
gp = model_class(X, y, kernel, likelihood)
# test shape
Xnew = torch.tensor([[2.0, 3.0, 1.0]])
loc0, cov0 = gp(Xnew, full_cov=True)
loc1, var1 = gp(Xnew, full_cov=False)
assert loc0.dim() == y.dim()
assert loc0.shape[-1] == Xnew.shape[0]
# test latent shape
assert loc0.shape[:-1] == y.shape[:-1]
assert cov0.shape[:-2] == y.shape[:-1]
assert cov0.shape[-1] == cov0.shape[-2]
assert cov0.shape[-1] == Xnew.shape[0]
assert_equal(loc0, loc1)
n = Xnew.shape[0]
cov0_diag = torch.stack([mat.diag() for mat in cov0.view(-1, n, n)]).reshape(var1.shape)
assert_equal(cov0_diag, var1)
# test trivial forward: Xnew = X
loc, cov = gp(X, full_cov=True)
if model_class is VariationalGP or model_class is VariationalSparseGP:
assert_equal(loc.norm().item(), 0)
assert_equal(cov, torch.eye(cov.shape[-1]).expand(cov.shape))
else:
assert_equal(loc, y)
assert_equal(cov.norm().item(), 0)
# test same input forward: Xnew[0,:] = Xnew[1,:] = ...
Xnew = torch.tensor([[2.0, 3.0, 1.0]]).expand(10, 3)
loc, cov = gp(Xnew, full_cov=True)
loc_diff = loc - loc[..., :1].expand(y.shape[:-1] + (10,))
assert_equal(loc_diff.norm().item(), 0)
cov_diff = cov - cov[..., :1, :1].expand(y.shape[:-1] + (10, 10))
assert_equal(cov_diff.norm().item(), 0)
# test noise kernel forward: kernel = WhiteNoise
gp.kernel = WhiteNoise(input_dim=3, variance=torch.tensor(10.))
loc, cov = gp(X, full_cov=True)
assert_equal(loc.norm().item(), 0)
assert_equal(cov, torch.eye(cov.shape[-1]).expand(cov.shape) * 10)
@pytest.mark.parametrize("model_class, X, y, kernel, likelihood", _TEST_CASES(), ids=TEST_IDS)
def test_forward_with_empty_latent_shape(model_class, X, y, kernel, likelihood):
# regression models don't use latent_shape, no need for test
if model_class is GPRegression or model_class is SparseGPRegression:
return
elif model_class is VariationalGP:
gp = model_class(X, y, kernel, likelihood, latent_shape=torch.Size([]))
else: # model_class is VariationalSparseGP
gp = model_class(X, y, kernel, X, likelihood, latent_shape=torch.Size([]))
# test shape
Xnew = torch.tensor([[2.0, 3.0, 1.0]])
loc0, cov0 = gp(Xnew, full_cov=True)
loc1, var1 = gp(Xnew, full_cov=False)
assert loc0.shape[-1] == Xnew.shape[0]
assert cov0.shape[-1] == cov0.shape[-2]
assert cov0.shape[-1] == Xnew.shape[0]
# test latent shape
assert loc0.shape[:-1] == torch.Size([])
assert cov0.shape[:-2] == torch.Size([])
assert_equal(loc0, loc1)
assert_equal(cov0.diag(), var1)
@pytest.mark.parametrize("model_class, X, y, kernel, likelihood", _TEST_CASES(), ids=TEST_IDS)
@pytest.mark.init(rng_seed=0)
def test_inference(model_class, X, y, kernel, likelihood):
# skip variational GP models because variance/lengthscale highly
# depend on variational parameters
if model_class is VariationalGP or model_class is VariationalSparseGP:
return
elif model_class is GPRegression:
gp = model_class(X, y, RBF(input_dim=3), likelihood)
else: # model_class is SparseGPRegression
gp = model_class(X, y, RBF(input_dim=3), X, likelihood)
# fix inducing points because variance/lengthscale highly depend on it
gp.Xu.requires_grad_(False)
generator = dist.MultivariateNormal(torch.zeros(X.shape[0]), kernel(X))
target_y = generator(sample_shape=torch.Size([1000])).detach()
gp.set_data(X, target_y)
train(gp)
y_cov = gp.kernel(X)
target_y_cov = kernel(X)
assert_equal(y_cov, target_y_cov, prec=0.1)
@pytest.mark.init(rng_seed=0)
def test_inference_sgpr():
N = 1000
X = dist.Uniform(torch.zeros(N), torch.ones(N)*5).sample()
y = 0.5 * torch.sin(3*X) + dist.Normal(torch.zeros(N), torch.ones(N)*0.5).sample()
kernel = RBF(input_dim=1)
Xu = torch.arange(0., 5.5, 0.5)
sgpr = SparseGPRegression(X, y, kernel, Xu)
train(sgpr)
Xnew = torch.arange(0., 5.05, 0.05)
loc, var = sgpr(Xnew, full_cov=False)
target = 0.5 * torch.sin(3*Xnew)
assert_equal((loc - target).abs().mean().item(), 0, prec=0.07)
@pytest.mark.init(rng_seed=0)
def test_inference_vsgp():
N = 1000
X = dist.Uniform(torch.zeros(N), torch.ones(N)*5).sample()
y = 0.5 * torch.sin(3*X) + dist.Normal(torch.zeros(N), torch.ones(N)*0.5).sample()
kernel = RBF(input_dim=1)
Xu = torch.arange(0., 5.5, 0.5)
vsgp = VariationalSparseGP(X, y, kernel, Xu, Gaussian())
optimizer = torch.optim.Adam(vsgp.parameters(), lr=0.03)
train(vsgp, optimizer)
Xnew = torch.arange(0., 5.05, 0.05)
loc, var = vsgp(Xnew, full_cov=False)
target = 0.5 * torch.sin(3*Xnew)
assert_equal((loc - target).abs().mean().item(), 0, prec=0.06)
@pytest.mark.init(rng_seed=0)
def test_inference_whiten_vsgp():
N = 1000
X = dist.Uniform(torch.zeros(N), torch.ones(N)*5).sample()
y = 0.5 * torch.sin(3*X) + dist.Normal(torch.zeros(N), torch.ones(N)*0.5).sample()
kernel = RBF(input_dim=1)
Xu = torch.arange(0., 5.5, 0.5)
vsgp = VariationalSparseGP(X, y, kernel, Xu, Gaussian(), whiten=True)
train(vsgp)
Xnew = torch.arange(0., 5.05, 0.05)
loc, var = vsgp(Xnew, full_cov=False)
target = 0.5 * torch.sin(3*Xnew)
assert_equal((loc - target).abs().mean().item(), 0, prec=0.07)
@pytest.mark.parametrize("model_class, X, y, kernel, likelihood", _TEST_CASES(), ids=TEST_IDS)
def test_inference_with_empty_latent_shape(model_class, X, y, kernel, likelihood):
# regression models don't use latent_shape (default=torch.Size([]))
if model_class is GPRegression or model_class is SparseGPRegression:
return
elif model_class is VariationalGP:
gp = model_class(X, y, kernel, likelihood, latent_shape=torch.Size([]))
else: # model_class is SparseVariationalGP
gp = model_class(X, y, kernel, X.clone(), likelihood, latent_shape=torch.Size([]))
train(gp, num_steps=1)
@pytest.mark.parametrize("model_class, X, y, kernel, likelihood", _TEST_CASES(), ids=TEST_IDS)
def test_inference_with_whiten(model_class, X, y, kernel, likelihood):
# regression models don't use whiten
if model_class is GPRegression or model_class is SparseGPRegression:
return
elif model_class is VariationalGP:
gp = model_class(X, y, kernel, likelihood, whiten=True)
else: # model_class is SparseVariationalGP
gp = model_class(X, y, kernel, X.clone(), likelihood, whiten=True)
train(gp, num_steps=1)
@pytest.mark.parametrize("model_class, X, y, kernel, likelihood", _TEST_CASES(), ids=TEST_IDS)
def test_hmc(model_class, X, y, kernel, likelihood):
if model_class is SparseGPRegression or model_class is VariationalSparseGP:
gp = model_class(X, y, kernel, X.clone(), likelihood)
else:
gp = model_class(X, y, kernel, likelihood)
if model_class is GPRegression:
model_name = "GPR"
elif model_class is SparseGPRegression:
model_name = "SGPR"
elif model_class is VariationalGP:
model_name = "VGP"
else:
model_name = "VSGP"
kernel.set_prior("variance", dist.Uniform(torch.tensor(0.5), torch.tensor(1.5)))
kernel.set_prior("lengthscale", dist.Uniform(torch.tensor(1.0), torch.tensor(3.0)))
hmc_kernel = HMC(gp.model, step_size=1)
mcmc_run = MCMC(hmc_kernel, num_samples=10)
post_trace = defaultdict(list)
for trace, _ in mcmc_run._traces():
variance_name = "{}/RBF/variance".format(model_name)
post_trace["variance"].append(trace.nodes[variance_name]["value"])
lengthscale_name = "{}/RBF/lengthscale".format(model_name)
post_trace["lengthscale"].append(trace.nodes[lengthscale_name]["value"])
if model_class is VariationalGP:
f_name = "VGP/f"
post_trace["f"].append(trace.nodes[f_name]["value"])
if model_class is VariationalSparseGP:
u_name = "VSGP/u"
post_trace["u"].append(trace.nodes[u_name]["value"])
for param in post_trace:
param_mean = torch.mean(torch.stack(post_trace[param]), 0)
logger.info("Posterior mean - {}".format(param))
logger.info(param_mean)
def test_inference_deepGP():
gp1 = GPRegression(X, None, RBF(input_dim=3, variance=torch.tensor(3.),
lengthscale=torch.tensor(2.)))
Z, _ = gp1.model()
gp2 = VariationalSparseGP(Z, y2D, Matern32(input_dim=3), Z.clone(),
Gaussian(torch.tensor(1e-6)))
class DeepGP(torch.nn.Module):
def __init__(self, gp1, gp2):
super(DeepGP, self).__init__()
self.gp1 = gp1
self.gp2 = gp2
def model(self):
Z, _ = self.gp1.model()
self.gp2.set_data(Z, y2D)
self.gp2.model()
def guide(self):
self.gp1.guide()
self.gp2.guide()
deepgp = DeepGP(gp1, gp2)
train(deepgp, num_steps=1)
@pytest.mark.parametrize("model_class, X, y, kernel, likelihood", _TEST_CASES(), ids=TEST_IDS)
def test_gplvm(model_class, X, y, kernel, likelihood):
if model_class is SparseGPRegression or model_class is VariationalSparseGP:
gp = model_class(X, y, kernel, X.clone(), likelihood)
else:
gp = model_class(X, y, kernel, likelihood)
gplvm = GPLVM(gp)
# test inference
train(gplvm, num_steps=1)
# test forward
gplvm(Xnew=X)
def _pre_test_mean_function():
def f(x):
return 2 * x + 3 + 5 * torch.sin(7 * x)
X = torch.arange(100, dtype=torch.Tensor().dtype)
y = f(X)
Xnew = torch.arange(100, 150, dtype=torch.Tensor().dtype)
ynew = f(Xnew)
kernel = Cosine(input_dim=1)
class Trend(torch.nn.Module):
def __init__(self):
super(Trend, self).__init__()
self.a = torch.nn.Parameter(torch.tensor(0.))
self.b = torch.nn.Parameter(torch.tensor(1.))
def forward(self, x):
return self.a * x + self.b
trend = Trend()
return X, y, Xnew, ynew, kernel, trend
def _mape(y_true, y_pred):
return ((y_pred - y_true) / y_true).abs().mean()
def _post_test_mean_function(gpmodule, Xnew, y_true):
assert_equal(gpmodule.mean_function.a.item(), 2, prec=0.02)
assert_equal(gpmodule.mean_function.b.item(), 3, prec=0.02)
y_pred, _ = gpmodule(Xnew)
assert_equal(_mape(y_true, y_pred).item(), 0, prec=0.02)
def test_mean_function_GPR():
X, y, Xnew, ynew, kernel, mean_fn = _pre_test_mean_function()
gpmodule = GPRegression(X, y, kernel, mean_function=mean_fn)
train(gpmodule)
_post_test_mean_function(gpmodule, Xnew, ynew)
def test_mean_function_SGPR():
X, y, Xnew, ynew, kernel, mean_fn = _pre_test_mean_function()
Xu = X[::20].clone()
gpmodule = SparseGPRegression(X, y, kernel, Xu, mean_function=mean_fn)
train(gpmodule)
_post_test_mean_function(gpmodule, Xnew, ynew)
def test_mean_function_SGPR_DTC():
X, y, Xnew, ynew, kernel, mean_fn = _pre_test_mean_function()
Xu = X[::20].clone()
gpmodule = SparseGPRegression(X, y, kernel, Xu, mean_function=mean_fn, approx="DTC")
train(gpmodule)
_post_test_mean_function(gpmodule, Xnew, ynew)
def test_mean_function_SGPR_FITC():
X, y, Xnew, ynew, kernel, mean_fn = _pre_test_mean_function()
Xu = X[::20].clone()
gpmodule = SparseGPRegression(X, y, kernel, Xu, mean_function=mean_fn, approx="FITC")
train(gpmodule)
_post_test_mean_function(gpmodule, Xnew, ynew)
def test_mean_function_VGP():
X, y, Xnew, ynew, kernel, mean_fn = _pre_test_mean_function()
likelihood = Gaussian()
gpmodule = VariationalGP(X, y, kernel, likelihood, mean_function=mean_fn)
train(gpmodule)
_post_test_mean_function(gpmodule, Xnew, ynew)
def test_mean_function_VGP_whiten():
X, y, Xnew, ynew, kernel, mean_fn = _pre_test_mean_function()
likelihood = Gaussian()
gpmodule = VariationalGP(X, y, kernel, likelihood, mean_function=mean_fn,
whiten=True)
optimizer = torch.optim.Adam(gpmodule.parameters(), lr=0.1)
train(gpmodule, optimizer)
_post_test_mean_function(gpmodule, Xnew, ynew)
def test_mean_function_VSGP():
X, y, Xnew, ynew, kernel, mean_fn = _pre_test_mean_function()
Xu = X[::20].clone()
likelihood = Gaussian()
gpmodule = VariationalSparseGP(X, y, kernel, Xu, likelihood, mean_function=mean_fn)
optimizer = torch.optim.Adam(gpmodule.parameters(), lr=0.02)
train(gpmodule, optimizer)
_post_test_mean_function(gpmodule, Xnew, ynew)
def test_mean_function_VSGP_whiten():
X, y, Xnew, ynew, kernel, mean_fn = _pre_test_mean_function()
Xu = X[::20].clone()
likelihood = Gaussian()
gpmodule = VariationalSparseGP(X, y, kernel, Xu, likelihood, mean_function=mean_fn,
whiten=True)
optimizer = torch.optim.Adam(gpmodule.parameters(), lr=0.1)
train(gpmodule, optimizer)
_post_test_mean_function(gpmodule, Xnew, ynew)
| 34.973799 | 94 | 0.648021 | from __future__ import absolute_import, division, print_function
import logging
from collections import defaultdict, namedtuple
import pytest
import torch
import pyro.distributions as dist
from pyro.contrib.gp.kernels import Cosine, Matern32, RBF, WhiteNoise
from pyro.contrib.gp.likelihoods import Gaussian
from pyro.contrib.gp.models import (GPLVM, GPRegression, SparseGPRegression,
VariationalGP, VariationalSparseGP)
from pyro.contrib.gp.util import train
from pyro.infer.mcmc.hmc import HMC
from pyro.infer.mcmc.mcmc import MCMC
from tests.common import assert_equal
logger = logging.getLogger(__name__)
T = namedtuple("TestGPModel", ["model_class", "X", "y", "kernel", "likelihood"])
X = torch.tensor([[1., 5., 3.], [4., 3., 7.]])
y1D = torch.tensor([2., 1.])
y2D = torch.tensor([[1., 2.], [3., 3.], [1., 4.], [-1., 1.]])
noise = torch.tensor(1e-7)
def _kernel():
return RBF(input_dim=3, variance=torch.tensor(3.), lengthscale=torch.tensor(2.))
def _likelihood():
return Gaussian(torch.tensor(1e-7))
def _TEST_CASES():
TEST_CASES = [
T(
GPRegression,
X, y1D, _kernel(), noise
),
T(
GPRegression,
X, y2D, _kernel(), noise
),
T(
SparseGPRegression,
X, y1D, _kernel(), noise
),
T(
SparseGPRegression,
X, y2D, _kernel(), noise
),
T(
VariationalGP,
X, y1D, _kernel(), _likelihood()
),
T(
VariationalGP,
X, y2D, _kernel(), _likelihood()
),
T(
VariationalSparseGP,
X, y1D, _kernel(), _likelihood()
),
T(
VariationalSparseGP,
X, y2D, _kernel(), _likelihood()
),
]
return TEST_CASES
TEST_IDS = [t[0].__name__ + "_y{}D".format(str(t[2].dim()))
for t in _TEST_CASES()]
@pytest.mark.parametrize("model_class, X, y, kernel, likelihood", _TEST_CASES(), ids=TEST_IDS)
def test_model(model_class, X, y, kernel, likelihood):
if model_class is SparseGPRegression or model_class is VariationalSparseGP:
gp = model_class(X, None, kernel, X, likelihood)
else:
gp = model_class(X, None, kernel, likelihood)
loc, var = gp.model()
if model_class is VariationalGP or model_class is VariationalSparseGP:
assert_equal(loc.norm().item(), 0)
assert_equal(var, torch.ones(var.shape[-1]).expand(var.shape))
else:
assert_equal(loc.norm().item(), 0)
assert_equal(var, kernel(X).diag())
@pytest.mark.parametrize("model_class, X, y, kernel, likelihood", _TEST_CASES(), ids=TEST_IDS)
def test_forward(model_class, X, y, kernel, likelihood):
if model_class is SparseGPRegression or model_class is VariationalSparseGP:
gp = model_class(X, y, kernel, X, likelihood)
else:
gp = model_class(X, y, kernel, likelihood)
Xnew = torch.tensor([[2.0, 3.0, 1.0]])
loc0, cov0 = gp(Xnew, full_cov=True)
loc1, var1 = gp(Xnew, full_cov=False)
assert loc0.dim() == y.dim()
assert loc0.shape[-1] == Xnew.shape[0]
assert loc0.shape[:-1] == y.shape[:-1]
assert cov0.shape[:-2] == y.shape[:-1]
assert cov0.shape[-1] == cov0.shape[-2]
assert cov0.shape[-1] == Xnew.shape[0]
assert_equal(loc0, loc1)
n = Xnew.shape[0]
cov0_diag = torch.stack([mat.diag() for mat in cov0.view(-1, n, n)]).reshape(var1.shape)
assert_equal(cov0_diag, var1)
loc, cov = gp(X, full_cov=True)
if model_class is VariationalGP or model_class is VariationalSparseGP:
assert_equal(loc.norm().item(), 0)
assert_equal(cov, torch.eye(cov.shape[-1]).expand(cov.shape))
else:
assert_equal(loc, y)
assert_equal(cov.norm().item(), 0)
Xnew = torch.tensor([[2.0, 3.0, 1.0]]).expand(10, 3)
loc, cov = gp(Xnew, full_cov=True)
loc_diff = loc - loc[..., :1].expand(y.shape[:-1] + (10,))
assert_equal(loc_diff.norm().item(), 0)
cov_diff = cov - cov[..., :1, :1].expand(y.shape[:-1] + (10, 10))
assert_equal(cov_diff.norm().item(), 0)
gp.kernel = WhiteNoise(input_dim=3, variance=torch.tensor(10.))
loc, cov = gp(X, full_cov=True)
assert_equal(loc.norm().item(), 0)
assert_equal(cov, torch.eye(cov.shape[-1]).expand(cov.shape) * 10)
@pytest.mark.parametrize("model_class, X, y, kernel, likelihood", _TEST_CASES(), ids=TEST_IDS)
def test_forward_with_empty_latent_shape(model_class, X, y, kernel, likelihood):
if model_class is GPRegression or model_class is SparseGPRegression:
return
elif model_class is VariationalGP:
gp = model_class(X, y, kernel, likelihood, latent_shape=torch.Size([]))
else: # model_class is VariationalSparseGP
gp = model_class(X, y, kernel, X, likelihood, latent_shape=torch.Size([]))
# test shape
Xnew = torch.tensor([[2.0, 3.0, 1.0]])
loc0, cov0 = gp(Xnew, full_cov=True)
loc1, var1 = gp(Xnew, full_cov=False)
assert loc0.shape[-1] == Xnew.shape[0]
assert cov0.shape[-1] == cov0.shape[-2]
assert cov0.shape[-1] == Xnew.shape[0]
# test latent shape
assert loc0.shape[:-1] == torch.Size([])
assert cov0.shape[:-2] == torch.Size([])
assert_equal(loc0, loc1)
assert_equal(cov0.diag(), var1)
@pytest.mark.parametrize("model_class, X, y, kernel, likelihood", _TEST_CASES(), ids=TEST_IDS)
@pytest.mark.init(rng_seed=0)
def test_inference(model_class, X, y, kernel, likelihood):
# skip variational GP models because variance/lengthscale highly
# depend on variational parameters
if model_class is VariationalGP or model_class is VariationalSparseGP:
return
elif model_class is GPRegression:
gp = model_class(X, y, RBF(input_dim=3), likelihood)
else: # model_class is SparseGPRegression
gp = model_class(X, y, RBF(input_dim=3), X, likelihood)
# fix inducing points because variance/lengthscale highly depend on it
gp.Xu.requires_grad_(False)
generator = dist.MultivariateNormal(torch.zeros(X.shape[0]), kernel(X))
target_y = generator(sample_shape=torch.Size([1000])).detach()
gp.set_data(X, target_y)
train(gp)
y_cov = gp.kernel(X)
target_y_cov = kernel(X)
assert_equal(y_cov, target_y_cov, prec=0.1)
@pytest.mark.init(rng_seed=0)
def test_inference_sgpr():
N = 1000
X = dist.Uniform(torch.zeros(N), torch.ones(N)*5).sample()
y = 0.5 * torch.sin(3*X) + dist.Normal(torch.zeros(N), torch.ones(N)*0.5).sample()
kernel = RBF(input_dim=1)
Xu = torch.arange(0., 5.5, 0.5)
sgpr = SparseGPRegression(X, y, kernel, Xu)
train(sgpr)
Xnew = torch.arange(0., 5.05, 0.05)
loc, var = sgpr(Xnew, full_cov=False)
target = 0.5 * torch.sin(3*Xnew)
assert_equal((loc - target).abs().mean().item(), 0, prec=0.07)
@pytest.mark.init(rng_seed=0)
def test_inference_vsgp():
N = 1000
X = dist.Uniform(torch.zeros(N), torch.ones(N)*5).sample()
y = 0.5 * torch.sin(3*X) + dist.Normal(torch.zeros(N), torch.ones(N)*0.5).sample()
kernel = RBF(input_dim=1)
Xu = torch.arange(0., 5.5, 0.5)
vsgp = VariationalSparseGP(X, y, kernel, Xu, Gaussian())
optimizer = torch.optim.Adam(vsgp.parameters(), lr=0.03)
train(vsgp, optimizer)
Xnew = torch.arange(0., 5.05, 0.05)
loc, var = vsgp(Xnew, full_cov=False)
target = 0.5 * torch.sin(3*Xnew)
assert_equal((loc - target).abs().mean().item(), 0, prec=0.06)
@pytest.mark.init(rng_seed=0)
def test_inference_whiten_vsgp():
N = 1000
X = dist.Uniform(torch.zeros(N), torch.ones(N)*5).sample()
y = 0.5 * torch.sin(3*X) + dist.Normal(torch.zeros(N), torch.ones(N)*0.5).sample()
kernel = RBF(input_dim=1)
Xu = torch.arange(0., 5.5, 0.5)
vsgp = VariationalSparseGP(X, y, kernel, Xu, Gaussian(), whiten=True)
train(vsgp)
Xnew = torch.arange(0., 5.05, 0.05)
loc, var = vsgp(Xnew, full_cov=False)
target = 0.5 * torch.sin(3*Xnew)
assert_equal((loc - target).abs().mean().item(), 0, prec=0.07)
@pytest.mark.parametrize("model_class, X, y, kernel, likelihood", _TEST_CASES(), ids=TEST_IDS)
def test_inference_with_empty_latent_shape(model_class, X, y, kernel, likelihood):
# regression models don't use latent_shape (default=torch.Size([]))
if model_class is GPRegression or model_class is SparseGPRegression:
return
elif model_class is VariationalGP:
gp = model_class(X, y, kernel, likelihood, latent_shape=torch.Size([]))
else:
gp = model_class(X, y, kernel, X.clone(), likelihood, latent_shape=torch.Size([]))
train(gp, num_steps=1)
@pytest.mark.parametrize("model_class, X, y, kernel, likelihood", _TEST_CASES(), ids=TEST_IDS)
def test_inference_with_whiten(model_class, X, y, kernel, likelihood):
if model_class is GPRegression or model_class is SparseGPRegression:
return
elif model_class is VariationalGP:
gp = model_class(X, y, kernel, likelihood, whiten=True)
else: # model_class is SparseVariationalGP
gp = model_class(X, y, kernel, X.clone(), likelihood, whiten=True)
train(gp, num_steps=1)
@pytest.mark.parametrize("model_class, X, y, kernel, likelihood", _TEST_CASES(), ids=TEST_IDS)
def test_hmc(model_class, X, y, kernel, likelihood):
if model_class is SparseGPRegression or model_class is VariationalSparseGP:
gp = model_class(X, y, kernel, X.clone(), likelihood)
else:
gp = model_class(X, y, kernel, likelihood)
if model_class is GPRegression:
model_name = "GPR"
elif model_class is SparseGPRegression:
model_name = "SGPR"
elif model_class is VariationalGP:
model_name = "VGP"
else:
model_name = "VSGP"
kernel.set_prior("variance", dist.Uniform(torch.tensor(0.5), torch.tensor(1.5)))
kernel.set_prior("lengthscale", dist.Uniform(torch.tensor(1.0), torch.tensor(3.0)))
hmc_kernel = HMC(gp.model, step_size=1)
mcmc_run = MCMC(hmc_kernel, num_samples=10)
post_trace = defaultdict(list)
for trace, _ in mcmc_run._traces():
variance_name = "{}/RBF/variance".format(model_name)
post_trace["variance"].append(trace.nodes[variance_name]["value"])
lengthscale_name = "{}/RBF/lengthscale".format(model_name)
post_trace["lengthscale"].append(trace.nodes[lengthscale_name]["value"])
if model_class is VariationalGP:
f_name = "VGP/f"
post_trace["f"].append(trace.nodes[f_name]["value"])
if model_class is VariationalSparseGP:
u_name = "VSGP/u"
post_trace["u"].append(trace.nodes[u_name]["value"])
for param in post_trace:
param_mean = torch.mean(torch.stack(post_trace[param]), 0)
logger.info("Posterior mean - {}".format(param))
logger.info(param_mean)
def test_inference_deepGP():
gp1 = GPRegression(X, None, RBF(input_dim=3, variance=torch.tensor(3.),
lengthscale=torch.tensor(2.)))
Z, _ = gp1.model()
gp2 = VariationalSparseGP(Z, y2D, Matern32(input_dim=3), Z.clone(),
Gaussian(torch.tensor(1e-6)))
class DeepGP(torch.nn.Module):
def __init__(self, gp1, gp2):
super(DeepGP, self).__init__()
self.gp1 = gp1
self.gp2 = gp2
def model(self):
Z, _ = self.gp1.model()
self.gp2.set_data(Z, y2D)
self.gp2.model()
def guide(self):
self.gp1.guide()
self.gp2.guide()
deepgp = DeepGP(gp1, gp2)
train(deepgp, num_steps=1)
@pytest.mark.parametrize("model_class, X, y, kernel, likelihood", _TEST_CASES(), ids=TEST_IDS)
def test_gplvm(model_class, X, y, kernel, likelihood):
if model_class is SparseGPRegression or model_class is VariationalSparseGP:
gp = model_class(X, y, kernel, X.clone(), likelihood)
else:
gp = model_class(X, y, kernel, likelihood)
gplvm = GPLVM(gp)
# test inference
train(gplvm, num_steps=1)
# test forward
gplvm(Xnew=X)
def _pre_test_mean_function():
def f(x):
return 2 * x + 3 + 5 * torch.sin(7 * x)
X = torch.arange(100, dtype=torch.Tensor().dtype)
y = f(X)
Xnew = torch.arange(100, 150, dtype=torch.Tensor().dtype)
ynew = f(Xnew)
kernel = Cosine(input_dim=1)
class Trend(torch.nn.Module):
def __init__(self):
super(Trend, self).__init__()
self.a = torch.nn.Parameter(torch.tensor(0.))
self.b = torch.nn.Parameter(torch.tensor(1.))
def forward(self, x):
return self.a * x + self.b
trend = Trend()
return X, y, Xnew, ynew, kernel, trend
def _mape(y_true, y_pred):
return ((y_pred - y_true) / y_true).abs().mean()
def _post_test_mean_function(gpmodule, Xnew, y_true):
assert_equal(gpmodule.mean_function.a.item(), 2, prec=0.02)
assert_equal(gpmodule.mean_function.b.item(), 3, prec=0.02)
y_pred, _ = gpmodule(Xnew)
assert_equal(_mape(y_true, y_pred).item(), 0, prec=0.02)
def test_mean_function_GPR():
X, y, Xnew, ynew, kernel, mean_fn = _pre_test_mean_function()
gpmodule = GPRegression(X, y, kernel, mean_function=mean_fn)
train(gpmodule)
_post_test_mean_function(gpmodule, Xnew, ynew)
def test_mean_function_SGPR():
X, y, Xnew, ynew, kernel, mean_fn = _pre_test_mean_function()
Xu = X[::20].clone()
gpmodule = SparseGPRegression(X, y, kernel, Xu, mean_function=mean_fn)
train(gpmodule)
_post_test_mean_function(gpmodule, Xnew, ynew)
def test_mean_function_SGPR_DTC():
X, y, Xnew, ynew, kernel, mean_fn = _pre_test_mean_function()
Xu = X[::20].clone()
gpmodule = SparseGPRegression(X, y, kernel, Xu, mean_function=mean_fn, approx="DTC")
train(gpmodule)
_post_test_mean_function(gpmodule, Xnew, ynew)
def test_mean_function_SGPR_FITC():
X, y, Xnew, ynew, kernel, mean_fn = _pre_test_mean_function()
Xu = X[::20].clone()
gpmodule = SparseGPRegression(X, y, kernel, Xu, mean_function=mean_fn, approx="FITC")
train(gpmodule)
_post_test_mean_function(gpmodule, Xnew, ynew)
def test_mean_function_VGP():
X, y, Xnew, ynew, kernel, mean_fn = _pre_test_mean_function()
likelihood = Gaussian()
gpmodule = VariationalGP(X, y, kernel, likelihood, mean_function=mean_fn)
train(gpmodule)
_post_test_mean_function(gpmodule, Xnew, ynew)
def test_mean_function_VGP_whiten():
X, y, Xnew, ynew, kernel, mean_fn = _pre_test_mean_function()
likelihood = Gaussian()
gpmodule = VariationalGP(X, y, kernel, likelihood, mean_function=mean_fn,
whiten=True)
optimizer = torch.optim.Adam(gpmodule.parameters(), lr=0.1)
train(gpmodule, optimizer)
_post_test_mean_function(gpmodule, Xnew, ynew)
def test_mean_function_VSGP():
X, y, Xnew, ynew, kernel, mean_fn = _pre_test_mean_function()
Xu = X[::20].clone()
likelihood = Gaussian()
gpmodule = VariationalSparseGP(X, y, kernel, Xu, likelihood, mean_function=mean_fn)
optimizer = torch.optim.Adam(gpmodule.parameters(), lr=0.02)
train(gpmodule, optimizer)
_post_test_mean_function(gpmodule, Xnew, ynew)
def test_mean_function_VSGP_whiten():
X, y, Xnew, ynew, kernel, mean_fn = _pre_test_mean_function()
Xu = X[::20].clone()
likelihood = Gaussian()
gpmodule = VariationalSparseGP(X, y, kernel, Xu, likelihood, mean_function=mean_fn,
whiten=True)
optimizer = torch.optim.Adam(gpmodule.parameters(), lr=0.1)
train(gpmodule, optimizer)
_post_test_mean_function(gpmodule, Xnew, ynew)
| true | true |
f7f924ad1810a0c8444d100e2966267673bb8db2 | 58 | py | Python | HAFTA-3/DERS-8/for_string.py | aydan08/Python-Kursu-15.02.21 | a1463501df47cacbd7ddd8c6f3aeb93abf1436f6 | [
"MIT"
] | 1 | 2021-03-08T16:16:35.000Z | 2021-03-08T16:16:35.000Z | HAFTA-3/DERS-8/for_string.py | aydan08/Python-Kursu-15.02.21 | a1463501df47cacbd7ddd8c6f3aeb93abf1436f6 | [
"MIT"
] | null | null | null | HAFTA-3/DERS-8/for_string.py | aydan08/Python-Kursu-15.02.21 | a1463501df47cacbd7ddd8c6f3aeb93abf1436f6 | [
"MIT"
] | null | null | null | for karakter in "Arhavi Halk Eğitim":
print(karakter) | 29 | 38 | 0.724138 | for karakter in "Arhavi Halk Eğitim":
print(karakter) | true | true |
f7f92575fe8831a6bc80d1edb600f2a04ffecd01 | 722 | py | Python | pythia/opal/content/Style.py | willic3/pythia | 2657b95a0c07fd3c914ab6b5f7ec89a8edba004c | [
"BSD-3-Clause"
] | 1 | 2015-11-30T08:01:39.000Z | 2015-11-30T08:01:39.000Z | pythia/opal/content/Style.py | willic3/pythia | 2657b95a0c07fd3c914ab6b5f7ec89a8edba004c | [
"BSD-3-Clause"
] | 27 | 2018-05-24T18:31:25.000Z | 2021-10-16T03:57:52.000Z | pythia/opal/content/Style.py | willic3/pythia | 2657b95a0c07fd3c914ab6b5f7ec89a8edba004c | [
"BSD-3-Clause"
] | 7 | 2019-07-19T02:30:56.000Z | 2021-06-02T22:00:01.000Z | #!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Michael A.G. Aivazis
# California Institute of Technology
# (C) 1998-2005 All Rights Reserved
#
# {LicenseText}
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
from .Element import Element
class Style(Element):
def identify(self, inspector):
return inspector.onStyle(self)
def __init__(self, **kwds):
Element.__init__(self, 'style', **kwds)
self.style = []
return
# version
__id__ = "$Id: Style.py,v 1.1 2005/03/20 07:22:58 aivazis Exp $"
# End of file
| 20.628571 | 80 | 0.429363 |
from .Element import Element
class Style(Element):
def identify(self, inspector):
return inspector.onStyle(self)
def __init__(self, **kwds):
Element.__init__(self, 'style', **kwds)
self.style = []
return
__id__ = "$Id: Style.py,v 1.1 2005/03/20 07:22:58 aivazis Exp $"
| true | true |
f7f92649f6a7e136179d208d352aa824ff4cae2a | 2,013 | py | Python | rlkit/envs/mujoco/ant.py | Asap7772/railrl_evalsawyer | baba8ce634d32a48c7dfe4dc03b123e18e96e0a3 | [
"MIT"
] | 1 | 2020-10-23T14:40:09.000Z | 2020-10-23T14:40:09.000Z | rlkit/envs/mujoco/ant.py | Asap7772/railrl_evalsawyer | baba8ce634d32a48c7dfe4dc03b123e18e96e0a3 | [
"MIT"
] | null | null | null | rlkit/envs/mujoco/ant.py | Asap7772/railrl_evalsawyer | baba8ce634d32a48c7dfe4dc03b123e18e96e0a3 | [
"MIT"
] | 1 | 2021-05-27T20:38:45.000Z | 2021-05-27T20:38:45.000Z | """
Exact same as gym env, except that the gear ratio is 30 rather than 150.
"""
import numpy as np
from gym.envs.mujoco import MujocoEnv
from rlkit.envs.env_utils import get_asset_full_path
class AntEnv(MujocoEnv):
def __init__(self, use_low_gear_ratio=True):
if use_low_gear_ratio:
xml_path = 'low_gear_ratio_ant.xml'
else:
xml_path = 'normal_gear_ratio_ant.xml'
super().__init__(
get_asset_full_path(xml_path),
frame_skip=5,
)
def step(self, a):
torso_xyz_before = self.get_body_com("torso")
self.do_simulation(a, self.frame_skip)
torso_xyz_after = self.get_body_com("torso")
torso_velocity = torso_xyz_after - torso_xyz_before
forward_reward = torso_velocity[0]/self.dt
ctrl_cost = .5 * np.square(a).sum()
contact_cost = 0.5 * 1e-3 * np.sum(
np.square(np.clip(self.sim.data.cfrc_ext, -1, 1)))
survive_reward = 1.0
reward = forward_reward - ctrl_cost - contact_cost + survive_reward
state = self.state_vector()
notdone = np.isfinite(state).all() \
and state[2] >= 0.2 and state[2] <= 1.0
done = not notdone
ob = self._get_obs()
return ob, reward, done, dict(
reward_forward=forward_reward,
reward_ctrl=-ctrl_cost,
reward_contact=-contact_cost,
reward_survive=survive_reward,
torso_velocity=torso_velocity,
)
def _get_obs(self):
return np.concatenate([
self.sim.data.qpos.flat[2:],
self.sim.data.qvel.flat,
])
def reset_model(self):
qpos = self.init_qpos + self.np_random.uniform(size=self.model.nq, low=-.1, high=.1)
qvel = self.init_qvel + self.np_random.randn(self.model.nv) * .1
self.set_state(qpos, qvel)
return self._get_obs()
def viewer_setup(self):
self.viewer.cam.distance = self.model.stat.extent * 0.5
| 33.55 | 92 | 0.614506 | import numpy as np
from gym.envs.mujoco import MujocoEnv
from rlkit.envs.env_utils import get_asset_full_path
class AntEnv(MujocoEnv):
def __init__(self, use_low_gear_ratio=True):
if use_low_gear_ratio:
xml_path = 'low_gear_ratio_ant.xml'
else:
xml_path = 'normal_gear_ratio_ant.xml'
super().__init__(
get_asset_full_path(xml_path),
frame_skip=5,
)
def step(self, a):
torso_xyz_before = self.get_body_com("torso")
self.do_simulation(a, self.frame_skip)
torso_xyz_after = self.get_body_com("torso")
torso_velocity = torso_xyz_after - torso_xyz_before
forward_reward = torso_velocity[0]/self.dt
ctrl_cost = .5 * np.square(a).sum()
contact_cost = 0.5 * 1e-3 * np.sum(
np.square(np.clip(self.sim.data.cfrc_ext, -1, 1)))
survive_reward = 1.0
reward = forward_reward - ctrl_cost - contact_cost + survive_reward
state = self.state_vector()
notdone = np.isfinite(state).all() \
and state[2] >= 0.2 and state[2] <= 1.0
done = not notdone
ob = self._get_obs()
return ob, reward, done, dict(
reward_forward=forward_reward,
reward_ctrl=-ctrl_cost,
reward_contact=-contact_cost,
reward_survive=survive_reward,
torso_velocity=torso_velocity,
)
def _get_obs(self):
return np.concatenate([
self.sim.data.qpos.flat[2:],
self.sim.data.qvel.flat,
])
def reset_model(self):
qpos = self.init_qpos + self.np_random.uniform(size=self.model.nq, low=-.1, high=.1)
qvel = self.init_qvel + self.np_random.randn(self.model.nv) * .1
self.set_state(qpos, qvel)
return self._get_obs()
def viewer_setup(self):
self.viewer.cam.distance = self.model.stat.extent * 0.5
| true | true |
f7f9266919d061fe61748360909c290f275d7b13 | 45,365 | py | Python | Lib/fontTools/ttLib/tables/_c_m_a_p.py | ctrlcctrlv/fonttools | 81d0042a9ee35d4ac91a9b4525db665f204c06e0 | [
"Apache-2.0",
"MIT"
] | 2 | 2021-04-07T16:47:04.000Z | 2022-01-15T04:01:01.000Z | Lib/fontTools/ttLib/tables/_c_m_a_p.py | ctrlcctrlv/fonttools | 81d0042a9ee35d4ac91a9b4525db665f204c06e0 | [
"Apache-2.0",
"MIT"
] | 74 | 2020-01-30T07:27:54.000Z | 2021-08-03T05:47:17.000Z | Lib/fontTools/ttLib/tables/_c_m_a_p.py | ctrlcctrlv/fonttools | 81d0042a9ee35d4ac91a9b4525db665f204c06e0 | [
"Apache-2.0",
"MIT"
] | 1 | 2020-01-22T20:06:09.000Z | 2020-01-22T20:06:09.000Z | from fontTools.misc.py23 import *
from fontTools.misc.textTools import safeEval, readHex
from fontTools.misc.encodingTools import getEncoding
from fontTools.ttLib import getSearchRange
from fontTools.unicode import Unicode
from . import DefaultTable
import sys
import struct
import array
import logging
log = logging.getLogger(__name__)
def _make_map(font, chars, gids):
assert len(chars) == len(gids)
cmap = {}
glyphOrder = font.getGlyphOrder()
for char,gid in zip(chars,gids):
if gid == 0:
continue
try:
name = glyphOrder[gid]
except IndexError:
name = font.getGlyphName(gid)
cmap[char] = name
return cmap
class table__c_m_a_p(DefaultTable.DefaultTable):
def getcmap(self, platformID, platEncID):
for subtable in self.tables:
if (subtable.platformID == platformID and
subtable.platEncID == platEncID):
return subtable
return None # not found
def getBestCmap(self, cmapPreferences=((3, 10), (0, 6), (0, 4), (3, 1), (0, 3), (0, 2), (0, 1), (0, 0))):
"""Return the 'best' unicode cmap dictionary available in the font,
or None, if no unicode cmap subtable is available.
By default it will search for the following (platformID, platEncID)
pairs:
(3, 10), (0, 6), (0, 4), (3, 1), (0, 3), (0, 2), (0, 1), (0, 0)
This can be customized via the cmapPreferences argument.
"""
for platformID, platEncID in cmapPreferences:
cmapSubtable = self.getcmap(platformID, platEncID)
if cmapSubtable is not None:
return cmapSubtable.cmap
return None # None of the requested cmap subtables were found
def buildReversed(self):
"""Returns a reverse cmap such as {'one':{0x31}, 'A':{0x41,0x391}}.
The values are sets of Unicode codepoints because
some fonts map different codepoints to the same glyph.
For example, U+0041 LATIN CAPITAL LETTER A and U+0391
GREEK CAPITAL LETTER ALPHA are sometimes the same glyph.
"""
result = {}
for subtable in self.tables:
if subtable.isUnicode():
for codepoint, name in subtable.cmap.items():
result.setdefault(name, set()).add(codepoint)
return result
def decompile(self, data, ttFont):
tableVersion, numSubTables = struct.unpack(">HH", data[:4])
self.tableVersion = int(tableVersion)
self.tables = tables = []
seenOffsets = {}
for i in range(numSubTables):
platformID, platEncID, offset = struct.unpack(
">HHl", data[4+i*8:4+(i+1)*8])
platformID, platEncID = int(platformID), int(platEncID)
format, length = struct.unpack(">HH", data[offset:offset+4])
if format in [8,10,12,13]:
format, reserved, length = struct.unpack(">HHL", data[offset:offset+8])
elif format in [14]:
format, length = struct.unpack(">HL", data[offset:offset+6])
if not length:
log.error(
"cmap subtable is reported as having zero length: platformID %s, "
"platEncID %s, format %s offset %s. Skipping table.",
platformID, platEncID, format, offset)
continue
table = CmapSubtable.newSubtable(format)
table.platformID = platformID
table.platEncID = platEncID
# Note that by default we decompile only the subtable header info;
# any other data gets decompiled only when an attribute of the
# subtable is referenced.
table.decompileHeader(data[offset:offset+int(length)], ttFont)
if offset in seenOffsets:
table.data = None # Mark as decompiled
table.cmap = tables[seenOffsets[offset]].cmap
else:
seenOffsets[offset] = i
tables.append(table)
def compile(self, ttFont):
self.tables.sort() # sort according to the spec; see CmapSubtable.__lt__()
numSubTables = len(self.tables)
totalOffset = 4 + 8 * numSubTables
data = struct.pack(">HH", self.tableVersion, numSubTables)
tableData = b""
seen = {} # Some tables are the same object reference. Don't compile them twice.
done = {} # Some tables are different objects, but compile to the same data chunk
for table in self.tables:
try:
offset = seen[id(table.cmap)]
except KeyError:
chunk = table.compile(ttFont)
if chunk in done:
offset = done[chunk]
else:
offset = seen[id(table.cmap)] = done[chunk] = totalOffset + len(tableData)
tableData = tableData + chunk
data = data + struct.pack(">HHl", table.platformID, table.platEncID, offset)
return data + tableData
def toXML(self, writer, ttFont):
writer.simpletag("tableVersion", version=self.tableVersion)
writer.newline()
for table in self.tables:
table.toXML(writer, ttFont)
def fromXML(self, name, attrs, content, ttFont):
if name == "tableVersion":
self.tableVersion = safeEval(attrs["version"])
return
if name[:12] != "cmap_format_":
return
if not hasattr(self, "tables"):
self.tables = []
format = safeEval(name[12:])
table = CmapSubtable.newSubtable(format)
table.platformID = safeEval(attrs["platformID"])
table.platEncID = safeEval(attrs["platEncID"])
table.fromXML(name, attrs, content, ttFont)
self.tables.append(table)
class CmapSubtable(object):
@staticmethod
def getSubtableClass(format):
"""Return the subtable class for a format."""
return cmap_classes.get(format, cmap_format_unknown)
@staticmethod
def newSubtable(format):
"""Return a new instance of a subtable for format."""
subtableClass = CmapSubtable.getSubtableClass(format)
return subtableClass(format)
def __init__(self, format):
self.format = format
self.data = None
self.ttFont = None
def __getattr__(self, attr):
# allow lazy decompilation of subtables.
if attr[:2] == '__': # don't handle requests for member functions like '__lt__'
raise AttributeError(attr)
if self.data is None:
raise AttributeError(attr)
self.decompile(None, None) # use saved data.
self.data = None # Once this table has been decompiled, make sure we don't
# just return the original data. Also avoids recursion when
# called with an attribute that the cmap subtable doesn't have.
return getattr(self, attr)
def decompileHeader(self, data, ttFont):
format, length, language = struct.unpack(">HHH", data[:6])
assert len(data) == length, "corrupt cmap table format %d (data length: %d, header length: %d)" % (format, len(data), length)
self.format = int(format)
self.length = int(length)
self.language = int(language)
self.data = data[6:]
self.ttFont = ttFont
def toXML(self, writer, ttFont):
writer.begintag(self.__class__.__name__, [
("platformID", self.platformID),
("platEncID", self.platEncID),
("language", self.language),
])
writer.newline()
codes = sorted(self.cmap.items())
self._writeCodes(codes, writer)
writer.endtag(self.__class__.__name__)
writer.newline()
def getEncoding(self, default=None):
"""Returns the Python encoding name for this cmap subtable based on its platformID,
platEncID, and language. If encoding for these values is not known, by default
None is returned. That can be overriden by passing a value to the default
argument.
Note that if you want to choose a "preferred" cmap subtable, most of the time
self.isUnicode() is what you want as that one only returns true for the modern,
commonly used, Unicode-compatible triplets, not the legacy ones.
"""
return getEncoding(self.platformID, self.platEncID, self.language, default)
def isUnicode(self):
return (self.platformID == 0 or
(self.platformID == 3 and self.platEncID in [0, 1, 10]))
def isSymbol(self):
return self.platformID == 3 and self.platEncID == 0
def _writeCodes(self, codes, writer):
isUnicode = self.isUnicode()
for code, name in codes:
writer.simpletag("map", code=hex(code), name=name)
if isUnicode:
writer.comment(Unicode[code])
writer.newline()
def __lt__(self, other):
if not isinstance(other, CmapSubtable):
return NotImplemented
# implemented so that list.sort() sorts according to the spec.
selfTuple = (
getattr(self, "platformID", None),
getattr(self, "platEncID", None),
getattr(self, "language", None),
self.__dict__)
otherTuple = (
getattr(other, "platformID", None),
getattr(other, "platEncID", None),
getattr(other, "language", None),
other.__dict__)
return selfTuple < otherTuple
class cmap_format_0(CmapSubtable):
def decompile(self, data, ttFont):
# we usually get here indirectly from the subtable __getattr__ function, in which case both args must be None.
# If not, someone is calling the subtable decompile() directly, and must provide both args.
if data is not None and ttFont is not None:
self.decompileHeader(data, ttFont)
else:
assert (data is None and ttFont is None), "Need both data and ttFont arguments"
data = self.data # decompileHeader assigns the data after the header to self.data
assert 262 == self.length, "Format 0 cmap subtable not 262 bytes"
gids = array.array("B")
gids.frombytes(self.data)
charCodes = list(range(len(gids)))
self.cmap = _make_map(self.ttFont, charCodes, gids)
def compile(self, ttFont):
if self.data:
return struct.pack(">HHH", 0, 262, self.language) + self.data
cmap = self.cmap
assert set(cmap.keys()).issubset(range(256))
getGlyphID = ttFont.getGlyphID
valueList = [getGlyphID(cmap[i]) if i in cmap else 0 for i in range(256)]
gids = array.array("B", valueList)
data = struct.pack(">HHH", 0, 262, self.language) + gids.tobytes()
assert len(data) == 262
return data
def fromXML(self, name, attrs, content, ttFont):
self.language = safeEval(attrs["language"])
if not hasattr(self, "cmap"):
self.cmap = {}
cmap = self.cmap
for element in content:
if not isinstance(element, tuple):
continue
name, attrs, content = element
if name != "map":
continue
cmap[safeEval(attrs["code"])] = attrs["name"]
subHeaderFormat = ">HHhH"
class SubHeader(object):
def __init__(self):
self.firstCode = None
self.entryCount = None
self.idDelta = None
self.idRangeOffset = None
self.glyphIndexArray = []
class cmap_format_2(CmapSubtable):
def setIDDelta(self, subHeader):
subHeader.idDelta = 0
# find the minGI which is not zero.
minGI = subHeader.glyphIndexArray[0]
for gid in subHeader.glyphIndexArray:
if (gid != 0) and (gid < minGI):
minGI = gid
# The lowest gid in glyphIndexArray, after subtracting idDelta, must be 1.
# idDelta is a short, and must be between -32K and 32K. minGI can be between 1 and 64K.
# We would like to pick an idDelta such that the first glyphArray GID is 1,
# so that we are more likely to be able to combine glypharray GID subranges.
# This means that we have a problem when minGI is > 32K
# Since the final gi is reconstructed from the glyphArray GID by:
# (short)finalGID = (gid + idDelta) % 0x10000),
# we can get from a glypharray GID of 1 to a final GID of 65K by subtracting 2, and casting the
# negative number to an unsigned short.
if (minGI > 1):
if minGI > 0x7FFF:
subHeader.idDelta = -(0x10000 - minGI) -1
else:
subHeader.idDelta = minGI -1
idDelta = subHeader.idDelta
for i in range(subHeader.entryCount):
gid = subHeader.glyphIndexArray[i]
if gid > 0:
subHeader.glyphIndexArray[i] = gid - idDelta
def decompile(self, data, ttFont):
# we usually get here indirectly from the subtable __getattr__ function, in which case both args must be None.
# If not, someone is calling the subtable decompile() directly, and must provide both args.
if data is not None and ttFont is not None:
self.decompileHeader(data, ttFont)
else:
assert (data is None and ttFont is None), "Need both data and ttFont arguments"
data = self.data # decompileHeader assigns the data after the header to self.data
subHeaderKeys = []
maxSubHeaderindex = 0
# get the key array, and determine the number of subHeaders.
allKeys = array.array("H")
allKeys.frombytes(data[:512])
data = data[512:]
if sys.byteorder != "big": allKeys.byteswap()
subHeaderKeys = [ key//8 for key in allKeys]
maxSubHeaderindex = max(subHeaderKeys)
#Load subHeaders
subHeaderList = []
pos = 0
for i in range(maxSubHeaderindex + 1):
subHeader = SubHeader()
(subHeader.firstCode, subHeader.entryCount, subHeader.idDelta, \
subHeader.idRangeOffset) = struct.unpack(subHeaderFormat, data[pos:pos + 8])
pos += 8
giDataPos = pos + subHeader.idRangeOffset-2
giList = array.array("H")
giList.frombytes(data[giDataPos:giDataPos + subHeader.entryCount*2])
if sys.byteorder != "big": giList.byteswap()
subHeader.glyphIndexArray = giList
subHeaderList.append(subHeader)
# How this gets processed.
# Charcodes may be one or two bytes.
# The first byte of a charcode is mapped through the subHeaderKeys, to select
# a subHeader. For any subheader but 0, the next byte is then mapped through the
# selected subheader. If subheader Index 0 is selected, then the byte itself is
# mapped through the subheader, and there is no second byte.
# Then assume that the subsequent byte is the first byte of the next charcode,and repeat.
#
# Each subheader references a range in the glyphIndexArray whose length is entryCount.
# The range in glyphIndexArray referenced by a sunheader may overlap with the range in glyphIndexArray
# referenced by another subheader.
# The only subheader that will be referenced by more than one first-byte value is the subheader
# that maps the entire range of glyphID values to glyphIndex 0, e.g notdef:
# {firstChar 0, EntryCount 0,idDelta 0,idRangeOffset xx}
# A byte being mapped though a subheader is treated as in index into a mapping of array index to font glyphIndex.
# A subheader specifies a subrange within (0...256) by the
# firstChar and EntryCount values. If the byte value is outside the subrange, then the glyphIndex is zero
# (e.g. glyph not in font).
# If the byte index is in the subrange, then an offset index is calculated as (byteIndex - firstChar).
# The index to glyphIndex mapping is a subrange of the glyphIndexArray. You find the start of the subrange by
# counting idRangeOffset bytes from the idRangeOffset word. The first value in this subrange is the
# glyphIndex for the index firstChar. The offset index should then be used in this array to get the glyphIndex.
# Example for Logocut-Medium
# first byte of charcode = 129; selects subheader 1.
# subheader 1 = {firstChar 64, EntryCount 108,idDelta 42,idRangeOffset 0252}
# second byte of charCode = 66
# the index offset = 66-64 = 2.
# The subrange of the glyphIndexArray starting at 0x0252 bytes from the idRangeOffset word is:
# [glyphIndexArray index], [subrange array index] = glyphIndex
# [256], [0]=1 from charcode [129, 64]
# [257], [1]=2 from charcode [129, 65]
# [258], [2]=3 from charcode [129, 66]
# [259], [3]=4 from charcode [129, 67]
# So, the glyphIndex = 3 from the array. Then if idDelta is not zero and the glyph ID is not zero,
# add it to the glyphID to get the final glyphIndex
# value. In this case the final glyph index = 3+ 42 -> 45 for the final glyphIndex. Whew!
self.data = b""
cmap = {}
notdefGI = 0
for firstByte in range(256):
subHeadindex = subHeaderKeys[firstByte]
subHeader = subHeaderList[subHeadindex]
if subHeadindex == 0:
if (firstByte < subHeader.firstCode) or (firstByte >= subHeader.firstCode + subHeader.entryCount):
continue # gi is notdef.
else:
charCode = firstByte
offsetIndex = firstByte - subHeader.firstCode
gi = subHeader.glyphIndexArray[offsetIndex]
if gi != 0:
gi = (gi + subHeader.idDelta) % 0x10000
else:
continue # gi is notdef.
cmap[charCode] = gi
else:
if subHeader.entryCount:
charCodeOffset = firstByte * 256 + subHeader.firstCode
for offsetIndex in range(subHeader.entryCount):
charCode = charCodeOffset + offsetIndex
gi = subHeader.glyphIndexArray[offsetIndex]
if gi != 0:
gi = (gi + subHeader.idDelta) % 0x10000
else:
continue
cmap[charCode] = gi
# If not subHeader.entryCount, then all char codes with this first byte are
# mapped to .notdef. We can skip this subtable, and leave the glyphs un-encoded, which is the
# same as mapping it to .notdef.
gids = list(cmap.values())
charCodes = list(cmap.keys())
self.cmap = _make_map(self.ttFont, charCodes, gids)
def compile(self, ttFont):
if self.data:
return struct.pack(">HHH", self.format, self.length, self.language) + self.data
kEmptyTwoCharCodeRange = -1
notdefGI = 0
items = sorted(self.cmap.items())
charCodes = [item[0] for item in items]
names = [item[1] for item in items]
nameMap = ttFont.getReverseGlyphMap()
try:
gids = [nameMap[name] for name in names]
except KeyError:
nameMap = ttFont.getReverseGlyphMap(rebuild=True)
try:
gids = [nameMap[name] for name in names]
except KeyError:
# allow virtual GIDs in format 2 tables
gids = []
for name in names:
try:
gid = nameMap[name]
except KeyError:
try:
if (name[:3] == 'gid'):
gid = int(name[3:])
else:
gid = ttFont.getGlyphID(name)
except:
raise KeyError(name)
gids.append(gid)
# Process the (char code to gid) item list in char code order.
# By definition, all one byte char codes map to subheader 0.
# For all the two byte char codes, we assume that the first byte maps maps to the empty subhead (with an entry count of 0,
# which defines all char codes in its range to map to notdef) unless proven otherwise.
# Note that since the char code items are processed in char code order, all the char codes with the
# same first byte are in sequential order.
subHeaderKeys = [kEmptyTwoCharCodeRange for x in range(256)] # list of indices into subHeaderList.
subHeaderList = []
# We force this subheader entry 0 to exist in the subHeaderList in the case where some one comes up
# with a cmap where all the one byte char codes map to notdef,
# with the result that the subhead 0 would not get created just by processing the item list.
charCode = charCodes[0]
if charCode > 255:
subHeader = SubHeader()
subHeader.firstCode = 0
subHeader.entryCount = 0
subHeader.idDelta = 0
subHeader.idRangeOffset = 0
subHeaderList.append(subHeader)
lastFirstByte = -1
items = zip(charCodes, gids)
for charCode, gid in items:
if gid == 0:
continue
firstbyte = charCode >> 8
secondByte = charCode & 0x00FF
if firstbyte != lastFirstByte: # Need to update the current subhead, and start a new one.
if lastFirstByte > -1:
# fix GI's and iDelta of current subheader.
self.setIDDelta(subHeader)
# If it was sunheader 0 for one-byte charCodes, then we need to set the subHeaderKeys value to zero
# for the indices matching the char codes.
if lastFirstByte == 0:
for index in range(subHeader.entryCount):
charCode = subHeader.firstCode + index
subHeaderKeys[charCode] = 0
assert (subHeader.entryCount == len(subHeader.glyphIndexArray)), "Error - subhead entry count does not match len of glyphID subrange."
# init new subheader
subHeader = SubHeader()
subHeader.firstCode = secondByte
subHeader.entryCount = 1
subHeader.glyphIndexArray.append(gid)
subHeaderList.append(subHeader)
subHeaderKeys[firstbyte] = len(subHeaderList) -1
lastFirstByte = firstbyte
else:
# need to fill in with notdefs all the code points between the last charCode and the current charCode.
codeDiff = secondByte - (subHeader.firstCode + subHeader.entryCount)
for i in range(codeDiff):
subHeader.glyphIndexArray.append(notdefGI)
subHeader.glyphIndexArray.append(gid)
subHeader.entryCount = subHeader.entryCount + codeDiff + 1
# fix GI's and iDelta of last subheader that we we added to the subheader array.
self.setIDDelta(subHeader)
# Now we add a final subheader for the subHeaderKeys which maps to empty two byte charcode ranges.
subHeader = SubHeader()
subHeader.firstCode = 0
subHeader.entryCount = 0
subHeader.idDelta = 0
subHeader.idRangeOffset = 2
subHeaderList.append(subHeader)
emptySubheadIndex = len(subHeaderList) - 1
for index in range(256):
if subHeaderKeys[index] == kEmptyTwoCharCodeRange:
subHeaderKeys[index] = emptySubheadIndex
# Since this is the last subheader, the GlyphIndex Array starts two bytes after the start of the
# idRangeOffset word of this subHeader. We can safely point to the first entry in the GlyphIndexArray,
# since the first subrange of the GlyphIndexArray is for subHeader 0, which always starts with
# charcode 0 and GID 0.
idRangeOffset = (len(subHeaderList)-1)*8 + 2 # offset to beginning of glyphIDArray from first subheader idRangeOffset.
subheadRangeLen = len(subHeaderList) -1 # skip last special empty-set subheader; we've already hardocodes its idRangeOffset to 2.
for index in range(subheadRangeLen):
subHeader = subHeaderList[index]
subHeader.idRangeOffset = 0
for j in range(index):
prevSubhead = subHeaderList[j]
if prevSubhead.glyphIndexArray == subHeader.glyphIndexArray: # use the glyphIndexArray subarray
subHeader.idRangeOffset = prevSubhead.idRangeOffset - (index-j)*8
subHeader.glyphIndexArray = []
break
if subHeader.idRangeOffset == 0: # didn't find one.
subHeader.idRangeOffset = idRangeOffset
idRangeOffset = (idRangeOffset - 8) + subHeader.entryCount*2 # one less subheader, one more subArray.
else:
idRangeOffset = idRangeOffset - 8 # one less subheader
# Now we can write out the data!
length = 6 + 512 + 8*len(subHeaderList) # header, 256 subHeaderKeys, and subheader array.
for subhead in subHeaderList[:-1]:
length = length + len(subhead.glyphIndexArray)*2 # We can't use subhead.entryCount, as some of the subhead may share subArrays.
dataList = [struct.pack(">HHH", 2, length, self.language)]
for index in subHeaderKeys:
dataList.append(struct.pack(">H", index*8))
for subhead in subHeaderList:
dataList.append(struct.pack(subHeaderFormat, subhead.firstCode, subhead.entryCount, subhead.idDelta, subhead.idRangeOffset))
for subhead in subHeaderList[:-1]:
for gi in subhead.glyphIndexArray:
dataList.append(struct.pack(">H", gi))
data = bytesjoin(dataList)
assert (len(data) == length), "Error: cmap format 2 is not same length as calculated! actual: " + str(len(data))+ " calc : " + str(length)
return data
def fromXML(self, name, attrs, content, ttFont):
self.language = safeEval(attrs["language"])
if not hasattr(self, "cmap"):
self.cmap = {}
cmap = self.cmap
for element in content:
if not isinstance(element, tuple):
continue
name, attrs, content = element
if name != "map":
continue
cmap[safeEval(attrs["code"])] = attrs["name"]
cmap_format_4_format = ">7H"
#uint16 endCode[segCount] # Ending character code for each segment, last = 0xFFFF.
#uint16 reservedPad # This value should be zero
#uint16 startCode[segCount] # Starting character code for each segment
#uint16 idDelta[segCount] # Delta for all character codes in segment
#uint16 idRangeOffset[segCount] # Offset in bytes to glyph indexArray, or 0
#uint16 glyphIndexArray[variable] # Glyph index array
def splitRange(startCode, endCode, cmap):
# Try to split a range of character codes into subranges with consecutive
# glyph IDs in such a way that the cmap4 subtable can be stored "most"
# efficiently. I can't prove I've got the optimal solution, but it seems
# to do well with the fonts I tested: none became bigger, many became smaller.
if startCode == endCode:
return [], [endCode]
lastID = cmap[startCode]
lastCode = startCode
inOrder = None
orderedBegin = None
subRanges = []
# Gather subranges in which the glyph IDs are consecutive.
for code in range(startCode + 1, endCode + 1):
glyphID = cmap[code]
if glyphID - 1 == lastID:
if inOrder is None or not inOrder:
inOrder = 1
orderedBegin = lastCode
else:
if inOrder:
inOrder = 0
subRanges.append((orderedBegin, lastCode))
orderedBegin = None
lastID = glyphID
lastCode = code
if inOrder:
subRanges.append((orderedBegin, lastCode))
assert lastCode == endCode
# Now filter out those new subranges that would only make the data bigger.
# A new segment cost 8 bytes, not using a new segment costs 2 bytes per
# character.
newRanges = []
for b, e in subRanges:
if b == startCode and e == endCode:
break # the whole range, we're fine
if b == startCode or e == endCode:
threshold = 4 # split costs one more segment
else:
threshold = 8 # split costs two more segments
if (e - b + 1) > threshold:
newRanges.append((b, e))
subRanges = newRanges
if not subRanges:
return [], [endCode]
if subRanges[0][0] != startCode:
subRanges.insert(0, (startCode, subRanges[0][0] - 1))
if subRanges[-1][1] != endCode:
subRanges.append((subRanges[-1][1] + 1, endCode))
# Fill the "holes" in the segments list -- those are the segments in which
# the glyph IDs are _not_ consecutive.
i = 1
while i < len(subRanges):
if subRanges[i-1][1] + 1 != subRanges[i][0]:
subRanges.insert(i, (subRanges[i-1][1] + 1, subRanges[i][0] - 1))
i = i + 1
i = i + 1
# Transform the ranges into startCode/endCode lists.
start = []
end = []
for b, e in subRanges:
start.append(b)
end.append(e)
start.pop(0)
assert len(start) + 1 == len(end)
return start, end
class cmap_format_4(CmapSubtable):
def decompile(self, data, ttFont):
# we usually get here indirectly from the subtable __getattr__ function, in which case both args must be None.
# If not, someone is calling the subtable decompile() directly, and must provide both args.
if data is not None and ttFont is not None:
self.decompileHeader(data, ttFont)
else:
assert (data is None and ttFont is None), "Need both data and ttFont arguments"
data = self.data # decompileHeader assigns the data after the header to self.data
(segCountX2, searchRange, entrySelector, rangeShift) = \
struct.unpack(">4H", data[:8])
data = data[8:]
segCount = segCountX2 // 2
allCodes = array.array("H")
allCodes.frombytes(data)
self.data = data = None
if sys.byteorder != "big": allCodes.byteswap()
# divide the data
endCode = allCodes[:segCount]
allCodes = allCodes[segCount+1:] # the +1 is skipping the reservedPad field
startCode = allCodes[:segCount]
allCodes = allCodes[segCount:]
idDelta = allCodes[:segCount]
allCodes = allCodes[segCount:]
idRangeOffset = allCodes[:segCount]
glyphIndexArray = allCodes[segCount:]
lenGIArray = len(glyphIndexArray)
# build 2-byte character mapping
charCodes = []
gids = []
for i in range(len(startCode) - 1): # don't do 0xffff!
start = startCode[i]
delta = idDelta[i]
rangeOffset = idRangeOffset[i]
# *someone* needs to get killed.
partial = rangeOffset // 2 - start + i - len(idRangeOffset)
rangeCharCodes = list(range(startCode[i], endCode[i] + 1))
charCodes.extend(rangeCharCodes)
if rangeOffset == 0:
gids.extend([(charCode + delta) & 0xFFFF for charCode in rangeCharCodes])
else:
for charCode in rangeCharCodes:
index = charCode + partial
assert (index < lenGIArray), "In format 4 cmap, range (%d), the calculated index (%d) into the glyph index array is not less than the length of the array (%d) !" % (i, index, lenGIArray)
if glyphIndexArray[index] != 0: # if not missing glyph
glyphID = glyphIndexArray[index] + delta
else:
glyphID = 0 # missing glyph
gids.append(glyphID & 0xFFFF)
self.cmap = _make_map(self.ttFont, charCodes, gids)
def compile(self, ttFont):
if self.data:
return struct.pack(">HHH", self.format, self.length, self.language) + self.data
charCodes = list(self.cmap.keys())
if not charCodes:
startCode = [0xffff]
endCode = [0xffff]
else:
charCodes.sort()
names = [self.cmap[code] for code in charCodes]
nameMap = ttFont.getReverseGlyphMap()
try:
gids = [nameMap[name] for name in names]
except KeyError:
nameMap = ttFont.getReverseGlyphMap(rebuild=True)
try:
gids = [nameMap[name] for name in names]
except KeyError:
# allow virtual GIDs in format 4 tables
gids = []
for name in names:
try:
gid = nameMap[name]
except KeyError:
try:
if (name[:3] == 'gid'):
gid = int(name[3:])
else:
gid = ttFont.getGlyphID(name)
except:
raise KeyError(name)
gids.append(gid)
cmap = {} # code:glyphID mapping
for code, gid in zip(charCodes, gids):
cmap[code] = gid
# Build startCode and endCode lists.
# Split the char codes in ranges of consecutive char codes, then split
# each range in more ranges of consecutive/not consecutive glyph IDs.
# See splitRange().
lastCode = charCodes[0]
endCode = []
startCode = [lastCode]
for charCode in charCodes[1:]: # skip the first code, it's the first start code
if charCode == lastCode + 1:
lastCode = charCode
continue
start, end = splitRange(startCode[-1], lastCode, cmap)
startCode.extend(start)
endCode.extend(end)
startCode.append(charCode)
lastCode = charCode
start, end = splitRange(startCode[-1], lastCode, cmap)
startCode.extend(start)
endCode.extend(end)
startCode.append(0xffff)
endCode.append(0xffff)
# build up rest of cruft
idDelta = []
idRangeOffset = []
glyphIndexArray = []
for i in range(len(endCode)-1): # skip the closing codes (0xffff)
indices = []
for charCode in range(startCode[i], endCode[i] + 1):
indices.append(cmap[charCode])
if (indices == list(range(indices[0], indices[0] + len(indices)))):
idDelta.append((indices[0] - startCode[i]) % 0x10000)
idRangeOffset.append(0)
else:
# someone *definitely* needs to get killed.
idDelta.append(0)
idRangeOffset.append(2 * (len(endCode) + len(glyphIndexArray) - i))
glyphIndexArray.extend(indices)
idDelta.append(1) # 0xffff + 1 == (tadaa!) 0. So this end code maps to .notdef
idRangeOffset.append(0)
# Insane.
segCount = len(endCode)
segCountX2 = segCount * 2
searchRange, entrySelector, rangeShift = getSearchRange(segCount, 2)
charCodeArray = array.array("H", endCode + [0] + startCode)
idDeltaArray = array.array("H", idDelta)
restArray = array.array("H", idRangeOffset + glyphIndexArray)
if sys.byteorder != "big": charCodeArray.byteswap()
if sys.byteorder != "big": idDeltaArray.byteswap()
if sys.byteorder != "big": restArray.byteswap()
data = charCodeArray.tobytes() + idDeltaArray.tobytes() + restArray.tobytes()
length = struct.calcsize(cmap_format_4_format) + len(data)
header = struct.pack(cmap_format_4_format, self.format, length, self.language,
segCountX2, searchRange, entrySelector, rangeShift)
return header + data
def fromXML(self, name, attrs, content, ttFont):
self.language = safeEval(attrs["language"])
if not hasattr(self, "cmap"):
self.cmap = {}
cmap = self.cmap
for element in content:
if not isinstance(element, tuple):
continue
nameMap, attrsMap, dummyContent = element
if nameMap != "map":
assert 0, "Unrecognized keyword in cmap subtable"
cmap[safeEval(attrsMap["code"])] = attrsMap["name"]
class cmap_format_6(CmapSubtable):
def decompile(self, data, ttFont):
# we usually get here indirectly from the subtable __getattr__ function, in which case both args must be None.
# If not, someone is calling the subtable decompile() directly, and must provide both args.
if data is not None and ttFont is not None:
self.decompileHeader(data, ttFont)
else:
assert (data is None and ttFont is None), "Need both data and ttFont arguments"
data = self.data # decompileHeader assigns the data after the header to self.data
firstCode, entryCount = struct.unpack(">HH", data[:4])
firstCode = int(firstCode)
data = data[4:]
#assert len(data) == 2 * entryCount # XXX not true in Apple's Helvetica!!!
gids = array.array("H")
gids.frombytes(data[:2 * int(entryCount)])
if sys.byteorder != "big": gids.byteswap()
self.data = data = None
charCodes = list(range(firstCode, firstCode + len(gids)))
self.cmap = _make_map(self.ttFont, charCodes, gids)
def compile(self, ttFont):
if self.data:
return struct.pack(">HHH", self.format, self.length, self.language) + self.data
cmap = self.cmap
codes = sorted(cmap.keys())
if codes: # yes, there are empty cmap tables.
codes = list(range(codes[0], codes[-1] + 1))
firstCode = codes[0]
valueList = [
ttFont.getGlyphID(cmap[code]) if code in cmap else 0
for code in codes
]
gids = array.array("H", valueList)
if sys.byteorder != "big": gids.byteswap()
data = gids.tobytes()
else:
data = b""
firstCode = 0
header = struct.pack(">HHHHH",
6, len(data) + 10, self.language, firstCode, len(codes))
return header + data
def fromXML(self, name, attrs, content, ttFont):
self.language = safeEval(attrs["language"])
if not hasattr(self, "cmap"):
self.cmap = {}
cmap = self.cmap
for element in content:
if not isinstance(element, tuple):
continue
name, attrs, content = element
if name != "map":
continue
cmap[safeEval(attrs["code"])] = attrs["name"]
class cmap_format_12_or_13(CmapSubtable):
def __init__(self, format):
self.format = format
self.reserved = 0
self.data = None
self.ttFont = None
def decompileHeader(self, data, ttFont):
format, reserved, length, language, nGroups = struct.unpack(">HHLLL", data[:16])
assert len(data) == (16 + nGroups*12) == (length), "corrupt cmap table format %d (data length: %d, header length: %d)" % (self.format, len(data), length)
self.format = format
self.reserved = reserved
self.length = length
self.language = language
self.nGroups = nGroups
self.data = data[16:]
self.ttFont = ttFont
def decompile(self, data, ttFont):
# we usually get here indirectly from the subtable __getattr__ function, in which case both args must be None.
# If not, someone is calling the subtable decompile() directly, and must provide both args.
if data is not None and ttFont is not None:
self.decompileHeader(data, ttFont)
else:
assert (data is None and ttFont is None), "Need both data and ttFont arguments"
data = self.data # decompileHeader assigns the data after the header to self.data
charCodes = []
gids = []
pos = 0
for i in range(self.nGroups):
startCharCode, endCharCode, glyphID = struct.unpack(">LLL",data[pos:pos+12] )
pos += 12
lenGroup = 1 + endCharCode - startCharCode
charCodes.extend(list(range(startCharCode, endCharCode +1)))
gids.extend(self._computeGIDs(glyphID, lenGroup))
self.data = data = None
self.cmap = _make_map(self.ttFont, charCodes, gids)
def compile(self, ttFont):
if self.data:
return struct.pack(">HHLLL", self.format, self.reserved, self.length, self.language, self.nGroups) + self.data
charCodes = list(self.cmap.keys())
names = list(self.cmap.values())
nameMap = ttFont.getReverseGlyphMap()
try:
gids = [nameMap[name] for name in names]
except KeyError:
nameMap = ttFont.getReverseGlyphMap(rebuild=True)
try:
gids = [nameMap[name] for name in names]
except KeyError:
# allow virtual GIDs in format 12 tables
gids = []
for name in names:
try:
gid = nameMap[name]
except KeyError:
try:
if (name[:3] == 'gid'):
gid = int(name[3:])
else:
gid = ttFont.getGlyphID(name)
except:
raise KeyError(name)
gids.append(gid)
cmap = {} # code:glyphID mapping
for code, gid in zip(charCodes, gids):
cmap[code] = gid
charCodes.sort()
index = 0
startCharCode = charCodes[0]
startGlyphID = cmap[startCharCode]
lastGlyphID = startGlyphID - self._format_step
lastCharCode = startCharCode - 1
nGroups = 0
dataList = []
maxIndex = len(charCodes)
for index in range(maxIndex):
charCode = charCodes[index]
glyphID = cmap[charCode]
if not self._IsInSameRun(glyphID, lastGlyphID, charCode, lastCharCode):
dataList.append(struct.pack(">LLL", startCharCode, lastCharCode, startGlyphID))
startCharCode = charCode
startGlyphID = glyphID
nGroups = nGroups + 1
lastGlyphID = glyphID
lastCharCode = charCode
dataList.append(struct.pack(">LLL", startCharCode, lastCharCode, startGlyphID))
nGroups = nGroups + 1
data = bytesjoin(dataList)
lengthSubtable = len(data) +16
assert len(data) == (nGroups*12) == (lengthSubtable-16)
return struct.pack(">HHLLL", self.format, self.reserved, lengthSubtable, self.language, nGroups) + data
def toXML(self, writer, ttFont):
writer.begintag(self.__class__.__name__, [
("platformID", self.platformID),
("platEncID", self.platEncID),
("format", self.format),
("reserved", self.reserved),
("length", self.length),
("language", self.language),
("nGroups", self.nGroups),
])
writer.newline()
codes = sorted(self.cmap.items())
self._writeCodes(codes, writer)
writer.endtag(self.__class__.__name__)
writer.newline()
def fromXML(self, name, attrs, content, ttFont):
self.format = safeEval(attrs["format"])
self.reserved = safeEval(attrs["reserved"])
self.length = safeEval(attrs["length"])
self.language = safeEval(attrs["language"])
self.nGroups = safeEval(attrs["nGroups"])
if not hasattr(self, "cmap"):
self.cmap = {}
cmap = self.cmap
for element in content:
if not isinstance(element, tuple):
continue
name, attrs, content = element
if name != "map":
continue
cmap[safeEval(attrs["code"])] = attrs["name"]
class cmap_format_12(cmap_format_12_or_13):
_format_step = 1
def __init__(self, format=12):
cmap_format_12_or_13.__init__(self, format)
def _computeGIDs(self, startingGlyph, numberOfGlyphs):
return list(range(startingGlyph, startingGlyph + numberOfGlyphs))
def _IsInSameRun(self, glyphID, lastGlyphID, charCode, lastCharCode):
return (glyphID == 1 + lastGlyphID) and (charCode == 1 + lastCharCode)
class cmap_format_13(cmap_format_12_or_13):
_format_step = 0
def __init__(self, format=13):
cmap_format_12_or_13.__init__(self, format)
def _computeGIDs(self, startingGlyph, numberOfGlyphs):
return [startingGlyph] * numberOfGlyphs
def _IsInSameRun(self, glyphID, lastGlyphID, charCode, lastCharCode):
return (glyphID == lastGlyphID) and (charCode == 1 + lastCharCode)
def cvtToUVS(threeByteString):
data = b"\0" + threeByteString
val, = struct.unpack(">L", data)
return val
def cvtFromUVS(val):
assert 0 <= val < 0x1000000
fourByteString = struct.pack(">L", val)
return fourByteString[1:]
class cmap_format_14(CmapSubtable):
def decompileHeader(self, data, ttFont):
format, length, numVarSelectorRecords = struct.unpack(">HLL", data[:10])
self.data = data[10:]
self.length = length
self.numVarSelectorRecords = numVarSelectorRecords
self.ttFont = ttFont
self.language = 0xFF # has no language.
def decompile(self, data, ttFont):
if data is not None and ttFont is not None:
self.decompileHeader(data, ttFont)
else:
assert (data is None and ttFont is None), "Need both data and ttFont arguments"
data = self.data
self.cmap = {} # so that clients that expect this to exist in a cmap table won't fail.
uvsDict = {}
recOffset = 0
for n in range(self.numVarSelectorRecords):
uvs, defOVSOffset, nonDefUVSOffset = struct.unpack(">3sLL", data[recOffset:recOffset +11])
recOffset += 11
varUVS = cvtToUVS(uvs)
if defOVSOffset:
startOffset = defOVSOffset - 10
numValues, = struct.unpack(">L", data[startOffset:startOffset+4])
startOffset +=4
for r in range(numValues):
uv, addtlCnt = struct.unpack(">3sB", data[startOffset:startOffset+4])
startOffset += 4
firstBaseUV = cvtToUVS(uv)
cnt = addtlCnt+1
baseUVList = list(range(firstBaseUV, firstBaseUV+cnt))
glyphList = [None]*cnt
localUVList = zip(baseUVList, glyphList)
try:
uvsDict[varUVS].extend(localUVList)
except KeyError:
uvsDict[varUVS] = list(localUVList)
if nonDefUVSOffset:
startOffset = nonDefUVSOffset - 10
numRecs, = struct.unpack(">L", data[startOffset:startOffset+4])
startOffset +=4
localUVList = []
for r in range(numRecs):
uv, gid = struct.unpack(">3sH", data[startOffset:startOffset+5])
startOffset += 5
uv = cvtToUVS(uv)
glyphName = self.ttFont.getGlyphName(gid)
localUVList.append((uv, glyphName))
try:
uvsDict[varUVS].extend(localUVList)
except KeyError:
uvsDict[varUVS] = localUVList
self.uvsDict = uvsDict
def toXML(self, writer, ttFont):
writer.begintag(self.__class__.__name__, [
("platformID", self.platformID),
("platEncID", self.platEncID),
])
writer.newline()
uvsDict = self.uvsDict
uvsList = sorted(uvsDict.keys())
for uvs in uvsList:
uvList = uvsDict[uvs]
uvList.sort(key=lambda item: (item[1] is not None, item[0], item[1]))
for uv, gname in uvList:
attrs = [("uv", hex(uv)), ("uvs", hex(uvs))]
if gname is not None:
attrs.append(("name", gname))
writer.simpletag("map", attrs)
writer.newline()
writer.endtag(self.__class__.__name__)
writer.newline()
def fromXML(self, name, attrs, content, ttFont):
self.language = 0xFF # provide a value so that CmapSubtable.__lt__() won't fail
if not hasattr(self, "cmap"):
self.cmap = {} # so that clients that expect this to exist in a cmap table won't fail.
if not hasattr(self, "uvsDict"):
self.uvsDict = {}
uvsDict = self.uvsDict
# For backwards compatibility reasons we accept "None" as an indicator
# for "default mapping", unless the font actually has a glyph named
# "None".
_hasGlyphNamedNone = None
for element in content:
if not isinstance(element, tuple):
continue
name, attrs, content = element
if name != "map":
continue
uvs = safeEval(attrs["uvs"])
uv = safeEval(attrs["uv"])
gname = attrs.get("name")
if gname == "None":
if _hasGlyphNamedNone is None:
_hasGlyphNamedNone = "None" in ttFont.getGlyphOrder()
if not _hasGlyphNamedNone:
gname = None
try:
uvsDict[uvs].append((uv, gname))
except KeyError:
uvsDict[uvs] = [(uv, gname)]
def compile(self, ttFont):
if self.data:
return struct.pack(">HLL", self.format, self.length, self.numVarSelectorRecords) + self.data
uvsDict = self.uvsDict
uvsList = sorted(uvsDict.keys())
self.numVarSelectorRecords = len(uvsList)
offset = 10 + self.numVarSelectorRecords*11 # current value is end of VarSelectorRecords block.
data = []
varSelectorRecords =[]
for uvs in uvsList:
entryList = uvsDict[uvs]
defList = [entry for entry in entryList if entry[1] is None]
if defList:
defList = [entry[0] for entry in defList]
defOVSOffset = offset
defList.sort()
lastUV = defList[0]
cnt = -1
defRecs = []
for defEntry in defList:
cnt +=1
if (lastUV+cnt) != defEntry:
rec = struct.pack(">3sB", cvtFromUVS(lastUV), cnt-1)
lastUV = defEntry
defRecs.append(rec)
cnt = 0
rec = struct.pack(">3sB", cvtFromUVS(lastUV), cnt)
defRecs.append(rec)
numDefRecs = len(defRecs)
data.append(struct.pack(">L", numDefRecs))
data.extend(defRecs)
offset += 4 + numDefRecs*4
else:
defOVSOffset = 0
ndefList = [entry for entry in entryList if entry[1] is not None]
if ndefList:
nonDefUVSOffset = offset
ndefList.sort()
numNonDefRecs = len(ndefList)
data.append(struct.pack(">L", numNonDefRecs))
offset += 4 + numNonDefRecs*5
for uv, gname in ndefList:
gid = ttFont.getGlyphID(gname)
ndrec = struct.pack(">3sH", cvtFromUVS(uv), gid)
data.append(ndrec)
else:
nonDefUVSOffset = 0
vrec = struct.pack(">3sLL", cvtFromUVS(uvs), defOVSOffset, nonDefUVSOffset)
varSelectorRecords.append(vrec)
data = bytesjoin(varSelectorRecords) + bytesjoin(data)
self.length = 10 + len(data)
headerdata = struct.pack(">HLL", self.format, self.length, self.numVarSelectorRecords)
return headerdata + data
class cmap_format_unknown(CmapSubtable):
def toXML(self, writer, ttFont):
cmapName = self.__class__.__name__[:12] + str(self.format)
writer.begintag(cmapName, [
("platformID", self.platformID),
("platEncID", self.platEncID),
])
writer.newline()
writer.dumphex(self.data)
writer.endtag(cmapName)
writer.newline()
def fromXML(self, name, attrs, content, ttFont):
self.data = readHex(content)
self.cmap = {}
def decompileHeader(self, data, ttFont):
self.language = 0 # dummy value
self.data = data
def decompile(self, data, ttFont):
# we usually get here indirectly from the subtable __getattr__ function, in which case both args must be None.
# If not, someone is calling the subtable decompile() directly, and must provide both args.
if data is not None and ttFont is not None:
self.decompileHeader(data, ttFont)
else:
assert (data is None and ttFont is None), "Need both data and ttFont arguments"
def compile(self, ttFont):
if self.data:
return self.data
else:
return None
cmap_classes = {
0: cmap_format_0,
2: cmap_format_2,
4: cmap_format_4,
6: cmap_format_6,
12: cmap_format_12,
13: cmap_format_13,
14: cmap_format_14,
}
| 34.78911 | 191 | 0.696308 | from fontTools.misc.py23 import *
from fontTools.misc.textTools import safeEval, readHex
from fontTools.misc.encodingTools import getEncoding
from fontTools.ttLib import getSearchRange
from fontTools.unicode import Unicode
from . import DefaultTable
import sys
import struct
import array
import logging
log = logging.getLogger(__name__)
def _make_map(font, chars, gids):
assert len(chars) == len(gids)
cmap = {}
glyphOrder = font.getGlyphOrder()
for char,gid in zip(chars,gids):
if gid == 0:
continue
try:
name = glyphOrder[gid]
except IndexError:
name = font.getGlyphName(gid)
cmap[char] = name
return cmap
class table__c_m_a_p(DefaultTable.DefaultTable):
def getcmap(self, platformID, platEncID):
for subtable in self.tables:
if (subtable.platformID == platformID and
subtable.platEncID == platEncID):
return subtable
return None
def getBestCmap(self, cmapPreferences=((3, 10), (0, 6), (0, 4), (3, 1), (0, 3), (0, 2), (0, 1), (0, 0))):
for platformID, platEncID in cmapPreferences:
cmapSubtable = self.getcmap(platformID, platEncID)
if cmapSubtable is not None:
return cmapSubtable.cmap
return None
def buildReversed(self):
result = {}
for subtable in self.tables:
if subtable.isUnicode():
for codepoint, name in subtable.cmap.items():
result.setdefault(name, set()).add(codepoint)
return result
def decompile(self, data, ttFont):
tableVersion, numSubTables = struct.unpack(">HH", data[:4])
self.tableVersion = int(tableVersion)
self.tables = tables = []
seenOffsets = {}
for i in range(numSubTables):
platformID, platEncID, offset = struct.unpack(
">HHl", data[4+i*8:4+(i+1)*8])
platformID, platEncID = int(platformID), int(platEncID)
format, length = struct.unpack(">HH", data[offset:offset+4])
if format in [8,10,12,13]:
format, reserved, length = struct.unpack(">HHL", data[offset:offset+8])
elif format in [14]:
format, length = struct.unpack(">HL", data[offset:offset+6])
if not length:
log.error(
"cmap subtable is reported as having zero length: platformID %s, "
"platEncID %s, format %s offset %s. Skipping table.",
platformID, platEncID, format, offset)
continue
table = CmapSubtable.newSubtable(format)
table.platformID = platformID
table.platEncID = platEncID
table.decompileHeader(data[offset:offset+int(length)], ttFont)
if offset in seenOffsets:
table.data = None
table.cmap = tables[seenOffsets[offset]].cmap
else:
seenOffsets[offset] = i
tables.append(table)
def compile(self, ttFont):
self.tables.sort()
numSubTables = len(self.tables)
totalOffset = 4 + 8 * numSubTables
data = struct.pack(">HH", self.tableVersion, numSubTables)
tableData = b""
seen = {}
done = {} # Some tables are different objects, but compile to the same data chunk
for table in self.tables:
try:
offset = seen[id(table.cmap)]
except KeyError:
chunk = table.compile(ttFont)
if chunk in done:
offset = done[chunk]
else:
offset = seen[id(table.cmap)] = done[chunk] = totalOffset + len(tableData)
tableData = tableData + chunk
data = data + struct.pack(">HHl", table.platformID, table.platEncID, offset)
return data + tableData
def toXML(self, writer, ttFont):
writer.simpletag("tableVersion", version=self.tableVersion)
writer.newline()
for table in self.tables:
table.toXML(writer, ttFont)
def fromXML(self, name, attrs, content, ttFont):
if name == "tableVersion":
self.tableVersion = safeEval(attrs["version"])
return
if name[:12] != "cmap_format_":
return
if not hasattr(self, "tables"):
self.tables = []
format = safeEval(name[12:])
table = CmapSubtable.newSubtable(format)
table.platformID = safeEval(attrs["platformID"])
table.platEncID = safeEval(attrs["platEncID"])
table.fromXML(name, attrs, content, ttFont)
self.tables.append(table)
class CmapSubtable(object):
@staticmethod
def getSubtableClass(format):
return cmap_classes.get(format, cmap_format_unknown)
@staticmethod
def newSubtable(format):
subtableClass = CmapSubtable.getSubtableClass(format)
return subtableClass(format)
def __init__(self, format):
self.format = format
self.data = None
self.ttFont = None
def __getattr__(self, attr):
# allow lazy decompilation of subtables.
if attr[:2] == '__': # don't handle requests for member functions like '__lt__'
raise AttributeError(attr)
if self.data is None:
raise AttributeError(attr)
self.decompile(None, None)
self.data = None
# just return the original data. Also avoids recursion when
# called with an attribute that the cmap subtable doesn't have.
return getattr(self, attr)
def decompileHeader(self, data, ttFont):
format, length, language = struct.unpack(">HHH", data[:6])
assert len(data) == length, "corrupt cmap table format %d (data length: %d, header length: %d)" % (format, len(data), length)
self.format = int(format)
self.length = int(length)
self.language = int(language)
self.data = data[6:]
self.ttFont = ttFont
def toXML(self, writer, ttFont):
writer.begintag(self.__class__.__name__, [
("platformID", self.platformID),
("platEncID", self.platEncID),
("language", self.language),
])
writer.newline()
codes = sorted(self.cmap.items())
self._writeCodes(codes, writer)
writer.endtag(self.__class__.__name__)
writer.newline()
def getEncoding(self, default=None):
return getEncoding(self.platformID, self.platEncID, self.language, default)
def isUnicode(self):
return (self.platformID == 0 or
(self.platformID == 3 and self.platEncID in [0, 1, 10]))
def isSymbol(self):
return self.platformID == 3 and self.platEncID == 0
def _writeCodes(self, codes, writer):
isUnicode = self.isUnicode()
for code, name in codes:
writer.simpletag("map", code=hex(code), name=name)
if isUnicode:
writer.comment(Unicode[code])
writer.newline()
def __lt__(self, other):
if not isinstance(other, CmapSubtable):
return NotImplemented
selfTuple = (
getattr(self, "platformID", None),
getattr(self, "platEncID", None),
getattr(self, "language", None),
self.__dict__)
otherTuple = (
getattr(other, "platformID", None),
getattr(other, "platEncID", None),
getattr(other, "language", None),
other.__dict__)
return selfTuple < otherTuple
class cmap_format_0(CmapSubtable):
def decompile(self, data, ttFont):
if data is not None and ttFont is not None:
self.decompileHeader(data, ttFont)
else:
assert (data is None and ttFont is None), "Need both data and ttFont arguments"
data = self.data
assert 262 == self.length, "Format 0 cmap subtable not 262 bytes"
gids = array.array("B")
gids.frombytes(self.data)
charCodes = list(range(len(gids)))
self.cmap = _make_map(self.ttFont, charCodes, gids)
def compile(self, ttFont):
if self.data:
return struct.pack(">HHH", 0, 262, self.language) + self.data
cmap = self.cmap
assert set(cmap.keys()).issubset(range(256))
getGlyphID = ttFont.getGlyphID
valueList = [getGlyphID(cmap[i]) if i in cmap else 0 for i in range(256)]
gids = array.array("B", valueList)
data = struct.pack(">HHH", 0, 262, self.language) + gids.tobytes()
assert len(data) == 262
return data
def fromXML(self, name, attrs, content, ttFont):
self.language = safeEval(attrs["language"])
if not hasattr(self, "cmap"):
self.cmap = {}
cmap = self.cmap
for element in content:
if not isinstance(element, tuple):
continue
name, attrs, content = element
if name != "map":
continue
cmap[safeEval(attrs["code"])] = attrs["name"]
subHeaderFormat = ">HHhH"
class SubHeader(object):
def __init__(self):
self.firstCode = None
self.entryCount = None
self.idDelta = None
self.idRangeOffset = None
self.glyphIndexArray = []
class cmap_format_2(CmapSubtable):
def setIDDelta(self, subHeader):
subHeader.idDelta = 0
minGI = subHeader.glyphIndexArray[0]
for gid in subHeader.glyphIndexArray:
if (gid != 0) and (gid < minGI):
minGI = gid
if (minGI > 1):
if minGI > 0x7FFF:
subHeader.idDelta = -(0x10000 - minGI) -1
else:
subHeader.idDelta = minGI -1
idDelta = subHeader.idDelta
for i in range(subHeader.entryCount):
gid = subHeader.glyphIndexArray[i]
if gid > 0:
subHeader.glyphIndexArray[i] = gid - idDelta
def decompile(self, data, ttFont):
if data is not None and ttFont is not None:
self.decompileHeader(data, ttFont)
else:
assert (data is None and ttFont is None), "Need both data and ttFont arguments"
data = self.data
subHeaderKeys = []
maxSubHeaderindex = 0
allKeys = array.array("H")
allKeys.frombytes(data[:512])
data = data[512:]
if sys.byteorder != "big": allKeys.byteswap()
subHeaderKeys = [ key//8 for key in allKeys]
maxSubHeaderindex = max(subHeaderKeys)
subHeaderList = []
pos = 0
for i in range(maxSubHeaderindex + 1):
subHeader = SubHeader()
(subHeader.firstCode, subHeader.entryCount, subHeader.idDelta, \
subHeader.idRangeOffset) = struct.unpack(subHeaderFormat, data[pos:pos + 8])
pos += 8
giDataPos = pos + subHeader.idRangeOffset-2
giList = array.array("H")
giList.frombytes(data[giDataPos:giDataPos + subHeader.entryCount*2])
if sys.byteorder != "big": giList.byteswap()
subHeader.glyphIndexArray = giList
subHeaderList.append(subHeader)
self.data = b""
cmap = {}
notdefGI = 0
for firstByte in range(256):
subHeadindex = subHeaderKeys[firstByte]
subHeader = subHeaderList[subHeadindex]
if subHeadindex == 0:
if (firstByte < subHeader.firstCode) or (firstByte >= subHeader.firstCode + subHeader.entryCount):
continue
else:
charCode = firstByte
offsetIndex = firstByte - subHeader.firstCode
gi = subHeader.glyphIndexArray[offsetIndex]
if gi != 0:
gi = (gi + subHeader.idDelta) % 0x10000
else:
continue
cmap[charCode] = gi
else:
if subHeader.entryCount:
charCodeOffset = firstByte * 256 + subHeader.firstCode
for offsetIndex in range(subHeader.entryCount):
charCode = charCodeOffset + offsetIndex
gi = subHeader.glyphIndexArray[offsetIndex]
if gi != 0:
gi = (gi + subHeader.idDelta) % 0x10000
else:
continue
cmap[charCode] = gi
gids = list(cmap.values())
charCodes = list(cmap.keys())
self.cmap = _make_map(self.ttFont, charCodes, gids)
def compile(self, ttFont):
if self.data:
return struct.pack(">HHH", self.format, self.length, self.language) + self.data
kEmptyTwoCharCodeRange = -1
notdefGI = 0
items = sorted(self.cmap.items())
charCodes = [item[0] for item in items]
names = [item[1] for item in items]
nameMap = ttFont.getReverseGlyphMap()
try:
gids = [nameMap[name] for name in names]
except KeyError:
nameMap = ttFont.getReverseGlyphMap(rebuild=True)
try:
gids = [nameMap[name] for name in names]
except KeyError:
gids = []
for name in names:
try:
gid = nameMap[name]
except KeyError:
try:
if (name[:3] == 'gid'):
gid = int(name[3:])
else:
gid = ttFont.getGlyphID(name)
except:
raise KeyError(name)
gids.append(gid)
subHeaderKeys = [kEmptyTwoCharCodeRange for x in range(256)]
subHeaderList = []
charCode = charCodes[0]
if charCode > 255:
subHeader = SubHeader()
subHeader.firstCode = 0
subHeader.entryCount = 0
subHeader.idDelta = 0
subHeader.idRangeOffset = 0
subHeaderList.append(subHeader)
lastFirstByte = -1
items = zip(charCodes, gids)
for charCode, gid in items:
if gid == 0:
continue
firstbyte = charCode >> 8
secondByte = charCode & 0x00FF
if firstbyte != lastFirstByte:
if lastFirstByte > -1:
self.setIDDelta(subHeader)
# If it was sunheader 0 for one-byte charCodes, then we need to set the subHeaderKeys value to zero
# for the indices matching the char codes.
if lastFirstByte == 0:
for index in range(subHeader.entryCount):
charCode = subHeader.firstCode + index
subHeaderKeys[charCode] = 0
assert (subHeader.entryCount == len(subHeader.glyphIndexArray)), "Error - subhead entry count does not match len of glyphID subrange."
# init new subheader
subHeader = SubHeader()
subHeader.firstCode = secondByte
subHeader.entryCount = 1
subHeader.glyphIndexArray.append(gid)
subHeaderList.append(subHeader)
subHeaderKeys[firstbyte] = len(subHeaderList) -1
lastFirstByte = firstbyte
else:
# need to fill in with notdefs all the code points between the last charCode and the current charCode.
codeDiff = secondByte - (subHeader.firstCode + subHeader.entryCount)
for i in range(codeDiff):
subHeader.glyphIndexArray.append(notdefGI)
subHeader.glyphIndexArray.append(gid)
subHeader.entryCount = subHeader.entryCount + codeDiff + 1
# fix GI's and iDelta of last subheader that we we added to the subheader array.
self.setIDDelta(subHeader)
subHeader = SubHeader()
subHeader.firstCode = 0
subHeader.entryCount = 0
subHeader.idDelta = 0
subHeader.idRangeOffset = 2
subHeaderList.append(subHeader)
emptySubheadIndex = len(subHeaderList) - 1
for index in range(256):
if subHeaderKeys[index] == kEmptyTwoCharCodeRange:
subHeaderKeys[index] = emptySubheadIndex
idRangeOffset = (len(subHeaderList)-1)*8 + 2
subheadRangeLen = len(subHeaderList) -1
for index in range(subheadRangeLen):
subHeader = subHeaderList[index]
subHeader.idRangeOffset = 0
for j in range(index):
prevSubhead = subHeaderList[j]
if prevSubhead.glyphIndexArray == subHeader.glyphIndexArray: # use the glyphIndexArray subarray
subHeader.idRangeOffset = prevSubhead.idRangeOffset - (index-j)*8
subHeader.glyphIndexArray = []
break
if subHeader.idRangeOffset == 0: # didn't find one.
subHeader.idRangeOffset = idRangeOffset
idRangeOffset = (idRangeOffset - 8) + subHeader.entryCount*2
else:
idRangeOffset = idRangeOffset - 8
length = 6 + 512 + 8*len(subHeaderList)
for subhead in subHeaderList[:-1]:
length = length + len(subhead.glyphIndexArray)*2
dataList = [struct.pack(">HHH", 2, length, self.language)]
for index in subHeaderKeys:
dataList.append(struct.pack(">H", index*8))
for subhead in subHeaderList:
dataList.append(struct.pack(subHeaderFormat, subhead.firstCode, subhead.entryCount, subhead.idDelta, subhead.idRangeOffset))
for subhead in subHeaderList[:-1]:
for gi in subhead.glyphIndexArray:
dataList.append(struct.pack(">H", gi))
data = bytesjoin(dataList)
assert (len(data) == length), "Error: cmap format 2 is not same length as calculated! actual: " + str(len(data))+ " calc : " + str(length)
return data
def fromXML(self, name, attrs, content, ttFont):
self.language = safeEval(attrs["language"])
if not hasattr(self, "cmap"):
self.cmap = {}
cmap = self.cmap
for element in content:
if not isinstance(element, tuple):
continue
name, attrs, content = element
if name != "map":
continue
cmap[safeEval(attrs["code"])] = attrs["name"]
cmap_format_4_format = ">7H"
#uint16 endCode[segCount] # Ending character code for each segment, last = 0xFFFF.
#uint16 reservedPad # This value should be zero
#uint16 startCode[segCount] # Starting character code for each segment
#uint16 idDelta[segCount] # Delta for all character codes in segment
#uint16 idRangeOffset[segCount] # Offset in bytes to glyph indexArray, or 0
#uint16 glyphIndexArray[variable] # Glyph index array
def splitRange(startCode, endCode, cmap):
# Try to split a range of character codes into subranges with consecutive
# glyph IDs in such a way that the cmap4 subtable can be stored "most"
# efficiently. I can't prove I've got the optimal solution, but it seems
# to do well with the fonts I tested: none became bigger, many became smaller.
if startCode == endCode:
return [], [endCode]
lastID = cmap[startCode]
lastCode = startCode
inOrder = None
orderedBegin = None
subRanges = []
# Gather subranges in which the glyph IDs are consecutive.
for code in range(startCode + 1, endCode + 1):
glyphID = cmap[code]
if glyphID - 1 == lastID:
if inOrder is None or not inOrder:
inOrder = 1
orderedBegin = lastCode
else:
if inOrder:
inOrder = 0
subRanges.append((orderedBegin, lastCode))
orderedBegin = None
lastID = glyphID
lastCode = code
if inOrder:
subRanges.append((orderedBegin, lastCode))
assert lastCode == endCode
# Now filter out those new subranges that would only make the data bigger.
# A new segment cost 8 bytes, not using a new segment costs 2 bytes per
# character.
newRanges = []
for b, e in subRanges:
if b == startCode and e == endCode:
break # the whole range, we're fine
if b == startCode or e == endCode:
threshold = 4
else:
threshold = 8
if (e - b + 1) > threshold:
newRanges.append((b, e))
subRanges = newRanges
if not subRanges:
return [], [endCode]
if subRanges[0][0] != startCode:
subRanges.insert(0, (startCode, subRanges[0][0] - 1))
if subRanges[-1][1] != endCode:
subRanges.append((subRanges[-1][1] + 1, endCode))
i = 1
while i < len(subRanges):
if subRanges[i-1][1] + 1 != subRanges[i][0]:
subRanges.insert(i, (subRanges[i-1][1] + 1, subRanges[i][0] - 1))
i = i + 1
i = i + 1
start = []
end = []
for b, e in subRanges:
start.append(b)
end.append(e)
start.pop(0)
assert len(start) + 1 == len(end)
return start, end
class cmap_format_4(CmapSubtable):
def decompile(self, data, ttFont):
if data is not None and ttFont is not None:
self.decompileHeader(data, ttFont)
else:
assert (data is None and ttFont is None), "Need both data and ttFont arguments"
data = self.data
(segCountX2, searchRange, entrySelector, rangeShift) = \
struct.unpack(">4H", data[:8])
data = data[8:]
segCount = segCountX2 // 2
allCodes = array.array("H")
allCodes.frombytes(data)
self.data = data = None
if sys.byteorder != "big": allCodes.byteswap()
endCode = allCodes[:segCount]
allCodes = allCodes[segCount+1:]
startCode = allCodes[:segCount]
allCodes = allCodes[segCount:]
idDelta = allCodes[:segCount]
allCodes = allCodes[segCount:]
idRangeOffset = allCodes[:segCount]
glyphIndexArray = allCodes[segCount:]
lenGIArray = len(glyphIndexArray)
charCodes = []
gids = []
for i in range(len(startCode) - 1):
start = startCode[i]
delta = idDelta[i]
rangeOffset = idRangeOffset[i]
# *someone* needs to get killed.
partial = rangeOffset // 2 - start + i - len(idRangeOffset)
rangeCharCodes = list(range(startCode[i], endCode[i] + 1))
charCodes.extend(rangeCharCodes)
if rangeOffset == 0:
gids.extend([(charCode + delta) & 0xFFFF for charCode in rangeCharCodes])
else:
for charCode in rangeCharCodes:
index = charCode + partial
assert (index < lenGIArray), "In format 4 cmap, range (%d), the calculated index (%d) into the glyph index array is not less than the length of the array (%d) !" % (i, index, lenGIArray)
if glyphIndexArray[index] != 0: # if not missing glyph
glyphID = glyphIndexArray[index] + delta
else:
glyphID = 0 # missing glyph
gids.append(glyphID & 0xFFFF)
self.cmap = _make_map(self.ttFont, charCodes, gids)
def compile(self, ttFont):
if self.data:
return struct.pack(">HHH", self.format, self.length, self.language) + self.data
charCodes = list(self.cmap.keys())
if not charCodes:
startCode = [0xffff]
endCode = [0xffff]
else:
charCodes.sort()
names = [self.cmap[code] for code in charCodes]
nameMap = ttFont.getReverseGlyphMap()
try:
gids = [nameMap[name] for name in names]
except KeyError:
nameMap = ttFont.getReverseGlyphMap(rebuild=True)
try:
gids = [nameMap[name] for name in names]
except KeyError:
# allow virtual GIDs in format 4 tables
gids = []
for name in names:
try:
gid = nameMap[name]
except KeyError:
try:
if (name[:3] == 'gid'):
gid = int(name[3:])
else:
gid = ttFont.getGlyphID(name)
except:
raise KeyError(name)
gids.append(gid)
cmap = {} # code:glyphID mapping
for code, gid in zip(charCodes, gids):
cmap[code] = gid
# Build startCode and endCode lists.
# Split the char codes in ranges of consecutive char codes, then split
# each range in more ranges of consecutive/not consecutive glyph IDs.
# See splitRange().
lastCode = charCodes[0]
endCode = []
startCode = [lastCode]
for charCode in charCodes[1:]: # skip the first code, it's the first start code
if charCode == lastCode + 1:
lastCode = charCode
continue
start, end = splitRange(startCode[-1], lastCode, cmap)
startCode.extend(start)
endCode.extend(end)
startCode.append(charCode)
lastCode = charCode
start, end = splitRange(startCode[-1], lastCode, cmap)
startCode.extend(start)
endCode.extend(end)
startCode.append(0xffff)
endCode.append(0xffff)
idDelta = []
idRangeOffset = []
glyphIndexArray = []
for i in range(len(endCode)-1):
indices = []
for charCode in range(startCode[i], endCode[i] + 1):
indices.append(cmap[charCode])
if (indices == list(range(indices[0], indices[0] + len(indices)))):
idDelta.append((indices[0] - startCode[i]) % 0x10000)
idRangeOffset.append(0)
else:
idDelta.append(0)
idRangeOffset.append(2 * (len(endCode) + len(glyphIndexArray) - i))
glyphIndexArray.extend(indices)
idDelta.append(1)
idRangeOffset.append(0)
segCount = len(endCode)
segCountX2 = segCount * 2
searchRange, entrySelector, rangeShift = getSearchRange(segCount, 2)
charCodeArray = array.array("H", endCode + [0] + startCode)
idDeltaArray = array.array("H", idDelta)
restArray = array.array("H", idRangeOffset + glyphIndexArray)
if sys.byteorder != "big": charCodeArray.byteswap()
if sys.byteorder != "big": idDeltaArray.byteswap()
if sys.byteorder != "big": restArray.byteswap()
data = charCodeArray.tobytes() + idDeltaArray.tobytes() + restArray.tobytes()
length = struct.calcsize(cmap_format_4_format) + len(data)
header = struct.pack(cmap_format_4_format, self.format, length, self.language,
segCountX2, searchRange, entrySelector, rangeShift)
return header + data
def fromXML(self, name, attrs, content, ttFont):
self.language = safeEval(attrs["language"])
if not hasattr(self, "cmap"):
self.cmap = {}
cmap = self.cmap
for element in content:
if not isinstance(element, tuple):
continue
nameMap, attrsMap, dummyContent = element
if nameMap != "map":
assert 0, "Unrecognized keyword in cmap subtable"
cmap[safeEval(attrsMap["code"])] = attrsMap["name"]
class cmap_format_6(CmapSubtable):
def decompile(self, data, ttFont):
if data is not None and ttFont is not None:
self.decompileHeader(data, ttFont)
else:
assert (data is None and ttFont is None), "Need both data and ttFont arguments"
data = self.data
firstCode, entryCount = struct.unpack(">HH", data[:4])
firstCode = int(firstCode)
data = data[4:]
bytes(data[:2 * int(entryCount)])
if sys.byteorder != "big": gids.byteswap()
self.data = data = None
charCodes = list(range(firstCode, firstCode + len(gids)))
self.cmap = _make_map(self.ttFont, charCodes, gids)
def compile(self, ttFont):
if self.data:
return struct.pack(">HHH", self.format, self.length, self.language) + self.data
cmap = self.cmap
codes = sorted(cmap.keys())
if codes: # yes, there are empty cmap tables.
codes = list(range(codes[0], codes[-1] + 1))
firstCode = codes[0]
valueList = [
ttFont.getGlyphID(cmap[code]) if code in cmap else 0
for code in codes
]
gids = array.array("H", valueList)
if sys.byteorder != "big": gids.byteswap()
data = gids.tobytes()
else:
data = b""
firstCode = 0
header = struct.pack(">HHHHH",
6, len(data) + 10, self.language, firstCode, len(codes))
return header + data
def fromXML(self, name, attrs, content, ttFont):
self.language = safeEval(attrs["language"])
if not hasattr(self, "cmap"):
self.cmap = {}
cmap = self.cmap
for element in content:
if not isinstance(element, tuple):
continue
name, attrs, content = element
if name != "map":
continue
cmap[safeEval(attrs["code"])] = attrs["name"]
class cmap_format_12_or_13(CmapSubtable):
def __init__(self, format):
self.format = format
self.reserved = 0
self.data = None
self.ttFont = None
def decompileHeader(self, data, ttFont):
format, reserved, length, language, nGroups = struct.unpack(">HHLLL", data[:16])
assert len(data) == (16 + nGroups*12) == (length), "corrupt cmap table format %d (data length: %d, header length: %d)" % (self.format, len(data), length)
self.format = format
self.reserved = reserved
self.length = length
self.language = language
self.nGroups = nGroups
self.data = data[16:]
self.ttFont = ttFont
def decompile(self, data, ttFont):
# we usually get here indirectly from the subtable __getattr__ function, in which case both args must be None.
# If not, someone is calling the subtable decompile() directly, and must provide both args.
if data is not None and ttFont is not None:
self.decompileHeader(data, ttFont)
else:
assert (data is None and ttFont is None), "Need both data and ttFont arguments"
data = self.data # decompileHeader assigns the data after the header to self.data
charCodes = []
gids = []
pos = 0
for i in range(self.nGroups):
startCharCode, endCharCode, glyphID = struct.unpack(">LLL",data[pos:pos+12] )
pos += 12
lenGroup = 1 + endCharCode - startCharCode
charCodes.extend(list(range(startCharCode, endCharCode +1)))
gids.extend(self._computeGIDs(glyphID, lenGroup))
self.data = data = None
self.cmap = _make_map(self.ttFont, charCodes, gids)
def compile(self, ttFont):
if self.data:
return struct.pack(">HHLLL", self.format, self.reserved, self.length, self.language, self.nGroups) + self.data
charCodes = list(self.cmap.keys())
names = list(self.cmap.values())
nameMap = ttFont.getReverseGlyphMap()
try:
gids = [nameMap[name] for name in names]
except KeyError:
nameMap = ttFont.getReverseGlyphMap(rebuild=True)
try:
gids = [nameMap[name] for name in names]
except KeyError:
# allow virtual GIDs in format 12 tables
gids = []
for name in names:
try:
gid = nameMap[name]
except KeyError:
try:
if (name[:3] == 'gid'):
gid = int(name[3:])
else:
gid = ttFont.getGlyphID(name)
except:
raise KeyError(name)
gids.append(gid)
cmap = {} # code:glyphID mapping
for code, gid in zip(charCodes, gids):
cmap[code] = gid
charCodes.sort()
index = 0
startCharCode = charCodes[0]
startGlyphID = cmap[startCharCode]
lastGlyphID = startGlyphID - self._format_step
lastCharCode = startCharCode - 1
nGroups = 0
dataList = []
maxIndex = len(charCodes)
for index in range(maxIndex):
charCode = charCodes[index]
glyphID = cmap[charCode]
if not self._IsInSameRun(glyphID, lastGlyphID, charCode, lastCharCode):
dataList.append(struct.pack(">LLL", startCharCode, lastCharCode, startGlyphID))
startCharCode = charCode
startGlyphID = glyphID
nGroups = nGroups + 1
lastGlyphID = glyphID
lastCharCode = charCode
dataList.append(struct.pack(">LLL", startCharCode, lastCharCode, startGlyphID))
nGroups = nGroups + 1
data = bytesjoin(dataList)
lengthSubtable = len(data) +16
assert len(data) == (nGroups*12) == (lengthSubtable-16)
return struct.pack(">HHLLL", self.format, self.reserved, lengthSubtable, self.language, nGroups) + data
def toXML(self, writer, ttFont):
writer.begintag(self.__class__.__name__, [
("platformID", self.platformID),
("platEncID", self.platEncID),
("format", self.format),
("reserved", self.reserved),
("length", self.length),
("language", self.language),
("nGroups", self.nGroups),
])
writer.newline()
codes = sorted(self.cmap.items())
self._writeCodes(codes, writer)
writer.endtag(self.__class__.__name__)
writer.newline()
def fromXML(self, name, attrs, content, ttFont):
self.format = safeEval(attrs["format"])
self.reserved = safeEval(attrs["reserved"])
self.length = safeEval(attrs["length"])
self.language = safeEval(attrs["language"])
self.nGroups = safeEval(attrs["nGroups"])
if not hasattr(self, "cmap"):
self.cmap = {}
cmap = self.cmap
for element in content:
if not isinstance(element, tuple):
continue
name, attrs, content = element
if name != "map":
continue
cmap[safeEval(attrs["code"])] = attrs["name"]
class cmap_format_12(cmap_format_12_or_13):
_format_step = 1
def __init__(self, format=12):
cmap_format_12_or_13.__init__(self, format)
def _computeGIDs(self, startingGlyph, numberOfGlyphs):
return list(range(startingGlyph, startingGlyph + numberOfGlyphs))
def _IsInSameRun(self, glyphID, lastGlyphID, charCode, lastCharCode):
return (glyphID == 1 + lastGlyphID) and (charCode == 1 + lastCharCode)
class cmap_format_13(cmap_format_12_or_13):
_format_step = 0
def __init__(self, format=13):
cmap_format_12_or_13.__init__(self, format)
def _computeGIDs(self, startingGlyph, numberOfGlyphs):
return [startingGlyph] * numberOfGlyphs
def _IsInSameRun(self, glyphID, lastGlyphID, charCode, lastCharCode):
return (glyphID == lastGlyphID) and (charCode == 1 + lastCharCode)
def cvtToUVS(threeByteString):
data = b"\0" + threeByteString
val, = struct.unpack(">L", data)
return val
def cvtFromUVS(val):
assert 0 <= val < 0x1000000
fourByteString = struct.pack(">L", val)
return fourByteString[1:]
class cmap_format_14(CmapSubtable):
def decompileHeader(self, data, ttFont):
format, length, numVarSelectorRecords = struct.unpack(">HLL", data[:10])
self.data = data[10:]
self.length = length
self.numVarSelectorRecords = numVarSelectorRecords
self.ttFont = ttFont
self.language = 0xFF # has no language.
def decompile(self, data, ttFont):
if data is not None and ttFont is not None:
self.decompileHeader(data, ttFont)
else:
assert (data is None and ttFont is None), "Need both data and ttFont arguments"
data = self.data
self.cmap = {} # so that clients that expect this to exist in a cmap table won't fail.
uvsDict = {}
recOffset = 0
for n in range(self.numVarSelectorRecords):
uvs, defOVSOffset, nonDefUVSOffset = struct.unpack(">3sLL", data[recOffset:recOffset +11])
recOffset += 11
varUVS = cvtToUVS(uvs)
if defOVSOffset:
startOffset = defOVSOffset - 10
numValues, = struct.unpack(">L", data[startOffset:startOffset+4])
startOffset +=4
for r in range(numValues):
uv, addtlCnt = struct.unpack(">3sB", data[startOffset:startOffset+4])
startOffset += 4
firstBaseUV = cvtToUVS(uv)
cnt = addtlCnt+1
baseUVList = list(range(firstBaseUV, firstBaseUV+cnt))
glyphList = [None]*cnt
localUVList = zip(baseUVList, glyphList)
try:
uvsDict[varUVS].extend(localUVList)
except KeyError:
uvsDict[varUVS] = list(localUVList)
if nonDefUVSOffset:
startOffset = nonDefUVSOffset - 10
numRecs, = struct.unpack(">L", data[startOffset:startOffset+4])
startOffset +=4
localUVList = []
for r in range(numRecs):
uv, gid = struct.unpack(">3sH", data[startOffset:startOffset+5])
startOffset += 5
uv = cvtToUVS(uv)
glyphName = self.ttFont.getGlyphName(gid)
localUVList.append((uv, glyphName))
try:
uvsDict[varUVS].extend(localUVList)
except KeyError:
uvsDict[varUVS] = localUVList
self.uvsDict = uvsDict
def toXML(self, writer, ttFont):
writer.begintag(self.__class__.__name__, [
("platformID", self.platformID),
("platEncID", self.platEncID),
])
writer.newline()
uvsDict = self.uvsDict
uvsList = sorted(uvsDict.keys())
for uvs in uvsList:
uvList = uvsDict[uvs]
uvList.sort(key=lambda item: (item[1] is not None, item[0], item[1]))
for uv, gname in uvList:
attrs = [("uv", hex(uv)), ("uvs", hex(uvs))]
if gname is not None:
attrs.append(("name", gname))
writer.simpletag("map", attrs)
writer.newline()
writer.endtag(self.__class__.__name__)
writer.newline()
def fromXML(self, name, attrs, content, ttFont):
self.language = 0xFF
if not hasattr(self, "cmap"):
self.cmap = {} # so that clients that expect this to exist in a cmap table won't fail.
if not hasattr(self, "uvsDict"):
self.uvsDict = {}
uvsDict = self.uvsDict
_hasGlyphNamedNone = None
for element in content:
if not isinstance(element, tuple):
continue
name, attrs, content = element
if name != "map":
continue
uvs = safeEval(attrs["uvs"])
uv = safeEval(attrs["uv"])
gname = attrs.get("name")
if gname == "None":
if _hasGlyphNamedNone is None:
_hasGlyphNamedNone = "None" in ttFont.getGlyphOrder()
if not _hasGlyphNamedNone:
gname = None
try:
uvsDict[uvs].append((uv, gname))
except KeyError:
uvsDict[uvs] = [(uv, gname)]
def compile(self, ttFont):
if self.data:
return struct.pack(">HLL", self.format, self.length, self.numVarSelectorRecords) + self.data
uvsDict = self.uvsDict
uvsList = sorted(uvsDict.keys())
self.numVarSelectorRecords = len(uvsList)
offset = 10 + self.numVarSelectorRecords*11
data = []
varSelectorRecords =[]
for uvs in uvsList:
entryList = uvsDict[uvs]
defList = [entry for entry in entryList if entry[1] is None]
if defList:
defList = [entry[0] for entry in defList]
defOVSOffset = offset
defList.sort()
lastUV = defList[0]
cnt = -1
defRecs = []
for defEntry in defList:
cnt +=1
if (lastUV+cnt) != defEntry:
rec = struct.pack(">3sB", cvtFromUVS(lastUV), cnt-1)
lastUV = defEntry
defRecs.append(rec)
cnt = 0
rec = struct.pack(">3sB", cvtFromUVS(lastUV), cnt)
defRecs.append(rec)
numDefRecs = len(defRecs)
data.append(struct.pack(">L", numDefRecs))
data.extend(defRecs)
offset += 4 + numDefRecs*4
else:
defOVSOffset = 0
ndefList = [entry for entry in entryList if entry[1] is not None]
if ndefList:
nonDefUVSOffset = offset
ndefList.sort()
numNonDefRecs = len(ndefList)
data.append(struct.pack(">L", numNonDefRecs))
offset += 4 + numNonDefRecs*5
for uv, gname in ndefList:
gid = ttFont.getGlyphID(gname)
ndrec = struct.pack(">3sH", cvtFromUVS(uv), gid)
data.append(ndrec)
else:
nonDefUVSOffset = 0
vrec = struct.pack(">3sLL", cvtFromUVS(uvs), defOVSOffset, nonDefUVSOffset)
varSelectorRecords.append(vrec)
data = bytesjoin(varSelectorRecords) + bytesjoin(data)
self.length = 10 + len(data)
headerdata = struct.pack(">HLL", self.format, self.length, self.numVarSelectorRecords)
return headerdata + data
class cmap_format_unknown(CmapSubtable):
def toXML(self, writer, ttFont):
cmapName = self.__class__.__name__[:12] + str(self.format)
writer.begintag(cmapName, [
("platformID", self.platformID),
("platEncID", self.platEncID),
])
writer.newline()
writer.dumphex(self.data)
writer.endtag(cmapName)
writer.newline()
def fromXML(self, name, attrs, content, ttFont):
self.data = readHex(content)
self.cmap = {}
def decompileHeader(self, data, ttFont):
self.language = 0
self.data = data
def decompile(self, data, ttFont):
if data is not None and ttFont is not None:
self.decompileHeader(data, ttFont)
else:
assert (data is None and ttFont is None), "Need both data and ttFont arguments"
def compile(self, ttFont):
if self.data:
return self.data
else:
return None
cmap_classes = {
0: cmap_format_0,
2: cmap_format_2,
4: cmap_format_4,
6: cmap_format_6,
12: cmap_format_12,
13: cmap_format_13,
14: cmap_format_14,
}
| true | true |
f7f926ed34066ddacdcd3afe5880a5e521b52bc1 | 480 | py | Python | OpenCV2/Image_Processing/Canny_Edge_Detection.py | siddharth-143/Python | 293f4643a3a13e3b82d23fd8922db54dbb0f12bc | [
"MIT"
] | null | null | null | OpenCV2/Image_Processing/Canny_Edge_Detection.py | siddharth-143/Python | 293f4643a3a13e3b82d23fd8922db54dbb0f12bc | [
"MIT"
] | null | null | null | OpenCV2/Image_Processing/Canny_Edge_Detection.py | siddharth-143/Python | 293f4643a3a13e3b82d23fd8922db54dbb0f12bc | [
"MIT"
] | null | null | null | """
OpenCV Canny Edge Detection :
Edge detection is term where identify the boundary of object in image.
"""
# importing module
import cv2
import numpy as np
# image path
img = cv2.imread("../images/1.jpeg")
# canny edge detection
edges = cv2.Canny(img, 100, 200)
# display the image
cv2.imshow("Edge detection image", edges)
cv2.imshow("Original image", img)
# waits until a key is pressed
cv2.waitKey(0)
# destroys the window showing image
cv2.destroyAllWindows()
| 19.2 | 74 | 0.725 |
import cv2
import numpy as np
img = cv2.imread("../images/1.jpeg")
edges = cv2.Canny(img, 100, 200)
cv2.imshow("Edge detection image", edges)
cv2.imshow("Original image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
| true | true |
f7f92756d4144e78fb3424cd6acd0c6a581225e4 | 1,209 | py | Python | desktopmagic/scripts/screengrab_torture_test.py | p3rd1x/Desktopmagic | 906cbe16f4e6c5fea7121c186ff8c6e7c997b2f7 | [
"MIT"
] | 49 | 2015-05-20T08:19:42.000Z | 2021-11-12T17:20:40.000Z | desktopmagic/scripts/screengrab_torture_test.py | p3rd1x/Desktopmagic | 906cbe16f4e6c5fea7121c186ff8c6e7c997b2f7 | [
"MIT"
] | 9 | 2015-06-17T22:47:21.000Z | 2022-03-15T09:00:28.000Z | desktopmagic/scripts/screengrab_torture_test.py | p3rd1x/Desktopmagic | 906cbe16f4e6c5fea7121c186ff8c6e7c997b2f7 | [
"MIT"
] | 16 | 2015-12-13T18:34:45.000Z | 2021-02-17T13:50:17.000Z | from __future__ import print_function
import sys
from desktopmagic.screengrab_win32 import GrabFailed, getScreenAsImage, getDisplaysAsImages, getRectAsImage
def main():
print("""\
This program helps you test whether screengrab_win32 has memory leaks
and other problems. It takes a screenshot repeatedly and discards it.
Open Task Manager and make sure Physical Memory % is not ballooning.
Memory leaks might not be blamed on the python process itself (which
will show low memory usage).
Lock the workstation for a few minutes; make sure there are no leaks
and that there are no uncaught exceptions here.
Repeat above after RDPing into the workstation and minimizing RDP;
this is like disconnecting the monitor.
Change your color depth settings. Add and remove monitors. RDP
in at 256 colors.
""")
while True:
try:
getScreenAsImage()
print("S", end=" ")
sys.stdout.flush()
except GrabFailed as e:
print(e)
try:
getDisplaysAsImages()
print("D", end=" ")
sys.stdout.flush()
except GrabFailed as e:
print(e)
try:
getRectAsImage((0, 0, 1, 1))
print("R", end=" ")
sys.stdout.flush()
except GrabFailed as e:
print(e)
if __name__ == '__main__':
main()
| 24.18 | 107 | 0.732837 | from __future__ import print_function
import sys
from desktopmagic.screengrab_win32 import GrabFailed, getScreenAsImage, getDisplaysAsImages, getRectAsImage
def main():
print("""\
This program helps you test whether screengrab_win32 has memory leaks
and other problems. It takes a screenshot repeatedly and discards it.
Open Task Manager and make sure Physical Memory % is not ballooning.
Memory leaks might not be blamed on the python process itself (which
will show low memory usage).
Lock the workstation for a few minutes; make sure there are no leaks
and that there are no uncaught exceptions here.
Repeat above after RDPing into the workstation and minimizing RDP;
this is like disconnecting the monitor.
Change your color depth settings. Add and remove monitors. RDP
in at 256 colors.
""")
while True:
try:
getScreenAsImage()
print("S", end=" ")
sys.stdout.flush()
except GrabFailed as e:
print(e)
try:
getDisplaysAsImages()
print("D", end=" ")
sys.stdout.flush()
except GrabFailed as e:
print(e)
try:
getRectAsImage((0, 0, 1, 1))
print("R", end=" ")
sys.stdout.flush()
except GrabFailed as e:
print(e)
if __name__ == '__main__':
main()
| true | true |
f7f927d5ac30fab3f5f2adddff8da39245dd8131 | 998 | py | Python | flaskr/__init__.py | iJKENNEDY/template_flask | 9810d2ab5750ec3603203a12004d21aed3bc61be | [
"MIT"
] | null | null | null | flaskr/__init__.py | iJKENNEDY/template_flask | 9810d2ab5750ec3603203a12004d21aed3bc61be | [
"MIT"
] | null | null | null | flaskr/__init__.py | iJKENNEDY/template_flask | 9810d2ab5750ec3603203a12004d21aed3bc61be | [
"MIT"
] | null | null | null | import os
from flask import Flask
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY='dev',
DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
)
if test_config is None:
# load the instance config, if it exists, when not testing
app.config.from_pyfile('config.py', silent=True)
else:
# load the test config if passed in
app.config.from_mapping(test_config)
# ensure the instance folder exists
try:
os.makedirs(app.instance_path)
except OSError:
pass
# a simple page that says hello
@app.route('/hello')
def hello():
return 'Hello, World!'
from . import db
db.init_app(app)
from . import auth
app.register_blueprint(auth.bp)
from . import blog
app.register_blueprint(blog.bp)
app.add_url_rule('/', endpoint='index')
return app | 23.761905 | 66 | 0.650301 | import os
from flask import Flask
def create_app(test_config=None):
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY='dev',
DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
)
if test_config is None:
app.config.from_pyfile('config.py', silent=True)
else:
app.config.from_mapping(test_config)
try:
os.makedirs(app.instance_path)
except OSError:
pass
@app.route('/hello')
def hello():
return 'Hello, World!'
from . import db
db.init_app(app)
from . import auth
app.register_blueprint(auth.bp)
from . import blog
app.register_blueprint(blog.bp)
app.add_url_rule('/', endpoint='index')
return app | true | true |
f7f9284e0b60183c0350cf42a0c81e48b3757b0c | 201 | py | Python | nbds_colab/ensemble1.py | hallmx/nbds_colab | 77e5cab5805a95cc1c80f7ee3ca9429c94e1876a | [
"Apache-2.0"
] | null | null | null | nbds_colab/ensemble1.py | hallmx/nbds_colab | 77e5cab5805a95cc1c80f7ee3ca9429c94e1876a | [
"Apache-2.0"
] | 2 | 2021-09-28T00:53:05.000Z | 2022-02-26T06:41:34.000Z | nbds_colab/ensemble1.py | hallmx/nbds_colab | 77e5cab5805a95cc1c80f7ee3ca9429c94e1876a | [
"Apache-2.0"
] | null | null | null | # AUTOGENERATED! DO NOT EDIT! File to edit: 08_ensemble1.ipynb (unless otherwise specified).
__all__ = ['ensemble1_test']
# Cell
def ensemble1_test(test_msg):
"Function ensemble1"
return test_msg | 25.125 | 92 | 0.766169 |
__all__ = ['ensemble1_test']
def ensemble1_test(test_msg):
return test_msg | true | true |
f7f929eec1c39bd6596a57c691c9257c4fac1c2b | 2,402 | py | Python | sdk/python/pulumi_azure_nextgen/azurestack/latest/get_registration_activation_key.py | test-wiz-sec/pulumi-azure-nextgen | 20a695af0d020b34b0f1c336e1b69702755174cc | [
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_azure_nextgen/azurestack/latest/get_registration_activation_key.py | test-wiz-sec/pulumi-azure-nextgen | 20a695af0d020b34b0f1c336e1b69702755174cc | [
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_azure_nextgen/azurestack/latest/get_registration_activation_key.py | test-wiz-sec/pulumi-azure-nextgen | 20a695af0d020b34b0f1c336e1b69702755174cc | [
"Apache-2.0"
] | null | null | null | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
__all__ = [
'GetRegistrationActivationKeyResult',
'AwaitableGetRegistrationActivationKeyResult',
'get_registration_activation_key',
]
@pulumi.output_type
class GetRegistrationActivationKeyResult:
"""
The resource containing the Azure Stack activation key.
"""
def __init__(__self__, activation_key=None):
if activation_key and not isinstance(activation_key, str):
raise TypeError("Expected argument 'activation_key' to be a str")
pulumi.set(__self__, "activation_key", activation_key)
@property
@pulumi.getter(name="activationKey")
def activation_key(self) -> Optional[str]:
"""
Azure Stack activation key.
"""
return pulumi.get(self, "activation_key")
class AwaitableGetRegistrationActivationKeyResult(GetRegistrationActivationKeyResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetRegistrationActivationKeyResult(
activation_key=self.activation_key)
def get_registration_activation_key(registration_name: Optional[str] = None,
resource_group: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetRegistrationActivationKeyResult:
"""
Use this data source to access information about an existing resource.
:param str registration_name: Name of the Azure Stack registration.
:param str resource_group: Name of the resource group.
"""
__args__ = dict()
__args__['registrationName'] = registration_name
__args__['resourceGroup'] = resource_group
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('azure-nextgen:azurestack/latest:getRegistrationActivationKey', __args__, opts=opts, typ=GetRegistrationActivationKeyResult).value
return AwaitableGetRegistrationActivationKeyResult(
activation_key=__ret__.activation_key)
| 36.953846 | 166 | 0.710241 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
__all__ = [
'GetRegistrationActivationKeyResult',
'AwaitableGetRegistrationActivationKeyResult',
'get_registration_activation_key',
]
@pulumi.output_type
class GetRegistrationActivationKeyResult:
def __init__(__self__, activation_key=None):
if activation_key and not isinstance(activation_key, str):
raise TypeError("Expected argument 'activation_key' to be a str")
pulumi.set(__self__, "activation_key", activation_key)
@property
@pulumi.getter(name="activationKey")
def activation_key(self) -> Optional[str]:
return pulumi.get(self, "activation_key")
class AwaitableGetRegistrationActivationKeyResult(GetRegistrationActivationKeyResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetRegistrationActivationKeyResult(
activation_key=self.activation_key)
def get_registration_activation_key(registration_name: Optional[str] = None,
resource_group: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetRegistrationActivationKeyResult:
__args__ = dict()
__args__['registrationName'] = registration_name
__args__['resourceGroup'] = resource_group
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('azure-nextgen:azurestack/latest:getRegistrationActivationKey', __args__, opts=opts, typ=GetRegistrationActivationKeyResult).value
return AwaitableGetRegistrationActivationKeyResult(
activation_key=__ret__.activation_key)
| true | true |
f7f92a15a8847696c90342e9eaf5928425147312 | 20,984 | py | Python | tensorflow/contrib/tensor_forest/client/random_forest.py | wunlung/tensorflow | e2b05608125d66716ada95433850b3ce8405c1e4 | [
"Apache-2.0"
] | 1 | 2021-04-14T07:48:21.000Z | 2021-04-14T07:48:21.000Z | tensorflow/contrib/tensor_forest/client/random_forest.py | ggaziv/tensorflow | e2b05608125d66716ada95433850b3ce8405c1e4 | [
"Apache-2.0"
] | null | null | null | tensorflow/contrib/tensor_forest/client/random_forest.py | ggaziv/tensorflow | e2b05608125d66716ada95433850b3ce8405c1e4 | [
"Apache-2.0"
] | 1 | 2018-03-16T05:49:15.000Z | 2018-03-16T05:49:15.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.
# ==============================================================================
"""A tf.learn implementation of tensor_forest (extremely random forests)."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib import framework as contrib_framework
from tensorflow.contrib.learn.python.learn.estimators import estimator
from tensorflow.contrib.learn.python.learn.estimators import head as head_lib
from tensorflow.contrib.learn.python.learn.estimators import model_fn as model_fn_lib
from tensorflow.contrib.tensor_forest.client import eval_metrics
from tensorflow.contrib.tensor_forest.python import tensor_forest
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.ops import state_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.summary import summary
from tensorflow.python.training import basic_session_run_hooks
from tensorflow.python.training import session_run_hook
KEYS_NAME = 'keys'
LOSS_NAME = 'rf_training_loss'
TREE_PATHS_PREDICTION_KEY = 'tree_paths'
EPSILON = 0.000001
def _assert_float32(tensors):
"""Assert all tensors are float32.
Args:
tensors: `Tensor` or `dict` of `Tensor` objects.
Raises:
TypeError: if any tensor is not float32.
"""
if not isinstance(tensors, dict):
tensors = [tensors]
else:
tensors = tensors.values()
for tensor in tensors:
if tensor.dtype.base_dtype != dtypes.float32:
raise TypeError('Expected dtype=float32, %s.' % tensor)
class TensorForestRunOpAtEndHook(session_run_hook.SessionRunHook):
def __init__(self, op_dict):
"""Ops is a dict of {name: op} to run before the session is destroyed."""
self._ops = op_dict
def end(self, session):
for name in sorted(self._ops.keys()):
logging.info('{0}: {1}'.format(name, session.run(self._ops[name])))
class TensorForestLossHook(session_run_hook.SessionRunHook):
"""Monitor to request stop when loss stops decreasing."""
def __init__(self,
early_stopping_rounds,
early_stopping_loss_threshold=None,
loss_op=None):
self.early_stopping_rounds = early_stopping_rounds
self.early_stopping_loss_threshold = early_stopping_loss_threshold
self.loss_op = loss_op
self.min_loss = None
self.last_step = -1
# self.steps records the number of steps for which the loss has been
# non-decreasing
self.steps = 0
def before_run(self, run_context):
loss = (self.loss_op if self.loss_op is not None else
run_context.session.graph.get_operation_by_name(
LOSS_NAME).outputs[0])
return session_run_hook.SessionRunArgs(
{'global_step': contrib_framework.get_global_step(),
'current_loss': loss})
def after_run(self, run_context, run_values):
current_loss = run_values.results['current_loss']
current_step = run_values.results['global_step']
self.steps += 1
# Guard against the global step going backwards, which might happen
# if we recover from something.
if self.last_step == -1 or self.last_step > current_step:
logging.info('TensorForestLossHook resetting last_step.')
self.last_step = current_step
self.steps = 0
self.min_loss = None
return
self.last_step = current_step
if (self.min_loss is None or current_loss <
(self.min_loss - self.min_loss * self.early_stopping_loss_threshold)):
self.min_loss = current_loss
self.steps = 0
if self.steps > self.early_stopping_rounds:
logging.info('TensorForestLossHook requesting stop.')
run_context.request_stop()
class EveryCheckpointPreSaveListener(
basic_session_run_hooks.CheckpointSaverListener):
"""Runs a given op before each checkpoint save."""
def __init__(self, op):
"""Initializes the object.
Args:
op: An op to run before each checkpoint save.
"""
self._op = op
def before_save(self, session, global_step_value):
session.run(self._op)
def get_default_head(params, weights_name, name=None):
if params.regression:
return head_lib.regression_head(
weight_column_name=weights_name,
label_dimension=params.num_outputs,
enable_centered_bias=False,
head_name=name)
else:
return head_lib.multi_class_head(
params.num_classes,
weight_column_name=weights_name,
enable_centered_bias=False,
head_name=name)
def get_model_fn(params,
graph_builder_class,
device_assigner,
weights_name=None,
model_head=None,
keys_name=None,
early_stopping_rounds=100,
early_stopping_loss_threshold=0.001,
num_trainers=1,
trainer_id=0,
report_feature_importances=False,
local_eval=False,
head_scope=None):
"""Return a model function given a way to construct a graph builder."""
if model_head is None:
model_head = get_default_head(params, weights_name)
def _model_fn(features, labels, mode):
"""Function that returns predictions, training loss, and training op."""
if (isinstance(features, ops.Tensor) or
isinstance(features, sparse_tensor.SparseTensor)):
features = {'features': features}
weights = None
if weights_name and weights_name in features:
weights = features.pop(weights_name)
keys = None
if keys_name and keys_name in features:
keys = features.pop(keys_name)
# If we're doing eval, optionally ignore device_assigner.
# Also ignore device assigner if we're exporting (mode == INFER)
dev_assn = device_assigner
if (mode == model_fn_lib.ModeKeys.INFER or
(local_eval and mode == model_fn_lib.ModeKeys.EVAL)):
dev_assn = None
graph_builder = graph_builder_class(params,
device_assigner=dev_assn)
logits, tree_paths = graph_builder.inference_graph(features)
summary.scalar('average_tree_size', graph_builder.average_size())
# For binary classification problems, convert probabilities to logits.
# Includes hack to get around the fact that a probability might be 0 or 1.
if not params.regression and params.num_classes == 2:
class_1_probs = array_ops.slice(logits, [0, 1], [-1, 1])
logits = math_ops.log(
math_ops.maximum(class_1_probs / math_ops.maximum(
1.0 - class_1_probs, EPSILON), EPSILON))
# labels might be None if we're doing prediction (which brings up the
# question of why we force everything to adhere to a single model_fn).
training_graph = None
training_hooks = []
if labels is not None and mode == model_fn_lib.ModeKeys.TRAIN:
with ops.control_dependencies([logits.op]):
training_graph = control_flow_ops.group(
graph_builder.training_graph(
features, labels, input_weights=weights,
num_trainers=num_trainers,
trainer_id=trainer_id),
state_ops.assign_add(contrib_framework.get_global_step(), 1))
# Put weights back in
if weights is not None:
features[weights_name] = weights
# TensorForest's training graph isn't calculated directly from the loss
# like many other models.
def _train_fn(unused_loss):
return training_graph
model_ops = model_head.create_model_fn_ops(
features=features,
labels=labels,
mode=mode,
train_op_fn=_train_fn,
logits=logits,
scope=head_scope)
# Ops are run in lexigraphical order of their keys. Run the resource
# clean-up op last.
all_handles = graph_builder.get_all_resource_handles()
ops_at_end = {
'9: clean up resources': control_flow_ops.group(
*[resource_variable_ops.destroy_resource_op(handle)
for handle in all_handles])}
if report_feature_importances:
ops_at_end['1: feature_importances'] = (
graph_builder.feature_importances())
training_hooks.append(TensorForestRunOpAtEndHook(ops_at_end))
if early_stopping_rounds:
training_hooks.append(
TensorForestLossHook(
early_stopping_rounds,
early_stopping_loss_threshold=early_stopping_loss_threshold,
loss_op=model_ops.loss))
model_ops.training_hooks.extend(training_hooks)
if keys is not None:
model_ops.predictions[keys_name] = keys
if params.inference_tree_paths:
model_ops.predictions[TREE_PATHS_PREDICTION_KEY] = tree_paths
return model_ops
return _model_fn
class TensorForestEstimator(estimator.Estimator):
"""An estimator that can train and evaluate a random forest.
Example:
```python
params = tf.contrib.tensor_forest.python.tensor_forest.ForestHParams(
num_classes=2, num_features=40, num_trees=10, max_nodes=1000)
# Estimator using the default graph builder.
estimator = TensorForestEstimator(params, model_dir=model_dir)
# Or estimator using TrainingLossForest as the graph builder.
estimator = TensorForestEstimator(
params, graph_builder_class=tensor_forest.TrainingLossForest,
model_dir=model_dir)
# Input builders
def input_fn_train: # returns x, y
...
def input_fn_eval: # returns x, y
...
estimator.fit(input_fn=input_fn_train)
estimator.evaluate(input_fn=input_fn_eval)
# Predict returns an iterable of dicts.
results = list(estimator.predict(x=x))
prob0 = results[0][eval_metrics.INFERENCE_PROB_NAME]
prediction0 = results[0][eval_metrics.INFERENCE_PRED_NAME]
```
"""
def __init__(self,
params,
device_assigner=None,
model_dir=None,
graph_builder_class=tensor_forest.RandomForestGraphs,
config=None,
weights_name=None,
keys_name=None,
feature_engineering_fn=None,
early_stopping_rounds=100,
early_stopping_loss_threshold=0.001,
num_trainers=1,
trainer_id=0,
report_feature_importances=False,
local_eval=False,
version=None,
head=None):
"""Initializes a TensorForestEstimator instance.
Args:
params: ForestHParams object that holds random forest hyperparameters.
These parameters will be passed into `model_fn`.
device_assigner: An `object` instance that controls how trees get
assigned to devices. If `None`, will use
`tensor_forest.RandomForestDeviceAssigner`.
model_dir: Directory to save model parameters, graph, etc. To continue
training a previously saved model, load checkpoints saved to this
directory into an estimator.
graph_builder_class: An `object` instance that defines how TF graphs for
random forest training and inference are built. By default will use
`tensor_forest.RandomForestGraphs`. Can be overridden by version
kwarg.
config: `RunConfig` object to configure the runtime settings.
weights_name: A string defining feature column name representing
weights. Will be multiplied by the loss of the example. Used to
downweight or boost examples during training.
keys_name: A string naming one of the features to strip out and
pass through into the inference/eval results dict. Useful for
associating specific examples with their prediction.
feature_engineering_fn: Feature engineering function. Takes features and
labels which are the output of `input_fn` and returns features and
labels which will be fed into the model.
early_stopping_rounds: Allows training to terminate early if the forest is
no longer growing. 100 by default. Set to a Falsy value to disable
the default training hook.
early_stopping_loss_threshold: Percentage (as fraction) that loss must
improve by within early_stopping_rounds steps, otherwise training will
terminate.
num_trainers: Number of training jobs, which will partition trees
among them.
trainer_id: Which trainer this instance is.
report_feature_importances: If True, print out feature importances
during evaluation.
local_eval: If True, don't use a device assigner for eval. This is to
support some common setups where eval is done on a single machine, even
though training might be distributed.
version: Unused.
head: A heads_lib.Head object that calculates losses and such. If None,
one will be automatically created based on params.
Returns:
A `TensorForestEstimator` instance.
"""
super(TensorForestEstimator, self).__init__(
model_fn=get_model_fn(
params.fill(),
graph_builder_class,
device_assigner,
model_head=head,
weights_name=weights_name,
keys_name=keys_name,
early_stopping_rounds=early_stopping_rounds,
early_stopping_loss_threshold=early_stopping_loss_threshold,
num_trainers=num_trainers,
trainer_id=trainer_id,
report_feature_importances=report_feature_importances,
local_eval=local_eval),
model_dir=model_dir,
config=config,
feature_engineering_fn=feature_engineering_fn)
def get_combined_model_fn(model_fns):
"""Get a combined model function given a list of other model fns.
The model function returned will call the individual model functions and
combine them appropriately. For:
training ops: tf.group them.
loss: average them.
predictions: concat probabilities such that predictions[*][0-C1] are the
probablities for output 1 (where C1 is the number of classes in output 1),
predictions[*][C1-(C1+C2)] are the probabilities for output 2 (where C2
is the number of classes in output 2), etc. Also stack predictions such
that predictions[i][j] is the class prediction for example i and output j.
This assumes that labels are 2-dimensional, with labels[i][j] being the
label for example i and output j, where forest j is trained using only
output j.
Args:
model_fns: A list of model functions obtained from get_model_fn.
Returns:
A ModelFnOps instance.
"""
def _model_fn(features, labels, mode):
"""Function that returns predictions, training loss, and training op."""
model_fn_ops = []
for i in range(len(model_fns)):
with variable_scope.variable_scope('label_{0}'.format(i)):
sliced_labels = array_ops.slice(labels, [0, i], [-1, 1])
model_fn_ops.append(
model_fns[i](features, sliced_labels, mode))
training_hooks = []
for mops in model_fn_ops:
training_hooks += mops.training_hooks
predictions = {}
if (mode == model_fn_lib.ModeKeys.EVAL or
mode == model_fn_lib.ModeKeys.INFER):
# Flatten the probabilities into one dimension.
predictions[eval_metrics.INFERENCE_PROB_NAME] = array_ops.concat(
[mops.predictions[eval_metrics.INFERENCE_PROB_NAME]
for mops in model_fn_ops], axis=1)
predictions[eval_metrics.INFERENCE_PRED_NAME] = array_ops.stack(
[mops.predictions[eval_metrics.INFERENCE_PRED_NAME]
for mops in model_fn_ops], axis=1)
loss = None
if (mode == model_fn_lib.ModeKeys.EVAL or
mode == model_fn_lib.ModeKeys.TRAIN):
loss = math_ops.reduce_sum(
array_ops.stack(
[mops.loss for mops in model_fn_ops])) / len(model_fn_ops)
train_op = None
if mode == model_fn_lib.ModeKeys.TRAIN:
train_op = control_flow_ops.group(
*[mops.train_op for mops in model_fn_ops])
return model_fn_lib.ModelFnOps(
mode=mode,
predictions=predictions,
loss=loss,
train_op=train_op,
training_hooks=training_hooks,
scaffold=None,
output_alternatives=None)
return _model_fn
class MultiForestMultiHeadEstimator(estimator.Estimator):
"""An estimator that can train a forest for a multi-headed problems.
This class essentially trains separate forests (each with their own
ForestHParams) for each output.
For multi-headed regression, a single-headed TensorForestEstimator can
be used to train a single model that predicts all outputs. This class can
be used to train separate forests for each output.
"""
def __init__(self, params_list, device_assigner=None, model_dir=None,
graph_builder_class=tensor_forest.RandomForestGraphs,
config=None, weights_name=None, keys_name=None,
feature_engineering_fn=None,
early_stopping_rounds=100,
num_trainers=1, trainer_id=0,
report_feature_importances=False,
local_eval=False):
"""Initializes a TensorForestEstimator instance.
Args:
params_list: A list of ForestHParams objects for each head, given in order
of outputs in the label tensor to be trained on.
device_assigner: An `object` instance that controls how trees get
assigned to devices. If `None`, will use
`tensor_forest.RandomForestDeviceAssigner`.
model_dir: Directory to save model parameters, graph, etc. To continue
training a previously saved model, load checkpoints saved to this
directory into an estimator.
graph_builder_class: An `object` instance that defines how TF graphs for
random forest training and inference are built. By default will use
`tensor_forest.RandomForestGraphs`.
config: `RunConfig` object to configure the runtime settings.
weights_name: A string defining feature column name representing
weights. Will be multiplied by the loss of the example. Used to
downweight or boost examples during training.
keys_name: A string naming one of the features to strip out and
pass through into the inference/eval results dict. Useful for
associating specific examples with their prediction.
feature_engineering_fn: Feature engineering function. Takes features and
labels which are the output of `input_fn` and returns features and
labels which will be fed into the model.
early_stopping_rounds: Allows training to terminate early if the forest is
no longer growing. 100 by default. Set to a Falsy value to disable
the default training hook.
num_trainers: Number of training jobs, which will partition trees
among them.
trainer_id: Which trainer this instance is.
report_feature_importances: If True, print out feature importances
during evaluation.
local_eval: If True, don't use a device assigner for eval. This is to
support some common setups where eval is done on a single machine, even
though training might be distributed.
Returns:
A `TensorForestEstimator` instance.
"""
model_fns = []
for i in range(len(params_list)):
params = params_list[i].fill()
model_fns.append(
get_model_fn(
params,
graph_builder_class,
device_assigner,
model_head=get_default_head(
params, weights_name, name='head{0}'.format(i)),
weights_name=weights_name,
keys_name=keys_name,
early_stopping_rounds=early_stopping_rounds,
num_trainers=num_trainers,
trainer_id=trainer_id,
report_feature_importances=report_feature_importances,
local_eval=local_eval,
head_scope='output{0}'.format(i)))
super(MultiForestMultiHeadEstimator, self).__init__(
model_fn=get_combined_model_fn(model_fns),
model_dir=model_dir,
config=config,
feature_engineering_fn=feature_engineering_fn)
| 39.07635 | 85 | 0.697674 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib import framework as contrib_framework
from tensorflow.contrib.learn.python.learn.estimators import estimator
from tensorflow.contrib.learn.python.learn.estimators import head as head_lib
from tensorflow.contrib.learn.python.learn.estimators import model_fn as model_fn_lib
from tensorflow.contrib.tensor_forest.client import eval_metrics
from tensorflow.contrib.tensor_forest.python import tensor_forest
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.ops import state_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.summary import summary
from tensorflow.python.training import basic_session_run_hooks
from tensorflow.python.training import session_run_hook
KEYS_NAME = 'keys'
LOSS_NAME = 'rf_training_loss'
TREE_PATHS_PREDICTION_KEY = 'tree_paths'
EPSILON = 0.000001
def _assert_float32(tensors):
if not isinstance(tensors, dict):
tensors = [tensors]
else:
tensors = tensors.values()
for tensor in tensors:
if tensor.dtype.base_dtype != dtypes.float32:
raise TypeError('Expected dtype=float32, %s.' % tensor)
class TensorForestRunOpAtEndHook(session_run_hook.SessionRunHook):
def __init__(self, op_dict):
self._ops = op_dict
def end(self, session):
for name in sorted(self._ops.keys()):
logging.info('{0}: {1}'.format(name, session.run(self._ops[name])))
class TensorForestLossHook(session_run_hook.SessionRunHook):
def __init__(self,
early_stopping_rounds,
early_stopping_loss_threshold=None,
loss_op=None):
self.early_stopping_rounds = early_stopping_rounds
self.early_stopping_loss_threshold = early_stopping_loss_threshold
self.loss_op = loss_op
self.min_loss = None
self.last_step = -1
self.steps = 0
def before_run(self, run_context):
loss = (self.loss_op if self.loss_op is not None else
run_context.session.graph.get_operation_by_name(
LOSS_NAME).outputs[0])
return session_run_hook.SessionRunArgs(
{'global_step': contrib_framework.get_global_step(),
'current_loss': loss})
def after_run(self, run_context, run_values):
current_loss = run_values.results['current_loss']
current_step = run_values.results['global_step']
self.steps += 1
if self.last_step == -1 or self.last_step > current_step:
logging.info('TensorForestLossHook resetting last_step.')
self.last_step = current_step
self.steps = 0
self.min_loss = None
return
self.last_step = current_step
if (self.min_loss is None or current_loss <
(self.min_loss - self.min_loss * self.early_stopping_loss_threshold)):
self.min_loss = current_loss
self.steps = 0
if self.steps > self.early_stopping_rounds:
logging.info('TensorForestLossHook requesting stop.')
run_context.request_stop()
class EveryCheckpointPreSaveListener(
basic_session_run_hooks.CheckpointSaverListener):
def __init__(self, op):
self._op = op
def before_save(self, session, global_step_value):
session.run(self._op)
def get_default_head(params, weights_name, name=None):
if params.regression:
return head_lib.regression_head(
weight_column_name=weights_name,
label_dimension=params.num_outputs,
enable_centered_bias=False,
head_name=name)
else:
return head_lib.multi_class_head(
params.num_classes,
weight_column_name=weights_name,
enable_centered_bias=False,
head_name=name)
def get_model_fn(params,
graph_builder_class,
device_assigner,
weights_name=None,
model_head=None,
keys_name=None,
early_stopping_rounds=100,
early_stopping_loss_threshold=0.001,
num_trainers=1,
trainer_id=0,
report_feature_importances=False,
local_eval=False,
head_scope=None):
if model_head is None:
model_head = get_default_head(params, weights_name)
def _model_fn(features, labels, mode):
if (isinstance(features, ops.Tensor) or
isinstance(features, sparse_tensor.SparseTensor)):
features = {'features': features}
weights = None
if weights_name and weights_name in features:
weights = features.pop(weights_name)
keys = None
if keys_name and keys_name in features:
keys = features.pop(keys_name)
# Also ignore device assigner if we're exporting (mode == INFER)
dev_assn = device_assigner
if (mode == model_fn_lib.ModeKeys.INFER or
(local_eval and mode == model_fn_lib.ModeKeys.EVAL)):
dev_assn = None
graph_builder = graph_builder_class(params,
device_assigner=dev_assn)
logits, tree_paths = graph_builder.inference_graph(features)
summary.scalar('average_tree_size', graph_builder.average_size())
if not params.regression and params.num_classes == 2:
class_1_probs = array_ops.slice(logits, [0, 1], [-1, 1])
logits = math_ops.log(
math_ops.maximum(class_1_probs / math_ops.maximum(
1.0 - class_1_probs, EPSILON), EPSILON))
# question of why we force everything to adhere to a single model_fn).
training_graph = None
training_hooks = []
if labels is not None and mode == model_fn_lib.ModeKeys.TRAIN:
with ops.control_dependencies([logits.op]):
training_graph = control_flow_ops.group(
graph_builder.training_graph(
features, labels, input_weights=weights,
num_trainers=num_trainers,
trainer_id=trainer_id),
state_ops.assign_add(contrib_framework.get_global_step(), 1))
# Put weights back in
if weights is not None:
features[weights_name] = weights
# TensorForest's training graph isn't calculated directly from the loss
# like many other models.
def _train_fn(unused_loss):
return training_graph
model_ops = model_head.create_model_fn_ops(
features=features,
labels=labels,
mode=mode,
train_op_fn=_train_fn,
logits=logits,
scope=head_scope)
# Ops are run in lexigraphical order of their keys. Run the resource
# clean-up op last.
all_handles = graph_builder.get_all_resource_handles()
ops_at_end = {
'9: clean up resources': control_flow_ops.group(
*[resource_variable_ops.destroy_resource_op(handle)
for handle in all_handles])}
if report_feature_importances:
ops_at_end['1: feature_importances'] = (
graph_builder.feature_importances())
training_hooks.append(TensorForestRunOpAtEndHook(ops_at_end))
if early_stopping_rounds:
training_hooks.append(
TensorForestLossHook(
early_stopping_rounds,
early_stopping_loss_threshold=early_stopping_loss_threshold,
loss_op=model_ops.loss))
model_ops.training_hooks.extend(training_hooks)
if keys is not None:
model_ops.predictions[keys_name] = keys
if params.inference_tree_paths:
model_ops.predictions[TREE_PATHS_PREDICTION_KEY] = tree_paths
return model_ops
return _model_fn
class TensorForestEstimator(estimator.Estimator):
def __init__(self,
params,
device_assigner=None,
model_dir=None,
graph_builder_class=tensor_forest.RandomForestGraphs,
config=None,
weights_name=None,
keys_name=None,
feature_engineering_fn=None,
early_stopping_rounds=100,
early_stopping_loss_threshold=0.001,
num_trainers=1,
trainer_id=0,
report_feature_importances=False,
local_eval=False,
version=None,
head=None):
super(TensorForestEstimator, self).__init__(
model_fn=get_model_fn(
params.fill(),
graph_builder_class,
device_assigner,
model_head=head,
weights_name=weights_name,
keys_name=keys_name,
early_stopping_rounds=early_stopping_rounds,
early_stopping_loss_threshold=early_stopping_loss_threshold,
num_trainers=num_trainers,
trainer_id=trainer_id,
report_feature_importances=report_feature_importances,
local_eval=local_eval),
model_dir=model_dir,
config=config,
feature_engineering_fn=feature_engineering_fn)
def get_combined_model_fn(model_fns):
def _model_fn(features, labels, mode):
model_fn_ops = []
for i in range(len(model_fns)):
with variable_scope.variable_scope('label_{0}'.format(i)):
sliced_labels = array_ops.slice(labels, [0, i], [-1, 1])
model_fn_ops.append(
model_fns[i](features, sliced_labels, mode))
training_hooks = []
for mops in model_fn_ops:
training_hooks += mops.training_hooks
predictions = {}
if (mode == model_fn_lib.ModeKeys.EVAL or
mode == model_fn_lib.ModeKeys.INFER):
# Flatten the probabilities into one dimension.
predictions[eval_metrics.INFERENCE_PROB_NAME] = array_ops.concat(
[mops.predictions[eval_metrics.INFERENCE_PROB_NAME]
for mops in model_fn_ops], axis=1)
predictions[eval_metrics.INFERENCE_PRED_NAME] = array_ops.stack(
[mops.predictions[eval_metrics.INFERENCE_PRED_NAME]
for mops in model_fn_ops], axis=1)
loss = None
if (mode == model_fn_lib.ModeKeys.EVAL or
mode == model_fn_lib.ModeKeys.TRAIN):
loss = math_ops.reduce_sum(
array_ops.stack(
[mops.loss for mops in model_fn_ops])) / len(model_fn_ops)
train_op = None
if mode == model_fn_lib.ModeKeys.TRAIN:
train_op = control_flow_ops.group(
*[mops.train_op for mops in model_fn_ops])
return model_fn_lib.ModelFnOps(
mode=mode,
predictions=predictions,
loss=loss,
train_op=train_op,
training_hooks=training_hooks,
scaffold=None,
output_alternatives=None)
return _model_fn
class MultiForestMultiHeadEstimator(estimator.Estimator):
def __init__(self, params_list, device_assigner=None, model_dir=None,
graph_builder_class=tensor_forest.RandomForestGraphs,
config=None, weights_name=None, keys_name=None,
feature_engineering_fn=None,
early_stopping_rounds=100,
num_trainers=1, trainer_id=0,
report_feature_importances=False,
local_eval=False):
model_fns = []
for i in range(len(params_list)):
params = params_list[i].fill()
model_fns.append(
get_model_fn(
params,
graph_builder_class,
device_assigner,
model_head=get_default_head(
params, weights_name, name='head{0}'.format(i)),
weights_name=weights_name,
keys_name=keys_name,
early_stopping_rounds=early_stopping_rounds,
num_trainers=num_trainers,
trainer_id=trainer_id,
report_feature_importances=report_feature_importances,
local_eval=local_eval,
head_scope='output{0}'.format(i)))
super(MultiForestMultiHeadEstimator, self).__init__(
model_fn=get_combined_model_fn(model_fns),
model_dir=model_dir,
config=config,
feature_engineering_fn=feature_engineering_fn)
| true | true |
f7f92a9a5709c2b464a4d05e569d5f8996fbcf5b | 6,372 | py | Python | airbyte-integrations/connectors/source-file/integration_tests/conftest.py | golf-canada/airbyte | a81b183a6b62d6bb4256347aaf39a3ada061aabe | [
"MIT"
] | null | null | null | airbyte-integrations/connectors/source-file/integration_tests/conftest.py | golf-canada/airbyte | a81b183a6b62d6bb4256347aaf39a3ada061aabe | [
"MIT"
] | null | null | null | airbyte-integrations/connectors/source-file/integration_tests/conftest.py | golf-canada/airbyte | a81b183a6b62d6bb4256347aaf39a3ada061aabe | [
"MIT"
] | null | null | null | """
MIT License
Copyright (c) 2020 Airbyte
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 json
import os
import socket
import tempfile
import uuid
from pathlib import Path
from typing import Mapping
import boto3
import pandas
import pytest
from botocore.errorfactory import ClientError
from google.api_core.exceptions import Conflict
from google.cloud import storage
from paramiko.client import AutoAddPolicy, SSHClient
from paramiko.ssh_exception import SSHException
HERE = Path(__file__).parent.absolute()
@pytest.fixture(scope="session")
def docker_compose_file() -> Path:
return HERE / "docker-compose.yml"
@pytest.fixture(scope="session")
def google_cloud_service_file() -> Path:
return HERE.parent / "secrets/gcs.json"
@pytest.fixture(scope="session")
def google_cloud_service_credentials(google_cloud_service_file) -> Mapping:
with open(google_cloud_service_file) as json_file:
return json.load(json_file)
@pytest.fixture(scope="session")
def aws_credentials() -> Mapping:
filename = HERE.parent / "secrets/aws.json"
with open(filename) as json_file:
return json.load(json_file)
@pytest.fixture(scope="session")
def cloud_bucket_name():
return "airbytetestbucket"
def is_ssh_ready(ip, port):
try:
with SSHClient() as ssh:
ssh.set_missing_host_key_policy(AutoAddPolicy)
ssh.connect(
ip,
port=port,
username="user1",
password="pass1",
)
return True
except (SSHException, socket.error):
return False
@pytest.fixture(scope="session")
def ssh_service(docker_ip, docker_services):
"""Ensure that SSH service is up and responsive."""
# `port_for` takes a container port and returns the corresponding host port
port = docker_services.port_for("ssh", 22)
docker_services.wait_until_responsive(timeout=30.0, pause=0.1, check=lambda: is_ssh_ready(docker_ip, port))
return docker_ip
@pytest.fixture
def provider_config(ssh_service):
def lookup(name):
providers = {
"ssh": dict(storage="SSH", host=ssh_service, user="user1", password="pass1", port=2222),
"scp": dict(storage="SCP", host=ssh_service, user="user1", password="pass1", port=2222),
"sftp": dict(storage="SFTP", host=ssh_service, user="user1", password="pass1", port=100),
"gcs": dict(storage="GCS"),
"s3": dict(storage="S3"),
}
return providers[name]
return lookup
def create_unique_gcs_bucket(storage_client, name: str) -> str:
"""
Make a unique bucket to which we'll upload the file.
(GCS buckets are part of a single global namespace.)
"""
for i in range(0, 5):
bucket_name = f"{name}-{uuid.uuid1()}"
try:
bucket = storage_client.bucket(bucket_name)
bucket.storage_class = "STANDARD"
# fixed locations are cheaper...
storage_client.create_bucket(bucket, location="us-east1")
print(f"\nNew GCS bucket created {bucket_name}")
return bucket_name
except Conflict:
print(f"\nError: {bucket_name} already exists!")
@pytest.fixture(scope="session")
def download_gcs_public_data():
print("\nDownload public dataset from gcs to local /tmp")
df = pandas.read_csv("https://storage.googleapis.com/covid19-open-data/v2/latest/epidemiology.csv")
tmp_file = tempfile.NamedTemporaryFile(delete=False)
df.to_csv(tmp_file.name, index=False)
yield tmp_file.name
os.remove(tmp_file.name)
print(f"\nLocal File {tmp_file.name} is now deleted")
@pytest.fixture(scope="session")
def private_google_cloud_file(google_cloud_service_file, cloud_bucket_name, download_gcs_public_data):
storage_client = storage.Client.from_service_account_json(str(google_cloud_service_file))
bucket_name = create_unique_gcs_bucket(storage_client, cloud_bucket_name)
print(f"\nUpload dataset to private gcs bucket {bucket_name}")
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob("myfile.csv")
blob.upload_from_filename(download_gcs_public_data)
yield f"{bucket_name}/myfile.csv"
bucket.delete(force=True)
print(f"\nGCS Bucket {bucket_name} is now deleted")
@pytest.fixture(scope="session")
def private_aws_file(aws_credentials, cloud_bucket_name, download_gcs_public_data):
region = "eu-west-3"
location = {"LocationConstraint": region}
s3_client = boto3.client(
"s3",
aws_access_key_id=aws_credentials["aws_access_key_id"],
aws_secret_access_key=aws_credentials["aws_secret_access_key"],
region_name=region,
)
bucket_name = cloud_bucket_name
print(f"\nUpload dataset to private aws bucket {bucket_name}")
try:
s3_client.head_bucket(Bucket=bucket_name)
except ClientError:
s3_client.create_bucket(Bucket=bucket_name, CreateBucketConfiguration=location)
s3_client.upload_file(download_gcs_public_data, bucket_name, "myfile.csv")
yield f"{bucket_name}/myfile.csv"
s3 = boto3.resource(
"s3", aws_access_key_id=aws_credentials["aws_access_key_id"], aws_secret_access_key=aws_credentials["aws_secret_access_key"]
)
bucket = s3.Bucket(bucket_name)
bucket.objects.all().delete()
print(f"\nS3 Bucket {bucket_name} is now deleted")
| 34.258065 | 132 | 0.719083 |
import json
import os
import socket
import tempfile
import uuid
from pathlib import Path
from typing import Mapping
import boto3
import pandas
import pytest
from botocore.errorfactory import ClientError
from google.api_core.exceptions import Conflict
from google.cloud import storage
from paramiko.client import AutoAddPolicy, SSHClient
from paramiko.ssh_exception import SSHException
HERE = Path(__file__).parent.absolute()
@pytest.fixture(scope="session")
def docker_compose_file() -> Path:
return HERE / "docker-compose.yml"
@pytest.fixture(scope="session")
def google_cloud_service_file() -> Path:
return HERE.parent / "secrets/gcs.json"
@pytest.fixture(scope="session")
def google_cloud_service_credentials(google_cloud_service_file) -> Mapping:
with open(google_cloud_service_file) as json_file:
return json.load(json_file)
@pytest.fixture(scope="session")
def aws_credentials() -> Mapping:
filename = HERE.parent / "secrets/aws.json"
with open(filename) as json_file:
return json.load(json_file)
@pytest.fixture(scope="session")
def cloud_bucket_name():
return "airbytetestbucket"
def is_ssh_ready(ip, port):
try:
with SSHClient() as ssh:
ssh.set_missing_host_key_policy(AutoAddPolicy)
ssh.connect(
ip,
port=port,
username="user1",
password="pass1",
)
return True
except (SSHException, socket.error):
return False
@pytest.fixture(scope="session")
def ssh_service(docker_ip, docker_services):
port = docker_services.port_for("ssh", 22)
docker_services.wait_until_responsive(timeout=30.0, pause=0.1, check=lambda: is_ssh_ready(docker_ip, port))
return docker_ip
@pytest.fixture
def provider_config(ssh_service):
def lookup(name):
providers = {
"ssh": dict(storage="SSH", host=ssh_service, user="user1", password="pass1", port=2222),
"scp": dict(storage="SCP", host=ssh_service, user="user1", password="pass1", port=2222),
"sftp": dict(storage="SFTP", host=ssh_service, user="user1", password="pass1", port=100),
"gcs": dict(storage="GCS"),
"s3": dict(storage="S3"),
}
return providers[name]
return lookup
def create_unique_gcs_bucket(storage_client, name: str) -> str:
for i in range(0, 5):
bucket_name = f"{name}-{uuid.uuid1()}"
try:
bucket = storage_client.bucket(bucket_name)
bucket.storage_class = "STANDARD"
storage_client.create_bucket(bucket, location="us-east1")
print(f"\nNew GCS bucket created {bucket_name}")
return bucket_name
except Conflict:
print(f"\nError: {bucket_name} already exists!")
@pytest.fixture(scope="session")
def download_gcs_public_data():
print("\nDownload public dataset from gcs to local /tmp")
df = pandas.read_csv("https://storage.googleapis.com/covid19-open-data/v2/latest/epidemiology.csv")
tmp_file = tempfile.NamedTemporaryFile(delete=False)
df.to_csv(tmp_file.name, index=False)
yield tmp_file.name
os.remove(tmp_file.name)
print(f"\nLocal File {tmp_file.name} is now deleted")
@pytest.fixture(scope="session")
def private_google_cloud_file(google_cloud_service_file, cloud_bucket_name, download_gcs_public_data):
storage_client = storage.Client.from_service_account_json(str(google_cloud_service_file))
bucket_name = create_unique_gcs_bucket(storage_client, cloud_bucket_name)
print(f"\nUpload dataset to private gcs bucket {bucket_name}")
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob("myfile.csv")
blob.upload_from_filename(download_gcs_public_data)
yield f"{bucket_name}/myfile.csv"
bucket.delete(force=True)
print(f"\nGCS Bucket {bucket_name} is now deleted")
@pytest.fixture(scope="session")
def private_aws_file(aws_credentials, cloud_bucket_name, download_gcs_public_data):
region = "eu-west-3"
location = {"LocationConstraint": region}
s3_client = boto3.client(
"s3",
aws_access_key_id=aws_credentials["aws_access_key_id"],
aws_secret_access_key=aws_credentials["aws_secret_access_key"],
region_name=region,
)
bucket_name = cloud_bucket_name
print(f"\nUpload dataset to private aws bucket {bucket_name}")
try:
s3_client.head_bucket(Bucket=bucket_name)
except ClientError:
s3_client.create_bucket(Bucket=bucket_name, CreateBucketConfiguration=location)
s3_client.upload_file(download_gcs_public_data, bucket_name, "myfile.csv")
yield f"{bucket_name}/myfile.csv"
s3 = boto3.resource(
"s3", aws_access_key_id=aws_credentials["aws_access_key_id"], aws_secret_access_key=aws_credentials["aws_secret_access_key"]
)
bucket = s3.Bucket(bucket_name)
bucket.objects.all().delete()
print(f"\nS3 Bucket {bucket_name} is now deleted")
| true | true |
f7f92ac258f92ba7447035ac1330134b91ddfd9d | 21,250 | py | Python | src/bin/calc_rec-cycrec-gv_gru-cycle-mcepvae-laplace_noar.py | entn-at/cyclevae-vc-neuralvoco | e0188457fe6d16e53b91066600dfe6fd5a9f8c23 | [
"Apache-2.0"
] | null | null | null | src/bin/calc_rec-cycrec-gv_gru-cycle-mcepvae-laplace_noar.py | entn-at/cyclevae-vc-neuralvoco | e0188457fe6d16e53b91066600dfe6fd5a9f8c23 | [
"Apache-2.0"
] | null | null | null | src/bin/calc_rec-cycrec-gv_gru-cycle-mcepvae-laplace_noar.py | entn-at/cyclevae-vc-neuralvoco | e0188457fe6d16e53b91066600dfe6fd5a9f8c23 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2020 Patrick Lumban Tobing (Nagoya University)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
from __future__ import division
import argparse
import logging
import math
import os
import sys
import numpy as np
import torch
import torch.multiprocessing as mp
from vcneuvoco import GRU_VAE_ENCODER, GRU_SPEC_DECODER
from utils import find_files, read_hdf5, read_txt, write_hdf5, check_hdf5
from dtw_c import dtw_c as dtw
import torch.nn.functional as F
import h5py
#np.set_printoptions(threshold=np.inf)
def main():
parser = argparse.ArgumentParser()
# decode setting
parser.add_argument("--feats", required=True,
type=str, help="list or directory of source eval feat files")
parser.add_argument("--spk", required=True,
type=str, help="speaker name to be reconstructed")
parser.add_argument("--model", required=True,
type=str, help="model file")
parser.add_argument("--config", required=True,
type=str, help="configure file")
parser.add_argument("--n_gpus", default=1,
type=int, help="number of gpus")
parser.add_argument("--outdir", required=True,
type=str, help="directory to save log")
parser.add_argument("--string_path", required=True,
type=str, help="path of h5 generated feature")
# other setting
parser.add_argument("--GPU_device", default=None,
type=int, help="selection of GPU device")
parser.add_argument("--GPU_device_str", default=None,
type=str, help="selection of GPU device")
parser.add_argument("--verbose", default=1,
type=int, help="log level")
args = parser.parse_args()
if args.GPU_device is not None or args.GPU_device_str is not None:
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
if args.GPU_device_str is None:
os.environ["CUDA_VISIBLE_DEVICES"] = str(args.GPU_device)
else:
os.environ["CUDA_VISIBLE_DEVICES"] = args.GPU_device_str
# check directory existence
if not os.path.exists(args.outdir):
os.makedirs(args.outdir)
# set log level
if args.verbose > 0:
logging.basicConfig(level=logging.INFO,
format='%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s',
datefmt='%m/%d/%Y %I:%M:%S', filemode='w',
filename=args.outdir + "/decode.log")
logging.getLogger().addHandler(logging.StreamHandler())
elif args.verbose > 1:
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s',
datefmt='%m/%d/%Y %I:%M:%S', filemode='w',
filename=args.outdir + "/decode.log")
logging.getLogger().addHandler(logging.StreamHandler())
else:
logging.basicConfig(level=logging.WARN,
format='%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s',
datefmt='%m/%d/%Y %I:%M:%S', filemode='w',
filename=args.outdir + "/decode.log")
logging.getLogger().addHandler(logging.StreamHandler())
logging.warn("logging is disabled.")
# load config
config = torch.load(args.config)
# get source feat list
if os.path.isdir(args.feats):
feat_list = sorted(find_files(args.feats, "*.h5"))
elif os.path.isfile(args.feats):
feat_list = read_txt(args.feats)
else:
logging.error("--feats should be directory or list.")
sys.exit(1)
# prepare the file list for parallel decoding
feat_lists = np.array_split(feat_list, args.n_gpus)
feat_lists = [f_list.tolist() for f_list in feat_lists]
for i in range(args.n_gpus):
logging.info('%d: %d' % (i+1, len(feat_lists[i])))
spk_list = config.spk_list.split('@')
n_spk = len(spk_list)
spk_idx = spk_list.index(args.spk)
stats_list = config.stats_list.split('@')
assert(n_spk == len(stats_list))
spk_stat = stats_list[spk_idx]
gv_mean = read_hdf5(spk_stat, "/gv_range_mean")[1:]
model_epoch = os.path.basename(args.model).split('.')[0].split('-')[1]
logging.info('epoch: '+model_epoch)
model_name = os.path.basename(os.path.dirname(args.model)).split('_')[1]
logging.info('mdl_name: '+model_name)
logging.info(config)
# define gpu decode function
def gpu_decode(feat_list, gpu, cvlist=None, mcdpow_cvlist=None, mcdpowstd_cvlist=None, mcd_cvlist=None, \
mcdstd_cvlist=None, cvlist_dv=None, mcdpow_cvlist_dv=None, mcdpowstd_cvlist_dv=None, \
mcd_cvlist_dv=None, mcdstd_cvlist_dv=None, \
cvlist_cyc=None, mcdpow_cvlist_cyc=None, mcdpowstd_cvlist_cyc=None, mcd_cvlist_cyc=None, \
mcdstd_cvlist_cyc=None, cvlist_cyc_dv=None, mcdpow_cvlist_cyc_dv=None, mcdpowstd_cvlist_cyc_dv=None, \
mcd_cvlist_cyc_dv=None, mcdstd_cvlist_cyc_dv=None):
with torch.cuda.device(gpu):
# define model and load parameters
with torch.no_grad():
model_encoder = GRU_VAE_ENCODER(
in_dim=config.mcep_dim+config.excit_dim,
n_spk=n_spk,
lat_dim=config.lat_dim,
hidden_layers=config.hidden_layers_enc,
hidden_units=config.hidden_units_enc,
kernel_size=config.kernel_size_enc,
dilation_size=config.dilation_size_enc,
causal_conv=config.causal_conv_enc,
bi=False,
ar=False,
pad_first=True,
right_size=config.right_size_enc)
logging.info(model_encoder)
model_decoder = GRU_SPEC_DECODER(
feat_dim=config.lat_dim,
out_dim=config.mcep_dim,
n_spk=n_spk,
hidden_layers=config.hidden_layers_dec,
hidden_units=config.hidden_units_dec,
kernel_size=config.kernel_size_dec,
dilation_size=config.dilation_size_dec,
causal_conv=config.causal_conv_dec,
bi=False,
ar=False,
pad_first=True,
right_size=config.right_size_dec)
logging.info(model_decoder)
model_encoder.load_state_dict(torch.load(args.model)["model_encoder"])
model_decoder.load_state_dict(torch.load(args.model)["model_decoder"])
model_encoder.remove_weight_norm()
model_decoder.remove_weight_norm()
model_encoder.cuda()
model_decoder.cuda()
model_encoder.eval()
model_decoder.eval()
for param in model_encoder.parameters():
param.requires_grad = False
for param in model_decoder.parameters():
param.requires_grad = False
count = 0
pad_left = (model_encoder.pad_left + model_decoder.pad_left)*2
pad_right = (model_encoder.pad_right + model_decoder.pad_right)*2
outpad_lefts = [None]*3
outpad_rights = [None]*3
outpad_lefts[0] = pad_left-model_encoder.pad_left
outpad_rights[0] = pad_right-model_encoder.pad_right
outpad_lefts[1] = outpad_lefts[0]-model_decoder.pad_left
outpad_rights[1] = outpad_rights[0]-model_decoder.pad_right
outpad_lefts[2] = outpad_lefts[1]-model_encoder.pad_left
outpad_rights[2] = outpad_rights[1]-model_encoder.pad_right
for feat_file in feat_list:
# convert mcep
logging.info("recmcep " + feat_file)
feat_org = read_hdf5(feat_file, "/feat_mceplf0cap")
logging.info(feat_org.shape)
mcep = np.array(feat_org[:,-config.mcep_dim:])
with torch.no_grad():
feat = F.pad(torch.FloatTensor(feat_org).cuda().unsqueeze(0).transpose(1,2), (pad_left,pad_right), "replicate").transpose(1,2)
feat_excit = torch.FloatTensor(feat_org[:,:config.excit_dim]).cuda().unsqueeze(0)
spk_logits, _, lat_src, _ = model_encoder(feat, sampling=False)
logging.info('input spkpost')
if outpad_rights[0] > 0:
logging.info(torch.mean(F.softmax(spk_logits[:,outpad_lefts[0]:-outpad_rights[0]], dim=-1), 1))
else:
logging.info(torch.mean(F.softmax(spk_logits[:,outpad_lefts[0]:], dim=-1), 1))
cvmcep_src, _ = model_decoder((torch.ones((1, lat_src.shape[1]))*spk_idx).cuda().long(), lat_src)
spk_logits, _, lat_rec, _ = model_encoder(torch.cat((F.pad(feat_excit.transpose(1,2), \
(outpad_lefts[1],outpad_rights[1]), "replicate").transpose(1,2), cvmcep_src), 2),
sampling=False)
logging.info('rec spkpost')
if outpad_rights[2] > 0:
logging.info(torch.mean(F.softmax(spk_logits[:,outpad_lefts[2]:-outpad_rights[2]], dim=-1), 1))
else:
logging.info(torch.mean(F.softmax(spk_logits[:,outpad_lefts[2]:], dim=-1), 1))
cvmcep_cyc, _ = model_decoder((torch.ones((1, lat_rec.shape[1]))*spk_idx).cuda().long(), lat_rec)
if outpad_rights[1] > 0:
feat_rec = torch.cat((feat_excit, cvmcep_src[:,outpad_lefts[1]:-outpad_rights[1]]), 2)[0].cpu().data.numpy()
else:
feat_rec = torch.cat((feat_excit, cvmcep_src[:,outpad_lefts[1]:]), 2)[0].cpu().data.numpy()
feat_cyc = torch.cat((feat_excit, cvmcep_cyc), 2)[0].cpu().data.numpy()
cvmcep_src = np.array(cvmcep_src[0].cpu().data.numpy(), dtype=np.float64)
cvmcep_cyc = np.array(cvmcep_cyc[0].cpu().data.numpy(), dtype=np.float64)
logging.info(cvmcep_src.shape)
logging.info(cvmcep_cyc.shape)
spcidx = read_hdf5(feat_file, "/spcidx_range")[0]
_, _, _, mcdpow_arr = dtw.dtw_org_to_trg(np.array(cvmcep_src[np.array(spcidx),:], \
dtype=np.float64), np.array(mcep[np.array(spcidx),:], dtype=np.float64))
_, _, _, mcd_arr = dtw.dtw_org_to_trg(np.array(cvmcep_src[np.array(spcidx),1:], \
dtype=np.float64), np.array(mcep[np.array(spcidx),1:], dtype=np.float64))
mcdpow_mean = np.mean(mcdpow_arr)
mcdpow_std = np.std(mcdpow_arr)
mcd_mean = np.mean(mcd_arr)
mcd_std = np.std(mcd_arr)
logging.info("mcdpow_rec: %.6f dB +- %.6f" % (mcdpow_mean, mcdpow_std))
logging.info("mcd_rec: %.6f dB +- %.6f" % (mcd_mean, mcd_std))
_, _, _, mcdpow_arr = dtw.dtw_org_to_trg(np.array(cvmcep_cyc[np.array(spcidx),:], \
dtype=np.float64), np.array(mcep[np.array(spcidx),:], dtype=np.float64))
_, _, _, mcd_arr = dtw.dtw_org_to_trg(np.array(cvmcep_cyc[np.array(spcidx),1:], \
dtype=np.float64), np.array(mcep[np.array(spcidx),1:], dtype=np.float64))
mcdpow_mean_cyc = np.mean(mcdpow_arr)
mcdpow_std_cyc = np.std(mcdpow_arr)
mcd_mean_cyc = np.mean(mcd_arr)
mcd_std_cyc = np.std(mcd_arr)
logging.info("mcdpow_cyc: %.6f dB +- %.6f" % (mcdpow_mean_cyc, mcdpow_std_cyc))
logging.info("mcd_cyc: %.6f dB +- %.6f" % (mcd_mean_cyc, mcd_std_cyc))
dataset = feat_file.split('/')[1].split('_')[0]
if 'tr' in dataset:
logging.info('trn')
mcdpow_cvlist.append(mcdpow_mean)
mcdpowstd_cvlist.append(mcdpow_std)
mcd_cvlist.append(mcd_mean)
mcdstd_cvlist.append(mcd_std)
cvlist.append(np.var(cvmcep_src[:,1:], axis=0))
logging.info(len(cvlist))
mcdpow_cvlist_cyc.append(mcdpow_mean_cyc)
mcdpowstd_cvlist_cyc.append(mcdpow_std_cyc)
mcd_cvlist_cyc.append(mcd_mean_cyc)
mcdstd_cvlist_cyc.append(mcd_std_cyc)
cvlist_cyc.append(np.var(cvmcep_cyc[:,1:], axis=0))
elif 'dv' in dataset:
logging.info('dev')
mcdpow_cvlist_dv.append(mcdpow_mean)
mcdpowstd_cvlist_dv.append(mcdpow_std)
mcd_cvlist_dv.append(mcd_mean)
mcdstd_cvlist_dv.append(mcd_std)
cvlist_dv.append(np.var(cvmcep_src[:,1:], axis=0))
logging.info(len(cvlist_dv))
mcdpow_cvlist_cyc_dv.append(mcdpow_mean_cyc)
mcdpowstd_cvlist_cyc_dv.append(mcdpow_std_cyc)
mcd_cvlist_cyc_dv.append(mcd_mean_cyc)
mcdstd_cvlist_cyc_dv.append(mcd_std_cyc)
cvlist_cyc_dv.append(np.var(cvmcep_cyc[:,1:], axis=0))
logging.info('write rec to h5')
outh5dir = os.path.join(os.path.dirname(os.path.dirname(feat_file)), args.spk+"-"+args.spk)
if not os.path.exists(outh5dir):
os.makedirs(outh5dir)
feat_file = os.path.join(outh5dir, os.path.basename(feat_file))
logging.info(feat_file + ' ' + args.string_path)
logging.info(feat_rec.shape)
write_hdf5(feat_file, args.string_path, feat_rec)
logging.info('write cyc to h5')
outh5dir = os.path.join(os.path.dirname(os.path.dirname(feat_file)), args.spk+"-"+args.spk+"-"+args.spk)
if not os.path.exists(outh5dir):
os.makedirs(outh5dir)
feat_file = os.path.join(outh5dir, os.path.basename(feat_file))
logging.info(feat_file + ' ' + args.string_path)
logging.info(feat_cyc.shape)
write_hdf5(feat_file, args.string_path, feat_cyc)
count += 1
#if count >= 5:
#if count >= 3:
# break
# parallel decode training
with mp.Manager() as manager:
gpu = 0
processes = []
cvlist = manager.list()
mcd_cvlist = manager.list()
mcdstd_cvlist = manager.list()
mcdpow_cvlist = manager.list()
mcdpowstd_cvlist = manager.list()
cvlist_dv = manager.list()
mcd_cvlist_dv = manager.list()
mcdstd_cvlist_dv = manager.list()
mcdpow_cvlist_dv = manager.list()
mcdpowstd_cvlist_dv = manager.list()
cvlist_cyc = manager.list()
mcd_cvlist_cyc = manager.list()
mcdstd_cvlist_cyc = manager.list()
mcdpow_cvlist_cyc = manager.list()
mcdpowstd_cvlist_cyc = manager.list()
cvlist_cyc_dv = manager.list()
mcd_cvlist_cyc_dv = manager.list()
mcdstd_cvlist_cyc_dv = manager.list()
mcdpow_cvlist_cyc_dv = manager.list()
mcdpowstd_cvlist_cyc_dv = manager.list()
for i, feat_list in enumerate(feat_lists):
logging.info(i)
p = mp.Process(target=gpu_decode, args=(feat_list, gpu, cvlist, mcdpow_cvlist, mcdpowstd_cvlist, \
mcd_cvlist, mcdstd_cvlist, cvlist_dv, mcdpow_cvlist_dv, \
mcdpowstd_cvlist_dv, mcd_cvlist_dv, mcdstd_cvlist_dv,\
cvlist_cyc, mcdpow_cvlist_cyc, mcdpowstd_cvlist_cyc, \
mcd_cvlist_cyc, mcdstd_cvlist_cyc, cvlist_cyc_dv, mcdpow_cvlist_cyc_dv, \
mcdpowstd_cvlist_cyc_dv, mcd_cvlist_cyc_dv, mcdstd_cvlist_cyc_dv,))
p.start()
processes.append(p)
gpu += 1
if (i + 1) % args.n_gpus == 0:
gpu = 0
# wait for all process
for p in processes:
p.join()
# calculate cv_gv statistics
if len(mcdpow_cvlist) > 0:
logging.info("mcdpow_rec: %.6f dB (+- %.6f) +- %.6f (+- %.6f)" % (np.mean(np.array(mcdpow_cvlist)), \
np.std(np.array(mcdpow_cvlist)),np.mean(np.array(mcdpowstd_cvlist)),\
np.std(np.array(mcdpowstd_cvlist))))
logging.info("mcd_rec: %.6f dB (+- %.6f) +- %.6f (+- %.6f)" % (np.mean(np.array(mcd_cvlist)), \
np.std(np.array(mcd_cvlist)),np.mean(np.array(mcdstd_cvlist)),\
np.std(np.array(mcdstd_cvlist))))
cvgv_mean = np.mean(np.array(cvlist), axis=0)
cvgv_var = np.var(np.array(cvlist), axis=0)
logging.info("%lf +- %lf" % (np.mean(np.sqrt(np.square(np.log(cvgv_mean)-np.log(gv_mean)))), \
np.std(np.sqrt(np.square(np.log(cvgv_mean)-np.log(gv_mean))))))
logging.info("mcdpow_cyc: %.6f dB (+- %.6f) +- %.6f (+- %.6f)" % (np.mean(np.array(mcdpow_cvlist_cyc)), \
np.std(np.array(mcdpow_cvlist_cyc)),np.mean(np.array(mcdpowstd_cvlist_cyc)),\
np.std(np.array(mcdpowstd_cvlist_cyc))))
logging.info("mcd_cyc: %.6f dB (+- %.6f) +- %.6f (+- %.6f)" % (np.mean(np.array(mcd_cvlist_cyc)), \
np.std(np.array(mcd_cvlist_cyc)),np.mean(np.array(mcdstd_cvlist_cyc)),\
np.std(np.array(mcdstd_cvlist_cyc))))
cvgv_mean = np.mean(np.array(cvlist_cyc), axis=0)
cvgv_var = np.var(np.array(cvlist_cyc), axis=0)
logging.info("%lf +- %lf" % (np.mean(np.sqrt(np.square(np.log(cvgv_mean)-np.log(gv_mean)))), \
np.std(np.sqrt(np.square(np.log(cvgv_mean)-np.log(gv_mean))))))
cvgv_mean = np.mean(np.array(np.r_[cvlist,cvlist_cyc]), axis=0)
cvgv_var = np.var(np.array(np.r_[cvlist,cvlist_cyc]), axis=0)
logging.info("%lf +- %lf" % (np.mean(np.sqrt(np.square(np.log(cvgv_mean)-np.log(gv_mean)))), \
np.std(np.sqrt(np.square(np.log(cvgv_mean)-np.log(gv_mean))))))
string_path = model_name+"-"+str(config.n_half_cyc)+"-"+str(config.lat_dim)+"-"+model_epoch
logging.info(string_path)
string_mean = "/recgv_mean_"+string_path
string_var = "/recgv_var_"+string_path
write_hdf5(spk_stat, string_mean, cvgv_mean)
write_hdf5(spk_stat, string_var, cvgv_var)
if len(mcdpow_cvlist_dv) > 0:
logging.info("mcdpow_rec_dv: %.6f dB (+- %.6f) +- %.6f (+- %.6f)" % (np.mean(np.array(mcdpow_cvlist_dv)), \
np.std(np.array(mcdpow_cvlist_dv)),np.mean(np.array(mcdpowstd_cvlist_dv)),\
np.std(np.array(mcdpowstd_cvlist_dv))))
logging.info("mcd_rec_dv: %.6f dB (+- %.6f) +- %.6f (+- %.6f)" % (np.mean(np.array(mcd_cvlist_dv)), \
np.std(np.array(mcd_cvlist_dv)),np.mean(np.array(mcdstd_cvlist_dv)),\
np.std(np.array(mcdstd_cvlist_dv))))
cvgv_mean = np.mean(np.array(cvlist_dv), axis=0)
cvgv_var = np.var(np.array(cvlist_dv), axis=0)
logging.info("%lf +- %lf" % (np.mean(np.sqrt(np.square(np.log(cvgv_mean)-np.log(gv_mean)))), \
np.std(np.sqrt(np.square(np.log(cvgv_mean)-np.log(gv_mean))))))
logging.info("mcdpow_cyc_dv: %.6f dB (+- %.6f) +- %.6f (+- %.6f)" % (np.mean(np.array(mcdpow_cvlist_cyc_dv)), \
np.std(np.array(mcdpow_cvlist_cyc_dv)),np.mean(np.array(mcdpowstd_cvlist_cyc_dv)),\
np.std(np.array(mcdpowstd_cvlist_cyc_dv))))
logging.info("mcd_cyc_dv: %.6f dB (+- %.6f) +- %.6f (+- %.6f)" % (np.mean(np.array(mcd_cvlist_cyc_dv)), \
np.std(np.array(mcd_cvlist_cyc_dv)),np.mean(np.array(mcdstd_cvlist_cyc_dv)),\
np.std(np.array(mcdstd_cvlist_cyc_dv))))
cvgv_mean = np.mean(np.array(cvlist_cyc_dv), axis=0)
cvgv_var = np.var(np.array(cvlist_cyc_dv), axis=0)
logging.info("%lf +- %lf" % (np.mean(np.sqrt(np.square(np.log(cvgv_mean)-np.log(gv_mean)))), \
np.std(np.sqrt(np.square(np.log(cvgv_mean)-np.log(gv_mean))))))
if __name__ == "__main__":
main()
| 52.339901 | 146 | 0.559059 |
from __future__ import division
import argparse
import logging
import math
import os
import sys
import numpy as np
import torch
import torch.multiprocessing as mp
from vcneuvoco import GRU_VAE_ENCODER, GRU_SPEC_DECODER
from utils import find_files, read_hdf5, read_txt, write_hdf5, check_hdf5
from dtw_c import dtw_c as dtw
import torch.nn.functional as F
import h5py
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--feats", required=True,
type=str, help="list or directory of source eval feat files")
parser.add_argument("--spk", required=True,
type=str, help="speaker name to be reconstructed")
parser.add_argument("--model", required=True,
type=str, help="model file")
parser.add_argument("--config", required=True,
type=str, help="configure file")
parser.add_argument("--n_gpus", default=1,
type=int, help="number of gpus")
parser.add_argument("--outdir", required=True,
type=str, help="directory to save log")
parser.add_argument("--string_path", required=True,
type=str, help="path of h5 generated feature")
parser.add_argument("--GPU_device", default=None,
type=int, help="selection of GPU device")
parser.add_argument("--GPU_device_str", default=None,
type=str, help="selection of GPU device")
parser.add_argument("--verbose", default=1,
type=int, help="log level")
args = parser.parse_args()
if args.GPU_device is not None or args.GPU_device_str is not None:
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
if args.GPU_device_str is None:
os.environ["CUDA_VISIBLE_DEVICES"] = str(args.GPU_device)
else:
os.environ["CUDA_VISIBLE_DEVICES"] = args.GPU_device_str
if not os.path.exists(args.outdir):
os.makedirs(args.outdir)
if args.verbose > 0:
logging.basicConfig(level=logging.INFO,
format='%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s',
datefmt='%m/%d/%Y %I:%M:%S', filemode='w',
filename=args.outdir + "/decode.log")
logging.getLogger().addHandler(logging.StreamHandler())
elif args.verbose > 1:
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s',
datefmt='%m/%d/%Y %I:%M:%S', filemode='w',
filename=args.outdir + "/decode.log")
logging.getLogger().addHandler(logging.StreamHandler())
else:
logging.basicConfig(level=logging.WARN,
format='%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s',
datefmt='%m/%d/%Y %I:%M:%S', filemode='w',
filename=args.outdir + "/decode.log")
logging.getLogger().addHandler(logging.StreamHandler())
logging.warn("logging is disabled.")
config = torch.load(args.config)
if os.path.isdir(args.feats):
feat_list = sorted(find_files(args.feats, "*.h5"))
elif os.path.isfile(args.feats):
feat_list = read_txt(args.feats)
else:
logging.error("--feats should be directory or list.")
sys.exit(1)
feat_lists = np.array_split(feat_list, args.n_gpus)
feat_lists = [f_list.tolist() for f_list in feat_lists]
for i in range(args.n_gpus):
logging.info('%d: %d' % (i+1, len(feat_lists[i])))
spk_list = config.spk_list.split('@')
n_spk = len(spk_list)
spk_idx = spk_list.index(args.spk)
stats_list = config.stats_list.split('@')
assert(n_spk == len(stats_list))
spk_stat = stats_list[spk_idx]
gv_mean = read_hdf5(spk_stat, "/gv_range_mean")[1:]
model_epoch = os.path.basename(args.model).split('.')[0].split('-')[1]
logging.info('epoch: '+model_epoch)
model_name = os.path.basename(os.path.dirname(args.model)).split('_')[1]
logging.info('mdl_name: '+model_name)
logging.info(config)
def gpu_decode(feat_list, gpu, cvlist=None, mcdpow_cvlist=None, mcdpowstd_cvlist=None, mcd_cvlist=None, \
mcdstd_cvlist=None, cvlist_dv=None, mcdpow_cvlist_dv=None, mcdpowstd_cvlist_dv=None, \
mcd_cvlist_dv=None, mcdstd_cvlist_dv=None, \
cvlist_cyc=None, mcdpow_cvlist_cyc=None, mcdpowstd_cvlist_cyc=None, mcd_cvlist_cyc=None, \
mcdstd_cvlist_cyc=None, cvlist_cyc_dv=None, mcdpow_cvlist_cyc_dv=None, mcdpowstd_cvlist_cyc_dv=None, \
mcd_cvlist_cyc_dv=None, mcdstd_cvlist_cyc_dv=None):
with torch.cuda.device(gpu):
with torch.no_grad():
model_encoder = GRU_VAE_ENCODER(
in_dim=config.mcep_dim+config.excit_dim,
n_spk=n_spk,
lat_dim=config.lat_dim,
hidden_layers=config.hidden_layers_enc,
hidden_units=config.hidden_units_enc,
kernel_size=config.kernel_size_enc,
dilation_size=config.dilation_size_enc,
causal_conv=config.causal_conv_enc,
bi=False,
ar=False,
pad_first=True,
right_size=config.right_size_enc)
logging.info(model_encoder)
model_decoder = GRU_SPEC_DECODER(
feat_dim=config.lat_dim,
out_dim=config.mcep_dim,
n_spk=n_spk,
hidden_layers=config.hidden_layers_dec,
hidden_units=config.hidden_units_dec,
kernel_size=config.kernel_size_dec,
dilation_size=config.dilation_size_dec,
causal_conv=config.causal_conv_dec,
bi=False,
ar=False,
pad_first=True,
right_size=config.right_size_dec)
logging.info(model_decoder)
model_encoder.load_state_dict(torch.load(args.model)["model_encoder"])
model_decoder.load_state_dict(torch.load(args.model)["model_decoder"])
model_encoder.remove_weight_norm()
model_decoder.remove_weight_norm()
model_encoder.cuda()
model_decoder.cuda()
model_encoder.eval()
model_decoder.eval()
for param in model_encoder.parameters():
param.requires_grad = False
for param in model_decoder.parameters():
param.requires_grad = False
count = 0
pad_left = (model_encoder.pad_left + model_decoder.pad_left)*2
pad_right = (model_encoder.pad_right + model_decoder.pad_right)*2
outpad_lefts = [None]*3
outpad_rights = [None]*3
outpad_lefts[0] = pad_left-model_encoder.pad_left
outpad_rights[0] = pad_right-model_encoder.pad_right
outpad_lefts[1] = outpad_lefts[0]-model_decoder.pad_left
outpad_rights[1] = outpad_rights[0]-model_decoder.pad_right
outpad_lefts[2] = outpad_lefts[1]-model_encoder.pad_left
outpad_rights[2] = outpad_rights[1]-model_encoder.pad_right
for feat_file in feat_list:
logging.info("recmcep " + feat_file)
feat_org = read_hdf5(feat_file, "/feat_mceplf0cap")
logging.info(feat_org.shape)
mcep = np.array(feat_org[:,-config.mcep_dim:])
with torch.no_grad():
feat = F.pad(torch.FloatTensor(feat_org).cuda().unsqueeze(0).transpose(1,2), (pad_left,pad_right), "replicate").transpose(1,2)
feat_excit = torch.FloatTensor(feat_org[:,:config.excit_dim]).cuda().unsqueeze(0)
spk_logits, _, lat_src, _ = model_encoder(feat, sampling=False)
logging.info('input spkpost')
if outpad_rights[0] > 0:
logging.info(torch.mean(F.softmax(spk_logits[:,outpad_lefts[0]:-outpad_rights[0]], dim=-1), 1))
else:
logging.info(torch.mean(F.softmax(spk_logits[:,outpad_lefts[0]:], dim=-1), 1))
cvmcep_src, _ = model_decoder((torch.ones((1, lat_src.shape[1]))*spk_idx).cuda().long(), lat_src)
spk_logits, _, lat_rec, _ = model_encoder(torch.cat((F.pad(feat_excit.transpose(1,2), \
(outpad_lefts[1],outpad_rights[1]), "replicate").transpose(1,2), cvmcep_src), 2),
sampling=False)
logging.info('rec spkpost')
if outpad_rights[2] > 0:
logging.info(torch.mean(F.softmax(spk_logits[:,outpad_lefts[2]:-outpad_rights[2]], dim=-1), 1))
else:
logging.info(torch.mean(F.softmax(spk_logits[:,outpad_lefts[2]:], dim=-1), 1))
cvmcep_cyc, _ = model_decoder((torch.ones((1, lat_rec.shape[1]))*spk_idx).cuda().long(), lat_rec)
if outpad_rights[1] > 0:
feat_rec = torch.cat((feat_excit, cvmcep_src[:,outpad_lefts[1]:-outpad_rights[1]]), 2)[0].cpu().data.numpy()
else:
feat_rec = torch.cat((feat_excit, cvmcep_src[:,outpad_lefts[1]:]), 2)[0].cpu().data.numpy()
feat_cyc = torch.cat((feat_excit, cvmcep_cyc), 2)[0].cpu().data.numpy()
cvmcep_src = np.array(cvmcep_src[0].cpu().data.numpy(), dtype=np.float64)
cvmcep_cyc = np.array(cvmcep_cyc[0].cpu().data.numpy(), dtype=np.float64)
logging.info(cvmcep_src.shape)
logging.info(cvmcep_cyc.shape)
spcidx = read_hdf5(feat_file, "/spcidx_range")[0]
_, _, _, mcdpow_arr = dtw.dtw_org_to_trg(np.array(cvmcep_src[np.array(spcidx),:], \
dtype=np.float64), np.array(mcep[np.array(spcidx),:], dtype=np.float64))
_, _, _, mcd_arr = dtw.dtw_org_to_trg(np.array(cvmcep_src[np.array(spcidx),1:], \
dtype=np.float64), np.array(mcep[np.array(spcidx),1:], dtype=np.float64))
mcdpow_mean = np.mean(mcdpow_arr)
mcdpow_std = np.std(mcdpow_arr)
mcd_mean = np.mean(mcd_arr)
mcd_std = np.std(mcd_arr)
logging.info("mcdpow_rec: %.6f dB +- %.6f" % (mcdpow_mean, mcdpow_std))
logging.info("mcd_rec: %.6f dB +- %.6f" % (mcd_mean, mcd_std))
_, _, _, mcdpow_arr = dtw.dtw_org_to_trg(np.array(cvmcep_cyc[np.array(spcidx),:], \
dtype=np.float64), np.array(mcep[np.array(spcidx),:], dtype=np.float64))
_, _, _, mcd_arr = dtw.dtw_org_to_trg(np.array(cvmcep_cyc[np.array(spcidx),1:], \
dtype=np.float64), np.array(mcep[np.array(spcidx),1:], dtype=np.float64))
mcdpow_mean_cyc = np.mean(mcdpow_arr)
mcdpow_std_cyc = np.std(mcdpow_arr)
mcd_mean_cyc = np.mean(mcd_arr)
mcd_std_cyc = np.std(mcd_arr)
logging.info("mcdpow_cyc: %.6f dB +- %.6f" % (mcdpow_mean_cyc, mcdpow_std_cyc))
logging.info("mcd_cyc: %.6f dB +- %.6f" % (mcd_mean_cyc, mcd_std_cyc))
dataset = feat_file.split('/')[1].split('_')[0]
if 'tr' in dataset:
logging.info('trn')
mcdpow_cvlist.append(mcdpow_mean)
mcdpowstd_cvlist.append(mcdpow_std)
mcd_cvlist.append(mcd_mean)
mcdstd_cvlist.append(mcd_std)
cvlist.append(np.var(cvmcep_src[:,1:], axis=0))
logging.info(len(cvlist))
mcdpow_cvlist_cyc.append(mcdpow_mean_cyc)
mcdpowstd_cvlist_cyc.append(mcdpow_std_cyc)
mcd_cvlist_cyc.append(mcd_mean_cyc)
mcdstd_cvlist_cyc.append(mcd_std_cyc)
cvlist_cyc.append(np.var(cvmcep_cyc[:,1:], axis=0))
elif 'dv' in dataset:
logging.info('dev')
mcdpow_cvlist_dv.append(mcdpow_mean)
mcdpowstd_cvlist_dv.append(mcdpow_std)
mcd_cvlist_dv.append(mcd_mean)
mcdstd_cvlist_dv.append(mcd_std)
cvlist_dv.append(np.var(cvmcep_src[:,1:], axis=0))
logging.info(len(cvlist_dv))
mcdpow_cvlist_cyc_dv.append(mcdpow_mean_cyc)
mcdpowstd_cvlist_cyc_dv.append(mcdpow_std_cyc)
mcd_cvlist_cyc_dv.append(mcd_mean_cyc)
mcdstd_cvlist_cyc_dv.append(mcd_std_cyc)
cvlist_cyc_dv.append(np.var(cvmcep_cyc[:,1:], axis=0))
logging.info('write rec to h5')
outh5dir = os.path.join(os.path.dirname(os.path.dirname(feat_file)), args.spk+"-"+args.spk)
if not os.path.exists(outh5dir):
os.makedirs(outh5dir)
feat_file = os.path.join(outh5dir, os.path.basename(feat_file))
logging.info(feat_file + ' ' + args.string_path)
logging.info(feat_rec.shape)
write_hdf5(feat_file, args.string_path, feat_rec)
logging.info('write cyc to h5')
outh5dir = os.path.join(os.path.dirname(os.path.dirname(feat_file)), args.spk+"-"+args.spk+"-"+args.spk)
if not os.path.exists(outh5dir):
os.makedirs(outh5dir)
feat_file = os.path.join(outh5dir, os.path.basename(feat_file))
logging.info(feat_file + ' ' + args.string_path)
logging.info(feat_cyc.shape)
write_hdf5(feat_file, args.string_path, feat_cyc)
count += 1
with mp.Manager() as manager:
gpu = 0
processes = []
cvlist = manager.list()
mcd_cvlist = manager.list()
mcdstd_cvlist = manager.list()
mcdpow_cvlist = manager.list()
mcdpowstd_cvlist = manager.list()
cvlist_dv = manager.list()
mcd_cvlist_dv = manager.list()
mcdstd_cvlist_dv = manager.list()
mcdpow_cvlist_dv = manager.list()
mcdpowstd_cvlist_dv = manager.list()
cvlist_cyc = manager.list()
mcd_cvlist_cyc = manager.list()
mcdstd_cvlist_cyc = manager.list()
mcdpow_cvlist_cyc = manager.list()
mcdpowstd_cvlist_cyc = manager.list()
cvlist_cyc_dv = manager.list()
mcd_cvlist_cyc_dv = manager.list()
mcdstd_cvlist_cyc_dv = manager.list()
mcdpow_cvlist_cyc_dv = manager.list()
mcdpowstd_cvlist_cyc_dv = manager.list()
for i, feat_list in enumerate(feat_lists):
logging.info(i)
p = mp.Process(target=gpu_decode, args=(feat_list, gpu, cvlist, mcdpow_cvlist, mcdpowstd_cvlist, \
mcd_cvlist, mcdstd_cvlist, cvlist_dv, mcdpow_cvlist_dv, \
mcdpowstd_cvlist_dv, mcd_cvlist_dv, mcdstd_cvlist_dv,\
cvlist_cyc, mcdpow_cvlist_cyc, mcdpowstd_cvlist_cyc, \
mcd_cvlist_cyc, mcdstd_cvlist_cyc, cvlist_cyc_dv, mcdpow_cvlist_cyc_dv, \
mcdpowstd_cvlist_cyc_dv, mcd_cvlist_cyc_dv, mcdstd_cvlist_cyc_dv,))
p.start()
processes.append(p)
gpu += 1
if (i + 1) % args.n_gpus == 0:
gpu = 0
for p in processes:
p.join()
if len(mcdpow_cvlist) > 0:
logging.info("mcdpow_rec: %.6f dB (+- %.6f) +- %.6f (+- %.6f)" % (np.mean(np.array(mcdpow_cvlist)), \
np.std(np.array(mcdpow_cvlist)),np.mean(np.array(mcdpowstd_cvlist)),\
np.std(np.array(mcdpowstd_cvlist))))
logging.info("mcd_rec: %.6f dB (+- %.6f) +- %.6f (+- %.6f)" % (np.mean(np.array(mcd_cvlist)), \
np.std(np.array(mcd_cvlist)),np.mean(np.array(mcdstd_cvlist)),\
np.std(np.array(mcdstd_cvlist))))
cvgv_mean = np.mean(np.array(cvlist), axis=0)
cvgv_var = np.var(np.array(cvlist), axis=0)
logging.info("%lf +- %lf" % (np.mean(np.sqrt(np.square(np.log(cvgv_mean)-np.log(gv_mean)))), \
np.std(np.sqrt(np.square(np.log(cvgv_mean)-np.log(gv_mean))))))
logging.info("mcdpow_cyc: %.6f dB (+- %.6f) +- %.6f (+- %.6f)" % (np.mean(np.array(mcdpow_cvlist_cyc)), \
np.std(np.array(mcdpow_cvlist_cyc)),np.mean(np.array(mcdpowstd_cvlist_cyc)),\
np.std(np.array(mcdpowstd_cvlist_cyc))))
logging.info("mcd_cyc: %.6f dB (+- %.6f) +- %.6f (+- %.6f)" % (np.mean(np.array(mcd_cvlist_cyc)), \
np.std(np.array(mcd_cvlist_cyc)),np.mean(np.array(mcdstd_cvlist_cyc)),\
np.std(np.array(mcdstd_cvlist_cyc))))
cvgv_mean = np.mean(np.array(cvlist_cyc), axis=0)
cvgv_var = np.var(np.array(cvlist_cyc), axis=0)
logging.info("%lf +- %lf" % (np.mean(np.sqrt(np.square(np.log(cvgv_mean)-np.log(gv_mean)))), \
np.std(np.sqrt(np.square(np.log(cvgv_mean)-np.log(gv_mean))))))
cvgv_mean = np.mean(np.array(np.r_[cvlist,cvlist_cyc]), axis=0)
cvgv_var = np.var(np.array(np.r_[cvlist,cvlist_cyc]), axis=0)
logging.info("%lf +- %lf" % (np.mean(np.sqrt(np.square(np.log(cvgv_mean)-np.log(gv_mean)))), \
np.std(np.sqrt(np.square(np.log(cvgv_mean)-np.log(gv_mean))))))
string_path = model_name+"-"+str(config.n_half_cyc)+"-"+str(config.lat_dim)+"-"+model_epoch
logging.info(string_path)
string_mean = "/recgv_mean_"+string_path
string_var = "/recgv_var_"+string_path
write_hdf5(spk_stat, string_mean, cvgv_mean)
write_hdf5(spk_stat, string_var, cvgv_var)
if len(mcdpow_cvlist_dv) > 0:
logging.info("mcdpow_rec_dv: %.6f dB (+- %.6f) +- %.6f (+- %.6f)" % (np.mean(np.array(mcdpow_cvlist_dv)), \
np.std(np.array(mcdpow_cvlist_dv)),np.mean(np.array(mcdpowstd_cvlist_dv)),\
np.std(np.array(mcdpowstd_cvlist_dv))))
logging.info("mcd_rec_dv: %.6f dB (+- %.6f) +- %.6f (+- %.6f)" % (np.mean(np.array(mcd_cvlist_dv)), \
np.std(np.array(mcd_cvlist_dv)),np.mean(np.array(mcdstd_cvlist_dv)),\
np.std(np.array(mcdstd_cvlist_dv))))
cvgv_mean = np.mean(np.array(cvlist_dv), axis=0)
cvgv_var = np.var(np.array(cvlist_dv), axis=0)
logging.info("%lf +- %lf" % (np.mean(np.sqrt(np.square(np.log(cvgv_mean)-np.log(gv_mean)))), \
np.std(np.sqrt(np.square(np.log(cvgv_mean)-np.log(gv_mean))))))
logging.info("mcdpow_cyc_dv: %.6f dB (+- %.6f) +- %.6f (+- %.6f)" % (np.mean(np.array(mcdpow_cvlist_cyc_dv)), \
np.std(np.array(mcdpow_cvlist_cyc_dv)),np.mean(np.array(mcdpowstd_cvlist_cyc_dv)),\
np.std(np.array(mcdpowstd_cvlist_cyc_dv))))
logging.info("mcd_cyc_dv: %.6f dB (+- %.6f) +- %.6f (+- %.6f)" % (np.mean(np.array(mcd_cvlist_cyc_dv)), \
np.std(np.array(mcd_cvlist_cyc_dv)),np.mean(np.array(mcdstd_cvlist_cyc_dv)),\
np.std(np.array(mcdstd_cvlist_cyc_dv))))
cvgv_mean = np.mean(np.array(cvlist_cyc_dv), axis=0)
cvgv_var = np.var(np.array(cvlist_cyc_dv), axis=0)
logging.info("%lf +- %lf" % (np.mean(np.sqrt(np.square(np.log(cvgv_mean)-np.log(gv_mean)))), \
np.std(np.sqrt(np.square(np.log(cvgv_mean)-np.log(gv_mean))))))
if __name__ == "__main__":
main()
| true | true |
f7f92b3d5ade59f2c089c5df9977c0f9a575a74e | 13,383 | py | Python | athena/models/speech_transformer.py | hyx100e/athena-1 | 2668de7acdd51a6d12a2768a57351b666b4edbf3 | [
"Apache-2.0"
] | 1 | 2019-12-25T06:38:03.000Z | 2019-12-25T06:38:03.000Z | athena/models/speech_transformer.py | cookingbear/athena | 2ff02d5f54070563c6a600199ae9e8d3ca3c66dd | [
"Apache-2.0"
] | null | null | null | athena/models/speech_transformer.py | cookingbear/athena | 2ff02d5f54070563c6a600199ae9e8d3ca3c66dd | [
"Apache-2.0"
] | null | null | null | # coding=utf-8
# Copyright (C) 2019 ATHENA AUTHORS; Xiangang Li; Dongwei Jiang; Xiaoning Lei
# 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.
# ==============================================================================
# Only support eager mode
# pylint: disable=no-member, invalid-name, relative-beyond-top-level
# pylint: disable=too-many-locals, too-many-statements, too-many-arguments, too-many-instance-attributes
""" speech transformer implementation"""
from absl import logging
import tensorflow as tf
from .base import BaseModel
from ..loss import Seq2SeqSparseCategoricalCrossentropy
from ..metrics import Seq2SeqSparseCategoricalAccuracy
from ..utils.misc import generate_square_subsequent_mask, insert_sos_in_labels
from ..layers.commons import PositionalEncoding
from ..layers.transformer import Transformer
from ..utils.hparam import register_and_parse_hparams
from ..tools.beam_search import BeamSearchDecoder
from ..tools.lm_scorer import NGramScorer, RNNScorer
class SpeechTransformer(BaseModel):
""" Standard implementation of a SpeechTransformer. Model mainly consists of three parts:
the x_net for input preparation, the y_net for output preparation and the transformer itself
"""
default_config = {
"return_encoder_output": False,
"num_filters": 512,
"d_model": 512,
"num_heads": 8,
"num_encoder_layers": 12,
"num_decoder_layers": 6,
"dff": 1280,
"rate": 0.1,
"schedual_sampling_rate": 0.9,
"label_smoothing_rate": 0.0
}
def __init__(self, data_descriptions, config=None):
super().__init__()
self.hparams = register_and_parse_hparams(self.default_config, config, cls=self.__class__)
self.num_class = data_descriptions.num_class + 1
self.sos = self.num_class - 1
self.eos = self.num_class - 1
ls_rate = self.hparams.label_smoothing_rate
self.loss_function = Seq2SeqSparseCategoricalCrossentropy(
num_classes=self.num_class, eos=self.eos, label_smoothing=ls_rate
)
self.metric = Seq2SeqSparseCategoricalAccuracy(eos=self.eos, name="Accuracy")
# for the x_net
num_filters = self.hparams.num_filters
d_model = self.hparams.d_model
layers = tf.keras.layers
input_features = layers.Input(shape=data_descriptions.sample_shape["input"], dtype=tf.float32)
inner = layers.Conv2D(
filters=num_filters,
kernel_size=(3, 3),
strides=(2, 2),
padding="same",
use_bias=False,
data_format="channels_last",
)(input_features)
inner = layers.BatchNormalization()(inner)
inner = tf.nn.relu6(inner)
inner = layers.Conv2D(
filters=num_filters,
kernel_size=(3, 3),
strides=(2, 2),
padding="same",
use_bias=False,
data_format="channels_last",
)(inner)
inner = layers.BatchNormalization()(inner)
inner = tf.nn.relu6(inner)
_, _, dim, channels = inner.get_shape().as_list()
output_dim = dim * channels
inner = layers.Reshape((-1, output_dim))(inner)
inner = layers.Dense(d_model, activation=tf.nn.relu6)(inner)
inner = PositionalEncoding(d_model, scale=False)(inner)
inner = layers.Dropout(self.hparams.rate)(inner) # self.hparams.rate
self.x_net = tf.keras.Model(inputs=input_features, outputs=inner, name="x_net")
print(self.x_net.summary())
# y_net for target
input_labels = layers.Input(shape=data_descriptions.sample_shape["output"], dtype=tf.int32)
inner = layers.Embedding(self.num_class, d_model)(input_labels)
inner = PositionalEncoding(d_model, scale=True)(inner)
inner = layers.Dropout(self.hparams.rate)(inner)
self.y_net = tf.keras.Model(inputs=input_labels, outputs=inner, name="y_net")
print(self.y_net.summary())
# transformer layer
self.transformer = Transformer(
self.hparams.d_model,
self.hparams.num_heads,
self.hparams.num_encoder_layers,
self.hparams.num_decoder_layers,
self.hparams.dff,
self.hparams.rate,
)
# last layer for output
self.final_layer = layers.Dense(self.num_class, input_shape=(d_model,))
# some temp function
self.random_num = tf.random_uniform_initializer(0, 1)
def call(self, samples, training: bool = None):
x0 = samples["input"]
y0 = insert_sos_in_labels(samples["output"], self.sos)
x = self.x_net(x0, training=training)
y = self.y_net(y0, training=training)
input_length = self.compute_logit_length(samples)
input_mask, output_mask = self._create_masks(x, input_length, y0)
y, encoder_output = self.transformer(
x,
y,
input_mask,
output_mask,
input_mask,
training=training,
return_encoder_output=True,
)
y = self.final_layer(y)
if self.hparams.return_encoder_output:
return y, encoder_output
return y
@staticmethod
def _create_masks(x, input_length, y):
r""" Generate a square mask for the sequence. The masked positions are
filled with float(1.0). Unmasked positions are filled with float(0.0).
"""
input_mask, output_mask = None, None
if x is not None:
input_mask = 1.0 - tf.sequence_mask(
input_length, tf.shape(x)[1], dtype=tf.float32
)
input_mask = input_mask[:, tf.newaxis, tf.newaxis, :]
input_mask.set_shape([None, None, None, None])
if y is not None:
output_mask = tf.cast(tf.math.equal(y, 0), tf.float32)
output_mask = output_mask[:, tf.newaxis, tf.newaxis, :]
look_ahead_mask = generate_square_subsequent_mask(tf.shape(y)[1])
output_mask = tf.maximum(output_mask, look_ahead_mask)
output_mask.set_shape([None, None, None, None])
return input_mask, output_mask
def compute_logit_length(self, samples):
""" used for get logit length """
input_length = tf.cast(samples["input_length"], tf.float32)
logit_length = tf.math.ceil(input_length / 2)
logit_length = tf.math.ceil(logit_length / 2)
logit_length = tf.cast(logit_length, tf.int32)
return logit_length
def time_propagate(self, history_logits, history_predictions, step, enc_outputs):
""" TODO: doctring
last_predictions: the predictions of last time_step, [beam_size]
history_predictions: the predictions of history from 0 to time_step,
[beam_size, time_steps]
states: (step)
"""
# merge
(encoder_output, memory_mask) = enc_outputs
step = step + 1
output_mask = generate_square_subsequent_mask(step)
# propagate 1 step
logits = self.y_net(tf.transpose(history_predictions.stack()), training=False)
logits = self.transformer.decoder(
logits,
encoder_output,
tgt_mask=output_mask,
memory_mask=memory_mask,
training=False,
)
logits = self.final_layer(logits)
logits = logits[:, -1, :]
history_logits = history_logits.write(step - 1, logits)
return logits, history_logits, step
def decode(self, samples, hparams, lm_model=None, return_encoder=False):
""" beam search decoding """
x0 = samples["input"]
batch = tf.shape(x0)[0]
x = self.x_net(x0, training=False)
input_length = self.compute_logit_length(samples)
input_mask, _ = self._create_masks(x, input_length, None)
encoder_output = self.transformer.encoder(x, input_mask, training=False)
if return_encoder:
return encoder_output, input_mask
# init op
last_predictions = tf.ones([batch], dtype=tf.int32) * self.sos
history_predictions = tf.TensorArray(
tf.int32, size=1, dynamic_size=True, clear_after_read=False
)
step = 0
history_predictions.write(0, last_predictions)
history_predictions = history_predictions.stack()
init_cand_states = [history_predictions]
beam_size = 1 if not hparams.beam_search else hparams.beam_size
beam_search_decoder = BeamSearchDecoder(
self.num_class, self.sos, self.eos, beam_size=beam_size
)
beam_search_decoder.build(self.time_propagate)
if hparams.lm_weight != 0:
if hparams.lm_path is None:
raise ValueError("lm path should not be none")
if hparams.lm_type == "ngram":
lm_scorer = NGramScorer(
hparams.lm_path,
self.sos,
self.eos,
self.num_class,
lm_weight=hparams.lm_weight,
)
elif hparams.lm_type == "rnn":
lm_scorer = RNNScorer(
lm_model,
lm_weight=hparams.lm_weight)
beam_search_decoder.add_scorer(lm_scorer)
predictions = beam_search_decoder(
history_predictions, init_cand_states, step, (encoder_output, input_mask)
)
return predictions
def restore_from_pretrained_model(self, pretrained_model, model_type=""):
if model_type == "":
return
if model_type == "mpc":
logging.info("loading from pretrained mpc model")
self.x_net = pretrained_model.x_net
self.transformer.encoder = pretrained_model.encoder
elif model_type == "SpeechTransformer":
logging.info("loading from pretrained SpeechTransformer model")
self.x_net = pretrained_model.x_net
self.y_net = pretrained_model.y_net
self.transformer = pretrained_model.transformer
self.final_layer = pretrained_model.final_layer
else:
raise ValueError("NOT SUPPORTED")
class SpeechTransformer2(SpeechTransformer):
""" Decoder for SpeechTransformer2 works for two pass schedual sampling"""
def call(self, samples, training: bool = None):
x0 = samples["input"]
y0 = insert_sos_in_labels(samples["output"], self.sos)
x = self.x_net(x0, training=training)
y = self.y_net(y0, training=training)
input_length = self.compute_logit_length(samples)
input_mask, output_mask = self._create_masks(x, input_length, y0)
# first pass
y, encoder_output = self.transformer(
x,
y,
input_mask,
output_mask,
input_mask,
training=training,
return_encoder_output=True,
)
y_pre = self.final_layer(y)
# second pass
y = self.mix_target_sequence(y0, y_pre, training)
y, encoder_output = self.transformer(
x,
y,
input_mask,
output_mask,
input_mask,
training=training,
return_encoder_output=True,
)
y = self.final_layer(y)
if self.hparams.return_encoder_output:
return y, encoder_output
return y
def mix_target_sequence(self, gold_token, predicted_token, training, top_k=5):
""" to mix gold token and prediction
param gold_token: true labels
param predicted_token: predictions by first pass
return: mix of the gold_token and predicted_token
"""
mix_result = tf.TensorArray(
tf.float32, size=1, dynamic_size=True, clear_after_read=False
)
for i in tf.range(tf.shape(gold_token)[-1]):
if self.random_num([1]) > self.hparams.schedual_sampling_rate:# do schedual sampling
selected_input = predicted_token[:, i, :]
selected_idx = tf.nn.top_k(selected_input, top_k).indices
embedding_input = self.y_net.layers[1](selected_idx, training=training)
embedding_input = tf.reduce_mean(embedding_input, axis=1)
mix_result = mix_result.write(i, embedding_input)
else:
selected_input = tf.reshape(gold_token[:, i], [-1, 1])
embedding_input = self.y_net.layers[1](selected_input, training=training)
mix_result = mix_result.write(i, embedding_input[:, 0, :])
final_input = self.y_net.layers[2](tf.transpose(mix_result.stack(), [1, 0, 2]),
training=training)
final_input = self.y_net.layers[3](final_input, training=training)
return final_input
| 41.305556 | 104 | 0.62826 |
from absl import logging
import tensorflow as tf
from .base import BaseModel
from ..loss import Seq2SeqSparseCategoricalCrossentropy
from ..metrics import Seq2SeqSparseCategoricalAccuracy
from ..utils.misc import generate_square_subsequent_mask, insert_sos_in_labels
from ..layers.commons import PositionalEncoding
from ..layers.transformer import Transformer
from ..utils.hparam import register_and_parse_hparams
from ..tools.beam_search import BeamSearchDecoder
from ..tools.lm_scorer import NGramScorer, RNNScorer
class SpeechTransformer(BaseModel):
default_config = {
"return_encoder_output": False,
"num_filters": 512,
"d_model": 512,
"num_heads": 8,
"num_encoder_layers": 12,
"num_decoder_layers": 6,
"dff": 1280,
"rate": 0.1,
"schedual_sampling_rate": 0.9,
"label_smoothing_rate": 0.0
}
def __init__(self, data_descriptions, config=None):
super().__init__()
self.hparams = register_and_parse_hparams(self.default_config, config, cls=self.__class__)
self.num_class = data_descriptions.num_class + 1
self.sos = self.num_class - 1
self.eos = self.num_class - 1
ls_rate = self.hparams.label_smoothing_rate
self.loss_function = Seq2SeqSparseCategoricalCrossentropy(
num_classes=self.num_class, eos=self.eos, label_smoothing=ls_rate
)
self.metric = Seq2SeqSparseCategoricalAccuracy(eos=self.eos, name="Accuracy")
num_filters = self.hparams.num_filters
d_model = self.hparams.d_model
layers = tf.keras.layers
input_features = layers.Input(shape=data_descriptions.sample_shape["input"], dtype=tf.float32)
inner = layers.Conv2D(
filters=num_filters,
kernel_size=(3, 3),
strides=(2, 2),
padding="same",
use_bias=False,
data_format="channels_last",
)(input_features)
inner = layers.BatchNormalization()(inner)
inner = tf.nn.relu6(inner)
inner = layers.Conv2D(
filters=num_filters,
kernel_size=(3, 3),
strides=(2, 2),
padding="same",
use_bias=False,
data_format="channels_last",
)(inner)
inner = layers.BatchNormalization()(inner)
inner = tf.nn.relu6(inner)
_, _, dim, channels = inner.get_shape().as_list()
output_dim = dim * channels
inner = layers.Reshape((-1, output_dim))(inner)
inner = layers.Dense(d_model, activation=tf.nn.relu6)(inner)
inner = PositionalEncoding(d_model, scale=False)(inner)
inner = layers.Dropout(self.hparams.rate)(inner)
self.x_net = tf.keras.Model(inputs=input_features, outputs=inner, name="x_net")
print(self.x_net.summary())
input_labels = layers.Input(shape=data_descriptions.sample_shape["output"], dtype=tf.int32)
inner = layers.Embedding(self.num_class, d_model)(input_labels)
inner = PositionalEncoding(d_model, scale=True)(inner)
inner = layers.Dropout(self.hparams.rate)(inner)
self.y_net = tf.keras.Model(inputs=input_labels, outputs=inner, name="y_net")
print(self.y_net.summary())
self.transformer = Transformer(
self.hparams.d_model,
self.hparams.num_heads,
self.hparams.num_encoder_layers,
self.hparams.num_decoder_layers,
self.hparams.dff,
self.hparams.rate,
)
self.final_layer = layers.Dense(self.num_class, input_shape=(d_model,))
self.random_num = tf.random_uniform_initializer(0, 1)
def call(self, samples, training: bool = None):
x0 = samples["input"]
y0 = insert_sos_in_labels(samples["output"], self.sos)
x = self.x_net(x0, training=training)
y = self.y_net(y0, training=training)
input_length = self.compute_logit_length(samples)
input_mask, output_mask = self._create_masks(x, input_length, y0)
y, encoder_output = self.transformer(
x,
y,
input_mask,
output_mask,
input_mask,
training=training,
return_encoder_output=True,
)
y = self.final_layer(y)
if self.hparams.return_encoder_output:
return y, encoder_output
return y
@staticmethod
def _create_masks(x, input_length, y):
input_mask, output_mask = None, None
if x is not None:
input_mask = 1.0 - tf.sequence_mask(
input_length, tf.shape(x)[1], dtype=tf.float32
)
input_mask = input_mask[:, tf.newaxis, tf.newaxis, :]
input_mask.set_shape([None, None, None, None])
if y is not None:
output_mask = tf.cast(tf.math.equal(y, 0), tf.float32)
output_mask = output_mask[:, tf.newaxis, tf.newaxis, :]
look_ahead_mask = generate_square_subsequent_mask(tf.shape(y)[1])
output_mask = tf.maximum(output_mask, look_ahead_mask)
output_mask.set_shape([None, None, None, None])
return input_mask, output_mask
def compute_logit_length(self, samples):
input_length = tf.cast(samples["input_length"], tf.float32)
logit_length = tf.math.ceil(input_length / 2)
logit_length = tf.math.ceil(logit_length / 2)
logit_length = tf.cast(logit_length, tf.int32)
return logit_length
def time_propagate(self, history_logits, history_predictions, step, enc_outputs):
(encoder_output, memory_mask) = enc_outputs
step = step + 1
output_mask = generate_square_subsequent_mask(step)
logits = self.y_net(tf.transpose(history_predictions.stack()), training=False)
logits = self.transformer.decoder(
logits,
encoder_output,
tgt_mask=output_mask,
memory_mask=memory_mask,
training=False,
)
logits = self.final_layer(logits)
logits = logits[:, -1, :]
history_logits = history_logits.write(step - 1, logits)
return logits, history_logits, step
def decode(self, samples, hparams, lm_model=None, return_encoder=False):
x0 = samples["input"]
batch = tf.shape(x0)[0]
x = self.x_net(x0, training=False)
input_length = self.compute_logit_length(samples)
input_mask, _ = self._create_masks(x, input_length, None)
encoder_output = self.transformer.encoder(x, input_mask, training=False)
if return_encoder:
return encoder_output, input_mask
last_predictions = tf.ones([batch], dtype=tf.int32) * self.sos
history_predictions = tf.TensorArray(
tf.int32, size=1, dynamic_size=True, clear_after_read=False
)
step = 0
history_predictions.write(0, last_predictions)
history_predictions = history_predictions.stack()
init_cand_states = [history_predictions]
beam_size = 1 if not hparams.beam_search else hparams.beam_size
beam_search_decoder = BeamSearchDecoder(
self.num_class, self.sos, self.eos, beam_size=beam_size
)
beam_search_decoder.build(self.time_propagate)
if hparams.lm_weight != 0:
if hparams.lm_path is None:
raise ValueError("lm path should not be none")
if hparams.lm_type == "ngram":
lm_scorer = NGramScorer(
hparams.lm_path,
self.sos,
self.eos,
self.num_class,
lm_weight=hparams.lm_weight,
)
elif hparams.lm_type == "rnn":
lm_scorer = RNNScorer(
lm_model,
lm_weight=hparams.lm_weight)
beam_search_decoder.add_scorer(lm_scorer)
predictions = beam_search_decoder(
history_predictions, init_cand_states, step, (encoder_output, input_mask)
)
return predictions
def restore_from_pretrained_model(self, pretrained_model, model_type=""):
if model_type == "":
return
if model_type == "mpc":
logging.info("loading from pretrained mpc model")
self.x_net = pretrained_model.x_net
self.transformer.encoder = pretrained_model.encoder
elif model_type == "SpeechTransformer":
logging.info("loading from pretrained SpeechTransformer model")
self.x_net = pretrained_model.x_net
self.y_net = pretrained_model.y_net
self.transformer = pretrained_model.transformer
self.final_layer = pretrained_model.final_layer
else:
raise ValueError("NOT SUPPORTED")
class SpeechTransformer2(SpeechTransformer):
def call(self, samples, training: bool = None):
x0 = samples["input"]
y0 = insert_sos_in_labels(samples["output"], self.sos)
x = self.x_net(x0, training=training)
y = self.y_net(y0, training=training)
input_length = self.compute_logit_length(samples)
input_mask, output_mask = self._create_masks(x, input_length, y0)
y, encoder_output = self.transformer(
x,
y,
input_mask,
output_mask,
input_mask,
training=training,
return_encoder_output=True,
)
y_pre = self.final_layer(y)
y = self.mix_target_sequence(y0, y_pre, training)
y, encoder_output = self.transformer(
x,
y,
input_mask,
output_mask,
input_mask,
training=training,
return_encoder_output=True,
)
y = self.final_layer(y)
if self.hparams.return_encoder_output:
return y, encoder_output
return y
def mix_target_sequence(self, gold_token, predicted_token, training, top_k=5):
mix_result = tf.TensorArray(
tf.float32, size=1, dynamic_size=True, clear_after_read=False
)
for i in tf.range(tf.shape(gold_token)[-1]):
if self.random_num([1]) > self.hparams.schedual_sampling_rate:
selected_input = predicted_token[:, i, :]
selected_idx = tf.nn.top_k(selected_input, top_k).indices
embedding_input = self.y_net.layers[1](selected_idx, training=training)
embedding_input = tf.reduce_mean(embedding_input, axis=1)
mix_result = mix_result.write(i, embedding_input)
else:
selected_input = tf.reshape(gold_token[:, i], [-1, 1])
embedding_input = self.y_net.layers[1](selected_input, training=training)
mix_result = mix_result.write(i, embedding_input[:, 0, :])
final_input = self.y_net.layers[2](tf.transpose(mix_result.stack(), [1, 0, 2]),
training=training)
final_input = self.y_net.layers[3](final_input, training=training)
return final_input
| true | true |
f7f92b8f50b0af5bf26719bffb221c20f87f5a30 | 510 | py | Python | IRIS_data_download/IRIS_download_support/obspy/io/scardec/tests/__init__.py | earthinversion/Fnet_IRIS_data_automated_download | 09a6e0c992662feac95744935e038d1c68539fa1 | [
"MIT"
] | 2 | 2020-03-05T01:03:01.000Z | 2020-12-17T05:04:07.000Z | IRIS_data_download/IRIS_download_support/obspy/io/scardec/tests/__init__.py | earthinversion/Fnet_IRIS_data_automated_download | 09a6e0c992662feac95744935e038d1c68539fa1 | [
"MIT"
] | 4 | 2021-03-31T19:25:55.000Z | 2021-12-13T20:32:46.000Z | IRIS_data_download/IRIS_download_support/obspy/io/scardec/tests/__init__.py | earthinversion/Fnet_IRIS_data_automated_download | 09a6e0c992662feac95744935e038d1c68539fa1 | [
"MIT"
] | 2 | 2020-09-08T19:33:40.000Z | 2021-04-05T09:47:50.000Z | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from future.builtins import * # NOQA
import unittest
from obspy.core.util import add_doctests, add_unittests
MODULE_NAME = "obspy.io.scardec"
def suite():
suite = unittest.TestSuite()
add_doctests(suite, MODULE_NAME)
add_unittests(suite, MODULE_NAME)
return suite
if __name__ == '__main__':
unittest.main(defaultTest='suite')
| 21.25 | 66 | 0.7 |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from future.builtins import *
import unittest
from obspy.core.util import add_doctests, add_unittests
MODULE_NAME = "obspy.io.scardec"
def suite():
suite = unittest.TestSuite()
add_doctests(suite, MODULE_NAME)
add_unittests(suite, MODULE_NAME)
return suite
if __name__ == '__main__':
unittest.main(defaultTest='suite')
| true | true |
f7f92c5acea418b4e2d911fc0bb0bf005281d9ac | 18,818 | py | Python | TME 11. MADDPG/utils.py | hanouticelina/reinforcement-learning | c7c6765486ea9546bbd8ce75e6032a408a1410cf | [
"MIT"
] | null | null | null | TME 11. MADDPG/utils.py | hanouticelina/reinforcement-learning | c7c6765486ea9546bbd8ce75e6032a408a1410cf | [
"MIT"
] | null | null | null | TME 11. MADDPG/utils.py | hanouticelina/reinforcement-learning | c7c6765486ea9546bbd8ce75e6032a408a1410cf | [
"MIT"
] | null | null | null | import time
import subprocess
from collections import namedtuple,defaultdict
import logging
import json
import os
import yaml
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import sys
import threading
import numpy as np
import gym
from collections import deque
import random
import torch.autograd
from torch.autograd import Variable
import torch.optim as optim
import copy
class CriticNetwork(nn.Module):
def __init__(self, state_dim, action_dim):
super(CriticNetwork, self).__init__()
self.state_fc = nn.Linear(state_dim, 64)
self.fc1 = nn.Linear(action_dim+64, 128)
self.fc2 = nn.Linear(128, 64)
self.fc3 = nn.Linear(64, 1)
self.reset_parameters()
def reset_parameters(self):
self.state_fc.weight.data.uniform_(*hidden_init(self.state_fc))
self.fc1.weight.data.uniform_(*hidden_init(self.fc1))
self.fc2.weight.data.uniform_(*hidden_init(self.fc2))
self.fc3.weight.data.uniform_(-3e-3, 3e-3)
def forward(self, state, action):
state, action = state.squeeze(), action.squeeze()
x = F.relu(self.state_fc(state))
x = torch.cat((x, action), dim=1)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
return self.fc3(x)
def hidden_init(layer):
fan_in = layer.weight.data.size()[0]
lim = 1. / np.sqrt(fan_in)
return (-lim, lim)
class ActorNetwork(nn.Module):
def __init__(self, state_dim, action_dim):
super(ActorNetwork, self).__init__()
self.fc1 = nn.Linear(state_dim, 64)
self.fc2 = nn.Linear(64, 128)
self.fc3 = nn.Linear(128, action_dim)
self.reset_parameters()
def reset_parameters(self):
"""
Initialize parameters
"""
self.fc1.weight.data.uniform_(*hidden_init(self.fc1))
self.fc2.weight.data.uniform_(*hidden_init(self.fc2))
self.fc3.weight.data.uniform_(-3e-3, 3e-3)
def forward(self, x):
"""
Maps a state to actions
"""
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
return torch.tanh(self.fc3(x))
class OUNoise(object):
def __init__(self, action_space, mu=0.0, theta=0.15, max_sigma=0.3, min_sigma=0.3, decay_period=100000):
self.mu = mu
self.theta = theta
self.sigma = max_sigma
self.max_sigma = max_sigma
self.min_sigma = min_sigma
self.decay_period = decay_period
self.action_dim = action_space.shape[0]
self.low = action_space.low
self.high = action_space.high
self.reset()
def reset(self):
self.state = np.ones(self.action_dim) * self.mu
def evolve_state(self):
x = self.state
dx = self.theta * (self.mu - x) + self.sigma * np.random.randn(self.action_dim)
self.state = x + dx
return self.state
def get_action(self, action, t=0):
ou_state = self.evolve_state()
self.sigma = self.max_sigma - (self.max_sigma - self.min_sigma) * min(1.0, t / self.decay_period)
return np.clip(action + ou_state, self.low, self.high)
def loadTensorBoard(outdir):
t = threading.Thread(target=launchTensorBoard, args=([outdir]))
t.start()
def launchTensorBoard(tensorBoardPath):
print('tensorboard --logdir=' + tensorBoardPath)
ret=os.system('tensorboard --logdir=' + tensorBoardPath)
if ret!=0:
syspath = os.path.dirname(sys.executable)
print(os.path.dirname(sys.executable))
ret = os.system(syspath+"/"+'tensorboard --logdir=' + tensorBoardPath)
return
class Orn_Uhlen:
def __init__(self, n_actions, mu=0, theta=0.15, sigma=0.2):
self.n_actions = n_actions
self.X = np.ones(n_actions) * mu
self.mu = mu
self.sigma = sigma
self.theta = theta
def reset(self):
self.X = np.ones(self.n_actions) * self.mu
def sample(self):
dX = self.theta * (self.mu - self.X)
dX += self.sigma * np.random.randn(self.n_actions)
self.X += dX
return torch.FloatTensor(self.X)
class FeatureExtractor(object):
def __init__(self):
super().__init__()
def getFeatures(self,obs):
pass
class NothingToDo(FeatureExtractor):
def __init__(self,env):
super().__init__()
ob=env.reset()
self.outSize=len(ob)
def getFeatures(self,obs):
return obs
###### Pour Gridworld #############################"
class MapFromDumpExtractor(FeatureExtractor):
def __init__(self,env):
super().__init__()
outSize = env.start_grid_map.reshape(1, -1).shape[1]
self.outSize=outSize
def getFeatures(self, obs):
#prs(obs)
return obs.reshape(1,-1)
class MapFromDumpExtractor2(FeatureExtractor):
def __init__(self,env):
super().__init__()
outSize=env.start_grid_map.reshape(1, -1).shape[1]
self.outSize=outSize*3
def getFeatures(self, obs):
state=np.zeros((3,np.shape(obs)[0],np.shape(obs)[1]))
state[0]=np.where(obs == 2,1,state[0])
state[1] = np.where(obs == 4, 1, state[1])
state[2] = np.where(obs == 6, 1, state[2])
return state.reshape(1,-1)
class DistsFromStates(FeatureExtractor):
def __init__(self,env):
super().__init__()
self.outSize=16
def getFeatures(self, obs):
#prs(obs)
#x=np.loads(obs)
x=obs
#print(x)
astate = list(map(
lambda x: x[0] if len(x) > 0 else None,
np.where(x == 2)
))
astate=np.array(astate)
a3=np.where(x == 3)
d3=np.array([0])
if len(a3[0])>0:
astate3 = np.concatenate(a3).reshape(2,-1).T
d3=np.power(astate-astate3,2).sum(1).min().reshape(1)
#d3 = np.array(d3).reshape(1)
a4 = np.where(x == 4)
d4 = np.array([0])
if len(a4[0]) > 0:
astate4 = np.concatenate(a4).reshape(2,-1).T
d4 = np.power(astate - astate4, 2).sum(1).min().reshape(1)
#d4 = np.array(d4)
a5 = np.where(x == 5)
d5 = np.array([0])
#prs(a5)
if len(a5[0]) > 0:
astate5 = np.concatenate(a5).reshape(2,-1).T
d5 = np.power(astate - astate5, 2).sum(1).min().reshape(1)
#d5 = np.array(d5)
a6 = np.where(x == 6)
d6 = np.array([0])
if len(a6[0]) > 0:
astate6 = np.concatenate(a6).reshape(2,-1).T
d6 = np.power(astate - astate6, 2).sum(1).min().reshape(1)
#d6=np.array(d6)
#prs("::",d3,d4,d5,d6)
ret=np.concatenate((d3,d4,d5,d6)).reshape(1,-1)
ret=np.dot(ret.T,ret)
return ret.reshape(1,-1)
class convMDP(nn.Module):
def __init__(self, inSize, outSize, layers=[], convs=None, finalActivation=None, batchNorm=False,init_batchNorm=False,activation=torch.tanh):
super(convMDP, self).__init__()
#print(inSize,outSize)
self.inSize=inSize
self.outSize=outSize
self.batchNorm=batchNorm
self.init_batchNorm = init_batchNorm
self.activation=activation
self.convs=None
if convs is not None:
self.convs = nn.ModuleList([])
for x in convs:
self.convs.append(nn.Conv2d(x[0], x[1], x[2], stride=x[3]))
inSize = np.sqrt(inSize / x[0])
inSize=((inSize-x[2])/x[3])+1
inSize=inSize*inSize*x[1]
#print(inSize)
self.layers = nn.ModuleList([])
self.bn = nn.ModuleList([])
i=0
if batchNorm or init_batchNorm:
self.bn.append(nn.BatchNorm1d(num_features=inSize))
for x in layers:
self.layers.append(nn.Linear(inSize, x))
if batchNorm:
self.bn.append(nn.BatchNorm1d(num_features=x))
#nn.init.xavier_uniform_(self.layers[i].weight)
nn.init.normal_(self.layers[i].weight.data, 0.0, 0.02)
nn.init.normal_(self.layers[i].bias.data,0.0,0.02)
i+=1
inSize = x
self.layers.append(nn.Linear(inSize, outSize))
#nn.init.uniform_(self.layers[-1].weight)
nn.init.normal_(self.layers[-1].weight.data, 0.0, 0.02)
nn.init.normal_(self.layers[-1].bias.data, 0.0, 0.02)
self.finalActivation=finalActivation
def forward(self, x):
#print("d", x.size(),self.inSize)
x=x.view(-1,self.inSize)
if self.convs is not None:
n=x.size()[0]
i=0
for c in self.convs:
if i==0:
w=np.sqrt(x.size()[1])
x=x.view(n,c.in_channels,w,w)
x=c(x)
x=self.activation(x)
i+=1
x=x.view(n,-1)
#print(x.size())
if self.batchNorm or self.init_batchNorm:
x=self.bn[0](x)
x = self.layers[0](x)
for i in range(1, len(self.layers)):
x = self.activation(x)
#if self.drop is not None:
# x = nn.drop(x)
if self.batchNorm:
x = self.bn[i](x)
x = self.layers[i](x)
if self.finalActivation is not None:
x=self.finalActivation(x)
#print("f",x.size())
return x
class NN(nn.Module):
def __init__(self, inSize, outSize, layers=[]):
super(NN, self).__init__()
self.layers = nn.ModuleList([])
for x in layers:
self.layers.append(nn.Linear(inSize, x))
inSize = x
self.layers.append(nn.Linear(inSize, outSize))
def forward(self, x):
x = self.layers[0](x)
for i in range(1, len(self.layers)):
x = torch.tanh(x)
x = self.layers[i](x)
return x
class Critic(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(Critic, self).__init__()
self.linear1 = nn.Linear(input_size, hidden_size)
self.linear2 = nn.Linear(hidden_size, hidden_size)
self.linear3 = nn.Linear(hidden_size, output_size)
def forward(self, state, action):
"""
Params state and actions are torch tensors
"""
x = torch.cat([state, action], 1)
x = F.relu(self.linear1(x))
x = F.relu(self.linear2(x))
x = self.linear3(x)
return x
class Actor(nn.Module):
def __init__(self, input_size, hidden_size, output_size, learning_rate = 3e-4):
super(Actor, self).__init__()
self.linear1 = nn.Linear(input_size, hidden_size)
self.linear2 = nn.Linear(hidden_size, hidden_size)
self.linear3 = nn.Linear(hidden_size, output_size)
def forward(self, state):
"""
Param state is a torch tensor
"""
x = F.relu(self.linear1(state))
x = F.relu(self.linear2(x))
x = torch.tanh(self.linear3(x))
return x
class LogMe(dict):
def __init__(self,writer,term=True):
self.writer = writer
self.dic = defaultdict(list)
self.term = term
def write(self,i):
if len(self.dic)==0: return
s=f"Epoch {i} : "
for k,v in self.dic.items():
self.writer.add_scalar(k,sum(v)*1./len(v),i)
s+=f"{k}:{sum(v)*1./len(v)} -- "
self.dic.clear()
if self.term: logging.info(s)
def update(self,l):
for k,v in l:
self.add(k,v)
def direct_write(self,k,v,i):
self.writer.add_scalar(k,v,i)
def add(self,k,v):
self.dic[k].append(v)
def save_src(path):
current_dir = os.getcwd()
package_dir = current_dir.split('RL', 1)[0]
#path = os.path.abspath(path)
os.chdir(package_dir)
#print(package_dir)
src_files = subprocess.Popen(('find', 'RL', '-name', '*.py', '-o', '-name', '*.yaml'),
stdout=subprocess.PIPE)
#print(package_dir,path)
#path=os.path.abspath(path)
#print(str(src_files))
subprocess.check_output(('tar', '-zcf', path+"/arch.tar", '-T', '-'), stdin=src_files.stdout, stderr=subprocess.STDOUT)
src_files.wait()
os.chdir(current_dir)
def draw(scores, path="fig.png", title="Performance", xlabel="Episode #", ylabel="Score"):
fig = plt.figure()
ax = fig.add_subplot(111)
plt.title(title)
plt.plot(np.arange(len(scores)), scores)
plt.ylabel(ylabel)
plt.xlabel(xlabel)
plt.savefig(path)
def prs(*args):
st = ""
for s in args:
st += str(s)
print(st)
class DotDict(dict):
"""dot.notation access to dictionary attributes (Thomas Robert)"""
__getattr__ = dict.get
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
def load_yaml(path):
with open(path, 'r') as stream:
opt = yaml.load(stream,Loader=yaml.Loader)
return DotDict(opt)
def write_yaml(file,dotdict):
d=dict(dotdict)
with open(file, 'w', encoding='utf8') as outfile:
yaml.dump(d, outfile, default_flow_style=False, allow_unicode=True)
class EpsilonGreedyDecay:
def __init__(self, epsilon, eta, epsilon_min):
self.eta = eta
self.epsilon=epsilon
self.epsilon_min=epsilon_min
def act(self, episode, q_values):
decay = self.epsilon / (1 + (self.eta * episode))
if decay<self.epsilon_min:
decay=self.epsilon_min
if np.random.random() > decay:
_,action = torch.max(q_values,0) # we take the action that maximize the q_value
return action.item()
return np.random.randint(len(q_values))
class DDPGAgent:
def __init__(self,
state_dim,
action_dim,
lr_actor = 1e-4,
lr_critic = 1e-4,
lr_decay = .95,
replay_buff_size = 10000,
gamma = .9,
batch_size = 128,
random_seed = 42,
soft_update_tau = 1e-3
):
self.lr_actor = lr_actor
self.gamma = gamma
self.lr_critic = lr_critic
self.lr_decay = lr_decay
self.tau = soft_update_tau
self.actor_local = ActorNetwork(state_dim, action_dim)
self.actor_target = ActorNetwork(state_dim, action_dim)
self.actor_optimizer = optim.Adam(self.actor_local.parameters(), lr=self.lr_actor)
self.critic_local = CriticNetwork(state_dim, action_dim)
self.critic_target = CriticNetwork(state_dim, action_dim)
self.critic_optimizer = optim.Adam(self.critic_local.parameters(), lr=self.lr_critic)
self.noise = OUNoise(action_dim, random_seed)
self.memory = ReplayBuffer(action_dim, replay_buff_size, batch_size, random_seed)
def update_model(self, state, action, reward, next_state, done):
self.memory.add(state, action, reward, next_state, done)
if not self.memory.is_ready():
return
experiences = self.memory.sample()
states, actions, rewards, next_states, dones = experiences
actions_next = self.actor_target(next_states)
Q_targets_next = self.critic_target(next_states, actions_next)
Q_targets = rewards + (self.gamma * Q_targets_next * (1 - dones)).detach()
Q_expected = self.critic_local(states, actions)
y = Q_targets.mean().item()
critic_loss = F.smooth_l1_loss(Q_expected, Q_targets)
self.critic_optimizer.zero_grad()
critic_loss.backward()
self.critic_optimizer.step()
actions_pred = self.actor_local(states)
actor_loss = -self.critic_local(states, actions_pred).mean()
self.actor_optimizer.zero_grad()
actor_loss.backward()
self.actor_optimizer.step()
self.soft_update(self.critic_local, self.critic_target, self.tau)
self.soft_update(self.actor_local, self.actor_target, self.tau)
def act(self, state, noise_t=0.0):
if random.random()<0.1:
v=random.random()
return np.array([v,1-v])
if len(np.shape(state)) == 1:
state = state.reshape(1,-1)
state = torch.from_numpy(state).float()
self.actor_local.eval()
with torch.no_grad():
action = self.actor_local(state).cpu().data.numpy()
self.actor_local.train()
action += self.noise.sample() * noise_t
return np.clip(action, -1, 1).squeeze()
def reset(self):
self.noise.reset()
def soft_update(self, local_model, target_model, tau):
for target_param, local_param in zip(target_model.parameters(), local_model.parameters()):
target_param.data.copy_(tau*local_param.data + (1.0-tau)*target_param.data)
class OUNoise:
def __init__(self, size, seed, mu=0., theta=0.15, sigma=0.2):
self.mu = mu * np.ones(size)
self.theta = theta
self.sigma = sigma
self.seed = random.seed(seed)
self.reset()
def reset(self):
self.state = copy.copy(self.mu)
def sample(self):
x = self.state
dx = self.theta * (self.mu - x) + self.sigma * np.array([random.random() for i in range(len(x))])
self.state = x + dx
return self.state
class ReplayBuffer:
def __init__(self, action_size, buffer_size, batch_size, seed):
self.action_size = action_size
self.memory = deque(maxlen=buffer_size) # internal memory (deque)
self.batch_size = batch_size
self.experience = namedtuple("Experience", field_names=["state", "action", "reward", "next_state", "done"])
self.seed = random.seed(seed)
def add(self, state, action, reward, next_state, done):
e = self.experience(state, action, reward, next_state, done)
self.memory.append(e)
def sample(self):
experiences = random.sample(self.memory, k=self.batch_size)
states = torch.from_numpy(np.vstack([e.state for e in experiences if e is not None])).float()
actions = torch.from_numpy(np.vstack([e.action for e in experiences if e is not None])).float()
rewards = torch.from_numpy(np.vstack([e.reward for e in experiences if e is not None])).float()
next_states = torch.from_numpy(np.vstack([e.next_state for e in experiences if e is not None])).float()
dones = torch.from_numpy(np.vstack([e.done for e in experiences if e is not None]).astype(np.uint8)).float()
return (states, actions, rewards, next_states, dones)
def is_ready(self):
return len(self.memory) > self.batch_size
def __len__(self):
return len(self.memory)
| 31.052805 | 145 | 0.587416 | import time
import subprocess
from collections import namedtuple,defaultdict
import logging
import json
import os
import yaml
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import sys
import threading
import numpy as np
import gym
from collections import deque
import random
import torch.autograd
from torch.autograd import Variable
import torch.optim as optim
import copy
class CriticNetwork(nn.Module):
def __init__(self, state_dim, action_dim):
super(CriticNetwork, self).__init__()
self.state_fc = nn.Linear(state_dim, 64)
self.fc1 = nn.Linear(action_dim+64, 128)
self.fc2 = nn.Linear(128, 64)
self.fc3 = nn.Linear(64, 1)
self.reset_parameters()
def reset_parameters(self):
self.state_fc.weight.data.uniform_(*hidden_init(self.state_fc))
self.fc1.weight.data.uniform_(*hidden_init(self.fc1))
self.fc2.weight.data.uniform_(*hidden_init(self.fc2))
self.fc3.weight.data.uniform_(-3e-3, 3e-3)
def forward(self, state, action):
state, action = state.squeeze(), action.squeeze()
x = F.relu(self.state_fc(state))
x = torch.cat((x, action), dim=1)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
return self.fc3(x)
def hidden_init(layer):
fan_in = layer.weight.data.size()[0]
lim = 1. / np.sqrt(fan_in)
return (-lim, lim)
class ActorNetwork(nn.Module):
def __init__(self, state_dim, action_dim):
super(ActorNetwork, self).__init__()
self.fc1 = nn.Linear(state_dim, 64)
self.fc2 = nn.Linear(64, 128)
self.fc3 = nn.Linear(128, action_dim)
self.reset_parameters()
def reset_parameters(self):
self.fc1.weight.data.uniform_(*hidden_init(self.fc1))
self.fc2.weight.data.uniform_(*hidden_init(self.fc2))
self.fc3.weight.data.uniform_(-3e-3, 3e-3)
def forward(self, x):
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
return torch.tanh(self.fc3(x))
class OUNoise(object):
def __init__(self, action_space, mu=0.0, theta=0.15, max_sigma=0.3, min_sigma=0.3, decay_period=100000):
self.mu = mu
self.theta = theta
self.sigma = max_sigma
self.max_sigma = max_sigma
self.min_sigma = min_sigma
self.decay_period = decay_period
self.action_dim = action_space.shape[0]
self.low = action_space.low
self.high = action_space.high
self.reset()
def reset(self):
self.state = np.ones(self.action_dim) * self.mu
def evolve_state(self):
x = self.state
dx = self.theta * (self.mu - x) + self.sigma * np.random.randn(self.action_dim)
self.state = x + dx
return self.state
def get_action(self, action, t=0):
ou_state = self.evolve_state()
self.sigma = self.max_sigma - (self.max_sigma - self.min_sigma) * min(1.0, t / self.decay_period)
return np.clip(action + ou_state, self.low, self.high)
def loadTensorBoard(outdir):
t = threading.Thread(target=launchTensorBoard, args=([outdir]))
t.start()
def launchTensorBoard(tensorBoardPath):
print('tensorboard --logdir=' + tensorBoardPath)
ret=os.system('tensorboard --logdir=' + tensorBoardPath)
if ret!=0:
syspath = os.path.dirname(sys.executable)
print(os.path.dirname(sys.executable))
ret = os.system(syspath+"/"+'tensorboard --logdir=' + tensorBoardPath)
return
class Orn_Uhlen:
def __init__(self, n_actions, mu=0, theta=0.15, sigma=0.2):
self.n_actions = n_actions
self.X = np.ones(n_actions) * mu
self.mu = mu
self.sigma = sigma
self.theta = theta
def reset(self):
self.X = np.ones(self.n_actions) * self.mu
def sample(self):
dX = self.theta * (self.mu - self.X)
dX += self.sigma * np.random.randn(self.n_actions)
self.X += dX
return torch.FloatTensor(self.X)
class FeatureExtractor(object):
def __init__(self):
super().__init__()
def getFeatures(self,obs):
pass
class NothingToDo(FeatureExtractor):
def __init__(self,env):
super().__init__()
ob=env.reset()
self.outSize=len(ob)
def getFeatures(self,obs):
return obs
return state.reshape(1,-1)
class DistsFromStates(FeatureExtractor):
def __init__(self,env):
super().__init__()
self.outSize=16
def getFeatures(self, obs):
#prs(obs)
#x=np.loads(obs)
x=obs
#print(x)
astate = list(map(
lambda x: x[0] if len(x) > 0 else None,
np.where(x == 2)
))
astate=np.array(astate)
a3=np.where(x == 3)
d3=np.array([0])
if len(a3[0])>0:
astate3 = np.concatenate(a3).reshape(2,-1).T
d3=np.power(astate-astate3,2).sum(1).min().reshape(1)
#d3 = np.array(d3).reshape(1)
a4 = np.where(x == 4)
d4 = np.array([0])
if len(a4[0]) > 0:
astate4 = np.concatenate(a4).reshape(2,-1).T
d4 = np.power(astate - astate4, 2).sum(1).min().reshape(1)
#d4 = np.array(d4)
a5 = np.where(x == 5)
d5 = np.array([0])
#prs(a5)
if len(a5[0]) > 0:
astate5 = np.concatenate(a5).reshape(2,-1).T
d5 = np.power(astate - astate5, 2).sum(1).min().reshape(1)
#d5 = np.array(d5)
a6 = np.where(x == 6)
d6 = np.array([0])
if len(a6[0]) > 0:
astate6 = np.concatenate(a6).reshape(2,-1).T
d6 = np.power(astate - astate6, 2).sum(1).min().reshape(1)
#d6=np.array(d6)
#prs("::",d3,d4,d5,d6)
ret=np.concatenate((d3,d4,d5,d6)).reshape(1,-1)
ret=np.dot(ret.T,ret)
return ret.reshape(1,-1)
class convMDP(nn.Module):
def __init__(self, inSize, outSize, layers=[], convs=None, finalActivation=None, batchNorm=False,init_batchNorm=False,activation=torch.tanh):
super(convMDP, self).__init__()
#print(inSize,outSize)
self.inSize=inSize
self.outSize=outSize
self.batchNorm=batchNorm
self.init_batchNorm = init_batchNorm
self.activation=activation
self.convs=None
if convs is not None:
self.convs = nn.ModuleList([])
for x in convs:
self.convs.append(nn.Conv2d(x[0], x[1], x[2], stride=x[3]))
inSize = np.sqrt(inSize / x[0])
inSize=((inSize-x[2])/x[3])+1
inSize=inSize*inSize*x[1]
#print(inSize)
self.layers = nn.ModuleList([])
self.bn = nn.ModuleList([])
i=0
if batchNorm or init_batchNorm:
self.bn.append(nn.BatchNorm1d(num_features=inSize))
for x in layers:
self.layers.append(nn.Linear(inSize, x))
if batchNorm:
self.bn.append(nn.BatchNorm1d(num_features=x))
#nn.init.xavier_uniform_(self.layers[i].weight)
nn.init.normal_(self.layers[i].weight.data, 0.0, 0.02)
nn.init.normal_(self.layers[i].bias.data,0.0,0.02)
i+=1
inSize = x
self.layers.append(nn.Linear(inSize, outSize))
#nn.init.uniform_(self.layers[-1].weight)
nn.init.normal_(self.layers[-1].weight.data, 0.0, 0.02)
nn.init.normal_(self.layers[-1].bias.data, 0.0, 0.02)
self.finalActivation=finalActivation
def forward(self, x):
#print("d", x.size(),self.inSize)
x=x.view(-1,self.inSize)
if self.convs is not None:
n=x.size()[0]
i=0
for c in self.convs:
if i==0:
w=np.sqrt(x.size()[1])
x=x.view(n,c.in_channels,w,w)
x=c(x)
x=self.activation(x)
i+=1
x=x.view(n,-1)
#print(x.size())
if self.batchNorm or self.init_batchNorm:
x=self.bn[0](x)
x = self.layers[0](x)
for i in range(1, len(self.layers)):
x = self.activation(x)
#if self.drop is not None:
# x = nn.drop(x)
if self.batchNorm:
x = self.bn[i](x)
x = self.layers[i](x)
if self.finalActivation is not None:
x=self.finalActivation(x)
#print("f",x.size())
return x
class NN(nn.Module):
def __init__(self, inSize, outSize, layers=[]):
super(NN, self).__init__()
self.layers = nn.ModuleList([])
for x in layers:
self.layers.append(nn.Linear(inSize, x))
inSize = x
self.layers.append(nn.Linear(inSize, outSize))
def forward(self, x):
x = self.layers[0](x)
for i in range(1, len(self.layers)):
x = torch.tanh(x)
x = self.layers[i](x)
return x
class Critic(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(Critic, self).__init__()
self.linear1 = nn.Linear(input_size, hidden_size)
self.linear2 = nn.Linear(hidden_size, hidden_size)
self.linear3 = nn.Linear(hidden_size, output_size)
def forward(self, state, action):
x = torch.cat([state, action], 1)
x = F.relu(self.linear1(x))
x = F.relu(self.linear2(x))
x = self.linear3(x)
return x
class Actor(nn.Module):
def __init__(self, input_size, hidden_size, output_size, learning_rate = 3e-4):
super(Actor, self).__init__()
self.linear1 = nn.Linear(input_size, hidden_size)
self.linear2 = nn.Linear(hidden_size, hidden_size)
self.linear3 = nn.Linear(hidden_size, output_size)
def forward(self, state):
x = F.relu(self.linear1(state))
x = F.relu(self.linear2(x))
x = torch.tanh(self.linear3(x))
return x
class LogMe(dict):
def __init__(self,writer,term=True):
self.writer = writer
self.dic = defaultdict(list)
self.term = term
def write(self,i):
if len(self.dic)==0: return
s=f"Epoch {i} : "
for k,v in self.dic.items():
self.writer.add_scalar(k,sum(v)*1./len(v),i)
s+=f"{k}:{sum(v)*1./len(v)} -- "
self.dic.clear()
if self.term: logging.info(s)
def update(self,l):
for k,v in l:
self.add(k,v)
def direct_write(self,k,v,i):
self.writer.add_scalar(k,v,i)
def add(self,k,v):
self.dic[k].append(v)
def save_src(path):
current_dir = os.getcwd()
package_dir = current_dir.split('RL', 1)[0]
#path = os.path.abspath(path)
os.chdir(package_dir)
#print(package_dir)
src_files = subprocess.Popen(('find', 'RL', '-name', '*.py', '-o', '-name', '*.yaml'),
stdout=subprocess.PIPE)
#print(package_dir,path)
#path=os.path.abspath(path)
#print(str(src_files))
subprocess.check_output(('tar', '-zcf', path+"/arch.tar", '-T', '-'), stdin=src_files.stdout, stderr=subprocess.STDOUT)
src_files.wait()
os.chdir(current_dir)
def draw(scores, path="fig.png", title="Performance", xlabel="Episode
fig = plt.figure()
ax = fig.add_subplot(111)
plt.title(title)
plt.plot(np.arange(len(scores)), scores)
plt.ylabel(ylabel)
plt.xlabel(xlabel)
plt.savefig(path)
def prs(*args):
st = ""
for s in args:
st += str(s)
print(st)
class DotDict(dict):
__getattr__ = dict.get
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
def load_yaml(path):
with open(path, 'r') as stream:
opt = yaml.load(stream,Loader=yaml.Loader)
return DotDict(opt)
def write_yaml(file,dotdict):
d=dict(dotdict)
with open(file, 'w', encoding='utf8') as outfile:
yaml.dump(d, outfile, default_flow_style=False, allow_unicode=True)
class EpsilonGreedyDecay:
def __init__(self, epsilon, eta, epsilon_min):
self.eta = eta
self.epsilon=epsilon
self.epsilon_min=epsilon_min
def act(self, episode, q_values):
decay = self.epsilon / (1 + (self.eta * episode))
if decay<self.epsilon_min:
decay=self.epsilon_min
if np.random.random() > decay:
_,action = torch.max(q_values,0) # we take the action that maximize the q_value
return action.item()
return np.random.randint(len(q_values))
class DDPGAgent:
def __init__(self,
state_dim,
action_dim,
lr_actor = 1e-4,
lr_critic = 1e-4,
lr_decay = .95,
replay_buff_size = 10000,
gamma = .9,
batch_size = 128,
random_seed = 42,
soft_update_tau = 1e-3
):
self.lr_actor = lr_actor
self.gamma = gamma
self.lr_critic = lr_critic
self.lr_decay = lr_decay
self.tau = soft_update_tau
self.actor_local = ActorNetwork(state_dim, action_dim)
self.actor_target = ActorNetwork(state_dim, action_dim)
self.actor_optimizer = optim.Adam(self.actor_local.parameters(), lr=self.lr_actor)
self.critic_local = CriticNetwork(state_dim, action_dim)
self.critic_target = CriticNetwork(state_dim, action_dim)
self.critic_optimizer = optim.Adam(self.critic_local.parameters(), lr=self.lr_critic)
self.noise = OUNoise(action_dim, random_seed)
self.memory = ReplayBuffer(action_dim, replay_buff_size, batch_size, random_seed)
def update_model(self, state, action, reward, next_state, done):
self.memory.add(state, action, reward, next_state, done)
if not self.memory.is_ready():
return
experiences = self.memory.sample()
states, actions, rewards, next_states, dones = experiences
actions_next = self.actor_target(next_states)
Q_targets_next = self.critic_target(next_states, actions_next)
Q_targets = rewards + (self.gamma * Q_targets_next * (1 - dones)).detach()
Q_expected = self.critic_local(states, actions)
y = Q_targets.mean().item()
critic_loss = F.smooth_l1_loss(Q_expected, Q_targets)
self.critic_optimizer.zero_grad()
critic_loss.backward()
self.critic_optimizer.step()
actions_pred = self.actor_local(states)
actor_loss = -self.critic_local(states, actions_pred).mean()
self.actor_optimizer.zero_grad()
actor_loss.backward()
self.actor_optimizer.step()
self.soft_update(self.critic_local, self.critic_target, self.tau)
self.soft_update(self.actor_local, self.actor_target, self.tau)
def act(self, state, noise_t=0.0):
if random.random()<0.1:
v=random.random()
return np.array([v,1-v])
if len(np.shape(state)) == 1:
state = state.reshape(1,-1)
state = torch.from_numpy(state).float()
self.actor_local.eval()
with torch.no_grad():
action = self.actor_local(state).cpu().data.numpy()
self.actor_local.train()
action += self.noise.sample() * noise_t
return np.clip(action, -1, 1).squeeze()
def reset(self):
self.noise.reset()
def soft_update(self, local_model, target_model, tau):
for target_param, local_param in zip(target_model.parameters(), local_model.parameters()):
target_param.data.copy_(tau*local_param.data + (1.0-tau)*target_param.data)
class OUNoise:
def __init__(self, size, seed, mu=0., theta=0.15, sigma=0.2):
self.mu = mu * np.ones(size)
self.theta = theta
self.sigma = sigma
self.seed = random.seed(seed)
self.reset()
def reset(self):
self.state = copy.copy(self.mu)
def sample(self):
x = self.state
dx = self.theta * (self.mu - x) + self.sigma * np.array([random.random() for i in range(len(x))])
self.state = x + dx
return self.state
class ReplayBuffer:
def __init__(self, action_size, buffer_size, batch_size, seed):
self.action_size = action_size
self.memory = deque(maxlen=buffer_size) # internal memory (deque)
self.batch_size = batch_size
self.experience = namedtuple("Experience", field_names=["state", "action", "reward", "next_state", "done"])
self.seed = random.seed(seed)
def add(self, state, action, reward, next_state, done):
e = self.experience(state, action, reward, next_state, done)
self.memory.append(e)
def sample(self):
experiences = random.sample(self.memory, k=self.batch_size)
states = torch.from_numpy(np.vstack([e.state for e in experiences if e is not None])).float()
actions = torch.from_numpy(np.vstack([e.action for e in experiences if e is not None])).float()
rewards = torch.from_numpy(np.vstack([e.reward for e in experiences if e is not None])).float()
next_states = torch.from_numpy(np.vstack([e.next_state for e in experiences if e is not None])).float()
dones = torch.from_numpy(np.vstack([e.done for e in experiences if e is not None]).astype(np.uint8)).float()
return (states, actions, rewards, next_states, dones)
def is_ready(self):
return len(self.memory) > self.batch_size
def __len__(self):
return len(self.memory)
| true | true |
f7f92ced61d900672394cb62f5631ec72b8361a7 | 660 | py | Python | examples/web_counter/tdmf_components.py | cmdimkpa/test-driven-modular-framework | 3006557ddc5a9e52c59fb492f5d01a130ab1c759 | [
"MIT"
] | null | null | null | examples/web_counter/tdmf_components.py | cmdimkpa/test-driven-modular-framework | 3006557ddc5a9e52c59fb492f5d01a130ab1c759 | [
"MIT"
] | null | null | null | examples/web_counter/tdmf_components.py | cmdimkpa/test-driven-modular-framework | 3006557ddc5a9e52c59fb492f5d01a130ab1c759 | [
"MIT"
] | null | null | null | def download_webpage(package):
'''
Grab HTML from a webpage
'''
func_name = "download_webpage"
output = []
try:
# package is an array with a single url
url = package[0]
# grab HTML
html = http.get(url).content.decode()
# update byte_counter state
byte_counter = flags.get("byte_counter")
byte_counter += len(html)
flags.set("byte_counter", byte_counter)
# push HTML to output
output.append(html)
except Exception as error:
print("Error occured at {}: {}".format(func_name, str(error)))
return output
| 24.444444 | 71 | 0.560606 | def download_webpage(package):
func_name = "download_webpage"
output = []
try:
url = package[0]
html = http.get(url).content.decode()
byte_counter = flags.get("byte_counter")
byte_counter += len(html)
flags.set("byte_counter", byte_counter)
output.append(html)
except Exception as error:
print("Error occured at {}: {}".format(func_name, str(error)))
return output
| true | true |
f7f92d2a185da5e809f82b907637b43fff531049 | 31,958 | py | Python | msal/application.py | dsanghan/microsoft-authentication-library-for-python | 9e122eeb4cd1224132eb06001f9d88939a996f8e | [
"MIT"
] | null | null | null | msal/application.py | dsanghan/microsoft-authentication-library-for-python | 9e122eeb4cd1224132eb06001f9d88939a996f8e | [
"MIT"
] | null | null | null | msal/application.py | dsanghan/microsoft-authentication-library-for-python | 9e122eeb4cd1224132eb06001f9d88939a996f8e | [
"MIT"
] | null | null | null | import time
try: # Python 2
from urlparse import urljoin
except: # Python 3
from urllib.parse import urljoin
import logging
import sys
import warnings
import requests
from .oauth2cli import Client, JwtAssertionCreator
from .authority import Authority
from .mex import send_request as mex_send_request
from .wstrust_request import send_request as wst_send_request
from .wstrust_response import *
from .token_cache import TokenCache
# The __init__.py will import this. Not the other way around.
__version__ = "0.6.1"
logger = logging.getLogger(__name__)
def decorate_scope(
scopes, client_id,
reserved_scope=frozenset(['openid', 'profile', 'offline_access'])):
if not isinstance(scopes, (list, set, tuple)):
raise ValueError("The input scopes should be a list, tuple, or set")
scope_set = set(scopes) # Input scopes is typically a list. Copy it to a set.
if scope_set & reserved_scope:
# These scopes are reserved for the API to provide good experience.
# We could make the developer pass these and then if they do they will
# come back asking why they don't see refresh token or user information.
raise ValueError(
"API does not accept {} value as user-provided scopes".format(
reserved_scope))
if client_id in scope_set:
if len(scope_set) > 1:
# We make developers pass their client id, so that they can express
# the intent that they want the token for themselves (their own
# app).
# If we do not restrict them to passing only client id then they
# could write code where they expect an id token but end up getting
# access_token.
raise ValueError("Client Id can only be provided as a single scope")
decorated = set(reserved_scope) # Make a writable copy
else:
decorated = scope_set | reserved_scope
return list(decorated)
def extract_certs(public_cert_content):
# Parses raw public certificate file contents and returns a list of strings
# Usage: headers = {"x5c": extract_certs(open("my_cert.pem").read())}
public_certificates = re.findall(
r'-----BEGIN CERTIFICATE-----(?P<cert_value>[^-]+)-----END CERTIFICATE-----',
public_cert_content, re.I)
if public_certificates:
return [cert.strip() for cert in public_certificates]
# The public cert tags are not found in the input,
# let's make best effort to exclude a private key pem file.
if "PRIVATE KEY" in public_cert_content:
raise ValueError(
"We expect your public key but detect a private key instead")
return [public_cert_content.strip()]
class ClientApplication(object):
def __init__(
self, client_id,
client_credential=None, authority=None, validate_authority=True,
token_cache=None,
verify=True, proxies=None, timeout=None,
client_claims=None):
"""Create an instance of application.
:param client_id: Your app has a client_id after you register it on AAD.
:param client_credential:
For :class:`PublicClientApplication`, you simply use `None` here.
For :class:`ConfidentialClientApplication`,
it can be a string containing client secret,
or an X509 certificate container in this form::
{
"private_key": "...-----BEGIN PRIVATE KEY-----...",
"thumbprint": "A1B2C3D4E5F6...",
"public_certificate": "...-----BEGIN CERTIFICATE-----..." (Optional. See below.)
}
*Added in version 0.5.0*:
public_certificate (optional) is public key certificate
which will be sent through 'x5c' JWT header only for
subject name and issuer authentication to support cert auto rolls.
:param dict client_claims:
*Added in version 0.5.0*:
It is a dictionary of extra claims that would be signed by
by this :class:`ConfidentialClientApplication` 's private key.
For example, you can use {"client_ip": "x.x.x.x"}.
You may also override any of the following default claims::
{
"aud": the_token_endpoint,
"iss": self.client_id,
"sub": same_as_issuer,
"exp": now + 10_min,
"iat": now,
"jti": a_random_uuid
}
:param str authority:
A URL that identifies a token authority. It should be of the format
https://login.microsoftonline.com/your_tenant
By default, we will use https://login.microsoftonline.com/common
:param bool validate_authority: (optional) Turns authority validation
on or off. This parameter default to true.
:param TokenCache cache:
Sets the token cache used by this ClientApplication instance.
By default, an in-memory cache will be created and used.
:param verify: (optional)
It will be passed to the
`verify parameter in the underlying requests library
<http://docs.python-requests.org/en/v2.9.1/user/advanced/#ssl-cert-verification>`_
:param proxies: (optional)
It will be passed to the
`proxies parameter in the underlying requests library
<http://docs.python-requests.org/en/v2.9.1/user/advanced/#proxies>`_
:param timeout: (optional)
It will be passed to the
`timeout parameter in the underlying requests library
<http://docs.python-requests.org/en/v2.9.1/user/advanced/#timeouts>`_
"""
self.client_id = client_id
self.client_credential = client_credential
self.client_claims = client_claims
self.verify = verify
self.proxies = proxies
self.timeout = timeout
self.authority = Authority(
authority or "https://login.microsoftonline.com/common/",
validate_authority, verify=verify, proxies=proxies, timeout=timeout)
# Here the self.authority is not the same type as authority in input
self.token_cache = token_cache or TokenCache()
self.client = self._build_client(client_credential, self.authority)
self.authority_groups = None
def _build_client(self, client_credential, authority):
client_assertion = None
client_assertion_type = None
default_body = {"client_info": 1}
if isinstance(client_credential, dict):
assert ("private_key" in client_credential
and "thumbprint" in client_credential)
headers = {}
if 'public_certificate' in client_credential:
headers["x5c"] = extract_certs(client_credential['public_certificate'])
assertion = JwtAssertionCreator(
client_credential["private_key"], algorithm="RS256",
sha1_thumbprint=client_credential.get("thumbprint"), headers=headers)
client_assertion = assertion.create_regenerative_assertion(
audience=authority.token_endpoint, issuer=self.client_id,
additional_claims=self.client_claims or {})
client_assertion_type = Client.CLIENT_ASSERTION_TYPE_JWT
else:
default_body['client_secret'] = client_credential
server_configuration = {
"authorization_endpoint": authority.authorization_endpoint,
"token_endpoint": authority.token_endpoint,
"device_authorization_endpoint":
urljoin(authority.token_endpoint, "devicecode"),
}
return Client(
server_configuration,
self.client_id,
default_headers={
"x-client-sku": "MSAL.Python", "x-client-ver": __version__,
"x-client-os": sys.platform,
"x-client-cpu": "x64" if sys.maxsize > 2 ** 32 else "x86",
},
default_body=default_body,
client_assertion=client_assertion,
client_assertion_type=client_assertion_type,
on_obtaining_tokens=self.token_cache.add,
on_removing_rt=self.token_cache.remove_rt,
on_updating_rt=self.token_cache.update_rt,
verify=self.verify, proxies=self.proxies, timeout=self.timeout)
def get_authorization_request_url(
self,
scopes, # type: list[str]
# additional_scope=None, # type: Optional[list]
login_hint=None, # type: Optional[str]
state=None, # Recommended by OAuth2 for CSRF protection
redirect_uri=None,
authority=None, # By default, it will use self.authority;
# Multi-tenant app can use new authority on demand
response_type="code", # Can be "token" if you use Implicit Grant
**kwargs):
"""Constructs a URL for you to start a Authorization Code Grant.
:param list[str] scopes: (Required)
Scopes requested to access a protected API (a resource).
:param str state: Recommended by OAuth2 for CSRF protection.
:param str login_hint:
Identifier of the user. Generally a User Principal Name (UPN).
:param str redirect_uri:
Address to return to upon receiving a response from the authority.
:return: The authorization url as a string.
"""
""" # TBD: this would only be meaningful in a new acquire_token_interactive()
:param additional_scope: Additional scope is a concept only in AAD.
It refers to other resources you might want to prompt to consent
for in the same interaction, but for which you won't get back a
token for in this particular operation.
(Under the hood, we simply merge scope and additional_scope before
sending them on the wire.)
"""
the_authority = Authority(
authority,
verify=self.verify, proxies=self.proxies, timeout=self.timeout,
) if authority else self.authority
client = Client(
{"authorization_endpoint": the_authority.authorization_endpoint},
self.client_id)
return client.build_auth_request_uri(
response_type="code", # Using Authorization Code grant
redirect_uri=redirect_uri, state=state, login_hint=login_hint,
scope=decorate_scope(scopes, self.client_id),
)
def acquire_token_by_authorization_code(
self,
code,
scopes, # Syntactically required. STS accepts empty value though.
redirect_uri=None,
# REQUIRED, if the "redirect_uri" parameter was included in the
# authorization request as described in Section 4.1.1, and their
# values MUST be identical.
):
"""The second half of the Authorization Code Grant.
:param code: The authorization code returned from Authorization Server.
:param list[str] scopes: (Required)
Scopes requested to access a protected API (a resource).
If you requested user consent for multiple resources, here you will
typically want to provide a subset of what you required in AuthCode.
OAuth2 was designed mostly for singleton services,
where tokens are always meant for the same resource and the only
changes are in the scopes.
In AAD, tokens can be issued for multiple 3rd party resources.
You can ask authorization code for multiple resources,
but when you redeem it, the token is for only one intended
recipient, called audience.
So the developer need to specify a scope so that we can restrict the
token to be issued for the corresponding audience.
:return: A dict representing the json response from AAD:
- A successful response would contain "access_token" key,
- an error response would contain "error" and usually "error_description".
"""
# If scope is absent on the wire, STS will give you a token associated
# to the FIRST scope sent during the authorization request.
# So in theory, you can omit scope here when you were working with only
# one scope. But, MSAL decorates your scope anyway, so they are never
# really empty.
assert isinstance(scopes, list), "Invalid parameter type"
return self.client.obtain_token_by_authorization_code(
code, redirect_uri=redirect_uri,
data={"scope": decorate_scope(scopes, self.client_id)},
)
def get_accounts(self, username=None):
"""Get a list of accounts which previously signed in, i.e. exists in cache.
An account can later be used in :func:`~acquire_token_silent`
to find its tokens.
:param username:
Filter accounts with this username only. Case insensitive.
:return: A list of account objects.
Each account is a dict. For now, we only document its "username" field.
Your app can choose to display those information to end user,
and allow user to choose one of his/her accounts to proceed.
"""
accounts = self._find_msal_accounts(environment=self.authority.instance)
if not accounts: # Now try other aliases of this authority instance
for alias in self._get_authority_aliases(self.authority.instance):
accounts = self._find_msal_accounts(environment=alias)
if accounts:
break
if username:
# Federated account["username"] from AAD could contain mixed case
lowercase_username = username.lower()
accounts = [a for a in accounts
if a["username"].lower() == lowercase_username]
# Does not further filter by existing RTs here. It probably won't matter.
# Because in most cases Accounts and RTs co-exist.
# Even in the rare case when an RT is revoked and then removed,
# acquire_token_silent() would then yield no result,
# apps would fall back to other acquire methods. This is the standard pattern.
return accounts
def _find_msal_accounts(self, environment):
return [a for a in self.token_cache.find(
TokenCache.CredentialType.ACCOUNT, query={"environment": environment})
if a["authority_type"] in (
TokenCache.AuthorityType.ADFS, TokenCache.AuthorityType.MSSTS)]
def _get_authority_aliases(self, instance):
if not self.authority_groups:
resp = requests.get(
"https://login.microsoftonline.com/common/discovery/instance?api-version=1.1&authorization_endpoint=https://login.microsoftonline.com/common/oauth2/authorize",
headers={'Accept': 'application/json'},
verify=self.verify, proxies=self.proxies, timeout=self.timeout)
resp.raise_for_status()
self.authority_groups = [
set(group['aliases']) for group in resp.json()['metadata']]
for group in self.authority_groups:
if instance in group:
return [alias for alias in group if alias != instance]
return []
def remove_account(self, account):
"""Sign me out and forget me from token cache"""
self._forget_me(account)
def _sign_out(self, home_account):
# Remove all relevant RTs and ATs from token cache
owned_by_home_account = {
"environment": home_account["environment"],
"home_account_id": home_account["home_account_id"],} # realm-independent
app_metadata = self._get_app_metadata(home_account["environment"])
# Remove RTs/FRTs, and they are realm-independent
for rt in [rt for rt in self.token_cache.find(
TokenCache.CredentialType.REFRESH_TOKEN, query=owned_by_home_account)
# Do RT's app ownership check as a precaution, in case family apps
# and 3rd-party apps share same token cache, although they should not.
if rt["client_id"] == self.client_id or (
app_metadata.get("family_id") # Now let's settle family business
and rt.get("family_id") == app_metadata["family_id"])
]:
self.token_cache.remove_rt(rt)
for at in self.token_cache.find( # Remove ATs
# Regardless of realm, b/c we've removed realm-independent RTs anyway
TokenCache.CredentialType.ACCESS_TOKEN, query=owned_by_home_account):
# To avoid the complexity of locating sibling family app's AT,
# we skip AT's app ownership check.
# It means ATs for other apps will also be removed, it is OK because:
# * non-family apps are not supposed to share token cache to begin with;
# * Even if it happens, we keep other app's RT already, so SSO still works
self.token_cache.remove_at(at)
def _forget_me(self, home_account):
# It implies signout, and then also remove all relevant accounts and IDTs
self._sign_out(home_account)
owned_by_home_account = {
"environment": home_account["environment"],
"home_account_id": home_account["home_account_id"],} # realm-independent
for idt in self.token_cache.find( # Remove IDTs, regardless of realm
TokenCache.CredentialType.ID_TOKEN, query=owned_by_home_account):
self.token_cache.remove_idt(idt)
for a in self.token_cache.find( # Remove Accounts, regardless of realm
TokenCache.CredentialType.ACCOUNT, query=owned_by_home_account):
self.token_cache.remove_account(a)
def acquire_token_silent(
self,
scopes, # type: List[str]
account, # type: Optional[Account]
authority=None, # See get_authorization_request_url()
force_refresh=False, # type: Optional[boolean]
**kwargs):
"""Acquire an access token for given account, without user interaction.
It is done either by finding a valid access token from cache,
or by finding a valid refresh token from cache and then automatically
use it to redeem a new access token.
:param list[str] scopes: (Required)
Scopes requested to access a protected API (a resource).
:param account:
one of the account object returned by :func:`~get_accounts`,
or use None when you want to find an access token for this client.
:param force_refresh:
If True, it will skip Access Token look-up,
and try to find a Refresh Token to obtain a new Access Token.
:return:
- A dict containing "access_token" key, when cache lookup succeeds.
- None when cache lookup does not yield anything.
"""
assert isinstance(scopes, list), "Invalid parameter type"
if authority:
warnings.warn("We haven't decided how/if this method will accept authority parameter")
# the_authority = Authority(
# authority,
# verify=self.verify, proxies=self.proxies, timeout=self.timeout,
# ) if authority else self.authority
result = self._acquire_token_silent_from_cache_and_possibly_refresh_it(
scopes, account, self.authority, **kwargs)
if result:
return result
for alias in self._get_authority_aliases(self.authority.instance):
the_authority = Authority(
"https://" + alias + "/" + self.authority.tenant,
validate_authority=False,
verify=self.verify, proxies=self.proxies, timeout=self.timeout)
result = self._acquire_token_silent_from_cache_and_possibly_refresh_it(
scopes, account, the_authority, **kwargs)
if result:
return result
def _acquire_token_silent_from_cache_and_possibly_refresh_it(
self,
scopes, # type: List[str]
account, # type: Optional[Account]
authority, # This can be different than self.authority
force_refresh=False, # type: Optional[boolean]
**kwargs):
if not force_refresh:
matches = self.token_cache.find(
self.token_cache.CredentialType.ACCESS_TOKEN,
target=scopes,
query={
"client_id": self.client_id,
"environment": authority.instance,
"realm": authority.tenant,
"home_account_id": (account or {}).get("home_account_id"),
})
now = time.time()
for entry in matches:
expires_in = int(entry["expires_on"]) - now
if expires_in < 5*60:
continue # Removal is not necessary, it will be overwritten
logger.debug("Cache hit an AT")
return { # Mimic a real response
"access_token": entry["secret"],
"token_type": "Bearer",
"expires_in": int(expires_in), # OAuth2 specs defines it as int
}
return self._acquire_token_silent_by_finding_rt_belongs_to_me_or_my_family(
authority, decorate_scope(scopes, self.client_id), account,
**kwargs)
def _acquire_token_silent_by_finding_rt_belongs_to_me_or_my_family(
self, authority, scopes, account, **kwargs):
query = {
"environment": authority.instance,
"home_account_id": (account or {}).get("home_account_id"),
# "realm": authority.tenant, # AAD RTs are tenant-independent
}
app_metadata = self._get_app_metadata(authority.instance)
if not app_metadata: # Meaning this app is now used for the first time.
# When/if we have a way to directly detect current app's family,
# we'll rewrite this block, to support multiple families.
# For now, we try existing RTs (*). If it works, we are in that family.
# (*) RTs of a different app/family are not supposed to be
# shared with or accessible by us in the first place.
at = self._acquire_token_silent_by_finding_specific_refresh_token(
authority, scopes,
dict(query, family_id="1"), # A hack, we have only 1 family for now
rt_remover=lambda rt_item: None, # NO-OP b/c RTs are likely not mine
break_condition=lambda response: # Break loop when app not in family
# Based on an AAD-only behavior mentioned in internal doc here
# https://msazure.visualstudio.com/One/_git/ESTS-Docs/pullrequest/1138595
"client_mismatch" in response.get("error_additional_info", []),
**kwargs)
if at:
return at
if app_metadata.get("family_id"): # Meaning this app belongs to this family
at = self._acquire_token_silent_by_finding_specific_refresh_token(
authority, scopes, dict(query, family_id=app_metadata["family_id"]),
**kwargs)
if at:
return at
# Either this app is an orphan, so we will naturally use its own RT;
# or all attempts above have failed, so we fall back to non-foci behavior.
return self._acquire_token_silent_by_finding_specific_refresh_token(
authority, scopes, dict(query, client_id=self.client_id), **kwargs)
def _get_app_metadata(self, environment):
apps = self.token_cache.find( # Use find(), rather than token_cache.get(...)
TokenCache.CredentialType.APP_METADATA, query={
"environment": environment, "client_id": self.client_id})
return apps[0] if apps else {}
def _acquire_token_silent_by_finding_specific_refresh_token(
self, authority, scopes, query,
rt_remover=None, break_condition=lambda response: False, **kwargs):
matches = self.token_cache.find(
self.token_cache.CredentialType.REFRESH_TOKEN,
# target=scopes, # AAD RTs are scope-independent
query=query)
logger.debug("Found %d RTs matching %s", len(matches), query)
client = self._build_client(self.client_credential, authority)
for entry in matches:
logger.debug("Cache attempts an RT")
response = client.obtain_token_by_refresh_token(
entry, rt_getter=lambda token_item: token_item["secret"],
on_removing_rt=rt_remover or self.token_cache.remove_rt,
scope=scopes,
**kwargs)
if "error" not in response:
return response
logger.debug(
"Refresh failed. {error}: {error_description}".format(**response))
if break_condition(response):
break
class PublicClientApplication(ClientApplication): # browser app or mobile app
def __init__(self, client_id, client_credential=None, **kwargs):
if client_credential is not None:
raise ValueError("Public Client should not possess credentials")
super(PublicClientApplication, self).__init__(
client_id, client_credential=None, **kwargs)
def initiate_device_flow(self, scopes=None, **kwargs):
"""Initiate a Device Flow instance,
which will be used in :func:`~acquire_token_by_device_flow`.
:param list[str] scopes:
Scopes requested to access a protected API (a resource).
:return: A dict representing a newly created Device Flow object.
- A successful response would contain "user_code" key, among others
- an error response would contain some other readable key/value pairs.
"""
return self.client.initiate_device_flow(
scope=decorate_scope(scopes or [], self.client_id),
**kwargs)
def acquire_token_by_device_flow(self, flow, **kwargs):
"""Obtain token by a device flow object, with customizable polling effect.
:param dict flow:
A dict previously generated by :func:`~initiate_device_flow`.
By default, this method's polling effect will block current thread.
You can abort the polling loop at any time,
by changing the value of the flow's "expires_at" key to 0.
:return: A dict representing the json response from AAD:
- A successful response would contain "access_token" key,
- an error response would contain "error" and usually "error_description".
"""
return self.client.obtain_token_by_device_flow(
flow,
data={"code": flow["device_code"]}, # 2018-10-4 Hack:
# during transition period,
# service seemingly need both device_code and code parameter.
**kwargs)
def acquire_token_by_username_password(
self, username, password, scopes, **kwargs):
"""Gets a token for a given resource via user credentails.
See this page for constraints of Username Password Flow.
https://github.com/AzureAD/microsoft-authentication-library-for-python/wiki/Username-Password-Authentication
:param str username: Typically a UPN in the form of an email address.
:param str password: The password.
:param list[str] scopes:
Scopes requested to access a protected API (a resource).
:return: A dict representing the json response from AAD:
- A successful response would contain "access_token" key,
- an error response would contain "error" and usually "error_description".
"""
scopes = decorate_scope(scopes, self.client_id)
if not self.authority.is_adfs:
user_realm_result = self.authority.user_realm_discovery(username)
if user_realm_result.get("account_type") == "Federated":
return self._acquire_token_by_username_password_federated(
user_realm_result, username, password, scopes=scopes, **kwargs)
return self.client.obtain_token_by_username_password(
username, password, scope=scopes, **kwargs)
def _acquire_token_by_username_password_federated(
self, user_realm_result, username, password, scopes=None, **kwargs):
verify = kwargs.pop("verify", self.verify)
proxies = kwargs.pop("proxies", self.proxies)
wstrust_endpoint = {}
if user_realm_result.get("federation_metadata_url"):
wstrust_endpoint = mex_send_request(
user_realm_result["federation_metadata_url"],
verify=verify, proxies=proxies)
if wstrust_endpoint is None:
raise ValueError("Unable to find wstrust endpoint from MEX. "
"This typically happens when attempting MSA accounts. "
"More details available here. "
"https://github.com/AzureAD/microsoft-authentication-library-for-python/wiki/Username-Password-Authentication")
logger.debug("wstrust_endpoint = %s", wstrust_endpoint)
wstrust_result = wst_send_request(
username, password, user_realm_result.get("cloud_audience_urn"),
wstrust_endpoint.get("address",
# Fallback to an AAD supplied endpoint
user_realm_result.get("federation_active_auth_url")),
wstrust_endpoint.get("action"), verify=verify, proxies=proxies)
if not ("token" in wstrust_result and "type" in wstrust_result):
raise RuntimeError("Unsuccessful RSTR. %s" % wstrust_result)
GRANT_TYPE_SAML1_1 = 'urn:ietf:params:oauth:grant-type:saml1_1-bearer'
grant_type = {
SAML_TOKEN_TYPE_V1: GRANT_TYPE_SAML1_1,
SAML_TOKEN_TYPE_V2: self.client.GRANT_TYPE_SAML2,
WSS_SAML_TOKEN_PROFILE_V1_1: GRANT_TYPE_SAML1_1,
WSS_SAML_TOKEN_PROFILE_V2: self.client.GRANT_TYPE_SAML2
}.get(wstrust_result.get("type"))
if not grant_type:
raise RuntimeError(
"RSTR returned unknown token type: %s", wstrust_result.get("type"))
self.client.grant_assertion_encoders.setdefault( # Register a non-standard type
grant_type, self.client.encode_saml_assertion)
return self.client.obtain_token_by_assertion(
wstrust_result["token"], grant_type, scope=scopes, **kwargs)
class ConfidentialClientApplication(ClientApplication): # server-side web app
def acquire_token_for_client(self, scopes, **kwargs):
"""Acquires token from the service for the confidential client.
:param list[str] scopes: (Required)
Scopes requested to access a protected API (a resource).
:return: A dict representing the json response from AAD:
- A successful response would contain "access_token" key,
- an error response would contain "error" and usually "error_description".
"""
# TBD: force_refresh behavior
return self.client.obtain_token_for_client(
scope=scopes, # This grant flow requires no scope decoration
**kwargs)
def acquire_token_on_behalf_of(self, user_assertion, scopes, authority=None):
raise NotImplementedError()
| 49.547287 | 175 | 0.632486 | import time
try:
from urlparse import urljoin
except:
from urllib.parse import urljoin
import logging
import sys
import warnings
import requests
from .oauth2cli import Client, JwtAssertionCreator
from .authority import Authority
from .mex import send_request as mex_send_request
from .wstrust_request import send_request as wst_send_request
from .wstrust_response import *
from .token_cache import TokenCache
__version__ = "0.6.1"
logger = logging.getLogger(__name__)
def decorate_scope(
scopes, client_id,
reserved_scope=frozenset(['openid', 'profile', 'offline_access'])):
if not isinstance(scopes, (list, set, tuple)):
raise ValueError("The input scopes should be a list, tuple, or set")
scope_set = set(scopes)
if scope_set & reserved_scope:
raise ValueError(
"API does not accept {} value as user-provided scopes".format(
reserved_scope))
if client_id in scope_set:
if len(scope_set) > 1:
# We make developers pass their client id, so that they can express
# the intent that they want the token for themselves (their own
# app).
# If we do not restrict them to passing only client id then they
# could write code where they expect an id token but end up getting
# access_token.
raise ValueError("Client Id can only be provided as a single scope")
decorated = set(reserved_scope) # Make a writable copy
else:
decorated = scope_set | reserved_scope
return list(decorated)
def extract_certs(public_cert_content):
# Parses raw public certificate file contents and returns a list of strings
# Usage: headers = {"x5c": extract_certs(open("my_cert.pem").read())}
public_certificates = re.findall(
r'-----BEGIN CERTIFICATE-----(?P<cert_value>[^-]+)-----END CERTIFICATE-----',
public_cert_content, re.I)
if public_certificates:
return [cert.strip() for cert in public_certificates]
# The public cert tags are not found in the input,
# let's make best effort to exclude a private key pem file.
if "PRIVATE KEY" in public_cert_content:
raise ValueError(
"We expect your public key but detect a private key instead")
return [public_cert_content.strip()]
class ClientApplication(object):
def __init__(
self, client_id,
client_credential=None, authority=None, validate_authority=True,
token_cache=None,
verify=True, proxies=None, timeout=None,
client_claims=None):
self.client_id = client_id
self.client_credential = client_credential
self.client_claims = client_claims
self.verify = verify
self.proxies = proxies
self.timeout = timeout
self.authority = Authority(
authority or "https://login.microsoftonline.com/common/",
validate_authority, verify=verify, proxies=proxies, timeout=timeout)
self.token_cache = token_cache or TokenCache()
self.client = self._build_client(client_credential, self.authority)
self.authority_groups = None
def _build_client(self, client_credential, authority):
client_assertion = None
client_assertion_type = None
default_body = {"client_info": 1}
if isinstance(client_credential, dict):
assert ("private_key" in client_credential
and "thumbprint" in client_credential)
headers = {}
if 'public_certificate' in client_credential:
headers["x5c"] = extract_certs(client_credential['public_certificate'])
assertion = JwtAssertionCreator(
client_credential["private_key"], algorithm="RS256",
sha1_thumbprint=client_credential.get("thumbprint"), headers=headers)
client_assertion = assertion.create_regenerative_assertion(
audience=authority.token_endpoint, issuer=self.client_id,
additional_claims=self.client_claims or {})
client_assertion_type = Client.CLIENT_ASSERTION_TYPE_JWT
else:
default_body['client_secret'] = client_credential
server_configuration = {
"authorization_endpoint": authority.authorization_endpoint,
"token_endpoint": authority.token_endpoint,
"device_authorization_endpoint":
urljoin(authority.token_endpoint, "devicecode"),
}
return Client(
server_configuration,
self.client_id,
default_headers={
"x-client-sku": "MSAL.Python", "x-client-ver": __version__,
"x-client-os": sys.platform,
"x-client-cpu": "x64" if sys.maxsize > 2 ** 32 else "x86",
},
default_body=default_body,
client_assertion=client_assertion,
client_assertion_type=client_assertion_type,
on_obtaining_tokens=self.token_cache.add,
on_removing_rt=self.token_cache.remove_rt,
on_updating_rt=self.token_cache.update_rt,
verify=self.verify, proxies=self.proxies, timeout=self.timeout)
def get_authorization_request_url(
self,
scopes,
t=None,
state=None,
redirect_uri=None,
authority=None,
response_type="code",
**kwargs):
the_authority = Authority(
authority,
verify=self.verify, proxies=self.proxies, timeout=self.timeout,
) if authority else self.authority
client = Client(
{"authorization_endpoint": the_authority.authorization_endpoint},
self.client_id)
return client.build_auth_request_uri(
response_type="code",
redirect_uri=redirect_uri, state=state, login_hint=login_hint,
scope=decorate_scope(scopes, self.client_id),
)
def acquire_token_by_authorization_code(
self,
code,
scopes,
redirect_uri=None,
):
assert isinstance(scopes, list), "Invalid parameter type"
return self.client.obtain_token_by_authorization_code(
code, redirect_uri=redirect_uri,
data={"scope": decorate_scope(scopes, self.client_id)},
)
def get_accounts(self, username=None):
accounts = self._find_msal_accounts(environment=self.authority.instance)
if not accounts:
for alias in self._get_authority_aliases(self.authority.instance):
accounts = self._find_msal_accounts(environment=alias)
if accounts:
break
if username:
lowercase_username = username.lower()
accounts = [a for a in accounts
if a["username"].lower() == lowercase_username]
# Because in most cases Accounts and RTs co-exist.
# Even in the rare case when an RT is revoked and then removed,
# acquire_token_silent() would then yield no result,
# apps would fall back to other acquire methods. This is the standard pattern.
return accounts
def _find_msal_accounts(self, environment):
return [a for a in self.token_cache.find(
TokenCache.CredentialType.ACCOUNT, query={"environment": environment})
if a["authority_type"] in (
TokenCache.AuthorityType.ADFS, TokenCache.AuthorityType.MSSTS)]
def _get_authority_aliases(self, instance):
if not self.authority_groups:
resp = requests.get(
"https://login.microsoftonline.com/common/discovery/instance?api-version=1.1&authorization_endpoint=https://login.microsoftonline.com/common/oauth2/authorize",
headers={'Accept': 'application/json'},
verify=self.verify, proxies=self.proxies, timeout=self.timeout)
resp.raise_for_status()
self.authority_groups = [
set(group['aliases']) for group in resp.json()['metadata']]
for group in self.authority_groups:
if instance in group:
return [alias for alias in group if alias != instance]
return []
def remove_account(self, account):
self._forget_me(account)
def _sign_out(self, home_account):
# Remove all relevant RTs and ATs from token cache
owned_by_home_account = {
"environment": home_account["environment"],
"home_account_id": home_account["home_account_id"],} # realm-independent
app_metadata = self._get_app_metadata(home_account["environment"])
# Remove RTs/FRTs, and they are realm-independent
for rt in [rt for rt in self.token_cache.find(
TokenCache.CredentialType.REFRESH_TOKEN, query=owned_by_home_account)
# Do RT's app ownership check as a precaution, in case family apps
if rt["client_id"] == self.client_id or (
app_metadata.get("family_id")
and rt.get("family_id") == app_metadata["family_id"])
]:
self.token_cache.remove_rt(rt)
for at in self.token_cache.find( # Remove ATs
# Regardless of realm, b/c we've removed realm-independent RTs anyway
TokenCache.CredentialType.ACCESS_TOKEN, query=owned_by_home_account):
# we skip AT's app ownership check.
self.token_cache.remove_at(at)
def _forget_me(self, home_account):
# It implies signout, and then also remove all relevant accounts and IDTs
self._sign_out(home_account)
owned_by_home_account = {
"environment": home_account["environment"],
"home_account_id": home_account["home_account_id"],} # realm-independent
for idt in self.token_cache.find( # Remove IDTs, regardless of realm
TokenCache.CredentialType.ID_TOKEN, query=owned_by_home_account):
self.token_cache.remove_idt(idt)
for a in self.token_cache.find( # Remove Accounts, regardless of realm
TokenCache.CredentialType.ACCOUNT, query=owned_by_home_account):
self.token_cache.remove_account(a)
def acquire_token_silent(
self,
scopes, # type: List[str]
account, # type: Optional[Account]
authority=None, # See get_authorization_request_url()
force_refresh=False, # type: Optional[boolean]
**kwargs):
assert isinstance(scopes, list), "Invalid parameter type"
if authority:
warnings.warn("We haven't decided how/if this method will accept authority parameter")
result = self._acquire_token_silent_from_cache_and_possibly_refresh_it(
scopes, account, self.authority, **kwargs)
if result:
return result
for alias in self._get_authority_aliases(self.authority.instance):
the_authority = Authority(
"https://" + alias + "/" + self.authority.tenant,
validate_authority=False,
verify=self.verify, proxies=self.proxies, timeout=self.timeout)
result = self._acquire_token_silent_from_cache_and_possibly_refresh_it(
scopes, account, the_authority, **kwargs)
if result:
return result
def _acquire_token_silent_from_cache_and_possibly_refresh_it(
self,
scopes,
account,
authority,
force_refresh=False,
**kwargs):
if not force_refresh:
matches = self.token_cache.find(
self.token_cache.CredentialType.ACCESS_TOKEN,
target=scopes,
query={
"client_id": self.client_id,
"environment": authority.instance,
"realm": authority.tenant,
"home_account_id": (account or {}).get("home_account_id"),
})
now = time.time()
for entry in matches:
expires_in = int(entry["expires_on"]) - now
if expires_in < 5*60:
continue
logger.debug("Cache hit an AT")
return {
"access_token": entry["secret"],
"token_type": "Bearer",
"expires_in": int(expires_in),
}
return self._acquire_token_silent_by_finding_rt_belongs_to_me_or_my_family(
authority, decorate_scope(scopes, self.client_id), account,
**kwargs)
def _acquire_token_silent_by_finding_rt_belongs_to_me_or_my_family(
self, authority, scopes, account, **kwargs):
query = {
"environment": authority.instance,
"home_account_id": (account or {}).get("home_account_id"),
ata = self._get_app_metadata(authority.instance)
if not app_metadata:
# we'll rewrite this block, to support multiple families.
at = self._acquire_token_silent_by_finding_specific_refresh_token(
authority, scopes,
dict(query, family_id="1"),
rt_remover=lambda rt_item: None,
break_condition=lambda response:
"client_mismatch" in response.get("error_additional_info", []),
**kwargs)
if at:
return at
if app_metadata.get("family_id"):
at = self._acquire_token_silent_by_finding_specific_refresh_token(
authority, scopes, dict(query, family_id=app_metadata["family_id"]),
**kwargs)
if at:
return at
return self._acquire_token_silent_by_finding_specific_refresh_token(
authority, scopes, dict(query, client_id=self.client_id), **kwargs)
def _get_app_metadata(self, environment):
apps = self.token_cache.find(
TokenCache.CredentialType.APP_METADATA, query={
"environment": environment, "client_id": self.client_id})
return apps[0] if apps else {}
def _acquire_token_silent_by_finding_specific_refresh_token(
self, authority, scopes, query,
rt_remover=None, break_condition=lambda response: False, **kwargs):
matches = self.token_cache.find(
self.token_cache.CredentialType.REFRESH_TOKEN,
logger.debug("Found %d RTs matching %s", len(matches), query)
client = self._build_client(self.client_credential, authority)
for entry in matches:
logger.debug("Cache attempts an RT")
response = client.obtain_token_by_refresh_token(
entry, rt_getter=lambda token_item: token_item["secret"],
on_removing_rt=rt_remover or self.token_cache.remove_rt,
scope=scopes,
**kwargs)
if "error" not in response:
return response
logger.debug(
"Refresh failed. {error}: {error_description}".format(**response))
if break_condition(response):
break
class PublicClientApplication(ClientApplication):
def __init__(self, client_id, client_credential=None, **kwargs):
if client_credential is not None:
raise ValueError("Public Client should not possess credentials")
super(PublicClientApplication, self).__init__(
client_id, client_credential=None, **kwargs)
def initiate_device_flow(self, scopes=None, **kwargs):
return self.client.initiate_device_flow(
scope=decorate_scope(scopes or [], self.client_id),
**kwargs)
def acquire_token_by_device_flow(self, flow, **kwargs):
return self.client.obtain_token_by_device_flow(
flow,
data={"code": flow["device_code"]},
**kwargs)
def acquire_token_by_username_password(
self, username, password, scopes, **kwargs):
scopes = decorate_scope(scopes, self.client_id)
if not self.authority.is_adfs:
user_realm_result = self.authority.user_realm_discovery(username)
if user_realm_result.get("account_type") == "Federated":
return self._acquire_token_by_username_password_federated(
user_realm_result, username, password, scopes=scopes, **kwargs)
return self.client.obtain_token_by_username_password(
username, password, scope=scopes, **kwargs)
def _acquire_token_by_username_password_federated(
self, user_realm_result, username, password, scopes=None, **kwargs):
verify = kwargs.pop("verify", self.verify)
proxies = kwargs.pop("proxies", self.proxies)
wstrust_endpoint = {}
if user_realm_result.get("federation_metadata_url"):
wstrust_endpoint = mex_send_request(
user_realm_result["federation_metadata_url"],
verify=verify, proxies=proxies)
if wstrust_endpoint is None:
raise ValueError("Unable to find wstrust endpoint from MEX. "
"This typically happens when attempting MSA accounts. "
"More details available here. "
"https://github.com/AzureAD/microsoft-authentication-library-for-python/wiki/Username-Password-Authentication")
logger.debug("wstrust_endpoint = %s", wstrust_endpoint)
wstrust_result = wst_send_request(
username, password, user_realm_result.get("cloud_audience_urn"),
wstrust_endpoint.get("address",
user_realm_result.get("federation_active_auth_url")),
wstrust_endpoint.get("action"), verify=verify, proxies=proxies)
if not ("token" in wstrust_result and "type" in wstrust_result):
raise RuntimeError("Unsuccessful RSTR. %s" % wstrust_result)
GRANT_TYPE_SAML1_1 = 'urn:ietf:params:oauth:grant-type:saml1_1-bearer'
grant_type = {
SAML_TOKEN_TYPE_V1: GRANT_TYPE_SAML1_1,
SAML_TOKEN_TYPE_V2: self.client.GRANT_TYPE_SAML2,
WSS_SAML_TOKEN_PROFILE_V1_1: GRANT_TYPE_SAML1_1,
WSS_SAML_TOKEN_PROFILE_V2: self.client.GRANT_TYPE_SAML2
}.get(wstrust_result.get("type"))
if not grant_type:
raise RuntimeError(
"RSTR returned unknown token type: %s", wstrust_result.get("type"))
self.client.grant_assertion_encoders.setdefault(
grant_type, self.client.encode_saml_assertion)
return self.client.obtain_token_by_assertion(
wstrust_result["token"], grant_type, scope=scopes, **kwargs)
class ConfidentialClientApplication(ClientApplication):
def acquire_token_for_client(self, scopes, **kwargs):
return self.client.obtain_token_for_client(
scope=scopes,
**kwargs)
def acquire_token_on_behalf_of(self, user_assertion, scopes, authority=None):
raise NotImplementedError()
| true | true |
f7f92d7bbc0ba48633b173e01370fd92e948128d | 2,487 | py | Python | paver/path.py | timgates42/paver | 62fb3d8e32c3727777b3ff7d75ba1b9b75703027 | [
"BSD-3-Clause"
] | 270 | 2015-01-10T01:00:09.000Z | 2022-03-13T21:05:27.000Z | paver/path.py | timgates42/paver | 62fb3d8e32c3727777b3ff7d75ba1b9b75703027 | [
"BSD-3-Clause"
] | 84 | 2015-02-10T18:45:25.000Z | 2021-06-21T14:55:33.000Z | paver/path.py | timgates42/paver | 62fb3d8e32c3727777b3ff7d75ba1b9b75703027 | [
"BSD-3-Clause"
] | 37 | 2015-03-26T14:05:33.000Z | 2022-03-22T12:32:19.000Z | """
Wrapper around path.py to add dry run support and other paver integration.
"""
import functools
import os
from contextlib import contextmanager
import sys
if sys.version_info[0] == 3:
from paver.deps.path3 import path as _orig_path
else:
from paver.deps.path2 import path as _orig_path
from paver import tasks
__all__ = ['path', 'pushd']
@contextmanager
def pushd(dir):
'''A context manager for stepping into a directory and automatically coming
back to the previous one. The original directory is returned.
Usage is like this::
from paver.easy import *
@task
def my_task():
with pushd('new/directory') as old_dir:
...do stuff...
'''
old_dir = os.getcwd()
tasks.environment.info('cd %s' % dir)
os.chdir(dir)
try:
yield old_dir
tasks.environment.info('cd %s' % old_dir)
finally:
os.chdir(old_dir)
class path(_orig_path):
def chdir(self):
# compatability with the ancient path.py that had a .chdir() method
self.__enter__()
# This is used to prevent implementation details of dry'd functions from
# printing redundant information.
# In particular, foo_p methods usually call the foo method internally and
# we don't want to print that information twice.
# We can say that the former implies the latter and call it a day.
_silence_nested_calls = False
def _make_wrapper(name, func):
from paver.easy import dry
@functools.wraps(func)
def wrapper(*args, **kwds):
global _silence_nested_calls
msg = None
if not _silence_nested_calls:
msg = name + ' ' + ' '.join(map(repr, args))
try:
_silence_nested_calls = True
return dry(msg, func, *args, **kwds)
finally:
_silence_nested_calls = False
return wrapper
_METHOD_BLACKLIST = [
'rename', 'renames', 'mkdir', 'mkdir_p', 'makedirs', 'makedirs_p',
'rmdir', 'rmdir_p', 'removedirs', 'removedirs_p', 'touch',
'remove', 'remove_p', 'unlink', 'unlink_p', 'link', 'symlink',
'copyfile', 'copymode', 'copystat', 'copy', 'copy2', 'copytree',
'move', 'rmtree', 'rmtree_p',
# added atop of original dry run support
'chown', 'chmod', 'utime', 'write_bytes', 'write_lines', 'write_text'
]
for name in _METHOD_BLACKLIST:
if not hasattr(_orig_path, name):
continue
wrapper = _make_wrapper(name, getattr(_orig_path, name))
setattr(path, name, wrapper)
| 29.258824 | 79 | 0.6538 | import functools
import os
from contextlib import contextmanager
import sys
if sys.version_info[0] == 3:
from paver.deps.path3 import path as _orig_path
else:
from paver.deps.path2 import path as _orig_path
from paver import tasks
__all__ = ['path', 'pushd']
@contextmanager
def pushd(dir):
old_dir = os.getcwd()
tasks.environment.info('cd %s' % dir)
os.chdir(dir)
try:
yield old_dir
tasks.environment.info('cd %s' % old_dir)
finally:
os.chdir(old_dir)
class path(_orig_path):
def chdir(self):
self.__enter__()
# printing redundant information.
# In particular, foo_p methods usually call the foo method internally and
# we don't want to print that information twice.
_silence_nested_calls = False
def _make_wrapper(name, func):
from paver.easy import dry
@functools.wraps(func)
def wrapper(*args, **kwds):
global _silence_nested_calls
msg = None
if not _silence_nested_calls:
msg = name + ' ' + ' '.join(map(repr, args))
try:
_silence_nested_calls = True
return dry(msg, func, *args, **kwds)
finally:
_silence_nested_calls = False
return wrapper
_METHOD_BLACKLIST = [
'rename', 'renames', 'mkdir', 'mkdir_p', 'makedirs', 'makedirs_p',
'rmdir', 'rmdir_p', 'removedirs', 'removedirs_p', 'touch',
'remove', 'remove_p', 'unlink', 'unlink_p', 'link', 'symlink',
'copyfile', 'copymode', 'copystat', 'copy', 'copy2', 'copytree',
'move', 'rmtree', 'rmtree_p',
'chown', 'chmod', 'utime', 'write_bytes', 'write_lines', 'write_text'
]
for name in _METHOD_BLACKLIST:
if not hasattr(_orig_path, name):
continue
wrapper = _make_wrapper(name, getattr(_orig_path, name))
setattr(path, name, wrapper)
| true | true |
f7f92f16a0d81de0c0ec408c6ec977683965b962 | 116 | py | Python | todo/tasks/admin.py | vijay0707/ToDo-List-Django | 388b338bc1394b46fc826c737c58b5977ccc6716 | [
"MIT"
] | null | null | null | todo/tasks/admin.py | vijay0707/ToDo-List-Django | 388b338bc1394b46fc826c737c58b5977ccc6716 | [
"MIT"
] | null | null | null | todo/tasks/admin.py | vijay0707/ToDo-List-Django | 388b338bc1394b46fc826c737c58b5977ccc6716 | [
"MIT"
] | null | null | null | from django.contrib import admin
# Register your models here.
from .models import *
admin.site.register(Taskmodel) | 19.333333 | 32 | 0.793103 | from django.contrib import admin
from .models import *
admin.site.register(Taskmodel) | true | true |
f7f92f6cb89c32d1d993c838e48103ec401169d0 | 2,764 | py | Python | DQM/TrackingMonitorClient/python/TrackingClientConfig_Tier0_Cosmic_cff.py | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 6 | 2017-09-08T14:12:56.000Z | 2022-03-09T23:57:01.000Z | DQM/TrackingMonitorClient/python/TrackingClientConfig_Tier0_Cosmic_cff.py | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 545 | 2017-09-19T17:10:19.000Z | 2022-03-07T16:55:27.000Z | DQM/TrackingMonitorClient/python/TrackingClientConfig_Tier0_Cosmic_cff.py | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 14 | 2017-10-04T09:47:21.000Z | 2019-10-23T18:04:45.000Z | import FWCore.ParameterSet.Config as cms
from DQMServices.Core.DQMEDHarvester import DQMEDHarvester
# TrackingOfflineDQM (for Tier0 Harvesting Step) ####
trackingOfflineAnalyser = DQMEDHarvester("TrackingOfflineDQM",
GlobalStatusFilling = cms.untracked.int32(2),
UsedWithEDMtoMEConverter = cms.untracked.bool(True),
TopFolderName = cms.untracked.string("Tracking"),
TrackingGlobalQualityPSets = cms.VPSet(
cms.PSet(
QT = cms.string("Rate"),
dir = cms.string("TrackParameters/GeneralProperties"),
name = cms.string("NumberOfTracks_"),
),
cms.PSet(
QT = cms.string("Chi2"),
dir = cms.string("TrackParameters/GeneralProperties"),
name = cms.string("Chi2oNDF_"),
),
cms.PSet(
QT = cms.string("RecHits"),
dir = cms.string("TrackParameters/HitProperties"),
name = cms.string("NumberOfRecHitsPerTrack_"),
),
),
TrackingLSQualityPSets = cms.VPSet(
cms.PSet(
QT = cms.string("Rate"),
LSdir = cms.string("TrackParameters/GeneralProperties/LSanalysis"),
LSname = cms.string("NumberOfTracks_lumiFlag_"),
LSlowerCut = cms.double( -1.0 ),
LSupperCut = cms.double( 1.0 )
),
cms.PSet(
QT = cms.string("Chi2"),
LSdir = cms.string("TrackParameters/GeneralProperties/LSanalysis"),
LSname = cms.string("Chi2oNDF_lumiFlag_"),
LSlowerCut = cms.double( 0.0 ),
LSupperCut = cms.double( 25.0 )
),
cms.PSet(
QT = cms.string("RecHits"),
LSdir = cms.string("TrackParameters/GeneralProperties/LSanalysis"),
LSname = cms.string("NumberOfRecHitsPerTrack_lumiFlag_"),
LSlowerCut = cms.double( 3.0 ),
LSupperCut = cms.double( 35.0 )
),
)
)
from DQMServices.Core.DQMQualityTester import DQMQualityTester
trackingQTester = DQMQualityTester(
qtList = cms.untracked.FileInPath('DQM/TrackingMonitorClient/data/tracking_qualitytest_config_tier0_cosmic.xml'),
prescaleFactor = cms.untracked.int32(1),
getQualityTestsFromFile = cms.untracked.bool(True)
)
from DQM.TrackingMonitor.TrackEfficiencyClient_cfi import *
TrackEffClient.FolderName = 'Tracking/TrackParameters/TrackEfficiency'
TrackEffClient.AlgoName = 'CKFTk'
# Sequence
TrackingCosmicDQMClient = cms.Sequence(trackingQTester*trackingOfflineAnalyser*TrackEffClient)
| 42.523077 | 117 | 0.591172 | import FWCore.ParameterSet.Config as cms
from DQMServices.Core.DQMEDHarvester import DQMEDHarvester
fflineAnalyser = DQMEDHarvester("TrackingOfflineDQM",
GlobalStatusFilling = cms.untracked.int32(2),
UsedWithEDMtoMEConverter = cms.untracked.bool(True),
TopFolderName = cms.untracked.string("Tracking"),
TrackingGlobalQualityPSets = cms.VPSet(
cms.PSet(
QT = cms.string("Rate"),
dir = cms.string("TrackParameters/GeneralProperties"),
name = cms.string("NumberOfTracks_"),
),
cms.PSet(
QT = cms.string("Chi2"),
dir = cms.string("TrackParameters/GeneralProperties"),
name = cms.string("Chi2oNDF_"),
),
cms.PSet(
QT = cms.string("RecHits"),
dir = cms.string("TrackParameters/HitProperties"),
name = cms.string("NumberOfRecHitsPerTrack_"),
),
),
TrackingLSQualityPSets = cms.VPSet(
cms.PSet(
QT = cms.string("Rate"),
LSdir = cms.string("TrackParameters/GeneralProperties/LSanalysis"),
LSname = cms.string("NumberOfTracks_lumiFlag_"),
LSlowerCut = cms.double( -1.0 ),
LSupperCut = cms.double( 1.0 )
),
cms.PSet(
QT = cms.string("Chi2"),
LSdir = cms.string("TrackParameters/GeneralProperties/LSanalysis"),
LSname = cms.string("Chi2oNDF_lumiFlag_"),
LSlowerCut = cms.double( 0.0 ),
LSupperCut = cms.double( 25.0 )
),
cms.PSet(
QT = cms.string("RecHits"),
LSdir = cms.string("TrackParameters/GeneralProperties/LSanalysis"),
LSname = cms.string("NumberOfRecHitsPerTrack_lumiFlag_"),
LSlowerCut = cms.double( 3.0 ),
LSupperCut = cms.double( 35.0 )
),
)
)
from DQMServices.Core.DQMQualityTester import DQMQualityTester
trackingQTester = DQMQualityTester(
qtList = cms.untracked.FileInPath('DQM/TrackingMonitorClient/data/tracking_qualitytest_config_tier0_cosmic.xml'),
prescaleFactor = cms.untracked.int32(1),
getQualityTestsFromFile = cms.untracked.bool(True)
)
from DQM.TrackingMonitor.TrackEfficiencyClient_cfi import *
TrackEffClient.FolderName = 'Tracking/TrackParameters/TrackEfficiency'
TrackEffClient.AlgoName = 'CKFTk'
TrackingCosmicDQMClient = cms.Sequence(trackingQTester*trackingOfflineAnalyser*TrackEffClient)
| true | true |
f7f930962fb927dd80bf6bf81062fcff9591a9df | 3,586 | py | Python | setupext.py | matthewturk/yt_astro_analysis | 84689a6e3495938b2a2da98d1589ce79410f6393 | [
"BSD-3-Clause-Clear"
] | null | null | null | setupext.py | matthewturk/yt_astro_analysis | 84689a6e3495938b2a2da98d1589ce79410f6393 | [
"BSD-3-Clause-Clear"
] | null | null | null | setupext.py | matthewturk/yt_astro_analysis | 84689a6e3495938b2a2da98d1589ce79410f6393 | [
"BSD-3-Clause-Clear"
] | null | null | null | import contextlib
import glob
import os
import subprocess
import sys
import tempfile
from distutils import log
from distutils.ccompiler import new_compiler
from distutils.sysconfig import customize_compiler
from distutils.errors import CompileError, LinkError
CCODE = """
#include <omp.h>
#include <stdio.h>
int main() {
omp_set_num_threads(2);
#pragma omp parallel
printf("nthreads=%d\\n", omp_get_num_threads());
return 0;
}
"""
@contextlib.contextmanager
def stdchannel_redirected(stdchannel, dest_filename):
"""
A context manager to temporarily redirect stdout or stderr
e.g.:
with stdchannel_redirected(sys.stderr, os.devnull):
if compiler.has_function('clock_gettime', libraries=['rt']):
libraries.append('rt')
Code adapted from https://stackoverflow.com/a/17752455/1382869
"""
try:
oldstdchannel = os.dup(stdchannel.fileno())
dest_file = open(dest_filename, 'w')
os.dup2(dest_file.fileno(), stdchannel.fileno())
yield
finally:
if oldstdchannel is not None:
os.dup2(oldstdchannel, stdchannel.fileno())
if dest_file is not None:
dest_file.close()
def check_for_openmp():
"""Returns True if local setup supports OpenMP, False otherwise
Code adapted from astropy_helpers, originally written by Tom
Robitaille and Curtis McCully.
"""
# See https://bugs.python.org/issue25150
if sys.version_info[:3] == (3, 5, 0):
return False
# Create a temporary directory
ccompiler = new_compiler()
customize_compiler(ccompiler)
tmp_dir = tempfile.mkdtemp()
start_dir = os.path.abspath('.')
if os.name == 'nt':
# TODO: make this work with mingw
# AFAICS there's no easy way to get the compiler distutils
# will be using until compilation actually happens
compile_flag = '-openmp'
link_flag = ''
else:
compile_flag = '-fopenmp'
link_flag = '-fopenmp'
try:
os.chdir(tmp_dir)
with open('test_openmp.c', 'w') as f:
f.write(CCODE)
os.mkdir('objects')
# Compile, link, and run test program
with stdchannel_redirected(sys.stderr, os.devnull):
ccompiler.compile(['test_openmp.c'], output_dir='objects',
extra_postargs=[compile_flag])
ccompiler.link_executable(
glob.glob(os.path.join('objects', '*')), 'test_openmp',
extra_postargs=[link_flag])
output = subprocess.check_output('./test_openmp').decode(
sys.stdout.encoding or 'utf-8').splitlines()
if 'nthreads=' in output[0]:
nthreads = int(output[0].strip().split('=')[1])
if len(output) == nthreads:
using_openmp = True
else:
log.warn("Unexpected number of lines from output of test "
"OpenMP program (output was {0})".format(output))
using_openmp = False
else:
log.warn("Unexpected output from test OpenMP "
"program (output was {0})".format(output))
using_openmp = False
except (CompileError, LinkError):
using_openmp = False
finally:
os.chdir(start_dir)
if using_openmp:
log.warn("Using OpenMP to compile parallel extensions")
else:
log.warn("Unable to compile OpenMP test program so Cython\n"
"extensions will be compiled without parallel support")
return using_openmp
| 29.393443 | 74 | 0.621584 | import contextlib
import glob
import os
import subprocess
import sys
import tempfile
from distutils import log
from distutils.ccompiler import new_compiler
from distutils.sysconfig import customize_compiler
from distutils.errors import CompileError, LinkError
CCODE = """
#include <omp.h>
#include <stdio.h>
int main() {
omp_set_num_threads(2);
#pragma omp parallel
printf("nthreads=%d\\n", omp_get_num_threads());
return 0;
}
"""
@contextlib.contextmanager
def stdchannel_redirected(stdchannel, dest_filename):
try:
oldstdchannel = os.dup(stdchannel.fileno())
dest_file = open(dest_filename, 'w')
os.dup2(dest_file.fileno(), stdchannel.fileno())
yield
finally:
if oldstdchannel is not None:
os.dup2(oldstdchannel, stdchannel.fileno())
if dest_file is not None:
dest_file.close()
def check_for_openmp():
if sys.version_info[:3] == (3, 5, 0):
return False
ccompiler = new_compiler()
customize_compiler(ccompiler)
tmp_dir = tempfile.mkdtemp()
start_dir = os.path.abspath('.')
if os.name == 'nt':
# will be using until compilation actually happens
compile_flag = '-openmp'
link_flag = ''
else:
compile_flag = '-fopenmp'
link_flag = '-fopenmp'
try:
os.chdir(tmp_dir)
with open('test_openmp.c', 'w') as f:
f.write(CCODE)
os.mkdir('objects')
# Compile, link, and run test program
with stdchannel_redirected(sys.stderr, os.devnull):
ccompiler.compile(['test_openmp.c'], output_dir='objects',
extra_postargs=[compile_flag])
ccompiler.link_executable(
glob.glob(os.path.join('objects', '*')), 'test_openmp',
extra_postargs=[link_flag])
output = subprocess.check_output('./test_openmp').decode(
sys.stdout.encoding or 'utf-8').splitlines()
if 'nthreads=' in output[0]:
nthreads = int(output[0].strip().split('=')[1])
if len(output) == nthreads:
using_openmp = True
else:
log.warn("Unexpected number of lines from output of test "
"OpenMP program (output was {0})".format(output))
using_openmp = False
else:
log.warn("Unexpected output from test OpenMP "
"program (output was {0})".format(output))
using_openmp = False
except (CompileError, LinkError):
using_openmp = False
finally:
os.chdir(start_dir)
if using_openmp:
log.warn("Using OpenMP to compile parallel extensions")
else:
log.warn("Unable to compile OpenMP test program so Cython\n"
"extensions will be compiled without parallel support")
return using_openmp
| true | true |
f7f930c810d1f3ae8287bd83a4ffe65d1eff6ff1 | 23,888 | py | Python | odps/df/backends/odpssql/codegen.py | jhhjwei/aliyun-odps-python-sdk | 9372024ef358674b17253ef716d50ad02c2af23e | [
"Apache-2.0"
] | null | null | null | odps/df/backends/odpssql/codegen.py | jhhjwei/aliyun-odps-python-sdk | 9372024ef358674b17253ef716d50ad02c2af23e | [
"Apache-2.0"
] | null | null | null | odps/df/backends/odpssql/codegen.py | jhhjwei/aliyun-odps-python-sdk | 9372024ef358674b17253ef716d50ad02c2af23e | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 1999-2017 Alibaba Group Holding 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 base64
import os
import sys
import platform
import uuid
from .types import df_type_to_odps_type
from ...expr.collections import RowAppliedCollectionExpr
from ...expr.element import MappedExpr
from ...expr.reduction import Aggregation, GroupedAggregation
from ...expr.utils import get_executed_collection_table_name
from ...utils import make_copy
from ....config import options
from ....lib import cloudpickle
from ....compat import OrderedDict, six, PY26, PY27
from ....models import FileResource, TableResource, ArchiveResource
from ....utils import to_str, hashable
dirname = os.path.dirname(os.path.abspath(cloudpickle.__file__))
CLOUD_PICKLE_FILE = os.path.join(dirname, 'cloudpickle.py')
with open(CLOUD_PICKLE_FILE) as f:
CLOUD_PICKLE = f.read()
IMPORT_FILE = os.path.join(dirname, 'importer.py')
with open(IMPORT_FILE) as f:
MEM_IMPORT = f.read()
CLIENT_IMPL = '(%d, %d, "%s")' % (sys.version_info[0],
sys.version_info[1],
platform.python_implementation().lower())
X_NAMED_TUPLE_FILE = os.path.join(dirname, 'xnamedtuple.py')
with open(X_NAMED_TUPLE_FILE) as f:
X_NAMED_TUPLE = f.read()
UDF_TMPL_HEADER = '''\
%(cloudpickle)s
%(memimport)s
%(xnamedtuple)s
import base64
import inspect
import time
import os
import sys
try:
import numpy
except ImportError:
pass
from odps.udf import annotate
from odps.distcache import get_cache_file, get_cache_table, get_cache_archive
try:
import socket
except ImportError:
class MockSocketModule(object):
_GLOBAL_DEFAULT_TIMEOUT = object()
def __getattr__(self, item):
raise AttributeError('Accessing attribute `{0}` of module `socket` is prohibited by sandbox.'.format(item))
sys.modules['socket'] = MockSocketModule()
def gen_resource_data(fields, tb):
named_args = xnamedtuple('NamedArgs', fields)
for args in tb:
yield named_args(*args)
def read_lib(lib, f):
if isinstance(f, list):
return dict((os.path.normpath(fo.name), fo) for fo in f)
if lib.endswith('.zip') or lib.endswith('.egg') or lib.endswith('.whl'):
return zipfile.ZipFile(f)
if lib.endswith('.tar') or lib.endswith('.tar.gz') or lib.endswith('.tar.bz2'):
from io import BytesIO
if lib.endswith('.tar'):
mode = 'r'
else:
mode = 'r:gz' if lib.endswith('.tar.gz') else 'r:bz2'
return tarfile.open(fileobj=BytesIO(f.read()), mode=mode)
raise ValueError(
'Unknown library type which should be one of zip(egg, wheel), tar, or tar.gz')
''' % {
'cloudpickle': CLOUD_PICKLE,
'memimport': MEM_IMPORT,
'xnamedtuple': X_NAMED_TUPLE,
}
UDF_TMPL = '''
@annotate('%(from_type)s->%(to_type)s')
class %(func_cls_name)s(object):
def __init__(self):
unpickler_kw = dict(impl=%(implementation)s, dump_code=%(dump_code)s)
rs = loads(base64.b64decode('%(resources)s'), **unpickler_kw)
resources = []
for t, n, fields in rs:
if t == 'file':
resources.append(get_cache_file(str(n)))
elif t == 'archive':
resources.append(get_cache_archive(str(n)))
else:
tb = get_cache_table(str(n))
if fields:
tb = gen_resource_data(fields, tb)
resources.append(tb)
encoded = '%(func_str)s'
f_str = base64.b64decode(encoded)
self.f = loads(f_str, **unpickler_kw)
if inspect.isclass(self.f):
if resources:
self.f = self.f(resources)
else:
self.f = self.f()
else:
if resources:
self.f = self.f(resources)
self.names = tuple(it for it in '%(names_str)s'.split(',') if it)
if self.names:
self.named_args = xnamedtuple('NamedArgs', self.names)
encoded_func_args = '%(func_args_str)s'
func_args_str = base64.b64decode(encoded_func_args)
self.args = loads(func_args_str, **unpickler_kw) or tuple()
encoded_func_kwargs = '%(func_kwargs_str)s'
func_kwargs_str = base64.b64decode(encoded_func_kwargs)
self.kwargs = loads(func_kwargs_str, **unpickler_kw) or dict()
self.from_types = '%(raw_from_type)s'.split(',')
self.to_type = '%(to_type)s'
libraries = (l for l in '%(libraries)s'.split(',') if len(l) > 0)
files = []
for lib in libraries:
if lib.startswith('a:'):
lib = lib[2:]
f = get_cache_archive(lib)
else:
f = get_cache_file(lib)
files.append(read_lib(lib, f))
sys.meta_path.append(CompressImporter(*files))
def _handle_input(self, args):
from datetime import datetime
from decimal import Decimal
res = []
for t, arg in zip(self.from_types, args):
if t == 'datetime' and arg is not None and not isinstance(arg, datetime):
res.append(datetime.fromtimestamp(arg / 1000.0))
elif t == 'decimal' and arg is not None and isinstance(arg, str):
res.append(Decimal(arg))
else:
res.append(arg)
return res
def _to_milliseconds(self, dt):
return int((time.mktime(dt.timetuple()) + dt.microsecond/1000000.0) * 1000)
def _handle_output(self, arg):
from datetime import datetime
from decimal import Decimal
t = self.to_type
if t == 'datetime' and isinstance(arg, datetime):
return self._to_milliseconds(arg)
elif t == 'string' and isinstance(arg, Decimal):
return str(arg)
else:
return arg
def evaluate(self, %(input_args)s):
args = %(input_args)s,
args = self._handle_input(args)
if not self.names:
args = tuple(args) + tuple(self.args)
res = self.f(*args, **self.kwargs)
return self._handle_output(res)
else:
res = self.f(self.named_args(*args), *self.args, **self.kwargs)
return self._handle_output(res)
'''
UDTF_TMPL = '''
import functools
from odps.udf import BaseUDTF
PY2 = sys.version_info[0] == 2
if PY2:
string_type = unicode
else:
string_type = str
@annotate('%(from_type)s->%(to_type)s')
class %(func_cls_name)s(BaseUDTF):
def __init__(self):
unpickler_kw = dict(impl=%(implementation)s, dump_code=%(dump_code)s)
rs = loads(base64.b64decode('%(resources)s'), **unpickler_kw)
resources = []
for t, n, fields in rs:
if t == 'file':
resources.append(get_cache_file(str(n)))
elif t == 'archive':
resources.append(get_cache_archive(str(n)))
else:
tb = get_cache_table(str(n))
if fields:
tb = gen_resource_data(fields, tb)
resources.append(tb)
encoded = '%(func_str)s'
f_str = base64.b64decode(encoded)
self.f = loads(f_str, **unpickler_kw)
if inspect.isclass(self.f):
if not resources:
self.f = self.f()
else:
self.f = self.f(resources)
self.is_f_generator = inspect.isgeneratorfunction(self.f.__call__)
self.close_f = getattr(self.f, 'close', None)
self.is_close_f_generator = inspect.isgeneratorfunction(self.close_f)
else:
if resources:
self.f = self.f(resources)
if isinstance(self.f, functools.partial):
self.is_f_generator = inspect.isgeneratorfunction(self.f.func)
else:
self.is_f_generator = inspect.isgeneratorfunction(self.f)
self.close_f = None
self.is_close_f_generator = False
encoded_func_args = '%(func_args_str)s'
func_args_str = base64.b64decode(encoded_func_args)
self.args = loads(func_args_str, **unpickler_kw) or tuple()
encoded_func_kwargs = '%(func_kwargs_str)s'
func_kwargs_str = base64.b64decode(encoded_func_kwargs)
self.kwargs = loads(func_kwargs_str, **unpickler_kw) or dict()
self.names = tuple(it for it in '%(names_str)s'.split(',') if it)
if self.names:
self.name_args = xnamedtuple('NamedArgs', self.names)
self.from_types = '%(raw_from_type)s'.split(',')
self.to_types = '%(to_type)s'.split(',')
libraries = (l for l in '%(libraries)s'.split(',') if len(l) > 0)
files = []
for lib in libraries:
if lib.startswith('a:'):
lib = lib[2:]
f = get_cache_archive(lib)
else:
f = get_cache_file(lib)
files.append(read_lib(lib, f))
sys.meta_path.append(CompressImporter(*files))
def _handle_input(self, args):
from datetime import datetime
from decimal import Decimal
res = []
for t, arg in zip(self.from_types, args):
if t == 'datetime' and arg is not None and not isinstance(arg, datetime):
res.append(datetime.fromtimestamp(arg / 1000.0))
elif t == 'decimal' and arg is not None and not isinstance(arg, Decimal):
res.append(Decimal(arg))
else:
res.append(arg)
return res
def _to_milliseconds(self, dt):
return int((time.mktime(dt.timetuple()) + dt.microsecond/1000000.0) * 1000)
def _handle_output(self, args):
from datetime import datetime
from decimal import Decimal
if len(self.to_types) != len(args):
raise ValueError('Function output size should be ' + str(len(self.to_types))
+ ', got ' + str(args))
res = []
for t, arg in zip(self.to_types, args):
if t == 'datetime' and isinstance(arg, datetime):
res.append(self._to_milliseconds(arg))
elif t == 'string' and isinstance(arg, Decimal):
res.append(str(arg))
elif PY2 and t == 'string' and isinstance(arg, string_type):
res.append(arg.encode('utf-8'))
else:
res.append(arg)
return res
def process(self, %(input_args)s):
args = %(input_args)s,
args = self._handle_input(args)
if not self.names:
args = tuple(args) + tuple(self.args)
else:
args = (self.name_args(*args), ) + tuple(self.args)
if self.is_f_generator:
for r in self.f(*args, **self.kwargs):
if not isinstance(r, (list, tuple)):
r = (r, )
self.forward(*self._handle_output(r))
else:
res = self.f(*args, **self.kwargs)
if res:
if not isinstance(res, (list, tuple)):
res = (res, )
self.forward(*self._handle_output(res))
def close(self):
if not self.close_f:
return
if self.is_close_f_generator:
for r in self.close_f(*self.args, **self.kwargs):
if not isinstance(r, (list, tuple)):
r = (r, )
self.forward(*self._handle_output(r))
else:
res = self.close_f(*self.args, **self.kwargs)
if res:
if not isinstance(res, (list, tuple)):
res = (res, )
self.forward(*self._handle_output(res))
'''
UDAF_TMPL = '''
from odps.udf import BaseUDAF
@annotate('%(from_type)s->%(to_type)s')
class %(func_cls_name)s(BaseUDAF):
def __init__(self):
unpickler_kw = dict(impl=%(implementation)s, dump_code=%(dump_code)s)
rs = loads(base64.b64decode('%(resources)s'), **unpickler_kw)
resources = []
for t, n, fields in rs:
if t == 'file':
resources.append(get_cache_file(str(n)))
elif t == 'archive':
resources.append(get_cache_archive(str(n)))
else:
tb = get_cache_table(str(n))
if fields:
tb = gen_resource_data(fields, tb)
resources.append(tb)
encoded_func_args = '%(func_args_str)s'
func_args_str = base64.b64decode(encoded_func_args)
args = loads(func_args_str, **unpickler_kw) or tuple()
encoded_func_kwargs = '%(func_kwargs_str)s'
func_kwargs_str = base64.b64decode(encoded_func_kwargs)
kwargs = loads(func_kwargs_str, **unpickler_kw) or dict()
encoded = '%(func_str)s'
f_str = base64.b64decode(encoded)
agg = loads(f_str, **unpickler_kw)
if resources:
if not args and not kwargs:
self.f = agg(resources)
else:
kwargs['resources'] = resources
self.f = agg(*args, **kwargs)
else:
self.f = agg(*args, **kwargs)
self.from_types = '%(raw_from_type)s'.split(',')
self.to_type = '%(to_type)s'
libraries = (l for l in '%(libraries)s'.split(',') if len(l) > 0)
files = []
for lib in libraries:
if lib.startswith('a:'):
lib = lib[2:]
f = get_cache_archive(lib)
else:
f = get_cache_file(lib)
files.append(read_lib(lib, f))
sys.meta_path.append(CompressImporter(*files))
def _handle_input(self, args):
from datetime import datetime
from decimal import Decimal
res = []
for t, arg in zip(self.from_types, args):
if t == 'datetime' and arg is not None and not isinstance(arg, datetime):
res.append(datetime.fromtimestamp(arg / 1000.0))
elif t == 'decimal' and arg is not None and not isinstance(arg, Decimal):
res.append(Decimal(arg))
else:
res.append(arg)
return res
def _to_milliseconds(self, dt):
return int((time.mktime(dt.timetuple()) + dt.microsecond/1000000.0) * 1000)
def _handle_output(self, arg):
from datetime import datetime
from decimal import Decimal
t = self.to_type
if t == 'datetime' and isinstance(arg, datetime):
return self._to_milliseconds(arg)
elif t == 'string' and isinstance(arg, Decimal):
return str(arg)
else:
return arg
def new_buffer(self):
return self.f.buffer()
def iterate(self, buffer, %(input_args)s):
args = %(input_args)s,
args = self._handle_input(args)
self.f(buffer, *args)
def merge(self, buffer, pbuffer):
self.f.merge(buffer, pbuffer)
def terminate(self, buffer):
res = self.f.getvalue(buffer)
return self._handle_output(res)
'''
def _gen_map_udf(node, func_cls_name, libraries, func, resources,
func_to_udfs, func_to_resources, func_params):
names_str = ''
if isinstance(node, MappedExpr) and node._multiple and \
all(f.name is not None for f in node.inputs):
names_str = ','.join(f.name for f in node.inputs)
from_type = ','.join(df_type_to_odps_type(t).name for t in node.input_types)
to_type = df_type_to_odps_type(node.dtype).name
raw_from_type = ','.join(df_type_to_odps_type(t).name for t in node.raw_input_types)
func_args_str = to_str(
base64.b64encode(cloudpickle.dumps(node._func_args, dump_code=options.df.dump_udf)))
func_kwargs_str = to_str(
base64.b64encode(cloudpickle.dumps(node._func_kwargs, dump_code=options.df.dump_udf)))
key = (from_type, to_type, func, tuple(resources), names_str, func_args_str, func_kwargs_str)
if key in func_params:
return
else:
if func in func_to_udfs:
func = make_copy(func)
node.func = func
func_params.add(key)
func_to_udfs[func] = UDF_TMPL_HEADER + UDF_TMPL % {
'raw_from_type': raw_from_type,
'from_type': from_type,
'to_type': to_type,
'func_cls_name': func_cls_name,
'func_str': to_str(base64.b64encode(cloudpickle.dumps(func, dump_code=options.df.dump_udf))),
'func_args_str': func_args_str,
'func_kwargs_str': func_kwargs_str,
'names_str': names_str,
'resources': to_str(
base64.b64encode(cloudpickle.dumps([r[:3] for r in resources], dump_code=options.df.dump_udf))),
'implementation': CLIENT_IMPL,
'dump_code': options.df.dump_udf,
'input_args': ', '.join('arg{0}'.format(i) for i in range(len(node.input_types))),
'libraries': ','.join(libraries if libraries is not None else []),
}
if resources:
func_to_resources[func] = resources
def _gen_apply_udf(node, func_cls_name, libraries, func, resources,
func_to_udfs, func_to_resources, func_params):
names_str = ','.join(f.name for f in node.fields)
from_type = ','.join(df_type_to_odps_type(t).name for t in node.input_types)
raw_from_type = ','.join(df_type_to_odps_type(t).name for t in node.raw_input_types)
to_type = ','.join(df_type_to_odps_type(t).name for t in node.schema.types)
func_args_str = to_str(
base64.b64encode(cloudpickle.dumps(node._func_args, dump_code=options.df.dump_udf)))
func_kwargs_str = to_str(
base64.b64encode(cloudpickle.dumps(node._func_kwargs, dump_code=options.df.dump_udf)))
key = (from_type, to_type, func, tuple(resources), names_str, func_args_str, func_kwargs_str)
if key in func_params:
return
else:
if func in func_to_udfs:
func = make_copy(func)
node.func = func
func_params.add(key)
func_to_udfs[func] = UDF_TMPL_HEADER + UDTF_TMPL % {
'raw_from_type': raw_from_type,
'from_type': from_type,
'to_type': to_type,
'func_cls_name': func_cls_name,
'func_str': to_str(base64.b64encode(cloudpickle.dumps(func, dump_code=options.df.dump_udf))),
'func_args_str': func_args_str,
'func_kwargs_str': func_kwargs_str,
'close_func_str': to_str(
base64.b64encode(cloudpickle.dumps(getattr(node, '_close_func', None), dump_code=options.df.dump_udf))),
'names_str': names_str,
'resources': to_str(base64.b64encode(cloudpickle.dumps([r[:3] for r in resources]))),
'implementation': CLIENT_IMPL,
'dump_code': options.df.dump_udf,
'input_args': ', '.join('arg{0}'.format(i) for i in range(len(node.input_types))),
'libraries': ','.join(libraries if libraries is not None else []),
}
if resources:
func_to_resources[func] = resources
def _gen_agg_udf(node, func_cls_name, libraries, func, resources,
func_to_udfs, func_to_resources, func_params):
from_type = ','.join(df_type_to_odps_type(t).name for t in node.input_types)
raw_from_type = ','.join(df_type_to_odps_type(t).name for t in node.raw_input_types)
to_type = df_type_to_odps_type(node.dtype).name
func_args_str = to_str(
base64.b64encode(cloudpickle.dumps(node._func_args, dump_code=options.df.dump_udf)))
func_kwargs_str = to_str(
base64.b64encode(cloudpickle.dumps(node._func_kwargs, dump_code=options.df.dump_udf)))
key = (from_type, to_type, func, tuple(resources), func_args_str, func_kwargs_str)
if key in func_params:
return
else:
if func in func_to_udfs:
func = make_copy(func)
node.func = func
func_params.add(key)
func_to_udfs[func] = UDF_TMPL_HEADER + UDAF_TMPL % {
'raw_from_type': raw_from_type,
'from_type': from_type,
'to_type': to_type,
'func_cls_name': func_cls_name,
'func_str': to_str(base64.b64encode(cloudpickle.dumps(func, dump_code=options.df.dump_udf))),
'func_args_str': func_args_str,
'func_kwargs_str': func_kwargs_str,
'resources': to_str(
base64.b64encode(cloudpickle.dumps([r[:3] for r in resources], dump_code=options.df.dump_udf))),
'implementation': CLIENT_IMPL,
'dump_code': options.df.dump_udf,
'input_args': ', '.join('arg{0}'.format(i) for i in range(len(node.input_types))),
'libraries': ','.join(libraries if libraries is not None else []),
}
if resources:
func_to_resources[func] = resources
def gen_udf(expr, func_cls_name=None, libraries=None):
func_to_udfs = OrderedDict()
func_to_resources = OrderedDict()
func_params = set()
if libraries is not None:
def _get_library_name(res):
if isinstance(res, six.string_types):
return res
elif isinstance(res, ArchiveResource):
return 'a:' + res.name
else:
return res.name
libraries = [_get_library_name(lib) for lib in libraries]
for node in expr.traverse(unique=True):
func = getattr(node, 'func', None)
if func is None:
continue
if isinstance(func, six.string_types):
continue
resources = []
collection_idx = 0
if hasattr(node, '_resources') and node._resources:
for res in node._resources:
if isinstance(res, ArchiveResource):
tp = 'archive'
name = res.name
fields = None
create = False
table_name = None
elif isinstance(res, FileResource):
tp = 'file'
name = res.name
fields = None
create = False
table_name = None
elif isinstance(res, TableResource):
tp = 'table'
name = res.name
fields = tuple(col.name for col in res.get_source_table().schema.columns)
create = False
table_name = None
else:
res = node._collection_resources[collection_idx]
collection_idx += 1
tp = 'table'
name = 'tmp_pyodps_resource_%s' % (uuid.uuid4())
fields = tuple(res.schema.names)
create = True
table_name = get_executed_collection_table_name(res)
resources.append((tp, name, fields, create, table_name))
if isinstance(node, MappedExpr):
_gen_map_udf(node, func_cls_name, libraries, func, resources,
func_to_udfs, func_to_resources, func_params)
elif isinstance(node, RowAppliedCollectionExpr):
_gen_apply_udf(node, func_cls_name, libraries, func, resources,
func_to_udfs, func_to_resources, func_params)
elif isinstance(node, (Aggregation, GroupedAggregation)):
_gen_agg_udf(node, func_cls_name, libraries, func, resources,
func_to_udfs, func_to_resources, func_params)
return func_to_udfs, func_to_resources
| 36.470229 | 119 | 0.59712 |
import base64
import os
import sys
import platform
import uuid
from .types import df_type_to_odps_type
from ...expr.collections import RowAppliedCollectionExpr
from ...expr.element import MappedExpr
from ...expr.reduction import Aggregation, GroupedAggregation
from ...expr.utils import get_executed_collection_table_name
from ...utils import make_copy
from ....config import options
from ....lib import cloudpickle
from ....compat import OrderedDict, six, PY26, PY27
from ....models import FileResource, TableResource, ArchiveResource
from ....utils import to_str, hashable
dirname = os.path.dirname(os.path.abspath(cloudpickle.__file__))
CLOUD_PICKLE_FILE = os.path.join(dirname, 'cloudpickle.py')
with open(CLOUD_PICKLE_FILE) as f:
CLOUD_PICKLE = f.read()
IMPORT_FILE = os.path.join(dirname, 'importer.py')
with open(IMPORT_FILE) as f:
MEM_IMPORT = f.read()
CLIENT_IMPL = '(%d, %d, "%s")' % (sys.version_info[0],
sys.version_info[1],
platform.python_implementation().lower())
X_NAMED_TUPLE_FILE = os.path.join(dirname, 'xnamedtuple.py')
with open(X_NAMED_TUPLE_FILE) as f:
X_NAMED_TUPLE = f.read()
UDF_TMPL_HEADER = '''\
%(cloudpickle)s
%(memimport)s
%(xnamedtuple)s
import base64
import inspect
import time
import os
import sys
try:
import numpy
except ImportError:
pass
from odps.udf import annotate
from odps.distcache import get_cache_file, get_cache_table, get_cache_archive
try:
import socket
except ImportError:
class MockSocketModule(object):
_GLOBAL_DEFAULT_TIMEOUT = object()
def __getattr__(self, item):
raise AttributeError('Accessing attribute `{0}` of module `socket` is prohibited by sandbox.'.format(item))
sys.modules['socket'] = MockSocketModule()
def gen_resource_data(fields, tb):
named_args = xnamedtuple('NamedArgs', fields)
for args in tb:
yield named_args(*args)
def read_lib(lib, f):
if isinstance(f, list):
return dict((os.path.normpath(fo.name), fo) for fo in f)
if lib.endswith('.zip') or lib.endswith('.egg') or lib.endswith('.whl'):
return zipfile.ZipFile(f)
if lib.endswith('.tar') or lib.endswith('.tar.gz') or lib.endswith('.tar.bz2'):
from io import BytesIO
if lib.endswith('.tar'):
mode = 'r'
else:
mode = 'r:gz' if lib.endswith('.tar.gz') else 'r:bz2'
return tarfile.open(fileobj=BytesIO(f.read()), mode=mode)
raise ValueError(
'Unknown library type which should be one of zip(egg, wheel), tar, or tar.gz')
''' % {
'cloudpickle': CLOUD_PICKLE,
'memimport': MEM_IMPORT,
'xnamedtuple': X_NAMED_TUPLE,
}
UDF_TMPL = '''
@annotate('%(from_type)s->%(to_type)s')
class %(func_cls_name)s(object):
def __init__(self):
unpickler_kw = dict(impl=%(implementation)s, dump_code=%(dump_code)s)
rs = loads(base64.b64decode('%(resources)s'), **unpickler_kw)
resources = []
for t, n, fields in rs:
if t == 'file':
resources.append(get_cache_file(str(n)))
elif t == 'archive':
resources.append(get_cache_archive(str(n)))
else:
tb = get_cache_table(str(n))
if fields:
tb = gen_resource_data(fields, tb)
resources.append(tb)
encoded = '%(func_str)s'
f_str = base64.b64decode(encoded)
self.f = loads(f_str, **unpickler_kw)
if inspect.isclass(self.f):
if resources:
self.f = self.f(resources)
else:
self.f = self.f()
else:
if resources:
self.f = self.f(resources)
self.names = tuple(it for it in '%(names_str)s'.split(',') if it)
if self.names:
self.named_args = xnamedtuple('NamedArgs', self.names)
encoded_func_args = '%(func_args_str)s'
func_args_str = base64.b64decode(encoded_func_args)
self.args = loads(func_args_str, **unpickler_kw) or tuple()
encoded_func_kwargs = '%(func_kwargs_str)s'
func_kwargs_str = base64.b64decode(encoded_func_kwargs)
self.kwargs = loads(func_kwargs_str, **unpickler_kw) or dict()
self.from_types = '%(raw_from_type)s'.split(',')
self.to_type = '%(to_type)s'
libraries = (l for l in '%(libraries)s'.split(',') if len(l) > 0)
files = []
for lib in libraries:
if lib.startswith('a:'):
lib = lib[2:]
f = get_cache_archive(lib)
else:
f = get_cache_file(lib)
files.append(read_lib(lib, f))
sys.meta_path.append(CompressImporter(*files))
def _handle_input(self, args):
from datetime import datetime
from decimal import Decimal
res = []
for t, arg in zip(self.from_types, args):
if t == 'datetime' and arg is not None and not isinstance(arg, datetime):
res.append(datetime.fromtimestamp(arg / 1000.0))
elif t == 'decimal' and arg is not None and isinstance(arg, str):
res.append(Decimal(arg))
else:
res.append(arg)
return res
def _to_milliseconds(self, dt):
return int((time.mktime(dt.timetuple()) + dt.microsecond/1000000.0) * 1000)
def _handle_output(self, arg):
from datetime import datetime
from decimal import Decimal
t = self.to_type
if t == 'datetime' and isinstance(arg, datetime):
return self._to_milliseconds(arg)
elif t == 'string' and isinstance(arg, Decimal):
return str(arg)
else:
return arg
def evaluate(self, %(input_args)s):
args = %(input_args)s,
args = self._handle_input(args)
if not self.names:
args = tuple(args) + tuple(self.args)
res = self.f(*args, **self.kwargs)
return self._handle_output(res)
else:
res = self.f(self.named_args(*args), *self.args, **self.kwargs)
return self._handle_output(res)
'''
UDTF_TMPL = '''
import functools
from odps.udf import BaseUDTF
PY2 = sys.version_info[0] == 2
if PY2:
string_type = unicode
else:
string_type = str
@annotate('%(from_type)s->%(to_type)s')
class %(func_cls_name)s(BaseUDTF):
def __init__(self):
unpickler_kw = dict(impl=%(implementation)s, dump_code=%(dump_code)s)
rs = loads(base64.b64decode('%(resources)s'), **unpickler_kw)
resources = []
for t, n, fields in rs:
if t == 'file':
resources.append(get_cache_file(str(n)))
elif t == 'archive':
resources.append(get_cache_archive(str(n)))
else:
tb = get_cache_table(str(n))
if fields:
tb = gen_resource_data(fields, tb)
resources.append(tb)
encoded = '%(func_str)s'
f_str = base64.b64decode(encoded)
self.f = loads(f_str, **unpickler_kw)
if inspect.isclass(self.f):
if not resources:
self.f = self.f()
else:
self.f = self.f(resources)
self.is_f_generator = inspect.isgeneratorfunction(self.f.__call__)
self.close_f = getattr(self.f, 'close', None)
self.is_close_f_generator = inspect.isgeneratorfunction(self.close_f)
else:
if resources:
self.f = self.f(resources)
if isinstance(self.f, functools.partial):
self.is_f_generator = inspect.isgeneratorfunction(self.f.func)
else:
self.is_f_generator = inspect.isgeneratorfunction(self.f)
self.close_f = None
self.is_close_f_generator = False
encoded_func_args = '%(func_args_str)s'
func_args_str = base64.b64decode(encoded_func_args)
self.args = loads(func_args_str, **unpickler_kw) or tuple()
encoded_func_kwargs = '%(func_kwargs_str)s'
func_kwargs_str = base64.b64decode(encoded_func_kwargs)
self.kwargs = loads(func_kwargs_str, **unpickler_kw) or dict()
self.names = tuple(it for it in '%(names_str)s'.split(',') if it)
if self.names:
self.name_args = xnamedtuple('NamedArgs', self.names)
self.from_types = '%(raw_from_type)s'.split(',')
self.to_types = '%(to_type)s'.split(',')
libraries = (l for l in '%(libraries)s'.split(',') if len(l) > 0)
files = []
for lib in libraries:
if lib.startswith('a:'):
lib = lib[2:]
f = get_cache_archive(lib)
else:
f = get_cache_file(lib)
files.append(read_lib(lib, f))
sys.meta_path.append(CompressImporter(*files))
def _handle_input(self, args):
from datetime import datetime
from decimal import Decimal
res = []
for t, arg in zip(self.from_types, args):
if t == 'datetime' and arg is not None and not isinstance(arg, datetime):
res.append(datetime.fromtimestamp(arg / 1000.0))
elif t == 'decimal' and arg is not None and not isinstance(arg, Decimal):
res.append(Decimal(arg))
else:
res.append(arg)
return res
def _to_milliseconds(self, dt):
return int((time.mktime(dt.timetuple()) + dt.microsecond/1000000.0) * 1000)
def _handle_output(self, args):
from datetime import datetime
from decimal import Decimal
if len(self.to_types) != len(args):
raise ValueError('Function output size should be ' + str(len(self.to_types))
+ ', got ' + str(args))
res = []
for t, arg in zip(self.to_types, args):
if t == 'datetime' and isinstance(arg, datetime):
res.append(self._to_milliseconds(arg))
elif t == 'string' and isinstance(arg, Decimal):
res.append(str(arg))
elif PY2 and t == 'string' and isinstance(arg, string_type):
res.append(arg.encode('utf-8'))
else:
res.append(arg)
return res
def process(self, %(input_args)s):
args = %(input_args)s,
args = self._handle_input(args)
if not self.names:
args = tuple(args) + tuple(self.args)
else:
args = (self.name_args(*args), ) + tuple(self.args)
if self.is_f_generator:
for r in self.f(*args, **self.kwargs):
if not isinstance(r, (list, tuple)):
r = (r, )
self.forward(*self._handle_output(r))
else:
res = self.f(*args, **self.kwargs)
if res:
if not isinstance(res, (list, tuple)):
res = (res, )
self.forward(*self._handle_output(res))
def close(self):
if not self.close_f:
return
if self.is_close_f_generator:
for r in self.close_f(*self.args, **self.kwargs):
if not isinstance(r, (list, tuple)):
r = (r, )
self.forward(*self._handle_output(r))
else:
res = self.close_f(*self.args, **self.kwargs)
if res:
if not isinstance(res, (list, tuple)):
res = (res, )
self.forward(*self._handle_output(res))
'''
UDAF_TMPL = '''
from odps.udf import BaseUDAF
@annotate('%(from_type)s->%(to_type)s')
class %(func_cls_name)s(BaseUDAF):
def __init__(self):
unpickler_kw = dict(impl=%(implementation)s, dump_code=%(dump_code)s)
rs = loads(base64.b64decode('%(resources)s'), **unpickler_kw)
resources = []
for t, n, fields in rs:
if t == 'file':
resources.append(get_cache_file(str(n)))
elif t == 'archive':
resources.append(get_cache_archive(str(n)))
else:
tb = get_cache_table(str(n))
if fields:
tb = gen_resource_data(fields, tb)
resources.append(tb)
encoded_func_args = '%(func_args_str)s'
func_args_str = base64.b64decode(encoded_func_args)
args = loads(func_args_str, **unpickler_kw) or tuple()
encoded_func_kwargs = '%(func_kwargs_str)s'
func_kwargs_str = base64.b64decode(encoded_func_kwargs)
kwargs = loads(func_kwargs_str, **unpickler_kw) or dict()
encoded = '%(func_str)s'
f_str = base64.b64decode(encoded)
agg = loads(f_str, **unpickler_kw)
if resources:
if not args and not kwargs:
self.f = agg(resources)
else:
kwargs['resources'] = resources
self.f = agg(*args, **kwargs)
else:
self.f = agg(*args, **kwargs)
self.from_types = '%(raw_from_type)s'.split(',')
self.to_type = '%(to_type)s'
libraries = (l for l in '%(libraries)s'.split(',') if len(l) > 0)
files = []
for lib in libraries:
if lib.startswith('a:'):
lib = lib[2:]
f = get_cache_archive(lib)
else:
f = get_cache_file(lib)
files.append(read_lib(lib, f))
sys.meta_path.append(CompressImporter(*files))
def _handle_input(self, args):
from datetime import datetime
from decimal import Decimal
res = []
for t, arg in zip(self.from_types, args):
if t == 'datetime' and arg is not None and not isinstance(arg, datetime):
res.append(datetime.fromtimestamp(arg / 1000.0))
elif t == 'decimal' and arg is not None and not isinstance(arg, Decimal):
res.append(Decimal(arg))
else:
res.append(arg)
return res
def _to_milliseconds(self, dt):
return int((time.mktime(dt.timetuple()) + dt.microsecond/1000000.0) * 1000)
def _handle_output(self, arg):
from datetime import datetime
from decimal import Decimal
t = self.to_type
if t == 'datetime' and isinstance(arg, datetime):
return self._to_milliseconds(arg)
elif t == 'string' and isinstance(arg, Decimal):
return str(arg)
else:
return arg
def new_buffer(self):
return self.f.buffer()
def iterate(self, buffer, %(input_args)s):
args = %(input_args)s,
args = self._handle_input(args)
self.f(buffer, *args)
def merge(self, buffer, pbuffer):
self.f.merge(buffer, pbuffer)
def terminate(self, buffer):
res = self.f.getvalue(buffer)
return self._handle_output(res)
'''
def _gen_map_udf(node, func_cls_name, libraries, func, resources,
func_to_udfs, func_to_resources, func_params):
names_str = ''
if isinstance(node, MappedExpr) and node._multiple and \
all(f.name is not None for f in node.inputs):
names_str = ','.join(f.name for f in node.inputs)
from_type = ','.join(df_type_to_odps_type(t).name for t in node.input_types)
to_type = df_type_to_odps_type(node.dtype).name
raw_from_type = ','.join(df_type_to_odps_type(t).name for t in node.raw_input_types)
func_args_str = to_str(
base64.b64encode(cloudpickle.dumps(node._func_args, dump_code=options.df.dump_udf)))
func_kwargs_str = to_str(
base64.b64encode(cloudpickle.dumps(node._func_kwargs, dump_code=options.df.dump_udf)))
key = (from_type, to_type, func, tuple(resources), names_str, func_args_str, func_kwargs_str)
if key in func_params:
return
else:
if func in func_to_udfs:
func = make_copy(func)
node.func = func
func_params.add(key)
func_to_udfs[func] = UDF_TMPL_HEADER + UDF_TMPL % {
'raw_from_type': raw_from_type,
'from_type': from_type,
'to_type': to_type,
'func_cls_name': func_cls_name,
'func_str': to_str(base64.b64encode(cloudpickle.dumps(func, dump_code=options.df.dump_udf))),
'func_args_str': func_args_str,
'func_kwargs_str': func_kwargs_str,
'names_str': names_str,
'resources': to_str(
base64.b64encode(cloudpickle.dumps([r[:3] for r in resources], dump_code=options.df.dump_udf))),
'implementation': CLIENT_IMPL,
'dump_code': options.df.dump_udf,
'input_args': ', '.join('arg{0}'.format(i) for i in range(len(node.input_types))),
'libraries': ','.join(libraries if libraries is not None else []),
}
if resources:
func_to_resources[func] = resources
def _gen_apply_udf(node, func_cls_name, libraries, func, resources,
func_to_udfs, func_to_resources, func_params):
names_str = ','.join(f.name for f in node.fields)
from_type = ','.join(df_type_to_odps_type(t).name for t in node.input_types)
raw_from_type = ','.join(df_type_to_odps_type(t).name for t in node.raw_input_types)
to_type = ','.join(df_type_to_odps_type(t).name for t in node.schema.types)
func_args_str = to_str(
base64.b64encode(cloudpickle.dumps(node._func_args, dump_code=options.df.dump_udf)))
func_kwargs_str = to_str(
base64.b64encode(cloudpickle.dumps(node._func_kwargs, dump_code=options.df.dump_udf)))
key = (from_type, to_type, func, tuple(resources), names_str, func_args_str, func_kwargs_str)
if key in func_params:
return
else:
if func in func_to_udfs:
func = make_copy(func)
node.func = func
func_params.add(key)
func_to_udfs[func] = UDF_TMPL_HEADER + UDTF_TMPL % {
'raw_from_type': raw_from_type,
'from_type': from_type,
'to_type': to_type,
'func_cls_name': func_cls_name,
'func_str': to_str(base64.b64encode(cloudpickle.dumps(func, dump_code=options.df.dump_udf))),
'func_args_str': func_args_str,
'func_kwargs_str': func_kwargs_str,
'close_func_str': to_str(
base64.b64encode(cloudpickle.dumps(getattr(node, '_close_func', None), dump_code=options.df.dump_udf))),
'names_str': names_str,
'resources': to_str(base64.b64encode(cloudpickle.dumps([r[:3] for r in resources]))),
'implementation': CLIENT_IMPL,
'dump_code': options.df.dump_udf,
'input_args': ', '.join('arg{0}'.format(i) for i in range(len(node.input_types))),
'libraries': ','.join(libraries if libraries is not None else []),
}
if resources:
func_to_resources[func] = resources
def _gen_agg_udf(node, func_cls_name, libraries, func, resources,
func_to_udfs, func_to_resources, func_params):
from_type = ','.join(df_type_to_odps_type(t).name for t in node.input_types)
raw_from_type = ','.join(df_type_to_odps_type(t).name for t in node.raw_input_types)
to_type = df_type_to_odps_type(node.dtype).name
func_args_str = to_str(
base64.b64encode(cloudpickle.dumps(node._func_args, dump_code=options.df.dump_udf)))
func_kwargs_str = to_str(
base64.b64encode(cloudpickle.dumps(node._func_kwargs, dump_code=options.df.dump_udf)))
key = (from_type, to_type, func, tuple(resources), func_args_str, func_kwargs_str)
if key in func_params:
return
else:
if func in func_to_udfs:
func = make_copy(func)
node.func = func
func_params.add(key)
func_to_udfs[func] = UDF_TMPL_HEADER + UDAF_TMPL % {
'raw_from_type': raw_from_type,
'from_type': from_type,
'to_type': to_type,
'func_cls_name': func_cls_name,
'func_str': to_str(base64.b64encode(cloudpickle.dumps(func, dump_code=options.df.dump_udf))),
'func_args_str': func_args_str,
'func_kwargs_str': func_kwargs_str,
'resources': to_str(
base64.b64encode(cloudpickle.dumps([r[:3] for r in resources], dump_code=options.df.dump_udf))),
'implementation': CLIENT_IMPL,
'dump_code': options.df.dump_udf,
'input_args': ', '.join('arg{0}'.format(i) for i in range(len(node.input_types))),
'libraries': ','.join(libraries if libraries is not None else []),
}
if resources:
func_to_resources[func] = resources
def gen_udf(expr, func_cls_name=None, libraries=None):
func_to_udfs = OrderedDict()
func_to_resources = OrderedDict()
func_params = set()
if libraries is not None:
def _get_library_name(res):
if isinstance(res, six.string_types):
return res
elif isinstance(res, ArchiveResource):
return 'a:' + res.name
else:
return res.name
libraries = [_get_library_name(lib) for lib in libraries]
for node in expr.traverse(unique=True):
func = getattr(node, 'func', None)
if func is None:
continue
if isinstance(func, six.string_types):
continue
resources = []
collection_idx = 0
if hasattr(node, '_resources') and node._resources:
for res in node._resources:
if isinstance(res, ArchiveResource):
tp = 'archive'
name = res.name
fields = None
create = False
table_name = None
elif isinstance(res, FileResource):
tp = 'file'
name = res.name
fields = None
create = False
table_name = None
elif isinstance(res, TableResource):
tp = 'table'
name = res.name
fields = tuple(col.name for col in res.get_source_table().schema.columns)
create = False
table_name = None
else:
res = node._collection_resources[collection_idx]
collection_idx += 1
tp = 'table'
name = 'tmp_pyodps_resource_%s' % (uuid.uuid4())
fields = tuple(res.schema.names)
create = True
table_name = get_executed_collection_table_name(res)
resources.append((tp, name, fields, create, table_name))
if isinstance(node, MappedExpr):
_gen_map_udf(node, func_cls_name, libraries, func, resources,
func_to_udfs, func_to_resources, func_params)
elif isinstance(node, RowAppliedCollectionExpr):
_gen_apply_udf(node, func_cls_name, libraries, func, resources,
func_to_udfs, func_to_resources, func_params)
elif isinstance(node, (Aggregation, GroupedAggregation)):
_gen_agg_udf(node, func_cls_name, libraries, func, resources,
func_to_udfs, func_to_resources, func_params)
return func_to_udfs, func_to_resources
| true | true |
f7f931130714c0aaaf7b480273806ac1243916e2 | 55,531 | py | Python | Lib/test/test_warnings/__init__.py | eendebakpt/cpython | 474fdbe9e4a2ff90ef39e8748da644c86a200981 | [
"0BSD"
] | 1 | 2020-09-28T16:41:16.000Z | 2020-09-28T16:41:16.000Z | Lib/test/test_warnings/__init__.py | eendebakpt/cpython | 474fdbe9e4a2ff90ef39e8748da644c86a200981 | [
"0BSD"
] | 2 | 2022-03-10T15:56:35.000Z | 2022-03-10T15:56:43.000Z | Lib/test/test_warnings/__init__.py | eendebakpt/cpython | 474fdbe9e4a2ff90ef39e8748da644c86a200981 | [
"0BSD"
] | null | null | null | from contextlib import contextmanager
import linecache
import os
from io import StringIO
import re
import sys
import textwrap
import unittest
from test import support
from test.support import import_helper
from test.support import os_helper
from test.support import warnings_helper
from test.support.script_helper import assert_python_ok, assert_python_failure
from test.test_warnings.data import stacklevel as warning_tests
import warnings as original_warnings
py_warnings = import_helper.import_fresh_module('warnings',
blocked=['_warnings'])
c_warnings = import_helper.import_fresh_module('warnings',
fresh=['_warnings'])
Py_DEBUG = hasattr(sys, 'gettotalrefcount')
@contextmanager
def warnings_state(module):
"""Use a specific warnings implementation in warning_tests."""
global __warningregistry__
for to_clear in (sys, warning_tests):
try:
to_clear.__warningregistry__.clear()
except AttributeError:
pass
try:
__warningregistry__.clear()
except NameError:
pass
original_warnings = warning_tests.warnings
original_filters = module.filters
try:
module.filters = original_filters[:]
module.simplefilter("once")
warning_tests.warnings = module
yield
finally:
warning_tests.warnings = original_warnings
module.filters = original_filters
class TestWarning(Warning):
pass
class BaseTest:
"""Basic bookkeeping required for testing."""
def setUp(self):
self.old_unittest_module = unittest.case.warnings
# The __warningregistry__ needs to be in a pristine state for tests
# to work properly.
if '__warningregistry__' in globals():
del globals()['__warningregistry__']
if hasattr(warning_tests, '__warningregistry__'):
del warning_tests.__warningregistry__
if hasattr(sys, '__warningregistry__'):
del sys.__warningregistry__
# The 'warnings' module must be explicitly set so that the proper
# interaction between _warnings and 'warnings' can be controlled.
sys.modules['warnings'] = self.module
# Ensure that unittest.TestCase.assertWarns() uses the same warnings
# module than warnings.catch_warnings(). Otherwise,
# warnings.catch_warnings() will be unable to remove the added filter.
unittest.case.warnings = self.module
super(BaseTest, self).setUp()
def tearDown(self):
sys.modules['warnings'] = original_warnings
unittest.case.warnings = self.old_unittest_module
super(BaseTest, self).tearDown()
class PublicAPITests(BaseTest):
"""Ensures that the correct values are exposed in the
public API.
"""
def test_module_all_attribute(self):
self.assertTrue(hasattr(self.module, '__all__'))
target_api = ["warn", "warn_explicit", "showwarning",
"formatwarning", "filterwarnings", "simplefilter",
"resetwarnings", "catch_warnings"]
self.assertSetEqual(set(self.module.__all__),
set(target_api))
class CPublicAPITests(PublicAPITests, unittest.TestCase):
module = c_warnings
class PyPublicAPITests(PublicAPITests, unittest.TestCase):
module = py_warnings
class FilterTests(BaseTest):
"""Testing the filtering functionality."""
def test_error(self):
with original_warnings.catch_warnings(module=self.module) as w:
self.module.resetwarnings()
self.module.filterwarnings("error", category=UserWarning)
self.assertRaises(UserWarning, self.module.warn,
"FilterTests.test_error")
def test_error_after_default(self):
with original_warnings.catch_warnings(module=self.module) as w:
self.module.resetwarnings()
message = "FilterTests.test_ignore_after_default"
def f():
self.module.warn(message, UserWarning)
with support.captured_stderr() as stderr:
f()
stderr = stderr.getvalue()
self.assertIn("UserWarning: FilterTests.test_ignore_after_default",
stderr)
self.assertIn("self.module.warn(message, UserWarning)",
stderr)
self.module.filterwarnings("error", category=UserWarning)
self.assertRaises(UserWarning, f)
def test_ignore(self):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.resetwarnings()
self.module.filterwarnings("ignore", category=UserWarning)
self.module.warn("FilterTests.test_ignore", UserWarning)
self.assertEqual(len(w), 0)
self.assertEqual(list(__warningregistry__), ['version'])
def test_ignore_after_default(self):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.resetwarnings()
message = "FilterTests.test_ignore_after_default"
def f():
self.module.warn(message, UserWarning)
f()
self.module.filterwarnings("ignore", category=UserWarning)
f()
f()
self.assertEqual(len(w), 1)
def test_always(self):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.resetwarnings()
self.module.filterwarnings("always", category=UserWarning)
message = "FilterTests.test_always"
def f():
self.module.warn(message, UserWarning)
f()
self.assertEqual(len(w), 1)
self.assertEqual(w[-1].message.args[0], message)
f()
self.assertEqual(len(w), 2)
self.assertEqual(w[-1].message.args[0], message)
def test_always_after_default(self):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.resetwarnings()
message = "FilterTests.test_always_after_ignore"
def f():
self.module.warn(message, UserWarning)
f()
self.assertEqual(len(w), 1)
self.assertEqual(w[-1].message.args[0], message)
f()
self.assertEqual(len(w), 1)
self.module.filterwarnings("always", category=UserWarning)
f()
self.assertEqual(len(w), 2)
self.assertEqual(w[-1].message.args[0], message)
f()
self.assertEqual(len(w), 3)
self.assertEqual(w[-1].message.args[0], message)
def test_default(self):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.resetwarnings()
self.module.filterwarnings("default", category=UserWarning)
message = UserWarning("FilterTests.test_default")
for x in range(2):
self.module.warn(message, UserWarning)
if x == 0:
self.assertEqual(w[-1].message, message)
del w[:]
elif x == 1:
self.assertEqual(len(w), 0)
else:
raise ValueError("loop variant unhandled")
def test_module(self):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.resetwarnings()
self.module.filterwarnings("module", category=UserWarning)
message = UserWarning("FilterTests.test_module")
self.module.warn(message, UserWarning)
self.assertEqual(w[-1].message, message)
del w[:]
self.module.warn(message, UserWarning)
self.assertEqual(len(w), 0)
def test_once(self):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.resetwarnings()
self.module.filterwarnings("once", category=UserWarning)
message = UserWarning("FilterTests.test_once")
self.module.warn_explicit(message, UserWarning, "__init__.py",
42)
self.assertEqual(w[-1].message, message)
del w[:]
self.module.warn_explicit(message, UserWarning, "__init__.py",
13)
self.assertEqual(len(w), 0)
self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
42)
self.assertEqual(len(w), 0)
def test_module_globals(self):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.simplefilter("always", UserWarning)
# bpo-33509: module_globals=None must not crash
self.module.warn_explicit('msg', UserWarning, "filename", 42,
module_globals=None)
self.assertEqual(len(w), 1)
# Invalid module_globals type
with self.assertRaises(TypeError):
self.module.warn_explicit('msg', UserWarning, "filename", 42,
module_globals=True)
self.assertEqual(len(w), 1)
# Empty module_globals
self.module.warn_explicit('msg', UserWarning, "filename", 42,
module_globals={})
self.assertEqual(len(w), 2)
def test_inheritance(self):
with original_warnings.catch_warnings(module=self.module) as w:
self.module.resetwarnings()
self.module.filterwarnings("error", category=Warning)
self.assertRaises(UserWarning, self.module.warn,
"FilterTests.test_inheritance", UserWarning)
def test_ordering(self):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.resetwarnings()
self.module.filterwarnings("ignore", category=UserWarning)
self.module.filterwarnings("error", category=UserWarning,
append=True)
del w[:]
try:
self.module.warn("FilterTests.test_ordering", UserWarning)
except UserWarning:
self.fail("order handling for actions failed")
self.assertEqual(len(w), 0)
def test_filterwarnings(self):
# Test filterwarnings().
# Implicitly also tests resetwarnings().
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.filterwarnings("error", "", Warning, "", 0)
self.assertRaises(UserWarning, self.module.warn, 'convert to error')
self.module.resetwarnings()
text = 'handle normally'
self.module.warn(text)
self.assertEqual(str(w[-1].message), text)
self.assertIs(w[-1].category, UserWarning)
self.module.filterwarnings("ignore", "", Warning, "", 0)
text = 'filtered out'
self.module.warn(text)
self.assertNotEqual(str(w[-1].message), text)
self.module.resetwarnings()
self.module.filterwarnings("error", "hex*", Warning, "", 0)
self.assertRaises(UserWarning, self.module.warn, 'hex/oct')
text = 'nonmatching text'
self.module.warn(text)
self.assertEqual(str(w[-1].message), text)
self.assertIs(w[-1].category, UserWarning)
def test_message_matching(self):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.simplefilter("ignore", UserWarning)
self.module.filterwarnings("error", "match", UserWarning)
self.assertRaises(UserWarning, self.module.warn, "match")
self.assertRaises(UserWarning, self.module.warn, "match prefix")
self.module.warn("suffix match")
self.assertEqual(w, [])
self.module.warn("something completely different")
self.assertEqual(w, [])
def test_mutate_filter_list(self):
class X:
def match(self, a):
L[:] = []
L = [("default",X(),UserWarning,X(),0) for i in range(2)]
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.filters = L
self.module.warn_explicit(UserWarning("b"), None, "f.py", 42)
self.assertEqual(str(w[-1].message), "b")
def test_filterwarnings_duplicate_filters(self):
with original_warnings.catch_warnings(module=self.module):
self.module.resetwarnings()
self.module.filterwarnings("error", category=UserWarning)
self.assertEqual(len(self.module.filters), 1)
self.module.filterwarnings("ignore", category=UserWarning)
self.module.filterwarnings("error", category=UserWarning)
self.assertEqual(
len(self.module.filters), 2,
"filterwarnings inserted duplicate filter"
)
self.assertEqual(
self.module.filters[0][0], "error",
"filterwarnings did not promote filter to "
"the beginning of list"
)
def test_simplefilter_duplicate_filters(self):
with original_warnings.catch_warnings(module=self.module):
self.module.resetwarnings()
self.module.simplefilter("error", category=UserWarning)
self.assertEqual(len(self.module.filters), 1)
self.module.simplefilter("ignore", category=UserWarning)
self.module.simplefilter("error", category=UserWarning)
self.assertEqual(
len(self.module.filters), 2,
"simplefilter inserted duplicate filter"
)
self.assertEqual(
self.module.filters[0][0], "error",
"simplefilter did not promote filter to the beginning of list"
)
def test_append_duplicate(self):
with original_warnings.catch_warnings(module=self.module,
record=True) as w:
self.module.resetwarnings()
self.module.simplefilter("ignore")
self.module.simplefilter("error", append=True)
self.module.simplefilter("ignore", append=True)
self.module.warn("test_append_duplicate", category=UserWarning)
self.assertEqual(len(self.module.filters), 2,
"simplefilter inserted duplicate filter"
)
self.assertEqual(len(w), 0,
"appended duplicate changed order of filters"
)
class CFilterTests(FilterTests, unittest.TestCase):
module = c_warnings
class PyFilterTests(FilterTests, unittest.TestCase):
module = py_warnings
class WarnTests(BaseTest):
"""Test warnings.warn() and warnings.warn_explicit()."""
def test_message(self):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.simplefilter("once")
for i in range(4):
text = 'multi %d' %i # Different text on each call.
self.module.warn(text)
self.assertEqual(str(w[-1].message), text)
self.assertIs(w[-1].category, UserWarning)
# Issue 3639
def test_warn_nonstandard_types(self):
# warn() should handle non-standard types without issue.
for ob in (Warning, None, 42):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.simplefilter("once")
self.module.warn(ob)
# Don't directly compare objects since
# ``Warning() != Warning()``.
self.assertEqual(str(w[-1].message), str(UserWarning(ob)))
def test_filename(self):
with warnings_state(self.module):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
warning_tests.inner("spam1")
self.assertEqual(os.path.basename(w[-1].filename),
"stacklevel.py")
warning_tests.outer("spam2")
self.assertEqual(os.path.basename(w[-1].filename),
"stacklevel.py")
def test_stacklevel(self):
# Test stacklevel argument
# make sure all messages are different, so the warning won't be skipped
with warnings_state(self.module):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
warning_tests.inner("spam3", stacklevel=1)
self.assertEqual(os.path.basename(w[-1].filename),
"stacklevel.py")
warning_tests.outer("spam4", stacklevel=1)
self.assertEqual(os.path.basename(w[-1].filename),
"stacklevel.py")
warning_tests.inner("spam5", stacklevel=2)
self.assertEqual(os.path.basename(w[-1].filename),
"__init__.py")
warning_tests.outer("spam6", stacklevel=2)
self.assertEqual(os.path.basename(w[-1].filename),
"stacklevel.py")
warning_tests.outer("spam6.5", stacklevel=3)
self.assertEqual(os.path.basename(w[-1].filename),
"__init__.py")
warning_tests.inner("spam7", stacklevel=9999)
self.assertEqual(os.path.basename(w[-1].filename),
"sys")
def test_stacklevel_import(self):
# Issue #24305: With stacklevel=2, module-level warnings should work.
import_helper.unload('test.test_warnings.data.import_warning')
with warnings_state(self.module):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.simplefilter('always')
import test.test_warnings.data.import_warning
self.assertEqual(len(w), 1)
self.assertEqual(w[0].filename, __file__)
def test_exec_filename(self):
filename = "<warnings-test>"
codeobj = compile(("import warnings\n"
"warnings.warn('hello', UserWarning)"),
filename, "exec")
with original_warnings.catch_warnings(record=True) as w:
self.module.simplefilter("always", category=UserWarning)
exec(codeobj)
self.assertEqual(w[0].filename, filename)
def test_warn_explicit_non_ascii_filename(self):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.resetwarnings()
self.module.filterwarnings("always", category=UserWarning)
for filename in ("nonascii\xe9\u20ac", "surrogate\udc80"):
try:
os.fsencode(filename)
except UnicodeEncodeError:
continue
self.module.warn_explicit("text", UserWarning, filename, 1)
self.assertEqual(w[-1].filename, filename)
def test_warn_explicit_type_errors(self):
# warn_explicit() should error out gracefully if it is given objects
# of the wrong types.
# lineno is expected to be an integer.
self.assertRaises(TypeError, self.module.warn_explicit,
None, UserWarning, None, None)
# Either 'message' needs to be an instance of Warning or 'category'
# needs to be a subclass.
self.assertRaises(TypeError, self.module.warn_explicit,
None, None, None, 1)
# 'registry' must be a dict or None.
self.assertRaises((TypeError, AttributeError),
self.module.warn_explicit,
None, Warning, None, 1, registry=42)
def test_bad_str(self):
# issue 6415
# Warnings instance with a bad format string for __str__ should not
# trigger a bus error.
class BadStrWarning(Warning):
"""Warning with a bad format string for __str__."""
def __str__(self):
return ("A bad formatted string %(err)" %
{"err" : "there is no %(err)s"})
with self.assertRaises(ValueError):
self.module.warn(BadStrWarning())
def test_warning_classes(self):
class MyWarningClass(Warning):
pass
class NonWarningSubclass:
pass
# passing a non-subclass of Warning should raise a TypeError
with self.assertRaises(TypeError) as cm:
self.module.warn('bad warning category', '')
self.assertIn('category must be a Warning subclass, not ',
str(cm.exception))
with self.assertRaises(TypeError) as cm:
self.module.warn('bad warning category', NonWarningSubclass)
self.assertIn('category must be a Warning subclass, not ',
str(cm.exception))
# check that warning instances also raise a TypeError
with self.assertRaises(TypeError) as cm:
self.module.warn('bad warning category', MyWarningClass())
self.assertIn('category must be a Warning subclass, not ',
str(cm.exception))
with original_warnings.catch_warnings(module=self.module):
self.module.resetwarnings()
self.module.filterwarnings('default')
with self.assertWarns(MyWarningClass) as cm:
self.module.warn('good warning category', MyWarningClass)
self.assertEqual('good warning category', str(cm.warning))
with self.assertWarns(UserWarning) as cm:
self.module.warn('good warning category', None)
self.assertEqual('good warning category', str(cm.warning))
with self.assertWarns(MyWarningClass) as cm:
self.module.warn('good warning category', MyWarningClass)
self.assertIsInstance(cm.warning, Warning)
class CWarnTests(WarnTests, unittest.TestCase):
module = c_warnings
# As an early adopter, we sanity check the
# test.import_helper.import_fresh_module utility function
def test_accelerated(self):
self.assertIsNot(original_warnings, self.module)
self.assertFalse(hasattr(self.module.warn, '__code__'))
class PyWarnTests(WarnTests, unittest.TestCase):
module = py_warnings
# As an early adopter, we sanity check the
# test.import_helper.import_fresh_module utility function
def test_pure_python(self):
self.assertIsNot(original_warnings, self.module)
self.assertTrue(hasattr(self.module.warn, '__code__'))
class WCmdLineTests(BaseTest):
def test_improper_input(self):
# Uses the private _setoption() function to test the parsing
# of command-line warning arguments
with original_warnings.catch_warnings(module=self.module):
self.assertRaises(self.module._OptionError,
self.module._setoption, '1:2:3:4:5:6')
self.assertRaises(self.module._OptionError,
self.module._setoption, 'bogus::Warning')
self.assertRaises(self.module._OptionError,
self.module._setoption, 'ignore:2::4:-5')
with self.assertRaises(self.module._OptionError):
self.module._setoption('ignore::123')
with self.assertRaises(self.module._OptionError):
self.module._setoption('ignore::123abc')
with self.assertRaises(self.module._OptionError):
self.module._setoption('ignore::===')
with self.assertRaisesRegex(self.module._OptionError, 'Wärning'):
self.module._setoption('ignore::Wärning')
self.module._setoption('error::Warning::0')
self.assertRaises(UserWarning, self.module.warn, 'convert to error')
def test_import_from_module(self):
with original_warnings.catch_warnings(module=self.module):
self.module._setoption('ignore::Warning')
with self.assertRaises(self.module._OptionError):
self.module._setoption('ignore::TestWarning')
with self.assertRaises(self.module._OptionError):
self.module._setoption('ignore::test.test_warnings.bogus')
self.module._setoption('error::test.test_warnings.TestWarning')
with self.assertRaises(TestWarning):
self.module.warn('test warning', TestWarning)
class CWCmdLineTests(WCmdLineTests, unittest.TestCase):
module = c_warnings
class PyWCmdLineTests(WCmdLineTests, unittest.TestCase):
module = py_warnings
def test_improper_option(self):
# Same as above, but check that the message is printed out when
# the interpreter is executed. This also checks that options are
# actually parsed at all.
rc, out, err = assert_python_ok("-Wxxx", "-c", "pass")
self.assertIn(b"Invalid -W option ignored: invalid action: 'xxx'", err)
def test_warnings_bootstrap(self):
# Check that the warnings module does get loaded when -W<some option>
# is used (see issue #10372 for an example of silent bootstrap failure).
rc, out, err = assert_python_ok("-Wi", "-c",
"import sys; sys.modules['warnings'].warn('foo', RuntimeWarning)")
# '-Wi' was observed
self.assertFalse(out.strip())
self.assertNotIn(b'RuntimeWarning', err)
class _WarningsTests(BaseTest, unittest.TestCase):
"""Tests specific to the _warnings module."""
module = c_warnings
def test_filter(self):
# Everything should function even if 'filters' is not in warnings.
with original_warnings.catch_warnings(module=self.module) as w:
self.module.filterwarnings("error", "", Warning, "", 0)
self.assertRaises(UserWarning, self.module.warn,
'convert to error')
del self.module.filters
self.assertRaises(UserWarning, self.module.warn,
'convert to error')
def test_onceregistry(self):
# Replacing or removing the onceregistry should be okay.
global __warningregistry__
message = UserWarning('onceregistry test')
try:
original_registry = self.module.onceregistry
__warningregistry__ = {}
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.resetwarnings()
self.module.filterwarnings("once", category=UserWarning)
self.module.warn_explicit(message, UserWarning, "file", 42)
self.assertEqual(w[-1].message, message)
del w[:]
self.module.warn_explicit(message, UserWarning, "file", 42)
self.assertEqual(len(w), 0)
# Test the resetting of onceregistry.
self.module.onceregistry = {}
__warningregistry__ = {}
self.module.warn('onceregistry test')
self.assertEqual(w[-1].message.args, message.args)
# Removal of onceregistry is okay.
del w[:]
del self.module.onceregistry
__warningregistry__ = {}
self.module.warn_explicit(message, UserWarning, "file", 42)
self.assertEqual(len(w), 0)
finally:
self.module.onceregistry = original_registry
def test_default_action(self):
# Replacing or removing defaultaction should be okay.
message = UserWarning("defaultaction test")
original = self.module.defaultaction
try:
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.resetwarnings()
registry = {}
self.module.warn_explicit(message, UserWarning, "<test>", 42,
registry=registry)
self.assertEqual(w[-1].message, message)
self.assertEqual(len(w), 1)
# One actual registry key plus the "version" key
self.assertEqual(len(registry), 2)
self.assertIn("version", registry)
del w[:]
# Test removal.
del self.module.defaultaction
__warningregistry__ = {}
registry = {}
self.module.warn_explicit(message, UserWarning, "<test>", 43,
registry=registry)
self.assertEqual(w[-1].message, message)
self.assertEqual(len(w), 1)
self.assertEqual(len(registry), 2)
del w[:]
# Test setting.
self.module.defaultaction = "ignore"
__warningregistry__ = {}
registry = {}
self.module.warn_explicit(message, UserWarning, "<test>", 44,
registry=registry)
self.assertEqual(len(w), 0)
finally:
self.module.defaultaction = original
def test_showwarning_missing(self):
# Test that showwarning() missing is okay.
text = 'del showwarning test'
with original_warnings.catch_warnings(module=self.module):
self.module.filterwarnings("always", category=UserWarning)
del self.module.showwarning
with support.captured_output('stderr') as stream:
self.module.warn(text)
result = stream.getvalue()
self.assertIn(text, result)
def test_showwarnmsg_missing(self):
# Test that _showwarnmsg() missing is okay.
text = 'del _showwarnmsg test'
with original_warnings.catch_warnings(module=self.module):
self.module.filterwarnings("always", category=UserWarning)
show = self.module._showwarnmsg
try:
del self.module._showwarnmsg
with support.captured_output('stderr') as stream:
self.module.warn(text)
result = stream.getvalue()
finally:
self.module._showwarnmsg = show
self.assertIn(text, result)
def test_showwarning_not_callable(self):
with original_warnings.catch_warnings(module=self.module):
self.module.filterwarnings("always", category=UserWarning)
self.module.showwarning = print
with support.captured_output('stdout'):
self.module.warn('Warning!')
self.module.showwarning = 23
self.assertRaises(TypeError, self.module.warn, "Warning!")
def test_show_warning_output(self):
# With showwarning() missing, make sure that output is okay.
text = 'test show_warning'
with original_warnings.catch_warnings(module=self.module):
self.module.filterwarnings("always", category=UserWarning)
del self.module.showwarning
with support.captured_output('stderr') as stream:
warning_tests.inner(text)
result = stream.getvalue()
self.assertEqual(result.count('\n'), 2,
"Too many newlines in %r" % result)
first_line, second_line = result.split('\n', 1)
expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
first_line_parts = first_line.rsplit(':', 3)
path, line, warning_class, message = first_line_parts
line = int(line)
self.assertEqual(expected_file, path)
self.assertEqual(warning_class, ' ' + UserWarning.__name__)
self.assertEqual(message, ' ' + text)
expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
assert expected_line
self.assertEqual(second_line, expected_line)
def test_filename_none(self):
# issue #12467: race condition if a warning is emitted at shutdown
globals_dict = globals()
oldfile = globals_dict['__file__']
try:
catch = original_warnings.catch_warnings(record=True,
module=self.module)
with catch as w:
self.module.filterwarnings("always", category=UserWarning)
globals_dict['__file__'] = None
original_warnings.warn('test', UserWarning)
self.assertTrue(len(w))
finally:
globals_dict['__file__'] = oldfile
def test_stderr_none(self):
rc, stdout, stderr = assert_python_ok("-c",
"import sys; sys.stderr = None; "
"import warnings; warnings.simplefilter('always'); "
"warnings.warn('Warning!')")
self.assertEqual(stdout, b'')
self.assertNotIn(b'Warning!', stderr)
self.assertNotIn(b'Error', stderr)
def test_issue31285(self):
# warn_explicit() should neither raise a SystemError nor cause an
# assertion failure, in case the return value of get_source() has a
# bad splitlines() method.
def get_bad_loader(splitlines_ret_val):
class BadLoader:
def get_source(self, fullname):
class BadSource(str):
def splitlines(self):
return splitlines_ret_val
return BadSource('spam')
return BadLoader()
wmod = self.module
with original_warnings.catch_warnings(module=wmod):
wmod.filterwarnings('default', category=UserWarning)
with support.captured_stderr() as stderr:
wmod.warn_explicit(
'foo', UserWarning, 'bar', 1,
module_globals={'__loader__': get_bad_loader(42),
'__name__': 'foobar'})
self.assertIn('UserWarning: foo', stderr.getvalue())
show = wmod._showwarnmsg
try:
del wmod._showwarnmsg
with support.captured_stderr() as stderr:
wmod.warn_explicit(
'eggs', UserWarning, 'bar', 1,
module_globals={'__loader__': get_bad_loader([42]),
'__name__': 'foobar'})
self.assertIn('UserWarning: eggs', stderr.getvalue())
finally:
wmod._showwarnmsg = show
@support.cpython_only
def test_issue31411(self):
# warn_explicit() shouldn't raise a SystemError in case
# warnings.onceregistry isn't a dictionary.
wmod = self.module
with original_warnings.catch_warnings(module=wmod):
wmod.filterwarnings('once')
with support.swap_attr(wmod, 'onceregistry', None):
with self.assertRaises(TypeError):
wmod.warn_explicit('foo', Warning, 'bar', 1, registry=None)
@support.cpython_only
def test_issue31416(self):
# warn_explicit() shouldn't cause an assertion failure in case of a
# bad warnings.filters or warnings.defaultaction.
wmod = self.module
with original_warnings.catch_warnings(module=wmod):
wmod.filters = [(None, None, Warning, None, 0)]
with self.assertRaises(TypeError):
wmod.warn_explicit('foo', Warning, 'bar', 1)
wmod.filters = []
with support.swap_attr(wmod, 'defaultaction', None), \
self.assertRaises(TypeError):
wmod.warn_explicit('foo', Warning, 'bar', 1)
@support.cpython_only
def test_issue31566(self):
# warn() shouldn't cause an assertion failure in case of a bad
# __name__ global.
with original_warnings.catch_warnings(module=self.module):
self.module.filterwarnings('error', category=UserWarning)
with support.swap_item(globals(), '__name__', b'foo'), \
support.swap_item(globals(), '__file__', None):
self.assertRaises(UserWarning, self.module.warn, 'bar')
class WarningsDisplayTests(BaseTest):
"""Test the displaying of warnings and the ability to overload functions
related to displaying warnings."""
def test_formatwarning(self):
message = "msg"
category = Warning
file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
line_num = 3
file_line = linecache.getline(file_name, line_num).strip()
format = "%s:%s: %s: %s\n %s\n"
expect = format % (file_name, line_num, category.__name__, message,
file_line)
self.assertEqual(expect, self.module.formatwarning(message,
category, file_name, line_num))
# Test the 'line' argument.
file_line += " for the win!"
expect = format % (file_name, line_num, category.__name__, message,
file_line)
self.assertEqual(expect, self.module.formatwarning(message,
category, file_name, line_num, file_line))
def test_showwarning(self):
file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
line_num = 3
expected_file_line = linecache.getline(file_name, line_num).strip()
message = 'msg'
category = Warning
file_object = StringIO()
expect = self.module.formatwarning(message, category, file_name,
line_num)
self.module.showwarning(message, category, file_name, line_num,
file_object)
self.assertEqual(file_object.getvalue(), expect)
# Test 'line' argument.
expected_file_line += "for the win!"
expect = self.module.formatwarning(message, category, file_name,
line_num, expected_file_line)
file_object = StringIO()
self.module.showwarning(message, category, file_name, line_num,
file_object, expected_file_line)
self.assertEqual(expect, file_object.getvalue())
def test_formatwarning_override(self):
# bpo-35178: Test that a custom formatwarning function gets the 'line'
# argument as a positional argument, and not only as a keyword argument
def myformatwarning(message, category, filename, lineno, text):
return f'm={message}:c={category}:f={filename}:l={lineno}:t={text}'
file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
line_num = 3
file_line = linecache.getline(file_name, line_num).strip()
message = 'msg'
category = Warning
file_object = StringIO()
expected = f'm={message}:c={category}:f={file_name}:l={line_num}' + \
f':t={file_line}'
with support.swap_attr(self.module, 'formatwarning', myformatwarning):
self.module.showwarning(message, category, file_name, line_num,
file_object, file_line)
self.assertEqual(file_object.getvalue(), expected)
class CWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase):
module = c_warnings
class PyWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase):
module = py_warnings
def test_tracemalloc(self):
self.addCleanup(os_helper.unlink, os_helper.TESTFN)
with open(os_helper.TESTFN, 'w', encoding="utf-8") as fp:
fp.write(textwrap.dedent("""
def func():
f = open(__file__, "rb")
# Emit ResourceWarning
f = None
func()
"""))
def run(*args):
res = assert_python_ok(*args, PYTHONIOENCODING='utf-8')
stderr = res.err.decode('utf-8', 'replace')
stderr = '\n'.join(stderr.splitlines())
# normalize newlines
stderr = re.sub('<.*>', '<...>', stderr)
return stderr
# tracemalloc disabled
filename = os.path.abspath(os_helper.TESTFN)
stderr = run('-Wd', os_helper.TESTFN)
expected = textwrap.dedent(f'''
{filename}:5: ResourceWarning: unclosed file <...>
f = None
ResourceWarning: Enable tracemalloc to get the object allocation traceback
''').strip()
self.assertEqual(stderr, expected)
# tracemalloc enabled
stderr = run('-Wd', '-X', 'tracemalloc=2', os_helper.TESTFN)
expected = textwrap.dedent(f'''
{filename}:5: ResourceWarning: unclosed file <...>
f = None
Object allocated at (most recent call last):
File "{filename}", lineno 7
func()
File "{filename}", lineno 3
f = open(__file__, "rb")
''').strip()
self.assertEqual(stderr, expected)
class CatchWarningTests(BaseTest):
"""Test catch_warnings()."""
def test_catch_warnings_restore(self):
wmod = self.module
orig_filters = wmod.filters
orig_showwarning = wmod.showwarning
# Ensure both showwarning and filters are restored when recording
with wmod.catch_warnings(module=wmod, record=True):
wmod.filters = wmod.showwarning = object()
self.assertIs(wmod.filters, orig_filters)
self.assertIs(wmod.showwarning, orig_showwarning)
# Same test, but with recording disabled
with wmod.catch_warnings(module=wmod, record=False):
wmod.filters = wmod.showwarning = object()
self.assertIs(wmod.filters, orig_filters)
self.assertIs(wmod.showwarning, orig_showwarning)
def test_catch_warnings_recording(self):
wmod = self.module
# Ensure warnings are recorded when requested
with wmod.catch_warnings(module=wmod, record=True) as w:
self.assertEqual(w, [])
self.assertIs(type(w), list)
wmod.simplefilter("always")
wmod.warn("foo")
self.assertEqual(str(w[-1].message), "foo")
wmod.warn("bar")
self.assertEqual(str(w[-1].message), "bar")
self.assertEqual(str(w[0].message), "foo")
self.assertEqual(str(w[1].message), "bar")
del w[:]
self.assertEqual(w, [])
# Ensure warnings are not recorded when not requested
orig_showwarning = wmod.showwarning
with wmod.catch_warnings(module=wmod, record=False) as w:
self.assertIsNone(w)
self.assertIs(wmod.showwarning, orig_showwarning)
def test_catch_warnings_reentry_guard(self):
wmod = self.module
# Ensure catch_warnings is protected against incorrect usage
x = wmod.catch_warnings(module=wmod, record=True)
self.assertRaises(RuntimeError, x.__exit__)
with x:
self.assertRaises(RuntimeError, x.__enter__)
# Same test, but with recording disabled
x = wmod.catch_warnings(module=wmod, record=False)
self.assertRaises(RuntimeError, x.__exit__)
with x:
self.assertRaises(RuntimeError, x.__enter__)
def test_catch_warnings_defaults(self):
wmod = self.module
orig_filters = wmod.filters
orig_showwarning = wmod.showwarning
# Ensure default behaviour is not to record warnings
with wmod.catch_warnings(module=wmod) as w:
self.assertIsNone(w)
self.assertIs(wmod.showwarning, orig_showwarning)
self.assertIsNot(wmod.filters, orig_filters)
self.assertIs(wmod.filters, orig_filters)
if wmod is sys.modules['warnings']:
# Ensure the default module is this one
with wmod.catch_warnings() as w:
self.assertIsNone(w)
self.assertIs(wmod.showwarning, orig_showwarning)
self.assertIsNot(wmod.filters, orig_filters)
self.assertIs(wmod.filters, orig_filters)
def test_record_override_showwarning_before(self):
# Issue #28835: If warnings.showwarning() was overridden, make sure
# that catch_warnings(record=True) overrides it again.
text = "This is a warning"
wmod = self.module
my_log = []
def my_logger(message, category, filename, lineno, file=None, line=None):
nonlocal my_log
my_log.append(message)
# Override warnings.showwarning() before calling catch_warnings()
with support.swap_attr(wmod, 'showwarning', my_logger):
with wmod.catch_warnings(module=wmod, record=True) as log:
self.assertIsNot(wmod.showwarning, my_logger)
wmod.simplefilter("always")
wmod.warn(text)
self.assertIs(wmod.showwarning, my_logger)
self.assertEqual(len(log), 1, log)
self.assertEqual(log[0].message.args[0], text)
self.assertEqual(my_log, [])
def test_record_override_showwarning_inside(self):
# Issue #28835: It is possible to override warnings.showwarning()
# in the catch_warnings(record=True) context manager.
text = "This is a warning"
wmod = self.module
my_log = []
def my_logger(message, category, filename, lineno, file=None, line=None):
nonlocal my_log
my_log.append(message)
with wmod.catch_warnings(module=wmod, record=True) as log:
wmod.simplefilter("always")
wmod.showwarning = my_logger
wmod.warn(text)
self.assertEqual(len(my_log), 1, my_log)
self.assertEqual(my_log[0].args[0], text)
self.assertEqual(log, [])
def test_check_warnings(self):
# Explicit tests for the test.support convenience wrapper
wmod = self.module
if wmod is not sys.modules['warnings']:
self.skipTest('module to test is not loaded warnings module')
with warnings_helper.check_warnings(quiet=False) as w:
self.assertEqual(w.warnings, [])
wmod.simplefilter("always")
wmod.warn("foo")
self.assertEqual(str(w.message), "foo")
wmod.warn("bar")
self.assertEqual(str(w.message), "bar")
self.assertEqual(str(w.warnings[0].message), "foo")
self.assertEqual(str(w.warnings[1].message), "bar")
w.reset()
self.assertEqual(w.warnings, [])
with warnings_helper.check_warnings():
# defaults to quiet=True without argument
pass
with warnings_helper.check_warnings(('foo', UserWarning)):
wmod.warn("foo")
with self.assertRaises(AssertionError):
with warnings_helper.check_warnings(('', RuntimeWarning)):
# defaults to quiet=False with argument
pass
with self.assertRaises(AssertionError):
with warnings_helper.check_warnings(('foo', RuntimeWarning)):
wmod.warn("foo")
class CCatchWarningTests(CatchWarningTests, unittest.TestCase):
module = c_warnings
class PyCatchWarningTests(CatchWarningTests, unittest.TestCase):
module = py_warnings
class EnvironmentVariableTests(BaseTest):
def test_single_warning(self):
rc, stdout, stderr = assert_python_ok("-c",
"import sys; sys.stdout.write(str(sys.warnoptions))",
PYTHONWARNINGS="ignore::DeprecationWarning",
PYTHONDEVMODE="")
self.assertEqual(stdout, b"['ignore::DeprecationWarning']")
def test_comma_separated_warnings(self):
rc, stdout, stderr = assert_python_ok("-c",
"import sys; sys.stdout.write(str(sys.warnoptions))",
PYTHONWARNINGS="ignore::DeprecationWarning,ignore::UnicodeWarning",
PYTHONDEVMODE="")
self.assertEqual(stdout,
b"['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
def test_envvar_and_command_line(self):
rc, stdout, stderr = assert_python_ok("-Wignore::UnicodeWarning", "-c",
"import sys; sys.stdout.write(str(sys.warnoptions))",
PYTHONWARNINGS="ignore::DeprecationWarning",
PYTHONDEVMODE="")
self.assertEqual(stdout,
b"['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
def test_conflicting_envvar_and_command_line(self):
rc, stdout, stderr = assert_python_failure("-Werror::DeprecationWarning", "-c",
"import sys, warnings; sys.stdout.write(str(sys.warnoptions)); "
"warnings.warn('Message', DeprecationWarning)",
PYTHONWARNINGS="default::DeprecationWarning",
PYTHONDEVMODE="")
self.assertEqual(stdout,
b"['default::DeprecationWarning', 'error::DeprecationWarning']")
self.assertEqual(stderr.splitlines(),
[b"Traceback (most recent call last):",
b" File \"<string>\", line 1, in <module>",
b"DeprecationWarning: Message"])
def test_default_filter_configuration(self):
pure_python_api = self.module is py_warnings
if Py_DEBUG:
expected_default_filters = []
else:
if pure_python_api:
main_module_filter = re.compile("__main__")
else:
main_module_filter = "__main__"
expected_default_filters = [
('default', None, DeprecationWarning, main_module_filter, 0),
('ignore', None, DeprecationWarning, None, 0),
('ignore', None, PendingDeprecationWarning, None, 0),
('ignore', None, ImportWarning, None, 0),
('ignore', None, ResourceWarning, None, 0),
]
expected_output = [str(f).encode() for f in expected_default_filters]
if pure_python_api:
# Disable the warnings acceleration module in the subprocess
code = "import sys; sys.modules.pop('warnings', None); sys.modules['_warnings'] = None; "
else:
code = ""
code += "import warnings; [print(f) for f in warnings.filters]"
rc, stdout, stderr = assert_python_ok("-c", code, __isolated=True)
stdout_lines = [line.strip() for line in stdout.splitlines()]
self.maxDiff = None
self.assertEqual(stdout_lines, expected_output)
@unittest.skipUnless(sys.getfilesystemencoding() != 'ascii',
'requires non-ascii filesystemencoding')
def test_nonascii(self):
PYTHONWARNINGS="ignore:DeprecationWarning" + os_helper.FS_NONASCII
rc, stdout, stderr = assert_python_ok("-c",
"import sys; sys.stdout.write(str(sys.warnoptions))",
PYTHONIOENCODING="utf-8",
PYTHONWARNINGS=PYTHONWARNINGS,
PYTHONDEVMODE="")
self.assertEqual(stdout, str([PYTHONWARNINGS]).encode())
class CEnvironmentVariableTests(EnvironmentVariableTests, unittest.TestCase):
module = c_warnings
class PyEnvironmentVariableTests(EnvironmentVariableTests, unittest.TestCase):
module = py_warnings
class _DeprecatedTest(BaseTest, unittest.TestCase):
"""Test _deprecated()."""
module = original_warnings
def test_warning(self):
version = (3, 11, 0, "final", 0)
test = [(4, 12), (4, 11), (4, 0), (3, 12)]
for remove in test:
msg = rf".*test_warnings.*{remove[0]}\.{remove[1]}"
filter = msg, DeprecationWarning
with self.subTest(remove=remove):
with warnings_helper.check_warnings(filter, quiet=False):
self.module._deprecated("test_warnings", remove=remove,
_version=version)
version = (3, 11, 0, "alpha", 0)
msg = r".*test_warnings.*3\.11"
with warnings_helper.check_warnings((msg, DeprecationWarning), quiet=False):
self.module._deprecated("test_warnings", remove=(3, 11),
_version=version)
def test_RuntimeError(self):
version = (3, 11, 0, "final", 0)
test = [(2, 0), (2, 12), (3, 10)]
for remove in test:
with self.subTest(remove=remove):
with self.assertRaises(RuntimeError):
self.module._deprecated("test_warnings", remove=remove,
_version=version)
for level in ["beta", "candidate", "final"]:
version = (3, 11, 0, level, 0)
with self.subTest(releaselevel=level):
with self.assertRaises(RuntimeError):
self.module._deprecated("test_warnings", remove=(3, 11),
_version=version)
class BootstrapTest(unittest.TestCase):
def test_issue_8766(self):
# "import encodings" emits a warning whereas the warnings is not loaded
# or not completely loaded (warnings imports indirectly encodings by
# importing linecache) yet
with os_helper.temp_cwd() as cwd, os_helper.temp_cwd('encodings'):
# encodings loaded by initfsencoding()
assert_python_ok('-c', 'pass', PYTHONPATH=cwd)
# Use -W to load warnings module at startup
assert_python_ok('-c', 'pass', '-W', 'always', PYTHONPATH=cwd)
class FinalizationTest(unittest.TestCase):
def test_finalization(self):
# Issue #19421: warnings.warn() should not crash
# during Python finalization
code = """
import warnings
warn = warnings.warn
class A:
def __del__(self):
warn("test")
a=A()
"""
rc, out, err = assert_python_ok("-c", code)
self.assertEqual(err.decode().rstrip(),
'<string>:7: UserWarning: test')
def test_late_resource_warning(self):
# Issue #21925: Emitting a ResourceWarning late during the Python
# shutdown must be logged.
expected = b"sys:1: ResourceWarning: unclosed file "
# don't import the warnings module
# (_warnings will try to import it)
code = "f = open(%a)" % __file__
rc, out, err = assert_python_ok("-Wd", "-c", code)
self.assertTrue(err.startswith(expected), ascii(err))
# import the warnings module
code = "import warnings; f = open(%a)" % __file__
rc, out, err = assert_python_ok("-Wd", "-c", code)
self.assertTrue(err.startswith(expected), ascii(err))
def setUpModule():
py_warnings.onceregistry.clear()
c_warnings.onceregistry.clear()
tearDownModule = setUpModule
if __name__ == "__main__":
unittest.main()
| 42.100834 | 101 | 0.597936 | from contextlib import contextmanager
import linecache
import os
from io import StringIO
import re
import sys
import textwrap
import unittest
from test import support
from test.support import import_helper
from test.support import os_helper
from test.support import warnings_helper
from test.support.script_helper import assert_python_ok, assert_python_failure
from test.test_warnings.data import stacklevel as warning_tests
import warnings as original_warnings
py_warnings = import_helper.import_fresh_module('warnings',
blocked=['_warnings'])
c_warnings = import_helper.import_fresh_module('warnings',
fresh=['_warnings'])
Py_DEBUG = hasattr(sys, 'gettotalrefcount')
@contextmanager
def warnings_state(module):
global __warningregistry__
for to_clear in (sys, warning_tests):
try:
to_clear.__warningregistry__.clear()
except AttributeError:
pass
try:
__warningregistry__.clear()
except NameError:
pass
original_warnings = warning_tests.warnings
original_filters = module.filters
try:
module.filters = original_filters[:]
module.simplefilter("once")
warning_tests.warnings = module
yield
finally:
warning_tests.warnings = original_warnings
module.filters = original_filters
class TestWarning(Warning):
pass
class BaseTest:
def setUp(self):
self.old_unittest_module = unittest.case.warnings
if '__warningregistry__' in globals():
del globals()['__warningregistry__']
if hasattr(warning_tests, '__warningregistry__'):
del warning_tests.__warningregistry__
if hasattr(sys, '__warningregistry__'):
del sys.__warningregistry__
sys.modules['warnings'] = self.module
unittest.case.warnings = self.module
super(BaseTest, self).setUp()
def tearDown(self):
sys.modules['warnings'] = original_warnings
unittest.case.warnings = self.old_unittest_module
super(BaseTest, self).tearDown()
class PublicAPITests(BaseTest):
def test_module_all_attribute(self):
self.assertTrue(hasattr(self.module, '__all__'))
target_api = ["warn", "warn_explicit", "showwarning",
"formatwarning", "filterwarnings", "simplefilter",
"resetwarnings", "catch_warnings"]
self.assertSetEqual(set(self.module.__all__),
set(target_api))
class CPublicAPITests(PublicAPITests, unittest.TestCase):
module = c_warnings
class PyPublicAPITests(PublicAPITests, unittest.TestCase):
module = py_warnings
class FilterTests(BaseTest):
def test_error(self):
with original_warnings.catch_warnings(module=self.module) as w:
self.module.resetwarnings()
self.module.filterwarnings("error", category=UserWarning)
self.assertRaises(UserWarning, self.module.warn,
"FilterTests.test_error")
def test_error_after_default(self):
with original_warnings.catch_warnings(module=self.module) as w:
self.module.resetwarnings()
message = "FilterTests.test_ignore_after_default"
def f():
self.module.warn(message, UserWarning)
with support.captured_stderr() as stderr:
f()
stderr = stderr.getvalue()
self.assertIn("UserWarning: FilterTests.test_ignore_after_default",
stderr)
self.assertIn("self.module.warn(message, UserWarning)",
stderr)
self.module.filterwarnings("error", category=UserWarning)
self.assertRaises(UserWarning, f)
def test_ignore(self):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.resetwarnings()
self.module.filterwarnings("ignore", category=UserWarning)
self.module.warn("FilterTests.test_ignore", UserWarning)
self.assertEqual(len(w), 0)
self.assertEqual(list(__warningregistry__), ['version'])
def test_ignore_after_default(self):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.resetwarnings()
message = "FilterTests.test_ignore_after_default"
def f():
self.module.warn(message, UserWarning)
f()
self.module.filterwarnings("ignore", category=UserWarning)
f()
f()
self.assertEqual(len(w), 1)
def test_always(self):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.resetwarnings()
self.module.filterwarnings("always", category=UserWarning)
message = "FilterTests.test_always"
def f():
self.module.warn(message, UserWarning)
f()
self.assertEqual(len(w), 1)
self.assertEqual(w[-1].message.args[0], message)
f()
self.assertEqual(len(w), 2)
self.assertEqual(w[-1].message.args[0], message)
def test_always_after_default(self):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.resetwarnings()
message = "FilterTests.test_always_after_ignore"
def f():
self.module.warn(message, UserWarning)
f()
self.assertEqual(len(w), 1)
self.assertEqual(w[-1].message.args[0], message)
f()
self.assertEqual(len(w), 1)
self.module.filterwarnings("always", category=UserWarning)
f()
self.assertEqual(len(w), 2)
self.assertEqual(w[-1].message.args[0], message)
f()
self.assertEqual(len(w), 3)
self.assertEqual(w[-1].message.args[0], message)
def test_default(self):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.resetwarnings()
self.module.filterwarnings("default", category=UserWarning)
message = UserWarning("FilterTests.test_default")
for x in range(2):
self.module.warn(message, UserWarning)
if x == 0:
self.assertEqual(w[-1].message, message)
del w[:]
elif x == 1:
self.assertEqual(len(w), 0)
else:
raise ValueError("loop variant unhandled")
def test_module(self):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.resetwarnings()
self.module.filterwarnings("module", category=UserWarning)
message = UserWarning("FilterTests.test_module")
self.module.warn(message, UserWarning)
self.assertEqual(w[-1].message, message)
del w[:]
self.module.warn(message, UserWarning)
self.assertEqual(len(w), 0)
def test_once(self):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.resetwarnings()
self.module.filterwarnings("once", category=UserWarning)
message = UserWarning("FilterTests.test_once")
self.module.warn_explicit(message, UserWarning, "__init__.py",
42)
self.assertEqual(w[-1].message, message)
del w[:]
self.module.warn_explicit(message, UserWarning, "__init__.py",
13)
self.assertEqual(len(w), 0)
self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
42)
self.assertEqual(len(w), 0)
def test_module_globals(self):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.simplefilter("always", UserWarning)
self.module.warn_explicit('msg', UserWarning, "filename", 42,
module_globals=None)
self.assertEqual(len(w), 1)
with self.assertRaises(TypeError):
self.module.warn_explicit('msg', UserWarning, "filename", 42,
module_globals=True)
self.assertEqual(len(w), 1)
self.module.warn_explicit('msg', UserWarning, "filename", 42,
module_globals={})
self.assertEqual(len(w), 2)
def test_inheritance(self):
with original_warnings.catch_warnings(module=self.module) as w:
self.module.resetwarnings()
self.module.filterwarnings("error", category=Warning)
self.assertRaises(UserWarning, self.module.warn,
"FilterTests.test_inheritance", UserWarning)
def test_ordering(self):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.resetwarnings()
self.module.filterwarnings("ignore", category=UserWarning)
self.module.filterwarnings("error", category=UserWarning,
append=True)
del w[:]
try:
self.module.warn("FilterTests.test_ordering", UserWarning)
except UserWarning:
self.fail("order handling for actions failed")
self.assertEqual(len(w), 0)
def test_filterwarnings(self):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.filterwarnings("error", "", Warning, "", 0)
self.assertRaises(UserWarning, self.module.warn, 'convert to error')
self.module.resetwarnings()
text = 'handle normally'
self.module.warn(text)
self.assertEqual(str(w[-1].message), text)
self.assertIs(w[-1].category, UserWarning)
self.module.filterwarnings("ignore", "", Warning, "", 0)
text = 'filtered out'
self.module.warn(text)
self.assertNotEqual(str(w[-1].message), text)
self.module.resetwarnings()
self.module.filterwarnings("error", "hex*", Warning, "", 0)
self.assertRaises(UserWarning, self.module.warn, 'hex/oct')
text = 'nonmatching text'
self.module.warn(text)
self.assertEqual(str(w[-1].message), text)
self.assertIs(w[-1].category, UserWarning)
def test_message_matching(self):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.simplefilter("ignore", UserWarning)
self.module.filterwarnings("error", "match", UserWarning)
self.assertRaises(UserWarning, self.module.warn, "match")
self.assertRaises(UserWarning, self.module.warn, "match prefix")
self.module.warn("suffix match")
self.assertEqual(w, [])
self.module.warn("something completely different")
self.assertEqual(w, [])
def test_mutate_filter_list(self):
class X:
def match(self, a):
L[:] = []
L = [("default",X(),UserWarning,X(),0) for i in range(2)]
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.filters = L
self.module.warn_explicit(UserWarning("b"), None, "f.py", 42)
self.assertEqual(str(w[-1].message), "b")
def test_filterwarnings_duplicate_filters(self):
with original_warnings.catch_warnings(module=self.module):
self.module.resetwarnings()
self.module.filterwarnings("error", category=UserWarning)
self.assertEqual(len(self.module.filters), 1)
self.module.filterwarnings("ignore", category=UserWarning)
self.module.filterwarnings("error", category=UserWarning)
self.assertEqual(
len(self.module.filters), 2,
"filterwarnings inserted duplicate filter"
)
self.assertEqual(
self.module.filters[0][0], "error",
"filterwarnings did not promote filter to "
"the beginning of list"
)
def test_simplefilter_duplicate_filters(self):
with original_warnings.catch_warnings(module=self.module):
self.module.resetwarnings()
self.module.simplefilter("error", category=UserWarning)
self.assertEqual(len(self.module.filters), 1)
self.module.simplefilter("ignore", category=UserWarning)
self.module.simplefilter("error", category=UserWarning)
self.assertEqual(
len(self.module.filters), 2,
"simplefilter inserted duplicate filter"
)
self.assertEqual(
self.module.filters[0][0], "error",
"simplefilter did not promote filter to the beginning of list"
)
def test_append_duplicate(self):
with original_warnings.catch_warnings(module=self.module,
record=True) as w:
self.module.resetwarnings()
self.module.simplefilter("ignore")
self.module.simplefilter("error", append=True)
self.module.simplefilter("ignore", append=True)
self.module.warn("test_append_duplicate", category=UserWarning)
self.assertEqual(len(self.module.filters), 2,
"simplefilter inserted duplicate filter"
)
self.assertEqual(len(w), 0,
"appended duplicate changed order of filters"
)
class CFilterTests(FilterTests, unittest.TestCase):
module = c_warnings
class PyFilterTests(FilterTests, unittest.TestCase):
module = py_warnings
class WarnTests(BaseTest):
def test_message(self):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.simplefilter("once")
for i in range(4):
text = 'multi %d' %i
self.module.warn(text)
self.assertEqual(str(w[-1].message), text)
self.assertIs(w[-1].category, UserWarning)
def test_warn_nonstandard_types(self):
for ob in (Warning, None, 42):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.simplefilter("once")
self.module.warn(ob)
# ``Warning() != Warning()``.
self.assertEqual(str(w[-1].message), str(UserWarning(ob)))
def test_filename(self):
with warnings_state(self.module):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
warning_tests.inner("spam1")
self.assertEqual(os.path.basename(w[-1].filename),
"stacklevel.py")
warning_tests.outer("spam2")
self.assertEqual(os.path.basename(w[-1].filename),
"stacklevel.py")
def test_stacklevel(self):
# Test stacklevel argument
# make sure all messages are different, so the warning won't be skipped
with warnings_state(self.module):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
warning_tests.inner("spam3", stacklevel=1)
self.assertEqual(os.path.basename(w[-1].filename),
"stacklevel.py")
warning_tests.outer("spam4", stacklevel=1)
self.assertEqual(os.path.basename(w[-1].filename),
"stacklevel.py")
warning_tests.inner("spam5", stacklevel=2)
self.assertEqual(os.path.basename(w[-1].filename),
"__init__.py")
warning_tests.outer("spam6", stacklevel=2)
self.assertEqual(os.path.basename(w[-1].filename),
"stacklevel.py")
warning_tests.outer("spam6.5", stacklevel=3)
self.assertEqual(os.path.basename(w[-1].filename),
"__init__.py")
warning_tests.inner("spam7", stacklevel=9999)
self.assertEqual(os.path.basename(w[-1].filename),
"sys")
def test_stacklevel_import(self):
_warning')
with warnings_state(self.module):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.simplefilter('always')
import test.test_warnings.data.import_warning
self.assertEqual(len(w), 1)
self.assertEqual(w[0].filename, __file__)
def test_exec_filename(self):
filename = "<warnings-test>"
codeobj = compile(("import warnings\n"
"warnings.warn('hello', UserWarning)"),
filename, "exec")
with original_warnings.catch_warnings(record=True) as w:
self.module.simplefilter("always", category=UserWarning)
exec(codeobj)
self.assertEqual(w[0].filename, filename)
def test_warn_explicit_non_ascii_filename(self):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.resetwarnings()
self.module.filterwarnings("always", category=UserWarning)
for filename in ("nonascii\xe9\u20ac", "surrogate\udc80"):
try:
os.fsencode(filename)
except UnicodeEncodeError:
continue
self.module.warn_explicit("text", UserWarning, filename, 1)
self.assertEqual(w[-1].filename, filename)
def test_warn_explicit_type_errors(self):
self.assertRaises(TypeError, self.module.warn_explicit,
None, UserWarning, None, None)
self.assertRaises(TypeError, self.module.warn_explicit,
None, None, None, 1)
self.assertRaises((TypeError, AttributeError),
self.module.warn_explicit,
None, Warning, None, 1, registry=42)
def test_bad_str(self):
class BadStrWarning(Warning):
def __str__(self):
return ("A bad formatted string %(err)" %
{"err" : "there is no %(err)s"})
with self.assertRaises(ValueError):
self.module.warn(BadStrWarning())
def test_warning_classes(self):
class MyWarningClass(Warning):
pass
class NonWarningSubclass:
pass
with self.assertRaises(TypeError) as cm:
self.module.warn('bad warning category', '')
self.assertIn('category must be a Warning subclass, not ',
str(cm.exception))
with self.assertRaises(TypeError) as cm:
self.module.warn('bad warning category', NonWarningSubclass)
self.assertIn('category must be a Warning subclass, not ',
str(cm.exception))
with self.assertRaises(TypeError) as cm:
self.module.warn('bad warning category', MyWarningClass())
self.assertIn('category must be a Warning subclass, not ',
str(cm.exception))
with original_warnings.catch_warnings(module=self.module):
self.module.resetwarnings()
self.module.filterwarnings('default')
with self.assertWarns(MyWarningClass) as cm:
self.module.warn('good warning category', MyWarningClass)
self.assertEqual('good warning category', str(cm.warning))
with self.assertWarns(UserWarning) as cm:
self.module.warn('good warning category', None)
self.assertEqual('good warning category', str(cm.warning))
with self.assertWarns(MyWarningClass) as cm:
self.module.warn('good warning category', MyWarningClass)
self.assertIsInstance(cm.warning, Warning)
class CWarnTests(WarnTests, unittest.TestCase):
module = c_warnings
def test_accelerated(self):
self.assertIsNot(original_warnings, self.module)
self.assertFalse(hasattr(self.module.warn, '__code__'))
class PyWarnTests(WarnTests, unittest.TestCase):
module = py_warnings
def test_pure_python(self):
self.assertIsNot(original_warnings, self.module)
self.assertTrue(hasattr(self.module.warn, '__code__'))
class WCmdLineTests(BaseTest):
def test_improper_input(self):
with original_warnings.catch_warnings(module=self.module):
self.assertRaises(self.module._OptionError,
self.module._setoption, '1:2:3:4:5:6')
self.assertRaises(self.module._OptionError,
self.module._setoption, 'bogus::Warning')
self.assertRaises(self.module._OptionError,
self.module._setoption, 'ignore:2::4:-5')
with self.assertRaises(self.module._OptionError):
self.module._setoption('ignore::123')
with self.assertRaises(self.module._OptionError):
self.module._setoption('ignore::123abc')
with self.assertRaises(self.module._OptionError):
self.module._setoption('ignore::===')
with self.assertRaisesRegex(self.module._OptionError, 'Wärning'):
self.module._setoption('ignore::Wärning')
self.module._setoption('error::Warning::0')
self.assertRaises(UserWarning, self.module.warn, 'convert to error')
def test_import_from_module(self):
with original_warnings.catch_warnings(module=self.module):
self.module._setoption('ignore::Warning')
with self.assertRaises(self.module._OptionError):
self.module._setoption('ignore::TestWarning')
with self.assertRaises(self.module._OptionError):
self.module._setoption('ignore::test.test_warnings.bogus')
self.module._setoption('error::test.test_warnings.TestWarning')
with self.assertRaises(TestWarning):
self.module.warn('test warning', TestWarning)
class CWCmdLineTests(WCmdLineTests, unittest.TestCase):
module = c_warnings
class PyWCmdLineTests(WCmdLineTests, unittest.TestCase):
module = py_warnings
def test_improper_option(self):
rc, out, err = assert_python_ok("-Wxxx", "-c", "pass")
self.assertIn(b"Invalid -W option ignored: invalid action: 'xxx'", err)
def test_warnings_bootstrap(self):
",
"import sys; sys.modules['warnings'].warn('foo', RuntimeWarning)")
self.assertFalse(out.strip())
self.assertNotIn(b'RuntimeWarning', err)
class _WarningsTests(BaseTest, unittest.TestCase):
module = c_warnings
def test_filter(self):
with original_warnings.catch_warnings(module=self.module) as w:
self.module.filterwarnings("error", "", Warning, "", 0)
self.assertRaises(UserWarning, self.module.warn,
'convert to error')
del self.module.filters
self.assertRaises(UserWarning, self.module.warn,
'convert to error')
def test_onceregistry(self):
global __warningregistry__
message = UserWarning('onceregistry test')
try:
original_registry = self.module.onceregistry
__warningregistry__ = {}
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.resetwarnings()
self.module.filterwarnings("once", category=UserWarning)
self.module.warn_explicit(message, UserWarning, "file", 42)
self.assertEqual(w[-1].message, message)
del w[:]
self.module.warn_explicit(message, UserWarning, "file", 42)
self.assertEqual(len(w), 0)
self.module.onceregistry = {}
__warningregistry__ = {}
self.module.warn('onceregistry test')
self.assertEqual(w[-1].message.args, message.args)
del w[:]
del self.module.onceregistry
__warningregistry__ = {}
self.module.warn_explicit(message, UserWarning, "file", 42)
self.assertEqual(len(w), 0)
finally:
self.module.onceregistry = original_registry
def test_default_action(self):
message = UserWarning("defaultaction test")
original = self.module.defaultaction
try:
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
self.module.resetwarnings()
registry = {}
self.module.warn_explicit(message, UserWarning, "<test>", 42,
registry=registry)
self.assertEqual(w[-1].message, message)
self.assertEqual(len(w), 1)
self.assertEqual(len(registry), 2)
self.assertIn("version", registry)
del w[:]
del self.module.defaultaction
__warningregistry__ = {}
registry = {}
self.module.warn_explicit(message, UserWarning, "<test>", 43,
registry=registry)
self.assertEqual(w[-1].message, message)
self.assertEqual(len(w), 1)
self.assertEqual(len(registry), 2)
del w[:]
self.module.defaultaction = "ignore"
__warningregistry__ = {}
registry = {}
self.module.warn_explicit(message, UserWarning, "<test>", 44,
registry=registry)
self.assertEqual(len(w), 0)
finally:
self.module.defaultaction = original
def test_showwarning_missing(self):
text = 'del showwarning test'
with original_warnings.catch_warnings(module=self.module):
self.module.filterwarnings("always", category=UserWarning)
del self.module.showwarning
with support.captured_output('stderr') as stream:
self.module.warn(text)
result = stream.getvalue()
self.assertIn(text, result)
def test_showwarnmsg_missing(self):
text = 'del _showwarnmsg test'
with original_warnings.catch_warnings(module=self.module):
self.module.filterwarnings("always", category=UserWarning)
show = self.module._showwarnmsg
try:
del self.module._showwarnmsg
with support.captured_output('stderr') as stream:
self.module.warn(text)
result = stream.getvalue()
finally:
self.module._showwarnmsg = show
self.assertIn(text, result)
def test_showwarning_not_callable(self):
with original_warnings.catch_warnings(module=self.module):
self.module.filterwarnings("always", category=UserWarning)
self.module.showwarning = print
with support.captured_output('stdout'):
self.module.warn('Warning!')
self.module.showwarning = 23
self.assertRaises(TypeError, self.module.warn, "Warning!")
def test_show_warning_output(self):
text = 'test show_warning'
with original_warnings.catch_warnings(module=self.module):
self.module.filterwarnings("always", category=UserWarning)
del self.module.showwarning
with support.captured_output('stderr') as stream:
warning_tests.inner(text)
result = stream.getvalue()
self.assertEqual(result.count('\n'), 2,
"Too many newlines in %r" % result)
first_line, second_line = result.split('\n', 1)
expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
first_line_parts = first_line.rsplit(':', 3)
path, line, warning_class, message = first_line_parts
line = int(line)
self.assertEqual(expected_file, path)
self.assertEqual(warning_class, ' ' + UserWarning.__name__)
self.assertEqual(message, ' ' + text)
expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
assert expected_line
self.assertEqual(second_line, expected_line)
def test_filename_none(self):
s_dict['__file__']
try:
catch = original_warnings.catch_warnings(record=True,
module=self.module)
with catch as w:
self.module.filterwarnings("always", category=UserWarning)
globals_dict['__file__'] = None
original_warnings.warn('test', UserWarning)
self.assertTrue(len(w))
finally:
globals_dict['__file__'] = oldfile
def test_stderr_none(self):
rc, stdout, stderr = assert_python_ok("-c",
"import sys; sys.stderr = None; "
"import warnings; warnings.simplefilter('always'); "
"warnings.warn('Warning!')")
self.assertEqual(stdout, b'')
self.assertNotIn(b'Warning!', stderr)
self.assertNotIn(b'Error', stderr)
def test_issue31285(self):
def get_bad_loader(splitlines_ret_val):
class BadLoader:
def get_source(self, fullname):
class BadSource(str):
def splitlines(self):
return splitlines_ret_val
return BadSource('spam')
return BadLoader()
wmod = self.module
with original_warnings.catch_warnings(module=wmod):
wmod.filterwarnings('default', category=UserWarning)
with support.captured_stderr() as stderr:
wmod.warn_explicit(
'foo', UserWarning, 'bar', 1,
module_globals={'__loader__': get_bad_loader(42),
'__name__': 'foobar'})
self.assertIn('UserWarning: foo', stderr.getvalue())
show = wmod._showwarnmsg
try:
del wmod._showwarnmsg
with support.captured_stderr() as stderr:
wmod.warn_explicit(
'eggs', UserWarning, 'bar', 1,
module_globals={'__loader__': get_bad_loader([42]),
'__name__': 'foobar'})
self.assertIn('UserWarning: eggs', stderr.getvalue())
finally:
wmod._showwarnmsg = show
@support.cpython_only
def test_issue31411(self):
# warnings.onceregistry isn't a dictionary.
wmod = self.module
with original_warnings.catch_warnings(module=wmod):
wmod.filterwarnings('once')
with support.swap_attr(wmod, 'onceregistry', None):
with self.assertRaises(TypeError):
wmod.warn_explicit('foo', Warning, 'bar', 1, registry=None)
@support.cpython_only
def test_issue31416(self):
# bad warnings.filters or warnings.defaultaction.
wmod = self.module
with original_warnings.catch_warnings(module=wmod):
wmod.filters = [(None, None, Warning, None, 0)]
with self.assertRaises(TypeError):
wmod.warn_explicit('foo', Warning, 'bar', 1)
wmod.filters = []
with support.swap_attr(wmod, 'defaultaction', None), \
self.assertRaises(TypeError):
wmod.warn_explicit('foo', Warning, 'bar', 1)
@support.cpython_only
def test_issue31566(self):
# warn() shouldn't cause an assertion failure in case of a bad
with original_warnings.catch_warnings(module=self.module):
self.module.filterwarnings('error', category=UserWarning)
with support.swap_item(globals(), '__name__', b'foo'), \
support.swap_item(globals(), '__file__', None):
self.assertRaises(UserWarning, self.module.warn, 'bar')
class WarningsDisplayTests(BaseTest):
def test_formatwarning(self):
message = "msg"
category = Warning
file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
line_num = 3
file_line = linecache.getline(file_name, line_num).strip()
format = "%s:%s: %s: %s\n %s\n"
expect = format % (file_name, line_num, category.__name__, message,
file_line)
self.assertEqual(expect, self.module.formatwarning(message,
category, file_name, line_num))
file_line += " for the win!"
expect = format % (file_name, line_num, category.__name__, message,
file_line)
self.assertEqual(expect, self.module.formatwarning(message,
category, file_name, line_num, file_line))
def test_showwarning(self):
file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
line_num = 3
expected_file_line = linecache.getline(file_name, line_num).strip()
message = 'msg'
category = Warning
file_object = StringIO()
expect = self.module.formatwarning(message, category, file_name,
line_num)
self.module.showwarning(message, category, file_name, line_num,
file_object)
self.assertEqual(file_object.getvalue(), expect)
expected_file_line += "for the win!"
expect = self.module.formatwarning(message, category, file_name,
line_num, expected_file_line)
file_object = StringIO()
self.module.showwarning(message, category, file_name, line_num,
file_object, expected_file_line)
self.assertEqual(expect, file_object.getvalue())
def test_formatwarning_override(self):
def myformatwarning(message, category, filename, lineno, text):
return f'm={message}:c={category}:f={filename}:l={lineno}:t={text}'
file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
line_num = 3
file_line = linecache.getline(file_name, line_num).strip()
message = 'msg'
category = Warning
file_object = StringIO()
expected = f'm={message}:c={category}:f={file_name}:l={line_num}' + \
f':t={file_line}'
with support.swap_attr(self.module, 'formatwarning', myformatwarning):
self.module.showwarning(message, category, file_name, line_num,
file_object, file_line)
self.assertEqual(file_object.getvalue(), expected)
class CWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase):
module = c_warnings
class PyWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase):
module = py_warnings
def test_tracemalloc(self):
self.addCleanup(os_helper.unlink, os_helper.TESTFN)
with open(os_helper.TESTFN, 'w', encoding="utf-8") as fp:
fp.write(textwrap.dedent("""
def func():
f = open(__file__, "rb")
# Emit ResourceWarning
f = None
func()
"""))
def run(*args):
res = assert_python_ok(*args, PYTHONIOENCODING='utf-8')
stderr = res.err.decode('utf-8', 'replace')
stderr = '\n'.join(stderr.splitlines())
stderr = re.sub('<.*>', '<...>', stderr)
return stderr
filename = os.path.abspath(os_helper.TESTFN)
stderr = run('-Wd', os_helper.TESTFN)
expected = textwrap.dedent(f'''
{filename}:5: ResourceWarning: unclosed file <...>
f = None
ResourceWarning: Enable tracemalloc to get the object allocation traceback
''').strip()
self.assertEqual(stderr, expected)
stderr = run('-Wd', '-X', 'tracemalloc=2', os_helper.TESTFN)
expected = textwrap.dedent(f'''
{filename}:5: ResourceWarning: unclosed file <...>
f = None
Object allocated at (most recent call last):
File "{filename}", lineno 7
func()
File "{filename}", lineno 3
f = open(__file__, "rb")
''').strip()
self.assertEqual(stderr, expected)
class CatchWarningTests(BaseTest):
def test_catch_warnings_restore(self):
wmod = self.module
orig_filters = wmod.filters
orig_showwarning = wmod.showwarning
with wmod.catch_warnings(module=wmod, record=True):
wmod.filters = wmod.showwarning = object()
self.assertIs(wmod.filters, orig_filters)
self.assertIs(wmod.showwarning, orig_showwarning)
with wmod.catch_warnings(module=wmod, record=False):
wmod.filters = wmod.showwarning = object()
self.assertIs(wmod.filters, orig_filters)
self.assertIs(wmod.showwarning, orig_showwarning)
def test_catch_warnings_recording(self):
wmod = self.module
with wmod.catch_warnings(module=wmod, record=True) as w:
self.assertEqual(w, [])
self.assertIs(type(w), list)
wmod.simplefilter("always")
wmod.warn("foo")
self.assertEqual(str(w[-1].message), "foo")
wmod.warn("bar")
self.assertEqual(str(w[-1].message), "bar")
self.assertEqual(str(w[0].message), "foo")
self.assertEqual(str(w[1].message), "bar")
del w[:]
self.assertEqual(w, [])
orig_showwarning = wmod.showwarning
with wmod.catch_warnings(module=wmod, record=False) as w:
self.assertIsNone(w)
self.assertIs(wmod.showwarning, orig_showwarning)
def test_catch_warnings_reentry_guard(self):
wmod = self.module
x = wmod.catch_warnings(module=wmod, record=True)
self.assertRaises(RuntimeError, x.__exit__)
with x:
self.assertRaises(RuntimeError, x.__enter__)
x = wmod.catch_warnings(module=wmod, record=False)
self.assertRaises(RuntimeError, x.__exit__)
with x:
self.assertRaises(RuntimeError, x.__enter__)
def test_catch_warnings_defaults(self):
wmod = self.module
orig_filters = wmod.filters
orig_showwarning = wmod.showwarning
with wmod.catch_warnings(module=wmod) as w:
self.assertIsNone(w)
self.assertIs(wmod.showwarning, orig_showwarning)
self.assertIsNot(wmod.filters, orig_filters)
self.assertIs(wmod.filters, orig_filters)
if wmod is sys.modules['warnings']:
with wmod.catch_warnings() as w:
self.assertIsNone(w)
self.assertIs(wmod.showwarning, orig_showwarning)
self.assertIsNot(wmod.filters, orig_filters)
self.assertIs(wmod.filters, orig_filters)
def test_record_override_showwarning_before(self):
self.module
my_log = []
def my_logger(message, category, filename, lineno, file=None, line=None):
nonlocal my_log
my_log.append(message)
with support.swap_attr(wmod, 'showwarning', my_logger):
with wmod.catch_warnings(module=wmod, record=True) as log:
self.assertIsNot(wmod.showwarning, my_logger)
wmod.simplefilter("always")
wmod.warn(text)
self.assertIs(wmod.showwarning, my_logger)
self.assertEqual(len(log), 1, log)
self.assertEqual(log[0].message.args[0], text)
self.assertEqual(my_log, [])
def test_record_override_showwarning_inside(self):
= self.module
my_log = []
def my_logger(message, category, filename, lineno, file=None, line=None):
nonlocal my_log
my_log.append(message)
with wmod.catch_warnings(module=wmod, record=True) as log:
wmod.simplefilter("always")
wmod.showwarning = my_logger
wmod.warn(text)
self.assertEqual(len(my_log), 1, my_log)
self.assertEqual(my_log[0].args[0], text)
self.assertEqual(log, [])
def test_check_warnings(self):
wmod = self.module
if wmod is not sys.modules['warnings']:
self.skipTest('module to test is not loaded warnings module')
with warnings_helper.check_warnings(quiet=False) as w:
self.assertEqual(w.warnings, [])
wmod.simplefilter("always")
wmod.warn("foo")
self.assertEqual(str(w.message), "foo")
wmod.warn("bar")
self.assertEqual(str(w.message), "bar")
self.assertEqual(str(w.warnings[0].message), "foo")
self.assertEqual(str(w.warnings[1].message), "bar")
w.reset()
self.assertEqual(w.warnings, [])
with warnings_helper.check_warnings():
pass
with warnings_helper.check_warnings(('foo', UserWarning)):
wmod.warn("foo")
with self.assertRaises(AssertionError):
with warnings_helper.check_warnings(('', RuntimeWarning)):
pass
with self.assertRaises(AssertionError):
with warnings_helper.check_warnings(('foo', RuntimeWarning)):
wmod.warn("foo")
class CCatchWarningTests(CatchWarningTests, unittest.TestCase):
module = c_warnings
class PyCatchWarningTests(CatchWarningTests, unittest.TestCase):
module = py_warnings
class EnvironmentVariableTests(BaseTest):
def test_single_warning(self):
rc, stdout, stderr = assert_python_ok("-c",
"import sys; sys.stdout.write(str(sys.warnoptions))",
PYTHONWARNINGS="ignore::DeprecationWarning",
PYTHONDEVMODE="")
self.assertEqual(stdout, b"['ignore::DeprecationWarning']")
def test_comma_separated_warnings(self):
rc, stdout, stderr = assert_python_ok("-c",
"import sys; sys.stdout.write(str(sys.warnoptions))",
PYTHONWARNINGS="ignore::DeprecationWarning,ignore::UnicodeWarning",
PYTHONDEVMODE="")
self.assertEqual(stdout,
b"['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
def test_envvar_and_command_line(self):
rc, stdout, stderr = assert_python_ok("-Wignore::UnicodeWarning", "-c",
"import sys; sys.stdout.write(str(sys.warnoptions))",
PYTHONWARNINGS="ignore::DeprecationWarning",
PYTHONDEVMODE="")
self.assertEqual(stdout,
b"['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
def test_conflicting_envvar_and_command_line(self):
rc, stdout, stderr = assert_python_failure("-Werror::DeprecationWarning", "-c",
"import sys, warnings; sys.stdout.write(str(sys.warnoptions)); "
"warnings.warn('Message', DeprecationWarning)",
PYTHONWARNINGS="default::DeprecationWarning",
PYTHONDEVMODE="")
self.assertEqual(stdout,
b"['default::DeprecationWarning', 'error::DeprecationWarning']")
self.assertEqual(stderr.splitlines(),
[b"Traceback (most recent call last):",
b" File \"<string>\", line 1, in <module>",
b"DeprecationWarning: Message"])
def test_default_filter_configuration(self):
pure_python_api = self.module is py_warnings
if Py_DEBUG:
expected_default_filters = []
else:
if pure_python_api:
main_module_filter = re.compile("__main__")
else:
main_module_filter = "__main__"
expected_default_filters = [
('default', None, DeprecationWarning, main_module_filter, 0),
('ignore', None, DeprecationWarning, None, 0),
('ignore', None, PendingDeprecationWarning, None, 0),
('ignore', None, ImportWarning, None, 0),
('ignore', None, ResourceWarning, None, 0),
]
expected_output = [str(f).encode() for f in expected_default_filters]
if pure_python_api:
code = "import sys; sys.modules.pop('warnings', None); sys.modules['_warnings'] = None; "
else:
code = ""
code += "import warnings; [print(f) for f in warnings.filters]"
rc, stdout, stderr = assert_python_ok("-c", code, __isolated=True)
stdout_lines = [line.strip() for line in stdout.splitlines()]
self.maxDiff = None
self.assertEqual(stdout_lines, expected_output)
@unittest.skipUnless(sys.getfilesystemencoding() != 'ascii',
'requires non-ascii filesystemencoding')
def test_nonascii(self):
PYTHONWARNINGS="ignore:DeprecationWarning" + os_helper.FS_NONASCII
rc, stdout, stderr = assert_python_ok("-c",
"import sys; sys.stdout.write(str(sys.warnoptions))",
PYTHONIOENCODING="utf-8",
PYTHONWARNINGS=PYTHONWARNINGS,
PYTHONDEVMODE="")
self.assertEqual(stdout, str([PYTHONWARNINGS]).encode())
class CEnvironmentVariableTests(EnvironmentVariableTests, unittest.TestCase):
module = c_warnings
class PyEnvironmentVariableTests(EnvironmentVariableTests, unittest.TestCase):
module = py_warnings
class _DeprecatedTest(BaseTest, unittest.TestCase):
module = original_warnings
def test_warning(self):
version = (3, 11, 0, "final", 0)
test = [(4, 12), (4, 11), (4, 0), (3, 12)]
for remove in test:
msg = rf".*test_warnings.*{remove[0]}\.{remove[1]}"
filter = msg, DeprecationWarning
with self.subTest(remove=remove):
with warnings_helper.check_warnings(filter, quiet=False):
self.module._deprecated("test_warnings", remove=remove,
_version=version)
version = (3, 11, 0, "alpha", 0)
msg = r".*test_warnings.*3\.11"
with warnings_helper.check_warnings((msg, DeprecationWarning), quiet=False):
self.module._deprecated("test_warnings", remove=(3, 11),
_version=version)
def test_RuntimeError(self):
version = (3, 11, 0, "final", 0)
test = [(2, 0), (2, 12), (3, 10)]
for remove in test:
with self.subTest(remove=remove):
with self.assertRaises(RuntimeError):
self.module._deprecated("test_warnings", remove=remove,
_version=version)
for level in ["beta", "candidate", "final"]:
version = (3, 11, 0, level, 0)
with self.subTest(releaselevel=level):
with self.assertRaises(RuntimeError):
self.module._deprecated("test_warnings", remove=(3, 11),
_version=version)
class BootstrapTest(unittest.TestCase):
def test_issue_8766(self):
with os_helper.temp_cwd() as cwd, os_helper.temp_cwd('encodings'):
assert_python_ok('-c', 'pass', PYTHONPATH=cwd)
assert_python_ok('-c', 'pass', '-W', 'always', PYTHONPATH=cwd)
class FinalizationTest(unittest.TestCase):
def test_finalization(self):
ings
warn = warnings.warn
class A:
def __del__(self):
warn("test")
a=A()
"""
rc, out, err = assert_python_ok("-c", code)
self.assertEqual(err.decode().rstrip(),
'<string>:7: UserWarning: test')
def test_late_resource_warning(self):
nclosed file "
# (_warnings will try to import it)
code = "f = open(%a)" % __file__
rc, out, err = assert_python_ok("-Wd", "-c", code)
self.assertTrue(err.startswith(expected), ascii(err))
# import the warnings module
code = "import warnings; f = open(%a)" % __file__
rc, out, err = assert_python_ok("-Wd", "-c", code)
self.assertTrue(err.startswith(expected), ascii(err))
def setUpModule():
py_warnings.onceregistry.clear()
c_warnings.onceregistry.clear()
tearDownModule = setUpModule
if __name__ == "__main__":
unittest.main()
| true | true |
f7f9321352b170d5736d58318b4db4e396c74ccd | 1,030 | py | Python | Exercicios/ex085.py | vincytarsis/Python | f98005917486bc191c85c971ec8e2c71fb9dd4c7 | [
"MIT"
] | null | null | null | Exercicios/ex085.py | vincytarsis/Python | f98005917486bc191c85c971ec8e2c71fb9dd4c7 | [
"MIT"
] | null | null | null | Exercicios/ex085.py | vincytarsis/Python | f98005917486bc191c85c971ec8e2c71fb9dd4c7 | [
"MIT"
] | null | null | null | """ Crie um programa onde o usuário possa digitar sete valores numéricos e cadastre-os em uma
lista única que mantenha separados os valores pares e impares. No final, mostre os valores
pares e ímpares em ordem crescente. """
'''princ = []
par = []
imp = []
#Ler 7 valores numéricos
for c in range(1, 8):
n = int(input(f'Digite o {c}°. valor:'))
if n % 2 == 0:
par.append(n)
else:
imp.append(n)
# Cadastrar em uma lista única
princ.extend(par)
princ.extend(imp)
imp.clear()
par.clear()
#Separ pares e impares
p = 0
if princ[p] % 2 ==0:
print(princ)
p +=1
else:
print(princ)
p+=1
#print(par)
#print(imp)
#Mostre os valores separados'''
#Guanabara
num = [[], []]
valor = 0
for c in range(1, 8):
valor = int(input(f'Digite {c}° o valor'))
if valor % 2 == 0:
num[0].append(valor)
else:
num[1].append(valor)
num[0].sort()
num[1].sort()
print(f'Os valores pares digitados foram {num[0]}')
print(f'Os valores impares digitados foram {num[1]}') | 22.888889 | 93 | 0.615534 |
num = [[], []]
valor = 0
for c in range(1, 8):
valor = int(input(f'Digite {c}° o valor'))
if valor % 2 == 0:
num[0].append(valor)
else:
num[1].append(valor)
num[0].sort()
num[1].sort()
print(f'Os valores pares digitados foram {num[0]}')
print(f'Os valores impares digitados foram {num[1]}') | true | true |
f7f932cf1cd9224ccb32b68b38b9ae5edee94239 | 1,174 | py | Python | app/models/campaign.py | chiatk/tforty-api | 8b2a2f32389201303208b8f2a7711dbcd73c8569 | [
"Apache-2.0"
] | null | null | null | app/models/campaign.py | chiatk/tforty-api | 8b2a2f32389201303208b8f2a7711dbcd73c8569 | [
"Apache-2.0"
] | null | null | null | app/models/campaign.py | chiatk/tforty-api | 8b2a2f32389201303208b8f2a7711dbcd73c8569 | [
"Apache-2.0"
] | null | null | null | from re import T
from sqlalchemy import Column, Table, ForeignKey
from sqlalchemy.sql.sqltypes import Integer, String, DateTime, Boolean
from sqlalchemy.sql.functions import func
from ..database.connection_mysql import meta
campaigns = Table(
"campaigns",
meta,
Column( "id", Integer, primary_key=True ),
Column( "created", DateTime(timezone=True), server_default=func.now() ),
Column( "updated", DateTime(timezone=True), onupdate=func.now() ),
Column( "user_id", Integer, ForeignKey("users.id"), nullable=False ),
Column( "active", Boolean ),
Column( "title", String(250) ),
Column( "chia_wallet", String(255) ),
Column( "country_id", Integer ),
Column( "short_desc", String(250) ),
Column( "card_image_url", String(250) ),
Column( "category", String(250) ),
Column( "duration", Integer ),
Column( "video_url", String(250) ),
Column( "video_overlay_image_url", String(250) ),
Column( "cover_image_url", String(250) ),
Column( "story", String(250) ),
Column( "goal", Integer ),
Column( "campaign_type_id", Integer ),
Column( "founded", Boolean ),
Column( "current_balance", Integer )
) | 39.133333 | 76 | 0.67121 | from re import T
from sqlalchemy import Column, Table, ForeignKey
from sqlalchemy.sql.sqltypes import Integer, String, DateTime, Boolean
from sqlalchemy.sql.functions import func
from ..database.connection_mysql import meta
campaigns = Table(
"campaigns",
meta,
Column( "id", Integer, primary_key=True ),
Column( "created", DateTime(timezone=True), server_default=func.now() ),
Column( "updated", DateTime(timezone=True), onupdate=func.now() ),
Column( "user_id", Integer, ForeignKey("users.id"), nullable=False ),
Column( "active", Boolean ),
Column( "title", String(250) ),
Column( "chia_wallet", String(255) ),
Column( "country_id", Integer ),
Column( "short_desc", String(250) ),
Column( "card_image_url", String(250) ),
Column( "category", String(250) ),
Column( "duration", Integer ),
Column( "video_url", String(250) ),
Column( "video_overlay_image_url", String(250) ),
Column( "cover_image_url", String(250) ),
Column( "story", String(250) ),
Column( "goal", Integer ),
Column( "campaign_type_id", Integer ),
Column( "founded", Boolean ),
Column( "current_balance", Integer )
) | true | true |
f7f9334d06b2ed9e4fbcf3f0d4789d12ed9cc1ef | 255 | py | Python | dump-glyphs-rules.py | simoncozens/nastaliq-engineering | 4785bbfd115d9a11fb90a48546e2e2a9c758fecf | [
"Apache-2.0"
] | 5 | 2020-10-16T17:49:39.000Z | 2021-03-09T13:18:14.000Z | dump-glyphs-rules.py | simoncozens/nastaliq-engineering | 4785bbfd115d9a11fb90a48546e2e2a9c758fecf | [
"Apache-2.0"
] | null | null | null | dump-glyphs-rules.py | simoncozens/nastaliq-engineering | 4785bbfd115d9a11fb90a48546e2e2a9c758fecf | [
"Apache-2.0"
] | null | null | null | import csv
from glyphsLib import GSFont
import sys
font = GSFont(sys.argv[1])
conn = font.userData["nastaliqConnections"]
with open('rules.csv', 'w') as outcsv:
w = csv.DictWriter(outcsv,conn["colnames"])
w.writeheader()
w.writerows(conn["rows"])
| 21.25 | 45 | 0.717647 | import csv
from glyphsLib import GSFont
import sys
font = GSFont(sys.argv[1])
conn = font.userData["nastaliqConnections"]
with open('rules.csv', 'w') as outcsv:
w = csv.DictWriter(outcsv,conn["colnames"])
w.writeheader()
w.writerows(conn["rows"])
| true | true |
f7f933a059433dd754baad8c39b4d0e83e5203c5 | 7,854 | py | Python | integration_tests/test_upgrade.py | tomtau/chain-main | b45fdbbfa25e9f266098f920f3d5ef2cb5742091 | [
"Apache-2.0"
] | null | null | null | integration_tests/test_upgrade.py | tomtau/chain-main | b45fdbbfa25e9f266098f920f3d5ef2cb5742091 | [
"Apache-2.0"
] | null | null | null | integration_tests/test_upgrade.py | tomtau/chain-main | b45fdbbfa25e9f266098f920f3d5ef2cb5742091 | [
"Apache-2.0"
] | null | null | null | import configparser
import json
import re
import subprocess
import time
from datetime import datetime, timedelta, timezone
from pathlib import Path
import pytest
from dateutil.parser import isoparse
from pystarport.cluster import SUPERVISOR_CONFIG_FILE
from pystarport.ports import rpc_port
from .utils import (
cluster_fixture,
parse_events,
wait_for_block,
wait_for_block_time,
wait_for_port,
)
def edit_chain_program(ini_path, callback):
# edit node process config in supervisor
ini = configparser.RawConfigParser()
ini.read_file(ini_path.open())
reg = re.compile(r"^program:node(\d+)")
for section in ini.sections():
m = reg.match(section)
if m:
i = m.group(1)
old = ini[section]
ini[section].update(callback(i, old))
with ini_path.open("w") as fp:
ini.write(fp)
def post_init(config, data):
"""
change to use cosmovisor
"""
def prepare_node(i, _):
# prepare cosmovisor directory
home = data / f"node{i}"
cosmovisor = home / "cosmovisor"
cosmovisor.mkdir()
subprocess.run(
[
"nix-build",
Path(__file__).parent / "upgrade-test.nix",
"-o",
cosmovisor / "upgrades",
],
check=True,
)
(cosmovisor / "genesis").symlink_to("./upgrades/genesis")
return {
"command": f"cosmovisor start --home %(here)s/node{i}",
"environment": f"DAEMON_NAME=chain-maind,DAEMON_HOME={home.absolute()}",
}
edit_chain_program(data / SUPERVISOR_CONFIG_FILE, prepare_node)
# use function scope to re-initialize for each test case
@pytest.fixture(scope="function")
def cosmovisor_cluster(pytestconfig, tmp_path_factory):
"override cluster fixture for this test module"
yield from cluster_fixture(
Path(__file__).parent / "configs/default.yaml",
26900,
tmp_path_factory,
quiet=pytestconfig.getoption("supervisord-quiet"),
post_init=post_init,
enable_cov=False,
)
@pytest.mark.slow
def test_cosmovisor(cosmovisor_cluster):
"""
- propose an upgrade and pass it
- wait for it to happen
- it should work transparently
"""
cluster = cosmovisor_cluster
height = cluster.block_height()
target_height = height + 15
print("upgrade height", target_height)
plan_name = "upgrade-test"
rsp = cluster.gov_propose(
"community",
"software-upgrade",
{
"name": plan_name,
"title": "upgrade test",
"description": "ditto",
"upgrade-height": target_height,
"deposit": "10000000basecro",
},
)
assert rsp["code"] == 0, rsp
# get proposal_id
ev = parse_events(rsp["logs"])["submit_proposal"]
assert ev["proposal_type"] == "SoftwareUpgrade", rsp
proposal_id = ev["proposal_id"]
rsp = cluster.gov_vote("validator", proposal_id, "yes")
assert rsp["code"] == 0, rsp["raw_log"]
rsp = cluster.gov_vote("validator", proposal_id, "yes", i=1)
assert rsp["code"] == 0, rsp["raw_log"]
proposal = cluster.query_proposal(proposal_id)
wait_for_block_time(cluster, isoparse(proposal["voting_end_time"]))
proposal = cluster.query_proposal(proposal_id)
assert proposal["status"] == "PROPOSAL_STATUS_PASSED", proposal
# block should just pass the target height
wait_for_block(cluster, target_height + 2)
def propose_and_pass(cluster, kind, proposal):
rsp = cluster.gov_propose(
"community",
kind,
proposal,
)
assert rsp["code"] == 0, rsp["raw_log"]
# get proposal_id
ev = parse_events(rsp["logs"])["submit_proposal"]
assert ev["proposal_type"] == kind.title().replace("-", ""), rsp
proposal_id = ev["proposal_id"]
proposal = cluster.query_proposal(proposal_id)
assert proposal["status"] == "PROPOSAL_STATUS_VOTING_PERIOD", proposal
rsp = cluster.gov_vote("validator", proposal_id, "yes")
assert rsp["code"] == 0, rsp["raw_log"]
rsp = cluster.gov_vote("validator", proposal_id, "yes", i=1)
assert rsp["code"] == 0, rsp["raw_log"]
proposal = cluster.query_proposal(proposal_id)
wait_for_block_time(cluster, isoparse(proposal["voting_end_time"]))
proposal = cluster.query_proposal(proposal_id)
assert proposal["status"] == "PROPOSAL_STATUS_PASSED", proposal
return proposal
@pytest.mark.slow
def test_manual_upgrade(cosmovisor_cluster):
"""
- do the upgrade test by replacing binary manually
- check the panic do happens
"""
cluster = cosmovisor_cluster
# use the normal binary first
edit_chain_program(
cluster.data_dir / SUPERVISOR_CONFIG_FILE,
lambda i, _: {
"command": f"%(here)s/node{i}/cosmovisor/genesis/bin/chain-maind start "
f"--home %(here)s/node{i}"
},
)
cluster.supervisor.stopAllProcesses()
cluster.restart_supervisor()
time.sleep(5) # FIXME the port seems still exists for a while after process stopped
wait_for_port(rpc_port(cluster.config["validators"][0]["base_port"]))
target_height = cluster.block_height() + 15
print("upgrade height", target_height)
plan_name = "upgrade-test"
propose_and_pass(
cluster,
"software-upgrade",
{
"name": plan_name,
"title": "upgrade test",
"description": "ditto",
"upgrade-height": target_height,
"deposit": "10000000basecro",
},
)
# wait for upgrade plan activated
wait_for_block(cluster, target_height)
# wait a little bit
time.sleep(0.5)
# check nodes are all stopped
assert cluster.supervisor.getProcessInfo("node0")["state"] != "RUNNING"
assert cluster.supervisor.getProcessInfo("node1")["state"] != "RUNNING"
# check upgrade-info.json file is written
assert (
json.load((cluster.home(0) / "data/upgrade-info.json").open())
== json.load((cluster.home(1) / "data/upgrade-info.json").open())
== {
"name": plan_name,
"height": target_height,
}
)
# use the upgrade-test binary
edit_chain_program(
cluster.data_dir / SUPERVISOR_CONFIG_FILE,
lambda i, _: {
"command": (
f"%(here)s/node{i}/cosmovisor/upgrades/upgrade-test/bin/chain-maind "
f"start --home %(here)s/node{i}"
)
},
)
cluster.restart_supervisor()
# wait for it to generate new blocks
wait_for_block(cluster, target_height + 2)
@pytest.mark.slow
def test_cancel_upgrade(cluster):
"""
use default cluster
- propose upgrade and pass it
- cancel the upgrade before execution
"""
plan_name = "upgrade-test"
# 25 = voting_period * 2 + 5
upgrade_time = datetime.utcnow() + timedelta(seconds=25)
print("propose upgrade plan")
print("upgrade time", upgrade_time)
propose_and_pass(
cluster,
"software-upgrade",
{
"name": plan_name,
"title": "upgrade test",
"description": "ditto",
"upgrade-time": upgrade_time.replace(tzinfo=None).isoformat("T") + "Z",
"deposit": "10000000basecro",
},
)
print("cancel upgrade plan")
propose_and_pass(
cluster,
"cancel-software-upgrade",
{
"title": "there's bug, cancel upgrade",
"description": "there's bug, cancel upgrade",
"deposit": "10000000basecro",
},
)
# wait for blocks after upgrade, should success since upgrade is canceled
wait_for_block_time(
cluster, upgrade_time.replace(tzinfo=timezone.utc) + timedelta(seconds=1)
)
| 29.863118 | 88 | 0.622995 | import configparser
import json
import re
import subprocess
import time
from datetime import datetime, timedelta, timezone
from pathlib import Path
import pytest
from dateutil.parser import isoparse
from pystarport.cluster import SUPERVISOR_CONFIG_FILE
from pystarport.ports import rpc_port
from .utils import (
cluster_fixture,
parse_events,
wait_for_block,
wait_for_block_time,
wait_for_port,
)
def edit_chain_program(ini_path, callback):
ini = configparser.RawConfigParser()
ini.read_file(ini_path.open())
reg = re.compile(r"^program:node(\d+)")
for section in ini.sections():
m = reg.match(section)
if m:
i = m.group(1)
old = ini[section]
ini[section].update(callback(i, old))
with ini_path.open("w") as fp:
ini.write(fp)
def post_init(config, data):
def prepare_node(i, _):
home = data / f"node{i}"
cosmovisor = home / "cosmovisor"
cosmovisor.mkdir()
subprocess.run(
[
"nix-build",
Path(__file__).parent / "upgrade-test.nix",
"-o",
cosmovisor / "upgrades",
],
check=True,
)
(cosmovisor / "genesis").symlink_to("./upgrades/genesis")
return {
"command": f"cosmovisor start --home %(here)s/node{i}",
"environment": f"DAEMON_NAME=chain-maind,DAEMON_HOME={home.absolute()}",
}
edit_chain_program(data / SUPERVISOR_CONFIG_FILE, prepare_node)
@pytest.fixture(scope="function")
def cosmovisor_cluster(pytestconfig, tmp_path_factory):
yield from cluster_fixture(
Path(__file__).parent / "configs/default.yaml",
26900,
tmp_path_factory,
quiet=pytestconfig.getoption("supervisord-quiet"),
post_init=post_init,
enable_cov=False,
)
@pytest.mark.slow
def test_cosmovisor(cosmovisor_cluster):
cluster = cosmovisor_cluster
height = cluster.block_height()
target_height = height + 15
print("upgrade height", target_height)
plan_name = "upgrade-test"
rsp = cluster.gov_propose(
"community",
"software-upgrade",
{
"name": plan_name,
"title": "upgrade test",
"description": "ditto",
"upgrade-height": target_height,
"deposit": "10000000basecro",
},
)
assert rsp["code"] == 0, rsp
ev = parse_events(rsp["logs"])["submit_proposal"]
assert ev["proposal_type"] == "SoftwareUpgrade", rsp
proposal_id = ev["proposal_id"]
rsp = cluster.gov_vote("validator", proposal_id, "yes")
assert rsp["code"] == 0, rsp["raw_log"]
rsp = cluster.gov_vote("validator", proposal_id, "yes", i=1)
assert rsp["code"] == 0, rsp["raw_log"]
proposal = cluster.query_proposal(proposal_id)
wait_for_block_time(cluster, isoparse(proposal["voting_end_time"]))
proposal = cluster.query_proposal(proposal_id)
assert proposal["status"] == "PROPOSAL_STATUS_PASSED", proposal
wait_for_block(cluster, target_height + 2)
def propose_and_pass(cluster, kind, proposal):
rsp = cluster.gov_propose(
"community",
kind,
proposal,
)
assert rsp["code"] == 0, rsp["raw_log"]
ev = parse_events(rsp["logs"])["submit_proposal"]
assert ev["proposal_type"] == kind.title().replace("-", ""), rsp
proposal_id = ev["proposal_id"]
proposal = cluster.query_proposal(proposal_id)
assert proposal["status"] == "PROPOSAL_STATUS_VOTING_PERIOD", proposal
rsp = cluster.gov_vote("validator", proposal_id, "yes")
assert rsp["code"] == 0, rsp["raw_log"]
rsp = cluster.gov_vote("validator", proposal_id, "yes", i=1)
assert rsp["code"] == 0, rsp["raw_log"]
proposal = cluster.query_proposal(proposal_id)
wait_for_block_time(cluster, isoparse(proposal["voting_end_time"]))
proposal = cluster.query_proposal(proposal_id)
assert proposal["status"] == "PROPOSAL_STATUS_PASSED", proposal
return proposal
@pytest.mark.slow
def test_manual_upgrade(cosmovisor_cluster):
cluster = cosmovisor_cluster
edit_chain_program(
cluster.data_dir / SUPERVISOR_CONFIG_FILE,
lambda i, _: {
"command": f"%(here)s/node{i}/cosmovisor/genesis/bin/chain-maind start "
f"--home %(here)s/node{i}"
},
)
cluster.supervisor.stopAllProcesses()
cluster.restart_supervisor()
time.sleep(5)
wait_for_port(rpc_port(cluster.config["validators"][0]["base_port"]))
target_height = cluster.block_height() + 15
print("upgrade height", target_height)
plan_name = "upgrade-test"
propose_and_pass(
cluster,
"software-upgrade",
{
"name": plan_name,
"title": "upgrade test",
"description": "ditto",
"upgrade-height": target_height,
"deposit": "10000000basecro",
},
)
wait_for_block(cluster, target_height)
time.sleep(0.5)
assert cluster.supervisor.getProcessInfo("node0")["state"] != "RUNNING"
assert cluster.supervisor.getProcessInfo("node1")["state"] != "RUNNING"
assert (
json.load((cluster.home(0) / "data/upgrade-info.json").open())
== json.load((cluster.home(1) / "data/upgrade-info.json").open())
== {
"name": plan_name,
"height": target_height,
}
)
edit_chain_program(
cluster.data_dir / SUPERVISOR_CONFIG_FILE,
lambda i, _: {
"command": (
f"%(here)s/node{i}/cosmovisor/upgrades/upgrade-test/bin/chain-maind "
f"start --home %(here)s/node{i}"
)
},
)
cluster.restart_supervisor()
wait_for_block(cluster, target_height + 2)
@pytest.mark.slow
def test_cancel_upgrade(cluster):
plan_name = "upgrade-test"
upgrade_time = datetime.utcnow() + timedelta(seconds=25)
print("propose upgrade plan")
print("upgrade time", upgrade_time)
propose_and_pass(
cluster,
"software-upgrade",
{
"name": plan_name,
"title": "upgrade test",
"description": "ditto",
"upgrade-time": upgrade_time.replace(tzinfo=None).isoformat("T") + "Z",
"deposit": "10000000basecro",
},
)
print("cancel upgrade plan")
propose_and_pass(
cluster,
"cancel-software-upgrade",
{
"title": "there's bug, cancel upgrade",
"description": "there's bug, cancel upgrade",
"deposit": "10000000basecro",
},
)
wait_for_block_time(
cluster, upgrade_time.replace(tzinfo=timezone.utc) + timedelta(seconds=1)
)
| true | true |
f7f933c87fdfd9fadc2004166a7c0687c5ea3056 | 21,418 | py | Python | tutorials/declarative_tutorial.py | Matze77/MetPy | 23c01414dd4141b0a83f5aa51b6e92db2c6d0fb6 | [
"BSD-3-Clause"
] | 3 | 2016-03-03T07:51:22.000Z | 2022-02-22T01:22:02.000Z | tutorials/declarative_tutorial.py | Matze77/MetPy | 23c01414dd4141b0a83f5aa51b6e92db2c6d0fb6 | [
"BSD-3-Clause"
] | 188 | 2020-09-10T19:13:48.000Z | 2022-03-30T20:03:34.000Z | tutorials/declarative_tutorial.py | Matze77/MetPy | 23c01414dd4141b0a83f5aa51b6e92db2c6d0fb6 | [
"BSD-3-Clause"
] | 2 | 2016-10-13T22:37:16.000Z | 2020-08-18T17:44:49.000Z | # Copyright (c) 2018 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""
MetPy Declarative Syntax Tutorial
=================================
The declarative syntax that is a part of the MetPy packaged is designed to aid in simple
data exploration and analysis needs by simplifying the plotting context from typical verbose
Python code. The complexity of data wrangling and plotting are hidden behind the simplified
syntax to allow a lower barrier to investigating your data.
"""
#########################################################################
# Imports
# -------
#
# You'll note that the number of imports is smaller due to using the declarative syntax.
# There is no need to import Matplotlib or Cartopy to your code as all of that is done
# behind the scenes.
from datetime import datetime, timedelta
import xarray as xr
import metpy.calc as mpcalc
from metpy.cbook import get_test_data
from metpy.io import metar
from metpy.plots.declarative import (BarbPlot, ContourPlot, FilledContourPlot, MapPanel,
PanelContainer, PlotObs)
from metpy.units import units
#########################################################################
# Getting Data
# ------------
#
# Depending on what kind of data you are wanting to plot you'll use either Xarray (for gridded
# data), Pandas (for CSV data), or the MetPy METAR parser (for METAR data).
#
# We'll start this tutorial by reading in a gridded dataset using Xarray.
# Open the netCDF file as a xarray Dataset and parse the full dataset
data = xr.open_dataset(get_test_data('GFS_test.nc', False)).metpy.parse_cf()
# View a summary of the Dataset
print(data)
#########################################################################
# Set Datetime
# ------------
#
# Set the date/time of that you desire to plot
plot_time = datetime(2010, 10, 26, 12)
#########################################################################
# Subsetting Data
# ---------------
#
# MetPy provides wrappers for the usual xarray indexing and selection routines that can handle
# quantities with units. For DataArrays, MetPy also allows using the coordinate axis types
# mentioned above as aliases for the coordinates. And so, if we wanted data to be just over
# the U.S. for plotting purposes
ds = data.metpy.sel(lat=slice(70, 10), lon=slice(360 - 150, 360 - 55))
#########################################################################
# For full details on xarray indexing/selection, see
# `xarray's documentation <http://xarray.pydata.org/en/stable/indexing.html>`_.
#########################################################################
# Calculations
# ------------
#
# In MetPy 1.0 and later, calculation functions accept Xarray DataArray's as input and the
# output a DataArray that can be easily added to an existing Dataset.
#
# As an example, we calculate wind speed from the wind components and add it as a new variable
# to our Dataset.
ds['wind_speed'] = mpcalc.wind_speed(ds['u-component_of_wind_isobaric'],
ds['v-component_of_wind_isobaric'])
#########################################################################
# Plotting
# --------
#
# With that miniaml preparation, we are now ready to use the simplified plotting syntax to be
# able to plot our data and analyze the meteorological situation.
#
# General Structure
#
# 1. Set contour attributes
#
# 2. Set map characteristics and collect contours
#
# 3. Collect panels and plot
#
# 4. Show (or save) the results
#
# Valid Plotting Types for Gridded Data:
#
# - ``ContourPlot()``
#
# - ``FilledContourPlot()``
#
# - ``ImagePlot()``
#
# - ``PlotBarbs()``
#
# More complete descrptions of these and other plotting types, as well as the map panel and
# panel containter classes are at the end of this tutorial.
#
# Let's plot a 300-hPa map with color-filled wind speed, which we calculated and added to
# our Dataset above, and geopotential heights over the CONUS.
#########################################################################
# We'll start by setting attributes for contours of Geopotential Heights at 300 hPa.
# We need to set at least the data, field, level, and time attributes. We'll set a few others
# to have greater control over hour the data is plotted.
# Set attributes for contours of Geopotential Heights at 300 hPa
cntr2 = ContourPlot()
cntr2.data = ds
cntr2.field = 'Geopotential_height_isobaric'
cntr2.level = 300 * units.hPa
cntr2.time = plot_time
cntr2.contours = list(range(0, 10000, 120))
cntr2.linecolor = 'black'
cntr2.linestyle = 'solid'
cntr2.clabels = True
#########################################################################
# Now we'll set the attributes for plotting color-filled contours of wind speed at 300 hPa.
# Again, the attributes that must be set include data, field, level, and time. We'll also set
# a colormap and colorbar to be purposeful for wind speed. Additionally, we'll set the
# attribute to change the units from m/s to knots, which is the common plotting units for
# wind speed.
# Set attributes for plotting color-filled contours of wind speed at 300 hPa
cfill = FilledContourPlot()
cfill.data = ds
cfill.field = 'wind_speed'
cfill.level = 300 * units.hPa
cfill.time = plot_time
cfill.contours = list(range(10, 201, 20))
cfill.colormap = 'BuPu'
cfill.colorbar = 'horizontal'
cfill.plot_units = 'knot'
#########################################################################
# Once we have our contours (and any colorfill plots) set up, we will want to define the map
# panel that we'll plot the data on. This is the place where we can set the view extent,
# projection of our plot, add map lines like coastlines and states, set a plot title.
# One of the key elements is to add the data to the map panel as a list with the plots
# attribute.
# Set the attributes for the map and add our data to the map
panel = MapPanel()
panel.area = [-125, -74, 20, 55]
panel.projection = 'lcc'
panel.layers = ['states', 'coastline', 'borders']
panel.title = f'{cfill.level.m}-hPa Heights and Wind Speed at {plot_time}'
panel.plots = [cfill, cntr2]
#########################################################################
# Finally we'll collect all of the panels to plot on the figure, set the size of the figure,
# and ultimately show or save the figure.
# Set the attributes for the panel and put the panel in the figure
pc = PanelContainer()
pc.size = (15, 15)
pc.panels = [panel]
#########################################################################
# All of our setting now produce the following map!
# Show the image
pc.show()
#########################################################################
# That's it! What a nice looking map, with relatively simple set of code.
#########################################################################
# Adding Wind Barbs
# -----------------
#
# We can easily add wind barbs to the plot we generated above by adding another plot type
# and adding it to the panel. The plot type for wind barbs is ``PlotBarbs()`` and has its own
# set of attributes to control plotting a vector quantity.
#########################################################################
# We start with setting the attributes that we had before for our 300 hPa plot inlcuding,
# Geopotential Height contours, and color-filled wind speed.
# Set attributes for contours of Geopotential Heights at 300 hPa
cntr2 = ContourPlot()
cntr2.data = ds
cntr2.field = 'Geopotential_height_isobaric'
cntr2.level = 300 * units.hPa
cntr2.time = plot_time
cntr2.contours = list(range(0, 10000, 120))
cntr2.linecolor = 'black'
cntr2.linestyle = 'solid'
cntr2.clabels = True
# Set attributes for plotting color-filled contours of wind speed at 300 hPa
cfill = FilledContourPlot()
cfill.data = ds
cfill.field = 'wind_speed'
cfill.level = 300 * units.hPa
cfill.time = plot_time
cfill.contours = list(range(10, 201, 20))
cfill.colormap = 'BuPu'
cfill.colorbar = 'horizontal'
cfill.plot_units = 'knot'
#########################################################################
# Now we'll set the attributes for plotting wind barbs, with the required attributes of data,
# time, field, and level. The skip attribute is particularly useful for thining the number of
# wind barbs that are plotted on the map and again we'll convert to units of knots.
# Set attributes for plotting wind barbs
barbs = BarbPlot()
barbs.data = ds
barbs.time = plot_time
barbs.field = ['u-component_of_wind_isobaric', 'v-component_of_wind_isobaric']
barbs.level = 300 * units.hPa
barbs.skip = (3, 3)
barbs.plot_units = 'knot'
#########################################################################
# Add all of our plot types to the panel, don't forget to add in the new wind barbs to our plot
# list!
# Set the attributes for the map and add our data to the map
panel = MapPanel()
panel.area = [-125, -74, 20, 55]
panel.projection = 'lcc'
panel.layers = ['states', 'coastline', 'borders']
panel.title = f'{cfill.level.m}-hPa Heights and Wind Speed at {plot_time}'
panel.plots = [cfill, cntr2, barbs]
# Set the attributes for the panel and put the panel in the figure
pc = PanelContainer()
pc.size = (15, 15)
pc.panels = [panel]
# Show the figure
pc.show()
#########################################################################
# Plot Surface Obs
# ----------------
#
# We can also plot surface (or upper-air) observations at point locations using the simplified
# syntax. Whether it is surface or upper-air data, the ``PlotObs()`` class is what you would
# want to use. Then you would add those observations to a map panel and then collect the panels
# to plot the figure; similar to what you would do for a gridded plot.
df = metar.parse_metar_file(get_test_data('metar_20190701_1200.txt', False), year=2019,
month=7)
# Let's take a look at the variables that we could plot coming from our METAR observations.
print(df.keys())
# Set the observation time
obs_time = datetime(2019, 7, 1, 12)
#########################################################################
# Setting of our attributes for plotting observations is pretty straignforward and just needs
# to be lists for the variables, and a comparable number of items for plot characteristics that
# are specific to the individual fields. For example, the locations around a station plot, the
# plot units, and any plotting formats would all meed to have the same number of items as the
# fields attribute.
#
# Plotting wind bards is done through the vector_field attribute and you can reduce the number
# of points plotted (especially important for surface observations) with the reduce points
# attribute.
#
# For a very basic plot of one field, the minimum required attributes are the data, time,
# fields, and location attributes.
# Plot desired data
obs = PlotObs()
obs.data = df
obs.time = obs_time
obs.time_window = timedelta(minutes=15)
obs.level = None
obs.fields = ['cloud_coverage', 'air_temperature', 'dew_point_temperature',
'air_pressure_at_sea_level', 'present_weather']
obs.plot_units = [None, 'degF', 'degF', None, None]
obs.locations = ['C', 'NW', 'SW', 'NE', 'W']
obs.formats = ['sky_cover', None, None, lambda v: format(v * 10, '.0f')[-3:],
'current_weather']
obs.reduce_points = 0.75
obs.vector_field = ['eastward_wind', 'northward_wind']
#########################################################################
# We use the same Classes for plotting our data on a map panel and collecting all of the
# panels on the figure. In this case we'll focus in on the state of Indiana for plotting.
# Panel for plot with Map features
panel = MapPanel()
panel.layout = (1, 1, 1)
panel.projection = 'lcc'
panel.area = 'in'
panel.layers = ['states']
panel.title = f'Surface plot for {obs_time}'
panel.plots = [obs]
# Bringing it all together
pc = PanelContainer()
pc.size = (10, 10)
pc.panels = [panel]
pc.show()
#########################################################################
# Detailed Attribute Descriptions
# -------------------------------
#
# This final section contains verbose descriptions of the attributes that can be set by the
# plot types used in this tutorial.
#########################################################################
# ContourPlot()
# -------------
#
# This class is designed to plot contours of gridded data, most commonly model output from the
# GFS, NAM, RAP, or other gridded dataset (e.g., NARR).
#
# Attributes:
#
# ``data``
#
# This attribute must be set with the variable name that contains the xarray dataset.
# (Typically this is the variable ds)
#
# ``field``
#
# This attribute must be set with the name of the variable that you want to contour.
# For example, to plot the heights of pressure surfaces from the GFS you would use the name
# ``‘Geopotential_height_isobaric’``
#
# ``level``
#
# This attribute sets the level of the data you wish to plot. If it is a pressure level,
# then it must be set to a unit bearing value (e.g., 500*units.hPa). If the variable does
# not have any vertical levels (e.g., mean sea-level pressure), then the level attribute must
# be set to None.
#
# ``time``
#
# This attribute must be set with a datetime object, just as with the ``PlotObs()`` class.
# To get a forecast hour, you can use the timedelta function from datetime to add the number of
# hours into the future you wish to plot. For example, if you wanted the six hour forecast from
# the 00 UTC 2 February 2020 model run, then you would set the attribute with:
#
# ``datetime(2020, 2, 2, 0) + timedelta(hours=6)``
#
# ``contours``
#
# This attribute sets the contour values to be plotted with a list. This can be set manually
# with a list of integers in square brackets (e.g., ``[5400, 5460, 5520, 5580, 5640, 5700]``)
# or programmatically (e.g., ``list(range(0, 10000, 60))``). The second method is a way to
# easily set a contour interval (in this case 60).
#
# ``clabel``
#
# This attribute can be set to ``True`` if you desire to have your contours labeled.
#
# ``linestyle``
#
# This attribute can be set to make the contours ``‘solid’``, ``‘dashed’``, ``‘dotted’``,
# or ``‘dashdot’``. Other linestyles are can be used and are found at:
# https://matplotlib.org/3.1.0/gallery/lines_bars_and_markers/linestyles.html
#
# Default is ``‘solid’``.
#
# ``linewidth``
#
# This attribute alters the width of the contours (defaults to 1). Setting the value greater
# than 1 will yield a thicker contour line.
#
# ``linecolor``
#
# This attribute sets the color of the contour lines. Default is ``‘black’``. All colors from
# matplotlib are valid: https://matplotlib.org/3.1.0/_images/sphx_glr_named_colors_003.png
#
# ``plot_units``
#
# If you want to change the units for plotting purposes, add the string value of the units
# desired. For example, if you want to plot temperature in Celsius, then set this attribute
# to ``‘degC’``.
#########################################################################
# FilledContourPlot()
# -------------------
#
# Works very similarly to ``ContourPlot()``, except that contours are filled using a colormap
# between contour values. All attributes for ``ContourPlot()`` work for color-filled plots,
# except for linestyle, linecolor, and linewidth. Additionally, there are the following
# attributes that work for color-filling:
#
# Attributes:
#
# ``colormap``
#
# This attribute is used to set a valid colormap from either Matplotlib or MetPy:
# Matplotlib Colormaps: https://matplotlib.org/3.1.1/gallery/color/colormap_reference.html
# MetPy Colormaps: https://unidata.github.io/MetPy/v1.0/api/generated/metpy.plots.ctables.html
#
# ``colorbar``
#
# This attribute can be set to ``‘vertical’`` or ``‘horizontal’``, which is the location the
# colorbar will be plotted on the panel.
#
# ``image_range``
#
# A set of values indicating the minimum and maximum for the data being plotted. This
# attribute should be set as ``(min_value, max_value)``, where min_value and max_value are
# numeric values.
#########################################################################
# PanelContainer()
# ----------------
#
# Attributes:
#
# ``size``
#
# The size of the figure in inches (e.g., (10, 8))
#
# ``panels``
#
# A list collecting the panels to be plotted in the figure.
#
# ``show``
#
# Show the plot
#
# ``save``
#
# Save the figure using the Matplotlib arguments/keyword arguments
#########################################################################
# MapPanel()
# ----------
#
# Attributes:
#
# ``layout``
#
# The Matplotlib layout of the figure. For a single panel figure the setting should be
# ``(1, 1, 1)``
#
# ``projection``
#
# The projection can be set with the name of a default projection (``‘lcc’``, ``‘mer’``, or
# ``‘ps’``) or it can be set to a Cartopy projection.
#
# ``layers``
#
# This attribute will add map layers to identify boundaries or features to plot on the map.
# Valid layers are ``'borders'``, ``'coastline'``, ``'states'``, ``'lakes'``, ``'land'``,
# ``'ocean'``, ``'rivers'``, ``'counties'``.
#
# ``area``
#
# This attribute sets the geographical area of the panel. This can be set with a predefined
# name of an area including all US state postal abbreviations (e.g., ``‘us’``, ``‘natl’``,
# ``‘in’``, ``‘il’``, ``‘wi’``, ``‘mi’``, etc.) or a tuple value that corresponds to
# longitude/latitude box based on the projection of the map with the format
# ``(west-most longitude, east-most longitude, south-most latitude, north-most latitude)``.
# This tuple defines a box from the lower-left to the upper-right corner.
#
# ``title``
#
# This attribute sets a title for the panel.
#
# ``plots``
#
# A list collecting the observations to be plotted in the panel.
#########################################################################
# BarbPlot()
# ----------
#
# This plot class is used to add wind barbs to the plot with the following
#
# Attributes:
#
# ``data``
#
# This attribute must be set to the variable that contains the vector components to be plotted.
#
# ``field``
#
# This attribute is a list of the vector components to be plotted. For the typical
# meteorological case it would be the ``[‘u-compopnent’, ‘v-component’]``.
#
# ``time``
#
# This attribute should be set to a datetime object, the same as for all other declarative
# classes.
#
# ``barblength``
#
# This attribute sets the length of the wind barbs. The default value is based on the
# font size.
#
# ``color``
#
# This attribute sets the color of the wind barbs, which can be any Matplotlib color.
# Default color is ``‘black’``.
#
# ``earth_relative``
#
# This attribute can be set to False if the vector components are grid relative (e.g., for NAM
# or NARR output)
#
# ``pivot``
#
# This attribute can be set to a string value about where the wind barb will pivot relative to
# the grid point. Possible values include ``‘tip’`` or ``‘middle’``. Default is ``‘middle’``.
########################################################################
# PlotObs()
# ---------
#
# This class is used to plot point observations from the surface or upper-air.
#
# Attributes:
#
# ``data``
#
# This attribute needs to be set to the DataFrame variable containing the fields that you
# desire to plot.
#
# ``fields``
#
# This attribute is a list of variable names from your DataFrame that you desire to plot at the
# given locations around the station model.
#
# ``level``
#
# For a surface plot this needs to be set to None.
#
# ``time``
#
# This attribute needs to be set to subset your data attribute for the time of the observations
# to be plotted. This needs to be a datetime object.
#
# ``locations``
#
# This attribute sets the location of the fields to be plotted around the surface station
# model. The default location is center ``(‘C’)``
#
# ``time_range``
#
# This attribute allows you to define a window for valid observations (e.g., 15 minutes on
# either side of the datetime object setting. This is important for surface data since actual
# observed times are not all exactly on the hour. If multiple observations exist in the defined
# window, the most recent observations is retained for plotting purposes.
#
# ``formats``
#
# This attribute sets a formatter for text or plotting symbols around the station model. For
# example, plotting mean sea-level pressure is done in a three-digit code and a formatter can
# be used to achieve that on the station plot.
#
# MSLP Formatter: ``lambda v: format(10 * v, '.0f')[-3:]``
#
# For plotting symbols use the available MetPy options through their name. Valid symbol formats
# are ``'current_weather'``, ``'sky_cover'``, ``'low_clouds'``, ``'mid_clouds'``,
# ``'high_clouds'``, and ``'pressure_tendency'``.
#
# ``colors``
#
# This attribute can change the color of the plotted observation. Default is ``‘black’``.
# Acceptable colors are those available through Matplotlib:
# https://matplotlib.org/3.1.1/_images/sphx_glr_named_colors_003.png
#
# ``vector_field``
#
# This attribute can be set to a list of wind component values for plotting
# (e.g., ``[‘uwind’, ‘vwind’]``)
#
# ``vector_field_color``
#
# Same as colors except only controls the color of the wind barbs. Default is ``‘black’``.
#
# ``reduce_points``
#
# This attribute can be set to a real number to reduce the number of stations that are plotted.
# Default value is zero (e.g., no points are removed from the plot).
| 35.996639 | 95 | 0.647866 | true | true | |
f7f933cc70c654fc0df7d7861af76d16032ed0f5 | 3,468 | py | Python | app/app/settings.py | ndizihiwesimon/recipe-app-api | 52f00837abc3c6e2952db9baafe600a7af17b322 | [
"MIT"
] | null | null | null | app/app/settings.py | ndizihiwesimon/recipe-app-api | 52f00837abc3c6e2952db9baafe600a7af17b322 | [
"MIT"
] | null | null | null | app/app/settings.py | ndizihiwesimon/recipe-app-api | 52f00837abc3c6e2952db9baafe600a7af17b322 | [
"MIT"
] | null | null | null | """
Django settings for app project.
Generated by 'django-admin startproject' using Django 4.0.1.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
import os
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-+g=^5wpckkb07&t_8@5yu@v6tqi*@wsy$5oop3#ki#y50mqnnn'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'core',
'user',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'app.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'app.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'HOST': os.environ.get('DB_HOST'),
'NAME': os.environ.get('DB_NAME'),
'USER': os.environ.get('DB_USER'),
'PASSWORD': os.environ.get('DB_PASS'),
}
}
# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
AUTH_USER_MODEL = 'core.User' | 26.075188 | 91 | 0.693772 |
import os
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = 'django-insecure-+g=^5wpckkb07&t_8@5yu@v6tqi*@wsy$5oop3#ki#y50mqnnn'
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'core',
'user',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'app.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'app.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'HOST': os.environ.get('DB_HOST'),
'NAME': os.environ.get('DB_NAME'),
'USER': os.environ.get('DB_USER'),
'PASSWORD': os.environ.get('DB_PASS'),
}
}
# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
AUTH_USER_MODEL = 'core.User' | true | true |
f7f934032d3eddc7d56b2f1f053d4bb02dbcb3cf | 2,508 | py | Python | frontend/util/session.py | EPC-MSU/uRPC | cd3c386a8320542052834ca28791a3ea2b57c54f | [
"CC0-1.0"
] | 1 | 2022-03-11T04:29:53.000Z | 2022-03-11T04:29:53.000Z | frontend/util/session.py | EPC-MSU/uRPC | cd3c386a8320542052834ca28791a3ea2b57c54f | [
"CC0-1.0"
] | null | null | null | frontend/util/session.py | EPC-MSU/uRPC | cd3c386a8320542052834ca28791a3ea2b57c54f | [
"CC0-1.0"
] | 1 | 2021-06-15T21:56:26.000Z | 2021-06-15T21:56:26.000Z | from collections import Container
from os import sep, access, R_OK
from os.path import join, isfile
from uuid import UUID
from tornado.ioloop import IOLoop
from urpc.ast import Protocol
from urpc.storage.json import JsonStorage
try:
from settings import temp_dir
except ImportError:
temp_dir = join(sep, "tmp") # join("tmp") for Windows
class CachedItem:
def __init__(self, timeout, project):
self.timeout = timeout
self.project = project
class SessionManager(Container):
# after 3 minutes without access project is removed from RAM cache and is dumped to disk
_dump_timeout = 3 * 60
def __init__(self):
self._storage = JsonStorage()
self._loop = IOLoop.current()
self._cache = {}
def _path_from_uid(self, uid):
file_name = str(uid) + ".json"
file_path = join(temp_dir, file_name)
return file_path
def __getitem__(self, uid):
assert isinstance(uid, UUID)
item = self._cache.setdefault(uid, CachedItem(None, None))
if item.timeout:
self._loop.remove_timeout(item.timeout)
if not item.project:
path = self._path_from_uid(uid)
if isfile(path) and access(path, R_OK):
with open(path, "rb") as f:
item.project = self._storage.load(f)
else:
item.project = Protocol(name="Default project", version="0")
item.timeout = self._loop.call_later(self._dump_timeout, self._dump_cached, uid)
return item.project
def __setitem__(self, uid, project):
assert isinstance(uid, UUID) and isinstance(project, Protocol)
item = self._cache.setdefault(uid, CachedItem(None, None))
if item.timeout:
self._loop.remove_timeout(item.timeout)
item.project = project
item.timeout = self._loop.call_later(self._dump_timeout, self._dump_cached, uid)
def __contains__(self, uid):
assert isinstance(uid, UUID)
if uid in self._cache:
return True
else:
file_name = str(uid) + ".json"
file_path = join(temp_dir, file_name)
return isfile(file_path) and access(file_path, R_OK)
def _dump_cached(self, uid):
assert isinstance(uid, UUID)
item = self._cache.pop(uid)
self._loop.remove_timeout(item.timeout)
path = self._path_from_uid(uid)
with open(path, "wb") as f:
self._storage.save(item.project, f)
| 32.153846 | 92 | 0.637161 | from collections import Container
from os import sep, access, R_OK
from os.path import join, isfile
from uuid import UUID
from tornado.ioloop import IOLoop
from urpc.ast import Protocol
from urpc.storage.json import JsonStorage
try:
from settings import temp_dir
except ImportError:
temp_dir = join(sep, "tmp")
class CachedItem:
def __init__(self, timeout, project):
self.timeout = timeout
self.project = project
class SessionManager(Container):
_dump_timeout = 3 * 60
def __init__(self):
self._storage = JsonStorage()
self._loop = IOLoop.current()
self._cache = {}
def _path_from_uid(self, uid):
file_name = str(uid) + ".json"
file_path = join(temp_dir, file_name)
return file_path
def __getitem__(self, uid):
assert isinstance(uid, UUID)
item = self._cache.setdefault(uid, CachedItem(None, None))
if item.timeout:
self._loop.remove_timeout(item.timeout)
if not item.project:
path = self._path_from_uid(uid)
if isfile(path) and access(path, R_OK):
with open(path, "rb") as f:
item.project = self._storage.load(f)
else:
item.project = Protocol(name="Default project", version="0")
item.timeout = self._loop.call_later(self._dump_timeout, self._dump_cached, uid)
return item.project
def __setitem__(self, uid, project):
assert isinstance(uid, UUID) and isinstance(project, Protocol)
item = self._cache.setdefault(uid, CachedItem(None, None))
if item.timeout:
self._loop.remove_timeout(item.timeout)
item.project = project
item.timeout = self._loop.call_later(self._dump_timeout, self._dump_cached, uid)
def __contains__(self, uid):
assert isinstance(uid, UUID)
if uid in self._cache:
return True
else:
file_name = str(uid) + ".json"
file_path = join(temp_dir, file_name)
return isfile(file_path) and access(file_path, R_OK)
def _dump_cached(self, uid):
assert isinstance(uid, UUID)
item = self._cache.pop(uid)
self._loop.remove_timeout(item.timeout)
path = self._path_from_uid(uid)
with open(path, "wb") as f:
self._storage.save(item.project, f)
| true | true |
f7f93415a321fe5f7c6093662ae097ed6941f512 | 8,248 | py | Python | zenml/steps/trainer/pytorch_trainers/torch_ff_trainer.py | ORG-MARS/zenml | 8ee9a9264397d4e24a34c906e34a443782b189d3 | [
"Apache-2.0"
] | 1 | 2021-08-13T03:07:53.000Z | 2021-08-13T03:07:53.000Z | zenml/steps/trainer/pytorch_trainers/torch_ff_trainer.py | ORG-MARS/zenml | 8ee9a9264397d4e24a34c906e34a443782b189d3 | [
"Apache-2.0"
] | null | null | null | zenml/steps/trainer/pytorch_trainers/torch_ff_trainer.py | ORG-MARS/zenml | 8ee9a9264397d4e24a34c906e34a443782b189d3 | [
"Apache-2.0"
] | null | null | null | # Copyright (c) maiot GmbH 2020. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing
# permissions and limitations under the License.
import os
from typing import List, Text, Dict
import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as data
from torch.utils.tensorboard import SummaryWriter
from zenml.steps.trainer import TorchBaseTrainerStep
from zenml.steps.trainer import utils
from zenml.steps.trainer.pytorch_trainers import utils as torch_utils
from zenml.utils import path_utils
class BinaryClassifier(nn.Module):
def __init__(self):
super(BinaryClassifier, self).__init__()
self.layer_1 = nn.Linear(8, 64)
self.layer_2 = nn.Linear(64, 64)
self.layer_out = nn.Linear(64, 1)
self.relu = nn.ReLU()
self.dropout = nn.Dropout(p=0.1)
self.batchnorm1 = nn.BatchNorm1d(64)
self.batchnorm2 = nn.BatchNorm1d(64)
def forward(self, inputs):
x = self.relu(self.layer_1(inputs))
x = self.batchnorm1(x)
x = self.relu(self.layer_2(x))
x = self.batchnorm2(x)
x = self.dropout(x)
x = self.layer_out(x)
return x
def binary_acc(y_pred, y_test):
y_pred_tag = torch.round(torch.sigmoid(y_pred))
correct_results_sum = (y_pred_tag == y_test).sum().float()
acc = correct_results_sum / y_test.shape[0]
acc = torch.round(acc * 100)
return acc
class FeedForwardTrainer(TorchBaseTrainerStep):
def __init__(self,
batch_size: int = 32,
lr: float = 0.0001,
epochs: int = 10,
dropout_chance: int = 0.2,
loss: str = 'mse',
metrics: List[str] = None,
hidden_layers: List[int] = None,
hidden_activation: str = 'relu',
last_activation: str = 'sigmoid',
input_units: int = 8,
output_units: int = 1,
device: str = None,
**kwargs):
self.batch_size = batch_size
self.lr = lr
self.epochs = epochs
self.dropout_chance = dropout_chance
self.loss = loss
self.metrics = metrics or []
self.hidden_layers = hidden_layers or [64, 32, 16]
self.hidden_activation = hidden_activation
self.last_activation = last_activation
self.input_units = input_units
self.output_units = output_units
self.device = torch_utils.assign_device(device)
super(FeedForwardTrainer, self).__init__(
batch_size=self.batch_size,
lr=self.lr,
epochs=self.epochs,
dropout_chance=self.dropout_chance,
loss=self.loss,
metrics=self.metrics,
hidden_layers=self.hidden_layers,
hidden_activation=self.hidden_activation,
last_activation=self.last_activation,
input_units=self.input_units,
output_units=self.output_units,
device = device,
**kwargs)
def input_fn(self,
file_patterns: List[Text]):
dataset = torch_utils.TFRecordTorchDataset(file_patterns,
self.schema)
loader = torch.utils.data.DataLoader(dataset,
batch_size=self.batch_size,
drop_last=True)
return loader
def model_fn(self, train_dataset, eval_dataset):
return BinaryClassifier()
def test_fn(self, model, dataset):
# Activate the evaluation mode
model.eval()
batch_list = []
for x, y, raw in dataset:
# start with an empty batch
batch = {}
# add the raw features with the transformed features and labels
batch.update(x)
batch.update(y)
batch.update(raw)
# finally, add the output of the model
x_batch = torch.cat([v.to(self.device) for v in x.values()], dim=-1)
p = model(x_batch)
if isinstance(p, torch.Tensor):
batch.update({'output': p})
elif isinstance(p, dict):
batch.update(p)
elif isinstance(p, list):
batch.update(
{'output_{}'.format(i): v for i, v in enumerate(p)})
else:
raise TypeError('Unknown output format!')
batch_list.append(batch)
combined_batch = utils.combine_batch_results(batch_list)
return combined_batch
def run_fn(self):
train_split_patterns = [self.input_patterns[split] for split in
self.split_mapping[utils.TRAIN_SPLITS]]
train_dataset = self.input_fn(train_split_patterns)
eval_split_patterns = [self.input_patterns[split] for split in
self.split_mapping[utils.EVAL_SPLITS]]
eval_dataset = self.input_fn(eval_split_patterns)
model = self.model_fn(train_dataset, eval_dataset)
model.to(self.device)
criterion = nn.BCEWithLogitsLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
writer = SummaryWriter(self.log_dir)
model.train()
total_count = 0
for e in range(1, self.epochs + 1):
epoch_loss = 0
epoch_acc = 0
step_count = 0
for x, y, _ in train_dataset:
step_count += 1
total_count += 1
x_batch = torch.cat([v.to(self.device) for v in x.values()], dim=-1)
y_batch = torch.cat([v.to(self.device) for v in y.values()], dim=-1)
optimizer.zero_grad()
y_pred = model(x_batch)
loss = criterion(y_pred, y_batch)
acc = binary_acc(y_pred, y_batch)
loss.backward()
optimizer.step()
epoch_loss += loss.item()
epoch_acc += acc.item()
if e == 1 and step_count == 1:
writer.add_graph(model, x_batch)
writer.add_scalar('training_loss', loss, total_count)
writer.add_scalar('training_accuracy', acc, total_count)
print(f'Epoch {e + 0:03}: | Loss: '
f'{epoch_loss / step_count:.5f} | Acc: '
f'{epoch_acc / step_count:.3f}')
# test
for split in self.split_mapping[utils.TEST_SPLITS]:
assert split in self.input_patterns, \
f'There are currently no inputs for the split "{split}" ' \
f'which is currently used in the {utils.TEST_SPLITS} of the ' \
f'split mapping.'
pattern = self.input_patterns[split]
test_dataset = self.input_fn([pattern])
test_results = self.test_fn(model, test_dataset)
utils.save_test_results(test_results, self.output_patterns[split])
path_utils.create_dir_if_not_exists(self.serving_model_dir)
if path_utils.is_remote(self.serving_model_dir):
temp_model_dir = '__temp_model_dir__'
temp_path = os.path.join(os.getcwd(), temp_model_dir)
if path_utils.is_dir(temp_path):
raise PermissionError('{} is used as a temp path but it '
'already exists. Please remove it to '
'continue.')
torch.save(model, temp_path)
path_utils.copy_dir(temp_path, self.serving_model_dir)
path_utils.rm_dir(temp_path)
else:
torch.save(model, os.path.join(self.serving_model_dir, 'model.pt'))
| 35.551724 | 84 | 0.579777 |
import os
from typing import List, Text, Dict
import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as data
from torch.utils.tensorboard import SummaryWriter
from zenml.steps.trainer import TorchBaseTrainerStep
from zenml.steps.trainer import utils
from zenml.steps.trainer.pytorch_trainers import utils as torch_utils
from zenml.utils import path_utils
class BinaryClassifier(nn.Module):
def __init__(self):
super(BinaryClassifier, self).__init__()
self.layer_1 = nn.Linear(8, 64)
self.layer_2 = nn.Linear(64, 64)
self.layer_out = nn.Linear(64, 1)
self.relu = nn.ReLU()
self.dropout = nn.Dropout(p=0.1)
self.batchnorm1 = nn.BatchNorm1d(64)
self.batchnorm2 = nn.BatchNorm1d(64)
def forward(self, inputs):
x = self.relu(self.layer_1(inputs))
x = self.batchnorm1(x)
x = self.relu(self.layer_2(x))
x = self.batchnorm2(x)
x = self.dropout(x)
x = self.layer_out(x)
return x
def binary_acc(y_pred, y_test):
y_pred_tag = torch.round(torch.sigmoid(y_pred))
correct_results_sum = (y_pred_tag == y_test).sum().float()
acc = correct_results_sum / y_test.shape[0]
acc = torch.round(acc * 100)
return acc
class FeedForwardTrainer(TorchBaseTrainerStep):
def __init__(self,
batch_size: int = 32,
lr: float = 0.0001,
epochs: int = 10,
dropout_chance: int = 0.2,
loss: str = 'mse',
metrics: List[str] = None,
hidden_layers: List[int] = None,
hidden_activation: str = 'relu',
last_activation: str = 'sigmoid',
input_units: int = 8,
output_units: int = 1,
device: str = None,
**kwargs):
self.batch_size = batch_size
self.lr = lr
self.epochs = epochs
self.dropout_chance = dropout_chance
self.loss = loss
self.metrics = metrics or []
self.hidden_layers = hidden_layers or [64, 32, 16]
self.hidden_activation = hidden_activation
self.last_activation = last_activation
self.input_units = input_units
self.output_units = output_units
self.device = torch_utils.assign_device(device)
super(FeedForwardTrainer, self).__init__(
batch_size=self.batch_size,
lr=self.lr,
epochs=self.epochs,
dropout_chance=self.dropout_chance,
loss=self.loss,
metrics=self.metrics,
hidden_layers=self.hidden_layers,
hidden_activation=self.hidden_activation,
last_activation=self.last_activation,
input_units=self.input_units,
output_units=self.output_units,
device = device,
**kwargs)
def input_fn(self,
file_patterns: List[Text]):
dataset = torch_utils.TFRecordTorchDataset(file_patterns,
self.schema)
loader = torch.utils.data.DataLoader(dataset,
batch_size=self.batch_size,
drop_last=True)
return loader
def model_fn(self, train_dataset, eval_dataset):
return BinaryClassifier()
def test_fn(self, model, dataset):
model.eval()
batch_list = []
for x, y, raw in dataset:
batch = {}
batch.update(x)
batch.update(y)
batch.update(raw)
x_batch = torch.cat([v.to(self.device) for v in x.values()], dim=-1)
p = model(x_batch)
if isinstance(p, torch.Tensor):
batch.update({'output': p})
elif isinstance(p, dict):
batch.update(p)
elif isinstance(p, list):
batch.update(
{'output_{}'.format(i): v for i, v in enumerate(p)})
else:
raise TypeError('Unknown output format!')
batch_list.append(batch)
combined_batch = utils.combine_batch_results(batch_list)
return combined_batch
def run_fn(self):
train_split_patterns = [self.input_patterns[split] for split in
self.split_mapping[utils.TRAIN_SPLITS]]
train_dataset = self.input_fn(train_split_patterns)
eval_split_patterns = [self.input_patterns[split] for split in
self.split_mapping[utils.EVAL_SPLITS]]
eval_dataset = self.input_fn(eval_split_patterns)
model = self.model_fn(train_dataset, eval_dataset)
model.to(self.device)
criterion = nn.BCEWithLogitsLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
writer = SummaryWriter(self.log_dir)
model.train()
total_count = 0
for e in range(1, self.epochs + 1):
epoch_loss = 0
epoch_acc = 0
step_count = 0
for x, y, _ in train_dataset:
step_count += 1
total_count += 1
x_batch = torch.cat([v.to(self.device) for v in x.values()], dim=-1)
y_batch = torch.cat([v.to(self.device) for v in y.values()], dim=-1)
optimizer.zero_grad()
y_pred = model(x_batch)
loss = criterion(y_pred, y_batch)
acc = binary_acc(y_pred, y_batch)
loss.backward()
optimizer.step()
epoch_loss += loss.item()
epoch_acc += acc.item()
if e == 1 and step_count == 1:
writer.add_graph(model, x_batch)
writer.add_scalar('training_loss', loss, total_count)
writer.add_scalar('training_accuracy', acc, total_count)
print(f'Epoch {e + 0:03}: | Loss: '
f'{epoch_loss / step_count:.5f} | Acc: '
f'{epoch_acc / step_count:.3f}')
for split in self.split_mapping[utils.TEST_SPLITS]:
assert split in self.input_patterns, \
f'There are currently no inputs for the split "{split}" ' \
f'which is currently used in the {utils.TEST_SPLITS} of the ' \
f'split mapping.'
pattern = self.input_patterns[split]
test_dataset = self.input_fn([pattern])
test_results = self.test_fn(model, test_dataset)
utils.save_test_results(test_results, self.output_patterns[split])
path_utils.create_dir_if_not_exists(self.serving_model_dir)
if path_utils.is_remote(self.serving_model_dir):
temp_model_dir = '__temp_model_dir__'
temp_path = os.path.join(os.getcwd(), temp_model_dir)
if path_utils.is_dir(temp_path):
raise PermissionError('{} is used as a temp path but it '
'already exists. Please remove it to '
'continue.')
torch.save(model, temp_path)
path_utils.copy_dir(temp_path, self.serving_model_dir)
path_utils.rm_dir(temp_path)
else:
torch.save(model, os.path.join(self.serving_model_dir, 'model.pt'))
| true | true |
f7f9343f8fae9608efa12d605fa88dcc017fb121 | 6,207 | py | Python | classes/DomainSegmentor.py | egurapha/prot_domain_segmentor | 407ae9f5ff37ae20a32f07dd46b85ef8201659e1 | [
"MIT"
] | 9 | 2018-09-20T02:45:08.000Z | 2022-02-21T02:50:08.000Z | classes/DomainSegmentor.py | egurapha/prot_domain_segmentor | 407ae9f5ff37ae20a32f07dd46b85ef8201659e1 | [
"MIT"
] | null | null | null | classes/DomainSegmentor.py | egurapha/prot_domain_segmentor | 407ae9f5ff37ae20a32f07dd46b85ef8201659e1 | [
"MIT"
] | 1 | 2021-04-26T00:15:28.000Z | 2021-04-26T00:15:28.000Z | import os, sys
sys.path.insert(0, 'model')
from segmentor_model_v2 import *
from segmentor_utils import *
import torch
from torch.autograd import Variable
import numpy as np
import torch.nn.functional as F
import scipy.stats
idx_to_class = {0: 'Unassigned (Loop)',
1: 'Orthogonal Bundle',
2: 'Up-down Bundle',
3: 'Alpha Horseshoe',
4: 'Alpha/alpha barrel',
5: 'Ribbon',
6: 'Aligned Prism',
7: '3-layer Sandwich',
8: '4 Propeller',
9: '5 Propeller',
10: '6 Propeller',
11: '7 Propeller',
12: '2 Solenoid',
13: '3 Solenoid',
14: 'Beta Complex',
15: 'Single Sheet',
16: 'Roll',
17: 'Beta Barrel',
18: 'Clam',
19: 'Sandwich',
20: 'Distorted Sandwich',
21: 'Trefoil',
22: 'Orthogonal Prism',
23: 'Roll',
24: 'Ribosomal Protein L15; Chain: K; domain 2',
25: 'Super Roll',
26: 'Alpha-Beta Barrel',
27: '2-Layer Sandwich',
28: '3-Layer(aba) Sandwich',
29: '3-Layer(bba) Sandwich',
30: '3-Layer(bab) Sandwich',
31: '4-Layer Sandwich',
32: 'Alpha-beta prism',
33: 'Box',
34: '5-stranded Propeller',
35: 'Alpha-Beta Horseshoe',
36: 'Alpha-Beta Complex',
37: 'Irregular',
-1: 'NULL'}
class DomainSegmentor:
def __init__(self, model_path='model/segmentor_epoch95_model_v2', class_dict=idx_to_class, try_gpu=True):
self.class_dict = class_dict
self.cuda_avail = torch.cuda.is_available() and try_gpu
self.num_classes = len(self.class_dict)-1
self.model = SegmentorModel(1,8,16, self.num_classes)
self._init_model(self.model, model_path)
def _init_model(self, net, model_path):
if self.cuda_avail:
net.load_state_dict(torch.load(model_path))
net.cuda()
net = torch.nn.DataParallel(net, device_ids=range(torch.cuda.device_count()))
print("Model Initialized on GPU.")
else:
net.load_state_dict(torch.load(model_path, map_location=lambda storage, loc: storage))
print("Model Initialized on CPU.")
net.eval() # Set model to evaluation mode to remove stochastic regularization.
def _get_input(self, pdb_name):
seq_len, numbering = get_pdb_info(pdb_name)
cm, numbering = makeContactMapTensor(pdb_name, seq_len, numbering, target_size=512, upper_tol=512)
if self.cuda_avail:
model_input = Variable(cm).cuda()
else:
model_input = Variable(cm)
return numbering, model_input
def predict(self, pdb_name, ignore_index=-9999, log=False):
'''
Input: pdb name as string.
Output:
trunc_class_probs -- 38 x 512 matrix. Entry (i,j) is the probility of residue j being in class i.
res_num -- the list of pdb_residue numberings corresponding to the columns of trunc_class_probs. For example, out_num[i] = 50, then the i-th column of trunc_class_probs corresponds to residue 50 in the actual PDB.
'''
numbering, model_input = self._get_input(pdb_name)
outputs = self.model(model_input)
if log:
outputs = F.log_softmax(outputs, dim=1)
else:
outputs = F.softmax(outputs, dim=1)
outputs = outputs.data[0,:,:,:]
# Format for output.
class_probs = outputs.cpu().numpy().squeeze() # 38 x 512 matrix. The columns define a probability distribution over the 38 classes for each residue.
res_num = []
trunc_class_probs = np.array([None])
for i in range(len(numbering)): # Remove entries outside of the range of the PDB.
if numbering[i] != ignore_index:
res_num.append(numbering[i])
if not trunc_class_probs.any():
trunc_class_probs = np.expand_dims(class_probs[:,i], axis=1)
else:
trunc_class_probs = np.column_stack([trunc_class_probs, class_probs[:,i]])
return trunc_class_probs, res_num
def predictClass(self, pdb_name, ignore_index=-9999):
'''
Input: pdb name as string.
Output:
out_pred -- the predicted classes for each residue.
res_num -- the pdb residue numberings corresponding to the entries in out_pred. For example, if res_num[i] = 10 and out_pred[i] = 15, then the model predicts class 15 for residue 10.
'''
numbering, model_input = self._get_input(pdb_name)
outputs = self.model(model_input)
_, predicted = torch.max(outputs.data, 1)
# Format for output.
predicted = predicted[0,:,:].cpu().numpy().flatten()
out_pred = []
res_num = []
for i in range(len(numbering)):
if numbering[i] != ignore_index:
out_pred.append(predicted[i])
res_num.append(numbering[i])
assert len(out_pred) == len(res_num)
return out_pred, res_num
def computeEntropy(self, pdb_name, ignore_index=-9999):
trunc_class_probs, res_num = self.predict(pdb_name, log=False)
entropy = scipy.stats.entropy(trunc_class_probs)
assert len(entropy) == len(res_num)
return entropy, res_num
# Usage Example.
if __name__ == '__main__':
segmentor = DomainSegmentor() # Initialize model, no params needed.
classes, res_nums = segmentor.predictClass('test_cases/3gqyA.pdb') # Run prediction. Pass in a path to a pdb file.
probs, res_nums = segmentor.predict('test_cases/3gqyA.pdb') # The predict function returns probabilities, the predictClass function returns a class prediction.
print("Residue Numbers: ")
print(res_nums)
print("Class Predictions: ")
print(classes)
print("Probability Matrix: ")
print(probs)
| 43.104167 | 225 | 0.586596 | import os, sys
sys.path.insert(0, 'model')
from segmentor_model_v2 import *
from segmentor_utils import *
import torch
from torch.autograd import Variable
import numpy as np
import torch.nn.functional as F
import scipy.stats
idx_to_class = {0: 'Unassigned (Loop)',
1: 'Orthogonal Bundle',
2: 'Up-down Bundle',
3: 'Alpha Horseshoe',
4: 'Alpha/alpha barrel',
5: 'Ribbon',
6: 'Aligned Prism',
7: '3-layer Sandwich',
8: '4 Propeller',
9: '5 Propeller',
10: '6 Propeller',
11: '7 Propeller',
12: '2 Solenoid',
13: '3 Solenoid',
14: 'Beta Complex',
15: 'Single Sheet',
16: 'Roll',
17: 'Beta Barrel',
18: 'Clam',
19: 'Sandwich',
20: 'Distorted Sandwich',
21: 'Trefoil',
22: 'Orthogonal Prism',
23: 'Roll',
24: 'Ribosomal Protein L15; Chain: K; domain 2',
25: 'Super Roll',
26: 'Alpha-Beta Barrel',
27: '2-Layer Sandwich',
28: '3-Layer(aba) Sandwich',
29: '3-Layer(bba) Sandwich',
30: '3-Layer(bab) Sandwich',
31: '4-Layer Sandwich',
32: 'Alpha-beta prism',
33: 'Box',
34: '5-stranded Propeller',
35: 'Alpha-Beta Horseshoe',
36: 'Alpha-Beta Complex',
37: 'Irregular',
-1: 'NULL'}
class DomainSegmentor:
def __init__(self, model_path='model/segmentor_epoch95_model_v2', class_dict=idx_to_class, try_gpu=True):
self.class_dict = class_dict
self.cuda_avail = torch.cuda.is_available() and try_gpu
self.num_classes = len(self.class_dict)-1
self.model = SegmentorModel(1,8,16, self.num_classes)
self._init_model(self.model, model_path)
def _init_model(self, net, model_path):
if self.cuda_avail:
net.load_state_dict(torch.load(model_path))
net.cuda()
net = torch.nn.DataParallel(net, device_ids=range(torch.cuda.device_count()))
print("Model Initialized on GPU.")
else:
net.load_state_dict(torch.load(model_path, map_location=lambda storage, loc: storage))
print("Model Initialized on CPU.")
net.eval()
def _get_input(self, pdb_name):
seq_len, numbering = get_pdb_info(pdb_name)
cm, numbering = makeContactMapTensor(pdb_name, seq_len, numbering, target_size=512, upper_tol=512)
if self.cuda_avail:
model_input = Variable(cm).cuda()
else:
model_input = Variable(cm)
return numbering, model_input
def predict(self, pdb_name, ignore_index=-9999, log=False):
numbering, model_input = self._get_input(pdb_name)
outputs = self.model(model_input)
if log:
outputs = F.log_softmax(outputs, dim=1)
else:
outputs = F.softmax(outputs, dim=1)
outputs = outputs.data[0,:,:,:]
class_probs = outputs.cpu().numpy().squeeze()
res_num = []
trunc_class_probs = np.array([None])
for i in range(len(numbering)):
if numbering[i] != ignore_index:
res_num.append(numbering[i])
if not trunc_class_probs.any():
trunc_class_probs = np.expand_dims(class_probs[:,i], axis=1)
else:
trunc_class_probs = np.column_stack([trunc_class_probs, class_probs[:,i]])
return trunc_class_probs, res_num
def predictClass(self, pdb_name, ignore_index=-9999):
numbering, model_input = self._get_input(pdb_name)
outputs = self.model(model_input)
_, predicted = torch.max(outputs.data, 1)
predicted = predicted[0,:,:].cpu().numpy().flatten()
out_pred = []
res_num = []
for i in range(len(numbering)):
if numbering[i] != ignore_index:
out_pred.append(predicted[i])
res_num.append(numbering[i])
assert len(out_pred) == len(res_num)
return out_pred, res_num
def computeEntropy(self, pdb_name, ignore_index=-9999):
trunc_class_probs, res_num = self.predict(pdb_name, log=False)
entropy = scipy.stats.entropy(trunc_class_probs)
assert len(entropy) == len(res_num)
return entropy, res_num
if __name__ == '__main__':
segmentor = DomainSegmentor()
classes, res_nums = segmentor.predictClass('test_cases/3gqyA.pdb')
probs, res_nums = segmentor.predict('test_cases/3gqyA.pdb')
print("Residue Numbers: ")
print(res_nums)
print("Class Predictions: ")
print(classes)
print("Probability Matrix: ")
print(probs)
| true | true |
f7f935cfce095d6cc6f392874cf37d9947cd761d | 1,791 | py | Python | ward/tests/test_util.py | mkuyper/ward | 526d582128db159959f40a123002f614ed31349b | [
"MIT"
] | null | null | null | ward/tests/test_util.py | mkuyper/ward | 526d582128db159959f40a123002f614ed31349b | [
"MIT"
] | null | null | null | ward/tests/test_util.py | mkuyper/ward | 526d582128db159959f40a123002f614ed31349b | [
"MIT"
] | null | null | null | import os
from pathlib import Path
from ward.tests.utilities import make_project
from ward import test, using, fixture
from ward.testing import each
from ward.util import (
truncate,
find_project_root,
group_by,
)
@fixture
def s():
return "hello world"
@test("truncate('{input}', num_chars={num_chars}) returns '{expected}'")
def _(
input=s, num_chars=each(20, 11, 10, 5), expected=each(s, s, "hello w...", "he...")
):
result = truncate(input, num_chars)
assert result == expected
@test("find_project_root returns the root dir if no paths supplied")
def _():
project_root = find_project_root([])
fs_root = os.path.normpath(os.path.abspath(os.sep))
assert project_root == Path(fs_root)
@fixture
def fake_project_pyproject():
yield from make_project("pyproject.toml")
@fixture
def fake_project_git():
yield from make_project(".git")
@using(
root_file=each("pyproject.toml", ".git"),
project=each(fake_project_pyproject, fake_project_git),
)
@test("find_project_root finds project root with '{root_file}' file")
def _(root_file, project):
root = find_project_root([project / "a/b/c", project / "a/d"])
assert root.resolve() == project.resolve()
assert (root / root_file).exists()
def is_even(n):
return n % 2 == 0
def is_vowel(char):
return char in "aeiou"
def square(x):
return x ** 2
@test("group {items!r} by {key} returns {result}")
def _(
items=each(range(5), "echolocation", [-2, 3, 4, -3, 2, 3]),
key=each(is_even, is_vowel, square),
result=each(
{True: [0, 2, 4], False: [1, 3]},
{True: ["e", "o", "o", "a", "i", "o"], False: ["c", "h", "l", "c", "t", "n"]},
{4: [-2, 2], 9: [3, -3, 3], 16: [4]},
),
):
assert group_by(items, key) == result
| 22.961538 | 86 | 0.629816 | import os
from pathlib import Path
from ward.tests.utilities import make_project
from ward import test, using, fixture
from ward.testing import each
from ward.util import (
truncate,
find_project_root,
group_by,
)
@fixture
def s():
return "hello world"
@test("truncate('{input}', num_chars={num_chars}) returns '{expected}'")
def _(
input=s, num_chars=each(20, 11, 10, 5), expected=each(s, s, "hello w...", "he...")
):
result = truncate(input, num_chars)
assert result == expected
@test("find_project_root returns the root dir if no paths supplied")
def _():
project_root = find_project_root([])
fs_root = os.path.normpath(os.path.abspath(os.sep))
assert project_root == Path(fs_root)
@fixture
def fake_project_pyproject():
yield from make_project("pyproject.toml")
@fixture
def fake_project_git():
yield from make_project(".git")
@using(
root_file=each("pyproject.toml", ".git"),
project=each(fake_project_pyproject, fake_project_git),
)
@test("find_project_root finds project root with '{root_file}' file")
def _(root_file, project):
root = find_project_root([project / "a/b/c", project / "a/d"])
assert root.resolve() == project.resolve()
assert (root / root_file).exists()
def is_even(n):
return n % 2 == 0
def is_vowel(char):
return char in "aeiou"
def square(x):
return x ** 2
@test("group {items!r} by {key} returns {result}")
def _(
items=each(range(5), "echolocation", [-2, 3, 4, -3, 2, 3]),
key=each(is_even, is_vowel, square),
result=each(
{True: [0, 2, 4], False: [1, 3]},
{True: ["e", "o", "o", "a", "i", "o"], False: ["c", "h", "l", "c", "t", "n"]},
{4: [-2, 2], 9: [3, -3, 3], 16: [4]},
),
):
assert group_by(items, key) == result
| true | true |
f7f936d29596bc6308c69005269b9fca8bf3c209 | 3,835 | py | Python | jase_im/jase_im/logger.py | chenomg/blog.jase.im_v0.1 | 41e77fae1435f2c16701d982bd71fddbd399508e | [
"MIT"
] | 2 | 2019-02-22T16:09:35.000Z | 2019-11-27T10:22:49.000Z | jase_im/jase_im/logger.py | chenomg/blog.jase.im_v0.1 | 41e77fae1435f2c16701d982bd71fddbd399508e | [
"MIT"
] | 3 | 2018-12-22T13:40:15.000Z | 2020-06-05T19:26:48.000Z | jase_im/jase_im/logger.py | chenomg/blog.jase.im_v0.1 | 41e77fae1435f2c16701d982bd71fddbd399508e | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import re
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BASE_LOG_DIR = os.path.join(BASE_DIR, "logs")
find_connectionpool = re.compile(r'connectionpool')
def set_connectionpool_debug(record):
# 设置日志过滤器
if record.exc_info:
exc_type, exc_value = record.exc_info[:2]
record.exc_info[0] = 'WARN'
# print(record.exc_info)
# if find_connectionpool.findall(exc_value):
# record.exc_info[0] = ''
# record.exc_info[1] = ''
return True
LOGGING = {
'version': 1, # 保留的参数,默认是1
'disable_existing_loggers': False, # 是否禁用已经存在的logger实例
# 日志输出格式的定义
'formatters': {
'standard': { # 标准的日志格式化
'format': '%(levelname)s %(asctime)s %(module)s %(message)s'
},
'error': { # 错误日志输出格式
'format':
'%(levelname)s %(asctime)s %(pathname)s %(module)s %(message)s'
},
'simple': {
'format': '%(levelname)s %(asctime)s %(message)s'
},
'collect': {
'format': '%(message)s'
}
},
# 日志过滤器, 待完成
'filters': {
# 特殊过滤器,替换foo成bar,可以自己配置
'set_connectionpool_debug': {
'[]': 'django.utils.log.CallbackFilter',
'callback': set_connectionpool_debug,
},
# 是否支持DEBUG级别日志过滤
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse',
},
},
# 处理器:需要处理什么级别的日志及如何处理
'handlers': {
# 将日志打印到终端
'console': {
'level': 'DEBUG', # 日志级别
'class': 'logging.StreamHandler', # 使用什么类去处理日志流
'formatter': 'simple' # 指定上面定义过的一种日志输出格式
},
# 默认日志处理器
'debug': {
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler', # 保存到文件,自动切
'filename': os.path.join(BASE_LOG_DIR, "debug.log"), # 日志文件路径
'maxBytes': 1024 * 1024 * 100, # 日志大小 100M
'backupCount': 5, # 日志文件备份的数量
'formatter': 'standard', # 日志输出格式
'encoding': 'utf-8',
'filters': ['set_connectionpool_debug'],
},
# 默认日志处理器
'default': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler', # 保存到文件,自动切
'filename': os.path.join(BASE_LOG_DIR, "default.log"), # 日志文件路径
'maxBytes': 1024 * 1024 * 100, # 日志大小 100M
'backupCount': 5, # 日志文件备份的数量
'formatter': 'standard', # 日志输出格式
'encoding': 'utf-8',
'filters': ['set_connectionpool_debug'],
},
# 日志处理级别warn
'warn': {
'level': 'WARN',
'class': 'logging.handlers.RotatingFileHandler', # 保存到文件,自动切
'filename': os.path.join(BASE_LOG_DIR, "warn.log"), # 日志文件路径
'maxBytes': 1024 * 1024 * 100, # 日志大小 100M
'backupCount': 5, # 日志文件备份的数量
'formatter': 'standard', # 日志格式
'encoding': 'utf-8',
},
# 日志级别error
'error': {
'level': 'ERROR',
'class': 'logging.handlers.RotatingFileHandler', # 保存到文件,自动切
'filename': os.path.join(BASE_LOG_DIR, "error.log"), # 日志文件路径
'maxBytes': 1024 * 1024 * 100, # 日志大小 100M
'backupCount': 5,
'formatter': 'error', # 日志格式
'encoding': 'utf-8',
},
},
'loggers': {
# 默认的logger应用如下配置
'': {
'handlers': ['debug', 'default', 'warn', 'error'],
'level': 'DEBUG',
'propagate': True, # 如果有父级的logger示例,表示不要向上传递日志流
},
'collect': {
'handlers': ['console', 'debug', 'default', 'warn', 'error'],
'level': 'INFO',
}
},
}
| 32.226891 | 76 | 0.504302 |
import os
import re
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BASE_LOG_DIR = os.path.join(BASE_DIR, "logs")
find_connectionpool = re.compile(r'connectionpool')
def set_connectionpool_debug(record):
if record.exc_info:
exc_type, exc_value = record.exc_info[:2]
record.exc_info[0] = 'WARN'
return True
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': '%(levelname)s %(asctime)s %(module)s %(message)s'
},
'error': {
'format':
'%(levelname)s %(asctime)s %(pathname)s %(module)s %(message)s'
},
'simple': {
'format': '%(levelname)s %(asctime)s %(message)s'
},
'collect': {
'format': '%(message)s'
}
},
'filters': {
'set_connectionpool_debug': {
'[]': 'django.utils.log.CallbackFilter',
'callback': set_connectionpool_debug,
},
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse',
},
},
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
'debug': {
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler',
'filename': os.path.join(BASE_LOG_DIR, "debug.log"),
'maxBytes': 1024 * 1024 * 100,
'backupCount': 5,
'formatter': 'standard',
'encoding': 'utf-8',
'filters': ['set_connectionpool_debug'],
},
'default': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler',
'filename': os.path.join(BASE_LOG_DIR, "default.log"),
'maxBytes': 1024 * 1024 * 100,
'backupCount': 5,
'formatter': 'standard',
'encoding': 'utf-8',
'filters': ['set_connectionpool_debug'],
},
'warn': {
'level': 'WARN',
'class': 'logging.handlers.RotatingFileHandler',
'filename': os.path.join(BASE_LOG_DIR, "warn.log"),
'maxBytes': 1024 * 1024 * 100,
'backupCount': 5,
'formatter': 'standard',
'encoding': 'utf-8',
},
'error': {
'level': 'ERROR',
'class': 'logging.handlers.RotatingFileHandler',
'filename': os.path.join(BASE_LOG_DIR, "error.log"),
'maxBytes': 1024 * 1024 * 100,
'backupCount': 5,
'formatter': 'error',
'encoding': 'utf-8',
},
},
'loggers': {
'': {
'handlers': ['debug', 'default', 'warn', 'error'],
'level': 'DEBUG',
'propagate': True,
},
'collect': {
'handlers': ['console', 'debug', 'default', 'warn', 'error'],
'level': 'INFO',
}
},
}
| true | true |
f7f93704e822608575b10511e26a82120c9c5b7a | 2,632 | py | Python | test/testQListWidget.py | WuNull/findmovie | 29d3ef6fe2282f48be57780f5e8366de1d3479a6 | [
"Apache-2.0"
] | 1 | 2019-11-26T07:03:06.000Z | 2019-11-26T07:03:06.000Z | test/testQListWidget.py | WuNull/findmovie | 29d3ef6fe2282f48be57780f5e8366de1d3479a6 | [
"Apache-2.0"
] | null | null | null | test/testQListWidget.py | WuNull/findmovie | 29d3ef6fe2282f48be57780f5e8366de1d3479a6 | [
"Apache-2.0"
] | null | null | null | import sys
import json
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
"""
自动生成的代码, 请不要修改
"""
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(455, 357)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.listWidget = QtWidgets.QListWidget(self.centralwidget)
self.listWidget.setGeometry(QtCore.QRect(10, 10, 341, 341))
self.listWidget.setObjectName("listWidget")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(360, 10, 81, 31))
self.pushButton.setObjectName("pushButton")
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "PushButton"))
class Windows(QMainWindow, Ui_MainWindow):
def __init__(self):
super(Windows, self).__init__()
self.setupUi(self)
self.pushButton.clicked.connect(self.deal)
def deal(self):
all_data = json.loads('[{"ship_name":"\u6d4b\u8bd5","ship_index":"1","ship_photo":"icon/2.png"}]')
def get_item_wight(data):
# 读取属性
ship_name = data['ship_name']
ship_photo = data['ship_photo']
ship_index = data['ship_index']
# 总Widget
wight = QWidget()
# 总体横向布局
layout_main = QHBoxLayout()
# 三列
layout_main.addWidget(QLabel(ship_name))
layout_main.addWidget(QLabel(ship_photo))
layout_main.addWidget(QLabel(str(ship_index) + "星"))
wight.setLayout(layout_main) # 布局给wight
return wight # 返回wight
for ship_data in all_data:
item = QListWidgetItem() # 创建QListWidgetItem对象
item.setSizeHint(QSize(200, 50)) # 设置QListWidgetItem大小
widget = get_item_wight(ship_data) # 调用上面的函数获取对应
self.listWidget.addItem(item) # 添加item
self.listWidget.setItemWidget(item, widget) # 为item设置widget
app = QtWidgets.QApplication(sys.argv)
windows = Windows()
windows.show()
sys.exit(app.exec_())
| 36.555556 | 107 | 0.639058 | import sys
import json
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(455, 357)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.listWidget = QtWidgets.QListWidget(self.centralwidget)
self.listWidget.setGeometry(QtCore.QRect(10, 10, 341, 341))
self.listWidget.setObjectName("listWidget")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(360, 10, 81, 31))
self.pushButton.setObjectName("pushButton")
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "PushButton"))
class Windows(QMainWindow, Ui_MainWindow):
def __init__(self):
super(Windows, self).__init__()
self.setupUi(self)
self.pushButton.clicked.connect(self.deal)
def deal(self):
all_data = json.loads('[{"ship_name":"\u6d4b\u8bd5","ship_index":"1","ship_photo":"icon/2.png"}]')
def get_item_wight(data):
ship_name = data['ship_name']
ship_photo = data['ship_photo']
ship_index = data['ship_index']
wight = QWidget()
layout_main = QHBoxLayout()
layout_main.addWidget(QLabel(ship_name))
layout_main.addWidget(QLabel(ship_photo))
layout_main.addWidget(QLabel(str(ship_index) + "星"))
wight.setLayout(layout_main)
return wight
for ship_data in all_data:
item = QListWidgetItem()
item.setSizeHint(QSize(200, 50))
widget = get_item_wight(ship_data)
self.listWidget.addItem(item)
self.listWidget.setItemWidget(item, widget)
app = QtWidgets.QApplication(sys.argv)
windows = Windows()
windows.show()
sys.exit(app.exec_())
| true | true |
f7f937e853eeb1035d79856c7ab46c6aced76acd | 5,511 | py | Python | serve_db/vizapi.py | IBM/covid19-india-data | e2be04e74e753fbd1b1580f62856bf7335b95d33 | [
"MIT"
] | 20 | 2021-08-15T19:00:57.000Z | 2022-03-28T21:23:28.000Z | serve_db/vizapi.py | IBM/covid19-india-data | e2be04e74e753fbd1b1580f62856bf7335b95d33 | [
"MIT"
] | 78 | 2021-08-17T22:34:39.000Z | 2022-01-06T02:49:30.000Z | serve_db/vizapi.py | IBM/covid19-india-data | e2be04e74e753fbd1b1580f62856bf7335b95d33 | [
"MIT"
] | 8 | 2021-08-30T19:35:27.000Z | 2022-02-08T14:07:10.000Z | import sqlite3
import pandas as pd
import json
def get_queries():
CONFIGPATH = './configs/visualization.sql.json'
with open(CONFIGPATH, 'r') as f:
queries = json.load(f)
return queries
def get_generic_query_result(db_uri, queryid, return_csv=True):
queries = get_queries()
query = queries[queryid]
sql = query['query']
cols = query['columns']
data = read_from_db(db_uri, sql)
df = pd.DataFrame(data)
df.columns = cols
if return_csv:
csvdata = df.to_csv(index=False)
return csvdata
return df
def read_from_db(db_uri, query):
try:
con = sqlite3.connect(db_uri, uri=True)
cursor = con.cursor()
cursor.execute(query)
except Exception as err:
print(err)
records = None
else:
records = cursor.fetchall()
finally:
con.close()
return records
def hospitalization(db_uri, last_60_days=False):
with open('./configs/visualization.sql.json', 'r') as f:
queries = json.load(f)
if last_60_days:
hospital_query = queries['hospitalizations.queries.60days']
else:
hospital_query = queries['hospitalizations.queries']
datadict = {}
ALL_STATES = sorted(hospital_query.keys())
NA = "N/A"
for statename in ALL_STATES:
query = hospital_query[statename]
records = read_from_db(db_uri, query)
if records is not None:
for date, val in records:
if date not in datadict:
datadict[date] = {key: NA for key in ALL_STATES}
datadict[date][statename] = val
df = pd.DataFrame.from_records(datadict).T
df = df.reset_index()
df.columns = ['date'] + ALL_STATES
csvdata = df.to_csv(index=False)
return csvdata
def hospitalization_last60days(db_uri):
return hospitalization(db_uri, last_60_days=True)
def DL_hospitalization_overall(db_uri):
key = 'DL.hospitalization.overall'
return get_generic_query_result(db_uri, key)
def DL_hospitalization_60days(db_uri):
key = 'DL.hospitalization.60days'
return get_generic_query_result(db_uri, key)
def DL_containment_zones(db_uri):
key = 'DL.containment.zones'
return get_generic_query_result(db_uri, key)
def DL_rtpcr_percentage(db_uri):
key = 'DL.rtpcr.percentage'
return get_generic_query_result(db_uri, key)
def GA_hospitalization(db_uri):
key = 'GA.hospitalization'
return get_generic_query_result(db_uri, key)
def HR_gender_samples(db_uri):
key = 'HR.gender.wise.samples'
return get_generic_query_result(db_uri, key)
def HR_homeisolation(db_uri):
key = 'HR.home.isolation'
return get_generic_query_result(db_uri, key)
def KA_gender_fatalities(db_uri):
key = 'KA.gender.wise.fatalities'
data = get_generic_query_result(db_uri, key, return_csv=False)
data = data.pivot_table(index=['month'], columns=['gender'], values=['count']).fillna('N/A').reset_index()
data = data.values.tolist()
data = pd.DataFrame(data, columns=['month', 'fatalities (female)', 'fatalities (male)'])
total = data['fatalities (female)'] + data['fatalities (male)']
data['fatalities (female)'] = data['fatalities (female)'] * 100.0 / total
data['fatalities (male)'] = data['fatalities (male)'] * 100.0 / total
data = data.to_csv(index=False)
return data
def KA_agewise_fatalities(db_uri):
def transform(val):
low = int(val/10.0) * 10
return f'{low}-{low+10}'
key = 'KA.age.wise.fatalities'
data = get_generic_query_result(db_uri, key, return_csv=False)
data['count'] = 1.0
data['age'] = data['age'].apply(transform)
data = data.pivot_table(index=['month'], columns=['age'], values=['count'], aggfunc='count').fillna(0).reset_index()
data = data.T.reset_index(drop=True, level=[0]).T
colorder = sorted(list(data.columns), key=lambda x: int(x.split('-')[0]) if x != '' else -1)
data = data[colorder]
cols = list(data.columns)
cols[0] = 'Month'
data.columns = cols
data = data.to_csv(index=False)
return data
def KL_gender_fatalities(db_uri):
key = 'KL.gender.wise.fatalities'
data = get_generic_query_result(db_uri, key, return_csv=False)
data = data.pivot_table(index=['month'], columns=['gender'], values=['count']).fillna('N/A').reset_index()
data = data.values.tolist()
data = pd.DataFrame(data, columns=['month', 'fatalities (female)', 'fatalities (male)'])
total = data['fatalities (female)'] + data['fatalities (male)']
data['fatalities (female)'] = data['fatalities (female)'] * 100.0 / total
data['fatalities (male)'] = data['fatalities (male)'] * 100.0 / total
data = data.to_csv(index=False)
return data
def KL_agewise_fatalities(db_uri):
def transform(val):
low = int(val/10.0) * 10
return f'{low}-{low+10}'
key = 'KL.age.wise.fatalities'
data = get_generic_query_result(db_uri, key, return_csv=False)
data['count'] = 1.0
data['age'] = data['age'].apply(transform)
data = data.pivot_table(index=['month'], columns=['age'], values=['count'], aggfunc='count').fillna(0).reset_index()
data = data.T.reset_index(drop=True, level=[0]).T
colorder = sorted(list(data.columns), key=lambda x: int(x.split('-')[0]) if x != '' else -1)
data = data[colorder]
cols = list(data.columns)
cols[0] = 'Month'
data.columns = cols
data = data.to_csv(index=False)
return data | 30.447514 | 120 | 0.65215 | import sqlite3
import pandas as pd
import json
def get_queries():
CONFIGPATH = './configs/visualization.sql.json'
with open(CONFIGPATH, 'r') as f:
queries = json.load(f)
return queries
def get_generic_query_result(db_uri, queryid, return_csv=True):
queries = get_queries()
query = queries[queryid]
sql = query['query']
cols = query['columns']
data = read_from_db(db_uri, sql)
df = pd.DataFrame(data)
df.columns = cols
if return_csv:
csvdata = df.to_csv(index=False)
return csvdata
return df
def read_from_db(db_uri, query):
try:
con = sqlite3.connect(db_uri, uri=True)
cursor = con.cursor()
cursor.execute(query)
except Exception as err:
print(err)
records = None
else:
records = cursor.fetchall()
finally:
con.close()
return records
def hospitalization(db_uri, last_60_days=False):
with open('./configs/visualization.sql.json', 'r') as f:
queries = json.load(f)
if last_60_days:
hospital_query = queries['hospitalizations.queries.60days']
else:
hospital_query = queries['hospitalizations.queries']
datadict = {}
ALL_STATES = sorted(hospital_query.keys())
NA = "N/A"
for statename in ALL_STATES:
query = hospital_query[statename]
records = read_from_db(db_uri, query)
if records is not None:
for date, val in records:
if date not in datadict:
datadict[date] = {key: NA for key in ALL_STATES}
datadict[date][statename] = val
df = pd.DataFrame.from_records(datadict).T
df = df.reset_index()
df.columns = ['date'] + ALL_STATES
csvdata = df.to_csv(index=False)
return csvdata
def hospitalization_last60days(db_uri):
return hospitalization(db_uri, last_60_days=True)
def DL_hospitalization_overall(db_uri):
key = 'DL.hospitalization.overall'
return get_generic_query_result(db_uri, key)
def DL_hospitalization_60days(db_uri):
key = 'DL.hospitalization.60days'
return get_generic_query_result(db_uri, key)
def DL_containment_zones(db_uri):
key = 'DL.containment.zones'
return get_generic_query_result(db_uri, key)
def DL_rtpcr_percentage(db_uri):
key = 'DL.rtpcr.percentage'
return get_generic_query_result(db_uri, key)
def GA_hospitalization(db_uri):
key = 'GA.hospitalization'
return get_generic_query_result(db_uri, key)
def HR_gender_samples(db_uri):
key = 'HR.gender.wise.samples'
return get_generic_query_result(db_uri, key)
def HR_homeisolation(db_uri):
key = 'HR.home.isolation'
return get_generic_query_result(db_uri, key)
def KA_gender_fatalities(db_uri):
key = 'KA.gender.wise.fatalities'
data = get_generic_query_result(db_uri, key, return_csv=False)
data = data.pivot_table(index=['month'], columns=['gender'], values=['count']).fillna('N/A').reset_index()
data = data.values.tolist()
data = pd.DataFrame(data, columns=['month', 'fatalities (female)', 'fatalities (male)'])
total = data['fatalities (female)'] + data['fatalities (male)']
data['fatalities (female)'] = data['fatalities (female)'] * 100.0 / total
data['fatalities (male)'] = data['fatalities (male)'] * 100.0 / total
data = data.to_csv(index=False)
return data
def KA_agewise_fatalities(db_uri):
def transform(val):
low = int(val/10.0) * 10
return f'{low}-{low+10}'
key = 'KA.age.wise.fatalities'
data = get_generic_query_result(db_uri, key, return_csv=False)
data['count'] = 1.0
data['age'] = data['age'].apply(transform)
data = data.pivot_table(index=['month'], columns=['age'], values=['count'], aggfunc='count').fillna(0).reset_index()
data = data.T.reset_index(drop=True, level=[0]).T
colorder = sorted(list(data.columns), key=lambda x: int(x.split('-')[0]) if x != '' else -1)
data = data[colorder]
cols = list(data.columns)
cols[0] = 'Month'
data.columns = cols
data = data.to_csv(index=False)
return data
def KL_gender_fatalities(db_uri):
key = 'KL.gender.wise.fatalities'
data = get_generic_query_result(db_uri, key, return_csv=False)
data = data.pivot_table(index=['month'], columns=['gender'], values=['count']).fillna('N/A').reset_index()
data = data.values.tolist()
data = pd.DataFrame(data, columns=['month', 'fatalities (female)', 'fatalities (male)'])
total = data['fatalities (female)'] + data['fatalities (male)']
data['fatalities (female)'] = data['fatalities (female)'] * 100.0 / total
data['fatalities (male)'] = data['fatalities (male)'] * 100.0 / total
data = data.to_csv(index=False)
return data
def KL_agewise_fatalities(db_uri):
def transform(val):
low = int(val/10.0) * 10
return f'{low}-{low+10}'
key = 'KL.age.wise.fatalities'
data = get_generic_query_result(db_uri, key, return_csv=False)
data['count'] = 1.0
data['age'] = data['age'].apply(transform)
data = data.pivot_table(index=['month'], columns=['age'], values=['count'], aggfunc='count').fillna(0).reset_index()
data = data.T.reset_index(drop=True, level=[0]).T
colorder = sorted(list(data.columns), key=lambda x: int(x.split('-')[0]) if x != '' else -1)
data = data[colorder]
cols = list(data.columns)
cols[0] = 'Month'
data.columns = cols
data = data.to_csv(index=False)
return data | true | true |
f7f9387f465eb1d8b8faca50add2f091dad1ce73 | 711 | py | Python | .history/postImages/index_20201006185606.py | Lambda-School-Labs/Labs27-C-Bridges-To-Prosperity-BE | 9a8289d8550115362c46dea3ed8570b789c09a10 | [
"MIT"
] | 2 | 2020-10-21T22:14:15.000Z | 2020-10-21T22:14:16.000Z | .history/postImages/index_20201006185606.py | Lambda-School-Labs/Labs27-C-Bridges-To-Prosperity-BE | 9a8289d8550115362c46dea3ed8570b789c09a10 | [
"MIT"
] | null | null | null | .history/postImages/index_20201006185606.py | Lambda-School-Labs/Labs27-C-Bridges-To-Prosperity-BE | 9a8289d8550115362c46dea3ed8570b789c09a10 | [
"MIT"
] | null | null | null | import csv
import requests
df = open("bridgeData3.csv",'r').readlines()
fin = open('final.csv','r').readlines()
finCsv = fin[1:]
# url = https://b2ptc.herokuapp.com/bridges
finalCsv = df[1:]
obj = {}
for i in finalCsv:
x = i.split(',')
obj[x[1]] = {'bridge_name':x[0],'proj_code':x[1],'before_img':x[2],'after_img':x[3]}
print(finCsv[0])
for i in finCsv:
x = i.split(',')
# for i in finalCsv:
# x = i.split(',')
# requests.put(url+x[0],data={before:x[2],after:x[3]})
# pull each id,before image and after from df
# for each data item do a put request with the id as the param id
# and then put the before and after image in an dict and place it as the data for the put request
| 29.625 | 97 | 0.637131 | import csv
import requests
df = open("bridgeData3.csv",'r').readlines()
fin = open('final.csv','r').readlines()
finCsv = fin[1:]
finalCsv = df[1:]
obj = {}
for i in finalCsv:
x = i.split(',')
obj[x[1]] = {'bridge_name':x[0],'proj_code':x[1],'before_img':x[2],'after_img':x[3]}
print(finCsv[0])
for i in finCsv:
x = i.split(',')
| true | true |
f7f939cd9e9e7cce717c5d8c9b17638fa7af00fe | 8,915 | py | Python | histogram.py | mcm7f/thesis | 412f35de9b1ce25ed4447d077a2a5292a57063f9 | [
"MIT"
] | 1 | 2015-07-24T04:26:45.000Z | 2015-07-24T04:26:45.000Z | histogram.py | mcm7f/thesis | 412f35de9b1ce25ed4447d077a2a5292a57063f9 | [
"MIT"
] | null | null | null | histogram.py | mcm7f/thesis | 412f35de9b1ce25ed4447d077a2a5292a57063f9 | [
"MIT"
] | null | null | null | # Need to parse .csv log files, process them, and plot results
# in an organize fashion.
# Thesis work
# Michael C. Murphy
# Code started: March 1, 2016
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib.mlab as mlab # what is this?
from math import log
from statistics import variance
import time
def main():
print( "Detected", len(sys.argv), "arguments")
# I need to process data files for slopes and append them to x
x = []
y = []
# Taken from matplotlib.org/1.2.1/examples/pylab_examples/histogram_demo.html
#mu, sigma = 100, 15
#x = mu + sigma*np.random.randn(10000)
#x = np.random.randn(10000)
# Here is the array of box widths
d = [3, 5, 10, 20, 30, 50, 100, 150, 300]
F = {} # Data Dictionary using filenames as keys
filelist = sys.argv[1:] # hold a list of files used
for filename in filelist:
N = {} # Data Dictonary holding Noise data
file = open(filename, 'r')
for line in file:
if line[0] != '#':
line = line.strip()
data = line.split(',')
# Noise % is the key, the array of counted boxes is the data
N[ data[1] ] = data[4:13]
F[filename] = N
# Steal image file name from the path:
image_name = sys.argv[1].split("/")
image_name = image_name[-1].split("_")
image_name = image_name[0]
# Debug print the size of our data structure
print(">> Size of F:",len(F))
# Now that we've read in the data, it is time to process it.
R = {} # Data Dictionary holding aggregate results
for filekey in F:
for noisekey in F[filekey]:
# F[filekey][noisekey] holds one array of 9 boxcounts
# Need to calculate an arithmetic mean of the dimension (dim_mean)
log_bc = []
# store the log(boxcounts)
for bc in F[filekey][noisekey]:
bc = int(bc)
if( bc == 0 ):
log_bc.append( log(1) )
else:
log_bc.append( log(bc) )
slopes = []
# Calculate Dimension slopes by taking delta(log(boxcounts) / delta(log(1/d))
for i in range(len(d)-1):
slopes.append( (log_bc[i] - log_bc[i+1]) / (log(1/d[i]) - log(1/d[i+1])) )
if( noisekey == "0.0" ):
print("NoiseKey:", noisekey, "Slopes: ", slopes)
x += slopes # append slopes to x
if( noisekey == "0.001" ):
print("NoiseKey:", noisekey, "Slopes: ", slopes)
y += slopes # append slopes to x
dim_mean = np.mean(slopes)
# Need to calculate the variance of the dimensional slopes (dsl_var)
dsl_var = np.var(slopes, ddof=1) #ddof = 1 matches old-style variance calculations
# Add each dim/var calculation to an array and store in results.
if noisekey in R:
R[noisekey].append( (dim_mean,dsl_var) )
else:
R[noisekey] = [ (dim_mean,dsl_var) ]
# Plot slopes
# the histogram of the data
print(">> Counted", len(x), "slopes...")
print(">> Slope vector: ", x)
binCount = 50
n, bins, patches = plt.hist(x, binCount, normed=1, facecolor='green', alpha=0.50)
n, bins, patches = plt.hist(y, binCount, normed=1, facecolor='red', alpha=0.50)
# add a 'best fit' line
#y = mlab.normpdf( bins, mu, sigma )
#l = plt.plot(bins, y, 'r--', linewidth=1)
plt.xlabel('Dimensional Estimate')
plt.ylabel('Count')
#plt.title(r'$\mathrm{Histogram\ of\ IQ:}\ \mu=100,\ \sigma=15$')
#plt.axis([1,2.1,0,20])
plt.grid(True)
plt.show()
# Now all the results should be processed; currently R is an array of tuples (Dim, Var)
print("Size of R:", len(R), "# results:",len(R['0.2']))
#print(">>",R['0.2'])
# separate the values and run statistics on them.
aggregated_results = [] # store final data to print here
for noisekey in R:
dim_array = []
dsl_array = []
# separate the data
for dataset in R[noisekey]: # dataset is 100 pairs of (Dim, Var)
dim_array.append(dataset[0])
dsl_array.append(dataset[1])
# calculate statistics
average_dimensional_estimate = np.mean(dim_array)
average_slope_variance_estimate = np.mean(dsl_array)
dim_standard_error = np.std(dim_array,ddof=1)/len(R[noisekey])
dsl_standard_error = np.std(dsl_array,ddof=1)/len(R[noisekey])
# add to aggregated results
aggregated_results.append( (float(noisekey), average_dimensional_estimate, dim_standard_error, average_slope_variance_estimate, dsl_standard_error) )
aggregated_results.sort()
#for item in aggregated_results:
# print(">> ", item)
# TODO: Need to save this data to a file
aggregate_datalog( aggregated_results, filelist, image_name )
# Attempt to plot:
nx = []
dimy = []
vary = []
dimerr = []
varerr = []
for item in aggregated_results:
nx.append( item[0] )
dimy.append( item[1] )
dimerr.append( item[2] )
vary.append( item[3] )
varerr.append( item[4] )
fig, axarr = plt.subplots(2, sharex=True)
fig.suptitle("Box Count Algorithm on " + image_name + " (Uniform Noise, 100 Seeds)", fontsize=14, fontweight='bold')
axarr[0].set_ylabel("dimension")
axarr[0].set_xscale('log')
axarr[0].set_title("Mean Fractal Dimension vs. Noise %")
axarr[0].set_ylim(0,2)
axarr[0].errorbar(nx,dimy,dimerr,fmt='r')
axarr[0].plot(nx,dimy, label="dimension")
axarr[1].set_ylabel("slope variance")
axarr[1].set_xlabel("noise %")
axarr[1].set_xscale('log')
axarr[1].set_title("Mean Slope Variance vs. Noise %")
axarr[1].set_ylim(0,1)
axarr[1].errorbar(nx,vary,varerr,fmt='r')
axarr[1].plot(nx,vary, label="variance")
plt.savefig("figures/" + image_name + "_uniform_D_V_vs_N.png")
#plt.show()
# results_array - an array of tuples of the form (noise, dimension, dimension std err, variance, variance std err)
# filelist - a list of filenames that were included in the aggregated data
# Version: V1.00 - initial log format
def aggregate_datalog( results_array, filelist, image_name ):
LOG_VERSION = "1.00"
pathname = "logfiles/"
filename = pathname + image_name + "_" + str(len(filelist)) + "_aggregateLog.csv"
log = open(filename, 'w')
# Write the header
log.write("# Aggregate Log Version: " + LOG_VERSION + ",,,,\n")
log.write("# Log Name: " + filename + ",,,,\n")
log.write("# Noise%, Dimension, Dim Std Err, Variance, Var Std Err\n")
# Write the data
for data in results_array:
log.write(str(data[0]) + "," + str(data[1]) + "," + str(data[2]) + "," + str(data[3]) + "," + str(data[4]) + "\n")
# Write a list of the files included in this data aggregation
log.write("# The data files below are included in this aggregation:,,,,\n")
for file in filelist:
log.write("# " + file + ",,,,\n")
print(">> Created aggregate datalog:", filename)
log.close()
main()
'''
# example data
#x = np.arange(0, 10, 1)
noise = np.array([0.0001, 0.001, 0.01, 0.1, 1, 10, 50])
dim = np.array([1.1, 1.15, 1.3, 1.6, 1.85, 1.95, 2])
var = np.array([0.1, 0.3, 0.2, 0.1, 0.01, 0.001, 0])
# example variable error bar values
stderr = np.array([.01,.1,.1,.05,.02,.01,0])
#xerr = 0.1 + yerr
# First illustrate basic byplot interface, using defaults where possible
#fig = plt.figure() # what does this do?
#fig.suptitle("Main Title", fontsize=14, fontweight='bold')
fig, axarr = plt.subplots(2, sharex=True)
fig.suptitle("Dimension and Slope Variance vs. Noise %", fontsize=14, fontweight='bold')
axarr[0].set_ylabel("dimension")
axarr[0].set_xscale('log')
axarr[0].errorbar(noise,dim,stderr,fmt='ro')
axarr[0].plot(noise,dim, label="dimension")
axarr[1].set_ylabel("slope variance")
axarr[1].set_xlabel("noise %")
axarr[1].set_xscale('log')
axarr[1].errorbar(noise,var,stderr,fmt='ro')
axarr[1].plot(noise,var, label="variance")
'''
'''
# create subplot (so that axis can be manipulated
ax = fig.add_subplot(111)
ax.set_title("subtitle")
ax.set_xlabel("noise axis")
ax.set_ylabel("dimension")
ax.set_xscale('log') # set x-axis to log scale
#plt.errorbar(x, dim, yerr=yerr, fmt='ro') # error bar plot, formatting
ax.errorbar(noise,dim, stderr, fmt='ro')
ax.errorbar(noise,var, stderr, fmt='ro')
ax.plot(noise,dim) # normal plot, formatting
ax.plot(noise,var)
#plt.title("Simplest errorbars, 0.2 in x, 0.4 in y")
'''
'''
plt.savefig("thesisPlotsExcample.png")
plt.show()
'''
| 30.118243 | 157 | 0.599663 |
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib.mlab as mlab
from math import log
from statistics import variance
import time
def main():
print( "Detected", len(sys.argv), "arguments")
x = []
y = []
d = [3, 5, 10, 20, 30, 50, 100, 150, 300]
F = {}
filelist = sys.argv[1:]
for filename in filelist:
N = {}
file = open(filename, 'r')
for line in file:
if line[0] != '#':
line = line.strip()
data = line.split(',')
N[ data[1] ] = data[4:13]
F[filename] = N
image_name = sys.argv[1].split("/")
image_name = image_name[-1].split("_")
image_name = image_name[0]
print(">> Size of F:",len(F))
R = {} # Data Dictionary holding aggregate results
for filekey in F:
for noisekey in F[filekey]:
# F[filekey][noisekey] holds one array of 9 boxcounts
# Need to calculate an arithmetic mean of the dimension (dim_mean)
log_bc = []
# store the log(boxcounts)
for bc in F[filekey][noisekey]:
bc = int(bc)
if( bc == 0 ):
log_bc.append( log(1) )
else:
log_bc.append( log(bc) )
slopes = []
# Calculate Dimension slopes by taking delta(log(boxcounts) / delta(log(1/d))
for i in range(len(d)-1):
slopes.append( (log_bc[i] - log_bc[i+1]) / (log(1/d[i]) - log(1/d[i+1])) )
if( noisekey == "0.0" ):
print("NoiseKey:", noisekey, "Slopes: ", slopes)
x += slopes # append slopes to x
if( noisekey == "0.001" ):
print("NoiseKey:", noisekey, "Slopes: ", slopes)
y += slopes # append slopes to x
dim_mean = np.mean(slopes)
# Need to calculate the variance of the dimensional slopes (dsl_var)
dsl_var = np.var(slopes, ddof=1) #ddof = 1 matches old-style variance calculations
# Add each dim/var calculation to an array and store in results.
if noisekey in R:
R[noisekey].append( (dim_mean,dsl_var) )
else:
R[noisekey] = [ (dim_mean,dsl_var) ]
# Plot slopes
# the histogram of the data
print(">> Counted", len(x), "slopes...")
print(">> Slope vector: ", x)
binCount = 50
n, bins, patches = plt.hist(x, binCount, normed=1, facecolor='green', alpha=0.50)
n, bins, patches = plt.hist(y, binCount, normed=1, facecolor='red', alpha=0.50)
# add a 'best fit' line
#y = mlab.normpdf( bins, mu, sigma )
#l = plt.plot(bins, y, 'r--', linewidth=1)
plt.xlabel('Dimensional Estimate')
plt.ylabel('Count')
#plt.title(r'$\mathrm{Histogram\ of\ IQ:}\ \mu=100,\ \sigma=15$')
#plt.axis([1,2.1,0,20])
plt.grid(True)
plt.show()
# Now all the results should be processed; currently R is an array of tuples (Dim, Var)
print("Size of R:", len(R), "# results:",len(R['0.2']))
#print(">>",R['0.2'])
# separate the values and run statistics on them.
aggregated_results = [] # store final data to print here
for noisekey in R:
dim_array = []
dsl_array = []
# separate the data
for dataset in R[noisekey]: # dataset is 100 pairs of (Dim, Var)
dim_array.append(dataset[0])
dsl_array.append(dataset[1])
# calculate statistics
average_dimensional_estimate = np.mean(dim_array)
average_slope_variance_estimate = np.mean(dsl_array)
dim_standard_error = np.std(dim_array,ddof=1)/len(R[noisekey])
dsl_standard_error = np.std(dsl_array,ddof=1)/len(R[noisekey])
# add to aggregated results
aggregated_results.append( (float(noisekey), average_dimensional_estimate, dim_standard_error, average_slope_variance_estimate, dsl_standard_error) )
aggregated_results.sort()
#for item in aggregated_results:
# print(">> ", item)
# TODO: Need to save this data to a file
aggregate_datalog( aggregated_results, filelist, image_name )
# Attempt to plot:
nx = []
dimy = []
vary = []
dimerr = []
varerr = []
for item in aggregated_results:
nx.append( item[0] )
dimy.append( item[1] )
dimerr.append( item[2] )
vary.append( item[3] )
varerr.append( item[4] )
fig, axarr = plt.subplots(2, sharex=True)
fig.suptitle("Box Count Algorithm on " + image_name + " (Uniform Noise, 100 Seeds)", fontsize=14, fontweight='bold')
axarr[0].set_ylabel("dimension")
axarr[0].set_xscale('log')
axarr[0].set_title("Mean Fractal Dimension vs. Noise %")
axarr[0].set_ylim(0,2)
axarr[0].errorbar(nx,dimy,dimerr,fmt='r')
axarr[0].plot(nx,dimy, label="dimension")
axarr[1].set_ylabel("slope variance")
axarr[1].set_xlabel("noise %")
axarr[1].set_xscale('log')
axarr[1].set_title("Mean Slope Variance vs. Noise %")
axarr[1].set_ylim(0,1)
axarr[1].errorbar(nx,vary,varerr,fmt='r')
axarr[1].plot(nx,vary, label="variance")
plt.savefig("figures/" + image_name + "_uniform_D_V_vs_N.png")
#plt.show()
# results_array - an array of tuples of the form (noise, dimension, dimension std err, variance, variance std err)
# filelist - a list of filenames that were included in the aggregated data
# Version: V1.00 - initial log format
def aggregate_datalog( results_array, filelist, image_name ):
LOG_VERSION = "1.00"
pathname = "logfiles/"
filename = pathname + image_name + "_" + str(len(filelist)) + "_aggregateLog.csv"
log = open(filename, 'w')
# Write the header
log.write("# Aggregate Log Version: " + LOG_VERSION + ",,,,\n")
log.write("# Log Name: " + filename + ",,,,\n")
log.write("# Noise%, Dimension, Dim Std Err, Variance, Var Std Err\n")
# Write the data
for data in results_array:
log.write(str(data[0]) + "," + str(data[1]) + "," + str(data[2]) + "," + str(data[3]) + "," + str(data[4]) + "\n")
# Write a list of the files included in this data aggregation
log.write("# The data files below are included in this aggregation:,,,,\n")
for file in filelist:
log.write("# " + file + ",,,,\n")
print(">> Created aggregate datalog:", filename)
log.close()
main()
| true | true |
f7f939dbed1408a7a84c24d2e2225ab404aee461 | 3,655 | py | Python | datahub/search/omis/models.py | Staberinde/data-hub-api | 3d0467dbceaf62a47158eea412a3dba827073300 | [
"MIT"
] | null | null | null | datahub/search/omis/models.py | Staberinde/data-hub-api | 3d0467dbceaf62a47158eea412a3dba827073300 | [
"MIT"
] | 4 | 2021-06-30T10:34:50.000Z | 2021-06-30T10:34:51.000Z | datahub/search/omis/models.py | Staberinde/data-hub-api | 3d0467dbceaf62a47158eea412a3dba827073300 | [
"MIT"
] | null | null | null | from elasticsearch_dsl import Boolean, Date, Integer, Keyword, Text
from datahub.search import dict_utils
from datahub.search import fields
from datahub.search.models import BaseESModel
class Order(BaseESModel):
"""Elasticsearch representation of Order model."""
id = Keyword()
reference = fields.NormalizedKeyword(
fields={
'trigram': fields.TrigramText(),
},
)
status = fields.NormalizedKeyword()
company = fields.company_field()
contact = fields.contact_or_adviser_field()
created_by = fields.contact_or_adviser_field(include_dit_team=True)
created_on = Date()
modified_on = Date()
primary_market = fields.id_name_field()
sector = fields.sector_field()
uk_region = fields.id_name_field()
description = fields.EnglishText()
contacts_not_to_approach = Text()
further_info = Text()
existing_agents = Text(index=False)
delivery_date = Date()
service_types = fields.id_name_field()
contact_email = fields.NormalizedKeyword()
contact_phone = Keyword()
subscribers = fields.contact_or_adviser_field(include_dit_team=True)
assignees = fields.contact_or_adviser_field(include_dit_team=True)
po_number = Keyword(index=False)
discount_value = Integer(index=False)
vat_status = Keyword(index=False)
vat_number = Keyword(index=False)
vat_verified = Boolean(index=False)
net_cost = Integer(index=False)
subtotal_cost = Integer(
fields={
'keyword': Keyword(),
},
)
vat_cost = Integer(index=False)
total_cost = Integer(
fields={
'keyword': Keyword(),
},
)
payment_due_date = Date()
paid_on = Date()
completed_by = fields.contact_or_adviser_field()
completed_on = Date()
cancelled_by = fields.contact_or_adviser_field()
cancelled_on = Date()
cancellation_reason = fields.id_name_field()
billing_company_name = Text()
billing_contact_name = Text()
billing_email = fields.NormalizedKeyword()
billing_phone = fields.NormalizedKeyword()
billing_address_1 = Text()
billing_address_2 = Text()
billing_address_town = fields.NormalizedKeyword()
billing_address_county = fields.NormalizedKeyword()
billing_address_postcode = Text()
billing_address_country = fields.id_name_field()
MAPPINGS = {
'company': dict_utils.company_dict,
'contact': dict_utils.contact_or_adviser_dict,
'created_by': dict_utils.adviser_dict_with_team,
'primary_market': dict_utils.id_name_dict,
'sector': dict_utils.sector_dict,
'uk_region': dict_utils.id_name_dict,
'service_types': lambda col: [dict_utils.id_name_dict(c) for c in col.all()],
'subscribers': lambda col: [
dict_utils.contact_or_adviser_dict(c.adviser, include_dit_team=True) for c in col.all()
],
'assignees': lambda col: [
dict_utils.contact_or_adviser_dict(c.adviser, include_dit_team=True) for c in col.all()
],
'billing_address_country': dict_utils.id_name_dict,
'completed_by': dict_utils.contact_or_adviser_dict,
'cancelled_by': dict_utils.contact_or_adviser_dict,
'cancellation_reason': dict_utils.id_name_dict,
}
COMPUTED_MAPPINGS = {
'payment_due_date': lambda x: x.invoice.payment_due_date if x.invoice else None,
}
SEARCH_FIELDS = (
'id',
'reference.trigram',
'company.name',
'company.name.trigram',
'contact.name',
'contact.name.trigram',
'total_cost.keyword',
'subtotal_cost.keyword',
)
| 34.481132 | 99 | 0.681532 | from elasticsearch_dsl import Boolean, Date, Integer, Keyword, Text
from datahub.search import dict_utils
from datahub.search import fields
from datahub.search.models import BaseESModel
class Order(BaseESModel):
id = Keyword()
reference = fields.NormalizedKeyword(
fields={
'trigram': fields.TrigramText(),
},
)
status = fields.NormalizedKeyword()
company = fields.company_field()
contact = fields.contact_or_adviser_field()
created_by = fields.contact_or_adviser_field(include_dit_team=True)
created_on = Date()
modified_on = Date()
primary_market = fields.id_name_field()
sector = fields.sector_field()
uk_region = fields.id_name_field()
description = fields.EnglishText()
contacts_not_to_approach = Text()
further_info = Text()
existing_agents = Text(index=False)
delivery_date = Date()
service_types = fields.id_name_field()
contact_email = fields.NormalizedKeyword()
contact_phone = Keyword()
subscribers = fields.contact_or_adviser_field(include_dit_team=True)
assignees = fields.contact_or_adviser_field(include_dit_team=True)
po_number = Keyword(index=False)
discount_value = Integer(index=False)
vat_status = Keyword(index=False)
vat_number = Keyword(index=False)
vat_verified = Boolean(index=False)
net_cost = Integer(index=False)
subtotal_cost = Integer(
fields={
'keyword': Keyword(),
},
)
vat_cost = Integer(index=False)
total_cost = Integer(
fields={
'keyword': Keyword(),
},
)
payment_due_date = Date()
paid_on = Date()
completed_by = fields.contact_or_adviser_field()
completed_on = Date()
cancelled_by = fields.contact_or_adviser_field()
cancelled_on = Date()
cancellation_reason = fields.id_name_field()
billing_company_name = Text()
billing_contact_name = Text()
billing_email = fields.NormalizedKeyword()
billing_phone = fields.NormalizedKeyword()
billing_address_1 = Text()
billing_address_2 = Text()
billing_address_town = fields.NormalizedKeyword()
billing_address_county = fields.NormalizedKeyword()
billing_address_postcode = Text()
billing_address_country = fields.id_name_field()
MAPPINGS = {
'company': dict_utils.company_dict,
'contact': dict_utils.contact_or_adviser_dict,
'created_by': dict_utils.adviser_dict_with_team,
'primary_market': dict_utils.id_name_dict,
'sector': dict_utils.sector_dict,
'uk_region': dict_utils.id_name_dict,
'service_types': lambda col: [dict_utils.id_name_dict(c) for c in col.all()],
'subscribers': lambda col: [
dict_utils.contact_or_adviser_dict(c.adviser, include_dit_team=True) for c in col.all()
],
'assignees': lambda col: [
dict_utils.contact_or_adviser_dict(c.adviser, include_dit_team=True) for c in col.all()
],
'billing_address_country': dict_utils.id_name_dict,
'completed_by': dict_utils.contact_or_adviser_dict,
'cancelled_by': dict_utils.contact_or_adviser_dict,
'cancellation_reason': dict_utils.id_name_dict,
}
COMPUTED_MAPPINGS = {
'payment_due_date': lambda x: x.invoice.payment_due_date if x.invoice else None,
}
SEARCH_FIELDS = (
'id',
'reference.trigram',
'company.name',
'company.name.trigram',
'contact.name',
'contact.name.trigram',
'total_cost.keyword',
'subtotal_cost.keyword',
)
| true | true |
f7f939dcb0a5a76dbe6ecd96c79470376e34207d | 5,110 | py | Python | python_experiments/data_analysis/figures_icde19/opt_gpu.py | mexuaz/AccTrussDecomposition | 15a9e8fd2f123f5acace5f3b40b94f1a74eb17d4 | [
"MIT"
] | 9 | 2020-03-30T13:00:15.000Z | 2022-03-17T13:40:17.000Z | python_experiments/data_analysis/figures_icde19/opt_gpu.py | mexuaz/AccTrussDecomposition | 15a9e8fd2f123f5acace5f3b40b94f1a74eb17d4 | [
"MIT"
] | null | null | null | python_experiments/data_analysis/figures_icde19/opt_gpu.py | mexuaz/AccTrussDecomposition | 15a9e8fd2f123f5acace5f3b40b94f1a74eb17d4 | [
"MIT"
] | 2 | 2020-08-17T10:05:51.000Z | 2020-08-30T22:57:55.000Z | import json
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from data_analysis.figures_icde19.general_config import *
from data_analysis.figures_icde19.parse_overall.parse_gpu_results import varying_gpu_tag, summary_tag, \
off_tc_tag, off_cpu_iep_tag, off_gpu_iep_tag, off_iep_total_tag, config_lst
from data_analysis.figures_icde19.parse_overall.parse_support_initialization import si_dir
from data_analysis.util.read_file_utils import *
from data_analysis.vis.vis_util import *
FIG_SIZE_MULTIPLE = (16, 4.5)
data_set_lst = ['webgraph_eu', 'webgraph_it', 'webgraph_twitter']
cuda_off_load_opt = 'cuda-pkt-offload-opt'
cuda_off_load = 'cuda-pkt-offload'
cuda_off_load_shrink = 'cuda-pkt-shrink-all-opt'
def get_opt_cpu_tc_lst():
with open('{}/{}/{}'.format('parse_overall', si_dir, 'pkt-eval-tc-wp.json')) as ifs:
tc_wp_si = json.load(ifs)
return [tc_wp_si[data]['40'] for data in data_set_lst]
def get_opt_cpu_iep_lst(cpu_exp_dir='exp-2019-10-04-eid'):
with open('parse_overall/varying_cpu/{}/{}.json'.format(cpu_exp_dir, 'pkt-bmpf')) as ifs:
bmpf_dict = json.load(ifs)
with open('parse_overall/varying_cpu/{}/{}.json'.format(cpu_exp_dir, 'pkt-inter-shrink')) as ifs:
bmpf_idx_dict = json.load(ifs)
def get_single_iep_time(data_dict, data):
return sum([data_dict[data][tag] for tag in ["Sync Time", "Shrink Time", "Scan Time", "Proc Time"]])
return [min(get_single_iep_time(bmpf_dict, data), get_single_iep_time(bmpf_idx_dict, data)) for data in
data_set_lst]
def get_off_iep_with_tag(tag, exec_name, lst):
with open('parse_overall/{}/{}/{}.json'.format(varying_gpu_tag, config_lst[0], exec_name)) as ifs:
cuda_offload_opt_dict = json.load(ifs)
return [cuda_offload_opt_dict[data][summary_tag][tag] for data in lst]
def get_off_tc():
return get_off_iep_with_tag(off_tc_tag, cuda_off_load_opt, data_set_lst)
bar_lst_lst = [
get_opt_cpu_tc_lst(), # OPT-CPU-TC
get_off_tc(), # OFF-TC
get_opt_cpu_iep_lst(), # OPT-CPU-IEP
get_off_iep_with_tag(off_iep_total_tag, cuda_off_load_shrink, data_set_lst),
get_off_iep_with_tag(off_iep_total_tag, cuda_off_load_opt, data_set_lst),
get_off_iep_with_tag(off_cpu_iep_tag, cuda_off_load_opt, data_set_lst),
get_off_iep_with_tag(off_gpu_iep_tag, cuda_off_load_opt, data_set_lst),
]
bar_legend_lst = ['\\textbf{' + name + '}' for name in
['OPT-TC', 'OFF-TC', 'OPT-IEP', 'OFF-EIEP',
'OFF-RIEP-Total',
'OFF-RIEP-CPU',
'OFF-RIEP-GPU']]
dataset_abbr_lst = ['WE', 'WI', 'TW']
for idx, bar_lst in enumerate(bar_lst_lst):
print(bar_legend_lst[idx], bar_lst)
def draw_bars(bar_lst_lst, legend_label_lst, x_tick_label_lst, x_label_name, fig_folder, file_name):
size_of_fig = (FIG_SIZE_MULTIPLE[0], FIG_SIZE_MULTIPLE[1])
fig, ax = plt.subplots()
assert len(bar_lst_lst) > 0
N = len(bar_lst_lst[0])
assert N == len(x_tick_label_lst)
# indent lst
width = 1.1 / len(legend_label_lst)
ind = 1.3 * np.arange(N) # the x locations for the groups
indent_lst = [ind + idx * width for idx in range(len(bar_lst_lst))]
for i in range(2, 5):
indent_lst[i] += 0.3 * width
for i in range(5, 7):
indent_lst[i] += 0.6 * width
# 1st: bars
for idx, bar_lst in enumerate(bar_lst_lst):
my_bar = ax.bar(indent_lst[idx], bar_lst, width, hatch=hatch_lst[idx], label=legend_label_lst[idx],
edgecolor=color_lst[idx], fill=False)
autolabel(ax, my_bar, roration=45, fontsize=20)
# 2nd: x and y's ticks and labels
ax.set_xticks(ind + 3.3 * width)
ax.set_xticklabels(x_tick_label_lst, fontsize=LABEL_SIZE)
plt.xticks(fontsize=TICK_SIZE)
plt.yscale('log')
ax.set_ylabel("Time (seconds)", fontsize=LABEL_SIZE)
plt.yticks(fontsize=TICK_SIZE)
max_val = max([max(lst) for lst in bar_lst_lst])
min_val = min([min(list(filter(lambda v: v != 0, lst)) + [max_val]) for lst in bar_lst_lst])
plt.ylim(min_val / 3, max_val * (10 ** 3) * 40)
plt.yticks(list(filter(lambda v: v > min_val / 10, [10 ** i for i in range(-1, 5, 1)])))
ax.set_xlabel(x_label_name, fontsize=LABEL_SIZE)
# 3rd: figure properties
fig.set_size_inches(*size_of_fig) # set ratio
plt.legend(legend_label_lst,
prop={'size': LEGEND_SIZE - 3, "weight": "bold"}, loc="upper left", ncol=4)
plt.tight_layout()
os.system('mkdir -p ' + fig_folder)
fig.savefig(os.sep.join([fig_folder, file_name]), bbox_inches='tight', dpi=300)
plt.close()
def option_time_tag_wrapper(obj):
return obj[time_tag] if obj is not None else 0
if __name__ == '__main__':
# matplotlib.rc('pdf', fonttype=42)
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
for suffix in ['.pdf']:
def draw_varying_algorithm():
draw_bars(bar_lst_lst, bar_legend_lst, dataset_abbr_lst, 'Dataset',
'../data-pdf/icde20', 'OFF-opts' + suffix)
draw_varying_algorithm()
| 35.985915 | 108 | 0.683366 | import json
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from data_analysis.figures_icde19.general_config import *
from data_analysis.figures_icde19.parse_overall.parse_gpu_results import varying_gpu_tag, summary_tag, \
off_tc_tag, off_cpu_iep_tag, off_gpu_iep_tag, off_iep_total_tag, config_lst
from data_analysis.figures_icde19.parse_overall.parse_support_initialization import si_dir
from data_analysis.util.read_file_utils import *
from data_analysis.vis.vis_util import *
FIG_SIZE_MULTIPLE = (16, 4.5)
data_set_lst = ['webgraph_eu', 'webgraph_it', 'webgraph_twitter']
cuda_off_load_opt = 'cuda-pkt-offload-opt'
cuda_off_load = 'cuda-pkt-offload'
cuda_off_load_shrink = 'cuda-pkt-shrink-all-opt'
def get_opt_cpu_tc_lst():
with open('{}/{}/{}'.format('parse_overall', si_dir, 'pkt-eval-tc-wp.json')) as ifs:
tc_wp_si = json.load(ifs)
return [tc_wp_si[data]['40'] for data in data_set_lst]
def get_opt_cpu_iep_lst(cpu_exp_dir='exp-2019-10-04-eid'):
with open('parse_overall/varying_cpu/{}/{}.json'.format(cpu_exp_dir, 'pkt-bmpf')) as ifs:
bmpf_dict = json.load(ifs)
with open('parse_overall/varying_cpu/{}/{}.json'.format(cpu_exp_dir, 'pkt-inter-shrink')) as ifs:
bmpf_idx_dict = json.load(ifs)
def get_single_iep_time(data_dict, data):
return sum([data_dict[data][tag] for tag in ["Sync Time", "Shrink Time", "Scan Time", "Proc Time"]])
return [min(get_single_iep_time(bmpf_dict, data), get_single_iep_time(bmpf_idx_dict, data)) for data in
data_set_lst]
def get_off_iep_with_tag(tag, exec_name, lst):
with open('parse_overall/{}/{}/{}.json'.format(varying_gpu_tag, config_lst[0], exec_name)) as ifs:
cuda_offload_opt_dict = json.load(ifs)
return [cuda_offload_opt_dict[data][summary_tag][tag] for data in lst]
def get_off_tc():
return get_off_iep_with_tag(off_tc_tag, cuda_off_load_opt, data_set_lst)
bar_lst_lst = [
get_opt_cpu_tc_lst(),
get_off_tc(),
get_opt_cpu_iep_lst(),
get_off_iep_with_tag(off_iep_total_tag, cuda_off_load_shrink, data_set_lst),
get_off_iep_with_tag(off_iep_total_tag, cuda_off_load_opt, data_set_lst),
get_off_iep_with_tag(off_cpu_iep_tag, cuda_off_load_opt, data_set_lst),
get_off_iep_with_tag(off_gpu_iep_tag, cuda_off_load_opt, data_set_lst),
]
bar_legend_lst = ['\\textbf{' + name + '}' for name in
['OPT-TC', 'OFF-TC', 'OPT-IEP', 'OFF-EIEP',
'OFF-RIEP-Total',
'OFF-RIEP-CPU',
'OFF-RIEP-GPU']]
dataset_abbr_lst = ['WE', 'WI', 'TW']
for idx, bar_lst in enumerate(bar_lst_lst):
print(bar_legend_lst[idx], bar_lst)
def draw_bars(bar_lst_lst, legend_label_lst, x_tick_label_lst, x_label_name, fig_folder, file_name):
size_of_fig = (FIG_SIZE_MULTIPLE[0], FIG_SIZE_MULTIPLE[1])
fig, ax = plt.subplots()
assert len(bar_lst_lst) > 0
N = len(bar_lst_lst[0])
assert N == len(x_tick_label_lst)
width = 1.1 / len(legend_label_lst)
ind = 1.3 * np.arange(N)
indent_lst = [ind + idx * width for idx in range(len(bar_lst_lst))]
for i in range(2, 5):
indent_lst[i] += 0.3 * width
for i in range(5, 7):
indent_lst[i] += 0.6 * width
for idx, bar_lst in enumerate(bar_lst_lst):
my_bar = ax.bar(indent_lst[idx], bar_lst, width, hatch=hatch_lst[idx], label=legend_label_lst[idx],
edgecolor=color_lst[idx], fill=False)
autolabel(ax, my_bar, roration=45, fontsize=20)
ax.set_xticks(ind + 3.3 * width)
ax.set_xticklabels(x_tick_label_lst, fontsize=LABEL_SIZE)
plt.xticks(fontsize=TICK_SIZE)
plt.yscale('log')
ax.set_ylabel("Time (seconds)", fontsize=LABEL_SIZE)
plt.yticks(fontsize=TICK_SIZE)
max_val = max([max(lst) for lst in bar_lst_lst])
min_val = min([min(list(filter(lambda v: v != 0, lst)) + [max_val]) for lst in bar_lst_lst])
plt.ylim(min_val / 3, max_val * (10 ** 3) * 40)
plt.yticks(list(filter(lambda v: v > min_val / 10, [10 ** i for i in range(-1, 5, 1)])))
ax.set_xlabel(x_label_name, fontsize=LABEL_SIZE)
# 3rd: figure properties
fig.set_size_inches(*size_of_fig) # set ratio
plt.legend(legend_label_lst,
prop={'size': LEGEND_SIZE - 3, "weight": "bold"}, loc="upper left", ncol=4)
plt.tight_layout()
os.system('mkdir -p ' + fig_folder)
fig.savefig(os.sep.join([fig_folder, file_name]), bbox_inches='tight', dpi=300)
plt.close()
def option_time_tag_wrapper(obj):
return obj[time_tag] if obj is not None else 0
if __name__ == '__main__':
# matplotlib.rc('pdf', fonttype=42)
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
for suffix in ['.pdf']:
def draw_varying_algorithm():
draw_bars(bar_lst_lst, bar_legend_lst, dataset_abbr_lst, 'Dataset',
'../data-pdf/icde20', 'OFF-opts' + suffix)
draw_varying_algorithm()
| true | true |
f7f93aac7b9d793ef23c38a97b1f3ca8216eaa8d | 24,348 | py | Python | samples/python/efficientdet/create_onnx.py | L-Net-1992/TensorRT | 34b664d404001bd724cb56b52a6e0e05e1fd97f2 | [
"Apache-2.0"
] | null | null | null | samples/python/efficientdet/create_onnx.py | L-Net-1992/TensorRT | 34b664d404001bd724cb56b52a6e0e05e1fd97f2 | [
"Apache-2.0"
] | null | null | null | samples/python/efficientdet/create_onnx.py | L-Net-1992/TensorRT | 34b664d404001bd724cb56b52a6e0e05e1fd97f2 | [
"Apache-2.0"
] | null | null | null | #
# SPDX-FileCopyrightText: Copyright (c) 1993-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import os
import sys
import argparse
import logging
import tensorflow as tf
import onnx_graphsurgeon as gs
import numpy as np
import onnx
from onnx import shape_inference
from tf2onnx import tfonnx, optimizer, tf_loader
import onnx_utils
logging.basicConfig(level=logging.INFO)
logging.getLogger("EfficientDetGraphSurgeon").setLevel(logging.INFO)
log = logging.getLogger("EfficientDetGraphSurgeon")
class EfficientDetGraphSurgeon:
def __init__(self, saved_model_path):
"""
Constructor of the EfficientDet Graph Surgeon object, to do the conversion of an EfficientDet TF saved model
to an ONNX-TensorRT parsable model.
:param saved_model_path: The path pointing to the TensorFlow saved model to load.
"""
saved_model_path = os.path.realpath(saved_model_path)
assert os.path.exists(saved_model_path)
# Use tf2onnx to convert saved model to an initial ONNX graph.
graph_def, inputs, outputs = tf_loader.from_saved_model(saved_model_path, None, None, "serve",
["serving_default"])
log.info("Loaded saved model from {}".format(saved_model_path))
with tf.Graph().as_default() as tf_graph:
tf.import_graph_def(graph_def, name="")
with tf_loader.tf_session(graph=tf_graph):
onnx_graph = tfonnx.process_tf_graph(tf_graph, input_names=inputs, output_names=outputs, opset=11)
onnx_model = optimizer.optimize_graph(onnx_graph).make_model("Converted from {}".format(saved_model_path))
self.graph = gs.import_onnx(onnx_model)
assert self.graph
log.info("TF2ONNX graph created successfully")
# Fold constants via ONNX-GS that TF2ONNX may have missed
self.graph.fold_constants()
# Try to auto-detect by finding if nodes match a specific name pattern expected for either of the APIs.
self.api = None
if len([node for node in self.graph.nodes if "class_net/" in node.name]) > 0:
self.api = "AutoML"
elif len([node for node in self.graph.nodes if "/WeightSharedConvolutionalClassHead/" in node.name]) > 0:
self.api = "TFOD"
assert self.api
log.info("Graph was detected as {}".format(self.api))
def sanitize(self):
"""
Sanitize the graph by cleaning any unconnected nodes, do a topological resort, and fold constant inputs values.
When possible, run shape inference on the ONNX graph to determine tensor shapes.
"""
for i in range(3):
count_before = len(self.graph.nodes)
self.graph.cleanup().toposort()
try:
for node in self.graph.nodes:
for o in node.outputs:
o.shape = None
model = gs.export_onnx(self.graph)
model = shape_inference.infer_shapes(model)
self.graph = gs.import_onnx(model)
except Exception as e:
log.info("Shape inference could not be performed at this time:\n{}".format(e))
try:
self.graph.fold_constants(fold_shapes=True)
except TypeError as e:
log.error("This version of ONNX GraphSurgeon does not support folding shapes, please upgrade your "
"onnx_graphsurgeon module. Error:\n{}".format(e))
raise
count_after = len(self.graph.nodes)
if count_before == count_after:
# No new folding occurred in this iteration, so we can stop for now.
break
def save(self, output_path):
"""
Save the ONNX model to the given location.
:param output_path: Path pointing to the location where to write out the updated ONNX model.
"""
self.graph.cleanup().toposort()
model = gs.export_onnx(self.graph)
output_path = os.path.realpath(output_path)
os.makedirs(os.path.dirname(output_path), exist_ok=True)
onnx.save(model, output_path)
log.info("Saved ONNX model to {}".format(output_path))
def update_preprocessor(self, input_format, input_size, preprocessor="imagenet"):
"""
Remove all the pre-processing nodes in the ONNX graph and leave only the image normalization essentials.
:param input_format: The input data format, either "NCHW" or "NHWC".
:param input_size: The input size as a comma-separated string in H,W format, e.g. "512,512".
:param preprocessor: The preprocessor to use, either "imagenet" for imagenet mean and stdev normalization,
or "scale_range" for uniform [-1,+1] range normalization.
"""
# Update the input and output tensors shape
input_size = input_size.split(",")
assert len(input_size) == 2
for i in range(len(input_size)):
input_size[i] = int(input_size[i])
assert input_size[i] >= 1
assert input_format in ["NCHW", "NHWC"]
if input_format == "NCHW":
self.graph.inputs[0].shape = ['N', 3, input_size[0], input_size[1]]
if input_format == "NHWC":
self.graph.inputs[0].shape = ['N', input_size[0], input_size[1], 3]
self.graph.inputs[0].dtype = np.float32
self.graph.inputs[0].name = "input"
log.info("ONNX graph input shape: {} [{} format]".format(self.graph.inputs[0].shape, input_format))
self.sanitize()
# Find the initial nodes of the graph, whatever the input is first connected to, and disconnect them
for node in [node for node in self.graph.nodes if self.graph.inputs[0] in node.inputs]:
node.inputs.clear()
# Convert to NCHW format if needed
input_tensor = self.graph.inputs[0]
if input_format == "NHWC":
input_tensor = self.graph.transpose("preprocessor/transpose", input_tensor, [0, 3, 1, 2])
assert preprocessor in ["imagenet", "scale_range"]
preprocessed_tensor = None
if preprocessor == "imagenet":
# RGB Normalizers. The per-channel values are given with shape [1, 3, 1, 1] for proper NCHW shape broadcasting
scale_val = 1 / np.asarray([255], dtype=np.float32)
mean_val = -1 * np.expand_dims(np.asarray([0.485, 0.456, 0.406], dtype=np.float32), axis=(0, 2, 3))
stddev_val = 1 / np.expand_dims(np.asarray([0.229, 0.224, 0.225], dtype=np.float32), axis=(0, 2, 3))
# y = (x * scale + mean) * stddev --> y = x * scale * stddev + mean * stddev
scale_out = self.graph.elt_const("Mul", "preprocessor/scale", input_tensor, scale_val * stddev_val)
mean_out = self.graph.elt_const("Add", "preprocessor/mean", scale_out, mean_val * stddev_val)
preprocessed_tensor = mean_out[0]
if preprocessor == "scale_range":
# RGB Normalizers. The per-channel values are given with shape [1, 3, 1, 1] for proper NCHW shape broadcasting
scale_val = 2 / np.asarray([255], dtype=np.float32)
offset_val = np.expand_dims(np.asarray([-1, -1, -1], dtype=np.float32), axis=(0, 2, 3))
# y = (x * scale + mean) * stddev --> y = x * scale * stddev + mean * stddev
scale_out = self.graph.elt_const("Mul", "preprocessor/scale", input_tensor, scale_val)
range_out = self.graph.elt_const("Add", "preprocessor/range", scale_out, offset_val)
preprocessed_tensor = range_out[0]
# Find the first stem conv node of the graph, and connect the normalizer directly to it
stem_name = None
if self.api == "AutoML":
stem_name = "/stem/"
if self.api == "TFOD":
stem_name = "/stem_conv2d/"
stem = [node for node in self.graph.nodes if node.op == "Conv" and stem_name in node.name][0]
log.info("Found {} node '{}' as stem entry".format(stem.op, stem.name))
stem.inputs[0] = preprocessed_tensor
self.sanitize()
def update_shapes(self):
# Reshape nodes have the batch dimension as a fixed value of 1, they should use the batch size instead
# Output-Head reshapes use [1, -1, C], corrected reshape value should be [-1, V, C]
for node in [node for node in self.graph.nodes if node.op == "Reshape"]:
shape_in = node.inputs[0].shape
if shape_in is None or len(shape_in) not in [4,5]: # TFOD graphs have 5-dim inputs on this Reshape
continue
if type(node.inputs[1]) != gs.Constant:
continue
shape_out = node.inputs[1].values
if len(shape_out) != 3 or shape_out[0] != 1 or shape_out[1] != -1:
continue
volume = shape_in[1] * shape_in[2] * shape_in[3] / shape_out[2]
if len(shape_in) == 5:
volume *= shape_in[4]
shape_corrected = np.asarray([-1, volume, shape_out[2]], dtype=np.int64)
node.inputs[1] = gs.Constant("{}_shape".format(node.name), values=shape_corrected)
log.info("Updating Output-Head Reshape node {} to {}".format(node.name, node.inputs[1].values))
# Other Reshapes only need to change the first dim to -1, as long as there are no -1's already
for node in [node for node in self.graph.nodes if node.op == "Reshape"]:
if type(node.inputs[1]) != gs.Constant or node.inputs[1].values[0] != 1 or -1 in node.inputs[1].values:
continue
node.inputs[1].values[0] = -1
log.info("Updating Reshape node {} to {}".format(node.name, node.inputs[1].values))
# Resize nodes try to calculate the output shape dynamically, it's more optimal to pre-compute the shape
if self.api == "AutoML":
# Resize on a BiFPN will always be 2x, but grab it from the graph just in case
for node in [node for node in self.graph.nodes if node.op == "Resize"]:
if len(node.inputs) < 4 or node.inputs[0].shape is None:
continue
scale_h, scale_w = None, None
if type(node.inputs[3]) == gs.Constant:
# The sizes input is already folded
if len(node.inputs[3].values) != 4:
continue
scale_h = node.inputs[3].values[2] / node.inputs[0].shape[2]
scale_w = node.inputs[3].values[3] / node.inputs[0].shape[3]
if type(node.inputs[3]) == gs.Variable:
# The sizes input comes from Shape+Slice+Concat
concat = node.i(3)
if concat.op != "Concat":
continue
if type(concat.inputs[1]) != gs.Constant or len(concat.inputs[1].values) != 2:
continue
scale_h = concat.inputs[1].values[0] / node.inputs[0].shape[2]
scale_w = concat.inputs[1].values[1] / node.inputs[0].shape[3]
scales = np.asarray([1, 1, scale_h, scale_w], dtype=np.float32)
del node.inputs[3]
node.inputs[2] = gs.Constant(name="{}_scales".format(node.name), values=scales)
log.info("Updating Resize node {} to {}".format(node.name, scales))
self.sanitize()
def update_network(self):
"""
Updates the graph to replace certain nodes in the main EfficientDet network:
- the global average pooling nodes are optimized when running for TFOD models.
"""
if self.api == "TFOD":
for reduce in [node for node in self.graph.nodes if node.op == "ReduceMean"]:
# TFOD models have their ReduceMean nodes applied with some redundant transposes that can be
# optimized away for better performance
# Make sure the correct subgraph is being replaced, basically search for this:
# X > Transpose (0,2,3,1) > ReduceMean (1,2) > Reshape (?,1,1,?) > Reshape (?,?,1,1) > Conv > Y
# And change to this:
# X > ReduceMean (2,3) > Conv > Y
transpose = reduce.i()
if transpose.op != "Transpose" or transpose.attrs['perm'] != [0, 2, 3, 1]:
continue
if len(reduce.attrs['axes']) != 2 or reduce.attrs['axes'] != [1, 2]:
continue
reshape1 = reduce.o()
if reshape1.op != "Reshape" or len(reshape1.inputs[1].values) != 4:
continue
if reshape1.inputs[1].values[1] != 1 or reshape1.inputs[1].values[2] != 1:
continue
reshape2 = reshape1.o()
if reshape2.op != "Reshape" or len(reshape2.inputs[1].values) != 4:
continue
if reshape2.inputs[1].values[2] != 1 or reshape2.inputs[1].values[3] != 1:
continue
conv = reshape2.o()
if conv.op != "Conv":
continue
# If all the checks above pass, then this node sequence can be optimized by just the ReduceMean itself
# operating on a different set of axes
input_tensor = transpose.inputs[0] # Input tensor to the Transpose
reduce.inputs[0] = input_tensor # Forward the Transpose input to the ReduceMean node
output_tensor = reduce.outputs[0] # Output tensor of the ReduceMean
conv.inputs[0] = output_tensor # Forward the ReduceMean output to the Conv node
reduce.attrs['axes'] = [2, 3] # Update the axes that ReduceMean operates on
reduce.attrs['keepdims'] = 1 # Keep the reduced dimensions
log.info("Optimized subgraph around ReduceMean node '{}'".format(reduce.name))
def update_nms(self, threshold=None, detections=None):
"""
Updates the graph to replace the NMS op by BatchedNMS_TRT TensorRT plugin node.
:param threshold: Override the score threshold attribute. If set to None, use the value in the graph.
:param detections: Override the max detections attribute. If set to None, use the value in the graph.
"""
def find_head_concat(name_scope):
# This will find the concatenation node at the end of either Class Net or Box Net. These concatenation nodes
# bring together prediction data for each of 5 scales.
# The concatenated Class Net node will have shape [batch_size, num_anchors, num_classes],
# and the concatenated Box Net node has the shape [batch_size, num_anchors, 4].
# These concatenation nodes can be be found by searching for all Concat's and checking if the node two
# steps above in the graph has a name that begins with either "box_net/..." or "class_net/...".
for node in [node for node in self.graph.nodes if node.op == "Transpose" and name_scope in node.name]:
concat = self.graph.find_descendant_by_op(node, "Concat")
assert concat and len(concat.inputs) == 5
log.info("Found {} node '{}' as the tip of {}".format(concat.op, concat.name, name_scope))
return concat
def extract_anchors_tensor(split):
# This will find the anchors that have been hardcoded somewhere within the ONNX graph.
# The function will return a gs.Constant that can be directly used as an input to the NMS plugin.
# The anchor tensor shape will be [1, num_anchors, 4]. Note that '1' is kept as first dim, regardless of
# batch size, as it's not necessary to replicate the anchors for all images in the batch.
# The anchors are available (one per coordinate) hardcoded as constants within certain box decoder nodes.
# Each of these four constants have shape [1, num_anchors], so some numpy operations are used to expand the
# dims and concatenate them as needed.
# These constants can be found by starting from the Box Net's split operation , and for each coordinate,
# walking down in the graph until either an Add or Mul node is found. The second input on this nodes will
# be the anchor data required.
def get_anchor_np(output_idx, op):
node = self.graph.find_descendant_by_op(split.o(0, output_idx), op)
assert node
val = np.squeeze(node.inputs[1].values)
return np.expand_dims(val.flatten(), axis=(0, 2))
anchors_y = get_anchor_np(0, "Add")
anchors_x = get_anchor_np(1, "Add")
anchors_h = get_anchor_np(2, "Mul")
anchors_w = get_anchor_np(3, "Mul")
anchors = np.concatenate([anchors_y, anchors_x, anchors_h, anchors_w], axis=2)
return gs.Constant(name="nms/anchors:0", values=anchors)
self.sanitize()
head_names = []
if self.api == "AutoML":
head_names = ["class_net/", "box_net/"]
if self.api == "TFOD":
head_names = ["/WeightSharedConvolutionalClassHead/", "/WeightSharedConvolutionalBoxHead/"]
# There are five nodes at the bottom of the graph that provide important connection points:
# 1. Find the concat node at the end of the class net (multi-scale class predictor)
class_net = find_head_concat(head_names[0])
class_net_tensor = class_net.outputs[0]
# 2. Find the concat node at the end of the box net (multi-scale localization predictor)
box_net = find_head_concat(head_names[1])
box_net_tensor = box_net.outputs[0]
# 3. Find the split node that separates the box net coordinates and feeds them into the box decoder.
box_net_split = self.graph.find_descendant_by_op(box_net, "Split")
assert box_net_split and len(box_net_split.outputs) == 4
# 4. Find the concat node at the end of the box decoder.
box_decoder = self.graph.find_descendant_by_op(box_net_split, "Concat")
assert box_decoder and len(box_decoder.inputs) == 4
box_decoder_tensor = box_decoder.outputs[0]
# 5. Find the NMS node.
nms_node = self.graph.find_node_by_op("NonMaxSuppression")
# Extract NMS Configuration
num_detections = int(nms_node.inputs[2].values) if detections is None else detections
iou_threshold = float(nms_node.inputs[3].values)
score_threshold = float(nms_node.inputs[4].values) if threshold is None else threshold
num_classes = class_net.i().inputs[1].values[-1]
normalized = True if self.api == "TFOD" else False
# NMS Inputs and Attributes
# NMS expects these shapes for its input tensors:
# box_net: [batch_size, number_boxes, 4]
# class_net: [batch_size, number_boxes, number_classes]
# anchors: [1, number_boxes, 4] (if used)
nms_op = None
nms_attrs = None
nms_inputs = None
# EfficientNMS TensorRT Plugin
# Fusing the decoder will always be faster, so this is the default NMS method supported. In this case,
# three inputs are given to the NMS TensorRT node:
# - The box predictions (from the Box Net node found above)
# - The class predictions (from the Class Net node found above)
# - The default anchor coordinates (from the extracted anchor constants)
# As the original tensors from EfficientDet will be used, the NMS code type is set to 1 (Center+Size),
# because this is the internal box coding format used by the network.
anchors_tensor = extract_anchors_tensor(box_net_split)
nms_inputs = [box_net_tensor, class_net_tensor, anchors_tensor]
nms_op = "EfficientNMS_TRT"
nms_attrs = {
'plugin_version': "1",
'background_class': -1,
'max_output_boxes': num_detections,
'score_threshold': max(0.01, score_threshold), # Keep threshold to at least 0.01 for better efficiency
'iou_threshold': iou_threshold,
'score_activation': True,
'box_coding': 1,
}
nms_output_classes_dtype = np.int32
# NMS Outputs
nms_output_num_detections = gs.Variable(name="num_detections", dtype=np.int32, shape=['N', 1])
nms_output_boxes = gs.Variable(name="detection_boxes", dtype=np.float32,
shape=['N', num_detections, 4])
nms_output_scores = gs.Variable(name="detection_scores", dtype=np.float32,
shape=['N', num_detections])
nms_output_classes = gs.Variable(name="detection_classes", dtype=nms_output_classes_dtype,
shape=['N', num_detections])
nms_outputs = [nms_output_num_detections, nms_output_boxes, nms_output_scores, nms_output_classes]
# Create the NMS Plugin node with the selected inputs. The outputs of the node will also become the final
# outputs of the graph.
self.graph.plugin(
op=nms_op,
name="nms/non_maximum_suppression",
inputs=nms_inputs,
outputs=nms_outputs,
attrs=nms_attrs)
log.info("Created NMS plugin '{}' with attributes: {}".format(nms_op, nms_attrs))
self.graph.outputs = nms_outputs
self.sanitize()
def main(args):
effdet_gs = EfficientDetGraphSurgeon(args.saved_model)
if args.tf2onnx:
effdet_gs.save(args.tf2onnx)
effdet_gs.update_preprocessor(args.input_format, args.input_size, args.preprocessor)
effdet_gs.update_shapes()
effdet_gs.update_network()
effdet_gs.update_nms(args.nms_threshold, args.nms_detections)
effdet_gs.save(args.onnx)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-m", "--saved_model", required=True,
help="The TensorFlow saved model directory to load")
parser.add_argument("-o", "--onnx", required=True,
help="The output ONNX model file to write")
parser.add_argument("-f", "--input_format", default="NHWC", choices=["NHWC", "NCHW"],
help="Set the input data format of the graph, either NCHW or NHWC, default: NHWC")
parser.add_argument("-i", "--input_size", default="512,512",
help="Set the input shape of the graph, as a comma-separated dimensions in H,W format, "
"default: 512,512")
parser.add_argument("-p", "--preprocessor", default="imagenet", choices=["imagenet", "scale_range"],
help="Set the preprocessor to apply on the graph, either 'imagenet' for standard mean "
"subtraction and stdev normalization, or 'scale_range' for uniform [-1,+1] "
"normalization as is used in the AdvProp models, default: imagenet")
parser.add_argument("-t", "--nms_threshold", type=float,
help="Override the NMS score threshold, default: use the original value in the model")
parser.add_argument("-d", "--nms_detections", type=int,
help="Override the NMS max detections, default: use the original value in the model")
parser.add_argument("--tf2onnx",
help="The path where to save the intermediate ONNX graph generated by tf2onnx, useful"
"for graph debugging purposes, default: not saved")
args = parser.parse_args()
main(args)
| 53.986696 | 122 | 0.619065 |
import os
import sys
import argparse
import logging
import tensorflow as tf
import onnx_graphsurgeon as gs
import numpy as np
import onnx
from onnx import shape_inference
from tf2onnx import tfonnx, optimizer, tf_loader
import onnx_utils
logging.basicConfig(level=logging.INFO)
logging.getLogger("EfficientDetGraphSurgeon").setLevel(logging.INFO)
log = logging.getLogger("EfficientDetGraphSurgeon")
class EfficientDetGraphSurgeon:
def __init__(self, saved_model_path):
saved_model_path = os.path.realpath(saved_model_path)
assert os.path.exists(saved_model_path)
graph_def, inputs, outputs = tf_loader.from_saved_model(saved_model_path, None, None, "serve",
["serving_default"])
log.info("Loaded saved model from {}".format(saved_model_path))
with tf.Graph().as_default() as tf_graph:
tf.import_graph_def(graph_def, name="")
with tf_loader.tf_session(graph=tf_graph):
onnx_graph = tfonnx.process_tf_graph(tf_graph, input_names=inputs, output_names=outputs, opset=11)
onnx_model = optimizer.optimize_graph(onnx_graph).make_model("Converted from {}".format(saved_model_path))
self.graph = gs.import_onnx(onnx_model)
assert self.graph
log.info("TF2ONNX graph created successfully")
self.graph.fold_constants()
self.api = None
if len([node for node in self.graph.nodes if "class_net/" in node.name]) > 0:
self.api = "AutoML"
elif len([node for node in self.graph.nodes if "/WeightSharedConvolutionalClassHead/" in node.name]) > 0:
self.api = "TFOD"
assert self.api
log.info("Graph was detected as {}".format(self.api))
def sanitize(self):
for i in range(3):
count_before = len(self.graph.nodes)
self.graph.cleanup().toposort()
try:
for node in self.graph.nodes:
for o in node.outputs:
o.shape = None
model = gs.export_onnx(self.graph)
model = shape_inference.infer_shapes(model)
self.graph = gs.import_onnx(model)
except Exception as e:
log.info("Shape inference could not be performed at this time:\n{}".format(e))
try:
self.graph.fold_constants(fold_shapes=True)
except TypeError as e:
log.error("This version of ONNX GraphSurgeon does not support folding shapes, please upgrade your "
"onnx_graphsurgeon module. Error:\n{}".format(e))
raise
count_after = len(self.graph.nodes)
if count_before == count_after:
break
def save(self, output_path):
self.graph.cleanup().toposort()
model = gs.export_onnx(self.graph)
output_path = os.path.realpath(output_path)
os.makedirs(os.path.dirname(output_path), exist_ok=True)
onnx.save(model, output_path)
log.info("Saved ONNX model to {}".format(output_path))
def update_preprocessor(self, input_format, input_size, preprocessor="imagenet"):
input_size = input_size.split(",")
assert len(input_size) == 2
for i in range(len(input_size)):
input_size[i] = int(input_size[i])
assert input_size[i] >= 1
assert input_format in ["NCHW", "NHWC"]
if input_format == "NCHW":
self.graph.inputs[0].shape = ['N', 3, input_size[0], input_size[1]]
if input_format == "NHWC":
self.graph.inputs[0].shape = ['N', input_size[0], input_size[1], 3]
self.graph.inputs[0].dtype = np.float32
self.graph.inputs[0].name = "input"
log.info("ONNX graph input shape: {} [{} format]".format(self.graph.inputs[0].shape, input_format))
self.sanitize()
for node in [node for node in self.graph.nodes if self.graph.inputs[0] in node.inputs]:
node.inputs.clear()
input_tensor = self.graph.inputs[0]
if input_format == "NHWC":
input_tensor = self.graph.transpose("preprocessor/transpose", input_tensor, [0, 3, 1, 2])
assert preprocessor in ["imagenet", "scale_range"]
preprocessed_tensor = None
if preprocessor == "imagenet":
scale_val = 1 / np.asarray([255], dtype=np.float32)
mean_val = -1 * np.expand_dims(np.asarray([0.485, 0.456, 0.406], dtype=np.float32), axis=(0, 2, 3))
stddev_val = 1 / np.expand_dims(np.asarray([0.229, 0.224, 0.225], dtype=np.float32), axis=(0, 2, 3))
scale_out = self.graph.elt_const("Mul", "preprocessor/scale", input_tensor, scale_val * stddev_val)
mean_out = self.graph.elt_const("Add", "preprocessor/mean", scale_out, mean_val * stddev_val)
preprocessed_tensor = mean_out[0]
if preprocessor == "scale_range":
scale_val = 2 / np.asarray([255], dtype=np.float32)
offset_val = np.expand_dims(np.asarray([-1, -1, -1], dtype=np.float32), axis=(0, 2, 3))
scale_out = self.graph.elt_const("Mul", "preprocessor/scale", input_tensor, scale_val)
range_out = self.graph.elt_const("Add", "preprocessor/range", scale_out, offset_val)
preprocessed_tensor = range_out[0]
stem_name = None
if self.api == "AutoML":
stem_name = "/stem/"
if self.api == "TFOD":
stem_name = "/stem_conv2d/"
stem = [node for node in self.graph.nodes if node.op == "Conv" and stem_name in node.name][0]
log.info("Found {} node '{}' as stem entry".format(stem.op, stem.name))
stem.inputs[0] = preprocessed_tensor
self.sanitize()
def update_shapes(self):
for node in [node for node in self.graph.nodes if node.op == "Reshape"]:
shape_in = node.inputs[0].shape
if shape_in is None or len(shape_in) not in [4,5]:
continue
if type(node.inputs[1]) != gs.Constant:
continue
shape_out = node.inputs[1].values
if len(shape_out) != 3 or shape_out[0] != 1 or shape_out[1] != -1:
continue
volume = shape_in[1] * shape_in[2] * shape_in[3] / shape_out[2]
if len(shape_in) == 5:
volume *= shape_in[4]
shape_corrected = np.asarray([-1, volume, shape_out[2]], dtype=np.int64)
node.inputs[1] = gs.Constant("{}_shape".format(node.name), values=shape_corrected)
log.info("Updating Output-Head Reshape node {} to {}".format(node.name, node.inputs[1].values))
for node in [node for node in self.graph.nodes if node.op == "Reshape"]:
if type(node.inputs[1]) != gs.Constant or node.inputs[1].values[0] != 1 or -1 in node.inputs[1].values:
continue
node.inputs[1].values[0] = -1
log.info("Updating Reshape node {} to {}".format(node.name, node.inputs[1].values))
# Resize nodes try to calculate the output shape dynamically, it's more optimal to pre-compute the shape
if self.api == "AutoML":
for node in [node for node in self.graph.nodes if node.op == "Resize"]:
if len(node.inputs) < 4 or node.inputs[0].shape is None:
continue
scale_h, scale_w = None, None
if type(node.inputs[3]) == gs.Constant:
if len(node.inputs[3].values) != 4:
continue
scale_h = node.inputs[3].values[2] / node.inputs[0].shape[2]
scale_w = node.inputs[3].values[3] / node.inputs[0].shape[3]
if type(node.inputs[3]) == gs.Variable:
concat = node.i(3)
if concat.op != "Concat":
continue
if type(concat.inputs[1]) != gs.Constant or len(concat.inputs[1].values) != 2:
continue
scale_h = concat.inputs[1].values[0] / node.inputs[0].shape[2]
scale_w = concat.inputs[1].values[1] / node.inputs[0].shape[3]
scales = np.asarray([1, 1, scale_h, scale_w], dtype=np.float32)
del node.inputs[3]
node.inputs[2] = gs.Constant(name="{}_scales".format(node.name), values=scales)
log.info("Updating Resize node {} to {}".format(node.name, scales))
self.sanitize()
def update_network(self):
if self.api == "TFOD":
for reduce in [node for node in self.graph.nodes if node.op == "ReduceMean"]:
transpose = reduce.i()
if transpose.op != "Transpose" or transpose.attrs['perm'] != [0, 2, 3, 1]:
continue
if len(reduce.attrs['axes']) != 2 or reduce.attrs['axes'] != [1, 2]:
continue
reshape1 = reduce.o()
if reshape1.op != "Reshape" or len(reshape1.inputs[1].values) != 4:
continue
if reshape1.inputs[1].values[1] != 1 or reshape1.inputs[1].values[2] != 1:
continue
reshape2 = reshape1.o()
if reshape2.op != "Reshape" or len(reshape2.inputs[1].values) != 4:
continue
if reshape2.inputs[1].values[2] != 1 or reshape2.inputs[1].values[3] != 1:
continue
conv = reshape2.o()
if conv.op != "Conv":
continue
input_tensor = transpose.inputs[0]
reduce.inputs[0] = input_tensor
output_tensor = reduce.outputs[0]
conv.inputs[0] = output_tensor
reduce.attrs['axes'] = [2, 3]
reduce.attrs['keepdims'] = 1
log.info("Optimized subgraph around ReduceMean node '{}'".format(reduce.name))
def update_nms(self, threshold=None, detections=None):
def find_head_concat(name_scope):
# steps above in the graph has a name that begins with either "box_net/..." or "class_net/...".
for node in [node for node in self.graph.nodes if node.op == "Transpose" and name_scope in node.name]:
concat = self.graph.find_descendant_by_op(node, "Concat")
assert concat and len(concat.inputs) == 5
log.info("Found {} node '{}' as the tip of {}".format(concat.op, concat.name, name_scope))
return concat
def extract_anchors_tensor(split):
# This will find the anchors that have been hardcoded somewhere within the ONNX graph.
# The function will return a gs.Constant that can be directly used as an input to the NMS plugin.
# The anchor tensor shape will be [1, num_anchors, 4]. Note that '1' is kept as first dim, regardless of
# batch size, as it's not necessary to replicate the anchors for all images in the batch.
# walking down in the graph until either an Add or Mul node is found. The second input on this nodes will
# be the anchor data required.
def get_anchor_np(output_idx, op):
node = self.graph.find_descendant_by_op(split.o(0, output_idx), op)
assert node
val = np.squeeze(node.inputs[1].values)
return np.expand_dims(val.flatten(), axis=(0, 2))
anchors_y = get_anchor_np(0, "Add")
anchors_x = get_anchor_np(1, "Add")
anchors_h = get_anchor_np(2, "Mul")
anchors_w = get_anchor_np(3, "Mul")
anchors = np.concatenate([anchors_y, anchors_x, anchors_h, anchors_w], axis=2)
return gs.Constant(name="nms/anchors:0", values=anchors)
self.sanitize()
head_names = []
if self.api == "AutoML":
head_names = ["class_net/", "box_net/"]
if self.api == "TFOD":
head_names = ["/WeightSharedConvolutionalClassHead/", "/WeightSharedConvolutionalBoxHead/"]
# There are five nodes at the bottom of the graph that provide important connection points:
# 1. Find the concat node at the end of the class net (multi-scale class predictor)
class_net = find_head_concat(head_names[0])
class_net_tensor = class_net.outputs[0]
# 2. Find the concat node at the end of the box net (multi-scale localization predictor)
box_net = find_head_concat(head_names[1])
box_net_tensor = box_net.outputs[0]
# 3. Find the split node that separates the box net coordinates and feeds them into the box decoder.
box_net_split = self.graph.find_descendant_by_op(box_net, "Split")
assert box_net_split and len(box_net_split.outputs) == 4
# 4. Find the concat node at the end of the box decoder.
box_decoder = self.graph.find_descendant_by_op(box_net_split, "Concat")
assert box_decoder and len(box_decoder.inputs) == 4
box_decoder_tensor = box_decoder.outputs[0]
# 5. Find the NMS node.
nms_node = self.graph.find_node_by_op("NonMaxSuppression")
# Extract NMS Configuration
num_detections = int(nms_node.inputs[2].values) if detections is None else detections
iou_threshold = float(nms_node.inputs[3].values)
score_threshold = float(nms_node.inputs[4].values) if threshold is None else threshold
num_classes = class_net.i().inputs[1].values[-1]
normalized = True if self.api == "TFOD" else False
# NMS Inputs and Attributes
# NMS expects these shapes for its input tensors:
# box_net: [batch_size, number_boxes, 4]
# class_net: [batch_size, number_boxes, number_classes]
# anchors: [1, number_boxes, 4] (if used)
nms_op = None
nms_attrs = None
nms_inputs = None
# EfficientNMS TensorRT Plugin
# Fusing the decoder will always be faster, so this is the default NMS method supported. In this case,
# three inputs are given to the NMS TensorRT node:
# - The box predictions (from the Box Net node found above)
# - The class predictions (from the Class Net node found above)
# - The default anchor coordinates (from the extracted anchor constants)
# As the original tensors from EfficientDet will be used, the NMS code type is set to 1 (Center+Size),
# because this is the internal box coding format used by the network.
anchors_tensor = extract_anchors_tensor(box_net_split)
nms_inputs = [box_net_tensor, class_net_tensor, anchors_tensor]
nms_op = "EfficientNMS_TRT"
nms_attrs = {
'plugin_version': "1",
'background_class': -1,
'max_output_boxes': num_detections,
'score_threshold': max(0.01, score_threshold), # Keep threshold to at least 0.01 for better efficiency
'iou_threshold': iou_threshold,
'score_activation': True,
'box_coding': 1,
}
nms_output_classes_dtype = np.int32
# NMS Outputs
nms_output_num_detections = gs.Variable(name="num_detections", dtype=np.int32, shape=['N', 1])
nms_output_boxes = gs.Variable(name="detection_boxes", dtype=np.float32,
shape=['N', num_detections, 4])
nms_output_scores = gs.Variable(name="detection_scores", dtype=np.float32,
shape=['N', num_detections])
nms_output_classes = gs.Variable(name="detection_classes", dtype=nms_output_classes_dtype,
shape=['N', num_detections])
nms_outputs = [nms_output_num_detections, nms_output_boxes, nms_output_scores, nms_output_classes]
# Create the NMS Plugin node with the selected inputs. The outputs of the node will also become the final
# outputs of the graph.
self.graph.plugin(
op=nms_op,
name="nms/non_maximum_suppression",
inputs=nms_inputs,
outputs=nms_outputs,
attrs=nms_attrs)
log.info("Created NMS plugin '{}' with attributes: {}".format(nms_op, nms_attrs))
self.graph.outputs = nms_outputs
self.sanitize()
def main(args):
effdet_gs = EfficientDetGraphSurgeon(args.saved_model)
if args.tf2onnx:
effdet_gs.save(args.tf2onnx)
effdet_gs.update_preprocessor(args.input_format, args.input_size, args.preprocessor)
effdet_gs.update_shapes()
effdet_gs.update_network()
effdet_gs.update_nms(args.nms_threshold, args.nms_detections)
effdet_gs.save(args.onnx)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-m", "--saved_model", required=True,
help="The TensorFlow saved model directory to load")
parser.add_argument("-o", "--onnx", required=True,
help="The output ONNX model file to write")
parser.add_argument("-f", "--input_format", default="NHWC", choices=["NHWC", "NCHW"],
help="Set the input data format of the graph, either NCHW or NHWC, default: NHWC")
parser.add_argument("-i", "--input_size", default="512,512",
help="Set the input shape of the graph, as a comma-separated dimensions in H,W format, "
"default: 512,512")
parser.add_argument("-p", "--preprocessor", default="imagenet", choices=["imagenet", "scale_range"],
help="Set the preprocessor to apply on the graph, either 'imagenet' for standard mean "
"subtraction and stdev normalization, or 'scale_range' for uniform [-1,+1] "
"normalization as is used in the AdvProp models, default: imagenet")
parser.add_argument("-t", "--nms_threshold", type=float,
help="Override the NMS score threshold, default: use the original value in the model")
parser.add_argument("-d", "--nms_detections", type=int,
help="Override the NMS max detections, default: use the original value in the model")
parser.add_argument("--tf2onnx",
help="The path where to save the intermediate ONNX graph generated by tf2onnx, useful"
"for graph debugging purposes, default: not saved")
args = parser.parse_args()
main(args)
| true | true |
f7f93b1f00383659b470b49241c9a0c547bacbf6 | 1,605 | py | Python | test/vanilla/low-level/AcceptanceTests/utils.py | cfculhane/autorest.python | 8cbca95faee88d933a58bbbd17b76834faa8d387 | [
"MIT"
] | 35 | 2018-04-03T12:15:53.000Z | 2022-03-11T14:03:34.000Z | test/vanilla/low-level/AcceptanceTests/utils.py | cfculhane/autorest.python | 8cbca95faee88d933a58bbbd17b76834faa8d387 | [
"MIT"
] | 652 | 2017-08-28T22:44:41.000Z | 2022-03-31T21:20:31.000Z | test/vanilla/low-level/AcceptanceTests/utils.py | cfculhane/autorest.python | 8cbca95faee88d933a58bbbd17b76834faa8d387 | [
"MIT"
] | 29 | 2017-08-28T20:57:01.000Z | 2022-03-11T14:03:38.000Z | # coding=utf-8
# --------------------------------------------------------------------------
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# The MIT License (MIT)
#
# 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 json
try:
JSON_DECODE_ERROR = json.decoder.JSONDecodeError
except:
JSON_DECODE_ERROR = ValueError
def dicts_equal(dict_one, dict_two):
assert set(dict_one.keys()) == set(dict_two.keys())
for key in dict_one.keys():
assert dict_one[key] == dict_two[key]
| 41.153846 | 78 | 0.686604 |
import json
try:
JSON_DECODE_ERROR = json.decoder.JSONDecodeError
except:
JSON_DECODE_ERROR = ValueError
def dicts_equal(dict_one, dict_two):
assert set(dict_one.keys()) == set(dict_two.keys())
for key in dict_one.keys():
assert dict_one[key] == dict_two[key]
| true | true |
f7f93b2b0e2d59856c9592423223414faa95744e | 356 | py | Python | mushroom_rl/environments/mujoco_envs/humanoid_gait/reward_goals/__init__.py | PuzeLiu/mushroom-rl | 99942b425e66b4ddcc26009d7105dde23841e95d | [
"MIT"
] | 344 | 2020-01-10T09:45:02.000Z | 2022-03-30T09:48:28.000Z | mushroom_rl/environments/mujoco_envs/humanoid_gait/reward_goals/__init__.py | AmmarFahmy/mushroom-rl | 2625ee7f64d5613b3b9fba00f0b7a39fece88ca5 | [
"MIT"
] | 44 | 2020-01-23T03:00:56.000Z | 2022-03-25T17:14:22.000Z | mushroom_rl/environments/mujoco_envs/humanoid_gait/reward_goals/__init__.py | AmmarFahmy/mushroom-rl | 2625ee7f64d5613b3b9fba00f0b7a39fece88ca5 | [
"MIT"
] | 93 | 2020-01-10T21:17:58.000Z | 2022-03-31T17:58:52.000Z | from .reward import NoGoalReward, MaxVelocityReward, \
VelocityProfileReward, CompleteTrajectoryReward
from .trajectory import HumanoidTrajectory
from .velocity_profile import VelocityProfile, PeriodicVelocityProfile,\
SinVelocityProfile, ConstantVelocityProfile, RandomConstantVelocityProfile,\
SquareWaveVelocityProfile, VelocityProfile3D
| 39.555556 | 80 | 0.853933 | from .reward import NoGoalReward, MaxVelocityReward, \
VelocityProfileReward, CompleteTrajectoryReward
from .trajectory import HumanoidTrajectory
from .velocity_profile import VelocityProfile, PeriodicVelocityProfile,\
SinVelocityProfile, ConstantVelocityProfile, RandomConstantVelocityProfile,\
SquareWaveVelocityProfile, VelocityProfile3D
| true | true |
f7f93b72d7a3d33d74baf1209fc7fd13fb46c029 | 2,409 | py | Python | tabcmd/commands/extracts/create_extracts_command.py | tableau/tabcmd | a6a44795b2568933505dfc8c443ee16542c9e4c0 | [
"MIT"
] | 3 | 2022-02-15T03:07:51.000Z | 2022-03-09T13:14:52.000Z | tabcmd/commands/extracts/create_extracts_command.py | tableau/tabcmd | a6a44795b2568933505dfc8c443ee16542c9e4c0 | [
"MIT"
] | 57 | 2022-01-31T22:33:17.000Z | 2022-03-28T22:05:53.000Z | tabcmd/commands/extracts/create_extracts_command.py | tableau/tabcmd | a6a44795b2568933505dfc8c443ee16542c9e4c0 | [
"MIT"
] | 2 | 2022-02-23T23:05:35.000Z | 2022-03-03T21:32:53.000Z | import tableauserverclient as TSC
from tabcmd.commands.auth.session import Session
from tabcmd.commands.constants import Errors
from tabcmd.commands.server import Server
from tabcmd.execution.global_options import *
from tabcmd.execution.localize import _
from tabcmd.execution.logger_config import log
class CreateExtracts(Server):
"""
Command that creates extracts for a published workbook or data source.
"""
name: str = "createextracts"
description: str = _("createextracts.short_description")
@staticmethod
def define_args(create_extract_parser):
set_ds_xor_wb_args(create_extract_parser)
set_embedded_datasources_options(create_extract_parser)
set_encryption_option(create_extract_parser)
set_project_arg(create_extract_parser)
set_parent_project_arg(create_extract_parser)
set_site_url_arg(create_extract_parser)
@staticmethod
def run_command(args):
logger = log(__class__.__name__, args.logging_level)
logger.debug(_("tabcmd.launching"))
session = Session()
server = session.create_session(args)
creation_call = None
try:
logger.debug(
"Extract params: encrypt={}, include_all={}, datasources={}".format(
args.encrypt, args.include_all, args.embedded_datasources
)
)
if args.datasource:
data_source_item = Server.get_data_source_item(logger, server, args.datasource)
logger.info(_("createextracts.for.datasource").format(args.datasource))
job = server.datasources.create_extract(data_source_item, encrypt=args.encrypt)
elif args.workbook:
workbook_item = Server.get_workbook_item(logger, server, args.workbook)
logger.info(_("createextracts.for.workbook_name").format(args.workbook))
job = server.workbooks.create_extract(
workbook_item,
encrypt=args.encrypt,
includeAll=args.include_all,
datasources=args.embedded_datasources,
)
except TSC.ServerResponseError as e:
Errors.exit_with_error(logger, exception=e)
logger.info(_("common.output.job_queued_success"))
logger.debug("Extract creation queued with JobID: {}".format(job.id))
| 39.491803 | 95 | 0.669157 | import tableauserverclient as TSC
from tabcmd.commands.auth.session import Session
from tabcmd.commands.constants import Errors
from tabcmd.commands.server import Server
from tabcmd.execution.global_options import *
from tabcmd.execution.localize import _
from tabcmd.execution.logger_config import log
class CreateExtracts(Server):
name: str = "createextracts"
description: str = _("createextracts.short_description")
@staticmethod
def define_args(create_extract_parser):
set_ds_xor_wb_args(create_extract_parser)
set_embedded_datasources_options(create_extract_parser)
set_encryption_option(create_extract_parser)
set_project_arg(create_extract_parser)
set_parent_project_arg(create_extract_parser)
set_site_url_arg(create_extract_parser)
@staticmethod
def run_command(args):
logger = log(__class__.__name__, args.logging_level)
logger.debug(_("tabcmd.launching"))
session = Session()
server = session.create_session(args)
creation_call = None
try:
logger.debug(
"Extract params: encrypt={}, include_all={}, datasources={}".format(
args.encrypt, args.include_all, args.embedded_datasources
)
)
if args.datasource:
data_source_item = Server.get_data_source_item(logger, server, args.datasource)
logger.info(_("createextracts.for.datasource").format(args.datasource))
job = server.datasources.create_extract(data_source_item, encrypt=args.encrypt)
elif args.workbook:
workbook_item = Server.get_workbook_item(logger, server, args.workbook)
logger.info(_("createextracts.for.workbook_name").format(args.workbook))
job = server.workbooks.create_extract(
workbook_item,
encrypt=args.encrypt,
includeAll=args.include_all,
datasources=args.embedded_datasources,
)
except TSC.ServerResponseError as e:
Errors.exit_with_error(logger, exception=e)
logger.info(_("common.output.job_queued_success"))
logger.debug("Extract creation queued with JobID: {}".format(job.id))
| true | true |
f7f93bad412e1d38fd7994b3fe862a4715f992ee | 833 | py | Python | record_audio.py | noorkhokhar99/24_hours_recoding | d6718966af8bf4584d15bb290ed07cc5f132ecbe | [
"MIT"
] | 1 | 2021-05-05T12:39:17.000Z | 2021-05-05T12:39:17.000Z | record_audio.py | noorkhokhar99/24_hours_recoding | d6718966af8bf4584d15bb290ed07cc5f132ecbe | [
"MIT"
] | null | null | null | record_audio.py | noorkhokhar99/24_hours_recoding | d6718966af8bf4584d15bb290ed07cc5f132ecbe | [
"MIT"
] | null | null | null | import pyaudio
import wave
filename = "record.wav"
chunk = 1024
FORMAT = pyaudio.paInt16
channels = 1
sample_rate = 44100
record_seconds = 86400
# print(record_seconds)
p = pyaudio.PyAudio()
# print(p)
stream = p.open(format=FORMAT,
channels=channels,
rate=sample_rate,
input=True,
output=True,
frames_per_buffer=chunk)
frames = []
print("Recording .. ")
for i in range(int(44100/chunk*record_seconds)):
data = stream.read(chunk)
frames.append(data)
print("Finish")
stream.start_stream()
stream.close()
p.terminate()
wf = wave.open(filename,"wb")
wf.setnchannels(channels)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(sample_rate)
wf.writeframes(b"".join(frames))
wf.close() | 19.372093 | 49 | 0.630252 | import pyaudio
import wave
filename = "record.wav"
chunk = 1024
FORMAT = pyaudio.paInt16
channels = 1
sample_rate = 44100
record_seconds = 86400
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=channels,
rate=sample_rate,
input=True,
output=True,
frames_per_buffer=chunk)
frames = []
print("Recording .. ")
for i in range(int(44100/chunk*record_seconds)):
data = stream.read(chunk)
frames.append(data)
print("Finish")
stream.start_stream()
stream.close()
p.terminate()
wf = wave.open(filename,"wb")
wf.setnchannels(channels)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(sample_rate)
wf.writeframes(b"".join(frames))
wf.close() | true | true |
f7f93bc06a539571f1cd61f2a7aba9ee08ba5996 | 11,835 | py | Python | hsjang/saitest/testListFeature.py | harrisonjang/testapp | f363dab1a480c788ca925ed42e7830e626e8c0de | [
"Apache-2.0"
] | null | null | null | hsjang/saitest/testListFeature.py | harrisonjang/testapp | f363dab1a480c788ca925ed42e7830e626e8c0de | [
"Apache-2.0"
] | null | null | null | hsjang/saitest/testListFeature.py | harrisonjang/testapp | f363dab1a480c788ca925ed42e7830e626e8c0de | [
"Apache-2.0"
] | null | null | null | #Contains List of tests
test_featureRegressionUT = [
'saiQosEgressFlowPolicer',
'saiQosEgressFlowPolicer',
]
crm_featureRegressionUT = [
'saiCrmFdbStaticTest', #FIXME: ac5p
'saiCrmFdbDynamicTest_1',
'saiCrmFdbDynamicTest_2',
'saiCrmFdbDynamicTest_3',
'saiCrmAclTableTest',
'saiCrmAclCounter',
'saiCrmAclGroup',
'saiCrmAclTableEntry',
'saiCrmIpv4RouteTest',
'saiCrmIpv6RouteTest',
'saiCrmIpv4NHTest',
'saiCrmIpv4NHTest_1',
'saiCrmIpv6NHTest',
'saiCrmIpv6NHTest_1',
'saiCrmIpv4NeighborTest', #FIXME: ac5p
'saiCrmIpv6NeighborTest', #FIXME: ac5p
'saiCrmNHGroupTest',
'saiCrmNHGroupMemberTest',
'saiCrmFdbDynamicAgeOutTest',
]
fdb_featureRegressionUT = [
'saiFdbDynamicForward_I',
'saiFdbDynamicForward_II',
'saiFdbDynamicForward_III',
'saiFdbDynamicForwardNeg_IV',
'saiFdbStaticForward',
'saiFdbStaticForwardNeg',
'saiFdbSAInvalidBehavior',
'saiFdbSAiszeroBehavior',
'saiFdbDAisSABehavior',
'saiFdbAgingDynamic_I',
'saiFdbAgingDynamic_II',
'saiFdbAgingDynamic_III',
'saiFdbAgingStatic_I',
'saiFdbAgingStatic_II',
'saiFdbAgingStatic_III',
'saiFdbAgingStatic_IV',
'saiFdbAgingIpv4_I',
'saiFdbAgingIpv4_II',
'saiFdbAgingIpv4_III',
'saiFdbAgingIpv4_IV',
'saiFdbAgingIpv6_I',
'saiFdbAgingIpv6_II',
'saiFdbAgingIpv6_III',
'saiFdbAgingIpv6_IV',
#'saiFdbFloodAfterDelete', #todo
]
mtu_featureRegressionUT = [
'saiMtuConfigTest',
'saiMtuConfigTest_I',
'saiMtuConfigTest_II',
'saiMtuConfigProfileTest',
'saiMtuConfigProfileTest_I',
'saiMtuIpProfileTest',
'saiMtuIpProfileTest_I',
'saiMtuIpProfileTest_II',
'saiMtuIpProfileTest_III',
'saiMtuIpProfileTest_IV',
]
l3_featureRegressionUT = [
'saiL3VerifyRouteNhForwarding',
'saiL3VerifyRouteNeigbourDrop',
'saiL3VerifyRouteNhLagForwarding',
'saiL3VerifyRouteNhLagForwardingIngressLag',
'saiL3VerifyRouteNhVlanIntfForwarding',
'saiL3VerifyRouteNhVlanIntfForwardingIngressVlanIntf',
'saiL3VerifyV4RouteDrop', #FIXME: ac5p
'saiL3VerifyV4RouteTrap', #FIXME: ac5p
'saiL3VerifyV6RouteDrop',
'saiL3VerifyV6RouteNhForwarding',
'saiL3VerifyV6RouteTrap',
'saiL3NhVerifyNhCreation', #FIXME: ac5p
'saiL3NhVerifyV4NeighbourCreation', #FIXME: ac5p
'saiL3NhVerifyV4NhGroupCreation', #FIXME: ac5p
'saiL3NhVerifyV6NeighbourCreation', #FIXME: ac5p
'saiL3NhVerifyV6NhCreation', #FIXME: ac5p
'saiL3NhVerifyV6NhGroupCreation', #FIXME: ac5p
'saiL3VerifyV4NhGroupForwarding',
'saiL3VerifyV4NhGroupForwarding_pktaction',
'saiL3VerifyV4NhMemberRemoveReAdd', #FIXME: ac5p
'saiL3VerifyV6NhGroupForwarding',
'saiL3NhVerifyNhDeletion',
#'saiL3VerifyRouteNeigbourTrap',
'saiL3SipEqualToDipBehavior',
]
everflow_featureRegressionUT = [
'saiEverflowIpv4ErspanTest',
#'saiEverflowIpv6ErspanTest', #TODO:Enable after IPV6 support
'saiEverflowIpv4ErspanMultipleACLRuleTest',
'saiEverflowIpv4ErspanMultipleMirrorSessionTest_1',
'saiEverflowIpv4ErspanMultipleMirrorSessionTest_2',
#'saiEverflowIpv6ErspanMultipleMirrorSessionTest_1', #TODO:Enable after IPV6 support
#'saiEverflowIpv6ErspanMultipleMirrorSessionTest_2', #TODO:Enable after IPV6 support
#'saiEverflowErspanMultipleMirrorSessionTest_1', #TODO:Enable after IPV6 support
#'saiEverflowErspanMultipleMirrorSessionTest_2', #TODO:Enable after IPV6 support
'saiEverflowIPUpdateTest',
'saiEverflowMACUpdateTest',
'saiEverflowMonitorPortUpdateTest',
'saiEverflowCrmCountAclEntryTest',
'saiEverflowGreProtoTypeUpdateTest',
'saiEverflowTOSUpdateTest',
'saiEverflowTTLUpdateTest',
'saiEverflowPolicer',
'saiEverflowPolicer_I',
]
acl_featureRegressionUT = [
'saiIngrAclL4SrcPort',
'saiIngrAclL4DstPort',
'saiIngrAclLagL4SrcDst',
'saiIngrAclLagParallelLookup',
'saiIngrAclParallelLookup',
'saiIngrAclLagSipv4Dipv4',
'saiIngrAclSipv6Dipv6',
'saiIngrAclTcpFlags',
'saiEgrAclL4SrcDst',
'saiEgrAclLagL4SrcDst',
'saiEgrAclLagParallelLookup',
'saiEgrAclLagSipv4Dipv4',
'saiEgrAclLagSipv6Dipv6',
'saiEgrAclParallelLookup',
'saiEgrAclSipv4Dipv4',
'saiEgrAclSipv6Dipv6',
]
qos_featureRegressionUT = [
'saiQosBufferPool',
'saiQosIngressBufferProfile', #FIXME:ac5p
'saiQosEgressBufferProfile', #FIXME:ac5p
'saiQosPortShaper',
'saiQosQueueScheduler',
'saiQosWredProfile',
'saiQosDot1pToTcMap',
'saiQosDot1pToColorMap',
'saiQosDscpToTcMap',
'saiQosDscpToColorMap',
'saiQosTcDpToDot1pMap',
'saiQosTcDpToDscpMap',
'saiQosTcToQueueMap',
'saiQosPfcToQueueMap',
'saiQosSymmetricPfc',
'saiQosAsymmetricPfc',
'saiQosIngressPortPolicer_I',
'saiQosIngressPortPolicer_II',
'saiQosIngressPortPolicerUcStorm',
'saiQosIngressPortPolicerBcStorm',
'saiQosIngressPortPolicerMcStorm',
'saiQosIngressFlowPolicer',
'saiQosEgressFlowPolicer',
]
mac_featureRegressionUT = [
'saiMacLinkStatus',
'saiMacPortLoopbackEnable',
'saiMacPortStatus',
'saiMacRxMaxFrameLen',
'saiMacRxMaxFrameLen_I',
'saiMacRxMaxFrameLen_II',
'saiMacRxMaxFrameLen_III',
'saiMacRxMaxFrameLen_IV',
'saiMacRxMaxFrameLen_V',
'saiMacSetFecModeFC',
'saiMacSetFecModeRS',
]
misc_featureRegressionUT = [
'saiPortAttrAdminState',
'saiFdbCreateGetPktAction',
'saiFdbSetGetPktAction',
'saiL2FloodingBasicUt',
'saiL3BasicUTRouting_I',
'saiL3BasicUTRouting_II',
'saiL3BasicUTRouting_III'
]
featureRegressionUT = [
'saiCrmFdbStaticTest',
'saiCrmFdbDynamicTest_1',
'saiCrmFdbDynamicTest_2',
'saiCrmFdbDynamicTest_3',
'saiCrmAclTableTest',
'saiCrmAclCounter',
'saiCrmAclGroup',
'saiCrmAclTableEntry',
'saiCrmIpv4RouteTest',
'saiCrmIpv6RouteTest',
'saiCrmIpv4NHTest',
'saiCrmIpv4NHTest_1',
'saiCrmIpv6NHTest',
'saiCrmIpv6NHTest_1',
'saiCrmIpv4NeighborTest',
'saiCrmIpv6NeighborTest',
'saiCrmNHGroupTest',
'saiCrmNHGroupMemberTest',
'saiCrmFdbDynamicAgeOutTest',
'saiFdbDynamicForward_I',
'saiFdbDynamicForward_II',
'saiFdbDynamicForward_III',
'saiFdbDynamicForwardNeg_IV',
'saiFdbStaticForward',
'saiFdbStaticForwardNeg',
'saiFdbSAInvalidBehavior',
'saiFdbSAiszeroBehavior',
'saiFdbDAisSABehavior',
'saiFdbAgingDynamic_I',
'saiFdbAgingDynamic_II',
'saiFdbAgingDynamic_III',
'saiFdbAgingStatic_I',
'saiFdbAgingStatic_II',
'saiFdbAgingStatic_III',
'saiFdbAgingStatic_IV',
'saiFdbAgingIpv4_I',
'saiFdbAgingIpv4_II',
'saiFdbAgingIpv4_III',
'saiFdbAgingIpv4_IV',
'saiFdbAgingIpv6_I',
'saiFdbAgingIpv6_II',
'saiFdbAgingIpv6_III',
'saiFdbAgingIpv6_IV',
#'saiFdbFloodAfterDelete', #todo
'saiMtuConfigTest',
'saiMtuConfigTest_I',
'saiMtuConfigTest_II',
'saiMtuConfigProfileTest',
'saiMtuConfigProfileTest_I',
'saiMtuIpProfileTest',
'saiMtuIpProfileTest_I',
'saiMtuIpProfileTest_II',
'saiMtuIpProfileTest_III',
'saiMtuIpProfileTest_IV',
'saiL3VerifyRouteNhForwarding',
'saiL3VerifyRouteNeigbourDrop',
'saiL3VerifyRouteNhLagForwarding',
'saiL3VerifyRouteNhLagForwardingIngressLag',
'saiL3VerifyRouteNhVlanIntfForwarding',
'saiL3VerifyRouteNhVlanIntfForwardingIngressVlanIntf',
'saiL3VerifyV4RouteDrop',
'saiL3VerifyV4RouteTrap',
'saiL3VerifyV6RouteDrop',
'saiL3VerifyV6RouteNhForwarding',
'saiL3VerifyV6RouteTrap',
'saiL3NhVerifyNhCreation',
'saiL3NhVerifyV4NeighbourCreation',
'saiL3NhVerifyV4NhGroupCreation',
'saiL3NhVerifyV6NeighbourCreation',
'saiL3NhVerifyV6NhCreation',
'saiL3NhVerifyV6NhGroupCreation',
'saiL3VerifyV4NhGroupForwarding',
'saiL3VerifyV4NhGroupForwarding_pktaction',
'saiL3VerifyV4NhMemberRemoveReAdd',
'saiL3VerifyV6NhGroupForwarding',
'saiL3NhVerifyNhDeletion',
#'saiL3VerifyRouteNeigbourTrap',
'saiL3SipEqualToDipBehavior',
'saiEverflowIpv4ErspanTest',
#'saiEverflowIpv6ErspanTest', #TODO:Enable after IPV6 support
'saiEverflowIpv4ErspanMultipleACLRuleTest',
'saiEverflowIpv4ErspanMultipleMirrorSessionTest_1',
'saiEverflowIpv4ErspanMultipleMirrorSessionTest_2',
#'saiEverflowIpv6ErspanMultipleMirrorSessionTest_1', #TODO:Enable after IPV6 support
#'saiEverflowIpv6ErspanMultipleMirrorSessionTest_2', #TODO:Enable after IPV6 support
#'saiEverflowErspanMultipleMirrorSessionTest_1', #TODO:Enable after IPV6 support
#'saiEverflowErspanMultipleMirrorSessionTest_2', #TODO:Enable after IPV6 support
'saiEverflowIPUpdateTest',
'saiEverflowMACUpdateTest',
'saiEverflowMonitorPortUpdateTest',
'saiEverflowCrmCountAclEntryTest',
'saiEverflowGreProtoTypeUpdateTest',
'saiEverflowTOSUpdateTest',
'saiEverflowTTLUpdateTest',
'saiEverflowPolicer',
'saiEverflowPolicer_I',
'saiIngrAclL4SrcPort',
'saiIngrAclL4DstPort',
'saiIngrAclLagL4SrcDst',
'saiIngrAclLagParallelLookup',
'saiIngrAclParallelLookup',
'saiIngrAclLagSipv4Dipv4',
'saiIngrAclSipv6Dipv6',
'saiIngrAclTcpFlags',
'saiEgrAclL4SrcDst',
'saiEgrAclLagL4SrcDst',
'saiEgrAclLagParallelLookup',
'saiEgrAclLagSipv4Dipv4',
'saiEgrAclLagSipv6Dipv6',
'saiEgrAclParallelLookup',
'saiEgrAclSipv4Dipv4',
'saiEgrAclSipv6Dipv6',
'saiQosBufferPool',
'saiQosIngressBufferProfile',
'saiQosEgressBufferProfile',
'saiQosPortShaper',
'saiQosQueueScheduler',
'saiQosWredProfile',
'saiQosDot1pToTcMap',
'saiQosDot1pToColorMap',
'saiQosDscpToTcMap',
'saiQosDscpToColorMap',
'saiQosTcDpToDot1pMap',
'saiQosTcDpToDscpMap',
'saiQosTcToQueueMap',
'saiQosPfcToQueueMap',
'saiQosSymmetricPfc',
'saiQosAsymmetricPfc',
'saiQosIngressPortPolicer_I',
'saiQosIngressPortPolicer_II',
'saiQosIngressPortPolicerUcStorm',
'saiQosIngressPortPolicerBcStorm',
'saiQosIngressPortPolicerMcStorm',
'saiQosIngressFlowPolicer',
'saiQosEgressFlowPolicer',
'saiMacLinkStatus',
'saiMacPortLoopbackEnable',
'saiMacPortStatus',
'saiMacRxMaxFrameLen',
'saiMacRxMaxFrameLen_I',
'saiMacRxMaxFrameLen_II',
'saiMacRxMaxFrameLen_III',
'saiMacRxMaxFrameLen_IV',
'saiMacRxMaxFrameLen_V',
'saiMacSetFecModeFC',
'saiMacSetFecModeRS',
'saiPortAttrAdminState',
]
m0_featureRegressionUT = [
'saiCrmFdbStaticTest',
'saiCrmFdbDynamicTest_1',
'saiCrmFdbDynamicTest_2',
'saiCrmFdbDynamicTest_3',
'saiCrmAclTableTest',
'saiCrmAclCounter',
'saiCrmAclGroup',
'saiCrmAclTableEntry',
'saiCrmIpv4RouteTest',
'saiCrmIpv6RouteTest',
'saiCrmIpv4NHTest',
'saiCrmIpv4NHTest_1',
'saiCrmIpv6NHTest',
'saiCrmIpv6NHTest_1',
'saiCrmIpv4NeighborTest',
'saiCrmIpv6NeighborTest',
'saiCrmNHGroupTest',
'saiCrmNHGroupMemberTest',
'saiCrmFdbDynamicAgeOutTest',
'saiFdbDynamicForward_I',
'saiFdbDynamicForward_II',
'saiFdbDynamicForward_III',
'saiFdbDynamicForwardNeg_IV',
'saiFdbStaticForward',
'saiFdbStaticForwardNeg',
'saiFdbSAInvalidBehavior',
'saiFdbSAiszeroBehavior',
'saiFdbDAisSABehavior',
'saiFdbAgingDynamic_I',
'saiFdbAgingDynamic_II',
'saiFdbAgingDynamic_III',
'saiFdbAgingStatic_I',
'saiFdbAgingStatic_II',
'saiFdbAgingStatic_III',
'saiFdbAgingStatic_IV',
'saiFdbAgingIpv4_I',
'saiFdbAgingIpv4_II',
'saiFdbAgingIpv4_III',
'saiFdbAgingIpv4_IV',
'saiFdbAgingIpv6_I',
'saiFdbAgingIpv6_II',
'saiFdbAgingIpv6_III',
'saiFdbAgingIpv6_IV',
#'saiFdbFloodAfterDelete', #todo
'saiMtuConfigTest',
'saiMtuConfigTest_I',
'saiMtuConfigTest_II',
'saiMtuConfigProfileTest',
'saiMtuConfigProfileTest_I',
'saiMtuIpProfileTest',
'saiMtuIpProfileTest_I',
'saiMtuIpProfileTest_II',
'saiMtuIpProfileTest_III',
'saiMtuIpProfileTest_IV',
'saiL3VerifyRouteNhForwarding',
'saiL3VerifyRouteNeigbourDrop',
'saiL3VerifyRouteNhLagForwarding',
'saiL3VerifyRouteNhLagForwardingIngressLag',
'saiL3VerifyRouteNhVlanIntfForwarding',
'saiL3VerifyRouteNhVlanIntfForwardingIngressVlanIntf',
'saiL3VerifyV4RouteDrop',
'saiL3VerifyV4RouteTrap',
'saiL3VerifyV6RouteDrop',
'saiL3VerifyV6RouteNhForwarding',
'saiL3VerifyV6RouteTrap',
'saiL3NhVerifyNhCreation',
'saiL3NhVerifyV4NeighbourCreation',
'saiL3NhVerifyV4NhGroupCreation',
'saiL3NhVerifyV6NeighbourCreation',
'saiL3NhVerifyV6NhCreation',
'saiL3NhVerifyV6NhGroupCreation',
'saiL3VerifyV4NhGroupForwarding',
'saiL3VerifyV4NhGroupForwarding_pktaction',
'saiL3VerifyV4NhMemberRemoveReAdd',
'saiL3VerifyV6NhGroupForwarding',
'saiL3NhVerifyNhDeletion',
#'saiL3VerifyRouteNeigbourTrap', #todo
'saiL3SipEqualToDipBehavior',
'saiEgrAclL4SrcDst',
'saiEgrAclLagL4SrcDst',
'saiEgrAclLagSipv6Dipv6',
'saiEgrAclLagSipv4Dipv4',
'saiEgrAclSipv6Dipv6',
'saiEgrAclSipv4Dipv4',
'saiIngrAclL4SrcPort',
'saiIngrAclL4DstPort',
'saiIngrAclLagL4SrcDst',
'saiIngrAclLagSipv4Dipv4',
'saiIngrAclSipv6Dipv6',
'saiIngrAclTcpFlags',
'saiMacRxMaxFrameLen',
'saiMacRxMaxFrameLen_I',
'saiMacRxMaxFrameLen_II',
'saiMacRxMaxFrameLen_III',
'saiMacRxMaxFrameLen_IV',
'saiMacRxMaxFrameLen_V',
]
| 27.144495 | 84 | 0.845289 |
test_featureRegressionUT = [
'saiQosEgressFlowPolicer',
'saiQosEgressFlowPolicer',
]
crm_featureRegressionUT = [
'saiCrmFdbStaticTest',
'saiCrmFdbDynamicTest_1',
'saiCrmFdbDynamicTest_2',
'saiCrmFdbDynamicTest_3',
'saiCrmAclTableTest',
'saiCrmAclCounter',
'saiCrmAclGroup',
'saiCrmAclTableEntry',
'saiCrmIpv4RouteTest',
'saiCrmIpv6RouteTest',
'saiCrmIpv4NHTest',
'saiCrmIpv4NHTest_1',
'saiCrmIpv6NHTest',
'saiCrmIpv6NHTest_1',
'saiCrmIpv4NeighborTest',
'saiCrmIpv6NeighborTest',
'saiCrmNHGroupTest',
'saiCrmNHGroupMemberTest',
'saiCrmFdbDynamicAgeOutTest',
]
fdb_featureRegressionUT = [
'saiFdbDynamicForward_I',
'saiFdbDynamicForward_II',
'saiFdbDynamicForward_III',
'saiFdbDynamicForwardNeg_IV',
'saiFdbStaticForward',
'saiFdbStaticForwardNeg',
'saiFdbSAInvalidBehavior',
'saiFdbSAiszeroBehavior',
'saiFdbDAisSABehavior',
'saiFdbAgingDynamic_I',
'saiFdbAgingDynamic_II',
'saiFdbAgingDynamic_III',
'saiFdbAgingStatic_I',
'saiFdbAgingStatic_II',
'saiFdbAgingStatic_III',
'saiFdbAgingStatic_IV',
'saiFdbAgingIpv4_I',
'saiFdbAgingIpv4_II',
'saiFdbAgingIpv4_III',
'saiFdbAgingIpv4_IV',
'saiFdbAgingIpv6_I',
'saiFdbAgingIpv6_II',
'saiFdbAgingIpv6_III',
'saiFdbAgingIpv6_IV',
tu_featureRegressionUT = [
'saiMtuConfigTest',
'saiMtuConfigTest_I',
'saiMtuConfigTest_II',
'saiMtuConfigProfileTest',
'saiMtuConfigProfileTest_I',
'saiMtuIpProfileTest',
'saiMtuIpProfileTest_I',
'saiMtuIpProfileTest_II',
'saiMtuIpProfileTest_III',
'saiMtuIpProfileTest_IV',
]
l3_featureRegressionUT = [
'saiL3VerifyRouteNhForwarding',
'saiL3VerifyRouteNeigbourDrop',
'saiL3VerifyRouteNhLagForwarding',
'saiL3VerifyRouteNhLagForwardingIngressLag',
'saiL3VerifyRouteNhVlanIntfForwarding',
'saiL3VerifyRouteNhVlanIntfForwardingIngressVlanIntf',
'saiL3VerifyV4RouteDrop',
'saiL3VerifyV4RouteTrap',
'saiL3VerifyV6RouteDrop',
'saiL3VerifyV6RouteNhForwarding',
'saiL3VerifyV6RouteTrap',
'saiL3NhVerifyNhCreation',
'saiL3NhVerifyV4NeighbourCreation',
'saiL3NhVerifyV4NhGroupCreation',
'saiL3NhVerifyV6NeighbourCreation',
'saiL3NhVerifyV6NhCreation',
'saiL3NhVerifyV6NhGroupCreation',
'saiL3VerifyV4NhGroupForwarding',
'saiL3VerifyV4NhGroupForwarding_pktaction',
'saiL3VerifyV4NhMemberRemoveReAdd',
'saiL3VerifyV6NhGroupForwarding',
'saiL3NhVerifyNhDeletion',
'saiL3SipEqualToDipBehavior',
]
everflow_featureRegressionUT = [
'saiEverflowIpv4ErspanTest',
ACLRuleTest',
'saiEverflowIpv4ErspanMultipleMirrorSessionTest_1',
'saiEverflowIpv4ErspanMultipleMirrorSessionTest_2',
est',
'saiEverflowGreProtoTypeUpdateTest',
'saiEverflowTOSUpdateTest',
'saiEverflowTTLUpdateTest',
'saiEverflowPolicer',
'saiEverflowPolicer_I',
]
acl_featureRegressionUT = [
'saiIngrAclL4SrcPort',
'saiIngrAclL4DstPort',
'saiIngrAclLagL4SrcDst',
'saiIngrAclLagParallelLookup',
'saiIngrAclParallelLookup',
'saiIngrAclLagSipv4Dipv4',
'saiIngrAclSipv6Dipv6',
'saiIngrAclTcpFlags',
'saiEgrAclL4SrcDst',
'saiEgrAclLagL4SrcDst',
'saiEgrAclLagParallelLookup',
'saiEgrAclLagSipv4Dipv4',
'saiEgrAclLagSipv6Dipv6',
'saiEgrAclParallelLookup',
'saiEgrAclSipv4Dipv4',
'saiEgrAclSipv6Dipv6',
]
qos_featureRegressionUT = [
'saiQosBufferPool',
'saiQosIngressBufferProfile',
'saiQosEgressBufferProfile',
'saiQosPortShaper',
'saiQosQueueScheduler',
'saiQosWredProfile',
'saiQosDot1pToTcMap',
'saiQosDot1pToColorMap',
'saiQosDscpToTcMap',
'saiQosDscpToColorMap',
'saiQosTcDpToDot1pMap',
'saiQosTcDpToDscpMap',
'saiQosTcToQueueMap',
'saiQosPfcToQueueMap',
'saiQosSymmetricPfc',
'saiQosAsymmetricPfc',
'saiQosIngressPortPolicer_I',
'saiQosIngressPortPolicer_II',
'saiQosIngressPortPolicerUcStorm',
'saiQosIngressPortPolicerBcStorm',
'saiQosIngressPortPolicerMcStorm',
'saiQosIngressFlowPolicer',
'saiQosEgressFlowPolicer',
]
mac_featureRegressionUT = [
'saiMacLinkStatus',
'saiMacPortLoopbackEnable',
'saiMacPortStatus',
'saiMacRxMaxFrameLen',
'saiMacRxMaxFrameLen_I',
'saiMacRxMaxFrameLen_II',
'saiMacRxMaxFrameLen_III',
'saiMacRxMaxFrameLen_IV',
'saiMacRxMaxFrameLen_V',
'saiMacSetFecModeFC',
'saiMacSetFecModeRS',
]
misc_featureRegressionUT = [
'saiPortAttrAdminState',
'saiFdbCreateGetPktAction',
'saiFdbSetGetPktAction',
'saiL2FloodingBasicUt',
'saiL3BasicUTRouting_I',
'saiL3BasicUTRouting_II',
'saiL3BasicUTRouting_III'
]
featureRegressionUT = [
'saiCrmFdbStaticTest',
'saiCrmFdbDynamicTest_1',
'saiCrmFdbDynamicTest_2',
'saiCrmFdbDynamicTest_3',
'saiCrmAclTableTest',
'saiCrmAclCounter',
'saiCrmAclGroup',
'saiCrmAclTableEntry',
'saiCrmIpv4RouteTest',
'saiCrmIpv6RouteTest',
'saiCrmIpv4NHTest',
'saiCrmIpv4NHTest_1',
'saiCrmIpv6NHTest',
'saiCrmIpv6NHTest_1',
'saiCrmIpv4NeighborTest',
'saiCrmIpv6NeighborTest',
'saiCrmNHGroupTest',
'saiCrmNHGroupMemberTest',
'saiCrmFdbDynamicAgeOutTest',
'saiFdbDynamicForward_I',
'saiFdbDynamicForward_II',
'saiFdbDynamicForward_III',
'saiFdbDynamicForwardNeg_IV',
'saiFdbStaticForward',
'saiFdbStaticForwardNeg',
'saiFdbSAInvalidBehavior',
'saiFdbSAiszeroBehavior',
'saiFdbDAisSABehavior',
'saiFdbAgingDynamic_I',
'saiFdbAgingDynamic_II',
'saiFdbAgingDynamic_III',
'saiFdbAgingStatic_I',
'saiFdbAgingStatic_II',
'saiFdbAgingStatic_III',
'saiFdbAgingStatic_IV',
'saiFdbAgingIpv4_I',
'saiFdbAgingIpv4_II',
'saiFdbAgingIpv4_III',
'saiFdbAgingIpv4_IV',
'saiFdbAgingIpv6_I',
'saiFdbAgingIpv6_II',
'saiFdbAgingIpv6_III',
'saiFdbAgingIpv6_IV',
MtuConfigTest',
'saiMtuConfigTest_I',
'saiMtuConfigTest_II',
'saiMtuConfigProfileTest',
'saiMtuConfigProfileTest_I',
'saiMtuIpProfileTest',
'saiMtuIpProfileTest_I',
'saiMtuIpProfileTest_II',
'saiMtuIpProfileTest_III',
'saiMtuIpProfileTest_IV',
'saiL3VerifyRouteNhForwarding',
'saiL3VerifyRouteNeigbourDrop',
'saiL3VerifyRouteNhLagForwarding',
'saiL3VerifyRouteNhLagForwardingIngressLag',
'saiL3VerifyRouteNhVlanIntfForwarding',
'saiL3VerifyRouteNhVlanIntfForwardingIngressVlanIntf',
'saiL3VerifyV4RouteDrop',
'saiL3VerifyV4RouteTrap',
'saiL3VerifyV6RouteDrop',
'saiL3VerifyV6RouteNhForwarding',
'saiL3VerifyV6RouteTrap',
'saiL3NhVerifyNhCreation',
'saiL3NhVerifyV4NeighbourCreation',
'saiL3NhVerifyV4NhGroupCreation',
'saiL3NhVerifyV6NeighbourCreation',
'saiL3NhVerifyV6NhCreation',
'saiL3NhVerifyV6NhGroupCreation',
'saiL3VerifyV4NhGroupForwarding',
'saiL3VerifyV4NhGroupForwarding_pktaction',
'saiL3VerifyV4NhMemberRemoveReAdd',
'saiL3VerifyV6NhGroupForwarding',
'saiL3NhVerifyNhDeletion',
'saiL3SipEqualToDipBehavior',
'saiEverflowIpv4ErspanTest',
ACLRuleTest',
'saiEverflowIpv4ErspanMultipleMirrorSessionTest_1',
'saiEverflowIpv4ErspanMultipleMirrorSessionTest_2',
est',
'saiEverflowGreProtoTypeUpdateTest',
'saiEverflowTOSUpdateTest',
'saiEverflowTTLUpdateTest',
'saiEverflowPolicer',
'saiEverflowPolicer_I',
'saiIngrAclL4SrcPort',
'saiIngrAclL4DstPort',
'saiIngrAclLagL4SrcDst',
'saiIngrAclLagParallelLookup',
'saiIngrAclParallelLookup',
'saiIngrAclLagSipv4Dipv4',
'saiIngrAclSipv6Dipv6',
'saiIngrAclTcpFlags',
'saiEgrAclL4SrcDst',
'saiEgrAclLagL4SrcDst',
'saiEgrAclLagParallelLookup',
'saiEgrAclLagSipv4Dipv4',
'saiEgrAclLagSipv6Dipv6',
'saiEgrAclParallelLookup',
'saiEgrAclSipv4Dipv4',
'saiEgrAclSipv6Dipv6',
'saiQosBufferPool',
'saiQosIngressBufferProfile',
'saiQosEgressBufferProfile',
'saiQosPortShaper',
'saiQosQueueScheduler',
'saiQosWredProfile',
'saiQosDot1pToTcMap',
'saiQosDot1pToColorMap',
'saiQosDscpToTcMap',
'saiQosDscpToColorMap',
'saiQosTcDpToDot1pMap',
'saiQosTcDpToDscpMap',
'saiQosTcToQueueMap',
'saiQosPfcToQueueMap',
'saiQosSymmetricPfc',
'saiQosAsymmetricPfc',
'saiQosIngressPortPolicer_I',
'saiQosIngressPortPolicer_II',
'saiQosIngressPortPolicerUcStorm',
'saiQosIngressPortPolicerBcStorm',
'saiQosIngressPortPolicerMcStorm',
'saiQosIngressFlowPolicer',
'saiQosEgressFlowPolicer',
'saiMacLinkStatus',
'saiMacPortLoopbackEnable',
'saiMacPortStatus',
'saiMacRxMaxFrameLen',
'saiMacRxMaxFrameLen_I',
'saiMacRxMaxFrameLen_II',
'saiMacRxMaxFrameLen_III',
'saiMacRxMaxFrameLen_IV',
'saiMacRxMaxFrameLen_V',
'saiMacSetFecModeFC',
'saiMacSetFecModeRS',
'saiPortAttrAdminState',
]
m0_featureRegressionUT = [
'saiCrmFdbStaticTest',
'saiCrmFdbDynamicTest_1',
'saiCrmFdbDynamicTest_2',
'saiCrmFdbDynamicTest_3',
'saiCrmAclTableTest',
'saiCrmAclCounter',
'saiCrmAclGroup',
'saiCrmAclTableEntry',
'saiCrmIpv4RouteTest',
'saiCrmIpv6RouteTest',
'saiCrmIpv4NHTest',
'saiCrmIpv4NHTest_1',
'saiCrmIpv6NHTest',
'saiCrmIpv6NHTest_1',
'saiCrmIpv4NeighborTest',
'saiCrmIpv6NeighborTest',
'saiCrmNHGroupTest',
'saiCrmNHGroupMemberTest',
'saiCrmFdbDynamicAgeOutTest',
'saiFdbDynamicForward_I',
'saiFdbDynamicForward_II',
'saiFdbDynamicForward_III',
'saiFdbDynamicForwardNeg_IV',
'saiFdbStaticForward',
'saiFdbStaticForwardNeg',
'saiFdbSAInvalidBehavior',
'saiFdbSAiszeroBehavior',
'saiFdbDAisSABehavior',
'saiFdbAgingDynamic_I',
'saiFdbAgingDynamic_II',
'saiFdbAgingDynamic_III',
'saiFdbAgingStatic_I',
'saiFdbAgingStatic_II',
'saiFdbAgingStatic_III',
'saiFdbAgingStatic_IV',
'saiFdbAgingIpv4_I',
'saiFdbAgingIpv4_II',
'saiFdbAgingIpv4_III',
'saiFdbAgingIpv4_IV',
'saiFdbAgingIpv6_I',
'saiFdbAgingIpv6_II',
'saiFdbAgingIpv6_III',
'saiFdbAgingIpv6_IV',
MtuConfigTest',
'saiMtuConfigTest_I',
'saiMtuConfigTest_II',
'saiMtuConfigProfileTest',
'saiMtuConfigProfileTest_I',
'saiMtuIpProfileTest',
'saiMtuIpProfileTest_I',
'saiMtuIpProfileTest_II',
'saiMtuIpProfileTest_III',
'saiMtuIpProfileTest_IV',
'saiL3VerifyRouteNhForwarding',
'saiL3VerifyRouteNeigbourDrop',
'saiL3VerifyRouteNhLagForwarding',
'saiL3VerifyRouteNhLagForwardingIngressLag',
'saiL3VerifyRouteNhVlanIntfForwarding',
'saiL3VerifyRouteNhVlanIntfForwardingIngressVlanIntf',
'saiL3VerifyV4RouteDrop',
'saiL3VerifyV4RouteTrap',
'saiL3VerifyV6RouteDrop',
'saiL3VerifyV6RouteNhForwarding',
'saiL3VerifyV6RouteTrap',
'saiL3NhVerifyNhCreation',
'saiL3NhVerifyV4NeighbourCreation',
'saiL3NhVerifyV4NhGroupCreation',
'saiL3NhVerifyV6NeighbourCreation',
'saiL3NhVerifyV6NhCreation',
'saiL3NhVerifyV6NhGroupCreation',
'saiL3VerifyV4NhGroupForwarding',
'saiL3VerifyV4NhGroupForwarding_pktaction',
'saiL3VerifyV4NhMemberRemoveReAdd',
'saiL3VerifyV6NhGroupForwarding',
'saiL3NhVerifyNhDeletion',
L3SipEqualToDipBehavior',
'saiEgrAclL4SrcDst',
'saiEgrAclLagL4SrcDst',
'saiEgrAclLagSipv6Dipv6',
'saiEgrAclLagSipv4Dipv4',
'saiEgrAclSipv6Dipv6',
'saiEgrAclSipv4Dipv4',
'saiIngrAclL4SrcPort',
'saiIngrAclL4DstPort',
'saiIngrAclLagL4SrcDst',
'saiIngrAclLagSipv4Dipv4',
'saiIngrAclSipv6Dipv6',
'saiIngrAclTcpFlags',
'saiMacRxMaxFrameLen',
'saiMacRxMaxFrameLen_I',
'saiMacRxMaxFrameLen_II',
'saiMacRxMaxFrameLen_III',
'saiMacRxMaxFrameLen_IV',
'saiMacRxMaxFrameLen_V',
]
| true | true |
f7f93d2d56c2073e4cb0f9350377c52ec8f41ad7 | 26,058 | py | Python | sdk/apimanagement/azure-mgmt-apimanagement/azure/mgmt/apimanagement/operations/_diagnostic_operations.py | mohamedshabanofficial/azure-sdk-for-python | 81c585f310cd2ec23d2ad145173958914a075a58 | [
"MIT"
] | 2 | 2021-03-24T06:26:11.000Z | 2021-04-18T15:55:59.000Z | sdk/apimanagement/azure-mgmt-apimanagement/azure/mgmt/apimanagement/operations/_diagnostic_operations.py | mohamedshabanofficial/azure-sdk-for-python | 81c585f310cd2ec23d2ad145173958914a075a58 | [
"MIT"
] | 2 | 2021-11-03T06:10:36.000Z | 2021-12-01T06:29:39.000Z | sdk/apimanagement/azure-mgmt-apimanagement/azure/mgmt/apimanagement/operations/_diagnostic_operations.py | mohamedshabanofficial/azure-sdk-for-python | 81c585f310cd2ec23d2ad145173958914a075a58 | [
"MIT"
] | 1 | 2021-05-19T02:55:10.000Z | 2021-05-19T02:55:10.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.mgmt.core.exceptions import ARMErrorFormat
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 DiagnosticOperations(object):
"""DiagnosticOperations 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.apimanagement.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 list_by_service(
self,
resource_group_name, # type: str
service_name, # type: str
filter=None, # type: Optional[str]
top=None, # type: Optional[int]
skip=None, # type: Optional[int]
**kwargs # type: Any
):
# type: (...) -> Iterable["_models.DiagnosticCollection"]
"""Lists all diagnostics of the API Management service instance.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param service_name: The name of the API Management service.
:type service_name: str
:param filter: | Field | Usage | Supported operators | Supported
functions |</br>|-------------|-------------|-------------|-------------|</br>| name |
filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>.
:type filter: str
:param top: Number of records to return.
:type top: int
:param skip: Number of records to skip.
:type skip: int
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either DiagnosticCollection or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.apimanagement.models.DiagnosticCollection]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.DiagnosticCollection"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-06-01-preview"
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_service.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'serviceName': self._serialize.url("service_name", service_name, 'str', max_length=50, min_length=1, pattern=r'^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$'),
'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]
if filter is not None:
query_parameters['$filter'] = self._serialize.query("filter", filter, 'str')
if top is not None:
query_parameters['$top'] = self._serialize.query("top", top, 'int', minimum=1)
if skip is not None:
query_parameters['$skip'] = self._serialize.query("skip", skip, 'int', minimum=0)
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('DiagnosticCollection', 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]:
error = self._deserialize(_models.ErrorResponse, response)
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list_by_service.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/diagnostics'} # type: ignore
def get_entity_tag(
self,
resource_group_name, # type: str
service_name, # type: str
diagnostic_id, # type: str
**kwargs # type: Any
):
# type: (...) -> bool
"""Gets the entity state (Etag) version of the Diagnostic specified by its identifier.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param service_name: The name of the API Management service.
:type service_name: str
:param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
service instance.
:type diagnostic_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: bool, or the result of cls(response)
:rtype: bool
:raises: ~azure.core.exceptions.HttpResponseError
"""
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-06-01-preview"
accept = "application/json"
# Construct URL
url = self.get_entity_tag.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'serviceName': self._serialize.url("service_name", service_name, 'str', max_length=50, min_length=1, pattern=r'^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$'),
'diagnosticId': self._serialize.url("diagnostic_id", diagnostic_id, 'str', max_length=80, min_length=1, pattern=r'^[^*#&+:<>?]+$'),
'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.head(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)
error = self._deserialize(_models.ErrorResponse, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
response_headers = {}
response_headers['ETag']=self._deserialize('str', response.headers.get('ETag'))
if cls:
return cls(pipeline_response, None, response_headers)
return 200 <= response.status_code <= 299
get_entity_tag.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/diagnostics/{diagnosticId}'} # type: ignore
def get(
self,
resource_group_name, # type: str
service_name, # type: str
diagnostic_id, # type: str
**kwargs # type: Any
):
# type: (...) -> "_models.DiagnosticContract"
"""Gets the details of the Diagnostic specified by its identifier.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param service_name: The name of the API Management service.
:type service_name: str
:param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
service instance.
:type diagnostic_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: DiagnosticContract, or the result of cls(response)
:rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.DiagnosticContract"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-06-01-preview"
accept = "application/json"
# Construct URL
url = self.get.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'serviceName': self._serialize.url("service_name", service_name, 'str', max_length=50, min_length=1, pattern=r'^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$'),
'diagnosticId': self._serialize.url("diagnostic_id", diagnostic_id, 'str', max_length=80, min_length=1, pattern=r'^[^*#&+:<>?]+$'),
'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.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)
error = self._deserialize(_models.ErrorResponse, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
response_headers = {}
response_headers['ETag']=self._deserialize('str', response.headers.get('ETag'))
deserialized = self._deserialize('DiagnosticContract', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, response_headers)
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/diagnostics/{diagnosticId}'} # type: ignore
def create_or_update(
self,
resource_group_name, # type: str
service_name, # type: str
diagnostic_id, # type: str
parameters, # type: "_models.DiagnosticContract"
if_match=None, # type: Optional[str]
**kwargs # type: Any
):
# type: (...) -> "_models.DiagnosticContract"
"""Creates a new Diagnostic or updates an existing one.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param service_name: The name of the API Management service.
:type service_name: str
:param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
service instance.
:type diagnostic_id: str
:param parameters: Create parameters.
:type parameters: ~azure.mgmt.apimanagement.models.DiagnosticContract
:param if_match: ETag of the Entity. Not required when creating an entity, but required when
updating an entity.
:type if_match: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: DiagnosticContract, or the result of cls(response)
:rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.DiagnosticContract"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-06-01-preview"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self.create_or_update.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'serviceName': self._serialize.url("service_name", service_name, 'str', max_length=50, min_length=1, pattern=r'^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$'),
'diagnosticId': self._serialize.url("diagnostic_id", diagnostic_id, 'str', max_length=80, min_length=1, pattern=r'^[^*#&+:<>?]+$'),
'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]
if if_match is not None:
header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str')
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, 'DiagnosticContract')
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)
error = self._deserialize(_models.ErrorResponse, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
response_headers = {}
if response.status_code == 200:
response_headers['ETag']=self._deserialize('str', response.headers.get('ETag'))
deserialized = self._deserialize('DiagnosticContract', pipeline_response)
if response.status_code == 201:
response_headers['ETag']=self._deserialize('str', response.headers.get('ETag'))
deserialized = self._deserialize('DiagnosticContract', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, response_headers)
return deserialized
create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/diagnostics/{diagnosticId}'} # type: ignore
def update(
self,
resource_group_name, # type: str
service_name, # type: str
diagnostic_id, # type: str
if_match, # type: str
parameters, # type: "_models.DiagnosticContract"
**kwargs # type: Any
):
# type: (...) -> "_models.DiagnosticContract"
"""Updates the details of the Diagnostic specified by its identifier.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param service_name: The name of the API Management service.
:type service_name: str
:param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
service instance.
:type diagnostic_id: str
:param if_match: ETag of the Entity. ETag should match the current entity state from the header
response of the GET request or it should be * for unconditional update.
:type if_match: str
:param parameters: Diagnostic Update parameters.
:type parameters: ~azure.mgmt.apimanagement.models.DiagnosticContract
:keyword callable cls: A custom type or function that will be passed the direct response
:return: DiagnosticContract, or the result of cls(response)
:rtype: ~azure.mgmt.apimanagement.models.DiagnosticContract
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.DiagnosticContract"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-06-01-preview"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self.update.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'serviceName': self._serialize.url("service_name", service_name, 'str', max_length=50, min_length=1, pattern=r'^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$'),
'diagnosticId': self._serialize.url("diagnostic_id", diagnostic_id, 'str', max_length=80, min_length=1, pattern=r'^[^*#&+:<>?]+$'),
'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['If-Match'] = self._serialize.header("if_match", if_match, 'str')
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, 'DiagnosticContract')
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)
error = self._deserialize(_models.ErrorResponse, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
response_headers = {}
response_headers['ETag']=self._deserialize('str', response.headers.get('ETag'))
deserialized = self._deserialize('DiagnosticContract', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, response_headers)
return deserialized
update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/diagnostics/{diagnosticId}'} # type: ignore
def delete(
self,
resource_group_name, # type: str
service_name, # type: str
diagnostic_id, # type: str
if_match, # type: str
**kwargs # type: Any
):
# type: (...) -> None
"""Deletes the specified Diagnostic.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param service_name: The name of the API Management service.
:type service_name: str
:param diagnostic_id: Diagnostic identifier. Must be unique in the current API Management
service instance.
:type diagnostic_id: str
:param if_match: ETag of the Entity. ETag should match the current entity state from the header
response of the GET request or it should be * for unconditional update.
:type if_match: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:raises: ~azure.core.exceptions.HttpResponseError
"""
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-06-01-preview"
accept = "application/json"
# Construct URL
url = self.delete.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'serviceName': self._serialize.url("service_name", service_name, 'str', max_length=50, min_length=1, pattern=r'^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$'),
'diagnosticId': self._serialize.url("diagnostic_id", diagnostic_id, 'str', max_length=80, min_length=1, pattern=r'^[^*#&+:<>?]+$'),
'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['If-Match'] = self._serialize.header("if_match", if_match, 'str')
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, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize(_models.ErrorResponse, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/diagnostics/{diagnosticId}'} # type: ignore
| 51.498024 | 208 | 0.657341 |
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.mgmt.core.exceptions import ARMErrorFormat
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 DiagnosticOperations(object):
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def list_by_service(
self,
resource_group_name,
service_name,
filter=None,
top=None,
skip=None,
**kwargs
):
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-06-01-preview"
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_service.metadata['url']
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'serviceName': self._serialize.url("service_name", service_name, 'str', max_length=50, min_length=1, pattern=r'^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
if filter is not None:
query_parameters['$filter'] = self._serialize.query("filter", filter, 'str')
if top is not None:
query_parameters['$top'] = self._serialize.query("top", top, 'int', minimum=1)
if skip is not None:
query_parameters['$skip'] = self._serialize.query("skip", skip, 'int', minimum=0)
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('DiagnosticCollection', 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]:
error = self._deserialize(_models.ErrorResponse, response)
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list_by_service.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/diagnostics'}
def get_entity_tag(
self,
resource_group_name,
service_name,
diagnostic_id,
**kwargs
):
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-06-01-preview"
accept = "application/json"
url = self.get_entity_tag.metadata['url']
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'serviceName': self._serialize.url("service_name", service_name, 'str', max_length=50, min_length=1, pattern=r'^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$'),
'diagnosticId': self._serialize.url("diagnostic_id", diagnostic_id, 'str', max_length=80, min_length=1, pattern=r'^[^*#&+:<>?]+$'),
'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.head(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)
error = self._deserialize(_models.ErrorResponse, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
response_headers = {}
response_headers['ETag']=self._deserialize('str', response.headers.get('ETag'))
if cls:
return cls(pipeline_response, None, response_headers)
return 200 <= response.status_code <= 299
get_entity_tag.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/diagnostics/{diagnosticId}'}
def get(
self,
resource_group_name,
service_name,
diagnostic_id,
**kwargs
):
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-06-01-preview"
accept = "application/json"
url = self.get.metadata['url']
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'serviceName': self._serialize.url("service_name", service_name, 'str', max_length=50, min_length=1, pattern=r'^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$'),
'diagnosticId': self._serialize.url("diagnostic_id", diagnostic_id, 'str', max_length=80, min_length=1, pattern=r'^[^*#&+:<>?]+$'),
'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.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)
error = self._deserialize(_models.ErrorResponse, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
response_headers = {}
response_headers['ETag']=self._deserialize('str', response.headers.get('ETag'))
deserialized = self._deserialize('DiagnosticContract', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, response_headers)
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/diagnostics/{diagnosticId}'}
def create_or_update(
self,
resource_group_name,
service_name,
diagnostic_id,
parameters,
if_match=None,
**kwargs
):
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-06-01-preview"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
url = self.create_or_update.metadata['url']
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'serviceName': self._serialize.url("service_name", service_name, 'str', max_length=50, min_length=1, pattern=r'^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$'),
'diagnosticId': self._serialize.url("diagnostic_id", diagnostic_id, 'str', max_length=80, min_length=1, pattern=r'^[^*#&+:<>?]+$'),
'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 = {}
if if_match is not None:
header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str')
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, 'DiagnosticContract')
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)
error = self._deserialize(_models.ErrorResponse, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
response_headers = {}
if response.status_code == 200:
response_headers['ETag']=self._deserialize('str', response.headers.get('ETag'))
deserialized = self._deserialize('DiagnosticContract', pipeline_response)
if response.status_code == 201:
response_headers['ETag']=self._deserialize('str', response.headers.get('ETag'))
deserialized = self._deserialize('DiagnosticContract', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, response_headers)
return deserialized
create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/diagnostics/{diagnosticId}'}
def update(
self,
resource_group_name,
service_name,
diagnostic_id,
if_match,
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-06-01-preview"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
url = self.update.metadata['url']
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'serviceName': self._serialize.url("service_name", service_name, 'str', max_length=50, min_length=1, pattern=r'^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$'),
'diagnosticId': self._serialize.url("diagnostic_id", diagnostic_id, 'str', max_length=80, min_length=1, pattern=r'^[^*#&+:<>?]+$'),
'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['If-Match'] = self._serialize.header("if_match", if_match, 'str')
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, 'DiagnosticContract')
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)
error = self._deserialize(_models.ErrorResponse, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
response_headers = {}
response_headers['ETag']=self._deserialize('str', response.headers.get('ETag'))
deserialized = self._deserialize('DiagnosticContract', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, response_headers)
return deserialized
update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/diagnostics/{diagnosticId}'}
def delete(
self,
resource_group_name,
service_name,
diagnostic_id,
if_match,
**kwargs
):
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-06-01-preview"
accept = "application/json"
url = self.delete.metadata['url']
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'serviceName': self._serialize.url("service_name", service_name, 'str', max_length=50, min_length=1, pattern=r'^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$'),
'diagnosticId': self._serialize.url("diagnostic_id", diagnostic_id, 'str', max_length=80, min_length=1, pattern=r'^[^*#&+:<>?]+$'),
'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['If-Match'] = self._serialize.header("if_match", if_match, 'str')
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, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize(_models.ErrorResponse, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/diagnostics/{diagnosticId}'}
| true | true |
f7f93dd897f60ba55b61ad8da80c4ef1c2949a55 | 2,782 | py | Python | benchmark/lsh_benchmark_plot.py | yrik/datasketch | 82d9639bc0011932a952bbae1d4b5bd5ac03c7c8 | [
"MIT"
] | 1 | 2019-06-05T15:06:08.000Z | 2019-06-05T15:06:08.000Z | benchmark/lsh_benchmark_plot.py | yrik/datasketch | 82d9639bc0011932a952bbae1d4b5bd5ac03c7c8 | [
"MIT"
] | null | null | null | benchmark/lsh_benchmark_plot.py | yrik/datasketch | 82d9639bc0011932a952bbae1d4b5bd5ac03c7c8 | [
"MIT"
] | 2 | 2018-11-12T18:00:52.000Z | 2022-03-21T05:36:20.000Z | import json, sys, argparse
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
def get_precision_recall(found, reference):
reference = set(reference)
intersect = sum(1 for i in found if i in reference)
if len(found) == 0:
precision = 0.0
else:
precision = float(intersect) / float(len(found))
if len(reference) == 0:
recall = 1.0
else:
recall = float(intersect) / float(len(reference))
if len(found) == len(reference) == 0:
precision = 1.0
recall = 1.0
return [precision, recall]
def fscore(precision, recall):
if precision == 0.0 and recall == 0.0:
return 0.0
return 2.0 / (1.0 / precision + 1.0 / recall)
def average_fscore(founds, references):
return np.mean([fscore(*get_precision_recall(found, reference))
for found, reference in zip(founds, references)])
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("benchmark_output")
args = parser.parse_args(sys.argv[1:])
with open(args.benchmark_output) as f:
benchmark = json.load(f)
num_perms = benchmark["num_perms"]
lsh_times = benchmark["lsh_times"]
linearscan_times = benchmark["linearscan_times"]
ground_truth_results = [[x[0] for x in r] for r in benchmark["ground_truth_results"]]
lsh_fscores = []
for results in benchmark["lsh_results"]:
query_results = [[x[0] for x in r] for r in results]
lsh_fscores.append(average_fscore(query_results, ground_truth_results))
linearscan_fscores = []
for results in benchmark["linearscan_results"]:
query_results = [[x[0] for x in r] for r in results]
linearscan_fscores.append(average_fscore(query_results, ground_truth_results))
lsh_times = np.array([np.percentile(ts, 90)
for ts in lsh_times])*1000
linearscan_times = np.array([np.percentile(ts, 90)
for ts in linearscan_times])*1000
fig, axes = plt.subplots(1, 2, figsize=(5*2, 4.5), sharex=True)
# Plot query fscore vs. num perm
axes[0].plot(num_perms, linearscan_fscores, marker="+", label="Linearscan")
axes[0].plot(num_perms, lsh_fscores, marker="+", label="LSH")
axes[0].set_ylabel("Average F-Score")
axes[0].set_xlabel("# of Permmutation Functions")
axes[0].grid()
# Plot query time vs. num perm
axes[1].plot(num_perms, linearscan_times, marker="+", label="Linearscan")
axes[1].plot(num_perms, lsh_times, marker="+", label="LSH")
axes[1].set_xlabel("# of Permutation Functions")
axes[1].set_ylabel("90 Percentile Query Time (ms)")
axes[1].grid()
axes[1].legend(loc="center right")
fig.savefig("lsh_benchmark.png", pad_inches=0.05, bbox_inches="tight")
| 37.594595 | 89 | 0.663911 | import json, sys, argparse
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
def get_precision_recall(found, reference):
reference = set(reference)
intersect = sum(1 for i in found if i in reference)
if len(found) == 0:
precision = 0.0
else:
precision = float(intersect) / float(len(found))
if len(reference) == 0:
recall = 1.0
else:
recall = float(intersect) / float(len(reference))
if len(found) == len(reference) == 0:
precision = 1.0
recall = 1.0
return [precision, recall]
def fscore(precision, recall):
if precision == 0.0 and recall == 0.0:
return 0.0
return 2.0 / (1.0 / precision + 1.0 / recall)
def average_fscore(founds, references):
return np.mean([fscore(*get_precision_recall(found, reference))
for found, reference in zip(founds, references)])
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("benchmark_output")
args = parser.parse_args(sys.argv[1:])
with open(args.benchmark_output) as f:
benchmark = json.load(f)
num_perms = benchmark["num_perms"]
lsh_times = benchmark["lsh_times"]
linearscan_times = benchmark["linearscan_times"]
ground_truth_results = [[x[0] for x in r] for r in benchmark["ground_truth_results"]]
lsh_fscores = []
for results in benchmark["lsh_results"]:
query_results = [[x[0] for x in r] for r in results]
lsh_fscores.append(average_fscore(query_results, ground_truth_results))
linearscan_fscores = []
for results in benchmark["linearscan_results"]:
query_results = [[x[0] for x in r] for r in results]
linearscan_fscores.append(average_fscore(query_results, ground_truth_results))
lsh_times = np.array([np.percentile(ts, 90)
for ts in lsh_times])*1000
linearscan_times = np.array([np.percentile(ts, 90)
for ts in linearscan_times])*1000
fig, axes = plt.subplots(1, 2, figsize=(5*2, 4.5), sharex=True)
axes[0].plot(num_perms, linearscan_fscores, marker="+", label="Linearscan")
axes[0].plot(num_perms, lsh_fscores, marker="+", label="LSH")
axes[0].set_ylabel("Average F-Score")
axes[0].set_xlabel("# of Permmutation Functions")
axes[0].grid()
axes[1].plot(num_perms, linearscan_times, marker="+", label="Linearscan")
axes[1].plot(num_perms, lsh_times, marker="+", label="LSH")
axes[1].set_xlabel("# of Permutation Functions")
axes[1].set_ylabel("90 Percentile Query Time (ms)")
axes[1].grid()
axes[1].legend(loc="center right")
fig.savefig("lsh_benchmark.png", pad_inches=0.05, bbox_inches="tight")
| true | true |
f7f93f56302e4afd3d3981bed46985d9836be30c | 1,529 | py | Python | diagnostics/AE_time_loop_grad.py | scheng1992/Data_Assimilation | b4d43895229205ee2cd16b15ee20beccb33b71d6 | [
"MIT"
] | 1 | 2021-11-25T12:46:48.000Z | 2021-11-25T12:46:48.000Z | diagnostics/AE_time_loop_grad.py | bugsuse/Data_Assimilation | 2965ccf78951df11f8686282cd6814bae18afde5 | [
"MIT"
] | null | null | null | diagnostics/AE_time_loop_grad.py | bugsuse/Data_Assimilation | 2965ccf78951df11f8686282cd6814bae18afde5 | [
"MIT"
] | 2 | 2021-03-02T13:29:34.000Z | 2022-03-12T11:01:08.000Z | import torch
import sys, os
sys.path.append(os.getcwd()) #to import pipeline
from pipeline.utils import ML_utils as ML
from pipeline.AutoEncoders import ToyAE
from pipeline import utils
import time
import matplotlib.pyplot as plt
def plot_time_w_output(outputs, inn, hidden, batch_sz, loop=True, no_batch=False):
T_2s = []
T_1s = []
factors = []
utils.set_seeds(42)
input = torch.rand((Batch_sz, inn), requires_grad=True)
if no_batch:
input = input[0]
for out_sz in outputs:
model = ToyAE(inn, hidden, out_sz)
model.gen_rand_weights()
output = model.decode(input)
t0 = time.time()
if loop:
jac_true = ML.jacobian_slow_torch(input, output)
t1 = time.time()
jac_expl = model.jac_explicit(input)
t2 = time.time()
T_1 = t1-t0
T_2 = t2-t1
try:
factor = T_1 / T_2
except ZeroDivisionError:
factor = 0
T_1s.append(T_1)
T_2s.append(T_2)
factors.append(factor)
if loop:
print("out = {}. Explicit x{:.1f} faster than loop method".format(out_sz, factor))
if loop:
plt.plot(outputs, T_1s)
plt.show()
plt.plot(outputs, factors)
plt.show()
plt.plot(outputs, T_2s)
plt.show()
if __name__ == "__main__":
INPUT = 32
HIDDEN = 128
Batch_sz = 64
outputs = [2**x for x in range(8)]
plot_time_w_output(outputs, INPUT, HIDDEN, Batch_sz, loop=True, no_batch=False)
| 24.269841 | 94 | 0.603009 | import torch
import sys, os
sys.path.append(os.getcwd())
from pipeline.utils import ML_utils as ML
from pipeline.AutoEncoders import ToyAE
from pipeline import utils
import time
import matplotlib.pyplot as plt
def plot_time_w_output(outputs, inn, hidden, batch_sz, loop=True, no_batch=False):
T_2s = []
T_1s = []
factors = []
utils.set_seeds(42)
input = torch.rand((Batch_sz, inn), requires_grad=True)
if no_batch:
input = input[0]
for out_sz in outputs:
model = ToyAE(inn, hidden, out_sz)
model.gen_rand_weights()
output = model.decode(input)
t0 = time.time()
if loop:
jac_true = ML.jacobian_slow_torch(input, output)
t1 = time.time()
jac_expl = model.jac_explicit(input)
t2 = time.time()
T_1 = t1-t0
T_2 = t2-t1
try:
factor = T_1 / T_2
except ZeroDivisionError:
factor = 0
T_1s.append(T_1)
T_2s.append(T_2)
factors.append(factor)
if loop:
print("out = {}. Explicit x{:.1f} faster than loop method".format(out_sz, factor))
if loop:
plt.plot(outputs, T_1s)
plt.show()
plt.plot(outputs, factors)
plt.show()
plt.plot(outputs, T_2s)
plt.show()
if __name__ == "__main__":
INPUT = 32
HIDDEN = 128
Batch_sz = 64
outputs = [2**x for x in range(8)]
plot_time_w_output(outputs, INPUT, HIDDEN, Batch_sz, loop=True, no_batch=False)
| true | true |
f7f93f796fa58111d4b3534adb7af35b1ee8eead | 1,123 | py | Python | malaya_speech/train/model/pix2pix/discriminator.py | ishine/malaya-speech | fd34afc7107af1656dff4b3201fa51dda54fde18 | [
"MIT"
] | 111 | 2020-08-31T04:58:54.000Z | 2022-03-29T15:44:18.000Z | malaya_speech/train/model/pix2pix/discriminator.py | ishine/malaya-speech | fd34afc7107af1656dff4b3201fa51dda54fde18 | [
"MIT"
] | 14 | 2020-12-16T07:27:22.000Z | 2022-03-15T17:39:01.000Z | malaya_speech/train/model/pix2pix/discriminator.py | ishine/malaya-speech | fd34afc7107af1656dff4b3201fa51dda54fde18 | [
"MIT"
] | 29 | 2021-02-09T08:57:15.000Z | 2022-03-12T14:09:19.000Z | import tensorflow as tf
from .layer import *
class Discriminator:
def __init__(self, inputs, targets, ndf=64):
n_layers = 3
layers = []
input = tf.concat([inputs, targets], axis=3)
with tf.variable_scope('layer_1'):
convolved = discrim_conv(input, ndf, stride=2)
rectified = lrelu(convolved, 0.2)
layers.append(rectified)
for i in range(n_layers):
with tf.variable_scope('layer_%d' % (len(layers) + 1)):
out_channels = ndf * min(2 ** (i + 1), 8)
stride = 1 if i == n_layers - 1 else 2
convolved = discrim_conv(
layers[-1], out_channels, stride=stride
)
normalized = batchnorm(convolved)
rectified = lrelu(normalized, 0.2)
layers.append(rectified)
with tf.variable_scope('layer_%d' % (len(layers) + 1)):
convolved = discrim_conv(rectified, out_channels=1, stride=1)
output = tf.sigmoid(convolved)
layers.append(output)
self.logits = layers[-1]
| 36.225806 | 73 | 0.548531 | import tensorflow as tf
from .layer import *
class Discriminator:
def __init__(self, inputs, targets, ndf=64):
n_layers = 3
layers = []
input = tf.concat([inputs, targets], axis=3)
with tf.variable_scope('layer_1'):
convolved = discrim_conv(input, ndf, stride=2)
rectified = lrelu(convolved, 0.2)
layers.append(rectified)
for i in range(n_layers):
with tf.variable_scope('layer_%d' % (len(layers) + 1)):
out_channels = ndf * min(2 ** (i + 1), 8)
stride = 1 if i == n_layers - 1 else 2
convolved = discrim_conv(
layers[-1], out_channels, stride=stride
)
normalized = batchnorm(convolved)
rectified = lrelu(normalized, 0.2)
layers.append(rectified)
with tf.variable_scope('layer_%d' % (len(layers) + 1)):
convolved = discrim_conv(rectified, out_channels=1, stride=1)
output = tf.sigmoid(convolved)
layers.append(output)
self.logits = layers[-1]
| true | true |
f7f93fbcc5d69ad0e6a57642ce60898248c5b51e | 4,181 | py | Python | swig/python/gdal-utils/osgeo_utils/samples/get_soundg.py | gajgeospatial/gdal-3.4.1 | 808ab4e7ffb8a2a1517557ac9fccf933f7479c4e | [
"Apache-2.0"
] | null | null | null | swig/python/gdal-utils/osgeo_utils/samples/get_soundg.py | gajgeospatial/gdal-3.4.1 | 808ab4e7ffb8a2a1517557ac9fccf933f7479c4e | [
"Apache-2.0"
] | null | null | null | swig/python/gdal-utils/osgeo_utils/samples/get_soundg.py | gajgeospatial/gdal-3.4.1 | 808ab4e7ffb8a2a1517557ac9fccf933f7479c4e | [
"Apache-2.0"
] | 1 | 2022-03-17T16:01:01.000Z | 2022-03-17T16:01:01.000Z | #!/usr/bin/env python3
###############################################################################
# $Id: get_soundg.py e4fe7cc06270e5f38dfe78e6785a6bcca4e39e29 2021-04-01 21:02:04 +0300 Idan Miara $
#
# Project: OGR Python samples
# Purpose: Extract SOUNDGings from an S-57 dataset, and write them to
# Shapefile format, creating one feature for each sounding, and
# adding the elevation as an attribute for easier use.
# Author: Frank Warmerdam, warmerdam@pobox.com
#
###############################################################################
# Copyright (c) 2003, Frank Warmerdam <warmerdam@pobox.com>
#
# 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 sys
from osgeo import ogr
#############################################################################
def Usage():
print('Usage: get_soundg.py <s57file> <shapefile>')
print('')
return 1
def main(argv):
if len(argv) != 3:
return Usage()
s57filename = argv[1]
shpfilename = argv[2]
# -
# Open the S57 file, and find the SOUNDG layer.
ds = ogr.Open(s57filename)
src_soundg = ds.GetLayerByName('SOUNDG')
# -
# Create the output shapefile.
shp_driver = ogr.GetDriverByName('ESRI Shapefile')
shp_driver.DeleteDataSource(shpfilename)
shp_ds = shp_driver.CreateDataSource(shpfilename)
shp_layer = shp_ds.CreateLayer('out', geom_type=ogr.wkbPoint25D)
src_defn = src_soundg.GetLayerDefn()
field_count = src_defn.GetFieldCount()
# -
# Copy the SOUNDG schema, and add an ELEV field.
out_mapping = []
for fld_index in range(field_count):
src_fd = src_defn.GetFieldDefn(fld_index)
fd = ogr.FieldDefn(src_fd.GetName(), src_fd.GetType())
fd.SetWidth(src_fd.GetWidth())
fd.SetPrecision(src_fd.GetPrecision())
if shp_layer.CreateField(fd) != 0:
out_mapping.append(-1)
else:
out_mapping.append(shp_layer.GetLayerDefn().GetFieldCount() - 1)
fd = ogr.FieldDefn('ELEV', ogr.OFTReal)
fd.SetWidth(12)
fd.SetPrecision(4)
shp_layer.CreateField(fd)
#############################################################################
# Process all SOUNDG features.
feat = src_soundg.GetNextFeature()
while feat is not None:
multi_geom = feat.GetGeometryRef()
for iPnt in range(multi_geom.GetGeometryCount()):
pnt = multi_geom.GetGeometryRef(iPnt)
feat2 = ogr.Feature(feature_def=shp_layer.GetLayerDefn())
for fld_index in range(field_count):
feat2.SetField(out_mapping[fld_index], feat.GetField(fld_index))
feat2.SetField('ELEV', pnt.GetZ(0))
feat2.SetGeometry(pnt)
shp_layer.CreateFeature(feat2)
feat2.Destroy()
feat.Destroy()
feat = src_soundg.GetNextFeature()
#############################################################################
# Cleanup
shp_ds.Destroy()
ds.Destroy()
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
| 32.664063 | 100 | 0.609663 | true | true | |
f7f93fe0777d750e8f8b5be60ef838282cfbdd79 | 13,227 | py | Python | src/train.py | Omkar-Ranadive/Fine-Tuning-BERT | b046092ec4007a4a59e1a478576cca7557c18d76 | [
"Apache-2.0"
] | 1 | 2020-05-24T03:21:25.000Z | 2020-05-24T03:21:25.000Z | src/train.py | Omkar-Ranadive/Fine-Tuning-BERT | b046092ec4007a4a59e1a478576cca7557c18d76 | [
"Apache-2.0"
] | null | null | null | src/train.py | Omkar-Ranadive/Fine-Tuning-BERT | b046092ec4007a4a59e1a478576cca7557c18d76 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
"""
Main training workflow
"""
from __future__ import division
import argparse
import glob
import os
import random
import signal
import time
import torch
from pytorch_pretrained_bert import BertConfig
import distributed
from models import data_loader, model_builder
from models.data_loader import load_dataset
from models.model_builder import Summarizer
from models.trainer import build_trainer
from others.logging import logger, init_logger
import matplotlib.pyplot as plt
from src.utils import save_pickle
model_flags = ['hidden_size', 'ff_size', 'heads', 'inter_layers','encoder','ff_actv', 'use_interval','rnn_size']
def str2bool(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')
def multi_main(args):
""" Spawns 1 process per GPU """
init_logger()
nb_gpu = args.world_size
mp = torch.multiprocessing.get_context('spawn')
# Create a thread to listen for errors in the child processes.
error_queue = mp.SimpleQueue()
error_handler = ErrorHandler(error_queue)
# Train with multiprocessing.
procs = []
for i in range(nb_gpu):
device_id = i
procs.append(mp.Process(target=run, args=(args,
device_id, error_queue,), daemon=True))
procs[i].start()
logger.info(" Starting process pid: %d " % procs[i].pid)
error_handler.add_child(procs[i].pid)
for p in procs:
p.join()
def run(args, device_id, error_queue):
""" run process """
setattr(args, 'gpu_ranks', [int(i) for i in args.gpu_ranks])
try:
gpu_rank = distributed.multi_init(device_id, args.world_size, args.gpu_ranks)
print('gpu_rank %d' %gpu_rank)
if gpu_rank != args.gpu_ranks[device_id]:
raise AssertionError("An error occurred in \
Distributed initialization")
train(args,device_id)
except KeyboardInterrupt:
pass # killed by parent, do nothing
except Exception:
# propagate exception to parent process, keeping original traceback
import traceback
error_queue.put((args.gpu_ranks[device_id], traceback.format_exc()))
class ErrorHandler(object):
"""A class that listens for exceptions in children processes and propagates
the tracebacks to the parent process."""
def __init__(self, error_queue):
""" init error handler """
import signal
import threading
self.error_queue = error_queue
self.children_pids = []
self.error_thread = threading.Thread(
target=self.error_listener, daemon=True)
self.error_thread.start()
signal.signal(signal.SIGUSR1, self.signal_handler)
def add_child(self, pid):
""" error handler """
self.children_pids.append(pid)
def error_listener(self):
""" error listener """
(rank, original_trace) = self.error_queue.get()
self.error_queue.put((rank, original_trace))
os.kill(os.getpid(), signal.SIGUSR1)
def signal_handler(self, signalnum, stackframe):
""" signal handler """
for pid in self.children_pids:
os.kill(pid, signal.SIGINT) # kill children processes
(rank, original_trace) = self.error_queue.get()
msg = """\n\n-- Tracebacks above this line can probably
be ignored --\n\n"""
msg += original_trace
raise Exception(msg)
def wait_and_validate(args, device_id):
timestep = 0
if (args.test_all):
print("In here!")
cp_files = sorted(glob.glob(os.path.join(args.model_path, 'model_step_*.pt')))
cp_files.sort(key=os.path.getmtime)
print("Cp files", cp_files)
xent_lst = []
for i, cp in enumerate(cp_files):
step = int(cp.split('.')[-2].split('_')[-1])
xent = validate(args, device_id, cp, step)
xent_lst.append((xent, cp))
max_step = xent_lst.index(min(xent_lst))
if (i - max_step > 10):
break
xent_lst = sorted(xent_lst, key=lambda x: x[0])[:3]
logger.info('PPL %s' % str(xent_lst))
for xent, cp in xent_lst:
step = int(cp.split('.')[-2].split('_')[-1])
test(args, device_id, cp, step)
else:
while (True):
cp_files = sorted(glob.glob(os.path.join(args.model_path, 'model_step_*.pt')))
cp_files.sort(key=os.path.getmtime)
if (cp_files):
cp = cp_files[-1]
time_of_cp = os.path.getmtime(cp)
if (not os.path.getsize(cp) > 0):
time.sleep(60)
continue
if (time_of_cp > timestep):
timestep = time_of_cp
step = int(cp.split('.')[-2].split('_')[-1])
validate(args, device_id, cp, step)
test(args, device_id, cp, step)
cp_files = sorted(glob.glob(os.path.join(args.model_path, 'model_step_*.pt')))
cp_files.sort(key=os.path.getmtime)
if (cp_files):
cp = cp_files[-1]
time_of_cp = os.path.getmtime(cp)
if (time_of_cp > timestep):
continue
else:
time.sleep(300)
def validate(args, device_id, pt, step):
device = "cpu" if args.visible_gpus == '-1' else "cuda"
if (pt != ''):
test_from = pt
else:
test_from = args.test_from
logger.info('Loading checkpoint from %s' % test_from)
checkpoint = torch.load(test_from, map_location=lambda storage, loc: storage)
opt = vars(checkpoint['opt'])
for k in opt.keys():
if (k in model_flags):
setattr(args, k, opt[k])
print(args)
config = BertConfig.from_json_file(args.bert_config_path)
model = Summarizer(args, device, load_pretrained_bert=False, bert_config = config)
model.load_cp(checkpoint)
model.eval()
valid_iter =data_loader.Dataloader(args, load_dataset(args, 'valid', shuffle=False),
args.batch_size, device,
shuffle=False, is_test=False)
trainer = build_trainer(args, device_id, model, None)
stats = trainer.validate(valid_iter, step)
print("Stats: {}".format(stats.xent()))
return stats.xent()
def test(args, device_id, pt, step):
device = "cpu" if args.visible_gpus == '-1' else "cuda"
if (pt != ''):
test_from = pt
else:
test_from = args.test_from
logger.info('Loading checkpoint from %s' % test_from)
checkpoint = torch.load(test_from, map_location=lambda storage, loc: storage)
opt = vars(checkpoint['opt'])
for k in opt.keys():
if (k in model_flags):
setattr(args, k, opt[k])
print(args)
config = BertConfig.from_json_file(args.bert_config_path)
model = Summarizer(args, device, load_pretrained_bert=False, bert_config = config)
model.load_cp(checkpoint)
model.eval()
test_iter =data_loader.Dataloader(args, load_dataset(args, 'test', shuffle=False),
args.batch_size, device,
shuffle=False, is_test=True)
trainer = build_trainer(args, device_id, model, None)
trainer.test(test_iter,step)
def baseline(args, cal_lead=False, cal_oracle=False):
test_iter =data_loader.Dataloader(args, load_dataset(args, 'test', shuffle=False),
args.batch_size, device,
shuffle=False, is_test=True)
trainer = build_trainer(args, device_id, None, None)
#
if (cal_lead):
trainer.test(test_iter, 0, cal_lead=True)
elif (cal_oracle):
trainer.test(test_iter, 0, cal_oracle=True)
def train(args, device_id):
init_logger(args.log_file)
device = "cpu" if args.visible_gpus == '-1' else "cuda"
logger.info('Device ID %d' % device_id)
logger.info('Device %s' % device)
torch.manual_seed(args.seed)
random.seed(args.seed)
torch.backends.cudnn.deterministic = True
if device_id >= 0:
torch.cuda.set_device(device_id)
torch.cuda.manual_seed(args.seed)
torch.manual_seed(args.seed)
random.seed(args.seed)
torch.backends.cudnn.deterministic = True
def train_iter_fct():
return data_loader.Dataloader(args, load_dataset(args, 'train', shuffle=True), args.batch_size, device,
shuffle=True, is_test=False)
model = Summarizer(args, device, load_pretrained_bert=True)
if args.train_from != '':
logger.info('Loading checkpoint from %s' % args.train_from)
checkpoint = torch.load(args.train_from,
map_location=lambda storage, loc: storage)
opt = vars(checkpoint['opt'])
for k in opt.keys():
if (k in model_flags):
setattr(args, k, opt[k])
model.load_cp(checkpoint)
optim = model_builder.build_optim(args, model, checkpoint)
else:
optim = model_builder.build_optim(args, model, None)
logger.info(model)
trainer = build_trainer(args, device_id, model, optim)
losses, n_docs = trainer.train(train_iter_fct, args.train_steps)
save_pickle(losses, 'losses_classifier')
save_pickle(n_docs, 'docs_classifier')
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-encoder", default='classifier', type=str, choices=['classifier','transformer','rnn','baseline', 'classifierDummy', 'gnn'])
parser.add_argument("-mode", default='train', type=str, choices=['train','validate','test'])
parser.add_argument("-bert_data_path", default='../bert_data/cnndm')
parser.add_argument("-model_path", default='../models/')
parser.add_argument("-result_path", default='../results/cnndm')
parser.add_argument("-temp_dir", default='../temp')
parser.add_argument("-bert_config_path", default='../bert_config_uncased_base.json')
parser.add_argument("-batch_size", default=1000, type=int)
parser.add_argument("-use_interval", type=str2bool, nargs='?',const=True,default=True)
parser.add_argument("-hidden_size", default=128, type=int)
parser.add_argument("-ff_size", default=512, type=int)
parser.add_argument("-heads", default=4, type=int)
parser.add_argument("-inter_layers", default=2, type=int)
parser.add_argument("-rnn_size", default=512, type=int)
parser.add_argument("-param_init", default=0, type=float)
parser.add_argument("-param_init_glorot", type=str2bool, nargs='?',const=True,default=True)
parser.add_argument("-dropout", default=0.1, type=float)
parser.add_argument("-optim", default='adam', type=str)
parser.add_argument("-lr", default=1, type=float)
parser.add_argument("-beta1", default= 0.9, type=float)
parser.add_argument("-beta2", default=0.999, type=float)
parser.add_argument("-decay_method", default='', type=str)
parser.add_argument("-warmup_steps", default=8000, type=int)
parser.add_argument("-max_grad_norm", default=0, type=float)
parser.add_argument("-save_checkpoint_steps", default=5, type=int)
parser.add_argument("-accum_count", default=1, type=int)
parser.add_argument("-world_size", default=1, type=int)
parser.add_argument("-report_every", default=1, type=int)
parser.add_argument("-train_steps", default=1000, type=int)
parser.add_argument("-recall_eval", type=str2bool, nargs='?',const=True,default=False)
parser.add_argument('-visible_gpus', default='-1', type=str)
parser.add_argument('-gpu_ranks', default='0', type=str)
parser.add_argument('-log_file', default='../logs/cnndm.log')
parser.add_argument('-dataset', default='')
parser.add_argument('-seed', default=666, type=int)
parser.add_argument("-test_all", type=str2bool, nargs='?',const=True,default=False)
parser.add_argument("-test_from", default='')
parser.add_argument("-train_from", default='')
parser.add_argument("-report_rouge", type=str2bool, nargs='?',const=True,default=True)
parser.add_argument("-block_trigram", type=str2bool, nargs='?', const=True, default=True)
args = parser.parse_args()
args.gpu_ranks = [int(i) for i in args.gpu_ranks.split(',')]
os.environ["CUDA_VISIBLE_DEVICES"] = args.visible_gpus
init_logger(args.log_file)
device = "cpu" if args.visible_gpus == '-1' else "cuda"
device_id = 0 if device == "cuda" else -1
if(args.world_size>1):
multi_main(args)
elif (args.mode == 'train'):
train(args, device_id)
elif (args.mode == 'validate'):
wait_and_validate(args, device_id)
elif (args.mode == 'lead'):
baseline(args, cal_lead=True)
elif (args.mode == 'oracle'):
baseline(args, cal_oracle=True)
elif (args.mode == 'test'):
cp = args.test_from
try:
step = int(cp.split('.')[-2].split('_')[-1])
except:
step = 0
test(args, device_id, cp, step)
| 36.946927 | 148 | 0.631889 |
from __future__ import division
import argparse
import glob
import os
import random
import signal
import time
import torch
from pytorch_pretrained_bert import BertConfig
import distributed
from models import data_loader, model_builder
from models.data_loader import load_dataset
from models.model_builder import Summarizer
from models.trainer import build_trainer
from others.logging import logger, init_logger
import matplotlib.pyplot as plt
from src.utils import save_pickle
model_flags = ['hidden_size', 'ff_size', 'heads', 'inter_layers','encoder','ff_actv', 'use_interval','rnn_size']
def str2bool(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')
def multi_main(args):
init_logger()
nb_gpu = args.world_size
mp = torch.multiprocessing.get_context('spawn')
error_queue = mp.SimpleQueue()
error_handler = ErrorHandler(error_queue)
procs = []
for i in range(nb_gpu):
device_id = i
procs.append(mp.Process(target=run, args=(args,
device_id, error_queue,), daemon=True))
procs[i].start()
logger.info(" Starting process pid: %d " % procs[i].pid)
error_handler.add_child(procs[i].pid)
for p in procs:
p.join()
def run(args, device_id, error_queue):
setattr(args, 'gpu_ranks', [int(i) for i in args.gpu_ranks])
try:
gpu_rank = distributed.multi_init(device_id, args.world_size, args.gpu_ranks)
print('gpu_rank %d' %gpu_rank)
if gpu_rank != args.gpu_ranks[device_id]:
raise AssertionError("An error occurred in \
Distributed initialization")
train(args,device_id)
except KeyboardInterrupt:
pass
except Exception:
import traceback
error_queue.put((args.gpu_ranks[device_id], traceback.format_exc()))
class ErrorHandler(object):
def __init__(self, error_queue):
import signal
import threading
self.error_queue = error_queue
self.children_pids = []
self.error_thread = threading.Thread(
target=self.error_listener, daemon=True)
self.error_thread.start()
signal.signal(signal.SIGUSR1, self.signal_handler)
def add_child(self, pid):
self.children_pids.append(pid)
def error_listener(self):
(rank, original_trace) = self.error_queue.get()
self.error_queue.put((rank, original_trace))
os.kill(os.getpid(), signal.SIGUSR1)
def signal_handler(self, signalnum, stackframe):
for pid in self.children_pids:
os.kill(pid, signal.SIGINT)
(rank, original_trace) = self.error_queue.get()
msg = """\n\n-- Tracebacks above this line can probably
be ignored --\n\n"""
msg += original_trace
raise Exception(msg)
def wait_and_validate(args, device_id):
timestep = 0
if (args.test_all):
print("In here!")
cp_files = sorted(glob.glob(os.path.join(args.model_path, 'model_step_*.pt')))
cp_files.sort(key=os.path.getmtime)
print("Cp files", cp_files)
xent_lst = []
for i, cp in enumerate(cp_files):
step = int(cp.split('.')[-2].split('_')[-1])
xent = validate(args, device_id, cp, step)
xent_lst.append((xent, cp))
max_step = xent_lst.index(min(xent_lst))
if (i - max_step > 10):
break
xent_lst = sorted(xent_lst, key=lambda x: x[0])[:3]
logger.info('PPL %s' % str(xent_lst))
for xent, cp in xent_lst:
step = int(cp.split('.')[-2].split('_')[-1])
test(args, device_id, cp, step)
else:
while (True):
cp_files = sorted(glob.glob(os.path.join(args.model_path, 'model_step_*.pt')))
cp_files.sort(key=os.path.getmtime)
if (cp_files):
cp = cp_files[-1]
time_of_cp = os.path.getmtime(cp)
if (not os.path.getsize(cp) > 0):
time.sleep(60)
continue
if (time_of_cp > timestep):
timestep = time_of_cp
step = int(cp.split('.')[-2].split('_')[-1])
validate(args, device_id, cp, step)
test(args, device_id, cp, step)
cp_files = sorted(glob.glob(os.path.join(args.model_path, 'model_step_*.pt')))
cp_files.sort(key=os.path.getmtime)
if (cp_files):
cp = cp_files[-1]
time_of_cp = os.path.getmtime(cp)
if (time_of_cp > timestep):
continue
else:
time.sleep(300)
def validate(args, device_id, pt, step):
device = "cpu" if args.visible_gpus == '-1' else "cuda"
if (pt != ''):
test_from = pt
else:
test_from = args.test_from
logger.info('Loading checkpoint from %s' % test_from)
checkpoint = torch.load(test_from, map_location=lambda storage, loc: storage)
opt = vars(checkpoint['opt'])
for k in opt.keys():
if (k in model_flags):
setattr(args, k, opt[k])
print(args)
config = BertConfig.from_json_file(args.bert_config_path)
model = Summarizer(args, device, load_pretrained_bert=False, bert_config = config)
model.load_cp(checkpoint)
model.eval()
valid_iter =data_loader.Dataloader(args, load_dataset(args, 'valid', shuffle=False),
args.batch_size, device,
shuffle=False, is_test=False)
trainer = build_trainer(args, device_id, model, None)
stats = trainer.validate(valid_iter, step)
print("Stats: {}".format(stats.xent()))
return stats.xent()
def test(args, device_id, pt, step):
device = "cpu" if args.visible_gpus == '-1' else "cuda"
if (pt != ''):
test_from = pt
else:
test_from = args.test_from
logger.info('Loading checkpoint from %s' % test_from)
checkpoint = torch.load(test_from, map_location=lambda storage, loc: storage)
opt = vars(checkpoint['opt'])
for k in opt.keys():
if (k in model_flags):
setattr(args, k, opt[k])
print(args)
config = BertConfig.from_json_file(args.bert_config_path)
model = Summarizer(args, device, load_pretrained_bert=False, bert_config = config)
model.load_cp(checkpoint)
model.eval()
test_iter =data_loader.Dataloader(args, load_dataset(args, 'test', shuffle=False),
args.batch_size, device,
shuffle=False, is_test=True)
trainer = build_trainer(args, device_id, model, None)
trainer.test(test_iter,step)
def baseline(args, cal_lead=False, cal_oracle=False):
test_iter =data_loader.Dataloader(args, load_dataset(args, 'test', shuffle=False),
args.batch_size, device,
shuffle=False, is_test=True)
trainer = build_trainer(args, device_id, None, None)
if (cal_lead):
trainer.test(test_iter, 0, cal_lead=True)
elif (cal_oracle):
trainer.test(test_iter, 0, cal_oracle=True)
def train(args, device_id):
init_logger(args.log_file)
device = "cpu" if args.visible_gpus == '-1' else "cuda"
logger.info('Device ID %d' % device_id)
logger.info('Device %s' % device)
torch.manual_seed(args.seed)
random.seed(args.seed)
torch.backends.cudnn.deterministic = True
if device_id >= 0:
torch.cuda.set_device(device_id)
torch.cuda.manual_seed(args.seed)
torch.manual_seed(args.seed)
random.seed(args.seed)
torch.backends.cudnn.deterministic = True
def train_iter_fct():
return data_loader.Dataloader(args, load_dataset(args, 'train', shuffle=True), args.batch_size, device,
shuffle=True, is_test=False)
model = Summarizer(args, device, load_pretrained_bert=True)
if args.train_from != '':
logger.info('Loading checkpoint from %s' % args.train_from)
checkpoint = torch.load(args.train_from,
map_location=lambda storage, loc: storage)
opt = vars(checkpoint['opt'])
for k in opt.keys():
if (k in model_flags):
setattr(args, k, opt[k])
model.load_cp(checkpoint)
optim = model_builder.build_optim(args, model, checkpoint)
else:
optim = model_builder.build_optim(args, model, None)
logger.info(model)
trainer = build_trainer(args, device_id, model, optim)
losses, n_docs = trainer.train(train_iter_fct, args.train_steps)
save_pickle(losses, 'losses_classifier')
save_pickle(n_docs, 'docs_classifier')
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-encoder", default='classifier', type=str, choices=['classifier','transformer','rnn','baseline', 'classifierDummy', 'gnn'])
parser.add_argument("-mode", default='train', type=str, choices=['train','validate','test'])
parser.add_argument("-bert_data_path", default='../bert_data/cnndm')
parser.add_argument("-model_path", default='../models/')
parser.add_argument("-result_path", default='../results/cnndm')
parser.add_argument("-temp_dir", default='../temp')
parser.add_argument("-bert_config_path", default='../bert_config_uncased_base.json')
parser.add_argument("-batch_size", default=1000, type=int)
parser.add_argument("-use_interval", type=str2bool, nargs='?',const=True,default=True)
parser.add_argument("-hidden_size", default=128, type=int)
parser.add_argument("-ff_size", default=512, type=int)
parser.add_argument("-heads", default=4, type=int)
parser.add_argument("-inter_layers", default=2, type=int)
parser.add_argument("-rnn_size", default=512, type=int)
parser.add_argument("-param_init", default=0, type=float)
parser.add_argument("-param_init_glorot", type=str2bool, nargs='?',const=True,default=True)
parser.add_argument("-dropout", default=0.1, type=float)
parser.add_argument("-optim", default='adam', type=str)
parser.add_argument("-lr", default=1, type=float)
parser.add_argument("-beta1", default= 0.9, type=float)
parser.add_argument("-beta2", default=0.999, type=float)
parser.add_argument("-decay_method", default='', type=str)
parser.add_argument("-warmup_steps", default=8000, type=int)
parser.add_argument("-max_grad_norm", default=0, type=float)
parser.add_argument("-save_checkpoint_steps", default=5, type=int)
parser.add_argument("-accum_count", default=1, type=int)
parser.add_argument("-world_size", default=1, type=int)
parser.add_argument("-report_every", default=1, type=int)
parser.add_argument("-train_steps", default=1000, type=int)
parser.add_argument("-recall_eval", type=str2bool, nargs='?',const=True,default=False)
parser.add_argument('-visible_gpus', default='-1', type=str)
parser.add_argument('-gpu_ranks', default='0', type=str)
parser.add_argument('-log_file', default='../logs/cnndm.log')
parser.add_argument('-dataset', default='')
parser.add_argument('-seed', default=666, type=int)
parser.add_argument("-test_all", type=str2bool, nargs='?',const=True,default=False)
parser.add_argument("-test_from", default='')
parser.add_argument("-train_from", default='')
parser.add_argument("-report_rouge", type=str2bool, nargs='?',const=True,default=True)
parser.add_argument("-block_trigram", type=str2bool, nargs='?', const=True, default=True)
args = parser.parse_args()
args.gpu_ranks = [int(i) for i in args.gpu_ranks.split(',')]
os.environ["CUDA_VISIBLE_DEVICES"] = args.visible_gpus
init_logger(args.log_file)
device = "cpu" if args.visible_gpus == '-1' else "cuda"
device_id = 0 if device == "cuda" else -1
if(args.world_size>1):
multi_main(args)
elif (args.mode == 'train'):
train(args, device_id)
elif (args.mode == 'validate'):
wait_and_validate(args, device_id)
elif (args.mode == 'lead'):
baseline(args, cal_lead=True)
elif (args.mode == 'oracle'):
baseline(args, cal_oracle=True)
elif (args.mode == 'test'):
cp = args.test_from
try:
step = int(cp.split('.')[-2].split('_')[-1])
except:
step = 0
test(args, device_id, cp, step)
| true | true |
f7f940cd5dd89ae570d03c068b44b22dfe6b1f45 | 7,344 | py | Python | app/modules/ui_functions/functions.py | SurfonL/Crest | 5f457e9d2290e52b3a6f70f6abc0c29e07c11e78 | [
"MIT"
] | null | null | null | app/modules/ui_functions/functions.py | SurfonL/Crest | 5f457e9d2290e52b3a6f70f6abc0c29e07c11e78 | [
"MIT"
] | null | null | null | app/modules/ui_functions/functions.py | SurfonL/Crest | 5f457e9d2290e52b3a6f70f6abc0c29e07c11e78 | [
"MIT"
] | null | null | null | # ///////////////////////////////////////////////////////////////
#
# BY: WANDERSON M.PIMENTA
# PROJECT MADE WITH: Qt Designer and PySide6
# V: 1.0.0
#
# This project can be used freely for all uses, as long as they maintain the
# respective credits only in the Python scripts, any information in the visual
# interface (GUI) can be modified without any implication.
#
# There are limitations on Qt licenses if you want to use your products
# commercially, I recommend reading them on the official website:
# https://doc.qt.io/qtforpython/licenses.html
#
# ///////////////////////////////////////////////////////////////
# IMPORT
# ///////////////////////////////////////////////////////////////
# Packages
from app.packages.pyside_or_pyqt import *
from app.packages.widgets import *
# GUI
from app.uis.main_window.ui_main import Ui_MainWindow # MainWindow
from app.modules.app_settings.settings import *
# GLOBAL VARS
# ///////////////////////////////////////////////////////////////
_is_maximized = False
# APP FUNCTIONS
# ///////////////////////////////////////////////////////////////
class UiFunctions:
def __init__(self):
super(UiFunctions, self).__init__()
# GET WIDGETS FROM "ui_main.py"
# Load widgets inside App Functions
# ///////////////////////////////////////////////////////////////
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
# SET UI DEFINITIONS
# Set ui definitions before "self.show()" in main.py
# ///////////////////////////////////////////////////////////////
def maximize_restore(self):
global _is_maximized
# CHANGE UI AND RESIZE GRIP
def change_ui():
if not _is_maximized:
self.resize(self.width()+1, self.height()+1)
self.ui.margins_app.setContentsMargins(10, 10, 10, 10)
self.ui.maximize_restore_app_btn.setToolTip("Restore")
self.ui.maximize_restore_app_btn.setStyleSheet("background-image: url(:/icons_svg/images/icons_svg/icon_maximize.svg);")
self.ui.bg_app.setStyleSheet("#bg_app { border-radius: 10px; border: 2px solid rgb(30, 32, 33); }")
self.left_grip.show()
self.right_grip.show()
self.top_grip.show()
self.bottom_grip.show()
else:
self.ui.margins_app.setContentsMargins(0, 0, 0, 0)
self.ui.maximize_restore_app_btn.setToolTip("Restore")
self.ui.maximize_restore_app_btn.setStyleSheet("background-image: url(:/icons_svg/images/icons_svg/icon_restore.svg);")
self.ui.bg_app.setStyleSheet("#bg_app { border-radius: 0px; border: none; }")
self.left_grip.hide()
self.right_grip.hide()
self.top_grip.hide()
self.bottom_grip.hide()
# CHECK EVENT
if self.isMaximized():
_is_maximized = False
self.showNormal()
change_ui()
else:
_is_maximized = True
self.showMaximized()
change_ui()
# START CHAT SELECTION
# ///////////////////////////////////////////////////////////////
def select_chat_message(self, widget):
for w in self.ui.messages_frame.findChildren(QWidget):
if w.objectName() == widget:
w.set_active(True)
# RESET CHAT SELECTION
# ///////////////////////////////////////////////////////////////
def deselect_chat_message(self, widget):
for w in self.ui.messages_frame.findChildren(QWidget):
if w.objectName() != widget:
if hasattr(w, 'set_active'):
w.set_active(False)
# SET UI DEFINITIONS
# Set ui definitions before "self.show()" in main.py
# ///////////////////////////////////////////////////////////////
def set_ui_definitions(self):
# GET SETTINGS FROM JSON DESERIALIZED
settings = Settings()
self.settings = settings.items
# REMOVE TITLE BAR
# ///////////////////////////////////////////////////////////////
self.setWindowFlag(Qt.FramelessWindowHint)
self.setAttribute(Qt.WA_TranslucentBackground)
# MOVE WINDOW / MAXIMIZE / RESTORE
def moveWindow(event):
# IF MAXIMIZED CHANGE TO NORMAL
if self.isMaximized():
UiFunctions.maximize_restore(self)
curso_x = self.pos().x()
curso_y = event.globalPos().y() - QCursor.pos().y()
self.move(curso_x, curso_y)
# MOVE WINDOW
if event.buttons() == Qt.LeftButton:
self.move(self.pos() + event.globalPos() - self.dragPos)
self.dragPos = event.globalPos()
event.accept()
self.ui.logo_top.mouseMoveEvent = moveWindow
self.ui.title_bar.mouseMoveEvent = moveWindow
self.ui.pomo_title_bar.mouseMoveEvent = moveWindow
# DOUBLE CLICK MAXIMIZE / RESTORE
def maximize_restore(event):
if event.type() == QEvent.MouseButtonDblClick:
UiFunctions.maximize_restore(self)
self.ui.title_bar.mouseDoubleClickEvent = maximize_restore
self.ui.pomo_title_bar.mouseDoubleClickEvent = maximize_restore
# TOP BTNS
def minimize_hide():
self.showMinimized()
self.setWindowFlags(Qt.FramelessWindowHint)
self.ui.minimize_app_btn.clicked.connect(lambda: minimize_hide())
self.ui.minimize_app_btn_2.clicked.connect(lambda: minimize_hide())
self.ui.maximize_restore_app_btn.clicked.connect(lambda: UiFunctions.maximize_restore(self))
self.ui.maximize_restore_app_btn_2.clicked.connect(lambda: UiFunctions.maximize_restore(self))
self.ui.close_app_btn.clicked.connect(lambda: self.close())
self.ui.close_app_btn_2.clicked.connect(lambda: self.close())
# DEFAULT PARAMETERS
self.setWindowTitle(self.settings["app_name"])
self.resize(self.settings["startup_size"][0], self.settings["startup_size"][1])
self.setMinimumSize(self.settings["minimum_size"][0], self.settings["minimum_size"][1])
# APPLY DROP SHADOW
self.shadow = QGraphicsDropShadowEffect()
self.shadow.setBlurRadius(25)
self.shadow.setXOffset(0)
self.shadow.setYOffset(0)
self.shadow.setColor(QColor(0, 0, 0, 80))
self.ui.stylesheet.setGraphicsEffect(self.shadow)
# CUSTOM GRIPS
# Create grips to resize window
self.left_grip = CustomGrip(self, Qt.LeftEdge, True)
self.right_grip = CustomGrip(self, Qt.RightEdge, True)
self.top_grip = CustomGrip(self, Qt.TopEdge, True)
self.bottom_grip = CustomGrip(self, Qt.BottomEdge, True)
# RESIZE GRIPS
# This function should be called whenever "MainWindow/main.py" has its window resized.
# ///////////////////////////////////////////////////////////////
def resize_grips(self):
self.left_grip.setGeometry(0, 10, 10, self.height())
self.right_grip.setGeometry(self.width() - 10, 10, 10, self.height())
self.top_grip.setGeometry(0, 0, self.width(), 10)
self.bottom_grip.setGeometry(0, self.height() - 10, self.width(), 10)
| 41.727273 | 136 | 0.565087 |
from app.packages.pyside_or_pyqt import *
from app.packages.widgets import *
from app.uis.main_window.ui_main import Ui_MainWindow
from app.modules.app_settings.settings import *
_is_maximized = False
class UiFunctions:
def __init__(self):
super(UiFunctions, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
def maximize_restore(self):
global _is_maximized
def change_ui():
if not _is_maximized:
self.resize(self.width()+1, self.height()+1)
self.ui.margins_app.setContentsMargins(10, 10, 10, 10)
self.ui.maximize_restore_app_btn.setToolTip("Restore")
self.ui.maximize_restore_app_btn.setStyleSheet("background-image: url(:/icons_svg/images/icons_svg/icon_maximize.svg);")
self.ui.bg_app.setStyleSheet("#bg_app { border-radius: 10px; border: 2px solid rgb(30, 32, 33); }")
self.left_grip.show()
self.right_grip.show()
self.top_grip.show()
self.bottom_grip.show()
else:
self.ui.margins_app.setContentsMargins(0, 0, 0, 0)
self.ui.maximize_restore_app_btn.setToolTip("Restore")
self.ui.maximize_restore_app_btn.setStyleSheet("background-image: url(:/icons_svg/images/icons_svg/icon_restore.svg);")
self.ui.bg_app.setStyleSheet("#bg_app { border-radius: 0px; border: none; }")
self.left_grip.hide()
self.right_grip.hide()
self.top_grip.hide()
self.bottom_grip.hide()
if self.isMaximized():
_is_maximized = False
self.showNormal()
change_ui()
else:
_is_maximized = True
self.showMaximized()
change_ui()
def select_chat_message(self, widget):
for w in self.ui.messages_frame.findChildren(QWidget):
if w.objectName() == widget:
w.set_active(True)
def deselect_chat_message(self, widget):
for w in self.ui.messages_frame.findChildren(QWidget):
if w.objectName() != widget:
if hasattr(w, 'set_active'):
w.set_active(False)
def set_ui_definitions(self):
settings = Settings()
self.settings = settings.items
self.setWindowFlag(Qt.FramelessWindowHint)
self.setAttribute(Qt.WA_TranslucentBackground)
def moveWindow(event):
if self.isMaximized():
UiFunctions.maximize_restore(self)
curso_x = self.pos().x()
curso_y = event.globalPos().y() - QCursor.pos().y()
self.move(curso_x, curso_y)
if event.buttons() == Qt.LeftButton:
self.move(self.pos() + event.globalPos() - self.dragPos)
self.dragPos = event.globalPos()
event.accept()
self.ui.logo_top.mouseMoveEvent = moveWindow
self.ui.title_bar.mouseMoveEvent = moveWindow
self.ui.pomo_title_bar.mouseMoveEvent = moveWindow
def maximize_restore(event):
if event.type() == QEvent.MouseButtonDblClick:
UiFunctions.maximize_restore(self)
self.ui.title_bar.mouseDoubleClickEvent = maximize_restore
self.ui.pomo_title_bar.mouseDoubleClickEvent = maximize_restore
def minimize_hide():
self.showMinimized()
self.setWindowFlags(Qt.FramelessWindowHint)
self.ui.minimize_app_btn.clicked.connect(lambda: minimize_hide())
self.ui.minimize_app_btn_2.clicked.connect(lambda: minimize_hide())
self.ui.maximize_restore_app_btn.clicked.connect(lambda: UiFunctions.maximize_restore(self))
self.ui.maximize_restore_app_btn_2.clicked.connect(lambda: UiFunctions.maximize_restore(self))
self.ui.close_app_btn.clicked.connect(lambda: self.close())
self.ui.close_app_btn_2.clicked.connect(lambda: self.close())
self.setWindowTitle(self.settings["app_name"])
self.resize(self.settings["startup_size"][0], self.settings["startup_size"][1])
self.setMinimumSize(self.settings["minimum_size"][0], self.settings["minimum_size"][1])
self.shadow = QGraphicsDropShadowEffect()
self.shadow.setBlurRadius(25)
self.shadow.setXOffset(0)
self.shadow.setYOffset(0)
self.shadow.setColor(QColor(0, 0, 0, 80))
self.ui.stylesheet.setGraphicsEffect(self.shadow)
self.left_grip = CustomGrip(self, Qt.LeftEdge, True)
self.right_grip = CustomGrip(self, Qt.RightEdge, True)
self.top_grip = CustomGrip(self, Qt.TopEdge, True)
self.bottom_grip = CustomGrip(self, Qt.BottomEdge, True)
def resize_grips(self):
self.left_grip.setGeometry(0, 10, 10, self.height())
self.right_grip.setGeometry(self.width() - 10, 10, 10, self.height())
self.top_grip.setGeometry(0, 0, self.width(), 10)
self.bottom_grip.setGeometry(0, self.height() - 10, self.width(), 10)
| true | true |
f7f942d875fe01b9d5785d51436c41ed2e79286d | 8,194 | py | Python | specutils/io/registers.py | aragilar/specutils | f3b5862fd0ea18fb9fe9973355e4169669c0675f | [
"BSD-3-Clause"
] | null | null | null | specutils/io/registers.py | aragilar/specutils | f3b5862fd0ea18fb9fe9973355e4169669c0675f | [
"BSD-3-Clause"
] | null | null | null | specutils/io/registers.py | aragilar/specutils | f3b5862fd0ea18fb9fe9973355e4169669c0675f | [
"BSD-3-Clause"
] | null | null | null | """
A module containing the mechanics of the specutils io registry.
"""
import os
import pathlib
import sys
from functools import wraps
import logging
from astropy.io import registry as io_registry
from ..spectra import Spectrum1D, SpectrumList, SpectrumCollection
__all__ = ['data_loader', 'custom_writer', 'get_loaders_by_extension', 'identify_spectrum_format']
log = logging.getLogger(__name__)
def data_loader(label, identifier=None, dtype=Spectrum1D, extensions=None,
priority=0):
"""
Wraps a function that can be added to an `~astropy.io.registry` for custom
file reading.
Parameters
----------
label : str
The label given to the function inside the registry.
identifier : func
The identified function used to verify that a file is to use a
particular file.
dtype : class
A class reference for which the data loader should be store.
extensions : list
A list of file extensions this loader supports loading from. In the
case that no identifier function is defined, but a list of file
extensions is, a simple identifier function will be created to check
for consistency with the extensions.
priority : int
Set the priority of the loader. Currently influences the sorting of the
returned loaders for a dtype.
"""
def identifier_wrapper(ident):
def wrapper(*args, **kwargs):
'''In case the identifier function raises an exception, log that and continue'''
try:
return ident(*args, **kwargs)
except Exception as e:
log.debug("Tried to read this as {} file, but could not.".format(label))
log.debug(e, exc_info=True)
return False
return wrapper
def decorator(func):
io_registry.register_reader(label, dtype, func)
if identifier is None:
# If the identifier is not defined, but the extensions are, create
# a simple identifier based off file extension.
if extensions is not None:
log.info("'{}' data loader provided for {} without "
"explicit identifier. Creating identifier using "
"list of compatible extensions".format(
label, dtype.__name__))
id_func = lambda *args, **kwargs: any([args[1].endswith(x)
for x in extensions])
# Otherwise, create a dummy identifier
else:
log.warning("'{}' data loader provided for {} without "
"explicit identifier or list of compatible "
"extensions".format(label, dtype.__name__))
id_func = lambda *args, **kwargs: True
else:
id_func = identifier_wrapper(identifier)
io_registry.register_identifier(label, dtype, id_func)
# Include the file extensions as attributes on the function object
func.extensions = extensions
# Include priority on the loader function attribute
func.priority = priority
# Sort the io_registry based on priority
sorted_loaders = sorted(io_registry._readers.items(),
key=lambda item: getattr(item[1], 'priority', 0))
# Update the registry with the sorted dictionary
io_registry._readers.clear()
io_registry._readers.update(sorted_loaders)
log.debug("Successfully loaded reader \"{}\".".format(label))
# Automatically register a SpectrumList reader for any data_loader that
# reads Spectrum1D objects. TODO: it's possible that this
# functionality should be opt-in rather than automatic.
if dtype is Spectrum1D:
def load_spectrum_list(*args, **kwargs):
return SpectrumList([ func(*args, **kwargs) ])
# Add these attributes to the SpectrumList reader as well
load_spectrum_list.extensions = extensions
load_spectrum_list.priority = priority
io_registry.register_reader(label, SpectrumList, load_spectrum_list)
io_registry.register_identifier(label, SpectrumList, id_func)
log.debug("Created SpectrumList reader for \"{}\".".format(label))
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
return decorator
def custom_writer(label, dtype=Spectrum1D):
def decorator(func):
io_registry.register_writer(label, Spectrum1D, func)
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
return decorator
def get_loaders_by_extension(extension):
"""
Retrieve a list of loader labels associated with a given extension.
Parameters
----------
extension : str
The extension for which associated loaders will be matched against.
Returns
-------
loaders : list
A list of loader names that are associated with the extension.
"""
def _registered_readers():
# With the implementation of priorities support in the astropy registry
# loaders, astropy version 4.2 and up return a tuple of ``func`` and
# ``priority``, while versions < 4.2 return just the ``func`` object.
# This function ignores priorities when calling extension loaders.
return [((fmt, cls), func[0])
if isinstance(func, tuple) else ((fmt, cls), func)
for (fmt, cls), func in io_registry._readers.items()]
return [fmt for (fmt, cls), func in _registered_readers()
if issubclass(cls, Spectrum1D) and
func.extensions is not None and
extension in func.extensions]
def _load_user_io():
# Get the path relative to the user's home directory
path = os.path.expanduser("~/.specutils")
# Import all python files from the directory if it exists
if os.path.exists(path):
for file in os.listdir(path):
if not file.endswith("py"):
continue
try:
import importlib.util as util
spec = util.spec_from_file_location(file[:-3],
os.path.join(path, file))
mod = util.module_from_spec(spec)
spec.loader.exec_module(mod)
except ImportError:
from importlib import import_module
sys.path.insert(0, path)
try:
import_module(file[:-3])
except ModuleNotFoundError: # noqa
pass
def identify_spectrum_format(filename, dtype=Spectrum1D):
""" Attempt to identify a spectrum file format
Given a filename, attempts to identify a valid file format
from the list of registered specutils loaders. Essentially a wrapper for
`~astropy.io.registry.identify_format` setting **origin** to ``read`` and
**data_class_required** to `~specutils.Spectrum1D`.
Parameters
----------
filename : str
A path to a file to be identified
dtype: object
class type of Spectrum1D, SpectrumList, or SpectrumCollection. Default is
Spectrum1D.
Returns
-------
valid_format : list, str
A list of valid file formats. If only one valid format found, returns
just that element.
"""
# check for valid string input
if not isinstance(filename, (str, pathlib.Path)) or not os.path.isfile(filename):
raise ValueError(f'{filename} is not a valid string path to a file')
# check for proper class type
assert dtype in \
[Spectrum1D, SpectrumList, SpectrumCollection], \
'dtype class must be either Spectrum1D, SpectrumList, or SpectrumCollection'
# identify the file format
valid_format = io_registry.identify_format(
'read', dtype, filename, None, {}, {})
if valid_format and len(valid_format) == 1:
return valid_format[0]
return valid_format
| 36.580357 | 98 | 0.619722 | import os
import pathlib
import sys
from functools import wraps
import logging
from astropy.io import registry as io_registry
from ..spectra import Spectrum1D, SpectrumList, SpectrumCollection
__all__ = ['data_loader', 'custom_writer', 'get_loaders_by_extension', 'identify_spectrum_format']
log = logging.getLogger(__name__)
def data_loader(label, identifier=None, dtype=Spectrum1D, extensions=None,
priority=0):
def identifier_wrapper(ident):
def wrapper(*args, **kwargs):
try:
return ident(*args, **kwargs)
except Exception as e:
log.debug("Tried to read this as {} file, but could not.".format(label))
log.debug(e, exc_info=True)
return False
return wrapper
def decorator(func):
io_registry.register_reader(label, dtype, func)
if identifier is None:
if extensions is not None:
log.info("'{}' data loader provided for {} without "
"explicit identifier. Creating identifier using "
"list of compatible extensions".format(
label, dtype.__name__))
id_func = lambda *args, **kwargs: any([args[1].endswith(x)
for x in extensions])
else:
log.warning("'{}' data loader provided for {} without "
"explicit identifier or list of compatible "
"extensions".format(label, dtype.__name__))
id_func = lambda *args, **kwargs: True
else:
id_func = identifier_wrapper(identifier)
io_registry.register_identifier(label, dtype, id_func)
func.extensions = extensions
func.priority = priority
sorted_loaders = sorted(io_registry._readers.items(),
key=lambda item: getattr(item[1], 'priority', 0))
io_registry._readers.clear()
io_registry._readers.update(sorted_loaders)
log.debug("Successfully loaded reader \"{}\".".format(label))
# functionality should be opt-in rather than automatic.
if dtype is Spectrum1D:
def load_spectrum_list(*args, **kwargs):
return SpectrumList([ func(*args, **kwargs) ])
# Add these attributes to the SpectrumList reader as well
load_spectrum_list.extensions = extensions
load_spectrum_list.priority = priority
io_registry.register_reader(label, SpectrumList, load_spectrum_list)
io_registry.register_identifier(label, SpectrumList, id_func)
log.debug("Created SpectrumList reader for \"{}\".".format(label))
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
return decorator
def custom_writer(label, dtype=Spectrum1D):
def decorator(func):
io_registry.register_writer(label, Spectrum1D, func)
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
return decorator
def get_loaders_by_extension(extension):
def _registered_readers():
# With the implementation of priorities support in the astropy registry
# loaders, astropy version 4.2 and up return a tuple of ``func`` and
# ``priority``, while versions < 4.2 return just the ``func`` object.
# This function ignores priorities when calling extension loaders.
return [((fmt, cls), func[0])
if isinstance(func, tuple) else ((fmt, cls), func)
for (fmt, cls), func in io_registry._readers.items()]
return [fmt for (fmt, cls), func in _registered_readers()
if issubclass(cls, Spectrum1D) and
func.extensions is not None and
extension in func.extensions]
def _load_user_io():
# Get the path relative to the user's home directory
path = os.path.expanduser("~/.specutils")
if os.path.exists(path):
for file in os.listdir(path):
if not file.endswith("py"):
continue
try:
import importlib.util as util
spec = util.spec_from_file_location(file[:-3],
os.path.join(path, file))
mod = util.module_from_spec(spec)
spec.loader.exec_module(mod)
except ImportError:
from importlib import import_module
sys.path.insert(0, path)
try:
import_module(file[:-3])
except ModuleNotFoundError:
pass
def identify_spectrum_format(filename, dtype=Spectrum1D):
if not isinstance(filename, (str, pathlib.Path)) or not os.path.isfile(filename):
raise ValueError(f'{filename} is not a valid string path to a file')
assert dtype in \
[Spectrum1D, SpectrumList, SpectrumCollection], \
'dtype class must be either Spectrum1D, SpectrumList, or SpectrumCollection'
valid_format = io_registry.identify_format(
'read', dtype, filename, None, {}, {})
if valid_format and len(valid_format) == 1:
return valid_format[0]
return valid_format
| true | true |
f7f9439c7b0c7375a65ae91f38df3d64c0a1d626 | 6,056 | py | Python | tests/libtests/feassemble/data/obsolete/feutils.py | Grant-Block/pylith | f6338261b17551eba879da998a5aaf2d91f5f658 | [
"MIT"
] | 93 | 2015-01-08T16:41:22.000Z | 2022-02-25T13:40:02.000Z | tests/libtests/feassemble/data/obsolete/feutils.py | Grant-Block/pylith | f6338261b17551eba879da998a5aaf2d91f5f658 | [
"MIT"
] | 277 | 2015-02-20T16:27:35.000Z | 2022-03-30T21:13:09.000Z | tests/libtests/feassemble/data/obsolete/feutils.py | Grant-Block/pylith | f6338261b17551eba879da998a5aaf2d91f5f658 | [
"MIT"
] | 71 | 2015-03-24T12:11:08.000Z | 2022-03-03T04:26:02.000Z | #!/usr/bin/env python
#
# ----------------------------------------------------------------------
#
# Brad T. Aagaard, U.S. Geological Survey
# Charles A. Williams, GNS Science
# Matthew G. Knepley, University of Chicago
#
# This code was developed as part of the Computational Infrastructure
# for Geodynamics (http://geodynamics.org).
#
# Copyright (c) 2010-2017 University of California, Davis
#
# See COPYING for license information.
#
# ----------------------------------------------------------------------
#
## @file tests/libtests/feassemble/data/feutils.py
## @brief Python routines for doing simple finite-element related
## calculations.
import numpy
# ----------------------------------------------------------------------
def calculateJacobian(quadrature, vertices):
"""
Calculate jacobian, its determinant, and its inverse at quadrature
points for a given cell.
@param quadrature Quadrature information
@param vertices Coordinates of cell's vertices
"""
(basis, basisDerivRef) = quadrature.calculateBasis()
numQuadPts = quadrature.numQuadPts
cellDim = quadrature.cellDim
spaceDim = quadrature.spaceDim
numBasis = quadrature.numBasis
jacobian = numpy.zeros( (numQuadPts, spaceDim, cellDim),
dtype=numpy.float64)
jacobianInv = numpy.zeros( (numQuadPts, cellDim, spaceDim),
dtype=numpy.float64)
jacobianDet = numpy.zeros( (numQuadPts,), dtype=numpy.float64)
basisDeriv = numpy.zeros( (numQuadPts, numBasis, spaceDim),
dtype=numpy.float64)
iQuad = 0
for q in quadrature.quadPtsRef:
# Jacobian at quadrature points
deriv = basisDerivRef[iQuad]
j = numpy.dot(vertices.transpose(), deriv)
jacobian[iQuad] = j
# Determinant of Jacobian and Jacobian inverse at quadrature points
if spaceDim == cellDim:
jacobianDet[iQuad] = numpy.linalg.det(j)
jacobianInv[iQuad] = numpy.linalg.inv(j)
else:
det = numpy.linalg.det(numpy.dot(j.transpose(), j))**0.5
jacobianDet[iQuad] = det
if 1 == quadrature.cellDim:
jacobianInv[iQuad] = 1.0 / j.transpose()
elif 2 == quadrature.cellDim:
minJacobian = 1.0e-06
jj01 = j[[0,1],:]
jj12 = j[[1,2],:]
jj02 = j[[0,2],:]
det01 = numpy.linalg.det(jj01)
det12 = numpy.linalg.det(jj12)
det02 = numpy.linalg.det(jj02)
if abs(det01) > minJacobian:
ij01 = numpy.linalg.inv(jj01)
if abs(det12) > minJacobian:
ij12 = numpy.linalg.inv(jj12)
jacobianInv[iQuad] = numpy.array([ [ij01[0,0], ij01[0,1], ij12[0,1]],
[ij01[1,0], ij01[1,1], ij12[1,1]] ],
dtype=numpy.float64)
elif abs(det02) > minJacobian:
ij02 = numpy.linalg.inv(jj02)
jacobianInv[iQuad] = numpy.array([ [ij01[0,0], ij01[0,0], ij02[0,1]],
[ij01[1,0], ij11[1,1], ij02[1,1]] ],
dtype=numpy.float64)
else:
jacobianInv[iQuad] = numpy.array([ [ij01[0,0], ij01[0,1], 0.0],
[ij01[1,0], ij01[1,1], 0.0] ],
dtype=numpy.float64)
elif abs(det02) > minJacobian:
ij02 = numpy.linalg.inv(jj02)
if abs(det12) > minJacobian:
ij12 = numpy.linalg.inv(jj12)
jacobianInv[iQuad] = numpy.array([ [ij02[0,0], ij12[0,0], ij02[0,1]],
[ij02[1,0], ij12[1,0], ij02[1,1]] ],
dtype=numpy.float64)
else:
jacobianInv[iQuad] = numpy.array([ [ij02[0,0], 0.0, ij02[0,1]],
[ij02[1,0], 0.0, ij02[1,1]] ],
dtype=numpy.float64)
elif abs(det12) > minJacobian:
ij12 = numpy.linalg.inv(jj12)
jacobianInv[iQuad] = numpy.array([ [0.0, ij12[0,0], ij12[0,1]],
[0.0, ij12[1,0], ij12[1,1]] ],
dtype=numpy.float64)
else:
raise ValueError("Could not find inverse of Jacobian.")
else:
raise ValueError("Could not find inverse of Jacobian.")
# Compute derivatives of basis functions with respect to global
# coordinates using derivatives of basis functions with respect
# to local cell coordinates and inverse of Jacobian matrix
for iBasis in xrange(numBasis):
matBasis = numpy.array(basisDerivRef[iQuad,iBasis], dtype=numpy.float64)
jInv = jacobianInv[iQuad]
basisDeriv[iQuad,iBasis,:] = numpy.dot(matBasis, jInv)
iQuad += 1
return (jacobian, jacobianInv, jacobianDet, basisDeriv)
# ----------------------------------------------------------------------
def assembleMat(globalMat, cellMat, cell, fiberDim):
"""
Assemble cell matrix into global matrix.
"""
(nrows, ncols) = cellMat.shape
for iR in xrange(nrows/fiberDim):
ibeginL = iR * fiberDim
iendL = ibeginL + fiberDim
ibeginG = cell[iR] * fiberDim
iendG = ibeginG + fiberDim
for iC in xrange(ncols/fiberDim):
jbeginL = iC * fiberDim
jendL = jbeginL + fiberDim
jbeginG = cell[iC] * fiberDim
jendG = jbeginG + fiberDim
globalMat[ibeginG:iendG, jbeginG:jendG] += cellMat[ibeginL:iendL,
jbeginL:jendL]
return
# ----------------------------------------------------------------------
def assembleVec(globalVec, cellVec, cell, fiberDim):
"""
Assemble cell vector into global vector.
"""
(nrows,) = cellVec.shape
for iR in xrange(nrows/fiberDim):
ibeginL = iR * fiberDim
iendL = ibeginL + fiberDim
ibeginG = cell[iR] * fiberDim
iendG = ibeginG + fiberDim
globalVec[ibeginG:iendG] += cellVec[ibeginL:iendL]
return
# End of file
| 38.08805 | 83 | 0.537318 |
adPts = quadrature.numQuadPts
cellDim = quadrature.cellDim
spaceDim = quadrature.spaceDim
numBasis = quadrature.numBasis
jacobian = numpy.zeros( (numQuadPts, spaceDim, cellDim),
dtype=numpy.float64)
jacobianInv = numpy.zeros( (numQuadPts, cellDim, spaceDim),
dtype=numpy.float64)
jacobianDet = numpy.zeros( (numQuadPts,), dtype=numpy.float64)
basisDeriv = numpy.zeros( (numQuadPts, numBasis, spaceDim),
dtype=numpy.float64)
iQuad = 0
for q in quadrature.quadPtsRef:
deriv = basisDerivRef[iQuad]
j = numpy.dot(vertices.transpose(), deriv)
jacobian[iQuad] = j
if spaceDim == cellDim:
jacobianDet[iQuad] = numpy.linalg.det(j)
jacobianInv[iQuad] = numpy.linalg.inv(j)
else:
det = numpy.linalg.det(numpy.dot(j.transpose(), j))**0.5
jacobianDet[iQuad] = det
if 1 == quadrature.cellDim:
jacobianInv[iQuad] = 1.0 / j.transpose()
elif 2 == quadrature.cellDim:
minJacobian = 1.0e-06
jj01 = j[[0,1],:]
jj12 = j[[1,2],:]
jj02 = j[[0,2],:]
det01 = numpy.linalg.det(jj01)
det12 = numpy.linalg.det(jj12)
det02 = numpy.linalg.det(jj02)
if abs(det01) > minJacobian:
ij01 = numpy.linalg.inv(jj01)
if abs(det12) > minJacobian:
ij12 = numpy.linalg.inv(jj12)
jacobianInv[iQuad] = numpy.array([ [ij01[0,0], ij01[0,1], ij12[0,1]],
[ij01[1,0], ij01[1,1], ij12[1,1]] ],
dtype=numpy.float64)
elif abs(det02) > minJacobian:
ij02 = numpy.linalg.inv(jj02)
jacobianInv[iQuad] = numpy.array([ [ij01[0,0], ij01[0,0], ij02[0,1]],
[ij01[1,0], ij11[1,1], ij02[1,1]] ],
dtype=numpy.float64)
else:
jacobianInv[iQuad] = numpy.array([ [ij01[0,0], ij01[0,1], 0.0],
[ij01[1,0], ij01[1,1], 0.0] ],
dtype=numpy.float64)
elif abs(det02) > minJacobian:
ij02 = numpy.linalg.inv(jj02)
if abs(det12) > minJacobian:
ij12 = numpy.linalg.inv(jj12)
jacobianInv[iQuad] = numpy.array([ [ij02[0,0], ij12[0,0], ij02[0,1]],
[ij02[1,0], ij12[1,0], ij02[1,1]] ],
dtype=numpy.float64)
else:
jacobianInv[iQuad] = numpy.array([ [ij02[0,0], 0.0, ij02[0,1]],
[ij02[1,0], 0.0, ij02[1,1]] ],
dtype=numpy.float64)
elif abs(det12) > minJacobian:
ij12 = numpy.linalg.inv(jj12)
jacobianInv[iQuad] = numpy.array([ [0.0, ij12[0,0], ij12[0,1]],
[0.0, ij12[1,0], ij12[1,1]] ],
dtype=numpy.float64)
else:
raise ValueError("Could not find inverse of Jacobian.")
else:
raise ValueError("Could not find inverse of Jacobian.")
for iBasis in xrange(numBasis):
matBasis = numpy.array(basisDerivRef[iQuad,iBasis], dtype=numpy.float64)
jInv = jacobianInv[iQuad]
basisDeriv[iQuad,iBasis,:] = numpy.dot(matBasis, jInv)
iQuad += 1
return (jacobian, jacobianInv, jacobianDet, basisDeriv)
def assembleMat(globalMat, cellMat, cell, fiberDim):
(nrows, ncols) = cellMat.shape
for iR in xrange(nrows/fiberDim):
ibeginL = iR * fiberDim
iendL = ibeginL + fiberDim
ibeginG = cell[iR] * fiberDim
iendG = ibeginG + fiberDim
for iC in xrange(ncols/fiberDim):
jbeginL = iC * fiberDim
jendL = jbeginL + fiberDim
jbeginG = cell[iC] * fiberDim
jendG = jbeginG + fiberDim
globalMat[ibeginG:iendG, jbeginG:jendG] += cellMat[ibeginL:iendL,
jbeginL:jendL]
return
def assembleVec(globalVec, cellVec, cell, fiberDim):
(nrows,) = cellVec.shape
for iR in xrange(nrows/fiberDim):
ibeginL = iR * fiberDim
iendL = ibeginL + fiberDim
ibeginG = cell[iR] * fiberDim
iendG = ibeginG + fiberDim
globalVec[ibeginG:iendG] += cellVec[ibeginL:iendL]
return
| true | true |
f7f943f22faaa0fb7ddc145d36a51a8a2f138736 | 12,870 | py | Python | utils/video_renderer.py | truongnhat-ryo/fsgan | 6d074c553a4b2d4ea8c4bc586e25f13486e2301b | [
"CC0-1.0"
] | null | null | null | utils/video_renderer.py | truongnhat-ryo/fsgan | 6d074c553a4b2d4ea8c4bc586e25f13486e2301b | [
"CC0-1.0"
] | null | null | null | utils/video_renderer.py | truongnhat-ryo/fsgan | 6d074c553a4b2d4ea8c4bc586e25f13486e2301b | [
"CC0-1.0"
] | null | null | null | import numpy as np
import cv2
import torch
import torch.multiprocessing as mp
from fsgan.utils.img_utils import tensor2bgr
from fsgan.utils.bbox_utils import crop2img, scale_bbox, crop2img_smooth_version
from fsgan.face_enhance.retinaface.retinaface_detection import RetinaFaceDetection
from fsgan.face_enhance.face_model.face_gan import FaceGAN
from fsgan.face_enhance.align_faces import warp_and_crop_face, get_reference_facial_points
from skimage import transform as tf
class FaceEnhancement(object):
def __init__(self, base_dir='/home/nhattruong/Project/FS/fsgan/face_enhance', size=512, model=None, channel_multiplier=2):
self.facedetector = RetinaFaceDetection(base_dir)
self.facegan = FaceGAN(base_dir, size, model, channel_multiplier)
self.size = size
self.threshold = 0.9
# the mask for pasting restored faces back
self.mask = np.zeros((512, 512), np.float32)
cv2.rectangle(self.mask, (26, 26), (486, 486), (1, 1, 1), -1, cv2.LINE_AA)
self.mask = cv2.GaussianBlur(self.mask, (101, 101), 11)
self.mask = cv2.GaussianBlur(self.mask, (101, 101), 11)
self.kernel = np.array((
[0.0625, 0.125, 0.0625],
[0.125, 0.25, 0.125],
[0.0625, 0.125, 0.0625]), dtype="float32")
# get the reference 5 landmarks position in the crop settings
default_square = True
inner_padding_factor = 0.25
outer_padding = (0, 0)
self.reference_5pts = get_reference_facial_points(
(self.size, self.size), inner_padding_factor, outer_padding, default_square)
def process(self, img):
facebs, landms = self.facedetector.detect(img)
orig_faces, enhanced_faces = [], []
height, width = img.shape[:2]
full_mask = np.zeros((height, width), dtype=np.float32)
full_img = np.zeros(img.shape, dtype=np.uint8)
for i, (faceb, facial5points) in enumerate(zip(facebs, landms)):
if faceb[4]<self.threshold: continue
fh, fw = (faceb[3]-faceb[1]), (faceb[2]-faceb[0])
facial5points = np.reshape(facial5points, (2, 5))
of, tfm_inv = warp_and_crop_face(img, facial5points, reference_pts=self.reference_5pts, crop_size=(self.size, self.size))
# enhance the face
ef = self.facegan.process(of)
orig_faces.append(of)
enhanced_faces.append(ef)
tmp_mask = self.mask
tmp_mask = cv2.resize(tmp_mask, ef.shape[:2])
tmp_mask = cv2.warpAffine(tmp_mask, tfm_inv, (width, height), flags=3)
if min(fh, fw)<100: # gaussian filter for small faces
ef = cv2.filter2D(ef, -1, self.kernel)
tmp_img = cv2.warpAffine(ef, tfm_inv, (width, height), flags=3)
mask = tmp_mask - full_mask
full_mask[np.where(mask>0)] = tmp_mask[np.where(mask>0)]
full_img[np.where(mask>0)] = tmp_img[np.where(mask>0)]
full_mask = full_mask[:, :, np.newaxis]
img = cv2.convertScaleAbs(img*(1-full_mask) + full_img*full_mask)
return img, orig_faces, enhanced_faces
class VideoRenderer(mp.Process):
""" Renders input video frames to both screen and video file.
For more control on the rendering, this class should be inherited from and the on_render method overridden
with an application specific implementation.
Args:
display (bool): If True, the rendered video will be displayed on screen
verbose (int): Verbose level. Controls the amount of debug information in the rendering
verbose_size (tuple of int): The rendered frame size for verbose level other than zero (width, height)
output_crop (bool): If True, a cropped frame of size (resolution, resolution) will be rendered for
verbose level zero
resolution (int): Determines the size of cropped frames to be (resolution, resolution)
crop_scale (float): Multiplier factor to scale tight bounding boxes
encoder_codec (str): Encoder codec code
separate_process (bool): If True, the renderer will be run in a separate process
"""
def __init__(self, display=False, verbose=0, verbose_size=None, output_crop=False, resolution=256, crop_scale=1.2,
encoder_codec='avc1', separate_process=False, img2img=True):
super(VideoRenderer, self).__init__()
self._display = display
self._verbose = verbose
self._verbose_size = verbose_size
self._output_crop = output_crop
self._resolution = resolution
self._crop_scale = crop_scale
self._running = True
self._input_queue = mp.Queue()
self._reply_queue = mp.Queue()
self._fourcc = cv2.VideoWriter_fourcc(*encoder_codec)
self._separate_process = separate_process
self._in_vid = None
self._out_vid = None
self._seq = None
self._in_vid_path = None
self._total_frames = None
self._frame_count = 0
self.img2img = img2img
self.faceenhancer = FaceEnhancement(size=512, model='GPEN-512', channel_multiplier=2)
def init(self, in_vid_path, seq, out_vid_path=None, **kwargs):
""" Initialize the video render for a new video rendering job.
Args:
in_vid_path (str): Input video path
seq (Sequence): Input sequence corresponding to the input video
out_vid_path (str, optional): If specified, the rendering will be written to an output video in that path
**kwargs (dict): Additional keyword arguments that will be added as members of the class. This allows
inheriting classes to access those arguments from the new process
"""
if self._separate_process:
self._input_queue.put([in_vid_path, seq, out_vid_path, kwargs])
else:
self._init_task(in_vid_path, seq, out_vid_path, kwargs)
def write(self, out_path, *args):
""" Add tensors for rendering.
Args:
*args (tuple of torch.Tensor): The tensors for rendering
"""
if self._separate_process:
self._input_queue.put([a.cpu() for a in args])
else:
self._write_batch([a.cpu() for a in args], out_path)
def finalize(self):
if self._separate_process:
self._input_queue.put(True)
else:
self._finalize_task()
def wait_until_finished(self):
""" Wait for the video renderer to finish the current video rendering job. """
if self._separate_process:
return self._reply_queue.get()
else:
return True
def on_render(self, *args):
""" Given the input tensors this method produces a cropped rendered image.
This method should be overridden by inheriting classes to customize the rendering. By default this method
expects the first tensor to be a cropped image tensor of shape (B, 3, H, W) where B is the batch size,
H is the height of the image and W is the width of the image.
Args:
*args (tuple of torch.Tensor): The tensors for rendering
Returns:
render_bgr (np.array): The cropped rendered image
"""
return tensor2bgr(args[0])
def start(self):
if self._separate_process:
super(VideoRenderer, self).start()
def kill(self):
if self._separate_process:
super(VideoRenderer, self).kill()
def run(self):
""" Main processing loop. Intended to be executed on a separate process. """
while self._running:
task = self._input_queue.get()
# Initialize new video rendering task
if self._in_vid is None:
self._init_task(*task[:3], task[3])
continue
# Finalize task
if isinstance(task, bool):
self._finalize_task()
# Notify job is finished
self._reply_queue.put(True)
continue
# Write a batch of frames
self._write_batch(task)
def _render(self, render_bgr, full_frame_bgr=None, bbox=None, out_path=None):
if self._verbose == 0 and not self._output_crop and full_frame_bgr is not None:
# import pdb; pdb.set_trace()
render_bgr, orig_faces, enhanced_faces = self.faceenhancer.process(render_bgr)
render_bgr = crop2img_smooth_version(full_frame_bgr, render_bgr, bbox)
if self.img2img:
cv2.imwrite(out_path, render_bgr)
if self._out_vid is not None:
self._out_vid.write(render_bgr)
if self._display:
cv2.imshow('render', render_bgr)
if cv2.waitKey(1) & 0xFF == ord('q'):
self._running = False
def _init_task(self, in_vid_path, seq, out_vid_path, additional_attributes):
# print('_init_task start')
self._in_vid_path, self._seq = in_vid_path, seq
self._frame_count = 0
# Add additional arguments as members
for attr_name, attr_val in additional_attributes.items():
setattr(self, attr_name, attr_val)
# Open input video
self._in_vid = cv2.VideoCapture(self._in_vid_path)
assert self._in_vid.isOpened(), f'Failed to open video: "{self._in_vid_path}"'
in_total_frames = int(self._in_vid.get(cv2.CAP_PROP_FRAME_COUNT))
fps = self._in_vid.get(cv2.CAP_PROP_FPS)
in_vid_width = int(self._in_vid.get(cv2.CAP_PROP_FRAME_WIDTH))
in_vid_height = int(self._in_vid.get(cv2.CAP_PROP_FRAME_HEIGHT))
self._total_frames = in_total_frames if self._verbose == 0 else len(self._seq)
# print(f'Debug: initializing video: "{self._in_vid_path}", total_frames={self._total_frames}')
# Initialize output video
if out_vid_path is not None:
out_size = (in_vid_width, in_vid_height)
if self._verbose <= 0 and self._output_crop:
out_size = (self._resolution, self._resolution)
elif self._verbose_size is not None:
out_size = self._verbose_size
if not self.img2img:
self._out_vid = cv2.VideoWriter(out_vid_path, self._fourcc, fps, out_size)
# Write frames as they are until the start of the sequence
if self._verbose == 0:
for i in range(self._seq.start_index):
# Read frame
ret, frame_bgr = self._in_vid.read()
assert frame_bgr is not None, f'Failed to read frame {i} from input video: "{self._in_vid_path}"'
self._render(frame_bgr) #uncmt for video rendering
self._frame_count += 1
def _write_batch(self, tensors, out_path):
batch_size = tensors[0].shape[0]
# For each frame in the current batch of tensors
for b in range(batch_size):
# Handle full frames if output_crop was not specified
full_frame_bgr, bbox = None, None
if self._verbose == 0 and not self._output_crop:
# Read frame from input video
ret, full_frame_bgr = self._in_vid.read()
assert full_frame_bgr is not None, \
f'Failed to read frame {self._frame_count} from input video: "{self._in_vid_path}"'
# Get bounding box from sequence
det = self._seq[self._frame_count - self._seq.start_index]
bbox = np.concatenate((det[:2], det[2:] - det[:2]))
bbox = scale_bbox(bbox, self._crop_scale)
render_bgr = self.on_render(*[t[b] for t in tensors])
self._render(render_bgr, full_frame_bgr, bbox, out_path)
self._frame_count += 1
# print(f'Debug: Wrote frame: {self._frame_count}')
def _finalize_task(self):
if self._verbose == 0 and self._frame_count >= (self._seq.start_index + len(self._seq)):
for i in range(self._seq.start_index + len(self._seq), self._total_frames):
# Read frame
ret, frame_bgr = self._in_vid.read()
assert frame_bgr is not None, f'Failed to read frame {i} from input video: "{self._in_vid_path}"'
self._render(frame_bgr) #uncmt for video rendering
self._frame_count += 1
# print(f'Debug: Wrote frame: {self._frame_count}')
# if self._frame_count >= self._total_frames:
# Clean up
self._in_vid.release()
# self._out_vid.release() # uncmt for video writer
self._in_vid = None
self._out_vid = None
self._seq = None
self._in_vid_path = None
self._total_frames = None
self._frame_count = 0
| 43.187919 | 133 | 0.627972 | import numpy as np
import cv2
import torch
import torch.multiprocessing as mp
from fsgan.utils.img_utils import tensor2bgr
from fsgan.utils.bbox_utils import crop2img, scale_bbox, crop2img_smooth_version
from fsgan.face_enhance.retinaface.retinaface_detection import RetinaFaceDetection
from fsgan.face_enhance.face_model.face_gan import FaceGAN
from fsgan.face_enhance.align_faces import warp_and_crop_face, get_reference_facial_points
from skimage import transform as tf
class FaceEnhancement(object):
def __init__(self, base_dir='/home/nhattruong/Project/FS/fsgan/face_enhance', size=512, model=None, channel_multiplier=2):
self.facedetector = RetinaFaceDetection(base_dir)
self.facegan = FaceGAN(base_dir, size, model, channel_multiplier)
self.size = size
self.threshold = 0.9
self.mask = np.zeros((512, 512), np.float32)
cv2.rectangle(self.mask, (26, 26), (486, 486), (1, 1, 1), -1, cv2.LINE_AA)
self.mask = cv2.GaussianBlur(self.mask, (101, 101), 11)
self.mask = cv2.GaussianBlur(self.mask, (101, 101), 11)
self.kernel = np.array((
[0.0625, 0.125, 0.0625],
[0.125, 0.25, 0.125],
[0.0625, 0.125, 0.0625]), dtype="float32")
default_square = True
inner_padding_factor = 0.25
outer_padding = (0, 0)
self.reference_5pts = get_reference_facial_points(
(self.size, self.size), inner_padding_factor, outer_padding, default_square)
def process(self, img):
facebs, landms = self.facedetector.detect(img)
orig_faces, enhanced_faces = [], []
height, width = img.shape[:2]
full_mask = np.zeros((height, width), dtype=np.float32)
full_img = np.zeros(img.shape, dtype=np.uint8)
for i, (faceb, facial5points) in enumerate(zip(facebs, landms)):
if faceb[4]<self.threshold: continue
fh, fw = (faceb[3]-faceb[1]), (faceb[2]-faceb[0])
facial5points = np.reshape(facial5points, (2, 5))
of, tfm_inv = warp_and_crop_face(img, facial5points, reference_pts=self.reference_5pts, crop_size=(self.size, self.size))
ef = self.facegan.process(of)
orig_faces.append(of)
enhanced_faces.append(ef)
tmp_mask = self.mask
tmp_mask = cv2.resize(tmp_mask, ef.shape[:2])
tmp_mask = cv2.warpAffine(tmp_mask, tfm_inv, (width, height), flags=3)
if min(fh, fw)<100:
ef = cv2.filter2D(ef, -1, self.kernel)
tmp_img = cv2.warpAffine(ef, tfm_inv, (width, height), flags=3)
mask = tmp_mask - full_mask
full_mask[np.where(mask>0)] = tmp_mask[np.where(mask>0)]
full_img[np.where(mask>0)] = tmp_img[np.where(mask>0)]
full_mask = full_mask[:, :, np.newaxis]
img = cv2.convertScaleAbs(img*(1-full_mask) + full_img*full_mask)
return img, orig_faces, enhanced_faces
class VideoRenderer(mp.Process):
def __init__(self, display=False, verbose=0, verbose_size=None, output_crop=False, resolution=256, crop_scale=1.2,
encoder_codec='avc1', separate_process=False, img2img=True):
super(VideoRenderer, self).__init__()
self._display = display
self._verbose = verbose
self._verbose_size = verbose_size
self._output_crop = output_crop
self._resolution = resolution
self._crop_scale = crop_scale
self._running = True
self._input_queue = mp.Queue()
self._reply_queue = mp.Queue()
self._fourcc = cv2.VideoWriter_fourcc(*encoder_codec)
self._separate_process = separate_process
self._in_vid = None
self._out_vid = None
self._seq = None
self._in_vid_path = None
self._total_frames = None
self._frame_count = 0
self.img2img = img2img
self.faceenhancer = FaceEnhancement(size=512, model='GPEN-512', channel_multiplier=2)
def init(self, in_vid_path, seq, out_vid_path=None, **kwargs):
if self._separate_process:
self._input_queue.put([in_vid_path, seq, out_vid_path, kwargs])
else:
self._init_task(in_vid_path, seq, out_vid_path, kwargs)
def write(self, out_path, *args):
if self._separate_process:
self._input_queue.put([a.cpu() for a in args])
else:
self._write_batch([a.cpu() for a in args], out_path)
def finalize(self):
if self._separate_process:
self._input_queue.put(True)
else:
self._finalize_task()
def wait_until_finished(self):
if self._separate_process:
return self._reply_queue.get()
else:
return True
def on_render(self, *args):
return tensor2bgr(args[0])
def start(self):
if self._separate_process:
super(VideoRenderer, self).start()
def kill(self):
if self._separate_process:
super(VideoRenderer, self).kill()
def run(self):
while self._running:
task = self._input_queue.get()
if self._in_vid is None:
self._init_task(*task[:3], task[3])
continue
if isinstance(task, bool):
self._finalize_task()
self._reply_queue.put(True)
continue
self._write_batch(task)
def _render(self, render_bgr, full_frame_bgr=None, bbox=None, out_path=None):
if self._verbose == 0 and not self._output_crop and full_frame_bgr is not None:
render_bgr, orig_faces, enhanced_faces = self.faceenhancer.process(render_bgr)
render_bgr = crop2img_smooth_version(full_frame_bgr, render_bgr, bbox)
if self.img2img:
cv2.imwrite(out_path, render_bgr)
if self._out_vid is not None:
self._out_vid.write(render_bgr)
if self._display:
cv2.imshow('render', render_bgr)
if cv2.waitKey(1) & 0xFF == ord('q'):
self._running = False
def _init_task(self, in_vid_path, seq, out_vid_path, additional_attributes):
self._in_vid_path, self._seq = in_vid_path, seq
self._frame_count = 0
for attr_name, attr_val in additional_attributes.items():
setattr(self, attr_name, attr_val)
self._in_vid = cv2.VideoCapture(self._in_vid_path)
assert self._in_vid.isOpened(), f'Failed to open video: "{self._in_vid_path}"'
in_total_frames = int(self._in_vid.get(cv2.CAP_PROP_FRAME_COUNT))
fps = self._in_vid.get(cv2.CAP_PROP_FPS)
in_vid_width = int(self._in_vid.get(cv2.CAP_PROP_FRAME_WIDTH))
in_vid_height = int(self._in_vid.get(cv2.CAP_PROP_FRAME_HEIGHT))
self._total_frames = in_total_frames if self._verbose == 0 else len(self._seq)
if out_vid_path is not None:
out_size = (in_vid_width, in_vid_height)
if self._verbose <= 0 and self._output_crop:
out_size = (self._resolution, self._resolution)
elif self._verbose_size is not None:
out_size = self._verbose_size
if not self.img2img:
self._out_vid = cv2.VideoWriter(out_vid_path, self._fourcc, fps, out_size)
if self._verbose == 0:
for i in range(self._seq.start_index):
ret, frame_bgr = self._in_vid.read()
assert frame_bgr is not None, f'Failed to read frame {i} from input video: "{self._in_vid_path}"'
self._render(frame_bgr)
self._frame_count += 1
def _write_batch(self, tensors, out_path):
batch_size = tensors[0].shape[0]
for b in range(batch_size):
full_frame_bgr, bbox = None, None
if self._verbose == 0 and not self._output_crop:
ret, full_frame_bgr = self._in_vid.read()
assert full_frame_bgr is not None, \
f'Failed to read frame {self._frame_count} from input video: "{self._in_vid_path}"'
det = self._seq[self._frame_count - self._seq.start_index]
bbox = np.concatenate((det[:2], det[2:] - det[:2]))
bbox = scale_bbox(bbox, self._crop_scale)
render_bgr = self.on_render(*[t[b] for t in tensors])
self._render(render_bgr, full_frame_bgr, bbox, out_path)
self._frame_count += 1
def _finalize_task(self):
if self._verbose == 0 and self._frame_count >= (self._seq.start_index + len(self._seq)):
for i in range(self._seq.start_index + len(self._seq), self._total_frames):
ret, frame_bgr = self._in_vid.read()
assert frame_bgr is not None, f'Failed to read frame {i} from input video: "{self._in_vid_path}"'
self._render(frame_bgr)
self._frame_count += 1
self._in_vid.release()
None
self._out_vid = None
self._seq = None
self._in_vid_path = None
self._total_frames = None
self._frame_count = 0
| true | true |
f7f94412ee93788a4449bdd3bb4f5358d5c9bb5e | 997 | py | Python | var/spack/repos/builtin/packages/py-google-auth/package.py | RemoteConnectionManager/spack | f2967b6c16effd26ce007cf86cadbb645c574f50 | [
"ECL-2.0",
"Apache-2.0",
"MIT"
] | 2 | 2020-10-15T01:08:42.000Z | 2021-10-18T01:28:18.000Z | var/spack/repos/builtin/packages/py-google-auth/package.py | openbiox/spack | bb6ec7fb40c14b37e094a860e3625af53f633174 | [
"ECL-2.0",
"Apache-2.0",
"MIT"
] | 17 | 2018-09-20T18:32:50.000Z | 2019-12-04T16:58:12.000Z | var/spack/repos/builtin/packages/py-google-auth/package.py | openbiox/spack | bb6ec7fb40c14b37e094a860e3625af53f633174 | [
"ECL-2.0",
"Apache-2.0",
"MIT"
] | 5 | 2019-07-30T09:42:14.000Z | 2021-01-25T05:39:20.000Z | # Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyGoogleAuth(PythonPackage):
"""This library simplifies using Google's various server-to-server
authentication mechanisms to access Google APIs."""
homepage = "https://github.com/GoogleCloudPlatform/google-auth-library-python"
url = "https://pypi.io/packages/source/g/google-auth/google-auth-1.6.3.tar.gz"
version('1.6.3', sha256='0f7c6a64927d34c1a474da92cfc59e552a5d3b940d3266606c6a28b72888b9e4')
depends_on('python@2.7:2.8,3.4:', type=('build', 'run'))
depends_on('py-setuptools', type='build')
depends_on('py-pyasn1-modules@0.2.1:', type=('build', 'run'))
depends_on('py-rsa@3.1.4:', type=('build', 'run'))
depends_on('py-six@1.9.0:', type=('build', 'run'))
depends_on('py-cachetools@2.0.0:', type=('build', 'run'))
| 41.541667 | 95 | 0.7001 |
from spack import *
class PyGoogleAuth(PythonPackage):
homepage = "https://github.com/GoogleCloudPlatform/google-auth-library-python"
url = "https://pypi.io/packages/source/g/google-auth/google-auth-1.6.3.tar.gz"
version('1.6.3', sha256='0f7c6a64927d34c1a474da92cfc59e552a5d3b940d3266606c6a28b72888b9e4')
depends_on('python@2.7:2.8,3.4:', type=('build', 'run'))
depends_on('py-setuptools', type='build')
depends_on('py-pyasn1-modules@0.2.1:', type=('build', 'run'))
depends_on('py-rsa@3.1.4:', type=('build', 'run'))
depends_on('py-six@1.9.0:', type=('build', 'run'))
depends_on('py-cachetools@2.0.0:', type=('build', 'run'))
| true | true |
f7f945b2cd620314831ac01ca2aeb2da1577cb10 | 156 | py | Python | src/libsncompress/__init__.py | congma/libsncompress | ef0c8ee36b8a53b6106ade675d5210fa6e4d5409 | [
"BSD-3-Clause"
] | 1 | 2018-03-12T14:40:08.000Z | 2018-03-12T14:40:08.000Z | src/libsncompress/__init__.py | congma/libsncompress | ef0c8ee36b8a53b6106ade675d5210fa6e4d5409 | [
"BSD-3-Clause"
] | null | null | null | src/libsncompress/__init__.py | congma/libsncompress | ef0c8ee36b8a53b6106ade675d5210fa6e4d5409 | [
"BSD-3-Clause"
] | null | null | null | from .base import BinnedSN
from .binning import BinCollection
from .evaluator import CovEvaluator
__all__ = ["BinnedSN", "BinCollection", "CovEvaluator"]
| 22.285714 | 55 | 0.788462 | from .base import BinnedSN
from .binning import BinCollection
from .evaluator import CovEvaluator
__all__ = ["BinnedSN", "BinCollection", "CovEvaluator"]
| true | true |
f7f94653905413c88a1a6e46ea4abeaa4215b711 | 21,395 | py | Python | lib/googlecloudsdk/third_party/apis/tpu/v1alpha1/tpu_v1alpha1_client.py | bopopescu/Google-Cloud-SDK-1 | c4683bacb2f6192d8a816932e438a0493085469b | [
"Apache-2.0"
] | null | null | null | lib/googlecloudsdk/third_party/apis/tpu/v1alpha1/tpu_v1alpha1_client.py | bopopescu/Google-Cloud-SDK-1 | c4683bacb2f6192d8a816932e438a0493085469b | [
"Apache-2.0"
] | null | null | null | lib/googlecloudsdk/third_party/apis/tpu/v1alpha1/tpu_v1alpha1_client.py | bopopescu/Google-Cloud-SDK-1 | c4683bacb2f6192d8a816932e438a0493085469b | [
"Apache-2.0"
] | 1 | 2020-07-24T20:13:29.000Z | 2020-07-24T20:13:29.000Z | """Generated client library for tpu version v1alpha1."""
# NOTE: This file is autogenerated and should not be edited by hand.
from apitools.base.py import base_api
from googlecloudsdk.third_party.apis.tpu.v1alpha1 import tpu_v1alpha1_messages as messages
class TpuV1alpha1(base_api.BaseApiClient):
"""Generated client library for service tpu version v1alpha1."""
MESSAGES_MODULE = messages
BASE_URL = u'https://tpu.googleapis.com/'
_PACKAGE = u'tpu'
_SCOPES = [u'https://www.googleapis.com/auth/cloud-platform']
_VERSION = u'v1alpha1'
_CLIENT_ID = '1042881264118.apps.googleusercontent.com'
_CLIENT_SECRET = 'x_Tw5K8nnjoRAqULM9PFAC2b'
_USER_AGENT = 'x_Tw5K8nnjoRAqULM9PFAC2b'
_CLIENT_CLASS_NAME = u'TpuV1alpha1'
_URL_VERSION = u'v1alpha1'
_API_KEY = None
def __init__(self, url='', credentials=None,
get_credentials=True, http=None, model=None,
log_request=False, log_response=False,
credentials_args=None, default_global_params=None,
additional_http_headers=None):
"""Create a new tpu handle."""
url = url or self.BASE_URL
super(TpuV1alpha1, self).__init__(
url, credentials=credentials,
get_credentials=get_credentials, http=http, model=model,
log_request=log_request, log_response=log_response,
credentials_args=credentials_args,
default_global_params=default_global_params,
additional_http_headers=additional_http_headers)
self.projects_locations_nodes = self.ProjectsLocationsNodesService(self)
self.projects_locations_operations = self.ProjectsLocationsOperationsService(self)
self.projects_locations_tensorflowVersions = self.ProjectsLocationsTensorflowVersionsService(self)
self.projects_locations = self.ProjectsLocationsService(self)
self.projects = self.ProjectsService(self)
class ProjectsLocationsNodesService(base_api.BaseApiService):
"""Service class for the projects_locations_nodes resource."""
_NAME = u'projects_locations_nodes'
def __init__(self, client):
super(TpuV1alpha1.ProjectsLocationsNodesService, self).__init__(client)
self._upload_configs = {
}
def Create(self, request, global_params=None):
"""Creates a node.
Args:
request: (TpuProjectsLocationsNodesCreateRequest) input message
global_params: (StandardQueryParameters, default: None) global arguments
Returns:
(Operation) The response message.
"""
config = self.GetMethodConfig('Create')
return self._RunMethod(
config, request, global_params=global_params)
Create.method_config = lambda: base_api.ApiMethodInfo(
flat_path=u'v1alpha1/projects/{projectsId}/locations/{locationsId}/nodes',
http_method=u'POST',
method_id=u'tpu.projects.locations.nodes.create',
ordered_params=[u'parent'],
path_params=[u'parent'],
query_params=[u'nodeId'],
relative_path=u'v1alpha1/{+parent}/nodes',
request_field=u'node',
request_type_name=u'TpuProjectsLocationsNodesCreateRequest',
response_type_name=u'Operation',
supports_download=False,
)
def Delete(self, request, global_params=None):
"""Deletes a node.
Args:
request: (TpuProjectsLocationsNodesDeleteRequest) input message
global_params: (StandardQueryParameters, default: None) global arguments
Returns:
(Operation) The response message.
"""
config = self.GetMethodConfig('Delete')
return self._RunMethod(
config, request, global_params=global_params)
Delete.method_config = lambda: base_api.ApiMethodInfo(
flat_path=u'v1alpha1/projects/{projectsId}/locations/{locationsId}/nodes/{nodesId}',
http_method=u'DELETE',
method_id=u'tpu.projects.locations.nodes.delete',
ordered_params=[u'name'],
path_params=[u'name'],
query_params=[],
relative_path=u'v1alpha1/{+name}',
request_field='',
request_type_name=u'TpuProjectsLocationsNodesDeleteRequest',
response_type_name=u'Operation',
supports_download=False,
)
def Get(self, request, global_params=None):
"""Gets the details of a node.
Args:
request: (TpuProjectsLocationsNodesGetRequest) input message
global_params: (StandardQueryParameters, default: None) global arguments
Returns:
(Node) The response message.
"""
config = self.GetMethodConfig('Get')
return self._RunMethod(
config, request, global_params=global_params)
Get.method_config = lambda: base_api.ApiMethodInfo(
flat_path=u'v1alpha1/projects/{projectsId}/locations/{locationsId}/nodes/{nodesId}',
http_method=u'GET',
method_id=u'tpu.projects.locations.nodes.get',
ordered_params=[u'name'],
path_params=[u'name'],
query_params=[],
relative_path=u'v1alpha1/{+name}',
request_field='',
request_type_name=u'TpuProjectsLocationsNodesGetRequest',
response_type_name=u'Node',
supports_download=False,
)
def List(self, request, global_params=None):
"""Lists nodes.
Args:
request: (TpuProjectsLocationsNodesListRequest) input message
global_params: (StandardQueryParameters, default: None) global arguments
Returns:
(ListNodesResponse) The response message.
"""
config = self.GetMethodConfig('List')
return self._RunMethod(
config, request, global_params=global_params)
List.method_config = lambda: base_api.ApiMethodInfo(
flat_path=u'v1alpha1/projects/{projectsId}/locations/{locationsId}/nodes',
http_method=u'GET',
method_id=u'tpu.projects.locations.nodes.list',
ordered_params=[u'parent'],
path_params=[u'parent'],
query_params=[u'pageSize', u'pageToken'],
relative_path=u'v1alpha1/{+parent}/nodes',
request_field='',
request_type_name=u'TpuProjectsLocationsNodesListRequest',
response_type_name=u'ListNodesResponse',
supports_download=False,
)
def Reimage(self, request, global_params=None):
"""Reimage a node's OS.
Args:
request: (TpuProjectsLocationsNodesReimageRequest) input message
global_params: (StandardQueryParameters, default: None) global arguments
Returns:
(Operation) The response message.
"""
config = self.GetMethodConfig('Reimage')
return self._RunMethod(
config, request, global_params=global_params)
Reimage.method_config = lambda: base_api.ApiMethodInfo(
flat_path=u'v1alpha1/projects/{projectsId}/locations/{locationsId}/nodes/{nodesId}:reimage',
http_method=u'POST',
method_id=u'tpu.projects.locations.nodes.reimage',
ordered_params=[u'name'],
path_params=[u'name'],
query_params=[],
relative_path=u'v1alpha1/{+name}:reimage',
request_field=u'reimageNodeRequest',
request_type_name=u'TpuProjectsLocationsNodesReimageRequest',
response_type_name=u'Operation',
supports_download=False,
)
def Reset(self, request, global_params=None):
"""Resets a node, which stops and starts the VM.
Args:
request: (TpuProjectsLocationsNodesResetRequest) input message
global_params: (StandardQueryParameters, default: None) global arguments
Returns:
(Operation) The response message.
"""
config = self.GetMethodConfig('Reset')
return self._RunMethod(
config, request, global_params=global_params)
Reset.method_config = lambda: base_api.ApiMethodInfo(
flat_path=u'v1alpha1/projects/{projectsId}/locations/{locationsId}/nodes/{nodesId}:reset',
http_method=u'POST',
method_id=u'tpu.projects.locations.nodes.reset',
ordered_params=[u'name'],
path_params=[u'name'],
query_params=[],
relative_path=u'v1alpha1/{+name}:reset',
request_field=u'resetNodeRequest',
request_type_name=u'TpuProjectsLocationsNodesResetRequest',
response_type_name=u'Operation',
supports_download=False,
)
def Start(self, request, global_params=None):
"""Start a node.
Args:
request: (TpuProjectsLocationsNodesStartRequest) input message
global_params: (StandardQueryParameters, default: None) global arguments
Returns:
(Operation) The response message.
"""
config = self.GetMethodConfig('Start')
return self._RunMethod(
config, request, global_params=global_params)
Start.method_config = lambda: base_api.ApiMethodInfo(
flat_path=u'v1alpha1/projects/{projectsId}/locations/{locationsId}/nodes/{nodesId}:start',
http_method=u'POST',
method_id=u'tpu.projects.locations.nodes.start',
ordered_params=[u'name'],
path_params=[u'name'],
query_params=[],
relative_path=u'v1alpha1/{+name}:start',
request_field=u'startNodeRequest',
request_type_name=u'TpuProjectsLocationsNodesStartRequest',
response_type_name=u'Operation',
supports_download=False,
)
def Stop(self, request, global_params=None):
"""Stops a node.
Args:
request: (TpuProjectsLocationsNodesStopRequest) input message
global_params: (StandardQueryParameters, default: None) global arguments
Returns:
(Operation) The response message.
"""
config = self.GetMethodConfig('Stop')
return self._RunMethod(
config, request, global_params=global_params)
Stop.method_config = lambda: base_api.ApiMethodInfo(
flat_path=u'v1alpha1/projects/{projectsId}/locations/{locationsId}/nodes/{nodesId}:stop',
http_method=u'POST',
method_id=u'tpu.projects.locations.nodes.stop',
ordered_params=[u'name'],
path_params=[u'name'],
query_params=[],
relative_path=u'v1alpha1/{+name}:stop',
request_field=u'stopNodeRequest',
request_type_name=u'TpuProjectsLocationsNodesStopRequest',
response_type_name=u'Operation',
supports_download=False,
)
class ProjectsLocationsOperationsService(base_api.BaseApiService):
"""Service class for the projects_locations_operations resource."""
_NAME = u'projects_locations_operations'
def __init__(self, client):
super(TpuV1alpha1.ProjectsLocationsOperationsService, self).__init__(client)
self._upload_configs = {
}
def Cancel(self, request, global_params=None):
"""Starts asynchronous cancellation on a long-running operation. The server.
makes a best effort to cancel the operation, but success is not
guaranteed. If the server doesn't support this method, it returns
`google.rpc.Code.UNIMPLEMENTED`. Clients can use
Operations.GetOperation or
other methods to check whether the cancellation succeeded or whether the
operation completed despite cancellation. On successful cancellation,
the operation is not deleted; instead, it becomes an operation with
an Operation.error value with a google.rpc.Status.code of 1,
corresponding to `Code.CANCELLED`.
Args:
request: (TpuProjectsLocationsOperationsCancelRequest) input message
global_params: (StandardQueryParameters, default: None) global arguments
Returns:
(Empty) The response message.
"""
config = self.GetMethodConfig('Cancel')
return self._RunMethod(
config, request, global_params=global_params)
Cancel.method_config = lambda: base_api.ApiMethodInfo(
flat_path=u'v1alpha1/projects/{projectsId}/locations/{locationsId}/operations/{operationsId}:cancel',
http_method=u'POST',
method_id=u'tpu.projects.locations.operations.cancel',
ordered_params=[u'name'],
path_params=[u'name'],
query_params=[],
relative_path=u'v1alpha1/{+name}:cancel',
request_field='',
request_type_name=u'TpuProjectsLocationsOperationsCancelRequest',
response_type_name=u'Empty',
supports_download=False,
)
def Delete(self, request, global_params=None):
"""Deletes a long-running operation. This method indicates that the client is.
no longer interested in the operation result. It does not cancel the
operation. If the server doesn't support this method, it returns
`google.rpc.Code.UNIMPLEMENTED`.
Args:
request: (TpuProjectsLocationsOperationsDeleteRequest) input message
global_params: (StandardQueryParameters, default: None) global arguments
Returns:
(Empty) The response message.
"""
config = self.GetMethodConfig('Delete')
return self._RunMethod(
config, request, global_params=global_params)
Delete.method_config = lambda: base_api.ApiMethodInfo(
flat_path=u'v1alpha1/projects/{projectsId}/locations/{locationsId}/operations/{operationsId}',
http_method=u'DELETE',
method_id=u'tpu.projects.locations.operations.delete',
ordered_params=[u'name'],
path_params=[u'name'],
query_params=[],
relative_path=u'v1alpha1/{+name}',
request_field='',
request_type_name=u'TpuProjectsLocationsOperationsDeleteRequest',
response_type_name=u'Empty',
supports_download=False,
)
def Get(self, request, global_params=None):
"""Gets the latest state of a long-running operation. Clients can use this.
method to poll the operation result at intervals as recommended by the API
service.
Args:
request: (TpuProjectsLocationsOperationsGetRequest) input message
global_params: (StandardQueryParameters, default: None) global arguments
Returns:
(Operation) The response message.
"""
config = self.GetMethodConfig('Get')
return self._RunMethod(
config, request, global_params=global_params)
Get.method_config = lambda: base_api.ApiMethodInfo(
flat_path=u'v1alpha1/projects/{projectsId}/locations/{locationsId}/operations/{operationsId}',
http_method=u'GET',
method_id=u'tpu.projects.locations.operations.get',
ordered_params=[u'name'],
path_params=[u'name'],
query_params=[],
relative_path=u'v1alpha1/{+name}',
request_field='',
request_type_name=u'TpuProjectsLocationsOperationsGetRequest',
response_type_name=u'Operation',
supports_download=False,
)
def List(self, request, global_params=None):
"""Lists operations that match the specified filter in the request. If the.
server doesn't support this method, it returns `UNIMPLEMENTED`.
NOTE: the `name` binding allows API services to override the binding
to use different resource name schemes, such as `users/*/operations`. To
override the binding, API services can add a binding such as
`"/v1/{name=users/*}/operations"` to their service configuration.
For backwards compatibility, the default name includes the operations
collection id, however overriding users must ensure the name binding
is the parent resource, without the operations collection id.
Args:
request: (TpuProjectsLocationsOperationsListRequest) input message
global_params: (StandardQueryParameters, default: None) global arguments
Returns:
(ListOperationsResponse) The response message.
"""
config = self.GetMethodConfig('List')
return self._RunMethod(
config, request, global_params=global_params)
List.method_config = lambda: base_api.ApiMethodInfo(
flat_path=u'v1alpha1/projects/{projectsId}/locations/{locationsId}/operations',
http_method=u'GET',
method_id=u'tpu.projects.locations.operations.list',
ordered_params=[u'name'],
path_params=[u'name'],
query_params=[u'filter', u'pageSize', u'pageToken'],
relative_path=u'v1alpha1/{+name}/operations',
request_field='',
request_type_name=u'TpuProjectsLocationsOperationsListRequest',
response_type_name=u'ListOperationsResponse',
supports_download=False,
)
class ProjectsLocationsTensorflowVersionsService(base_api.BaseApiService):
"""Service class for the projects_locations_tensorflowVersions resource."""
_NAME = u'projects_locations_tensorflowVersions'
def __init__(self, client):
super(TpuV1alpha1.ProjectsLocationsTensorflowVersionsService, self).__init__(client)
self._upload_configs = {
}
def Get(self, request, global_params=None):
"""Gets TensorFlow Version.
Args:
request: (TpuProjectsLocationsTensorflowVersionsGetRequest) input message
global_params: (StandardQueryParameters, default: None) global arguments
Returns:
(TensorFlowVersion) The response message.
"""
config = self.GetMethodConfig('Get')
return self._RunMethod(
config, request, global_params=global_params)
Get.method_config = lambda: base_api.ApiMethodInfo(
flat_path=u'v1alpha1/projects/{projectsId}/locations/{locationsId}/tensorflowVersions/{tensorflowVersionsId}',
http_method=u'GET',
method_id=u'tpu.projects.locations.tensorflowVersions.get',
ordered_params=[u'name'],
path_params=[u'name'],
query_params=[],
relative_path=u'v1alpha1/{+name}',
request_field='',
request_type_name=u'TpuProjectsLocationsTensorflowVersionsGetRequest',
response_type_name=u'TensorFlowVersion',
supports_download=False,
)
def List(self, request, global_params=None):
"""List TensorFlow versions.
Args:
request: (TpuProjectsLocationsTensorflowVersionsListRequest) input message
global_params: (StandardQueryParameters, default: None) global arguments
Returns:
(ListTensorFlowVersionsResponse) The response message.
"""
config = self.GetMethodConfig('List')
return self._RunMethod(
config, request, global_params=global_params)
List.method_config = lambda: base_api.ApiMethodInfo(
flat_path=u'v1alpha1/projects/{projectsId}/locations/{locationsId}/tensorflowVersions',
http_method=u'GET',
method_id=u'tpu.projects.locations.tensorflowVersions.list',
ordered_params=[u'parent'],
path_params=[u'parent'],
query_params=[u'filter', u'orderBy', u'pageSize', u'pageToken'],
relative_path=u'v1alpha1/{+parent}/tensorflowVersions',
request_field='',
request_type_name=u'TpuProjectsLocationsTensorflowVersionsListRequest',
response_type_name=u'ListTensorFlowVersionsResponse',
supports_download=False,
)
class ProjectsLocationsService(base_api.BaseApiService):
"""Service class for the projects_locations resource."""
_NAME = u'projects_locations'
def __init__(self, client):
super(TpuV1alpha1.ProjectsLocationsService, self).__init__(client)
self._upload_configs = {
}
def Get(self, request, global_params=None):
"""Get information about a location.
Args:
request: (TpuProjectsLocationsGetRequest) input message
global_params: (StandardQueryParameters, default: None) global arguments
Returns:
(Location) The response message.
"""
config = self.GetMethodConfig('Get')
return self._RunMethod(
config, request, global_params=global_params)
Get.method_config = lambda: base_api.ApiMethodInfo(
flat_path=u'v1alpha1/projects/{projectsId}/locations/{locationsId}',
http_method=u'GET',
method_id=u'tpu.projects.locations.get',
ordered_params=[u'name'],
path_params=[u'name'],
query_params=[],
relative_path=u'v1alpha1/{+name}',
request_field='',
request_type_name=u'TpuProjectsLocationsGetRequest',
response_type_name=u'Location',
supports_download=False,
)
def List(self, request, global_params=None):
"""Lists information about the supported locations for this service.
Args:
request: (TpuProjectsLocationsListRequest) input message
global_params: (StandardQueryParameters, default: None) global arguments
Returns:
(ListLocationsResponse) The response message.
"""
config = self.GetMethodConfig('List')
return self._RunMethod(
config, request, global_params=global_params)
List.method_config = lambda: base_api.ApiMethodInfo(
flat_path=u'v1alpha1/projects/{projectsId}/locations',
http_method=u'GET',
method_id=u'tpu.projects.locations.list',
ordered_params=[u'name'],
path_params=[u'name'],
query_params=[u'filter', u'pageSize', u'pageToken'],
relative_path=u'v1alpha1/{+name}/locations',
request_field='',
request_type_name=u'TpuProjectsLocationsListRequest',
response_type_name=u'ListLocationsResponse',
supports_download=False,
)
class ProjectsService(base_api.BaseApiService):
"""Service class for the projects resource."""
_NAME = u'projects'
def __init__(self, client):
super(TpuV1alpha1.ProjectsService, self).__init__(client)
self._upload_configs = {
}
| 39.113346 | 118 | 0.694882 |
from apitools.base.py import base_api
from googlecloudsdk.third_party.apis.tpu.v1alpha1 import tpu_v1alpha1_messages as messages
class TpuV1alpha1(base_api.BaseApiClient):
MESSAGES_MODULE = messages
BASE_URL = u'https://tpu.googleapis.com/'
_PACKAGE = u'tpu'
_SCOPES = [u'https://www.googleapis.com/auth/cloud-platform']
_VERSION = u'v1alpha1'
_CLIENT_ID = '1042881264118.apps.googleusercontent.com'
_CLIENT_SECRET = 'x_Tw5K8nnjoRAqULM9PFAC2b'
_USER_AGENT = 'x_Tw5K8nnjoRAqULM9PFAC2b'
_CLIENT_CLASS_NAME = u'TpuV1alpha1'
_URL_VERSION = u'v1alpha1'
_API_KEY = None
def __init__(self, url='', credentials=None,
get_credentials=True, http=None, model=None,
log_request=False, log_response=False,
credentials_args=None, default_global_params=None,
additional_http_headers=None):
url = url or self.BASE_URL
super(TpuV1alpha1, self).__init__(
url, credentials=credentials,
get_credentials=get_credentials, http=http, model=model,
log_request=log_request, log_response=log_response,
credentials_args=credentials_args,
default_global_params=default_global_params,
additional_http_headers=additional_http_headers)
self.projects_locations_nodes = self.ProjectsLocationsNodesService(self)
self.projects_locations_operations = self.ProjectsLocationsOperationsService(self)
self.projects_locations_tensorflowVersions = self.ProjectsLocationsTensorflowVersionsService(self)
self.projects_locations = self.ProjectsLocationsService(self)
self.projects = self.ProjectsService(self)
class ProjectsLocationsNodesService(base_api.BaseApiService):
_NAME = u'projects_locations_nodes'
def __init__(self, client):
super(TpuV1alpha1.ProjectsLocationsNodesService, self).__init__(client)
self._upload_configs = {
}
def Create(self, request, global_params=None):
config = self.GetMethodConfig('Create')
return self._RunMethod(
config, request, global_params=global_params)
Create.method_config = lambda: base_api.ApiMethodInfo(
flat_path=u'v1alpha1/projects/{projectsId}/locations/{locationsId}/nodes',
http_method=u'POST',
method_id=u'tpu.projects.locations.nodes.create',
ordered_params=[u'parent'],
path_params=[u'parent'],
query_params=[u'nodeId'],
relative_path=u'v1alpha1/{+parent}/nodes',
request_field=u'node',
request_type_name=u'TpuProjectsLocationsNodesCreateRequest',
response_type_name=u'Operation',
supports_download=False,
)
def Delete(self, request, global_params=None):
config = self.GetMethodConfig('Delete')
return self._RunMethod(
config, request, global_params=global_params)
Delete.method_config = lambda: base_api.ApiMethodInfo(
flat_path=u'v1alpha1/projects/{projectsId}/locations/{locationsId}/nodes/{nodesId}',
http_method=u'DELETE',
method_id=u'tpu.projects.locations.nodes.delete',
ordered_params=[u'name'],
path_params=[u'name'],
query_params=[],
relative_path=u'v1alpha1/{+name}',
request_field='',
request_type_name=u'TpuProjectsLocationsNodesDeleteRequest',
response_type_name=u'Operation',
supports_download=False,
)
def Get(self, request, global_params=None):
config = self.GetMethodConfig('Get')
return self._RunMethod(
config, request, global_params=global_params)
Get.method_config = lambda: base_api.ApiMethodInfo(
flat_path=u'v1alpha1/projects/{projectsId}/locations/{locationsId}/nodes/{nodesId}',
http_method=u'GET',
method_id=u'tpu.projects.locations.nodes.get',
ordered_params=[u'name'],
path_params=[u'name'],
query_params=[],
relative_path=u'v1alpha1/{+name}',
request_field='',
request_type_name=u'TpuProjectsLocationsNodesGetRequest',
response_type_name=u'Node',
supports_download=False,
)
def List(self, request, global_params=None):
config = self.GetMethodConfig('List')
return self._RunMethod(
config, request, global_params=global_params)
List.method_config = lambda: base_api.ApiMethodInfo(
flat_path=u'v1alpha1/projects/{projectsId}/locations/{locationsId}/nodes',
http_method=u'GET',
method_id=u'tpu.projects.locations.nodes.list',
ordered_params=[u'parent'],
path_params=[u'parent'],
query_params=[u'pageSize', u'pageToken'],
relative_path=u'v1alpha1/{+parent}/nodes',
request_field='',
request_type_name=u'TpuProjectsLocationsNodesListRequest',
response_type_name=u'ListNodesResponse',
supports_download=False,
)
def Reimage(self, request, global_params=None):
config = self.GetMethodConfig('Reimage')
return self._RunMethod(
config, request, global_params=global_params)
Reimage.method_config = lambda: base_api.ApiMethodInfo(
flat_path=u'v1alpha1/projects/{projectsId}/locations/{locationsId}/nodes/{nodesId}:reimage',
http_method=u'POST',
method_id=u'tpu.projects.locations.nodes.reimage',
ordered_params=[u'name'],
path_params=[u'name'],
query_params=[],
relative_path=u'v1alpha1/{+name}:reimage',
request_field=u'reimageNodeRequest',
request_type_name=u'TpuProjectsLocationsNodesReimageRequest',
response_type_name=u'Operation',
supports_download=False,
)
def Reset(self, request, global_params=None):
config = self.GetMethodConfig('Reset')
return self._RunMethod(
config, request, global_params=global_params)
Reset.method_config = lambda: base_api.ApiMethodInfo(
flat_path=u'v1alpha1/projects/{projectsId}/locations/{locationsId}/nodes/{nodesId}:reset',
http_method=u'POST',
method_id=u'tpu.projects.locations.nodes.reset',
ordered_params=[u'name'],
path_params=[u'name'],
query_params=[],
relative_path=u'v1alpha1/{+name}:reset',
request_field=u'resetNodeRequest',
request_type_name=u'TpuProjectsLocationsNodesResetRequest',
response_type_name=u'Operation',
supports_download=False,
)
def Start(self, request, global_params=None):
config = self.GetMethodConfig('Start')
return self._RunMethod(
config, request, global_params=global_params)
Start.method_config = lambda: base_api.ApiMethodInfo(
flat_path=u'v1alpha1/projects/{projectsId}/locations/{locationsId}/nodes/{nodesId}:start',
http_method=u'POST',
method_id=u'tpu.projects.locations.nodes.start',
ordered_params=[u'name'],
path_params=[u'name'],
query_params=[],
relative_path=u'v1alpha1/{+name}:start',
request_field=u'startNodeRequest',
request_type_name=u'TpuProjectsLocationsNodesStartRequest',
response_type_name=u'Operation',
supports_download=False,
)
def Stop(self, request, global_params=None):
config = self.GetMethodConfig('Stop')
return self._RunMethod(
config, request, global_params=global_params)
Stop.method_config = lambda: base_api.ApiMethodInfo(
flat_path=u'v1alpha1/projects/{projectsId}/locations/{locationsId}/nodes/{nodesId}:stop',
http_method=u'POST',
method_id=u'tpu.projects.locations.nodes.stop',
ordered_params=[u'name'],
path_params=[u'name'],
query_params=[],
relative_path=u'v1alpha1/{+name}:stop',
request_field=u'stopNodeRequest',
request_type_name=u'TpuProjectsLocationsNodesStopRequest',
response_type_name=u'Operation',
supports_download=False,
)
class ProjectsLocationsOperationsService(base_api.BaseApiService):
_NAME = u'projects_locations_operations'
def __init__(self, client):
super(TpuV1alpha1.ProjectsLocationsOperationsService, self).__init__(client)
self._upload_configs = {
}
def Cancel(self, request, global_params=None):
config = self.GetMethodConfig('Cancel')
return self._RunMethod(
config, request, global_params=global_params)
Cancel.method_config = lambda: base_api.ApiMethodInfo(
flat_path=u'v1alpha1/projects/{projectsId}/locations/{locationsId}/operations/{operationsId}:cancel',
http_method=u'POST',
method_id=u'tpu.projects.locations.operations.cancel',
ordered_params=[u'name'],
path_params=[u'name'],
query_params=[],
relative_path=u'v1alpha1/{+name}:cancel',
request_field='',
request_type_name=u'TpuProjectsLocationsOperationsCancelRequest',
response_type_name=u'Empty',
supports_download=False,
)
def Delete(self, request, global_params=None):
config = self.GetMethodConfig('Delete')
return self._RunMethod(
config, request, global_params=global_params)
Delete.method_config = lambda: base_api.ApiMethodInfo(
flat_path=u'v1alpha1/projects/{projectsId}/locations/{locationsId}/operations/{operationsId}',
http_method=u'DELETE',
method_id=u'tpu.projects.locations.operations.delete',
ordered_params=[u'name'],
path_params=[u'name'],
query_params=[],
relative_path=u'v1alpha1/{+name}',
request_field='',
request_type_name=u'TpuProjectsLocationsOperationsDeleteRequest',
response_type_name=u'Empty',
supports_download=False,
)
def Get(self, request, global_params=None):
config = self.GetMethodConfig('Get')
return self._RunMethod(
config, request, global_params=global_params)
Get.method_config = lambda: base_api.ApiMethodInfo(
flat_path=u'v1alpha1/projects/{projectsId}/locations/{locationsId}/operations/{operationsId}',
http_method=u'GET',
method_id=u'tpu.projects.locations.operations.get',
ordered_params=[u'name'],
path_params=[u'name'],
query_params=[],
relative_path=u'v1alpha1/{+name}',
request_field='',
request_type_name=u'TpuProjectsLocationsOperationsGetRequest',
response_type_name=u'Operation',
supports_download=False,
)
def List(self, request, global_params=None):
config = self.GetMethodConfig('List')
return self._RunMethod(
config, request, global_params=global_params)
List.method_config = lambda: base_api.ApiMethodInfo(
flat_path=u'v1alpha1/projects/{projectsId}/locations/{locationsId}/operations',
http_method=u'GET',
method_id=u'tpu.projects.locations.operations.list',
ordered_params=[u'name'],
path_params=[u'name'],
query_params=[u'filter', u'pageSize', u'pageToken'],
relative_path=u'v1alpha1/{+name}/operations',
request_field='',
request_type_name=u'TpuProjectsLocationsOperationsListRequest',
response_type_name=u'ListOperationsResponse',
supports_download=False,
)
class ProjectsLocationsTensorflowVersionsService(base_api.BaseApiService):
_NAME = u'projects_locations_tensorflowVersions'
def __init__(self, client):
super(TpuV1alpha1.ProjectsLocationsTensorflowVersionsService, self).__init__(client)
self._upload_configs = {
}
def Get(self, request, global_params=None):
config = self.GetMethodConfig('Get')
return self._RunMethod(
config, request, global_params=global_params)
Get.method_config = lambda: base_api.ApiMethodInfo(
flat_path=u'v1alpha1/projects/{projectsId}/locations/{locationsId}/tensorflowVersions/{tensorflowVersionsId}',
http_method=u'GET',
method_id=u'tpu.projects.locations.tensorflowVersions.get',
ordered_params=[u'name'],
path_params=[u'name'],
query_params=[],
relative_path=u'v1alpha1/{+name}',
request_field='',
request_type_name=u'TpuProjectsLocationsTensorflowVersionsGetRequest',
response_type_name=u'TensorFlowVersion',
supports_download=False,
)
def List(self, request, global_params=None):
config = self.GetMethodConfig('List')
return self._RunMethod(
config, request, global_params=global_params)
List.method_config = lambda: base_api.ApiMethodInfo(
flat_path=u'v1alpha1/projects/{projectsId}/locations/{locationsId}/tensorflowVersions',
http_method=u'GET',
method_id=u'tpu.projects.locations.tensorflowVersions.list',
ordered_params=[u'parent'],
path_params=[u'parent'],
query_params=[u'filter', u'orderBy', u'pageSize', u'pageToken'],
relative_path=u'v1alpha1/{+parent}/tensorflowVersions',
request_field='',
request_type_name=u'TpuProjectsLocationsTensorflowVersionsListRequest',
response_type_name=u'ListTensorFlowVersionsResponse',
supports_download=False,
)
class ProjectsLocationsService(base_api.BaseApiService):
_NAME = u'projects_locations'
def __init__(self, client):
super(TpuV1alpha1.ProjectsLocationsService, self).__init__(client)
self._upload_configs = {
}
def Get(self, request, global_params=None):
config = self.GetMethodConfig('Get')
return self._RunMethod(
config, request, global_params=global_params)
Get.method_config = lambda: base_api.ApiMethodInfo(
flat_path=u'v1alpha1/projects/{projectsId}/locations/{locationsId}',
http_method=u'GET',
method_id=u'tpu.projects.locations.get',
ordered_params=[u'name'],
path_params=[u'name'],
query_params=[],
relative_path=u'v1alpha1/{+name}',
request_field='',
request_type_name=u'TpuProjectsLocationsGetRequest',
response_type_name=u'Location',
supports_download=False,
)
def List(self, request, global_params=None):
config = self.GetMethodConfig('List')
return self._RunMethod(
config, request, global_params=global_params)
List.method_config = lambda: base_api.ApiMethodInfo(
flat_path=u'v1alpha1/projects/{projectsId}/locations',
http_method=u'GET',
method_id=u'tpu.projects.locations.list',
ordered_params=[u'name'],
path_params=[u'name'],
query_params=[u'filter', u'pageSize', u'pageToken'],
relative_path=u'v1alpha1/{+name}/locations',
request_field='',
request_type_name=u'TpuProjectsLocationsListRequest',
response_type_name=u'ListLocationsResponse',
supports_download=False,
)
class ProjectsService(base_api.BaseApiService):
_NAME = u'projects'
def __init__(self, client):
super(TpuV1alpha1.ProjectsService, self).__init__(client)
self._upload_configs = {
}
| true | true |
f7f94685094d6f2510a1731fd8a684fc2dc7f096 | 2,036 | py | Python | src/sqapi/messaging/brokers/kafka.py | mabruras/sqapi | e4fa8d800b57a5017b5a48f7cf459d171e69946d | [
"MIT"
] | 3 | 2019-06-25T05:55:06.000Z | 2020-06-21T03:30:53.000Z | src/sqapi/messaging/brokers/kafka.py | mabruras/sqapi | e4fa8d800b57a5017b5a48f7cf459d171e69946d | [
"MIT"
] | null | null | null | src/sqapi/messaging/brokers/kafka.py | mabruras/sqapi | e4fa8d800b57a5017b5a48f7cf459d171e69946d | [
"MIT"
] | null | null | null | #! /usr/bin/env python
import logging
import time
from kafka import KafkaConsumer
log = logging.getLogger(__name__)
class Listener:
def __init__(self, config: dict, process_message):
self.config = config if config else dict()
self.pm_callback = process_message
log.info('Loading Kafka')
self.retry_interval = float(config.get('retry_interval', 3))
self.delay = config.get('process_delay', 0)
self.host = config.get('host', 'localhost')
self.port = config.get('port', 9092)
self.topic_names = config.get('topic_names', [])
self.sub_pattern = config.get('subscription_pattern', None)
self.consumer_group = config.get('consumer_group', 'sqapi')
self.api_version = tuple(config.get('api_version', [0, 10, 0]))
def start_listener(self):
while True:
log.info(f'Listening for messages from Kafka')
consumer = KafkaConsumer(
group_id=self.consumer_group,
api_version=self.api_version,
bootstrap_servers=f'{self.host}:{self.port}'
)
log.info(f'Subscription topics: {self.topic_names}')
log.info(f'Subscription pattern: {self.sub_pattern}')
consumer.subscribe(topics=self.topic_names, pattern=self.sub_pattern)
consumer.poll()
for msg in consumer:
log.info('Received message: {} (topic), {} (partition), {} (offset), {} (key)'.format(
msg.topic, msg.partition, msg.offset, msg.key
))
self.parse_message(msg)
def parse_message(self, body):
log.info('Processing starts after delay ({} seconds)'.format(self.delay))
time.sleep(self.delay)
try:
log.debug('Message body: {}'.format(body))
self.pm_callback(body.value.decode('utf-8'))
except Exception as e:
err = 'Could not process received message: {}'.format(str(e))
log.warning(err)
| 33.933333 | 102 | 0.600196 |
import logging
import time
from kafka import KafkaConsumer
log = logging.getLogger(__name__)
class Listener:
def __init__(self, config: dict, process_message):
self.config = config if config else dict()
self.pm_callback = process_message
log.info('Loading Kafka')
self.retry_interval = float(config.get('retry_interval', 3))
self.delay = config.get('process_delay', 0)
self.host = config.get('host', 'localhost')
self.port = config.get('port', 9092)
self.topic_names = config.get('topic_names', [])
self.sub_pattern = config.get('subscription_pattern', None)
self.consumer_group = config.get('consumer_group', 'sqapi')
self.api_version = tuple(config.get('api_version', [0, 10, 0]))
def start_listener(self):
while True:
log.info(f'Listening for messages from Kafka')
consumer = KafkaConsumer(
group_id=self.consumer_group,
api_version=self.api_version,
bootstrap_servers=f'{self.host}:{self.port}'
)
log.info(f'Subscription topics: {self.topic_names}')
log.info(f'Subscription pattern: {self.sub_pattern}')
consumer.subscribe(topics=self.topic_names, pattern=self.sub_pattern)
consumer.poll()
for msg in consumer:
log.info('Received message: {} (topic), {} (partition), {} (offset), {} (key)'.format(
msg.topic, msg.partition, msg.offset, msg.key
))
self.parse_message(msg)
def parse_message(self, body):
log.info('Processing starts after delay ({} seconds)'.format(self.delay))
time.sleep(self.delay)
try:
log.debug('Message body: {}'.format(body))
self.pm_callback(body.value.decode('utf-8'))
except Exception as e:
err = 'Could not process received message: {}'.format(str(e))
log.warning(err)
| true | true |
f7f947668d87730d6af70415ef3b6ce7ca2134f5 | 85 | py | Python | library-scrapper/views/InductionCoil.py | mir3z/life.js | b6936a881ec5f7d425ef5419daea3049d4c24df7 | [
"MIT"
] | 1 | 2021-07-13T11:06:50.000Z | 2021-07-13T11:06:50.000Z | library-scrapper/views/InductionCoil.py | mir3z/life.js | b6936a881ec5f7d425ef5419daea3049d4c24df7 | [
"MIT"
] | 2 | 2021-03-09T09:46:10.000Z | 2021-05-09T13:54:07.000Z | library-scrapper/views/InductionCoil.py | mir3z/life.js | b6936a881ec5f7d425ef5419daea3049d4c24df7 | [
"MIT"
] | 1 | 2021-03-03T09:31:55.000Z | 2021-03-03T09:31:55.000Z | from .View import View
class InductionCoilView(View):
type = "Induction Coil"
| 12.142857 | 30 | 0.717647 | from .View import View
class InductionCoilView(View):
type = "Induction Coil"
| true | true |
f7f947f9095a297f23dbc9159b08a10b3643369f | 25,238 | py | Python | python/graphscope/nx/generators/random_graphs.py | haoxins/GraphScope | e1e22a425b5c33bed0dea930f8722e6159484153 | [
"Apache-2.0"
] | 2 | 2021-04-07T07:57:13.000Z | 2021-11-19T09:44:01.000Z | python/graphscope/nx/generators/random_graphs.py | haoxins/GraphScope | e1e22a425b5c33bed0dea930f8722e6159484153 | [
"Apache-2.0"
] | 16 | 2021-12-22T09:19:25.000Z | 2022-03-29T02:43:34.000Z | python/graphscope/nx/generators/random_graphs.py | haoxins/GraphScope | e1e22a425b5c33bed0dea930f8722e6159484153 | [
"Apache-2.0"
] | 2 | 2022-01-25T10:16:51.000Z | 2022-02-07T11:51:20.000Z | # -*- coding: utf-8 -*-
#
# This file random_graphs.py is referred and derived from project NetworkX,
#
# https://github.com/networkx/networkx/blob/master/networkx/generators/random_graphs.py
#
# which has the following license:
#
# Copyright (C) 2004-2020, NetworkX Developers
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
#
# This file is part of NetworkX.
#
# NetworkX is distributed under a BSD license; see LICENSE.txt for more
# information.
#
"""
Generators for random graphs.
"""
import itertools
import math
from collections import defaultdict
import networkx as nxa
from networkx.utils import powerlaw_sequence
from networkx.utils import py_random_state
from graphscope import nx
from graphscope.nx.generators.classic import complete_graph
from graphscope.nx.generators.classic import empty_graph
from graphscope.nx.generators.classic import path_graph
from graphscope.nx.generators.degree_seq import degree_sequence_tree
from graphscope.nx.utils.compat import patch_docstring
__all__ = [
"fast_gnp_random_graph",
"gnp_random_graph",
"dense_gnm_random_graph",
"gnm_random_graph",
"erdos_renyi_graph",
"binomial_graph",
"newman_watts_strogatz_graph",
"watts_strogatz_graph",
"connected_watts_strogatz_graph",
"random_regular_graph",
"barabasi_albert_graph",
"dual_barabasi_albert_graph",
"extended_barabasi_albert_graph",
"powerlaw_cluster_graph",
"random_lobster",
"random_shell_graph",
"random_powerlaw_tree",
"random_powerlaw_tree_sequence",
"random_kernel_graph",
]
# -------------------------------------------------------------------------
# Some Famous Random Graphs
# -------------------------------------------------------------------------
@patch_docstring(nxa.fast_gnp_random_graph)
@py_random_state(2)
def fast_gnp_random_graph(n, p, seed=None, directed=False):
G = empty_graph(n)
if p <= 0 or p >= 1:
return nx.gnp_random_graph(n, p, seed=seed, directed=directed)
w = -1
lp = math.log(1.0 - p)
if directed:
G = nx.DiGraph(G)
# Nodes in graph are from 0,n-1 (start with v as the first node index).
v = 0
while v < n:
lr = math.log(1.0 - seed.random())
w = w + 1 + int(lr / lp)
if v == w: # avoid self loops
w = w + 1
while v < n <= w:
w = w - n
v = v + 1
if v == w: # avoid self loops
w = w + 1
if v < n:
G.add_edge(v, w)
else:
# Nodes in graph are from 0,n-1 (start with v as the second node index).
v = 1
while v < n:
lr = math.log(1.0 - seed.random())
w = w + 1 + int(lr / lp)
while w >= v and v < n:
w = w - v
v = v + 1
if v < n:
G.add_edge(v, w)
return G
@patch_docstring(nxa.gnp_random_graph)
@py_random_state(2)
def gnp_random_graph(n, p, seed=None, directed=False):
if directed:
edges = itertools.permutations(range(n), 2)
G = nx.DiGraph()
else:
edges = itertools.combinations(range(n), 2)
G = nx.Graph()
G.add_nodes_from(range(n))
if p <= 0:
return G
if p >= 1:
return complete_graph(n, create_using=G)
for e in edges:
if seed.random() < p:
G.add_edge(*e)
return G
# add some aliases to common names
binomial_graph = gnp_random_graph
erdos_renyi_graph = gnp_random_graph
@patch_docstring(nxa.dense_gnm_random_graph)
@py_random_state(2)
def dense_gnm_random_graph(n, m, seed=None):
mmax = n * (n - 1) / 2
if m >= mmax:
G = complete_graph(n)
else:
G = empty_graph(n)
if n == 1 or m >= mmax:
return G
u = 0
v = 1
t = 0
k = 0
while True:
if seed.randrange(mmax - t) < m - k:
G.add_edge(u, v)
k += 1
if k == m:
return G
t += 1
v += 1
if v == n: # go to next row of adjacency matrix
u += 1
v = u + 1
@patch_docstring(nxa.gnm_random_graph)
@py_random_state(2)
def gnm_random_graph(n, m, seed=None, directed=False):
if directed:
G = nx.DiGraph()
else:
G = nx.Graph()
G.add_nodes_from(range(n))
if n == 1:
return G
max_edges = n * (n - 1)
if not directed:
max_edges /= 2.0
if m >= max_edges:
return complete_graph(n, create_using=G)
nlist = list(G)
edge_count = 0
while edge_count < m:
# generate random edge,u,v
u = seed.choice(nlist)
v = seed.choice(nlist)
if u == v:
continue
else:
G.add_edge(u, v)
edge_count = edge_count + 1
return G
@patch_docstring(nxa.newman_watts_strogatz_graph)
@py_random_state(3)
def newman_watts_strogatz_graph(n, k, p, seed=None):
if k > n:
raise nx.NetworkXError("k>=n, choose smaller k or larger n")
# If k == n the graph return is a complete graph
if k == n:
return nx.complete_graph(n)
G = empty_graph(n)
nlist = list(G.nodes())
fromv = nlist
# connect the k/2 neighbors
for j in range(1, k // 2 + 1):
tov = fromv[j:] + fromv[0:j] # the first j are now last
for i, value in enumerate(fromv):
G.add_edge(value, tov[i])
# for each edge u-v, with probability p, randomly select existing
# node w and add new edge u-w
e = list(G.edges())
for (u, v) in e:
if seed.random() < p:
w = seed.choice(nlist)
# no self-loops and reject if edge u-w exists
# is that the correct NWS model?
while w == u or G.has_edge(u, w):
w = seed.choice(nlist)
if G.degree(u) >= n - 1:
break # skip this rewiring
else:
G.add_edge(u, w)
return G
@patch_docstring(nxa.watts_strogatz_graph)
@py_random_state(3)
def watts_strogatz_graph(n, k, p, seed=None):
if k > n:
raise nx.NetworkXError("k>n, choose smaller k or larger n")
# If k == n, the graph is complete not Watts-Strogatz
if k == n:
return nx.complete_graph(n)
G = nx.Graph()
nodes = list(range(n)) # nodes are labeled 0 to n-1
# connect each node to k/2 neighbors
for j in range(1, k // 2 + 1):
targets = nodes[j:] + nodes[0:j] # first j nodes are now last in list
G.add_edges_from(zip(nodes, targets))
# rewire edges from each node
# loop over all nodes in order (label) and neighbors in order (distance)
# no self loops or multiple edges allowed
for j in range(1, k // 2 + 1): # outer loop is neighbors
targets = nodes[j:] + nodes[0:j] # first j nodes are now last in list
# inner loop in node order
for u, v in zip(nodes, targets):
if seed.random() < p:
w = seed.choice(nodes)
# Enforce no self-loops or multiple edges
while w == u or G.has_edge(u, w):
w = seed.choice(nodes)
if G.degree(u) >= n - 1:
break # skip this rewiring
else:
G.remove_edge(u, v)
G.add_edge(u, w)
return G
@patch_docstring(nxa.connected_watts_strogatz_graph)
@py_random_state(4)
def connected_watts_strogatz_graph(n, k, p, tries=100, seed=None):
for i in range(tries):
# seed is an RNG so should change sequence each call
G = watts_strogatz_graph(n, k, p, seed)
if nx.is_connected(G):
return G
raise nx.NetworkXError("Maximum number of tries exceeded")
@patch_docstring(nxa.random_regular_graph)
@py_random_state(2)
def random_regular_graph(d, n, seed=None):
if (n * d) % 2 != 0:
raise nx.NetworkXError("n * d must be even")
if not 0 <= d < n:
raise nx.NetworkXError("the 0 <= d < n inequality must be satisfied")
if d == 0:
return empty_graph(n)
def _suitable(edges, potential_edges):
# Helper subroutine to check if there are suitable edges remaining
# If False, the generation of the graph has failed
if not potential_edges:
return True
for s1 in potential_edges:
for s2 in potential_edges:
# Two iterators on the same dictionary are guaranteed
# to visit it in the same order if there are no
# intervening modifications.
if s1 == s2:
# Only need to consider s1-s2 pair one time
break
if s1 > s2:
s1, s2 = s2, s1
if (s1, s2) not in edges:
return True
return False
def _try_creation():
# Attempt to create an edge set
edges = set()
stubs = list(range(n)) * d
while stubs:
potential_edges = defaultdict(lambda: 0)
seed.shuffle(stubs)
stubiter = iter(stubs)
for s1, s2 in zip(stubiter, stubiter):
if s1 > s2:
s1, s2 = s2, s1
if s1 != s2 and ((s1, s2) not in edges):
edges.add((s1, s2))
else:
potential_edges[s1] += 1
potential_edges[s2] += 1
if not _suitable(edges, potential_edges):
return None # failed to find suitable edge set
stubs = [
node
for node, potential in potential_edges.items()
for _ in range(potential)
]
return edges
# Even though a suitable edge set exists,
# the generation of such a set is not guaranteed.
# Try repeatedly to find one.
edges = _try_creation()
while edges is None:
edges = _try_creation()
G = nx.Graph()
G.add_edges_from(edges)
return G
def _random_subset(seq, m, rng):
"""Return m unique elements from seq.
This differs from random.sample which can return repeated
elements if seq holds repeated elements.
Note: rng is a random.Random or numpy.random.RandomState instance.
"""
targets = set()
while len(targets) < m:
x = rng.choice(seq)
targets.add(x)
return targets
@patch_docstring(nxa.barabasi_albert_graph)
@py_random_state(2)
def barabasi_albert_graph(n, m, seed=None, initial_graph=None):
if m < 1 or m >= n:
raise nx.NetworkXError(
"Barabási–Albert network must have m >= 1"
" and m < n, m = %d, n = %d" % (m, n)
)
if initial_graph is None:
# Default initial graph : star graph on (m + 1) nodes
G = nx.star_graph(m)
else:
if len(initial_graph) < m or len(initial_graph) > n:
raise nx.NetworkXError(
f"Barabási–Albert initial graph needs between m={m} and n={n} nodes"
)
G = initial_graph.copy()
# List of existing nodes, with nodes repeated once for each adjacent edge
repeated_nodes = [n for n, d in G.degree() for _ in range(d)]
# Start adding the other n - m0 nodes.
source = len(G)
while source < n:
# Now choose m unique nodes from the existing nodes
# Pick uniformly from repeated_nodes (preferential attachment)
targets = _random_subset(repeated_nodes, m, seed)
# Add edges to m nodes from the source.
G.add_edges_from(zip([source] * m, targets))
# Add one node to the list for each new edge just created.
repeated_nodes.extend(targets)
# And the new node "source" has m edges to add to the list.
repeated_nodes.extend([source] * m)
source += 1
return G
@patch_docstring(nxa.dual_barabasi_albert_graph)
@py_random_state(4)
def dual_barabasi_albert_graph(n, m1, m2, p, seed=None, initial_graph=None):
if m1 < 1 or m1 >= n:
raise nx.NetworkXError(
"Dual Barabási–Albert network must have m1 >= 1"
" and m1 < n, m1 = %d, n = %d" % (m1, n)
)
if m2 < 1 or m2 >= n:
raise nx.NetworkXError(
"Dual Barabási–Albert network must have m2 >= 1"
" and m2 < n, m2 = %d, n = %d" % (m2, n)
)
if p < 0 or p > 1:
raise nx.NetworkXError(
"Dual Barabási–Albert network must have 0 <= p <= 1," "p = %f" % p
)
# For simplicity, if p == 0 or 1, just return BA
if p == 1:
return barabasi_albert_graph(n, m1, seed)
if p == 0:
return barabasi_albert_graph(n, m2, seed)
if initial_graph is None:
# Default initial graph : empty graph on max(m1, m2) nodes
G = nx.star_graph(max(m1, m2))
else:
if len(initial_graph) < max(m1, m2) or len(initial_graph) > n:
raise nx.NetworkXError(
f"Barabási–Albert initial graph must have between "
f"max(m1, m2) = {max(m1, m2)} and n = {n} nodes"
)
G = initial_graph.copy()
# Target nodes for new edges
targets = list(G)
# List of existing nodes, with nodes repeated once for each adjacent edge
repeated_nodes = [n for n, d in G.degree() for _ in range(d)]
# Start adding the remaining nodes.
source = len(G)
while source < n:
# Pick which m to use (m1 or m2)
if seed.random() < p:
m = m1
else:
m = m2
# Now choose m unique nodes from the existing nodes
# Pick uniformly from repeated_nodes (preferential attachment)
targets = _random_subset(repeated_nodes, m, seed)
# Add edges to m nodes from the source.
G.add_edges_from(zip([source] * m, targets))
# Add one node to the list for each new edge just created.
repeated_nodes.extend(targets)
# And the new node "source" has m edges to add to the list.
repeated_nodes.extend([source] * m)
source += 1
return G
@patch_docstring(nxa.extended_barabasi_albert_graph)
@py_random_state(4)
def extended_barabasi_albert_graph(n, m, p, q, seed=None):
if m < 1 or m >= n:
msg = "Extended Barabasi-Albert network needs m>=1 and m<n, m=%d, n=%d"
raise nx.NetworkXError(msg % (m, n))
if p + q >= 1:
msg = "Extended Barabasi-Albert network needs p + q <= 1, p=%d, q=%d"
raise nx.NetworkXError(msg % (p, q))
# Add m initial nodes (m0 in barabasi-speak)
G = empty_graph(m)
# List of nodes to represent the preferential attachment random selection.
# At the creation of the graph, all nodes are added to the list
# so that even nodes that are not connected have a chance to get selected,
# for rewiring and adding of edges.
# With each new edge, nodes at the ends of the edge are added to the list.
attachment_preference = []
attachment_preference.extend(range(m))
# Start adding the other n-m nodes. The first node is m.
new_node = m
while new_node < n:
a_probability = seed.random()
# Total number of edges of a Clique of all the nodes
clique_degree = len(G) - 1
clique_size = (len(G) * clique_degree) / 2
# Adding m new edges, if there is room to add them
if a_probability < p and G.size() <= clique_size - m:
# Select the nodes where an edge can be added
elligible_nodes = [nd for nd, deg in G.degree() if deg < clique_degree]
for i in range(m):
# Choosing a random source node from elligible_nodes
src_node = seed.choice(elligible_nodes)
# Picking a possible node that is not 'src_node' or
# neighbor with 'src_node', with preferential attachment
prohibited_nodes = list(G[src_node])
prohibited_nodes.append(src_node)
# This will raise an exception if the sequence is empty
dest_node = seed.choice(
[nd for nd in attachment_preference if nd not in prohibited_nodes]
)
# Adding the new edge
G.add_edge(src_node, dest_node)
# Appending both nodes to add to their preferential attachment
attachment_preference.append(src_node)
attachment_preference.append(dest_node)
# Adjusting the elligible nodes. Degree may be saturated.
if G.degree(src_node) == clique_degree:
elligible_nodes.remove(src_node)
if (
G.degree(dest_node) == clique_degree
and dest_node in elligible_nodes
):
elligible_nodes.remove(dest_node)
# Rewiring m edges, if there are enough edges
elif p <= a_probability < (p + q) and m <= G.size() < clique_size:
# Selecting nodes that have at least 1 edge but that are not
# fully connected to ALL other nodes (center of star).
# These nodes are the pivot nodes of the edges to rewire
elligible_nodes = [nd for nd, deg in G.degree() if 0 < deg < clique_degree]
for i in range(m):
# Choosing a random source node
node = seed.choice(elligible_nodes)
# The available nodes do have a neighbor at least.
neighbor_nodes = list(G[node])
# Choosing the other end that will get dettached
src_node = seed.choice(neighbor_nodes)
# Picking a target node that is not 'node' or
# neighbor with 'node', with preferential attachment
neighbor_nodes.append(node)
dest_node = seed.choice(
[nd for nd in attachment_preference if nd not in neighbor_nodes]
)
# Rewire
G.remove_edge(node, src_node)
G.add_edge(node, dest_node)
# Adjusting the preferential attachment list
attachment_preference.remove(src_node)
attachment_preference.append(dest_node)
# Adjusting the elligible nodes.
# nodes may be saturated or isolated.
if G.degree(src_node) == 0 and src_node in elligible_nodes:
elligible_nodes.remove(src_node)
if dest_node in elligible_nodes:
if G.degree(dest_node) == clique_degree:
elligible_nodes.remove(dest_node)
else:
if G.degree(dest_node) == 1:
elligible_nodes.append(dest_node)
# Adding new node with m edges
else:
# Select the edges' nodes by preferential attachment
targets = _random_subset(attachment_preference, m, seed)
G.add_edges_from(zip([new_node] * m, targets))
# Add one node to the list for each new edge just created.
attachment_preference.extend(targets)
# The new node has m edges to it, plus itself: m + 1
attachment_preference.extend([new_node] * (m + 1))
new_node += 1
return G
@patch_docstring(nxa.powerlaw_cluster_graph)
@py_random_state(3)
def powerlaw_cluster_graph(n, m, p, seed=None):
if m < 1 or n < m:
raise nx.NetworkXError(
"NetworkXError must have m>1 and m<n, m=%d,n=%d" % (m, n)
)
if p > 1 or p < 0:
raise nx.NetworkXError("NetworkXError p must be in [0,1], p=%f" % (p))
G = empty_graph(m) # add m initial nodes (m0 in barabasi-speak)
repeated_nodes = list(G.nodes()) # list of existing nodes to sample from
# with nodes repeated once for each adjacent edge
source = m # next node is m
while source < n: # Now add the other n-1 nodes
possible_targets = _random_subset(repeated_nodes, m, seed)
# do one preferential attachment for new node
target = possible_targets.pop()
G.add_edge(source, target)
repeated_nodes.append(target) # add one node to list for each new link
count = 1
while count < m: # add m-1 more new links
if seed.random() < p: # clustering step: add triangle
neighborhood = [
nbr
for nbr in G.neighbors(target)
if not G.has_edge(source, nbr) and not nbr == source
]
if neighborhood: # if there is a neighbor without a link
nbr = seed.choice(neighborhood)
G.add_edge(source, nbr) # add triangle
repeated_nodes.append(nbr)
count = count + 1
continue # go to top of while loop
# else do preferential attachment step if above fails
target = possible_targets.pop()
G.add_edge(source, target)
repeated_nodes.append(target)
count = count + 1
repeated_nodes.extend([source] * m) # add source node to list m times
source += 1
return G
@patch_docstring(nxa.random_lobster)
@py_random_state(3)
def random_lobster(n, p1, p2, seed=None):
# a necessary ingredient in any self-respecting graph library
llen = int(2 * seed.random() * n + 0.5)
L = path_graph(llen)
# build caterpillar: add edges to path graph with probability p1
current_node = llen - 1
for n in range(llen):
if seed.random() < p1: # add fuzzy caterpillar parts
current_node += 1
L.add_edge(n, current_node)
if seed.random() < p2: # add crunchy lobster bits
current_node += 1
L.add_edge(current_node - 1, current_node)
return L # voila, un lobster!
@patch_docstring(nxa.random_shell_graph)
@py_random_state(1)
def random_shell_graph(constructor, seed=None):
G = empty_graph(0)
glist = []
intra_edges = []
nnodes = 0
# create gnm graphs for each shell
for (n, m, d) in constructor:
inter_edges = int(m * d)
intra_edges.append(m - inter_edges)
g = nx.convert_node_labels_to_integers(
gnm_random_graph(n, inter_edges, seed=seed), first_label=nnodes
)
glist.append(g)
nnodes += n
G = nx.operators.union(G, g)
# connect the shells randomly
for gi in range(len(glist) - 1):
nlist1 = list(glist[gi])
nlist2 = list(glist[gi + 1])
total_edges = intra_edges[gi]
edge_count = 0
while edge_count < total_edges:
u = seed.choice(nlist1)
v = seed.choice(nlist2)
if u == v or G.has_edge(u, v):
continue
else:
G.add_edge(u, v)
edge_count = edge_count + 1
return G
@patch_docstring(nxa.random_powerlaw_tree)
@py_random_state(2)
def random_powerlaw_tree(n, gamma=3, seed=None, tries=100):
# This call may raise a NetworkXError if the number of tries is succeeded.
seq = random_powerlaw_tree_sequence(n, gamma=gamma, seed=seed, tries=tries)
G = degree_sequence_tree(seq)
return G
@patch_docstring(nxa.random_powerlaw_tree_sequence)
@py_random_state(2)
def random_powerlaw_tree_sequence(n, gamma=3, seed=None, tries=100):
# get trial sequence
z = powerlaw_sequence(n, exponent=gamma, seed=seed)
# round to integer values in the range [0,n]
zseq = [min(n, max(int(round(s)), 0)) for s in z]
# another sequence to swap values from
z = powerlaw_sequence(tries, exponent=gamma, seed=seed)
# round to integer values in the range [0,n]
swap = [min(n, max(int(round(s)), 0)) for s in z]
for deg in swap:
# If this degree sequence can be the degree sequence of a tree, return
# it. It can be a tree if the number of edges is one fewer than the
# number of nodes, or in other words, `n - sum(zseq) / 2 == 1`. We
# use an equivalent condition below that avoids floating point
# operations.
if 2 * n - sum(zseq) == 2:
return zseq
index = seed.randint(0, n - 1)
zseq[index] = swap.pop()
raise nx.NetworkXError(
"Exceeded max (%d) attempts for a valid tree" " sequence." % tries
)
@patch_docstring(nxa.random_kernel_graph)
@py_random_state(3)
def random_kernel_graph(n, kernel_integral, kernel_root=None, seed=None):
if kernel_root is None:
import scipy.optimize as optimize
def kernel_root(y, a, r):
def my_function(b):
return kernel_integral(y, a, b) - r
return optimize.brentq(my_function, a, 1)
graph = nx.Graph()
graph.add_nodes_from(range(n))
(i, j) = (1, 1)
while i < n:
r = -math.log(1 - seed.random()) # (1-seed.random()) in (0, 1]
if kernel_integral(i / n, j / n, 1) <= r:
i, j = i + 1, i + 1
else:
j = int(math.ceil(n * kernel_root(i / n, j / n, r)))
graph.add_edge(i - 1, j - 1)
return graph
| 34.059379 | 88 | 0.57881 |
import itertools
import math
from collections import defaultdict
import networkx as nxa
from networkx.utils import powerlaw_sequence
from networkx.utils import py_random_state
from graphscope import nx
from graphscope.nx.generators.classic import complete_graph
from graphscope.nx.generators.classic import empty_graph
from graphscope.nx.generators.classic import path_graph
from graphscope.nx.generators.degree_seq import degree_sequence_tree
from graphscope.nx.utils.compat import patch_docstring
__all__ = [
"fast_gnp_random_graph",
"gnp_random_graph",
"dense_gnm_random_graph",
"gnm_random_graph",
"erdos_renyi_graph",
"binomial_graph",
"newman_watts_strogatz_graph",
"watts_strogatz_graph",
"connected_watts_strogatz_graph",
"random_regular_graph",
"barabasi_albert_graph",
"dual_barabasi_albert_graph",
"extended_barabasi_albert_graph",
"powerlaw_cluster_graph",
"random_lobster",
"random_shell_graph",
"random_powerlaw_tree",
"random_powerlaw_tree_sequence",
"random_kernel_graph",
]
@patch_docstring(nxa.fast_gnp_random_graph)
@py_random_state(2)
def fast_gnp_random_graph(n, p, seed=None, directed=False):
G = empty_graph(n)
if p <= 0 or p >= 1:
return nx.gnp_random_graph(n, p, seed=seed, directed=directed)
w = -1
lp = math.log(1.0 - p)
if directed:
G = nx.DiGraph(G)
v = 0
while v < n:
lr = math.log(1.0 - seed.random())
w = w + 1 + int(lr / lp)
if v == w:
w = w + 1
while v < n <= w:
w = w - n
v = v + 1
if v == w:
w = w + 1
if v < n:
G.add_edge(v, w)
else:
v = 1
while v < n:
lr = math.log(1.0 - seed.random())
w = w + 1 + int(lr / lp)
while w >= v and v < n:
w = w - v
v = v + 1
if v < n:
G.add_edge(v, w)
return G
@patch_docstring(nxa.gnp_random_graph)
@py_random_state(2)
def gnp_random_graph(n, p, seed=None, directed=False):
if directed:
edges = itertools.permutations(range(n), 2)
G = nx.DiGraph()
else:
edges = itertools.combinations(range(n), 2)
G = nx.Graph()
G.add_nodes_from(range(n))
if p <= 0:
return G
if p >= 1:
return complete_graph(n, create_using=G)
for e in edges:
if seed.random() < p:
G.add_edge(*e)
return G
binomial_graph = gnp_random_graph
erdos_renyi_graph = gnp_random_graph
@patch_docstring(nxa.dense_gnm_random_graph)
@py_random_state(2)
def dense_gnm_random_graph(n, m, seed=None):
mmax = n * (n - 1) / 2
if m >= mmax:
G = complete_graph(n)
else:
G = empty_graph(n)
if n == 1 or m >= mmax:
return G
u = 0
v = 1
t = 0
k = 0
while True:
if seed.randrange(mmax - t) < m - k:
G.add_edge(u, v)
k += 1
if k == m:
return G
t += 1
v += 1
if v == n:
u += 1
v = u + 1
@patch_docstring(nxa.gnm_random_graph)
@py_random_state(2)
def gnm_random_graph(n, m, seed=None, directed=False):
if directed:
G = nx.DiGraph()
else:
G = nx.Graph()
G.add_nodes_from(range(n))
if n == 1:
return G
max_edges = n * (n - 1)
if not directed:
max_edges /= 2.0
if m >= max_edges:
return complete_graph(n, create_using=G)
nlist = list(G)
edge_count = 0
while edge_count < m:
u = seed.choice(nlist)
v = seed.choice(nlist)
if u == v:
continue
else:
G.add_edge(u, v)
edge_count = edge_count + 1
return G
@patch_docstring(nxa.newman_watts_strogatz_graph)
@py_random_state(3)
def newman_watts_strogatz_graph(n, k, p, seed=None):
if k > n:
raise nx.NetworkXError("k>=n, choose smaller k or larger n")
if k == n:
return nx.complete_graph(n)
G = empty_graph(n)
nlist = list(G.nodes())
fromv = nlist
for j in range(1, k // 2 + 1):
tov = fromv[j:] + fromv[0:j]
for i, value in enumerate(fromv):
G.add_edge(value, tov[i])
e = list(G.edges())
for (u, v) in e:
if seed.random() < p:
w = seed.choice(nlist)
while w == u or G.has_edge(u, w):
w = seed.choice(nlist)
if G.degree(u) >= n - 1:
break
else:
G.add_edge(u, w)
return G
@patch_docstring(nxa.watts_strogatz_graph)
@py_random_state(3)
def watts_strogatz_graph(n, k, p, seed=None):
if k > n:
raise nx.NetworkXError("k>n, choose smaller k or larger n")
if k == n:
return nx.complete_graph(n)
G = nx.Graph()
nodes = list(range(n))
for j in range(1, k // 2 + 1):
targets = nodes[j:] + nodes[0:j]
G.add_edges_from(zip(nodes, targets))
for j in range(1, k // 2 + 1):
targets = nodes[j:] + nodes[0:j]
for u, v in zip(nodes, targets):
if seed.random() < p:
w = seed.choice(nodes)
while w == u or G.has_edge(u, w):
w = seed.choice(nodes)
if G.degree(u) >= n - 1:
break
else:
G.remove_edge(u, v)
G.add_edge(u, w)
return G
@patch_docstring(nxa.connected_watts_strogatz_graph)
@py_random_state(4)
def connected_watts_strogatz_graph(n, k, p, tries=100, seed=None):
for i in range(tries):
G = watts_strogatz_graph(n, k, p, seed)
if nx.is_connected(G):
return G
raise nx.NetworkXError("Maximum number of tries exceeded")
@patch_docstring(nxa.random_regular_graph)
@py_random_state(2)
def random_regular_graph(d, n, seed=None):
if (n * d) % 2 != 0:
raise nx.NetworkXError("n * d must be even")
if not 0 <= d < n:
raise nx.NetworkXError("the 0 <= d < n inequality must be satisfied")
if d == 0:
return empty_graph(n)
def _suitable(edges, potential_edges):
if not potential_edges:
return True
for s1 in potential_edges:
for s2 in potential_edges:
if s1 == s2:
break
if s1 > s2:
s1, s2 = s2, s1
if (s1, s2) not in edges:
return True
return False
def _try_creation():
edges = set()
stubs = list(range(n)) * d
while stubs:
potential_edges = defaultdict(lambda: 0)
seed.shuffle(stubs)
stubiter = iter(stubs)
for s1, s2 in zip(stubiter, stubiter):
if s1 > s2:
s1, s2 = s2, s1
if s1 != s2 and ((s1, s2) not in edges):
edges.add((s1, s2))
else:
potential_edges[s1] += 1
potential_edges[s2] += 1
if not _suitable(edges, potential_edges):
return None
stubs = [
node
for node, potential in potential_edges.items()
for _ in range(potential)
]
return edges
edges = _try_creation()
while edges is None:
edges = _try_creation()
G = nx.Graph()
G.add_edges_from(edges)
return G
def _random_subset(seq, m, rng):
targets = set()
while len(targets) < m:
x = rng.choice(seq)
targets.add(x)
return targets
@patch_docstring(nxa.barabasi_albert_graph)
@py_random_state(2)
def barabasi_albert_graph(n, m, seed=None, initial_graph=None):
if m < 1 or m >= n:
raise nx.NetworkXError(
"Barabási–Albert network must have m >= 1"
" and m < n, m = %d, n = %d" % (m, n)
)
if initial_graph is None:
G = nx.star_graph(m)
else:
if len(initial_graph) < m or len(initial_graph) > n:
raise nx.NetworkXError(
f"Barabási–Albert initial graph needs between m={m} and n={n} nodes"
)
G = initial_graph.copy()
repeated_nodes = [n for n, d in G.degree() for _ in range(d)]
source = len(G)
while source < n:
targets = _random_subset(repeated_nodes, m, seed)
G.add_edges_from(zip([source] * m, targets))
repeated_nodes.extend(targets)
repeated_nodes.extend([source] * m)
source += 1
return G
@patch_docstring(nxa.dual_barabasi_albert_graph)
@py_random_state(4)
def dual_barabasi_albert_graph(n, m1, m2, p, seed=None, initial_graph=None):
if m1 < 1 or m1 >= n:
raise nx.NetworkXError(
"Dual Barabási–Albert network must have m1 >= 1"
" and m1 < n, m1 = %d, n = %d" % (m1, n)
)
if m2 < 1 or m2 >= n:
raise nx.NetworkXError(
"Dual Barabási–Albert network must have m2 >= 1"
" and m2 < n, m2 = %d, n = %d" % (m2, n)
)
if p < 0 or p > 1:
raise nx.NetworkXError(
"Dual Barabási–Albert network must have 0 <= p <= 1," "p = %f" % p
)
if p == 1:
return barabasi_albert_graph(n, m1, seed)
if p == 0:
return barabasi_albert_graph(n, m2, seed)
if initial_graph is None:
G = nx.star_graph(max(m1, m2))
else:
if len(initial_graph) < max(m1, m2) or len(initial_graph) > n:
raise nx.NetworkXError(
f"Barabási–Albert initial graph must have between "
f"max(m1, m2) = {max(m1, m2)} and n = {n} nodes"
)
G = initial_graph.copy()
targets = list(G)
repeated_nodes = [n for n, d in G.degree() for _ in range(d)]
source = len(G)
while source < n:
if seed.random() < p:
m = m1
else:
m = m2
targets = _random_subset(repeated_nodes, m, seed)
G.add_edges_from(zip([source] * m, targets))
repeated_nodes.extend(targets)
repeated_nodes.extend([source] * m)
source += 1
return G
@patch_docstring(nxa.extended_barabasi_albert_graph)
@py_random_state(4)
def extended_barabasi_albert_graph(n, m, p, q, seed=None):
if m < 1 or m >= n:
msg = "Extended Barabasi-Albert network needs m>=1 and m<n, m=%d, n=%d"
raise nx.NetworkXError(msg % (m, n))
if p + q >= 1:
msg = "Extended Barabasi-Albert network needs p + q <= 1, p=%d, q=%d"
raise nx.NetworkXError(msg % (p, q))
G = empty_graph(m)
attachment_preference = []
attachment_preference.extend(range(m))
new_node = m
while new_node < n:
a_probability = seed.random()
clique_degree = len(G) - 1
clique_size = (len(G) * clique_degree) / 2
if a_probability < p and G.size() <= clique_size - m:
elligible_nodes = [nd for nd, deg in G.degree() if deg < clique_degree]
for i in range(m):
src_node = seed.choice(elligible_nodes)
prohibited_nodes = list(G[src_node])
prohibited_nodes.append(src_node)
dest_node = seed.choice(
[nd for nd in attachment_preference if nd not in prohibited_nodes]
)
G.add_edge(src_node, dest_node)
attachment_preference.append(src_node)
attachment_preference.append(dest_node)
if G.degree(src_node) == clique_degree:
elligible_nodes.remove(src_node)
if (
G.degree(dest_node) == clique_degree
and dest_node in elligible_nodes
):
elligible_nodes.remove(dest_node)
elif p <= a_probability < (p + q) and m <= G.size() < clique_size:
elligible_nodes = [nd for nd, deg in G.degree() if 0 < deg < clique_degree]
for i in range(m):
node = seed.choice(elligible_nodes)
neighbor_nodes = list(G[node])
src_node = seed.choice(neighbor_nodes)
neighbor_nodes.append(node)
dest_node = seed.choice(
[nd for nd in attachment_preference if nd not in neighbor_nodes]
)
G.remove_edge(node, src_node)
G.add_edge(node, dest_node)
attachment_preference.remove(src_node)
attachment_preference.append(dest_node)
if G.degree(src_node) == 0 and src_node in elligible_nodes:
elligible_nodes.remove(src_node)
if dest_node in elligible_nodes:
if G.degree(dest_node) == clique_degree:
elligible_nodes.remove(dest_node)
else:
if G.degree(dest_node) == 1:
elligible_nodes.append(dest_node)
else:
targets = _random_subset(attachment_preference, m, seed)
G.add_edges_from(zip([new_node] * m, targets))
# Add one node to the list for each new edge just created.
attachment_preference.extend(targets)
# The new node has m edges to it, plus itself: m + 1
attachment_preference.extend([new_node] * (m + 1))
new_node += 1
return G
@patch_docstring(nxa.powerlaw_cluster_graph)
@py_random_state(3)
def powerlaw_cluster_graph(n, m, p, seed=None):
if m < 1 or n < m:
raise nx.NetworkXError(
"NetworkXError must have m>1 and m<n, m=%d,n=%d" % (m, n)
)
if p > 1 or p < 0:
raise nx.NetworkXError("NetworkXError p must be in [0,1], p=%f" % (p))
G = empty_graph(m) # add m initial nodes (m0 in barabasi-speak)
repeated_nodes = list(G.nodes()) # list of existing nodes to sample from
# with nodes repeated once for each adjacent edge
source = m # next node is m
while source < n: # Now add the other n-1 nodes
possible_targets = _random_subset(repeated_nodes, m, seed)
# do one preferential attachment for new node
target = possible_targets.pop()
G.add_edge(source, target)
repeated_nodes.append(target) # add one node to list for each new link
count = 1
while count < m: # add m-1 more new links
if seed.random() < p: # clustering step: add triangle
neighborhood = [
nbr
for nbr in G.neighbors(target)
if not G.has_edge(source, nbr) and not nbr == source
]
if neighborhood: # if there is a neighbor without a link
nbr = seed.choice(neighborhood)
G.add_edge(source, nbr) # add triangle
repeated_nodes.append(nbr)
count = count + 1
continue # go to top of while loop
# else do preferential attachment step if above fails
target = possible_targets.pop()
G.add_edge(source, target)
repeated_nodes.append(target)
count = count + 1
repeated_nodes.extend([source] * m) # add source node to list m times
source += 1
return G
@patch_docstring(nxa.random_lobster)
@py_random_state(3)
def random_lobster(n, p1, p2, seed=None):
# a necessary ingredient in any self-respecting graph library
llen = int(2 * seed.random() * n + 0.5)
L = path_graph(llen)
# build caterpillar: add edges to path graph with probability p1
current_node = llen - 1
for n in range(llen):
if seed.random() < p1: # add fuzzy caterpillar parts
current_node += 1
L.add_edge(n, current_node)
if seed.random() < p2: # add crunchy lobster bits
current_node += 1
L.add_edge(current_node - 1, current_node)
return L # voila, un lobster!
@patch_docstring(nxa.random_shell_graph)
@py_random_state(1)
def random_shell_graph(constructor, seed=None):
G = empty_graph(0)
glist = []
intra_edges = []
nnodes = 0
# create gnm graphs for each shell
for (n, m, d) in constructor:
inter_edges = int(m * d)
intra_edges.append(m - inter_edges)
g = nx.convert_node_labels_to_integers(
gnm_random_graph(n, inter_edges, seed=seed), first_label=nnodes
)
glist.append(g)
nnodes += n
G = nx.operators.union(G, g)
# connect the shells randomly
for gi in range(len(glist) - 1):
nlist1 = list(glist[gi])
nlist2 = list(glist[gi + 1])
total_edges = intra_edges[gi]
edge_count = 0
while edge_count < total_edges:
u = seed.choice(nlist1)
v = seed.choice(nlist2)
if u == v or G.has_edge(u, v):
continue
else:
G.add_edge(u, v)
edge_count = edge_count + 1
return G
@patch_docstring(nxa.random_powerlaw_tree)
@py_random_state(2)
def random_powerlaw_tree(n, gamma=3, seed=None, tries=100):
# This call may raise a NetworkXError if the number of tries is succeeded.
seq = random_powerlaw_tree_sequence(n, gamma=gamma, seed=seed, tries=tries)
G = degree_sequence_tree(seq)
return G
@patch_docstring(nxa.random_powerlaw_tree_sequence)
@py_random_state(2)
def random_powerlaw_tree_sequence(n, gamma=3, seed=None, tries=100):
# get trial sequence
z = powerlaw_sequence(n, exponent=gamma, seed=seed)
# round to integer values in the range [0,n]
zseq = [min(n, max(int(round(s)), 0)) for s in z]
# another sequence to swap values from
z = powerlaw_sequence(tries, exponent=gamma, seed=seed)
# round to integer values in the range [0,n]
swap = [min(n, max(int(round(s)), 0)) for s in z]
for deg in swap:
# If this degree sequence can be the degree sequence of a tree, return
# it. It can be a tree if the number of edges is one fewer than the
# number of nodes, or in other words, `n - sum(zseq) / 2 == 1`. We
# use an equivalent condition below that avoids floating point
# operations.
if 2 * n - sum(zseq) == 2:
return zseq
index = seed.randint(0, n - 1)
zseq[index] = swap.pop()
raise nx.NetworkXError(
"Exceeded max (%d) attempts for a valid tree" " sequence." % tries
)
@patch_docstring(nxa.random_kernel_graph)
@py_random_state(3)
def random_kernel_graph(n, kernel_integral, kernel_root=None, seed=None):
if kernel_root is None:
import scipy.optimize as optimize
def kernel_root(y, a, r):
def my_function(b):
return kernel_integral(y, a, b) - r
return optimize.brentq(my_function, a, 1)
graph = nx.Graph()
graph.add_nodes_from(range(n))
(i, j) = (1, 1)
while i < n:
r = -math.log(1 - seed.random()) # (1-seed.random()) in (0, 1]
if kernel_integral(i / n, j / n, 1) <= r:
i, j = i + 1, i + 1
else:
j = int(math.ceil(n * kernel_root(i / n, j / n, r)))
graph.add_edge(i - 1, j - 1)
return graph
| true | true |
f7f94890a02109456d0629c13468f3a396acc4c1 | 3,001 | py | Python | src/tensorforce/tensorforce/core/models/constant_model.py | linus87/drl_shape_optimization | 39e6b66bd5b70dfce07e145aafe815071bc1b6fe | [
"MIT"
] | 17 | 2020-12-28T16:25:47.000Z | 2022-03-27T18:28:44.000Z | src/tensorforce/tensorforce/core/models/constant_model.py | linus87/drl_shape_optimization | 39e6b66bd5b70dfce07e145aafe815071bc1b6fe | [
"MIT"
] | 2 | 2021-04-18T03:40:02.000Z | 2022-01-24T08:40:10.000Z | src/tensorforce/tensorforce/core/models/constant_model.py | linus87/drl_shape_optimization | 39e6b66bd5b70dfce07e145aafe815071bc1b6fe | [
"MIT"
] | 8 | 2020-12-23T05:59:52.000Z | 2022-03-28T12:06:35.000Z | # Copyright 2018 Tensorforce Team. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
from collections import OrderedDict
import tensorflow as tf
from tensorforce import util
from tensorforce.core.models import Model
class ConstantModel(Model):
"""
Utility class to return constant actions of a desired shape and with given bounds.
"""
def __init__(
self,
# Model
states, actions, scope, device, saver, summarizer, execution, parallel_interactions,
buffer_observe,
# ConstantModel
action_values
):
super().__init__(
# Model
states=states, internals=None, actions=actions, scope=scope, device=device,
saver=saver, summarizer=summarizer, execution=execution,
parallel_interactions=parallel_interactions, buffer_observe=buffer_observe,
exploration=None, variable_noise=None, states_preprocessing=None,
reward_preprocessing=None
)
# check values
self.action_values = action_values
def tf_core_act(self, states, internals):
assert len(internals) == 0
actions = OrderedDict()
for name, action_spec in self.actions_spec.items():
batch_size = tf.shape(
input=next(iter(states.values())), out_type=util.tf_dtype(dtype='int')
)[0:1]
shape = tf.constant(value=action_spec['shape'], dtype=util.tf_dtype(dtype='int'))
shape = tf.concat(values=(batch_size, shape), axis=0)
dtype = util.tf_dtype(dtype=action_spec['type'])
if self.action_values is not None and name in self.action_values:
value = self.action_values[name]
actions[name] = tf.fill(dims=shape, value=tf.constant(value=value, dtype=dtype))
elif action_spec['type'] == 'float' and 'min_value' in action_spec:
min_value = action_spec['min_value']
max_value = action_spec['max_value']
mean = min_value + 0.5 * (max_value - min_value)
actions[name] = tf.fill(dims=shape, value=tf.constant(value=mean, dtype=dtype))
else:
actions[name] = tf.zeros(shape=shape, dtype=dtype)
return actions, OrderedDict()
def tf_core_observe(self, states, internals, actions, terminal, reward):
return util.no_operation()
| 38.474359 | 96 | 0.639787 |
from collections import OrderedDict
import tensorflow as tf
from tensorforce import util
from tensorforce.core.models import Model
class ConstantModel(Model):
def __init__(
self,
states, actions, scope, device, saver, summarizer, execution, parallel_interactions,
buffer_observe,
action_values
):
super().__init__(
states=states, internals=None, actions=actions, scope=scope, device=device,
saver=saver, summarizer=summarizer, execution=execution,
parallel_interactions=parallel_interactions, buffer_observe=buffer_observe,
exploration=None, variable_noise=None, states_preprocessing=None,
reward_preprocessing=None
)
self.action_values = action_values
def tf_core_act(self, states, internals):
assert len(internals) == 0
actions = OrderedDict()
for name, action_spec in self.actions_spec.items():
batch_size = tf.shape(
input=next(iter(states.values())), out_type=util.tf_dtype(dtype='int')
)[0:1]
shape = tf.constant(value=action_spec['shape'], dtype=util.tf_dtype(dtype='int'))
shape = tf.concat(values=(batch_size, shape), axis=0)
dtype = util.tf_dtype(dtype=action_spec['type'])
if self.action_values is not None and name in self.action_values:
value = self.action_values[name]
actions[name] = tf.fill(dims=shape, value=tf.constant(value=value, dtype=dtype))
elif action_spec['type'] == 'float' and 'min_value' in action_spec:
min_value = action_spec['min_value']
max_value = action_spec['max_value']
mean = min_value + 0.5 * (max_value - min_value)
actions[name] = tf.fill(dims=shape, value=tf.constant(value=mean, dtype=dtype))
else:
actions[name] = tf.zeros(shape=shape, dtype=dtype)
return actions, OrderedDict()
def tf_core_observe(self, states, internals, actions, terminal, reward):
return util.no_operation()
| true | true |
f7f948d092d21a5b4a27d8252472b7d1a151aa20 | 1,605 | py | Python | detailsScrape/commaskd/commaskd20.py | Asyikin98/SkinFerm | 72fd1ad6339c96adf5ec154bde566de9eb1472c3 | [
"MIT"
] | null | null | null | detailsScrape/commaskd/commaskd20.py | Asyikin98/SkinFerm | 72fd1ad6339c96adf5ec154bde566de9eb1472c3 | [
"MIT"
] | 2 | 2021-02-03T01:55:13.000Z | 2021-04-30T12:46:33.000Z | detailsScrape/commaskd/commaskd20.py | Asyikin98/SkinFerm | 72fd1ad6339c96adf5ec154bde566de9eb1472c3 | [
"MIT"
] | null | null | null | import urllib.request
import random
from bs4 import BeautifulSoup
from requests import get
import mysql.connector
conn = mysql.connector.connect(user="root", passwd="",host="localhost", database="product")
cursor = conn.cursor()
sql = """INSERT INTO commaskd (about, rate, top, comment, dari) VALUES (%s, %s, %s, %s, %s)"""
def crawl_url(pageUrl, maskcomd_arr):
url = 'https://www.skinstore.com/jurlique-rose-moisture-plus-moisturising-cream-mask-100ml/10809271.html'
page = get(url)
soup = BeautifulSoup(page.text, 'html.parser')
type(soup)
#######################################################for product 1############################################################################
mask = soup.find_all('div', class_='primary-wrap column-row')
try:
for maskd in mask :
about = maskd.find("div",{"class":"productDescription_synopsisContent"}).get_text().strip()
rate = maskd.find("span",{"class":"visually-hidden productReviews_aggregateRating_hiddenLabel"}).get_text().strip()
top = maskd.find("h2",{"class":"productReviews_topReviewsTitle"}).get_text().strip()
comment = maskd.find("p",{"class":"productReviews_topReviewsExcerpt"}).get_text().strip()
dari = maskd.find("div",{"class":"productReviews_footerDateAndName"}).get_text().strip()
maskcomd_arr.append((about, rate, top, comment, dari))
finally:
return maskcomd_arr
maskcomd_arr = crawl_url("", [])
print(len(maskcomd_arr))
cursor.executemany(sql, maskcomd_arr)
conn.commit()
cursor.close()
conn.close()
| 35.666667 | 148 | 0.624299 | import urllib.request
import random
from bs4 import BeautifulSoup
from requests import get
import mysql.connector
conn = mysql.connector.connect(user="root", passwd="",host="localhost", database="product")
cursor = conn.cursor()
sql = """INSERT INTO commaskd (about, rate, top, comment, dari) VALUES (%s, %s, %s, %s, %s)"""
def crawl_url(pageUrl, maskcomd_arr):
url = 'https://www.skinstore.com/jurlique-rose-moisture-plus-moisturising-cream-mask-100ml/10809271.html'
page = get(url)
soup = BeautifulSoup(page.text, 'html.parser')
type(soup)
| true | true |
f7f94a71a63aa4fcb0b46f82fae4fee4dd45441f | 1,296 | py | Python | src/waldur_openstack/openstack_tenant/migrations/0034_immutable_default_json.py | opennode/waldur-openstack | 8a4170c09bdb8367493441016ef06081250fddb8 | [
"MIT"
] | 1 | 2017-11-07T19:53:57.000Z | 2017-11-07T19:53:57.000Z | src/waldur_openstack/openstack_tenant/migrations/0034_immutable_default_json.py | opennode/waldur-openstack | 8a4170c09bdb8367493441016ef06081250fddb8 | [
"MIT"
] | null | null | null | src/waldur_openstack/openstack_tenant/migrations/0034_immutable_default_json.py | opennode/waldur-openstack | 8a4170c09bdb8367493441016ef06081250fddb8 | [
"MIT"
] | 3 | 2017-09-24T03:11:19.000Z | 2018-08-12T07:43:13.000Z | # -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2018-07-03 17:09
from __future__ import unicode_literals
from django.db import migrations
import waldur_core.core.fields
class Migration(migrations.Migration):
dependencies = [
('openstack_tenant', '0033_unique_instance_backend_id'),
]
operations = [
migrations.AlterField(
model_name='instance',
name='action_details',
field=waldur_core.core.fields.JSONField(default=dict),
),
migrations.AlterField(
model_name='snapshot',
name='action_details',
field=waldur_core.core.fields.JSONField(default=dict),
),
migrations.AlterField(
model_name='subnet',
name='allocation_pools',
field=waldur_core.core.fields.JSONField(default=dict),
),
migrations.AlterField(
model_name='subnet',
name='dns_nameservers',
field=waldur_core.core.fields.JSONField(default=list, help_text='List of DNS name servers associated with the subnet.'),
),
migrations.AlterField(
model_name='volume',
name='action_details',
field=waldur_core.core.fields.JSONField(default=dict),
),
]
| 30.857143 | 132 | 0.614969 |
from __future__ import unicode_literals
from django.db import migrations
import waldur_core.core.fields
class Migration(migrations.Migration):
dependencies = [
('openstack_tenant', '0033_unique_instance_backend_id'),
]
operations = [
migrations.AlterField(
model_name='instance',
name='action_details',
field=waldur_core.core.fields.JSONField(default=dict),
),
migrations.AlterField(
model_name='snapshot',
name='action_details',
field=waldur_core.core.fields.JSONField(default=dict),
),
migrations.AlterField(
model_name='subnet',
name='allocation_pools',
field=waldur_core.core.fields.JSONField(default=dict),
),
migrations.AlterField(
model_name='subnet',
name='dns_nameservers',
field=waldur_core.core.fields.JSONField(default=list, help_text='List of DNS name servers associated with the subnet.'),
),
migrations.AlterField(
model_name='volume',
name='action_details',
field=waldur_core.core.fields.JSONField(default=dict),
),
]
| true | true |
f7f94ac3f31089c24b0d2beee5188d6442c953c4 | 2,501 | py | Python | setup.py | molssi-seamm/loop_step | 847da7f69a6fffaefc4655cb05ecf043f4adf64e | [
"BSD-3-Clause"
] | null | null | null | setup.py | molssi-seamm/loop_step | 847da7f69a6fffaefc4655cb05ecf043f4adf64e | [
"BSD-3-Clause"
] | 13 | 2019-08-21T13:34:02.000Z | 2021-12-21T22:38:46.000Z | setup.py | molssi-seamm/loop_step | 847da7f69a6fffaefc4655cb05ecf043f4adf64e | [
"BSD-3-Clause"
] | 1 | 2022-01-16T11:40:19.000Z | 2022-01-16T11:40:19.000Z | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""loop_step
A SEAMM plug-in which provides loops in flowcharts.
"""
import sys
from setuptools import setup, find_packages
import versioneer
short_description = __doc__.splitlines()[1]
# from https://github.com/pytest-dev/pytest-runner#conditional-requirement
needs_pytest = {'pytest', 'test', 'ptr'}.intersection(sys.argv)
pytest_runner = ['pytest-runner'] if needs_pytest else []
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
with open('requirements_install.txt') as fd:
requirements = fd.read()
setup_requirements = [
'pytest-runner',
]
test_requirements = [
'pytest',
]
setup(
name='loop_step',
author="Paul Saxe",
author_email='psaxe@molssi.org',
description=short_description,
long_description=readme + '\n\n' + history,
long_description_content_type='text/x-rst',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
license='BSD-3-Clause',
url='https://github.com/molssi-seamm/loop_step',
packages=find_packages(include=['loop_step']),
include_package_data=True,
# Allows `setup.py test` to work correctly with pytest
setup_requires=[] + pytest_runner,
# Required packages, pulls from pip if needed; do not use for Conda
# deployment
install_requires=requirements,
test_suite='tests',
# Valid platforms your code works on, adjust to your flavor
platforms=['Linux',
'Mac OS-X',
'Unix',
'Windows'],
# Manual control if final package is compressible or not, set False to
# prevent the .egg from being made
zip_safe=False,
keywords=['SEAMM', 'plug-in', 'flowchart', 'control', 'loops'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering :: Chemistry',
'Topic :: Scientific/Engineering :: Physics',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
],
entry_points={
'org.molssi.seamm': [
'Loop = loop_step:LoopStep',
],
'org.molssi.seamm.tk': [
'Loop = loop_step:LoopStep',
],
}
)
| 28.101124 | 74 | 0.643743 |
import sys
from setuptools import setup, find_packages
import versioneer
short_description = __doc__.splitlines()[1]
', 'test', 'ptr'}.intersection(sys.argv)
pytest_runner = ['pytest-runner'] if needs_pytest else []
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
with open('requirements_install.txt') as fd:
requirements = fd.read()
setup_requirements = [
'pytest-runner',
]
test_requirements = [
'pytest',
]
setup(
name='loop_step',
author="Paul Saxe",
author_email='psaxe@molssi.org',
description=short_description,
long_description=readme + '\n\n' + history,
long_description_content_type='text/x-rst',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
license='BSD-3-Clause',
url='https://github.com/molssi-seamm/loop_step',
packages=find_packages(include=['loop_step']),
include_package_data=True,
setup_requires=[] + pytest_runner,
install_requires=requirements,
test_suite='tests',
platforms=['Linux',
'Mac OS-X',
'Unix',
'Windows'],
zip_safe=False,
keywords=['SEAMM', 'plug-in', 'flowchart', 'control', 'loops'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering :: Chemistry',
'Topic :: Scientific/Engineering :: Physics',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
],
entry_points={
'org.molssi.seamm': [
'Loop = loop_step:LoopStep',
],
'org.molssi.seamm.tk': [
'Loop = loop_step:LoopStep',
],
}
)
| true | true |
f7f94b6efd460bf8cf1b140206b0c56c8c6bdf68 | 9,716 | py | Python | src/scripts/tests/test_suricata_alert_watcher.py | obsrvbl/ona | c0a3d464e1a53a41d1bc39c3595addf801b8b8ba | [
"Apache-2.0"
] | 12 | 2018-03-20T21:39:10.000Z | 2021-04-13T04:32:43.000Z | src/scripts/tests/test_suricata_alert_watcher.py | obsrvbl/ona | c0a3d464e1a53a41d1bc39c3595addf801b8b8ba | [
"Apache-2.0"
] | 2 | 2018-09-18T16:35:36.000Z | 2021-04-13T13:41:40.000Z | src/scripts/tests/test_suricata_alert_watcher.py | obsrvbl/ona | c0a3d464e1a53a41d1bc39c3595addf801b8b8ba | [
"Apache-2.0"
] | 11 | 2017-07-24T12:51:40.000Z | 2021-08-23T05:06:18.000Z | # Copyright 2015 Observable Networks
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from datetime import datetime
from glob import glob
from os import path, rename
from subprocess import CalledProcessError
from tempfile import TemporaryDirectory
from unittest import TestCase
from unittest.mock import call, MagicMock, patch
from ona_service.suricata_alert_watcher import (
_compress_log,
SuricataAlertWatcher,
MANAGE_SCRIPT,
SURICATA_LOGNAME,
)
def dummy_get_ip():
return '10.1.1.1'
def dummy_utcoffset():
return 0
patch_path = 'ona_service.suricata_alert_watcher.{}'.format
class SuricataAlertWatcherTest(TestCase):
def setUp(self):
self.temp_dir = TemporaryDirectory()
def tearDown(self):
self.temp_dir.cleanup()
@patch(patch_path('check_call'), autospec=True)
def test_compress_log(self, mock_check_call):
in_path = '/tmp/obsrvbl/eve.json.12345678.archived'
out_path = '/tmp/obsrvbl/eve.json.12345678.archived.gz'
# No error -> file is compressed
self.assertEqual(_compress_log(in_path), out_path)
# Error -> file is not compressed
mock_check_call.side_effect = CalledProcessError(1, 'gzip')
self.assertEqual(_compress_log(in_path), in_path)
# Check for correct call
expected_call = 'gzip -f {}'.format(in_path).split(' ')
mock_check_call.assert_called_with(expected_call)
@patch(patch_path('check_output'), autospec=True)
def test_rotate_logs(self, mock_check_output):
watcher = SuricataAlertWatcher()
# Success
mock_check_output.return_value = 0
watcher._rotate_logs()
mock_check_output.assert_called_once_with(
['sudo', '-u', 'suricata', MANAGE_SCRIPT, 'rotate-logs']
)
# Failure - don't die
mock_check_output.side_effect = CalledProcessError(1, '')
watcher._rotate_logs()
@patch(patch_path('get_ip'), dummy_get_ip)
@patch(patch_path('utcoffset'), dummy_utcoffset)
def test_upload(self):
file1 = path.join(self.temp_dir.name, 'eve.json.foo.archived')
file2 = path.join(self.temp_dir.name, 'eve.json.bar.archived')
ignored = path.join(self.temp_dir.name, 'ignored')
with open(file1, 'w'):
pass
with open(file2, 'w'):
pass
with open(ignored, 'w'):
pass
now = datetime(2015, 3, 12)
watcher = SuricataAlertWatcher(log_dir=self.temp_dir.name)
watcher.api = MagicMock()
watcher.api.send_file.return_value = 'send_destination'
watcher._upload(now)
self.assertFalse(path.exists(file1))
self.assertFalse(path.exists(file2))
self.assertTrue(path.exists(ignored))
self.assertCountEqual(watcher.api.send_file.call_args_list, [
call('logs', file1, now, suffix='suricata'),
call('logs', file2, now, suffix='suricata'),
])
watcher.api.send_signal.assert_called_with('logs', {
'path': 'send_destination',
'utcoffset': 0,
'log_type': 'suricata',
'ip': '10.1.1.1',
})
self.assertEquals(len(watcher.api.send_signal.call_args_list), 2)
def test_upload_compressed(self):
watcher = SuricataAlertWatcher(log_dir=self.temp_dir.name)
watcher.api = MagicMock()
# Write some fake data
outfile_name = '{}.12345678.archived'.format(SURICATA_LOGNAME)
outfile_path = path.join(self.temp_dir.name, outfile_name)
with open(outfile_path, 'w') as outfile:
print('I am but a meer cat.', file=outfile)
# Make the call
now = datetime.now()
watcher._upload(now, compress=True)
# Ensure API calls are correct
watcher.api.send_file.assert_called_once_with(
'logs',
'{}.gz'.format(outfile_path),
now,
suffix='suricata'
)
self.assertEqual(watcher.api.send_signal.call_count, 1)
# Ensure that directory was cleaned up
self.assertEqual(glob(path.join(self.temp_dir.name, '*.*')), [])
@patch(patch_path('get_ip'), dummy_get_ip)
@patch(patch_path('utcoffset'), dummy_utcoffset)
def test_upload_nothing(self):
now = datetime(2015, 3, 12)
watcher = SuricataAlertWatcher(log_dir=self.temp_dir.name)
watcher.api = MagicMock()
watcher.api.send_file.return_value = 'send_destination'
watcher._upload(now)
self.assertEquals(watcher.api.send_file.call_args_list, [])
self.assertEquals(watcher.api.call_args_list, [])
@patch(patch_path('get_ip'), dummy_get_ip)
@patch(patch_path('utcoffset'), dummy_utcoffset)
@patch(patch_path('check_output'), autospec=True)
def test_rotate_then_upload(self, mock_check_output):
logfile = path.join(self.temp_dir.name, 'eve.json')
with open(logfile, 'w'):
pass
after_rename = '{}.{}.archived'.format(logfile, '12345678')
mock_check_output.return_value = 0
mock_check_output.side_effect = rename(logfile, after_rename)
now = datetime(2015, 3, 12)
watcher = SuricataAlertWatcher(log_dir=self.temp_dir.name)
watcher.api = MagicMock()
watcher.api.send_file.return_value = 'send_destination'
watcher._rotate_logs()
self.assertFalse(path.exists(logfile))
self.assertTrue(path.exists(after_rename))
watcher._upload(now)
self.assertFalse(path.exists(after_rename))
self.assertEquals(watcher.api.send_file.call_args_list, [
call('logs', after_rename, now, suffix='suricata'),
])
self.assertEquals(watcher.api.send_signal.call_args_list, [
call('logs', {
'path': 'send_destination',
'utcoffset': 0,
'log_type': 'suricata',
'ip': '10.1.1.1',
})
])
@patch(patch_path('check_output'), autospec=True)
def test_update_rules(self, mock_check_output):
watcher = SuricataAlertWatcher(log_dir=self.temp_dir.name)
watcher.api = MagicMock()
watcher.api.get_data.return_value.iter_content.return_value = [
b'foo', b'bar', b'oof'
]
my_rules = '{}/some.rules'.format(self.temp_dir.name)
with patch(patch_path('SURICATA_RULE_PATH'), my_rules):
watcher._update_rules()
with open(my_rules) as r:
contents = r.read()
self.assertEquals(contents, 'foobaroof')
mock_check_output.assert_called_once_with(
['sudo', '-u', 'suricata', MANAGE_SCRIPT, 'reload-config']
)
watcher.api.get_data.assert_called_once_with('suricata-rules')
@patch(patch_path('SuricataAlertWatcher._rotate_logs'), autospec=True)
@patch(patch_path('SuricataAlertWatcher._upload'), autospec=True)
@patch(patch_path('SuricataAlertWatcher._update_rules'), autospec=True)
def test_execute(self, mock_rules, mock_upload, mock_rotate_logs):
watcher = SuricataAlertWatcher()
# Rules exist
rule_path = path.join(self.temp_dir.name, 'downloaded.rules')
with open(rule_path, 'wb') as outfile:
outfile.write(b'rule_data\n')
# 2015 was a long time ago, so it's time to update
with patch(patch_path('SURICATA_RULE_PATH'), rule_path):
now = datetime(2015, 1, 1)
watcher.execute(now)
mock_rotate_logs.assert_called_with(watcher)
mock_upload.assert_called_with(watcher, now, compress=True)
mock_rules.assert_called_with(watcher)
@patch(patch_path('utcnow'), autospec=True)
@patch(patch_path('SuricataAlertWatcher._rotate_logs'), autospec=True)
@patch(patch_path('SuricataAlertWatcher._upload'), autospec=True)
@patch(patch_path('SuricataAlertWatcher._update_rules'), autospec=True)
def test_execute_no_rules(
self, mock_rules, mock_upload, mock_rotate_logs, mock_utc
):
watcher = SuricataAlertWatcher()
rule_path = path.join(self.temp_dir.name, 'downloaded.rules')
# 2015 is now, according to this test, so it's not time to update.
# However, the rule file doesn't exist - so we will.
now = datetime(2015, 1, 1)
mock_utc.return_value = now
with patch(patch_path('SURICATA_RULE_PATH'), rule_path):
watcher.execute(now)
mock_rotate_logs.assert_called_with(watcher)
mock_upload.assert_called_with(watcher, now, compress=True)
self.assertEquals(mock_rules.call_count, 1)
@patch(patch_path('check_output'), autospec=True)
def test_execute_no_suricata(self, mock_check_output):
watcher = SuricataAlertWatcher()
watcher.api = MagicMock()
# It's time to update, but the rule directory doesn't exist.
# So we won't.
rule_path = path.join(
self.temp_dir.name, 'different-dir/downloaded.rules'
)
with patch(patch_path('SURICATA_RULE_PATH'), rule_path):
now = datetime(2015, 1, 1)
watcher.execute(now)
self.assertFalse(watcher.api.mock_calls)
| 36.389513 | 75 | 0.656237 |
from datetime import datetime
from glob import glob
from os import path, rename
from subprocess import CalledProcessError
from tempfile import TemporaryDirectory
from unittest import TestCase
from unittest.mock import call, MagicMock, patch
from ona_service.suricata_alert_watcher import (
_compress_log,
SuricataAlertWatcher,
MANAGE_SCRIPT,
SURICATA_LOGNAME,
)
def dummy_get_ip():
return '10.1.1.1'
def dummy_utcoffset():
return 0
patch_path = 'ona_service.suricata_alert_watcher.{}'.format
class SuricataAlertWatcherTest(TestCase):
def setUp(self):
self.temp_dir = TemporaryDirectory()
def tearDown(self):
self.temp_dir.cleanup()
@patch(patch_path('check_call'), autospec=True)
def test_compress_log(self, mock_check_call):
in_path = '/tmp/obsrvbl/eve.json.12345678.archived'
out_path = '/tmp/obsrvbl/eve.json.12345678.archived.gz'
self.assertEqual(_compress_log(in_path), out_path)
mock_check_call.side_effect = CalledProcessError(1, 'gzip')
self.assertEqual(_compress_log(in_path), in_path)
expected_call = 'gzip -f {}'.format(in_path).split(' ')
mock_check_call.assert_called_with(expected_call)
@patch(patch_path('check_output'), autospec=True)
def test_rotate_logs(self, mock_check_output):
watcher = SuricataAlertWatcher()
mock_check_output.return_value = 0
watcher._rotate_logs()
mock_check_output.assert_called_once_with(
['sudo', '-u', 'suricata', MANAGE_SCRIPT, 'rotate-logs']
)
mock_check_output.side_effect = CalledProcessError(1, '')
watcher._rotate_logs()
@patch(patch_path('get_ip'), dummy_get_ip)
@patch(patch_path('utcoffset'), dummy_utcoffset)
def test_upload(self):
file1 = path.join(self.temp_dir.name, 'eve.json.foo.archived')
file2 = path.join(self.temp_dir.name, 'eve.json.bar.archived')
ignored = path.join(self.temp_dir.name, 'ignored')
with open(file1, 'w'):
pass
with open(file2, 'w'):
pass
with open(ignored, 'w'):
pass
now = datetime(2015, 3, 12)
watcher = SuricataAlertWatcher(log_dir=self.temp_dir.name)
watcher.api = MagicMock()
watcher.api.send_file.return_value = 'send_destination'
watcher._upload(now)
self.assertFalse(path.exists(file1))
self.assertFalse(path.exists(file2))
self.assertTrue(path.exists(ignored))
self.assertCountEqual(watcher.api.send_file.call_args_list, [
call('logs', file1, now, suffix='suricata'),
call('logs', file2, now, suffix='suricata'),
])
watcher.api.send_signal.assert_called_with('logs', {
'path': 'send_destination',
'utcoffset': 0,
'log_type': 'suricata',
'ip': '10.1.1.1',
})
self.assertEquals(len(watcher.api.send_signal.call_args_list), 2)
def test_upload_compressed(self):
watcher = SuricataAlertWatcher(log_dir=self.temp_dir.name)
watcher.api = MagicMock()
# Write some fake data
outfile_name = '{}.12345678.archived'.format(SURICATA_LOGNAME)
outfile_path = path.join(self.temp_dir.name, outfile_name)
with open(outfile_path, 'w') as outfile:
print('I am but a meer cat.', file=outfile)
# Make the call
now = datetime.now()
watcher._upload(now, compress=True)
# Ensure API calls are correct
watcher.api.send_file.assert_called_once_with(
'logs',
'{}.gz'.format(outfile_path),
now,
suffix='suricata'
)
self.assertEqual(watcher.api.send_signal.call_count, 1)
# Ensure that directory was cleaned up
self.assertEqual(glob(path.join(self.temp_dir.name, '*.*')), [])
@patch(patch_path('get_ip'), dummy_get_ip)
@patch(patch_path('utcoffset'), dummy_utcoffset)
def test_upload_nothing(self):
now = datetime(2015, 3, 12)
watcher = SuricataAlertWatcher(log_dir=self.temp_dir.name)
watcher.api = MagicMock()
watcher.api.send_file.return_value = 'send_destination'
watcher._upload(now)
self.assertEquals(watcher.api.send_file.call_args_list, [])
self.assertEquals(watcher.api.call_args_list, [])
@patch(patch_path('get_ip'), dummy_get_ip)
@patch(patch_path('utcoffset'), dummy_utcoffset)
@patch(patch_path('check_output'), autospec=True)
def test_rotate_then_upload(self, mock_check_output):
logfile = path.join(self.temp_dir.name, 'eve.json')
with open(logfile, 'w'):
pass
after_rename = '{}.{}.archived'.format(logfile, '12345678')
mock_check_output.return_value = 0
mock_check_output.side_effect = rename(logfile, after_rename)
now = datetime(2015, 3, 12)
watcher = SuricataAlertWatcher(log_dir=self.temp_dir.name)
watcher.api = MagicMock()
watcher.api.send_file.return_value = 'send_destination'
watcher._rotate_logs()
self.assertFalse(path.exists(logfile))
self.assertTrue(path.exists(after_rename))
watcher._upload(now)
self.assertFalse(path.exists(after_rename))
self.assertEquals(watcher.api.send_file.call_args_list, [
call('logs', after_rename, now, suffix='suricata'),
])
self.assertEquals(watcher.api.send_signal.call_args_list, [
call('logs', {
'path': 'send_destination',
'utcoffset': 0,
'log_type': 'suricata',
'ip': '10.1.1.1',
})
])
@patch(patch_path('check_output'), autospec=True)
def test_update_rules(self, mock_check_output):
watcher = SuricataAlertWatcher(log_dir=self.temp_dir.name)
watcher.api = MagicMock()
watcher.api.get_data.return_value.iter_content.return_value = [
b'foo', b'bar', b'oof'
]
my_rules = '{}/some.rules'.format(self.temp_dir.name)
with patch(patch_path('SURICATA_RULE_PATH'), my_rules):
watcher._update_rules()
with open(my_rules) as r:
contents = r.read()
self.assertEquals(contents, 'foobaroof')
mock_check_output.assert_called_once_with(
['sudo', '-u', 'suricata', MANAGE_SCRIPT, 'reload-config']
)
watcher.api.get_data.assert_called_once_with('suricata-rules')
@patch(patch_path('SuricataAlertWatcher._rotate_logs'), autospec=True)
@patch(patch_path('SuricataAlertWatcher._upload'), autospec=True)
@patch(patch_path('SuricataAlertWatcher._update_rules'), autospec=True)
def test_execute(self, mock_rules, mock_upload, mock_rotate_logs):
watcher = SuricataAlertWatcher()
# Rules exist
rule_path = path.join(self.temp_dir.name, 'downloaded.rules')
with open(rule_path, 'wb') as outfile:
outfile.write(b'rule_data\n')
# 2015 was a long time ago, so it's time to update
with patch(patch_path('SURICATA_RULE_PATH'), rule_path):
now = datetime(2015, 1, 1)
watcher.execute(now)
mock_rotate_logs.assert_called_with(watcher)
mock_upload.assert_called_with(watcher, now, compress=True)
mock_rules.assert_called_with(watcher)
@patch(patch_path('utcnow'), autospec=True)
@patch(patch_path('SuricataAlertWatcher._rotate_logs'), autospec=True)
@patch(patch_path('SuricataAlertWatcher._upload'), autospec=True)
@patch(patch_path('SuricataAlertWatcher._update_rules'), autospec=True)
def test_execute_no_rules(
self, mock_rules, mock_upload, mock_rotate_logs, mock_utc
):
watcher = SuricataAlertWatcher()
rule_path = path.join(self.temp_dir.name, 'downloaded.rules')
# However, the rule file doesn't exist - so we will.
now = datetime(2015, 1, 1)
mock_utc.return_value = now
with patch(patch_path('SURICATA_RULE_PATH'), rule_path):
watcher.execute(now)
mock_rotate_logs.assert_called_with(watcher)
mock_upload.assert_called_with(watcher, now, compress=True)
self.assertEquals(mock_rules.call_count, 1)
@patch(patch_path('check_output'), autospec=True)
def test_execute_no_suricata(self, mock_check_output):
watcher = SuricataAlertWatcher()
watcher.api = MagicMock()
rule_path = path.join(
self.temp_dir.name, 'different-dir/downloaded.rules'
)
with patch(patch_path('SURICATA_RULE_PATH'), rule_path):
now = datetime(2015, 1, 1)
watcher.execute(now)
self.assertFalse(watcher.api.mock_calls)
| true | true |
f7f94bbe72953ace702554472502a6d69589d097 | 11,859 | py | Python | jams/str2tex.py | MuellerSeb/jams_python | 1bca04557da79d8f8a4c447f5ccc517c40ab7dfc | [
"MIT"
] | 9 | 2019-06-03T03:24:16.000Z | 2021-12-03T07:14:00.000Z | jams/str2tex.py | MuellerSeb/jams_python | 1bca04557da79d8f8a4c447f5ccc517c40ab7dfc | [
"MIT"
] | 6 | 2020-03-25T21:56:59.000Z | 2021-11-08T14:58:27.000Z | jams/str2tex.py | MuellerSeb/jams_python | 1bca04557da79d8f8a4c447f5ccc517c40ab7dfc | [
"MIT"
] | 5 | 2019-10-17T12:04:33.000Z | 2021-09-28T07:45:07.000Z | #!/usr/bin/env python
from __future__ import division, absolute_import, print_function
import numpy as np
__all__ = ['str2tex']
def str2tex(strin, space2linebreak=False, bold=False, italic=False, usetex=True):
"""
Convert strings to LaTeX strings in math environement used by matplotlib's usetex.
Strings are embedded into $\mathrm{strin}$ be default but can be embedded into
\mathbf and \mathit.
Spaces are escaped but can be replaced by linebreaks.
Definition
----------
def str2tex(strin, space2linebreak=False, bold=False, italic=False):
Input
-----
list/ND-array of strings
Optional Input
--------------
space2linebreak True: replace space (' ') by linebreak ('\n')
bold True: use \mathbf
italic True: use \mathit
usetex False: do only space2linebreak otherwise nothing
Output
------
list/ND-array of strings that can be used in plots independent of usetex.
Examples
--------
# replace all \ by \\ in docstring in- and outputs
>>> strin = ['One', 'One-', 'One-Two', 'One Two', 'One\\nTwo', 'A $S_{Ti}$ is great\\nbut use-less']
>>> print(str2tex(strin))
['$\\\\mathrm{One}$', '$\\\\mathrm{One}$$\\\\textrm{-}$', '$\\\\mathrm{One}$$\\\\textrm{-}$$\\\\mathrm{Two}$', '$\\\\mathrm{One\\\\ Two}$', '$\\\\mathrm{One}$ \\n $\\\\mathrm{Two}$', '$\\\\mathrm{A\\\\ }$$S_{Ti}$$\\\\mathrm{\\\\ is\\\\ great}$ \\n $\\\\mathrm{but\\\\ use}$$\\\\textrm{-}$$\\\\mathrm{less}$']
>>> print(str2tex(strin, bold=True))
['$\\\\mathbf{One}$', '$\\\\mathbf{One}$$\\\\textbf{-}$', '$\\\\mathbf{One}$$\\\\textbf{-}$$\\\\mathbf{Two}$', '$\\\\mathbf{One\\\\ Two}$', '$\\\\mathbf{One}$ \\n $\\\\mathbf{Two}$', '$\\\\mathbf{A\\\\ }$$S_{Ti}$$\\\\mathbf{\\\\ is\\\\ great}$ \\n $\\\\mathbf{but\\\\ use}$$\\\\textbf{-}$$\\\\mathbf{less}$']
>>> print(str2tex(strin, italic=True))
['$\\\\mathit{One}$', '$\\\\mathit{One}$$\\\\textit{-}$', '$\\\\mathit{One}$$\\\\textit{-}$$\\\\mathit{Two}$', '$\\\\mathit{One\\\\ Two}$', '$\\\\mathit{One}$ \\n $\\\\mathit{Two}$', '$\\\\mathit{A\\\\ }$$S_{Ti}$$\\\\mathit{\\\\ is\\\\ great}$ \\n $\\\\mathit{but\\\\ use}$$\\\\textit{-}$$\\\\mathit{less}$']
>>> print(str2tex(strin, space2linebreak=True))
['$\\\\mathrm{One}$', '$\\\\mathrm{One}$$\\\\textrm{-}$', '$\\\\mathrm{One}$$\\\\textrm{-}$$\\\\mathrm{Two}$', '$\\\\mathrm{One}$ \\n $\\\\mathrm{Two}$', '$\\\\mathrm{One}$ \\n $\\\\mathrm{Two}$', '$\\\\mathrm{A}$ \\n $\\\\mathrm{}$$S_{Ti}$$\\\\mathrm{ \\n $\\\\mathrm{is \\n $\\\\mathrm{great}$ \\n $\\\\mathrm{but \\n $\\\\mathrm{use}$$\\\\textrm{-}$$\\\\mathrm{less}$']
>>> print(str2tex(strin, space2linebreak=True, bold=True))
['$\\\\mathbf{One}$', '$\\\\mathbf{One}$$\\\\textbf{-}$', '$\\\\mathbf{One}$$\\\\textbf{-}$$\\\\mathbf{Two}$', '$\\\\mathbf{One}$ \\n $\\\\mathbf{Two}$', '$\\\\mathbf{One}$ \\n $\\\\mathbf{Two}$', '$\\\\mathbf{A}$ \\n $\\\\mathbf{}$$S_{Ti}$$\\\\mathbf{ \\n $\\\\mathbf{is \\n $\\\\mathbf{great}$ \\n $\\\\mathbf{but \\n $\\\\mathbf{use}$$\\\\textbf{-}$$\\\\mathbf{less}$']
>>> print(str2tex(strin, usetex=False))
['One', 'One-', 'One-Two', 'One Two', 'One\\nTwo', 'A $S_{Ti}$ is great\\nbut use-less']
>>> print(str2tex(strin, space2linebreak=True, usetex=False))
['One', 'One-', 'One-Two', 'One\\nTwo', 'One\\nTwo', 'A\\n$S_{Ti}$\\nis\\ngreat\\nbut\\nuse-less']
License
-------
This file is part of the JAMS Python package, distributed under the MIT
License. The JAMS Python package originates from the former UFZ Python library,
Department of Computational Hydrosystems, Helmholtz Centre for Environmental
Research - UFZ, Leipzig, Germany.
Copyright (c) 2015 Matthias Cuntz - mc (at) macu (dot) de
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.
History
-------
Written, MC, Oct 2015
"""
# Input type and shape
if isinstance(strin, list):
from copy import copy
istrin = copy(strin)
elif isinstance(strin, tuple):
istrin = list(strin)
elif isinstance(strin, np.ndarray):
istrin = list(strin.flatten())
else:
istrin = [strin]
# nstrin = len(istrin)
# font style
if (bold+italic) > 1:
raise ValueError('bold and italic are mutually exclusive.')
else:
if bold:
mtex = r'$\mathbf{'
ttex = r'$\textbf{'
elif italic:
mtex = r'$\mathit{'
ttex = r'$\textit{'
else:
mtex = r'$\mathrm{'
ttex = r'$\textrm{'
# helpers
a0 = chr(0) # ascii 0
# string replacements
rep_n = lambda s : s.replace('\n', '}$'+a0+'\n'+a0+mtex)
rep_down = lambda s : s.replace('_', '\_')
rep_up = lambda s : s.replace('^', '\^')
rep_hash = lambda s : s.replace('#', '\#')
rep_percent = lambda s : s.replace('%', '\%')
rep_space = lambda s : s.replace(' ', '\ ')
rep_minus = lambda s : s.replace('-', '}$'+ttex+'-}$'+mtex)
rep_a02space = lambda s : s.replace(a0, ' ')
rep_space2n = lambda s : s.replace(' ', '\n')
if usetex:
for j, s in enumerate(istrin):
if '$' in s:
# -, _, ^ only escaped if not between $
ss = s.split('$')
for ii in range(0,len(ss),2):
ss[ii] = mtex+ss[ii]+'}$'
# - not minus sign
if '-' in ss[ii]:
ss[ii] = rep_minus(ss[ii])
if ss[ii].endswith('{}$'): ss[ii] = ss[ii][:-11] # remove trailing $\mathrm{}$
# \n not in tex mode but normal matplotlib
if '\n' in ss[ii]: ss[ii] = rep_n(ss[ii])
# escape _
if '_' in ss[ii]: ss[ii] = rep_down(ss[ii])
# escape ^
if '^' in ss[ii]: ss[ii] = rep_up(ss[ii])
# escape #
if '#' in ss[ii]: ss[ii] = rep_hash(ss[ii])
# escape %
if ('%' in ss[ii]) and not ('\%' in ss[ii]) : ss[ii] = rep_percent(ss[ii])
istrin[j] = '$'.join(ss)
if s[0] == '$': istrin[j] = istrin[j][11:] # remove leading $\mathrm{}$ if started with $
else:
istrin[j] = mtex+s+'}$'
# - not minus sign
if '-' in istrin[j]:
istrin[j] = rep_minus(istrin[j])
if istrin[j].endswith('{}$'): istrin[j] = istrin[j][:-11] # remove trailing $\mathrm{}$
# \n not in tex mode but normal matplotlib
if '\n' in istrin[j]: istrin[j] = rep_n(istrin[j])
# escape _
if '_' in istrin[j]: istrin[j] = rep_down(istrin[j])
# escape ^
if '^' in istrin[j]: istrin[j] = rep_up(istrin[j])
# escape #
if '#' in istrin[j]: istrin[j] = rep_hash(istrin[j])
# escape %
if ('%' in istrin[j]) and not ('\%' in istrin[j]): istrin[j] = rep_percent(istrin[j])
# escape space or linebreak at space
if ' ' in istrin[j]:
if space2linebreak:
# line break
ic = istrin[j].split(' ')
for ii, iic in enumerate(ic):
if ii==0:
istrin[j] = iic + '}$'
else:
istrin[j] = istrin[j] + a0 + '\n' + a0 + mtex+ iic
else:
# escaped space
istrin[j] = rep_space(istrin[j])
# rm ascii character 0 around linebreaks introduced above
if a0 in istrin[j]: istrin[j] = rep_a02space(istrin[j])
else:
# escape %
if ('%' in istrin) and not ('\%' in istrin): istrin = rep_percent(istrin)
if space2linebreak: istrin = [ rep_space2n(i) for i in istrin ]
# Return right type
if isinstance(strin, list):
return istrin
elif isinstance(strin, tuple):
return tuple(istrin)
elif isinstance(strin, np.ndarray):
return np.array(istrin).reshape(strin.shape)
else:
return istrin[0]
if __name__ == '__main__':
import doctest
doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)
# strin = ['One', 'One-', 'One-Two', 'One Two', 'One\nTwo', 'A $S_{Ti}$ is great\nbut use-less']
# print(str2tex(strin))
# # ['$\\mathrm{One}$', '$\\mathrm{One}$$\\textrm{-}$', '$\\mathrm{One}$$\\textrm{-}$$\\mathrm{Two}$', '$\\mathrm{One\\ Two}$', '$\\mathrm{One}$ \n $\\mathrm{Two}$', '$\\mathrm{A\\ }$$S_{Ti}$$\\mathrm{\\ is\\ great}$ \n $\\mathrm{but\\ use}$$\\textrm{-}$$\\mathrm{less}$']
# print(str2tex(strin, bold=True))
# # ['$\\mathbf{One}$', '$\\mathbf{One}$$\\textbf{-}$', '$\\mathbf{One}$$\\textbf{-}$$\\mathbf{Two}$', '$\\mathbf{One\\ Two}$', '$\\mathbf{One}$ \n $\\mathbf{Two}$', '$\\mathbf{A\\ }$$S_{Ti}$$\\mathbf{\\ is\\ great}$ \n $\\mathbf{but\\ use}$$\\textbf{-}$$\\mathbf{less}$']
# print(str2tex(strin, italic=True))
# # ['$\\mathit{One}$', '$\\mathit{One}$$\\textit{-}$', '$\\mathit{One}$$\\textit{-}$$\\mathit{Two}$', '$\\mathit{One\\ Two}$', '$\\mathit{One}$ \n $\\mathit{Two}$', '$\\mathit{A\\ }$$S_{Ti}$$\\mathit{\\ is\\ great}$ \n $\\mathit{but\\ use}$$\\textit{-}$$\\mathit{less}$']
# print(str2tex(strin, space2linebreak=True))
# # ['$\\mathrm{One}$', '$\\mathrm{One}$$\\textrm{-}$', '$\\mathrm{One}$$\\textrm{-}$$\\mathrm{Two}$', '$\\mathrm{One}$ \n $\\mathrm{Two}$', '$\\mathrm{One}$ \n $\\mathrm{Two}$', '$\\mathrm{A}$ \n $\\mathrm{}$$S_{Ti}$$\\mathrm{ \n $\\mathrm{is \n $\\mathrm{great}$ \n $\\mathrm{but \n $\\mathrm{use}$$\\textrm{-}$$\\mathrm{less}$']
# print(str2tex(strin, space2linebreak=True, bold=True))
# # ['$\\mathbf{One}$', '$\\mathbf{One}$$\\textbf{-}$', '$\\mathbf{One}$$\\textbf{-}$$\\mathbf{Two}$', '$\\mathbf{One}$ \n $\\mathbf{Two}$', '$\\mathbf{One}$ \n $\\mathbf{Two}$', '$\\mathbf{A}$ \n $\\mathbf{}$$S_{Ti}$$\\mathbf{ \n $\\mathbf{is \n $\\mathbf{great}$ \n $\\mathbf{but \n $\\mathbf{use}$$\\textbf{-}$$\\mathbf{less}$']
# print(str2tex(strin, usetex=False))
# # ['One', 'One-', 'One-Two', 'One Two', 'One\nTwo', 'A $S_{Ti}$ is great\nbut use-less']
# print(str2tex(strin, space2linebreak=True, usetex=False))
# # ['One', 'One-', 'One-Two', 'One\nTwo', 'One\nTwo', 'A\n$S_{Ti}$\nis\ngreat\nbut\nuse-less']
| 53.904545 | 380 | 0.511089 |
from __future__ import division, absolute_import, print_function
import numpy as np
__all__ = ['str2tex']
def str2tex(strin, space2linebreak=False, bold=False, italic=False, usetex=True):
if isinstance(strin, list):
from copy import copy
istrin = copy(strin)
elif isinstance(strin, tuple):
istrin = list(strin)
elif isinstance(strin, np.ndarray):
istrin = list(strin.flatten())
else:
istrin = [strin]
if (bold+italic) > 1:
raise ValueError('bold and italic are mutually exclusive.')
else:
if bold:
mtex = r'$\mathbf{'
ttex = r'$\textbf{'
elif italic:
mtex = r'$\mathit{'
ttex = r'$\textit{'
else:
mtex = r'$\mathrm{'
ttex = r'$\textrm{'
a0 = chr(0)
rep_n = lambda s : s.replace('\n', '}$'+a0+'\n'+a0+mtex)
rep_down = lambda s : s.replace('_', '\_')
rep_up = lambda s : s.replace('^', '\^')
rep_hash = lambda s : s.replace('#', '\#')
rep_percent = lambda s : s.replace('%', '\%')
rep_space = lambda s : s.replace(' ', '\ ')
rep_minus = lambda s : s.replace('-', '}$'+ttex+'-}$'+mtex)
rep_a02space = lambda s : s.replace(a0, ' ')
rep_space2n = lambda s : s.replace(' ', '\n')
if usetex:
for j, s in enumerate(istrin):
if '$' in s:
ss = s.split('$')
for ii in range(0,len(ss),2):
ss[ii] = mtex+ss[ii]+'}$'
if '-' in ss[ii]:
ss[ii] = rep_minus(ss[ii])
if ss[ii].endswith('{}$'): ss[ii] = ss[ii][:-11]
if '\n' in ss[ii]: ss[ii] = rep_n(ss[ii])
if '_' in ss[ii]: ss[ii] = rep_down(ss[ii])
if '^' in ss[ii]: ss[ii] = rep_up(ss[ii])
if '#' in ss[ii]: ss[ii] = rep_hash(ss[ii])
if ('%' in ss[ii]) and not ('\%' in ss[ii]) : ss[ii] = rep_percent(ss[ii])
istrin[j] = '$'.join(ss)
if s[0] == '$': istrin[j] = istrin[j][11:]
else:
istrin[j] = mtex+s+'}$'
if '-' in istrin[j]:
istrin[j] = rep_minus(istrin[j])
if istrin[j].endswith('{}$'): istrin[j] = istrin[j][:-11]
if '\n' in istrin[j]: istrin[j] = rep_n(istrin[j])
if '_' in istrin[j]: istrin[j] = rep_down(istrin[j])
if '^' in istrin[j]: istrin[j] = rep_up(istrin[j])
if '#' in istrin[j]: istrin[j] = rep_hash(istrin[j])
if ('%' in istrin[j]) and not ('\%' in istrin[j]): istrin[j] = rep_percent(istrin[j])
if ' ' in istrin[j]:
if space2linebreak:
ic = istrin[j].split(' ')
for ii, iic in enumerate(ic):
if ii==0:
istrin[j] = iic + '}$'
else:
istrin[j] = istrin[j] + a0 + '\n' + a0 + mtex+ iic
else:
istrin[j] = rep_space(istrin[j])
if a0 in istrin[j]: istrin[j] = rep_a02space(istrin[j])
else:
if ('%' in istrin) and not ('\%' in istrin): istrin = rep_percent(istrin)
if space2linebreak: istrin = [ rep_space2n(i) for i in istrin ]
if isinstance(strin, list):
return istrin
elif isinstance(strin, tuple):
return tuple(istrin)
elif isinstance(strin, np.ndarray):
return np.array(istrin).reshape(strin.shape)
else:
return istrin[0]
if __name__ == '__main__':
import doctest
doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)
| true | true |
f7f94c320e40536edc61fa1ee46b772e690b3986 | 3,880 | py | Python | instaproject/settings.py | Michellemukami/the-hood | 0a1aea481065bb3187ec6a74f09761a4332389fe | [
"MIT"
] | null | null | null | instaproject/settings.py | Michellemukami/the-hood | 0a1aea481065bb3187ec6a74f09761a4332389fe | [
"MIT"
] | 4 | 2020-06-05T22:57:54.000Z | 2021-09-08T01:19:22.000Z | instaproject/settings.py | Michellemukami/the-hood | 0a1aea481065bb3187ec6a74f09761a4332389fe | [
"MIT"
] | null | null | null | """
Django settings for instaproject project.
Generated by 'django-admin startproject' using Django 1.11.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
import django_heroku
from decouple import config
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '=yf(p_f0ad1-aab7lxq_bx^fgsx^p0hj2_v4_qg$1###81x*j*'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'instaapp.apps.InstaappConfig',
'django.contrib.humanize',
'tinymce',
'bootstrap4',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'instaproject.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.media',
],
},
},
]
WSGI_APPLICATION = 'instaproject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'mello',
'USER': 'kami',
'PASSWORD':'kami',
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# Email configurations remember to install python-decouple
LOGIN_REDIRECT_URL= '/edit_profile/'
django_heroku.settings(locals()) | 26.758621 | 91 | 0.703093 |
import os
import django_heroku
from decouple import config
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = '=yf(p_f0ad1-aab7lxq_bx^fgsx^p0hj2_v4_qg$1###81x*j*'
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'instaapp.apps.InstaappConfig',
'django.contrib.humanize',
'tinymce',
'bootstrap4',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'instaproject.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.media',
],
},
},
]
WSGI_APPLICATION = 'instaproject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'mello',
'USER': 'kami',
'PASSWORD':'kami',
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# Email configurations remember to install python-decouple
LOGIN_REDIRECT_URL= '/edit_profile/'
django_heroku.settings(locals()) | true | true |
f7f94c44669ee262bc44ac23bd7ba4b5a217f8ed | 1,933 | py | Python | src/tests/transform/test_grayscale_transform.py | allanchua101/ipynta | 861c36b1c2d675611fcd5ed478d658f8180d03af | [
"MIT"
] | null | null | null | src/tests/transform/test_grayscale_transform.py | allanchua101/ipynta | 861c36b1c2d675611fcd5ed478d658f8180d03af | [
"MIT"
] | null | null | null | src/tests/transform/test_grayscale_transform.py | allanchua101/ipynta | 861c36b1c2d675611fcd5ed478d658f8180d03af | [
"MIT"
] | null | null | null | from ipynta.sourcing import DirectorySniffer
from ipynta.loaders import PillowLoader
from ipynta.transform import GrayscaleTransform
from os import path
import pytest
SAMPLES_DIR = path.dirname(path.abspath(__file__)) + "/sample_images/grayscale"
@pytest.fixture
def sample_images():
img_list = DirectorySniffer().get_img_paths(SAMPLES_DIR)
return PillowLoader().load(img_list)
def _check_if_grayscale(img):
"""Method used for checking if an image is grayscale or colored.
Args:
images (PIL.Image): Image to check.
Returns:
boolean: True if the image is grayscale, False otherwise.
"""
tmp = img.convert('RGB')
w, h = img.size
for i in range(w):
for j in range(h):
r, g, b = tmp.getpixel((i,j))
if r != g != b:
return False
return True
def test_grayscale_transform_init():
try:
GrayscaleTransform()
except Exception:
pytest.fail("GrayscaleTransform constructor failed")
@pytest.mark.parametrize("test_input", [
(None),
([]),
])
def test_grayscale_transform_vs_empty_list(test_input):
grayscale_img_list = GrayscaleTransform().execute(test_input)
output_count = len(grayscale_img_list)
assert(output_count == 0)
assert(isinstance(grayscale_img_list, list))
def test_grayscale_output_count(sample_images):
grayscale_img_list = GrayscaleTransform().execute(sample_images)
output_count = len(grayscale_img_list)
assert(output_count == len(sample_images))
def test_grayscale_output_type(sample_images):
grayscale_img_list = GrayscaleTransform().execute(sample_images)
assert(isinstance(grayscale_img_list, list))
def test_grayscale_output_colors(sample_images):
grayscale_img_list = GrayscaleTransform().execute(sample_images)
grayscale_flags = [_check_if_grayscale(img) for img in grayscale_img_list]
assert(all(grayscale_flags))
| 28.426471 | 80 | 0.722193 | from ipynta.sourcing import DirectorySniffer
from ipynta.loaders import PillowLoader
from ipynta.transform import GrayscaleTransform
from os import path
import pytest
SAMPLES_DIR = path.dirname(path.abspath(__file__)) + "/sample_images/grayscale"
@pytest.fixture
def sample_images():
img_list = DirectorySniffer().get_img_paths(SAMPLES_DIR)
return PillowLoader().load(img_list)
def _check_if_grayscale(img):
tmp = img.convert('RGB')
w, h = img.size
for i in range(w):
for j in range(h):
r, g, b = tmp.getpixel((i,j))
if r != g != b:
return False
return True
def test_grayscale_transform_init():
try:
GrayscaleTransform()
except Exception:
pytest.fail("GrayscaleTransform constructor failed")
@pytest.mark.parametrize("test_input", [
(None),
([]),
])
def test_grayscale_transform_vs_empty_list(test_input):
grayscale_img_list = GrayscaleTransform().execute(test_input)
output_count = len(grayscale_img_list)
assert(output_count == 0)
assert(isinstance(grayscale_img_list, list))
def test_grayscale_output_count(sample_images):
grayscale_img_list = GrayscaleTransform().execute(sample_images)
output_count = len(grayscale_img_list)
assert(output_count == len(sample_images))
def test_grayscale_output_type(sample_images):
grayscale_img_list = GrayscaleTransform().execute(sample_images)
assert(isinstance(grayscale_img_list, list))
def test_grayscale_output_colors(sample_images):
grayscale_img_list = GrayscaleTransform().execute(sample_images)
grayscale_flags = [_check_if_grayscale(img) for img in grayscale_img_list]
assert(all(grayscale_flags))
| true | true |
f7f94c456f7d954581afe1af1e91b9e011152a8d | 352 | py | Python | vnpy/app/fcoin_clean_order/__init__.py | xiaoxiaoleo/fmexminer | cf4ff2aa041f749e8b2c73607dcf2f50199a81c2 | [
"Apache-2.0"
] | 16 | 2019-10-31T03:15:24.000Z | 2021-11-07T20:27:54.000Z | vnpy/app/fmex_miner_guadan/__init__.py | xiaoxiaoleo/fmexminer | cf4ff2aa041f749e8b2c73607dcf2f50199a81c2 | [
"Apache-2.0"
] | 2 | 2019-10-31T03:16:37.000Z | 2019-12-03T07:55:28.000Z | vnpy/app/fcoin_clean_order/__init__.py | xiaoxiaoleo/fmexminer | cf4ff2aa041f749e8b2c73607dcf2f50199a81c2 | [
"Apache-2.0"
] | 7 | 2019-11-24T04:24:48.000Z | 2022-01-29T16:21:03.000Z | from pathlib import Path
from vnpy.trader.app import BaseApp
from .engine import AlgoEngine, APP_NAME
class AlgoTradingApp(BaseApp):
""""""
app_name = APP_NAME
app_module = __module__
app_path = Path(__file__).parent
display_name = "算法交易"
engine_class = AlgoEngine
widget_name = "AlgoManager"
icon_name = "algo.ico"
| 20.705882 | 40 | 0.707386 | from pathlib import Path
from vnpy.trader.app import BaseApp
from .engine import AlgoEngine, APP_NAME
class AlgoTradingApp(BaseApp):
app_name = APP_NAME
app_module = __module__
app_path = Path(__file__).parent
display_name = "算法交易"
engine_class = AlgoEngine
widget_name = "AlgoManager"
icon_name = "algo.ico"
| true | true |
f7f94c822c2ac221ef5668e02438174dc4634e03 | 10,565 | py | Python | pandapower/test/consistency_checks.py | hmaschke/pandapower-1 | 2e93969050d3d468ce57f73d358e97fabc6e5141 | [
"BSD-3-Clause"
] | 2 | 2019-11-01T11:01:41.000Z | 2022-02-07T12:55:55.000Z | pandapower/test/consistency_checks.py | hmaschke/pandapower-1 | 2e93969050d3d468ce57f73d358e97fabc6e5141 | [
"BSD-3-Clause"
] | null | null | null | pandapower/test/consistency_checks.py | hmaschke/pandapower-1 | 2e93969050d3d468ce57f73d358e97fabc6e5141 | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
# Copyright (c) 2016-2022 by University of Kassel and Fraunhofer Institute for Energy Economics
# and Energy System Technology (IEE), Kassel. All rights reserved.
import pandas as pd
from numpy import allclose, isclose
from pandapower.pf.runpp_3ph import runpp_3ph
from pandapower.results import get_relevant_elements
import pandapower as pp
def runpp_with_consistency_checks(net, **kwargs):
pp.runpp(net, **kwargs)
consistency_checks(net)
return True
def runpp_3ph_with_consistency_checks(net, **kwargs):
runpp_3ph(net, **kwargs)
consistency_checks_3ph(net)
return True
def rundcpp_with_consistency_checks(net, **kwargs):
pp.rundcpp(net, **kwargs)
consistency_checks(net, test_q=False)
return True
def consistency_checks(net, rtol=1e-3, test_q=True):
indices_consistent(net)
branch_loss_consistent_with_bus_feed_in(net, rtol)
element_power_consistent_with_bus_power(net, rtol, test_q)
def indices_consistent(net):
elements = get_relevant_elements()
for element in elements:
e_idx = net[element].index
res_idx = net["res_" + element].index
assert len(e_idx) == len(res_idx), "length of %s bus and res_%s indices do not match"%(element, element)
assert all(e_idx == res_idx), "%s bus and res_%s indices do not match"%(element, element)
def branch_loss_consistent_with_bus_feed_in(net, atol=1e-2):
"""
The surpluss of bus feed summed over all buses always has to be equal to the sum of losses in
all branches.
"""
# Active Power
bus_surplus_p = -net.res_bus.p_mw.sum()
bus_surplus_q = -net.res_bus.q_mvar.sum()
branch_loss_p = net.res_line.pl_mw.values.sum() + net.res_trafo.pl_mw.values.sum() + \
net.res_trafo3w.pl_mw.values.sum() + net.res_impedance.pl_mw.values.sum() + \
net.res_dcline.pl_mw.values.sum()
branch_loss_q = net.res_line.ql_mvar.values.sum() + net.res_trafo.ql_mvar.values.sum() + \
net.res_trafo3w.ql_mvar.values.sum() + net.res_impedance.ql_mvar.values.sum() + \
net.res_dcline.q_to_mvar.values.sum() + net.res_dcline.q_from_mvar.values.sum()
try:
assert isclose(bus_surplus_p, branch_loss_p, atol=atol)
except AssertionError:
raise AssertionError("Branch losses are %.4f MW, but power generation at the buses exceeds the feedin by %.4f MW"%(branch_loss_p, bus_surplus_p))
try:
assert isclose(bus_surplus_q, branch_loss_q, atol=atol)
except AssertionError:
raise AssertionError("Branch losses are %.4f MVar, but power generation at the buses exceeds the feedin by %.4f MVar"%(branch_loss_q, bus_surplus_q))
def element_power_consistent_with_bus_power(net, rtol=1e-2, test_q=True):
"""
The bus feed-in at each node has to be equal to the sum of the element feed ins at each node.
"""
bus_p = pd.Series(data=0., index=net.bus.index)
bus_q = pd.Series(data=0., index=net.bus.index)
for idx, tab in net.ext_grid.iterrows():
if tab.in_service:
bus_p.at[tab.bus] -= net.res_ext_grid.p_mw.at[idx]
bus_q.at[tab.bus] -= net.res_ext_grid.q_mvar.at[idx]
for idx, tab in net.gen.iterrows():
if tab.in_service:
bus_p.at[tab.bus] -= net.res_gen.p_mw.at[idx]
bus_q.at[tab.bus] -= net.res_gen.q_mvar.at[idx]
for idx, tab in net.load.iterrows():
bus_p.at[tab.bus] += net.res_load.p_mw.at[idx]
bus_q.at[tab.bus] += net.res_load.q_mvar.at[idx]
for idx, tab in net.sgen.iterrows():
bus_p.at[tab.bus] -= net.res_sgen.p_mw.at[idx]
bus_q.at[tab.bus] -= net.res_sgen.q_mvar.at[idx]
for idx, tab in net.asymmetric_load.iterrows():
bus_p.at[tab.bus] += net.res_asymmetric_load.p_mw.at[idx]
bus_q.at[tab.bus] += net.res_asymmetric_load.q_mvar.at[idx]
for idx, tab in net.asymmetric_sgen.iterrows():
bus_p.at[tab.bus] -= net.res_asymmetric_sgen.p_mw.at[idx]
bus_q.at[tab.bus] -= net.res_asymmetric_sgen.q_mvar.at[idx]
for idx, tab in net.storage.iterrows():
bus_p.at[tab.bus] += net.res_storage.p_mw.at[idx]
bus_q.at[tab.bus] += net.res_storage.q_mvar.at[idx]
for idx, tab in net.shunt.iterrows():
bus_p.at[tab.bus] += net.res_shunt.p_mw.at[idx]
bus_q.at[tab.bus] += net.res_shunt.q_mvar.at[idx]
for idx, tab in net.ward.iterrows():
bus_p.at[tab.bus] += net.res_ward.p_mw.at[idx]
bus_q.at[tab.bus] += net.res_ward.q_mvar.at[idx]
for idx, tab in net.xward.iterrows():
bus_p.at[tab.bus] += net.res_xward.p_mw.at[idx]
bus_q.at[tab.bus] += net.res_xward.q_mvar.at[idx]
assert allclose(net.res_bus.p_mw.values, bus_p.values, equal_nan=True, rtol=rtol)
if test_q:
assert allclose(net.res_bus.q_mvar.values, bus_q.values, equal_nan=True, rtol=rtol)
def consistency_checks_3ph(net, rtol=2e-3):
indices_consistent_3ph(net)
branch_loss_consistent_with_bus_feed_in_3ph(net, rtol)
element_power_consistent_with_bus_power_3ph(net, rtol)
def indices_consistent_3ph(net):
elements = get_relevant_elements("pf_3ph")
for element in elements:
e_idx = net[element].index
res_idx = net["res_" + element+"_3ph"].index
assert len(e_idx) == len(res_idx), "length of %s bus and res_%s indices do not match"%(element, element)
assert all(e_idx == res_idx), "%s bus and res_%s indices do not match"%(element, element)
def branch_loss_consistent_with_bus_feed_in_3ph(net, atol=1e-2):
"""
The surpluss of bus feed summed over all buses always has to be equal to the sum of losses in
all branches.
"""
bus_surplus_p = -net.res_bus_3ph[["p_a_mw", "p_b_mw", "p_c_mw"]].sum().sum()
bus_surplus_q = -net.res_bus_3ph[["q_a_mvar", "q_b_mvar", "q_c_mvar"]].sum().sum()
branch_loss_p = net.res_line_3ph.p_a_l_mw.sum() + net.res_trafo_3ph.p_a_l_mw.sum() + \
net.res_line_3ph.p_b_l_mw.sum() + net.res_trafo_3ph.p_b_l_mw.sum() + \
net.res_line_3ph.p_c_l_mw.sum() + net.res_trafo_3ph.p_c_l_mw.sum()
branch_loss_q = net.res_line_3ph.q_a_l_mvar.sum() + net.res_trafo_3ph.q_a_l_mvar.sum() + \
net.res_line_3ph.q_b_l_mvar.sum() + net.res_trafo_3ph.q_b_l_mvar.sum() + \
net.res_line_3ph.q_c_l_mvar.sum() + net.res_trafo_3ph.q_c_l_mvar.sum()
try:
assert isclose(bus_surplus_p, branch_loss_p, atol=atol)
except AssertionError:
raise AssertionError("Branch losses are %.4f MW, but power generation at the buses exceeds the feedin by %.4f MW"%(branch_loss_p, bus_surplus_p))
try:
assert isclose(bus_surplus_q, branch_loss_q, atol=atol)
except AssertionError:
raise AssertionError("Branch losses are %.4f MVar, but power generation at the buses exceeds the feedin by %.4f MVar"%(branch_loss_q, bus_surplus_q))
def element_power_consistent_with_bus_power_3ph(net, rtol=1e-2):
"""
The bus feed-in at each node has to be equal to the sum of the element feed ins at each node.
"""
bus_p_a = pd.Series(data=0., index=net.bus.index)
bus_q_a = pd.Series(data=0., index=net.bus.index)
bus_p_b = pd.Series(data=0., index=net.bus.index)
bus_q_b = pd.Series(data=0., index=net.bus.index)
bus_p_c = pd.Series(data=0., index=net.bus.index)
bus_q_c = pd.Series(data=0., index=net.bus.index)
for idx, tab in net.ext_grid.iterrows():
bus_p_a.at[tab.bus] -= net.res_ext_grid_3ph.p_a_mw.at[idx]
bus_q_a.at[tab.bus] -= net.res_ext_grid_3ph.q_a_mvar.at[idx]
bus_p_b.at[tab.bus] -= net.res_ext_grid_3ph.p_b_mw.at[idx]
bus_q_b.at[tab.bus] -= net.res_ext_grid_3ph.q_b_mvar.at[idx]
bus_p_c.at[tab.bus] -= net.res_ext_grid_3ph.p_c_mw.at[idx]
bus_q_c.at[tab.bus] -= net.res_ext_grid_3ph.q_c_mvar.at[idx]
for idx, tab in net.load.iterrows():
bus_p_a.at[tab.bus] += net.res_load_3ph.p_mw.at[idx]/3
bus_q_a.at[tab.bus] += net.res_load_3ph.q_mvar.at[idx] /3
bus_p_b.at[tab.bus] += net.res_load_3ph.p_mw.at[idx]/3
bus_q_b.at[tab.bus] += net.res_load_3ph.q_mvar.at[idx] /3
bus_p_c.at[tab.bus] += net.res_load_3ph.p_mw.at[idx]/3
bus_q_c.at[tab.bus] += net.res_load_3ph.q_mvar.at[idx] /3
for idx, tab in net.asymmetric_load.iterrows():
bus_p_a.at[tab.bus] += net.res_asymmetric_load_3ph.p_a_mw.at[idx]
bus_q_a.at[tab.bus] += net.res_asymmetric_load_3ph.q_a_mvar.at[idx]
bus_p_b.at[tab.bus] += net.res_asymmetric_load_3ph.p_b_mw.at[idx]
bus_q_b.at[tab.bus] += net.res_asymmetric_load_3ph.q_b_mvar.at[idx]
bus_p_c.at[tab.bus] += net.res_asymmetric_load_3ph.p_c_mw.at[idx]
bus_q_c.at[tab.bus] += net.res_asymmetric_load_3ph.q_c_mvar.at[idx]
for idx, tab in net.asymmetric_sgen.iterrows():
bus_p_a.at[tab.bus] -= net.res_asymmetric_sgen_3ph.p_a_mw.at[idx]
bus_q_a.at[tab.bus] -= net.res_asymmetric_sgen_3ph.q_a_mvar.at[idx]
bus_p_b.at[tab.bus] -= net.res_asymmetric_sgen_3ph.p_b_mw.at[idx]
bus_q_b.at[tab.bus] -= net.res_asymmetric_sgen_3ph.q_b_mvar.at[idx]
bus_p_c.at[tab.bus] -= net.res_asymmetric_sgen_3ph.p_c_mw.at[idx]
bus_q_c.at[tab.bus] -= net.res_asymmetric_sgen_3ph.q_c_mvar.at[idx]
for idx, tab in net.sgen.iterrows():
bus_p_a.at[tab.bus] -= net.res_sgen_3ph.p_mw.at[idx] / 3
bus_q_a.at[tab.bus] -= net.res_sgen_3ph.q_mvar.at[idx] / 3
bus_p_b.at[tab.bus] -= net.res_sgen_3ph.p_mw.at[idx] / 3
bus_q_b.at[tab.bus] -= net.res_sgen_3ph.q_mvar.at[idx] / 3
bus_p_c.at[tab.bus] -= net.res_sgen_3ph.p_mw.at[idx] / 3
bus_q_c.at[tab.bus] -= net.res_sgen_3ph.q_mvar.at[idx] / 3
assert allclose(net.res_bus_3ph.p_a_mw.values, bus_p_a.values, equal_nan=True, rtol=rtol)
assert allclose(net.res_bus_3ph.q_a_mvar.values, bus_q_a.values, equal_nan=True, rtol=rtol)
assert allclose(net.res_bus_3ph.p_b_mw.values, bus_p_b.values, equal_nan=True, rtol=rtol)
assert allclose(net.res_bus_3ph.q_b_mvar.values, bus_q_b.values, equal_nan=True, rtol=rtol)
assert allclose(net.res_bus_3ph.p_c_mw.values, bus_p_c.values, equal_nan=True, rtol=rtol)
assert allclose(net.res_bus_3ph.q_c_mvar.values, bus_q_c.values, equal_nan=True, rtol=rtol)
| 47.59009 | 158 | 0.671084 |
import pandas as pd
from numpy import allclose, isclose
from pandapower.pf.runpp_3ph import runpp_3ph
from pandapower.results import get_relevant_elements
import pandapower as pp
def runpp_with_consistency_checks(net, **kwargs):
pp.runpp(net, **kwargs)
consistency_checks(net)
return True
def runpp_3ph_with_consistency_checks(net, **kwargs):
runpp_3ph(net, **kwargs)
consistency_checks_3ph(net)
return True
def rundcpp_with_consistency_checks(net, **kwargs):
pp.rundcpp(net, **kwargs)
consistency_checks(net, test_q=False)
return True
def consistency_checks(net, rtol=1e-3, test_q=True):
indices_consistent(net)
branch_loss_consistent_with_bus_feed_in(net, rtol)
element_power_consistent_with_bus_power(net, rtol, test_q)
def indices_consistent(net):
elements = get_relevant_elements()
for element in elements:
e_idx = net[element].index
res_idx = net["res_" + element].index
assert len(e_idx) == len(res_idx), "length of %s bus and res_%s indices do not match"%(element, element)
assert all(e_idx == res_idx), "%s bus and res_%s indices do not match"%(element, element)
def branch_loss_consistent_with_bus_feed_in(net, atol=1e-2):
bus_surplus_p = -net.res_bus.p_mw.sum()
bus_surplus_q = -net.res_bus.q_mvar.sum()
branch_loss_p = net.res_line.pl_mw.values.sum() + net.res_trafo.pl_mw.values.sum() + \
net.res_trafo3w.pl_mw.values.sum() + net.res_impedance.pl_mw.values.sum() + \
net.res_dcline.pl_mw.values.sum()
branch_loss_q = net.res_line.ql_mvar.values.sum() + net.res_trafo.ql_mvar.values.sum() + \
net.res_trafo3w.ql_mvar.values.sum() + net.res_impedance.ql_mvar.values.sum() + \
net.res_dcline.q_to_mvar.values.sum() + net.res_dcline.q_from_mvar.values.sum()
try:
assert isclose(bus_surplus_p, branch_loss_p, atol=atol)
except AssertionError:
raise AssertionError("Branch losses are %.4f MW, but power generation at the buses exceeds the feedin by %.4f MW"%(branch_loss_p, bus_surplus_p))
try:
assert isclose(bus_surplus_q, branch_loss_q, atol=atol)
except AssertionError:
raise AssertionError("Branch losses are %.4f MVar, but power generation at the buses exceeds the feedin by %.4f MVar"%(branch_loss_q, bus_surplus_q))
def element_power_consistent_with_bus_power(net, rtol=1e-2, test_q=True):
bus_p = pd.Series(data=0., index=net.bus.index)
bus_q = pd.Series(data=0., index=net.bus.index)
for idx, tab in net.ext_grid.iterrows():
if tab.in_service:
bus_p.at[tab.bus] -= net.res_ext_grid.p_mw.at[idx]
bus_q.at[tab.bus] -= net.res_ext_grid.q_mvar.at[idx]
for idx, tab in net.gen.iterrows():
if tab.in_service:
bus_p.at[tab.bus] -= net.res_gen.p_mw.at[idx]
bus_q.at[tab.bus] -= net.res_gen.q_mvar.at[idx]
for idx, tab in net.load.iterrows():
bus_p.at[tab.bus] += net.res_load.p_mw.at[idx]
bus_q.at[tab.bus] += net.res_load.q_mvar.at[idx]
for idx, tab in net.sgen.iterrows():
bus_p.at[tab.bus] -= net.res_sgen.p_mw.at[idx]
bus_q.at[tab.bus] -= net.res_sgen.q_mvar.at[idx]
for idx, tab in net.asymmetric_load.iterrows():
bus_p.at[tab.bus] += net.res_asymmetric_load.p_mw.at[idx]
bus_q.at[tab.bus] += net.res_asymmetric_load.q_mvar.at[idx]
for idx, tab in net.asymmetric_sgen.iterrows():
bus_p.at[tab.bus] -= net.res_asymmetric_sgen.p_mw.at[idx]
bus_q.at[tab.bus] -= net.res_asymmetric_sgen.q_mvar.at[idx]
for idx, tab in net.storage.iterrows():
bus_p.at[tab.bus] += net.res_storage.p_mw.at[idx]
bus_q.at[tab.bus] += net.res_storage.q_mvar.at[idx]
for idx, tab in net.shunt.iterrows():
bus_p.at[tab.bus] += net.res_shunt.p_mw.at[idx]
bus_q.at[tab.bus] += net.res_shunt.q_mvar.at[idx]
for idx, tab in net.ward.iterrows():
bus_p.at[tab.bus] += net.res_ward.p_mw.at[idx]
bus_q.at[tab.bus] += net.res_ward.q_mvar.at[idx]
for idx, tab in net.xward.iterrows():
bus_p.at[tab.bus] += net.res_xward.p_mw.at[idx]
bus_q.at[tab.bus] += net.res_xward.q_mvar.at[idx]
assert allclose(net.res_bus.p_mw.values, bus_p.values, equal_nan=True, rtol=rtol)
if test_q:
assert allclose(net.res_bus.q_mvar.values, bus_q.values, equal_nan=True, rtol=rtol)
def consistency_checks_3ph(net, rtol=2e-3):
indices_consistent_3ph(net)
branch_loss_consistent_with_bus_feed_in_3ph(net, rtol)
element_power_consistent_with_bus_power_3ph(net, rtol)
def indices_consistent_3ph(net):
elements = get_relevant_elements("pf_3ph")
for element in elements:
e_idx = net[element].index
res_idx = net["res_" + element+"_3ph"].index
assert len(e_idx) == len(res_idx), "length of %s bus and res_%s indices do not match"%(element, element)
assert all(e_idx == res_idx), "%s bus and res_%s indices do not match"%(element, element)
def branch_loss_consistent_with_bus_feed_in_3ph(net, atol=1e-2):
bus_surplus_p = -net.res_bus_3ph[["p_a_mw", "p_b_mw", "p_c_mw"]].sum().sum()
bus_surplus_q = -net.res_bus_3ph[["q_a_mvar", "q_b_mvar", "q_c_mvar"]].sum().sum()
branch_loss_p = net.res_line_3ph.p_a_l_mw.sum() + net.res_trafo_3ph.p_a_l_mw.sum() + \
net.res_line_3ph.p_b_l_mw.sum() + net.res_trafo_3ph.p_b_l_mw.sum() + \
net.res_line_3ph.p_c_l_mw.sum() + net.res_trafo_3ph.p_c_l_mw.sum()
branch_loss_q = net.res_line_3ph.q_a_l_mvar.sum() + net.res_trafo_3ph.q_a_l_mvar.sum() + \
net.res_line_3ph.q_b_l_mvar.sum() + net.res_trafo_3ph.q_b_l_mvar.sum() + \
net.res_line_3ph.q_c_l_mvar.sum() + net.res_trafo_3ph.q_c_l_mvar.sum()
try:
assert isclose(bus_surplus_p, branch_loss_p, atol=atol)
except AssertionError:
raise AssertionError("Branch losses are %.4f MW, but power generation at the buses exceeds the feedin by %.4f MW"%(branch_loss_p, bus_surplus_p))
try:
assert isclose(bus_surplus_q, branch_loss_q, atol=atol)
except AssertionError:
raise AssertionError("Branch losses are %.4f MVar, but power generation at the buses exceeds the feedin by %.4f MVar"%(branch_loss_q, bus_surplus_q))
def element_power_consistent_with_bus_power_3ph(net, rtol=1e-2):
bus_p_a = pd.Series(data=0., index=net.bus.index)
bus_q_a = pd.Series(data=0., index=net.bus.index)
bus_p_b = pd.Series(data=0., index=net.bus.index)
bus_q_b = pd.Series(data=0., index=net.bus.index)
bus_p_c = pd.Series(data=0., index=net.bus.index)
bus_q_c = pd.Series(data=0., index=net.bus.index)
for idx, tab in net.ext_grid.iterrows():
bus_p_a.at[tab.bus] -= net.res_ext_grid_3ph.p_a_mw.at[idx]
bus_q_a.at[tab.bus] -= net.res_ext_grid_3ph.q_a_mvar.at[idx]
bus_p_b.at[tab.bus] -= net.res_ext_grid_3ph.p_b_mw.at[idx]
bus_q_b.at[tab.bus] -= net.res_ext_grid_3ph.q_b_mvar.at[idx]
bus_p_c.at[tab.bus] -= net.res_ext_grid_3ph.p_c_mw.at[idx]
bus_q_c.at[tab.bus] -= net.res_ext_grid_3ph.q_c_mvar.at[idx]
for idx, tab in net.load.iterrows():
bus_p_a.at[tab.bus] += net.res_load_3ph.p_mw.at[idx]/3
bus_q_a.at[tab.bus] += net.res_load_3ph.q_mvar.at[idx] /3
bus_p_b.at[tab.bus] += net.res_load_3ph.p_mw.at[idx]/3
bus_q_b.at[tab.bus] += net.res_load_3ph.q_mvar.at[idx] /3
bus_p_c.at[tab.bus] += net.res_load_3ph.p_mw.at[idx]/3
bus_q_c.at[tab.bus] += net.res_load_3ph.q_mvar.at[idx] /3
for idx, tab in net.asymmetric_load.iterrows():
bus_p_a.at[tab.bus] += net.res_asymmetric_load_3ph.p_a_mw.at[idx]
bus_q_a.at[tab.bus] += net.res_asymmetric_load_3ph.q_a_mvar.at[idx]
bus_p_b.at[tab.bus] += net.res_asymmetric_load_3ph.p_b_mw.at[idx]
bus_q_b.at[tab.bus] += net.res_asymmetric_load_3ph.q_b_mvar.at[idx]
bus_p_c.at[tab.bus] += net.res_asymmetric_load_3ph.p_c_mw.at[idx]
bus_q_c.at[tab.bus] += net.res_asymmetric_load_3ph.q_c_mvar.at[idx]
for idx, tab in net.asymmetric_sgen.iterrows():
bus_p_a.at[tab.bus] -= net.res_asymmetric_sgen_3ph.p_a_mw.at[idx]
bus_q_a.at[tab.bus] -= net.res_asymmetric_sgen_3ph.q_a_mvar.at[idx]
bus_p_b.at[tab.bus] -= net.res_asymmetric_sgen_3ph.p_b_mw.at[idx]
bus_q_b.at[tab.bus] -= net.res_asymmetric_sgen_3ph.q_b_mvar.at[idx]
bus_p_c.at[tab.bus] -= net.res_asymmetric_sgen_3ph.p_c_mw.at[idx]
bus_q_c.at[tab.bus] -= net.res_asymmetric_sgen_3ph.q_c_mvar.at[idx]
for idx, tab in net.sgen.iterrows():
bus_p_a.at[tab.bus] -= net.res_sgen_3ph.p_mw.at[idx] / 3
bus_q_a.at[tab.bus] -= net.res_sgen_3ph.q_mvar.at[idx] / 3
bus_p_b.at[tab.bus] -= net.res_sgen_3ph.p_mw.at[idx] / 3
bus_q_b.at[tab.bus] -= net.res_sgen_3ph.q_mvar.at[idx] / 3
bus_p_c.at[tab.bus] -= net.res_sgen_3ph.p_mw.at[idx] / 3
bus_q_c.at[tab.bus] -= net.res_sgen_3ph.q_mvar.at[idx] / 3
assert allclose(net.res_bus_3ph.p_a_mw.values, bus_p_a.values, equal_nan=True, rtol=rtol)
assert allclose(net.res_bus_3ph.q_a_mvar.values, bus_q_a.values, equal_nan=True, rtol=rtol)
assert allclose(net.res_bus_3ph.p_b_mw.values, bus_p_b.values, equal_nan=True, rtol=rtol)
assert allclose(net.res_bus_3ph.q_b_mvar.values, bus_q_b.values, equal_nan=True, rtol=rtol)
assert allclose(net.res_bus_3ph.p_c_mw.values, bus_p_c.values, equal_nan=True, rtol=rtol)
assert allclose(net.res_bus_3ph.q_c_mvar.values, bus_q_c.values, equal_nan=True, rtol=rtol)
| true | true |
f7f94cf84b12d34d0ba08564cdc90359b65d98b5 | 767 | py | Python | logging/api-client/list_logs_test.py | baditaflorin/python-docs-samples | f122cbc13f20336d15409b5bd9820377dcb65464 | [
"Apache-2.0"
] | 2 | 2017-09-23T04:23:46.000Z | 2021-06-11T01:23:06.000Z | logging/api-client/list_logs_test.py | baditaflorin/python-docs-samples | f122cbc13f20336d15409b5bd9820377dcb65464 | [
"Apache-2.0"
] | 2 | 2021-06-10T23:54:32.000Z | 2021-06-10T23:54:33.000Z | logging/api-client/list_logs_test.py | baditaflorin/python-docs-samples | f122cbc13f20336d15409b5bd9820377dcb65464 | [
"Apache-2.0"
] | 2 | 2019-11-27T00:13:37.000Z | 2021-03-24T00:05:36.000Z | # Copyright 2015, Google, 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 re
import list_logs
def test_main(cloud_config, capsys):
list_logs.main(cloud_config.project)
out, _ = capsys.readouterr()
assert re.search(re.compile(r'.*', re.S), out)
| 33.347826 | 74 | 0.747066 |
import re
import list_logs
def test_main(cloud_config, capsys):
list_logs.main(cloud_config.project)
out, _ = capsys.readouterr()
assert re.search(re.compile(r'.*', re.S), out)
| true | true |
f7f94d8192588fb7c74ab6fde66cca6320e60c50 | 13,339 | py | Python | binho/interfaces/gpio.py | pixelfelon/binho-python-package | 92f4898722f0578973cb672d1387fbea6cb7bb3d | [
"BSD-3-Clause"
] | null | null | null | binho/interfaces/gpio.py | pixelfelon/binho-python-package | 92f4898722f0578973cb672d1387fbea6cb7bb3d | [
"BSD-3-Clause"
] | null | null | null | binho/interfaces/gpio.py | pixelfelon/binho-python-package | 92f4898722f0578973cb672d1387fbea6cb7bb3d | [
"BSD-3-Clause"
] | null | null | null | from ..interface import binhoInterface
# TODOs:
# - XXX: Overhaul the GPIO(Collection) class to be more efficient
# - More cleanup to use the GPIOPin model.
# - Support ranges of pins from the same port (GPIOPort objects?)
# - Implement a release function so if e.g. an I2C device is no longer in use
# it releases its pins back to the GPIO pool.
class ioPinModes:
digitalInput = "DIN"
digitalOutput = "DOUT"
analogInput = "AIN"
analogOutput = "AOUT"
pwmOutput = "PWM"
class GPIOProvider(binhoInterface):
""" Base class for an object that provides access to GPIO pins. """
# If the subclass has a fixed set of pins, it can override this mapping to
# specify the fixed pin names to be automatically registered.
FIXED_GPIO_PINS = {}
# If the subclass doesn't want to allow external sources to register GPIO
# pins
ALLOW_EXTERNAL_REGISTRATION = True
def __init__(self, board, name_mappings=None):
"""Sets up the basic fields for a GPIOProvider.
Parameters:
name_mappings -- Allows callers to rename the local / fixed GPIO pin names.
Optional; accepts a dictionary mapping their fixed names to their new names, or
to None to remove the relevant pin from the list of available pins.
This allows instantiators to give a given GPIO collection more specific names, or
to hide them from general API display/usage.
"""
super().__init__(board)
if name_mappings is None:
name_mappings = {}
# Set up our basic tracking parameters, which track which GPIO pins
# are available and in use.
self.pin_mappings = {}
self.active_gpio = {}
self.available_pins = []
# Add all of our fixed pins as acceptable GPIO.
for name, line in self.FIXED_GPIO_PINS.items():
# If we've been asked to rename the given pin, register it under
# the new name, rather than under the provided name,
if name in name_mappings:
name = name_mappings[name]
# If our name field winds up remapping to 'None', the instantiator
# is trying to hide the relevant pin. Skip registering it.
if name is None:
continue
# Register each fixed GPIO.
self.__registerGPIO(board, name, line)
def registerGPIO(self, board, name, line, used=False):
"""
Registers a GPIO pin for later use. Usually only used in board setup.
Args:
name -- The name for the GPIO, usually expressed as IO#.
line -- An abstract argument passed to subclass methods that serves
to identify the pin. Subclasses often use this to store e.g. port and pin
numbers.
"""
# If this class doesn't allow pin registration, raise an error.
if not self.ALLOW_EXTERNAL_REGISTRATION:
raise NotImplementedError("This GPIO collection does not allow registration of new pins.")
# Otherwise, delegate to our internal registration method.
self.__registerGPIO(board, name, line, used)
def __registerGPIO(self, board, name, line, used=False):
"""
Registers a GPIO pin for later use. Usually only used in board setup.
Args:
name -- The name for the GPIO, usually expressed as IO[n].
line -- An abstract argument passed to subclass methods that serves
to identify the pin. Subclasses often use this to store e.g. port and pin
numbers.
"""
# Store the full name in our pin mappings.
self.pin_mappings[name] = line
board.addIOPinAPI(name, line)
if not used:
self.markPinAsUnused(name)
def markPinAsUsed(self, name):
""" Marks a pin as used by another peripheral. """
if name not in self.pin_mappings:
raise ValueError("Unknown GPIO pin {}".format(name))
self.available_pins.remove(name)
def markPinAsUnused(self, name):
""" Mark a pin as no longer used by another peripheral. """
if name not in self.pin_mappings:
raise ValueError("Unknown GPIO pin {}".format(name))
if name not in self.available_pins:
self.available_pins.append(name)
def getAvailablePins(self, include_active=True): # pylint: disable=unused-argument
""" Returns a list of available GPIO names. """
available = self.available_pins[:]
available.extend(self.active_gpio.keys())
return sorted(available)
def getPin(self, name, unique=False):
"""
Returns a GPIOPin object by which a given pin can be controlled.
Args:
name -- The GPIO name to be used.
unique -- True if this should fail if a GPIO object for this pin
already exists.
"""
if str(name).isnumeric():
name = "IO" + str(name)
name = name.upper()
# If we already have an active GPIO pin for the relevant name, return
# it.
if name in self.active_gpio and not unique:
return self.active_gpio[name]
# If the pin's available for GPIO use, grab it.
if name in self.available_pins:
port = self.pin_mappings[name]
self.active_gpio[name] = GPIOPin(self, name, port)
self.markPinAsUsed(name)
return self.active_gpio[name]
# If we couldn't create the GPIO pin, fail out.
raise ValueError("No available GPIO pin {}".format(name))
def releasePin(self, gpio_pin):
"""
Releases a GPIO pin back to the system for re-use, potentially
not as a GPIO.
"""
if gpio_pin.name not in self.active_gpio:
raise ValueError("Trying to release a pin we don't own!")
# Mark the pin as an input, placing it into High-Z mode.
# TODO: Disable any pull-ups present on the pin.
gpio_pin.mode = ioPinModes.digitalInput
# Remove the GPIO pin from our active array, and add it back to the
# available pool.
del self.active_gpio[gpio_pin.name]
self.markPinAsUnused(gpio_pin.name)
def setPinMode(self, line, mode, initial_value=False):
"""
Configure a GPIO line for use as an input or output. This must be
called before the line can be used by other functions.
Parameters:
line -- A unique identifier for the given pin that has meaning to the subclass.
direction -- Directions.IN (input) or Directions.OUT (output)
"""
def setPinValue(self, line, state):
"""
Set the state of an output line. The line must have previously been
configured as an output using setup().
Parameters:
line -- A unique identifier for the given pin that has meaning to the subclass.
state -- True sets line high, False sets line low
"""
def readPinValue(self, line):
"""
Get the state of an input line. The line must have previously been
configured as an input using setup().
Args:
line -- A unique identifier for the given pin that has meaning to the subclass.
Return:
bool -- True if line is high, False if line is low
"""
def getPinMode(self, line):
"""
Gets the direction of a GPIO pin.
Args:
line -- A unique identifier for the given pin that has meaning to the subclass.
Return:
bool -- True if line is an output, False if line is an input
"""
def getPinIndex(self, line):
"""Returns the 'pin number' for a given GPIO pin.
This number is typically the 'bit number' in a larger, organized port. For providers
in which this isn't a valid semantic concept, any convenient semantic identifier (or None)
is acceptable.
"""
def getPinIdentifier(self, line):
"""Returns the 'pin number' for a given GPIO pin.
This number is typically the 'bit number' in a larger, organized port. For providers
in which this isn't a valid semantic concept, any convenient semantic identifier (or None)
is acceptable.
"""
class GPIO(GPIOProvider):
""" Work with the GPIO directly present on the Binho host adapter. """
def __init__(self, board):
"""
Args:
board -- Binho host adapter whose GPIO lines are to be controlled
"""
# store information about the our low-level connection.
self.board = board
# Set up our basic fields...
super().__init__(self.board)
def setPinMode(self, line, mode, initial_value=False):
"""
Configure a GPIO line for use as an input or output. This must be
called before the line can be used by other functions.
Args:
line -- (port, pin); typically a tuple from J1, J2, J7 below
direction -- Directions.IN (input) or Directions.OUT (output)
TODO: allow pull-up/pull-down resistors to be configured for inputs
"""
self.board.apis.io[line].mode = mode
if mode == "DOUT" and initial_value:
self.board.apis.io[line].value = 1
def setPinValue(self, line, state):
"""
Set the state of an output line. The line must have previously been
configured as an output using setup().
Args:
line -- (port, pin); typically a tuple from J1, J2, J7 below
state -- True sets line high, False sets line low
"""
# TODO: validate GPIO direction?
self.board.apis.io[line].value = state
def readPinValue(self, line):
"""
Get the state of an input line. The line must have previously been
configured as an input using setup().
Args:
line -- (port, pin); typically a tuple from J1, J2, J7 below
Return:
bool -- True if line is high, False if line is low
"""
return self.board.apis.io[line].value
def getPWMFrequency(self, line):
return self.board.apis.io[line].pwmFrequency
def setPWMFrequency(self, line, freq):
self.board.apis.io[line].pwmFrequency = freq
def getPinMode(self, line):
"""
Gets the direction of a GPIO pin.
Args:
line -- (port, pin); typically a tuple from J1, J2, J7 below
Return:
bool -- True if line is an output, False if line is an input
"""
return self.board.apis.io[line].mode
def getPinIndex(self, line):
""" Returns the 'port number' for a given GPIO pin."""
return line
def getPinIdentifier(self, line):
""" Returns the 'pin number' for a given GPIO pin. """
return "IO" + str(line)
class GPIOPin:
"""
Class representing a single GPIO pin.
"""
def __init__(self, gpio_provider, name, line):
"""
Creates a new object representing a GPIO Pin. Usually instantiated via
a GPIO object.
Args:
gpio_provider -- The GPIO object to which this pin belongs.
name -- The name of the given pin. Should match a name registered
in its GPIO collection.
line -- The pin's 'line' information, as defined by the object that created
this GPIO pin. This variable has semantic meaning to the GPIO collection;
but doesn't have any semantic meaning to this class.
"""
self.name = name
self._parent = gpio_provider
self._line = line
# Set up the pin for use. Idempotent.
self._parent.setPinMode(self._line, "DIN")
@property
def mode(self):
return self._parent.getPinMode(self._line)
@mode.setter
def mode(self, ioPinMode, initial_value=False):
"""
Sets the GPIO pin to use a given mode.
"""
modeStr = "DIN"
if ioPinMode == ioPinModes.digitalInput:
modeStr = "DIN"
elif ioPinMode == ioPinModes.digitalOutput:
modeStr = "DOUT"
elif ioPinMode == ioPinModes.analogInput:
modeStr = "AIN"
elif ioPinMode == ioPinModes.analogOutput:
modeStr = "AOUT"
elif ioPinMode == ioPinModes.pwmOutput:
modeStr = "PWM"
self._parent.setPinMode(self._line, modeStr, initial_value)
@property
def value(self):
""" Returns the value of a GPIO pin. """
raw = self._parent.readPinValue(self._line)
return raw
@value.setter
def value(self, value):
self._parent.setPinValue(self._line, value)
@property
def pwmFreq(self):
return self._parent.getPWMFrequency(self._line)
@pwmFreq.setter
def pwmFreq(self, freq):
self._parent.setPWMFrequency(self._line, freq)
@property
def pinNumber(self):
""" Returns pin's pin number within its port, if possible. """
return self._parent.getPinIndex(self._line)
@property
def pinName(self):
""" Returns pin's full pin name """
return self._parent.getPinIdentifier(self._line)
| 34.736979 | 102 | 0.61144 | from ..interface import binhoInterface
class ioPinModes:
digitalInput = "DIN"
digitalOutput = "DOUT"
analogInput = "AIN"
analogOutput = "AOUT"
pwmOutput = "PWM"
class GPIOProvider(binhoInterface):
FIXED_GPIO_PINS = {}
# pins
ALLOW_EXTERNAL_REGISTRATION = True
def __init__(self, board, name_mappings=None):
super().__init__(board)
if name_mappings is None:
name_mappings = {}
# Set up our basic tracking parameters, which track which GPIO pins
# are available and in use.
self.pin_mappings = {}
self.active_gpio = {}
self.available_pins = []
# Add all of our fixed pins as acceptable GPIO.
for name, line in self.FIXED_GPIO_PINS.items():
# If we've been asked to rename the given pin, register it under
if name in name_mappings:
name = name_mappings[name]
if name is None:
continue
self.__registerGPIO(board, name, line)
def registerGPIO(self, board, name, line, used=False):
if not self.ALLOW_EXTERNAL_REGISTRATION:
raise NotImplementedError("This GPIO collection does not allow registration of new pins.")
# Otherwise, delegate to our internal registration method.
self.__registerGPIO(board, name, line, used)
def __registerGPIO(self, board, name, line, used=False):
# Store the full name in our pin mappings.
self.pin_mappings[name] = line
board.addIOPinAPI(name, line)
if not used:
self.markPinAsUnused(name)
def markPinAsUsed(self, name):
if name not in self.pin_mappings:
raise ValueError("Unknown GPIO pin {}".format(name))
self.available_pins.remove(name)
def markPinAsUnused(self, name):
if name not in self.pin_mappings:
raise ValueError("Unknown GPIO pin {}".format(name))
if name not in self.available_pins:
self.available_pins.append(name)
def getAvailablePins(self, include_active=True): # pylint: disable=unused-argument
available = self.available_pins[:]
available.extend(self.active_gpio.keys())
return sorted(available)
def getPin(self, name, unique=False):
if str(name).isnumeric():
name = "IO" + str(name)
name = name.upper()
# If we already have an active GPIO pin for the relevant name, return
# it.
if name in self.active_gpio and not unique:
return self.active_gpio[name]
# If the pin's available for GPIO use, grab it.
if name in self.available_pins:
port = self.pin_mappings[name]
self.active_gpio[name] = GPIOPin(self, name, port)
self.markPinAsUsed(name)
return self.active_gpio[name]
raise ValueError("No available GPIO pin {}".format(name))
def releasePin(self, gpio_pin):
if gpio_pin.name not in self.active_gpio:
raise ValueError("Trying to release a pin we don't own!")
gpio_pin.mode = ioPinModes.digitalInput
del self.active_gpio[gpio_pin.name]
self.markPinAsUnused(gpio_pin.name)
def setPinMode(self, line, mode, initial_value=False):
def setPinValue(self, line, state):
def readPinValue(self, line):
def getPinMode(self, line):
def getPinIndex(self, line):
def getPinIdentifier(self, line):
class GPIO(GPIOProvider):
def __init__(self, board):
self.board = board
super().__init__(self.board)
def setPinMode(self, line, mode, initial_value=False):
self.board.apis.io[line].mode = mode
if mode == "DOUT" and initial_value:
self.board.apis.io[line].value = 1
def setPinValue(self, line, state):
self.board.apis.io[line].value = state
def readPinValue(self, line):
return self.board.apis.io[line].value
def getPWMFrequency(self, line):
return self.board.apis.io[line].pwmFrequency
def setPWMFrequency(self, line, freq):
self.board.apis.io[line].pwmFrequency = freq
def getPinMode(self, line):
return self.board.apis.io[line].mode
def getPinIndex(self, line):
return line
def getPinIdentifier(self, line):
return "IO" + str(line)
class GPIOPin:
def __init__(self, gpio_provider, name, line):
self.name = name
self._parent = gpio_provider
self._line = line
self._parent.setPinMode(self._line, "DIN")
@property
def mode(self):
return self._parent.getPinMode(self._line)
@mode.setter
def mode(self, ioPinMode, initial_value=False):
modeStr = "DIN"
if ioPinMode == ioPinModes.digitalInput:
modeStr = "DIN"
elif ioPinMode == ioPinModes.digitalOutput:
modeStr = "DOUT"
elif ioPinMode == ioPinModes.analogInput:
modeStr = "AIN"
elif ioPinMode == ioPinModes.analogOutput:
modeStr = "AOUT"
elif ioPinMode == ioPinModes.pwmOutput:
modeStr = "PWM"
self._parent.setPinMode(self._line, modeStr, initial_value)
@property
def value(self):
raw = self._parent.readPinValue(self._line)
return raw
@value.setter
def value(self, value):
self._parent.setPinValue(self._line, value)
@property
def pwmFreq(self):
return self._parent.getPWMFrequency(self._line)
@pwmFreq.setter
def pwmFreq(self, freq):
self._parent.setPWMFrequency(self._line, freq)
@property
def pinNumber(self):
return self._parent.getPinIndex(self._line)
@property
def pinName(self):
return self._parent.getPinIdentifier(self._line)
| true | true |
f7f94daa11128cdff4f10775cd966ab747f37169 | 2,971 | py | Python | sdcflows/conftest.py | madisoth/sdcflows | c2f01e4f9b19dbd89ac1b54e3cfb0643fc3fd4f2 | [
"Apache-2.0"
] | 16 | 2020-02-25T17:47:10.000Z | 2022-03-07T02:54:51.000Z | sdcflows/conftest.py | madisoth/sdcflows | c2f01e4f9b19dbd89ac1b54e3cfb0643fc3fd4f2 | [
"Apache-2.0"
] | 175 | 2020-02-15T00:52:28.000Z | 2022-03-29T21:42:31.000Z | sdcflows/conftest.py | madisoth/sdcflows | c2f01e4f9b19dbd89ac1b54e3cfb0643fc3fd4f2 | [
"Apache-2.0"
] | 8 | 2020-02-15T23:47:22.000Z | 2021-11-26T01:40:41.000Z | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
#
# Copyright 2021 The NiPreps Developers <nipreps@gmail.com>
#
# 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.
#
# We support and encourage derived works from this project, please read
# about our expectations at
#
# https://www.nipreps.org/community/licensing/
#
"""py.test configuration."""
import os
from pathlib import Path
import numpy
import nibabel
import pytest
from bids.layout import BIDSLayout
test_data_env = os.getenv("TEST_DATA_HOME", str(Path.home() / "sdcflows-tests"))
test_output_dir = os.getenv("TEST_OUTPUT_DIR")
test_workdir = os.getenv("TEST_WORK_DIR")
_sloppy_mode = os.getenv("TEST_PRODUCTION", "off").lower() not in ("on", "1", "true", "yes", "y")
layouts = {
p.name: BIDSLayout(str(p), validate=False, derivatives=True)
for p in Path(test_data_env).glob("*")
if p.is_dir()
}
data_dir = Path(__file__).parent / "tests" / "data"
layouts.update({
folder.name: BIDSLayout(folder, validate=False, derivatives=False)
for folder in data_dir.glob("ds*") if folder.is_dir()
})
def pytest_report_header(config):
return f"""\
TEST_DATA_HOME={test_data_env}
-> Available datasets: {', '.join(layouts.keys())}.
TEST_OUTPUT_DIR={test_output_dir or '<unset> (output files will be discarded)'}.
TEST_WORK_DIR={test_workdir or '<unset> (intermediate files will be discarded)'}.
"""
@pytest.fixture(autouse=True)
def add_np(doctest_namespace):
doctest_namespace["np"] = numpy
doctest_namespace["nb"] = nibabel
doctest_namespace["os"] = os
doctest_namespace["Path"] = Path
doctest_namespace["layouts"] = layouts
for key, val in list(layouts.items()):
doctest_namespace[key] = Path(val.root)
doctest_namespace["dsA_dir"] = data_dir / "dsA"
doctest_namespace["dsB_dir"] = data_dir / "dsB"
doctest_namespace["dsC_dir"] = data_dir / "dsC"
@pytest.fixture
def workdir():
return None if test_workdir is None else Path(test_workdir)
@pytest.fixture
def outdir():
return None if test_output_dir is None else Path(test_output_dir)
@pytest.fixture
def bids_layouts():
if layouts:
return layouts
pytest.skip()
@pytest.fixture
def datadir():
return Path(test_data_env)
@pytest.fixture
def testdata_dir():
return data_dir
@pytest.fixture
def dsA_dir():
return data_dir / "dsA"
@pytest.fixture
def sloppy_mode():
return _sloppy_mode
| 27.509259 | 97 | 0.71794 |
import os
from pathlib import Path
import numpy
import nibabel
import pytest
from bids.layout import BIDSLayout
test_data_env = os.getenv("TEST_DATA_HOME", str(Path.home() / "sdcflows-tests"))
test_output_dir = os.getenv("TEST_OUTPUT_DIR")
test_workdir = os.getenv("TEST_WORK_DIR")
_sloppy_mode = os.getenv("TEST_PRODUCTION", "off").lower() not in ("on", "1", "true", "yes", "y")
layouts = {
p.name: BIDSLayout(str(p), validate=False, derivatives=True)
for p in Path(test_data_env).glob("*")
if p.is_dir()
}
data_dir = Path(__file__).parent / "tests" / "data"
layouts.update({
folder.name: BIDSLayout(folder, validate=False, derivatives=False)
for folder in data_dir.glob("ds*") if folder.is_dir()
})
def pytest_report_header(config):
return f"""\
TEST_DATA_HOME={test_data_env}
-> Available datasets: {', '.join(layouts.keys())}.
TEST_OUTPUT_DIR={test_output_dir or '<unset> (output files will be discarded)'}.
TEST_WORK_DIR={test_workdir or '<unset> (intermediate files will be discarded)'}.
"""
@pytest.fixture(autouse=True)
def add_np(doctest_namespace):
doctest_namespace["np"] = numpy
doctest_namespace["nb"] = nibabel
doctest_namespace["os"] = os
doctest_namespace["Path"] = Path
doctest_namespace["layouts"] = layouts
for key, val in list(layouts.items()):
doctest_namespace[key] = Path(val.root)
doctest_namespace["dsA_dir"] = data_dir / "dsA"
doctest_namespace["dsB_dir"] = data_dir / "dsB"
doctest_namespace["dsC_dir"] = data_dir / "dsC"
@pytest.fixture
def workdir():
return None if test_workdir is None else Path(test_workdir)
@pytest.fixture
def outdir():
return None if test_output_dir is None else Path(test_output_dir)
@pytest.fixture
def bids_layouts():
if layouts:
return layouts
pytest.skip()
@pytest.fixture
def datadir():
return Path(test_data_env)
@pytest.fixture
def testdata_dir():
return data_dir
@pytest.fixture
def dsA_dir():
return data_dir / "dsA"
@pytest.fixture
def sloppy_mode():
return _sloppy_mode
| true | true |
f7f94e28aa841fa20d6c7d1e139080d89a9b8735 | 537 | py | Python | Python_ABC/2-19autoGUI/2mouseNow.py | Chandler-Song/Python_Awesome | a44b8b79de7b429a00ac5798e7ecdc26c79a09ed | [
"MIT"
] | null | null | null | Python_ABC/2-19autoGUI/2mouseNow.py | Chandler-Song/Python_Awesome | a44b8b79de7b429a00ac5798e7ecdc26c79a09ed | [
"MIT"
] | null | null | null | Python_ABC/2-19autoGUI/2mouseNow.py | Chandler-Song/Python_Awesome | a44b8b79de7b429a00ac5798e7ecdc26c79a09ed | [
"MIT"
] | null | null | null | # mouseNow.py - Displays the mouse cursor's current position.
import pyautogui
import time
print('Press fn+command+F2(Mac) or Ctrl+C(windows) to quit.')
positionStr = ''
try:
while True:
time.sleep(3)
# Get and print the mouse coordinates.
x, y = pyautogui.position()
pixelColor = pyautogui.screenshot().getpixel((x, y))
positionStr = 'X: {:4}; Y: {:4}; RGB:{}'.format(x, y, pixelColor)
print(positionStr)
except KeyboardInterrupt:
print('\nDone.')
| 22.375 | 75 | 0.60149 |
import pyautogui
import time
print('Press fn+command+F2(Mac) or Ctrl+C(windows) to quit.')
positionStr = ''
try:
while True:
time.sleep(3)
# Get and print the mouse coordinates.
x, y = pyautogui.position()
pixelColor = pyautogui.screenshot().getpixel((x, y))
positionStr = 'X: {:4}; Y: {:4}; RGB:{}'.format(x, y, pixelColor)
print(positionStr)
except KeyboardInterrupt:
print('\nDone.')
| true | true |
f7f9501600e1599aaa470dabe3cfc9f313bd705e | 6,845 | py | Python | foundryapp/foundryapp/report/sales_order/sales_order.py | umaepoch/foundryapp | 75e20cb399b114d416d3bdd286edd8c5a4690c75 | [
"MIT"
] | null | null | null | foundryapp/foundryapp/report/sales_order/sales_order.py | umaepoch/foundryapp | 75e20cb399b114d416d3bdd286edd8c5a4690c75 | [
"MIT"
] | null | null | null | foundryapp/foundryapp/report/sales_order/sales_order.py | umaepoch/foundryapp | 75e20cb399b114d416d3bdd286edd8c5a4690c75 | [
"MIT"
] | null | null | null | # Copyright (c) 2013, yashwanth and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
import datetime
def execute(filters=None):
columns = get_columns(filters)
sor_data = []
data = []
week = ""
day_of_week = {'Sunday': '1', 'Monday': '2', 'Tuesday': '3',
'Wednesday': '4', 'Thursday': '5', 'Friday': '6', 'Saturday': '7'}
foundry_settings = frappe.get_doc('FoundryApp Settings')
for k in day_of_week.keys():
if foundry_settings.weekly_planning_cycle_ends_on == k:
# print("week :",k," value :",day_of_week[k])
week = day_of_week[k]
if filters.get("show_dispatch_items") == 1:
data = fetch_dispatch_items_report(week)
if filters.get("show_dispatch_items") is None:
data = fetch_invoice_items_report(week)
datum = generate_qty_plan(data, filters)
sor_data = construct_report(datum, filters)
return columns, sor_data
# fetches the report for dispatch items data by joining sales order, sales order item, BOM, BOM item, Item.
def fetch_dispatch_items_report(week):
r_data = []
r_data = frappe.db.sql("""select tso.name, tso.po_no, tso.foreign_buyer_name, tso.final_destination,
tbi.item_code, tsi.pch_pallet_size, truncate((tsi.qty*tbi.qty)/tb.quantity, 0) as qty,
date_sub(date(tsi.delivery_date), interval dayofweek(tsi.delivery_date)-%s day) delivery_date
from `tabSales Order Item` as tsi
join `tabSales Order` as tso on tso.name = tsi.parent
join `tabBOM` as tb on tsi.item_code = tb.item
join `tabBOM Item` as tbi on tb.name = tbi.parent
join `tabItem` as ti on ti.item_code = tbi.item_code
where ti.pch_made=1 and tb.is_default=1
order by tso.po_no""",(week), as_dict=1)
return r_data
# fetches the report for dispatch items data by joining sales order, sales order item, Item.
def fetch_invoice_items_report(week):
r_data = []
r_data = frappe.db.sql("""select tso.name, tso.po_no, tso.foreign_buyer_name, tso.final_destination,
tsi.item_code, tsi.pch_pallet_size, tsi.qty, date_sub(date(tsi.delivery_date), interval dayofweek(tsi.delivery_date)-%s day) as delivery_date
from `tabSales Order Item` as tsi
join `tabSales Order` as tso on tso.name = tsi.parent
join `tabItem` as ti on ti.item_code = tsi.item_code
where ti.pch_made=1
order by tso.po_no,tsi.item_code""",(week), as_dict = 1)
return r_data
def generate_qty_plan(data, filters):
if filters.get("show_dispatch_items") == 1:
for d in data:
query = frappe.db.sql("""select tcc.parent, tbi.item_code, truncate(tcc.so_qty*tbi.qty/tb.quantity,0) as so_qty,
truncate(tcc.qty_to_be_filled*tbi.qty/tb.quantity, 0) as qty_to_be_filled
from `tabContainer Child` as tcc
join `tabContainer` as tc on tcc.parent = tc.name
join `tabBOM` as tb on tcc.item =tb.item
join `tabBOM Item` as tbi on tb.name = tbi.parent
where (tc.foreign_buyer=%s and tc.final_destination=%s) and (tbi.item_code=%s and tcc.so_no=%s) and tb.is_default=1""",
(d['foreign_buyer_name'], d['final_destination'], d['item_code'], d['name']), as_dict=1)
# print(query)
if len(query) > 0:
for q in query:
d['Quantity Planned in Containers'] = q['qty_to_be_filled']
d['Quantity not Planned in Containers'] = q['so_qty'] - q['qty_to_be_filled']
if len(query) == 0:
d['Quantity Planned in Containers'] = 0
d['Quantity not Planned in Containers'] = 0
if filters.get("show_dispatch_items") is None:
for d in data:
query = frappe.db.sql("""select tcc.parent, tcc.so_no, tcc.item, tcc.so_qty, tcc.qty_to_be_filled
from `tabContainer Child` as tcc
join `tabContainer` as tc on tcc.parent = tc.name
where (tc.foreign_buyer=%s and tc.final_destination=%s) and (tcc.item=%s and tcc.so_no=%s)""",
(d['foreign_buyer_name'], d['final_destination'], d['item_code'], d['name']), as_dict=1)
print(query)
if len(query) > 0:
for q in query:
d['Quantity Planned in Containers'] = q['qty_to_be_filled']
d['Quantity not Planned in Containers'] = q['so_qty'] - q['qty_to_be_filled']
if len(query) == 0:
d['Quantity Planned in Containers'] = 0
d['Quantity not Planned in Containers'] = 0
return data
def construct_report(data, filters):
r_data = []
if filters.get("foreign_buyer") and filters.get("final_destination"):
for d in data:
if ((d["foreign_buyer_name"] == filters.get("foreign_buyer")) and (d["final_destination"] == filters.get("final_destination"))):
r_data.append([d['name'],d['po_no'],d['foreign_buyer_name'],
d['final_destination'],d['item_code'],
d['pch_pallet_size'],d['qty'],d['delivery_date'].strftime("%d-%m-%y"),
d['Quantity Planned in Containers'],d['Quantity not Planned in Containers']])
elif filters.get("foreign_buyer"):
for d in data:
if d["foreign_buyer_name"] == filters.get("foreign_buyer"):
r_data.append([d['name'],d['po_no'],d['foreign_buyer_name'],
d['final_destination'],d['item_code'],
d['pch_pallet_size'],d['qty'],d['delivery_date'].strftime("%d-%m-%y"),
d['Quantity Planned in Containers'],d['Quantity not Planned in Containers']])
elif filters.get("final_destination"):
for d in data:
if d["final_destination"] == filters.get("final_destination"):
r_data.append([d['name'],d['po_no'],d['foreign_buyer_name'],
d['final_destination'],d['item_code'],
d['pch_pallet_size'],d['qty'],d['delivery_date'].strftime("%d-%m-%y"),
d['Quantity Planned in Containers'],d['Quantity not Planned in Containers']])
else:
for d in data:
r_data.append([d['name'],d['po_no'],d['foreign_buyer_name'],
d['final_destination'],d['item_code'],
d['pch_pallet_size'],d['qty'],d['delivery_date'].strftime("%d-%m-%y"),
d['Quantity Planned in Containers'],d['Quantity not Planned in Containers']])
# print(r_data)
return r_data
def get_columns(filters):
"""return columns"""
columns = []
if filters.get("show_dispatch_items") == 1:
columns = [
("Sales Order")+"::150",
("Customer PO Number")+"::100",
("Foreign Buyer Name")+":150",
("Port")+"::100",
("Dispatch Item")+"::100",
("Pallet Size")+"::80",
("Quantity")+"::70",
("Delivery Date")+"::100",
("Quantity Planned in Containers")+"::120",
("Quantity not Planned in Containers")+"::130",
]
if filters.get("show_dispatch_items") is None:
columns = [
("Sales Order")+"::150",
("Customer PO Number")+"::100",
("Foreign Buyer Name")+":150",
("Port")+"::100",
("Invoice Item")+"::100",
("Pallet Size")+"::80",
("Quantity")+"::70",
("Delivery Date")+"::100",
("Quantity Planned in Containers")+"::120",
("Quantity not Planned in Containers")+"::130",
]
return columns | 40.264706 | 148 | 0.662089 |
from __future__ import unicode_literals
import frappe
import datetime
def execute(filters=None):
columns = get_columns(filters)
sor_data = []
data = []
week = ""
day_of_week = {'Sunday': '1', 'Monday': '2', 'Tuesday': '3',
'Wednesday': '4', 'Thursday': '5', 'Friday': '6', 'Saturday': '7'}
foundry_settings = frappe.get_doc('FoundryApp Settings')
for k in day_of_week.keys():
if foundry_settings.weekly_planning_cycle_ends_on == k:
week = day_of_week[k]
if filters.get("show_dispatch_items") == 1:
data = fetch_dispatch_items_report(week)
if filters.get("show_dispatch_items") is None:
data = fetch_invoice_items_report(week)
datum = generate_qty_plan(data, filters)
sor_data = construct_report(datum, filters)
return columns, sor_data
def fetch_dispatch_items_report(week):
r_data = []
r_data = frappe.db.sql("""select tso.name, tso.po_no, tso.foreign_buyer_name, tso.final_destination,
tbi.item_code, tsi.pch_pallet_size, truncate((tsi.qty*tbi.qty)/tb.quantity, 0) as qty,
date_sub(date(tsi.delivery_date), interval dayofweek(tsi.delivery_date)-%s day) delivery_date
from `tabSales Order Item` as tsi
join `tabSales Order` as tso on tso.name = tsi.parent
join `tabBOM` as tb on tsi.item_code = tb.item
join `tabBOM Item` as tbi on tb.name = tbi.parent
join `tabItem` as ti on ti.item_code = tbi.item_code
where ti.pch_made=1 and tb.is_default=1
order by tso.po_no""",(week), as_dict=1)
return r_data
def fetch_invoice_items_report(week):
r_data = []
r_data = frappe.db.sql("""select tso.name, tso.po_no, tso.foreign_buyer_name, tso.final_destination,
tsi.item_code, tsi.pch_pallet_size, tsi.qty, date_sub(date(tsi.delivery_date), interval dayofweek(tsi.delivery_date)-%s day) as delivery_date
from `tabSales Order Item` as tsi
join `tabSales Order` as tso on tso.name = tsi.parent
join `tabItem` as ti on ti.item_code = tsi.item_code
where ti.pch_made=1
order by tso.po_no,tsi.item_code""",(week), as_dict = 1)
return r_data
def generate_qty_plan(data, filters):
if filters.get("show_dispatch_items") == 1:
for d in data:
query = frappe.db.sql("""select tcc.parent, tbi.item_code, truncate(tcc.so_qty*tbi.qty/tb.quantity,0) as so_qty,
truncate(tcc.qty_to_be_filled*tbi.qty/tb.quantity, 0) as qty_to_be_filled
from `tabContainer Child` as tcc
join `tabContainer` as tc on tcc.parent = tc.name
join `tabBOM` as tb on tcc.item =tb.item
join `tabBOM Item` as tbi on tb.name = tbi.parent
where (tc.foreign_buyer=%s and tc.final_destination=%s) and (tbi.item_code=%s and tcc.so_no=%s) and tb.is_default=1""",
(d['foreign_buyer_name'], d['final_destination'], d['item_code'], d['name']), as_dict=1)
if len(query) > 0:
for q in query:
d['Quantity Planned in Containers'] = q['qty_to_be_filled']
d['Quantity not Planned in Containers'] = q['so_qty'] - q['qty_to_be_filled']
if len(query) == 0:
d['Quantity Planned in Containers'] = 0
d['Quantity not Planned in Containers'] = 0
if filters.get("show_dispatch_items") is None:
for d in data:
query = frappe.db.sql("""select tcc.parent, tcc.so_no, tcc.item, tcc.so_qty, tcc.qty_to_be_filled
from `tabContainer Child` as tcc
join `tabContainer` as tc on tcc.parent = tc.name
where (tc.foreign_buyer=%s and tc.final_destination=%s) and (tcc.item=%s and tcc.so_no=%s)""",
(d['foreign_buyer_name'], d['final_destination'], d['item_code'], d['name']), as_dict=1)
print(query)
if len(query) > 0:
for q in query:
d['Quantity Planned in Containers'] = q['qty_to_be_filled']
d['Quantity not Planned in Containers'] = q['so_qty'] - q['qty_to_be_filled']
if len(query) == 0:
d['Quantity Planned in Containers'] = 0
d['Quantity not Planned in Containers'] = 0
return data
def construct_report(data, filters):
r_data = []
if filters.get("foreign_buyer") and filters.get("final_destination"):
for d in data:
if ((d["foreign_buyer_name"] == filters.get("foreign_buyer")) and (d["final_destination"] == filters.get("final_destination"))):
r_data.append([d['name'],d['po_no'],d['foreign_buyer_name'],
d['final_destination'],d['item_code'],
d['pch_pallet_size'],d['qty'],d['delivery_date'].strftime("%d-%m-%y"),
d['Quantity Planned in Containers'],d['Quantity not Planned in Containers']])
elif filters.get("foreign_buyer"):
for d in data:
if d["foreign_buyer_name"] == filters.get("foreign_buyer"):
r_data.append([d['name'],d['po_no'],d['foreign_buyer_name'],
d['final_destination'],d['item_code'],
d['pch_pallet_size'],d['qty'],d['delivery_date'].strftime("%d-%m-%y"),
d['Quantity Planned in Containers'],d['Quantity not Planned in Containers']])
elif filters.get("final_destination"):
for d in data:
if d["final_destination"] == filters.get("final_destination"):
r_data.append([d['name'],d['po_no'],d['foreign_buyer_name'],
d['final_destination'],d['item_code'],
d['pch_pallet_size'],d['qty'],d['delivery_date'].strftime("%d-%m-%y"),
d['Quantity Planned in Containers'],d['Quantity not Planned in Containers']])
else:
for d in data:
r_data.append([d['name'],d['po_no'],d['foreign_buyer_name'],
d['final_destination'],d['item_code'],
d['pch_pallet_size'],d['qty'],d['delivery_date'].strftime("%d-%m-%y"),
d['Quantity Planned in Containers'],d['Quantity not Planned in Containers']])
return r_data
def get_columns(filters):
columns = []
if filters.get("show_dispatch_items") == 1:
columns = [
("Sales Order")+"::150",
("Customer PO Number")+"::100",
("Foreign Buyer Name")+":150",
("Port")+"::100",
("Dispatch Item")+"::100",
("Pallet Size")+"::80",
("Quantity")+"::70",
("Delivery Date")+"::100",
("Quantity Planned in Containers")+"::120",
("Quantity not Planned in Containers")+"::130",
]
if filters.get("show_dispatch_items") is None:
columns = [
("Sales Order")+"::150",
("Customer PO Number")+"::100",
("Foreign Buyer Name")+":150",
("Port")+"::100",
("Invoice Item")+"::100",
("Pallet Size")+"::80",
("Quantity")+"::70",
("Delivery Date")+"::100",
("Quantity Planned in Containers")+"::120",
("Quantity not Planned in Containers")+"::130",
]
return columns | true | true |
f7f9506ecb7f7d0534f72c555c8854226aff2d09 | 6,792 | py | Python | ros/src/tl_detector/tl_detector.py | 1560800/CarND-Capstone | ec0cb8e99042e5002370f4cd62847d3d61586533 | [
"MIT"
] | 1 | 2019-12-13T11:04:59.000Z | 2019-12-13T11:04:59.000Z | ros/src/tl_detector/tl_detector.py | 1560800/CarND-Capstone | ec0cb8e99042e5002370f4cd62847d3d61586533 | [
"MIT"
] | null | null | null | ros/src/tl_detector/tl_detector.py | 1560800/CarND-Capstone | ec0cb8e99042e5002370f4cd62847d3d61586533 | [
"MIT"
] | 4 | 2019-12-16T08:35:27.000Z | 2019-12-18T07:23:28.000Z | #!/usr/bin/env python
import rospy
from std_msgs.msg import Int32
from geometry_msgs.msg import PoseStamped, Pose
from styx_msgs.msg import TrafficLightArray, TrafficLight
from styx_msgs.msg import Lane
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
from light_classification.tl_classifier import TLClassifier
import tf
import cv2
import yaml
from scipy.spatial import KDTree
import numpy as np
STATE_COUNT_THRESHOLD = 3
CLASSIFIER_ACTIVATION_DIST = 100
class TLDetector(object):
def __init__(self):
rospy.init_node('tl_detector')
self.pose = None
self.waypoints = None
self.waypoints_2d = None
self.waypoints_tree = None
self.camera_image = None
self.lights = []
rospy.Subscriber('/current_pose', PoseStamped, self.pose_cb)
rospy.Subscriber('/base_waypoints', Lane, self.waypoints_cb)
'''
/vehicle/traffic_lights provides you with the location of the traffic light in 3D map space and
helps you acquire an accurate ground truth data source for the traffic light
classifier by sending the current color state of all traffic lights in the
simulator. When testing on the vehicle, the color state will not be available. You'll need to
rely on the position of the light and the camera image to predict it.
'''
rospy.Subscriber('/vehicle/traffic_lights', TrafficLightArray, self.traffic_cb)
rospy.Subscriber('/image_color', Image, self.image_cb)
config_string = rospy.get_param("/traffic_light_config")
self.config = yaml.load(config_string)
rospy.logwarn("TL_Detector_Init")
self.upcoming_red_light_pub = rospy.Publisher('/traffic_waypoint', Int32, queue_size=1)
self.has_image = False
self.bridge = CvBridge()
self.light_classifier = TLClassifier(self.config['is_site'])
self.listener = tf.TransformListener()
self.has_image = False
self.state = TrafficLight.UNKNOWN
self.last_state = TrafficLight.UNKNOWN
self.last_wp = -1
self.state_count = 0
self.frame_skip_counter = 0
rospy.spin()
def pose_cb(self, msg):
self.pose = msg
def waypoints_cb(self, waypoints):
self.waypoints = waypoints
rospy.logwarn("TL getting waypoint")
if not self.waypoints_2d:
self.waypoints_2d = [[waypoint.pose.pose.position.x, waypoint.pose.pose.position.y] for waypoint in waypoints.waypoints]
self.waypoints_tree = KDTree(self.waypoints_2d)
def traffic_cb(self, msg):
self.lights = msg.lights
def image_cb(self, msg):
"""Identifies red lights in the incoming camera image and publishes the index
of the waypoint closest to the red light's stop line to /traffic_waypoint
Args:
msg (Image): image from car-mounted camera
"""
self.frame_skip_counter +=1
if(self.frame_skip_counter <= 4):
self.has_image = False
rospy.logwarn("TL Skipping Frame")
return
else:
self.frame_skip_counter =0
self.has_image = True
self.camera_image = msg
light_wp, state = self.process_traffic_lights()
rospy.logwarn("TL getting Image")
'''
Publish upcoming red lights at camera frequency.
Each predicted state has to occur `STATE_COUNT_THRESHOLD` number
of times till we start using it. Otherwise the previous stable state is
used.
'''
if self.state != state:
self.state_count = 0
self.state = state
elif self.state_count >= STATE_COUNT_THRESHOLD:
self.last_state = self.state
light_wp = light_wp if state == TrafficLight.RED else -1
self.last_wp = light_wp
self.upcoming_red_light_pub.publish(Int32(light_wp))
else:
self.upcoming_red_light_pub.publish(Int32(self.last_wp))
self.state_count += 1
def get_closest_waypoint(self, pose_x,pose_y):
"""Identifies the closest path waypoint to the given position
https://en.wikipedia.org/wiki/Closest_pair_of_points_problem
Args:
pose (Pose): position to match a waypoint to
Returns:
int: index of the closest waypoint in self.waypoints
"""
closest_idx = self.waypoints_tree.query([pose_x, pose_y],1)[1]
return closest_idx
def get_light_state(self, light):
"""Determines the current color of the traffic light
Args:
light (TrafficLight): light to classify
Returns:
int: ID of traffic light color (specified in styx_msgs/TrafficLight)
"""
#### Uncomment this for the ground truth
# return light.state
#### Integrate the traffic light classification here
if(not self.has_image):
self.prev_light_loc = None
return False
# print("Has image.......................")
cv_image = self.bridge.imgmsg_to_cv2(self.camera_image, "bgr8")
#Get classification
return self.light_classifier.get_classification(cv2.cvtColor(cv_image,cv2.COLOR_BGR2RGB))
def process_traffic_lights(self):
"""Finds closest visible traffic light, if one exists, and determines its
location and color
Returns:
int: index of waypoint closes to the upcoming stop line for a traffic light (-1 if none exists)
int: ID of traffic light color (specified in styx_msgs/TrafficLight)
"""
light = None
closest_light = None
line_wp_idx = None
car_position = None
# List of positions that correspond to the line to stop in front of for a given intersection
stop_line_positions = self.config['stop_line_positions']
if(self.pose and self.waypoints_tree and self.waypoints):
car_position = self.get_closest_waypoint(self.pose.pose.position.x, self.pose.pose.position.y)
diff = len(self.waypoints.waypoints)
for i,light in enumerate(self.lights):
line = stop_line_positions[i]
temp_wp_idx = self.get_closest_waypoint(line[0],line[1])
d = temp_wp_idx - car_position
if d >= 0 and d < diff:
diff = d
closest_light = light
line_wp_idx = temp_wp_idx
#TODO find the closest visible traffic light (if one exists)
if closest_light and diff < CLASSIFIER_ACTIVATION_DIST:
rospy.loginfo("... approaching [TL_stop_line: %s | distance to Traffic Light: %s] ..." % (line_wp_idx, diff))
state = self.get_light_state(closest_light)
return line_wp_idx, state
return -1, TrafficLight.UNKNOWN
if __name__ == '__main__':
try:
TLDetector()
except rospy.ROSInterruptException:
rospy.logerr('Could not start traffic node.')
| 36.913043 | 132 | 0.671378 |
import rospy
from std_msgs.msg import Int32
from geometry_msgs.msg import PoseStamped, Pose
from styx_msgs.msg import TrafficLightArray, TrafficLight
from styx_msgs.msg import Lane
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
from light_classification.tl_classifier import TLClassifier
import tf
import cv2
import yaml
from scipy.spatial import KDTree
import numpy as np
STATE_COUNT_THRESHOLD = 3
CLASSIFIER_ACTIVATION_DIST = 100
class TLDetector(object):
def __init__(self):
rospy.init_node('tl_detector')
self.pose = None
self.waypoints = None
self.waypoints_2d = None
self.waypoints_tree = None
self.camera_image = None
self.lights = []
rospy.Subscriber('/current_pose', PoseStamped, self.pose_cb)
rospy.Subscriber('/base_waypoints', Lane, self.waypoints_cb)
'''
/vehicle/traffic_lights provides you with the location of the traffic light in 3D map space and
helps you acquire an accurate ground truth data source for the traffic light
classifier by sending the current color state of all traffic lights in the
simulator. When testing on the vehicle, the color state will not be available. You'll need to
rely on the position of the light and the camera image to predict it.
'''
rospy.Subscriber('/vehicle/traffic_lights', TrafficLightArray, self.traffic_cb)
rospy.Subscriber('/image_color', Image, self.image_cb)
config_string = rospy.get_param("/traffic_light_config")
self.config = yaml.load(config_string)
rospy.logwarn("TL_Detector_Init")
self.upcoming_red_light_pub = rospy.Publisher('/traffic_waypoint', Int32, queue_size=1)
self.has_image = False
self.bridge = CvBridge()
self.light_classifier = TLClassifier(self.config['is_site'])
self.listener = tf.TransformListener()
self.has_image = False
self.state = TrafficLight.UNKNOWN
self.last_state = TrafficLight.UNKNOWN
self.last_wp = -1
self.state_count = 0
self.frame_skip_counter = 0
rospy.spin()
def pose_cb(self, msg):
self.pose = msg
def waypoints_cb(self, waypoints):
self.waypoints = waypoints
rospy.logwarn("TL getting waypoint")
if not self.waypoints_2d:
self.waypoints_2d = [[waypoint.pose.pose.position.x, waypoint.pose.pose.position.y] for waypoint in waypoints.waypoints]
self.waypoints_tree = KDTree(self.waypoints_2d)
def traffic_cb(self, msg):
self.lights = msg.lights
def image_cb(self, msg):
"""Identifies red lights in the incoming camera image and publishes the index
of the waypoint closest to the red light's stop line to /traffic_waypoint
Args:
msg (Image): image from car-mounted camera
"""
self.frame_skip_counter +=1
if(self.frame_skip_counter <= 4):
self.has_image = False
rospy.logwarn("TL Skipping Frame")
return
else:
self.frame_skip_counter =0
self.has_image = True
self.camera_image = msg
light_wp, state = self.process_traffic_lights()
rospy.logwarn("TL getting Image")
'''
Publish upcoming red lights at camera frequency.
Each predicted state has to occur `STATE_COUNT_THRESHOLD` number
of times till we start using it. Otherwise the previous stable state is
used.
'''
if self.state != state:
self.state_count = 0
self.state = state
elif self.state_count >= STATE_COUNT_THRESHOLD:
self.last_state = self.state
light_wp = light_wp if state == TrafficLight.RED else -1
self.last_wp = light_wp
self.upcoming_red_light_pub.publish(Int32(light_wp))
else:
self.upcoming_red_light_pub.publish(Int32(self.last_wp))
self.state_count += 1
def get_closest_waypoint(self, pose_x,pose_y):
"""Identifies the closest path waypoint to the given position
https://en.wikipedia.org/wiki/Closest_pair_of_points_problem
Args:
pose (Pose): position to match a waypoint to
Returns:
int: index of the closest waypoint in self.waypoints
"""
closest_idx = self.waypoints_tree.query([pose_x, pose_y],1)[1]
return closest_idx
def get_light_state(self, light):
"""Determines the current color of the traffic light
Args:
light (TrafficLight): light to classify
Returns:
int: ID of traffic light color (specified in styx_msgs/TrafficLight)
"""
2.cvtColor(cv_image,cv2.COLOR_BGR2RGB))
def process_traffic_lights(self):
"""Finds closest visible traffic light, if one exists, and determines its
location and color
Returns:
int: index of waypoint closes to the upcoming stop line for a traffic light (-1 if none exists)
int: ID of traffic light color (specified in styx_msgs/TrafficLight)
"""
light = None
closest_light = None
line_wp_idx = None
car_position = None
stop_line_positions = self.config['stop_line_positions']
if(self.pose and self.waypoints_tree and self.waypoints):
car_position = self.get_closest_waypoint(self.pose.pose.position.x, self.pose.pose.position.y)
diff = len(self.waypoints.waypoints)
for i,light in enumerate(self.lights):
line = stop_line_positions[i]
temp_wp_idx = self.get_closest_waypoint(line[0],line[1])
d = temp_wp_idx - car_position
if d >= 0 and d < diff:
diff = d
closest_light = light
line_wp_idx = temp_wp_idx
if closest_light and diff < CLASSIFIER_ACTIVATION_DIST:
rospy.loginfo("... approaching [TL_stop_line: %s | distance to Traffic Light: %s] ..." % (line_wp_idx, diff))
state = self.get_light_state(closest_light)
return line_wp_idx, state
return -1, TrafficLight.UNKNOWN
if __name__ == '__main__':
try:
TLDetector()
except rospy.ROSInterruptException:
rospy.logerr('Could not start traffic node.')
| false | true |
f7f9507910c13fb5948d92afaef10421278324ff | 4,040 | py | Python | src/tortuga/scripts/commonSpotInstanceCli.py | tprestegard/tortuga-kit-awsadapter | cde0a35befa8e5e65929a950fae597cd4adb37b7 | [
"Apache-2.0"
] | 3 | 2018-03-03T15:43:51.000Z | 2019-08-15T11:37:12.000Z | src/tortuga/scripts/commonSpotInstanceCli.py | tprestegard/tortuga-kit-awsadapter | cde0a35befa8e5e65929a950fae597cd4adb37b7 | [
"Apache-2.0"
] | 56 | 2018-03-02T20:24:17.000Z | 2020-11-21T00:29:20.000Z | src/tortuga/scripts/commonSpotInstanceCli.py | tprestegard/tortuga-kit-awsadapter | cde0a35befa8e5e65929a950fae597cd4adb37b7 | [
"Apache-2.0"
] | 11 | 2018-03-03T14:32:13.000Z | 2020-11-18T15:05:30.000Z | # Copyright 2008-2018 Univa Corporation
#
# 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 json
from typing import Generator, List, Optional, Tuple, Dict
from tortuga.cli.tortugaCli import TortugaCli
from tortuga.wsapi.metadataWsApi import MetadataWsApi
from tortuga.wsapi.resourceAdapterConfigurationWsApi import \
ResourceAdapterConfigurationWsApi
from .spot_common import SpotInstanceCommonMixin
class CommonSpotInstanceCLI(TortugaCli, SpotInstanceCommonMixin):
def __init__(self):
super().__init__()
self.__metadataWsApi: Optional[MetadataWsApi] = None
@property
def metadataWsApi(self):
if self.__metadataWsApi is None:
self.__metadataWsApi = self.configureClient(MetadataWsApi)
return self.__metadataWsApi
def _get_spot_instance_request(
self,
sir_id: str,
) -> Optional[Tuple[str, dict, Optional[str]]]:
result = self.metadataWsApi.list(filter_key=sir_id)
if not result:
return None
return self.__get_spot_instance_tuple(result[0])
def _iter_spot_instance_requests(
self,
adapter_cfg_name: Optional[str] = None
) -> Generator[Tuple[str, dict, Optional[str]], None, None]:
"""
Iterate on instance metadata results; filtering out any non-spot
instance requests as well as those not matching the specified
resource adapter configuration profile.
"""
for item in self.metadataWsApi.list():
if not item['key'].startswith('sir-'):
continue
sir_id, sir_metadata, node_name = self.__get_spot_instance_tuple(item)
if adapter_cfg_name and \
sir_metadata['resource_adapter_configuration'] != \
adapter_cfg_name:
continue
yield sir_id, sir_metadata, node_name
def __get_spot_instance_tuple(self, item: dict) \
-> Tuple[str, dict, Optional[str]]:
sir_metadata = json.loads(item['value'])
name = item['instance']['node']['name'] \
if item.get('instance') else None
return item['key'], sir_metadata, name
def _get_adapter_cfg(self, name: str) -> dict:
"""
Return list of resource adapter configuration dicts
"""
resourceAdapterConfigurationWsApi = self.configureClient(ResourceAdapterConfigurationWsApi)
adapter_cfg = resourceAdapterConfigurationWsApi.get(
'AWS',
'Default',
)['configuration']
result = self.__get_adapter_cfg_as_dict(adapter_cfg)
if name != 'Default':
resource_adapter_cfg = resourceAdapterConfigurationWsApi.get(
'AWS',
name,
)['configuration']
result.update(self.__get_adapter_cfg_as_dict(resource_adapter_cfg))
return result
def __get_adapter_cfg_as_dict(self, adapter_cfg: List[dict]) \
-> Dict[str, str]:
"""
Convert list of dict output from resource adapter WS API to
dict keyed on setting name.
"""
return {item['key']: item for item in adapter_cfg}
def _get_adapter_cfg_key(self, adapter_cfg: dict, key: str) \
-> Optional[str]:
"""
Iterate over list of resource adapter configuration key-value pairs
"""
entry = adapter_cfg.get(key)
if entry is None:
return entry
return entry.get('value')
| 33.114754 | 99 | 0.648267 |
import json
from typing import Generator, List, Optional, Tuple, Dict
from tortuga.cli.tortugaCli import TortugaCli
from tortuga.wsapi.metadataWsApi import MetadataWsApi
from tortuga.wsapi.resourceAdapterConfigurationWsApi import \
ResourceAdapterConfigurationWsApi
from .spot_common import SpotInstanceCommonMixin
class CommonSpotInstanceCLI(TortugaCli, SpotInstanceCommonMixin):
def __init__(self):
super().__init__()
self.__metadataWsApi: Optional[MetadataWsApi] = None
@property
def metadataWsApi(self):
if self.__metadataWsApi is None:
self.__metadataWsApi = self.configureClient(MetadataWsApi)
return self.__metadataWsApi
def _get_spot_instance_request(
self,
sir_id: str,
) -> Optional[Tuple[str, dict, Optional[str]]]:
result = self.metadataWsApi.list(filter_key=sir_id)
if not result:
return None
return self.__get_spot_instance_tuple(result[0])
def _iter_spot_instance_requests(
self,
adapter_cfg_name: Optional[str] = None
) -> Generator[Tuple[str, dict, Optional[str]], None, None]:
for item in self.metadataWsApi.list():
if not item['key'].startswith('sir-'):
continue
sir_id, sir_metadata, node_name = self.__get_spot_instance_tuple(item)
if adapter_cfg_name and \
sir_metadata['resource_adapter_configuration'] != \
adapter_cfg_name:
continue
yield sir_id, sir_metadata, node_name
def __get_spot_instance_tuple(self, item: dict) \
-> Tuple[str, dict, Optional[str]]:
sir_metadata = json.loads(item['value'])
name = item['instance']['node']['name'] \
if item.get('instance') else None
return item['key'], sir_metadata, name
def _get_adapter_cfg(self, name: str) -> dict:
resourceAdapterConfigurationWsApi = self.configureClient(ResourceAdapterConfigurationWsApi)
adapter_cfg = resourceAdapterConfigurationWsApi.get(
'AWS',
'Default',
)['configuration']
result = self.__get_adapter_cfg_as_dict(adapter_cfg)
if name != 'Default':
resource_adapter_cfg = resourceAdapterConfigurationWsApi.get(
'AWS',
name,
)['configuration']
result.update(self.__get_adapter_cfg_as_dict(resource_adapter_cfg))
return result
def __get_adapter_cfg_as_dict(self, adapter_cfg: List[dict]) \
-> Dict[str, str]:
return {item['key']: item for item in adapter_cfg}
def _get_adapter_cfg_key(self, adapter_cfg: dict, key: str) \
-> Optional[str]:
entry = adapter_cfg.get(key)
if entry is None:
return entry
return entry.get('value')
| true | true |
f7f951cb3e510cfefab6b6099260d453a2eaf7d7 | 4,760 | py | Python | genetic_algorithm/models/zoo/preprocess_c.py | JacobARose/genetic_algorithm | de4c52637f6b928b96c0306b7da59a054322b56c | [
"Apache-2.0"
] | null | null | null | genetic_algorithm/models/zoo/preprocess_c.py | JacobARose/genetic_algorithm | de4c52637f6b928b96c0306b7da59a054322b56c | [
"Apache-2.0"
] | null | null | null | genetic_algorithm/models/zoo/preprocess_c.py | JacobARose/genetic_algorithm | de4c52637f6b928b96c0306b7da59a054322b56c | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import tensorflow as tf
from tensorflow.keras import Sequential, Model, Input
from tensorflow.keras import layers
from tensorflow.keras.layers import ReLU, Dense, Conv2D, Conv2DTranspose
from tensorflow.keras.layers import DepthwiseConv2D, SeparableConv2D, Dropout
from tensorflow.keras.layers import GlobalAveragePooling2D, Activation, BatchNormalization
from tensorflow.keras.regularizers import l2
from tensorflow.keras.optimizers import Adam, SGD
from tensorflow.compat.v1.keras.initializers import glorot_uniform, he_normal
from tensorflow.keras.callbacks import LearningRateScheduler
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.utils import to_categorical
import tensorflow_datasets as tfds
import tensorflow.keras.backend as K
import numpy as np
from sklearn.model_selection import train_test_split
from tfrecord_utils.img_utils import resize_repeat
from boltons.funcutils import partial
import random
import math
import sys
def get_parse_example_func(target_size=(224,224,3), num_classes=10):
resize = resize_repeat(target_size=tuple(target_size), training=False)
one_hot = partial(tf.one_hot, depth=num_classes)
def _parse_example(x, y):
x = tf.image.convert_image_dtype(x, tf.float32)
x = resize(x)
y = one_hot(y)
return x,y
return _parse_example
# def resize(self):
# def preprocess_data(data: tf.data.Dataset, target_size=None, num_classes=None, batch_size=1, buffer_size=1024): #class_encoder=None):
# parse_example = get_parse_example_func(target_size=target_size, num_classes=num_classes) #class_encoder=class_encoder)
# return data.map(lambda x,y: parse_example(x, y), num_parallel_calls=-1) \
# .shuffle(buffer_size) \
# .batch(batch_size) \
# .prefetch(-1)
class Preprocess:
''' Preprocess base (super) class for Composable Models '''
def __init__(self):
""" Constructor
"""
pass
###
# Preprocessing
###
def normalization(self, x_train, x_test=None, centered=False):
""" Normalize the input
x_train : training images
y_train : test images
"""
if x_train.dtype == np.uint8:
if centered:
x_train = ((x_train - 1) / 127.5).astype(np.float32)
if x_test is not None:
x_test = ((x_test - 1) / 127.5).astype(np.float32)
else:
x_train = (x_train / 255.0).astype(np.float32)
if x_test is not None:
x_test = (x_test / 255.0).astype(np.float32)
return x_train, x_test
def standardization(self, x_train, x_test=None):
""" Standardize the input
x_train : training images
x_test : test images
"""
self.mean = np.mean(x_train)
self.std = np.std(x_train)
x_train = ((x_train - self.mean) / self.std).astype(np.float32)
if x_test is not None:
x_test = ((x_test - self.mean) / self.std).astype(np.float32)
return x_train, x_test
def label_smoothing(self, y_train, n_classes, factor=0.1):
""" Convert a matrix of one-hot row-vector labels into smoothed versions.
y_train : training labels
n_classes: number of classes
factor : smoothing factor (between 0 and 1)
"""
if 0 <= factor <= 1:
# label smoothing ref: https://www.robots.ox.ac.uk/~vgg/rg/papers/reinception.pdf
y_train *= 1 - factor
y_train += factor / n_classes
else:
raise Exception('Invalid label smoothing factor: ' + str(factor))
return y_train
## class-Weighted label smoothing
# def class_weight(labels_dict,mu=0.15):
# total = np.sum(labels_dict.values())
# keys = labels_dict.keys()
# weight = dict()
# for i in keys:
# score = np.log(mu*total/float(labels_dict[i]))
# weight[i] = score if score > 1 else 1
# return weight
# # random labels_dict
# labels_dict = df[target_Y].value_counts().to_dict()
# weights = class_weight(labels_dict) | 37.777778 | 135 | 0.669328 |
import tensorflow as tf
from tensorflow.keras import Sequential, Model, Input
from tensorflow.keras import layers
from tensorflow.keras.layers import ReLU, Dense, Conv2D, Conv2DTranspose
from tensorflow.keras.layers import DepthwiseConv2D, SeparableConv2D, Dropout
from tensorflow.keras.layers import GlobalAveragePooling2D, Activation, BatchNormalization
from tensorflow.keras.regularizers import l2
from tensorflow.keras.optimizers import Adam, SGD
from tensorflow.compat.v1.keras.initializers import glorot_uniform, he_normal
from tensorflow.keras.callbacks import LearningRateScheduler
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.utils import to_categorical
import tensorflow_datasets as tfds
import tensorflow.keras.backend as K
import numpy as np
from sklearn.model_selection import train_test_split
from tfrecord_utils.img_utils import resize_repeat
from boltons.funcutils import partial
import random
import math
import sys
def get_parse_example_func(target_size=(224,224,3), num_classes=10):
resize = resize_repeat(target_size=tuple(target_size), training=False)
one_hot = partial(tf.one_hot, depth=num_classes)
def _parse_example(x, y):
x = tf.image.convert_image_dtype(x, tf.float32)
x = resize(x)
y = one_hot(y)
return x,y
return _parse_example
pass
def normalization(self, x_train, x_test=None, centered=False):
if x_train.dtype == np.uint8:
if centered:
x_train = ((x_train - 1) / 127.5).astype(np.float32)
if x_test is not None:
x_test = ((x_test - 1) / 127.5).astype(np.float32)
else:
x_train = (x_train / 255.0).astype(np.float32)
if x_test is not None:
x_test = (x_test / 255.0).astype(np.float32)
return x_train, x_test
def standardization(self, x_train, x_test=None):
self.mean = np.mean(x_train)
self.std = np.std(x_train)
x_train = ((x_train - self.mean) / self.std).astype(np.float32)
if x_test is not None:
x_test = ((x_test - self.mean) / self.std).astype(np.float32)
return x_train, x_test
def label_smoothing(self, y_train, n_classes, factor=0.1):
if 0 <= factor <= 1:
y_train *= 1 - factor
y_train += factor / n_classes
else:
raise Exception('Invalid label smoothing factor: ' + str(factor))
return y_train
| true | true |
f7f951d12a4b67f49be963a01a11b78e12557fc9 | 3,517 | py | Python | setup.py | ObsidianProtocol/obsidian-rpc-python | 1f977f06af37c871e7257e04fb81a06eaf7bca32 | [
"MIT"
] | null | null | null | setup.py | ObsidianProtocol/obsidian-rpc-python | 1f977f06af37c871e7257e04fb81a06eaf7bca32 | [
"MIT"
] | null | null | null | setup.py | ObsidianProtocol/obsidian-rpc-python | 1f977f06af37c871e7257e04fb81a06eaf7bca32 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Note: To use the 'upload' functionality of this file, you must:
# $ pip install twine
import io
import os
import sys
from shutil import rmtree
from setuptools import find_packages, setup, Command
# Package meta-data.
NAME = 'obsidian'
DESCRIPTION = 'A Python wrapper for the obsidian JSON-RPC interface'
URL = 'https://github.com/arthurk/obsidian-python/'
EMAIL = 'arthur@arthurkoziel.com'
AUTHOR = 'Arthur Koziel'
REQUIRES_PYTHON = '>=3.6.0'
VERSION = None
# What packages are required for this module to be executed?
REQUIRED = [
'requests'
]
# The rest you shouldn't have to touch too much :)
# ------------------------------------------------
# Except, perhaps the License and Trove Classifiers!
# If you do change the License, remember to change the Trove Classifier for that!
here = os.path.abspath(os.path.dirname(__file__))
# Import the README and use it as the long-description.
# Note: this will only work if 'README.rst' is present in your MANIFEST.in file!
with io.open(os.path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = '\n' + f.read()
# Load the package's __version__.py module as a dictionary.
about = {}
if not VERSION:
with open(os.path.join(here, NAME, '__version__.py')) as f:
exec(f.read(), about)
else:
about['__version__'] = VERSION
class UploadCommand(Command):
"""Support setup.py upload."""
description = 'Build and publish the package.'
user_options = []
@staticmethod
def status(s):
"""Prints things in bold."""
print('\033[1m{0}\033[0m'.format(s))
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
try:
self.status('Removing previous builds…')
rmtree(os.path.join(here, 'dist'))
except OSError:
pass
self.status('Building Source and Wheel (universal) distribution…')
os.system('{0} setup.py sdist bdist_wheel --universal'.format(sys.executable))
self.status('Uploading the package to PyPi via Twine…')
os.system('twine upload dist/*')
self.status('Pushing git tags…')
os.system('git tag v{0}'.format(about['__version__']))
os.system('git push --tags')
sys.exit()
# Where the magic happens:
setup(
name=NAME,
version=about['__version__'],
description=DESCRIPTION,
long_description=long_description,
author=AUTHOR,
author_email=EMAIL,
python_requires=REQUIRES_PYTHON,
url=URL,
packages=find_packages(exclude=('tests',)),
# If your package is a single module, use this instead of 'packages':
# py_modules=['mypackage'],
# entry_points={
# 'console_scripts': ['mycli=mymodule:cli'],
# },
install_requires=REQUIRED,
extras_require={
'docs': ['sphinx>=1.7', 'sphinx_rtd_theme'],
},
include_package_data=True,
license='MIT',
classifiers=[
# Trove classifiers
# Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy'
],
# $ setup.py publish support.
cmdclass={
'upload': UploadCommand,
},
)
| 28.362903 | 86 | 0.639181 |
import io
import os
import sys
from shutil import rmtree
from setuptools import find_packages, setup, Command
NAME = 'obsidian'
DESCRIPTION = 'A Python wrapper for the obsidian JSON-RPC interface'
URL = 'https://github.com/arthurk/obsidian-python/'
EMAIL = 'arthur@arthurkoziel.com'
AUTHOR = 'Arthur Koziel'
REQUIRES_PYTHON = '>=3.6.0'
VERSION = None
REQUIRED = [
'requests'
]
# ------------------------------------------------
# Except, perhaps the License and Trove Classifiers!
# If you do change the License, remember to change the Trove Classifier for that!
here = os.path.abspath(os.path.dirname(__file__))
# Import the README and use it as the long-description.
# Note: this will only work if 'README.rst' is present in your MANIFEST.in file!
with io.open(os.path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = '\n' + f.read()
# Load the package's __version__.py module as a dictionary.
about = {}
if not VERSION:
with open(os.path.join(here, NAME, '__version__.py')) as f:
exec(f.read(), about)
else:
about['__version__'] = VERSION
class UploadCommand(Command):
description = 'Build and publish the package.'
user_options = []
@staticmethod
def status(s):
print('\033[1m{0}\033[0m'.format(s))
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
try:
self.status('Removing previous builds…')
rmtree(os.path.join(here, 'dist'))
except OSError:
pass
self.status('Building Source and Wheel (universal) distribution…')
os.system('{0} setup.py sdist bdist_wheel --universal'.format(sys.executable))
self.status('Uploading the package to PyPi via Twine…')
os.system('twine upload dist/*')
self.status('Pushing git tags…')
os.system('git tag v{0}'.format(about['__version__']))
os.system('git push --tags')
sys.exit()
setup(
name=NAME,
version=about['__version__'],
description=DESCRIPTION,
long_description=long_description,
author=AUTHOR,
author_email=EMAIL,
python_requires=REQUIRES_PYTHON,
url=URL,
packages=find_packages(exclude=('tests',)),
install_requires=REQUIRED,
extras_require={
'docs': ['sphinx>=1.7', 'sphinx_rtd_theme'],
},
include_package_data=True,
license='MIT',
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy'
],
cmdclass={
'upload': UploadCommand,
},
)
| true | true |
f7f95228e55ecf40da724ea9666d239bc69011ea | 28,042 | py | Python | dwave_networkx/algorithms/elimination_ordering.py | CatherineCMcGeoch/dwave_networkx | 126731c516d31e7bf0491f3034ccecdb79d648fb | [
"Apache-2.0"
] | 1 | 2022-02-01T14:40:05.000Z | 2022-02-01T14:40:05.000Z | dwave_networkx/algorithms/elimination_ordering.py | CatherineCMcGeoch/dwave_networkx | 126731c516d31e7bf0491f3034ccecdb79d648fb | [
"Apache-2.0"
] | null | null | null | dwave_networkx/algorithms/elimination_ordering.py | CatherineCMcGeoch/dwave_networkx | 126731c516d31e7bf0491f3034ccecdb79d648fb | [
"Apache-2.0"
] | 1 | 2022-02-01T14:40:31.000Z | 2022-02-01T14:40:31.000Z | # 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 itertools
from random import random, sample
import networkx as nx
from dwave_networkx.generators.pegasus import pegasus_coordinates
__all__ = ['is_almost_simplicial',
'is_simplicial',
'chimera_elimination_order',
'pegasus_elimination_order',
'max_cardinality_heuristic',
'min_fill_heuristic',
'min_width_heuristic',
'treewidth_branch_and_bound',
'minor_min_width',
'elimination_order_width',
]
def is_simplicial(G, n):
"""Determines whether a node n in G is simplicial.
Parameters
----------
G : NetworkX graph
The graph on which to check whether node n is simplicial.
n : node
A node in graph G.
Returns
-------
is_simplicial : bool
True if its neighbors form a clique.
Examples
--------
This example checks whether node 0 is simplicial for two graphs: G, a
single Chimera unit cell, which is bipartite, and K_5, the :math:`K_5`
complete graph.
>>> G = dnx.chimera_graph(1, 1, 4)
>>> K_5 = nx.complete_graph(5)
>>> dnx.is_simplicial(G, 0)
False
>>> dnx.is_simplicial(K_5, 0)
True
"""
return all(u in G[v] for u, v in itertools.combinations(G[n], 2))
def is_almost_simplicial(G, n):
"""Determines whether a node n in G is almost simplicial.
Parameters
----------
G : NetworkX graph
The graph on which to check whether node n is almost simplicial.
n : node
A node in graph G.
Returns
-------
is_almost_simplicial : bool
True if all but one of its neighbors induce a clique
Examples
--------
This example checks whether node 0 is simplicial or almost simplicial for
a :math:`K_5` complete graph with one edge removed.
>>> K_5 = nx.complete_graph(5)
>>> K_5.remove_edge(1,3)
>>> dnx.is_simplicial(K_5, 0)
False
>>> dnx.is_almost_simplicial(K_5, 0)
True
"""
for w in G[n]:
if all(u in G[v] for u, v in itertools.combinations(G[n], 2) if u != w and v != w):
return True
return False
def minor_min_width(G):
"""Computes a lower bound for the treewidth of graph G.
Parameters
----------
G : NetworkX graph
The graph on which to compute a lower bound on the treewidth.
Returns
-------
lb : int
A lower bound on the treewidth.
Examples
--------
This example computes a lower bound for the treewidth of the :math:`K_7`
complete graph.
>>> K_7 = nx.complete_graph(7)
>>> dnx.minor_min_width(K_7)
6
References
----------
Based on the algorithm presented in [GD]_
"""
# we need only deal with the adjacency structure of G. We will also
# be manipulating it directly so let's go ahead and make a new one
adj = {v: set(u for u in G[v] if u != v) for v in G}
lb = 0 # lower bound on treewidth
while len(adj) > 1:
# get the node with the smallest degree
v = min(adj, key=lambda v: len(adj[v]))
# find the vertex u such that the degree of u is minimal in the neighborhood of v
neighbors = adj[v]
if not neighbors:
# if v is a singleton, then we can just delete it
del adj[v]
continue
def neighborhood_degree(u):
Gu = adj[u]
return sum(w in Gu for w in neighbors)
u = min(neighbors, key=neighborhood_degree)
# update the lower bound
new_lb = len(adj[v])
if new_lb > lb:
lb = new_lb
# contract the edge between u, v
adj[v] = adj[v].union(n for n in adj[u] if n != v)
for n in adj[v]:
adj[n].add(v)
for n in adj[u]:
adj[n].discard(u)
del adj[u]
return lb
def min_fill_heuristic(G):
"""Computes an upper bound on the treewidth of graph G based on
the min-fill heuristic for the elimination ordering.
Parameters
----------
G : NetworkX graph
The graph on which to compute an upper bound for the treewidth.
Returns
-------
treewidth_upper_bound : int
An upper bound on the treewidth of the graph G.
order : list
An elimination order that induces the treewidth.
Examples
--------
This example computes an upper bound for the treewidth of the :math:`K_4`
complete graph.
>>> K_4 = nx.complete_graph(4)
>>> tw, order = dnx.min_fill_heuristic(K_4)
References
----------
Based on the algorithm presented in [GD]_
"""
# we need only deal with the adjacency structure of G. We will also
# be manipulating it directly so let's go ahead and make a new one
adj = {v: set(u for u in G[v] if u != v) for v in G}
num_nodes = len(adj)
# preallocate the return values
order = [0] * num_nodes
upper_bound = 0
for i in range(num_nodes):
# get the node that adds the fewest number of edges when eliminated from the graph
v = min(adj, key=lambda x: _min_fill_needed_edges(adj, x))
# if the number of neighbours of v is higher than upper_bound, update
dv = len(adj[v])
if dv > upper_bound:
upper_bound = dv
# make v simplicial by making its neighborhood a clique then remove the
# node
_elim_adj(adj, v)
order[i] = v
return upper_bound, order
def _min_fill_needed_edges(adj, n):
# determines how many edges would needed to be added to G in order
# to make node n simplicial.
e = 0 # number of edges needed
for u, v in itertools.combinations(adj[n], 2):
if u not in adj[v]:
e += 1
# We add random() which picks a value in the range [0., 1.). This is ok because the
# e are all integers. By adding a small random value, we randomize which node is
# chosen without affecting correctness.
return e + random()
def min_width_heuristic(G):
"""Computes an upper bound on the treewidth of graph G based on
the min-width heuristic for the elimination ordering.
Parameters
----------
G : NetworkX graph
The graph on which to compute an upper bound for the treewidth.
Returns
-------
treewidth_upper_bound : int
An upper bound on the treewidth of the graph G.
order : list
An elimination order that induces the treewidth.
Examples
--------
This example computes an upper bound for the treewidth of the :math:`K_4`
complete graph.
>>> K_4 = nx.complete_graph(4)
>>> tw, order = dnx.min_width_heuristic(K_4)
References
----------
Based on the algorithm presented in [GD]_
"""
# we need only deal with the adjacency structure of G. We will also
# be manipulating it directly so let's go ahead and make a new one
adj = {v: set(u for u in G[v] if u != v) for v in G}
num_nodes = len(adj)
# preallocate the return values
order = [0] * num_nodes
upper_bound = 0
for i in range(num_nodes):
# get the node with the smallest degree. We add random() which picks a value
# in the range [0., 1.). This is ok because the lens are all integers. By
# adding a small random value, we randomize which node is chosen without affecting
# correctness.
v = min(adj, key=lambda u: len(adj[u]) + random())
# if the number of neighbours of v is higher than upper_bound, update
dv = len(adj[v])
if dv > upper_bound:
upper_bound = dv
# make v simplicial by making its neighborhood a clique then remove the
# node
_elim_adj(adj, v)
order[i] = v
return upper_bound, order
def max_cardinality_heuristic(G):
"""Computes an upper bound on the treewidth of graph G based on
the max-cardinality heuristic for the elimination ordering.
Parameters
----------
G : NetworkX graph
The graph on which to compute an upper bound for the treewidth.
Returns
-------
treewidth_upper_bound : int
An upper bound on the treewidth of the graph G.
order : list
An elimination order that induces the treewidth.
Examples
--------
This example computes an upper bound for the treewidth of the :math:`K_4`
complete graph.
>>> K_4 = nx.complete_graph(4)
>>> tw, order = dnx.max_cardinality_heuristic(K_4)
References
----------
Based on the algorithm presented in [GD]_
"""
# we need only deal with the adjacency structure of G. We will also
# be manipulating it directly so let's go ahead and make a new one
adj = {v: set(u for u in G[v] if u != v) for v in G}
num_nodes = len(adj)
# preallocate the return values
order = [0] * num_nodes
upper_bound = 0
# we will need to track the nodes and how many labelled neighbors
# each node has
labelled_neighbors = {v: 0 for v in adj}
# working backwards
for i in range(num_nodes):
# pick the node with the most labelled neighbors
v = max(labelled_neighbors, key=lambda u: labelled_neighbors[u] + random())
del labelled_neighbors[v]
# increment all of its neighbors
for u in adj[v]:
if u in labelled_neighbors:
labelled_neighbors[u] += 1
order[-(i + 1)] = v
for v in order:
# if the number of neighbours of v is higher than upper_bound, update
dv = len(adj[v])
if dv > upper_bound:
upper_bound = dv
# make v simplicial by making its neighborhood a clique then remove the node
# add v to order
_elim_adj(adj, v)
return upper_bound, order
def _elim_adj(adj, n):
"""eliminates a variable, acting on the adj matrix of G,
returning set of edges that were added.
Parameters
----------
adj: dict
A dict of the form {v: neighbors, ...} where v are
vertices in a graph and neighbors is a set.
Returns
----------
new_edges: set of edges that were added by eliminating v.
"""
neighbors = adj[n]
new_edges = set()
for u, v in itertools.combinations(neighbors, 2):
if v not in adj[u]:
adj[u].add(v)
adj[v].add(u)
new_edges.add((u, v))
new_edges.add((v, u))
for v in neighbors:
adj[v].discard(n)
del adj[n]
return new_edges
def elimination_order_width(G, order):
"""Calculates the width of the tree decomposition induced by a
variable elimination order.
Parameters
----------
G : NetworkX graph
The graph on which to compute the width of the tree decomposition.
order : list
The elimination order. Must be a list of all of the variables
in G.
Returns
-------
treewidth : int
The width of the tree decomposition induced by order.
Examples
--------
This example computes the width of the tree decomposition for the :math:`K_4`
complete graph induced by an elimination order found through the min-width
heuristic.
>>> K_4 = nx.complete_graph(4)
>>> tw, order = dnx.min_width_heuristic(K_4)
>>> print(tw)
3
>>> dnx.elimination_order_width(K_4, order)
3
"""
# we need only deal with the adjacency structure of G. We will also
# be manipulating it directly so let's go ahead and make a new one
adj = {v: set(u for u in G[v] if u != v) for v in G}
treewidth = 0
for v in order:
# get the degree of the eliminated variable
try:
dv = len(adj[v])
except KeyError:
raise ValueError('{} is in order but not in G'.format(v))
# the treewidth is the max of the current treewidth and the degree
if dv > treewidth:
treewidth = dv
# eliminate v by making it simplicial (acts on adj in place)
_elim_adj(adj, v)
# if adj is not empty, then order did not include all of the nodes in G.
if adj:
raise ValueError('not all nodes in G were in order')
return treewidth
def treewidth_branch_and_bound(G, elimination_order=None, treewidth_upperbound=None):
"""Computes the treewidth of graph G and a corresponding perfect elimination ordering.
Alogorithm based on [GD]_.
Parameters
----------
G : NetworkX graph
The graph on which to compute the treewidth and perfect elimination ordering.
elimination_order: list (optional, Default None)
An elimination order used as an initial best-known order. If a good
order is provided, it may speed up computation. If not provided, the
initial order is generated using the min-fill heuristic.
treewidth_upperbound : int (optional, Default None)
An upper bound on the treewidth. Note that using
this parameter can result in no returned order.
Returns
-------
treewidth : int
The treewidth of graph G.
order : list
An elimination order that induces the treewidth.
Examples
--------
This example computes the treewidth for the :math:`K_7`
complete graph using an optionally provided elimination order (a sequential
ordering of the nodes, arbitrally chosen).
>>> K_7 = nx.complete_graph(7)
>>> dnx.treewidth_branch_and_bound(K_7, [0, 1, 2, 3, 4, 5, 6])
(6, [0, 1, 2, 3, 4, 5, 6])
References
----------
.. [GD] Gogate & Dechter, "A Complete Anytime Algorithm for Treewidth",
https://arxiv.org/abs/1207.4109
"""
# empty graphs have treewidth 0 and the nodes can be eliminated in
# any order
if not any(G[v] for v in G):
return 0, list(G)
# variable names are chosen to match the paper
# our order will be stored in vector x, named to be consistent with
# the paper
x = [] # the partial order
f = minor_min_width(G) # our current lower bound guess, f(s) in the paper
g = 0 # g(s) in the paper
# we need the best current update we can find.
ub, order = min_fill_heuristic(G)
# if the user has provided an upperbound or an elimination order, check those against
# our current best guess
if elimination_order is not None:
upperbound = elimination_order_width(G, elimination_order)
if upperbound <= ub:
ub, order = upperbound, elimination_order
if treewidth_upperbound is not None and treewidth_upperbound < ub:
# in this case the order might never be found
ub, order = treewidth_upperbound, []
# best found encodes the ub and the order
best_found = ub, order
# if our upper bound is the same as f, then we are done! Otherwise begin the
# algorithm.
if f < ub:
# we need only deal with the adjacency structure of G. We will also
# be manipulating it directly so let's go ahead and make a new one
adj = {v: set(u for u in G[v] if u != v) for v in G}
best_found = _branch_and_bound(adj, x, g, f, best_found)
elif f > ub and treewidth_upperbound is None:
raise RuntimeError("logic error")
return best_found
def _branch_and_bound(adj, x, g, f, best_found, skipable=set(), theorem6p2=None):
""" Recursive branch and bound for computing treewidth of a subgraph.
adj: adjacency list
x: partial elimination order
g: width of x so far
f: lower bound on width of any elimination order starting with x
best_found = ub,order: best upper bound on the treewidth found so far, and its elimination order
skipable: vertices that can be skipped according to Lemma 5.3
theorem6p2: terms that have been explored/can be pruned according to Theorem 6.2
"""
# theorem6p2 checks for branches that can be pruned using Theorem 6.2
if theorem6p2 is None:
theorem6p2 = _theorem6p2()
prune6p2, explored6p2, finished6p2 = theorem6p2
# current6p2 is the list of prunable terms created during this instantiation of _branch_and_bound.
# These terms will only be use during this call and its successors,
# so they are removed before the function terminates.
current6p2 = list()
# theorem6p4 checks for branches that can be pruned using Theorem 6.4.
# These terms do not need to be passed to successive calls to _branch_and_bound,
# so they are simply created and deleted during this call.
prune6p4, explored6p4 = _theorem6p4()
# Note: theorem6p1 and theorem6p3 are a pruning strategies that are currently disabled
# # as they does not appear to be invoked regularly,
# and invoking it can require large memory allocations.
# This can be fixed in the future if there is evidence that it's useful.
# To add them in, define _branch_and_bound as follows:
# def _branch_and_bound(adj, x, g, f, best_found, skipable=set(), theorem6p1=None,
# theorem6p2=None, theorem6p3=None):
# if theorem6p1 is None:
# theorem6p1 = _theorem6p1()
# prune6p1, explored6p1 = theorem6p1
# if theorem6p3 is None:
# theorem6p3 = _theorem6p3()
# prune6p3, explored6p3 = theorem6p3
# we'll need to know our current upper bound in several places
ub, order = best_found
# ok, take care of the base case first
if len(adj) < 2:
# check if our current branch is better than the best we've already
# found and if so update our best solution accordingly.
if f < ub:
return (f, x + list(adj))
elif f == ub and not order:
return (f, x + list(adj))
else:
return best_found
# so we have not yet reached the base case
# Note: theorem 6.4 gives a heuristic for choosing order of n in adj.
# Quick_bb suggests using a min-fill or random order.
# We don't need to consider the neighbors of the last vertex eliminated
sorted_adj = sorted((n for n in adj if n not in skipable), key=lambda x: _min_fill_needed_edges(adj, x))
for n in sorted_adj:
g_s = max(g, len(adj[n]))
# according to Lemma 5.3, we can skip all of the neighbors of the last
# variable eliniated when choosing the next variable
# this does not get altered so we don't need a copy
next_skipable = adj[n]
if prune6p2(x, n, next_skipable):
continue
# update the state by eliminating n and adding it to the partial ordering
adj_s = {v: adj[v].copy() for v in adj} # create a new object
edges_n = _elim_adj(adj_s, n)
x_s = x + [n] # new partial ordering
# pruning (disabled):
# if prune6p1(x_s):
# continue
if prune6p4(edges_n):
continue
# By Theorem 5.4, if any two vertices have ub + 1 common neighbors then
# we can add an edge between them
_theorem5p4(adj_s, ub)
# ok, let's update our values
f_s = max(g_s, minor_min_width(adj_s))
g_s, f_s, as_list = _graph_reduction(adj_s, x_s, g_s, f_s)
# pruning (disabled):
# if prune6p3(x, as_list, n):
# continue
if f_s < ub:
best_found = _branch_and_bound(adj_s, x_s, g_s, f_s, best_found,
next_skipable, theorem6p2=theorem6p2)
# if theorem6p1, theorem6p3 are enabled, this should be called as:
# best_found = _branch_and_bound(adj_s, x_s, g_s, f_s, best_found,
# next_skipable, theorem6p1=theorem6p1,
# theorem6p2=theorem6p2,theorem6p3=theorem6p3)
ub, __ = best_found
# store some information for pruning (disabled):
# explored6p3(x, n, as_list)
prunable = explored6p2(x, n, next_skipable)
current6p2.append(prunable)
explored6p4(edges_n)
# store some information for pruning (disabled):
# explored6p1(x)
for prunable in current6p2:
finished6p2(prunable)
return best_found
def _graph_reduction(adj, x, g, f):
"""we can go ahead and remove any simplicial or almost-simplicial vertices from adj.
"""
as_list = set()
as_nodes = {v for v in adj if len(adj[v]) <= f and is_almost_simplicial(adj, v)}
while as_nodes:
as_list.union(as_nodes)
for n in as_nodes:
# update g and f
dv = len(adj[n])
if dv > g:
g = dv
if g > f:
f = g
# eliminate v
x.append(n)
_elim_adj(adj, n)
# see if we have any more simplicial nodes
as_nodes = {v for v in adj if len(adj[v]) <= f and is_almost_simplicial(adj, v)}
return g, f, as_list
def _theorem5p4(adj, ub):
"""By Theorem 5.4, if any two vertices have ub + 1 common neighbors
then we can add an edge between them.
"""
new_edges = set()
for u, v in itertools.combinations(adj, 2):
if u in adj[v]:
# already an edge
continue
if len(adj[u].intersection(adj[v])) > ub:
new_edges.add((u, v))
while new_edges:
for u, v in new_edges:
adj[u].add(v)
adj[v].add(u)
new_edges = set()
for u, v in itertools.combinations(adj, 2):
if u in adj[v]:
continue
if len(adj[u].intersection(adj[v])) > ub:
new_edges.add((u, v))
def _theorem6p1():
"""See Theorem 6.1 in paper."""
pruning_set = set()
def _prune(x):
if len(x) <= 2:
return False
# this is faster than tuple(x[-3:])
key = (tuple(x[:-2]), x[-2], x[-1])
return key in pruning_set
def _explored(x):
if len(x) >= 3:
prunable = (tuple(x[:-2]), x[-1], x[-2])
pruning_set.add(prunable)
return _prune, _explored
def _theorem6p2():
"""See Theorem 6.2 in paper.
Prunes (x,...,a) when (x,a) is explored and a has the same neighbour set in both graphs.
"""
pruning_set2 = set()
def _prune2(x, a, nbrs_a):
frozen_nbrs_a = frozenset(nbrs_a)
for i in range(len(x)):
key = (tuple(x[0:i]), a, frozen_nbrs_a)
if key in pruning_set2:
return True
return False
def _explored2(x, a, nbrs_a):
prunable = (tuple(x), a, frozenset(nbrs_a)) # (s,a,N(a))
pruning_set2.add(prunable)
return prunable
def _finished2(prunable):
pruning_set2.remove(prunable)
return _prune2, _explored2, _finished2
def _theorem6p3():
"""See Theorem 6.3 in paper.
Prunes (s,b) when (s,a) is explored, b (almost) simplicial in (s,a), and a (almost) simplicial in (s,b)
"""
pruning_set3 = set()
def _prune3(x, as_list, b):
for a in as_list:
key = (tuple(x), a, b) # (s,a,b) with (s,a) explored
if key in pruning_set3:
return True
return False
def _explored3(x, a, as_list):
for b in as_list:
prunable = (tuple(x), a, b) # (s,a,b) with (s,a) explored
pruning_set3.add(prunable)
return _prune3, _explored3
def _theorem6p4():
"""See Theorem 6.4 in paper.
Let E(x) denote the edges added when eliminating x. (edges_x below).
Prunes (s,b) when (s,a) is explored and E(a) is a subset of E(b).
For this theorem we only record E(a) rather than (s,E(a))
because we only need to check for pruning in the same s context
(i.e the same level of recursion).
"""
pruning_set4 = list()
def _prune4(edges_b):
for edges_a in pruning_set4:
if edges_a.issubset(edges_b):
return True
return False
def _explored4(edges_a):
pruning_set4.append(edges_a) # (s,E_a) with (s,a) explored
return _prune4, _explored4
def chimera_elimination_order(m, n=None, t=None):
"""Provides a variable elimination order for a Chimera graph.
A graph defined by `chimera_graph(m,n,t)` has treewidth :math:`max(m,n)*t`.
This function outputs a variable elimination order inducing a tree
decomposition of that width.
Parameters
----------
m : int
Number of rows in the Chimera lattice.
n : int (optional, default m)
Number of columns in the Chimera lattice.
t : int (optional, default 4)
Size of the shore within each Chimera tile.
Returns
-------
order : list
An elimination order that induces the treewidth of chimera_graph(m,n,t).
Examples
--------
>>> G = dnx.chimera_elimination_order(1, 1, 4) # a single Chimera tile
"""
if n is None:
n = m
if t is None:
t = 4
index_flip = m > n
if index_flip:
m, n = n, m
def chimeraI(m0, n0, k0, l0):
if index_flip:
return m*2*t*n0 + 2*t*m0 + t*(1-k0) + l0
else:
return n*2*t*m0 + 2*t*n0 + t*k0 + l0
order = []
for n_i in range(n):
for t_i in range(t):
for m_i in range(m):
order.append(chimeraI(m_i, n_i, 0, t_i))
for n_i in range(n):
for m_i in range(m):
for t_i in range(t):
order.append(chimeraI(m_i, n_i, 1, t_i))
return order
def pegasus_elimination_order(n, coordinates=False):
"""Provides a variable elimination order for the Pegasus graph.
The treewidth of a Pegasus graph `P(n)` is lower-bounded by `12n-11` and
upper bounded by `12-4` [bbrr]_ .
Simple pegasus variable elimination order rules:
- eliminate vertical qubits, one column at a time
- eliminate horizontal qubits in each column once their adjacent vertical
qubits have been eliminated
Args
----
n : int
The size parameter for the Pegasus lattice.
coordinates : bool, optional (default False)
If True, the elimination order is given in terms of 4-term Pegasus
coordinates, otherwise given in linear indices.
Returns
-------
order : list
An elimination order that provides an upper bound on the treewidth.
.. [bbrr] Boothby, K., P. Bunky, J. Raymond, A. Roy. Next-Generation Topology
of D-Wave Quantum Processors. Technical Report, Februrary 2019.
https://www.dwavesys.com/resources/publications?type=white#publication-987
"""
m = n
l = 12
# ordering for horizontal qubits in each tile, from east to west:
h_order = [4, 5, 6, 7, 0, 1, 2, 3, 8, 9, 10, 11]
order = []
for n_i in range(n): # for each tile offset
# eliminate vertical qubits:
for l_i in range(0, l, 2):
for l_v in range(l_i, l_i + 2):
for m_i in range(m - 1): # for each column
order.append((0, n_i, l_v, m_i))
# eliminate horizontal qubits:
if n_i > 0 and not(l_i % 4):
# a new set of horizontal qubits have had all their neighbouring vertical qubits eliminated.
for m_i in range(m):
for l_h in range(h_order[l_i], h_order[l_i] + 4):
order.append((1, m_i, l_h, n_i - 1))
if coordinates:
return order
else:
return pegasus_coordinates(n).iter_pegasus_to_linear(order)
| 30.381365 | 108 | 0.610334 |
import itertools
from random import random, sample
import networkx as nx
from dwave_networkx.generators.pegasus import pegasus_coordinates
__all__ = ['is_almost_simplicial',
'is_simplicial',
'chimera_elimination_order',
'pegasus_elimination_order',
'max_cardinality_heuristic',
'min_fill_heuristic',
'min_width_heuristic',
'treewidth_branch_and_bound',
'minor_min_width',
'elimination_order_width',
]
def is_simplicial(G, n):
return all(u in G[v] for u, v in itertools.combinations(G[n], 2))
def is_almost_simplicial(G, n):
for w in G[n]:
if all(u in G[v] for u, v in itertools.combinations(G[n], 2) if u != w and v != w):
return True
return False
def minor_min_width(G):
adj = {v: set(u for u in G[v] if u != v) for v in G}
lb = 0 # lower bound on treewidth
while len(adj) > 1:
# get the node with the smallest degree
v = min(adj, key=lambda v: len(adj[v]))
# find the vertex u such that the degree of u is minimal in the neighborhood of v
neighbors = adj[v]
if not neighbors:
# if v is a singleton, then we can just delete it
del adj[v]
continue
def neighborhood_degree(u):
Gu = adj[u]
return sum(w in Gu for w in neighbors)
u = min(neighbors, key=neighborhood_degree)
# update the lower bound
new_lb = len(adj[v])
if new_lb > lb:
lb = new_lb
# contract the edge between u, v
adj[v] = adj[v].union(n for n in adj[u] if n != v)
for n in adj[v]:
adj[n].add(v)
for n in adj[u]:
adj[n].discard(u)
del adj[u]
return lb
def min_fill_heuristic(G):
# we need only deal with the adjacency structure of G. We will also
# be manipulating it directly so let's go ahead and make a new one
adj = {v: set(u for u in G[v] if u != v) for v in G}
num_nodes = len(adj)
order = [0] * num_nodes
upper_bound = 0
for i in range(num_nodes):
v = min(adj, key=lambda x: _min_fill_needed_edges(adj, x))
dv = len(adj[v])
if dv > upper_bound:
upper_bound = dv
_elim_adj(adj, v)
order[i] = v
return upper_bound, order
def _min_fill_needed_edges(adj, n):
e = 0
for u, v in itertools.combinations(adj[n], 2):
if u not in adj[v]:
e += 1
return e + random()
def min_width_heuristic(G):
adj = {v: set(u for u in G[v] if u != v) for v in G}
num_nodes = len(adj)
# preallocate the return values
order = [0] * num_nodes
upper_bound = 0
for i in range(num_nodes):
# get the node with the smallest degree. We add random() which picks a value
# in the range [0., 1.). This is ok because the lens are all integers. By
# adding a small random value, we randomize which node is chosen without affecting
# correctness.
v = min(adj, key=lambda u: len(adj[u]) + random())
# if the number of neighbours of v is higher than upper_bound, update
dv = len(adj[v])
if dv > upper_bound:
upper_bound = dv
# make v simplicial by making its neighborhood a clique then remove the
# node
_elim_adj(adj, v)
order[i] = v
return upper_bound, order
def max_cardinality_heuristic(G):
# we need only deal with the adjacency structure of G. We will also
# be manipulating it directly so let's go ahead and make a new one
adj = {v: set(u for u in G[v] if u != v) for v in G}
num_nodes = len(adj)
order = [0] * num_nodes
upper_bound = 0
labelled_neighbors = {v: 0 for v in adj}
for i in range(num_nodes):
v = max(labelled_neighbors, key=lambda u: labelled_neighbors[u] + random())
del labelled_neighbors[v]
for u in adj[v]:
if u in labelled_neighbors:
labelled_neighbors[u] += 1
order[-(i + 1)] = v
for v in order:
dv = len(adj[v])
if dv > upper_bound:
upper_bound = dv
_elim_adj(adj, v)
return upper_bound, order
def _elim_adj(adj, n):
neighbors = adj[n]
new_edges = set()
for u, v in itertools.combinations(neighbors, 2):
if v not in adj[u]:
adj[u].add(v)
adj[v].add(u)
new_edges.add((u, v))
new_edges.add((v, u))
for v in neighbors:
adj[v].discard(n)
del adj[n]
return new_edges
def elimination_order_width(G, order):
adj = {v: set(u for u in G[v] if u != v) for v in G}
treewidth = 0
for v in order:
# get the degree of the eliminated variable
try:
dv = len(adj[v])
except KeyError:
raise ValueError('{} is in order but not in G'.format(v))
# the treewidth is the max of the current treewidth and the degree
if dv > treewidth:
treewidth = dv
# eliminate v by making it simplicial (acts on adj in place)
_elim_adj(adj, v)
# if adj is not empty, then order did not include all of the nodes in G.
if adj:
raise ValueError('not all nodes in G were in order')
return treewidth
def treewidth_branch_and_bound(G, elimination_order=None, treewidth_upperbound=None):
# empty graphs have treewidth 0 and the nodes can be eliminated in
# any order
if not any(G[v] for v in G):
return 0, list(G)
# variable names are chosen to match the paper
# our order will be stored in vector x, named to be consistent with
# the paper
x = [] # the partial order
f = minor_min_width(G) # our current lower bound guess, f(s) in the paper
g = 0 # g(s) in the paper
# we need the best current update we can find.
ub, order = min_fill_heuristic(G)
# if the user has provided an upperbound or an elimination order, check those against
# our current best guess
if elimination_order is not None:
upperbound = elimination_order_width(G, elimination_order)
if upperbound <= ub:
ub, order = upperbound, elimination_order
if treewidth_upperbound is not None and treewidth_upperbound < ub:
# in this case the order might never be found
ub, order = treewidth_upperbound, []
# best found encodes the ub and the order
best_found = ub, order
# if our upper bound is the same as f, then we are done! Otherwise begin the
# algorithm.
if f < ub:
# we need only deal with the adjacency structure of G. We will also
# be manipulating it directly so let's go ahead and make a new one
adj = {v: set(u for u in G[v] if u != v) for v in G}
best_found = _branch_and_bound(adj, x, g, f, best_found)
elif f > ub and treewidth_upperbound is None:
raise RuntimeError("logic error")
return best_found
def _branch_and_bound(adj, x, g, f, best_found, skipable=set(), theorem6p2=None):
if theorem6p2 is None:
theorem6p2 = _theorem6p2()
prune6p2, explored6p2, finished6p2 = theorem6p2
current6p2 = list()
prune6p4, explored6p4 = _theorem6p4()
d_bound as follows:
# def _branch_and_bound(adj, x, g, f, best_found, skipable=set(), theorem6p1=None,
# theorem6p2=None, theorem6p3=None):
# if theorem6p1 is None:
# theorem6p1 = _theorem6p1()
# prune6p1, explored6p1 = theorem6p1
# if theorem6p3 is None:
# theorem6p3 = _theorem6p3()
# prune6p3, explored6p3 = theorem6p3
# we'll need to know our current upper bound in several places
ub, order = best_found
if len(adj) < 2:
# found and if so update our best solution accordingly.
if f < ub:
return (f, x + list(adj))
elif f == ub and not order:
return (f, x + list(adj))
else:
return best_found
# so we have not yet reached the base case
# Note: theorem 6.4 gives a heuristic for choosing order of n in adj.
# Quick_bb suggests using a min-fill or random order.
# We don't need to consider the neighbors of the last vertex eliminated
sorted_adj = sorted((n for n in adj if n not in skipable), key=lambda x: _min_fill_needed_edges(adj, x))
for n in sorted_adj:
g_s = max(g, len(adj[n]))
next_skipable = adj[n]
if prune6p2(x, n, next_skipable):
continue
# update the state by eliminating n and adding it to the partial ordering
adj_s = {v: adj[v].copy() for v in adj} # create a new object
edges_n = _elim_adj(adj_s, n)
x_s = x + [n] # new partial ordering
# pruning (disabled):
# if prune6p1(x_s):
# continue
if prune6p4(edges_n):
continue
# By Theorem 5.4, if any two vertices have ub + 1 common neighbors then
# we can add an edge between them
_theorem5p4(adj_s, ub)
# ok, let's update our values
f_s = max(g_s, minor_min_width(adj_s))
g_s, f_s, as_list = _graph_reduction(adj_s, x_s, g_s, f_s)
if f_s < ub:
best_found = _branch_and_bound(adj_s, x_s, g_s, f_s, best_found,
next_skipable, theorem6p2=theorem6p2)
ub, __ = best_found
prunable = explored6p2(x, n, next_skipable)
current6p2.append(prunable)
explored6p4(edges_n)
for prunable in current6p2:
finished6p2(prunable)
return best_found
def _graph_reduction(adj, x, g, f):
as_list = set()
as_nodes = {v for v in adj if len(adj[v]) <= f and is_almost_simplicial(adj, v)}
while as_nodes:
as_list.union(as_nodes)
for n in as_nodes:
dv = len(adj[n])
if dv > g:
g = dv
if g > f:
f = g
x.append(n)
_elim_adj(adj, n)
as_nodes = {v for v in adj if len(adj[v]) <= f and is_almost_simplicial(adj, v)}
return g, f, as_list
def _theorem5p4(adj, ub):
new_edges = set()
for u, v in itertools.combinations(adj, 2):
if u in adj[v]:
continue
if len(adj[u].intersection(adj[v])) > ub:
new_edges.add((u, v))
while new_edges:
for u, v in new_edges:
adj[u].add(v)
adj[v].add(u)
new_edges = set()
for u, v in itertools.combinations(adj, 2):
if u in adj[v]:
continue
if len(adj[u].intersection(adj[v])) > ub:
new_edges.add((u, v))
def _theorem6p1():
pruning_set = set()
def _prune(x):
if len(x) <= 2:
return False
key = (tuple(x[:-2]), x[-2], x[-1])
return key in pruning_set
def _explored(x):
if len(x) >= 3:
prunable = (tuple(x[:-2]), x[-1], x[-2])
pruning_set.add(prunable)
return _prune, _explored
def _theorem6p2():
pruning_set2 = set()
def _prune2(x, a, nbrs_a):
frozen_nbrs_a = frozenset(nbrs_a)
for i in range(len(x)):
key = (tuple(x[0:i]), a, frozen_nbrs_a)
if key in pruning_set2:
return True
return False
def _explored2(x, a, nbrs_a):
prunable = (tuple(x), a, frozenset(nbrs_a))
pruning_set2.add(prunable)
return prunable
def _finished2(prunable):
pruning_set2.remove(prunable)
return _prune2, _explored2, _finished2
def _theorem6p3():
pruning_set3 = set()
def _prune3(x, as_list, b):
for a in as_list:
key = (tuple(x), a, b)
if key in pruning_set3:
return True
return False
def _explored3(x, a, as_list):
for b in as_list:
prunable = (tuple(x), a, b)
pruning_set3.add(prunable)
return _prune3, _explored3
def _theorem6p4():
pruning_set4 = list()
def _prune4(edges_b):
for edges_a in pruning_set4:
if edges_a.issubset(edges_b):
return True
return False
def _explored4(edges_a):
pruning_set4.append(edges_a)
return _prune4, _explored4
def chimera_elimination_order(m, n=None, t=None):
if n is None:
n = m
if t is None:
t = 4
index_flip = m > n
if index_flip:
m, n = n, m
def chimeraI(m0, n0, k0, l0):
if index_flip:
return m*2*t*n0 + 2*t*m0 + t*(1-k0) + l0
else:
return n*2*t*m0 + 2*t*n0 + t*k0 + l0
order = []
for n_i in range(n):
for t_i in range(t):
for m_i in range(m):
order.append(chimeraI(m_i, n_i, 0, t_i))
for n_i in range(n):
for m_i in range(m):
for t_i in range(t):
order.append(chimeraI(m_i, n_i, 1, t_i))
return order
def pegasus_elimination_order(n, coordinates=False):
m = n
l = 12
h_order = [4, 5, 6, 7, 0, 1, 2, 3, 8, 9, 10, 11]
order = []
for n_i in range(n):
for l_i in range(0, l, 2):
for l_v in range(l_i, l_i + 2):
for m_i in range(m - 1):
order.append((0, n_i, l_v, m_i))
if n_i > 0 and not(l_i % 4):
for m_i in range(m):
for l_h in range(h_order[l_i], h_order[l_i] + 4):
order.append((1, m_i, l_h, n_i - 1))
if coordinates:
return order
else:
return pegasus_coordinates(n).iter_pegasus_to_linear(order)
| true | true |
f7f9542766d370aadcc641d0b88390b4139552f2 | 360 | py | Python | hospitals_api/urls.py | API-Imperfect/geodjango-hospitals-api-home | 69f8773e8904bdb6ba6f8c4f0d1547e9a4edc21d | [
"MIT"
] | null | null | null | hospitals_api/urls.py | API-Imperfect/geodjango-hospitals-api-home | 69f8773e8904bdb6ba6f8c4f0d1547e9a4edc21d | [
"MIT"
] | null | null | null | hospitals_api/urls.py | API-Imperfect/geodjango-hospitals-api-home | 69f8773e8904bdb6ba6f8c4f0d1547e9a4edc21d | [
"MIT"
] | null | null | null | from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("hospitals.urls")),
path("", include("boundaries.urls")),
]
admin.site.site_header = "Hospitals Admin"
admin.site.site_title = "Rwanda GIS Admin Portal"
admin.site.index_title = "Welcome to Rwanda GIS Portal"
| 27.692308 | 55 | 0.716667 | from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("hospitals.urls")),
path("", include("boundaries.urls")),
]
admin.site.site_header = "Hospitals Admin"
admin.site.site_title = "Rwanda GIS Admin Portal"
admin.site.index_title = "Welcome to Rwanda GIS Portal"
| true | true |
f7f9554ee75dee8f114eb50d9b2c895996982f61 | 341 | py | Python | decorators.py | caseyr003/catalog | b729515e1ff92ea019520e54ed6079a078d538f9 | [
"MIT"
] | null | null | null | decorators.py | caseyr003/catalog | b729515e1ff92ea019520e54ed6079a078d538f9 | [
"MIT"
] | null | null | null | decorators.py | caseyr003/catalog | b729515e1ff92ea019520e54ed6079a078d538f9 | [
"MIT"
] | null | null | null | from functools import wraps
from flask import redirect, session as login_session
def logged_in(function):
@wraps(function)
def wrapper(*a, **kw):
# If not logged in redirect to login page
if 'username' not in login_session:
return redirect('/login')
return function(*a, **kw)
return wrapper
| 26.230769 | 52 | 0.656891 | from functools import wraps
from flask import redirect, session as login_session
def logged_in(function):
@wraps(function)
def wrapper(*a, **kw):
if 'username' not in login_session:
return redirect('/login')
return function(*a, **kw)
return wrapper
| true | true |
f7f9567922528dd6970210457c964e9ee21a1480 | 768 | py | Python | shblog/spiders/shblog_sitemap.py | malberts/scrapy-demo | 686b853b9ef7b49e085d23af346c8c7b6291cea0 | [
"BSD-3-Clause"
] | null | null | null | shblog/spiders/shblog_sitemap.py | malberts/scrapy-demo | 686b853b9ef7b49e085d23af346c8c7b6291cea0 | [
"BSD-3-Clause"
] | null | null | null | shblog/spiders/shblog_sitemap.py | malberts/scrapy-demo | 686b853b9ef7b49e085d23af346c8c7b6291cea0 | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
from scrapy.spiders import SitemapSpider
from .shblog_base import SHBlogBaseSpider
class SHBlogSitemapSpider(SHBlogBaseSpider, SitemapSpider):
name = "shblog_sitemap"
user_agent = "shblog_sitemap (+https://github.com/malberts/scrapy-demo/)"
allowed_domains = ["blog.scrapinghub.com"]
sitemap_urls = ["https://blog.scrapinghub.com/sitemap.xml"]
sitemap_rules = [("", "parse_post_item")]
def parse_post_item(self, response):
"""
Parses an individual blog post item.
@url https://blog.scrapinghub.com/2010/06/26/hello-world
@returns items 1 1
@returns requests 0 0
@scrapes title date author summary tags
"""
yield from super().parse_post_item(response)
| 32 | 77 | 0.678385 |
from scrapy.spiders import SitemapSpider
from .shblog_base import SHBlogBaseSpider
class SHBlogSitemapSpider(SHBlogBaseSpider, SitemapSpider):
name = "shblog_sitemap"
user_agent = "shblog_sitemap (+https://github.com/malberts/scrapy-demo/)"
allowed_domains = ["blog.scrapinghub.com"]
sitemap_urls = ["https://blog.scrapinghub.com/sitemap.xml"]
sitemap_rules = [("", "parse_post_item")]
def parse_post_item(self, response):
yield from super().parse_post_item(response)
| true | true |
f7f956a16ac611e290129975927452000a373e50 | 5,452 | py | Python | swift3/etree.py | AymericDu/swift3 | a64be4ed9c6657fc5471e87e08e6c7465b7bd444 | [
"Apache-2.0"
] | 10 | 2017-04-21T13:56:48.000Z | 2022-03-29T17:15:40.000Z | swift3/etree.py | AymericDu/swift3 | a64be4ed9c6657fc5471e87e08e6c7465b7bd444 | [
"Apache-2.0"
] | 12 | 2017-05-04T16:23:35.000Z | 2021-09-08T16:42:58.000Z | swift3/etree.py | AymericDu/swift3 | a64be4ed9c6657fc5471e87e08e6c7465b7bd444 | [
"Apache-2.0"
] | 10 | 2017-05-10T14:00:42.000Z | 2019-10-28T13:24:57.000Z | # Copyright (c) 2014 OpenStack Foundation.
#
# 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 lxml.etree
from copy import deepcopy
from pkg_resources import resource_stream # pylint: disable-msg=E0611
from six.moves.urllib.parse import quote
from swift3.exception import S3Exception
from swift3.utils import LOGGER, camel_to_snake, utf8encode, utf8decode
XMLNS_S3 = 'http://s3.amazonaws.com/doc/2006-03-01/'
XMLNS_XSI = 'http://www.w3.org/2001/XMLSchema-instance'
URLENCODE_BLACKLIST = ['LastModified', 'ID', 'DisplayName', 'Initiated',
'ContinuationToken', 'NextContinuationToken', 'ETag']
class XMLSyntaxError(S3Exception):
pass
class DocumentInvalid(S3Exception):
pass
def cleanup_namespaces(elem):
def remove_ns(tag, ns):
if tag.startswith('{%s}' % ns):
tag = tag[len('{%s}' % ns):]
return tag
if not isinstance(elem.tag, basestring):
# elem is a comment element.
return
# remove s3 namespace
elem.tag = remove_ns(elem.tag, XMLNS_S3)
# remove default namespace
if elem.nsmap and None in elem.nsmap:
elem.tag = remove_ns(elem.tag, elem.nsmap[None])
for e in elem.iterchildren():
cleanup_namespaces(e)
def fromstring(text, root_tag=None):
try:
elem = lxml.etree.fromstring(text, parser)
except lxml.etree.XMLSyntaxError as e:
LOGGER.debug(e)
raise XMLSyntaxError(e)
cleanup_namespaces(elem)
if root_tag is not None:
# validate XML
try:
path = 'schema/%s.rng' % camel_to_snake(root_tag)
with resource_stream(__name__, path) as rng:
lxml.etree.RelaxNG(file=rng).assertValid(elem)
except IOError as e:
# Probably, the schema file doesn't exist.
LOGGER.error(e)
raise
except lxml.etree.DocumentInvalid as e:
LOGGER.debug(e)
raise DocumentInvalid(e)
return elem
def tostring(tree, encoding_type=None, use_s3ns=True):
if use_s3ns:
nsmap = tree.nsmap.copy()
nsmap[None] = XMLNS_S3
root = Element(tree.tag, attrib=tree.attrib, nsmap=nsmap)
root.text = tree.text
root.extend(deepcopy(tree.getchildren()))
tree = root
if encoding_type == 'url':
tree = deepcopy(tree)
for e in tree.iter():
# Some elements are not url-encoded even when we specify
# encoding_type=url.
if e.tag not in URLENCODE_BLACKLIST:
if isinstance(e.text, basestring):
# If the value contains control chars,
# it may be urlencoded already.
if e.get('urlencoded', None) == 'True':
e.attrib.pop('urlencoded')
else:
e.text = quote(e.text)
return lxml.etree.tostring(tree, xml_declaration=True, encoding='UTF-8')
class _Element(lxml.etree.ElementBase):
"""
Wrapper Element class of lxml.etree.Element to support
a utf-8 encoded non-ascii string as a text.
Why we need this?:
Original lxml.etree.Element supports only unicode for the text.
It declines maintainability because we have to call a lot of encode/decode
methods to apply account/container/object name (i.e. PATH_INFO) to each
Element instance. When using this class, we can remove such a redundant
codes from swift3 middleware.
"""
def __init__(self, *args, **kwargs):
# pylint: disable-msg=E1002
super(_Element, self).__init__(*args, **kwargs)
def _init(self, *args, **kwargs):
super(_Element, self)._init(*args, **kwargs)
self.encoding_type = None
@property
def text(self):
"""
utf-8 wrapper property of lxml.etree.Element.text
"""
return utf8encode(lxml.etree.ElementBase.text.__get__(self))
@text.setter
def text(self, value):
decoded = utf8decode(value)
try:
lxml.etree.ElementBase.text.__set__(self, decoded)
except ValueError:
root = self.getroottree().getroot()
# URL encoding is usually done at the end, but sometimes we get
# control characters that are rejected by the XML encoder.
# If we are going to urlencode the value, do it now.
if root.encoding_type != 'url' or \
self.tag in URLENCODE_BLACKLIST:
raise
lxml.etree.ElementBase.text.__set__(self, quote(decoded))
# The deepcopy seems to not copy custom fields, thus we use
# an attribute which will be deleted when marshalling.
self.set('urlencoded', 'True')
parser_lookup = lxml.etree.ElementDefaultClassLookup(element=_Element)
parser = lxml.etree.XMLParser()
parser.set_element_class_lookup(parser_lookup)
Element = parser.makeelement
SubElement = lxml.etree.SubElement
| 33.243902 | 78 | 0.644534 |
import lxml.etree
from copy import deepcopy
from pkg_resources import resource_stream
from six.moves.urllib.parse import quote
from swift3.exception import S3Exception
from swift3.utils import LOGGER, camel_to_snake, utf8encode, utf8decode
XMLNS_S3 = 'http://s3.amazonaws.com/doc/2006-03-01/'
XMLNS_XSI = 'http://www.w3.org/2001/XMLSchema-instance'
URLENCODE_BLACKLIST = ['LastModified', 'ID', 'DisplayName', 'Initiated',
'ContinuationToken', 'NextContinuationToken', 'ETag']
class XMLSyntaxError(S3Exception):
pass
class DocumentInvalid(S3Exception):
pass
def cleanup_namespaces(elem):
def remove_ns(tag, ns):
if tag.startswith('{%s}' % ns):
tag = tag[len('{%s}' % ns):]
return tag
if not isinstance(elem.tag, basestring):
return
elem.tag = remove_ns(elem.tag, XMLNS_S3)
if elem.nsmap and None in elem.nsmap:
elem.tag = remove_ns(elem.tag, elem.nsmap[None])
for e in elem.iterchildren():
cleanup_namespaces(e)
def fromstring(text, root_tag=None):
try:
elem = lxml.etree.fromstring(text, parser)
except lxml.etree.XMLSyntaxError as e:
LOGGER.debug(e)
raise XMLSyntaxError(e)
cleanup_namespaces(elem)
if root_tag is not None:
try:
path = 'schema/%s.rng' % camel_to_snake(root_tag)
with resource_stream(__name__, path) as rng:
lxml.etree.RelaxNG(file=rng).assertValid(elem)
except IOError as e:
LOGGER.error(e)
raise
except lxml.etree.DocumentInvalid as e:
LOGGER.debug(e)
raise DocumentInvalid(e)
return elem
def tostring(tree, encoding_type=None, use_s3ns=True):
if use_s3ns:
nsmap = tree.nsmap.copy()
nsmap[None] = XMLNS_S3
root = Element(tree.tag, attrib=tree.attrib, nsmap=nsmap)
root.text = tree.text
root.extend(deepcopy(tree.getchildren()))
tree = root
if encoding_type == 'url':
tree = deepcopy(tree)
for e in tree.iter():
# Some elements are not url-encoded even when we specify
# encoding_type=url.
if e.tag not in URLENCODE_BLACKLIST:
if isinstance(e.text, basestring):
# If the value contains control chars,
# it may be urlencoded already.
if e.get('urlencoded', None) == 'True':
e.attrib.pop('urlencoded')
else:
e.text = quote(e.text)
return lxml.etree.tostring(tree, xml_declaration=True, encoding='UTF-8')
class _Element(lxml.etree.ElementBase):
def __init__(self, *args, **kwargs):
# pylint: disable-msg=E1002
super(_Element, self).__init__(*args, **kwargs)
def _init(self, *args, **kwargs):
super(_Element, self)._init(*args, **kwargs)
self.encoding_type = None
@property
def text(self):
return utf8encode(lxml.etree.ElementBase.text.__get__(self))
@text.setter
def text(self, value):
decoded = utf8decode(value)
try:
lxml.etree.ElementBase.text.__set__(self, decoded)
except ValueError:
root = self.getroottree().getroot()
# URL encoding is usually done at the end, but sometimes we get
# control characters that are rejected by the XML encoder.
# If we are going to urlencode the value, do it now.
if root.encoding_type != 'url' or \
self.tag in URLENCODE_BLACKLIST:
raise
lxml.etree.ElementBase.text.__set__(self, quote(decoded))
# The deepcopy seems to not copy custom fields, thus we use
# an attribute which will be deleted when marshalling.
self.set('urlencoded', 'True')
parser_lookup = lxml.etree.ElementDefaultClassLookup(element=_Element)
parser = lxml.etree.XMLParser()
parser.set_element_class_lookup(parser_lookup)
Element = parser.makeelement
SubElement = lxml.etree.SubElement
| true | true |
f7f9583ea98785181b96028c049795d2ea989b1a | 3,795 | py | Python | ptgaze/common/visualizer.py | martinhoang11/pytorch_mpiigaze_demo | 26f9cd0c4278041ceb905ebb1ccbe5825f822d6f | [
"MIT"
] | null | null | null | ptgaze/common/visualizer.py | martinhoang11/pytorch_mpiigaze_demo | 26f9cd0c4278041ceb905ebb1ccbe5825f822d6f | [
"MIT"
] | null | null | null | ptgaze/common/visualizer.py | martinhoang11/pytorch_mpiigaze_demo | 26f9cd0c4278041ceb905ebb1ccbe5825f822d6f | [
"MIT"
] | null | null | null | from typing import Optional, Tuple
import cv2
import numpy as np
from scipy.spatial.transform import Rotation
from .camera import Camera
from .face import Face
AXIS_COLORS = [(0, 0, 255), (0, 255, 0), (255, 0, 0)]
class Visualizer:
def __init__(self, camera: Camera, center_point_index: int):
self._camera = camera
self._center_point_index = center_point_index
self.image: Optional[np.ndarray] = None
def set_image(self, image: np.ndarray) -> None:
self.image = image
def draw_bbox(self,
bbox: np.ndarray,
color: Tuple[int, int, int] = (0, 255, 0),
lw: int = 1) -> None:
assert self.image is not None
assert bbox.shape == (2, 2)
bbox = np.round(bbox).astype(np.int).tolist()
cv2.rectangle(self.image, tuple(bbox[0]), tuple(bbox[1]), color, lw)
@staticmethod
def _convert_pt(point: np.ndarray) -> Tuple[int, int]:
return tuple(np.round(point).astype(np.int).tolist())
def draw_points(self,
points: np.ndarray,
color: Tuple[int, int, int] = (0, 0, 255),
size: int = 3) -> None:
assert self.image is not None
assert points.shape[1] == 2
for pt in points:
pt = self._convert_pt(pt)
cv2.circle(self.image, pt, size, color, cv2.FILLED)
def draw_3d_points(self,
points3d: np.ndarray,
color: Tuple[int, int, int] = (255, 0, 255),
size=3) -> None:
assert self.image is not None
assert points3d.shape[1] == 3
points2d = self._camera.project_points(points3d)
self.draw_points(points2d, color=color, size=size)
def draw_3d_line(self,
point0: np.ndarray,
point1: np.ndarray,
color: Tuple[int, int, int] = (255, 255, 0),
lw=2) -> None:
assert self.image is not None
assert point0.shape == point1.shape == (3, )
points3d = np.vstack([point0, point1])
points2d = self._camera.project_points(points3d)
pt0 = self._convert_pt(points2d[0])
pt1 = self._convert_pt(points2d[1])
# cv2.line(self.image, pt0, pt1, color, lw, cv2.LINE_AA)
cv2.arrowedLine(self.image, pt0, pt1, color, lw, cv2.LINE_AA)
# cv2.arrowedLine(image_out, tuple(np.round(pos).astype(np.int32)),
# tuple(np.round([pos[0] + dx, pos[1] + dy]).astype(int)), color,
# thickness, cv2.LINE_AA, tipLength=0.2)
def draw_model_axes(self, face: Face, length: float, lw: int = 2) -> None:
assert self.image is not None
assert face is not None
assert face.head_pose_rot is not None
assert face.head_position is not None
assert face.landmarks is not None
# Get the axes of the model coordinate system
axes3d = np.eye(3, dtype=np.float) @ Rotation.from_euler(
'XYZ', [0, np.pi, 0]).as_matrix()
axes3d = axes3d * length
axes2d = self._camera.project_points(axes3d,
face.head_pose_rot.as_rotvec(),
face.head_position)
center = face.landmarks[self._center_point_index]
print(self._center_point_index)
center = self._convert_pt(center)
for pt, color in zip(axes2d, AXIS_COLORS):
pt = self._convert_pt(pt)
cv2.line(self.image, center, pt, color, lw, cv2.LINE_AA)
def draw_info(self, name, attr, org: int, color: int = (255, 0, 0)) -> None:
cv2.putText(self.image, f"{name}: {attr}", org, cv2.FONT_HERSHEY_SIMPLEX, 0.7, color, 1, cv2.LINE_AA)
| 40.806452 | 109 | 0.570224 | from typing import Optional, Tuple
import cv2
import numpy as np
from scipy.spatial.transform import Rotation
from .camera import Camera
from .face import Face
AXIS_COLORS = [(0, 0, 255), (0, 255, 0), (255, 0, 0)]
class Visualizer:
def __init__(self, camera: Camera, center_point_index: int):
self._camera = camera
self._center_point_index = center_point_index
self.image: Optional[np.ndarray] = None
def set_image(self, image: np.ndarray) -> None:
self.image = image
def draw_bbox(self,
bbox: np.ndarray,
color: Tuple[int, int, int] = (0, 255, 0),
lw: int = 1) -> None:
assert self.image is not None
assert bbox.shape == (2, 2)
bbox = np.round(bbox).astype(np.int).tolist()
cv2.rectangle(self.image, tuple(bbox[0]), tuple(bbox[1]), color, lw)
@staticmethod
def _convert_pt(point: np.ndarray) -> Tuple[int, int]:
return tuple(np.round(point).astype(np.int).tolist())
def draw_points(self,
points: np.ndarray,
color: Tuple[int, int, int] = (0, 0, 255),
size: int = 3) -> None:
assert self.image is not None
assert points.shape[1] == 2
for pt in points:
pt = self._convert_pt(pt)
cv2.circle(self.image, pt, size, color, cv2.FILLED)
def draw_3d_points(self,
points3d: np.ndarray,
color: Tuple[int, int, int] = (255, 0, 255),
size=3) -> None:
assert self.image is not None
assert points3d.shape[1] == 3
points2d = self._camera.project_points(points3d)
self.draw_points(points2d, color=color, size=size)
def draw_3d_line(self,
point0: np.ndarray,
point1: np.ndarray,
color: Tuple[int, int, int] = (255, 255, 0),
lw=2) -> None:
assert self.image is not None
assert point0.shape == point1.shape == (3, )
points3d = np.vstack([point0, point1])
points2d = self._camera.project_points(points3d)
pt0 = self._convert_pt(points2d[0])
pt1 = self._convert_pt(points2d[1])
cv2.arrowedLine(self.image, pt0, pt1, color, lw, cv2.LINE_AA)
def draw_model_axes(self, face: Face, length: float, lw: int = 2) -> None:
assert self.image is not None
assert face is not None
assert face.head_pose_rot is not None
assert face.head_position is not None
assert face.landmarks is not None
axes3d = np.eye(3, dtype=np.float) @ Rotation.from_euler(
'XYZ', [0, np.pi, 0]).as_matrix()
axes3d = axes3d * length
axes2d = self._camera.project_points(axes3d,
face.head_pose_rot.as_rotvec(),
face.head_position)
center = face.landmarks[self._center_point_index]
print(self._center_point_index)
center = self._convert_pt(center)
for pt, color in zip(axes2d, AXIS_COLORS):
pt = self._convert_pt(pt)
cv2.line(self.image, center, pt, color, lw, cv2.LINE_AA)
def draw_info(self, name, attr, org: int, color: int = (255, 0, 0)) -> None:
cv2.putText(self.image, f"{name}: {attr}", org, cv2.FONT_HERSHEY_SIMPLEX, 0.7, color, 1, cv2.LINE_AA)
| true | true |
f7f958dc52beb1d93c8e1733dc266a29eaaabf1c | 3,162 | py | Python | examples/vision/caltech101.py | erip/data | 9c6e5ddfcdf1061e3968ed5cd9d55754cc713965 | [
"BSD-3-Clause"
] | null | null | null | examples/vision/caltech101.py | erip/data | 9c6e5ddfcdf1061e3968ed5cd9d55754cc713965 | [
"BSD-3-Clause"
] | null | null | null | examples/vision/caltech101.py | erip/data | 9c6e5ddfcdf1061e3968ed5cd9d55754cc713965 | [
"BSD-3-Clause"
] | null | null | null | # Copyright (c) Facebook, Inc. and its affiliates.
import os.path
import re
import torch
from torch.utils.data.datapipes.utils.decoder import imagehandler, mathandler
from torchdata.datapipes.iter import (
FileOpener,
Filter,
IterableWrapper,
IterKeyZipper,
Mapper,
RoutedDecoder,
TarArchiveReader,
)
# Download size is ~150 MB so fake data is provided
URL = {
"images": "http://www.vision.caltech.edu/Image_Datasets/Caltech101/101_ObjectCategories.tar.gz",
"annotations": "http://www.vision.caltech.edu/Image_Datasets/Caltech101/Annotations.tar",
}
# We really shouldn't use MD5 anymore and switch to a more secure hash like SHA256 or
# SHA512
MD5 = {
"images": "b224c7392d521a49829488ab0f1120d9",
"annotations": "f83eeb1f24d99cab4eb377263132c91",
}
ROOT = os.path.join("fakedata", "caltech101")
IMAGES_NAME_PATTERN = re.compile(r"image_(?P<id>\d+)[.]jpg")
ANNS_NAME_PATTERN = re.compile(r"annotation_(?P<id>\d+)[.]mat")
ANNS_CLASS_MAP = {
"Faces_2": "Faces",
"Faces_3": "Faces_easy",
"Motorbikes_16": "Motorbikes",
"Airplanes_Side_2": "airplanes",
}
def is_ann(data):
path, _ = data
return bool(ANNS_NAME_PATTERN.match(os.path.basename(path)))
def collate_ann(data):
path, ann = data
cls = os.path.split(os.path.dirname(path))[1]
if cls in ANNS_CLASS_MAP:
cls = ANNS_CLASS_MAP[cls]
return path, {"cls": cls, "contour": torch.as_tensor(ann["obj_contour"])}
def is_not_background_image(data):
path, _ = data
return os.path.split(os.path.dirname(path))[1] != "BACKGROUND_Google"
def is_not_rogue_image(data) -> bool:
path, _ = data
return os.path.basename(path) != "RENAME2"
def extract_file_id(path, *, pattern):
match = pattern.match(os.path.basename(path))
return int(match.group("id"))
def images_key_fn(data):
path, _ = data
cls = os.path.split(os.path.dirname(path))[1]
id = extract_file_id(path, pattern=IMAGES_NAME_PATTERN)
return cls, id
def anns_key_fn(data):
path, ann = data
id = extract_file_id(path, pattern=ANNS_NAME_PATTERN)
return ann["cls"], id
def collate_sample(data):
(image_path, image), (ann_path, ann) = data
return dict(ann, image_path=image_path, image=image, ann_path=ann_path)
def Caltech101(root=ROOT):
anns_dp = IterableWrapper([os.path.join(root, "Annotations.tar")])
anns_dp = FileOpener(anns_dp, mode="b")
anns_dp = TarArchiveReader(anns_dp)
anns_dp = Filter(anns_dp, is_ann)
anns_dp = RoutedDecoder(anns_dp, mathandler())
anns_dp = Mapper(anns_dp, collate_ann)
images_dp = IterableWrapper([os.path.join(root, "101_ObjectCategories.tar.gz")])
images_dp = FileOpener(images_dp, mode="b")
images_dp = TarArchiveReader(images_dp)
images_dp = Filter(images_dp, is_not_background_image)
images_dp = Filter(images_dp, is_not_rogue_image)
images_dp = RoutedDecoder(images_dp, imagehandler("pil"))
dp = IterKeyZipper(images_dp, anns_dp, images_key_fn, ref_key_fn=anns_key_fn, buffer_size=None)
return Mapper(dp, collate_sample)
if __name__ == "__main__":
for _sample in Caltech101():
pass
| 28.232143 | 100 | 0.705882 |
import os.path
import re
import torch
from torch.utils.data.datapipes.utils.decoder import imagehandler, mathandler
from torchdata.datapipes.iter import (
FileOpener,
Filter,
IterableWrapper,
IterKeyZipper,
Mapper,
RoutedDecoder,
TarArchiveReader,
)
URL = {
"images": "http://www.vision.caltech.edu/Image_Datasets/Caltech101/101_ObjectCategories.tar.gz",
"annotations": "http://www.vision.caltech.edu/Image_Datasets/Caltech101/Annotations.tar",
}
# SHA512
MD5 = {
"images": "b224c7392d521a49829488ab0f1120d9",
"annotations": "f83eeb1f24d99cab4eb377263132c91",
}
ROOT = os.path.join("fakedata", "caltech101")
IMAGES_NAME_PATTERN = re.compile(r"image_(?P<id>\d+)[.]jpg")
ANNS_NAME_PATTERN = re.compile(r"annotation_(?P<id>\d+)[.]mat")
ANNS_CLASS_MAP = {
"Faces_2": "Faces",
"Faces_3": "Faces_easy",
"Motorbikes_16": "Motorbikes",
"Airplanes_Side_2": "airplanes",
}
def is_ann(data):
path, _ = data
return bool(ANNS_NAME_PATTERN.match(os.path.basename(path)))
def collate_ann(data):
path, ann = data
cls = os.path.split(os.path.dirname(path))[1]
if cls in ANNS_CLASS_MAP:
cls = ANNS_CLASS_MAP[cls]
return path, {"cls": cls, "contour": torch.as_tensor(ann["obj_contour"])}
def is_not_background_image(data):
path, _ = data
return os.path.split(os.path.dirname(path))[1] != "BACKGROUND_Google"
def is_not_rogue_image(data) -> bool:
path, _ = data
return os.path.basename(path) != "RENAME2"
def extract_file_id(path, *, pattern):
match = pattern.match(os.path.basename(path))
return int(match.group("id"))
def images_key_fn(data):
path, _ = data
cls = os.path.split(os.path.dirname(path))[1]
id = extract_file_id(path, pattern=IMAGES_NAME_PATTERN)
return cls, id
def anns_key_fn(data):
path, ann = data
id = extract_file_id(path, pattern=ANNS_NAME_PATTERN)
return ann["cls"], id
def collate_sample(data):
(image_path, image), (ann_path, ann) = data
return dict(ann, image_path=image_path, image=image, ann_path=ann_path)
def Caltech101(root=ROOT):
anns_dp = IterableWrapper([os.path.join(root, "Annotations.tar")])
anns_dp = FileOpener(anns_dp, mode="b")
anns_dp = TarArchiveReader(anns_dp)
anns_dp = Filter(anns_dp, is_ann)
anns_dp = RoutedDecoder(anns_dp, mathandler())
anns_dp = Mapper(anns_dp, collate_ann)
images_dp = IterableWrapper([os.path.join(root, "101_ObjectCategories.tar.gz")])
images_dp = FileOpener(images_dp, mode="b")
images_dp = TarArchiveReader(images_dp)
images_dp = Filter(images_dp, is_not_background_image)
images_dp = Filter(images_dp, is_not_rogue_image)
images_dp = RoutedDecoder(images_dp, imagehandler("pil"))
dp = IterKeyZipper(images_dp, anns_dp, images_key_fn, ref_key_fn=anns_key_fn, buffer_size=None)
return Mapper(dp, collate_sample)
if __name__ == "__main__":
for _sample in Caltech101():
pass
| true | true |
f7f95c9052d568304e8639c61338929d28fefd0d | 3,289 | py | Python | geotrek/feedback/migrations/0007_auto_20200407_0728.py | pierreloicq/Geotrek-admin | 00cd29f29843f2cc25e5a3c7372fcccf14956887 | [
"BSD-2-Clause"
] | 50 | 2016-10-19T23:01:21.000Z | 2022-03-28T08:28:34.000Z | geotrek/feedback/migrations/0007_auto_20200407_0728.py | pierreloicq/Geotrek-admin | 00cd29f29843f2cc25e5a3c7372fcccf14956887 | [
"BSD-2-Clause"
] | 1,422 | 2016-10-27T10:39:40.000Z | 2022-03-31T13:37:10.000Z | geotrek/feedback/migrations/0007_auto_20200407_0728.py | pierreloicq/Geotrek-admin | 00cd29f29843f2cc25e5a3c7372fcccf14956887 | [
"BSD-2-Clause"
] | 46 | 2016-10-27T10:59:10.000Z | 2022-03-22T15:55:56.000Z | # Generated by Django 2.0.13 on 2020-04-07 07:28
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('feedback', '0006_auto_20200406_1408'),
]
operations = [
migrations.CreateModel(
name='ReportActivity',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('label', models.CharField(max_length=128, verbose_name='Activity')),
('suricate_id', models.PositiveIntegerField(blank=True, null=True, verbose_name='Suricate id')),
],
options={
'verbose_name': 'Activity',
'verbose_name_plural': 'Activities',
'ordering': ('label',),
},
),
migrations.CreateModel(
name='ReportProblemMagnitude',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('label', models.CharField(max_length=128, verbose_name='Problem magnitude')),
('suricate_id', models.PositiveIntegerField(blank=True, null=True, verbose_name='Suricate id')),
],
options={
'verbose_name': 'Problem magnitude',
'verbose_name_plural': 'Problem magnitudes',
'ordering': ('id',),
},
),
migrations.AlterModelOptions(
name='reportcategory',
options={'ordering': ('label',), 'verbose_name': 'Category', 'verbose_name_plural': 'Categories'},
),
migrations.RenameField(
model_name='reportcategory',
old_name='category',
new_name='label',
),
migrations.RenameField(
model_name='reportstatus',
old_name='status',
new_name='label',
),
migrations.AddField(
model_name='reportcategory',
name='suricate_id',
field=models.PositiveIntegerField(blank=True, null=True, verbose_name='Suricate id'),
),
migrations.AlterField(
model_name='report',
name='category',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='feedback.ReportCategory', verbose_name='Category'),
),
migrations.AlterField(
model_name='report',
name='status',
field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='feedback.ReportStatus', verbose_name='Status'),
),
migrations.AddField(
model_name='report',
name='activity',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='feedback.ReportActivity', verbose_name='Activity'),
),
migrations.AddField(
model_name='report',
name='problem_magnitude',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='feedback.ReportProblemMagnitude', verbose_name='Problem magnitude'),
),
]
| 41.1125 | 177 | 0.588629 |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('feedback', '0006_auto_20200406_1408'),
]
operations = [
migrations.CreateModel(
name='ReportActivity',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('label', models.CharField(max_length=128, verbose_name='Activity')),
('suricate_id', models.PositiveIntegerField(blank=True, null=True, verbose_name='Suricate id')),
],
options={
'verbose_name': 'Activity',
'verbose_name_plural': 'Activities',
'ordering': ('label',),
},
),
migrations.CreateModel(
name='ReportProblemMagnitude',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('label', models.CharField(max_length=128, verbose_name='Problem magnitude')),
('suricate_id', models.PositiveIntegerField(blank=True, null=True, verbose_name='Suricate id')),
],
options={
'verbose_name': 'Problem magnitude',
'verbose_name_plural': 'Problem magnitudes',
'ordering': ('id',),
},
),
migrations.AlterModelOptions(
name='reportcategory',
options={'ordering': ('label',), 'verbose_name': 'Category', 'verbose_name_plural': 'Categories'},
),
migrations.RenameField(
model_name='reportcategory',
old_name='category',
new_name='label',
),
migrations.RenameField(
model_name='reportstatus',
old_name='status',
new_name='label',
),
migrations.AddField(
model_name='reportcategory',
name='suricate_id',
field=models.PositiveIntegerField(blank=True, null=True, verbose_name='Suricate id'),
),
migrations.AlterField(
model_name='report',
name='category',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='feedback.ReportCategory', verbose_name='Category'),
),
migrations.AlterField(
model_name='report',
name='status',
field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='feedback.ReportStatus', verbose_name='Status'),
),
migrations.AddField(
model_name='report',
name='activity',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='feedback.ReportActivity', verbose_name='Activity'),
),
migrations.AddField(
model_name='report',
name='problem_magnitude',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='feedback.ReportProblemMagnitude', verbose_name='Problem magnitude'),
),
]
| true | true |
f7f95d6729901524e560552c813dab4c6f2153e7 | 6,812 | py | Python | perfkitbenchmarker/linux_benchmarks/cluster_boot_benchmark.py | srelf-ukcloud/PerfKitBenchmarker | 8ebdf1c90a34a4af33d08283198aaafc5f6e5099 | [
"Apache-2.0"
] | null | null | null | perfkitbenchmarker/linux_benchmarks/cluster_boot_benchmark.py | srelf-ukcloud/PerfKitBenchmarker | 8ebdf1c90a34a4af33d08283198aaafc5f6e5099 | [
"Apache-2.0"
] | null | null | null | perfkitbenchmarker/linux_benchmarks/cluster_boot_benchmark.py | srelf-ukcloud/PerfKitBenchmarker | 8ebdf1c90a34a4af33d08283198aaafc5f6e5099 | [
"Apache-2.0"
] | null | null | null | # Copyright 2014 PerfKitBenchmarker Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Records the time required to boot a cluster of VMs."""
import logging
import time
from absl import flags
from perfkitbenchmarker import configs
from perfkitbenchmarker import sample
from perfkitbenchmarker import vm_util
BENCHMARK_NAME = 'cluster_boot'
BENCHMARK_CONFIG = """
cluster_boot:
description: >
Create a cluster, record all times to boot.
Specify the cluster size with --num_vms.
vm_groups:
default:
vm_spec:
AWS:
machine_type: m5.large
zone: us-east-1
Azure:
machine_type: Standard_D2s_v3
zone: eastus
boot_disk_type: StandardSSD_LRS
GCP:
machine_type: n1-standard-2
zone: us-central1-a
boot_disk_type: pd-ssd
IBMCloud:
machine_type: cx2-2x4
zone: us-south-1
Kubernetes:
image: null
vm_count: null
flags:
# We don't want boot time samples to be affected from retrying, so don't
# retry cluster_boot when rate limited.
retry_on_rate_limited: False
"""
flags.DEFINE_boolean(
'cluster_boot_time_reboot', False,
'Whether to reboot the VMs during the cluster boot benchmark to measure '
'reboot performance.')
flags.DEFINE_boolean(
'cluster_boot_test_port_listening', False,
'Test the time it takes to successfully connect to the port that is used to run the remote command.'
)
FLAGS = flags.FLAGS
def GetConfig(user_config):
return configs.LoadConfig(BENCHMARK_CONFIG, user_config, BENCHMARK_NAME)
def Prepare(unused_benchmark_spec):
pass
def GetTimeToBoot(vms):
"""Creates Samples for the boot time of a list of VMs.
The boot time is the time difference from before the VM is created to when
the VM is responsive to SSH commands.
Args:
vms: List of BaseVirtualMachine subclasses.
Returns:
List of Samples containing the boot times and an overall cluster boot time.
"""
if not vms:
return []
min_create_start_time = min(vm.create_start_time for vm in vms)
max_create_delay_sec = 0
max_boot_time_sec = 0
max_port_listening_time_sec = 0
max_rdp_port_listening_time_sec = 0
samples = []
os_types = set()
for i, vm in enumerate(vms):
assert vm.bootable_time
assert vm.create_start_time
assert vm.bootable_time >= vm.create_start_time
os_types.add(vm.OS_TYPE)
create_delay_sec = vm.create_start_time - min_create_start_time
max_create_delay_sec = max(max_create_delay_sec, create_delay_sec)
metadata = {
'machine_instance': i,
'num_vms': len(vms),
'os_type': vm.OS_TYPE,
'create_delay_sec': '%0.1f' % create_delay_sec
}
boot_time_sec = vm.bootable_time - min_create_start_time
max_boot_time_sec = max(max_boot_time_sec, boot_time_sec)
samples.append(
sample.Sample('Boot Time', boot_time_sec, 'seconds', metadata))
if FLAGS.cluster_boot_test_port_listening:
assert vm.port_listening_time
assert vm.port_listening_time >= vm.create_start_time
port_listening_time_sec = vm.port_listening_time - min_create_start_time
max_port_listening_time_sec = max(max_port_listening_time_sec,
port_listening_time_sec)
samples.append(
sample.Sample('Port Listening Time', port_listening_time_sec,
'seconds', metadata))
# TODO(user): refactor so Windows specifics aren't in linux_benchmarks
if FLAGS.cluster_boot_test_rdp_port_listening:
assert vm.rdp_port_listening_time
assert vm.rdp_port_listening_time >= vm.create_start_time
rdp_port_listening_time_sec = (
vm.rdp_port_listening_time - min_create_start_time)
max_rdp_port_listening_time_sec = max(max_rdp_port_listening_time_sec,
rdp_port_listening_time_sec)
samples.append(
sample.Sample('RDP Port Listening Time', rdp_port_listening_time_sec,
'seconds', metadata))
# Add a total cluster boot sample as the maximum boot time.
metadata = {
'num_vms': len(vms),
'os_type': ','.join(sorted(os_types)),
'max_create_delay_sec': '%0.1f' % max_create_delay_sec
}
samples.append(
sample.Sample('Cluster Boot Time', max_boot_time_sec, 'seconds',
metadata))
if FLAGS.cluster_boot_test_port_listening:
samples.append(
sample.Sample('Cluster Port Listening Time',
max_port_listening_time_sec, 'seconds', metadata))
if FLAGS.cluster_boot_test_rdp_port_listening:
samples.append(
sample.Sample('Cluster RDP Port Listening Time',
max_rdp_port_listening_time_sec, 'seconds', metadata))
if max_create_delay_sec > 1:
logging.warning(
'The maximum delay between starting VM creations is %0.1fs.',
max_create_delay_sec)
return samples
def _MeasureReboot(vms):
"""Measures the time to reboot the cluster of VMs.
Args:
vms: List of BaseVirtualMachine subclasses.
Returns:
List of Samples containing the reboot times and an overall cluster reboot
time.
"""
samples = []
before_reboot_timestamp = time.time()
reboot_times = vm_util.RunThreaded(lambda vm: vm.Reboot(), vms)
cluster_reboot_time = time.time() - before_reboot_timestamp
os_types = set()
for i, vm in enumerate(vms):
metadata = {
'machine_instance': i,
'num_vms': len(vms),
'os_type': vm.OS_TYPE
}
os_types.add(vm.OS_TYPE)
samples.append(
sample.Sample('Reboot Time', reboot_times[i], 'seconds', metadata))
metadata = {'num_vms': len(vms), 'os_type': ','.join(sorted(os_types))}
samples.append(
sample.Sample('Cluster Reboot Time', cluster_reboot_time, 'seconds',
metadata))
return samples
def Run(benchmark_spec):
"""Measure the boot time for all VMs.
Args:
benchmark_spec: The benchmark specification.
Returns:
An empty list (all boot samples will be added later).
"""
samples = []
if FLAGS.cluster_boot_time_reboot:
samples.extend(_MeasureReboot(benchmark_spec.vms))
return samples
def Cleanup(unused_benchmark_spec):
pass
| 32.75 | 104 | 0.69539 |
import logging
import time
from absl import flags
from perfkitbenchmarker import configs
from perfkitbenchmarker import sample
from perfkitbenchmarker import vm_util
BENCHMARK_NAME = 'cluster_boot'
BENCHMARK_CONFIG = """
cluster_boot:
description: >
Create a cluster, record all times to boot.
Specify the cluster size with --num_vms.
vm_groups:
default:
vm_spec:
AWS:
machine_type: m5.large
zone: us-east-1
Azure:
machine_type: Standard_D2s_v3
zone: eastus
boot_disk_type: StandardSSD_LRS
GCP:
machine_type: n1-standard-2
zone: us-central1-a
boot_disk_type: pd-ssd
IBMCloud:
machine_type: cx2-2x4
zone: us-south-1
Kubernetes:
image: null
vm_count: null
flags:
# We don't want boot time samples to be affected from retrying, so don't
# retry cluster_boot when rate limited.
retry_on_rate_limited: False
"""
flags.DEFINE_boolean(
'cluster_boot_time_reboot', False,
'Whether to reboot the VMs during the cluster boot benchmark to measure '
'reboot performance.')
flags.DEFINE_boolean(
'cluster_boot_test_port_listening', False,
'Test the time it takes to successfully connect to the port that is used to run the remote command.'
)
FLAGS = flags.FLAGS
def GetConfig(user_config):
return configs.LoadConfig(BENCHMARK_CONFIG, user_config, BENCHMARK_NAME)
def Prepare(unused_benchmark_spec):
pass
def GetTimeToBoot(vms):
if not vms:
return []
min_create_start_time = min(vm.create_start_time for vm in vms)
max_create_delay_sec = 0
max_boot_time_sec = 0
max_port_listening_time_sec = 0
max_rdp_port_listening_time_sec = 0
samples = []
os_types = set()
for i, vm in enumerate(vms):
assert vm.bootable_time
assert vm.create_start_time
assert vm.bootable_time >= vm.create_start_time
os_types.add(vm.OS_TYPE)
create_delay_sec = vm.create_start_time - min_create_start_time
max_create_delay_sec = max(max_create_delay_sec, create_delay_sec)
metadata = {
'machine_instance': i,
'num_vms': len(vms),
'os_type': vm.OS_TYPE,
'create_delay_sec': '%0.1f' % create_delay_sec
}
boot_time_sec = vm.bootable_time - min_create_start_time
max_boot_time_sec = max(max_boot_time_sec, boot_time_sec)
samples.append(
sample.Sample('Boot Time', boot_time_sec, 'seconds', metadata))
if FLAGS.cluster_boot_test_port_listening:
assert vm.port_listening_time
assert vm.port_listening_time >= vm.create_start_time
port_listening_time_sec = vm.port_listening_time - min_create_start_time
max_port_listening_time_sec = max(max_port_listening_time_sec,
port_listening_time_sec)
samples.append(
sample.Sample('Port Listening Time', port_listening_time_sec,
'seconds', metadata))
if FLAGS.cluster_boot_test_rdp_port_listening:
assert vm.rdp_port_listening_time
assert vm.rdp_port_listening_time >= vm.create_start_time
rdp_port_listening_time_sec = (
vm.rdp_port_listening_time - min_create_start_time)
max_rdp_port_listening_time_sec = max(max_rdp_port_listening_time_sec,
rdp_port_listening_time_sec)
samples.append(
sample.Sample('RDP Port Listening Time', rdp_port_listening_time_sec,
'seconds', metadata))
# Add a total cluster boot sample as the maximum boot time.
metadata = {
'num_vms': len(vms),
'os_type': ','.join(sorted(os_types)),
'max_create_delay_sec': '%0.1f' % max_create_delay_sec
}
samples.append(
sample.Sample('Cluster Boot Time', max_boot_time_sec, 'seconds',
metadata))
if FLAGS.cluster_boot_test_port_listening:
samples.append(
sample.Sample('Cluster Port Listening Time',
max_port_listening_time_sec, 'seconds', metadata))
if FLAGS.cluster_boot_test_rdp_port_listening:
samples.append(
sample.Sample('Cluster RDP Port Listening Time',
max_rdp_port_listening_time_sec, 'seconds', metadata))
if max_create_delay_sec > 1:
logging.warning(
'The maximum delay between starting VM creations is %0.1fs.',
max_create_delay_sec)
return samples
def _MeasureReboot(vms):
samples = []
before_reboot_timestamp = time.time()
reboot_times = vm_util.RunThreaded(lambda vm: vm.Reboot(), vms)
cluster_reboot_time = time.time() - before_reboot_timestamp
os_types = set()
for i, vm in enumerate(vms):
metadata = {
'machine_instance': i,
'num_vms': len(vms),
'os_type': vm.OS_TYPE
}
os_types.add(vm.OS_TYPE)
samples.append(
sample.Sample('Reboot Time', reboot_times[i], 'seconds', metadata))
metadata = {'num_vms': len(vms), 'os_type': ','.join(sorted(os_types))}
samples.append(
sample.Sample('Cluster Reboot Time', cluster_reboot_time, 'seconds',
metadata))
return samples
def Run(benchmark_spec):
samples = []
if FLAGS.cluster_boot_time_reboot:
samples.extend(_MeasureReboot(benchmark_spec.vms))
return samples
def Cleanup(unused_benchmark_spec):
pass
| true | true |
f7f95df184761194dfdaba42ea0b3b9622834b12 | 3,387 | py | Python | tests/utils.py | pcanas/vissl | d293b8295f03a4caeaebd25f3e5ed38866dd4d10 | [
"MIT"
] | 3 | 2021-07-08T15:06:49.000Z | 2021-08-13T18:55:02.000Z | tests/utils.py | pcanas/vissl | d293b8295f03a4caeaebd25f3e5ed38866dd4d10 | [
"MIT"
] | 2 | 2021-07-25T15:46:07.000Z | 2021-08-11T10:08:53.000Z | tests/utils.py | pcanas/vissl | d293b8295f03a4caeaebd25f3e5ed38866dd4d10 | [
"MIT"
] | 2 | 2021-07-08T15:15:55.000Z | 2021-08-25T14:16:01.000Z | # Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
import re
import sys
from typing import Any, List
import pkg_resources
from hydra.experimental import compose, initialize_config_module
from omegaconf import OmegaConf
logger = logging.getLogger("vissl")
# List all the config files, used to generate the unit tests on the fly
def list_config_files(dir_path, exclude_folders):
resource_name = "configs"
assert pkg_resources.resource_isdir(resource_name, dir_path)
all_items = pkg_resources.resource_listdir(resource_name, dir_path)
config_files = []
def valid_file(filename):
if not filename.endswith("yaml"):
return False
if exclude_folders and any(x in filename for x in exclude_folders):
return False
return True
for item in all_items:
subpath = f"{dir_path}/{item}"
if pkg_resources.resource_isdir(resource_name, subpath):
# Recursively test all the tree
config_files.extend(list_config_files(subpath, exclude_folders))
if valid_file(subpath):
# If valid leaf, return the config file
config_files.append(subpath)
return config_files
def create_valid_input(input_list):
out_list = []
for item in input_list:
out_list.append(re.sub("config/", "config=", item))
return out_list
# we skip object detection configs since they are for detectron2 codebase
BENCHMARK_CONFIGS = create_valid_input(
list_config_files("config/benchmark", exclude_folders=["object_detection"])
)
PRETRAIN_CONFIGS = create_valid_input(
list_config_files("config/pretrain", exclude_folders=None)
)
INTEGRATION_TEST_CONFIGS = create_valid_input(
list_config_files("config/test/integration_test", exclude_folders=None)
)
ROOT_CONFIGS = create_valid_input(
list_config_files(
"config", exclude_folders=["models", "optimization", "object_detection"]
)
)
ROOT_OSS_CONFIGS = create_valid_input(
list_config_files(
"config", exclude_folders=["models", "optimization", "object_detection", "fb"]
)
)
# configs that require loss optimization and hence trainable
ROOT_LOSS_CONFIGS = create_valid_input(
list_config_files(
"config",
exclude_folders=[
"models",
"optimization",
"object_detection",
"nearest_neighbor",
"feature_extraction",
"fb",
],
)
)
UNIT_TEST_CONFIGS = create_valid_input(
list_config_files("config/test/cpu_test", exclude_folders=None)
)
initialize_config_module(config_module="vissl.config")
class SSLHydraConfig(object):
def __init__(self, overrides: List[Any] = None):
self.overrides = []
if overrides is not None and len(overrides) > 0:
self.overrides.extend(overrides)
cfg = compose(config_name="defaults", overrides=self.overrides)
self.default_cfg = cfg
@classmethod
def from_configs(cls, config_files: List[Any] = None):
return cls(config_files)
def override(self, config_files: List[Any]):
sys.argv = config_files
cli_conf = OmegaConf.from_cli(config_files)
self.default_cfg = OmegaConf.merge(self.default_cfg, cli_conf)
| 29.452174 | 86 | 0.700325 |
import logging
import re
import sys
from typing import Any, List
import pkg_resources
from hydra.experimental import compose, initialize_config_module
from omegaconf import OmegaConf
logger = logging.getLogger("vissl")
def list_config_files(dir_path, exclude_folders):
resource_name = "configs"
assert pkg_resources.resource_isdir(resource_name, dir_path)
all_items = pkg_resources.resource_listdir(resource_name, dir_path)
config_files = []
def valid_file(filename):
if not filename.endswith("yaml"):
return False
if exclude_folders and any(x in filename for x in exclude_folders):
return False
return True
for item in all_items:
subpath = f"{dir_path}/{item}"
if pkg_resources.resource_isdir(resource_name, subpath):
config_files.extend(list_config_files(subpath, exclude_folders))
if valid_file(subpath):
config_files.append(subpath)
return config_files
def create_valid_input(input_list):
out_list = []
for item in input_list:
out_list.append(re.sub("config/", "config=", item))
return out_list
BENCHMARK_CONFIGS = create_valid_input(
list_config_files("config/benchmark", exclude_folders=["object_detection"])
)
PRETRAIN_CONFIGS = create_valid_input(
list_config_files("config/pretrain", exclude_folders=None)
)
INTEGRATION_TEST_CONFIGS = create_valid_input(
list_config_files("config/test/integration_test", exclude_folders=None)
)
ROOT_CONFIGS = create_valid_input(
list_config_files(
"config", exclude_folders=["models", "optimization", "object_detection"]
)
)
ROOT_OSS_CONFIGS = create_valid_input(
list_config_files(
"config", exclude_folders=["models", "optimization", "object_detection", "fb"]
)
)
ROOT_LOSS_CONFIGS = create_valid_input(
list_config_files(
"config",
exclude_folders=[
"models",
"optimization",
"object_detection",
"nearest_neighbor",
"feature_extraction",
"fb",
],
)
)
UNIT_TEST_CONFIGS = create_valid_input(
list_config_files("config/test/cpu_test", exclude_folders=None)
)
initialize_config_module(config_module="vissl.config")
class SSLHydraConfig(object):
def __init__(self, overrides: List[Any] = None):
self.overrides = []
if overrides is not None and len(overrides) > 0:
self.overrides.extend(overrides)
cfg = compose(config_name="defaults", overrides=self.overrides)
self.default_cfg = cfg
@classmethod
def from_configs(cls, config_files: List[Any] = None):
return cls(config_files)
def override(self, config_files: List[Any]):
sys.argv = config_files
cli_conf = OmegaConf.from_cli(config_files)
self.default_cfg = OmegaConf.merge(self.default_cfg, cli_conf)
| true | true |
f7f95e5f3975a2d20a6f117ebaf8890415be9a32 | 47,103 | py | Python | bentoml/_internal/yatai_client/proto/deployment_pb2.py | jmc529/BentoML | 96c1ec9e486d98930e24bbbac5b2991a6d416f97 | [
"Apache-2.0"
] | null | null | null | bentoml/_internal/yatai_client/proto/deployment_pb2.py | jmc529/BentoML | 96c1ec9e486d98930e24bbbac5b2991a6d416f97 | [
"Apache-2.0"
] | null | null | null | bentoml/_internal/yatai_client/proto/deployment_pb2.py | jmc529/BentoML | 96c1ec9e486d98930e24bbbac5b2991a6d416f97 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: deployment.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2
from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2
import bentoml._internal.yatai_client.proto.status_pb2 as status__pb2
import bentoml._internal.yatai_client.proto.label_selectors_pb2 as label__selectors__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='deployment.proto',
package='bentoml',
syntax='proto3',
serialized_options=None,
create_key=_descriptor._internal_create_key,
serialized_pb=b'\n\x10\x64\x65ployment.proto\x12\x07\x62\x65ntoml\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x0cstatus.proto\x1a\x15label_selectors.proto\"\xe3\x02\n\x0e\x44\x65ploymentSpec\x12\x12\n\nbento_name\x18\x01 \x01(\t\x12\x15\n\rbento_version\x18\x02 \x01(\t\x12<\n\x08operator\x18\x03 \x01(\x0e\x32*.bentoml.DeploymentSpec.DeploymentOperator\x12N\n\x16\x63ustom_operator_config\x18\x04 \x01(\x0b\x32,.bentoml.DeploymentSpec.CustomOperatorConfigH\x00\x1aM\n\x14\x43ustomOperatorConfig\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\'\n\x06\x63onfig\x18\x02 \x01(\x0b\x32\x17.google.protobuf.Struct\"+\n\x12\x44\x65ploymentOperator\x12\t\n\x05UNSET\x10\x00\x12\n\n\x06\x43USTOM\x10\x01\x42\x1c\n\x1a\x64\x65ployment_operator_config\"\xa9\x02\n\x0f\x44\x65ploymentState\x12-\n\x05state\x18\x01 \x01(\x0e\x32\x1e.bentoml.DeploymentState.State\x12\x15\n\rerror_message\x18\x02 \x01(\t\x12\x11\n\tinfo_json\x18\x03 \x01(\t\x12-\n\ttimestamp\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"\x8d\x01\n\x05State\x12\x0b\n\x07PENDING\x10\x00\x12\x0b\n\x07RUNNING\x10\x01\x12\r\n\tSUCCEEDED\x10\x02\x12\n\n\x06\x46\x41ILED\x10\x03\x12\x0b\n\x07UNKNOWN\x10\x04\x12\r\n\tCOMPLETED\x10\x05\x12\x17\n\x13\x43RASH_LOOP_BACK_OFF\x10\x06\x12\t\n\x05\x45RROR\x10\x07\x12\x0f\n\x0bINACTIVATED\x10\x08\"\xb1\x03\n\nDeployment\x12\x11\n\tnamespace\x18\x01 \x01(\t\x12\x0c\n\x04name\x18\x02 \x01(\t\x12%\n\x04spec\x18\x03 \x01(\x0b\x32\x17.bentoml.DeploymentSpec\x12\'\n\x05state\x18\x04 \x01(\x0b\x32\x18.bentoml.DeploymentState\x12\x39\n\x0b\x61nnotations\x18\x05 \x03(\x0b\x32$.bentoml.Deployment.AnnotationsEntry\x12/\n\x06labels\x18\x06 \x03(\x0b\x32\x1f.bentoml.Deployment.LabelsEntry\x12.\n\ncreated_at\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x33\n\x0flast_updated_at\x18\x08 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x1a\x32\n\x10\x41nnotationsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\";\n\x10\x44\x65ploymentStatus\x12\'\n\x05state\x18\x01 \x01(\x0b\x32\x18.bentoml.DeploymentState\"A\n\x16\x41pplyDeploymentRequest\x12\'\n\ndeployment\x18\x01 \x01(\x0b\x32\x13.bentoml.Deployment\"c\n\x17\x41pplyDeploymentResponse\x12\x1f\n\x06status\x18\x01 \x01(\x0b\x32\x0f.bentoml.Status\x12\'\n\ndeployment\x18\x02 \x01(\x0b\x32\x13.bentoml.Deployment\"[\n\x17\x44\x65leteDeploymentRequest\x12\x17\n\x0f\x64\x65ployment_name\x18\x01 \x01(\t\x12\x11\n\tnamespace\x18\x02 \x01(\t\x12\x14\n\x0c\x66orce_delete\x18\x03 \x01(\x08\";\n\x18\x44\x65leteDeploymentResponse\x12\x1f\n\x06status\x18\x01 \x01(\x0b\x32\x0f.bentoml.Status\"B\n\x14GetDeploymentRequest\x12\x17\n\x0f\x64\x65ployment_name\x18\x01 \x01(\t\x12\x11\n\tnamespace\x18\x02 \x01(\t\"a\n\x15GetDeploymentResponse\x12\x1f\n\x06status\x18\x01 \x01(\x0b\x32\x0f.bentoml.Status\x12\'\n\ndeployment\x18\x02 \x01(\x0b\x32\x13.bentoml.Deployment\"G\n\x19\x44\x65scribeDeploymentRequest\x12\x17\n\x0f\x64\x65ployment_name\x18\x01 \x01(\t\x12\x11\n\tnamespace\x18\x02 \x01(\t\"f\n\x1a\x44\x65scribeDeploymentResponse\x12\x1f\n\x06status\x18\x01 \x01(\x0b\x32\x0f.bentoml.Status\x12\'\n\x05state\x18\x02 \x01(\x0b\x32\x18.bentoml.DeploymentState\"\xd9\x02\n\x16ListDeploymentsRequest\x12\x11\n\tnamespace\x18\x01 \x01(\t\x12\x0e\n\x06offset\x18\x02 \x01(\x05\x12\r\n\x05limit\x18\x03 \x01(\x05\x12<\n\x08operator\x18\x04 \x01(\x0e\x32*.bentoml.DeploymentSpec.DeploymentOperator\x12\x41\n\x08order_by\x18\x05 \x01(\x0e\x32/.bentoml.ListDeploymentsRequest.SORTABLE_COLUMN\x12\x17\n\x0f\x61scending_order\x18\x06 \x01(\x08\x12\x14\n\x0clabels_query\x18\x07 \x01(\t\x12\x30\n\x0flabel_selectors\x18\x08 \x01(\x0b\x32\x17.bentoml.LabelSelectors\"+\n\x0fSORTABLE_COLUMN\x12\x0e\n\ncreated_at\x10\x00\x12\x08\n\x04name\x10\x01\"d\n\x17ListDeploymentsResponse\x12\x1f\n\x06status\x18\x01 \x01(\x0b\x32\x0f.bentoml.Status\x12(\n\x0b\x64\x65ployments\x18\x02 \x03(\x0b\x32\x13.bentoml.Deploymentb\x06proto3'
,
dependencies=[google_dot_protobuf_dot_struct__pb2.DESCRIPTOR,google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR,status__pb2.DESCRIPTOR,label__selectors__pb2.DESCRIPTOR,])
_DEPLOYMENTSPEC_DEPLOYMENTOPERATOR = _descriptor.EnumDescriptor(
name='DeploymentOperator',
full_name='bentoml.DeploymentSpec.DeploymentOperator',
filename=None,
file=DESCRIPTOR,
create_key=_descriptor._internal_create_key,
values=[
_descriptor.EnumValueDescriptor(
name='UNSET', index=0, number=0,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='CUSTOM', index=1, number=1,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
],
containing_type=None,
serialized_options=None,
serialized_start=412,
serialized_end=455,
)
_sym_db.RegisterEnumDescriptor(_DEPLOYMENTSPEC_DEPLOYMENTOPERATOR)
_DEPLOYMENTSTATE_STATE = _descriptor.EnumDescriptor(
name='State',
full_name='bentoml.DeploymentState.State',
filename=None,
file=DESCRIPTOR,
create_key=_descriptor._internal_create_key,
values=[
_descriptor.EnumValueDescriptor(
name='PENDING', index=0, number=0,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='RUNNING', index=1, number=1,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='SUCCEEDED', index=2, number=2,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='FAILED', index=3, number=3,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='UNKNOWN', index=4, number=4,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='COMPLETED', index=5, number=5,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='CRASH_LOOP_BACK_OFF', index=6, number=6,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='ERROR', index=7, number=7,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='INACTIVATED', index=8, number=8,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
],
containing_type=None,
serialized_options=None,
serialized_start=644,
serialized_end=785,
)
_sym_db.RegisterEnumDescriptor(_DEPLOYMENTSTATE_STATE)
_LISTDEPLOYMENTSREQUEST_SORTABLE_COLUMN = _descriptor.EnumDescriptor(
name='SORTABLE_COLUMN',
full_name='bentoml.ListDeploymentsRequest.SORTABLE_COLUMN',
filename=None,
file=DESCRIPTOR,
create_key=_descriptor._internal_create_key,
values=[
_descriptor.EnumValueDescriptor(
name='created_at', index=0, number=0,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='name', index=1, number=1,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
],
containing_type=None,
serialized_options=None,
serialized_start=2253,
serialized_end=2296,
)
_sym_db.RegisterEnumDescriptor(_LISTDEPLOYMENTSREQUEST_SORTABLE_COLUMN)
_DEPLOYMENTSPEC_CUSTOMOPERATORCONFIG = _descriptor.Descriptor(
name='CustomOperatorConfig',
full_name='bentoml.DeploymentSpec.CustomOperatorConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='name', full_name='bentoml.DeploymentSpec.CustomOperatorConfig.name', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='config', full_name='bentoml.DeploymentSpec.CustomOperatorConfig.config', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=333,
serialized_end=410,
)
_DEPLOYMENTSPEC = _descriptor.Descriptor(
name='DeploymentSpec',
full_name='bentoml.DeploymentSpec',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='bento_name', full_name='bentoml.DeploymentSpec.bento_name', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='bento_version', full_name='bentoml.DeploymentSpec.bento_version', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='operator', full_name='bentoml.DeploymentSpec.operator', index=2,
number=3, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='custom_operator_config', full_name='bentoml.DeploymentSpec.custom_operator_config', index=3,
number=4, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[_DEPLOYMENTSPEC_CUSTOMOPERATORCONFIG, ],
enum_types=[
_DEPLOYMENTSPEC_DEPLOYMENTOPERATOR,
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
_descriptor.OneofDescriptor(
name='deployment_operator_config', full_name='bentoml.DeploymentSpec.deployment_operator_config',
index=0, containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[]),
],
serialized_start=130,
serialized_end=485,
)
_DEPLOYMENTSTATE = _descriptor.Descriptor(
name='DeploymentState',
full_name='bentoml.DeploymentState',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='state', full_name='bentoml.DeploymentState.state', index=0,
number=1, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='error_message', full_name='bentoml.DeploymentState.error_message', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='info_json', full_name='bentoml.DeploymentState.info_json', index=2,
number=3, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='timestamp', full_name='bentoml.DeploymentState.timestamp', index=3,
number=4, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
_DEPLOYMENTSTATE_STATE,
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=488,
serialized_end=785,
)
_DEPLOYMENT_ANNOTATIONSENTRY = _descriptor.Descriptor(
name='AnnotationsEntry',
full_name='bentoml.Deployment.AnnotationsEntry',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='key', full_name='bentoml.Deployment.AnnotationsEntry.key', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='value', full_name='bentoml.Deployment.AnnotationsEntry.value', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=b'8\001',
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=1124,
serialized_end=1174,
)
_DEPLOYMENT_LABELSENTRY = _descriptor.Descriptor(
name='LabelsEntry',
full_name='bentoml.Deployment.LabelsEntry',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='key', full_name='bentoml.Deployment.LabelsEntry.key', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='value', full_name='bentoml.Deployment.LabelsEntry.value', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=b'8\001',
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=1176,
serialized_end=1221,
)
_DEPLOYMENT = _descriptor.Descriptor(
name='Deployment',
full_name='bentoml.Deployment',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='namespace', full_name='bentoml.Deployment.namespace', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='name', full_name='bentoml.Deployment.name', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='spec', full_name='bentoml.Deployment.spec', index=2,
number=3, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='state', full_name='bentoml.Deployment.state', index=3,
number=4, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='annotations', full_name='bentoml.Deployment.annotations', index=4,
number=5, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='labels', full_name='bentoml.Deployment.labels', index=5,
number=6, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='created_at', full_name='bentoml.Deployment.created_at', index=6,
number=7, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='last_updated_at', full_name='bentoml.Deployment.last_updated_at', index=7,
number=8, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[_DEPLOYMENT_ANNOTATIONSENTRY, _DEPLOYMENT_LABELSENTRY, ],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=788,
serialized_end=1221,
)
_DEPLOYMENTSTATUS = _descriptor.Descriptor(
name='DeploymentStatus',
full_name='bentoml.DeploymentStatus',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='state', full_name='bentoml.DeploymentStatus.state', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=1223,
serialized_end=1282,
)
_APPLYDEPLOYMENTREQUEST = _descriptor.Descriptor(
name='ApplyDeploymentRequest',
full_name='bentoml.ApplyDeploymentRequest',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='deployment', full_name='bentoml.ApplyDeploymentRequest.deployment', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=1284,
serialized_end=1349,
)
_APPLYDEPLOYMENTRESPONSE = _descriptor.Descriptor(
name='ApplyDeploymentResponse',
full_name='bentoml.ApplyDeploymentResponse',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='status', full_name='bentoml.ApplyDeploymentResponse.status', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='deployment', full_name='bentoml.ApplyDeploymentResponse.deployment', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=1351,
serialized_end=1450,
)
_DELETEDEPLOYMENTREQUEST = _descriptor.Descriptor(
name='DeleteDeploymentRequest',
full_name='bentoml.DeleteDeploymentRequest',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='deployment_name', full_name='bentoml.DeleteDeploymentRequest.deployment_name', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='namespace', full_name='bentoml.DeleteDeploymentRequest.namespace', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='force_delete', full_name='bentoml.DeleteDeploymentRequest.force_delete', index=2,
number=3, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=1452,
serialized_end=1543,
)
_DELETEDEPLOYMENTRESPONSE = _descriptor.Descriptor(
name='DeleteDeploymentResponse',
full_name='bentoml.DeleteDeploymentResponse',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='status', full_name='bentoml.DeleteDeploymentResponse.status', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=1545,
serialized_end=1604,
)
_GETDEPLOYMENTREQUEST = _descriptor.Descriptor(
name='GetDeploymentRequest',
full_name='bentoml.GetDeploymentRequest',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='deployment_name', full_name='bentoml.GetDeploymentRequest.deployment_name', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='namespace', full_name='bentoml.GetDeploymentRequest.namespace', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=1606,
serialized_end=1672,
)
_GETDEPLOYMENTRESPONSE = _descriptor.Descriptor(
name='GetDeploymentResponse',
full_name='bentoml.GetDeploymentResponse',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='status', full_name='bentoml.GetDeploymentResponse.status', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='deployment', full_name='bentoml.GetDeploymentResponse.deployment', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=1674,
serialized_end=1771,
)
_DESCRIBEDEPLOYMENTREQUEST = _descriptor.Descriptor(
name='DescribeDeploymentRequest',
full_name='bentoml.DescribeDeploymentRequest',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='deployment_name', full_name='bentoml.DescribeDeploymentRequest.deployment_name', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='namespace', full_name='bentoml.DescribeDeploymentRequest.namespace', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=1773,
serialized_end=1844,
)
_DESCRIBEDEPLOYMENTRESPONSE = _descriptor.Descriptor(
name='DescribeDeploymentResponse',
full_name='bentoml.DescribeDeploymentResponse',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='status', full_name='bentoml.DescribeDeploymentResponse.status', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='state', full_name='bentoml.DescribeDeploymentResponse.state', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=1846,
serialized_end=1948,
)
_LISTDEPLOYMENTSREQUEST = _descriptor.Descriptor(
name='ListDeploymentsRequest',
full_name='bentoml.ListDeploymentsRequest',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='namespace', full_name='bentoml.ListDeploymentsRequest.namespace', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='offset', full_name='bentoml.ListDeploymentsRequest.offset', index=1,
number=2, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='limit', full_name='bentoml.ListDeploymentsRequest.limit', index=2,
number=3, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='operator', full_name='bentoml.ListDeploymentsRequest.operator', index=3,
number=4, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='order_by', full_name='bentoml.ListDeploymentsRequest.order_by', index=4,
number=5, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='ascending_order', full_name='bentoml.ListDeploymentsRequest.ascending_order', index=5,
number=6, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='labels_query', full_name='bentoml.ListDeploymentsRequest.labels_query', index=6,
number=7, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='label_selectors', full_name='bentoml.ListDeploymentsRequest.label_selectors', index=7,
number=8, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
_LISTDEPLOYMENTSREQUEST_SORTABLE_COLUMN,
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=1951,
serialized_end=2296,
)
_LISTDEPLOYMENTSRESPONSE = _descriptor.Descriptor(
name='ListDeploymentsResponse',
full_name='bentoml.ListDeploymentsResponse',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='status', full_name='bentoml.ListDeploymentsResponse.status', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='deployments', full_name='bentoml.ListDeploymentsResponse.deployments', index=1,
number=2, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=2298,
serialized_end=2398,
)
_DEPLOYMENTSPEC_CUSTOMOPERATORCONFIG.fields_by_name['config'].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT
_DEPLOYMENTSPEC_CUSTOMOPERATORCONFIG.containing_type = _DEPLOYMENTSPEC
_DEPLOYMENTSPEC.fields_by_name['operator'].enum_type = _DEPLOYMENTSPEC_DEPLOYMENTOPERATOR
_DEPLOYMENTSPEC.fields_by_name['custom_operator_config'].message_type = _DEPLOYMENTSPEC_CUSTOMOPERATORCONFIG
_DEPLOYMENTSPEC_DEPLOYMENTOPERATOR.containing_type = _DEPLOYMENTSPEC
_DEPLOYMENTSPEC.oneofs_by_name['deployment_operator_config'].fields.append(
_DEPLOYMENTSPEC.fields_by_name['custom_operator_config'])
_DEPLOYMENTSPEC.fields_by_name['custom_operator_config'].containing_oneof = _DEPLOYMENTSPEC.oneofs_by_name['deployment_operator_config']
_DEPLOYMENTSTATE.fields_by_name['state'].enum_type = _DEPLOYMENTSTATE_STATE
_DEPLOYMENTSTATE.fields_by_name['timestamp'].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP
_DEPLOYMENTSTATE_STATE.containing_type = _DEPLOYMENTSTATE
_DEPLOYMENT_ANNOTATIONSENTRY.containing_type = _DEPLOYMENT
_DEPLOYMENT_LABELSENTRY.containing_type = _DEPLOYMENT
_DEPLOYMENT.fields_by_name['spec'].message_type = _DEPLOYMENTSPEC
_DEPLOYMENT.fields_by_name['state'].message_type = _DEPLOYMENTSTATE
_DEPLOYMENT.fields_by_name['annotations'].message_type = _DEPLOYMENT_ANNOTATIONSENTRY
_DEPLOYMENT.fields_by_name['labels'].message_type = _DEPLOYMENT_LABELSENTRY
_DEPLOYMENT.fields_by_name['created_at'].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP
_DEPLOYMENT.fields_by_name['last_updated_at'].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP
_DEPLOYMENTSTATUS.fields_by_name['state'].message_type = _DEPLOYMENTSTATE
_APPLYDEPLOYMENTREQUEST.fields_by_name['deployment'].message_type = _DEPLOYMENT
_APPLYDEPLOYMENTRESPONSE.fields_by_name['status'].message_type = status__pb2._STATUS
_APPLYDEPLOYMENTRESPONSE.fields_by_name['deployment'].message_type = _DEPLOYMENT
_DELETEDEPLOYMENTRESPONSE.fields_by_name['status'].message_type = status__pb2._STATUS
_GETDEPLOYMENTRESPONSE.fields_by_name['status'].message_type = status__pb2._STATUS
_GETDEPLOYMENTRESPONSE.fields_by_name['deployment'].message_type = _DEPLOYMENT
_DESCRIBEDEPLOYMENTRESPONSE.fields_by_name['status'].message_type = status__pb2._STATUS
_DESCRIBEDEPLOYMENTRESPONSE.fields_by_name['state'].message_type = _DEPLOYMENTSTATE
_LISTDEPLOYMENTSREQUEST.fields_by_name['operator'].enum_type = _DEPLOYMENTSPEC_DEPLOYMENTOPERATOR
_LISTDEPLOYMENTSREQUEST.fields_by_name['order_by'].enum_type = _LISTDEPLOYMENTSREQUEST_SORTABLE_COLUMN
_LISTDEPLOYMENTSREQUEST.fields_by_name['label_selectors'].message_type = label__selectors__pb2._LABELSELECTORS
_LISTDEPLOYMENTSREQUEST_SORTABLE_COLUMN.containing_type = _LISTDEPLOYMENTSREQUEST
_LISTDEPLOYMENTSRESPONSE.fields_by_name['status'].message_type = status__pb2._STATUS
_LISTDEPLOYMENTSRESPONSE.fields_by_name['deployments'].message_type = _DEPLOYMENT
DESCRIPTOR.message_types_by_name['DeploymentSpec'] = _DEPLOYMENTSPEC
DESCRIPTOR.message_types_by_name['DeploymentState'] = _DEPLOYMENTSTATE
DESCRIPTOR.message_types_by_name['Deployment'] = _DEPLOYMENT
DESCRIPTOR.message_types_by_name['DeploymentStatus'] = _DEPLOYMENTSTATUS
DESCRIPTOR.message_types_by_name['ApplyDeploymentRequest'] = _APPLYDEPLOYMENTREQUEST
DESCRIPTOR.message_types_by_name['ApplyDeploymentResponse'] = _APPLYDEPLOYMENTRESPONSE
DESCRIPTOR.message_types_by_name['DeleteDeploymentRequest'] = _DELETEDEPLOYMENTREQUEST
DESCRIPTOR.message_types_by_name['DeleteDeploymentResponse'] = _DELETEDEPLOYMENTRESPONSE
DESCRIPTOR.message_types_by_name['GetDeploymentRequest'] = _GETDEPLOYMENTREQUEST
DESCRIPTOR.message_types_by_name['GetDeploymentResponse'] = _GETDEPLOYMENTRESPONSE
DESCRIPTOR.message_types_by_name['DescribeDeploymentRequest'] = _DESCRIBEDEPLOYMENTREQUEST
DESCRIPTOR.message_types_by_name['DescribeDeploymentResponse'] = _DESCRIBEDEPLOYMENTRESPONSE
DESCRIPTOR.message_types_by_name['ListDeploymentsRequest'] = _LISTDEPLOYMENTSREQUEST
DESCRIPTOR.message_types_by_name['ListDeploymentsResponse'] = _LISTDEPLOYMENTSRESPONSE
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
DeploymentSpec = _reflection.GeneratedProtocolMessageType('DeploymentSpec', (_message.Message,), {
'CustomOperatorConfig' : _reflection.GeneratedProtocolMessageType('CustomOperatorConfig', (_message.Message,), {
'DESCRIPTOR' : _DEPLOYMENTSPEC_CUSTOMOPERATORCONFIG,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.DeploymentSpec.CustomOperatorConfig)
})
,
'DESCRIPTOR' : _DEPLOYMENTSPEC,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.DeploymentSpec)
})
_sym_db.RegisterMessage(DeploymentSpec)
_sym_db.RegisterMessage(DeploymentSpec.CustomOperatorConfig)
DeploymentState = _reflection.GeneratedProtocolMessageType('DeploymentState', (_message.Message,), {
'DESCRIPTOR' : _DEPLOYMENTSTATE,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.DeploymentState)
})
_sym_db.RegisterMessage(DeploymentState)
Deployment = _reflection.GeneratedProtocolMessageType('Deployment', (_message.Message,), {
'AnnotationsEntry' : _reflection.GeneratedProtocolMessageType('AnnotationsEntry', (_message.Message,), {
'DESCRIPTOR' : _DEPLOYMENT_ANNOTATIONSENTRY,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.Deployment.AnnotationsEntry)
})
,
'LabelsEntry' : _reflection.GeneratedProtocolMessageType('LabelsEntry', (_message.Message,), {
'DESCRIPTOR' : _DEPLOYMENT_LABELSENTRY,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.Deployment.LabelsEntry)
})
,
'DESCRIPTOR' : _DEPLOYMENT,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.Deployment)
})
_sym_db.RegisterMessage(Deployment)
_sym_db.RegisterMessage(Deployment.AnnotationsEntry)
_sym_db.RegisterMessage(Deployment.LabelsEntry)
DeploymentStatus = _reflection.GeneratedProtocolMessageType('DeploymentStatus', (_message.Message,), {
'DESCRIPTOR' : _DEPLOYMENTSTATUS,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.DeploymentStatus)
})
_sym_db.RegisterMessage(DeploymentStatus)
ApplyDeploymentRequest = _reflection.GeneratedProtocolMessageType('ApplyDeploymentRequest', (_message.Message,), {
'DESCRIPTOR' : _APPLYDEPLOYMENTREQUEST,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.ApplyDeploymentRequest)
})
_sym_db.RegisterMessage(ApplyDeploymentRequest)
ApplyDeploymentResponse = _reflection.GeneratedProtocolMessageType('ApplyDeploymentResponse', (_message.Message,), {
'DESCRIPTOR' : _APPLYDEPLOYMENTRESPONSE,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.ApplyDeploymentResponse)
})
_sym_db.RegisterMessage(ApplyDeploymentResponse)
DeleteDeploymentRequest = _reflection.GeneratedProtocolMessageType('DeleteDeploymentRequest', (_message.Message,), {
'DESCRIPTOR' : _DELETEDEPLOYMENTREQUEST,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.DeleteDeploymentRequest)
})
_sym_db.RegisterMessage(DeleteDeploymentRequest)
DeleteDeploymentResponse = _reflection.GeneratedProtocolMessageType('DeleteDeploymentResponse', (_message.Message,), {
'DESCRIPTOR' : _DELETEDEPLOYMENTRESPONSE,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.DeleteDeploymentResponse)
})
_sym_db.RegisterMessage(DeleteDeploymentResponse)
GetDeploymentRequest = _reflection.GeneratedProtocolMessageType('GetDeploymentRequest', (_message.Message,), {
'DESCRIPTOR' : _GETDEPLOYMENTREQUEST,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.GetDeploymentRequest)
})
_sym_db.RegisterMessage(GetDeploymentRequest)
GetDeploymentResponse = _reflection.GeneratedProtocolMessageType('GetDeploymentResponse', (_message.Message,), {
'DESCRIPTOR' : _GETDEPLOYMENTRESPONSE,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.GetDeploymentResponse)
})
_sym_db.RegisterMessage(GetDeploymentResponse)
DescribeDeploymentRequest = _reflection.GeneratedProtocolMessageType('DescribeDeploymentRequest', (_message.Message,), {
'DESCRIPTOR' : _DESCRIBEDEPLOYMENTREQUEST,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.DescribeDeploymentRequest)
})
_sym_db.RegisterMessage(DescribeDeploymentRequest)
DescribeDeploymentResponse = _reflection.GeneratedProtocolMessageType('DescribeDeploymentResponse', (_message.Message,), {
'DESCRIPTOR' : _DESCRIBEDEPLOYMENTRESPONSE,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.DescribeDeploymentResponse)
})
_sym_db.RegisterMessage(DescribeDeploymentResponse)
ListDeploymentsRequest = _reflection.GeneratedProtocolMessageType('ListDeploymentsRequest', (_message.Message,), {
'DESCRIPTOR' : _LISTDEPLOYMENTSREQUEST,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.ListDeploymentsRequest)
})
_sym_db.RegisterMessage(ListDeploymentsRequest)
ListDeploymentsResponse = _reflection.GeneratedProtocolMessageType('ListDeploymentsResponse', (_message.Message,), {
'DESCRIPTOR' : _LISTDEPLOYMENTSRESPONSE,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.ListDeploymentsResponse)
})
_sym_db.RegisterMessage(ListDeploymentsResponse)
_DEPLOYMENT_ANNOTATIONSENTRY._options = None
_DEPLOYMENT_LABELSENTRY._options = None
# @@protoc_insertion_point(module_scope)
| 43.452952 | 4,030 | 0.770715 |
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
_sym_db = _symbol_database.Default()
from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2
from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2
import bentoml._internal.yatai_client.proto.status_pb2 as status__pb2
import bentoml._internal.yatai_client.proto.label_selectors_pb2 as label__selectors__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='deployment.proto',
package='bentoml',
syntax='proto3',
serialized_options=None,
create_key=_descriptor._internal_create_key,
serialized_pb=b'\n\x10\x64\x65ployment.proto\x12\x07\x62\x65ntoml\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x0cstatus.proto\x1a\x15label_selectors.proto\"\xe3\x02\n\x0e\x44\x65ploymentSpec\x12\x12\n\nbento_name\x18\x01 \x01(\t\x12\x15\n\rbento_version\x18\x02 \x01(\t\x12<\n\x08operator\x18\x03 \x01(\x0e\x32*.bentoml.DeploymentSpec.DeploymentOperator\x12N\n\x16\x63ustom_operator_config\x18\x04 \x01(\x0b\x32,.bentoml.DeploymentSpec.CustomOperatorConfigH\x00\x1aM\n\x14\x43ustomOperatorConfig\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\'\n\x06\x63onfig\x18\x02 \x01(\x0b\x32\x17.google.protobuf.Struct\"+\n\x12\x44\x65ploymentOperator\x12\t\n\x05UNSET\x10\x00\x12\n\n\x06\x43USTOM\x10\x01\x42\x1c\n\x1a\x64\x65ployment_operator_config\"\xa9\x02\n\x0f\x44\x65ploymentState\x12-\n\x05state\x18\x01 \x01(\x0e\x32\x1e.bentoml.DeploymentState.State\x12\x15\n\rerror_message\x18\x02 \x01(\t\x12\x11\n\tinfo_json\x18\x03 \x01(\t\x12-\n\ttimestamp\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"\x8d\x01\n\x05State\x12\x0b\n\x07PENDING\x10\x00\x12\x0b\n\x07RUNNING\x10\x01\x12\r\n\tSUCCEEDED\x10\x02\x12\n\n\x06\x46\x41ILED\x10\x03\x12\x0b\n\x07UNKNOWN\x10\x04\x12\r\n\tCOMPLETED\x10\x05\x12\x17\n\x13\x43RASH_LOOP_BACK_OFF\x10\x06\x12\t\n\x05\x45RROR\x10\x07\x12\x0f\n\x0bINACTIVATED\x10\x08\"\xb1\x03\n\nDeployment\x12\x11\n\tnamespace\x18\x01 \x01(\t\x12\x0c\n\x04name\x18\x02 \x01(\t\x12%\n\x04spec\x18\x03 \x01(\x0b\x32\x17.bentoml.DeploymentSpec\x12\'\n\x05state\x18\x04 \x01(\x0b\x32\x18.bentoml.DeploymentState\x12\x39\n\x0b\x61nnotations\x18\x05 \x03(\x0b\x32$.bentoml.Deployment.AnnotationsEntry\x12/\n\x06labels\x18\x06 \x03(\x0b\x32\x1f.bentoml.Deployment.LabelsEntry\x12.\n\ncreated_at\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x33\n\x0flast_updated_at\x18\x08 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x1a\x32\n\x10\x41nnotationsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\";\n\x10\x44\x65ploymentStatus\x12\'\n\x05state\x18\x01 \x01(\x0b\x32\x18.bentoml.DeploymentState\"A\n\x16\x41pplyDeploymentRequest\x12\'\n\ndeployment\x18\x01 \x01(\x0b\x32\x13.bentoml.Deployment\"c\n\x17\x41pplyDeploymentResponse\x12\x1f\n\x06status\x18\x01 \x01(\x0b\x32\x0f.bentoml.Status\x12\'\n\ndeployment\x18\x02 \x01(\x0b\x32\x13.bentoml.Deployment\"[\n\x17\x44\x65leteDeploymentRequest\x12\x17\n\x0f\x64\x65ployment_name\x18\x01 \x01(\t\x12\x11\n\tnamespace\x18\x02 \x01(\t\x12\x14\n\x0c\x66orce_delete\x18\x03 \x01(\x08\";\n\x18\x44\x65leteDeploymentResponse\x12\x1f\n\x06status\x18\x01 \x01(\x0b\x32\x0f.bentoml.Status\"B\n\x14GetDeploymentRequest\x12\x17\n\x0f\x64\x65ployment_name\x18\x01 \x01(\t\x12\x11\n\tnamespace\x18\x02 \x01(\t\"a\n\x15GetDeploymentResponse\x12\x1f\n\x06status\x18\x01 \x01(\x0b\x32\x0f.bentoml.Status\x12\'\n\ndeployment\x18\x02 \x01(\x0b\x32\x13.bentoml.Deployment\"G\n\x19\x44\x65scribeDeploymentRequest\x12\x17\n\x0f\x64\x65ployment_name\x18\x01 \x01(\t\x12\x11\n\tnamespace\x18\x02 \x01(\t\"f\n\x1a\x44\x65scribeDeploymentResponse\x12\x1f\n\x06status\x18\x01 \x01(\x0b\x32\x0f.bentoml.Status\x12\'\n\x05state\x18\x02 \x01(\x0b\x32\x18.bentoml.DeploymentState\"\xd9\x02\n\x16ListDeploymentsRequest\x12\x11\n\tnamespace\x18\x01 \x01(\t\x12\x0e\n\x06offset\x18\x02 \x01(\x05\x12\r\n\x05limit\x18\x03 \x01(\x05\x12<\n\x08operator\x18\x04 \x01(\x0e\x32*.bentoml.DeploymentSpec.DeploymentOperator\x12\x41\n\x08order_by\x18\x05 \x01(\x0e\x32/.bentoml.ListDeploymentsRequest.SORTABLE_COLUMN\x12\x17\n\x0f\x61scending_order\x18\x06 \x01(\x08\x12\x14\n\x0clabels_query\x18\x07 \x01(\t\x12\x30\n\x0flabel_selectors\x18\x08 \x01(\x0b\x32\x17.bentoml.LabelSelectors\"+\n\x0fSORTABLE_COLUMN\x12\x0e\n\ncreated_at\x10\x00\x12\x08\n\x04name\x10\x01\"d\n\x17ListDeploymentsResponse\x12\x1f\n\x06status\x18\x01 \x01(\x0b\x32\x0f.bentoml.Status\x12(\n\x0b\x64\x65ployments\x18\x02 \x03(\x0b\x32\x13.bentoml.Deploymentb\x06proto3'
,
dependencies=[google_dot_protobuf_dot_struct__pb2.DESCRIPTOR,google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR,status__pb2.DESCRIPTOR,label__selectors__pb2.DESCRIPTOR,])
_DEPLOYMENTSPEC_DEPLOYMENTOPERATOR = _descriptor.EnumDescriptor(
name='DeploymentOperator',
full_name='bentoml.DeploymentSpec.DeploymentOperator',
filename=None,
file=DESCRIPTOR,
create_key=_descriptor._internal_create_key,
values=[
_descriptor.EnumValueDescriptor(
name='UNSET', index=0, number=0,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='CUSTOM', index=1, number=1,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
],
containing_type=None,
serialized_options=None,
serialized_start=412,
serialized_end=455,
)
_sym_db.RegisterEnumDescriptor(_DEPLOYMENTSPEC_DEPLOYMENTOPERATOR)
_DEPLOYMENTSTATE_STATE = _descriptor.EnumDescriptor(
name='State',
full_name='bentoml.DeploymentState.State',
filename=None,
file=DESCRIPTOR,
create_key=_descriptor._internal_create_key,
values=[
_descriptor.EnumValueDescriptor(
name='PENDING', index=0, number=0,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='RUNNING', index=1, number=1,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='SUCCEEDED', index=2, number=2,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='FAILED', index=3, number=3,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='UNKNOWN', index=4, number=4,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='COMPLETED', index=5, number=5,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='CRASH_LOOP_BACK_OFF', index=6, number=6,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='ERROR', index=7, number=7,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='INACTIVATED', index=8, number=8,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
],
containing_type=None,
serialized_options=None,
serialized_start=644,
serialized_end=785,
)
_sym_db.RegisterEnumDescriptor(_DEPLOYMENTSTATE_STATE)
_LISTDEPLOYMENTSREQUEST_SORTABLE_COLUMN = _descriptor.EnumDescriptor(
name='SORTABLE_COLUMN',
full_name='bentoml.ListDeploymentsRequest.SORTABLE_COLUMN',
filename=None,
file=DESCRIPTOR,
create_key=_descriptor._internal_create_key,
values=[
_descriptor.EnumValueDescriptor(
name='created_at', index=0, number=0,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='name', index=1, number=1,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
],
containing_type=None,
serialized_options=None,
serialized_start=2253,
serialized_end=2296,
)
_sym_db.RegisterEnumDescriptor(_LISTDEPLOYMENTSREQUEST_SORTABLE_COLUMN)
_DEPLOYMENTSPEC_CUSTOMOPERATORCONFIG = _descriptor.Descriptor(
name='CustomOperatorConfig',
full_name='bentoml.DeploymentSpec.CustomOperatorConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='name', full_name='bentoml.DeploymentSpec.CustomOperatorConfig.name', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='config', full_name='bentoml.DeploymentSpec.CustomOperatorConfig.config', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=333,
serialized_end=410,
)
_DEPLOYMENTSPEC = _descriptor.Descriptor(
name='DeploymentSpec',
full_name='bentoml.DeploymentSpec',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='bento_name', full_name='bentoml.DeploymentSpec.bento_name', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='bento_version', full_name='bentoml.DeploymentSpec.bento_version', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='operator', full_name='bentoml.DeploymentSpec.operator', index=2,
number=3, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='custom_operator_config', full_name='bentoml.DeploymentSpec.custom_operator_config', index=3,
number=4, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[_DEPLOYMENTSPEC_CUSTOMOPERATORCONFIG, ],
enum_types=[
_DEPLOYMENTSPEC_DEPLOYMENTOPERATOR,
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
_descriptor.OneofDescriptor(
name='deployment_operator_config', full_name='bentoml.DeploymentSpec.deployment_operator_config',
index=0, containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[]),
],
serialized_start=130,
serialized_end=485,
)
_DEPLOYMENTSTATE = _descriptor.Descriptor(
name='DeploymentState',
full_name='bentoml.DeploymentState',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='state', full_name='bentoml.DeploymentState.state', index=0,
number=1, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='error_message', full_name='bentoml.DeploymentState.error_message', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='info_json', full_name='bentoml.DeploymentState.info_json', index=2,
number=3, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='timestamp', full_name='bentoml.DeploymentState.timestamp', index=3,
number=4, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
_DEPLOYMENTSTATE_STATE,
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=488,
serialized_end=785,
)
_DEPLOYMENT_ANNOTATIONSENTRY = _descriptor.Descriptor(
name='AnnotationsEntry',
full_name='bentoml.Deployment.AnnotationsEntry',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='key', full_name='bentoml.Deployment.AnnotationsEntry.key', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='value', full_name='bentoml.Deployment.AnnotationsEntry.value', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=b'8\001',
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=1124,
serialized_end=1174,
)
_DEPLOYMENT_LABELSENTRY = _descriptor.Descriptor(
name='LabelsEntry',
full_name='bentoml.Deployment.LabelsEntry',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='key', full_name='bentoml.Deployment.LabelsEntry.key', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='value', full_name='bentoml.Deployment.LabelsEntry.value', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=b'8\001',
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=1176,
serialized_end=1221,
)
_DEPLOYMENT = _descriptor.Descriptor(
name='Deployment',
full_name='bentoml.Deployment',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='namespace', full_name='bentoml.Deployment.namespace', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='name', full_name='bentoml.Deployment.name', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='spec', full_name='bentoml.Deployment.spec', index=2,
number=3, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='state', full_name='bentoml.Deployment.state', index=3,
number=4, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='annotations', full_name='bentoml.Deployment.annotations', index=4,
number=5, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='labels', full_name='bentoml.Deployment.labels', index=5,
number=6, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='created_at', full_name='bentoml.Deployment.created_at', index=6,
number=7, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='last_updated_at', full_name='bentoml.Deployment.last_updated_at', index=7,
number=8, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[_DEPLOYMENT_ANNOTATIONSENTRY, _DEPLOYMENT_LABELSENTRY, ],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=788,
serialized_end=1221,
)
_DEPLOYMENTSTATUS = _descriptor.Descriptor(
name='DeploymentStatus',
full_name='bentoml.DeploymentStatus',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='state', full_name='bentoml.DeploymentStatus.state', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=1223,
serialized_end=1282,
)
_APPLYDEPLOYMENTREQUEST = _descriptor.Descriptor(
name='ApplyDeploymentRequest',
full_name='bentoml.ApplyDeploymentRequest',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='deployment', full_name='bentoml.ApplyDeploymentRequest.deployment', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=1284,
serialized_end=1349,
)
_APPLYDEPLOYMENTRESPONSE = _descriptor.Descriptor(
name='ApplyDeploymentResponse',
full_name='bentoml.ApplyDeploymentResponse',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='status', full_name='bentoml.ApplyDeploymentResponse.status', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='deployment', full_name='bentoml.ApplyDeploymentResponse.deployment', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=1351,
serialized_end=1450,
)
_DELETEDEPLOYMENTREQUEST = _descriptor.Descriptor(
name='DeleteDeploymentRequest',
full_name='bentoml.DeleteDeploymentRequest',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='deployment_name', full_name='bentoml.DeleteDeploymentRequest.deployment_name', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='namespace', full_name='bentoml.DeleteDeploymentRequest.namespace', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='force_delete', full_name='bentoml.DeleteDeploymentRequest.force_delete', index=2,
number=3, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=1452,
serialized_end=1543,
)
_DELETEDEPLOYMENTRESPONSE = _descriptor.Descriptor(
name='DeleteDeploymentResponse',
full_name='bentoml.DeleteDeploymentResponse',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='status', full_name='bentoml.DeleteDeploymentResponse.status', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=1545,
serialized_end=1604,
)
_GETDEPLOYMENTREQUEST = _descriptor.Descriptor(
name='GetDeploymentRequest',
full_name='bentoml.GetDeploymentRequest',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='deployment_name', full_name='bentoml.GetDeploymentRequest.deployment_name', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='namespace', full_name='bentoml.GetDeploymentRequest.namespace', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=1606,
serialized_end=1672,
)
_GETDEPLOYMENTRESPONSE = _descriptor.Descriptor(
name='GetDeploymentResponse',
full_name='bentoml.GetDeploymentResponse',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='status', full_name='bentoml.GetDeploymentResponse.status', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='deployment', full_name='bentoml.GetDeploymentResponse.deployment', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=1674,
serialized_end=1771,
)
_DESCRIBEDEPLOYMENTREQUEST = _descriptor.Descriptor(
name='DescribeDeploymentRequest',
full_name='bentoml.DescribeDeploymentRequest',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='deployment_name', full_name='bentoml.DescribeDeploymentRequest.deployment_name', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='namespace', full_name='bentoml.DescribeDeploymentRequest.namespace', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=1773,
serialized_end=1844,
)
_DESCRIBEDEPLOYMENTRESPONSE = _descriptor.Descriptor(
name='DescribeDeploymentResponse',
full_name='bentoml.DescribeDeploymentResponse',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='status', full_name='bentoml.DescribeDeploymentResponse.status', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='state', full_name='bentoml.DescribeDeploymentResponse.state', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=1846,
serialized_end=1948,
)
_LISTDEPLOYMENTSREQUEST = _descriptor.Descriptor(
name='ListDeploymentsRequest',
full_name='bentoml.ListDeploymentsRequest',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='namespace', full_name='bentoml.ListDeploymentsRequest.namespace', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='offset', full_name='bentoml.ListDeploymentsRequest.offset', index=1,
number=2, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='limit', full_name='bentoml.ListDeploymentsRequest.limit', index=2,
number=3, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='operator', full_name='bentoml.ListDeploymentsRequest.operator', index=3,
number=4, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='order_by', full_name='bentoml.ListDeploymentsRequest.order_by', index=4,
number=5, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='ascending_order', full_name='bentoml.ListDeploymentsRequest.ascending_order', index=5,
number=6, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='labels_query', full_name='bentoml.ListDeploymentsRequest.labels_query', index=6,
number=7, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='label_selectors', full_name='bentoml.ListDeploymentsRequest.label_selectors', index=7,
number=8, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
_LISTDEPLOYMENTSREQUEST_SORTABLE_COLUMN,
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=1951,
serialized_end=2296,
)
_LISTDEPLOYMENTSRESPONSE = _descriptor.Descriptor(
name='ListDeploymentsResponse',
full_name='bentoml.ListDeploymentsResponse',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='status', full_name='bentoml.ListDeploymentsResponse.status', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='deployments', full_name='bentoml.ListDeploymentsResponse.deployments', index=1,
number=2, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=2298,
serialized_end=2398,
)
_DEPLOYMENTSPEC_CUSTOMOPERATORCONFIG.fields_by_name['config'].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT
_DEPLOYMENTSPEC_CUSTOMOPERATORCONFIG.containing_type = _DEPLOYMENTSPEC
_DEPLOYMENTSPEC.fields_by_name['operator'].enum_type = _DEPLOYMENTSPEC_DEPLOYMENTOPERATOR
_DEPLOYMENTSPEC.fields_by_name['custom_operator_config'].message_type = _DEPLOYMENTSPEC_CUSTOMOPERATORCONFIG
_DEPLOYMENTSPEC_DEPLOYMENTOPERATOR.containing_type = _DEPLOYMENTSPEC
_DEPLOYMENTSPEC.oneofs_by_name['deployment_operator_config'].fields.append(
_DEPLOYMENTSPEC.fields_by_name['custom_operator_config'])
_DEPLOYMENTSPEC.fields_by_name['custom_operator_config'].containing_oneof = _DEPLOYMENTSPEC.oneofs_by_name['deployment_operator_config']
_DEPLOYMENTSTATE.fields_by_name['state'].enum_type = _DEPLOYMENTSTATE_STATE
_DEPLOYMENTSTATE.fields_by_name['timestamp'].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP
_DEPLOYMENTSTATE_STATE.containing_type = _DEPLOYMENTSTATE
_DEPLOYMENT_ANNOTATIONSENTRY.containing_type = _DEPLOYMENT
_DEPLOYMENT_LABELSENTRY.containing_type = _DEPLOYMENT
_DEPLOYMENT.fields_by_name['spec'].message_type = _DEPLOYMENTSPEC
_DEPLOYMENT.fields_by_name['state'].message_type = _DEPLOYMENTSTATE
_DEPLOYMENT.fields_by_name['annotations'].message_type = _DEPLOYMENT_ANNOTATIONSENTRY
_DEPLOYMENT.fields_by_name['labels'].message_type = _DEPLOYMENT_LABELSENTRY
_DEPLOYMENT.fields_by_name['created_at'].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP
_DEPLOYMENT.fields_by_name['last_updated_at'].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP
_DEPLOYMENTSTATUS.fields_by_name['state'].message_type = _DEPLOYMENTSTATE
_APPLYDEPLOYMENTREQUEST.fields_by_name['deployment'].message_type = _DEPLOYMENT
_APPLYDEPLOYMENTRESPONSE.fields_by_name['status'].message_type = status__pb2._STATUS
_APPLYDEPLOYMENTRESPONSE.fields_by_name['deployment'].message_type = _DEPLOYMENT
_DELETEDEPLOYMENTRESPONSE.fields_by_name['status'].message_type = status__pb2._STATUS
_GETDEPLOYMENTRESPONSE.fields_by_name['status'].message_type = status__pb2._STATUS
_GETDEPLOYMENTRESPONSE.fields_by_name['deployment'].message_type = _DEPLOYMENT
_DESCRIBEDEPLOYMENTRESPONSE.fields_by_name['status'].message_type = status__pb2._STATUS
_DESCRIBEDEPLOYMENTRESPONSE.fields_by_name['state'].message_type = _DEPLOYMENTSTATE
_LISTDEPLOYMENTSREQUEST.fields_by_name['operator'].enum_type = _DEPLOYMENTSPEC_DEPLOYMENTOPERATOR
_LISTDEPLOYMENTSREQUEST.fields_by_name['order_by'].enum_type = _LISTDEPLOYMENTSREQUEST_SORTABLE_COLUMN
_LISTDEPLOYMENTSREQUEST.fields_by_name['label_selectors'].message_type = label__selectors__pb2._LABELSELECTORS
_LISTDEPLOYMENTSREQUEST_SORTABLE_COLUMN.containing_type = _LISTDEPLOYMENTSREQUEST
_LISTDEPLOYMENTSRESPONSE.fields_by_name['status'].message_type = status__pb2._STATUS
_LISTDEPLOYMENTSRESPONSE.fields_by_name['deployments'].message_type = _DEPLOYMENT
DESCRIPTOR.message_types_by_name['DeploymentSpec'] = _DEPLOYMENTSPEC
DESCRIPTOR.message_types_by_name['DeploymentState'] = _DEPLOYMENTSTATE
DESCRIPTOR.message_types_by_name['Deployment'] = _DEPLOYMENT
DESCRIPTOR.message_types_by_name['DeploymentStatus'] = _DEPLOYMENTSTATUS
DESCRIPTOR.message_types_by_name['ApplyDeploymentRequest'] = _APPLYDEPLOYMENTREQUEST
DESCRIPTOR.message_types_by_name['ApplyDeploymentResponse'] = _APPLYDEPLOYMENTRESPONSE
DESCRIPTOR.message_types_by_name['DeleteDeploymentRequest'] = _DELETEDEPLOYMENTREQUEST
DESCRIPTOR.message_types_by_name['DeleteDeploymentResponse'] = _DELETEDEPLOYMENTRESPONSE
DESCRIPTOR.message_types_by_name['GetDeploymentRequest'] = _GETDEPLOYMENTREQUEST
DESCRIPTOR.message_types_by_name['GetDeploymentResponse'] = _GETDEPLOYMENTRESPONSE
DESCRIPTOR.message_types_by_name['DescribeDeploymentRequest'] = _DESCRIBEDEPLOYMENTREQUEST
DESCRIPTOR.message_types_by_name['DescribeDeploymentResponse'] = _DESCRIBEDEPLOYMENTRESPONSE
DESCRIPTOR.message_types_by_name['ListDeploymentsRequest'] = _LISTDEPLOYMENTSREQUEST
DESCRIPTOR.message_types_by_name['ListDeploymentsResponse'] = _LISTDEPLOYMENTSRESPONSE
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
DeploymentSpec = _reflection.GeneratedProtocolMessageType('DeploymentSpec', (_message.Message,), {
'CustomOperatorConfig' : _reflection.GeneratedProtocolMessageType('CustomOperatorConfig', (_message.Message,), {
'DESCRIPTOR' : _DEPLOYMENTSPEC_CUSTOMOPERATORCONFIG,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.DeploymentSpec.CustomOperatorConfig)
})
,
'DESCRIPTOR' : _DEPLOYMENTSPEC,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.DeploymentSpec)
})
_sym_db.RegisterMessage(DeploymentSpec)
_sym_db.RegisterMessage(DeploymentSpec.CustomOperatorConfig)
DeploymentState = _reflection.GeneratedProtocolMessageType('DeploymentState', (_message.Message,), {
'DESCRIPTOR' : _DEPLOYMENTSTATE,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.DeploymentState)
})
_sym_db.RegisterMessage(DeploymentState)
Deployment = _reflection.GeneratedProtocolMessageType('Deployment', (_message.Message,), {
'AnnotationsEntry' : _reflection.GeneratedProtocolMessageType('AnnotationsEntry', (_message.Message,), {
'DESCRIPTOR' : _DEPLOYMENT_ANNOTATIONSENTRY,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.Deployment.AnnotationsEntry)
})
,
'LabelsEntry' : _reflection.GeneratedProtocolMessageType('LabelsEntry', (_message.Message,), {
'DESCRIPTOR' : _DEPLOYMENT_LABELSENTRY,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.Deployment.LabelsEntry)
})
,
'DESCRIPTOR' : _DEPLOYMENT,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.Deployment)
})
_sym_db.RegisterMessage(Deployment)
_sym_db.RegisterMessage(Deployment.AnnotationsEntry)
_sym_db.RegisterMessage(Deployment.LabelsEntry)
DeploymentStatus = _reflection.GeneratedProtocolMessageType('DeploymentStatus', (_message.Message,), {
'DESCRIPTOR' : _DEPLOYMENTSTATUS,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.DeploymentStatus)
})
_sym_db.RegisterMessage(DeploymentStatus)
ApplyDeploymentRequest = _reflection.GeneratedProtocolMessageType('ApplyDeploymentRequest', (_message.Message,), {
'DESCRIPTOR' : _APPLYDEPLOYMENTREQUEST,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.ApplyDeploymentRequest)
})
_sym_db.RegisterMessage(ApplyDeploymentRequest)
ApplyDeploymentResponse = _reflection.GeneratedProtocolMessageType('ApplyDeploymentResponse', (_message.Message,), {
'DESCRIPTOR' : _APPLYDEPLOYMENTRESPONSE,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.ApplyDeploymentResponse)
})
_sym_db.RegisterMessage(ApplyDeploymentResponse)
DeleteDeploymentRequest = _reflection.GeneratedProtocolMessageType('DeleteDeploymentRequest', (_message.Message,), {
'DESCRIPTOR' : _DELETEDEPLOYMENTREQUEST,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.DeleteDeploymentRequest)
})
_sym_db.RegisterMessage(DeleteDeploymentRequest)
DeleteDeploymentResponse = _reflection.GeneratedProtocolMessageType('DeleteDeploymentResponse', (_message.Message,), {
'DESCRIPTOR' : _DELETEDEPLOYMENTRESPONSE,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.DeleteDeploymentResponse)
})
_sym_db.RegisterMessage(DeleteDeploymentResponse)
GetDeploymentRequest = _reflection.GeneratedProtocolMessageType('GetDeploymentRequest', (_message.Message,), {
'DESCRIPTOR' : _GETDEPLOYMENTREQUEST,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.GetDeploymentRequest)
})
_sym_db.RegisterMessage(GetDeploymentRequest)
GetDeploymentResponse = _reflection.GeneratedProtocolMessageType('GetDeploymentResponse', (_message.Message,), {
'DESCRIPTOR' : _GETDEPLOYMENTRESPONSE,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.GetDeploymentResponse)
})
_sym_db.RegisterMessage(GetDeploymentResponse)
DescribeDeploymentRequest = _reflection.GeneratedProtocolMessageType('DescribeDeploymentRequest', (_message.Message,), {
'DESCRIPTOR' : _DESCRIBEDEPLOYMENTREQUEST,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.DescribeDeploymentRequest)
})
_sym_db.RegisterMessage(DescribeDeploymentRequest)
DescribeDeploymentResponse = _reflection.GeneratedProtocolMessageType('DescribeDeploymentResponse', (_message.Message,), {
'DESCRIPTOR' : _DESCRIBEDEPLOYMENTRESPONSE,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.DescribeDeploymentResponse)
})
_sym_db.RegisterMessage(DescribeDeploymentResponse)
ListDeploymentsRequest = _reflection.GeneratedProtocolMessageType('ListDeploymentsRequest', (_message.Message,), {
'DESCRIPTOR' : _LISTDEPLOYMENTSREQUEST,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.ListDeploymentsRequest)
})
_sym_db.RegisterMessage(ListDeploymentsRequest)
ListDeploymentsResponse = _reflection.GeneratedProtocolMessageType('ListDeploymentsResponse', (_message.Message,), {
'DESCRIPTOR' : _LISTDEPLOYMENTSRESPONSE,
'__module__' : 'deployment_pb2'
# @@protoc_insertion_point(class_scope:bentoml.ListDeploymentsResponse)
})
_sym_db.RegisterMessage(ListDeploymentsResponse)
_DEPLOYMENT_ANNOTATIONSENTRY._options = None
_DEPLOYMENT_LABELSENTRY._options = None
# @@protoc_insertion_point(module_scope)
| true | true |
f7f95ef5199af6ab40f535296b13b96fc365a5da | 1,498 | py | Python | ceilometer/cmd/storage.py | vmturbo/ceilometer | f856d3c915b738a64bce14967ba8114fe923c1af | [
"Apache-2.0"
] | null | null | null | ceilometer/cmd/storage.py | vmturbo/ceilometer | f856d3c915b738a64bce14967ba8114fe923c1af | [
"Apache-2.0"
] | null | null | null | ceilometer/cmd/storage.py | vmturbo/ceilometer | f856d3c915b738a64bce14967ba8114fe923c1af | [
"Apache-2.0"
] | 1 | 2019-09-16T02:11:41.000Z | 2019-09-16T02:11:41.000Z | # -*- encoding: utf-8 -*-
#
# Copyright 2014 OpenStack Foundation
#
# 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 logging
from oslo.config import cfg
from ceilometer import service
from ceilometer import storage
cfg.CONF.import_opt('time_to_live', 'ceilometer.storage',
group='database')
LOG = logging.getLogger(__name__)
def dbsync():
service.prepare_service()
storage.get_connection_from_config(cfg.CONF, 'metering').upgrade()
storage.get_connection_from_config(cfg.CONF, 'alarm').upgrade()
storage.get_connection_from_config(cfg.CONF, 'event').upgrade()
def expirer():
service.prepare_service()
if cfg.CONF.database.time_to_live > 0:
LOG.debug(_("Clearing expired metering data"))
storage_conn = storage.get_connection_from_config(cfg.CONF)
storage_conn.clear_expired_metering_data(
cfg.CONF.database.time_to_live)
else:
LOG.info(_("Nothing to clean, database time to live is disabled"))
| 32.565217 | 75 | 0.731642 |
import logging
from oslo.config import cfg
from ceilometer import service
from ceilometer import storage
cfg.CONF.import_opt('time_to_live', 'ceilometer.storage',
group='database')
LOG = logging.getLogger(__name__)
def dbsync():
service.prepare_service()
storage.get_connection_from_config(cfg.CONF, 'metering').upgrade()
storage.get_connection_from_config(cfg.CONF, 'alarm').upgrade()
storage.get_connection_from_config(cfg.CONF, 'event').upgrade()
def expirer():
service.prepare_service()
if cfg.CONF.database.time_to_live > 0:
LOG.debug(_("Clearing expired metering data"))
storage_conn = storage.get_connection_from_config(cfg.CONF)
storage_conn.clear_expired_metering_data(
cfg.CONF.database.time_to_live)
else:
LOG.info(_("Nothing to clean, database time to live is disabled"))
| true | true |
f7f95efe4638a4b6abd0ebed0b02dd838996c6ef | 542 | py | Python | packages/python/plotly/plotly/validators/pie/_insidetextorientation.py | mastermind88/plotly.py | efa70710df1af22958e1be080e105130042f1839 | [
"MIT"
] | null | null | null | packages/python/plotly/plotly/validators/pie/_insidetextorientation.py | mastermind88/plotly.py | efa70710df1af22958e1be080e105130042f1839 | [
"MIT"
] | null | null | null | packages/python/plotly/plotly/validators/pie/_insidetextorientation.py | mastermind88/plotly.py | efa70710df1af22958e1be080e105130042f1839 | [
"MIT"
] | null | null | null | import _plotly_utils.basevalidators
class InsidetextorientationValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(
self, plotly_name="insidetextorientation", parent_name="pie", **kwargs
):
super(InsidetextorientationValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "plot"),
values=kwargs.pop("values", ["horizontal", "radial", "tangential", "auto"]),
**kwargs,
)
| 36.133333 | 88 | 0.664207 | import _plotly_utils.basevalidators
class InsidetextorientationValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(
self, plotly_name="insidetextorientation", parent_name="pie", **kwargs
):
super(InsidetextorientationValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "plot"),
values=kwargs.pop("values", ["horizontal", "radial", "tangential", "auto"]),
**kwargs,
)
| true | true |
f7f95f5962303bd2f2a3a4349c065d7e7f872a13 | 856 | py | Python | Packs/Ransomware/Scripts/RansomwareHostWidget/RansomwareHostWidget.py | diCagri/content | c532c50b213e6dddb8ae6a378d6d09198e08fc9f | [
"MIT"
] | 799 | 2016-08-02T06:43:14.000Z | 2022-03-31T11:10:11.000Z | Packs/Ransomware/Scripts/RansomwareHostWidget/RansomwareHostWidget.py | diCagri/content | c532c50b213e6dddb8ae6a378d6d09198e08fc9f | [
"MIT"
] | 9,317 | 2016-08-07T19:00:51.000Z | 2022-03-31T21:56:04.000Z | Packs/Ransomware/Scripts/RansomwareHostWidget/RansomwareHostWidget.py | diCagri/content | c532c50b213e6dddb8ae6a378d6d09198e08fc9f | [
"MIT"
] | 1,297 | 2016-08-04T13:59:00.000Z | 2022-03-31T23:43:06.000Z | import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
incident = demisto.incidents()
data = {
"Type": 17,
"ContentsFormat": "number",
"Contents": {
"stats": int(incident[0].get('CustomFields', {}).get('ransomwareapproximatenumberofencryptedendpoints', 0)),
"params": {
"layout": "horizontal",
"name": "Hosts Count",
"sign": "",
"colors": {
"items": {
"#32CD32": {
"value": -1
},
"#FF9000": {
"value": 0
},
"#EE4443": {
"value": 3
}
}
},
"type": "above"
}
}
}
demisto.results(data)
| 25.939394 | 116 | 0.384346 | import demistomock as demisto
from CommonServerPython import *
incident = demisto.incidents()
data = {
"Type": 17,
"ContentsFormat": "number",
"Contents": {
"stats": int(incident[0].get('CustomFields', {}).get('ransomwareapproximatenumberofencryptedendpoints', 0)),
"params": {
"layout": "horizontal",
"name": "Hosts Count",
"sign": "",
"colors": {
"items": {
"#32CD32": {
"value": -1
},
"#FF9000": {
"value": 0
},
"#EE4443": {
"value": 3
}
}
},
"type": "above"
}
}
}
demisto.results(data)
| true | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.