filename
stringlengths 13
19
| text
stringlengths 134
1.04M
|
---|---|
the-stack_0_14659 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from functools import partial
import itertools
import logging
import os
import re
import threading
import time
from typing import Callable, Optional, Sequence
from unittest import skip, SkipTest
from absl.testing import absltest
from absl.testing import parameterized
import jax
from jax import core
from jax._src import api
from jax.config import config
from jax import dtypes
from jax.experimental import host_callback as hcb
from jax.experimental import PartitionSpec as P
from jax.experimental import maps
from jax.experimental import pjit
from jax import lax
from jax import numpy as jnp
from jax import test_util as jtu
from jax import tree_util
from jax.lib import xla_bridge
import numpy as np
config.parse_flags_with_absl()
FLAGS = config.FLAGS
class _TestingOutputStream(object):
"""Use as `output_stream` for tests."""
def __init__(self):
self._output = []
self._test_method_name = None
def write(self, what: str) -> None:
print(f"output_stream[{self._test_method_name}]: {what}", end="")
self._output.append(what)
@property
def output(self):
return "".join(self._output)
@property
def output_sorted_by_device(self):
# Assume that the output is a sequence of strings including metadata
# and data, with metadata containing `device: xxx`
by_device = [] # each element is a pair (device, str_list)
for s in self._output:
m = re.match(r".*device: (\S+)", s)
if m:
by_device.append((m.group(1), []))
assert by_device, f"output does not include 'device:': {self._output}"
by_device[-1][1].append(s)
sorted_by_device = sorted(by_device, key=lambda x: x[0])
return "\n".join(itertools.chain(*[s[1] for s in sorted_by_device]))
def __str__(self):
return "TestingOutputStream"
def reset(self):
self._output = []
testing_stream = _TestingOutputStream()
def fun1(a):
"""Function used for several `id_tap` tests."""
y = hcb.id_print(a * 2., what="a * 2", output_stream=testing_stream)
y = hcb.id_print(y * 3., what="y * 3", output_stream=testing_stream, result=y)
return y ** 2 # Some computation to make the gradient interesting
def fun1_equiv(a): # Numerical equivalent of fun1
return (a * 2.) ** 2
def maybe_print(do_print: bool, arg, what: str, tap_with_device: Optional[bool] = False):
"""Conditionally print on testing_string"""
if do_print:
return hcb.id_print(arg, what=what,
output_stream=testing_stream, tap_with_device=tap_with_device)
else:
return arg
def local_devices():
# Tests require using not more than 2 devices.
return api.local_devices()[:2]
ignore_jit_of_pmap_warning = partial(
jtu.ignore_warning, message=".*jit-of-pmap.*")
def assertMultiLineStrippedEqual(tst: jtu.JaxTestCase,
expected: str, what: str):
"""A variant that preprocesses the string to eliminate non-determinism in
floating point values, and several uninteresting id_tap primitive params.
"""
# Sometimes we get floating points in the output; we round them
def repl_floats(match_group):
matched = match_group.group(0)
if matched == ".": return matched
x = np.around(float(matched), decimals=2)
return f"{x:.2f}"
what = re.sub(r"\-?\d*\.[\-\def]*", repl_floats, what)
what = re.sub(r"output_stream=[^\]\n,]*,?", "", what)
what = re.sub(r"threshold=[^\]\n,]*,?", "", what)
what = re.sub(r"bwd=[^\]\n]*", "", what)
what = re.sub(r"out_trees=[^\]\n]*", "", what)
what = re.sub(r"fwd_jaxpr_thunk=[^\]\n]*", "", what)
what = re.sub(r"jvp_jaxpr_thunk=[^\]\n]*", "", what)
# Empty lines
what = re.sub(r"^\s*\n", "", what, flags=re.MULTILINE)
def repl_func(match_group):
matched = match_group.group(3)
if "function _print_consumer" in matched:
return match_group.group(1) + "=_print"
else:
return match_group.group(1) + "=..."
what = re.sub(r"((tap_func_)|(callback))=([^\]\n,]*),?", repl_func, what)
tst.assertMultiLineStrippedEqual(expected, what)
def helper_set_hlo_dump():
flags_str = os.getenv("XLA_FLAGS", "")
import shutil
dump_dir = "/tmp/xla_dump"
os.environ["XLA_FLAGS"] = f"{flags_str} --xla_dump_to={dump_dir}"
if os.path.isdir(dump_dir):
logging.warning(f"Deleting old XLA dump directory {dump_dir}")
shutil.rmtree(dump_dir)
logging.warning(f"Setting XLA dump directory {dump_dir}")
# Clear any cached backends so new CPU backend will pick up the env var.
xla_bridge.get_backend.cache_clear()
def helper_print_optimized_hlo(fun, *args):
backend = api.lib.xla_bridge.get_backend()
c = api.xla_computation(fun)(*args)
print(re.sub(r", metadata.*", "",
backend.compile(c).hlo_modules()[0].to_string()))
def helper_log_ir(name,
f_jax,
*args,
num_partitions=None,
strip_metadata=False):
print(f"Jaxpr[{name}]: {jax.make_jaxpr(f_jax)(*args)}")
jax_comp = jax.xla_computation(f_jax)(*args)
print(f"HLO[{name}]: {jax_comp.as_hlo_text()}")
backend = jax.lib.xla_bridge.get_backend()
if num_partitions is not None:
num_replicas = 1
device_assignment = np.arange(num_partitions * num_replicas)
device_assignment = np.reshape(device_assignment, (-1, num_partitions))
use_spmd_partitioning = num_partitions > 1
compile_options = jax.lib.xla_bridge.get_compile_options(
num_replicas=num_replicas,
num_partitions=num_partitions,
device_assignment=device_assignment,
use_spmd_partitioning=use_spmd_partitioning,
)
else:
compile_options = None
jax_optimized_hlo = backend.compile(
jax_comp, compile_options).hlo_modules()[0].to_string()
if strip_metadata:
jax_optimized_hlo = re.sub(r", metadata.*", "", jax_optimized_hlo)
print(f"Optimized HLO[{name}] for "
f"platform {backend.platform}: {jax_optimized_hlo}")
prev_xla_flags = None
def setUpModule():
global prev_xla_flags
# This will control the CPU devices. On TPU we always have 2 devices
prev_xla_flags = jtu.set_host_platform_device_count(2)
# Reset to previous configuration in case other test modules will be run.
def tearDownModule():
prev_xla_flags()
def assertMultiDeviceOutputEqual(tst: jtu.JaxTestCase,
expected_2CPUs: str):
"""Check that the multi-device output is equal to the expected.
The tests run with 2 devices if available, otherwise 1 device.
We adjust the expected output here for 1 device.
Args:
expected_2CPUs: the expected output for 2 CPUs. If there is only
one device, this is trimmed to the first device. If the current
device_under_test is not a CPU, then we change the names
"""
expected = expected_2CPUs
if len(local_devices()) == 1:
start_device_1 = expected.find('device: cpu:1')
if start_device_1 >= 0:
expected = expected[0:start_device_1]
def replace_device_name(m) -> str:
return str(local_devices()[int(m.group(1))])
expected = re.sub(r'cpu:(\d+)', replace_device_name, expected)
what = testing_stream.output_sorted_by_device
return assertMultiLineStrippedEqual(tst, expected, what)
class HostCallbackTapTest(jtu.JaxTestCase):
def setUp(self):
super().setUp()
if jtu.device_under_test() == "gpu" and jax.device_count() > 1:
raise SkipTest("host_callback broken on multi-GPU platforms (#6447)")
testing_stream.reset()
testing_stream._test_method_name = self._testMethodName
self.old_flags = os.getenv("XLA_FLAGS", "")
def tearDown(self) -> None:
if os.getenv("XLA_FLAGS") != self.old_flags:
os.environ["XLA_FLAGS"] = self.old_flags
xla_bridge.get_backend.cache_clear()
hcb.barrier_wait("HostCallbackTapTest.tearDown")
super().tearDown()
def test_tap_eval(self):
self.assertAllClose((5. * 2.) ** 2, fun1(5.))
hcb.barrier_wait()
assertMultiLineStrippedEqual(self, """
what: a * 2
10.00
what: y * 3
30.00""", testing_stream.output)
def test_tap_with_tuple_results(self):
def func2(x):
x1, y1 = hcb.id_print((x * 2., x * 3.), output_stream=testing_stream)
return x1 + y1
self.assertEqual(3. * (2. + 3.), func2(3.))
hcb.barrier_wait()
assertMultiLineStrippedEqual(self, """
( 6.00
9.00 )""", testing_stream.output)
def test_tap_with_dict_results(self):
def func2(x):
res = hcb.id_print(dict(a=x * 2., b=x * 3.), output_stream=testing_stream)
return res["a"] + res["b"]
self.assertEqual(3. * (2. + 3.), func2(3.))
hcb.barrier_wait()
assertMultiLineStrippedEqual(self, """
{ a=6.00
b=9.00 }""", testing_stream.output)
def test_tap_with_result(self):
def func2(x):
x1 = hcb.id_print((x * 2., x * 3.), result=x * 4.,
output_stream=testing_stream)
return x1
self.assertEqual(3. * 4., func2(3.))
hcb.barrier_wait()
assertMultiLineStrippedEqual(self, """
( 6.00
9.00 )""", testing_stream.output)
def test_tap_with_result_no_arg(self):
def tap_func(arg, transforms):
testing_stream.write(f"called tap_func with {arg}")
def func2(x):
x1 = hcb.id_tap(tap_func, None, result=x)
return x1
self.assertEqual(3., func2(3.))
hcb.barrier_wait()
assertMultiLineStrippedEqual(self, "called tap_func with None",
testing_stream.output)
def test_tap_result_unused(self):
def tap_func(arg, transforms):
testing_stream.write(f"called tap_func with {arg}")
def func2(x):
hcb.id_tap(tap_func, None)
return x
self.assertEqual(3., func2(3.))
hcb.barrier_wait()
assertMultiLineStrippedEqual(self, "called tap_func with None",
testing_stream.output)
def test_tap_with_device(self):
def func2(x):
x1 = hcb.id_print((x * 2., x * 3.), result=x * 4.,
output_stream=testing_stream,
tap_with_device=True)
return x1
self.assertEqual(3. * 4., func2(3.))
hcb.barrier_wait()
assertMultiDeviceOutputEqual(self, """
device: cpu:0
( 6.00
9.00 )""")
def test_tap_eval_exception(self):
if not FLAGS.jax_host_callback_outfeed:
raise SkipTest("TODO: implement error handling for customcall")
# Simulate a tap error
def tap_err(*args, **kwargs):
raise ValueError("Some user message")
def func(x):
x1 = hcb.id_print(x + 1, what="x1", output_stream=testing_stream)
x2 = hcb.id_tap(tap_err, x1 + 1)
x3 = hcb.id_print(x2 + 1, what="x3", output_stream=testing_stream)
return x3
with self.assertRaisesRegex(
hcb.CallbackException,
re.compile("There were exceptions during callback processing. Last one was:.*"
"ValueError: Some user message", re.DOTALL)):
func(0)
hcb.barrier_wait()
# We should have received everything before the error
assertMultiLineStrippedEqual(self, """
what: x1
1
what: x3
3""", testing_stream.output)
def test_tap_empty(self):
"""Tap empty arrays."""
hcb.id_print((), output_stream=testing_stream)
hcb.id_print((1., np.ones((2, 0))), what="second", output_stream=testing_stream)
hcb.barrier_wait()
assertMultiLineStrippedEqual(self, """
( )
what: second
( 1.00
[] )""", testing_stream.output)
def test_tap_jit_simple(self):
jit_fun1 = api.jit(lambda x: 3. * hcb.id_print(
2. * x, what="here", output_stream=testing_stream))
self.assertAllClose(6. * 5., jit_fun1(5.))
hcb.barrier_wait()
assertMultiLineStrippedEqual(self, """
what: here
10.00""", testing_stream.output)
def test_tap_jit_no_invars(self):
def func(): # jitted function does not take arguments
return hcb.id_print(42, output_stream=testing_stream)
self.assertAllClose(42, api.jit(func)())
hcb.barrier_wait()
assertMultiLineStrippedEqual(self, """
42""", testing_stream.output)
def test_tap_jit_multiple_invars(self):
def func(x1, x2):
return hcb.id_print(x1 + x2, output_stream=testing_stream)
self.assertAllClose(42, api.jit(func)(40, 2))
hcb.barrier_wait()
assertMultiLineStrippedEqual(self, """
42""", testing_stream.output)
def test_tap_jit_constant(self):
def func(x):
return hcb.id_print(42, result=x, output_stream=testing_stream)
self.assertAllClose(5, api.jit(func)(5))
hcb.barrier_wait()
assertMultiLineStrippedEqual(self, """
42""", testing_stream.output)
def test_tap_jit_sequence1(self):
def func(x):
x1 = hcb.id_print(x, where="1", output_stream=testing_stream)
return hcb.id_print(x1 + 1, where="2", output_stream=testing_stream)
logging.info("%s: %s", self._testMethodName,
api.make_jaxpr(func)(1))
logging.info("%s: %s", self._testMethodName,
api.xla_computation(func)(1).as_hlo_text())
self.assertEqual(2, api.jit(func)(1))
hcb.barrier_wait()
assertMultiLineStrippedEqual(self, """
where: 1
1
where: 2
2""", testing_stream.output)
def test_tap_jit2(self):
"""A sequence of JIT."""
def func(x):
x1 = hcb.id_print(x, where="1", output_stream=testing_stream)
x2 = hcb.id_print(x1 + 1, where="2", output_stream=testing_stream)
return x2
self.assertEqual(2, api.jit(func)(1))
self.assertEqual(11, api.jit(func)(10))
hcb.barrier_wait()
assertMultiLineStrippedEqual(self, """
where: 1
1
where: 2
2
where: 1
10
where: 2
11""", testing_stream.output)
def test_tap_jit_result_unused(self):
"""We can id_print even if we don't use the result."""
def func(x):
hcb.id_print(x, where="1", output_stream=testing_stream)
hcb.id_print(x + 1, where="2", output_stream=testing_stream)
return x + 1
self.assertEqual(2, api.jit(func)(1))
self.assertEqual(11, api.jit(func)(10))
hcb.barrier_wait()
assertMultiLineStrippedEqual(self, """
where: 1
1
where: 2
2
where: 1
10
where: 2
11""", testing_stream.output)
def test_tap_jit_nested(self):
def func(x):
x1 = hcb.id_print(x, where="1", output_stream=testing_stream)
def func_nested(x):
x2 = hcb.id_print(x + 1, where="nested", output_stream=testing_stream)
return x2
x3 = api.jit(func_nested)(x1)
return hcb.id_print(x3 + 1, where="3", output_stream=testing_stream)
self.assertEqual(3, api.jit(func)(1))
hcb.barrier_wait()
assertMultiLineStrippedEqual(self, """
where: 1
1
where: nested
2
where: 3
3""", testing_stream.output)
def test_tap_jit_devices(self):
"""Running on multiple devices."""
logging.info(f"{self._testMethodName}: has devices {local_devices()}")
def func(x, device_id):
x1 = hcb.id_print(x, dev=str(device_id), output_stream=testing_stream)
x2 = hcb.id_print(x1 + 1, dev=str(device_id), output_stream=testing_stream)
return x2
for d in local_devices():
self.assertEqual(112, api.jit(func, device=d, static_argnums=1)(111, d.id))
hcb.barrier_wait()
logging.info(f"{self._testMethodName}: found output {testing_stream.output}")
self.assertEqual(
len(local_devices()), len(re.findall(r"111", testing_stream.output)))
self.assertEqual(
len(local_devices()), len(re.findall(r"112", testing_stream.output)))
@parameterized.named_parameters(
jtu.cases_from_list(
dict(
testcase_name=f"_with_jit_{with_jit}",
with_jit=with_jit)
for with_jit in [True, False]))
def test_tap_pytree(self, with_jit=False):
def func(x, what=""):
"""Returns some pytrees depending on x"""
if what == "pair_1_x":
return (1, x)
elif what == "pair_x_2x":
return (x, 2 * x)
elif what == "dict":
return dict(a=2 * x, b=3 * x)
else:
assert False
tap_count = 0
def tap_func(a, _, *, what=""):
nonlocal tap_count
tap_count += 1
self.assertEqual(func(5, what), a)
transform = api.jit if with_jit else lambda f: f
for what in ("pair_1_x", "pair_x_2x", "dict"):
transformed = transform(
lambda x: hcb.id_tap(
partial(tap_func, what=what),
func(x, what),
result=func(x * 2, what))
)(5)
self.assertEqual(func(10, what), transformed)
hcb.barrier_wait() # Wait for receivers to be done
self.assertEqual(3, tap_count)
@parameterized.named_parameters(
jtu.cases_from_list(
dict(
testcase_name=f"_concurrent_{concurrent}",
concurrent=concurrent)
for concurrent in [True, False]))
def test_tap_multiple(self, concurrent=False):
"""Call id_tap multiple times, concurrently or in sequence. """
if concurrent and jtu.device_under_test() in ["cpu", "gpu"]:
# TODO(necula): if there is device side concurrency, outfeeds from
# different computations can be interleaved. For example, it seems that
# on GPU if multiple host threads run a jit computation, the multiple
# computations are interleaved on the GPU. This can result in the outfeed
# trains being interleaved, which will trigger an error.
# The solution is to fix on GPU the receiving logic so that we can outfeed
# the train as one tuple, and receive it one piece as a time. Then the
# trains should be atomic.
# See also b/160692602.
raise SkipTest("concurrent id_tap not supported on CPU, GPU")
received = set()
count = 5
def pause_tap(idx, _):
received.add(int(idx))
logging.info(f"Starting do_tap {idx}. Sleeping 1sec ...")
time.sleep(0.3)
logging.info(f"Finish do_tap {idx}")
def do_tap(idx):
api.jit(lambda idx: hcb.id_tap(pause_tap, idx))(idx)
if concurrent:
threads = [
threading.Thread(
name=f"enqueue_tap_{idx}", target=do_tap, args=(idx,))
for idx in range(count)
]
[t.start() for t in threads]
[t.join() for t in threads]
else:
for idx in range(count):
do_tap(idx)
hcb.barrier_wait()
self.assertEqual(received, set(range(count)))
# TODO(necula): see comment for test_multiple_tap. Here we disable also
# on TPU, because the barrier_wait runs on all devices, including on the CPU
# where it would run into concurrency problems.
@skip("Concurrency not supported")
def test_tap_multiple_barriers(self):
"""Call barrier_wait concurrently."""
def pause_tap(*args, **kwargs):
logging.info("pause_tap waiting")
time.sleep(0.3)
logging.info("pause_tap done")
def long_run(x):
return hcb.id_tap(pause_tap, x)
api.jit(long_run)(5.)
def try_barrier(idx):
logging.info(f"Starting test barrier {idx}")
hcb.barrier_wait()
logging.info(f"Finished test barrier {idx}")
threads = [
threading.Thread(
name=f"barrier_{idx}", target=try_barrier, args=(idx,))
for idx in range(3)
]
[t.start() for t in threads]
[t.join() for t in threads]
@parameterized.named_parameters(
jtu.cases_from_list(
dict(
testcase_name=f"_with_jit_{with_jit}",
with_jit=with_jit)
for with_jit in [True, False]))
def test_tap_cond(self, with_jit=False):
"""A conditional"""
def func(x):
x1 = hcb.id_print(x, where="1", output_stream=testing_stream)
x2 = hcb.id_print(x1 + 1, where="2", output_stream=testing_stream)
x4 = lax.cond(x % 2 == 0,
lambda x: hcb.id_print(x, where="cond_t",
output_stream=testing_stream),
lambda x: hcb.id_print(-1, where="cond_f", result=x,
output_stream=testing_stream),
x2 + 1)
x5 = hcb.id_print(x4 + 1, where="end", output_stream=testing_stream)
return x5
transform = api.jit if with_jit else lambda f: f
self.assertEqual(4, transform(func)(1))
hcb.barrier_wait()
assertMultiLineStrippedEqual(self, """
where: 1
1
where: 2
2
where: cond_f
-1
where: end
4""", testing_stream.output)
@parameterized.named_parameters(
jtu.cases_from_list(
dict(testcase_name=f"_with_jit_{with_jit}",
with_jit=with_jit)
for with_jit in [True, False]))
def test_tap_while_cond(self, with_jit=False):
def func(x):
x1 = hcb.id_print(x, where="1", output_stream=testing_stream)
x2 = hcb.id_print(x1 + 1, where="2", output_stream=testing_stream)
def body(x):
x3 = hcb.id_print(x, where="w_b_1", output_stream=testing_stream)
x4 = lax.cond(x % 2 == 0,
lambda x: hcb.id_print(x, where="w_b_t",
output_stream=testing_stream),
lambda x: hcb.id_print(-1, where="w_b_f",
result=x, output_stream=testing_stream),
x3 + 1)
return hcb.id_print(x4, where="w_b_2", output_stream=testing_stream)
x10 = lax.while_loop(lambda x: x <= 3, body, x2)
res = hcb.id_print(x10, where="end", output_stream=testing_stream)
return res
transform = api.jit if with_jit else lambda f: f
self.assertEqual(4, transform(func)(1))
hcb.barrier_wait()
assertMultiLineStrippedEqual(self, """
where: 1
1
where: 2
2
where: w_b_1
2
where: w_b_t
3
where: w_b_2
3
where: w_b_1
3
where: w_b_f
-1
where: w_b_2
4
where: end
4""", testing_stream.output)
def test_tap_jit_while_pred_tap(self):
"""While with printing in the conditional."""
def func(x):
x1 = hcb.id_print(x, where="1")
x10 = lax.while_loop(lambda x: hcb.id_print(x < 3,
where="w_p",
output_stream=testing_stream),
lambda x: hcb.id_print(x + 1, where="w_b",
output_stream=testing_stream),
x1)
res = hcb.id_print(x10, where="3", output_stream=testing_stream)
return res
self.assertEqual(3, api.jit(func)(1))
hcb.barrier_wait()
assertMultiLineStrippedEqual(self,
"""
where: w_p
True
where: w_b
2
where: w_p
True
where: w_b
3
where: w_p
False
where: 3
3""", testing_stream.output)
@parameterized.named_parameters(
jtu.cases_from_list(
dict(
testcase_name=f"_with_jit_{with_jit}",
with_jit=with_jit)
for with_jit in [True, False]))
def test_tap_scan_cond(self, with_jit=True):
def func(x):
x1 = hcb.id_print(x, where="1", output_stream=testing_stream)
x2 = hcb.id_print(x1 + 1, where="2", output_stream=testing_stream)
def body(c, x):
x3 = hcb.id_print(x, where="s_1", output_stream=testing_stream)
x4 = lax.cond(x % 2 == 0,
lambda x: hcb.id_print(x, where="s_t", output_stream=testing_stream),
lambda x: hcb.id_print(-1, where="s_f", result=x, output_stream=testing_stream),
x3 + 1)
return (c, hcb.id_print(x4, where="s_2", output_stream=testing_stream))
_, x10 = lax.scan(body, x2, jnp.arange(3))
res = hcb.id_print(x10, where="10", output_stream=testing_stream)
return res
if with_jit:
func = api.jit(func)
res = func(1)
self.assertAllClose(jnp.array([1, 2, 3]), res)
hcb.barrier_wait()
assertMultiLineStrippedEqual(self, """
where: 1
1
where: 2
2
where: s_1
0
where: s_t
1
where: s_2
1
where: s_1
1
where: s_f
-1
where: s_2
2
where: s_1
2
where: s_t
3
where: s_2
3
where: 10
[1 2 3]""", testing_stream.output)
testing_stream.reset()
@parameterized.named_parameters(
jtu.cases_from_list(
dict(
testcase_name=f"_shape_{shape}_dtype_{np.dtype(dtype).name}_nr_args={nr_args}",
shape=shape,
dtype=dtype,
nr_args=nr_args) for nr_args in [1, 2]
for shape in [(), (2,), (2, 3), (2, 3, 4)]
for dtype in jtu.dtypes.all))
def test_tap_jit_dtypes(self, nr_args=2, dtype=jnp.int16, shape=(2,)):
if dtype in (jnp.complex64, jnp.complex128, jnp.bool_):
raise SkipTest(f"host_callback not implemented for {dtype}.")
if dtype == np.bool_:
args = [np.random.choice(a=[True, False], size=shape)]
else:
args = [jnp.arange(np.prod(shape), dtype=dtype).reshape(shape)]
if nr_args > 1:
args = args * nr_args
jit_fun1 = api.jit(lambda xs: hcb.id_print(
xs,
a_new_test="************",
testcase_name=f"shape_{shape}_dtype_{dtype}_nr_args={nr_args}"))
res = jit_fun1(args)
self.assertAllClose(args, res, check_dtypes=True)
def test_tap_jit_large(self):
arg = jnp.arange(10000, dtype=jnp.int32).reshape((10, 10, 5, -1))
api.jit(hcb.id_print)(arg)
def test_tap_jit_several_together(self):
arg = jnp.arange(50, dtype=jnp.int32).reshape((10, 5))
api.jit(lambda x, y: hcb.id_print((x, y, x * 2.)))(arg, jnp.ones(100, dtype=jnp.int32))
def test_tap_jit_interleaving(self):
# Several jit's without data dependencies; they may interfere
count = 0 # Count tap invocations
nr_arrays = 5
def tap_func(arg, _):
nonlocal count
assert len(arg) == nr_arrays
count += 1
# This is the function that we'll run multiple times
def func(x, count):
for i in range(count):
x = hcb.id_tap(tap_func, [x + i for i in range(nr_arrays)])[-1]
return x
x = jnp.array(1, dtype=np.int32)
res = 0
for _ in range(10):
# No dependencies between the jit invocations
res += api.jit(lambda x: func(x, 10))(x)
hcb.barrier_wait()
self.assertEqual(100, count)
def test_tap_jit_tap_exception(self):
if not FLAGS.jax_host_callback_outfeed:
raise SkipTest("TODO: implement error handling for customcall")
# Simulate a tap error
def tap_err(*args, **kwargs):
raise NotImplementedError
def func(x):
x1 = hcb.id_print(x + 1, what="x1", output_stream=testing_stream)
x2 = hcb.id_tap(tap_err, x1 + 1)
x3 = hcb.id_print(x2 + 1, what="x3", output_stream=testing_stream)
return x3
res = api.jit(func)(0) # No error yet
with self.assertRaises(hcb.CallbackException):
hcb.barrier_wait()
# Even though the receiver thread raised, the main thread should still
# return 3.
self.assertEqual(3, res)
# We should have received all others
assertMultiLineStrippedEqual(self, """
what: x1
1
what: x3
3""", testing_stream.output)
def test_tap_while(self):
"""Executing while, even without JIT uses compiled code"""
y = jnp.ones(5) # captured const
def func(x):
return lax.while_loop(
lambda c: c[1] < 5,
lambda c: (y, hcb.id_print(c[1], output_stream=testing_stream) + 1),
(x, 1))
func(y)
hcb.barrier_wait()
assertMultiLineStrippedEqual(self, """
1
2
3
4""", testing_stream.output)
def test_tap_jvp(self):
jvp_fun1 = lambda x, xt: api.jvp(fun1, (x,), (xt,))
res_primals, res_tangents = jvp_fun1(jnp.float32(5.), jnp.float32(0.1))
self.assertAllClose(100., res_primals, check_dtypes=False)
self.assertAllClose(4., res_tangents, check_dtypes=False)
hcb.barrier_wait()
assertMultiLineStrippedEqual(self, """
transforms: ['jvp'] what: a * 2
( 10.00
0.20 )
transforms: ['jvp'] what: y * 3
( 30.00
0.60 )""", testing_stream.output)
def test_tap_grad_primal_unused(self):
# The output of id_print is not needed for backwards pass
def func(x):
return 2. * hcb.id_print(x * 3., what="x * 3",
output_stream=testing_stream)
grad_func = api.grad(func)
arg = jnp.float32(5.)
jaxpr = str(api.make_jaxpr(grad_func)(arg))
# making the Jaxpr does not print anything
hcb.barrier_wait()
treedef = tree_util.tree_structure(arg)
assertMultiLineStrippedEqual(self, f"""
{{ lambda ; a.
let b = mul a 3.00
c = outside_call[ arg_treedef={treedef}
callback=...
identity=True
transforms=( ) ] b
_ = mul c 2.00
d = mul 1.00 2.00
_ = broadcast_in_dim[ broadcast_dimensions=( )
shape=( ) ] 0.00
e = outside_call[ arg_treedef={treedef}
callback=...
identity=True
transforms=(('jvp',), ('transpose',)) ] d
f = mul e 3.00
in (f,) }}""", jaxpr)
assertMultiLineStrippedEqual(self, "", testing_stream.output)
testing_stream.reset()
res_grad = grad_func(arg)
hcb.barrier_wait()
self.assertAllClose(6., res_grad, check_dtypes=False)
assertMultiLineStrippedEqual(self, """
what: x * 3
15.00
transforms: ['jvp', 'transpose'] what: x * 3
2.00""", testing_stream.output)
def test_tap_grad_simple(self):
def func(x):
y = hcb.id_print(x * 2., what="x * 2", output_stream=testing_stream)
return x * hcb.id_print(y * 3., what="y * 3",
output_stream=testing_stream)
grad_func = api.grad(func)
res_grad = grad_func(jnp.float32(5.))
self.assertAllClose(2. * 5. * 6., res_grad, check_dtypes=False)
hcb.barrier_wait()
assertMultiLineStrippedEqual(self, """
what: x * 2
10.00
what: y * 3
30.00
transforms: ['jvp', 'transpose'] what: y * 3
5.00
transforms: ['jvp', 'transpose'] what: x * 2
15.00""", testing_stream.output)
def test_tap_grad_grad(self):
def func(x):
y = hcb.id_print(x * 2., what="x * 2", output_stream=testing_stream)
return x * (y * 3.)
grad_func = api.grad(api.grad(func))
# making the Jaxpr does not print anything
_ = api.make_jaxpr(grad_func)(5.)
hcb.barrier_wait()
assertMultiLineStrippedEqual(self, "", testing_stream.output)
res_grad = grad_func(jnp.float32(5.))
self.assertAllClose(12., res_grad, check_dtypes=False)
hcb.barrier_wait()
assertMultiLineStrippedEqual(self, """
what: x * 2
10.00
transforms: ['jvp', 'transpose'] what: x * 2
15.00
transforms: ['jvp', 'transpose', 'jvp', 'transpose'] what: x * 2
2.00
transforms: ['jvp', 'transpose'] what: x * 2
3.00""", testing_stream.output)
def test_tap_grad_pytree(self):
def func(x):
x4, x5 = hcb.id_print((x * 2., x * 3.), what="pair",
result=(x * 4., x * 5.),
output_stream=testing_stream)
return x4 + 2. * x5
x = jnp.float32(5.)
grad_func = api.grad(func)
print(api.make_jaxpr(grad_func)(x))
res_grad = grad_func(x)
self.assertAllClose(14., res_grad, check_dtypes=False)
hcb.barrier_wait()
assertMultiLineStrippedEqual(self, """
what: pair
( 10.00
15.00 )
transforms: ['jvp', 'transpose'] what: pair
( 0.00
0.00 )""", testing_stream.output)
def test_tap_jvp_float0(self):
def f(x, yint):
x, yint = hcb.id_tap(lambda arg, _: arg, (x, yint))
return x * yint
res = api.jvp(f, (2., 3), (0.2, np.zeros((), dtypes.float0)))
self.assertAllClose((6., 0.6), res)
def test_tap_grad_float0(self):
def func(x, yint):
x, yint = hcb.id_print((x, yint), what="pair", output_stream=testing_stream)
return x * yint
grad_func = api.grad(func)
res_grad = grad_func(jnp.float32(5.), jnp.int32(2))
self.assertAllClose(2., res_grad, check_dtypes=False)
hcb.barrier_wait()
assertMultiLineStrippedEqual(self, """
what: pair
( 5.00
2 )
transforms: ['jvp', 'transpose'] what: pair
( 2.00
False )""", testing_stream.output)
def test_tap_grad_float0_result(self):
# https://github.com/google/jax/issues/7340
# x is a Tuple[f32[2], s32[3]]
x = (np.array([.7, .8], dtype=np.float32),
np.array([11, 12, 13], dtype=np.int32))
def f_jax(x):
x = hcb.id_print(x, result=x, output_stream=testing_stream) # result= is important
return (3. * x[0], x[1])
def f_jax_vjp(x):
res, pullback = jax.vjp(f_jax, x)
g, = pullback((np.ones(x[0].shape, dtype=x[0].dtype),
np.zeros(x[1].shape, dtype=dtypes.float0)))
return g
g = f_jax_vjp(x)
self.assertAllClose(np.array([3., 3.], dtype=np.float32), g[0])
self.assertEqual(dtypes.float0, g[1].dtype)
hcb.barrier_wait()
assertMultiLineStrippedEqual(self, """
( [0.70 0.80]
[11 12 13] )
transforms: ['jvp', 'transpose']
( [0.00 0.00]
[False False False] )""", testing_stream.output)
def test_tap_higher_order_grad_float0_result(self):
# https://github.com/google/jax/issues/7340
# x is a Tuple[f32[2], s32[3]]
x = (np.array([.7, .8], dtype=np.float32),
np.array([11, 12, 13], dtype=np.int32))
def f_jax(x):
x = hcb.id_print(x, result=x, output_stream=testing_stream) # result= is important
return (jnp.sin(x[0]), x[1])
def wrap_vjp(f, args, res_f_of_args):
# Given a function "f" and "args" return the f_vjp and args_vjp
def make_ct(res):
res_dtype = np.result_type(res)
if res_dtype == dtypes.float0:
return res
ct_dtype = core.primal_dtype_to_tangent_dtype(res_dtype)
return np.ones(np.shape(res), dtype=ct_dtype)
cts = tree_util.tree_map(make_ct, res_f_of_args)
def f_vjp(args, cts):
res, pullback = jax.vjp(f, *args)
return pullback(cts)
return (f_vjp, (args, cts))
res = f_jax(x)
hcb.barrier_wait()
assertMultiLineStrippedEqual(self, """
( [0.70 0.80]
[11 12 13] )""", testing_stream.output)
testing_stream.reset()
# 1st order
f_jax_vjp1, args_vjp1 = wrap_vjp(f_jax, (x,), res)
res_vjp1 = f_jax_vjp1(*args_vjp1)
hcb.barrier_wait()
assertMultiLineStrippedEqual(self, """
( [0.70 0.80]
[11 12 13] )
transforms: ['jvp', 'transpose']
( [0.00 0.00]
[False False False] )""", testing_stream.output)
testing_stream.reset()
# 2nd order
f_jax_vjp2, args_vjp2 = wrap_vjp(f_jax_vjp1, args_vjp1, res_vjp1)
res_vjp2 = f_jax_vjp2(*args_vjp2)
# 3rd order
f_jax_vjp3, args_vjp3 = wrap_vjp(f_jax_vjp2, args_vjp2, res_vjp2)
_ = f_jax_vjp3(*args_vjp3)
def test_tap_vmap(self):
vmap_fun1 = api.vmap(fun1)
vargs = jnp.array([jnp.float32(4.), jnp.float32(5.)])
vmap_fun1(vargs)
hcb.barrier_wait()
assertMultiLineStrippedEqual(self, """
transforms: [('batch', {'batch_dims': (0,)})] what: a * 2
[ 8.00 10.00]
transforms: [('batch', {'batch_dims': (0,)})] what: y * 3
[24.00 30.00]""", testing_stream.output)
def test_tap_vmap_not_batched(self):
x = 3.
def func(y):
# x is not mapped, y is mapped
_, y = hcb.id_print((x, y), output_stream=testing_stream)
return x + y
vmap_func = api.vmap(func)
vargs = jnp.array([jnp.float32(4.), jnp.float32(5.)])
_ = vmap_func(vargs)
hcb.barrier_wait()
assertMultiLineStrippedEqual(self, """
transforms: [('batch', {'batch_dims': (None, 0)})]
( 3.00
[4.00 5.00] )""", testing_stream.output)
def test_tap_vmap_vmap(self):
# A 2D tensor with x[i, j] = i + j using 2 vmap
def sum(x, y):
return hcb.id_print(x + y, output_stream=testing_stream)
def sum_rows(xv, y):
return api.vmap(sum, in_axes=(0, None))(xv, y)
def sum_all(xv, yv):
return api.vmap(sum_rows, in_axes=(None, 0))(xv, yv)
xv = jnp.arange(5, dtype=np.int32)
yv = jnp.arange(3, dtype=np.int32)
# assertMultiLineStrippedEqual(self, "", str(api.make_jaxpr(sum_all)(xv, yv)))
_ = sum_all(xv, yv)
hcb.barrier_wait()
assertMultiLineStrippedEqual(self, """
transforms: [('batch', {'batch_dims': (0,)}), ('batch', {'batch_dims': (0,)})]
[[0 1 2 3 4]
[1 2 3 4 5]
[2 3 4 5 6]]""", testing_stream.output)
def test_tap_vmap_while(self):
"""Vmap of while."""
def func(x):
# like max(x, 2)
x1 = hcb.id_print(x, where="before:x", output_stream=testing_stream)
x2 = lax.while_loop(
lambda x: x < 2, lambda x: hcb.id_print(
x + 1, where="body:x+1", output_stream=testing_stream), x1)
res = hcb.id_print(x2, where="after:x", output_stream=testing_stream)
return res
inputs = np.arange(5, dtype=np.int32)
self.assertAllClose(
np.array([2, 2, 2, 3, 4]),
api.jit(api.vmap(func))(inputs),
check_dtypes=False)
hcb.barrier_wait()
assertMultiLineStrippedEqual(
self, """
transforms: [('batch', {'batch_dims': (0,)})] where: before:x
[0 1 2 3 4]
transforms: [('batch', {'batch_dims': (0,)})] where: body:x+1
[1 2 3 4 5]
transforms: [('batch', {'batch_dims': (0,)})] where: body:x+1
[2 3 3 4 5]
transforms: [('batch', {'batch_dims': (0,)})] where: after:x
[2 2 2 3 4]""", testing_stream.output)
def test_tap_vmap_while_tap_cond(self):
"""Vmap of while, with a tap in the conditional."""
def func(x):
# like max(x, 2)
x1 = hcb.id_print(x, where="1", output_stream=testing_stream)
x2 = lax.while_loop(lambda x: hcb.id_print(x < 2, where="w_c",
output_stream=testing_stream),
lambda x: hcb.id_print(x + 1, where="w_b",
output_stream=testing_stream),
x1)
res = hcb.id_print(x2, where="3", output_stream=testing_stream)
return res
inputs = np.arange(5, dtype=np.int32)
res = api.jit(api.vmap(func))(inputs)
hcb.barrier_wait()
self.assertAllClose(np.array([2, 2, 2, 3, 4]), res, check_dtypes=False)
assertMultiLineStrippedEqual(self, """
transforms: [('batch', {'batch_dims': (0,)})] where: 1
[0 1 2 3 4]
transforms: [('batch', {'batch_dims': (0,)})] where: w_c
[ True True False False False]
transforms: [('batch', {'batch_dims': (0,)})] where: w_b
[1 2 3 4 5]
transforms: [('batch', {'batch_dims': (0,)})] where: w_c
[ True False False False False]
transforms: [('batch', {'batch_dims': (0,)})] where: w_b
[2 3 3 4 5]
transforms: [('batch', {'batch_dims': (0,)})] where: w_c
[False False False False False]
transforms: [('batch', {'batch_dims': (0,)})] where: 3
[2 2 2 3 4]""", testing_stream.output)
def test_tap_transforms(self):
def power3(x):
y = x * x
# Print both 'x' and 'x^2'. Must pack as a tuple.
_, y = hcb.id_print((x, y), what="x,x^2", output_stream=testing_stream)
return y * x
print(f"impl = {power3(3.)}")
hcb.barrier_wait()
expected = """
what: x,x^2
( 3.
9. )"""
self.assertMultiLineStrippedEqual(expected, testing_stream.output)
testing_stream.reset()
print(f"vmap = {jax.vmap(power3)(np.arange(3.))}")
hcb.barrier_wait()
expected = """
transforms: [('batch', {'batch_dims': (0, 0)})] what: x,x^2
( [0. 1. 2.]
[0. 1. 4.] )"""
self.assertMultiLineStrippedEqual(expected, testing_stream.output)
testing_stream.reset()
print(f"jvp = {jax.jvp(power3, (3.,), (0.1,))}")
hcb.barrier_wait()
expected = """
transforms: ['jvp'] what: x,x^2
( ( 3.
9. )
( 0.1
0.6 ) )"""
self.assertMultiLineStrippedEqual(expected, testing_stream.output)
testing_stream.reset()
print(f"grad = {jax.grad(power3)(3.)}")
hcb.barrier_wait()
expected = """
what: x,x^2
( 3.
9. )
transforms: ['jvp', 'transpose'] what: x,x^2
( 0.
3. )"""
self.assertMultiLineStrippedEqual(expected, testing_stream.output)
testing_stream.reset()
print(f"vmap o grad {jax.vmap(jax.grad(power3))(np.array([2., 3.]))}")
hcb.barrier_wait()
expected = """
transforms: [('batch', {'batch_dims': (0, 0)})] what: x,x^2
( [2. 3.]
[4. 9.] )
transforms: ['jvp', 'transpose', ('batch', {'batch_dims': (None, 0)})] what: x,x^2
( 0.
[2. 3.] )"""
self.assertMultiLineStrippedEqual(expected, testing_stream.output)
def test_tap_pmap(self):
if len(local_devices()) < 2:
raise SkipTest("test requires at least 2 devices")
def power3(x):
y = x * x
# Print both 'x' and 'x^2'. Must pack as a tuple.
_, y = hcb.id_print((x, y),
what="x,x^2",
output_stream=testing_stream,
tap_with_device=True)
return y * x
pmap_power3 = api.pmap(power3, devices=local_devices())
xv = np.array([3, 4], dtype=np.int32)
res = pmap_power3(xv)
hcb.barrier_wait()
self.assertAllClose(xv * xv * xv, res, check_dtypes=False)
# Assertion text is for 2 devices (also works for 1 device)
assertMultiDeviceOutputEqual(
self, """
device: cpu:0 what: x,x^2
( 3
9 )
device: cpu:1 what: x,x^2
( 4
16 )""")
def test_tap_pmap_vmap(self):
# A matrix M[ij] = i * 10 + j
nr_devices = len(local_devices())
shape = (nr_devices, 3)
matrix = np.fromfunction(lambda i, j: 10. * i + j, shape,
dtype=np.int32)
def fun1(x, do_print=False): # x: i32
return maybe_print(do_print, x * 2, "x * 2", tap_with_device=True)
pmap_vmap_fun1 = api.pmap(
api.vmap(partial(fun1, do_print=True)), devices=local_devices())
res = pmap_vmap_fun1(matrix)
hcb.barrier_wait()
expected_res = api.pmap(
api.vmap(partial(fun1, do_print=False)), devices=local_devices())(
matrix)
self.assertAllClose(expected_res, res, check_dtypes=False)
# Assertion text is for 2 devices (also works for 1 device)
assertMultiDeviceOutputEqual(self, """
device: cpu:0 transforms: [('batch', {'batch_dims': (0,)})] what: x * 2
[0.00 2.00 4.00]
device: cpu:1 transforms: [('batch', {'batch_dims': (0,)})] what: x * 2
[20.00 22.00 24.00]""")
def test_tap_pmap_pmap_vmap(self):
# A matrix M[ijk] = i * 100 + j * 10 + k
nr_devices = len(local_devices())
if nr_devices % 2 != 0:
raise SkipTest("test works only on even number of devices")
shape = (2, nr_devices // 2, 3)
matrix = np.fromfunction(lambda i, j, k: 100. * i + 10. * j + k, shape,
dtype=np.float32)
def fun1(x, do_print=False): # x: f32
y = maybe_print(do_print, x * 2., "x * 2", tap_with_device=True)
return y ** 2
pmap_fun1 = api.pmap(
api.pmap(api.vmap(partial(fun1, do_print=True))),
devices=local_devices())
res = pmap_fun1(matrix)
hcb.barrier_wait()
expected_res = api.pmap(
api.pmap(api.vmap(partial(fun1, do_print=False))),
devices=local_devices())(
matrix)
self.assertAllClose(expected_res, res, check_dtypes=False)
# Assertion text is for 2 devices (also works for 1 device)
assertMultiDeviceOutputEqual(self, """
device: cpu:0 transforms: [('batch', {'batch_dims': (0,)})] what: x * 2
[0.00 2.00 4.00]
device: cpu:1 transforms: [('batch', {'batch_dims': (0,)})] what: x * 2
[200.00 202.00 204.00]""")
@ignore_jit_of_pmap_warning()
def test_tap_pmap_pmap_extra(self):
"""pmap of a pmap surrounded by extra code."""
# A matrix M[ij] = i * 10 + j
nr_devices = len(local_devices())
if nr_devices != 2:
raise SkipTest("test works only on 2 devices")
shape = (2, 1, 3)
matrix = np.fromfunction(lambda i, j, k: 100. * i + 10. * j + k, shape,
dtype=np.float32)
def fun(xv, do_print=False):
# This will be printed on all devices, with shape [1, 3]
xv = maybe_print(do_print, xv + 1., "before", tap_with_device=True)
res = api.pmap(lambda x: maybe_print(do_print, x * 2., "inside", tap_with_device=True))(xv)
# This will be printed on all devices, with shape [1, 3]
return maybe_print(do_print, res + 1., "after", tap_with_device=True)
res = api.pmap(partial(fun, do_print=True))(matrix)
self.assertAllClose(fun(matrix, do_print=False), res, check_dtypes=False)
hcb.barrier_wait()
# Assertion text is for 2 devices (also works for 1 device)
assertMultiDeviceOutputEqual(self, """
device: cpu:0 what: before
[[1.00 2.00 3.00]]
device: cpu:0 what: inside
[2.00 4.00 6.00]
device: cpu:0 what: after
[[3.00 5.00 7.00]]
device: cpu:1 what: before
[[101.00 102.00 103.00]]
device: cpu:1 what: inside
[202.00 204.00 206.00]
device: cpu:1 what: after
[[203.00 205.00 207.00]]""")
def test_tap_jvp_pmap_vmap(self):
# A matrix M[ijk] = i * 100 + j * 10 * k
nr_devices = len(local_devices())
shape = (nr_devices, 2, 3)
matrix = np.fromfunction(lambda i, j, k: 100. * i + 10. * j + k, shape,
dtype=np.float32)
def fun(xv, do_print=False):
# x: f32[3]
return api.jvp(api.pmap(api.vmap(lambda x: maybe_print(do_print, x * 2., "x * 2", tap_with_device=True))),
(xv,), (.1 * jnp.ones_like(xv),))
res = fun(matrix, do_print=True)
hcb.barrier_wait()
expected_res = fun(matrix, do_print=False)
self.assertAllClose(expected_res, res, check_dtypes=False)
# Assertion text is for 2 devices (also works for 1 device)
# Device 0 will get to execute api.jvp(api.vmap(...)) for matrix[0, :, :]
assertMultiDeviceOutputEqual(self, """
device: cpu:0 transforms: [('batch', {'batch_dims': (0,)}), 'jvp'] what: x * 2
( [[ 0.00 2.00 4.00]
[20.00 22.00 24.00]]
[[0.20 0.20 0.20]
[0.20 0.20 0.20]] )
device: cpu:1 transforms: [('batch', {'batch_dims': (0,)}), 'jvp'] what: x * 2
( [[200.00 202.00 204.00]
[220.00 222.00 224.00]]
[[0.20 0.20 0.20]
[0.20 0.20 0.20]] )""")
def test_tap_vmap_pmap(self):
# A matrix M[ijk] = i * 100 + j * 10 * k
nr_devices = len(local_devices())
shape = (2, nr_devices, 3)
matrix = np.fromfunction(lambda i, j, k: 100. * i + 10. * j + k, shape,
dtype=np.float32)
def fun(xv, do_print=False):
# x: f32[3]
return api.vmap(api.pmap(lambda x: maybe_print(do_print, x * 2., "x * 2", tap_with_device=True)))(xv)
res = fun(matrix, do_print=True)
hcb.barrier_wait()
expected_res = fun(matrix, do_print=False)
self.assertAllClose(expected_res, res, check_dtypes=False)
# Assertion text is for 2 devices (also works for 1 device)
# Device 0 will get to execute api.jvp(api.vmap(...)) for matrix[:, 0, :]
assertMultiDeviceOutputEqual(self, """
device: cpu:0 transforms: [('batch', {'batch_dims': (0,)})] what: x * 2
[[ 0.00 2.00 4.00]
[200.00 202.00 204.00]]
device: cpu:1 transforms: [('batch', {'batch_dims': (0,)})] what: x * 2
[[ 20.00 22.00 24.00]
[220.00 222.00 224.00]]""")
@ignore_jit_of_pmap_warning()
def test_tap_jit_pmap_extra(self):
"""jit of a pmap surrounded by extra code."""
# A matrix M[ij] = i * 10 + j
nr_devices = len(local_devices())
assert nr_devices in (1, 2)
shape = (nr_devices, 3)
matrix = np.fromfunction(lambda i, j: 10. * i + j, shape,
dtype=np.float32)
def fun(xv, do_print=False):
# This will be printed on all devices with shape (nr_devices, 3)
xv = maybe_print(do_print, xv + 1., "before", tap_with_device=True)
res = api.pmap(lambda x: maybe_print(do_print, x * 2., "inside", tap_with_device=True))(xv)
# This will be printed on all devices with shape (nr_devices, 3)
return maybe_print(do_print, res + 1., "after", tap_with_device=True)
res = api.jit(partial(fun, do_print=True))(matrix)
self.assertAllClose(fun(matrix, do_print=False), res, check_dtypes=False)
hcb.barrier_wait()
if len(local_devices()) == 2:
assertMultiDeviceOutputEqual(self, """
device: cpu:0 what: before
[[ 1.00 2.00 3.00]
[11.00 12.00 13.00]]
device: cpu:0 what: inside
[2.00 4.00 6.00]
device: cpu:0 what: after
[[ 3.00 5.00 7.00]
[23.00 25.00 27.00]]
device: cpu:1 what: before
[[ 1.00 2.00 3.00]
[11.00 12.00 13.00]]
device: cpu:1 what: inside
[22.00 24.00 26.00]
device: cpu:1 what: after
[[ 3.00 5.00 7.00]
[23.00 25.00 27.00]]""")
else:
assert len(local_devices()) == 1
assertMultiDeviceOutputEqual(self, """
device: cpu:0 what: before
[[1.00 2.00 3.00]]
device: cpu:0 what: inside
[2.00 4.00 6.00]
device: cpu:0 what: after
[[3.00 5.00 7.00]]""")
def test_tap_cond_pmap(self):
raise SkipTest("cond of pmap does not work in JAX. Issue #5178.")
# A matrix M[ij] = i * 10 + j
nr_devices = len(local_devices())
shape = (nr_devices, 3)
matrix = np.fromfunction(lambda i, j: 10. * i + j, shape,
dtype=np.float32)
def fun1(x, do_print=False):
return maybe_print(do_print, x * 2., "x * 2")
def fun2(cond, xv, do_print=False):
return lax.cond(cond, api.pmap(partial(fun1, do_print=do_print)),
lambda xv: xv, xv)
res = fun2(True, matrix)
self.assertAllClose(fun2(True, matrix, do_print=False), res, check_dtypes=False)
hcb.barrier_wait()
assertMultiLineStrippedEqual(self, """
TBD""", testing_stream.output)
@jtu.skip_on_devices("cpu", "gpu")
# TODO(necula): file XLA:GPU bug for the 'Sharding' CustomCall
def test_tap_pjit(self):
devices = np.array(local_devices())
nr_devices = len(devices)
if nr_devices < 2:
raise SkipTest("test requires at least 2 devices")
print(f"test_tap_pjit is running on devices {devices}.")
# x: i32[D, 3] = [[0, 1, 2], [10, 11, 12], ...]
# y: i32[3, 4]
x = jnp.arange(100, dtype=jnp.int32).reshape((10, 10))[:nr_devices, :3]
y = jnp.ones((3, 4), np.int32)
@partial(jax.named_call, name="fun1") # for xprof debugging
def fun1(x, do_print=False):
z = jnp.dot(x, y)
return maybe_print(do_print, z, "z", tap_with_device=True)
res0 = fun1(x, do_print=False)
pjit_fun1 = pjit.pjit(
partial(fun1, do_print=True),
in_axis_resources=(P("d"),),
out_axis_resources=P("d"))
with maps.mesh(devices, ["d"]):
# Print the internal IR
helper_log_ir(
f"{self._testMethodName}.pjit",
pjit_fun1,
x,
num_partitions=nr_devices)
res = pjit_fun1(x)
self.assertAllClose(res0, res)
hcb.barrier_wait("before check")
# Assertion text is for 2 devices (also works for 1 device)
# Note that a single call is made.
assertMultiDeviceOutputEqual(
self, """
device: cpu:0 what: z
[[ 3 3 3 3]
[33 33 33 33]]""")
def test_tap_tap_scan_custom_jvp(self):
"""custom JVP, inside scan.
This exercises the custom_jvp_call_jaxpr primitives."""
@api.custom_jvp
def f(x):
return x * hcb.id_print(x, output_stream=testing_stream, what="x")
@f.defjvp
def f_jvp(primals, tangents):
x, = primals
x_dot, = tangents
primal_out = f(x)
tangent_out = 3. * x * hcb.id_print(x_dot, output_stream=testing_stream, what="x_dot")
return primal_out, tangent_out
def g(x):
# Sum f(x_i)
return lax.scan(lambda carry, inp: (carry + f(inp), 0.),
np.full(x.shape[1:], 0.), # Like x w/o leading dim
x)[0]
arg = np.full((2,), 0.7)
self.assertAllClose(0.7 * 0.7 * 2, g(arg))
hcb.barrier_wait()
self.assertMultiLineStrippedEqual("""
what: x
0.7
what: x
0.7""", testing_stream.output)
testing_stream.reset()
self.assertAllClose(np.array([2.1, 2.1]), api.grad(g)(arg), check_dtypes=False)
hcb.barrier_wait()
self.assertMultiLineStrippedEqual("""
what: x
0.7
what: x
0.7
transforms: ['transpose'] what: x_dot
2.1
transforms: ['transpose'] what: x_dot
2.1""", testing_stream.output)
def test_tap_scan_custom_vjp(self):
"""custom VJP, inside scan.
This exercises the custom_vjp_call_jaxpr primitives."""
@api.custom_vjp
def f(x):
return x * hcb.id_print(x, output_stream=testing_stream, what="x")
# f_fwd: a -> (b, residual)
def f_fwd(x):
return f(x), 3. * x
# f_bwd: (residual, CT b) -> [CT a]
def f_bwd(residual, ct_b):
return residual * hcb.id_print(ct_b, output_stream=testing_stream, what="ct_b"),
f.defvjp(f_fwd, f_bwd)
def g(x):
# Sum f(x_i)
return lax.scan(lambda carry, inp: (carry + f(inp), 0.),
np.full(x.shape[1:], 0.), # Like x w/o leading dim
x)[0]
arg = np.full((2,), 0.7)
self.assertAllClose(0.7 * 0.7 * 2, g(arg))
hcb.barrier_wait()
self.assertMultiLineStrippedEqual("""
what: x
0.7
what: x
0.7""", testing_stream.output)
testing_stream.reset()
self.assertAllClose(np.array([2.1, 2.1]), api.grad(g)(arg), check_dtypes=False)
hcb.barrier_wait()
self.assertMultiLineStrippedEqual("""
what: x
0.7
what: x
0.7
what: ct_b
1.
what: ct_b
1.""", testing_stream.output)
def test_tap_mask(self):
@partial(api.mask, in_shapes=['n'], out_shape='')
def padded_sum(x):
three_x = hcb.id_print((x, 2 * x), result=3 * x, what="x",
output_stream=testing_stream)
return jnp.sum(three_x)
x = np.arange(5.)
self.assertAllClose(9., padded_sum([x], dict(n=3)))
hcb.barrier_wait()
self.assertMultiLineStrippedEqual("""
transforms: [('mask', {'logical_shapes': 5})] what: x
( ( [0. 1. 2. 3. 4.]
[0. 2. 4. 6. 8.] )
( ( 3 )
( 3 ) ) )""", testing_stream.output)
testing_stream.reset()
# With VMAP
xv = np.arange(10.).reshape((2, 5)) # logical_shape = 5
self.assertAllClose(
np.array([9., 78.]),
# batch_size = 2, n=3 and 4 for the two elements
api.vmap(padded_sum)([xv],
dict(n=np.array([3., 4.]))))
hcb.barrier_wait()
self.assertMultiLineStrippedEqual("""
transforms: [('mask', {'logical_shapes': 5}), ('batch', {'batch_dims': (0, 0, 0, 0)})] what: x
( ( [[0. 1. 2. 3. 4.]
[5. 6. 7. 8. 9.]]
[[ 0. 2. 4. 6. 8.]
[10. 12. 14. 16. 18.]] )
( ( [3. 4.] )
( [3. 4.] ) ) )""", testing_stream.output)
testing_stream.reset()
# With JVP
self.assertAllClose((9., 0.9),
api.jvp(lambda arg: padded_sum([arg], dict(n=3)),
(x,), (x * 0.1,)))
hcb.barrier_wait()
self.assertMultiLineStrippedEqual("""
transforms: [('mask', {'logical_shapes': 5}), 'jvp'] what: x
( ( ( [0. 1. 2. 3. 4.]
[0. 2. 4. 6. 8.] )
( ( 3 )
( 3 ) ) )
( ( [0. 0.1 0.2 0.3 0.4]
[0. 0.2 0.4 0.6 0.8] )
( ( False )
( False ) ) ) )""", testing_stream.output)
testing_stream.reset()
# Now with JIT
self.assertAllClose(9., api.jit(padded_sum)([x], dict(n=3)))
hcb.barrier_wait()
self.assertMultiLineStrippedEqual("""
transforms: [('mask', {'logical_shapes': 5})] what: x
( ( [0. 1. 2. 3. 4.]
[0. 2. 4. 6. 8.] )
( ( 3 )
( 3 ) ) )""", testing_stream.output)
def test_tap_callback_delay(self):
hcb.callback_extra = lambda dev: time.sleep(1)
def func(x):
for i in range(5):
x = hcb.id_print(x * i, what="x times i")
return x
api.jit(func)(np.arange(6, dtype=np.float32).reshape((2, 3)))
def test_tap_callback_delay_barrier(self):
hcb.callback_extra = lambda dev: time.sleep(2)
def func(x):
for i in range(1, 4):
x = hcb.id_print(x * i, what=f"x times {i}", output_stream=testing_stream)
return x
api.jit(func)(np.arange(6, dtype=np.float32).reshape((2, 3)))
# Wait for the results
hcb.barrier_wait("first")
expected = """
what: x times 1
[[0. 1. 2.]
[3. 4. 5.]]
what: x times 2
[[ 0. 2. 4.]
[ 6. 8. 10.]]
what: x times 3
[[ 0. 6. 12.]
[18. 24. 30.]]"""
self.assertMultiLineStrippedEqual(expected, testing_stream.output)
testing_stream.reset()
# Call again
api.jit(func)(np.arange(6, dtype=np.float32).reshape((2, 3)))
hcb.barrier_wait("second")
self.assertMultiLineStrippedEqual(expected, testing_stream.output)
def test_tap_error_bad_consumer_id(self):
"""Try to use reserved consumer ID 0.
Check that we get the proper error from the runtime."""
if not hcb._use_outfeed(jtu.device_under_test()):
raise SkipTest("test works only for outfeed")
comp = xla_bridge.make_computation_builder(self._testMethodName)
token = hcb.xops.CreateToken(comp)
hcb._initialize_outfeed_receiver() # Needed if this is the sole test
with self.assertRaisesRegex(RuntimeError,
"Consumer ID cannot be a reserved value: 0"):
hcb._callback_handler_data.receiver.add_outfeed(
comp, token, 0,
[xla_bridge.constant(comp, np.zeros((2, 3), dtype=np.float32))])
def test_tap_error_different_shapes(self):
"""Try to register different shapes for the same consumer ID."""
if not hcb._use_outfeed(jtu.device_under_test()):
raise SkipTest("test works only for outfeed")
comp = xla_bridge.make_computation_builder(self._testMethodName)
token = hcb.xops.CreateToken(comp)
hcb._initialize_outfeed_receiver() # Needed if this is the sole test
hcb._callback_handler_data.receiver.add_outfeed(
comp, token, 123,
[xla_bridge.constant(comp, np.zeros((2, 3), dtype=np.float32))])
with self.assertRaisesRegex(
RuntimeError, ".*does not match previous shape element_type.*"):
hcb._callback_handler_data.receiver.add_outfeed(
comp, token, 123,
[xla_bridge.constant(comp, np.zeros((2, 3), dtype=np.int32))])
with self.assertRaisesRegex(
RuntimeError, ".*does not match previous shape element_type.*"):
hcb._callback_handler_data.receiver.add_outfeed(
comp, token, 123,
[xla_bridge.constant(comp, np.zeros((2,), dtype=np.float32))])
def test_tap_id_tap_removed_kwargs(self):
def func(x, transforms, y):
pass
with self.assertRaisesRegex(TypeError, r"Support for \*\*kwargs in ``id_tap``"):
hcb.id_tap(func, 1, y=2)
def test_tap_odeint(self):
# TODO: find a smaller repro for bug #4015
# Seems to be xla_call(scan(xla_call)), all under grad.
from jax.experimental.ode import odeint
def f(x, t, k):
x = hcb.id_print(x)
return -k * x
def loss(k=1.0):
t = jnp.linspace(0, 0.001, num=2)
xs = odeint(f, 1.0, t, k)
return xs[-1]
api.grad(loss)(1.0) # should not fail
def test_tap_remat(self):
def f(i, k):
x = hcb.id_print(k + i, output_stream=testing_stream)
return k * x
def loss(k):
return lax.fori_loop(0, 2, api.remat(f), k)
print(loss(3))
hcb.barrier_wait()
expected = """
3
10"""
self.assertMultiLineStrippedEqual(expected, testing_stream.output)
def test_tap_named_call(self):
def tap_scalar(init, do_print=False):
@partial(api.named_call, name="step")
def step(acc, step_nr):
acc = acc + step_nr
maybe_print(do_print, step_nr, what="step_nr")
return acc, None
return lax.scan(step, init, np.arange(2))
self.assertAllClose(tap_scalar(3., do_print=False), tap_scalar(3., do_print=True))
hcb.barrier_wait()
expected = """
what: step_nr
0
what: step_nr
1"""
self.assertMultiLineStrippedEqual(expected, testing_stream.output)
class HostCallbackCallTest(jtu.JaxTestCase):
"""Tests for hcb.call"""
def setUp(self):
super().setUp()
if jtu.device_under_test() == "gpu" and jax.device_count() > 1:
raise SkipTest("host_callback broken on multi-GPU platforms (#6447)")
testing_stream.reset()
testing_stream._test_method_name = self._testMethodName
def tearDown(self) -> None:
hcb.barrier_wait("HostCallbackCallTest.tearDown")
super().tearDown()
def call_log_testing_stream(self, func, arg, *, result_shape, name=""):
"""Call `func` and log inputs and outputs to the testing stream"""
def call_log(arg):
def val2str(v):
return np.array2string(np.array(arg))
testing_stream.write(f"Call {name}({val2str(arg)})\n")
res = func(arg)
testing_stream.write(f" = {val2str(res)}\n")
return res
return hcb.call(call_log, arg, result_shape=result_shape)
def test_call_simple(self):
def f_outside(x):
return 2 * x
def fun(x):
y = hcb.call(f_outside, x + 1, result_shape=x)
return 3 * (1 + y)
arg = np.arange(24, dtype=np.int32).reshape((2, 3, 4))
self.assertAllClose(3 * (1 + 2 * (arg + 1)), fun(arg))
@parameterized.named_parameters(
jtu.cases_from_list(
dict(testcase_name=f"_{np.dtype(dtype).name}", dtype=dtype)
for dtype in jtu.dtypes.all
if dtype != np.bool_))
def test_call_types(self, dtype=np.float64):
def f_outside(x):
# Use x + x to ensure that the result type is the same
return x + x
def fun(x):
return hcb.call(f_outside, x + x, result_shape=x)
arg = np.arange(24, dtype=dtype).reshape((2, 3, 4))
self.assertAllClose(arg + arg + arg + arg, fun(arg), check_dtypes=True)
def test_call_types_bool(self, dtype=np.float64):
def f_outside(x):
return np.invert(x)
def fun(x):
return hcb.call(f_outside, x, result_shape=x)
arg = np.random.choice(a=[True, False], size=(2, 3, 4))
self.assertAllClose(np.invert(arg), fun(arg))
def test_call_tuples(self):
def f_outside(args):
x, y = args
return y, x # Swap the tuple
def fun(x):
xy = hcb.call(f_outside, (x, x + 1), result_shape=(x, x))
return 2 * xy[0] + 3 * xy[1]
arg = np.arange(24, dtype=np.int32).reshape((2, 3, 4))
self.assertAllClose(2 * (arg + 1) + 3 * arg, fun(arg))
def test_call_empty_arg(self):
"""Call with empty array."""
result = np.ones((2,), dtype=np.float32)
def f_outside(_):
return result
def fun(x):
return x + hcb.call(f_outside, (),
result_shape=api.ShapeDtypeStruct(result.shape, result.dtype))
self.assertAllClose(2. + result, fun(2.))
def test_call_empty_result(self):
"""Call returning empty array."""
result_shape = (2, 0)
def f_outside(_):
return np.ones(result_shape, dtype=np.float32)
def fun(x):
return x + hcb.call(f_outside, 1.,
result_shape=api.ShapeDtypeStruct(result_shape, np.float32))
self.assertAllClose(f_outside(0.), fun(2.))
def test_call_empty_result_inside_pytree(self):
"""Call returning a tuple with an empty array and a non-empty one."""
result_shape_0 = (2, 0)
result_shape_2 = (0,)
def f_outside(_):
return (np.ones(result_shape_0, dtype=np.float32),
np.ones((1,), dtype=np.float32),
np.ones(result_shape_2, dtype=np.float32))
def fun(x):
res = hcb.call(f_outside, 1.,
result_shape=(api.ShapeDtypeStruct(result_shape_0, np.float32),
api.ShapeDtypeStruct((1,), np.float32),
api.ShapeDtypeStruct(result_shape_2, np.float32)))
self.assertEqual(result_shape_0, res[0].shape)
self.assertEqual(result_shape_2, res[2].shape)
return x + res[1]
self.assertAllClose(2 + np.ones((1,), dtype=np.float32), fun(2.))
def test_call_empty_result_all_pytree(self):
"""Call returning a tuple of empty arrays."""
result_shape = (2, 0)
def f_outside(_):
return (np.ones(result_shape, dtype=np.float32),
np.ones(result_shape, dtype=np.float32))
def fun(x):
res = hcb.call(f_outside, 1.,
result_shape=(api.ShapeDtypeStruct(result_shape, np.float32),
api.ShapeDtypeStruct(result_shape, np.float32)))
return x + res[0] + res[1]
self.assertAllClose(np.ones(result_shape, dtype=np.float32),
fun(2.))
def test_call_no_result(self):
def f_outside(arg):
self.call_log_testing_stream(lambda x: None, arg,
result_shape=None,
name="outside")
return arg
self.assertAllClose((3., 4.), f_outside((3., 4.)))
hcb.barrier_wait()
expected = """
Call outside([3. 4.])
= [3. 4.]"""
self.assertMultiLineStrippedEqual(expected, testing_stream.output)
def test_call_cond(self):
def f_outside(args):
x, y = args
return x * y
def loop(x, use_outside=True):
def body(i, acc):
return lax.cond(i % 2 == 1,
lambda _: (hcb.call(f_outside, (acc, i),
result_shape=acc)
if use_outside else f_outside((acc, i))),
lambda _: acc,
None)
return lax.fori_loop(0, 18, body, x)
res_inside = loop(1.2, use_outside=False)
self.assertAllClose(res_inside, api.jit(loop)(1.2))
def test_call_jit_scan_call(self):
def f_outside(x):
return x
def loop(x, use_outside=True):
def body(carry, i):
if use_outside:
return carry + hcb.call(f_outside, i,
result_shape=i), None
else:
return carry + i, None
return lax.scan(body, 0, x)
x = np.arange(5, dtype=np.int32)
res_outside = api.jit(partial(loop, use_outside=True))(x)
self.assertAllClose(res_outside, loop(x, use_outside=False))
def test_call_doc_example1(self):
"""Examples from the documentation: simplest, call a function"""
def host_eig(x):
return np.linalg.eigvals(x)
shape = (2, 5, 4, 4)
m = np.ones(shape, dtype=np.float32)
def fun(m):
eig_m = hcb.call(host_eig, m,
result_shape=api.ShapeDtypeStruct(m.shape[:-1], m.dtype))
return eig_m
expected_res = np.linalg.eigvals(m)
self.assertAllClose(expected_res, fun(m))
def test_call_doc_example_hlo(self):
"""Examples from the documentation: simplest, call a function."""
def fun1(m):
return jnp.sin(hcb.call(lambda x: np.cos,
jnp.cos(m),
result_shape=m))
m = np.ones((2,), np.float32)
helper_print_optimized_hlo(fun1, m)
def fun2(m):
x = hcb.call(lambda x: None, 2, result_shape=())
return x
m = np.ones((2,), np.float32)
helper_print_optimized_hlo(fun2, m)
def test_call_with_device(self):
def callback_func(x, device=None):
testing_stream.write(f"device: {device}\n Called with {x}")
return x
def func(x):
return hcb.call(callback_func, x,
result_shape=x,
call_with_device=True)
self.assertEqual(3., func(3.))
assertMultiDeviceOutputEqual(self, """
device: cpu:0
Called with 3.00""")
def test_call_pmap(self):
# Works for 1 or 2 devices
def callback_func(x, device=None):
testing_stream.write(f"device: {device}\n Called with {x}")
return x * np.array(3, np.int32)
def fun(x): # x: i32
return hcb.call(callback_func, x * 2,
result_shape=x,
call_with_device=True)
xv = jnp.arange(len(local_devices()), dtype=jnp.int32)
res = api.pmap(fun)(xv)
self.assertAllClose(api.pmap(lambda x: x * 6)(xv), res)
# Assertion text is for 2 devices (also works for 1 device)
assertMultiDeviceOutputEqual(self, """
device: cpu:0
Called with 0
device: cpu:1
Called with 2""")
def test_call_vmap(self):
def f_outside(x): return x
def fun(x):
return hcb.call(f_outside, x, result_shape=x)
with self.assertRaisesRegex(NotImplementedError,
"batching rules are implemented only for id_tap, not for call"):
api.vmap(fun)(np.ones((2, 3)))
@jtu.skip_on_devices("cpu", "gpu")
# TODO(necula): file XLA:GPU bug for the 'Sharding' CustomCall
def test_call_pjit(self):
devices = np.array(local_devices())
nr_devices = len(devices)
if nr_devices < 2:
raise SkipTest("test requires at least 2 devices")
print(f"test_call_pjit is running on devices {devices}.")
# x: i32[D, 3] = [[0, 1, 2], [10, 11, 12], ...]
# y: i32[3, 4]
x = jnp.arange(100, dtype=jnp.int32).reshape((10, 10))[:nr_devices, :3]
y = jnp.ones((3, 4), np.int32)
def callback_x5_func(x, device=None):
testing_stream.write(f"device: {device}\n Called with {x}")
return x * np.array(5, np.int32)
def fun(x):
xy = jnp.dot(x, y)
return hcb.call(
callback_x5_func, xy, result_shape=xy, call_with_device=True)
pjit_fun = pjit.pjit(
fun, in_axis_resources=(P("d"),), out_axis_resources=P("d"))
with maps.mesh(devices, ["d"]):
# Print the internal IR
helper_log_ir(
f"{self._testMethodName}.pjit",
pjit_fun,
x,
num_partitions=nr_devices)
res = pjit_fun(x)
expected_res = jnp.dot(x, y) * np.array(5, np.int32)
self.assertAllClose(expected_res, res, check_dtypes=False)
hcb.barrier_wait("before assertion")
# Assertion text is for 2 devices (also works for 1 device)
assertMultiDeviceOutputEqual(
self, """
device: cpu:0
Called with [[ 3 3 3 3]
[33 33 33 33]]""")
def test_call_error_bad_result_shape(self):
with self.assertRaisesRegex(
ValueError,
"The values must be either numeric scalars, or must have 'shape' and 'dtype' attributes"):
hcb.call(lambda x: x, 3., result_shape="string")
with self.assertRaisesRegex(
ValueError,
"The values must be either numeric scalars, or must have 'shape' and 'dtype' attributes"):
hcb.call(lambda x: x, 3., result_shape=lambda x: x)
hcb.barrier_wait("wait for error")
def helper_check_callback_errors(self, thunk: Callable,
expected_exc_txt: str):
"""Calls thunk() and checks for expected exceptions.
"""
if jtu.device_under_test() == "cpu":
# On CPU the runtime crashes, and the tests are all aborted
raise SkipTest("TODO: CPU runtime crashes on unexpected infeed")
elif jtu.device_under_test() == "gpu":
# On GPU we get a nice error back to Python
with self.assertRaisesRegex(
RuntimeError,
"RET_CHECK failure .* Mismatch between infeed source buffer shape s8.12345."):
thunk()
elif jtu.device_under_test() == "tpu":
# On TPU we get no error!!!
raise SkipTest("TODO: TPU runtime does not check infeed, and just computes with garbage")
# Both on GPU and TPU we also get an error during the barrier_wait at the
# end of the test. Run a barrier_wait now, to consume that error.
with self.assertRaisesRegex(
hcb.CallbackException,
re.compile(
"There were exceptions during callback processing.*Last one was:.*" +
expected_exc_txt,
re.DOTALL)):
hcb.barrier_wait("Waiting for error")
def test_call_error_callback_throws_exception(self):
def f_outside(x):
raise ValueError("user exception")
def fun(x):
return hcb.call(f_outside, x, result_shape=x)
self.helper_check_callback_errors(lambda: fun(3.),
"ValueError: user exception")
def test_call_error_callback_returns_unexpected_shape(self):
def fun(x):
return hcb.call(lambda x: (x, x), x, result_shape=x)
self.helper_check_callback_errors(lambda: fun(3.),
"Callback func .* should have returned a result with pytree")
def test_call_error_then_compute(self):
# Continue computation on device after error
def f_outside(x):
raise ValueError("user exception")
def fun(x):
x1 = hcb.call(f_outside, x, result_shape=x)
return x1
arg = np.arange(3, dtype=np.int32)
self.helper_check_callback_errors(lambda: self.assertAllClose(arg, fun(arg)),
"ValueError: user exception")
def call_jax_other_device(jax_outside_fun, arg, *, device):
"""Calls a JAX function on a specific device with simple support for reverse AD.
Functions whose name starts with "jax_outside" are called on another device,
by way of hcb.call.
"""
def run_jax_outside_fun(arg):
return api.jit(jax_outside_fun)(api.device_put(arg, device))
@api.custom_vjp
def make_call(arg):
return hcb.call(run_jax_outside_fun, arg,
result_shape=api.eval_shape(jax_outside_fun, arg))
# Define the fwd and bwd custom_vjp functions
def make_call_vjp_fwd(arg):
# Return the primal argument as the residual. Use `make_call` for the
# primal computation to enable higher-order AD.
return make_call(arg), arg # Return the primal argument as the residual
def make_call_vjp_bwd(res, ct_res):
arg = res # residual is the primal argument
def jax_outside_vjp_fun(arg_and_ct):
arg, ct = arg_and_ct
_, f_vjp = api.vjp(jax_outside_fun, arg)
ct_in, = f_vjp(ct)
return ct_in
return (call_jax_other_device(jax_outside_vjp_fun, (arg, ct_res), device=device),)
make_call.defvjp(make_call_vjp_fwd, make_call_vjp_bwd)
return make_call(arg)
class CallJaxTest(jtu.JaxTestCase):
"""Tests using `call_jax_other_device`."""
def setUp(self):
if jtu.device_under_test() == "gpu" and jax.device_count() > 1:
raise SkipTest("host_callback broken on multi-GPU platforms (#6447)")
if jtu.device_under_test() != "cpu":
assert api.devices("cpu")
self.outside_device = api.devices("cpu")[0]
else:
if len(api.devices("cpu")) == 1:
raise SkipTest("Test needs at least two devices. On CPU use XLA_FLAGS=--xla_force_host_platform_device_count=2")
self.outside_device = api.devices("cpu")[1]
super().setUp()
def test_jax_impl(self):
def f_jax(x):
return jnp.sin(x)
def f_outside(x):
return call_jax_other_device(f_jax, x, device=self.outside_device)
self.assertAllClose(f_jax(3.), f_outside(3.))
self.assertAllClose(f_jax(3.), api.jit(f_outside)(3.))
def test_jax_impl_pytree(self):
def f_jax(x):
# x : dict(a=..., b=...) and output is a list of two elements
return [jnp.sin(x["a"]), jnp.sin(x["b"])]
def f_outside(x):
return call_jax_other_device(f_jax, x, device=self.outside_device)
x = dict(a=3., b=4.)
res_jax = f_jax(x)
# print(f"outside_jaxpr = {api.make_jaxpr(f_outside)(x)}")
res_outside = f_outside(x)
self.assertAllClose(res_jax, res_outside)
def test_jax_grad(self):
def f_jax(x):
return 2. * jnp.sin(x)
def f_outside(x):
return 2. * call_jax_other_device(jnp.sin, x, device=self.outside_device)
res_jax = api.grad(f_jax)(3.)
self.assertAllClose(res_jax, api.grad(f_outside)(3.))
def test_jax_grad_pytree(self):
def f_jax(x):
# x : dict(a=..., b=...) and output is a float
return 3. * jnp.sin(x["a"]) + jnp.sin(x["b"])
def f_outside(x):
return call_jax_other_device(f_jax, x, device=self.outside_device)
x = dict(a=3., b=4.)
res_jax = api.grad(f_jax)(x)
self.assertAllClose(res_jax, api.grad(f_outside)(x))
def test_jax_grad_of_grad(self):
def f_jax(x):
return 2. * x * x * x
def f_outside(x):
return 2. * call_jax_other_device(lambda x: x * x * x, x, device=self.outside_device)
res_jax = api.grad(api.grad(f_jax))(5.)
res_outside = api.grad(api.grad(f_outside))(5.)
self.assertAllClose(res_jax, res_outside)
class OutfeedRewriterTest(jtu.JaxTestCase):
def setUp(self):
if jtu.device_under_test() == "gpu" and jax.device_count() > 1:
raise SkipTest("host_callback broken on multi-GPU platforms (#6447)")
super().setUp()
def assertRewrite(self, expected: str, func: Callable, args: Sequence,
has_input_token=True, has_output_token=True):
"""Check that the rewrite of func(*args) matches expected."""
jaxpr = api.make_jaxpr(func)(*args)
rewritten = hcb._rewrite_closed_jaxpr(jaxpr, # noqa: F841
has_input_token, has_output_token)
# Since it is somewhat annoying to update the Jaxpr assertions when we change
# the Jaxpr printing, we do not check these by default. It is recommended that
# before making changes to the code generation and Jaxpr rewriting, turn on
# the checking, update the expected Jaxpr, and then make the changes.
# assertMultiLineStrippedEqual(self, expected, str(rewritten))
del rewritten
def test_no_outfeed(self):
self.assertRewrite("""
{ lambda ; a.
let b = mul a a
c = add a b
in (c,) }""", lambda x: x + x * x, [0], has_input_token=False,
has_output_token=False)
self.assertRewrite("""
{ lambda ; a d e.
let b = mul a a
c = add a b
in (c,) }""", lambda x: x + x * x, [0], has_output_token=False)
self.assertRewrite("""
{ lambda ; a d e.
let b = mul a a
c = add a b
in (c, d, e) }""", lambda x: x + x * x, [0])
def test_simple_outfeed(self):
self.assertRewrite("""
{ lambda ; a d e.
let b = add a a
c f g = outside_call[ arg_treedef=*
callback=...
has_token=True
identity=True ] b d e
in (c, f, g) }""", lambda x: hcb.id_print(x + x), [0])
def test_simple_outfeed_without_input_token(self):
self.assertRewrite("""
{ lambda ; a b.
let e = create_token a b
f = create_token a b
c = add a b
d g h = outside_call[ arg_treedef=*
callback=...
has_token=True
identity=True ] c e f
in (d,) }""", lambda x1, x2: hcb.id_print(x1 + x2), [1, 2],
has_input_token=False, has_output_token=False)
def test_simple_outfeed_without_input_token_nor_invars(self):
self.assertRewrite("""
{ lambda ; .
let b = create_token
c = create_token
a d e = outside_call[ arg_treedef=*
callback=...
has_token=True
identity=True ] 42 b c
in (a,) }""", lambda: hcb.id_print(42), [],
has_input_token=False, has_output_token=False)
def test_multiple_tap_without_dependencies(self):
def f(x):
hcb.id_print(x, what="x")
hcb.id_print(x + 1, what="x + 1")
return 2
self.assertRewrite("""
{ lambda ; a c d.
let _ e f = outside_call[ arg_treedef=*
callback=...
has_token=True
identity=True ] a c d
b = add a 1
_ g h = outside_call[ arg_treedef=*
callback=...
has_token=True
identity=True ] b e f
in (2, g, h) }""", f, [1])
def test_cond(self):
y = jnp.ones(5) # captured const
def func(x, z):
return lax.cond(z > 0, (1, 2), lambda a: (a[0], jnp.zeros(5)),
z, lambda a: (hcb.id_print(a), y))
self.assertRewrite("""
{ lambda a ; b c h i.
let d = gt c 0
e = convert_element_type[ new_dtype=int32 ] d
f g j k =
cond[ branches=( { lambda ; a b c d f g.
let e h i = outside_call[ arg_treedef=*
callback=...
has_token=True
identity=True ] d f g
in (e, a, h, i) }
{ lambda ; f_ a b c g h.
let d = broadcast_in_dim[ broadcast_dimensions=( )
shape=(5,) ] 0.00
in (a, d, g, h) } )
linear=(False, False, False, False, False, False) ] e a 1 2 c h i
in (f, g, j, k) }""", func, [y, 5])
def test_while(self):
ct_body = jnp.ones(5, np.float32) # captured const for the body
ct_cond = jnp.ones(5, np.float32) # captured const for the conditional
def func(x):
# x: f32[5]
# c: (f32[5], f32)
return lax.while_loop(lambda c: c[1] < jnp.sum(c[0] + ct_cond),
lambda c: (ct_body, hcb.id_print(c[1]) + 1.),
(x, np.float32(1.)))
self.assertRewrite("""
{ lambda a b ; c f g.
let d e h i =
while[ body_jaxpr={ lambda ; a b c f g.
let d h i = outside_call[ arg_treedef=*
callback=...
has_token=True
identity=True ] c f g
e = add d 1.00
in (a, e, h, i) }
body_nconsts=1
cond_jaxpr={ lambda ; a b c g h.
let d = add b a
e = reduce_sum[ axes=(0,) ] d
f = lt c e
in (f,) }
cond_nconsts=1 ] a b c 1.00 f g
in (d, e, h, i) }""", func, [ct_body])
def test_while_pred_outfeed(self):
"""A while with outfeed in the pred."""
ct_body = jnp.ones(5) # captured const for the body
ct_cond = jnp.ones(2) # captured const for the conditional
def func(x):
return lax.while_loop(lambda c: hcb.id_print(ct_cond, result=c[1]) < 5,
lambda c: (ct_body, hcb.id_print(c[1]) + 1),
(x, 1))
self.assertRewrite("""
{ lambda a b ; c f g.
let j k l = xla_call[ call_jaxpr={ lambda ; a b c g h.
let d i j = outside_call[ arg_treedef=*
callback=...
has_token=True
identity=True ] a g h
e = id_tap_dep c d
f = lt e 5
in (f, i, j) }
donated_invars=(False, False, False, False, False)
name=cond_before ] a c 1 f g
bf d e h i =
while[ body_jaxpr={ lambda ; r s t u v w x.
let y z ba bb =
xla_call[ call_jaxpr={ lambda ; a b c f g.
let d h i = outside_call[ arg_treedef=*
callback=...
has_token=True
identity=True ] c f g
e = add d 1
in (a, e, h, i) }
donated_invars=(False, False, False, False, False)
name=body ] s u v w x
bc bd be =
xla_call[ call_jaxpr={ lambda ; a b c g h.
let d i j = outside_call[ arg_treedef=*
callback=...
has_token=True
identity=True ] a g h
e = id_tap_dep c d
f = lt e 5
in (f, i, j) }
donated_invars=(False, False, False, False, False)
name=cond_body ] r y z ba bb
in (bc, y, z, bd, be) }
body_nconsts=2
cond_jaxpr={ lambda ; m n o p q.
let
in (m,) }
cond_nconsts=0 ] a b j c 1 k l
in (d, e, h, i) }""", func, [ct_body])
def test_scan(self):
y = jnp.ones(5) # captured const
def func(x):
return lax.scan(lambda c, a: (hcb.id_print(c), y), (1, 2), x)
self.assertRewrite("""
{ lambda a ; b f g.
let c d h i e =
scan[ jaxpr={ lambda ; a b c g h d.
let e f i j =
outside_call[ arg_treedef=PyTreeDef(tuple, [*,*])
callback=...
has_token=True
identity=True ] b c g h
in (e, f, i, j, a) }
length=5
linear=(False, False, False, False, False, False)
num_carry=4
num_consts=1
reverse=False
unroll=1 ] a 1 2 f g b
in (c, d, e, h, i) }""", func, [y])
def test_scan_custom_jvp(self):
"""custom JVP, inside scan.
This exercises the custom_jvp_call_jaxpr primitives."""
@api.custom_jvp
def f(x):
return x * hcb.id_print(x)
@f.defjvp
def f_jvp(primals, tangents):
x, = primals
x_dot, = tangents
primal_out = f(x)
tangent_out = 3. * x * hcb.id_print(x_dot)
return primal_out, tangent_out
def g(x):
# Sum f(x_i)
return lax.scan(lambda carry, inp: (carry + f(inp), 0.),
np.full(x.shape[1:], 0.), # Like x w/o leading dim
x)[0]
arg = np.full((5,), 0.7)
self.assertRewrite("""
{ lambda ; a c d.
let b e f _ =
scan[ jaxpr={ lambda ; a e f b.
let c g h = custom_jvp_call_jaxpr[ fun_jaxpr={ lambda ; a d e.
let b f g = outside_call[ arg_treedef=*
callback=...
has_token=True
identity=True ] a d e
c = mul a b
in (c, f, g) }
num_consts=0 ] b e f
d = add a c
in (d, g, h, 0.00) }
length=5
linear=(False, False, False, False)
num_carry=3
num_consts=0
reverse=False
unroll=1 ] 0.00 c d a
in (b, e, f) }""", g, [arg])
self.assertRewrite("""
{ lambda ; a d e.
let _ _ f g _ b =
scan[ jaxpr={ lambda ; a b h i c d.
let e j k = custom_jvp_call_jaxpr[ fun_jaxpr={ lambda ; a d e.
let b f g = outside_call[ arg_treedef=*
callback=...
has_token=True
identity=True ] a d e
c = mul a b
in (c, f, g) }
num_consts=0 ] c h i
f = add a e
g = mul c 3.00
in (f, *, j, k, 0.00, g) }
length=5
linear=(False, True, False, False, False, True)
num_carry=4
num_consts=0
reverse=False
unroll=1 ] 0.00 * d e a *
_ _ h i _ c =
scan[ jaxpr={ lambda ; a b g h c d.
let e = mul b d
f i j = outside_call[ arg_treedef=*
callback=...
has_token=True
identity=True
transforms=(('transpose',),) ] e g h
in (*, b, i, j, *, f) }
length=5
linear=(True, True, False, False, True, False)
num_carry=4
num_consts=0
reverse=True
unroll=1 ] * 1.00 f g * b
in (c, h, i) }""", api.grad(g), [arg])
def test_scan_custom_vjp(self):
"""custom VJP, inside scan.
This exercises the custom_vjp_call_jaxpr primitives."""
@api.custom_vjp
def f(x):
return x * hcb.id_print(x)
# f_fwd: a -> (b, residual)
def f_fwd(x):
return f(x), 3. * x
# f_bwd: (residual, CT b) -> [CT a]
def f_bwd(residual, ct_b):
return residual * hcb.id_print(ct_b),
f.defvjp(f_fwd, f_bwd)
def g(x):
# Sum f(x_i)
return lax.scan(lambda carry, inp: (carry + f(inp), 0.),
np.full(x.shape[1:], 0.), # Like x w/o leading dim
x)[0]
arg = np.full((2,), 0.7)
self.assertRewrite("""
{ lambda ; a c d.
let b e f _ =
scan[ jaxpr={ lambda ; a e f b.
let c g h = custom_vjp_call_jaxpr[
fun_jaxpr={ lambda ; a d e.
let b f g = outside_call[ arg_treedef=*
callback=...
has_token=True
identity=True ] a d e
c = mul a b
in (c, f, g) }
num_consts=0
] b e f
d = add a c
in (d, g, h, 0.00) }
length=2
linear=(False, False, False, False)
num_carry=3
num_consts=0
reverse=False
unroll=1 ] 0.00 c d a
in (b, e, f) }""", g, [arg])
self.assertRewrite("""
{ lambda ; a d e.
let _ _ f g _ b =
scan[ jaxpr={ lambda ; a b h i c d.
let e j k = custom_vjp_call_jaxpr[
fun_jaxpr={ lambda ; a d e.
let b f g = outside_call[ arg_treedef=*
callback=...
has_token=True
identity=True ] a d e
c = mul a b
in (c, f, g) }
num_consts=0
] c h i
f = add a e
g = mul c 3.00
in (f, *, j, k, 0.00, g) }
length=2
linear=(False, True, False, False, False, True)
num_carry=4
num_consts=0
reverse=False
unroll=1 ] 0.00 * d e a *
_ _ h i _ c =
scan[ jaxpr={ lambda ; a b g h c d.
let e i j = outside_call[ arg_treedef=*
callback=...
has_token=True
identity=True ] b g h
f = mul d e
in (*, b, i, j, *, f) }
length=2
linear=(True, True, False, False, True, False)
num_carry=4
num_consts=0
reverse=True
unroll=1 ] * 1.00 f g * b
in (c, h, i) }""", api.grad(g), [arg])
def test_remat_loop(self):
def f(k, x):
x = hcb.id_print(k + x)
return -k * x
def loss(k):
return lax.fori_loop(0, 1, api.remat(f), k)
self.assertRewrite("""
{ lambda ; a c d.
let _ _ b e f =
while[ body_jaxpr={ lambda ; a b c f g.
let d = add a 1
e h i = remat_call[ call_jaxpr={ lambda ; a b g h.
let c = add a b
d i j = outside_call[ arg_treedef=*
callback=...
has_token=True
identity=True ] c g h
e = neg a
f = mul e d
in (f, i, j) }
concrete=False
name=f ] a c f g
in (d, b, e, h, i) }
body_nconsts=0
cond_jaxpr={ lambda ; a b c e f.
let d = lt a b
in (d,) }
cond_nconsts=0 ] 0 1 a c d
in (b, e, f) }""", loss, [2])
def test_named_call(self):
def tap_scalar(init, do_print=False):
@partial(api.named_call, name="step")
def step(acc, step_nr):
acc = acc + step_nr
maybe_print(do_print, step_nr, what="step_nr")
return acc, None
return lax.scan(step, init, np.arange(2, dtype=np.int32))
self.assertRewrite("""
{ lambda a ; b d e.
let c = scan[ jaxpr={ lambda ; a b.
let c = named_call[ call_jaxpr={ lambda ; a b.
let c = add a b
in (c,) }
name=step ] a b
in (c,) }
length=2
linear=(False, False)
num_carry=1
num_consts=0
reverse=False
unroll=1 ] b a
in (c, d, e) }""", tap_scalar, [np.int32(3)])
def test_pmap(self):
def f(xv):
api.pmap(lambda x: jnp.sin(hcb.id_print(x, tap_with_device=True)),
axis_name="i")(xv)
self.assertRewrite("""
{ lambda ; a b c.
let _ d e = xla_pmap[ axis_name=i
axis_size=1
backend=None
call_jaxpr={ lambda ; a d e.
let b f g = outside_call[ arg_treedef=*
callback=...
has_token=True
identity=True ] a d e
c = sin b
in (c, f, g) }
devices=None
donated_invars=(False, False, False)
global_arg_shapes=(None,)
global_axis_size=None
in_axes=(0, 0, 0)
name=<lambda>
out_axes=(0, 0, 0) ] a b c
in (d, e) }""", f, [np.array([2.], dtype=np.float32)])
if __name__ == "__main__":
absltest.main(testLoader=jtu.JaxTestLoader())
|
the-stack_0_14660 | """Define a class for managing a thread pool with delayed execution.
Attributes:
log (logging.Logger): Logger for current module.
"""
import time
import logging
from concurrent import futures
from threading import Lock
from threading import Thread
from .singleton import singleton
log = logging.getLogger("ECC")
@singleton
class ThreadPool:
"""Thread pool that makes sure we don't get recurring jobs.
Whenever a job is submitted we check if there is already a job like this
running. If it is, we try to cancel the previous job. We are only able to
cancel this job if it has not started yet.
Example:
active: ['update', 'info'] and 'update' is running.
incoming: 'update' and then another 'update'.
We will try to cancel the first 'update' and will fail as it is running. We
still cancel the 'info' job as it has less priority (no need to get info if
the translation unit is not up to date). We add a new 'update' to the list.
Now there are two 'update' jobs, one running, one pending. Adding another
'update' job will replace the pending update job.
"""
def __init__(self, max_workers=1):
"""Create a thread pool.
Args:
max_workers (int): Maximum number of parallel workers.
"""
self.__thread_pool = futures.ThreadPoolExecutor(
max_workers=max_workers)
self.__lock = Lock()
self.__progress_lock = Lock()
self.__show_animation = False
self.__progress_update_delay = 0.1
self.__progress_idle_delay = 0.3
# All the jobs that are currently active are stored here.
self.__active_jobs = []
# start animation thread
self.__progress_status = None
self.__progress_thread = Thread(target=self.__animate_progress,
daemon=True).start()
@property
def progress_status(self):
"""Return current progress status."""
return self.__progress_status
@progress_status.setter
def progress_status(self, val):
"""Set progress status instance."""
with self.__progress_lock:
self.__progress_status = val
def new_job(self, job):
"""Add a new job to be submitted to a thread pool.
Args:
job (ThreadJob): A job to be run asynchronously.
"""
# Cancel all the jobs with the same name that are already running.
# Iterating over a list is atomic in python, so we should be safe.
for active_job in self.__active_jobs:
if job.overrides(active_job):
if active_job.future.cancel():
log.debug("Canceled job: '%s'", job)
else:
log.debug("Cannot cancel job: '%s'", active_job)
# Submit a new job to the pool.
future = self.__thread_pool.submit(job.function, *job.args)
future.add_done_callback(job.callback)
future.add_done_callback(self.__on_job_done)
job.future = future # Set the future for this job.
with self.__lock:
self.__active_jobs.append(job)
self.__show_animation = True
def __on_job_done(self, future):
"""Call this when the job is done or cancelled."""
# We want to clear the old list and alter the positions of elements.
# This is a potentially dangerous operation, so protect it by a mutex.
with self.__lock:
self.__active_jobs[:] = [
job for job in self.__active_jobs if not job.future.done()]
if len(self.__active_jobs) < 1:
self.__show_animation = False
def __animate_progress(self):
"""Change the status message, mostly used to animate progress."""
while True:
sleep_time = self.__progress_idle_delay
with self.__progress_lock:
if not self.__progress_status:
sleep_time = self.__progress_idle_delay
elif self.__show_animation:
self.__progress_status.show_next_message()
sleep_time = self.__progress_update_delay
else:
self.__progress_status.show_ready_message()
sleep_time = self.__progress_idle_delay
# Allow some time for progress status to be updated.
time.sleep(sleep_time)
|
the-stack_0_14661 | import StringIO
import os
import unittest
from rnn_prof import simple_rnn
from rnn_prof.data.wrapper import load_data
from rnn_prof.data.rnn import build_nn_data
TESTDATA_FILENAME = os.path.join(os.path.dirname(__file__), 'data', 'test_assist_data.csv.gz')
class TestRnn(unittest.TestCase):
def test_initialization(self):
""" Just make sure initialize doesn't cause the interpreter to crash """
data, _, item_ids, _, _ = load_data(TESTDATA_FILENAME, 'assistments')
num_questions = len(item_ids)
nn_data = build_nn_data(data, num_questions)
pivot = len(nn_data) // 2
train_data = nn_data[:pivot]
test_data = nn_data[pivot:]
opts = simple_rnn.RnnOpts(hidden_dim=20)
simple_rnn.SimpleRnn(train_data, opts, test_data=test_data)
def test_dump_and_load(self):
"""
Test dumping and loading the SimpleRnn and make sure that all of its properties remain in
shape.
"""
data, _, item_ids, _, _ = load_data(TESTDATA_FILENAME, 'assistments')
num_questions = len(item_ids)
nn_data = build_nn_data(data, num_questions)
pivot = len(nn_data) // 2
train_data = nn_data[:pivot]
max_compress_dim = 10
hidden_dim = 20
recurrent = False
grad_norm_limit = 1.0
first_learning_rate = 20.0
decay_rate = 0.5
largest_grad = 4.0
batch_threshold = 0.8
opts = simple_rnn.RnnOpts(max_compress_dim=max_compress_dim, hidden_dim=hidden_dim,
recurrent=recurrent, grad_norm_limit=grad_norm_limit,
largest_grad=largest_grad, batch_threshold=batch_threshold,
first_learning_rate=first_learning_rate, decay_rate=decay_rate)
original = simple_rnn.SimpleRnn(train_data, opts)
dumped = StringIO.StringIO()
original.dump(dumped)
dumped_str = dumped.getvalue()
dumped_reader = StringIO.StringIO(dumped_str)
recalled = simple_rnn.SimpleRnn.load(dumped_reader)
for attr in ('max_compress_dim', 'recurrent', 'grad_norm_limit',
'first_learning_rate', 'decay_rate', 'largest_grad', 'batch_threshold'):
self.assertEqual(getattr(original.opts, attr), getattr(recalled.opts, attr),
"%s was changed" % attr)
|
the-stack_0_14663 | # -*- coding: utf-8 -*-
import MeCab
from .tokenizer_none import NoneTokenizer
class TokenizerJaMecab(NoneTokenizer):
def __init__(self):
self.tagger = MeCab.Tagger("-Owakati")
# make sure the dictionary is IPA
# sacreBLEU is only compatible with 0.996.5 for now
# Please see: https://github.com/mjpost/sacrebleu/issues/94
d = self.tagger.dictionary_info()
assert d.size == 392126, \
"Please make sure to use IPA dictionary for MeCab"
assert d.next is None
def __call__(self, line):
"""
Tokenizes an Japanese input line using MeCab morphological analyzer.
:param line: a segment to tokenize
:return: the tokenized line
"""
line = line.strip()
sentence = self.tagger.parse(line).strip()
return sentence
def signature(self):
"""
Returns the MeCab parameters.
:return: signature string
"""
signature = self.tagger.version() + "-IPA"
return 'ja-mecab-' + signature
|
the-stack_0_14664 | # Linear autoencoder (ie PCA) applied to a 3d dataset projecting to 2d
#https://github.com/ageron/handson-ml2/blob/master/17_autoencoders_and_gans.ipynb
import numpy as np
import matplotlib.pyplot as plt
import os
figdir = "../figures"
def save_fig(fname): plt.savefig(os.path.join(figdir, fname))
import tensorflow as tf
from tensorflow import keras
from sklearn.decomposition import PCA
from mpl_toolkits import mplot3d
from mpl_toolkits.mplot3d import Axes3D
np.random.seed(4)
def generate_3d_data(m, w1=0.1, w2=0.3, noise=0.1):
angles = np.random.rand(m) * 3 * np.pi / 2 - 0.5
data = np.empty((m, 3))
data[:, 0] = np.cos(angles) + np.sin(angles)/2 + noise * np.random.randn(m) / 2
data[:, 1] = np.sin(angles) * 0.7 + noise * np.random.randn(m) / 2
data[:, 2] = data[:, 0] * w1 + data[:, 1] * w2 + noise * np.random.randn(m)
return data
X_train = generate_3d_data(60)
X_train = X_train - X_train.mean(axis=0, keepdims=0)
np.random.seed(42)
tf.random.set_seed(42)
encoder = keras.models.Sequential([keras.layers.Dense(2, input_shape=[3])])
decoder = keras.models.Sequential([keras.layers.Dense(3, input_shape=[2])])
autoencoder = keras.models.Sequential([encoder, decoder])
autoencoder.compile(loss="mse", optimizer=keras.optimizers.SGD(lr=1.5))
history = autoencoder.fit(X_train, X_train, epochs=20)
codings = encoder.predict(X_train)
X = X_train
fig = plt.figure().gca(projection='3d')
fig.scatter(X[:,0], X[:,1], X[:,2], s=50, marker='o')
save_fig("linear-autoecoder-data3d.pdf")
plt.show()
fig = plt.figure(figsize=(4,3))
plt.plot(codings[:,0], codings[:, 1], "b.")
plt.xlabel("$z_1$", fontsize=18)
plt.ylabel("$z_2$", fontsize=18, rotation=0)
plt.grid(True)
save_fig("linear-autoencoder-embedding.pdf")
plt.show()
# PCA version
pca = PCA(n_components=2)
mu = np.mean(X_train, axis=0)
Xc = X_train - mu # center the data
pca.fit(Xc)
W = pca.components_.T # D*K
Z = np.dot(Xc, W) # N * K latent scores
Xrecon = np.dot(Z, W.T) + mu # N*D
fig = plt.figure(figsize=(4,3))
plt.plot(Z[:,0], Z[:, 1], "b.")
plt.xlabel("$z_1$", fontsize=18)
plt.ylabel("$z_2$", fontsize=18, rotation=0)
plt.grid(True)
save_fig("linear-autoencoder-pca.pdf")
plt.show()
|
the-stack_0_14665 | """
Defines the NotebookCell class
"""
#***************************************************************************************************
# Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
# Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights
# in this software.
# 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 or in the LICENSE file in the root pyGSTi directory.
#***************************************************************************************************
import json as _json
import os as _os
class NotebookCell(object):
"""
Struct representing either a code or markdown cell
Parameters
----------
cell_type : str, optional
Tag for the cell: either 'code' or 'markdown'
source : list, optional
A list of strings that are the lines of code/markdown in the cell.
"""
def __init__(self, cell_type='code', source=None):
'''
Build a notebook cell
Parameters
----------
cell_type : str, optional
tag for the cell: either 'code' or 'markdown'
source : list(str), optional
lines of code/markdown in the cell
'''
if source is None:
source = []
self.cellType = cell_type
self.source = source
def to_json_dict(self):
"""
Convert this cell to a json representation of a cell, using a default template
Returns
-------
dict
"""
if self.cellType == 'markdown':
templateFilename = 'MDcell.json'
elif self.cellType == 'code':
templateFilename = 'CodeCell.json'
templateFilename = _os.path.join(_os.path.dirname(_os.path.abspath(__file__)),
'templates', templateFilename)
with open(templateFilename, 'r') as infile:
cellDict = _json.load(infile)
cellDict['source'].extend(self.source)
return cellDict
|
the-stack_0_14667 | import os
from flask import g, current_app
from .utils import Singleton
class MediaFinder(metaclass=Singleton):
def __init__(self, path):
self.path = path
self._collection = []
for root, dirs, files in os.walk(path):
for name in files:
fname = os.path.abspath(os.path.join(root, name))
size = os.stat(fname).st_size
self._collection.append({'name': fname, 'size': size})
self._collection.sort(key=lambda x: x['name'])
self._collection = {x['name']: x['size'] for x in self._collection}
@property
def collection(self):
return self._collection
def get_media_finder():
if 'media_finder' not in g:
g.media_finder = MediaFinder(current_app.config['MEDIA_DIR'])
return g.media_finder
|
the-stack_0_14670 | # Copyright 2018, Kay Hayen, mailto:[email protected]
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# 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.
#
""" Common test infrastructure functions. To be used by test runners. """
from __future__ import print_function
import ast
import atexit
import os
import re
import shutil
import subprocess
import sys
import tempfile
from contextlib import contextmanager
from nuitka.Tracing import my_print
from nuitka.utils.AppDirs import getAppDir, getCacheDir
from nuitka.utils.Execution import check_output
from nuitka.utils.FileOperations import makePath, removeDirectory
from .SearchModes import (
SearchModeBase,
SearchModeByPattern,
SearchModeCoverage,
SearchModeResume
)
def check_result(*popenargs, **kwargs):
if "stdout" in kwargs:
raise ValueError("stdout argument not allowed, it will be overridden.")
process = subprocess.Popen(
stdout = subprocess.PIPE,
*popenargs,
**kwargs
)
_unused_output, _unused_err = process.communicate()
retcode = process.poll()
if retcode:
return False
else:
return True
def goMainDir():
# Go its own directory, to have it easy with path knowledge.
os.chdir(
os.path.dirname(
os.path.abspath(sys.modules[ "__main__" ].__file__)
)
)
_python_version = None
_python_arch = None
_python_executable = None
def setup(suite = "", needs_io_encoding = False, silent = False, go_main = True):
if go_main:
goMainDir()
if "PYTHON" not in os.environ:
os.environ["PYTHON"] = sys.executable
# Allow test code to use this to make caching specific.
os.environ["NUITKA_TEST_SUITE"] = suite
# Allow providing 33, 27, and expand that to python2.7
if len(os.environ["PYTHON"]) == 2 and \
os.environ["PYTHON"].isdigit() and \
os.name != "nt":
os.environ["PYTHON"] = "python%s.%s" % (
os.environ["PYTHON"][0],
os.environ["PYTHON"][1]
)
if needs_io_encoding and "PYTHONIOENCODING" not in os.environ:
os.environ["PYTHONIOENCODING"] = "utf-8"
version_output = check_output(
(
os.environ["PYTHON"],
"-c",
"""\
import sys, os;\
print(".".join(str(s) for s in list(sys.version_info)[:3]));\
print(("x86_64" if "AMD64" in sys.version else "x86") if os.name == "nt" else os.uname()[4]);\
print(sys.executable);\
""",
),
stderr = subprocess.STDOUT
)
global _python_version, _python_arch, _python_executable # singleton, pylint: disable=global-statement
_python_version = version_output.split(b"\n")[0].strip()
_python_arch = version_output.split(b"\n")[1].strip()
_python_executable = version_output.split(b"\n")[2].strip()
if sys.version.startswith('3'):
_python_arch = _python_arch.decode("utf-8")
_python_version = _python_version.decode("utf-8")
_python_executable = _python_executable.decode("utf-8")
if not silent:
my_print("Using concrete python", _python_version, "on", _python_arch)
assert type(_python_version) is str, repr(_python_version)
assert type(_python_arch) is str, repr(_python_arch)
assert type(_python_executable) is str, repr(_python_executable)
if "COVERAGE_FILE" not in os.environ:
os.environ["COVERAGE_FILE"] = os.path.join(
os.path.dirname(__file__),
"..",
"..",
"..",
".coverage"
)
return _python_version
tmp_dir = None
def getTempDir():
# Create a temporary directory to work in, automatically remove it in case
# it is empty in the end.
global tmp_dir # singleton, pylint: disable=global-statement
if tmp_dir is None:
tmp_dir = tempfile.mkdtemp(
prefix = os.path.basename(
os.path.dirname(
os.path.abspath(sys.modules[ "__main__" ].__file__)
)
) + '-',
dir = tempfile.gettempdir() if
not os.path.exists("/var/tmp") else
"/var/tmp"
)
def removeTempDir():
removeDirectory(
path = tmp_dir,
ignore_errors = True
)
atexit.register(removeTempDir)
return tmp_dir
def convertUsing2to3(path, force = False):
command = [
os.environ["PYTHON"],
"-m",
"py_compile",
path
]
if not force:
with open(path) as source_file:
if "xrange" not in source_file.read():
with open(os.devnull, 'w') as stderr:
if check_result(command, stderr = stderr):
return path, False
filename = os.path.basename(path)
new_path = os.path.join(getTempDir(), filename)
# This may already be a temp file, e.g. because of construct creation.
try:
shutil.copy(path, new_path)
except shutil.Error:
pass
# For Python2.6 and 3.2 the -m lib2to3 was not yet supported.
use_binary = sys.version_info[:2] in ((2,6), (3,2))
if use_binary:
# On Windows, we cannot rely on 2to3 to be in the path.
if os.name == "nt":
command = [
sys.executable,
os.path.join(
os.path.dirname(sys.executable),
"Tools/Scripts/2to3.py"
)
]
else:
command = [
"2to3"
]
else:
command = [
sys.executable,
"-m",
"lib2to3",
]
command += [
"-w",
"-n",
"--no-diffs",
new_path
]
with open(os.devnull, 'w') as devnull:
check_output(
command,
stderr = devnull
)
with open(new_path) as result_file:
data = result_file.read()
with open(new_path, 'w') as result_file:
result_file.write("__file__ = %r\n" % os.path.abspath(path))
result_file.write(data)
return new_path, True
def decideFilenameVersionSkip(filename):
""" Make decision whether to skip based on filename and Python version.
This codifies certain rules that files can have as suffixes or prefixes
to make them be part of the set of tests executed for a version or not.
Generally, an ening of "<major><minor>.py" indicates that it must be that
Python version or higher. There is no need for ending in "26.py" as this
is the minimum version anyway.
The "_2.py" indicates a maxmimum version of 2.7, i.e. not Python 3.x, for
language syntax no more supported.
"""
# This will make many decisions with immediate returns.
# pylint: disable=too-many-return-statements
assert type(filename) is str
assert type(_python_version) is str
# Skip runner scripts by default.
if filename.startswith("run_"):
return False
# Skip tests that require Python 2.7 at least.
if filename.endswith("27.py") and _python_version.startswith("2.6"):
return False
if filename.endswith("_2.py") and _python_version.startswith('3'):
return False
# Skip tests that require Python 3.2 at least.
if filename.endswith("32.py") and _python_version < "3.2":
return False
# Skip tests that require Python 3.3 at least.
if filename.endswith("33.py") and _python_version < "3.3":
return False
# Skip tests that require Python 3.4 at least.
if filename.endswith("34.py") and _python_version < "3.4":
return False
# Skip tests that require Python 3.5 at least.
if filename.endswith("35.py") and _python_version < "3.5":
return False
# Skip tests that require Python 3.6 at least.
if filename.endswith("36.py") and _python_version < "3.6":
return False
return True
def _removeCPythonTestSuiteDir():
# Cleanup, some tests apparently forget that.
try:
if os.path.isdir("@test"):
removeDirectory("@test", ignore_errors = False)
elif os.path.isfile("@test"):
os.unlink("@test")
except OSError:
# TODO: Move this into removeDirectory maybe. Doing an external
# call as last resort could be a good idea.
# This seems to work for broken "lnk" files.
if os.name == "nt":
os.system("rmdir /S /Q @test")
if os.path.exists("@test"):
raise
def compareWithCPython(dirname, filename, extra_flags, search_mode, needs_2to3):
""" Call the comparison tool. For a given directory filename.
The search mode decides if the test case aborts on error or gets extra
flags that are exceptions.
"""
if dirname is None:
path = filename
else:
path = os.path.join(dirname, filename)
# Apply 2to3 conversion if necessary.
if needs_2to3:
path, converted = convertUsing2to3(path)
else:
converted = False
command = [
sys.executable,
os.path.join("..", "..", "bin", "compare_with_cpython"),
path,
"silent"
]
if extra_flags is not None:
command += extra_flags
command += search_mode.getExtraFlags(dirname, filename)
# Cleanup before and after test stage directory.
_removeCPythonTestSuiteDir()
try:
result = subprocess.call(
command
)
except KeyboardInterrupt:
result = 2
# Cleanup before and after test stage directory.
_removeCPythonTestSuiteDir()
if result != 0 and \
result != 2 and \
search_mode.abortOnFinding(dirname, filename):
my_print("Error exit!", result)
sys.exit(result)
if converted:
os.unlink(path)
if result == 2:
sys.stderr.write("Interrupted, with CTRL-C\n")
sys.exit(2)
def checkCompilesNotWithCPython(dirname, filename, search_mode):
if dirname is None:
path = filename
else:
path = os.path.join(dirname, filename)
command = [
_python_executable,
"-mcompileall",
path
]
try:
result = subprocess.call(
command
)
except KeyboardInterrupt:
result = 2
if result != 1 and \
result != 2 and \
search_mode.abortOnFinding(dirname, filename):
my_print("Error exit!", result)
sys.exit(result)
def checkSucceedsWithCPython(filename):
command = [
_python_executable,
filename
]
result = subprocess.call(
command,
stdout = open(os.devnull,'w'),
stderr = subprocess.STDOUT
)
return result == 0
def hasDebugPython():
# On Debian systems, these work.
debug_python = os.path.join("/usr/bin/", os.environ["PYTHON"] + "-dbg")
if os.path.exists(debug_python):
return True
# On Windows systems, these work.
debug_python = os.environ["PYTHON"]
if debug_python.lower().endswith(".exe"):
debug_python = debug_python[:-4]
debug_python = debug_python + "_d.exe"
if os.path.exists(debug_python):
return True
# For other Python, if it's the one also executing the runner, which is
# very probably the case, we check that. We don't check the provided
# binary here, this could be done as well.
if sys.executable == os.environ["PYTHON"] and \
hasattr(sys, "gettotalrefcount"):
return True
# Otherwise no.
return False
def getArchitecture():
if os.name == "nt":
if "AMD64" in sys.version:
return "x86_64"
else:
return "x86"
else:
return os.uname()[4] # @UndefinedVariable
def getDependsExePath():
if "APPDATA" not in os.environ:
sys.exit("Error, standalone mode cannot find 'APPDATA' environment.")
nuitka_app_dir = getAppDir()
depends_dir = os.path.join(
nuitka_app_dir,
_python_arch,
)
depends_exe = os.path.join(
depends_dir,
"depends.exe"
)
assert os.path.exists(depends_exe), depends_exe
return depends_exe
def isExecutableCommand(command):
path = os.environ["PATH"]
suffixes = (".exe",) if os.name == "nt" else ("",)
for part in path.split(os.pathsep):
if not part:
continue
for suffix in suffixes:
if os.path.isfile(os.path.join(part, command + suffix)):
return True
return False
def getRuntimeTraceOfLoadedFiles(path, trace_error = True):
""" Returns the files loaded when executing a binary. """
# This will make a crazy amount of work, pylint: disable=too-many-branches,too-many-statements
result = []
if os.name == "posix":
if sys.platform == "darwin" or \
sys.platform.startswith("freebsd"):
if not isExecutableCommand("dtruss"):
sys.exit(
"""\
Error, needs 'dtruss' on your system to scan used libraries."""
)
if not isExecutableCommand("sudo"):
sys.exit(
"""\
Error, needs 'sudo' on your system to scan used libraries."""
)
args = (
"sudo",
"dtruss",
"-t",
"open",
path
)
else:
if not isExecutableCommand("strace"):
sys.exit(
"""\
Error, needs 'strace' on your system to scan used libraries."""
)
args = (
"strace",
"-e", "file",
"-s4096", # Some paths are truncated otherwise.
path
)
process = subprocess.Popen(
args = args,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE
)
_stdout_strace, stderr_strace = process.communicate()
exit_strace = process.returncode
if exit_strace != 0:
if str is not bytes:
stderr_strace = stderr_strace.decode("utf8")
my_print(stderr_strace, file = sys.stderr)
sys.exit("Failed to run strace.")
open(path+".strace","wb").write(stderr_strace)
for line in stderr_strace.split(b"\n"):
if process.returncode != 0 and trace_error:
my_print(line)
if not line:
continue
# Don't consider files not found. The "site" module checks lots
# of things.
if b"ENOENT" in line:
continue
if line.startswith(b"stat(") and b"S_IFDIR" in line:
continue
# Allow stats on the python binary, and stuff pointing to the
# standard library, just not uses of it. It will search there
# for stuff.
if line.startswith(b"lstat(") or \
line.startswith(b"stat(") or \
line.startswith(b"readlink("):
filename = line[line.find(b"(")+2:line.find(b", ")-1]
# At least Python3.7 considers the default Python3 path.
if filename == b"/usr/bin/python3":
continue
if filename in (b"/usr/bin/python3." + version for version in (b"5", b"6", b"7")):
continue
binary_path = _python_executable
if str is not bytes:
binary_path = binary_path.encode("utf-8")
found = False
while binary_path:
if filename == binary_path:
found = True
break
if binary_path == os.path.dirname(binary_path):
break
binary_path = os.path.dirname(binary_path)
if filename == os.path.join(binary_path, b"python" + _python_version[:3].encode("utf8")):
found = True
continue
if found:
continue
result.extend(
os.path.abspath(match)
for match in
re.findall(b'"(.*?)(?:\\\\0)?"', line)
)
if sys.version.startswith('3'):
result = [s.decode("utf-8") for s in result]
elif os.name == "nt":
subprocess.call(
(
getDependsExePath(),
"-c",
"-ot%s" % path + ".depends",
"-f1",
"-pa1",
"-ps1",
"-pp0",
"-pl1",
path
)
)
inside = False
for line in open(path + ".depends"):
if "| Module Dependency Tree |" in line:
inside = True
continue
if not inside:
continue
if "| Module List |" in line:
break
if ']' not in line:
continue
# Skip missing DLLs, apparently not needed anyway.
if '?' in line[:line.find(']')]:
continue
dll_filename = line[line.find(']')+2:-1]
assert os.path.isfile(dll_filename), dll_filename
# The executable itself is of course exempted.
if os.path.normcase(dll_filename) == \
os.path.normcase(os.path.abspath(path)):
continue
dll_filename = os.path.normcase(dll_filename)
result.append(dll_filename)
os.unlink(path + ".depends")
result = list(sorted(set(result)))
return result
def checkRuntimeLoadedFilesForOutsideAccesses(loaded_filenames, white_list):
# A lot of special white listing is required.
# pylint: disable=too-many-branches,too-many-statements
result = []
for loaded_filename in loaded_filenames:
loaded_filename = os.path.normpath(loaded_filename)
loaded_filename = os.path.normcase(loaded_filename)
loaded_basename = os.path.basename(loaded_filename)
ok = False
for entry in white_list:
if loaded_filename.startswith(entry):
ok = True
while entry:
old_entry = entry
entry = os.path.dirname(entry)
if old_entry == entry:
break
if loaded_filename == entry:
ok = True
break
if ok:
continue
if loaded_filename.startswith("/etc/"):
continue
if loaded_filename.startswith("/proc/") or loaded_filename == "/proc":
continue
if loaded_filename.startswith("/dev/"):
continue
if loaded_filename.startswith("/tmp/"):
continue
if loaded_filename.startswith("/run/"):
continue
if loaded_filename.startswith("/sys/"):
continue
if loaded_filename.startswith("/usr/lib/locale/"):
continue
if loaded_filename.startswith("/usr/share/locale/"):
continue
if loaded_filename.startswith("/usr/share/X11/locale/"):
continue
# Themes may of course be loaded.
if loaded_filename.startswith("/usr/share/themes"):
continue
if "gtk" in loaded_filename and "/engines/" in loaded_filename:
continue
# Terminal info files are OK too.
if loaded_filename.startswith("/lib/terminfo/"):
continue
# System C libraries are to be expected.
if loaded_basename.startswith((
"libc.so.",
"libpthread.so.",
"libdl.so.",
"libm.so.",
)):
continue
# Taking these from system is harmless and desirable
if loaded_basename.startswith((
"libz.so",
"libutil.so",
"libgcc_s.so",
)):
continue
# TODO: Unclear, loading gconv from filesystem of installed system
# may be OK or not. I think it should be.
if loaded_basename == "gconv-modules.cache":
continue
if "/gconv/" in loaded_filename:
continue
if loaded_basename.startswith("libicu"):
continue
# GTK may access X files.
if loaded_basename == ".Xauthority":
continue
result.append(loaded_filename)
return result
def hasModule(module_name):
result = subprocess.call(
(
os.environ["PYTHON"],
"-c"
"import %s" % module_name
),
stdout = open(os.devnull,'w'),
stderr = subprocess.STDOUT
)
return result == 0
m1 = {}
m2 = {}
def snapObjRefCntMap(before):
import gc
if before:
m = m1
else:
m = m2
for x in gc.get_objects():
if x is m1:
continue
if x is m2:
continue
m[ str(x) ] = sys.getrefcount(x)
def checkReferenceCount(checked_function, max_rounds = 10):
assert sys.exc_info() == (None, None, None), sys.exc_info()
print(checked_function.__name__ + ": ", end = "")
sys.stdout.flush()
ref_count1 = 17
ref_count2 = 17
explain = False
import gc
assert max_rounds > 0
for count in range(max_rounds):
gc.collect()
ref_count1 = sys.gettotalrefcount() # @UndefinedVariable
if explain and count == max_rounds - 1:
snapObjRefCntMap(True)
checked_function()
# Not allowed, but happens when bugs occur.
assert sys.exc_info() == (None, None, None), sys.exc_info()
gc.collect()
if explain and count == max_rounds - 1:
snapObjRefCntMap(False)
ref_count2 = sys.gettotalrefcount() # @UndefinedVariable
if ref_count1 == ref_count2:
result = True
print("PASSED")
break
# print count, ref_count1, ref_count2
else:
result = False
print("FAILED", ref_count1, ref_count2, "leaked", ref_count2 - ref_count1)
if explain:
assert m1
assert m2
for key in m1:
if key not in m2:
print('*' * 80)
print("extra", key)
elif m1[key] != m2[key]:
print('*' * 80)
print(m1[key], "->", m2[key], key)
else:
pass
# print m1[key]
assert sys.exc_info() == (None, None, None), sys.exc_info()
gc.collect()
sys.stdout.flush()
return result
def createSearchMode():
search_mode = len(sys.argv) > 1 and sys.argv[1] == "search"
resume_mode = len(sys.argv) > 1 and sys.argv[1] == "resume"
start_at = sys.argv[2] if len(sys.argv) > 2 else None
coverage_mode = len(sys.argv) > 1 and sys.argv[1] == "coverage"
if coverage_mode:
return SearchModeCoverage()
elif resume_mode:
return SearchModeResume(
sys.modules["__main__"].__file__
)
elif search_mode and start_at:
start_at = start_at.replace('/', os.path.sep)
return SearchModeByPattern(start_at)
else:
class SearchModeImmediate(SearchModeBase):
def abortOnFinding(self, dirname, filename):
return search_mode and \
SearchModeBase.abortOnFinding(self, dirname, filename)
return SearchModeImmediate()
def reportSkip(reason, dirname, filename):
case = os.path.join(dirname, filename)
case = os.path.normpath(case)
my_print("Skipped, %s (%s)." % (case, reason))
def executeReferenceChecked(prefix, names, tests_skipped, tests_stderr):
import gc
gc.disable()
extract_number = lambda name: int(name.replace(prefix, ""))
# Find the function names.
matching_names = tuple(
name
for name in names
if name.startswith(prefix) and name[-1].isdigit()
)
old_stderr = sys.stderr
# Everything passed
result = True
for name in sorted(matching_names, key = extract_number):
number = extract_number(name)
# print(tests_skipped)
if number in tests_skipped:
my_print(name + ": SKIPPED (%s)" % tests_skipped[number])
continue
# Avoid unraisable output.
try:
if number in tests_stderr:
sys.stderr = open(os.devnull, "wb")
except OSError: # Windows
if not checkReferenceCount(names[name]):
result = False
else:
if not checkReferenceCount(names[name]):
result = False
if number in tests_stderr:
new_stderr = sys.stderr
sys.stderr = old_stderr
new_stderr.close()
gc.enable()
return result
def checkDebugPython():
if not hasattr(sys, "gettotalrefcount"):
my_print("Warning, using non-debug Python makes this test ineffective.")
sys.gettotalrefcount = lambda : 0
elif sys.version_info >= (3,7,0) and sys.version_info < (3,7,2):
my_print("Warning, bug of CPython 3.7.0/1 breaks reference counting and makes this test ineffective.")
sys.gettotalrefcount = lambda : 0
def addToPythonPath(python_path):
if type(python_path) in (tuple, list):
python_path = os.pathsep.join(python_path)
if python_path:
if "PYTHONPATH" in os.environ:
os.environ["PYTHONPATH"] += os.pathsep + python_path
else:
os.environ["PYTHONPATH"] = python_path
@contextmanager
def withPythonPathChange(python_path):
if python_path:
if type(python_path) not in (tuple, list):
python_path = python_path.split(os.pathsep)
python_path = [
os.path.normpath(os.path.abspath(element))
for element in
python_path
]
python_path = os.pathsep.join(python_path)
if "PYTHONPATH" in os.environ:
old_path = os.environ["PYTHONPATH"]
os.environ["PYTHONPATH"] += os.pathsep + python_path
else:
old_path = None
os.environ["PYTHONPATH"] = python_path
# print(
# "Effective PYTHONPATH in %s is %r" % (
# sys.modules["__main__"],
# os.environ.get("PYTHONPATH", "")
# )
# )
yield
if python_path:
if old_path is None:
del os.environ["PYTHONPATH"]
else:
os.environ["PYTHONPATH"] = old_path
@contextmanager
def withExtendedExtraOptions(*args):
assert args
old_value = os.environ.get("NUITKA_EXTRA_OPTIONS", None)
value = old_value
for arg in args:
if value is None:
value = arg
else:
value += ' ' + arg
os.environ[ "NUITKA_EXTRA_OPTIONS" ] = value
yield
if old_value is None:
del os.environ[ "NUITKA_EXTRA_OPTIONS" ]
else:
os.environ[ "NUITKA_EXTRA_OPTIONS" ] = old_value
def indentedCode(codes, count):
""" Indent code, used for generating test codes.
"""
return '\n'.join( ' ' * count + line if line else "" for line in codes )
def convertToPython(doctests, line_filter = None):
""" Convert give doctest string to static Python code.
"""
# This is convoluted, but it just needs to work, pylint: disable=too-many-branches
import doctest
code = doctest.script_from_examples(doctests)
if code.endswith('\n'):
code += "#\n"
else:
assert False
output = []
inside = False
def getPrintPrefixed(evaluated, line_number):
try:
node = ast.parse(evaluated.lstrip(), "eval")
except SyntaxError:
return evaluated
if node.body[0].__class__.__name__ == "Expr":
count = 0
while evaluated.startswith(' ' * count):
count += 1
if sys.version_info < (3,):
modified = (count-1) * ' ' + "print " + evaluated
return (count-1) * ' ' + ("print 'Line %d'" % line_number) + '\n' + modified
else:
modified = (count-1) * ' ' + "print(" + evaluated + "\n)\n"
return (count-1) * ' ' + ("print('Line %d'" % line_number) + ")\n" + modified
else:
return evaluated
def getTried(evaluated, line_number):
if sys.version_info < (3,):
return """
try:
%(evaluated)s
except Exception as __e:
print "Occurred", type(__e), __e
""" % { "evaluated" : indentedCode(getPrintPrefixed(evaluated, line_number).split('\n'), 4) }
else:
return """
try:
%(evaluated)s
except Exception as __e:
print("Occurred", type(__e), __e)
""" % { "evaluated" : indentedCode(getPrintPrefixed(evaluated, line_number).split('\n'), 4) }
def isOpener(evaluated):
evaluated = evaluated.lstrip()
if evaluated == "":
return False
return evaluated.split()[0] in (
"def", "class", "for", "while", "try:", "except", "except:",
"finally:", "else:"
)
chunk = None
for line_number, line in enumerate(code.split('\n')):
# print "->", inside, line
if line_filter is not None and line_filter(line):
continue
if inside and line and line[0].isalnum() and not isOpener(line):
output.append(getTried('\n'.join(chunk), line_number)) # @UndefinedVariable
chunk = []
inside = False
if inside and not (line.startswith('#') and line.find("SyntaxError:") != -1):
chunk.append(line)
elif line.startswith('#'):
if line.find("SyntaxError:") != -1:
# print "Syntax error detected"
if inside:
# print "Dropping chunk", chunk
chunk = []
inside = False
else:
del output[-1]
elif isOpener(line):
inside = True
chunk = [line]
elif line.strip() == "":
output.append(line)
else:
output.append(getTried(line, line_number))
return '\n'.join(output).rstrip() + '\n'
def compileLibraryPath(search_mode, path, stage_dir, decide, action):
my_print("Checking standard library path:", path)
for root, dirnames, filenames in os.walk(path):
dirnames_to_remove = [
dirname
for dirname in dirnames
if '-' in dirname
]
for dirname in dirnames_to_remove:
dirnames.remove(dirname)
dirnames.sort()
filenames = [
filename
for filename in filenames
if decide(root, filename)
]
for filename in sorted(filenames):
if not search_mode.consider(root, filename):
continue
full_path = os.path.join(root, filename)
my_print(full_path, ':', end = ' ')
sys.stdout.flush()
action(stage_dir, path, full_path)
def compileLibraryTest(search_mode, stage_dir, decide, action):
if not os.path.exists(stage_dir):
os.makedirs(stage_dir)
my_dirname = os.path.join(os.path.dirname(__file__), "../../..")
my_dirname = os.path.normpath(my_dirname)
paths = [
path
for path in
sys.path
if not path.startswith(my_dirname)
]
my_print("Using standard library paths:")
for path in paths:
my_print(path)
for path in paths:
print("Checking path:", path)
compileLibraryPath(
search_mode = search_mode,
path = path,
stage_dir = stage_dir,
decide = decide,
action = action
)
search_mode.finish()
def run_async(coro):
""" Execute a coroutine until it's done. """
values = []
result = None
while True:
try:
values.append(coro.send(None))
except StopIteration as ex:
result = ex.args[0] if ex.args else None
break
return values, result
def async_iterate(g):
""" Execute async generator until it's done. """
# Test code for Python3, catches all kinds of exceptions.
# pylint: disable=broad-except
# Also Python3 only, pylint: disable=I0021,undefined-variable
res = []
while True:
try:
g.__anext__().__next__()
except StopAsyncIteration: # @UndefinedVariable
res.append("STOP")
break
except StopIteration as ex:
if ex.args:
res.append("ex arg %s" % ex.args[0])
else:
res.append("EMPTY StopIteration")
break
except Exception as ex:
res.append(str(type(ex)))
return res
def getTestingCacheDir():
cache_dir = getCacheDir()
result = os.path.join(cache_dir, "tests_state")
makePath(result)
return result
def getTestingCPythonOutputsCacheDir():
cache_dir = getCacheDir()
result = os.path.join(cache_dir, "cpython_outputs", os.environ.get("NUITKA_TEST_SUITE", ""))
makePath(result)
return result
@contextmanager
def withDirectoryChange(path, allow_none = False):
if path is not None or not allow_none:
old_cwd = os.getcwd()
os.chdir(path)
yield
if path is not None or not allow_none:
os.chdir(old_cwd)
def someGenerator():
yield 1
yield 2
yield 3
def someGeneratorRaising():
yield 1
raise TypeError(2)
|
the-stack_0_14671 | from pazusoba import adventureEx, Profile, ProfileName, Orb
import time
import random
def random_board() -> str:
return "".join(random.choice(["L", "R", "G", "B", "D", "H"]) for _ in range(30))
def amen_benchmark():
print("Running amen benchmark...")
COUNT = 10
goal_counter = 0
steps = 0
start = time.time()
for i in range(COUNT):
print("Test {}".format(i + 1))
board = random_board()
print("Board: {}".format(board))
result = adventureEx(board, 3, 150, 10000, [
Profile(name=ProfileName.COMBO, target=7),
Profile(name=ProfileName.ORB_REMAINING, target=3),
])
if result.goal:
goal_counter += 1
steps += result.step
time_taken = time.time() - start
print("It took {} seconds, {} seconds on average".format(
time_taken, time_taken / COUNT))
print("Goal rate: {}/{}".format(goal_counter, COUNT))
print("Average steps: {}".format(steps / COUNT))
def combo_benchmark():
print("Running combo benchmark...")
COUNT = 100
goal_counter = 0
steps = 0
start = time.time()
for i in range(COUNT):
board = random_board()
print("{} - {}".format(i + 1, board))
result = adventureEx(board, 3, 150, 1000, [
Profile(name=ProfileName.COMBO, threshold=50)
])
if result.goal:
goal_counter += 1
steps += result.step
time_taken = time.time() - start
print("It took {} seconds, {} seconds on average".format(
time_taken, time_taken / COUNT))
print("Goal rate: {}/{}".format(goal_counter, COUNT))
print("Average steps: {}".format(steps / COUNT))
def find_best_small_size_combo():
COUNT = 20
# generate same board
boards = [random_board() for _ in range(COUNT)]
for x in range(1, 11):
size = x * 100
goal_counter = 0
steps = 0
start = time.time()
for i in range(COUNT):
result = adventureEx(boards[i], 3, 150, 1000, [
Profile(name=ProfileName.COMBO, threshold=20)
])
if result.goal:
goal_counter += 1
steps += result.step
time_taken = time.time() - start
print("Size {} - avg {} s, {}/{}, avg {} steps".format(
size, time_taken / COUNT, goal_counter, COUNT, steps / COUNT))
if __name__ == '__main__':
print("Running benchmark")
# amen_benchmark()
combo_benchmark()
# find_best_small_size_combo()
|
the-stack_0_14672 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for XLA JIT compiler."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import unittest
import numpy as np
from six.moves import xrange # pylint: disable=redefined-builtin
from tensorflow.compiler.tests.xla_test import XLATestCase
from tensorflow.python.framework import dtypes
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import bitwise_ops
from tensorflow.python.ops import gen_nn_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn_ops
from tensorflow.python.platform import googletest
def nhwc_to_format(x, data_format):
"""Converts a numpy array from NHWC format to `data_format`."""
rank = len(x.shape)
if data_format == "NCHW":
return np.transpose(x, [0, rank - 1] + list(range(1, rank - 1)))
elif data_format == "NHWC":
return x
else:
raise ValueError("Unknown format {}".format(data_format))
class UnaryOpsTest(XLATestCase):
"""Test cases for unary operators."""
def _assertOpOutputMatchesExpected(self, op, inp, expected,
equality_test=None, rtol=1e-3, atol=1e-5):
"""Verifies that 'op' produces 'expected' when fed input 'inp' .
Args:
op: operator to test
inp: numpy input array to use as input to 'op'.
expected: numpy array representing the expected output of 'op'.
equality_test: either None, or a function that tests two numpy arrays for
equality. If None, self.assertAllClose is used.
rtol: relative tolerance for equality test.
atol: absolute tolerance for equality test.
"""
with self.test_session() as session:
with self.test_scope():
pinp = array_ops.placeholder(
dtypes.as_dtype(inp.dtype), inp.shape, name="a")
output = op(pinp)
result = session.run(output, {pinp: inp})
if equality_test is None:
self.assertAllCloseAccordingToType(
result, expected, rtol=rtol, atol=atol, bfloat16_rtol=0.03)
else:
equality_test(result, expected, rtol=rtol, atol=atol)
def ListsAreClose(self, result, expected, rtol, atol):
"""Tests closeness of two lists of floats."""
self.assertEqual(len(result), len(expected))
for i in xrange(len(result)):
self.assertAllClose(result[i], expected[i], rtol, atol)
def testAllTypeOps(self):
for dtype in self.numeric_types:
self._assertOpOutputMatchesExpected(
array_ops.diag,
np.array([1, 2, 3, 4], dtype=dtype),
np.array([[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]],
dtype=dtype))
self._assertOpOutputMatchesExpected(
array_ops.diag_part,
np.arange(36).reshape([2, 3, 2, 3]).astype(dtype),
np.array([[0, 7, 14], [21, 28, 35]], dtype=dtype))
self._assertOpOutputMatchesExpected(
array_ops.diag, np.array([[1, 2], [3, 4]], dtype=dtype),
np.array(
[[[[1, 0], [0, 0]], [[0, 2], [0, 0]]], [[[0, 0], [3, 0]],
[[0, 0], [0, 4]]]],
dtype=dtype))
self._assertOpOutputMatchesExpected(
array_ops.identity,
np.array([[-1, 1]], dtype=dtype),
expected=np.array([[-1, 1]], dtype=dtype))
self._assertOpOutputMatchesExpected(
array_ops.matrix_diag,
np.array([[1, 2], [3, 4]], dtype=dtype),
np.array([[[1, 0], [0, 2]], [[3, 0], [0, 4]]], dtype=dtype))
self._assertOpOutputMatchesExpected(
array_ops.matrix_diag, np.array([1, 2, 3, 4], dtype=dtype),
np.array(
[[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]],
dtype=dtype))
self._assertOpOutputMatchesExpected(
array_ops.matrix_diag,
np.array(
[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]], dtype=dtype),
np.array(
[[[[1, 0, 0], [0, 2, 0], [0, 0, 3]],
[[4, 0, 0], [0, 5, 0], [0, 0, 6]]],
[[[7, 0, 0], [0, 8, 0], [0, 0, 9]],
[[10, 0, 0], [0, 11, 0], [0, 0, 12]]]],
dtype=dtype))
self._assertOpOutputMatchesExpected(
array_ops.matrix_diag_part,
np.arange(3 * 2 * 4).reshape([3, 2, 4]).astype(dtype),
np.array([[0, 5], [8, 13], [16, 21]], dtype=dtype))
self._assertOpOutputMatchesExpected(
array_ops.prevent_gradient,
np.array([[-1, 1]], dtype=dtype),
expected=np.array([[-1, 1]], dtype=dtype))
self._assertOpOutputMatchesExpected(
array_ops.squeeze,
np.array([[[[[]]]]], dtype=dtype),
expected=np.array([], dtype=dtype))
self._assertOpOutputMatchesExpected(
array_ops.squeeze,
np.array([[[1], [2]]], dtype=dtype),
expected=np.array([1, 2], dtype=dtype))
self._assertOpOutputMatchesExpected(
array_ops.squeeze,
np.array([[[1]], [[2]]], dtype=dtype),
expected=np.array([1, 2], dtype=dtype))
self._assertOpOutputMatchesExpected(
array_ops.squeeze,
np.array([[[1, 2], [3, 4]]], dtype=dtype),
expected=np.array([[1, 2], [3, 4]], dtype=dtype))
self._assertOpOutputMatchesExpected(
array_ops.stop_gradient,
np.array([[-1, 1]], dtype=dtype),
expected=np.array([[-1, 1]], dtype=dtype))
def testFloatOps(self):
for dtype in self.float_types:
# TODO (b/77694432): Half test failed on CPU, last ran on 04-06-2018. id:177
# https://github.com/imdone/tensorflow/issues/178
if dtype == np.float16 and self.device == "XLA_CPU":
continue
x = np.arange(-0.90, 0.90, 0.25)
self._assertOpOutputMatchesExpected(
math_ops.acos,
x.astype(dtype),
expected=np.arccos(x).astype(dtype))
self._assertOpOutputMatchesExpected(
math_ops.asin,
x.astype(dtype),
expected=np.arcsin(x).astype(dtype))
x = np.arange(-3, 3).reshape(1, 3, 2)
self._assertOpOutputMatchesExpected(
math_ops.atan,
x.astype(dtype),
expected=np.arctan(x).astype(dtype))
self._assertOpOutputMatchesExpected(
math_ops.acosh,
np.array([1, 2, 3, 4], dtype=dtype),
expected=np.array([0, 1.3169579, 1.76274717, 2.06343707],
dtype=dtype))
self._assertOpOutputMatchesExpected(
math_ops.asinh,
np.array([1, 2, 3, 4], dtype=dtype),
expected=np.array([0.88137359, 1.44363548, 1.81844646, 2.09471255],
dtype=dtype))
self._assertOpOutputMatchesExpected(
math_ops.atanh,
np.array([0.1, 0.2, 0.3, 0.4], dtype=dtype),
expected=np.array([0.10033535, 0.20273255, 0.3095196, 0.42364893],
dtype=dtype))
self._assertOpOutputMatchesExpected(
math_ops.ceil,
np.array([[-1.7, 1.2]], dtype=dtype),
expected=np.array([[-1, 2]], dtype=dtype))
self._assertOpOutputMatchesExpected(
math_ops.cosh,
np.array([1, 2, 3, 4], dtype=dtype),
expected=np.array([1.54308063, 3.76219569, 10.067662, 27.30823284],
dtype=dtype))
self._assertOpOutputMatchesExpected(
math_ops.exp,
np.array([[-1, 1]], dtype=dtype),
expected=np.array([[0.36787945, 2.7182817]], dtype=dtype))
self._assertOpOutputMatchesExpected(
math_ops.expm1,
np.array([[-1, 1]], dtype=dtype),
expected=np.array([[-0.63212056, 1.71828183]], dtype=dtype))
self._assertOpOutputMatchesExpected(
math_ops.floor,
np.array([[-1.7, 1.2]], dtype=dtype),
expected=np.array([[-2, 1]], dtype=dtype))
self._assertOpOutputMatchesExpected(
math_ops.is_finite,
np.array([[np.NINF, -2, -1, 0, 0.5, 1, 2, np.inf, np.nan]],
dtype=dtype),
expected=np.array([[0, 1, 1, 1, 1, 1, 1, 0, 0]], dtype=np.bool))
# Tests for tf.nn ops.
self._assertOpOutputMatchesExpected(
nn_ops.l2_loss, np.array([[[]]], dtype=dtype), expected=dtype(0))
self._assertOpOutputMatchesExpected(nn_ops.l2_loss, dtype(4), dtype(8))
self._assertOpOutputMatchesExpected(
nn_ops.l2_loss, np.array([[-2, 4]], dtype=dtype), expected=dtype(10))
self._assertOpOutputMatchesExpected(
math_ops.reciprocal,
np.array([[1, 2]], dtype=dtype),
expected=np.array([[1, 0.5]], dtype=dtype))
self._assertOpOutputMatchesExpected(
math_ops.log,
np.array([[1, 2]], dtype=dtype),
expected=np.array([[0, 0.69314718]], dtype=dtype))
self._assertOpOutputMatchesExpected(
math_ops.sin,
np.array([[1, 2]], dtype=dtype),
expected=np.array([[0.841478, 0.909302]], dtype=dtype))
self._assertOpOutputMatchesExpected(
math_ops.cos,
np.array([[1, 2]], dtype=dtype),
expected=np.array([[0.540297, -0.41614]], dtype=dtype))
# TODO (b/34703906): improve log1p implementation and make tolerance id:332
# https://github.com/imdone/tensorflow/issues/333
# tighter.
self._assertOpOutputMatchesExpected(
math_ops.log1p,
np.array([[1e-14, 1e-15, 0.6]], dtype=dtype),
expected=np.log1p(np.array([[1e-14, 1e-15, 0.6]], dtype=dtype)))
self._assertOpOutputMatchesExpected(
math_ops.rint,
np.array([[-1.7, 1.2, 4.0, 0.0], [-3.5, -2.5, -1.5, -0.5],
[0.5, 1.5, 2.5, 3.5]], dtype=dtype),
expected=np.array([[-2, 1, 4, 0], [-4, -2, -2, 0], [0, 2, 2, 4]],
dtype=dtype))
self._assertOpOutputMatchesExpected(
math_ops.round,
np.array([[-1.7, 1.2, 4.0, 0.0], [-3.5, -2.5, -1.5, -0.5],
[0.5, 1.5, 2.5, 3.5]], dtype=dtype),
expected=np.array([[-2, 1, 4, 0], [-4, -2, -2, 0], [0, 2, 2, 4]],
dtype=dtype))
self._assertOpOutputMatchesExpected(
math_ops.rsqrt,
np.array([[4, 16]], dtype=dtype),
expected=np.array([[0.5, 0.25]], dtype=dtype))
self._assertOpOutputMatchesExpected(
math_ops.sigmoid,
np.array(
[[1, 1, 1, 1],
[1, 2, 3, 4]],
dtype=dtype),
expected=np.array(
[[0.7310586, 0.7310586, 0.7310586, 0.7310586],
[0.7310586, 0.880797, 0.95257413, 0.98201376]],
dtype=dtype))
self._assertOpOutputMatchesExpected(
math_ops.sigmoid,
np.array([-300, -150, 0, 150, 300], dtype=dtype),
expected=np.array([0, 0, 0.5, 1, 1], dtype=dtype))
self._assertOpOutputMatchesExpected(
math_ops.sinh,
np.array([1, 2, 3, 4], dtype=dtype),
expected=np.array([1.17520119, 3.62686041, 10.01787493, 27.2899172],
dtype=dtype))
self._assertOpOutputMatchesExpected(
math_ops.sqrt,
np.array([[4, 9]], dtype=dtype),
expected=np.array([[2, 3]], dtype=dtype))
self._assertOpOutputMatchesExpected(
math_ops.tan,
np.array([1, 2, 3, 4], dtype=dtype),
expected=np.array([1.55740772, -2.18503986, -0.14254654, 1.15782128],
dtype=dtype))
self._assertOpOutputMatchesExpected(
math_ops.tanh,
np.array(
[[1, 1, 1, 1],
[1, 2, 3, 4]],
dtype=dtype),
expected=np.array(
[[0.76159418, 0.76159418, 0.76159418, 0.76159418],
[0.76159418, 0.96402758, 0.99505478, 0.99932933]],
dtype=dtype))
self._assertOpOutputMatchesExpected(
nn_ops.log_softmax,
np.array(
[[1, 1, 1, 1],
[1, 2, 3, 4]],
dtype=dtype),
expected=np.array(
[[-1.3862944, -1.3862944, -1.3862944, -1.3862944],
[-3.4401896, -2.4401896, -1.4401897, -0.44018969]],
dtype=dtype))
self._assertOpOutputMatchesExpected(
nn_ops.elu,
np.array([[-1, 0, 1]], dtype=dtype),
expected=np.array([[-0.63212056, 0, 1]], dtype=dtype))
self._assertOpOutputMatchesExpected(
nn_ops.selu,
np.array([[-1, 0, 1]], dtype=dtype),
expected=np.array([[-1.11133074, 0., 1.05070099]], dtype=dtype))
self._assertOpOutputMatchesExpected(
nn_ops.relu,
np.array([[-1, 1]], dtype=dtype),
expected=np.array([[0, 1]], dtype=dtype))
self._assertOpOutputMatchesExpected(
nn_ops.relu6,
np.array([[-0.05, 6.05, 5]], dtype=dtype),
expected=np.array([[0, 6, 5]], dtype=dtype))
self._assertOpOutputMatchesExpected(
nn_ops.softmax,
np.array(
[[1, 1, 1, 1],
[1, 2, 3, 4]],
dtype=dtype),
expected=np.array(
[[0.25, 0.25, 0.25, 0.25],
[0.032058604, 0.087144323, 0.23688284, 0.64391428]],
dtype=dtype))
self._assertOpOutputMatchesExpected(
nn_ops.softsign,
np.array([[-2, -1, 0, 1, 2]], dtype=dtype),
expected=np.array([[-0.66666669, -0.5, 0, 0.5, 0.66666669]],
dtype=dtype))
self._assertOpOutputMatchesExpected(
math_ops.is_finite,
np.array(
[[42, float("inf"), -123], [float("nan"), 0, -0.0]], dtype=dtype),
expected=np.array(
[[True, False, True], [False, True, True]], dtype=np.bool))
self._assertOpOutputMatchesExpected(
lambda x: array_ops.quantize_and_dequantize_v2(x, -127, 127, True, 8),
np.array([-1, -0.5, 0, 0.3], dtype=dtype),
expected=np.array([-1, -64.0 / 127, 0, 38.0 / 127], dtype=dtype))
def testComplexOps(self):
for dtype in self.complex_types:
self._assertOpOutputMatchesExpected(
math_ops.acosh,
np.array([0.1, 0.2j, 0.3 - 0.1j, 0.4 + 0.5j], dtype=dtype),
expected=np.arccosh(
np.array([0.1, 0.2j, 0.3 - 0.1j, 0.4 + 0.5j], dtype=dtype)))
self._assertOpOutputMatchesExpected(
math_ops.asinh,
np.array([0.1, 0.2j, 0.3 - 0.1j, 0.4 + 0.5j], dtype=dtype),
expected=np.arcsinh(
np.array([0.1, 0.2j, 0.3 - 0.1j, 0.4 + 0.5j], dtype=dtype)))
self._assertOpOutputMatchesExpected(
math_ops.atanh,
np.array([0.1, 0.2j, 0.3 - 0.1j, 0.4 + 0.5j], dtype=dtype),
expected=np.arctanh(
np.array([0.1, 0.2j, 0.3 - 0.1j, 0.4 + 0.5j], dtype=dtype)))
self._assertOpOutputMatchesExpected(
math_ops.cosh,
np.array([1j, 2 - 3j, 3, 4 + 2j], dtype=dtype),
expected=np.cosh(np.array([1j, 2 - 3j, 3, 4 + 2j], dtype=dtype)))
self._assertOpOutputMatchesExpected(
math_ops.sinh,
np.array([1, 2j, 2 - 3j, 4 + 5j], dtype=dtype),
expected=np.sinh(np.array([1, 2j, 2 - 3j, 4 + 5j], dtype=dtype)))
self._assertOpOutputMatchesExpected(
math_ops.exp,
np.array([[-1 + 2j, 3j, 2 - 3j]], dtype=dtype),
expected=np.exp(np.array([[-1 + 2j, 3j, 2 - 3j]], dtype=dtype)))
self._assertOpOutputMatchesExpected(
math_ops.expm1,
np.array([[-1 + 2j, 3j, 2 - 3j]], dtype=dtype),
expected=np.expm1(np.array([[-1 + 2j, 3j, 2 - 3j]], dtype=dtype)))
self._assertOpOutputMatchesExpected(
math_ops.reciprocal,
np.array([[1, 2j, 2 + 3j]], dtype=dtype),
expected=1.0 / np.array([[1, 2j, 2 + 3j]], dtype=dtype))
self._assertOpOutputMatchesExpected(
math_ops.log,
np.array([[5j, 3 - 2j]], dtype=dtype),
expected=np.log(np.array([[5j, 3 - 2j]], dtype=dtype)))
self._assertOpOutputMatchesExpected(
math_ops.sin,
np.array([[5j, 3 - 2j]], dtype=dtype),
expected=np.sin(np.array([[5j, 3 - 2j]], dtype=dtype)))
self._assertOpOutputMatchesExpected(
math_ops.cos,
np.array([[5j, 3 - 2j]], dtype=dtype),
expected=np.cos(np.array([[5j, 3 - 2j]], dtype=dtype)))
# TODO (b/34703906): improve log1p implementation and make tolerance id:256
# https://github.com/imdone/tensorflow/issues/257
# tighter.
self._assertOpOutputMatchesExpected(
math_ops.log1p,
np.array([[1e-14, 1e-15j, 0.6 - 0.3j]], dtype=dtype),
expected=np.log1p(
np.array([[1e-14, 1e-15j, 0.6 - 0.3j]], dtype=dtype)))
val = np.array([1, 2j, 2 - 3j, 4 + 5j], dtype=dtype)
self._assertOpOutputMatchesExpected(
math_ops.rsqrt, val, expected=1 / np.sqrt(val))
self._assertOpOutputMatchesExpected(
math_ops.sigmoid, val, expected=1 / (1 + np.exp(-val)))
self._assertOpOutputMatchesExpected(
math_ops.sqrt, val, expected=np.sqrt(val))
self._assertOpOutputMatchesExpected(
math_ops.tanh,
np.array([1, 2j, 2 - 3j, 4 + 5j], dtype=dtype),
expected=np.tanh(np.array([1, 2j, 2 - 3j, 4 + 5j], dtype=dtype)))
self._assertOpOutputMatchesExpected(
math_ops.tan,
np.array([1, 2j, 2 - 3j, 4 + 5j], dtype=dtype),
expected=np.tan(np.array([1, 2j, 2 - 3j, 4 + 5j], dtype=dtype)))
ctypes = {np.complex64: np.float32}
self._assertOpOutputMatchesExpected(
math_ops.abs,
np.array([[3 - 4j, -1j, np.inf]], dtype=dtype),
expected=np.array([[5, 1, np.inf]], dtype=ctypes[dtype]))
self._assertOpOutputMatchesExpected(
math_ops.negative,
np.array([[-1 + 2j, -3j]], dtype=dtype),
expected=np.array([[1 - 2j, 3j]], dtype=dtype))
self._assertOpOutputMatchesExpected(
math_ops.square,
np.array([[-2 - 3j, 3 + 4j, 5j]], dtype=dtype),
expected=np.array([[-2 - 3j, 3 + 4j, 5j]], dtype=dtype)**2)
self._assertOpOutputMatchesExpected(
array_ops.zeros_like,
np.array([[4j, 3 - 2j], [2, -1j]], dtype=dtype),
expected=np.array([[0, 0], [0, 0]], dtype=dtype))
self._assertOpOutputMatchesExpected(
array_ops.ones_like,
np.array([[-4j, 3 + 2j], [2, -1j]], dtype=dtype),
expected=np.array([[1, 1], [1, 1]], dtype=dtype))
self._assertOpOutputMatchesExpected(
math_ops.angle,
np.array([1 + 3j, -4 + 7j, 2.7, -3j], dtype=dtype),
expected=np.angle(np.array([1 + 3j, -4 + 7j, 2.7, -3j], dtype=dtype)))
self._assertOpOutputMatchesExpected(
math_ops.conj,
np.array([1 + 3j, -4 + 7j, 2.7, -3j], dtype=dtype),
expected=np.array([1 - 3j, -4 - 7j, 2.7, 3j], dtype=dtype))
self._assertOpOutputMatchesExpected(
math_ops.imag,
np.array([1 + 3j, -4 + 7j, 2.7, -3j], dtype=dtype),
expected=np.array([3, 7, 0, -3], dtype=ctypes[dtype]))
self._assertOpOutputMatchesExpected(
math_ops.real,
np.array([1 + 3j, -4 + 7j, 2.7, -3j], dtype=dtype),
expected=np.array([1, -4, 2.7, 0], dtype=ctypes[dtype]))
def testIntOps(self):
for dtype in self.int_types:
self._assertOpOutputMatchesExpected(
bitwise_ops.invert,
np.array([0, -1, 1, 16, 42], dtype=dtype),
expected=np.array([-1, 0, -2, -17, -43], dtype=dtype))
def testNumericOps(self):
for dtype in self.numeric_types:
self._assertOpOutputMatchesExpected(
math_ops.abs,
np.array([[2, -1]], dtype=dtype),
expected=np.array([[2, 1]], dtype=dtype))
self._assertOpOutputMatchesExpected(
math_ops.negative,
np.array([[-1, 1]], dtype=dtype),
expected=np.array([[1, -1]], dtype=dtype))
self._assertOpOutputMatchesExpected(
math_ops.square,
np.array([[-2, 3]], dtype=dtype),
expected=np.array([[4, 9]], dtype=dtype))
self._assertOpOutputMatchesExpected(
array_ops.zeros_like,
np.array([[4, 3], [2, 1]], dtype=dtype),
expected=np.array([[0, 0], [0, 0]], dtype=dtype))
self._assertOpOutputMatchesExpected(
array_ops.ones_like,
np.array([[4, 3], [2, 1]], dtype=dtype),
expected=np.array([[1, 1], [1, 1]], dtype=dtype))
# TODO (phawkins): these tests fail unless fastmath optimizations id:202
# https://github.com/imdone/tensorflow/issues/203
# are disabled. Use more robust IsInf/IsNaN detection and enable these
# tests.
@unittest.skip("test case fails in fast-math mode")
def testIsInfAndIsNan(self):
for dtype in self.float_types:
self._assertOpOutputMatchesExpected(
math_ops.is_inf,
np.array([[np.NINF, -2, -1, 0, 0.5, 1, 2, np.inf, np.nan]],
dtype=dtype),
expected=np.array([[1, 0, 0, 0, 0, 0, 0, 1, 0]], dtype=np.bool))
self._assertOpOutputMatchesExpected(
math_ops.is_nan,
np.array([[np.NINF, -2, -1, 0, 0.5, 1, 2, np.inf, np.nan]],
dtype=dtype),
expected=np.array([[0, 0, 0, 0, 0, 0, 0, 0, 1]], dtype=np.bool))
def testLogicalOps(self):
self._assertOpOutputMatchesExpected(
math_ops.logical_not,
np.array([[True, False], [False, True]], dtype=np.bool),
expected=np.array([[False, True], [True, False]], dtype=np.bool))
def testBiasAddGrad(self):
self._assertOpOutputMatchesExpected(
gen_nn_ops.bias_add_grad,
np.array([[1., 2.], [3., 4.]], dtype=np.float32),
expected=np.array([4., 6.], dtype=np.float32))
self._assertOpOutputMatchesExpected(
lambda x: gen_nn_ops.bias_add_grad(x, data_format="NCHW"),
np.array([[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]]],
dtype=np.float32),
expected=np.array([10., 26.], dtype=np.float32))
def testCast(self):
shapes = [[], [4], [2, 3], [2, 0, 4]]
types = (set([dtypes.bool, dtypes.int32, dtypes.float32]) |
self.complex_tf_types)
for shape in shapes:
for src_type in types:
for dst_type in types:
src = np.arange(np.prod(shape)).astype(src_type.as_numpy_dtype)
if src_type in self.complex_tf_types:
src += (np.arange(np.prod(shape)) * 2j).astype(
src_type.as_numpy_dtype)
src = src.reshape(shape)
dst = src.astype(dst_type.as_numpy_dtype)
self._assertOpOutputMatchesExpected(
lambda x, dst_type=dst_type: math_ops.cast(x, dst_type),
src,
expected=dst)
def testBitcast(self):
self._assertOpOutputMatchesExpected(
lambda x: array_ops.bitcast(x, dtypes.int32),
np.array([1, 0x3f800000], np.int32),
expected=np.array([1, 0x3f800000], np.int32))
self._assertOpOutputMatchesExpected(
lambda x: array_ops.bitcast(x, dtypes.float32),
np.array([1, 0x3f800000], np.int32),
expected=np.array([1e-45, 1.0], np.float32))
self._assertOpOutputMatchesExpected(
lambda x: array_ops.bitcast(x, dtypes.int32),
np.array([1e-45, 1.0], np.float32),
expected=np.array([1, 0x3f800000], np.int32))
def testInvertPermutation(self):
self._assertOpOutputMatchesExpected(
array_ops.invert_permutation,
np.array([1, 2, 0], np.int32),
expected=np.array([2, 0, 1], dtype=np.int32))
def testRank(self):
rank_op = lambda x: array_ops.rank_internal(x, optimize=False)
for dtype in self.numeric_types:
self._assertOpOutputMatchesExpected(
rank_op, dtype(7), expected=np.int32(0))
self._assertOpOutputMatchesExpected(
rank_op, np.array(
[[], []], dtype=dtype), expected=np.int32(2))
self._assertOpOutputMatchesExpected(
rank_op, np.array(
[-1, 1], dtype=dtype), expected=np.int32(1))
self._assertOpOutputMatchesExpected(
rank_op, np.array(
[[-1, 1]], dtype=dtype), expected=np.int32(2))
self._assertOpOutputMatchesExpected(
rank_op,
np.array([[-1], [1], [4]], dtype=dtype),
expected=np.int32(2))
def testShape(self):
shape_op = lambda x: array_ops.shape_internal(x, optimize=False)
for dtype in self.numeric_types:
self._assertOpOutputMatchesExpected(
shape_op, dtype(7), expected=np.array([], dtype=np.int32))
self._assertOpOutputMatchesExpected(
shape_op,
np.array([[], []], dtype=dtype),
expected=np.array([2, 0], dtype=np.int32))
self._assertOpOutputMatchesExpected(
shape_op,
np.array([-1, 1], dtype=dtype),
expected=np.array([2], dtype=np.int32))
self._assertOpOutputMatchesExpected(
shape_op,
np.array([[-1, 1]], dtype=dtype),
expected=np.array([1, 2], dtype=np.int32))
self._assertOpOutputMatchesExpected(
shape_op,
np.array([[-1], [1], [4]], dtype=dtype),
expected=np.array([3, 1], dtype=np.int32))
def testSize(self):
size_op = lambda x: array_ops.size_internal(x, optimize=False)
for dtype in self.numeric_types:
self._assertOpOutputMatchesExpected(
size_op, dtype(7), expected=np.int32(1))
self._assertOpOutputMatchesExpected(
size_op, np.array([[], []], dtype=dtype), expected=np.int32(0))
self._assertOpOutputMatchesExpected(
size_op, np.array([-1, 1], dtype=dtype), expected=np.int32(2))
self._assertOpOutputMatchesExpected(
size_op, np.array([[-1, 1]], dtype=dtype), expected=np.int32(2))
self._assertOpOutputMatchesExpected(
size_op,
np.array([[-1], [1], [4]], dtype=dtype),
expected=np.int32(3))
def testUnpack(self):
self._assertOpOutputMatchesExpected(
array_ops.unstack,
np.array([[1., 2.], [3., 4.], [5., 6.]], dtype=np.float32),
expected=[
np.array([1., 2.], dtype=np.float32),
np.array([3., 4.], dtype=np.float32),
np.array([5., 6.], dtype=np.float32),
],
equality_test=self.ListsAreClose)
self._assertOpOutputMatchesExpected(
lambda x: array_ops.unstack(x, axis=1),
np.array([[1., 2.], [3., 4.], [5., 6.]], dtype=np.float32),
expected=[
np.array([1., 3., 5.], dtype=np.float32),
np.array([2., 4., 6.], dtype=np.float32),
],
equality_test=self.ListsAreClose)
def testDepthToSpace(self):
def make_op(data_format):
def op(x):
return array_ops.depth_to_space(x, block_size=2,
data_format=data_format)
return op
for dtype in self.numeric_types:
for data_format in ["NCHW", "NHWC"]:
self._assertOpOutputMatchesExpected(
make_op(data_format),
nhwc_to_format(np.array([[[[1, 2, 3, 4]]]], dtype=dtype),
data_format),
expected=nhwc_to_format(np.array([[[[1], [2]],
[[3], [4]]]], dtype=dtype),
data_format))
self._assertOpOutputMatchesExpected(
make_op(data_format),
nhwc_to_format(
np.array([[[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]]],
dtype=dtype),
data_format),
expected=nhwc_to_format(
np.array([[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]],
dtype=dtype),
data_format))
self._assertOpOutputMatchesExpected(
make_op(data_format),
nhwc_to_format(
np.array([[[[1, 2, 3, 4],
[5, 6, 7, 8]],
[[9, 10, 11, 12],
[13, 14, 15, 16]]]], dtype=dtype),
data_format),
expected=nhwc_to_format(
np.array([[[[1], [2], [5], [6]],
[[3], [4], [7], [8]],
[[9], [10], [13], [14]],
[[11], [12], [15], [16]]]], dtype=dtype),
data_format))
def testSpaceToDepth(self):
def make_op(data_format):
def op(x):
return array_ops.space_to_depth(x, block_size=2,
data_format=data_format)
return op
for dtype in self.numeric_types:
for data_format in ["NCHW", "NHWC"]:
self._assertOpOutputMatchesExpected(
make_op(data_format),
nhwc_to_format(np.array([[[[1], [2]],
[[3], [4]]]], dtype=dtype),
data_format),
expected=nhwc_to_format(np.array([[[[1, 2, 3, 4]]]], dtype=dtype),
data_format))
self._assertOpOutputMatchesExpected(
make_op(data_format),
nhwc_to_format(np.array([[[[1, 2, 3], [4, 5, 6]],
[[7, 8, 9], [10, 11, 12]]]], dtype=dtype),
data_format),
expected=nhwc_to_format(
np.array([[[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]]],
dtype=dtype),
data_format))
self._assertOpOutputMatchesExpected(
make_op(data_format),
nhwc_to_format(np.array([[[[1], [2], [5], [6]],
[[3], [4], [7], [8]],
[[9], [10], [13], [14]],
[[11], [12], [15], [16]]]], dtype=dtype),
data_format),
expected=nhwc_to_format(
np.array([[[[1, 2, 3, 4],
[5, 6, 7, 8]],
[[9, 10, 11, 12],
[13, 14, 15, 16]]]], dtype=dtype),
data_format))
def _assertSoftplusMatchesExpected(self, features, dtype):
features = np.array(features, dtype=dtype)
zero = np.asarray(0).astype(dtype)
expected = np.logaddexp(zero, features)
self._assertOpOutputMatchesExpected(
nn_ops.softplus, features, expected=expected)
def testSoftplus(self):
for dtype in self.float_types:
self._assertSoftplusMatchesExpected([[-2, 0, 8]], dtype)
self._assertSoftplusMatchesExpected(
[[-9, 7, -5, 3, -1], [1, -3, 5, -7, 9]], dtype)
if dtype == dtypes.bfloat16.as_numpy_dtype:
log_eps = np.log(np.finfo(np.float32).eps)
else:
log_eps = np.log(np.finfo(dtype).eps)
one = dtype(1)
ten = dtype(10)
self._assertSoftplusMatchesExpected([
log_eps, log_eps - one, log_eps + one, log_eps - ten,
log_eps + ten, -log_eps, -log_eps - one, -log_eps + one,
-log_eps - ten, -log_eps + ten], dtype)
if __name__ == "__main__":
googletest.main()
|
the-stack_0_14674 | # coding: utf-8
import re
import six
from huaweicloudsdkcore.sdk_response import SdkResponse
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class ShowServerTagsResponse(SdkResponse):
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
'tags': 'list[ServerTag]'
}
attribute_map = {
'tags': 'tags'
}
def __init__(self, tags=None):
"""ShowServerTagsResponse - a model defined in huaweicloud sdk"""
super(ShowServerTagsResponse, self).__init__()
self._tags = None
self.discriminator = None
if tags is not None:
self.tags = tags
@property
def tags(self):
"""Gets the tags of this ShowServerTagsResponse.
标签列表
:return: The tags of this ShowServerTagsResponse.
:rtype: list[ServerTag]
"""
return self._tags
@tags.setter
def tags(self, tags):
"""Sets the tags of this ShowServerTagsResponse.
标签列表
:param tags: The tags of this ShowServerTagsResponse.
:type: list[ServerTag]
"""
self._tags = tags
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
import simplejson as json
if six.PY2:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)
def __repr__(self):
"""For `print`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, ShowServerTagsResponse):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
the-stack_0_14675 | from random import randint
palpite = []
jog = []
jogcop = []
qtd = int(input('Digite quantos jogos você quer fazer: '))
i = 0
c = 0
while i < qtd:
while c < 6:
n1 = randint(1, 60)
if n1 not in jog:
jog.append(n1)
c += 1
jog.sort()
palpite.append(jog[:])
jog.clear()
c = 0
print(f'{i+1}° jogo: {palpite[i]}.')
i += 1
|
the-stack_0_14676 | """ Sample Data"""
# published as /alice/index.schema
alice_index_schema = ''.join(("doc:/alice/movies/[^/]+$\n"
" -> wrapper:/irtf/icnrg/flic\n"
" -> wrapper:/alice/homebrewed/ac\n"
" mode='CBC'\n"
" padding='PKCS5'\n"
" => type:/mime/video/mp4\n"
"\n"
"doc:/alice/public/docs/.*[.]pdf$\n"
" -> wrapper:/simple/chunking\n"
" => type:/mime/application/pdf\n"
"\n"
"doc:/alice/public/img/basel.jpg$\n"
" -> wrapper:/simple/chunking\n"
" => type:/mime/image/jpeg\n"))
# published as /alice/homebrewed/ac
ac_wrapper_desc = ''.join(("def decap:\n"
" $secDek = call:/alice/homebrewed/fetchDEK(#, @id.pub)\n"
" $dek = call:/crypto/lib/rsa/decrypt($secDek, @id.priv)\n"
" return call:/nist/aes/decrypt(#, $dek, %mode, %padding)\n"
"\n"
"\n"
"def encap:\n"
" $secDek = call:/alice/homebrewed/fetchDEK(#, @id.pub)\n",
" $dek = call:/crypto/lib/rsa/decrypt($secDek, @id.priv\n",
" sreturn call:/nist/aes/encrypt(#, $dek, %mode, %padding)\n"))
|
the-stack_0_14677 | """
This is an end to end release test automation script used to kick off periodic
release tests, running on Anyscale.
The tool leverages app configs and compute templates.
Calling this script will run a single release test.
Example:
python e2e.py --test-config ~/ray/release/xgboost_tests/xgboost_tests.yaml --test-name tune_small
The following steps are then performed:
1. It will look up the test tune_small in the file xgboost_tests.yaml
2. It will fetch the specified app config and compute template and register
those with anyscale (if they don’t exist yet)
3. It waits until the app config is built
4. It then kicks off the script defined in the run block
5. When the script is finished, it will fetch the latest logs, the full log
output, and any artifacts specified in the artifacts block.
6. The full logs and artifacts will be stored in a s3 bucket
7. It will also fetch the json file specified in the run block as results.
This is the file where you should write your metrics to.
8. All results are then stored in a database.
Specifically it will store the following fields:
- Timestamp
- Test name
- Status (finished, error, timeout, invalid)
- Last logs (50 lines)
- results (see above)
- artifacts (links to s3 files)
Then the script exits. If an error occurs at any time, a fail result is
written to the database.
Writing a new release test
--------------------------
Each release test requires the following:
1. It has to be added in a release test yaml file, describing meta information
about the test (e.g. name, command to run, timeout)
2. You need an app config yaml
3. You need a compute template yaml
4. You need to define a command to run. This is usually a python script.
The command should accept (or ignore) a single optional
`--smoke-test` argument.
Usually the command should write its result metrics to a json file.
The json filename is available in the TEST_OUTPUT_JSON env variable.
5. Add your test in release/.buildkite/build_pipeline.py.
The script will have access to these environment variables:
"RAY_ADDRESS": os.environ.get("RAY_ADDRESS", "auto")
"TEST_OUTPUT_JSON": results_json_filename
"IS_SMOKE_TEST": "1" if smoke_test else "0"
For an example, take a look at the XGBoost test suite:
https://github.com/ray-project/ray/blob/master/release/xgboost_tests/xgboost_tests.yaml
These all use the same app configs and similar compute templates. This means
that app configs can be re-used across runs and only have to be built ones.
App configs and compute templates can interpret environment variables.
A notable one is the `RAY_WHEELS` variable which points to the wheels that
should be tested (e.g. latest master wheels). You might want to include
something like this in your `post_build_cmds`:
- pip3 install -U {{ env["RAY_WHEELS"] | default("ray") }}
If you want to force rebuilds, consider using something like
- echo {{ env["TIMESTAMP"] }}
so that your app configs changes each time the script is executed. If you
only want to trigger rebuilds once per day, use `DATESTAMP` instead:
- echo {{ env["DATESTAMP"] }}
Local testing
-------------
For local testing, make sure to authenticate with the ray-ossci AWS user
(e.g. by setting the respective environment variables obtained from go/aws),
or use the `--no-report` command line argument.
Also make sure to set these environment variables:
- ANYSCALE_CLI_TOKEN (should contain your anyscale credential token)
- ANYSCALE_PROJECT (should point to a project ID you have access to)
A test can then be run like this:
python e2e.py --no-report --test-config ~/ray/release/xgboost_tests/xgboost_tests.yaml --test-name tune_small
The `--no-report` option disables storing the results in the DB and
artifacts on S3. If you set this option, you do not need access to the
ray-ossci AWS user.
Using Compilation on Product + App Config Override
--------------------------------------------------
For quick iteration when debugging a release test, go/compile-on-product allows
you to easily modify and recompile Ray, such that the recompilation happens
within an app build step and can benefit from a warm Bazel cache. See
go/compile-on-product for more information.
After kicking off the app build, you can give the app config ID to this script
as an app config override, where the indicated app config will be used instead
of the app config given in the test config. E.g., running
python e2e.py --no-report --test-config ~/ray/benchmarks/benchmark_tests.yaml --test-name=single_node --app-config-id-override=apt_TBngEXXXrhipMXgexVcrpC9i
would run the single_node benchmark test with the apt_TBngEXXXrhipMXgexVcrpC9i
app config instead of the app config given in
~/ray/benchmarks/benchmark_tests.yaml. If the build for the app config is still
in progress, the script will wait until it completes, same as for a locally
defined app config.
Running on Head Node vs Running with Anyscale Connect
-----------------------------------------------------
By default release tests run their drivers on the head node. Support is being
added to run release tests that execute the driver as a subprocess and run
the workload on Anyscale product via Anyscale connect.
Note that when the driver in the test is a subprocess of releaser, releaser
cannot be terminated before the test finishes.
Other known feature gaps when running with Anyscale connect:
- Kicking off a test or checking progress is not supported.
- Downloading / uploading logs and artifacts are unsupported.
- Logs from remote may not have finished streaming, before the driver exits.
Long running tests
------------------
Long running tests can be kicked off with by adding the --kick-off-only
parameters to the e2e script. The status can then be checked with the
--check command.
Long running test sessions will be terminated after `timeout` seconds, after
which the latest result in the TEST_OUTPUT_JSON will be reported. Thus,
long running release tests should update this file periodically.
There are also two config options to configure behavior. The `time_key` is
needed to track the latest update of the TEST_OUTPUT_JSON and should contain
a floating point number (usually `time.time()`). The `max_update_delay` then
specified the maximum time in seconds that can be passed without an update
to the results json. If the output file hasn't been updated in e.g. 60 seconds,
this could indicate that the command is stale/frozen, and thus should fail.
Release test yaml example
-------------------------
- name: example
owner:
mail: "[email protected]" # Currently not used
slack: "@tune-team" # Currentl not used
cluster:
app_config: app_config.yaml # Relative to the release test yaml
compute_template: tpl_cpu.yaml
run:
timeout: 600 # in seconds
prepare: python wait_cluster.py 4 600 # prepare cmd to run before test
script: python workloads/train.py # actual release test command
# Only needed for long running test
time_key: last_update # Key in the results json indicating current time
max_update_delay: 30 # If state hasn't been updated in 30s, terminate
# This block is optional
artifacts:
# Artifact name: location on head node
- detailed_output: detailed_output.csv
# This block is optional. If present, the contents will be
# deep updated for smoke testing
smoke_test:
cluster:
compute_template: tpl_cpu_smoketest.yaml
""" # noqa: E501
import argparse
import boto3
import collections
import copy
import datetime
import hashlib
import jinja2
import json
import logging
import multiprocessing
import os
import requests
import shutil
import subprocess
import sys
import tempfile
import time
from queue import Empty
from typing import Any, Dict, Optional, Tuple, List
import yaml
import anyscale
import anyscale.conf
from anyscale.api import instantiate_api_client
from anyscale.controllers.session_controller import SessionController
from anyscale.sdk.anyscale_client.sdk import AnyscaleSDK
logger = logging.getLogger()
logger.setLevel(logging.INFO)
handler = logging.StreamHandler(stream=sys.stdout)
formatter = logging.Formatter(fmt="[%(levelname)s %(asctime)s] "
"%(filename)s: %(lineno)d "
"%(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
def getenv_default(key: str, default: Optional[str] = None):
"""Return environment variable with default value"""
# If the environment variable is set but "", still return default
return os.environ.get(key, None) or default
GLOBAL_CONFIG = {
"ANYSCALE_USER": getenv_default("ANYSCALE_USER",
"[email protected]"),
"ANYSCALE_HOST": getenv_default("ANYSCALE_HOST",
"https://beta.anyscale.com"),
"ANYSCALE_CLI_TOKEN": getenv_default("ANYSCALE_CLI_TOKEN"),
"ANYSCALE_CLOUD_ID": getenv_default(
"ANYSCALE_CLOUD_ID",
"cld_4F7k8814aZzGG8TNUGPKnc"), # cld_4F7k8814aZzGG8TNUGPKnc
"ANYSCALE_PROJECT": getenv_default("ANYSCALE_PROJECT", ""),
"RAY_VERSION": getenv_default("RAY_VERSION", "2.0.0.dev0"),
"RAY_REPO": getenv_default("RAY_REPO",
"https://github.com/ray-project/ray.git"),
"RAY_BRANCH": getenv_default("RAY_BRANCH", "master"),
"RELEASE_AWS_BUCKET": getenv_default("RELEASE_AWS_BUCKET",
"ray-release-automation-results"),
"RELEASE_AWS_LOCATION": getenv_default("RELEASE_AWS_LOCATION", "dev"),
"RELEASE_AWS_DB_NAME": getenv_default("RELEASE_AWS_DB_NAME", "ray_ci"),
"RELEASE_AWS_DB_TABLE": getenv_default("RELEASE_AWS_DB_TABLE",
"release_test_result"),
"RELEASE_AWS_DB_SECRET_ARN": getenv_default(
"RELEASE_AWS_DB_SECRET_ARN",
"arn:aws:secretsmanager:us-west-2:029272617770:secret:"
"rds-db-credentials/cluster-7RB7EYTTBK2EUC3MMTONYRBJLE/ray_ci-MQN2hh",
),
"RELEASE_AWS_DB_RESOURCE_ARN": getenv_default(
"RELEASE_AWS_DB_RESOURCE_ARN",
"arn:aws:rds:us-west-2:029272617770:cluster:ci-reporting",
),
"RELEASE_RESULTS_DIR": getenv_default("RELEASE_RESULTS_DIR",
"/tmp/ray_release_test_artifacts"),
"DATESTAMP": str(datetime.datetime.now().strftime("%Y%m%d")),
"TIMESTAMP": str(int(datetime.datetime.now().timestamp())),
"EXPIRATION_1D": str((datetime.datetime.now() +
datetime.timedelta(days=1)).strftime("%Y-%m-%d")),
"EXPIRATION_2D": str((datetime.datetime.now() +
datetime.timedelta(days=2)).strftime("%Y-%m-%d")),
"EXPIRATION_3D": str((datetime.datetime.now() +
datetime.timedelta(days=3)).strftime("%Y-%m-%d")),
}
REPORT_S = 30
RETRY_MULTIPLIER = 2
def exponential_backoff_retry(f, retry_exceptions, initial_retry_delay_s,
max_retries):
retry_cnt = 0
retry_delay_s = initial_retry_delay_s
while True:
try:
return f()
except retry_exceptions as e:
retry_cnt += 1
if retry_cnt > max_retries:
raise
logger.info(f"Retry function call failed due to {e} "
f"in {retry_delay_s} seconds...")
time.sleep(retry_delay_s)
retry_delay_s *= RETRY_MULTIPLIER
def maybe_fetch_api_token():
if GLOBAL_CONFIG["ANYSCALE_CLI_TOKEN"] is None:
logger.info(
"Missing ANYSCALE_CLI_TOKEN, retrieving from AWS secrets store")
# NOTE(simon) This should automatically retrieve
# [email protected]'s anyscale token
GLOBAL_CONFIG["ANYSCALE_CLI_TOKEN"] = boto3.client(
"secretsmanager", region_name="us-west-2"
).get_secret_value(
SecretId="arn:aws:secretsmanager:us-west-2:029272617770:secret:"
"release-automation/"
"anyscale-token20210505220406333800000001-BcUuKB")["SecretString"]
class PrepareCommandRuntimeError(RuntimeError):
pass
class ReleaseTestTimeoutError(RuntimeError):
pass
class SessionTimeoutError(ReleaseTestTimeoutError):
pass
class FileSyncTimeoutError(ReleaseTestTimeoutError):
pass
class CommandTimeoutError(ReleaseTestTimeoutError):
pass
class PrepareCommandTimeoutError(ReleaseTestTimeoutError):
pass
# e.g., App config failure.
class AppConfigBuildFailure(RuntimeError):
pass
class State:
def __init__(self, state: str, timestamp: float, data: Any):
self.state = state
self.timestamp = timestamp
self.data = data
sys.path.insert(0, anyscale.ANYSCALE_RAY_DIR)
def anyscale_project_url(project_id: str):
return f"{GLOBAL_CONFIG['ANYSCALE_HOST']}" \
f"/o/anyscale-internal/projects/{project_id}" \
f"/?tab=session-list"
def anyscale_session_url(project_id: str, session_id: str):
return f"{GLOBAL_CONFIG['ANYSCALE_HOST']}" \
f"/o/anyscale-internal/projects/{project_id}" \
f"/clusters/{session_id}"
def anyscale_compute_tpl_url(compute_tpl_id: str):
return f"{GLOBAL_CONFIG['ANYSCALE_HOST']}" \
f"/o/anyscale-internal/configurations/cluster-computes" \
f"/{compute_tpl_id}"
def anyscale_app_config_build_url(build_id: str):
return f"{GLOBAL_CONFIG['ANYSCALE_HOST']}" \
f"/o/anyscale-internal/configurations/app-config-details" \
f"/{build_id}"
def wheel_url(ray_version, git_branch, git_commit):
return f"https://s3-us-west-2.amazonaws.com/ray-wheels/" \
f"{git_branch}/{git_commit}/" \
f"ray-{ray_version}-cp37-cp37m-manylinux2014_x86_64.whl"
def wheel_exists(ray_version, git_branch, git_commit):
url = wheel_url(ray_version, git_branch, git_commit)
return requests.head(url).status_code == 200
def commit_or_url(commit_or_url: str) -> str:
if commit_or_url.startswith("http"):
# Assume URL
return commit_or_url
# Else, assume commit
os.environ["RAY_COMMIT"] = commit_or_url
return wheel_url(GLOBAL_CONFIG["RAY_VERSION"], GLOBAL_CONFIG["RAY_BRANCH"],
commit_or_url)
def get_latest_commits(repo: str, branch: str = "master") -> List[str]:
cur = os.getcwd()
with tempfile.TemporaryDirectory() as tmpdir:
os.chdir(tmpdir)
clone_cmd = [
"git",
"clone",
"--filter=tree:0",
"--no-checkout",
# "--single-branch",
# "--depth=10",
f"--branch={branch}",
repo,
tmpdir,
]
log_cmd = [
"git",
"log",
"-n",
"10",
"--pretty=format:%H",
]
subprocess.check_output(clone_cmd)
commits = subprocess.check_output(log_cmd).decode(
sys.stdout.encoding).split("\n")
os.chdir(cur)
return commits
def find_ray_wheels(repo: str, branch: str, version: str):
url = None
commits = get_latest_commits(repo, branch)
logger.info(f"Latest 10 commits for branch {branch}: {commits}")
for commit in commits:
if wheel_exists(version, branch, commit):
url = wheel_url(version, branch, commit)
os.environ["RAY_WHEELS"] = url
os.environ["RAY_COMMIT"] = commit
logger.info(
f"Found wheels URL for Ray {version}, branch {branch}: "
f"{url}")
break
return url
def populate_wheels_sanity_check(commit: Optional[str] = None):
if not commit:
cmd = ("python -c 'import ray; print("
"\"No commit sanity check available, but this is the "
"Ray wheel commit:\", ray.__commit__)'")
else:
cmd = (f"python -c 'import ray; "
f"assert ray.__commit__ == \"{commit}\", ray.__commit__'")
os.environ["RAY_WHEELS_SANITY_CHECK"] = cmd
def _check_stop(stop_event: multiprocessing.Event, timeout_type: str):
if stop_event.is_set():
if timeout_type == "prepare_command":
raise PrepareCommandTimeoutError(
"Process timed out in the prepare command stage.")
if timeout_type == "command":
raise CommandTimeoutError(
"Process timed out while running a command.")
elif timeout_type == "file_sync":
raise FileSyncTimeoutError(
"Process timed out while syncing files.")
elif timeout_type == "session":
raise SessionTimeoutError(
"Process timed out while starting a session.")
else:
assert False, "Unexpected timeout type."
def _deep_update(d, u):
for k, v in u.items():
if isinstance(v, collections.abc.Mapping):
d[k] = _deep_update(d.get(k, {}), v)
else:
d[k] = v
return d
def _dict_hash(dt: Dict[Any, Any]) -> str:
json_str = json.dumps(dt, sort_keys=True, ensure_ascii=True)
sha = hashlib.sha256()
sha.update(json_str.encode())
return sha.hexdigest()
def _load_config(local_dir: str, config_file: Optional[str]) -> Optional[Dict]:
if not config_file:
return None
config_path = os.path.join(local_dir, config_file)
with open(config_path, "rt") as f:
# Todo: jinja2 render
content = f.read()
env = copy.deepcopy(os.environ)
env.update(GLOBAL_CONFIG)
content = jinja2.Template(content).render(env=env)
return yaml.safe_load(content)
def has_errored(result: Dict[Any, Any]) -> bool:
return result.get("status", "invalid") != "finished"
def report_result(test_suite: str, test_name: str, status: str, last_logs: str,
results: Dict[Any, Any], artifacts: Dict[Any, Any],
category: str):
now = datetime.datetime.utcnow()
rds_data_client = boto3.client("rds-data", region_name="us-west-2")
schema = GLOBAL_CONFIG["RELEASE_AWS_DB_TABLE"]
sql = (
f"INSERT INTO {schema} "
f"(created_on, test_suite, test_name, status, last_logs, "
f"results, artifacts, category) "
f"VALUES (:created_on, :test_suite, :test_name, :status, :last_logs, "
f":results, :artifacts, :category)")
parameters = [{
"name": "created_on",
"typeHint": "TIMESTAMP",
"value": {
"stringValue": now.strftime("%Y-%m-%d %H:%M:%S")
},
}, {
"name": "test_suite",
"value": {
"stringValue": test_suite
}
}, {
"name": "test_name",
"value": {
"stringValue": test_name
}
}, {
"name": "status",
"value": {
"stringValue": status
}
}, {
"name": "last_logs",
"value": {
"stringValue": last_logs
}
}, {
"name": "results",
"typeHint": "JSON",
"value": {
"stringValue": json.dumps(results)
},
}, {
"name": "artifacts",
"typeHint": "JSON",
"value": {
"stringValue": json.dumps(artifacts)
},
}, {
"name": "category",
"value": {
"stringValue": category
}
}]
# Default boto3 call timeout is 45 seconds.
retry_delay_s = 64
MAX_RDS_RETRY = 3
exponential_backoff_retry(
lambda: rds_data_client.execute_statement(
database=GLOBAL_CONFIG["RELEASE_AWS_DB_NAME"],
parameters=parameters,
secretArn=GLOBAL_CONFIG["RELEASE_AWS_DB_SECRET_ARN"],
resourceArn=GLOBAL_CONFIG["RELEASE_AWS_DB_RESOURCE_ARN"],
schema=schema,
sql=sql),
retry_exceptions=rds_data_client.exceptions.StatementTimeoutException,
initial_retry_delay_s=retry_delay_s,
max_retries=MAX_RDS_RETRY)
logger.info("Result has been persisted to the databse")
def log_results_and_artifacts(result: Dict):
results = result.get("results", {})
if results:
msg = "Observed the following results:\n\n"
for key, val in results.items():
msg += f" {key} = {val}\n"
else:
msg = "Did not find any results."
logger.info(msg)
artifacts = result.get("artifacts", {})
if artifacts:
msg = "Saved the following artifacts:\n\n"
for key, val in artifacts.items():
msg += f" {key} = {val}\n"
else:
msg = "Did not find any artifacts."
logger.info(msg)
def _cleanup_session(sdk: AnyscaleSDK, session_id: str):
if session_id:
# Just trigger a request. No need to wait until session shutdown.
sdk.terminate_session(
session_id=session_id, terminate_session_options={})
def search_running_session(sdk: AnyscaleSDK, project_id: str,
session_name: str) -> Optional[str]:
session_id = None
logger.info(f"Looking for existing session with name {session_name}")
result = sdk.search_sessions(
project_id=project_id,
sessions_query=dict(name=dict(equals=session_name)))
if len(result.results) > 0 and result.results[0].state == "Running":
logger.info("Found existing session.")
session_id = result.results[0].id
return session_id
def create_or_find_compute_template(
sdk: AnyscaleSDK,
project_id: str,
compute_tpl: Dict[Any, Any],
_repeat: bool = True) -> Tuple[Optional[str], Optional[str]]:
compute_tpl_id = None
compute_tpl_name = None
if compute_tpl:
# As of Anyscale 0.4.1, it is an error to use the same compute template
# name within the same organization, between different projects.
compute_tpl_name = f"{project_id}/compute/{_dict_hash(compute_tpl)}"
logger.info(f"Tests uses compute template "
f"with name {compute_tpl_name}. Looking up existing "
f"templates.")
paging_token = None
while not compute_tpl_id:
result = sdk.search_compute_templates(
dict(
project_id=project_id,
name=dict(equals=compute_tpl_name),
include_anonymous=True),
paging_token=paging_token)
paging_token = result.metadata.next_paging_token
for res in result.results:
if res.name == compute_tpl_name:
compute_tpl_id = res.id
logger.info(
f"Template already exists with ID {compute_tpl_id}")
break
if not paging_token:
break
if not compute_tpl_id:
logger.info(f"Compute template not found. "
f"Creating with name {compute_tpl_name}.")
try:
result = sdk.create_compute_template(
dict(
name=compute_tpl_name,
project_id=project_id,
config=compute_tpl))
compute_tpl_id = result.result.id
except Exception as e:
if _repeat:
logger.warning(
f"Got exception when trying to create compute "
f"template: {e}. Sleeping for 10 seconds and then "
f"try again once...")
time.sleep(10)
return create_or_find_compute_template(
sdk=sdk,
project_id=project_id,
compute_tpl=compute_tpl,
_repeat=False)
raise e
logger.info(f"Compute template created with ID {compute_tpl_id}")
return compute_tpl_id, compute_tpl_name
def create_or_find_app_config(
sdk: AnyscaleSDK,
project_id: str,
app_config: Dict[Any, Any],
_repeat: bool = True) -> Tuple[Optional[str], Optional[str]]:
app_config_id = None
app_config_name = None
if app_config:
app_config_name = f"{project_id}-{_dict_hash(app_config)}"
logger.info(f"Test uses an app config with hash {app_config_name}. "
f"Looking up existing app configs with this name.")
paging_token = None
while not app_config_id:
result = sdk.list_app_configs(
project_id=project_id, count=50, paging_token=paging_token)
paging_token = result.metadata.next_paging_token
for res in result.results:
if res.name == app_config_name:
app_config_id = res.id
logger.info(
f"App config already exists with ID {app_config_id}")
break
if not paging_token or app_config_id:
break
if not app_config_id:
logger.info("App config not found. Creating new one.")
try:
result = sdk.create_app_config(
dict(
name=app_config_name,
project_id=project_id,
config_json=app_config))
app_config_id = result.result.id
except Exception as e:
if _repeat:
logger.warning(
f"Got exception when trying to create app "
f"config: {e}. Sleeping for 10 seconds and then "
f"try again once...")
time.sleep(10)
return create_or_find_app_config(
sdk=sdk,
project_id=project_id,
app_config=app_config,
_repeat=False)
raise e
logger.info(f"App config created with ID {app_config_id}")
return app_config_id, app_config_name
def install_app_config_packages(app_config: Dict[Any, Any]):
os.environ.update(app_config.get("env_vars", {}))
packages = app_config["python"]["pip_packages"]
for package in packages:
subprocess.check_output(["pip", "install", "-U", package], text=True)
def install_matching_ray():
wheel = os.environ.get("RAY_WHEELS", None)
if not wheel:
return
assert "manylinux2014_x86_64" in wheel, wheel
if sys.platform == "darwin":
platform = "macosx_10_15_intel"
elif sys.platform == "win32":
platform = "win_amd64"
else:
platform = "manylinux2014_x86_64"
wheel = wheel.replace("manylinux2014_x86_64", platform)
subprocess.check_output(["pip", "uninstall", "-y", "ray"], text=True)
subprocess.check_output(["pip", "install", "-U", wheel], text=True)
def wait_for_build_or_raise(sdk: AnyscaleSDK,
app_config_id: Optional[str]) -> Optional[str]:
if not app_config_id:
return None
# Fetch build
build_id = None
last_status = None
result = sdk.list_builds(app_config_id)
for build in sorted(result.results, key=lambda b: b.created_at):
build_id = build.id
last_status = build.status
if build.status == "failed":
continue
if build.status == "succeeded":
logger.info(f"Link to app config build: "
f"{anyscale_app_config_build_url(build_id)}")
return build_id
if last_status == "failed":
raise AppConfigBuildFailure("App config build failed.")
if not build_id:
raise AppConfigBuildFailure("No build found for app config.")
# Build found but not failed/finished yet
completed = False
start_wait = time.time()
next_report = start_wait + REPORT_S
logger.info(f"Waiting for build {build_id} to finish...")
logger.info(f"Track progress here: "
f"{anyscale_app_config_build_url(build_id)}")
while not completed:
now = time.time()
if now > next_report:
logger.info(f"... still waiting for build {build_id} to finish "
f"({int(now - start_wait)} seconds) ...")
next_report = next_report + REPORT_S
result = sdk.get_build(build_id)
build = result.result
if build.status == "failed":
raise AppConfigBuildFailure(
f"App config build failed. Please see "
f"{anyscale_app_config_build_url(build_id)} for details")
if build.status == "succeeded":
logger.info("Build succeeded.")
return build_id
completed = build.status not in ["in_progress", "pending"]
if completed:
raise AppConfigBuildFailure(
f"Unknown build status: {build.status}. Please see "
f"{anyscale_app_config_build_url(build_id)} for details")
time.sleep(1)
return build_id
def run_job(cluster_name: str, compute_tpl_name: str, cluster_env_name: str,
job_name: str, min_workers: str, script: str,
script_args: List[str], env_vars: Dict[str, str],
autosuspend: int) -> Tuple[int, str]:
# Start cluster and job
address = f"anyscale://{cluster_name}?autosuspend={autosuspend}"
logger.info(f"Starting job {job_name} with Ray address: {address}")
env = copy.deepcopy(os.environ)
env.update(GLOBAL_CONFIG)
env.update(env_vars)
env["RAY_ADDRESS"] = address
env["RAY_JOB_NAME"] = job_name
env["RAY_RELEASE_MIN_WORKERS"] = str(min_workers)
proc = subprocess.Popen(
script.split(" ") + script_args,
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True)
proc.stdout.reconfigure(line_buffering=True)
logs = ""
for line in proc.stdout:
logs += line
sys.stdout.write(line)
proc.wait()
return proc.returncode, logs
def create_and_wait_for_session(
sdk: AnyscaleSDK,
stop_event: multiprocessing.Event,
session_name: str,
session_options: Dict[Any, Any],
) -> str:
# Create session
logger.info(f"Creating session {session_name}")
result = sdk.create_session(session_options)
session_id = result.result.id
# Trigger session start
logger.info(f"Starting session {session_name} ({session_id})")
session_url = anyscale_session_url(
project_id=GLOBAL_CONFIG["ANYSCALE_PROJECT"], session_id=session_id)
logger.info(f"Link to session: {session_url}")
result = sdk.start_session(session_id, start_session_options={})
sop_id = result.result.id
completed = result.result.completed
# Wait for session
logger.info(f"Waiting for session {session_name}...")
start_wait = time.time()
next_report = start_wait + REPORT_S
while not completed:
# Sleep 1 sec before next check.
time.sleep(1)
session_operation_response = sdk.get_session_operation(
sop_id, _request_timeout=30)
session_operation = session_operation_response.result
completed = session_operation.completed
_check_stop(stop_event, "session")
now = time.time()
if now > next_report:
logger.info(f"... still waiting for session {session_name} "
f"({int(now - start_wait)} seconds) ...")
next_report = next_report + REPORT_S
return session_id
def run_session_command(sdk: AnyscaleSDK,
session_id: str,
cmd_to_run: str,
result_queue: multiprocessing.Queue,
env_vars: Dict[str, str],
state_str: str = "CMD_RUN") -> Tuple[str, int]:
full_cmd = " ".join(f"{k}={v}"
for k, v in env_vars.items()) + " " + cmd_to_run
logger.info(f"Running command in session {session_id}: \n" f"{full_cmd}")
session_url = anyscale_session_url(
project_id=GLOBAL_CONFIG["ANYSCALE_PROJECT"], session_id=session_id)
logger.info(f"Link to session: {session_url}")
result_queue.put(State(state_str, time.time(), None))
result = sdk.create_session_command(
dict(session_id=session_id, shell_command=full_cmd))
scd_id = result.result.id
return scd_id, result
def wait_for_session_command_to_complete(create_session_command_result,
sdk: AnyscaleSDK,
scd_id: str,
stop_event: multiprocessing.Event,
state_str: str = "CMD_RUN"):
result = create_session_command_result
completed = result.result.finished_at is not None
start_wait = time.time()
next_report = start_wait + REPORT_S
while not completed:
# Sleep 1 sec before next check.
time.sleep(1)
result = exponential_backoff_retry(
lambda: sdk.get_session_command(session_command_id=scd_id),
retry_exceptions=Exception,
initial_retry_delay_s=10,
max_retries=3)
completed = result.result.finished_at
if state_str == "CMD_RUN":
_check_stop(stop_event, "command")
elif state_str == "CMD_PREPARE":
_check_stop(stop_event, "prepare_command")
now = time.time()
if now > next_report:
logger.info(f"... still waiting for command to finish "
f"({int(now - start_wait)} seconds) ...")
next_report = next_report + REPORT_S
status_code = result.result.status_code
runtime = time.time() - start_wait
if status_code != 0:
if state_str == "CMD_RUN":
raise RuntimeError(
f"Command returned non-success status: {status_code}")
elif state_str == "CMD_PREPARE":
raise PrepareCommandRuntimeError(
f"Prepare command returned non-success status: {status_code}")
return status_code, runtime
def get_command_logs(session_controller: SessionController,
scd_id: str,
lines: int = 50):
result = exponential_backoff_retry(
lambda: session_controller.api_client.get_execution_logs_api_v2_session_commands_session_command_id_execution_logs_get( # noqa: E501
session_command_id=scd_id,
start_line=-1 * lines,
end_line=0),
retry_exceptions=Exception,
initial_retry_delay_s=10,
max_retries=3)
return result.result.lines
def get_remote_json_content(
temp_dir: str,
session_name: str,
remote_file: Optional[str],
session_controller: SessionController,
):
if not remote_file:
logger.warning("No remote file specified, returning empty dict")
return {}
local_target_file = os.path.join(temp_dir, ".tmp.json")
session_controller.pull(
session_name=session_name,
source=remote_file,
target=local_target_file)
with open(local_target_file, "rt") as f:
return json.load(f)
def get_local_json_content(local_file: Optional[str], ):
if not local_file:
logger.warning("No local file specified, returning empty dict")
return {}
with open(local_file, "rt") as f:
return json.load(f)
def pull_artifacts_and_store_in_cloud(
temp_dir: str,
logs: str,
session_name: str,
test_name: str,
artifacts: Optional[Dict[Any, Any]],
session_controller: SessionController,
):
output_log_file = os.path.join(temp_dir, "output.log")
with open(output_log_file, "wt") as f:
f.write(logs)
bucket = GLOBAL_CONFIG["RELEASE_AWS_BUCKET"]
location = f"{GLOBAL_CONFIG['RELEASE_AWS_LOCATION']}" \
f"/{session_name}/{test_name}"
saved_artifacts = {}
s3_client = boto3.client("s3")
s3_client.upload_file(output_log_file, bucket, f"{location}/output.log")
saved_artifacts["output.log"] = f"s3://{bucket}/{location}/output.log"
# Download artifacts
if artifacts:
for name, remote_file in artifacts.items():
logger.info(f"Downloading artifact `{name}` from "
f"{remote_file}")
local_target_file = os.path.join(temp_dir, name)
session_controller.pull(
session_name=session_name,
source=remote_file,
target=local_target_file)
# Upload artifacts to s3
s3_client.upload_file(local_target_file, bucket,
f"{location}/{name}")
saved_artifacts[name] = f"s3://{bucket}/{location}/{name}"
return saved_artifacts
def find_session_by_test_name(
sdk: AnyscaleSDK,
session_controller: SessionController,
temp_dir: str,
state_json: str,
project_id: str,
test_name: str,
) -> Optional[Tuple[str, str, Dict[Any, Any]]]:
paging_token = None
while True: # Will break if paging_token is None after first search
result = sdk.search_sessions(
project_id=project_id,
sessions_query=dict(
name=dict(contains=test_name),
state_filter=["Running"],
paging=dict(count=20, paging_token=paging_token)))
for session in result.results:
logger.info(f"Found sessions {session.name}")
if not session.name.startswith(test_name):
continue
try:
session_state = get_remote_json_content(
temp_dir=temp_dir,
session_name=session.name,
remote_file=state_json,
session_controller=session_controller)
except Exception as exc:
raise RuntimeError(f"Could not get remote json content "
f"for session {session.name}") from exc
if session_state.get("test_name") == test_name:
return session.id, session.name, session_state
session_token = result.metadata.next_paging_token
if not session_token:
return None
def get_latest_running_command_id(sdk: AnyscaleSDK, session_id: str
) -> Tuple[Optional[str], Optional[bool]]:
scd_id = None
paging_token = None
success = None
while not scd_id:
result = sdk.list_session_commands(
session_id=session_id, paging_token=paging_token)
paging_token = result.metadata.next_paging_token
for cmd in result.results:
if not scd_id:
scd_id = cmd.id
completed = cmd.finished_at is not None
if completed:
if success is None:
success = True
success = success and cmd.status_code == 0
if not completed:
return cmd.id, None
return scd_id, success or False
def run_test_config(
local_dir: str,
project_id: str,
test_name: str,
test_config: Dict[Any, Any],
commit_url: str,
session_name: str = None,
smoke_test: bool = False,
no_terminate: bool = False,
kick_off_only: bool = False,
check_progress: bool = False,
upload_artifacts: bool = True,
keep_results_dir: bool = False,
app_config_id_override: Optional[str] = None,
) -> Dict[Any, Any]:
"""
Returns:
Dict with the following entries:
status (str): One of [finished, error, timeout]
command_link (str): Link to command (Anyscale web UI)
last_logs (str): Last logs (excerpt) to send to owner
artifacts (dict): Dict of artifacts
Key: Name
Value: S3 URL
"""
# Todo (mid-term): Support other cluster definitions
# (not only cluster configs)
cluster_config_rel_path = test_config["cluster"].get(
"cluster_config", None)
cluster_config = _load_config(local_dir, cluster_config_rel_path)
app_config_rel_path = test_config["cluster"].get("app_config", None)
app_config = _load_config(local_dir, app_config_rel_path)
compute_tpl_rel_path = test_config["cluster"].get("compute_template", None)
compute_tpl = _load_config(local_dir, compute_tpl_rel_path)
stop_event = multiprocessing.Event()
result_queue = multiprocessing.Queue()
if not session_name:
session_name = f"{test_name}_{int(time.time())}"
temp_dir = tempfile.mkdtemp()
# Result and state files
results_json = test_config["run"].get("results", None)
if results_json is None:
results_json = "/tmp/release_test_out.json"
state_json = test_config["run"].get("state", None)
if state_json is None:
state_json = "/tmp/release_test_state.json"
env_vars = {
"RAY_ADDRESS": os.environ.get("RAY_ADDRESS", "auto"),
"TEST_OUTPUT_JSON": results_json,
"TEST_STATE_JSON": state_json,
"IS_SMOKE_TEST": "1" if smoke_test else "0",
}
with open(os.path.join(local_dir, ".anyscale.yaml"), "wt") as f:
f.write(f"project_id: {project_id}")
os.chdir(local_dir)
# Setup interface
# Unfortunately, there currently seems to be no great way to
# transfer files with the Anyscale SDK.
# So we use the session controller instead.
sdk = AnyscaleSDK(auth_token=GLOBAL_CONFIG["ANYSCALE_CLI_TOKEN"])
session_controller = SessionController(
api_client=instantiate_api_client(
cli_token=GLOBAL_CONFIG["ANYSCALE_CLI_TOKEN"],
host=GLOBAL_CONFIG["ANYSCALE_HOST"],
),
anyscale_api_client=sdk.api_client,
)
timeout = test_config["run"].get("timeout", 1800)
if "RELEASE_OVERRIDE_TIMEOUT" in os.environ:
previous_timeout = timeout
timeout = int(os.environ.get("RELEASE_OVERRIDE_TIMEOUT", str(timeout)))
logger.warning(f"Release test timeout override: {timeout} "
f"(would have been {previous_timeout})")
# If a test is long running, timeout does not mean it failed
is_long_running = test_config["run"].get("long_running", False)
build_id_override = None
if test_config["run"].get("use_connect"):
autosuspend_mins = test_config["run"].get("autosuspend_mins", 5)
assert not kick_off_only, \
"Unsupported for running with Anyscale connect."
if app_config_id_override is not None:
logger.info(
"Using connect and an app config override, waiting until "
"build finishes so we can fetch the app config in order to "
"install its pip packages locally.")
build_id_override = wait_for_build_or_raise(
sdk, app_config_id_override)
response = sdk.get_cluster_environment_build(build_id_override)
app_config = response.result.config_json
install_app_config_packages(app_config)
install_matching_ray()
elif "autosuspend_mins" in test_config["run"]:
raise ValueError(
"'autosuspend_mins' is only supported if 'use_connect' is True.")
# Add information to results dict
def _update_results(results: Dict):
if "last_update" in results:
results["last_update_diff"] = time.time() - results["last_update"]
if smoke_test:
results["smoke_test"] = True
def _process_finished_command(session_controller: SessionController,
scd_id: str,
results: Optional[Dict] = None,
runtime: int = None,
commit_url: str = None,
session_url: str = None):
logger.info("Command finished successfully.")
if results_json:
results = results or get_remote_json_content(
temp_dir=temp_dir,
session_name=session_name,
remote_file=results_json,
session_controller=session_controller,
)
else:
results = {"passed": 1}
_update_results(results)
if scd_id:
logs = get_command_logs(session_controller, scd_id,
test_config.get("log_lines", 50))
else:
logs = "No command found to fetch logs for"
if upload_artifacts:
saved_artifacts = pull_artifacts_and_store_in_cloud(
temp_dir=temp_dir,
logs=logs, # Also save logs in cloud
session_name=session_name,
test_name=test_name,
artifacts=test_config.get("artifacts", {}),
session_controller=session_controller,
)
logger.info("Fetched results and stored on the cloud. Returning.")
else:
saved_artifacts = {}
logger.info("Usually I would have fetched the results and "
"artifacts and stored them on S3.")
# Add these metadata here to avoid changing SQL schema.
results["_runtime"] = runtime
results["_session_url"] = session_url
results["_commit_url"] = commit_url
results["_stable"] = test_config.get("stable", True)
result_queue.put(
State(
"END",
time.time(),
{
"status": "finished",
"last_logs": logs,
"results": results,
"artifacts": saved_artifacts,
},
))
# When running the test script in client mode, the finish command is a
# completed local process.
def _process_finished_client_command(returncode: int, logs: str):
if upload_artifacts:
saved_artifacts = pull_artifacts_and_store_in_cloud(
temp_dir=temp_dir,
logs=logs, # Also save logs in cloud
session_name=session_name,
test_name=test_name,
artifacts=None,
session_controller=None,
)
logger.info("Stored results on the cloud. Returning.")
else:
saved_artifacts = {}
logger.info("Usually I would have fetched the results and "
"artifacts and stored them on S3.")
if results_json:
results = get_local_json_content(local_file=results_json, )
else:
results = {
"passed": int(returncode == 0),
}
results["returncode"] = returncode
_update_results(results)
result_queue.put(
State(
"END",
time.time(),
{
"status": "finished",
"last_logs": logs,
"results": results,
"artifacts": saved_artifacts,
},
))
def _run(logger):
# These values will be set as the test runs.
session_url = None
runtime = None
anyscale.conf.CLI_TOKEN = GLOBAL_CONFIG["ANYSCALE_CLI_TOKEN"]
test_uses_ray_connect = test_config["run"].get("use_connect")
session_id = None
scd_id = None
try:
# First, look for running sessions
session_id = search_running_session(sdk, project_id, session_name)
compute_tpl_name = None
app_config_id = app_config_id_override
app_config_name = None
build_id = build_id_override
if not session_id:
logger.info("No session found.")
# Start session
session_options = dict(
name=session_name, project_id=project_id)
if cluster_config is not None:
logging.info("Starting session with cluster config")
cluster_config_str = json.dumps(cluster_config)
session_options["cluster_config"] = cluster_config_str
session_options["cloud_id"] = (
GLOBAL_CONFIG["ANYSCALE_CLOUD_ID"], )
session_options["uses_app_config"] = False
else:
logging.info("Starting session with app/compute config")
# Find/create compute template
compute_tpl_id, compute_tpl_name = \
create_or_find_compute_template(
sdk, project_id, compute_tpl)
logger.info(f"Link to compute template: "
f"{anyscale_compute_tpl_url(compute_tpl_id)}")
# Find/create app config
if app_config_id is None:
(
app_config_id,
app_config_name,
) = create_or_find_app_config(sdk, project_id,
app_config)
else:
logger.info(
f"Using override app config {app_config_id}")
app_config_name = sdk.get_app_config(
app_config_id).result.name
if build_id is None:
# We might have already retrieved the build ID when
# installing app config packages locally if using
# connect, so only get the build ID if it's not set.
build_id = wait_for_build_or_raise(sdk, app_config_id)
session_options["compute_template_id"] = compute_tpl_id
session_options["build_id"] = build_id
session_options["uses_app_config"] = True
# Start session
session_id = create_and_wait_for_session(
sdk=sdk,
stop_event=stop_event,
session_name=session_name,
session_options=session_options,
)
prepare_command = test_config["run"].get("prepare")
# Write test state json
test_state_file = os.path.join(local_dir, "test_state.json")
with open(test_state_file, "wt") as f:
json.dump({
"start_time": time.time(),
"test_name": test_name
}, f)
if prepare_command or not test_uses_ray_connect:
if test_uses_ray_connect:
logger.info("Found a prepare command, so pushing it "
"to the session.")
# Rsync up
logger.info("Syncing files to session...")
session_controller.push(
session_name=session_name,
source=None,
target=None,
config=None,
all_nodes=False,
)
logger.info("Syncing test state to session...")
session_controller.push(
session_name=session_name,
source=test_state_file,
target=state_json,
config=None,
all_nodes=False,
)
session_url = anyscale_session_url(
project_id=GLOBAL_CONFIG["ANYSCALE_PROJECT"],
session_id=session_id)
_check_stop(stop_event, "file_sync")
# Optionally run preparation command
if prepare_command:
logger.info(
f"Running preparation command: {prepare_command}")
scd_id, result = run_session_command(
sdk=sdk,
session_id=session_id,
cmd_to_run=prepare_command,
result_queue=result_queue,
env_vars=env_vars,
state_str="CMD_PREPARE")
_, _ = wait_for_session_command_to_complete(
result,
sdk=sdk,
scd_id=scd_id,
stop_event=stop_event,
state_str="CMD_PREPARE")
if test_uses_ray_connect:
script_args = test_config["run"].get("args", [])
if smoke_test:
script_args += ["--smoke-test"]
min_workers = 0
for node_type in compute_tpl["worker_node_types"]:
min_workers += node_type["min_workers"]
# Build completed, use job timeout
result_queue.put(State("CMD_RUN", time.time(), None))
returncode, logs = run_job(
cluster_name=session_name,
compute_tpl_name=compute_tpl_name,
cluster_env_name=app_config_name,
job_name=session_name,
min_workers=min_workers,
script=test_config["run"]["script"],
script_args=script_args,
env_vars=env_vars,
autosuspend=autosuspend_mins)
_process_finished_client_command(returncode, logs)
return
# Run release test command
cmd_to_run = test_config["run"]["script"] + " "
args = test_config["run"].get("args", [])
if args:
cmd_to_run += " ".join(args) + " "
if smoke_test:
cmd_to_run += " --smoke-test"
scd_id, result = run_session_command(
sdk=sdk,
session_id=session_id,
cmd_to_run=cmd_to_run,
result_queue=result_queue,
env_vars=env_vars,
state_str="CMD_RUN")
if not kick_off_only:
_, runtime = wait_for_session_command_to_complete(
result,
sdk=sdk,
scd_id=scd_id,
stop_event=stop_event,
state_str="CMD_RUN")
_process_finished_command(
session_controller=session_controller,
scd_id=scd_id,
runtime=runtime,
session_url=session_url,
commit_url=commit_url)
else:
result_queue.put(
State("END", time.time(), {
"status": "kickoff",
"last_logs": ""
}))
except (ReleaseTestTimeoutError, Exception) as e:
logger.error(e, exc_info=True)
logs = str(e)
if scd_id is not None:
try:
logs = logs + "; Command logs:" + get_command_logs(
session_controller, scd_id,
test_config.get("log_lines", 50))
except Exception as e2:
logger.error(e2, exc_info=True)
# Long running tests are "finished" successfully when
# timed out
if isinstance(e, ReleaseTestTimeoutError) and is_long_running:
_process_finished_command(
session_controller=session_controller, scd_id=scd_id)
else:
timeout_type = ""
runtime = None
if isinstance(e, CommandTimeoutError):
timeout_type = "timeout"
runtime = 0
elif (isinstance(e, PrepareCommandTimeoutError)
or isinstance(e, FileSyncTimeoutError)
or isinstance(e, SessionTimeoutError)
or isinstance(e, PrepareCommandRuntimeError)
or isinstance(e, AppConfigBuildFailure)):
timeout_type = "infra_timeout"
runtime = None
elif isinstance(e, RuntimeError):
timeout_type = "runtime_error"
runtime = 0
else:
timeout_type = "unknown timeout"
runtime = None
# Add these metadata here to avoid changing SQL schema.
results = {}
results["_runtime"] = runtime
results["_session_url"] = session_url
results["_commit_url"] = commit_url
results["_stable"] = test_config.get("stable", True)
result_queue.put(
State(
"END", time.time(), {
"status": timeout_type,
"last_logs": logs,
"results": results
}))
finally:
if no_terminate:
logger.warning(
"`no_terminate` is set to True, so the session will "
"*not* be terminated!")
else:
_cleanup_session(sdk, session_id)
def _check_progress(logger):
anyscale.conf.CLI_TOKEN = GLOBAL_CONFIG["ANYSCALE_CLI_TOKEN"]
should_terminate = False
session_id = None
scd_id = None
try:
existing_session = find_session_by_test_name(
sdk=sdk,
session_controller=session_controller,
temp_dir=temp_dir,
state_json=state_json,
project_id=project_id,
test_name=test_name)
if existing_session is None:
logger.info(f"Found no existing session for {test_name}")
result_queue.put(
State("END", time.time(), {
"status": "nosession",
"last_logs": ""
}))
return
session_id, session_name, session_state = existing_session
logger.info(f"Found existing session for {test_name}: "
f"{session_name}")
scd_id, success = get_latest_running_command_id(
sdk=sdk, session_id=session_id)
latest_result = get_remote_json_content(
temp_dir=temp_dir,
session_name=session_name,
remote_file=results_json,
session_controller=session_controller,
)
# Fetch result json and check if it has been updated recently
result_time_key = test_config["run"].get("time_key", None)
maximum_update_delay = test_config["run"].get(
"max_update_delay", None)
if result_time_key and maximum_update_delay:
last_update = latest_result.get(result_time_key, None)
if not last_update:
result_queue.put(
State(
"END", time.time(), {
"status": "error",
"last_logs": f"Test did not store "
f"{result_time_key} in the "
f"results json."
}))
return
delay = time.time() - last_update
logger.info(f"Last update was at {last_update:.2f}. "
f"This was {delay:.2f} seconds ago "
f"(maximum allowed: {maximum_update_delay})")
if delay > maximum_update_delay:
raise RuntimeError(
f"Test did not update the results json within "
f"the last {maximum_update_delay} seconds.")
if time.time() - session_state["start_time"] > timeout:
# Long running test reached timeout
logger.info(
f"Test command reached timeout after {timeout} seconds")
_process_finished_command(
session_controller=session_controller,
scd_id=scd_id,
results=latest_result)
should_terminate = True
elif success:
logger.info("All commands finished.")
_process_finished_command(
session_controller=session_controller,
scd_id=scd_id,
results=latest_result)
should_terminate = True
else:
rest_time = timeout - time.time() + session_state["start_time"]
logger.info(f"Test command should continue running "
f"for {rest_time} seconds")
result_queue.put(
State("END", time.time(), {
"status": "kickoff",
"last_logs": "Test is still running"
}))
except Exception as e:
logger.error(e, exc_info=True)
logs = str(e)
if scd_id is not None:
try:
logs = get_command_logs(session_controller, scd_id,
test_config.get("log_lines", 50))
logs += f"\n{str(e)}"
except Exception as e2:
logger.error(e2, exc_info=True)
result_queue.put(
State("END", time.time(), {
"status": "error",
"last_logs": logs
}))
should_terminate = True
finally:
if should_terminate:
logger.warning("Terminating session")
_cleanup_session(sdk, session_id)
if not check_progress:
process = multiprocessing.Process(target=_run, args=(logger, ))
else:
process = multiprocessing.Process(
target=_check_progress, args=(logger, ))
build_timeout = test_config["run"].get("build_timeout", 1800)
prepare_timeout = test_config["run"].get("prepare_timeout", timeout)
project_url = anyscale_project_url(
project_id=GLOBAL_CONFIG["ANYSCALE_PROJECT"])
logger.info(f"Link to project: {project_url}")
msg = f"This will now run test {test_name}."
if smoke_test:
msg += " This is a smoke test."
if is_long_running:
msg += " This is a long running test."
logger.info(msg)
logger.info(f"Starting process with timeout {timeout} "
f"(prepare timeout {prepare_timeout}, "
f"build timeout {build_timeout})")
process.start()
# The timeout time will be updated after the build finished
# Build = App config + compute template build and session start
timeout_time = time.time() + build_timeout
result = {}
while process.is_alive():
try:
state: State = result_queue.get(timeout=1)
except (Empty, TimeoutError):
if time.time() > timeout_time:
stop_event.set()
logger.warning("Process timed out.")
if not is_long_running:
logger.warning("Terminating process in 10 seconds.")
time.sleep(10)
logger.warning("Terminating process now.")
process.terminate()
else:
logger.info("Process is long running. Give 2 minutes to "
"fetch result and terminate.")
start_terminate = time.time()
while time.time(
) < start_terminate + 120 and process.is_alive():
time.sleep(1)
if process.is_alive():
logger.warning("Terminating forcefully now.")
process.terminate()
else:
logger.info("Long running results collected.")
break
continue
if not isinstance(state, State):
raise RuntimeError(f"Expected `State` object, got {result}")
if state.state == "CMD_PREPARE":
# Reset timeout after build finished
timeout_time = state.timestamp + prepare_timeout
if state.state == "CMD_RUN":
# Reset timeout after prepare command or build finished
timeout_time = state.timestamp + timeout
elif state.state == "END":
result = state.data
break
while not result_queue.empty():
state = result_queue.get_nowait()
result = state.data
logger.info("Final check if everything worked.")
try:
result.setdefault("status", "error (status not found)")
except (TimeoutError, Empty):
result = {"status": "timeout", "last_logs": "Test timed out."}
logger.info(f"Final results: {result}")
log_results_and_artifacts(result)
if not keep_results_dir:
logger.info(f"Removing results dir {temp_dir}")
shutil.rmtree(temp_dir)
else:
# Write results.json
with open(os.path.join(temp_dir, "results.json"), "wt") as fp:
json.dump(result, fp)
out_dir = os.path.expanduser(GLOBAL_CONFIG["RELEASE_RESULTS_DIR"])
logger.info(f"Moving results dir {temp_dir} to persistent location "
f"{out_dir}")
shutil.rmtree(out_dir, ignore_errors=True)
shutil.copytree(temp_dir, out_dir)
logger.info(f"Dir contents: {os.listdir(out_dir)}")
return result
def run_test(test_config_file: str,
test_name: str,
project_id: str,
commit_url: str,
category: str = "unspecified",
smoke_test: bool = False,
no_terminate: bool = False,
kick_off_only: bool = False,
check_progress: bool = False,
report: bool = True,
keep_results_dir: bool = False,
session_name: Optional[str] = None,
app_config_id_override=None) -> Dict[str, Any]:
with open(test_config_file, "rt") as f:
test_configs = yaml.safe_load(f)
test_config_dict = {}
for test_config in test_configs:
name = test_config.pop("name")
test_config_dict[name] = test_config
if test_name not in test_config_dict:
raise ValueError(
f"Test with name `{test_name}` not found in test config file "
f"at `{test_config_file}`.")
test_config = test_config_dict[test_name]
if smoke_test and "smoke_test" in test_config:
smoke_test_config = test_config.pop("smoke_test")
test_config = _deep_update(test_config, smoke_test_config)
local_dir = os.path.dirname(test_config_file)
if "local_dir" in test_config:
# local_dir is relative to test_config_file
local_dir = os.path.join(local_dir, test_config["local_dir"])
if test_config["run"].get("use_connect"):
assert not kick_off_only, \
"--kick-off-only is unsupported when running with " \
"Anyscale connect."
assert not check_progress, \
"--check is unsupported when running with Anyscale connect."
if test_config.get("artifacts", {}):
logger.error(
"Saving artifacts are not yet supported when running with "
"Anyscale connect.")
result = run_test_config(
local_dir,
project_id,
test_name,
test_config,
commit_url,
session_name=session_name,
smoke_test=smoke_test,
no_terminate=no_terminate,
kick_off_only=kick_off_only,
check_progress=check_progress,
upload_artifacts=report,
keep_results_dir=keep_results_dir,
app_config_id_override=app_config_id_override)
status = result.get("status", "invalid")
if kick_off_only:
if status != "kickoff":
raise RuntimeError("Error kicking off test.")
logger.info("Kicked off test. It's now up to the `--check` "
"part of the script to track its process.")
return {}
else:
# `--check` or no kick off only
if status == "nosession":
logger.info(f"No running session found for test {test_name}, so "
f"assuming everything is fine.")
return {}
if status == "kickoff":
logger.info(f"Test {test_name} is still running.")
return {}
last_logs = result.get("last_logs", "No logs.")
test_suite = os.path.basename(test_config_file).replace(".yaml", "")
report_kwargs = dict(
test_suite=test_suite,
test_name=test_name,
status=status,
last_logs=last_logs,
results=result.get("results", {}),
artifacts=result.get("artifacts", {}),
category=category,
)
if report:
report_result(**report_kwargs)
else:
logger.info(f"Usually I would now report the following results:\n"
f"{report_kwargs}")
if has_errored(result):
raise RuntimeError(last_logs)
return report_kwargs
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument(
"--test-config", type=str, required=True, help="Test config file")
parser.add_argument("--test-name", type=str, help="Test name in config")
parser.add_argument(
"--ray-wheels", required=False, type=str, help="URL to ray wheels")
parser.add_argument(
"--no-terminate",
action="store_true",
default=False,
help="Don't terminate session after failure")
parser.add_argument(
"--no-report",
action="store_true",
default=False,
help="Do not report any results or upload to S3")
parser.add_argument(
"--kick-off-only",
action="store_true",
default=False,
help="Kick off only (don't wait for command to finish)")
parser.add_argument(
"--check",
action="store_true",
default=False,
help="Check (long running) status")
parser.add_argument(
"--keep-results-dir",
action="store_true",
default=False,
help="Keep results in directory (named RELEASE_RESULTS_DIR), e.g. "
"for Buildkite artifact upload.")
parser.add_argument(
"--category",
type=str,
default="unspecified",
help="Category name, e.g. `release-1.3.0` (will be saved in database)")
parser.add_argument(
"--smoke-test", action="store_true", help="Finish quickly for testing")
parser.add_argument(
"--session-name",
required=False,
type=str,
help="Name of the session to run this test.")
parser.add_argument(
"--app-config-id-override",
required=False,
type=str,
help=("An app config ID, which will override the test config app "
"config."))
args, _ = parser.parse_known_args()
if not GLOBAL_CONFIG["ANYSCALE_PROJECT"]:
raise RuntimeError(
"You have to set the ANYSCALE_PROJECT environment variable!")
ray_wheels = args.ray_wheels or os.environ.get("RAY_WHEELS", "")
maybe_fetch_api_token()
if ray_wheels:
logger.info(f"Using Ray wheels provided from URL/commit: "
f"{ray_wheels}")
url = commit_or_url(str(ray_wheels))
# Overwrite with actual URL
os.environ["RAY_WHEELS"] = url
elif not args.check:
url = find_ray_wheels(
GLOBAL_CONFIG["RAY_REPO"],
GLOBAL_CONFIG["RAY_BRANCH"],
GLOBAL_CONFIG["RAY_VERSION"],
)
if not url:
raise RuntimeError(f"Could not find wheels for "
f"Ray {GLOBAL_CONFIG['RAY_VERSION']}, "
f"branch {GLOBAL_CONFIG['RAY_BRANCH']}")
# RAY_COMMIT is set by commit_or_url and find_ray_wheels
populate_wheels_sanity_check(os.environ.get("RAY_COMMIT", ""))
test_config_file = os.path.abspath(os.path.expanduser(args.test_config))
result_dict = run_test(
test_config_file=test_config_file,
test_name=args.test_name,
project_id=GLOBAL_CONFIG["ANYSCALE_PROJECT"],
commit_url=url,
category=args.category,
smoke_test=args.smoke_test,
no_terminate=args.no_terminate or args.kick_off_only,
kick_off_only=args.kick_off_only,
check_progress=args.check,
report=not args.no_report,
session_name=args.session_name,
keep_results_dir=args.keep_results_dir,
app_config_id_override=args.app_config_id_override,
)
if result_dict:
# If we get a result dict, check if any alerts should be raised
from alert import SUITE_TO_FN, default_handle_result
logger.info("Checking if results are valid...")
handle_result_kwargs = result_dict.copy()
handle_result_kwargs["created_on"] = None
test_suite = handle_result_kwargs.get("test_suite", None)
test_name = handle_result_kwargs.get("test_name", None)
category = handle_result_kwargs.get("category", None)
handle_fn = SUITE_TO_FN.get(test_suite, None)
if not handle_fn:
logger.warning(f"No handle for suite {test_suite}")
alert = default_handle_result(**handle_result_kwargs)
else:
alert = handle_fn(**handle_result_kwargs)
if alert:
# If we get an alert, the test failed.
raise RuntimeError(alert)
else:
logger.info(f"No alert raised for test {test_suite}/{test_name} "
f"({category}) - the test successfully passed!")
|
the-stack_0_14681 | # Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.d (the "License");
# you may not use this file except in compliance with the License.
# All Credits to https://t.me/azrim89 for timestamp.
# All Credits to https://t.me/Devp73 for Offline stamps..
#
""" Userbot module which contains afk-related commands """
from datetime import datetime
import time
from random import randint
from telethon.events import StopPropagation
from telethon.tl.functions.account import UpdateProfileRequest
from userbot import (AFKREASON, CMD_HELP, BOTLOG, BOTLOG_CHATID, PM_AUTO_BAN,
bot)
from userbot.events import register
# =================================================================
global USER_AFK # pylint:disable=E0602
global afk_time # pylint:disable=E0602
global afk_start
global afk_end
USER_AFK = {}
afk_time = None
afk_start = {}
# =================================================================
@register(outgoing=True, pattern="^.afk(?: |$)(.*)", disable_errors=True)
async def set_afk(afk_e):
""" For .afk command, allows you to inform people that you are afk when they message you """
afk_e.text
string = afk_e.pattern_match.group(1)
global ISAFK
global AFKREASON
global USER_AFK # pylint:disable=E0602
global afk_time # pylint:disable=E0602
global afk_start
global afk_end
user = await bot.get_me()
global reason
USER_AFK = {}
afk_time = None
afk_end = {}
start_1 = datetime.now()
afk_start = start_1.replace(microsecond=0)
if string:
AFKREASON = string
await afk_e.edit(f"**Gonna go AFK. I'll be right back.**")
else:
await afk_e.edit("**Gonna go AFK. I'll be right back.**")
if user.last_name:
await afk_e.client(UpdateProfileRequest(first_name=user.first_name, last_name=user.last_name + " [OFF]"))
else:
await afk_e.client(UpdateProfileRequest(first_name=user.first_name, last_name=" [OFF]"))
if BOTLOG:
await afk_e.client.send_message(BOTLOG_CHATID, "#AFK\nYou went AFK!")
ISAFK = True
afk_time = datetime.now() # pylint:disable=E0602
raise StopPropagation
@register(outgoing=True, pattern="^.unafk(?: |$)(.*)", disable_errors=True)
async def type_afk_is_not_true(notafk):
""" This sets your status as not afk automatically when you write something while being afk """
global ISAFK
global COUNT_MSG
global USERS
global AFKREASON
global USER_AFK # pylint:disable=E0602
global afk_time # pylint:disable=E0602
global afk_start
global afk_end
user = await bot.get_me()
last = user.last_name
if last and last.endswith(" [OFF]"):
raw_last = f"{last}"
last1 = raw_last.replace(" [OFF]", "")
else:
last1 = ""
back_alive = datetime.now()
afk_end = back_alive.replace(microsecond=0)
if ISAFK:
ISAFK = False
msg = await notafk.edit("**I'm back! Did you guys miss me?**")
time.sleep(3)
await msg.delete()
await notafk.client(UpdateProfileRequest(first_name=user.first_name, last_name=last1))
if BOTLOG:
await notafk.client.send_message(
BOTLOG_CHATID,
"You've recieved " + str(COUNT_MSG) + " messages from " +
str(len(USERS)) + " chats while you were away",
)
for i in USERS:
name = await notafk.client.get_entity(i)
name0 = str(name.first_name)
await notafk.client.send_message(
BOTLOG_CHATID,
"[" + name0 + "](tg://user?id=" + str(i) + ")" +
" sent you " + "`" + str(USERS[i]) + " messages`",
)
COUNT_MSG = 0
USERS = {}
AFKREASON = None
@register(incoming=True, disable_edited=True)
async def mention_afk(mention):
""" This function takes care of notifying the people who mention you that you are AFK."""
global COUNT_MSG
global USERS
global ISAFK
global USER_AFK # pylint:disable=E0602
global afk_time # pylint:disable=E0602
global afk_start
global afk_end
await bot.get_me()
back_alivee = datetime.now()
afk_end = back_alivee.replace(microsecond=0)
afk_since = "**a while ago**"
if mention.message.mentioned and not (await mention.get_sender()).bot:
if ISAFK:
now = datetime.now()
datime_since_afk = now - afk_time # pylint:disable=E0602
time = float(datime_since_afk.seconds)
days = time // (24 * 3600)
time = time % (24 * 3600)
hours = time // 3600
time %= 3600
minutes = time // 60
time %= 60
seconds = time
if days == 1:
afk_since = "**Yesterday**"
elif days > 1:
if days > 6:
date = now + \
datetime.timedelta(
days=-days, hours=-hours, minutes=-minutes)
afk_since = date.strftime("%A, %Y %B %m, %H:%I")
else:
wday = now + datetime.timedelta(days=-days)
afk_since = wday.strftime('%A')
elif hours > 1:
afk_since = f"`{int(hours)}h {int(minutes)}m`"
elif minutes > 0:
afk_since = f"`{int(minutes)}m {int(seconds)}s`"
else:
afk_since = f"`{int(seconds)}s`"
if mention.sender_id not in USERS:
if AFKREASON:
await mention.reply(f"**I've been AFK.** (Since {afk_since} ago.)\
\n**Reason:** `{AFKREASON}`")
else:
await mention.reply(f"**I've been AFK.** (Since {afk_since} ago.)")
USERS.update({mention.sender_id: 1})
COUNT_MSG = COUNT_MSG + 1
elif mention.sender_id in USERS:
if USERS[mention.sender_id] % randint(2, 4) == 0:
if AFKREASON:
await mention.reply(f"**I'm still AFK.** (Since {afk_since} ago.)\
\n**Reason:** `{AFKREASON}`")
else:
await mention.reply(f"**I'm still AFK.** (Since {afk_since} ago.)")
USERS[mention.sender_id] = USERS[mention.sender_id] + 1
COUNT_MSG = COUNT_MSG + 1
else:
USERS[mention.sender_id] = USERS[mention.sender_id] + 1
COUNT_MSG = COUNT_MSG + 1
@register(incoming=True, disable_errors=True)
async def afk_on_pm(sender):
""" Function which informs people that you are AFK in PM """
global ISAFK
global USERS
global COUNT_MSG
global COUNT_MSG
global USERS
global ISAFK
global USER_AFK # pylint:disable=E0602
global afk_time # pylint:disable=E0602
global afk_start
global afk_end
await bot.get_me()
back_alivee = datetime.now()
afk_end = back_alivee.replace(microsecond=0)
afk_since = "**a while ago**"
if sender.is_private and sender.sender_id != 777000 and not (
await sender.get_sender()).bot:
if PM_AUTO_BAN:
try:
from userbot.modules.sql_helper.pm_permit_sql import is_approved
apprv = is_approved(sender.sender_id)
except AttributeError:
apprv = True
else:
apprv = True
if apprv and ISAFK:
now = datetime.now()
datime_since_afk = now - afk_time # pylint:disable=E0602
time = float(datime_since_afk.seconds)
days = time // (24 * 3600)
time = time % (24 * 3600)
hours = time // 3600
time %= 3600
minutes = time // 60
time %= 60
seconds = time
if days == 1:
afk_since = "**yesterday**"
elif days > 1:
if days > 6:
date = now + \
datetime.timedelta(
days=-days, hours=-hours, minutes=-minutes)
afk_since = date.strftime("%A, %Y %B %m, %H:%I")
else:
wday = now + datetime.timedelta(days=-days)
afk_since = wday.strftime('%A')
elif hours > 1:
afk_since = f"`{int(hours)}h {int(minutes)}m`"
elif minutes > 0:
afk_since = f"`{int(minutes)}m {int(seconds)}s`"
else:
afk_since = f"`{int(seconds)}s`"
if sender.sender_id not in USERS:
if AFKREASON:
await sender.reply(f"**I've been AFK.** (Since {afk_since} ago.)\
\n**Reason:** `{AFKREASON}`")
else:
await sender.reply(f"**I've been AFK.** (Since {afk_since} ago.)")
USERS.update({sender.sender_id: 1})
COUNT_MSG = COUNT_MSG + 1
elif apprv and sender.sender_id in USERS:
if USERS[sender.sender_id] % randint(2, 4) == 0:
if AFKREASON:
await sender.reply(f"**I'm still AFK.** (Since {afk_since} ago.)\
\n**Reason:** `{AFKREASON}`")
else:
await sender.reply(f"**I'm still AFK.** (Since {afk_since} ago.)")
USERS[sender.sender_id] = USERS[sender.sender_id] + 1
COUNT_MSG = COUNT_MSG + 1
else:
USERS[sender.sender_id] = USERS[sender.sender_id] + 1
COUNT_MSG = COUNT_MSG + 1
CMD_HELP.update({
"afk":
"`.afk` [Optional Reason]\
\nUsage: Sets you as afk.\nReplies to anyone who tags/PM's \
you telling them that you are AFK(reason).\
\n\n`.unafk`\
\nBack from AFK state, anywhere.\
"
})
|
the-stack_0_14682 | from ..base.Dat import Dat
class VerbWord():
def __init__(self, filename1, filename2):
self.__vmDat = Dat(filename=filename1)
self.__vdDat = Dat(filename=filename2)
self.__tagV = 'v'
def adjustTag(self, sentence):
if not self.__vmDat or not self.__vdDat:
return
for i in range(len(sentence) - 1):
if sentence[i].tag == self.__tagV and sentence[i + 1].tag == self.__tagV:
if self.__vmDat.match(sentence[i].word) != -1:
sentence[i].tag = 'vm'
elif self.__vdDat.match(sentence[i + 1].word) != -1:
sentence[i + 1].tag = 'vd'
|
the-stack_0_14685 | ##############################################################################
# Copyright 2016-2019 Rigetti Computing
#
# 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.
##############################################################################
r"""
Standard gate set, as detailed in Quil whitepaper (arXiV:1608:03355v2)
Currently includes:
I - identity :math:`\begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix}`
X - Pauli-X :math:`\begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}`
Y - Pauli-Y :math:`\begin{pmatrix} 0 & -i \\ i & 0 \end{pmatrix}`
Z - Pauli-Z :math:`\begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix}`
H - Hadamard
:math:`\frac{1}{\sqrt{2}} \begin{pmatrix} 1 & 1 \\ 1 & -1 \end{pmatrix}`
S - PHASE(pi/2)
:math:`\begin{pmatrix} 1 & 0 \\ 0 & i \end{pmatrix}`
T - PHASE(pi/4)
:math:`\begin{pmatrix} 1 & 0 \\ 0 & e^{i \pi / 4} \end{pmatrix}`
PHASE(:math:`\phi`) - PHASE
:math:`\begin{pmatrix} 1 & 0 \\ 0 & e^{i \phi} \end{pmatrix}`
RX(:math:`\phi`) - RX
:math:`\begin{pmatrix} \cos(\phi / 2) & -i \sin(\phi/2) \\
-i \sin(\phi/2) & \cos(\phi/2) \end{pmatrix}`
RY(:math:`\phi`) - RY
:math:`\begin{pmatrix} \cos(\phi / 2) & -\sin(\phi / 2) \\
\sin(\phi/2) & \cos(\phi/2) \end{pmatrix}`
RZ(:math:`\phi`) - RZ
:math:`\begin{pmatrix} \cos(\phi/2) - i \sin(\phi/2) & 0 \\
0 & \cos(\phi/2) + i \sin(\phi/2) \end{pmatrix}`
CZ - controlled-Z
:math:`P_0 \otimes I + P_1 \otimes Z = \begin{pmatrix} 1&0&0&0 \\ 0&1&0&0 \\
0&0&1&0 \\ 0&0&0&-1 \end{pmatrix}`
CNOT - controlled-X / controlled-NOT
:math:`P_0 \otimes I + P_1 \otimes X = \begin{pmatrix} 1&0&0&0 \\ 0&1&0&0 \\
0&0&0&1 \\ 0&0&1&0 \end{pmatrix}`
CCNOT - double-controlled-X
:math:`P_0 \otimes P_0 \otimes I + P_0 \otimes P_1 \otimes I + P_1 \otimes P_0 \otimes I
+ P_1 \otimes P_1 \otimes X`
CPHASE00(:math:`\phi`) - controlled-phase-on-|00>
:math:`\text{diag}(e^{i \phi}, 1, 1, 1,)`
CPHASE01(:math:`\phi`) - controlled-phase-on-|01>
:math:`\text{diag}(1, e^{i \phi}, 1, 1,)`
CPHASE10(:math:`\phi`) - controlled-phase-on-|10>
:math:`\text{diag}(1, 1, e^{i \phi}, 1)`
CPHASE(:math:`\phi`) - controlled-phase-on-|11>
:math:`\text{diag}(1, 1, 1, e^{i \phi})`
SWAP - swap
:math:`\begin{pmatrix} 1&0&0&0 \\ 0&0&1&0 \\ 0&1&0&0 \\ 0&0&0&1 \end{pmatrix}`
CSWAP - controlled-swap
:math:`P_0 \otimes I_2 + P_1 \otimes \text{SWAP}`
ISWAP - i-phase-swap
:math:`\begin{pmatrix} 1&0&0&0 \\ 0&0&i&0 \\ 0&i&0&0 \\ 0&0&0&1 \end{pmatrix}`
PSWAP(:math:`\phi`) - phi-phase-swap
:math:`\begin{pmatrix} 1&0&0&0 \\ 0&0&e^{i\phi}&0 \\ 0&e^{i\phi}&0&0 \\ 0&0&0&1 \end{pmatrix}`
XY(:math:`\phi`) - XY-interaction
:math:`\begin{pmatrix} 1&0&0&0 \\
0&\cos(\phi/2)&i\sin(\phi/2)&0 \\
0&i\sin(\phi/2)&\cos(\phi/2)&0 \\
0&0&0&1 \end{pmatrix}`
Specialized gates / internal utility gates:
BARENCO(:math:`\alpha, \phi, \theta`) - Barenco gate
:math:`\begin{pmatrix} 1&0&0&0 \\ 0&1&0&0 \\ 0&0&e^{i\phi} \cos\theta & -i e^{i(\alpha-\phi)}
\sin\theta \\ 0&0&-i e^{i(\alpha+\phi)} \sin\theta & e^{i\alpha} \cos\theta \end{pmatrix}`
P0 - project-onto-zero
:math:`\begin{pmatrix} 1 & 0 \\ 0 & 0 \end{pmatrix}`
P1 - project-onto-one
:math:`\begin{pmatrix} 0 & 0 \\ 0 & 1 \end{pmatrix}`
"""
import cmath
from typing import Tuple
import numpy as np
I = np.array([[1.0, 0.0], [0.0, 1.0]])
X = np.array([[0.0, 1.0], [1.0, 0.0]])
Y = np.array([[0.0, 0.0 - 1.0j], [0.0 + 1.0j, 0.0]])
Z = np.array([[1.0, 0.0], [0.0, -1.0]])
H = (1.0 / np.sqrt(2.0)) * np.array([[1.0, 1.0], [1.0, -1.0]])
S = np.array([[1.0, 0.0], [0.0, 1.0j]])
T = np.array([[1.0, 0.0], [0.0, cmath.exp(1.0j * np.pi / 4.0)]])
def PHASE(phi: float) -> np.ndarray:
return np.array([[1.0, 0.0], [0.0, np.exp(1j * phi)]])
def RX(phi: float) -> np.ndarray:
return np.array(
[[np.cos(phi / 2.0), -1j * np.sin(phi / 2.0)], [-1j * np.sin(phi / 2.0), np.cos(phi / 2.0)]]
)
def RY(phi: float) -> np.ndarray:
return np.array(
[[np.cos(phi / 2.0), -np.sin(phi / 2.0)], [np.sin(phi / 2.0), np.cos(phi / 2.0)]]
)
def RZ(phi: float) -> np.ndarray:
return np.array(
[
[np.cos(phi / 2.0) - 1j * np.sin(phi / 2.0), 0],
[0, np.cos(phi / 2.0) + 1j * np.sin(phi / 2.0)],
]
)
CZ = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1]])
CNOT = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])
CCNOT = np.array(
[
[1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 1, 0],
]
)
def CPHASE00(phi: float) -> np.ndarray:
return np.diag([np.exp(1j * phi), 1.0, 1.0, 1.0])
def CPHASE01(phi: float) -> np.ndarray:
return np.diag([1.0, np.exp(1j * phi), 1.0, 1.0])
def CPHASE10(phi: float) -> np.ndarray:
return np.diag([1.0, 1.0, np.exp(1j * phi), 1.0])
def CPHASE(phi: float) -> np.ndarray:
return np.diag([1.0, 1.0, 1.0, np.exp(1j * phi)])
SWAP = np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]])
CSWAP = np.array(
[
[1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1],
]
)
ISWAP = np.array([[1, 0, 0, 0], [0, 0, 1j, 0], [0, 1j, 0, 0], [0, 0, 0, 1]])
def PSWAP(phi: float) -> np.ndarray:
return np.array(
[[1, 0, 0, 0], [0, 0, np.exp(1j * phi), 0], [0, np.exp(1j * phi), 0, 0], [0, 0, 0, 1]]
)
def XY(phi: float) -> np.ndarray:
return np.array(
[
[1, 0, 0, 0],
[0, np.cos(phi / 2), 1j * np.sin(phi / 2), 0],
[0, 1j * np.sin(phi / 2), np.cos(phi / 2), 0],
[0, 0, 0, 1],
]
)
# Utility gates for internal QVM use
P0 = np.array([[1, 0], [0, 0]])
P1 = np.array([[0, 0], [0, 1]])
# Specialized useful gates; not officially in standard gate set
def BARENCO(alpha: float, phi: float, theta: float) -> np.ndarray:
lower_unitary = np.array(
[
[np.exp(1j * phi) * np.cos(theta), -1j * np.exp(1j * (alpha - phi)) * np.sin(theta)],
[-1j * np.exp(1j * (alpha + phi)) * np.sin(theta), np.exp(1j * alpha) * np.cos(theta)],
]
)
return np.kron(P0, np.eye(2)) + np.kron(P1, lower_unitary)
QUANTUM_GATES = {
"I": I,
"X": X,
"Y": Y,
"Z": Z,
"H": H,
"S": S,
"T": T,
"PHASE": PHASE,
"RX": RX,
"RY": RY,
"RZ": RZ,
"CNOT": CNOT,
"CCNOT": CCNOT,
"CPHASE00": CPHASE00,
"CPHASE01": CPHASE01,
"CPHASE10": CPHASE10,
"CPHASE": CPHASE,
"SWAP": SWAP,
"CSWAP": CSWAP,
"ISWAP": ISWAP,
"PSWAP": PSWAP,
"BARENCO": BARENCO,
"CZ": CZ,
"XY": XY,
}
def relaxation_operators(p: float) -> Tuple[np.ndarray, np.ndarray]:
"""
Return the amplitude damping Kraus operators
"""
k0 = np.array([[1.0, 0.0], [0.0, np.sqrt(1 - p)]])
k1 = np.array([[0.0, np.sqrt(p)], [0.0, 0.0]])
return k0, k1
def dephasing_operators(p: float) -> Tuple[np.ndarray, np.ndarray]:
"""
Return the phase damping Kraus operators
"""
k0 = np.eye(2) * np.sqrt(1 - p / 2)
k1 = np.sqrt(p / 2) * Z
return k0, k1
def depolarizing_operators(p: float) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
"""
Return the phase damping Kraus operators
"""
k0 = np.sqrt(1.0 - p) * I
k1 = np.sqrt(p / 3.0) * X
k2 = np.sqrt(p / 3.0) * Y
k3 = np.sqrt(p / 3.0) * Z
return k0, k1, k2, k3
def phase_flip_operators(p: float) -> Tuple[np.ndarray, np.ndarray]:
"""
Return the phase flip kraus operators
"""
k0 = np.sqrt(1 - p) * I
k1 = np.sqrt(p) * Z
return k0, k1
def bit_flip_operators(p: float) -> Tuple[np.ndarray, np.ndarray]:
"""
Return the phase flip kraus operators
"""
k0 = np.sqrt(1 - p) * I
k1 = np.sqrt(p) * X
return k0, k1
def bitphase_flip_operators(p: float) -> Tuple[np.ndarray, np.ndarray]:
"""
Return the bitphase flip kraus operators
"""
k0 = np.sqrt(1 - p) * I
k1 = np.sqrt(p) * Y
return k0, k1
KRAUS_OPS = {
"relaxation": relaxation_operators,
"dephasing": dephasing_operators,
"depolarizing": depolarizing_operators,
"phase_flip": phase_flip_operators,
"bit_flip": bit_flip_operators,
"bitphase_flip": bitphase_flip_operators,
}
SIC0 = np.array([1, 0])
SIC1 = np.array([1, np.sqrt(2)]) / np.sqrt(3)
SIC2 = np.array([1, np.exp(-np.pi * 2j / 3) * np.sqrt(2)]) / np.sqrt(3)
SIC3 = np.array([1, np.exp(np.pi * 2j / 3) * np.sqrt(2)]) / np.sqrt(3)
"""
The symmetric informationally complete POVMs for a qubit.
These can reduce the number of experiments to perform quantum process tomography.
For more information, please see http://info.phys.unm.edu/~caves/reports/infopovm.pdf
"""
STATES = {
"X": [np.array([1, 1]) / np.sqrt(2), np.array([1, -1]) / np.sqrt(2)],
"Y": [np.array([1, 1j]) / np.sqrt(2), np.array([1, -1j]) / np.sqrt(2)],
"Z": [np.array([1, 0]), np.array([0, 1])],
"SIC": [SIC0, SIC1, SIC2, SIC3],
}
__all__ = list(QUANTUM_GATES.keys()) + [
"relaxation_operators",
"dephasing_operators",
"depolarizing_operators",
"phase_flip_operators",
"bit_flip_operators",
"bitphase_flip_operators",
"STATES",
"SIC0",
"SIC1",
"SIC2",
"SIC3",
]
|
the-stack_0_14687 | #!/usr/bin/env python3
# Copyright 2015-2021 Scott Bezek and the splitflap contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import json
import logging
import os
import subprocess
import sys
from svg_processor import SvgProcessor
from projection_renderer import Renderer
script_dir = os.path.dirname(os.path.abspath(__file__))
source_parts_dir = os.path.dirname(script_dir)
repo_root = os.path.dirname(source_parts_dir)
sys.path.append(repo_root)
from util import rev_info
KERF_PRESETS = {
'ponoko-3mm-mdf': 0.18,
'ponoko-3mm-acrylic': 0.1,
}
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
parser = argparse.ArgumentParser()
parser.add_argument('--panelize', type=int, default=1, help='Quantity to panelize - must be 1 or an even number')
parser.add_argument('--skip-optimize', action='store_true', help='Don\'t remove redundant/overlapping cut lines')
kerf_group = parser.add_mutually_exclusive_group()
kerf_group.add_argument('--kerf', type=float, help='Override kerf_width value')
kerf_group.add_argument('--kerf-preset', choices=KERF_PRESETS, help='Override kerf_width using a defined preset')
parser.add_argument('--render-raster', action='store_true', help='Render raster PNG from the output SVG (requires '
'Inkscape)')
parser.add_argument('--thickness', type=float, help='Override panel thickness value')
parser.add_argument('--no-etch', action='store_true', help='Do not render laser-etched features')
parser.add_argument('--mirror', action='store_true', help='Mirror the assembly so the outside faces are facing up. '
'Note that this will remove all etched features.')
args = parser.parse_args()
laser_parts_directory = os.path.join(source_parts_dir, 'build', 'laser_parts')
extra_variables = {
'render_revision': rev_info.git_short_rev(),
'render_date': rev_info.current_date(),
'render_etch': not args.no_etch,
'render_2d_mirror': args.mirror,
}
if args.kerf is not None:
extra_variables['kerf_width'] = args.kerf
elif args.kerf_preset is not None:
extra_variables['kerf_width'] = KERF_PRESETS[args.kerf_preset]
if args.thickness is not None:
extra_variables['thickness'] = args.thickness
print('Variables:\n' + json.dumps(extra_variables, indent=4))
renderer = Renderer(os.path.join(source_parts_dir, 'splitflap.scad'), laser_parts_directory, extra_variables)
renderer.clean()
svg_output = renderer.render_svgs(panelize_quantity=args.panelize)
logging.info('Removing redundant lines')
processor = SvgProcessor(svg_output)
redundant_lines, merged_lines = None, None
if not args.skip_optimize:
redundant_lines, merged_lines = processor.remove_redundant_lines()
processor.write(svg_output)
logging.info('\n\n\nDone rendering to SVG: ' + svg_output)
if args.render_raster:
# Export to png
logging.info('Generating raster preview')
raster_svg = os.path.join(laser_parts_directory, 'raster.svg')
raster_png = os.path.join(laser_parts_directory, 'raster.png')
processor.apply_raster_render_style()
if not args.skip_optimize:
# Show which redundant lines were removed and lines merged
processor.add_highlight_lines(redundant_lines, '#ff0000')
processor.add_highlight_lines(merged_lines, '#0000ff')
processor.write(raster_svg)
logging.info('Resize SVG canvas')
subprocess.check_call([
'inkscape',
'--verb=FitCanvasToDrawing',
'--verb=FileSave',
'--verb=FileClose',
'--verb=FileQuit',
raster_svg,
])
logging.info('Export PNG')
subprocess.check_call([
'inkscape',
'--export-width=320',
'--export-png', raster_png,
raster_svg,
])
|
the-stack_0_14688 | # coding=utf-8
# Copyright 2020 The HuggingFace 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.
import unittest
from copy import deepcopy
from transformers import RobertaConfig, is_torch_available
from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device
from .test_configuration_common import ConfigTester
from .test_generation_utils import GenerationTesterMixin
from .test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
if is_torch_available():
import torch
from transformers import (
RobertaForCausalLM,
RobertaForMaskedLM,
RobertaForMultipleChoice,
RobertaForQuestionAnswering,
RobertaForSequenceClassification,
RobertaForTokenClassification,
RobertaModel,
)
from transformers.models.roberta.modeling_roberta import (
ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
RobertaEmbeddings,
create_position_ids_from_input_ids,
)
ROBERTA_TINY = "sshleifer/tiny-distilroberta-base"
class RobertaModelTester:
def __init__(
self,
parent,
):
self.parent = parent
self.batch_size = 13
self.seq_length = 7
self.is_training = True
self.use_input_mask = True
self.use_token_type_ids = True
self.use_labels = True
self.vocab_size = 99
self.hidden_size = 32
self.num_hidden_layers = 5
self.num_attention_heads = 4
self.intermediate_size = 37
self.hidden_act = "gelu"
self.hidden_dropout_prob = 0.1
self.attention_probs_dropout_prob = 0.1
self.max_position_embeddings = 512
self.type_vocab_size = 16
self.type_sequence_label_size = 2
self.initializer_range = 0.02
self.num_labels = 3
self.num_choices = 4
self.scope = None
def prepare_config_and_inputs(self):
input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
input_mask = None
if self.use_input_mask:
input_mask = random_attention_mask([self.batch_size, self.seq_length])
token_type_ids = None
if self.use_token_type_ids:
token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
sequence_labels = None
token_labels = None
choice_labels = None
if self.use_labels:
sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
choice_labels = ids_tensor([self.batch_size], self.num_choices)
config = self.get_config()
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def get_config(self):
return RobertaConfig(
vocab_size=self.vocab_size,
hidden_size=self.hidden_size,
num_hidden_layers=self.num_hidden_layers,
num_attention_heads=self.num_attention_heads,
intermediate_size=self.intermediate_size,
hidden_act=self.hidden_act,
hidden_dropout_prob=self.hidden_dropout_prob,
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
max_position_embeddings=self.max_position_embeddings,
type_vocab_size=self.type_vocab_size,
initializer_range=self.initializer_range,
)
def prepare_config_and_inputs_for_decoder(self):
(
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
) = self.prepare_config_and_inputs()
config.is_decoder = True
encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size])
encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2)
return (
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
encoder_hidden_states,
encoder_attention_mask,
)
def create_and_check_model(
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
):
model = RobertaModel(config=config)
model.to(torch_device)
model.eval()
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
result = model(input_ids, token_type_ids=token_type_ids)
result = model(input_ids)
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size))
def create_and_check_model_as_decoder(
self,
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
encoder_hidden_states,
encoder_attention_mask,
):
config.add_cross_attention = True
model = RobertaModel(config)
model.to(torch_device)
model.eval()
result = model(
input_ids,
attention_mask=input_mask,
token_type_ids=token_type_ids,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
)
result = model(
input_ids,
attention_mask=input_mask,
token_type_ids=token_type_ids,
encoder_hidden_states=encoder_hidden_states,
)
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size))
def create_and_check_for_causal_lm(
self,
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
encoder_hidden_states,
encoder_attention_mask,
):
model = RobertaForCausalLM(config=config)
model.to(torch_device)
model.eval()
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
def create_and_check_decoder_model_past_large_inputs(
self,
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
encoder_hidden_states,
encoder_attention_mask,
):
config.is_decoder = True
config.add_cross_attention = True
model = RobertaForCausalLM(config=config).to(torch_device).eval()
# make sure that ids don't start with pad token
mask = input_ids.ne(config.pad_token_id).long()
input_ids = input_ids * mask
# first forward pass
outputs = model(
input_ids,
attention_mask=input_mask,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
use_cache=True,
)
past_key_values = outputs.past_key_values
# create hypothetical multiple next token and extent to next_input_ids
next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
# make sure that ids don't start with pad token
mask = next_tokens.ne(config.pad_token_id).long()
next_tokens = next_tokens * mask
next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)
# append to next input_ids and
next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
next_attention_mask = torch.cat([input_mask, next_mask], dim=-1)
output_from_no_past = model(
next_input_ids,
attention_mask=next_attention_mask,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
output_hidden_states=True,
)["hidden_states"][0]
output_from_past = model(
next_tokens,
attention_mask=next_attention_mask,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
past_key_values=past_key_values,
output_hidden_states=True,
)["hidden_states"][0]
# select random slice
random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
# test that outputs are equal for slice
self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
def create_and_check_for_masked_lm(
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
):
model = RobertaForMaskedLM(config=config)
model.to(torch_device)
model.eval()
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
def create_and_check_for_token_classification(
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
):
config.num_labels = self.num_labels
model = RobertaForTokenClassification(config=config)
model.to(torch_device)
model.eval()
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
def create_and_check_for_multiple_choice(
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
):
config.num_choices = self.num_choices
model = RobertaForMultipleChoice(config=config)
model.to(torch_device)
model.eval()
multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
result = model(
multiple_choice_inputs_ids,
attention_mask=multiple_choice_input_mask,
token_type_ids=multiple_choice_token_type_ids,
labels=choice_labels,
)
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))
def create_and_check_for_question_answering(
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
):
model = RobertaForQuestionAnswering(config=config)
model.to(torch_device)
model.eval()
result = model(
input_ids,
attention_mask=input_mask,
token_type_ids=token_type_ids,
start_positions=sequence_labels,
end_positions=sequence_labels,
)
self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
def prepare_config_and_inputs_for_common(self):
config_and_inputs = self.prepare_config_and_inputs()
(
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
) = config_and_inputs
inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
return config, inputs_dict
@require_torch
class RobertaModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
all_model_classes = (
(
RobertaForCausalLM,
RobertaForMaskedLM,
RobertaModel,
RobertaForSequenceClassification,
RobertaForTokenClassification,
RobertaForMultipleChoice,
RobertaForQuestionAnswering,
)
if is_torch_available()
else ()
)
all_generative_model_classes = (RobertaForCausalLM,) if is_torch_available() else ()
fx_compatible = True
def setUp(self):
self.model_tester = RobertaModelTester(self)
self.config_tester = ConfigTester(self, config_class=RobertaConfig, hidden_size=37)
def test_config(self):
self.config_tester.run_common_tests()
def test_model(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*config_and_inputs)
def test_model_various_embeddings(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
for type in ["absolute", "relative_key", "relative_key_query"]:
config_and_inputs[0].position_embedding_type = type
self.model_tester.create_and_check_model(*config_and_inputs)
def test_model_as_decoder(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
self.model_tester.create_and_check_model_as_decoder(*config_and_inputs)
def test_model_as_decoder_with_default_input_mask(self):
# This regression test was failing with PyTorch < 1.3
(
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
encoder_hidden_states,
encoder_attention_mask,
) = self.model_tester.prepare_config_and_inputs_for_decoder()
input_mask = None
self.model_tester.create_and_check_model_as_decoder(
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
encoder_hidden_states,
encoder_attention_mask,
)
def test_for_causal_lm(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
self.model_tester.create_and_check_for_causal_lm(*config_and_inputs)
def test_decoder_model_past_with_large_inputs(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)
def test_for_masked_lm(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*config_and_inputs)
def test_for_token_classification(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*config_and_inputs)
def test_for_multiple_choice(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs)
def test_for_question_answering(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*config_and_inputs)
@slow
def test_model_from_pretrained(self):
for model_name in ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
model = RobertaModel.from_pretrained(model_name)
self.assertIsNotNone(model)
def test_create_position_ids_respects_padding_index(self):
"""Ensure that the default position ids only assign a sequential . This is a regression
test for https://github.com/huggingface/transformers/issues/1761
The position ids should be masked with the embedding object's padding index. Therefore, the
first available non-padding position index is RobertaEmbeddings.padding_idx + 1
"""
config = self.model_tester.prepare_config_and_inputs()[0]
model = RobertaEmbeddings(config=config)
input_ids = torch.as_tensor([[12, 31, 13, model.padding_idx]])
expected_positions = torch.as_tensor(
[[0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx]]
)
position_ids = create_position_ids_from_input_ids(input_ids, model.padding_idx)
self.assertEqual(position_ids.shape, expected_positions.shape)
self.assertTrue(torch.all(torch.eq(position_ids, expected_positions)))
def test_create_position_ids_from_inputs_embeds(self):
"""Ensure that the default position ids only assign a sequential . This is a regression
test for https://github.com/huggingface/transformers/issues/1761
The position ids should be masked with the embedding object's padding index. Therefore, the
first available non-padding position index is RobertaEmbeddings.padding_idx + 1
"""
config = self.model_tester.prepare_config_and_inputs()[0]
embeddings = RobertaEmbeddings(config=config)
inputs_embeds = torch.empty(2, 4, 30)
expected_single_positions = [
0 + embeddings.padding_idx + 1,
1 + embeddings.padding_idx + 1,
2 + embeddings.padding_idx + 1,
3 + embeddings.padding_idx + 1,
]
expected_positions = torch.as_tensor([expected_single_positions, expected_single_positions])
position_ids = embeddings.create_position_ids_from_inputs_embeds(inputs_embeds)
self.assertEqual(position_ids.shape, expected_positions.shape)
self.assertTrue(torch.all(torch.eq(position_ids, expected_positions)))
@require_torch
class RobertaModelIntegrationTest(TestCasePlus):
@slow
def test_inference_masked_lm(self):
model = RobertaForMaskedLM.from_pretrained("roberta-base")
input_ids = torch.tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
with torch.no_grad():
output = model(input_ids)[0]
expected_shape = torch.Size((1, 11, 50265))
self.assertEqual(output.shape, expected_shape)
# compare the actual values for a slice.
expected_slice = torch.tensor(
[[[33.8802, -4.3103, 22.7761], [4.6539, -2.8098, 13.6253], [1.8228, -3.6898, 8.8600]]]
)
# roberta = torch.hub.load('pytorch/fairseq', 'roberta.base')
# roberta.eval()
# expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach()
self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=1e-4))
@slow
def test_inference_no_head(self):
model = RobertaModel.from_pretrained("roberta-base")
input_ids = torch.tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
with torch.no_grad():
output = model(input_ids)[0]
# compare the actual values for a slice.
expected_slice = torch.tensor(
[[[-0.0231, 0.0782, 0.0074], [-0.1854, 0.0540, -0.0175], [0.0548, 0.0799, 0.1687]]]
)
# roberta = torch.hub.load('pytorch/fairseq', 'roberta.base')
# roberta.eval()
# expected_slice = roberta.extract_features(input_ids)[:, :3, :3].detach()
self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=1e-4))
@slow
def test_inference_classification_head(self):
model = RobertaForSequenceClassification.from_pretrained("roberta-large-mnli")
input_ids = torch.tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
with torch.no_grad():
output = model(input_ids)[0]
expected_shape = torch.Size((1, 3))
self.assertEqual(output.shape, expected_shape)
expected_tensor = torch.tensor([[-0.9469, 0.3913, 0.5118]])
# roberta = torch.hub.load('pytorch/fairseq', 'roberta.large.mnli')
# roberta.eval()
# expected_tensor = roberta.predict("mnli", input_ids, return_logits=True).detach()
self.assertTrue(torch.allclose(output, expected_tensor, atol=1e-4))
# XXX: this might be a candidate for common tests if we have many of those
def test_lm_head_ignore_keys(self):
keys_to_ignore_on_save_tied = [r"lm_head.decoder.weight", r"lm_head.decoder.bias"]
keys_to_ignore_on_save_untied = [r"lm_head.decoder.bias"]
config = RobertaConfig.from_pretrained(ROBERTA_TINY)
config_tied = deepcopy(config)
config_tied.tie_word_embeddings = True
config_untied = deepcopy(config)
config_untied.tie_word_embeddings = False
for cls in [RobertaForMaskedLM, RobertaForCausalLM]:
model = cls(config_tied)
self.assertEqual(model._keys_to_ignore_on_save, keys_to_ignore_on_save_tied, cls)
# the keys should be different when embeddings aren't tied
model = cls(config_untied)
self.assertEqual(model._keys_to_ignore_on_save, keys_to_ignore_on_save_untied, cls)
# test that saving works with updated ignore keys - just testing that it doesn't fail
model.save_pretrained(self.get_auto_remove_tmp_dir())
|
the-stack_0_14689 | """Binary tree
=== CSC148 Winter 2018 ===
University of Toronto,
Department of Computer Science
__author__ = 'Eric K'
=== Module Description ===
This module contains a binary tree implementation
"""
from typing import Union, Optional
class BinaryTree:
"""
A Binary Tree, i.e. arity 2.
"""
value: object
left: Optional['BinaryTree']
right: Optional['BinaryTree']
def __init__(self, value: object, left: Optional['BinaryTree'] = None,
right: Optional['BinaryTree'] = None) -> None:
"""
Create BinaryTree self with value and children left and right.
"""
self.value, self.left, self.right = value, left, right
def __eq__(self, other: Union['BinaryTree', object]) -> bool:
"""
Return whether BinaryTree self is equivalent to other.
>>> BinaryTree(7).__eq__("seven")
False
>>> b1 = BinaryTree(7, BinaryTree(5))
>>> b1.__eq__(BinaryTree(7, BinaryTree(5), None))
True
>>> b1.__eq__(BinaryTree(7, BinaryTree(5,BinaryTree(2)), None))
False
"""
return (type(self) is type(other) and
self.value == other.value and
self.left == other.left and
self.right == other.right)
def __repr__(self) -> str:
"""
Represent BinaryTree (self) as a string that can be evaluated to
produce an equivalent BinaryTree.
>>> BinaryTree(1, BinaryTree(2), BinaryTree(3))
BinaryTree(1, BinaryTree(2), BinaryTree(3))
"""
if self.value is None:
return ''
elif self.left is None and self.right is None:
return f'BinaryTree({self.value})'
else:
return "BinaryTree({}, {}, {})".format(repr(self.value),
repr(self.left),
repr(self.right))
def __str__(self, level: str = '') -> str:
"""
Return a user-friendly string representing BinaryTree (self)
inorder. Indent by indent.
>>> b = BinaryTree(1, BinaryTree(2, BinaryTree(3)), BinaryTree(4))
>>> print(b)
4
1
2
3
<BLANKLINE>
"""
if self.value is None:
return ''
else:
right = self.right.__str__(level + ' ') if self.right else ''
left = self.left.__str__(level + ' ') if self.left else ''
s = right + "{}{}\n".format(level, str(self.value)) + left
return s
def __contains__(self, value: object) -> bool:
"""
Return whether tree rooted at self contains value.
>>> t = BinaryTree(5, BinaryTree(7), BinaryTree(9))
>>> 7 in t
True
>>> t = BinaryTree(5, BinaryTree(7), None)
>>> 3 in t
False
"""
# Can also use: self.left.__contains__(value) rather than in
# Version 1
if self.value is None:
return False
elif value == self.value:
return True
else:
return any([self.left is not None and value in self.left,
self.right is not None and value in self.right])
# Version 2
# if self.value is None:
# return False
# else:
# return any([self.value == value,
# self.left is not None and value in self.left,
# self.right is not None and value in self.right])
# Version 3
# if self.value is None:
# return False
# elif value == self.value:
# return True
# else:
# return any([value in self.left if self.left else False,
# value in self.right if self.right else False])
if __name__ == '__main__':
import doctest
doctest.testmod()
|
the-stack_0_14695 | #!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Interfaces and abstractions for filesystem access.
We should be agnostic whether we're using a "temporary" file
system, rooted in a local tmp dir, or whether we're using
a true HDFS. This file defines the interface.
Note that PEP 355 (Path - object oriented filesystem paths) did
not pass. Many file system methods are in __builtin__, os, or
os.path, and take strings representing filenames as arguments.
We maintain this usage of paths as arguments.
When possible, the interfaces here have fidelity to the
native python interfaces.
"""
from __future__ import division
from future import standard_library
from functools import reduce
standard_library.install_aliases()
from builtins import map
from builtins import range
from builtins import object
import errno
import grp
import logging
import math
import os
import posixpath
import pwd
import re
import shutil
import stat
import sys
if sys.version_info[0] > 2:
from builtins import open as builtins_open
else:
from __builtin__ import open as builtins_open
SEEK_SET, SEEK_CUR, SEEK_END = os.SEEK_SET, os.SEEK_CUR, os.SEEK_END
# The web (and POSIX) always uses forward slash as a separator
LEADING_DOUBLE_SEPARATORS = re.compile("^" + posixpath.sep*2)
def normpath(path):
"""
Eliminates double-slashes.
Oddly, posixpath.normpath doesn't eliminate leading double slashes,
but it does clean-up triple-slashes.
"""
p = posixpath.normpath(path)
return LEADING_DOUBLE_SEPARATORS.sub(posixpath.sep, p)
class IllegalPathException(Exception):
pass
class LocalSubFileSystem(object):
"""
Facade around normal python filesystem calls, for a temporary/local
file system rooted in a root directory. This is intended for testing,
and is not a secure chroot alternative.
So far, this doesn't have a notion of current working dir, so all
paths are "absolute". I dislike the state that having cwd's implies,
but it may be convenient.
TODO(philip):
* chown: want to implement with names, not uids.
* chmod
* stat: perhaps implement "stats" which returns a dictionary;
Hadoop and posix have different stats
* set_replication: no equivalent
* file-system level stats
I think this covers all the functionality in "src/contrib/thriftfs/if/hadoopfs.thrift",
but there may be some bits missing. The implementation of the file-like object
for HDFS will be a bit tricky: open(f, "w") is generally the equivalent
of createFile, but it has to handle the case where f already
exists (in which case the best we can do is append, if that).
"""
def __init__(self, root):
"""
A file system rooted in root.
"""
self.root = root
self.name = "file://%s" % self.root
if not os.path.isdir(root):
logging.fatal("Root(%s) not found." % root +
" Perhaps you need to run manage.py create_test_fs")
def _resolve_path(self, path):
"""
Returns path to use in native file system.
"""
# Strip leading "/"
if not path.startswith("/"):
raise IllegalPathException("Path %s must start with leading /." % path)
path = path.lstrip("/")
joined = os.path.join(self.root, path)
absolute = os.path.abspath(joined)
normalized = os.path.normpath(absolute)
prefix = os.path.commonprefix([self.root, normalized])
if prefix != self.root:
raise IllegalPathException("Path %s is not valid." % path)
return joined
def _unresolve_path(self, path):
"""
Given an absolute path within the wrapped filesystem,
return the path that the user of this class sees.
"""
# Resolve it to make it realy absolute
assert path.startswith(self.root)
return path[len(self.root):]
def _wrap(f, paths=None, users=None, groups=None):
"""
Wraps an existing function f, and transforms
path arguments to "resolved paths" and
user arguments to uids.
By default transforms the first (zeroth) argument as
a path, but can be customized.
This lets us write:
def open(self, name, mode="r"):
return open(self._resolve_path(name), mode)
as
open = _wrap(__builtin__.open)
NOTE: No transformation is done on the keyword args;
they are not accepted. (The alternative would be to
require the names of the keyword transformations.)
"""
if users is None:
users = []
if groups is None:
groups = []
if paths is None and 0 not in users and 0 not in groups:
paths = [0]
# complicated way of taking the intersection of three lists.
assert not reduce(set.intersection, list(map(set, [paths, users, groups])))
def wrapped(*args):
self = args[0]
newargs = list(args[1:])
for i in paths:
newargs[i] = self._resolve_path(newargs[i])
for i in users:
newargs[i] = pwd.getpwnam(newargs[i]).pw_uid
for i in groups:
newargs[i] = grp.getgrnam(newargs[i]).gr_gid
if f == builtins_open and sys.version_info[0] > 2:
return f(*newargs, encoding='utf-8')
return f(*newargs)
return wrapped
# These follow their namesakes.
open = _wrap(builtins_open)
remove = _wrap(os.remove)
mkdir = _wrap(os.mkdir)
rmdir = _wrap(os.rmdir)
listdir = _wrap(os.listdir)
rename = _wrap(os.rename, paths=[0,1])
exists = _wrap(os.path.exists)
isfile = _wrap(os.path.isfile)
isdir = _wrap(os.path.isdir)
chmod = _wrap(os.chmod)
join = _wrap(os.path.join)
# This could be provided with an error_handler
rmtree = _wrap(shutil.rmtree)
chown = _wrap(os.chown, paths=[0], users=[1], groups=[2])
@property
def uri(self):
return self.name
def stats(self, path, raise_on_fnf=True):
path = self._resolve_path(path)
try:
statobj = os.stat(path)
except OSError as ose:
if ose.errno == errno.ENOENT and not raise_on_fnf:
return None
raise
ret = dict()
ret["path"] = self._unresolve_path(path)
ret["size"] = statobj[stat.ST_SIZE]
ret["mtime"] = statobj[stat.ST_MTIME]
ret["mode"] = statobj[stat.ST_MODE]
ret["user"] = pwd.getpwuid(statobj[stat.ST_UID]).pw_name
ret["group"] = grp.getgrgid(statobj[stat.ST_GID]).gr_name
return ret
def setuser(self, user, groups=None):
pass
def status(self):
return FakeStatus()
def listdir_stats(self, path):
"""
This is an equivalent of listdir that, instead of returning file names,
returns a list of stats instead.
"""
listdir_files = self.listdir(path)
paths = [posixpath.join(path, f) for f in listdir_files]
return [self.stats(path) for path in paths]
def __repr__(self):
return "LocalFileSystem(%s)" % repr(self.root)
class FakeStatus(object):
"""
A fake implementation of HDFS health RPCs.
These follow the thrift naming conventions,
but return dicts or arrays of dicts,
because they will be encoded as JSON.
"""
def get_messages(self):
"""Warnings/lint checks."""
return [
dict(type="WARNING",message="All your base belong to us."),
dict(type="INFO", message="Hamster Dance!")
]
def get_health(self):
o = dict()
GB = 1024*1024*1024
o["bytesTotal"] = 5*GB
o["bytesUsed"] = math.floor(5*GB / 2)
o["bytesRemaining"] = 2*GB
o["bytesNonDfs"] = math.floor(GB / 2)
o["liveDataNodes"] = 13
o["deadDataNodes"] = 2
o["upgradeStatus"] = dict(version=13, percentComplete=100, finalized=True)
return o
def get_datanode_report(self):
r = []
for i in range(0, 13):
dinfo = dict()
dinfo["name"] = "fake-%d" % i
dinfo["storageID"] = "fake-id-%d" % i
dinfo["host"] = "fake-host-%d" % i
dinfo["capacity"] = 123456789
dinfo["dfsUsed"] = 23456779
dinfo["remaining"] = 100000010
dinfo["xceiverCount"] = 3
dinfo["state"] = "NORMAL_STATE"
r.append(dinfo)
for i in range(0, 2):
dinfo = dict()
dinfo["name"] = "fake-dead-%d" % i
dinfo["storageID"] = "fake-dead-id-%d" % i
dinfo["host"] = "fake-dead-host-%d" % i
dinfo["capacity"] = 523456789
dinfo["dfsUsed"] = 23456779
dinfo["remaining"] = 500000010
dinfo["xceiverCount"] = 3
dinfo["state"] = "DECOMISSION_INPROGRESS"
r.append(dinfo)
return r
|
the-stack_0_14697 | import anndata as ad
import episcanpy as epi
import scanpy as sc
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import plotly.io as pio
from scanpy.plotting._tools.scatterplots import _get_palette
def river_plot_2_omics(adata,
source,
target,
omic,
cell_number=False,
title='River plot (Sankey Diagram)',
save=None,
scale=4):
"""
cell number count doesn't work in this function yet.
"""
omics = list(set(adata.obs[omic]))
# print(omics[1], ' cells on the left')
adata_rna = adata[adata.obs[omic] == omics[1], :].copy()
# print(omics[0], ' cells on the right')
adata_atac = adata[adata.obs[omic] == omics[0], :].copy()
df_nodes_rna, df_links_rna = __tool_sankey(adata_rna,
source=source,
target=target,
cell_number=False)
key_infos = pd.crosstab(adata_atac.obs[target], adata_atac.obs[source])
# key_infos
label_list = key_infos.columns.tolist()
id_list = list(range(df_nodes_rna.shape[0], df_nodes_rna.shape[0] + len(label_list), 1))
nodes = [['ID', 'Label', 'Color']]
if source + '_colors' not in adata_atac.uns.keys():
adata_atac.uns[source + '_colors'] = list(_get_palette(adata_atac, source).values())
if type(adata_atac.uns[source + '_colors']) == np.ndarray:
adata_atac.uns[source + '_colors'] = adata_atac.uns[source + '_colors'].tolist()
colors = adata.uns[source + '_colors'] + adata.uns[target + '_colors']
index = 0
for number in id_list:
tmp_list = [number, label_list[index], colors[index]]
nodes.append(tmp_list)
index += 1
### merge atac nodes to rna nodes
nodes_headers = nodes.pop(0)
df_nodes = pd.DataFrame(nodes, columns=nodes_headers)
df_nodes = df_nodes_rna.append(df_nodes)
index_target = df_nodes_rna.shape[0] - len(nodes)
# print(index_target)
del nodes
### add cell number
if cell_number:
df_nodes.index = df_nodes['ID']
key_infos = pd.crosstab(adata_atac.obs[target], adata_atac.obs[source], margins=True)
atac_cell_numbers_source = ['(n=' + str(x) + ')' for x in key_infos.loc['All'].tolist()[:-1]]
atac_cell_numbers_target = key_infos['All'].tolist()[:-1]
key_infos = pd.crosstab(adata_rna.obs[target], adata_rna.obs[source], margins=True)
rna_cell_numbers_source = ['(n=' + str(x) + ')' for x in key_infos.loc['All'].tolist()[:-1]]
rna_cell_numbers_target = key_infos['All'].tolist()[:-1]
rna_cell_numbers_target = [": ".join([str(omics[1]), str(x)]) for x in rna_cell_numbers_target]
atac_cell_numbers_target = [": ".join([str(omics[0]), str(x)]) for x in atac_cell_numbers_target]
target_cell_numbers = []
index = 0
for rna_count in rna_cell_numbers_target:
target_cell_numbers.append('(' + ' & '.join([str(rna_count), str(atac_cell_numbers_target[index])]) + ')')
index += 1
total_count = rna_cell_numbers_source + target_cell_numbers + atac_cell_numbers_source
new_label = []
index = 0
for n_cells in total_count:
new_label.append(' '.join([str(df_nodes['Label'][index]), str(n_cells)]))
index += 1
df_nodes['Label'] = new_label
###### LINKS ######
key_infos_values = key_infos.values.tolist()
key_infos_index = key_infos.index.tolist()
# make the link df
links = [['Source', 'Target', 'Value', 'Link Color']]
# index_target = len(label_list)-len(key_infos.index.tolist())
# print(key_infos)
for index_value in key_infos_values:
index_source = df_nodes_rna.shape[0]
index_color = 0
for count in index_value:
tmp_list = [index_source, index_target, count, colors[index_color]]
index_source += 1
index_color += 1
links.append(tmp_list)
index_target += 1
### merge atac links to rna links
links_headers = links.pop(0)
df_links = pd.DataFrame(links, columns=links_headers)
tmp_var = df_links['Source'].tolist()
tmp_var2 = df_links['Target'].tolist()
df_links['Source'] = tmp_var2
df_links['Target'] = tmp_var
del tmp_var, tmp_var2
df_links = df_links_rna.append(df_links)
new_title = title + '\n (' + omics[1] + ' cells on the left & ' + omics[0] + ' cells on the right)'
__plot_sankey(df_nodes, df_links,
title=new_title,
save=save,
scale=4)
def __tool_sankey(adata, source, target, cell_number=True):
# extract key_infos in adata
key_infos = pd.crosstab(adata.obs[target], adata.obs[source])
###### NODES ######
# transform key_infos into the nodes df
nodes = [['ID', 'Label', 'Color']]
if not cell_number:
label_list = key_infos.columns.tolist() + key_infos.index.tolist()
else:
target_cell_nb = pd.crosstab(adata.obs[target], adata.obs[target], margins=True)
source_cell_nb = pd.crosstab(adata.obs[source], adata.obs[source], margins=True)
source_names = []
for n in range(0, len(key_infos.columns.tolist())):
source_names.append(" n=".join([str(key_infos.columns.tolist()[n]), str(source_cell_nb['All'][n])]))
target_names = []
index = 0
for target_name in key_infos.index.tolist():
# print(target_name, target_cell_nb['All'][index])
target_names.append(" n=".join([target_name, str(target_cell_nb['All'][index])]))
index += 1
label_list = source_names + target_names
# print(label_list)
id_list = list(range(0, len(label_list), 1))
# Pay attention if clusters_colors or 'orig.ident_colors' missing
if source + '_colors' not in adata.uns.keys():
adata.uns[source + '_colors'] = list(_get_palette(adata, source).values())
if target + '_colors' not in adata.uns.keys():
adata.uns[target + '_colors'] = list(_get_palette(adata, target).values())
if type(adata.uns[source + '_colors']) == np.ndarray:
adata.uns[source + '_colors'] = adata.uns[source + '_colors'].tolist()
if type(adata.uns[target + '_colors']) == np.ndarray:
adata.uns[target + '_colors'] = adata.uns[target + '_colors'].tolist()
colors = adata.uns[source + '_colors'] + adata.uns[target + '_colors']
for number in id_list:
tmp_list = [number, label_list[number], colors[number]]
nodes.append(tmp_list)
###### LINKS ######
key_infos_values = key_infos.values.tolist()
key_infos_index = key_infos.index.tolist()
# make the link df
links = [['Source', 'Target', 'Value', 'Link Color']]
index_target = len(label_list) - len(key_infos.index.tolist())
for index_value in key_infos_values:
index_source = 0
for count in index_value:
tmp_list = [index_source, index_target, count, colors[index_source]]
index_source += 1
links.append(tmp_list)
index_target += 1
# Retrieve headers and build dataframes
nodes_headers = nodes.pop(0)
links_headers = links.pop(0)
df_nodes = pd.DataFrame(nodes, columns=nodes_headers)
df_links = pd.DataFrame(links, columns=links_headers)
return df_nodes, df_links
def __plot_sankey(df_nodes,
df_links,
title="Draw Sankey Diagram from dataframes",
save=None, scale=1):
"""
"""
# Sankey plot setup
data_trace = dict(
type='sankey',
domain=dict(
x=[0, 1],
y=[0, 1]
),
orientation="h",
valueformat=".0f",
node=dict(
pad=10,
# thickness = 30,
line=dict(
color="black",
width=0
),
label=df_nodes['Label'].dropna(axis=0, how='any'),
color=df_nodes['Color']
),
link=dict(
source=df_links['Source'].dropna(axis=0, how='any'),
target=df_links['Target'].dropna(axis=0, how='any'),
value=df_links['Value'].dropna(axis=0, how='any'),
color=df_links['Link Color'].dropna(axis=0, how='any'),
)
)
layout = dict(
title=title,
height=772,
font=dict(
size=10), )
fig = dict(data=[data_trace], layout=layout)
# fig.savefig('test.png')
iplot(fig, validate=False)
if save:
pio.write_image(fig, save, width=700, height=775, scale=scale)
|
the-stack_0_14698 | import argparse
import math
from urllib.request import urlopen
import sys
import os
import subprocess
import glob
from braceexpand import braceexpand
from types import SimpleNamespace
# pip install taming-transformers work with Gumbel, but does works with coco etc
# appending the path works with Gumbel, but gives ModuleNotFoundError: No module named 'transformers' for coco etc
sys.path.append("taming-transformers")
import os.path
from omegaconf import OmegaConf
from taming.models import cond_transformer, vqgan
import torch
from torch import nn, optim
from torch.nn import functional as F
from torchvision import transforms
from torchvision.transforms import functional as TF
torch.backends.cudnn.benchmark = (
False # NR: True is a bit faster, but can lead to OOM. False is more deterministic.
)
# torch.use_deterministic_algorithms(True) # NR: grid_sampler_2d_backward_cuda does not have a deterministic implementation
from torch_optimizer import DiffGrad, AdamP, RAdam
from perlin_numpy import generate_fractal_noise_2d
from CLIP import clip
import kornia
import kornia.augmentation as K
import numpy as np
import imageio
from PIL import ImageFile, Image, PngImagePlugin
ImageFile.LOAD_TRUNCATED_IMAGES = True
# or 'border'
global_padding_mode = "reflection"
global_aspect_width = 1
vqgan_config_table = {
"imagenet_f16_1024": "http://mirror.io.community/blob/vqgan/vqgan_imagenet_f16_1024.yaml",
"imagenet_f16_16384": "http://mirror.io.community/blob/vqgan/vqgan_imagenet_f16_16384.yaml",
"openimages_f16_8192": "https://heibox.uni-heidelberg.de/d/2e5662443a6b4307b470/files/?p=%2Fconfigs%2Fmodel.yaml&dl=1",
"coco": "https://dl.nmkd.de/ai/clip/coco/coco.yaml",
"faceshq": "https://drive.google.com/uc?export=download&id=1fHwGx_hnBtC8nsq7hesJvs-Klv-P0gzT",
"wikiart_1024": "http://mirror.io.community/blob/vqgan/wikiart.yaml",
"wikiart_16384": "http://mirror.io.community/blob/vqgan/wikiart_16384.yaml",
"sflckr": "https://heibox.uni-heidelberg.de/d/73487ab6e5314cb5adba/files/?p=%2Fconfigs%2F2020-11-09T13-31-51-project.yaml&dl=1",
}
vqgan_checkpoint_table = {
"imagenet_f16_1024": "http://mirror.io.community/blob/vqgan/vqgan_imagenet_f16_1024.ckpt",
"imagenet_f16_16384": "http://mirror.io.community/blob/vqgan/vqgan_imagenet_f16_16384.ckpt",
"openimages_f16_8192": "https://heibox.uni-heidelberg.de/d/2e5662443a6b4307b470/files/?p=%2Fckpts%2Flast.ckpt&dl=1",
"coco": "https://dl.nmkd.de/ai/clip/coco/coco.ckpt",
"faceshq": "https://app.koofr.net/content/links/a04deec9-0c59-4673-8b37-3d696fe63a5d/files/get/last.ckpt?path=%2F2020-11-13T21-41-45_faceshq_transformer%2Fcheckpoints%2Flast.ckpt",
"wikiart_1024": "http://mirror.io.community/blob/vqgan/wikiart.ckpt",
"wikiart_16384": "http://mirror.io.community/blob/vqgan/wikiart_16384.ckpt",
"sflckr": "https://heibox.uni-heidelberg.de/d/73487ab6e5314cb5adba/files/?p=%2Fcheckpoints%2Flast.ckpt&dl=1",
}
# https://stackoverflow.com/a/39662359
def isnotebook():
try:
shell = get_ipython().__class__.__name__
if shell == "ZMQInteractiveShell":
return True # Jupyter notebook or qtconsole
elif shell == "Shell":
return True # Seems to be what co-lab does
elif shell == "TerminalInteractiveShell":
return False # Terminal running IPython
else:
return False # Other type (?)
except NameError:
return False # Probably standard Python interpreter
IS_NOTEBOOK = isnotebook()
if IS_NOTEBOOK:
from IPython import display
from tqdm.notebook import tqdm
else:
from tqdm import tqdm
# file helpers
def real_glob(rglob):
glob_list = braceexpand(rglob)
files = []
for g in glob_list:
files = files + glob.glob(g)
return sorted(files)
# Functions and classes
def sinc(x):
return torch.where(x != 0, torch.sin(math.pi * x) / (math.pi * x), x.new_ones([]))
def lanczos(x, a):
cond = torch.logical_and(-a < x, x < a)
out = torch.where(cond, sinc(x) * sinc(x / a), x.new_zeros([]))
return out / out.sum()
def ramp(ratio, width):
n = math.ceil(width / ratio + 1)
out = torch.empty([n])
cur = 0
for i in range(out.shape[0]):
out[i] = cur
cur += ratio
return torch.cat([-out[1:].flip([0]), out])[1:-1]
# NR: Testing with different intital images
def old_random_noise_image(w, h):
random_image = Image.fromarray(
np.random.randint(0, 255, (w, h, 3), dtype=np.dtype("uint8"))
)
return random_image
def NormalizeData(data):
return (data - np.min(data)) / (np.max(data) - np.min(data))
def random_noise_image(w, h):
# scale up roughly as power of 2
if w > 1024 or h > 1024:
side, octp = 2048, 7
elif w > 512 or h > 512:
side, octp = 1024, 6
elif w > 256 or h > 256:
side, octp = 512, 5
else:
side, octp = 256, 4
nr = NormalizeData(generate_fractal_noise_2d((side, side), (32, 32), octp))
ng = NormalizeData(generate_fractal_noise_2d((side, side), (32, 32), octp))
nb = NormalizeData(generate_fractal_noise_2d((side, side), (32, 32), octp))
stack = np.dstack((nr, ng, nb))
substack = stack[:h, :w, :]
im = Image.fromarray((255.9 * stack).astype("uint8"))
return im
# testing
def gradient_2d(start, stop, width, height, is_horizontal):
if is_horizontal:
return np.tile(np.linspace(start, stop, width), (height, 1))
else:
return np.tile(np.linspace(start, stop, height), (width, 1)).T
def gradient_3d(width, height, start_list, stop_list, is_horizontal_list):
result = np.zeros((height, width, len(start_list)), dtype=float)
for i, (start, stop, is_horizontal) in enumerate(
zip(start_list, stop_list, is_horizontal_list)
):
result[:, :, i] = gradient_2d(start, stop, width, height, is_horizontal)
return result
def random_gradient_image(w, h):
array = gradient_3d(
w,
h,
(0, 0, np.random.randint(0, 255)),
(
np.random.randint(1, 255),
np.random.randint(2, 255),
np.random.randint(3, 128),
),
(True, False, False),
)
random_image = Image.fromarray(np.uint8(array))
return random_image
# Not used?
def resample(input, size, align_corners=True):
n, c, h, w = input.shape
dh, dw = size
input = input.view([n * c, 1, h, w])
if dh < h:
kernel_h = lanczos(ramp(dh / h, 2), 2).to(input.device, input.dtype)
pad_h = (kernel_h.shape[0] - 1) // 2
input = F.pad(input, (0, 0, pad_h, pad_h), "reflect")
input = F.conv2d(input, kernel_h[None, None, :, None])
if dw < w:
kernel_w = lanczos(ramp(dw / w, 2), 2).to(input.device, input.dtype)
pad_w = (kernel_w.shape[0] - 1) // 2
input = F.pad(input, (pad_w, pad_w, 0, 0), "reflect")
input = F.conv2d(input, kernel_w[None, None, None, :])
input = input.view([n, c, h, w])
return F.interpolate(input, size, mode="bicubic", align_corners=align_corners)
class ReplaceGrad(torch.autograd.Function):
@staticmethod
def forward(ctx, x_forward, x_backward):
ctx.shape = x_backward.shape
return x_forward
@staticmethod
def backward(ctx, grad_in):
return None, grad_in.sum_to_size(ctx.shape)
replace_grad = ReplaceGrad.apply
class ClampWithGrad(torch.autograd.Function):
@staticmethod
def forward(ctx, input, min, max):
ctx.min = min
ctx.max = max
ctx.save_for_backward(input)
return input.clamp(min, max)
@staticmethod
def backward(ctx, grad_in):
(input,) = ctx.saved_tensors
return (
grad_in * (grad_in * (input - input.clamp(ctx.min, ctx.max)) >= 0),
None,
None,
)
clamp_with_grad = ClampWithGrad.apply
def vector_quantize(x, codebook):
d = (
x.pow(2).sum(dim=-1, keepdim=True)
+ codebook.pow(2).sum(dim=1)
- 2 * x @ codebook.T
)
indices = d.argmin(-1)
x_q = F.one_hot(indices, codebook.shape[0]).to(d.dtype) @ codebook
return replace_grad(x_q, x)
def spherical_dist_loss(x, y):
x = F.normalize(x, dim=-1)
y = F.normalize(y, dim=-1)
return (x - y).norm(dim=-1).div(2).arcsin().pow(2).mul(2)
class Prompt(nn.Module):
def __init__(self, embed, weight=1.0, stop=float("-inf")):
super().__init__()
self.register_buffer("embed", embed)
self.register_buffer("weight", torch.as_tensor(weight))
self.register_buffer("stop", torch.as_tensor(stop))
def forward(self, input):
input_normed = F.normalize(input.unsqueeze(1), dim=2)
embed_normed = F.normalize(self.embed.unsqueeze(0), dim=2)
dists = input_normed.sub(embed_normed).norm(dim=2).div(2).arcsin().pow(2).mul(2)
dists = dists * self.weight.sign()
return (
self.weight.abs()
* replace_grad(dists, torch.maximum(dists, self.stop)).mean()
)
def parse_prompt(prompt):
vals = prompt.rsplit(":", 2)
vals = vals + ["", "1", "-inf"][len(vals) :]
# print(f"parsed vals is {vals}")
return vals[0], float(vals[1]), float(vals[2])
from typing import cast, Dict, List, Optional, Tuple, Union
# override class to get padding_mode
class MyRandomPerspective(K.RandomPerspective):
def apply_transform(
self,
input: torch.Tensor,
params: Dict[str, torch.Tensor],
transform: Optional[torch.Tensor] = None,
) -> torch.Tensor:
_, _, height, width = input.shape
transform = cast(torch.Tensor, transform)
return kornia.geometry.warp_perspective(
input,
transform,
(height, width),
mode=self.resample.name.lower(),
align_corners=self.align_corners,
padding_mode=global_padding_mode,
)
cached_spot_indexes = {}
def fetch_spot_indexes(sideX, sideY):
# make sure image is loaded if we need it
cache_key = (sideX, sideY)
if cache_key not in cached_spot_indexes:
if global_aspect_width != 1:
mask_image = Image.open("inputs/spot_wide.png")
else:
mask_image = Image.open("inputs/spot_square.png")
# this is a one channel mask
mask_image = mask_image.convert("RGB")
mask_image = mask_image.resize((sideX, sideY), Image.LANCZOS)
mask_image_tensor = TF.to_tensor(mask_image)
# print("ONE CHANNEL ", mask_image_tensor.shape)
mask_indexes = mask_image_tensor.ge(0.5).to(device)
# print("GE ", mask_indexes.shape)
# sys.exit(0)
mask_indexes_off = mask_image_tensor.lt(0.5).to(device)
cached_spot_indexes[cache_key] = [mask_indexes, mask_indexes_off]
return cached_spot_indexes[cache_key]
# n = torch.ones((3,5,5))
# f = generate.fetch_spot_indexes(5, 5)
# f[0].shape = [60,3]
class MakeCutouts(nn.Module):
def __init__(self, cut_size, cutn, cut_pow=1.0):
global global_aspect_width
super().__init__()
self.cut_size = cut_size
self.cutn = cutn
self.cut_pow = cut_pow
self.transforms = None
augmentations = []
if global_aspect_width != 1:
augmentations.append(
K.RandomCrop(
size=(self.cut_size, self.cut_size), p=1.0, return_transform=True
)
)
augmentations.append(
MyRandomPerspective(distortion_scale=0.40, p=0.7, return_transform=True)
)
augmentations.append(
K.RandomResizedCrop(
size=(self.cut_size, self.cut_size),
scale=(0.15, 0.80),
ratio=(0.75, 1.333),
cropping_mode="resample",
p=0.7,
return_transform=True,
)
)
augmentations.append(
K.ColorJitter(hue=0.1, saturation=0.1, p=0.8, return_transform=True)
)
self.augs = nn.Sequential(*augmentations)
# self.augs = nn.Sequential(
# # K.RandomHorizontalFlip(p=0.5), # NR: add augmentation options
# # K.RandomVerticalFlip(p=0.5),
# # K.RandomSolarize(0.01, 0.01, p=0.7),
# # K.RandomSharpness(0.3,p=0.4),
# # K.RandomResizedCrop(size=(self.cut_size,self.cut_size), scale=(0.1,1), ratio=(0.75,1.333), cropping_mode='resample', p=0.5, return_transform=True),
# K.RandomCrop(size=(self.cut_size,self.cut_size), p=1.0),
# # K.RandomAffine(degrees=15, translate=0.1, p=0.7, padding_mode='border', return_transform=True),
# # MyRandomPerspective(distortion_scale=0.40, p=0.7, return_transform=True),
# # K.RandomResizedCrop(size=(self.cut_size,self.cut_size), scale=(0.15,0.80), ratio=(0.75,1.333), cropping_mode='resample', p=0.7, return_transform=True),
# K.ColorJitter(hue=0.1, saturation=0.1, p=0.8, return_transform=True),
# # K.RandomErasing((.1, .4), (.3, 1/.3), same_on_batch=True, p=0.7, return_transform=True),
# )
self.noise_fac = 0.1
# Pooling
self.av_pool = nn.AdaptiveAvgPool2d((self.cut_size, self.cut_size))
self.max_pool = nn.AdaptiveMaxPool2d((self.cut_size, self.cut_size))
def forward(self, input, spot=None):
global i, global_aspect_width
sideY, sideX = input.shape[2:4]
max_size = min(sideX, sideY)
min_size = min(sideX, sideY, self.cut_size)
cutouts = []
mask_indexes = None
if spot is not None:
spot_indexes = fetch_spot_indexes(self.cut_size, self.cut_size)
if spot == 0:
mask_indexes = spot_indexes[1]
else:
mask_indexes = spot_indexes[0]
# print("Mask indexes ", mask_indexes)
for _ in range(self.cutn):
# size = int(torch.rand([])**self.cut_pow * (max_size - min_size) + min_size)
# offsetx = torch.randint(0, sideX - size + 1, ())
# offsety = torch.randint(0, sideY - size + 1, ())
# cutout = input[:, :, offsety:offsety + size, offsetx:offsetx + size]
# cutouts.append(resample(cutout, (self.cut_size, self.cut_size)))
# cutout = transforms.Resize(size=(self.cut_size, self.cut_size))(input)
# Pooling
cutout = (self.av_pool(input) + self.max_pool(input)) / 2
if mask_indexes is not None:
cutout[0][mask_indexes] = 0.5
if global_aspect_width != 1:
cutout = kornia.geometry.transform.rescale(cutout, (1, 16 / 9))
# if i % 50 == 0 and _ == 0:
# print(cutout.shape)
# TF.to_pil_image(cutout[0].cpu()).save(f"cutout_im_{i:02d}_{spot}.png")
cutouts.append(cutout)
if self.transforms is not None:
# print("Cached transforms available, but I'm not smart enough to use them")
# print(cutouts.shape)
# print(torch.cat(cutouts, dim=0).shape)
# print(self.transforms.shape)
# batch = kornia.geometry.transform.warp_affine(torch.cat(cutouts, dim=0), self.transforms, (sideY, sideX))
# batch = self.transforms @ torch.cat(cutouts, dim=0)
batch = kornia.geometry.transform.warp_perspective(
torch.cat(cutouts, dim=0),
self.transforms,
(self.cut_size, self.cut_size),
padding_mode=global_padding_mode,
)
# if i < 4:
# for j in range(4):
# TF.to_pil_image(batch[j].cpu()).save(f"cached_im_{i:02d}_{j:02d}_{spot}.png")
else:
batch, self.transforms = self.augs(torch.cat(cutouts, dim=0))
# if i < 4:
# for j in range(4):
# TF.to_pil_image(batch[j].cpu()).save(f"live_im_{i:02d}_{j:02d}_{spot}.png")
# print(batch.shape, self.transforms.shape)
if self.noise_fac:
facs = batch.new_empty([self.cutn, 1, 1, 1]).uniform_(0, self.noise_fac)
batch = batch + facs * torch.randn_like(batch)
return batch
def load_vqgan_model(config_path, checkpoint_path):
global gumbel
gumbel = False
config = OmegaConf.load(config_path)
if config.model.target == "taming.models.vqgan.VQModel":
model = vqgan.VQModel(**config.model.params)
model.eval().requires_grad_(False)
model.init_from_ckpt(checkpoint_path)
elif config.model.target == "taming.models.vqgan.GumbelVQ":
model = vqgan.GumbelVQ(**config.model.params)
model.eval().requires_grad_(False)
model.init_from_ckpt(checkpoint_path)
gumbel = True
elif config.model.target == "taming.models.cond_transformer.Net2NetTransformer":
parent_model = cond_transformer.Net2NetTransformer(**config.model.params)
parent_model.eval().requires_grad_(False)
parent_model.init_from_ckpt(checkpoint_path)
model = parent_model.first_stage_model
else:
raise ValueError(f"unknown model type: {config.model.target}")
del model.loss
return model
def resize_image(image, out_size):
ratio = image.size[0] / image.size[1]
area = min(image.size[0] * image.size[1], out_size[0] * out_size[1])
size = round((area * ratio) ** 0.5), round((area / ratio) ** 0.5)
return image.resize(size, Image.LANCZOS)
def wget_file(url, out):
try:
output = subprocess.check_output(["wget", "-O", out, url])
except subprocess.CalledProcessError as cpe:
output = e.output
print("Ignoring non-zero exit: ", output)
def do_init(args):
global model, opt, perceptors, normalize, cutoutsTable, cutoutSizeTable
global z, z_orig, z_targets, z_labels, z_min, z_max, init_image_tensor
global gside_X, gside_Y, overlay_image_rgba
global pmsTable, pImages, device, spotPmsTable, spotOffPmsTable
# Do it (init that is)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
if args.vqgan_config is not None:
vqgan_config = args.vqgan_config
vqgan_checkpoint = args.vqgan_checkpoint
else:
# the "vqgan_model" option also downloads if necessary
vqgan_config = f"models/vqgan_{args.vqgan_model}.yaml"
vqgan_checkpoint = f"models/vqgan_{args.vqgan_model}.ckpt"
if not os.path.exists(vqgan_config):
wget_file(vqgan_config_table[args.vqgan_model], vqgan_config)
if not os.path.exists(vqgan_checkpoint):
wget_file(vqgan_checkpoint_table[args.vqgan_model], vqgan_checkpoint)
model = load_vqgan_model(vqgan_config, vqgan_checkpoint).to(device)
jit = True if float(torch.__version__[:3]) < 1.8 else False
f = 2 ** (model.decoder.num_resolutions - 1)
for clip_model in args.clip_models:
perceptor = (
clip.load(clip_model, jit=jit)[0].eval().requires_grad_(False).to(device)
)
perceptors[clip_model] = perceptor
# TODO: is one cut_size enought? I hope so.
cut_size = perceptor.visual.input_resolution
cutoutSizeTable[clip_model] = cut_size
if not cut_size in cutoutsTable:
make_cutouts = MakeCutouts(cut_size, args.num_cuts, cut_pow=args.cut_pow)
cutoutsTable[cut_size] = make_cutouts
toksX, toksY = args.size[0] // f, args.size[1] // f
sideX, sideY = toksX * f, toksY * f
if gumbel:
e_dim = 256
n_toks = model.quantize.n_embed
z_min = model.quantize.embed.weight.min(dim=0).values[None, :, None, None]
z_max = model.quantize.embed.weight.max(dim=0).values[None, :, None, None]
else:
e_dim = model.quantize.e_dim
n_toks = model.quantize.n_e
z_min = model.quantize.embedding.weight.min(dim=0).values[None, :, None, None]
z_max = model.quantize.embedding.weight.max(dim=0).values[None, :, None, None]
# z_min = model.quantize.embedding.weight.min(dim=0).values[None, :, None, None]
# z_max = model.quantize.embedding.weight.max(dim=0).values[None, :, None, None]
# normalize_imagenet = transforms.Normalize(mean=[0.485, 0.456, 0.406],
# std=[0.229, 0.224, 0.225])
# save sideX, sideY in globals (need if using overlay)
gside_X = sideX
gside_Y = sideY
init_image_tensor = None
# Image initialisation
if args.init_image or args.init_noise:
# setup init image wih pil
# first - always start with noise or blank
if args.init_noise == "pixels":
img = random_noise_image(args.size[0], args.size[1])
elif args.init_noise == "gradient":
img = random_gradient_image(args.size[0], args.size[1])
else:
img = Image.new(
mode="RGB", size=(args.size[0], args.size[1]), color=(255, 255, 255)
)
starting_image = img.convert("RGB")
starting_image = starting_image.resize((sideX, sideY), Image.LANCZOS)
if args.init_image:
# now we might overlay an init image (init_image also can be recycled as overlay)
if "http" in args.init_image:
init_image = Image.open(urlopen(args.init_image))
else:
init_image = Image.open(args.init_image)
# this version is needed potentially for the loss function
init_image_rgb = init_image.convert("RGB")
init_image_rgb = init_image_rgb.resize((sideX, sideY), Image.LANCZOS)
init_image_tensor = TF.to_tensor(init_image_rgb)
init_image_tensor = init_image_tensor.to(device).unsqueeze(0)
# this version gets overlaid on the background (noise)
init_image_rgba = init_image.convert("RGBA")
init_image_rgba = init_image_rgba.resize((sideX, sideY), Image.LANCZOS)
top_image = init_image_rgba.copy()
if args.init_image_alpha and args.init_image_alpha >= 0:
top_image.putalpha(args.init_image_alpha)
starting_image.paste(top_image, (0, 0), top_image)
starting_image.save("starting_image.png")
starting_tensor = TF.to_tensor(starting_image)
z, *_ = model.encode(starting_tensor.to(device).unsqueeze(0) * 2 - 1)
else:
# legacy init
one_hot = F.one_hot(
torch.randint(n_toks, [toksY * toksX], device=device), n_toks
).float()
# z = one_hot @ model.quantize.embedding.weight
if gumbel:
z = one_hot @ model.quantize.embed.weight
else:
z = one_hot @ model.quantize.embedding.weight
z = z.view([-1, toksY, toksX, e_dim]).permute(0, 3, 1, 2)
if args.overlay_every:
if args.overlay_image:
if "http" in args.overlay_image:
overlay_image = Image.open(urlopen(args.overlay_image))
else:
overlay_image = Image.open(args.overlay_image)
overlay_image_rgba = overlay_image.convert("RGBA")
overlay_image_rgba = overlay_image_rgba.resize(
(sideX, sideY), Image.LANCZOS
)
else:
overlay_image_rgba = init_image_rgba
if args.overlay_alpha:
overlay_image_rgba.putalpha(args.overlay_alpha)
overlay_image_rgba.save("overlay_image.png")
if args.target_images is not None:
z_targets = []
filelist = real_glob(args.target_images)
for target_image in filelist:
target_image = Image.open(target_image)
target_image_rgb = target_image.convert("RGB")
target_image_rgb = target_image_rgb.resize((sideX, sideY), Image.LANCZOS)
target_image_tensor = TF.to_tensor(target_image_rgb)
target_image_tensor = target_image_tensor.to(device).unsqueeze(0) * 2 - 1
z_target, *_ = model.encode(target_image_tensor)
z_targets.append(z_target)
if args.image_labels is not None:
z_labels = []
filelist = real_glob(args.image_labels)
cur_labels = []
for image_label in filelist:
image_label = Image.open(image_label)
image_label_rgb = image_label.convert("RGB")
image_label_rgb = image_label_rgb.resize((sideX, sideY), Image.LANCZOS)
image_label_rgb_tensor = TF.to_tensor(image_label_rgb)
image_label_rgb_tensor = (
image_label_rgb_tensor.to(device).unsqueeze(0) * 2 - 1
)
z_label, *_ = model.encode(image_label_rgb_tensor)
cur_labels.append(z_label)
image_embeddings = torch.stack(cur_labels)
print("Processing labels: ", image_embeddings.shape)
image_embeddings /= image_embeddings.norm(dim=-1, keepdim=True)
image_embeddings = image_embeddings.mean(dim=0)
image_embeddings /= image_embeddings.norm()
z_labels.append(image_embeddings.unsqueeze(0))
z_orig = z.clone()
z.requires_grad_(True)
pmsTable = {}
spotPmsTable = {}
spotOffPmsTable = {}
for clip_model in args.clip_models:
pmsTable[clip_model] = []
spotPmsTable[clip_model] = []
spotOffPmsTable[clip_model] = []
pImages = []
normalize = transforms.Normalize(
mean=[0.48145466, 0.4578275, 0.40821073],
std=[0.26862954, 0.26130258, 0.27577711],
)
# CLIP tokenize/encode
# NR: Weights / blending
for prompt in args.prompts:
for clip_model in args.clip_models:
pMs = pmsTable[clip_model]
perceptor = perceptors[clip_model]
txt, weight, stop = parse_prompt(prompt)
embed = perceptor.encode_text(clip.tokenize(txt).to(device)).float()
pMs.append(Prompt(embed, weight, stop).to(device))
for prompt in args.spot_prompts:
for clip_model in args.clip_models:
pMs = spotPmsTable[clip_model]
perceptor = perceptors[clip_model]
txt, weight, stop = parse_prompt(prompt)
embed = perceptor.encode_text(clip.tokenize(txt).to(device)).float()
pMs.append(Prompt(embed, weight, stop).to(device))
for prompt in args.spot_prompts_off:
for clip_model in args.clip_models:
pMs = spotOffPmsTable[clip_model]
perceptor = perceptors[clip_model]
txt, weight, stop = parse_prompt(prompt)
embed = perceptor.encode_text(clip.tokenize(txt).to(device)).float()
pMs.append(Prompt(embed, weight, stop).to(device))
for label in args.labels:
for clip_model in args.clip_models:
pMs = pmsTable[clip_model]
perceptor = perceptors[clip_model]
txt, weight, stop = parse_prompt(label)
texts = [
template.format(txt) for template in imagenet_templates
] # format with class
print(f"Tokenizing all of {texts}")
texts = clip.tokenize(texts).to(device) # tokenize
class_embeddings = perceptor.encode_text(texts) # embed with text encoder
class_embeddings /= class_embeddings.norm(dim=-1, keepdim=True)
class_embedding = class_embeddings.mean(dim=0)
class_embedding /= class_embedding.norm()
pMs.append(Prompt(class_embedding.unsqueeze(0), weight, stop).to(device))
for prompt in args.image_prompts:
path, weight, stop = parse_prompt(prompt)
img = Image.open(path)
pil_image = img.convert("RGB")
img = resize_image(pil_image, (sideX, sideY))
pImages.append(TF.to_tensor(img).unsqueeze(0).to(device))
# batch = make_cutouts(TF.to_tensor(img).unsqueeze(0).to(device))
# embed = perceptor.encode_image(normalize(batch)).float()
# pMs.append(Prompt(embed, weight, stop).to(device))
for seed, weight in zip(args.noise_prompt_seeds, args.noise_prompt_weights):
gen = torch.Generator().manual_seed(seed)
embed = torch.empty([1, perceptor.visual.output_dim]).normal_(generator=gen)
pMs.append(Prompt(embed, weight).to(device))
# Set the optimiser
if args.optimiser == "Adam":
opt = optim.Adam([z], lr=args.step_size) # LR=0.1
elif args.optimiser == "AdamW":
opt = optim.AdamW([z], lr=args.step_size) # LR=0.2
elif args.optimiser == "Adagrad":
opt = optim.Adagrad([z], lr=args.step_size) # LR=0.5+
elif args.optimiser == "Adamax":
opt = optim.Adamax([z], lr=args.step_size) # LR=0.5+?
elif args.optimiser == "DiffGrad":
opt = DiffGrad([z], lr=args.step_size) # LR=2+?
elif args.optimiser == "AdamP":
opt = AdamP([z], lr=args.step_size) # LR=2+?
elif args.optimiser == "RAdam":
opt = RAdam([z], lr=args.step_size) # LR=2+?
# Output for the user
print("Using device:", device)
print("Optimising using:", args.optimiser)
if args.prompts:
print("Using text prompts:", args.prompts)
if args.spot_prompts:
print("Using spot prompts:", args.spot_prompts)
if args.spot_prompts_off:
print("Using spot off prompts:", args.spot_prompts_off)
if args.image_prompts:
print("Using image prompts:", args.image_prompts)
if args.init_image:
print("Using initial image:", args.init_image)
if args.noise_prompt_weights:
print("Noise prompt weights:", args.noise_prompt_weights)
if args.seed is None:
seed = torch.seed()
else:
seed = args.seed
torch.manual_seed(seed)
print("Using seed:", seed)
def synth(z):
if gumbel:
z_q = vector_quantize(z.movedim(1, 3), model.quantize.embed.weight).movedim(
3, 1
) # Vector quantize
else:
z_q = vector_quantize(z.movedim(1, 3), model.quantize.embedding.weight).movedim(
3, 1
)
return clamp_with_grad(model.decode(z_q).add(1).div(2), 0, 1)
# dreaded globals (for now)
z = None
z_orig = None
z_targets = None
z_labels = None
z_min = None
z_max = None
opt = None
model = None
perceptors = {}
normalize = None
cutoutsTable = {}
cutoutSizeTable = {}
init_image_tensor = None
pmsTable = None
spotPmsTable = None
spotOffPmsTable = None
pImages = None
gside_X = None
gside_Y = None
overlay_image_rgba = None
device = None
# OK, THIS ONE IS AWFUL
i = None
@torch.no_grad()
def z_to_pil():
global z
out = synth(z)
return TF.to_pil_image(out[0].cpu())
@torch.no_grad()
def checkin(args, i, losses):
losses_str = ", ".join(f"{loss.item():g}" for loss in losses)
tqdm.write(f"i: {i}, loss: {sum(losses).item():g}, losses: {losses_str}")
info = PngImagePlugin.PngInfo()
info.add_text("comment", f"{args.prompts}")
img = z_to_pil()
img.save(args.output, pnginfo=info)
if IS_NOTEBOOK:
display.display(display.Image(args.output))
def ascend_txt(args):
global i, perceptors, normalize, cutoutsTable, cutoutSizeTable
global z, z_orig, z_targets, z_labels, init_image_tensor
global pmsTable, spotPmsTable, spotOffPmsTable, global_padding_mode
out = synth(z)
result = []
if i % 2 == 0:
global_padding_mode = "reflection"
else:
global_padding_mode = "border"
cur_cutouts = {}
cur_spot_cutouts = {}
cur_spot_off_cutouts = {}
for cutoutSize in cutoutsTable:
make_cutouts = cutoutsTable[cutoutSize]
cur_cutouts[cutoutSize] = make_cutouts(out)
if args.spot_prompts:
for cutoutSize in cutoutsTable:
cur_spot_cutouts[cutoutSize] = make_cutouts(out, spot=1)
if args.spot_prompts_off:
for cutoutSize in cutoutsTable:
cur_spot_off_cutouts[cutoutSize] = make_cutouts(out, spot=0)
for clip_model in args.clip_models:
perceptor = perceptors[clip_model]
cutoutSize = cutoutSizeTable[clip_model]
transient_pMs = []
if args.spot_prompts:
iii_s = perceptor.encode_image(
normalize(cur_spot_cutouts[cutoutSize])
).float()
spotPms = spotPmsTable[clip_model]
for prompt in spotPms:
result.append(prompt(iii_s))
if args.spot_prompts_off:
iii_so = perceptor.encode_image(
normalize(cur_spot_off_cutouts[cutoutSize])
).float()
spotOffPms = spotOffPmsTable[clip_model]
for prompt in spotOffPms:
result.append(prompt(iii_so))
pMs = pmsTable[clip_model]
iii = perceptor.encode_image(normalize(cur_cutouts[cutoutSize])).float()
for prompt in pMs:
result.append(prompt(iii))
# If there are image prompts we make cutouts for those each time
# so that they line up with the current cutouts from augmentation
make_cutouts = cutoutsTable[cutoutSize]
for timg in pImages:
# note: this caches and reuses the transforms - a bit of a hack but it works
if args.image_prompt_shuffle:
# print("Disabling cached transforms")
make_cutouts.transforms = None
# new way builds throwaway Prompts
batch = make_cutouts(timg)
embed = perceptor.encode_image(normalize(batch)).float()
if args.image_prompt_weight is not None:
transient_pMs.append(Prompt(embed, args.image_prompt_weight).to(device))
else:
transient_pMs.append(Prompt(embed).to(device))
for prompt in transient_pMs:
result.append(prompt(iii))
for cutoutSize in cutoutsTable:
# clear the transform "cache"
make_cutouts = cutoutsTable[cutoutSize]
make_cutouts.transforms = None
# main init_weight uses spherical loss
if args.target_images is not None:
for z_target in z_targets:
f = z.reshape(1, -1)
f2 = z_target.reshape(1, -1)
cur_loss = spherical_dist_loss(f, f2) * args.target_image_weight
result.append(cur_loss)
if args.image_labels is not None:
for z_label in z_labels:
f = z.reshape(1, -1)
f2 = z_label.reshape(1, -1)
cur_loss = spherical_dist_loss(f, f2) * args.image_label_weight
result.append(cur_loss)
# main init_weight uses spherical loss
if args.init_weight:
f = z.reshape(1, -1)
f2 = z_orig.reshape(1, -1)
cur_loss = spherical_dist_loss(f, f2) * args.init_weight
result.append(cur_loss)
# these three init_weight variants offer mse_loss, mse_loss in pixel space, and cos loss
if args.init_weight_dist:
cur_loss = F.mse_loss(z, z_orig) * args.init_weight_dist / 2
result.append(cur_loss)
if args.init_weight_pix:
if init_image_tensor is None:
print("OOPS IIT is 0")
else:
# TF.to_pil_image(out[0].cpu()).save(f"out_1.png")
# TF.to_pil_image(init_image_tensor[0].cpu()).save(f"init_1.png")
# print(out.shape)
# print(init_image_tensor.shape)
# print(out[0][0])
# print(init_image_tensor[0][0])
cur_loss = F.l1_loss(out, init_image_tensor) * args.init_weight_pix / 2
result.append(cur_loss)
if args.init_weight_cos:
f = z.reshape(1, -1)
f2 = z_orig.reshape(1, -1)
y = torch.ones_like(f[0])
cur_loss = F.cosine_embedding_loss(f, f2, y) * args.init_weight_cos
result.append(cur_loss)
if args.make_video:
img = np.array(
out.mul(255).clamp(0, 255)[0].cpu().detach().numpy().astype(np.uint8)
)[:, :, :]
img = np.transpose(img, (1, 2, 0))
imageio.imwrite(f"./steps/frame_{i:04d}.png", np.array(img))
return result
def re_average_z(args):
global z, gside_X, gside_Y
global model, device
# old_z = z.clone()
cur_z_image = z_to_pil()
cur_z_image = cur_z_image.convert("RGB")
if overlay_image_rgba:
# print("applying overlay image")
cur_z_image.paste(overlay_image_rgba, (0, 0), overlay_image_rgba)
cur_z_image.save("overlaid.png")
cur_z_image = cur_z_image.resize((gside_X, gside_Y), Image.LANCZOS)
new_z, *_ = model.encode(TF.to_tensor(cur_z_image).to(device).unsqueeze(0) * 2 - 1)
# t_dist = F.pairwise_distance(new_z, old_z)
with torch.no_grad():
z.copy_(new_z)
# with torch.no_grad():
# z.copy_(z.maximum(z_min).minimum(z_max))
# torch.autograd.set_detect_anomaly(True)
def train(args, i):
global z, z_min, z_max
opt.zero_grad(set_to_none=True)
lossAll = ascend_txt(args)
if i % args.display_freq == 0:
checkin(args, i, lossAll)
loss = sum(lossAll)
loss.backward()
opt.step()
if (
args.overlay_every
and i != 0
and (i % (args.overlay_every + args.overlay_offset)) == 0
):
re_average_z(args)
with torch.no_grad():
z.copy_(z.maximum(z_min).minimum(z_max))
imagenet_templates = [
"itap of a {}.",
"a bad photo of the {}.",
"a origami {}.",
"a photo of the large {}.",
"a {} in a video game.",
"art of the {}.",
"a photo of the small {}.",
]
def do_run(args):
global i
i = 0
try:
with tqdm() as pbar:
while True:
try:
train(args, i)
if i == args.iterations:
break
i += 1
pbar.update()
except RuntimeError as e:
print("Oops: runtime error: ", e)
print("Try reducing --num-cuts to save memory")
raise e
except KeyboardInterrupt:
pass
if args.make_video:
do_video(settings)
def do_video(args):
global i
# Video generation
init_frame = 1 # This is the frame where the video will start
last_frame = i # You can change i to the number of the last frame you want to generate. It will raise an error if that number of frames does not exist.
min_fps = 10
max_fps = 60
total_frames = last_frame - init_frame
length = 15 # Desired time of the video in seconds
frames = []
tqdm.write("Generating video...")
for i in range(init_frame, last_frame): #
frames.append(Image.open(f"./steps/frame_{i:04d}.png"))
# fps = last_frame/10
fps = np.clip(total_frames / length, min_fps, max_fps)
from subprocess import Popen, PIPE
import re
output_file = re.compile("\.png$").sub(".mp4", args.output)
p = Popen(
[
"ffmpeg",
"-y",
"-f",
"image2pipe",
"-vcodec",
"png",
"-r",
str(fps),
"-i",
"-",
"-vcodec",
"libx264",
"-r",
str(fps),
"-pix_fmt",
"yuv420p",
"-crf",
"17",
"-preset",
"veryslow",
"-metadata",
f"comment={args.prompts}",
output_file,
],
stdin=PIPE,
)
for im in tqdm(frames):
im.save(p.stdin, "PNG")
p.stdin.close()
p.wait()
# this dictionary is used for settings in the notebook
global_clipit_settings = {}
def setup_parser():
# Create the parser
vq_parser = argparse.ArgumentParser(description="Image generation using VQGAN+CLIP")
# Add the arguments
vq_parser.add_argument(
"-p", "--prompts", type=str, help="Text prompts", default=[], dest="prompts"
)
vq_parser.add_argument(
"-sp",
"--spot",
type=str,
help="Spot Text prompts",
default=[],
dest="spot_prompts",
)
vq_parser.add_argument(
"-spo",
"--spot_off",
type=str,
help="Spot off Text prompts",
default=[],
dest="spot_prompts_off",
)
vq_parser.add_argument(
"-l", "--labels", type=str, help="ImageNet labels", default=[], dest="labels"
)
vq_parser.add_argument(
"-ip",
"--image_prompts",
type=str,
help="Image prompts",
default=[],
dest="image_prompts",
)
vq_parser.add_argument(
"-ipw",
"--image_prompt_weight",
type=float,
help="Weight for image prompt",
default=None,
dest="image_prompt_weight",
)
vq_parser.add_argument(
"-ips",
"--image_prompt_shuffle",
type=bool,
help="Shuffle image prompts",
default=False,
dest="image_prompt_shuffle",
)
vq_parser.add_argument(
"-il",
"--image_labels",
type=str,
help="Image prompts",
default=None,
dest="image_labels",
)
vq_parser.add_argument(
"-ilw",
"--image_label_weight",
type=float,
help="Weight for image prompt",
default=1.0,
dest="image_label_weight",
)
vq_parser.add_argument(
"-i",
"--iterations",
type=int,
help="Number of iterations",
default=None,
dest="iterations",
)
vq_parser.add_argument(
"-se",
"--save_every",
type=int,
help="Save image iterations",
default=50,
dest="display_freq",
)
vq_parser.add_argument(
"-ove",
"--overlay_every",
type=int,
help="Overlay image iterations",
default=None,
dest="overlay_every",
)
vq_parser.add_argument(
"-ovo",
"--overlay_offset",
type=int,
help="Overlay image iteration offset",
default=0,
dest="overlay_offset",
)
vq_parser.add_argument(
"-ovi",
"--overlay_image",
type=str,
help="Overlay image (if not init)",
default=None,
dest="overlay_image",
)
vq_parser.add_argument(
"-qua",
"--quality",
type=str,
help="draft, normal, best",
default="normal",
dest="quality",
)
vq_parser.add_argument(
"-asp",
"--aspect",
type=str,
help="widescreen, square",
default="widescreen",
dest="aspect",
)
vq_parser.add_argument(
"-ezs",
"--ezsize",
type=str,
help="small, medium, large",
default=None,
dest="ezsize",
)
vq_parser.add_argument(
"-sca",
"--scale",
type=float,
help="scale (instead of ezsize)",
default=None,
dest="scale",
)
vq_parser.add_argument(
"-ova",
"--overlay_alpha",
type=int,
help="Overlay alpha (0-255)",
default=None,
dest="overlay_alpha",
)
vq_parser.add_argument(
"-s",
"--size",
nargs=2,
type=int,
help="Image size (width height)",
default=None,
dest="size",
)
vq_parser.add_argument(
"-ii",
"--init_image",
type=str,
help="Initial image",
default=None,
dest="init_image",
)
vq_parser.add_argument(
"-iia",
"--init_image_alpha",
type=int,
help="Init image alpha (0-255)",
default=200,
dest="init_image_alpha",
)
vq_parser.add_argument(
"-in",
"--init_noise",
type=str,
help="Initial noise image (pixels or gradient)",
default="pixels",
dest="init_noise",
)
vq_parser.add_argument(
"-ti",
"--target_images",
type=str,
help="Target images",
default=None,
dest="target_images",
)
vq_parser.add_argument(
"-tiw",
"--target_image_weight",
type=float,
help="Target images weight",
default=1.0,
dest="target_image_weight",
)
vq_parser.add_argument(
"-iw",
"--init_weight",
type=float,
help="Initial weight (main=spherical)",
default=None,
dest="init_weight",
)
vq_parser.add_argument(
"-iwd",
"--init_weight_dist",
type=float,
help="Initial weight dist loss",
default=0.0,
dest="init_weight_dist",
)
vq_parser.add_argument(
"-iwc",
"--init_weight_cos",
type=float,
help="Initial weight cos loss",
default=0.0,
dest="init_weight_cos",
)
vq_parser.add_argument(
"-iwp",
"--init_weight_pix",
type=float,
help="Initial weight pix loss",
default=0.0,
dest="init_weight_pix",
)
vq_parser.add_argument(
"-m",
"--clip_models",
type=str,
help="CLIP model",
default=None,
dest="clip_models",
)
vq_parser.add_argument(
"-vqgan",
"--vqgan_model",
type=str,
help="VQGAN model",
default="imagenet_f16_16384",
dest="vqgan_model",
)
vq_parser.add_argument(
"-conf",
"--vqgan_config",
type=str,
help="VQGAN config",
default=None,
dest="vqgan_config",
)
vq_parser.add_argument(
"-ckpt",
"--vqgan_checkpoint",
type=str,
help="VQGAN checkpoint",
default=None,
dest="vqgan_checkpoint",
)
vq_parser.add_argument(
"-nps",
"--noise_prompt_seeds",
nargs="*",
type=int,
help="Noise prompt seeds",
default=[],
dest="noise_prompt_seeds",
)
vq_parser.add_argument(
"-npw",
"--noise_prompt_weights",
nargs="*",
type=float,
help="Noise prompt weights",
default=[],
dest="noise_prompt_weights",
)
vq_parser.add_argument(
"-lr",
"--learning_rate",
type=float,
help="Learning rate",
default=0.2,
dest="step_size",
)
vq_parser.add_argument(
"-cuts",
"--num_cuts",
type=int,
help="Number of cuts",
default=None,
dest="num_cuts",
)
vq_parser.add_argument(
"-cutp",
"--cut_power",
type=float,
help="Cut power",
default=1.0,
dest="cut_pow",
)
vq_parser.add_argument(
"-sd", "--seed", type=int, help="Seed", default=None, dest="seed"
)
vq_parser.add_argument(
"-opt",
"--optimiser",
type=str,
help="Optimiser (Adam, AdamW, Adagrad, Adamax, DiffGrad, AdamP or RAdam)",
default="Adam",
dest="optimiser",
)
vq_parser.add_argument(
"-o",
"--output",
type=str,
help="Output file",
default="output.png",
dest="output",
)
vq_parser.add_argument(
"-vid",
"--video",
type=bool,
help="Create video frames?",
default=False,
dest="make_video",
)
vq_parser.add_argument(
"-d",
"--deterministic",
type=bool,
help="Enable cudnn.deterministic?",
default=False,
dest="cudnn_determinism",
)
return vq_parser
square_size = [144, 144]
widescreen_size = [200, 112] # at the small size this becomes 192,112
def process_args(vq_parser, namespace=None):
global global_aspect_width
if namespace == None:
# command line: use ARGV to get args
args = vq_parser.parse_args()
else:
# notebook, ignore ARGV and use dictionary instead
args = vq_parser.parse_args(args=[], namespace=namespace)
if args.cudnn_determinism:
torch.backends.cudnn.deterministic = True
quality_to_clip_models_table = {
"draft": "ViT-B/32",
"normal": "ViT-B/32,ViT-B/16",
"better": "RN50,ViT-B/32,ViT-B/16",
"best": "RN50x4,ViT-B/32,ViT-B/16",
}
quality_to_iterations_table = {
"draft": 200,
"normal": 350,
"better": 500,
"best": 500,
}
quality_to_scale_table = {"draft": 1, "normal": 2, "better": 3, "best": 4}
# this should be replaced with logic that does somethings
# smart based on available memory (eg: size, num_models, etc)
quality_to_num_cuts_table = {"draft": 40, "normal": 40, "better": 40, "best": 40}
if args.quality not in quality_to_clip_models_table:
print("Qualitfy setting not understood, aborting -> ", argz.quality)
exit(1)
if args.clip_models is None:
args.clip_models = quality_to_clip_models_table[args.quality]
if args.iterations is None:
args.iterations = quality_to_iterations_table[args.quality]
if args.num_cuts is None:
args.num_cuts = quality_to_num_cuts_table[args.quality]
if args.ezsize is None and args.scale is None:
args.scale = quality_to_scale_table[args.quality]
size_to_scale_table = {"small": 1, "medium": 2, "large": 4}
aspect_to_size_table = {"square": [150, 150], "widescreen": [200, 112]}
# determine size if not set
if args.size is None:
size_scale = args.scale
if size_scale is None:
if args.ezsize in size_to_scale_table:
size_scale = size_to_scale_table[args.ezsize]
else:
print("EZ Size not understood, aborting -> ", argz.ezsize)
exit(1)
if args.aspect in aspect_to_size_table:
base_size = aspect_to_size_table[args.aspect]
base_width = int(size_scale * base_size[0])
base_height = int(size_scale * base_size[1])
args.size = [base_width, base_height]
else:
print("aspect not understood, aborting -> ", argz.aspect)
exit(1)
if args.aspect == "widescreen":
global_aspect_width = 16 / 9
if args.init_noise.lower() == "none":
args.init_noise = None
# Split text prompts using the pipe character
if args.prompts:
args.prompts = [phrase.strip() for phrase in args.prompts.split("|")]
# Split text prompts using the pipe character
if args.spot_prompts:
args.spot_prompts = [phrase.strip() for phrase in args.spot_prompts.split("|")]
# Split text prompts using the pipe character
if args.spot_prompts_off:
args.spot_prompts_off = [
phrase.strip() for phrase in args.spot_prompts_off.split("|")
]
# Split text labels using the pipe character
if args.labels:
args.labels = [phrase.strip() for phrase in args.labels.split("|")]
# Split target images using the pipe character
if args.image_prompts:
args.image_prompts = args.image_prompts.split("|")
args.image_prompts = [image.strip() for image in args.image_prompts]
# legacy "spread mode" removed
# if args.init_weight is not None:
# args.init_weight_pix = args.init_weight
# args.init_weight_cos = args.init_weight
# args.init_weight_dist = args.init_weight
if args.overlay_every is not None and args.overlay_every <= 0:
args.overlay_every = None
clip_models = args.clip_models.split(",")
args.clip_models = [model.strip() for model in clip_models]
# Make video steps directory
if args.make_video:
if not os.path.exists("steps"):
os.mkdir("steps")
return args
def reset_settings():
global global_clipit_settings
global_clipit_settings = {}
def add_settings(**kwargs):
global global_clipit_settings
for k, v in kwargs.items():
if v is None:
# just remove the key if it is there
global_clipit_settings.pop(k, None)
else:
global_clipit_settings[k] = v
def apply_settings():
global global_clipit_settings
settingsDict = None
vq_parser = setup_parser()
if len(global_clipit_settings) > 0:
# check for any bogus entries in the settings
dests = [d.dest for d in vq_parser._actions]
for k in global_clipit_settings:
if not k in dests:
raise ValueError(
f"Requested setting not found, aborting: {k}={global_clipit_settings[k]}"
)
# convert dictionary to easyDict
# which can be used as an argparse namespace instead
# settingsDict = easydict.EasyDict(global_clipit_settings)
settingsDict = SimpleNamespace(**global_clipit_settings)
settings = process_args(vq_parser, settingsDict)
return settings
def main():
settings = apply_settings()
do_init(settings)
do_run(settings)
if __name__ == "__main__":
main()
|
the-stack_0_14699 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012, Red Hat, 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.
"""
Unit Tests for nova.cert.rpcapi
"""
from oslo.config import cfg
from nova.cert import rpcapi as cert_rpcapi
from nova import context
from nova.openstack.common import rpc
from nova import test
CONF = cfg.CONF
class CertRpcAPITestCase(test.NoDBTestCase):
def _test_cert_api(self, method, **kwargs):
ctxt = context.RequestContext('fake_user', 'fake_project')
rpcapi = cert_rpcapi.CertAPI()
expected_retval = 'foo'
expected_version = kwargs.pop('version', rpcapi.BASE_RPC_API_VERSION)
expected_msg = rpcapi.make_msg(method, **kwargs)
expected_msg['version'] = expected_version
self.call_ctxt = None
self.call_topic = None
self.call_msg = None
self.call_timeout = None
def _fake_call(_ctxt, _topic, _msg, _timeout):
self.call_ctxt = _ctxt
self.call_topic = _topic
self.call_msg = _msg
self.call_timeout = _timeout
return expected_retval
self.stubs.Set(rpc, 'call', _fake_call)
retval = getattr(rpcapi, method)(ctxt, **kwargs)
self.assertEqual(retval, expected_retval)
self.assertEqual(self.call_ctxt, ctxt)
self.assertEqual(self.call_topic, CONF.cert_topic)
self.assertEqual(self.call_msg, expected_msg)
self.assertIsNone(self.call_timeout)
def test_revoke_certs_by_user(self):
self._test_cert_api('revoke_certs_by_user', user_id='fake_user_id')
# NOTE(russellb) Havana compat
self.flags(cert='havana', group='upgrade_levels')
self._test_cert_api('revoke_certs_by_user', user_id='fake_user_id',
version='1.0')
def test_revoke_certs_by_project(self):
self._test_cert_api('revoke_certs_by_project',
project_id='fake_project_id')
# NOTE(russellb) Havana compat
self.flags(cert='havana', group='upgrade_levels')
self._test_cert_api('revoke_certs_by_project',
project_id='fake_project_id', version='1.0')
def test_revoke_certs_by_user_and_project(self):
self._test_cert_api('revoke_certs_by_user_and_project',
user_id='fake_user_id',
project_id='fake_project_id')
# NOTE(russellb) Havana compat
self.flags(cert='havana', group='upgrade_levels')
self._test_cert_api('revoke_certs_by_user_and_project',
user_id='fake_user_id',
project_id='fake_project_id', version='1.0')
def test_generate_x509_cert(self):
self._test_cert_api('generate_x509_cert',
user_id='fake_user_id',
project_id='fake_project_id')
# NOTE(russellb) Havana compat
self.flags(cert='havana', group='upgrade_levels')
self._test_cert_api('generate_x509_cert',
user_id='fake_user_id',
project_id='fake_project_id', version='1.0')
def test_fetch_ca(self):
self._test_cert_api('fetch_ca', project_id='fake_project_id')
# NOTE(russellb) Havana compat
self.flags(cert='havana', group='upgrade_levels')
self._test_cert_api('fetch_ca', project_id='fake_project_id',
version='1.0')
def test_fetch_crl(self):
self._test_cert_api('fetch_crl', project_id='fake_project_id')
# NOTE(russellb) Havana compat
self.flags(cert='havana', group='upgrade_levels')
self._test_cert_api('fetch_crl', project_id='fake_project_id',
version='1.0')
def test_decrypt_text(self):
self._test_cert_api('decrypt_text',
project_id='fake_project_id', text='blah')
# NOTE(russellb) Havana compat
self.flags(cert='havana', group='upgrade_levels')
self._test_cert_api('decrypt_text',
project_id='fake_project_id', text='blah',
version='1.0')
|
the-stack_0_14702 | # :coding: utf-8
import re
import functools
from .helper import collapse_all
from .helper import get_docstring
#: Regular Expression pattern for data
_DATA_PATTERN = re.compile(
r"(?P<start_regex>(\n|^)) *(?P<export>export +)?(?P<default>default +)?"
r"(?P<type>(const|let|var)) (?P<name>[\w._-]+) *= *(?P<value>.+?;)",
re.DOTALL
)
def fetch_environment(content, module_id):
"""Return data environment dictionary from *content*.
*module_id* represent the identifier of the module.
The environment is in the form of::
{
"moduleName.DATA": {
"id": "moduleName.DATA",
"module_id": "moduleName",
"exported": False,
"default": False,
"name": "DATA",
"value": "42",
"type": "const",
"line_number": 2,
"description": "Variable doc.\\n\\nDetailed description."
}
}
"""
environment = {}
lines = content.split("\n")
# The comment filter is made during the collapse content process to
# preserve the entire value (with semi-colons and docstrings!)
content, collapsed_content = collapse_all(content, filter_comment=True)
for match in _DATA_PATTERN.finditer(content):
data_id = ".".join([module_id, match.group("name")])
line_number = (
content[:match.start()].count("\n") +
match.group("start_regex").count("\n") + 1
)
value = match.group("value")
if "{}" in value and line_number in collapsed_content.keys():
value = value.replace("{}", collapsed_content[line_number])
# Do not keep semi-colon in value
if value.endswith(";"):
value = value[:-1]
data_environment = {
"id": data_id,
"module_id": module_id,
"exported": match.group("export") is not None,
"default": match.group("default") is not None,
"name": match.group("name"),
"value": functools.reduce(_clean_value, value.split('\n')).strip(),
"type": match.group("type"),
"line_number": line_number,
"description": get_docstring(line_number, lines)
}
environment[data_id] = data_environment
return environment
def _clean_value(line1, line2):
"""Clean up variable value for display."""
_line1 = line1.strip()
_line2 = line2.strip()
# Let trailing space to make the code easier to read
if _line1[-1:] in ["{", "}", "(", ")", "[", "]", ";", ","]:
_line1 += " "
return _line1 + _line2
|
the-stack_0_14704 | #! /usr/bin/env python
################################################################################
#
# DemoFusion.py
#
"""Fusion Demo
The Fusion Demo demonstrates a command-line interface to the Fusion Reactor
application.
Author: Robin D. Knight
Email: [email protected]
URL: http://www.roadnarrowsrobotics.com
Date: 2005.01.05
Copyright (C) 2006. RoadNarrows LLC.
"""
#
# All Rights Reserved
#
# Permission is hereby granted, without written agreement and without
# license or royalty fees, to use, copy, modify, and distribute this
# software and its documentation for any purpose, provided that
# (1) The above copyright notice and the following two paragraphs
# appear in all copies of the source code and (2) redistributions
# including binaries reproduces these notices in the supporting
# documentation. Substantial modifications to this software may be
# copyrighted by their authors and need not follow the licensing terms
# described here, provided that the new terms are clearly indicated in
# all files where they apply.
#
# IN NO EVENT SHALL THE AUTHOR, ROADNARROWS LLC, OR ANY MEMBERS/EMPLOYEES
# OF ROADNARROW LLC OR DISTRIBUTORS OF THIS SOFTWARE BE LIABLE TO ANY
# PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
# DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION,
# EVEN IF THE AUTHORS OR ANY OF THE ABOVE PARTIES HAVE BEEN ADVISED OF
# THE POSSIBILITY OF SUCH DAMAGE.
#
# THE AUTHOR AND ROADNARROWS LLC SPECIFICALLY DISCLAIM ANY WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
# FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN
# "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO
# PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
#
################################################################################
import sys
import getopt
import Fusion.Core.Reactor as Reactor
_Argv0 = ''
#--
class Usage(Exception):
""" Command-Line Options Usage Exception Class. """
def __init__(self, msg):
self.msg = msg
#--
def PrintUsageErr(emsg):
""" Print Error Usage Message. """
if emsg:
print("%s: %s" % (_Argv0, emsg))
else:
print("%s: error" % (_Argv0))
print("Try '%s --help' for more information." % (_Argv0))
#--
def PrintUsage():
""" Print Fusion Command-Line Usage Message """
print("usage: %s [options]..." % (_Argv0))
print("""Options and arguments:
-i, --ini <filename> : additional ini configuration file. Default: None
--debuglevel <num> : debug level 0=off, 1 - 5. Default: 0
--debugfile <filename> : debug output filename. Default: stdout
-h, --help : Display this help and exit.
Environment variables:
FUSION : points to the Fusion package base directory
FUSIONSTARTUP : a site/user standard ini configuration file
""")
#--
def main(argv=None, **kwargs):
""" Fusion Main. """
global _Argv0
print('main')
if argv is None:
argv = sys.argv
print('args', repr(argv))
_Argv0 = argv[0]
#if 'argv0' in kwargs:
# _Argv0 = kwargs['argv0']
#else:
# _Argv0 = __file__
# Reactor defaults
kwargs = {'vRobot': None, 'vBrain': None, 'iniFileName': None,
'debuglevel': 0, 'debugfout': None}
try:
try:
opts, args = getopt.getopt(argv[1:], "?hi:",
['help', 'ini=', 'debuglevel=', 'debugfile='])
except getopt.error as msg:
raise Usage(msg)
for opt, optarg in opts:
if opt in ('-h', '--help', '-?'):
PrintUsage()
return 0
elif opt in ('-i', '--ini'):
kwargs['iniFileName'] = optarg
elif opt in ('--debuglevel'):
try:
kwargs['debuglevel'] = int(optarg)
except ValueError as msg:
raise Usage(msg)
elif opt in ('--debugfile'):
try:
fout = open(optarg, 'w')
except IOError as msg:
raise Usage(msg)
kwargs['debugfout'] = fout
except Usage as err:
PrintUsageErr(err.msg)
return 2
reactor = Reactor.Reactor(**kwargs)
reactor.mGuiRoot.mainloop()
return 0
# run fusion
if __name__ == "__main__":
sys.exit( main(argv=None) )
|
the-stack_0_14705 | result = 0
instructions = []
registers = {
"a": 0,
"b": 0
}
with open("input.txt", "r") as input:
for line in input:
line = line.strip().replace(",","").split()
opcode = line[0]
if opcode == "jmp":
offset = int(line[1])
reg = None
else:
offset = None
reg = line[1]
if opcode in ["jie", "jio"]:
offset = int(line[2])
instructions.append({
"opcode": opcode,
"reg": reg,
"offset": offset
})
i = 0
while 0 <= i < len(instructions):
instruction = instructions[i]
opcode = instruction["opcode"]
reg = instruction["reg"]
offset = instruction["offset"]
if opcode == "jmp":
i += offset
elif opcode == "jie":
if registers[reg] % 2 == 0:
i += offset
else:
i += 1
elif opcode == "jio":
if registers[reg] == 1:
i += offset
else:
i += 1
else:
i += 1
if opcode == "inc":
registers[reg] += 1
elif opcode == "hlf":
registers[reg] //= 2
elif opcode == "tpl":
registers[reg] *= 3
else:
print("ERROR")
result = registers["b"]
with open("output1.txt", "w") as output:
output.write(str(result))
print(str(result))
|
the-stack_0_14709 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
from time import localtime, strftime
import argparse
from argparse import RawTextHelpFormatter
from gdcmdtools.rm import GDRm
from gdcmdtools.base import BASE_INFO
from gdcmdtools.base import DEBUG_LEVEL
from gdcmdtools.perm import help_permission_text
import csv
import pprint
__THIS_APP = 'gdrm'
__THIS_DESCRIPTION = 'Tool to remove file or folder on Google Drive'
__THIS_VERSION = BASE_INFO["version"]
import logging
logger = logging.getLogger(__THIS_APP)
def test():
assert True
if __name__ == '__main__':
arg_parser = argparse.ArgumentParser(
description='%s v%s - %s - %s (%s)' %
(__THIS_APP,
__THIS_VERSION,
__THIS_DESCRIPTION,
BASE_INFO["app"],
BASE_INFO["description"]),
formatter_class=RawTextHelpFormatter)
arg_parser.add_argument(
'-d',
'--delete',
action='store_true',
help='Permanently deletes the file instead of trashing it')
arg_parser.add_argument(
'file_id',
help='The file id or drive link for the file you\'re going to remove')
arg_parser.add_argument('--debug',
choices=DEBUG_LEVEL,
default=DEBUG_LEVEL[-1],
help='define the debug level')
args = arg_parser.parse_args()
# set debug devel
logger.setLevel(getattr(logging, args.debug.upper()))
logger.debug(args)
rm = GDRm(args)
try:
response = rm.run()
except:
raise
logger.debug(pprint.pformat(response))
sys.exit(0)
|
the-stack_0_14710 | # BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE
from __future__ import absolute_import
import numba
import numba.core.typing
import numba.core.typing.ctypes_utils
import awkward as ak
numpy = ak.nplike.Numpy.instance()
dynamic_addrs = {}
def globalstring(context, builder, pyvalue):
import llvmlite.ir.types
if pyvalue not in dynamic_addrs:
buf = dynamic_addrs[pyvalue] = numpy.array(pyvalue.encode("utf-8") + b"\x00")
context.add_dynamic_addr(
builder, buf.ctypes.data, info="str({0})".format(repr(pyvalue))
)
ptr = context.get_constant(numba.types.uintp, dynamic_addrs[pyvalue].ctypes.data)
return builder.inttoptr(
ptr, llvmlite.llvmpy.core.Type.pointer(llvmlite.llvmpy.core.Type.int(8))
)
class ArrayBuilderType(numba.types.Type):
def __init__(self, behavior):
super(ArrayBuilderType, self).__init__(
name="ak.ArrayBuilderType({0})".format(
ak._connect._numba.repr_behavior(behavior)
)
)
self.behavior = behavior
@numba.extending.register_model(ArrayBuilderType)
class ArrayBuilderModel(numba.core.datamodel.models.StructModel):
def __init__(self, dmm, fe_type):
members = [("rawptr", numba.types.voidptr), ("pyptr", numba.types.pyobject)]
super(ArrayBuilderModel, self).__init__(dmm, fe_type, members)
@numba.core.imputils.lower_constant(ArrayBuilderType)
def lower_const_ArrayBuilder(context, builder, arraybuildertype, arraybuilder):
layout = arraybuilder._layout
rawptr = context.get_constant(numba.intp, arraybuilder._layout._ptr)
proxyout = context.make_helper(builder, arraybuildertype)
proxyout.rawptr = builder.inttoptr(
rawptr, context.get_value_type(numba.types.voidptr)
)
proxyout.pyptr = context.add_dynamic_addr(
builder, id(layout), info=str(type(layout))
)
return proxyout._getvalue()
@numba.extending.unbox(ArrayBuilderType)
def unbox_ArrayBuilder(arraybuildertype, arraybuilderobj, c):
inner_obj = c.pyapi.object_getattr_string(arraybuilderobj, "_layout")
rawptr_obj = c.pyapi.object_getattr_string(inner_obj, "_ptr")
proxyout = c.context.make_helper(c.builder, arraybuildertype)
proxyout.rawptr = c.pyapi.long_as_voidptr(rawptr_obj)
proxyout.pyptr = inner_obj
c.pyapi.decref(inner_obj)
c.pyapi.decref(rawptr_obj)
is_error = numba.core.cgutils.is_not_null(c.builder, c.pyapi.err_occurred())
return numba.extending.NativeValue(proxyout._getvalue(), is_error)
@numba.extending.box(ArrayBuilderType)
def box_ArrayBuilder(arraybuildertype, arraybuilderval, c):
ArrayBuilder_obj = c.pyapi.unserialize(
c.pyapi.serialize_object(ak.highlevel.ArrayBuilder)
)
behavior_obj = c.pyapi.unserialize(
c.pyapi.serialize_object(arraybuildertype.behavior)
)
proxyin = c.context.make_helper(c.builder, arraybuildertype, arraybuilderval)
c.pyapi.incref(proxyin.pyptr)
out = c.pyapi.call_method(ArrayBuilder_obj, "_wrap", (proxyin.pyptr, behavior_obj))
c.pyapi.decref(ArrayBuilder_obj)
c.pyapi.decref(behavior_obj)
c.pyapi.decref(proxyin.pyptr)
return out
def call(context, builder, fcn, args):
numbatype = numba.core.typing.ctypes_utils.make_function_type(fcn)
fcntype = context.get_function_pointer_type(numbatype)
fcnval = context.add_dynamic_addr(
builder, numbatype.get_pointer(fcn), info=fcn.name
)
fcnptr = builder.bitcast(fcnval, fcntype)
err = context.call_function_pointer(builder, fcnptr, args)
with builder.if_then(
builder.icmp_unsigned("!=", err, context.get_constant(numba.uint8, 0)),
likely=False,
):
context.call_conv.return_user_exc(builder, ValueError, (fcn.name + " failed",))
@numba.core.typing.templates.infer_global(len)
class type_len(numba.core.typing.templates.AbstractTemplate):
def generic(self, args, kwargs):
if (
len(args) == 1
and len(kwargs) == 0
and isinstance(args[0], ArrayBuilderType)
):
return numba.intp(args[0])
@numba.extending.lower_builtin(len, ArrayBuilderType)
def lower_len(context, builder, sig, args):
(arraybuildertype,) = sig.args
(arraybuilderval,) = args
proxyin = context.make_helper(builder, arraybuildertype, arraybuilderval)
result = numba.core.cgutils.alloca_once(
builder, context.get_value_type(numba.int64)
)
call(
context, builder, ak._libawkward.ArrayBuilder_length, (proxyin.rawptr, result),
)
return ak._connect._numba.castint(
context, builder, numba.int64, numba.intp, builder.load(result)
)
@numba.core.typing.templates.infer_getattr
class type_methods(numba.core.typing.templates.AttributeTemplate):
key = ArrayBuilderType
@numba.core.typing.templates.bound_function("clear")
def resolve_clear(self, arraybuildertype, args, kwargs):
if len(args) == 0 and len(kwargs) == 0:
return numba.types.none()
else:
raise TypeError(
"wrong number of arguments for ArrayBuilder.clear"
+ ak._util.exception_suffix(__file__)
)
@numba.core.typing.templates.bound_function("null")
def resolve_null(self, arraybuildertype, args, kwargs):
if len(args) == 0 and len(kwargs) == 0:
return numba.types.none()
else:
raise TypeError(
"wrong number of arguments for ArrayBuilder.null"
+ ak._util.exception_suffix(__file__)
)
@numba.core.typing.templates.bound_function("boolean")
def resolve_boolean(self, arraybuildertype, args, kwargs):
if (
len(args) == 1
and len(kwargs) == 0
and isinstance(args[0], numba.types.Boolean)
):
return numba.types.none(args[0])
else:
raise TypeError(
"wrong number or types of arguments for ArrayBuilder.boolean"
+ ak._util.exception_suffix(__file__)
)
@numba.core.typing.templates.bound_function("integer")
def resolve_integer(self, arraybuildertype, args, kwargs):
if (
len(args) == 1
and len(kwargs) == 0
and isinstance(args[0], numba.types.Integer)
):
return numba.types.none(args[0])
else:
raise TypeError(
"wrong number or types of arguments for ArrayBuilder.integer"
+ ak._util.exception_suffix(__file__)
)
@numba.core.typing.templates.bound_function("real")
def resolve_real(self, arraybuildertype, args, kwargs):
if (
len(args) == 1
and len(kwargs) == 0
and isinstance(args[0], (numba.types.Integer, numba.types.Float))
):
return numba.types.none(args[0])
else:
raise TypeError(
"wrong number or types of arguments for ArrayBuilder.real"
+ ak._util.exception_suffix(__file__)
)
@numba.core.typing.templates.bound_function("begin_list")
def resolve_begin_list(self, arraybuildertype, args, kwargs):
if len(args) == 0 and len(kwargs) == 0:
return numba.types.none()
else:
raise TypeError(
"wrong number of arguments for ArrayBuilder.begin_list"
+ ak._util.exception_suffix(__file__)
)
@numba.core.typing.templates.bound_function("end_list")
def resolve_end_list(self, arraybuildertype, args, kwargs):
if len(args) == 0 and len(kwargs) == 0:
return numba.types.none()
else:
raise TypeError(
"wrong number of arguments for ArrayBuilder.end_list"
+ ak._util.exception_suffix(__file__)
)
@numba.core.typing.templates.bound_function("begin_tuple")
def resolve_begin_tuple(self, arraybuildertype, args, kwargs):
if (
len(args) == 1
and len(kwargs) == 0
and isinstance(args[0], numba.types.Integer)
):
return numba.types.none(args[0])
else:
raise TypeError(
"wrong number or types of arguments for ArrayBuilder.begin_tuple"
+ ak._util.exception_suffix(__file__)
)
@numba.core.typing.templates.bound_function("index")
def resolve_index(self, arraybuildertype, args, kwargs):
if (
len(args) == 1
and len(kwargs) == 0
and isinstance(args[0], numba.types.Integer)
):
return arraybuildertype(args[0])
else:
raise TypeError(
"wrong number or types of arguments for ArrayBuilder.index"
+ ak._util.exception_suffix(__file__)
)
@numba.core.typing.templates.bound_function("end_tuple")
def resolve_end_tuple(self, arraybuildertype, args, kwargs):
if len(args) == 0 and len(kwargs) == 0:
return numba.types.none()
else:
raise TypeError(
"wrong number of arguments for ArrayBuilder.end_tuple"
+ ak._util.exception_suffix(__file__)
)
@numba.core.typing.templates.bound_function("begin_record")
def resolve_begin_record(self, arraybuildertype, args, kwargs):
if len(args) == 0 and len(kwargs) == 0:
return numba.types.none()
elif (
len(args) == 1
and len(kwargs) == 0
and isinstance(args[0], numba.types.StringLiteral)
):
return numba.types.none(args[0])
else:
raise TypeError(
"wrong number or types of arguments for ArrayBuilder.begin_record"
+ ak._util.exception_suffix(__file__)
)
@numba.core.typing.templates.bound_function("field")
def resolve_field(self, arraybuildertype, args, kwargs):
if (
len(args) == 1
and len(kwargs) == 0
and isinstance(args[0], numba.types.StringLiteral)
):
return arraybuildertype(args[0])
else:
raise TypeError(
"wrong number or types of arguments for ArrayBuilder.field"
+ ak._util.exception_suffix(__file__)
)
@numba.core.typing.templates.bound_function("end_record")
def resolve_end_record(self, arraybuildertype, args, kwargs):
if len(args) == 0 and len(kwargs) == 0:
return numba.types.none()
else:
raise TypeError(
"wrong number of arguments for ArrayBuilder.end_record"
+ ak._util.exception_suffix(__file__)
)
@numba.core.typing.templates.bound_function("append")
def resolve_append(self, arraybuildertype, args, kwargs):
if (
len(args) == 1
and len(kwargs) == 0
and isinstance(
args[0],
(
ak._connect._numba.arrayview.ArrayViewType,
ak._connect._numba.arrayview.RecordViewType,
numba.types.Boolean,
numba.types.Integer,
numba.types.Float,
),
)
):
return numba.types.none(args[0])
elif (
len(args) == 1
and len(kwargs) == 0
and isinstance(args[0], numba.types.Optional)
and isinstance(
args[0].type,
(numba.types.Boolean, numba.types.Integer, numba.types.Float),
)
):
return numba.types.none(args[0])
elif (
len(args) == 1
and len(kwargs) == 0
and isinstance(args[0], numba.types.NoneType)
):
return numba.types.none(args[0])
elif (
len(args) == 2
and len(kwargs) == 0
and isinstance(args[0], ak._connect._numba.arrayview.ArrayViewType)
and isinstance(args[1], numba.types.Integer)
):
return numba.types.none(args[0], args[1])
else:
if len(args) == 1 and arraybuildertype.behavior is not None:
for key, lower in arraybuildertype.behavior.items():
if (
isinstance(key, tuple)
and len(key) == 3
and key[0] == "__numba_lower__"
and key[1] == ak.highlevel.ArrayBuilder.append
and (
args[0] == key[2]
or (
isinstance(key[2], type) and isinstance(args[0], key[2])
)
)
):
numba.extending.lower_builtin(
"append", ArrayBuilderType, args[0]
)(lower)
return numba.types.none(args[0])
raise TypeError(
"wrong number or types of arguments for ArrayBuilder.append"
+ ak._util.exception_suffix(__file__)
)
@numba.core.typing.templates.bound_function("extend")
def resolve_extend(self, arraybuildertype, args, kwargs):
if (
len(args) == 1
and len(kwargs) == 0
and isinstance(args[0], ak._connect._numba.arrayview.ArrayViewType)
):
return numba.types.none(args[0])
else:
raise TypeError(
"wrong number or types of arguments for ArrayBuilder.extend"
+ ak._util.exception_suffix(__file__)
)
@numba.extending.lower_builtin("clear", ArrayBuilderType)
def lower_clear(context, builder, sig, args):
(arraybuildertype,) = sig.args
(arraybuilderval,) = args
proxyin = context.make_helper(builder, arraybuildertype, arraybuilderval)
call(context, builder, ak._libawkward.ArrayBuilder_clear, (proxyin.rawptr,))
return context.get_dummy_value()
@numba.extending.lower_builtin("null", ArrayBuilderType)
def lower_null(context, builder, sig, args):
(arraybuildertype,) = sig.args
(arraybuilderval,) = args
proxyin = context.make_helper(builder, arraybuildertype, arraybuilderval)
call(context, builder, ak._libawkward.ArrayBuilder_null, (proxyin.rawptr,))
return context.get_dummy_value()
@numba.extending.lower_builtin("boolean", ArrayBuilderType, numba.types.Boolean)
def lower_boolean(context, builder, sig, args):
arraybuildertype, xtype = sig.args
arraybuilderval, xval = args
proxyin = context.make_helper(builder, arraybuildertype, arraybuilderval)
x = builder.zext(xval, context.get_value_type(numba.uint8))
call(context, builder, ak._libawkward.ArrayBuilder_boolean, (proxyin.rawptr, x))
return context.get_dummy_value()
@numba.extending.lower_builtin("integer", ArrayBuilderType, numba.types.Integer)
def lower_integer(context, builder, sig, args):
arraybuildertype, xtype = sig.args
arraybuilderval, xval = args
proxyin = context.make_helper(builder, arraybuildertype, arraybuilderval)
x = ak._connect._numba.castint(context, builder, xtype, numba.int64, xval)
call(context, builder, ak._libawkward.ArrayBuilder_integer, (proxyin.rawptr, x))
return context.get_dummy_value()
@numba.extending.lower_builtin("real", ArrayBuilderType, numba.types.Integer)
@numba.extending.lower_builtin("real", ArrayBuilderType, numba.types.Float)
def lower_real(context, builder, sig, args):
arraybuildertype, xtype = sig.args
arraybuilderval, xval = args
proxyin = context.make_helper(builder, arraybuildertype, arraybuilderval)
if isinstance(xtype, numba.types.Integer) and xtype.signed:
x = builder.sitofp(xval, context.get_value_type(numba.types.float64))
elif isinstance(xtype, numba.types.Integer):
x = builder.uitofp(xval, context.get_value_type(numba.types.float64))
elif xtype.bitwidth < 64:
x = builder.fpext(xval, context.get_value_type(numba.types.float64))
elif xtype.bitwidth > 64:
x = builder.fptrunc(xval, context.get_value_type(numba.types.float64))
else:
x = xval
call(context, builder, ak._libawkward.ArrayBuilder_real, (proxyin.rawptr, x))
return context.get_dummy_value()
@numba.extending.lower_builtin("begin_list", ArrayBuilderType)
def lower_beginlist(context, builder, sig, args):
(arraybuildertype,) = sig.args
(arraybuilderval,) = args
proxyin = context.make_helper(builder, arraybuildertype, arraybuilderval)
call(context, builder, ak._libawkward.ArrayBuilder_beginlist, (proxyin.rawptr,))
return context.get_dummy_value()
@numba.extending.lower_builtin("end_list", ArrayBuilderType)
def lower_endlist(context, builder, sig, args):
(arraybuildertype,) = sig.args
(arraybuilderval,) = args
proxyin = context.make_helper(builder, arraybuildertype, arraybuilderval)
call(context, builder, ak._libawkward.ArrayBuilder_endlist, (proxyin.rawptr,))
return context.get_dummy_value()
@numba.extending.lower_builtin("begin_tuple", ArrayBuilderType, numba.types.Integer)
def lower_begintuple(context, builder, sig, args):
arraybuildertype, numfieldstype = sig.args
arraybuilderval, numfieldsval = args
proxyin = context.make_helper(builder, arraybuildertype, arraybuilderval)
numfields = ak._connect._numba.castint(
context, builder, numfieldstype, numba.int64, numfieldsval
)
call(
context,
builder,
ak._libawkward.ArrayBuilder_begintuple,
(proxyin.rawptr, numfields),
)
return context.get_dummy_value()
@numba.extending.lower_builtin("index", ArrayBuilderType, numba.types.Integer)
def lower_index(context, builder, sig, args):
arraybuildertype, indextype = sig.args
arraybuilderval, indexval = args
proxyin = context.make_helper(builder, arraybuildertype, arraybuilderval)
index = ak._connect._numba.castint(
context, builder, indextype, numba.int64, indexval
)
call(
context, builder, ak._libawkward.ArrayBuilder_index, (proxyin.rawptr, index),
)
return arraybuilderval
@numba.extending.lower_builtin("end_tuple", ArrayBuilderType)
def lower_endtuple(context, builder, sig, args):
(arraybuildertype,) = sig.args
(arraybuilderval,) = args
proxyin = context.make_helper(builder, arraybuildertype, arraybuilderval)
call(context, builder, ak._libawkward.ArrayBuilder_endtuple, (proxyin.rawptr,))
return context.get_dummy_value()
@numba.extending.lower_builtin("begin_record", ArrayBuilderType)
def lower_beginrecord(context, builder, sig, args):
(arraybuildertype,) = sig.args
(arraybuilderval,) = args
proxyin = context.make_helper(builder, arraybuildertype, arraybuilderval)
call(
context, builder, ak._libawkward.ArrayBuilder_beginrecord, (proxyin.rawptr,),
)
return context.get_dummy_value()
@numba.extending.lower_builtin(
"begin_record", ArrayBuilderType, numba.types.StringLiteral
)
def lower_beginrecord_field(context, builder, sig, args):
arraybuildertype, nametype = sig.args
arraybuilderval, nameval = args
proxyin = context.make_helper(builder, arraybuildertype, arraybuilderval)
name = globalstring(context, builder, nametype.literal_value)
call(
context,
builder,
ak._libawkward.ArrayBuilder_beginrecord_fast,
(proxyin.rawptr, name),
)
return context.get_dummy_value()
@numba.extending.lower_builtin("field", ArrayBuilderType, numba.types.StringLiteral)
def lower_field(context, builder, sig, args):
arraybuildertype, keytype = sig.args
arraybuilderval, keyval = args
proxyin = context.make_helper(builder, arraybuildertype, arraybuilderval)
key = globalstring(context, builder, keytype.literal_value)
call(
context, builder, ak._libawkward.ArrayBuilder_field_fast, (proxyin.rawptr, key),
)
return arraybuilderval
@numba.extending.lower_builtin("end_record", ArrayBuilderType)
def lower_endrecord(context, builder, sig, args):
(arraybuildertype,) = sig.args
(arraybuilderval,) = args
proxyin = context.make_helper(builder, arraybuildertype, arraybuilderval)
call(context, builder, ak._libawkward.ArrayBuilder_endrecord, (proxyin.rawptr,))
return context.get_dummy_value()
@numba.extending.lower_builtin(
"append",
ArrayBuilderType,
ak._connect._numba.arrayview.ArrayViewType,
numba.types.Integer,
)
def lower_append_array_at(context, builder, sig, args):
arraybuildertype, viewtype, attype = sig.args
arraybuilderval, viewval, atval = args
viewproxy = context.make_helper(builder, viewtype, viewval)
atval = ak._connect._numba.layout.regularize_atval(
context, builder, viewproxy, attype, atval, True, True
)
atval = ak._connect._numba.castint(context, builder, numba.intp, numba.int64, atval)
sharedptr = ak._connect._numba.layout.getat(
context, builder, viewproxy.sharedptrs, viewproxy.pos
)
proxyin = context.make_helper(builder, arraybuildertype, arraybuilderval)
call(
context,
builder,
ak._libawkward.ArrayBuilder_append_nowrap,
(
proxyin.rawptr,
builder.inttoptr(sharedptr, context.get_value_type(numba.types.voidptr)),
atval,
),
)
return context.get_dummy_value()
@numba.extending.lower_builtin(
"append", ArrayBuilderType, ak._connect._numba.arrayview.ArrayViewType
)
def lower_append_array(context, builder, sig, args):
arraybuildertype, viewtype = sig.args
arraybuilderval, viewval = args
proxyin = context.make_helper(builder, arraybuildertype, arraybuilderval)
call(context, builder, ak._libawkward.ArrayBuilder_beginlist, (proxyin.rawptr,))
lower_extend_array(context, builder, sig, args)
call(context, builder, ak._libawkward.ArrayBuilder_endlist, (proxyin.rawptr,))
return context.get_dummy_value()
@numba.extending.lower_builtin(
"append", ArrayBuilderType, ak._connect._numba.arrayview.RecordViewType
)
def lower_append_record(context, builder, sig, args):
arraybuildertype, recordviewtype = sig.args
arraybuilderval, recordviewval = args
recordviewproxy = context.make_helper(builder, recordviewtype, recordviewval)
arrayviewproxy = context.make_helper(
builder, recordviewtype.arrayviewtype, recordviewproxy.arrayview
)
atval = ak._connect._numba.castint(
context, builder, numba.intp, numba.int64, recordviewproxy.at
)
sharedptr = ak._connect._numba.layout.getat(
context, builder, arrayviewproxy.sharedptrs, arrayviewproxy.pos
)
proxyin = context.make_helper(builder, arraybuildertype, arraybuilderval)
call(
context,
builder,
ak._libawkward.ArrayBuilder_append_nowrap,
(
proxyin.rawptr,
builder.inttoptr(sharedptr, context.get_value_type(numba.types.voidptr)),
atval,
),
)
return context.get_dummy_value()
@numba.extending.lower_builtin("append", ArrayBuilderType, numba.types.Boolean)
def lower_append_bool(context, builder, sig, args):
return lower_boolean(context, builder, sig, args)
@numba.extending.lower_builtin("append", ArrayBuilderType, numba.types.Integer)
def lower_append_int(context, builder, sig, args):
return lower_integer(context, builder, sig, args)
@numba.extending.lower_builtin("append", ArrayBuilderType, numba.types.Float)
def lower_append_float(context, builder, sig, args):
return lower_real(context, builder, sig, args)
@numba.extending.lower_builtin("append", ArrayBuilderType, numba.types.Optional)
def lower_append_optional(context, builder, sig, args):
arraybuildertype, opttype = sig.args
arraybuilderval, optval = args
optproxy = context.make_helper(builder, opttype, optval)
validbit = numba.core.cgutils.as_bool_bit(builder, optproxy.valid)
with builder.if_else(validbit) as (is_valid, is_not_valid):
with is_valid:
if isinstance(opttype.type, numba.types.Boolean):
lower_boolean(
context,
builder,
numba.types.none(arraybuildertype, opttype.type),
(arraybuilderval, optproxy.data),
)
elif isinstance(opttype.type, numba.types.Integer):
lower_integer(
context,
builder,
numba.types.none(arraybuildertype, opttype.type),
(arraybuilderval, optproxy.data),
)
elif isinstance(opttype.type, numba.types.Float):
lower_real(
context,
builder,
numba.types.none(arraybuildertype, opttype.type),
(arraybuilderval, optproxy.data),
)
else:
raise AssertionError(
repr(opttype.type) + ak._util.exception_suffix(__file__)
)
with is_not_valid:
lower_null(
context,
builder,
numba.types.none(arraybuildertype,),
(arraybuilderval,),
)
return context.get_dummy_value()
@numba.extending.lower_builtin("append", ArrayBuilderType, numba.types.NoneType)
def lower_append_none(context, builder, sig, args):
return lower_null(context, builder, sig.return_type(sig.args[0]), (args[0],))
@numba.extending.lower_builtin(
"extend", ArrayBuilderType, ak._connect._numba.arrayview.ArrayViewType
)
def lower_extend_array(context, builder, sig, args):
arraybuildertype, viewtype = sig.args
arraybuilderval, viewval = args
viewproxy = context.make_helper(builder, viewtype, viewval)
sharedptr = ak._connect._numba.layout.getat(
context, builder, viewproxy.sharedptrs, viewproxy.pos
)
proxyin = context.make_helper(builder, arraybuildertype, arraybuilderval)
with numba.core.cgutils.for_range(builder, viewproxy.stop, viewproxy.start) as loop:
atval = ak._connect._numba.castint(
context, builder, numba.intp, numba.int64, loop.index
)
call(
context,
builder,
ak._libawkward.ArrayBuilder_append_nowrap,
(
proxyin.rawptr,
builder.inttoptr(
sharedptr, context.get_value_type(numba.types.voidptr)
),
atval,
),
)
return context.get_dummy_value()
|
the-stack_0_14711 | #!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'community'}
DOCUMENTATION = '''
module: route53_zone
short_description: add or delete Route53 zones
description:
- Creates and deletes Route53 private and public zones
version_added: "2.0"
requirements: [ boto3 ]
options:
zone:
description:
- "The DNS zone record (eg: foo.com.)"
required: true
state:
description:
- whether or not the zone should exist or not
default: present
choices: [ "present", "absent" ]
vpc_id:
description:
- The VPC ID the zone should be a part of (if this is going to be a private zone)
vpc_region:
description:
- The VPC Region the zone should be a part of (if this is going to be a private zone)
comment:
description:
- Comment associated with the zone
default: ''
hosted_zone_id:
description:
- The unique zone identifier you want to delete or "all" if there are many zones with the same domain name.
Required if there are multiple zones identified with the above options
version_added: 2.4
delegation_set_id:
description:
- The reusable delegation set ID to be associated with the zone.
Note that you can't associate a reusable delegation set with a private hosted zone.
version_added: 2.6
extends_documentation_fragment:
- aws
- ec2
author: "Christopher Troup (@minichate)"
'''
EXAMPLES = '''
- name: create a public zone
route53_zone:
zone: example.com
comment: this is an example
- name: delete a public zone
route53_zone:
zone: example.com
state: absent
- name: create a private zone
route53_zone:
zone: devel.example.com
vpc_id: '{{ myvpc_id }}'
vpc_region: us-west-2
comment: developer domain
- name: create a public zone associated with a specific reusable delegation set
route53_zone:
zone: example.com
comment: reusable delegation set example
delegation_set_id: A1BCDEF2GHIJKL
'''
RETURN = '''
comment:
description: optional hosted zone comment
returned: when hosted zone exists
type: str
sample: "Private zone"
name:
description: hosted zone name
returned: when hosted zone exists
type: str
sample: "private.local."
private_zone:
description: whether hosted zone is private or public
returned: when hosted zone exists
type: bool
sample: true
vpc_id:
description: id of vpc attached to private hosted zone
returned: for private hosted zone
type: str
sample: "vpc-1d36c84f"
vpc_region:
description: region of vpc attached to private hosted zone
returned: for private hosted zone
type: str
sample: "eu-west-1"
zone_id:
description: hosted zone id
returned: when hosted zone exists
type: str
sample: "Z6JQG9820BEFMW"
delegation_set_id:
description: id of the associated reusable delegation set
returned: for public hosted zones, if they have been associated with a reusable delegation set
type: str
sample: "A1BCDEF2GHIJKL"
'''
import time
from ansible.module_utils.aws.core import AnsibleAWSModule
from ansible.module_utils.ec2 import boto3_conn, ec2_argument_spec, get_aws_connection_info
try:
from botocore.exceptions import BotoCoreError, ClientError
except ImportError:
pass # handled by AnsibleAWSModule
def find_zones(module, client, zone_in, private_zone):
try:
paginator = client.get_paginator('list_hosted_zones')
results = paginator.paginate().build_full_result()
except (BotoCoreError, ClientError) as e:
module.fail_json_aws(e, msg="Could not list current hosted zones")
zones = []
for r53zone in results['HostedZones']:
if r53zone['Name'] != zone_in:
continue
# only save zone names that match the public/private setting
if (r53zone['Config']['PrivateZone'] and private_zone) or \
(not r53zone['Config']['PrivateZone'] and not private_zone):
zones.append(r53zone)
return zones
def create(module, client, matching_zones):
zone_in = module.params.get('zone').lower()
vpc_id = module.params.get('vpc_id')
vpc_region = module.params.get('vpc_region')
comment = module.params.get('comment')
delegation_set_id = module.params.get('delegation_set_id')
if not zone_in.endswith('.'):
zone_in += "."
private_zone = bool(vpc_id and vpc_region)
record = {
'private_zone': private_zone,
'vpc_id': vpc_id,
'vpc_region': vpc_region,
'comment': comment,
'name': zone_in,
'delegation_set_id': delegation_set_id,
}
if private_zone:
changed, result = create_or_update_private(module, client, matching_zones, record)
else:
changed, result = create_or_update_public(module, client, matching_zones, record)
return changed, result
def create_or_update_private(module, client, matching_zones, record):
for z in matching_zones:
try:
result = client.get_hosted_zone(Id=z['Id']) # could be in different regions or have different VPCids
except (BotoCoreError, ClientError) as e:
module.fail_json_aws(e, msg="Could not get details about hosted zone %s" % z['Id'])
zone_details = result['HostedZone']
vpc_details = result['VPCs']
current_vpc_id = None
current_vpc_region = None
if isinstance(vpc_details, dict):
if vpc_details['VPC']['VPCId'] == record['vpc_id']:
current_vpc_id = vpc_details['VPC']['VPCId']
current_vpc_region = vpc_details['VPC']['VPCRegion']
else:
if record['vpc_id'] in [v['VPCId'] for v in vpc_details]:
current_vpc_id = record['vpc_id']
if record['vpc_region'] in [v['VPCRegion'] for v in vpc_details]:
current_vpc_region = record['vpc_region']
if record['vpc_id'] == current_vpc_id and record['vpc_region'] == current_vpc_region:
record['zone_id'] = zone_details['Id'].replace('/hostedzone/', '')
if 'Comment' in zone_details['Config'] and zone_details['Config']['Comment'] != record['comment']:
if not module.check_mode:
try:
client.update_hosted_zone_comment(Id=zone_details['Id'], Comment=record['comment'])
except (BotoCoreError, ClientError) as e:
module.fail_json_aws(e, msg="Could not update comment for hosted zone %s" % zone_details['Id'])
return True, record
else:
record['msg'] = "There is already a private hosted zone in the same region with the same VPC \
you chose. Unable to create a new private hosted zone in the same name space."
return False, record
if not module.check_mode:
try:
result = client.create_hosted_zone(
Name=record['name'],
HostedZoneConfig={
'Comment': record['comment'] if record['comment'] is not None else "",
'PrivateZone': True,
},
VPC={
'VPCRegion': record['vpc_region'],
'VPCId': record['vpc_id'],
},
CallerReference="%s-%s" % (record['name'], time.time()),
)
except (BotoCoreError, ClientError) as e:
module.fail_json_aws(e, msg="Could not create hosted zone")
hosted_zone = result['HostedZone']
zone_id = hosted_zone['Id'].replace('/hostedzone/', '')
record['zone_id'] = zone_id
changed = True
return changed, record
def create_or_update_public(module, client, matching_zones, record):
zone_details, zone_delegation_set_details = None, {}
for matching_zone in matching_zones:
try:
zone = client.get_hosted_zone(Id=matching_zone['Id'])
zone_details = zone['HostedZone']
zone_delegation_set_details = zone.get('DelegationSet', {})
except (BotoCoreError, ClientError) as e:
module.fail_json_aws(e, msg="Could not get details about hosted zone %s" % matching_zone['Id'])
if 'Comment' in zone_details['Config'] and zone_details['Config']['Comment'] != record['comment']:
if not module.check_mode:
try:
client.update_hosted_zone_comment(
Id=zone_details['Id'],
Comment=record['comment']
)
except (BotoCoreError, ClientError) as e:
module.fail_json_aws(e, msg="Could not update comment for hosted zone %s" % zone_details['Id'])
changed = True
else:
changed = False
break
if zone_details is None:
if not module.check_mode:
try:
params = dict(
Name=record['name'],
HostedZoneConfig={
'Comment': record['comment'] if record['comment'] is not None else "",
'PrivateZone': False,
},
CallerReference="%s-%s" % (record['name'], time.time()),
)
if record.get('delegation_set_id') is not None:
params['DelegationSetId'] = record['delegation_set_id']
result = client.create_hosted_zone(**params)
zone_details = result['HostedZone']
zone_delegation_set_details = result.get('DelegationSet', {})
except (BotoCoreError, ClientError) as e:
module.fail_json_aws(e, msg="Could not create hosted zone")
changed = True
if not module.check_mode:
record['zone_id'] = zone_details['Id'].replace('/hostedzone/', '')
record['name'] = zone_details['Name']
record['delegation_set_id'] = zone_delegation_set_details.get('Id', '').replace('/delegationset/', '')
return changed, record
def delete_private(module, client, matching_zones, vpc_id, vpc_region):
for z in matching_zones:
try:
result = client.get_hosted_zone(Id=z['Id'])
except (BotoCoreError, ClientError) as e:
module.fail_json_aws(e, msg="Could not get details about hosted zone %s" % z['Id'])
zone_details = result['HostedZone']
vpc_details = result['VPCs']
if isinstance(vpc_details, dict):
if vpc_details['VPC']['VPCId'] == vpc_id and vpc_region == vpc_details['VPC']['VPCRegion']:
if not module.check_mode:
try:
client.delete_hosted_zone(Id=z['Id'])
except (BotoCoreError, ClientError) as e:
module.fail_json_aws(e, msg="Could not delete hosted zone %s" % z['Id'])
return True, "Successfully deleted %s" % zone_details['Name']
else:
if vpc_id in [v['VPCId'] for v in vpc_details] and vpc_region in [v['VPCRegion'] for v in vpc_details]:
if not module.check_mode:
try:
client.delete_hosted_zone(Id=z['Id'])
except (BotoCoreError, ClientError) as e:
module.fail_json_aws(e, msg="Could not delete hosted zone %s" % z['Id'])
return True, "Successfully deleted %s" % zone_details['Name']
return False, "The vpc_id and the vpc_region do not match a private hosted zone."
def delete_public(module, client, matching_zones):
if len(matching_zones) > 1:
changed = False
msg = "There are multiple zones that match. Use hosted_zone_id to specify the correct zone."
else:
if not module.check_mode:
try:
client.delete_hosted_zone(Id=matching_zones[0]['Id'])
except (BotoCoreError, ClientError) as e:
module.fail_json_aws(e, msg="Could not get delete hosted zone %s" % matching_zones[0]['Id'])
changed = True
msg = "Successfully deleted %s" % matching_zones[0]['Id']
return changed, msg
def delete_hosted_id(module, client, hosted_zone_id, matching_zones):
if hosted_zone_id == "all":
deleted = []
for z in matching_zones:
deleted.append(z['Id'])
if not module.check_mode:
try:
client.delete_hosted_zone(Id=z['Id'])
except (BotoCoreError, ClientError) as e:
module.fail_json_aws(e, msg="Could not delete hosted zone %s" % z['Id'])
changed = True
msg = "Successfully deleted zones: %s" % deleted
elif hosted_zone_id in [zo['Id'].replace('/hostedzone/', '') for zo in matching_zones]:
if not module.check_mode:
try:
client.delete_hosted_zone(Id=hosted_zone_id)
except (BotoCoreError, ClientError) as e:
module.fail_json_aws(e, msg="Could not delete hosted zone %s" % hosted_zone_id)
changed = True
msg = "Successfully deleted zone: %s" % hosted_zone_id
else:
changed = False
msg = "There is no zone to delete that matches hosted_zone_id %s." % hosted_zone_id
return changed, msg
def delete(module, client, matching_zones):
zone_in = module.params.get('zone').lower()
vpc_id = module.params.get('vpc_id')
vpc_region = module.params.get('vpc_region')
hosted_zone_id = module.params.get('hosted_zone_id')
if not zone_in.endswith('.'):
zone_in += "."
private_zone = bool(vpc_id and vpc_region)
if zone_in in [z['Name'] for z in matching_zones]:
if hosted_zone_id:
changed, result = delete_hosted_id(module, client, hosted_zone_id, matching_zones)
else:
if private_zone:
changed, result = delete_private(module, client, matching_zones, vpc_id, vpc_region)
else:
changed, result = delete_public(module, client, matching_zones)
else:
changed = False
result = "No zone to delete."
return changed, result
def main():
argument_spec = dict(
zone=dict(required=True),
state=dict(default='present', choices=['present', 'absent']),
vpc_id=dict(default=None),
vpc_region=dict(default=None),
comment=dict(default=''),
hosted_zone_id=dict(),
delegation_set_id=dict(),
)
mutually_exclusive = [
['delegation_set_id', 'vpc_id'],
['delegation_set_id', 'vpc_region'],
]
module = AnsibleAWSModule(
argument_spec=argument_spec,
mutually_exclusive=mutually_exclusive,
supports_check_mode=True,
)
zone_in = module.params.get('zone').lower()
state = module.params.get('state').lower()
vpc_id = module.params.get('vpc_id')
vpc_region = module.params.get('vpc_region')
if not zone_in.endswith('.'):
zone_in += "."
private_zone = bool(vpc_id and vpc_region)
client = module.client('route53')
zones = find_zones(module, client, zone_in, private_zone)
if state == 'present':
changed, result = create(module, client, matching_zones=zones)
elif state == 'absent':
changed, result = delete(module, client, matching_zones=zones)
if isinstance(result, dict):
module.exit_json(changed=changed, result=result, **result)
else:
module.exit_json(changed=changed, result=result)
if __name__ == '__main__':
main()
|
the-stack_0_14712 | """Support for MyChevy sensors."""
import logging
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN, SensorEntity
from homeassistant.const import PERCENTAGE
from homeassistant.core import callback
from homeassistant.helpers.icon import icon_for_battery_level
from homeassistant.util import slugify
from . import (
DOMAIN as MYCHEVY_DOMAIN,
ERROR_TOPIC,
MYCHEVY_ERROR,
MYCHEVY_SUCCESS,
UPDATE_TOPIC,
EVSensorConfig,
)
_LOGGER = logging.getLogger(__name__)
BATTERY_SENSOR = "batteryLevel"
SENSORS = [
EVSensorConfig("Mileage", "totalMiles", "miles", "mdi:speedometer"),
EVSensorConfig("Electric Range", "electricRange", "miles", "mdi:speedometer"),
EVSensorConfig("Charged By", "estimatedFullChargeBy"),
EVSensorConfig("Charge Mode", "chargeMode"),
EVSensorConfig(
"Battery Level", BATTERY_SENSOR, PERCENTAGE, "mdi:battery", ["charging"]
),
]
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the MyChevy sensors."""
if discovery_info is None:
return
hub = hass.data[MYCHEVY_DOMAIN]
sensors = [MyChevyStatus()]
for sconfig in SENSORS:
for car in hub.cars:
sensors.append(EVSensor(hub, sconfig, car.vid))
add_entities(sensors)
class MyChevyStatus(SensorEntity):
"""A string representing the charge mode."""
_name = "MyChevy Status"
_icon = "mdi:car-connected"
def __init__(self):
"""Initialize sensor with car connection."""
self._state = None
async def async_added_to_hass(self):
"""Register callbacks."""
self.async_on_remove(
self.hass.helpers.dispatcher.async_dispatcher_connect(
UPDATE_TOPIC, self.success
)
)
self.async_on_remove(
self.hass.helpers.dispatcher.async_dispatcher_connect(
ERROR_TOPIC, self.error
)
)
@callback
def success(self):
"""Update state, trigger updates."""
if self._state != MYCHEVY_SUCCESS:
_LOGGER.debug("Successfully connected to mychevy website")
self._state = MYCHEVY_SUCCESS
self.async_write_ha_state()
@callback
def error(self):
"""Update state, trigger updates."""
_LOGGER.error(
"Connection to mychevy website failed. "
"This probably means the mychevy to OnStar link is down"
)
self._state = MYCHEVY_ERROR
self.async_write_ha_state()
@property
def icon(self):
"""Return the icon."""
return self._icon
@property
def name(self):
"""Return the name."""
return self._name
@property
def native_value(self):
"""Return the state."""
return self._state
@property
def should_poll(self):
"""Return the polling state."""
return False
class EVSensor(SensorEntity):
"""Base EVSensor class.
The only real difference between sensors is which units and what
attribute from the car object they are returning. All logic can be
built with just setting subclass attributes.
"""
def __init__(self, connection, config, car_vid):
"""Initialize sensor with car connection."""
self._conn = connection
self._name = config.name
self._attr = config.attr
self._extra_attrs = config.extra_attrs
self._unit_of_measurement = config.unit_of_measurement
self._icon = config.icon
self._state = None
self._state_attributes = {}
self._car_vid = car_vid
self.entity_id = f"{SENSOR_DOMAIN}.{MYCHEVY_DOMAIN}_{slugify(self._car.name)}_{slugify(self._name)}"
async def async_added_to_hass(self):
"""Register callbacks."""
self.hass.helpers.dispatcher.async_dispatcher_connect(
UPDATE_TOPIC, self.async_update_callback
)
@property
def _car(self):
"""Return the car."""
return self._conn.get_car(self._car_vid)
@property
def icon(self):
"""Return the icon."""
if self._attr == BATTERY_SENSOR:
charging = self._state_attributes.get("charging", False)
return icon_for_battery_level(self.state, charging)
return self._icon
@property
def name(self):
"""Return the name."""
return self._name
@callback
def async_update_callback(self):
"""Update state."""
if self._car is not None:
self._state = getattr(self._car, self._attr, None)
if self._unit_of_measurement == "miles":
self._state = round(self._state)
for attr in self._extra_attrs:
self._state_attributes[attr] = getattr(self._car, attr)
self.async_write_ha_state()
@property
def native_value(self):
"""Return the state."""
return self._state
@property
def extra_state_attributes(self):
"""Return all the state attributes."""
return self._state_attributes
@property
def native_unit_of_measurement(self):
"""Return the unit of measurement the state is expressed in."""
return self._unit_of_measurement
@property
def should_poll(self):
"""Return the polling state."""
return False
|
the-stack_0_14714 | #!/usr/bin/env python3
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
from test_framework.script import *
from test_framework.mininode import *
from test_framework.address import *
from test_framework.qtum import *
import sys
import random
import time
class QtumPrematureCoinstakeSpendTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
def remove_from_staking_prevouts(self, remove_prevout):
for j in range(len(self.staking_prevouts)):
prevout = self.staking_prevouts[j]
if prevout[0].serialize() == remove_prevout.serialize():
self.staking_prevouts.pop(j)
break
def assert_spend_of_coinstake_at_height(self, height, should_accept):
spend_block = self.node.getblock(self.node.getblockhash(height))
spend_coinstake_txid = spend_block['tx'][1]
spend_coinstake_txout = self.node.gettxout(spend_coinstake_txid, 1)
tx = CTransaction()
tx.vin = [CTxIn(COutPoint(int(spend_coinstake_txid, 16), 1))]
tx.vout = [CTxOut(int(float(str(spend_coinstake_txout['value']))*COIN - 1000000), scriptPubKey=CScript([OP_TRUE]))]
tx = rpc_sign_transaction(self.node, tx)
if should_accept:
self.node.sendrawtransaction(bytes_to_hex_str(tx.serialize()))
else:
assert_raises_rpc_error(-26, "bad-txns-premature-spend-of-coinbase", self.node.sendrawtransaction, bytes_to_hex_str(tx.serialize()))
tip = self.node.getblock(self.node.getbestblockhash())
next_block_time = (tip['time'] + 0x30) & 0xfffffff0
self.node.setmocktime(next_block_time)
block, sig_key = create_unsigned_mpos_block(self.node, self.staking_prevouts, next_block_time, 1000000)
block.vtx.append(tx)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.sign_block(sig_key)
blockcount = self.node.getblockcount()
self.node.submitblock(bytes_to_hex_str(block.serialize()))
#assert_equal(self.node.getblockcount(), blockcount + (1 if should_accept else 0))
self.remove_from_staking_prevouts(block.prevoutStake)
def run_test(self):
self.node = self.nodes[0]
self.node.setmocktime(int(time.time()) - 1000000)
self.node.generate(10 + COINBASE_MATURITY)
# These are the privkeys that corresponds to the pubkeys in the pos outputs
# These are used by default by create_pos_block
for i in range(0xff+1):
privkey = byte_to_base58(hash256(struct.pack('<I', i)), 239)
self.node.importprivkey(privkey)
generatedMpos = activate_mpos(self.node)
self.staking_prevouts = collect_prevouts(self.node)
last_height = self.node.getblock(self.node.getbestblockhash())['height']
self.log.info('last_height=%s' % (last_height))
self.assert_spend_of_coinstake_at_height(height=last_height, should_accept=False)
if generatedMpos > COINBASE_MATURITY:
self.assert_spend_of_coinstake_at_height(last_height - generatedMpos + 1, should_accept=True)
# Invalidate the last block and make sure that the previous rejection of the premature coinstake spends fails
self.node.invalidateblock(self.node.getbestblockhash())
assert_equal(last_height, self.node.getblock(self.node.getbestblockhash())['height'] + 1)
#self.log.info('updated last_height=%s' % (self.node.getblock(self.node.getbestblockhash())['height']))
#self.assert_spend_of_coinstake_at_height(height=last_height, should_accept=False)
if __name__ == '__main__':
QtumPrematureCoinstakeSpendTest().main()
|
the-stack_0_14715 | import getpass
import os
import re
import subprocess
import click
from .config import *
class JumpOutFuckingClick(Exception):
"""Just to break out the unkown loop"""
pass
class JumpOutFuckingClick2(Exception):
"""Just to break out the unkown loop2"""
pass
def ssl_file_gen(domain,usr,loc,email,key):
with open(SSL, "r") as fh:
fds = fh.read()
fcd = re.sub(r'{{DOMAIN}}', '.'.join(domain.split('.')[-2:]), fds)
fce = re.sub(r'{{EMAIL}}', email, fcd)
res = re.sub(r'{{KEY}}', key, fce)
with open(domain+"/"+domain+'.sh', 'w') as ssl_sh:
ssl_sh.write(res)
ssl_sh.close()
fh.close()
click.echo("-4- SSL script: {} create successfully".format(domain+"/"+domain+'.sh'))
def ssl_multi_gen(domain,usr,loc,op1,op2,dns_op):
with open(SSL, "r") as fh:
fds = fh.read()
fcd = re.sub(r'{{DOMAIN}}', '.'.join(domain.split('.')[-2:]), fds)
fce = re.sub(r'{{OP1}}', op1, fcd)
fcf = re.sub(r'{{OP2}}', op2, fce)
res = re.sub(r'{{DNS_OP}}', dns_op, fcf)
with open(domain+"/"+domain+'.sh', 'w') as ssl_sh:
ssl_sh.write(res)
ssl_sh.close()
fh.close()
click.echo("-4- SSL script: {} create successfully".format(domain+"/"+domain+'.sh'))
def docker_file_gen(domain,usr,loc):
with open(DOCKER, "r") as fh:
fds = fh.read()
fcd = re.sub(r'{{DOMAIN}}', domain, fds)
fcu = re.sub(r'{{usr}}', usr, fcd)
res = re.sub(r'{{passwd}}', loc+domain+usr, fcu)
with open(domain+"/"+domain+'.run', 'w') as docker_run:
docker_run.write(res)
docker_run.close()
fh.close()
click.echo("-3- Docker config script: {} create successfully".format(domain+"/"+domain+'.run'))
def uwsgi_file_gen(domain,usr,loc):
env = os.path.dirname(loc)
with open(uWSGI, 'r') as fh:
fds = fh.read()
fce = re.sub(r'{{env}}',env,fds)
fcu = re.sub(r'{{usr}}',usr,fce)
res = re.sub(r'{{loc}}',loc,fcu)
with open(domain+"/"+domain+'.ini', 'w') as uwsgi_ini:
uwsgi_ini.write(res)
uwsgi_ini.close()
fh.close()
click.echo("-0- uwsgi config file: {} create successfully".format(domain+"/"+domain+'.ini'))
#static
def nginx_file_gen(domain,usr,loc):
with open(NGINX, "r") as fh:
fds = fh.read()
fcd = re.sub(r'{{DOMAIN}}', domain, fds)
res = re.sub(r'{{loc}}', loc, fcd)
with open(domain+"/"+domain+'.conf', 'w') as nginx_conf:
nginx_conf.write(res)
nginx_conf.close()
fh.close()
click.echo("-1- Nginx config file: {} create successfully".format(domain+"/"+domain+'.conf'))
#static
def service_file_gen(domain,usr,loc):
with open(SERVICE, "r") as fh:
fds = fh.read()
fcd = re.sub(r'{{DOMAIN}}', domain, fds)
fcu = re.sub(r'{{usr}}', usr, fcd)
res = re.sub(r'{{loc}}', loc, fcu)
with open(domain+"/"+domain+'.service', 'w') as confservice:
confservice.write(res)
confservice.close()
fh.close()
click.echo("-2- Systemd service file : {} create successfully".format(domain+"/"+domain+'.service'))
def script_files_gen(domain, usr, loc):
cmd = []
files = loc+"/"+domain
c = None
if os.path.exists(files+'.sh'):
c = "sudo mkdir -p /etc/nginx/certs"
c1 = "sudo /bin/bash "+files+'.sh'
cmd.append(c)
cmd.append(c1)
if os.path.exists(files+'.run'):
c = "sudo "+files+'.run'
cmd.append(c)
if os.path.exists(files+'.conf'):
c = "sudo cp "+files+'.conf ' + NGINX_CONF1
c1 = "sudo cp "+files+'.conf ' + NGINX_CONF2
c2 = "sudo nginx -s reload"
cmd.append(c)
cmd.append(c1)
cmd.append(c2)
if os.path.exists(files+'.service'):
c = "sudo cp "+files+'.service ' + SYSTEMD_CONF
c1 = "sudo systemctl enable "+domain+'.service'
c2 = "sudo systemctl start "+domain+'.service'
cmd.append(c)
cmd.append(c1)
cmd.append(c2)
with open(loc+'/start.sh', 'w') as file:
for c in cmd:
file.write(c+"\n")
file.close()
click.echo("-5- One click script file : {} create successfully".format(domain+"/"+'start.sh'))
def script_files_run(domain, usr, loc):
subprocess.call(['sudo', '/bin/bash',loc+'/start.sh'])
|
the-stack_0_14716 | import timeit
from typing import *
from subseq import is_subseq_py, is_subseq_rs
seq = ['a', 'b', 'c'] * 100
subseq = ['dd', 'ee']
joined_seq = "," + ",".join(seq) + ","
joined_subseq = "," + ",".join(subseq) + ","
def find_loop(seq, subseq):
n = len(seq)
m = len(subseq)
for i in range(n - m + 1):
found = True
for j in range(m):
if seq[i + j] != subseq[j]:
found = False
break
if found:
return True
def is_subseq_str(seq, subseq):
return subseq in seq
is_subseq_py(seq, subseq)
n = 10000
timer = timeit.Timer("is_subseq(seq, subseq)", globals={"is_subseq": is_subseq_rs, "seq": seq, "subseq": subseq})
t = timer.timeit(number=n)
print(f"rust (rust): {t*10**9/n}")
timer = timeit.Timer("is_subseq(seq, subseq)", globals={"is_subseq": is_subseq_py, "seq": seq, "subseq": subseq})
t = timer.timeit(number=n)
print(f"rust (py): {t*10**9/n}")
timer = timeit.Timer("is_subseq(seq, subseq)", globals={"is_subseq": find_loop, "seq": seq, "subseq": subseq})
t = timer.timeit(number=n)
print(f"python: {t*10**9/n}")
timer = timeit.Timer("is_subseq(seq, subseq)", globals={"is_subseq": is_subseq_str, "seq": seq, "subseq": subseq})
t = timer.timeit(number=n)
print(f"python str: {t*10**9/n}")
|
the-stack_0_14717 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import codecs
import json
import os.path
import re
import resources
import subprocess
import sys
try:
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
except ImportError:
# needed for py3+qt4
# Ref:
# http://pyqt.sourceforge.net/Docs/PyQt4/incompatible_apis.html
# http://stackoverflow.com/questions/21217399/pyqt4-qtcore-qvariant-object-instead-of-a-string
if sys.version_info.major >= 3:
import sip
sip.setapi('QVariant', 2)
from PyQt4.QtGui import *
from PyQt4.QtCore import *
# Add internal libs
from bisect import insort
from collections import defaultdict
from functools import partial
from libs.canvas import Canvas
from libs.colorDialog import ColorDialog
from libs.constants import *
from libs.labelDialog import LabelDialog
from libs.labelFile import LabelFile, LabelFileError
from libs.lib import struct, newAction, newIcon, addActions, fmtShortcut, generateColorByText
from libs.loginDialog import Login
from libs.pascal_voc_io import PascalVocReader, XML_EXT
from libs.settings import Settings
from libs.shape import Shape, DEFAULT_LINE_COLOR, DEFAULT_FILL_COLOR
from libs.toolBar import ToolBar
from libs.ustr import ustr
from libs.version import __version__
from libs.zoomWidget import ZoomWidget
import lmdb
__appname__ = 'vanno_ver'
server_path = "../vanno_server/env/"
dataset = 'jester'
# Utility functions and classes.
def have_qstring():
'''p3/qt5 get rid of QString wrapper as py3 has native unicode str type'''
return not (sys.version_info.major >= 3 or QT_VERSION_STR.startswith('5.'))
def util_qt_strlistclass():
return QStringList if have_qstring() else list
class WindowMixin(object):
def menu(self, title, actions=None):
menu = self.menuBar().addMenu(title)
if actions:
addActions(menu, actions)
return menu
def toolbar(self, title, actions=None):
toolbar = ToolBar(title)
toolbar.setObjectName(u'%sToolBar' % title)
# toolbar.setOrientation(Qt.Vertical)
toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
if actions:
addActions(toolbar, actions)
self.addToolBar(Qt.LeftToolBarArea, toolbar)
return toolbar
# PyQt5: TypeError: unhashable type: 'QListWidgetItem'
class HashableQListWidgetItem(QListWidgetItem):
def __init__(self, *args):
super(HashableQListWidgetItem, self).__init__(*args)
def __hash__(self):
return hash(id(self))
class MainWindow(QMainWindow, WindowMixin):
FIT_WINDOW, FIT_WIDTH, MANUAL_ZOOM = list(range(3))
def __init__(self,logged_id, defaultFilename=None, defaultPrefdefClassFile=None):
super(MainWindow, self).__init__()
self.setWindowTitle(__appname__)
# Load setting in the main thread
self.settings = Settings()
self.settings.load()
settings = self.settings
# Save as Pascal voc xml
self.defaultSaveDir = ""
self.defaultSaveDir_folder= ""
self.usingPascalVocFormat = True
# For loading all image under a directory
self.mImgList = []
self.mDirList = []
self.dirname = None
self.labelHist = []
self.lastOpenDir = None
self.old_Filepath=None
# self.proj_dir=None
# Whether we need to save or not.
self.dirty = False
self._noSelectionSlot = False
self._beginner = True
self.screencastViewer = "firefox"
self.screencast = "https://youtu.be/p0nR2YsCY_U"
self.logged_id=logged_id
self.ids = []
# Load predefined classes to the list
if defaultPrefdefClassFile is not None:
self.loadPredefinedClasses(defaultPrefdefClassFile)
# Main widgets and related state.
self.labelDialog = LabelDialog(parent=self, listItem=self.labelHist)
self.itemsToShapes = {}
self.shapesToItems = {}
self.prevLabelText = ''
listLayout = QVBoxLayout()
listLayout.setContentsMargins(0, 0, 0, 0)
# Create a widget for using default label
self.useDefaultLabelCheckbox = QCheckBox(u'Use default label')
self.useDefaultLabelCheckbox.setChecked(False)
self.defaultLabelTextLine = QLineEdit()
useDefaultLabelQHBoxLayout = QHBoxLayout()
useDefaultLabelQHBoxLayout.addWidget(self.useDefaultLabelCheckbox)
useDefaultLabelQHBoxLayout.addWidget(self.defaultLabelTextLine)
useDefaultLabelContainer = QWidget()
useDefaultLabelContainer.setLayout(useDefaultLabelQHBoxLayout)
# Create a widget for edit and diffc button
self.diffcButton = QCheckBox(u'difficult')
self.diffcButton.setChecked(False)
self.diffcButton.stateChanged.connect(self.btnstate)
self.editButton = QToolButton()
self.editButton.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
# self.saveButton = QToolButton()
# self.saveButton.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
# self.saveButton.setText("Save checking")
# self.saveButton.clicked.connect(self.saveButtonClicked)
self.edit_label = QLabel()
self.save_label = QLabel()
self.anno_label = QLabel()
self.id_label = QLabel()
# Add some of widgets to listLayout
listLayout.addWidget(self.editButton)
listLayout.addWidget(self.diffcButton)
listLayout.addWidget(useDefaultLabelContainer)
# Create and add a widget for showing current label items
self.labelList = QListWidget()
labelListContainer = QWidget()
labelListContainer.setLayout(listLayout)
self.labelList.itemActivated.connect(self.labelSelectionChanged)
self.labelList.itemSelectionChanged.connect(self.labelSelectionChanged)
self.labelList.itemDoubleClicked.connect(self.editLabel)
# Connect to itemChanged to detect checkbox changes.
self.labelList.itemChanged.connect(self.labelItemChanged)
listLayout.addWidget(self.labelList)
listLayout.addWidget(self.anno_label)
listLayout.addWidget(self.edit_label)
listLayout.addWidget(self.save_label)
self.dock = QDockWidget(self.logged_id, self)
self.dock.setObjectName(u'Labels')
self.dock.setWidget(labelListContainer)
self.folderListWidget = QListWidget()
self.folderListWidget.itemDoubleClicked.connect(self.diritemDoubleClicked)
self.folderListWidget.itemChanged.connect(self.diritemChanged)
folderlistLayout = QVBoxLayout()
folderlistLayout.setContentsMargins(0, 0, 0, 0)
# folderlistLayout.addWidget(self.saveButton)
###
self.savebtncnt_label = QLabel()
folderlistLayout.addWidget(self.savebtncnt_label)
# self.savebtn_label = QLabel()
# folderlistLayout.addWidget(self.savebtn_label)
folderlistLayout.addWidget(self.folderListWidget)
folderListContainer = QWidget()
folderListContainer.setLayout(folderlistLayout)
self.folderdock = QDockWidget(u'Folder List', self)
self.folderdock.setObjectName(u'Folders')
self.folderdock.setWidget(folderListContainer)
# Tzutalin 20160906 : Add file list and dock to move faster
self.fileListWidget = QListWidget()
self.fileListWidget.itemDoubleClicked.connect(self.fileitemDoubleClicked)
filelistLayout = QVBoxLayout()
filelistLayout.setContentsMargins(0, 0, 0, 0)
filelistLayout.addWidget(self.fileListWidget)
fileListContainer = QWidget()
fileListContainer.setLayout(filelistLayout)
self.filedock = QDockWidget(u'File List', self)
self.filedock.setObjectName(u'Files')
self.filedock.setWidget(fileListContainer)
self.zoomWidget = ZoomWidget()
self.colorDialog = ColorDialog(parent=self)
self.canvas = Canvas(parent=self)
self.canvas.zoomRequest.connect(self.zoomRequest)
scroll = QScrollArea()
scroll.setWidget(self.canvas)
scroll.setWidgetResizable(True)
self.scrollBars = {
Qt.Vertical: scroll.verticalScrollBar(),
Qt.Horizontal: scroll.horizontalScrollBar()
}
self.scrollArea = scroll
self.canvas.scrollRequest.connect(self.scrollRequest)
self.canvas.newShape.connect(self.newShape)
self.canvas.shapeMoved.connect(self.setDirty)
self.canvas.selectionChanged.connect(self.shapeSelectionChanged)
self.canvas.drawingPolygon.connect(self.toggleDrawingSensitive)
self.setCentralWidget(scroll)
self.addDockWidget(Qt.RightDockWidgetArea, self.dock)
# Tzutalin 20160906 : Add file list and dock to move faster
self.addDockWidget(Qt.RightDockWidgetArea, self.folderdock)
self.addDockWidget(Qt.RightDockWidgetArea, self.filedock)
# self.filedock.setFeatures(QDockWidget.DockWidgetFloatable)
# self.dockFeatures = QDockWidget.DockWidgetClosable | QDockWidget.DockWidgetFloatable
# self.dock.setFeatures(self.dock.features() ^ self.dockFeatures)
###
self.foldercnt = 0
self.checkList = []
self.verJobList = []
file = QFile(server_path + '../ids.txt')
if file.open(QFile.ReadOnly | QFile.Text):
while not file.atEnd():
line = bytearray(file.readLine()).decode().strip()
insort(self.ids, line)
file.close()
for id in self.ids:
file = QFile(server_path + dataset + '/' + id + '.txt')
if file.open(QFile.ReadOnly | QFile.Text):
while not file.atEnd():
line = bytearray(file.readLine()).decode().strip()
insort(self.verJobList, line)
file.close()
# file = QFile(server_path + dataset + '/' + self.logged_id + '.txt')
# if file.open(QFile.ReadOnly | QFile.Text):
# while not file.atEnd():
# line = bytearray(file.readLine()).decode().strip()
# insort(self.checkList, line)
# file.close()
# Actions
action = partial(newAction, self)
quit = action('&Quit', self.close,
'Ctrl+Q', 'quit', u'Quit application')
open = action('&Open', self.openFile,
'Ctrl+O', 'open', u'Open image or label file')
opendir = action('&Open Dir', self.openDirDialog,
'u', 'open', u'Open Dir')
changeSavedir = action('&Change Save Dir', self.changeSavedirDialog,
'r', 'open', u'Change default saved Annotation dir')
openAnnotation = action('&Open Annotation', self.openAnnotationDialog,
'Ctrl+Shift+O', 'open', u'Open Annotation')
openNextImg = action('&Next Image', self.openNextImg,
'd', 'next', u'Open Next')
openPrevImg = action('&Prev Image', self.openPrevImg,
'a', 'prev', u'Open Prev')
verify = action('&Verify Image', self.verifyImg,
'space', 'verify', u'Verify Image')
save = action('&Save', self.saveFile,
's', 'save', u'Save labels to file', enabled=False)
saveAs = action('&Save As', self.saveFileAs,
'Ctrl+Shift+S', 'save-as', u'Save labels to a different file', enabled=False)
close = action('&Close', self.closeFile, 'Ctrl+W', 'close', u'Close current file')
resetAll = action('&ResetAll', self.resetAll, None, 'resetall', u'Reset all')
color1 = action('Box Line Color', self.chooseColor1,
'Ctrl+L', 'color_line', u'Choose Box line color')
createMode = action('Create\nRectBox', self.setCreateMode,
'w', 'new', u'Start drawing Boxs', enabled=False)
editMode = action('&Edit\nRectBox', self.setEditMode,
'Ctrl+J', 'edit', u'Move and edit Boxs', enabled=False)
create = action('Create\nRectBox', self.createShape,
'w', 'new', u'Draw a new Box', enabled=False)
delete = action('Delete\nRectBox', self.deleteSelectedShape,
'Delete', 'delete', u'Delete', enabled=False)
copy = action('&Duplicate\nRectBox', self.copySelectedShape,
'Ctrl+D', 'copy', u'Create a duplicate of the selected Box',
enabled=False)
advancedMode = action('&Advanced Mode', self.toggleAdvancedMode,
'Ctrl+Shift+A', 'expert', u'Switch to advanced mode',
checkable=True)
hideAll = action('&Hide\nRectBox', partial(self.togglePolygons, False),
'Ctrl+H', 'hide', u'Hide all Boxs',
enabled=False)
showAll = action('&Show\nRectBox', partial(self.togglePolygons, True),
'Ctrl+A', 'hide', u'Show all Boxs',
enabled=False)
help = action('&Tutorial', self.showTutorialDialog, None, 'help', u'Show demos')
showInfo = action('&Information', self.showInfoDialog, None, 'help', u'Information')
zoom = QWidgetAction(self)
zoom.setDefaultWidget(self.zoomWidget)
self.zoomWidget.setWhatsThis(
u"Zoom in or out of the image. Also accessible with"
" %s and %s from the canvas." % (fmtShortcut("Ctrl+[-+]"),
fmtShortcut("Ctrl+Wheel")))
self.zoomWidget.setEnabled(False)
zoomIn = action('Zoom &In', partial(self.addZoom, 10),
'Ctrl++', 'zoom-in', u'Increase zoom level', enabled=False)
zoomOut = action('&Zoom Out', partial(self.addZoom, -10),
'Ctrl+-', 'zoom-out', u'Decrease zoom level', enabled=False)
zoomOrg = action('&Original size', partial(self.setZoom, 100),
'Ctrl+=', 'zoom', u'Zoom to original size', enabled=False)
fitWindow = action('&Fit Window', self.setFitWindow,
'Ctrl+F', 'fit-window', u'Zoom follows window size',
checkable=True, enabled=False)
fitWidth = action('Fit &Width', self.setFitWidth,
'Ctrl+Shift+F', 'fit-width', u'Zoom follows window width',
checkable=True, enabled=False)
# Group zoom controls into a list for easier toggling.
zoomActions = (self.zoomWidget, zoomIn, zoomOut,
zoomOrg, fitWindow, fitWidth)
self.zoomMode = self.MANUAL_ZOOM
self.scalers = {
self.FIT_WINDOW: self.scaleFitWindow,
self.FIT_WIDTH: self.scaleFitWidth,
# Set to one to scale to 100% when loading files.
self.MANUAL_ZOOM: lambda: 1,
}
edit = action('&Edit Label', self.editLabel,
'Ctrl+E', 'edit', u'Modify the label of the selected Box',
enabled=False)
self.editButton.setDefaultAction(edit)
shapeLineColor = action('Shape &Line Color', self.chshapeLineColor,
icon='color_line', tip=u'Change the line color for this specific shape',
enabled=False)
shapeFillColor = action('Shape &Fill Color', self.chshapeFillColor,
icon='color', tip=u'Change the fill color for this specific shape',
enabled=False)
labels = self.dock.toggleViewAction()
labels.setText('Show/Hide Label Panel')
labels.setShortcut('Ctrl+Shift+L')
# Lavel list context menu.
labelMenu = QMenu()
addActions(labelMenu, (edit, delete))
self.labelList.setContextMenuPolicy(Qt.CustomContextMenu)
self.labelList.customContextMenuRequested.connect(
self.popLabelListMenu)
# Store actions for further handling.
self.actions = struct(save=save, saveAs=saveAs, open=open, close=close, resetAll = resetAll,
lineColor=color1, create=create, delete=delete, edit=edit, copy=copy,
createMode=createMode, editMode=editMode, advancedMode=advancedMode,
shapeLineColor=shapeLineColor, shapeFillColor=shapeFillColor,
zoom=zoom, zoomIn=zoomIn, zoomOut=zoomOut, zoomOrg=zoomOrg,
fitWindow=fitWindow, fitWidth=fitWidth,
zoomActions=zoomActions,
fileMenuActions=(
open, opendir, save, saveAs, close, resetAll, quit),
beginner=(), advanced=(),
editMenu=(edit, copy, delete,
None, color1),
beginnerContext=(create, edit, copy, delete),
advancedContext=(createMode, editMode, edit, copy,
delete, shapeLineColor, shapeFillColor),
onLoadActive=(
close, create, createMode, editMode),
onShapesPresent=(saveAs, hideAll, showAll))
self.menus = struct(
file=self.menu('&File'),
edit=self.menu('&Edit'),
view=self.menu('&View'),
help=self.menu('&Help'),
recentFiles=QMenu('Open &Recent'),
labelList=labelMenu)
# Auto saving : Enable auto saving if pressing next
self.autoSaving = QAction("Auto Saving", self)
self.autoSaving.setCheckable(True)
self.autoSaving.setChecked(settings.get(SETTING_AUTO_SAVE, False))
# Sync single class mode from PR#106
self.singleClassMode = QAction("Single Class Mode", self)
self.singleClassMode.setShortcut("Ctrl+Shift+S")
self.singleClassMode.setCheckable(True)
self.singleClassMode.setChecked(settings.get(SETTING_SINGLE_CLASS, False))
self.lastLabel = None
addActions(self.menus.file,
(open, opendir, changeSavedir, openAnnotation, self.menus.recentFiles, save, saveAs, close, resetAll, quit))
addActions(self.menus.help, (help, showInfo))
addActions(self.menus.view, (
self.autoSaving,
self.singleClassMode,
labels, advancedMode, None,
hideAll, showAll, None,
zoomIn, zoomOut, zoomOrg, None,
fitWindow, fitWidth))
self.menus.file.aboutToShow.connect(self.updateFileMenu)
# Custom context menu for the canvas widget:
addActions(self.canvas.menus[0], self.actions.beginnerContext)
addActions(self.canvas.menus[1], (
action('&Copy here', self.copyShape),
action('&Move here', self.moveShape)))
self.tools = self.toolbar('Tools')
self.actions.beginner = (
open, opendir, changeSavedir, openNextImg, openPrevImg, verify, save, None, create, copy, delete, None,
zoomIn, zoom, zoomOut, fitWindow, fitWidth)
self.actions.advanced = (
open, opendir, changeSavedir, openNextImg, openPrevImg, save, None,
createMode, editMode, None,
hideAll, showAll)
self.statusBar().showMessage('%s started.' % __appname__)
self.statusBar().show()
# Application state.
self.image = QImage()
self.filePath = ustr(defaultFilename)
self.recentFiles = []
self.maxRecent = 7
self.lineColor = None
self.fillColor = None
self.zoom_level = 100
self.fit_window = False
# Add Chris
self.difficult = False
## Fix the compatible issue for qt4 and qt5. Convert the QStringList to python list
if settings.get(SETTING_RECENT_FILES):
if have_qstring():
recentFileQStringList = settings.get(SETTING_RECENT_FILES)
self.recentFiles = [ustr(i) for i in recentFileQStringList]
else:
self.recentFiles = recentFileQStringList = settings.get(SETTING_RECENT_FILES)
size = settings.get(SETTING_WIN_SIZE, QSize(600, 500))
position = settings.get(SETTING_WIN_POSE, QPoint(0, 0))
self.resize(size)
self.move(position)
saveDir = ustr(settings.get(SETTING_SAVE_DIR, None))
self.lastOpenDir = ustr(settings.get(SETTING_LAST_OPEN_DIR, None))
if saveDir is not None and os.path.exists(saveDir):
self.defaultSaveDir = saveDir
self.statusBar().showMessage('%s started. Annotation will be saved to %s' %
(__appname__, self.defaultSaveDir))
self.statusBar().show()
# self.restoreState(settings.get(SETTING_WIN_STATE, QByteArray()))
Shape.line_color = self.lineColor = QColor(settings.get(SETTING_LINE_COLOR, DEFAULT_LINE_COLOR))
Shape.fill_color = self.fillColor = QColor(settings.get(SETTING_FILL_COLOR, DEFAULT_FILL_COLOR))
self.canvas.setDrawingColor(self.lineColor)
# Add chris
Shape.difficult = self.difficult
def xbool(x):
if isinstance(x, QVariant):
return x.toBool()
return bool(x)
if xbool(settings.get(SETTING_ADVANCE_MODE, False)):
self.actions.advancedMode.setChecked(True)
self.toggleAdvancedMode()
# Populate the File menu dynamically.
self.updateFileMenu()
# Since loading the file may take some time, make sure it runs in the background.
if self.filePath and os.path.isdir(self.filePath):
self.queueEvent(partial(self.importDirImages, self.filePath or ""))
elif self.filePath:
self.queueEvent(partial(self.loadFile, self.filePath or ""))
# Callbacks:
self.zoomWidget.valueChanged.connect(self.paintCanvas)
self.populateModeActions()
# Display cursor coordinates at the right of status bar
self.labelCoordinates = QLabel('')
self.statusBar().addPermanentWidget(self.labelCoordinates)
# Open Dir if deafult file
if self.filePath and os.path.isdir(self.filePath):
self.openDirDialog(dirpath=self.filePath)
self.save_label.setText("Save DIR: " + self.defaultSaveDir)
## Support Functions ##
def noShapes(self):
return not self.itemsToShapes
def toggleAdvancedMode(self, value=True):
self._beginner = not value
self.canvas.setEditing(True)
self.populateModeActions()
self.editButton.setVisible(not value)
if value:
self.actions.createMode.setEnabled(True)
self.actions.editMode.setEnabled(False)
self.dock.setFeatures(self.dock.features() | self.dockFeatures)
else:
self.dock.setFeatures(self.dock.features() ^ self.dockFeatures)
def populateModeActions(self):
if self.beginner():
tool, menu = self.actions.beginner, self.actions.beginnerContext
else:
tool, menu = self.actions.advanced, self.actions.advancedContext
self.tools.clear()
addActions(self.tools, tool)
self.canvas.menus[0].clear()
addActions(self.canvas.menus[0], menu)
self.menus.edit.clear()
actions = (self.actions.create,) if self.beginner()\
else (self.actions.createMode, self.actions.editMode)
addActions(self.menus.edit, actions + self.actions.editMenu)
def setBeginner(self):
self.tools.clear()
addActions(self.tools, self.actions.beginner)
def setAdvanced(self):
self.tools.clear()
addActions(self.tools, self.actions.advanced)
def setDirty(self):
self.dirty = True
self.actions.save.setEnabled(True)
def setClean(self):
self.dirty = False
self.actions.save.setEnabled(False)
self.actions.create.setEnabled(True)
def toggleActions(self, value=True):
"""Enable/Disable widgets which depend on an opened image."""
for z in self.actions.zoomActions:
z.setEnabled(value)
for action in self.actions.onLoadActive:
action.setEnabled(value)
def queueEvent(self, function):
QTimer.singleShot(0, function)
def status(self, message, delay=5000):
self.statusBar().showMessage(message, delay)
def resetState(self):
self.itemsToShapes.clear()
self.shapesToItems.clear()
self.labelList.clear()
self.filePath = None
#self.old_Filepath = None
self.imageData = None
self.labelFile = None
self.canvas.resetState()
self.labelCoordinates.clear()
self.canvas.itemsToShapes.clear()
self.canvas.shapesToItems.clear()
def currentItem(self):
items = self.labelList.selectedItems()
if items:
return items[0]
return None
def addRecentFile(self, filePath):
if filePath in self.recentFiles:
self.recentFiles.remove(filePath)
elif len(self.recentFiles) >= self.maxRecent:
self.recentFiles.pop()
self.recentFiles.insert(0, filePath)
def beginner(self):
return self._beginner
def advanced(self):
return not self.beginner()
## Callbacks ##
def showTutorialDialog(self):
subprocess.Popen([self.screencastViewer, self.screencast])
def showInfoDialog(self):
msg = u'Name:{0} \nApp Version:{1} \n{2} '.format(__appname__, __version__, sys.version_info)
QMessageBox.information(self, u'Information', msg)
def createShape(self):
assert self.beginner()
self.canvas.setEditing(False)
self.actions.create.setEnabled(False)
def toggleDrawingSensitive(self, drawing=True):
"""In the middle of drawing, toggling between modes should be disabled."""
self.actions.editMode.setEnabled(not drawing)
if not drawing and self.beginner():
# Cancel creation.
print('Cancel creation.')
self.canvas.setEditing(True)
self.canvas.restoreCursor()
self.actions.create.setEnabled(True)
def toggleDrawMode(self, edit=True):
self.canvas.setEditing(edit)
self.actions.createMode.setEnabled(edit)
self.actions.editMode.setEnabled(not edit)
def setCreateMode(self):
assert self.advanced()
self.toggleDrawMode(False)
def setEditMode(self):
assert self.advanced()
self.toggleDrawMode(True)
self.labelSelectionChanged()
def updateFileMenu(self):
currFilePath = self.filePath
def exists(filename):
return os.path.exists(filename)
menu = self.menus.recentFiles
menu.clear()
files = [f for f in self.recentFiles if f !=
currFilePath and exists(f)]
for i, f in enumerate(files):
icon = newIcon('labels')
action = QAction(
icon, '&%d %s' % (i + 1, QFileInfo(f).fileName()), self)
action.triggered.connect(partial(self.loadRecent, f))
menu.addAction(action)
def popLabelListMenu(self, point):
self.menus.labelList.exec_(self.labelList.mapToGlobal(point))
def editLabel(self):
if not self.canvas.editing():
return
item = self.currentItem()
text = self.labelDialog.popUp(item.text())
if text is not None:
item.setText(text)
item.setBackground(generateColorByText(text))
self.setDirty()
# Tzutalin 20160906 : Add file list and dock to move faster
def fileitemDoubleClicked(self, item=None):
currIndex = self.mImgList.index(ustr(item.text()))
if currIndex < len(self.mImgList):
filename = self.mImgList[currIndex]
if filename:
self.loadFile(filename)
def diritemDoubleClicked(self, item=None):
currIndex = self.mDirList.index(ustr(item.text()))
if currIndex < len(self.mDirList):
foldername = self.mDirList[currIndex]
if foldername:
self.defaultSaveDir_folder = os.path.join(self.defaultSaveDir, foldername)
self.importDirImages(os.path.join(self.lastOpenDir,foldername))
self.save_label.setText("Save DIR: " + self.defaultSaveDir_folder)
self.fileListWidget.setFocus(True)
# self.fileListWidget.setSelected(0)
###
def diritemChanged(self, item=None):
# QMessageBox.warning(self, u'changed', msg, yes | no)
# self.savebtn_label.setText('Not saved')
# self.savebtn_label.setStyleSheet('color: red')
# if item.text() in self.checkList:
# self.checkList.remove(item.text())
# else:
# insort(self.checkList, item.text())
# self.savebtncnt_label.setText('{0}/{1}'.format(len(self.checkList), self.foldercnt))
###
with self.lmdb.begin(write=True) as txn:
flag = txn.put(item.text().encode('ascii'), "1".encode('ascii'), overwrite=False)
if flag:
self.checknum += 1
else:
# QMessageBox.warning(self, u'Duplicate', "Already checked")
txn.delete(item.text().encode('ascii'))
self.checknum -= 1
print("put: ",flag)
self.savebtncnt_label.setText('{0}/{1}'.format(self.checknum, self.foldercnt))
###
# def saveButtonClicked(self):
# self.savebtn_label.setText('')
# file = QFile(server_path + dataset + '/'+ self.logged_id + '.txt')
# if file.open(QFile.WriteOnly | QFile.Text):
# for check in self.checkList:
# file.write(bytearray(check + '\n', 'utf8'))
# file.close()
# print('saved')
# Add chris
def btnstate(self, item= None):
""" Function to handle difficult examples
Update on each object """
if not self.canvas.editing():
return
item = self.currentItem()
if not item: # If not selected Item, take the first one
item = self.labelList.item(self.labelList.count()-1)
difficult = self.diffcButton.isChecked()
try:
shape = self.itemsToShapes[item]
except:
pass
# Checked and Update
try:
if difficult != shape.difficult:
shape.difficult = difficult
self.setDirty()
else: # User probably changed item visibility
self.canvas.setShapeVisible(shape, item.checkState() == Qt.Checked)
except:
pass
# React to canvas signals.
def shapeSelectionChanged(self, selected=False):
if self._noSelectionSlot:
self._noSelectionSlot = False
else:
shape = self.canvas.selectedShape
if shape:
self.shapesToItems[shape].setSelected(True)
else:
self.labelList.clearSelection()
self.actions.delete.setEnabled(selected)
self.actions.copy.setEnabled(selected)
self.actions.edit.setEnabled(selected)
self.actions.shapeLineColor.setEnabled(selected)
self.actions.shapeFillColor.setEnabled(selected)
def addLabel(self, shape):
item = HashableQListWidgetItem(shape.label)
item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
item.setCheckState(Qt.Checked)
item.setBackground(generateColorByText(shape.label))
self.itemsToShapes[item] = shape
self.shapesToItems[shape] = item
self.labelList.addItem(item)
self.canvas.itemsToShapes[item] = shape
self.canvas.shapesToItems[shape] = item
for action in self.actions.onShapesPresent:
action.setEnabled(True)
def remLabel(self, shape):
if shape is None:
# print('rm empty label')
return
item = self.shapesToItems[shape]
self.labelList.takeItem(self.labelList.row(item))
del self.shapesToItems[shape]
del self.itemsToShapes[item]
del self.canvas.shapesToItems[shape]
del self.canvas.itemsToShapes[item]
def loadLabels(self, shapes):
s = []
for label, points, line_color, fill_color, difficult in shapes:
shape = Shape(label=label)
for x, y in points:
shape.addPoint(QPointF(x, y))
shape.difficult = difficult
shape.close()
s.append(shape)
if line_color:
shape.line_color = QColor(*line_color)
else:
shape.line_color = generateColorByText(label)
if fill_color:
shape.fill_color = QColor(*fill_color)
else:
shape.fill_color = generateColorByText(label)
self.addLabel(shape)
self.canvas.loadShapes(s)
def saveLabels(self, annotationFilePath):
annotationFilePath = ustr(annotationFilePath)
if self.labelFile is None:
self.labelFile = LabelFile()
self.labelFile.verified = self.canvas.verified
def format_shape(s):
return dict(label=s.label,
line_color=s.line_color.getRgb(),
fill_color=s.fill_color.getRgb(),
points=[(p.x(), p.y()) for p in s.points],
# add chris
difficult = s.difficult)
shapes = [format_shape(shape) for shape in self.canvas.shapes]
# Can add differrent annotation formats here
try:
if self.usingPascalVocFormat is True:
print ('Img: ' + self.filePath + ' -> Its xml: ' + annotationFilePath)
self.labelFile.savePascalVocFormat(annotationFilePath, shapes, self.filePath, self.imageData,
self.lineColor.getRgb(), self.fillColor.getRgb())
else:
self.labelFile.save(annotationFilePath, shapes, self.filePath, self.imageData,
self.lineColor.getRgb(), self.fillColor.getRgb())
return True
except LabelFileError as e:
self.errorMessage(u'Error saving label data', u'<b>%s</b>' % e)
return False
def copySelectedShape(self):
self.addLabel(self.canvas.copySelectedShape())
# fix copy and delete
self.shapeSelectionChanged(True)
def labelSelectionChanged(self):
item = self.currentItem()
if item and self.canvas.editing():
self._noSelectionSlot = True
self.canvas.selectShape(self.itemsToShapes[item])
shape = self.itemsToShapes[item]
# Add Chris
self.diffcButton.setChecked(shape.difficult)
def labelItemChanged(self, item):
shape = self.itemsToShapes[item]
label = item.text()
if label != shape.label:
shape.label = item.text()
shape.line_color = generateColorByText(shape.label)
self.setDirty()
else: # User probably changed item visibility
self.canvas.setShapeVisible(shape, item.checkState() == Qt.Checked)
# Callback functions:
def newShape(self):
"""Pop-up and give focus to the label editor.
position MUST be in global coordinates.
"""
if not self.useDefaultLabelCheckbox.isChecked() or not self.defaultLabelTextLine.text():
if len(self.labelHist) > 0:
self.labelDialog = LabelDialog(
parent=self, listItem=self.labelHist)
# Sync single class mode from PR#106
if self.singleClassMode.isChecked() and self.lastLabel:
text = self.lastLabel
else:
text = self.labelDialog.popUp(text=self.prevLabelText)
self.lastLabel = text
else:
text = self.defaultLabelTextLine.text()
# Add Chris
self.diffcButton.setChecked(False)
if text is not None:
self.prevLabelText = text
generate_color = generateColorByText(text)
shape = self.canvas.setLastLabel(text, generate_color, generate_color)
self.addLabel(shape)
if self.beginner(): # Switch to edit mode.
self.canvas.setEditing(True)
self.actions.create.setEnabled(True)
else:
self.actions.editMode.setEnabled(True)
self.setDirty()
if text not in self.labelHist:
self.labelHist.append(text)
else:
# self.canvas.undoLastLine()
self.canvas.resetAllLines()
def scrollRequest(self, delta, orientation):
units = - delta / (8 * 15)
bar = self.scrollBars[orientation]
bar.setValue(bar.value() + bar.singleStep() * units)
def setZoom(self, value):
self.actions.fitWidth.setChecked(False)
self.actions.fitWindow.setChecked(False)
self.zoomMode = self.MANUAL_ZOOM
self.zoomWidget.setValue(value)
def addZoom(self, increment=10):
self.setZoom(self.zoomWidget.value() + increment)
def zoomRequest(self, delta):
# get the current scrollbar positions
# calculate the percentages ~ coordinates
h_bar = self.scrollBars[Qt.Horizontal]
v_bar = self.scrollBars[Qt.Vertical]
# get the current maximum, to know the difference after zooming
h_bar_max = h_bar.maximum()
v_bar_max = v_bar.maximum()
# get the cursor position and canvas size
# calculate the desired movement from 0 to 1
# where 0 = move left
# 1 = move right
# up and down analogous
cursor = QCursor()
pos = cursor.pos()
relative_pos = QWidget.mapFromGlobal(self, pos)
cursor_x = relative_pos.x()
cursor_y = relative_pos.y()
w = self.scrollArea.width()
h = self.scrollArea.height()
# the scaling from 0 to 1 has some padding
# you don't have to hit the very leftmost pixel for a maximum-left movement
margin = 0.1
move_x = (cursor_x - margin * w) / (w - 2 * margin * w)
move_y = (cursor_y - margin * h) / (h - 2 * margin * h)
# clamp the values from 0 to 1
move_x = min(max(move_x, 0), 1)
move_y = min(max(move_y, 0), 1)
# zoom in
units = delta / (8 * 15)
scale = 10
self.addZoom(scale * units)
# get the difference in scrollbar values
# this is how far we can move
d_h_bar_max = h_bar.maximum() - h_bar_max
d_v_bar_max = v_bar.maximum() - v_bar_max
# get the new scrollbar values
new_h_bar_value = h_bar.value() + move_x * d_h_bar_max
new_v_bar_value = v_bar.value() + move_y * d_v_bar_max
h_bar.setValue(new_h_bar_value)
v_bar.setValue(new_v_bar_value)
def setFitWindow(self, value=True):
if value:
self.actions.fitWidth.setChecked(False)
self.zoomMode = self.FIT_WINDOW if value else self.MANUAL_ZOOM
self.adjustScale()
def setFitWidth(self, value=True):
if value:
self.actions.fitWindow.setChecked(False)
self.zoomMode = self.FIT_WIDTH if value else self.MANUAL_ZOOM
self.adjustScale()
def togglePolygons(self, value):
for item, shape in self.itemsToShapes.items():
item.setCheckState(Qt.Checked if value else Qt.Unchecked)
def loadFile(self, filePath=None):
"""Load the specified file, or the last opened file if None."""
self.resetState()
self.canvas.setEnabled(False)
if filePath is None:
filePath = self.settings.get(SETTING_FILENAME)
# Make sure that filePath is a regular python string, rather than QString
filePath = str(filePath)
unicodeFilePath = ustr(filePath)
# Tzutalin 20160906 : Add file list and dock to move faster
# Highlight the file item
if unicodeFilePath and self.fileListWidget.count() > 0:
index = self.mImgList.index(unicodeFilePath)
fileWidgetItem = self.fileListWidget.item(index)
fileWidgetItem.setSelected(True)
if unicodeFilePath and os.path.exists(unicodeFilePath):
if LabelFile.isLabelFile(unicodeFilePath):
try:
self.labelFile = LabelFile(unicodeFilePath)
except LabelFileError as e:
self.errorMessage(u'Error opening file',
(u"<p><b>%s</b></p>"
u"<p>Make sure <i>%s</i> is a valid label file.")
% (e, unicodeFilePath))
self.status("Error reading %s" % unicodeFilePath)
return False
self.imageData = self.labelFile.imageData
self.lineColor = QColor(*self.labelFile.lineColor)
self.fillColor = QColor(*self.labelFile.fillColor)
else:
# Load image:
# read data first and store for saving into label file.
self.imageData = read(unicodeFilePath, None)
self.labelFile = None
image = QImage.fromData(self.imageData)
if image.isNull():
self.errorMessage(u'Error opening file',
u"<p>Make sure <i>%s</i> is a valid image file." % unicodeFilePath)
self.status("Error reading %s" % unicodeFilePath)
return False
self.status("Loaded %s" % os.path.basename(unicodeFilePath))
self.image = image
self.filePath = unicodeFilePath
self.canvas.loadPixmap(QPixmap.fromImage(image))
if self.labelFile:
self.loadLabels(self.labelFile.shapes)
self.setClean()
self.canvas.setEnabled(True)
self.adjustScale(initial=True)
self.paintCanvas()
self.addRecentFile(self.filePath)
self.toggleActions(True)
bsucces = True
# Label xml file and show bound box according to its filename
if self.usingPascalVocFormat is True:
if self.defaultSaveDir_folder is not None:
basename = os.path.basename(
os.path.splitext(self.filePath)[0]) + XML_EXT
xmlPath = os.path.join(self.defaultSaveDir_folder, basename)
bsucces = self.loadPascalXMLByFilename(xmlPath)
else:
xmlPath = os.path.splitext(filePath)[0] + XML_EXT
if os.path.isfile(xmlPath):
bsucces = self.loadPascalXMLByFilename(xmlPath)
if bsucces is False:
self.anno_label.setText("")
self.diffcButton.setChecked(False)
self.old_Filepath = str(self.old_Filepath)
self.old_Filepath = ustr(self.old_Filepath)
# print("old: ",self.old_Filepath)
basename_old = os.path.basename(
os.path.splitext(self.old_Filepath)[0]) + XML_EXT
xmlPath_old = os.path.join(self.defaultSaveDir_folder, basename_old)
bsucces = self.loadPascalXMLByFilename(xmlPath_old, False)
self.diffcButton.setChecked(False)
if bsucces is True:
self.actions.save.setEnabled(True)
else:
self.anno_label.setText(xmlPath)
self.anno_label.setStyleSheet('color: red')
self.setWindowTitle(__appname__ + ' ' + filePath)
# Default : select last item if there is at least one item
if self.labelList.count():
self.labelList.setCurrentItem(self.labelList.item(self.labelList.count()-1))
self.labelList.item(self.labelList.count()-1).setSelected(True)
self.canvas.setFocus(True)
return True
return False
def resizeEvent(self, event):
if self.canvas and not self.image.isNull()\
and self.zoomMode != self.MANUAL_ZOOM:
self.adjustScale()
super(MainWindow, self).resizeEvent(event)
def paintCanvas(self):
assert not self.image.isNull(), "cannot paint null image"
self.canvas.scale = 0.01 * self.zoomWidget.value()
self.canvas.adjustSize()
self.canvas.update()
def adjustScale(self, initial=False):
value = self.scalers[self.FIT_WINDOW if initial else self.zoomMode]()
self.zoomWidget.setValue(int(100 * value))
def scaleFitWindow(self):
"""Figure out the size of the pixmap in order to fit the main widget."""
e = 2.0 # So that no scrollbars are generated.
w1 = self.centralWidget().width() - e
h1 = self.centralWidget().height() - e
a1 = w1 / h1
# Calculate a new scale value based on the pixmap's aspect ratio.
w2 = self.canvas.pixmap.width() - 0.0
h2 = self.canvas.pixmap.height() - 0.0
a2 = w2 / h2
return w1 / w2 if a2 >= a1 else h1 / h2
def scaleFitWidth(self):
# The epsilon does not seem to work too well here.
w = self.centralWidget().width() - 2.0
return w / self.canvas.pixmap.width()
def closeEvent(self, event):
if not self.mayContinue():
event.ignore()
settings = self.settings
# If it loads images from dir, don't load it at the begining
if self.dirname is None:
settings[SETTING_FILENAME] = self.filePath if self.filePath else ''
else:
settings[SETTING_FILENAME] = ''
settings[SETTING_WIN_SIZE] = self.size()
settings[SETTING_WIN_POSE] = self.pos()
settings[SETTING_WIN_STATE] = self.saveState()
settings[SETTING_LINE_COLOR] = self.lineColor
settings[SETTING_FILL_COLOR] = self.fillColor
settings[SETTING_RECENT_FILES] = self.recentFiles
settings[SETTING_ADVANCE_MODE] = not self._beginner
if self.defaultSaveDir and os.path.exists(self.defaultSaveDir):
settings[SETTING_SAVE_DIR] = ustr(self.defaultSaveDir)
else:
settings[SETTING_SAVE_DIR] = ""
if self.lastOpenDir and os.path.exists(self.lastOpenDir):
settings[SETTING_LAST_OPEN_DIR] = self.lastOpenDir
else:
settings[SETTING_LAST_OPEN_DIR] = ""
settings[SETTING_AUTO_SAVE] = self.autoSaving.isChecked()
settings[SETTING_SINGLE_CLASS] = self.singleClassMode.isChecked()
settings.save()
## User Dialogs ##
def loadRecent(self, filename):
if self.mayContinue():
self.loadFile(filename)
def scanAllImages(self, folderPath):
extensions = ['.jpeg', '.jpg', '.png', '.bmp']
images = []
for root, dirs, files in os.walk(folderPath):
for file in files:
if file.lower().endswith(tuple(extensions)):
relativePath = os.path.join(root, file)
path = ustr(os.path.abspath(relativePath))
images.append(path)
images.sort(key=lambda x: x.lower())
return images
def scanAllDirs(self, folderPath):
pre_dirs = os.listdir(folderPath)
# for root, dirs, files in os.walk(folderPath):
# for file in files:
# if file.lower().endswith(tuple(extensions)):
# relativePath = os.path.join(root, file)
# path = ustr(os.path.abspath(relativePath))
# images.append(path)
pre_dirs.sort(key=lambda x: x.lower())
return pre_dirs
def changeSavedirDialog(self, _value=False):
if self.defaultSaveDir is not None:
path = ustr(self.defaultSaveDir)
else:
path = '.'
dirpath = ustr(QFileDialog.getExistingDirectory(self,
'%s - Save annotations to the directory' % __appname__, path, QFileDialog.ShowDirsOnly
| QFileDialog.DontResolveSymlinks))
self.save_label.setText("Save DIR: " + dirpath)
if dirpath is not None and len(dirpath) > 1:
self.defaultSaveDir = dirpath
self.statusBar().showMessage('%s . Annotation will be saved to %s' %
('Change saved folder', self.defaultSaveDir))
self.statusBar().show()
def openAnnotationDialog(self, _value=False):
if self.filePath is None:
self.statusBar().showMessage('Please select image first')
self.statusBar().show()
return
path = os.path.dirname(ustr(self.filePath))\
if self.filePath else '.'
if self.usingPascalVocFormat:
filters = "Open Annotation XML file (%s)" % ' '.join(['*.xml'])
filename = ustr(QFileDialog.getOpenFileName(self,'%s - Choose a xml file' % __appname__, path, filters))
if filename:
if isinstance(filename, (tuple, list)):
filename = filename[0]
self.loadPascalXMLByFilename(filename)
def openDirDialog(self, _value=False, dirpath=None):
if not self.mayContinue():
return
defaultOpenDirPath = dirpath if dirpath else '.'
if self.lastOpenDir and os.path.exists(self.lastOpenDir):
defaultOpenDirPath = self.lastOpenDir
else:
defaultOpenDirPath = os.path.dirname(self.filePath) if self.filePath else '.'
targetDirPath = ustr(QFileDialog.getExistingDirectory(self,
'%s - Open Directory' % __appname__, defaultOpenDirPath,
QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks))
self.importDirs(targetDirPath)
def importJobs(self, envpath):
envpath = server_path + envpath.split("/")[-1]
self.lmdb=lmdb.open(os.path.join(envpath,self.logged_id))
return json.load(open(os.path.join(envpath,"job_assign.json")))
def importDirs(self, dirpath):
if not self.mayContinue() or not dirpath:
return
self.lastOpenDir = dirpath
# self.dirname = dirpath
# self.filePath = None
job_dict = self.importJobs(dirpath)
# print(job_dict)
###
# job_list = list(chain(job_list))
# job_list = job_dict.values()
# job_list = [k for j in job_list for k in j]
# print(job_list)
job_list = self.verJobList
with self.lmdb.begin() as txn:
cursor = txn.cursor()
for key, value in cursor:
# print(key.decode('ascii'), value.decode('ascii'))
insort(self.checkList, key.decode('ascii'))
self.checknum = len(self.checkList)
self.folderListWidget.clear()
self.mDirList = self.scanAllDirs(dirpath)
# self.openNextImg()
###
for dirPath in self.mDirList:
if dirPath in job_list:
self.foldercnt += 1
item = QListWidgetItem(dirPath)
item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
if item.text() in self.checkList:
item.setCheckState(Qt.Checked)
else:
item.setCheckState(Qt.Unchecked)
self.folderListWidget.addItem(item)
self.savebtncnt_label.setText('{0}/{1}'.format(len(self.checkList), self.foldercnt))
self.edit_label.setText("Edit DIR: " + dirpath)
def importDirImages(self, dirpath):
if not self.mayContinue() or not dirpath:
return
# self.lastOpenDir = dirpath
self.dirname = dirpath
self.filePath = None
self.fileListWidget.clear()
self.mImgList = self.scanAllImages(dirpath)
self.openNextImg()
self.fileListWidget.setFocus(True)
for imgPath in self.mImgList:
item = QListWidgetItem(imgPath)
self.fileListWidget.addItem(item)
self.edit_label.setText("Edit DIR: " + dirpath)
def verifyImg(self, _value=False):
# Proceding next image without dialog if having any label
if self.filePath is not None:
try:
self.labelFile.toggleVerify()
except AttributeError:
# If the labelling file does not exist yet, create if and
# re-save it with the verified attribute.
self.saveFile()
self.labelFile.toggleVerify()
self.canvas.verified = self.labelFile.verified
self.paintCanvas()
self.saveFile()
def openPrevImg(self, _value=False):
# Proceding prev image without dialog if having any label
if self.autoSaving.isChecked():
if self.defaultSaveDir is not None:
if self.dirty is True:
self.saveFile()
else:
self.changeSavedirDialog()
return
if not self.mayContinue():
return
if len(self.mImgList) <= 0:
return
if self.filePath is None:
return
currIndex = self.mImgList.index(self.filePath)
if currIndex - 1 >= 0:
filename = self.mImgList[currIndex - 1]
if filename:
self.loadFile(filename)
def openNextImg(self, _value=False):
# Proceding prev image without dialog if having any label
if self.autoSaving.isChecked():
if self.defaultSaveDir is not None:
if self.dirty is True:
self.saveFile()
else:
self.changeSavedirDialog()
return
if not self.mayContinue():
return
if len(self.mImgList) <= 0:
return
# print("now ", self.filePath)
self.old_Filepath=self.filePath
filename = None
if self.filePath is None:
filename = self.mImgList[0]
else:
currIndex = self.mImgList.index(self.filePath)
if currIndex + 1 < len(self.mImgList):
filename = self.mImgList[currIndex + 1]
if filename:
self.loadFile(filename)
def openFile(self, _value=False):
if not self.mayContinue():
return
path = os.path.dirname(ustr(self.filePath)) if self.filePath else '.'
formats = ['*.%s' % fmt.data().decode("ascii").lower() for fmt in QImageReader.supportedImageFormats()]
filters = "Image & Label files (%s)" % ' '.join(formats + ['*%s' % LabelFile.suffix])
filename = QFileDialog.getOpenFileName(self, '%s - Choose Image or Label file' % __appname__, path, filters)
if filename:
if isinstance(filename, (tuple, list)):
filename = filename[0]
self.loadFile(filename)
def saveFile(self, _value=False):
if self.defaultSaveDir_folder is not None and len(ustr(self.defaultSaveDir_folder)):
if self.filePath:
imgFileName = os.path.basename(self.filePath)
savedFileName = os.path.splitext(imgFileName)[0] + XML_EXT
savedPath = os.path.join(ustr(self.defaultSaveDir_folder), savedFileName)
self._saveFile(savedPath)
else:
imgFileDir = os.path.dirname(self.filePath)
imgFileName = os.path.basename(self.filePath)
savedFileName = os.path.splitext(imgFileName)[0] + XML_EXT
savedPath = os.path.join(imgFileDir, savedFileName)
self._saveFile(savedPath if self.labelFile
else self.saveFileDialog())
def saveFileAs(self, _value=False):
assert not self.image.isNull(), "cannot save empty image"
self._saveFile(self.saveFileDialog())
def saveFileDialog(self):
caption = '%s - Choose File' % __appname__
filters = 'File (*%s)' % LabelFile.suffix
openDialogPath = self.currentPath()
dlg = QFileDialog(self, caption, openDialogPath, filters)
dlg.setDefaultSuffix(LabelFile.suffix[1:])
dlg.setAcceptMode(QFileDialog.AcceptSave)
filenameWithoutExtension = os.path.splitext(self.filePath)[0]
dlg.selectFile(filenameWithoutExtension)
dlg.setOption(QFileDialog.DontUseNativeDialog, False)
if dlg.exec_():
return dlg.selectedFiles()[0]
return ''
def _saveFile(self, annotationFilePath):
if annotationFilePath and self.saveLabels(annotationFilePath):
self.setClean()
self.statusBar().showMessage('Saved to %s' % annotationFilePath)
self.statusBar().show()
def closeFile(self, _value=False):
if not self.mayContinue():
return
self.resetState()
self.setClean()
self.toggleActions(False)
self.canvas.setEnabled(False)
self.actions.saveAs.setEnabled(False)
def resetAll(self):
self.settings.reset()
self.close()
proc = QProcess()
proc.startDetached(os.path.abspath(__file__))
def mayContinue(self):
return not (self.dirty and not self.discardChangesDialog())
def discardChangesDialog(self):
yes, no = QMessageBox.Yes, QMessageBox.No
msg = u'You have unsaved changes, proceed anyway?'
return yes == QMessageBox.warning(self, u'Attention', msg, yes | no)
def errorMessage(self, title, message):
return QMessageBox.critical(self, title,
'<p><b>%s</b></p>%s' % (title, message))
def currentPath(self):
return os.path.dirname(self.filePath) if self.filePath else '.'
def chooseColor1(self):
color = self.colorDialog.getColor(self.lineColor, u'Choose line color',
default=DEFAULT_LINE_COLOR)
if color:
self.lineColor = color
Shape.line_color = color
self.canvas.setDrawingColor(color)
self.canvas.update()
self.setDirty()
def deleteSelectedShape(self):
self.remLabel(self.canvas.deleteSelected())
self.setDirty()
if self.noShapes():
for action in self.actions.onShapesPresent:
action.setEnabled(False)
def chshapeLineColor(self):
color = self.colorDialog.getColor(self.lineColor, u'Choose line color',
default=DEFAULT_LINE_COLOR)
if color:
self.canvas.selectedShape.line_color = color
self.canvas.update()
self.setDirty()
def chshapeFillColor(self):
color = self.colorDialog.getColor(self.fillColor, u'Choose fill color',
default=DEFAULT_FILL_COLOR)
if color:
self.canvas.selectedShape.fill_color = color
self.canvas.update()
self.setDirty()
def copyShape(self):
self.canvas.endMove(copy=True)
self.addLabel(self.canvas.selectedShape)
self.setDirty()
def moveShape(self):
self.canvas.endMove(copy=False)
self.setDirty()
def loadPredefinedClasses(self, predefClassesFile):
if os.path.exists(predefClassesFile) is True:
with codecs.open(predefClassesFile, 'r', 'utf8') as f:
for line in f:
line = line.strip()
if self.labelHist is None:
self.labelHist = [line]
else:
self.labelHist.append(line)
def loadPascalXMLByFilename(self, xmlPath, current=True):
if self.filePath is None:
return False
if os.path.isfile(xmlPath) is False:
return False
tVocParseReader = PascalVocReader(xmlPath)
shapes = tVocParseReader.getShapes()
self.loadLabels(shapes)
if current:
self.canvas.verified = tVocParseReader.verified
else:
self.canvas.verified = False
return True
def inverted(color):
return QColor(*[255 - v for v in color.getRgb()])
def read(filename, default=None):
try:
with open(filename, 'rb') as f:
return f.read()
except:
return default
def get_main_app(argv=[]):
"""
Standard boilerplate Qt application code.
Do everything but app.exec_() -- so that we can test the application in one thread
"""
app = QApplication(argv)
app.setApplicationName(__appname__)
app.setWindowIcon(newIcon("app"))
login = Login()
# Tzutalin 201705+: Accept extra agruments to change predefined class file
# Usage : labelImg.py image predefClassFile
if login.exec_() == QDialog.Accepted:
# win = MainWindow(login.logged_id,argv[1] if len(argv) >= 2 else None,
# argv[2] if len(argv) >= 3 else os.path.join(
# os.path.dirname(sys.argv[0]),
# 'data', 'predefined_classes.txt'))
win = MainWindow(login.logged_id)
# win.logged_id=login.logged_id
win.show()
return app, win
else:
sys.exit()
def main(argv=[]):
'''construct main app and run it'''
app, _win = get_main_app(argv)
return app.exec_()
if __name__ == '__main__':
sys.exit(main(sys.argv))
|
the-stack_0_14719 | # -*- coding: utf-8 -*
import serial
import time
ser = serial.Serial("/dev/ttyS0", 115200)
def getTFminiData():
while True:
#time.sleep(0.1)
count = ser.in_waiting
if count > 8:
recv = ser.read(9)
ser.reset_input_buffer()
# type(recv), 'str' in python2(recv[0] = 'Y'), 'bytes' in python3(recv[0] = 89)
# type(recv[0]), 'str' in python2, 'int' in python3
if recv[0] == 0x59 and recv[1] == 0x59: #python3
distance = recv[2] + recv[3] * 256
strength = recv[4] + recv[5] * 256
print('(', distance, ',', strength, ')')
ser.reset_input_buffer()
if recv[0] == 'Y' and recv[1] == 'Y': #python2
lowD = int(recv[2].encode('hex'), 16)
highD = int(recv[3].encode('hex'), 16)
lowS = int(recv[4].encode('hex'), 16)
highS = int(recv[5].encode('hex'), 16)
distance = lowD + highD * 256
strength = lowS + highS * 256
print(distance, strength)
# you can also distinguish python2 and python3:
#import sys
#sys.version[0] == '2' #True, python2
#sys.version[0] == '3' #True, python3
if __name__ == '__main__':
try:
if ser.is_open == False:
ser.open()
getTFminiData()
except KeyboardInterrupt: # Ctrl+C
if ser != None:
ser.close()
|
the-stack_0_14720 | from pydantic import BaseModel, validator, Field
from typing import List, Dict
from datetime import datetime
class Agents(BaseModel):
name: str
integration: str
id: str
class CampaignTasksOut(BaseModel):
name: str
scheduled_date: str
start_date: str = None
end_date: str = None
agents: List[Agents]
dependencies: List[str]
state: str
@validator('scheduled_date', pre=True, always=True)
def _get_scheduled_date(cls, v):
return str(datetime.fromtimestamp(v['$date']/1000))
@validator('start_date', pre=True, always=True)
def _get_start_date(cls, v):
return None if not v else str(datetime.fromtimestamp(v['$date']/1000))
@validator('end_date', pre=True, always=True)
def _get_end_date(cls, v):
return None if not v else str(datetime.fromtimestamp(v['$date']/1000))
class CampaignsOut(BaseModel):
id: str = Field(None, alias='_id')
group_id: str
name: str
saved_date: str
tasks: List[CampaignTasksOut]
@validator('id', pre=True, always=True)
def _get_id(cls, v):
return v['$oid']
@validator('saved_date', pre=True, always=True)
def _get_saved_date(cls, v):
return str(datetime.fromtimestamp(v['$date']/1000))
# Data input
class CommandIn(BaseModel):
reference: str = None
reference_name: str = None
technique_name: str = None
kill_chain_phase: str = None
technique_id: str = None
category: str
integration: str
module: str
input: Dict
sleep: str = 1
class DependencyIn(BaseModel):
source: str
destination: str
class CampaignTaskIn(BaseModel):
name: str
sleep: int
scheduled_date: datetime = None
commands: List[CommandIn]
agents: List[Agents]
@validator('scheduled_date', pre=True, always=True)
def _set_date(cls, v):
return v or datetime.now()
class CampaignIn(BaseModel):
name: str
tasks: List[CampaignTaskIn]
dependencies: List[DependencyIn]
# Filtered values for denormalization
class CampaignTaskDenomIn(BaseModel):
name: str
scheduled_date: datetime = None
agents: List[Agents]
@validator('scheduled_date', pre=True, always=True)
def _set_date(cls, v):
return v or datetime.now()
class CampaignDenomIn(BaseModel):
name: str
group_id: str
tasks: List[CampaignTaskDenomIn]
dependencies: List[DependencyIn]
class CreateCampaignTasksOut(BaseModel):
task: str
class ScheduledTasksOut(BaseModel):
agent: str
queue: List[str]
class CreateCampaignOut(BaseModel):
campaign: str
group_id: str
scheduled_tasks: List[ScheduledTasksOut]
|
the-stack_0_14725 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import argparse
import time
import torch
import torch.utils.data
import torch.optim as optim
import numpy as np
import math
import random
import os
import datetime
from optimization.training import train, evaluate
from utils.load_data import load_dataset
parser = argparse.ArgumentParser(description='PyTorch Discrete Normalizing flows')
parser.add_argument('-d', '--dataset', type=str, default='cifar10',
choices=['cifar10', 'imagenet32', 'imagenet64'],
metavar='DATASET',
help='Dataset choice.')
parser.add_argument('-nc', '--no_cuda', action='store_true', default=False,
help='disables CUDA training')
parser.add_argument('--manual_seed', type=int, help='manual seed, if not given resorts to random seed.')
parser.add_argument('-li', '--log_interval', type=int, default=20, metavar='LOG_INTERVAL',
help='how many batches to wait before logging training status')
parser.add_argument('--evaluate_interval_epochs', type=int, default=25,
help='Evaluate per how many epochs')
parser.add_argument('-od', '--out_dir', type=str, default='snapshots', metavar='OUT_DIR',
help='output directory for model snapshots etc.')
fp = parser.add_mutually_exclusive_group(required=False)
fp.add_argument('-te', '--testing', action='store_true', dest='testing',
help='evaluate on test set after training')
fp.add_argument('-va', '--validation', action='store_false', dest='testing',
help='only evaluate on validation set')
parser.set_defaults(testing=True)
# optimization settings
parser.add_argument('-e', '--epochs', type=int, default=2000, metavar='EPOCHS',
help='number of epochs to train (default: 2000)')
parser.add_argument('-es', '--early_stopping_epochs', type=int, default=300, metavar='EARLY_STOPPING',
help='number of early stopping epochs')
parser.add_argument('-bs', '--batch_size', type=int, default=96, metavar='BATCH_SIZE',
help='input batch size for training (default: 100)')
parser.add_argument('-lr', '--learning_rate', type=float, default=0.001, metavar='LEARNING_RATE',
help='learning rate')
parser.add_argument('--warmup', type=int, default=10,
help='number of warmup epochs')
parser.add_argument('--data_augmentation_level', type=int, default=2,
help='data augmentation level')
parser.add_argument('--variable_type', type=str, default='discrete',
help='variable type of data distribution: discrete/continuous',
choices=['discrete', 'continuous'])
parser.add_argument('--distribution_type', type=str, default='logistic',
choices=['logistic', 'normal', 'steplogistic'],
help='distribution type: logistic/normal')
parser.add_argument('--n_flows', type=int, default=8,
help='number of flows per level')
parser.add_argument('--n_levels', type=int, default=3,
help='number of levels')
parser.add_argument('--n_bits', type=int, default=8,
help='')
# ---------------- SETTINGS CONCERNING NETWORKS -------------
parser.add_argument('--densenet_depth', type=int, default=8,
help='Depth of densenets')
parser.add_argument('--n_channels', type=int, default=512,
help='number of channels in coupling and splitprior')
# ---------------- ----------------------------- -------------
# ---------------- SETTINGS CONCERNING COUPLING LAYERS -------------
parser.add_argument('--coupling_type', type=str, default='shallow',
choices=['shallow', 'resnet', 'densenet'],
help='Type of coupling layer')
parser.add_argument('--splitfactor', default=0, type=int,
help='Split factor for coupling layers.')
parser.add_argument('--split_quarter', dest='split_quarter', action='store_true',
help='Split coupling layer on quarter')
parser.add_argument('--no_split_quarter', dest='split_quarter', action='store_false')
parser.set_defaults(split_quarter=True)
# ---------------- ----------------------------------- -------------
# ---------------- SETTINGS CONCERNING SPLITPRIORS -------------
parser.add_argument('--splitprior_type', type=str, default='shallow',
choices=['none', 'shallow', 'resnet', 'densenet'],
help='Type of splitprior. Use \'none\' for no splitprior')
# ---------------- ------------------------------- -------------
# ---------------- SETTINGS CONCERNING PRIORS -------------
parser.add_argument('--n_mixtures', type=int, default=1,
help='number of mixtures')
# ---------------- ------------------------------- -------------
parser.add_argument('--hard_round', dest='hard_round', action='store_true',
help='Rounding of translation in discrete models. Weird '
'probabilistic implications, only for experimental phase')
parser.add_argument('--no_hard_round', dest='hard_round', action='store_false')
parser.set_defaults(hard_round=True)
parser.add_argument('--round_approx', type=str, default='smooth',
choices=['smooth', 'stochastic'])
parser.add_argument('--lr_decay', default=0.999, type=float,
help='Learning rate')
parser.add_argument('--temperature', default=1.0, type=float,
help='Temperature used for BackRound. It is used in '
'the the SmoothRound module. '
'(default=1.0')
# gpu/cpu
parser.add_argument('--gpu_num', type=int, default=0, metavar='GPU',
help='choose GPU to run on.')
args = parser.parse_args()
args.cuda = not args.no_cuda and torch.cuda.is_available()
if args.manual_seed is None:
args.manual_seed = random.randint(1, 100000)
random.seed(args.manual_seed)
torch.manual_seed(args.manual_seed)
np.random.seed(args.manual_seed)
kwargs = {'num_workers': 4, 'pin_memory': True} if args.cuda else {}
def run(args, kwargs):
print('\nMODEL SETTINGS: \n', args, '\n')
print("Random Seed: ", args.manual_seed)
if 'imagenet' in args.dataset and args.evaluate_interval_epochs > 5:
args.evaluate_interval_epochs = 5
# ==================================================================================================================
# SNAPSHOTS
# ==================================================================================================================
args.model_signature = str(datetime.datetime.now())[0:19].replace(' ', '_')
args.model_signature = args.model_signature.replace(':', '_')
snapshots_path = os.path.join(args.out_dir, args.variable_type + '_' + args.distribution_type + args.dataset)
snap_dir = snapshots_path
snap_dir += '_' + 'flows_' + str(args.n_flows) + '_levels_' + str(args.n_levels)
snap_dir = snap_dir + '__' + args.model_signature + '/'
args.snap_dir = snap_dir
if not os.path.exists(snap_dir):
os.makedirs(snap_dir)
with open(snap_dir + 'log.txt', 'a') as ff:
print('\nMODEL SETTINGS: \n', args, '\n', file=ff)
# SAVING
torch.save(args, snap_dir + '.config')
# ==================================================================================================================
# LOAD DATA
# ==================================================================================================================
train_loader, val_loader, test_loader, args = load_dataset(args, **kwargs)
# ==================================================================================================================
# SELECT MODEL
# ==================================================================================================================
# flow parameters and architecture choice are passed on to model through args
print(args.input_size)
import models.Model as Model
model = Model.Model(args)
args.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model.set_temperature(args.temperature)
model.enable_hard_round(args.hard_round)
model_sample = model
# ====================================
# INIT
# ====================================
# data dependend initialization on CPU
for batch_idx, (data, _) in enumerate(train_loader):
model(data)
break
if torch.cuda.device_count() > 1:
print("Let's use", torch.cuda.device_count(), "GPUs!")
model = torch.nn.DataParallel(model, dim=0)
model.to(args.device)
def lr_lambda(epoch):
return min(1., (epoch+1) / args.warmup) * np.power(args.lr_decay, epoch)
optimizer = optim.Adamax(model.parameters(), lr=args.learning_rate, eps=1.e-7)
scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda, last_epoch=-1)
# ==================================================================================================================
# TRAINING
# ==================================================================================================================
train_bpd = []
val_bpd = []
# for early stopping
best_val_bpd = np.inf
best_train_bpd = np.inf
epoch = 0
train_times = []
model.eval()
model.train()
for epoch in range(1, args.epochs + 1):
t_start = time.time()
scheduler.step()
tr_loss, tr_bpd = train(epoch, train_loader, model, optimizer, args)
train_bpd.append(tr_bpd)
train_times.append(time.time()-t_start)
print('One training epoch took %.2f seconds' % (time.time()-t_start))
if epoch < 25 or epoch % args.evaluate_interval_epochs == 0:
v_loss, v_bpd = evaluate(
train_loader, val_loader, model, model_sample, args,
epoch=epoch, file=snap_dir + 'log.txt')
val_bpd.append(v_bpd)
# Model save based on TRAIN performance (is heavily correlated with validation performance.)
if np.mean(tr_bpd) < best_train_bpd:
best_train_bpd = np.mean(tr_bpd)
best_val_bpd = v_bpd
torch.save(model, snap_dir + 'a.model')
torch.save(optimizer, snap_dir + 'a.optimizer')
print('->model saved<-')
print('(BEST: train bpd {:.4f}, test bpd {:.4f})\n'.format(
best_train_bpd, best_val_bpd))
if math.isnan(v_loss):
raise ValueError('NaN encountered!')
train_bpd = np.hstack(train_bpd)
val_bpd = np.array(val_bpd)
# training time per epoch
train_times = np.array(train_times)
mean_train_time = np.mean(train_times)
std_train_time = np.std(train_times, ddof=1)
print('Average train time per epoch: %.2f +/- %.2f' % (mean_train_time, std_train_time))
# ==================================================================================================================
# EVALUATION
# ==================================================================================================================
final_model = torch.load(snap_dir + 'a.model')
test_loss, test_bpd = evaluate(
train_loader, test_loader, final_model, final_model, args,
epoch=epoch, file=snap_dir + 'test_log.txt')
print('Test loss / bpd: %.2f / %.2f' % (test_loss, test_bpd))
if __name__ == "__main__":
run(args, kwargs)
|
the-stack_0_14727 | # using SendGrid's Python Library
# https://github.com/sendgrid/sendgrid-python
import sendgrid
import os
from sendgrid.helpers.mail import *
def notify_by_email(user, email):
sg = sendgrid.SendGridAPIClient(apikey=os.environ['SENDGRID_API_KEY'])
from_email = Email('[email protected]')
to_email = Email(email)
subject = 'You have not solved any problem on Leetcode for a day!'
content = Content('text/plain', open('email.txt').read().format(user=user))
mail = Mail(from_email, subject, to_email, content)
response = sg.client.mail.send.post(request_body=mail.get())
print("Sent email to %s\'s email %s. Status code: %d." % (user, email, response.status_code))
return response |
the-stack_0_14729 | from ..context import Context
from .base import BaseTag, tag_registry
class Compose(BaseTag):
'''
arguments: |
`value`: The value to apply tags on
`tags`: A list of tag names to apply, latest first
example: |
`!Base64,Var foo`
description: |
Used internally to implement tag composition.
Usually not used in the spelt-out form.
See _Tag composition_ below.
'''
value_types = (dict,)
def enrich(self, context: Context):
value = self.data.get('value')
for tag_name in reversed(self.data['tags']):
tag_class = tag_registry[tag_name]
value = tag_class(value)
return context.enrich(value)
|
the-stack_0_14730 | import numpy
from chainer.backends import cuda
from chainer.backends import intel64
from chainer import function_node
import chainer.functions
from chainer.graph_optimizations import static_code
from chainer.utils import type_check
class LinearFunction(function_node.FunctionNode):
_config_use_ideep = None
_supports_static_optimizations = True
def check_type_forward(self, in_types):
n_in = in_types.size()
type_check.expect(2 <= n_in, n_in <= 3)
x_type, w_type = in_types[:2]
type_check.argname((x_type, w_type), ('x', 'W'))
type_check.expect(
x_type.dtype.kind == 'f',
w_type.dtype.kind == 'f',
x_type.ndim == 2,
w_type.ndim == 2,
x_type.shape[1] == w_type.shape[1],
)
if type_check.eval(n_in) == 3:
b_type = in_types[2]
type_check.argname((b_type,), ('b',))
type_check.expect(
b_type.dtype == x_type.dtype,
b_type.ndim == 1,
b_type.shape[0] == w_type.shape[0],
)
@static_code
def static_linear_no_bias(self, xp, optimized, inputs, outputs):
x, W = inputs
y = outputs[0]
# NumPy raises an error when the array is not contiguous.
# See: https://github.com/chainer/chainer/issues/2744
# TODO(niboshi): Remove this code when NumPy is fixed.
if (isinstance(x, numpy.ndarray) and
not (x.flags.c_contiguous or x.flags.f_contiguous) and
1 in x.shape):
x = numpy.ascontiguousarray(x)
if optimized:
# Note: We can only call this function when both x and W
# have the same dtype. Otherwise, the output type (for y)
# may not be as expected (i.e., not the same dtype as x).
xp.dot(x, W.T, out=y)
else:
y[:] = x.dot(W.T).astype(x.dtype, copy=False)
@static_code
def static_add_bias(self, inputs, outputs):
bias = inputs[0]
y = outputs[0]
y += bias
def forward(self, inputs):
self._config_use_ideep = chainer.config.use_ideep
if (intel64.should_use_ideep('>=auto')
and intel64.inputs_all_ready(inputs)):
# iDeep implementation
return self._forward_ideep(inputs)
# Generic implementation
if len(inputs) == 3:
x, W, b = inputs
else:
(x, W), b = inputs, None
# NumPy raises an error when the array is not contiguous.
# See: https://github.com/chainer/chainer/issues/2744
# TODO(niboshi): Remove this code when NumPy is fixed.
if (isinstance(x, numpy.ndarray) and
not (x.flags.c_contiguous or x.flags.f_contiguous) and
1 in x.shape):
x = numpy.ascontiguousarray(x)
# In order to be compatible with the "static graph" feature, it is
# required that all output arrays of this forward
# function be allocated explicitly:
xp = cuda.get_array_module(x)
y = xp.empty((x.shape[0], W.shape[0])).astype(x.dtype)
# This is required because all of the "static_*()" functions
# use the convention that any output arrays are supplied
# as input arguments to the function. That is because it is
# not allowed for a "static_*()" function to return anything
# other than `None`. The reason is to prevent dynamic allocation
# of output arrays during execution of the static schedule
# because it would break the model.
self.static_linear_no_bias(xp, x.dtype == W.dtype, inputs=[x, W],
outputs=[y])
if len(inputs) == 3:
self.static_add_bias(inputs=[b], outputs=[y])
self.retain_inputs((0, 1)) # b is not retained
return y,
def _forward_ideep(self, inputs):
if len(inputs) == 3:
x, W, b = inputs
else:
(x, W), b = inputs, None
y = intel64.ideep.linear.Forward(
intel64.ideep.array(x),
intel64.ideep.array(W),
intel64.ideep.array(b) if b is not None else None)
self.retain_inputs((0, 1))
return y,
def backward(self, indexes, grad_outputs):
x, W = self.get_retained_inputs()
gy, = grad_outputs
ret = []
with chainer.using_config('use_ideep', self._config_use_ideep):
if 0 in indexes:
gx, = LinearGradData().apply((W, gy))
ret.append(chainer.functions.cast(gx, x.dtype))
if 1 in indexes:
gW, = LinearGradWeight(W.dtype).apply((x, gy))
ret.append(chainer.functions.cast(gW, W.dtype))
if 2 in indexes:
gb = chainer.functions.sum(gy, axis=0)
ret.append(gb)
return ret
class LinearGradData(function_node.FunctionNode):
_config_use_ideep = None
def forward(self, inputs):
self._config_use_ideep = chainer.config.use_ideep
if (intel64.should_use_ideep('>=auto')
and intel64.inputs_all_ready(inputs)):
# iDeep implementation
return self._forward_ideep(inputs)
# Generic implementation
self.retain_inputs((0, 1))
W, gy = inputs
if (isinstance(gy, numpy.ndarray) and
not (gy.flags.c_contiguous or gy.flags.f_contiguous) and
1 in gy.shape):
gy = numpy.ascontiguousarray(gy)
gx = gy.dot(W).astype(gy.dtype, copy=False)
return gx,
def _forward_ideep(self, inputs):
self.retain_inputs((0, 1))
W, gy = inputs
gx = intel64.ideep.linear.BackwardData(
intel64.ideep.array(W),
intel64.ideep.array(gy))
return gx,
def backward(self, indexes, grad_outputs):
W, gy = self.get_retained_inputs()
ggx, = grad_outputs
ret = []
with chainer.using_config('use_ideep', self._config_use_ideep):
if 0 in indexes:
gw, = LinearGradWeight(W.dtype).apply((ggx, gy))
ret.append(chainer.functions.cast(gw, W.dtype))
if 1 in indexes:
ggy = linear(ggx, W)
ret.append(chainer.functions.cast(ggy, gy.dtype))
return ret
class LinearGradWeight(function_node.FunctionNode):
_config_use_ideep = None
def __init__(self, w_dtype):
self._w_dtype = w_dtype
def forward(self, inputs):
self._config_use_ideep = chainer.config.use_ideep
if (intel64.should_use_ideep('>=auto')
and self._w_dtype == numpy.float32
and intel64.inputs_all_ready(inputs)):
# iDeep implementation
return self._forward_ideep(inputs)
# Generic implementation
self.retain_inputs((0, 1))
x, gy = inputs
if (isinstance(gy, numpy.ndarray) and
not (gy.flags.c_contiguous or gy.flags.f_contiguous) and
1 in gy.shape):
gy = numpy.ascontiguousarray(gy)
gW = gy.T.dot(x).astype(self._w_dtype, copy=False)
return gW,
def _forward_ideep(self, inputs):
self.retain_inputs((0, 1))
x, gy = inputs
gW = intel64.ideep.linear.BackwardWeights(
intel64.ideep.array(x),
intel64.ideep.array(gy))
return gW,
def backward(self, indexes, grad_outputs):
x, gy = self.get_retained_inputs()
ggW, = grad_outputs
ret = []
with chainer.using_config('use_ideep', self._config_use_ideep):
if 0 in indexes:
gx, = LinearGradData().apply((ggW, gy))
ret.append(chainer.functions.cast(gx, x.dtype))
if 1 in indexes:
ggy = linear(x, ggW)
ret.append(chainer.functions.cast(ggy, gy.dtype))
return ret
def linear(x, W, b=None, n_batch_axes=1):
"""Linear function, or affine transformation.
It accepts two or three arguments: an input minibatch ``x``, a weight
matrix ``W``, and optionally a bias vector ``b``. It computes
.. math:: Y = xW^\\top + b.
Args:
x (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \
:class:`cupy.ndarray`): Input variable, which is a :math:`(s_1, s_2, \
..., s_n)`-shaped float array. Its first ``n_batch_axes``
dimensions are handled as *minibatch dimensions*. The
other dimensions are handled as concatenated one dimension whose
size must be :math:`(s_{\\rm n\\_batch\\_axes} * ... * s_n = N)`.
W (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \
:class:`cupy.ndarray`): Weight variable of shape :math:`(M, N)`,
where :math:`(N = s_{\\rm n\\_batch\\_axes} * ... * s_n)`.
b (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \
:class:`cupy.ndarray`): Bias variable (optional) of shape
:math:`(M,)`.
n_batch_axes (int): The number of batch axes. The default is 1. The
input variable is reshaped into
(:math:`{\\rm n\\_batch\\_axes} + 1`)-dimensional tensor.
This should be greater than 0.
Returns:
~chainer.Variable: Output variable. A float array with shape
of :math:`(s_1, ..., s_{\\rm n\\_batch\\_axes}, M)`.
.. seealso:: :class:`~chainer.links.Linear`
.. admonition:: Example
>>> x = np.random.uniform(0, 1, (3, 4)).astype(np.float32)
>>> W = np.random.uniform(0, 1, (5, 4)).astype(np.float32)
>>> b = np.random.uniform(0, 1, (5,)).astype(np.float32)
>>> y = F.linear(x, W, b)
>>> y.shape
(3, 5)
"""
if n_batch_axes <= 0:
raise ValueError('n_batch_axes should be greater than 0.')
if n_batch_axes > 1:
batch_shape = x.shape[:n_batch_axes]
batch_size = numpy.prod(batch_shape)
x = x.reshape(batch_size, -1)
elif x.ndim > 2:
x = x.reshape(x.shape[0], -1)
if b is None:
args = x, W
else:
args = x, W, b
y, = LinearFunction().apply(args)
if n_batch_axes > 1:
y = y.reshape(batch_shape + (-1,))
return y
|
the-stack_0_14732 | from idm.objects import dp, Event
from idm.api_utils import get_msg_id
@dp.event_register('banGetReason')
def ban_get_reason(event: Event) -> str:
reply = {}
if event.obj['local_id'] != 0:
reply['reply_to'] = get_msg_id(
event.api, event.chat.peer_id, event.obj['local_id']
)
event.api.msg_op(1, event.chat.peer_id, event.obj['message'], **reply)
return "ok"
|
the-stack_0_14735 | """
Gaussian Kernel Expansion Diagram
---------------------------------
"""
# Author: Jake VanderPlas
# License: BSD
# The figure produced by this code is published in the textbook
# "Statistics, Data Mining, and Machine Learning in Astronomy" (2013)
# For more information, see http://astroML.github.com
# To report a bug or issue, use the following forum:
# https://groups.google.com/forum/#!forum/astroml-general
import numpy as np
from matplotlib import pyplot as plt
#----------------------------------------------------------------------
# This function adjusts matplotlib settings for a uniform feel in the textbook.
# Note that with usetex=True, fonts are rendered with LaTeX. This may
# result in an error if LaTeX is not installed on your system. In that case,
# you can set usetex to False.
from astroML.plotting import setup_text_plots
setup_text_plots(fontsize=8, usetex=True)
plt.figure(figsize=(5, 3.75), facecolor='w')
ax = plt.axes([0, 0, 1, 1], frameon=False, xticks=[], yticks=[])
ax.add_patch(plt.Rectangle((-0.5, -0.25), 0.8, 0.4,
fc='none', ec='k', lw=2))
ax.add_patch(plt.Rectangle((-1.75, 0.1), 0.8, 0.4,
fc='none', ec='k', lw=2, linestyle='dashed'))
ax.add_patch(plt.Rectangle((0.8, -0.55), 0.8, 0.4,
fc='none', ec='k', lw=2, linestyle='dashed'))
ax.add_patch(plt.Rectangle((-1.3, -0.95), 0.8, 0.4,
fc='none', ec='k', lw=2, linestyle='dashed'))
red_pts = np.array([[-0.163, 0.093],
[-0.123, -0.22],
[0.194, 0.035],
[0.146, -0.178],
[-0.387, -0.143]])
blue_pts = np.array([[-1.51, 0.17],
[-1.17, 0.36],
[-1.23, -0.68],
[-0.80, -0.83],
[1.28, -0.45],
[1.41, -0.26]])
x0 = -0.5 + 0.4
y0 = -0.25 + 0.2
ax.scatter(red_pts[:, 0], red_pts[:, 1], c='r')
ax.scatter(blue_pts[:, 0], blue_pts[:, 1], c='b')
ax.scatter([x0], [y0], c='gray')
for pt in blue_pts:
ax.annotate("", pt, (x0, y0), arrowprops=dict(arrowstyle='->',
linestyle='dashed'))
for i, pt in enumerate(red_pts):
ax.annotate("", pt, (x0, y0), arrowprops=dict(arrowstyle='<-'))
ax.text(pt[0] + 0.03, pt[1] + 0.03, '$r_{j%i}$' % (i + 1),
bbox=dict(boxstyle='round', ec='k', fc='w', alpha=0.7))
ax.annotate("R.c", (x0, y0), (0.2, 0.2),
arrowprops=dict(arrowstyle='-', color='gray'),
bbox=dict(boxstyle='round', ec='k', fc='w'))
ax.set_xlim(-1.9, 1.9)
ax.set_ylim(-1.2, 0.8)
plt.show()
|
the-stack_0_14737 | from __future__ import print_function
#
# cfg file to unpack RAW L1 GT DAQ data
# the options set in "user choices" file
# L1Trigger/GlobalTriggerAnalyzer/python/UserOptions.py
# V M Ghete 2009-04-03
# V M Ghete 2011-02-09 use UserOptions.py
import FWCore.ParameterSet.Config as cms
import sys
process = cms.Process("TestL1GtUnpacker")
print('\n')
from L1Trigger.GlobalTriggerAnalyzer.UserOptions_cff import *
if errorUserOptions == True :
print('\nError returned by UserOptions_cff\n')
sys.exit()
# source according to data type
if dataType == 'StreamFile' :
process.source = cms.Source("NewEventStreamFileReader", fileNames=readFiles)
else :
process.source = cms.Source ('PoolSource',
fileNames=readFiles,
secondaryFileNames=secFiles,
eventsToProcess = selectedEvents
)
# number of events to be processed and source file
process.maxEvents = cms.untracked.PSet(
input=cms.untracked.int32(maxNumberEvents)
)
# load and configure modules via Global Tag
# https://twiki.cern.ch/twiki/bin/view/CMS/SWGuideFrontierConditions
process.load("Configuration.StandardSequences.GeometryDB_cff")
process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff')
process.GlobalTag.globaltag = useGlobalTag
# L1 GT/GMT unpack
process.load("EventFilter.L1GlobalTriggerRawToDigi.l1GtUnpack_cfi")
# input tag for GT readout collection (before CMSSW_5_0_X)
# source = hardware record
#
#if useRelValSample == True :
# daqGtInputTag = 'rawDataCollector'
#else :
# daqGtInputTag = 'rawDataCollector'
daqGtInputTag = 'rawDataCollector'
process.l1GtUnpack.DaqGtInputTag = daqGtInputTag
#process.l1GtUnpack.DaqGtInputTag = 'l1GtTextToRaw'
# Active Boards Mask
# no board masked (default)
#process.l1GtUnpack.ActiveBoardsMask = 0xFFFF
# GTFE only in the record
#process.l1GtUnpack.ActiveBoardsMask = 0x0000
# GTFE + FDL
#process.l1GtUnpack.ActiveBoardsMask = 0x0001
# GTFE + GMT
#process.l1GtUnpack.ActiveBoardsMask = 0x0100
# GTFE + FDL + GMT
#process.l1GtUnpack.ActiveBoardsMask = 0x0101
# BxInEvent to be unpacked
# all available BxInEvent (default)
#process.l1GtUnpack.UnpackBxInEvent = -1
# BxInEvent = 0 (L1A)
#process.l1GtUnpack.UnpackBxInEvent = 1
# 3 BxInEvent (F, 0, 1)
#process.l1GtUnpack.UnpackBxInEvent = 3
# set it to verbose
process.l1GtUnpack.Verbosity = cms.untracked.int32(1)
#
# l1GtTrigReport module
#
process.load("L1Trigger.GlobalTriggerAnalyzer.l1GtTrigReport_cfi")
# boolean flag to select the input record
# if true, it will use L1GlobalTriggerRecord
#process.l1GtTrigReport.UseL1GlobalTriggerRecord = True
# input tag for GT record:
# GT emulator: gtDigis (DAQ record)
# GT unpacker: gtDigis (DAQ record)
# GT lite record: l1GtRecord
process.l1GtTrigReport.L1GtRecordInputTag = "l1GtUnpack"
#process.l1GtTrigReport.PrintVerbosity = 10
# print output: 0 = std::cout; 1 = LogTrace; 2 = LogVerbatim; 3 = LogInfo
#process.l1GtTrigReport.PrintOutput = 0
# path to be run
process.p = cms.Path(process.l1GtUnpack*process.l1GtTrigReport)
# Message Logger
process.load('FWCore.MessageService.MessageLogger_cfi')
process.MessageLogger.debugModules = ['l1GtUnpack', 'l1GtTrigReport']
process.MessageLogger.cerr.enable = False
process.MessageLogger.files.L1GtUnpacker_errors = cms.untracked.PSet(
threshold = cms.untracked.string('ERROR'),
ERROR = cms.untracked.PSet( limit = cms.untracked.int32(-1) ),
L1GlobalTriggerRawToDigi = cms.untracked.PSet( limit = cms.untracked.int32(-1) )
)
process.MessageLogger.files.L1GtUnpacker_warnings = cms.untracked.PSet(
threshold = cms.untracked.string('WARNING'),
WARNING = cms.untracked.PSet( limit = cms.untracked.int32(0) ),
ERROR = cms.untracked.PSet( limit = cms.untracked.int32(0) ),
L1GlobalTriggerRawToDigi = cms.untracked.PSet( limit = cms.untracked.int32(-1) )
)
process.MessageLogger.files.L1GtUnpacker_info = cms.untracked.PSet(
threshold = cms.untracked.string('INFO'),
INFO = cms.untracked.PSet( limit = cms.untracked.int32(0) ),
WARNING = cms.untracked.PSet( limit = cms.untracked.int32(0) ),
ERROR = cms.untracked.PSet( limit = cms.untracked.int32(0) ),
L1GtTrigReport = cms.untracked.PSet( limit = cms.untracked.int32(-1) )
)
process.MessageLogger.files.L1GtUnpacker = cms.untracked.PSet(
threshold = cms.untracked.string('DEBUG'),
DEBUG = cms.untracked.PSet( limit = cms.untracked.int32(0) ),
INFO = cms.untracked.PSet( limit = cms.untracked.int32(0) ),
WARNING = cms.untracked.PSet( limit = cms.untracked.int32(0) ),
ERROR = cms.untracked.PSet( limit = cms.untracked.int32(0) ),
L1GlobalTriggerRawToDigi = cms.untracked.PSet( limit = cms.untracked.int32(-1) )
)
# summary
process.options = cms.untracked.PSet(
wantSummary = cms.untracked.bool(True)
)
# output
process.outputL1GtUnpack = cms.OutputModule("PoolOutputModule",
fileName = cms.untracked.string('L1GtUnpacker.root'),
# keep only unpacked data in the ROOT file
outputCommands = cms.untracked.vstring('drop *',
'keep *_l1GtUnpack_*_*')
)
process.outpath = cms.EndPath(process.outputL1GtUnpack)
|
the-stack_0_14738 | # Train an agent from scratch with PPO2 and save package and learning graphs
# from OpenGL import GLU
import os
import glob
import time
import subprocess
import shutil
import gym
import wandb
import random
import logging
from collections import defaultdict
from gym_smartquad.envs import quad_env
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import customMonitor
import datetime
import imageio
from stable_baselines3.ppo import MlpPolicy
from stable_baselines3.common.vec_env import SubprocVecEnv, DummyVecEnv, VecNormalize, sync_envs_normalization
from stable_baselines3.common.callbacks import BaseCallback
from stable_baselines3.common.vec_env import VecFrameStack
from stable_baselines3.common.evaluation import evaluate_policy
from stable_baselines3 import PPO
from stable_baselines3.common.monitor import Monitor
from stable_baselines3.common.results_plotter import load_results, ts2xy
from stable_baselines3.common.cmd_util import make_vec_env
from stable_baselines3.common import logger
from tensorboard.backend.event_processing.event_accumulator import EventAccumulator
import json
class smartCurriculumCallback(BaseCallback):
"""
A custom callback that derives from ``BaseCallback``.
:param verbose: (int) Verbosity level 0: no output 1: info 2: debug
"""
def __init__(self, envFunct, refreshRate, betaRate, initCurriculum, endDomain, targetDomain, domainPowers, ADRMethod = 'ep_reward_mean',targetReliability=None, targetReward=None, renders = True, verbose=1):
super(smartCurriculumCallback, self).__init__(verbose)
self.refreshRate = refreshRate
self.evalRate = 100000
self.betaRate = betaRate
self.n_calls = 0
self.oldLoss = None
self.newLoss = None
self.oldStep = 0
self.oldEvalStep = 0
self.meanRew = 0
self.rewardScale = 700 #TO BE FULLY INTEGRATED
self.envFunct = envFunct
self.curriculum = initCurriculum
self.initCurriculum = initCurriculum
self.endDomain = endDomain
self.progress = 0
self.targetDomain = targetDomain
self.domainPowers = domainPowers
self.targetReliability = targetReliability
self.targetReward = targetReward
self.best_min = np.NINF
self.best_mean = np.NINF
self.ADRMethod = ADRMethod
self.n_eval_episodes = 15
self.evaluations_results = []
self.evaluations_mins = []
self.evaluations_timesteps = []
self.gif_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "tmp_gif/")
self.models_tmp_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "models_tmp/")
self.renders = renders
# Those variables will be accessible in the callback
# The RL model
# self.model = None # type: BaseRLModel
# An alias for self.model.get_env(), the environment used for training
# self.training_env = None # type: Union[gym.Env, VecEnv, None]
# Number of time the callback was called
# self.n_calls = 0 # type: int
# self.num_timesteps = 0 # type: int
# local and global variables
# self.locals = None # type: Dict[str, Any]
# self.globals = None # type: Dict[str, Any]
self.logger_dir = None
#self.logger_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "logger/")
#logger.make_output_format('csv', self.logger_dir, log_suffix = 'progresslog')
def _on_training_start(self) :
"""
This method is called before the first rollout starts.
"""
self.logger_dir = self.logger.get_dir() +'/'+ os.listdir(self.logger.get_dir())[0]
def _on_rollout_start(self) :
"""
A rollout is the collection of environment interaction
using the current policy.
This event is triggered before collecting new samples.
"""
pass
def _on_step(self) :
#Basic curriculum progression, every self.refreshRate timesteps
if self.num_timesteps-self.oldStep >= self.refreshRate :
self.oldStep = self.num_timesteps
print(self.num_timesteps)
#Loss based ADR
if self.ADRMethod == 'loss':
self.lossMethod()
if self.ADRMethod == 'ep_reward_mean':
self.rewardMethod()
#evaluation
if self.num_timesteps - self.oldEvalStep >= self.evalRate :
self.oldEvalStep = self.num_timesteps
evalEnv = self.envFunct(self.targetDomain)
#sync_envs_normalization(self.training_env, evalEnv)
episode_rewards, episode_lengths = evaluate_policy(self.model, evalEnv,
n_eval_episodes=self.n_eval_episodes,
return_episode_rewards=True)
print(episode_rewards)
self.evaluations_results.append(np.mean(episode_rewards))
self.evaluations_mins.append(np.min(episode_rewards))
self.evaluations_timesteps.append(self.num_timesteps)
#remembering the best results :
if np.mean(episode_rewards) == np.max(self.evaluations_results):
self.best_mean = np.mean(episode_rewards)
self.best_min = np.min(episode_rewards)
#wandb.log({"best_mean": self.best_mean, "best_min": self.best_min}, step=self.num_timesteps)
self.model.save(self.models_tmp_dir +"best_network"+".plk")
#TO IMPLEMENT : SAVE THE NETWORK
#External logging
wandb.log({"eval_reward": self.evaluations_results[-1]}, step=self.num_timesteps)
wandb.log({"best_mean": self.best_mean, "best_min": self.best_min}, step=self.num_timesteps)
print('average score in a real environment : '+str(self.evaluations_results[-1]))
print('minimum score in a real environment : '+str(self.evaluations_mins[-1]))
self.model.save(self.models_tmp_dir +"step_"+str(self.num_timesteps)+".plk")
if self.renders :
self.createGif(evalEnv)
else :
evalEnv.close()
#Not used yet
if self.targetReliability!=None and self.targetReward!=None:
goalReached = True
for i in range(self.n_eval_episodes):
if episode_rewards < self.targetReward :
goalReached = False
if goalReached :
return False
return True
def rewardMethod(self):
summary_iterators = EventAccumulator(self.logger_dir).Reload()
tags = summary_iterators.Tags()['scalars']
out = defaultdict(list)
for tag in tags:
#steps = [e.step for e in summary_iterators.Scalars(tag)]
for events in summary_iterators.Scalars(tag):
out[tag].append([e for e in events])
out = np.array(out['rollout/ep_rew_mean'])
#print(out) #May help debugging in case anything happens
try :
self.meanRew = out[-1,2]
except : #if there is only one logged element
try :
self.meanRew = out[2]
except : #if nothing is logged yet
return True
print(self.curriculum)
for i in range(len(self.curriculum)):
self.progress = self.meanRew/self.rewardScale
if self.progress < 0 :
self.progress = 0
elif self.progress > 1 :
self.progress = 1
#For now, the only supported progression goes from the simplest to the most difficult
self.curriculum[i] = self.initCurriculum[i] + (self.endDomain[i]-self.initCurriculum[i])*self.progress**self.domainPowers[i]
#print(self.progress)
self.training_env.env_method('refresh',self.curriculum)
wandb.log({"domain_progress": self.progress}, step=self.num_timesteps)
def lossMethod(self):
summary_iterators = EventAccumulator(self.logger_dir).Reload()
tags = summary_iterators.Tags()['scalars']
out = defaultdict(list)
for tag in tags:
#steps = [e.step for e in summary_iterators.Scalars(tag)]
for events in summary_iterators.Scalars(tag):
out[tag].append([e for e in events])
out = np.array(out['train/loss'])
#print(out) #May help debugging in case anything happens
try :
meanLoss = out[:,2]
except : #if there is only one logged element
try :
meanLoss = out[2]
except : #if nothing is logged yet
return True
try :
meanLoss = np.mean(meanLoss[-5:]) #may be edited
except :
meanLoss = meanLoss[-1]
if self.oldLoss != None :
self.oldLoss = self.newLoss
self.newLoss = meanLoss
lossDiff = self.newLoss-self.oldLoss
#Updating the curriculum
if lossDiff > 0 :
print(self.curriculum)
for i in range(len(self.curriculum)):
progressStep = self.betaRate*lossDiff
#Clipping progress :
if progressStep > 0.05 :
progressStep = 0.05
self.progress += progressStep
#For now, the only supported progression goes from the simplest to the most difficult
if self.progress>1 :
self.progress=1
self.curriculum[i] = self.initCurriculum[i] + (self.endDomain[i]-self.initCurriculum[i])*self.progress**self.domainPowers[i]
#print(self.progress)
self.training_env.env_method('refresh',self.curriculum)
wandb.log({"domain_progress": self.progress, "loss_dif": lossDiff}, step=self.num_timesteps)
print(self.num_timesteps)
else :
self.newLoss = meanLoss
self.oldLoss = self.newLoss
def createGif(self,evalEnv):
gif_name = "PPO_"+str(self.num_timesteps)
save_str = self.gif_dir + gif_name + '.gif'
model = PPO.load(self.models_tmp_dir +"step_"+str(self.num_timesteps)+".plk", env=evalEnv)
images = []
obs = evalEnv.reset()
img = evalEnv.sim.render(
width=400, height=400, camera_name="isometric_view")
for _ in range(600):
action, _ = model.predict(obs)
obs, _, _, _ = evalEnv.step(action)
img = evalEnv.sim.render(
width=400, height=400, camera_name="isometric_view")
images.append(np.flipud(img))
#print("creating gif...")
imageio.mimsave(save_str, [np.array(img)
for i, img in enumerate(images) if i % 2 == 0], fps=29)
print("gif created...")
evalEnv.close()
def _on_rollout_end(self) :
"""
This event is triggered before updating the policy.
"""
pass
def _on_training_end(self) :
"""
This event is triggered before exiting the `learn()` method.
"""
pass
class PPOtraining():
def __init__(self, envFunct, trainingSteps, targetDomain, domainPowers, domainProgressRate, learningRate = 0.0003, batchSize = 256, ADRMethod ='loss', autoParameters = False, startDomain=None, endDomain=None, targetReliability=None, targetReward=None, initModelLoc=None, render=False, verbose = 1, tag="") :
"""Trains a model using PPO (baselines3, based on PyTorch).
Env :
Must be imported at the beginning of the file, and declared in the 'updateEnv' method. Please do check out the evaluation section of the Callback class. Currently supports Gym structure.
WARNING : In order to support smart curriculum learning, the environment must incorporate a 'refresh' method, which updates domains parameters.
Note that this additionnal method is different from a reset method, but can simply update values that will be used in the 'reset' method (especially true for geometrical parameters).
As for noise parameters, they can be directly used after being updated, even in the middle of an episode.
Args:
envFunct : function. See the aforementioned 'Env' section.
trainingSteps : int. Total number of steps for the training.
autoParameters : bool. False by default. Automatically assess the impact of domain variable on the performance of the neural network, and infers custom progress parameters for the ADR.
targetDomain : vector (1D) of domain parameters estimated as representative of the real environment. If possible, it is recommended to characterize such values by performing measurements of the sub-systems (sensors/actuators), or environmental parameters.
These parameters can also be infered from the system requirements. Set to a Null vector to ignore Domain Randomization.
domainPowers : same dimension as targetDomains. Vector of empirical parameters. Default should be np.ones(targetDomain.shape).
1 means that that this parameter will be more or less linearly increased throughout the learning. x<1 means that the parameter will mostly increase in the final phase of the learning. x>1 means that that parameter will mostly increase in the early phase of the learning.
Base function is parameters = (progress)**domainPowers, with progress belonging in [0,1]. Set to a 0.00001 vector to ignore Curriculum Learning.
domainProgressRate : float < 1. Describes of fast is the ADR going to progress. Requires a bit of fine-tuning. Set such as the domain_progress reaches 1 toward the end of the training. A uniform parameter sweep is probably the best best way to go.
KwArgs :
startDomain : vector (1D) of domain parameters to begin the learning with. None by default, meaning that all of these parameters will be 0.
endDomain : vector (1D) of domain parameters to end the learning with. By default, equals to None, and is automatically chosen as being equal to targetDomain.
targetReliability : float in [0,1]. Enables validation to be performed every now and then, and the learning process to be stopped when the model achieves a targetReliability rate of success (achieving targetReward with an environment defined with targetDomain)
targetReward : float.
initModelLoc : path to a stable_baselines model. Enables a previously trained model to be improved with domain randomization
render : bool. Default is 0. Renders Gifs of the target environment every 100000 steps.
verbose : bool. Default is 1. Display essential learning data in the shell.
tag : str. fefault is "". Puts a label on the best saved network
"""
self.step_total = trainingSteps
self.verbose = verbose
self.env = None
self.envFunct = envFunct
self.n_cpu = 8
self.modelLoc = initModelLoc
self.model = None
self.batchSize = batchSize
self.learningRate = learningRate
self.tag = tag
self.createDirectories()
#Callbacks parameters
self.refreshRate = 30000
self.betaRate = domainProgressRate
self.targetDomain = targetDomain
self.domainPowers = domainPowers
if not isinstance(startDomain,np.ndarray) :
self.curriculum = np.zeros(targetDomain.shape)
else :
self.curriculum = startDomain
if not isinstance(endDomain,np.ndarray) :
self.endDomain = self.targetDomain
else :
self.endDomain = endDomain
self.renders = render
self.ADRMethod = ADRMethod
#External logging
self.updateEnv(self.curriculum)
self.updateModel()
self.train()
wandb.join()
def train(self):
start = time.time()
#evalEnv = self.envFunct(self.targetDomain)
#self.model.learn(total_timesteps=self.step_total, eval_env = evalEnv, eval_freq = 20000, n_eval_episodes= 15,log_interval=1, tb_log_name="PPO",callback=smartCurriculumCallback(self.refreshRate, self.betaRate, self.curriculum, self.targetDomain, self.domainPowers, targetReliability=None, targetReward=None, renders = False, verbose=1))
#Using callbacks to perform evaluations instead :
callbackFunction = smartCurriculumCallback(self.envFunct, self.refreshRate, self.betaRate,
self.curriculum, self.endDomain, self.targetDomain,
self.domainPowers, ADRMethod = self.ADRMethod, targetReliability=None, targetReward=None,
renders = self.renders , verbose=1)
self.model.learn(total_timesteps=self.step_total,log_interval=1, tb_log_name="PPO",callback=callbackFunction)
end = time.time()
training_time = end - start
t = time.localtime()
timestamp = time.strftime('%b-%d-%Y_%H%M', t)
src_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "models_tmp/best_network.plk")
dst_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "models/best_network"+wandb.run.name+self.tag+timestamp+".plk")
shutil.copy(src_dir,dst_dir)
#Performance summary is now handled by the validation log.
def updateEnv(self, initCurriculum):
if self.env != None :
self.env.close()
self.env = self.envFunct(initCurriculum)
self.env = customMonitor.Monitor(self.env, allow_early_resets=True)
self.env = DummyVecEnv( [lambda: self.env for i in range(self.n_cpu)] )
def updateModel(self):
if self.modelLoc==None:
self.model = PPO(MlpPolicy, self.env, tensorboard_log="./logger/",verbose=1, device='cuda',n_steps = 2048, n_epochs=10, batch_size= self.batchSize, learning_rate= self.learningRate)
self.modelLoc = self.models_dir
else :
pass
def createDirectories(self):
self.models_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "models/")
self.models_tmp_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "models_tmp/")
self.log_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "tmp")
self.gif_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "tmp_gif/")
self.plt_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "plot")
self.logger_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "logger/")
os.makedirs(self.log_dir, exist_ok=True)
os.makedirs(self.gif_dir, exist_ok=True)
os.makedirs(self.models_dir, exist_ok=True)
os.makedirs(self.models_tmp_dir, exist_ok=True)
os.makedirs(self.plt_dir, exist_ok=True)
os.makedirs(self.logger_dir, exist_ok=True)
if __name__ == '__main__':
for i in range(5):
params_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "paramsADR.json")
with open(params_path) as json_file:
params = json.load(json_file)
tag = params["tag"]
wandb.init(project="Smart_Quad_Friction", sync_tensorboard=True, allow_val_change=True, reinit=True, tags=[tag])
print(str(wandb.run.name))
wandb.config.progress_rate = params["progress_rate"]
wandb.config.domain_powers = None
wandb.config.learningRate = 0.002
wandb.config.batchSize = 1800
training = PPOtraining(quad_env.QuadEnv, 2000000, np.array(params["targetDomain"]), np.array(params["domainPowers"]), wandb.config.progress_rate , learningRate = wandb.config.learningRate, batchSize = wandb.config.batchSize, startDomain= np.array(params["startDomain"]), endDomain = np.array(params["endDomain"]), ADRMethod = 'loss', targetReliability=None, targetReward=None, initModelLoc=None, render = False, verbose = 1, tag = tag)
for i in range(5):
params_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "paramsDR.json")
with open(params_path) as json_file:
params = json.load(json_file)
tag = params["tag"]
wandb.init(project="Smart_Quad_Friction", sync_tensorboard=True, allow_val_change=True, reinit=True, tags=[tag])
wandb.config.progress_rate = params["progress_rate"]
wandb.config.domain_powers = None
wandb.config.learningRate = 0.002
wandb.config.batchSize = 1800
training = PPOtraining(quad_env.QuadEnv, 2000000, np.array(params["targetDomain"]), np.array(params["domainPowers"]), wandb.config.progress_rate , learningRate = wandb.config.learningRate, batchSize = wandb.config.batchSize, startDomain= np.array(params["startDomain"]), endDomain = np.array(params["endDomain"]), ADRMethod = 'loss', targetReliability=None, targetReward=None, initModelLoc=None, render = False, verbose = 1, tag = tag)
for i in range(5):
params_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "paramsNoDR.json")
with open(params_path) as json_file:
params = json.load(json_file)
tag = params["tag"]
wandb.init(project="Smart_Quad_Friction", sync_tensorboard=True, allow_val_change=True, reinit=True, tags=[tag])
wandb.config.progress_rate = params["progress_rate"]
wandb.config.domain_powers = None
wandb.config.learningRate = 0.002
wandb.config.batchSize = 1800
training = PPOtraining(quad_env.QuadEnv, 2000000, np.array(params["targetDomain"]), np.array(params["domainPowers"]), wandb.config.progress_rate , learningRate = wandb.config.learningRate, batchSize = wandb.config.batchSize, startDomain= np.array(params["startDomain"]), endDomain = np.array(params["endDomain"]), ADRMethod = 'loss', targetReliability=None, targetReward=None, initModelLoc=None, render = False, verbose = 1, tag = tag)
|
the-stack_0_14740 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import logging
import sys
from collections import defaultdict
from datetime import datetime
from operator import attrgetter
from time import time
from typing import List, Optional, Tuple
from urllib.parse import quote
# Using `from elasticsearch import *` would break elasticsearch mocking used in unit test.
import elasticsearch
import pendulum
from elasticsearch_dsl import Search
from airflow.configuration import conf
from airflow.models import TaskInstance
from airflow.utils import timezone
from airflow.utils.log.file_task_handler import FileTaskHandler
from airflow.utils.log.json_formatter import JSONFormatter
from airflow.utils.log.logging_mixin import ExternalLoggingMixin, LoggingMixin
# Elasticsearch hosted log type
EsLogMsgType = List[Tuple[str, str]]
class ElasticsearchTaskHandler(FileTaskHandler, ExternalLoggingMixin, LoggingMixin):
"""
ElasticsearchTaskHandler is a python log handler that
reads logs from Elasticsearch. Note logs are not directly
indexed into Elasticsearch. Instead, it flushes logs
into local files. Additional software setup is required
to index the log into Elasticsearch, such as using
Filebeat and Logstash.
To efficiently query and sort Elasticsearch results, we assume each
log message has a field `log_id` consists of ti primary keys:
`log_id = {dag_id}-{task_id}-{execution_date}-{try_number}`
Log messages with specific log_id are sorted based on `offset`,
which is a unique integer indicates log message's order.
Timestamp here are unreliable because multiple log messages
might have the same timestamp.
"""
PAGE = 0
MAX_LINE_PER_PAGE = 1000
LOG_NAME = 'Elasticsearch'
def __init__(
self,
base_log_folder: str,
filename_template: str,
log_id_template: str,
end_of_log_mark: str,
write_stdout: bool,
json_format: bool,
json_fields: str,
host_field: str = "host",
offset_field: str = "offset",
host: str = "localhost:9200",
frontend: str = "localhost:5601",
es_kwargs: Optional[dict] = conf.getsection("elasticsearch_configs"),
):
"""
:param base_log_folder: base folder to store logs locally
:param log_id_template: log id template
:param host: Elasticsearch host name
"""
es_kwargs = es_kwargs or {}
super().__init__(base_log_folder, filename_template)
self.closed = False
self.client = elasticsearch.Elasticsearch([host], **es_kwargs)
self.log_id_template = log_id_template
self.frontend = frontend
self.mark_end_on_close = True
self.end_of_log_mark = end_of_log_mark
self.write_stdout = write_stdout
self.json_format = json_format
self.json_fields = [label.strip() for label in json_fields.split(",")]
self.host_field = host_field
self.offset_field = offset_field
self.handler = None
self.context_set = False
def _render_log_id(self, ti: TaskInstance, try_number: int) -> str:
if self.json_format:
execution_date = self._clean_execution_date(ti.execution_date)
else:
execution_date = ti.execution_date.isoformat()
return self.log_id_template.format(
dag_id=ti.dag_id, task_id=ti.task_id, execution_date=execution_date, try_number=try_number
)
@staticmethod
def _clean_execution_date(execution_date: datetime) -> str:
"""
Clean up an execution date so that it is safe to query in elasticsearch
by removing reserved characters.
# https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html#_reserved_characters
:param execution_date: execution date of the dag run.
"""
return execution_date.strftime("%Y_%m_%dT%H_%M_%S_%f")
def _group_logs_by_host(self, logs):
grouped_logs = defaultdict(list)
for log in logs:
key = getattr(log, self.host_field, 'default_host')
grouped_logs[key].append(log)
# return items sorted by timestamp.
result = sorted(grouped_logs.items(), key=lambda kv: getattr(kv[1][0], 'message', '_'))
return result
def _read_grouped_logs(self):
return True
def _read(
self, ti: TaskInstance, try_number: int, metadata: Optional[dict] = None
) -> Tuple[EsLogMsgType, dict]:
"""
Endpoint for streaming log.
:param ti: task instance object
:param try_number: try_number of the task instance
:param metadata: log metadata,
can be used for steaming log reading and auto-tailing.
:return: a list of tuple with host and log documents, metadata.
"""
if not metadata:
metadata = {'offset': 0}
if 'offset' not in metadata:
metadata['offset'] = 0
offset = metadata['offset']
log_id = self._render_log_id(ti, try_number)
logs = self.es_read(log_id, offset, metadata)
logs_by_host = self._group_logs_by_host(logs)
next_offset = offset if not logs else attrgetter(self.offset_field)(logs[-1])
# Ensure a string here. Large offset numbers will get JSON.parsed incorrectly
# on the client. Sending as a string prevents this issue.
# https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER
metadata['offset'] = str(next_offset)
# end_of_log_mark may contain characters like '\n' which is needed to
# have the log uploaded but will not be stored in elasticsearch.
loading_hosts = [
item[0] for item in logs_by_host if item[-1][-1].message != self.end_of_log_mark.strip()
]
metadata['end_of_log'] = False if not logs else len(loading_hosts) == 0
cur_ts = pendulum.now()
# Assume end of log after not receiving new log for 5 min,
# as executor heartbeat is 1 min and there might be some
# delay before Elasticsearch makes the log available.
if 'last_log_timestamp' in metadata:
last_log_ts = timezone.parse(metadata['last_log_timestamp'])
if (
cur_ts.diff(last_log_ts).in_minutes() >= 5
or 'max_offset' in metadata
and int(offset) >= int(metadata['max_offset'])
):
metadata['end_of_log'] = True
if int(offset) != int(next_offset) or 'last_log_timestamp' not in metadata:
metadata['last_log_timestamp'] = str(cur_ts)
# If we hit the end of the log, remove the actual end_of_log message
# to prevent it from showing in the UI.
def concat_logs(lines):
log_range = (len(lines) - 1) if lines[-1].message == self.end_of_log_mark.strip() else len(lines)
return '\n'.join(self._format_msg(lines[i]) for i in range(log_range))
message = [(host, concat_logs(hosted_log)) for host, hosted_log in logs_by_host]
return message, metadata
def _format_msg(self, log_line):
"""Format ES Record to match settings.LOG_FORMAT when used with json_format"""
# Using formatter._style.format makes it future proof i.e.
# if we change the formatter style from '%' to '{' or '$', this will still work
if self.json_format:
try:
return self.formatter._style.format(_ESJsonLogFmt(self.json_fields, **log_line.to_dict()))
except Exception:
pass
# Just a safe-guard to preserve backwards-compatibility
return log_line.message
def es_read(self, log_id: str, offset: str, metadata: dict) -> list:
"""
Returns the logs matching log_id in Elasticsearch and next offset.
Returns '' if no log is found or there was an error.
:param log_id: the log_id of the log to read.
:type log_id: str
:param offset: the offset start to read log from.
:type offset: str
:param metadata: log metadata, used for steaming log download.
:type metadata: dict
"""
# Offset is the unique key for sorting logs given log_id.
search = Search(using=self.client).query('match_phrase', log_id=log_id).sort(self.offset_field)
search = search.filter('range', **{self.offset_field: {'gt': int(offset)}})
max_log_line = search.count()
if 'download_logs' in metadata and metadata['download_logs'] and 'max_offset' not in metadata:
try:
if max_log_line > 0:
metadata['max_offset'] = attrgetter(self.offset_field)(
search[max_log_line - 1].execute()[-1]
)
else:
metadata['max_offset'] = 0
except Exception:
self.log.exception('Could not get current log size with log_id: %s', log_id)
logs = []
if max_log_line != 0:
try:
logs = search[self.MAX_LINE_PER_PAGE * self.PAGE : self.MAX_LINE_PER_PAGE].execute()
except Exception:
self.log.exception('Could not read log with log_id: %s', log_id)
return logs
def emit(self, record):
if self.handler:
record.offset = int(time() * (10 ** 9))
self.handler.emit(record)
def set_context(self, ti: TaskInstance) -> None:
"""
Provide task_instance context to airflow task handler.
:param ti: task instance object
"""
self.mark_end_on_close = not ti.raw
if self.json_format:
self.formatter = JSONFormatter(
fmt=self.formatter._fmt,
json_fields=self.json_fields + [self.offset_field],
extras={
'dag_id': str(ti.dag_id),
'task_id': str(ti.task_id),
'execution_date': self._clean_execution_date(ti.execution_date),
'try_number': str(ti.try_number),
'log_id': self._render_log_id(ti, ti.try_number),
},
)
if self.write_stdout:
if self.context_set:
# We don't want to re-set up the handler if this logger has
# already been initialized
return
self.handler = logging.StreamHandler(stream=sys.__stdout__) # type: ignore
self.handler.setLevel(self.level) # type: ignore
self.handler.setFormatter(self.formatter) # type: ignore
else:
super().set_context(ti)
self.context_set = True
def close(self) -> None:
# When application exit, system shuts down all handlers by
# calling close method. Here we check if logger is already
# closed to prevent uploading the log to remote storage multiple
# times when `logging.shutdown` is called.
if self.closed:
return
if not self.mark_end_on_close:
self.closed = True
return
# Case which context of the handler was not set.
if self.handler is None:
self.closed = True
return
# Reopen the file stream, because FileHandler.close() would be called
# first in logging.shutdown() and the stream in it would be set to None.
if self.handler.stream is None or self.handler.stream.closed:
self.handler.stream = self.handler._open()
# Mark the end of file using end of log mark,
# so we know where to stop while auto-tailing.
self.handler.stream.write(self.end_of_log_mark)
if self.write_stdout:
self.handler.close()
sys.stdout = sys.__stdout__
super().close()
self.closed = True
@property
def log_name(self) -> str:
"""The log name"""
return self.LOG_NAME
def get_external_log_url(self, task_instance: TaskInstance, try_number: int) -> str:
"""
Creates an address for an external log collecting service.
:param task_instance: task instance object
:type: task_instance: TaskInstance
:param try_number: task instance try_number to read logs from.
:type try_number: Optional[int]
:return: URL to the external log collection service
:rtype: str
"""
log_id = self._render_log_id(task_instance, try_number)
scheme = '' if '://' in self.frontend else 'https://'
return scheme + self.frontend.format(log_id=quote(log_id))
@property
def supports_external_link(self) -> bool:
"""Whether we can support external links"""
return bool(self.frontend)
class _ESJsonLogFmt:
"""Helper class to read ES Logs and re-format it to match settings.LOG_FORMAT"""
# A separate class is needed because 'self.formatter._style.format' uses '.__dict__'
def __init__(self, json_fields: List, **kwargs):
for field in json_fields:
self.__setattr__(field, '')
self.__dict__.update(kwargs)
|
the-stack_0_14741 | import pathlib
from setuptools import find_packages, setup
# The directory containing this file
HERE = pathlib.Path(__file__).parent
# The text of the README file
README = (HERE / "README.md").read_text()
# This call to setup() does all the work
setup(
name="sectoolkit",
version="0.2.4",
description="Tools for working with Securities and Exchange Commission (SEC) indices, SGML header files, filing archives and individual filing documents.",
long_description=README,
long_description_content_type="text/markdown",
url="https://github.com/dlouton/sectoolkit",
author="Dave Louton",
author_email="[email protected]",
license="MIT",
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.7",
],
packages=find_packages(exclude=("tests",)),
include_package_data=True,
install_requires=["bs4", "numpy", "pandas", "xmltodict", "tqdm"],
# entry_points={
# "console_scripts": [
# "realpython=reader.__main__:main",
# ]
# },
)
|
the-stack_0_14742 | #!/usr/bin/env python3
# Copyright 2014 BitPay Inc.
# Copyright 2016-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test framework for crackedcoin utils.
Runs automatically during `make check`.
Can also be run manually."""
import argparse
import binascii
import configparser
import difflib
import json
import logging
import os
import pprint
import subprocess
import sys
def main():
config = configparser.ConfigParser()
config.optionxform = str
config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8"))
env_conf = dict(config.items('environment'))
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-v', '--verbose', action='store_true')
args = parser.parse_args()
verbose = args.verbose
if verbose:
level = logging.DEBUG
else:
level = logging.ERROR
formatter = '%(asctime)s - %(levelname)s - %(message)s'
# Add the format/level to the logger
logging.basicConfig(format=formatter, level=level)
bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "bitcoin-util-test.json", env_conf)
def bctester(testDir, input_basename, buildenv):
""" Loads and parses the input file, runs all tests and reports results"""
input_filename = os.path.join(testDir, input_basename)
raw_data = open(input_filename, encoding="utf8").read()
input_data = json.loads(raw_data)
failed_testcases = []
for testObj in input_data:
try:
bctest(testDir, testObj, buildenv)
logging.info("PASSED: " + testObj["description"])
except:
logging.info("FAILED: " + testObj["description"])
failed_testcases.append(testObj["description"])
if failed_testcases:
error_message = "FAILED_TESTCASES:\n"
error_message += pprint.pformat(failed_testcases, width=400)
logging.error(error_message)
sys.exit(1)
else:
sys.exit(0)
def bctest(testDir, testObj, buildenv):
"""Runs a single test, comparing output and RC to expected output and RC.
Raises an error if input can't be read, executable fails, or output/RC
are not as expected. Error is caught by bctester() and reported.
"""
# Get the exec names and arguments
execprog = os.path.join(buildenv["BUILDDIR"], "src", testObj["exec"] + buildenv["EXEEXT"])
execargs = testObj['args']
execrun = [execprog] + execargs
# Read the input data (if there is any)
stdinCfg = None
inputData = None
if "input" in testObj:
filename = os.path.join(testDir, testObj["input"])
inputData = open(filename, encoding="utf8").read()
stdinCfg = subprocess.PIPE
# Read the expected output data (if there is any)
outputFn = None
outputData = None
outputType = None
if "output_cmp" in testObj:
outputFn = testObj['output_cmp']
outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare)
try:
outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read()
except:
logging.error("Output file " + outputFn + " can not be opened")
raise
if not outputData:
logging.error("Output data missing for " + outputFn)
raise Exception
if not outputType:
logging.error("Output file %s does not have a file extension" % outputFn)
raise Exception
# Run the test
proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
try:
outs = proc.communicate(input=inputData)
except OSError:
logging.error("OSError, Failed to execute " + execprog)
raise
if outputData:
data_mismatch, formatting_mismatch = False, False
# Parse command output and expected output
try:
a_parsed = parse_output(outs[0], outputType)
except Exception as e:
logging.error('Error parsing command output as %s: %s' % (outputType, e))
raise
try:
b_parsed = parse_output(outputData, outputType)
except Exception as e:
logging.error('Error parsing expected output %s as %s: %s' % (outputFn, outputType, e))
raise
# Compare data
if a_parsed != b_parsed:
logging.error("Output data mismatch for " + outputFn + " (format " + outputType + ")")
data_mismatch = True
# Compare formatting
if outs[0] != outputData:
error_message = "Output formatting mismatch for " + outputFn + ":\n"
error_message += "".join(difflib.context_diff(outputData.splitlines(True),
outs[0].splitlines(True),
fromfile=outputFn,
tofile="returned"))
logging.error(error_message)
formatting_mismatch = True
assert not data_mismatch and not formatting_mismatch
# Compare the return code to the expected return code
wantRC = 0
if "return_code" in testObj:
wantRC = testObj['return_code']
if proc.returncode != wantRC:
logging.error("Return code mismatch for " + outputFn)
raise Exception
if "error_txt" in testObj:
want_error = testObj["error_txt"]
# Compare error text
# TODO: ideally, we'd compare the strings exactly and also assert
# That stderr is empty if no errors are expected. However, bitcoin-tx
# emits DISPLAY errors when running as a windows application on
# linux through wine. Just assert that the expected error text appears
# somewhere in stderr.
if want_error not in outs[1]:
logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip())
raise Exception
def parse_output(a, fmt):
"""Parse the output according to specified format.
Raise an error if the output can't be parsed."""
if fmt == 'json': # json: compare parsed data
return json.loads(a)
elif fmt == 'hex': # hex: parse and compare binary data
return binascii.a2b_hex(a.strip())
else:
raise NotImplementedError("Don't know how to compare %s" % fmt)
if __name__ == '__main__':
main()
|
the-stack_0_14743 | from matplotlib import colors, colorbar
from mpl_toolkits.axes_grid1 import make_axes_locatable
# Add colorbar to existing imshow
def imshow_add_color_bar(fig, ax, img):
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size='5%', pad=0.05)
fig.colorbar(img, cax=cax, orientation='vertical')
# Adds fake colorbar to any axis. That colorbar will linearly interpolate an existing colormap
def imshow_add_fake_color_bar(fig, ax, cmap, vmin=0, vmax=1):
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size='5%', pad=0.05)
norm = colors.Normalize(vmin=vmin, vmax=vmax)
cb1 = colorbar.ColorbarBase(cax, cmap=cmap, norm=norm, orientation='vertical') |
the-stack_0_14744 | import asyncio
import pytest
import time
from hddcoin.consensus.block_rewards import calculate_base_farmer_reward, calculate_pool_reward
from hddcoin.protocols.full_node_protocol import RespondBlock
from hddcoin.server.server import HDDcoinServer
from hddcoin.simulator.simulator_protocol import FarmNewBlockProtocol, ReorgProtocol
from hddcoin.types.peer_info import PeerInfo
from hddcoin.util.ints import uint16, uint32, uint64
from hddcoin.wallet.util.transaction_type import TransactionType
from hddcoin.wallet.transaction_record import TransactionRecord
from hddcoin.wallet.wallet_node import WalletNode
from hddcoin.wallet.wallet_state_manager import WalletStateManager
from tests.setup_nodes import self_hostname, setup_simulators_and_wallets
from tests.time_out_assert import time_out_assert, time_out_assert_not_none
from tests.wallet.cc_wallet.test_cc_wallet import tx_in_pool
@pytest.fixture(scope="module")
def event_loop():
loop = asyncio.get_event_loop()
yield loop
class TestWalletSimulator:
@pytest.fixture(scope="function")
async def wallet_node(self):
async for _ in setup_simulators_and_wallets(1, 1, {}):
yield _
@pytest.fixture(scope="function")
async def two_wallet_nodes(self):
async for _ in setup_simulators_and_wallets(1, 2, {}):
yield _
@pytest.fixture(scope="function")
async def two_wallet_nodes_five_freeze(self):
async for _ in setup_simulators_and_wallets(1, 2, {}):
yield _
@pytest.fixture(scope="function")
async def three_sim_two_wallets(self):
async for _ in setup_simulators_and_wallets(3, 2, {}):
yield _
@pytest.mark.asyncio
async def test_wallet_coinbase(self, wallet_node):
num_blocks = 10
full_nodes, wallets = wallet_node
full_node_api = full_nodes[0]
server_1: HDDcoinServer = full_node_api.full_node.server
wallet_node, server_2 = wallets[0]
wallet = wallet_node.wallet_state_manager.main_wallet
ph = await wallet.get_new_puzzlehash()
await server_2.start_client(PeerInfo(self_hostname, uint16(server_1._port)), None)
for i in range(0, num_blocks):
await full_node_api.farm_new_block(FarmNewBlockProtocol(ph))
await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph))
await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph))
funds = sum(
[
calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i))
for i in range(1, num_blocks + 2)
]
)
async def check_tx_are_pool_farm_rewards():
wsm: WalletStateManager = wallet_node.wallet_state_manager
all_txs = await wsm.get_all_transactions(1)
expected_count = (num_blocks + 1) * 2
if len(all_txs) != expected_count:
return False
pool_rewards = 0
farm_rewards = 0
for tx in all_txs:
if tx.type == TransactionType.COINBASE_REWARD:
pool_rewards += 1
elif tx.type == TransactionType.FEE_REWARD:
farm_rewards += 1
if pool_rewards != expected_count / 2:
return False
if farm_rewards != expected_count / 2:
return False
return True
await time_out_assert(10, check_tx_are_pool_farm_rewards, True)
await time_out_assert(5, wallet.get_confirmed_balance, funds)
@pytest.mark.asyncio
async def test_wallet_make_transaction(self, two_wallet_nodes):
num_blocks = 5
full_nodes, wallets = two_wallet_nodes
full_node_api = full_nodes[0]
server_1 = full_node_api.full_node.server
wallet_node, server_2 = wallets[0]
wallet_node_2, server_3 = wallets[1]
wallet = wallet_node.wallet_state_manager.main_wallet
ph = await wallet.get_new_puzzlehash()
await server_2.start_client(PeerInfo(self_hostname, uint16(server_1._port)), None)
for i in range(0, num_blocks):
await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph))
funds = sum(
[calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i)) for i in range(1, num_blocks)]
)
await time_out_assert(5, wallet.get_confirmed_balance, funds)
await time_out_assert(5, wallet.get_unconfirmed_balance, funds)
tx = await wallet.generate_signed_transaction(
10,
await wallet_node_2.wallet_state_manager.main_wallet.get_new_puzzlehash(),
0,
)
await wallet.push_transaction(tx)
await time_out_assert(5, wallet.get_confirmed_balance, funds)
await time_out_assert(5, wallet.get_unconfirmed_balance, funds - 10)
for i in range(0, num_blocks):
await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph))
new_funds = sum(
[
calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i))
for i in range(1, (2 * num_blocks))
]
)
await time_out_assert(5, wallet.get_confirmed_balance, new_funds - 10)
await time_out_assert(5, wallet.get_unconfirmed_balance, new_funds - 10)
@pytest.mark.asyncio
async def test_wallet_coinbase_reorg(self, wallet_node):
num_blocks = 5
full_nodes, wallets = wallet_node
full_node_api = full_nodes[0]
fn_server = full_node_api.full_node.server
wallet_node, server_2 = wallets[0]
wallet = wallet_node.wallet_state_manager.main_wallet
ph = await wallet.get_new_puzzlehash()
await server_2.start_client(PeerInfo(self_hostname, uint16(fn_server._port)), None)
for i in range(0, num_blocks):
await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph))
funds = sum(
[calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i)) for i in range(1, num_blocks)]
)
await time_out_assert(5, wallet.get_confirmed_balance, funds)
await full_node_api.reorg_from_index_to_new_index(ReorgProtocol(uint32(2), uint32(num_blocks + 6), 32 * b"0"))
funds = sum(
[
calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i))
for i in range(1, num_blocks - 2)
]
)
await time_out_assert(5, wallet.get_confirmed_balance, funds)
@pytest.mark.asyncio
async def test_wallet_send_to_three_peers(self, three_sim_two_wallets):
num_blocks = 10
full_nodes, wallets = three_sim_two_wallets
wallet_0, wallet_server_0 = wallets[0]
full_node_api_0 = full_nodes[0]
full_node_api_1 = full_nodes[1]
full_node_api_2 = full_nodes[2]
full_node_0 = full_node_api_0.full_node
full_node_1 = full_node_api_1.full_node
full_node_2 = full_node_api_2.full_node
server_0 = full_node_0.server
server_1 = full_node_1.server
server_2 = full_node_2.server
ph = await wallet_0.wallet_state_manager.main_wallet.get_new_puzzlehash()
# wallet0 <-> sever0
await wallet_server_0.start_client(PeerInfo(self_hostname, uint16(server_0._port)), None)
for i in range(0, num_blocks):
await full_node_api_0.farm_new_transaction_block(FarmNewBlockProtocol(ph))
all_blocks = await full_node_api_0.get_all_full_blocks()
for block in all_blocks:
await full_node_1.respond_block(RespondBlock(block))
await full_node_2.respond_block(RespondBlock(block))
funds = sum(
[calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i)) for i in range(1, num_blocks)]
)
await time_out_assert(5, wallet_0.wallet_state_manager.main_wallet.get_confirmed_balance, funds)
tx = await wallet_0.wallet_state_manager.main_wallet.generate_signed_transaction(10, 32 * b"0", 0)
await wallet_0.wallet_state_manager.main_wallet.push_transaction(tx)
await time_out_assert_not_none(5, full_node_0.mempool_manager.get_spendbundle, tx.spend_bundle.name())
# wallet0 <-> sever1
await wallet_server_0.start_client(PeerInfo(self_hostname, uint16(server_1._port)), wallet_0.on_connect)
await time_out_assert_not_none(5, full_node_1.mempool_manager.get_spendbundle, tx.spend_bundle.name())
# wallet0 <-> sever2
await wallet_server_0.start_client(PeerInfo(self_hostname, uint16(server_2._port)), wallet_0.on_connect)
await time_out_assert_not_none(5, full_node_2.mempool_manager.get_spendbundle, tx.spend_bundle.name())
@pytest.mark.asyncio
async def test_wallet_make_transaction_hop(self, two_wallet_nodes_five_freeze):
num_blocks = 10
full_nodes, wallets = two_wallet_nodes_five_freeze
full_node_api_0 = full_nodes[0]
full_node_0 = full_node_api_0.full_node
server_0 = full_node_0.server
wallet_node_0, wallet_0_server = wallets[0]
wallet_node_1, wallet_1_server = wallets[1]
wallet_0 = wallet_node_0.wallet_state_manager.main_wallet
wallet_1 = wallet_node_1.wallet_state_manager.main_wallet
ph = await wallet_0.get_new_puzzlehash()
await wallet_0_server.start_client(PeerInfo(self_hostname, uint16(server_0._port)), None)
await wallet_1_server.start_client(PeerInfo(self_hostname, uint16(server_0._port)), None)
for i in range(0, num_blocks):
await full_node_api_0.farm_new_transaction_block(FarmNewBlockProtocol(ph))
funds = sum(
[calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i)) for i in range(1, num_blocks)]
)
await time_out_assert(5, wallet_0.get_confirmed_balance, funds)
await time_out_assert(5, wallet_0.get_unconfirmed_balance, funds)
assert await wallet_0.get_confirmed_balance() == funds
assert await wallet_0.get_unconfirmed_balance() == funds
tx = await wallet_0.generate_signed_transaction(
10,
await wallet_node_1.wallet_state_manager.main_wallet.get_new_puzzlehash(),
0,
)
await wallet_0.push_transaction(tx)
# Full node height 11, wallet height 9
await time_out_assert(5, wallet_0.get_confirmed_balance, funds)
await time_out_assert(5, wallet_0.get_unconfirmed_balance, funds - 10)
for i in range(0, 4):
await full_node_api_0.farm_new_transaction_block(FarmNewBlockProtocol(32 * b"0"))
# here it's num_blocks + 1 because our last reward is included in the first block that we just farmed
new_funds = sum(
[
calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i))
for i in range(1, num_blocks + 1)
]
)
# Full node height 17, wallet height 15
await time_out_assert(5, wallet_0.get_confirmed_balance, new_funds - 10)
await time_out_assert(5, wallet_0.get_unconfirmed_balance, new_funds - 10)
await time_out_assert(5, wallet_1.get_confirmed_balance, 10)
tx = await wallet_1.generate_signed_transaction(5, await wallet_0.get_new_puzzlehash(), 0)
await wallet_1.push_transaction(tx)
for i in range(0, 4):
await full_node_api_0.farm_new_transaction_block(FarmNewBlockProtocol(32 * b"0"))
await wallet_0.get_confirmed_balance()
await wallet_0.get_unconfirmed_balance()
await wallet_1.get_confirmed_balance()
await time_out_assert(5, wallet_0.get_confirmed_balance, new_funds - 5)
await time_out_assert(5, wallet_0.get_unconfirmed_balance, new_funds - 5)
await time_out_assert(5, wallet_1.get_confirmed_balance, 5)
# @pytest.mark.asyncio
# async def test_wallet_finds_full_node(self):
# node_iters = [
# setup_full_node(
# test_constants,
# "blockchain_test.db",
# 11234,
# introducer_port=11236,
# simulator=False,
# ),
# setup_wallet_node(
# 11235,
# test_constants,
# None,
# introducer_port=11236,
# ),
# setup_introducer(11236),
# ]
#
# full_node_api = await node_iters[0].__anext__()
# wallet, wallet_server = await node_iters[1].__anext__()
# introducer, introducer_server = await node_iters[2].__anext__()
#
# async def has_full_node():
# outbound: List[WSHDDcoinConnection] = wallet.server.get_outgoing_connections()
# for connection in outbound:
# if connection.connection_type is NodeType.FULL_NODE:
# return True
# return False
#
# await time_out_assert(
# 2 * 60,
# has_full_node,
# True,
# )
# await _teardown_nodes(node_iters)
@pytest.mark.asyncio
async def test_wallet_make_transaction_with_fee(self, two_wallet_nodes):
num_blocks = 5
full_nodes, wallets = two_wallet_nodes
full_node_1 = full_nodes[0]
wallet_node, server_2 = wallets[0]
wallet_node_2, server_3 = wallets[1]
wallet = wallet_node.wallet_state_manager.main_wallet
ph = await wallet.get_new_puzzlehash()
await server_2.start_client(PeerInfo(self_hostname, uint16(full_node_1.full_node.server._port)), None)
for i in range(0, num_blocks):
await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph))
funds = sum(
[calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i)) for i in range(1, num_blocks)]
)
await time_out_assert(5, wallet.get_confirmed_balance, funds)
await time_out_assert(5, wallet.get_unconfirmed_balance, funds)
assert await wallet.get_confirmed_balance() == funds
assert await wallet.get_unconfirmed_balance() == funds
tx_amount = 3200000000000
tx_fee = 10
tx = await wallet.generate_signed_transaction(
tx_amount,
await wallet_node_2.wallet_state_manager.main_wallet.get_new_puzzlehash(),
tx_fee,
)
fees = tx.spend_bundle.fees()
assert fees == tx_fee
await wallet.push_transaction(tx)
await time_out_assert(5, wallet.get_confirmed_balance, funds)
await time_out_assert(5, wallet.get_unconfirmed_balance, funds - tx_amount - tx_fee)
for i in range(0, num_blocks):
await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(32 * b"0"))
new_funds = sum(
[
calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i))
for i in range(1, num_blocks + 1)
]
)
await time_out_assert(5, wallet.get_confirmed_balance, new_funds - tx_amount - tx_fee)
await time_out_assert(5, wallet.get_unconfirmed_balance, new_funds - tx_amount - tx_fee)
@pytest.mark.asyncio
async def test_wallet_create_hit_max_send_amount(self, two_wallet_nodes):
num_blocks = 5
full_nodes, wallets = two_wallet_nodes
full_node_1 = full_nodes[0]
wallet_node, server_2 = wallets[0]
wallet_node_2, server_3 = wallets[1]
wallet = wallet_node.wallet_state_manager.main_wallet
ph = await wallet.get_new_puzzlehash()
await server_2.start_client(PeerInfo(self_hostname, uint16(full_node_1.full_node.server._port)), None)
for i in range(0, num_blocks):
await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph))
funds = sum(
[calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i)) for i in range(1, num_blocks)]
)
await time_out_assert(5, wallet.get_confirmed_balance, funds)
primaries = []
for i in range(0, 600):
primaries.append({"puzzlehash": ph, "amount": 100000000 + i})
tx_split_coins = await wallet.generate_signed_transaction(1, ph, 0, primaries=primaries)
await wallet.push_transaction(tx_split_coins)
await time_out_assert(
15, tx_in_pool, True, full_node_1.full_node.mempool_manager, tx_split_coins.spend_bundle.name()
)
for i in range(0, num_blocks):
await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(32 * b"0"))
funds = sum(
[
calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i))
for i in range(1, num_blocks + 1)
]
)
await time_out_assert(90, wallet.get_confirmed_balance, funds)
max_sent_amount = await wallet.get_max_send_amount()
# 1) Generate transaction that is under the limit
under_limit_tx = None
try:
under_limit_tx = await wallet.generate_signed_transaction(
max_sent_amount - 1,
ph,
0,
)
except ValueError:
assert ValueError
assert under_limit_tx is not None
# 2) Generate transaction that is equal to limit
at_limit_tx = None
try:
at_limit_tx = await wallet.generate_signed_transaction(
max_sent_amount,
ph,
0,
)
except ValueError:
assert ValueError
assert at_limit_tx is not None
# 3) Generate transaction that is greater than limit
above_limit_tx = None
try:
above_limit_tx = await wallet.generate_signed_transaction(
max_sent_amount + 1,
ph,
0,
)
except ValueError:
pass
assert above_limit_tx is None
@pytest.mark.asyncio
async def test_wallet_prevent_fee_theft(self, two_wallet_nodes):
num_blocks = 5
full_nodes, wallets = two_wallet_nodes
full_node_1 = full_nodes[0]
wallet_node, server_2 = wallets[0]
wallet_node_2, server_3 = wallets[1]
wallet = wallet_node.wallet_state_manager.main_wallet
ph = await wallet.get_new_puzzlehash()
await server_2.start_client(PeerInfo(self_hostname, uint16(full_node_1.full_node.server._port)), None)
for i in range(0, num_blocks):
await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph))
funds = sum(
[calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i)) for i in range(1, num_blocks)]
)
await time_out_assert(5, wallet.get_confirmed_balance, funds)
await time_out_assert(5, wallet.get_unconfirmed_balance, funds)
assert await wallet.get_confirmed_balance() == funds
assert await wallet.get_unconfirmed_balance() == funds
tx_amount = 3200000000000
tx_fee = 300000000000
tx = await wallet.generate_signed_transaction(
tx_amount,
await wallet_node_2.wallet_state_manager.main_wallet.get_new_puzzlehash(),
tx_fee,
)
# extract coin_solution from generated spend_bundle
for cs in tx.spend_bundle.coin_solutions:
if cs.additions() == []:
stolen_cs = cs
# get a legit signature
stolen_sb = await wallet.sign_transaction([stolen_cs])
now = uint64(int(time.time()))
add_list = list(stolen_sb.additions())
rem_list = list(stolen_sb.removals())
name = stolen_sb.name()
stolen_tx = TransactionRecord(
confirmed_at_height=uint32(0),
created_at_time=now,
to_puzzle_hash=32 * b"0",
amount=0,
fee_amount=stolen_cs.coin.amount,
confirmed=False,
sent=uint32(0),
spend_bundle=stolen_sb,
additions=add_list,
removals=rem_list,
wallet_id=wallet.id(),
sent_to=[],
trade_id=None,
type=uint32(TransactionType.OUTGOING_TX.value),
name=name,
)
await wallet.push_transaction(stolen_tx)
await time_out_assert(5, wallet.get_confirmed_balance, funds)
await time_out_assert(5, wallet.get_unconfirmed_balance, funds - stolen_cs.coin.amount)
for i in range(0, num_blocks):
await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(32 * b"0"))
# Funds have not decreased because stolen_tx was rejected
outstanding_coinbase_rewards = 2000000000000
await time_out_assert(5, wallet.get_confirmed_balance, funds + outstanding_coinbase_rewards)
await time_out_assert(5, wallet.get_confirmed_balance, funds + outstanding_coinbase_rewards)
@pytest.mark.asyncio
async def test_wallet_tx_reorg(self, two_wallet_nodes):
num_blocks = 5
full_nodes, wallets = two_wallet_nodes
full_node_api = full_nodes[0]
fn_server = full_node_api.full_node.server
wallet_node, server_2 = wallets[0]
wallet_node: WalletNode = wallet_node
wallet_node_2, server_3 = wallets[1]
wallet = wallet_node.wallet_state_manager.main_wallet
wallet_2 = wallet_node_2.wallet_state_manager.main_wallet
ph = await wallet.get_new_puzzlehash()
ph2 = await wallet_2.get_new_puzzlehash()
await server_2.start_client(PeerInfo(self_hostname, uint16(fn_server._port)), None)
await server_3.start_client(PeerInfo(self_hostname, uint16(fn_server._port)), None)
for i in range(0, num_blocks):
await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph))
funds = sum(
[calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i)) for i in range(1, num_blocks)]
)
# Waits a few seconds to receive rewards
all_blocks = await full_node_api.get_all_full_blocks()
# Ensure that we use a coin that we will not reorg out
coin = list(all_blocks[-3].get_included_reward_coins())[0]
await asyncio.sleep(5)
tx = await wallet.generate_signed_transaction(1000, ph2, coins={coin})
await wallet.push_transaction(tx)
await full_node_api.full_node.respond_transaction(tx.spend_bundle, tx.name)
await time_out_assert(5, wallet.get_confirmed_balance, funds)
for i in range(0, 2):
await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(32 * b"0"))
await time_out_assert(5, wallet_2.get_confirmed_balance, 1000)
await time_out_assert(5, wallet_node.wallet_state_manager.blockchain.get_peak_height, 7)
peak_height = full_node_api.full_node.blockchain.get_peak().height
print(peak_height)
# Perform a reorg, which will revert the transaction in the full node and wallet, and cause wallet to resubmit
await full_node_api.reorg_from_index_to_new_index(
ReorgProtocol(uint32(peak_height - 3), uint32(peak_height + 3), 32 * b"0")
)
funds = sum(
[
calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i))
for i in range(1, peak_height - 2)
]
)
await time_out_assert(7, full_node_api.full_node.blockchain.get_peak_height, peak_height + 3)
await time_out_assert(7, wallet_node.wallet_state_manager.blockchain.get_peak_height, peak_height + 3)
# Farm a few blocks so we can confirm the resubmitted transaction
for i in range(0, num_blocks):
await asyncio.sleep(1)
await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(32 * b"0"))
# By this point, the transaction should be confirmed
print(await wallet.get_confirmed_balance())
await time_out_assert(15, wallet.get_confirmed_balance, funds - 1000)
unconfirmed = await wallet_node.wallet_state_manager.tx_store.get_unconfirmed_for_wallet(int(wallet.id()))
assert len(unconfirmed) == 0
tx_record = await wallet_node.wallet_state_manager.tx_store.get_transaction_record(tx.name)
removed = tx_record.removals[0]
added = tx_record.additions[0]
added_1 = tx_record.additions[1]
wallet_coin_record_rem = await wallet_node.wallet_state_manager.coin_store.get_coin_record(removed.name())
assert wallet_coin_record_rem.spent
coin_record_full_node = await full_node_api.full_node.coin_store.get_coin_record(removed.name())
assert coin_record_full_node.spent
add_1_coin_record_full_node = await full_node_api.full_node.coin_store.get_coin_record(added.name())
assert add_1_coin_record_full_node is not None
assert add_1_coin_record_full_node.confirmed_block_index > 0
add_2_coin_record_full_node = await full_node_api.full_node.coin_store.get_coin_record(added_1.name())
assert add_2_coin_record_full_node is not None
assert add_2_coin_record_full_node.confirmed_block_index > 0
|
the-stack_0_14745 | """
Copyright (c) 2020 Intel 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.
"""
from abc import ABC, abstractmethod
import tensorflow_datasets as tfds
from beta.examples.tensorflow.common.logger import logger
from beta.examples.tensorflow.common.utils import set_hard_limit_num_open_files
class BaseDatasetBuilder(ABC):
"""Abstract dataset loader and input processing."""
def __init__(self, config, is_train, num_devices):
self._config = config
self._is_train = is_train
self._num_devices = num_devices
self._global_batch_size = config.batch_size
# Dataset params
self._dataset_dir = config.dataset_dir
self._dataset_name = config.get('dataset', None)
self._dataset_type = config.get('dataset_type', 'tfds')
self._as_supervised = False
# Dataset loader
self._dataset_loader = None
# TFDS params
self._skip_decoding = False
# Dict with TFRecordDatasets
self._tfrecord_datasets = {}
self._split = 'train' if self._is_train else 'validation'
@property
def is_train(self):
"""Returns a `bool` flag which specifies whether it is a training or evaluation dataset."""
return self._is_train
@property
def batch_size(self):
"""Returns per replica batch size."""
return self._global_batch_size // self._num_devices
@property
def global_batch_size(self):
"""Returns global batch size."""
return self.batch_size * self._num_devices
@property
def steps_per_epoch(self):
"""Returns steps per epoch"""
return self.num_examples // self.global_batch_size
@property
@abstractmethod
def num_examples(self):
"""Returns number of examples in the current dataset."""
@property
@abstractmethod
def num_classes(self):
"""Returns number of classes in the current dataset."""
@abstractmethod
def _pipeline(self, dataset):
"""The pipeline which decodes and preprocesses the input data for model."""
def build(self):
dataset_builders = {
'tfds': self._load_tfds,
'tfrecords': self._load_tfrecords,
}
builder = dataset_builders.get(self._dataset_type, None)
if builder is None:
raise ValueError('Unknown dataset type {}'.format(self._dataset_type))
dataset = builder()
dataset = self._pipeline(dataset)
return dataset
def _load_tfds(self):
logger.info('Using TFDS to load data.')
set_hard_limit_num_open_files()
self._dataset_loader = tfds.builder(self._dataset_name,
data_dir=self._dataset_dir)
self._dataset_loader.download_and_prepare()
decoders = {'image': tfds.decode.SkipDecoding()} \
if self._skip_decoding else None
read_config = tfds.ReadConfig(
interleave_cycle_length=64,
interleave_block_length=1)
dataset = self._dataset_loader.as_dataset(
split=self._split,
as_supervised=self._as_supervised,
shuffle_files=True,
decoders=decoders,
read_config=read_config)
return dataset
def _load_tfrecords(self):
logger.info('Using TFRecords to load data')
dataset_key = self._dataset_name.replace('/', '')
if dataset_key in self._tfrecord_datasets:
self._dataset_loader = self._tfrecord_datasets[dataset_key](
config=self._config, is_train=self._is_train
)
else:
raise ValueError('Unknown dataset name: {}'.format(self._dataset_name))
dataset = self._dataset_loader.as_dataset()
return dataset
|
the-stack_0_14746 | #!/usr/bin/env python3
# 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.
"""
Test the analysis code for the model chat task.
"""
import glob
import os
import pytest
from pytest_regressions.file_regression import FileRegressionFixture
import parlai.utils.testing as testing_utils
try:
from parlai.crowdsourcing.tasks.model_chat.analysis.compile_results import (
ModelChatResultsCompiler,
)
from parlai.crowdsourcing.utils.tests import check_stdout
class TestCompileResults:
"""
Test the analysis code for the model chat task.
"""
@pytest.fixture(scope="module")
def setup_teardown(self):
"""
Call code to set up and tear down tests.
Run this only once because we'll be running all analysis code before
checking any results.
"""
outputs = {}
# Paths
analysis_samples_folder = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'analysis_samples'
)
analysis_outputs_folder = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'test_model_chat_analysis'
)
outputs['expected_stdout_path'] = os.path.join(
analysis_outputs_folder, 'test_stdout.txt'
)
prefixes = ['results', 'worker_results']
with testing_utils.tempdir() as tmpdir:
# Run analysis
with testing_utils.capture_output() as output:
arg_string = f"""\
--results-folders {analysis_samples_folder}
--output-folder {tmpdir}
"""
parser_ = ModelChatResultsCompiler.setup_args()
args_ = parser_.parse_args(arg_string.split())
ModelChatResultsCompiler(vars(args_)).compile_and_save_results()
stdout = output.getvalue()
# Define output structure
filtered_stdout = '\n'.join(
[line for line in stdout.split('\n') if not line.endswith('.csv')]
)
# Don't track lines that record where a file was saved to, because filenames
# are timestamped
outputs['stdout'] = filtered_stdout
for prefix in prefixes:
results_path = list(glob.glob(os.path.join(tmpdir, f'{prefix}_*')))[
0
]
with open(results_path) as f:
outputs[prefix] = f.read()
yield outputs
# All code after this will be run upon teardown
def test_stdout(self, setup_teardown):
"""
Check the output against what it should be.
"""
outputs = setup_teardown
check_stdout(
actual_stdout=outputs['stdout'],
expected_stdout_path=outputs['expected_stdout_path'],
)
def test_results_file(
self, setup_teardown, file_regression: FileRegressionFixture
):
"""
Check the results file against what it should be.
We don't use DataFrameRegression fixture because the results might include
non-numeric data.
"""
prefix = 'results'
outputs = setup_teardown
file_regression.check(outputs[prefix], basename=prefix)
def test_worker_results_file(
self, setup_teardown, file_regression: FileRegressionFixture
):
"""
Check the worker_results file against what it should be.
We don't use DataFrameRegression fixture because the results might include
non-numeric data.
"""
prefix = 'worker_results'
outputs = setup_teardown
file_regression.check(outputs[prefix], basename=prefix)
except ImportError:
pass
|
the-stack_0_14748 | # coding:utf-8
'''
温度补偿自动化测试
'''
import os
import datetime
import re
import json
from shutil import copyfile
import time
import modbus_tk
import threading
import atexit
from asgiref.sync import async_to_sync
from .api.fsv import FSVCtrl
from .baseboard.handle_board import BT2KHandler
from .excel.common_excel import BoardExcel
from commoninterface.master import THDevice
from .ftp.ftp_client import MyFTP
from .api.file_process import FlatProcess, GainProcess
from commoninterface.utils import PropagatingThread
class TcompTEST(object):
def __init__(self,chl_name,chl_layer,log):
self.channel_name = chl_name
self.channel_layer = chl_layer
self.logger = log
self.fsv = FSVCtrl() # 频谱仪
self.bd = None
self.bdexl = BoardExcel() # excel模板
self.th_dev = None
self.process_flat = FlatProcess()
self.process_gain = GainProcess()
self.adjust_evt = threading.Event()
self.adjust_evt.clear()
self.wait_evt = threading.Event()
self.wait_evt.clear()
self.wait_thread = PropagatingThread(target=self.check_cpu_temp)
self.wait_thread.setDaemon(True)
self.wait_thread.start()
self.adjust_thread = None
atexit.register(self.clean)
def rpt_message(self, msg):
try:
if self.channel_layer and self.channel_name:
print('rpt_msg')
async_to_sync(self.channel_layer.send)(
self.channel_name,
{
"type": "send.message",
"message": msg
}
)
except Exception as e:
print('rpt_msg error:{}'.format(e))
def clean(self):
self.fsv.close_inst()
self.bdexl.close_file()
def init_all(self, fsvconf, bdconf, thconf):
try:
fsvip = fsvconf['IP']
exlpath = fsvconf['DIR']
self.bd = BT2KHandler(**bdconf)
bip = bdconf['IP'] # 设备IP
if thconf:
self.th_dev = THDevice() # 高低温箱初始化
ret = self.bd.read_bb_sn()
if ret is None:
raise RuntimeError('no serial number or productno')
bbver, sn, productno = ret # 返回BB版本,序列号,物料号
excel_path = self.make_dirs(exlpath, sn, bbver, productno) # 复制excel模板
fsvoffset = self.read_offset(excel_path)
# for test
self.fsv.init_inst(fsvip)
self.fsv.set_offset(fsvoffset) # 设置衰减值
self.fsv.reset_fsv()
self.fsv.close_inst()
params_lst = [productno, excel_path, bip, fsvip]
self.gd_test(*params_lst, **thconf)
return True,excel_path
except Exception as e:
self.logger.error('error.{}.'.format(e))
self.rpt_message('ERROR.{}.'.format(e))
return False
finally:
self.bdexl.close_file()
self.fsv.close_inst()
def make_dirs(self, exlpath, sn, bbver, pno):
'''
根据excel测试模板复制一份excel
:param exlpath:
:return:
'''
try:
today = datetime.date.today().strftime('%y-%m-%d') # 返回字符串
dirname = os.path.dirname(exlpath)
new_path = os.path.join(dirname, today)
if sn:
new_path = os.path.join(new_path, sn)
if not os.path.exists(new_path):
os.makedirs(new_path)
# newexl_name = str(sn) + '.xlsx'
newexl_name = '1.xlsx'
end_path = os.path.join(new_path, newexl_name)
if os.path.exists(end_path):
return end_path
else:
copyfile(exlpath, end_path)
if self.bdexl.open_excel(end_path):
# 写入bb ver,serialnumber
self.bdexl.write_bbver_sn(bbver, sn)
self.bdexl.write_productno(pno)
else:
return None
return end_path
except Exception as e:
self.logger.error(e)
finally:
self.bdexl.close_file()
def gd_test(self, *args, **kwargs):
try:
thconf = kwargs
# if not thconf:
# raise ModuleNotFoundError('高低温箱没有配置项')
port = thconf.get('PORT', None)
# for test
# self.do_test(*args)
if self.th_dev.connect_th(PORT='COM{}'.format(port)):
self.logger.info('高低温箱connected**')
self.th_dev.set_fixed_mode()
self.th_dev.start_dev()
self.do_test(*args)
self.logger.debug('高低温箱20度运行')
# self.th_dev.stop_dev() # 停止运行
self.th_dev.set_temp_sv(int(20 * 10)) # 设置成20度
except modbus_tk.modbus.ModbusError as e:
self.logger.exception('{}'.format(e))
raise StopIteration('th_dev')
def do_test(self, *args):
productno, excel_path, bip, fsvip = args
if excel_path is None:
raise RuntimeError('excel does not exist!')
if not self.bd.do_set_bd():
raise RuntimeError('强建小区失败')
self.do_test_on_cellid(productno, excel_path, bip, fsvip)
self.bd.switch_reboot() # 开启检测不到采集就重启的开关
def set_bd_rf(self, freqpoint_dict):
key_bands = freqpoint_dict.keys()
for cellband in key_bands:
if 'CELL0' in cellband.upper():
cellid = '0'
self.bd.set_rf('1', 0)
else:
cellid = '1'
self.bd.set_rf('0', 0)
freq_points = freqpoint_dict[str(cellband)]
self.conf_board_on_some_freq(cellid, freq_points[0])
def do_test_on_cellid(self, productno, excel_path, bip, fsvip):
freqpoint_dict, freq_dict = self.read_boardtype(excel_path) # 返回各band的频点,频率
self.logger.debug(freqpoint_dict)
self.logger.debug(freq_dict)
power_range, test_temp, centertemp = self.read_excel_txatt_norm(excel_path) # 功率的指标[下限,标准值,上限]
self.logger.debug(power_range)
test_temp = [float(item) for item in test_temp]
centertemp = float(centertemp)
if not self.bd.do_compensation('0'):
return
# 初始化温补,频补表
self.init_flat_and_gain_comp(productno, freqpoint_dict, test_temp, centertemp, bip, excel_path)
# 打开该打开的射频开关并将档位设置成0档
self.set_bd_rf(freqpoint_dict)
self.set_cpu_temp(centertemp, 0,0)
if self.process_flat.read_and_set(freqpoint_dict, centertemp):
self.update_bb_flat_comp(productno, bip, excel_path)
if self.process_gain.read_and_set(freqpoint_dict):
self.update_bb_gain_comp(productno, bip, excel_path)
# for test
flg = self.repeat_flat_comp(centertemp, fsvip, freqpoint_dict, freq_dict, power_range, productno, bip,
excel_path)
if not flg:
self.rpt_message('基准温度补偿失败')
raise RuntimeError('基准温度补偿失败')
self.repeat_gain_comp(test_temp, centertemp, fsvip, power_range, freqpoint_dict,
freq_dict, productno, bip, excel_path)
def repeat_gain_comp(self, test_temp, centertemp, fsvip, power_range, freqpoint_dict, freq_dict,
productno, bip, excel_path):
'''
温度补偿
:return:
'''
key_bands = freqpoint_dict.keys()
target = power_range[1]
length = len(test_temp)
centeridx = test_temp.index(centertemp)
# 测试不同温度下补偿值
self.logger.debug('开始温度补偿测试')
self.rpt_message('开始温度补偿测试')
# 温度[20,10,0,-10,-20,40,50,60,70]
if centeridx >= 1:
newrange = list(range(centeridx - 1, -1, -1)) + list(range(centeridx + 1, length)) # 序号[]
else:
newrange = list(range(centeridx + 1, length))
self.logger.debug(newrange)
for index, idx in enumerate(newrange): # 按从基准温度降温到最低温度再升温度
temp = test_temp[idx] # 取温度
self.logger.debug('待测温度{}'.format(temp))
self.rpt_message('待测温度{}'.format(temp))
tempidx = self.process_gain.read_tempidx(temp)
# 取下一温度的tempidx
nexttemp = None
nexttempidx = None
if temp < centertemp:
nexttemp = int(temp) - 10 # 减10度,20,10,0,-10,-20,...
self.logger.debug('下一复制温度{}'.format(nexttemp))
nexttempidx = self.process_gain.read_tempidx(nexttemp)
else:
nexttemp = int(temp) + 10 # 加10度,40,50,60,70
nexttempidx = self.process_gain.read_tempidx(nexttemp)
self.logger.debug('下一复制温度{}'.format(nexttemp))
if temp > 0:
self.set_cpu_temp(temp - 1, 1, 1) # 低于目标温度1度即可,因为运行着温度会上升
else:
self.set_cpu_temp(temp + 1, 1, -1) # 低温时,最好高于目标温度1度,因为温度会下降
# fg = self.set_temp_comp(fsvip, target, freqpoint_dict, freq_dict, tempidx, nexttempidx)
# if not fg:
# raise RuntimeError('温度补偿失败')
# self.update_bb_gain_comp(productno, bip, excel_path)
self.logger.debug('复测{}度'.format(temp))
power_dict = dict() # {'B41':[power,power,power],'E':[power,power,power]}
d1 = dict()
try:
self.conf_device(fsvip)
for cellband in key_bands:
if 'CELL0' in cellband.upper():
cellid = '0'
self.bd.set_rf('1', 0)
else:
cellid = '1'
self.bd.set_rf('0', 0)
bandstr = cellband.split('_')[-1]
band = re.sub('\D', '', bandstr) # band的数字,1/3/41/38/39
freq_points = freqpoint_dict[str(cellband)]
freqs = freq_dict[str(cellband)]
power_dict.setdefault(cellband, [('', '')] * len(freq_points))
d1.setdefault(cellband, [''] * len(freq_points))
for ii, freq_point in enumerate(freq_points):
if not freq_point:
continue
freq = freqs[ii]
if not self.conf_board_on_some_freq(cellid, freq_point): # 设置基带板一类参数,并返回PCI
self.logger.error('设置一类参数异常')
continue
i = 0
while True:
i = i + 1
if i > 10:
self.logger.error('{}-{}温补失败'.format(temp, freq_point))
self.rpt_message('{}-{}温补失败'.format(temp, freq_point))
self.fsv.close_inst()
os.system('pause')
break
result = self.power_test_on_some_freq(cellid, fsvip, freq, power_range)
if result is None:
self.conf_board_on_some_freq(cellid, freq_point)
continue
if result[0]:
power_dict[cellband][ii] = result[1:]
break
else:
# if i > 7:
# self.logger.error('{}-{}温补失败'.format(temp, freq_point))
# self.rpt_message('{}-{}温补失败'.format(temp, freq_point))
# self.fsv.close_inst()
# os.system('pause')
# break
# for test
currenttemp = self.bd.repeat_get_temp() # 获取基带板温度
self.logger.debug('复补当前设备温度{}'.format(currenttemp))
self.rpt_message('复补当前设备温度{}'.format(currenttemp))
if abs(currenttemp - temp) >= 2:
if temp > 0:
self.set_cpu_temp(temp - 1, 1, 1)
else:
self.set_cpu_temp(temp + 1, 1, -1)
result = self.power_test_on_some_freq(cellid, fsvip, freq, power_range)
if result is None:
self.conf_board_on_some_freq(cellid, freq_point)
continue
power = result[1] # 获取功率
self.logger.debug('fsv read power={}'.format(power))
self.rpt_message('fsv read power={}'.format(power))
value = float(power) - float(target)
# if i > 1:
# value = value * 0.6
if abs(value)<=0.4:
value=0.15 if value>0 else -0.15
self.logger.debug('power-target={}'.format(value))
self.rpt_message('power-target={}'.format(value))
self.process_gain.set_bandinfo(tempidx, nexttempidx, band, freq_point,
float('%6.2f' % value))
self.update_bb_gain_comp(productno, bip, excel_path)
d1[cellband][ii] = self.process_gain.read_bandinfo(tempidx, band, freq_point)
except Exception as e:
self.logger.error(e)
self.rpt_message('ERROR:{}'.format(e))
finally:
self.fsv.close_inst()
try:
eid = (list(range(-20, 80, 10))).index(temp)
if self.bdexl.open_excel(excel_path):
self.bdexl.write_cali(eid, **d1)
self.bdexl.write_power(eid, **power_dict)
except Exception as e:
self.logger.error(e)
finally:
self.bdexl.close_file()
# 增加-30,-40度的补偿值,复制-20度的补偿值
self.process_gain.copy_30and40()
self.process_gain.copy_70()
self.update_bb_gain_comp(productno, bip, excel_path)
def update_bb_gain_comp(self, productno, bip, excel_path):
'''
将本地温补表更新到BB
:return:
'''
self.logger.debug('update_bb_gain_comp')
i = 0
while 1:
if i > 3:
raise RuntimeError('补偿文件异常')
try:
if self.bd.remove_gain_comp_json(): # 删除原gaincomp.json文件
if self.write_gain_comp_json(productno, bip, excel_path): # 写文件并上传
self.bd.refresh_comp() # 刷新
break
else:
self.reset_bd()
time.sleep(3)
i = i + 1
except Exception as e:
self.reset_bd()
i = i + 1
def update_bb_flat_comp(self, productno, bip, excel_path):
self.logger.debug('update_bb_flat_comp')
i = 0
while 1:
if i > 3:
raise RuntimeError('补偿文件异常')
try:
if self.bd.remove_flat_comp_json(): # 删除原gaincomp.json文件
if self.write_flat_comp_json(productno, bip, excel_path): # 写文件并上传
self.bd.refresh_comp() # 刷新
break
else:
self.reset_bd()
time.sleep(3)
i = i + 1
except Exception as e:
self.reset_bd()
i = i + 1
def init_flat_and_gain_comp(self, productno, freqpoint_dict, test_temp, centertemp, bip, excel_path):
'''
初始化温补,频补表到内存
:return:
'''
ret = self.bd.read_flat_and_gain_json(productno)
if ret is None:
self.process_flat.init_flat_comp(freqpoint_dict, test_temp, centertemp)
self.process_gain.init_gain_comp(freqpoint_dict, test_temp)
self.update_bb_flat_comp(productno, bip, excel_path)
self.update_bb_gain_comp(productno, bip, excel_path)
else:
fj, gj = ret
if fj is None:
self.process_flat.init_flat_comp(freqpoint_dict, test_temp, centertemp)
self.update_bb_flat_comp(productno, bip, excel_path)
else:
self.process_flat.init_comp_from_file(fj)
if gj is None:
self.process_gain.init_gain_comp(freqpoint_dict, test_temp)
self.update_bb_gain_comp(productno, bip, excel_path)
else:
self.process_gain.init_comp_from_file(gj)
def repeat_flat_comp(self, centertemp, fsvip, freqpoint_dict, freq_dict, power_range, productno, bip, excel_path):
'''
多次平坦度补偿,直到达标
:return:
'''
target = float(power_range[1])
lower = float(power_range[0]) # 下限
upper = float(power_range[2]) # 上限
freq_keys = freqpoint_dict.keys()
freq_values = freqpoint_dict.values()
tempidx = list(range(-20, 80, 10)).index(centertemp)
# self.set_flat_comp(fsvip, target, freqpoint_dict, freq_dict, productno, bip, excel_path)
# 基准温度下温补默认为0
temp_cali_dict = dict(zip(freq_keys, [[0] * len(list(freq_values)[0])] * len(freq_keys)))
power_dict = dict() # {'B41':[power,power,power],'E':[power,power,power]}
try:
self.conf_device(fsvip)
for cellband in freq_keys:
self.logger.debug('cellband={}'.format(cellband))
self.rpt_message('cellband={}'.format(cellband))
if 'CELL0' in cellband.upper():
cellid = '0'
self.bd.set_rf('1', 0)
else:
cellid = '1'
self.bd.set_rf('0', 0)
bandstr = cellband.split('_')[-1]
band = re.sub('\D', '', bandstr) # band的数字,1/3/41/38/39
freq_points = freqpoint_dict[str(cellband)]
freqs = freq_dict[str(cellband)]
power_dict.setdefault(cellband, [('', '')] * len(freq_points))
for idx, point in enumerate(freq_points):
freq = freqs[idx]
self.conf_board_on_some_freq(cellid, point) # 设置基带板频点
i = 0
while 1:
i = i + 1
if i > 9:
return False
# 复测
# for test
plst = self.get_fsv_power(fsvip, target, freq)
if plst is None:
time.sleep(10)
continue
power = float(plst) # 读取频谱仪功率
if lower <= power <= upper:
power_dict[cellband][idx] = power, 'PASS'
break
power_dict[cellband][idx] = power, 'FAIL'
delta = power - target
if abs(delta)<=0.4:
delta=0.15 if delta>0 else -0.15
self.logger.debug('flat delta={}'.format(delta))
cali = float('%.2f' % delta)
self.process_flat.set_bandinfo(band, point, cali)
# 更新设备频补补偿表
self.update_bb_flat_comp(productno, bip, excel_path)
else:
return True
except Exception as e:
self.logger.error(e)
finally:
self.fsv.close_inst()
try:
if self.bdexl.open_excel(excel_path):
self.bdexl.write_power(tempidx, **power_dict)
self.bdexl.write_cali(tempidx, **temp_cali_dict)
except Exception:
pass
finally:
self.bdexl.close_file()
def power_test_on_some_freq(self, cellid, fsvip, freq, power_range):
'''
freq:频率
power_range:功率标准[下限,理想值,上限,]
:return:
'''
lower = float(power_range[0]) # 下限
upper = float(power_range[2]) # 上限
# for test
plst = self.get_fsv_power(fsvip, float(power_range[1]), freq)
if plst is None:
return None
power = float(plst) # 读取频谱仪功率
# txatt = self.bd.read_txatt(cellid)
if power >= lower and power <= upper:
return True, power, 'PASS'
elif power > upper:
# self.bd.set_rf(cellid, 0) # 关闭射频
self.logger.error('功率{}超限'.format(power))
else:
# self.bd.set_rf(cellid, 0) # 关闭射频
self.logger.error('功率{}不达标'.format(power))
return False, power, 'FAIL'
def conf_board_on_some_freq(self, cellid, freq):
'''
基于某频点
freq:频点
:return:
'''
self.logger.debug('conf_board_on_some_freq')
try:
flag = self.bd.conf_para(cellid, freq) # 设置频点并打开功放
return flag
except Exception as e:
self.logger.error(e)
return False
def get_and_send_powercali(self, cellid, fsvip, band, freq_points, freqs, target):
'''
遍历band的三个频点,得到功率补偿,发送给BB
band:
freq_points:频点,用于发给基带板
freqs:频率,用于设置频谱仪
target:功率理想值dBm
return [[int(freq), float(cali),温度],,]
'''
temp = self.bd.repeat_get_temp() # 获取基带板温度
if temp is None:
raise IOError('get temp failed')
self.logger.debug('current temp={}'.format(temp))
for idx, point in enumerate(freq_points):
freq = freqs[idx]
self.conf_board_on_some_freq(cellid, point) # 设置基带板频点
plst = self.get_fsv_power(fsvip, target, freq)
if plst is None:
raise IOError('read fsv power failed')
power = plst
self.logger.debug('fsv read power={}'.format(power))
value = float(power) - float(target)
cali = float('%.2f' % value)
self.process_flat.set_bandinfo(band, point, cali) # 更新内存
def get_fsv_power(self, fsvip, upper, freq):
'''
读取频谱仪功率
upper:输出功率上限,用来设置ref level,ref level=upper+3
:return:
'''
i = 0
ref_level = float(upper) + 7
lowedge = float(upper) - 21 - 4
while 1:
try:
if i >= 3:
return None
i = i + 1
self.fsv.set_for_txatt(ref_level, freq)
time.sleep(1)
plst = []
j = 0
# sweep time 1s,读5次取平均值
# 12.23 频谱仪读平均值5次
while j < 1:
power = self.fsv.get_power(ref_level, freq) # 读取频谱仪功率,返回列表
self.logger.debug('get_fsv_power={}'.format(power[0]))
if power is not None:
# plst.append(power)
# for test
if float(power[0]) > lowedge:
plst.append(power)
else:
self.logger.error('before reset_bd,power={}'.format(power[0]))
self.reset_bd() # 可能设备重启了,导致输出-19以下
return None
else:
break
j = j + 1
if plst:
plst = [float(item[0]) for item in plst]
self.logger.debug('power list={}'.format(plst))
return sum(plst) / len(plst)
time.sleep(3)
except Exception as e:
self.logger.error(e)
time.sleep(3)
self.fsv.close_inst()
self.conf_device(fsvip)
time.sleep(3)
continue
def reset_bd(self):
if not self.bd.do_set_bd():
raise RuntimeError('强建小区失败')
def read_excel_txatt_norm(self, excel_path):
'''
读取excel的上下行功率,频点等参数
:param excel_path:
:return:
'''
try:
if self.bdexl.open_excel(excel_path):
normlist = self.bdexl.get_txatt_norm() # 读取输出功率标准
templist = self.bdexl.read_cpu_temp() # 读取一系列待测温度
centertemp = self.bdexl.read_cpu_center_temp() # 读取基准温度
return normlist, templist, centertemp
except Exception as e:
raise RuntimeError(e)
finally:
self.bdexl.close_file()
def read_boardtype(self, excel_path):
'''
从excel中读取board类型及主从片频点,频率
:param excel_path:
:return:
'''
try:
if self.bdexl.open_excel(excel_path):
freqpoint_dict, freq_dict = self.bdexl.get_set_condition()
return freqpoint_dict, freq_dict
except Exception as e:
raise RuntimeError('read_boardtype ERROR:{}'.format(e))
finally:
self.bdexl.close_file()
def read_offset(self, excel_path):
try:
if self.bdexl.open_excel(excel_path):
self.bdexl.get_dl_rows()
offset = self.bdexl.get_offset()
return offset
except Exception as e:
raise RuntimeError('read_offset ERROR:{}'.format(e))
finally:
self.bdexl.close_file()
def conf_device(self, fsvip):
'''
仪器初始化
:return:
'''
self.logger.debug('conf_fsv')
# for test
i = 0
while 1:
i = i + 1
if i >= 3:
self.logger.error('fsv error')
raise RuntimeError('fsv error')
try:
self.fsv.init_inst(fsvip)
time.sleep(1)
self.fsv.reset_fsv()
time.sleep(1)
except Exception as e:
self.logger.error(e)
time.sleep(10)
self.fsv.close_inst()
else:
break
def set_flat_comp(self, fsvip, target, freqpoint_dict, freq_dict, productno, bip, excel_path):
'''
平坦度补偿
:return:
'''
try:
self.logger.debug('基准平坦度补偿')
key_bands = freqpoint_dict.keys()
self.conf_device(fsvip)
for cellband in key_bands:
self.logger.debug('cellband={}'.format(cellband))
if 'CELL0' in cellband.upper():
cellid = '0'
self.bd.set_rf('1', 0)
else:
cellid = '1'
self.bd.set_rf('0', 0)
bandstr = cellband.split('_')[-1]
band = re.sub('\D', '', bandstr) # band的数字,1/3/41/38/39
freq_points = freqpoint_dict[str(cellband)]
freqs = freq_dict[str(cellband)]
self.get_and_send_powercali(cellid, fsvip, band, freq_points, freqs,
target) # 写平坦度补偿表
# 更新设备频补补偿表
self.update_bb_flat_comp(productno, bip, excel_path)
except Exception as e:
self.logger.error(e)
raise RuntimeError(e)
finally:
self.fsv.close_inst()
def set_temp_comp(self, fsvip, target, freqpoint_dict, freq_dict, tempidx, nexttempidx):
'''
温度补偿
:return:补偿值{'':[],'':[]}
'''
i = 0
while 1:
if i > 3:
return False
try:
key_bands = freqpoint_dict.keys()
self.conf_device(fsvip)
for cellband in key_bands:
self.logger.debug('cellband={}'.format(cellband))
if 'CELL0' in cellband.upper():
cellid = '0'
self.bd.set_rf('1', 0)
else:
cellid = '1'
self.bd.set_rf('0', 0)
bandstr = cellband.split('_')[-1]
band = re.sub('\D', '', bandstr) # band的数字,1/3/41/38/39
# bandinfo=self.process_gain.read_bandinfo(int(band))
freq_points = freqpoint_dict[str(cellband)]
freqs = freq_dict[str(cellband)]
for idx, point in enumerate(freq_points):
freq = freqs[idx]
self.conf_board_on_some_freq(cellid, point) # 设置基带板频点
# for test
plst = self.get_fsv_power(fsvip, target, freq)
if plst is None:
raise IOError('read fsv power failed')
power = plst
self.logger.debug('fsv read power={}'.format(power))
value = float(power) - float(target)
self.process_gain.set_bandinfo(tempidx, nexttempidx, band, point, float('%6.2f' % value))
return True
except Exception as e:
self.logger.error(e)
i = i + 1
finally:
self.fsv.close_inst()
def set_cpu_temp(self, target, bias, direction):
'''
设定设备到达某温度
target:温度
bias:偏离目标温度多少度
:return:
'''
# for test
# logger.debug('wait for test...')
# time.sleep(10)
self.logger.debug('温度设定目标{}'.format(target))
self.rpt_message('温度设定目标{}'.format(target))
# time.sleep(3)
# for test
if not self.adjust_thread or not self.adjust_thread.is_alive():
self.adjust_thread = PropagatingThread(target=self.adjust_cpu_temp, args=(target, bias, direction))
self.adjust_evt.set()
self.adjust_thread.setDaemon(True)
self.adjust_thread.start()
self.adjust_thread.join()
def write_gain_comp_json(self, productno, bip, excel_path):
'''
写文件并ftp上传给T2K
:return:
'''
myftp = MyFTP(str(bip))
try:
js = self.process_gain.get_json()
dirname = os.path.dirname(excel_path)
pno = productno
remote_file = '/mnt/flash/scbs/{}_GainComp.json'.format(pno)
local_file = os.path.join(dirname, 'GainComp.json')
with open(local_file, 'wb') as f:
f.write(json.dumps(js, indent=4, ensure_ascii=False).encode('utf-8'))
if myftp.rpt_json(local_file, remote_file):
return True
except Exception as e:
self.logger.error('write_gain_comp_json ERROR:{}'.format(e))
return False
finally:
myftp.close()
def write_flat_comp_json(self, productno, bip, excel_path):
'''
将本地频补表上传给BB
:param productno:
:param bip:
:param excel_path:
:return:
'''
myftp = MyFTP(str(bip))
try:
js = self.process_flat.get_json()
dirname = os.path.dirname(excel_path)
pno = productno
remote_file = '/mnt/flash/scbs/{}_FlatComp.json'.format(pno)
local_file = os.path.join(dirname, 'FlatComp.json')
with open(local_file, 'wb') as f:
f.write(json.dumps(js, indent=4, ensure_ascii=False).encode('utf-8'))
if myftp.rpt_json(local_file, remote_file):
return True
except Exception as e:
self.logger.error('write_flat_comp_json ERROR:{}'.format(e))
return False
finally:
myftp.close()
def check_cpu_temp(self):
'''
读取设备温度
:return:
'''
a, b, c, d, e = [-100] * 5
i = 0
MAX = 90
while True:
if i > MAX:
break
if self.wait_evt.is_set():
temp = self.bd.repeat_get_temp() # 获取基带板温度
self.logger.debug('current cpu temp={}'.format(temp))
self.rpt_message('current cpu temp={}'.format(temp))
if temp is None:
i = i + 1
continue
f = temp
a, b, c, d, e = b, c, d, e, f
if a == e or abs(a - e) <= 1:
self.logger.debug('cpu hit {}'.format(e))
self.rpt_message('cpu hit {}'.format(e))
self.wait_evt.clear()
# self.adjust_flag = True
self.adjust_evt.set()
else:
time.sleep(50)
else:
self.logger.debug('wait evt')
self.wait_evt.wait()
i = 0
a, b, c, d, e = [-100] * 5
i = i + 1
def adjust_cpu_temp(self, target, bias, direction=1):
'''
:param target:
:param bias:
:param direction: 1,表示目标温度为正,-1表示目标温度为负或0
:return:
'''
x = 0.7
y = 0.4
z = 0.7
i = 0
period = 1
oldt = None
if bias == 0:
trg = [0, 0]
else:
if direction > 0:
trg = [-2, 0]
else:
trg = [0, 2]
while True:
Tset = self.th_dev.get_temp_pv() / 10.0 # 温箱温度
self.logger.debug('th temp={}'.format(Tset))
self.logger.debug('last th setvalue={}'.format(oldt))
if oldt is not None and abs(Tset - oldt) >= 0.3:
time.sleep(30)
self.logger.debug('wait th-dev hit setvalue')
continue
if oldt is not None and self.adjust_evt.is_set():
self.wait_evt.set()
self.adjust_evt.clear()
self.logger.debug('wait adjust_evt')
self.adjust_evt.wait()
try:
if self.adjust_evt.is_set():
Tact = self.bd.repeat_get_temp() # 获取基带板温度
self.logger.debug('cpu temp={}'.format(Tact))
self.rpt_message('cpu temp={}'.format(Tact))
if Tact is None:
raise IOError('get temp failed')
delta = float(target) - float(Tact)
self.logger.debug('temp delta={}'.format(delta))
if trg[0] <= delta <= trg[1]:
i += 1
time.sleep(30)
elif abs(delta) >= 10:
i = 0
T = Tset + delta * x
oldt = T
self.logger.debug('SET T={}'.format(T))
self.th_dev.set_temp_sv(int(T * 10))
time.sleep(60 * 10)
elif abs(delta) >= 3:
i = 0
T = Tset + delta * y
oldt = T
self.logger.debug('SET T={}'.format(T))
self.th_dev.set_temp_sv(int(T * 10))
time.sleep(60 * int(period))
else:
i = 0
if delta > 0:
T = Tset + z
else:
T = Tset - z
oldt = T
self.th_dev.set_temp_sv(int(T * 10))
time.sleep(30 * 1) # 1分钟
if i >= 1:
self.logger.debug('hit target')
break
except Exception as e:
self.logger.error(e)
self.reset_bd()
|
the-stack_0_14749 | import argparse
import os
import data
import models
import visualize
def main():
parser = argparse.ArgumentParser(description='Yelp Rating Interpretation')
parser.add_argument('--n-estimators', type=int, default=100)
parser.add_argument('--criterion', type=str, default='gini',
choices=['gini', 'entropy'])
parser.add_argument('--max-depth', type=int, default=20)
parser.add_argument('--seed', type=int, default=23)
parser.add_argument('--top-n-features', type=int)
parser.add_argument('--train-datafile', type=str,
default='data/train.csv')
parser.add_argument('--test-datafile', type=str,
default='data/test.csv')
parser.add_argument('--model-path', type=str,
default='models/model.pkl')
parser.add_argument('--fig-path', type=str,
default='figure/importance.png')
args = parser.parse_args()
model = models.RatingInterpreter(n_estimators=args.n_estimators,
criterion=args.criterion,
max_depth=args.max_depth,
seed=args.seed,
top_n_features=args.top_n_features)
# if os.path.exists(args.model_path):
# model.load(args.model_path)
# else:
train_dataset = data.Dataset(args.train_datafile)
test_dataset = data.Dataset(args.test_datafile)
# acc, rmse = model.train(train_dataset, test_dataset)
acc = model.train(train_dataset, test_dataset)
model.save(args.model_path)
importances, std = model.get_importance()
# visualize.display(importances, std, acc, rmse, args.fig_path,
# top_n_features=args.top_n_features)
visualize.display(importances, std, acc, args.fig_path,
top_n_features=args.top_n_features)
if __name__ == '__main__':
main()
|
the-stack_0_14751 | # Copyright 2015 Yelp 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 collections
import socket
from paasta_tools.smartstack_tools import get_multiple_backends
def get_replication_for_services(synapse_host, synapse_port, services):
"""Returns the replication level for the provided services
This check is intended to be used with an haproxy load balancer, and
relies on the implementation details of that choice.
:param synapse_host: The hose that this check should contact for replication information.
:param synapse_port: The port number that this check should contact for replication information.
:param services: A list of strings that are the service names
that should be checked for replication.
:returns available_instance_counts: A dictionary mapping the service names
to an integer number of available
replicas
:returns None: If it cannot connect to the specified synapse host and port
"""
backends = get_multiple_backends(
services=services,
synapse_host=synapse_host,
synapse_port=synapse_port,
)
counter = collections.Counter([b['pxname'] for b in backends if backend_is_up(b)])
return dict((sn, counter[sn]) for sn in services)
def backend_is_up(backend):
"""Returns whether a server is receiving traffic in HAProxy.
:param backend: backend dict, like one of those returned by smartstack_tools.get_multiple_backends.
:returns is_up: Whether the backend is in a state that receives traffic.
"""
return str(backend['status']).startswith('UP')
def ip_port_hostname_from_svname(svname):
"""This parses the haproxy svname that smartstack creates, which is in the form ip:port_hostname.
:param svname: A string in the format ip:port_hostname
:returns ip_port_hostname: A tuple of ip, port, hostname.
"""
ip, port_hostname = svname.split(':', 1)
port, hostname = port_hostname.split('_', 1)
return ip, int(port), hostname
def get_registered_marathon_tasks(
synapse_host,
synapse_port,
service,
marathon_tasks,
):
"""Returns the marathon tasks that are registered in haproxy under a given service (nerve_ns).
:param synapse_host: The host that this check should contact for replication information.
:param synapse_port: The port that this check should contact for replication information.
:param service: A list of strings that are the service names that should be checked for replication.
:param marathon_tasks: A list of MarathonTask objects, whose tasks we will check for in the HAProxy status.
"""
backends = get_multiple_backends([service], synapse_host=synapse_host, synapse_port=synapse_port)
healthy_tasks = []
for backend, task in match_backends_and_tasks(backends, marathon_tasks):
if backend is not None and task is not None and backend['status'].startswith('UP'):
healthy_tasks.append(task)
return healthy_tasks
def match_backends_and_tasks(backends, tasks):
"""Returns tuples of matching (backend, task) pairs, as matched by IP and port. Each backend will be listed exactly
once, and each task will be listed once per port. If a backend does not match with a task, (backend, None) will
be included. If a task's port does not match with any backends, (None, task) will be included.
:param backends: An iterable of haproxy backend dictionaries, e.g. the list returned by
smartstack_tools.get_multiple_backends.
:param tasks: An iterable of MarathonTask objects.
"""
backends_by_ip_port = collections.defaultdict(list) # { (ip, port) : [backend1, backend2], ... }
backend_task_pairs = []
for backend in backends:
ip, port, _ = ip_port_hostname_from_svname(backend['svname'])
backends_by_ip_port[ip, port].append(backend)
for task in tasks:
ip = socket.gethostbyname(task.host)
for port in task.ports:
for backend in backends_by_ip_port.pop((ip, port), [None]):
backend_task_pairs.append((backend, task))
# we've been popping in the above loop, so anything left didn't match a marathon task.
for backends in backends_by_ip_port.values():
for backend in backends:
backend_task_pairs.append((backend, None))
return backend_task_pairs
|
the-stack_0_14753 | # -*- coding: ISO-8859-15 -*-
# =============================================================================
# Copyright (c) 2009 Tom Kralidis
#
# Authors : Tom Kralidis <[email protected]>
# Angelos Tzotsos <[email protected]>
#
# Contact email: [email protected]
# =============================================================================
""" ISO metadata parser """
from __future__ import (absolute_import, division, print_function)
import warnings
from owslib.etree import etree
from owslib import util
from owslib.namespaces import Namespaces
# default variables
def get_namespaces():
n = Namespaces()
ns = n.get_namespaces(["gco","gfc","gmd","gml","gml32","gmx","gts","srv","xlink"])
ns[None] = n.get_namespace("gmd")
return ns
namespaces = get_namespaces()
class MD_Metadata(object):
""" Process gmd:MD_Metadata """
def __init__(self, md=None):
if md is None:
self.xml = None
self.identifier = None
self.parentidentifier = None
self.language = None
self.dataseturi = None
self.languagecode = None
self.datestamp = None
self.charset = None
self.hierarchy = None
self.contact = []
self.datetimestamp = None
self.stdname = None
self.stdver = None
self.locales = []
self.referencesystem = None
self.identification = None
self.serviceidentification = None
self.identificationinfo = []
self.contentinfo = []
self.distribution = None
self.dataquality = None
else:
if hasattr(md, 'getroot'): # standalone document
self.xml = etree.tostring(md.getroot())
else: # part of a larger document
self.xml = etree.tostring(md)
val = md.find(util.nspath_eval('gmd:fileIdentifier/gco:CharacterString', namespaces))
self.identifier = util.testXMLValue(val)
val = md.find(util.nspath_eval('gmd:parentIdentifier/gco:CharacterString', namespaces))
self.parentidentifier = util.testXMLValue(val)
val = md.find(util.nspath_eval('gmd:language/gco:CharacterString', namespaces))
self.language = util.testXMLValue(val)
val = md.find(util.nspath_eval('gmd:dataSetURI/gco:CharacterString', namespaces))
self.dataseturi = util.testXMLValue(val)
val = md.find(util.nspath_eval('gmd:language/gmd:LanguageCode', namespaces))
self.languagecode = util.testXMLAttribute(val, 'codeListValue')
val = md.find(util.nspath_eval('gmd:dateStamp/gco:Date', namespaces))
self.datestamp = util.testXMLValue(val)
if not self.datestamp:
val = md.find(util.nspath_eval('gmd:dateStamp/gco:DateTime', namespaces))
self.datestamp = util.testXMLValue(val)
self.charset = _testCodeListValue(md.find(util.nspath_eval('gmd:characterSet/gmd:MD_CharacterSetCode', namespaces)))
self.hierarchy = _testCodeListValue(md.find(util.nspath_eval('gmd:hierarchyLevel/gmd:MD_ScopeCode', namespaces)))
self.contact = []
for i in md.findall(util.nspath_eval('gmd:contact/gmd:CI_ResponsibleParty', namespaces)):
o = CI_ResponsibleParty(i)
self.contact.append(o)
val = md.find(util.nspath_eval('gmd:dateStamp/gco:DateTime', namespaces))
self.datetimestamp = util.testXMLValue(val)
val = md.find(util.nspath_eval('gmd:metadataStandardName/gco:CharacterString', namespaces))
self.stdname = util.testXMLValue(val)
val = md.find(util.nspath_eval('gmd:metadataStandardVersion/gco:CharacterString', namespaces))
self.stdver = util.testXMLValue(val)
self.locales = []
for i in md.findall(util.nspath_eval('gmd:locale/gmd:PT_Locale', namespaces)):
self.locales.append(PT_Locale(i))
val = md.find(util.nspath_eval('gmd:referenceSystemInfo/gmd:MD_ReferenceSystem', namespaces))
if val is not None:
self.referencesystem = MD_ReferenceSystem(val)
else:
self.referencesystem = None
# TODO: merge .identificationinfo into .identification
warnings.warn(
'the .identification and .serviceidentification properties will merge into '
'.identification being a list of properties. This is currently implemented '
'in .identificationinfo. '
'Please see https://github.com/geopython/OWSLib/issues/38 for more information',
FutureWarning)
val = md.find(util.nspath_eval('gmd:identificationInfo/gmd:MD_DataIdentification', namespaces))
val2 = md.find(util.nspath_eval('gmd:identificationInfo/srv:SV_ServiceIdentification', namespaces))
if val is not None:
self.identification = MD_DataIdentification(val, 'dataset')
self.serviceidentification = None
elif val2 is not None:
self.identification = MD_DataIdentification(val2, 'service')
self.serviceidentification = SV_ServiceIdentification(val2)
else:
self.identification = None
self.serviceidentification = None
self.identificationinfo = []
for idinfo in md.findall(util.nspath_eval('gmd:identificationInfo', namespaces)):
if len(idinfo) > 0:
val = list(idinfo)[0]
tagval = util.xmltag_split(val.tag)
if tagval == 'MD_DataIdentification':
self.identificationinfo.append(MD_DataIdentification(val, 'dataset'))
elif tagval == 'MD_ServiceIdentification':
self.identificationinfo.append(MD_DataIdentification(val, 'service'))
elif tagval == 'SV_ServiceIdentification':
self.identificationinfo.append(SV_ServiceIdentification(val))
self.contentinfo = []
for contentinfo in md.findall(util.nspath_eval('gmd:contentInfo/gmd:MD_FeatureCatalogueDescription', namespaces)):
self.contentinfo.append(MD_FeatureCatalogueDescription(contentinfo))
val = md.find(util.nspath_eval('gmd:distributionInfo/gmd:MD_Distribution', namespaces))
if val is not None:
self.distribution = MD_Distribution(val)
else:
self.distribution = None
val = md.find(util.nspath_eval('gmd:dataQualityInfo/gmd:DQ_DataQuality', namespaces))
if val is not None:
self.dataquality = DQ_DataQuality(val)
else:
self.dataquality = None
def get_default_locale(self):
""" get default gmd:PT_Locale based on gmd:language """
for loc in self.locales:
if loc.languagecode == self.language:
return loc
return None
class PT_Locale(object):
""" process PT_Locale """
def __init__(self, md=None):
if md is None:
self.id = None
self.languagecode = None
self.charset = None
else:
self.id = md.attrib.get('id')
self.languagecode = md.find(util.nspath_eval('gmd:languageCode/gmd:LanguageCode', namespaces)).attrib.get('codeListValue')
self.charset = md.find(util.nspath_eval('gmd:characterEncoding/gmd:MD_CharacterSetCode', namespaces)).attrib.get('codeListValue')
class CI_Date(object):
""" process CI_Date """
def __init__(self, md=None):
if md is None:
self.date = None
self.type = None
else:
val = md.find(util.nspath_eval('gmd:date/gco:Date', namespaces))
if val is not None:
self.date = util.testXMLValue(val)
else:
val = md.find(util.nspath_eval('gmd:date/gco:DateTime', namespaces))
if val is not None:
self.date = util.testXMLValue(val)
else:
self.date = None
val = md.find(util.nspath_eval('gmd:dateType/gmd:CI_DateTypeCode', namespaces))
self.type = _testCodeListValue(val)
class CI_ResponsibleParty(object):
""" process CI_ResponsibleParty """
def __init__(self, md=None):
if md is None:
self.name = None
self.organization = None
self.position = None
self.phone = None
self.fax = None
self.address = None
self.city = None
self.region = None
self.postcode = None
self.country = None
self.email = None
self.onlineresource = None
self.role = None
else:
val = md.find(util.nspath_eval('gmd:individualName/gco:CharacterString', namespaces))
self.name = util.testXMLValue(val)
val = md.find(util.nspath_eval('gmd:organisationName/gco:CharacterString', namespaces))
self.organization = util.testXMLValue(val)
val = md.find(util.nspath_eval('gmd:positionName/gco:CharacterString', namespaces))
self.position = util.testXMLValue(val)
val = md.find(util.nspath_eval('gmd:contactInfo/gmd:CI_Contact/gmd:phone/gmd:CI_Telephone/gmd:voice/gco:CharacterString', namespaces))
self.phone = util.testXMLValue(val)
val = md.find(util.nspath_eval('gmd:contactInfo/gmd:CI_Contact/gmd:phone/gmd:CI_Telephone/gmd:facsimile/gco:CharacterString', namespaces))
self.fax = util.testXMLValue(val)
val = md.find(util.nspath_eval('gmd:contactInfo/gmd:CI_Contact/gmd:address/gmd:CI_Address/gmd:deliveryPoint/gco:CharacterString', namespaces))
self.address = util.testXMLValue(val)
val = md.find(util.nspath_eval('gmd:contactInfo/gmd:CI_Contact/gmd:address/gmd:CI_Address/gmd:city/gco:CharacterString', namespaces))
self.city = util.testXMLValue(val)
val = md.find(util.nspath_eval('gmd:contactInfo/gmd:CI_Contact/gmd:address/gmd:CI_Address/gmd:administrativeArea/gco:CharacterString', namespaces))
self.region = util.testXMLValue(val)
val = md.find(util.nspath_eval('gmd:contactInfo/gmd:CI_Contact/gmd:address/gmd:CI_Address/gmd:postalCode/gco:CharacterString', namespaces))
self.postcode = util.testXMLValue(val)
val = md.find(util.nspath_eval('gmd:contactInfo/gmd:CI_Contact/gmd:address/gmd:CI_Address/gmd:country/gco:CharacterString', namespaces))
self.country = util.testXMLValue(val)
val = md.find(util.nspath_eval('gmd:contactInfo/gmd:CI_Contact/gmd:address/gmd:CI_Address/gmd:electronicMailAddress/gco:CharacterString', namespaces))
self.email = util.testXMLValue(val)
val = md.find(util.nspath_eval('gmd:contactInfo/gmd:CI_Contact/gmd:onlineResource/gmd:CI_OnlineResource', namespaces))
if val is not None:
self.onlineresource = CI_OnlineResource(val)
else:
self.onlineresource = None
self.role = _testCodeListValue(md.find(util.nspath_eval('gmd:role/gmd:CI_RoleCode', namespaces)))
class MD_Keywords(object):
"""
Class for the metadata MD_Keywords element
"""
def __init__(self, md=None):
if md is None:
self.keywords = []
self.type = None
self.thesaurus = None
self.kwdtype_codeList = 'http://standards.iso.org/ittf/PubliclyAvailableStandards/ISO_19139_Schemas/resources/codelist/gmxCodelists.xml#MD_KeywordTypeCode'
else:
self.keywords = []
val = md.findall(util.nspath_eval('gmd:keyword/gco:CharacterString', namespaces))
for word in val:
self.keywords.append(util.testXMLValue(word))
self.type = None
val = md.find(util.nspath_eval('gmd:type/gmd:MD_KeywordTypeCode', namespaces))
self.type = util.testXMLAttribute(val, 'codeListValue')
self.thesaurus = None
val = md.find(util.nspath_eval('gmd:thesaurusName/gmd:CI_Citation', namespaces))
if val is not None:
self.thesaurus = {}
thesaurus = val.find(util.nspath_eval('gmd:title/gco:CharacterString', namespaces))
self.thesaurus['title'] = util.testXMLValue(thesaurus)
thesaurus = val.find(util.nspath_eval('gmd:date/gmd:CI_Date/gmd:date/gco:Date', namespaces))
self.thesaurus['date'] = util.testXMLValue(thesaurus)
thesaurus = val.find(util.nspath_eval('gmd:date/gmd:CI_Date/gmd:dateType/gmd:CI_DateTypeCode', namespaces))
self.thesaurus['datetype'] = util.testXMLAttribute(thesaurus, 'codeListValue')
class MD_DataIdentification(object):
""" process MD_DataIdentification """
def __init__(self, md=None, identtype=None):
if md is None:
self.identtype = None
self.title = None
self.alternatetitle = None
self.aggregationinfo = None
self.uricode = []
self.uricodespace = []
self.date = []
self.datetype = []
self.uselimitation = []
self.uselimitation_url = []
self.accessconstraints = []
self.classification = []
self.otherconstraints = []
self.securityconstraints = []
self.useconstraints = []
self.denominators = []
self.distance = []
self.uom = []
self.resourcelanguage = []
self.resourcelanguagecode = []
self.creator = []
self.publisher = []
self.contributor = []
self.edition = None
self.abstract = None
self.abstract_url = None
self.purpose = None
self.status = None
self.contact = []
self.keywords = []
self.keywords2 = []
self.topiccategory = []
self.supplementalinformation = None
self.extent = None
self.bbox = None
self.temporalextent_start = None
self.temporalextent_end = None
self.spatialrepresentationtype = []
else:
self.identtype = identtype
val = md.find(util.nspath_eval('gmd:citation/gmd:CI_Citation/gmd:title/gco:CharacterString', namespaces))
self.title = util.testXMLValue(val)
val = md.find(util.nspath_eval('gmd:citation/gmd:CI_Citation/gmd:alternateTitle/gco:CharacterString', namespaces))
self.alternatetitle = util.testXMLValue(val)
val = md.find(util.nspath_eval('gmd:aggregationInfo', namespaces))
self.aggregationinfo = util.testXMLValue(val)
self.uricode = []
for i in md.findall(util.nspath_eval('gmd:citation/gmd:CI_Citation/gmd:identifier/gmd:RS_Identifier/gmd:code/gco:CharacterString', namespaces)) + \
md.findall(util.nspath_eval('gmd:citation/gmd:CI_Citation/gmd:identifier/gmd:MD_Identifier/gmd:code/gco:CharacterString', namespaces)):
val = util.testXMLValue(i)
if val is not None:
self.uricode.append(val)
self.uricodespace = []
for i in md.findall(util.nspath_eval('gmd:citation/gmd:CI_Citation/gmd:identifier/gmd:RS_Identifier/gmd:codeSpace/gco:CharacterString', namespaces)):
val = util.testXMLValue(i)
if val is not None:
self.uricodespace.append(val)
self.date = []
self.datetype = []
for i in md.findall(util.nspath_eval('gmd:citation/gmd:CI_Citation/gmd:date/gmd:CI_Date', namespaces)):
self.date.append(CI_Date(i))
self.uselimitation = []
self.uselimitation_url = []
for i in \
md.findall(util.nspath_eval('gmd:resourceConstraints/gmd:MD_LegalConstraints/gmd:useLimitation/gco:CharacterString', namespaces)) + \
md.findall(util.nspath_eval('gmd:resourceConstraints/gmd:MD_Constraints/gmd:useLimitation/gco:CharacterString', namespaces)):
val = util.testXMLValue(i)
if val is not None:
self.uselimitation.append(val)
for i in \
md.findall(util.nspath_eval('gmd:resourceConstraints/gmd:MD_LegalConstraints/gmd:useLimitation/gmx:Anchor', namespaces)) + \
md.findall(util.nspath_eval('gmd:resourceConstraints/gmd:MD_Constraints/gmd:useLimitation/gmx:Anchor', namespaces)):
val = util.testXMLValue(i)
val1 = i.attrib.get(util.nspath_eval('xlink:href', namespaces))
if val is not None:
self.uselimitation.append(val)
self.uselimitation_url.append(val1)
self.accessconstraints = []
for i in md.findall(util.nspath_eval('gmd:resourceConstraints/gmd:MD_LegalConstraints/gmd:accessConstraints/gmd:MD_RestrictionCode', namespaces)):
val = _testCodeListValue(i)
if val is not None:
self.accessconstraints.append(val)
self.classification = []
for i in md.findall(util.nspath_eval('gmd:resourceConstraints/gmd:MD_LegalConstraints/gmd:accessConstraints/gmd:MD_ClassificationCode', namespaces)):
val = _testCodeListValue(i)
if val is not None:
self.classification.append(val)
self.otherconstraints = []
for i in md.findall(util.nspath_eval('gmd:resourceConstraints/gmd:MD_LegalConstraints/gmd:otherConstraints/gco:CharacterString', namespaces)):
val = util.testXMLValue(i)
if val is not None:
self.otherconstraints.append(val)
self.securityconstraints = []
for i in md.findall(util.nspath_eval('gmd:resourceConstraints/gmd:MD_SecurityConstraints/gmd:classification/gmd:MD_ClassificationCode', namespaces)):
val = _testCodeListValue(i)
if val is not None:
self.securityconstraints.append(val)
self.useconstraints = []
for i in md.findall(util.nspath_eval('gmd:resourceConstraints/gmd:MD_LegalConstraints/gmd:useConstraints/gmd:MD_RestrictionCode', namespaces)):
val = _testCodeListValue(i)
if val is not None:
self.useconstraints.append(val)
self.denominators = []
for i in md.findall(util.nspath_eval('gmd:spatialResolution/gmd:MD_Resolution/gmd:equivalentScale/gmd:MD_RepresentativeFraction/gmd:denominator/gco:Integer', namespaces)):
val = util.testXMLValue(i)
if val is not None:
self.denominators.append(val)
self.distance = []
self.uom = []
for i in md.findall(util.nspath_eval('gmd:spatialResolution/gmd:MD_Resolution/gmd:distance/gco:Distance', namespaces)):
val = util.testXMLValue(i)
if val is not None:
self.distance.append(val)
self.uom.append(i.get("uom"))
self.resourcelanguagecode = []
for i in md.findall(util.nspath_eval('gmd:language/gmd:LanguageCode', namespaces)):
val = _testCodeListValue(i)
if val is not None:
self.resourcelanguagecode.append(val)
self.resourcelanguage = []
for i in md.findall(util.nspath_eval('gmd:language/gco:CharacterString', namespaces)):
val = util.testXMLValue(i)
if val is not None:
self.resourcelanguage.append(val)
self.creator = []
self.publisher = []
self.contributor = []
for val in md.findall(util.nspath_eval('gmd:pointOfContact/gmd:CI_ResponsibleParty', namespaces)):
role = val.find(util.nspath_eval('gmd:role/gmd:CI_RoleCode', namespaces))
if role is not None:
clv = _testCodeListValue(role)
rp = CI_ResponsibleParty(val)
if clv == 'originator':
self.creator.append(rp)
elif clv == 'publisher':
self.publisher.append(rp)
elif clv == 'author':
self.contributor.append(rp)
val = md.find(util.nspath_eval('gmd:edition/gco:CharacterString', namespaces))
self.edition = util.testXMLValue(val)
val = md.find(util.nspath_eval('gmd:abstract/gco:CharacterString', namespaces))
self.abstract = util.testXMLValue(val)
val = md.find(util.nspath_eval('gmd:abstract/gmx:Anchor', namespaces))
self.abstract_url = None
if val is not None:
self.abstract = util.testXMLValue(val)
self.abstract_url = val.attrib.get(util.nspath_eval('xlink:href', namespaces))
val = md.find(util.nspath_eval('gmd:purpose/gco:CharacterString', namespaces))
self.purpose = util.testXMLValue(val)
self.status = _testCodeListValue(md.find(util.nspath_eval('gmd:status/gmd:MD_ProgressCode', namespaces)))
self.contact = []
for i in md.findall(util.nspath_eval('gmd:pointOfContact/gmd:CI_ResponsibleParty', namespaces)):
o = CI_ResponsibleParty(i)
self.contact.append(o)
self.spatialrepresentationtype = []
for val in md.findall(util.nspath_eval('gmd:spatialRepresentationType/gmd:MD_SpatialRepresentationTypeCode', namespaces)):
val = util.testXMLAttribute(val, 'codeListValue')
if val:
self.spatialrepresentationtype.append(val)
warnings.warn(
'The .keywords and .keywords2 properties will merge into the '
'.keywords property in the future, with .keywords becoming a list '
'of MD_Keywords instances. This is currently implemented in .keywords2. '
'Please see https://github.com/geopython/OWSLib/issues/301 for more information',
FutureWarning)
self.keywords = []
for i in md.findall(util.nspath_eval('gmd:descriptiveKeywords', namespaces)):
mdkw = {}
mdkw['type'] = _testCodeListValue(i.find(util.nspath_eval('gmd:MD_Keywords/gmd:type/gmd:MD_KeywordTypeCode', namespaces)))
mdkw['thesaurus'] = {}
val = i.find(util.nspath_eval('gmd:MD_Keywords/gmd:thesaurusName/gmd:CI_Citation/gmd:title/gco:CharacterString', namespaces))
mdkw['thesaurus']['title'] = util.testXMLValue(val)
val = i.find(util.nspath_eval('gmd:MD_Keywords/gmd:thesaurusName/gmd:CI_Citation/gmd:date/gmd:CI_Date/gmd:date/gco:Date', namespaces))
mdkw['thesaurus']['date'] = util.testXMLValue(val)
val = i.find(util.nspath_eval('gmd:MD_Keywords/gmd:thesaurusName/gmd:CI_Citation/gmd:date/gmd:CI_Date/gmd:dateType/gmd:CI_DateTypeCode', namespaces))
mdkw['thesaurus']['datetype'] = util.testXMLAttribute(val, 'codeListValue')
mdkw['keywords'] = []
for k in i.findall(util.nspath_eval('gmd:MD_Keywords/gmd:keyword', namespaces)):
val = k.find(util.nspath_eval('gco:CharacterString', namespaces))
if val is not None:
val2 = util.testXMLValue(val)
if val2 is not None:
mdkw['keywords'].append(val2)
self.keywords.append(mdkw)
self.keywords2 = []
for mdkw in md.findall(util.nspath_eval('gmd:descriptiveKeywords/gmd:MD_Keywords', namespaces)):
self.keywords2.append(MD_Keywords(mdkw))
self.topiccategory = []
for i in md.findall(util.nspath_eval('gmd:topicCategory/gmd:MD_TopicCategoryCode', namespaces)):
val = util.testXMLValue(i)
if val is not None:
self.topiccategory.append(val)
val = md.find(util.nspath_eval('gmd:supplementalInformation/gco:CharacterString', namespaces))
self.supplementalinformation = util.testXMLValue(val)
# There may be multiple geographicElement, create an extent
# from the one containing either an EX_GeographicBoundingBox or EX_BoundingPolygon.
# The schema also specifies an EX_GeographicDescription. This is not implemented yet.
val = None
val2 = None
val3 = None
extents = md.findall(util.nspath_eval('gmd:extent', namespaces))
extents.extend(md.findall(util.nspath_eval('srv:extent', namespaces)))
for extent in extents:
if val is None:
for e in extent.findall(util.nspath_eval('gmd:EX_Extent/gmd:geographicElement', namespaces)):
if e.find(util.nspath_eval('gmd:EX_GeographicBoundingBox', namespaces)) is not None or e.find(util.nspath_eval('gmd:EX_BoundingPolygon', namespaces)) is not None:
val = e
break
self.extent = EX_Extent(val)
self.bbox = self.extent.boundingBox # for backwards compatibility
if val2 is None:
val2 = extent.find(util.nspath_eval('gmd:EX_Extent/gmd:temporalElement/gmd:EX_TemporalExtent/gmd:extent/gml:TimePeriod/gml:beginPosition', namespaces))
if val2 is None:
val2 = extent.find(util.nspath_eval('gmd:EX_Extent/gmd:temporalElement/gmd:EX_TemporalExtent/gmd:extent/gml32:TimePeriod/gml32:beginPosition', namespaces))
self.temporalextent_start = util.testXMLValue(val2)
if val3 is None:
val3 = extent.find(util.nspath_eval('gmd:EX_Extent/gmd:temporalElement/gmd:EX_TemporalExtent/gmd:extent/gml:TimePeriod/gml:endPosition', namespaces))
if val3 is None:
val3 = extent.find(util.nspath_eval('gmd:EX_Extent/gmd:temporalElement/gmd:EX_TemporalExtent/gmd:extent/gml32:TimePeriod/gml32:endPosition', namespaces))
self.temporalextent_end = util.testXMLValue(val3)
class MD_Distributor(object):
""" process MD_Distributor """
def __init__(self, md=None):
if md is None:
self.contact = None
self.online = []
else:
self.contact = None
val = md.find(util.nspath_eval('gmd:MD_Distributor/gmd:distributorContact/gmd:CI_ResponsibleParty', namespaces))
if val is not None:
self.contact = CI_ResponsibleParty(val)
self.online = []
for ol in md.findall(util.nspath_eval('gmd:MD_Distributor/gmd:distributorTransferOptions/gmd:MD_DigitalTransferOptions/gmd:onLine/gmd:CI_OnlineResource', namespaces)):
self.online.append(CI_OnlineResource(ol))
class MD_Distribution(object):
""" process MD_Distribution """
def __init__(self, md=None):
if md is None:
self.format = None
self.version = None
self.distributor = []
self.online = []
pass
else:
val = md.find(util.nspath_eval('gmd:distributionFormat/gmd:MD_Format/gmd:name/gco:CharacterString', namespaces))
self.format = util.testXMLValue(val)
val = md.find(util.nspath_eval('gmd:distributionFormat/gmd:MD_Format/gmd:version/gco:CharacterString', namespaces))
self.version = util.testXMLValue(val)
self.distributor = []
for dist in md.findall(util.nspath_eval('gmd:distributor', namespaces)):
self.distributor.append(MD_Distributor(dist))
self.online = []
for ol in md.findall(util.nspath_eval('gmd:transferOptions/gmd:MD_DigitalTransferOptions/gmd:onLine/gmd:CI_OnlineResource', namespaces)):
self.online.append(CI_OnlineResource(ol))
class DQ_DataQuality(object):
''' process DQ_DataQuality'''
def __init__(self, md=None):
if md is None:
self.conformancetitle = []
self.conformancedate = []
self.conformancedatetype = []
self.conformancedegree = []
self.lineage = None
self.lineage_url = None
self.specificationtitle = None
self.specificationdate = []
else:
self.conformancetitle = []
for i in md.findall(util.nspath_eval('gmd:report/gmd:DQ_DomainConsistency/gmd:result/gmd:DQ_ConformanceResult/gmd:specification/gmd:CI_Citation/gmd:title/gco:CharacterString', namespaces)):
val = util.testXMLValue(i)
if val is not None:
self.conformancetitle.append(val)
self.conformancedate = []
for i in md.findall(util.nspath_eval('gmd:report/gmd:DQ_DomainConsistency/gmd:result/gmd:DQ_ConformanceResult/gmd:specification/gmd:CI_Citation/gmd:date/gmd:CI_Date/gmd:date/gco:Date', namespaces)):
val = util.testXMLValue(i)
if val is not None:
self.conformancedate.append(val)
self.conformancedatetype = []
for i in md.findall(util.nspath_eval('gmd:report/gmd:DQ_DomainConsistency/gmd:result/gmd:DQ_ConformanceResult/gmd:specification/gmd:CI_Citation/gmd:date/gmd:CI_Date/gmd:dateType/gmd:CI_DateTypeCode', namespaces)):
val = _testCodeListValue(i)
if val is not None:
self.conformancedatetype.append(val)
self.conformancedegree = []
for i in md.findall(util.nspath_eval('gmd:report/gmd:DQ_DomainConsistency/gmd:result/gmd:DQ_ConformanceResult/gmd:pass/gco:Boolean', namespaces)):
val = util.testXMLValue(i)
if val is not None:
self.conformancedegree.append(val)
val = md.find(util.nspath_eval('gmd:lineage/gmd:LI_Lineage/gmd:statement/gco:CharacterString', namespaces))
self.lineage = util.testXMLValue(val)
val = md.find(util.nspath_eval('gmd:lineage/gmd:LI_Lineage/gmd:statement/gmx:Anchor', namespaces))
if val is not None:
self.lineage = util.testXMLValue(val)
self.lineage_url = val.attrib.get(util.nspath_eval('xlink:href', namespaces))
val = md.find(util.nspath_eval('gmd:report/gmd:DQ_DomainConsistency/gmd:result/gmd:DQ_ConformanceResult/gmd:specification/gmd:CI_Citation/gmd:title/gco:CharacterString', namespaces))
self.specificationtitle = util.testXMLValue(val)
self.specificationdate = []
for i in md.findall(util.nspath_eval('gmd:report/gmd:DQ_DomainConsistency/gmd:result/gmd:DQ_ConformanceResult/gmd:specification/gmd:CI_Citation/gmd:date/gmd:CI_Date', namespaces)):
val = util.testXMLValue(i)
if val is not None:
self.specificationdate.append(val)
class SV_ServiceIdentification(object):
""" process SV_ServiceIdentification """
def __init__(self, md=None):
if md is None:
self.title = None
self.abstract = None
self.contact = None
self.identtype = 'service'
self.type = None
self.version = None
self.fees = None
self.bbox = None
self.couplingtype = None
self.operations = []
self.operateson = []
else:
val = md.find(util.nspath_eval('gmd:citation/gmd:CI_Citation/gmd:title/gco:CharacterString', namespaces))
self.title=util.testXMLValue(val)
val = md.find(util.nspath_eval('gmd:abstract/gco:CharacterString', namespaces))
self.abstract = util.testXMLValue(val)
self.contact = None
val = md.find(util.nspath_eval('gmd:citation/gmd:CI_Citation/gmd:citedResponsibleParty/gmd:CI_ResponsibleParty', namespaces))
if val is not None:
self.contact = CI_ResponsibleParty(val)
self.identtype = 'service'
val = md.find(util.nspath_eval('srv:serviceType/gco:LocalName', namespaces))
self.type = util.testXMLValue(val)
val = md.find(util.nspath_eval('srv:serviceTypeVersion/gco:CharacterString', namespaces))
self.version = util.testXMLValue(val)
val = md.find(util.nspath_eval('srv:accessProperties/gmd:MD_StandardOrderProcess/gmd:fees/gco:CharacterString', namespaces))
self.fees = util.testXMLValue(val)
val = md.find(util.nspath_eval('srv:extent/gmd:EX_Extent', namespaces))
if val is not None:
self.bbox = EX_Extent(val)
else:
self.bbox = None
self.couplingtype = _testCodeListValue(md.find(util.nspath_eval('gmd:couplingType/gmd:SV_CouplingType', namespaces)))
self.operations = []
for i in md.findall(util.nspath_eval('srv:containsOperations', namespaces)):
tmp = {}
val = i.find(util.nspath_eval('srv:SV_OperationMetadata/srv:operationName/gco:CharacterString', namespaces))
tmp['name'] = util.testXMLValue(val)
tmp['dcplist'] = []
for d in i.findall(util.nspath_eval('srv:SV_OperationMetadata/srv:DCP', namespaces)):
tmp2 = _testCodeListValue(d.find(util.nspath_eval('srv:DCPList', namespaces)))
tmp['dcplist'].append(tmp2)
tmp['connectpoint'] = []
for d in i.findall(util.nspath_eval('srv:SV_OperationMetadata/srv:connectPoint', namespaces)):
tmp3 = d.find(util.nspath_eval('gmd:CI_OnlineResource', namespaces))
tmp['connectpoint'].append(CI_OnlineResource(tmp3))
self.operations.append(tmp)
self.operateson = []
for i in md.findall(util.nspath_eval('srv:operatesOn', namespaces)):
tmp = {}
tmp['uuidref'] = i.attrib.get('uuidref')
tmp['href'] = i.attrib.get(util.nspath_eval('xlink:href', namespaces))
tmp['title'] = i.attrib.get(util.nspath_eval('xlink:title', namespaces))
self.operateson.append(tmp)
class CI_OnlineResource(object):
""" process CI_OnlineResource """
def __init__(self,md=None):
if md is None:
self.url = None
self.protocol = None
self.name = None
self.description = None
self.function = None
else:
val = md.find(util.nspath_eval('gmd:linkage/gmd:URL', namespaces))
self.url = util.testXMLValue(val)
val = md.find(util.nspath_eval('gmd:protocol/gco:CharacterString', namespaces))
self.protocol = util.testXMLValue(val)
val = md.find(util.nspath_eval('gmd:name/gco:CharacterString', namespaces))
self.name = util.testXMLValue(val)
val = md.find(util.nspath_eval('gmd:description/gco:CharacterString', namespaces))
self.description = util.testXMLValue(val)
self.function = _testCodeListValue(md.find(util.nspath_eval('gmd:function/gmd:CI_OnLineFunctionCode', namespaces)))
class EX_GeographicBoundingBox(object):
def __init__(self, md=None):
if md is None:
self.minx = None
self.maxx = None
self.miny = None
self.maxy = None
else:
val = md.find(util.nspath_eval('gmd:westBoundLongitude/gco:Decimal', namespaces))
self.minx = util.testXMLValue(val)
val = md.find(util.nspath_eval('gmd:eastBoundLongitude/gco:Decimal', namespaces))
self.maxx = util.testXMLValue(val)
val = md.find(util.nspath_eval('gmd:southBoundLatitude/gco:Decimal', namespaces))
self.miny = util.testXMLValue(val)
val = md.find(util.nspath_eval('gmd:northBoundLatitude/gco:Decimal', namespaces))
self.maxy = util.testXMLValue(val)
class EX_Polygon(object):
def __init__(self, md=None):
if md is None:
self.exterior_ring = None
self.interior_rings = []
else:
linear_ring = md.find(util.nspath_eval('gml32:Polygon/gml32:exterior/gml32:LinearRing', namespaces))
if linear_ring is not None:
self.exterior_ring = self._coordinates_for_ring(linear_ring)
interior_ring_elements = md.findall(util.nspath_eval('gml32:Polygon/gml32:interior', namespaces))
self.interior_rings = []
for iring_element in interior_ring_elements:
linear_ring = iring_element.find(util.nspath_eval('gml32:LinearRing', namespaces))
self.interior_rings.append(self._coordinates_for_ring(linear_ring))
def _coordinates_for_ring(self, linear_ring):
coordinates = []
positions = linear_ring.findall(util.nspath_eval('gml32:pos', namespaces))
for pos in positions:
tokens = pos.text.split()
coords = tuple([float(t) for t in tokens])
coordinates.append(coords)
return coordinates
class EX_GeographicBoundingPolygon(object):
def __init__(self, md=None):
if md is None:
self.is_extent = None
self.polygons = []
else:
val = md.find(util.nspath_eval('gmd:extentTypeCode', namespaces))
self.is_extent = util.testXMLValue(val)
md_polygons = md.findall(util.nspath_eval('gmd:polygon', namespaces))
self.polygons = []
for val in md_polygons:
self.polygons.append(EX_Polygon(val))
class EX_Extent(object):
""" process EX_Extent """
def __init__(self, md=None):
if md is None:
self.boundingBox = None
self.boundingPolygon = None
self.description_code = None
else:
self.boundingBox = None
self.boundingPolygon = None
if md is not None:
bboxElement = md.find(util.nspath_eval('gmd:EX_GeographicBoundingBox', namespaces))
if bboxElement is not None:
self.boundingBox = EX_GeographicBoundingBox(bboxElement)
polygonElement = md.find(util.nspath_eval('gmd:EX_BoundingPolygon', namespaces))
if polygonElement is not None:
self.boundingPolygon = EX_GeographicBoundingPolygon(polygonElement)
val = md.find(util.nspath_eval('gmd:EX_GeographicDescription/gmd:geographicIdentifier/gmd:MD_Identifier/gmd:code/gco:CharacterString', namespaces))
self.description_code = util.testXMLValue(val)
class MD_ReferenceSystem(object):
""" process MD_ReferenceSystem """
def __init__(self, md=None):
if md is None:
self.code = None
self.codeSpace = None
self.version = None
else:
val = md.find(util.nspath_eval('gmd:referenceSystemIdentifier/gmd:RS_Identifier/gmd:code/gco:CharacterString', namespaces))
if val is not None:
self.code = util.testXMLValue(val)
else:
self.code = None
val = md.find(util.nspath_eval('gmd:referenceSystemIdentifier/gmd:RS_Identifier/gmd:codeSpace/gco:CharacterString', namespaces))
if val is not None:
self.codeSpace = util.testXMLValue(val)
else:
self.codeSpace = None
val = md.find(util.nspath_eval('gmd:referenceSystemIdentifier/gmd:RS_Identifier/gmd:version/gco:CharacterString', namespaces))
if val is not None:
self.version = util.testXMLValue(val)
else:
self.version = None
def _testCodeListValue(elpath):
""" get gco:CodeListValue_Type attribute, else get text content """
if elpath is not None: # try to get @codeListValue
val = util.testXMLValue(elpath.attrib.get('codeListValue'), True)
if val is not None:
return val
else: # see if there is element text
return util.testXMLValue(elpath)
else:
return None
class CodelistCatalogue(object):
""" process CT_CodelistCatalogue """
def __init__(self, ct):
val = ct.find(util.nspath_eval('gmx:name/gco:CharacterString', namespaces))
self.name = util.testXMLValue(val)
val = ct.find(util.nspath_eval('gmx:scope/gco:CharacterString', namespaces))
self.scope = util.testXMLValue(val)
val = ct.find(util.nspath_eval('gmx:fieldOfApplication/gco:CharacterString', namespaces))
self.fieldapp = util.testXMLValue(val)
val = ct.find(util.nspath_eval('gmx:versionNumber/gco:CharacterString', namespaces))
self.version = util.testXMLValue(val)
val = ct.find(util.nspath_eval('gmx:versionDate/gco:Date', namespaces))
self.date = util.testXMLValue(val)
self.dictionaries = {}
for i in ct.findall(util.nspath_eval('gmx:codelistItem/gmx:CodeListDictionary', namespaces)):
id = i.attrib.get(util.nspath_eval('gml32:id', namespaces))
self.dictionaries[id] = {}
val = i.find(util.nspath_eval('gml32:description', namespaces))
self.dictionaries[id]['description'] = util.testXMLValue(val)
val = i.find(util.nspath_eval('gml32:identifier', namespaces))
self.dictionaries[id]['identifier'] = util.testXMLValue(val)
self.dictionaries[id]['entries'] = {}
for j in i.findall(util.nspath_eval('gmx:codeEntry', namespaces)):
id2 = j.find(util.nspath_eval('gmx:CodeDefinition', namespaces)).attrib.get(util.nspath_eval('gml32:id', namespaces))
self.dictionaries[id]['entries'][id2] = {}
val = j.find(util.nspath_eval('gmx:CodeDefinition/gml32:description', namespaces))
self.dictionaries[id]['entries'][id2]['description'] = util.testXMLValue(val)
val = j.find(util.nspath_eval('gmx:CodeDefinition/gml32:identifier', namespaces))
self.dictionaries[id]['entries'][id2]['identifier'] = util.testXMLValue(val)
val = j.find(util.nspath_eval('gmx:CodeDefinition', namespaces)).attrib.get('codeSpace')
self.dictionaries[id]['entries'][id2]['codespace'] = util.testXMLValue(val, True)
def getcodelistdictionaries(self):
return list(self.dictionaries.keys())
def getcodedefinitionidentifiers(self, cdl):
if cdl in self.dictionaries:
ids = []
for i in self.dictionaries[cdl]['entries']:
ids.append(self.dictionaries[cdl]['entries'][i]['identifier'])
return ids
else:
return None
class MD_FeatureCatalogueDescription(object):
"""Process gmd:MD_FeatureCatalogueDescription"""
def __init__(self, fcd=None):
if fcd is None:
self.xml = None
self.compliancecode = None
self.language = []
self.includedwithdataset = None
self.featuretypenames = []
self.featurecatalogues = []
else:
if hasattr(fcd, 'getroot'): # standalone document
self.xml = etree.tostring(fcd.getroot())
else: # part of a larger document
self.xml = etree.tostring(fcd)
self.compliancecode = None
val = fcd.find(util.nspath_eval('gmd:complianceCode/gco:Boolean', namespaces))
val = util.testXMLValue(val)
if val is not None:
self.compliancecode = util.getTypedValue('boolean', val)
self.language = []
for i in fcd.findall(util.nspath_eval('gmd:language/gco:CharacterString', namespaces)):
val = util.testXMLValue(i)
if val is not None:
self.language.append(val)
self.includedwithdataset = None
val = fcd.find(util.nspath_eval('gmd:includedWithDataset/gco:Boolean', namespaces))
val = util.testXMLValue(val)
if val is not None:
self.includedwithdataset = util.getTypedValue('boolean', val)
self.featuretypenames = []
for i in fcd.findall(util.nspath_eval('gmd:featureTypes/gco:LocalName', namespaces)):
val = util.testXMLValue(i)
if val is not None:
self.featuretypenames.append(val)
for i in fcd.findall(util.nspath_eval('gmd:featureTypes/gco:ScopedName', namespaces)):
val = util.testXMLValue(i)
if val is not None:
self.featuretypenames.append(val)
self.featurecatalogues = []
for i in fcd.findall(util.nspath_eval('gmd:featureCatalogueCitation', namespaces)):
val = i.attrib.get('uuidref')
val = util.testXMLValue(val, attrib=True)
if val is not None:
self.featurecatalogues.append(val)
class FC_FeatureCatalogue(object):
"""Process gfc:FC_FeatureCatalogue"""
def __init__(self, fc=None):
if fc is None:
self.xml = None
self.identifier = None
self.name = None
self.versiondate = None
self.producer = None
self.featuretypes = []
else:
if hasattr(fc, 'getroot'): # standalone document
self.xml = etree.tostring(fc.getroot())
else: # part of a larger document
self.xml = etree.tostring(fc)
val = fc.attrib['uuid']
self.identifier = util.testXMLValue(val, attrib=True)
val = fc.find(util.nspath_eval('gmx:name/gco:CharacterString', namespaces))
self.name = util.testXMLValue(val)
val = fc.find(util.nspath_eval('gmx:versionDate/gco:Date', namespaces))
self.versiondate = util.testXMLValue(val)
if not self.versiondate:
val = fc.find(util.nspath_eval('gmx:versionDate/gco:DateTime', namespaces))
self.versiondate = util.testXMLValue(val)
self.producer = None
prod = fc.find(util.nspath_eval('gfc:producer/gmd:CI_ResponsibleParty', namespaces))
if prod is not None:
self.producer = CI_ResponsibleParty(prod)
self.featuretypes = []
for i in fc.findall(util.nspath_eval('gfc:featureType/gfc:FC_FeatureType', namespaces)):
self.featuretypes.append(FC_FeatureType(i))
class FC_FeatureType(object):
"""Process gfc:FC_FeatureType"""
def __init__(self, ft=None):
if ft is None:
self.xml = None
self.identifier = None
self.typename = None
self.definition = None
self.isabstract = None
self.aliases = []
self.attributes = []
else:
if hasattr(ft, 'getroot'): # standalone document
self.xml = etree.tostring(ft.getroot())
else: # part of a larger document
self.xml = etree.tostring(ft)
val = ft.attrib['uuid']
self.identifier = util.testXMLValue(val, attrib=True)
val = ft.find(util.nspath_eval('gfc:typeName/gco:LocalName', namespaces))
self.typename = util.testXMLValue(val)
val = ft.find(util.nspath_eval('gfc:definition/gco:CharacterString', namespaces))
self.definition = util.testXMLValue(val)
self.isabstract = None
val = ft.find(util.nspath_eval('gfc:isAbstract/gco:Boolean', namespaces))
val = util.testXMLValue(val)
if val is not None:
self.isabstract = util.getTypedValue('boolean', val)
self.aliases = []
for i in ft.findall(util.nspath_eval('gfc:aliases/gco:LocalName', namespaces)):
self.aliases.append(util.testXMLValue(i))
self.attributes = []
for i in ft.findall(util.nspath_eval('gfc:carrierOfCharacteristics/gfc:FC_FeatureAttribute', namespaces)):
self.attributes.append(FC_FeatureAttribute(i))
class FC_FeatureAttribute(object):
"""Process gfc:FC_FeatureAttribute"""
def __init__(self, fa=None):
if fa is None:
self.xml = None
self.membername = None
self.definition = None
self.code = None
self.valuetype = None
self.listedvalues = []
else:
if hasattr(fa, 'getroot'): # standalone document
self.xml = etree.tostring(fa.getroot())
else: # part of a larger document
self.xml = etree.tostring(fa)
val = fa.find(util.nspath_eval('gfc:memberName/gco:LocalName', namespaces))
self.membername = util.testXMLValue(val)
val = fa.find(util.nspath_eval('gfc:definition/gco:CharacterString', namespaces))
self.definition = util.testXMLValue(val)
val = fa.find(util.nspath_eval('gfc:code/gco:CharacterString', namespaces))
self.code = util.testXMLValue(val)
val = fa.find(util.nspath_eval('gfc:valueType/gco:TypeName/gco:aName/gco:CharacterString', namespaces))
self.valuetype = util.testXMLValue(val)
self.listedvalues = []
for i in fa.findall(util.nspath_eval('gfc:listedValue/gfc:FC_ListedValue', namespaces)):
self.listedvalues.append(FC_ListedValue(i))
class FC_ListedValue(object):
"""Process gfc:FC_ListedValue"""
def __init__(self, lv=None):
if lv is None:
self.xml = None
self.label = None
self.code = None
self.definition = None
else:
if hasattr(lv, 'getroot'): # standalone document
self.xml = etree.tostring(lv.getroot())
else: # part of a larger document
self.xml = etree.tostring(lv)
val = lv.find(util.nspath_eval('gfc:label/gco:CharacterString', namespaces))
self.label = util.testXMLValue(val)
val = lv.find(util.nspath_eval('gfc:code/gco:CharacterString', namespaces))
self.code = util.testXMLValue(val)
val = lv.find(util.nspath_eval('gfc:definition/gco:CharacterString', namespaces))
self.definition = util.testXMLValue(val)
|
the-stack_0_14754 | import socket
sock = socket.socket()
sock.connect(('127.0.0.1', 9900))
sock.send(b"Hello, server!\n")
data = sock.recv(1024)
udata = data.decode("utf-8")
print(udata)
sock.close()
|
the-stack_0_14756 | # Copyright 2020 - 2021 MONAI Consortium
# 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 typing import Callable, Dict, Optional, Sequence, Union
import numpy as np
import torch
from monai.config import IndexSelection, KeysCollection
from monai.networks.layers import GaussianFilter
from monai.transforms import Resize, SpatialCrop
from monai.transforms.transform import MapTransform, Randomizable, Transform
from monai.transforms.utils import generate_spatial_bounding_box
from monai.utils import InterpolateMode, ensure_tuple_rep, min_version, optional_import
measure, _ = optional_import("skimage.measure", "0.14.2", min_version)
distance_transform_cdt, _ = optional_import("scipy.ndimage.morphology", name="distance_transform_cdt")
# Transforms to support Training for Deepgrow models
class FindAllValidSlicesd(Transform):
"""
Find/List all valid slices in the label.
Label is assumed to be a 4D Volume with shape CDHW, where C=1.
Args:
label: key to the label source.
sids: key to store slices indices having valid label map.
"""
def __init__(self, label: str = "label", sids: str = "sids"):
self.label = label
self.sids = sids
def _apply(self, label):
sids = []
for sid in range(label.shape[1]): # Assume channel is first
if np.sum(label[0][sid]) != 0:
sids.append(sid)
return np.asarray(sids)
def __call__(self, data):
d: Dict = dict(data)
label = d[self.label]
if label.shape[0] != 1:
raise ValueError("Only supports single channel labels!")
if len(label.shape) != 4: # only for 3D
raise ValueError("Only supports label with shape CDHW!")
sids = self._apply(label)
if sids is not None and len(sids):
d[self.sids] = sids
return d
class AddInitialSeedPointd(Randomizable):
"""
Add random guidance as initial seed point for a given label.
Note that the label is of size (C, D, H, W) or (C, H, W)
The guidance is of size (2, N, # of dims) where N is number of guidance added.
# of dims = 4 when C, D, H, W; # of dims = 3 when (C, H, W)
Args:
label: label source.
guidance: key to store guidance.
sids: key that represents list of valid slice indices for the given label.
sid: key that represents the slice to add initial seed point. If not present, random sid will be chosen.
connected_regions: maximum connected regions to use for adding initial points.
"""
def __init__(
self,
label: str = "label",
guidance: str = "guidance",
sids: str = "sids",
sid: str = "sid",
connected_regions: int = 5,
):
self.label = label
self.sids_key = sids
self.sid_key = sid
self.sid = None
self.guidance = guidance
self.connected_regions = connected_regions
def randomize(self, data):
sid = data.get(self.sid_key, None)
sids = data.get(self.sids_key, None)
if sids is not None:
if sid is None or sid not in sids:
sid = self.R.choice(sids, replace=False)
else:
sid = None
self.sid = sid
def _apply(self, label, sid):
dimensions = 3 if len(label.shape) > 3 else 2
default_guidance = [-1] * (dimensions + 1)
dims = dimensions
if sid is not None and dimensions == 3:
dims = 2
label = label[0][sid][np.newaxis] # Assume channel is first
label = (label > 0.5).astype(np.float32)
blobs_labels = measure.label(label.astype(int), background=0) if dims == 2 else label
if np.max(blobs_labels) <= 0:
raise AssertionError("Not a valid Label")
pos_guidance = []
for ridx in range(1, 2 if dims == 3 else self.connected_regions + 1):
if dims == 2:
label = (blobs_labels == ridx).astype(np.float32)
if np.sum(label) == 0:
pos_guidance.append(default_guidance)
continue
distance = distance_transform_cdt(label).flatten()
probability = np.exp(distance) - 1.0
idx = np.where(label.flatten() > 0)[0]
seed = self.R.choice(idx, size=1, p=probability[idx] / np.sum(probability[idx]))
dst = distance[seed]
g = np.asarray(np.unravel_index(seed, label.shape)).transpose().tolist()[0]
g[0] = dst[0] # for debug
if dimensions == 2 or dims == 3:
pos_guidance.append(g)
else:
pos_guidance.append([g[0], sid, g[-2], g[-1]])
return np.asarray([pos_guidance, [default_guidance] * len(pos_guidance)])
def __call__(self, data):
d = dict(data)
self.randomize(data)
d[self.guidance] = self._apply(d[self.label], self.sid)
return d
class AddGuidanceSignald(Transform):
"""
Add Guidance signal for input image.
Based on the "guidance" points, apply gaussian to them and add them as new channel for input image.
Args:
image: key to the image source.
guidance: key to store guidance.
sigma: standard deviation for Gaussian kernel.
number_intensity_ch: channel index.
batched: whether input is batched or not.
"""
def __init__(
self,
image: str = "image",
guidance: str = "guidance",
sigma: int = 2,
number_intensity_ch: int = 1,
batched: bool = False,
):
self.image = image
self.guidance = guidance
self.sigma = sigma
self.number_intensity_ch = number_intensity_ch
self.batched = batched
def _get_signal(self, image, guidance):
dimensions = 3 if len(image.shape) > 3 else 2
guidance = guidance.tolist() if isinstance(guidance, np.ndarray) else guidance
if dimensions == 3:
signal = np.zeros((len(guidance), image.shape[-3], image.shape[-2], image.shape[-1]), dtype=np.float32)
else:
signal = np.zeros((len(guidance), image.shape[-2], image.shape[-1]), dtype=np.float32)
sshape = signal.shape
for i in range(len(guidance)):
for point in guidance[i]:
if np.any(np.asarray(point) < 0):
continue
if dimensions == 3:
p1 = max(0, min(int(point[-3]), sshape[-3] - 1))
p2 = max(0, min(int(point[-2]), sshape[-2] - 1))
p3 = max(0, min(int(point[-1]), sshape[-1] - 1))
signal[i, p1, p2, p3] = 1.0
else:
p1 = max(0, min(int(point[-2]), sshape[-2] - 1))
p2 = max(0, min(int(point[-1]), sshape[-1] - 1))
signal[i, p1, p2] = 1.0
if np.max(signal[i]) > 0:
signal_tensor = torch.tensor(signal[i])
pt_gaussian = GaussianFilter(len(signal_tensor.shape), sigma=self.sigma)
signal_tensor = pt_gaussian(signal_tensor.unsqueeze(0).unsqueeze(0))
signal_tensor = signal_tensor.squeeze(0).squeeze(0)
signal[i] = signal_tensor.detach().cpu().numpy()
signal[i] = (signal[i] - np.min(signal[i])) / (np.max(signal[i]) - np.min(signal[i]))
return signal
def _apply(self, image, guidance):
if not self.batched:
signal = self._get_signal(image, guidance)
return np.concatenate([image, signal], axis=0)
images = []
for i, g in zip(image, guidance):
i = i[0 : 0 + self.number_intensity_ch, ...]
signal = self._get_signal(i, g)
images.append(np.concatenate([i, signal], axis=0))
return images
def __call__(self, data):
d = dict(data)
image = d[self.image]
guidance = d[self.guidance]
d[self.image] = self._apply(image, guidance)
return d
class FindDiscrepancyRegionsd(Transform):
"""
Find discrepancy between prediction and actual during click interactions during training.
If batched is true:
label is in shape (B, C, D, H, W) or (B, C, H, W)
pred has same shape as label
discrepancy will have shape (B, 2, C, D, H, W) or (B, 2, C, H, W)
Args:
label: key to label source.
pred: key to prediction source.
discrepancy: key to store discrepancies found between label and prediction.
batched: whether input is batched or not.
"""
def __init__(
self, label: str = "label", pred: str = "pred", discrepancy: str = "discrepancy", batched: bool = True
):
self.label = label
self.pred = pred
self.discrepancy = discrepancy
self.batched = batched
@staticmethod
def disparity(label, pred):
label = (label > 0.5).astype(np.float32)
pred = (pred > 0.5).astype(np.float32)
disparity = label - pred
pos_disparity = (disparity > 0).astype(np.float32)
neg_disparity = (disparity < 0).astype(np.float32)
return [pos_disparity, neg_disparity]
def _apply(self, label, pred):
if not self.batched:
return self.disparity(label, pred)
disparity = []
for la, pr in zip(label, pred):
disparity.append(self.disparity(la, pr))
return disparity
def __call__(self, data):
d = dict(data)
label = d[self.label]
pred = d[self.pred]
d[self.discrepancy] = self._apply(label, pred)
return d
class AddRandomGuidanced(Randomizable):
"""
Add random guidance based on discrepancies that were found between label and prediction.
If batched is True, input shape is as below:
Guidance is of shape (B, 2, N, # of dim) where B is batch size, 2 means positive and negative,
N means how many guidance points, # of dim is the total number of dimensions of the image
(for example if the image is CDHW, then # of dim would be 4).
Discrepancy is of shape (B, 2, C, D, H, W) or (B, 2, C, H, W)
Probability is of shape (B, 1)
else:
Guidance is of shape (2, N, # of dim)
Discrepancy is of shape (2, C, D, H, W) or (2, C, H, W)
Probability is of shape (1)
Args:
guidance: key to guidance source.
discrepancy: key that represents discrepancies found between label and prediction.
probability: key that represents click/interaction probability.
batched: whether input is batched or not.
"""
def __init__(
self,
guidance: str = "guidance",
discrepancy: str = "discrepancy",
probability: str = "probability",
batched: bool = True,
):
self.guidance = guidance
self.discrepancy = discrepancy
self.probability = probability
self.batched = batched
self._will_interact = None
def randomize(self, data=None):
probability = data[self.probability]
if not self.batched:
self._will_interact = self.R.choice([True, False], p=[probability, 1.0 - probability])
else:
self._will_interact = []
for p in probability:
self._will_interact.append(self.R.choice([True, False], p=[p, 1.0 - p]))
def find_guidance(self, discrepancy):
distance = distance_transform_cdt(discrepancy).flatten()
probability = np.exp(distance) - 1.0
idx = np.where(discrepancy.flatten() > 0)[0]
if np.sum(discrepancy > 0) > 0:
seed = self.R.choice(idx, size=1, p=probability[idx] / np.sum(probability[idx]))
dst = distance[seed]
g = np.asarray(np.unravel_index(seed, discrepancy.shape)).transpose().tolist()[0]
g[0] = dst[0]
return g
return None
def add_guidance(self, discrepancy, will_interact):
if not will_interact:
return None, None
pos_discr = discrepancy[0]
neg_discr = discrepancy[1]
can_be_positive = np.sum(pos_discr) > 0
can_be_negative = np.sum(neg_discr) > 0
correct_pos = np.sum(pos_discr) >= np.sum(neg_discr)
if correct_pos and can_be_positive:
return self.find_guidance(pos_discr), None
if not correct_pos and can_be_negative:
return None, self.find_guidance(neg_discr)
return None, None
def _apply(self, guidance, discrepancy):
guidance = guidance.tolist() if isinstance(guidance, np.ndarray) else guidance
if not self.batched:
pos, neg = self.add_guidance(discrepancy, self._will_interact)
if pos:
guidance[0].append(pos)
guidance[1].append([-1] * len(pos))
if neg:
guidance[0].append([-1] * len(neg))
guidance[1].append(neg)
else:
for g, d, w in zip(guidance, discrepancy, self._will_interact):
pos, neg = self.add_guidance(d, w)
if pos:
g[0].append(pos)
g[1].append([-1] * len(pos))
if neg:
g[0].append([-1] * len(neg))
g[1].append(neg)
return np.asarray(guidance)
def __call__(self, data):
d = dict(data)
guidance = d[self.guidance]
discrepancy = d[self.discrepancy]
self.randomize(data)
d[self.guidance] = self._apply(guidance, discrepancy)
return d
class SpatialCropForegroundd(MapTransform):
"""
Crop only the foreground object of the expected images.
Difference VS :py:class:`monai.transforms.CropForegroundd`:
1. If the bounding box is smaller than spatial size in all dimensions then this transform will crop the
object using box's center and spatial_size.
2. This transform will set "start_coord_key", "end_coord_key", "original_shape_key" and "cropped_shape_key"
in data[{key}_{meta_key_postfix}]
The typical usage is to help training and evaluation if the valid part is small in the whole medical image.
The valid part can be determined by any field in the data with `source_key`, for example:
- Select values > 0 in image field as the foreground and crop on all fields specified by `keys`.
- Select label = 3 in label field as the foreground to crop on all fields specified by `keys`.
- Select label > 0 in the third channel of a One-Hot label field as the foreground to crop all `keys` fields.
Users can define arbitrary function to select expected foreground from the whole source image or specified
channels. And it can also add margin to every dim of the bounding box of foreground object.
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.MapTransform`
source_key: data source to generate the bounding box of foreground, can be image or label, etc.
spatial_size: minimal spatial size of the image patch e.g. [128, 128, 128] to fit in.
select_fn: function to select expected foreground, default is to select values > 0.
channel_indices: if defined, select foreground only on the specified channels
of image. if None, select foreground on the whole image.
margin: add margin value to spatial dims of the bounding box, if only 1 value provided, use it for all dims.
meta_key_postfix: use `{key}_{meta_key_postfix}` to to fetch/store the meta data according to the key data,
default is `meta_dict`, the meta data is a dictionary object.
For example, to handle key `image`, read/write affine matrices from the
metadata `image_meta_dict` dictionary's `affine` field.
start_coord_key: key to record the start coordinate of spatial bounding box for foreground.
end_coord_key: key to record the end coordinate of spatial bounding box for foreground.
original_shape_key: key to record original shape for foreground.
cropped_shape_key: key to record cropped shape for foreground.
allow_missing_keys: don't raise exception if key is missing.
"""
def __init__(
self,
keys: KeysCollection,
source_key: str,
spatial_size: Union[Sequence[int], np.ndarray],
select_fn: Callable = lambda x: x > 0,
channel_indices: Optional[IndexSelection] = None,
margin: int = 0,
meta_key_postfix="meta_dict",
start_coord_key: str = "foreground_start_coord",
end_coord_key: str = "foreground_end_coord",
original_shape_key: str = "foreground_original_shape",
cropped_shape_key: str = "foreground_cropped_shape",
allow_missing_keys: bool = False,
) -> None:
super().__init__(keys, allow_missing_keys)
self.source_key = source_key
self.spatial_size = list(spatial_size)
self.select_fn = select_fn
self.channel_indices = channel_indices
self.margin = margin
self.meta_key_postfix = meta_key_postfix
self.start_coord_key = start_coord_key
self.end_coord_key = end_coord_key
self.original_shape_key = original_shape_key
self.cropped_shape_key = cropped_shape_key
def __call__(self, data):
d = dict(data)
box_start, box_end = generate_spatial_bounding_box(
d[self.source_key], self.select_fn, self.channel_indices, self.margin
)
center = list(np.mean([box_start, box_end], axis=0).astype(int))
current_size = list(np.subtract(box_end, box_start).astype(int))
if np.all(np.less(current_size, self.spatial_size)):
cropper = SpatialCrop(roi_center=center, roi_size=self.spatial_size)
box_start = cropper.roi_start
box_end = cropper.roi_end
else:
cropper = SpatialCrop(roi_start=box_start, roi_end=box_end)
for key in self.key_iterator(d):
meta_key = f"{key}_{self.meta_key_postfix}"
d[meta_key][self.start_coord_key] = box_start
d[meta_key][self.end_coord_key] = box_end
d[meta_key][self.original_shape_key] = d[key].shape
image = cropper(d[key])
d[meta_key][self.cropped_shape_key] = image.shape
d[key] = image
return d
# Transforms to support Inference for Deepgrow models
class AddGuidanceFromPointsd(Transform):
"""
Add guidance based on user clicks.
We assume the input is loaded by LoadImaged and has the shape of (H, W, D) originally.
Clicks always specify the coordinates in (H, W, D)
If depth_first is True:
Input is now of shape (D, H, W), will return guidance that specifies the coordinates in (D, H, W)
else:
Input is now of shape (H, W, D), will return guidance that specifies the coordinates in (H, W, D)
Args:
ref_image: key to reference image to fetch current and original image details.
guidance: output key to store guidance.
foreground: key that represents user foreground (+ve) clicks.
background: key that represents user background (-ve) clicks.
axis: axis that represents slices in 3D volume. (axis to Depth)
depth_first: if depth (slices) is positioned at first dimension.
dimensions: dimensions based on model used for deepgrow (2D vs 3D).
slice_key: key that represents applicable slice to add guidance.
meta_key_postfix: use `{ref_image}_{postfix}` to to fetch the meta data according to the key data,
default is `meta_dict`, the meta data is a dictionary object.
For example, to handle key `image`, read/write affine matrices from the
metadata `image_meta_dict` dictionary's `affine` field.
"""
def __init__(
self,
ref_image,
guidance: str = "guidance",
foreground: str = "foreground",
background: str = "background",
axis: int = 0,
depth_first: bool = True,
dimensions: int = 2,
slice_key: str = "slice",
meta_key_postfix: str = "meta_dict",
):
self.ref_image = ref_image
self.guidance = guidance
self.foreground = foreground
self.background = background
self.axis = axis
self.depth_first = depth_first
self.dimensions = dimensions
self.slice = slice_key
self.meta_key_postfix = meta_key_postfix
def _apply(self, pos_clicks, neg_clicks, factor, slice_num):
pos = neg = []
if self.dimensions == 2:
points = list(pos_clicks)
points.extend(neg_clicks)
points = np.array(points)
slices = list(np.unique(points[:, self.axis]))
slice_idx = slices[0] if slice_num is None else next(x for x in slices if x == slice_num)
if len(pos_clicks):
pos_clicks = np.array(pos_clicks)
pos = (pos_clicks[np.where(pos_clicks[:, self.axis] == slice_idx)] * factor)[:, 1:].astype(int).tolist()
if len(neg_clicks):
neg_clicks = np.array(neg_clicks)
neg = (neg_clicks[np.where(neg_clicks[:, self.axis] == slice_idx)] * factor)[:, 1:].astype(int).tolist()
guidance = [pos, neg, slice_idx]
else:
if len(pos_clicks):
pos = np.multiply(pos_clicks, factor).astype(int).tolist()
if len(neg_clicks):
neg = np.multiply(neg_clicks, factor).astype(int).tolist()
guidance = [pos, neg]
return guidance
def __call__(self, data):
d = dict(data)
meta_dict_key = f"{self.ref_image}_{self.meta_key_postfix}"
if meta_dict_key not in d:
raise RuntimeError(f"Missing meta_dict {meta_dict_key} in data!")
if "spatial_shape" not in d[meta_dict_key]:
raise RuntimeError('Missing "spatial_shape" in meta_dict!')
original_shape = d[meta_dict_key]["spatial_shape"]
current_shape = list(d[self.ref_image].shape)
if self.depth_first:
if self.axis != 0:
raise RuntimeError("Depth first means the depth axis should be 0.")
# in here we assume the depth dimension was in the last dimension of "original_shape"
original_shape = np.roll(original_shape, 1)
factor = np.array(current_shape) / original_shape
fg_bg_clicks = []
for key in [self.foreground, self.background]:
clicks = d[key]
clicks = list(np.array(clicks).astype(int))
if self.depth_first:
for i in range(len(clicks)):
clicks[i] = list(np.roll(clicks[i], 1))
fg_bg_clicks.append(clicks)
d[self.guidance] = self._apply(fg_bg_clicks[0], fg_bg_clicks[1], factor, d.get(self.slice))
return d
class SpatialCropGuidanced(MapTransform):
"""
Crop image based on guidance with minimal spatial size.
- If the bounding box is smaller than spatial size in all dimensions then this transform will crop the
object using box's center and spatial_size.
- This transform will set "start_coord_key", "end_coord_key", "original_shape_key" and "cropped_shape_key"
in data[{key}_{meta_key_postfix}]
Input data is of shape (C, spatial_1, [spatial_2, ...])
Args:
keys: keys of the corresponding items to be transformed.
guidance: key to the guidance. It is used to generate the bounding box of foreground
spatial_size: minimal spatial size of the image patch e.g. [128, 128, 128] to fit in.
margin: add margin value to spatial dims of the bounding box, if only 1 value provided, use it for all dims.
meta_key_postfix: use `key_{postfix}` to to fetch the meta data according to the key data,
default is `meta_dict`, the meta data is a dictionary object.
For example, to handle key `image`, read/write affine matrices from the
metadata `image_meta_dict` dictionary's `affine` field.
start_coord_key: key to record the start coordinate of spatial bounding box for foreground.
end_coord_key: key to record the end coordinate of spatial bounding box for foreground.
original_shape_key: key to record original shape for foreground.
cropped_shape_key: key to record cropped shape for foreground.
allow_missing_keys: don't raise exception if key is missing.
"""
def __init__(
self,
keys: KeysCollection,
guidance: str,
spatial_size,
margin=20,
meta_key_postfix="meta_dict",
start_coord_key: str = "foreground_start_coord",
end_coord_key: str = "foreground_end_coord",
original_shape_key: str = "foreground_original_shape",
cropped_shape_key: str = "foreground_cropped_shape",
allow_missing_keys: bool = False,
) -> None:
super().__init__(keys, allow_missing_keys)
self.guidance = guidance
self.spatial_size = list(spatial_size)
self.margin = margin
self.meta_key_postfix = meta_key_postfix
self.start_coord_key = start_coord_key
self.end_coord_key = end_coord_key
self.original_shape_key = original_shape_key
self.cropped_shape_key = cropped_shape_key
def bounding_box(self, points, img_shape):
ndim = len(img_shape)
margin = ensure_tuple_rep(self.margin, ndim)
for m in margin:
if m < 0:
raise ValueError("margin value should not be negative number.")
box_start = [0] * ndim
box_end = [0] * ndim
for di in range(ndim):
dt = points[..., di]
min_d = max(min(dt - margin[di]), 0)
max_d = min(img_shape[di], max(dt + margin[di] + 1))
box_start[di], box_end[di] = min_d, max_d
return box_start, box_end
def __call__(self, data):
d: Dict = dict(data)
guidance = d[self.guidance]
original_spatial_shape = d[self.keys[0]].shape[1:]
box_start, box_end = self.bounding_box(np.array(guidance[0] + guidance[1]), original_spatial_shape)
center = list(np.mean([box_start, box_end], axis=0).astype(int))
spatial_size = self.spatial_size
box_size = list(np.subtract(box_end, box_start).astype(int))
spatial_size = spatial_size[-len(box_size) :]
if len(spatial_size) < len(box_size):
# If the data is in 3D and spatial_size is specified as 2D [256,256]
# Then we will get all slices in such case
diff = len(box_size) - len(spatial_size)
spatial_size = list(original_spatial_shape[1 : (1 + diff)]) + spatial_size
if np.all(np.less(box_size, spatial_size)):
if len(center) == 3:
# 3D Deepgrow: set center to be middle of the depth dimension (D)
center[0] = spatial_size[0] // 2
cropper = SpatialCrop(roi_center=center, roi_size=spatial_size)
else:
cropper = SpatialCrop(roi_start=box_start, roi_end=box_end)
# update bounding box in case it was corrected by the SpatialCrop constructor
box_start = np.array([s.start for s in cropper.slices])
box_end = np.array([s.stop for s in cropper.slices])
for key in self.key_iterator(d):
if not np.array_equal(d[key].shape[1:], original_spatial_shape):
raise RuntimeError("All the image specified in keys should have same spatial shape")
meta_key = f"{key}_{self.meta_key_postfix}"
d[meta_key][self.start_coord_key] = box_start
d[meta_key][self.end_coord_key] = box_end
d[meta_key][self.original_shape_key] = d[key].shape
image = cropper(d[key])
d[meta_key][self.cropped_shape_key] = image.shape
d[key] = image
pos_clicks, neg_clicks = guidance[0], guidance[1]
pos = np.subtract(pos_clicks, box_start).tolist() if len(pos_clicks) else []
neg = np.subtract(neg_clicks, box_start).tolist() if len(neg_clicks) else []
d[self.guidance] = [pos, neg]
return d
class ResizeGuidanced(Transform):
"""
Resize the guidance based on cropped vs resized image.
This transform assumes that the images have been cropped and resized. And the shape after cropped is store inside
the meta dict of ref image.
Args:
guidance: key to guidance
ref_image: key to reference image to fetch current and original image details
meta_key_postfix: use `{ref_image}_{postfix}` to to fetch the meta data according to the key data,
default is `meta_dict`, the meta data is a dictionary object.
For example, to handle key `image`, read/write affine matrices from the
metadata `image_meta_dict` dictionary's `affine` field.
cropped_shape_key: key that records cropped shape for foreground.
"""
def __init__(
self,
guidance: str,
ref_image: str,
meta_key_postfix="meta_dict",
cropped_shape_key: str = "foreground_cropped_shape",
) -> None:
self.guidance = guidance
self.ref_image = ref_image
self.meta_key_postfix = meta_key_postfix
self.cropped_shape_key = cropped_shape_key
def __call__(self, data):
d = dict(data)
guidance = d[self.guidance]
meta_dict: Dict = d[f"{self.ref_image}_{self.meta_key_postfix}"]
current_shape = d[self.ref_image].shape[1:]
cropped_shape = meta_dict[self.cropped_shape_key][1:]
factor = np.divide(current_shape, cropped_shape)
pos_clicks, neg_clicks = guidance[0], guidance[1]
pos = np.multiply(pos_clicks, factor).astype(int).tolist() if len(pos_clicks) else []
neg = np.multiply(neg_clicks, factor).astype(int).tolist() if len(neg_clicks) else []
d[self.guidance] = [pos, neg]
return d
class RestoreLabeld(MapTransform):
"""
Restores label based on the ref image.
The ref_image is assumed that it went through the following transforms:
1. Fetch2DSliced (If 2D)
2. Spacingd
3. SpatialCropGuidanced
4. Resized
And its shape is assumed to be (C, D, H, W)
This transform tries to undo these operation so that the result label can be overlapped with original volume.
It does the following operation:
1. Undo Resized
2. Undo SpatialCropGuidanced
3. Undo Spacingd
4. Undo Fetch2DSliced
The resulting label is of shape (D, H, W)
Args:
keys: keys of the corresponding items to be transformed.
ref_image: reference image to fetch current and original image details
slice_only: apply only to an applicable slice, in case of 2D model/prediction
mode: {``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``, ``"mean"``,
``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``}
One of the listed string values or a user supplied function for padding. Defaults to ``"constant"``.
See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html
align_corners: Geometrically, we consider the pixels of the input as squares rather than points.
See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample
It also can be a sequence of bool, each element corresponds to a key in ``keys``.
meta_key_postfix: use `{ref_image}_{meta_key_postfix}` to to fetch the meta data according to the key data,
default is `meta_dict`, the meta data is a dictionary object.
For example, to handle key `image`, read/write affine matrices from the
metadata `image_meta_dict` dictionary's `affine` field.
start_coord_key: key that records the start coordinate of spatial bounding box for foreground.
end_coord_key: key that records the end coordinate of spatial bounding box for foreground.
original_shape_key: key that records original shape for foreground.
cropped_shape_key: key that records cropped shape for foreground.
allow_missing_keys: don't raise exception if key is missing.
"""
def __init__(
self,
keys: KeysCollection,
ref_image: str,
slice_only: bool = False,
mode: Union[Sequence[Union[InterpolateMode, str]], InterpolateMode, str] = InterpolateMode.NEAREST,
align_corners: Union[Sequence[Optional[bool]], Optional[bool]] = None,
meta_key_postfix: str = "meta_dict",
start_coord_key: str = "foreground_start_coord",
end_coord_key: str = "foreground_end_coord",
original_shape_key: str = "foreground_original_shape",
cropped_shape_key: str = "foreground_cropped_shape",
allow_missing_keys: bool = False,
) -> None:
super().__init__(keys, allow_missing_keys)
self.ref_image = ref_image
self.slice_only = slice_only
self.mode = ensure_tuple_rep(mode, len(self.keys))
self.align_corners = ensure_tuple_rep(align_corners, len(self.keys))
self.meta_key_postfix = meta_key_postfix
self.start_coord_key = start_coord_key
self.end_coord_key = end_coord_key
self.original_shape_key = original_shape_key
self.cropped_shape_key = cropped_shape_key
def __call__(self, data):
d = dict(data)
meta_dict: Dict = d[f"{self.ref_image}_{self.meta_key_postfix}"]
for key, mode, align_corners in self.key_iterator(d, self.mode, self.align_corners):
image = d[key]
# Undo Resize
current_shape = image.shape
cropped_shape = meta_dict[self.cropped_shape_key]
if np.any(np.not_equal(current_shape, cropped_shape)):
resizer = Resize(spatial_size=cropped_shape[1:], mode=mode)
image = resizer(image, mode=mode, align_corners=align_corners)
# Undo Crop
original_shape = meta_dict[self.original_shape_key]
result = np.zeros(original_shape, dtype=np.float32)
box_start = meta_dict[self.start_coord_key]
box_end = meta_dict[self.end_coord_key]
spatial_dims = min(len(box_start), len(image.shape[1:]))
slices = [slice(None)] + [slice(s, e) for s, e in zip(box_start[:spatial_dims], box_end[:spatial_dims])]
slices = tuple(slices)
result[slices] = image
# Undo Spacing
current_size = result.shape[1:]
# change spatial_shape from HWD to DHW
spatial_shape = list(np.roll(meta_dict["spatial_shape"], 1))
spatial_size = spatial_shape[-len(current_size) :]
if np.any(np.not_equal(current_size, spatial_size)):
resizer = Resize(spatial_size=spatial_size, mode=mode)
result = resizer(result, mode=mode, align_corners=align_corners)
# Undo Slicing
slice_idx = meta_dict.get("slice_idx")
if slice_idx is None or self.slice_only:
final_result = result if len(result.shape) <= 3 else result[0]
else:
slice_idx = meta_dict["slice_idx"][0]
final_result = np.zeros(tuple(spatial_shape))
final_result[slice_idx] = result
d[key] = final_result
meta = d.get(f"{key}_{self.meta_key_postfix}")
if meta is None:
meta = dict()
d[f"{key}_{self.meta_key_postfix}"] = meta
meta["slice_idx"] = slice_idx
meta["affine"] = meta_dict["original_affine"]
return d
class Fetch2DSliced(MapTransform):
"""
Fetch one slice in case of a 3D volume.
The volume only contains spatial coordinates.
Args:
keys: keys of the corresponding items to be transformed.
guidance: key that represents guidance.
axis: axis that represents slice in 3D volume.
meta_key_postfix: use `key_{meta_key_postfix}` to to fetch the meta data according to the key data,
default is `meta_dict`, the meta data is a dictionary object.
For example, to handle key `image`, read/write affine matrices from the
metadata `image_meta_dict` dictionary's `affine` field.
allow_missing_keys: don't raise exception if key is missing.
"""
def __init__(
self,
keys,
guidance="guidance",
axis: int = 0,
meta_key_postfix: str = "meta_dict",
allow_missing_keys: bool = False,
):
super().__init__(keys, allow_missing_keys)
self.guidance = guidance
self.axis = axis
self.meta_key_postfix = meta_key_postfix
def _apply(self, image, guidance):
slice_idx = guidance[2] # (pos, neg, slice_idx)
idx = []
for i in range(len(image.shape)):
idx.append(slice_idx) if i == self.axis else idx.append(slice(0, image.shape[i]))
idx = tuple(idx)
return image[idx], idx
def __call__(self, data):
d = dict(data)
guidance = d[self.guidance]
if len(guidance) < 3:
raise RuntimeError("Guidance does not container slice_idx!")
for key in self.key_iterator(d):
img_slice, idx = self._apply(d[key], guidance)
d[key] = img_slice
d[f"{key}_{self.meta_key_postfix}"]["slice_idx"] = idx
return d
|
the-stack_0_14758 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2019/3/13 10:58
# @Author : Money
# @Site :
# @File : middlewareloginrequired.py
# @Software: PyCharm
from functools import wraps
from django.conf import settings
from django.shortcuts import HttpResponseRedirect
from django.urls import RegexURLPattern # django2.0以上替换为:from django.urls import URLPattern
from . import urls
class MiddlewareLoginRequired(object):
"""
需要用户登录之后才能访问页面的中间件,
使用session判断用户是否登录
"""
_NO_NEED_LOGIN = [] #用来存放不需要做登录认证的view
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request, *args, **kwargs):
response = self.get_response(request)
user_hash = request.session.get('_auth_user_hash','')
if not user_hash:
url = request.path
if url in self.exclude_url_path():
return response
else:
return HttpResponseRedirect(settings.LOGIN_URL + '?next=' + url)
return response
@staticmethod
def no_need_login(func):
view_func = func.__module__ + '.' + func.__name__
MiddlewareLoginRequired._NO_NEED_LOGIN.append(view_func)
def get_all_urls(self, patterns, pre_fix, result):
"""
获取所有的view函数和url的映射关系,
:param patterns: urlpatterns
:param pre_fix:
:param result: 字典,{view函数:url}
:return:
"""
for item in patterns:
part = item.regex.pattern.strip("^$") #django2.0以上替换为:part = item.pattern.regex.pattern.strip("^$")
if isinstance(item, RegexURLPattern): #django2.0以上替换为:if isinstance(item, URLPattern):
# django2.0以上替换为:url_path = item.pattern.regex.pattern.strip("^$").replace('\\', "")
url_path = item.regex.pattern.strip("^$").replace('\\', "")
view_func = item.callback.__module__ + '.' + item.callback.__name__
if view_func.startswith(('django',)):
continue
result.setdefault(view_func, pre_fix + url_path)
else:
self.get_all_urls(item.url_patterns, pre_fix + part, result=result)
return result
def exclude_url_path(self):
view_url_dicts = self.get_all_urls(urls.urlpatterns, pre_fix="/", result={})
url_paths = list([view_url_dicts[view] for view in self._NO_NEED_LOGIN
if view in view_url_dicts])
return url_paths
def login_excepted(func=None):
"""
类似login_required,
使用这个函数装饰的view不需要登录就可以访问,
使用方法:@login_excepted 或者
@login_excepted()
:param func:
:return:
"""
def _wrapped(func):
MiddlewareLoginRequired.no_need_login(func)
@wraps(func)
def inner(*args, **kwargs):
return func(*args, **kwargs)
return inner
if not func:
return _wrapped
return _wrapped(func) |
the-stack_0_14759 | import re
#This function writes to terms.txt file
def prepTerms(inFile):
termsFile = open("terms.txt", "w+") #Creates terms.txt with w+ (writing and reading) rights
with open(inFile, 'r') as file: #Opens inFile (xml file passed as argument)
for line in file: #for loop for each line
if line.startswith("<mail>"): #Only take lines starting with <mail>
if line.split("<subj>")[1].split("</subj>")[0] != "": #checks if <subj> content is non-empty
for term in re.split("[^A-Za-z0-9\-_]+", re.sub("&.*?;", " ", line.split("<subj>")[1].split("</subj>")[0])): #splits by all chars except [A-Za-z0-9_-], substitutes all instances of &xxx; with space char, splits by <subj> and </subj> to get contents
if len(term) > 2: #only write to file if the term length is greater than 2
termsFile.write("s-%s:%s\n" %(term.lower(), line.split("<row>")[1].split("</row>")[0])) #write the term and row id
if line.split("<body>")[1].split("</body>") != "": #checks if <body> content is non-empty
for term in re.split("[^A-Za-z0-9\-_]+", re.sub("&.*?;", " ", line.split("<body>")[1].split("</body>")[0])): #splits the same as above for <subj>
if len(term) > 2: #only write term length > 2
termsFile.write("b-%s:%s\n" %(term.lower(), line.split("<row>")[1].split("</row>")[0])) #write the term and row id
#This functions write to emails.txt file
def prepEmails(inFile):
emailsFile = open("emails.txt", "w+") #same as above but for emails.txt
with open(inFile, 'r') as file: #same as above
for line in file: #same as above
if line.startswith("<mail>"): #same as above
emailsFile.write("from-%s:%s\n" %(line.split("<from>")[1].split("</from>")[0],line.split("<row>")[1].split("</row>")[0])) #write <from> contents into file. No condition since will always have from email
if line.split("<to>")[1].split("</to>")[0] != "": #checks if <to> content is non-empty
for email in line.split("<to>")[1].split("</to>")[0].split(","): #for loop to print all emails in <to> split by ','
emailsFile.write("to-%s:%s\n" %(email,line.split("<row>")[1].split("</row>")[0])) #writes <to> contents and row id to file
if line.split("<cc>")[1].split("</cc>")[0] != "": #checks if <cc> content is non-empty
for email in line.split("<cc>")[1].split("</cc>")[0].split(","): #for loop to print all emails in <cc> split by ','
emailsFile.write("cc-%s:%s\n" %(email,line.split("<row>")[1].split("</row>")[0])) #writes <cc> contents and row id to file
if line.split("<bcc>")[1].split("</bcc>")[0] != "": #checks if <bcc> content is non-empty
for email in line.split("<bcc>")[1].split("</bcc>")[0].split(","): #for loop to print all emails in <bcc> split by ','
emailsFile.write("bcc-%s:%s\n" %(email,line.split("<row>")[1].split("</row>")[0])) #writes <bcc> contents and row id to file
def prepDates(inFile):
datesFile = open("dates.txt", "w+") #same as above but for dates.txt
with open(inFile, 'r') as file: #same as above
for line in file: #same as above
if line.startswith("<mail>"): #same as above
datesFile.write("%s:%s\n" %(line.split("<date>")[1].split("</date>")[0],line.split("<row>")[1].split("</row>")[0])) #writes <date> content and row id
def prepRecs(inFile):
recsFile = open("recs.txt", "w+") #same as above but for recs.txt
with open(inFile, 'r') as file: #same as above
for line in file: #same as above
if line.startswith("<mail>"): #same as above
recsFile.write("%s:%s" %(line.split("<row>")[1].split("</row>")[0], line)) #writes row id and full line
|
the-stack_0_14760 | # -*- coding: utf-8 -*-
# File: graph.py
""" Graph related callbacks"""
import tensorflow as tf
import os
import numpy as np
from six.moves import zip
from ..utils import logger
from .base import Callback
from ..tfutils.common import get_op_tensor_name
__all__ = ['RunOp', 'RunUpdateOps', 'ProcessTensors', 'DumpTensors',
'DumpTensor', 'DumpTensorAsImage', 'DumpParamAsImage']
class RunOp(Callback):
""" Run an Op. """
_chief_only = False
def __init__(self, op,
run_before=True, run_as_trigger=True,
run_step=False, verbose=False):
"""
Args:
op (tf.Operation or function): an Op, or a function that returns the Op in the graph.
The function will be called after the main graph has been created (in the `setup_graph` callback).
run_before (bool): run the Op before training
run_as_trigger (bool): run the Op on every :meth:`trigger()` call.
run_step (bool): run the Op every step (along with training)
verbose (bool): print logs when the op is run.
Example:
The `DQN Example
<https://github.com/tensorpack/tensorpack/blob/master/examples/DeepQNetwork/>`_
uses this callback to update target network.
"""
if not callable(op):
self.setup_func = lambda: op # noqa
else:
self.setup_func = op
self.run_before = run_before
self.run_as_trigger = run_as_trigger
self.run_step = run_step
self.verbose = verbose
def _setup_graph(self):
self._op = self.setup_func()
if self.run_step:
self._fetch = tf.train.SessionRunArgs(fetches=self._op)
def _before_train(self):
if self.run_before:
self._print()
self._op.run()
def _trigger(self):
if self.run_as_trigger:
self._print()
self._op.run()
def _before_run(self, _):
if self.run_step:
self._print()
return self._fetch
def _print(self):
if self.verbose:
logger.info("Running Op {} ...".format(self._op.name))
class RunUpdateOps(RunOp):
"""
Run ops from the collection UPDATE_OPS every step.
The ops will be hooked to `trainer.hooked_sess` and run along with
each `sess.run` call.
"""
def __init__(self, collection=tf.GraphKeys.UPDATE_OPS):
"""
Args:
collection (str): collection of ops to run. Defaults to ``tf.GraphKeys.UPDATE_OPS``
"""
name = 'UPDATE_OPS' if collection == tf.GraphKeys.UPDATE_OPS else collection
def f():
ops = tf.get_collection(collection)
if ops:
logger.info("Applying collection {} of {} ops.".format(name, len(ops)))
return tf.group(*ops, name='update_ops')
else:
return tf.no_op(name='empty_update_ops')
super(RunUpdateOps, self).__init__(
f, run_before=False, run_as_trigger=False, run_step=True)
class ProcessTensors(Callback):
"""
Fetch extra tensors **along with** each training step,
and call some function over the values.
It uses `_{before,after}_run` method to inject `tf.train.SessionRunHooks`
to the session.
You can use it to print tensors, save tensors to file, etc.
Example:
.. code-block:: python
ProcessTensors(['mycost1', 'mycost2'], lambda c1, c2: print(c1, c2, c1 + c2))
"""
def __init__(self, names, fn):
"""
Args:
names (list[str]): names of tensors
fn: a function taking all requested tensors as input
"""
assert isinstance(names, (list, tuple)), names
self._names = names
self._fn = fn
def _setup_graph(self):
tensors = self.get_tensors_maybe_in_tower(self._names)
self._fetch = tf.train.SessionRunArgs(fetches=tensors)
def _before_run(self, _):
return self._fetch
def _after_run(self, _, rv):
results = rv.results
self._fn(*results)
class DumpTensors(ProcessTensors):
"""
Dump some tensors to a file.
Every step this callback fetches tensors and write them to a npz file
under ``logger.get_logger_dir``.
The dump can be loaded by ``dict(np.load(filename).items())``.
"""
def __init__(self, names):
"""
Args:
names (list[str]): names of tensors
"""
assert isinstance(names, (list, tuple)), names
self._names = names
dir = logger.get_logger_dir()
def fn(*args):
dic = {}
for name, val in zip(self._names, args):
dic[name] = val
fname = os.path.join(
dir, 'DumpTensor-{}.npz'.format(self.global_step))
np.savez(fname, **dic)
super(DumpTensors, self).__init__(names, fn)
class DumpTensorAsImage(Callback):
"""
Dump a tensor to image(s) to ``logger.get_logger_dir()`` once triggered.
Note that it requires the tensor is directly evaluable, i.e. either inputs
are not its dependency (e.g. the weights of the model), or the inputs are
feedfree (in which case this callback will take an extra datapoint from the input pipeline).
"""
def __init__(self, tensor_name, prefix=None, map_func=None, scale=255):
"""
Args:
tensor_name (str): the name of the tensor.
prefix (str): the filename prefix for saved images. Defaults to the Op name.
map_func: map the value of the tensor to an image or list of
images of shape [h, w] or [h, w, c]. If None, will use identity.
scale (float): a multiplier on pixel values, applied after map_func.
"""
op_name, self.tensor_name = get_op_tensor_name(tensor_name)
self.func = map_func
if prefix is None:
self.prefix = op_name
else:
self.prefix = prefix
self.log_dir = logger.get_logger_dir()
self.scale = scale
def _before_train(self):
self._tensor = self.graph.get_tensor_by_name(self.tensor_name)
def _trigger(self):
val = self.trainer.sess.run(self._tensor)
if self.func is not None:
val = self.func(val)
if isinstance(val, list) or val.ndim == 4:
for idx, im in enumerate(val):
self._dump_image(im, idx)
else:
self._dump_image(val)
self.trainer.monitors.put_image(self.prefix, val)
def _dump_image(self, im, idx=None):
assert im.ndim in [2, 3], str(im.ndim)
fname = os.path.join(
self.log_dir,
self.prefix + '-ep{:03d}{}.png'.format(
self.epoch_num, '-' + str(idx) if idx else ''))
res = im * self.scale
res = np.clip(res, 0, 255)
cv2.imwrite(fname, res.astype('uint8'))
try:
import cv2
except ImportError:
from ..utils.develop import create_dummy_class
DumpTensorAsImage = create_dummy_class('DumpTensorAsImage', 'cv2') # noqa
# alias
DumpParamAsImage = DumpTensorAsImage
DumpTensor = DumpTensors
|
the-stack_0_14763 | # -*- coding: utf-8 -*-
import json
import shutil
import logging
from pathlib import Path
from tempfile import TemporaryDirectory
import numpy as np
import rasterio
import rasterio.mask
from retrying import retry
try:
import gdal
except ModuleNotFoundError as e:
try:
from osgeo import gdal
except ModuleNotFoundError:
raise e
from ost.helpers import vector as vec
from ost.helpers import helpers as h
logger = logging.getLogger(__name__)
def create_timeseries_mosaic_vrt(list_of_args):
ts_dir, product, outfiles = list_of_args
gdal.BuildVRT(
str(ts_dir.joinpath(f'{product}.Timeseries.vrt')),
[str(outfile) for outfile in outfiles],
options=gdal.BuildVRTOptions(srcNodata=0, separate=True)
)
@retry(stop_max_attempt_number=3, wait_fixed=1)
def mosaic(filelist, outfile, config_file, cut_to_aoi=None, harm=None):
if outfile.parent.joinpath(f'.{outfile.name[:-4]}.processed').exists():
logger.info(f'{outfile} already exists.')
return
logger.info(f'Mosaicking file {outfile}.')
with open(config_file, 'r') as ard_file:
config_dict = json.load(ard_file)
temp_dir = config_dict['temp_dir']
aoi = config_dict['aoi']
epsg = config_dict['processing']['single_ARD']['dem']['out_projection']
if not harm:
harm = config_dict['processing']['mosaic']['harmonization']
if not cut_to_aoi:
cut_to_aoi = config_dict['processing']['mosaic']['cut_to_aoi']
logfile = outfile.parent.joinpath(f'{str(outfile)[:-4]}.errLog')
with TemporaryDirectory(prefix=f'{temp_dir}/') as temp:
temp = Path(temp)
# get datatype from first image in our mosaic filelist
with rasterio.open(filelist.split(' ')[0]) as src:
dtype = src.meta['dtype']
dtype = 'float' if dtype == 'float32' else dtype
if cut_to_aoi:
tempfile = temp.joinpath(outfile.name)
else:
tempfile = outfile
harm = 'band' if harm else 'none'
cmd = (
f"otbcli_Mosaic -ram 8192 -progress 1 "
f"-comp.feather large "
f"-harmo.method {harm} "
f"-harmo.cost rmse "
f"-tmpdir {str(temp)} "
f"-interpolator bco"
f" -il {filelist} "
f" -out {str(tempfile)} {dtype}"
)
return_code = h.run_command(cmd, logfile)
if return_code != 0:
if tempfile.exists():
tempfile.unlink()
return
if cut_to_aoi:
# get aoi in a way rasterio wants it
aoi_gdf = vec.wkt_to_gdf(aoi)
features = vec.gdf_to_json_geometry(aoi_gdf.to_crs(epsg=epsg))
# import raster and mask
with rasterio.open(tempfile) as src:
out_image, out_transform = rasterio.mask.mask(src, features,
crop=True)
out_meta = src.meta.copy()
ndv = src.nodata
out_image = np.ma.masked_where(out_image == ndv, out_image)
out_meta.update({
'driver': 'GTiff',
'height': out_image.shape[1],
'width': out_image.shape[2],
'transform': out_transform,
'tiled': True,
'blockxsize': 128,
'blockysize': 128
})
with rasterio.open(outfile, 'w', **out_meta) as dest:
dest.write(out_image.data)
# remove intermediate file
tempfile.unlink()
# check
return_code = h.check_out_tiff(outfile)
if return_code != 0:
if outfile.exists():
outfile.unlink()
else:
check_file = outfile.parent.joinpath(
f'.{outfile.name[:-4]}.processed'
)
with open(str(check_file), 'w') as file:
file.write('passed all tests \n')
def gd_mosaic(list_of_args):
filelist, outfile, config_file = list_of_args
mosaic(filelist, outfile, config_file)
def _burst_list(track, date, product, subswath, config_dict):
from shapely.wkt import loads
import geopandas as gpd
aoi = loads(config_dict['aoi'])
processing_dir = Path(config_dict['processing_dir'])
# adjust search pattern in case of coherence
search_last = f'*.{product}.tif' if 'coh' in product else f'{product}.tif'
# search for all bursts within subswath(s) in time-series
list_of_files = list(processing_dir.glob(
f'[A,D]{track}_{subswath}*/Timeseries/'
f'*.{date}.{search_last}'
))
# search for timescans (in case timeseries not found)
if not list_of_files:
list_of_files = list(processing_dir.glob(
f'[A,D]{track}_{subswath}*/Timescan/'
f'*.{product}.{date}.tif'
))
if not list_of_files:
return None
# get a list of all extent files to check for real AOI overlap
if config_dict['processing']['time-series_ARD']['apply_ls_mask']:
list_of_extents = processing_dir.glob(
f'*{track}_{subswath}*/*{track}*.valid.json'
)
else:
list_of_extents = processing_dir.glob(
f'*{track}_{subswath}*/*{track}*.min_bounds.json'
)
list_of_actual_extents = []
for burst_extent in list_of_extents:
burst = gpd.read_file(burst_extent)
if any(burst.intersects(aoi)):
burst_name = Path(str(burst_extent).split('.')[-3]).name
list_of_actual_extents.append(burst_name)
# filter the bursts for real AOI overlap
list_of_files = [
file for file in list_of_files for pattern in list_of_actual_extents
if pattern in str(file)
]
# and join them into a otb readable list
list_of_files = ' '.join([str(file) for file in list_of_files])
return list_of_files
def mosaic_slc_acquisition(track, date, product, outfile, config_file):
# -------------------------------------
# 1 load project config
with open(config_file, 'r') as ard_file:
config_dict = json.load(ard_file)
temp_dir = Path(config_dict['temp_dir'])
# create a list of bursts that actually overlap theAOI
list_of_iw12 = _burst_list(track, date, product, 'IW[1,2]', config_dict)
list_of_iw3 = _burst_list(track, date, product, 'IW3', config_dict)
if list_of_iw12:
logger.info(
f'Pre-mosaicking {product} acquisition\'s IW1 and IW2 subswaths '
f'from {track} taken at {date}.'
)
temp_iw12 = temp_dir.joinpath(f'{date}_{track}_{product}_IW1_2.tif')
mosaic(list_of_iw12, temp_iw12, config_file, harm=False)
if list_of_iw3:
logger.info(
f'Pre-mosaicking {product} acquisition\'s IW3 subswath '
f'from {track} taken at {date}.'
)
temp_iw3 = temp_dir.joinpath(f'{date}_{track}_{product}_IW3.tif')
mosaic(list_of_iw3, temp_iw3, config_file, harm=False)
if list_of_iw12 and list_of_iw3:
mosaic(
' '.join([str(temp_iw12), str(temp_iw3)]), outfile, config_file,
False, harm=True
)
temp_iw12.unlink()
temp_iw3.unlink()
elif list_of_iw12 and not list_of_iw3:
shutil.move(temp_iw12, outfile)
elif not list_of_iw12 and list_of_iw3:
shutil.move(temp_iw3, outfile)
else:
return
def gd_mosaic_slc_acquisition(list_of_args):
track, date, product, outfile, config_file = list_of_args
mosaic_slc_acquisition(track, date, product, outfile, config_file) |
the-stack_0_14766 | from discord import Game
from aiohttp import ClientSession
from discord.ext import commands, tasks
# -----------------------------------------------------
#-------------------- START CONFIG --------------------
# -----------------------------------------------------
discordBotToken = "" #type: str
battleMetricsServerID = None #type: int
# -----------------------------------------------------
#--------------------- END CONFIG ---------------------
# -----------------------------------------------------
client = commands.Bot(command_prefix="-",help_command=None)
@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.errors.CommandNotFound):
pass
@client.event
async def on_ready():
print(f"Bot successfully started\n")
@tasks.loop(seconds=60)
async def change_status():
await client.wait_until_ready()
serverData = await makeWebRequest(f"https://api.battlemetrics.com/servers/{battleMetricsServerID}")
if serverData == None:
return
serverPlayers = serverData['data']['attributes']['players']
serverMaxPlayers = serverData['data']['attributes']['maxPlayers']
serverQueue = serverData['data']['attributes']['details']['rust_queued_players']
if serverQueue > 0:
await client.change_presence(activity=Game(f"{serverPlayers}/{serverMaxPlayers} Queue {serverQueue}"))
else:
await client.change_presence(activity=Game(f"{serverPlayers}/{serverMaxPlayers}"))
async def makeWebRequest(URL):
async with ClientSession() as session:
async with session.get(URL) as preJSData:
if preJSData.status == 200:
return await preJSData.json()
else:
print(f"BattleMetrics Error [Code {preJSData.status}]")
change_status.start()
client.run(discordBotToken) |
the-stack_0_14768 | """Definitions of common enumerations to be used together with ``Enum`` property. """
from __future__ import absolute_import
from six import string_types
from . import colors, icons, palettes
class Enumeration(object):
pass
def enumeration(*values):
if not (values and all(isinstance(value, string_types) and value for value in values)):
raise ValueError("expected a non-empty sequence of strings, got %s" % values)
if len(values) != len(set(values)):
raise ValueError("enumeration items must be unique, got %s" % values)
attrs = dict([ (value, value) for value in values ])
attrs.update({
"__slots__": [],
"_values": list(values),
"_default": values[0],
})
return type("Enumeration", (Enumeration,), attrs)()
LineJoin = enumeration("miter", "round", "bevel")
LineDash = enumeration("solid", "dashed", "dotted", "dotdash", "dashdot")
LineCap = enumeration("butt", "round", "square")
FontStyle = enumeration("normal", "italic", "bold")
TextAlign = enumeration("left", "right", "center")
TextBaseline = enumeration("top", "middle", "bottom", "alphabetic", "hanging")
Direction = enumeration("clock", "anticlock")
Units = enumeration("screen", "data")
AngleUnits = enumeration("deg", "rad")
DatetimeUnits = enumeration("microseconds", "milliseconds", "seconds", "minsec", "minutes", "hourmin", "hours", "days", "months", "years")
Dimension = enumeration("width", "height", "x", "y")
Anchor = enumeration("top_left", "top_center", "top_right", "right_center", "bottom_right", "bottom_center", "bottom_left", "left_center", "center")
Location = enumeration("above", "below", "left", "right")
Orientation = enumeration("top_right", "top_left", "bottom_left", "bottom_right")
DashPattern = enumeration("solid", "dashed", "dotted", "dotdash", "dashdot")
ButtonType = enumeration("default", "primary", "success", "warning", "danger", "link")
NamedColor = enumeration(*colors.__colors__)
NamedIcon = enumeration(*icons.__icons__)
Palette = enumeration(*palettes.__palettes__)
MapType = enumeration("satellite", "roadmap", "terrain", "hybrid")
DateFormat = enumeration("ATOM", "W3C", "RFC-3339", "ISO-8601", "COOKIE", "RFC-822", "RFC-850", "RFC-1036", "RFC-1123", "RFC-2822", "RSS", "TICKS", "TIMESTAMP")
RoundingFunction = enumeration("round", "nearest", "floor", "rounddown", "ceil", "roundup")
NumeralLanguage = enumeration("be-nl", "chs", "cs", "da-dk", "de-ch", "de", "en", "en-gb", "es-ES", "es", "et", "fi", "fr-CA", "fr-ch", "fr", "hu", "it", "ja", "nl-nl", "pl", "pt-br", "pt-pt", "ru", "ru-UA", "sk", "th", "tr", "uk-UA")
|
the-stack_0_14770 | # Copyright 2018 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Optional, Tuple
import cirq
from cirq import Extensions, ops
from cirq import abc
from cirq.ops import gate_features
class QCircuitDiagrammable(metaclass=abc.ABCMeta):
@abc.abstractmethod
def qcircuit_diagram_info(self, args: ops.TextDiagramInfoArgs
) -> ops.TextDiagramInfo:
pass
def _escape_text_for_latex(text):
escaped = (text
.replace('\\', '\\textbackslash{}')
.replace('^', '\\textasciicircum{}')
.replace('~', '\\textasciitilde{}')
.replace('_', '\\_')
.replace('{', '\\{')
.replace('}', '\\}')
.replace('$', '\\$')
.replace('%', '\\%')
.replace('&', '\\&')
.replace('#', '\\#'))
return '\\text{' + escaped + '}'
class _HardcodedQCircuitSymbolsGate(QCircuitDiagrammable):
def __init__(self, *symbols: str) -> None:
self.symbols = symbols
def qcircuit_diagram_info(self, args: ops.TextDiagramInfoArgs
) -> ops.TextDiagramInfo:
return ops.TextDiagramInfo(self.symbols)
def _get_multigate_parameters(gate: ops.TextDiagrammable,
args: ops.TextDiagramInfoArgs
) -> Optional[Tuple[int, int]]:
if not isinstance(gate, gate_features.InterchangeableQubitsGate):
return None
if args.qubit_map is None or args.known_qubits is None:
return None
indices = [args.qubit_map[q] for q in args.known_qubits]
min_index = min(indices)
n_qubits = len(args.known_qubits)
if sorted(indices) != list(range(min_index, min_index + n_qubits)):
return None
return min_index, n_qubits
class _TextToQCircuitDiagrammable(QCircuitDiagrammable):
def __init__(self, sub: ops.TextDiagrammable) -> None:
self.sub = sub
def qcircuit_diagram_info(self, args: ops.TextDiagramInfoArgs
) -> ops.TextDiagramInfo:
info = self.sub.text_diagram_info(args)
multigate_parameters = _get_multigate_parameters(self.sub, args)
if multigate_parameters is not None:
min_index, n_qubits = multigate_parameters
name = _escape_text_for_latex(str(self.sub).rsplit('**', 1)[0])
if info.exponent != 1:
name += '^{' + str(info.exponent) + '}'
box = '\multigate{' + str(n_qubits - 1) + '}{' + name + '}'
ghost = '\ghost{' + name + '}'
assert args.qubit_map is not None
assert args.known_qubits is not None
symbols = tuple(box if (args.qubit_map[q] == min_index) else
ghost for q in args.known_qubits)
return ops.TextDiagramInfo(symbols, exponent=info.exponent,
connected=False)
s = [_escape_text_for_latex(e) for e in info.wire_symbols]
if info.exponent != 1:
s[0] += '^{' + str(info.exponent) + '}'
return ops.TextDiagramInfo(tuple('\\gate{' + e + '}' for e in s))
class _FallbackQCircuitGate(QCircuitDiagrammable):
def __init__(self, sub: ops.Gate) -> None:
self.sub = sub
def qcircuit_diagram_info(self, args: ops.TextDiagramInfoArgs
) -> ops.TextDiagramInfo:
name = str(self.sub)
qubit_count = ((len(args.known_qubits) if
(args.known_qubits is not None) else 1)
if args.known_qubit_count is None
else args.known_qubit_count)
symbols = tuple(_escape_text_for_latex('{}:{}'.format(name, i))
for i in range(qubit_count))
return ops.TextDiagramInfo(symbols)
fallback_qcircuit_extensions = Extensions()
fallback_qcircuit_extensions.add_cast(
QCircuitDiagrammable,
ops.TextDiagrammable,
_TextToQCircuitDiagrammable)
fallback_qcircuit_extensions.add_recursive_cast(
QCircuitDiagrammable,
ops.GateOperation,
lambda ext, op: ext.try_cast(QCircuitDiagrammable, op.gate))
fallback_qcircuit_extensions.add_cast(
QCircuitDiagrammable,
ops.RotXGate,
lambda gate:
_HardcodedQCircuitSymbolsGate('\\targ')
if gate.half_turns == 1
else None)
fallback_qcircuit_extensions.add_cast(
QCircuitDiagrammable,
ops.MeasurementGate,
lambda gate: _HardcodedQCircuitSymbolsGate('\\meter'))
fallback_qcircuit_extensions.add_cast(
QCircuitDiagrammable,
cirq.google.ExpWGate,
lambda gate:
_HardcodedQCircuitSymbolsGate('\\targ')
if gate.half_turns == 1 and gate.axis_half_turns == 0
else None)
fallback_qcircuit_extensions.add_cast(
QCircuitDiagrammable,
ops.Rot11Gate,
lambda gate:
_HardcodedQCircuitSymbolsGate('\\control', '\\control')
if gate.half_turns == 1
else None)
fallback_qcircuit_extensions.add_cast(
QCircuitDiagrammable,
ops.CNotGate,
lambda gate: _HardcodedQCircuitSymbolsGate('\\control', '\\targ'))
fallback_qcircuit_extensions.add_cast(
QCircuitDiagrammable,
ops.Gate,
_FallbackQCircuitGate)
|
the-stack_0_14772 | import numpy as np
import time
from deprecated import deprecated
from sklearn.ensemble import GradientBoostingClassifier
from sklearn import datasets
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from sklearn import ensemble
from scipy.special import expit, logsumexp
from CartTree_regression_xrh import *
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import f1_score
from sklearn.metrics import precision_recall_curve
import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve
class GBDT_Regressor:
"""
适用于 回归问题 的 梯度提升树
基分类器为 CART 回归树
Author: xrh
Date: 2021-04-04
ref: https://blog.csdn.net/zpalyq110/article/details/79527653
test0: 回归 任务
数据集:boston房价 数据集
参数: error_rate_threshold=0.01, max_iter=100, max_depth=3,learning_rate=0.1
训练集数量:455
测试集数量:51
测试集的 MSE: 7.610308909461337
模型训练时长:160s
"""
def __init__(self, square_loss_threshold=0.05, max_iter=10, max_depth=3):
# 训练中止条件 square_loss < self.square_loss_threshold ( 若当前得到的基分类器的组合 平方损失 小于阈值, 则停止训练)
self.square_loss_threshold = square_loss_threshold
# 最大迭代次数
self.max_iter = max_iter
self.max_depth = max_depth
self.G = [] # 弱分类器 集合
def fit(self, X, y, learning_rate):
"""
对训练数据进行学习
"""
f = 0 # 基分类器 的加权和
y_predict = np.mean(y)
# y_predict =0
self.G.append(y_predict)
f += y_predict
feature_value_set = RegresionTree.get_feature_value_set(X) # 可供选择的特征集合 , 包括 (特征, 切分值)
for m in range(self.max_iter): # 进行 第 m 轮迭代
r = y - f # 残差
RT = RegresionTree(threshold=0.01, max_depth=self.max_depth,print_log=False)
# RT=DecisionTreeRegressor(max_depth=self.max_depth) # sklearn 的 回归树
RT.fit(X, r, feature_value_set=feature_value_set)
y_predict = RT.predict(X)
self.G.append((learning_rate, RT)) # 存储 基分类器
# 当前 所有弱分类器加权 得到的 最终分类器 的 分类错误率
f += learning_rate * y_predict
square_loss = np.average(np.square(f - y)) # 平方误差损失
print('round:{}, square_loss:{}'.format(m, square_loss))
print('======================')
if square_loss < self.square_loss_threshold: # 错误率 已经小于 阈值, 则停止训练
break
def predict(self, X):
"""
对新数据进行预测
"""
f = 0 # 最终分类器
f += self.G[0] # 第一个 存储的是 初始化情况
for alpha, RT in self.G[1:]:
y_predict = RT.predict(X)
f += alpha * y_predict
return f
def score(self, X, y):
"""对训练效果进行评价"""
f = self.predict(X)
square_loss = np.average(np.square(f - y)) # 平方误差损失
return square_loss
class GBDT_2Classifier:
"""
适用于 二分类 问题 的 梯度提升树
基分类器为 CART 回归树
Author: xrh
Date: 2021-04-10
ref: https://zhuanlan.zhihu.com/p/89549390
test1: 二分类任务
数据集:Mnist
参数: error_rate_threshold=0.01, max_iter=30, max_depth=3,learning_rate=0.2
训练集数量:60000
测试集数量:10000
正确率: 0.9891
模型训练时长:205.7052161693573
"""
def __init__(self, error_rate_threshold=0.05, max_iter=10, max_depth=1):
"""
:param error_rate_threshold: 训练中止条件, 若当前得到的基分类器的组合 的错误率 小于阈值, 则停止训练
:param max_iter: 最大迭代次数
:param max_depth: CART 回归树 的最大深度
"""
# 训练中止条件 error_rate < self.error_rate_threshold ( 若当前得到的基分类器的组合 的错误率 小于阈值, 则停止训练)
self.error_rate_threshold = error_rate_threshold
# 最大迭代次数
self.max_iter = max_iter
# CART 回归树 的最大深度
self.max_depth = max_depth
self.G = [] # 弱分类器 集合
def sigmoid( self , X ):
"""
sigmoid 激活函数
:param X:
:return:
"""
return 1 / (1 + np.exp(-X))
def fit(self, X, y, learning_rate):
"""
用 训练数据 拟合模型
:param X: 特征数据 , shape=(N_sample, N_feature)
:param y: 标签数据 , shape=(N_sample,)
:param learning_rate: 学习率
:return:
"""
N = np.shape(X)[0] # 样本的个数
f = 0 # 基分类器 的加权和
P_1 = len(y[y == 1]) / len(y)
y_predict = np.log(P_1 / (1 - P_1))
self.G.append(y_predict)
f += y_predict
feature_value_set = RegresionTree.get_feature_value_set(X) # 可供选择的特征集合 , 包括 (特征, 切分值)
for m in range(self.max_iter): # 进行 第 m 轮迭代
r = y - self.sigmoid(f) # 残差
RT = RegresionTree_GBDT(min_square_loss=0.1, max_depth=self.max_depth,print_log=False)
RT.fit(X, r, y, feature_value_set=feature_value_set)
y_predict = RT.predict(X)
self.G.append((learning_rate, RT)) # 存储 基分类器
f += learning_rate * y_predict
# 计算 当前 所有弱分类器加权 得到的 最终分类器 的 分类错误率
G = self.sigmoid(f)
#TODO: 负例 设置为 -1 会导致 在训练集的 训练误差率无法下降 \
# 原因: 二分类时 ,默认 y = {0,1}, 若要 改为 y={-1,1} 则 损失函数 要使用另外的形式
G[G >= 0.5] = 1 # 概率 大于 0.5 被标记为 正例
G[G < 0.5] = 0 # 概率 小于 0.5 被标记为 负例
err_arr = np.ones(N, dtype=int)
err_arr[G == y] = 0
err_rate = np.mean(err_arr)
print('round:{}, err_rate:{}'.format(m, err_rate))
print('======================')
if err_rate < self.error_rate_threshold: # 错误率 已经小于 阈值, 则停止训练
break
def predict(self, X):
"""
对 测试 数据进行预测, 返回预测的标签
:param X: 特征数据 , shape=(N_sample, N_feature)
:return:
"""
f = 0 # 最终分类器
f += self.G[0] # 第一个 存储的是 初始化情况
for alpha, RT in self.G[1:]:
y_predict = RT.predict(X)
f += alpha * y_predict
# print('f:',f)
G = self.sigmoid(f)
# print('G:',G)
G[G >= 0.5] = 1 # 概率 大于 0.5 被标记为 正例
G[G < 0.5] = 0 # 概率 小于 0.5 被标记为 负例
return G
def predict_proba(self, X):
"""
对 测试 数据进行预测, 返回预测的 概率值
:param X: 特征数据 , shape=(N_sample, N_feature)
:return:
"""
f = 0 # 最终分类器
f += self.G[0] # 第一个 存储的是 初始化情况
for alpha, RT in self.G[1:]:
y_predict = RT.predict(X)
f += alpha * y_predict
# print('f:',f)
G = self.sigmoid(f)
return G
def score(self, X, y):
"""
使用 测试数据集 对模型进行评价, 返回正确率
:param X: 特征数据 , shape=(N_sample, N_feature)
:param y: 标签数据 , shape=(N_sample,)
:return: 正确率 accuracy
"""
N = np.shape(X)[0] # 样本的个数
G = self.predict(X)
err_arr = np.ones(N, dtype=int)
err_arr[G == y] = 0
err_rate = np.mean(err_arr)
accuracy = 1 - err_rate
return accuracy
class GBDT_MultiClassifier:
"""
适用于 二分类 问题 的 梯度提升树
基分类器为 CART 回归树
Author: xrh
Date: 2021-04-18
ref: https://zhuanlan.zhihu.com/p/91652813
test1: 多分类任务
数据集:Mnist
参数: error_rate_threshold=0.01, max_iter=20, max_depth=3 , learning_rate=0.5
训练集数量:60000
测试集数量:10000
正确率: 0.915
模型训练时长:1542s
"""
def __init__(self, error_rate_threshold=0.05, max_iter=10, max_depth=1):
"""
:param error_rate_threshold: 训练中止条件, 若当前得到的基分类器的组合 的错误率 小于阈值, 则停止训练
:param max_iter: 最大迭代次数
:param max_depth: CART 回归树 的最大深度
"""
# 训练中止条件 error_rate < self.error_rate_threshold ( 若当前得到的基分类器的组合 的错误率 小于阈值, 则停止训练)
self.error_rate_threshold = error_rate_threshold
# 最大迭代次数
self.max_iter = max_iter
# CART 回归树 的最大深度
self.max_depth = max_depth
self.G = [] # 弱分类器 集合
def sigmoid( self , X ):
"""
sigmoid 激活函数
:param X:
:return:
"""
return 1 / (1 + np.exp(-X))
@deprecated(version='1.0', reason="You should use another function")
def softmax_v1_0(self,X):
"""
softmax处理,将结果转化为概率
:param X:
:return:
"""
#TODO: 导致 上溢出 和 下溢出 问题
return np.exp(X) / np.sum( np.exp(X) , axis=0 ) # softmax处理,将结果转化为概率
@deprecated(version='1.1', reason="You should use another function")
def softmax_v1_1(self,X):
"""
softmax处理,将结果转化为概率
解决了 softmax的 上溢出 和 下溢出的问题
ref: https://www.cnblogs.com/guoyaohua/p/8900683.html
:param X: shape (K,N)
:return: shape (N,)
"""
X_max= np.max( X, axis=0)
X= X-X_max
return np.exp(X) / np.sum( np.exp(X) , axis=0 ) # softmax处理,将结果转化为概率
def softmax(self,X):
"""
softmax处理,将结果转化为概率
解决了 softmax的 溢出问题
np.nan_to_num : 使用0代替数组x中的nan元素,使用有限的数字代替inf元素
ref: sklearn 源码
MultinomialDeviance -> def negative_gradient
:param X: shape (K,N)
:return: shape (N,)
"""
return np.nan_to_num( np.exp(X - logsumexp(X, axis=0)) ) # softmax处理,将结果转化为概率
def fit(self, X, y, learning_rate):
"""
用 训练数据 拟合模型
:param X: 特征数据 , shape=(N_sample, N_feature)
:param y: 标签数据 , shape=(N_sample,)
:param learning_rate: 学习率
:return:
"""
N = np.shape(X)[0] # 样本的个数
self.K = len({ele for ele in y}) # y 中有多少种不同的标签, K分类
print('according to the training dataset : K={} classification task'.format(self.K))
F_0 = np.zeros( (self.K ),dtype=float) # shape : (K,)
for k in range(self.K): # 遍历 所有的 类别
F_0[k] = len(y[y == k]) / len(y)
self.G.append(F_0)
F = np.transpose([F_0] * N) # 对 F_0 进行复制, shape : (K, N)
feature_value_set = RegresionTree.get_feature_value_set(X) # 可供选择的特征集合 , 包括 (特征, 切分值)
y_one_hot = (y == np.array(range(self.K)).reshape(-1, 1)).astype(
np.int8) # 将 预测向量 扩展为 one-hot , shape: (K,N)
for m in range(1,self.max_iter): # 进行 第 m 轮迭代
p = self.softmax( F ) # shape: (K,N)
DT_list=[]
for k in range(self.K): # 依次训练 K 个 二分类器
print( '======= train No.{} 2Classifier ======='.format(k) )
r = y_one_hot[k] - p[k] # 残差 shape:(N,)
# 训练 用于 2分类的 回归树
DT = RegresionTree_GBDT(min_square_loss=0.1, max_depth=self.max_depth,print_log=True)
DT.fit(X, r, y_one_hot[k], feature_value_set=feature_value_set)
y_predict = (self.K / (self.K-1)) * ( DT.predict(X) ) # shape:(N,)
DT_list.append(DT)
F[k] += learning_rate * y_predict # F[k] shape:(N,)
# print('======= end =======')
self.G.append( (learning_rate, DT_list) ) # 存储 基分类器
# 计算 当前 所有弱分类器加权 得到的 最终分类器 的 分类错误率
G = self.softmax( F ) # F shape: (K,N)
G_label = np.argmax( G, axis=0 ) # 取 概率最大的 作为 预测的标签
err_arr = np.ones( N, dtype=int )
err_arr[G_label == y] = 0
err_rate = np.mean(err_arr) # 计算训练误差
print('round:{}, err_rate:{}'.format(m, err_rate))
print('======================')
if err_rate < self.error_rate_threshold: # 错误率 已经小于 阈值, 则停止训练
break
def predict(self, X):
"""
对 测试 数据进行预测, 返回预测的标签
:param X: 特征数据 , shape=(N_sample, N_feature)
:return:
"""
N = np.shape(X)[0] # 样本的个数
F_0 = self.G[0] # G中 第一个 存储的是 初始化情况
F = np.transpose([F_0] * N) # shape : (K, N)
for alpha, DT_list in self.G[1:]:
for k in range(self.K):
DT = DT_list[k]
y_predict = (self.K / (self.K - 1)) * (DT.predict(X)) # shape:(N,)
F[k] += alpha * y_predict # F[k] shape:(N,)
G = self.softmax(F)
G_label = np.argmax(G, axis=0)
return G_label
def predict_proba(self, X):
"""
对 测试 数据进行预测, 返回预测的 概率值
:param X: 特征数据 , shape=(N_sample, N_feature)
:return:
"""
F = self.G[0] # 第一个 存储的是 初始化情况
for alpha, DT_list in self.G[1:]:
for k in range(self.K):
DT = DT_list[k]
y_predict = (self.K / (self.K - 1)) * (DT.predict(X)) # shape:(N,)
DT_list.append(DT)
F[k] += alpha * y_predict # F[k] shape:(N,)
G = self.softmax(F)
return G
def score(self, X, y):
"""
使用 测试数据集 对模型进行评价, 返回正确率
:param X: 特征数据 , shape=(N_sample, N_feature)
:param y: 标签数据 , shape=(N_sample,)
:return: 正确率 accuracy
"""
N = np.shape(X)[0] # 样本的个数
G = self.predict(X)
err_arr = np.ones(N, dtype=int)
err_arr[G == y] = 0
err_rate = np.mean(err_arr)
accuracy = 1 - err_rate
return accuracy
class Test:
def test_tiny_regress_dataset(self):
"""
利用 https://blog.csdn.net/zpalyq110/article/details/79527653 中的数据集
测试 GBDT 回归
:return:
"""
# 获取训练集
dataset = np.array(
[[5, 20, 1.1],
[7, 30, 1.3],
[21, 70, 1.7],
[30, 60, 1.8],
])
columns = ['id', 'age', 'weight', 'label']
X = dataset[:, 0:2]
y = dataset[:, 2]
# 开始时间
start = time.time()
# 创建决策树
print('start create model')
clf = GBDT_Regressor(max_iter=5, max_depth=3)
clf.fit(X, y, learning_rate=0.1)
print(' model complete ')
# 结束时间
end = time.time()
print('time span:', end - start)
# 测试数据集
X_test = np.array([
[25, 65]
])
y_predict = clf.predict(X_test)
print('res: ', y_predict)
def test_regress_dataset(self):
"""
利用 boston房价 数据集
测试 GBDT 回归
:return:
"""
# 加载sklearn自带的波士顿房价数据集
dataset = load_boston()
# 提取特征数据和目标数据
X = dataset.data
y = dataset.target
# 将数据集以9:1的比例随机分为训练集和测试集,为了重现随机分配设置随机种子,即random_state参数
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.9, test_size=0.1, random_state=188)
# 实例化估计器对象
params = {'n_estimators': 100, 'max_depth': 3, 'min_samples_split': 2,
'learning_rate': 0.1, 'loss': 'ls'}
gbr = ensemble.GradientBoostingRegressor(**params)
# 估计器拟合训练数据
gbr.fit(X_train, y_train)
# 训练完的估计器对测试数据进行预测
y_pred = gbr.predict(X_test)
# 输出特征重要性列表
# print(gbr.feature_importances_)
start = time.time()
print('start create model')
clf = GBDT_Regressor(max_iter=100, max_depth=3)
clf.fit(X_train, y_train, learning_rate=0.1)
print(' model complete ')
# 结束时间
end = time.time()
print('time span:', end - start)
y_pred_test = clf.predict(X_test)
print('by sklearn , the squared_error:', mean_squared_error(y_test, y_pred)) # the squared_error: 8.46788133276128
print('by xrh , the squared_error:', mean_squared_error(y_test, y_pred_test)) #
def test_tiny_2classification_dataset(self):
"""
利用 https://blog.csdn.net/zpalyq110/article/details/79527653 中的数据集
测试 GBDT 回归
:return:
"""
dataset = np.array(
[[5, 20, 0],
[7, 30, 0],
[21, 70, 1],
[30, 60, 1],
])
columns = ['age', 'weight', 'label']
X = dataset[:, 0:2]
y = dataset[:, 2]
clf = GBDT_2Classifier(error_rate_threshold=0.0, max_iter=5, max_depth=3)
clf.fit(X, y, learning_rate=0.1)
X_test = np.array(
[[25, 65]])
print('y predict:', clf.predict(X_test))
def loadData_2classification(self, fileName, n=1000):
'''
加载文件
将 数据集 的标签 转换为 二分类的标签
:param fileName:要加载的文件路径
:param n: 返回的数据集的规模
:return: 数据集和标签集
'''
# 存放数据及标记
dataArr = []
labelArr = []
# 读取文件
fr = open(fileName)
cnt = 0 # 计数器
# 遍历文件中的每一行
for line in fr.readlines():
if cnt == n:
break
# 获取当前行,并按“,”切割成字段放入列表中
# strip:去掉每行字符串首尾指定的字符(默认空格或换行符)
# split:按照指定的字符将字符串切割成每个字段,返回列表形式
curLine = line.strip().split(',')
# 将每行中除标记外的数据放入数据集中(curLine[0]为标记信息)
# 在放入的同时将原先字符串形式的数据转换为整型
# 此外将数据进行了二值化处理,大于128的转换成1,小于的转换成0,方便后续计算
dataArr.append([int(int(num) > 128) for num in curLine[1:]])
# 将标记信息放入标记集中
# 转换成二分类任务
# 标签0设置为1,反之为0
# 显然这会导致 正负 样本的 分布不均衡, 1 的样本很少(10%), 而0 的很多
if int(curLine[0]) == 0:
labelArr.append(1)
else:
labelArr.append(0)
# if int(curLine[0]) <= 5:
# labelArr.append(1)
# else:
# labelArr.append(0)
cnt += 1
fr.close()
# 返回数据集和标记
return dataArr, labelArr
def test_Mnist_dataset_2classification(self, n_train, n_test):
"""
将 Mnist (手写数字) 数据集 转变为 二分类 数据集
测试 GBDT, 并对 模型效果做出评估
:param n_train: 使用训练数据集的规模
:param n_test: 使用测试数据集的规模
:return:
"""
# 获取训练集
trainDataList, trainLabelList = self.loadData_2classification('../Mnist/mnist_train.csv', n=n_train)
print('train data, row num:{} , column num:{} '.format(len(trainDataList), len(trainDataList[0])))
trainDataArr = np.array(trainDataList)
trainLabelArr = np.array(trainLabelList)
# 开始时间
print('start training model....')
start = time.time()
'''
sklearn GradientBoostingClassifier 调参:
loss:损失函数。有deviance和exponential两种。deviance是采用对数似然,exponential是指数损失,后者相当于AdaBoost。
n_estimators:最大弱学习器个数,默认是100,调参时要注意过拟合或欠拟合,一般和learning_rate一起考虑。
learning_rate:步长,即每个弱学习器的权重缩减系数,默认为0.1,取值范围0-1,当取值为1时,相当于权重不缩减。较小的learning_rate相当于更多的迭代次数。
subsample:子采样,默认为1,取值范围(0,1],当取值为1时,相当于没有采样。小于1时,即进行采样,按比例采样得到的样本去构建弱学习器。这样做可以防止过拟合,但是值不能太低,会造成高方差。
init:初始化弱学习器。不使用的话就是第一轮迭代构建的弱学习器.如果没有先验的话就可以不用管
由于GBDT使用CART回归决策树。以下参数用于调优弱学习器,主要都是为了防止过拟合
max_feature:树分裂时考虑的最大特征数,默认为None,也就是考虑所有特征。可以取值有:log2,auto,sqrt
max_depth:CART最大深度,默认为None
min_sample_split:划分节点时需要保留的样本数。当某节点的样本数小于某个值时,就当做叶子节点,不允许再分裂。默认是2
min_sample_leaf:叶子节点最少样本数。如果某个叶子节点数量少于某个值,会同它的兄弟节点一起被剪枝。默认是1
min_weight_fraction_leaf:叶子节点最小的样本权重和。如果小于某个值,会同它的兄弟节点一起被剪枝。一般用于权重变化的样本。默认是0
min_leaf_nodes:最大叶子节点数
'''
"""
sklearn 性能指标
参数 learning_rate=0.1, n_estimators=50 , max_depth=3
train data, row num:6000 , column num:784
training cost time : 9.30972957611084
test data, row num:1000 , column num:784
test dataset accuracy: 0.976
"""
clf = GradientBoostingClassifier(loss='deviance', learning_rate=0.1, n_estimators=50
, max_depth=3
)
clf.fit(trainDataArr, trainLabelArr)
# clf = GBDT_2Classifier( error_rate_threshold=0.01, max_iter=30, max_depth=3 )
# clf.fit(trainDataArr, trainLabelArr,learning_rate=0.2)
# 结束时间
end = time.time()
print('training cost time :', end - start)
# 获取测试集
testDataList, testLabelList = self.loadData_2classification('../Mnist/mnist_test.csv', n=n_test)
print('test data, row num:{} , column num:{} '.format(len(testDataList), len(testDataList[0])))
testDataArr = np.array(testDataList)
testLabelArr = np.array(testLabelList)
# print('test dataset accuracy: {} '.format(clf.score(testDataArr, testLabelArr)))
# 模型评估
y_pred = clf.predict(testDataArr)
y_true = testLabelArr
# 1.正确率
print('test dataset accuracy: {} '.format(accuracy_score(y_true, y_pred)))
print('====================')
# 2.精确率
# print(precision_score(y_true, y_pred, average='macro')) #
# print(precision_score(y_true, y_pred, average='micro')) #
# print(precision_score(y_true, y_pred, average='weighted')) #
print('pos-1 precision: ', precision_score(y_true, y_pred, average='binary'))
precision_list = precision_score(y_true, y_pred, average=None)
print('neg-0 precision:{}, pos-1 precision:{} '.format(precision_list[0], precision_list[1]))
print('====================')
# 3. 召回率
# print(recall_score(y_true, y_pred, average='macro')) #
# print(recall_score(y_true, y_pred, average='micro')) #
# print(recall_score(y_true, y_pred, average='weighted')) #
print('pos-1 recall: ', recall_score(y_true, y_pred, average='binary'))
recall_list = recall_score(y_true, y_pred, average=None)
print('neg-0 recall:{}, pos-1 recall:{} '.format(recall_list[0], recall_list[1]))
print('====================')
# 4. F1-score
# print(f1_score(y_true, y_pred, average='macro'))
# print(f1_score(y_true, y_pred, average='micro'))
# print(f1_score(y_true, y_pred, average='weighted'))
print('pos-1 f1_score: ', f1_score(y_true, y_pred, average='binary'))
f1_score_list = f1_score(y_true, y_pred, average=None)
print('neg-0 f1_score:{}, pos-1 f1_score:{} '.format(f1_score_list[0], f1_score_list[1]))
print('====================')
# 画出 P-R 曲线
# sklearn 的 GBDT 作为基线
clf2 = GradientBoostingClassifier(loss='deviance', learning_rate=0.1, n_estimators=30
, max_depth=3
)
clf2.fit(trainDataArr, trainLabelArr)
y_pred = clf.predict(testDataArr)
y_scores = clf.predict_proba(testDataArr)
y_true = testLabelArr
precision, recall, thresholds = precision_recall_curve(y_true, y_scores)
y_scores2 = clf2.predict_proba(testDataArr)[:, 1] # 第 1 列 , 表示为 正例的概率
precision2, recall2, thresholds2 = precision_recall_curve(y_true, y_scores2)
# disp = PrecisionRecallDisplay(precision=precision, recall=recall)
# disp.plot()
plt.plot(recall, precision, label="GDBT_2Classifier(xrh)", color='navy') #
plt.plot(recall2, precision2, label="GradientBoostingClassifier(sklearn)", color='turquoise')
plt.title(' Precision-Recall curve ')
# plt.ylim([0.0, 1.05]) # Y 轴的取值范围
# plt.xlim([0.0, 1.0]) # X 轴的取值范围
plt.xlabel("recall")
plt.ylabel("precision")
plt.legend(loc=(0, -.38), prop=dict(size=14)) # 图例
plt.show()
# ROC 曲线
fpr, tpr, _ = roc_curve(y_true, y_scores)
fpr2, tpr2, _ = roc_curve(y_true, y_scores2)
plt.plot([0, 1], [0, 1], color='navy', linestyle='--')
plt.plot(fpr, tpr, label="GDBT_2Classifier(xrh)", color='darkorange') #
plt.plot(fpr2, tpr2, label="GradientBoostingClassifier(sklearn)", color='turquoise')
# plt.xlim( [0.0, 1.0] )
# plt.ylim( [0.0, 1.05] )
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.legend(loc=(0, -.38), prop=dict(size=14)) # 图例
plt.show()
def test_tiny_multiclassification_dataset(self):
"""
使用 https://zhuanlan.zhihu.com/p/91652813 中的数据测试 GBDT-多分类
:return:
"""
X_train =np.array( [[6],
[12],
[14],
[18],
[20],
[65],
[31],
[40],
[1],
[2],
[100],
[101],
[65],
[54],
])
y_train = np.array([[0], [0], [0], [0], [0], [1], [1], [1], [1], [1], [2], [2], [2], [2]]).ravel()
clf = GBDT_MultiClassifier( error_rate_threshold=0.01, max_iter=5, max_depth=1 )
clf.fit(X_train, y_train,learning_rate=1)
def loadData(self, fileName, n=1000):
'''
加载文件
:param fileName:要加载的文件路径
:param n: 返回的数据集的规模
:return: 数据集和标签集
'''
# 存放数据及标记
dataArr = []
labelArr = []
# 读取文件
fr = open(fileName)
cnt = 0 # 计数器
# 遍历文件中的每一行
for line in fr.readlines():
if cnt == n:
break
# 获取当前行,并按“,”切割成字段放入列表中
# strip:去掉每行字符串首尾指定的字符(默认空格或换行符)
# split:按照指定的字符将字符串切割成每个字段,返回列表形式
curLine = line.strip().split(',')
# 将每行中除标记外的数据放入数据集中(curLine[0]为标记信息)
# 在放入的同时将原先字符串形式的数据转换为整型
# 此外将数据进行了二值化处理,大于128的转换成1,小于的转换成0,方便后续计算
dataArr.append([int(int(num) > 128) for num in curLine[1:]])
# 将标记信息放入标记集中
labelArr.append(int(curLine[0]))
cnt += 1
fr.close()
# 返回数据集和标记
return dataArr, labelArr
def test_Mnist_dataset(self, n_train, n_test):
"""
Mnist (手写数字) 数据集
测试 AdaBoost 的 多分类
:param n_train: 使用训练数据集的规模
:param n_test: 使用测试数据集的规模
:return:
"""
# 获取训练集
trainDataList, trainLabelList = self.loadData('../Mnist/mnist_train.csv', n=n_train)
print('train data, row num:{} , column num:{} '.format(len(trainDataList), len(trainDataList[0])))
trainDataArr = np.array(trainDataList)
trainLabelArr = np.array(trainLabelList)
# 开始时间
print('start training model....')
start = time.time()
"""
调参:
loss:损失函数。有deviance和exponential两种。deviance是采用对数似然,exponential是指数损失,后者相当于AdaBoost。
n_estimators:最大弱学习器个数,默认是100,调参时要注意过拟合或欠拟合,一般和learning_rate一起考虑。
criterion: 切分叶子节点时, 选择切分特征考虑的误差函数, 默认是 “ friedman_mse”( Friedman 均方误差),“ mse”(均方误差)和“ mae”(均绝对误差)
learning_rate:步长,即每个弱学习器的权重缩减系数,默认为0.1,取值范围0-1,当取值为1时,相当于权重不缩减。较小的learning_rate相当于更多的迭代次数。
subsample:子采样,默认为1,取值范围(0,1],当取值为1时,相当于没有采样。小于1时,即进行采样,按比例采样得到的样本去构建弱学习器。这样做可以防止过拟合,但是值不能太低,会造成高方差。
init:初始化弱学习器。不使用的话就是第一轮迭代构建的弱学习器.如果没有先验的话就可以不用管
由于GBDT使用CART回归决策树。以下参数用于调优弱学习器,主要都是为了防止过拟合
max_feature:树分裂时考虑的最大特征数,默认为None,也就是考虑所有特征。可以取值有:log2,auto,sqrt
max_depth:CART最大深度,默认为None
min_sample_split:划分节点时需要保留的样本数。当某节点的样本数小于某个值时,就当做叶子节点,不允许再分裂。默认是2
min_sample_leaf:叶子节点最少样本数。如果某个叶子节点数量少于某个值,会同它的兄弟节点一起被剪枝。默认是1
min_weight_fraction_leaf:叶子节点最小的样本权重和。如果小于某个值,会同它的兄弟节点一起被剪枝。一般用于权重变化的样本。默认是0
min_leaf_nodes:最大叶子节点数
ref: https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.GradientBoostingClassifier.html
测试1:
max_depth=3, n_estimators=30, learning_rate=0.8,
n_train=60000
n_test=10000
训练时间 : 795.5719292163849
准确率: 0.8883
测试2:
max_depth=3, n_estimators=20, learning_rate=0.5,
n_train=60000
n_test=10000
训练时间 : 589 s
准确率: 0.9197
"""
# clf = GradientBoostingClassifier(loss='deviance',criterion='mse', n_estimators=20, learning_rate=0.5,
# max_depth=3)
#
# clf.fit(trainDataArr, trainLabelArr)
clf = GBDT_MultiClassifier( error_rate_threshold=0.01, max_iter=20, max_depth=3 )
clf.fit( trainDataArr, trainLabelArr,learning_rate= 0.5 ) #
# 结束时间
end = time.time()
print('training cost time :', end - start)
# 获取测试集
testDataList, testLabelList = self.loadData('../Mnist/mnist_test.csv', n=n_test)
print('test data, row num:{} , column num:{} '.format(len(testDataList), len(testDataList[0])))
testDataArr = np.array(testDataList)
testLabelArr = np.array(testLabelList)
print('test dataset accuracy: {} '.format(clf.score(testDataArr, testLabelArr)))
def test_iris_dataset(self):
# 使用iris数据集,其中有三个分类, y的取值为0,1,2
X, y = datasets.load_iris(True) # 包括150行记录
# 将数据集一分为二,训练数据占80%,测试数据占20%
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=188)
# clf = GradientBoostingClassifier(loss='deviance',n_estimators=3, learning_rate=0.1,
# max_depth=2)
# clf.fit(X_train, y_train)
clf = GBDT_MultiClassifier( error_rate_threshold=0.01, max_iter=5, max_depth=3 )
clf.fit(X_train, y_train,learning_rate=0.8)
print(clf.score(X_test, y_test))
if __name__ == '__main__':
test = Test()
# test.test_tiny_regress_dataset()
# test.test_regress_dataset()
# test.test_Mnist_dataset_2classification(60000,10000)
# test.test_tiny_2classification_dataset()
# test.test_tiny_multiclassification_dataset()
# test.test_Mnist_dataset(6000, 1000)
# test.test_Mnist_dataset(60000,10000)
test.test_iris_dataset()
|
the-stack_0_14774 | """main.py
# Facial Expression Recognition
**Author**: Christopher Holzweber
**Description**: Bachelorthesis - Prototype for FER
**Institution**: Johannes Kepler University Linz - Institute of Computational Perception
This file handles starts the FER application by creating an instance of the GUI class and call the run() method.
"""
from Application.UserInterface import GUI
if __name__ == '__main__':
app = GUI()
app.run()
|
the-stack_0_14775 | """
This script creates a test that fails when garage.tf.algos.NPO performance is
too low.
"""
import gym
import pytest
import tensorflow as tf
from garage.envs import normalize
from garage.experiment import LocalRunner
from garage.tf.algos import NPO
from garage.tf.baselines import GaussianMLPBaseline
from garage.tf.envs import TfEnv
from garage.tf.policies import GaussianMLPPolicy
from tests.fixtures import TfGraphTestCase
class TestNPO(TfGraphTestCase):
def setup_method(self):
super().setup_method()
self.env = TfEnv(normalize(gym.make('InvertedDoublePendulum-v2')))
self.policy = GaussianMLPPolicy(
env_spec=self.env.spec,
hidden_sizes=(64, 64),
hidden_nonlinearity=tf.nn.tanh,
output_nonlinearity=None,
)
self.baseline = GaussianMLPBaseline(
env_spec=self.env.spec,
regressor_args=dict(hidden_sizes=(32, 32)),
)
@pytest.mark.large
def test_npo_pendulum(self):
"""Test NPO with Pendulum environment."""
with LocalRunner(sess=self.sess) as runner:
algo = NPO(
env_spec=self.env.spec,
policy=self.policy,
baseline=self.baseline,
max_path_length=100,
discount=0.99,
gae_lambda=0.98,
policy_ent_coeff=0.0)
runner.setup(algo, self.env)
last_avg_ret = runner.train(n_epochs=10, batch_size=2048)
assert last_avg_ret > 20
def test_npo_with_unknown_pg_loss(self):
"""Test NPO with unkown pg loss."""
with pytest.raises(ValueError, match='Invalid pg_loss'):
NPO(
env_spec=self.env.spec,
policy=self.policy,
baseline=self.baseline,
pg_loss='random pg_loss',
)
def test_npo_with_invalid_entropy_method(self):
"""Test NPO with invalid entropy method."""
with pytest.raises(ValueError, match='Invalid entropy_method'):
NPO(
env_spec=self.env.spec,
policy=self.policy,
baseline=self.baseline,
entropy_method=None,
)
def test_npo_with_max_entropy_and_center_adv(self):
"""Test NPO with max entropy and center_adv."""
with pytest.raises(ValueError):
NPO(
env_spec=self.env.spec,
policy=self.policy,
baseline=self.baseline,
entropy_method='max',
center_adv=True,
)
def test_npo_with_max_entropy_and_no_stop_entropy_gradient(self):
"""Test NPO with max entropy and false stop_entropy_gradient."""
with pytest.raises(ValueError):
NPO(
env_spec=self.env.spec,
policy=self.policy,
baseline=self.baseline,
entropy_method='max',
stop_entropy_gradient=False,
)
def test_npo_with_invalid_no_entropy_configuration(self):
"""Test NPO with invalid no entropy configuration."""
with pytest.raises(ValueError):
NPO(
env_spec=self.env.spec,
policy=self.policy,
baseline=self.baseline,
entropy_method='no_entropy',
policy_ent_coeff=0.02,
)
def teardown_method(self):
self.env.close()
super().teardown_method()
|
the-stack_0_14778 | # Copyright 2018-2019 Geek Guild Co., Ltd.
# ==============================================================================
import glob
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import os
"""Gif module.
"""
def generate_gif_animation(src_file_path_list, dst_file_path, interval=500, repeat_delay=1000):
# prepare figure
fig = plt.figure()
# clearn the figure edge
ax = plt.subplot(1, 1, 1)
ax.spines['right'].set_color('None')
ax.spines['top'].set_color('None')
ax.spines['left'].set_color('None')
ax.spines['bottom'].set_color('None')
ax.tick_params(axis='x', which='both', top='off', bottom='off', labelbottom='off')
ax.tick_params(axis='y', which='both', left='off', right='off', labelleft='off')
image_list = []
for src_file_path in src_file_path_list:
image_file = Image.open(src_file_path)
# spline36
image_list.append([plt.imshow(image_file, interpolation="spline36")])
# animation
ani = animation.ArtistAnimation(fig, image_list, interval=interval, repeat_delay=repeat_delay)
ani.save(dst_file_path)
if __name__ == '__main__':
# sample
src_dir_path = "/var/tensorflow/tsp/sample/animation/"
src_file_path_list = glob.glob(src_dir_path + "*.png")
generate_gif_animation(src_file_path_list, src_file_path_list) |
the-stack_0_14779 | from ektelo import util
from ektelo.mixins import Marshallable
import hashlib
class Base(Marshallable):
def __init__(self, short_name=None):
if short_name is None:
self.short_name = 'ektelo_' + self.__class__.__name__
else:
self.short_name = short_name
@property
def hash(self):
m = hashlib.sha1()
m.update(util.prepare_for_hash(self.short_name))
for key, value in util.prepare_for_hash(self.init_params).items():
m.update(key.encode('utf-8'))
m.update(repr(value).encode('utf-8'))
return m.hexdigest()
|
the-stack_0_14780 | from .supported import EXCEPTIONS, LICENSES
def normalize_license_expression(license_expression):
if not license_expression:
return license_expression
# First normalize to lower case so we can look up licenses/exceptions
# and so boolean operators are Python-compatible
license_expression = license_expression.lower()
# Then pad parentheses so tokenization can be achieved by merely splitting on white space
license_expression = license_expression.replace('(', ' ( ').replace(')', ' ) ')
# Now we begin parsing
tokens = license_expression.split()
# Rather than implementing boolean logic we create an expression that Python can parse.
# Everything that is not involved with the grammar itself is treated as `False` and the
# expression should evaluate as such.
python_tokens = []
for token in tokens:
if token not in ('or', 'and', 'with', '(', ')'):
python_tokens.append('False')
elif token == 'with':
python_tokens.append('or')
elif token == '(' and python_tokens and python_tokens[-1] not in ('or', 'and'):
raise ValueError('Invalid license expression')
else:
python_tokens.append(token)
python_expression = ' '.join(python_tokens)
try:
assert eval(python_expression) is False
except Exception:
raise ValueError('Invalid license expression')
# Take a final pass to check for unknown licenses/exceptions
normalized_tokens = []
for token in tokens:
if token in ('or', 'and', 'with', '(', ')'):
normalized_tokens.append(token.upper())
continue
if normalized_tokens and normalized_tokens[-1] == 'WITH':
if token not in EXCEPTIONS:
raise ValueError('Unknown license exception: {}'.format(token))
normalized_tokens.append(EXCEPTIONS[token]['id'])
else:
if token.endswith('+'):
token = token[:-1]
suffix = '+'
else:
suffix = ''
if token not in LICENSES:
raise ValueError('Unknown license: {}'.format(token))
normalized_tokens.append(LICENSES[token]['id'] + suffix)
# Construct the normalized expression
normalized_expression = ' '.join(normalized_tokens)
# Fix internal padding for parentheses
normalized_expression = normalized_expression.replace('( ', '(').replace(' )', ')')
return normalized_expression
|
the-stack_0_14782 | import sqlite3
import databaseCreate
#file for deleting the choosen entries
#RUN THE SQL STATEMENT TO DELETE THE SELECTED RECORD
db=sqlite3.connect("SongStorage.db")
def deleteSong(songToDelete):
try:
databaseCreate.createDb()
delete = "DELETE song FROM song WHERE title = ?",(songToDelete,)
cur = db.cursor()
cur.execute(delete)
db.commit()
cur.close()
db.close()
input("Item deleted, press enter to continue: ")
except:
print ("THERE WAS A PROBLEM DELETING THE RECORD")
input("Press Enter to continue: ")
#TAKE USER INPUT AND RUN FUNCTION TO DELETE THE SELECTED RECORD
def DeleteItem():
print ("===============================")
print ("DELEte A SONG RECORD:")
print ("===============================")
songToDelete = input("\nEnter the title of the DVD to delete:\t")
delete = "DELETE song FROM song WHERE title = ? "(songToDelete,)
try:
cur = db.cursor()
cur.execute(delete)
searchResult = cur.fetchall()
if searchResult[0] == ():
raise
except:
print ("THERE WAS A PROBLEM ACCESSING THE RECORD IN THE DATABASE!")
input("Press Enter to continue: ")
return
print( "===============================")
print ("delete song RECORD:")
print( "===============================")
print ("1 - Title:\t" + modifyResult[0][0])
print ("2 - Star:\t" + modifyResult[0][1])
print ("3 - Costar:\t" + modifyResult[0][2])
print ("4 - Year:\t" + modifyResult[0][3])
print ("5 - Genre\t"+ modifyResult[0][4])
print ("===============================")
input("Press enter to continue: ")
print("""
Are you sure you want to delete? Enter a choice and press enter
(Y/y = yes, Anything else = No)
""")
choice = input("\t")
if (choice == "Y" or choice == "y"):
deleteSong(songToDelete)
else:
c.close()
db.close()
input("Item NOT deleted, press enter to continue: ") |
the-stack_0_14783 | import numpy as np
from zest import zest
from plumbum import local
from plaster.run.sigproc_v2 import synth
from plaster.tools.test_tools.test_tools import (
integration_before,
integration_after,
run_p,
)
# The only reason I'm not entirely deleting sigproc_v1 is because
# Angela has a paper in the works
@zest.skip("sigproc_v1 deprecated")
@zest.group("integration")
def zest_sigproc_v1_integration():
# If test_folder is None it will be set by _before()
# otherwise you can set it here to reuse a debugging folder
test_folder = None
# test_folder = (
# "/erisyon/internal/jobs_folder/_integration_tests/it_runs_sigproc_v1/1613159055"
# )
dim = (512, 512)
amps_constant_val = 6000
n_peaks = 1000
bg_mean = 100.0
bg_std = 30.0
channel_scale_factor = (1.0, 0.5)
channel_peak_width_scale_factor = (1.0, 0.8)
psf_width = 1.5
def _synth_field(n_cycles):
with synth.Synth(n_channels=2, n_cycles=n_cycles, dim=dim) as s:
peaks = (
synth.PeaksModelGaussianCircular(n_peaks=n_peaks)
.locs_randomize()
.widths_uniform(psf_width)
.channel_scale_factor(channel_scale_factor)
.channel_peak_width_scale_factor(channel_peak_width_scale_factor)
)
synth.CameraModel(bg_mean=bg_mean, bg_std=bg_std)
synth.HaloModel()
synth.IlluminationQuadraticFalloffModel()
return s, peaks
def _synth_save_field(s, fl_i, source_folder):
chcy_ims = s.render_chcy(0)
for ch_i in range(chcy_ims.shape[0]):
for cy_i in range(chcy_ims.shape[1]):
np.save(
str(
source_folder
/ f"area_{fl_i:03d}_cell_000_{ch_i:03d}nm_{cy_i:03d}.npy"
),
chcy_ims[ch_i, cy_i],
)
def _synth_dyts(source_folder):
n_fields = 3
for fl_i in range(n_fields):
s, peaks = _synth_field(n_cycles=4)
peaks.dyt_random_choice(
[[3, 2, 2, 1], [2, 1, 1, 0], [1, 0, 0, 0]], [0.5, 0.3, 0.2]
)
peaks.gain_constant(amps_constant_val)
_synth_save_field(s, fl_i, source_folder)
def _it_runs_sigproc_v1():
job_folder = test_folder / "sigproc_v1"
source_folder = test_folder / "sigproc_source"
source_folder.mkdir()
_synth_dyts(source_folder)
run_p(
[
f"gen",
f"sigproc_v1",
f"--job={job_folder}",
f"--sigproc_source={source_folder}",
f"--sample=foo",
f"--force",
]
)
run_p(["run", job_folder, "--no_progress"])
# def _it_runs_sigclass():
# """
# Test that classification can run on sigprov_v2 data
# """
#
# csv_file = test_folder / "protein.csv"
# job_folder = test_folder / "sigproc_v1_class"
# source_folder = test_folder / "sigproc_source"
# source_folder.mkdir()
#
# csv_contents = (
# "Name,Abundance,POI,Seq\n"
# "ACE,28,1,"
# "MGAASGRRGPGLLLPLPLLLLLPPQPALALDPGLQPGNFSADEAGAQLFAQSYNSSAEQV"
# "LFQSVAASWAHDTNITAENARRQEEAALLSQEFAEAWGQKAKELYEPIWQNFTDPQLRRI"
# "IGAVRTLGSANLPLAKRQQYNALLSNMSRIYSTAKVCLPNKTATCWSLDPDLTNILASSR"
# "SYAMLLFAWEGWHNAAGIPLKPLYEDFTALSNEAYKQDGFTDTGAYWRSWYNSPTFEDDL"
# "EHLYQQLEPLYLNLHAFVRRALHRRYGDRYINLRGPIPAHLLGDMWAQSWENIYDMVVPF"
# "PDKPNLDVTSTMLQQGWNATHMFRVAEEFFTSLELSPMPPEFWEGSMLEKPADGREVVCH"
# "ASAWDFYNRKDFRIKQCTRVTMDQLSTVHHEMGHIQYYLQYKDLPVSLRRGANPGFHEAI"
# "GDVLALSVSTPEHLHKIGLLDRVTNDTESDINYLLKMALEKIAFLPFGYLVDQWRWGVFS"
# "GRTPPSRYNFDWWYLRTKYQGICPPVTRNETHFDAGAKFHVPNVTPYIRYFVSFVLQFQF"
# "HEALCKEAGYEGPLHQCDIYRSTKAGAKLRKVLQAGSSRPWQEVLKDMVGLDALDAQPLL"
# "KYFQPVTQWLQEQNQQNGEVLGWPEYQWHPPLPDNYPEGIDLVTDEAEASKFVEEYDRTS"
# "QVVWNEYAEANWNYNTNITTETSKILLQKNMQIANHTLKYGTQARKFDVNQLQNTTIKRI"
# "IKKVQDLERAALPAQELEEYNKILLDMETTYSVATVCHPNGSCLQLEPDLTNVMATSRKY"
# "EDLLWAWEGWRDKAGRAILQFYPKYVELINQAARLNGYVDAGDSWRSMYETPSLEQDLER"
# "LFQELQPLYLNLHAYVRRALHRHYGAQHINLEGPIPAHLLGNMWAQTWSNIYDLVVPFPS"
# "APSMDTTEAMLKQGWTPRRMFKEADDFFTSLGLLPVPPEFWNKSMLEKPTDGREVVCHAS"
# "AWDFYNGKDFRIKQCTTVNLEDLVVAHHEMGHIQYFMQYKDLPVALREGANPGFHEAIGD"
# "VLALSVSTPKHLHSLNLLSSEGGSDEHDINFLMKMALDKIAFIPFSYLVDQWRWRVFDGS"
# "ITKENYNQEWWSLRLKYQGLCPPVPRTQGDFDPGAKFHIPSSVPYIRYFVSFIIQFQFHE"
# "ALCQAAGHTGPLHKCDIYQSKEAGQRLATAMKLGFSRPWPEAMQLITGQPNMSASAMLSY"
# "FKPLLDWLRTENELHGEKLGWPQYNWTPNSARSEGPLPDSGRVSFLGLDLDAQQARVGQW"
# "LLLFLGIALLVATLGLSQRLFSIRHRSLHRHSHGPQFGSEVELRHS\n"
# "ACE2,12,1,"
# "MSSSSWLLLSLVAVTAAQSTIEEQAKTFLDKFNHEAEDLFYQSSLASWNYNTNITEENVQ"
# "NMNNAGDKWSAFLKEQSTLAQMYPLQEIQNLTVKLQLQALQQNGSSVLSEDKSKRLNTIL"
# "NTMSTIYSTGKVCNPDNPQECLLLEPGLNEIMANSLDYNERLWAWESWRSEVGKQLRPLY"
# "EEYVVLKNEMARANHYEDYGDYWRGDYEVNGVDGYDYSRGQLIEDVEHTFEEIKPLYEHL"
# "HAYVRAKLMNAYPSYISPIGCLPAHLLGDMWGRFWTNLYSLTVPFGQKPNIDVTDAMVDQ"
# "AWDAQRIFKEAEKFFVSVGLPNMTQGFWENSMLTDPGNVQKAVCHPTAWDLGKGDFRILM"
# "CTKVTMDDFLTAHHEMGHIQYDMAYAAQPFLLRNGANEGFHEAVGEIMSLSAATPKHLKS"
# "IGLLSPDFQEDNETEINFLLKQALTIVGTLPFTYMLEKWRWMVFKGEIPKDQWMKKWWEM"
# "KREIVGVVEPVPHDETYCDPASLFHVSNDYSFIRYYTRTLYQFQFQEALCQAAKHEGPLH"
# "KCDISNSTEAGQKLFNMLRLGKSEPWTLALENVVGAKNMNVRPLLNYFEPLFTWLKDQNK"
# "NSFVGWSTDWSPYADQSIKVRISLKSALGDKAYEWNDNEMYLFRSSVAYAMRQYFLKVKN"
# "QMILFGEEDVRVANLKPRISFNFFVTAPKNVSDIIPRTEVEKAIRMSRSRINDAFRLNDN"
# "SLEFLGIQPTLGPPNQPPVSIWLIVFGVVMGVIVVGIVILIFTGIRDRKKKNKARSGENP"
# "YASIDISKGENNPGFQNTDDVQTSF\n"
# "ACTB,7,1,"
# "MDDDIAALVVDNGSGMCKAGFAGDDAPRAVFPSIVGRPRHQGVMVGMGQKDSYVGDEAQS"
# "KRGILTLKYPIEHGIVTNWDDMEKIWHHTFYNELRVAPEEHPVLLTEAPLNPKANREKMT"
# "QIMFETFNTPAMYVAIQAVLSLYASGRTTGIVMDSGDGVTHTVPIYEGYALPHAILRLDL"
# "AGRDLTDYLMKILTERGYSFTTTAEREIVRDIKEKLCYVALDFEQEMATAASSSSLEKSY"
# "ELPDGQVITIGNERFRCPEALFQPSFLGMESCGIHETTFNSIMKCDVDIRKDLYANTVLS"
# "GGTTMYPGIADRMQKEITALAPSTMKIKIIAPPERKYSVWIGGSILASLSTFQQMWISKQ"
# "EYDESGPSIVHRKCF\n"
# )
# csv_contents = "\n".join(csv_contents.split()) + "\n"
# csv_file.write(csv_contents)
#
# _synth_dyts(source_folder)
#
# # DEBUGGING HINT: Comment out following to debug report only
# run_p(
# [
# f"gen",
# f"classify_v1",
# f"--sample=KidneyBiomarkers1",
# f"--job={job_folder}",
# f"--protein_csv={csv_file}",
# f"--label_set=C,DE",
# f"--protease=trypsin",
# f"--n_pres=1",
# f"--n_mocks=1",
# f"--n_edmans=2",
# f"--rf",
# f"--decoys=reverse",
# f"--force",
# f"--sigproc_source={source_folder}",
# ]
# )
#
# run_p(["run", job_folder, "--no_progress"])
def _before():
nonlocal test_folder
if test_folder is None:
test_folder = integration_before()
test_folder = local.path(test_folder)
def _after():
integration_after()
def it_runs_sigproc_v1():
# zest randomizes order so the following ensures order...
# WHEN DEBUGGING:
# * Set the test_folder to the folder that failed rather then None
# (indicated in the blue trace).
# * Comment out the following tests that you don't need to iterate on
# (Example, _it_runs_calib and _it_runs_sigproc_v2_with_calib has already passed
# and you just want to run _it_runs_sigclass over and over until it passes)
_it_runs_sigproc_v1()
# _it_runs_sigclass()
zest()
|
the-stack_0_14784 | #!/usr/bin/env python3
import os
import subprocess
from typing import List, Optional
from functools import lru_cache
from common.basedir import BASEDIR
from selfdrive.swaglog import cloudlog
TESTED_BRANCHES = ['devel', 'release3-staging', 'dashcam3-staging', 'release3', 'dashcam3']
training_version: bytes = b"0.2.0"
terms_version: bytes = b"2"
def cache(user_function, /):
return lru_cache(maxsize=None)(user_function)
def run_cmd(cmd: List[str]) -> str:
return subprocess.check_output(cmd, encoding='utf8').strip()
def run_cmd_default(cmd: List[str], default: Optional[str] = None) -> Optional[str]:
try:
return run_cmd(cmd)
except subprocess.CalledProcessError:
return default
@cache
def get_commit(branch: str = "HEAD", default: Optional[str] = None) -> Optional[str]:
return run_cmd_default(["git", "rev-parse", branch], default=default)
@cache
def get_short_branch(default: Optional[str] = None) -> Optional[str]:
return run_cmd_default(["git", "rev-parse", "--abbrev-ref", "HEAD"], default=default)
@cache
def get_branch(default: Optional[str] = None) -> Optional[str]:
return run_cmd_default(["git", "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"], default=default)
@cache
def get_origin(default: Optional[str] = None) -> Optional[str]:
try:
local_branch = run_cmd(["git", "name-rev", "--name-only", "HEAD"])
tracking_remote = run_cmd(["git", "config", "branch." + local_branch + ".remote"])
return run_cmd(["git", "config", "remote." + tracking_remote + ".url"])
except subprocess.CalledProcessError: # Not on a branch, fallback
return run_cmd_default(["git", "config", "--get", "remote.origin.url"], default=default)
@cache
def get_normalized_origin(default: Optional[str] = None) -> Optional[str]:
origin: Optional[str] = get_origin()
if origin is None:
return default
return origin.replace("git@", "", 1) \
.replace(".git", "", 1) \
.replace("https://", "", 1) \
.replace(":", "/", 1)
@cache
def get_version() -> str:
with open(os.path.join(BASEDIR, "common", "version.h")) as _versionf:
version = _versionf.read().split('"')[1]
return version
@cache
def get_short_version() -> str:
return get_version().split('-')[0] # type: ignore
@cache
def is_prebuilt() -> bool:
return os.path.exists(os.path.join(BASEDIR, 'prebuilt'))
@cache
def is_comma_remote() -> bool:
# note to fork maintainers, this is used for release metrics. please do not
# touch this to get rid of the orange startup alert. there's better ways to do that
origin: Optional[str] = get_origin()
if origin is None:
return False
return origin.startswith('[email protected]:sunnyhaibin') or origin.startswith('https://github.com/sunnyhaibin')
@cache
def is_tested_branch() -> bool:
return get_short_branch() in TESTED_BRANCHES
@cache
def is_dirty() -> bool:
origin = get_origin()
branch = get_branch()
if (origin is None) or (branch is None):
return True
dirty = False
try:
# Actually check dirty files
if not is_prebuilt():
# This is needed otherwise touched files might show up as modified
try:
subprocess.check_call(["git", "update-index", "--refresh"])
except subprocess.CalledProcessError:
pass
dirty = (subprocess.call(["git", "diff-index", "--quiet", branch, "--"]) != 0)
except subprocess.CalledProcessError:
cloudlog.exception("git subprocess failed while checking dirty")
dirty = True
return dirty
if __name__ == "__main__":
from common.params import Params
params = Params()
params.put("TermsVersion", terms_version)
params.put("TrainingVersion", training_version)
print(f"Dirty: {is_dirty()}")
print(f"Version: {get_version()}")
print(f"Short version: {get_short_version()}")
print(f"Origin: {get_origin()}")
print(f"Normalized origin: {get_normalized_origin()}")
print(f"Branch: {get_branch()}")
print(f"Short branch: {get_short_branch()}")
print(f"Prebuilt: {is_prebuilt()}")
|
the-stack_0_14785 | import time
import torch
from torch.autograd import Variable
from torch.utils.data.sampler import SubsetRandomSampler
from archived.elasticache.Memcached import memcached_init
from archived.s3.get_object import get_object
from archived.s3 import put_object
from archived.old_model import LogisticRegression
from data_loader.libsvm_dataset import DenseDatasetWithLines
# lambda setting
grad_bucket = "async-grads"
model_bucket = "async-updates"
local_dir = "/tmp"
w_prefix = "w_"
b_prefix = "b_"
w_grad_prefix = "w_grad_"
b_grad_prefix = "b_grad_"
# algorithm setting
learning_rate = 0.1 #np.arange(0.09,0.15,0.01)
batch_size = 100000
num_epochs = 55
validation_ratio = .2
shuffle_dataset = True
random_seed = 42
def handler(event, context):
start_time = time.time()
bucket = event['bucket']
key = event['name']
num_features = event['num_features']
num_classes = event['num_classes']
elasti_location = event['elasticache']
endpoint = memcached_init(elasti_location)
print('bucket = {}'.format(bucket))
print('key = {}'.format(key))
key_splits = key.split("_")
worker_index = int(key_splits[0])
num_worker = event['num_files']
batch_size = 100000
batch_size = int(np.ceil(batch_size/num_worker))
torch.manual_seed(random_seed)
# read file(dataset) from s3
file = get_object(bucket, key).read().decode('utf-8').split("\n")
print("read data cost {} s".format(time.time() - start_time))
parse_start = time.time()
dataset = DenseDatasetWithLines(file, num_features)
preprocess_start = time.time()
print("libsvm operation cost {}s".format(parse_start - preprocess_start))
# Creating data indices for training and validation splits:
dataset_size = len(dataset)
print("dataset size = {}".format(dataset_size))
indices = list(range(dataset_size))
split = int(np.floor(validation_ratio * dataset_size))
if shuffle_dataset:
np.random.seed(random_seed)
np.random.shuffle(indices)
train_indices, val_indices = indices[split:], indices[:split]
# Creating PT data samplers and loaders:
train_sampler = SubsetRandomSampler(train_indices)
valid_sampler = SubsetRandomSampler(val_indices)
train_loader = torch.utils.data.DataLoader(dataset,
batch_size=batch_size,
sampler=train_sampler)
validation_loader = torch.utils.data.DataLoader(dataset,
batch_size=batch_size,
sampler=valid_sampler)
print("preprocess data cost {} s".format(time.time() - preprocess_start))
model = LogisticRegression(num_features, num_classes)
# Loss and Optimizer
# Softmax is internally computed.
# Set parameters to be updated.
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
train_loss = []
test_loss = []
test_acc = []
total_time = 0
# Training the Model
epoch_start = time.time()
for epoch in range(num_epochs):
tmp_train = 0
for batch_index, (items, labels) in enumerate(train_loader):
#batch_start = time.time()
print("------worker {} epoch {} batch {}------".format(worker_index, epoch, batch_index))
items = Variable(items.view(-1, num_features))
labels = Variable(labels)
# Forward + Backward + Optimize
optimizer.zero_grad()
outputs = model(items)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
w = model.linear.weight.data.numpy()
b = model.linear.bias.data.numpy()
file_postfix = "{}_{}".format(batch_index,epoch)
#asynchronization / shuffle starts from that every worker writes their gradients of this batch and epoch
#upload individual gradient
if batch_index == 0 and epoch == 0:
hset_object(endpoint, model_bucket, w_prefix, w.tobytes())
hset_object(endpoint, model_bucket, b_prefix, b.tobytes())
time.sleep(0.0001)
#randomly get one from others. (Asynchronized)
w_new = np.fromstring(hget_object(endpoint, model_bucket, w_prefix), dtype=w.dtype).reshape(w.shape)
b_new = np.fromstring(hget_object(endpoint, model_bucket, b_prefix), dtype=b.dtype).reshape(b.shape)
else:
w_new = np.fromstring(hget_object(endpoint, model_bucket, w_prefix), dtype=w.dtype).reshape(w.shape)
b_new = np.fromstring(hget_object(endpoint, model_bucket, b_prefix), dtype=b.dtype).reshape(b.shape)
hset_object(endpoint, model_bucket, w_prefix, w.tobytes())
hset_object(endpoint, model_bucket, b_prefix, b.tobytes())
model.linear.weight.data = torch.from_numpy(w_new)
model.linear.bias.data = torch.from_numpy(b_new)
#report train loss and test loss for every mini batch
if (batch_index + 1) % 1 == 0:
print('Epoch: [%d/%d], Step: [%d/%d], Loss: %.4f'
% (epoch + 1, num_epochs, batch_index + 1, len(train_indices) / batch_size, loss.data))
tmp_train += loss.item()
total_time += time.time()-epoch_start
train_loss.append(tmp_train)
tmp_test, tmp_acc = test(model, validation_loader, criterion)
test_loss.append(tmp_test)
test_acc.append(tmp_acc)
epoch_start = time.time()
print("total time = {}".format(total_time))
end_time = time.time()
print("elapsed time = {} s".format(end_time - start_time))
loss_record = [test_loss, test_acc, train_loss, total_time]
put_object("async-model-loss", "async-loss{}".format(worker_index), pickle.dumps(loss_record))
def test(model, testloader, criterion):
# Test the Model
correct = 0
total = 0
total_loss = 0
count = 0
with torch.no_grad():
for items,labels in testloader:
outputs = model(items)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum()
loss = criterion(outputs,labels)
total_loss += loss.data
count = count+1
return total_loss/count, float(correct)/float(total)*100
|
the-stack_0_14786 | import pandas as pd
import numpy as np
import scipy.stats
from pandas import DataFrame
from typing import List
from blacksheep._constants import *
SampleList = List[str]
def _convert_to_outliers(
df: DataFrame, samples: SampleList, num_iqrs: float, up_or_down: str
) -> DataFrame:
"""Calls outliers on a given values table.
Args:
df: Input DataFrame with samples as columns and genes or sites as rows. \
Index should be an identifier for each row.
samples: List of samples to be considered in the distribution when defining median, \
IQR and outliers.
num_iqrs: How many inter-quartile ranges (IQRs) above or below the median to consider \
something an outlier.
up_or_down: Whether to call outliers above the median (up) or below the median (down)
Returns:
A DataFrame with outlier calls for each value. 0 means not an outlier; 1 means there is \
an outlier. Missing values are propagated.
"""
if num_iqrs <= 0:
raise ValueError("num_iqrs must be greater than 0")
df = df.copy()
df[row_iqr_name] = scipy.stats.iqr(df[samples], axis=1, nan_policy="omit")
df[row_median_name] = np.nanquantile(df[samples], q=0.5, axis=1)
outlier_df = pd.DataFrame()
if up_or_down == "up":
df[row_upper_bound_name] = df[row_median_name] + (num_iqrs * df[row_iqr_name])
outlier_df[samples] = (
df[samples].gt(df[row_upper_bound_name], axis=0).astype(int)
)
outlier_df[df[samples].isnull()] = np.nan
return outlier_df
elif up_or_down == "down":
df[row_lower_bound_name] = df[row_median_name] - (num_iqrs * df[row_iqr_name])
outlier_df[samples] = (
df[samples].lt(df[row_lower_bound_name], axis=0).astype(int)
)
outlier_df[df[samples].isnull()] = np.nan
return outlier_df
raise ValueError("up_or_down must be either 'up' or 'down'")
def _convert_to_counts(
df: DataFrame, samples: SampleList, aggregate: bool, ind_sep: str
) -> DataFrame:
"""Counts outliers and non-outlier values for each sample and each row (if aggregate=False)
or each unique identifier (if aggregate=True).
Args:
df: Outlier DataFrame from convertToOutliers function.
samples: List of samples to consider. Should be same list as input to convertToOutliers.
aggregate: Whether or not to collapse multiple rows with identical identifiers before \
a separater. Collapsing values is done by counting outliers and non-outliers for each \
sample per unique identifier.
ind_sep: The separator used in the index to separate a more general ID and less specific \
ID. e.g. in RAG2-S365 the separater is "-".
Returns:
Outlier DataFrame that has a column with counts of non-outliers and outliers for \
each sample, with a row for each input site (if no aggregation) or each unique identifier \
(with aggregation). This table is the input for the comparison function.
"""
not_outlier_cols = [x + col_seps + col_not_outlier_suffix for x in samples]
outlier_cols = [x + col_seps + col_outlier_suffix for x in samples]
if aggregate:
df.index = [ind.split(ind_sep)[0] for ind in df.index]
df_inv = df == 0
output_df = pd.DataFrame()
output_df[not_outlier_cols] = df_inv.groupby(level=0)[samples].sum()
output_df[outlier_cols] = df.groupby(level=0)[samples].sum()
elif not aggregate:
output_df = pd.DataFrame(index=df.index)
output_df[outlier_cols] = df[samples]
output_df[not_outlier_cols] = 1 - df[samples]
return output_df
|
the-stack_0_14787 | from functools import partial
from inspect import signature
from itertools import product
from itertools import chain
from itertools import permutations
import numpy as np
import scipy.sparse as sp
import pytest
from sklearn.datasets import make_multilabel_classification
from sklearn.preprocessing import LabelBinarizer
from sklearn.utils.multiclass import type_of_target
from sklearn.utils.validation import _num_samples
from sklearn.utils.validation import check_random_state
from sklearn.utils import shuffle
from sklearn.utils._testing import assert_allclose
from sklearn.utils._testing import assert_almost_equal
from sklearn.utils._testing import assert_array_equal
from sklearn.utils._testing import assert_array_less
from sklearn.utils._testing import ignore_warnings
from sklearn.metrics import accuracy_score
from sklearn.metrics import average_precision_score
from sklearn.metrics import balanced_accuracy_score
from sklearn.metrics import brier_score_loss
from sklearn.metrics import cohen_kappa_score
from sklearn.metrics import confusion_matrix
from sklearn.metrics import coverage_error
from sklearn.metrics import d2_tweedie_score
from sklearn.metrics import det_curve
from sklearn.metrics import explained_variance_score
from sklearn.metrics import f1_score
from sklearn.metrics import fbeta_score
from sklearn.metrics import hamming_loss
from sklearn.metrics import hinge_loss
from sklearn.metrics import jaccard_score
from sklearn.metrics import label_ranking_average_precision_score
from sklearn.metrics import label_ranking_loss
from sklearn.metrics import log_loss
from sklearn.metrics import max_error
from sklearn.metrics import matthews_corrcoef
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_absolute_percentage_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_tweedie_deviance
from sklearn.metrics import mean_poisson_deviance
from sklearn.metrics import mean_gamma_deviance
from sklearn.metrics import median_absolute_error
from sklearn.metrics import multilabel_confusion_matrix
from sklearn.metrics import mean_pinball_loss
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import precision_score
from sklearn.metrics import r2_score
from sklearn.metrics import recall_score
from sklearn.metrics import roc_auc_score
from sklearn.metrics import roc_curve
from sklearn.metrics import zero_one_loss
from sklearn.metrics import ndcg_score
from sklearn.metrics import dcg_score
from sklearn.metrics import top_k_accuracy_score
from sklearn.metrics._base import _average_binary_score
# Note toward developers about metric testing
# -------------------------------------------
# It is often possible to write one general test for several metrics:
#
# - invariance properties, e.g. invariance to sample order
# - common behavior for an argument, e.g. the "normalize" with value True
# will return the mean of the metrics and with value False will return
# the sum of the metrics.
#
# In order to improve the overall metric testing, it is a good idea to write
# first a specific test for the given metric and then add a general test for
# all metrics that have the same behavior.
#
# Two types of datastructures are used in order to implement this system:
# dictionaries of metrics and lists of metrics with common properties.
#
# Dictionaries of metrics
# ------------------------
# The goal of having those dictionaries is to have an easy way to call a
# particular metric and associate a name to each function:
#
# - REGRESSION_METRICS: all regression metrics.
# - CLASSIFICATION_METRICS: all classification metrics
# which compare a ground truth and the estimated targets as returned by a
# classifier.
# - THRESHOLDED_METRICS: all classification metrics which
# compare a ground truth and a score, e.g. estimated probabilities or
# decision function (format might vary)
#
# Those dictionaries will be used to test systematically some invariance
# properties, e.g. invariance toward several input layout.
#
REGRESSION_METRICS = {
"max_error": max_error,
"mean_absolute_error": mean_absolute_error,
"mean_squared_error": mean_squared_error,
"mean_pinball_loss": mean_pinball_loss,
"median_absolute_error": median_absolute_error,
"mean_absolute_percentage_error": mean_absolute_percentage_error,
"explained_variance_score": explained_variance_score,
"r2_score": partial(r2_score, multioutput="variance_weighted"),
"mean_normal_deviance": partial(mean_tweedie_deviance, power=0),
"mean_poisson_deviance": mean_poisson_deviance,
"mean_gamma_deviance": mean_gamma_deviance,
"mean_compound_poisson_deviance": partial(mean_tweedie_deviance, power=1.4),
"d2_tweedie_score": partial(d2_tweedie_score, power=1.4),
}
CLASSIFICATION_METRICS = {
"accuracy_score": accuracy_score,
"balanced_accuracy_score": balanced_accuracy_score,
"adjusted_balanced_accuracy_score": partial(balanced_accuracy_score, adjusted=True),
"unnormalized_accuracy_score": partial(accuracy_score, normalize=False),
# `confusion_matrix` returns absolute values and hence behaves unnormalized
# . Naming it with an unnormalized_ prefix is necessary for this module to
# skip sample_weight scaling checks which will fail for unnormalized
# metrics.
"unnormalized_confusion_matrix": confusion_matrix,
"normalized_confusion_matrix": lambda *args, **kwargs: (
confusion_matrix(*args, **kwargs).astype("float")
/ confusion_matrix(*args, **kwargs).sum(axis=1)[:, np.newaxis]
),
"unnormalized_multilabel_confusion_matrix": multilabel_confusion_matrix,
"unnormalized_multilabel_confusion_matrix_sample": partial(
multilabel_confusion_matrix, samplewise=True
),
"hamming_loss": hamming_loss,
"zero_one_loss": zero_one_loss,
"unnormalized_zero_one_loss": partial(zero_one_loss, normalize=False),
# These are needed to test averaging
"jaccard_score": jaccard_score,
"precision_score": precision_score,
"recall_score": recall_score,
"f1_score": f1_score,
"f2_score": partial(fbeta_score, beta=2),
"f0.5_score": partial(fbeta_score, beta=0.5),
"matthews_corrcoef_score": matthews_corrcoef,
"weighted_f0.5_score": partial(fbeta_score, average="weighted", beta=0.5),
"weighted_f1_score": partial(f1_score, average="weighted"),
"weighted_f2_score": partial(fbeta_score, average="weighted", beta=2),
"weighted_precision_score": partial(precision_score, average="weighted"),
"weighted_recall_score": partial(recall_score, average="weighted"),
"weighted_jaccard_score": partial(jaccard_score, average="weighted"),
"micro_f0.5_score": partial(fbeta_score, average="micro", beta=0.5),
"micro_f1_score": partial(f1_score, average="micro"),
"micro_f2_score": partial(fbeta_score, average="micro", beta=2),
"micro_precision_score": partial(precision_score, average="micro"),
"micro_recall_score": partial(recall_score, average="micro"),
"micro_jaccard_score": partial(jaccard_score, average="micro"),
"macro_f0.5_score": partial(fbeta_score, average="macro", beta=0.5),
"macro_f1_score": partial(f1_score, average="macro"),
"macro_f2_score": partial(fbeta_score, average="macro", beta=2),
"macro_precision_score": partial(precision_score, average="macro"),
"macro_recall_score": partial(recall_score, average="macro"),
"macro_jaccard_score": partial(jaccard_score, average="macro"),
"samples_f0.5_score": partial(fbeta_score, average="samples", beta=0.5),
"samples_f1_score": partial(f1_score, average="samples"),
"samples_f2_score": partial(fbeta_score, average="samples", beta=2),
"samples_precision_score": partial(precision_score, average="samples"),
"samples_recall_score": partial(recall_score, average="samples"),
"samples_jaccard_score": partial(jaccard_score, average="samples"),
"cohen_kappa_score": cohen_kappa_score,
}
def precision_recall_curve_padded_thresholds(*args, **kwargs):
"""
The dimensions of precision-recall pairs and the threshold array as
returned by the precision_recall_curve do not match. See
func:`sklearn.metrics.precision_recall_curve`
This prevents implicit conversion of return value triple to an higher
dimensional np.array of dtype('float64') (it will be of dtype('object)
instead). This again is needed for assert_array_equal to work correctly.
As a workaround we pad the threshold array with NaN values to match
the dimension of precision and recall arrays respectively.
"""
precision, recall, thresholds = precision_recall_curve(*args, **kwargs)
pad_threshholds = len(precision) - len(thresholds)
return np.array(
[
precision,
recall,
np.pad(
thresholds.astype(np.float64),
pad_width=(0, pad_threshholds),
mode="constant",
constant_values=[np.nan],
),
]
)
CURVE_METRICS = {
"roc_curve": roc_curve,
"precision_recall_curve": precision_recall_curve_padded_thresholds,
"det_curve": det_curve,
}
THRESHOLDED_METRICS = {
"coverage_error": coverage_error,
"label_ranking_loss": label_ranking_loss,
"log_loss": log_loss,
"unnormalized_log_loss": partial(log_loss, normalize=False),
"hinge_loss": hinge_loss,
"brier_score_loss": brier_score_loss,
"roc_auc_score": roc_auc_score, # default: average="macro"
"weighted_roc_auc": partial(roc_auc_score, average="weighted"),
"samples_roc_auc": partial(roc_auc_score, average="samples"),
"micro_roc_auc": partial(roc_auc_score, average="micro"),
"ovr_roc_auc": partial(roc_auc_score, average="macro", multi_class="ovr"),
"weighted_ovr_roc_auc": partial(
roc_auc_score, average="weighted", multi_class="ovr"
),
"ovo_roc_auc": partial(roc_auc_score, average="macro", multi_class="ovo"),
"weighted_ovo_roc_auc": partial(
roc_auc_score, average="weighted", multi_class="ovo"
),
"partial_roc_auc": partial(roc_auc_score, max_fpr=0.5),
"average_precision_score": average_precision_score, # default: average="macro"
"weighted_average_precision_score": partial(
average_precision_score, average="weighted"
),
"samples_average_precision_score": partial(
average_precision_score, average="samples"
),
"micro_average_precision_score": partial(average_precision_score, average="micro"),
"label_ranking_average_precision_score": label_ranking_average_precision_score,
"ndcg_score": ndcg_score,
"dcg_score": dcg_score,
"top_k_accuracy_score": top_k_accuracy_score,
}
ALL_METRICS = dict()
ALL_METRICS.update(THRESHOLDED_METRICS)
ALL_METRICS.update(CLASSIFICATION_METRICS)
ALL_METRICS.update(REGRESSION_METRICS)
ALL_METRICS.update(CURVE_METRICS)
# Lists of metrics with common properties
# ---------------------------------------
# Lists of metrics with common properties are used to test systematically some
# functionalities and invariance, e.g. SYMMETRIC_METRICS lists all metrics that
# are symmetric with respect to their input argument y_true and y_pred.
#
# When you add a new metric or functionality, check if a general test
# is already written.
# Those metrics don't support binary inputs
METRIC_UNDEFINED_BINARY = {
"samples_f0.5_score",
"samples_f1_score",
"samples_f2_score",
"samples_precision_score",
"samples_recall_score",
"samples_jaccard_score",
"coverage_error",
"unnormalized_multilabel_confusion_matrix_sample",
"label_ranking_loss",
"label_ranking_average_precision_score",
"dcg_score",
"ndcg_score",
}
# Those metrics don't support multiclass inputs
METRIC_UNDEFINED_MULTICLASS = {
"brier_score_loss",
"micro_roc_auc",
"samples_roc_auc",
"partial_roc_auc",
"roc_auc_score",
"weighted_roc_auc",
"average_precision_score",
"weighted_average_precision_score",
"micro_average_precision_score",
"samples_average_precision_score",
"jaccard_score",
# with default average='binary', multiclass is prohibited
"precision_score",
"recall_score",
"f1_score",
"f2_score",
"f0.5_score",
# curves
"roc_curve",
"precision_recall_curve",
"det_curve",
}
# Metric undefined with "binary" or "multiclass" input
METRIC_UNDEFINED_BINARY_MULTICLASS = METRIC_UNDEFINED_BINARY.union(
METRIC_UNDEFINED_MULTICLASS
)
# Metrics with an "average" argument
METRICS_WITH_AVERAGING = {
"precision_score",
"recall_score",
"f1_score",
"f2_score",
"f0.5_score",
"jaccard_score",
}
# Threshold-based metrics with an "average" argument
THRESHOLDED_METRICS_WITH_AVERAGING = {
"roc_auc_score",
"average_precision_score",
"partial_roc_auc",
}
# Metrics with a "pos_label" argument
METRICS_WITH_POS_LABEL = {
"roc_curve",
"precision_recall_curve",
"det_curve",
"brier_score_loss",
"precision_score",
"recall_score",
"f1_score",
"f2_score",
"f0.5_score",
"jaccard_score",
"average_precision_score",
"weighted_average_precision_score",
"micro_average_precision_score",
"samples_average_precision_score",
}
# Metrics with a "labels" argument
# TODO: Handle multi_class metrics that has a labels argument as well as a
# decision function argument. e.g hinge_loss
METRICS_WITH_LABELS = {
"unnormalized_confusion_matrix",
"normalized_confusion_matrix",
"roc_curve",
"precision_recall_curve",
"det_curve",
"precision_score",
"recall_score",
"f1_score",
"f2_score",
"f0.5_score",
"jaccard_score",
"weighted_f0.5_score",
"weighted_f1_score",
"weighted_f2_score",
"weighted_precision_score",
"weighted_recall_score",
"weighted_jaccard_score",
"micro_f0.5_score",
"micro_f1_score",
"micro_f2_score",
"micro_precision_score",
"micro_recall_score",
"micro_jaccard_score",
"macro_f0.5_score",
"macro_f1_score",
"macro_f2_score",
"macro_precision_score",
"macro_recall_score",
"macro_jaccard_score",
"unnormalized_multilabel_confusion_matrix",
"unnormalized_multilabel_confusion_matrix_sample",
"cohen_kappa_score",
}
# Metrics with a "normalize" option
METRICS_WITH_NORMALIZE_OPTION = {
"accuracy_score",
"top_k_accuracy_score",
"zero_one_loss",
}
# Threshold-based metrics with "multilabel-indicator" format support
THRESHOLDED_MULTILABEL_METRICS = {
"log_loss",
"unnormalized_log_loss",
"roc_auc_score",
"weighted_roc_auc",
"samples_roc_auc",
"micro_roc_auc",
"partial_roc_auc",
"average_precision_score",
"weighted_average_precision_score",
"samples_average_precision_score",
"micro_average_precision_score",
"coverage_error",
"label_ranking_loss",
"ndcg_score",
"dcg_score",
"label_ranking_average_precision_score",
}
# Classification metrics with "multilabel-indicator" format
MULTILABELS_METRICS = {
"accuracy_score",
"unnormalized_accuracy_score",
"hamming_loss",
"zero_one_loss",
"unnormalized_zero_one_loss",
"weighted_f0.5_score",
"weighted_f1_score",
"weighted_f2_score",
"weighted_precision_score",
"weighted_recall_score",
"weighted_jaccard_score",
"macro_f0.5_score",
"macro_f1_score",
"macro_f2_score",
"macro_precision_score",
"macro_recall_score",
"macro_jaccard_score",
"micro_f0.5_score",
"micro_f1_score",
"micro_f2_score",
"micro_precision_score",
"micro_recall_score",
"micro_jaccard_score",
"unnormalized_multilabel_confusion_matrix",
"samples_f0.5_score",
"samples_f1_score",
"samples_f2_score",
"samples_precision_score",
"samples_recall_score",
"samples_jaccard_score",
}
# Regression metrics with "multioutput-continuous" format support
MULTIOUTPUT_METRICS = {
"mean_absolute_error",
"median_absolute_error",
"mean_squared_error",
"r2_score",
"explained_variance_score",
"mean_absolute_percentage_error",
"mean_pinball_loss",
}
# Symmetric with respect to their input arguments y_true and y_pred
# metric(y_true, y_pred) == metric(y_pred, y_true).
SYMMETRIC_METRICS = {
"accuracy_score",
"unnormalized_accuracy_score",
"hamming_loss",
"zero_one_loss",
"unnormalized_zero_one_loss",
"micro_jaccard_score",
"macro_jaccard_score",
"jaccard_score",
"samples_jaccard_score",
"f1_score",
"micro_f1_score",
"macro_f1_score",
"weighted_recall_score",
# P = R = F = accuracy in multiclass case
"micro_f0.5_score",
"micro_f1_score",
"micro_f2_score",
"micro_precision_score",
"micro_recall_score",
"matthews_corrcoef_score",
"mean_absolute_error",
"mean_squared_error",
"median_absolute_error",
"max_error",
# Pinball loss is only symmetric for alpha=0.5 which is the default.
"mean_pinball_loss",
"cohen_kappa_score",
"mean_normal_deviance",
}
# Asymmetric with respect to their input arguments y_true and y_pred
# metric(y_true, y_pred) != metric(y_pred, y_true).
NOT_SYMMETRIC_METRICS = {
"balanced_accuracy_score",
"adjusted_balanced_accuracy_score",
"explained_variance_score",
"r2_score",
"unnormalized_confusion_matrix",
"normalized_confusion_matrix",
"roc_curve",
"precision_recall_curve",
"det_curve",
"precision_score",
"recall_score",
"f2_score",
"f0.5_score",
"weighted_f0.5_score",
"weighted_f1_score",
"weighted_f2_score",
"weighted_precision_score",
"weighted_jaccard_score",
"unnormalized_multilabel_confusion_matrix",
"macro_f0.5_score",
"macro_f2_score",
"macro_precision_score",
"macro_recall_score",
"log_loss",
"hinge_loss",
"mean_gamma_deviance",
"mean_poisson_deviance",
"mean_compound_poisson_deviance",
"d2_tweedie_score",
"mean_absolute_percentage_error",
}
# No Sample weight support
METRICS_WITHOUT_SAMPLE_WEIGHT = {
"median_absolute_error",
"max_error",
"ovo_roc_auc",
"weighted_ovo_roc_auc",
}
METRICS_REQUIRE_POSITIVE_Y = {
"mean_poisson_deviance",
"mean_gamma_deviance",
"mean_compound_poisson_deviance",
"d2_tweedie_score",
}
def _require_positive_targets(y1, y2):
"""Make targets strictly positive"""
offset = abs(min(y1.min(), y2.min())) + 1
y1 += offset
y2 += offset
return y1, y2
def test_symmetry_consistency():
# We shouldn't forget any metrics
assert (
SYMMETRIC_METRICS
| NOT_SYMMETRIC_METRICS
| set(THRESHOLDED_METRICS)
| METRIC_UNDEFINED_BINARY_MULTICLASS
) == set(ALL_METRICS)
assert (SYMMETRIC_METRICS & NOT_SYMMETRIC_METRICS) == set()
@pytest.mark.parametrize("name", sorted(SYMMETRIC_METRICS))
def test_symmetric_metric(name):
# Test the symmetry of score and loss functions
random_state = check_random_state(0)
y_true = random_state.randint(0, 2, size=(20,))
y_pred = random_state.randint(0, 2, size=(20,))
if name in METRICS_REQUIRE_POSITIVE_Y:
y_true, y_pred = _require_positive_targets(y_true, y_pred)
y_true_bin = random_state.randint(0, 2, size=(20, 25))
y_pred_bin = random_state.randint(0, 2, size=(20, 25))
metric = ALL_METRICS[name]
if name in METRIC_UNDEFINED_BINARY:
if name in MULTILABELS_METRICS:
assert_allclose(
metric(y_true_bin, y_pred_bin),
metric(y_pred_bin, y_true_bin),
err_msg="%s is not symmetric" % name,
)
else:
assert False, "This case is currently unhandled"
else:
assert_allclose(
metric(y_true, y_pred),
metric(y_pred, y_true),
err_msg="%s is not symmetric" % name,
)
@pytest.mark.parametrize("name", sorted(NOT_SYMMETRIC_METRICS))
def test_not_symmetric_metric(name):
# Test the symmetry of score and loss functions
random_state = check_random_state(0)
y_true = random_state.randint(0, 2, size=(20,))
y_pred = random_state.randint(0, 2, size=(20,))
if name in METRICS_REQUIRE_POSITIVE_Y:
y_true, y_pred = _require_positive_targets(y_true, y_pred)
metric = ALL_METRICS[name]
# use context manager to supply custom error message
with pytest.raises(AssertionError):
assert_array_equal(metric(y_true, y_pred), metric(y_pred, y_true))
raise ValueError("%s seems to be symmetric" % name)
@pytest.mark.parametrize(
"name", sorted(set(ALL_METRICS) - METRIC_UNDEFINED_BINARY_MULTICLASS)
)
def test_sample_order_invariance(name):
random_state = check_random_state(0)
y_true = random_state.randint(0, 2, size=(20,))
y_pred = random_state.randint(0, 2, size=(20,))
if name in METRICS_REQUIRE_POSITIVE_Y:
y_true, y_pred = _require_positive_targets(y_true, y_pred)
y_true_shuffle, y_pred_shuffle = shuffle(y_true, y_pred, random_state=0)
with ignore_warnings():
metric = ALL_METRICS[name]
assert_allclose(
metric(y_true, y_pred),
metric(y_true_shuffle, y_pred_shuffle),
err_msg="%s is not sample order invariant" % name,
)
@ignore_warnings
def test_sample_order_invariance_multilabel_and_multioutput():
random_state = check_random_state(0)
# Generate some data
y_true = random_state.randint(0, 2, size=(20, 25))
y_pred = random_state.randint(0, 2, size=(20, 25))
y_score = random_state.normal(size=y_true.shape)
y_true_shuffle, y_pred_shuffle, y_score_shuffle = shuffle(
y_true, y_pred, y_score, random_state=0
)
for name in MULTILABELS_METRICS:
metric = ALL_METRICS[name]
assert_allclose(
metric(y_true, y_pred),
metric(y_true_shuffle, y_pred_shuffle),
err_msg="%s is not sample order invariant" % name,
)
for name in THRESHOLDED_MULTILABEL_METRICS:
metric = ALL_METRICS[name]
assert_allclose(
metric(y_true, y_score),
metric(y_true_shuffle, y_score_shuffle),
err_msg="%s is not sample order invariant" % name,
)
for name in MULTIOUTPUT_METRICS:
metric = ALL_METRICS[name]
assert_allclose(
metric(y_true, y_score),
metric(y_true_shuffle, y_score_shuffle),
err_msg="%s is not sample order invariant" % name,
)
assert_allclose(
metric(y_true, y_pred),
metric(y_true_shuffle, y_pred_shuffle),
err_msg="%s is not sample order invariant" % name,
)
@pytest.mark.parametrize(
"name", sorted(set(ALL_METRICS) - METRIC_UNDEFINED_BINARY_MULTICLASS)
)
def test_format_invariance_with_1d_vectors(name):
random_state = check_random_state(0)
y1 = random_state.randint(0, 2, size=(20,))
y2 = random_state.randint(0, 2, size=(20,))
if name in METRICS_REQUIRE_POSITIVE_Y:
y1, y2 = _require_positive_targets(y1, y2)
y1_list = list(y1)
y2_list = list(y2)
y1_1d, y2_1d = np.array(y1), np.array(y2)
assert_array_equal(y1_1d.ndim, 1)
assert_array_equal(y2_1d.ndim, 1)
y1_column = np.reshape(y1_1d, (-1, 1))
y2_column = np.reshape(y2_1d, (-1, 1))
y1_row = np.reshape(y1_1d, (1, -1))
y2_row = np.reshape(y2_1d, (1, -1))
with ignore_warnings():
metric = ALL_METRICS[name]
measure = metric(y1, y2)
assert_allclose(
metric(y1_list, y2_list),
measure,
err_msg="%s is not representation invariant with list" % name,
)
assert_allclose(
metric(y1_1d, y2_1d),
measure,
err_msg="%s is not representation invariant with np-array-1d" % name,
)
assert_allclose(
metric(y1_column, y2_column),
measure,
err_msg="%s is not representation invariant with np-array-column" % name,
)
# Mix format support
assert_allclose(
metric(y1_1d, y2_list),
measure,
err_msg="%s is not representation invariant with mix np-array-1d and list"
% name,
)
assert_allclose(
metric(y1_list, y2_1d),
measure,
err_msg="%s is not representation invariant with mix np-array-1d and list"
% name,
)
assert_allclose(
metric(y1_1d, y2_column),
measure,
err_msg=(
"%s is not representation invariant with mix "
"np-array-1d and np-array-column"
)
% name,
)
assert_allclose(
metric(y1_column, y2_1d),
measure,
err_msg=(
"%s is not representation invariant with mix "
"np-array-1d and np-array-column"
)
% name,
)
assert_allclose(
metric(y1_list, y2_column),
measure,
err_msg=(
"%s is not representation invariant with mix list and np-array-column"
)
% name,
)
assert_allclose(
metric(y1_column, y2_list),
measure,
err_msg=(
"%s is not representation invariant with mix list and np-array-column"
)
% name,
)
# These mix representations aren't allowed
with pytest.raises(ValueError):
metric(y1_1d, y2_row)
with pytest.raises(ValueError):
metric(y1_row, y2_1d)
with pytest.raises(ValueError):
metric(y1_list, y2_row)
with pytest.raises(ValueError):
metric(y1_row, y2_list)
with pytest.raises(ValueError):
metric(y1_column, y2_row)
with pytest.raises(ValueError):
metric(y1_row, y2_column)
# NB: We do not test for y1_row, y2_row as these may be
# interpreted as multilabel or multioutput data.
if name not in (
MULTIOUTPUT_METRICS | THRESHOLDED_MULTILABEL_METRICS | MULTILABELS_METRICS
):
with pytest.raises(ValueError):
metric(y1_row, y2_row)
@pytest.mark.parametrize(
"name", sorted(set(CLASSIFICATION_METRICS) - METRIC_UNDEFINED_BINARY_MULTICLASS)
)
def test_classification_invariance_string_vs_numbers_labels(name):
# Ensure that classification metrics with string labels are invariant
random_state = check_random_state(0)
y1 = random_state.randint(0, 2, size=(20,))
y2 = random_state.randint(0, 2, size=(20,))
y1_str = np.array(["eggs", "spam"])[y1]
y2_str = np.array(["eggs", "spam"])[y2]
pos_label_str = "spam"
labels_str = ["eggs", "spam"]
with ignore_warnings():
metric = CLASSIFICATION_METRICS[name]
measure_with_number = metric(y1, y2)
# Ugly, but handle case with a pos_label and label
metric_str = metric
if name in METRICS_WITH_POS_LABEL:
metric_str = partial(metric_str, pos_label=pos_label_str)
measure_with_str = metric_str(y1_str, y2_str)
assert_array_equal(
measure_with_number,
measure_with_str,
err_msg="{0} failed string vs number invariance test".format(name),
)
measure_with_strobj = metric_str(y1_str.astype("O"), y2_str.astype("O"))
assert_array_equal(
measure_with_number,
measure_with_strobj,
err_msg="{0} failed string object vs number invariance test".format(name),
)
if name in METRICS_WITH_LABELS:
metric_str = partial(metric_str, labels=labels_str)
measure_with_str = metric_str(y1_str, y2_str)
assert_array_equal(
measure_with_number,
measure_with_str,
err_msg="{0} failed string vs number invariance test".format(name),
)
measure_with_strobj = metric_str(y1_str.astype("O"), y2_str.astype("O"))
assert_array_equal(
measure_with_number,
measure_with_strobj,
err_msg="{0} failed string vs number invariance test".format(name),
)
@pytest.mark.parametrize("name", THRESHOLDED_METRICS)
def test_thresholded_invariance_string_vs_numbers_labels(name):
# Ensure that thresholded metrics with string labels are invariant
random_state = check_random_state(0)
y1 = random_state.randint(0, 2, size=(20,))
y2 = random_state.randint(0, 2, size=(20,))
y1_str = np.array(["eggs", "spam"])[y1]
pos_label_str = "spam"
with ignore_warnings():
metric = THRESHOLDED_METRICS[name]
if name not in METRIC_UNDEFINED_BINARY:
# Ugly, but handle case with a pos_label and label
metric_str = metric
if name in METRICS_WITH_POS_LABEL:
metric_str = partial(metric_str, pos_label=pos_label_str)
measure_with_number = metric(y1, y2)
measure_with_str = metric_str(y1_str, y2)
assert_array_equal(
measure_with_number,
measure_with_str,
err_msg="{0} failed string vs number invariance test".format(name),
)
measure_with_strobj = metric_str(y1_str.astype("O"), y2)
assert_array_equal(
measure_with_number,
measure_with_strobj,
err_msg="{0} failed string object vs number invariance test".format(
name
),
)
else:
# TODO those metrics doesn't support string label yet
with pytest.raises(ValueError):
metric(y1_str, y2)
with pytest.raises(ValueError):
metric(y1_str.astype("O"), y2)
invalids_nan_inf = [
([0, 1], [np.inf, np.inf]),
([0, 1], [np.nan, np.nan]),
([0, 1], [np.nan, np.inf]),
([0, 1], [np.inf, 1]),
([0, 1], [np.nan, 1]),
]
@pytest.mark.parametrize(
"metric", chain(THRESHOLDED_METRICS.values(), REGRESSION_METRICS.values())
)
@pytest.mark.parametrize("y_true, y_score", invalids_nan_inf)
def test_regression_thresholded_inf_nan_input(metric, y_true, y_score):
with pytest.raises(ValueError, match="contains NaN, infinity"):
metric(y_true, y_score)
@pytest.mark.parametrize("metric", CLASSIFICATION_METRICS.values())
@pytest.mark.parametrize(
"y_true, y_score",
invalids_nan_inf +
# Add an additional case for classification only
# non-regression test for:
# https://github.com/scikit-learn/scikit-learn/issues/6809
[([np.nan, 1, 2], [1, 2, 3])], # type: ignore
)
def test_classification_inf_nan_input(metric, y_true, y_score):
"""check that classification metrics raise a message mentioning the
occurrence of non-finite values in the target vectors."""
err_msg = "Input contains NaN, infinity or a value too large"
with pytest.raises(ValueError, match=err_msg):
metric(y_true, y_score)
@pytest.mark.parametrize("metric", CLASSIFICATION_METRICS.values())
def test_classification_binary_continuous_input(metric):
"""check that classification metrics raise a message of mixed type data
with continuous/binary target vectors."""
y_true, y_score = ["a", "b", "a"], [0.1, 0.2, 0.3]
err_msg = (
"Classification metrics can't handle a mix of binary and continuous targets"
)
with pytest.raises(ValueError, match=err_msg):
metric(y_true, y_score)
@ignore_warnings
def check_single_sample(name):
# Non-regression test: scores should work with a single sample.
# This is important for leave-one-out cross validation.
# Score functions tested are those that formerly called np.squeeze,
# which turns an array of size 1 into a 0-d array (!).
metric = ALL_METRICS[name]
# assert that no exception is thrown
if name in METRICS_REQUIRE_POSITIVE_Y:
values = [1, 2]
else:
values = [0, 1]
for i, j in product(values, repeat=2):
metric([i], [j])
@ignore_warnings
def check_single_sample_multioutput(name):
metric = ALL_METRICS[name]
for i, j, k, l in product([0, 1], repeat=4):
metric(np.array([[i, j]]), np.array([[k, l]]))
@pytest.mark.parametrize(
"name",
sorted(
set(ALL_METRICS)
# Those metrics are not always defined with one sample
# or in multiclass classification
- METRIC_UNDEFINED_BINARY_MULTICLASS
- set(THRESHOLDED_METRICS)
),
)
def test_single_sample(name):
check_single_sample(name)
@pytest.mark.parametrize("name", sorted(MULTIOUTPUT_METRICS | MULTILABELS_METRICS))
def test_single_sample_multioutput(name):
check_single_sample_multioutput(name)
@pytest.mark.parametrize("name", sorted(MULTIOUTPUT_METRICS))
def test_multioutput_number_of_output_differ(name):
y_true = np.array([[1, 0, 0, 1], [0, 1, 1, 1], [1, 1, 0, 1]])
y_pred = np.array([[0, 0], [1, 0], [0, 0]])
metric = ALL_METRICS[name]
with pytest.raises(ValueError):
metric(y_true, y_pred)
@pytest.mark.parametrize("name", sorted(MULTIOUTPUT_METRICS))
def test_multioutput_regression_invariance_to_dimension_shuffling(name):
# test invariance to dimension shuffling
random_state = check_random_state(0)
y_true = random_state.uniform(0, 2, size=(20, 5))
y_pred = random_state.uniform(0, 2, size=(20, 5))
metric = ALL_METRICS[name]
error = metric(y_true, y_pred)
for _ in range(3):
perm = random_state.permutation(y_true.shape[1])
assert_allclose(
metric(y_true[:, perm], y_pred[:, perm]),
error,
err_msg="%s is not dimension shuffling invariant" % (name),
)
@ignore_warnings
def test_multilabel_representation_invariance():
# Generate some data
n_classes = 4
n_samples = 50
_, y1 = make_multilabel_classification(
n_features=1,
n_classes=n_classes,
random_state=0,
n_samples=n_samples,
allow_unlabeled=True,
)
_, y2 = make_multilabel_classification(
n_features=1,
n_classes=n_classes,
random_state=1,
n_samples=n_samples,
allow_unlabeled=True,
)
# To make sure at least one empty label is present
y1 = np.vstack([y1, [[0] * n_classes]])
y2 = np.vstack([y2, [[0] * n_classes]])
y1_sparse_indicator = sp.coo_matrix(y1)
y2_sparse_indicator = sp.coo_matrix(y2)
y1_list_array_indicator = list(y1)
y2_list_array_indicator = list(y2)
y1_list_list_indicator = [list(a) for a in y1_list_array_indicator]
y2_list_list_indicator = [list(a) for a in y2_list_array_indicator]
for name in MULTILABELS_METRICS:
metric = ALL_METRICS[name]
# XXX cruel hack to work with partial functions
if isinstance(metric, partial):
metric.__module__ = "tmp"
metric.__name__ = name
measure = metric(y1, y2)
# Check representation invariance
assert_allclose(
metric(y1_sparse_indicator, y2_sparse_indicator),
measure,
err_msg=(
"%s failed representation invariance between "
"dense and sparse indicator formats."
)
% name,
)
assert_almost_equal(
metric(y1_list_list_indicator, y2_list_list_indicator),
measure,
err_msg=(
"%s failed representation invariance "
"between dense array and list of list "
"indicator formats."
)
% name,
)
assert_almost_equal(
metric(y1_list_array_indicator, y2_list_array_indicator),
measure,
err_msg=(
"%s failed representation invariance "
"between dense and list of array "
"indicator formats."
)
% name,
)
@pytest.mark.parametrize("name", sorted(MULTILABELS_METRICS))
def test_raise_value_error_multilabel_sequences(name):
# make sure the multilabel-sequence format raises ValueError
multilabel_sequences = [
[[1], [2], [0, 1]],
[(), (2), (0, 1)],
[[]],
[()],
np.array([[], [1, 2]], dtype="object"),
]
metric = ALL_METRICS[name]
for seq in multilabel_sequences:
with pytest.raises(ValueError):
metric(seq, seq)
@pytest.mark.parametrize("name", sorted(METRICS_WITH_NORMALIZE_OPTION))
def test_normalize_option_binary_classification(name):
# Test in the binary case
n_classes = 2
n_samples = 20
random_state = check_random_state(0)
y_true = random_state.randint(0, n_classes, size=(n_samples,))
y_pred = random_state.randint(0, n_classes, size=(n_samples,))
y_score = random_state.normal(size=y_true.shape)
metrics = ALL_METRICS[name]
pred = y_score if name in THRESHOLDED_METRICS else y_pred
measure_normalized = metrics(y_true, pred, normalize=True)
measure_not_normalized = metrics(y_true, pred, normalize=False)
assert_array_less(
-1.0 * measure_normalized,
0,
err_msg="We failed to test correctly the normalize option",
)
assert_allclose(
measure_normalized,
measure_not_normalized / n_samples,
err_msg=f"Failed with {name}",
)
@pytest.mark.parametrize("name", sorted(METRICS_WITH_NORMALIZE_OPTION))
def test_normalize_option_multiclass_classification(name):
# Test in the multiclass case
n_classes = 4
n_samples = 20
random_state = check_random_state(0)
y_true = random_state.randint(0, n_classes, size=(n_samples,))
y_pred = random_state.randint(0, n_classes, size=(n_samples,))
y_score = random_state.uniform(size=(n_samples, n_classes))
metrics = ALL_METRICS[name]
pred = y_score if name in THRESHOLDED_METRICS else y_pred
measure_normalized = metrics(y_true, pred, normalize=True)
measure_not_normalized = metrics(y_true, pred, normalize=False)
assert_array_less(
-1.0 * measure_normalized,
0,
err_msg="We failed to test correctly the normalize option",
)
assert_allclose(
measure_normalized,
measure_not_normalized / n_samples,
err_msg=f"Failed with {name}",
)
@pytest.mark.parametrize(
"name", sorted(METRICS_WITH_NORMALIZE_OPTION.intersection(MULTILABELS_METRICS))
)
def test_normalize_option_multilabel_classification(name):
# Test in the multilabel case
n_classes = 4
n_samples = 100
random_state = check_random_state(0)
# for both random_state 0 and 1, y_true and y_pred has at least one
# unlabelled entry
_, y_true = make_multilabel_classification(
n_features=1,
n_classes=n_classes,
random_state=0,
allow_unlabeled=True,
n_samples=n_samples,
)
_, y_pred = make_multilabel_classification(
n_features=1,
n_classes=n_classes,
random_state=1,
allow_unlabeled=True,
n_samples=n_samples,
)
y_score = random_state.uniform(size=y_true.shape)
# To make sure at least one empty label is present
y_true += [0] * n_classes
y_pred += [0] * n_classes
metrics = ALL_METRICS[name]
pred = y_score if name in THRESHOLDED_METRICS else y_pred
measure_normalized = metrics(y_true, pred, normalize=True)
measure_not_normalized = metrics(y_true, pred, normalize=False)
assert_array_less(
-1.0 * measure_normalized,
0,
err_msg="We failed to test correctly the normalize option",
)
assert_allclose(
measure_normalized,
measure_not_normalized / n_samples,
err_msg=f"Failed with {name}",
)
@ignore_warnings
def _check_averaging(
metric, y_true, y_pred, y_true_binarize, y_pred_binarize, is_multilabel
):
n_samples, n_classes = y_true_binarize.shape
# No averaging
label_measure = metric(y_true, y_pred, average=None)
assert_allclose(
label_measure,
[
metric(y_true_binarize[:, i], y_pred_binarize[:, i])
for i in range(n_classes)
],
)
# Micro measure
micro_measure = metric(y_true, y_pred, average="micro")
assert_allclose(
micro_measure, metric(y_true_binarize.ravel(), y_pred_binarize.ravel())
)
# Macro measure
macro_measure = metric(y_true, y_pred, average="macro")
assert_allclose(macro_measure, np.mean(label_measure))
# Weighted measure
weights = np.sum(y_true_binarize, axis=0, dtype=int)
if np.sum(weights) != 0:
weighted_measure = metric(y_true, y_pred, average="weighted")
assert_allclose(weighted_measure, np.average(label_measure, weights=weights))
else:
weighted_measure = metric(y_true, y_pred, average="weighted")
assert_allclose(weighted_measure, 0)
# Sample measure
if is_multilabel:
sample_measure = metric(y_true, y_pred, average="samples")
assert_allclose(
sample_measure,
np.mean(
[
metric(y_true_binarize[i], y_pred_binarize[i])
for i in range(n_samples)
]
),
)
with pytest.raises(ValueError):
metric(y_true, y_pred, average="unknown")
with pytest.raises(ValueError):
metric(y_true, y_pred, average="garbage")
def check_averaging(name, y_true, y_true_binarize, y_pred, y_pred_binarize, y_score):
is_multilabel = type_of_target(y_true).startswith("multilabel")
metric = ALL_METRICS[name]
if name in METRICS_WITH_AVERAGING:
_check_averaging(
metric, y_true, y_pred, y_true_binarize, y_pred_binarize, is_multilabel
)
elif name in THRESHOLDED_METRICS_WITH_AVERAGING:
_check_averaging(
metric, y_true, y_score, y_true_binarize, y_score, is_multilabel
)
else:
raise ValueError("Metric is not recorded as having an average option")
@pytest.mark.parametrize("name", sorted(METRICS_WITH_AVERAGING))
def test_averaging_multiclass(name):
n_samples, n_classes = 50, 3
random_state = check_random_state(0)
y_true = random_state.randint(0, n_classes, size=(n_samples,))
y_pred = random_state.randint(0, n_classes, size=(n_samples,))
y_score = random_state.uniform(size=(n_samples, n_classes))
lb = LabelBinarizer().fit(y_true)
y_true_binarize = lb.transform(y_true)
y_pred_binarize = lb.transform(y_pred)
check_averaging(name, y_true, y_true_binarize, y_pred, y_pred_binarize, y_score)
@pytest.mark.parametrize(
"name", sorted(METRICS_WITH_AVERAGING | THRESHOLDED_METRICS_WITH_AVERAGING)
)
def test_averaging_multilabel(name):
n_samples, n_classes = 40, 5
_, y = make_multilabel_classification(
n_features=1,
n_classes=n_classes,
random_state=5,
n_samples=n_samples,
allow_unlabeled=False,
)
y_true = y[:20]
y_pred = y[20:]
y_score = check_random_state(0).normal(size=(20, n_classes))
y_true_binarize = y_true
y_pred_binarize = y_pred
check_averaging(name, y_true, y_true_binarize, y_pred, y_pred_binarize, y_score)
@pytest.mark.parametrize("name", sorted(METRICS_WITH_AVERAGING))
def test_averaging_multilabel_all_zeroes(name):
y_true = np.zeros((20, 3))
y_pred = np.zeros((20, 3))
y_score = np.zeros((20, 3))
y_true_binarize = y_true
y_pred_binarize = y_pred
check_averaging(name, y_true, y_true_binarize, y_pred, y_pred_binarize, y_score)
def test_averaging_binary_multilabel_all_zeroes():
y_true = np.zeros((20, 3))
y_pred = np.zeros((20, 3))
y_true_binarize = y_true
y_pred_binarize = y_pred
# Test _average_binary_score for weight.sum() == 0
binary_metric = lambda y_true, y_score, average="macro": _average_binary_score(
precision_score, y_true, y_score, average
)
_check_averaging(
binary_metric,
y_true,
y_pred,
y_true_binarize,
y_pred_binarize,
is_multilabel=True,
)
@pytest.mark.parametrize("name", sorted(METRICS_WITH_AVERAGING))
def test_averaging_multilabel_all_ones(name):
y_true = np.ones((20, 3))
y_pred = np.ones((20, 3))
y_score = np.ones((20, 3))
y_true_binarize = y_true
y_pred_binarize = y_pred
check_averaging(name, y_true, y_true_binarize, y_pred, y_pred_binarize, y_score)
@ignore_warnings
def check_sample_weight_invariance(name, metric, y1, y2):
rng = np.random.RandomState(0)
sample_weight = rng.randint(1, 10, size=len(y1))
# top_k_accuracy_score always lead to a perfect score for k > 1 in the
# binary case
metric = partial(metric, k=1) if name == "top_k_accuracy_score" else metric
# check that unit weights gives the same score as no weight
unweighted_score = metric(y1, y2, sample_weight=None)
assert_allclose(
unweighted_score,
metric(y1, y2, sample_weight=np.ones(shape=len(y1))),
err_msg="For %s sample_weight=None is not equivalent to sample_weight=ones"
% name,
)
# check that the weighted and unweighted scores are unequal
weighted_score = metric(y1, y2, sample_weight=sample_weight)
# use context manager to supply custom error message
with pytest.raises(AssertionError):
assert_allclose(unweighted_score, weighted_score)
raise ValueError(
"Unweighted and weighted scores are unexpectedly "
"almost equal (%s) and (%s) "
"for %s" % (unweighted_score, weighted_score, name)
)
# check that sample_weight can be a list
weighted_score_list = metric(y1, y2, sample_weight=sample_weight.tolist())
assert_allclose(
weighted_score,
weighted_score_list,
err_msg=(
"Weighted scores for array and list "
"sample_weight input are not equal (%s != %s) for %s"
)
% (weighted_score, weighted_score_list, name),
)
# check that integer weights is the same as repeated samples
repeat_weighted_score = metric(
np.repeat(y1, sample_weight, axis=0),
np.repeat(y2, sample_weight, axis=0),
sample_weight=None,
)
assert_allclose(
weighted_score,
repeat_weighted_score,
err_msg="Weighting %s is not equal to repeating samples" % name,
)
# check that ignoring a fraction of the samples is equivalent to setting
# the corresponding weights to zero
sample_weight_subset = sample_weight[1::2]
sample_weight_zeroed = np.copy(sample_weight)
sample_weight_zeroed[::2] = 0
y1_subset = y1[1::2]
y2_subset = y2[1::2]
weighted_score_subset = metric(
y1_subset, y2_subset, sample_weight=sample_weight_subset
)
weighted_score_zeroed = metric(y1, y2, sample_weight=sample_weight_zeroed)
assert_allclose(
weighted_score_subset,
weighted_score_zeroed,
err_msg=(
"Zeroing weights does not give the same result as "
"removing the corresponding samples (%s != %s) for %s"
)
% (weighted_score_zeroed, weighted_score_subset, name),
)
if not name.startswith("unnormalized"):
# check that the score is invariant under scaling of the weights by a
# common factor
for scaling in [2, 0.3]:
assert_allclose(
weighted_score,
metric(y1, y2, sample_weight=sample_weight * scaling),
err_msg="%s sample_weight is not invariant under scaling" % name,
)
# Check that if number of samples in y_true and sample_weight are not
# equal, meaningful error is raised.
error_message = (
r"Found input variables with inconsistent numbers of "
r"samples: \[{}, {}, {}\]".format(
_num_samples(y1), _num_samples(y2), _num_samples(sample_weight) * 2
)
)
with pytest.raises(ValueError, match=error_message):
metric(y1, y2, sample_weight=np.hstack([sample_weight, sample_weight]))
@pytest.mark.parametrize(
"name",
sorted(
set(ALL_METRICS).intersection(set(REGRESSION_METRICS))
- METRICS_WITHOUT_SAMPLE_WEIGHT
),
)
def test_regression_sample_weight_invariance(name):
n_samples = 50
random_state = check_random_state(0)
# regression
y_true = random_state.random_sample(size=(n_samples,))
y_pred = random_state.random_sample(size=(n_samples,))
metric = ALL_METRICS[name]
check_sample_weight_invariance(name, metric, y_true, y_pred)
@pytest.mark.parametrize(
"name",
sorted(
set(ALL_METRICS)
- set(REGRESSION_METRICS)
- METRICS_WITHOUT_SAMPLE_WEIGHT
- METRIC_UNDEFINED_BINARY
),
)
def test_binary_sample_weight_invariance(name):
# binary
n_samples = 50
random_state = check_random_state(0)
y_true = random_state.randint(0, 2, size=(n_samples,))
y_pred = random_state.randint(0, 2, size=(n_samples,))
y_score = random_state.random_sample(size=(n_samples,))
metric = ALL_METRICS[name]
if name in THRESHOLDED_METRICS:
check_sample_weight_invariance(name, metric, y_true, y_score)
else:
check_sample_weight_invariance(name, metric, y_true, y_pred)
@pytest.mark.parametrize(
"name",
sorted(
set(ALL_METRICS)
- set(REGRESSION_METRICS)
- METRICS_WITHOUT_SAMPLE_WEIGHT
- METRIC_UNDEFINED_BINARY_MULTICLASS
),
)
def test_multiclass_sample_weight_invariance(name):
# multiclass
n_samples = 50
random_state = check_random_state(0)
y_true = random_state.randint(0, 5, size=(n_samples,))
y_pred = random_state.randint(0, 5, size=(n_samples,))
y_score = random_state.random_sample(size=(n_samples, 5))
metric = ALL_METRICS[name]
if name in THRESHOLDED_METRICS:
# softmax
temp = np.exp(-y_score)
y_score_norm = temp / temp.sum(axis=-1).reshape(-1, 1)
check_sample_weight_invariance(name, metric, y_true, y_score_norm)
else:
check_sample_weight_invariance(name, metric, y_true, y_pred)
@pytest.mark.parametrize(
"name",
sorted(
(MULTILABELS_METRICS | THRESHOLDED_MULTILABEL_METRICS | MULTIOUTPUT_METRICS)
- METRICS_WITHOUT_SAMPLE_WEIGHT
),
)
def test_multilabel_sample_weight_invariance(name):
# multilabel indicator
random_state = check_random_state(0)
_, ya = make_multilabel_classification(
n_features=1, n_classes=10, random_state=0, n_samples=50, allow_unlabeled=False
)
_, yb = make_multilabel_classification(
n_features=1, n_classes=10, random_state=1, n_samples=50, allow_unlabeled=False
)
y_true = np.vstack([ya, yb])
y_pred = np.vstack([ya, ya])
y_score = random_state.randint(1, 4, size=y_true.shape)
metric = ALL_METRICS[name]
if name in THRESHOLDED_METRICS:
check_sample_weight_invariance(name, metric, y_true, y_score)
else:
check_sample_weight_invariance(name, metric, y_true, y_pred)
@ignore_warnings
def test_no_averaging_labels():
# test labels argument when not using averaging
# in multi-class and multi-label cases
y_true_multilabel = np.array([[1, 1, 0, 0], [1, 1, 0, 0]])
y_pred_multilabel = np.array([[0, 0, 1, 1], [0, 1, 1, 0]])
y_true_multiclass = np.array([0, 1, 2])
y_pred_multiclass = np.array([0, 2, 3])
labels = np.array([3, 0, 1, 2])
_, inverse_labels = np.unique(labels, return_inverse=True)
for name in METRICS_WITH_AVERAGING:
for y_true, y_pred in [
[y_true_multiclass, y_pred_multiclass],
[y_true_multilabel, y_pred_multilabel],
]:
if name not in MULTILABELS_METRICS and y_pred.ndim > 1:
continue
metric = ALL_METRICS[name]
score_labels = metric(y_true, y_pred, labels=labels, average=None)
score = metric(y_true, y_pred, average=None)
assert_array_equal(score_labels, score[inverse_labels])
@pytest.mark.parametrize(
"name", sorted(MULTILABELS_METRICS - {"unnormalized_multilabel_confusion_matrix"})
)
def test_multilabel_label_permutations_invariance(name):
random_state = check_random_state(0)
n_samples, n_classes = 20, 4
y_true = random_state.randint(0, 2, size=(n_samples, n_classes))
y_score = random_state.randint(0, 2, size=(n_samples, n_classes))
metric = ALL_METRICS[name]
score = metric(y_true, y_score)
for perm in permutations(range(n_classes), n_classes):
y_score_perm = y_score[:, perm]
y_true_perm = y_true[:, perm]
current_score = metric(y_true_perm, y_score_perm)
assert_almost_equal(score, current_score)
@pytest.mark.parametrize(
"name", sorted(THRESHOLDED_MULTILABEL_METRICS | MULTIOUTPUT_METRICS)
)
def test_thresholded_multilabel_multioutput_permutations_invariance(name):
random_state = check_random_state(0)
n_samples, n_classes = 20, 4
y_true = random_state.randint(0, 2, size=(n_samples, n_classes))
y_score = random_state.normal(size=y_true.shape)
# Makes sure all samples have at least one label. This works around errors
# when running metrics where average="sample"
y_true[y_true.sum(1) == 4, 0] = 0
y_true[y_true.sum(1) == 0, 0] = 1
metric = ALL_METRICS[name]
score = metric(y_true, y_score)
for perm in permutations(range(n_classes), n_classes):
y_score_perm = y_score[:, perm]
y_true_perm = y_true[:, perm]
current_score = metric(y_true_perm, y_score_perm)
if metric == mean_absolute_percentage_error:
assert np.isfinite(current_score)
assert current_score > 1e6
# Here we are not comparing the values in case of MAPE because
# whenever y_true value is exactly zero, the MAPE value doesn't
# signify anything. Thus, in this case we are just expecting
# very large finite value.
else:
assert_almost_equal(score, current_score)
@pytest.mark.parametrize(
"name", sorted(set(THRESHOLDED_METRICS) - METRIC_UNDEFINED_BINARY_MULTICLASS)
)
def test_thresholded_metric_permutation_invariance(name):
n_samples, n_classes = 100, 3
random_state = check_random_state(0)
y_score = random_state.rand(n_samples, n_classes)
temp = np.exp(-y_score)
y_score = temp / temp.sum(axis=-1).reshape(-1, 1)
y_true = random_state.randint(0, n_classes, size=n_samples)
metric = ALL_METRICS[name]
score = metric(y_true, y_score)
for perm in permutations(range(n_classes), n_classes):
inverse_perm = np.zeros(n_classes, dtype=int)
inverse_perm[list(perm)] = np.arange(n_classes)
y_score_perm = y_score[:, inverse_perm]
y_true_perm = np.take(perm, y_true)
current_score = metric(y_true_perm, y_score_perm)
assert_almost_equal(score, current_score)
@pytest.mark.parametrize("metric_name", CLASSIFICATION_METRICS)
def test_metrics_consistent_type_error(metric_name):
# check that an understable message is raised when the type between y_true
# and y_pred mismatch
rng = np.random.RandomState(42)
y1 = np.array(["spam"] * 3 + ["eggs"] * 2, dtype=object)
y2 = rng.randint(0, 2, size=y1.size)
err_msg = "Labels in y_true and y_pred should be of the same type."
with pytest.raises(TypeError, match=err_msg):
CLASSIFICATION_METRICS[metric_name](y1, y2)
@pytest.mark.parametrize(
"metric, y_pred_threshold",
[
(average_precision_score, True),
(brier_score_loss, True),
(f1_score, False),
(partial(fbeta_score, beta=1), False),
(jaccard_score, False),
(precision_recall_curve, True),
(precision_score, False),
(recall_score, False),
(roc_curve, True),
],
)
@pytest.mark.parametrize("dtype_y_str", [str, object])
def test_metrics_pos_label_error_str(metric, y_pred_threshold, dtype_y_str):
# check that the error message if `pos_label` is not specified and the
# targets is made of strings.
rng = np.random.RandomState(42)
y1 = np.array(["spam"] * 3 + ["eggs"] * 2, dtype=dtype_y_str)
y2 = rng.randint(0, 2, size=y1.size)
if not y_pred_threshold:
y2 = np.array(["spam", "eggs"], dtype=dtype_y_str)[y2]
err_msg_pos_label_None = (
"y_true takes value in {'eggs', 'spam'} and pos_label is not "
"specified: either make y_true take value in {0, 1} or {-1, 1} or "
"pass pos_label explicit"
)
err_msg_pos_label_1 = (
r"pos_label=1 is not a valid label. It should be one of " r"\['eggs', 'spam'\]"
)
pos_label_default = signature(metric).parameters["pos_label"].default
err_msg = err_msg_pos_label_1 if pos_label_default == 1 else err_msg_pos_label_None
with pytest.raises(ValueError, match=err_msg):
metric(y1, y2)
|
the-stack_0_14791 | """A class to represent a chemical species."""
# The MIT License (MIT)
#
# Copyright (c) 2018 Institute for Molecular Systems Biology, ETH Zurich.
# Copyright (c) 2019 Novo Nordisk Foundation Center for Biosustainability,
# Technical University of Denmark
#
# 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.
from typing import (
Dict,
TypeVar
)
from logging import (
Logger,
getLogger
)
from copy import deepcopy
from chemlite import Compound
from rplibs.rpObject import rpObject
class rpCompound(Compound, rpObject):
"""A class to implement a chemical species
enriched with FBA and thermodynamics informations.
"""
__thermo_str = 'standard_dg_formation'
__fba_str = 'shadow_price'
def __init__(
self,
id: str,
smiles: str = '',
inchi: str = '',
inchikey: str = '',
formula: str = '',
name: str = '',
compartment_id: str = 'c',
logger: Logger = getLogger(__name__)
):
"""Create a rpCompound object with default settings.
Parameters
----------
id: str
smiles: str, optional
inchi: str, optional
inchikey: str, optional
formula: str, optional
name: str, optional
compartment_id: str, optional
logger : Logger, optional
"""
Compound.__init__(
self,
id=id,
smiles=smiles,
inchi=inchi,
inchikey=inchikey,
formula=formula,
name=name,
logger=logger
)
rpObject.__init__(self)
self.set_compartment(compartment_id)
def _to_dict(
self,
full: bool = True
) -> Dict:
"""Get attributes as a dictionary.
Parameters
----------
full: bool, optional
If set to False, the returned dictionary will not
contain attributes inherited from Compound class
(default: True).
"""
if full:
return {
**Compound._to_dict(self),
**rpObject._to_dict(self),
**self.__to_dict()
}
else:
return {
**self.__to_dict(),
**rpObject._to_dict(self)
}
def __to_dict(self) -> Dict:
"""Returns a dictionary which contains attributes
only from rpCompound class excluding inherited ones."""
return {
# 'compartment': self.get_compartment()
}
# def __eq__(self, other) -> bool:
# """Returns the equality between two rpCompound objects."""
# return super(Compound, self).__eq__(other)
def get_thermo_standard_dg_formation(self) -> TypeVar:
"""Get thermodynamics dG formation cost."""
return self.get_thermo_info(rpCompound.__thermo_str)
def get_fba_biomass_shadow_price(self) -> TypeVar:
"""Get flux shadow price during biomass production."""
return self.get_fba_info(f'biomass_{rpCompound.__fba_str}')
def get_fba_fraction_shadow_price(self) -> TypeVar:
"""Get flux shadow price during fraction of reaction analysis."""
return self.get_fba_info(f'fraction_{rpCompound.__fba_str}')
def get_fba_fba_shadow_price(self) -> TypeVar:
"""Get flux shadow price during balance analysis."""
return self.get_fba_info(f'fba_{rpCompound.__fba_str}')
def get_fba_pfba_shadow_price(self) -> TypeVar:
"""Get flux shadow price during parcimonious balance analysis."""
return self.get_fba_info(f'pfba_{rpCompound.__fba_str}')
def get_compartment(self) -> str:
"""Get compound compartment ID."""
return self.__compartment
def set_thermo_standard_dg_formation(self, value: float) -> None:
"""Set dG formation cost.
Parameters
----------
value: float
"""
self.add_thermo_info(rpCompound.__thermo_str, value)
def set_fba_biomass_shadow_price(self, value: float) -> None:
"""Set flux shadow price during biomass production.
Parameters
----------
value: float
"""
self.add_fba_info(f'biomass_{rpCompound.__fba_str}', value)
def set_fba_fraction_shadow_price(self, value: float) -> None:
"""Set flux shadow price during fraction of reaction analysis.
Parameters
----------
value: float
"""
self.add_fba_info(f'fraction_{rpCompound.__fba_str}', value)
def set_fba_fba_shadow_price(self, value: float) -> None:
"""Set flux shadow price during balance analysis..
Parameters
----------
value: float
"""
self.add_fba_info(f'fba_{rpCompound.__fba_str}', value)
def set_fba_pfba_shadow_price(self, value: float) -> None:
"""Set flux shadow price during parcimonious balance analysis.
Parameters
----------
value: float
"""
self.add_fba_info(f'pfba_{rpCompound.__fba_str}', value)
def set_compartment(self, compartment: str) -> None:
"""Set compartment ID of the compound.
Parameters
----------
compartment: str
"""
self.__compartment = compartment
@staticmethod
def from_compound(
compound:Compound,
compartment_id:str='c',
logger: Logger = getLogger(__name__)
) -> 'rpCompound':
'''Create a rpCompound object from a Compound object
:param compound: A Compound object
:param compartment_id: A compartment id (Default: 'c')
:param logger: A logging object (Default: create one)
:type compound: Compound
:type compartment_id: str
:type logger: logging
:return: An rpCompound object
:rtype: rpCompound
'''
return rpCompound(
id=compound.get_id(),
smiles=compound.get_smiles(),
inchi=compound.get_inchi(),
inchikey=compound.get_inchikey(),
formula=compound.get_formula(),
name=compound.get_name(),
compartment_id=compartment_id,
logger=logger
)
|
the-stack_0_14792 | from setuptools import setup, find_packages
import codecs
import os
def get_lookup():
"""get version by way of sourcecred.version, returns a
lookup dictionary with several global variables without
needing to import singularity
"""
lookup = dict()
version_file = os.path.join("sourcecred", "version.py")
with open(version_file) as filey:
exec(filey.read(), lookup)
return lookup
# Read in requirements
def get_reqs(lookup=None, key="INSTALL_REQUIRES"):
"""get requirements, mean reading in requirements and versions from
the lookup obtained with get_lookup
"""
if lookup == None:
lookup = get_lookup()
install_requires = []
for module in lookup[key]:
module_name = module[0]
module_meta = module[1]
if "exact_version" in module_meta:
dependency = "%s==%s" % (module_name, module_meta["exact_version"])
elif "min_version" in module_meta:
if module_meta["min_version"] == None:
dependency = module_name
else:
dependency = "%s>=%s" % (module_name, module_meta["min_version"])
install_requires.append(dependency)
return install_requires
# Make sure everything is relative to setup.py
install_path = os.path.dirname(os.path.abspath(__file__))
os.chdir(install_path)
# Get version information from the lookup
lookup = get_lookup()
VERSION = lookup["__version__"]
NAME = lookup["NAME"]
AUTHOR = lookup["AUTHOR"]
AUTHOR_EMAIL = lookup["AUTHOR_EMAIL"]
PACKAGE_URL = lookup["PACKAGE_URL"]
KEYWORDS = lookup["KEYWORDS"]
DESCRIPTION = lookup["DESCRIPTION"]
LICENSE = lookup["LICENSE"]
with open("README.md") as filey:
LONG_DESCRIPTION = filey.read()
################################################################################
# MAIN #########################################################################
################################################################################
if __name__ == "__main__":
INSTALL_REQUIRES = get_reqs(lookup)
TESTS_REQUIRES = get_reqs(lookup, "TESTS_REQUIRES")
setup(
name=NAME,
version=VERSION,
author=AUTHOR,
author_email=AUTHOR_EMAIL,
maintainer=AUTHOR,
maintainer_email=AUTHOR_EMAIL,
packages=find_packages(),
include_package_data=True,
zip_safe=False,
url=PACKAGE_URL,
license=LICENSE,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
long_description_content_type="text/markdown",
keywords=KEYWORDS,
setup_requires=["pytest-runner"],
install_requires=INSTALL_REQUIRES,
tests_require=TESTS_REQUIRES,
classifiers=[
"Intended Audience :: Science/Research",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python",
"Topic :: Software Development",
"Topic :: Scientific/Engineering",
"Operating System :: Unix",
"Programming Language :: Python :: 3.7",
],
entry_points={"console_scripts": ["sourcecred=sourcecred.cli:main"]},
)
|
the-stack_0_14794 | from random import randint
import codecs
import time
compteur = False
def traitement(mot):
liste = []
for x in range(1, len(mot)-1):
liste.append(mot[x])
res = mot
while res == mot:
alea = []
cp_liste = liste.copy()
n = None
for x in range(0, len(cp_liste)):
n = randint(0, len(cp_liste)-1)
alea.append(cp_liste[n])
cp_liste.remove(cp_liste[n])
alea = ''.join(alea)
res = mot[0]+alea+mot[-1]
return res
sortie = []
i = 0
print(f"Traitement en cours...")
try:
if compteur:
print("")
fichier = codecs.open("input.txt", "r", "utf-8")
texte = fichier.read()
texte2 = texte
lignes = texte.split("\n")
nb_mots = len(texte2.split(" ")) + len(lignes) - 1
fichier.close()
tps1 = time.time()
for x in range(0, len(lignes)):
lignes[x] = lignes[x].split(" ")
sortie_lignes = []
for mot in lignes[x]:
if len(mot.split("-")) > 1:
tirets = []
for tiret in mot.split("-"):
if len(tiret) >= 4:
tirets.append(f"{traitement(tiret)}")
else:
tirets.append(f"{tiret}")
tirets = '-'.join(tirets)
sortie.append(tirets)
else:
if len(mot) >= 4:
sortie.append(traitement(mot))
else:
sortie.append(mot)
if compteur:
i = i + 1
p = "{:06.2F}".format(i * 100 / nb_mots)
print(f"[{p}%] {i} sur {nb_mots} Traité")
sortie.append("\n")
tps2 = time.time()
with codecs.open("output.txt","w", "utf-8") as fichier:
for x in range(0, len(lignes)):
sortie_lignes = " ".join(sortie).split("\n")
sortie_lignes[x] = sortie_lignes[x].strip()
fichier.write(f"{sortie_lignes[x]}\n")
fichier.close()
print(f"\n {nb_mots} mots en {(tps2 - tps1)} seconde(s)")
print(f" {int(nb_mots/(tps2 - tps1))} Mots/s\n")
except Exception as e:
print(f" /!\\ Erreur: {e}\n") |
the-stack_0_14796 | #!/usr/bin/python
import math
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import colors as mcolors
import matplotlib.ticker as ticker
from matplotlib import cm
import sys
sys.path.append('../../python')
from instance import Instance
import visualizer
import histogram
#------------------------------------------------------------------------------
# Load the gene clusters from text files
#------------------------------------------------------------------------------
def load_clusters(filename):
file = open(filename, 'r')
content = file.read().splitlines()
file.close()
gene_clusters = []
for line in content:
gene_cluster = []
atoms_str = line.split(' ')
for elt in atoms_str:
tokens = elt.split('_')
if len(tokens) == 2:
atom = (tokens[0], int(tokens[1]))
gene_cluster.append(atom)
gene_clusters.append(gene_cluster)
return gene_clusters
#------------------------------------------------------------------------------
# Print the gene clusters formatted in LaTex
#------------------------------------------------------------------------------
def print_cluster_latex(instance, cluster):
print(cluster)
cluster_values = { (0,3):0, (0,2):1, (0,1):2, (1,3):3, (1,2):4, (2,3):5, (1,1):6, (2,2):7, (3,3):9}
ordered_cluster = cluster.copy()
ordered_cluster.sort(key = lambda atom: cluster_values[(atom[1], instance.n_values[atom[0]]-1)])
# output the clusters formatted in LaTex
res = ''
for elt in ordered_cluster:
atom_index = instance.get_atom_index(elt)
val = elt[1]
nval = instance.n_values[elt[0]]
color_str = None
if nval == 2:
if val == 0:
color_str = 'BrickRed'
elif val == 1:
color_str = 'OliveGreen'
elif nval == 3:
if val == 0:
color_str = 'BrickRed'
elif val == 1:
color_str = 'Goldenrod'
elif val == 2:
color_str = 'OliveGreen'
elif nval == 4:
if val == 0:
color_str = 'BrickRed'
elif val == 1:
color_str = 'Orange'
elif val == 2:
color_str = 'SpringGreen'
elif val == 3:
color_str = 'OliveGreen'
res += '\\textcolor{' + color_str + '}{$\\boldsymbol{\\textit{' + elt[0] + '}' + '_{' + str(elt[1]) + '/' + str(nval-1) + '}}$}, '
print(res)
return
#------------------------------------------------------------------------------
# Print the gene clusters
#------------------------------------------------------------------------------
def print_gene_clusters(gene_clusters):
for ind_cluster in range(len(gene_clusters)):
print('gene cluster ', ind_cluster, ': ')
str_clusters = ''
for atom in gene_clusters[ind_cluster]:
str_clusters += atom[0] + '_' + str(atom[1]) + ', '
print(str_clusters)
print('\n\n')
return
#------------------------------------------------------------------------------
# Plot the rule matching error for a body
#------------------------------------------------------------------------------
def plot_rule_error(df_discrete, df_coordinates, instance, body, ax):
histo = histogram.Histogram(instance, body, histogram.Histogram_type.GLOBAL)
plasma = cm.get_cmap('plasma_r', 256)
cnorm = mcolors.Normalize(vmin=0, vmax=len(histo.positive_histogram))
cell_score = {barcode : error for error in range(len(histo.positive_histogram)) for barcode in histo.positive_histogram[error]}
# sort all the cells according to the score
barcodes = [index for index in df_coordinates.index]
barcodes.sort(key = lambda elt: cell_score[elt], reverse=True)
df_coordinates_sorted = df_coordinates.loc[barcodes]
col = [cell_score[barcode] for barcode in df_coordinates_sorted.index]
ax.scatter(df_coordinates_sorted['UMAP_1'].values, df_coordinates_sorted['UMAP_2'].values, c=col, cmap=plasma, norm=cnorm, s=3)
# remove UMAP coordinates
ax.xaxis.set_major_locator(ticker.NullLocator())
ax.yaxis.set_major_locator(ticker.NullLocator())
ax.set_xlabel('UMAP 1')
ax.set_ylabel('UMAP 2')
# squared plots
# ax.set_aspect((ax.get_ylim()[1]-ax.get_ylim()[0])/(ax.get_xlim()[1]-ax.get_xlim()[0]))
ax.set_aspect((ax.get_xlim()[1]-ax.get_xlim()[0])/(ax.get_ylim()[1]-ax.get_ylim()[0]))
cbar = ax.get_figure().colorbar(cm.ScalarMappable(norm=cnorm, cmap=plasma), ax=ax)
cbar.set_label('Matching error')
# cbar.set_label('Erreur de couv.')
return
#------------------------------------------------------------------------------
# Plot the cell scores for each cluster
#------------------------------------------------------------------------------
def plot_cell_scores(df_discrete, df_coordinates, gene_clusters, cluster_selection = None, n_col = 3, title=None):
instance = Instance.create_random_instance(df_discrete.copy(deep=False), 0.5)
if cluster_selection == None:
cluster_indexes = [ind for ind in range(len(gene_clusters))]
else:
cluster_indexes = cluster_selection
n_line = math.ceil(len(cluster_indexes)/n_col)
fig, axs = plt.subplots(n_line, n_col)
# fig.tight_layout()
ind_plot = 0
for ind_line in range(n_line):
for ind_col in range(n_col):
if ind_plot < len(cluster_indexes):
ax = axs[ind_line, ind_col]
ind_cluster = cluster_indexes[ind_plot]
body = [instance.get_atom_index(atom) for atom in gene_clusters[ind_cluster] ]
plot_rule_error(df_discrete, df_coordinates, instance, body, ax)
ax.set_title('cluster ' + str(ind_cluster))
ind_plot += 1
# title = None
if title != None:
fig.suptitle(title)
return
#------------------------------------------------------------------------------
# create a dataframe with the gene clusters identity
#------------------------------------------------------------------------------
def create_dataframe_clusters(filename, gene_clusters):
genes = np.concatenate(gene_clusters)
data = [ [int(elt[1]) ] for elt in genes]
for ind_gene in range(len(genes)):
for ind_cluster in range(len(gene_clusters)):
gene_cluster = gene_clusters[ind_cluster]
if (genes[ind_gene][0], int(genes[ind_gene][1])) in gene_cluster:
data[ind_gene].append(1)
else:
data[ind_gene].append(0)
df_gene_clusters = pd.DataFrame(data, index=[elt[0] for elt in genes], columns=['gene_value'] + ['cluster_'+str(ind) for ind in range(len(gene_clusters))])
df_gene_clusters.to_csv(filename)
return
#------------------------------------------------------------------------------
# create a dataframe containing the matching error for all cells on the clusters
#------------------------------------------------------------------------------
def create_cell_score_dataframe(filename, df_discrete, gene_clusters):
instance = Instance.create_random_instance(df_discrete.copy(deep=False), 0.5)
data = [[] for _ in df_discrete.index]
barcode_to_ind = { df_discrete.index[ind]:ind for ind in range(len(df_discrete.index))}
for ind_cluster in range(len(gene_clusters)):
print('gene cluster index: ', ind_cluster)
body = [instance.get_atom_index(atom) for atom in gene_clusters[ind_cluster] ]
histo = histogram.Histogram(instance, body, histogram.Histogram_type.GLOBAL)
for error in range(len(body)+1):
cell_score = 1.-error/len(body)
for barcode in histo.positive_histogram[error]:
data[barcode_to_ind[barcode]].append(cell_score)
df_cell_score = pd.DataFrame(data, index=df_discrete.index, columns=['gene_cluster_' + str(ind) for ind in range(len(gene_clusters))])
df_cell_score.to_csv(filename)
return
#------------------------------------------------------------------------------
# create a discrete dataframe with a subset of the cells
#------------------------------------------------------------------------------
def create_sub_dataframe(filename, df_discrete, selected_cells):
df_sub_discrete = df_discrete.copy()
df_sub_discrete = df_sub_discrete.loc[selected_cells]
df_sub_discrete = df_sub_discrete.loc[:, (df_sub_discrete != df_sub_discrete.iloc[0]).any()] # remove potential constant columns
# print(df_sub_discrete)
# print('filename: ', filename)
df_sub_discrete.to_csv(filename)
return
#------------------------------------------------------------------------------
# compose the cells into two subset based on the cluster matching error
#------------------------------------------------------------------------------
def decompose_cluster(df_coordinates, instance, gene_clusters, cluster_index, error_threshold, all_cells = False):
# plot global histogram from cluster 6 and select cells with a small matching error
body = [instance.get_atom_index(atom) for atom in gene_clusters[cluster_index] ]
histo = histogram.Histogram(instance, body, histogram.Histogram_type.GLOBAL)
fig,ax = plt.subplots()
visualizer.plot_global_histogram(ax, histo)
ax.set_ylabel('cell proportion')
title = 'Matching error of cluster ' + str(cluster_index)
if all_cells:
title += ' on all cells'
else:
title += ' on the myeloids'
ax.set_title(title)
selected_cells = [cell for error in range(error_threshold+1) for cell in histo.positive_histogram[error]]
selected_cells
remaining_cells = [barcode for barcode in df_coordinates.index if not barcode in selected_cells]
# plot the selected cells from cluster 6 in the UMAP
fig, ax = plt.subplots()
ax.scatter(df_coordinates.loc[selected_cells]['UMAP_1'].values, df_coordinates.loc[selected_cells]['UMAP_2'].values, s=3, c='red', zorder=1, label='selected cells')
ax.scatter(df_coordinates.loc[remaining_cells]['UMAP_1'].values, df_coordinates.loc[remaining_cells]['UMAP_2'].values, s=3, zorder=0, c='black', label='other cell')
ax.legend()
title = 'Cells selected from the matching error on cluster ' + str(cluster_index)
if all_cells:
title += ' (on all cells)'
ax.set_title(title)
# export the cells corresponding to cluster 6 in a csv file
df_selection = pd.DataFrame([1 for _ in selected_cells] + [0 for _ in remaining_cells], index=selected_cells+remaining_cells, columns=['selection'])
filename = '../../dataset/Imagine/coexpression/myeloid_c' + str(cluster_index) + '_selection'
if all_cells:
filename += '_all_cells'
filename += '.csv'
df_selection.to_csv(filename)
return
#------------------------------------------------------------------------------
# process the global clusters
#------------------------------------------------------------------------------
def process_global_clusters():
# read the discrete matrix
filename = '../../dataset/Imagine/discrete_matrix.csv'
df_discrete = pd.read_csv(filename, index_col=0)
# print(df_discrete)
# read the embedding coordinates
df_coordinates = pd.read_csv('../../dataset/Imagine/umap_coordinates.csv', index_col=0)
# read the gene clusters
gene_clusters = load_clusters('../../dataset/Imagine/coexpression/gene_clusters.txt')
print('number of gene clusters: ', len(gene_clusters))
# create an artifial instance
instance = Instance.create_random_instance(df_discrete.copy(deep=False), 0.5)
# output the clusters formatted in LaTex
# for cluster_index in range(len(gene_clusters)):
# cluster = gene_clusters[cluster_index]
# print('gene cluster ', cluster_index, '(', len(cluster), ' atoms)')
# print_cluster_latex(instance, gene_clusters[cluster_index])
# print('\n\n')
# Display the cell score for each gene cluster on the UMAP
plot_cell_scores(df_discrete, df_coordinates, gene_clusters, None, 2, 'Matching error of the gene clusters on the cells')
# display gene cluster 5 cell score in a histogram
ind_cluster = 5
body = [instance.get_atom_index(atom) for atom in gene_clusters[ind_cluster] ]
histo = histogram.Histogram(instance, body, histogram.Histogram_type.GLOBAL)
# visualization of the matching error histogram of cluster #4 on all the cells
fig,ax = plt.subplots()
values = [ error for error in range(len(histo.positive_histogram)) for _ in histo.positive_histogram[error] ]
ax.hist(values, 50, density=True, edgecolor='black')
# print(ax.get_ylim())
temp_ylim = ax.get_ylim()
ax.plot([193, 193], [ax.get_ylim()[0], ax.get_ylim()[1]], '--', color='red')
ax.set_ylim(temp_ylim)
# print(ax.get_ylim())
ax.set_ylabel('cell proportion')
ax.set_xlabel('matching error')
ax.set_title('Matching error of gene cluster ' + str(ind_cluster) + ' on all cells')
# ax.set_ylabel('proportion de cellules')
# ax.set_xlabel('erreur de couverture')
# select the cells that have the lower score
threshold = 193
selected_cells = []
other_cells = []
for error in range(threshold+1):
selected_cells += histo.positive_histogram[error]
for error in range(threshold+1,len(histo.positive_histogram)):
other_cells += histo.positive_histogram[error]
# plot a UMAP with the selected cells
fig, ax = plt.subplots()
ax.set_xlabel('UMAP 1')
ax.set_ylabel('UMAP 2')
# ax.set_title('Selected cells from gene cluster ' + str(ind_cluster))
colors = ['red' if barcode in selected_cells else 'black' for barcode in df_coordinates.index]
ax.scatter(df_coordinates.loc[selected_cells]['UMAP_1'], df_coordinates.loc[selected_cells]['UMAP_2'], c='red', s=3, label='selected cells', zorder=1)
# ax.scatter(df_coordinates.loc[selected_cells]['UMAP_1'], df_coordinates.loc[selected_cells]['UMAP_2'], c='red', s=3, label='cellules sélectionnées', zorder=1)
ax.scatter(df_coordinates.loc[other_cells]['UMAP_1'], df_coordinates.loc[other_cells]['UMAP_2'], c='black', s=3, label='other cells', zorder=0)
# ax.scatter(df_coordinates.loc[other_cells]['UMAP_1'], df_coordinates.loc[other_cells]['UMAP_2'], c='black', s=3, label='autres cellules', zorder=0)
ax.set_aspect((ax.get_xlim()[1]-ax.get_xlim()[0])/(ax.get_ylim()[1]-ax.get_ylim()[0]))
ax.set_title('Cells selected through the matching error from cluster ' + str(ind_cluster))
ax.legend(loc='upper right')
# print the gene clusters
print('\n\nList of the gene clusters:\n\n')
print_gene_clusters(gene_clusters)
# creation of a DataFrame with the gene clusters
#create_dataframe_clusters('../../coexpression/gene_clusters.csv', gene_clusters)
# creation of a dataframe with the cell scores (between 0 and 1)
#create_cell_score_dataframe('../../coexpression/gene_cluster_cell_scores.csv', df_discrete, gene_clusters)
# create a sub dataset with the selected cells (presumably Myeloids)
create_sub_dataframe('../../dataset/Imagine/sub_dataset_discrete.csv', df_discrete, selected_cells)
plt.show()
return
#------------------------------------------------------------------------------
# process the sub network clusters
#------------------------------------------------------------------------------
def process_sub_network_clusters():
# read the sub discrete matrix (with only cells selected from the first network)
filename = '../../dataset/Imagine/sub_dataset_discrete.csv'
df_discrete_sub = pd.read_csv(filename, index_col=0)
# print(df_discrete_sub.head())
# print(df_discrete_sub.shape)
# read the complete discrete matrix (to visualize the cluster matching error on all the cells)
filename = '../../dataset/Imagine/discrete_matrix.csv'
df_discrete = pd.read_csv(filename, index_col=0)
# read the embedding coordinates
df_coordinates = pd.read_csv('../../dataset/Imagine/umap_coordinates.csv', index_col=0)
df_coordinates_sub = df_coordinates.loc[df_discrete_sub.index] # select only cells in the sub dataset
# read the gene clusters
gene_clusters = load_clusters('../../dataset/Imagine/coexpression/sub_network_gene_clusters.txt')
###########################################################################
# Manual sub selection of the myeloids
selected_indexes = []
for index in df_coordinates_sub.index:
pos = (df_coordinates_sub['UMAP_1'][index], df_coordinates_sub['UMAP_2'][index])
if pos[0] >= -8 and pos[0] <= 8.0:
if pos[1] >= -16 and pos[1] <= -11:
selected_indexes.append(index)
df_coordinates_sub_manual = df_coordinates_sub.loc[selected_indexes]
print(df_coordinates_sub.shape[0]-df_coordinates_sub_manual.shape[0], ' cells are discarded for the visualization')
###########################################################################
print('number of clusters: ', len(gene_clusters))
print('\n\nList of the gene clusters:\n\n')
print_gene_clusters(gene_clusters)
# create a artificial instance to compute the matching error
instance = Instance.create_random_instance(df_discrete_sub.copy(deep=False), 0.5)
selected_clusters = [2,3,5,6]
print('Selection of clusters: ', selected_clusters)
# Display the cell score for each gene cluster on the UMAP
plot_cell_scores(df_discrete_sub, df_coordinates_sub_manual, gene_clusters, selected_clusters, 2, 'Clusters matching error (sub graph) on the myeloids')
# Same visualization on all the cells this time
plot_cell_scores(df_discrete, df_coordinates, gene_clusters, selected_clusters, 2, 'Clusters matching error (sub graph) on all the cells')
# analysis of cluster 5 matching error
# cluster_index = 5
# error_threshold = 6
# decompose_cluster(df_coordinates_sub, instance, gene_clusters, cluster_index, error_threshold, False)
instance_global = Instance.create_random_instance(df_discrete.copy(deep=False), 0.5) # create a artificial instance on al cells
# output the clusters formatted in LaTex
# for cluster_index in selected_clusters:
# cluster = gene_clusters[cluster_index]
# print('gene cluster ', cluster_index, '(', len(cluster), ' atoms)')
# # print_cluster_latex(instance, gene_clusters[cluster_index])
# print_cluster_latex(instance_global, gene_clusters[cluster_index])
# print('\n\n')
# analysis of cluster 5 matching error on all cells
# cluster_index = 5
# error_threshold = 8
# decompose_cluster(df_coordinates, instance_global, gene_clusters, cluster_index, error_threshold, True)
# cluster 5: inflammed cells
# analysis of cluster 5: selection of cells and decomposition into two groups: cells in the sub dataset and other cells
cluster_index = 5
# visualization of the matching error histogram of cluster #5 on all the cells
body = [instance.get_atom_index(atom) for atom in gene_clusters[cluster_index] ]
histo = histogram.Histogram(instance_global, body, histogram.Histogram_type.GLOBAL)
fig,ax = plt.subplots()
visualizer.plot_global_histogram(ax, histo)
# values = [ error for error in range(len(histo.positive_histogram)) for _ in histo.positive_histogram[error] ]
# print('n values: ', len(values))
# print('len body: ', len(body))
# print(values[:50])
# ax.hist(values, 10, density=True, edgecolor='black')
ax.set_ylabel('cell proportion')
ax.set_xlabel('matching error')
ax.set_title('Matching error of cluster ' + str(cluster_index) + ' on all cells')
# visualisation of the selected cells on the umap
error_threshold = 5
body = [instance_global.get_atom_index(atom) for atom in gene_clusters[cluster_index] ]
histo = histogram.Histogram(instance_global, body, histogram.Histogram_type.GLOBAL)
selected_cells = [cell for error in range(error_threshold+1) for cell in histo.positive_histogram[error]]
other_cells = [barcode for barcode in df_discrete.index if not barcode in selected_cells]
positive_cells = [barcode for barcode in selected_cells if barcode in df_discrete_sub.index]
negative_cells = [barcode for barcode in selected_cells if not barcode in positive_cells]
fig,ax = plt.subplots()
ax.scatter(df_coordinates.loc[other_cells]['UMAP_1'].values, df_coordinates.loc[other_cells]['UMAP_2'].values, c='k', s=3, label='other cells')
ax.scatter(df_coordinates.loc[positive_cells]['UMAP_1'].values, df_coordinates.loc[positive_cells]['UMAP_2'].values, c='r', s=3, label='selected myeloids')
ax.scatter(df_coordinates.loc[negative_cells]['UMAP_1'].values, df_coordinates.loc[negative_cells]['UMAP_2'].values, c='b', s=3, label='other cells selected')
ax.set_title('Cells selected from cluster 5 (red and blue)' + ' threshold = ' + str(error_threshold))
ax.set_xlabel('UMAP_1')
ax.set_ylabel('UMAP_2')
ax.legend()
df_selection = pd.DataFrame([1 for _ in positive_cells] + [0 for _ in negative_cells], index=positive_cells+negative_cells, columns=['selection'])
filename = '../../dataset/Imagine/coexpression/myeloid_c5_selection_myeloid_vs_others.csv'
df_selection.to_csv(filename)
# analysis of cluster 6 (CD8) matching error
cluster_index = 6
body = [instance.get_atom_index(atom) for atom in gene_clusters[cluster_index] ]
body_global = [instance_global.get_atom_index(atom) for atom in gene_clusters[cluster_index]]
# print(body)
histo_global = histogram.Histogram(instance_global, body_global, histogram.Histogram_type.GLOBAL)
fig,ax = plt.subplots()
visualizer.plot_global_histogram(ax, histo_global)
ax.set_ylabel('cell proportion')
ax.set_xlabel('matching error')
ax.set_title('Matching error of cluster ' + str(cluster_index) + ' on all cells')
error_threshold = 9
decompose_cluster(df_coordinates_sub, instance, gene_clusters, cluster_index, error_threshold, False)
# display the selected cells
selected_cells = [elt for error in range(error_threshold) for elt in histo.positive_histogram[error]]
other_cells = [barcode for barcode in df_discrete.index if not barcode in selected_cells]
fig, ax = plt.subplots()
ax.scatter(df_coordinates.loc[other_cells]['UMAP_1'].values, df_coordinates.loc[other_cells]['UMAP_2'].values, c='k', s=3, label = 'other cells')
ax.scatter(df_coordinates.loc[selected_cells]['UMAP_1'].values, df_coordinates.loc[selected_cells]['UMAP_2'].values, c='red', s=3, label='selected cells')
ax.set_title('Cells selected from the matching error of cluster ' + str(cluster_index) + ' (threshold = ' + str(error_threshold) + ')')
ax.set_xlabel('UMAP_1')
ax.set_ylabel('UMAP_2')
ax.legend()
# fig, ax = plt.subplots()
# plot_rule_error(df_discrete, df_coordinates, instance_global, body_global, ax)
# print the gene clusters
# print_gene_clusters(gene_clusters)
# creation of a DataFrame with the gene clusters
# create_dataframe_clusters('../../dataset/Imagine/coexpression/sub_network_gene_clusters.csv', gene_clusters)
# creation of a dataframe with the cell scores (between 0 and 1)
# create_cell_score_dataframe('../../dataset/Imagine/coexpression/sub_network_gene_cluster_cell_scores.csv', df_discrete, gene_clusters)
plt.show()
return
process_global_clusters()
process_sub_network_clusters()
|
the-stack_0_14797 | # -*- coding: utf-8 -*-
from anima import logger
from anima.ui.lib import QtGui, QtWidgets
class VersionsTableWidget(QtWidgets.QTableWidget):
"""A QTableWidget derivative specialized to hold version data
"""
def __init__(self, parent=None, *args, **kwargs):
QtWidgets.QTableWidget.__init__(self, parent, *args, **kwargs)
self.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
# self.setAlternatingRowColors(True)
self.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
self.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
self.setShowGrid(False)
self.setColumnCount(5)
self.setObjectName("previous_versions_table_widget")
self.setColumnCount(5)
self.setRowCount(0)
self.setHorizontalHeaderItem(0, QtWidgets.QTableWidgetItem())
self.setHorizontalHeaderItem(1, QtWidgets.QTableWidgetItem())
self.setHorizontalHeaderItem(2, QtWidgets.QTableWidgetItem())
self.setHorizontalHeaderItem(3, QtWidgets.QTableWidgetItem())
self.setHorizontalHeaderItem(4, QtWidgets.QTableWidgetItem())
self.horizontalHeader().setStretchLastSection(True)
self.verticalHeader().setStretchLastSection(False)
tool_tip_html = \
"<html><head/><body><p>Right click to:</p><ul style=\"" \
"margin-top: 0px; margin-bottom: 0px; margin-left: 0px; " \
"margin-right: 0px; -qt-list-indent: 1;\"><li><span style=\" " \
"font-weight:600;\">Copy Path</span></li><li><span style=\" " \
"font-weight:600;\">Browse Path</span></li><li><span style=\" " \
"font-weight:600;\">Change Description</span></li></ul>" \
"<p>Double click to:</p><ul style=\"margin-top: 0px; " \
"margin-bottom: 0px; margin-left: 0px; margin-right: 0px; " \
"-qt-list-indent: 1;\"><li style=\" margin-top:12px; " \
"margin-bottom:12px; margin-left:0px; margin-right:0px; " \
"-qt-block-indent:0; text-indent:0px;\"><span style=\" " \
"font-weight:600;\">Open</span></li></ul></body></html>"
try:
self.setToolTip(
QtWidgets.QApplication.translate(
"Dialog",
tool_tip_html,
None,
QtWidgets.QApplication.UnicodeUTF8
)
)
except AttributeError:
self.setToolTip(
QtWidgets.QApplication.translate(
"Dialog",
tool_tip_html,
None
)
)
self.versions = []
self.labels = [
'#',
'App',
'Created By',
'Updated By',
'Size',
'Date',
'Description',
]
self.setColumnCount(len(self.labels))
def clear(self):
"""overridden clear method
"""
QtWidgets.QTableWidget.clear(self)
self.versions = []
# reset the labels
self.setHorizontalHeaderLabels(self.labels)
def select_version(self, version):
"""selects the given version in the list
"""
# select the version in the previous version list
index = -1
for i, prev_version in enumerate(self.versions):
if self.versions[i].id == version.id:
index = i
break
logger.debug('current index: %s' % index)
# select the row
if index != -1:
item = self.item(index, 0)
logger.debug('item : %s' % item)
self.setCurrentItem(item)
@property
def current_version(self):
"""returns the current selected version from the table
"""
index = self.currentRow()
try:
version = self.versions[index]
return version
except IndexError:
return None
def update_content(self, versions):
"""updates the content with the given versions data
"""
import os
import datetime
logger.debug('VersionsTableWidget.update_content() is started')
self.clear()
self.versions = versions
self.setRowCount(len(versions))
def set_published_font(item):
"""sets the font for the given item
:param item: the a QTableWidgetItem
"""
my_font = item.font()
my_font.setBold(True)
item.setFont(my_font)
foreground = item.foreground()
foreground.setColor(QtGui.QColor(0, 192, 0))
item.setForeground(foreground)
# update the previous versions list
from anima import defaults
for i, version in enumerate(versions):
is_published = version.is_published
absolute_full_path = os.path.normpath(
os.path.expandvars(version.full_path)
).replace('\\', '/')
version_file_exists = os.path.exists(absolute_full_path)
c = 0
# ------------------------------------
# version_number
item = QtWidgets.QTableWidgetItem(str(version.version_number))
# align to center and vertical center
item.setTextAlignment(0x0004 | 0x0080)
if is_published:
set_published_font(item)
if not version_file_exists:
item.setBackground(QtGui.QColor(64, 0, 0))
self.setItem(i, c, item)
c += 1
# ------------------------------------
# ------------------------------------
# created_with
item = QtWidgets.QTableWidgetItem()
if version.created_with:
from anima.ui import utils as ui_utils
app_icon = ui_utils.get_icon(version.created_with.lower())
if app_icon:
item.setIcon(app_icon)
if is_published:
set_published_font(item)
if not version_file_exists:
item.setBackground(QtGui.QColor(64, 0, 0))
self.setItem(i, c, item)
c += 1
# ------------------------------------
# ------------------------------------
# user.name
created_by = ''
if version.created_by_id:
created_by = defaults.user_names_lut[version.created_by_id]
item = QtWidgets.QTableWidgetItem(created_by)
# align to left and vertical center
item.setTextAlignment(0x0001 | 0x0080)
if is_published:
set_published_font(item)
if not version_file_exists:
item.setBackground(QtGui.QColor(64, 0, 0))
self.setItem(i, c, item)
c += 1
# ------------------------------------
# ------------------------------------
# user.name
updated_by = ''
if version.updated_by_id:
updated_by = defaults.user_names_lut[version.updated_by_id]
item = QtWidgets.QTableWidgetItem(updated_by)
# align to left and vertical center
item.setTextAlignment(0x0001 | 0x0080)
if is_published:
set_published_font(item)
if not version_file_exists:
item.setBackground(QtGui.QColor(64, 0, 0))
self.setItem(i, c, item)
c += 1
# ------------------------------------
# ------------------------------------
# file size
# get the file size
# file_size_format = "%.2f MB"
file_size = -1
if version_file_exists:
file_size = float(
os.path.getsize(absolute_full_path)) / 1048576
from anima import defaults
item = QtWidgets.QTableWidgetItem(
defaults.file_size_format % file_size
)
# align to left and vertical center
item.setTextAlignment(0x0001 | 0x0080)
if is_published:
set_published_font(item)
if not version_file_exists:
item.setBackground(QtGui.QColor(64, 0, 0))
self.setItem(i, c, item)
c += 1
# ------------------------------------
# ------------------------------------
# date
# get the file date
file_date = datetime.datetime.today()
if version_file_exists:
file_date = datetime.datetime.fromtimestamp(
os.path.getmtime(absolute_full_path)
)
item = QtWidgets.QTableWidgetItem(
file_date.strftime(defaults.date_time_format)
)
# align to left and vertical center
item.setTextAlignment(0x0001 | 0x0080)
if is_published:
set_published_font(item)
if not version_file_exists:
item.setBackground(QtGui.QColor(64, 0, 0))
self.setItem(i, c, item)
c += 1
# ------------------------------------
# ------------------------------------
# description
item = QtWidgets.QTableWidgetItem(version.description)
# align to left and vertical center
item.setTextAlignment(0x0001 | 0x0080)
if is_published:
set_published_font(item)
if not version_file_exists:
item.setBackground(QtGui.QColor(64, 0, 0))
self.setItem(i, c, item)
c += 1
# ------------------------------------
# resize the first column
self.resizeRowsToContents()
self.resizeColumnsToContents()
self.resizeRowsToContents()
logger.debug('VersionsTableWidget.update_content() is finished')
|
the-stack_0_14798 | """
AWR + SAC from demo experiment
"""
from railrl.demos.source.dict_to_mdp_path_loader import DictToMDPPathLoader
from railrl.demos.source.mdp_path_loader import MDPPathLoader, MDPPathLoader
from railrl.launchers.experiments.ashvin.awr_sac_rl import experiment
import railrl.misc.hyperparameter as hyp
from railrl.launchers.arglauncher import run_variants
if __name__ == "__main__":
variant = dict(
num_epochs=100,
num_eval_steps_per_epoch=5000,
num_trains_per_train_loop=1000,
num_expl_steps_per_train_loop=1000,
min_num_steps_before_training=1000,
max_path_length=1000,
batch_size=256,
replay_buffer_size=int(1E6),
algorithm="SAC",
version="normal",
collection_mode='batch',
layer_size=256,
policy_kwargs=dict(
hidden_sizes=[256, 256],
),
trainer_kwargs=dict(
discount=0.99,
soft_target_tau=5e-3,
target_update_period=1,
policy_lr=3E-4,
qf_lr=3E-4,
reward_scale=1,
beta=1,
use_automatic_entropy_tuning=True,
bc_num_pretrain_steps=10000,
q_num_pretrain_steps=10000,
policy_weight_decay=1e-4,
bc_loss_type="mle",
),
num_exps_per_instance=1,
region='us-west-2',
path_loader_class=DictToMDPPathLoader,
path_loader_kwargs=dict(
obs_key="state_observation",
demo_path=["demos/icml2020/hand/door.npy"],
demo_off_policy_path=[
"/home/ashvin/data/s3doodad/ashvin/icml2020/hand/door/demo-bc5/run0/id*/video_*.p",
# "ashvin/icml2020/hand/door/demo-bc1/run4/video_*.p",
# "ashvin/icml2020/hand/door/demo-bc1/run5/video_*.p",
],
),
logger_variant=dict(
tensorboard=True,
),
load_demos=True,
pretrain_policy=True,
pretrain_rl=True,
)
search_space = {
'env': ["door-v0", ],
'seedid': range(5),
'trainer_kwargs.beta': [10, ],
}
sweeper = hyp.DeterministicHyperparameterSweeper(
search_space, default_parameters=variant,
)
variants = []
for variant in sweeper.iterate_hyperparameters():
variants.append(variant)
run_variants(experiment, variants, run_id=0)
|
the-stack_0_14799 | #!/usr/bin/python
import math
import sys
from PIL import Image
from util import Helper, ImageHelper
from util.CharType import CharType, maps as char_maps
from util.ImageType import ImageType
BRAILLE_BASE = int('0x2800', 16)
def convert(pixel, char_type=CharType.ASCII):
return char_maps[char_type][pixel // (256 // len(char_maps[char_type]))]
def convert_to_braille(image, threshold=128, use_dot_spacing=False):
"""
convert sets of 2x4 pixels into their braille equivalent by checking if a given pixel should be displayed or not
and setting its respective bit
see https://en.wikipedia.org/wiki/Braille_Patterns#Block for more info
"""
width, height = image.size
text = [[0] * math.ceil(width / 2) for _ in range(math.ceil(height / 4))]
data = image.load()
# convert every 2x4 area in its braille equivalent
for y in range(0, height, 4):
for x in range(0, width, 2):
unicode_offset = 0
for i in range(2):
for j in range(4):
if x + i < width and y + j < height:
# mark bit index if pixel is white or not
unicode_offset += (data[x + i, y + j] <= threshold) << ((i * 4) + j)
if use_dot_spacing and unicode_offset == 0:
unicode_offset = 4 # blank braille char has kerning issues for some fonts
text[y // 4][x // 2] = chr(BRAILLE_BASE + unicode_offset)
return text
def convert_to_text(image, char_type=CharType.ASCII):
if char_type == CharType.BRAILLE:
return convert_to_braille(image)
text = []
data = image.load()
for y in range(image.height):
text.append([])
for x in range(image.width):
text[y].append(convert(data[x, y], char_type))
return text
def setup_text_image(text):
image = ''
for i in range(len(text)):
image += ''.join(text[i]) + '\n'
return image
def store_text(text, input_filename):
with open(ImageHelper.resource_folder(f'output/{input_filename}.txt'), 'w', encoding='utf-8') as output_file:
output_file.write(text)
def gray_scale_image():
image = Image.new('L', [255, 255])
data = image.load()
for x in range(image.width):
for y in range(image.height):
data[x, y] = x
return image
def to_ascii_from_image(image, name='image', invert=True, char_type=CharType.BRAILLE, image_type=ImageType.DITHER):
"""
convert to text via the following steps:
1. fit image to terminal screen size
2. invert image if needed
3. convert image based on given ImageType
4. convert pixels in image to their given CharType equivalent
5. join the 2d image array into a single string
"""
image = Helper.fit_image_to_terminal(image, char_type == CharType.BRAILLE)
if invert:
image = ImageHelper.invert(image)
image = ImageHelper.convert_image(image, image_type)
text_array = convert_to_text(image, char_type)
ascii_text = setup_text_image(text_array)
if ImageHelper.DEBUG:
store_text(ascii_text, name)
return ascii_text
def to_ascii(input_filename):
return to_ascii_from_image(Image.open(input_filename).convert('RGB'), input_filename)
def main():
if len(sys.argv) < 2:
raise RuntimeError('Usage: this_script.py <input file>')
input_filename = sys.argv[1]
text = to_ascii(input_filename)
print(text)
if __name__ == '__main__':
main()
# input('Press enter to exit')
|
the-stack_0_14801 | #!/usr/bin/env python
##
## Copyright (C) 2017, Amit Aides, all rights reserved.
##
## This file is part of Camera Network
## (see https://bitbucket.org/amitibo/cameranetwork_git).
##
## Redistribution and use in source and binary forms, with or without modification,
## are permitted provided that the following conditions are met:
##
## 1) The software is provided under the terms of this license strictly for
## academic, non-commercial, not-for-profit purposes.
## 2) Redistributions of source code must retain the above copyright notice, this
## list of conditions (license) and the following disclaimer.
## 3) Redistributions in binary form must reproduce the above copyright notice,
## this list of conditions (license) and the following disclaimer in the
## documentation and/or other materials provided with the distribution.
## 4) The name of the author may not be used to endorse or promote products derived
## from this software without specific prior written permission.
## 5) As this software depends on other libraries, the user must adhere to and keep
## in place any licensing terms of those libraries.
## 6) Any publications arising from the use of this software, including but not
## limited to academic journal and conference publications, technical reports and
## manuals, must cite the following works:
## Dmitry Veikherman, Amit Aides, Yoav Y. Schechner and Aviad Levis, "Clouds in The Cloud" Proc. ACCV, pp. 659-674 (2014).
##
## THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
## WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
## MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
## EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
## INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
## BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
## LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
## OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
## ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.##
"""
Clean memory of the odroid.
The script moves captured date to a backup folder. To remove
the backup folder (and clear the memory) use the ``--delete`` flag.
"""
import argparse
import CameraNetwork.global_settings as gs
import datetime
import os
import shutil
import warnings
gs.initPaths()
BACKUP_FOLDER = os.path.expanduser(
datetime.datetime.now().strftime("~/BACKUP_%Y_%m_%d")
)
def move(src_path):
_, tmp = os.path.split(src_path)
dst_path = os.path.join(BACKUP_FOLDER, tmp)
if not os.path.exists(src_path):
print("Source path does not exist: {}".format(src_path))
return
assert not os.path.exists(dst_path),"Destination path exists: {}".format(dst_path)
shutil.move(src_path, dst_path)
def main(delete_backup=False):
if not os.path.exists(BACKUP_FOLDER):
os.makedirs(BACKUP_FOLDER)
print("Created backup folder: {}".format(BACKUP_FOLDER))
move(gs.CAPTURE_PATH)
move(gs.DEFAULT_LOG_FOLDER)
move(gs.MASK_PATH)
move(gs.SUN_POSITIONS_PATH)
if delete_backup:
answer = raw_input("Remove backup? [y/n]:")
if answer == 'y':
shutil.rmtree(BACKUP_FOLDER)
print("Backup folder removed!")
else:
print("Backup folder NOT removed!")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Clean memory of the odroid.")
parser.add_argument(
'--delete',
action='store_true',
help='When set, the backup folder will be deleted.'
)
args = parser.parse_args()
main(args.delete)
|
the-stack_0_14802 | """
"""
import time
import unittest
import threading
from pynetworking import ClientManager, MultiServerCommunicator
from pynetworking.tests.example_functions import DummyServerCommunicator, DummyMultiServerCommunicator, \
DummyClientCommunicator
from pynetworking.Logging import logger
from pynetworking import Communication_general
logger.setLevel(10)
class TestManyClients(unittest.TestCase):
address = "127.0.0.1", 5000
def setUp(self):
self.manager = ClientManager(self.address, DummyClientCommunicator)
self.manager.start()
Communication_general.ENCRYPTED_COMMUNICATION = False
def tearDown(self):
DummyMultiServerCommunicator.close_all_connections()
logger.debug(self.manager.clients)
self.manager.stop_listening()
self.manager.stop_connections()
def test_many(self):
clients = []
thread_pool = []
def client_exe(client: DummyMultiServerCommunicator):
client.connect(self.address)
c_id = client.remote_functions.return_client_id()
print(c_id)
time.sleep(5)
client.close_connection()
for i in range(20):
clients.append(DummyMultiServerCommunicator(i))
thread_pool.append(threading.Thread(target=client_exe, args=(clients[i],)))
thread_pool[i].start()
time.sleep(0.1)
time.sleep(1)
logger.debug("Finished") |
the-stack_0_14804 | from pythonds.graphs import PriorityQueue, Graph, Vertex
def dijkstra(aGraph: Graph, start: Vertex):
pq = PriorityQueue()
start.setDistance(0)
pq.buildHeap([(v.getDistance(), v) for v in aGraph])
while not pq.isEmpty():
currentVert = pq.delMin()
for nextVert in currentVert.getConnections():
newDist = currentVert.getDistance() + currentVert.getWeight(nextVert)
if newDist < nextVert.getDistance():
nextVert.setDistance(newDist)
nextVert.setPred(currentVert)
pd.decreaseKey(nextVert, newDist)
|
the-stack_0_14806 | # Copyright (c) 2010-2012 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.
# See http://code.google.com/p/python-nose/issues/detail?id=373
# The code below enables nosetests to work with i18n _() blocks
from __future__ import print_function
import sys
import os
try:
from unittest.util import safe_repr
except ImportError:
# Probably py26
_MAX_LENGTH = 80
def safe_repr(obj, short=False):
try:
result = repr(obj)
except Exception:
result = object.__repr__(obj)
if not short or len(result) < _MAX_LENGTH:
return result
return result[:_MAX_LENGTH] + ' [truncated]...'
from eventlet.green import socket
# make unittests pass on all locale
import swift
setattr(swift, 'gettext_', lambda x: x)
from swift.common.utils import readconf
# Work around what seems to be a Python bug.
# c.f. https://bugs.launchpad.net/swift/+bug/820185.
import logging
logging.raiseExceptions = False
def get_config(section_name=None, defaults=None):
"""
Attempt to get a test config dictionary.
:param section_name: the section to read (all sections if not defined)
:param defaults: an optional dictionary namespace of defaults
"""
config = {}
if defaults is not None:
config.update(defaults)
config_file = os.environ.get('SWIFT_TEST_CONFIG_FILE',
'/etc/swift/test.conf')
try:
config = readconf(config_file, section_name)
except IOError:
if not os.path.exists(config_file):
print('Unable to read test config %s - file not found'
% config_file, file=sys.stderr)
elif not os.access(config_file, os.R_OK):
print('Unable to read test config %s - permission denied'
% config_file, file=sys.stderr)
except ValueError as e:
print(e)
return config
def listen_zero():
"""
The eventlet.listen() always sets SO_REUSEPORT, so when called with
("localhost",0), instead of returning unique ports it can return the
same port twice. That causes our tests to fail, so open-code it here
without SO_REUSEPORT.
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("127.0.0.1", 0))
sock.listen(50)
return sock
|
the-stack_0_14807 | # Lint as: python3
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""API for Tensorflow Model Analysis."""
# TODO(b/149126671): Put ValidationResultsWriter in a separate file.
from __future__ import absolute_import
from __future__ import division
# Standard __future__ imports
from __future__ import print_function
import os
import tempfile
from typing import Any, Dict, Iterator, List, Optional, Set, Text, Union
from absl import logging
import apache_beam as beam
import pandas as pd
import pyarrow as pa
import tensorflow as tf
from tensorflow_model_analysis import config
from tensorflow_model_analysis import constants
from tensorflow_model_analysis import model_util
from tensorflow_model_analysis import types
from tensorflow_model_analysis.eval_saved_model import constants as eval_constants
from tensorflow_model_analysis.evaluators import evaluator
from tensorflow_model_analysis.evaluators import metrics_and_plots_evaluator
from tensorflow_model_analysis.evaluators import metrics_and_plots_evaluator_v2
from tensorflow_model_analysis.extractors import batched_input_extractor
from tensorflow_model_analysis.extractors import batched_predict_extractor_v2
from tensorflow_model_analysis.extractors import extractor
from tensorflow_model_analysis.extractors import input_extractor
from tensorflow_model_analysis.extractors import predict_extractor
from tensorflow_model_analysis.extractors import slice_key_extractor
from tensorflow_model_analysis.extractors import tfjs_predict_extractor
from tensorflow_model_analysis.extractors import tflite_predict_extractor
from tensorflow_model_analysis.extractors import unbatch_extractor
from tensorflow_model_analysis.post_export_metrics import post_export_metrics
from tensorflow_model_analysis.proto import metrics_for_slice_pb2
from tensorflow_model_analysis.proto import validation_result_pb2
from tensorflow_model_analysis.slicer import slicer_lib as slicer
from tensorflow_model_analysis.validators import validator
from tensorflow_model_analysis.view import util
from tensorflow_model_analysis.view import view_types
from tensorflow_model_analysis.writers import eval_config_writer
from tensorflow_model_analysis.writers import metrics_plots_and_validations_writer
from tensorflow_model_analysis.writers import writer
from tfx_bsl.arrow import table_util
from tfx_bsl.tfxio import tensor_adapter
from tfx_bsl.tfxio import tf_example_record
from tensorflow_metadata.proto.v0 import schema_pb2
def _assert_tensorflow_version():
"""Check that we're using a compatible TF version."""
# Fail with a clear error in case we are not using a compatible TF version.
major, minor, _ = tf.version.VERSION.split('.')
if (int(major) not in (1, 2)) or (int(major) == 1 and int(minor) < 15):
raise RuntimeError(
'Tensorflow version >= 1.15, < 3 is required. Found (%s). Please '
'install the latest 1.x or 2.x version from '
'https://github.com/tensorflow/tensorflow. ' % tf.version.VERSION)
if int(major) == 2:
logging.warning(
'Tensorflow version (%s) found. Note that TFMA support for TF 2.0 '
'is currently in beta', tf.version.VERSION)
def _is_legacy_eval(
eval_shared_model: Optional[types.MaybeMultipleEvalSharedModels],
eval_config: Optional[config.EvalConfig]):
"""Returns True if legacy evaluation is being used."""
# A legacy evaluation is an evalution that uses only a single EvalSharedModel,
# has no tags (or uses "eval" as its tag), and does not specify an eval_config
# (or specifies an eval_config with no metrics). The legacy evaluation is
# based on using add_metrics_callbacks to create a modified version of the
# graph saved with an EvalSavedModel. The newer version of evaluation supports
# both add_metrics_callbacks as well as metrics defined in MetricsSpecs inside
# of EvalConfig. The newer version works with both "eval" and serving models
# and also supports multi-model evaluation. This function is used by code to
# support backwards compatibility for callers that have not updated to use the
# new EvalConfig.
return (eval_shared_model and not isinstance(eval_shared_model, dict) and
not isinstance(eval_shared_model, list) and
((not eval_shared_model.model_loader.tags or
eval_constants.EVAL_TAG in eval_shared_model.model_loader.tags) and
(not eval_config or not eval_config.metrics_specs)))
def _default_eval_config(eval_shared_models: List[types.EvalSharedModel],
slice_spec: Optional[List[slicer.SingleSliceSpec]],
write_config: Optional[bool],
compute_confidence_intervals: Optional[bool],
min_slice_size: int):
"""Creates default EvalConfig (for use in legacy evaluations)."""
model_specs = []
for shared_model in eval_shared_models:
example_weight_key = shared_model.example_weight_key
example_weight_keys = {}
if example_weight_key and isinstance(example_weight_key, dict):
example_weight_keys = example_weight_key
example_weight_key = ''
model_specs.append(
config.ModelSpec(
name=shared_model.model_name,
example_weight_key=example_weight_key,
example_weight_keys=example_weight_keys))
slicing_specs = None
if slice_spec:
slicing_specs = [s.to_proto() for s in slice_spec]
options = config.Options()
options.compute_confidence_intervals.value = compute_confidence_intervals
options.min_slice_size.value = min_slice_size
if not write_config:
options.disabled_outputs.values.append(eval_config_writer.EVAL_CONFIG_FILE)
return config.EvalConfig(
model_specs=model_specs, slicing_specs=slicing_specs, options=options)
def _model_types(
eval_shared_model: Optional[types.MaybeMultipleEvalSharedModels]
) -> Optional[Set[Text]]:
"""Returns model types associated with given EvalSharedModels."""
eval_shared_models = model_util.verify_and_update_eval_shared_models(
eval_shared_model)
if not eval_shared_models:
return None
else:
return set([m.model_type for m in eval_shared_models])
def _update_eval_config_with_defaults(
eval_config: config.EvalConfig,
eval_shared_model: Optional[types.MaybeMultipleEvalSharedModels]
) -> config.EvalConfig:
"""Returns updated eval config with default values."""
eval_shared_models = model_util.verify_and_update_eval_shared_models(
eval_shared_model)
maybe_add_baseline = eval_shared_models and len(eval_shared_models) == 2
return config.update_eval_config_with_defaults(
eval_config, maybe_add_baseline=maybe_add_baseline)
MetricsForSlice = metrics_for_slice_pb2.MetricsForSlice
def load_metrics(output_path: Text,
output_file_format: Text = '') -> Iterator[MetricsForSlice]:
"""Read and deserialize the MetricsForSlice records."""
for m in metrics_plots_and_validations_writer.load_and_deserialize_metrics(
output_path, output_file_format):
yield m
PlotsForSlice = metrics_for_slice_pb2.PlotsForSlice
def load_plots(output_path: Text,
output_file_format: Text = '') -> Iterator[PlotsForSlice]:
"""Read and deserialize the PlotsForSlice records."""
for p in metrics_plots_and_validations_writer.load_and_deserialize_plots(
output_path, output_file_format):
yield p
# Define types here to avoid type errors between OSS and internal code.
ValidationResult = validation_result_pb2.ValidationResult
def load_validation_result(output_path: Text,
output_file_format: Text = '') -> ValidationResult:
"""Read and deserialize the ValidationResult."""
return metrics_plots_and_validations_writer.load_and_deserialize_validation_result(
output_path, output_file_format)
def make_eval_results(results: List[view_types.EvalResult],
mode: Text) -> view_types.EvalResults:
"""Run model analysis for a single model on multiple data sets.
Args:
results: A list of TFMA evaluation results.
mode: The mode of the evaluation. Currently, tfma.DATA_CENTRIC_MODE and
tfma.MODEL_CENTRIC_MODE are supported.
Returns:
An `tfma.view.EvalResults` object containing all evaluation results. This
can be used to construct a time series view.
"""
return view_types.EvalResults(results, mode)
def load_eval_results(
output_paths: Union[Text, List[Text]],
output_file_format: Optional[Text] = '',
mode: Text = constants.MODEL_CENTRIC_MODE,
model_name: Optional[Text] = None) -> view_types.EvalResults:
"""Loads results for multiple models or multiple data sets.
Args:
output_paths: A single path or list of output paths of completed tfma runs.
output_file_format: Optional file extension to filter files by.
mode: The mode of the evaluation. Currently, tfma.DATA_CENTRIC_MODE and
tfma.MODEL_CENTRIC_MODE are supported.
model_name: Filters to only return results for given model. If unset all
models are returned.
Returns:
An EvalResults containing the evaluation results serialized at output_paths.
This can be used to construct a time series view.
"""
results = []
if not isinstance(output_paths, list):
output_paths = [output_paths]
for output_path in output_paths:
if model_name is None:
_, _, _, model_locations = eval_config_writer.load_eval_run(output_path)
model_names = list(model_locations.keys())
else:
model_names = [model_name]
for model_name in model_names:
results.append(
load_eval_result(
output_path, output_file_format, model_name=model_name))
return make_eval_results(results, mode)
def load_eval_result(
output_path: Text,
output_file_format: Optional[Text] = '',
model_name: Optional[Text] = None) -> view_types.EvalResult:
"""Loads EvalResult object for use with the visualization functions.
Args:
output_path: Output directory containing config, metrics, plots, etc.
output_file_format: Optional file extension to filter files by.
model_name: Optional model name. Required if multi-model evaluation was run.
Returns:
EvalResult object for use with the visualization functions.
"""
# Config, metrics, and plots files should all exist under the given output
# directory, but fairness plugin has a use-case where only the metrics are
# provided so we support all files as being optional (the EvalResult will have
# corresponding None values for files that are not present).
eval_config, data_location, file_format, model_locations = (
eval_config_writer.load_eval_run(output_path))
metrics_list = []
for p in metrics_plots_and_validations_writer.load_and_deserialize_metrics(
output_path, output_file_format):
metrics = util.convert_metrics_proto_to_dict(p, model_name=model_name)
if metrics is not None:
metrics_list.append(metrics)
plots_list = []
for p in metrics_plots_and_validations_writer.load_and_deserialize_plots(
output_path, output_file_format):
plots = util.convert_plots_proto_to_dict(p, model_name=model_name)
if plots is not None:
plots_list.append(plots)
if not model_locations:
model_location = ''
elif model_name is None:
model_location = list(model_locations.values())[0]
else:
model_location = model_locations[model_name]
return view_types.EvalResult(
slicing_metrics=metrics_list,
plots=plots_list,
config=eval_config,
data_location=data_location,
file_format=file_format,
model_location=model_location)
def default_eval_shared_model(
eval_saved_model_path: Text,
add_metrics_callbacks: Optional[List[types.AddMetricsCallbackType]] = None,
include_default_metrics: Optional[bool] = True,
example_weight_key: Optional[Union[Text, Dict[Text, Text]]] = None,
additional_fetches: Optional[List[Text]] = None,
blacklist_feature_fetches: Optional[List[Text]] = None,
tags: Optional[List[Text]] = None,
model_name: Text = '',
eval_config: Optional[config.EvalConfig] = None,
custom_model_loader: Optional[types.ModelLoader] = None
) -> types.EvalSharedModel:
"""Returns default EvalSharedModel.
Args:
eval_saved_model_path: Path to EvalSavedModel.
add_metrics_callbacks: Optional list of callbacks for adding additional
metrics to the graph (see EvalSharedModel for more information on how to
configure additional metrics). Metrics for example count and example
weights will be added automatically.
include_default_metrics: True to include the default metrics that are part
of the saved model graph during evaluation. Note that
eval_config.options.include_default_metrics must also be true.
example_weight_key: Example weight key (single-output model) or dict of
example weight keys (multi-output model) keyed by output name.
additional_fetches: Prefixes of additional tensors stored in
signature_def.inputs that should be fetched at prediction time. The
"features" and "labels" tensors are handled automatically and should not
be included.
blacklist_feature_fetches: List of tensor names in the features dictionary
which should be excluded from the fetches request. This is useful in
scenarios where features are large (e.g. images) and can lead to excessive
memory use if stored.
tags: Model tags (e.g. 'serve' for serving or 'eval' for EvalSavedModel).
model_name: Optional name of the model being created (should match
ModelSpecs.name). The name should only be provided if multiple models are
being evaluated.
eval_config: Eval config. Only used for setting default tags.
custom_model_loader: Optional custom model loader for non-TF models.
"""
if not eval_config:
model_type = constants.TF_ESTIMATOR
if tags is None:
tags = [eval_constants.EVAL_TAG]
else:
model_spec = model_util.get_model_spec(eval_config, model_name)
if not model_spec:
raise ValueError('ModelSpec for model name {} not found in EvalConfig: '
'config={}'.format(model_name, eval_config))
model_type = model_util.get_model_type(model_spec, eval_saved_model_path,
tags)
if tags is None:
# Default to serving unless estimator is used.
if model_type == constants.TF_ESTIMATOR:
tags = [eval_constants.EVAL_TAG]
else:
tags = [tf.saved_model.SERVING]
# Backwards compatibility for legacy add_metrics_callbacks implementation.
if model_type == constants.TF_ESTIMATOR and eval_constants.EVAL_TAG in tags:
# PyType doesn't know about the magic exports we do in post_export_metrics.
# Additionally, the lines seem to get reordered in compilation, so we can't
# just put the disable-attr on the add_metrics_callbacks lines.
# pytype: disable=module-attr
if not add_metrics_callbacks:
add_metrics_callbacks = []
# Always compute example weight and example count.
example_count_callback = post_export_metrics.example_count()
add_metrics_callbacks.append(example_count_callback)
if example_weight_key:
if isinstance(example_weight_key, dict):
for output_name, key in example_weight_key.items():
example_weight_callback = post_export_metrics.example_weight(
key, metric_tag=output_name)
add_metrics_callbacks.append(example_weight_callback)
else:
example_weight_callback = post_export_metrics.example_weight(
example_weight_key)
add_metrics_callbacks.append(example_weight_callback)
# pytype: enable=module-attr
model_loader = custom_model_loader
if not model_loader and model_type in constants.VALID_TF_MODEL_TYPES:
model_loader = types.ModelLoader(
construct_fn=model_util.model_construct_fn(
eval_saved_model_path=eval_saved_model_path,
add_metrics_callbacks=add_metrics_callbacks,
include_default_metrics=include_default_metrics,
additional_fetches=additional_fetches,
blacklist_feature_fetches=blacklist_feature_fetches,
model_type=model_type,
tags=tags),
tags=tags)
return types.EvalSharedModel(
model_name=model_name,
model_type=model_type,
model_path=eval_saved_model_path,
add_metrics_callbacks=add_metrics_callbacks,
include_default_metrics=include_default_metrics,
example_weight_key=example_weight_key,
additional_fetches=additional_fetches,
model_loader=model_loader)
def default_extractors( # pylint: disable=invalid-name
eval_shared_model: Optional[types.MaybeMultipleEvalSharedModels] = None,
eval_config: config.EvalConfig = None,
slice_spec: Optional[List[slicer.SingleSliceSpec]] = None,
materialize: Optional[bool] = True,
tensor_adapter_config: Optional[tensor_adapter.TensorAdapterConfig] = None,
custom_predict_extractor: Optional[extractor.Extractor] = None
) -> List[extractor.Extractor]:
"""Returns the default extractors for use in ExtractAndEvaluate.
Args:
eval_shared_model: Shared model (single-model evaluation) or list of shared
models (multi-model evaluation). Required unless the predictions are
provided alongside of the features (i.e. model-agnostic evaluations).
eval_config: Eval config.
slice_spec: Deprecated (use EvalConfig).
materialize: True to have extractors create materialized output.
tensor_adapter_config: Tensor adapter config which specifies how to obtain
tensors from the Arrow RecordBatch. If None, we feed the raw examples to
the model.
custom_predict_extractor: Optional custom predict extractor for non-TF
models.
Raises:
NotImplementedError: If eval_config contains mixed serving and eval models.
"""
if slice_spec and eval_config:
raise ValueError('slice_spec is deprecated, only use eval_config')
if eval_config is not None:
eval_config = _update_eval_config_with_defaults(eval_config,
eval_shared_model)
if _is_legacy_eval(eval_shared_model, eval_config):
# Backwards compatibility for previous add_metrics_callbacks implementation.
if not eval_config and slice_spec:
eval_config = config.EvalConfig(
slicing_specs=[s.to_proto() for s in slice_spec])
return [
custom_predict_extractor or predict_extractor.PredictExtractor(
eval_shared_model, materialize=materialize),
slice_key_extractor.SliceKeyExtractor(
eval_config=eval_config, materialize=materialize)
]
elif eval_shared_model:
model_types = _model_types(eval_shared_model)
eval_shared_models = model_util.verify_and_update_eval_shared_models(
eval_shared_model)
if (not model_types.issubset(constants.VALID_TF_MODEL_TYPES) and
not custom_predict_extractor):
raise NotImplementedError(
'either a custom_predict_extractor must be used or model type must '
'be one of: {}. evalconfig={}'.format(
str(constants.VALID_TF_MODEL_TYPES), eval_config))
if model_types == set([constants.TF_LITE]):
# TODO(b/163889779): Convert TFLite extractor to operate on batched
# extracts. Then we can remove the input extractor.
return [
input_extractor.InputExtractor(eval_config=eval_config),
(custom_predict_extractor or
tflite_predict_extractor.TFLitePredictExtractor(
eval_config=eval_config, eval_shared_model=eval_shared_model)),
slice_key_extractor.SliceKeyExtractor(
eval_config=eval_config, materialize=materialize)
]
elif constants.TF_LITE in model_types:
raise NotImplementedError(
'support for mixing tf_lite and non-tf_lite models is not '
'implemented: eval_config={}'.format(eval_config))
if model_types == set([constants.TF_JS]):
return [
input_extractor.InputExtractor(eval_config=eval_config),
(custom_predict_extractor or
tfjs_predict_extractor.TFJSPredictExtractor(
eval_config=eval_config, eval_shared_model=eval_shared_model)),
slice_key_extractor.SliceKeyExtractor(
eval_config=eval_config, materialize=materialize)
]
elif constants.TF_JS in model_types:
raise NotImplementedError(
'support for mixing tf_js and non-tf_js models is not '
'implemented: eval_config={}'.format(eval_config))
elif (eval_config and model_types == set([constants.TF_ESTIMATOR]) and
all(eval_constants.EVAL_TAG in m.model_loader.tags
for m in eval_shared_models)):
return [
custom_predict_extractor or predict_extractor.PredictExtractor(
eval_shared_model,
materialize=materialize,
eval_config=eval_config),
slice_key_extractor.SliceKeyExtractor(
eval_config=eval_config, materialize=materialize)
]
elif (eval_config and constants.TF_ESTIMATOR in model_types and
any(eval_constants.EVAL_TAG in m.model_loader.tags
for m in eval_shared_models)):
raise NotImplementedError(
'support for mixing eval and non-eval estimator models is not '
'implemented: eval_config={}'.format(eval_config))
else:
return [
batched_input_extractor.BatchedInputExtractor(
eval_config=eval_config),
(custom_predict_extractor or
batched_predict_extractor_v2.BatchedPredictExtractor(
eval_config=eval_config,
eval_shared_model=eval_shared_model,
tensor_adapter_config=tensor_adapter_config)),
unbatch_extractor.UnbatchExtractor(),
slice_key_extractor.SliceKeyExtractor(
eval_config=eval_config, materialize=materialize)
]
else:
return [
batched_input_extractor.BatchedInputExtractor(eval_config=eval_config),
unbatch_extractor.UnbatchExtractor(),
slice_key_extractor.SliceKeyExtractor(
eval_config=eval_config, materialize=materialize)
]
def default_evaluators( # pylint: disable=invalid-name
eval_shared_model: Optional[types.MaybeMultipleEvalSharedModels] = None,
eval_config: config.EvalConfig = None,
schema: Optional[schema_pb2.Schema] = None,
compute_confidence_intervals: Optional[bool] = False,
min_slice_size: int = 1,
serialize: bool = False,
random_seed_for_testing: Optional[int] = None) -> List[evaluator.Evaluator]:
"""Returns the default evaluators for use in ExtractAndEvaluate.
Args:
eval_shared_model: Optional shared model (single-model evaluation) or list
of shared models (multi-model evaluation). Only required if there are
metrics to be computed in-graph using the model.
eval_config: Eval config.
schema: A schema to use for customizing default evaluators.
compute_confidence_intervals: Deprecated (use eval_config).
min_slice_size: Deprecated (use eval_config).
serialize: Deprecated.
random_seed_for_testing: Provide for deterministic tests only.
"""
disabled_outputs = []
if eval_config:
eval_config = _update_eval_config_with_defaults(eval_config,
eval_shared_model)
disabled_outputs = eval_config.options.disabled_outputs.values
if (_model_types(eval_shared_model) == set([constants.TF_LITE]) or
_model_types(eval_shared_model) == set([constants.TF_JS])):
# no in-graph metrics present when tflite or tfjs is used.
if eval_shared_model:
if isinstance(eval_shared_model, dict):
eval_shared_model = {
k: v._replace(include_default_metrics=False)
for k, v in eval_shared_model.items()
}
elif isinstance(eval_shared_model, list):
eval_shared_model = [
v._replace(include_default_metrics=False)
for v in eval_shared_model
]
else:
eval_shared_model = eval_shared_model._replace(
include_default_metrics=False)
if (constants.METRICS_KEY in disabled_outputs and
constants.PLOTS_KEY in disabled_outputs):
return []
if _is_legacy_eval(eval_shared_model, eval_config):
# Backwards compatibility for previous add_metrics_callbacks implementation.
if eval_config is not None:
if eval_config.options.HasField('compute_confidence_intervals'):
compute_confidence_intervals = (
eval_config.options.compute_confidence_intervals.value)
if eval_config.options.HasField('min_slice_size'):
min_slice_size = eval_config.options.min_slice_size.value
return [
metrics_and_plots_evaluator.MetricsAndPlotsEvaluator(
eval_shared_model,
compute_confidence_intervals=compute_confidence_intervals,
min_slice_size=min_slice_size,
serialize=serialize,
random_seed_for_testing=random_seed_for_testing)
]
else:
return [
metrics_and_plots_evaluator_v2.MetricsAndPlotsEvaluator(
eval_config=eval_config,
eval_shared_model=eval_shared_model,
schema=schema,
random_seed_for_testing=random_seed_for_testing)
]
def default_writers(
output_path: Optional[Text],
eval_shared_model: Optional[types.MaybeMultipleEvalSharedModels] = None,
eval_config: Optional[config.EvalConfig] = None,
display_only_data_location: Optional[Text] = None,
display_only_data_file_format: Optional[Text] = None,
output_file_format: Text = '',
add_metric_callbacks: List[types.AddMetricsCallbackType] = None
) -> List[writer.Writer]: # pylint: disable=invalid-name
"""Returns the default writers for use in WriteResults.
Note, sharding will be enabled by default if an output_file_format is
provided. Filenames will be <output_path>-SSSSS-of-NNNNN.<output_file_format>
where SSSSS is the shard number and NNNNN is the number of shards.
Args:
output_path: Output path.
eval_shared_model: Optional shared model (single-model evaluation) or list
of shared models (multi-model evaluation). Only required if legacy
add_metrics_callbacks are used.
eval_config: Eval config for writing out config along with results. Also
used for to check for missing slices.
display_only_data_location: Optional path indicating where the examples were
read from. This is used only for display purposes - data will not actually
be read from this path.
display_only_data_file_format: Optional format of the input examples. This
is used only for display purposes.
output_file_format: File format to use when saving files. Currently only
'tfrecord' is supported.
add_metric_callbacks: Optional list of metric callbacks (if used).
"""
writers = []
if not add_metric_callbacks:
add_metric_callbacks = []
# The add_metric_callbacks are used in the metrics and plots serialization
# code to post process the metric data by calling populate_stats_and_pop.
# While both the legacy (V1) and new (V2) evaluation implementations support
# EvalSavedModels using add_metric_callbacks, this particular code is only
# required for the legacy evaluation based on the MetricsAndPlotsEvaluator.
# The V2 MetricsAndPlotsEvaluator output requires no additional processing.
# Since the V1 code only supports a single EvalSharedModel, we only set the
# add_metrics_callbacks if a dict is not passed.
if (eval_shared_model and not isinstance(eval_shared_model, dict) and
not isinstance(eval_shared_model, list)):
add_metric_callbacks = eval_shared_model.add_metrics_callbacks
if eval_config:
model_locations = {}
eval_shared_models = model_util.verify_and_update_eval_shared_models(
eval_shared_model)
for v in (eval_shared_models or [None]):
k = '' if v is None else v.model_name
model_locations[k] = ('<unknown>' if v is None or v.model_path is None
else v.model_path)
writers.append(
eval_config_writer.EvalConfigWriter(
output_path,
eval_config=eval_config,
data_location=display_only_data_location,
data_file_format=display_only_data_file_format,
model_locations=model_locations))
output_paths = {
constants.METRICS_KEY:
os.path.join(output_path, constants.METRICS_KEY),
constants.PLOTS_KEY:
os.path.join(output_path, constants.PLOTS_KEY),
constants.VALIDATIONS_KEY:
os.path.join(output_path, constants.VALIDATIONS_KEY)
}
writers.append(
metrics_plots_and_validations_writer.MetricsPlotsAndValidationsWriter(
output_paths=output_paths,
# Empty EvalConfig supported for backwards compatibility.
eval_config=eval_config or config.EvalConfig(),
add_metrics_callbacks=add_metric_callbacks,
output_file_format=output_file_format))
return writers
@beam.ptransform_fn
# TODO(b/156538355): Find out why str is also required instead of just bytes
# after adding types.Extracts.
@beam.typehints.with_input_types(Union[bytes, str, types.Extracts])
@beam.typehints.with_output_types(types.Extracts)
def InputsToExtracts( # pylint: disable=invalid-name
inputs: beam.pvalue.PCollection) -> beam.pvalue.PCollection:
"""Converts serialized inputs (e.g. examples) to Extracts if not already."""
def to_extracts(x: Union[bytes, str, types.Extracts]) -> types.Extracts:
result = {}
if isinstance(x, dict):
result.update(x)
else:
result[constants.INPUT_KEY] = x
return result
return inputs | 'AddInputKey' >> beam.Map(to_extracts)
@beam.ptransform_fn
@beam.typehints.with_input_types(Union[bytes, pa.RecordBatch])
@beam.typehints.with_output_types(types.Extracts)
def BatchedInputsToExtracts( # pylint: disable=invalid-name
batched_inputs: beam.pvalue.PCollection) -> beam.pvalue.PCollection:
"""Converts Arrow RecordBatch inputs to Extracts."""
def to_extracts(x: Union[bytes, pa.RecordBatch]) -> types.Extracts:
result = {}
if isinstance(x, dict):
result.update(x)
else:
result[constants.ARROW_RECORD_BATCH_KEY] = x
return result
return batched_inputs | 'AddArrowRecordBatchKey' >> beam.Map(to_extracts)
@beam.ptransform_fn
@beam.typehints.with_input_types(types.Extracts)
@beam.typehints.with_output_types(Any)
def ExtractAndEvaluate( # pylint: disable=invalid-name
extracts: beam.pvalue.PCollection, extractors: List[extractor.Extractor],
evaluators: List[evaluator.Evaluator]) -> evaluator.Evaluation:
"""Performs Extractions and Evaluations in provided order."""
# evaluation[k] = list of values for k
evaluation = {}
def update(evaluation: Dict[Text, Any], new_evaluation: Dict[Text, Any]):
for k, v in new_evaluation.items():
if k not in evaluation:
evaluation[k] = []
evaluation[k].append(v)
return evaluation
# Run evaluators that run before extraction (i.e. that only require
# the incoming input extract added by ReadInputs)
for v in evaluators:
if not v.run_after:
update(evaluation, extracts | v.stage_name >> v.ptransform)
for x in extractors:
extracts = (extracts | x.stage_name >> x.ptransform)
for v in evaluators:
if v.run_after == x.stage_name:
update(evaluation, extracts | v.stage_name >> v.ptransform)
for v in evaluators:
if v.run_after == extractor.LAST_EXTRACTOR_STAGE_NAME:
update(evaluation, extracts | v.stage_name >> v.ptransform)
# Merge multi-valued keys if necessary.
result = {}
for k, v in evaluation.items():
if len(v) == 1:
result[k] = v[0]
continue
# Note that we assume that if a key is multivalued, its values are
# dictionaries with disjoint keys. The combined value will simply be the
# disjoint union of all the dictionaries.
result[k] = (
v
| 'FlattenEvaluationOutput(%s)' % k >> beam.Flatten()
| 'CombineEvaluationOutput(%s)' % k >> beam.CombinePerKey(
_CombineEvaluationDictionariesFn()))
return result
class _CombineEvaluationDictionariesFn(beam.CombineFn):
"""CombineFn to combine dictionaries generated by different evaluators."""
def create_accumulator(self) -> Dict[Text, Any]:
return {}
def _merge(self, accumulator: Dict[Text, Any],
output_dict: Dict[Text, Any]) -> None:
intersection = set(accumulator) & set(output_dict)
if intersection:
raise ValueError(
'Dictionaries generated by different evaluators should have '
'different keys, but keys %s appeared in the output of multiple '
'evaluators' % intersection)
accumulator.update(output_dict)
def add_input(self, accumulator: Dict[Text, Any],
output_dict: Dict[Text, Any]) -> Dict[Text, Any]:
if not isinstance(output_dict, dict):
raise TypeError(
'for outputs written to by multiple evaluators, the outputs must all '
'be dictionaries, but got output of type %s, value %s' %
(type(output_dict), str(output_dict)))
self._merge(accumulator, output_dict)
return accumulator
def merge_accumulators(
self, accumulators: List[Dict[Text, Any]]) -> Dict[Text, Any]:
result = self.create_accumulator()
for acc in accumulators:
self._merge(result, acc)
return result
def extract_output(self, accumulator: Dict[Text, Any]) -> Dict[Text, Any]:
return accumulator
@beam.ptransform_fn
# TODO(b/157600974): Add input typehint.
@beam.typehints.with_output_types(beam.pvalue.PDone)
def WriteResults( # pylint: disable=invalid-name
evaluation_or_validation: Union[evaluator.Evaluation, validator.Validation],
writers: List[writer.Writer]) -> beam.pvalue.PDone:
"""Writes Evaluation or Validation results using given writers.
Args:
evaluation_or_validation: Evaluation or Validation output.
writers: Writes to use for writing out output.
Raises:
ValueError: If Evaluation or Validation is empty.
Returns:
beam.pvalue.PDone.
"""
if not evaluation_or_validation:
raise ValueError('Evaluations and Validations cannot be empty')
for w in writers:
_ = evaluation_or_validation | w.stage_name >> w.ptransform
return beam.pvalue.PDone(list(evaluation_or_validation.values())[0].pipeline)
def is_batched_input(eval_shared_model: Optional[
types.MaybeMultipleEvalSharedModels] = None,
eval_config: config.EvalConfig = None) -> bool:
"""Returns true if batched input should be used.
We will keep supporting the legacy unbatched V1 PredictExtractor as it parses
the features and labels, and is the only solution currently that allows for
slicing on transformed features. Eventually we should have support for
transformed features via keras preprocessing layers.
Args:
eval_shared_model: Shared model (single-model evaluation) or list of shared
models (multi-model evaluation). Required unless the predictions are
provided alongside of the features (i.e. model-agnostic evaluations).
eval_config: Eval config.
Returns:
A boolean indicating if batched extractors should be used.
"""
if _is_legacy_eval(eval_shared_model, eval_config):
return False
elif eval_shared_model:
model_types = _model_types(eval_shared_model)
eval_shared_models = model_util.verify_and_update_eval_shared_models(
eval_shared_model)
if (model_types == set([constants.TF_LITE]) or
model_types == set([constants.TF_JS])):
return False
elif (eval_config and model_types == set([constants.TF_ESTIMATOR]) and
all(eval_constants.EVAL_TAG in m.model_loader.tags
for m in eval_shared_models)):
return False
return True
@beam.ptransform_fn
@beam.typehints.with_input_types(Any)
@beam.typehints.with_output_types(beam.pvalue.PDone)
def ExtractEvaluateAndWriteResults( # pylint: disable=invalid-name
examples: beam.pvalue.PCollection,
eval_shared_model: Optional[types.MaybeMultipleEvalSharedModels] = None,
eval_config: config.EvalConfig = None,
extractors: Optional[List[extractor.Extractor]] = None,
evaluators: Optional[List[evaluator.Evaluator]] = None,
writers: Optional[List[writer.Writer]] = None,
output_path: Optional[Text] = None,
display_only_data_location: Optional[Text] = None,
display_only_file_format: Optional[Text] = None,
slice_spec: Optional[List[slicer.SingleSliceSpec]] = None,
write_config: Optional[bool] = True,
compute_confidence_intervals: Optional[bool] = False,
min_slice_size: int = 1,
random_seed_for_testing: Optional[int] = None,
tensor_adapter_config: Optional[tensor_adapter.TensorAdapterConfig] = None,
schema: Optional[schema_pb2.Schema] = None) -> beam.pvalue.PDone:
"""PTransform for performing extraction, evaluation, and writing results.
Users who want to construct their own Beam pipelines instead of using the
lightweight run_model_analysis functions should use this PTransform.
Example usage:
```python
eval_config = tfma.EvalConfig(slicing_specs=[...], metrics_specs=[...])
eval_shared_model = tfma.default_eval_shared_model(
eval_saved_model_path=model_location, eval_config=eval_config)
with beam.Pipeline(runner=...) as p:
_ = (p
| 'ReadData' >> beam.io.ReadFromTFRecord(data_location)
| 'ExtractEvaluateAndWriteResults' >>
tfma.ExtractEvaluateAndWriteResults(
eval_shared_model=eval_shared_model,
eval_config=eval_config,
...))
result = tfma.load_eval_result(output_path=output_path)
tfma.view.render_slicing_metrics(result)
```
Note that the exact serialization format is an internal implementation detail
and subject to change. Users should only use the TFMA functions to write and
read the results.
Args:
examples: PCollection of input examples or Arrow Record batches. Examples
can be any format the model accepts (e.g. string containing CSV row,
TensorFlow.Example, etc). If the examples are in the form of a dict it
will be assumed that input is already in the form of tfma.Extracts with
examples stored under tfma.INPUT_KEY (any other keys will be passed along
unchanged to downstream extractors and evaluators).
eval_shared_model: Optional shared model (single-model evaluation) or list
of shared models (multi-model evaluation). Only required if needed by
default extractors, evaluators, or writers and for display purposes of the
model path.
eval_config: Eval config.
extractors: Optional list of Extractors to apply to Extracts. Typically
these will be added by calling the default_extractors function. If no
extractors are provided, default_extractors (non-materialized) will be
used.
evaluators: Optional list of Evaluators for evaluating Extracts. Typically
these will be added by calling the default_evaluators function. If no
evaluators are provided, default_evaluators will be used.
writers: Optional list of Writers for writing Evaluation output. Typically
these will be added by calling the default_writers function. If no writers
are provided, default_writers will be used.
output_path: Path to output results to (config file, metrics, plots, etc).
display_only_data_location: Optional path indicating where the examples were
read from. This is used only for display purposes - data will not actually
be read from this path.
display_only_file_format: Optional format of the examples. This is used only
for display purposes.
slice_spec: Deprecated (use EvalConfig).
write_config: Deprecated (use EvalConfig).
compute_confidence_intervals: Deprecated (use EvalConfig).
min_slice_size: Deprecated (use EvalConfig).
random_seed_for_testing: Provide for deterministic tests only.
tensor_adapter_config: Tensor adapter config which specifies how to obtain
tensors from the Arrow RecordBatch. If None, we feed the raw examples to
the model.
schema: A schema to use for customizing evaluators.
Raises:
ValueError: If EvalConfig invalid or matching Extractor not found for an
Evaluator.
Returns:
PDone.
"""
eval_shared_models = model_util.verify_and_update_eval_shared_models(
eval_shared_model)
if eval_config is None:
eval_config = _default_eval_config(eval_shared_models, slice_spec,
write_config,
compute_confidence_intervals,
min_slice_size)
else:
eval_config = _update_eval_config_with_defaults(eval_config,
eval_shared_model)
config.verify_eval_config(eval_config)
if not extractors:
extractors = default_extractors(
eval_config=eval_config,
eval_shared_model=eval_shared_model,
materialize=False,
tensor_adapter_config=tensor_adapter_config)
if not evaluators:
evaluators = default_evaluators(
eval_config=eval_config,
eval_shared_model=eval_shared_model,
random_seed_for_testing=random_seed_for_testing,
schema=schema)
for v in evaluators:
evaluator.verify_evaluator(v, extractors)
if not writers:
writers = default_writers(
output_path=output_path,
eval_shared_model=eval_shared_model,
eval_config=eval_config,
display_only_data_location=display_only_data_location,
display_only_data_file_format=display_only_file_format)
# pylint: disable=no-value-for-parameter
if is_batched_input(eval_shared_model, eval_config):
extracts = (
examples
| 'BatchedInputsToExtracts' >> BatchedInputsToExtracts())
else:
extracts = (examples | 'InputsToExtracts' >> InputsToExtracts())
_ = (
extracts
| 'ExtractAndEvaluate' >> ExtractAndEvaluate(
extractors=extractors, evaluators=evaluators)
| 'WriteResults' >> WriteResults(writers=writers))
return beam.pvalue.PDone(examples.pipeline)
def run_model_analysis(
eval_shared_model: Optional[types.MaybeMultipleEvalSharedModels] = None,
eval_config: config.EvalConfig = None,
data_location: Text = '',
file_format: Text = 'tfrecords',
output_path: Optional[Text] = None,
extractors: Optional[List[extractor.Extractor]] = None,
evaluators: Optional[List[evaluator.Evaluator]] = None,
writers: Optional[List[writer.Writer]] = None,
pipeline_options: Optional[Any] = None,
slice_spec: Optional[List[slicer.SingleSliceSpec]] = None,
write_config: Optional[bool] = True,
compute_confidence_intervals: Optional[bool] = False,
min_slice_size: int = 1,
random_seed_for_testing: Optional[int] = None,
schema: Optional[schema_pb2.Schema] = None,
) -> Union[view_types.EvalResult, view_types.EvalResults]:
"""Runs TensorFlow model analysis.
It runs a Beam pipeline to compute the slicing metrics exported in TensorFlow
Eval SavedModel and returns the results.
This is a simplified API for users who want to quickly get something running
locally. Users who wish to create their own Beam pipelines can use the
Evaluate PTransform instead.
Args:
eval_shared_model: Optional shared model (single-model evaluation) or list
of shared models (multi-model evaluation). Only required if needed by
default extractors, evaluators, or writers.
eval_config: Eval config.
data_location: The location of the data files.
file_format: The file format of the data, can be either 'text' or
'tfrecords' for now. By default, 'tfrecords' will be used.
output_path: The directory to output metrics and results to. If None, we use
a temporary directory.
extractors: Optional list of Extractors to apply to Extracts. Typically
these will be added by calling the default_extractors function. If no
extractors are provided, default_extractors (non-materialized) will be
used.
evaluators: Optional list of Evaluators for evaluating Extracts. Typically
these will be added by calling the default_evaluators function. If no
evaluators are provided, default_evaluators will be used.
writers: Optional list of Writers for writing Evaluation output. Typically
these will be added by calling the default_writers function. If no writers
are provided, default_writers will be used.
pipeline_options: Optional arguments to run the Pipeline, for instance
whether to run directly.
slice_spec: Deprecated (use EvalConfig).
write_config: Deprecated (use EvalConfig).
compute_confidence_intervals: Deprecated (use EvalConfig).
min_slice_size: Deprecated (use EvalConfig).
random_seed_for_testing: Provide for deterministic tests only.
schema: Optional tf.Metadata schema of the input data.
Returns:
An EvalResult that can be used with the TFMA visualization functions.
Raises:
ValueError: If the file_format is unknown to us.
"""
_assert_tensorflow_version()
if output_path is None:
output_path = tempfile.mkdtemp()
if not tf.io.gfile.exists(output_path):
tf.io.gfile.makedirs(output_path)
if eval_config is None:
eval_shared_models = model_util.verify_and_update_eval_shared_models(
eval_shared_model)
eval_config = _default_eval_config(eval_shared_models, slice_spec,
write_config,
compute_confidence_intervals,
min_slice_size)
else:
eval_config = _update_eval_config_with_defaults(eval_config,
eval_shared_model)
tensor_adapter_config = None
with beam.Pipeline(options=pipeline_options) as p:
if file_format == 'tfrecords':
if is_batched_input(eval_shared_model, eval_config):
tfxio = tf_example_record.TFExampleRecord(
file_pattern=data_location,
schema=schema,
raw_record_column_name=constants.ARROW_INPUT_COLUMN)
if schema is not None:
tensor_adapter_config = tensor_adapter.TensorAdapterConfig(
arrow_schema=tfxio.ArrowSchema(),
tensor_representations=tfxio.TensorRepresentations())
data = p | 'ReadFromTFRecordToArrow' >> tfxio.BeamSource()
else:
data = p | 'ReadFromTFRecord' >> beam.io.ReadFromTFRecord(
file_pattern=data_location,
compression_type=beam.io.filesystem.CompressionTypes.AUTO)
elif file_format == 'text':
data = p | 'ReadFromText' >> beam.io.textio.ReadFromText(data_location)
else:
raise ValueError('unknown file_format: {}'.format(file_format))
# pylint: disable=no-value-for-parameter
_ = (
data
| 'ExtractEvaluateAndWriteResults' >> ExtractEvaluateAndWriteResults(
eval_config=eval_config,
eval_shared_model=eval_shared_model,
display_only_data_location=data_location,
display_only_file_format=file_format,
output_path=output_path,
extractors=extractors,
evaluators=evaluators,
writers=writers,
random_seed_for_testing=random_seed_for_testing,
tensor_adapter_config=tensor_adapter_config,
schema=schema))
# pylint: enable=no-value-for-parameter
if len(eval_config.model_specs) <= 1:
return load_eval_result(output_path)
else:
results = []
for spec in eval_config.model_specs:
results.append(load_eval_result(output_path, model_name=spec.name))
return view_types.EvalResults(results, constants.MODEL_CENTRIC_MODE)
def single_model_analysis(
model_location: Text,
data_location: Text,
output_path: Text = None,
eval_config: Optional[config.EvalConfig] = None,
slice_spec: Optional[List[slicer.SingleSliceSpec]] = None
) -> view_types.EvalResult:
"""Run model analysis for a single model on a single data set.
This is a convenience wrapper around run_model_analysis for a single model
with a single data set. For more complex use cases, use
tfma.run_model_analysis.
Args:
model_location: Path to the export eval saved model.
data_location: The location of the data files.
output_path: The directory to output metrics and results to. If None, we use
a temporary directory.
eval_config: Eval config.
slice_spec: Deprecated (use EvalConfig).
Returns:
An EvalResult that can be used with the TFMA visualization functions.
"""
# Get working_dir ready.
if output_path is None:
output_path = tempfile.mkdtemp()
if not tf.io.gfile.exists(output_path):
tf.io.gfile.makedirs(output_path)
if slice_spec and eval_config:
raise ValueError('slice_spec is deprecated, only use eval_config')
if slice_spec:
eval_config = config.EvalConfig(
slicing_specs=[s.to_proto() for s in slice_spec])
return run_model_analysis(
eval_config=eval_config,
eval_shared_model=default_eval_shared_model(
eval_saved_model_path=model_location),
data_location=data_location,
output_path=output_path) # pytype: disable=bad-return-type
def multiple_model_analysis(model_locations: List[Text], data_location: Text,
**kwargs) -> view_types.EvalResults:
"""Run model analysis for multiple models on the same data set.
Args:
model_locations: A list of paths to the export eval saved model.
data_location: The location of the data files.
**kwargs: The args used for evaluation. See tfma.single_model_analysis() for
details.
Returns:
A tfma.EvalResults containing all the evaluation results with the same order
as model_locations.
"""
results = []
for m in model_locations:
results.append(single_model_analysis(m, data_location, **kwargs))
return view_types.EvalResults(results, constants.MODEL_CENTRIC_MODE)
def multiple_data_analysis(model_location: Text, data_locations: List[Text],
**kwargs) -> view_types.EvalResults:
"""Run model analysis for a single model on multiple data sets.
Args:
model_location: The location of the exported eval saved model.
data_locations: A list of data set locations.
**kwargs: The args used for evaluation. See tfma.run_model_analysis() for
details.
Returns:
A tfma.EvalResults containing all the evaluation results with the same order
as data_locations.
"""
results = []
for d in data_locations:
results.append(single_model_analysis(model_location, d, **kwargs))
return view_types.EvalResults(results, constants.DATA_CENTRIC_MODE)
def analyze_raw_data(
data: pd.DataFrame,
eval_config: config.EvalConfig = None,
output_path: Optional[Text] = None,
add_metric_callbacks: List[types.AddMetricsCallbackType] = None
) -> view_types.EvalResult:
"""Runs TensorFlow model analysis on a pandas.DataFrame.
This function allows you to use TFMA with Pandas DataFrames. The dataframe
must include a 'predicted' column for the predicted label and a 'label' column
for the actual label.
In addition to a DataFrame, this function requires an eval_config, a
`tfma.EvalConfig` object containing various configuration parameters (see
[config.proto](https://github.com/tensorflow/model-analysis/blob/master/tensorflow_model_analysis/proto/config.proto)
for a comprehensive list)...
* the metrics to compute
* the slices to compute metrics on
* the DataFrame's column names for example labels and predictions ('label'
and 'prediction' by default)
* confidence interval options
This function returns a `tfma.EvalResult`, which contains TFMA's computed
metrics and can be used to generate plots with
`tfma.view.render_slicing_metrics`.
Example usage:
```python
model_specs = [
config.ModelSpec(
prediction_key='prediction',
label_key='label')
]
config.options.compute_confidence_intervals.value
metrics_specs = [
config.MetricsSpec(metrics=[
config.MetricConfig(class_name='Accuracy'),
config.MetricConfig(class_name='ExampleCount')
])
]
slicing_specs = [
config.SlicingSpec(), # the empty slice represents the overall dataset
config.SlicingSpec(feature_keys=['language'])
]
eval_config = config.EvalConfig(
model_specs=model_specs,
metrics_specs=metrics_specs,
slicing_specs=slicing_specs)
result = model_eval_lib.analyze_raw_data(df, eval_config)
tfma.view.render_slicing_metrics(result)
# Example with Fairness Indicators
from tensorflow_model_analysis.addons.fairness.post_export_metrics import
fairness_indicators
from tensorflow_model_analysis.addons.fairness.view import widget_view
add_metrics_callbacks = [
tfma.post_export_metrics.fairness_indicators(thresholds=[0.25, 0.5, 0.75])
]
result = model_eval_lib.analyze_raw_data(
data=df,
metrics_specs=metrics_specs,
slicing_specs=slicing_specs,
add_metric_callbacks=add_metrics_callbacks
)
widget_view.render_fairness_indicator(result)
```
Args:
data: A pandas.DataFrame, where rows correspond to examples and columns
correspond to features. One column must indicate a row's predicted label,
and one column must indicate a row's actual label.
eval_config: A `tfma.EvalConfig`, which contains various configuration
parameters including metrics, slices, and label/prediction column names.
output_path: Path to write EvalResult to.
add_metric_callbacks: Optional list of metric callbacks (if used).
Returns:
A tfma.EvalResult to extract metrics or generate visualizations from.
Raises:
KeyError: If the prediction or label columns are not found within the
DataFrame.
"""
for model_spec in eval_config.model_specs:
model_spec.prediction_key = model_spec.prediction_key or 'prediction'
model_spec.label_key = model_spec.label_key or 'label'
if model_spec.prediction_key not in data.columns:
raise KeyError(
'The prediction_key column was not found. Looked for %s but found: %s'
% (model_spec.prediction_key, list(data.columns)))
if model_spec.label_key not in data.columns:
raise KeyError(
'The label_key column was not found. Looked for %s but found: %s' %
(model_spec.label_key, list(data.columns)))
# TODO(b/153570803): Validity check / assertions for dataframe structure
if eval_config.slicing_specs is None:
eval_config.slicing_specs = [config.SlicingSpec(feature_keys=[''])]
if output_path is None:
output_path = tempfile.mkdtemp()
arrow_data = table_util.CanonicalizeRecordBatch(
table_util.DataFrameToRecordBatch(data))
beam_data = beam.Create([arrow_data])
writers = default_writers(
output_path,
eval_config=eval_config,
add_metric_callbacks=add_metric_callbacks)
with beam.Pipeline() as p:
_ = (
p
| beam_data
| 'ExtractEvaluateAndWriteResults' >> ExtractEvaluateAndWriteResults( # pylint: disable=no-value-for-parameter
writers=writers,
eval_config=eval_config,
output_path=output_path))
return load_eval_result(output_path)
|
the-stack_0_14808 | """
Utilities for general use
"""
import pandas as pd
import random
def cartesianproduct(*args):
"""Create full cartesian product of all objects passed"""
# Create a random string to name a new random column for merging
key_col = randomstring(16)
out = pd.DataFrame(args[0].drop_duplicates())
out[key_col] = 1
for itm in args[1:]:
itm = pd.DataFrame(itm.drop_duplicates())
itm[key_col] = 1
out = out.merge(itm, on=key_col)
out.drop(columns=key_col, inplace=True)
return out
|
the-stack_0_14809 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from bincrafters import build_template_default
import os
import platform
if __name__ == "__main__":
CONAN_USERNAME = os.environ.get("CONAN_USERNAME", "yjjnls")
CONAN_UPLOAD = 'https://api.bintray.com/conan/%s/%s' % (CONAN_USERNAME,
'stable')
os.environ['CONAN_UPLOAD'] = CONAN_UPLOAD
os.environ['CONAN_CHANNEL'] = 'stable'
os.environ['CONAN_UPLOAD_ONLY_WHEN_STABLE'] = 'False'
os.environ['CONAN_USERNAME'] = CONAN_USERNAME
DEPENDENT_BINTRAY_REPO = os.environ.get(
"DEPENDENT_BINTRAY_REPO", CONAN_USERNAME)
os.environ['DEPENDENT_BINTRAY_REPO'] = DEPENDENT_BINTRAY_REPO
builder = build_template_default.get_builder()
builds = []
for settings, options, env_vars, build_requires, reference in builder.items:
# dynamic only
if not options["gstreamer-custom:shared"]:
continue
# release only
if settings["build_type"] == "Debug":
continue
# Visual Sutido 2017 only
if platform.system() == "Windows":
if settings["compiler"] == "Visual Studio":
if settings["compiler.version"] == '14':
builds.append(
[settings, options, env_vars, build_requires])
elif platform.system() == "Linux":
if settings["compiler"] == "gcc":
if settings["compiler.version"] == '4.9' and settings["arch"] == 'x86_64':
builds.append(
[settings, options,
{'DEPENDENT_BINTRAY_REPO':
DEPENDENT_BINTRAY_REPO},
build_requires])
builder.builds = builds
builder.run()
|
the-stack_0_14810 | conv_encoder = km.Sequential(name="ConvEncoderModel")
conv_encoder.add(kl.Conv2D(16, (3,3) , activation='relu', input_shape=(28,28,1) , padding='same' ))
conv_encoder.add(kl.MaxPooling2D((2, 2), padding='same'))
conv_encoder.add(kl.Conv2D(8, (3, 3), activation='relu', padding='same'))
conv_encoder.add(kl.MaxPooling2D((2, 2), padding='same'))
conv_encoder.add(kl.Conv2D(8, (3, 3), activation='relu', padding='same'))
conv_encoder.add(kl. MaxPooling2D((2, 2), padding='same'))
conv_decoder = km.Sequential(name="ConvDecoderModel")
conv_decoder.add(kl.Conv2D(8, (3, 3), activation='relu', input_shape = (4, 4, 8), padding='same'))
conv_decoder.add(kl.UpSampling2D((2, 2)))
conv_decoder.add(kl.Conv2D(8, (3, 3), activation='relu', padding='same'))
conv_decoder.add(kl.UpSampling2D((2, 2)))
conv_decoder.add(kl.Conv2D(16, (3, 3), activation='relu'))
conv_decoder.add(kl.UpSampling2D((2, 2)))
conv_decoder.add(kl.Conv2D(1, (3, 3), activation='sigmoid', padding='same'))
conv_autoencoder = km.Sequential(name="ConvAutoencoderModel")
conv_autoencoder.add(conv_encoder)
conv_autoencoder.add(conv_decoder)
conv_autoencoder.compile(optimizer='adam', loss='binary_crossentropy')
conv_autoencoder.fit(x_train_noisy, x_train_conv, epochs=10, batch_size=256, validation_data=(x_test_noisy, x_test_conv)) |
the-stack_0_14811 | import bluetooth
bd_addr = "98:D3:31:F5:B9:E6"
port = 1
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.connect((bd_addr,port))
while 1:
a = sock.recv(1)
print(a)
sock.close()
|
the-stack_0_14812 | from nltk.stem.wordnet import WordNetLemmatizer
from SentimentAnalysis.common_functions import preprocess_one_line, remove_duplicates
lemmatizer = WordNetLemmatizer()
lemmatize_flag = True
pos_raw_file = open('/home/data/positive-words-raw.txt', 'r')
neg_raw_file = open('/home/data/negative-words-raw.txt', 'r')
pos_file = open('/home/data/positive-words.txt', 'w')
neg_file = open('/home/data/negative-words.txt', 'w')
positives_raw = pos_raw_file.readlines()
negatives_raw = neg_raw_file.readlines()
positives = []
for pos_line in positives_raw:
new_pos_line = preprocess_one_line(pos_line, lemmatizer, lemmatize_flag, []) # last arg is stopwords -- there are none by definition
positives.append(new_pos_line)
positives = remove_duplicates(positives)
negatives = []
for neg_line in negatives_raw:
new_neg_line = preprocess_one_line(neg_line, lemmatizer, lemmatize_flag, [])
negatives.append(new_neg_line)
negatives = remove_duplicates(negatives)
for word in negatives:
neg_file.write(word+'\n')
neg_file.close()
for word in positives:
pos_file.write(word+'\n')
pos_file.close()
|
the-stack_0_14814 | #!/usr/bin/env python3
#
# Copyright (c) 2021 Nordic Semiconductor ASA
#
# SPDX-License-Identifier: Apache-2.0
#
from unittest import TestCase, main
from subprocess import Popen, PIPE
from re import sub
from pathlib import Path
from pprint import pprint
# from ecdsa import VerifyingKey
from hashlib import sha256
import cbor2
try:
import cddl_gen
except ImportError:
print("""
The cddl_gen package must be installed to run these tests.
During development, install with `python3 setup.py develop` to install in a way
that picks up changes in the files without having to reinstall.
""")
import sys
sys.exit(1)
p_root = Path(__file__).absolute().parents[2]
p_tests = Path(p_root, 'tests')
p_manifest12 = Path(p_tests, 'cases', 'manifest12.cddl')
p_manifest14 = Path(p_tests, 'cases', 'manifest14.cddl')
p_test_vectors12 = tuple(Path(p_tests, 'cases', f'manifest12_example{i}.cborhex') for i in range(6))
p_test_vectors14 = tuple(Path(p_tests, 'cases', f'manifest14_example{i}.cborhex') for i in range(6))
p_optional = Path(p_tests, 'cases', 'optional.cddl')
p_cose = Path(p_tests, 'cases', 'cose.cddl')
p_manifest14_priv = Path(p_tests, 'cases', 'manifest14.priv')
p_manifest14_pub = Path(p_tests, 'cases', 'manifest14.pub')
class Testn(TestCase):
def decode_file(self, data_path, *cddl_paths):
data = bytes.fromhex(data_path.read_text().replace("\n", ""))
self.decode_string(data, *cddl_paths)
def decode_string(self, data_string, *cddl_paths):
cddl_str = " ".join((Path(p).read_text() for p in cddl_paths))
self.my_types = cddl_gen.DataTranslator.from_cddl(cddl_str, 16).my_types
cddl = self.my_types["SUIT_Envelope_Tagged"]
self.decoded = cddl.decode_str(data_string)
class Test0(Testn):
def __init__(self, *args, **kwargs):
super(Test0, self).__init__(*args, **kwargs)
self.decode_file(p_test_vectors12[0], p_manifest12)
def test_manifest_digest(self):
self.assertEqual(
bytes.fromhex("5c097ef64bf3bb9b494e71e1f2418eef8d466cc902f639a855ec9af3e9eddb99"),
self.decoded.suit_authentication_wrapper.SUIT_Digest_bstr.suit_digest_bytes)
def test_signature(self):
self.assertEqual(
1,
self.decoded.suit_authentication_wrapper.SUIT_Authentication_Block_bstr[0].COSE_Sign1_Tagged.protected.uintint[0].uintint_key)
self.assertEqual(
-7,
self.decoded.suit_authentication_wrapper.SUIT_Authentication_Block_bstr[0].COSE_Sign1_Tagged.protected.uintint[0].uintint)
self.assertEqual(
bytes.fromhex("a19fd1f23b17beed321cece7423dfb48c457b8f1f6ac83577a3c10c6773f6f3a7902376b59540920b6c5f57bac5fc8543d8f5d3d974faa2e6d03daa534b443a7"),
self.decoded.suit_authentication_wrapper.SUIT_Authentication_Block_bstr[0].COSE_Sign1_Tagged.signature)
def test_validate_run(self):
self.assertEqual(
"suit_condition_image_match",
self.decoded.suit_manifest.SUIT_Unseverable_Members.suit_validate[0].suit_validate.union[0].SUIT_Condition.union_choice)
self.assertEqual(
"suit_directive_run",
self.decoded.suit_manifest.SUIT_Unseverable_Members.suit_run[0].suit_run.union[0].SUIT_Directive.union_choice)
def test_image_size(self):
self.assertEqual(34768, self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union[0].SUIT_Common_Commands.suit_directive_override_parameters.map[3].suit_parameter_image_size)
class Test1(Testn):
def __init__(self, *args, **kwargs):
super(Test1, self).__init__(*args, **kwargs)
self.decode_file(p_test_vectors12[1], p_manifest12)
def test_components(self):
self.assertEqual(
[b'\x00'],
self.decoded.suit_manifest.suit_common.suit_components[0][0].bstr)
def test_uri(self):
self.assertEqual(
"http://example.com/file.bin",
self.decoded.suit_manifest.SUIT_Severable_Manifest_Members.suit_install[0].suit_install.union[0].SUIT_Directive.suit_directive_set_parameters.map[0].suit_parameter_uri)
class Test2(Testn):
def __init__(self, *args, **kwargs):
super(Test2, self).__init__(*args, **kwargs)
self.decode_file(p_test_vectors12[2], p_manifest12)
def test_severed_uri(self):
self.assertEqual(
"http://example.com/very/long/path/to/file/file.bin",
self.decoded.SUIT_Severable_Manifest_Members.suit_install[0].suit_install.union[0].SUIT_Directive.suit_directive_set_parameters.map[0].suit_parameter_uri)
def test_severed_text(self):
self.assertIn(
"Example 2",
self.decoded.SUIT_Severable_Manifest_Members.suit_text[0].suit_text.SUIT_Text_Keys.suit_text_manifest_description[0])
self.assertEqual(
[b'\x00'],
self.decoded.SUIT_Severable_Manifest_Members.suit_text[0].suit_text.SUIT_Component_Identifier[0].SUIT_Component_Identifier_key.bstr)
self.assertEqual(
"arm.com",
self.decoded.SUIT_Severable_Manifest_Members.suit_text[0].suit_text.SUIT_Component_Identifier[0].SUIT_Component_Identifier.SUIT_Text_Component_Keys.suit_text_vendor_domain[0])
self.assertEqual(
"This component is a demonstration. The digest is a sample pattern, not a real one.",
self.decoded.SUIT_Severable_Manifest_Members.suit_text[0].suit_text.SUIT_Component_Identifier[0].SUIT_Component_Identifier.SUIT_Text_Component_Keys.suit_text_component_description[0])
class Test3(Testn):
def __init__(self, *args, **kwargs):
super(Test3, self).__init__(*args, **kwargs)
self.decode_file(p_test_vectors12[3], p_manifest12)
def test_A_B_offset(self):
self.assertEqual(
33792,
self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union[1].SUIT_Common_Commands.suit_directive_try_each.SUIT_Directive_Try_Each_Argument.SUIT_Command_Sequence_bstr[0].union[0].SUIT_Directive.suit_directive_override_parameters.map[0].suit_parameter_component_offset)
self.assertEqual(
541696,
self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union[1].SUIT_Common_Commands.suit_directive_try_each.SUIT_Directive_Try_Each_Argument.SUIT_Command_Sequence_bstr[1].union[0].SUIT_Directive.suit_directive_override_parameters.map[0].suit_parameter_component_offset)
class Test4(Testn):
def __init__(self, *args, **kwargs):
super(Test4, self).__init__(*args, **kwargs)
self.decode_file(p_test_vectors12[4], p_manifest12)
def test_load_decompress(self):
self.assertEqual(
0,
self.decoded.suit_manifest.SUIT_Unseverable_Members.suit_load[0].suit_load.union[1].SUIT_Directive.suit_directive_set_parameters.map[3].suit_parameter_source_component)
self.assertEqual(
"SUIT_Compression_Algorithm_zlib",
self.decoded.suit_manifest.SUIT_Unseverable_Members.suit_load[0].suit_load.union[1].SUIT_Directive.suit_directive_set_parameters.map[2].suit_parameter_compression_info.suit_compression_algorithm)
class Test5(Testn):
def __init__(self, *args, **kwargs):
super(Test5, self).__init__(*args, **kwargs)
self.decode_file(p_test_vectors12[5], p_manifest12)
def test_two_image_match(self):
self.assertEqual(
"suit_condition_image_match",
self.decoded.suit_manifest.SUIT_Severable_Manifest_Members.suit_install[0].suit_install.union[3].SUIT_Condition.union_choice)
self.assertEqual(
"suit_condition_image_match",
self.decoded.suit_manifest.SUIT_Severable_Manifest_Members.suit_install[0].suit_install.union[7].SUIT_Condition.union_choice)
def dumps(obj):
return cbor2.dumps(obj, canonical=True)
def loads(string):
return cbor2.loads(string)
class Test6(Testn):
def __init__(self, *args, **kwargs):
super(Test6, self).__init__(*args, **kwargs)
self.decode_file(p_test_vectors14[0], p_manifest14, p_cose)
def test_authentication(self):
digest = bytes.fromhex("a6c4590ac53043a98e8c4106e1e31b305516d7cf0a655eddfac6d45c810e036a")
signature = bytes.fromhex("d11a2dd9610fb62a707335f584079225709f96e8117e7eeed98a2f207d05c8ecfba1755208f6abea977b8a6efe3bc2ca3215e1193be201467d052b42db6b7287")
sig_struct = bytes.fromhex("846a5369676e61747572653143a10126405820a6c4590ac53043a98e8c4106e1e31b305516d7cf0a655eddfac6d45c810e036a")
# key = VerifyingKey.from_pem(p_manifest14_pub.read_text())
# key.verify_digest(signature, digest)
# key.verify(signature, digest, hashfunc=sha256)
# key.verify(signature, sig_struct, hashfunc=sha256)
self.assertEqual("COSE_Sign1_Tagged", self.decoded.suit_authentication_wrapper.SUIT_Authentication_Block_bstr[0].union_choice)
self.assertEqual(-7, self.decoded.suit_authentication_wrapper.SUIT_Authentication_Block_bstr[0].COSE_Sign1_Tagged.Headers.protected.header_map_bstr.Generic_Headers.uint1union[0].int)
manifest_signature = self.decoded.suit_authentication_wrapper.SUIT_Authentication_Block_bstr[0].COSE_Sign1_Tagged.signature
sig_struct = ["Signature", self.decoded.suit_authentication_wrapper.SUIT_Authentication_Block_bstr[0].COSE_Sign1_Tagged.Headers.protected.header_map_bstr_bstr, b'', b'', b'']
sig_struct_encoded = dumps(sig_struct)
# self.assertEqual(dumps(self.decoded.suit_manifest.orig_obj), self.decoded.orig_obj[3])
manifest_str = dumps(self.decoded.suit_manifest_bstr)
# manifest_hash = sha256(manifest_str).digest()
manifest_hash = dumps(sha256(manifest_str).digest())
manifest_suit_digest = self.decoded.suit_authentication_wrapper.SUIT_Digest_bstr_bstr
# manifest_suit_digest = dumps(dumps(self.decoded.suit_authentication_wrapper.SUIT_Digest_bstr.orig_obj))
sig_struct_encoded = sig_struct_encoded[:-1] + manifest_hash
# sig_struct_encoded = sig_struct_encoded[:-1] + dumps(manifest_hash)
# sig_struct_encoded = sig_struct_encoded[:-1] + dumps(manifest_suit_digest)
# sig_struct_encoded = sig_struct_encoded[:-1] + dumps(dumps(manifest_suit_digest))
# res = self.my_types["Sig_structure"].validate_str(sig_struct_encoded)
# print (sig_struct_encoded.hex())
loaded = loads(sig_struct_encoded)
# key = VerifyingKey.from_pem(p_manifest14_pub.read_text())
# print(sig_struct_encoded.hex())
# print(key.to_string().hex())
# print(manifest_signature.hex())
# res = key.verify(manifest_signature, dumps(self.decoded.orig_obj[3]), hashfunc=sha256)
# res = key.verify_digest(manifest_signature, manifest_hash)
# res = key.verify(manifest_signature, manifest_hash, hashfunc=sha256)
# res = key.verify(manifest_signature, dumps(manifest_hash), hashfunc=sha256)
# res = key.verify(manifest_signature, manifest_suit_digest, hashfunc=sha256)
# res = key.verify(manifest_signature, dumps(manifest_suit_digest), hashfunc=sha256)
# res = key.verify(manifest_signature, dumps(sig_struct_encoded), hashfunc=sha256)
# res = key.verify(manifest_signature, sig_struct_encoded, hashfunc=sha256)
# print(res)
class Test7(Testn):
def __init__(self, *args, **kwargs):
super(Test7, self).__init__(*args, **kwargs)
self.decode_file(p_test_vectors14[1], p_manifest14, p_cose)
def test_structure(self):
self.assertEqual("COSE_Sign1_Tagged", self.decoded.suit_authentication_wrapper.SUIT_Authentication_Block_bstr[0].union_choice)
self.assertEqual(-7, self.decoded.suit_authentication_wrapper.SUIT_Authentication_Block_bstr[0].COSE_Sign1_Tagged.Headers.protected.header_map_bstr.Generic_Headers.uint1union[0].int)
self.assertEqual(bytes.fromhex("60c61d6eb7a1aaeddc49ce8157a55cff0821537eeee77a4ded44155b03045132"), self.decoded.suit_authentication_wrapper.SUIT_Digest_bstr.suit_digest_bytes)
self.assertEqual(1, self.decoded.suit_manifest.suit_manifest_sequence_number)
self.assertEqual(bytes.fromhex("fa6b4a53d5ad5fdfbe9de663e4d41ffe"), self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union[0].SUIT_Common_Commands.suit_directive_override_parameters.map[0].suit_parameter_vendor_identifier.RFC4122_UUID)
self.assertEqual(bytes.fromhex("1492af1425695e48bf429b2d51f2ab45"), self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union[0].SUIT_Common_Commands.suit_directive_override_parameters.map[1].suit_parameter_class_identifier)
self.assertEqual(bytes.fromhex("00112233445566778899aabbccddeeff0123456789abcdeffedcba9876543210"), self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union[0].SUIT_Common_Commands.suit_directive_override_parameters.map[2].suit_parameter_image_digest.suit_digest_bytes)
self.assertEqual('cose_alg_sha_256', self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union[0].SUIT_Common_Commands.suit_directive_override_parameters.map[2].suit_parameter_image_digest.suit_digest_algorithm_id.union_choice)
self.assertEqual(34768, self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union[0].SUIT_Common_Commands.suit_directive_override_parameters.map[3].suit_parameter_image_size)
self.assertEqual(4, len(self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union[0].SUIT_Common_Commands.suit_directive_override_parameters.map))
self.assertEqual(15, self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union[1].SUIT_Condition.suit_condition_vendor_identifier.SUIT_Rep_Policy)
self.assertEqual(15, self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union[2].SUIT_Condition.suit_condition_class_identifier.SUIT_Rep_Policy)
self.assertEqual(3, len(self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union))
self.assertEqual(2, len(self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union[0]))
self.assertEqual(2, len(self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union[0].SUIT_Common_Commands))
self.assertEqual(1, len(self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union[0].SUIT_Common_Commands.suit_directive_override_parameters))
self.assertEqual(4, len(self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union[0].SUIT_Common_Commands.suit_directive_override_parameters.map))
self.assertEqual(2, len(self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union[0].SUIT_Common_Commands.suit_directive_override_parameters.map[0]))
def test_cbor_pen(self):
data = bytes.fromhex(p_test_vectors14[1].read_text().replace("\n", ""))
struct = loads(data)
struct2 = loads(struct.value[3]) # manifest
struct3 = loads(struct2[3]) # common sequence
struct4 = loads(struct3[4]) # override params
self.assertEqual(struct4[0], 20)
self.assertTrue(isinstance(struct4[1][1], bytes))
struct4[1][1] = cbor2.CBORTag(112, struct4[1][1]) # Add the tag for cbor-pen
struct3[4] = dumps(struct4)
struct2[3] = dumps(struct3)
struct.value[3] = dumps(struct2)
data = dumps(struct)
self.decode_string(data, p_manifest14, p_cose)
class Test7Inv(Testn):
def test_inv0(self):
data = bytes.fromhex(p_test_vectors14[1].read_text().replace("\n", ""))
struct = loads(data)
struct2 = loads(struct.value[2]) # authentication
struct3 = loads(struct2[1])
struct3.tag = 99999 # invalid tag for COSE_Sign1
struct2[1] = dumps(struct3)
struct.value[2] = dumps(struct2)
data = dumps(struct)
try:
self.decode_string(data, p_manifest14, p_cose)
except cddl_gen.CddlValidationError as e:
return
else:
assert False, "Should have failed validation"
def test_inv1(self):
data = bytes.fromhex(p_test_vectors14[1].read_text().replace("\n", ""))
struct = loads(data)
struct2 = loads(struct.value[3]) # manifest
struct2[1] += 1 # invalid manifest version
struct.value[3] = dumps(struct2)
data = dumps(struct)
try:
self.decode_string(data, p_manifest14, p_cose)
except cddl_gen.CddlValidationError as e:
return
else:
assert False, "Should have failed validation"
def test_inv2(self):
data = bytes.fromhex(p_test_vectors14[1].read_text().replace("\n", ""))
struct = loads(data)
struct.value[23] = b'' # Invalid integrated payload key
data = dumps(struct)
try:
self.decode_string(data, p_manifest14, p_cose)
except (cddl_gen.CddlValidationError, cbor2.CBORDecodeEOF) as e:
return
else:
assert False, "Should have failed validation"
def test_inv3(self):
data = bytes.fromhex(p_test_vectors14[1].read_text().replace("\n", ""))
struct = loads(data)
struct2 = loads(struct.value[3]) # manifest
struct3 = loads(struct2[3]) # common sequence
struct4 = loads(struct3[4]) # override params
self.assertEqual(struct4[0], 20)
self.assertTrue(isinstance(struct4[1][1], bytes))
struct4[1][1] += b'x' # vendor ID: wrong length
struct3[4] = dumps(struct4)
struct2[3] = dumps(struct3)
struct.value[3] = dumps(struct2)
data = dumps(struct)
try:
self.decode_string(data, p_manifest14, p_cose)
except cddl_gen.CddlValidationError as e:
return
else:
assert False, "Should have failed validation"
class Test8(Testn):
def __init__(self, *args, **kwargs):
super(Test8, self).__init__(*args, **kwargs)
self.decode_file(p_test_vectors14[2], p_manifest14, p_cose)
def test_text(self):
self.assertEqual(
bytes.fromhex('2bfc4d0cc6680be7dd9f5ca30aa2bb5d1998145de33d54101b80e2ca49faf918'),
self.decoded.suit_manifest.SUIT_Severable_Members_Choice.suit_text[0].SUIT_Digest.suit_digest_bytes)
self.assertEqual(
bytes.fromhex('2bfc4d0cc6680be7dd9f5ca30aa2bb5d1998145de33d54101b80e2ca49faf918'),
sha256(dumps(self.decoded.SUIT_Severable_Manifest_Members.suit_text[0].suit_text_bstr)).digest())
self.assertEqual('arm.com', self.decoded.SUIT_Severable_Manifest_Members.suit_text[0].suit_text.SUIT_Component_Identifier[0].SUIT_Component_Identifier.SUIT_Text_Component_Keys.suit_text_vendor_domain[0])
self.assertEqual('This component is a demonstration. The digest is a sample pattern, not a real one.', self.decoded.SUIT_Severable_Manifest_Members.suit_text[0].suit_text.SUIT_Component_Identifier[0].SUIT_Component_Identifier.SUIT_Text_Component_Keys.suit_text_component_description[0])
# Check manifest description. The concatenation and .replace() call are there to add
# trailing whitespace to all blank lines except the first.
# This is done in this way to avoid editors automatically removing the whitespace.
self.assertEqual('''## Example 2: Simultaneous Download, Installation, Secure Boot, Severed Fields
''' + '''
This example covers the following templates:
* Compatibility Check ({{template-compatibility-check}})
* Secure Boot ({{template-secure-boot}})
* Firmware Download ({{firmware-download-template}})
This example also demonstrates severable elements ({{ovr-severable}}), and text ({{manifest-digest-text}}).'''.replace("\n\n", "\n \n"), self.decoded.SUIT_Severable_Manifest_Members.suit_text[0].suit_text.SUIT_Text_Keys.suit_text_manifest_description[0])
class Test9(Testn):
def __init__(self, *args, **kwargs):
super(Test9, self).__init__(*args, **kwargs)
self.decode_file(p_test_vectors14[3], p_manifest14, p_cose)
def test_try_each(self):
self.assertEqual(2, len(self.decoded.suit_manifest.SUIT_Severable_Members_Choice.suit_install[0].SUIT_Command_Sequence_bstr.union[0].SUIT_Directive.suit_directive_try_each.SUIT_Directive_Try_Each_Argument.SUIT_Command_Sequence_bstr))
self.assertEqual(33792, self.decoded.suit_manifest.SUIT_Severable_Members_Choice.suit_install[0].SUIT_Command_Sequence_bstr.union[0].SUIT_Directive.suit_directive_try_each.SUIT_Directive_Try_Each_Argument.SUIT_Command_Sequence_bstr[0].union[0].SUIT_Directive.suit_directive_set_parameters.map[0].suit_parameter_component_slot)
self.assertEqual(541696, self.decoded.suit_manifest.SUIT_Severable_Members_Choice.suit_install[0].SUIT_Command_Sequence_bstr.union[0].SUIT_Directive.suit_directive_try_each.SUIT_Directive_Try_Each_Argument.SUIT_Command_Sequence_bstr[1].union[0].SUIT_Directive.suit_directive_set_parameters.map[0].suit_parameter_component_slot)
class Test10(Testn):
def __init__(self, *args, **kwargs):
super(Test10, self).__init__(*args, **kwargs)
self.decode_file(p_test_vectors14[4], p_manifest14, p_cose)
def test_components(self):
self.assertEqual(3, len(self.decoded.suit_manifest.suit_common.suit_components[0]))
self.assertEqual(b'\x00', self.decoded.suit_manifest.suit_common.suit_components[0][0].bstr[0])
self.assertEqual(b'\x02', self.decoded.suit_manifest.suit_common.suit_components[0][1].bstr[0])
self.assertEqual(b'\x01', self.decoded.suit_manifest.suit_common.suit_components[0][2].bstr[0])
class Test11(Testn):
def __init__(self, *args, **kwargs):
super(Test11, self).__init__(*args, **kwargs)
self.decode_file(p_test_vectors14[5], p_manifest14, p_cose)
def test_validate(self):
self.assertEqual(4, len(self.decoded.suit_manifest.SUIT_Unseverable_Members.suit_validate[0].suit_validate.union))
self.assertEqual(15, self.decoded.suit_manifest.SUIT_Unseverable_Members.suit_validate[0].suit_validate.union[1].SUIT_Condition.suit_condition_image_match.SUIT_Rep_Policy)
class Test11Inv(Testn):
def test_invalid_rep_policy(self):
data = bytes.fromhex(p_test_vectors14[5].read_text().replace("\n", ""))
struct = loads(data)
struct2 = loads(struct.value[3]) # manifest
struct3 = loads(struct2[10]) # suit_validate
struct3[3] += 16 # invalid Rep_Policy
struct2[10] = dumps(struct3)
struct.value[3] = dumps(struct2)
data = dumps(struct)
try:
self.decode_string(data, p_manifest14, p_cose)
except cddl_gen.CddlValidationError as e:
return
else:
assert False, "Should have failed validation"
class TestCLI(TestCase):
def get_std_args(self, input):
return ["cddl-gen", "--cddl", p_manifest12, "--default-max-qty", "16", "convert", "--input", input, "-t", "SUIT_Envelope_Tagged"]
def do_testn(self, n):
call0 = Popen(self.get_std_args(p_test_vectors12[n]) + ["--output", "-", "--output-as", "cbor"], stdout=PIPE)
stdout0, _ = call0.communicate()
self.assertEqual(0, call0.returncode)
call1 = Popen(self.get_std_args("-") + ["--input-as", "cbor", "--output", "-", "--output-as", "json"], stdin=PIPE, stdout=PIPE)
stdout1, _ = call1.communicate(input=stdout0)
self.assertEqual(0, call1.returncode)
call2 = Popen(self.get_std_args("-") + ["--input-as", "json", "--output", "-", "--output-as", "yaml"], stdin=PIPE, stdout=PIPE)
stdout2, _ = call2.communicate(input=stdout1)
self.assertEqual(0, call2.returncode)
call3 = Popen(self.get_std_args("-") + ["--input-as", "yaml", "--output", "-", "--output-as", "cbor"], stdin=PIPE, stdout=PIPE)
stdout3, _ = call3.communicate(input=stdout2)
self.assertEqual(0, call3.returncode)
self.assertEqual(stdout0, stdout3)
call4 = Popen(self.get_std_args("-") + ["--input-as", "cbor", "--output", "-", "--output-as", "cborhex"], stdin=PIPE, stdout=PIPE)
stdout4, _ = call4.communicate(input=stdout3)
self.assertEqual(0, call4.returncode)
call5 = Popen(self.get_std_args("-") + ["--input-as", "cborhex", "--output", "-", "--output-as", "json"], stdin=PIPE, stdout=PIPE)
stdout5, _ = call5.communicate(input=stdout4)
self.assertEqual(0, call5.returncode)
self.assertEqual(stdout1, stdout5)
self.maxDiff = None
with open(p_test_vectors12[n], 'r') as f:
self.assertEqual(sub(r"\W+", "", f.read()), sub(r"\W+", "", stdout4.decode("utf-8")))
def test_0(self):
self.do_testn(0)
def test_1(self):
self.do_testn(1)
def test_2(self):
self.do_testn(2)
def test_3(self):
self.do_testn(3)
def test_4(self):
self.do_testn(4)
def test_5(self):
self.do_testn(5)
class TestOptional(TestCase):
def test_0(self):
with open(p_optional, 'r') as f:
cddl_res = cddl_gen.DataTranslator.from_cddl(f.read(), 16)
cddl = cddl_res.my_types['cfg']
test_yaml = """
mem_config:
- 0
- 5"""
decoded = cddl.decode_str_yaml(test_yaml)
self.assertEqual(decoded.mem_config[0].READ.union_choice, "uint0")
self.assertEqual(decoded.mem_config[0].N, [5])
if __name__ == "__main__":
main()
|
the-stack_0_14817 | import argparse
import time
from pyspark.sql import SparkSession
from pyspark.sql.types import StructType, StructField, FloatType, LongType, DecimalType, IntegerType, StringType, DateType
def run_convert_files():
with SparkSession.builder.appName("convert_files").getOrCreate() as spark:
sc = spark.sparkContext
block_size = 1024 * 1024 * 1024 # 1GB
sc._jsc.hadoopConfiguration().setInt("dfs.blocksize", block_size)
sc._jsc.hadoopConfiguration().setInt("parquet.block.size", blockSize)
def convert_files(src, dst, schema):
df = sc.read.option("header", "false").option("delimiter","|")\
.schema(schema)\
.csv(src)
df.write.parquet(dst)
return
path_src = "s3://tpc-h-small/"
path_dst = "s3://tpc-h-small/parquet/"
src_lineitem = path_src + "lineitem.tbl"
dst_lineitem = path_dst + "lineitem"
schema_lineitem = StructType()\
.add("l_orderkey",LongType(),False)\
.add("l_partkey",LongType(),True)\
.add("l_suppkey",LongType(),True)\
.add("l_linenumber",IntegerType(),True)\
.add("l_quantity",DecimalType(10,2),True)\
.add("l_extendedprice",DecimalType(10,2),True)\
.add("l_discount",DecimalType(10,2),True)\
.add("l_tax",DecimalType(10,2),True)\
.add("l_returnflag",StringType(),True)\
.add("l_linestatus",StringType(),True)\
.add("l_shipdate",DateType(),True)\
.add("l_commitdate",DateType(),True)\
.add("l_receiptdate",DateType(),True)\
.add("l_shipinstruct",StringType(),True)\
.add("l_shipmode",StringType(),True)\
.add("l_comment",StringType(),True)
convert_files(src_lineitem, dst_lineitem, schema_lineitem)
# src_orders = path_src + "orders.tbl"
# dst_orders = path_dst + "orders"
# schema_orders = StructType()\
# .add("o_orderkey",LongType(),False)\
# .add("o_custkey",LongType(),False)\
# .add("o_orderstatus",StringType(),True)\
# .add("o_totalprice",DecimalType(10,2),True)\
# .add("o_orderdate",DateType(),True)\
# .add("o_orderpriority",StringType(),True)\
# .add("o_clerk",StringType(),True)\
# .add("o_shippriority",IntegerType(),True)\
# .add("o_comment",StringType(),True)
# convert_files(src_orders, dst_orders, schema_orders)
if __name__ == "__main__":
run_convert_files()
|
the-stack_0_14818 | # Copyright 2019 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
r"""Unit tests for the states.py fock probabilities methods"""
import pytest
import numpy as np
import tensorflow as tf
from scipy.special import factorial as fac
from strawberryfields import backends
from strawberryfields import utils
MAG_ALPHAS = np.linspace(0, 0.8, 3)
PHASE_ALPHAS = np.linspace(0, 2 * np.pi, 3, endpoint=False)
@pytest.mark.parametrize("a", MAG_ALPHAS)
@pytest.mark.parametrize("phi", PHASE_ALPHAS)
class TestFockProbabilities:
"""Tests for the fock_prob state method"""
def test_gaussian(self, a, phi, setup_backend, cutoff, tol):
"""Tests that probabilities of particular Fock states
|n> are correct for a gaussian state."""
backend = setup_backend(1)
alpha = a * np.exp(1j * phi)
n = np.arange(cutoff)
ref_state = np.exp(-0.5 * np.abs(alpha) ** 2) * alpha ** n / np.sqrt(fac(n))
ref_probs = np.abs(ref_state) ** 2
backend.prepare_coherent_state(np.abs(alpha), np.angle(alpha), 0)
state = backend.state()
for n in range(cutoff):
prob_n = state.fock_prob([n])
assert np.allclose(prob_n, ref_probs[n], atol=tol, rtol=0)
@pytest.mark.backends("fock", "tf")
def test_nongaussian(self, a, phi, setup_backend, cutoff, tol):
"""Tests that probabilities of particular Fock states |n> are
correct for a nongaussian state."""
backend = setup_backend(2)
alpha = a * np.exp(1j * phi)
n = np.arange(cutoff)
ref_state = np.exp(-0.5 * np.abs(alpha) ** 2) * alpha ** n / np.sqrt(fac(n))
ref_probs = np.abs(ref_state) ** 2
backend.prepare_coherent_state(np.abs(alpha), np.angle(alpha), 0)
backend.prepare_fock_state(cutoff // 2, 1)
state = backend.state()
for n in range(cutoff):
prob_n = state.fock_prob([n, cutoff // 2])
assert np.allclose(prob_n, ref_probs[n], atol=tol, rtol=0)
@pytest.mark.backends("fock", "tf", "gaussian")
@pytest.mark.parametrize("a", MAG_ALPHAS)
@pytest.mark.parametrize("phi", PHASE_ALPHAS)
class TestAllFockProbs:
"""Tests for the all_fock_probs state method"""
def test_pure(self, a, phi, setup_backend, cutoff, batch_size, tol):
"""Tests that the numeric probabilities in the full Fock basis are
correct for a one-mode pure state."""
backend = setup_backend(1)
alpha = a * np.exp(1j * phi)
n = np.arange(cutoff)
ref_state = np.exp(-0.5 * np.abs(alpha) ** 2) * alpha ** n / np.sqrt(fac(n))
ref_probs = np.abs(ref_state) ** 2
backend.prepare_coherent_state(np.abs(alpha), np.angle(alpha), 0)
state = backend.state()
probs = state.all_fock_probs(cutoff=cutoff)
if isinstance(probs, tf.Tensor):
probs = probs.numpy()
probs = probs.flatten()
if batch_size is not None:
ref_probs = np.tile(ref_probs, batch_size)
assert np.allclose(probs, ref_probs, atol=tol, rtol=0)
def test_two_mode_gaussian(self, a, phi, setup_backend, batch_size, cutoff, tol):
"""Tests that the numeric probabilities in the full Fock basis are
correct for a two-mode gaussian state."""
if a == 0.0:
pytest.skip("Test only runs for states with non-zero displacement")
backend = setup_backend(2)
alpha = a * np.exp(1j * phi)
n = np.arange(cutoff)
ref_state1 = np.exp(-0.5 * np.abs(alpha) ** 2) * alpha ** n / np.sqrt(fac(n))
ref_state2 = (
np.exp(-0.5 * np.abs(-alpha) ** 2) * (-alpha) ** n / np.sqrt(fac(n))
)
ref_state = np.outer(ref_state1, ref_state2)
ref_probs = np.abs(np.reshape(ref_state ** 2, -1))
if batch_size is not None:
ref_probs = np.tile(ref_probs, batch_size)
backend.prepare_coherent_state(np.abs(alpha), np.angle(alpha), 0)
backend.prepare_coherent_state(np.abs(alpha), np.angle(alpha)+np.pi, 1)
state = backend.state()
for n in range(cutoff):
for m in range(cutoff):
probs = state.all_fock_probs(cutoff=cutoff)
if isinstance(probs, tf.Tensor):
probs = probs.numpy()
assert np.allclose(probs.flatten(), ref_probs, atol=tol, rtol=0)
|
the-stack_0_14819 | ##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Adjustments are tunable parameters.
"""
import getopt
import socket
from waitress.compat import (
PY2,
WIN,
string_types,
HAS_IPV6,
)
truthy = frozenset(('t', 'true', 'y', 'yes', 'on', '1'))
def asbool(s):
""" Return the boolean value ``True`` if the case-lowered value of string
input ``s`` is any of ``t``, ``true``, ``y``, ``on``, or ``1``, otherwise
return the boolean value ``False``. If ``s`` is the value ``None``,
return ``False``. If ``s`` is already one of the boolean values ``True``
or ``False``, return it."""
if s is None:
return False
if isinstance(s, bool):
return s
s = str(s).strip()
return s.lower() in truthy
def asoctal(s):
"""Convert the given octal string to an actual number."""
return int(s, 8)
def aslist_cronly(value):
if isinstance(value, string_types):
value = filter(None, [x.strip() for x in value.splitlines()])
return list(value)
def aslist(value):
""" Return a list of strings, separating the input based on newlines
and, if flatten=True (the default), also split on spaces within
each line."""
values = aslist_cronly(value)
result = []
for value in values:
subvalues = value.split()
result.extend(subvalues)
return result
def slash_fixed_str(s):
s = s.strip()
if s:
# always have a leading slash, replace any number of leading slashes
# with a single slash, and strip any trailing slashes
s = '/' + s.lstrip('/').rstrip('/')
return s
class _str_marker(str):
pass
class _int_marker(int):
pass
class Adjustments(object):
"""This class contains tunable parameters.
"""
_params = (
('host', str),
('port', int),
('ipv4', asbool),
('ipv6', asbool),
('listen', aslist),
('threads', int),
('trusted_proxy', str),
('url_scheme', str),
('url_prefix', slash_fixed_str),
('backlog', int),
('recv_bytes', int),
('send_bytes', int),
('outbuf_overflow', int),
('inbuf_overflow', int),
('connection_limit', int),
('cleanup_interval', int),
('channel_timeout', int),
('log_socket_errors', asbool),
('max_request_header_size', int),
('max_request_body_size', int),
('expose_tracebacks', asbool),
('ident', str),
('asyncore_loop_timeout', int),
('asyncore_use_poll', asbool),
('unix_socket', str),
('unix_socket_perms', asoctal),
)
_param_map = dict(_params)
# hostname or IP address to listen on
host = _str_marker('0.0.0.0')
# TCP port to listen on
port = _int_marker(8080)
listen = ['{}:{}'.format(host, port)]
# mumber of threads available for tasks
threads = 4
# Host allowed to overrid ``wsgi.url_scheme`` via header
trusted_proxy = None
# default ``wsgi.url_scheme`` value
url_scheme = 'http'
# default ``SCRIPT_NAME`` value, also helps reset ``PATH_INFO``
# when nonempty
url_prefix = ''
# server identity (sent in Server: header)
ident = 'waitress'
# backlog is the value waitress passes to pass to socket.listen() This is
# the maximum number of incoming TCP connections that will wait in an OS
# queue for an available channel. From listen(1): "If a connection
# request arrives when the queue is full, the client may receive an error
# with an indication of ECONNREFUSED or, if the underlying protocol
# supports retransmission, the request may be ignored so that a later
# reattempt at connection succeeds."
backlog = 1024
# recv_bytes is the argument to pass to socket.recv().
recv_bytes = 8192
# send_bytes is the number of bytes to send to socket.send(). Multiples
# of 9000 should avoid partly-filled packets, but don't set this larger
# than the TCP write buffer size. In Linux, /proc/sys/net/ipv4/tcp_wmem
# controls the minimum, default, and maximum sizes of TCP write buffers.
send_bytes = 18000
# A tempfile should be created if the pending output is larger than
# outbuf_overflow, which is measured in bytes. The default is 1MB. This
# is conservative.
outbuf_overflow = 1048576
# A tempfile should be created if the pending input is larger than
# inbuf_overflow, which is measured in bytes. The default is 512K. This
# is conservative.
inbuf_overflow = 524288
# Stop creating new channels if too many are already active (integer).
# Each channel consumes at least one file descriptor, and, depending on
# the input and output body sizes, potentially up to three. The default
# is conservative, but you may need to increase the number of file
# descriptors available to the Waitress process on most platforms in
# order to safely change it (see ``ulimit -a`` "open files" setting).
# Note that this doesn't control the maximum number of TCP connections
# that can be waiting for processing; the ``backlog`` argument controls
# that.
connection_limit = 100
# Minimum seconds between cleaning up inactive channels.
cleanup_interval = 30
# Maximum seconds to leave an inactive connection open.
channel_timeout = 120
# Boolean: turn off to not log premature client disconnects.
log_socket_errors = True
# maximum number of bytes of all request headers combined (256K default)
max_request_header_size = 262144
# maximum number of bytes in request body (1GB default)
max_request_body_size = 1073741824
# expose tracebacks of uncaught exceptions
expose_tracebacks = False
# Path to a Unix domain socket to use.
unix_socket = None
# Path to a Unix domain socket to use.
unix_socket_perms = 0o600
# The socket options to set on receiving a connection. It is a list of
# (level, optname, value) tuples. TCP_NODELAY disables the Nagle
# algorithm for writes (Waitress already buffers its writes).
socket_options = [
(socket.SOL_TCP, socket.TCP_NODELAY, 1),
]
# The asyncore.loop timeout value
asyncore_loop_timeout = 1
# The asyncore.loop flag to use poll() instead of the default select().
asyncore_use_poll = False
# Enable IPv4 by default
ipv4 = True
# Enable IPv6 by default
ipv6 = True
def __init__(self, **kw):
if 'listen' in kw and ('host' in kw or 'port' in kw):
raise ValueError('host and or port may not be set if listen is set.')
for k, v in kw.items():
if k not in self._param_map:
raise ValueError('Unknown adjustment %r' % k)
setattr(self, k, self._param_map[k](v))
if (not isinstance(self.host, _str_marker) or
not isinstance(self.port, _int_marker)):
self.listen = ['{}:{}'.format(self.host, self.port)]
enabled_families = socket.AF_UNSPEC
if not self.ipv4 and not HAS_IPV6: # pragma: no cover
raise ValueError(
'IPv4 is disabled but IPv6 is not available. Cowardly refusing to start.'
)
if self.ipv4 and not self.ipv6:
enabled_families = socket.AF_INET
if not self.ipv4 and self.ipv6 and HAS_IPV6:
enabled_families = socket.AF_INET6
wanted_sockets = []
hp_pairs = []
for i in self.listen:
if ':' in i:
(host, port) = i.rsplit(":", 1)
# IPv6 we need to make sure that we didn't split on the address
if ']' in port: # pragma: nocover
(host, port) = (i, str(self.port))
else:
(host, port) = (i, str(self.port))
if WIN and PY2: # pragma: no cover
try:
# Try turning the port into an integer
port = int(port)
except:
raise ValueError(
'Windows does not support service names instead of port numbers'
)
try:
if '[' in host and ']' in host: # pragma: nocover
host = host.strip('[').rstrip(']')
if host == '*':
host = None
for s in socket.getaddrinfo(
host,
port,
enabled_families,
socket.SOCK_STREAM,
socket.IPPROTO_TCP,
socket.AI_PASSIVE
):
(family, socktype, proto, _, sockaddr) = s
# It seems that getaddrinfo() may sometimes happily return
# the same result multiple times, this of course makes
# bind() very unhappy...
#
# Split on %, and drop the zone-index from the host in the
# sockaddr. Works around a bug in OS X whereby
# getaddrinfo() returns the same link-local interface with
# two different zone-indices (which makes no sense what so
# ever...) yet treats them equally when we attempt to bind().
if (
sockaddr[1] == 0 or
(sockaddr[0].split('%', 1)[0], sockaddr[1]) not in hp_pairs
):
wanted_sockets.append((family, socktype, proto, sockaddr))
hp_pairs.append((sockaddr[0].split('%', 1)[0], sockaddr[1]))
except:
raise ValueError('Invalid host/port specified.')
self.listen = wanted_sockets
@classmethod
def parse_args(cls, argv):
"""Pre-parse command line arguments for input into __init__. Note that
this does not cast values into adjustment types, it just creates a
dictionary suitable for passing into __init__, where __init__ does the
casting.
"""
long_opts = ['help', 'call']
for opt, cast in cls._params:
opt = opt.replace('_', '-')
if cast is asbool:
long_opts.append(opt)
long_opts.append('no-' + opt)
else:
long_opts.append(opt + '=')
kw = {
'help': False,
'call': False,
}
opts, args = getopt.getopt(argv, '', long_opts)
for opt, value in opts:
param = opt.lstrip('-').replace('-', '_')
if param == 'listen':
kw['listen'] = '{} {}'.format(kw.get('listen', ''), value)
continue
if param.startswith('no_'):
param = param[3:]
kw[param] = 'false'
elif param in ('help', 'call'):
kw[param] = True
elif cls._param_map[param] is asbool:
kw[param] = 'true'
else:
kw[param] = value
return kw, args
|
the-stack_0_14822 | #!/usr/bin/env python3
import argparse
import os
import sys
import logging
from vapi_json_parser import Field, Struct, Enum, Union, Message, JsonParser,\
SimpleType, StructType, Alias
class CField(Field):
def get_c_name(self):
return "vapi_type_%s" % self.name
def get_c_def(self):
if self.type.get_c_name() == 'vl_api_string_t':
if self.len:
return "u8 %s[%d];" % (self.name, self.len)
else:
return "vl_api_string_t %s;" % (self.name)
else:
if self.len is not None and type(self.len) != dict:
return "%s %s[%d];" % (self.type.get_c_name(), self.name, self.len)
else:
return "%s %s;" % (self.type.get_c_name(), self.name)
def get_swap_to_be_code(self, struct, var):
if self.len is not None and type(self.len) != dict:
if self.len > 0:
return "do { unsigned i; for (i = 0; i < %d; ++i) { %s } }"\
" while(0);" % (
self.len,
self.type.get_swap_to_be_code(struct, "%s[i]" % var))
else:
if self.nelem_field.needs_byte_swap():
nelem_field = "%s(%s%s)" % (
self.nelem_field.type.get_swap_to_host_func_name(),
struct, self.nelem_field.name)
else:
nelem_field = "%s%s" % (struct, self.nelem_field.name)
return (
"do { unsigned i; for (i = 0; i < %s; ++i) { %s } }"
" while(0);" %
(nelem_field, self.type.get_swap_to_be_code(
struct, "%s[i]" % var)))
return self.type.get_swap_to_be_code(struct, "%s" % var)
def get_swap_to_host_code(self, struct, var):
if self.len is not None and type(self.len) != dict:
if self.len > 0:
return "do { unsigned i; for (i = 0; i < %d; ++i) { %s } }"\
" while(0);" % (
self.len,
self.type.get_swap_to_host_code(struct, "%s[i]" % var))
else:
# nelem_field already swapped to host here...
return (
"do { unsigned i; for (i = 0; i < %s%s; ++i) { %s } }"
" while(0);" %
(struct, self.nelem_field.name,
self.type.get_swap_to_host_code(
struct, "%s[i]" % var)))
return self.type.get_swap_to_host_code(struct, "%s" % var)
def needs_byte_swap(self):
return self.type.needs_byte_swap()
def get_vla_field_length_name(self, path):
return "%s_%s_array_size" % ("_".join(path), self.name)
def get_alloc_vla_param_names(self, path):
if self.is_vla():
result = [self.get_vla_field_length_name(path)]
else:
result = []
if self.type.has_vla():
t = self.type.get_alloc_vla_param_names(path + [self.name])
result.extend(t)
return result
def get_vla_calc_size_code(self, prefix, path):
if self.is_vla():
result = ["sizeof(%s.%s[0]) * %s" % (
".".join([prefix] + path),
self.name,
self.get_vla_field_length_name(path))]
else:
result = []
if self.type.has_vla():
t = self.type.get_vla_calc_size_code(prefix, path + [self.name])
result.extend(t)
return result
def get_vla_assign_code(self, prefix, path):
result = []
if self.is_vla():
result.append("%s.%s = %s" % (
".".join([prefix] + path),
self.nelem_field.name,
self.get_vla_field_length_name(path)))
if self.type.has_vla():
t = self.type.get_vla_assign_code(prefix, path + [self.name])
result.extend(t)
return result
class CAlias(CField):
def get_c_name(self):
return "vapi_type_%s" % self.name
def get_c_def(self):
if self.len is not None:
return "typedef %s vapi_type_%s[%d];" % (
self.type.get_c_name(), self.name, self.len)
else:
return "typedef %s vapi_type_%s;" % (
self.type.get_c_name(), self.name)
class CStruct(Struct):
def get_c_def(self):
return "\n".join([
"typedef struct __attribute__((__packed__)) {\n%s" % (
"\n".join([" %s" % x.get_c_def()
for x in self.fields])),
"} %s;" % self.get_c_name()])
def get_vla_assign_code(self, prefix, path):
return [x for f in self.fields if f.has_vla()
for x in f.get_vla_assign_code(prefix, path)]
def get_alloc_vla_param_names(self, path):
return [x for f in self.fields
if f.has_vla()
for x in f.get_alloc_vla_param_names(path)]
def get_vla_calc_size_code(self, prefix, path):
return [x for f in self.fields if f.has_vla()
for x in f.get_vla_calc_size_code(prefix, path)]
class CSimpleType (SimpleType):
swap_to_be_dict = {
'i16': 'htobe16', 'u16': 'htobe16',
'i32': 'htobe32', 'u32': 'htobe32',
'i64': 'htobe64', 'u64': 'htobe64',
}
swap_to_host_dict = {
'i16': 'be16toh', 'u16': 'be16toh',
'i32': 'be32toh', 'u32': 'be32toh',
'i64': 'be64toh', 'u64': 'be64toh',
}
__packed = "__attribute__((packed))"
pack_dict = {
'i8': __packed, 'u8': __packed,
'i16': __packed, 'u16': __packed,
}
def get_c_name(self):
return self.name
def get_swap_to_be_func_name(self):
return self.swap_to_be_dict[self.name]
def get_swap_to_host_func_name(self):
return self.swap_to_host_dict[self.name]
def get_packed_string(self):
return self.pack_dict[self.name]
def get_swap_to_be_code(self, struct, var, cast=None):
x = "%s%s" % (struct, var)
return "%s = %s%s(%s);" % (x,
"(%s)" % cast if cast else "",
self.get_swap_to_be_func_name(), x)
def get_swap_to_host_code(self, struct, var, cast=None):
x = "%s%s" % (struct, var)
return "%s = %s%s(%s);" % (x,
"(%s)" % cast if cast else "",
self.get_swap_to_host_func_name(), x)
def needs_byte_swap(self):
try:
self.get_swap_to_host_func_name()
return True
except KeyError:
pass
return False
def get_packed(self):
return self.pack_dict.get(self.name, "")
class CEnum(Enum):
def get_c_name(self):
return "vapi_enum_%s" % self.name
def get_c_def(self):
return "typedef enum {\n%s\n} %s %s;" % (
"\n".join([" %s = %s," % (i, j) for i, j in self.value_pairs]),
self.type.get_packed(),
self.get_c_name()
)
def needs_byte_swap(self):
return self.type.needs_byte_swap()
def get_swap_to_be_code(self, struct, var):
return self.type.get_swap_to_be_code(struct, var, self.get_c_name())
def get_swap_to_host_code(self, struct, var):
return self.type.get_swap_to_host_code(struct, var, self.get_c_name())
class CUnion(Union):
def get_c_name(self):
return "vapi_union_%s" % self.name
def get_c_def(self):
return "typedef union {\n%s\n} %s;" % (
"\n".join([" %s %s;" % (i.get_c_name(), j)
for i, j in self.type_pairs]),
self.get_c_name()
)
def needs_byte_swap(self):
return False
class CStructType (StructType, CStruct):
def get_c_name(self):
return "vapi_type_%s" % self.name
def get_swap_to_be_func_name(self):
return "%s_hton" % self.get_c_name()
def get_swap_to_host_func_name(self):
return "%s_ntoh" % self.get_c_name()
def get_swap_to_be_func_decl(self):
return "void %s(%s *msg)" % (
self.get_swap_to_be_func_name(), self.get_c_name())
def get_swap_to_be_func_def(self):
return "%s\n{\n%s\n}" % (
self.get_swap_to_be_func_decl(),
"\n".join([
" %s" % p.get_swap_to_be_code("msg->", "%s" % p.name)
for p in self.fields if p.needs_byte_swap()]),
)
def get_swap_to_host_func_decl(self):
return "void %s(%s *msg)" % (
self.get_swap_to_host_func_name(), self.get_c_name())
def get_swap_to_host_func_def(self):
return "%s\n{\n%s\n}" % (
self.get_swap_to_host_func_decl(),
"\n".join([
" %s" % p.get_swap_to_host_code("msg->", "%s" % p.name)
for p in self.fields if p.needs_byte_swap()]),
)
def get_swap_to_be_code(self, struct, var):
return "%s(&%s%s);" % (self.get_swap_to_be_func_name(), struct, var)
def get_swap_to_host_code(self, struct, var):
return "%s(&%s%s);" % (self.get_swap_to_host_func_name(), struct, var)
def needs_byte_swap(self):
for f in self.fields:
if f.needs_byte_swap():
return True
return False
class CMessage (Message):
def __init__(self, logger, definition, json_parser):
super(CMessage, self).__init__(logger, definition, json_parser)
self.payload_members = [
" %s" % p.get_c_def()
for p in self.fields
if p.type != self.header
]
def has_payload(self):
return len(self.payload_members) > 0
def get_msg_id_name(self):
return "vapi_msg_id_%s" % self.name
def get_c_name(self):
return "vapi_msg_%s" % self.name
def get_payload_struct_name(self):
return "vapi_payload_%s" % self.name
def get_alloc_func_name(self):
return "vapi_alloc_%s" % self.name
def get_alloc_vla_param_names(self):
return [x for f in self.fields
if f.has_vla()
for x in f.get_alloc_vla_param_names([])]
def get_alloc_func_decl(self):
return "%s* %s(struct vapi_ctx_s *ctx%s)" % (
self.get_c_name(),
self.get_alloc_func_name(),
"".join([", size_t %s" % n for n in
self.get_alloc_vla_param_names()]))
def get_alloc_func_def(self):
extra = []
if self.header.has_field('client_index'):
extra.append(
" msg->header.client_index = vapi_get_client_index(ctx);")
if self.header.has_field('context'):
extra.append(" msg->header.context = 0;")
return "\n".join([
"%s" % self.get_alloc_func_decl(),
"{",
" %s *msg = NULL;" % self.get_c_name(),
" const size_t size = sizeof(%s)%s;" % (
self.get_c_name(),
"".join([" + %s" % x for f in self.fields if f.has_vla()
for x in f.get_vla_calc_size_code("msg->payload",
[])])),
" /* cast here required to play nicely with C++ world ... */",
" msg = (%s*)vapi_msg_alloc(ctx, size);" % self.get_c_name(),
" if (!msg) {",
" return NULL;",
" }",
] + extra + [
" msg->header._vl_msg_id = vapi_lookup_vl_msg_id(ctx, %s);" %
self.get_msg_id_name(),
"".join([" %s;\n" % line
for f in self.fields if f.has_vla()
for line in f.get_vla_assign_code("msg->payload", [])]),
" return msg;",
"}"])
def get_calc_msg_size_func_name(self):
return "vapi_calc_%s_msg_size" % self.name
def get_calc_msg_size_func_decl(self):
return "uword %s(%s *msg)" % (
self.get_calc_msg_size_func_name(),
self.get_c_name())
def get_calc_msg_size_func_def(self):
return "\n".join([
"%s" % self.get_calc_msg_size_func_decl(),
"{",
" return sizeof(*msg)%s;" %
"".join(["+ msg->payload.%s * sizeof(msg->payload.%s[0])" % (
f.nelem_field.name,
f.name)
for f in self.fields
if f.nelem_field is not None
]),
"}",
])
def get_c_def(self):
if self.has_payload():
return "\n".join([
"typedef struct __attribute__ ((__packed__)) {",
"%s " %
"\n".join(self.payload_members),
"} %s;" % self.get_payload_struct_name(),
"",
"typedef struct __attribute__ ((__packed__)) {",
(" %s %s;" % (self.header.get_c_name(),
self.fields[0].name)
if self.header is not None else ""),
" %s payload;" % self.get_payload_struct_name(),
"} %s;" % self.get_c_name(), ])
else:
return "\n".join([
"typedef struct __attribute__ ((__packed__)) {",
(" %s %s;" % (self.header.get_c_name(),
self.fields[0].name)
if self.header is not None else ""),
"} %s;" % self.get_c_name(), ])
def get_swap_payload_to_host_func_name(self):
return "%s_payload_ntoh" % self.get_c_name()
def get_swap_payload_to_be_func_name(self):
return "%s_payload_hton" % self.get_c_name()
def get_swap_payload_to_host_func_decl(self):
return "void %s(%s *payload)" % (
self.get_swap_payload_to_host_func_name(),
self.get_payload_struct_name())
def get_swap_payload_to_be_func_decl(self):
return "void %s(%s *payload)" % (
self.get_swap_payload_to_be_func_name(),
self.get_payload_struct_name())
def get_swap_payload_to_be_func_def(self):
return "%s\n{\n%s\n}" % (
self.get_swap_payload_to_be_func_decl(),
"\n".join([
" %s" % p.get_swap_to_be_code("payload->", "%s" % p.name)
for p in self.fields
if p.needs_byte_swap() and p.type != self.header]),
)
def get_swap_payload_to_host_func_def(self):
return "%s\n{\n%s\n}" % (
self.get_swap_payload_to_host_func_decl(),
"\n".join([
" %s" % p.get_swap_to_host_code("payload->", "%s" % p.name)
for p in self.fields
if p.needs_byte_swap() and p.type != self.header]),
)
def get_swap_to_host_func_name(self):
return "%s_ntoh" % self.get_c_name()
def get_swap_to_be_func_name(self):
return "%s_hton" % self.get_c_name()
def get_swap_to_host_func_decl(self):
return "void %s(%s *msg)" % (
self.get_swap_to_host_func_name(), self.get_c_name())
def get_swap_to_be_func_decl(self):
return "void %s(%s *msg)" % (
self.get_swap_to_be_func_name(), self.get_c_name())
def get_swap_to_be_func_def(self):
return "\n".join([
"%s" % self.get_swap_to_be_func_decl(),
"{",
(" VAPI_DBG(\"Swapping `%s'@%%p to big endian\", msg);" %
self.get_c_name()),
" %s(&msg->header);" % self.header.get_swap_to_be_func_name()
if self.header is not None else "",
" %s(&msg->payload);" % self.get_swap_payload_to_be_func_name()
if self.has_payload() else "",
"}",
])
def get_swap_to_host_func_def(self):
return "\n".join([
"%s" % self.get_swap_to_host_func_decl(),
"{",
(" VAPI_DBG(\"Swapping `%s'@%%p to host byte order\", msg);" %
self.get_c_name()),
" %s(&msg->header);" % self.header.get_swap_to_host_func_name()
if self.header is not None else "",
" %s(&msg->payload);" % self.get_swap_payload_to_host_func_name()
if self.has_payload() else "",
"}",
])
def get_op_func_name(self):
return "vapi_%s" % self.name
def get_op_func_decl(self):
if self.reply.has_payload():
return "vapi_error_e %s(%s)" % (
self.get_op_func_name(),
",\n ".join([
'struct vapi_ctx_s *ctx',
'%s *msg' % self.get_c_name(),
'vapi_error_e (*callback)(struct vapi_ctx_s *ctx',
' void *callback_ctx',
' vapi_error_e rv',
' bool is_last',
' %s *reply)' %
self.reply.get_payload_struct_name(),
'void *callback_ctx',
])
)
else:
return "vapi_error_e %s(%s)" % (
self.get_op_func_name(),
",\n ".join([
'struct vapi_ctx_s *ctx',
'%s *msg' % self.get_c_name(),
'vapi_error_e (*callback)(struct vapi_ctx_s *ctx',
' void *callback_ctx',
' vapi_error_e rv',
' bool is_last)',
'void *callback_ctx',
])
)
def get_op_func_def(self):
return "\n".join([
"%s" % self.get_op_func_decl(),
"{",
" if (!msg || !callback) {",
" return VAPI_EINVAL;",
" }",
" if (vapi_is_nonblocking(ctx) && vapi_requests_full(ctx)) {",
" return VAPI_EAGAIN;",
" }",
" vapi_error_e rv;",
" if (VAPI_OK != (rv = vapi_producer_lock (ctx))) {",
" return rv;",
" }",
" u32 req_context = vapi_gen_req_context(ctx);",
" msg->header.context = req_context;",
" %s(msg);" % self.get_swap_to_be_func_name(),
(" if (VAPI_OK == (rv = vapi_send_with_control_ping "
"(ctx, msg, req_context))) {"
if self.reply_is_stream else
" if (VAPI_OK == (rv = vapi_send (ctx, msg))) {"
),
(" vapi_store_request(ctx, req_context, %s, "
"(vapi_cb_t)callback, callback_ctx);" %
("true" if self.reply_is_stream else "false")),
" if (VAPI_OK != vapi_producer_unlock (ctx)) {",
" abort (); /* this really shouldn't happen */",
" }",
" if (vapi_is_nonblocking(ctx)) {",
" rv = VAPI_OK;",
" } else {",
" rv = vapi_dispatch(ctx);",
" }",
" } else {",
" %s(msg);" % self.get_swap_to_host_func_name(),
" if (VAPI_OK != vapi_producer_unlock (ctx)) {",
" abort (); /* this really shouldn't happen */",
" }",
" }",
" return rv;",
"}",
"",
])
def get_event_cb_func_decl(self):
if not self.is_reply and not self.is_event:
raise Exception(
"Cannot register event callback for non-reply message")
if self.has_payload():
return "\n".join([
"void vapi_set_%s_event_cb (" %
self.get_c_name(),
" struct vapi_ctx_s *ctx, ",
(" vapi_error_e (*callback)(struct vapi_ctx_s *ctx, "
"void *callback_ctx, %s *payload)," %
self.get_payload_struct_name()),
" void *callback_ctx)",
])
else:
return "\n".join([
"void vapi_set_%s_event_cb (" %
self.get_c_name(),
" struct vapi_ctx_s *ctx, ",
" vapi_error_e (*callback)(struct vapi_ctx_s *ctx, "
"void *callback_ctx),",
" void *callback_ctx)",
])
def get_event_cb_func_def(self):
if not self.is_reply and not self.is_event:
raise Exception(
"Cannot register event callback for non-reply function")
return "\n".join([
"%s" % self.get_event_cb_func_decl(),
"{",
(" vapi_set_event_cb(ctx, %s, (vapi_event_cb)callback, "
"callback_ctx);" %
self.get_msg_id_name()),
"}"])
def get_c_metadata_struct_name(self):
return "__vapi_metadata_%s" % self.name
def get_c_constructor(self):
has_context = False
if self.header is not None:
has_context = self.header.has_field('context')
return '\n'.join([
'static void __attribute__((constructor)) __vapi_constructor_%s()'
% self.name,
'{',
' static const char name[] = "%s";' % self.name,
' static const char name_with_crc[] = "%s_%s";'
% (self.name, self.crc[2:]),
' static vapi_message_desc_t %s = {' %
self.get_c_metadata_struct_name(),
' name,',
' sizeof(name) - 1,',
' name_with_crc,',
' sizeof(name_with_crc) - 1,',
' true,' if has_context else ' false,',
' offsetof(%s, context),' % self.header.get_c_name()
if has_context else ' 0,',
(' offsetof(%s, payload),' % self.get_c_name())
if self.has_payload() else ' VAPI_INVALID_MSG_ID,',
' sizeof(%s),' % self.get_c_name(),
' (generic_swap_fn_t)%s,' % self.get_swap_to_be_func_name(),
' (generic_swap_fn_t)%s,' % self.get_swap_to_host_func_name(),
' VAPI_INVALID_MSG_ID,',
' };',
'',
' %s = vapi_register_msg(&%s);' %
(self.get_msg_id_name(), self.get_c_metadata_struct_name()),
' VAPI_DBG("Assigned msg id %%d to %s", %s);' %
(self.name, self.get_msg_id_name()),
'}',
])
vapi_send_with_control_ping = """
static inline vapi_error_e
vapi_send_with_control_ping (vapi_ctx_t ctx, void *msg, u32 context)
{
vapi_msg_control_ping *ping = vapi_alloc_control_ping (ctx);
if (!ping)
{
return VAPI_ENOMEM;
}
ping->header.context = context;
vapi_msg_control_ping_hton (ping);
return vapi_send2 (ctx, msg, ping);
}
"""
def emit_definition(parser, json_file, emitted, o):
if o in emitted:
return
if o.name in ("msg_header1_t", "msg_header2_t"):
return
if hasattr(o, "depends"):
for x in o.depends:
emit_definition(parser, json_file, emitted, x)
if hasattr(o, "reply"):
emit_definition(parser, json_file, emitted, o.reply)
if hasattr(o, "get_c_def"):
if (o not in parser.enums_by_json[json_file] and
o not in parser.types_by_json[json_file] and
o not in parser.unions_by_json[json_file] and
o.name not in parser.messages_by_json[json_file] and
o not in parser.aliases_by_json[json_file]):
return
guard = "defined_%s" % o.get_c_name()
print("#ifndef %s" % guard)
print("#define %s" % guard)
print("%s" % o.get_c_def())
print("")
function_attrs = "static inline "
if o.name in parser.messages_by_json[json_file]:
if o.has_payload():
print("%s%s" % (function_attrs,
o.get_swap_payload_to_be_func_def()))
print("")
print("%s%s" % (function_attrs,
o.get_swap_payload_to_host_func_def()))
print("")
print("%s%s" % (function_attrs, o.get_swap_to_be_func_def()))
print("")
print("%s%s" % (function_attrs, o.get_swap_to_host_func_def()))
print("")
print("%s%s" % (function_attrs, o.get_calc_msg_size_func_def()))
if not o.is_reply and not o.is_event:
print("")
print("%s%s" % (function_attrs, o.get_alloc_func_def()))
print("")
print("%s%s" % (function_attrs, o.get_op_func_def()))
print("")
print("%s" % o.get_c_constructor())
if o.is_reply or o.is_event:
print("")
print("%s%s;" % (function_attrs, o.get_event_cb_func_def()))
elif hasattr(o, "get_swap_to_be_func_def"):
print("%s%s" % (function_attrs, o.get_swap_to_be_func_def()))
print("")
print("%s%s" % (function_attrs, o.get_swap_to_host_func_def()))
print("#endif")
print("")
emitted.append(o)
def gen_json_unified_header(parser, logger, j, io, name):
d, f = os.path.split(j)
logger.info("Generating header `%s'" % name)
orig_stdout = sys.stdout
sys.stdout = io
include_guard = "__included_%s" % (
j.replace(".", "_").replace("/", "_").replace("-", "_").replace("+", "_"))
print("#ifndef %s" % include_guard)
print("#define %s" % include_guard)
print("")
print("#include <stdlib.h>")
print("#include <stddef.h>")
print("#include <arpa/inet.h>")
print("#include <vapi/vapi_internal.h>")
print("#include <vapi/vapi.h>")
print("#include <vapi/vapi_dbg.h>")
print("")
print("#ifdef __cplusplus")
print("extern \"C\" {")
print("#endif")
if name == "memclnt.api.vapi.h":
print("")
print("static inline vapi_error_e vapi_send_with_control_ping "
"(vapi_ctx_t ctx, void * msg, u32 context);")
else:
print("#include <vapi/vlib.api.vapi.h>")
print("")
for m in parser.messages_by_json[j].values():
print("extern vapi_msg_id_t %s;" % m.get_msg_id_name())
print("")
print("#define DEFINE_VAPI_MSG_IDS_%s\\" %
f.replace(".", "_").replace("/", "_").replace("-", "_").upper())
print("\\\n".join([
" vapi_msg_id_t %s;" % m.get_msg_id_name()
for m in parser.messages_by_json[j].values()
]))
print("")
print("")
emitted = []
for e in parser.enums_by_json[j]:
emit_definition(parser, j, emitted, e)
for u in parser.unions_by_json[j]:
emit_definition(parser, j, emitted, u)
for t in parser.types_by_json[j]:
emit_definition(parser, j, emitted, t)
for a in parser.aliases_by_json[j]:
emit_definition(parser, j, emitted, a)
for m in parser.messages_by_json[j].values():
emit_definition(parser, j, emitted, m)
print("")
if name == "vlib.api.vapi.h":
print("%s" % vapi_send_with_control_ping)
print("")
print("#ifdef __cplusplus")
print("}")
print("#endif")
print("")
print("#endif")
sys.stdout = orig_stdout
def json_to_c_header_name(json_name):
if json_name.endswith(".json"):
return "%s.vapi.h" % os.path.splitext(json_name)[0]
raise Exception("Unexpected json name `%s'!" % json_name)
def gen_c_unified_headers(parser, logger, prefix, remove_path):
if prefix == "" or prefix is None:
prefix = ""
else:
prefix = "%s/" % prefix
for j in parser.json_files:
if remove_path:
d, f = os.path.split(j)
else:
f = j
with open('%s%s' % (prefix, json_to_c_header_name(f)), "w") as io:
gen_json_unified_header(
parser, logger, j, io, json_to_c_header_name(f))
if __name__ == '__main__':
try:
verbose = int(os.getenv("V", 0))
except:
verbose = 0
if verbose >= 2:
log_level = 10
elif verbose == 1:
log_level = 20
else:
log_level = 40
logging.basicConfig(stream=sys.stdout, level=log_level)
logger = logging.getLogger("VAPI C GEN")
logger.setLevel(log_level)
argparser = argparse.ArgumentParser(description="VPP C API generator")
argparser.add_argument('files', metavar='api-file', action='append',
type=str, help='json api file'
'(may be specified multiple times)')
argparser.add_argument('--prefix', action='store', default=None,
help='path prefix')
argparser.add_argument('--remove-path', action='store_true',
help='remove path from filename')
args = argparser.parse_args()
jsonparser = JsonParser(logger, args.files,
simple_type_class=CSimpleType,
enum_class=CEnum,
union_class=CUnion,
struct_type_class=CStructType,
field_class=CField,
message_class=CMessage,
alias_class=CAlias)
# not using the model of having separate generated header and code files
# with generated symbols present in shared library (per discussion with
# Damjan), to avoid symbol version issues in .so
# gen_c_headers_and_code(jsonparser, logger, args.prefix)
gen_c_unified_headers(jsonparser, logger, args.prefix, args.remove_path)
for e in jsonparser.exceptions:
logger.warning(e)
|
the-stack_0_14823 | import pickle
from graph_features import GraphFeatures
import numpy as np
from loggers import BaseLogger, PrintLogger
import os
MOTIFS_VAR_PATH = os.path.join(__file__.rsplit(os.sep, 1)[0])
class MotifRatio:
def __init__(self, ftr: GraphFeatures, is_directed, logger: BaseLogger=None):
self._is_directed = is_directed # are the graphs directed
self._index_ftr = None # list of ftr names + counter [ ... (ftr_i, 0), (ftr_i, 1) ...]
self._logger = logger if logger else PrintLogger("graphs logger")
# self._graph_order = graph_order if graph_order else [g for g in sorted(graph_ftr_dict)]
self._gnx_ftr = ftr
self._set_index_to_ftr(self._gnx_ftr)
# list index in motif to number of edges in the motif
self._motif_index_to_edge_num = {"motif3": self._motif_num_to_number_of_edges(3),
"motif4": self._motif_num_to_number_of_edges(4)}
self._ftr_mx = self._gnx_ftr.to_matrix(dtype=np.float32, mtype=np.matrix, should_zscore=False)
self._headers = []
self._motif_ratio_vec = None
self._motif_ratio_matrix = None
# load motif variation file
def _load_variations_file(self, level):
fname = "%d_%sdirected.pkl" % (level, "" if self._is_directed else "un")
fpath = os.path.join(MOTIFS_VAR_PATH, "motif_variations", fname)
return pickle.load(open(fpath, "rb"))
# return dictionary { motif_index: number_of_edges }
def _motif_num_to_number_of_edges(self, level):
motif_edge_num_dict = {}
for bit_sec, motif_num in self._load_variations_file(level).items():
motif_edge_num_dict[motif_num] = bin(bit_sec).count('1')
return motif_edge_num_dict
# map matrix columns to features + count if there's more then one from a single feature
def _set_index_to_ftr(self, gnx_ftr):
if not self._index_ftr:
sorted_ftr = [f for f in sorted(gnx_ftr) if gnx_ftr[f].is_relevant()] # fix feature order (names)
self._index_ftr = []
for ftr in sorted_ftr:
len_ftr = len(gnx_ftr[ftr])
# fill list with (ftr, counter)
self._index_ftr += [(ftr, i) for i in range(len_ftr)]
# get feature vector for a graph
def _build_vector(self):
# get gnx gnx
final_vec = np.zeros((1, self._ftr_mx.shape[1]))
motif3_ratio = None
motif4_ratio = None
for i, (ftr, ftr_count) in enumerate(self._index_ftr):
if ftr == "motif3":
# calculate { motif_index: motif ratio }
motif3_ratio = self._count_subgraph_motif_by_size(self._ftr_mx, ftr) if not motif3_ratio else motif3_ratio
final_vec[0, i] = motif3_ratio[ftr_count]
self._headers.append("motif3_" + str(self._motif_index_to_edge_num["motif3"][ftr_count]) + "_edges")
elif ftr == "motif4":
# calculate { motif_index: motif ratio }
motif4_ratio = self._count_subgraph_motif_by_size(self._ftr_mx, ftr) if not motif4_ratio else motif4_ratio
final_vec[0, i] = motif4_ratio[ftr_count]
self._headers.append("motif4_" + str(self._motif_index_to_edge_num["motif4"][ftr_count]) + "_edges")
else:
# calculate average of column
final_vec[0, i] = np.sum(self._ftr_mx[:, i]) / self._ftr_mx.shape[0]
self._headers.append(ftr + "_" + str(ftr_count))
return final_vec
def _build_matrix(self):
sum_dictionaries_motifs3 = []
sum_dictionaries_motifs4 = []
# 3: [ ... row(node): { num_edges_in_motif3: count (for_this_node_only) } ... ]
for i in range(self._ftr_mx.shape[0]):
sum_dictionaries_motifs3.append({})
sum_dictionaries_motifs4.append({})
for j, (ftr, ftr_count) in enumerate(self._index_ftr):
if ftr == "motif3":
key = self._motif_index_to_edge_num[ftr][ftr_count]
sum_dictionaries_motifs3[i][key] = sum_dictionaries_motifs3[i].get(key, 1e-3) + self._ftr_mx[i, j]
elif ftr == "motif4":
key = self._motif_index_to_edge_num[ftr][ftr_count]
sum_dictionaries_motifs4[i][key] = sum_dictionaries_motifs4[i].get(key, 1e-3) + self._ftr_mx[i, j]
return_mx = self._ftr_mx.copy()
for i in range(self._ftr_mx.shape[0]):
for j, (ftr, ftr_count) in enumerate(self._index_ftr):
if ftr == "motif3":
# calculate { motif_index: motif ratio }
return_mx[i, j] /= sum_dictionaries_motifs3[i][self._motif_index_to_edge_num[ftr][ftr_count]]
if i == 0:
self._headers.append("motif3_" + str(self._motif_index_to_edge_num["motif3"][ftr_count]) + "_edges")
elif ftr == "motif4":
# calculate { motif_index: motif ratio }
return_mx[i, j] /= sum_dictionaries_motifs4[i][self._motif_index_to_edge_num[ftr][ftr_count]]
if i == 0:
self._headers.append("motif4_" + str(self._motif_index_to_edge_num["motif4"][ftr_count]) + "_edges")
else:
if i == 0:
self._headers.append(ftr + "_" + str(ftr_count))
return return_mx
def motif_ratio_vector(self):
self._motif_ratio_vec = self._motif_ratio_vec if self._motif_ratio_vec else self._build_vector()
return self._motif_ratio_vec[0]
def motif_ratio_matrix(self):
self._motif_ratio_matrix = self._motif_ratio_matrix if self._motif_ratio_matrix else self._build_matrix()
return self._motif_ratio_matrix
def get_headers(self):
return self._headers
# return { motif_index: sum motif in index/ total motifs with same edge count }
def _count_subgraph_motif_by_size(self, ftr_mat, motif_type):
sum_dict = {ftr_count: np.sum(ftr_mat[:, i]) for i, (ftr, ftr_count) in enumerate(self._index_ftr)
if ftr == motif_type} # dictionary { motif_index: sum column }
sum_by_edge = {} # dictionary { num_edges_in_motif: sum of }
for motif_count, sum_motif in sum_dict.items():
key = self._motif_index_to_edge_num[motif_type][motif_count]
sum_by_edge[key] = sum_by_edge.get(key, 0) + sum_motif
# rewrite dictionary { motif_index: sum column/ total motifs with same edge count }
for motif_count in sum_dict:
key = self._motif_index_to_edge_num[motif_type][motif_count]
sum_dict[motif_count] = sum_dict[motif_count] / sum_by_edge[key] if sum_by_edge[key] else 0
return sum_dict
# return [ ... (motif_type, counter) ... ]
def _get_motif_type(self, motif_type, num_motifs):
header = []
for i in range(num_motifs):
header.append((motif_type, i))
return header
@staticmethod
def is_motif(ftr):
return ftr == 'motif4' or ftr == "motif3"
if __name__ == "__main__":
import networkx as nx
from feature_meta import NODE_FEATURES
gnx = nx.Graph()
gnx.add_edges_from([
(1, 2),
(1, 3),
(2, 3),
(2, 7),
(7, 8),
(3, 6),
(4, 6),
(6, 8),
(5, 6),
])
gnx_ftr = GraphFeatures(gnx, NODE_FEATURES, ".", is_max_connected=True)
gnx_ftr.build()
m = MotifRatio(gnx_ftr, False)
e = 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.